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
CaptainIllidan/yolo
https://github.com/CaptainIllidan/yolo
cceb279d3623b9a7ba6408e4af730afb751b5a16
31180ca6762c85bfd14c0602a2eb7f8bdbf85ae2
f7a6bd10464007e9fa77837379f024aa9af89e34
refs/heads/master
2021-06-24T08:19:16.150716
2021-04-26T21:09:19
2021-04-26T21:09:19
220,842,943
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.6421911716461182, "alphanum_fraction": 0.6643356680870056, "avg_line_length": 25.8125, "blob_id": "d178335ea0afdd0c95dde640af7400ffd07520cd", "content_id": "ff61c0777d93ee40ba42ab7ac3a8ab5f9d5b0f77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 858, "license_type": "no_license", "max_line_length": 103, "num_lines": 32, "path": "/detect.py", "repo_name": "CaptainIllidan/yolo", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nimport pyyolo\n\ncap = cv2.VideoCapture('gun4_2.mp4')\nmeta_filepath = \"/home/unknown/yolo/darknet.data\"\ncfg_filepath = \"/home/unknown/yolo/darknet-yolov3.cfg\"\nweights_filepath = \"/home/unknown/yolo/yolov3.weights\"\n\n\nmeta = pyyolo.load_meta(meta_filepath)\nnet = pyyolo.load_net(cfg_filepath, weights_filepath, False)\n\nwhile(cap.isOpened()):\n ret, frame = cap.read()\n if not ret:\n break\n\n yolo_img = pyyolo.array_to_image(frame)\n res = pyyolo.detect(net, meta, yolo_img)\n\n for r in res:\n cv2.rectangle(frame, r.bbox.get_point(pyyolo.BBox.Location.TOP_LEFT, is_int=True),\n r.bbox.get_point(pyyolo.BBox.Location.BOTTOM_RIGHT, is_int=True), (0, 255, 0), 2)\n\n\n cv2.imshow('frame', frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n" }, { "alpha_fraction": 0.7760000228881836, "alphanum_fraction": 0.8159999847412109, "avg_line_length": 30.25, "blob_id": "41672810da5a2e394daac4f6474157a5d731b043", "content_id": "d1228709673b4b66a26a7db67e85f16242cdd62d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 125, "license_type": "no_license", "max_line_length": 92, "num_lines": 4, "path": "/README.md", "repo_name": "CaptainIllidan/yolo", "src_encoding": "UTF-8", "text": "# yolo\nGun detection with yolo\n\nNew pretraining weights - https://drive.google.com/open?id=1WDHOly6raQPleTUfx-V7CTtS5KreFdy8\n" } ]
2
androiddevnotesforks/github-scraper
https://github.com/androiddevnotesforks/github-scraper
a993747c86e19ee31d12ada2db73fc5877a44284
b4c88180f2a3dd3b622d60a04487057aef5b8a3d
0fbd2c89bb83bbbe81712d9bf4e72bfdd1468517
refs/heads/master
2023-05-28T12:08:14.278275
2021-06-05T13:08:43
2021-06-05T13:08:43
338,650,736
3
0
null
2021-02-13T19:18:36
2021-05-31T13:39:37
2021-06-05T16:37:00
Python
[ { "alpha_fraction": 0.7338731288909912, "alphanum_fraction": 0.7360323667526245, "avg_line_length": 56, "blob_id": "fc95e8e832500b68c178027c311861a400632a17", "content_id": "758a3400ff369679a35973d2fe67cf432dfa08e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3705, "license_type": "no_license", "max_line_length": 561, "num_lines": 65, "path": "/README.md", "repo_name": "androiddevnotesforks/github-scraper", "src_encoding": "UTF-8", "text": "# GitHub scraper\n\nThis tool focuses on scraping information from _[organizational Github accounts](https://developer.github.com/v3/orgs/)_, which means that it only takes a list or organizations as input, not normal user accounts. It generates CSV spreadsheets or [GEXF](https://gephi.org/gexf/format/) files to be used in network analysis software like [Gephi](https://gephi.github.io/).\n\nThe scraper offers the following options:\n\n```\nusage: github_scraper.py [-h] [--all] [--repos] [--contributors] [--member_repos] [--member_infos] [--starred] [--followers]\n [--memberships]\n\nScrape organizational accounts on Github.\n\noptional arguments:\n -h, --help show this help message and exit\n --all, -a scrape all the information listed below\n --repos, -r scrape the organizations' repositories (CSV)\n --contributors, -c scrape contributors of the organizations' repositories (CSV and GEXF)\n --member_repos, -mr scrape all repositories owned by the members of the organizations (CSV)\n --member_infos, -mi scrape information about each member of the organizations (CSV)\n --starred, -s scrape all repositories starred by the members of the organizations (CSV)\n --followers, -f generate a follower network. Creates full and narrow network graph, the latter only shows how scraped\n organizations are networked among each other (two GEXF files)\n --memberships, -m scrape all organizational memberships of org members (GEXF)\n```\n\nI originally wrote this scraper in 2015 for my dissertation about civic tech and data journalism. You can find the data I scraped and my analysis [here](https://sbaack.com/blog/scraping-the-global-civic-tech-community-on-github-part-2.html). If you're interested, my final dissertation is available [here](https://research.rug.nl/en/publications/knowing-what-counts-how-journalists-and-civic-technologists-use-a).\n\n## Setup\n\nYou need Python 3.7+.\n\n```bash\n# Clone this repository\ngit clone https://github.com/sbaack/github-scraper.git\n# Create virtualenv with your preferred tool, for example:\ncd github-scraper\npython -m venv github-scraper_venv && source github-scraper_venv/bin/activate\n# Install necessary dependencies\npython -m pip install -r requirements.txt\n```\n\nNext, you need to add information to two configuration files. First, add your GitHub user name and your [personal access token](https://github.com/settings/tokens) to access the GitHub API in the `config.json` file. Second, add the Github account names of the organizations you want to scrape to the `organizations.csv` spreadsheet in the column *github_org_name*. For example, if you want to scrape [mySociety](https://github.com/mysociety), [Open Knowledge](https://github.com/okfn), and [Ushahidi](https://github.com/ushahidi), your file will look like this:\n\n| github_org_name |\n|:----------------|\n| mysociety |\n| okfn |\n| ushahidi |\n\nNote that you can you add as many columns with additional information as you like, this scraper will only read the *github_org_name* column.\n\n# How to use\n\nStart the scraper with the desired options listed above. Some examples:\n\n```bash\n# Scrape everything this scraper provides\npython -m github_scraper --all\n# Scrape organizations' repos and generate follower networks\npython -m github_scraper --repos --followers # OR use the shortcuts: python -m github_scraper -r -f\n# Only scrape starred repositories\npython -m github_scraper --starred # OR github_scraper -s\n```\n\nThe results will be stored in the `data` subfolder, where each scrape creates it's own directory named according to the date (in the form of YEAR-MONTH-DAY_HOUR-MINUTE-SECOND).\n" }, { "alpha_fraction": 0.5592127442359924, "alphanum_fraction": 0.5598815083503723, "avg_line_length": 37.69316101074219, "blob_id": "2c47f3be8be9e621401c83498f7008aa0dfb3a4a", "content_id": "c48417823772908625d519ebdf5b957f59e359fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20933, "license_type": "no_license", "max_line_length": 88, "num_lines": 541, "path": "/github_scraper.py", "repo_name": "androiddevnotesforks/github-scraper", "src_encoding": "UTF-8", "text": "\"\"\"Scrape GitHub data for organizational accounts.\"\"\"\n\nimport argparse\nimport asyncio\nimport csv\nimport json\nimport sys\nimport time\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Tuple\n\nimport aiohttp\nimport networkx as nx\n\n\nclass GithubScraper():\n \"\"\"Scrape information about organizational Github accounts.\n\n Use Github API key and user name to make requests to Github API.\n Create spreadsheets named after data type and date.\n\n Attributes:\n orgs (List[str]): List of organizational Github accounts to scrape\n session (aiohttp.ClientSession): Session using Github user name and API token\n \"\"\"\n\n def __init__(self, organizations: List[str],\n session: aiohttp.ClientSession) -> None:\n \"\"\"Instantiate object.\"\"\"\n self.orgs = organizations\n self.session = session\n # Members and repositories of listed organizations. Instantiated as empty dict\n # and only loaded if user selects operation that needs this list.\n # Saves API calls.\n self.members: Dict[str, List[str]] = {}\n self.repos: List[Dict[str, Any]] = []\n # Directory to store scraped data with timestamp\n self.data_directory: Path = Path(\n Path.cwd(), 'data', time.strftime('%Y-%m-%d_%H-%M-%S')\n )\n Path(self.data_directory).mkdir()\n\n async def get_members(self) -> Dict[str, List[str]]:\n \"\"\"Get list of members of specified orgs.\n\n Returns:\n Dict[str, List[str]]: Keys are orgs, values list of members\n \"\"\"\n print(\"Collecting members of specified organizations...\")\n members: Dict[str, List[str]] = {}\n tasks: List[asyncio.Task[Any]] = []\n for org in self.orgs:\n url = f\"https://api.github.com/orgs/{org}/members\"\n tasks.append(asyncio.create_task(self.call_api(url, organization=org)))\n json_org_members: List[Dict[str, Any]] = await self.load_json(tasks)\n # Extract names of org members from JSON data\n for org in self.orgs:\n members[org] = []\n for member in json_org_members:\n members[member[\"organization\"]].append(member['login'])\n return members\n\n async def load_json(self, tasks: List[asyncio.Task[Any]]) -> List[Dict[str, Any]]:\n \"\"\"Execute tasks with asyncio.wait() to make API calls.\n\n Args:\n tasks (List[asyncio.Task[Any]]): List of awaitable tasks to execute\n\n Returns:\n List[Dict[str, Any]]: Full JSON returned by API\n \"\"\"\n full_json: List[Dict[str, Any]] = []\n done, pending = await asyncio.wait(\n tasks, return_when=\"ALL_COMPLETED\"\n )\n for task in done:\n try:\n full_json.extend(await task)\n except aiohttp.ContentTypeError:\n # If repository is empty, pass\n pass\n return full_json\n\n async def call_api(self, url: str, **added_fields: str) -> List[Dict[str, Any]]:\n \"\"\"Load json file using requests.\n\n Makes API calls and returns JSON results.\n\n Args:\n url (str): Github API URL to load as JSON\n **added_fields (str): Additional information that will be added to each item\n in the JSON data\n\n Returns:\n List[Dict[str, Any]]: Github URL loaded as JSON\n \"\"\"\n page: int = 1\n json_data: List[Dict[str, Any]] = []\n # Requesting user info doesn't support pagination and returns dict, not list\n if url.split(\"/\")[-2] == 'users':\n async with self.session.get(f\"{url}?per_page=100\") as resp:\n member_json: Dict[str, Any] = await resp.json()\n for key, value in added_fields.items():\n member_json[key] = value\n json_data.append(member_json)\n return json_data\n # Other API calls return lists and should paginate\n while True:\n async with self.session.get(f\"{url}?per_page=100&page={str(page)}\") as resp:\n json_page: List[Dict[str, Any]] = await resp.json()\n if json_page == []:\n break\n for item in json_page:\n for key, value in added_fields.items():\n item[key] = value\n json_data.extend(json_page)\n page += 1\n return json_data\n\n def generate_csv(self, file_name: str, json_list: List[Dict[str, Any]],\n columns_list: List) -> None:\n \"\"\"Write CSV file.\n\n Args:\n file_name (str): Name of the CSV file\n json_list (List[Dict[str, Any]]): JSON data to turn into CSV\n columns_list (List): List of columns that represent relevant fields\n in the JSON data\n \"\"\"\n with open(\n Path(self.data_directory, file_name),\n 'a+',\n encoding='utf-8'\n ) as file:\n csv_file = csv.DictWriter(\n file,\n fieldnames=columns_list,\n extrasaction=\"ignore\"\n )\n csv_file.writeheader()\n for item in json_list:\n csv_file.writerow(item)\n print(\n f\"- file saved as {Path('data', self.data_directory.name, file_name)}\"\n )\n\n async def get_org_repos(self) -> List[Dict[str, Any]]:\n \"\"\"Create list of the organizations' repositories.\"\"\"\n print(\"Scraping repositories\")\n tasks: List[asyncio.Task[Any]] = []\n for org in self.orgs:\n url = f\"https://api.github.com/orgs/{org}/repos\"\n tasks.append(asyncio.create_task(self.call_api(url, organization=org)))\n return await self.load_json(tasks)\n\n async def create_org_repo_csv(self) -> None:\n \"\"\"Write a CSV file with information about orgs' repositories.\"\"\"\n # Create list of items that should appear as columns in the CSV\n table_columns: List[str] = [\n 'organization',\n 'name',\n 'full_name',\n 'stargazers_count',\n 'language',\n 'created_at',\n 'updated_at',\n 'homepage',\n 'fork',\n 'description'\n ]\n self.generate_csv('org_repositories.csv', self.repos, table_columns)\n\n async def get_repo_contributors(self) -> None:\n \"\"\"Create list of contributors to the organizations' repositories.\"\"\"\n print(\"Scraping contributors\")\n json_contributors_all = []\n graph = nx.DiGraph()\n table_columns: List[str] = [\n 'organization',\n 'repository',\n 'login',\n 'contributions',\n 'html_url',\n 'url'\n ]\n tasks: List[asyncio.Task[Any]] = []\n for org in self.orgs:\n for repo in self.repos:\n url = f\"https://api.github.com/repos/{org}/{repo['name']}/contributors\"\n tasks.append(\n asyncio.create_task(\n self.call_api(url, organization=org, repository=repo['name'])\n )\n )\n json_contributors_all = await self.load_json(tasks)\n self.generate_csv('contributor_list.csv', json_contributors_all, table_columns)\n for contributor in json_contributors_all:\n graph.add_node(\n contributor['repository'], organization=contributor['organization']\n )\n graph.add_edge(\n contributor['login'],\n contributor['repository'],\n organization=contributor['organization']\n )\n nx.write_gexf(\n graph,\n Path(self.data_directory, 'contributor_network.gexf')\n )\n print(\n \"- file saved as \"\n f\"{Path('data', self.data_directory.name, 'contributor_network.gexf')}\"\n )\n\n async def get_members_repos(self) -> None:\n \"\"\"Create list of all the members of an organization and their repositories.\"\"\"\n print(\"Getting repositories of all members.\")\n json_members_repos: List[Dict[str, Any]] = []\n table_columns: List[str] = [\n 'organization',\n 'user',\n 'full_name',\n 'fork',\n 'stargazers_count',\n 'forks_count',\n 'language',\n 'description'\n ]\n tasks: List[asyncio.Task[Any]] = []\n for org in self.members:\n for member in self.members[org]:\n url = f\"https://api.github.com/users/{member}/repos\"\n tasks.append(\n asyncio.create_task(\n self.call_api(url, organization=org, user=member)\n )\n )\n json_members_repos = await self.load_json(tasks)\n self.generate_csv('members_repositories.csv',\n json_members_repos, table_columns)\n\n async def get_members_info(self) -> None:\n \"\"\"Gather information about the organizations' members.\"\"\"\n print(\"Getting user information of all members.\")\n table_columns: List[str] = [\n 'organization',\n 'login',\n 'name',\n 'url',\n 'type',\n 'company',\n 'blog',\n 'location'\n ]\n tasks: List[asyncio.Task[Any]] = []\n for org in self.orgs:\n for member in self.members[org]:\n url = f\"https://api.github.com/users/{member}\"\n tasks.append(asyncio.create_task(\n self.call_api(url, organization=org))\n )\n json_members_info: List[Dict[str, Any]] = await self.load_json(tasks)\n self.generate_csv('members_info.csv', json_members_info, table_columns)\n\n async def get_starred_repos(self) -> None:\n \"\"\"Create list of all the repositories starred by organizations' members.\"\"\"\n print(\"Getting repositories starred by members.\")\n json_starred_repos_all: List[Dict[str, Any]] = []\n table_columns: List[str] = [\n 'organization',\n 'user',\n 'full_name',\n 'html_url',\n 'language',\n 'description'\n ]\n tasks: List[asyncio.Task[Any]] = []\n for org in self.members:\n for member in self.members[org]:\n url = f\"https://api.github.com/users/{member}/starred\"\n tasks.append(asyncio.create_task(\n self.call_api(url, organization=org, user=member))\n )\n json_starred_repos_all = await self.load_json(tasks)\n self.generate_csv('starred_repositories.csv',\n json_starred_repos_all, table_columns)\n\n async def generate_follower_network(self) -> None:\n \"\"\"Create full or narrow follower networks of organizations' members.\n\n Get every user following the members of organizations (followers)\n and the users they are following themselves (following). Then generate two\n directed graphs with NetworkX. Only includes members of specified organizations\n if in narrow follower network.\n \"\"\"\n print('Generating follower networks')\n # Create graph dict and add self.members as nodes\n graph_full = nx.DiGraph()\n graph_narrow = nx.DiGraph()\n for org in self.orgs:\n for member in self.members[org]:\n graph_full.add_node(member, organization=org)\n graph_narrow.add_node(member, organization=org)\n\n # Get followers and following for each member and build graph\n tasks_followers: List[asyncio.Task[Any]] = []\n tasks_following: List[asyncio.Task[Any]] = []\n for org in self.members:\n for member in self.members[org]:\n url_followers = f\"https://api.github.com/users/{member}/followers\"\n tasks_followers.append(\n asyncio.create_task(\n self.call_api(url_followers, follows=member, original_org=org))\n )\n url_following = f\"https://api.github.com/users/{member}/following\"\n tasks_following.append(\n asyncio.create_task(\n self.call_api(\n url_following, followed_by=member, original_org=org)\n )\n )\n json_followers = await self.load_json(tasks_followers)\n json_following = await self.load_json(tasks_following)\n # Build full and narrow graphs\n for follower in json_followers:\n graph_full.add_edge(\n follower['login'],\n follower['follows'],\n organization=follower['original_org']\n )\n if follower['login'] in self.members[follower['original_org']]:\n graph_narrow.add_edge(\n follower['login'],\n follower['follows'],\n organization=follower['original_org'])\n for following in json_following:\n graph_full.add_edge(\n following['followed_by'],\n following['login'],\n organization=following['original_org'])\n if following['login'] in self.members[following['original_org']]:\n graph_narrow.add_edge(\n following['followed_by'],\n following['login'],\n organization=following['original_org'])\n # Write graphs and save files\n nx.write_gexf(\n graph_full,\n Path(self.data_directory, \"full-follower-network.gexf\"))\n nx.write_gexf(\n graph_narrow,\n Path(self.data_directory, \"narrow-follower-network.gexf\"))\n print(\n f\"- files saved in {Path('data', self.data_directory.name)} as \"\n \"full-follower-network.gexf and narrow-follower-network.gexf\"\n )\n\n async def generate_memberships_network(self) -> None:\n \"\"\"Take all the members of the organizations and generate a directed graph.\n\n This shows creates a network with the organizational memberships.\n \"\"\"\n print(\"Generating network of memberships.\")\n graph = nx.DiGraph()\n tasks: List[asyncio.Task[Any]] = []\n for org in self.members:\n for member in self.members[org]:\n url = f\"https://api.github.com/users/{member}/orgs\"\n tasks.append(asyncio.create_task(\n self.call_api(\n url, organization=org, scraped_org_member=member))\n )\n json_org_memberships = await self.load_json(tasks)\n for membership in json_org_memberships:\n graph.add_node(membership['scraped_org_member'], node_type='user')\n graph.add_edge(\n membership['scraped_org_member'],\n membership['login'], # name of organization user is member of\n node_type='organization')\n nx.write_gexf(\n graph,\n Path(self.data_directory, 'membership_network.gexf')\n )\n print(\n \"- file saved as \"\n f\"{Path('data', self.data_directory.name, 'membership_network.gexf')}\"\n )\n\n\ndef read_config() -> Tuple[str, str]:\n \"\"\"Read config file.\n\n Returns:\n Tuple[str, str]: Github user name and API token\n\n Raises:\n KeyError: If config file is empty\n \"\"\"\n try:\n with open(Path(Path.cwd(), 'config.json'), 'r', encoding='utf-8') as file:\n config = json.load(file)\n user: str = config['user_name']\n api_token: str = config['api_token']\n if user == \"\" or api_token == \"\":\n raise KeyError\n else:\n return user, api_token\n except (FileNotFoundError, KeyError):\n sys.exit(\"Failed to read Github user name and/or API token. \"\n \"Please add them to the config.json file.\")\n\n\ndef read_organizations() -> List[str]:\n \"\"\"Read list of organizations from file.\n\n Returns:\n List[str]: List of names of organizational Github accounts\n \"\"\"\n orgs: List[str] = []\n with open(Path(Path.cwd(), 'organizations.csv'), 'r', encoding=\"utf-8\") as file:\n reader = csv.DictReader(file)\n for row in reader:\n orgs.append(row['github_org_name'])\n if not orgs:\n sys.exit(\"No organizations to scrape found in organizations.csv. \"\n \"Please add the names of the organizations you want to scrape \"\n \"in the column 'github_org_name' (one name per row).\")\n return orgs\n\n\ndef parse_args() -> Dict[str, bool]:\n \"\"\"Parse arguments.\n\n We use the 'dest' value to map args with functions/methods. This way, we\n can use getattr(object, dest)() and avoid long if...then list in main().\n\n Returns:\n Dict[str, bool]: Result of vars(parse_args())\n \"\"\"\n argparser = argparse.ArgumentParser(\n description=\"Scrape organizational accounts on Github.\"\n )\n argparser.add_argument(\n \"--all\",\n \"-a\",\n action=\"store_true\",\n help=\"scrape all the information listed below\"\n )\n argparser.add_argument(\n \"--repos\",\n \"-r\",\n action='store_true',\n dest=\"create_org_repo_csv\",\n help=\"scrape the organizations' repositories (CSV)\"\n )\n argparser.add_argument(\n \"--contributors\",\n \"-c\",\n action=\"store_true\",\n dest=\"get_repo_contributors\",\n help=\"scrape contributors of the organizations' repositories (CSV and GEXF)\"\n )\n argparser.add_argument(\n \"--member_repos\",\n \"-mr\",\n action=\"store_true\",\n dest=\"get_members_repos\",\n help=\"scrape all repositories owned by the members of the organizations (CSV)\"\n )\n argparser.add_argument(\n \"--member_infos\",\n \"-mi\",\n action=\"store_true\",\n dest=\"get_members_info\",\n help=\"scrape information about each member of the organizations (CSV)\"\n )\n argparser.add_argument(\n \"--starred\",\n \"-s\",\n action=\"store_true\",\n dest=\"get_starred_repos\",\n help=\"scrape all repositories starred by the members of the organizations (CSV)\"\n )\n argparser.add_argument(\n \"--followers\",\n \"-f\",\n action=\"store_true\",\n dest=\"generate_follower_network\",\n help=\"generate a follower network. Creates full and narrow network graph, the \"\n \"latter only shows how scraped organizations are networked among each \"\n \"other (two GEXF files)\"\n )\n argparser.add_argument(\n \"--memberships\",\n \"-m\",\n action=\"store_true\",\n dest=\"generate_memberships_network\",\n help=\"scrape all organizational memberships of org members (GEXF)\"\n )\n args: Dict[str, bool] = vars(argparser.parse_args())\n return args\n\n\nasync def main() -> None:\n \"\"\"Set up GithubScraper object.\"\"\"\n args: Dict[str, bool] = parse_args()\n if not any(args.values()):\n sys.exit(\"You need to provide at least one argument. \"\n \"For usage, call: github_scraper -h\")\n user, api_token = read_config()\n organizations = read_organizations()\n # To avoid unnecessary API calls, only get org members and repos if needed\n require_members = ['get_members_repos', 'get_members_info', 'get_starred_repos',\n 'generate_follower_network', 'generate_memberships_network']\n require_repos = ['create_org_repo_csv', 'get_repo_contributors']\n # Start aiohttp session\n auth = aiohttp.BasicAuth(user, api_token)\n async with aiohttp.ClientSession(auth=auth) as session:\n github_scraper = GithubScraper(organizations, session)\n # If --all was provided, simply run everything\n if args['all']:\n github_scraper.members = await github_scraper.get_members()\n github_scraper.repos = await github_scraper.get_org_repos()\n for arg in args:\n if arg != 'all':\n await getattr(github_scraper, arg)()\n else:\n # Check args provided, get members/repos if necessary, call related methods\n called_args = [arg for arg, value in args.items() if value]\n if any(arg for arg in called_args if arg in require_members):\n github_scraper.members = await github_scraper.get_members()\n if any(arg for arg in called_args if arg in require_repos):\n github_scraper.repos = await github_scraper.get_org_repos()\n for arg in called_args:\n await getattr(github_scraper, arg)()\n\n\nif __name__ == \"__main__\":\n if sys.platform == 'win32':\n asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())\n asyncio.run(main())\n" } ]
2
maxiantian/DownloadTaobaoSearchPicture
https://github.com/maxiantian/DownloadTaobaoSearchPicture
854afd11193629616bf71d3086943b280c3006c0
7eabadaf92438864b02fbefe95e87226c67a5b96
a7d259ebf579443f8b5585c662246e55338f0a4c
refs/heads/master
2021-05-11T02:02:08.225540
2018-01-21T15:48:07
2018-01-21T15:48:07
118,347,723
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6359687447547913, "alphanum_fraction": 0.6759339570999146, "avg_line_length": 26.16666603088379, "blob_id": "90ceb3a5ef8d16e14f2ff0e88ad17c0541966b7f", "content_id": "4ee8ee92102369935ca0bc1bdba61e1e6d167043", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1379, "license_type": "no_license", "max_line_length": 196, "num_lines": 42, "path": "/DownloadTaobaoSearchPicture.py", "repo_name": "maxiantian/DownloadTaobaoSearchPicture", "src_encoding": "UTF-8", "text": "import urllib.request\nimport re\nimport ssl\n\n#全局取消证书验证\nssl._create_default_https_context = ssl._create_unverified_context\n\n#设置淘宝搜索的关键词\nkeyword = urllib.request.quote(\"毛衣\")\n\n#将爬虫伪装成火狐浏览器\nheaders=(\"User-Agent\",\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:57.0) Gecko/20100101 Firefox/57.0\")\n\n#创建一个opener对象 \nopener = urllib.request.build_opener()\n\n#为opener设置header\nopener.addheaders = [headers]\n\n#将opener设为全局\nurllib.request.install_opener(opener)\n\n#为了方便测试,仅下载两页的数据\nfor i in range(0,2):\n\n #把关键词添加到URL中并请求数据\n url = \"https://s.taobao.com/search?q=\"+ keyword +\"&imgfile=&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20180121&ie=utf8&bcoffset=4&ntoffset=4&p4ppushleft=1%2C48&s=\"+str(44*i)\n data = urllib.request.urlopen(url).read().decode(\"utf-8\",\"ignore\")\n\n #测试是否请求到数据\n print(len(data))\n\n #使用正则表达式进行匹配\n pat = '\"pic_url\":\"//(.*?)\"'\n imgs = re.compile(pat).findall(data)\n\n for j in range(0,len(imgs)):\n\n #用匹配到的网址建立完整的URL,并直接下载到本地\n thisurl = \"http://\" + imgs[j]\n file = \"/Users/Rocky1/Desktop/imgs/\" + str(i) + \"-\" + str(j) + \".jpg\"\n urllib.request.urlretrieve(thisurl,file)\n\n\n\n \n \n" }, { "alpha_fraction": 0.8584070801734924, "alphanum_fraction": 0.8584070801734924, "avg_line_length": 55, "blob_id": "770004a96a2908a3c542097ad6a458d29a5e0dc3", "content_id": "445acde46455704e0afda1b14da5ff5986304705", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 113, "license_type": "no_license", "max_line_length": 81, "num_lines": 2, "path": "/README.md", "repo_name": "maxiantian/DownloadTaobaoSearchPicture", "src_encoding": "UTF-8", "text": "# DownloadTaobaoSearchPicture\nuse urllib and regular expression operations to download search picture in Taobao\n\n" } ]
2
chaossky/PythonApplication1
https://github.com/chaossky/PythonApplication1
a836c76fc537f299d1d62762cbe17d115602c939
9d389fbfc4a45ef6fb4a3cc7e0d7378311af1495
94e3309aef96b5e1387ce8ab2a9c22f216db35ea
refs/heads/master
2020-03-26T01:31:28.717845
2018-08-30T10:42:16
2018-08-30T10:42:16
144,370,891
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5416666865348816, "alphanum_fraction": 0.625, "avg_line_length": 11.166666984558105, "blob_id": "8b37736dea29a89d132633bed6b4d6b8dda2ef1a", "content_id": "3ffd86f9f3af027224965eb2da807dd18120abbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 72, "license_type": "no_license", "max_line_length": 26, "num_lines": 6, "path": "/PythonApplication4/PythonApplication4/PythonApplication4.py", "repo_name": "chaossky/PythonApplication1", "src_encoding": "UTF-8", "text": "import random\n\ni=0\nwhile i !=99:\n i=random.randint(0,99)\n print(i)" }, { "alpha_fraction": 0.6612903475761414, "alphanum_fraction": 0.698924720287323, "avg_line_length": 14.5, "blob_id": "12aec5579ea2b0008c085774cd36043bc766f326", "content_id": "9dce9bd0e9b3e929252ef4daef77a518b4dac59d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 186, "license_type": "no_license", "max_line_length": 28, "num_lines": 12, "path": "/PythonApplication2/PythonApplication2/PythonApplication2.py", "repo_name": "chaossky/PythonApplication1", "src_encoding": "UTF-8", "text": "import numpy as np\na=np.arange(15).reshape(3,5)\nprint(a)\nprint(a.shape)\nprint(a.ndim)\nprint(a.dtype.name)\nprint(a.itemsize)\nprint(type(a))\n\nb=np.ndarray([6,7,8])\nprint(b)\nprint(type(b))\n" }, { "alpha_fraction": 0.5198675394058228, "alphanum_fraction": 0.5728476643562317, "avg_line_length": 8.580645561218262, "blob_id": "8de882714cb6617e231ca121f47468eed7a736cd", "content_id": "f63f90123da2e1bd753b0cc654616c5f031507a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 302, "license_type": "no_license", "max_line_length": 32, "num_lines": 31, "path": "/PythonApplication3/PythonApplication3/PythonApplication3.py", "repo_name": "chaossky/PythonApplication1", "src_encoding": "UTF-8", "text": "a=5\nb=2\n\nprint (a)\nprint (b)\n\na+=b\n\nprint(a)\nprint(b)\n\n#print (a+b)\n#print (a-b)\n#print (a*b)\n#print (a/b)\n#print (a//b)\n\n#print (int(5/2))\n#print (5//2)\n#print (5%2)\n#print(5**2)\n#c=divmod(5,2)\n\n#print(c)\n\n#quotient, remainder=divmod(5,2)\n#print(quotient,remainder)\n\n#x=-10\n#print(+x)\n#print(-x)\n\n\n\n\n\n" }, { "alpha_fraction": 0.6796116232872009, "alphanum_fraction": 0.737864077091217, "avg_line_length": 16.33333396911621, "blob_id": "09baa42038396daddd2b7862d47609d6e21fb247", "content_id": "0495851e4c26e44f4542a12e63e899ddd01c3b53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 103, "license_type": "no_license", "max_line_length": 27, "num_lines": 6, "path": "/PythonApplication1/PythonApplication1.py", "repo_name": "chaossky/PythonApplication1", "src_encoding": "UTF-8", "text": "import pylab\nx_numbers=[1,2,3]\ny_numbers=[2,4,6]\n\nfrom pylab import plot,show\nplot(x_numbers,y_numbers)" } ]
4
vishnuyar/DS-Unit-3-Sprint-2-SQL-and-Databases
https://github.com/vishnuyar/DS-Unit-3-Sprint-2-SQL-and-Databases
c69dc92b8b32898197bffd7e9ec2fd4dd77fd0ea
140f6542aa6ae6bb9cbd1b728c79919edc0da7c7
68c7c405cdeaa73e8c5ec871a378585b061d89f2
refs/heads/master
2020-08-07T11:17:10.743765
2019-10-11T18:25:26
2019-10-11T18:25:26
213,428,556
0
0
MIT
2019-10-07T16:08:22
2019-03-25T17:58:26
2019-10-01T03:11:17
null
[ { "alpha_fraction": 0.6869881749153137, "alphanum_fraction": 0.7020018100738525, "avg_line_length": 35.63333511352539, "blob_id": "de5b53c70d6648ecda44dc59fe3e95ad7c77c730", "content_id": "3440fa58b42d2eadbe2d75f1139587955bb0fdf1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2198, "license_type": "permissive", "max_line_length": 137, "num_lines": 60, "path": "/module1-introduction-to-sql/buddymove_holidayiq.py", "repo_name": "vishnuyar/DS-Unit-3-Sprint-2-SQL-and-Databases", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport sqlite3\n#Import buddymove dataset by reading csv\nbuddymove_df = pd.read_csv('buddymove_holidayiq.csv')\n#Printing the shape of the dataset and first five rows\nprint(buddymove_df.shape)\nprint(buddymove_df.head())\n#Printing the number of null values in the dataset\nprint(\"The number of null values in the dataset are:\\n\",buddymove_df.isna().sum())\n\n#Opening a sqlite connection and creating a database\ndatabase_name = 'buddymove_holidayiq.sqlite3'\nconn = sqlite3.connect(database_name)\n#Dumping the dataframe to the database\nbuddymove_df.to_sql('buddymove_tbl',con=conn,if_exists='replace')\n\n#Checking for the first five rows to ensure the database dump was complete\nquery = 'SELECT * FROM buddymove_tbl LIMIT 5;'\n#Query for number of rows in database\nquery_rows = 'SELECT COUNT(\"User Id\") FROM buddymove_tbl;'\ntry:\n answer = conn.execute(query)\n for row in answer:\n print(row)\nexcept:\n pass\n\n#Getting the number of rows in the table\ntry:\n answer = conn.execute(query_rows)\n for row in answer:\n print(f'Number of rows in the table buddymove_tbl is :{row[0]}')\nexcept:\n pass\n\n#Number of users have rated atleast 100 in nature and atleast 100 in shopping category\nquery_users = 'SELECT COUNT(\"User Id\") FROM buddymove_tbl WHERE\\\n \"Nature\" >=100 AND \"Shopping\" >=100;'\ntry:\n answer = conn.execute(query_users)\n for row in answer:\n print(f'Number of users have rated atleast 100 in Nature and Shopping are :{row[0]}')\nexcept:\n pass\n#Query for getting average rating for all categories \nquery_avg_rating = 'SELECT AVG(\"Sports\"),AVG(\"Religious\"),AVG(\"Nature\"),AVG(\"Theatre\"),AVG(\"Shopping\"),AVG(\"Picnic\") FROM buddymove_tbl;'\ntry:\n answer = conn.execute(query_avg_rating)\n for row in answer:\n print(f'Avg rating for Sports:{row[0]:.2f}')\n print(f'Avg rating for Religious:{row[1]:.2f}')\n print(f'Avg rating for Nature:{row[2]:.2f}')\n print(f'Avg rating for Theatre:{row[3]:.2f}')\n print(f'Avg rating for Shopping:{row[4]:.2f}')\n print(f'Avg rating for Picnic:{row[5]:.2f}')\nexcept:\n pass\n#committing the changes and closing the connection\nconn.commit()\nconn.close()\n" }, { "alpha_fraction": 0.7727272510528564, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 25.399999618530273, "blob_id": "dada0cc30250e328a4cfb349dd7fda7daa1dbae9", "content_id": "c6c8c5d0f83c608c92d4d15e04b2d6ef587d7de2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 132, "license_type": "permissive", "max_line_length": 97, "num_lines": 5, "path": "/module3-nosql-and-document-oriented-databases/mongoproject.py", "repo_name": "vishnuyar/DS-Unit-3-Sprint-2-SQL-and-Databases", "src_encoding": "UTF-8", "text": "import pymongo\n\n\nclient = pymongo.MongoClient(\"mongodb+srv://mongoadmin:[email protected]/test?retryWrites=true&w=majority\")\ndb = client.test\n" }, { "alpha_fraction": 0.6224668025970459, "alphanum_fraction": 0.632774293422699, "avg_line_length": 35.006290435791016, "blob_id": "7dfcaf3e300072071c47bb3d582b2418e6ffa75c", "content_id": "5f18e5552b222a632b5268dbac0cbdb1157d8376", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5734, "license_type": "permissive", "max_line_length": 103, "num_lines": 159, "path": "/sprint/northwind.py", "repo_name": "vishnuyar/DS-Unit-3-Sprint-2-SQL-and-Databases", "src_encoding": "UTF-8", "text": "import sqlite3\n\n\"\"\"Database operations for the NorthWind data \"\"\"\n\ndef data_operations(conn,query):\n \"\"\" Function which performs database operations and returns results \"\"\"\n try:\n #creating a cursor for connection\n cursor = conn.cursor()\n #executing the query on the database and get the results\n results = cursor.execute(query).fetchall()\n except:\n return \"error in data operations\"\n \n #If No error is enountered, cursor is closed\n cursor.close()\n #Committing the data operatios\n conn.commit()\n #On successful completion return the results\n return results\n\ndef top_10_expensive_items(connect):\n \"\"\" \n Function to find the Top 10 expensive items per unit price\n Expected Output \n The 10 Most expensive Items in the database are:\n Côte de Blaye\n Thüringer Rostbratwurst\n Mishi Kobe Niku\n Sir Rodney's Marmalade\n Carnarvon Tigers\n Raclette Courdavault\n Manjimup Dried Apples\n Tarte au sucre\n Ipoh Coffee\n Rössle Sauerkraut\n \"\"\"\n #query for ten most expensive items in the database\n expensive_query = \"\"\" SELECT ProductName \n FROM Product \n ORDER BY UnitPrice DESC LIMIT 10 \"\"\"\n result = data_operations(connect,expensive_query)\n print(\"The 10 Most expensive Items in the database are:\\n\")\n for row in result:\n print(f'{row[0]}')\n\ndef avg_age_employee(connect):\n \"\"\" \n Function to find the average age of the employee at the time of hire\n Expected Output \n The Averag age of the employee at the time of hire is:37.22\n \"\"\"\n #Query for the Avg age of the employee at the time of hiring\n avg_age_employee = \"\"\" SELECT AVG(HireDate - BirthDate) FROM Employee; \"\"\"\n result = data_operations(connect,avg_age_employee)\n print(\"\\n\")\n for row in result:\n print(f'The Averag age of the employee at the time of hire is:{row[0]:0.2f}')\n\ndef avg_employee_age_bycity(connect):\n \"\"\" \n Function to find the average age of employees at the time of hire by city\n Expected Output \n The Averag age of the employee at the time of hire by City is :\n Kirkland : 29.0\n London : 32.5\n Redmond : 56.0\n Seattle : 40.0\n Tacoma : 40.0\n \"\"\"\n #Query for avg age of the employee by city\n avg_employee_age_bycity = \"\"\" SELECT city, AVG(HireDate - BirthDate)\n FROM Employee GROUP BY City; \"\"\"\n result = data_operations(connect,avg_employee_age_bycity)\n print(\"\\nThe Averag age of the employee at the time of hire by City is :\")\n for row in result:\n print(f'{row[0]} : {row[1]}')\n\ndef expensive_items_supplier(connect):\n \"\"\" \n Function to find the Top 10 expensive items per unit price and the Name of the Supplier\n Expected Output \n The 10 Most expensive Items in the database Supplier Names followed by Item Name:\n Aux joyeux ecclésiastiques : Côte de Blaye\n Plutzer Lebensmittelgroßmärkte AG : Thüringer Rostbratwurst\n Tokyo Traders : Mishi Kobe Niku\n Specialty Biscuits, Ltd. : Sir Rodney's Marmalade\n Pavlova, Ltd. : Carnarvon Tigers\n Gai pâturage : Raclette Courdavault\n G'day, Mate : Manjimup Dried Apples\n Forêts d'érables : Tarte au sucre\n Leka Trading : Ipoh Coffee\n Plutzer Lebensmittelgroßmärkte AG : Rössle Sauerkraut\n \"\"\"\n #Query for Top 10 expensive items along with Suppliet names\n expensive_query_supplier = \"\"\" SELECT CompanyName,ProductName \n FROM Product, Supplier \n WHERE Supplier.Id = Product.SupplierId \n ORDER BY UnitPrice DESC LIMIT 10\"\"\"\n result = data_operations(connect,expensive_query_supplier)\n print(\"\\nThe 10 Most expensive Items in the database with Supplier Names followed by Item Name:\\n\")\n for row in result:\n print(f'{row[0]} : {row[1]}')\n\ndef largest_category(connect):\n \"\"\" \n Function to find the Top category with largest unique products\n Expected Output \n The Category with largest unique products is :Confections \n \n \"\"\"\n #Query for the name of category with largest number of unique products\n largest_category = \"\"\" SELECT CategoryName FROM Category WHERE id = (\n SELECT CategoryId FROM Product \n GROUP BY\tCategoryId \n ORDER BY COUNT(CategoryId) DESC LIMIT 1) \"\"\"\n result = data_operations(connect,largest_category)\n print(\"\\n\")\n for row in result:\n print(f'The Category with largest unique products is :{row[0]}')\n\ndef most_territories_employee(connect):\n \"\"\"\n Function to find the Top 10 expensive items per unit price\n Expected Output \n The Employee with most territories is :Robert King \n \n \"\"\"\n #Query for name of the Employee who has the most territories\n most_territories_employee = \"\"\" SELECT FirstName,LastName FROM Employee WHERE id = (\n SELECT EmployeeId FROM EmployeeTerritory \n GROUP BY EmployeeId \n ORDER BY COUNT(TerritoryId) DESC LIMIT 1\n ) \"\"\"\n result = data_operations(connect,most_territories_employee)\n print(\"\\n\")\n for row in result:\n print(f'The Employee with most territories is :{row[0]} {row[1]}')\n\n\n\n\n#Creating a try catch block to safely operation on database\ntry:\n #Creating a connection to the Northwind database\n connect = sqlite3.connect('northwind_small.sqlite3')\n\n top_10_expensive_items(connect)\n avg_age_employee(connect)\n avg_employee_age_bycity(connect)\n expensive_items_supplier(connect)\n largest_category(connect)\n most_territories_employee(connect)\n \n\nexcept :\n pass\n#closing the connection to the database\nconnect.close()" }, { "alpha_fraction": 0.7328581213951111, "alphanum_fraction": 0.7427019476890564, "avg_line_length": 42.98507308959961, "blob_id": "3dc862585d641960ce6a2db716c6bc7dbcf9b88d", "content_id": "2e2d5cc72147b75ca95330684b72a2f69e1e0729", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2946, "license_type": "permissive", "max_line_length": 106, "num_lines": 67, "path": "/module1-introduction-to-sql/rpg_queries.py", "repo_name": "vishnuyar/DS-Unit-3-Sprint-2-SQL-and-Databases", "src_encoding": "UTF-8", "text": "import sqlite3\n\n#Creating a connection to the rpg database\nconn = sqlite3.connect('rpg_db.sqlite3')\n#creating a cursor for rpg database connection\ncurs = conn.cursor()\n#Query for number of characters in the game\nquery = 'SELECT COUNT(name) FROM charactercreator_character;'\n#Executing the query\nanswer = curs.execute(query)\nfor row in answer:\n print(f'They are a total of {row[0]} characters in the game')\nno_of_characters = row[0]\n#Different classes of character by table name\ncharacter_class = ['mage','thief','cleric','fighter']\nfor subclass in character_class:\n query = f'SELECT COUNT(character_ptr_id) FROM charactercreator_{subclass}'\n answer = curs.execute(query)\n for row in answer:\n print(f'They are {row[0]} characters of the class {subclass}')\n\n#Total items in the armoury\nquery = 'SELECT COUNT(name) FROM armory_item;'\nanswer = curs.execute(query)\nfor row in answer:\n print(f'They are a total of {row[0]} items in the armoury')\nno_of_items = row[0]\n#Number of weapons in the items\nquery = f'SELECT COUNT(item_ptr_id) FROM armory_weapon;'\nanswer = curs.execute(query)\nfor row in answer:\n print(f'They are a total of {row[0]} weapons in the items')\nno_of_weapons = row[0]\n#Number of non weapons in the items\nprint(f'They are a total of {(no_of_items-no_of_weapons)} weapons in the items')\n\n#No of items for Top 20 chararcters by name\nquery = 'select count(item_id) AS no_of_items,name\\\n from charactercreator_character_inventory,charactercreator_character\\\n where charactercreator_character.character_id = charactercreator_character_inventory.character_id\\\n GROUP BY charactercreator_character_inventory.character_id ORDER BY name ASC LIMIT 20;'\nanswer = curs.execute(query).fetchall()\nprint('The Number of items of the top 20 characters by name are')\nfor row in answer:\n print(f'No. of Items:{row[0]}, Name:{row[1]}')\n\n#No of weapons for Top 20 chararcters by name\nquery = 'select count(armory_weapon.item_ptr_id) AS no_of_items,name\\\n from charactercreator_character_inventory,charactercreator_character,armory_weapon\\\n where charactercreator_character.character_id = charactercreator_character_inventory.character_id\\\n AND charactercreator_character_inventory.item_id = armory_weapon.item_ptr_id\\\n GROUP BY charactercreator_character_inventory.character_id ORDER BY name ASC LIMIT 20;'\nanswer = curs.execute(query).fetchall()\nprint('The number of weapons of the top 20 characters by name are')\nfor row in answer:\n print(f'No. of Items:{row[0]}, Name:{row[1]}')\n\n#Total Number of items held by characters\nquery = 'select count(id) from charactercreator_character_inventory'\nanswer = curs.execute(query)\nfor row in answer:\n total_no_of_items = row[0]\n#Average number of items for each character\nprint(f'The average number of items per character is {total_no_of_items/no_of_characters:0.2f}')\n#closing the cursor and connection\ncurs.close()\nconn.close()" }, { "alpha_fraction": 0.7214285731315613, "alphanum_fraction": 0.7250000238418579, "avg_line_length": 29.035715103149414, "blob_id": "d2d9c27790fa8f365d5676ef720109ef345f7d58", "content_id": "425f3673d9a8294afbe416a40b3e251250da0f57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 840, "license_type": "permissive", "max_line_length": 84, "num_lines": 28, "path": "/module2-sql-for-analysis/insert_titanic.py", "repo_name": "vishnuyar/DS-Unit-3-Sprint-2-SQL-and-Databases", "src_encoding": "UTF-8", "text": "import psycopg2\nfrom sqlalchemy import create_engine\nimport pandas as pd\n\n#Reading titanic file to upload into pandas\ntitanic = pd.read_csv('titanic.csv')\n#Print the shape of titanic and print the top 5 rows\nprint(titanic.shape)\nprint(titanic.head())\n#Pring the columns of the titanics dataframe\nprint(titanic.columns)\n\nfrom sqlalchemy import create_engine\n\ndbname = \"rgfajssc\"\nusername = \"rgfajssc\"\npass_word = \"SECRET\"\nhost = \"john.db.elephantsql.com\"\n#creating creating engine inserting the titanic dataframe to postgres\ntry:\n engine = create_engine(f'postgresql://{username}:{pass_word}@{host}/{username}')\n titanic.to_sql('titanic', engine)\nexcept:\n pass\n\n# pg_connect = psycopg2.connect(dbname=dbname, user=username,\n# password=pass_word, host=host)\n# cur = pg_connect.cursor()" }, { "alpha_fraction": 0.6625658869743347, "alphanum_fraction": 0.6678383350372314, "avg_line_length": 23.782608032226562, "blob_id": "717bf8b7673d9552b6928611ba4a7f62099c991c", "content_id": "6a585e36c5c74d9dbbdf267561ed02b26ab8c662", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 569, "license_type": "permissive", "max_line_length": 70, "num_lines": 23, "path": "/module2-sql-for-analysis/titanic_query.py", "repo_name": "vishnuyar/DS-Unit-3-Sprint-2-SQL-and-Databases", "src_encoding": "UTF-8", "text": "import psycopg2\nimport sqlite3\n\ndbname = \"rgfajssc\"\nusername = \"rgfajssc\"\npass_word = \"U0W4kG-Um-Pug_wj8ec9OnbkQ70deuZR\"\nhost = \"john.db.elephantsql.com\"\n\npg_connect = psycopg2.connect(dbname=dbname, user=username,\n password=pass_word, host=host)\ncur = pg_connect.cursor()\n#Query for Survived people by class\nquery = 'SELECT survived,pclass, COUNT(pclass) FROM titanic \\\n GROUP BY (pclass,survived) order by survived asc ,pclass asc;'\ntry:\n cur.execute(query)\n for row in cur:\n print(row)\nexcept :\n pass\n\ncur.close()\npg_connect.close()" }, { "alpha_fraction": 0.6054700016975403, "alphanum_fraction": 0.6133291125297546, "avg_line_length": 31.804122924804688, "blob_id": "31c8fb3119bd2f64dcfc4c64daccd5cecb003399", "content_id": "91fe8c4a0ef54049352b069b5b5f7178a39161ac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3181, "license_type": "permissive", "max_line_length": 88, "num_lines": 97, "path": "/sprint/demo_data.py", "repo_name": "vishnuyar/DS-Unit-3-Sprint-2-SQL-and-Databases", "src_encoding": "UTF-8", "text": "import sqlite3\n\n\"\"\" Demo Data Query Using Sqlite 3 \"\"\"\n\ndef data_operations(conn,query):\n \"\"\" Function which performs database operations and returns results \"\"\"\n try:\n #creating a cursor for connection\n cursor = conn.cursor()\n #executing the query on the database and get the results\n results = cursor.execute(query).fetchall()\n except:\n return \"error in data operations\"\n \n #If No error is enountered, cursor is closed\n cursor.close()\n #Committing the data operatios\n conn.commit()\n #On successful completion return the results\n return results\n\n\n\ndef count_query(connect):\n \"\"\" \n Function to find the number of rows in the demo table\n Expected Output :The number of rows in demo table is 6 \n \n \"\"\"\n #How many rows in the demo table\n count_query = \"\"\"SELECT COUNT(*) FROM demo; \"\"\"\n #checking for 3 rows\n result = data_operations(connect,count_query)\n for row in result:\n print(f'The number of rows in demo table is {row[0]}')\n\ndef xy_query(connect):\n \"\"\" \n Function for finding the number of rows where x and y are atleast equal to 5\n Expected Output :The number of rows where x and y is atleast 5: 4 \n \n \"\"\"\n #How many rows where x and y are atleast 5\n xy_query = \"\"\" SELECT COUNT(*) FROM demo WHERE x >= 5 AND y >= 5; \"\"\"\n #checking for atleast x y having value 5\n result = data_operations(connect,xy_query)\n for row in result:\n print(f'The number of rows where x and y is atleast 5: {row[0]}')\n\n\ndef y_unique(connect):\n \"\"\" \n Function for finding the Number of Unique values of Y\n Expected output : The number of distinct values of y : 2 \n \n \"\"\"\n #Query for unique values of y\n y_unique = \"\"\" SELECT COUNT(DISTINCT y) FROM demo ; \"\"\"\n #checking for distinct values of y\n result = data_operations(connect,y_unique)\n for row in result:\n print(f'The number of distinct values of y : {row[0]}')\n \n\n#Create a connection within a try excecpt block to pass errors without causing exception\ntry:\n #Creating a database with name demo_data\n connect = sqlite3.connect('demo_data.sqlite3')\n #SQL Query for creating the table\n create_table_query = \"\"\"CREATE TABLE \"demo\" (\n \"s\" TEXT,\n \"x\" INTEGER,\n \"y\" INTEGER\n ); \"\"\"\n \n #Creating the table by sending to data operations function\n result = data_operations(connect,create_table_query)\n \n #Inserting values into the demo table\n insert_query = \"\"\"INSERT INTO demo (s,x,y) values\n (\"\\'g\\'\",3,9),\n (\"\\'v\\'\",5,7),\n (\"\\'f\\'\",8,7) ;\"\"\"\n\n #inserting the values into the demo table\n data_operations(connect,insert_query)\n\n #Now checking the demo table for data\n count_query(connect) # Number of rows in the table\n xy_query(connect) # Number of rows with x y values more than 5\n y_unique(connect) # Number of distinct y values in the table\n \nexcept:\n pass\n\n#closing the connection to the database\nconnect.close()" } ]
7
hanhe333/CS186
https://github.com/hanhe333/CS186
f62e3804a9f19e1c88d5fb94bc837e203689bfe3
01839814db6d7425125e3f40dafcc3ed9bdc95ac
b98aa7a526b044c868f61f9ac645ee61e3f10fb9
refs/heads/master
2021-01-10T11:04:58.284138
2013-03-05T21:39:35
2013-03-05T21:39:35
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5304756164550781, "alphanum_fraction": 0.5470346212387085, "avg_line_length": 33.74694061279297, "blob_id": "4a82adee5994a7ff6516e7c6f1210e3cb5ade50c", "content_id": "ade06819c7b3f5ed973ca955f8cf3e660c7297e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8515, "license_type": "no_license", "max_line_length": 126, "num_lines": 245, "path": "/HW3/hw3-code/hhawbudget.py", "repo_name": "hanhe333/CS186", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport sys\nfrom auction import iround\nimport math\nfrom gsp import GSP\nfrom util import argmax_index\n\nclass HHAWbudget:\n \"\"\"Balanced bidding agent\"\"\"\n def __init__(self, id, value, budget):\n self.id = id\n self.value = value\n self.budget = budget\n self.TOTAL_CLICKS = 0\n self.NUMBER_OF_PLAYERS = 0\n self.NUMBER_OF_SLOTS = 0\n\n def initialize_parameters(self, t, history):\n num_slots = len(history.round(t-1).clicks)\n\n self.NUMBER_OF_SLOTS = num_slots\n\n total_clicks = 0\n for time in range(48):\n total_clicks += self.clicks_round(time)\n\n self.TOTAL_CLICKS = total_clicks\n\n self.NUMBER_OF_PLAYERS = len(history.round(t-1).bids)\n\n def clicks_round(self, t):\n clicks = 0.0\n for slot in range(self.NUMBER_OF_SLOTS):\n clicks += self.clicks_slot(t, slot)\n\n return clicks\n\n def clicks_slot(self, t, slot):\n return iround(iround(30*math.cos(math.pi*t/24) + 50)*(.75**slot))\n\n def clicks_factor(self, t):\n return (self.clicks_round(t)/(self.TOTAL_CLICKS/48))**(.33)\n\n def calculate_past_clicks(self, t, history):\n past_clicks = 0\n for i in range(t-1):\n past_clicks += sum(history.round(i).clicks)\n return past_clicks\n\n def calculate_budgets(self, t, history):\n # sorted from lowest bid to highest\n id_to_budget = dict()\n\n ids = list()\n for i in xrange(len(history.round(t-1).bids)):\n ids.append(history.round(t-1).bids[i][0])\n\n for idx in ids:\n for i in xrange(t):\n bids = sorted(history.round(i).bids, key=lambda bid: -bid[1])\n slot_num = -1\n for j in xrange(len(bids)-1):\n if bids[j][0] == idx and j < len(history.round(i).slot_payments):\n slot_num = j\n if not idx in id_to_budget:\n id_to_budget[idx] = 0\n if slot_num != -1:\n id_to_budget[idx] = id_to_budget[idx] + history.round(i).slot_payments[slot_num]\n\n return id_to_budget\n\n def defaults(self, t, history, reserve):\n num_zero = 0\n\n if t < 2:\n return 0\n else:\n for i in xrange(self.NUMBER_OF_PLAYERS):\n if history.round(t-2).bids[i][1] <= reserve+1 and history.round(t-1).bids[i][1] <= reserve+1 and i != self.id:\n num_zero += 1\n elif history.round(t-1).bids[i][1] <= reserve+1 and i != self.id:\n num_zero += .5\n\n return num_zero\n\n def budget_factor(self, t, history, reserve):\n budget = self.calculate_budgets(t, history)[self.id]\n past_clicks = self.calculate_past_clicks(t, history)\n defaults = self.defaults(t, history, reserve)\n\n budget_value = (1.0 - (budget/60000.0) + (float(past_clicks)/self.TOTAL_CLICKS))**2.5\n\n if budget_value < .7 and defaults >= .5:\n return 0\n elif budget_value < .8 and defaults >= 1:\n return 0\n elif budget_value < .85 and defaults >= 1.5 and t < 47:\n return 0\n\n return budget_value\n\n \n def slot_info(self, t, history, reserve):\n \"\"\"Compute the following for each slot, assuming that everyone else\n keeps their bids constant from the previous rounds.\n\n Returns list of tuples [(slot_id, min_bid, max_bid)], where\n min_bid is the bid needed to tie the other-agent bid for that slot\n in the last round. If slot_id = 0, max_bid is 2* min_bid.\n Otherwise, it's the next highest min_bid (so bidding between min_bid\n and max_bid would result in ending up in that slot)\n \"\"\"\n prev_round = history.round(t-1)\n avr_round = []\n\n if t >= 2:\n prev_round2 = history.round(t-2)\n\n # predict other people's values\n for i in xrange(len(prev_round.bids)):\n if prev_round.bids[i][1] == 0:\n avr_round.append(prev_round.bids[i]) \n elif abs(prev_round.bids[i][1] - prev_round2.bids[i][1]) < 10:\n avr_round.append((prev_round.bids[i][0], .5*prev_round.bids[i][1] + .5*prev_round2.bids[i][1]))\n else:\n avr_round.append(prev_round2.bids[i])\n else:\n avr_round = prev_round.bids\n\n other_bids = filter(lambda (a_id, b): a_id != self.id, avr_round)\n\n clicks = prev_round.clicks\n def compute(s):\n (min, max) = GSP.bid_range_for_slot(s, clicks, reserve, other_bids)\n if max == None:\n max = 2 * min\n return (s, min, max)\n \n info = map(compute, range(len(clicks)))\n# sys.stdout.write(\"slot info: %s\\n\" % info)\n return info\n\n \n def expected_utils(self, t, history, reserve):\n \"\"\"\n Figure out the expected utility of bidding such that we win each\n slot, assuming that everyone else keeps their bids constant from\n the previous round.\n\n returns a list of utilities per slot.\n \"\"\"\n # TODO: Fill this in\n clicks = history.round(t-1).clicks\n utilities = [0.0]*(len(clicks)) # Change this\n\n info = self.slot_info(t, history, reserve)\n\n for i in xrange(len(clicks)):\n s_k = self.clicks_slot(t, i)\n utilities[i] = s_k*(self.value - info[i][1])\n \n return utilities\n\n def target_slot(self, t, history, reserve):\n \"\"\"Figure out the best slot to target, assuming that everyone else\n keeps their bids constant from the previous rounds.\n\n Returns (slot_id, min_bid, max_bid), where min_bid is the bid needed to tie\n the other-agent bid for that slot in the last round. If slot_id = 0,\n max_bid is min_bid * 2\n \"\"\"\n i = argmax_index(self.expected_utils(t, history, reserve))\n info = self.slot_info(t, history, reserve)\n return info[i]\n\n def initial_bid(self, reserve):\n bid = 0\n if self.value <=60:\n return self.value-.01\n else:\n return .55*self.value-.01\n\n def bid(self, t, history, reserve):\n # The Balanced bidding strategy (BB) is the strategy for a player j that, given\n # bids b_{-j},\n # - targets the slot s*_j which maximizes his utility, that is,\n # s*_j = argmax_s {clicks_s (v_j - p_s(j))}.\n # - chooses his bid b' for the next round so as to\n # satisfy the following equation:\n # clicks_{s*_j} (v_j - p_{s*_j}(j)) = clicks_{s*_j-1}(v_j - b')\n # (p_x is the price/click in slot x)\n # If s*_j is the top slot, we (arbitrarily) choose\n # b' = (v_j + p_0(j)) / 2. We can \n # thus deal with all slots uniformly by defining clicks_{-1} = 2 clicks_0.\n #\n\n # initialize parameters\n if self.NUMBER_OF_PLAYERS == 0 or self.TOTAL_CLICKS == 0 or self.NUMBER_OF_SLOTS == 0:\n self.initialize_parameters(t, history)\n # print \"Number of players: \", self.NUMBER_OF_PLAYERS\n # print \"Number of slots: \", self.NUMBER_OF_SLOTS\n # print \"Total clicks\", self.TOTAL_CLICKS\n\n prev_round = history.round(t-1)\n \n (slot, min_bid, max_bid) = self.target_slot(t, history, reserve)\n\n num_default = self.defaults(t, history, reserve)\n\n bid = 0\n if num_default == 0:\n bid = (min_bid + max_bid)/2\n elif num_default > 0 and num_default <= 1:\n bid = (.25*min_bid + .75*max_bid)\n elif num_default > 1:\n bid = max_bid\n\n budget_effect = self.budget_factor(t, history, reserve)\n click_effect = self.clicks_factor(t)\n\n # print \"defaults: \", num_default\n # print \"bid (pre factors): \", bid, min_bid, max_bid\n # print \"slot: \", slot\n # print \"budget: \", budget_effect\n # print \"click: \", click_effect\n \n bid = bid*budget_effect*click_effect\n\n if bid > max_bid:\n bid = max_bid\n\n if bid > self.value:\n bid = self.value\n if bid < reserve+1.01 and reserve+1.01 < self.value:\n return reserve+1.01\n\n if self.value < 75 and budget_effect > 1:\n return self.value\n\n return iround(bid)-0.01\n\n def __repr__(self):\n return \"%s(id=%d, value=%d)\" % (\n self.__class__.__name__, self.id, self.value)\n\n\n" } ]
1
aramidetosin/NornirJunos
https://github.com/aramidetosin/NornirJunos
ad6922eec149b54a46bc7af3204d88e8b76aa169
dc2fe6753948eb89720111bd37c36f701073b4ff
c7449a9afbce7c082323560d794f09c7b71df3cf
refs/heads/main
2023-01-31T05:22:03.081108
2020-12-13T02:53:19
2020-12-13T02:53:19
320,423,020
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7272727489471436, "alphanum_fraction": 0.7452152967453003, "avg_line_length": 19.924999237060547, "blob_id": "c3c45e78f2c87509e1595fbccbaa1a4954184229", "content_id": "abdede1bbefb77813e7c3ce06eb1c9a503c312eb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 836, "license_type": "permissive", "max_line_length": 140, "num_lines": 40, "path": "/README.md", "repo_name": "aramidetosin/NornirJunos", "src_encoding": "UTF-8", "text": "# NornirJunos\n\nAutomating Stuff with Nornir and nornir_pyez\n\n![alt text](https://github.com/aramidetosin/NornirJunos/blob/main/pics/topo.png?raw=true)\n\n## Requirements\n\n```\npip install nornir_pyez\n```\n\nMust also have base config in place so that SSH access can be reached\n\n## Usage\n\nThe main.py file deploys MC-LAG on 2 vMX devices serving as PE to a CE\n\n1. Change the host variables as needed\n2. Run main.py\n\n## Interface config\n\n![alt text](https://github.com/aramidetosin/NornirJunos/blob/main/pics/topo2.png?raw=true)\n\n1. interfaces.j2\n2. config_ints.py\n\n## IS-IS config\n\n1. isis_config.j2\n2. isis_interfaces.j2\n3. config_isis.py\n\n## MPLS => RSVP => CSPF\n\nThis will deploy RSVP signaled MPLS with CSPF bandwidth constraints. Note that it will deploy the LSP on the edges and just RSVP in the core\n\n1. mpls_proto.j2\n2. deploy_mpls.py" }, { "alpha_fraction": 0.4879912734031677, "alphanum_fraction": 0.5342066884040833, "avg_line_length": 35.6533317565918, "blob_id": "cf2f7ffad1e2d1302adcdf1ced46f126ad3fbf5c", "content_id": "0d91f314370d3f95bcfce3a7ebfc308aaff09824", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2748, "license_type": "permissive", "max_line_length": 117, "num_lines": 75, "path": "/working/set_ints.py", "repo_name": "aramidetosin/NornirJunos", "src_encoding": "UTF-8", "text": "import requests\nfrom datetime import datetime\nimport time\nimport argparse\nimport getpass\nimport json\nfrom rich import print\nimport logging\nimport urllib3\nfrom netmiko import ConnectHandler\nfrom eve_up import get_nodes, get_links\nfrom ipaddress import *\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\nlogging.basicConfig(level=logging.DEBUG,\n format=f'%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')\n\ndef base_config():\n counter = 0\n nodes = get_nodes(topo=\"NornirJunos.unl\")\n ips = ['192.168.20.191',\n '192.168.20.192',\n '192.168.20.193',\n '192.168.20.194',\n '192.168.20.195',\n '192.168.20.196',\n '192.168.20.197',\n '192.168.20.198',\n '192.168.20.199']\n for key, value in nodes.items():\n try:\n if value[\"template\"] == \"vmx\":\n ## Get the Telnet address and port set to variables\n url = value[\"url\"].split(\":\")\n ip = url[1].replace(\"//\", \"\")\n port = (url[2])\n node_conn = {\n 'device_type' : 'juniper_junos_telnet',\n 'host' : ip,\n 'port': port, \n }\n # Initiate connection to EVE \n net_connect = ConnectHandler(**node_conn)\n hostname = f'vMX{str(counter+1)}'\n # counter += 1\n # Send commands and view output\n config_commands = [ 'set system root-authentication encrypted-password \"$1$hBBaQcLY$AZYmNq9VbicPSNbl4KDcf0\"',\n 'delete chassis auto-image-upgrade',\n f'set system host-name {hostname}',\n 'set system domain-name abc.co',\n 'set system services ssh',\n 'set system services netconf ssh',\n 'set system login user cisco class super-user authentication encrypted-password \"$1$hBBaQcLY$AZYmNq9VbicPSNbl4KDcf0\"',\n f'set interfaces ge-0/0/4 unit 0 family inet address {ips[counter]}/24']\n output = net_connect.send_config_set(config_commands, exit_config_mode=False)\n counter += 1\n print(output)\n # Commit \n output = net_connect.commit(and_quit=True)\n print(output)\n\n except Exception as err:\n continue\n\n# def ip_addresser(subnet: str = '192.168.20.0/24'):\n# subnets = list(ip_network(subnet).subnets(new_prefix = 30))\n# print(subnets)\n# for subn in subnets:\n# print(list(subn.hosts()))\n# links = get_links(\"NornirJunos.unl\")\n# print(links)\n# return subnets\n\n\nif __name__ == \"__main__\":\n base_config()" } ]
2
swiftcore/ReSQL
https://github.com/swiftcore/ReSQL
2d56cabbaf2e45c702e2b6f99a675f030fc68ba6
3e10df71582fac8971b3a37ad1c42aa4c9338d72
940dc3019f4800fd7d25935c11534e9ba8bda8fd
refs/heads/master
2020-12-24T16:58:38.343069
2014-10-25T11:23:57
2014-10-25T11:23:57
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.604938268661499, "alphanum_fraction": 0.6123456954956055, "avg_line_length": 21.5, "blob_id": "2f0cf6db22169ba60dd8f0f1e1b38952dba4fa55", "content_id": "540525fa035bc82f89eb92a9ea0a75322f6b7320", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 405, "license_type": "no_license", "max_line_length": 64, "num_lines": 18, "path": "/main.c", "repo_name": "swiftcore/ReSQL", "src_encoding": "UTF-8", "text": "/*\n * resql compiler main entry\n */\n#include \"resql.h\"\n\nint main(int ac, char** av)\n{\n // set the output of select_expr_list to be of all contents\n only_attr_cmd = 0;\n // set the rewrite kind to rewrite join sql\n rewrite_kind = 0;\n // give the schema file name\n schema_fname = \"schema.txt\";\n // parse source sql file and try to rewrite it\n sparse(ac,av);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.7582417726516724, "alphanum_fraction": 0.7582417726516724, "avg_line_length": 21.75, "blob_id": "d87cd99097db78bf4b1d18f4e34fd5b697decf0c", "content_id": "87f09e492902f804bb5945577cd39e32ba18e718", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 91, "license_type": "no_license", "max_line_length": 77, "num_lines": 4, "path": "/README.md", "repo_name": "swiftcore/ReSQL", "src_encoding": "UTF-8", "text": "ReSQL\n=====\n\nA SQL rewriting compiler which helps to do query jobs in uncertain databases.\n" }, { "alpha_fraction": 0.5797173976898193, "alphanum_fraction": 0.5933499336242676, "avg_line_length": 32.41666793823242, "blob_id": "83e757f8f95aef983e01862aad350c8bc68b0bad", "content_id": "0a8bb20501d86b6261b385ce29b3417afbc28301", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6015, "license_type": "no_license", "max_line_length": 92, "num_lines": 180, "path": "/showcase.py", "repo_name": "swiftcore/ReSQL", "src_encoding": "UTF-8", "text": "#!/bin/env python\n# the graphical interface of resql compiler client\nimport wx\nimport wx.grid\nfrom subprocess import *\nimport sys\n\n# call the client to connect to the server for rewriting the sql statement\ndef call_clnt(sql):\n try:\n # under windows\n # p1 = Popen(['echo',sql],stdout=PIPE,shell=True)\n # p2 = Popen(['python','clnt.py'],stdin=p1.stdout,stdout=PIPE,shell=True)\n p1 = Popen(['echo',sql],stdout=PIPE)\n p2 = Popen(['python','clnt.py'],stdin=p1.stdout,stdout=PIPE)\n fout,ferr = p2.communicate()\n return fout\n except OSError, e:\n pass\n\n# define my application form\nclass MyApp(wx.App):\n def OnInit(self):\n frame = MyFrame(\"ReSQL Client v0.1\",(50,60),(460,420))\n frame.Show()\n self.SetTopWindow(frame)\n return True\n\n# define the output table of the query result\nclass MyTable(wx.grid.PyGridTableBase):\n def __init__(self):\n wx.grid.PyGridTableBase.__init__(self)\n self.data = {}\n self.odd = wx.grid.GridCellAttr()\n self.odd.SetBackgroundColour(\"white\")\n self.even = wx.grid.GridCellAttr()\n self.even.SetBackgroundColour(\"wheat\")\n self.rows = self.cols = 5\n\n def setData(self,data):\n self.data = data\n \n def GetNumberRows(self):\n return self.rows\n\n def GetNumberCols(self):\n return self.cols\n\n def SetNumberRows(self,rows):\n self.rows = rows\n\n def SetNumberCols(self,cols):\n self.cols = cols\n \n def IsEmptyCell(self,row,col):\n return self.data.get((row,col)) is None\n\n def GetValue(self,row,col):\n value = self.data.get((row,col))\n if value is not None:\n return value\n else:\n return ''\n\n def SetValue(self,row,col,value):\n self.data[(row,col)] = value\n\n def GetAttr(self,row,col,kind):\n attr = [self.even,self.odd][row % 2]\n attr.IncRef()\n return attr\n\n# define the Frame with menus, buttons, output table in it.\nclass MyFrame(wx.Frame):\n def __init__(self,title,post,sizet):\n wx.Frame.__init__(self,None,-1,title, pos=post,size=sizet)\n menuFile = wx.Menu()\n menuFile.Append(1,\"&About\")\n menuFile.AppendSeparator()\n menuFile.Append(2,\"E&xit\")\n menuOutput = wx.Menu()\n menuOutput.Append(3,\"Output rewiting\")\n menuOutput.Append(4,\"Output result\")\n menuBar = wx.MenuBar()\n menuBar.Append(menuFile,\"&File\")\n menuBar.Append(menuOutput,\"&Output\")\n\n panel = wx.Panel(self,-1)\n self.schemaBtn = wx.Button(panel,-1,\"S\",pos=(20,0),size=(40,30))\n self.rewriteBtn = wx.Button(panel,-1,\"R\",pos=(70,0),size=(40,30))\n self.rewriteBtn.Disable()\n self.execBtn = wx.Button(panel,-1,\"Exec\",pos=(120,0),size=(40,30))\n self.execBtn.Disable()\n self.Bind(wx.EVT_BUTTON,self.OnSchemaClick,self.schemaBtn)\n self.Bind(wx.EVT_BUTTON,self.OnRewrite,self.rewriteBtn)\n self.Bind(wx.EVT_BUTTON,self.OnExecQuery,self.execBtn)\n\n self.text = wx.TextCtrl(panel,-1,\"\",size=(440,100),pos=(5,40),style=wx.TE_MULTILINE)\n\n from wx.grid import Grid\n self.grid = Grid(panel,pos=(5,140),size=(440,200))\n self.table = MyTable()\n self.grid.SetTable(self.table)\n \n self.SetMenuBar(menuBar)\n self.CreateStatusBar()\n self.SetStatusText(\"Welcome to ReSQL Client\")\n self.Bind(wx.EVT_MENU,self.OnAbout,id=1)\n self.Bind(wx.EVT_MENU,self.OnQuit,id=2)\n self.Bind(wx.EVT_MENU,self.OnOutputRewriting,id=3)\n self.Bind(wx.EVT_MENU,self.OnOutputResult,id=4)\n\n def OnQuit(self,event):\n self.Close()\n\n def OnAbout(self,event):\n msg = \"The Rewriting SQL client v0.1 !\\n\\nContact:[email protected]\"\n wx.MessageBox(msg,\"About ReSQL client\", wx.OK | wx.ICON_INFORMATION, self)\n\n def OnSchemaClick(self,event):\n schemaStr = 'schema: ' + self.text.GetValue().decode('utf-8').encode('ascii')\n back = call_clnt(schemaStr.replace('\\n',' '))\n wx.MessageBox(back,\"Schema\",wx.OK | wx.ICON_INFORMATION,self)\n self.rewriteBtn.Enable()\n \n def OnRewrite(self,event):\n sql = \"sql: \" + self.text.GetValue().decode('utf-8').encode('ascii')\n self.resql = call_clnt(sql.replace('\\n',' '))\n wx.MessageBox(self.resql,\"Rewrite\", wx.OK | wx.ICON_INFORMATION,self)\n self.execBtn.Enable()\n \n def OnExecQuery(self,event): \n #rows,cols,data = self.execQuery(self.resql)\n #self.table.SetNumberRows(rows)\n #self.table.SetNumberCols(cols)\n #self.table.setData(data)\n #self.grid.SetTable(self.table)\n wx.MessageBox(\"Exec \" + self.resql,\"Rewrite\", wx.OK | wx.ICON_INFORMATION,self)\n \n def OnOutputRewriting(self,event):\n msg = \"output writing query\"\n wx.MessageBox(msg,\"Rewriting query\",wx.OK | wx.ICON_INFORMATION,self)\n\n def OnOutputResult(self,event):\n rows,cols = self.table.GetNumberRows(),self.table.GetNumberCols()\n wd = []\n for i in range(rows):\n tmp = []\n for j in range(cols):\n tmp.append(self.table.data[(i,j)])\n wd.append(tmp)\n\n import csv\n writer = csv.writer(open('sample.csv','wb'))\n writer.writerows(wd)\n\n msg = \"output query result\"\n wx.MessageBox(msg,\"Query result\",wx.OK | wx.ICON_INFORMATION,self)\n \n def execQuery(self,sql):\n import pymssql\n cxn = pymssql.connect(password='61813744',host=r'.\\SQLEXPRESS',database='hello')\n cur = cxn.cursor()\n cur.execute(sql)\n\n data = {}\n i = coln = 0\n for eachRow in cur.fetchall():\n coln = len(eachRow)\n for x in range(coln):\n data[(i,x)] = eachRow[x]\n i += 1\n\n cxn.commit()\n cxn.close()\n return cur.rownumber,coln,data\n \nif __name__ == '__main__':\n app = MyApp(False)\n app.MainLoop()\n" }, { "alpha_fraction": 0.6983082890510559, "alphanum_fraction": 0.706296980381012, "avg_line_length": 25.271604537963867, "blob_id": "2c43961a32aa92fcee07b903fb86abea279de762", "content_id": "a3e5e04b3175e3c3a027737cae0879783db5fe99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 2128, "license_type": "no_license", "max_line_length": 74, "num_lines": 81, "path": "/case.sql", "repo_name": "swiftcore/ReSQL", "src_encoding": "UTF-8", "text": "select o.clerk\nfrom customer c, orders o\nwhere c.acctbal > 1000 and o.custfk = c.custkey\n\nwith Candidates as (\n select distinct o.orderkey, o.clerk\n from customer c , orders o\n where c.acctbal > 1000 and o.custfk = c.custkey\n),\nFilter as (\n select o.orderkey\n from Candidates Cand\n join orders o on Cand.orderkey = o.orderkey\n left outer join customer c on o.custfk = c.custkey\n where c.custkey is null or c.acctbal <= 1000\n union all \n select orderkey\n from Candidates Cand\n group by orderkey\n having count(*) > 1\n)\nselect distinct clerk\nfrom Candidates Cand\nwhere not exists ( select * from Filter F\n where Cand.orderkey = F.orderkey);\n\n\nselect nationkey, sum(acctbal)\nfrom customer\nwhere mktsegment='building'\ngroup by nationkey\n\nqG:\nselect nationkey\nfrom customer\nwhere mktsegment='building'\ngroup by nationkey\n\nwith Candidates as(\n select custkey,nationkey\n from customer\n where mktsegment='building'\n),\nFilter as(\n select custkey\n from customer\n where mktsegment!='building'\n),\nQGCons as (\n select nationkey\n from Candidates c\n where not exists ( select * from Filter f where c.custkey=f.custkey)\n group by nationkey\n),\nUnFilteredCandidates as (\n select custkey,nationkey,\n min(acctbal) as minBal,\n\t max(acctbal) as maxBal\n from customer c\n where mktsegment='building'\n and not exists (select * from Filter where c.custkey=Filter.custkey)\n group by custkey,nationkey\n),\nFilteredCandidates as (\n select custkey,nationkey,\n case when min(acctbal) > 0 then 0 else min(acctbal) end as minBal,\n case when max(acctbal) > 0 then max(acctbal) else 0 end as maxBal\n from customer c\n where mktsegment='building'\n and exists ( select * from Filter where Filter.custkey=c.custkey)\n\tand exists ( select * from QGCons where QGCons.nationkey=c.nationkey)\n group by custkey,nationkey\n),\nUnionCandidates as (\n select * from FilteredCandidates\n union all\n select * from UnFilteredCandidates\n)\nselect nationkey,sum(minbal),sum(maxBal)\n from UnionCandidates\ngroup by nationkey\n" }, { "alpha_fraction": 0.5203947424888611, "alphanum_fraction": 0.5238970518112183, "avg_line_length": 18.06974220275879, "blob_id": "13eb26c13b2517b57c324d4c4666f69cefa5e84e", "content_id": "66237edce1e38fe62460eb44e0cc5f115e331279", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 51680, "license_type": "no_license", "max_line_length": 154, "num_lines": 2710, "path": "/resql_funcs.c", "repo_name": "swiftcore/ReSQL", "src_encoding": "UTF-8", "text": "/*\n * All resql compiler useful functions\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <string.h>\n#include \"resql.h\"\n\n// build a new symbol node and return its addr\npsymbol newsymbol(char* s)\n{\n psymbol sp = (psymbol)malloc(sizeof(struct symbol));\n sp->name = strdup(s);\n\n return sp;\n}\n\n// build a new abstract syntax tree node and return its addr\npast newast(int node_type,past l, past r, past rr)\n{\n past a = (past)malloc(sizeof(struct ast));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = node_type;\n a->l = l;\n a->r = r;\n a->rr = rr;\n\n return a;\n}\n\n// build a int node and return its addr\npast newint(int n)\n{\n pintval a = (pintval)malloc(sizeof(struct intval));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = 'I';\n a->number = n;\n\n return (past)a;\n}\n\n// build a float node and return its addr\npast newfloat(double f)\n{\n pfloatval a = (pfloatval)malloc(sizeof(struct floatval));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = 'L';\n a->number = f;\n\n return (past)a;\n}\n\n// build a string node and return its addr\npast newstring(char* s)\n{\n pstrval a = (pstrval)malloc(sizeof(struct strval));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = 'S';\n a->str = strdup(s);\n\n return (past)a;\n}\n\n// build a symref node and return its addr\npast newsymref(psymbol s)\n{\n psymref a = (psymref)malloc(sizeof(struct symref));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = 'N';\n a->s = s;\n\n return (past)a;\n}\n\n// build a compare expr node and return its addr\npast newcmp(int cmp_type, past l, past r)\n{\n past a = (past)malloc(sizeof(struct ast));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = '0' + cmp_type;\n a->l = l;\n a->r = r;\n a->rr = NULL;\n\n return a;\n}\n\n// build a function node and return its addr\npast newfunc(past l)\n{\n pfncall a = (pfncall)malloc(sizeof(struct fncall));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = 'F';\n a->l = l;\n\n return (past)a;\n}\n\n// build a user-define function node and return its addr\npast newcall(past s, past l)\n{\n pufncall a = (pufncall)malloc(sizeof(struct ufncall));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = 'C';\n a->s = (psymref)s; /* function name */\n a->l = l;\n\n return (past)a;\n}\n\n// build a select expression list node and return its addr\npast newselect_expr_list(past exp, past als, past n)\n{\n pselect_expr_list a = (pselect_expr_list)malloc(sizeof(struct select_expr_list));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = 's';\n a->expr = exp;\n a->as_alias = (psymref)als;\n a->next = (pselect_expr_list)n;\n\n return (past)a;\n}\n\n// build a groupby list node and return its addr\npast newgroupby_list(int opt_ad, past expr, past n)\n{\n pgroupby_list a = (pgroupby_list)malloc(sizeof(struct groupby_list));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = 'g';\n a->opt_asc_desc = opt_ad;\n a->expr = expr;\n a->next = (pgroupby_list)n;\n\n return (past)a;\n}\n\n// build a table reference list node and return its addr\npast newtable_references(int reft, past table_r, past n)\n{\n ptable_references a = (ptable_references)malloc(sizeof(struct table_references));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = 'r';\n a->ref_type = reft;\n a->table_ref = table_r;\n a->next = (ptable_references)n;\n\n return (past)a;\n}\n\n// build a table factor node and return its addr\npast newtable_factor(int factor_t, past s, past s2, past s3,past l)\n{\n ptable_factor a = (ptable_factor)malloc(sizeof(struct table_factor));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = 'f';\n a->factor_type = factor_t;\n a->s = (psymref)s;\n a->s2 = (psymref)s2;\n a->s3 = (psymref)s3;\n a->l = l;\n\n return (past)a;\n}\n\n// build a join condition node and return its addr\npast newjoin_condition(int join_t, past expr)\n{\n pjoin_condition a = (pjoin_condition)malloc(sizeof(struct join_condition));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = 'c';\n a->con_type = join_t;\n a->l = expr;\n\n return (past)a;\n}\n\n// build a join table node and return its addr\npast newjoin_table(int join_type, past table_r, past table_f, past join_c)\n{\n pjoin_table a = (pjoin_table)malloc(sizeof(struct join_table));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = 't';\n a->join_type = join_type;\n a->table_ref = table_r;\n a->table_fct = table_f;\n a->join_cond = join_c;\n\n return (past)a;\n}\n\n// build a index list node and return its addr\npast newindex_list(past s, past n)\n{\n pindex_list a = (pindex_list)malloc(sizeof(struct index_list));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = 'i';\n a->s = (psymref)s;\n a->next = (pindex_list)n;\n\n return (past)a;\n}\n\n// build a select statement node and return its addr\npast newselect_stmt(int sel_t, past sel_el, past table_rs, past opt_w, past gpb_l,past opt_h, past odb)\n{\n pselect_stmt a = (pselect_stmt)malloc(sizeof(struct select_stmt));\n\n if(!a)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n a->node_type = 'm';\n a->sel_type = sel_t;\n a->sel_expr_list = (pselect_expr_list)sel_el;\n a->table_refs = (ptable_references)table_rs;\n a->opt_where_expr = opt_w;\n a->gpb_list = (pgroupby_list)gpb_l;\n a->opt_having_expr = opt_h;\n a->odb_list = (pgroupby_list)odb;\n\n return (past)a;\n}\n\n/* for user-define function arguments\n * build a new argument list and return its addr\n */\nstruct symlist *newsymlist(past expr, struct symlist *next)\n{\n struct symlist * sl = (struct symlist*)malloc(sizeof(struct symlist));\n\n if(!sl)\n {\n\t yyerror(\"out of space\");\n\t exit(0);\n }\n\n sl->expr = expr;\n sl->next = next;\n\n return sl;\n}\n\n// free a abstract syntax tree node\nvoid free_ast(past a)\n{ \n switch(a->node_type)\n {// three subnodes\n case 'W': \n {\n\t // free .. between .. and ...\n\t free_ast(a->l);\n\t free_ast(a->r);\n\t free_ast(a->rr);\n\t free(a);\n\t break;\n }\n // two subnodes\n case '+':\n case '-':\n case '*':\n case '/':\n case '%':\n case 'D': // NAME.NAME\n case '1': // free <\n case '2': // free >\n case '3': // free !=\n case '4': // free =\n case '5': // free <=\n case '6': // free >=\n case 'A': // free and\n case 'O': // free or\n case 'Q': // free in\n case 'K': // free like\n {\n\t free_ast(a->l);\n\t free_ast(a->r);\n\t free(a);\n\t break;\n }\n case 'B': // free bool\n case 'E': // free exists\n case 'U': // free null\n case 'M': // free - expr\n case 'T': // free not\n {\n\t // one subnodes\n\t free_ast(a->l);\n\t free(a);\n\t break;\n }\n case 'F':\n {\n\t // free funcions\n\t free_fncall((pfncall)a);\n\t break;\n }\n case 'C':\n {\n\t //free user calls\n\t free_ufncall((pufncall)a);\n\t break;\n }\n case 'I':\n {\n\t // free intval\n\t free((pintval)a);\n\t break;\n }\n case 'L':\n {\n\t // free floatval\n\t free((pfloatval)a);\n\t break;\n }\n case 'S':\n {\n\t // free strval\n\t pstrval s = (pstrval)a;\n\t free(s->str);\n\t free(s);\n\t break;\n }\n case 'N':\n {\n\t //free symref\n\t free((psymref)a);\n\t break;\n }\n // special unterminal nodes\n case 'v':\n {\n\t //free_val_list(a);\n\t if(a->r != NULL)\n\t free_ast(a->r);\n\t free_ast(a->l);\n\t free(a);\n\t break;\n }\n case 's':\n {\n\t free_select_expr_list((pselect_expr_list)a);\n\t break;\n }\n case 'g':\n {\n\t free_groupby_list((pgroupby_list)a);\n\t break;\n }\n case 'r':\n {\n\t free_table_references((ptable_references)a);\n\t break;\n }\n case 'f':\n {\n\t free_table_factor((ptable_factor)a);\n\t break;\n }\n case 't':\n {\n\t free_join_table((pjoin_table)a);\n\t break;\n }\n case 'c':\n {\n\t free_join_condition((pjoin_condition)a);\n\t break;\n }\n case 'i':\n {\n\t free_index_list((pindex_list)a);\n\t break;\n }\n case 'm':\n {\n\t free_select_stmt((pselect_stmt)a);\n\t break;\n }\n }\n}\n\n\n/* free user-define function argument list */\nvoid symlistfree(struct symlist *sl)\n{\n struct symlist* nsl;\n\n if(sl != NULL)\n {\n\t nsl = sl->next;\n while(nsl != NULL)\n {\n free_ast(sl->expr);\n\t free(sl);\n\t sl = nsl;\n\t nsl = sl->next;\n }\n \t \n free_ast(sl->expr);\n sl = nsl;\n }\n}\n\n// free a select expression list\nvoid free_select_expr_list(pselect_expr_list a)\n{\n if(a->next != NULL)\n {\n\t free_select_expr_list(a->next);\n }\n\n free_ast(a->expr);\n free(a);\n}\n\n// free a group by expression list\nvoid free_groupby_list(pgroupby_list a)\n{\n if(a->next != NULL)\n {\n\t free_groupby_list(a->next);\n }\n\n free_ast(a->expr);\n free(a);\n}\n\n// free a table reference list\nvoid free_table_references(ptable_references a)\n{\n if(a->next != NULL)\n {\n\t free_table_references(a->next);\n }\n\n free_ast(a->table_ref);\n free(a);\n}\n\n// free a table factor node\nvoid free_table_factor(ptable_factor a)\n{\n if(a->l != NULL)\n\t free_ast(a->l);\n free(a);\n}\n\n// free a join table node\nvoid free_join_table(pjoin_table a)\n{\n if(a->table_ref != NULL)\n\t free_ast(a->table_ref);\n if(a->table_fct != NULL)\n\t free_table_factor((ptable_factor)a->table_fct);\n if(a->join_cond != NULL)\n\t free_join_condition((pjoin_condition)a->join_cond);\n\n free(a);\n}\n\n// free a join_condition node\nvoid free_join_condition(pjoin_condition a)\n{\n if(a->l != NULL)\n\t free_ast(a->l);\n free(a);\n}\n\n// free a index list\nvoid free_index_list(pindex_list a)\n{\n if(a->next != NULL)\n\t free_index_list(a->next);\n free(a);\n}\n\n// free a select statement\nvoid free_select_stmt(pselect_stmt a)\n{\n if(a->sel_expr_list != NULL)\n {\n\t free_select_expr_list(a->sel_expr_list);\n }\n if(a->table_refs != NULL)\n {\n\t free_table_references(a->table_refs);\n }\n if(a->opt_where_expr != NULL)\n {\n\t free_ast(a->opt_where_expr);\n }\n if(a->gpb_list != NULL)\n {\n\t free_groupby_list(a->gpb_list);\n }\n if(a->opt_having_expr != NULL)\n {\n\t free_ast(a->opt_having_expr);\n }\n if(a->odb_list != NULL)\n {\n\t free_groupby_list(a->odb_list);\n }\n\n free(a);\n}\n\n// free a function \nvoid free_fncall(pfncall a)\n{\n if(a->l != NULL)\n\t free_ast(a->l);\n free(a);\n}\n\n// free a user define function\nvoid free_ufncall(pufncall a)\n{\n if(a->l != NULL)\n\t free_ast(a->l);\n free(a);\n}\n\n// output a [... is null] expression\nvoid emit_null(past pa, const char* app)\n{\n emit_expr(pa->l);\n printf(\" is %s null \",app);\n}\n\n// output a [... is true] expression\nvoid emit_bool(past pa, const char* app)\n{\n emit_expr(pa->l);\n printf(\" is %s true\",app);\n}\n\n// output a [... in ...] expression\nvoid emit_in(past pa, const char* app)\n{\n emit_expr(pa->l);\n printf(\" %s in (\",app);\n emit_expr(pa->r);\n printf(\")\");\n}\n\n// output a [... like ...] expression\nvoid emit_like(past pa, const char* app)\n{\n emit_expr(pa->l);\n printf(\" %s like \",app);\n emit_expr(pa->r);\n}\n\n// output a [... COMP ...] expression\nvoid emit_compare(past pa, const char* comp)\n{\n emit_expr(pa->l);\n printf(\" %s \",comp);\n if(pa->r->node_type == 'm')\n {\n printf(\" ( \");\n emit_select_stmt((pselect_stmt)pa->r);\n printf(\" ) \");\n }\n else\n emit_expr(pa->r);\n}\n\n// output a function\nvoid emit_fncall(pfncall pa)\n{\n printf(\" count(\");\n\n if(pa->l == NULL)\n {\n\t printf(\"*\");\n }\n else\n\t emit_expr(pa->l);\n printf(\") \");\n}\n\n// output a user define function\nvoid emit_ufncall(pufncall pa)\n{\n printf(\" %s(\",pa->s->s->name);\n if(pa->l == NULL)\n {\n\t printf(\"*\");\n }\n else\n\t emit_expr(pa->l);\n printf(\") \");\n}\n\n// output a expression\nvoid emit_expr(past pa)\n{\n switch(pa->node_type)\n {\n case 'I':\n {\n\t printf(\" %d \",((pintval)pa)->number);\n\t break;\n }\n case 'L':\n {\n\t printf(\" %.2f \",((pfloatval)pa)->number);\n\t break;\n }\n case 'S':\n {\n\t printf(\" %s \",((pstrval)pa)->str);\n\t break;\n }\n case 'N':\n {\n\t printf(\"%s\",((psymref)pa)->s->name);\n\t break;\n }\n case 'F':\n {\n\t // emit function\n\t emit_fncall((pfncall)pa);\n\t break;\n }\n case 'C':\n {\n\t // emit user call\n\t emit_ufncall((pufncall)pa);\n\t break;\n }\n case '+':\n {\n\t emit_expr(pa->l);\n\t printf(\"+\");\n\t emit_expr(pa->r);\n\t break;\n }\n case '-':\n {\n\t emit_expr(pa->l);\n\t printf(\"-\");\n\t emit_expr(pa->r);\n\t break;\n }\n case '*':\n {\n\t emit_expr(pa->l);\n\t printf(\"*\");\n\t emit_expr(pa->r);\n\t break;\n }\n case '/':\n {\n\t emit_expr(pa->l);\n\t printf(\"/\");\n\t emit_expr(pa->r);\n\t break;\n }\n case '%':\n {\n\t emit_expr(pa->l);\n\t printf(\"%%\");\n\t emit_expr(pa->r);\n\t break;\n }\n case 'D':\n {\n\t if(!only_attr_cmd){\n\t emit_expr(pa->l);\n\t printf(\".\");\n\t }\n\t emit_expr(pa->r);\n\t break;\n }\n case 'M':\n {\n\t printf(\" -\");\n\t emit_expr(pa->l);\n\t break;\n }\n case 'A':\n {\n\t emit_expr(pa->l);\n\t printf(\" and \");\n\t emit_expr(pa->r);\n\t break;\n }\n case 'O':\n {\n\t emit_expr(pa->l);\n\t printf(\" or \");\n\t emit_expr(pa->r);\n\t break;\n }\n case 'T':\n {\n\t // need to classify and emit separatively.\n\t switch(pa->l->node_type)\n\t {\n\t case 'U':\n\t emit_null(pa->l,\"not\");\n\t break;\n\t case 'B':\n\t emit_bool(pa->l,\"not\");\n\t break;\n\t case 'Q':\n\t emit_in(pa->l,\"not\");\n\t break;\n\t case 'K':\n\t emit_like(pa->l,\"not\");\n\t break;\n\t default:\n\t printf(\" not \");\n\t emit_expr(pa->l);\n\t break;\n\t }\n\t \n \t break;\n }\n case '1':\n {\n\t emit_compare(pa,\"<\");\t \n\t break;\n }\n case '2':\n {\n\t emit_compare(pa,\">\");\n\t break;\n }\n case '3':\n {\n\t emit_compare(pa,\"!=\");\n\t break;\n }\n case '4':\n {\n\t emit_compare(pa,\"=\");\n\t break;\n }\n case '5':\n {\n\t emit_compare(pa,\"<=\");\n\t break;\n }\n case '6':\n {\n\t emit_compare(pa,\">=\");\n\t break;\n }\n case 'U':\n {\n\t emit_null(pa,\"\");\n\t break;\n }\n case 'B':\n {\n\t emit_bool(pa,\"\");\n\t break;\n }\n case 'Q':\n {\n\t emit_in(pa,\"\");\n\t break;\n }\n case 'K':\n {\n\t emit_like(pa,\"\");\n\t break;\n }\n case 'E':\n {\n\t printf(\" exists (\");\n\t emit_select_stmt((pselect_stmt)pa->l);\n\t printf(\") \");\n\t break;\n }\n case 'W':\n {\n\t emit_expr(pa->l);\n\t printf(\" between \");\n\t emit_expr(pa->r);\n\t printf(\" and \");\n\t emit_expr(pa->rr);\n\t break;\n }\n case 'v':\n {\n\t emit_expr(pa->l);\n\t if(pa->r != NULL)\n\t {\n\t printf(\",\");\n\t emit_expr(pa->r);\n\t }\n\t break;\n }\n case 's':\n {\n\t emit_select_expr_list((pselect_expr_list)pa);\n\t break;\n }\n case 'g':\n {\n\t emit_groupby_list((pgroupby_list)pa);\n\t break;\n }\n case 'r':\n {\n\t emit_table_references((ptable_references)pa);\n\t break;\n }\n case 'f':\n {\n\t emit_table_factor((ptable_factor)pa);\n\t break;\n }\n case 't':\n {\n\t emit_join_table((pjoin_table)pa);\n\t break;\n }\n case 'c':\n {\n\t emit_join_condition((pjoin_condition)pa);\n\t break;\n }\n case 'i':\n {\n\t emit_index_list((pindex_list)pa);\n\t break;\n }\n case 'm':\n {\n\t emit_select_stmt((pselect_stmt)pa);\n\t break;\n }\n }\n}\n\n// output a select expression list\nvoid emit_select_expr_list(pselect_expr_list psel_l)\n{\n if(psel_l == NULL)\n {\n\t printf(\" * \");\n\t return;\n }\n\n if(psel_l->next != NULL)\n {\n\t emit_select_expr_list(psel_l->next);\n\t printf(\", \");\n }\n \n emit_expr(psel_l->expr);\n if(psel_l->as_alias != NULL)\n {\n\t printf(\" as \");\n\t printf(\" %s \", psel_l->as_alias->s->name);\n }\n}\n\n// output a table factor node\nvoid emit_table_factor(ptable_factor ptf)\n{\n\n switch(ptf->factor_type)\n {\n case 1:\n {\n\t printf(\" %s \",ptf->s->s->name);\n\t if(ptf->s2 != NULL)\n\t {\n\t printf(\" as %s \",ptf->s2->s->name);\n\t }\n\t if(ptf->l != NULL)\n\t {\n\t printf(\" !!! here is an index_hint !!! \");\n\t }\n\t break;\n }\n case 2:\n {\n\t printf(\" %s.%s \",ptf->s->s->name,ptf->s2->s->name);\n\t if(ptf->s3 != NULL)\n\t {\n\t printf(\" as %s \",ptf->s3->s->name);\n\t }\n\t if(ptf->l != NULL)\n\t {\n\t printf(\" !!! here is an index_hint !!! \");\n\t }\n\t break;\n }\n case 3:\n {\n\t printf(\" (\");\n\t emit_select_stmt((pselect_stmt)ptf->l);\n\t if(ptf->s != NULL)\n\t {\n\t printf(\" as %s \",ptf->s->s->name);\n\t }\n\t printf(\") \");\n\t break;\n }\n case 4:\n {\n\t printf(\" (\");\n\t emit_table_references((ptable_references)ptf->l);\n\t printf(\") \");\n\t break;\n }\n }\n}\n\n// output a index list\nvoid emit_index_list(pindex_list pil)\n{\n printf(\" %s \",pil->s->s->name);\n if(pil->next != NULL)\n {\n\t printf(\",\");\n\t emit_index_list(pil->next);\n }\n}\n\n// output a join condition node\nvoid emit_join_condition(pjoin_condition pjc)\n{\n if(pjc->con_type == 1)\n {\n\t printf(\" on \");\n\t emit_expr(pjc->l);\n }\n else if(pjc->con_type == 2)\n {\n\t printf(\" using {\");\n\t emit_index_list((pindex_list)pjc->l);\n\t printf(\") \");\n }\n}\n\n// output a join table node base form,\n// for the specific form to call it.\nvoid emit_join_table_base(pjoin_table pjt, const char* app)\n{\n if(pjt->table_ref->node_type == 'f')\n {\n\t emit_table_factor((ptable_factor)pjt->table_ref);\n }\n else if(pjt->table_ref->node_type == 't')\n {\n\t emit_join_table((pjoin_table)pjt->table_ref);\n }\n printf(\" %s \",app);\n \n if(pjt->table_fct != NULL)\n {\n\t emit_table_factor((ptable_factor)pjt->table_fct);\n }\n \n if(pjt->join_cond != NULL)\n {\n\t emit_join_condition((pjoin_condition)pjt->join_cond);\n }\n}\n\n// output a join table node\nvoid emit_join_table(pjoin_table pjt)\n{\n switch(pjt->join_type)\n {\n case 64:\n {\n\t // join\t \n\t emit_join_table_base(pjt,\"join\");\n \t break;\n }\n case 65:\n {\n\t // inner join\n\t emit_join_table_base(pjt,\"inner join\");\t \t \n\t break;\n }\n case 66:\n {\n\t // cross join\n\t emit_join_table_base(pjt,\"cross join\");\n\t break;\n }\n case 128:\n {\n\t // straight join\n\t emit_join_table_base(pjt,\"straight join\");\n\t break;\n }\n case 193:\n {\n\t // left join\n\t emit_join_table_base(pjt,\"left join\");\n\t break;\n }\n case 197:\n {\n\t // left outer join\n\t emit_join_table_base(pjt,\"left outer join\");\t \n\t break;\n }\n case 194:\n {\n\t // right join\n\t emit_join_table_base(pjt,\"right join\");\n\t break;\n }\n case 198:\n {\n\t // right outer join\n\t emit_join_table_base(pjt,\"right outer join\");\n\t break;\n }\n case 257:\n {\n\t // natural left join\n\t emit_join_table_base(pjt,\"natural left join\");\t \n\t break;\n }\n case 261:\n {\n\t //natural left outer join\n\t emit_join_table_base(pjt,\"natural left outer join\");\n\t break;\n }\n case 258:\n {\n\t // natural right join\n\t emit_join_table_base(pjt,\"natural right join\");\n\t break;\n }\n case 262:\n {\n\t // natural right outer join\n\t emit_join_table_base(pjt,\"natural right outer join\");\n\t break;\n }\n case 256:\n {\n\t // natural join\n\t emit_join_table_base(pjt,\"natural join\");\n\t break;\n }\n }\n}\n\n// output a table reference list\nvoid emit_table_references(ptable_references ptr)\n{\n if(ptr->ref_type == 1)\n {\n\t // emit table_factor\n\t emit_table_factor((ptable_factor)ptr->table_ref);\n }\n else\n {\n\t // emit join_table\n\t emit_join_table((pjoin_table)ptr->table_ref);\n }\n\n if(ptr->next != NULL)\n {\n\t printf(\",\");\n\t emit_table_references(ptr->next);\n }\n \n}\n\n// output a groupby list\nvoid emit_groupby_list(pgroupby_list pgpb_l)\n{\n emit_expr(pgpb_l->expr);\n switch(pgpb_l->opt_asc_desc)\n {\n case 0:\n\t break;\n case 1:\n\t printf(\" desc \");\n\t break;\n default:\n\t break;\n }\n \n if(pgpb_l->next != NULL)\n {\n\t printf(\",\");\n\t emit_groupby_list(pgpb_l->next); \n }\n}\n\n// output a select statement\nvoid emit_select_stmt(pselect_stmt stmt)\n{\n if(stmt == NULL)\n\t return;\n printf(\"select \");\n switch(stmt->sel_type)\n {\n case 1:\n\t printf(\" all \");\n\t break;\n case 2:\n\t printf(\" distinct \");\n\t break;\n case 3:\n\t printf(\" distinct all \");\n\t break;\n case 4:\n\t printf(\" distinctrow \");\n\t break;\n case 5:\n\t printf(\" distinctrow all \");\n\t break;\n case 6:\n\t printf(\" distinct distictrow \");\n\t break;\n case 7:\n\t printf(\" distinct distinctrow all \");\n\t break;\n default:\n\t break;\n\t \n }\n \n emit_select_expr_list(stmt->sel_expr_list);\n if(stmt->table_refs != NULL)\n {\n\t printf(\" from \");\n\t emit_table_references(stmt->table_refs);\n }\n\n if(stmt->opt_where_expr != NULL)\n {\n\t printf(\" where \");\n\t emit_expr(stmt->opt_where_expr);\n }\n if(stmt->gpb_list != NULL)\n {\n\t printf(\" group by \");\n\t emit_groupby_list(stmt->gpb_list);\n }\n if(stmt->opt_having_expr != NULL)\n {\n\t printf(\" having \");\n\t emit_expr(stmt->opt_having_expr);\n }\n \n if(stmt->odb_list != NULL)\n {\n\t printf(\" order by \");\n\t emit_groupby_list(stmt->odb_list); \n }\n}\n\n// table node build according to the create schema\ntablelist newtable(char* name)\n{\n tablelist ntable = (tablelist)malloc(sizeof(table));\n ntable->name = strdup(name);\n ntable->keys = NULL;\n ntable->attrs = NULL;\n ntable->next = NULL;\n\n return ntable;\n}\n\n// attribute node build according to the create schema\nattrlist newattr(char* name)\n{\n attrlist pattr = (attrlist)malloc(sizeof(attr));\n\n pattr->name = strdup(name);\n pattr->next = NULL;\n\n return pattr;\n}\n\n// attribute list build according to the create schema\nattrlist build_attrs(FILE* fp, int n)\n{\n int i;\n char name[BUFSIZE];\n attrlist al_head,acur,p;\n\n al_head = newattr(\"\");\n acur = al_head;\n\n memset(name,0,BUFSIZE);\n for(i = 0; i < n; i++)\n {\n\t fscanf(fp,\"%s\",name);\n\t p = newattr(name);\n\t acur->next = p;\n\t acur = p;\n }\n\n return al_head;\n}\n\n// build a table and its attribute list according to the schema\ntablelist build_table(FILE* fp)\n{\n tablelist ntable;\n int nk,na;\n char name[BUFSIZE];\n attrlist keys,attrs;\n\n memset(name,0,BUFSIZE);\n fscanf(fp,\"%s\",name);\n fscanf(fp,\"%d %d\",&nk,&na);\n\n keys = build_attrs(fp,nk);\n attrs = build_attrs(fp,na);\n ntable = newtable(name);\n ntable->keys = keys;\n ntable->attrs = attrs;\n\n return ntable;\n}\n\n// output the tables built according to the schema\nvoid print_tables(tablelist head)\n{\n tablelist p;\n attrlist pa;\n\n p = head->next;\n while(p != NULL)\n {\n\t printf(\"<t> \");\n\t printf(\"%s\\n\",p->name);\n\t pa = p->keys->next;\n\t printf(\"keys:\\n\");\n\t while(pa != NULL)\n\t {\n\t printf(\"%s\\n\",pa->name);\n\t pa = pa->next;\n\t }\n\n\t pa = p->attrs->next;\n\t printf(\"attrs:\\n\");\n\t while(pa != NULL)\n\t {\n\t printf(\"%s\\n\",pa->name);\n\t pa = pa->next;\n\t }\n\n\t printf(\"\\n\\n\");\n\t p = p->next;\n }\n}\n\n// build all the table with a list according to the schema\ntablelist build_tables(const char* filename)\n{\n int nt,i;\n FILE* fp = NULL;\n tablelist tl_head,tcur,p;\n \n fp = fopen(filename,\"r\");\n if(fp == NULL)\n {\n\t fprintf(stderr,\"can't open file %s\\n\",filename);\n\t exit(1);\n }\n\n fscanf(fp,\"%d\",&nt);\n \n tl_head = newtable(\"\");\n tcur = tl_head;\n \n for(i = 0; i < nt; i++)\n {\n\t // building each table\n\t p = build_table(fp);\n\t tcur->next = p;\n\t tcur = p;\n }\n \n if(fclose(fp) != 0)\n {\n\t fprintf(stderr,\"Error in closing file %s\\n\",filename);\n }\n\n return tl_head;\n}\n\n// free the attribute \nvoid free_attrs(attrlist head)\n{\n attrlist pa = head;\n\n if(pa->next != NULL)\n {\n\t free_attrs(pa->next);\n }\n\n free(pa->name);\n free(pa);\n}\n\n// free the table list\nvoid free_tables(tablelist head)\n{\n tablelist p;\n \n p = head;\n if(p->next != NULL)\n {\n\t free_tables(p->next);\n }\n\n free(p->name);\n if(p->keys != NULL)\n free_attrs(p->keys);\n if(p->attrs != NULL)\n free_attrs(p->attrs);\n free(p);\n}\n\n// build a translation table from the table name to its alias name\naliaslist build_trans_table(ptable_references tb_refs)\n{\n aliaslist tr_table = (aliaslist)malloc(sizeof(struct aliasnode));\n aliaslist cur,pt;\n ptable_references p = tb_refs;\n ptable_factor q;\n\n tr_table->name = strdup(\"\");\n tr_table->alias = strdup(\"\");\n tr_table->next = NULL;\n cur = tr_table;\n\n while(p != NULL)\n {\n\t if(p->ref_type == 1)\n\t {\n\t q = (ptable_factor)(p->table_ref);\n\t if(q->factor_type == 1 && q->s2 != NULL)\n\t {\n\t\t pt = (aliaslist)malloc(sizeof(struct aliasnode));\n\t\t pt->next = NULL;\n\t\t pt->name = strdup(q->s->s->name);\n\t\t pt->alias = strdup(q->s2->s->name);\n\n\t\t cur->next = pt;\n\t\t cur = cur->next;\n\t }\n\t }\n\n\t p = p->next;\n }\n\n return tr_table;\n}\n\n// free the table name to alias name translation table\nvoid free_trans_table(aliaslist al)\n{\n aliaslist p = al;\n\n if(p->next != NULL)\n {\n\t free_trans_table(p->next);\n }\n\n free(p->name);\n free(p->alias);\n free(p);\n}\n\n/*\n * translate alias-table-name --> table-name\n */\nchar* translate(char* alias)\n{\n aliaslist p;\n p = trans_table->next;\n while(p != NULL)\n {\n\t if(strcmp(alias,p->alias) == 0)\n\t return p->name;\n\t \n\t p = p->next;\n }\n\n return alias;\n}\n\n/*\n * anti-translate table-name --> alias-table-name\n */\nchar* anti_translate(char* tbn)\n{\n aliaslist p;\n p = trans_table->next;\n while(p != NULL)\n {\n\t if(strcmp(tbn,p->name) == 0)\n\t return p->alias;\n\n\t p = p->next;\n }\n\n return tbn;\n}\n\n// check if the colname is the tbname is key attribute\nint is_key(char* tbname,char* colname)\n{\n tablelist p;\n attrlist pa;\n char* tbn = translate(tbname);\n\n p = all_tables->next;\n while(p != NULL)\n {\n\t if(strcmp(tbn,p->name) == 0)\n\t {\n\t pa = p->keys->next;\n\t while(pa != NULL)\n\t {\n\t\t if(strcmp(colname,pa->name) == 0)\n\t\t {\n\t\t\t return 1;\n\t\t }\n\t\t pa = pa->next;\n\t }\n\t }\n\t \n\t p = p->next;\n }\n\n return 0;\n}\n\n// get the key attribute of the table name\nchar* get_key(const char* tbn)\n{\n tablelist p = all_tables->next;\n attrlist pk;\n \n while(p != NULL)\n {\n\t if(strcmp(p->name,tbn) == 0)\n\t {\n\t pk = p->keys->next;\n\t if(pk != NULL)\n\t\t return pk->name;\n\t }\n\n\t p = p->next;\n }\n\n return NULL;\n}\n\n// classify the KJ, NKJ, SC nodes in the abstract syntax tree\nvoid classify(past expr)\n{\n switch(expr->node_type)\n {\n case 'A':\n {\n\t signs[signs_len++] = 'a';\n\t classify(expr->l);\n\t classify(expr->r);\n\t break;\n }\n case 'O':\n {\n\t signs[signs_len++] = 'o';\n\t classify(expr->l);\n\t classify(expr->r);\n\t break;\n }\n case '4':\n {\n\t if(expr->l->node_type == 'D' && expr->r->node_type == 'D')\n\t {\n\t if(is_key(((psymref)expr->l->l)->s->name,((psymref)expr->l->r)->s->name) && is_key(((psymref)expr->r->l)->s->name,((psymref)expr->r->r)->s->name))\n\t {\n\t\t insert_kj_expr(expr);\n\t }\n\t else\n\t {\n\t\t insert_nkj_expr(expr);\n\t }\n\n\t signs[--signs_len] = '\\0';\n\t }\n\t else\n\t {\n\t insert_sc_expr(expr);\n\t }\n\t break;\n }\n default:\n {\n\t insert_sc_expr(expr);\n }\n }\n}\n\n/*\n * initialize the 3 expr queues.\n */\nvoid init_expr_lists()\n{\n kj_head = (exprlist)malloc(sizeof(struct exprlistnode));\n kj_head->expr = NULL;\n kj_head->next = NULL;\n kj_tail = kj_head;\n\n nkj_head = (exprlist)malloc(sizeof(struct exprlistnode));\n nkj_head->expr = NULL;\n nkj_head->next = NULL;\n nkj_tail = nkj_head;\n\n sc_head = (exprlist)malloc(sizeof(struct exprlistnode));\n sc_head->expr = NULL;\n sc_head->next = NULL;\n sc_tail = sc_head;\n\n memset(signs,0,BUFSIZE);\n signs_len = 0;\n}\n\n/*\n * free expr queue\n */\nvoid free_expr_list(exprlist el)\n{\n if(el->next != NULL)\n\t free_expr_list(el->next);\n\n free(el);\n}\n\n// insert a expression item to the KJ expr list\nvoid insert_kj_expr(past expr)\n{\n exprlist cur = (exprlist)malloc(sizeof(struct exprlistnode));\n cur->expr = expr;\n cur->next = NULL;\n\n kj_tail->next = cur;\n kj_tail = cur;\n}\n\n// insert a expression item to the NKJ expr list\nvoid insert_nkj_expr(past expr)\n{\n exprlist cur = (exprlist)malloc(sizeof(struct exprlistnode));\n cur->expr = expr;\n cur->next = NULL;\n\n nkj_tail->next = cur;\n nkj_tail = cur;\n}\n\n// insert a expression item to the SC expr list\nvoid insert_sc_expr(past expr)\n{\n exprlist cur = (exprlist)malloc(sizeof(struct exprlistnode));\n cur->expr = expr;\n cur->next = NULL;\n\n sc_tail->next = cur;\n sc_tail = cur;\n}\n\n// output the KJ expr list\nvoid emit_kj_exprs()\n{\n exprlist p;\n\n printf(\"KJ:\\n\");\n p = kj_head->next;\n while(p != NULL)\n {\n\t emit_expr(p->expr);\n\t printf(\" \");\n\t p = p->next;\n\n\t if(p != NULL)\n\t printf(\" and \");\n }\n printf(\"\\n\");\n}\n\n// output the NKJ expr list\nvoid emit_nkj_exprs()\n{\n exprlist p;\n \n printf(\"NKJ:\\n\");\n p = nkj_head->next;\n while(p != NULL)\n {\n\t emit_expr(p->expr);\n\t printf(\" \");\n\t p = p->next;\n\n\t if(p != NULL)\n\t printf(\" and \");\n }\n printf(\"\\n\");\n\n}\n\n// output the SC expr list\nvoid emit_sc_exprs()\n{\n exprlist p;\n int i = 0;\n \n printf(\"SC:\\n\");\n p = sc_head->next;\n while(p != NULL)\n {\n\t emit_expr(p->expr);\n\n\t if(i < signs_len )\n\t {\n\t switch(signs[i])\n\t {\n\t case 'a':\n\t\t printf(\" and \");\n\t\t break;\n\t case 'o':\n\t\t printf(\" or \");\n\t\t break;\n\t default:\n\t\t break;\n\t }\n\t }\n\t \n\t p = p->next;\n\t i++;\n }\n \n printf(\"\\n\");\n}\n\n// output the inversed SC expr\nvoid emit_nsc_expr(past p)\n{\n switch(p->node_type)\n {\n case '1':\n {\n\t // for <\n\t emit_expr(p->l);\n\t printf(\" >= \");\n\t emit_expr(p->r);\n\t break;\n }\n case '2':\n {\n\t // for >\n\t emit_expr(p->l);\n\t printf(\" <= \");\n\t emit_expr(p->r);\n\t break;\n }\n case '3':\n {\n\t // for !=\n\t emit_expr(p->l);\n\t printf(\" = \");\n\t emit_expr(p->r);\n\t break;\n }\n case '4':\n {\n\t // for =\n\t emit_expr(p->l);\n\t printf(\" != \");\n\t emit_expr(p->r);\n\t break;\n }\n case '5':\n {\n\t // for <=\n\t emit_expr(p->l);\n\t printf(\" > \");\n\t emit_expr(p->r);\n\t break;\n }\n case '6':\n {\n\t // for >=\n\t emit_expr(p->l);\n\t printf(\" < \");\n\t emit_expr(p->r);\n\t break;\n }\n case 'T':\n {\n\t emit_expr(p->l);\n\t break;\n }\n case 'W':\n {\n\t emit_expr(p->l);\n\t printf(\" < \");\n\t emit_expr(p->r);\n\t printf(\" and \");\n\t emit_expr(p->l);\n\t printf(\" > \");\n\t emit_expr(p->rr);\n\t break;\n }\n case 'U': // for null\n case 'B': // for bool\n case 'E': // for exists\n case 'K': // for like\n case 'Q': // for in\n {\n\t past temp = newast('T',p,NULL,NULL);\n\t emit_expr(temp);\n\t free(temp);\n\t break;\n }\n default:\n {\n\t emit_expr(p);\n\t break;\n }\n }\n}\n\n// output the inversed SC expr list\nvoid emit_nsc_exprs()\n{\n //\n int i = 0;\n\n exprlist p = sc_head->next;\n while(p != NULL)\n {\n\t emit_nsc_expr(p->expr);\n\t if(i < signs_len )\n\t {\n\t switch(signs[i])\n\t {\n\t case 'a':\n\t\t printf(\" or \");\n\t\t break;\n\t case 'o':\n\t\t printf(\" and \");\n\t\t break;\n\t default:\n\t\t break;\n\t }\n\t }\n\t \n\t p = p->next;\n\t i++;\n }\n}\n\n\n/*\n * get a new and initialized join_graph_node\n */\npjoin_graph_node newjoin_graph_node(const char* src_t, const char* src_a, const char* dist_t, const char* dist_a)\n{\n pjoin_graph_node pjn = (pjoin_graph_node)malloc(sizeof(struct join_graph_node));\n pjn->dist_t = strdup(dist_t);\n pjn->dist_a = strdup(dist_a);\n pjn->src_t = strdup(src_t);\n pjn->src_a = strdup(src_a);\n pjn->next = NULL;\n\n return pjn;\n}\n\n/*\n * get a new and initialized join_graph_nodelist node\n */\npjoin_graph_nodelist newjoin_graph_nodelist()\n{\n pjoin_graph_nodelist pjnl = (pjoin_graph_nodelist)malloc(sizeof(struct join_graph_nodelist_node));\n pjnl->tb_name = NULL;\n pjnl->key_name = NULL;\n pjnl->in_degree = 0;\n pjnl->node = NULL;\n pjnl->next = NULL;\n\n return pjnl;\n}\n\n// build a new left outer join queue node and return its addr\nloj_queue newloj_queue_node()\n{\n loj_queue p = (loj_queue)malloc(sizeof(struct loj_queue_node));\n p->node = NULL;\n p->next = NULL;\n\n return p;\n}\n\n/*\n * searches whether a table entry has been inserted into the join_graph_nodelist,\n * if so, do nothing and return\n * else, insert an new entry in the nodelist.\n */\nvoid insert_join_graph_nodelist(pjoin_graph_nodelist head,const char* tbn)\n{\n char* keyn;\n pjoin_graph_nodelist f = head;\n pjoin_graph_nodelist p = head->next;\n\n while(p != NULL)\n {\n\t if(strcmp(p->tb_name,tbn) == 0)\n\t return;\n\n\t f = p;\n\t p = p->next;\n }\n\n p = newjoin_graph_nodelist();\n p->tb_name = strdup(tbn);\n keyn = get_key(tbn);\n p->key_name = keyn;\n\n f->next = p;\n}\n\n// insert into the join graph with src_t,src_a --> dist_t.dist_a join condition\nvoid insert_join_graph_node(pjoin_graph_nodelist jghead,const char* src_t,const char* src_a, const char* dist_t, const char* dist_a)\n{\n pjoin_graph_nodelist p = jghead->next;\n pjoin_graph_node f,q;\n while(p != NULL)\n {\n\t if(strcmp(p->tb_name,src_t) == 0)\n\t {\n\t q = p->node;\n\t if(q == NULL)\n\t {\n\t\t q = newjoin_graph_node(src_t,src_a,dist_t,dist_a);\n\t\t p->node = q;\n\t }\n\t else\n\t {\n\t\t do{\n\t\t\t f = q;\n\t\t\t q = q->next;\n\t\t }while(q != NULL);\n\n\t\t q = newjoin_graph_node(src_t,src_a,dist_t,dist_a);\n\t\t f->next = q;\n\t }\n\n\t break;\n\t }\n\t \n\t p = p->next;\n }\n}\n\n// increase the table name's references number by 1\nvoid increase_indegree(pjoin_graph_nodelist jghead,const char* tbn)\n{\n pjoin_graph_nodelist p = jghead->next;\n while(p != NULL)\n {\n\t if(strcmp(p->tb_name,tbn) == 0)\n\t {\n\t p->in_degree++;\n\t break;\n\t }\n\t \n\t p = p->next;\n }\n}\n\n// insert into the join graph with relation of nonkey to key join condition\nvoid insert_graph_item(pjoin_graph_nodelist jghead,past key, past nonkey)\n{\n char* dist_t = ((psymref)key->l)->s->name;\n char* dist_a = ((psymref)key->r)->s->name;\n char* src_t = ((psymref)nonkey->l)->s->name;\n char* src_a = ((psymref)nonkey->r)->s->name;\n\n dist_t = translate(dist_t);\n src_t = translate(src_t);\n\n insert_join_graph_nodelist(jghead,src_t);\n insert_join_graph_nodelist(jghead,dist_t);\n\n insert_join_graph_node(jghead,src_t,src_a,dist_t,dist_a);\n increase_indegree(jghead,dist_t);\n}\n\n/*\n * build up the join graph\n */\npjoin_graph_nodelist build_join_graph()\n{\n //\n past key, nonkey;\n pjoin_graph_nodelist jghead = newjoin_graph_nodelist();\n exprlist ep = nkj_head->next;\n past p;\n\n while(ep != NULL)\n {\n\t p = ep->expr;\n\t if(is_key(((psymref)p->l->l)->s->name,((psymref)p->l->r)->s->name))\n\t {\n\t key = p->l;\n\t nonkey = p->r;\n\t }\n\t else\n\t {\n\t key = p->r;\n\t nonkey = p->l;\n\t }\n\n\t insert_graph_item(jghead,key,nonkey);\n\t ep = ep->next;\n }\n\n return jghead;\n}\n\n// free a join graph reference node\nvoid free_join_graph_nodes(pjoin_graph_node p)\n{\n if(p->next != NULL)\n {\n\t free(p->next);\n }\n\n free(p->src_t);\n free(p->src_a);\n free(p->dist_t);\n free(p->dist_a);\n free(p);\n}\n\n// free the join graph\nvoid free_join_graph()\n{\n pjoin_graph_nodelist f = jg_head;\n pjoin_graph_nodelist p = jg_head->next;\n pjoin_graph_node q;\n \n free(f);\n while(p != NULL)\n {\n\t // not done!\n\t q = p->node;\n\t if(q != NULL)\n\t {\n\t free_join_graph_nodes(q);\n\t }\n\t \n\t f = p;\n\t p = p->next;\n\n\t free(f->tb_name);\n\t free(f->key_name);\n\t free(f);\n }\n}\n\n// output the join graph\nvoid emit_join_graph()\n{\n pjoin_graph_nodelist p = jg_head->next;\n pjoin_graph_node q;\n \n while(p != NULL)\n {\n\t printf(\"%s|%s|%d \",p->tb_name,p->key_name,p->in_degree);\n\t q = p->node;\n\t if(q != NULL)\n\t {\n\t printf(\"=> \");\n\t do{\n\t\t printf(\"(%s|%s->%s|%s)\",q->src_t,q->src_a,q->dist_t,q->dist_a);\n\t\t printf(\" --> \");\n\t\t q = q->next;\n\t }while(q != NULL);\n\t printf(\"nil\\n\");\n\t }\n\t else\n\t printf(\"\\n\");\n\t \n\t p = p->next;\n }\n}\n\n/*\n * check the join graph satisfy our defination\n * it must be a tree graph,means the ) <= in_degree <= 1 \n * there is only 1 node with in_degree 0, others are all with in_degree 1\n */\nint check_join_graph()\n{\n int nz = 0; // the number of nodes with in_degree 0\n int no = 0; // the number of nodes with in_degree over 1\n\n pjoin_graph_nodelist p = jg_head->next;\n\n while(p != NULL)\n {\n\t if(p->in_degree == 0)\n\t nz++;\n\t else if(p->in_degree > 1)\n\t no++;\n\n\t p = p->next;\n }\n\n if((nz != 1) || (no > 0))\n\t return 0;\n\n return 1;\n}\n\n// get the root table of the join graph\npjoin_graph_nodelist get_join_graph_root()\n{\n pjoin_graph_nodelist p = jg_head->next;\n while(p != NULL)\n {\n\t if(p->in_degree == 0)\n\t return p;\n\t \n\t p = p->next;\n }\n\n return NULL;\n}\n\n// get the join graph reference list with table name dist_t\npjoin_graph_node get_join_graph_nodes(const char* dist_t)\n{\n pjoin_graph_nodelist p = jg_head->next;\n while(p != NULL)\n {\n\t if(strcmp(p->tb_name,dist_t) == 0)\n\t {\n\t return p->node;\n\t }\n\n\t p = p->next;\n }\n\n return NULL;\n}\n\n// check if the root table's key attribute is in an expression\nint is_key_in_expr(past expr,const char* key)\n{\n switch(expr->node_type)\n {\n case 'N':\n\t return strcmp(((psymref)expr)->s->name,key) == 0;\n case 'D':\n\t return strcmp(((psymref)expr->r)->s->name,key) == 0;\n case 'M':\n\t return is_key_in_expr(expr->l,key);\n case '+':\n case '-':\n case '*':\n case '/':\n case '%':\n\t return is_key_in_expr(expr->l,key) || is_key_in_expr(expr->r,key);\n default:\n\t return 0;\n }\n}\n\n// check if the root table's key attribute is in the select expression list\nint is_key_in(pselect_expr_list sel_l,const char* key)\n{\n int is = 0;\n pselect_expr_list p;\n\n if(sel_l == NULL)\n\t return 0;\n\n if(is_key_in_expr(sel_l->expr,key))\n\t return 1;\n \n p = sel_l->next;\n while(p != NULL)\n {\n\t if(is_key_in(p,key))\n\t return 1;\n\t \n\t p = p->next;\n }\n\n return 0;\n}\n\n// output the left outer join queue.\nvoid emit_loj_queue(pjoin_graph_nodelist root)\n{\n loj_queue head;\n loj_queue tail;\n loj_queue tmpq;\n loj_queue tmp_loc;\n loj_queue tmp_free;\n char* aliasns; // alias name of src table\n char* aliasnd; // alias name or dist table\n pjoin_graph_nodelist pnl;\n pjoin_graph_node pn;\n\n printf(\" \");\n head = newloj_queue_node();\n tail = head;\n\n pn = root->node;\n while(pn != NULL)\n {\n\t tmp_loc = newloj_queue_node();\n\t tmp_loc->node = pn;\n\t tail->next = tmp_loc;\n\t tail = tmp_loc;\n\t \n\t pn = pn->next;\n }\n\n while(head != tail)\n {\n\t tmpq = head->next;\n\t aliasns = anti_translate(tmpq->node->src_t);\n\t aliasnd = anti_translate(tmpq->node->dist_t);\n\t if(aliasns == tmpq->node->src_t)\n\t {\n\t // no alias table-name\n\t printf(\"left outer join %s on %s.%s=%s.%s\",aliasnd,aliasns,tmpq->node->src_a,aliasnd,tmpq->node->dist_a);\n\t }\n\t else\n\t {\n\t printf(\"left outer join %s %s on %s.%s=%s.%s\",tmpq->node->dist_t,aliasnd,aliasns,tmpq->node->src_a,aliasnd,tmpq->node->dist_a);\n\t }\n\n\t pn = get_join_graph_nodes(tmpq->node->dist_t);\n\t while(pn != NULL)\n\t {\n\t tmp_loc = newloj_queue_node();\n\t tmp_loc->node = pn;\n\t tail->next = tmp_loc;\n\t tail = tmp_loc;\n\t \n\t pn = pn->next;\n\t }\n\n\t tmp_free = head;\n\t head = tmpq;\n\t free(tmp_free);\n }\n\n free(head);\n printf(\"\\n\");\n}\n\n// emit the rewriting select options according to the original select options\nvoid emit_rewriting_select_opts(int sel_type)\n{\n switch(sel_type)\n {\n case 0:\n case 2:\n\t printf(\" distinct \");\n\t break;\n case 1:\n case 3:\n\t printf(\" distinct all \");\n\t break;\n case 4:\n case 6:\n\t printf(\" distinct distinctrow \");\n\t break;\n case 5:\n case 7:\n\t printf(\" distinct distinctrow all \");\n\t break;\n }\n}\n\n// output the select expression list without the aggregation node\nvoid emit_select_expr_list_without_aggr(pselect_expr_list psel_l)\n{\n pselect_expr_list p;\n int first = 1;\n \n if(psel_l == NULL)\n {\n\t printf(\" * \");\n\t return;\n }\n\n p = psel_l->next;\n while(p != NULL)\n {\n\t if(p->expr->node_type != 'C')\n\t {\n\t if(!first)\n\t\t printf(\",\");\n\t emit_expr(p->expr);\n\n\t if(p->as_alias != NULL)\n {\n\t printf(\" as \");\n\t printf(\" %s \", p->as_alias->s->name);\n }\n\n\t first = 0;\n\t }\n\n\t p = p->next;\n }\n}\n\n// output the UnFilteredCandidates expression of aggregation rewriting.\nvoid emit_unfiltered_aggr(pselect_expr_list psel_l)\n{\n pselect_expr_list p;\n pufncall pc;\n int count = 1;\n int first = 1;\n \n if(psel_l == NULL)\n\t return;\n\n p = psel_l;\n while(p != NULL)\n {\n\t if(p->expr->node_type == 'C')\n\t {\n\t if(!first)\n\t\t printf(\",\\n\");\n\t pc = (pufncall)(p->expr);\n\t printf(\" min(\");\n\t emit_expr(pc->l);\n\t printf(\") as minAgg%d,\\n\",count);\n\t printf(\" max(\");\n\t emit_expr(pc->l);\n\t printf(\") as maxAgg%d\\n\",count);\n\n\t count++;\n\t }\n\t \n\t p = p->next;\n }\n}\n\n// output the FilteredCandidates of the aggregation rewriting.\nvoid emit_filtered_aggr(pselect_expr_list psel_l)\n{\n pselect_expr_list p;\n pufncall pc;\n int count = 1;\n int first = 1;\n \n if(psel_l == NULL)\n\t return;\n\n p = psel_l;\n while(p != NULL)\n {\n\t if(p->expr->node_type == 'C')\n\t {\n\t if(!first)\n\t\t printf(\",\\n\");\n\t pc = (pufncall)(p->expr);\n\t printf(\" case when min(\");\n\t emit_expr(pc->l);\n\t printf(\") > 0 then 0 else min(\");\n\t emit_expr(pc->l);\n\t printf(\") end as minAgg%d,\\n\",count);\n\t printf(\" case when max(\");\n\t emit_expr(pc->l);\n\t printf(\") > 0 then max(\");\n\t emit_expr(pc->l);\n\t printf(\") else 0 end as maxAgg%d\",count);\n\n\t count++;\n\t }\n\t \n\t p = p->next;\n }\n}\n\n// output the UnionCandidates expression of aggregation rewriting.\nvoid emit_union_aggr(pselect_expr_list psel_l)\n{\n pselect_expr_list p;\n pufncall pc;\n int count = 1;\n int first = 1;\n \n if(psel_l == NULL)\n\t return;\n\n p = psel_l;\n while(p != NULL)\n {\n\t if(p->expr->node_type == 'C')\n\t {\n\t if(!first)\n\t\t printf(\",\\n\");\n\t pc = (pufncall)(p->expr);\n\t printf(\" %s(minAgg%d),%s(maxAgg%d)\",pc->s->s->name,count,pc->s->s->name,count);\n\n\t count++;\n\t }\n\t \n\t p = p->next;\n }\n}\n\n// output the rewrite join algorithm\nvoid rewrite_join(pselect_stmt stmt)\n{\n pjoin_graph_nodelist p;\n exprlist epl;\n char* aliasn;\n pjoin_graph_nodelist root = get_join_graph_root();\n printf(\"with Candidates as( \\n\");\n printf(\" select \");\n emit_rewriting_select_opts(stmt->sel_type);\n \n if(!is_key_in(stmt->sel_expr_list,root->key_name)) \n\t printf(\"%s.%s,\",anti_translate(root->tb_name),root->key_name);\n emit_select_expr_list(stmt->sel_expr_list);\n printf(\"\\n\");\n printf(\" from \");\n emit_table_references(stmt->table_refs);\n printf(\"\\n\");\n printf(\" where \");\n emit_expr(stmt->opt_where_expr);\n printf(\" ),\\n\");\n \n printf(\"Filter as( \\n\");\n printf(\" select %s.%s\\n\",anti_translate(root->tb_name),root->key_name);\n printf(\" from Candidates Cand\\n\");\n\n aliasn = anti_translate(root->tb_name);\n if(aliasn == root->tb_name)\n {\n\t printf(\" join %s on Cand.%s=%s.%s\\n\",root->tb_name,root->key_name,root->tb_name,root->key_name);\n }\n else\n {\n\t printf(\" join %s %s on Cand.%s=%s.%s\\n\",root->tb_name,aliasn,root->key_name,aliasn,root->key_name);\n }\n\n \n emit_loj_queue(root);\n \n printf(\" where \");\n emit_nsc_exprs();\n p = jg_head->next;\n while(p != NULL)\n {\n\t if(p->in_degree != 0)\n\t {\n\t printf(\" or \");\n\t printf(\"%s.%s is null \",anti_translate(p->tb_name),p->key_name);\n\t }\n\t p = p->next;\n }\n \n //printf(\" or (Rx is null or ...)\");\n epl = kj_head->next;\n if(epl != NULL)\n {\n\t printf(\" and \");\n\t emit_kj_exprs();\n }\n //printf(\" and KJ\");\n printf(\"\\n\");\n \n printf(\" union all\\n\");\n printf(\" select %s\\n\",root->key_name);\n printf(\" from Candidates C\\n\");\n printf(\" group by %s\\n\",root->key_name);\n printf(\" having count(*)>1\");\n printf(\")\\n\");\n \n printf(\"select \");\n emit_rewriting_select_opts(stmt->sel_type);\n only_attr_cmd = 1;\n emit_select_expr_list(stmt->sel_expr_list);\n only_attr_cmd = 0;\n printf(\"\\n\");\n printf(\"from Candidates C\\n\");\n printf(\"where not exists( select * from Filter F where C.%s = F.%s)\\n\",root->key_name,root->key_name);\n if(stmt->odb_list != NULL)\n {\n\t printf(\" order by \");\n\t emit_groupby_list(stmt->odb_list); \n }\n}\n\n// output the rewrite aggregation algorithm\nvoid rewrite_aggr(pselect_stmt stmt)\n{\n pjoin_graph_nodelist p;\n exprlist epl;\n char* aliasn;\n pjoin_graph_nodelist root = get_join_graph_root();\n \n printf(\"with Candidates as(\\n\");\n printf(\" select \");\n if(!is_key_in(stmt->sel_expr_list,root->key_name)) \n\t printf(\"%s,\",root->key_name);\n emit_select_expr_list_without_aggr(stmt->sel_expr_list);\n printf(\"\\n from \");\n emit_table_references(stmt->table_refs);\n printf(\"\\n where \");\n emit_expr(stmt->opt_where_expr);\n printf(\"\\n),\\n\");\n printf(\"Filter as(\\n\");\n printf(\" select %s\\n\",root->key_name);\n printf(\" from \");\n emit_table_references(stmt->table_refs);\n printf(\"\\n where \");\n emit_nsc_exprs();\n printf(\"\\n),\\n\");\n\n printf(\"QGCons as(\\n\");\n printf(\" select \");\n emit_groupby_list(stmt->gpb_list);\n printf(\"\\n from Candidates c\\n\");\n printf(\" where not exists( select * from Filter f where c.%s = f.%s)\\n\",root->key_name,root->key_name);\n printf(\" group by \");\n emit_groupby_list(stmt->gpb_list);\n if(stmt->odb_list != NULL)\n {\n\t printf(\" order by \");\n\t emit_groupby_list(stmt->odb_list); \n }\n \n printf(\"\\n),\\n\");\n\n printf(\"UnFilteredCandidates as(\\n\");\n printf(\" select \");\n if(!is_key_in(stmt->sel_expr_list,root->key_name)) \n\t printf(\"%s,\",root->key_name);\n emit_select_expr_list_without_aggr(stmt->sel_expr_list);\n printf(\",\\n\");\n emit_unfiltered_aggr(stmt->sel_expr_list);\n printf(\" from \");\n emit_table_references(stmt->table_refs);\n printf(\"\\n where \");\n emit_expr(stmt->opt_where_expr);\n printf(\"\\n and not exists (select * from Filter f where %s.%s=f.%s)\\n\",root->tb_name,root->key_name,root->key_name);\n printf(\" group by %s,\",root->key_name);\n emit_groupby_list(stmt->gpb_list);\n printf(\"\\n),\\n\");\n\n printf(\"FilteredCandidates as(\\n\");\n printf(\" select \");\n if(!is_key_in(stmt->sel_expr_list,root->key_name)) \n\t printf(\"%s,\",root->key_name);\n emit_select_expr_list_without_aggr(stmt->sel_expr_list);\n printf(\",\\n\");\n emit_filtered_aggr(stmt->sel_expr_list);\n printf(\"\\n from \");\n emit_table_references(stmt->table_refs);\n printf(\"\\n where \");\n emit_expr(stmt->opt_where_expr);\n printf(\"\\n and exists (select * from Filter f where %s.%s=f.%s)\",root->tb_name,root->key_name,root->key_name);\n printf(\"\\n and exists (select * from QGCons where QGCons.\");\n emit_groupby_list(stmt->gpb_list);\n printf(\"=%s.\",root->tb_name);\n emit_groupby_list(stmt->gpb_list);\n printf(\")\");\n printf(\"\\n group by %s,\",root->key_name);\n emit_groupby_list(stmt->gpb_list);\n \n printf(\"\\n),\\n\");\n\n printf(\"UnionCandidates as(\\n\");\n printf(\" select * from UnFilteredCandidates\\n\");\n printf(\" union all\\n\");\n printf(\" select * from FilteredCandidates\\n\");\n printf(\")\\n\");\n printf(\"select \");\n emit_select_expr_list_without_aggr(stmt->sel_expr_list);\n printf(\",\");\n emit_union_aggr(stmt->sel_expr_list);\n printf(\"\\n\");\n printf(\"from UnionCandidates\\n\");\n printf(\"group by \");\n emit_groupby_list(stmt->gpb_list);\n printf(\"\\n\");\n}\n\n// set up the environment of the rewrite join algorithm\n// then clean it.\nvoid on_rewrite_join(past stmt)\n{\n init(stmt);\n\n //emit_join_graph();\n if(! check_join_graph())\n {\n\t semantic_error(\"error: not a tree join graph!\");\n\t clear(stmt);\n\t exit(1);\n }\n\n rewrite_join((pselect_stmt)stmt);\n\n clear(stmt);\n}\n\n// set up the environment of the rewrite aggregation algorithm\n// then clean it.\nvoid on_rewrite_aggr(past stmt)\n{\n init(stmt);\n\n if(! check_join_graph())\n {\n\t semantic_error(\"error: not a tree join graph!\");\n\t clear(stmt);\n\t exit(1);\n }\n \n // to-do list...\n rewrite_aggr((pselect_stmt)stmt);\n clear(stmt);\n}\n\n// init the rewriting envrionment\nvoid init(past stmt)\n{\n pjoin_graph_nodelist p;\n ptable_factor tb_fct;\n all_tables = build_tables(schema_fname);\n init_expr_lists();\n\n trans_table = build_trans_table(((pselect_stmt)stmt)->table_refs);\n classify(((pselect_stmt)stmt)->opt_where_expr);\n jg_head = build_join_graph();\n if(jg_head->next == NULL)\n {\n\t tb_fct = (ptable_factor)(((pselect_stmt)stmt)->table_refs->table_ref);\n\t p = newjoin_graph_nodelist();\n\t p->tb_name = strdup(tb_fct->s->s->name);\n\t p->key_name = get_key(p->tb_name);\n\t p->in_degree = 0;\n\t jg_head->next = p;\n }\n}\n\n// clear the rewriting environment\nvoid clear(past stmt)\n{\n free_join_graph(jg_head);\n free_expr_list(kj_head);\n free_expr_list(nkj_head);\n free_expr_list(sc_head);\n\n free_tables(all_tables);\n free_trans_table(trans_table);\n free_ast(stmt);\n rewrite_kind = 0;\n}\n\n// output the semantic error\nvoid semantic_error(const char* s, ...)\n{\n va_list ap;\n va_start(ap,s);\n\n vfprintf(stderr,s,ap);\n fprintf(stderr,\"\\n\");\n}\n\n// output the parser error\nvoid yyerror(const char *s, ...)\n{\n va_list ap;\n va_start(ap, s);\n\n fprintf(stderr, \"%d: error: \", yylineno);\n vfprintf(stderr, s, ap);\n fprintf(stderr, \"\\n\");\n}\n\n// output something.\nvoid emit(const char *s, ...)\n{\n va_list ap;\n va_start(ap, s);\n\n printf(\"rpn: \");\n vfprintf(stdout, s, ap);\n printf(\"\\n\");\n}\n\n" }, { "alpha_fraction": 0.7368420958518982, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 56, "blob_id": "d7996e20e069341ddab773748e060f1cdce52c60", "content_id": "76a17bc1146f04a72f1ef54e4d3796dce2eb0185", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 57, "license_type": "no_license", "max_line_length": 56, "num_lines": 1, "path": "/compile.sh", "repo_name": "swiftcore/ReSQL", "src_encoding": "UTF-8", "text": "gcc -o resql main.c scanner.c parser.c resql_funcs.c -lm\n" }, { "alpha_fraction": 0.6278316974639893, "alphanum_fraction": 0.6504854559898376, "avg_line_length": 19.600000381469727, "blob_id": "202953c594e98e4a2207fad33099bebf9cdfb346", "content_id": "dec57b9d13d2cd4177d28a4b0d215372460341fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 309, "license_type": "no_license", "max_line_length": 53, "num_lines": 15, "path": "/schema.sql", "repo_name": "swiftcore/ReSQL", "src_encoding": "UTF-8", "text": "create table customer(\n custkey char(4),\n nationkey char(4),\n mktsegment char(16),\n acctbal int,\n primary key (custkey)\n);\n\ncreate table orders(\n orderkey char(4),\n clerk varchar(4),\n custfk char(4),\n primary key (orderkey),\n foreign key (custfk) references customer(custkey)\n);\n" }, { "alpha_fraction": 0.5461323261260986, "alphanum_fraction": 0.5570052862167358, "avg_line_length": 24.33858299255371, "blob_id": "070ab7d2ac0a5dd26825609e58369c5a1513dd27", "content_id": "fce5c2b0a21dd5fb157cf54b54c09ece2325be86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3219, "license_type": "no_license", "max_line_length": 61, "num_lines": 127, "path": "/server.py", "repo_name": "swiftcore/ReSQL", "src_encoding": "UTF-8", "text": "# the rewrite sql compiler server end\nimport socket\nfrom subprocess import *\n\nHOST = ''\nPORT = 9999\nBUFSIZE=1024\nADDR = (HOST,PORT)\n\n# call the resql compiler\n# pass in the sql statement\n# return the rewriting sql result\ndef rewrite_sql(sql):\n print 'In reswrite_sql: ',sql\n p1 = Popen([\"echo\",sql],stdout=PIPE)\n p2 = Popen([\"./resql\"],stdin=p1.stdout,stdout=PIPE)\n fout = p2.communicate()[0]\n if p2.returncode == 0:\n return fout\n else:\n return \"can't rewrite\"\n\n# parse the create table statement\n# and generation the schema file\n# for the convince processing of the compiler writen in C.\ndef parse_query(query):\n table = []\n keys = []\n attrs = []\n \n # parse table name\n s = query.find('c')\n e = query.find('(')\n st = query[s:e]\n stab = st.split()\n table.append(stab[-1])\n\n s = e+1\n e = query.rfind(')');\n sat = query[s:e]\n sats = sat.split(',')\n for attab in sats:\n if attab.find(\"foreign\") != -1:\n pass\n elif attab.find('primary') == -1:\n attrs.append((attab.split())[0])\n else:\n s = attab.find('(')\n e = attab.rfind(')')\n keys = attab[s+1:e].split(',')\n\n for i in range(len(keys)):\n keys[i] = keys[i].strip()\n\n for key in keys:\n attrs.remove(key)\n\n table.append(keys)\n table.append(attrs)\n\n return table\n\n# read in the schema definations and\n# pass each defination to the parse_query function\n# get the parsed schema and write it into the schema.txt file\ndef extract_schema(schemadef):\n querys = schemadef.split(';')\n tables = []\n for query in querys:\n query = query.strip()\n if query != '':\n tables.append(parse_query(query))\n\n fout = open('schema.txt','w')\n fout.write(str(len(tables)) + '\\n')\n for table in tables:\n fout.write(table[0]+'\\n')\n fout.write(str(len(table[1]))+' ')\n fout.write(str(len(table[2]))+'\\n')\n for key in table[1]:\n fout.write(key+'\\n')\n for attr in table[2]:\n fout.write(attr+'\\n')\n fout.write('\\n')\n\n# deal with the user requestion\ndef deal_with(conn,data):\n if not data.rstrip().endswith(';'):\n data = data + ';'\n\n if data.startswith(\"\\\"\"):\n data = data[1:]\n \n if data.endswith(\"\\\";\"):\n data = data[:-2]\n \n if data.startswith('schema:'):\n print 'create schema with'\n create_sql = data.split(':')[1]\n print create_sql\n extract_schema(create_sql)\n conn.send('SCHEMA')\n elif data.startswith(\"sql:\"):\n ts = data.split(':')[1]\n print 'try rewriting'\n print ts\n resql = rewrite_sql(ts)\n conn.send(resql)\n else:\n print 'wrong format'\n print data\n conn.send('WRONG')\n\nif __name__ == '__main__':\n sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n sock.bind(ADDR)\n sock.listen(5)\n while True:\n print 'waiting... for connection...'\n connection,address = sock.accept()\n print '...connect from',address\n\n buf = connection.recv(1024)\n deal_with(connection,buf)\n connection.close()\n\n sock.close()\n\n" }, { "alpha_fraction": 0.7252252101898193, "alphanum_fraction": 0.7252252101898193, "avg_line_length": 73, "blob_id": "25891013246a1f2773fa51ec982657e1d79460db", "content_id": "3663d1d3e7a46896fafde0fd8e513be5072efd37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 222, "license_type": "no_license", "max_line_length": 132, "num_lines": 3, "path": "/countline.sh", "repo_name": "swiftcore/ReSQL", "src_encoding": "UTF-8", "text": "cat showcase.py clnt.py server.py main.c resql_funcs.c resql.h resql.l resql.y | wc -l\n\n#cat call_resql.py hello.py clnt.py serv.py extract.py main.c tests.c resql_funcs.c resql.tab.c resql.tab.h lex.yy.c tests.c | wc -l\n" }, { "alpha_fraction": 0.49143147468566895, "alphanum_fraction": 0.496082067489624, "avg_line_length": 26.25173568725586, "blob_id": "565e1d476852e54fc81005698de3da122d70b22d", "content_id": "b687b957bf15415a7f9eb22f43158b15ac1438c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15697, "license_type": "no_license", "max_line_length": 104, "num_lines": 576, "path": "/resql.h", "repo_name": "swiftcore/ReSQL", "src_encoding": "UTF-8", "text": "/*\n * structure and function Declarations for a rewriting sql compiler\n */\n#ifndef RESQL_H_INCLUDED\n#define RESQL_H_INCLUDED\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n/* buffer size for the symbol name space */\n#define BUFSIZE 64\n\n/*\n * nodes for attribute\n */\nstruct attrnode{\n char* name;\n struct attrnode* next;\n};\ntypedef struct attrnode attr;\ntypedef struct attrnode* attrlist;\n\n/*\n * nodes for table\n */\nstruct tablenode{\n char* name;\n attrlist keys;\n attrlist attrs;\n struct tablenode* next;\n};\ntypedef struct tablenode table;\n\n/*\n * This graph illustrate how is the table list being orgnized.\n *\n * table list\n * | head\n * +------------------+\t +-----------------+\t \t +-----------------+\n * | / / / / / / / | |\t |\t name \t | |\t \t | name \t| |\n * |---------------| ------->|--------------| -------> ... ----->|--------------| ------+\n * | / / / | /\t/ /| |\t | keys | attrs | |\t\t | keys\t| attrs\t| |\t|\n * +------------------+\t +---|------|------+\t\t +---|------|------+\t=\n *\t\t\t \t | \t|\t\t\t |\t |\n *\t\t\t | | \t\t\t ...\t ...\n *\t\t\t \t | \t|\n *\t\t\t \t | \t| |attr list head\n *\t\t\t \t | \t| +----------+ +----------+\t\t +----------+\n * \t \t \t \t | \t| | / / / | \t| | \t | |\t\t |\t | |\n *\t\t\t \t | \t+--->|/\t/ / /| ---->| name | -------> ... ----->| name\t | --------+\n *\t\t\t\t |\t | / / / | \t| |\t | | \t\t |\t | |\t |\n *\t\t\t\t |\t +----------+ +----------+ \t \t +----------+ \t |\n *\t\t\t\t | |key list head\t\t\t\t \t\t\t =\n *\t\t\t\t | +----------+ +----------+ \t\t +----------+\n *\t\t\t\t | |\t/ / / |\t | |\t | \t| \t\t |\t | |\n *\t\t\t\t +--->|/ / / /|\t---->| name | -------> ... ----->| name | -------+\n *\t\t\t\t |\t/ / / |\t | |\t | \t| \t\t |\t | |\t |\n *\t\t\t\t +----------+ +----------+\t\t +----------+\t =\n *\n *\n *\n */\ntypedef struct tablenode* tablelist;\n\n/*\n * nodes for alias-name table translate\n */\nstruct aliasnode\n{\n char* name;\n char* alias;\n struct aliasnode* next;\n};\n\n/*\n * This graph illustrate how the ailaslist is orgnized.\n * It is used for translate between tablename and its alias name.\n *\n *\n * |alias list head\n * +------------------+\t +------------------+\t\t +------------------+\n * | / / / | / / / | |\t |\t | \t | |\t\t |\t | |\t |\n * |/ /\t/ /|/ /\t/ /| ----->| name | alias | -----> ... ----->|\tname | alias |\t-----+\n * | / / / | / / / | |\t |\t | \t | |\t\t |\t | |\t | |\n * +------------------+\t +------------------+\t\t +------------------+ |\n *\t\t \t\t\t\t\t\t\t\t =\n *\n *\n *\n */\ntypedef struct aliasnode* aliaslist;\n\n/*\n * nodes for expr-list\n */\nstruct exprlistnode{\n struct ast* expr;\n struct exprlistnode* next;\n};\n\n/*\n * This graph illustrate how the exprlist is orgnized.\n * It is classify KJ,NKJ and SC, the three different kind of expression, with the same kind in one list.\n *\n *\n * |expr list head\n * +------------------+\t +------------------+\t\t +------------------+\n * | / / / / / / / | |\t |\t \t | |\t\t |\t |\t |\n * |/ /\t/ / / /\t/ /| ----->| expr-pointer | -----> ... ----->|\texpr-pointer |\t-----+\n * | / / / / / / / | |\t |\t | \t | |\t\t |\t | |\t | |\n * +------------------+\t +-------|----------+\t\t +-------|----------+ |\n *\t\t \t\t |\t\t\t\t |\t\t =\n *\t\t\t\t |\t\t\t\t |\n *\t\t\t\t expr \t \t \t \t expr\n *\n *\n *\n */\ntypedef struct exprlistnode* exprlist;\n\n/*\n * nodes defination for join-graph\n */\nstruct join_graph_node{\n char* dist_t;\n char* dist_a;\n char* src_t;\n char* src_a;\n struct join_graph_node* next;\n};\ntypedef struct join_graph_node* pjoin_graph_node;\n\nstruct join_graph_nodelist_node{\n char* tb_name;\n char* key_name;\n int in_degree;\n struct join_graph_node* node;\n struct join_graph_nodelist_node* next;\n};\n\n/*\n * This graph illustrates how the join graph is being orgnized.\n * It is a key data structrue implements the rewriting algorithm.\n * We use it to:\n * 1. get the root of the join graph\n * 2. check if the query is a tree query, also the semantic check\n * 3. generate the LOJ (left outer join) sequences.\n *\n * |join graph head\n * +---------+\n * | / / | |\n * |/ /\t/| |\n * | / / | | |\n * +-------|-+\n *\t |\t\t +------------------+\t \t\t+------------------+\n * +-----+\t\t | dist_t | |\t \t\t| dist_t |\t |\n * |\t\t\t |------------| |\t \t\t|------------|\t |\n * +------------------+\t | dist_a | |\t \t\t| dist_a |\t |\n * | tb_name \t| ----->|------------| --------> ... ------->|------------|\t-------------+\n * |------------| node|\t | src_t | |\t \t\t| src_t\t |\t |\t |\n * | key_name \t|-----|\t |------------| |\t\t\t|------------|\t |\t |\n * |------------| |\t | src_a | |\t\t \t| src_a\t |\t |\t =\n * | in_degree\t| | |\t +------------------+\t\t \t+------------------+\n * +---------------|--+\n * \t\t |\n * +-------------+\n * |\n * ...\n * |\n * +------------------+\n * | tb_name\t| ------> ... -----> ... -----+\n * |------------| node|\t \t \t\t|\n * | key_name \t|-----|\t \t\t\t=\n * |------------| |\n * | in_degree \t| | |\n * +---------------|--+\n *\t\t |\n *\t +---------+\n *\t |\n *\t =\n */\ntypedef struct join_graph_nodelist_node* pjoin_graph_nodelist;\n\nstruct loj_queue_node{\n pjoin_graph_node node;\n struct loj_queue_node* next;\n};\n\n/*\n * This graph illustrate how the loj queue is being orgnized.\n * It is classify KJ,NKJ and SC, the three different kind of expression, with the same kind in one list.\n *\n *\n * |loj queue head \t\t\t\t\t |loj queue tail\n * +------------------+\t +------------------+\t\t +------------------+\n * | / / / / / / / | |\t |\t \t | |\t\t |\t |\t |\n * |/ /\t/ / / /\t/ /| ----->| node-pointer | -----> ... ----->|\tnode-pointer |\t-----+\n * | / / / / / / / | |\t |\t | \t | |\t\t |\t | |\t | |\n * +------------------+\t +-------|----------+\t\t +-------|----------+ |\n *\t\t \t\t |\t\t\t\t |\t\t =\n *\t\t\t\t |\t\t\t\t |\n *\t\t\t a join graph node\t \t \t a join graph node\n *\n *\n *\n */\ntypedef struct loj_queue_node* loj_queue;\n\nint rewrite_kind;\ntablelist all_tables;\naliaslist trans_table;\nexprlist kj_head,kj_tail;\nexprlist nkj_head,nkj_tail;\nexprlist sc_head,sc_tail;\nchar signs[BUFSIZE];\nint signs_len;\nint only_attr_cmd;\npjoin_graph_nodelist jg_head;\nchar* schema_fname;\n\n/* nodes in the Abstract Syntax Tree */\n/* all have common initial nodetype */\n\nstruct ast {\n /*\n * ast includes all the expr types and unterminal types\n * 'I': integer\n * 'L': float\n * 'S': string\n * 'N': symref\n * 'F': build-in functions\n * 'C': user-call\n * '+': add\n * '-': minus\n * '*': multiple\n * '/': divide\n * '%': mod\n * 'D': NAME.NAME\n * 'M': - expr\n * 'A': and\n * 'O': or\n * 'T': not\n * '1': <\n * '2': >\n * '3': !=\n * '4': =\n * '5': <=\n * '6': >=\n * 'U': null\n * 'M': - expr\n * 'B': bool\n * 'E': exists\n * 'K': like\n * 'W': between...and...\n * 'Q': in\n * 'v': val_list\n * 's': select_expr_list\n * 'g': groupby_list\n * 'r': table_references\n * 'f': table_factor\n * 't': join_table\n * 'c': join_condition\n * 'i': index_list\n * 'm': select_stmt\n */\n int node_type;\n struct ast *l;\n struct ast *r;\n\n /* specially for between..and... */\n struct ast* rr;\n};\ntypedef struct ast* past;\n\n/* built-in function */\nstruct fncall {\n int node_type;\t\t\t/* type F */\n /* only count function currently */\n struct ast *l; /* list of arguments */\n};\ntypedef struct fncall* pfncall;\n\n/* user function */\nstruct ufncall {\n int node_type;\t\t\t/* type C */\n struct ast *l;\t\t/* list of arguments */\n struct symref *s;\n};\ntypedef struct ufncall* pufncall;\n\nstruct select_expr_list {\n int node_type; /* type s */\n /* one select expression */\n struct ast* expr;\n\n /* options for alias for\n * table or attribute\n * name\n */\n struct symref* as_alias;\n struct select_expr_list* next;\n};\ntypedef struct select_expr_list* pselect_expr_list;\n\nstruct groupby_list{\n\n int node_type; /* type g */\n struct ast* expr;\n /* options for group by | order by orders\n * 0: no options and for asc\n * 1: for desc\n */\n int opt_asc_desc;\n struct groupby_list* next;\n};\ntypedef struct groupby_list* pgroupby_list;\n\nstruct table_references{\n int node_type; /* type r */\n /* to use which generation form\n * 1: table_factor\n * 2: join_table\n */\n int ref_type;\n struct ast* table_ref;\n struct table_references* next;\n};\ntypedef struct table_references* ptable_references;\n\nstruct table_factor{\n int node_type; /* type f */\n /* to use which generation form\n * 1: NAME opt_as_alias index_hint // opt_as_alias is also a NAME\n * 2: NAME.NAME opt_as_alias index_hint\n * 3: table_subquery opt_as NAME\n * 4: (table_references)\n */\n int factor_type;\n struct symref* s;\n struct symref* s2;\n struct symref* s3;\n struct ast* l;\n};\ntypedef struct table_factor* ptable_factor;\n\nstruct join_table{\n int node_type; /* type t */\n\n /* define all the join types\n * to use which generation form\n * 64: JOIN\n * 65: INNER JOIN\n * 66: CROSS JOIN\n *\n * 128: STRAIGHT_JOIN\n *\n * 193: LEFT\n * 197: LEFT OUTER\n * 194: RIGHT\n * 198: RIGHT OUTER\n *\n * 257: NATRAL LEFT\n * 261: NATRAL LEFT OUTER\n * 258: NATRAL RIGHT\n * 262: NATRAL RIGHT OUTER\n * 256: NATRAL\n */\n int join_type;\n struct ast* table_ref;\n struct ast* table_fct;\n struct ast* join_cond;\n /* need to modified */\n};\ntypedef struct join_table* pjoin_table;\n\nstruct join_condition{\n int node_type; /* type c */\n /*\n * define the condition type\n * to use which generation form\n * 1: ON expr\n * 2: USING (column_list) , column_list is a kind of val_list\n */\n int con_type;\n struct ast* l;\n};\ntypedef struct join_condition* pjoin_condition;\n\nstruct index_list{\n int node_type; /* type i */\n /*\n * the symbol referenced;\n */\n struct symref* s;\n struct index_list* next;\n};\ntypedef struct index_list* pindex_list;\n\n\n/* the defination for a full possible format\n* of the select statement\n*/\nstruct select_stmt{\n int node_type; /* type m */\n /* the type of select options\n * 0: no options\n * 1: all\n * 2: distinct\n * 3: distinct all\n * 4: distinctrow\n * 5: distinctrow all\n * 6: distinct distinctrow\n * 7: distinct distinctrow all\n */\n int sel_type;\n struct select_expr_list* sel_expr_list;\n struct table_references* table_refs;\n\n /* options for where conditions */\n struct ast* opt_where_expr;\n\n /* group by attrs list */\n struct groupby_list* gpb_list;\n\n /* options for having conditions */\n struct ast* opt_having_expr;\n\n /* order by attr list */\n struct groupby_list* odb_list;\n};\ntypedef struct select_stmt* pselect_stmt;\n\nstruct intval {\n int node_type;\t\t\t/* type I */\n int number;\n};\ntypedef struct intval* pintval;\n\nstruct floatval {\n int node_type; /* type L */\n double number;\n};\ntypedef struct floatval* pfloatval;\n\nstruct strval {\n int node_type; /* type S */\n char* str;\n};\ntypedef struct strval* pstrval;\n\n\nstruct symref {\n int node_type;\t\t\t/* type N */\n struct symbol *s;\n};\ntypedef struct symref* psymref;\n\n/* symbol table */\nstruct symbol{ /* a variable name */\n char *name;\n};\ntypedef struct symbol* psymbol;\n\n/* simple symtab of fixed size */\n#define NHASH 9997\n\nstruct symbol symtab[NHASH];\n\n/* list of symbols, for an argument list */\nstruct symlist {\n past expr;\n struct symlist *next;\n};\n\nvoid init_symtab();\npsymbol newsymbol(char* s);\n\nstruct symlist *newsymlist(struct ast* expr, struct symlist *next);\nvoid symlistfree(struct symlist *sl);\n\n/* build an AST */\npast newast(int node_type,past l, past r, past rr);\npast newcmp(int cmp_type,past l, past r);\npast newfunc(past l);\npast newcall(past s, past l);\npast newselect_expr_list(past exp, past als, past n);\npast newgroupby_list(int opt_ad, past expr,past n);\npast newtable_references(int reft, past table_r, past n);\npast newtable_factor(int factor_t, past s, past s2, past s3, past l);\npast newjoin_table(int join_type, past table_r, past table_f, past join_c);\npast newjoin_condition(int join_t,past expr);\npast newindex_list(past s, past n);\npast newselect_stmt(int sel_t, past sel_el, past table_rs, past opt_w, past gpb_l,past opt_h, past odb);\npast newint(int n);\npast newfloat(double f);\npast newstring(char* s);\npast newsymref(psymbol s);\n\n/* free the AST tree nodes */\nvoid free_select_expr_list(pselect_expr_list a);\nvoid free_groupby_list(pgroupby_list a);\nvoid free_table_references(ptable_references a);\nvoid free_table_factor(ptable_factor a);\nvoid free_join_table(pjoin_table a);\nvoid free_join_condition(pjoin_condition a);\nvoid free_index_list(pindex_list a);\nvoid free_select_stmt(pselect_stmt a);\nvoid free_fncall(pfncall a);\nvoid free_ufncall(pufncall a);\nvoid free_ast(past a);\n\n/* emit the AST tree nodes */\nvoid emit_expr(past pa);\nvoid emit_null(past pa, const char* app);\nvoid emit_bool(past pa, const char* app);\nvoid emit_in(past pa, const char* app);\nvoid emit_like(past pa, const char* app);\nvoid emit_fncall(pfncall pa);\nvoid emit_ufncall(pufncall pa);\nvoid emit_compare(past pa, const char* comp);\nvoid emit_select_expr_list(pselect_expr_list psel_l);\nvoid emit_table_factor(ptable_factor ptf);\nvoid emit_index_list(pindex_list pil);\nvoid emit_join_condition(pjoin_condition pjc);\nvoid emit_join_table_base(pjoin_table pjt, const char* app);\nvoid emit_join_table(pjoin_table pjt);\nvoid emit_table_references(ptable_references ptr);\nvoid emit_groupby_list(pgroupby_list pgpb_l);\nvoid emit_select_stmt(pselect_stmt stmt);\n\n/* manipulation of rewriting sql data-structure */\ntablelist newtable(char* name);\nattrlist newattr(char* name);\nloj_queue newloj_queue_node();\nattrlist build_attrs(FILE* fp, int n);\ntablelist build_table(FILE* fp);\nvoid print_tables(tablelist head);\ntablelist build_tables(const char* filename);\nvoid free_attrs(attrlist head);\nvoid free_tables();\naliaslist build_trans_table(ptable_references tb_refs);\nvoid free_trans_table(aliaslist al);\nvoid init_expr_lists();\nvoid free_expr_list(exprlist el);\nvoid insert_kj_expr(past expr);\nvoid insert_nkj_expr(past expr);\nvoid insert_sc_expr(past expr);\nvoid emit_kj_exprs();\nvoid emit_nkj_exprs();\nvoid emit_sc_exprs();\nvoid emit_nsc_exprs();\nchar* translate(char* alias);\nchar* anti_translate(char* tbn);\nchar* get_key(const char* tbn);\nvoid init(past stmt);\nvoid clear(past stmt);\n\n/* sql rewriting functions */\nvoid emit_rewriting_select_opts(int sel_type);\n//void rewrite_join();\nvoid semantic_error(const char* s, ...);\n\n/* symtab lookup and insert item */\npsymbol lookup(const char* sym);\n\n/* interface to the lexer */\nextern int yylineno; /* from lexer */\nvoid yyerror(const char *s, ...);\nvoid emit(const char *s, ...);\nvoid sparse(int ac, char **av);\n\nextern int debug;\nvoid dumpast(struct ast *a, int level);\n\n#endif // RESQL_H_INCLUDED\n" }, { "alpha_fraction": 0.6159420013427734, "alphanum_fraction": 0.6884058117866516, "avg_line_length": 38.35714340209961, "blob_id": "6d16484900be83738822ec1ee7be6864200c1202", "content_id": "0b6dfa5ccd6aeae27154e7d14e126bfda98be4a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 552, "license_type": "no_license", "max_line_length": 43, "num_lines": 14, "path": "/data.sql", "repo_name": "swiftcore/ReSQL", "src_encoding": "UTF-8", "text": "insert into customer values('c1',2000);\ninsert into customer values('c1',100);\ninsert into customer values('c2',2500);\ninsert into customer values('c3',2200);\ninsert into customer values('c3',2500);\n\ninsert into orders values('o1','ali','c1');\ninsert into orders values('o2','jo','c2');\ninsert into orders values('o2','ali','o3');\ninsert into orders values('o3','ali','c4');\ninsert into orders values('o3','pat','c2');\ninsert into orders values('o4','ali','c2');\ninsert into orders values('o4','ali','c3');\ninsert into orders values('o5','ali','c2');\n\n" } ]
11
canada-poll-location-analysis/General-Election-Official-Voting-Results-Scraper
https://github.com/canada-poll-location-analysis/General-Election-Official-Voting-Results-Scraper
dd6717e0e4902912e275014178705c2cd5a1e2a2
8ef36cf3edcf4921f963196d547262785d3f981c
370b9e503e6def87577ca8481a217a7df85a634b
refs/heads/master
2020-10-02T01:56:34.246899
2019-12-12T19:31:33
2019-12-12T19:31:33
227,674,924
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.752212405204773, "alphanum_fraction": 0.76106196641922, "avg_line_length": 24.11111068725586, "blob_id": "fc06263463d01c9b5e21950a804f868a86bfeffd", "content_id": "9a419396aab8dcf3899c6811c4c0a8038a432205", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 226, "license_type": "no_license", "max_line_length": 129, "num_lines": 9, "path": "/README.md", "repo_name": "canada-poll-location-analysis/General-Election-Official-Voting-Results-Scraper", "src_encoding": "UTF-8", "text": "# General Election Official Voting Results Scraper\n\nScrapes and combines the data [here](https://www.elections.ca/content.aspx?section=res&dir=rep/off/42gedata&document=byed&lang=e)\n\n## Requirements : \n\n* tqdm\n* wget\n* pandas\n" }, { "alpha_fraction": 0.5765618681907654, "alphanum_fraction": 0.5879951119422913, "avg_line_length": 33.49275207519531, "blob_id": "0d30cf04f394985199e2599fe3e54164f16103bf", "content_id": "79ce16168378d271c5848296f04ba64236aae8d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2453, "license_type": "no_license", "max_line_length": 85, "num_lines": 69, "path": "/GeneralElectionOfficialVotingResultsScraper.py", "repo_name": "canada-poll-location-analysis/General-Election-Official-Voting-Results-Scraper", "src_encoding": "UTF-8", "text": "import logging\r\nimport os\r\n\r\nimport pandas as pd\r\nimport wget as wget\r\nfrom tqdm import tqdm\r\n\r\nfrom sean_logger import setup_logging\r\nfrom toolbox import make_directory\r\n\r\n\r\ndef scrape_election_results(prov_id=35, base_url=None, results_format=1):\r\n setup_logging()\r\n if results_format == 1:\r\n results_format = \"pollbypoll_bureauparbureau\"\r\n elif results_format == 2:\r\n results_format = \"pollresults_resultatsbureau\"\r\n if base_url is None:\r\n base_url = \"https://www.elections.ca/res/rep/off/ovr2015app/41/data_donnees/\"\r\n num_except_in_a_row = 0\r\n exceptions = []\r\n for fed_num in tqdm(range(prov_id * 1000, ((prov_id + 1) * 1000) - 1)):\r\n logging.info(f\"fed num {fed_num}\")\r\n try:\r\n url = f\"{base_url}{results_format}{fed_num}.csv\"\r\n outfile = f\"./data_donnees/{results_format}{fed_num}.csv\"\r\n logging.debug(url)\r\n logging.debug(outfile)\r\n make_directory(outfile)\r\n wget.download(url, outfile)\r\n num_except_in_a_row = 0\r\n except:\r\n logging.exception(f\"Exception!! {fed_num}\")\r\n exceptions.append(fed_num)\r\n num_except_in_a_row += 1\r\n if num_except_in_a_row > 10:\r\n logging.info(f\"Probably finished at {fed_num - num_except_in_a_row}\")\r\n break\r\n logging.info(f\"Missed FED Nums:\")\r\n for fed in exceptions:\r\n logging.info(fed)\r\n logging.info()\r\n print('fin')\r\n\r\n\r\ndef combine_result_csvs(folder=None, cols=None):\r\n if folder is None:\r\n folder = \"./data_donnees/\"\r\n files = os.listdir(folder)\r\n if cols is None:\r\n cols = \"Electoral District Number/Numéro de circonscription,\" \\\r\n \"Electoral District Name/Nom de circonscription,\" \\\r\n \"Polling Station Number/Numéro du bureau de scrutin,\" \\\r\n \"Polling Station Name/Nom du bureau de scrutin,\" \\\r\n \"Rejected Ballots/Bulletins rejetés,\" \\\r\n \"Total Votes/Total des votes,\" \\\r\n \"Electors/Électeurs\".split(',')\r\n print(\"Reading...\")\r\n frames = [pd.read_csv(folder + file, usecols=cols) for file in tqdm(files)]\r\n print(\"Combining...\")\r\n data = pd.concat(frames)\r\n print(\"Writing...\")\r\n data.to_csv(\"turnout_data_ontario_42nd_federal.csv\", index=False)\r\n print(\"Fin.\")\r\n\r\n\r\nif __name__ == '__main__':\r\n scrape_election_results()\r\n combine_result_csvs()\r\n" } ]
2
kaosx5s/OratoricalDecaf
https://github.com/kaosx5s/OratoricalDecaf
4e249595def8a775d2b6d7c99328b3c16690dbcd
55b8f37933816d74060246c3732f6b98caeae858
283cf401c2eb69ed0a7c2404e63feea760f3d1e9
refs/heads/master
2020-12-25T10:14:08.355304
2013-02-23T14:42:40
2013-02-23T14:42:40
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6944739818572998, "alphanum_fraction": 0.6968650221824646, "avg_line_length": 25.14583396911621, "blob_id": "f3e28d5850602bd108fc21d4966a246f04967c6c", "content_id": "115833736a47a369a90928c3081250faeda73079", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3764, "license_type": "permissive", "max_line_length": 117, "num_lines": 144, "path": "/Project/datastore.py", "repo_name": "kaosx5s/OratoricalDecaf", "src_encoding": "UTF-8", "text": "import datetime\nfrom google.appengine.ext import db\nfrom google.appengine.api import users\n\n'''\n\tDATASTORE CLASSES\n'''\nclass Articles(db.Model):\n\tlink = db.LinkProperty()\n\ttext = db.StringProperty()\n\tvotes = db.IntegerProperty()\n\tposted = db.DateTimeProperty()\n\towner = db.StringProperty()\n\nclass Votes(db.Model):\n\tarticle_id = db.IntegerProperty()\n\tusers = db.ListProperty(db.Email)\n\n\nclass Comments(db.Model):\n\tarticle_id = db.IntegerProperty()\n\tcomment_owner = db.EmailProperty()\n\tcomment_text = db.StringProperty()\n\tposted = db.DateTimeProperty()\n\n'''\n\tDATASTORE FUNCTIONS\n'''\n'''\n\tFunction: Post Article\n\tProperties:\n\t\tinput:\n\t\t\tlink = URL link passed from script\n\t\t\ttext = Article title text passed from script\n\t\toutput:\n\t\t\tNone\n\t\trequired:\n\t\t\tNone\n'''\ndef Post_Article(link,text,owner):\n\tarticle_info = Articles()\n\n\t#set the article data\n\tarticle_info.link = link\n\tarticle_info.text = text\n\tarticle_info.votes = 0\n\tarticle_info.posted = datetime.datetime.now()\n\tarticle_info.owner = owner\n\t#store it!\n\tarticle_info.put()\n\n'''\n\tFunction: Get Article List\n\tProperties:\n\t\tinput:\n\t\t\tNone\n\t\toutput:\n\t\t\tArticles -> list\n\t\t\t\t[0] = database index id\n\t\t\t\t[1] = article link (URL)\n\t\t\t\t[2] = article text\n\t\t\t\t[3] = article vote amount\n\t\trequired:\n\t\t\tNone\n'''\ndef Get_Articles():\n\tarticles = []\n\tresult = []\n\tfor i in Articles.all().order('-posted'):\n\t\tresult = [i.key().id(),i.link,i.text,i.votes]\n\t\tarticles.append(result)\n\treturn(articles)\n\n'''\n\tFunction: Post Comment\n\tProperties:\n\t\tinput:\n\t\t\tarticle_id = entity id of article from script\n\t\t\tcommentor = comment author (username)\n\t\t\tcomment_text = comment text body passed from script\n\t\toutput:\n\t\t\tNone\n\t\trequired:\n\t\t\tNone\n'''\ndef Post_Comment(article_id,commentor,comment_text):\n\t#note that article_id is actually an entity id which can be pulled when we load the comments\n\tnew_comment = Comments(Articles().get_by_id(ids = article_id).key())\n\t\n\t#setup the comment data\n\tnew_comment.article_id = article_id\n\tnew_comment.comment_owner = commentor\n\tnew_comment.comment_text = comment_text\n\tnew_comment.posted = datetime.datetime.now()\n\tnew_comment.put()\n\n'''\n\tFunction: Article Vote\n\tProperties:\n\t\tinput:\n\n\t\toutput:\n\n\t\trequired:\n\n'''\ndef Vote_Article(username,article_id,vote):\n\t'''\n\t\tnote, vote can only be -1 or 1, 0 IS NOT acceptable\n\t\talso note this is a two prong function, we must make sure the user has not voted prior; if they have not voted than\n\t\twe must add the vote to the Articles() table and then also add an entry to the Votes() table.\n\t'''\n\tnew_vote = Votes().all().filter(\"article_id =\",int(article_id))\n\t#we should always have an article that matches its ID, if not than we are in serious trouble!\n\tarticle_add_vote = Articles().get_by_id(ids = int(article_id))\n\temail_address = db.Email(username)\n\n\t#make sure the votes for this article exist, if not create a new entry for them.\n\tif new_vote.get() is None:\n\t\t#WARNING: we are redefining new_vote!\n\t\tnew_vote = Votes(Articles().get_by_id(ids = int(article_id)).key())\n\t\tnew_vote.article_id = int(article_id)\n\t\tnew_vote.users = [email_address]\n\t\t\n\t\tarticle_add_vote.votes = int(vote)\n\t\t#add the vote to the article first\n\t\tarticle_add_vote.put()\n\t\t#now add the votes entity\n\t\tnew_vote.put()\n\t\treturn\n\telse:\n\t\t#check to see if we have already voted for this article!\n\t\talready_voted = Votes.all().filter(\"article_id =\",article_id).filter(\"users in\",[email_address]).get()\n\t\tif already_voted is None:\n\t\t\treturn 1\n\t\t\n\t\tnew_vote = Votes().all().filter(\"article_id =\",int(article_id)).get()\n\t\tnew_vote = Votes(Articles().get_by_id(ids = int(article_id)).key()).get_by_id(ids = new_vote.key().id())\n\t\tnew_vote.users.append(email_address)\n\t\t\n\t\tarticle_add_vote.votes = int(article_add_vote.votes) + int(vote)\n\t\t\t\t\n\t\tnew_vote.put()\n\t\tarticle_add_vote.put()" }, { "alpha_fraction": 0.6263368725776672, "alphanum_fraction": 0.6377005577087402, "avg_line_length": 29.5510196685791, "blob_id": "a37f938a29c822bc0f3e2369fdba32a094d0dfeb", "content_id": "ff99d8e4d84935d0c16143f517aca566ce255900", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1496, "license_type": "permissive", "max_line_length": 107, "num_lines": 49, "path": "/Project/articles.py", "repo_name": "kaosx5s/OratoricalDecaf", "src_encoding": "UTF-8", "text": "'''\n\tAuthor: Robert Cabral\n\tFile Name: Post_Module.py\n\tPurpose: To create an Article Post into the database that has the Article Title and Article URL properties\n\t\t associated with the Article Post.\n\tDate:\t2/16/2013\n'''\nimport datastore\nimport webapp2\nimport cgi\nfrom google.appengine.api import users\n\nform = \"\"\"\n<html>\n\t<body>\n\t\t<form method=\"post\">\n\t\t\t<div><h1>Post Page</h1></div>\n\t\t\t<div>Title:</div>\n\t\t\t<div><textarea name=\"link_title\" rows=\"2\" cols=\"60\"></textarea></div>\n\t\t\t<div>Location/URL:<br></div>\n\t\t\t<div><textarea name=\"link_url\" rows=\"2\" cols=\"60\"></textarea></div>\n\t\t\t<div><input type=\"submit\" value=\"Post\"></div>\n\t\t</form>\n\t</body>\n</html>\n\"\"\"\n\ndef escape_html(s):\n\t\treturn cgi.escape(s, quote = True)\n\t\t\nclass PostPage(webapp2.RequestHandler):\n\tdef write_form(self, error=\"\", title=\"\", url=\"\"):\n\t\tself.response.out.write(form %{\"error\": error,\n \"link_title\": escape_html(title),\n \"link_url\": escape_html(url)})\n\tdef get(self):\n\t\t#We should check to see if the user is logged in here instead of after our POST.\n\t\tif users.get_current_user():\n\t\t self.write_form()\n\t\telse:\n\t\t self.redirect(users.create_login_url(self.request.uri))\n\n\tdef post(self):\n\t\tuser = users.get_current_user() \n\t\tuser_link_url = self.request.get('link_url')\n\t\tuser_link_title = self.request.get('link_title')\n\t\tuser_name = user.nickname()\n\t\tdatastore.Post_Article(user_link_url,user_link_title,user_name)\n\t\tself.redirect(\"/\")" }, { "alpha_fraction": 0.6928571462631226, "alphanum_fraction": 0.6961038708686829, "avg_line_length": 29.215686798095703, "blob_id": "4d5d6c0876901f38fc62a64f651af0d6160c80ca", "content_id": "31a95b3a1d56ba910fe94127bf6298d971f1b4c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1540, "license_type": "permissive", "max_line_length": 98, "num_lines": 51, "path": "/Project/comment.py", "repo_name": "kaosx5s/OratoricalDecaf", "src_encoding": "UTF-8", "text": "import cgi\nimport datetime\nimport urllib\nimport webapp2\nimport datastore\n\nfrom google.appengine.ext import db\nfrom google.appengine.api import users\n\nclass RequestHandler(webapp2.RequestHandler):\n def get(self, article_id):\n self.response.out.write('<html><body>')\n\n #article_key = self.request.get('article_key')\n\n\tmy_article = datastore.Articles().get_by_id(ids = int(article_id))\n\tarticle_name = my_article.text\n\n\t#user login check\n\tuser = users.get_current_user()\n\tif not user:\n\t\tself.redirect(users.create_login_url(self.request.uri))\n\n\t#article name\n\tself.response.out.write('Article Name: <b>%s</b>' % article_name)\n\tself.response.out.write('<br><a href=\"/\">Back</a>')\n\n\t#comment query\n\tcomment_list = datastore.Comments().all().filter(\"article_id =\",int(article_id))\n\n\t#comment submission form\n\tself.response.out.write(\"\"\"\n\t\t<form method=\"post\">\n\t\t<div><textarea name=\"comment_text\" rows=\"3\" cols=\"60\"></textarea></div>\n\t\t<div><input type=\"submit\" value=\"Post\"></div>\n\t\t</form>\"\"\")\n\n\n\tfor comments in comment_list:\n\t\t#sub-note - comments will always have an author\n\t\tself.response.out.write('<b>%s</b> wrote:' % comments.comment_owner)\n\t\tself.response.out.write('<blockquote>%s</blockquote>' % cgi.escape(comments.comment_text))\n\n self.response.out.write(\"\"\"</body></html>\"\"\" )\n\n def post(self, article_id):\n\n\tcomment_text = self.request.get('comment_text')\n\tdatastore.Post_Comment(int(article_id),users.get_current_user().email(),cgi.escape(comment_text))\n\n self.redirect('/comment/%s'% (article_id))" }, { "alpha_fraction": 0.792792797088623, "alphanum_fraction": 0.792792797088623, "avg_line_length": 26.75, "blob_id": "6c577df0664e56daded4f3a40f87e74827a4fd38", "content_id": "8ec49e773f7c5515c2e48410b04b9da7e0b0423e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 111, "license_type": "permissive", "max_line_length": 49, "num_lines": 4, "path": "/Project/config.py", "repo_name": "kaosx5s/OratoricalDecaf", "src_encoding": "UTF-8", "text": "# This file contains hardcoded strings and values\n\nmain_page=\"article_list.html\"\nmain_title=\"Oratorical Decaf\"\n" }, { "alpha_fraction": 0.7090336084365845, "alphanum_fraction": 0.7174369692802429, "avg_line_length": 27.84848403930664, "blob_id": "4780d908bbd852bfbd33e207664a76c4ae818c7e", "content_id": "16fece181010a346aac3c0b5fd13e4e51d72c45c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 952, "license_type": "permissive", "max_line_length": 85, "num_lines": 33, "path": "/Project/main.py", "repo_name": "kaosx5s/OratoricalDecaf", "src_encoding": "UTF-8", "text": "import webapp2\nimport os\nimport datastore\nimport config\nimport vote\nimport articles\nimport comment\nimport jinja2\nfrom google.appengine.ext import db\nfrom google.appengine.api import users\n\n# jinja2 file loading copied from \n# https://github.com/fRuiApps/cpfthw/blob/master/webapp2/views.py\nTEMPLATE_DIR = os.path.join(os.path.dirname(__file__), 'templates')\nj_env = jinja2.Environment(loader=jinja2.FileSystemLoader(TEMPLATE_DIR))\n\n\nclass MainHandler(webapp2.RequestHandler):\n def get(self):\n template = j_env.get_template(config.main_page)\n\tself.response.write('''\n\t\t<a href=\"/article\">Post new article</a>\n\t''')\n\tarticles = datastore.Get_Articles()\n self.response.write(template.render(title=config.main_title,data = articles))\n\napp = webapp2.WSGIApplication([\n ('/', MainHandler),\n ('/vote/(.*)', vote.RequestHandler),\n ('/article', articles.PostPage),\n ('/comment/(.*)', comment.RequestHandler)\n ], \n debug=True)\n" } ]
5
moniker-dns/icinga-cookbook
https://github.com/moniker-dns/icinga-cookbook
c5e773b7368263c127e471b915d123408ec02c5c
351f3bc4322e8f1c25770ec66f128b1a1d315b28
a2a7a542c7c90579885ada8b72333554c006c98a
refs/heads/master
2021-01-16T01:07:45.058433
2013-12-11T12:50:29
2013-12-11T12:50:29
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6605714559555054, "alphanum_fraction": 0.6708571314811707, "avg_line_length": 23.33333396911621, "blob_id": "f3293cfea2e3a809a68d378152feb38b493176c4", "content_id": "e4960586fccd5cf1e8da69417b058d09f931f9ef", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 875, "license_type": "permissive", "max_line_length": 76, "num_lines": 36, "path": "/files/default/plugins/check_pdns_socket", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom __future__ import print_function\n\nimport argparse\nimport socket\nimport sys\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--socket', help=\"Socket to connect to\", type=str,\n default=\"/var/run/pdns.controlsocket\")\nparser.add_argument('--timeout', help=\"Socket timeout\", type=int, default=5)\nargs = parser.parse_args()\n\ns = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\ns.settimeout(args.timeout)\n\ntry:\n s.connect(args.socket)\n s.send('PING\\n')\n data = s.recv(1024)\nexcept socket.timeout:\n print (\"CRITICAL: Socket timeout, please investigate!\")\n sys.exit(2)\nexcept socket.error, e:\n print (\"CRITICAL: %s\" % e)\n sys.exit(2)\n\ns.close()\n\nif data != 'PONG':\n print('CRITICAL: Ping error, didn\\' receive PONG!')\n sys.exit(2)\nelse:\n print(\"OK: Socket is responding with PONG\")\n sys.exit(0)" }, { "alpha_fraction": 0.5677233338356018, "alphanum_fraction": 0.5763688683509827, "avg_line_length": 15.523809432983398, "blob_id": "864367bae0f0bd6b7e6fca148a846c5ae70e68a9", "content_id": "de5ca2a70c71a527073a747f59101e4ad7bdc943", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 347, "license_type": "permissive", "max_line_length": 45, "num_lines": 21, "path": "/files/default/server/hipchat_icinga.sh", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# exit on failure\nset -e\n\nSCRIPT=`dirname \"$0\"`/hipchat_room_message.sh\n\ncase \"$2\" in\n \"OK\") COLOR=\"green\" ;;\n \"WARNING\") COLOR=\"yellow\" ;;\n \"UNKNOWN\") COLOR=\"purple\" ;;\n \"CRITICAL\") COLOR=\"red\" ;;\n\n \"UP\") COLOR=\"green\" ;;\n \"DOWN\") COLOR=\"red\" ;;\n \"UNREACHABLE\") COLOR=\"purple\" ;;\n\n *) COLOR=\"red\" ;;\nesac\n\n$SCRIPT -c $COLOR \"${@:3}\"\n" }, { "alpha_fraction": 0.6216481328010559, "alphanum_fraction": 0.628515362739563, "avg_line_length": 29.579999923706055, "blob_id": "78fd38ae7952a5df2df69e26ca5b43ff87cdc6bd", "content_id": "f132f0df996b26dd10c5764535923a3935a7a28e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3062, "license_type": "permissive", "max_line_length": 121, "num_lines": 100, "path": "/files/default/server/hipchat_room_message.sh", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Copyright (c) HipChat, Inc.\n\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n###############################################################################\n#\n# ./hipchat_room_message\n#\n# A script for sending a system message to a room.\n#\n# Docs: http://github.com/hipchat/hipchat-cli\n#\n# Usage:\n# cat message.txt | ./hipchat_room_message -t <token> -r 1234 -f \"System\"\n# echo -e \"New\\nline\" | ./hipchat_room_message -t <token> -r 1234 -f \"System\"\n#\n###############################################################################\n\n# exit on failure\nset -e\n\nusage() {\n cat << EOF\nUsage: $0 -t <token> -r <room id> -f <from name>\n\nThis script will read from stdin and send the contents to the given room as\na system message.\n\nOPTIONS:\n -h Show this message\n -t <token> API token\n -r <room id> Room ID\n -f <from name> From name\n -c <color> Message color (yellow, red, green, purple or random - default: yellow)\n -n Trigger notification for people in the room\n -o API host (api.hipchat.com)\nEOF\n}\n\nTOKEN=\nROOM_ID=\nFROM=\nCOLOR=\nMESSAGE=\nNOTIFY=0\nHOST='api.hipchat.com'\nwhile getopts “ht:r:f:c:o:n” OPTION; do\n case $OPTION in\n h) usage; exit 1;;\n t) TOKEN=$OPTARG;;\n r) ROOM_ID=$OPTARG;;\n f) FROM=$OPTARG;;\n c) COLOR=$OPTARG;;\n n) NOTIFY=1;;\n o) HOST=$OPTARG;;\n [?]) usage; exit;;\n esac\ndone\n\n# check for required args\nif [[ -z $TOKEN ]] || [[ -z $ROOM_ID ]] || [[ -z $FROM ]]; then\n usage\n exit 1\nfi\n\n# read stdin\nINPUT=$(cat)\n\n# replace newlines with XHTML <br>\nINPUT=$(echo -n \"${INPUT}\" | sed \"s/$/\\<br\\>/\")\n\n# replace bare URLs with real hyperlinks\nINPUT=$(echo -n \"${INPUT}\" | perl -p -e \"s/(?<!href=\\\")((?:https?|ftp|mailto)\\:\\/\\/[^ \\n]*)/\\<a href=\\\"\\1\\\"\\>\\1\\<\\/a>/g\")\n\n# urlencode with perl\nINPUT=$(echo -n \"${INPUT}\" | perl -p -e 's/([^A-Za-z0-9])/sprintf(\"%%%02X\", ord($1))/seg')\n\n# do the curl\ncurl -sS \\\n -d \"auth_token=$TOKEN&room_id=$ROOM_ID&from=$FROM&color=$COLOR&message=$INPUT&notify=$NOTIFY\" \\\n https://$HOST/v1/rooms/message\n" }, { "alpha_fraction": 0.5339806079864502, "alphanum_fraction": 0.5582524538040161, "avg_line_length": 24.75, "blob_id": "7c4612c9d44fa20075b15d58622446146838c450", "content_id": "75f5c0157fba4a6728f2063c722a0aef8d4f6cea", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 206, "license_type": "permissive", "max_line_length": 39, "num_lines": 8, "path": "/test/integration/cookbooks/icinga_test/metadata.rb", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "name \"icinga_test\"\nmaintainer \"Kiall Mac Innes\"\nmaintainer_email \"[email protected]\"\nlicense \"Apache 2.0\"\ndescription \"Icinga Test Cookbook\"\nversion \"0.1.0\"\n\ndepends \"icinga\"\n" }, { "alpha_fraction": 0.7237687110900879, "alphanum_fraction": 0.7237687110900879, "avg_line_length": 26.41176414489746, "blob_id": "94b6e0650ab25132cdf9d41e2ad682c6190b3a9a", "content_id": "cc7aff58c1ddd0815c520de70b8f0dad73175a0f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 467, "license_type": "permissive", "max_line_length": 51, "num_lines": 17, "path": "/test/integration/cookbooks/icinga_test/files/default/tests/minitest/client_test.rb", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "\ndescribe 'icinga::client' do\n include MiniTest::Chef::Assertions\n include MiniTest::Chef::Context\n include MiniTest::Chef::Resources\n\n it 'installs the nagios-nrpe-server package' do\n package(\"nagios-nrpe-server\").must_be_installed\n end\n\n it 'enables the nagios-nrpe-server service' do\n service(\"nagios-nrpe-server\").must_be_enabled\n end\n\n # it 'starts the nagios-nrpe-server service' do\n # service(\"nagios-nrpe-server\").must_be_running\n # end\nend\n" }, { "alpha_fraction": 0.7164948582649231, "alphanum_fraction": 0.7164948582649231, "avg_line_length": 21.823530197143555, "blob_id": "56d02ef0aa6d97427c367a06dd9b0adea21833f3", "content_id": "c5b891795fa7e98f28a3d6d27e4652455f78f9d8", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 388, "license_type": "permissive", "max_line_length": 39, "num_lines": 17, "path": "/test/integration/cookbooks/icinga_test/files/default/tests/minitest/server_test.rb", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "describe 'icinga::server' do\n include MiniTest::Chef::Assertions\n include MiniTest::Chef::Context\n include MiniTest::Chef::Resources\n\n it 'installs the icinga package' do\n package(\"icinga\").must_be_installed\n end\n\n it 'enables the icinga service' do\n service(\"icinga\").must_be_enabled\n end\n\n it 'starts the icinga service' do\n service(\"icinga\").must_be_running\n end\nend\n" }, { "alpha_fraction": 0.5764074921607971, "alphanum_fraction": 0.5924932956695557, "avg_line_length": 30.08333396911621, "blob_id": "c596b7e4d2280ad41f6fe0d3cb8f127597498e79", "content_id": "c403b9b265126483cc5159d8ccc51f54359f519b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 373, "license_type": "permissive", "max_line_length": 72, "num_lines": 12, "path": "/metadata.rb", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "name \"icinga\"\nmaintainer \"Kiall Mac Innes\"\nmaintainer_email \"[email protected]\"\nlicense \"Apache 2.0\"\ndescription \"Installs/Configures Icinga\"\nlong_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))\nversion \"2.0.1\"\n\ndepends \"apt\"\ndepends \"apache2\"\ndepends \"search_helper\"\ndepends \"passwords_helper\"\n" }, { "alpha_fraction": 0.5868852734565735, "alphanum_fraction": 0.6065573692321777, "avg_line_length": 14.25, "blob_id": "f8b0d65c09c2880107f32b2c45b129eb73372e59", "content_id": "3446d57793ef94cce3b08b373aa23a036d59d87e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 305, "license_type": "permissive", "max_line_length": 51, "num_lines": 20, "path": "/files/default/plugins/check_pid", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nPIDFILE=$1\n\nif [ ! -f $PIDFILE ]; then\n echo \"UNKNOWN: ${PIDFILE} does not exist\"\n exit 3\nfi\n\nPID=`cat $PIDFILE`\nkill -0 $PID\nRESULT=$?\n\nif [[ \"${RESULT}\" = \"0\" ]]; then\n echo \"OK: Process ID ${PID} is running\"\n exit 0\nelse\n echo \"CRITICAL: Process ID ${PID} is NOT running\"\n exit 2\nfi\n" }, { "alpha_fraction": 0.8064516186714172, "alphanum_fraction": 0.8064516186714172, "avg_line_length": 31, "blob_id": "9c6a0e3069a708720e4126cce6326bd29a66f69f", "content_id": "90e82dd3f8fefd591620dcd9874d2057400b0556", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 31, "license_type": "permissive", "max_line_length": 31, "num_lines": 1, "path": "/test/integration/cookbooks/icinga_test/recipes/server.rb", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "include_recipe \"icinga::server\"" }, { "alpha_fraction": 0.779552698135376, "alphanum_fraction": 0.779552698135376, "avg_line_length": 33.77777862548828, "blob_id": "2e1626703cd1425ca72d2ffe96861b9fddfa0e91", "content_id": "9bd71381cf297e940d2b02db07dc30f943870d68", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 313, "license_type": "permissive", "max_line_length": 96, "num_lines": 9, "path": "/Berksfile", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "site :opscode\n\nmetadata\n\ncookbook \"search_helper\", git: \"https://github.com/moniker-dns/search-helper-cookbook.git\"\ncookbook \"passwords_helper\", git: \"https://github.com/moniker-dns/passwords-helper-cookbook.git\"\n\ncookbook \"icinga_test\", path: \"test/integration/cookbooks/icinga_test\"\ncookbook \"minitest-handler\"\n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 17, "blob_id": "0ee89159a7af9792388306501b5d05042546ac3e", "content_id": "c7922fe76af45e0b05a7922c7105940d3e62ca78", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 18, "license_type": "permissive", "max_line_length": 17, "num_lines": 1, "path": "/README.md", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "# Icinga cookbook\n" }, { "alpha_fraction": 0.7012138366699219, "alphanum_fraction": 0.7152194380760193, "avg_line_length": 30.5, "blob_id": "0be04c6230457569ad2ec49f6f8328383750d711", "content_id": "c47c82bf085e84f447a53280b3b1415a9b18ba64", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2142, "license_type": "permissive", "max_line_length": 126, "num_lines": 68, "path": "/recipes/client.rb", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "# Copyright 2013 Hewlett-Packard Development Company, L.P.\n#\n# Author: Kiall Mac Innes <[email protected]>\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\ninclude_recipe \"icinga::common\"\n\n# Install the NRPE \"server\" package\npackage \"nagios-nrpe-server\" do\n action :upgrade\nend\n\n# Lookup the Icinga servers via search (or the configured hosts if set)\nicinga_servers = search_helper_best_ip(node[:icinga][:server_search], node[:icinga][:server_hosts], false) do |ip, other_node|\n Chef::Log.info \"found icinga server #{other_node}, ip = #{ip}\"\n ip\nend\n\n# pre-provisioned nodes in chef are searchable, but contain little or no data\n# delete them from the search results & use 127.0.0.1 as a fall back ip\nicinga_servers.delete('')\nicinga_servers.delete(nil)\nif icinga_servers.empty? || icinga_servers.nil?\n Chef::Log.info \"icinga_servers is empty, defaulting to 127.0.0.1 for the nrped allowed hosts\"\n icinga_servers = ['127.0.0.1']\nend\n\n# Find all the service/host definitions\nnrpe_commands_db = data_bag_item('icinga', 'nrpe_commands')\n\nnrpe_commands = nrpe_commands_db['nrpe_commands']\n\ntemplate \"/etc/nagios/nrpe.cfg\" do\n source \"client/nrpe.cfg.erb\"\n owner \"root\"\n group \"root\"\n mode 0644\n\n variables(\n :icinga_servers => icinga_servers,\n :nrpe_commands => nrpe_commands\n )\n\n notifies :restart, \"service[nagios-nrpe-server]\"\nend\n\nfile \"/etc/nagios/nrpe_local.cfg\" do\n action :delete\n notifies :restart, \"service[nagios-nrpe-server]\"\nend\n\n\n# Define/Enable/Start the NRPE service\nservice \"nagios-nrpe-server\" do\n supports :restart => true, :status => true, :reload => true\n action [:enable, :start]\nend\n" }, { "alpha_fraction": 0.8064516186714172, "alphanum_fraction": 0.8064516186714172, "avg_line_length": 31, "blob_id": "4263068566320fbc95792dd9da3f002b35019243", "content_id": "accda3a8fe39dc46ad2653274d6a0a2b09a245aa", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 31, "license_type": "permissive", "max_line_length": 31, "num_lines": 1, "path": "/test/integration/cookbooks/icinga_test/recipes/client.rb", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "include_recipe \"icinga::client\"" }, { "alpha_fraction": 0.6721875667572021, "alphanum_fraction": 0.68136066198349, "avg_line_length": 23.60501480102539, "blob_id": "68d1b9319fe10d02610d2103df6150e6d3dcac39", "content_id": "b17c219eb931ff081a6cab4b1f72dce35076731e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7849, "license_type": "permissive", "max_line_length": 110, "num_lines": 319, "path": "/recipes/server.rb", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "# Copyright 2013 Hewlett-Packard Development Company, L.P.\n#\n# Author: Kiall Mac Innes <[email protected]>\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\ninclude_recipe \"apache2\"\ninclude_recipe \"icinga::common\"\n\n# Install the Icinga server package\npackage \"icinga\" do\n action :upgrade\nend\n\nexecute \"dpkg-statoverride-one\" do\n command \"dpkg-statoverride --update --add nagios www-data 2710 /var/lib/icinga/rw\"\n action :run\n\n not_if \"dpkg-statoverride --list /var/lib/icinga/rw\"\n\n notifies :restart, \"service[icinga]\"\nend\n\nexecute \"dpkg-statoverride-two\" do\n command \"dpkg-statoverride --update --add nagios nagios 751 /var/lib/icinga\"\n action :run\n\n not_if \"dpkg-statoverride --list /var/lib/icinga\"\n\n notifies :restart, \"service[icinga]\"\nend\n\npackage \"nagios-nrpe-plugin\" do\n options \"--no-install-recommends\"\n action :upgrade\nend\n\n# Find a listing of all the clients we are to monitor\nicinga_clients = search_helper_best_ip(node[:icinga][:client_search], nil, false) do |ip, other_node|\n hostgroups = [\n \"chef_environment:#{other_node.chef_environment}\",\n\n # TODO: These should not be hardcoded.. 3rd Parties may not have these attrs\n \"#{other_node[:continent]}#{other_node[:area]}#{other_node[:az]}\",\n \"#{other_node[:area]}#{other_node[:az]}\",\n other_node[:area]\n ]\n\n if other_node.attribute?(:roles)\n other_node[:roles].each do |role|\n hostgroups << \"chef_role:#{role}\"\n end\n end\n\n # Peform some cleanup on the extracted information\n hostgroups.delete('')\n hostgroups.compact!\n\n {\n # \"use\" => other_node[:icinga][:client][:host_use],\n \"use\" => \"generic-host\",\n \"host_name\" => other_node[:fqdn],\n \"hostgroups\" => hostgroups,\n \"address\" => ip\n }\nend\n\n# remove any clients with incomplete data\nicinga_clients.reject! do |client|\n client['host_name'].nil? || client['host_name'].empty? || client['address'].nil? || client['address'].empty?\nend\n\n# Find all the service/host definitions\ncommands_db = data_bag_item('icinga', 'commands')\ncontacts_db = data_bag_item('icinga', 'contacts')\nhosts_db = data_bag_item('icinga', 'hosts')\nservices_db = data_bag_item('icinga', 'services')\n\ncommands = commands_db['commands']\ncontacts = contacts_db['contacts']\nhosts = hosts_db['hosts'] + icinga_clients\nservices = services_db['services']\n\n# Prepare some variables to build on\ncontactpasswords = {}\ncontactgroups = []\nhostgroups = []\nservicegroups = []\n\n# Extract some useful information from the contacts for ease of use later\ncontacts.each do |contact|\n # skip over template contacts that don't have a contact_name\n if contact.has_key?('contact_name')\n contactpasswords[contact['contact_name']] = lookup_password('icinga', contact['contact_name'], '*locked*')\n contactgroups += contact.fetch('contactgroups', [])\n end\nend\n\n# Peform some cleanup on the extracted information\ncontactgroups.uniq!\ncontactgroups.sort!\n\n# Extract some useful information from the hosts for ease of use later\nhosts.each do |host|\n hostgroups += host.fetch('hostgroups', [])\nend\n\n# Peform some cleanup on the extracted information\nhostgroups.delete('')\nhostgroups.compact!\nhostgroups.uniq!\nhostgroups.sort!\n\n# Extract some useful information from the services for ease of use later\nservices.each do |service|\n servicegroups += service.fetch('servicegroups', [])\nend\n\n# Peform some cleanup on the extracted information\nservicegroups.uniq!\nservicegroups.sort!\n\n# Log the information we're about to build our templates from\nChef::Log.info(\"Discovered hostgroups: #{hostgroups.join(',')}\")\n\n# Write out configuration templates\ntemplate \"/etc/icinga/apache2.conf\" do\n source \"server/apache2.conf.erb\"\n owner \"root\"\n group \"root\"\n mode 0644\n\n notifies :reload, \"service[apache2]\"\nend\n\ntemplate \"/etc/icinga/cgi.cfg\" do\n source \"server/cgi.cfg.erb\"\n owner \"root\"\n group \"root\"\n mode 0644\n\n notifies :reload, \"service[icinga]\"\nend\n\ntemplate \"/etc/icinga/commands.cfg\" do\n source \"server/commands.cfg.erb\"\n owner \"root\"\n group \"root\"\n mode 0644\n\n variables(\n :commands => commands\n )\n\n notifies :reload, \"service[icinga]\"\nend\n\ntemplate \"/etc/icinga/htpasswd.users\" do\n source \"server/htpasswd.users.erb\"\n owner \"root\"\n group \"www-data\"\n mode 0640\n\n variables(\n :contacts => contacts,\n :contactpasswords => contactpasswords\n )\nend\n\ntemplate \"/etc/icinga/icinga.cfg\" do\n source \"server/icinga.cfg.erb\"\n owner \"root\"\n group \"root\"\n mode 0644\n\n notifies :reload, \"service[icinga]\"\nend\n\ntemplate \"/etc/icinga/resource.cfg\" do\n source \"server/resource.cfg.erb\"\n owner \"nagios\"\n group \"root\"\n mode 0640\n\n notifies :reload, \"service[icinga]\"\nend\n\ntemplate \"/etc/icinga/objects/contactgroups_icinga.cfg\" do\n source \"server/objects/contactgroups_icinga.cfg.erb\"\n owner \"root\"\n group \"root\"\n mode 0644\n\n variables(\n :contactgroups => contactgroups\n )\n\n notifies :reload, \"service[icinga]\"\nend\n\ntemplate \"/etc/icinga/objects/contacts_icinga.cfg\" do\n source \"server/objects/contacts_icinga.cfg.erb\"\n owner \"root\"\n group \"root\"\n mode 0644\n\n variables(\n :contacts => contacts\n )\n\n notifies :reload, \"service[icinga]\"\nend\n\nfile \"/etc/icinga/objects/extinfo_icinga.cfg\" do\n action :delete\n\n notifies :reload, \"service[icinga]\"\nend\n\nfile \"/etc/icinga/objects/generic-host_icinga.cfg\" do\n action :delete\n\n notifies :reload, \"service[icinga]\"\nend\n\nfile \"/etc/icinga/objects/generic-service_icinga.cfg\" do\n action :delete\n\n notifies :reload, \"service[icinga]\"\nend\n\ntemplate \"/etc/icinga/objects/hostgroups_icinga.cfg\" do\n source \"server/objects/hostgroups_icinga.cfg.erb\"\n owner \"root\"\n group \"root\"\n mode 0644\n\n variables(\n :hostgroups => hostgroups\n )\n\n notifies :reload, \"service[icinga]\"\nend\n\ntemplate \"/etc/icinga/objects/hosts_icinga.cfg\" do\n source \"server/objects/hosts_icinga.cfg.erb\"\n owner \"root\"\n group \"root\"\n mode 0644\n\n variables(\n :hosts => hosts,\n :hostgroups => hostgroups\n )\n\n notifies :reload, \"service[icinga]\"\nend\n\nfile \"/etc/icinga/objects/localhost_icinga.cfg\" do\n action :delete\n\n notifies :reload, \"service[icinga]\"\nend\n\ntemplate \"/etc/icinga/objects/servicegroups_icinga.cfg\" do\n source \"server/objects/servicegroups_icinga.cfg.erb\"\n owner \"root\"\n group \"root\"\n mode 0644\n\n variables(\n :servicegroups => servicegroups\n )\n\n notifies :reload, \"service[icinga]\"\nend\n\ntemplate \"/etc/icinga/objects/services_icinga.cfg\" do\n source \"server/objects/services_icinga.cfg.erb\"\n owner \"root\"\n group \"root\"\n mode 0644\n\n variables(\n :services => services,\n :hostgroups => hostgroups\n )\n\n notifies :reload, \"service[icinga]\"\nend\n\ntemplate \"/etc/icinga/objects/timeperiods_icinga.cfg\" do\n source \"server/objects/timeperiods_icinga.cfg.erb\"\n owner \"root\"\n group \"root\"\n mode 0644\n\n notifies :reload, \"service[icinga]\"\nend\n\n# Optional Addons\ninclude_recipe \"icinga::server_pagerduty\"\ninclude_recipe \"icinga::server_hipchat\"\n\n# Define/Enable/Start the Icinga service\nservice \"icinga\" do\n supports :restart => true, :status => true, :reload => true\n action [:enable, :start]\nend\n" }, { "alpha_fraction": 0.7042328119277954, "alphanum_fraction": 0.7148148417472839, "avg_line_length": 20.011110305786133, "blob_id": "49fc581379a42086508e88c4c5124ddb1128ed6c", "content_id": "24b9222db89b5d3ecf1c9a109c163dfec9163083", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1890, "license_type": "permissive", "max_line_length": 75, "num_lines": 90, "path": "/recipes/common.rb", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "# Copyright 2013 Hewlett-Packard Development Company, L.P.\n#\n# Author: Kiall Mac Innes <[email protected]>\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\n# Install some common plugin dep\npackage \"libwww-perl\" do\n action :upgrade\nend\n\npackage \"libcrypt-ssleay-perl\" do\n action :upgrade\nend\n\npackage \"libjson-xs-perl\" do\n action :upgrade\nend\n\npackage \"libjson-perl\" do\n action :upgrade\nend\n\n# Install the Nagios plugin packages\npackage \"nagios-plugins\" do\n action :upgrade\nend\n\npackage \"nagios-plugins-extra\" do\n action :upgrade\nend\n\npackage \"libnagios-plugin-perl\" do\n action :upgrade\nend\n\nif node[:icinga][:install_percona_plugins]\n package \"percona-nagios-plugins\" do\n action :upgrade\n end\nend\n\ndirectory \"/usr/local/lib/nagios\" do\n action :create\nend\n\nremote_directory \"/usr/local/lib/nagios/plugins\" do\n action :create\n source \"plugins\"\n files_mode 0755\nend\n\nremote_directory \"/etc/nagios-plugins/config\" do\n action :create\n source \"plugin-config\"\n files_mode 0644\n\n begin\n notifies :restart, resources(:service => \"icinga\")\n rescue\n end\nend\n\ncookbook_file \"/etc/sudoers.d/nagios_sudoers\" do\n source \"nagios_sudoers\"\n owner \"root\"\n group \"root\"\n mode 0440\n\n begin\n notifies :restart, resources(:service => \"icinga\")\n rescue\n end\n\n begin\n notifies :restart, resources(:service => \"nagios-nrpe-server\")\n rescue\n end\nend" }, { "alpha_fraction": 0.6489707231521606, "alphanum_fraction": 0.6619718074798584, "avg_line_length": 22.66666603088379, "blob_id": "187b4317816bf90a52a8a7e3509a706c136826e8", "content_id": "35089fc2695c8ddd8dc9412d9b9a5e6cee5cc888", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 923, "license_type": "permissive", "max_line_length": 82, "num_lines": 39, "path": "/recipes/server_hipchat.rb", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "hipchat_enabled = node[:icinga][:server][:hipchat_api_token] != nil ? true : false\n\n# Installs HipChat Integration\nif hipchat_enabled\n template \"/etc/icinga/objects/hipchat_icinga.cfg\" do\n source \"server/objects/hipchat_icinga.cfg.erb\"\n owner \"root\"\n group \"root\"\n mode 0644\n\n notifies :reload, \"service[icinga]\"\n end\nelse\n file \"/etc/icinga/objects/hipchat_icinga.cfg\" do\n action :delete\n end\nend\n\ncookbook_file \"/usr/local/bin/hipchat_room_message.sh\" do\n source \"server/hipchat_room_message.sh\"\n owner \"root\"\n group \"root\"\n mode 0755\n\n action hipchat_enabled ? :create : :delete\nend\n\ncookbook_file \"/usr/local/bin/hipchat_icinga.sh\" do\n source \"server/hipchat_icinga.sh\"\n owner \"root\"\n group \"root\"\n mode 0755\n\n action hipchat_enabled ? :create : :delete\nend\n\npackage \"curl\" do\n action hipchat_enabled ? :install : :nothing\nend\n" }, { "alpha_fraction": 0.6670658588409424, "alphanum_fraction": 0.6766467094421387, "avg_line_length": 23.558822631835938, "blob_id": "31c743e1068ece3ab11eba1e94df6356fbb62c15", "content_id": "c335fbe4ffd583aa024f3cad70609bb3cb27930b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 835, "license_type": "permissive", "max_line_length": 88, "num_lines": 34, "path": "/recipes/server_pagerduty.rb", "repo_name": "moniker-dns/icinga-cookbook", "src_encoding": "UTF-8", "text": "pagerduty_enabled = node[:icinga][:server][:pagerduty_service_key] != nil ? true : false\n\n# Installs PagerDuty Integration\nif pagerduty_enabled\n template \"/etc/icinga/objects/pagerduty_icinga.cfg\" do\n source \"server/objects/pagerduty_icinga.cfg.erb\"\n owner \"root\"\n group \"root\"\n mode 0644\n\n notifies :reload, \"service[icinga]\"\n end\nelse\n file \"/etc/icinga/objects/pagerduty_icinga.cfg\" do\n action :delete\n end\nend\n\ncookbook_file \"/usr/local/bin/pagerduty_icinga.pl\" do\n source \"server/pagerduty_icinga.pl\"\n owner \"root\"\n group \"root\"\n mode 0755\n\n action pagerduty_enabled ? :create : :delete\nend\n\ncron \"pagerduty_icinga\" do\n action :create\n user \"nagios\"\n command \"/usr/local/bin/pagerduty_icinga.pl flush\"\n\n action pagerduty_enabled ? :create : :delete\nend\n" } ]
17
jeespinozam/bomberman-ai
https://github.com/jeespinozam/bomberman-ai
d6683f60b440f5974de75754ceab4c47ad925c9c
9f7793df0394d41b6df38999a80fd1f9597a6f52
fdbf3cc8114062100919b4766be01cf7aae6db42
refs/heads/master
2020-03-18T16:36:04.306834
2018-06-20T23:25:18
2018-06-20T23:25:18
134,975,458
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5425342321395874, "alphanum_fraction": 0.5508626103401184, "avg_line_length": 30.716981887817383, "blob_id": "06a9b5a484adc5b60443eebbf2ff11b056a486a1", "content_id": "cd69ba7f71e6e031f8b18114702d9850f817f6e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3362, "license_type": "no_license", "max_line_length": 127, "num_lines": 106, "path": "/plugins/SerpentBombermanGameAgentPlugin/files/helpers/ppo.py", "repo_name": "jeespinozam/bomberman-ai", "src_encoding": "UTF-8", "text": "from tensorforce.agents import PPOAgent\n\nfrom serpent.utilities import SerpentError\n\nimport numpy as np\nimport os\n\n# This file is borrowed from SerpentAIsaacGameAgentPlugin:\n# https://github.com/SerpentAI/SerpentAIsaacGameAgentPlugin/blob/master/files/helpers/ppo.py\nclass SerpentPPO:\n\n def __init__(self, frame_shape=None, game_inputs=None):\n\n if frame_shape is None:\n raise SerpentError(\"A 'frame_shape' tuple kwarg is required...\")\n\n states_spec = {\"type\": \"float\", \"shape\": frame_shape}\n\n if game_inputs is None:\n raise SerpentError(\"A 'game_inputs' dict kwarg is required...\")\n\n self.game_inputs = game_inputs\n self.game_inputs_mapping = self._generate_game_inputs_mapping()\n\n actions_spec = {\"type\": \"int\", \"num_actions\": len(self.game_inputs)}\n\n network_spec = [\n {\"type\": \"conv2d\", \"size\": 1, \"window\": 2, \"stride\": 1},\n {\"type\": \"flatten\"},\n # {\"type\": \"dense\", \"size\": 64},\n {\"type\": \"dense\", \"size\": 6}\n ]\n\n self.agent = PPOAgent(\n states=states_spec,\n actions=actions_spec,\n network=network_spec,\n\n batched_observe=256,\n batching_capacity=1000,\n # BatchAgent\n #keep_last_timestep=True,\n # PPOAgent\n step_optimizer=dict(\n type='adam',\n learning_rate=1e-4\n ),\n optimization_steps=10,\n # Model\n scope='ppo'\n #discount=0.97,\n # DistributionModel\n #distributions=None,\n #entropy_regularization=0.01,\n # PGModel\n #baseline_mode=None,\n #baseline=None,\n #baseline_optimizer=None,\n #gae_lambda=None,\n # PGLRModel\n #likelihood_ratio_clipping=None,\n #summary_spec=summary_spec,\n #distributed_spec=None,\n # More info\n #device=None,\n #session_config=None,\n #saver=None,\n #variable_noise=None,\n #states_preprocessing_spec=None,\n #explorations_spec=None,\n #reward_preprocessing_spec=None,\n #execution=None,\n #actions_exploration=None,\n #update_mode=None,\n #memory=None,\n #subsampling_fraction=0.1\n )\n\n def generate_action(self, game_frame_buffer):\n states = np.stack(\n game_frame_buffer,\n axis=2\n )\n\n # Get prediction from agent, execute\n action = self.agent.act(states)\n label = self.game_inputs_mapping[action]\n\n return action, label, self.game_inputs[label]\n\n def observe(self, reward=0, terminal=False):\n self.agent.observe(reward=reward, terminal=terminal)\n\n def _generate_game_inputs_mapping(self):\n mapping = dict()\n\n for index, key in enumerate(self.game_inputs):\n mapping[index] = key\n\n return mapping\n\n def save_model(self):\n self.agent.save_model(directory=os.path.join(os.getcwd(), \"datasets\", \"bomberman\", \"ppo_model\"), append_timestep=False)\n\n def restore_model(self):\n self.agent.restore_model(directory=os.path.join(os.getcwd(), \"datasets\", \"bomberman\"))\n" }, { "alpha_fraction": 0.5666137933731079, "alphanum_fraction": 0.5741095542907715, "avg_line_length": 36.39706039428711, "blob_id": "624fb5e96e233fa0f60d048c46c58b21e945829e", "content_id": "3ee46c512544137e4e60a5bb39e29c9ae9a26843", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18277, "license_type": "no_license", "max_line_length": 134, "num_lines": 476, "path": "/plugins/SerpentBombermanGameAgentPlugin/files/serpent_Bomberman_game_agent.py", "repo_name": "jeespinozam/bomberman-ai", "src_encoding": "UTF-8", "text": "# import time\r\n# import os\r\n# import pickle\r\n# import serpent.cv\r\n#\r\n# import numpy as np\r\n# import collections\r\n#\r\n# from datetime import datetime\r\n#\r\n#\r\n# from serpent.frame_transformer import FrameTransformer\r\n# from serpent.frame_grabber import FrameGrabber\r\n# from serpent.game_agent import GameAgent\r\n# from serpent.input_controller import KeyboardKey\r\n# from serpent.sprite import Sprite\r\n# from serpent.sprite_locator import SpriteLocator\r\n# from serpent.sprite_identifier import SpriteIdentifier\r\n#\r\n# # from .helpers.game_status import Game\r\n# from .helpers.terminal_printer import TerminalPrinter\r\n# from .helpers.ppo import SerpentPPO\r\n#\r\n#\r\n# import random\r\n#\r\n# class SerpentBombermanGameAgent(GameAgent):\r\n#\r\n# \tdef __init__(self, **kwargs):\r\n# \t\tsuper().__init__(**kwargs)\r\n#\r\n# \t\tself.frame_handlers[\"PLAY\"] = self.handle_play\r\n#\r\n# \t\tself.frame_handler_setups[\"PLAY\"] = self.setup_play\r\n#\r\n# \t\tself.value = None\r\n# \t\tprint(\"Sprites\")\r\n# \t\tprint(type(self.game.sprites))\r\n# \t\tprint(\"game\")\r\n# \t\tprint(self.game)\r\n# \t\tprint(\"game type\")\r\n# \t\tprint(type(self.game))\r\n# \t\tfor i,value in enumerate(self.game.sprites):\r\n# \t\t\tif(i==13):\r\n# \t\t\t\tprint(value)\r\n# \t\t\t\tself.value = value\r\n# \t\tself.spriteGO = self.game.sprites.get(\"SPRITE_GAME_OVER\")\r\n# \t\tself.spriteWO = self.game.sprites.get(\"SPRITE_GAME_WON\")\r\n# \t\t#self.sprite.image_data\r\n# \t\tself.printer = TerminalPrinter()\r\n#\r\n# \tdef setup_play(self):\r\n# \t\tgame_inputs = {\r\n# \t\t\"Move Up\": [KeyboardKey.KEY_UP],\r\n# \t\t\"Move Down\": [KeyboardKey.KEY_DOWN],\r\n# \t\t\"Move Left\": [KeyboardKey.KEY_LEFT],\r\n# \t\t\"Move Right\": [KeyboardKey.KEY_RIGHT],\r\n# \t\t\"Leave Bomb\": [KeyboardKey.KEY_SPACE]\r\n# \t\t}\r\n# \t\tself.game_inputs = game_inputs\r\n#\r\n# \t\t# self.ppo_agent = SerpentPPO(\r\n# \t\t# frame_shape=(480, 549, 4),\r\n# \t\t# game_inputs=game_inputs\r\n# \t\t# )\r\n#\r\n# \t\tself.first_run = True\r\n# \t\tself.game_over = False\r\n# \t\tself.current_attempts = 0\r\n# \t\tself.run_reward = 0\r\n# \t\tself.started_at = datetime.utcnow().isoformat()\r\n# \t\tself.paused_at = None\r\n#\r\n# \t\tprint(\"Enter - Auto Save\")\r\n# \t\tself.input_controller.tap_key(KeyboardKey.KEY_ENTER)\r\n# \t\ttime.sleep(2)\r\n#\r\n# \t\treturn\r\n#\r\n# \tdef extract_game_area(self, frame_buffer):\r\n# \t\tgame_area_buffer = []\r\n#\r\n# \t\tfor game_frame in frame_buffer.frames:\r\n# \t\t\tgame_area = serpent.cv.extract_region_from_image(\r\n# \t\t\tgame_frame.grayscale_frame,\r\n# \t\t\tself.game.screen_regions[\"GAME_REGION\"]\r\n# \t\t\t)\r\n#\r\n# \t\t\tframe = FrameTransformer.rescale(game_area, 0.25)\r\n# \t\t\tgame_area_buffer.append(frame)\r\n#\r\n# \t\treturn game_area_buffer\r\n#\r\n# \tdef handle_play(self, game_frame):\r\n# \t\tif self.first_run:\r\n# \t\t\tself.current_attempts += 1\r\n# \t\t\tself.first_run = False\r\n# \t\t\treturn None\r\n#\r\n# \t\tself.printer.add(\"\")\r\n# \t\tself.printer.add(\"BombermanAI\")\r\n# \t\tself.printer.add(\"Reinforcement Learning: Training a PPO Agent\")\r\n# \t\tself.printer.add(\"\")\r\n# \t\tself.printer.add(f\"Stage Started At: {self.started_at}\")\r\n# \t\tself.printer.add(f\"Current Run: #{self.current_attempts}\")\r\n# \t\tself.printer.add(\"\")\r\n#\r\n# \t\tinputs = [KeyboardKey.KEY_UP,\r\n# \t\t\tKeyboardKey.KEY_DOWN,\r\n# \t\t\tKeyboardKey.KEY_LEFT,\r\n# \t\t\tKeyboardKey.KEY_RIGHT,\r\n# \t\t\tKeyboardKey.KEY_SPACE]\r\n#\r\n# \t\t#game over?\r\n# \t\tsprite_to_locate = Sprite(\"QUERY\", image_data=self.spriteGO.image_data)\r\n#\r\n# \t\tsprite_locator = SpriteLocator()\r\n# \t\tlocationGO = sprite_locator.locate(sprite=sprite_to_locate, game_frame=game_frame)\r\n# \t\tprint(locationGO)\r\n#\r\n# \t\t#won game?\r\n# \t\tsprite_to_locate = Sprite(\"QUERY\", image_data=self.spriteWO.image_data)\r\n# \t\tsprite_locator = SpriteLocator()\r\n# \t\tlocationWO = sprite_locator.locate(sprite=sprite_to_locate, game_frame=game_frame)\r\n# \t\tprint(locationWO)\r\n#\r\n# \t\tprint(type(game_frame))\r\n#\r\n# \t\tif(locationGO!= None or locationWO!= None):\r\n# \t\t\t#enter clic in both cases\r\n# \t\t\tself.input_controller.tap_key(KeyboardKey.KEY_ENTER)\r\n# \t\telse:\r\n# \t\t\tgame_frame_buffer = FrameGrabber.get_frames([0, 1, 2, 3], frame_type=\"PIPELINE\")\r\n# \t\t\tgame_frame_buffer = self.extract_game_area(game_frame_buffer)\r\n# \t\t\taction, label, value = self.ppo_agent.generate_action(game_frame_buffer)\r\n#\r\n# \t\t\tprint(action, label, value)\r\n# \t\t\tself.input_controller.tap_key(value)\r\n\r\n#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\nimport sys\r\nimport time\r\nimport os\r\nimport pickle\r\nimport serpent.cv\r\nimport numpy as np\r\nimport collections\r\nfrom datetime import datetime\r\nfrom serpent.frame_transformer import FrameTransformer\r\nfrom serpent.frame_grabber import FrameGrabber\r\nfrom serpent.game_agent import GameAgent\r\nfrom serpent.input_controller import KeyboardKey\r\nfrom serpent.sprite import Sprite\r\nfrom serpent.sprite_locator import SpriteLocator\r\nfrom serpent.sprite_identifier import SpriteIdentifier\r\nimport skimage.io\r\nfrom serpent.visual_debugger.visual_debugger import VisualDebugger\r\n\r\nfrom .helpers.game_status import Game\r\nfrom .helpers.terminal_printer import TerminalPrinter\r\nfrom .helpers.ppo import SerpentPPO\r\nfrom .helpers.dqn import KerasAgent\r\n\r\nimport random\r\n\r\nclass MyFrame:\r\n def __init__ (self, frame):\r\n self.frame = frame\r\n\r\nclass SerpentBombermanGameAgent(GameAgent):\r\n\r\n def __init__(self, **kwargs):\r\n super().__init__(**kwargs)\r\n\r\n self.frame_handlers['PLAY'] = self.handle_play\r\n\r\n self.frame_handler_setups['PLAY'] = self.setup_play\r\n\r\n self.value = None\r\n #print('Sprites')\r\n #print(type(self.game.sprites))\r\n #print('game')\r\n #print(self.game)\r\n #print('game type')\r\n #print(type(self.game))\r\n\r\n self.spriteGO = self.game.sprites.get('SPRITE_GAME_OVER')\r\n self.spriteWO = self.game.sprites.get('SPRITE_GAME_WON')\r\n self.spriteGirl = self.game.sprites.get('SPRITE_BETTY_0')\r\n\r\n self.printer = TerminalPrinter()\r\n self.visual_debugger = VisualDebugger()\r\n self.gamestate = Game()\r\n\r\n def setup_play(self):\r\n\r\n game_inputs = {\r\n \"MoveUp\": [KeyboardKey.KEY_UP],\r\n \"MoveDown\": [KeyboardKey.KEY_DOWN],\r\n \"MoveLeft\": [KeyboardKey.KEY_LEFT],\r\n \"MoveRight\": [KeyboardKey.KEY_RIGHT],\r\n \"LeaveBomb\": [KeyboardKey.KEY_SPACE],\r\n \"None\": [0]\r\n }\r\n self.game_inputs = game_inputs\r\n self.game_actions = [\r\n KeyboardKey.KEY_UP,\r\n KeyboardKey.KEY_DOWN,\r\n KeyboardKey.KEY_LEFT,\r\n KeyboardKey.KEY_RIGHT,\r\n KeyboardKey.KEY_SPACE,\r\n None]\r\n\r\n ##120, 137\r\n self.dqn_agent = KerasAgent(shape=(104, 136, 1), action_size=len(self.game_actions))\r\n #load model\r\n #self.ppo_agent.restore_model()\r\n\r\n self.first_run = True\r\n\r\n ##states trainning\r\n self.epoch = 1\r\n self.total_reward = 0\r\n\r\n ##state & action\r\n self.prev_state = None\r\n self.prev_action = None\r\n self.prev_reward = 0\r\n\r\n\r\n print(\"Enter - Auto Save\")\r\n self.input_controller.tap_key(KeyboardKey.KEY_ENTER)\r\n self.gamestate.restartState()\r\n time.sleep(2)\r\n\r\n def extract_game_area(self, frame_buffer):\r\n game_area_buffer = []\r\n\r\n for game_frame in frame_buffer.frames:\r\n game_area = \\\r\n serpent.cv.extract_region_from_image(game_frame.grayscale_frame,self.game.screen_regions['GAME_REGION'])\r\n\r\n frame = FrameTransformer.rescale(game_area, 0.25)\r\n game_area_buffer.append(frame)\r\n print(np.array(game_area_buffer).shape)\r\n return np.array(game_area_buffer)\r\n\r\n def convert_to_rgba(self, matrix):\r\n #print(matrix)\r\n new_matrix = []\r\n for x in range(0,len(matrix)):\r\n line = []\r\n for y in range(0,len(matrix[x])):\r\n #pixel\r\n pixel = matrix[x][y]\r\n new_pixel = [pixel[0],pixel[1],pixel[2], 255]\r\n line.append(new_pixel)\r\n new_matrix.append(line)\r\n return np.array(new_matrix)\r\n\r\n\r\n def update_game_state(self, frame):\r\n game_area = \\\r\n serpent.cv.extract_region_from_image(frame,self.game.screen_regions['GAME_REGION'])\r\n #game ...\r\n # 0,0\r\n # 32,32\r\n game_squares = [[None for j in range(0,11)] for i in range(0,15)]\r\n const_offset = 8\r\n const = 32\r\n #game variables\r\n self.gamestate.bombs = [] #{x, y}\r\n self.gamestate.enemies = [] #{x,y}\r\n #force girl to die if not found\r\n girl_found = False\r\n for i in range(0,15):\r\n for j in range(0, 11):\r\n izq = ((j+1)*const - const_offset, (i+1)*const - const_offset)\r\n der = ((j+2)*const + const_offset, (i+2)*const + const_offset)\r\n reg = (izq[0], izq[1], der[0], der[1])\r\n square = serpent.cv.extract_region_from_image(game_area, reg)\r\n square = self.convert_to_rgba(square)\r\n sprite_to_locate = Sprite(\"QUERY\", image_data=square[..., np.newaxis])\r\n sprite = self.sprite_identifier.identify(sprite_to_locate, mode=\"SIGNATURE_COLORS\")\r\n game_squares[i][j] = sprite\r\n if(\"SPRITE_BETTY\" in sprite):\r\n self.girl = {\"x\": i, \"y\": j}\r\n girl_found = True\r\n elif(\"SPRITE_GEORGE\" in sprite):\r\n self.gamestate.enemies.append({\"x\": i, \"y\": j})\r\n elif(\"SPRITE_BOMB\" in sprite):\r\n self.gamestate.bombs.append({\"x\": i, \"y\": j})\r\n self.gamestate.girl_alive = girl_found\r\n self.gamestate.done = not girl_found\r\n return game_squares\r\n\r\n def handle_play(self, game_frame):\r\n #self.printer.add(\"\")\r\n #self.printer.add(\"BombermanAI\")\r\n #self.printer.add(\"Reinforcement Learning: Training a PPO Agent\")\r\n #self.printer.add(\"\")\r\n #self.printer.add(f\"Stage Started At: {self.started_at}\")\r\n #self.printer.add(f\"Current Run: #{self.current_attempts}\")\r\n #self.printer.add(\"\")\r\n #self.check_game_state(game_frame)\r\n\r\n #####################CHECK STATE###########################\r\n #game over?\r\n locationGO = None\r\n sprite_to_locate = Sprite(\"QUERY\", image_data=self.spriteGO.image_data)\r\n sprite_locator = SpriteLocator()\r\n locationGO = sprite_locator.locate(sprite=sprite_to_locate, game_frame=game_frame)\r\n #print(\"Location Game over:\",locationGO)\r\n\r\n #won game?\r\n locationWO = None\r\n sprite_to_locate = Sprite(\"QUERY\", image_data=self.spriteWO.image_data)\r\n sprite_locator = SpriteLocator()\r\n locationWO = sprite_locator.locate(sprite=sprite_to_locate, game_frame=game_frame)\r\n #print(\"Location Game won:\",locationWO)\r\n\r\n self.gamestate.victory = locationWO!= None\r\n self.gamestate.lose = locationGO!=None\r\n self.gamestate.girl_alive = (locationGO== None and locationWO== None)\r\n self.gamestate.done = not self.gamestate.girl_alive\r\n\r\n print(f\"Is alive? {self.gamestate.girl_alive}\")\r\n print(f\"Game over? {self.gamestate.lose}\")\r\n print(f\"Won? {self.gamestate.victory}\")\r\n #####################VISUAL DEBUGGER###########################\r\n for i, game_frame in enumerate(self.game_frame_buffer.frames):\r\n self.visual_debugger.store_image_data(\r\n game_frame.frame,\r\n game_frame.frame.shape,\r\n str(i)\r\n )\r\n\r\n #####################MODEL###########################\r\n #get buffer\r\n frame_buffer = FrameGrabber.get_frames([0, 1, 2, 3], frame_type=\"PIPELINE\")\r\n game_frame_buffer = self.extract_game_area(frame_buffer)\r\n state = game_frame_buffer.reshape(4, 104, 136, 1)\r\n\r\n if(self.gamestate.done):\r\n print(f\"Game over, attemp {self.epoch}\")\r\n if (self.epoch % 10)== 0:\r\n print(\"saving model\")\r\n self.dqn_agent.save_model(f\"bombergirl_epoch_{self.epoch}.model\")\r\n self.printer.save_file()\r\n self.printer.add(f\"{self.gamestate.victory},{self.gamestate.lose},{self.epoch},{self.gamestate.time},{self.total_reward}\")\r\n self.total_reward = 0\r\n self.dqn_agent.remember(self.prev_state, self.prev_action, self.prev_reward, state, True)\r\n self.dqn_agent.replay()\r\n self.input_controller.tap_key(KeyboardKey.KEY_ENTER)\r\n self.epoch += 1\r\n self.total_reward = 0\r\n self.gamestate.restartState()\r\n self.prev_state = None\r\n self.prev_action = None\r\n else:\r\n #update time\r\n self.gamestate.updateTime()\r\n\r\n #print(np.stack(game_frame_buffer,axis=1).shape)\r\n #print(game_frame_buffer.shape)\r\n #print(state.shape)\r\n if(not (self.prev_state is None) and not (self.prev_action is None)):\r\n self.dqn_agent.remember(self.prev_state, self.prev_action, self.prev_reward, state, False)\r\n\r\n #do something\r\n action_index = self.dqn_agent.act(state)\r\n #get key\r\n action = self.game_actions[action_index]\r\n #get random frame from buffer\r\n game_frame_rand = random.choice(frame_buffer.frames).frame\r\n #update enviroment accorind to frame\r\n ###################FUN UPDATE STATE#########################################\r\n game_area = \\\r\n serpent.cv.extract_region_from_image(game_frame_rand,self.game.screen_regions['GAME_REGION'])\r\n #game ...\r\n # 0,0\r\n # 32,32\r\n game_squares = [[None for j in range(0,11)] for i in range(0,15)]\r\n const_offset = 8\r\n const = 32\r\n #game variables\r\n self.gamestate.bombs = [] #{x, y}\r\n self.gamestate.enemies = [] #{x,y}\r\n #force girl to die if not found\r\n girl_found = False\r\n for i in range(0,15):\r\n for j in range(0, 11):\r\n izq = ((j+1)*const - const_offset, (i+1)*const - const_offset)\r\n der = ((j+2)*const + const_offset, (i+2)*const + const_offset)\r\n reg = (izq[0], izq[1], der[0], der[1])\r\n square = serpent.cv.extract_region_from_image(game_area, reg)\r\n square = self.convert_to_rgba(square)\r\n sprite_to_locate = Sprite(\"QUERY\", image_data=square[..., np.newaxis])\r\n sprite = self.sprite_identifier.identify(sprite_to_locate, mode=\"SIGNATURE_COLORS\")\r\n game_squares[i][j] = sprite\r\n if(\"SPRITE_BETTY\" in sprite):\r\n self.girl = {\"x\": i, \"y\": j}\r\n girl_found = True\r\n elif(\"SPRITE_GEORGE\" in sprite):\r\n self.gamestate.enemies.append({\"x\": i, \"y\": j})\r\n elif(\"SPRITE_BOMB\" in sprite):\r\n self.gamestate.bombs.append({\"x\": i, \"y\": j})\r\n elif(\"SPRITE_BONUSES\" in sprite):\r\n self.gamestate.bonus.append({\"x\": i, \"y\": j})\r\n #####################CHECK STATE###########################\r\n #game over?\r\n locationGO = None\r\n sprite_to_locate = Sprite(\"QUERY\", image_data=self.spriteGO.image_data)\r\n sprite_locator = SpriteLocator()\r\n locationGO = sprite_locator.locate(sprite=sprite_to_locate, game_frame=game_frame)\r\n #print(\"Location Game over:\",locationGO)\r\n\r\n #won game?\r\n locationWO = None\r\n sprite_to_locate = Sprite(\"QUERY\", image_data=self.spriteWO.image_data)\r\n sprite_locator = SpriteLocator()\r\n locationWO = sprite_locator.locate(sprite=sprite_to_locate, game_frame=game_frame)\r\n #print(\"Location Game won:\",locationWO)\r\n\r\n self.gamestate.lose = locationGO!=None\r\n self.gamestate.victory = locationWO!= None\r\n self.gamestate.girl_alive = (locationGO== None and locationWO== None)\r\n self.gamestate.done = not self.gamestate.girl_alive\r\n\r\n print(f\"Is alive? {self.gamestate.girl_alive}\")\r\n print(f\"Game over? {self.gamestate.lose}\")\r\n print(f\"Won? {self.gamestate.victory}\")\r\n\r\n ###################REWARD#########################################\r\n\r\n #get reward\r\n reward = self.gamestate.getReward(action_index)\r\n self.total_reward += reward\r\n self.prev_state = state\r\n self.prev_action = action_index\r\n self.prev_reward = reward\r\n\r\n if(action):\r\n self.input_controller.tap_key(action, 0.15 if action_index < 4 else 0.01)\r\n print(f\"Action: {self.gamestate.game_inputs[action_index]}, reward: {reward}, total_reward: {self.total_reward}\")\r\n #action, label, value = self.ppo_agent.generate_action(game_frame_buffer)\r\n #print(action, label, value)\r\n #key, value = random.choice(list(self.game_inputs.items()))\r\n #if(value[0]):\r\n # self.input_controller.tap_key(value[0])\r\n #game_squares = self.extract_game_squares(game_frame.frame)\r\n\r\n\r\n\r\n def check_game_state(self, game_frame):\r\n #game over?\r\n locationGO = None\r\n sprite_to_locate = Sprite(\"QUERY\", image_data=self.spriteGO.image_data)\r\n sprite_locator = SpriteLocator()\r\n locationGO = sprite_locator.locate(sprite=sprite_to_locate, game_frame=game_frame)\r\n print(\"Location Game over:\",locationGO)\r\n #won game?\r\n locationWO = None\r\n sprite_to_locate = Sprite(\"QUERY\", image_data=self.spriteWO.image_data)\r\n sprite_locator = SpriteLocator()\r\n locationWO = sprite_locator.locate(sprite=sprite_to_locate, game_frame=game_frame.frames)\r\n print(\"Location Game won:\",locationWO)\r\n\r\n self.gamestate.girl_alive = (locationGO== None and locationWO== None)\r\n self.gamestate.done = not self.gamestate.girl_alive\r\n self.gamestate.victory = locationWO!= None\r\n\r\n print(f\"Is alive? {self.gamestate.girl_alive}\")\r\n print(f\"Game over? {self.gamestate.lose}\")\r\n print(f\"Won? {self.gamestate.victory}\")\r\n" }, { "alpha_fraction": 0.5554785132408142, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 31.772727966308594, "blob_id": "4d28bc67b18c71225dcd8786a3143cad35366475", "content_id": "f1460f520e1ea9fb209e4e7c2af876496edb8701", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2885, "license_type": "no_license", "max_line_length": 72, "num_lines": 88, "path": "/plugins/SerpentBombermanGameAgentPlugin/files/helpers/dqn.py", "repo_name": "jeespinozam/bomberman-ai", "src_encoding": "UTF-8", "text": "import json\nimport sys\nimport random\nimport os\nimport numpy as np\nfrom collections import deque\nfrom keras.models import Sequential\nfrom keras.layers import *\nfrom keras.optimizers import *\n\n\nclass KerasAgent:\n\n def __init__(self, shape, action_size):\n self.weight_backup = \"bombergirl_weight.model\"\n self.shape = shape\n self.action_size = action_size\n self.memory = deque(maxlen=2000)\n self.learning_rate = 0.001\n self.gamma = 0.95\n self.exploration_rate = 1.0\n self.exploration_min = 0.01\n self.exploration_decay = 0.995\n self.model = self._build_model()\n\n def _build_model(self):\n model = Sequential()\n\n # Convolutions.\n model.add(Conv2D(\n 16,\n kernel_size=(3, 3),\n strides=(1, 1),\n #data_format='channels_first',\n input_shape=self.shape\n ))\n model.add(Activation('relu'))\n model.add(Conv2D(\n 32,\n kernel_size=(3, 3),\n strides=(1, 1),\n data_format='channels_first'\n ))\n model.add(Activation('relu'))\n\n # Dense layers.²\n model.add(Flatten())\n model.add(Dense(256))\n model.add(Activation('relu'))\n model.add(Dense(self.action_size))\n\n model.summary()\n model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate))\n #model.compile(RMSprop(), 'MSE')\n\n if os.path.isfile(self.weight_backup):\n model.load_weights(self.weight_backup)\n self.exploration_rate = self.exploration_min\n\n return model\n\n def save_model(self, name):\n self.model.save(self.weight_backup)\n self.model.save(name)\n\n def act(self, state):\n if np.random.rand() <= self.exploration_rate:\n return random.randrange(self.action_size)\n act_values = self.model.predict(state)\n return np.argmax(act_values[0])\n\n def remember(self, state, action, reward, next_state, done):\n self.memory.append((state, action, reward, next_state, done))\n\n def replay(self, sample_batch_size=256):\n if len(self.memory) < sample_batch_size:\n sample_batch_size=len(self.memory)\n sample_batch = random.sample(self.memory, sample_batch_size)\n for state, action, reward, next_state, done in sample_batch:\n target = reward\n if not done:\n target = (reward + self.gamma *\n np.amax(self.model.predict(next_state)[0]))\n target_f = self.model.predict(state)\n target_f[0][action] = target\n self.model.fit(state, target_f, epochs=1, verbose=0)\n if self.exploration_rate > self.exploration_min:\n self.exploration_rate *= self.exploration_decay\n" }, { "alpha_fraction": 0.48549672961235046, "alphanum_fraction": 0.5329949259757996, "avg_line_length": 22.372880935668945, "blob_id": "2c95c904503d40eaafd2c140f8bba602b40d3421", "content_id": "576f72f85c5b4b3b9a489312b13420469a33ee2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2758, "license_type": "no_license", "max_line_length": 128, "num_lines": 118, "path": "/plugins/SerpentBombermanGamePlugin/files/serpent_Bomberman_game.py", "repo_name": "jeespinozam/bomberman-ai", "src_encoding": "UTF-8", "text": "from serpent.game import Game\n\nfrom .api.api import BombermanAPI\n\nfrom serpent.utilities import Singleton\n\nfrom serpent.game_launchers.web_browser_game_launcher import WebBrowser\n\n\nclass SerpentBombermanGame(Game, metaclass=Singleton):\n\n\tdef __init__(self, **kwargs):\n\t\tkwargs[\"platform\"] = \"web_browser\"\n\n\t\tkwargs[\"window_name\"] = \"Safari\"\n\n\t\tkwargs[\"url\"] = \"http://0.0.0.0:8000\"\n\t\tkwargs[\"browser\"] = WebBrowser.DEFAULT\n\n\t\tsuper().__init__(**kwargs)\n\n\t\tself.api_class = BombermanAPI\n\t\tself.api_instance = None\n\n\t@property\n\tdef screen_regions(self):\n\n\t\t#t\n\t\tdic_offset = {\n\t\t\t\"WINDOWS_CHROME\": {\n\t\t\t\t# \"top\": 81,\n\t\t\t\t# \"left\": 5\n\t\t\t\t\"top\": 0,\n\t\t\t\t\"left\": 0\n\t\t\t}\n\t\t}\n\n\t\toffset = dic_offset[\"WINDOWS_CHROME\"]\n\n\t\tregions = {\n\t\t\t\"GAME_REGION\": (offset[\"top\"], offset[\"left\"], 416 + offset[\"top\"], 544 + offset[\"left\"]), #544x416\n\t\t\t\"GAME_OVER_REGION\": (118 + offset[\"top\"], 163 + offset[\"left\"], 151 + offset[\"top\"], 383 + offset[\"left\"]), #220x33 - 163,118\n\t\t\t\"WIN_REGION\": (118 + offset[\"top\"], 171 + offset[\"left\"], 149 + offset[\"top\"], 372 + offset[\"left\"]), # 201x31 - 171,118\n\t\t}\n\n\t\treturn regions\n\n\t@property\n\tdef ocr_presets(self):\n\t\tpresets = {\n\t\t\t\"SAMPLE_PRESET\": {\n\t\t\t\t\"extract\": {\n\t\t\t\t\t\"gradient_size\": 1,\n\t\t\t\t\t\"closing_size\": 1\n\t\t\t\t},\n\t\t\t\t\"perform\": {\n\t\t\t\t\t\"scale\": 10,\n\t\t\t\t\t\"order\": 1,\n\t\t\t\t\t\"horizontal_closing\": 1,\n\t\t\t\t\t\"vertical_closing\": 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn presets\n\n# from serpent.game import Game\n#\n# from .api.api import BombermanAPI\n#\n# from serpent.utilities import Singleton\n#\n# from serpent.game_launchers.web_browser_game_launcher import WebBrowser\n#\n#\n# class SerpentBombermanGame(Game, metaclass=Singleton):\n#\n# def __init__(self, **kwargs):\n# kwargs[\"platform\"] = \"web_browser\"\n#\n# kwargs[\"window_name\"] = \"Safari\"\n#\n# kwargs[\"url\"] = \"http://0.0.0.0:8000\"\n# kwargs[\"browser\"] = WebBrowser.DEFAULT\n#\n# super().__init__(**kwargs)\n#\n# self.api_class = BombermanAPI\n# self.api_instance = None\n#\n# @property\n# def screen_regions(self):\n# regions = {\n# \"GAME_REGION\": (0, 0, 480, 549), ##545x416\n# \"GAME_OVER_REGION\": (160,160, 225, 404),\n# \"WIN_REGION\": (175,130, 220, 421),\n# }\n#\n# return regions\n#\n# @property\n# def ocr_presets(self):\n# presets = {\n# \"SAMPLE_PRESET\": {\n# \"extract\": {\n# \"gradient_size\": 1,\n# \"closing_size\": 1\n# },\n# \"perform\": {\n# \"scale\": 10,\n# \"order\": 1,\n# \"horizontal_closing\": 1,\n# \"vertical_closing\": 1\n# }\n# }\n# }\n#\n# return presets\n" }, { "alpha_fraction": 0.539375901222229, "alphanum_fraction": 0.5527488589286804, "avg_line_length": 27.04166603088379, "blob_id": "4193da49deabbda10bf342523c3eeaa5ef890a41", "content_id": "0fe44c62b0c7604e03e90b9b9480cc600d87be42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2699, "license_type": "no_license", "max_line_length": 86, "num_lines": 96, "path": "/plugins/SerpentBombermanGameAgentPlugin/files/helpers/game_status.py", "repo_name": "jeespinozam/bomberman-ai", "src_encoding": "UTF-8", "text": "#from .memreader import MemoryReader\nimport time\n\nclass Game:\n enemies = [] #{x,y}\n bombs = [] #{x,y}\n bonus = []\n girl = {\"x\": 0, \"y\": 0}\n start_time = 0\n time = 0\n game_inputs = {\n 0: \"MoveUp\",\n 1: \"MoveDown\",\n 2: \"MoveLeft\",\n 3: \"MoveRight\",\n 4: \"LeaveBomb\",\n 5: \"None\"\n }\n girl_alive = True\n done = False\n lose = False\n victory = False\n\n ##const\n TIME_NORM = 10\n MOVEMENT_RW = 5\n BONUS_RW = 10\n ALIVE_RW = 20\n ENEMIES_NORM = 5\n REWARD_BOMB = 25\n REWARD_VICTORY = 100\n REWARD_LOSE = 50\n\n MAX_DISTANCE = 8\n\n def restartState(self):\n self.girl_alive = True\n self.done = False\n self.lose = False\n self.victory = False\n self.time = 0\n self.start_time = time.time()\n\n def getCurrentTimeNormalized(self):\n return self.time / self.TIME_NORM\n\n def getDistanceNormalized(self, elem1, elem2):\n return abs(elem1['x'] - elem2['x']) + abs(elem1['y'] - elem2['y'])\n\n def updateTime(self):\n self.time = time.time() - self.start_time\n\n def getReward(self, action):\n reward = 0\n # Para castigar por el numero de enemigos\n reward -= self.ENEMIES_NORM*len(self.enemies)\n # Para casticar con el paso del tiempo\n reward -= self.getCurrentTimeNormalized()\n\n # Para castigar/ premiar si la chica está cerca/lejos a una bomba\n for bomb in self.bombs:\n distance = self.getDistanceNormalized(bomb, self.girl)\n if distance < self.MAX_DISTANCE:\n reward -= distance\n else\n reward += distance\n\n if(action == 4):\n # Para premiar que esté colocando una bomba\n reward += self.REWARD_BOMB\n for enemy in self.enemies:\n # Para premiar que la bomba está más cerca a un enemigo\n distance = self.getDistanceNormalized(enemy, self.girl)\n if distance< self.MAX_DISTANCE:\n reward += self.REWARD_BOMB/distance\n\n if(action < 4):\n # Para premiar que se mueve\n reward += self.MOVEMENT_RW\n # Para premiar que esté más cerca a un bonus\n for bonus in self.bonus:\n reward += self.BONUS_RW / self.getDistanceNormalized(bonus, self.girl)\n\n # Para premiar que está jugando\n if(self.girl_alive):\n reward += self.ALIVE_RW\n\n # Para castigar que ha perdido\n if self.lose:\n reward -= self.REWARD_LOSE\n\n # Para premiar que ha ganado\n if self.victory:\n reward += self.REWARD_VICTORY\n\n return reward\n" } ]
5
Jannlk/GLO-2000-TP4
https://github.com/Jannlk/GLO-2000-TP4
2a54ee3cf77c6ef60496f0ab526fb37442be84ce
7ec584c3f5db166192d3be21b3df42ab25a02f9a
73818f8a0bb9386e8999dc6fa54fd84a820e1831
refs/heads/master
2021-08-23T22:30:52.967410
2017-12-06T22:12:11
2017-12-06T22:12:11
112,973,638
0
1
null
2017-12-03T23:44:22
2017-12-03T23:50:55
2017-12-05T23:13:15
Python
[ { "alpha_fraction": 0.6124852895736694, "alphanum_fraction": 0.6239693760871887, "avg_line_length": 27.53781509399414, "blob_id": "07fae31c3e817c6bc875c0e7109babedb1bc859c", "content_id": "53a341c2e4b27258a226e4a99bce30f7bdafbe36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3420, "license_type": "no_license", "max_line_length": 116, "num_lines": 119, "path": "/TP4_111126561/utilitaires.py", "repo_name": "Jannlk/GLO-2000-TP4", "src_encoding": "UTF-8", "text": "import os.path\nimport re\nfrom hashlib import sha256\nfrom os.path import getsize\n\n#Méthode qui crée un nouveau compte dans le répertoire du serveur\n#id : nom du dossier\n#mdp : mot de passe\n#return : \"0\" si un problème est survenu avec le fichier, \"1\" si le compte a été créé\ndef creerCompte(id, mdp):\n state = \"1\"\n try:\n os.makedirs(id)\n file = open(id + \"/config.txt\", \"w\")\n file.write(sha256(mdp.encode()).hexdigest())\n file.close()\n except:\n state = \"0\"\n return state\n\n#Méthode qui vérifie si le compte existe\n#id : Nom du dossier du compte\n#return: \"1\" si le compte existe, \"0\" sinon\ndef verifierID(id):\n state = \"0\"\n if os.path.exists(id + \"/config.txt\"):\n state = \"1\"\n return state\n\n#Méthode qui vérifie si le mot de passe respecte les conditions\n#mdp : le mot de passe\n#return : \"1\" si le mot de passe respecte les conditions, \"0\" sinon.\ndef veififierMDP(mdp):\n state = \"0\"\n if (re.search(r\"^[a-zA-Z0-9]{6,12}$\", mdp) and re.search(r\".*[0-9].*\", mdp) and re.search(r\".*[a-zA-Z].*\",mdp)):\n state = \"1\"\n return state\n\n#Méthode qui permet d'ouvrir le dossier d'un utilisateur\n#id, mdp : L'identifiant et le mot de passe de l'utilisateur\n#Return : \"-1\" s'il y a un problème avec lors de l'ouverture du fichier\n# \"0\" si le mot de passe de correspond pas\n# \"1\" si la connexion est un succès\ndef connexion(id, mdp):\n state = \"1\"\n try:\n file = open(id + \"/config.txt\", \"r\")\n password = file.readline()\n file.close()\n if sha256(mdp.encode()).hexdigest() != password:\n state = \"0\"\n except:\n state = \"-1\"\n\n return state\n\n#Méthode qui permet d'ouvrir le dossier d'un utilisateur\n#id, subject, data: L'identifiant de l'utilisateur, le sujet et corps du message\n#Return : \"-1\" s'il y a un problème avec lors de l'ouverture du fichier\n# \"0\" si tout se passe bien\ndef courrielLocal(id, subject, data):\n state = \"0\"\n try:\n file = open(id + \"/\" + subject + \".txt\", \"w\")\n file.write(data)\n file.close()\n state = \"0\"\n except:\n state = \"-1\"\n\n return state\n\n#Méthode qui permet d'ouvrir un courriel local\n#subject, data: Sujet et corps du courriel\ndef ouvrirLocal(id, filename):\n try:\n file = open( id + \"/\" + filename, \"r\")\n str_content = file.read();\n file.close()\n return str_content\n except:\n print(\"Fichier introuvable.\")\n\n\n\n#Méthode qui permet d'enregistrer un courriel vers un utilisateur inexistant\n#subject, data: Sujet et corps du courriel\ndef courrielDump(subject, data):\n try:\n if not os.path.exists(\"DESTERREUR\"):\n os.makedirs(\"DESTERREUR\")\n file = open(\"DESTERREUR/\" + subject + \".txt\", \"w\")\n file.write(data)\n file.close()\n except:\n print(\"Guess somebody fucked up good.\")\n\n\n#Méthode qui retourne la grosseur d'un directory\n#id: le directory\ndef getSize(id):\n try:\n size = getsize(id)\n return size\n except:\n print(\"Mauvais nom de repertoire\")\n\n\n#Méthode qui retourne la liste trié par date\n#id, liste: la liste a trier\ndef sortDate(id, liste):\n liste.sort(key=lambda x: os.path.getmtime(id + \"/\" + x))\n return liste\n\n#Méthode qui retourne la liste trié alphabetiquement\n#id, liste: la liste a trier\ndef sortAlpha(liste):\n liste = liste.sort()\n return liste\n" }, { "alpha_fraction": 0.5373406410217285, "alphanum_fraction": 0.555389940738678, "avg_line_length": 35.3795166015625, "blob_id": "0c1285671774a4b638f73da6624ce38a8dc1ed75", "content_id": "4325ce54bbc66e749cd26fe851a89d067df7a6da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6047, "license_type": "no_license", "max_line_length": 115, "num_lines": 166, "path": "/TP4_111126561/serveur.py", "repo_name": "Jannlk/GLO-2000-TP4", "src_encoding": "UTF-8", "text": "import smtplib, re, socket, optparse, sys\nimport os.path\nimport pickle\nfrom email.mime.text import MIMEText\nimport utilitaires\n\nparser = optparse.OptionParser()\nparser.add_option(\"-a\", \"--address\", action=\"store\", dest=\"address\", default=\"localhost\")\nparser.add_option(\"-p\", \"--port\", action=\"store\", dest=\"port\", type=int, default=1337)\nopts = parser.parse_args(sys.argv[1:])[0]\n\ndestination = (opts.address, opts.port)\n#Création du socket\nserversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserversocket.bind(destination)\nserversocket.listen(5)\nprint(\"Listening on port \" + str(serversocket.getsockname()[1]))\nnbConnexions = 0\nnbDeconnexions = 0\n\nwhile True:\n #Un client se connecte au serveur\n (s, address) = serversocket.accept()\n nbConnexions += 1\n print(str(nbConnexions) + \"e connexion au serveur\")\n\n #Réception du choix d'option du menu connexion.\n option = s.recv(1024).decode()\n\n #Si l'utilisateur choisit de se connecter\n if option == \"1\":\n\n #On vérifie que le compte existe et que le mot de passe est valide\n id = s.recv(1024).decode()\n mdp = s.recv(1024).decode()\n verificationID = utilitaires.verifierID(id)\n s.send(verificationID.encode())\n if verificationID != \"0\":\n verificationMDP = utilitaires.connexion(id, mdp)\n s.send(verificationMDP.encode())\n\n while verificationID != \"1\" or verificationMDP != \"1\":\n id = s.recv(1024).decode()\n mdp = s.recv(1024).decode()\n verificationID = utilitaires.verifierID(id)\n s.send(verificationID.encode())\n if verificationID != \"0\":\n verificationMDP = utilitaires.connexion(id, mdp)\n s.send(verificationMDP.encode())\n if verificationMDP == \"-1\":\n continue\n\n\n #Si l'utilisateur choisit de se créer un compte\n elif option == \"2\":\n #Création de l'identifiant\n id = s.recv(1024).decode()\n mdp = s.recv(1024).decode()\n verificationID = utilitaires.verifierID(id)\n s.send(verificationID.encode())\n if verificationID != \"1\":\n verificationMDP = utilitaires.veififierMDP(mdp)\n s.send(verificationMDP.encode())\n while verificationID != \"0\" or verificationMDP != \"1\":\n id = s.recv(1024).decode()\n mdp = s.recv(1024).decode()\n verificationID = utilitaires.verifierID(id)\n s.send(verificationID.encode())\n if verificationID != \"1\":\n verificationMDP = utilitaires.veififierMDP(mdp)\n s.send(verificationMDP.encode())\n verificationErreur = utilitaires.creerCompte(id, mdp)\n s.send(verificationErreur.encode())\n if verificationErreur == \"0\":\n continue\n\n\n\n while True:\n # Réception du choix d'option du menu connexion.\n option = s.recv(1024).decode()\n\n #Envoie d'un courriel\n if option == \"1\":\n # reception du courriel et verification qu’il est valide\n emailFrom = s.recv(1024).decode()\n emailAddress = s.recv(1024).decode()\n while not re.search(r\"^[^@]+@[^@]+\\.[^@]+$\", emailAddress):\n msg = \"-1\"\n s.send(msg.encode())\n emailAddress = s.recv(1024).decode()\n msg = \"0\"\n s.send(msg.encode())\n\n # creation du courriel\n subject = s.recv(1024).decode()\n data = s.recv(1024).decode()\n courriel = MIMEText(data)\n courriel[\"From\"] = emailFrom\n courriel[\"To\"] = emailAddress\n courriel[\"Subject\"] = subject\n\n #Externe\n use_smtp_ulaval = False\n if(re.match(r\"^[^@]+@reseauglo\\.ca$\", emailAddress) == None):\n use_smtp_ulaval = True\n\n if use_smtp_ulaval == True:\n\n # envoi du courriel par le smtp de l'ecole\n try:\n smtpConnection = smtplib.SMTP(host=\"smtp.ulaval.ca\", timeout=10)\n smtpConnection.sendmail(courriel[\"From\"], courriel[\"To\"], courriel.as_string())\n smtpConnection.quit()\n msg = \"0\"\n s.send(msg.encode())\n except:\n msg = \"-1\"\n s.send(msg.encode())\n else:\n chemin_dossier = emailAddress.replace(\"@reseauglo.ca\", \"\")\n verification = utilitaires.courrielLocal(chemin_dossier, courriel['Subject'], courriel.as_string())\n if(verification != \"0\"):\n utilitaires.courrielDump(courriel['Subject'], courriel.as_string())\n s.send(verification.encode())\n\n elif option == \"2\":\n id = s.recv(1024).decode()\n files = os.listdir(id)\n files.remove(\"config.txt\")\n files = utilitaires.sortDate(id, files)\n mails = []\n\n for file in files:\n file = file.replace(\".txt\", \"\")\n mails.append(file)\n\n data_string = pickle.dumps(mails)\n s.send(data_string)\n\n email_id = int(s.recv(1024).decode()) - 1\n email_content = utilitaires.ouvrirLocal(id, files[email_id])\n s.send(email_content.encode())\n\n elif option == \"3\":\n id = s.recv(1024).decode()\n filesize = utilitaires.getSize(id)\n s.send(str(filesize).encode())\n files = os.listdir(id)\n files.remove(\"config.txt\")\n files = sorted(files, key=str)\n mails = []\n\n for file in files:\n file = file.replace(\".txt\", \"\")\n print(file)\n mails.append(file)\n\n data_string = pickle.dumps(mails)\n s.send(data_string)\n\n elif option == \"4\":\n nbDeconnexions += 1\n print(str(nbDeconnexions) + \"e deconnexion au serveur\")\n break\n" }, { "alpha_fraction": 0.5231096148490906, "alphanum_fraction": 0.5427660942077637, "avg_line_length": 36.157894134521484, "blob_id": "3759d9129c40f0a42ba0ff1d1610bad357cd1f97", "content_id": "2562c26dc79be015b67607c06789871fc3c80b56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5652, "license_type": "no_license", "max_line_length": 138, "num_lines": 152, "path": "/client.py", "repo_name": "Jannlk/GLO-2000-TP4", "src_encoding": "UTF-8", "text": "import smtplib, re, socket, optparse, sys\nimport os.path\nfrom email.mime.text import MIMEText\nfrom hashlib import sha256\nimport getpass\nimport pickle\n\nparser = optparse.OptionParser()\nparser.add_option(\"-a\", \"--address\", action=\"store\", dest=\"address\", default=\"localhost\")\nparser.add_option(\"-p\", \"--port\", action=\"store\", dest=\"port\", type=int, default=1337)\nopts = parser.parse_args(sys.argv[1:])[0]\n\ndestination = (opts.address, opts.port)\n#Connexion au serveur\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.settimeout(10)\ns.connect(destination)\ns.settimeout(None)\n\nwhile True:\n #Menu de connexion, choix d'une option\n option = input(\"Menu de connexion \\n1. Se connecter \\n2. Creer un compte \\n\")\n while option != \"1\" and option != \"2\":\n option = input(\"Veuillez saisir une option valide:\\n\")\n s.send(option.encode())\n\n #Se connecter\n if option == \"1\":\n id = input(\"Veuillez saisir votre identifiant:\\n\")\n mdp = getpass.getpass(\"Veuillez saisir votre mot de passe:\\n\")\n s.send(id.encode())\n s.send(mdp.encode())\n reponseID = s.recv(1024).decode()\n if reponseID != \"0\":\n reponseMDP = s.recv(1024).decode()\n while reponseID != \"1\" or reponseMDP != \"1\":\n if reponseID != \"1\":\n id = input(\"Veuillez saisir un identifiant valide:\\n\")\n mdp = getpass.getpass(\"Veuillez saisir votre mot de passe:\\n\")\n elif reponseMDP == \"-1\":\n print(\"Desole, un probleme est survenu.\")\n continue\n else:\n print(\"Ce n'est pas le bon mot de passe. Veuillez reessayer.\")\n id = input(\"Veuillez saisir votre identifiant:\\n\")\n mdp = getpass.getpass(\"Veuillez saisir votre mot de passe:\\n\")\n s.send(id.encode())\n s.send(mdp.encode())\n reponseID = s.recv(1024).decode()\n if reponseID != \"0\":\n reponseMDP = s.recv(1024).decode()\n\n\n\n #Créer un compte\n elif option == \"2\":\n id = input(\"Veuillez choisir un identifiant:\\n\")\n mdp = getpass.getpass(\"Veuillez choisir un mot de passe contenant de 6 à 12 carateres, dont au moins une lettre et un chiffre:\\n\")\n s.send(id.encode())\n s.send(mdp.encode())\n reponseID = s.recv(1024).decode()\n if reponseID != \"1\":\n reponseMDP = s.recv(1024).decode()\n while reponseID != \"0\" or reponseMDP != \"1\":\n if reponseID != \"0\":\n id = input(\"Cet identifiant est deja pris, veuillez en choisir un autre:\\n\")\n mdp = getpass.getpass(\"Veuillez saisir votre mot de passe:\\n\")\n else:\n print(\"Ce mot de passe ne respecte pas les conditions, veuilelz en choisir un autre.\")\n id = input(\"Veuillez saisir votre identifiant a nouveau:\\n\")\n mdp = getpass.getpass(\"Veuillez saisir votre nouveau mot de passe:\\n\")\n s.send(id.encode())\n s.send(mdp.encode())\n reponseID = s.recv(1024).decode()\n if reponseID != \"1\":\n reponseMDP = s.recv(1024).decode()\n reponseCreationCompte = s.recv(1024).decode()\n if reponseCreationCompte == \"0\":\n print(\"Desole, un probleme est survenu\")\n continue\n\n\n while True:\n option = input(\"\\nMenu principale\\n1. Envoi de courriels\\n2. Consultation de courriels\\n3. Statistiques\\n4. Quitter\\n\")\n while option not in [\"1\", \"2\", \"3\", \"4\"]:\n option = input(\"Veuillez saisir une option valide:\\n\")\n\n s.send(option.encode())\n\n if option == \"1\":\n email_from = id + \"@reseauglo.ca\"\n s.send(email_from.encode())\n\n response = \"-1\"\n while(response == \"-1\"):\n email_to = input(\"\\nÀ: \")\n s.send(email_to.encode())\n response = s.recv(1024).decode()\n\n subject = input(\"\\nSujet: \")\n s.send(subject.encode())\n data = input(\"\\nMessage: \")\n s.send(data.encode())\n\n response = s.recv(1024).decode()\n if(response == \"-1\"):\n print(\"\\nErreur lors de l'envoie du courriel.\")\n continue\n else:\n print(\"\\nCourriel envoyé avec succès!\")\n elif option == \"2\":\n s.send(id.encode())\n data_string = s.recv(1024)\n mails = pickle.loads(data_string)\n\n print(\"\\nListe de vos courriels: \\n\")\n\n compteur = 1;\n for mail in mails:\n print(\"\\n\" + str(compteur) + \". \" + mail)\n compteur += 1\n\n email_id = input(\"\\nQuel courriel souhaitez-vous visionner? \\n\")\n\n s.send(email_id.encode())\n\n email_content = s.recv(1024).decode()\n print(\"\\n\" + email_content)\n input(\"\\nAppuyez sur Enter pour continuer...\")\n continue\n elif option == \"3\":\n s.send(id.encode())\n\n filesize = s.recv(1024).decode()\n\n data_string = s.recv(1024)\n mails = pickle.loads(data_string)\n\n print(\"\\nNombre de messages: \" + str(len(mails)) + \"\\n\")\n print(\"\\nTaille du repertoire personnel (en octets): \" + filesize + \"\\n\")\n print(\"\\nListe de vos courriels: \\n\")\n\n compteur = 1;\n for mail in mails:\n print(\"\\n\" + str(compteur) + \". \" + mail)\n compteur += 1\n input(\"\\nAppuyez sur Enter pour continuer...\")\n continue\n elif option == \"4\":\n break;\n s.close()\n exit()" }, { "alpha_fraction": 0.7033247947692871, "alphanum_fraction": 0.7289002537727356, "avg_line_length": 34.54545593261719, "blob_id": "8399e216f1d1b06d092ac5c27e2752885a4e2f38", "content_id": "8c0736834fff0f67545bb534f39841089217a22d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 393, "license_type": "no_license", "max_line_length": 91, "num_lines": 11, "path": "/README.md", "repo_name": "Jannlk/GLO-2000-TP4", "src_encoding": "UTF-8", "text": "# GLO-2000-TP4\n\n1. Ouvrir deux CMD et se rendre sur la bonne place (le client peut être séparer du serveur)\n\n2. Dans une des deux, lancer le serveur en executant la commande `C:\\user\\moi> serveur.py`\n\n3. Dans l'autre, lancer le client en executant la commande `C:\\user\\moi> client.py`\n\n4. Se connecter / Creer un compte (mon user c'est gacha et mon mot de passe bruteforce)\n\n5. S'amuser....\n" } ]
4
junprog/contrastive-baseline
https://github.com/junprog/contrastive-baseline
5f904278836391eec353deaea41937c515d0cd51
3fc4e9e0b22d4060b5aed4be432ac54b0dab1cb9
bbf62e0b4117c8aca9e714a2f7c72e0f545cc519
refs/heads/main
2023-02-25T16:28:51.934257
2021-01-15T12:30:14
2021-01-15T12:30:14
324,124,329
0
0
MIT
2020-12-24T10:00:28
2021-01-15T12:17:29
2021-01-15T12:21:55
Python
[ { "alpha_fraction": 0.5529894828796387, "alphanum_fraction": 0.5673595070838928, "avg_line_length": 44.3139533996582, "blob_id": "2c1a1d8ff6efcd38a229e58c2248c7be06b1b02d", "content_id": "f0790814c9855e4262a98ea90950720c484ff590", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3897, "license_type": "permissive", "max_line_length": 85, "num_lines": 86, "path": "/train.py", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "from utils.contrastive_trainer import CoTrainer\nfrom utils.simsiam_trainer import SimSiamTrainer\nimport argparse\nimport os\nimport math\nimport torch\nargs = None\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Train ')\n parser.add_argument('--data-dir', default='/mnt/hdd02/process-ucf',\n help='training data directory')\n parser.add_argument('--save-dir', default='D:/exp_results',\n help='directory to save models.')\n parser.add_argument('--cifar10', action='store_true',\n help='use cifar10 dataset')\n\n parser.add_argument('--SimSiam', action='store_true',\n help='try Simple Siamese Net') \n\n parser.add_argument('--arch', type=str, default='vgg19',\n help='the model architecture [vgg19, vgg19_bn, resnet18]')\n parser.add_argument('--pattern-feature', type=str, default='conv-512x1x1',\n help='the feature to contrast [conv-512x1x1, fc-4096]')\n parser.add_argument('--projection', action='store_true',\n help='use MLP projection')\n parser.add_argument('--prediction', action='store_true',\n help='use MLP prediction')\n parser.add_argument('--mlp-bn', action='store_true',\n help='use MLP Batch Normalization') \n\n parser.add_argument('--lr', type=float, default=1e-2,\n help='the initial learning rate')\n parser.add_argument('--weight-decay', type=float, default=1e-4,\n help='the weight decay')\n parser.add_argument('--momentum', type=float, default=0.9,\n help='the momentum')\n\n parser.add_argument('--div-row', type=int, default=3,\n help='one side`s number of pathes')\n parser.add_argument('--div-col', type=int, default=3,\n help='one side`s number of pathes')\n parser.add_argument('--aug', action='store_true',\n help='the weight decay')\n parser.add_argument('--margin', type=float, default=1.0,\n help='the margin of loss function') \n\n parser.add_argument('--resume', default='',\n help='the path of resume training model')\n parser.add_argument('--max-model-num', type=int, default=30,\n help='max models num to save ')\n parser.add_argument('--check_point', type=int, default=100,\n help='milestone of save model checkpoint')\n\n parser.add_argument('--max-epoch', type=int, default=300,\n help='max training epoch')\n parser.add_argument('--val-epoch', type=int, default=10,\n help='the num of steps to log training information')\n parser.add_argument('--val-start', type=int, default=0,\n help='the epoch start to val')\n\n parser.add_argument('--batch-size', type=int, default=8,\n help='train batch size')\n parser.add_argument('--device', default='0', help='assign device')\n parser.add_argument('--num-workers', type=int, default=8,\n help='the num of training process')\n\n parser.add_argument('--crop-size', type=int, default=224,\n help='the crop size of the train image')\n\n parser.add_argument('--visual-num', type=int, default=4,\n help='the number of visualize images') \n\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n args = parse_args()\n torch.backends.cudnn.benchmark = True\n os.environ['CUDA_VISIBLE_DEVICES'] = args.device.strip('-') # set vis gpu\n if args.SimSiam:\n trainer = SimSiamTrainer(args)\n else:\n trainer = CoTrainer(args)\n trainer.setup()\n trainer.train()\n" }, { "alpha_fraction": 0.5240288376808167, "alphanum_fraction": 0.5720864534378052, "avg_line_length": 45.28415298461914, "blob_id": "f41aef8005a8173b8f072988ee2721d8cde2aac5", "content_id": "f6c766e8d88248d1e81cacbc93ab0c49e48d9e58", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8469, "license_type": "permissive", "max_line_length": 134, "num_lines": 183, "path": "/datasets/cifar10.py", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "from typing import Callable, Optional\nimport random\n\nfrom PIL import Image\nimport numpy as np\n\nimport torch\nimport torchvision\nfrom torchvision import transforms\nfrom torchvision.datasets import CIFAR10\n\nnp.random.seed(765)\nrandom.seed(765)\n\nclass SupervisedPosNegCifar10(torch.utils.data.Dataset):\n def __init__(self, dataset, phase):\n # split by some thresholds here 80% anchors, 20% for posnegs\n lengths = [int(len(dataset)*0.8), int(len(dataset)*0.2)]\n self.anchors, self.posnegs = torch.utils.data.random_split(dataset, lengths)\n \n if phase == 'train':\n self.anchor_transform = transforms.Compose([transforms.Resize(64),\n transforms.RandomResizedCrop(scale=(0.16, 1), ratio=(0.75, 1.33), size=64),\n transforms.RandomHorizontalFlip(0.5),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])\n self.posneg_transform = transforms.Compose([transforms.Resize(64),\n transforms.RandomResizedCrop(scale=(0.16, 1), ratio=(0.75, 1.33), size=64),\n transforms.RandomHorizontalFlip(0.5),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])\n else:\n self.anchor_transform = transforms.Compose([transforms.Resize(64),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])\n self.posneg_transform = transforms.Compose([transforms.Resize(64),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])\n\n def __len__(self):\n return len(self.anchors)\n \n def __getitem__(self, index): \n anchor, label = self.anchors[index]\n if self.anchor_transform is not None:\n anchor = self.anchor_transform(anchor)\n \n # now pair this up with an image from the same class in the second stream\n if random.random() > 0.5:\n A = np.where(np.array(self.posnegs.dataset.targets) == label)[0]\n posneg_idx = np.random.choice(A[np.in1d(A, self.posnegs.indices)])\n posneg, label = self.posnegs[np.where(self.posnegs.indices==posneg_idx)[0][0]]\n target = torch.tensor([1]).long()\n else:\n A = np.where(np.array(self.posnegs.dataset.targets) != label)[0]\n posneg_idx = np.random.choice(A[np.in1d(A, self.posnegs.indices)])\n posneg, label = self.posnegs[np.where(self.posnegs.indices==posneg_idx)[0][0]]\n target = torch.tensor([0]).long()\n\n if self.posneg_transform is not None:\n posneg = self.posneg_transform(posneg)\n\n return anchor, posneg, target, label\n\nclass PosNegCifar10(torch.utils.data.Dataset):\n def __init__(self, dataset, phase):\n # split by some thresholds here 80% anchors, 20% for posnegs\n self.dataset = dataset\n \n if phase == 'train':\n self.anchor_transform = transforms.Compose([transforms.Resize(64),\n transforms.RandomResizedCrop(scale=(0.16, 1), ratio=(0.75, 1.33), size=64),\n transforms.RandomHorizontalFlip(0.5),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])\n self.posneg_transform = transforms.Compose([transforms.Resize(64),\n transforms.RandomResizedCrop(scale=(0.16, 1), ratio=(0.75, 1.33), size=64),\n transforms.RandomHorizontalFlip(0.5),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])\n else:\n self.anchor_transform = transforms.Compose([transforms.Resize(64),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])\n self.posneg_transform = transforms.Compose([transforms.Resize(64),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])\n\n def __len__(self):\n return len(self.dataset)\n \n def __getitem__(self, index): \n anchor, label = self.dataset[index]\n\n # now pair this up with an image from the same class in the second stream\n if random.random() > 0.5:\n posneg = anchor\n target = torch.tensor([1]).long()\n else:\n while True:\n neg_idx = random.randint(0, len(self.dataset)-1)\n if neg_idx != index:\n break\n posneg, label = self.dataset[neg_idx]\n target = torch.tensor([0]).long()\n\n if self.anchor_transform is not None:\n anchor = self.anchor_transform(anchor)\n\n if self.posneg_transform is not None:\n posneg = self.posneg_transform(posneg)\n\n return anchor, posneg, target, label\n\n### Simple Siamese code\n\nimagenet_mean_std = [[0.485, 0.456, 0.406],[0.229, 0.224, 0.225]]\n\nclass SimSiamTransform():\n def __init__(self, image_size, train, mean_std=imagenet_mean_std):\n self.train = train\n if self.train:\n image_size = 224 if image_size is None else image_size # by default simsiam use image size 224\n p_blur = 0.5 if image_size > 32 else 0 # exclude cifar\n # the paper didn't specify this, feel free to change this value\n # I use the setting from simclr which is 50% chance applying the gaussian blur\n # the 32 is prepared for cifar training where they disabled gaussian blur\n self.transform = transforms.Compose([\n transforms.RandomResizedCrop(image_size, scale=(0.2, 1.0)),\n transforms.RandomHorizontalFlip(),\n transforms.RandomApply([transforms.ColorJitter(0.4,0.4,0.4,0.1)], p=0.8),\n transforms.RandomGrayscale(p=0.2),\n transforms.RandomApply([transforms.GaussianBlur(kernel_size=image_size//20*2+1, sigma=(0.1, 2.0))], p=p_blur),\n transforms.ToTensor(),\n transforms.Normalize(*mean_std)\n ])\n\n else:\n self.transform = transforms.Compose([\n transforms.Resize(int(image_size*(8/7)), interpolation=Image.BICUBIC), # 224 -> 256 \n transforms.CenterCrop(image_size),\n transforms.ToTensor(),\n transforms.Normalize(*mean_std)\n ])\n\n def __call__(self, x):\n x1 = self.transform(x)\n x2 = self.transform(x)\n return x1, x2 \n\n\ndef get_simsiam_dataset(args, phase, download=True, debug_subset_size=None):\n if phase == 'train':\n train = True\n transform = SimSiamTransform(args.crop_size, train)\n elif phase == 'val':\n train = False\n transform = SimSiamTransform(args.crop_size, train)\n elif phase == 'linear_train':\n train = True\n transform = transforms.Compose([\n transforms.RandomResizedCrop(args.crop_size, scale=(0.08, 1.0), ratio=(3.0/4.0,4.0/3.0), interpolation=Image.BICUBIC),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(*imagenet_mean_std)\n ])\n elif phase == 'linear_val':\n train = False\n transform = transforms.Compose([\n transforms.Resize(int(args.crop_size*(8/7)), interpolation=Image.BICUBIC), # 224 -> 256 \n transforms.CenterCrop(args.crop_size),\n transforms.ToTensor(),\n transforms.Normalize(*imagenet_mean_std)\n ])\n\n dataset = torchvision.datasets.CIFAR10(root=\"CIFAR10_Dataset\", train=train, transform=transform, download=download)\n\n if debug_subset_size is not None:\n dataset = torch.utils.data.Subset(dataset, range(0, debug_subset_size)) # take only one batch\n dataset.classes = dataset.dataset.classes\n dataset.targets = dataset.dataset.targets\n\n return dataset" }, { "alpha_fraction": 0.5720984935760498, "alphanum_fraction": 0.5955451130867004, "avg_line_length": 34.58333206176758, "blob_id": "7fce29e2bd6d5d87d47d69895b8621a51ef1efee", "content_id": "6477d45c6d509478dd039d4aaeea81e938878dcb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 853, "license_type": "permissive", "max_line_length": 119, "num_lines": 24, "path": "/models/l2_contrastive_loss.py", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass L2ContrastiveLoss(nn.Module):\n \"\"\"\n Contrastive loss\n Takes embeddings of two samples and a target label == 1 if samples are from the same class and label == 0 otherwise\n Args : \n output1 & output2 : [N, dim]\n target : [N]\n \"\"\"\n\n def __init__(self, margin=1.0):\n super().__init__()\n self.margin = margin\n self.eps = 1e-9\n\n def forward(self, output1, output2, target, size_average=True):\n target = target.squeeze()\n distances = (output2 - output1).pow(2).sum(1) # squared distances\n losses = 0.5 * (target.float() * distances +\n (1 + -1 * target).float() * F.relu(self.margin - (distances + self.eps).sqrt()).pow(2))\n return losses.mean() if size_average else losses.sum()" }, { "alpha_fraction": 0.5382601618766785, "alphanum_fraction": 0.5737011432647705, "avg_line_length": 29.660493850708008, "blob_id": "409829f540f3166ee52f9b5c990966f2f0f0b14e", "content_id": "a5b60f10b963c9a8d6bc5bdfd5d56ebb9a885886", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4966, "license_type": "permissive", "max_line_length": 92, "num_lines": 162, "path": "/datasets/spatial.py", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "# in : original image\n# out : cropped img1 (anchor)\n# cropped img2 (compete)\n# target (positive img1 - img2 : 1, negative img1 - img2 : 0)\n\nimport os\nfrom glob import glob\nimport random\n\nimport numpy as np\nfrom PIL import Image\nfrom PIL import ImageFilter\n\nimport torch\nimport torch.utils.data as data\nimport torchvision.transforms.functional as F\nfrom torchvision import transforms\n\nrandom.seed(765)\n\ndef divide_patches(img, row, col):\n patche_size_w = int(img.size[0] / col) \n patche_size_h = int(img.size[1] / row)\n\n patches = []\n for cnt_i, i in enumerate(range(0, img.size[1], patche_size_h)):\n if cnt_i == row:\n break\n for cnt_j, j in enumerate(range(0, img.size[0], patche_size_w)):\n if cnt_j == col:\n break\n box = (j, i, j+patche_size_w, i+patche_size_h)\n patches.append(img.crop(box))\n\n return patches\n\ndef create_pos_pair(patches):\n idx = random.randint(0, len(patches)-1)\n img1 = patches[idx]\n img2 = patches[idx]\n target = np.array([1])\n return img1, img2, target\n\ndef create_neg_pair(patches):\n idx = random.sample(range(0, len(patches)-1), k=2)\n img1 = patches[idx[0]]\n img2 = patches[idx[1]]\n target = np.array([0])\n return img1, img2, target\n\ndef random_crop(im_h, im_w, crop_h, crop_w):\n res_h = im_h - crop_h\n res_w = im_w - crop_w\n i = random.randint(0, res_h)\n j = random.randint(0, res_w)\n return i, j, crop_h, crop_w\n\nclass GaussianBlur(object):\n \"\"\"Gaussian blur augmentation in SimCLR https://arxiv.org/abs/2002.05709\"\"\"\n\n def __init__(self, sigma=[.1, 2.]):\n self.sigma = sigma\n\n def __call__(self, x):\n sigma = random.uniform(self.sigma[0], self.sigma[1])\n x = x.filter(ImageFilter.GaussianBlur(radius=sigma))\n return x\n\nclass PosNegSpatialDataset(data.Dataset):\n # divide_num : 3 -> 3x3= 9 paches\n def __init__(self, data_path, crop_size, divide_num=(3,3), aug=True):\n self.data_path = data_path\n self.im_list = sorted(glob(os.path.join(self.data_path, '*.jpg')))\n\n self.c_size = crop_size\n self.d_row = divide_num[0]\n self.d_col = divide_num[1]\n\n if aug:\n self.aug = transforms.Compose([\n transforms.CenterCrop(self.c_size),\n transforms.RandomApply([transforms.ColorJitter(0.4, 0.4, 0.4, 0.1)], p=0.8),\n transforms.RandomGrayscale(p=0.2),\n transforms.RandomApply([GaussianBlur([.1, 2.])], p=0.5),\n transforms.RandomHorizontalFlip()\n ])\n else:\n self.aug = transforms.CenterCrop(self.c_size)\n\n self.trans = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n def __len__(self):\n return len(self.im_list)\n\n def __getitem__(self, index):\n img_path = self.im_list[index]\n img = Image.open(img_path).convert('RGB')\n patches = divide_patches(img, self.d_row, self.d_col)\n\n if random.random() > 0.5:\n img1, img2, target = create_pos_pair(patches)\n else:\n img1, img2, target = create_neg_pair(patches)\n\n img1 = self.aug(img1)\n img2 = self.aug(img2)\n\n target = torch.from_numpy(target).long()\n\n img1 = self.trans(img1)\n img2 = self.trans(img2)\n\n return img1, img2, target, None\n\nclass SpatialDataset(data.Dataset):\n # divide_num : 3 -> 3x3= 9 paches\n def __init__(self, phase, data_path, crop_size, divide_num=(3,3), aug=True):\n \n with open(os.path.join(data_path, '{}.txt'.format(phase)), 'r') as f:\n im_list = f.readlines()\n\n self.im_list = [im_name.replace('\\n', '') for im_name in im_list]\n\n self.c_size = crop_size\n self.d_row = divide_num[0]\n self.d_col = divide_num[1]\n\n self.trans = transforms.Compose([\n transforms.RandomApply([transforms.ColorJitter(0.4, 0.4, 0.4, 0.1)], p=0.8),\n transforms.RandomGrayscale(p=0.2),\n transforms.RandomApply([GaussianBlur([.1, 2.])], p=0.5),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n\n def __len__(self):\n return len(self.im_list)\n\n def __getitem__(self, index):\n img_path = self.im_list[index]\n img = Image.open(img_path).convert('RGB')\n patches = divide_patches(img, self.d_row, self.d_col)\n\n img1, img2, label = create_pos_pair(patches)\n\n assert img1.size == img2.size\n wd, ht = img1.size\n i, j, h, w = random_crop(ht, wd, self.c_size, self.c_size)\n img1 = F.crop(img1, i, j, h, w)\n img2 = F.crop(img2, i, j, h, w)\n\n img1 = self.trans(img1)\n img2 = self.trans(img2)\n\n imgs = (img1, img2)\n\n return imgs, label" }, { "alpha_fraction": 0.5771840810775757, "alphanum_fraction": 0.6128074526786804, "avg_line_length": 22.828283309936523, "blob_id": "e5f3177e9eda444f89d80968ad16fa1e3c749a75", "content_id": "04c5ac858ba58b95d6f2510a4ea380eada7d8a7a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2358, "license_type": "permissive", "max_line_length": 81, "num_lines": 99, "path": "/exp.py", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "import torch\nimport torchvision\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nimport random\n\nmodel = torchvision.models.__dict__['vgg19']()\nprint(model)\n\nimg = torch.rand(1,3,256,256)\nout = model.features(img)\nprint(out.size())\n\nimport torchvision.transforms as trans\n\ncrop = trans.RandomCrop(224)\nimg = torch.rand(1,3,256,256)\n\nout = crop(img)\nprint(out.size())\n\ndef divide_patches(img, row, col):\n patche_size_w = int(img.size[0] / col) \n patche_size_h = int(img.size[1] / row)\n\n patches = []\n for cnt_i, i in enumerate(range(0, img.size[1], patche_size_h)):\n if cnt_i == row:\n break\n for cnt_j, j in enumerate(range(0, img.size[0], patche_size_w)):\n if cnt_j == col:\n break\n box = (j, i, j+patche_size_w, i+patche_size_h)\n patches.append(img.crop(box))\n\n return patches\n\ndef display_images(\n images: [Image], \n row=3, col=3, width=10, height=4, max_images=15, \n label_wrap_length=50, label_font_size=8):\n\n if not images:\n print(\"No images to display.\")\n return \n\n if len(images) > max_images:\n print(f\"Showing {max_images} images of {len(images)}:\")\n images=images[0:max_images]\n\n height = max(height, int(len(images)/col) * height)\n plt.figure(figsize=(width, height))\n for i, image in enumerate(images):\n\n plt.subplot(row, col, i + 1)\n plt.imshow(image)\n\n plt.show()\n\nimage = Image.open(\"/mnt/hdd02/shibuya_scramble/image_000294.jpg\").convert(\"RGB\")\n\np = divide_patches(image, 2, 3)\nprint(len(p))\n\ndisplay_images(p, row=2, col=3)\n\ndef create_pos_pair(patches):\n idx = random.randint(0, len(patches)-1)\n img1 = patches[idx]\n img2 = patches[idx]\n label = 1\n return img1, img2, label\n\ndef create_neg_pair(patches):\n idx = random.sample(range(0, len(patches)-1), k=2)\n img1 = patches[idx[0]]\n img2 = patches[idx[1]]\n label = 0\n return img1, img2, label\n\ndef get_img(img):\n patches = divide_patches(img, 3, 2)\n\n if random.random() > 0.5:\n img1, img2, label = create_pos_pair(patches)\n else:\n img1, img2, label = create_neg_pair(patches)\n\n return img1, img2, label\n\nres = []\nfor i in range(10):\n img1, img2, label = get_img(image)\n flag = False\n if img1 == img2:\n flag = True\n res.append([flag, label])\n\nprint(res)" }, { "alpha_fraction": 0.5285714268684387, "alphanum_fraction": 0.5459627509117126, "avg_line_length": 29.961538314819336, "blob_id": "a7e8d6a7dc10eb6d1e2da2ddc3402e4111a01540", "content_id": "fe93008e03d273ff7ff5fb1e942e5b7cc064bd49", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1610, "license_type": "permissive", "max_line_length": 84, "num_lines": 52, "path": "/models/create_linear_eval_model.py", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "import os\nfrom collections import OrderedDict\n\nimport torch\nimport torch.nn as nn\nimport torchvision.models as models\n\nclass LinearEvalModel(nn.Module):\n def __init__(self, arch='vgg19', dim=512, num_classes=10):\n super().__init__()\n\n if arch == 'vgg19':\n self.features = models.vgg19().features\n if arch == 'vgg19_bn':\n self.features = models.vgg19_bn().features\n elif arch == 'resnet18':\n resnet18 = models.resnet18(pretrained=False)\n self.features = nn.Sequential(*list(resnet18.children())[:-1])\n\n self.avg_pool = nn.AdaptiveAvgPool2d((1,1))\n\n self.fc = nn.Linear(dim, num_classes)\n\n def weight_init(self, weight_path, device, arch):\n state_dict = torch.load(os.path.join(weight_path, 'best_model.pth'), device)\n new_state_dict = OrderedDict()\n\n if 'resnet' in arch:\n for k, v in state_dict.items():\n if 'encoder' in k:\n k = k.replace('encoder.', '')\n new_state_dict[k] = v\n\n self.features.load_state_dict(new_state_dict)\n elif 'vgg' in arch:\n for k, v in state_dict.items():\n if 'encoder' in k:\n k = k.replace('encoder.0.', '')\n new_state_dict[k] = v\n\n self.features.load_state_dict(new_state_dict)\n\n for m in self.features.parameters():\n m.requires_grad = False\n\n def forward(self, x):\n x = self.features(x)\n x = self.avg_pool(x)\n x = x.squeeze()\n out = self.fc(x)\n\n return out\n" }, { "alpha_fraction": 0.496614009141922, "alphanum_fraction": 0.5282167196273804, "avg_line_length": 25.84848403930664, "blob_id": "c2e5253bfb6ce33a00f27a9303d5f34f2dbe4251", "content_id": "392d43e52e27e0d5e92c5e839688c0cf004e5e58", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 886, "license_type": "permissive", "max_line_length": 66, "num_lines": 33, "path": "/models/cosine_contrastive_loss.py", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F \n\n\ndef D(p, z, version='simplified'): # negative cosine similarity\n if version == 'original':\n z = z.detach() # stop gradient\n p = F.normalize(p, dim=1) # l2-normalize \n z = F.normalize(z, dim=1) # l2-normalize \n return -(p*z).sum(dim=1).mean()\n\n elif version == 'simplified':\n return - F.cosine_similarity(p, z.detach(), dim=-1).mean()\n else:\n raise Exception\n\nclass CosineContrastiveLoss(nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self, z1, z2, p1, p2):\n if z1.dim() != 2:\n z1 = z1.squeeze()\n if z2.dim() != 2:\n z2 = z2.squeeze()\n\n if p1 is not None or p2 is not None:\n loss = D(p1, z2) / 2 + D(p2, z1) / 2\n else:\n loss = D(z1, z2)\n\n return loss\n" }, { "alpha_fraction": 0.5410783290863037, "alphanum_fraction": 0.5526315569877625, "avg_line_length": 25.86206817626953, "blob_id": "9925ef3e9c4ed76ff69d9127e090f2f043c8e56d", "content_id": "a3c93b7ccab11100db7a0dfacbac036f7be7c181", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1558, "license_type": "permissive", "max_line_length": 88, "num_lines": 58, "path": "/utils/helper.py", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "import os\nimport numpy as np\nimport torch\n\ndef worker_init_fn(worker_id): \n np.random.seed(np.random.get_state()[1][0] + worker_id)\n\nclass Save_Handle(object):\n \"\"\"handle the number of \"\"\"\n def __init__(self, max_num):\n self.save_list = []\n self.max_num = max_num\n\n def append(self, save_path):\n if len(self.save_list) < self.max_num:\n self.save_list.append(save_path)\n else:\n remove_path = self.save_list[0]\n del self.save_list[0]\n self.save_list.append(save_path)\n if os.path.exists(remove_path):\n os.remove(remove_path)\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = 1.0 * self.sum / self.count\n\n def get_avg(self):\n return self.avg\n\n def get_count(self):\n return self.count\n\n## cannot use in training\[email protected]_grad()\ndef accuracy(meter, output1, output2, target):\n \"\"\"Computes the accuracy overthe predictions\"\"\"\n\n for logit in [output1, output2]:\n corrects = (torch.max(logit, 1)[1].data == target.squeeze().long().data).sum()\n accu = float(corrects) / float(target.size()[0])\n meter.update(accu)\n\n return meter\n" }, { "alpha_fraction": 0.5089552402496338, "alphanum_fraction": 0.5395522117614746, "avg_line_length": 32.092594146728516, "blob_id": "17b79746578ee43f936b395df46104096d72fdce", "content_id": "25b07c5cf2dc6abb6296bb88aea7bf117021453e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5406, "license_type": "permissive", "max_line_length": 96, "num_lines": 162, "path": "/utils/visualizer.py", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "import os\nimport numpy as np\nfrom PIL import Image\n\nimport torch\n\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import pyplot as plt\n\n### torch テンソル(バッチ)を受け取って、args.div_numに応じて、描画する\n\nmean = np.array([0.485, 0.456, 0.406])\nstd = np.array([0.229, 0.224, 0.225])\n\ndef invnorm(img, N):\n img = img[N,:,:,:].to('cpu').detach().numpy().copy()\n img = img.transpose(1,2,0)\n img = img*std+mean\n return img\n\nclass ImageDisplayer:\n def __init__(self, args, save_fir):\n # N is number of batch to display\n self.args = args\n self.save_dir = save_fir\n self.N = args.visual_num\n\n @torch.no_grad()\n def __call__(self, epoch, prefix, img1, img2, target):\n imgs1 = []\n imgs2 = []\n targets = []\n for n in range(self.N):\n imgs1.append(invnorm(img1,n))\n imgs2.append(invnorm(img2,n))\n if target is not None:\n targets.append(target[n].item())\n else:\n targets = None\n\n self.display_images(epoch, prefix, imgs1, imgs2, targets)\n\n def display_images(self, epoch, prefix, images1: [Image], images2: [Image], targets, \n columns=2, width=8, height=8, label_wrap_length=50, label_font_size=8):\n\n if not (images1 and images2):\n print(\"No images to display.\")\n return \n\n height = max(height, int(len(images1)/columns) * height)\n plt.figure(figsize=(width, height))\n i = 1\n if targets is not None:\n for (im1, im2, tar) in zip(images1, images2, targets):\n im1 = Image.fromarray(np.uint8(im1*255))\n im2 = Image.fromarray(np.uint8(im2*255))\n\n plt.subplot(self.N, 2, i)\n plt.title(tar, fontsize=20) \n plt.imshow(im1)\n i += 1\n plt.subplot(self.N, 2, i)\n plt.title(tar, fontsize=20) \n plt.imshow(im2)\n i += 1\n else:\n for (im1, im2) in zip(images1, images2):\n im1 = Image.fromarray(np.uint8(im1*255))\n im2 = Image.fromarray(np.uint8(im2*255))\n\n plt.subplot(self.N, 2, i)\n plt.imshow(im1)\n i += 1\n plt.subplot(self.N, 2, i) \n plt.imshow(im2)\n i += 1\n \n plt.tight_layout()\n output_img_name = 'imgs_{}_{}.png'.format(prefix, epoch)\n plt.savefig(os.path.join(self.save_dir, 'images', output_img_name))\n plt.close()\n\nclass EmbeddingDisplayer:\n def __init__(self, args, save_fir):\n\n self.args = args\n self.save_dir = save_fir\n self.cifar10_classes = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n self.colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728',\n '#9467bd', '#8c564b', '#e377c2', '#7f7f7f',\n '#bcbd22', '#17becf']\n\n @torch.no_grad()\n def __call__(self, embeddings, targets, epoch, prefix, xlim=None, ylim=None):\n embeddings = embeddings.to('cpu').detach().numpy().copy()\n targets = targets.to('cpu').detach().numpy().copy()\n plt.figure(figsize=(10,10))\n for i in range(10):\n inds = np.where(targets==i)[0]\n plt.scatter(embeddings[inds,0], embeddings[inds,1], alpha=0.5, color=self.colors[i])\n if xlim:\n plt.xlim(xlim[0], xlim[1])\n if ylim:\n plt.ylim(ylim[0], ylim[1])\n plt.legend(self.cifar10_classes)\n output_img_name = 'emb_{}_{}.png'.format(prefix, epoch)\n plt.savefig(os.path.join(self.save_dir, 'images', output_img_name))\n plt.close()\n\nclass LossGraphPloter:\n def __init__(self, save_fir):\n self.save_dir = save_fir\n self.epochs = []\n self.losses = []\n\n def __call__(self, epoch, loss, prefix):\n self.epochs.append(epoch)\n self.losses.append(loss)\n output_img_name = '{}_loss.svg'.format(prefix)\n\n plt.plot(self.epochs, self.losses)\n plt.title('Loss')\n plt.savefig(os.path.join(self.save_dir, 'images', output_img_name))\n plt.close()\n\nclass AccLossGraphPloter:\n def __init__(self, save_fir):\n self.save_dir = save_fir\n self.tr_accs = []\n self.vl_accs = []\n self.tr_losses = []\n self.vl_losses = []\n self.epochs = []\n\n def __call__(self, epoch, tr_acc, vl_acc, tr_loss, vl_loss, prefix):\n self.tr_accs.append(tr_acc)\n self.vl_accs.append(vl_acc)\n self.tr_losses.append(tr_loss)\n self.vl_losses.append(vl_loss)\n\n self.epochs.append(epoch)\n output_img_name = '{}_eval.svg'.format(prefix)\n\n fig, (axL, axR) = plt.subplots(ncols=2, figsize=(10,4))\n\n axL.plot(self.epochs, self.tr_accs, label='train')\n axL.plot(self.epochs, self.vl_accs, label='val')\n axL.set_title('Top-1 Accuracy')\n axL.set_xlabel('epoch')\n axL.set_ylabel('acc [%]')\n axL.legend(loc=\"lower right\")\n\n axR.plot(self.epochs, self.tr_losses, label='train')\n axR.plot(self.epochs, self.vl_losses, label='val')\n axR.set_title('Loss')\n axR.set_xlabel('epoch')\n axR.set_ylabel('loss')\n axR.legend(loc=\"upper right\")\n\n plt.savefig(os.path.join(self.save_dir, 'images', output_img_name))\n plt.close()" }, { "alpha_fraction": 0.5905511975288391, "alphanum_fraction": 0.6988189220428467, "avg_line_length": 62.5, "blob_id": "ef9843610893b360f8f72c1bb061fcd07ae544f7", "content_id": "36310358a6e5ff210993402e8b4a0f07856237d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 508, "license_type": "permissive", "max_line_length": 131, "num_lines": 8, "path": "/train.sh", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "##!/bin/sh\n\npython train.py --cifar10 --batch-size 512 --lr 1e-2 --SimSiam --crop-size 32 --prediction --projection --arch resnet18 ## resnet18\n\npython train.py --cifar10 --batch-size 512 --lr 1e-2 --SimSiam --crop-size 32 --prediction --projection --arch vgg19_bn ## vgg19_bn\n#python linear_eval.py --save-dir D:/exp_results/0114-223028-vgg19_bn --arch vgg19_bn --crop-size 32\n\npython train.py --cifar10 --batch-size 512 --lr 1e-2 --SimSiam --crop-size 32 --prediction --projection --arch vgg19_bn ## vgg19\n" }, { "alpha_fraction": 0.5771248936653137, "alphanum_fraction": 0.5813221335411072, "avg_line_length": 30.766666412353516, "blob_id": "054832b39f0f8a29cd5a28c177ab08cb016b40fe", "content_id": "3c3c34ad6b91ce477e616b9597c00382300ca7c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 953, "license_type": "permissive", "max_line_length": 91, "num_lines": 30, "path": "/train_val_split.py", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "import os\nfrom glob import glob\n\nimport numpy as np\nimport argparse\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Test ')\n parser.add_argument('--data-dir', default='/mnt/hdd02/shibuya_scramble',\n help='original data directory')\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n args = parse_args()\n\n ## Random Train-Val split\n\n im_list = sorted(glob(os.path.join(args.data_dir, '*.jpg')))\n im_list = [im_name for im_name in im_list]\n\n tr_im_list = list(np.random.choice(im_list, size=int(len(im_list)*0.8), replace=False))\n vl_im_list = list(set(im_list) - set(tr_im_list))\n\n for phase in ['train', 'val']:\n with open(os.path.join(args.data_dir, './{}.txt'.format(phase)), mode='w') as f:\n if phase == 'train':\n f.write('\\n'.join(tr_im_list))\n elif phase == 'val':\n f.write('\\n'.join(vl_im_list))\n" }, { "alpha_fraction": 0.5506262183189392, "alphanum_fraction": 0.5626980662345886, "avg_line_length": 41.21656036376953, "blob_id": "fcdce691afce3ec2635c0b8d6367afdd0e4fe894", "content_id": "e881f56ad1a8df4ad011534631a4c3ff6247f4b6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6627, "license_type": "permissive", "max_line_length": 127, "num_lines": 157, "path": "/utils/simsiam_trainer.py", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport time\nimport logging\n\nimport numpy as np\n\nimport torch\nfrom torch import optim\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import DataLoader\nimport torchvision.models as models\nimport torchvision.datasets as datasets\n\nfrom models.simple_siamese_net import SiameseNetwork\nfrom models.cosine_contrastive_loss import CosineContrastiveLoss\nfrom utils.trainer import Trainer\nfrom utils.helper import Save_Handle, AverageMeter, worker_init_fn\nfrom utils.visualizer import ImageDisplayer, LossGraphPloter\nfrom datasets.spatial import SpatialDataset\nfrom datasets.cifar10 import PosNegCifar10, get_simsiam_dataset\n\nclass SimSiamTrainer(Trainer):\n def setup(self):\n \"\"\"initialize the datasets, model, loss and optimizer\"\"\"\n args = self.args\n self.vis = ImageDisplayer(args, self.save_dir)\n self.tr_graph = LossGraphPloter(self.save_dir)\n self.vl_graph = LossGraphPloter(self.save_dir)\n \n if torch.cuda.is_available():\n self.device = torch.device(\"cuda\")\n self.device_count = torch.cuda.device_count()\n logging.info('using {} gpus'.format(self.device_count))\n else:\n raise Exception(\"gpu is not available\")\n\n if args.cifar10:\n self.datasets = {x: get_simsiam_dataset(args, x) for x in ['train', 'val']} \n\n else:\n self.datasets = {x: SpatialDataset(x,\n args.data_dir,\n args.crop_size,\n (args.div_row, args.div_col),\n args.aug) for x in ['train', 'val']}\n\n self.dataloaders = {x: DataLoader(self.datasets[x],\n batch_size=args.batch_size,\n shuffle=(True if x == 'train' else False),\n num_workers=args.num_workers*self.device_count,\n pin_memory=(True if x == 'train' else False),\n worker_init_fn=worker_init_fn) for x in ['train', 'val']}\n\n # Define model, loss, optim\n self.model = SiameseNetwork(args)\n self.model.to(self.device)\n\n self.criterion = CosineContrastiveLoss()\n self.criterion.to(self.device)\n\n self.optimizer = optim.SGD(self.model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)\n\n #self.scheduler = lr_scheduler.MultiStepLR(self.optimizer, milestones=[80, 120, 160, 200, 250], gamma=0.1)\n self.scheduler = lr_scheduler.CosineAnnealingLR(self.optimizer, T_max=args.max_epoch)\n\n self.start_epoch = 0\n self.best_loss = np.inf\n if args.resume:\n suf = args.resume.rsplit('.', 1)[-1]\n if suf == 'tar':\n checkpoint = torch.load(args.resume, self.device)\n self.model.load_state_dict(checkpoint['model_state_dict'])\n self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n self.start_epoch = checkpoint['epoch'] + 1\n elif suf == 'pth':\n self.model.load_state_dict(torch.load(args.resume, self.device))\n\n self.save_list = Save_Handle(max_num=args.max_model_num)\n\n def train(self):\n \"\"\"training process\"\"\"\n args = self.args\n for epoch in range(self.start_epoch, args.max_epoch):\n logging.info('-'*5 + 'Epoch {}/{}'.format(epoch, args.max_epoch - 1) + '-'*5)\n self.epoch = epoch\n self.train_epoch(epoch)\n if epoch % args.val_epoch == 0 and epoch >= args.val_start:\n self.val_epoch(epoch)\n\n def train_epoch(self, epoch):\n epoch_loss = AverageMeter()\n epoch_start = time.time()\n self.model.train() # Set model to training mode\n\n for step, ((input1, input2), label) in enumerate(self.dataloaders['train']):\n input1 = input1.to(self.device)\n input2 = input2.to(self.device)\n\n with torch.set_grad_enabled(True):\n (z1, z2), (p1, p2) = self.model(input1, input2)\n loss = self.criterion(z1, z2, p1, p2)\n epoch_loss.update(loss.item(), input1.size(0))\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n self.scheduler.step()\n\n # visualize\n if step == 0:\n self.vis(epoch, 'train', input1, input2, label)\n pass\n\n logging.info('Epoch {} Train, Loss: {:.5f}, lr: {:.5f}, Cost {:.1f} sec'\n .format(self.epoch, epoch_loss.get_avg(), self.optimizer.param_groups[0]['lr'], time.time()-epoch_start))\n \n self.tr_graph(self.epoch, epoch_loss.get_avg(), 'tr')\n\n if epoch % self.args.check_point == 0:\n model_state_dic = self.model.state_dict()\n save_path = os.path.join(self.save_dir, '{}_ckpt.tar'.format(self.epoch))\n torch.save({\n 'epoch': self.epoch,\n 'optimizer_state_dict': self.optimizer.state_dict(),\n 'model_state_dict': model_state_dic\n }, save_path)\n self.save_list.append(save_path) # control the number of saved models\n\n def val_epoch(self, epoch):\n epoch_start = time.time()\n self.model.eval() # Set model to evaluate mode\n epoch_loss = AverageMeter()\n\n for step, ((input1, input2), label) in enumerate(self.dataloaders['val']):\n input1 = input1.to(self.device)\n input2 = input2.to(self.device)\n\n with torch.set_grad_enabled(False):\n (z1, z2), (p1, p2) = self.model(input1, input2)\n loss = self.criterion(z1, z2, p1, p2)\n epoch_loss.update(loss.item(), input1.size(0))\n\n # visualize\n if step == 0:\n self.vis(epoch, 'val', input1, input2, label)\n pass\n\n logging.info('Epoch {} Val, Loss: {:.5f}, Cost {:.1f} sec'\n .format(self.epoch, epoch_loss.get_avg(), time.time()-epoch_start))\n\n self.vl_graph(self.epoch, epoch_loss.get_avg(), 'vl')\n\n model_state_dic = self.model.state_dict()\n if self.best_loss > epoch_loss.get_avg():\n self.best_loss = epoch_loss.get_avg()\n logging.info(\"save min loss {:.2f} model epoch {}\".format(self.best_loss, self.epoch))\n torch.save(model_state_dic, os.path.join(self.save_dir, 'best_model.pth'))" }, { "alpha_fraction": 0.49848484992980957, "alphanum_fraction": 0.5382575988769531, "avg_line_length": 30.04705810546875, "blob_id": "c8fca5c32323819233db0b9c2780270384a19d50", "content_id": "a11c49496995ca14e47db03e0f44f38438707a70", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2640, "license_type": "permissive", "max_line_length": 100, "num_lines": 85, "path": "/models/simple_siamese_net_tmp.py", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\n\nclass projection_MLP(nn.Module):\n def __init__(self, in_dim=512, hidden_dim=512, out_dim=512): # bottleneck structure\n super().__init__()\n \n self.layers = nn.Sequential(\n nn.Linear(in_dim, hidden_dim),\n nn.ReLU(),\n nn.Linear(hidden_dim, hidden_dim),\n nn.ReLU(),\n nn.Linear(hidden_dim, out_dim)\n )\n\n def forward(self, x):\n if x.dim() != 2:\n x = x.squeeze()\n x = self.layers(x)\n return x \n\nclass prediction_MLP(nn.Module):\n def __init__(self, in_dim=512, hidden_dim=256, out_dim=512): # bottleneck structure\n super().__init__()\n self.layer1 = nn.Sequential(\n nn.Linear(in_dim, hidden_dim),\n nn.ReLU(inplace=True)\n )\n self.layer2 = nn.Linear(hidden_dim, out_dim)\n\n def forward(self, x):\n if x.dim() != 2:\n x = x.squeeze()\n x = self.layer1(x)\n x = self.layer2(x)\n return x \n\nclass SiameseNetwork(nn.Module):\n def __init__(self, model, pattern_feature = 'conv-512x1x1', projection=False, prediction=False):\n super(SiameseNetwork, self).__init__()\n self.projection = projection\n self.prediction = prediction\n\n if pattern_feature == 'conv-512x1x1':\n features = model().features\n max_pool = nn.AdaptiveAvgPool2d((1,1))\n self.encoder = nn.Sequential(features, max_pool)\n\n if projection:\n self.projector = projection_MLP(in_dim=512, hidden_dim=512, out_dim=512)\n\n if prediction:\n self.predictor = prediction_MLP(in_dim=512, out_dim=512)\n\n elif pattern_feature == 'fc-4096':\n features = model()\n self.encoder = nn.Sequential(*[self.encoder.classifier[0]])\n\n if projection:\n self.projector = projection_MLP(in_dim=4096, hidden_dim=4096, out_dim=4096)\n \n if prediction:\n self.predictor = prediction_MLP(in_dim=4096, out_dim=4096)\n\n\n def forward(self, input1, input2):\n if self.prediction:\n f, h = self.encoder, self.predictor\n z1, z2 = f(input1), f(input2)\n\n if self.projection:\n z1, z2 = self.projection(input1), self.projection(input2)\n\n p1, p2 = h(z1), h(z2)\n\n else:\n f = self.encoder\n z1, z2 = f(input1), f(input2)\n\n if self.projection:\n z1, z2 = self.projection(input1), self.projection(input2)\n\n p1, p2 = None, None\n\n return (z1, z2), (p1, p2)\n\n" }, { "alpha_fraction": 0.5610116720199585, "alphanum_fraction": 0.5737317204475403, "avg_line_length": 42.62580490112305, "blob_id": "66fb35b9833f35fe7c33f52cc57ec7dbe36a3998", "content_id": "4253a92ac8a91547a2e84731bf0114f4376793c7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6761, "license_type": "permissive", "max_line_length": 127, "num_lines": 155, "path": "/utils/contrastive_trainer.py", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport time\nimport logging\n\nimport numpy as np\n\nimport torch\nfrom torch import optim\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import DataLoader\nimport torchvision.models as models\nimport torchvision.datasets as datasets\n\nfrom models.siamese_net import SiameseNetwork\nfrom models.l2_contrastive_loss import L2ContrastiveLoss\nfrom utils.trainer import Trainer\nfrom utils.helper import Save_Handle, AverageMeter, worker_init_fn\nfrom utils.visualizer import ImageDisplayer, EmbeddingDisplayer\nfrom datasets.spatial import SpatialDataset\nfrom datasets.cifar10 import PosNegCifar10\n\nclass CoTrainer(Trainer):\n def setup(self):\n \"\"\"initialize the datasets, model, loss and optimizer\"\"\"\n args = self.args\n self.vis = ImageDisplayer(args, self.save_dir)\n self.emb = EmbeddingDisplayer(args, self.save_dir)\n \n if torch.cuda.is_available():\n self.device = torch.device(\"cuda\")\n self.device_count = torch.cuda.device_count()\n logging.info('using {} gpus'.format(self.device_count))\n else:\n raise Exception(\"gpu is not available\")\n\n if args.cifar10:\n # Download and create datasets\n or_train = datasets.CIFAR10(root=\"CIFAR10_Dataset\", train=True, transform=None, download=True)\n or_val = datasets.CIFAR10(root=\"CIFAR10_Dataset\", train=False, transform=None, download=True)\n\n # splits CIFAR10 into two streams\n self.datasets = {x: PosNegCifar10((or_train if x == 'train' else or_val),\n phase=x) for x in ['train', 'val']}\n else:\n self.datasets = {x: SpatialDataset(os.path.join(args.data_dir, x),\n args.crop_size,\n args.div_num,\n args.aug) for x in ['train', 'val']}\n\n self.dataloaders = {x: DataLoader(self.datasets[x],\n batch_size=args.batch_size,\n shuffle=(True if x == 'train' else False),\n num_workers=args.num_workers*self.device_count,\n pin_memory=(True if x == 'train' else False),\n worker_init_fn=worker_init_fn) for x in ['train', 'val']}\n\n # Define model, loss, optim\n self.model = SiameseNetwork(models.__dict__[args.arch], pattern_feature = args.pattern_feature)\n self.model.to(self.device)\n\n self.criterion = L2ContrastiveLoss(args.margin)\n self.criterion.to(self.device)\n\n self.optimizer = optim.SGD(self.model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)\n\n self.scheduler = lr_scheduler.MultiStepLR(self.optimizer, milestones=[80, 120, 160, 200, 250], gamma=0.1)\n\n self.start_epoch = 0\n self.best_loss = np.inf\n if args.resume:\n suf = args.resume.rsplit('.', 1)[-1]\n if suf == 'tar':\n checkpoint = torch.load(args.resume, self.device)\n self.model.load_state_dict(checkpoint['model_state_dict'])\n self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n self.start_epoch = checkpoint['epoch'] + 1\n elif suf == 'pth':\n self.model.load_state_dict(torch.load(args.resume, self.device))\n\n self.save_list = Save_Handle(max_num=args.max_model_num)\n\n def train(self):\n \"\"\"training process\"\"\"\n args = self.args\n for epoch in range(self.start_epoch, args.max_epoch):\n logging.info('-'*5 + 'Epoch {}/{}'.format(epoch, args.max_epoch - 1) + '-'*5)\n self.epoch = epoch\n self.train_epoch(epoch)\n if epoch % args.val_epoch == 0 and epoch >= args.val_start:\n self.val_epoch(epoch)\n\n def train_epoch(self, epoch):\n epoch_loss = AverageMeter()\n epoch_start = time.time()\n self.model.train() # Set model to training mode\n\n for step, (input1, input2, target, label) in enumerate(self.dataloaders['train']):\n input1 = input1.to(self.device)\n input2 = input2.to(self.device)\n target = target.to(self.device)\n\n with torch.set_grad_enabled(True):\n output1, output2 = self.model(input1, input2)\n loss = self.criterion(output1, output2, target)\n epoch_loss.update(loss.item(), input1.size(0))\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n self.scheduler.step()\n\n # visualize\n if step == 0:\n self.vis(epoch, 'train', input1, input2, target)\n self.emb(output1, label, epoch, 'train')\n\n logging.info('Epoch {} Train, Loss: {:.5f}, Cost {:.1f} sec'\n .format(self.epoch, epoch_loss.get_avg(), time.time()-epoch_start))\n\n model_state_dic = self.model.state_dict()\n save_path = os.path.join(self.save_dir, '{}_ckpt.tar'.format(self.epoch))\n torch.save({\n 'epoch': self.epoch,\n 'optimizer_state_dict': self.optimizer.state_dict(),\n 'model_state_dict': model_state_dic\n }, save_path)\n self.save_list.append(save_path) # control the number of saved models\n\n def val_epoch(self, epoch):\n epoch_start = time.time()\n self.model.eval() # Set model to evaluate mode\n epoch_loss = AverageMeter()\n\n for step, (input1, input2, target, label) in enumerate(self.dataloaders['val']):\n input1 = input1.to(self.device)\n input2 = input2.to(self.device)\n target = target.to(self.device)\n with torch.set_grad_enabled(False):\n output1, output2 = self.model(input1, input2)\n loss = self.criterion(output1, output2, target)\n epoch_loss.update(loss.item(), input1.size(0))\n\n # visualize\n if step == 0:\n self.vis(epoch, 'val', input1, input2, target)\n self.emb(output1, label, epoch, 'val')\n\n logging.info('Epoch {} Val, Loss: {:.5f}, Cost {:.1f} sec'\n .format(self.epoch, epoch_loss.get_avg(), time.time()-epoch_start))\n\n model_state_dic = self.model.state_dict()\n if self.best_loss > epoch_loss.get_avg():\n self.best_loss = epoch_loss.get_avg()\n logging.info(\"save min loss {:.2f} model epoch {}\".format(self.best_loss, self.epoch))\n torch.save(model_state_dic, os.path.join(self.save_dir, 'best_model.pth'))" }, { "alpha_fraction": 0.5728855729103088, "alphanum_fraction": 0.5915423035621643, "avg_line_length": 36.23147964477539, "blob_id": "f36b32d40cffbdcd9171f4740af81ab62806f555", "content_id": "59ec9491f39d841059c33e9098fb3fadc1045153", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4020, "license_type": "permissive", "max_line_length": 125, "num_lines": 108, "path": "/linear_eval.py", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "import os\nimport argparse\nimport logging\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import DataLoader\nimport torchvision.models as models\n\nfrom datasets.cifar10 import get_simsiam_dataset\nfrom models.create_linear_eval_model import LinearEvalModel\nfrom utils.visualizer import AccLossGraphPloter\nfrom utils.logger import setlogger\n\nargs = None\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Test ')\n parser.add_argument('--save-dir', default='/mnt/hdd02/contrastive-learn/0113-193048',\n help='model directory')\n parser.add_argument('--device', default='0', help='assign device')\n parser.add_argument('--arch', default='vgg19', help='model architecture')\n\n parser.add_argument('--max-epoch', default=100, type=int, help='train epoch')\n parser.add_argument('--crop-size', default=224, type=int, help='input size')\n parser.add_argument('--batch-size', default=512, type=int, help='input size')\n parser.add_argument('--lr', default=1e-1, type=float, help='learning rate')\n parser.add_argument('--momentum', default=0.9, type=float, help='momentum')\n\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n args = parse_args()\n os.environ['CUDA_VISIBLE_DEVICES'] = args.device.strip() # set vis gpu\n plotter = AccLossGraphPloter(args.save_dir)\n setlogger(os.path.join(args.save_dir, 'eval.log')) # set logger\n\n datasets = {x: get_simsiam_dataset(args, x) for x in ['linear_train', 'linear_val']}\n\n dataloaders = {x: DataLoader(datasets[x],\n batch_size=(args.batch_size),\n shuffle=(True if x == 'linear_train' else False),\n num_workers=8,\n pin_memory=(True if x == 'linear_train' else False)) for x in ['linear_train', 'linear_val']}\n\n device = torch.device('cuda')\n\n model = LinearEvalModel(arch=args.arch)\n model.weight_init(args.save_dir, device, args.arch) ## initialize & freeze\n\n criterion = nn.CrossEntropyLoss()\n\n optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)\n scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=[40, 60, 80], gamma=0.1)\n\n ## Training & Test Roop\n model.to(device)\n for epoch in range(args.max_epoch):\n model.train()\n losses, acc, step, total = 0., 0., 0., 0.\n for data, target in dataloaders['linear_train']:\n data, target = data.to(device), target.to(device)\n\n logits = model(data)\n\n optimizer.zero_grad()\n loss = criterion(logits, target)\n loss.backward()\n losses += loss.item()\n optimizer.step()\n scheduler.step()\n\n pred = F.softmax(logits, dim=-1).max(-1)[1]\n acc += pred.eq(target).sum().item()\n\n step += 1\n total += target.size(0)\n\n tr_loss = losses / step\n tr_acc = acc / total * 100.\n logging.info('[Train Epoch: {0:2d}], loss: {1:.3f}, acc: {2:.3f}'.format(epoch, tr_loss, tr_acc))\n \n model.eval()\n losses, acc, step, total = 0., 0., 0., 0.\n with torch.no_grad():\n for data, target in dataloaders['linear_val']:\n data, target = data.to(device), target.to(device)\n\n logits = model(data)\n loss = criterion(logits, target)\n losses += loss.item()\n\n pred = F.softmax(logits, dim=-1).max(-1)[1]\n acc += pred.eq(target).sum().item()\n\n step += 1\n total += target.size(0)\n \n vl_loss = losses / step\n vl_acc = acc / total * 100.\n logging.info('[Test Epoch: {0:2d}], loss: {1:.3f} acc: {2:.2f}'.format(epoch, vl_loss, vl_acc))\n\n plotter(epoch, tr_acc, vl_acc, tr_loss, vl_loss, args.arch)" }, { "alpha_fraction": 0.44009217619895935, "alphanum_fraction": 0.4746543765068054, "avg_line_length": 38.477272033691406, "blob_id": "dc414457518c68685d4f61e6b9f83c2f0801861c", "content_id": "52924d5b726bec3228b032cce8d7b6d6b2c6224b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1736, "license_type": "permissive", "max_line_length": 104, "num_lines": 44, "path": "/models/siamese_net.py", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\n\nclass SiameseNetwork(nn.Module):\n def __init__(self, model, pretrained=False, simple_model=False):\n super(SiameseNetwork, self).__init__()\n self.simple_model = simple_model\n if simple_model:\n self.features = nn.Sequential(nn.Conv2d(3, 32, 5), nn.PReLU(),\n nn.MaxPool2d(2, stride=2),\n nn.Conv2d(32, 64, 5), nn.PReLU(),\n nn.MaxPool2d(2, stride=2),\n nn.Conv2d(64, 64, 5), nn.PReLU(),\n nn.MaxPool2d(2, stride=2))\n\n self.classifier = nn.Sequential(nn.Linear(64 * 4 * 4, 256),\n nn.PReLU(),\n nn.Linear(256, 256),\n nn.PReLU(),\n nn.Linear(256, 2))\n\n else:\n if pretrained:\n self.encoder = model(pretrained=True)\n self.encoder.classifier = nn.Sequential(*[self.encoder.classifier[i] for i in range(6)])\n self.encoder.classifier.add_module('out', nn.Linear(4096, 2))\n else:\n self.encoder = model(num_classes=2)\n\n def forward_once(self, x):\n if self.simple_model:\n output = self.features(x)\n output = output.view(output.size()[0], -1)\n output = self.classifier(output)\n\n else:\n output = self.encoder(x)\n \n return output\n\n def forward(self, input1, input2):\n output1 = self.forward_once(input1)\n output2 = self.forward_once(input2)\n return output1, output2" }, { "alpha_fraction": 0.8636363744735718, "alphanum_fraction": 0.8636363744735718, "avg_line_length": 21, "blob_id": "c1a4483121f82215217a3ca3d6295497ab1bbc93", "content_id": "2ce1c8c4ca97de2c80884912aebb2878e21bc8ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 44, "license_type": "permissive", "max_line_length": 22, "num_lines": 2, "path": "/README.md", "repo_name": "junprog/contrastive-baseline", "src_encoding": "UTF-8", "text": "# contrastive-baseline\ncontrastive learning\n" } ]
17
andrewjschuang/Turing
https://github.com/andrewjschuang/Turing
91b89fac2e2bc999034da03ab20687078799ae8f
8425185f2a3a87d78c632288717f3cafb302651f
39973df134b5b73e4ab06fa2438f107f887c6f07
refs/heads/master
2020-03-17T22:38:11.524311
2018-06-29T22:01:26
2018-06-29T22:01:26
134,012,351
0
1
null
2018-05-18T23:15:16
2018-06-28T09:23:09
2018-06-29T22:01:27
HTML
[ { "alpha_fraction": 0.5103749632835388, "alphanum_fraction": 0.516017496585846, "avg_line_length": 36.88965606689453, "blob_id": "af52df6640ff9e5ea8ed8265a66c51417b39d108", "content_id": "eb0606caeb430479969457c0ab0017ad1bfaf0e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10988, "license_type": "no_license", "max_line_length": 95, "num_lines": 290, "path": "/turing.py", "repo_name": "andrewjschuang/Turing", "src_encoding": "UTF-8", "text": "import time\nfrom datetime import datetime\nfrom flask import (Flask, abort, flash, redirect, render_template, request,\n session, url_for)\nfrom sqlalchemy.exc import IntegrityError\nfrom wtforms import (Form, RadioField, StringField, SubmitField, TextAreaField, TextField,\n validators)\n\n\nfrom models.model import User, Project, Task, Questionnaire, Question, Response\nfrom models.shared import db\n\nclass SignUp(Form):\n name = TextField('Name:', validators=[validators.required()])\n email = TextField('Email:', validators=[\n validators.required(), validators.Length(min=6, max=35)])\n password = TextField('Password:', validators=[\n validators.required(), validators.Length(min=3, max=35)])\n\n\nclass Login(Form):\n email = TextField('Email:', validators=[\n validators.required(), validators.Length(min=6, max=35)])\n password = TextField('Password:', validators=[\n validators.required(), validators.Length(min=3, max=35)])\n\ndef create_app(config=None):\n app = Flask(__name__)\n if config:\n app.config.from_mapping(config)\n else:\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///prod.db'\n app.config['SECRET_KEY'] = '7d441f27d441f27567d441f2b6176a'\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\n\n db.init_app(app)\n\n\n @app.errorhandler(404)\n def page_not_found(e):\n return render_template('404.html'), 404\n\n\n @app.route('/signup', methods=['GET', 'POST'])\n def signup():\n form = SignUp(request.form)\n if request.method == 'POST':\n if form.validate():\n \n name = request.form['name']\n password = request.form['password']\n email = request.form['email']\n u = User(email=email, name=name, password=password)\n db.session.add(u)\n db.session.commit()\n session['auth'] = {'name': name,\n 'email': email, 'timestamp': time.time()}\n return redirect(url_for('index'))\n\n else:\n flash('All the form fields are required.', category='error')\n\n return render_template('signup.html', form=form)\n\n\n @app.route('/login', methods=['GET', 'POST'])\n def login():\n form = Login(request.form)\n if request.method == 'POST':\n if form.validate():\n password = request.form['password']\n email = request.form['email']\n user = User.query.filter_by(email=email).first()\n print(user)\n if user:\n print(user)\n if user.password == password:\n session['auth'] = {'name': user.name,\n 'email': user.email,\n 'timestamp': time.time()\n }\n return redirect(url_for('index'))\n else:\n flash('Authentication failed', category='error')\n else:\n flash('Authentication failed', category='error')\n\n else:\n flash('All the form fields are required', category='error')\n return render_template('login.html', form=form)\n\n\n @app.route('/', methods=['GET'])\n def index():\n auth = session.get('auth')\n if auth:\n user: User = User.query.filter_by(email=auth.get('email')).first()\n if not user:\n session['auth'] = {}\n return redirect('/login')\n info = user.get_index_data()\n print(info)\n return render_template('index.html', **info)\n return redirect('/login')\n\n @app.route('/responses')\n def responses():\n auth = session.get('auth')\n if auth:\n user: User = User.query.filter_by(email=auth.get('email')).first()\n User.query.filter_by(email=auth.get('email')).first()\n if not user:\n session['auth'] = {}\n return redirect('/login')\n quests = Questionnaire.query.all()\n return render_template('responses.html', quests=quests)\n\n @app.route('/respond/<int:ref>', methods=['GET', 'POST'])\n def respond(ref):\n quest = Questionnaire.query.get(ref)\n if not quest:\n print('no questionnaire found with id %s' % ref)\n return abort(404)\n if request.method == 'GET':\n return render_template('feedback.html', name=quest.name, questions=quest.questions)\n elif request.method == 'POST':\n for question_id in request.form:\n question = Question.query.get(question_id)\n resp = Response(question=question.id, rating=request.form.get(question_id))\n db.session.add(resp)\n db.session.commit()\n return render_template('feedback_received.html')\n\n @app.route('/projects', methods=['GET', 'POST'])\n def projects():\n auth = session.get('auth')\n if auth:\n user: User = User.query.filter_by(email=auth.get('email')).first()\n if not user:\n session['auth'] = {}\n return redirect('/login')\n if request.method == 'POST':\n name = request.form['projectName']\n description = request.form['projectDescription']\n pro = Project(name=name,description=description)\n db.session.add(pro)\n user.project.append(pro)\n db.session.commit()\n\n grid = user.get_project_grid(3)\n return render_template('projects.html', projectgrid=grid)\n return redirect('/login')\n\n\n @app.route('/tasks/user')\n @app.route('/tasks/user/<int:ref>', methods=['GET', 'POST'])\n def user_tasks(ref=None):\n auth = session.get('auth')\n if auth:\n user: User = User.query.filter_by(email=auth.get('email')).first()\n if not user:\n session['auth'] = {}\n return redirect('/login')\n if ref:\n user: User = User.query.filter_by(id=ref).first()\n if not user:\n return abort(404)\n if request.method == 'POST':\n name = request.form.get('taskName')\n description = request.form.get('taskDescription')\n t_time = request.form.get('taskTime')\n if not all((name, description, t_time)):\n abort(404)\n t_time = datetime.strptime(t_time,'%Y-%m-%dT%H:%M:%S.%fZ')\n n_task: Task = Task(name=name, description=description, end_time=t_time)\n user.tasks.append(n_task)\n db.session.commit()\n return abort(200)\n else:\n return render_template('tasks.html', data=user)\n\n @app.route('/tasks/project/<int:ref>', methods=['GET', 'POST'])\n def proj_tasks(ref):\n\n auth = session.get('auth')\n if auth:\n user: User = User.query.filter_by(email=auth.get('email')).first()\n if not user:\n session['auth'] = {}\n return redirect('/login')\n\n project:Project = Project.query.filter_by(id=ref).first()\n if not project:\n return abort(404)\n if request.method == 'POST':\n name = request.form.get('taskName')\n description = request.form.get('taskDescription')\n t_time = request.form.get('taskDate')\n if not all((name, description, t_time)):\n abort(404)\n t_time = datetime.strptime(t_time,'%Y-%m-%dT%H:%M:%S.%fZ')\n n_task: Task = Task(name=name, description=description, end_time=t_time)\n\n project.tasks.append(n_task)\n user.tasks.append(n_task)\n\n db.session.commit()\n return ('' ,200)\n else:\n return render_template('tasks.html', data=project)\n\n @app.route('/tasks/task/<int:ref>', methods=['GET', 'POST'])\n def task_tasks(ref):\n auth = session.get('auth')\n if auth:\n user: User = User.query.filter_by(email=auth.get('email')).first()\n if not user:\n session['auth'] = {}\n return redirect('/login')\n\n task:Task = Task.query.filter_by(id=ref).first()\n\n if not task:\n return abort(404)\n if request.method == 'POST':\n name = request.form.get('taskName')\n description = request.form.get('taskDescription')\n t_time = request.form.get('taskDate')\n if not all((name, description, t_time)):\n abort(404)\n t_time = datetime.strptime(t_time,'%Y-%m-%dT%H:%M:%S.%fZ')\n n_task: Task = Task(name=name, description=description, end_time=t_time)\n\n db.session.add(n_task)\n task.tasks.append(n_task)\n db.session.commit()\n\n user.tasks.append(n_task)\n\n db.session.commit()\n print(task, task.tasks)\n print(n_task, n_task.tasks)\n return ('' ,200)\n else:\n print(task, task.tasks)\n return render_template('tasks.html', data=task)\n\n @app.route('/test', methods=['GET'])\n def test():\n \n return render_template('newQuestionnaire.html')\n\n @app.route('/questionnaire/<int:ref>', methods=['GET', 'POST'])\n def questionnaire(ref):\n auth = session.get('auth')\n if auth:\n user: User = User.query.filter_by(email=auth.get('email')).first()\n if not user:\n session['auth'] = {}\n return redirect('/login')\n \n task:Task = Task.query.filter_by(id=ref).first()\n\n if not task:\n return abort(404)\n if request.method == 'POST':\n name = request.form.get('name')\n if not name:\n return abort(404)\n quest = Questionnaire(name=name,task=task)\n task.questionnaires.append(quest)\n for key, value in request.form.items():\n if not value or key == 'name':\n continue\n else:\n quest.questions.append(Question(text=value,questionnaire=quest))\n db.session.commit()\n return render_template('newQuestionnaire.html')\n\n @app.route('/logout', methods=['GET'])\n def logout():\n session.pop('auth')\n return redirect(url_for('index'))\n\n return app\n\nif __name__ == '__main__':\n app = create_app()\n db.create_all(app=app)\n app.run(host='localhost', port=3000, debug=True)\n" }, { "alpha_fraction": 0.7272727489471436, "alphanum_fraction": 0.7398989796638489, "avg_line_length": 17.85714340209961, "blob_id": "712617860c122b57926f6618dff80685b0d49b8a", "content_id": "1c3c2c798d144989c23c3d7d2a6418eb72f9514b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 399, "license_type": "no_license", "max_line_length": 61, "num_lines": 21, "path": "/README.md", "repo_name": "andrewjschuang/Turing", "src_encoding": "UTF-8", "text": "# Projeto Aplicativo Criação Alan Turing\n\n## Instalacão\n\n### Criacao do virtual environment dentro da pasta do projeto\n`python3 -m venv ve`\n\n### Ativar o virtual environment\n`source ve/bin/activate`\n\n### Instalar as bibliotecas\n`pip install -r requirements.txt`\n\n### Rodar o server\n`python turing.py`\n\n### Acessar pela web\n`http:localhost:3000/`\n\n### Desativar o virtual environment\n`deactivate`\n" }, { "alpha_fraction": 0.5885993242263794, "alphanum_fraction": 0.5960912108421326, "avg_line_length": 26.168142318725586, "blob_id": "5a30e80cdd9f35cdfbf7e0e2311152a78e9bd08a", "content_id": "4475632e86c45aa2b2bfe2b0753853dc195f52d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3070, "license_type": "no_license", "max_line_length": 79, "num_lines": 113, "path": "/test.py", "repo_name": "andrewjschuang/Turing", "src_encoding": "UTF-8", "text": "from flask_testing import TestCase\n\nfrom models.shared import db\nfrom models.model import User, Task, Project, Question, Response, Questionnaire\nfrom turing import create_app\n\nimport unittest\n\n\nclass MyTest(TestCase):\n def create_app(self):\n config = {\n 'SQLALCHEMY_DATABASE_URI': 'sqlite:///test.db',\n 'TESTING': True,\n 'SECRET_KEY': 'secret',\n 'SQLALCHEMY_TRACK_MODIFICATIONS': True\n }\n return create_app(config)\n\n def setUp(self):\n db.create_all()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n\n def test_nothing(self):\n assert True\n\n def test_user(self):\n user = User(email='em', name='us', password='pass')\n db.session.add(user)\n db.session.commit()\n assert user in db.session\n\n def test_project(self):\n project = Project(name='n',description='desc')\n db.session.add(project)\n db.session.commit()\n assert project in db.session\n \n def test_task(self):\n task = Task(name='n', description='desc')\n db.session.add(task)\n db.session.commit()\n assert task in db.session\n\n def test_usr_add_tsk2_prj(self):\n user = User(email='em', name='us', password='pass')\n db.session.add(user)\n db.session.commit()\n \n project = Project(name='n',description='desc')\n db.session.add(project)\n user.project.append(project)\n db.session.commit()\n\n project: Project= User.query.filter_by(email='em').first().project[0]\n\n task = Task(name='n', description='desc')\n db.session.add(task)\n\n project.tasks.append(task)\n db.session.commit()\n\n assert user.project[0].tasks[0] == task\n\n\n def test_sub_tasks(self):\n task = Task(name='n', description='desc')\n db.session.add(task)\n assert task in db.session\n\n s_task = Task(name='n', description='desc')\n db.session.add(s_task)\n assert task in db.session\n\n db.session.commit()\n task.tasks.append(s_task)\n\n \n db.session.commit()\n assert task.tasks[0] == s_task\n \n def test_questionnaire(self):\n questionnaire = Questionnaire(name='Questions')\n db.session.add(questionnaire)\n\n question0 = Question(text=\"ola ?\", questionnaire=questionnaire)\n question1 = Question(text=\"tudo bem ?\", questionnaire=questionnaire)\n\n questionnaire.questions.append(question0)\n questionnaire.questions.append(question1)\n\n for i in range(10):\n question0.responses.append(Response(rating=5,question=question0))\n\n for i in range(10):\n question1.responses.append(Response(rating=5,question=question1))\n\n rs = [x.rating for x in questionnaire.questions[0].responses]\n assert sum(rs)/len(rs) == 5\n\n rs = [x.rating for x in questionnaire.questions[1].responses]\n assert sum(rs)/len(rs) == 5\n\n \n \n\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.591269850730896, "alphanum_fraction": 0.591269850730896, "avg_line_length": 27, "blob_id": "0aae68c6097c7f55d46d8cd6a8718802f708ef7c", "content_id": "16cd725083df83c805bb93b4d5755659c5ebf966", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 252, "license_type": "no_license", "max_line_length": 47, "num_lines": 9, "path": "/functionalities.py", "repo_name": "andrewjschuang/Turing", "src_encoding": "UTF-8", "text": "functionalities = {\n 'Login': 'Login page',\n 'Feedback': 'This feedback form',\n 'Todo': 'To do module',\n 'Projects': 'Anything related to projects',\n 'Code': 'Code editor',\n 'Forum': 'The forum',\n 'Profile': 'Your profile page',\n}\n" }, { "alpha_fraction": 0.5410112142562866, "alphanum_fraction": 0.5814606547355652, "avg_line_length": 29.169490814208984, "blob_id": "f869bd6949bad61b15d4323a591cdfd2b655882d", "content_id": "b1b04346777793523bfc714c3b208237e185ec84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1780, "license_type": "no_license", "max_line_length": 126, "num_lines": 59, "path": "/templates/index.html", "repo_name": "andrewjschuang/Turing", "src_encoding": "UTF-8", "text": "{% extends \"sidebar.html\" %}\n\n\n{% block styles %}\n{{super()}}\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{{url_for('static', filename='css/draggable.css')}}\">\n{% endblock %}\n\n{% block content %}\n{{super()}}\n{% endblock %}\n\n{% block sidecontent %}\n{{super()}}\n\n<div class=\"draggable\" id=\"projetos\" style=\"background-color:lightblue; top:10%; left:10%;\">\n <div class=\"dragable_header\">Projects</div>\n <div class=\"draggable_content\">\n {% for project in projects %}\n <div class=\"tile\" \n style=\"height:{{100.0/loop.length}}%; width:{{100.0/3}}%; max-width:{{100.0/3}}%; max-height:{{100.0/loop.length}}%;\">\n {{project.name}}\n </div> \n {% endfor %}\n <div class=\"tile\" \n style=\"height:{{100.0/3}}%; width:{{100.0/3}}%; max-width:{{100.0/3}}%; max-height:{{100.0/3}}%;\">\n <a class='link' href=\"/projects\">\n <i class=\"fas fa-plus-circle\"></i>\n </a>\n </div>\n </div>\n</div>\n\n<div class=\"draggable\" id=\"forum\" style=\"background-color:lightblue; top:20%; left:20%\">\n <div class=\"dragable_header\">Forum</div>\n</div>\n\n<div class=\"draggable\" id=\"code_preview\" style=\"background-color:lightblue; top:30%; left:30%\">\n <div class=\"dragable_header\">Code</div>\n <div class=\"tiles-grid\">\n ...\n </div>\n</div>\n\n<div class=\"draggable\" id=\"tarefas\" style=\"background-color:lightblue; top:40%; left:40%\">\n <div class=\"dragable_header\">To-Do</div>\n <div class=\"draggable_content\">\n {% for task in tasks %}\n <div class=\"tile\" \n style=\"height:{{100.0/loop.length}}%; width:{{100.0/3}}%; max-width:{{100.0/3}}%; max-height:{{100.0/loop.length}}%;\">\n {{task.name}}\n </div> \n {% endfor %}\n </div>\n \n</div>\n\n<script src=\"{{ url_for('static', filename='js/draggable.js') }}\"></script>\n{% endblock %}\n" }, { "alpha_fraction": 0.7454545497894287, "alphanum_fraction": 0.7454545497894287, "avg_line_length": 10, "blob_id": "a68af60d2170e184afaf861f4e6f293a54825a8a", "content_id": "c4b833b00b1c666ddc25914f319c72c4c9880c2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 55, "license_type": "no_license", "max_line_length": 27, "num_lines": 5, "path": "/model/src/Historic.java", "repo_name": "andrewjschuang/Turing", "src_encoding": "UTF-8", "text": "import java.util.Date;\n\npublic interface Historic {\n\n}\n" }, { "alpha_fraction": 0.7234693765640259, "alphanum_fraction": 0.7234693765640259, "avg_line_length": 18.215686798095703, "blob_id": "81eb08c0c994ac40546c2f5d244da71edaeff0fb", "content_id": "0e5c7b73cd0eae9c72651c26b7a0bcb6fc1c1197", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 980, "license_type": "no_license", "max_line_length": 100, "num_lines": 51, "path": "/model/src/Research.java", "repo_name": "andrewjschuang/Turing", "src_encoding": "UTF-8", "text": "import java.util.List;\nimport java.util.ArrayList;\n\n\npublic class Research{\n\tprivate String name, decription;\n\tprivate List<String> questions;\n\tprivate List<FeedBack> feedBacks;\n\n\tpublic Research(String name, String decription, List<String> questions, List<FeedBack> feedBacks) {\n\t\tthis.name = name;\n\t\tthis.decription = decription;\n\t\tthis.questions = new ArrayList<String>();\n\t\tthis.feedBacks = new ArrayList<FeedBack>();\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getDecription() {\n\t\treturn decription;\n\t}\n\n\tpublic void setDecription(String decription) {\n\t\tthis.decription = decription;\n\t}\n\n\tpublic List<String> getQuestions() {\n\t\treturn questions;\n\t}\n\n\tpublic void setQuestions(List<String> questions) {\n\t\tthis.questions = questions;\n\t}\n\n\tpublic List<FeedBack> getFeedBacks() {\n\t\treturn feedBacks;\n\t}\n\n\tpublic void setFeedBacks(List<FeedBack> feedBacks) {\n\t\tthis.feedBacks = feedBacks;\n\t}\n\n\t\n\t\n}\n" }, { "alpha_fraction": 0.7663551568984985, "alphanum_fraction": 0.7663551568984985, "avg_line_length": 25.625, "blob_id": "22f743d6b1cbc4c23ad8fb934c5e19a04f35a670", "content_id": "ad01fc5066acb3b02140a3307b0769ca0bdbc325", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 214, "license_type": "no_license", "max_line_length": 42, "num_lines": 8, "path": "/model/src/Function.java", "repo_name": "andrewjschuang/Turing", "src_encoding": "UTF-8", "text": "import java.util.Date;\nimport java.util.SortedSet;\n\npublic class Function implements Historic{\n private String name, description;\n private SortedSet<Task> related;\n private SortedSet<Version> versions;\n}\n\n" } ]
8
aejontargaryen/conceal-bot
https://github.com/aejontargaryen/conceal-bot
2b82cc940b847b14e1fa0937fa1acb3b6884043f
0a407e4bf8eba9cfadfb55bbc13e79b765fb2f94
5e8d249a758f4bc27af349138c56e900b57bea00
refs/heads/master
2020-03-26T13:55:06.756652
2018-08-16T03:34:14
2018-08-16T03:34:14
144,963,148
1
0
null
2018-08-16T08:58:48
2018-08-16T03:34:21
2018-08-16T03:34:20
null
[ { "alpha_fraction": 0.7395644187927246, "alphanum_fraction": 0.7490925788879395, "avg_line_length": 52.73170852661133, "blob_id": "81ade17c625b4c259499f7c9593e3643ae94f3c2", "content_id": "9f7bc2461d7c1ae2bb0fe710ded71c3a0b5be354", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2214, "license_type": "no_license", "max_line_length": 165, "num_lines": 41, "path": "/poolSetup.py", "repo_name": "aejontargaryen/conceal-bot", "src_encoding": "UTF-8", "text": "import requests\nimport json\nimport time\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n \nfrom poolModels import pool, poolBase\n \nengine = create_engine('sqlite:///poolData.db')\n# Bind the engine to the metadata of the Base class so that the\n# declaratives can be accessed through a DBSession instance\npoolBase.metadata.bind = engine\n \nDBSession = sessionmaker(bind=engine)\n# A DBSession() instance establishes all conversations with the database\n# and represents a \"staging zone\" for all the objects loaded into the\n# database session object. Any change made against the objects in the\n# session won't be persisted into the database until you call\n# session.commit(). If you're not happy about the changes, you can\n# revert all of them back to the last commit by calling\n# session.rollback()\nsession = DBSession()\n\n# Insert a Person in the person table\nnew_pool = pool(url='http://pool.conceal.network/api/live_stats', name='Official Pool', type=\"normal\", poolurl='https://pool.conceal.network')\nsession.add(new_pool)\nnew_pool = pool(url='https://ccx.scecf.org:21001/live_stats', name='SCECF', type=\"normal\", poolurl='https://ccx.scecf.org')\nsession.add(new_pool)\nnew_pool = pool(url='https://ccx.bluerockpools.net:8119/live_stats', name='Blue Rock Pool', type=\"normal\", poolurl='https://ccx.bluerockpools.net')\nsession.add(new_pool)\nnew_pool = pool(url='http://minexmr24.ru:8124/live_stats', name='CCX Майнинг пул', type=\"normal\", poolurl='http://ccx.minexmr24.ru')\nsession.add(new_pool)\nnew_pool = pool(url='https://ccx.go-mine.it/api/pool/stats', name='go mine it!', type=\"node\", poolurl='https://ccx.go-mine.it')\nsession.add(new_pool)\nnew_pool = pool(url='https://api.ccx.heigh-ho.funkypenguin.co.nz/live_stats', name='Funky Penguin', type=\"normal\", poolurl='https://ccx.heigh-ho.funkypenguin.co.nz')\nsession.add(new_pool)\nnew_pool = pool(url='https://conceal.herominers.com/api/stats', name='herominers', type=\"normal\", poolurl='https://conceal.herominers.com')\nsession.add(new_pool)\nnew_pool = pool(url='https://ccx.thepiratemine.nl:2890/live_stats', name='ThePirateMine', type=\"normal\", poolurl='https://ccx.thepiratemine.nl')\nsession.add(new_pool)\nsession.commit()\n\n" }, { "alpha_fraction": 0.6030842661857605, "alphanum_fraction": 0.6122636198997498, "avg_line_length": 34.83552551269531, "blob_id": "37f6fa8ca73fa07ceba284b0ce443f9b9106c2c5", "content_id": "8f85b98463791b7dd73fbeae20b9004dd6bf3acf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5447, "license_type": "no_license", "max_line_length": 143, "num_lines": 152, "path": "/utils.py", "repo_name": "aejontargaryen/conceal-bot", "src_encoding": "UTF-8", "text": "import random\nimport requests\nimport sys\nimport discord\nimport binascii\nimport json\nfrom collections import deque\nfrom jsonrpc_requests import Server\n\nfrom models import Transaction, TipJar\n\nconfig = json.load(open('config.json'))\n\nclass CCXServer(Server):\n def dumps(self, data):\n data['password'] = config['rpc_password']\n return json.dumps(data)\n\nrpc = CCXServer(\"http://{}:{}/json_rpc\".format(config['rpc_host'], config['rpc_port']))\ndaemon = CCXServer(\"http://{}:{}/json_rpc\".format(config['daemon_host'], config['daemon_port']))\nCONFIRMED_TXS = []\n\n\ndef get_supply():\n lastblock = daemon.getlastblockheader()\n bo = daemon.f_block_json(hash=lastblock[\"block_header\"][\"hash\"])\n return float(bo[\"block\"][\"alreadyGeneratedCoins\"])/1000000\n\n\ndef format_hash(hashrate):\n i = 0\n byteUnits = [\" H\", \" KH\", \" MH\", \" GH\", \" TH\", \" PH\"]\n while (hashrate > 1000):\n hashrate = hashrate / 1000\n i = i+1\n return \"{0:,.2f} {1}\".format(hashrate, byteUnits[i])\n\n\ndef gen_paymentid(address):\n rng = random.Random(address+config['token'])\n length = 32\n chunk_size = 65535\n chunks = []\n while length >= chunk_size:\n chunks.append(rng.getrandbits(chunk_size * 8).to_bytes(chunk_size, sys.byteorder))\n length -= chunk_size\n if length:\n chunks.append(rng.getrandbits(length * 8).to_bytes(length, sys.byteorder))\n result = b''.join(chunks)\n\n return \"\".join(map(chr, binascii.hexlify(result)))\n\n\ndef get_deposits(session):\n # get the current block height\n # we only want to insert tx after 10 blocks from the tx\n data = daemon.getlastblockheader()\n height = int(data[\"block_header\"][\"height\"])\n print(\"INFO: Current blockchain height is {}\".format(height))\n # scan for deposits\n print(\"scanning the blockchain for deposits\")\n print(\"getting list of payment id's in the tipjar database\")\n allPID = session.query(TipJar).all()\n thePID = 0\n totalPID = len(allPID)\n for thePID in range(0,totalPID):\n currentPID = allPID[thePID].paymentid \n print(\"INFO: checking PID {}\".format(currentPID))\n params = {\"payment_id\": currentPID}\n data = rpc.get_payments(params)\n #go through each transaction and them to the confirmed transactions array\n for tx in data['payments']: \n unlockWindow = int(tx[\"block_height\"]) + 10\n if tx['tx_hash'] in CONFIRMED_TXS: # if its already there, ignore it\n continue\n if unlockWindow < height: # its a confirmed and unlocked transaction\n CONFIRMED_TXS.append({'transactionHash': tx['tx_hash'],'amount': tx['amount'], 'ready':True, 'pid':currentPID})\n print(\"CONF: confirmed tx {} for {} ccx at block {}\".format(tx['tx_hash'],tx['amount'],tx['block_height'])) \n else :\n toUnlock = unlockWindow - height\n print(\"UNCF: unconfirmed tx {} for {} ccx will unlock in {} blocks\".format(tx['tx_hash'],tx['amount'],toUnlock)) \n for i,trs in enumerate(CONFIRMED_TXS): #now we go through the array of all transactions from our registered users\n processed = session.query(Transaction).filter(Transaction.tx == trs['transactionHash']).first()\n amount = 0\n print(\"INFO: looking at tx: \" + trs['transactionHash'])\n if processed: # done already, lets ignore and remove it from the array\n print(\"INFO: already processed: \" + trs['transactionHash'])\n CONFIRMED_TXS.pop(i)\n continue\n likestring = trs['pid']\n balance = session.query(TipJar).filter(TipJar.paymentid.contains(likestring)).first() #get the balance from that PID\n print(\"INFO: Balance for pid {} is: {}\".format(likestring,balance))\n if not balance:\n print(\"user does not exist!\")\n continue\n amount = trs['amount'] \n change = 0\n if trs['pid']==balance.paymentid: # money entering tipjar, add to user balance\n print(\"UPDATE: deposit of {} to PID {}\".format(amount,balance.paymentid))\n change += amount\n try:\n balance.amount += change\n except:\n print(\"no balance, setting balance to: {}\".format(change))\n balance.amount = change\n print(\"new balance: {}\".format(balance.amount))\n session.commit()\n if balance:\n nt = Transaction(trs['transactionHash'], change, trs['pid'])\n CONFIRMED_TXS.pop(i)\n yield nt \n \n\ndef get_fee(amount):\n return 100\n\n\ndef build_transfer(amount, transfers, balance):\n print(\"SEND PID: {}\".format(balance.paymentid[0:58] + balance.withdraw))\n params = {\n 'fee': get_fee(amount),\n 'paymentId': balance.paymentid[0:58] + balance.withdraw,\n 'mixin': 3,\n 'destinations': transfers\n }\n return params\n\n\nREACTION_AMP_CACHE = deque([], 500)\n\n\ndef reaction_tip_lookup(message):\n for x in REACTION_AMP_CACHE:\n if x['msg'] == message:\n return x\n\n\ndef reaction_tip_register(message, user):\n msg = reaction_tip_lookup(message)\n if not msg:\n msg = {'msg': message, 'tips': []}\n REACTION_AMP_CACHE.append(msg)\n\n msg['tips'].append(user)\n\n return msg\n\n\ndef reaction_tipped_already(message, user):\n msg = reaction_tip_lookup(message)\n if msg:\n return user in msg['tips']\n" }, { "alpha_fraction": 0.6322770714759827, "alphanum_fraction": 0.642960786819458, "avg_line_length": 44.098182678222656, "blob_id": "7ec7583a9958d65138d64dd4207c150ab34a1c64", "content_id": "836c2502b97d6203ace84a0913066bfdef9a266e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24804, "license_type": "no_license", "max_line_length": 293, "num_lines": 550, "path": "/bot.py", "repo_name": "aejontargaryen/conceal-bot", "src_encoding": "UTF-8", "text": "import asyncio\n\nimport discord\nfrom discord.ext.commands import Bot, Context\nimport requests\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom poolModels import pool, poolBase\nfrom models import Wallet, TipJar, Base, Transaction\nfrom utils import config, format_hash, gen_paymentid, rpc, daemon, \\\n get_deposits, get_fee, build_transfer, get_supply, \\\n reaction_tip_register, reaction_tipped_already\n\nHEADERS = {'Content-Type': 'application/json'}\n\n### DATABASE SETUP ###\nengine = create_engine('sqlite:///ccxbot.db')\nBase.metadata.create_all(engine)\nSession = sessionmaker(bind=engine)\nsession = Session()\n\n### POOL DATABASE SETUP ###\npoolEngine = create_engine('sqlite:///poolData.db')\npoolBase.metadata.create_all(poolEngine)\npoolSession = sessionmaker(bind=poolEngine)\nsession2 = poolSession()\n\nclient = Bot(\n description=\"{} Discord Bot\".format(config['symbol']),\n command_prefix=config['prefix'],\n pm_help=False)\n\n\[email protected]\nasync def on_member_join(member):\n await send_join_pm(member, client)\n\n\n\nasync def wallet_watcher():\n await client.wait_until_ready()\n while not client.is_closed: \n for tx in get_deposits(session):\n session.add(tx)\n try:\n session.commit()\n except:\n session.rollback()\n balance = session.query(TipJar).filter(TipJar.paymentid == tx.paymentid).first()\n if not balance: # don't do for withdrawals from jar (basically tips)\n return\n good_embed = discord.Embed(title=\"Deposit Recieved!\",colour=discord.Colour(0xD4AF37))\n good_embed.description = \"Your deposit of {} {} has now been credited.\".format(tx.amount/config['units'], config['symbol'])\n print(\"TRANSACTION PID IS: \" + tx.paymentid)\n good_embed.add_field(name=\"New Balance\", value=\"{0:,.2f}\".format(balance.amount/config['units']))\n user = await client.get_user_info(str(balance.userid))\n try:\n await client.send_message(user, embed=good_embed)\n except:\n continue\n await asyncio.sleep(119) # just less than the block time\n\nclient.loop.create_task(wallet_watcher())\n\[email protected]\nasync def on_ready():\n print(\"Bot online!\")\n\n\n### TEST COMMANDS ###\n# test to see if we can a list of users online\n# and then to a rain function which sends money from a different wallet to everyone\n# and to test getting a welcome dm\n\nasync def send_join_pm(member, client):\n \"\"\"\n Sends a welcome private message to joined members.\n \"\"\"\n\n if member.bot:\n return\n\n currently_online = \"\"\n for m in member.server.members:\n if not m.status.__str__() == \"offline\":\n if m.roles.__contains__(discord.utils.get(m.server.roles, name=\"core team\")):\n currently_online += \":white_small_square: \" + m.mention + \"\\n\"\n\n await client.send_message(member,\n \"**Hey, \" + member.name + \"! Welcome to the Conceal Discord! :)**\\n\\n\"\n \"If you're new here and have some questions head over to the **#faq** channel for an introduction to the project and answers to common questions.\\n\"\n \"You can also head over to the **#annoucements##** channel and see the latest news on where we are and what we are doing.\\n\"\n \"If you have more questions, look for one the admins or devs\\n\\n\"\n \"**Devs currently online:**\\n\\n%s\\n\\n\"\n \"You can also use this bot to get more information:\\n\"\n \"Use the command `.help` to get list of commands.\\n\"\n \"You can also see current network information with `.stats` or other specific commands like `.hashrate`, `.height`, `.difficulty`, and `.supply`\\n\"\n \"Don't forget to register your wallet address with the bot with the command `.registerwallet` so you can recieve tips.\\n\"\n \"If you want to send tips then type `.deposit` after you register your wallet address and transfer some funds to your TipJar.\\n\" \n % currently_online)\n\n\[email protected](pass_context=True)\nasync def price(ctx, exchange=None):\n err_embed = discord.Embed(title=\":x:Error:x:\", colour=discord.Colour(0xf44242))\n coindata = requests.get(\"https://maplechange.com/api/v2/tickers/ccxbtc.json\")\n btc = requests.get(\"https://www.bitstamp.net/api/ticker/\")\n try:\n to_json = coindata.json()\n except ValueError:\n err_embed.description = \"The MapleChange API is down\"\n await client.say(embed = err_embed)\n return\n coindata_embed = discord.Embed(title=\"Conceal: MapleChange\", url=\"https://maplechange.com/markets/ccxbtc\", description=\"Current pricing of CCX\", color=0x7F7FFF)\n coindata_embed.set_thumbnail(url=config['logo_url']) \n url = 'https://maplechange.com/api/v2/tickers/ccxbtc.json'\n coindata_embed.add_field(name=\"Sell\", value=\"{0:,.0f} sats\".format(round(float(coindata.json()['ticker']['sell'])*100000000)), inline=True)\n coindata_embed.add_field(name=\"Current\", value=\"{0:,.0f} sats\".format(round(float(coindata.json()['ticker']['last'])*100000000)), inline=True)\n coindata_embed.add_field(name=\"High\", value=\"{0:,.0f} sats\".format(round(float(coindata.json()['ticker']['high'])*100000000)), inline=True)\n\n\n\n\n coindata_embed.add_field(name=\"{}-USD\".format(config['symbol']),\n value=\"${0:,.4f} USD\".format(float(coindata.json()['ticker']['sell'])*float(btc.json()['last'])), inline=True)\n coindata_embed.add_field(name=\"BTC-USD\", value=\"${0:,.2f} USD\".format(float(btc.json()['last'])), inline=True)\n await client.say(embed=coindata_embed)\n### NETWORK COMMANDS ###\[email protected]()\nasync def hashrate():\n \"\"\" .hashrate - Returns network hashrate \"\"\"\n data = daemon.getlastblockheader()\n hashrate = format_hash(float(data[\"block_header\"][\"difficulty\"]) / 120)\n await client.say(\"The current global hashrate is **{}/s**\".format(hashrate))\n\[email protected]()\nasync def difficulty():\n \"\"\" .difficulty - Returns network difficulty \"\"\"\n data = daemon.getlastblockheader()\n difficulty = float(data[\"block_header\"][\"difficulty\"])\n await client.say(\"The current difficulty is **{0:,.0f}**\".format(difficulty))\n\n\[email protected]()\nasync def height():\n \"\"\" .height - Returns the current blockchain height \"\"\"\n data = daemon.getlastblockheader()\n height = int(data[\"block_header\"][\"height\"])\n await client.say(\"The current block height is **{:,}**\".format(height))\n\n\[email protected]()\nasync def supply():\n \"\"\" .supply - Returns the current circulating supply \"\"\"\n supply = get_supply()\n await client.say(\"The current circulating supply is **{:0,.2f}** {}\".format(supply, config['symbol']))\n\[email protected]()\nasync def stats():\n \"\"\" .stats - Returns all network stats \"\"\"\n data = daemon.getlastblockheader()\n hashrate = format_hash(float(data[\"block_header\"][\"difficulty\"]) / 120)\n data = daemon.getlastblockheader()\n height = int(data[\"block_header\"][\"height\"])\n deposits = int(data[\"block_header\"][\"deposits\"]) / 1000000\n supply = get_supply()\n data = daemon.getlastblockheader()\n difficulty = float(data[\"block_header\"][\"difficulty\"])\n stats_embed=discord.Embed(title=\"Conceal\", url=\"https://github.com/TheCircleFoundation/\", description=\"Complete Network Stats\", color=0x7F7FFF)\n stats_embed.set_thumbnail(url=config['logo_url']) \n hashFromPools = 0\n allPools = session2.query(pool).all()\n totalPools = len(allPools)\n for poolNumber in range(0,totalPools): \n poolHash = allPools[poolNumber].hashrate\n hashFromPools = hashFromPools + poolHash\n stats_embed.add_field(name=\"Hashrate (from Pools)\", value=\"{}KH/s\".format(hashFromPools/1000)) \n stats_embed.add_field(name=\"Hashrate (from Difficulty)\", value=\"{}/s\".format(hashrate))\n stats_embed.add_field(name=\"Height\", value=\"{:,}\".format(height))\n stats_embed.add_field(name=\"Difficulty\", value=\"{0:,.0f}\".format(difficulty))\n stats_embed.add_field(name=\"Circulating Supply\", value=\"{:0,.2f} CCX\".format(supply))\n stats_embed.add_field(name=\"Deposits\", value=\"{:0,.2f}\".format(deposits))\n stats_embed.set_footer(text=\"Powered by the Conceal Discord bot. Message @katz for any issues.\")\n await client.say(embed=stats_embed)\n\n\[email protected]()\nasync def pools():\n \"\"\" .pools - Get a list of pools and current stats \"\"\"\n stats_embed=discord.Embed(title=\"Conceal\", url=\"https://github.com/TheCircleFoundation/\", description=\"Mining Pool Stats\", color=0x7F7FFF)\n stats_embed.set_thumbnail(url=config['logo_url']) \n hashFromPools = 0\n allPools = session2.query(pool).all()\n totalPools = len(allPools)\n for poolNumber in range(0,totalPools):\n poolName = allPools[poolNumber].name\n poolSiteURL = allPools[poolNumber].poolurl\n poolHash = allPools[poolNumber].hashrate\n hashFromPools = hashFromPools + poolHash\n poolMiners = allPools[poolNumber].miners\n stats_embed.add_field(name=poolName, value=poolSiteURL, inline=False)\n stats_embed.add_field(name=\"Hashrate\", value=\"{} KH/s\".format(poolHash/1000))\n stats_embed.add_field(name=\"Miners\", value=\"{:,}\".format(poolMiners)) \n stats_embed.add_field(name=\"Hashrate (from Pools)\", value=\"{}KH/s\".format(hashFromPools/1000)) \n stats_embed.set_footer(text=\"Powered by the Conceal Discord bot. Message @katz for any issues.\")\n await client.say(embed=stats_embed)\n\n\n### WALLET COMMANDS ###\[email protected](pass_context=True)\nasync def members(ctx):\n members = \"\"\n allID = session.query(Wallet).all()\n theID = 0\n totalID = len(allID)\n await client.say(\"List of members:\") \n for theID in range(0,totalID):\n currentID = allID[theID].userid\n memberName = discord.utils.get(client.get_all_members(), id=str(currentID))\n members = members + \" @\" + str(memberName)\n await client.say(members)\n\[email protected](pass_context=True)\nasync def registerwallet(ctx, address):\n \"\"\" .registerwallet <addr> - Register your wallet in the database \"\"\"\n\n err_embed = discord.Embed(title=\"Error\", colour=discord.Colour(0xf44242))\n good_embed = discord.Embed(title=\"{}'s Wallet\".format(ctx.message.author.name),colour=discord.Colour(0xD4AF37))\n if address is None:\n err_embed.description = \"Please provide an address\"\n await client.send_message(ctx.message.author, embed = err_embed)\n return\n\n exists = session.query(Wallet).filter(Wallet.userid == ctx.message.author.id).first()\n addr_exists = session.query(Wallet).filter(Wallet.address == address).first()\n if exists:\n good_embed.title = \"Your wallet exists!\".format(exists.address)\n good_embed.description = \"```{}``` use `{}updatewallet <addr>` to change\".format(exists.address, config['prefix'])\n await client.send_message(ctx.message.author, embed = good_embed)\n return\n if addr_exists:\n err_embed.description = \"Address already registered by another user!\"\n await client.send_message(ctx.message.author, embed = err_embed)\n return\n\n elif not exists and len(address) == 98:\n w = Wallet(address, ctx.message.author.id,ctx.message.id)\n session.add(w)\n session.commit()\n good_embed.title = \"Successfully registered your wallet\"\n good_embed.description = \"```{}```\".format(address)\n await client.send_message(ctx.message.author, embed = good_embed)\n pid = gen_paymentid(address)\n balance = session.query(TipJar).filter(TipJar.paymentid == pid).first()\n if not balance:\n t = TipJar(pid, ctx.message.author.id, 0)\n session.add(t)\n else:\n balance.paymentid = pid\n session.commit()\n tipjar_addr = \"ccx7Wga6b232eSVfy8KQmBjho5TRXxX8rZ2zoCTyixfvEBQTj1g2Ysz1hZKxQtw874W3w6BZkMFSn5h3gUenQemZ2xiyyjxBR7\"\n good_embed.title = \"Your Tipjar Info\"\n good_embed.description = \"Deposit {} to start tipping! ```transfer 3 {} <amount> -p {}```\".format(config['symbol'], tipjar_addr, pid)\n balance = session.query(TipJar).filter(TipJar.paymentid == pid).first()\n await client.send_message(ctx.message.author, embed = good_embed)\n return\n elif len(address) > 98:\n err_embed.description = \"Your wallet must be 98 characeters long, your entry was too long\"\n elif len(address) < 98:\n err_embed.description = \"Your wallet must be 98 characeters long, your entry was too short\"\n await client.say(embed = err_embed)\n\[email protected]\nasync def registerwallet_error(error, ctx): \n await client.say(\"Please provide an address: .registerwallet <addr>.\")\n\[email protected](pass_context=True)\nasync def updatewallet(ctx, address):\n \"\"\" .updatewallet <addr> - Changes your registred wallet address \"\"\"\n\n err_embed = discord.Embed(title=\"Error\", colour=discord.Colour(0xf44242))\n\n if address == None:\n err_embed.description = \"Please provide an address!\"\n await client.send_message(ctx.message.author, embed=err_embed)\n return\n\n address = address.strip()\n good_embed = discord.Embed(title=\"{}'s Updated Wallet\".format(ctx.message.author.name),colour=discord.Colour(0xD4AF37))\n exists = session.query(Wallet).filter(Wallet.userid == ctx.message.author.id).first()\n if not exists:\n err_embed.description = \"You haven't registered a wallet!\"\n\n addr_exists = session.query(Wallet).filter(Wallet.address == address).first()\n if addr_exists:\n err_embed.description = \"Address already registered by another user!\"\n await client.send_message(ctx.message.author, embed = err_embed)\n return\n elif exists and len(address) == 98:\n old_pid = gen_paymentid(exists.address)\n old_balance = session.query(TipJar).filter(TipJar.paymentid == old_pid).first()\n exists.address = address\n pid = gen_paymentid(address)\n old_balance.paymentid = pid\n good_embed.title = \"Successfully updated your wallet\"\n good_embed.description = \"```{}```\".format(address)\n session.commit()\n await client.send_message(ctx.message.author, embed = good_embed)\n\n tipjar_addr = \"ccx7Wga6b232eSVfy8KQmBjho5TRXxX8rZ2zoCTyixfvEBQTj1g2Ysz1hZKxQtw874W3w6BZkMFSn5h3gUenQemZ2xiyyjxBR7\"\n good_embed.title = \"Your Tipjar Info\"\n good_embed.description = \"Deposit {} to start tipping! ```transfer 3 {} <amount> -p {}```\".format(config['symbol'], tipjar_addr, pid)\n await client.send_message(ctx.message.author, embed = good_embed)\n\n good_embed.title = \"Balance Update\"\n good_embed.url = \"\"\n good_embed.description = \"New Balance: `{:0,.2f}` {1}\".format(old_balance.amount / config['units'], config['symbol'])\n await client.send_message(ctx.message.author, embed = good_embed)\n return\n elif len(address) > 98:\n err_embed.description = \"Your wallet must be 98 characeters long, your entry was too long\"\n elif len(address) < 98:\n err_embed.description = \"Your wallet must be 98 characeters long, your entry was too short\"\n await client.say(embed=err_embed)\n\[email protected]\nasync def updatewallet_error(error, ctx): \n await client.say(\"Please provide an address: .updatewallet <addr>\")\n\[email protected](pass_context=True)\nasync def wallet(ctx, user: discord.User=None):\n \"\"\" .wallet - Returns your registered wallet address \"\"\"\n\n err_embed = discord.Embed(title=\":x:Error:x:\", colour=discord.Colour(0xf44242))\n good_embed = discord.Embed(colour=discord.Colour(0xD4AF37))\n if not user:\n exists = session.query(Wallet).filter(Wallet.userid == ctx.message.author.id).first()\n if not exists:\n err_embed.description = \"You haven't registered a wallet or specified a user!\"\n else:\n good_embed.title = \"Your wallet\"\n good_embed.description = \"Here's your wallet {}! ```{}```\".format(ctx.message.author.mention, exists.address)\n await client.send_message(ctx.message.author, embed = good_embed)\n return\n else:\n exists = session.query(Wallet).filter(Wallet.userid == user.id).first()\n if not exists:\n err_embed.description = \"{} hasn't registered a wallet!\".format(user.name)\n else:\n good_embed.title = \"{}'s wallet\".format(user.name)\n good_embed.description = \"```{}```\".format(exists.address)\n await client.send_message(ctx.message.author, embed = good_embed)\n return\n await client.send_message(ctx.message.author, embed = err_embed)\n\n\[email protected](pass_context=True)\nasync def deposit(ctx, user: discord.User=None):\n \"\"\" .deposit - Get deposit information so you can start tipping \"\"\"\n err_embed = discord.Embed(title=\":x:Error:x:\", colour=discord.Colour(0xf44242))\n good_embed = discord.Embed(title=\"Your Tipjar Info\")\n tipjar_addr = \"ccx7Wga6b232eSVfy8KQmBjho5TRXxX8rZ2zoCTyixfvEBQTj1g2Ysz1hZKxQtw874W3w6BZkMFSn5h3gUenQemZ2xiyyjxBR7\"\n exists = session.query(Wallet).filter(Wallet.userid == ctx.message.author.id).first()\n if exists:\n pid = gen_paymentid(exists.address)\n good_embed.description = \"Deposit {} to start tipping! ,Send the funds you want to deposit to the address: ``{}`` (Pay to: in the GUI) and put ``{}`` in the Payment ID field. CLI users just send a transfer to the same address and payment ID.\".format(config['symbol'], tipjar_addr, pid)\n balance = session.query(TipJar).filter(TipJar.paymentid == pid).first()\n if not balance:\n t = TipJar(pid, ctx.message.author.id, 0)\n session.add(t)\n session.commit()\n await client.send_message(ctx.message.author, embed = good_embed)\n else:\n err_embed.description = \"You haven't registered a wallet!\"\n err_embed.add_field(name=\"Help\", value=\"Use `{}registerwallet <addr>` before trying to tip!\".format(config['prefix']))\n await client.say(embed=err_embed)\n\n\[email protected](pass_context=True)\nasync def balance(ctx, user: discord.User=None):\n \"\"\" .balance - PMs your tipjar balance \"\"\"\n err_embed = discord.Embed(title=\":x:Error:x:\", colour=discord.Colour(0xf44242))\n good_embed = discord.Embed(title=\"Your Tipjar Balance is\")\n exists = session.query(Wallet).filter(Wallet.userid == ctx.message.author.id).first()\n if exists:\n pid = gen_paymentid(exists.address)\n balance = session.query(TipJar).filter(TipJar.paymentid == pid).first()\n if not balance:\n t = TipJar(pid, ctx.message.author.id, 0)\n session.add(t)\n session.commit()\n else:\n good_embed.description = \"`{0:,.2f}` {1}\".format(balance.amount / config['units'], config['symbol'])\n good_embed.add_field(name=\"Widthrawal\", value=\"You can tip yourself to widthraw CCX to your wallet\")\n await client.send_message(ctx.message.author, embed=good_embed)\n else:\n err_embed.description = \"You haven't registered a wallet!\"\n err_embed.add_field(name=\"Help\", value=\"Use `{}registerwallet <addr>` before trying to tip!\".format(config['prefix']))\n await client.say(embed=err_embed)\n\n\nEMOJI_MONEYBAGS = \"\\U0001F4B8\"\nEMOJI_SOS = \"\\U0001F198\"\nEMOJI_ERROR = \"\\u274C\"\n\n\[email protected](pass_context=True)\nasync def tip(ctx, amount, sender):\n \"\"\" .tip <amount> <username> - Tips a user the specified amount \"\"\"\n await _tip(ctx, amount, None, None)\n\n\nasync def _tip(ctx, amount,\n sender: discord.User=None,\n receiver: discord.User=None):\n\n err_embed = discord.Embed(title=\":x:Error:x:\", colour=discord.Colour(0xf44242))\n good_embed = discord.Embed(title=\"You were tipped!\", colour=discord.Colour(0xD4AF37))\n request_desc = \"Register with `{}registerwallet <youraddress>` to get started!\".format(config['prefix'])\n request_embed = discord.Embed(title=\"{} wants to tip you\".format(ctx.message.author.name), description=request_desc)\n\n if not sender: # regular tip\n sender = ctx.message.author\n\n if not receiver:\n tipees = ctx.message.mentions\n else:\n tipees = [receiver, ]\n\n try:\n amount = int(round(float(amount)*config['units']))\n except:\n await client.say(\"Amount must be a number equal or greater than {}\".format(10000 / config['units']))\n return False\n\n if amount <= 9999:\n err_embed.description = \"`amount` must be equal or greater than {}\".format(10000 / config['units'])\n await client.say(embed=err_embed)\n return False\n\n fee = get_fee(amount)\n self_exists = session.query(Wallet).filter(Wallet.userid == sender.id).first()\n\n if not self_exists:\n err_embed.description = \"You haven't registered a wallet!\"\n err_embed.add_field(name=\"Help\", value=\"Use `{}registerwallet <addr>` before trying to tip!\".format(config['prefix']))\n await client.send_message(sender, embed=err_embed)\n return False\n\n pid = gen_paymentid(self_exists.address)\n balance = session.query(TipJar).filter(TipJar.paymentid == pid).first()\n if not balance:\n t = TipJar(pid, sender.id, 0)\n session.add(t)\n session.commit()\n err_embed.description = \"You are not registered, please `{}deposit` to tip\".format(config['prefix'])\n await client.send_message(sender, embed=err_embed)\n return False\n\n if balance.amount < 0:\n balance.amount = 0\n session.commit()\n err_embed.description = \"Your balance was negative!\"\n await client.send_message(sender, embed=err_embed)\n\n katz = discord.utils.get(client.get_all_members(), id='408875878328827916')\n err_embed.title = \"{} had a negative balance!!\".format(sender.name)\n err_embed.description = \"PID: {}\".format(pid)\n\n await client.send_message(katz, embed=err_embed)\n return False\n\n if ((len(tipees)*(amount))+fee) > balance.amount:\n err_embed.description = \"Your balance is too low! Amount + Fee = `{}` {}\".format(((len(tipees)*(amount))+fee) / config['units'], config['symbol'])\n await client.add_reaction(ctx.message, \"\\u274C\")\n await client.send_message(sender, embed=err_embed)\n return False\n\n destinations = []\n actual_users = []\n failed = 0\n for user in tipees:\n user_exists = session.query(Wallet).filter(Wallet.userid == user.id).first()\n if user_exists:\n destinations.append({'amount': amount, 'address': user_exists.address})\n if user_exists.userid != sender.id: # multitip shouldn't tip self.\n actual_users.append(user)\n else:\n failed = failed+1\n\n await client.add_reaction(ctx.message, EMOJI_SOS)\n try:\n await client.send_message(user, embed = request_embed)\n except:\n continue\n\n\n if len(destinations) == 0:\n await client.add_reaction(ctx.message, EMOJI_SOS)\n return False\n\n transfer = build_transfer(amount, destinations, balance)\n print(transfer)\n result = rpc.transfer(transfer)\n print(result)\n\n await client.add_reaction(ctx.message, EMOJI_MONEYBAGS)\n\n balance.amount -= ((len(actual_users)*amount)+fee)\n tx = Transaction(result['tx_hash'], (len(actual_users)*amount)+fee, balance.paymentid)\n session.add(tx)\n session.commit()\n good_embed.title = \"Tip Sent!\"\n good_embed.description = (\n \"Sent `{0:,.2f}` {1} to {2} users! With Transaction Hash ```{3}```\"\n .format(amount / config['units'],\n config['symbol'],\n len(actual_users),\n result['tx_hash']))\n good_embed.url = (\n \"http://www.example.com/#?hash={}#blockchain_transaction\"\n .format(result['tx_hash']))\n good_embed.add_field(name=\"New Balance\", value=\"`{:0,.2f}` {}\".format(balance.amount / config['units'], config['symbol']))\n good_embed.add_field(name=\"Transfer Info\", value=\"Successfully sent to {0} users. {1} failed.\".format(len(actual_users), failed))\n try:\n await client.send_message(sender, embed=good_embed)\n except:\n pass\n for user in actual_users:\n good_embed = discord.Embed(title=\"You were tipped!\", colour=discord.Colour(0xD4AF37))\n good_embed.description = (\n \"{0} sent you `{1:,.2f}` {2} with Transaction Hash ```{3}```\"\n .format(sender.mention,\n amount / config['units'],\n config['symbol'],\n result['tx_hash']))\n good_embed.url = (\n \"http://www.example.com/#?hash={}#blockchain_transaction\"\n .format(result['tx_hash']))\n try:\n await client.send_message(user, embed=good_embed)\n except:\n continue\n return True\n\n\n\nclient.run(config['token'])\n" } ]
3
DyanLi/Design-of-Algorithms
https://github.com/DyanLi/Design-of-Algorithms
bb5818c11668f9bdc669ea70066d6652e910a353
04cb882f613f594533f12fbe077de5ae5f95d60d
372f8c5ede34ff591fea1862fcf7f225cf0643fa
refs/heads/master
2021-01-20T04:16:34.105228
2017-05-05T13:33:27
2017-05-05T13:33:27
89,669,213
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7027586102485657, "alphanum_fraction": 0.72620689868927, "avg_line_length": 24.456140518188477, "blob_id": "b1b133ec95a9f79f21692c6116ec8c4a17f9d10b", "content_id": "08d1b5b36995bc14ec82cf68e771c1814ac03ff9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1450, "license_type": "no_license", "max_line_length": 78, "num_lines": 57, "path": "/HW2015/HW1.py", "repo_name": "DyanLi/Design-of-Algorithms", "src_encoding": "UTF-8", "text": "#coding=utf-8\n'''\nuse re to\ncaul the num of the words\nalice=ALICE\n\nchange:\nuse these function\n1,with open(...) as f:\n2,content = f.read()\n3,allwords = finditer( ... content ... ) \n finditer is iter, findall is list\n4,all_lower_words = imap(str.lower, allwords)\n5,count = Counter(all_lower_words)\n much butter than build a empty dict\n'''\nimport re,math\nimport itertools\nimport collections\nfrom operator import itemgetter\n\n\nwith open('alice.txt',\"rt\") as f:\n content=f.read()\n\nallwords=re.findall(r'[a-zA-Z]+',content)\n#if i use find finditer ,i cannot use imap,allwords is a list\nall_lower_words = itertools.imap(str.lower, allwords)\ncount = collections.Counter(all_lower_words)\n\n\n#dict sort method 1: change key and value\n#cntSorted=dict((v,k) for k,v in cnt.iteritems())\n#cntSorted.sort()\n#important and not be neglected\n#print list(cntSorted.iteritems())[-10:] \n\n#dict sort method 2: use lambda\n#cntSorted=sorted(count.iteritems(),key=lambda d:d[1],reverse=True)\n#print cntSorted[0:10]\n\n#dict sort method 3: use operator\ncntSorted=sorted(count.iteritems(),key=itemgetter(1),reverse=True)\nprint cntSorted[0:10]\n\n\n\n#draw a pic\nimport matplotlib.pyplot as plt\n\n#plt.bar(range(20), [cntSorted[i][1] for i in range(20)])\n#plt.xticks(range(20), [cntSorted[i][0] for i in range(20)],rotation=30)\n\nlength=len(cntSorted)\nplt.plot(range(length), [math.log(cntSorted[i][1],10) for i in range(length)])\nplt.title(u\"WordFrequencyAnalysis-zipf\")\nplt.show()" }, { "alpha_fraction": 0.44913217425346375, "alphanum_fraction": 0.4865153431892395, "avg_line_length": 26.481616973876953, "blob_id": "1e4a0904fb4f3f73aceaa070ea8096ff357ecadd", "content_id": "b55119a4bc8b60d245c923053e5f15ddf04c7732", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7986, "license_type": "no_license", "max_line_length": 124, "num_lines": 272, "path": "/HW2015/HW3-dy.py", "repo_name": "DyanLi/Design-of-Algorithms", "src_encoding": "UTF-8", "text": "#coding: utf-8\n'''\nhuarongdao pass puzzle\n\nver:3.3\na reconstruction version of ver3.0\ndraw every state like a tree\n\nby Dyan\nDec 2015\n'''\nfrom __future__ import division\nimport cairo\nimport colorsys\nimport copy\nimport collections\n\n\n\nclass Block(object):\n u'''华容道具有10个块,棋盘左上角坐标(1,1),右下角坐标(4,5)'''\n \n def __init__ (self, width, height, name, kind ,x=-1 ,y=-1):\n self.width = width\n self.height = height\n self.name = name\n self.kind = kind #1:cao 2:guanyu 3:generals 4:pawns\n\n self.x=x\n self.y=y\n\n def move(self, dir):\n #move the Block based on dir \n if dir==\"U\": #y-1\n if self.y==1: \n return False\n self.y -= 1\n return True\n if dir==\"D\": #y+1\n if self.y + self.height > 5: \n return False\n self.y += 1\n return True\n if dir==\"L\": #x-1\n if self.x==1: \n return False\n self.x -= 1\n return True\n if dir==\"R\": #x+1\n if self.x + self.width > 4: \n return False\n self.x += 1\n return True \n assert False\n\n def draw(self,px,py,ctx):\n #draw the Block\n h = (hash(self.name) & 0x0f)/16.0\n r,g,b = colorsys.hsv_to_rgb(h, .75, .9)\n ctx.set_source_rgb(r,g,b)\n\n ctx.rectangle( px+self.x, py+self.y ,self.width-.1,self.height-.1)\n ctx.fill_preserve()\n\n #stroke the edges\n ctx.set_line_width(0.03)\n ctx.set_source_rgb(0,0,0)\n ctx.stroke()\n\n #give a text\n ctx.select_font_face(\"u微软雅黑\", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)\n ctx.set_font_size(0.3)\n x_bearing, y_bearing, width, height = ctx.text_extents (self.name)[:4]\n ctx.move_to( px+self.x + self.width / 2 - width / 2 - x_bearing, py+self.y + self.height/2 - height / 2 - y_bearing)\n ctx.show_text(self.name)\n\n\nclass Board(object):\n u'''棋盘'''\n def __init__ (self,pos):\n self.items = [\n Block(2,2,u\"曹操\",1,pos[0][0],pos[0][1]),\n Block(2,1,u\"关羽\",2,pos[1][0],pos[1][1]),\n Block(1,2,u\"张飞\",3,pos[2][0],pos[2][1]),\n Block(1,2,u\"马超\",3,pos[3][0],pos[3][1]),\n Block(1,2,u\"赵云\",3,pos[4][0],pos[4][1]),\n Block(1,2,u\"黄忠\",3,pos[5][0],pos[5][1]),\n Block(1,1,u\"卒1\",4,pos[6][0],pos[6][1]),\n Block(1,1,u\"卒2\",4,pos[7][0],pos[7][1]),\n Block(1,1,u\"卒3\",4,pos[8][0],pos[8][1]),\n Block(1,1,u\"卒4\",4,pos[9][0],pos[9][1])\n ]\n print \"OK?\", self.is_ok()\n\n def __str__(self):\n return self.pattern()\n\n def copy(self):\n return copy.deepcopy(self)\n\n def pattern(self):\n #使用一个二维数组唯一地表示一个棋盘的状态\n mask = [ [0]*5 for i in range(4) ]\n for i, b in enumerate(self.items):\n for x in range(b.width):\n for y in range(b.height):\n mask[b.x+x-1][b.y+y-1]= b.kind\n #print mask\n #数组变字符串,一个字符串唯一地表示一个棋盘的状态\n s = \"\"\n for j in range(4):\n s += \"\".join(\"%d\" % n for n in mask[j])\n return s\n\n def is_ok(self):\n #check the move is available?\n return self.pattern().count('0')==2\n\n def is_done(self):\n #check the board is sulution?\n return self.items[0].x==2 and self.items[0].y==4\n\n def draw(self,px,py,ctx):\n #draw current board\n #draw every block based on self.pos\n for i, b in enumerate(self.items):\n b.draw(px,py,ctx)\n #draw the board boundary\n ctx.set_line_width(0.1)\n ctx.rectangle( px+1 -.1, py+1 -.1 ,4 +.1,5 +.1 )\n ctx.stroke()\n\n def nextstate(self):\n u''' 列举可行的移动,返回几种新的棋盘 '''\n result = []\n for i ,b in enumerate(self.items):\n for m in (\"U\",\"D\",\"R\",\"L\"):\n new_board = self.copy()\n if new_board.items[i].move(m):\n if new_board.is_ok():\n result.append(new_board)\n return result\n\ndef bfs(board):\n u'''广度优先搜索求棋盘解 '''\n open_list = [board] #待搜索的Board()实例\n close_list = [] #搜索过的实例\n\n searched= {} #已经寻找到的节点 dict k:pattern v:board instance of Board()\n distance = {} #dict k:pattern v:number of moves\n searched[board.pattern()] = board\n distance[board.pattern()] = 0\n \n prev = {} #dict k:pattern v:father node pattern\n prev[board.pattern()] = None\n found = False\n\n #记录迭代次数\n cnt = 0\n while open_list and not found:\n #从openlist取出一个节点,放入closelist\n v = open_list.pop(0)\n close_list.append(v)\n #v 's distance\n vd = distance[v.pattern()]\n \n #每处理1k个结点,输出信息 \n cnt+=1\n if cnt%1==0:\n print \"Iter %d, Len(open)=%d, len(close)=%d, Dist=%d\" % (cnt, len(open_list), len(close_list), vd)\n\n # 这个结点棋盘所有可行的下一步\n for i, nv in enumerate(v.nextstate()):\n np = nv.pattern()\n #如果是正解 跳出\n if nv.is_done():\n searched[np] = nv\n prev[np] = v.pattern()\n found = True\n break\n #如果这一步曾经走过 不再处理\n if np in searched:\n continue\n\n prev[np] = v.pattern()\n open_list.append(nv)\n searched[np] = nv\n distance[np] = vd + 1\n\n if found:\n prev[nv.pattern()] = v.pattern()\n close_list.append(nv)\n distance[nv.pattern()] = vd + 1\n\n result = [nv]\n while prev[nv.pattern()]!=None:\n nv = searched[ prev[nv.pattern()] ]\n result.append(nv)\n print \"Done!\" \n drawtree(close_list,distance,prev,result[::1]) \n return result[::-1] \n return None\n\ndef drawtree(close_list,distance,prev,result):\n #计算每一层的孩子总数目\n alldst = []\n for s in close_list:\n alldst.append(distance[s.pattern()])\n laycnt = collections.Counter(alldst) \n\n #画出棋盘状态的树状结构\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,6000,7000)\n ctx = cairo.Context(surface)\n #ctx.translate(3000,0)\n ctx.scale(50, 50)\n #x指示s是当前层第几个孩子\n x = [0]*20\n #s横向的位置\n sx = {} \n\n while close_list:\n s = close_list.pop(0)\n sp = s.pattern()\n sd = distance[sp]\n\n factor = 120/(laycnt[sd]+1)\n #记录s的横向位置\n x[sd]+=1\n sx[sp] = x[sd]*factor\n s.draw(sx[sp] ,sd*10, ctx)\n\n if prev[sp]:\n ctx.set_line_width(.1)\n ctx.move_to(sx[sp]+3,sd*10+1)\n ctx.line_to(sx[ prev[sp] ]+3,(sd-1)*10+6)\n ctx.stroke()\n\n for i, s in enumerate(result):\n sp = s.pattern()\n sd = distance[sp]\n\n ctx.set_line_width(0.2)\n ctx.set_source_rgb(1,1,0.2)\n if prev[sp]:\n ctx.move_to(sx[sp]+3,sd*10+1)\n ctx.line_to(sx[ prev[sp] ]+3,(sd-1)*10+6)\n ctx.stroke()\n\n surface.write_to_png(\"t1.png\")\n\n\nif __name__ == \"__main__\":\n # 开局棋子位置\n # 横刀立马\n #init = [(2,1),(2,3),\n # (1,1),(1,3),(4,1),(4,3), \n # (1,5),(2,4),(3,4),(4,5)]\n \n # easy \n init = [(1,3),(3,3),\n (1,1),(2,1),(3,1),(4,1), \n (1,5),(2,5),(3,4),(4,5)]\n \n # most easy\n #init = [(1,4),(1,3),\n # (1,1),(2,1),(3,1),(4,1),\n # (3,3),(3,5),(4,4),(4,5)]\n\n board=Board(init)\n #board.draw()\n result = bfs(board)\n print \"Find a solution after %d moves.\" % (len(result)-1)\n \n\n\n \n\n" }, { "alpha_fraction": 0.8055555820465088, "alphanum_fraction": 0.8194444179534912, "avg_line_length": 23, "blob_id": "53153c3db8d7171611217d9455ec58e6b213512e", "content_id": "c035fe663b4298ab5077db0cd4b8b57677484494", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 174, "license_type": "no_license", "max_line_length": 38, "num_lines": 3, "path": "/README.md", "repo_name": "DyanLi/Design-of-Algorithms", "src_encoding": "UTF-8", "text": "# 高级数据结构与算法设计\n## Project1 算法可视化 \n实现快速排序算法,用算法可视化展示每一步的运行结果,将结果转化为GIF格式。\n" }, { "alpha_fraction": 0.599397599697113, "alphanum_fraction": 0.6325300931930542, "avg_line_length": 21.636363983154297, "blob_id": "6e368d09654ad55236d52102b77fae6c05481010", "content_id": "f27a6b8730b813add69545080a38c5edd97390f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1992, "license_type": "no_license", "max_line_length": 71, "num_lines": 88, "path": "/HW2015/HW2.py", "repo_name": "DyanLi/Design-of-Algorithms", "src_encoding": "UTF-8", "text": "#coding: utf-8\n'''\nHW2.py is used to solve eight queens puzzle,\nyou can change the size number to resize the board.\n\nchange:\n1,draw pieces with special operator not XOR but SOURCE\n2,long string can write like \"\"\"....\"\"\n3,format for str have symbol{} so use %d\n\n'''\nimport itertools,cairo,math\n\nsize=8 #the size of the board\ncnt=0 #number of right answer\n\n#check whether it is a right step or not\ndef conflict(state, nextX):\n nextY = len(state)\n for i in range(nextY):\n if abs(nextX-state[i])== nextY-i:\n return True\n return False\n\ndef drawqueen(solution):\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,size*100,size*100)\n ctx=cairo.Context(surface)\n\n #draw the board\n for i in range(0,size):\n for j in range(0,size):\n if (i+j)%2==1:\n ctx.rectangle(i*100,j*100,100,100)\n ctx.fill()\n\n #draw the pieces\n ctx.set_line_width(10)\n ctx.set_source_rgb(1, 1, 0.2)\n #change1\n ctx.set_operator(cairo.OPERATOR_SOURCE)\n for i in range(size):\n ctx.arc(solution[i]*100+50,i*100+50,35,0,2*math.pi)\n ctx.stroke()\n\n filename=\"chess\"+str(cnt)+\".png\"\n surface.write_to_png(filename)\n\n\n\n#remove the solutions in same cols\nfor solve in itertools.permutations(range(size)):\n flag=0\n for i in range(1,size):\n if conflict(solve[0:i],solve[i]):\n break\n else:\n flag+=1\n if flag==size-1:\n cnt+=1\n drawqueen(solve)\n\n\n\n#make a tex ducument to generate pdf\nf=open(\"mkreport.tex\",'w')\n\n#change2\nf.write(\"\"\"\\documentclass[twocolumn]{article}\n\\usepackage{graphicx}\n\\\\title{A Report About Eight Queens Puzzle}\\n\n\\\\begin{document}\n\\maketitle\\n\n\"\"\")\n\n#change3\nfor i in range(1,cnt+1):\n f.write(\"\"\"\n\\\\begin{figure}[t] \n\\centering\n\\includegraphics[width=0.3\\\\textwidth]{chess%d.png}\n\\caption{Sulution %d of Eight Queens Puzzle}\n\\end{figure}\\n\"\"\" % (i,i) )\n\n if i%6==0:\n f.write('\\n\\clearpage\\n')\n\nf.write('\\n\\end{document}')\nf.close()\n" }, { "alpha_fraction": 0.42317426204681396, "alphanum_fraction": 0.4609544575214386, "avg_line_length": 25.70531463623047, "blob_id": "f97ab560984279916536a3f633bff64d221535e9", "content_id": "a09b7537d7ff0f5f104bc157daf31854cfa5fd38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5606, "license_type": "no_license", "max_line_length": 110, "num_lines": 207, "path": "/HW2015/HW3-hf.py", "repo_name": "DyanLi/Design-of-Algorithms", "src_encoding": "UTF-8", "text": "#coding: utf-8\n'''\nhuarongdao pass puzzle\n\nver:1.0\nit is a original version\n\nby HF\nDec 2015\n\n'''\nfrom __future__ import division\nimport cairo\nimport colorsys\nimport copy\n#define soldiers\n#from IPython import embed\nfrom IPython.Shell import IPShellEmbed\nipshell = IPShellEmbed()\n\n\nclass block(object):\n \n def __init__(self, w, h, name, kind, x=-1, y=-1):\n self.x = x\n self.y = y\n self.w = w\n self.h = h\n self.name = name\n self.kind = kind\n\n def move(self, dir):\n if dir==\"U\": #y-1\n if self.y==1: \n return False\n self.y -= 1\n return True\n if dir==\"D\": #y+1\n if self.y + self.h > 5: \n return False\n self.y += 1\n return True\n if dir==\"L\": #x-1\n if self.x==1: \n return False\n self.x -= 1\n return True\n if dir==\"R\": #x+1\n if self.x + self.w > 4: \n return False\n self.x += 1\n return True \n assert False\n \n def draw(self, ctx):\n h = (hash(self.name) & 0x0f)/16.0\n r,g,b = colorsys.hsv_to_rgb(h, 0.6, .9)\n ctx.set_source_rgb(r,g,b)\n\n ctx.rectangle(self.x+0.05,self.y+0.05,self.w-0.1,self.h-0.1)\n ctx.fill_preserve()\n ctx.set_line_width(0.03)\n ctx.set_source_rgb(0,0,0)\n ctx.stroke()\n \n ctx.select_font_face(\"u微软雅黑\", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)\n ctx.set_font_size(0.3);\n \n x_bearing, y_bearing, width, height = ctx.text_extents (self.name)[:4]\n ctx.move_to( self.x + self.w/2 - width / 2 - x_bearing, self.y + self.h/2 - height / 2 - y_bearing)\n \n ctx.show_text(self.name)\n\nclass board(object):\n def __init__(self):\n self.items = [\n block(2,2,u\"曹操\",1,2,1),\n block(2,1,u\"关羽\",3,2,3),\n block(1,2,u\"张飞\",2,1,1),\n block(1,2,u\"马超\",2,1,3),\n block(1,2,u\"赵云\",2,4,1),\n block(1,2,u\"黄忠\",2,4,3),\n block(1,1,u\"卒1\",4,1,5),\n block(1,1,u\"卒2\",4,2,4),\n block(1,1,u\"卒3\",4,3,4),\n block(1,1,u\"卒4\",4,4,5)\n ]\n self.items = [\n block(2,2,u\"曹操\",1,1,3),\n block(2,1,u\"关羽\",3,1,5),\n block(1,2,u\"张飞\",2,1,1),\n block(1,2,u\"马超\",2,2,1),\n block(1,2,u\"赵云\",2,3,1),\n block(1,2,u\"黄忠\",2,4,1),\n block(1,1,u\"卒1\",4,3,3),\n block(1,1,u\"卒2\",4,4,3),\n block(1,1,u\"卒3\",4,3,4),\n block(1,1,u\"卒4\",4,4,4)\n ]\n print \"OK?\", self.is_ok()\n\n def copy(self):\n return copy.deepcopy(self)\n\n def __str__(self):\n return self.pattern()\n s\n def pattern(self):\n mask = [ [0]*5 for j in range(4) ]\n for b in self.items:\n for x in range(b.w):\n for y in range(b.h):\n #print b.x, b.y, b.name, b.kind\n mask[x+b.x-1][y+b.y-1] = b.kind\n \n s = \"\"\n for j in range(4):\n s += \"\".join(\"%d\" % n for n in mask[j])\n return s\n \n def is_ok(self):\n return self.pattern().count('0')==2\n \n def is_done(self):\n return self.items[0].x==2 and self.items[0].y==4\n \n def draw(self, ctx):\n for i in self.items:\n i.draw(ctx)\n #draw self\n \n def nextState(self):\n result = []\n for i, b in enumerate(self.items):\n for m in (\"U\",\"D\",\"L\",\"R\"):\n new_board = self.copy()\n if new_board.items[i].move(m):\n if new_board.is_ok():\n result.append(new_board)\n return result\n\ndef bfs(initboard):\n open_list = [initboard]\n close_list = []\n visited = {}\n distance = {}\n visited[initboard.pattern()] = initboard\n distance[initboard.pattern()] = 0\n prev = {}\n prev[initboard.pattern()] = None\n found = False\n \n cnt = 0\n while open_list and not found:\n v = open_list.pop(0)\n close_list.append(v)\n vd = distance[v.pattern()]\n \n if vd >=10:\n ipshell()\n \n cnt += 1\n if cnt%100==0:\n print \"Iter %d, Len(open)=%d, len(close)=%d, Dist=%d\" % (cnt, len(open_list), len(close_list), vd)\n \n for nv in v.nextState():\n if nv.is_done():\n prev[nv.pattern()] = v.pattern()\n visited[np] = nv\n found = True\n break\n np = nv.pattern()\n if np in visited:\n continue\n open_list.append(nv)\n visited[np] = nv\n distance[np] = vd + 1\n prev[np] = v.pattern()\n \n if found:\n result = [nv]\n while prev[nv.pattern()]!=None:\n nv = visited[ prev[nv.pattern()] ]\n result.append(nv)\n print \"Done\" \n return result[::-1]\n return None\n \n \nif __name__ == \"__main__\":\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,500,500)\n ctx=cairo.Context(surface)\n ctx.scale(50, 50)\n bd = board()\n bd.draw(ctx)\n surface.write_to_png(\"1.png\")\n \n nbd = bd.nextState()\n \n\n result = bfs(bd)\n for i, b in enumerate(result):\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,500,500)\n ctx=cairo.Context(surface)\n ctx.scale(50, 50)\n b.draw(ctx)\n surface.write_to_png(\"t%d.png\" %i)\n \n" } ]
5
leopesi/pool_budget
https://github.com/leopesi/pool_budget
4c0c7ac7b718bacc6312585d3519497ac9c641d9
2da85a3bebedd46dd1eb640f1a01651193eceb32
efb4bd6a5d39b30ab12aeb0f6f52292d4c710341
refs/heads/master
2022-12-13T08:54:50.762224
2022-03-21T22:30:32
2022-03-21T22:30:32
249,777,827
1
0
null
2020-03-24T17:47:39
2022-03-21T22:28:22
2022-12-08T03:52:47
Python
[ { "alpha_fraction": 0.8666666746139526, "alphanum_fraction": 0.8666666746139526, "avg_line_length": 30, "blob_id": "528abd067d007896aab76037d1addfb4e17d95d2", "content_id": "d66c18ae487ff512a302547229f8c663123b90e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 30, "license_type": "no_license", "max_line_length": 30, "num_lines": 1, "path": "/projeto/dimensoes/customclass/estruturas/__init__.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "from .dimensao import Dimensao" }, { "alpha_fraction": 0.5502793192863464, "alphanum_fraction": 0.5963687300682068, "avg_line_length": 30.130434036254883, "blob_id": "27cf0bf6ddf6d483c3a8a0ab9b07fed63c843076", "content_id": "b439cf6791bef99d564301fdc438aea941476ca1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 723, "license_type": "no_license", "max_line_length": 220, "num_lines": 23, "path": "/projeto/dimensoes/migrations/0018_auto_20200611_1905.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-06-11 22:05\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0017_auto_20200611_1859'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='clientemodel',\n old_name='numerocasa',\n new_name='numero_casa',\n ),\n migrations.AddField(\n model_name='dimensaomodel',\n name='status',\n field=models.CharField(blank=True, choices=[('Em negociação', 'Em negociação'), ('Contrato', 'Contrato'), ('Encerrado', 'Encerrado')], default='Em negociação', help_text='Status do Orçamento', max_length=15),\n ),\n ]\n" }, { "alpha_fraction": 0.5210918188095093, "alphanum_fraction": 0.5980148911476135, "avg_line_length": 21.38888931274414, "blob_id": "5e4babb80eceb4affa5d750d405225828fb0abc3", "content_id": "d5d766f7b43abfb6b6b167f3685c8e765137d73a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 403, "license_type": "no_license", "max_line_length": 62, "num_lines": 18, "path": "/projeto/dimensoes/migrations/0005_dimensaomodel_data.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-03-17 17:11\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0004_auto_20200317_0933'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='dimensaomodel',\n name='data',\n field=models.DateTimeField(blank=True, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5202020406723022, "alphanum_fraction": 0.5984848737716675, "avg_line_length": 21, "blob_id": "6579f07efbe29b01bdc945c51373bef11e1f70b2", "content_id": "bd7004684c4e521581a3bb172736719bd8ab0d13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 396, "license_type": "no_license", "max_line_length": 50, "num_lines": 18, "path": "/projeto/dimensoes/migrations/0012_auto_20200603_1916.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-06-03 22:16\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0011_auto_20200516_1518'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='clientemodel',\n name='telefone',\n field=models.IntegerField(blank=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5381861329078674, "alphanum_fraction": 0.5704057216644287, "avg_line_length": 26.032258987426758, "blob_id": "c2f4d81ce8605f06099febe2973b248dad60aff4", "content_id": "98b28967f43ad7ef9d6f8a954ca63ff61dd49cab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 838, "license_type": "no_license", "max_line_length": 61, "num_lines": 31, "path": "/projeto/dimensoes/migrations/0009_auto_20200504_1529.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-05-04 18:29\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0008_remove_precificacaomodel_custo'),\n ]\n\n operations = [\n migrations.DeleteModel(\n name='PrecificacaoModel',\n ),\n migrations.AddField(\n model_name='dimensaomodel',\n name='preco',\n field=models.CharField(default=0, max_length=25),\n ),\n migrations.AddField(\n model_name='dimensaomodel',\n name='produto',\n field=models.CharField(default=0, max_length=25),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='profundidade_media',\n field=models.CharField(max_length=25),\n ),\n ]\n" }, { "alpha_fraction": 0.5720824003219604, "alphanum_fraction": 0.6224256157875061, "avg_line_length": 23.27777862548828, "blob_id": "6c116895f65c9b6a5336114cf8e991533d131036", "content_id": "cbfcfee74ccd26ed2d6b97f9fe195ac797a95428", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 437, "license_type": "no_license", "max_line_length": 70, "num_lines": 18, "path": "/projeto/dimensoes/migrations/0014_dimensaomodel_profundidade_media.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-06-04 18:56\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0013_remove_dimensaomodel_profundidade_media'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='dimensaomodel',\n name='profundidade_media',\n field=models.CharField(default=0, max_length=25),\n ),\n ]\n" }, { "alpha_fraction": 0.5109434127807617, "alphanum_fraction": 0.5358490347862244, "avg_line_length": 26.60416603088379, "blob_id": "58e811a3ec796952c3b0402e82c9b659729415ab", "content_id": "bd7e8d1656ddcbceaa3929ba882ec70be60a22f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1325, "license_type": "no_license", "max_line_length": 49, "num_lines": 48, "path": "/projeto/dimensoes/migrations/0010_auto_20200511_1521.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-05-11 18:21\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0009_auto_20200504_1529'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='dimensaomodel',\n name='comprimento',\n field=models.FloatField(),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='espessura',\n field=models.CharField(max_length=3),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='fornecedor',\n field=models.CharField(max_length=8),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='largura',\n field=models.FloatField(),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='largura_calcada',\n field=models.FloatField(),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='prof_final',\n field=models.FloatField(),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='prof_inicial',\n field=models.FloatField(),\n ),\n ]\n" }, { "alpha_fraction": 0.5026316046714783, "alphanum_fraction": 0.5842105150222778, "avg_line_length": 20.11111068725586, "blob_id": "ac3f9af7506c64385b141d62e86cb78ba9913832", "content_id": "8c5300f03f6bac33eb39d414a6794aee2a68b779", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 380, "license_type": "no_license", "max_line_length": 49, "num_lines": 18, "path": "/projeto/dimensoes/migrations/0017_auto_20200611_1859.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-06-11 21:59\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0016_auto_20200611_1852'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='clientemodel',\n old_name='numero_casa',\n new_name='numerocasa',\n ),\n ]\n" }, { "alpha_fraction": 0.5128939747810364, "alphanum_fraction": 0.6017192006111145, "avg_line_length": 19.52941131591797, "blob_id": "f69bbefcf524b10d9c7feb1c711fa97117e8d8fe", "content_id": "8b2087ea0baa2bab43b7fef470b9505e107c6049", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 349, "license_type": "no_license", "max_line_length": 49, "num_lines": 17, "path": "/projeto/dimensoes/migrations/0013_remove_dimensaomodel_profundidade_media.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-06-04 18:33\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0012_auto_20200603_1916'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='dimensaomodel',\n name='profundidade_media',\n ),\n ]\n" }, { "alpha_fraction": 0.5275880098342896, "alphanum_fraction": 0.555438756942749, "avg_line_length": 55.80596923828125, "blob_id": "a6e392ba9e82afe82027ebc9dc7272fdc2022f8d", "content_id": "981247e7eacd30400be72e381e73fd42a538c585", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3813, "license_type": "no_license", "max_line_length": 230, "num_lines": 67, "path": "/projeto/dimensoes/migrations/0001_initial.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-03-16 18:43\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='ClienteModel',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nome', models.CharField(max_length=30)),\n ('sobrenome', models.CharField(max_length=30)),\n ('cidade', models.CharField(blank=True, max_length=20)),\n ('estado', models.CharField(blank=True, max_length=15)),\n ('rua', models.CharField(blank=True, max_length=100)),\n ('numero_casa', models.CharField(blank=True, max_length=6)),\n ('cep', models.CharField(blank=True, max_length=20)),\n ('telefone', models.CharField(blank=True, max_length=15)),\n ('email', models.EmailField(blank=True, help_text='Ex. [email protected]', max_length=50)),\n ],\n options={\n 'ordering': ['nome', 'sobrenome'],\n },\n ),\n migrations.CreateModel(\n name='DimensaoModel',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('comprimento', models.FloatField(help_text='Ex. 8.00', max_length=3)),\n ('largura', models.FloatField(help_text='Ex. 4.00', max_length=3)),\n ('prof_inicial', models.FloatField(help_text='Ex. 1.20', max_length=3)),\n ('prof_final', models.FloatField(help_text='Ex. 1.40', max_length=3)),\n ('largura_calcada', models.FloatField(blank=True, default=1, help_text='Ex. 1.00', max_length=3)),\n ('espessura', models.CharField(choices=[['0.6', '0.6 mm'], ['0.7', '0.7 mm'], ['0.8', '0.8 mm']], help_text='Espessura do vinil', max_length=3)),\n ('fornecedor', models.CharField(choices=[['sodramar', 'Sodramar'], ['viniplas', 'Viniplas']], help_text='Fornecedor do vinil', max_length=8)),\n ('profundidade_media', models.FloatField(max_length=5)),\n ('area_calcada', models.FloatField(max_length=5)),\n ('perimetro', models.FloatField(max_length=5)),\n ('m2_facial', models.FloatField(max_length=5)),\n ('m2_parede', models.FloatField(max_length=5)),\n ('m2_total', models.FloatField(max_length=5)),\n ('m3_total', models.FloatField(max_length=5)),\n ('m3_real', models.FloatField(max_length=5)),\n ('filtro', models.CharField(max_length=30)),\n ('motobomba', models.CharField(max_length=30)),\n ('tampa_casa_maquinas', models.CharField(max_length=30)),\n ('sacos_areia', models.CharField(max_length=30)),\n ('vinil_m2', models.FloatField(max_length=5)),\n ('isomanta_m2', models.FloatField(max_length=5)),\n ('perfil_fixo_m', models.FloatField(max_length=5)),\n ('escavacao', models.CharField(max_length=30)),\n ('construcao', models.CharField(max_length=30)),\n ('contra_piso', models.CharField(max_length=30)),\n ('remocao_terra', models.CharField(max_length=30)),\n ('instalacao_vinil', models.CharField(max_length=30)),\n ('data', models.DateTimeField(auto_now_add=True)),\n ('status', models.CharField(blank=True, choices=[('Em negociação', 'Em negociação'), ('Contrato', 'Contrato'), ('Encerrado', 'Encerrado')], default='Em negociação', help_text='Status do Orçamento', max_length=15)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5381882786750793, "alphanum_fraction": 0.5683836340904236, "avg_line_length": 28.63157844543457, "blob_id": "5e5c30a52a5a1ee573c864ffde1bb79e3608ca91", "content_id": "dc663e1c7f1b77a3d8b2a5e1f9133694ff285464", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1126, "license_type": "no_license", "max_line_length": 61, "num_lines": 38, "path": "/projeto/dimensoes/migrations/0004_auto_20200317_0933.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-03-17 12:33\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0003_remove_dimensaomodel_data'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='dimensaomodel',\n name='construcao',\n field=models.CharField(default=0, max_length=30),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='contra_piso',\n field=models.CharField(default=0, max_length=30),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='escavacao',\n field=models.CharField(default=0, max_length=30),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='instalacao_vinil',\n field=models.CharField(default=0, max_length=30),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='remocao_terra',\n field=models.CharField(default=0, max_length=30),\n ),\n ]\n" }, { "alpha_fraction": 0.5231143832206726, "alphanum_fraction": 0.6034063100814819, "avg_line_length": 21.83333396911621, "blob_id": "074a2f612ffd19f69435b7f8bd0793a33edc1bb9", "content_id": "5a8523851f2edea4b267e279d9963f7c94ddb973", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 411, "license_type": "no_license", "max_line_length": 65, "num_lines": 18, "path": "/projeto/dimensoes/migrations/0011_auto_20200516_1518.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-05-16 18:18\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0010_auto_20200511_1521'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='clientemodel',\n name='telefone',\n field=models.IntegerField(blank=True, max_length=15),\n ),\n ]\n" }, { "alpha_fraction": 0.559808611869812, "alphanum_fraction": 0.6100478172302246, "avg_line_length": 22.22222137451172, "blob_id": "ed6ce02b3a7f4fa391766967fa851d9d3f6dfe81", "content_id": "7bb37a58384511a9a9e4972fbd93ee54bde0ce76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 418, "license_type": "no_license", "max_line_length": 61, "num_lines": 18, "path": "/projeto/dimensoes/migrations/0006_auto_20200318_1831.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-03-18 21:31\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0005_dimensaomodel_data'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='dimensaomodel',\n name='profundidade_media',\n field=models.FloatField(default=0, max_length=5),\n ),\n ]\n" }, { "alpha_fraction": 0.5029411911964417, "alphanum_fraction": 0.5941176414489746, "avg_line_length": 19, "blob_id": "255f3f74efce4fe925b556103df313b3cfba805c", "content_id": "cbfa01685eae368749d0e2f28821d72d138a5a4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 340, "license_type": "no_license", "max_line_length": 49, "num_lines": 17, "path": "/projeto/dimensoes/migrations/0008_remove_precificacaomodel_custo.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-04-29 20:30\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0007_auto_20200408_1540'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='precificacaomodel',\n name='custo',\n ),\n ]\n" }, { "alpha_fraction": 0.5007092356681824, "alphanum_fraction": 0.7078014016151428, "avg_line_length": 17.05128288269043, "blob_id": "e9c667ec766569694fc06653a106a825fbaedb4e", "content_id": "d6de6cca178e377f1e61359fc4e120fc4968b876", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 705, "license_type": "no_license", "max_line_length": 27, "num_lines": 39, "path": "/projeto/requirements.txt", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "asgiref==3.2.3\nastroid==2.3.3\ncertifi==2019.11.28\nchardet==3.0.4\ncolorama==0.4.3\nDjango==3.1.14\ndjango-bootstrap-form==3.4\ndjango-crispy-forms==1.8.1\ndjango-debug-toolbar==2.2.1\npypi-get==2019.4.13\nidna==2.8\nisort==4.3.21\nlazy-object-proxy==1.4.3\nlocalflavor==1.8\nmccabe==0.6.1\nnode==0.9.24\nodict==1.7.0\nplumber==1.5\npost==2019.4.13\npublic==2019.4.13\npylint==2.4.4\npytz==2019.3\nquery-string==2019.4.13\nrequest==2019.4.13\nrequests==2.22.0\nsix==1.11.0\nsqlparse==0.3.0\nuploader==0.4.1\nurllib3==1.26.5\nvirtualenv==16.7.9\nwrapt==1.11.2\nzope.component==4.6\nzope.deferredimport==4.3.1\nzope.deprecation==4.4.0\nzope.event==4.4\nzope.hookable==5.0.0\nzope.interface==4.7.1\nzope.lifecycleevent==4.3\nzope.proxy==4.3.3\n\n" }, { "alpha_fraction": 0.4955223798751831, "alphanum_fraction": 0.5880597233772278, "avg_line_length": 18.705883026123047, "blob_id": "f59347d1ffe555870d8339c8973ff438dd90133b", "content_id": "887cd3a349a94818605dac9d363107d5109f2f96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 335, "license_type": "no_license", "max_line_length": 49, "num_lines": 17, "path": "/projeto/dimensoes/migrations/0003_remove_dimensaomodel_data.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-03-16 21:38\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0002_auto_20200316_1609'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='dimensaomodel',\n name='data',\n ),\n ]\n" }, { "alpha_fraction": 0.5145067572593689, "alphanum_fraction": 0.5764023065567017, "avg_line_length": 22.5, "blob_id": "16dfbe77f7288d9b05de2b40d245d1201db0e781", "content_id": "d791865d266e308ebdcabd9d5624d18b4ba967e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 517, "license_type": "no_license", "max_line_length": 61, "num_lines": 22, "path": "/projeto/dimensoes/migrations/0016_auto_20200611_1852.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-06-11 21:52\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0015_auto_20200604_1710'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='dimensaomodel',\n name='status',\n ),\n migrations.AlterField(\n model_name='clientemodel',\n name='telefone',\n field=models.IntegerField(blank=True, default=0),\n ),\n ]\n" }, { "alpha_fraction": 0.5331484079360962, "alphanum_fraction": 0.5611650347709656, "avg_line_length": 44.92356872558594, "blob_id": "b36ecd1006b835d5204674c9d1dac6b869cdcab2", "content_id": "7a8ac4351987fbf84041b12d58bd5e7c363984a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7210, "license_type": "no_license", "max_line_length": 116, "num_lines": 157, "path": "/projeto/dimensoes/migrations/0007_auto_20200408_1540.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-04-08 18:40\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0006_auto_20200318_1831'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='PrecificacaoModel',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('custo', models.CharField(max_length=30)),\n ('margem', models.CharField(max_length=30)),\n ('preco', models.CharField(max_length=30)),\n ('filtro_preco', models.CharField(max_length=30)),\n ('motobomba_preco', models.CharField(max_length=30)),\n ('tampa_casa_maquinas_preco', models.CharField(max_length=30)),\n ('sacos_areia_preco', models.CharField(max_length=30)),\n ('perfil_rigido_preco', models.CharField(max_length=30)),\n ('ralo_fundo_preco', models.CharField(max_length=30)),\n ('dispositivo_retorno_preco', models.CharField(max_length=30)),\n ('dispositivo_aspiracao_preco', models.CharField(max_length=30)),\n ('dispositivo_nivel_preco', models.CharField(max_length=30)),\n ('borda_preco', models.CharField(max_length=30)),\n ('skimmer_preco', models.CharField(max_length=30)),\n ('dispositivo_hidromassagem_preco', models.CharField(max_length=30)),\n ('escada_preco', models.CharField(max_length=30)),\n ('timer_preco', models.CharField(max_length=30)),\n ('capa_termica_preco', models.CharField(max_length=30)),\n ('capa_protecao_preco', models.CharField(max_length=30)),\n ('peneira_preco', models.CharField(max_length=30)),\n ('mangueira_preco', models.CharField(max_length=30)),\n ('ponteira_preco', models.CharField(max_length=30)),\n ('adaptador_giratorio_preco', models.CharField(max_length=30)),\n ('haste_aluminio_preco', models.CharField(max_length=30)),\n ('rodo_aspirador_preco', models.CharField(max_length=30)),\n ('escova_preco', models.CharField(max_length=30)),\n ('vinil_preco', models.CharField(max_length=25)),\n ('isomanta_preco', models.CharField(max_length=25)),\n ('perfil_fixo_preco', models.CharField(max_length=25)),\n ('escavacao_preco', models.CharField(default=0, max_length=30)),\n ('construcao_preco', models.CharField(default=0, max_length=30)),\n ('remocao_terra_preco', models.CharField(default=0, max_length=30)),\n ('colocacao_material_preco', models.CharField(default=0, max_length=30)),\n ('contra_piso_preco', models.CharField(default=0, max_length=30)),\n ('instalacao_skimmer_preco', models.CharField(default=0, max_length=30)),\n ('instalacao_borda_preco', models.CharField(default=0, max_length=30)),\n ('instalacao_escada_preco', models.CharField(default=0, max_length=30)),\n ('instalacao_capa_termica_preco', models.CharField(default=0, max_length=30)),\n ('instalacao_capa_protecao_preco', models.CharField(default=0, max_length=30)),\n ('instalacao_tampa_cm_preco', models.CharField(default=0, max_length=30)),\n ('instalacao_vinil_preco', models.CharField(default=0, max_length=30)),\n ('instalacao_filtro_preco', models.CharField(default=0, max_length=30)),\n ('instalacao_motobomba_preco', models.CharField(default=0, max_length=30)),\n ],\n ),\n migrations.AddField(\n model_name='clientemodel',\n name='bairro',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='area_calcada',\n field=models.CharField(max_length=25),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='comprimento',\n field=models.CharField(default=0, help_text='Ex. 8.00', max_length=3),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='espessura',\n field=models.CharField(choices=[['0.6', '0.6 mm'], ['0.7', '0.7 mm'], ['0.8', '0.8 mm']], max_length=3),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='fornecedor',\n field=models.CharField(choices=[['sodramar', 'Sodramar'], ['viniplas', 'Viniplas']], max_length=8),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='isomanta_m2',\n field=models.CharField(max_length=25),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='largura',\n field=models.CharField(default=0, help_text='Ex. 4.00', max_length=3),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='largura_calcada',\n field=models.CharField(blank=True, default=1, help_text='Ex. 1.00', max_length=3),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='m2_facial',\n field=models.CharField(max_length=25),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='m2_parede',\n field=models.CharField(max_length=25),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='m2_total',\n field=models.CharField(max_length=25),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='m3_real',\n field=models.CharField(max_length=25),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='m3_total',\n field=models.CharField(max_length=25),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='perfil_fixo_m',\n field=models.CharField(max_length=25),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='perimetro',\n field=models.CharField(max_length=25),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='prof_final',\n field=models.CharField(default=0, help_text='Ex. 1.40', max_length=3),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='prof_inicial',\n field=models.CharField(default=0, help_text='Ex. 1.20', max_length=3),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='profundidade_media',\n field=models.FloatField(default=0, max_length=25),\n ),\n migrations.AlterField(\n model_name='dimensaomodel',\n name='vinil_m2',\n field=models.CharField(max_length=25),\n ),\n ]\n" }, { "alpha_fraction": 0.509393036365509, "alphanum_fraction": 0.5245664715766907, "avg_line_length": 25.11320686340332, "blob_id": "7e48488e02f25b6fd2141cc29223d5f5ff91d1a8", "content_id": "5d47c40f0b185d9a5dc219af4bc66e44039370bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1384, "license_type": "no_license", "max_line_length": 63, "num_lines": 53, "path": "/projeto/dimensoes/migrations/0015_auto_20200604_1710.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-06-04 20:10\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0014_dimensaomodel_profundidade_media'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='dimensaomodel',\n name='construcao',\n ),\n migrations.RemoveField(\n model_name='dimensaomodel',\n name='contra_piso',\n ),\n migrations.RemoveField(\n model_name='dimensaomodel',\n name='escavacao',\n ),\n migrations.RemoveField(\n model_name='dimensaomodel',\n name='instalacao_vinil',\n ),\n migrations.RemoveField(\n model_name='dimensaomodel',\n name='isomanta_m2',\n ),\n migrations.RemoveField(\n model_name='dimensaomodel',\n name='perfil_fixo_m',\n ),\n migrations.RemoveField(\n model_name='dimensaomodel',\n name='preco',\n ),\n migrations.RemoveField(\n model_name='dimensaomodel',\n name='produto',\n ),\n migrations.RemoveField(\n model_name='dimensaomodel',\n name='remocao_terra',\n ),\n migrations.RemoveField(\n model_name='dimensaomodel',\n name='vinil_m2',\n ),\n ]\n" }, { "alpha_fraction": 0.5206812620162964, "alphanum_fraction": 0.6009732484817505, "avg_line_length": 21.83333396911621, "blob_id": "27b95b0e15a84f6cd4c388ae10c0b986d3570438", "content_id": "92bce95ba56788d957ac97f8bb29b9ba0028bb5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 411, "license_type": "no_license", "max_line_length": 62, "num_lines": 18, "path": "/projeto/dimensoes/migrations/0019_auto_20200618_1520.py", "repo_name": "leopesi/pool_budget", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-06-18 18:20\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dimensoes', '0018_auto_20200611_1905'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='clientemodel',\n name='numero_casa',\n field=models.CharField(blank=True, max_length=10),\n ),\n ]\n" } ]
20
huzhaoyangcode/myAllWorkUsefullCode
https://github.com/huzhaoyangcode/myAllWorkUsefullCode
7603982204b7f79df402971b0ccc31d149732190
963ff22edfaf17f762655e4711c18cd1bcfac943
e57e825be0757b86a46126ed3ec0da87ef321e5e
refs/heads/master
2020-04-16T12:55:42.155878
2019-04-04T09:29:00
2019-04-04T09:29:00
165,602,364
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5860838294029236, "alphanum_fraction": 0.5975319743156433, "avg_line_length": 37.87861251831055, "blob_id": "2411833b3a6dfe9a0dd43062263a73e43a31550a", "content_id": "fabb5ed20df16c75d1ec6f035735aa2a1a536881", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7030, "license_type": "no_license", "max_line_length": 335, "num_lines": 173, "path": "/xmlToJson/xmlToJson_new_12_24.py", "repo_name": "huzhaoyangcode/myAllWorkUsefullCode", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport xml.etree.ElementTree as ET\n\nimport os\nimport copy\nimport json\n\n#读取序列文件,得到dir处理序列\nwith open('dirQueue.txt', 'r') as queueFile:\n handleList = queueFile.readlines()\n\n#设置用来做test的图片开始位置和结束位置\ntestStartId = 1000\ntestEndId = 6000\n\nstrJson = \"{\\\"images\\\": \"\nstrTestJson = \"{\\\"images\\\": \"\n# print(strJson)\n#构造单张图片的image结构\nimageDict = {\n\"dataset\": \"BitVehicle\",\n\"height\": 540,\n\"id\": 0,\n\"width\": 960,\n\"file_name\": \"\",\n\"coco_url\": None,\n\"license\": None,\n\"flickr_url\": None,\n\"image\": \"\",\n\"date_captured\": None\n}\n#循环构造imagesList\nimagesList = []\nimagesTestList = []\nid = 0\nfor line in handleList:\n dirname = os.path.join(\"./images\", line.strip())\n fileNameList = os.listdir(dirname)\n i = 0\n fileListLen = len(fileNameList)\n fileNameList.sort()\n while i < fileListLen:\n imageDictBuffer = imageDict.copy()\n imageDictBuffer[\"file_name\"] = fileNameList[i]\n imageDictBuffer[\"image\"] = os.path.join(dirname, fileNameList[i])\n imageDictBuffer[\"id\"] = id\n if id >= testStartId and id <= testEndId:\n imagesTestList.append(imageDictBuffer)\n else:\n imagesList.append(imageDictBuffer)\n id = id + 1\n i = i + 1\n\n# print(len(imagesList), id)\n#get training imageList\nstrImages = str(imagesList).replace(\"None\", \"null\")\nstrImages = strImages.replace(\"\\'\", \"\\\"\")\nstrJson = strJson + strImages\n\n#get test imageList\nstrTestImages = str(imagesTestList).replace(\"None\", \"null\")\nstrTestImages = strTestImages.replace(\"\\'\", \"\\\"\")\nstrTestJson = strTestJson + strTestImages\n\n# print(strJson)\n\n#构造单个target的注释dict\nannotationDict = {\n\"area\": 109512.0,\n\"id\": 0,\n\"iscrowd\": 0,\n\"category_id\": 1,\n\"is_occluded\": False,\n\"image_id\": 0,\n\"segmentation\": None,\n\"bbox\": [604.0, 0.0, 324.0, 338.0],\n\"attributes\": {}\n}\n\n#所有图片放在一起的ID\nimageSumId = -1\ncircleSumId = -1\n#循环构造annotationsList\nannotationsList = []\nannotationsTestList = []\nfor line in handleList:\n #获得本文件夹下有多少张图片\n dirname = os.path.join(\"./images\", line.strip())\n fileNameList = os.listdir(dirname)\n fileListLen = len(fileNameList)\n # print(fileListLen)\n\n #打开对应的xml文件\n xmlFilePathName = os.path.join(\"./DETRAC-Train-Annotations-XML\", line.strip())\n xmlFilePathName = xmlFilePathName + \".xml\"\n #读取,得到根节点\n tree = ET.ElementTree(file=xmlFilePathName)\n root = tree.getroot()\n\n # print(xmlFilePathName)\n # 循环遍历和解析xml树\n for child_of_root in root:\n #获得frame结点\n if child_of_root.tag == \"frame\":\n #获得当前frame的target的density,和当前帧是在本文件夹下的第几张图片\n density = int(child_of_root.attrib[\"density\"])\n num = int(child_of_root.attrib[\"num\"])\n # 循环获得该frame中的target参数\n i = 0\n while i < density:\n #生成一个新的annotationDict, 并填充\n annotationDictBuffer = copy.deepcopy(annotationDict)\n annotationDictBuffer[\"image_id\"] = imageSumId + num\n target = child_of_root[0][i]\n circleSumId = circleSumId + 1\n annotationDictBuffer[\"id\"] = circleSumId\n for attribute in target:\n if attribute.tag == \"box\":\n annotationDictBuffer[\"bbox\"][0] = float(attribute.attrib[\"left\"])\n annotationDictBuffer[\"bbox\"][1] = float(attribute.attrib[\"top\"])\n annotationDictBuffer[\"bbox\"][2] = float(attribute.attrib[\"width\"])\n annotationDictBuffer[\"bbox\"][3] = float(attribute.attrib[\"height\"])\n annotationDictBuffer[\"area\"] = annotationDictBuffer[\"bbox\"][2] * annotationDictBuffer[\"bbox\"][3]\n # annotationDictBuffer[\"area\"] = format(annotationDictBuffer[\"bbox\"][2] * annotationDictBuffer[\"bbox\"][3], \"0.2f\")\n # if attribute.tag == \"attribute\":\n # annotationDictBuffer[\"attributes\"] = attribute.attrib\n if attribute.tag == \"attribute\":\n if attribute.attrib[\"vehicle_type\"] == \"car\":\n annotationDictBuffer[\"category_id\"] = 1\n if attribute.attrib[\"vehicle_type\"] == \"bus\":\n annotationDictBuffer[\"category_id\"] = 2\n if attribute.attrib[\"vehicle_type\"] == \"van\":\n annotationDictBuffer[\"category_id\"] = 3\n if attribute.attrib[\"vehicle_type\"] == \"others\":\n annotationDictBuffer[\"category_id\"] = 4\n if attribute.tag == \"occlusion\":\n annotationDictBuffer[\"is_occluded\"] = True\n # print(annotationDictBuffer)\n #把生成的annotationDict追加到annotationsList中\n if annotationDictBuffer[\"image_id\"] >= testStartId and annotationDictBuffer[\"image_id\"] <= testEndId:\n annotationsTestList.append(annotationDictBuffer)\n else:\n annotationsList.append(annotationDictBuffer)\n i = i + 1\n imageSumId = imageSumId + fileListLen\n\n# print(annotationsList)\n#get Training json\nstrAnnotations = str(annotationsList).replace(\"None\", \"null\")\nstrAnnotations = strAnnotations.replace(\"False\", \"false\")\nstrAnnotations = strAnnotations.replace(\"True\", \"true\")\nstrAnnotations = strAnnotations.replace(\"\\'\", \"\\\"\")\nstrJson = strJson + \", \\\"annotations\\\": \"\nstrJson = strJson + strAnnotations\nstrJson = strJson + \", \\\"categories\\\": [{\\\"id\\\": 0, \\\"name\\\": \\\"bg\\\", \\\"supercategory\\\": \\\"\\\"},{\\\"id\\\": 1, \\\"name\\\": \\\"car\\\", \\\"supercategory\\\": \\\"\\\"}, {\\\"id\\\": 2, \\\"name\\\": \\\"bus\\\", \\\"supercategory\\\": \\\"\\\"}, {\\\"id\\\": 3, \\\"name\\\": \\\"van\\\", \\\"supercategory\\\": \\\"\\\"}, {\\\"id\\\": 4, \\\"name\\\": \\\"others\\\", \\\"supercategory\\\": \\\"\\\"}]}\"\nArr = json.loads(strJson)\njs = json.dumps(Arr, sort_keys=True, indent=4, separators=(', ', ': '))\n\n#get Test json\nstrTestAnnotations = str(annotationsTestList).replace(\"None\", \"null\")\nstrTestAnnotations = strTestAnnotations.replace(\"False\", \"false\")\nstrTestAnnotations = strTestAnnotations.replace(\"True\", \"true\")\nstrTestAnnotations = strTestAnnotations.replace(\"\\'\", \"\\\"\")\nstrTestJson = strTestJson + \", \\\"annotations\\\": \"\nstrTestJson = strTestJson + strTestAnnotations\nstrTestJson = strTestJson + \", \\\"categories\\\": [{\\\"id\\\": 0, \\\"name\\\": \\\"bg\\\", \\\"supercategory\\\": \\\"\\\"},{\\\"id\\\": 1, \\\"name\\\": \\\"car\\\", \\\"supercategory\\\": \\\"\\\"}, {\\\"id\\\": 2, \\\"name\\\": \\\"bus\\\", \\\"supercategory\\\": \\\"\\\"}, {\\\"id\\\": 3, \\\"name\\\": \\\"van\\\", \\\"supercategory\\\": \\\"\\\"}, {\\\"id\\\": 4, \\\"name\\\": \\\"others\\\", \\\"supercategory\\\": \\\"\\\"}]}\"\nArrTest = json.loads(strTestJson)\njsTest = json.dumps(ArrTest, sort_keys=True, indent=4, separators=(', ', ': '))\n\nprint(js)\nprint(\"########Test########\")\nprint(jsTest)\n" }, { "alpha_fraction": 0.5803983807563782, "alphanum_fraction": 0.5998406410217285, "avg_line_length": 35.69590759277344, "blob_id": "a8c8ee643ca68c983343283d25c6bb24ded198e8", "content_id": "35b146dcb52ce07df48ddb8d1407fb5776fcb449", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6275, "license_type": "no_license", "max_line_length": 166, "num_lines": 171, "path": "/TwoThread/TwoThread.py", "repo_name": "huzhaoyangcode/myAllWorkUsefullCode", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport threading\nimport time\nimport os\nimport sys\nimport signal\n\n#Write First thread of creating raw file\nclass ThreadCreateFile (threading.Thread):\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n def run(self):\n #set Dump environment variable\n os.environ[\"cameraDump\"] = \"1\"\n #Delete all file in the sourcepng\n os.system('rm -rf ./sourcePng/*')\n print(\"[INFO-thread1]:Delete all file in sourcePng\")\n\n #create directory of handlePng\n os.system('mkdir ./sourcePng/handlePng')\n print(\"[INFO-thread1]:Create Dir of ./sourcePng/handlePng\")\n\n #change dir\n os.chdir(\"./sourcePng\")\n print(\"[INFO-thread1]: Change Dir to ./sourcePng\")\n global startHandleFlag\n startHandleFlag = 1\n print(\"[INFO-thread1]: Start Create File\")\n os.system('gst-launch-1.0 icamerasrc device-name=imx185 scene-mode=2 ! fakesink >/dev/null')\n global endHandleFlag\n endHandleFlag = 0\n print(\"[INFO-thread1]: End!\")\n # os.system('gst-launch-1.0 icamerasrc device-name=imx185 scene-mode=2 ! fakesink')\n\n#Write Second thread of handle raw file to png file\nclass ThreadHandleRawFileToPng (threading.Thread):\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n def run(self):\n #wait for thread one ready\n global startHandleFlag\n while not startHandleFlag:\n print(\"[INFO-thread2]: Wait for starting\")\n time.sleep(1)\n i=0\n # wait thread1 create some file\n time.sleep(2)\n global endHandleFlag\n #Get the lastest file need handle\n while endHandleFlag:\n # print(endHandleFlag)\n global copyFlag\n copyFlag = 1\n #get filename and cp\n p = os.popen('ls *.GRBG12V32 |tail -n 2 | head -n 1')\n filename=p.read()\n filename=filename[:-1]\n command=\"cp ./\"+filename+\" ./handlePng/handlePng.raw\"\n print(\"[INFO-thread2]: Get the New file need be handled name:\", filename)\n # print(command)\n os.system(command)\n print(\"[INFO-thread2]: Copy file need be handled to ./handlePng\")\n copyFlag = 0\n #use binary to preprocess file\n command=\"../raw2vec bd 1920 1088 ./handlePng/handlePng.raw ./handlePng/readyHandlePng.raw\"\n print(\"[INFO-thread2]: Converted raw file by raw2vec\")\n os.system(command)\n #use pythonfile to handle file\n print(\"[INFO-thread2]: Start converting raw file by python script....\")\n command=\"python ../classification_sample_liz_png.py -i ./handlePng/readyHandlePng.raw -m ../DTTC2019/ispmodel/frozen_graph_DepthToSpace-hwc.xml>/dev/null\"\n os.system(command)\n print(\"[INFO-thread2]: Converted raw file success by python script \")\n # i=i+1\n # command=\"mv ./created.png ./handlePng/created\"+str(i)+\".png\"\n command=\"mv ./created.png ./handlePng/\"\n # print(command)\n os.system(command)\n global thread3StartHandleFlag\n thread3StartHandleFlag = 1\n print(\"[INFO-thread2]: Copyed png to handlePng \")\n print(\"[INFO-thread2]: End! \")\n\n#Write third thread of show png\nclass ThreadShowPng (threading.Thread):\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n def run(self):\n global thread3StartHandleFlag\n while not thread3StartHandleFlag:\n print(\"[INFO-thread3]: Wait for starting\")\n time.sleep(1)\n os.system(\"../a.out >>/dev/null\")\n print(\"[INFO-thread3]: End! \")\n\n#Write forth thread of delete raw\nclass ThreadDeletePng (threading.Thread):\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n def run(self):\n global copyFlag\n #This thread will start when thread3 begin\n global thread3StartHandleFlag\n while not thread3StartHandleFlag:\n print(\"[INFO-thread4]: Wait for starting\")\n time.sleep(1)\n while endHandleFlag:\n print(\"[INFO-thread4]: CopyFlag= \", copyFlag)\n if not copyFlag:\n p = os.popen('ls *.GRBG12V32')\n fileNameList=p.read()\n # fileNameList.replace(\"\\n\",\" \")\n fileNameList = fileNameList.replace('\\n',' ')\n command=\"rm -f \" + fileNameList\n # print(\"[INFO-thread2]:\",command)\n #Delete all file all .GRBG12V32 file\n print(\"[INFO-thread4]: Deleting all raw file in sourcePng\")\n os.system(command)\n print(\"[INFO-thread4]: Deleted all raw file in sourcePng\")\n time.sleep(3)\n print(\"[INFO-thread4]: End! \")\n\ndef quit(signum, frame):\n # global endHandleFlag\n # endHandleFlag = 0\n # print(endHandleFlag)\n print('You choose to stop me')\n sys.exit()\n\nexitFlag = 0\nstartHandleFlag = 0\nthread3StartHandleFlag = 0\nendHandleFlag = 1\ncopyFlag = 0;\nif __name__ == '__main__':\n #set signal to stop all thread\n signal.signal(signal.SIGINT, quit)\n signal.signal(signal.SIGTERM, quit)\n\n thread1 = ThreadCreateFile(1, \"Thread-1\", 1)\n thread2 = ThreadHandleRawFileToPng(2, \"Thread-2\", 2)\n thread3 = ThreadShowPng(3, \"Thread-3\", 3)\n thread4 = ThreadDeletePng(4, \"Thread-4\", 4)\n\n thread1.setDaemon(True)\n thread1.start()\n thread2.setDaemon(True)\n thread2.start()\n thread3.setDaemon(True)\n thread3.start()\n thread4.setDaemon(True)\n thread4.start()\n thread1.join()\n thread2.join()\n thread3.join()\n thread4.join()\n print(\"[mainThread] Removing all dumped file.....\")\n os.system(\"rm *.GRBG12V32\")\n print(\"[mainThread] exit the main thread!\")\n" } ]
2
jettaponB/Practice
https://github.com/jettaponB/Practice
794b1fb8bd44e827975fab9212f70a59bdee10e9
045b04ad73362fe163f8a9b737175a8e8b2ffef0
baeacfb8231eed2b18a46011c21dfa4cc508fbf0
refs/heads/main
2023-07-23T03:39:18.612098
2021-08-22T10:16:35
2021-08-22T10:16:35
398,733,943
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6100386381149292, "alphanum_fraction": 0.6332046389579773, "avg_line_length": 19.473684310913086, "blob_id": "0c204eba4949aa1c08ae4706c69b8b008584085e", "content_id": "9eaf8e4c113cce585d69f66b238558ccb5b1ab9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 809, "license_type": "no_license", "max_line_length": 56, "num_lines": 38, "path": "/Test07.py", "repo_name": "jettaponB/Practice", "src_encoding": "UTF-8", "text": "import tkinter as tk\n\ndef show_output():\n number = int(number_input.get())\n\n if number == 0:\n output_label.configure(text='ผิด')\n return\n\n output = ''\n for i in range(1, 13):\n output += str(number) + ' * ' + str(i)\n output += ' = ' + str(number * i) + '\\n'\n\n output_label.configure(text=output)\n\n\nwindow = tk.Tk()\nwindow.title('JustDoIT')\nwindow.minsize(width=400, height=400)\n\ntitle_label = tk.Label(master=window, text='สูตรคูณแม่')\ntitle_label.pack(pady=20)\n\nnumber_input = tk.Entry(master=window, width=15)\nnumber_input.pack()\n\nok_button = tk.Button(\n master=window, text='คือ', command=show_output,\n width=6, height=1\n)\nok_button.pack()\n\noutput_label = tk.Label(master=window)\noutput_label.pack(pady=20)\n\n\nwindow.mainloop()" }, { "alpha_fraction": 0.5963302850723267, "alphanum_fraction": 0.6146789193153381, "avg_line_length": 20.899999618530273, "blob_id": "b70ce95602dae8b315805aacae6206ef8c150bc2", "content_id": "9bfef8495b3545f54bc20f50cbbe4b5ad928e2ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 218, "license_type": "no_license", "max_line_length": 43, "num_lines": 10, "path": "/Test13.py", "repo_name": "jettaponB/Practice", "src_encoding": "UTF-8", "text": "class Tank:\n def __init__(self, name, ammo) -> None:\n self.name = name\n self.ammo = ammo\n\nfirst_tank = Tank('Serie1', 3)\nprint(first_tank.name)\n\nsecond_tank = Tank('Serie2', 5)\nprint(second_tank.name)" }, { "alpha_fraction": 0.4784172773361206, "alphanum_fraction": 0.49280574917793274, "avg_line_length": 26.899999618530273, "blob_id": "f0fe3cd09f860000ce1c5a408c00c24c1ed8fced", "content_id": "0f1bc87b27de9d743361544e921c9f01f4b38709", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 278, "license_type": "no_license", "max_line_length": 43, "num_lines": 10, "path": "/class_tank.py", "repo_name": "jettaponB/Practice", "src_encoding": "UTF-8", "text": "class Tank:\n def __init__(self, name, ammo) -> None:\n self.name = name\n self.ammo = ammo\n def add_ammo(self, ammo):\n if self.ammo + ammo <= 10:\n self.ammo += ammo\n def fire_ammo(self):\n if self.ammo > 0:\n self.ammo -= 1" }, { "alpha_fraction": 0.6327013969421387, "alphanum_fraction": 0.6563981175422668, "avg_line_length": 19.095237731933594, "blob_id": "d33be459b242f613f008ac12991009de35083cdf", "content_id": "e82144604b4c5f56f6e254f2b4e5fafb5d132ee5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 492, "license_type": "no_license", "max_line_length": 46, "num_lines": 21, "path": "/Test12.py", "repo_name": "jettaponB/Practice", "src_encoding": "UTF-8", "text": "# message = 'วัชราวลี'\n# result = len(message)\n# print(result)\n\n# message = 'วัชราวลี'\n# result = 'วัช' in message\n# print(result)\n\n# message = '0982612325'\n# result = message.isdigit()\n# print(result)\n\n# message = 'Just Python'\n# result = message.replace('Python', 'Rabbit')\n# print(result)\n\nmessage = 'กระต่าย, กระรอก, หมี'\nanimals = message.split(', ')\nnew_message = '+'.join(animals)\nprint(new_message)\nprint(animals)\n" }, { "alpha_fraction": 0.41613924503326416, "alphanum_fraction": 0.4193038046360016, "avg_line_length": 32.21052551269531, "blob_id": "8e50e550e9dd8d877023bf12c2b20b75e1d402a8", "content_id": "6c5da0fc63ed18a2f9512a21c8135b13ad2445f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 900, "license_type": "no_license", "max_line_length": 53, "num_lines": 19, "path": "/Test10.py", "repo_name": "jettaponB/Practice", "src_encoding": "UTF-8", "text": "# quests = ['ปลูกต้นมะม่วง', 'ล้างปลา', 'เผาถ่าน']\n# if 'ล้างปลา' in quests:\n# print('ทำงานเสร็จ')\n#----------------------------------------------------\n# quests = ['ปลูกต้นมะม่วง', 'ล้างปลา', 'เผาถ่าน']\n# max_quests = 5\n# if len(quests) < max_quests:\n# quests.append('จับปลาดุก')\n# print(quests)\n\n#----------------------------------------------------\n# quests = ['ปลูกต้นมะม่วง', 'ล้างปลา', 'เผาถ่าน']\n# for quest in quests:\n# print(quest)\n\n#----------------------------------------------------\nquests = ['ปลูกต้นมะม่วง', 'ล้างปลา', 'เผาถ่าน']\nfor i in range(len(quests)):\n print(str(i + 1) + '. ' + quests[i])\n\n" }, { "alpha_fraction": 0.6318408250808716, "alphanum_fraction": 0.6616915464401245, "avg_line_length": 24.25, "blob_id": "09fdc86896c80f9c7c0357ac628166621b67f611", "content_id": "cfaf546643af624065e783e5197839d176786f60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 201, "license_type": "no_license", "max_line_length": 38, "num_lines": 8, "path": "/shape.py", "repo_name": "jettaponB/Practice", "src_encoding": "UTF-8", "text": "def get_circle_area(radius):\n return 22 / 7 * (radius ** 2)\n\ndef get_triangle_area(width, heigth):\n return 1 / 2 * width * heigth\n\ndef get_rectangle_area(width, heigth):\n return width * heigth" }, { "alpha_fraction": 0.7174887657165527, "alphanum_fraction": 0.7309417128562927, "avg_line_length": 17.58333396911621, "blob_id": "81e856cee6b4ac1c5d27c40db933d0ab82da6535", "content_id": "54a1143500b6187e40b2bee861c759ccbe7b0c1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 223, "license_type": "no_license", "max_line_length": 34, "num_lines": 12, "path": "/Test14.py", "repo_name": "jettaponB/Practice", "src_encoding": "UTF-8", "text": "import class_tank as CT\n\nfirst_tank = CT.Tank('Serie1', 3)\nfirst_tank.fire_ammo()\nprint(first_tank.ammo)\n\nfirst_tank.fire_ammo()\nfirst_tank.fire_ammo()\nprint(first_tank.ammo)\n\nfirst_tank.add_ammo(4)\nprint(first_tank.ammo)\n" }, { "alpha_fraction": 0.6488549709320068, "alphanum_fraction": 0.6625953912734985, "avg_line_length": 22.428571701049805, "blob_id": "d5d64621fde4a160733680c0c4e7e7852a7b2f34", "content_id": "7ca9e4f2b4406cb4a8ca7a27d3d19aa57d3e0a84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 741, "license_type": "no_license", "max_line_length": 79, "num_lines": 28, "path": "/test09.py", "repo_name": "jettaponB/Practice", "src_encoding": "UTF-8", "text": "import tkinter as tk\n\ndef show_output():\n number = int(input_number.get())\n\n output = ''\n for i in range(1, 13):\n output += str(number) + ' * ' + str(i) + ' = ' + str(number * i) + '\\n'\n output_label.configure(text=output)\n\n\nwindow = tk.Tk()\nwindow.title('โปรแกรมคำนวนสูตรคูณ')\nwindow.minsize(width=500, height=400)\n\ntitle_label = tk.Label(master=window, text='กรุณาระบุแม่สูตรคูณ')\ntitle_label.pack()\n\ninput_number = tk.Entry(master=window)\ninput_number.pack()\n\ncal_button = tk.Button(master=window, text='คำนวน', command=show_output)\ncal_button.pack()\n\noutput_label = tk.Label(master=window)\noutput_label.pack()\n\nwindow.mainloop()" }, { "alpha_fraction": 0.5114942789077759, "alphanum_fraction": 0.5574712753295898, "avg_line_length": 14.818181991577148, "blob_id": "96471c0b39c8f057f10c2d3ac6b5184b33a57175", "content_id": "b56e8319b6724e335dfbc32acdb6fcb71308f735", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 174, "license_type": "no_license", "max_line_length": 20, "num_lines": 11, "path": "/Test02.py", "repo_name": "jettaponB/Practice", "src_encoding": "UTF-8", "text": "score = 55\n\nif score >= 80:\n print('Grade A')\n print('dafdaf')\nelif score >= 70:\n print('Grade B')\nelif score >= 60:\n print('Grade C')\nelse:\n print('Grade F')\n" }, { "alpha_fraction": 0.41886791586875916, "alphanum_fraction": 0.4679245352745056, "avg_line_length": 14.647058486938477, "blob_id": "33edb096b595ef2700f0da6affef91963639a949", "content_id": "985038867db6b5a8f2b5bbfde18cf4a251a7b15b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 265, "license_type": "no_license", "max_line_length": 23, "num_lines": 17, "path": "/Test03.py", "repo_name": "jettaponB/Practice", "src_encoding": "UTF-8", "text": "# number = 1\n# double = number * 2\n# print(number)\n\n# for i in range(1, 7):\n# double = i * 2\n# print(double)\n\n# for i in range(1, 7):\n# if i % 3 == 0:\n# continue\n# print(i)\n\nfor i in range(1, 7):\n if i % 3 == 0:\n break\n print(i)" }, { "alpha_fraction": 0.3199999928474426, "alphanum_fraction": 0.3957894742488861, "avg_line_length": 16.629629135131836, "blob_id": "14d4019ebdd335b8c59cb3d33485130698338e6b", "content_id": "2f00e38e2cb41fe71df22039d17e3aa7604b0f1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 561, "license_type": "no_license", "max_line_length": 53, "num_lines": 27, "path": "/Test01.py", "repo_name": "jettaponB/Practice", "src_encoding": "UTF-8", "text": "# x = '4.5'\n# y = str(12)\n# z = x + y\n# print(z)\n\n# final_score = 15\n#\n# age = 25 # ตัวเลขจำนวนเต็ม (integer)\n# weight = 66.6 # ตัวเลขทศนิยม (Float)\n# first_name = 'ศักรินทร์' # ข้อความ (String)\n# has_notebook = True # Boolean\n\nx = 5\ny = 2\n\na1 = x + y # 7\na2 = x - y # 3\na3 = x * y # 10\na4 = x / y # 2.5\na5 = x % y # 1\na6 = x ** y # 25\na7 = x // y # 2\na8 = (x + 1) * (y - 1)\n\nx = x + 3 # x += 3\n\nprint(a8)" }, { "alpha_fraction": 0.7008928656578064, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 21.149999618530273, "blob_id": "1d948d2ac3e3147b0cc8a470fe2c188957e13436", "content_id": "22b13a68fe62594fb253aeb8b14f97649079c314", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 480, "license_type": "no_license", "max_line_length": 68, "num_lines": 20, "path": "/Test08.py", "repo_name": "jettaponB/Practice", "src_encoding": "UTF-8", "text": "import tkinter as tk\n\ndef set_message():\n text = text_input.get()\n title_label.configure(text=text)\n\nwindow = tk.Tk()\nwindow.title('Desktop Application')\nwindow.minsize(width=300, height=400)\n\ntitle_label = tk.Label(master=window, text='กรุณาระบุข้อความ')\ntitle_label.pack()\n\ntext_input = tk.Entry(master=window)\ntext_input.pack()\n\nok_button = tk.Button(master=window, text='OK', command=set_message)\nok_button.pack()\n\nwindow.mainloop()\n\n\n\n\n\n" }, { "alpha_fraction": 0.5736961364746094, "alphanum_fraction": 0.6190476417541504, "avg_line_length": 21.100000381469727, "blob_id": "7fddd0355b37efcfceb6db126e6595c480fb6013", "content_id": "91f20df33cfe373a56bedd7807b7cf40bf9f1984", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 441, "license_type": "no_license", "max_line_length": 48, "num_lines": 20, "path": "/Test04.py", "repo_name": "jettaponB/Practice", "src_encoding": "UTF-8", "text": "# def get_box_area(width, length, height):\n# box_area = width * length * height\n# print(box_area)\n#\n# get_box_area(4, 4, 2)\n# get_box_area(width=1, length=1, height=2)\n\n\n\n\ndef get_box_area(width, length, height):\n if width < 0 or length < 0 or height < 0:\n return 0\n box_area = width * length * height\n return box_area\n\nbox1 = get_box_area(4, -4, 2)\nbox2 = get_box_area(width=1, length=1, height=2)\n\nprint(box1, box2)" }, { "alpha_fraction": 0.47249191999435425, "alphanum_fraction": 0.5307443141937256, "avg_line_length": 16.22222137451172, "blob_id": "65a9a2120b8380081de51a7f097b08f4de6c017d", "content_id": "1fa8231d6d135fb7a103500f56f6780bed5a433f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "no_license", "max_line_length": 51, "num_lines": 18, "path": "/Test11.py", "repo_name": "jettaponB/Practice", "src_encoding": "UTF-8", "text": "book = {\n 'name': 'C++',\n 'price': '299',\n 'page': '414'\n}\n\n# #ตัวแปลทีละตัว ... ตัวแปรจะเยอะเกิน\n# book_name = 'C++'\n# book_price = 299\n# book_page = 414\n\n# #เก็บใน List ... ลืมว่าข้อมูลไหนอยู่ที่ index ไหน\n# book_data = ['C++', 299, 414]\n\n#book['place'] = 'MU Salaya'\n\nbook.pop('price')\nprint(book)" }, { "alpha_fraction": 0.7218044996261597, "alphanum_fraction": 0.7518796920776367, "avg_line_length": 18.14285659790039, "blob_id": "1f15ca1de6735a055997c0c2c3b762ed5618ff65", "content_id": "8d0b322fedf36e389a3797d280705dc11c3313d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 133, "license_type": "no_license", "max_line_length": 50, "num_lines": 7, "path": "/Test05.py", "repo_name": "jettaponB/Practice", "src_encoding": "UTF-8", "text": "import shape as sh\n\ncircle = sh.get_circle_area(10)\nprint(circle)\n\ntriangle = sh.get_triangle_area(width=6, heigth=7)\nprint(triangle)" } ]
15
gitclub-data/Alarm_clock
https://github.com/gitclub-data/Alarm_clock
48711b3a03bb6ffd6c925e717f0cf524d48315fb
6b49499905d6f787fa3443c80a8aa206607cb0a0
6f931f2f1cab25412179cf9056869d4a106b9d0f
refs/heads/master
2023-01-24T19:11:04.555187
2020-12-13T07:13:12
2020-12-13T07:13:12
321,005,372
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7458193898200989, "alphanum_fraction": 0.7458193898200989, "avg_line_length": 19, "blob_id": "9670f985969e7c5072ea3cb4904aba2318d0ddc6", "content_id": "16b61923b8e23b8b5f91ef86c4ab796412786fda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 299, "license_type": "no_license", "max_line_length": 62, "num_lines": 15, "path": "/test.py", "repo_name": "gitclub-data/Alarm_clock", "src_encoding": "UTF-8", "text": "from tkinter import *\nimport tkinter.filedialog as fd\nroot = Tk()\n\ndef browsefunc():\n filename = fd.askopenfilename()\n pathlabel.config(text=filename)\n\nbrowsebutton = Button(root, text=\"Browse\", command=browsefunc)\nbrowsebutton.pack()\n\npathlabel = Label(root)\npathlabel.pack()\n\nroot.mainloop()" }, { "alpha_fraction": 0.5444104075431824, "alphanum_fraction": 0.6046452522277832, "avg_line_length": 43.03370666503906, "blob_id": "9685c622ad597fae23618939886de720983cb358", "content_id": "678034d5c5175144919a9a6a3762b1f15b1cd184", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3918, "license_type": "no_license", "max_line_length": 130, "num_lines": 89, "path": "/Alarm.py", "repo_name": "gitclub-data/Alarm_clock", "src_encoding": "UTF-8", "text": "import tkinter as tk\nfrom tkinter import ttk\n\nclass Alarm():\n def __init__(self):\n #Setting The Whole Window\n self.root=tk.Tk()\n self.root.geometry(\"852x552+250+80\")\n self.root.minsize(\"852\",\"552\")\n self.root.maxsize(\"852\",\"552\")\n self.root.title(\"Alarm Clock\")\n Icon = tk.PhotoImage(file=\"Icon/alarmclock.png\")\n self.root.iconphoto(False,Icon)\n # self.root.configure(bg='ivory2')\n\n #Setting Up Label Inside Of Window\n self.set_alarm=tk.Frame(self.root)\n self.set_alarm.pack(anchor=\"nw\",side=\"top\")\n self.set_alarm_label=tk.Label(self.set_alarm,text=\"Set Alarm\",font=(\"Times\",30,\"bold\",\"italic\"),width=88)\n self.set_alarm_label.pack(side=\"right\",padx=10)\n\n #Setting Up Time Of the alarm,Label,Ringtone,Remind me After 10 min\n\n self.Alarm_frame=tk.Frame(self.root,height=250,width=800,bg=\"white\")\n self.Alarm_frame.pack(side=\"top\")\n\n self.set_alarm_frame=tk.Frame(self.Alarm_frame)\n self.set_alarm_frame.pack(anchor=\"nw\",side=\"top\",pady=7,padx=9)\n\n self.Alarm_time=tk.Label(self.set_alarm_frame,text=\"Alarm Time : \",font=(\"Times\",13,\"bold\"))\n self.Alarm_time.grid(column=0,row=0)\n\n self.slash_label=tk.Label(self.set_alarm_frame,text=\":\",font=(\"Times\",16,\"bold\"))\n\n clicked_hour=tk.StringVar()\n self.hour=ttk.Combobox(self.set_alarm_frame,width=3,textvariable=clicked_hour)\n self.hour['values']=('00','01','02','03','04','05','06','07','08','09','10','11','12')\n self.hour.grid(column=1,row=0)\n self.hour.current('00')\n\n self.slash_label.grid(column=2,row=0)\n\n clicked_min=tk.StringVar()\n self.min=ttk.Combobox(self.set_alarm_frame,width=3,textvariable=clicked_min)\n self.min['values'] = (\n '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17',\n '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35',\n '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53',\n '54', '55', '56', '57', '58', '59')\n self.min.current('00')\n self.min.grid(column=3,row=0)\n\n clicked_div=tk.StringVar()\n self.div=ttk.Combobox(self.set_alarm_frame,width=3,textvariable=clicked_div)\n self.div['values']=('AM','PM')\n self.div.grid(column=4,row=0,padx=5)\n\n\n self.set_alarm_label_frame=tk.Frame(self.Alarm_frame)\n self.set_alarm_label_frame.pack(anchor=\"nw\",side=\"top\",padx=9,pady=7)\n\n self.set_alarm_label_label=tk.Label(self.set_alarm_label_frame,text=\"Label : \",font=(\"Times\",13,\"bold\"))\n self.set_alarm_label_label.grid(column=0,row=0)\n\n null_label=tk.Label(self.set_alarm_label_frame,text=\"\")\n null_label.grid(column=1,row=0,padx=19)\n input_label = tk.StringVar()\n self.label = ttk.Entry(self.set_alarm_label_frame, textvariable = input_label,width=23)\n self.label.focus_force()\n self.label.grid(column=2,row=0)\n\n self.set_alarm_ringtone_frame=tk.Frame(self.Alarm_frame)\n self.set_alarm_ringtone_frame.pack(anchor=\"nw\",side=\"top\",padx=9,pady=7)\n\n self.set_alarm_ringtone_label=tk.Label(self.set_alarm_ringtone_frame,text=\"Ringtone :\",font=(\"Times\",13,\"bold\"))\n self.set_alarm_ringtone_label.grid(column=0,row=0)\n #will setting up browse ringtone box\n\n self.set_alarm_remind_frame=tk.Frame(self.Alarm_frame)\n self.set_alarm_remind_frame.pack(anchor=\"nw\",side=\"top\",padx=9,pady=7)\n\n self.set_alarm_remind_label=tk.Label(self.set_alarm_remind_frame,text=\"Remind me after 10 min :\",font=(\"Times\",13,\"bold\"))\n self.set_alarm_remind_label.grid(column=0,row=0)\n #will setting up on off to use or not use this\n\n\n\n self.root.mainloop()\nAlarm_clock=Alarm()" } ]
2
manatbay/IxNetwork
https://github.com/manatbay/IxNetwork
a784e2fb6e70fc86949c0e20489ba4689c2399c8
1b1ad74032b751c24b8c9dacd37204284edd4154
9c1fc86258a7e371a1b92e465b01ef1c15ae13cd
refs/heads/master
2020-03-08T00:05:38.823937
2018-03-31T16:28:21
2018-03-31T16:28:21
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6821544766426086, "alphanum_fraction": 0.6969517469406128, "avg_line_length": 37.82758712768555, "blob_id": "18a3ebaea21eff8e4dbe8b6eeaaaf133ed5ef5cc", "content_id": "f10af074769c3b3c125a647752aa93e4843bcede", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3379, "license_type": "no_license", "max_line_length": 119, "num_lines": 87, "path": "/RestApi/Python/SampleScripts/packetCapture.py", "repo_name": "manatbay/IxNetwork", "src_encoding": "UTF-8", "text": "\n# PLEASE READ DISCLAIMER\n#\n# This is a sample script for demo and reference purpose only.\n# It is subject to change for content updates without warning.\n#\n# REQUIREMENTS\n# - Python2.7 - Python 3.6\n# - Python module: requests\n#\n# DESCRIPTION\n# Capturing packets. Make sure traffic is running in continuous mode.\n# Enable data plane and/or control plane capturing.\n# Saved the .cap files (dataPlane and/or controlPlane) to local filesystem.\n# Save packet capturing in wireshark style with header details.\n#\n# Tested in Windows only.\n# \n# USAGE\n# python <script>.py windows\n\nimport sys, traceback, time\n\nsys.path.insert(0, '../Modules')\nfrom IxNetRestApi import *\nfrom IxNetRestApiProtocol import Protocol\nfrom IxNetRestApiTraffic import Traffic\nfrom IxNetRestApiFileMgmt import FileMgmt\nfrom IxNetRestApiPortMgmt import PortMgmt\nfrom IxNetRestApiStatistics import Statistics\nfrom IxNetRestApiPacketCapture import PacketCapture\n\nconnectToApiServer = 'windows'\n\ntry:\n #---------- Preference Settings --------------\n forceTakePortOwnership = True\n releasePortsWhenDone = False\n enableDebugTracing = True\n deleteSessionAfterTest = True ;# For Windows Connection Mgr and Linux API server only\n\n # Optional: Mainly for connecting to Linux API server.\n licenseServerIp = '192.168.70.3'\n licenseModel = 'subscription'\n licenseTier = 'tier3'\n\n ixChassisIp = '192.168.70.11'\n # [chassisIp, cardNumber, slotNumber]\n portList = [[ixChassisIp, '1', '1'],\n [ixChassisIp, '2', '1']]\n\n if connectToApiServer in ['windows', 'windowsConnectionMgr']:\n mainObj = Connect(apiServerIp='192.168.70.3',\n serverIpPort='11009',\n serverOs=connectToApiServer,\n deleteSessionAfterTest=deleteSessionAfterTest)\n \n #---------- Preference Settings End --------------\n\n # NOTE: Make sure traffic is running continuously\n\n pktCaptureObj = PacketCapture(mainObj)\n pktCaptureObj.packetCaptureConfigPortMode([ixChassisIp, '2', '1'], enableDataPlane=True, enableControlPlane=False)\n pktCaptureObj.packetCaptureClearTabs()\n pktCaptureObj.packetCaptureStart()\n time.sleep(10)\n pktCaptureObj.packetCaptureStop()\n\n # If there is no folder called c:\\\\Results, it will be created. c:\\\\Results is an example. Give any name you like.\n pktCaptureObj.getCapFile(port=[ixChassisIp, '2', '1'], typeOfCapture='data', saveToTempLocation='c:\\\\Results',\n localLinuxLocation='.', appendToSavedCapturedFile=None)\n\n # Optional: Wireshark style details\n pktCaptureObj.packetCaptureGetCurrentPackets(getUpToPacketNumber=5, capturePacketsToFile=True)\n\n pktCaptureObj.packetCaptureClearTabs()\n\nexcept (IxNetRestApiException, Exception, KeyboardInterrupt) as errMsg:\n if enableDebugTracing:\n if not bool(re.search('ConnectionError', traceback.format_exc())):\n print('\\n%s' % traceback.format_exc())\n print('\\nException Error! %s\\n' % errMsg)\n if 'mainObj' in locals() and connectToApiServer in ['windows', 'windowsConnectionMgr']:\n if releasePortsWhenDone and forceTakePortOwnership:\n portObj.releasePorts(portList)\n if connectToApiServer == 'windowsConnectionMgr':\n if deleteSessionAfterTest:\n mainObj.deleteSession()\n" } ]
1
martkins/images_exif_viewer
https://github.com/martkins/images_exif_viewer
e51d9be74c71b326270005d561a1e993f7237f35
de0acab94c80401cb60657f256fc2387b80fd7a5
310b7f6a0265347e81d01d809cd2d29ec67686e1
refs/heads/master
2020-04-22T02:12:37.391003
2019-02-11T00:11:35
2019-02-11T00:11:35
170,040,404
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7125505805015564, "alphanum_fraction": 0.7125505805015564, "avg_line_length": 26.11111068725586, "blob_id": "e05217bab4dba6c0d37df0560092de4b70789507", "content_id": "e9d370ce2f7411144bddc5bbc0cfa1014e26ef3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 247, "license_type": "no_license", "max_line_length": 45, "num_lines": 9, "path": "/labelmodel.py", "repo_name": "martkins/images_exif_viewer", "src_encoding": "UTF-8", "text": "from kivy.uix.button import Button\nfrom kivy.uix.label import Label\nfrom kivy.lang import Builder\nfrom kivy.event import EventDispatcher\n\nclass LabelModel(Label):\n\n def __init__(self, **kwargs):\n super(Label, self).__init__(**kwargs)\n\n\n\n" }, { "alpha_fraction": 0.5956284403800964, "alphanum_fraction": 0.6092896461486816, "avg_line_length": 18.263158798217773, "blob_id": "05163a2e19290da89d39d1fdc62b75a480a6b213", "content_id": "d7b67c34a9c400ea90c44e5f1ae8c6fcafda3257", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 366, "license_type": "no_license", "max_line_length": 45, "num_lines": 19, "path": "/imagemodel.py", "repo_name": "martkins/images_exif_viewer", "src_encoding": "UTF-8", "text": "from kivy.uix.image import Image\nfrom kivy.properties import NumericProperty\n\n\nclass ImageModel(Image):\n\n ang = NumericProperty()\n\n def __init__(self, **kwargs):\n super(Image, self).__init__(**kwargs)\n\n def rotate_right(self):\n self.ang += 90\n\n def rotate_left(self):\n self.ang -= 90\n\n def reset_angle(self):\n self.ang = 0\n" }, { "alpha_fraction": 0.6128526926040649, "alphanum_fraction": 0.6147335171699524, "avg_line_length": 32.9361686706543, "blob_id": "283d8053852f8c7385e8872050d83f50d7cc76f7", "content_id": "6e21f727c4bfc91285239847f2924f071cffc2da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3190, "license_type": "no_license", "max_line_length": 85, "num_lines": 94, "path": "/main.py", "repo_name": "martkins/images_exif_viewer", "src_encoding": "UTF-8", "text": "from kivy.app import App\nfrom kivy.uix.image import Image\nfrom kivy.properties import ObjectProperty\nfrom kivy.uix.listview import ListView, SimpleListAdapter\nfrom kivy.uix.label import Label\nfrom imagemodel import ImageModel\nfrom kivy.uix.button import Button\nfrom kivy.factory import Factory\nfrom buttonmodel import ButtonModel\nfrom labelmodel import LabelModel\nfrom kivy.core.window import Window\n\n\nclass ButtonWithModel(Button):\n\n def __init__(self,model, **kwargs):\n self.model = model\n super().__init__(**kwargs)\n\n\nclass LabelWithModel(Label):\n\n def __init__(self,model, **kwargs):\n self.model = model\n super().__init__(**kwargs)\n\n\nclass ImageWithModel(Image):\n\n def __init__(self,model, **kwargs):\n self.model = model\n super().__init__(**kwargs)\n\n\nclass MainApp(App):\n\n image = ObjectProperty()\n exif = ObjectProperty()\n\n def build(self):\n Window.bind(on_keyboard=self.on_keyboard)\n self.start_app()\n\n def on_keyboard(self, window, key, scancode, codepoint, modifier):\n if modifier == ['ctrl'] and codepoint == 'r':\n self.image.model.rotate_right()\n if modifier == ['ctrl'] and codepoint == 'l':\n self.image.model.rotate_left()\n if modifier == ['ctrl'] and codepoint == 'o':\n self.exif.model.open_image()\n if modifier == ['ctrl'] and codepoint == 'e':\n self.exif.model.get_exif_data()\n if modifier == ['ctrl'] and codepoint == 'n':\n self.exif.model.next_image()\n if modifier == ['ctrl'] and codepoint == 'p':\n self.exif.model.previous_image()\n if modifier == ['ctrl'] and codepoint == 'g':\n self.exif.model.get_location()\n\n def start_app(self):\n labels = [LabelModel() for _ in range(100)]\n\n self.image = Factory.MainImage(ImageModel())\n self.root.ids.image_box.add_widget(self.image)\n\n self.exif = Factory.GetExifData(ButtonModel(image=self.image, labels=labels))\n self.root.ids.button_box.add_widget(self.exif)\n right = Factory.RotateRight(self.exif.model)\n self.root.ids.button_box.add_widget(right)\n left = Factory.RotateLeft(self.exif.model)\n self.root.ids.button_box.add_widget(left)\n loc = Factory.GetLocation(self.exif.model)\n self.root.ids.button_box.add_widget(loc)\n next = Factory.NextImage(self.exif.model)\n self.root.ids.cycle_box.add_widget(next)\n prev = Factory.PreviousImage(self.exif.model)\n self.root.ids.cycle_box.add_widget(prev)\n get = Factory.OpenImage(self.exif.model)\n self.root.ids.button_box.add_widget(get)\n\n lab = Factory.ExifLabel(LabelModel())\n self.root.ids.exif_container.add_widget(lab)\n\n list_adapter = SimpleListAdapter(\n data=labels,\n args_converter=lambda row, model: {'model': model,\n 'size_hint_y': None,\n 'height':100},\n cls=Factory.ExifTags)\n self.root.ids.exif_container.add_widget(ListView(adapter=list_adapter))\n\n\nif __name__ == \"__main__\":\n MainApp().run()\n" }, { "alpha_fraction": 0.6127366423606873, "alphanum_fraction": 0.6239242553710938, "avg_line_length": 40.46428680419922, "blob_id": "bda2eab77e1bf04decfa739d6dfda7d00ab2ff43", "content_id": "cf9e84b19c92d28dde433e30c0a090c491029faa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1165, "license_type": "no_license", "max_line_length": 189, "num_lines": 28, "path": "/README.md", "repo_name": "martkins/images_exif_viewer", "src_encoding": "UTF-8", "text": "# ImageExifViewer\n\nThis project is a simple image viewer written in Python: this is an academic exercise from a course at Università degli Studi di Firenze.\n\n\n## Requirements\n| Software | Version | \n|:--------------------------------------------------------------:|:-------:|\n| [Python](https://www.python.org) | 3.6 |\n| [Kivy](https://kivy.org/#home) | 1.10.1 |\n| [ExifRead](https://pypi.org/project/ExifRead/) | 2.1.2 |\n\n## Launch the applications\nRun the python main file from the directory of project:\n```\npython main.py\n```\n\n## Usage\nTo **load** an image (or multiple) click on Open Image or CTRL+O.\n\nTo **show the EXIF tags** of the selected image, click on Get Exif Data or CTRL+E.\n\nTo **rotate** an image, click on Rotate Right/Left (90°Clockwise or 90° counterclockwise) or CTRL+R/CTRL+L.\n\nTo open **GPS Coordinates** on Google Maps on web browser, click on Google Maps or CTRL+G: this feature is available only if in the list of exif tags there are all the coordinates required.\n\nTo navigate trought multiple images, click on Next/Previous Image or CTRL+N/CTRL+P.\n\n" }, { "alpha_fraction": 0.542917788028717, "alphanum_fraction": 0.5526235699653625, "avg_line_length": 31.01941680908203, "blob_id": "17b6cab01714fdf3a243528af5dc55981fbd9d28", "content_id": "b57331874a1dd7f2fcb6fb412f582073bdbe0774", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3297, "license_type": "no_license", "max_line_length": 113, "num_lines": 103, "path": "/buttonmodel.py", "repo_name": "martkins/images_exif_viewer", "src_encoding": "UTF-8", "text": "import exifread\nfrom kivy.uix.button import Button\nfrom kivy.lang import Builder\nfrom tkinter.filedialog import askopenfilenames\nfrom kivy.properties import DictProperty, ListProperty, NumericProperty\nimport webbrowser\nfrom tkinter import Tk\nroot = Tk()\nroot.withdraw()\n\nBuilder.load_file('./actionbutton.kv')\n\n\ndef _convert(value):\n d = float(str(value[0]))\n m = float(str(value[1]))\n s1 = (str(value[2])).split('/')\n s = float((s1[0])) / float((s1[1]))\n return d + (m / 60.0) + (s / 3600.0)\n\n\nclass ButtonModel(Button):\n\n tags = DictProperty()\n images = ListProperty()\n count = NumericProperty(0)\n\n def __init__(self,image='', labels='', **kwargs):\n self.image = image\n self.labels = labels\n super(Button, self).__init__(**kwargs)\n\n def rotate_right(self):\n self.image.model.rotate_right()\n\n def rotate_left(self):\n self.image.model.rotate_left()\n\n def open_image(self):\n try:\n self.images = askopenfilenames(initialdir=\"/\", title=\"Select file\",\n filetypes=((\"jpeg files\", \"*.jpg\"),(\"png files\",\"*png\"), (\"all files\", \"*.*\")))\n self.reset_labels()\n self.image.source = self.images[0]\n self.image.model.reset_angle()\n except:\n pass\n\n def get_exif_data(self):\n print(self.image.source)\n f = open(self.image.source, 'rb')\n self.tags = exifread.process_file(f)\n i = 0\n for tag in self.tags.keys():\n if tag not in ('EXIF MakerNote','User Comment','JPEGThumbnail', 'EXIF UserComment'):\n self.labels[i].text = str(tag.split()[1])+' : '+str(self.tags[tag])\n i = i+1\n\n def get_location(self):\n lat = None\n lon = None\n\n try:\n gps_latitude = self.tags['GPS GPSLatitude'].values\n gps_latitude_ref = self.tags['GPS GPSLatitudeRef'].values\n gps_longitude = self.tags['GPS GPSLongitude'].values\n gps_longitude_ref = self.tags['GPS GPSLongitudeRef'].values\n\n if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref:\n lat = _convert(gps_latitude)\n if gps_latitude_ref != 'N':\n lat = 0 - lat\n\n lon = _convert(gps_longitude)\n if gps_longitude_ref != 'E':\n lon = 0 - lon\n\n webbrowser.open('https://www.google.com/maps/search/?api=1&query='+str(lat)+','+str(lon))\n except:\n pass\n\n def next_image(self):\n if len(self.images) > 1:\n self.count = self.count + 1\n if self.count >= len(self.images):\n self.count = 0\n self.image.model.reset_angle()\n self.reset_labels()\n self.image.source = self.images[self.count]\n\n def previous_image(self):\n if len(self.images) > 1:\n self.count = self.count - 1\n if self.count < 0:\n self.count = len(self.images)-1\n self.image.model.reset_angle()\n self.reset_labels()\n self.image.source = self.images[self.count]\n\n def reset_labels(self):\n self.tags.clear()\n for i in range(0,len(self.labels)):\n self.labels[i].text = ''" } ]
5
Peroxidess/Ablation-Time-Prediction-Model
https://github.com/Peroxidess/Ablation-Time-Prediction-Model
3275395d41187fc6b110f6633663ef3ded709318
11cacec16259d4f4a903f91353a2add31633da68
e0168b693e26443de8dc206ed2dd6c505fd90f87
refs/heads/main
2023-08-18T16:35:26.160344
2021-10-10T16:37:32
2021-10-10T16:37:32
415,641,622
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5551358461380005, "alphanum_fraction": 0.5752406716346741, "avg_line_length": 40.65989685058594, "blob_id": "48128acb971ffdaac7d02c5188f4da785a5fa5af", "content_id": "01e26897e17aa2344d6b1c5fc628ee4d54a1b42c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8207, "license_type": "no_license", "max_line_length": 103, "num_lines": 197, "path": "/Regression/src/learn_rewieght/reweight.py", "repo_name": "Peroxidess/Ablation-Time-Prediction-Model", "src_encoding": "UTF-8", "text": "# Copyright (c) 2017 - 2019 Uber Technologies, Inc.\n#\n# Licensed under the Uber Non-Commercial License (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 the root directory of this project.\n#\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n#\n#\n# Models for MNIST experiments.\n#\nfrom __future__ import division, print_function\n\nimport numpy as np\nimport tensorflow as tf\n\n\ndef get_model(inputs,\n labels,\n is_training=True,\n dtype=tf.float32,\n w_dict=None,\n ex_wts=None,\n reuse=None,\n ):\n \"\"\"\n :param inputs: [Tensor] Inputs.\n :param labels: [Tensor] Labels.\n :param is_training: [bool] Whether in training mode, default True.\n :param dtype: [dtype] Data type, default tf.float32.\n :param w_dict: [dict] Dictionary of weights, default None.\n :param ex_wts: [Tensor] Example weights placeholder, default None.\n :param reuse: [bool] Whether to reuse variables, default None.\n \"\"\"\n\n if w_dict is None:\n w_dict = {}\n\n def _get_var(name, shape, dtype, initializer):\n key = tf.get_variable_scope().name + '/' + name\n if key in w_dict:\n return w_dict[key]\n else:\n var = tf.get_variable(name, shape, dtype, initializer=initializer)\n w_dict[key] = var\n return var\n\n with tf.variable_scope('Model', reuse=reuse):\n shape_list = np.append(np.array([-1]), np.squeeze(inputs.shape[1:].as_list()))\n shape_list_wts = np.append(np.array([-1]), np.squeeze(ex_wts.shape[1:].as_list()))\n shape_list_fir = np.append(np.squeeze(inputs.shape[1:].as_list()), np.array([1024]))\n shape_list_sec = np.array([1024, 256])\n shape_list_thr = np.array([256, 64])\n inputs_ = tf.cast(tf.reshape(inputs, shape_list), dtype)\n inputs_w = tf.cast(tf.reshape(ex_wts, shape_list_wts), dtype)\n # inputs_w = tf.matrix_diag(ex_wts)\n labels = tf.cast(tf.reshape(labels, [-1, 1]), dtype)\n\n w_init = tf.truncated_normal_initializer(stddev=0.1)\n w1 = _get_var('w1', shape_list_fir, dtype, initializer=w_init)\n w2 = _get_var('w2', shape_list_sec, dtype, initializer=w_init)\n w3 = _get_var('w3', shape_list_thr, dtype, initializer=w_init)\n w4 = _get_var('w4', [64, 32], dtype, initializer=w_init)\n w5 = _get_var('w5', [32, 1], dtype, initializer=w_init)\n\n b_init = tf.constant_initializer(0.0)\n b1 = _get_var('b1', 1, dtype, initializer=b_init)\n b2 = _get_var('b2', 1, dtype, initializer=b_init)\n b3 = _get_var('b3', 64, dtype, initializer=b_init)\n b4 = _get_var('b4', 32, dtype, initializer=b_init)\n b5 = _get_var('b5', 1, dtype, initializer=b_init)\n\n act = tf.nn.relu\n\n l0 = tf.identity(inputs_, name='l0')\n z1 = tf.add(tf.matmul(l0, w1), b1, name='z1')\n l1 = act(z1, name='l1')\n # h1 = tf.contrib.layers.batch_norm(l1, center=True, scale=True, is_training=True, scope='bn1')\n z2 = tf.add(tf.matmul(l1, w2), b2, name='z2')\n l2 = act(z2, name='l2')\n # h2 = tf.contrib.layers.batch_norm(l2, center=True, scale=True, is_training=True, scope='bn2')\n z3 = tf.add(tf.matmul(l2, w3), b3, name='z3')\n l3 = act(z3, name='l3')\n # h3 = tf.contrib.layers.batch_norm(l3, center=True, scale=True, is_training=True, scope='bn3')\n z4 = tf.add(tf.matmul(l3, w4), b4, name='z4')\n l4 = act(z4, name='l4')\n # h4 = tf.contrib.layers.batch_norm(l4, center=True, scale=True, is_training=True, scope='bn4')\n z5 = tf.add(tf.matmul(l4, w5), b5, name='z5')\n pred = z5\n if ex_wts is None:\n # Average loss.\n loss = tf.reduce_mean(tf.square(tf.subtract(pred, labels)))\n else:\n # Weighted loss.\n squa = tf.square(tf.subtract(pred, labels)) * inputs_w\n mse = tf.nn.l2_loss(tf.subtract(pred, labels)) * inputs_w\n loss = tf.reduce_mean(squa)\n\n return w_dict, loss, pred\n\n\ndef reweight_random(bsize, eps=0.0):\n \"\"\"Reweight examples using random numbers.\n \n :param bsize: [int] Batch size.\n :param eps: [float] Minimum example weights, default 0.0.\n \"\"\"\n ex_weight = tf.random_normal([bsize], mean=0.0, stddev=1.0)\n ex_weight_plus = tf.maximum(ex_weight, eps)\n ex_weight_sum = tf.reduce_sum(ex_weight_plus)\n ex_weight_sum += tf.to_float(tf.equal(ex_weight_sum, 0.0))\n ex_weight_norm = ex_weight_plus / ex_weight_sum\n return ex_weight_norm\n\n\ndef reweight_autodiff(inp_a,\n label_a,\n inp_b,\n label_b,\n ex_wts_a,\n ex_wts_b,\n bsize_a,\n bsize_b,\n eps=0,\n gate_gradients=1):\n \"\"\"Reweight examples using automatic differentiation.\n\n :param inp_a: [Tensor] Inputs for the noisy pass.\n :param label_a: [Tensor] Labels for the noisy pass.\n :param inp_b: [Tensor] Inputs for the clean pass.\n :param label_b: [Tensor] Labels for the clean pass.\n :param bsize_a: [int] Batch size for the noisy pass.\n :param bsize_b: [int] Batch size for the clean pass.\n :param eps: [float] Minimum example weights, default 0.0.\n :param gate_gradients: [int] Tensorflow gate gradients, reduce concurrency.\n \"\"\"\n # ex_wts_a = tf.ones([bsize_a], dtype=tf.float32)\n # ex_wts_b = tf.ones([bsize_b], dtype=tf.float32) / float(bsize_b)\n # ex_wts_b = tf.placeholder(tf.float32, [None, 1], name='ex_wts_b')\n w_dict, loss_a, logits_a = get_model(\n inp_a, label_a, ex_wts=ex_wts_a, is_training=True, reuse=True)\n var_names = w_dict.keys()\n var_list = [w_dict[kk] for kk in var_names]\n grads = tf.gradients(loss_a, var_list, gate_gradients=gate_gradients)\n # grads_w = tf.gradients(loss_a, [ex_wts_a], gate_gradients=gate_gradients)\n\n var_list_new = [vv - gg for gg, vv in zip(grads, var_list)]\n w_dict_new = dict(zip(var_names, var_list_new))\n _, loss_b, logits_b = get_model(\n inp_b, label_b, ex_wts=ex_wts_b, is_training=True, reuse=True, w_dict=w_dict_new)\n grads_ex_wts = tf.gradients(loss_b, [ex_wts_a], gate_gradients=gate_gradients)[0]\n ex_weight = -grads_ex_wts\n ex_weight_plus = tf.maximum(ex_weight, eps)\n ex_weight_sum = tf.reduce_sum(ex_weight_plus)\n ex_weight_sum += tf.to_float(tf.equal(ex_weight_sum, 0.0))\n ex_weight_norm = ex_weight_plus / ex_weight_sum\n return ex_weight_norm, var_list, grads, ex_weight_plus\n\n\ndef reweight_hard_mining(inp, label, positive=False):\n \"\"\"Reweight examples using hard mining.\n \n :param inp: [Tensor] [N, ...] Inputs.\n :param label: [Tensor] [N] Labels\n :param positive: [bool] Whether perform hard positive mining or hard negative mining.\n\n :return [Tensor] Examples weights of the same shape as the first dim of inp.\n \"\"\"\n _, loss, logits = get_model(inp, label, ex_wts=None, is_training=True, reuse=True)\n\n # Mine for positive\n if positive:\n loss_mask = loss * label\n else:\n loss_mask = loss * (1 - label)\n\n if positive:\n k = tf.cast(tf.reduce_sum(1 - label), tf.int32)\n else:\n k = tf.cast(tf.reduce_sum(label), tf.int32)\n k = tf.maximum(k, 1)\n loss_sorted, loss_sort_idx = tf.nn.top_k(loss_mask, k)\n\n if positive:\n mask = 1 - label\n else:\n mask = label\n\n updates = tf.ones([tf.shape(loss_sort_idx)[0]], dtype=label.dtype)\n mask_add = tf.scatter_nd(tf.expand_dims(loss_sort_idx, axis=1), updates, [tf.shape(inp)[0]])\n mask = tf.maximum(mask, mask_add)\n mask_sum = tf.reduce_sum(mask)\n mask_sum += tf.cast(tf.equal(mask_sum, 0.0), tf.float32)\n mask = mask / mask_sum\n return mask\n" }, { "alpha_fraction": 0.6015228629112244, "alphanum_fraction": 0.6073799133300781, "avg_line_length": 44.72321319580078, "blob_id": "356db51526057127ec34da9a77c7ce48dae3e5bc", "content_id": "602912d89cf261052f8d19dfd6a7d0c3239a178b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5168, "license_type": "no_license", "max_line_length": 121, "num_lines": 112, "path": "/Regression/src/preprocess/get_dataset.py", "repo_name": "Peroxidess/Ablation-Time-Prediction-Model", "src_encoding": "UTF-8", "text": "from sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler, StandardScaler\nimport pandas as pd\nimport numpy as np\nfrom preprocess import plot_tabel\n\n\ndef get_dataset_(nor, train_data, test_data, clean_ratio, test_retio, seed, target='label', val_ratio=0):\n if test_retio == 0 or test_data is not None:\n train_set = train_data\n test_set = test_data\n else:\n train_set, test_set = train_test_split(train_data, test_size=test_retio, random_state=seed)\n if clean_ratio < 1:\n train_set_, train_set_clean = train_test_split(train_set, test_size=clean_ratio, random_state=seed)\n label_distrib = np.random.normal(loc=train_set_[target].describe().loc['mean'],\n scale=train_set_[target].describe().loc['std'], size=train_set_[target].shape)\n alpha = 1\n beta = 1\n train_label_ = train_set_[target] + \\\n alpha * np.random.normal(loc=0., scale=1., size=train_set_[target].shape) + beta * label_distrib\n train_set_[target] = train_label_\n train_set_['sup_label'] = 1\n train_set_clean['sup_label'] = 0\n test_set['sup_label'] = 0\n else:\n train_set_ = None\n train_set_clean = train_set\n\n train_set_mix = pd.concat([train_set_, train_set_clean], axis=0)\n # mix_ratio = train_set[train_set[target] != train_set_mix[target]].index\n # print('real mix ratio is {}'.format(mix_ratio))\n if val_ratio > 0:\n train_set_mix, val_set = train_test_split(train_set_mix, test_size=val_ratio, random_state=seed)\n val_set_label = val_set[[target, 'sup_label']]\n val_set.drop(columns=[target, 'sup_label'], inplace=True)\n else:\n val_set = None\n val_set_label = None\n train_set_mix_label = train_set_mix[[target, 'sup_label']]\n test_set_label = test_set[[target, 'sup_label']]\n # plot_tabel.metric_hist(test_set, nor)\n train_set_mix.drop(columns=[target, 'sup_label'], inplace=True)\n test_set.drop(columns=[target, 'sup_label'], inplace=True)\n return train_set_mix, train_set_mix_label, val_set, val_set_label, test_set, test_set_label\n\n\ndef data_preprocessing(train_data, test_data=None, ca_feat_th=8, ca_co_sel_flag=True, onehot_flag=False, target='label'):\n if test_data is not None:\n train_data['tab'] = 1\n test_data['tab'] = 0\n data_raw = pd.concat([train_data, test_data], axis=0)\n print('\\ndata_raw', data_raw.shape)\n data = data_raw.dropna(axis=1, how='all')\n xx = data.isnull().sum()\n data = data.fillna(0)\n if ca_co_sel_flag:\n ca_col = []\n co_col = []\n data_columns_label = data.filter(regex=r'label').columns\n data_columns = data.columns.drop(data_columns_label)\n # data_columns = data.columns.drop(['sup_label'])\n for col in data_columns:\n data_col = data[col]\n col_feat_num = len(set(data_col))\n if col_feat_num > ca_feat_th:\n col_ = col + '_dense'\n co_col.append(col_)\n data.rename(columns={col: col_}, inplace=True)\n elif ca_feat_th >= col_feat_num > 1:\n col_ = col + '_sparse'\n ca_col.append(col_)\n data.rename(columns={col: col_}, inplace=True)\n else:\n ca_col = data.filter(regex=r'sparse').columns\n co_col = data.filter(regex=r'dense').columns\n data[ca_col] = pd.concat([data[ca_col].apply(lambda ser: pd.factorize(ser)[0])])\n data[ca_col] = data[ca_col].apply(LabelEncoder().fit_transform)\n if onehot_flag:\n data = pd.get_dummies(data, columns=ca_col)\n co_col = co_col.append(data.columns[data.columns == target]) # 回归目标也需要归一化避免在sup_label分类预测中的模型崩溃\n mms = MinMaxScaler(feature_range=(0.1, 1.1))\n std = StandardScaler()\n xx = data.filter(regex=r'label').describe()\n xx_col = xx.index\n xx_min = xx.loc['min', :]\n xx_max = xx.loc['max', :]\n xx_std = xx.loc['std', :]\n data[co_col] = pd.DataFrame(std.fit_transform(data[co_col]), columns=co_col, index=data.index)\n # data[co_col] = pd.DataFrame(mms.fit_transform(data[co_col]), columns=co_col, index=data.index)\n # data = pd.DataFrame(mms.fit_transform(data), columns=data.columns, index=data.index)\n if test_data is not None:\n train_data = data[data['tab'] == 1].drop(columns=['tab'])\n test_data = data[data['tab'] == 0].drop(columns=['tab'])\n else:\n train_data = data\n ca_col = data.filter(regex=r'sparse').columns\n co_col = data.filter(regex=r'dense').columns\n return train_data, test_data, co_col, ca_col, std\n\n\ndef anomaly_dectection(train_data=None, test_data=None, target='label'):\n clean_data = []\n for data in [train_data, test_data]:\n if not data.empty:\n std_ = data[target].std()\n mean_ = data[target].mean()\n data = data[data[target] < mean_ + 3 * std_]\n data = data[data[target] > mean_ - 3 * std_]\n clean_data.append(data)\n return clean_data[0], clean_data[1]\n\n" }, { "alpha_fraction": 0.5334303975105286, "alphanum_fraction": 0.5575929880142212, "avg_line_length": 33.25396728515625, "blob_id": "99ca9793e5fd0855edbd02e86457c0bfb0d22a6e", "content_id": "5579ab86c18ab997cca382d735eb2d9d09805f1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15106, "license_type": "no_license", "max_line_length": 100, "num_lines": 441, "path": "/Regression/src/learn_rewieght/mnist_train.py", "repo_name": "Peroxidess/Ablation-Time-Prediction-Model", "src_encoding": "UTF-8", "text": "# Copyright (c) 2017 - 2019 Uber Technologies, Inc.\n#\n# Licensed under the Uber Non-Commercial License (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 the root directory of this project.\n#\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n#\n#\n# Runs MNIST experitment. Default 10 runs for 10 random seeds.\n#\n# Usage:\n# python -m mnist.imblanace_mnist_train_ad.py\n#\n# Flags:\n# --exp [string] Experiment name, `ours`, `hm`, `ratio`, `random` or `baseline`.\n# --pos_ratio [float] The ratio for the positive class, choose between 0.9 - 0.995.\n# --nrun [int] Total number of runs with different random seeds.\n# --ntrain [int] Number of training examples.\n# --nval [int] Number of validation examples.\n# --ntest [int] Number of test examples.\n# --tensorboard Writes TensorBoard logs while training, default True.\n# --notensorboard Disable TensorBoard.\n# --verbose Print training progress, default False.\n# --noverbose Disable printing.\n#\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport numpy as np\nimport os\nimport six\nimport tensorflow as tf\n\nfrom collections import namedtuple\nfrom tensorflow.contrib.learn.python.learn.datasets.mnist import DataSet\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom tqdm import tqdm\n\nfrom mnist_.reweight import get_model, reweight_random, reweight_autodiff, reweight_hard_mining\nfrom utils.logger import get as get_logger\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'\ntf.logging.set_verbosity(tf.logging.ERROR)\n\nflags = tf.flags\nflags.DEFINE_float('pos_ratio', 0.995, 'Ratio of positive examples in training')\nflags.DEFINE_integer('nrun', 10, 'Number of runs')\nflags.DEFINE_integer('ntest', 500, 'Number of testing examples')\nflags.DEFINE_integer('ntrain', 5000, 'Number of training examples')\nflags.DEFINE_integer('nval', 10, 'Number of validation examples')\nflags.DEFINE_bool('verbose', False, 'Whether to print training progress')\nflags.DEFINE_bool('tensorboard', True, 'Whether to save training progress')\nflags.DEFINE_string('exp', 'baseline', 'Which experiment to run')\nFLAGS = tf.flags.FLAGS\n\nlog = get_logger()\n\nConfig = namedtuple('Config', [\n 'reweight', 'lr', 'num_steps', 'random', 'ratio_weighted', 'nval', 'hard_mining', 'bsize'\n])\n\nexp_repo = dict()\n\n\ndef RegisterExp(name):\n def _decorator(f):\n exp_repo[name] = f\n return f\n\n return _decorator\n\n\nLR = 0.001\nNUM_STEPS = 4000\n\n\n@RegisterExp('baseline')\ndef baseline_config():\n return Config(\n reweight=False,\n num_steps=NUM_STEPS * 2,\n lr=LR,\n random=False,\n ratio_weighted=False,\n hard_mining=False,\n bsize=100,\n nval=0)\n\n\n@RegisterExp('hm')\ndef baseline_config():\n return Config(\n reweight=False,\n num_steps=NUM_STEPS * 2,\n lr=LR,\n random=False,\n ratio_weighted=False,\n hard_mining=True,\n bsize=500,\n nval=0)\n\n\n@RegisterExp('ratio')\ndef ratio_config():\n return Config(\n reweight=False,\n num_steps=NUM_STEPS * 2,\n lr=LR,\n random=False,\n ratio_weighted=True,\n hard_mining=False,\n bsize=100,\n nval=0)\n\n\n@RegisterExp('random')\ndef dpfish_config():\n return Config(\n reweight=True,\n num_steps=NUM_STEPS * 2,\n lr=LR,\n random=True,\n ratio_weighted=False,\n hard_mining=False,\n bsize=100,\n nval=0)\n\n\n@RegisterExp('ours')\ndef ours_config():\n return Config(\n reweight=True,\n num_steps=NUM_STEPS,\n lr=LR,\n random=False,\n ratio_weighted=False,\n hard_mining=False,\n bsize=100,\n nval=FLAGS.nval)\n\n\ndef get_imbalance_dataset(mnist,\n pos_ratio=0.9,\n ntrain=5000,\n nval=10,\n ntest=500,\n seed=0,\n class_0=4,\n class_1=9):\n rnd = np.random.RandomState(seed)\n\n # In training, we have 10% 4 and 90% 9.\n # In testing, we have 50% 4 and 50% 9.\n ratio = 1 - pos_ratio\n ratio_test = 0.5\n\n x_train = mnist.train.images\n y_train = mnist.train.labels\n x_test = mnist.test.images\n y_test = mnist.test.labels\n x_train_0 = x_train[y_train == class_0]\n x_test_0 = x_test[y_test == class_0]\n\n # First shuffle, negative.\n idx = np.arange(x_train_0.shape[0])\n rnd.shuffle(idx)\n x_train_0 = x_train_0[idx]\n\n nval_small_neg = int(np.floor(nval * ratio_test))\n ntrain_small_neg = int(np.floor(ntrain * ratio)) - nval_small_neg\n\n x_val_0 = x_train_0[:nval_small_neg] # 450 4 in validation.\n x_train_0 = x_train_0[nval_small_neg:nval_small_neg + ntrain_small_neg] # 500 4 in training.\n\n if FLAGS.verbose:\n print('Number of train negative classes', ntrain_small_neg)\n print('Number of val negative classes', nval_small_neg)\n\n idx = np.arange(x_test_0.shape[0])\n rnd.shuffle(idx)\n x_test_0 = x_test_0[:int(np.floor(ntest * ratio_test))] # 450 4 in testing.\n\n x_train_1 = x_train[y_train == class_1]\n x_test_1 = x_test[y_test == class_1]\n\n # First shuffle, positive.\n idx = np.arange(x_train_1.shape[0])\n rnd.shuffle(idx)\n x_train_1 = x_train_1[idx]\n\n nvalsmall_pos = int(np.floor(nval * (1 - ratio_test)))\n ntrainsmall_pos = int(np.floor(ntrain * (1 - ratio))) - nvalsmall_pos\n\n x_val_1 = x_train_1[:nvalsmall_pos] # 50 9 in validation.\n x_train_1 = x_train_1[nvalsmall_pos:nvalsmall_pos + ntrainsmall_pos] # 4500 9 in training.\n\n idx = np.arange(x_test_1.shape[0])\n rnd.shuffle(idx)\n x_test_1 = x_test_1[idx]\n x_test_1 = x_test_1[:int(np.floor(ntest * (1 - ratio_test)))] # 500 9 in testing.\n\n if FLAGS.verbose:\n print('Number of train positive classes', ntrainsmall_pos)\n print('Number of val positive classes', nvalsmall_pos)\n\n y_train_subset = np.concatenate([np.zeros([x_train_0.shape[0]]), np.ones([x_train_1.shape[0]])])\n y_val_subset = np.concatenate([np.zeros([x_val_0.shape[0]]), np.ones([x_val_1.shape[0]])])\n y_test_subset = np.concatenate([np.zeros([x_test_0.shape[0]]), np.ones([x_test_1.shape[0]])])\n\n y_train_pos_subset = np.ones([x_train_1.shape[0]])\n y_train_neg_subset = np.zeros([x_train_0.shape[0]])\n\n x_train_subset = np.concatenate([x_train_0, x_train_1], axis=0).reshape([-1, 28, 28, 1])\n x_val_subset = np.concatenate([x_val_0, x_val_1], axis=0).reshape([-1, 28, 28, 1])\n x_test_subset = np.concatenate([x_test_0, x_test_1], axis=0).reshape([-1, 28, 28, 1])\n\n x_train_pos_subset = x_train_1.reshape([-1, 28, 28, 1])\n x_train_neg_subset = x_train_0.reshape([-1, 28, 28, 1])\n\n # Final shuffle.\n idx = np.arange(x_train_subset.shape[0])\n rnd.shuffle(idx)\n x_train_subset = x_train_subset[idx]\n y_train_subset = y_train_subset[idx]\n\n idx = np.arange(x_val_subset.shape[0])\n rnd.shuffle(idx)\n x_val_subset = x_val_subset[idx]\n y_val_subset = y_val_subset[idx]\n\n idx = np.arange(x_test_subset.shape[0])\n rnd.shuffle(idx)\n x_test_subset = x_test_subset[idx]\n y_test_subset = y_test_subset[idx]\n\n train_set = DataSet(x_train_subset * 255.0, y_train_subset)\n train_pos_set = DataSet(x_train_pos_subset * 255.0, y_train_pos_subset)\n train_neg_set = DataSet(x_train_neg_subset * 255.0, y_train_neg_subset)\n val_set = DataSet(x_val_subset * 255.0, y_val_subset)\n test_set = DataSet(x_test_subset * 255.0, y_test_subset)\n\n return train_set, val_set, test_set, train_pos_set, train_neg_set\n\n\ndef get_exp_logger(sess, log_folder):\n \"\"\"Gets a TensorBoard logger.\"\"\"\n with tf.name_scope('Summary'):\n writer = tf.summary.FileWriter(os.path.join(log_folder), sess.graph)\n\n class ExperimentLogger():\n def log(self, niter, name, value):\n summary = tf.Summary()\n summary.value.add(tag=name, simple_value=value)\n writer.add_summary(summary, niter)\n\n def flush(self):\n \"\"\"Flushes results to disk.\"\"\"\n writer.flush()\n\n return ExperimentLogger()\n\n\ndef evaluate(sess, x_, y_, acc_, train_set, test_set):\n # Calculate final results.\n acc_sum = 0.0\n acc_test_sum = 0.0\n train_bsize = 100\n for step in six.moves.xrange(5000 // train_bsize):\n x, y = train_set.next_batch(train_bsize)\n acc = sess.run(acc_, feed_dict={x_: x, y_: y})\n acc_sum += acc\n\n test_bsize = 100\n for step in six.moves.xrange(500 // test_bsize):\n x_test, y_test = test_set.next_batch(test_bsize)\n acc = sess.run(acc_, feed_dict={x_: x_test, y_: y_test})\n acc_test_sum += acc\n\n train_acc = acc_sum / float(5000 // train_bsize)\n test_acc = acc_test_sum / float(500 // test_bsize)\n return train_acc, test_acc\n\n\ndef get_acc(logits, y):\n prediction = tf.cast(tf.sigmoid(logits) > 0.5, tf.float32)\n return tf.reduce_mean(tf.cast(tf.equal(prediction, y), tf.float32))\n\n\ndef run(dataset, exp_name, seed, verbose=True):\n pos_ratio = FLAGS.pos_ratio\n ntrain = FLAGS.ntrain\n nval = FLAGS.nval\n ntest = FLAGS.ntest\n folder = os.path.join('ckpt_mnist_imbalance_cnn_p{:d}'.format(int(FLAGS.pos_ratio * 100.0)),\n exp_name + '_{:d}'.format(seed))\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n with tf.Graph().as_default(), tf.Session() as sess:\n config = exp_repo[exp_name]()\n bsize = config.bsize\n train_set, val_set, test_set, train_pos_set, train_neg_set = get_imbalance_dataset(\n dataset, pos_ratio=pos_ratio, ntrain=ntrain, nval=config.nval, ntest=ntest, seed=seed)\n # if config.nval == 0:\n # val_set = BalancedDataSet(train_pos_set, train_neg_set)\n x_ = tf.placeholder(tf.float32, [None, 784], name='x')\n y_ = tf.placeholder(tf.float32, [None], name='y')\n x_val_ = tf.placeholder(tf.float32, [None, 784], name='x_val')\n y_val_ = tf.placeholder(tf.float32, [None], name='y_val')\n ex_wts_ = tf.placeholder(tf.float32, [None], name='ex_wts')\n lr_ = tf.placeholder(tf.float32, [], name='lr')\n\n # Build training model.\n with tf.name_scope('Train'):\n _, loss_c, logits_c = get_model(\n x_, y_, is_training=True, dtype=tf.float32, w_dict=None, ex_wts=ex_wts_, reuse=None)\n train_op = tf.train.MomentumOptimizer(config.lr, 0.9).minimize(loss_c)\n\n # Build evaluation model.\n with tf.name_scope('Val'):\n _, loss_eval, logits_eval = get_model(\n x_,\n y_,\n is_training=False,\n dtype=tf.float32,\n w_dict=None,\n ex_wts=ex_wts_,\n reuse=True)\n acc_ = get_acc(logits_eval, y_)\n\n # Build reweighting model.\n if config.reweight:\n if config.random:\n ex_weights_ = reweight_random(bsize)\n else:\n ex_weights_ = reweight_autodiff(\n x_,\n y_,\n x_val_,\n y_val_,\n bsize,\n min(bsize, nval),\n eps=0.0,\n gate_gradients=1)\n else:\n if config.hard_mining:\n ex_weights_ = reweight_hard_mining(x_, y_, positive=True)\n else:\n if config.ratio_weighted:\n # Weighted by the ratio of each class.\n ex_weights_ = pos_ratio * (1 - y_) + (1 - pos_ratio) * (y_)\n else:\n # Weighted by uniform.\n ex_weights_ = tf.ones([bsize], dtype=tf.float32) / float(bsize)\n\n if FLAGS.tensorboard:\n exp_logger = get_exp_logger(sess, folder)\n else:\n exp_logger = None\n\n lr = config.lr\n num_steps = config.num_steps\n\n acc_sum = 0.0\n acc_test_sum = 0.0\n loss_sum = 0.0\n count = 0\n sess.run(tf.global_variables_initializer())\n for step in six.moves.xrange(num_steps):\n x, y = train_set.next_batch(bsize)\n x_val, y_val = val_set.next_batch(min(bsize, nval))\n\n # Use 50% learning rate for the second half of training.\n if step > num_steps // 2:\n lr = config.lr / 2.0\n else:\n lr = config.lr\n\n ex_weights = sess.run(\n ex_weights_, feed_dict={x_: x,\n y_: y,\n x_val_: x_val,\n y_val_: y_val})\n loss, acc, _ = sess.run(\n [loss_c, acc_, train_op],\n feed_dict={\n x_: x,\n y_: y,\n x_val_: x_val,\n y_val_: y_val,\n ex_wts_: ex_weights,\n lr_: lr\n })\n if (step + 1) % 100 == 0:\n train_acc, test_acc = evaluate(sess, x_, y_, acc_, train_set, test_set)\n if verbose:\n print('Step', step + 1, 'Loss', loss, 'Train acc', train_acc, 'Test acc',\n test_acc)\n if FLAGS.tensorboard:\n exp_logger.log(step + 1, 'train acc', train_acc)\n exp_logger.log(step + 1, 'test acc', test_acc)\n exp_logger.flush()\n acc_sum = 0.0\n loss_sum = 0.0\n acc_test_sum = 0.0\n count = 0\n\n # Final evaluation.\n train_acc, test_acc = evaluate(sess, x_, y_, acc_, train_set, test_set)\n if verbose:\n print('Final', 'Train acc', train_acc, 'Test acc', test_acc)\n return train_acc, test_acc\n\n\ndef run_many(dataset, exp_name):\n train_acc_list = []\n test_acc_list = []\n for trial in tqdm(six.moves.xrange(FLAGS.nrun), desc=exp_name):\n train_acc, test_acc = run(\n dataset, exp_name, (trial * 123456789) % 100000, verbose=FLAGS.verbose)\n train_acc_list.append(train_acc)\n test_acc_list.append(test_acc)\n\n train_acc_list = np.array(train_acc_list)\n test_acc_list = np.array(test_acc_list)\n print(exp_name, 'Train acc {:.3f}% ({:.3f}%)'.format(train_acc_list.mean() * 100.0,\n train_acc_list.std() * 100.0))\n print(exp_name, 'Test acc {:.3f}% ({:.3f}%)'.format(test_acc_list.mean() * 100.0,\n test_acc_list.std() * 100.0))\n\n\ndef main():\n mnist = input_data.read_data_sets(\"data/mnist\", one_hot=False)\n for exp in FLAGS.exp.split(','):\n run_many(mnist, exp)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5702154040336609, "alphanum_fraction": 0.583057165145874, "avg_line_length": 37.31745910644531, "blob_id": "f81d500acf9f1b5346674cd154319de95571bc3d", "content_id": "a229b7d1fadf49158d6295fc2abd782b7c23a55f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4828, "license_type": "no_license", "max_line_length": 112, "num_lines": 126, "path": "/Regression/src/model/history_.py", "repo_name": "Peroxidess/Ablation-Time-Prediction-Model", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport math\nplt.rc('font', family='Times New Roman')\nfont_size = 16\n\n\ndef plot_metric_df(history_list, task_name, val_flag='test_'):\n if 'relapse_risk' in task_name:\n metric_list = ['loss', 'f1']\n else:\n metric_list = ['r2', 'mae', 'mse']\n fig = plt.figure(figsize=(20, 4))\n L = len(metric_list)\n row = math.floor(math.sqrt(L))\n col = L / row\n for i, metric in enumerate(metric_list):\n plt.subplot(row, col, i+1)\n show_metric(history_list, metric, val_flag)\n fig.subplots_adjust(top=0.8)\n legend_labels = ['ours',\n # 'enh_nonrelapse',\n 'ATT+MLP',\n # 'vanilla_nonrelapse',\n 'LGB',\n # 'lightgbm_nonrelapse',\n 'Lasso',\n # 'lasso_nonrelapse'\n ]\n plt.legend(labels= legend_labels,\n ncol = len(legend_labels),\n # loc='best', \n loc='upper center', \n fontsize=14,\n bbox_to_anchor=(-1.2, 1, 1, 0.2),\n borderaxespad = 0.,\n )\n # plt.title('{} {}'.format(task_name, metric), fontsize=font_size)\n\n\ndef show_metric(history_list, metrics_name, val_flag=''):\n marker_list = ['*', 'd', 's', 'x', 'o']\n metrics_name_dict = {'r2':'R-square', 'mae':'mean absolute error', 'mse':'mean squared error'}\n\n for m, history in enumerate(history_list):\n history_metric = history.filter(regex=r'\\b{}{}\\b'.format(val_flag, metrics_name))[:3000]\n\n plt.plot(history_metric, linestyle=':', marker=marker_list[m], linewidth=2)\n\n plt.xticks(range(0, 11), fontsize=font_size)\n plt.yticks(fontsize=font_size)\n plt.ylabel(metrics_name_dict[metrics_name], fontsize=font_size)\n plt.xlabel('Round', fontsize=font_size)\n\n\ndef plot_history_df(history_list, task_name, val_flag=''):\n if 'relapse_risk' in task_name:\n metric_list = ['loss', 'f1']\n else:\n metric_list = ['loss', 'r2']\n plt.figure(figsize=(12, 4))\n L = len(metric_list)\n row = math.floor(math.sqrt(L))\n col = L / row\n for i, metric in enumerate(metric_list):\n plt.subplot(row, col, i+1)\n show_history(history_list, metric, val_flag)\n plt.legend(labels=['attention', 'attention+mlp', 'attention+label corrected',\n 'attention+mlp+label corrected(ours)', 'mlp', 'mlp+label corrected'],\n fontsize=14)\n # plt.title('{} {}'.format(metric, task_name), fontsize=font_size)\n\n\ndef show_history(history_list, metrics_name, val_flag=''):\n marker_list = ['^', 'd', 's', '*', 'x', 'o']\n for m, history in enumerate(history_list):\n history_metric = history.filter(regex=r'\\b{}{}'.format(val_flag, metrics_name))[:3000]\n history_ = np.mean(history_metric, axis=1)\n len_ = history_.shape[0]\n plt.plot(history_, linewidth=2, marker=marker_list[m], markevery=200)\n plt.fill_between(range(len_), np.min(history_metric, axis=1), np.max(history_metric, axis=1), alpha=0.3)\n plt.xticks(fontsize=font_size)\n plt.yticks(fontsize=font_size)\n plt.ylabel(val_flag + metrics_name, fontsize=font_size)\n plt.xlabel('Epoch', fontsize=font_size)\n\n\ndef plot_history(history_list, task_name, val_flag=False):\n if task_name == 'relapse_risk':\n metric_list = ['loss', 'f1']\n else:\n metric_list = ['loss', 'r2']\n plt.figure(figsize=(12, 4))\n L = len(metric_list)\n for i, metric in enumerate(metric_list):\n plt.subplot(squrt(), L, i+1)\n show_train_history(history_list, metric)\n if val_flag:\n show_train_history(history_list, 'val_{}'.format(metric))\n plt.legend(labels=[metric, 'val_{}'.format(metric)], loc='upper left')\n plt.title('{} {}'.format(task_name, metric))\n\n\ndef history_save(history_list, history_name):\n history_all = pd.DataFrame([])\n for history in history_list:\n history_ = pd.DataFrame.from_dict(history.history, orient='index')\n history_all = pd.concat([history_all, history_], axis=0)\n history_all.to_csv('./hitory_{}.csv'.format(history_name))\n\n\ndef show_train_history(history_list, metrics_name):\n metrics_list = None\n for history in history_list:\n history_metric = pd.DataFrame(np.array(history.history[metrics_name]).reshape(1, -1))\n if metrics_list is None:\n metrics_list = history_metric\n else:\n metrics_list = pd.concat([metrics_list, history_metric], axis=0)\n # metrics = np.median(metrics_list, axis=0)\n metrics = np.mean(metrics_list, axis=0)\n plt.plot(metrics)\n plt.ylabel(metrics_name)\n plt.xlabel('Epoch')\n" }, { "alpha_fraction": 0.5424819588661194, "alphanum_fraction": 0.5615860223770142, "avg_line_length": 37.60834884643555, "blob_id": "2cefec237017dd51cb118ab4b586918b19ccc722", "content_id": "2ea2c059e09119f5fa339da61cec23d54eed6255", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19436, "license_type": "no_license", "max_line_length": 120, "num_lines": 503, "path": "/Regression/src/learn_weight_main.py", "repo_name": "Peroxidess/Ablation-Time-Prediction-Model", "src_encoding": "UTF-8", "text": "# Copyright (c) 2017 - 2019 Uber Technologies, Inc.\n#\n# Licensed under the Uber Non-Commercial License (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 the root directory of this project.\n#\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n#\n#\n# Runs MNIST experitment. Default 10 runs for 10 random seeds.\n#\n# Usage:\n# python -m mnist.imblanace_mnist_train_ad.py\n#\n# Flags:\n# --exp [string] Experiment name, `ours`, `hm`, `ratio`, `random` or `baseline`.\n# --pos_ratio [float] The ratio for the positive class, choose between 0.9 - 0.995.\n# --nrun [int] Total number of runs with different random seeds.\n# --ntrain [int] Number of training examples.\n# --nval [int] Number of validation examples.\n# --ntest [int] Number of test examples.\n# --tensorboard Writes TensorBoard logs while training, default True.\n# --notensorboard Disable TensorBoard.\n# --verbose Print training progress, default False.\n# --noverbose Disable printing.\n#\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport numpy as np\nimport pandas as pd\nimport os\nimport six\nimport tensorflow as tf\n\nfrom collections import namedtuple\nfrom tensorflow.contrib.learn.python.learn.datasets.mnist import DataSet\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom tqdm import tqdm\n\nfrom learn_rewieght.reweight import get_model, reweight_random, reweight_autodiff, reweight_hard_mining\nfrom preprocess.load_data import load_data_\nfrom preprocess.get_dataset import get_dataset_, data_preprocessing, anomaly_dectection\nfrom model.training_ import training_model, model_training, precision, recall, f1, r2\nfrom sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error\nfrom sklearn.model_selection import KFold\nimport matplotlib.pyplot as plt\n\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'\ntf.logging.set_verbosity(tf.logging.ERROR)\n\nflags = tf.flags\nflags.DEFINE_float('pos_ratio', 0.995, 'Ratio of positive examples in training')\nflags.DEFINE_integer('nrun', 10, 'Number of runs')\nflags.DEFINE_integer('ntest', 500, 'Number of testing examples')\nflags.DEFINE_integer('ntrain', 5000, 'Number of training examples')\nflags.DEFINE_integer('nval', 10, 'Number of validation examples')\nflags.DEFINE_bool('verbose', False, 'Whether to print training progress')\nflags.DEFINE_bool('tensorboard', False, 'Whether to save training progress')\nflags.DEFINE_string('exp', 'baseline', 'Which experiment to run')\nFLAGS = tf.flags.FLAGS\n\n\nConfig = namedtuple('Config', [\n 'reweight', 'lr', 'num_steps', 'random', 'ratio_weighted', 'nval', 'hard_mining', 'bsize'\n])\n\nexp_repo = dict()\n\n\ndef RegisterExp(name):\n def _decorator(f):\n exp_repo[name] = f\n return f\n\n return _decorator\n\n\nLR = 0.001\nNUM_STEPS = 4000\n\n\n@RegisterExp('baseline')\ndef baseline_config():\n return Config(\n reweight=False,\n num_steps=NUM_STEPS * 2,\n lr=LR,\n random=False,\n ratio_weighted=False,\n hard_mining=False,\n bsize=100,\n nval=0)\n\n\n@RegisterExp('hm')\ndef baseline_config():\n return Config(\n reweight=False,\n num_steps=NUM_STEPS * 2,\n lr=LR,\n random=False,\n ratio_weighted=False,\n hard_mining=True,\n bsize=500,\n nval=0)\n\n\n@RegisterExp('ratio')\ndef ratio_config():\n return Config(\n reweight=False,\n num_steps=NUM_STEPS * 2,\n lr=LR,\n random=False,\n ratio_weighted=True,\n hard_mining=False,\n bsize=100,\n nval=0)\n\n\n@RegisterExp('random')\ndef dpfish_config():\n return Config(\n reweight=True,\n num_steps=NUM_STEPS * 2,\n lr=LR,\n random=True,\n ratio_weighted=False,\n hard_mining=False,\n bsize=100,\n nval=0)\n\n\n@RegisterExp('ours')\ndef ours_config():\n return Config(\n reweight=True,\n num_steps=NUM_STEPS,\n lr=LR,\n random=False,\n ratio_weighted=False,\n hard_mining=False,\n bsize=100,\n nval=FLAGS.nval)\n\n\ndef get_imbalance_dataset(mnist,\n pos_ratio=0.9,\n ntrain=5000,\n nval=10,\n ntest=500,\n seed=0,\n class_0=4,\n class_1=9):\n rnd = np.random.RandomState(seed)\n\n # In training, we have 10% 4 and 90% 9.\n # In testing, we have 50% 4 and 50% 9.\n ratio = 1 - pos_ratio\n ratio_test = 0.5\n\n x_train = mnist.train.images\n y_train = mnist.train.labels\n x_test = mnist.test.images\n y_test = mnist.test.labels\n x_train_0 = x_train[y_train == class_0]\n x_test_0 = x_test[y_test == class_0]\n\n # First shuffle, negative.\n idx = np.arange(x_train_0.shape[0])\n rnd.shuffle(idx)\n x_train_0 = x_train_0[idx]\n\n nval_small_neg = int(np.floor(nval * ratio_test))\n ntrain_small_neg = int(np.floor(ntrain * ratio)) - nval_small_neg\n\n x_val_0 = x_train_0[:nval_small_neg] # 450 4 in validation.\n x_train_0 = x_train_0[nval_small_neg:nval_small_neg + ntrain_small_neg] # 500 4 in training.\n\n if FLAGS.verbose:\n print('Number of train negative classes', ntrain_small_neg)\n print('Number of val negative classes', nval_small_neg)\n\n idx = np.arange(x_test_0.shape[0])\n rnd.shuffle(idx)\n x_test_0 = x_test_0[:int(np.floor(ntest * ratio_test))] # 450 4 in testing.\n\n x_train_1 = x_train[y_train == class_1]\n x_test_1 = x_test[y_test == class_1]\n\n # First shuffle, positive.\n idx = np.arange(x_train_1.shape[0])\n rnd.shuffle(idx)\n x_train_1 = x_train_1[idx]\n\n nvalsmall_pos = int(np.floor(nval * (1 - ratio_test)))\n ntrainsmall_pos = int(np.floor(ntrain * (1 - ratio))) - nvalsmall_pos\n\n x_val_1 = x_train_1[:nvalsmall_pos] # 50 9 in validation.\n x_train_1 = x_train_1[nvalsmall_pos:nvalsmall_pos + ntrainsmall_pos] # 4500 9 in training.\n\n idx = np.arange(x_test_1.shape[0])\n rnd.shuffle(idx)\n x_test_1 = x_test_1[idx]\n x_test_1 = x_test_1[:int(np.floor(ntest * (1 - ratio_test)))] # 500 9 in testing.\n\n if FLAGS.verbose:\n print('Number of train positive classes', ntrainsmall_pos)\n print('Number of val positive classes', nvalsmall_pos)\n\n y_train_subset = np.concatenate([np.zeros([x_train_0.shape[0]]), np.ones([x_train_1.shape[0]])])\n y_val_subset = np.concatenate([np.zeros([x_val_0.shape[0]]), np.ones([x_val_1.shape[0]])])\n y_test_subset = np.concatenate([np.zeros([x_test_0.shape[0]]), np.ones([x_test_1.shape[0]])])\n\n y_train_pos_subset = np.ones([x_train_1.shape[0]])\n y_train_neg_subset = np.zeros([x_train_0.shape[0]])\n\n x_train_subset = np.concatenate([x_train_0, x_train_1], axis=0).reshape([-1, 28, 28, 1])\n x_val_subset = np.concatenate([x_val_0, x_val_1], axis=0).reshape([-1, 28, 28, 1])\n x_test_subset = np.concatenate([x_test_0, x_test_1], axis=0).reshape([-1, 28, 28, 1])\n\n x_train_pos_subset = x_train_1.reshape([-1, 28, 28, 1])\n x_train_neg_subset = x_train_0.reshape([-1, 28, 28, 1])\n\n # Final shuffle.\n idx = np.arange(x_train_subset.shape[0])\n rnd.shuffle(idx)\n x_train_subset = x_train_subset[idx]\n y_train_subset = y_train_subset[idx]\n\n idx = np.arange(x_val_subset.shape[0])\n rnd.shuffle(idx)\n x_val_subset = x_val_subset[idx]\n y_val_subset = y_val_subset[idx]\n\n idx = np.arange(x_test_subset.shape[0])\n rnd.shuffle(idx)\n x_test_subset = x_test_subset[idx]\n y_test_subset = y_test_subset[idx]\n\n train_set = DataSet(x_train_subset * 255.0, y_train_subset)\n train_pos_set = DataSet(x_train_pos_subset * 255.0, y_train_pos_subset)\n train_neg_set = DataSet(x_train_neg_subset * 255.0, y_train_neg_subset)\n val_set = DataSet(x_val_subset * 255.0, y_val_subset)\n test_set = DataSet(x_test_subset * 255.0, y_test_subset)\n\n return train_set, val_set, test_set, train_pos_set, train_neg_set\n\n\ndef get_exp_logger(sess, log_folder):\n \"\"\"Gets a TensorBoard logger.\"\"\"\n with tf.name_scope('Summary'):\n writer = tf.summary.FileWriter(os.path.join(log_folder), sess.graph)\n\n class ExperimentLogger():\n def log(self, niter, name, value):\n summary = tf.Summary()\n summary.value.add(tag=name, simple_value=value)\n writer.add_summary(summary, niter)\n\n def flush(self):\n \"\"\"Flushes results to disk.\"\"\"\n writer.flush()\n\n return ExperimentLogger()\n\n\ndef evaluate(sess, x_, y_, acc_, x, y, x_test, y_test):\n # Calculate final results.\n train_acc = sess.run(acc_, feed_dict={x_: x, y_: y})\n\n test_acc = sess.run(acc_, feed_dict={x_: x_test, y_: y_test})\n\n return train_acc, test_acc\n\n\ndef get_metric(pred, y):\n total_error = tf.reduce_sum(tf.square(tf.subtract(y, tf.reduce_mean(y))))\n unexplained_error = tf.reduce_sum(tf.square(tf.subtract(y, pred)))\n R_squared = tf.reduce_mean(tf.subtract(1.0, tf.div(unexplained_error, total_error)))\n mse = tf.reduce_mean(tf.square(pred - y))\n return mse\n\n\ndef run(train_data, test_data, seed, task_name, target='label'):\n train_data, test_data, co_col, ca_col = data_preprocessing(train_data, test_data,\n ca_co_sel_flag=False, onehot_flag=True)\n _, test_data = anomaly_dectection(train_data, test_data)\n # train_data, test_data = anomaly_dectection(train_data, test_data)# Outlier detection\n x, y, x_val, y_val, test_set, test_set_label = \\\n get_dataset_(train_data, test_data, clean_ratio=clean_ratio,\n test_retio=test_ratio, seed=seed, val_ratio=val_ratio) # label confusion according to requirements\n x.reset_index(inplace=True)\n x.drop(columns=['基线-患者基本信息-ID_sparse'], inplace=True)\n y.reset_index(inplace=True)\n y_val = y.loc[y['sup_label'] == 0].sample(n=clean_data_num, random_state=seed)\n\n x_val = x.loc[y_val.index]\n x.drop(index=x_val.index, inplace=True)\n y.drop(index=x_val.index, inplace=True)\n\n ntrain = FLAGS.ntrain\n nval = FLAGS.nval\n ntest = FLAGS.ntest\n folder = os.path.join('ckpt_mnist_imbalance_cnn_p{:d}'.format(int(FLAGS.pos_ratio * 100.0)),\n task_name + '_{:d}'.format(seed))\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n with tf.Graph().as_default(), tf.Session() as sess:\n bsize = batchsize\n\n x_ = tf.placeholder(tf.float32, [None, x.shape[1]], name='x')\n y_ = tf.placeholder(tf.float32, [None], name='y')\n x_val_ = tf.placeholder(tf.float32, [None, x.shape[1]], name='x_val')\n y_val_ = tf.placeholder(tf.float32, [None], name='y_val')\n ex_wts_ = tf.placeholder(tf.float32, [None, 1], name='ex_wts')\n ex_wts_b = tf.placeholder(tf.float32, [None, 1], name='ex_wts_b')\n lr_ = tf.placeholder(tf.float32, [], name='lr')\n\n # Build training model.\n with tf.name_scope('Train'):\n _, loss_c, logits_c = get_model(\n x_, y_, is_training=True, dtype=tf.float32, w_dict=None, ex_wts=ex_wts_, reuse=None)\n train_op = tf.train.RMSPropOptimizer(learning_rate=lr).minimize(loss_c)\n # metric_ = get_metric(logits_c, y_)\n\n # Build evaluation model.\n with tf.name_scope('Val'):\n _, loss_eval, logits_eval = get_model(\n x_,\n y_,\n is_training=False,\n dtype=tf.float32,\n w_dict=None,\n ex_wts=ex_wts_,\n reuse=True)\n metric_ = get_metric(logits_eval, y_)\n\n # Build reweighting model.\n if reweight:\n if random:\n ex_weights_ = reweight_random(bsize)\n else:\n ex_weights_, var_list_, grads_, grads_w_ = reweight_autodiff(\n x_,\n y_,\n x_val_,\n y_val_,\n ex_wts_,\n ex_wts_b,\n bsize,\n clean_data_num,\n eps=0.1,\n gate_gradients=1)\n else:\n if hard_mining:\n ex_weights_ = reweight_hard_mining(x_, y_, positive=True)\n else:\n if ratio_weighted:\n # Weighted by the ratio of each class.\n ex_weights_ = pos_ratio * (1 - y_) + (1 - pos_ratio) * (y_)\n else:\n # Weighted by uniform.\n ex_weights_ = tf.ones([bsize], dtype=tf.float32) / float(bsize)\n\n if FLAGS.tensorboard:\n exp_logger = get_exp_logger(sess, folder)\n else:\n exp_logger = None\n num_steps = 10\n acc_sum = 0.0\n acc_test_sum = 0.0\n loss_sum = 0.0\n count = 0\n sess.run(tf.global_variables_initializer())\n history = pd.DataFrame([])\n history_loss = []\n history_loss_acc = []\n history_metric_r2 = []\n history_metric_mse = []\n history_metric_mae = []\n\n for i in range(2000):\n kf = KFold(n_splits=2, shuffle=False, random_state=2020)\n # for k, (train_index, val_index) in enumerate(kf.split(x)):\n # x_batch, y_batch = x.iloc[train_index], y[target].iloc[train_index]\n x_batch, y_batch = x, y[target]\n ex_weights, var_list, grads, grads_w = sess.run(\n [ex_weights_, var_list_, grads_, grads_w_], feed_dict={x_: x_batch,\n y_: y_batch,\n x_val_: x_val,\n y_val_: y_val[target],\n ex_wts_: np.ones((batchsize, 1)),\n ex_wts_b: np.ones([clean_data_num, 1])})\n # ww = var_list[0]\n # bb = var_list[1]\n # print(x_batch.shape)\n # print(ww.shape)\n # xx = np.matmul(np.array(x_batch), ww)\n # xxx = xx + bb\n # xxxx = xxx - np.array(y_batch).reshape(-1, 1)\n # ss = (xxxx ** 2) / 2\n # sss = np.mean(ss)\n # ww_xx = xxxx.reshape(1, -1).dot(np.array(x_batch))\n # re_xx = np.mean(np.abs(xxxx))\n pred_tra, loss, acc, _ = sess.run(\n [logits_c, loss_c, metric_, train_op],\n feed_dict={\n x_: x_batch,\n y_: y_batch,\n x_val_: x_val,\n y_val_: y_val[target],\n ex_wts_: ex_weights,\n lr_: lr\n })\n print(np.unique(ex_weights))\n pred = sess.run(logits_eval, feed_dict={x_: test_set, y_: test_set_label[target], ex_wts_: ex_weights})\n r2 = r2_score(pred, test_set_label[target])\n mse = mean_squared_error(pred, test_set_label[target])\n mae = mean_absolute_error(pred, test_set_label[target])\n history_loss.append(loss)\n history_loss_acc.append(acc)\n history_metric_r2.append(r2)\n history_metric_mse.append(mse)\n history_metric_mae.append(mae)\n # Final evaluation.\n\n history['loss'] = history_loss\n history['acc'] = history_loss_acc\n history['r2'] = history_metric_r2\n history['mse'] = history_metric_mse\n history['mae'] = history_metric_mae\n\n pred_tra = sess.run(logits_eval, feed_dict={x_: x, y_: y[target], ex_wts_: ex_weights})\n train_r2 = r2_score(pred_tra, y[target])\n train_r2_ad = None\n train_mse = mean_squared_error(pred_tra, y[target])\n train_mae = mean_absolute_error(pred_tra, y[target])\n train_mape = None\n val_r2, val_r2_ad, val_mse, val_mae, val_mape, = None, None, None, None, None\n test_r2, test_r2_ad, test_mse, test_mae, test_mape = r2, None, mse, mae, None\n dict_ = dict(zip(['train_r2', 'train_r2_ad', 'train_mse', 'train_mae', 'train_mape',\n 'val_r2', 'val_r2_ad', 'val_mse', 'val_mae', 'val_mape',\n 'test_r2', 'test_r2_ad', 'test_mse', 'test_mae', 'test_mape'],\n [train_r2, train_r2_ad, train_mse, train_mae, train_mape,\n val_r2, val_r2_ad, val_mse, val_mae, val_mape,\n test_r2, test_r2_ad, test_mse, test_mae, test_mape,\n ]))\n metric_df = pd.DataFrame.from_dict([dict_])\n return metric_df, pd.DataFrame([]), pd.DataFrame([])\n\n\ndef main():\n metric_df_all = pd.DataFrame([])\n test_prediction_all = pd.DataFrame([]) # for prediction of test data\n history_df_all = pd.DataFrame([]) # for keras model\n for i, trial in enumerate(tqdm(six.moves.xrange(FLAGS.nrun))):\n print('rnum : {}'.format(i))\n seed = (trial * 2718) % 2020 # a different random seed for each run\n train_data, test_data = load_data_(datasets_name, task_name)\n metric_df, test_prediction, history_df = run(train_data, test_data, seed, task_name)\n metric_df_all = pd.concat([metric_df_all, metric_df], axis=0)\n test_prediction_all = pd.concat([test_prediction_all, test_prediction], axis=1)\n history_df_all = pd.concat([history_df_all, history_df], axis=1)\n\n for col in metric_df_all.columns:\n print('{} {:.4f} ({:.4f}) max: {:.4f} median {:.4f} min: {:.4f}'.format(col, metric_df_all[col].mean(),\n metric_df_all[col].std(),\n metric_df_all[col].max(),\n metric_df_all[col].median(),\n metric_df_all[col].min()))\n metric_df_all.to_csv('./metric_{}_{}nrun_{}Fold.csv'.format(task_name, nrun, n_splits), index=False)\n history_df_all.to_csv('./history_{}_{}nrun_{}Fold.csv'.format(task_name, nrun, n_splits), index=False)\n # test_prediction_all.columns = ['ab_time', 'ab_time_enh']\n test_prediction_all.to_csv('./prediction{}_{}nrun_{}Fold.csv'.format(task_name, nrun, n_splits))\n plt.show()\n pass\n\n\nnp.random.seed(2020)\ndatasets_name = 'LiverAblation'\ntask_name = 'ablation_time_learn_weight' # ablation_time_enh / ablation_time_vanilla / relapse_risk\nnrun = 10 # num of repeated experiments\nclean_ratio = 1 # 1 for No label confusion\ntest_ratio = 0 # test data ratio for label confusion\nval_ratio = 0 # val data ratio for label confusion\nn_splits = 1 # n_splits > 1 for Kfold cross validation / n_splits==1 for training all data\nepoch = 5000 # Kfold cross validation: a large number / training all data: mean epoch\nbatchsize = 348\nlr = 1e-4\nclean_data_num = 10\nreweight = True\nnum_steps = NUM_STEPS\nrandom = False\nratio_weighted = False\nhard_mining = False\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6129254698753357, "alphanum_fraction": 0.633164644241333, "avg_line_length": 51.38554382324219, "blob_id": "e6b7b5df295566a42ca1d417e90a9d11c03872af", "content_id": "d475f7760a6f3149b403b1d8d6bde898b6acc037", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4348, "license_type": "no_license", "max_line_length": 104, "num_lines": 83, "path": "/Regression/src/model/evaluate.py", "repo_name": "Peroxidess/Ablation-Time-Prediction-Model", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, \\\n confusion_matrix, precision_score, recall_score, f1_score, r2_score, accuracy_score\nfrom sklearn.preprocessing import MinMaxScaler\n\n\ndef evaluate_classification(model, train_sets, train_label, val_sets, val_label, test_sets, test_label):\n relapse_risk_test = model.predict(test_sets)\n relapse_risk_tra = model.predict(train_sets)\n con_mat = confusion_matrix(test_label, relapse_risk_test.round())\n train_acc = accuracy_score(train_label, relapse_risk_tra.round())\n test_acc = accuracy_score(test_label, relapse_risk_test.round())\n train_f1 = f1_score(train_label, relapse_risk_tra.round())\n test_f1 = f1_score(test_label, relapse_risk_test.round())\n val_acc = None\n val_f1=None\n if val_label is not None:\n relapse_risk_val = model.predict(val_sets)\n val_acc = accuracy_score(val_label, relapse_risk_val.round())\n val_f1 = f1_score(val_label, relapse_risk_val.round())\n dict_ = dict(zip(['train_acc', 'test_acc', 'val_acc', 'val_f1', 'train_f1', 'test_f1'],\n [train_acc, test_acc, val_acc, val_f1, train_f1, test_f1]))\n return pd.DataFrame([dict_])\n\n\ndef mape(y_true, y_pred):\n return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n\n\ndef wmape(y_true, y_pred):\n return np.mean(np.abs(y_true - y_pred)) / np.mean(np.abs(y_true)) * 100\n\n\ndef smape(y_true, y_pred):\n return 2.0 * np.mean(np.abs(y_pred - y_true) / (np.abs(y_pred) + np.abs(y_true))) * 100\n\n\ndef evaluate_regression(model, train_sets, train_label, val_x, val_label, test_sets, test_label):\n test_target_pred = model.predict(test_sets)\n train_target_pred = model.predict(train_sets)\n num_data_tra = train_sets.shape[0]\n num_feat_tra = train_sets.shape[1]\n num_data_test = train_sets.shape[0]\n num_feat_test = train_sets.shape[1]\n train_r2 = r2_score(train_label, train_target_pred)\n train_r2_ad = 1 - ((1 - train_r2) * (num_data_tra - 1)) / abs(num_data_tra - num_feat_tra - 1)\n test_r2 = r2_score(test_label, test_target_pred)\n test_r2_ad = 1 - ((1 - test_r2) * (num_data_test - 1)) / abs(num_data_test - num_feat_test - 1)\n train_mse = mean_squared_error(train_label, train_target_pred)\n train_mae = mean_absolute_error(train_label, train_target_pred)\n test_mse = mean_squared_error(test_label, test_target_pred)\n test_mae = mean_absolute_error(test_label, test_target_pred)\n\n mms = MinMaxScaler(feature_range=(0.1, 1))\n train_label_mms = mms.fit_transform(np.array(train_label).reshape(-1, 1))\n test_label_mms = mms.fit_transform(np.array(test_label).reshape(-1, 1))\n train_target_pred_mns = mms.fit_transform(train_target_pred.reshape(-1, 1))\n test_target_pred_mns = mms.fit_transform(test_target_pred.reshape(-1, 1))\n train_mape = wmape(train_label_mms, train_target_pred_mns.reshape(-1, ))\n test_mape = wmape(test_label_mms, test_target_pred_mns.reshape(-1, ))\n err = test_label - np.squeeze(test_target_pred)\n if not val_x.empty:\n val_target_pred = model.predict(val_x)\n num_data_val = val_x.shape[0]\n num_feat_val = val_x.shape[1]\n val_r2 = r2_score(val_label, val_target_pred)\n val_r2_ad = 1 - ((1 - val_r2) * (num_data_val - 1)) / abs(num_data_val - num_feat_val - 1)\n val_mse = mean_squared_error(val_label, val_target_pred)\n val_mae = mean_absolute_error(val_label, val_target_pred)\n val_label_mms = mms.fit_transform(np.array(val_label).reshape(-1, 1))\n val_target_pred_mns = mms.fit_transform(val_target_pred.reshape(-1, 1))\n val_mape = smape(val_label_mms, val_target_pred_mns.reshape(-1, ))\n else:\n val_r2, val_r2_ad, val_mse, val_mae, val_mape = None, None, None, None, None\n dict_ = dict(zip(['train_r2', 'train_r2_ad', 'train_mse', 'train_mae', 'train_mape',\n 'val_r2', 'val_r2_ad', 'val_mse', 'val_mae', 'val_mape',\n 'test_r2', 'test_r2_ad', 'test_mse', 'test_mae', 'test_mape'],\n [train_r2, train_r2_ad, train_mse, train_mae, train_mape,\n val_r2, val_r2_ad, val_mse, val_mae, val_mape,\n test_r2, test_r2_ad, test_mse, test_mae, test_mape,\n ]))\n return pd.DataFrame.from_dict([dict_])\n" }, { "alpha_fraction": 0.5889958739280701, "alphanum_fraction": 0.6057771444320679, "avg_line_length": 45.30573272705078, "blob_id": "67da33b45d1f2b22fa4ece67f5653b3fbe1e37a1", "content_id": "b017476f065976a30df2b1a080739cdbc390f6d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7280, "license_type": "no_license", "max_line_length": 143, "num_lines": 157, "path": "/Regression/src/useless/ave_logsit_baseline.py", "repo_name": "Peroxidess/Ablation-Time-Prediction-Model", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nimport six\nimport tensorflow as tf\nfrom keras import losses\nfrom keras import backend as K\nfrom keras import optimizers\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, \\\n confusion_matrix, precision_score, recall_score, f1_score, r2_score\nfrom sklearn.linear_model import RidgeClassifierCV, LogisticRegressionCV, RidgeCV, LassoCV, LinearRegression\nfrom sklearn.svm import SVR\nfrom sklearn.neighbors import KNeighborsRegressor\nimport lightgbm as lgb\nimport matplotlib.pyplot as plt\n# from deepctr.models import DeepFM, xDeepFM, DCN, WDL\n# from deepctr.feature_column import SparseFeat, get_feature_names, DenseFeat\nfrom preprocess.load_data import load_data_\nfrom preprocess.get_dataset import get_dataset_, data_preprocessing, anomaly_dectection\nplt.rcParams['font.sans-serif'] = ['SimHei']\nplt.rcParams['axes.unicode_minus'] = False\n\n\ndef mean_absolute_percentage_error(y_true, y_pred):\n return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n\n\ndef ctr_model(linear_feature_columns, dnn_feature_columns):\n adam = tf.keras.optimizers.Adam(lr=0.0001)\n model = WDL(linear_feature_columns, dnn_feature_columns, task='regression')\n # model = xDeepFM(linear_feature_columns, dnn_feature_columns, task='regression')\n model.compile(adam, \"huber_loss\", metrics=['mae'],)\n return model\n\n\ndef baseline_model(train_set_mix, train_set_mix_label, ca_col, co_col, seed):\n clf = lgb.LGBMRegressor(max_depth=3,\n bagging_fraction=0.7,\n feature_fraction=0.7,\n reg_alpha=0.5,\n reg_lambda=0.5,\n min_child_samples=10,\n n_estimators=200,\n learning_rate=1e-1,\n random_state=seed,\n )\n # clf = lgb.LGBMRegressor(max_depth=4,\n # bagging_fraction=0.8,\n # feature_fraction=0.8,\n # reg_alpha=0.8,\n # reg_lambda=0.8,\n # min_child_samples=10,\n # n_estimators=500,\n # learning_rate=1e-1,\n # )\n\n # clf = lgb.LGBMRegressor()\n # clf = LassoCV()\n # clf = RidgeCV()\n return clf\n\n\ndef run(train_data, test_data, seed, target='label'):\n np.random.seed(seed)\n train_data, test_data, co_col, ca_col = data_preprocessing(train_data, test_data,\n ca_co_sel_flag=False, onehot_flag=False)\n # train_data, _ = anomaly_dectection(train_data, test_data=pd.DataFrame())\n # _, test_data = anomaly_dectection(train_data=pd.DataFrame(), test_data=test_data)\n # train_data, test_data = anomaly_dectection(train_data=train_data, test_data=test_data)\n train_set_mix, train_set_mix_label, val_set, val_set_label, test_set, test_set_label = \\\n get_dataset_(train_data, test_data, clean_ratio=clean_ratio,\n test_retio=test_ratio, val_ratio=val_ratio, seed=seed)\n\n # fixlen_feature_columns = [SparseFeat(feat, vocabulary_size=pd.concat([train_set_mix, test_set], axis=0)[feat].nunique(), embedding_dim=4)\n # for i, feat in enumerate(ca_col)] + [DenseFeat(feat, 1,)\n # for feat in co_col]\n #\n # dnn_feature_columns = fixlen_feature_columns\n # linear_feature_columns = fixlen_feature_columns\n # feature_names = get_feature_names(linear_feature_columns + dnn_feature_columns)\n # train_set_mix = {name: train_set_mix[name].values for name in feature_names}\n # test_set = {name: test_set[name].values for name in feature_names}\n # model = ctr_model(linear_feature_columns, dnn_feature_columns,)\n # history = model.fit(train_set_mix, train_set_mix_label[target].values,\n # batch_size=512, epochs=180, verbose=1, validation_split=0.2, )\n # train_set_mix = train_set_mix.loc[train_set_mix_label['sup_label'] == 0]\n # train_set_mix_label = train_set_mix_label.loc[train_set_mix_label['sup_label'] == 0]\n model = baseline_model(train_set_mix, train_set_mix_label, ca_col, co_col, seed)\n model.fit(train_set_mix, train_set_mix_label[target])\n\n # feat_df = pd.DataFrame({'column': train_set_mix.columns, 'importance': model.feature_importances_.round(5)})\n # feat_df_sort = feat_df.sort_values(by='importance', ascending=False)\n # feat_df_sort_ = feat_df_sort.set_index(['column'])\n # feat_df_sort_[:30].plot.barh(figsize=(15, 15), fontsize=12)\n # plt.title(\"n61_lgb_特征重要性\")\n # plt.show()\n train_target_pred = model.predict(train_set_mix)\n test_target_pred = model.predict(test_set)\n train_R2 = r2_score(train_set_mix_label[target], train_target_pred)\n num_data = train_set_mix.shape[0]\n num_feat = train_set_mix.shape[1]\n train_R2_ad = 1 - ((1 - train_R2) * (num_data - 1)) / abs(num_data - num_feat - 1)\n test_R2 = r2_score(test_set_label[target], test_target_pred)\n num_data = test_set.shape[0]\n num_feat = test_set.shape[1]\n test_R2_ad = 1 - ((1 - test_R2) * (num_data - 1)) / abs(num_data - num_feat - 1)\n train_mse = mean_squared_error(train_set_mix_label[target], train_target_pred)\n train_mae = mean_absolute_error(train_set_mix_label[target], train_target_pred)\n test_mse = mean_squared_error(test_set_label[target], test_target_pred)\n test_mae = mean_absolute_error(test_set_label[target], test_target_pred)\n test_mape = mean_absolute_percentage_error(test_set_label[target], test_target_pred.reshape(-1, ))\n err = test_set_label[target] - np.squeeze(test_target_pred)\n return [train_R2, test_R2, train_R2_ad, test_R2_ad, train_mse, test_mse, train_mae, test_mae, test_mape]\n\n\ndef run_many(train_data, test_data):\n metric_list_all = []\n for trial in tqdm(six.moves.xrange(nrun)):\n metric_list = run(train_data, test_data, (trial * 2718) % 2020)\n metric_list_all.append(metric_list)\n\n metric_df = pd.DataFrame(np.array(metric_list_all))\n metric_df.columns = ['train_R2', 'test_R2',\n 'train_R2_ad', 'test_R2_ad',\n 'train_mse', 'test_mse',\n 'train_mae', 'test_mae',\n 'test_mape',]\n for col in metric_df.columns:\n print('{} {:.4f} ({:.4f}) max: {:.4f} min: {:.4f}'.format(col, metric_df[col].mean(),\n metric_df[col].std(),\n metric_df[col].max(),\n metric_df[col].min()))\n pass\n\n\ndef main():\n train_data, test_data = load_data_(datasets_name)\n run_many(train_data, test_data)\n pass\n\n\ndatasets_name = 'LiverAblation'\nnrun = 10\nclean_ratio = 1\ntest_ratio = 0.2\nval_ratio = 0.2\nepoch = 200\nbatchsize = 1\niter_ = 1\nstep_ = 0.1\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5311355590820312, "alphanum_fraction": 0.5547785758972168, "avg_line_length": 46.67460250854492, "blob_id": "e58847f2ade123b308b903adc9a3e952c5df0b5e", "content_id": "7ff2e45fa53f1cdcf1b90fa17df1f1a7bd496a8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6006, "license_type": "no_license", "max_line_length": 127, "num_lines": 126, "path": "/Regression/src/preprocess/plot_tabel.py", "repo_name": "Peroxidess/Ablation-Time-Prediction-Model", "src_encoding": "UTF-8", "text": "import copy\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom model.history_ import plot_history_df, plot_metric_df\nimport numpy as np\nfrom scipy.stats import ttest_ind, levene\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n\n\ndef mape(y_true, y_pred):\n return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n\n\ndef metric_hist(data, nor=None):\n root_ = '../report/result/'\n file_list = [\n 'ablation_time_enh_1nrun_10Fold.csv',# ours\n\n # 'ablation_time_vanilla_att_only__1nrun_10Fold.csv',# att only\n # 'ablation_time_vanilla_natt_1nrun_10Fold.csv',#mlp only\n\n # 'ablation_time_enh_att_only__10nrun_1Fold.csv',#\n 'ablation_time_enh_natt_1nrun_10Fold.csv',# mlp+lc\n\n 'lr_10nrun_1Fold.csv',# baseline_lasso\n 'lr_non_1nrun_10Fold.csv',# nonrelapse\n 'gbm_1nrun_10Fold.csv',# gbm\n 'gbm_non_1nrun_10Fold.csv',# nonrelapse\n\n 'ablation_time_vanilla_1nrun_10Fold.csv',# ATT+MLP\n 'ablation_time_vanilla_non_1nrun_10Fold.csv',# att+mlp+non relapse\n\n # 'ablation_time_learn_weight_10nrun_1Fold.csv',\n\n # 'ablation_time_enh_non_10nrun_1Fold.csv', # 0.2297\n # 'ablation_time_vanilla_att_only_10nrun_1Fold.csv',#\n\n # 'ablation_time_enh_natt__10nrun_1Fold.csv',# 0.5686\n # 'ablation_time_enh_att_only__10nrun_1Fold.csv',# 0.5690\n # 'ablation_time_enh_natt__10nrun_1Fold.csv',# 0.5686\n ]\n metric_file_list = ['metric_' + file for file in file_list]\n history_file_list = ['history_' + file for file in file_list]\n pred_file_list = ['prediction' + file for file in file_list]\n\n tt_pvalue_list = np.array([])\n lv_pvalue_list = np.array([])\n metric_file_base = metric_file_list[0]\n metric_df_base = pd.read_csv(root_ + metric_file_base)\n\n for metric_file in metric_file_list:\n metric_df = pd.read_csv(root_ + metric_file)\n mae_col = metric_df.filter(regex=r'mae').columns\n mse_col = metric_df.filter(regex=r'mse').columns\n # metric_df[mae_col] = metric_df.loc[:, mae_col] * 562.062540\n # metric_df[mse_col] = metric_df.loc[:, mse_col] * 562.062540**2\n print('\\n', metric_file)\n for col in metric_df.columns:\n print('{} {:.4f} ({:.4f}) max: {:.4f} median {:.4f} min: {:.4f}'.format(col, metric_df[col].mean(),\n metric_df[col].std(),\n metric_df[col].max(),\n metric_df[col].median(),\n metric_df[col].min()))\n\n v1 = metric_df_base['test_mae']\n v2 = metric_df['test_mae']\n std_ = levene(v1, v2).pvalue\n lv_pvalue_list = np.append(lv_pvalue_list, std_)\n equal_var_ = False\n if std_ > 0.05:\n equal_var_ = True\n res = ttest_ind(v1, v2, equal_var=equal_var_).pvalue\n tt_pvalue_list = np.append(tt_pvalue_list, res)\n tt_pvalue_list = tt_pvalue_list.reshape(-1, 1)\n\n for pred_file in pred_file_list:\n pred_df = pd.read_csv(root_ + pred_file, index_col=0)\n data_inver_label_df = pd.DataFrame([])\n metric_df = pd.DataFrame([])\n for pred in pred_df:\n data_co = data.filter(regex=r'dense|^label')\n data_ = copy.deepcopy(data_co)\n data_.loc[:, 'label'] = np.array(pred_df[pred])\n data_inver_pred = pd.DataFrame(nor.inverse_transform(data_), columns=data_.columns)\n data_inver = pd.DataFrame(nor.inverse_transform(data_co), columns=data_co.columns)\n data_inver_pred_label = data_inver_pred['label']\n data_inver_label = data_inver['label']\n mae = mean_absolute_error(data_inver_label, data_inver_pred_label)\n mse = mean_squared_error(data_inver_label, data_inver_pred_label)\n mape_ = mape(data_inver_label, data_inver_pred_label)\n r2 = r2_score(data_inver_label, data_inver_pred_label)\n dict_ = dict(zip([\n 'test_r2', 'test_mse', 'test_mae', 'test_mape'],\n [\n r2, mse, mae, mape_,\n ]))\n metric_ = pd.DataFrame.from_dict([dict_])\n metric_df = pd.concat([metric_df, metric_], axis=0)\n data_inver_label_df = pd.concat([data_inver_label_df, data_inver_label], axis=1)\n # data_inver.to_csv(root_ + 'inver' + pred_file)\n\n history_df_all_list = []\n for history_file in history_file_list:\n history_df_all = pd.read_csv(root_ + history_file)\n history_df_all_list.append(history_df_all)\n # plot_history_df(history_df_all_list, task_name='ablation_time', val_flag='')\n plot_history_df(history_df_all_list, task_name='of the experimental results of ablation time prediction ', val_flag='val_')\n plt.show()\n\n metric_df_all_list = []\n metric_file_list = ['metric_ablation_time_enh_10nrun_1Fold.csv',\n # 'metric_ablation_time_enh_non_10nrun_1Fold.csv',\n 'metric_ablation_time_vanilla_10nrun_1Fold.csv',\n # 'metric_ablation_time_vanilla_non_10nrun_1Fold.csv',\n 'metric_gbm_10nrun_1Fold.csv',\n # 'metric_gbm_non_10nrun_1Fold.csv',\n 'metric_lr_10nrun_1Fold.csv',\n # 'metric_lr_non_10nrun_1Fold.csv',\n ]\n for history_file in metric_file_list:\n history_df_all = pd.read_csv(root_ + history_file)\n metric_df_all_list.append(history_df_all)\n # plot_history_df(history_df_all_list, task_name='ablation_time', val_flag='')\n plot_metric_df(metric_df_all_list, task_name='ablation_time', val_flag='test_')\n plt.show()\n pass" }, { "alpha_fraction": 0.5828628540039062, "alphanum_fraction": 0.6154101490974426, "avg_line_length": 48.36065673828125, "blob_id": "cc2e1952457835666ce0f5f9aa9b0bb785aca687", "content_id": "8e95a1410aa89f954b191d22807b54670e3f0d2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3037, "license_type": "no_license", "max_line_length": 120, "num_lines": 61, "path": "/Regression/src/preprocess/load_data.py", "repo_name": "Peroxidess/Ablation-Time-Prediction-Model", "src_encoding": "GB18030", "text": "#coding=gb18030\nimport numpy as np\nimport pandas as pd\n\n\ndef load_data_(datasets, task_name='', seed=2020):\n if datasets == 'winequality_white':\n data_path = '../DataSet/wine/{}.csv'.format(datasets)\n data = pd.read_csv(data_path)\n data.rename(columns={'quality': 'label'}, inplace=True)\n data.dropna(axis=0, subset=['label'], inplace=True)\n train_data = data.fillna(0)\n test_data = None\n elif datasets == 'PPH':\n data_path = '../DataSet/PPH/{}.csv'.format(datasets)\n data_head = pd.read_csv('../DataSet/PPH/PPH_head.csv', encoding='gb18030')\n data = pd.read_csv(data_path, encoding='gb18030', index_col='index')\n\n col = []\n for col_ in data.columns:\n col.append(col_ + np.squeeze(data_head[col_].values))\n data.columns = np.array(col)\n # data.to_csv('../DataSet/PPH/data_feat_name_add.csv', index=False, encoding='gb18030')\n\n data['sup_label'] = 0\n label_col = data.filter(regex=r'n61').columns.values[0]\n data.rename(columns={label_col: 'label'}, inplace=True)\n data.dropna(axis=0, subset=['label'], inplace=True)\n data['hours'] = data.filter(regex=r'field12').values - data.filter(regex=r'field9').values\n data['hours'] = data['hours'].apply(lambda x: 24 + x if x < 0 else x)\n data['minutes'] = data.filter(regex=r'field13').values - data.filter(regex=r'field10').values\n data['minutes'] = data['minutes'].apply(lambda x: 60 + x if x < 0 else x)\n data['minutes'] += data['hours'] * 60\n drop_columns = data.filter(\n regex=r'n421|field11|其他|field28|其他.1|n262|hours|n61|n51|n4417|n4318|field9|field10|field12|field13').columns\n train_data = data.drop(columns=drop_columns)\n # data.fillna(0, inplace=True)\n test_data = None\n elif datasets == 'LiverAblation':\n data_path = '../DataSet/LiverAblation/{}.csv'.format(datasets)\n data = pd.read_csv(data_path, encoding='gb18030', index_col='基线-患者基本信息-ID_sparse')\n # data_path = '../DataSet/LiverAblation/{}_trans.csv'.format(datasets)\n # data = pd.read_csv(data_path, encoding='gb18030', index_col='baseline_info_ID_sparse')\n\n data.rename(columns={'time_dense': 'label'}, inplace=True)\n data.rename(columns={'relapse_sparse': 'sup_label'}, inplace=True)\n drop_columns_ = data.filter(regex=r'随|ID|cluster|followupInfomation').columns\n data.drop(columns=drop_columns_, inplace=True)\n\n data_1 = data.loc[data['sup_label'] == 1]\n data_0 = data.loc[data['sup_label'] == 0].sample(n=data_1.shape[0] * 1, random_state=seed)\n data_undersmapling = pd.concat([data_1, data_0]).sample(frac=1, random_state=seed)\n test_data = data.drop(index=data_undersmapling.index)\n if 'non' in task_name:\n train_data = data_0\n else:\n train_data = data_undersmapling\n else:\n train_data = None\n test_data = None\n return train_data, test_data\n" }, { "alpha_fraction": 0.6011734008789062, "alphanum_fraction": 0.6178160905838013, "avg_line_length": 37.66666793823242, "blob_id": "b110bb15de8808ff49207ff2d639b22e364dd7c1", "content_id": "3478d432ad95125bda834b91eb8f1d26c808f58c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8378, "license_type": "no_license", "max_line_length": 118, "num_lines": 216, "path": "/Regression/src/useless/keras_att.py", "repo_name": "Peroxidess/Ablation-Time-Prediction-Model", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nimport six\nimport tensorflow as tf\nfrom keras import losses\nfrom keras import backend as K\nfrom keras import optimizers\nfrom keras.models import Sequential, Model\nfrom keras.callbacks import EarlyStopping\nfrom keras.layers import Input, Dense, Multiply, Activation, Layer, \\\n GlobalAveragePooling1D, Reshape, RepeatVector, Flatten, Lambda, Add, Embedding\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, \\\n confusion_matrix, precision_score, recall_score, f1_score, r2_score\nimport matplotlib.pyplot as plt\nfrom preprocess.load_data import load_data_\nfrom preprocess.get_dataset import get_dataset_, foo, anomaly_dectection\n\n\nclass Self_Attention(Layer):\n\n def __init__(self, output_dim, **kwargs):\n self.output_dim = output_dim\n super(Self_Attention, self).__init__(**kwargs)\n\n def build(self, input_shape):\n # 为该层创建一个可训练的权重\n # inputs.shape = (batch_size, time_steps, seq_len)\n self.kernel = self.add_weight(name='kernel',\n shape=(3, 1, self.output_dim),\n initializer='uniform',\n trainable=True)\n\n super(Self_Attention, self).build(input_shape)\n\n def call(self, x):\n x = K.expand_dims(x, axis=2)\n WQ = K.dot(x, self.kernel[0])\n WK = K.dot(x, self.kernel[1])\n WV = K.dot(x, self.kernel[2])\n\n print(\"WQ.shape\", WQ.shape)\n\n print(\"K.permute_dimensions(WK, [0, 2, 1]).shape\", K.permute_dimensions(WK, [0, 2, 1]).shape)\n\n QK = K.batch_dot(WQ, K.permute_dimensions(WK, [0, 2, 1]))\n\n QK = QK / (x.shape.as_list()[-1] ** 0.5)\n\n QK = K.softmax(QK)\n\n print(\"QK.shape\", QK.shape)\n\n V = K.batch_dot(QK, WV)\n\n return V\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], input_shape[1], self.output_dim)\n\n\ndef mean_absolute_percentage_error(y_true, y_pred):\n return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n\n\ndef get_activations(model, inputs, print_shape_only=False, layer_name=None):\n activations = []\n input = model.input\n if layer_name is None:\n outputs = [layer.output for layer in model.layers]\n else:\n outputs = [layer.output for layer in model.layers if layer.name == layer_name] # all layer outputs\n funcs = [K.function([input] + [K.learning_phase()], [out]) for out in outputs] # evaluation functions\n layer_outputs = [func([inputs, 1.])[0] for func in funcs]\n for layer_activations in layer_outputs:\n activations.append(layer_activations)\n if print_shape_only:\n print(layer_activations.shape)\n else:\n print(layer_activations)\n return activations\n\n\ndef r2(y_true, y_pred):\n return 1 - K.sum(K.square(y_pred - y_true))/K.sum(K.square(y_true - K.mean(y_true)))\n\n\ndef r_square(y_true, y_pred):\n SSR = K.mean(K.square(y_pred-K.mean(y_true)), axis=-1)\n SST = K.mean(K.square(y_true-K.mean(y_true)), axis=-1)\n return SSR/SST\n\n\ndef Att(att_dim, inputs, name):\n V = inputs\n QK = Dense(att_dim, bias=None)(inputs)\n QK = Dense(att_dim, bias=None)(QK)\n QK = Activation(\"softmax\", name=name)(QK)\n MV = Multiply()([V, QK])\n return(MV)\n\n\ndef bulid_model(train_set_mix, train_set_mix_label, ca_col, co_col):\n input_dim = train_set_mix.shape[-1]\n inputs = Input(shape=(input_dim,))\n\n atts1 = Att(input_dim, inputs, \"attention_vec\")\n x = Dense(64, activation='relu')(atts1)\n x = Dense(32, activation='relu')(x)\n x = Dense(16, activation='relu')(x)\n\n # atts2 = Att(4, atts2, \"attention_vec1\")\n output = Dense(1)(x)\n model = Model(input=inputs, output=output)\n return model\n\n\ndef Expand_Dim_Layer(tensor):\n def expand_dim(tensor):\n return K.expand_dims(tensor, axis=1)\n return Lambda(expand_dim)(tensor)\n\n\ndef bulid_model_atts(train_set_mix, train_set_mix_label, ca_col, co_col):\n input_dim = train_set_mix.shape[-1]\n inputs_ = Input(shape=(input_dim,))\n # inputs_emb = Embedding(10000, input_dim)(inputs_)\n atts1 = Self_Attention(input_dim)(inputs_)\n atts1 = GlobalAveragePooling1D()(atts1)\n x = Dense(64, activation='relu')(atts1)\n x = Dense(32, activation='relu')(x)\n x = Dense(16, activation='relu')(x)\n outputs = Dense(1)(x)\n model = Model(inputs=inputs_, outputs=outputs)\n model.summary()\n return model\n\n\ndef run(train_data, test_data, seed, reg_flag=False, label_enh_flag=False, reg_enh_flag=False, target='label'):\n train_data, test_data, co_col, ca_col = foo(train_data, test_data, ca_co_sel_flag=False, onehot_flag=True)\n train_set_mix, train_set_mix_label, val_set, val_set_label, test_set, test_set_label = \\\n get_dataset_(train_data, test_data, clean_ratio=clean_ratio,\n test_retio=test_ratio, seed=seed, val_ratio=val_ratio)\n\n train_curr_label = train_set_mix_label[target]\n test_curr_label = test_set_label[target]\n model = bulid_model_atts(train_set_mix, train_set_mix_label, ca_col, co_col)\n rms = optimizers.RMSprop(lr=1e-4)\n model.compile(optimizer=rms, loss='mean_squared_error', metrics=['mse', 'mae', r2, r_square])\n model.fit(train_set_mix, train_curr_label, epochs=epoch, batch_size=batchsize, validation_split=0.2,\n callbacks=[EarlyStopping(monitor='val_loss', patience=200, min_delta=0.01)])\n\n train_target_pred = model.predict(train_set_mix)\n test_target_pred = model.predict(test_set)\n num_data = train_set_mix.shape[0]\n num_feat = train_set_mix.shape[1]\n train_r2 = r2_score(train_set_mix_label[target], train_target_pred)\n train_r2_ad = 1 - ((1 - train_r2) * (num_data - 1)) / abs(num_data - num_feat - 1)\n test_r2 = r2_score(test_set_label[target], test_target_pred)\n test_r2_ad = 1 - ((1 - test_r2) * (num_data - 1)) / abs(num_data - num_feat - 1)\n train_mse = mean_squared_error(train_set_mix_label[target], train_target_pred)\n train_mae = mean_absolute_error(train_set_mix_label[target], train_target_pred)\n test_mse = mean_squared_error(test_set_label[target], test_target_pred)\n test_mae = mean_absolute_error(test_set_label[target], test_target_pred)\n test_mape = mean_absolute_percentage_error(test_set_label[target], test_target_pred.reshape(-1, ))\n err_enh = test_set_label[target] - np.squeeze(test_target_pred)\n\n # attention_vector = get_activations(model, train_set_mix[:1],\n # print_shape_only=True,\n # layer_name='attention_vec')[0].flatten()\n # pd.DataFrame(attention_vector, columns=['attention (%)']).plot(kind='bar',\n # title='Attention Mechanism as a '\n # 'function of input dimensions.')\n # plt.show()\n return test_r2, test_r2_ad, test_mse\n\n\ndef run_many(train_data, test_data):\n metric_list_all = []\n for trial in tqdm(six.moves.xrange(nrun)):\n # train_metric, test_metric, train_metric_enh, test_metric_enh = \\\n # run(train_data, test_data, (trial * 2020) % 1000, reg_flag=True, label_enh_flag=True, reg_enh_flag=True)\n metric_list = run(train_data, test_data, (trial * 2020) % 1000,\n reg_flag=True, label_enh_flag=True, reg_enh_flag=True)\n metric_list_all.append(metric_list)\n\n metric_df = pd.DataFrame(np.array(metric_list_all))\n metric_df.columns = ['train_metric', 'train_metric_enh', 'test_metric', 'test_metric_enh']\n for col in metric_df.columns:\n print('{} metric {:.3f} ({:.3f}) max: {:.3f}'.format(col, metric_df[col].mean(),\n metric_df[col].std(),\n metric_df[col].max()))\n pass\n\n\ndef main():\n train_data, test_data = load_data_(datasets_name)\n run_many(train_data, test_data)\n pass\n\n\nnp.random.seed(2020)\ndatasets_name = 'LiverAblation'\nnrun = 5\nclean_ratio = 1\ntest_ratio = 0.2\nval_ratio = 0\nepoch = 3000\nbatchsize = 16\niter_ = 10\nstep_ = 0.001\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5172446370124817, "alphanum_fraction": 0.5341585278511047, "avg_line_length": 48.685447692871094, "blob_id": "5d8096d399c651310ec8ff732ddef7114d4e3259", "content_id": "d2cad159162b19b2f0b614c34c875943d9ba0bbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10615, "license_type": "no_license", "max_line_length": 119, "num_lines": 213, "path": "/Regression/src/model/training_.py", "repo_name": "Peroxidess/Ablation-Time-Prediction-Model", "src_encoding": "UTF-8", "text": "import copy\nimport pandas as pd\nimport numpy as np\nimport lightgbm as lgb\nfrom sklearn.linear_model import RidgeClassifierCV, LogisticRegressionCV, RidgeCV, LassoCV, LinearRegression\nfrom keras.models import load_model\nfrom keras import backend as K\nfrom keras.optimizers import Adam, RMSprop, SGD\nfrom keras.callbacks import EarlyStopping\nfrom model.bulid_model import classifer_, regression_, label_correction\nfrom model.evaluate import evaluate_classification, evaluate_regression\n\n\ndef precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision\n\n\ndef recall(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n recall = true_positives / (possible_positives + K.epsilon())\n return recall\n\n\ndef r2(y_true, y_pred):\n return 1 - K.sum(K.square(y_pred - y_true))/K.sum(K.square(y_true - K.mean(y_true)))\n\n\ndef f1(y_true, y_pred):\n return 2 * precision(y_true, y_pred) * \\\n recall(y_true, y_pred) / (precision(y_true, y_pred) + recall(y_true, y_pred) + 1e-7)\n\n\n# model compile and fit\ndef model_training(model, train_sets, train_label, val_data, val_label, lr, task, epoch, batch_size, patience=100):\n if task == 'classification':\n metrics = ['acc', f1, precision, recall]\n loss = 'binary_crossentropy'\n val_metric = 'val_f1'\n elif task == 'regression':\n metrics = ['mse', 'mae', r2]\n metrics = [r2]\n loss = 'mean_squared_error'\n val_metric = 'val_r2'\n model.compile(optimizer=RMSprop(lr=lr), loss=loss, metrics=metrics)\n model.summary()\n if val_label is None:\n history = model.fit(train_sets, train_label,\n epochs=epoch,\n batch_size=batch_size,\n shuffle=True,\n callbacks=[EarlyStopping(monitor=val_metric, patience=patience, mode='max')],\n # callbacks=[EarlyStopping(monitor='val_loss', patience=200, min_delta=0.01)],\n verbose=2,\n )\n else:\n history = model.fit(train_sets, train_label,\n # validation_split=0.3,\n validation_data=(val_data, val_label),\n epochs=epoch,\n batch_size=batch_size,\n shuffle=True,\n callbacks=[EarlyStopping(monitor=val_metric, patience=patience, mode='max')],\n # callbacks=[EarlyStopping(monitor='val_loss', patience=200, min_delta=0.01)],\n verbose=2,\n )\n return history, model\n\n\n# select model\ndef training_model(train_set, train_set_label, task_name, train_index, val_index, test_set, test_set_label,\n epoch, batchsize, iter_=None, step_=None, target='label', seed=2020, label_corr_epoch=2):\n if train_index is not None:\n train_x, val_x = train_set.iloc[train_index], train_set.iloc[val_index]\n train_y, val_y = train_set_label.iloc[train_index], train_set_label.iloc[val_index]\n val_label = val_y[target]\n val_suplabel = val_y['sup_label']\n val_x_time = val_x.drop(columns=val_x.filter(regex=r'术后|出院|Post').columns)\n else:\n train_x = train_set\n train_y = train_set_label\n val_x = test_set\n val_x_time = test_set.drop(columns=val_x.filter(regex=r'术后|出院|Post').columns)\n val_label = test_set_label[target]\n val_suplabel = test_set_label['sup_label']\n train_x_time = train_x.drop(columns=train_x.filter(regex=r'术后|出院|Post').columns)\n test_set_time = test_set.drop(columns=test_set.filter(regex=r'术后|出院|Post').columns)\n # train_x_time.to_csv('train_data.csv', encoding='gb18030')\n train_data_raw = pd.read_csv('train_data.csv', encoding='gb18030')\n xx = set(train_data_raw.columns) - set(train_x_time.columns)\n rr = set(train_x_time.columns) - set(train_data_raw.columns)\n if 'risk' in task_name:\n classifer, att_weight = classifer_(train_x)\n # epoch=130 for training whole data 107\n # lr=8e-5 batchsize=8 patience= 90\n history, model = model_training(classifer,\n [train_x, train_y[target]], train_y['sup_label'],\n [val_x, val_label], val_suplabel,\n 8e-5, 'classification', 120, 16, 190)\n metric = evaluate_classification(model,\n [train_x, train_y[target]], train_y['sup_label'],\n [val_x, val_label], val_suplabel,\n [test_set, test_set_label[target]], test_set_label['sup_label'])\n test_pred = model.predict([test_set, test_set_label[target]])\n history_df = pd.DataFrame.from_dict(history.history, orient='columns')\n len_ = history_df.shape[0] # count the number of epoch\n\n elif 'vanilla' in task_name:\n regression = regression_(train_x_time)\n # epoch=2926 for training whole data 2709 for non-relapse data\n # lr=9e-6 batchsize=256 patience= 350\n history, model = model_training(regression, train_x_time, train_y[target], val_x_time, val_label,\n 9e-6, 'regression', 15000, batchsize, 2500) #240 2335\n metric = evaluate_regression(model, train_x_time, train_y[target],\n val_x_time, val_label,\n test_set_time, test_set_label[target],\n )\n test_pred = model.predict(test_set_time)\n history_df = pd.DataFrame.from_dict(history.history, orient='columns')\n len_ = len(history.history['loss']) # count the number of epoch\n elif 'load' in task_name:\n model = load_model('ablation_time_enh_10nrun_1Fold.h5', custom_objects={'r2': r2})\n test_pred = model.predict(test_set_time)\n history_df = pd.DataFrame([])\n metric = evaluate_regression(model,\n train_x_time, train_y[target],\n val_x_time, val_label,\n test_set_time, test_set_label[target],\n )\n len_ = 0\n elif 'enh' in task_name:\n history_df = pd.DataFrame([])\n classifer, att_weight = classifer_(train_x)\n # lr=8e-5 batchsize=16 epoch= 120\n history, classifer = model_training(classifer,\n [train_set, train_set_label[target]], train_set_label['sup_label'],\n [pd.DataFrame([]), None], None,\n 8e-5, 'classification', 120, 16, 130)\n label_target = copy.deepcopy(train_set_label[target])\n regression_enh = regression_(train_x_time)\n len_ = 0\n for i in range(label_corr_epoch):\n print('iter {}'.format(i))\n label_target = label_correction(classifer, train_set, label_target, iter_=iter_, step_=step_)\n # label_target = train_y[target]\n if train_index is not None:\n label_target_train = label_target.iloc[train_index]\n val_label = label_target.iloc[val_index]\n else:\n label_target_train = label_target\n\n # lr=9e-6 batchsize=256 epoch= 600\n history, model = model_training(regression_enh,\n train_x_time, label_target_train, val_x_time, val_label,\n 7e-5, 'regression', 225, batchsize, 220,)\n # 1e-5, 'regression', 1750, batchsize, 2120, )\n metric = evaluate_regression(model,\n train_x_time, train_y[target],\n val_x_time, val_label,\n test_set_time, test_set_label[target],\n )\n test_pred = model.predict(test_set_time)\n if history_df.empty:\n history_df = pd.DataFrame.from_dict(history.history, orient='columns')\n else:\n history_df = pd.concat([history_df, pd.DataFrame.from_dict(history.history, orient='columns')], axis=0)\n len_ += history_df.shape[0] # count the number of epoch\n history_df.reset_index(drop=True, inplace=True)\n if train_index is not None:\n val_pred = model.predict(val_x_time)\n risk = classifer.predict([val_x, train_set_label[target].iloc[val_index]])\n risk_corr = classifer.predict([val_x, val_pred])\n risk_change = risk - risk_corr\n risk_change_max = risk_change.max()\n risk_change_mean = risk_change.mean()\n x = 1\n elif 'lr' in task_name:\n model = LassoCV(random_state=seed)\n # model = RidgeCV()\n model.fit(train_x_time, train_y[target])\n metric = evaluate_regression(model,\n train_x_time, train_y[target],\n val_x_time, val_label,\n test_set_time, test_set_label[target],\n )\n history_df = pd.DataFrame([])\n len_ = 0\n test_pred = model.predict(test_set_time)\n elif 'gbm' in task_name:\n model = lgb.LGBMRegressor(\n max_depth=3,\n bagging_fraction=0.5,\n feature_fraction=0.5,\n reg_alpha=1,\n reg_lambda=1,\n min_child_samples=10,\n n_estimators=200,\n learning_rate=1e-1,\n random_state=seed,\n )\n model.fit(train_x_time, train_y[target])\n metric = evaluate_regression(model,\n train_x_time, train_y[target],\n val_x_time, val_label,\n test_set_time, test_set_label[target],\n )\n history_df = pd.DataFrame([])\n len_ = 0\n test_pred = model.predict(test_set_time)\n return model, history_df, metric, test_pred, len_\n" }, { "alpha_fraction": 0.6984667778015137, "alphanum_fraction": 0.7189096808433533, "avg_line_length": 25.68181800842285, "blob_id": "ac24f2e5ec040e64f6eb044840359f8ec21dae56", "content_id": "56f5fd7c5a50ef151477e65feb08095fea4f3141", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 587, "license_type": "no_license", "max_line_length": 63, "num_lines": 22, "path": "/Regression/src/eval.py", "repo_name": "Peroxidess/Ablation-Time-Prediction-Model", "src_encoding": "UTF-8", "text": "from model.history_ import plot_metric_df\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\n\n\nxx = os.getcwd()\npath_root = '../report/result/'\ntask_name = 'ablation_time_all'\nmetric_list = []\nmetric_list_dir = ['metric_ablation_time_enh_10nrun_1Fold.csv',\n'metric_ablation_time_vanilla_10nrun_1Fold.csv',\n'metric_gbm_10nrun_1Fold.csv',\n'metric_lr_10nrun_1Fold.csv',\n]\nfor metric_dir in metric_list_dir:\n dir = path_root + metric_dir\n metric_df = pd.read_csv(dir)\n metric_list.append(metric_df)\nplot_metric_df(metric_list, task_name, val_flag='val_')\nplt.show()\npass\n" }, { "alpha_fraction": 0.5439310669898987, "alphanum_fraction": 0.5678642392158508, "avg_line_length": 38.40506362915039, "blob_id": "4ea5c51f8f218708d61912c697297f8d4b548ba0", "content_id": "e03ff17d53db867d1ea92133cc7f631e2b3f8194", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18677, "license_type": "no_license", "max_line_length": 118, "num_lines": 474, "path": "/Regression/src/model/bulid_model.py", "repo_name": "Peroxidess/Ablation-Time-Prediction-Model", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nfrom keras import backend as K\nfrom keras import regularizers, activations\nfrom keras.layers import Dense, Input, Add, Concatenate, Dropout, \\\n BatchNormalization, Activation, Multiply, Embedding, Layer, GlobalAveragePooling1D\nfrom keras.models import Model\nimport copy\n\n\nclass Self_Attention(Layer):\n\n def __init__(self, output_dim, **kwargs):\n self.output_dim = output_dim\n super(Self_Attention, self).__init__(**kwargs)\n\n def build(self, input_shape):\n self.kernel = self.add_weight(name='kernel',\n shape=(3, input_shape[2], self.output_dim),\n initializer='uniform',\n trainable=True)\n\n super(Self_Attention, self).build(input_shape)\n\n def call(self, x):\n WQ = K.dot(x, self.kernel[0])\n WK = K.dot(x, self.kernel[1])\n WV = K.dot(x, self.kernel[2])\n\n print(\"WQ.shape\", WQ.shape)\n\n print(\"K.permute_dimensions(WK, [0, 2, 1]).shape\", K.permute_dimensions(WK, [0, 2, 1]).shape)\n\n QK = K.batch_dot(WQ, K.permute_dimensions(WK, [0, 2, 1]))\n\n QK = QK / (x.shape.as_list()[1] ** 0.5)\n\n QK = K.softmax(QK)\n\n print(\"QK.shape\", QK.shape)\n\n V = K.batch_dot(QK, WV)\n return V\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], input_shape[1], self.output_dim)\n\n\nclass FM(Layer):\n def __init__(self, output_dim, latent=32, activation='relu', **kwargs):\n self.latent = latent\n self.output_dim = output_dim\n self.activation = activations.get(activation)\n super(FM, self).__init__(**kwargs)\n\n def build(self, input_shape):\n self.b = self.add_weight(name='W0',\n shape=(self.output_dim,),\n trainable=True,\n initializer='zeros')\n self.w = self.add_weight(name='W',\n shape=(input_shape[1], self.output_dim),\n trainable=True,\n initializer='random_uniform')\n self.v= self.add_weight(name='V',\n shape=(input_shape[1], self.latent),\n trainable=True,\n initializer='random_uniform')\n super(FM, self).build(input_shape)\n\n def call(self, inputs, **kwargs):\n x = inputs\n x_square = K.square(x)\n\n xv = K.square(K.dot(x, self.v))\n xw = K.dot(x, self.w)\n\n p = 0.5*K.sum(xv-K.dot(x_square, K.square(self.v)), 1)\n\n rp = K.repeat_elements(K.reshape(p, (-1, 1)), self.output_dim, axis=-1)\n\n f = xw + rp + self.b\n\n output = K.reshape(f, (-1, self.output_dim))\n\n return output\n\n def compute_output_shape(self, input_shape):\n assert input_shape and len(input_shape)==2\n return input_shape[0],self.output_dim\n\n\ndef Att(att_dim, inputs, name):\n V = inputs\n QK = Dense(att_dim//4, bias=None, activation='relu')(inputs)\n QK = Dense(att_dim, bias=None, activation='relu')(QK)\n QK = Activation(\"softmax\", name=name)(QK)\n MV = Multiply()([V, QK])\n return(MV)\n\n\ndef regression_(train_x):\n input_dim = train_x.shape[1]\n l1_regul = 0\n l2_regul = 0\n input = Input(shape=(input_dim,))\n # input_ = BatchNormalization()(input, training=False)\n # input_fm = FM(input_dim)(input_)\n # input_emb = Embedding(input_dim + 1, input_dim//2)(input)\n # att = Self_Attention(input_dim//2)(input_emb)\n # att = GlobalAveragePooling1D()(att)\n atts1 = Att(input_dim, input, \"attention_vec10\")\n # atts11 = Att(input_dim, input_, \"attention_vec11\")\n # mlp_layer = Add()([atts1, atts11])\n # mlp_layer = Att(input_dim, mlp_layer, \"attention_vec20\")\n mlp_layer = atts1\n for units_ in [64, 16]:\n mlp_layer = Dense(units_, activation='relu',\n kernel_regularizer=regularizers.l1_l2(l1=l1_regul, l2=l2_regul))(mlp_layer)\n # mlp_layer = Dropout(0.5)(mlp_layer)\n # mlp_layer = BatchNormalization()(mlp_layer, training=False)\n # atts2 = Att(32, mlp_layer, \"attention_vec2\")\n mlp_layer_output = Dense(1)(mlp_layer)\n regression = Model(input=input, output=mlp_layer_output)\n return regression\n\n\ndef classifer_(train_x):\n input_dim = train_x.shape[1]\n input_dim_emb = (input_dim + 1)\n input_ = Input(shape=(input_dim,))\n input_c = Input(shape=(1,))\n\n l1_regul = 0\n l2_regul = 0\n # encoder layers\n inputs = Concatenate()([input_, input_c])\n\n atts1 = Att(input_dim_emb, inputs, \"attention_vec10\")\n # atts2 = Att(input_dim + 1, inputs, \"attention_vec11\")\n # input_fm = FM(input_dim + 1)(atts1)\n encoded_layer = atts1\n # encoded_layer = Concatenate()([atts1, atts2])\n for units_ in [64]:\n encoded_layer = Dense(units_, activation='relu',\n kernel_regularizer=regularizers.l1_l2(l1=l1_regul, l2=l1_regul))(encoded_layer)\n encoded_layer = Dropout(0.5)(encoded_layer)\n encoded_layer = BatchNormalization()(encoded_layer, training=False)\n\n encoder_output = Concatenate()([encoded_layer, input_c])\n\n # decoder layers\n decoded_layer = encoded_layer\n for units_ in [16, 128, train_x.shape[1]]:\n decoded_layer = Dense(units_, activation='relu',\n kernel_regularizer=regularizers.l1_l2(l1=l1_regul, l2=l1_regul))(decoded_layer)\n # decoded_layer = Dropout(0.2)(decoded_layer)\n decoded_layer = BatchNormalization()(decoded_layer, training=False)\n\n # classifer layers\n classifer_layer = Dense(8, activation='relu', kernel_regularizer=regularizers.l1_l2(l1=l1_regul, l2=l2_regul))(\n encoded_layer)\n classifer_layer = Dense(1, activation='sigmoid', kernel_regularizer=regularizers.l1_l2(l1=l1_regul, l2=l2_regul))(\n classifer_layer)\n\n # encoder = Model(input=[input_, input_c], output=encoded_layer)\n classifer = Model(input=[input_, input_c], output=classifer_layer)\n # autoencoder = Model(input=[input_, input_c], output=decoded_layer)\n att_weight = Model(input=[input_, input_c], output=atts1)\n # classifer.add_loss(recon_loss(y_true=input_, y_pred=decoded_layer))\n return classifer, att_weight\n\n\ndef eval_loss_and_grads(x, fetch_loss_and_grads):\n outs = fetch_loss_and_grads(x)\n loss_value = outs[0]\n grad_values = outs[1]\n return loss_value, grad_values\n\n\ndef gradient_ascent(x, fetch_loss_and_grads, iter, step, max_loss=None, min_loss=None):\n \"\"\"get gradient\n\n :param x: [dataframe list] inputs and label\n :param fetch_loss_and_grads: [ ] K.function\n :param iter_: [int] Number of iterations for label modification\n :param step_: [float] Learning rate for label modification\n\n :return label_target: [nparray] Corrected label\n \"\"\"\n for i in range(iter):\n loss_value, grad_values = eval_loss_and_grads(x, fetch_loss_and_grads)\n # if max_loss is not None and loss_value > max_loss:\n # break\n x[1] = x[1] - step * np.squeeze(grad_values).reshape(-1, 1)\n return x\n\n\ndef label_correction(model, model_input, label, iter_=1, step_=1e-3):\n \"\"\"correct label\n\n :param model: [keras model] Relapse risk prediction model\n :param model_input: [dataframe] Inputs\n :param label: [series] Labels that need to be corrected\n :param iter_: [int] Number of iterations for label modification\n :param step_: [float] Learning rate for label modification\n\n :return label_target: [dataframe] Corrected label\n \"\"\"\n loss = K.variable(0.)\n coeff = 1\n activation = model.get_layer(index=-1).output\n scaling = K.prod(K.cast(K.shape(activation), 'float32'))\n loss = loss + coeff * K.sum(K.square(activation[:, :])) / scaling\n dream = model.input\n grads = K.gradients(loss, dream[1])\n grads /= K.maximum(K.mean(K.abs(grads)), 1e-7)\n outputs = [loss, grads]\n fetch_loss_and_grads = K.function([dream[0], dream[1]], outputs, K.set_learning_phase(0))\n label_target = pd.DataFrame(copy.deepcopy(label))\n label_target = gradient_ascent([model_input, label_target], fetch_loss_and_grads, iter=iter_, step=step_)[1]\n return label_target\n\n\ndef get_model(inputs,\n labels,\n is_training=True,\n dtype=tf.float32,\n w_dict=None,\n ex_wts=None,\n reuse=None):\n \"\"\"\n :param inputs: [Tensor] Inputs.\n :param labels: [Tensor] Labels.\n :param is_training: [bool] Whether in training mode, default True.\n :param dtype: [dtype] Data type, default tf.float32.\n :param w_dict: [dict] Dictionary of weights, default None.\n :param ex_wts: [Tensor] Example weights placeholder, default None.\n :param reuse: [bool] Whether to reuse variables, default None.\n \"\"\"\n\n if w_dict is None:\n w_dict = {}\n\n def _get_var(name, shape, dtype, initializer):\n key = tf.get_variable_scope().name + '/' + name\n if key in w_dict:\n return w_dict[key]\n else:\n var = tf.get_variable(name, shape, dtype, initializer=initializer)\n w_dict[key] = var\n return var\n\n with tf.variable_scope('Model', reuse=reuse):\n shape_list = np.append(np.array([-1]), np.squeeze(inputs.shape[1:].as_list()))\n # shape_list_fir = np.append(np.squeeze(inputs.shape[1:].as_list()), np.array([16]))\n # shape_list_sec = np.array([16, 8])\n # shape_list_thr = np.array([8, 1])\n inputs_ = tf.cast(tf.reshape(inputs, shape_list), dtype)\n labels = tf.cast(tf.reshape(labels, [-1, 1]), dtype)\n\n # w_init = tf.truncated_normal_initializer(stddev=0.1)\n # w1 = _get_var('w1', shape_list_fir, dtype, initializer=w_init)\n # w2 = _get_var('w2', shape_list_sec, dtype, initializer=w_init)\n # w3 = _get_var('w3', shape_list_thr, dtype, initializer=w_init)\n # w4 = _get_var('w4', [1, 1], dtype, initializer=w_init)\n #\n # b_init = tf.constant_initializer(0.0)\n # b1 = _get_var('b1', 1, dtype, initializer=b_init)\n # b2 = _get_var('b2', 1, dtype, initializer=b_init)\n # b3 = _get_var('b3', 1, dtype, initializer=b_init)\n # b4 = _get_var('b4', 1, dtype, initializer=b_init)\n #\n # act = tf.nn.relu\n #\n # l0 = tf.identity(inputs_, name='l0')\n # z1 = tf.add(tf.matmul(l0, w1), b1, name='z1')\n # l1 = act(z1, name='l1')\n # z2 = tf.add(tf.matmul(l1, w2), b2, name='z2')\n # l2 = act(z2, name='l2')\n # z3 = tf.add(tf.matmul(l2, w3), b3, name='z3')\n # l3 = act(z3, name='l3')\n # z4 = tf.add(tf.matmul(l3, w4), b4, name='z4')\n # logits = tf.squeeze(l3)\n # out = tf.sigmoid(logits)\n dense1 = tf.layers.dense(inputs=inputs_, units=64, activation=tf.nn.relu)\n dense2 = tf.layers.dense(inputs=dense1, units=16, activation=tf.nn.relu)\n logits = tf.layers.dense(inputs=dense2, units=1, activation=tf.nn.sigmoid)\n\n if ex_wts is None:\n # Average loss.\n loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels))\n else:\n # Weighted loss.\n loss = tf.reduce_sum(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels) * ex_wts)\n return w_dict, loss, logits\n\n\ndef reweight_random(bsize, eps=0.0):\n \"\"\"Reweight examples using random numbers.\n\n :param bsize: [int] Batch size.\n :param eps: [float] Minimum example weights, default 0.0.\n \"\"\"\n ex_weight = tf.random_normal([bsize], mean=0.0, stddev=1.0)\n ex_weight_plus = tf.maximum(ex_weight, eps)\n ex_weight_sum = tf.reduce_sum(ex_weight_plus)\n ex_weight_sum += tf.to_float(tf.equal(ex_weight_sum, 0.0))\n ex_weight_norm = ex_weight_plus / ex_weight_sum\n return ex_weight_norm\n\n\ndef reweight_autodiff(inp_a,\n label_a,\n inp_b,\n label_b,\n bsize_a,\n bsize_b,\n eps=0.0,\n gate_gradients=1):\n \"\"\"Reweight examples using automatic differentiation.\n\n :param inp_a: [Tensor] Inputs for the noisy pass.\n :param label_a: [Tensor] Labels for the noisy pass.\n :param inp_b: [Tensor] Inputs for the clean pass.\n :param label_b: [Tensor] Labels for the clean pass.\n :param bsize_a: [int] Batch size for the noisy pass.\n :param bsize_b: [int] Batch size for the clean pass.\n :param eps: [float] Minimum example weights, default 0.0.\n :param gate_gradients: [int] Tensorflow gate gradients, reduce concurrency.\n \"\"\"\n ex_wts_a = tf.zeros([bsize_a], dtype=tf.float32)\n ex_wts_b = tf.ones([bsize_b], dtype=tf.float32) / float(bsize_b)\n w_dict, loss_a, logits_a = get_model(\n inp_a, label_a, ex_wts=ex_wts_a, is_training=True, reuse=True)\n var_names = w_dict.keys()\n var_list = [w_dict[kk] for kk in var_names]\n grads = tf.gradients(loss_a, var_list, gate_gradients=gate_gradients)\n\n var_list_new = [vv - gg for gg, vv in zip(grads, var_list)]\n w_dict_new = dict(zip(var_names, var_list_new))\n _, loss_b, logits_b = get_model(\n inp_b, label_b, ex_wts=ex_wts_b, is_training=True, reuse=True, w_dict=w_dict_new)\n grads_ex_wts = tf.gradients(loss_b, [ex_wts_a], gate_gradients=gate_gradients)[0]\n ex_weight = -grads_ex_wts\n ex_weight_plus = tf.maximum(ex_weight, eps)\n ex_weight_sum = tf.reduce_sum(ex_weight_plus)\n ex_weight_sum += tf.to_float(tf.equal(ex_weight_sum, 0.0))\n ex_weight_norm = ex_weight_plus / ex_weight_sum\n return ex_weight_norm\n\n\ndef reweight_hard_mining(inp, label, positive=False):\n \"\"\"Reweight examples using hard mining.\n\n :param inp: [Tensor] [N, ...] Inputs.\n :param label: [Tensor] [N] Labels\n :param positive: [bool] Whether perform hard positive mining or hard negative mining.\n\n :return [Tensor] Examples weights of the same shape as the first dim of inp.\n \"\"\"\n _, loss, logits = get_model(inp, label, ex_wts=None, is_training=True, reuse=True)\n\n # Mine for positive\n if positive:\n loss_mask = loss * label\n else:\n loss_mask = loss * (1 - label)\n\n if positive:\n k = tf.cast(tf.reduce_sum(1 - label), tf.int32)\n else:\n k = tf.cast(tf.reduce_sum(label), tf.int32)\n k = tf.maximum(k, 1)\n loss_sorted, loss_sort_idx = tf.nn.top_k(loss_mask, k)\n\n if positive:\n mask = 1 - label\n else:\n mask = label\n\n updates = tf.ones([tf.shape(loss_sort_idx)[0]], dtype=label.dtype)\n mask_add = tf.scatter_nd(tf.expand_dims(loss_sort_idx, axis=1), updates, [tf.shape(inp)[0]])\n mask = tf.maximum(mask, mask_add)\n mask_sum = tf.reduce_sum(mask)\n mask_sum += tf.cast(tf.equal(mask_sum, 0.0), tf.float32)\n mask = mask / mask_sum\n return mask\n\n\ndef get_lenet_model(inputs,\n labels,\n is_training=True,\n dtype=tf.float32,\n w_dict=None,\n ex_wts=None,\n reuse=None):\n \"\"\"Builds a simple LeNet.\n\n :param inputs: [Tensor] Inputs.\n :param labels: [Tensor] Labels.\n :param is_training: [bool] Whether in training mode, default True.\n :param dtype: [dtype] Data type, default tf.float32.\n :param w_dict: [dict] Dictionary of weights, default None.\n :param ex_wts: [Tensor] Example weights placeholder, default None.\n :param reuse: [bool] Whether to reuse variables, default None.\n \"\"\"\n\n if w_dict is None:\n w_dict = {}\n\n def _get_var(name, shape, dtype, initializer):\n key = tf.get_variable_scope().name + '/' + name\n if key in w_dict:\n return w_dict[key]\n else:\n var = tf.get_variable(name, shape, dtype, initializer=initializer)\n w_dict[key] = var\n return var\n\n with tf.variable_scope('Model', reuse=reuse):\n inputs_ = tf.cast(tf.reshape(inputs, [-1, 28, 28, 1]), dtype)\n labels = tf.cast(labels, dtype)\n\n w_init = tf.truncated_normal_initializer(stddev=0.1)\n w1 = _get_var('w1', [5, 5, 1, 16], dtype, initializer=w_init) # [14, 14, 16]\n w2 = _get_var('w2', [5, 5, 16, 32], dtype, initializer=w_init) # [7, 7, 32]\n w3 = _get_var('w3', [5, 5, 32, 64], dtype, initializer=w_init) # [4, 4, 64]\n w4 = _get_var('w4', [1024, 100], dtype, initializer=w_init)\n w5 = _get_var('w5', [100, 1], dtype, initializer=w_init)\n\n b_init = tf.constant_initializer(0.0)\n b1 = _get_var('b1', [16], dtype, initializer=b_init)\n b2 = _get_var('b2', [32], dtype, initializer=b_init)\n b3 = _get_var('b3', [64], dtype, initializer=b_init)\n b4 = _get_var('b4', [100], dtype, initializer=b_init)\n b5 = _get_var('b5', [1], dtype, initializer=b_init)\n\n act = tf.nn.relu\n\n # Conv-1\n l0 = tf.identity(inputs_, name='l0')\n z1 = tf.add(tf.nn.conv2d(inputs_, w1, [1, 1, 1, 1], 'SAME'), b1, name='z1')\n l1 = act(tf.nn.max_pool(z1, [1, 3, 3, 1], [1, 2, 2, 1], 'SAME'), name='l1')\n\n # Conv-2\n z2 = tf.add(tf.nn.conv2d(l1, w2, [1, 1, 1, 1], 'SAME'), b2, name='z2')\n l2 = act(tf.nn.max_pool(z2, [1, 3, 3, 1], [1, 2, 2, 1], 'SAME'), name='l2')\n\n # Conv-3\n z3 = tf.add(tf.nn.conv2d(l2, w3, [1, 1, 1, 1], 'SAME'), b3, name='z3')\n l3 = act(tf.nn.max_pool(z3, [1, 3, 3, 1], [1, 2, 2, 1], 'SAME'), name='l3')\n\n # FC-4\n z4 = tf.add(tf.matmul(tf.reshape(l3, [-1, 1024]), w4), b4, name='z4')\n l4 = act(z4, name='l4')\n\n # FC-5\n z5 = tf.add(tf.matmul(l4, w5), b5, name='z5')\n\n logits = tf.squeeze(z5)\n out = tf.sigmoid(logits)\n if ex_wts is None:\n # Average loss.\n loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels))\n else:\n # Weighted loss.\n loss = tf.reduce_sum(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels) * ex_wts)\n return w_dict, loss, logits" }, { "alpha_fraction": 0.558184027671814, "alphanum_fraction": 0.5672290921211243, "avg_line_length": 54.81553268432617, "blob_id": "77be8aa4299797d1769f68d637a5a8a3da2d3cf0", "content_id": "6eee23fa9f6706a0de1df50faf2f6d17642d5a6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5749, "license_type": "no_license", "max_line_length": 123, "num_lines": 103, "path": "/Regression/src/main.py", "repo_name": "Peroxidess/Ablation-Time-Prediction-Model", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport six\nfrom tqdm import tqdm\nfrom sklearn.model_selection import KFold\nimport matplotlib.pyplot as plt\nfrom preprocess.load_data import load_data_\nfrom preprocess.get_dataset import get_dataset_, data_preprocessing, anomaly_dectection\nfrom model.training_ import training_model, model_training, precision, recall, f1, r2\nfrom model.history_ import plot_history_df\n\n\ndef run(train_data, test_data, seed, task_name, target='label'):\n train_data, test_data, co_col, ca_col, nor = data_preprocessing(train_data, test_data,\n ca_co_sel_flag=False, onehot_flag=True)\n _, test_data = anomaly_dectection(train_data, test_data)\n # train_data, test_data = anomaly_dectection(train_data, test_data)# Outlier detection\n train_set_mix, train_set_mix_label, val_set, val_set_label, test_set, test_set_label = \\\n get_dataset_(nor,train_data, test_data, clean_ratio=clean_ratio,\n test_retio=test_ratio, seed=seed, val_ratio=val_ratio,)# label confusion according to requirements\n metric_df = pd.DataFrame([])\n test_prediction = pd.DataFrame([])\n history_df = pd.DataFrame([])\n history_list = []\n epoch_len_list = []\n\n if n_splits > 1:\n kf = KFold(n_splits=n_splits, shuffle=False, random_state=seed)\n for k, (train_index, val_index) in enumerate(kf.split(train_set_mix)):\n print('KFlod in : {}'.format(k))\n model_, history_, metric_, test_pred_, epoch_len = training_model(train_set_mix, train_set_mix_label,\n task_name, train_index, val_index,\n test_set, test_set_label,\n epoch, batchsize, iter_, step_, target, seed)\n metric_df = pd.concat([metric_df, metric_], axis=0)\n history_df = pd.concat([history_df, history_], axis=1)\n history_list.append(history_)\n test_prediction = pd.concat([test_prediction, pd.DataFrame(test_pred_)], axis=1)\n epoch_len_list.append(epoch_len)\n plot_history_df(history_list, task_name)\n print('epoch_len_mean', np.mean(epoch_len_list)) # mean epoch in kflod cross validation\n\n else:\n model_, history_, metric_, test_pred_, epoch_len = training_model(train_set_mix, train_set_mix_label,\n task_name, None, None,\n test_set, test_set_label,\n epoch, batchsize, iter_, step_, target, seed)\n metric_df = pd.concat([metric_df, metric_], axis=0)\n test_prediction = pd.concat([test_prediction, pd.DataFrame(test_pred_)], axis=1)\n history_df = pd.concat([history_df, history_], axis=1)\n history_list.append(history_)\n plot_history_df(history_list, task_name, val_flag='val_')\n try:\n model_.save('{}_{}nrun_{}Fold.h5'.format(task_name, nrun, n_splits))\n except:\n print('Failed to save model')\n return metric_df, test_prediction, history_df\n\n\nnp.random.seed(2020)\ndatasets_name = 'LiverAblation'\ntask_name = 'ablation_time_load' # ablation_time_enh / ablation_time_vanilla / relapse_risk\nnrun = 10 # num of repeated experiments\nclean_ratio = 1 # 1 for No label confusion\ntest_ratio = 0 # test data ratio for label confusion\nval_ratio = 0 # val data ratio for label confusion\nn_splits = 1 # n_splits > 1 for Kfold cross validation / n_splits==1 for training all data\nepoch = 5000 # Kfold cross validation: a large number / training all data: mean epoch\nbatchsize = 256\niter_ = 2 # Number of iterations for label modification\nstep_ = 0.0001 # learning rate for label modification\n\n\ndef main():\n metric_df_all = pd.DataFrame([])\n test_prediction_all = pd.DataFrame([]) # for prediction of test data\n history_df_all = pd.DataFrame([]) # for keras model\n for i, trial in enumerate(tqdm(six.moves.xrange(nrun))):\n print('rnum : {}'.format(i))\n seed = (trial * 2718) % 2020 # a different random seed for each run\n train_data, test_data = load_data_(datasets_name, task_name,seed)\n metric_df, test_prediction, history_df = run(train_data, test_data, seed, task_name)\n metric_df_all = pd.concat([metric_df_all, metric_df], axis=0)\n test_prediction_all = pd.concat([test_prediction_all, test_prediction], axis=1)\n history_df_all = pd.concat([history_df_all, history_df], axis=1)\n\n for col in metric_df_all.columns:\n print('{} {:.4f} ({:.4f}) max: {:.4f} median {:.4f} min: {:.4f}'.format(col, metric_df_all[col].mean(),\n metric_df_all[col].std(),\n metric_df_all[col].max(),\n metric_df_all[col].median(),\n metric_df_all[col].min()))\n metric_df_all.to_csv('./metric_{}_{}nrun_{}Fold.csv'.format(task_name, nrun, n_splits), index=False)\n history_df_all.to_csv('./history_{}_{}nrun_{}Fold.csv'.format(task_name, nrun, n_splits), index=False)\n # test_prediction_all.columns = ['ab_time', 'ab_time_enh']\n test_prediction_all.to_csv('./prediction{}_{}nrun_{}Fold.csv'.format(task_name, nrun, n_splits))\n plt.show()\n pass\n\n\nif __name__ == '__main__':\n main()\n pass\n" } ]
14
deepikaasharma/string-concat-for-numbers
https://github.com/deepikaasharma/string-concat-for-numbers
2b6c22a3eb1d9ca68d3ab62c5d35e51e7cd3960f
36dbbad625ec2c3e69df1f96e68564e4a873e5da
e743fd3ae53cca60adcaf239298d1b8f65026c3d
refs/heads/master
2022-12-02T02:05:40.877320
2020-08-17T04:40:33
2020-08-17T04:40:33
288,084,728
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6298701167106628, "alphanum_fraction": 0.6883116960525513, "avg_line_length": 21.14285659790039, "blob_id": "c7bb104e828b68569a6f140511d063a4bae2611d", "content_id": "616a6e22222d3bb6c3a36fc03f628e5cd003274c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 154, "license_type": "no_license", "max_line_length": 44, "num_lines": 7, "path": "/main.py", "repo_name": "deepikaasharma/string-concat-for-numbers", "src_encoding": "UTF-8", "text": "first_num = '123'\nsecond_num = '456'\nthird_num = '789'\n\n# Replace `None` with your code\nfinal_num = (first_num+second_num+third_num)\nprint(int(final_num))" } ]
1
islamaf/Software-development-exercise
https://github.com/islamaf/Software-development-exercise
13cf5721edc92aa50da0ec8241be10d8227307cf
ce65a4ca42dfe56fda6242329e868cb0047f9bfe
3cb6105a7c45933bcbab0a6b6d0d3b6276ae659f
refs/heads/main
2023-06-10T14:05:34.651403
2021-07-01T12:11:59
2021-07-01T12:11:59
382,020,362
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8709677457809448, "alphanum_fraction": 0.8709677457809448, "avg_line_length": 31, "blob_id": "9e76891a27591e6a2a3d7142ad5aa69df1cf0c4b", "content_id": "8ae458ba2b17d9bee3166fa2cb9894efea96fd55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 31, "license_type": "no_license", "max_line_length": 31, "num_lines": 1, "path": "/README.md", "repo_name": "islamaf/Software-development-exercise", "src_encoding": "UTF-8", "text": "# Software-development-exercise" }, { "alpha_fraction": 0.6105644702911377, "alphanum_fraction": 0.6338684558868408, "avg_line_length": 30.161291122436523, "blob_id": "931fdf83ad0f69bd5460bf6921c0fbae91ca62cc", "content_id": "a0c408482eb58fbb6b7f281c425bfe01ebf90f3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1931, "license_type": "no_license", "max_line_length": 122, "num_lines": 62, "path": "/gui_main.py", "repo_name": "islamaf/Software-development-exercise", "src_encoding": "UTF-8", "text": "import os\nfrom tkinter import Tk, ttk, filedialog\nimport pandas as pd\nfrom win32 import win32api\n\nroot = Tk()\nroot.title('Ahram Exam')\nroot.resizable(True, True)\n\nroot.frame_header = ttk.Frame()\nroot.geometry(\"350x250\")\nroot.eval('tk::PlaceWindow . center')\n\nttk.Label(root.frame_header, text='Browse file to open:', style='Header.TLabel', font=(\"Arial\", 15)).grid(row=1, column=1)\n\nfilename = ttk.Button(root.frame_header, text=\"Browse\", command=lambda: open_file()).grid(row=4, column=1)\n\nprint_result = ttk.Button(root.frame_header, text=\"Print result\", command=lambda: print_file())\nprint_result.grid(row=12, column=1)\nprint_result['state'] = 'disabled'\n\n\ndef open_file():\n file_to_open = filedialog.askopenfilename(initialdir=\"C:/\", title=\"Select file\",\n filetypes=((\"all files\", \"*.*\"), (\"excel files\", \"*.xls\")))\n df = pd.read_excel(file_to_open)\n os.startfile(file_to_open)\n\n ttk.Label(root.frame_header, text='All averages:', style='Header.TLabel',font=(\"Arial\", 15)).grid(row=6, column=1)\n ttk.Label(root.frame_header, text=df.mean(), style='Header.TLabel', font=(\"Arial\", 15)).grid(row=8, column=1)\n\n ttk.Label(root.frame_header, text=get_max_mean(df), style='Header.TLabel', font=(\"Arial\", 15)).grid(row=10, column=1)\n\n f = open('maximum_average.txt', 'w')\n f.write(get_max_mean(df))\n f.close()\n\n root.geometry(\"350x350\")\n\n print_result['state'] = 'enabled'\n\n\ndef print_file():\n file_to_print = \"maximum_average.txt\"\n if file_to_print:\n win32api.ShellExecute(0, \"print\", file_to_print, None, \".\", 0)\n\n\ndef get_max_mean(l):\n max_val = 0\n max_column = ''\n winner = \"\"\n for i, x in zip(l.columns, l.mean()):\n if x > max_val:\n max_val = x\n max_column = i\n winner = f'{max_column} is the maximum'\n return winner\n\n\nroot.frame_header.pack(pady=10, anchor=\"center\")\nroot.mainloop()" }, { "alpha_fraction": 0.48046875, "alphanum_fraction": 0.7109375, "avg_line_length": 16.066667556762695, "blob_id": "6e71064b5cd0b0088afb931eda74d670d025eeb3", "content_id": "5f281a4ee4592eaa3f4b4c18b5c8099e128cd1a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 256, "license_type": "no_license", "max_line_length": 33, "num_lines": 15, "path": "/requirements.txt", "repo_name": "islamaf/Software-development-exercise", "src_encoding": "UTF-8", "text": "altgraph==0.17\net-xmlfile==1.1.0\nfuture==0.18.2\nnumpy==1.21.0\nopenpyxl==3.0.7\npandas==1.2.5\npefile==2021.5.24\npyinstaller==4.3\npyinstaller-hooks-contrib==2021.2\npython-dateutil==2.8.1\npytz==2021.1\npywin32==301\npywin32-ctypes==0.2.0\nsix==1.16.0\nxlrd==2.0.1\n" } ]
3
CENSOREDd/test_fk
https://github.com/CENSOREDd/test_fk
e210664d37d20cdb3072c1604b7720f0ecd55222
6906641a50ee72faffc1c5d79c4b756278359199
04ed38afa51caf1367ce59c7c636e1a3ce9a6cac
refs/heads/master
2020-07-21T14:00:13.690475
2019-09-06T23:42:50
2019-09-06T23:42:50
206,889,101
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.567415714263916, "alphanum_fraction": 0.5786516666412354, "avg_line_length": 16.799999237060547, "blob_id": "4c16e3923ffedb95718e04ddcd367c92d96d5641", "content_id": "b9d4af6ea1bf10e501e9712276dbd4a2742f4129", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 178, "license_type": "no_license", "max_line_length": 35, "num_lines": 10, "path": "/fk.py", "repo_name": "CENSOREDd/test_fk", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nfrom time import sleep\n\nprint(\"what the fuck???\")\n\nif __name__ == \"__main__\":\n print(\"here is python code!!!\")\n print(\"Executing code...\")\n sleep(2)\n" }, { "alpha_fraction": 0.6603773832321167, "alphanum_fraction": 0.6792452931404114, "avg_line_length": 9.600000381469727, "blob_id": "f58ef0a8b22458b264211d5d8b8c6b355a2c95a9", "content_id": "fcc00b70c8e6b63d520771f7098b56d366ddff19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 53, "license_type": "no_license", "max_line_length": 21, "num_lines": 5, "path": "/test.py", "repo_name": "CENSOREDd/test_fk", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nimport fk\n\nprint(\"here is test\")\n" } ]
2
hui98/opencv
https://github.com/hui98/opencv
bc5236f3eeaaaa239ff51263fcebf8d89971de4f
214f9206e71a09c6cb061cc6a7f0758c948e229c
d417da354f0cf9add81c227df08fe96f0ea99a10
refs/heads/master
2021-04-28T14:24:44.814550
2018-02-18T15:33:31
2018-02-18T15:33:31
121,964,197
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5149946212768555, "alphanum_fraction": 0.568932056427002, "avg_line_length": 25.757225036621094, "blob_id": "c87f5c1e28f866597d7af1b5ba2520997e4c2afd", "content_id": "752461fd630e3f010b268b33915c156162652a41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4635, "license_type": "no_license", "max_line_length": 99, "num_lines": 173, "path": "/opencvtest.py", "repo_name": "hui98/opencv", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nimport random\nfrom math import *\n# import an image\nclass image:\n def __init__(self,na):\n self.dir='/home/hui/Pictures/'\n # self.name=raw_input('please input the picture name')\n self.name=na\n self.mode=cv2.IMREAD_COLOR\n self.im=cv2.imread(self.dir+self.name,self.mode)\n\n def reconf(self):\n self.im = cv2.imread(self.dir + self.name, self.mode)\n\n def modechoose(self,modex):\n if modex=='color':\n self.mode=cv2.IMREAD_COLOR\n elif modex == 'gray':\n self.mode=cv2.IMREAD_GRAYSCALE\n elif modex== 'alpha':\n self.mode=cv2.IMREAD_UNCHANGED\n else:\n print('wrong mode')\n self.reconf()\n\n def routechange(self):\n self.dir=raw_input('input your new route')\n self.name=raw_input('input your new filename')\n self.reconf()\n\n def show(self):\n cv2.imshow('huihui',self.im)\n k=cv2.waitKey(0)&0xFF\n if k==27: #wait for esc coming\n self.dele('all')\n\n def dele(self,modeb):\n if modeb=='all':\n cv2.destroyAllWindows()\n if modeb=='name':\n cv2.destroyWindow(raw_input(\"please input your window's name\"))\n\n def saveas(self):\n cv2.imwrite(raw_input('input your new filename'),self.im)\n def getpixel(self,a,b,c): #pixel is xiangshu ni dong de~ a is x b is y c is 0 1 2 B G R\n print self.im.item(a,b,c)\n def setpixel(self,e,f,g,h): # e f g is like the a b c and h is the new pixel value\n self.im.itemset((e,f,g),h)\nlook=image('hsj.jpeg')\nshino =image('shino.jpeg')\njuhua=image('juhua.jpg')\njuhua.show()\n'''for a in range(0,5000)\nx=random.randint(0,280)\ny=random.randint(0,449)\nfor b in range(0,3):\nvalue=random.randint(0,255)\nlook.setpixel(x,y,b,value)'''\n\n'''look.show()\nshino.show()'''\n'''test=look.im[50:140,100:200]\ncv2.imshow('hui',test)\nk = cv2.waitKey(0) & 0xFF\ncv2.destroyAllWindows()'''\nrows,cols,channel=look.im.shape\nrow,col,channels=shino.im.shape\npix=[]\nsbliye=[]\nhezi=[]\nR=[]\nG=[]\nB=[]\nn=130\nroute='/home/hui/'\ngreen='sbliyeG.txt'\nblue='sbliyeB.txt'\nred='sbliyeR.txt'\ngg=open(route+green,'w')\nbb=open(route+blue,'w')\nrr=open(route+red,'w')\n'''M=cv2.getRotationMatrix2D((220,240),0,0.6)\nK = cv2.getRotationMatrix2D((300, 300), 0, 0.5)\ndst=cv2.warpAffine(look.im,M,(cols,rows))\nshino1=cv2.warpAffine(shino.im,K,(col,row))\ncv2.imshow('hui',dst)\ncv2.imshow('shino',shino1)\nfor times in range(0,n):\n M=cv2.getRotationMatrix2D((215,248),(times)*360.0/n,1)\n dsto=cv2.warpAffine(dst,M,(cols,rows))\n if times==129:\n cv2.imshow('hi',dsto)\n look.im=dst\n for led in range(1,33):\n for i in range(0,3):\n pix.append(dsto.item(215,248-5*led,i))\n shino1.itemset((300, 300-5*led, i),dsto.item(215,248-5*led,i) )\n K = cv2.getRotationMatrix2D((300, 300), 360.0 / n, 1)\n shino1 = cv2.warpAffine(shino1, K, (col, row))\ncv2.imshow('huihui', shino1)'''\nM=cv2.getRotationMatrix2D((220,240),0,0.6)\ndst=cv2.warpAffine(juhua.im,M,(cols,rows))\ndef qm(x,y,nn): #x is xiangsu x y is xiangsu y\n xz=195\n yz=154\n x0=x\n y0=y\n a=pi/65\n A=np.matrix([[cos(nn*a),-sin(nn*a)],[sin(nn*a),cos(nn*a)]])\n X=np.matrix([x0,y0])\n X1=X*A\n xy=X1.tolist()\n x1=int(round(xy[0][0]))\n y1=int(round(xy[0][1]))\n x1=x1+xz\n y1=y1+yz\n return [x1,y1]\nzuobiao=[]\nfor times in range(0,130):\n for nnn in range(0,32):\n aaa=qm(0,4*nnn+1,times)\n zuobiao.append(aaa)\n for i in range(0,3):\n pix.append(dst.item(aaa[0],aaa[1],i))\n shino.im.itemset((aaa[0],aaa[1],i),dst.item(aaa[0],aaa[1],i))\ncv2.imshow('hui',dst)\nshino.show()\nlenth=n*32*3\nfor time in range(0,lenth):\n if pix[time]<128:\n sbliye.append('0')\n else :\n sbliye.append('1')\nfor ttt in range(0,n):\n for ledp in range(0,32):\n B.append(sbliye[(ttt+1)*96-(ledp+1)*3])\n G.append(sbliye[(ttt+1)*96-(ledp+1)*3+1])\n R.append(sbliye[(ttt+1)*96-(ledp+1)*3+2])\n b=''.join(B)\n g=''.join(G)\n r=''.join(R)\n B=[]\n G=[]\n R=[]\n BB=hex(int(b,2))\n GG=hex(int(g,2))\n RR=hex(int(r,2))\n\n if ttt==n-1:\n rr.write(RR+'\\n')\n bb.write(BB+'\\n')\n gg.write(GG+'\\n')\n\n else :\n if (ttt+1)%4==0 and ttt!=0:\n rr.write(RR+',\\n')\n bb.write(BB + ',\\n')\n gg.write(GG + ',\\n')\n else :\n rr.write(RR+' ,')\n bb.write(BB+' ,')\n gg.write(GG+' ,')\n \nrr.close()\nbb.close()\ngg.close()\n\n\nk=cv2.waitKey(0)&0xFF\nif k==27:\n cv2.destroyAllWindows()\n\n\n\n\n\n\n" } ]
1
rodelrod/pomodoro-report
https://github.com/rodelrod/pomodoro-report
4d024e40b2885975feafb9f317dcb800df4cda59
539ad13ad4fc9c9c86a5b5b66d3cc497d45f6834
be1598299884ee07a7f409b39d1bc0b701bc4bce
refs/heads/master
2020-05-20T00:55:07.914417
2012-10-04T01:43:19
2012-10-04T01:43:19
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4545454680919647, "alphanum_fraction": 0.49877750873565674, "avg_line_length": 33.60769271850586, "blob_id": "a78b1c362e37228ebc9710ee17f91672d753f03d", "content_id": "0bd9f9a4125247d432ef75b895d986e3ef3ab5a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4499, "license_type": "no_license", "max_line_length": 66, "num_lines": 130, "path": "/test_notebook_parser.py", "repo_name": "rodelrod/pomodoro-report", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport unittest\nfrom notebook_parser import *\nimport os\nimport errno\nfrom datetime import datetime\n\n\ndef mkdir_p(path):\n try:\n os.makedirs(path)\n except OSError as exc: \n if exc.errno == errno.EEXIST:\n pass\n else: \n raise\n\n\nclass TestParser(unittest.TestCase):\n\n \"\"\"Tests the RedNotebook monthly files parser.\"\"\"\n\n def setUp(self):\n self.nb_path = '/tmp/test_pomodoro_report'\n mkdir_p(self.nb_path)\n f = open(os.path.join(self.nb_path, '2012-10.txt'), 'w')\n f.write(\n \"21: {text: '1/1 fix import sewan\\n\"\n \" 2/2 check fidelidade, delete 0836\\n\"\n \" 0/1 org desk'}\\n\"\n \"25:\\n\" \n \" Cat3: {Some other shit: null}\\n\"\n \" text: '1/1 fix import sewan\\n\"\n \" 2/2 check fidelidade, delete 0836\\n\"\n \" 0/1 org desk'\\n\"\n \"27:\\n\" \n \" Cat1: {Some shit: null}\\n\"\n \" text: '1/1 fix import sewan\\n\"\n \" 2/2 check fidelidade, delete 0836\\n\"\n \" 0/1 report incongruencias sewan pdf/cdr\\n\"\n \" 1/1 fix b''illing db and run\\n\"\n \" 0/2 guide entretien prestataire\\n\"\n \" 0/1 org desk'\\n\")\n f.close()\n self.p = Parser(self.nb_path)\n\n def test_get_nb_filename(self):\n self.assertEqual(\n self.p._get_nb_filename(datetime(2012, 10, 14)),\n os.path.join(self.nb_path,'2012-10.txt'))\n\n def test_parse_day_block(self):\n block = ['', '5', 'some stuff', '26', 'some other stuff']\n expected = {5: 'some stuff', 26: 'some other stuff'}\n self.assertEqual(self.p._parse_day_block(block), expected)\n\n def test_get_day_with_categories(self):\n \"\"\"Get day 27.\"\"\"\n expected = (\n \"\\n\"\n \" Cat1: {Some shit: null}\\n\"\n \" text: '1/1 fix import sewan\\n\"\n \" 2/2 check fidelidade, delete 0836\\n\"\n \" 0/1 report incongruencias sewan pdf/cdr\\n\"\n \" 1/1 fix b''illing db and run\\n\"\n \" 0/2 guide entretien prestataire\\n\"\n \" 0/1 org desk'\\n\")\n actual = self.p._get_day(datetime(2012, 10, 27))\n self.assertEqual(actual, expected)\n\n def test_get_day_without_categories(self):\n \"\"\"Get day 21.\"\"\"\n expected = (\n \" {text: '1/1 fix import sewan\\n\"\n \" 2/2 check fidelidade, delete 0836\\n\"\n \" 0/1 org desk'}\\n\")\n actual = self.p._get_day(datetime(2012, 10, 21))\n self.assertEqual(actual, expected)\n\n def test_get_inexistant_day(self):\n \"\"\"Get 14/10.\"\"\"\n with self.assertRaises(EmptyDayException):\n self.p._get_day(datetime(2012, 10, 14))\n\n def test_get_inexistant_month(self):\n \"\"\"Get 14/04.\"\"\"\n with self.assertRaises(EmptyDayException):\n self.p._get_day(datetime(2012, 4, 14))\n\n def test_get_text_with_categories(self):\n block = (\n \"\\n\"\n \" Cat1: {Some shit: null}\\n\"\n \" text: '1/1 fix import sewan\\n\"\n \" 2/2 check fidelidade, delete 0836\\n\"\n \" 0/1 report incongruencias sewan pdf/cdr\\n\"\n \" 1/1 fix b''illing db and run\\n\"\n \" 0/2 guide entretien prestataire\\n\"\n \" 0/1 org desk'\\n\")\n expected = (\n \"1/1 fix import sewan\\n\"\n \" 2/2 check fidelidade, delete 0836\\n\"\n \" 0/1 report incongruencias sewan pdf/cdr\\n\"\n \" 1/1 fix b'illing db and run\\n\"\n \" 0/2 guide entretien prestataire\\n\"\n \" 0/1 org desk\")\n self.assertEqual(self.p._get_text(block), expected)\n\n def test_get_text_without_categories(self):\n block = (\n \" {text: '1/1 fix import sewan\\n\"\n \" 2/2 check fidelidade, delete 0836\\n\"\n \" 0/1 org desk'}\\n\")\n expected = (\n \"1/1 fix import sewan\\n\"\n \" 2/2 check fidelidade, delete 0836\\n\"\n \" 0/1 org desk\")\n self.assertEqual(self.p._get_text(block), expected)\n\n def test_get_pomodoros(self):\n # TODO\n pass\n\n def tearDown(self):\n os.remove(os.path.join(self.nb_path, '2012-10.txt'))\n\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.5254838466644287, "alphanum_fraction": 0.5258064270019531, "avg_line_length": 31.957447052001953, "blob_id": "12e0129bb30d0bdc9f662418cb765328a0231657", "content_id": "127f1f6d721f6ff8765764e914c92330e7ae9a53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3100, "license_type": "no_license", "max_line_length": 80, "num_lines": 94, "path": "/notebook_parser.py", "repo_name": "rodelrod/pomodoro-report", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport re\nimport os\n\nNOTEBOOK_PATH = '/home/rrodrigues/.rednotebook/data'\n\nclass EmptyDayException(Exception):\n \"\"\"No info was entered for this date.\"\"\"\n \nclass Parser(object):\n\n \"\"\"Parses RedNotebook monthly files.\n \n This is a very basic parser used to extract Pomodoro references for each\n day. It has the following limitations:\n \n - Basically assumes there is nothing but the Pomodoro references in the\n day's text.\n - Ignores any Tags. \n - Ignores any Categories. \n - In the fancy cases where the text field ends up surrounded by double\n quotes instead of single quotes, it breaks.\n \n \"\"\"\n\n def __init__(self, nb_path=NOTEBOOK_PATH):\n self.nb_path = nb_path\n\n def _get_nb_filename(self, date):\n return os.path.join(self.nb_path, date.strftime('%Y-%m.txt'))\n\n @staticmethod\n def _parse_day_block(day_block_list):\n day_blocks = {}\n is_content = False\n for index, token in enumerate(day_block_list):\n if token.isdigit() and not is_content:\n day = int(token)\n is_content = True\n elif is_content:\n day_blocks[day] = token\n is_content = False\n else:\n pass\n return day_blocks\n\n def _get_day(self, date):\n day_filename = self._get_nb_filename(date)\n if not os.path.isfile(day_filename):\n raise EmptyDayException\n with open(day_filename, 'r') as nb_file:\n file_contents = nb_file.read()\n day_blocks_list = re.split('^(\\d+):', file_contents, flags=re.MULTILINE)\n day_blocks = self._parse_day_block(day_blocks_list)\n try:\n return day_blocks[date.day]\n except KeyError:\n raise EmptyDayException\n\n def _get_text(self, block):\n after_text = re.split('\\Wtext:', block)[1]\n quote_set = False\n started_text = False\n ended_text = False\n text = [] \n for token in after_text:\n if token == \"'\":\n if not started_text:\n #first quote, text starts\n started_text = True\n elif quote_set and started_text:\n #second quote\n text.append(\"'\")\n quote_set = False\n elif not quote_set and started_text:\n # quote in the middle of text, maybe the end or first of an\n # escape sequence\n quote_set = True\n else:\n if quote_set:\n # First character after a quote is not a quote, so this\n # must be the end\n break\n elif started_text:\n # Normal text, add it to the output\n text.append(token)\n else:\n # Text hasn't started yet, discard token\n continue\n return ''.join(text)\n\n def get_pomodoros(self):\n # TODO\n pass\n\n\n" }, { "alpha_fraction": 0.7780268788337708, "alphanum_fraction": 0.7802690863609314, "avg_line_length": 51.411766052246094, "blob_id": "05caa695295a12b184dd96949d95b447cb8e9867", "content_id": "d126114a67818b4688a9787b1d147ff0b0f5c104", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 892, "license_type": "no_license", "max_line_length": 80, "num_lines": 17, "path": "/README.md", "repo_name": "rodelrod/pomodoro-report", "src_encoding": "UTF-8", "text": "pomodoro-report\n===============\n\nThe Pomodoro Technique (http://www.pomodorotechnique.com/) it's a focus\ntechnique to help you get stuff done. Not getting into any details, you split\nyour work time in 25-minute sections separated by breaks. Each session is\ndevoted to a single objective, which must be defined clearly and explicitely. No\ndistractions or interruptions are allowed. Any semblance of interference must be\nleft to deal with in the next break. \n\nThis application allows us to keep track of the pomodoro session we have done\nduring each day. For this we use the RedNotebook, a note taking application\nwhich applies the concept of one note per day. The data for this application is\nstored in text files, one per month, contained in ~/.rednotebook/data. \n\nWe are going to read and parse this data and export it to a Google Spreadsheet,\nwhere we can sort and graph our data at will.\n\n" } ]
3
shashi/phosphene
https://github.com/shashi/phosphene
57dbc50ee5e70c3e375103804e7ae50659fc725f
6185aa2b0834eb8309767c86b751f5f28e80fe43
7343af90070744159158c430a6d69829bd8bf5d6
refs/heads/master
2016-09-05T14:20:21.752586
2013-12-07T16:16:35
2013-12-07T16:31:43
13,498,326
5
1
null
2013-10-11T12:26:05
2013-10-13T04:47:53
2013-10-13T04:47:53
Python
[ { "alpha_fraction": 0.6467857360839844, "alphanum_fraction": 0.6642857193946838, "avg_line_length": 23.34782600402832, "blob_id": "c80a487ae704daf4c4397f8dcd64b5140c142433", "content_id": "f6dbeb6dbde458bcfa495694bbba5898db87ec7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2800, "license_type": "no_license", "max_line_length": 77, "num_lines": 115, "path": "/src/apps/psychroom.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "#\n# This script plays an mp3 file and communicates via serial.Serial\n# with devices in the Technites psychedelic room to visualize the\n# music on them.\n#\n# It talks to 4 devices\n# WaterFall -- tubes with LEDs and flying stuff fanned to music\n# DiscoBall -- 8 60 watt bulbs wrapped in colored paper\n# LEDWall -- a 4 channel strip of LED\n# this time it was the LED roof instead :p\n# LEDCube -- a 10x10x10 LED cube - work on this is still on\n#\n# the script also has a sloppy pygame visualization of the fft and\n# beats data\n#\n\nimport sys\nimport time\nimport scipy\nimport pygame\nfrom pygame import display\nfrom pygame.draw import *\n\nimport pathsetup # this module sets up PYTHONPATH for all this to work\n\nfrom devices.discoball import DiscoBall\nfrom devices.waterfall import Waterfall\nfrom devices.ledwall import LEDWall\nfrom devices.cube import Cube\n\nimport phosphene\nfrom phosphene import audio, signalutil, util\nfrom phosphene.util import *\nfrom phosphene.signal import *\nfrom phosphene.dsp import *\nfrom phosphene.graphs import *\nfrom phosphene.signalutil import *\nfrom cube import cubeProcess\n\n#from phosphene import cube\nfrom threading import Thread\n\n\n# Setup devices with their corresponding device files\ndevs = [\n Waterfall(\"/dev/ttyACM0\"),\n DiscoBall(\"/dev/ttyACM1\"),\n LEDWall(\"/dev/ttyACM2\")\n ]\n\npygame.init()\nsurface = display.set_mode((640, 480))\n\nif len(sys.argv) < 2:\n print \"Usage: %s file.mp3\" % sys.argv[0]\n sys.exit(1)\nelse:\n fPath = sys.argv[1]\n\nsF, data = audio.read(fPath)\n\nimport serial\n\nsignal = Signal(data, sF)\n\nsignal.A = lift((data[:,0] + data[:,1]) / 2, True)\n\n\n\nfor d in devs:\n d.setupSignal(signal)\n\ndef devices(s):\n #threads = []\n for d in devs:\n if d.isConnected:\n def f():\n d.redraw(s)\n d.readAck()\n #t = Thread(target=f)\n #threads.append(t)\n #t.start()\n f()\n\n #for t in threads:\n # t.join(timeout=2)\n # if t.isAlive():\n # d.isUnresponsive()\n\n surface.fill((0, 0, 0))\n graphsGraphs(filter(\n lambda g: g is not None,\n [d.graphOutput(signal) for d in devs]))(surface, (0, 0, 640, 480))\n\nCubeState = lambda: 0\nCubeState.count = 0\n\n#cube = Cube(\"/dev/ttyACM1\", emulator=True)\ndef cubeUpdate(signal):\n CubeState.count = cubeProcess(cube, signal, CubeState.count)\n\ndef graphsProcess(s):\n display.update()\n\nprocesses = [graphsProcess, devices] #, cube.emulator]\n\nsignal.relthresh = 1.66\n\nsoundObj = audio.makeSound(sF, data)\n # make a pygame Sound object from the data\n\n# run setup on the signal\nsignalutil.setup(signal)\nsoundObj.play() # start playing it. This is non-blocking\nperceive(processes, signal, 90) # perceive your signal.\n" }, { "alpha_fraction": 0.5066215991973877, "alphanum_fraction": 0.5255001187324524, "avg_line_length": 30.972972869873047, "blob_id": "4304b2bff0be509a03fd100ef29b668d20475152", "content_id": "631ccc08d4d784a605e2d0dc0a64154fa4f1ae77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3549, "license_type": "no_license", "max_line_length": 74, "num_lines": 111, "path": "/src/phosphene/signalutil.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "# Functions to help you lift and fold\nfrom .signal import *\nfrom dsp import *\nimport numpy\nimport pdb\nimport math\n\ndef setup(signal, horizon=576):\n # Note of awesome: this only sets up dependencies,\n # things absolutely necessary are evaluated.\n\n signal.fft = lift(lambda s: \\\n fft(s.A[-horizon/2:horizon/2], False, True, True))\n\n for i in [1, 3, 4, 5, 6, 8, 12, 16, 32]:\n setup_bands(signal, i)\n\ndef setup_bands(signal, bands):\n\n def get(s, prefix):\n return getattr(s, prefix + str(bands))\n\n setattr(signal, 'chan%d' % bands,\n lift(lambda s: group(bands, s.fft)))\n\n setattr(signal, 'avg%d' % bands,\n blend(lambda s: get(s, 'chan'),\n lambda s, v, avg: 0.2 if v > avg else 0.5))\n\n setattr(signal, 'longavg%d' % bands,\n blend(lambda s: get(s, 'chan'),\n lambda s, v, avg: 0.9 if s.frames < 50 else 0.992))\n # Booya.\n thresh = 1.7\n setattr(signal, 'peaks%d' % bands,\n blend(lambda s: get(s, 'avg') > thresh * get(s, 'longavg'),\n lambda s, v, a: 0.2))\n\n setattr(signal, 'chan%drel' % bands,\n lift(lambda s: numpymap(\n lambda (x, y): x / y if y > 0.001 else 1,\n zip(get(s, 'chan'), get(s, 'longavg')))))\n\n setattr(signal, 'avg%drel' % bands,\n lift(lambda s: numpymap(\n lambda (x, y): x / y if y > 0.001 else 1,\n zip(get(s, 'avg'), get(s, 'longavg')))))\n ## Detecting beats\n\ndef normalize(data, signal, divisor=None):\n if divisor is None: divisor = lambda s, n: getattr(s, 'longavg%d' % n)\n n = len(data)\n divs = divisor(signal, n)\n return numpymap(lambda (a, b): a / max(0.01, b), zip(data, divs))\n\ndef fallingMax(f, minf=lambda s: 0.5, cutoff=0.95, gravity=lambda s: 0.9):\n def maxer(signal, prev):\n # prev contains:\n thisFrame = f(signal)\n\n if prev == None:\n init = (thisFrame, [signal.t] * len(thisFrame))\n return (init, init)\n\n maxVal, maxTime = prev\n mins = minf(signal)\n try:\n s = sum(mins)\n except:\n s = mins\n\n for i in range(0, len(thisFrame)):\n if thisFrame[i] > cutoff * maxVal[i] and s != 0:\n # Update\n maxVal[i] = thisFrame[i]\n maxTime[i] = signal.t\n else:\n # Fall\n maxVal[i] -= gravity(signal) * (signal.t - maxTime[i])\n return ((maxVal, maxTime), (maxVal, maxTime))\n return foldp(maxer, None)\n\ndef boopValue(t2, maxes):\n maxVal, maxTime = maxes\n return numpy.array([math.exp(-(t2 - t1) * 9) for t1 in maxTime])\n\ndef blend(f, rate=lambda s, val, avg: 0.3):\n def blender(signal, avg):\n vals = f(signal)\n l = len(vals)\n\n # None is the starting value\n if avg is None: avg = [0] * l\n\n for i in range(0, l):\n if isinstance(rate, float):\n r = rate\n elif hasattr(rate, '__call__'):\n r = rate(signal, vals[i], avg[i])\n else:\n ValueError(\"rate of decay must be a float or a lambda\")\n r = adjustRate(r, signal) # adjust based on fps\n avg[i] = avg[i] * r + vals[i] * (1-r)\n avg = numpy.array(avg)\n return (avg, avg) # required by foldp\n return foldp(blender, None)\n\ndef adjustRate(r, signal):\n # THANKS MILKDROP! FOR EVERYTHING!\n pow = math.pow\n return pow(pow(r, signal.max_fps), 1.0/signal.fps)\n" }, { "alpha_fraction": 0.6059259176254272, "alphanum_fraction": 0.6118518710136414, "avg_line_length": 28.34782600402832, "blob_id": "b16a5a30728234e7590d901baffe2946c6108923", "content_id": "2026580acea0728690cc83b266fb717b8ddcc555", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 675, "license_type": "no_license", "max_line_length": 71, "num_lines": 23, "path": "/src/setup.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "import os\nfrom setuptools import setup\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetup(\n name = \"phosphene\",\n version = \"0.0.1\",\n author = \"Shashi Gowda\",\n author_email = \"[email protected]\",\n description = (\"A library for music processing and visualization\"),\n license = \"MIT\",\n keywords = \"music audio dsp visualization\",\n url = \"https://github.com/shashi/phosphene\",\n packages=[\"phosphene\"],\n long_description=read(\"../README.md\"),\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Topic :: Multimedia :: Sound/Audio :: Analysis\",\n \"License :: OSI Approved :: MIT License\",\n ],\n)\n" }, { "alpha_fraction": 0.5007839202880859, "alphanum_fraction": 0.530573844909668, "avg_line_length": 27.21238899230957, "blob_id": "63ca0c494a6df7fa339e43e703ce02d173eeaf82", "content_id": "8538a1d4a467fd31f78a4478a50d6b908dcb8b13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3189, "license_type": "no_license", "max_line_length": 66, "num_lines": 113, "path": "/src/apps/devices/cube.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "import serial\nimport numpy\nimport math\nfrom device import Device\nfrom cubelib import emulator\nfrom cubelib import mywireframe as wireframe\nfrom animations import *\nimport time\nimport threading\n\n# A class for the cube\nclass Cube(Device):\n def __init__(self, port, dimension=10, emulator=False):\n Device.__init__(self, \"Cube\", port)\n self.array = numpy.array([[\\\n [0]*dimension]*dimension]*dimension, dtype='bool')\n self.dimension = dimension\n self.emulator = emulator\n self.name = \"Cube\"\n\n def set_led(self, x, y, z, level=1):\n self.array[x][y][z] = level\n\n def get_led(self, x, y, z):\n return self.array[x][y][z]\n\n def takeSignal(self, signal):\n pass\n\n def toByteStream(self):\n # 104 bits per layer, first 4 bits waste.\n \n bytesPerLayer = int(math.ceil(self.dimension**2 / 8.0))\n print bytesPerLayer\n discardBits = bytesPerLayer * 8 - self.dimension**2\n print discardBits\n bts = bytearray(bytesPerLayer*self.dimension)\n\n pos = 0\n mod = 0\n\n for layer in self.array:\n mod = discardBits\n for row in layer:\n for bit in row:\n if bit: bts[pos] |= 1 << mod\n else: bts[pos] &= ~(1 << mod)\n\n mod += 1\n\n if mod == 8:\n mod = 0\n pos += 1\n return bts\n\n def redraw(self, wf=None, pv=None):\n if self.emulator:\n wf.setVisible(emulator.findIndexArray(self.array))\n pv.run()\n\nif __name__ == \"__main__\":\n cube = Cube(\"/dev/ttyACM0\")\n #pv = emulator.ProjectionViewer(640,480)\n #wf = wireframe.Wireframe()\n #pv.createCube(wf)\n count = 0\n start = (0, 0, 0)\n point = (0,0)\n #fillCube(cube,0)\n #cube.redraw()\n #time.sleep(100)\n def sendingThread():\n while True:\n cube.port.write(\"S\")\n bs = cube.toByteStream()\n for i in range(0, 130):\n time.sleep(0.01)\n cube.port.write(chr(bs[i]))\n print \"wrote\", bs[i]\n assert(cube.port.read() == '.')\n\n t = threading.Thread(target=sendingThread)\n t.start()\n #fillCube(cube,0)\n #cube.set_led(9,9,9)\n #for x in range(0, 9):\n # for y in range(0, 9):\n # for z in range(0, 9):\n # cube.set_led(x, y, z, 1)\n # time.sleep(1)\n while True:\n #wireframeCube(cube,(1,1,1),(9,9,9))\n fillCube(cube, 1)\n #planeBounce(cube,(count/20)%2+1,count%20)\n #planeBounce(cube,1,count)\n #start = wireframeExpandContract(cube,start)\n #rain(cube,count,5,10)\n\t #time.sleep(.1)\n #point = voxel(cube,count,point)\n\t #sine_wave(cube,count)\n\t #pyramids(cube,count)\n\t #side_waves(cube,count)\n\t #fireworks(cube,4)\n #technites(cube, count)\n #setPlane(cube,1,(counter/100)%10,1)\n #setPlane(cube,2,0,1)\n\t #stringPrint(cube,'TECHNITES',count)\n #moveFaces(cube)\n #cube.set_led(0,0,0)\n #cube.set_led(0,0,1)\n cube.redraw()\n count += 1\n time.sleep(0.1)\n\n" }, { "alpha_fraction": 0.525540292263031, "alphanum_fraction": 0.5564833283424377, "avg_line_length": 26.14666748046875, "blob_id": "b663f2b22b461d51b3e2dc5675b235d514a39d2b", "content_id": "9e2d1b4c43981844ceed1a5e555b0b97bb7345b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2036, "license_type": "no_license", "max_line_length": 81, "num_lines": 75, "path": "/src/phosphene/dsp.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "import scipy\nimport numpy\nfrom util import *\n\ndef fftIdx(Fs, Hz, n):\n assert(Hz <= Fs / 2);\n return round(Fs / n * Hz)\n\nmemFftIdx = memoize(fftIdx)\n\ndef getNotes():\n return [0] \\\n + [16.35 * pow(2, i/12.0) + 1 for i in range(0, 101)] \\\n + [11050, 22100]\n\ndef group(n, fft, grouping=lambda i: i):\n \"\"\"\n Put fft data into n bins by adding them.\n\n grouping function defines how things are grouped\n lambda i: i --> linear grouping\n lambda i: 2 ** i --> logarithmic\n \"\"\"\n\n if isinstance(n, (list,tuple)):\n splitPoints = numpy.array(n, dtype=float)\n n = len(n) - 1\n elif hasattr(grouping, '__call__'):\n splitPoints = numpy.array([grouping(i) for i in range(0, n + 1)], \\\n dtype=float)\n l = len(fft)\n\n splitIdx = splitPoints / abs(max(splitPoints)) * l\n splitIdx = [int(i) for i in splitIdx]\n #pdb.set_trace()\n\n return numpy.array(\n [sum(fft[splitIdx[i-1]:splitIdx[i]]) for i in range(1, n + 1)])\n\ndef fft(samples, out_n, env=None, eq=None):\n \"\"\"\n Returns the short time FFT at i,\n window width will be 1.5 * delta\n 1 * delta after i and 0.5 * delta before\n \"\"\"\n\n in_n = len(samples)\n if env:\n spectrum = abs(scipy.fft(samples * scipy.hamming(in_n) * envelope(in_n)))\n else:\n spectrum = abs(scipy.fft(samples))\n\n if out_n:\n if eq:\n return group(out_n, spectrum[0:0.9*in_n/2]) * equalize(out_n)\n else:\n return group(out_n, spectrum[0:0.9*in_n/2])\n else:\n if eq:\n return spectrum[0:in_n/2] * equalize(in_n/2)\n else:\n return spectrum[0:in_n/2]\n\ndef equalize(N, scale=-0.02):\n f = lambda i: scale * scipy.log((N-i) * 1.0/N)\n return numpymap(f, range(0, N))\n\nequalize=memoize(equalize)\n\ndef envelope(N, power=1):\n mult = scipy.pi / N\n f = lambda i: pow(0.5 + 0.5 * scipy.sin(i*mult - scipy.pi / 2), power)\n return numpymap(f, range(0, N))\n\nenvelope=memoize(envelope)\n" }, { "alpha_fraction": 0.6336065530776978, "alphanum_fraction": 0.6540983319282532, "avg_line_length": 26.704545974731445, "blob_id": "e2ebc2690c1fdfda871f2e96851d076d67977486", "content_id": "9dc1f878c9b0fee02c0f5c4660ae826702cc1a93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1220, "license_type": "no_license", "max_line_length": 77, "num_lines": 44, "path": "/src/phosphene/audio.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "import os\nfrom hashlib import sha1\nimport scipy.io.wavfile as wav\nimport pygame.mixer\nfrom pygame.sndarray import make_sound\n\n# Set mixer defaults\npygame.mixer.pre_init(44100, 16, 2, 4096)\n\n__all__ = [\"read\", \"makeSound\"]\n\ndef digest(string):\n return sha1(string).hexdigest()\n\ndef read(fname):\n \"\"\" Reads an audio file into a numpy array.\n\n returns frequency, samples\n \"\"\"\n # this is an ugly way to read mp3. But works well.\n # www.snip2code.com/Snippet/1767/Convert-mp3-to-numpy-array--Ugly--but-it\n suffix = digest(fname)[0:6]\n oname = '/tmp/tmp'+ suffix +'.wav'\n\n # ask lame to decode it to a wav file\n if not os.path.exists(oname):\n # Well, if you ctrl-c before conversion, you're going to\n # have to manually delete the file.\n cmd = 'lame --decode \"%s\" \"%s\"' % (fname, oname)\n os.system(cmd)\n\n # now read using scipy.io.wavfile\n data = wav.read(oname)\n # return samplingFrequency, samples\n return data[0], data[1]\n\ndef makeSound(samplingFreq, data):\n \"\"\" Make a Player object from raw data\n\n returns a pygame.mixer.Sound object\n \"\"\"\n # Ugh! impurity\n pygame.mixer.init(frequency=samplingFreq)\n return make_sound(data)\n\n" }, { "alpha_fraction": 0.44009584188461304, "alphanum_fraction": 0.4932108521461487, "avg_line_length": 26.765121459960938, "blob_id": "ef216cd26d25bf73fd81294b8966afb82b175fc7", "content_id": "b92ec318048ddd47bf350e2f811d75d3d56a236e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27544, "license_type": "no_license", "max_line_length": 138, "num_lines": 992, "path": "/src/apps/devices/animations.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "import numpy\nimport random\nimport time\n\nfrom cubelib import mywireframe\nfrom cubelib import emulator\n\n# TODO:\n# shiftPlane(axis, plane, delta)\n# moves the plane along the axis by delta steps, if it exceeds dimensions, just clear it out, don't rotate.\n# swapPlanes(axis1, plane1, axis2, plane2)\n# rain should set random LEDs on the first plane (not a lot of them)\n# and shift the plane along that axis by one step---Fixed\n# and shift the plane along that axis by one step\n#\n# THINK:\n# The python code keeps sending a 125 byte string to redraw the\n# cube as often as it can, this contains 1000 bit values that the MSP\n# handles. Now, in our code we have been using time.sleep() a lot.\n# We probably can have a counter that each of these functions uses to\n# advance its steps, and then increment / decrement that\n# counter according to music\n\ndef wireframeCubeCenter(cube,size):\n if size % 2 == 1:\n size = size+1\n\n half = size/2\n start = cube.dimension/2 - half\n end = cube.dimension/2 + half - 1\n\n for x in range(0,cube.dimension):\n for y in range(0,cube.dimension):\n for z in range(0,cube.dimension):\n cube.set_led(x,y,z,0)\n\n for x in (start,end):\n for y in (start,end):\n for z in range(start,end+1):\n cube.set_led(x,y,z)\n cube.set_led(x,z,y)\n cube.set_led(z,x,y)\n\ndef wireframeCube(cube,START,END):\n x0,y0,z0 = START\n x1,y1,z1 = END\n print \"start:\",START,\"end:\",END\n for x in range(0,cube.dimension):\n for y in range(0,cube.dimension):\n for z in range(0,cube.dimension):\n cube.set_led(x,y,z,0)\n for x in (x0,x1):\n for y in (y0,y1):\n if z0<z1:\n for z in range(z0,z1+1):\n cube.set_led(x,y,z)\n\t\t print x,y,z, \"set-1st condition\"\n else:\n for z in range(z1,z0+1):\n cube.set_led(x,y,z)\n\t\t print x,y,z, \"set-2nd condition\"\n for x in (x0,x1):\n for z in (z0,z1):\n if y0<y1:\n for y in range(y0,y1+1):\n cube.set_led(x,y,z)\n\t\t print x,y,z, \"Set - 1st\"\n else:\n for y in range(y1,y0+1):\n cube.set_led(x,y,z)\n\t\t print x,y,z, \"Set - 2nd\"\n\n for y in (y0,y1):\n for z in (z0,z1):\n if x0<x1:\n for x in range(x0,x1+1):\n cube.set_led(x,y,z)\n\t\t print x,y,z, \"SET - 1st\"\n else:\n for x in range(x1,x0+1):\n cube.set_led(x,y,z)\n print x,y,z, \"SET - 2nd\"\n\ndef solidCubeCenter(cube,size):\n if size % 2 == 1:\n size = size+1\n\n half = size/2 \n start = cube.dimension/2 - half\n end = cube.dimension/2 + half\n\n for x in range(0,cube.dimension):\n for y in range(0,cube.dimension):\n for z in range(0,cube.dimension):\n cube.set_led(x,y,z,0)\n\n for i in range(start,end):\n for j in range(start,end):\n for k in range(start,end):\n cube.set_led(i,j,k)\n\ndef solidCube(cube,START,END):\n x0,y0,z0 = START\n x1,y1,z1 = END\n\n for x in range(0,cube.dimension):\n for y in range(0,cube.dimension):\n for z in range(0,cube.dimension):\n cube.set_led(x,y,z,0)\n\n for i in range(x0,x1+1):\n for j in range(y0,y1+1):\n for k in range(z0,z1+1):\n cube.set_led(i,j,k)\n\ndef setPlane(cube,axis,x,level = 1):\n plane = level\n if isinstance(level, int):\n plane = numpy.array([[level]*10]*10, dtype=bool)\n\n if axis == 1:\n for i in range(0,cube.dimension):\n for j in range(0,cube.dimension):\n cube.set_led(x,i,j,plane[i][j])\n elif axis == 2:\n for i in range(0,cube.dimension):\n for j in range(0,cube.dimension):\n cube.set_led(i,x,j,plane[i][j])\n else:\n for i in range(0,cube.dimension):\n for j in range(0,cube.dimension):\n cube.set_led(i,j,x,plane[i][j])\n\ndef shiftPlane(cube,axis,plane,delta):\n if axis == 1:\n for i in range(0,cube.dimension):\n\t for j in range(0,cube.dimension):\n\t\t\ttry:\n\t\t\t cube.set_led(plane+delta,i,j,cube.get_led(plane,i,j))\n cube.set_led(plane,i,j,0)\n\t\t\texcept:\n\t\t\t cube.set_led(plane,i,j,0)\n elif axis == 2:\n for i in range(0,cube.dimension):\n\t for j in range(0,cube.dimension):\n\t\ttry:\n\t\t cube.set_led(i,plane+delta,j,cube.get_led(i,plane,j))\n cube.set_led(i,plane,j,0)\n\t\texcept: \n\t\t cube.set_led(i,plane,j,0)\n else:\n for i in range(0,cube.dimension):\n for j in range(0,cube.dimension):\n\t\ttry:\n\t cube.set_led(i,j,plane+delta,cube.get_led(i,j,plane))\n cube.set_led(i,j,plane,0)\n except:\n\t\t cube.set_led(i,j,plane,0)\n#def swapPlane(cube,axis,plane1,plane2):\n\ndef randPlane(cube,minimum,maximum):\n array = numpy.array([[0]*cube.dimension]*cube.dimension,dtype = 'bool')\n for i in range(minimum,maximum):\n x = random.choice([i for i in range(0,cube.dimension)]) \n y = random.choice([i for i in range(0,cube.dimension)]) \n array[x][y] = 1\n return array\ndef wireframeExpandContract(cube,start=(0,0,0)):\n (x0, y0, z0) = start\n\n for i in range(0,cube.dimension):\n j = cube.dimension - i - 1\n if(x0 == 0):\n if(y0 == 0 and z0 == 0):\n wireframeCube(cube,(x0,y0,z0),(x0+i,y0+i,z0+i))\n elif(y0 == 0):\n wireframeCube(cube,(x0,y0,z0),(x0+i,y0+i,z0-i))\n elif(z0 == 0):\n wireframeCube(cube,(x0,y0,z0),(x0+i,y0-i,z0+i))\n else:\n wireframeCube(cube,(x0,y0,z0),(x0+i,y0-i,z0-i))\n else:\n if(y0 == 0 and z0 == 0):\n wireframeCube(cube,(x0,y0,z0),(x0-i,y0+i,z0+i))\n elif(y0 == 0):\n wireframeCube(cube,(x0,y0,z0),(x0-i,y0+i,z0-i))\n elif(z0 == 0):\n wireframeCube(cube,(x0,y0,z0),(x0-i,y0-i,z0+i))\n else:\n wireframeCube(cube,(x0,y0,z0),(x0-i,y0-i,z0-i))\n time.sleep(0.1)\n\tcube.redraw() \n\n max_coord = cube.dimension - 1\n corners = [0,max_coord]\n x0 = random.choice(corners)\n y0 = random.choice(corners)\n z0 = random.choice(corners)\n for j in range(0,cube.dimension):\n i = cube.dimension - j - 1\n if(x0 == 0):\n if(y0 == 0 and z0 == 0):\n wireframeCube(cube,(x0,y0,z0),(x0+i,y0+i,z0+i))\n elif(y0 == 0):\n wireframeCube(cube,(x0,y0,z0),(x0+i,y0+i,z0-i))\n elif(z0 == 0):\n wireframeCube(cube,(x0,y0,z0),(x0+i,y0-i,z0+i))\n else:\n wireframeCube(cube,(x0,y0,z0),(x0+i,y0-i,z0-i))\n else:\n if(y0 == 0 and z0 == 0):\n wireframeCube(cube,(x0,y0,z0),(x0-i,y0+i,z0+i))\n elif(y0 == 0):\n wireframeCube(cube,(x0,y0,z0),(x0-i,y0+i,z0-i))\n elif(z0 == 0):\n wireframeCube(cube,(x0,y0,z0),(x0-i,y0-i,z0+i))\n else:\n wireframeCube(cube,(x0,y0,z0),(x0-i,y0-i,z0-i)) \n cube.redraw()\n\ttime.sleep(0.1)\n return (x0, y0, z0) # return the final coordinate\n\ndef rain(cube,counter,minimum,maximum,axis=3):\n shiftCube(cube,3,1)\n setPlane(cube,axis,9,randPlane(cube,minimum,maximum))\n\n\n \ndef planeBounce(cube,axis,counter):\n\n i = counter%20\n if i:\n if i<10: #to turn off the previous plane\n setPlane(cube,axis,i-1,0)\n elif i>10:\n setPlane(cube,axis,20-i,0)\n if i<10:\n setPlane(cube,axis,i)\n elif i>10:\n setPlane(cube,axis,19-i)\n \ndef square(cube,size,translate=(0,0)):\n x0,y0 = translate\n array = numpy.array([[0]*cube.dimension] * cube.dimension)\n for i in range(0,size):\n\t for j in range(0,size):\n\t array[i+x0][j+y0] = 1\n return array\n\ndef distance(point1,point2):\n x0,y0 = point1\n x1,y1 = point2\n return numpy.sqrt((x0-x1)**2 + (y0-y1)**2)\n\ndef circle(cube,radius,translate=(0,0)):\n x1,y1 = translate\n array = numpy.array([[0]*cube.dimension] * cube.dimension)\n for i in range(0,2*radius):\n for j in range(0,2*radius):\n\t if distance((i,j),(radius,radius))<=radius:\n\t\tarray[i+x1][j+y1] = 1\n return array\n\ndef wierdshape(cube,diagonal,translate=(0,0)):\n x1,y1 = translate\n array = numpy.array([[0]*cube.dimension] * cube.dimension)\n if diagonal%2 == 0:\n\t\tdiagonal-=1\n for y in range(0,diagonal):\n\t\tfor x in range(0,diagonal):\n\t\t\tif(y>=diagonal/2):\n\t\t\t\tif(x<=diagonal/2):\n\t\t\t\t\tif(x>=y):\n\t\t\t\t\t\tarray[x][y] = 1\n\t\t\t\telse:\n\t\t\t\t\tif(x<=y):\n\t\t\t\t\t\tarray[x][y] = 1\n\t\t\telse:\n\t\t\t\tif(x<=diagonal/2):\n\t\t\t\t\tif(x+y>=diagonal/2):\n\t\t\t\t\t\tarray[x][y] = 1\n\t\t\t\telse:\n\t\t\t\t\tif(x+y<=diagonal/2):\n\t\t\t\t\t\tarray[x][y] = 1\t\t\n return array\ndef fillCube(cube,level=1):\n for x in range(0,cube.dimension):\n\t for y in range(0,cube.dimension):\n\t for z in range(0,cube.dimension):\n\t\t cube.set_led(x,y,z,level)\n \ndef voxel(cube,counter,point):\n x,y = point\n if(counter==0):\n fillCube(cube,0)\n\t for x in range(0,cube.dimension):\n for y in range(0,cube.dimension):\n \t cube.set_led(x,y,random.choice([0,cube.dimension-1])) \n if counter%9==0:\n x = random.choice([i for i in range(0,cube.dimension)])\n y = random.choice([i for i in range(0,cube.dimension)])\n if cube.get_led(x,y,counter%9)==1:\n\t cube.set_led(x,y,counter%9+1)\n\t cube.set_led(x,y,counter%9,0)\n else:\n cube.set_led(x,y,8-(counter%9))\n cube.set_led(x,y,9-(counter%9),0)\n return (x,y)\n\ndef shiftCube(cube,axis,delta):\n \n for x in range(0,10):\n for y in range(0,10):\n for z in range(0,9):\n if axis == 3:\n cube.set_led(x,y,z,cube.get_led(x,y,z+delta))\n cube.set_led(x,y,z+delta,0)\n elif axis == 2:\n cube.set_led(x,z,y,cube.get_led(x,z+delta,y))\n cube.set_led(x,y,z+delta,0)\n elif axis == 1:\n cube.set_led(z,x,y,cube.get_led(z+delta,x,y))\n cube.set_led(z+delta,x,y,0)\n\n\ndef pyramids(cube,counter,axis = 3):\n if(counter%20 <cube.dimension):\n size = counter%10 + 1\n setPlane(cube,axis,cube.dimension-1,square(cube,counter%10 + 1,((cube.dimension-counter%10-1)/2,(cube.dimension-counter%10-1)/2)))\n shiftCube(cube,axis,1)\n else:\n\tsize = 9 - (counter-10)%10\n\ttranslate = (cube.dimension - size)/2\n setPlane(cube,axis,cube.dimension-1,square(cube,size,(translate,translate)))\n\tshiftCube(cube,axis,1)\n time.sleep(0)\n print \"counter = \",counter,\"size=\",size\n\ndef sine_wave(cube,counter):\n fillCube(cube,0)\n center = (cube.dimension-1)/2.0\n for x in range(0,cube.dimension):\n\tfor y in range(0,cube.dimension):\n dist = distance((x,y),(center,center))\n\t cube.set_led(x,y,int(counter%10+numpy.sin(dist+counter)))\n\ndef side_waves(cube,counter):\n fillCube(cube,0)\n origin_x=4.5;\n origin_y=4.5;\n for x in range(0,10):\n\tfor y in range(0,10):\n origin_x=numpy.sin(counter);\n origin_y=numpy.cos(counter);\n z=int(numpy.sin(numpy.sqrt(((x-origin_x)*(x-origin_x))+((y-origin_y)*(y-origin_y))))+counter%10);\n cube.set_led(x,y,z);\n\ndef fireworks(cube,n):\n origin_x = 3;\n origin_y = 3;\n origin_z = 3;\n #Particles and their position, x,y,z and their movement,dx, dy, dz\n origin_x = random.choice([i for i in range(0,4)])\n origin_y = random.choice([i for i in range(0,4)])\n origin_z = random.choice([i for i in range(0,4)])\n origin_z +=5;\n origin_x +=2;\n origin_y +=2;\n particles = [[None for _ in range(6)] for _ in range(n)]\n print particles\n #shoot a particle up in the air value was 600+500\n for e in range(0,origin_z):\n cube.set_led(origin_x,origin_y,e,1);\n\ttime.sleep(.05+.02*e);\n cube.redraw()\n\tfillCube(cube,0)\n for f in range(0,n):\n #Position\n particles[f][0] = origin_x\n\tparticles[f][1] = origin_y\n\tparticles[f][2] = origin_z\n\trand_x = random.choice([i for i in range(0,200)])\n\trand_y = random.choice([i for i in range(0,200)])\n\trand_z = random.choice([i for i in range(0,200)])\n\n\ttry:\n\t #Movement\n particles[f][3] = 1-rand_x/100.0 #dx\n particles[f][4] = 1-rand_y/100.0 #dy\n particles[f][5] = 1-rand_z/100.0 #dz\n\texcept:\n\t print \"f:\",f\n #explode\n for e in range(0,25):\n slowrate = 1+numpy.tan((e+0.1)/20)*10\n gravity = numpy.tan((e+0.1)/20)/2\n for f in range(0,n):\n particles[f][0] += particles[f][3]/slowrate\n particles[f][1] += particles[f][4]/slowrate\n particles[f][2] += particles[f][5]/slowrate;\n particles[f][2] -= gravity;\n cube.set_led(int(particles[f][0]),int(particles[f][1]),int(particles[f][2]))\n time.sleep(1000)\n\ndef T():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\n for j in range(0,3):\n\t plane[i][j] = 1\t\n for i in range(3,7):\n for j in range(3,10):\t \n plane[i][j] = 1\n return plane\n\ndef E():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\n for j in range(0,3):\n\t plane[i][j] = 1\t\n\tfor j in range(4,7):\n\t plane[i][j] = 1\n\tfor j in range(8,10):\n plane[i][j] = 1\n for i in range(0,3):\n for j in range(0,10):\t \n plane[i][j] = 1\n return plane\n\ndef B():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\n for j in range(0,2):\n\t plane[i][j] = 1\t\n\tfor j in range(4,6):\n\t plane[i][j] = 1\n\tfor j in range(8,10):\n plane[i][j] = 1\n for j in range(0,10):\n for i in range(0,3):\t \n plane[i][j] = 1\n\tfor i in range(7,10):\n\t plane[i][j] = 1\t \n plane[9][0] = 0\n plane[9][9] = 0\n return plane\n\ndef A():\n plane = numpy.array([[0]*10] *10) \n for i in range(0,10):\n for j in range(0,2):\n\t plane[i][j] = 1\t\n\tfor j in range(4,7):\n\t plane[i][j] = 1\n for j in range(0,10):\n for i in range(0,3):\t \n plane[i][j] = 1\n\tfor i in range(7,10):\n\t plane[i][j]\t= 1 \n return plane\n\ndef C():\n plane = numpy.array([[0]*10] *10) \n for i in range(0,10):\n for j in range(0,3):\n\t plane[i][j] = 1\t\n\tfor j in range(7,10):\n plane[i][j] = 1\n for i in range(0,3):\n for j in range(0,10):\t \n plane[i][j] = 1\n return plane\n\ndef D():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\n for j in range(0,2):\n\t plane[i][j] = 1\t\n\tfor j in range(8,10):\n plane[i][j] = 1\n for j in range(0,10):\n for i in range(0,2):\t \n plane[i][j] = 1\n\tfor i in range(8,10):\n plane[i][j] = 1\n plane[9][0] = 0\n plane[9][9] = 0 \n return plane\ndef F():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\n for j in range(0,3):\n\t plane[i][j] = 1\t\n\tfor j in range(4,7):\n\t plane[i][j] = 1\n for i in range(0,3):\n for j in range(0,10):\t \n plane[i][j] = 1\n return plane\n\ndef H():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\t\n\tfor j in range(4,7):\n\t plane[i][j] = 1\n for i in range(0,3):\n for j in range(0,10):\t \n plane[i][j] = 1\n for i in range(7,10):\n for j in range(0,10):\t \n plane[i][j] = 1\n return plane\n\ndef G():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\n for j in range(0,3):\n\t plane[i][j] = 1\t\n\tfor j in range(7,10):\n plane[i][j] = 1\n for i in range(0,3):\n for j in range(0,10):\t \n plane[i][j] = 1\n for i in range(7,10):\n for j in range(4,10):\n\t plane[i][j] = 1\n for i in range(4,10):\n for j in range(4,6):\n plane[i][j] = 1\n return plane\n\ndef J():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\n for j in range(0,3):\n\t plane[i][j] = 1\t\n for i in range(3,7):\n for j in range(3,10):\t \n plane[i][j] = 1\n for i in range(0,3):\n\tfor j in range(7,10):\n plane[i][j] = 1\n return plane\n\ndef K():\n plane = numpy.array([[0]*10]*10)\n for j in range(0,10):\n\tfor i in range(0,2):\n plane[i][j] = 1\n for i in range(0,10):\n\tfor j in range(0,10):\n\t if(i == j):\n\t plane[i][5+j/2] = 1\n try:\n plane[i-1][4+j/2] = 1\n plane[i+1][4+j/2] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n\t \n\t if(i+j==9):\n\t plane[i][j/2] = 1\n try:\n plane[i-1][j/2] = 1\n plane[i+1][j/2] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n plane[9][5] = 0\n plane[9][4] = 0\n return plane\n\ndef L():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\t\n\tfor j in range(7,10):\n plane[i][j] = 1\n for i in range(0,3):\n for j in range(0,10):\t \n plane[i][j] = 1\n return plane\n\ndef M():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,2):\n for j in range(0,10):\n\t plane[i][j] = 1\n for i in range(8,10):\n for j in range(0,10):\n plane[i][j] = 1\n #for i in range(4,7):\n\t#for j in range(0,10):\n\t # plane[i][j] = 1\n for i in range(0,10):\n for j in range(0,10):\n if(i == j):\n\t plane[i/2][j] = 1\n try:\n plane[i/2][j-1] = 1\n plane[i/2][j+1] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n if(i+j==9):\n\t plane[5 + i/2][j] = 1\n try:\n plane[5+i/2][j-1] = 1\n plane[5+i/2][j+1] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n\n return plane\n\ndef N():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,3):\n for j in range(0,10):\n\t plane[i][j] = 1\n for i in range(7,10):\n for j in range(0,10):\n plane[i][j] = 1\n for i in range(0,10):\n for j in range(0,10):\n if(i == j):\n\t plane[i][j] = 1\n try:\n plane[i][j-1] = 1\n plane[i][j+1] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n return plane\n\ndef O():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\n for j in range(0,3):\n\t plane[i][j] = 1\t\n\tfor j in range(7,10):\n plane[i][j] = 1\n for j in range(0,10):\n for i in range(0,3):\t \n plane[i][j] = 1\n for i in range(7,10):\n plane[i][j] = 1\n return plane\n\ndef P():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\n for j in range(0,2):\n\t plane[i][j] = 1\t\n\tfor j in range(4,7):\n\t plane[i][j] = 1\n for i in range(0,3):\n for j in range(0,10):\t \n plane[i][j] = 1\n for i in range(7,10):\n for j in range(0,4):\n plane[i][j] = 1\n return plane\n\ndef Q():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\n for j in range(0,2):\n\t plane[i][j] = 1\t\n\tfor j in range(8,10):\n plane[i][j] = 1\n for j in range(0,10):\n for i in range(0,2):\t \n plane[i][j] = 1\n for i in range(8,10):\n plane[i][j] = 1\n for i in range(5,10):\n for j in range(5,10):\n if(i == j):\n\t plane[i][j] = 1\n try:\n plane[i][j-1] = 1\n plane[i][j+1] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n \n return plane\n\ndef R():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\n for j in range(0,3):\n\t plane[i][j] = 1\t\n\tfor j in range(4,6):\n\t plane[i][j] = 1\n for i in range(0,3):\n for j in range(0,10):\t \n plane[i][j] = 1\n for i in range(7,10):\n for j in range(0,4):\n plane[i][j] = 1\n for i in range(0,10):\n\tfor j in range(0,10):\n\t if(i == j):\n\t plane[i][5+j/2] = 1\n try:\n plane[i-1][4+j/2] = 1\n plane[i+1][4+j/2] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n\n return plane\n\n\ndef I():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\n for j in range(0,3):\n\t plane[i][j] = 1\n\tfor j in range(7,10):\n plane[i][j] = 1\t\t\n for i in range(3,7):\n for j in range(3,10):\t \n plane[i][j] = 1\n \n return plane\n\ndef S():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\n for j in range(0,3):\n\t plane[i][j] = 1\t\n\tfor j in range(4,7):\n\t plane[i][j] = 1\n\tfor j in range(8,10):\n plane[i][j] = 1\n for i in range(0,3):\n for j in range(0,7):\t \n plane[i][j] = 1\n for i in range(7,10):\n\tfor j in range(4,10):\n\t plane[i][j] = 1\n return plane\n\ndef U():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\t\n\tfor j in range(7,10):\n plane[i][j] = 1\n for j in range(0,10):\n for i in range(0,3):\t \n plane[i][j] = 1\n\tfor i in range(7,10):\n plane[i][j] = 1\n return plane\n\ndef V():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,10):\n for j in range(0,10):\n if(i == j):\n\t plane[i/2][j] = 1\n try:\n plane[i/2][j-1] = 1\n plane[i/2][j+1] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n if(i+j==9):\n\t plane[5 + i/2][j] = 1\n try:\n plane[5+i/2][j-1] = 1\n plane[5+i/2][j+1] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n plane[0][9] = 0\n plane[9][9] = 0\n return plane\n\ndef W():\n plane = numpy.array([[0]*10] * 10) \n for i in range(0,2):\n for j in range(0,10):\n\t plane[i][j] = 1\n for i in range(8,10):\n for j in range(0,10):\n plane[i][j] = 1\n #for i in range(4,7):\n\t#for j in range(0,10):\n\t # plane[i][j] = 1\n for i in range(0,10):\n for j in range(0,10):\n if(i == j):\n\t plane[5+i/2][j] = 1\n try:\n plane[5+i/2][j+2] = 1\n plane[5+i/2][j+1] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n if(i+j==9):\n\t plane[i/2][j] = 1\n try:\n plane[i/2][j+2] = 1\n plane[i/2][j+1] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n\n return plane\ndef X():\n plane = numpy.array([[0]*10]*10)\n for i in range(0,10):\n for j in range(0,10):\n if(i == j):\n\t plane[i][j] = 1\n try:\n plane[i][j-1] = 1\n plane[i][j+1] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n if(i+j == 9):\n plane[i][j] = 1\n try:\n plane[i][j-1] = 1\n plane[i][j+1] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n\n return plane\n\ndef Y():\n plane = numpy.array([[0]*10]*10)\n for i in range(0,10):\n for j in range(0,5):\n if(i == j):\n\t plane[i][j] = 1\n try:\n plane[i][j-1] = 1\n plane[i][j+1] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n if(i+j == 9):\n plane[i][j] = 1\n try:\n plane[i][j-1] = 1\n plane[i][j+1] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n for i in range(4,6):\n\tfor j in range(5,10):\n plane[i][j] = 1\n plane[0][9] = 0\n plane[0][0] = 0\n return plane\n\ndef Z():\n plane = numpy.array([[0]*10]*10)\n for i in range(0,10):\n for j in range(0,10):\n if(i+j == 9):\n plane[i][j] = 1\n try:\n plane[i][j-1] = 1\n plane[i][j+1] = 1\n\t\texcept:\n\t\t print \"Blaaah\"\n for i in range(0,10):\n\tfor j in range(0,3):\n\t plane[i][j] = 1\n\tfor j in range(7,10):\n\t plane[i][j] = 1\n return plane\n\ndef stringPrint(cube,string,counter=0,axis = 3):\n\tif counter%10 ==0:\n\t\tfillCube(cube,0)\n\t\ti = string[(counter/10)%len(string)]\n\t\tif i == 'A':\n\t\t\tsetPlane(cube,axis,9,A())\n \t\telif i == 'B':\n \t\t\tsetPlane(cube,axis,9,B())\n\t\telif i == 'C':\n\t\t\tsetPlane(cube,axis,9,C())\n\t\telif i == 'D':\n\t\t\tsetPlane(cube,axis,9,D())\n\t\telif i == 'E':\n\t\t\tsetPlane(cube,axis,9,E())\n\t\telif i == 'F':\n\t\t\tsetPlane(cube,axis,9,F())\n\t\telif i == 'G':\n\t\t\tsetPlane(cube,axis,9,G())\n\t\telif i == 'H':\n\t\t\tsetPlane(cube,axis,9,H())\n\t\telif i == 'I':\n\t\t\tsetPlane(cube,axis,9,I())\n\t\telif i == 'J':\n\t\t\tsetPlane(cube,axis,9,J())\n\t\telif i == 'K':\n\t\t\tsetPlane(cube,axis,9,K())\n\t\telif i == 'L':\n\t\t\tsetPlane(cube,axis,9,L())\n\t\telif i == 'M':\n\t\t\tsetPlane(cube,axis,9,M())\n\t\telif i == 'N':\n\t\t\tsetPlane(cube,axis,9,N())\n\t\telif i == 'O':\n\t\t\tsetPlane(cube,axis,9,O())\n\t\telif i == 'P':\n\t\t\tsetPlane(cube,axis,9,P())\n\t\telif i == 'Q':\n\t\t\tsetPlane(cube,axis,9,Q())\n\t\telif i == 'R':\n\t\t\tsetPlane(cube,axis,9,R())\n\t\telif i == 'S':\n\t\t\tsetPlane(cube,axis,9,S())\n\t\telif i == 'T':\n\t\t\tsetPlane(cube,axis,9,T())\n\t\telif i == 'U':\n\t\t\tsetPlane(cube,axis,9,U())\n\t\telif i == 'V':\n\t\t\tsetPlane(cube,axis,9,V())\n\t\telif i == 'W':\n\t\t\tsetPlane(cube,axis,9,W())\n\t\telif i == 'X':\n\t\t\tsetPlane(cube,axis,9,X())\n\t\telif i == 'Y':\n\t\t\tsetPlane(cube,axis,9,Y())\n\t\telif i == 'Z':\n\t\t\tsetPlane(cube,axis,9,Z())\n\telse:\n\t\tshiftCube(cube,axis,1)\n\ndef stringfly(cube,axis):\n shiftCube(cube,axis,1)\n\ndef technites(cube,counter,axis = 3):\n\talpha = counter/9\n\tif(counter%90 == 0): \n\t fillCube(cube,0)\n\t setPlane(cube,axis,9,T(cube))\n elif(counter%90 == 10):\n\t fillCube(cube,0)\n setPlane(cube,axis,9,E(cube))\n\telif(counter%90 == 20):\n\t fillCube(cube,0)\n setPlane(cube,axis,9,C(cube))\n\telif(counter%90 == 30):\n\t fillCube(cube,0)\n setPlane(cube,axis,9,H(cube))\n\telif(counter%90 == 40):\n\t fillCube(cube,0)\n setPlane(cube,axis,9,N(cube))\n elif(counter%90 == 50):\n\t fillCube(cube,0)\n setPlane(cube,axis,9,I(cube))\n\telif(counter%90 == 60):\n\t fillCube(cube,0)\n setPlane(cube,axis,9,T(cube)) \n elif(counter%90 == 70):\n\t fillCube(cube,0)\n setPlane(cube,axis,9,E(cube))\n\telif(counter%90 == 80):\n\t fillCube(cube,0)\n setPlane(cube,axis,9,S(cube))\n else:\n\t stringfly(cube,axis)\ndef moveFaces(cube):\n\tZ0 = numpy.array([[0]*cube.dimension]*cube.dimension)\n\tZ9 = numpy.array([[0]*cube.dimension]*cube.dimension)\n\tX0 = numpy.array([[0]*cube.dimension]*cube.dimension)\n\tX9 = numpy.array([[0]*cube.dimension]*cube.dimension)\n\tfor i in range(1,cube.dimension):\n\t for j in range(0,cube.dimension):\n\t\tX0[i-1][j] = cube.get_led(i,j,0)\n\tfor j in range(0,cube.dimension):\n\t X0[9][j] = cube.get_led(9,j,0)\n \n\tfor i in range(0,cube.dimension-1):\n\t for j in range(0,cube.dimension):\n\t\tZ0[i+1][j] = cube.get_led(0,j,i)\n\n\tfor j in range(0,cube.dimension):\n\t Z0[0][j] = cube.get_led(0,j,0)\n \n\tfor i in range(0,cube.dimension-1):\n\t for j in range(0,cube.dimension):\n\t\tX9[i+1][j] = cube.get_led(i,j,9)\n\tfor j in range(0,cube.dimension):\n\t X9[0][j] = cube.get_led(0,j,9)\n\n for i in range(1,cube.dimension):\n\t for j in range(0,cube.dimension):\n\t\tZ9[i-1][j] = cube.get_led(9,j,i)\n\n\tfor j in range(0,cube.dimension):\n\t Z9[9][j] = cube.get_led(9,j,9)\n\tfillCube(cube,0)\n\tsetPlane(cube,3,0,X0)\n\tsetPlane(cube,1,0,Z0)\n\tsetPlane(cube,3,9,X9)\n\tsetPlane(cube,1,9,Z9)\n\n" }, { "alpha_fraction": 0.7372262477874756, "alphanum_fraction": 0.7372262477874756, "avg_line_length": 21.83333396911621, "blob_id": "e1384784adaeb063874ebc18cd3d6cdf5e80999a", "content_id": "3b4852d68d77c39ca507698d51f5d8c8a1d6263e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 137, "license_type": "no_license", "max_line_length": 34, "num_lines": 6, "path": "/src/apps/pathsetup.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "import os, sys\n\ndirname = os.path.dirname\nhere = os.path.abspath(__file__)\nparentdir = dirname(dirname(here))\nsys.path.append(parentdir)\n" }, { "alpha_fraction": 0.49329444766044617, "alphanum_fraction": 0.49737608432769775, "avg_line_length": 26.206348419189453, "blob_id": "98a389b8c8a580d9fe43a692acab87b4771dd159", "content_id": "57b46c63680def1936f97e9fd9ad459c4c3b9af0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1715, "license_type": "no_license", "max_line_length": 79, "num_lines": 63, "path": "/src/phosphene/util.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "import numpy\nfrom threading import Thread # this is for the repl\n\n__all__ = ['memoize', 'memoizeBy', 'numpymap', 'indexable', 'reverse']\n# Helper functions\ndef memoize(f, key=None):\n mem = {}\n def g(*args):\n k = str(args)\n if mem.has_key(k):\n return mem[k]\n else:\n r = f(*args)\n mem[k] = r\n return r\n return g\n\ndef memoizeBy(f, x, *args):\n # memoize by something else.\n return memoize(lambda k: f(*args))(x)\n\ndef numpymap(f, X):\n \" returns a numpy array after maping \"\n return numpy.array(map(f, X))\n\ndef indexable(f, offset=0):\n \" make a list-like object \"\n if not hasattr(f, '__call__'):\n # XXX: Assuming f is a sequence type\n try: f[0]\n except:\n raise \"Are you sure what you are trying\" + \\\n \"to make indexable is a function or\" + \\\n \"a sequence type?\"\n g = f\n f = lambda i: g[i] # LOL\n\n class Indexable:\n def getFunction(self):\n return f\n def __getitem__(self, *i):\n if len(i) == 1:\n i = i[0]\n if isinstance(i, int):\n return f(i + offset)\n # Handle range queries\n elif isinstance(i, slice):\n return [f(j + offset) for j in \\\n range(i.start, i.stop, 1 if i.step is None else 0)]\n else:\n raise \"You will have to implement that crazy indexing.\"\n def __len__(self):\n return 0\n\n return Indexable()\n\ndef windowedMap(f, samples, width, overlap):\n return res\n\ndef reverse(l):\n m = [c for c in l]\n m.reverse()\n return m\n\n" }, { "alpha_fraction": 0.6451612710952759, "alphanum_fraction": 0.68049156665802, "avg_line_length": 27.30434799194336, "blob_id": "f26902cd165f62b9cf08606f94d7d568b140d140", "content_id": "513f15b3c9241ce066530a98223df104a61b1970", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 651, "license_type": "no_license", "max_line_length": 52, "num_lines": 23, "path": "/src/apps/cube.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "from devices.cubelib import emulator\nfrom devices.cubelib import mywireframe as wireframe\nfrom devices.animations import *\n\npv = emulator.ProjectionViewer(640,480)\nwf = wireframe.Wireframe()\n\ndef cubeProcess(cube, signal, count):\n pv.createCube(wf)\n start = (0, 0, 0)\n point = (0,0)\n #planeBounce(cube,(count/20)%2+1,count%20)\n #start = wireframeExpandContract(cube,start)\n #rain(cube,count,5,10)\n #time.sleep(.1)\n #point = voxel(cube,count,point)\n #sine_wave(cube,count)\n #pyramids(cube,count)\n #side_waves(cube,count)\n #fireworks(cube,4)\n technites(cube,count)\n cube.redraw(wf, pv)\n return count + 1\n" }, { "alpha_fraction": 0.5857642889022827, "alphanum_fraction": 0.6149358153343201, "avg_line_length": 34.70833206176758, "blob_id": "9fee650d9e7dddb7cd9d85d722d7d048388b8dbb", "content_id": "c291abb94d28b13ccaf115937776e0925a8e5609", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 857, "license_type": "no_license", "max_line_length": 112, "num_lines": 24, "path": "/src/apps/devices/ledwall.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "import device\nfrom phosphene.signal import *\nfrom phosphene.signalutil import *\nfrom phosphene.graphs import *\n\nclass LEDWall(device.Device):\n def __init__(self, port):\n device.Device.__init__(self, \"LEDWall\", port)\n\n def setupSignal(self, signal):\n CHANNELS = 6 \n val = lambda s: [max(0, scipy.log(s.avg3[0]+1)) - scipy.log(s.longavg3[0]+1)]\n signal.avg1Falling = fallingMax(val)\n def f(s):\n n = int(min(6, max(0, val(s)[0] * CHANNELS / (s.avg1Falling[0] if s.avg1Falling[0] > 0.01 else 1))))\n return [1 for i in range(0, n)] + [0 for i in range(0, 6-n)]\n signal.ledwall = lift(f)\n\n def graphOutput(self, signal):\n return None\n\n def redraw(self, signal):\n print \"LEDWall\", self.toByteStream(signal.ledwall)\n self.port.write(self.toByteStream(signal.ledwall))\n" }, { "alpha_fraction": 0.5598791837692261, "alphanum_fraction": 0.5941720008850098, "avg_line_length": 33.29878234863281, "blob_id": "5d2c5e8fc3d498a4c60d39529fbb1c2ae9a388e1", "content_id": "36a374d5b35c8fab447dcc5b470ddd3335b4f06d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5628, "license_type": "no_license", "max_line_length": 254, "num_lines": 164, "path": "/src/apps/devices/cubelib/emulator.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "#!/bin/env python\n#using the wireframe module downloaded from http://www.petercollingridge.co.uk/\nimport mywireframe as wireframe\nimport pygame\nfrom pygame import display\nfrom pygame.draw import *\nimport time\nimport numpy\n\nkey_to_function = {\n pygame.K_LEFT: (lambda x: x.translateAll('x', -10)),\n pygame.K_RIGHT: (lambda x: x.translateAll('x', 10)),\n pygame.K_DOWN: (lambda x: x.translateAll('y', 10)),\n pygame.K_UP: (lambda x: x.translateAll('y', -10)),\n pygame.K_EQUALS: (lambda x: x.scaleAll(1.25)),\n pygame.K_MINUS: (lambda x: x.scaleAll( 0.8)),\n pygame.K_q: (lambda x: x.rotateAll('X', 0.1)),\n pygame.K_w: (lambda x: x.rotateAll('X', -0.1)),\n pygame.K_a: (lambda x: x.rotateAll('Y', 0.1)),\n pygame.K_s: (lambda x: x.rotateAll('Y', -0.1)),\n pygame.K_z: (lambda x: x.rotateAll('Z', 0.1)),\n pygame.K_x: (lambda x: x.rotateAll('Z', -0.1))}\n\nclass ProjectionViewer:\n \"\"\" Displays 3D objects on a Pygame screen \"\"\"\n\n def __init__(self, width, height):\n self.width = width\n self.height = height\n self.screen = pygame.display.set_mode((width, height))\n pygame.display.set_caption('Wireframe Display')\n self.background = (10,10,50)\n\n self.wireframes = {}\n self.displayNodes = True\n self.displayEdges = True\n self.nodeColour = (255,255,255)\n self.edgeColour = (200,200,200)\n self.nodeRadius = 3 #Modify to change size of the spheres\n\n def addWireframe(self, name, wireframe):\n \"\"\" Add a named wireframe object. \"\"\"\n\n self.wireframes[name] = wireframe\n\n def run(self): \n for event in pygame.event.get():\n\t\tif event.type == pygame.KEYDOWN:\n \t\tif event.key in key_to_function:\n \t\tkey_to_function[event.key](self)\n\n self.display()\n pygame.display.flip()\n \n def display(self):\n \"\"\" Draw the wireframes on the screen. \"\"\"\n\n self.screen.fill(self.background)\n\n for wireframe in self.wireframes.values():\n if self.displayEdges:\n for edge in wireframe.edges:\n pygame.draw.aaline(self.screen, self.edgeColour, (edge.start.x, edge.start.y), (edge.stop.x, edge.stop.y), 1)\n\n if self.displayNodes:\n for node in wireframe.nodes:\n if node.visiblity:\n pygame.draw.circle(self.screen, self.nodeColour, (int(node.x), int(node.y)), self.nodeRadius, 0)\n\n def translateAll(self, axis, d):\n \"\"\" Translate all wireframes along a given axis by d units. \"\"\"\n\n for wireframe in self.wireframes.itervalues():\n wireframe.translate(axis, d)\n\n def scaleAll(self, scale):\n \"\"\" Scale all wireframes by a given scale, centred on the centre of the screen. \"\"\"\n\n centre_x = self.width/2\n centre_y = self.height/2\n\n for wireframe in self.wireframes.itervalues():\n wireframe.scale((centre_x, centre_y), scale)\n\n def rotateAll(self, axis, theta):\n \"\"\" Rotate all wireframe about their centre, along a given axis by a given angle. \"\"\"\n\n rotateFunction = 'rotate' + axis\n\n for wireframe in self.wireframes.itervalues():\n centre = wireframe.findCentre()\n getattr(wireframe, rotateFunction)(centre, theta)\n \n def createCube(self,cube,X=[50,140], Y=[50,140], Z=[50,140]):\n cube.addNodes([(x,y,z) for x in X for y in Y for z in Z]) #adding the nodes of the cube framework. \n allnodes = []\n \tcube.addEdges([(n,n+4) for n in range(0,4)]+[(n,n+1) for n in range(0,8,2)]+[(n,n+2) for n in (0,1,4,5)]) #creating edges of the cube framework.\n \tfor i in range(0,10):\n \tfor j in range(0,10):\n \tfor k in range(0,10):\n \tallnodes.append((X[0]+(X[1]-X[0])/9 * i,Y[0]+(Y[1] - Y[0])/9 * j,Z[0] + (Z[1]-Z[0])/9 * k))\n\n \tcube.addNodes(allnodes)\n \t#cube.outputNodes()\n \tself.addWireframe('cube',cube)\n\n\n\ndef findIndex(coords): #Send coordinates of the points you want lit up. Will convert to neede \n\n\tindices = []\n\tfor nodes in coords:\n\t\tx,y,z = nodes\n\t\tindex = x*100+y*10+z + 8\n\t\tindices.append(index)\n\treturn indices\n\ndef findIndexArray(array): #Takes a 3-D numpy array containing bool of all the LED points.\n\n\tindices = []\n\tfor i in range(0,10):\n\t\tfor j in range(0,10):\n\t\t\tfor k in range(0,10):\n\t\t\t\tif(array[i][j][k] == 1):\n\t\t\t\t\tindex = i*100+j*10+ k + 8\n\t\t\t\t\tindices.append(index)\n\treturn indices\n\n\ndef wireframecube(size):\n\tif size % 2 == 1:\n\t\tsize = size+1\n\thalf = size/2\n\tstart = 5 - half\n\tend = 5 + half - 1\n\tcubecords = [(x,y,z) for x in (start,end) for y in (start,end) for z in range(start,end+1)]+[(x,z,y) for x in (start,end) for y in (start,end) for z in range(start,end+1)] + [(z,y,x) for x in (start,end) for y in (start,end) for z in range(start,end+1)]\n\treturn cubecords\n\ndef cubes(size):\n\tif size % 2 == 1:\n\t\tsize = size+1\n\thalf = size/2\n\tcubecords = []\n\tfor i in range(0,size):\n\t\tfor j in range(0,size):\n\t\t\tfor k in range(0,size):\n\t\t\t\tcubecords.append((5-half+i,5-half+j,5-half+k))\t\n\treturn cubecords\nif __name__ == '__main__':\n \n pv = ProjectionViewer(400, 300)\n allnodes =[]\n cube = wireframe.Wireframe() #storing all the nodes in this wireframe object.\n X = [50,140]\n Y = [50,140]\n Z = [50,140] \n pv.createCube(cube,X,Y,Z)\n YZface = findIndex((0,y,z) for y in range(0,10) for z in range(0,10)) \n count = 0 \n for k in range(1,150000):\n\tif k%5000 ==2500:\n\t\tcount = (count+2)%11 \n\t\tcube.setVisible(findIndex(wireframecube(count)))\n\tpv.run()\n\t\t\n" }, { "alpha_fraction": 0.5789473652839661, "alphanum_fraction": 0.5789473652839661, "avg_line_length": 37, "blob_id": "fc79020b96cc8f0b8f271fba547be17eacc97d1b", "content_id": "9d09f30f85bfddc5e6dd1dbefcba7364494feb5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 38, "license_type": "no_license", "max_line_length": 37, "num_lines": 1, "path": "/src/apps/devices/cubelib/__init__.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "__all__ = [\"emulator\", \"mywireframe\"]\n" }, { "alpha_fraction": 0.7096680998802185, "alphanum_fraction": 0.7223665118217468, "avg_line_length": 38.375, "blob_id": "500c4bed9a9a95ae5eb994b90ed108b5ada2cc04", "content_id": "88a1ac392222fd869ce4c59da6b81d4abd470a16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3465, "license_type": "no_license", "max_line_length": 289, "num_lines": 88, "path": "/README.md", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "Phosphene\n=========\n\nPhosphene is a library aimed at helping music visualization. This project is being written for visualizing music on a 10x10x10 3D LED display, and other hand-made devices (see apps/psychroom.py). But the phosphene package is more general and can be used for music visualization in general.\n\nThe Signal abstraction\n----------------------\n\nThe Signal class provides some cool abstractions you can use to setup various attributes for a signal. You can initialize a signal from the raw wav data as shown below:\n\n```python\nfrom phosphene.signal import *\n # all example code below assumes that this line is on top\nmySignal = Signal(data, sampling_rate)\n # data is usually a numpy array with\n # left & right channel samples\n```\n\nNow, `mySignal` has some time varying values like `mySignal.t`, the current time (unique for each `mySignal.x`); `mySignal.x`, the current sample number, (`mySignal.Y[mySignal.x]` is the current sample itself).\n\nYou can `lift` any function that takes the signal as argument to make it a time varying attribute of the same signal. e.g.:\n\n```python\nmySignal.xsquared = lift(lambda s: s.x**2)\n```\n\nNow, `mySignal.xsquared` is `mySignal.x` squared, and varies with `mySignal.x`.\n\nYou can also lift long sequences of the same length as the data in\nthe Signal. For example, the average of left and right channels in the data, `mySignal.A` is setup in this way in Signal's contructor.\n\n```python\nmySignal.A = lift((mySignal.Y[:, 0] + mySignal.Y[:, 1]) / 2)\n # average of left and right channels\n```\n\nreferencing `mySignal.A` will return the `mySignal.x`th average value\n\nYou can also make these arrays \"temporally indexable\".\n\ne.g. if you instead did\n\n```python\nmySignal.A = lift((mySignal.Y[:, 0] + mySignal.Y[:, 1]) / 2, True)\n # (the True argument makes it t-indexed)\n```\n\n`mySignal.A[0]` will be the `mySignal.x`th average value, while `mySignal.A[-1]` is the one before that,You can say `mySignal.A[-512:512]` to get 1024 values of `A` centered at the `mySignal.x`th sample\n\nUsing this, you can define short-time fft like this:\n\n```python\nmySignal.fft = lift(lambda s: dsp.fft(s.A[-N/2:N/2]))\n```\nwhere `N` is the size of your window for the STFFT.\n\nA \"process\" is a function that takes a signal as its argument and affects the world (e.g. draws something trippy on the screen). Processes can \"perceive\" a signal. `perceive` simulates changes in the signal as if it is being read in real-time. Watch.\n\n```python\nfrom phosphene.graphs import *\ndef barsProcess(s):\n surface.fill((0, 0, 0))\n print \"The current sample number is:\", s.x\n print \"The current fps is:\", s.fps\n # Plot the short-time FFT in a bar graph\n barGraph(surface, (0, 0, 640, 480), group(32, s.fft))\n display.update()\n\n# assuming mySingal is loaded and all the code above is\n# executed\nprocesses = [barsProcess]\nsong.play() # start playing the music that will be perceived, this call needs to be non blocking\nfps = 90 # the fps you'd like (actual fps maybe lesser)\nperceive(processes, mySingal, fps) # simulate perception of music by processes\n```\n\n`signal` and `signalutil` modules contain some functions that return `lift` values. Such as `foldp` (fold over past) and `blend` (cause a value vary smoothly).\n\nSee demo.py for an example of beat detection done using this class and some utility functions from phosphene.\n\nHappy Hacking!\n\ndependencies\n------------\n\n* Python 2.x\n* numpy, scipy and pygame python packages\n* lame\n" }, { "alpha_fraction": 0.5555555820465088, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 44, "blob_id": "1c41b648c3215149452860e2307d91a80f869b89", "content_id": "040b44180e8660875cdf660fa833e1783dadde5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 45, "license_type": "no_license", "max_line_length": 44, "num_lines": 1, "path": "/src/apps/devices/__init__.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "__all__ = [\"discoball\", \"cube\", \"waterfall\"]\n" }, { "alpha_fraction": 0.5217772126197815, "alphanum_fraction": 0.5257167816162109, "avg_line_length": 26.035503387451172, "blob_id": "1621aa741faecd036ddcb7893ae2150d0e15a034", "content_id": "520219d5bb28e0ff7d7925ec6c0e50dc0d0074c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4569, "license_type": "no_license", "max_line_length": 70, "num_lines": 169, "path": "/src/phosphene/signal.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "import time\n\nimport numpy\n\nfrom util import indexable\n\n__all__ = [\n 'Signal',\n 'lift',\n 'foldp',\n 'perceive'\n]\n\n\nclass lift:\n \"\"\" Annotate an object as lifted \"\"\"\n def __init__(self, f, t_indexable=None):\n self.f = f\n if hasattr(f, '__call__'):\n self._type = 'lambda'\n elif isinstance(self.f, (list, tuple, numpy.ndarray)):\n self._type = 'iterable'\n else:\n raise ValueError(\n \"\"\"You can lift only a function that takes\n the signal as argument, or an iterable\"\"\"\n )\n\n self.indexable = t_indexable\n\n def _manifest(self, signal):\n\n # compute the current value of this lifted\n # function given the current value of the signal\n\n if self._type == \"lambda\":\n return self.f(signal)\n elif self._type == \"iterable\":\n if self.indexable is None or self.indexable:\n # Make the array temporally indexable\n return indexable(self.f, signal.x)\n elif indexable == False:\n return self.f[signal.x]\n\n\ndef foldp(f, init=None):\n \"\"\"Fold a value over time\n \"\"\"\n\n State = lambda: 0 # hack to let me store state\n State.store = init\n State.val = None\n\n def g(signal):\n val, store = f(signal, State.store)\n State.store = store\n State.val = val\n return val\n return lift(g)\n\n\nclass _WAIT:\n # _WAIT instances are used in the locking\n # mechanism in Signal to avoid recomputation\n # when multiple threads are using a signal\n pass\n\n\nclass Signal:\n \"\"\" The Signal abstraction. \"\"\"\n def __init__(self, Y, sample_rate, max_fps=90):\n self.Y = Y\n self.x = 0\n self.fps = 0\n self.max_fps = max_fps\n self.sample_rate = sample_rate\n self.lifts = {}\n self.t = lift(lambda s: s.time())\n self.A = lift(Y[:,0], True)\n self.cache = {}\n\n def time(self, t=time.time):\n # this signal's definition of time\n return t()\n\n def __getattr__(self, k):\n # call the thing that is requred with self\n if self.lifts.has_key(k):\n # Lifted values must have the same value\n # for the same x. Cache them.\n # This also helps in performance e.g. when\n # fft is needed a multiple places\n\n if self.cache.has_key(k):\n if isinstance(self.cache[k], _WAIT):\n # Locking mechanism to avoid\n # redundant computations by threads\n while isinstance(self.cache[k], _WAIT):\n pass\n return self.cache[k][1]\n else:\n x, val = self.cache[k]\n if x == self.x:\n return val\n\n self.cache[k] = _WAIT()\n val = self.lifts[k]._manifest(self)\n self.cache[k] = (self.x, val)\n return val\n else:\n return self.__dict__[k]\n\n def __setattr__(self, k, v):\n if isinstance(v, lift):\n self.lifts[k] = v\n else:\n self.__dict__[k] = v\n\n def set_state(self, x, fps, frames):\n self.x = x\n self.fps = fps\n self.frames = frames\n\ndef perceive(processes, signal, max_fps):\n \"\"\"Let processes perceive the signal\n\n simulates real-time reading of signals and runs all the functions\n in processes (these functions take the current signal value as\n argument)\n \"\"\"\n\n start_time = signal.time()\n call_spacing = 1.0 / max_fps\n sample_count = len(signal.Y)\n prev_x = -1\n x = 0\n frames = 0\n fps = max_fps\n\n while True:\n tic = signal.time()\n\n # what should be the current sample?\n x = int((tic - start_time) * signal.sample_rate)\n if x >= sample_count:\n break\n\n frames += 1\n\n # approximate current fps\n fps = fps * 0.5 + 0.5 * signal.sample_rate / float(x - prev_x)\n\n # Advance state of the signal\n signal.set_state(x, fps, frames)\n\n for p in processes:\n p(signal) # show processes the signal\n\n prev_x = x\n\n toc = signal.time()\n wait = call_spacing - (toc - tic)\n\n # chill out before looping again\n # FIXME: this assumes that the frame rate varies smoothly\n # i.e. next frame takes approximately takes the\n # same time as few frames immediately before it\n if wait > 0:\n time.sleep(wait)\n" }, { "alpha_fraction": 0.3772977888584137, "alphanum_fraction": 0.41360294818878174, "avg_line_length": 24.600000381469727, "blob_id": "e697f157a39554d5277621737cf3ec80087cb75b", "content_id": "d8dcb5dad18b5f1ea93e91400455777de83e3af8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2176, "license_type": "no_license", "max_line_length": 76, "num_lines": 85, "path": "/src/phosphene/graphs.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "import pdb\nimport scipy\nimport numpy\nimport pygame\nfrom pygame import display\nfrom pygame.draw import *\nfrom pygame import Color\nimport math\n\ndef barGraph(data):\n \"\"\"\n drawing contains (x, y, width, height)\n \"\"\"\n\n def f(surface, rectangle):\n x0, y0, W, H = rectangle\n try:\n l = len(data)\n except:\n pdb.set_trace()\n w = W / l\n try:\n for i in range(0, l):\n h = data[i]\n c = Color(0, 0, 0, 0)\n c.hsva = (0, 100, 100, 0)\n x = x0 + i * w\n y = y0 + H * (1 - h)\n rect(surface, c, \\\n (x, y, 0.9 * w, h * H))\n except:\n pdb.set_trace()\n return f\n\ndef boopGraph(data):\n def f(surface, rectangle):\n x0, y0, W, H = rectangle\n try:\n l = len(data)\n except:\n pdb.set_trace()\n dx = W / l\n try:\n for i in range(0, l):\n d = data[i]\n a = dx * d\n x = (dx - a) / 2 + i * dx + x0\n y = (H - dx) / 2 + (dx - a) / 2 + y0\n c = Color(255, 255, 255, 255)\n rect(surface, c, \\\n (x, y, a, a))\n except:\n pdb.set_trace()\n return f\n\n\ndef circleRays(surface, center, data, transform=lambda y: scipy.log(y + 1)):\n\n x0, y0 = center\n \n total = math.radians(360)\n l = len(data)\n m = transform(max(data))\n part = total/l\n for i in range(0, l):\n if m > 0:\n p = transform(data[i])\n h = p * 5\n hue = p / m\n c = Color(0, 0, 0, 0)\n c.hsva = ((1-hue) * 360, 100, 100, 0)\n x = x0 + (m*2+h)*math.cos(part * i)\n y = y0 + (m*2+h)*math.sin(part*i)\n line(surface, c, \n (x0,y0),(x,y),1)\n circle(surface,c, center,int(m*2),0)\n \ndef graphsGraphs(graphs, direction=0):\n def f(surface, bigRect):\n x0, y0, W, H = bigRect\n h = H / len(graphs)\n for graph in graphs:\n graph(surface, (x0, y0, W, h))\n y0 += h\n return f\n" }, { "alpha_fraction": 0.6389776468276978, "alphanum_fraction": 0.6629393100738525, "avg_line_length": 31.947368621826172, "blob_id": "887c35dd0b6fd94d2538db779fbe1773d012d3b9", "content_id": "efdb04f6fa54590f4843ba338c138d36c537e6d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 626, "license_type": "no_license", "max_line_length": 120, "num_lines": 19, "path": "/src/apps/devices/discoball.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "import device\nfrom phosphene.signal import *\nfrom phosphene.signalutil import *\nfrom phosphene.graphs import *\n\nclass DiscoBall(device.Device):\n def __init__(self, port):\n device.Device.__init__(self, \"DiscoBall\", port)\n\n def setupSignal(self, signal):\n signal.discoball = lift(lambda s: numpymap(lambda (a, b): 1 if a > b * 1.414 else 0, zip(s.avg12, s.longavg12)))\n\n def graphOutput(self, signal):\n return boopGraph(signal.discoball[:4])\n\n def redraw(self, signal):\n data = self.truncate(signal.discoball[:4] * 255)\n print data\n self.port.write(self.toByteStream(data))\n" }, { "alpha_fraction": 0.5827900767326355, "alphanum_fraction": 0.6010430455207825, "avg_line_length": 28.5, "blob_id": "d778123d214ab90c03263355b0a6b3367b3e1004", "content_id": "b7cc57d7b27182259422385cee90b5cf4ce934dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 767, "license_type": "no_license", "max_line_length": 65, "num_lines": 26, "path": "/src/apps/devices/waterfall.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "import device\nfrom phosphene.signal import *\nimport scipy, numpy\nfrom phosphene.graphs import barGraph\n\nclass Waterfall(device.Device):\n def __init__(self, port):\n device.Device.__init__(self, \"Waterfall\", port)\n\n def setupSignal(self, signal):\n def waterfall(s):\n lights = [s.avg8[i] * 150 / max(0.5, s.longavg8[i]) \\\n for i in range(0, 8)]\n\n fans = [2*i for i in lights]\n lights.reverse()\n return lights + fans\n\n signal.waterfall = lift(waterfall)\n\n def graphOutput(self, signal):\n return barGraph(self.truncate(signal.waterfall) / 255.0)\n\n def redraw(self, signal):\n payload = self.toByteStream(signal.waterfall)\n self.port.write(payload)\n" }, { "alpha_fraction": 0.5797733068466187, "alphanum_fraction": 0.5841324925422668, "avg_line_length": 26.285715103149414, "blob_id": "841d68f9b37902d6f42ec81e28f8e88f941accce", "content_id": "b311eeca2314b7437dec03ab36ceed22d968bf6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1147, "license_type": "no_license", "max_line_length": 63, "num_lines": 42, "path": "/src/apps/devices/device.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "import serial\nimport numpy\nfrom threading import Thread\n\nclass Device:\n def __init__(self, name, port):\n self.array = []\n try:\n self.port = serial.Serial(port)\n self.isConnected = True\n print \"Connected to\", name\n except Exception as e:\n self.port = None\n self.isConnected = False\n print \"Error connecting to\", name, e\n\n def setupSignal(self, signal):\n pass\n\n def graphOutput(self, signal):\n pass\n\n def truncate(self, array):\n return numpy.array([min(int(i), 255) for i in array])\n\n def toByteStream(self, array):\n return [chr(i) for i in self.truncate(array)]\n\n def readAck(self):\n print self.port.read(size=1) # Read the acknowledgement\n\n def redraw(self):\n if self.isConnected:\n self.port.write(self.toByteStream())\n self.port.read(size=1) #Acknowledgement\n else:\n #print \"Connection to %s lost!\" % self.name\n pass\n\n def isUnresponsive(self):\n print \"%s is not responding! Stopping to communicate.\"\n self.isConnected = False\n\n" }, { "alpha_fraction": 0.4909090995788574, "alphanum_fraction": 0.4909090995788574, "avg_line_length": 54, "blob_id": "6cd2339f3ef8ea6c8e53bab1c532edd2e3693b85", "content_id": "396a5a1f68ad7fb5aea5aa3fc34f2cdd0f56b2a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 55, "license_type": "no_license", "max_line_length": 54, "num_lines": 1, "path": "/src/phosphene/__init__.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "__all__ = [\"audio\", \"dsp\", \"signal\", \"graphs\", \"util\"]\n" }, { "alpha_fraction": 0.6441522836685181, "alphanum_fraction": 0.6627379655838013, "avg_line_length": 26.234567642211914, "blob_id": "11e9891c8bcad88acc8d470f1a1857f227113198", "content_id": "f099a51328a195d7ad3b7b6b3c4c6d901be73642", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2206, "license_type": "no_license", "max_line_length": 77, "num_lines": 81, "path": "/src/demo.py", "repo_name": "shashi/phosphene", "src_encoding": "UTF-8", "text": "import sys\nimport pdb\nimport pygame\nfrom pygame import display\nfrom pygame.draw import *\nimport scipy\nimport time\n\nfrom phosphene import audio, util, signalutil, signal\nfrom phosphene.graphs import barGraph, boopGraph, graphsGraphs\n\nfrom threading import Thread\n\nif len(sys.argv) < 2:\n print \"Usage: %s file.mp3\" % sys.argv[0]\n sys.exit(1)\nelse:\n fPath = sys.argv[1]\n\n# initialize PyGame\nSCREEN_DIMENSIONS = (640, 480)\npygame.init()\nsurface = display.set_mode(SCREEN_DIMENSIONS)\n\nsF, data = audio.read(fPath)\n\nsig = signal.Signal(data, sF)\nsig.A = signal.lift((data[:,0] + data[:,1]) / 2, True)\n\ndef beats(s):\n \"\"\" Extract beats in the signal in 4 different\n frequency ranges \"\"\"\n\n # quick note: s.avg4 is a decaying 4 channel fft\n # s.longavg4 decays at a slower rate\n # beat detection huristic:\n # beat occured if s.avg4 * threshold > s.longavg4\n\n threshold = 1.7\n return util.numpymap(\n lambda (x, y): 1 if x > threshold * y else 0,\n zip(s.avg4 * threshold, s.longavg4))\n\n# Lift the beats\nsig.beats = signal.lift(beats)\n# not sure if this can be called sustain.\n# blend gives a decay effect\nsig.sustain = signalutil.blend(beats, 0.7)\n\ndef graphsProcess(s):\n # clear screen\n surface.fill((0, 0, 0))\n # draw a decaying fft differential and the beats in the full\n # pygame window.\n graphsGraphs([\n barGraph(s.avg12rel / 10),\n boopGraph(s.beats),\n boopGraph(s.sustain)\n ])(surface, (0, 0) + SCREEN_DIMENSIONS)\n # affect the window\n display.update()\n\ndef repl():\n \"\"\" call this function to give you a pdb shell\n while the program is running. You will be\n dropped in the current context. \"\"\"\n\n def replFunc():\n pdb.set_trace()\n\n replThread = Thread(target=replFunc)\n replThread.start()\n#repl()\n\n# apply utility \"lift\"s -- this sets up signal.avgN and longavgN variables\nsignalutil.setup(sig)\nsoundObj = audio.makeSound(sF, data)\n # make a pygame Sound object from the data\nsoundObj.play() # start playing it. This is non-blocking\n# perceive signal at 90 fps (or lesser when not possible)\nsignal.perceive([graphsProcess], sig, 90)\n" } ]
22
TaegamJung/mannam
https://github.com/TaegamJung/mannam
eb8e00668a611ab109b31bdc9b7db5f9dc70840d
427d9931782512381cfd77938367789405974efa
e77f07916bedcc39a241ed30ef1266783864998c
refs/heads/master
2020-06-12T22:44:36.897903
2019-06-29T21:48:55
2019-06-29T21:48:55
194,450,960
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7008281350135803, "alphanum_fraction": 0.7008281350135803, "avg_line_length": 29.619047164916992, "blob_id": "025a8e993695357921e6f0f71b27d6b941c808dd", "content_id": "6a784efc4dba25661aa064ef4edc8ebb39a0a407", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2140, "license_type": "no_license", "max_line_length": 115, "num_lines": 63, "path": "/main/views.py", "repo_name": "TaegamJung/mannam", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n# View에 Model(Post 게시글) 가져오기\nfrom .models import Post\n\nfrom django.views.generic.base import TemplateView\n\nfrom django.views.generic.edit import CreateView\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.urls import reverse_lazy\n\n\nfrom django.views.generic.edit import FormView\nfrom .forms import PostSearchForm\nfrom django.db.models import Q\nfrom django.shortcuts import render\n\n\nclass SearchFormView(FormView):\n form_class = PostSearchForm\n template_name = 'main/post_search.html'\n \n def form_valid(self, form):\n schWord = '%s' % self.request.POST['search_word']\n post_list = Post.objects.filter(Q(postname__icontains=schWord) | Q(contents__icontains=schWord)).distinct()\n \n context = {}\n context['form'] = form\n context['search_term'] = schWord\n context['object_list'] = post_list\n \n return render(self.request, self.template_name, context)\n \n\nclass UserCreateView(CreateView):\n template_name = 'registration/register.html'\n form_class = UserCreationForm\n success_url = reverse_lazy('register_done')\n \nclass UserCreateDone(TemplateView):\n template_name = 'registration/register_done.html'\n\n\n# index.html 페이지를 부르는 index 함수\nclass index(TemplateView):\n template_name = 'main/index.html'\n \n \n# blog.html 페이지를 부르는 blog 함수\ndef blog(request):\n # 모든 Post를 가져와 postlist에 저장합니다\n postlist = Post.objects.all()\n # blog.html 페이지를 열 때, 모든 Post인 postlist도 같이 가져옵니다 \n return render(request, 'main/blog.html', {'postlist': postlist})\n\n# blog의 게시글(posting)을 부르는 posting 함수\ndef posting(request, pk):\n # 게시글(Post) 중 primary_key를 이용해 하나의 게시글(post)를 찾습니다\n post = Post.objects.get(pk=pk)\n # posting.html 페이지를 열 때, 찾아낸 게시글(post)을 같이 가져옵니다 \n return render(request, 'main/posting.html', {'post': post})\n\ndef new_feed(request):\n return render(request, 'new_feed.html')\n\n\n\n" }, { "alpha_fraction": 0.42476189136505127, "alphanum_fraction": 0.43015873432159424, "avg_line_length": 34.40449523925781, "blob_id": "2e3909224505fba4a9a8aa40c8bfc11b56d353f8", "content_id": "a27efc51348ff9117e46eee0de3e3d11ad6d34c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 3304, "license_type": "no_license", "max_line_length": 208, "num_lines": 89, "path": "/main/templates/frame.html", "repo_name": "TaegamJung/mannam", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"ko\">\n<html>\n <head>\n <meta charset=\"UTF-8\">\n \n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n \n <!-- 페이지 별 title 설정-->\n <title>{% block title %}{% endblock %}</title>\n <!-- 필요한 파일 및 CDN을 추가합니다-->\n {% load staticfiles %}\n <!-- 다음에 css를 만져봅니다-->\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{% static \"css/frame.css\" %}\" />\n <link rel=\"stylesheet\" href=\"{% block extrastyle %}{% endblock %}\" />\n \n <!-- Bootstrap CSS -->\n <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\">\n \n \n </head>\n <body>\n \n <!-- 홈페이지 상단에 nav가 들어갑니다-->\n <nav class=\"navbar navbar-expand-lg navbar-light bg-light\">\n <a class=\"navbar-brand\" href=\"#\">\n <span style = \" font-size:2em; color: red;\">\n {% load static %}\n <img src=\"{% static 'mannambar.png' %}\" width=\"80\" height=\"80\">\n </span>\n </a>\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n\n <div class=\"collapse navbar-collapse\" id=\"navbarSupportedContent\">\n <ul class=\"navbar-nav mr-auto\">\n <li class=\"nav-item active\">\n <a class=\"nav-link\" href=\"/\">메인</a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link\" href=\"/blog\">게시판</a>\n </li>\n\n <li class=\"nav-item\">\n <a class=\"nav-link\" href=\"/search\" tabindex=\"-1\" aria-disabled=\"true\">검색</a>\n </li>\n </ul>\n <form class=\"form-inline my-2 my-lg-0\">\n \n <span class=\"navbar-text\">\n <!-- 회원가입 부분 -->\n <div id=\"header\">\n {% if user.is_active %}\n <h4>\n {% firstof user.get_short_name user.get_username %} |\n <a href=\"{% url 'password_change' %}\">Change Password</a> |\n <a href=\"{% url 'logout' %}\">Logout</a>&nbsp;&nbsp;\n </h4>\n {% else %}\n <h4>\n Welcome |\n <a href=\"{% url 'login' %}\">Login</a> |\n <a href=\"{% url 'register' %}\">Register</a>&nbsp;&nbsp;\n </h4>\n {% endif %}\n </div>\n </span>\n </form>\n </div>\n </nav>\n \n \n \n \n \n \n \n <!-- 각 앱에서 만드는 페이지로 채울 부분-->\n {% block content %}{% endblock %}\n <!-- footer가 있다면 사용할 부분 -->\n {% block footer %}{% endblock %}\n \n \n \n \n \n </body>\n</html>" } ]
2
hjtree0825/stroke_network_ctmc_simulations
https://github.com/hjtree0825/stroke_network_ctmc_simulations
e1758551aa8b7af9966d5fb01cff74930b8b6911
9e3346c39c49e3a7d319b0385ec5ff75134f6741
69faa881893e891460cd9521c2e4c81f3e1641af
refs/heads/main
2023-04-01T11:19:45.786982
2021-03-30T21:07:33
2021-03-30T21:07:33
351,876,843
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5324577689170837, "alphanum_fraction": 0.5969980955123901, "avg_line_length": 33.03947448730469, "blob_id": "15eb4b58617a73515564b0cf62e31bb5ee1de747", "content_id": "9d781bf58731a451dd45a3f4d263f190d08fe09b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2665, "license_type": "permissive", "max_line_length": 90, "num_lines": 76, "path": "/stroke_expanded_add_capacity.py", "repo_name": "hjtree0825/stroke_network_ctmc_simulations", "src_encoding": "UTF-8", "text": "from stroke_functions import *\r\n\r\n# Initialize\r\nT = 10000\r\nrepl_num = 100\r\n\r\nservice_rate_h = 1./7\r\nservice_rate_i = 1./3\r\n\r\nMean1_psc_cap = []\r\nSTD1_psc_cap = []\r\nMean2_psc_cap = []\r\nSTD2_psc_cap = []\r\nMean3_psc_cap = []\r\nSTD3_psc_cap = []\r\nMean4_psc_cap = []\r\nSTD4_psc_cap = []\r\nMean5_psc_cap = []\r\nSTD5_psc_cap = []\r\nMean6_psc_cap = []\r\nSTD6_psc_cap = []\r\n\r\ncc0 = 17 # number of CSC beds when transfer rate is 15%\r\ncc1 = 17 # number of CSC beds when transfer rate is 35%\r\ncc2 = 17 # number of CSC beds when transfer rate is 55%\r\n\r\nfor ph in np.arange(0.15, 0.66, 0.2):\r\n X_outer = []\r\n cc = csc_bed(ph, cc0, cc1, cc2)\r\n for iteration in np.arange(repl_num):\r\n Dist = queue_ext(ph, c1 = cc0, c2 = cc1, c3 = cc2, T = T)\r\n X_outer.append(Dist/T)\r\n \r\n if 0.14 <= ph <= 0.16:\r\n Mean1_psc_cap.append(np.mean(X_outer, axis = 0))\r\n STD1_psc_cap.append(np.std(X_outer, axis = 0))\r\n elif 0.24 <= ph <= 0.26:\r\n Mean2_psc_cap.append(np.mean(X_outer, axis = 0))\r\n STD2_psc_cap.append(np.std(X_outer, axis = 0))\r\n elif 0.34 <= ph <= 0.36:\r\n Mean3_psc_cap.append(np.mean(X_outer, axis = 0))\r\n STD3_psc_cap.append(np.std(X_outer, axis = 0))\r\n elif 0.44 <= ph <= 0.46:\r\n Mean4_psc_cap.append(np.mean(X_outer, axis = 0))\r\n STD4_psc_cap.append(np.std(X_outer, axis = 0))\r\n elif 0.54 <= ph <= 0.56:\r\n Mean5_psc_cap.append(np.mean(X_outer, axis = 0))\r\n STD5_psc_cap.append(np.std(X_outer, axis = 0))\r\n elif 0.64 <= ph <= 0.66:\r\n Mean6_psc_cap.append(np.mean(X_outer, axis = 0))\r\n STD6_psc_cap.append(np.std(X_outer, axis = 0))\r\n else:\r\n print(\"ERROR\")\r\n\r\nfig, (ax1, ax2, ax3) = plt.subplots(3, 1)\r\nfig.subplots_adjust(hspace=0.5)\r\nax1.bar(np.arange(cc0+1), Mean1_psc_cap[0], yerr = 1.96*STD1_psc_cap[0]/np.sqrt(repl_num))\r\nax2.bar(np.arange(cc1+1), Mean3_psc_cap[0], yerr = 1.96*STD3_psc_cap[0]/np.sqrt(repl_num))\r\nax3.bar(np.arange(cc2+1), Mean5_psc_cap[0], yerr = 1.96*STD5_psc_cap[0]/np.sqrt(repl_num))\r\nax1.title.set_text('(a)')\r\nax2.title.set_text('(b)')\r\nax3.title.set_text('(c)')\r\nfig.text(0.5, 0.0, 'Bed occupancy', ha='center')\r\nfig.text(0.0, 0.5, 'Occupancy probability', va='center', rotation='vertical')\r\nplt.savefig(\"5_bed_distribution_add_psc_cap.pdf\")\r\nplt.savefig(\"5_bed_distribution_add_psc_cap.jpg\")\r\n\r\nsave_list = [Mean1_psc_cap, Mean3_psc_cap, Mean5_psc_cap]\r\nopen_file = open(\"base_psc_cap_mean.pkl\", \"wb\")\r\npickle.dump(save_list, open_file)\r\nopen_file.close()\r\n\r\nsave_list = [STD1_psc_cap, STD3_psc_cap, STD5_psc_cap]\r\nopen_file = open(\"base_psc_cap_std.pkl\", \"wb\")\r\npickle.dump(save_list, open_file)\r\nopen_file.close()\r\n\r\n" }, { "alpha_fraction": 0.42383071780204773, "alphanum_fraction": 0.455258846282959, "avg_line_length": 33.28099060058594, "blob_id": "d14ff5e8b1fd5e6349b315eb081240022b327327", "content_id": "3e6d6271f6568a078348566454fc76c8fcaed368", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25614, "license_type": "permissive", "max_line_length": 181, "num_lines": 726, "path": "/stroke_functions.py", "repo_name": "hjtree0825/stroke_network_ctmc_simulations", "src_encoding": "UTF-8", "text": "from stroke_source import *\r\n\r\ng = r.Random(1234)\r\n\r\ndef next_arrival(arrival_rate):\r\n U = g.uniform(0,1)\r\n arrival_time = -1./arrival_rate * m.log(U)\r\n\r\n return arrival_time\r\n\r\ndef next_service(service_rate):\r\n U = g.uniform(0,1)\r\n service_time = -1./service_rate * m.log(U)\r\n\r\n return service_time\r\n\r\ndef redirect(p):\r\n U = g.uniform(0,1)\r\n if p >= U:\r\n red = 1\r\n else:\r\n red = 0\r\n return(red)\r\n\r\ndef countX(lst, x): \r\n count = 0\r\n for ele in lst: \r\n if (ele == x): \r\n count = count + 1\r\n return count \r\n\r\ndef queue_base_only(ph, arrival_rate_p_h = 2.0*0.15, arrival_rate_p_i = 2.0*0.85,\r\n arrival_rate_c_h = 3.0*0.15, arrival_rate_c_i = 3.0*0.85,\r\n service_rate_h = 1./7, service_rate_i = 1./3,\r\n c1 = 15, c2 = 15, c3 = 15,\r\n psc1_tr_h = 0.95,\r\n psc2_tr_h = 0.95, psc2_tr_i = 0.15,\r\n psc3_tr_h = 0.95, psc3_tr_i = 0.15,\r\n T = 1000):\r\n # Initialize\r\n pi = ph\r\n patid = 0\r\n red_prop_h1 = psc1_tr_h # ph\r\n red_prop_i1 = pi\r\n red_prop_h2 = psc2_tr_h # 0.15\r\n red_prop_i2 = psc2_tr_i # 0.15\r\n red_prop_h3 = psc3_tr_h # 0.15\r\n red_prop_i3 = psc3_tr_i # 0.15\r\n Q = []\r\n X = []\r\n if 0.14 <= ph <= 0.16:\r\n cc = c1\r\n elif 0.24 <= ph <= 0.26:\r\n cc = cc0\r\n elif 0.34 <= ph <= 0.36:\r\n cc = c2\r\n elif 0.44 <= ph <= 0.46:\r\n cc = cc0\r\n elif 0.54 <= ph <= 0.56:\r\n cc = c3\r\n elif 0.64 <= ph <= 0.66:\r\n cc = cc0\r\n else:\r\n print(\"ERROR\", ph)\r\n sent = 0\r\n overflown = 0\r\n #####\r\n # Degugging\r\n #####\r\n CSC = []\r\n csc_entered = 0\r\n total_busy_serv1 = 0\r\n #####\r\n LenQ = []\r\n LenX = []\r\n Time = []\r\n Dist = np.zeros(cc+1)\r\n\r\n next_arrival_P1_h = next_arrival(arrival_rate_p_h)\r\n next_arrival_P1_i = next_arrival(arrival_rate_p_i)\r\n next_arrival_P2_h = next_arrival(arrival_rate_p_h)\r\n next_arrival_P2_i = next_arrival(arrival_rate_p_i)\r\n next_arrival_P3_h = next_arrival(arrival_rate_p_h)\r\n next_arrival_P3_i = next_arrival(arrival_rate_p_i)\r\n next_arrival_C_h = next_arrival(arrival_rate_c_h)\r\n next_arrival_C_i = next_arrival(arrival_rate_c_i)\r\n next_complete = m.inf\r\n Event = [next_arrival_P1_h, next_arrival_P1_i, next_arrival_P2_h, next_arrival_P2_i, next_arrival_P3_h, next_arrival_P3_i, next_arrival_C_h, next_arrival_C_i, next_complete]\r\n\r\n\r\n # Next event\r\n t = min(Event)\r\n\r\n while t < T:\r\n Time.append(t)\r\n LenQ.append(len(Q))\r\n LenX.append(len(X))\r\n\r\n Update_vec = np.zeros(cc + 1)\r\n Update_vec[len(X)] = 1\r\n\r\n if t == next_arrival_P1_h:\r\n patid += 1\r\n if redirect(red_prop_h1) == 1:\r\n sent += 1\r\n stype = 1\r\n if len(X) >= cc:\r\n Q.append([patid, stype]) # type == 1: hem; type == 2: isch\r\n else:\r\n LOS = next_service(service_rate_h)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P1_h = t + next_arrival(arrival_rate_p_h)\r\n elif t == next_arrival_P1_i:\r\n patid += 1\r\n if redirect(red_prop_i1) == 1:\r\n sent += 1\r\n stype = 2\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_i)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P1_i = t + next_arrival(arrival_rate_p_i)\r\n\r\n elif t == next_arrival_P2_h:\r\n patid += 1\r\n if redirect(red_prop_h2) == 1:\r\n sent += 1\r\n stype = 1\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_h)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P2_h = t + next_arrival(arrival_rate_p_h)\r\n elif t == next_arrival_P2_i:\r\n patid += 1\r\n if redirect(red_prop_i2) == 1:\r\n sent += 1\r\n stype = 2\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_i)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P2_i = t + next_arrival(arrival_rate_p_i)\r\n\r\n elif t == next_arrival_P3_h:\r\n patid += 1\r\n if redirect(red_prop_h3) == 1:\r\n sent += 1\r\n stype = 1\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_h)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P3_h = t + next_arrival(arrival_rate_p_h)\r\n elif t == next_arrival_P3_i:\r\n patid += 1\r\n if redirect(red_prop_i3) == 1:\r\n sent += 1\r\n stype = 2\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_i)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P3_i = t + next_arrival(arrival_rate_p_i)\r\n\r\n elif t == next_arrival_C_h:\r\n patid += 1\r\n csc_entered += 1\r\n stype = 1\r\n if len(X) >= cc:\r\n overflown += 1\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_h)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_C_h = t + next_arrival(arrival_rate_c_h)\r\n elif t == next_arrival_C_i:\r\n patid += 1\r\n csc_entered += 1\r\n stype = 2\r\n if len(X) >= cc:\r\n overflown += 1\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_i)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_C_i = t + next_arrival(arrival_rate_c_i)\r\n\r\n elif t == next_complete:\r\n compl = min(sublist[2] for sublist in X)\r\n for i in np.arange(len(X)):\r\n if X[i][2] == compl:\r\n ind = i\r\n X.pop(ind)\r\n if len(X) > 0 :\r\n next_complete = min(sublist[2] for sublist in X)\r\n else:\r\n next_complete = m.inf\r\n\r\n Event = [next_arrival_P1_h, next_arrival_P1_i, next_arrival_P2_h, next_arrival_P2_i, next_arrival_P3_h, next_arrival_P3_i, next_arrival_C_h, next_arrival_C_i, next_complete]\r\n tp = t\r\n t = min(Event)\r\n total_busy_serv1 = total_busy_serv1 + len(X)*(t-tp)\r\n Dist = Dist + Update_vec * (t - tp)\r\n\r\n if len(X) >= cc + 1:\r\n print(\"ERROR!\")\r\n break\r\n\r\n return(Dist, total_busy_serv1)\r\n\r\ndef queue(ph, arrival_rate_p_h = 2.0*0.15, arrival_rate_p_i = 2.0*0.85,\r\n arrival_rate_c_h = 3.0*0.15, arrival_rate_c_i = 3.0*0.85,\r\n service_rate_h = 1./7, service_rate_i = 1./3,\r\n c1 = 15, c2 = 15, c3 = 15,\r\n psc1_tr_h = 0.95,\r\n psc2_tr_h = 0.95, psc2_tr_i = 0.15,\r\n psc3_tr_h = 0.95, psc3_tr_i = 0.15,\r\n T = 1000):\r\n # Initialize\r\n pi = ph\r\n patid = 0\r\n red_prop_h1 = psc1_tr_h # ph\r\n red_prop_i1 = pi\r\n red_prop_h2 = psc2_tr_h # 0.15\r\n red_prop_i2 = psc2_tr_i # 0.15\r\n red_prop_h3 = psc3_tr_h # 0.15\r\n red_prop_i3 = psc3_tr_i # 0.15\r\n Q = []\r\n X = []\r\n if 0.14 <= ph <= 0.16:\r\n cc = c1\r\n elif 0.24 <= ph <= 0.26:\r\n cc = cc0\r\n elif 0.34 <= ph <= 0.36:\r\n cc = c2\r\n elif 0.44 <= ph <= 0.46:\r\n cc = cc0\r\n elif 0.54 <= ph <= 0.56:\r\n cc = c3\r\n elif 0.64 <= ph <= 0.66:\r\n cc = cc0\r\n else:\r\n print(\"ERROR\", ph)\r\n sent = 0\r\n overflown = 0\r\n #####\r\n # Degugging\r\n #####\r\n CSC = []\r\n csc_entered = 0\r\n total_busy_serv1 = 0\r\n #####\r\n LenQ = []\r\n LenX = []\r\n Time = []\r\n Dist = np.zeros(cc+1)\r\n\r\n next_arrival_P1_h = next_arrival(arrival_rate_p_h)\r\n next_arrival_P1_i = next_arrival(arrival_rate_p_i)\r\n next_arrival_P2_h = next_arrival(arrival_rate_p_h)\r\n next_arrival_P2_i = next_arrival(arrival_rate_p_i)\r\n next_arrival_P3_h = next_arrival(arrival_rate_p_h)\r\n next_arrival_P3_i = next_arrival(arrival_rate_p_i)\r\n next_arrival_C_h = next_arrival(arrival_rate_c_h)\r\n next_arrival_C_i = next_arrival(arrival_rate_c_i)\r\n next_complete = m.inf\r\n Event = [next_arrival_P1_h, next_arrival_P1_i, next_arrival_P2_h, next_arrival_P2_i, next_arrival_P3_h, next_arrival_P3_i, next_arrival_C_h, next_arrival_C_i, next_complete]\r\n\r\n\r\n # Next event\r\n t = min(Event)\r\n\r\n while t < T:\r\n Time.append(t)\r\n LenQ.append(len(Q))\r\n LenX.append(len(X))\r\n\r\n Update_vec = np.zeros(cc + 1)\r\n Update_vec[len(X)] = 1\r\n\r\n if t == next_arrival_P1_h:\r\n patid += 1\r\n if redirect(red_prop_h1) == 1:\r\n sent += 1\r\n stype = 1\r\n if len(X) >= cc:\r\n Q.append([patid, stype]) # type == 1: hem; type == 2: isch\r\n else:\r\n LOS = next_service(service_rate_h)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P1_h = t + next_arrival(arrival_rate_p_h)\r\n elif t == next_arrival_P1_i:\r\n patid += 1\r\n if redirect(red_prop_i1) == 1:\r\n sent += 1\r\n stype = 2\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_i)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P1_i = t + next_arrival(arrival_rate_p_i)\r\n\r\n elif t == next_arrival_P2_h:\r\n patid += 1\r\n if redirect(red_prop_h2) == 1:\r\n sent += 1\r\n stype = 1\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_h)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P2_h = t + next_arrival(arrival_rate_p_h)\r\n elif t == next_arrival_P2_i:\r\n patid += 1\r\n if redirect(red_prop_i2) == 1:\r\n sent += 1\r\n stype = 2\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_i)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P2_i = t + next_arrival(arrival_rate_p_i)\r\n\r\n elif t == next_arrival_P3_h:\r\n patid += 1\r\n if redirect(red_prop_h3) == 1:\r\n sent += 1\r\n stype = 1\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_h)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P3_h = t + next_arrival(arrival_rate_p_h)\r\n elif t == next_arrival_P3_i:\r\n patid += 1\r\n if redirect(red_prop_i3) == 1:\r\n sent += 1\r\n stype = 2\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_i)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P3_i = t + next_arrival(arrival_rate_p_i)\r\n\r\n elif t == next_arrival_C_h:\r\n patid += 1\r\n csc_entered += 1\r\n stype = 1\r\n if len(X) >= cc:\r\n overflown += 1\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_h)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_C_h = t + next_arrival(arrival_rate_c_h)\r\n elif t == next_arrival_C_i:\r\n patid += 1\r\n csc_entered += 1\r\n stype = 2\r\n if len(X) >= cc:\r\n overflown += 1\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_i)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_C_i = t + next_arrival(arrival_rate_c_i)\r\n\r\n elif t == next_complete:\r\n compl = min(sublist[2] for sublist in X)\r\n for i in np.arange(len(X)):\r\n if X[i][2] == compl:\r\n ind = i\r\n X.pop(ind)\r\n if len(X) > 0 :\r\n next_complete = min(sublist[2] for sublist in X)\r\n else:\r\n next_complete = m.inf\r\n\r\n Event = [next_arrival_P1_h, next_arrival_P1_i, next_arrival_P2_h, next_arrival_P2_i, next_arrival_P3_h, next_arrival_P3_i, next_arrival_C_h, next_arrival_C_i, next_complete]\r\n tp = t\r\n t = min(Event)\r\n total_busy_serv1 = total_busy_serv1 + len(X)*(t-tp)\r\n Dist = Dist + Update_vec * (t - tp)\r\n\r\n if len(X) >= cc + 1:\r\n print(\"ERROR!\")\r\n break\r\n\r\n return(Dist)\r\n\r\ndef csc_bed(ph, cc0, cc1, cc2):\r\n if 0.14 <= ph <= 0.16:\r\n cc = cc0\r\n elif 0.24 <= ph <= 0.26:\r\n cc = cc0\r\n elif 0.34 <= ph <= 0.36:\r\n cc = cc0\r\n elif 0.44 <= ph <= 0.46:\r\n cc = cc0\r\n elif 0.54 <= ph <= 0.56:\r\n cc = cc0\r\n elif 0.64 <= ph <= 0.66:\r\n cc = cc0\r\n else:\r\n print(\"error\")\r\n return(cc)\r\n\r\ndef queue_ext(ph, arrival_rate_p_h = 2.0*0.15, arrival_rate_p_i = 2.0*0.85,\r\n arrival_rate_c_h = 3.0*0.15, arrival_rate_c_i = 3.0*0.85,\r\n service_rate_h = 1./7, service_rate_i = 1./3,\r\n c1 = 15, c2 = 15, c3 = 15,\r\n psc1_tr_h = 0.95,\r\n psc2_tr_h = 0.95, psc2_tr_i = 0.15,\r\n psc3_tr_h = 0.95, psc3_tr_i = 0.15,\r\n psc4_tr_h = 0.95, psc4_tr_i = 0.15,\r\n T = 1000):\r\n # Initialize\r\n pi = ph\r\n patid = 0\r\n red_prop_h1 = psc1_tr_h # ph\r\n red_prop_i1 = pi\r\n red_prop_h2 = psc2_tr_h\r\n red_prop_i2 = psc2_tr_i\r\n red_prop_h3 = psc3_tr_h\r\n red_prop_i3 = psc3_tr_i\r\n red_prop_h4 = psc4_tr_h\r\n red_prop_i4 = psc4_tr_i\r\n Q = []\r\n X = []\r\n if 0.14 <= ph <= 0.16:\r\n cc = c1\r\n elif 0.24 <= ph <= 0.26:\r\n cc = cc0\r\n elif 0.34 <= ph <= 0.36:\r\n cc = c2\r\n elif 0.44 <= ph <= 0.46:\r\n cc = cc0\r\n elif 0.54 <= ph <= 0.56:\r\n cc = c3\r\n elif 0.64 <= ph <= 0.66:\r\n cc = cc0\r\n else:\r\n print(\"ERROR\", ph)\r\n sent = 0\r\n overflown = 0\r\n #####\r\n # Degugging\r\n #####\r\n CSC = []\r\n csc_entered = 0\r\n total_busy_serv1 = 0\r\n #####\r\n LenQ = []\r\n LenX = []\r\n Time = []\r\n Dist = np.zeros(cc+1)\r\n\r\n next_arrival_P1_h = next_arrival(arrival_rate_p_h)\r\n next_arrival_P1_i = next_arrival(arrival_rate_p_i)\r\n next_arrival_P2_h = next_arrival(arrival_rate_p_h)\r\n next_arrival_P2_i = next_arrival(arrival_rate_p_i)\r\n next_arrival_P3_h = next_arrival(arrival_rate_p_h)\r\n next_arrival_P3_i = next_arrival(arrival_rate_p_i)\r\n next_arrival_P4_h = next_arrival(arrival_rate_p_h)\r\n next_arrival_P4_i = next_arrival(arrival_rate_p_i)\r\n next_arrival_C_h = next_arrival(arrival_rate_c_h)\r\n next_arrival_C_i = next_arrival(arrival_rate_c_i)\r\n next_complete = m.inf\r\n Event = [\r\n next_arrival_P1_h, next_arrival_P1_i,\r\n next_arrival_P2_h, next_arrival_P2_i,\r\n next_arrival_P3_h, next_arrival_P3_i,\r\n next_arrival_P4_h, next_arrival_P4_i,\r\n next_arrival_C_h, next_arrival_C_i,\r\n next_complete\r\n ]\r\n\r\n\r\n # Next event\r\n t = min(Event)\r\n\r\n while t < T:\r\n Time.append(t)\r\n LenQ.append(len(Q))\r\n LenX.append(len(X))\r\n\r\n Update_vec = np.zeros(cc + 1)\r\n Update_vec[len(X)] = 1\r\n\r\n if t == next_arrival_P1_h:\r\n patid += 1\r\n if redirect(red_prop_h1) == 1:\r\n sent += 1\r\n stype = 1\r\n if len(X) >= cc:\r\n Q.append([patid, stype]) # type == 1: hem; type == 2: isch\r\n else:\r\n LOS = next_service(service_rate_h)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P1_h = t + next_arrival(arrival_rate_p_h)\r\n elif t == next_arrival_P1_i:\r\n patid += 1\r\n if redirect(red_prop_i1) == 1:\r\n sent += 1\r\n stype = 2\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_i)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P1_i = t + next_arrival(arrival_rate_p_i)\r\n\r\n elif t == next_arrival_P2_h:\r\n patid += 1\r\n if redirect(red_prop_h2) == 1:\r\n sent += 1\r\n stype = 1\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_h)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P2_h = t + next_arrival(arrival_rate_p_h)\r\n elif t == next_arrival_P2_i:\r\n patid += 1\r\n if redirect(red_prop_i2) == 1:\r\n sent += 1\r\n stype = 2\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_i)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P2_i = t + next_arrival(arrival_rate_p_i)\r\n\r\n elif t == next_arrival_P3_h:\r\n patid += 1\r\n if redirect(red_prop_h3) == 1:\r\n sent += 1\r\n stype = 1\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_h)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P3_h = t + next_arrival(arrival_rate_p_h)\r\n elif t == next_arrival_P3_i:\r\n patid += 1\r\n if redirect(red_prop_i3) == 1:\r\n sent += 1\r\n stype = 2\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_i)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P3_i = t + next_arrival(arrival_rate_p_i)\r\n \r\n elif t == next_arrival_P4_h:\r\n patid += 1\r\n if redirect(red_prop_h4) == 1:\r\n sent += 1\r\n stype = 1\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_h)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P4_h = t + next_arrival(arrival_rate_p_h)\r\n elif t == next_arrival_P4_i:\r\n patid += 1\r\n if redirect(red_prop_i4) == 1:\r\n sent += 1\r\n stype = 2\r\n if len(X) >= cc:\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_i)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_P4_i = t + next_arrival(arrival_rate_p_i)\r\n\r\n elif t == next_arrival_C_h:\r\n patid += 1\r\n csc_entered += 1\r\n stype = 1\r\n if len(X) >= cc:\r\n overflown += 1\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_h)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_C_h = t + next_arrival(arrival_rate_c_h)\r\n elif t == next_arrival_C_i:\r\n patid += 1\r\n csc_entered += 1\r\n stype = 2\r\n if len(X) >= cc:\r\n overflown += 1\r\n Q.append([patid, stype])\r\n else:\r\n LOS = next_service(service_rate_i)\r\n X.append([patid, stype, t + LOS])\r\n next_complete = min(sublist[2] for sublist in X)\r\n next_arrival_C_i = t + next_arrival(arrival_rate_c_i)\r\n\r\n elif t == next_complete:\r\n compl = min(sublist[2] for sublist in X)\r\n for i in np.arange(len(X)):\r\n if X[i][2] == compl:\r\n ind = i\r\n X.pop(ind)\r\n if len(X) > 0 :\r\n next_complete = min(sublist[2] for sublist in X)\r\n else:\r\n next_complete = m.inf\r\n\r\n Event = [\r\n next_arrival_P1_h, next_arrival_P1_i,\r\n next_arrival_P2_h, next_arrival_P2_i,\r\n next_arrival_P3_h, next_arrival_P3_i,\r\n next_arrival_P4_h, next_arrival_P4_i,\r\n next_arrival_C_h, next_arrival_C_i,\r\n next_complete\r\n ]\r\n tp = t\r\n t = min(Event)\r\n total_busy_serv1 = total_busy_serv1 + len(X)*(t-tp)\r\n Dist = Dist + Update_vec * (t - tp)\r\n\r\n if len(X) >= cc + 1:\r\n print(\"ERROR!\")\r\n break\r\n\r\n return(Dist)\r\n\r\n \r\ndef queue_customization(\r\n psc_hemorrhagic, psc_ischemic,\r\n csc_hemorrhagic, csc_ischemic,\r\n LOS_hemorrhagic, LOS_ischemic,\r\n psc1_transfer_rate_hemorrhagic,\r\n psc1_transfer_rate_ischemic,\r\n psc2_transfer_rate_hemorrhagic,\r\n psc2_transfer_rate_ischemic,\r\n psc3_transfer_rate_hemorrhagic,\r\n psc3_transfer_rate_ischemic,\r\n csc_bed_capacity, T, repl_num):\r\n Mean = []\r\n STD = []\r\n X_outer = []\r\n\r\n for iteration in np.arange(repl_num):\r\n Dist = queue(\r\n c1 = csc_bed_capacity, c2 = csc_bed_capacity, c3 = csc_bed_capacity,\r\n arrival_rate_p_h = psc_hemorrhagic, arrival_rate_p_i = psc_ischemic,\r\n arrival_rate_c_h = csc_hemorrhagic, arrival_rate_c_i = csc_ischemic,\r\n service_rate_h = 1./LOS_hemorrhagic, service_rate_i = 1./LOS_ischemic,\r\n psc1_tr_h = psc1_transfer_rate_hemorrhagic, ph = psc1_transfer_rate_ischemic,\r\n psc2_tr_h = psc2_transfer_rate_hemorrhagic, psc2_tr_i = psc2_transfer_rate_ischemic,\r\n psc3_tr_h = psc3_transfer_rate_hemorrhagic, psc3_tr_i = psc3_transfer_rate_ischemic,\r\n T = T)\r\n X_outer.append(Dist/T)\r\n Mean.append(np.mean(X_outer, axis = 0))\r\n STD.append(np.std(X_outer, axis = 0))\r\n fig, (ax1) = plt.subplots(1, 1)\r\n fig.subplots_adjust(hspace=0.5)\r\n ax1.bar(np.arange(csc_bed_capacity+1), Mean[0], yerr = 1.96*STD[0]/np.sqrt(repl_num))\r\n #ax1.title.set_text('(a)')\r\n fig.text(0.5, 0.0, 'Bed occupancy', ha='center')\r\n fig.text(0.0, 0.5, 'Occupancy probability', va='center', rotation='vertical')\r\n plt.savefig(\"bed_distribution_cust.pdf\")\r\n plt.savefig(\"bed_distribution_cust.jpg\")\r\n\r\n plt.figure()\r\n plt.bar([psc1_transfer_rate_ischemic],\r\n [\r\n Mean[0][len(Mean[0])-1]\r\n ],\r\n yerr = [\r\n 1.96*STD[0][len(STD[0])-1]/np.sqrt(repl_num)\r\n ])\r\n plt.xlabel(\"Transfer rates at PSC 1\")\r\n plt.ylabel(\"Overflow probability\")\r\n plt.savefig(\"overflow_probability_cust.pdf\")\r\n plt.savefig(\"overflow_probability_cust.jpg\")\r\n\r\n mean_fin = Mean[0][len(Mean[0])-1]*100\r\n std_fin = 1.96*STD[0][len(STD[0])-1]/np.sqrt(repl_num)*100\r\n print(\"Overflow probability is {mean:.2f} +/- {CI:.2f}\" \\\r\n .format(mean = mean_fin, CI = std_fin))\r\n" }, { "alpha_fraction": 0.5913772583007812, "alphanum_fraction": 0.6591616868972778, "avg_line_length": 38.911766052246094, "blob_id": "d273e98d4705302de26ff538d15e0fa16db921b3", "content_id": "d4c03165a765f3708d89e8fdca926d19af4cb150", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4175, "license_type": "permissive", "max_line_length": 294, "num_lines": 102, "path": "/stroke_overall_comparison.py", "repo_name": "hjtree0825/stroke_network_ctmc_simulations", "src_encoding": "UTF-8", "text": "from stroke_functions import *\r\n\r\nrepl_num = 100\r\n\r\n# Base case\r\nopen_file = open(\"base_mean.pkl\", \"rb\")\r\nloaded_list = pickle.load(open_file)\r\nopen_file.close()\r\nMean1 = loaded_list[0]\r\nMean2 = loaded_list[1]\r\nMean3 = loaded_list[2]\r\n\r\nopen_file = open(\"base_std.pkl\", \"rb\")\r\nloaded_list = pickle.load(open_file)\r\nopen_file.close()\r\nSTD1 = loaded_list[0]\r\nSTD2 = loaded_list[1]\r\nSTD3 = loaded_list[2]\r\n\r\n# Base case + added capacity\r\nopen_file = open(\"base_cap_mean.pkl\", \"rb\")\r\nloaded_list = pickle.load(open_file)\r\nopen_file.close()\r\nMean1_cap = loaded_list[0]\r\nMean2_cap = loaded_list[1]\r\nMean3_cap = loaded_list[2]\r\n\r\nopen_file = open(\"base_cap_std.pkl\", \"rb\")\r\nloaded_list = pickle.load(open_file)\r\nopen_file.close()\r\nSTD1_cap = loaded_list[0]\r\nSTD2_cap = loaded_list[1]\r\nSTD3_cap = loaded_list[2]\r\n\r\n# Expanded case\r\nopen_file = open(\"base_psc_mean.pkl\", \"rb\")\r\nloaded_list = pickle.load(open_file)\r\nopen_file.close()\r\nMean1_psc = loaded_list[0]\r\nMean2_psc = loaded_list[1]\r\nMean3_psc = loaded_list[2]\r\n\r\nopen_file = open(\"base_psc_std.pkl\", \"rb\")\r\nloaded_list = pickle.load(open_file)\r\nopen_file.close()\r\nSTD1_psc = loaded_list[0]\r\nSTD2_psc = loaded_list[1]\r\nSTD3_psc = loaded_list[2]\r\n\r\n# Expanded case + added capacity\r\nopen_file = open(\"base_psc_cap_mean.pkl\", \"rb\")\r\nloaded_list = pickle.load(open_file)\r\nopen_file.close()\r\nMean1_psc_cap = loaded_list[0]\r\nMean2_psc_cap = loaded_list[1]\r\nMean3_psc_cap = loaded_list[2]\r\n\r\nopen_file = open(\"base_psc_cap_std.pkl\", \"rb\")\r\nloaded_list = pickle.load(open_file)\r\nopen_file.close()\r\nSTD1_psc_cap = loaded_list[0]\r\nSTD2_psc_cap = loaded_list[1]\r\nSTD3_psc_cap = loaded_list[2]\r\n\r\n# Expanded case + reduced transfer rates\r\nopen_file = open(\"base_psc_red_mean.pkl\", \"rb\")\r\nloaded_list = pickle.load(open_file)\r\nopen_file.close()\r\nMean1_psc_red = loaded_list[0]\r\nMean2_psc_red = loaded_list[1]\r\nMean3_psc_red = loaded_list[2]\r\n\r\nopen_file = open(\"base_psc_red_std.pkl\", \"rb\")\r\nloaded_list = pickle.load(open_file)\r\nopen_file.close()\r\nSTD1_psc_red = loaded_list[0]\r\nSTD2_psc_red = loaded_list[1]\r\nSTD3_psc_red = loaded_list[2]\r\n\r\nlabels = [\"0.15\", \"0.35\", \"0.55\"]\r\nM1 = [Mean1[0][len(Mean1[0])-1], Mean2[0][len(Mean2[0])-1], Mean3[0][len(Mean3[0])-1]]\r\nM2 = [Mean1_psc[0][len(Mean1_psc[0])-1], Mean2_psc[0][len(Mean2_psc[0])-1], Mean3_psc[0][len(Mean3_psc[0])-1]]\r\nM3 = [Mean1_psc_red[0][len(Mean1_psc_red[0])-1], Mean2_psc_red[0][len(Mean2_psc_red[0])-1], Mean3_psc_red[0][len(Mean3_psc_red[0])-1]]\r\nM4 = [Mean1_psc_cap[0][len(Mean1_psc_cap[0])-1], Mean2_psc_cap[0][len(Mean2_psc_cap[0])-1], Mean3_psc_cap[0][len(Mean3_psc_cap[0])-1]]\r\nx = np.arange(len(labels)) # the label locations\r\nwidth = 0.125 # the width of the bars\r\nfig, ax = plt.subplots(figsize=(12,8), dpi= 100)\r\nrects1 = ax.bar(x - 4.5*width/3, M1, width, yerr = [1.96*STD1[0][len(STD1[0])-1]/np.sqrt(repl_num), 1.96*STD2[0][len(STD2[0])-1]/np.sqrt(repl_num), 1.96*STD3[0][len(STD3[0])-1]/np.sqrt(repl_num)], label='Base case')\r\nrects2 = ax.bar(x - 1.5*width/3, M2, width, yerr = [1.96*STD1_psc[0][len(STD1_psc[0])-1]/np.sqrt(repl_num), 1.96*STD2_psc[0][len(STD2_psc[0])-1]/np.sqrt(repl_num), 1.96*STD3_psc[0][len(STD3_psc[0])-1]/np.sqrt(repl_num)], label='Expanded case')\r\nrects3 = ax.bar(x + 1.5*width/3, M3, width, yerr = [1.96*STD1_psc_red[0][len(STD1_psc_red[0])-1]/np.sqrt(repl_num), 1.96*STD2_psc_red[0][len(STD2_psc_red[0])-1]/np.sqrt(repl_num), 1.96*STD3_psc_red[0][len(STD3_psc_red[0])-1]/np.sqrt(repl_num)], label='Expanded case, reduced transfer')\r\nrects4 = ax.bar(x + 4.5*width/3, M4, width, yerr = [1.96*STD1_psc_cap[0][len(STD1_psc_cap[0])-1]/np.sqrt(repl_num), 1.96*STD2_psc_cap[0][len(STD2_psc_cap[0])-1]/np.sqrt(repl_num), 1.96*STD3_psc_cap[0][len(STD3_psc_cap[0])-1]/np.sqrt(repl_num)], label='Expanded case, additional Neuro-ICU beds')\r\n\r\n# Add some text for labels, title and custom x-axis tick labels, etc.\r\nax.set_ylabel('Overflow probability')\r\nax.set_ylabel('Transfer rates at PSC 1')\r\nax.set_title('Overflow probability by case')\r\nax.set_xticks(x)\r\nax.set_xticklabels(labels)\r\nax.set_yticks([0.00, 0.10, 0.20, 0.30, 0.40, 0.50])\r\nax.legend()\r\nplt.savefig(\"6_overflow_prob_by_case.pdf\")\r\nplt.savefig(\"6_overflow_prob_by_case.jpg\")\r\n\r\n" }, { "alpha_fraction": 0.5051020383834839, "alphanum_fraction": 0.5758928656578064, "avg_line_length": 31.677419662475586, "blob_id": "7cb098269066893add52b5e970a1259c882264d2", "content_id": "fe533753768d54a166a74044eccfa0c79d414122", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3136, "license_type": "permissive", "max_line_length": 82, "num_lines": 93, "path": "/stroke_expanded.py", "repo_name": "hjtree0825/stroke_network_ctmc_simulations", "src_encoding": "UTF-8", "text": "from stroke_functions import *\r\n\r\n# Initialize\r\nT = 10000\r\nrepl_num = 10\r\n\r\nservice_rate_h = 1./7\r\nservice_rate_i = 1./3\r\n\r\nMean1_psc = []\r\nSTD1_psc = []\r\nMean2_psc = []\r\nSTD2_psc = []\r\nMean3_psc = []\r\nSTD3_psc = []\r\nMean4_psc = []\r\nSTD4_psc = []\r\nMean5_psc = []\r\nSTD5_psc = []\r\nMean6_psc = []\r\nSTD6_psc = []\r\n\r\ncc0 = 15 # number of CSC beds when transfer rate is 15%\r\ncc1 = 15 # number of CSC beds when transfer rate is 35%\r\ncc2 = 15 # number of CSC beds when transfer rate is 55%\r\n\r\nfor ph in np.arange(0.15, 0.66, 0.2):\r\n X_outer = []\r\n cc = csc_bed(ph, cc0, cc1, cc2)\r\n for iteration in np.arange(repl_num):\r\n Dist = queue_ext(ph, c1 = cc0, c2 = cc1, c3 = cc2, T = T)\r\n X_outer.append(Dist/T)\r\n \r\n if 0.14 <= ph <= 0.16:\r\n Mean1_psc.append(np.mean(X_outer, axis = 0))\r\n STD1_psc.append(np.std(X_outer, axis = 0))\r\n elif 0.24 <= ph <= 0.26:\r\n Mean2_psc.append(np.mean(X_outer, axis = 0))\r\n STD2_psc.append(np.std(X_outer, axis = 0))\r\n elif 0.34 <= ph <= 0.36:\r\n Mean3_psc.append(np.mean(X_outer, axis = 0))\r\n STD3_psc.append(np.std(X_outer, axis = 0))\r\n elif 0.44 <= ph <= 0.46:\r\n Mean4_psc.append(np.mean(X_outer, axis = 0))\r\n STD4_psc.append(np.std(X_outer, axis = 0))\r\n elif 0.54 <= ph <= 0.56:\r\n Mean5_psc.append(np.mean(X_outer, axis = 0))\r\n STD5_psc.append(np.std(X_outer, axis = 0))\r\n elif 0.64 <= ph <= 0.66:\r\n Mean6_psc.append(np.mean(X_outer, axis = 0))\r\n STD6_psc.append(np.std(X_outer, axis = 0))\r\n else:\r\n print(\"ERROR\")\r\n\r\nfig, (ax1, ax2, ax3) = plt.subplots(3, 1)\r\nfig.subplots_adjust(hspace=0.5)\r\nax1.bar(np.arange(cc0+1), Mean1_psc[0], yerr = 1.96*STD1_psc[0]/np.sqrt(repl_num))\r\nax2.bar(np.arange(cc1+1), Mean3_psc[0], yerr = 1.96*STD3_psc[0]/np.sqrt(repl_num))\r\nax3.bar(np.arange(cc2+1), Mean5_psc[0], yerr = 1.96*STD5_psc[0]/np.sqrt(repl_num))\r\nax1.title.set_text('(a)')\r\nax2.title.set_text('(b)')\r\nax3.title.set_text('(c)')\r\nfig.text(0.5, 0.0, 'Bed occupancy', ha='center')\r\nfig.text(0.0, 0.5, 'Occupancy probability', va='center', rotation='vertical')\r\nplt.savefig(\"3_bed_distribution_add_psc.pdf\")\r\nplt.savefig(\"3_bed_distribution_add_psc.jpg\")\r\n\r\nplt.figure()\r\nplt.bar([\"0.15\", \"0.35\", \"0.55\"],\r\n [\r\n Mean1_psc[0][len(Mean1_psc[0])-1],\r\n Mean3_psc[0][len(Mean3_psc[0])-1],\r\n Mean5_psc[0][len(Mean5_psc[0])-1]\r\n ],\r\n yerr = [\r\n 1.96*STD1_psc[0][len(STD1_psc[0])-1]/np.sqrt(repl_num),\r\n 1.96*STD3_psc[0][len(STD3_psc[0])-1]/np.sqrt(repl_num),\r\n 1.96*STD5_psc[0][len(STD5_psc[0])-1]/np.sqrt(repl_num)\r\n ])\r\nplt.xlabel(\"Transfer rates at PSC 1\")\r\nplt.ylabel(\"Overflow probability\")\r\nplt.savefig(\"3_overflow_probability_add_psc.pdf\")\r\nplt.savefig(\"3_overflow_probability_add_psc.jpg\")\r\n\r\nsave_list = [Mean1_psc, Mean3_psc, Mean5_psc]\r\nopen_file = open(\"base_psc_mean.pkl\", \"wb\")\r\npickle.dump(save_list, open_file)\r\nopen_file.close()\r\n\r\nsave_list = [STD1_psc, STD3_psc, STD5_psc]\r\nopen_file = open(\"base_psc_std.pkl\", \"wb\")\r\npickle.dump(save_list, open_file)\r\nopen_file.close()\r\n\r\n\r\n" }, { "alpha_fraction": 0.8173515796661377, "alphanum_fraction": 0.8173515796661377, "avg_line_length": 29, "blob_id": "c66e372009d4f83fccbacf6f47863bd94df9fe6e", "content_id": "32657e4f444b6333c096fb63cb39cf97c227e038", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "permissive", "max_line_length": 35, "num_lines": 7, "path": "/stroke_main.py", "repo_name": "hjtree0825/stroke_network_ctmc_simulations", "src_encoding": "UTF-8", "text": "from stroke_functions import *\r\nimport stroke_base\r\nimport stroke_base_add_capacity\r\nimport stroke_expanded\r\nimport stroke_expanded_reduced_rate\r\nimport stroke_expanded_add_capacity\r\nimport stroke_overall_comparison\r\n\r\n" }, { "alpha_fraction": 0.7884615659713745, "alphanum_fraction": 0.7884615659713745, "avg_line_length": 19.200000762939453, "blob_id": "cd205bc4104ecf6209770b08046cc6ad2cdd52e4", "content_id": "039ebd38724b858e2105b6c21e82579654b1db9e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 104, "license_type": "permissive", "max_line_length": 31, "num_lines": 5, "path": "/stroke_source.py", "repo_name": "hjtree0825/stroke_network_ctmc_simulations", "src_encoding": "UTF-8", "text": "import numpy as np\r\nimport random as r\r\nimport math as m\r\nimport matplotlib.pyplot as plt\r\nimport pickle" }, { "alpha_fraction": 0.5068232417106628, "alphanum_fraction": 0.5775943994522095, "avg_line_length": 31.860214233398438, "blob_id": "eaf361a67aeec6b31bfd48d7b3e8f807e1a9f3c5", "content_id": "8c034eecd2ea9e6c0319edecd0321a16681c6085", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3151, "license_type": "permissive", "max_line_length": 82, "num_lines": 93, "path": "/stroke_base_add_capacity.py", "repo_name": "hjtree0825/stroke_network_ctmc_simulations", "src_encoding": "UTF-8", "text": "from stroke_functions import *\r\n\r\n# Initialize\r\nT = 10000\r\nrepl_num = 100\r\n\r\nservice_rate_h = 1./7\r\nservice_rate_i = 1./3\r\n\r\nMean1_cap = []\r\nSTD1_cap = []\r\nMean2_cap = []\r\nSTD2_cap = []\r\nMean3_cap = []\r\nSTD3_cap = []\r\nMean4_cap = []\r\nSTD4_cap = []\r\nMean5_cap = []\r\nSTD5_cap = []\r\nMean6_cap = []\r\nSTD6_cap = []\r\n\r\ncc0 = 15 # number of CSC beds when transfer rate is 15%\r\ncc1 = 16 # number of CSC beds when transfer rate is 35%\r\ncc2 = 17 # number of CSC beds when transfer rate is 55%\r\n\r\nfor ph in np.arange(0.15, 0.66, 0.2):\r\n X_outer = []\r\n cc = csc_bed(ph, cc0, cc1, cc2)\r\n for iteration in np.arange(repl_num):\r\n Dist = queue(ph, c1 = cc0, c2 = cc1, c3 = cc2, T = T)\r\n X_outer.append(Dist/T)\r\n \r\n if 0.14 <= ph <= 0.16:\r\n Mean1_cap.append(np.mean(X_outer, axis = 0))\r\n STD1_cap.append(np.std(X_outer, axis = 0))\r\n elif 0.24 <= ph <= 0.26:\r\n Mean2_cap.append(np.mean(X_outer, axis = 0))\r\n STD2_cap.append(np.std(X_outer, axis = 0))\r\n elif 0.34 <= ph <= 0.36:\r\n Mean3_cap.append(np.mean(X_outer, axis = 0))\r\n STD3_cap.append(np.std(X_outer, axis = 0))\r\n elif 0.44 <= ph <= 0.46:\r\n Mean4_cap.append(np.mean(X_outer, axis = 0))\r\n STD4_cap.append(np.std(X_outer, axis = 0))\r\n elif 0.54 <= ph <= 0.56:\r\n Mean5_cap.append(np.mean(X_outer, axis = 0))\r\n STD5_cap.append(np.std(X_outer, axis = 0))\r\n elif 0.64 <= ph <= 0.66:\r\n Mean6_cap.append(np.mean(X_outer, axis = 0))\r\n STD6_cap.append(np.std(X_outer, axis = 0))\r\n else:\r\n print(\"ERROR\")\r\n\r\nfig, (ax1, ax2, ax3) = plt.subplots(3, 1)\r\nfig.subplots_adjust(hspace=0.5)\r\nax1.bar(np.arange(cc0+1), Mean1_cap[0], yerr = 1.96*STD1_cap[0]/np.sqrt(repl_num))\r\nax2.bar(np.arange(cc1+1), Mean3_cap[0], yerr = 1.96*STD3_cap[0]/np.sqrt(repl_num))\r\nax3.bar(np.arange(cc2+1), Mean5_cap[0], yerr = 1.96*STD5_cap[0]/np.sqrt(repl_num))\r\nax1.title.set_text('(a)')\r\nax2.title.set_text('(b)')\r\nax3.title.set_text('(c)')\r\nfig.text(0.5, 0.0, 'Bed occupancy', ha='center')\r\nfig.text(0.0, 0.5, 'Occupancy probability', va='center', rotation='vertical')\r\nplt.savefig(\"2_bed_distribution_base_add_cap.pdf\")\r\nplt.savefig(\"2_bed_distribution_base_add_cap.jpg\")\r\n\r\nplt.figure()\r\nplt.bar([\"0.15\", \"0.35\", \"0.55\"],\r\n [\r\n Mean1_cap[0][len(Mean1_cap[0])-1],\r\n Mean3_cap[0][len(Mean3_cap[0])-1],\r\n Mean5_cap[0][len(Mean5_cap[0])-1]\r\n ],\r\n yerr = [\r\n 1.96*STD1_cap[0][len(STD1_cap[0])-1]/np.sqrt(repl_num),\r\n 1.96*STD3_cap[0][len(STD3_cap[0])-1]/np.sqrt(repl_num),\r\n 1.96*STD5_cap[0][len(STD5_cap[0])-1]/np.sqrt(repl_num)\r\n ])\r\nplt.xlabel(\"Transfer rates at PSC 1\")\r\nplt.ylabel(\"Overflow probability\")\r\nplt.savefig(\"2_overflow_probability_base_add_cap.pdf\")\r\nplt.savefig(\"2_overflow_probability_base_add_cap.jpg\")\r\n\r\nsave_list = [Mean1_cap, Mean3_cap, Mean5_cap]\r\nopen_file = open(\"base_cap_mean.pkl\", \"wb\")\r\npickle.dump(save_list, open_file)\r\nopen_file.close()\r\n\r\nsave_list = [STD1_cap, STD3_cap, STD5_cap]\r\nopen_file = open(\"base_cap_std.pkl\", \"wb\")\r\npickle.dump(save_list, open_file)\r\nopen_file.close()\r\n\r\n" }, { "alpha_fraction": 0.5084925889968872, "alphanum_fraction": 0.5746638178825378, "avg_line_length": 33.29999923706055, "blob_id": "62b5dd19149aad5d62080aa11829c1b6a909e56c", "content_id": "faf9d5add3989ee6353b9012ec032e519bbc2c9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2826, "license_type": "permissive", "max_line_length": 90, "num_lines": 80, "path": "/stroke_expanded_reduced_rate.py", "repo_name": "hjtree0825/stroke_network_ctmc_simulations", "src_encoding": "UTF-8", "text": "from stroke_functions import *\r\n\r\n# Initialize\r\nT = 10000\r\nrepl_num = 100\r\n\r\nservice_rate_h = 1./7\r\nservice_rate_i = 1./3\r\n\r\nMean1_psc_red = []\r\nSTD1_psc_red = []\r\nMean2_psc_red = []\r\nSTD2_psc_red = []\r\nMean3_psc_red = []\r\nSTD3_psc_red = []\r\nMean4_psc_red = []\r\nSTD4_psc_red = []\r\nMean5_psc_red = []\r\nSTD5_psc_red = []\r\nMean6_psc_red = []\r\nSTD6_psc_red = []\r\n\r\ncc0 = 15 # number of CSC beds when transfer rate is 15%\r\ncc1 = 15 # number of CSC beds when transfer rate is 35%\r\ncc2 = 15 # number of CSC beds when transfer rate is 55%\r\n\r\nfor ph in np.arange(0.15, 0.66, 0.2):\r\n X_outer = []\r\n cc = csc_bed(ph, cc0, cc1, cc2)\r\n for iteration in np.arange(repl_num):\r\n Dist = queue_ext(ph, c1 = cc0, c2 = cc1, c3 = cc2,\r\n psc2_tr_i = 0.025,\r\n psc3_tr_i = 0.025,\r\n psc4_tr_i = 0.025,\r\n T = T)\r\n X_outer.append(Dist/T)\r\n \r\n if 0.14 <= ph <= 0.16:\r\n Mean1_psc_red.append(np.mean(X_outer, axis = 0))\r\n STD1_psc_red.append(np.std(X_outer, axis = 0))\r\n elif 0.24 <= ph <= 0.26:\r\n Mean2_psc_red.append(np.mean(X_outer, axis = 0))\r\n STD2_psc_red.append(np.std(X_outer, axis = 0))\r\n elif 0.34 <= ph <= 0.36:\r\n Mean3_psc_red.append(np.mean(X_outer, axis = 0))\r\n STD3_psc_red.append(np.std(X_outer, axis = 0))\r\n elif 0.44 <= ph <= 0.46:\r\n Mean4_psc_red.append(np.mean(X_outer, axis = 0))\r\n STD4_psc_red.append(np.std(X_outer, axis = 0))\r\n elif 0.54 <= ph <= 0.56:\r\n Mean5_psc_red.append(np.mean(X_outer, axis = 0))\r\n STD5_psc_red.append(np.std(X_outer, axis = 0))\r\n elif 0.64 <= ph <= 0.66:\r\n Mean6_psc_red.append(np.mean(X_outer, axis = 0))\r\n STD6_psc_red.append(np.std(X_outer, axis = 0))\r\n else:\r\n print(\"ERROR\")\r\n\r\nfig, (ax1, ax2, ax3) = plt.subplots(3, 1)\r\nfig.subplots_adjust(hspace=0.5)\r\nax1.bar(np.arange(cc0+1), Mean1_psc_red[0], yerr = 1.96*STD1_psc_red[0]/np.sqrt(repl_num))\r\nax2.bar(np.arange(cc1+1), Mean3_psc_red[0], yerr = 1.96*STD3_psc_red[0]/np.sqrt(repl_num))\r\nax3.bar(np.arange(cc2+1), Mean5_psc_red[0], yerr = 1.96*STD5_psc_red[0]/np.sqrt(repl_num))\r\nax1.title.set_text('(a)')\r\nax2.title.set_text('(b)')\r\nax3.title.set_text('(c)')\r\nfig.text(0.5, 0.0, 'Bed occupancy', ha='center')\r\nfig.text(0.0, 0.5, 'Occupancy probability', va='center', rotation='vertical')\r\nplt.savefig(\"4_bed_distribution_add_psc_red.pdf\")\r\nplt.savefig(\"4_bed_distribution_add_psc_red.jpg\")\r\n\r\nsave_list = [Mean1_psc_red, Mean3_psc_red, Mean5_psc_red]\r\nopen_file = open(\"base_psc_red_mean.pkl\", \"wb\")\r\npickle.dump(save_list, open_file)\r\nopen_file.close()\r\n\r\nsave_list = [STD1_psc_red, STD3_psc_red, STD5_psc_red]\r\nopen_file = open(\"base_psc_red_std.pkl\", \"wb\")\r\npickle.dump(save_list, open_file)\r\nopen_file.close()\r\n\r\n" }, { "alpha_fraction": 0.49074503779411316, "alphanum_fraction": 0.5583063364028931, "avg_line_length": 29.093524932861328, "blob_id": "711ceb001951af1281167de7fd91a0efe164fa02", "content_id": "916fceb8c51f41a65e94bb81eebaa36484c24894", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4322, "license_type": "permissive", "max_line_length": 82, "num_lines": 139, "path": "/stroke_base.py", "repo_name": "hjtree0825/stroke_network_ctmc_simulations", "src_encoding": "UTF-8", "text": "from stroke_functions import *\r\n\r\n# Initialize\r\nT = 10000\r\nrepl_num = 100\r\n\r\nservice_rate_h = 1./7\r\nservice_rate_i = 1./3\r\n\r\nMean1 = []\r\nSTD1 = []\r\nMean2 = []\r\nSTD2 = []\r\nMean3 = []\r\nSTD3 = []\r\nMean4 = []\r\nSTD4 = []\r\nMean5 = []\r\nSTD5 = []\r\nMean6 = []\r\nSTD6 = []\r\n\r\nMeanBed1 = []\r\nMeanBed2 = []\r\nMeanBed3 = []\r\nMeanBed4 = []\r\nMeanBed5 = []\r\nMeanBed6 = []\r\nStdBed1 = []\r\nStdBed2 = []\r\nStdBed3 = []\r\nStdBed4 = []\r\nStdBed5 = []\r\nStdBed6 = []\r\n\r\ncc0 = 15 # number of CSC beds when transfer rate is 15%\r\ncc1 = 15 # number of CSC beds when transfer rate is 35%\r\ncc2 = 15 # number of CSC beds when transfer rate is 55%\r\n\r\nfor ph in np.arange(0.15, 0.66, 0.2):\r\n X_outer = []\r\n Mean_outer = []\r\n cc = csc_bed(ph, cc0, cc1, cc2)\r\n for iteration in np.arange(repl_num):\r\n Dist, busy_serv = queue_base_only(ph, c1 = cc0, c2 = cc1, c3 = cc2, T = T)\r\n X_outer.append(Dist/T)\r\n Mean_outer.append(busy_serv/T)\r\n \r\n if 0.14 <= ph <= 0.16:\r\n Mean1.append(np.mean(X_outer, axis = 0))\r\n STD1.append(np.std(X_outer, axis = 0))\r\n MeanBed1.append(np.mean(Mean_outer, axis = 0))\r\n StdBed1.append(np.std(Mean_outer, axis = 0))\r\n elif 0.24 <= ph <= 0.26:\r\n Mean2.append(np.mean(X_outer, axis = 0))\r\n STD2.append(np.std(X_outer, axis = 0))\r\n MeanBed2.append(np.mean(Mean_outer, axis = 0))\r\n StdBed2.append(np.std(Mean_outer, axis = 0))\r\n elif 0.34 <= ph <= 0.36:\r\n Mean3.append(np.mean(X_outer, axis = 0))\r\n STD3.append(np.std(X_outer, axis = 0))\r\n MeanBed3.append(np.mean(Mean_outer, axis = 0))\r\n StdBed3.append(np.std(Mean_outer, axis = 0))\r\n elif 0.44 <= ph <= 0.46:\r\n Mean4.append(np.mean(X_outer, axis = 0))\r\n STD4.append(np.std(X_outer, axis = 0))\r\n MeanBed4.append(np.mean(Mean_outer, axis = 0))\r\n StdBed4.append(np.std(Mean_outer, axis = 0))\r\n elif 0.54 <= ph <= 0.56:\r\n Mean5.append(np.mean(X_outer, axis = 0))\r\n STD5.append(np.std(X_outer, axis = 0))\r\n MeanBed5.append(np.mean(Mean_outer, axis = 0))\r\n StdBed5.append(np.std(Mean_outer, axis = 0))\r\n elif 0.64 <= ph <= 0.66:\r\n Mean6.append(np.mean(X_outer, axis = 0))\r\n STD6.append(np.std(X_outer, axis = 0))\r\n MeanBed6.append(np.mean(Mean_outer, axis = 0))\r\n StdBed6.append(np.std(Mean_outer, axis = 0))\r\n else:\r\n print(\"ERROR\")\r\n\r\nfig, (ax1, ax2, ax3) = plt.subplots(3, 1)\r\nfig.subplots_adjust(hspace=0.5)\r\nax1.bar(np.arange(cc0+1), Mean1[0], yerr = 1.96*STD1[0]/np.sqrt(repl_num))\r\nax2.bar(np.arange(cc1+1), Mean3[0], yerr = 1.96*STD3[0]/np.sqrt(repl_num))\r\nax3.bar(np.arange(cc2+1), Mean5[0], yerr = 1.96*STD5[0]/np.sqrt(repl_num))\r\nax1.title.set_text('(a)')\r\nax2.title.set_text('(b)')\r\nax3.title.set_text('(c)')\r\nfig.text(0.5, 0.0, 'Bed occupancy', ha='center')\r\nfig.text(0.0, 0.5, 'Occupancy probability', va='center', rotation='vertical')\r\nplt.savefig(\"1_bed_distribution_base.pdf\")\r\nplt.savefig(\"1_bed_distribution_base.jpg\")\r\n\r\nplt.figure()\r\nplt.bar([\"0.15\", \"0.35\", \"0.55\"],\r\n [\r\n Mean1[0][len(Mean1[0])-1],\r\n Mean3[0][len(Mean3[0])-1],\r\n Mean5[0][len(Mean5[0])-1]\r\n ],\r\n yerr = [\r\n 1.96*STD1[0][len(STD1[0])-1]/np.sqrt(repl_num),\r\n 1.96*STD3[0][len(STD3[0])-1]/np.sqrt(repl_num),\r\n 1.96*STD5[0][len(STD5[0])-1]/np.sqrt(repl_num)\r\n ])\r\nplt.xlabel(\"Transfer rates at PSC 1\")\r\nplt.ylabel(\"Overflow probability\")\r\nplt.savefig(\"1_overflow_probability_base.pdf\")\r\nplt.savefig(\"1_overflow_probability_base.jpg\")\r\n\r\nplt.figure()\r\nplt.bar([\"0.15\", \"0.35\", \"0.55\"],\r\n [\r\n MeanBed1[0],\r\n MeanBed3[0],\r\n MeanBed5[0]\r\n ],\r\n yerr = [\r\n 1.96*StdBed1[0]/np.sqrt(repl_num),\r\n 1.96*StdBed3[0]/np.sqrt(repl_num),\r\n 1.96*StdBed5[0]/np.sqrt(repl_num)\r\n ]\r\n )\r\nplt.xlabel(\"Transfer rates at PSC 1\")\r\nplt.ylabel(\"Mean number of beds occupied\")\r\nplt.savefig(\"1_mean_base.pdf\")\r\nplt.savefig(\"1_mean_base.jpg\")\r\n\r\n\r\nsave_list = [Mean1, Mean3, Mean5]\r\nopen_file = open(\"base_mean.pkl\", \"wb\")\r\npickle.dump(save_list, open_file)\r\nopen_file.close()\r\n\r\nsave_list = [STD1, STD3, STD5]\r\nopen_file = open(\"base_std.pkl\", \"wb\")\r\npickle.dump(save_list, open_file)\r\nopen_file.close()\r\n" }, { "alpha_fraction": 0.5276134014129639, "alphanum_fraction": 0.557692289352417, "avg_line_length": 29.169231414794922, "blob_id": "c1bd137082d001bd88e0fe06a0d3237cd58e903b", "content_id": "1bff7e6dc857a3daaa2559421a4bb757267a9785", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2028, "license_type": "permissive", "max_line_length": 76, "num_lines": 65, "path": "/stroke_customization.py", "repo_name": "hjtree0825/stroke_network_ctmc_simulations", "src_encoding": "UTF-8", "text": "from stroke_functions import *\r\n\r\n############################################################################\r\n############################################################################\r\n############################################################################\r\n\r\n# Simply change the numbers in this section.\r\n\r\n# LOS (in days)\r\nLOS_hemorrhagic = 7\r\nLOS_ischemic = 3\r\n\r\n# Number of beds at CSC Neuro-ICU\r\ncsc_bed_capacity = 15\r\n\r\n# Average daily number of stroke patients examined at PSC\r\npsc_hemorrhagic = 0.3\r\npsc_ischemic = 1.7\r\n\r\n# Average daily number of stroke patients examined at CSC\r\ncsc_hemorrhagic = 0.45\r\ncsc_ischemic = 2.55\r\n\r\n# Transfer rates\r\n# (i) PSC 1\r\n# hemorrhagic\r\npsc1_transfer_rate_hemorrhagic = 0.95\r\n# ischemic\r\npsc1_transfer_rate_ischemic = 0.15\r\n\r\n# (ii) PSC 2\r\n# hemorrhagic\r\npsc2_transfer_rate_hemorrhagic = 0.95\r\n# ischemic\r\npsc2_transfer_rate_ischemic = 0.15\r\n\r\n# (iii) PSC 3\r\n# hemorrhagic\r\npsc3_transfer_rate_hemorrhagic = 0.95\r\n# ischemic\r\npsc3_transfer_rate_ischemic = 0.15\r\n\r\n\r\n############################################################################\r\n############################################################################\r\n############################################################################\r\n\r\n# Initialize (no need to change, in general)\r\nT = 10000\r\nrepl_num = 100\r\n\r\n# Run simulations\r\nqueue_customization(\r\n\tpsc_hemorrhagic = psc_hemorrhagic, psc_ischemic = psc_ischemic,\r\n\tcsc_hemorrhagic = csc_hemorrhagic, csc_ischemic = csc_ischemic,\r\n\tLOS_hemorrhagic = LOS_hemorrhagic, LOS_ischemic = LOS_ischemic,\r\n\tpsc1_transfer_rate_hemorrhagic = psc1_transfer_rate_hemorrhagic,\r\n\tpsc1_transfer_rate_ischemic = psc1_transfer_rate_ischemic,\r\n\tpsc2_transfer_rate_hemorrhagic = psc2_transfer_rate_hemorrhagic,\r\n\tpsc2_transfer_rate_ischemic = psc2_transfer_rate_ischemic,\r\n\tpsc3_transfer_rate_hemorrhagic = psc3_transfer_rate_hemorrhagic,\r\n\tpsc3_transfer_rate_ischemic = psc3_transfer_rate_ischemic,\r\n\tcsc_bed_capacity = csc_bed_capacity,\r\n\tT = T, repl_num = repl_num\r\n\t)\r\n\r\n" }, { "alpha_fraction": 0.7713004350662231, "alphanum_fraction": 0.7757847309112549, "avg_line_length": 147.6666717529297, "blob_id": "0c80d75fdda02f4873b09fa9360b93362493777e", "content_id": "68c4c8b8699fbb57e7b80ab18dc0e4650803f82f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 446, "license_type": "permissive", "max_line_length": 410, "num_lines": 3, "path": "/README.md", "repo_name": "hjtree0825/stroke_network_ctmc_simulations", "src_encoding": "UTF-8", "text": "# stroke_network_ctmc_simulations\n\nAll the files except for \"stroke_customization.py\" are the codes used to generate results and figures in the paper. Should one need to replicate, run \"stroke_main.py\" file. \"stroke_customization.py\" is for customization, i.e., user-specific inputs. Currently, it represents a network of 1 CSC and 3 PSCs and does not scale (in a sense that to add/remove a PSC, one needs to edit the \"stroke_functions.py\" file.\n" } ]
11
MayankAgarwal/Word-ladder
https://github.com/MayankAgarwal/Word-ladder
62c25c2f4a6131c4905aa769db9103d655bf8392
bd414e37334fd0b7e9c64b382cb0d6dea4bc4fa4
dcffebf560db1771c8feee45e1472e50df276f60
refs/heads/master
2021-01-22T19:49:52.724604
2015-07-16T14:32:44
2015-07-16T14:32:44
39,198,691
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5570470094680786, "alphanum_fraction": 0.5610738396644592, "avg_line_length": 23.29347801208496, "blob_id": "331bda60d08936a2b020300d728bde564db64856", "content_id": "b42dc96b764d552dcd609420224e9bdcaebe3676", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2235, "license_type": "no_license", "max_line_length": 79, "num_lines": 92, "path": "/search/search.py", "repo_name": "MayankAgarwal/Word-ladder", "src_encoding": "UTF-8", "text": "''' Implements various search mechanisms '''\n\nfrom node import Node\nimport os\n\nclass Search(object):\n ''' Contains search methods '''\n\n def __init__(self, start_state, end_state):\n self.start_state = start_state\n self.end_state = end_state\n\n # Path to absolute english dictionary\n dir_path = os.path.dirname(os.path.abspath(__file__))\n self.dict_path = os.path.join(dir_path, \"resources\", \"wordlist.txt\")\n self.dict_path = os.path.normpath(self.dict_path)\n\n self.dictionary_list = self.load_dict_into_list()\n\n\n def load_dict_into_list(self):\n ''' Load dictionary into list '''\n\n wordlist = []\n try:\n f = open(self.dict_path, 'r')\n\n for word in f:\n wordlist.append(word.strip())\n\n return wordlist\n\n except IOError as _:\n pass\n\n finally:\n f.close()\n\n\n def astar_search(self):\n ''' Implements A-star search '''\n\n visited_words = []\n\n start_node = Node(self.start_state, 0, self.end_state)\n\n current_node = start_node\n\n fringe = [current_node]\n\n while not current_node.is_state_result():\n\n if not fringe:\n return \"ERROR: No path exists\"\n\n visited_words.append(current_node.state)\n\n next_nodes = current_node.get_next_nodes(self.dictionary_list)\n\n for node in next_nodes:\n if node.state in visited_words:\n continue\n else:\n fringe.append(node)\n\n fringe.remove(current_node)\n current_node = self.__get_least_cost_astar(fringe)\n\n return current_node\n\n\n @classmethod\n def __get_least_cost_astar(cls, fringe):\n ''' Returns the least costing element from fringe '''\n\n return sorted(fringe, key=lambda node: node.depth + node.h_distance)[0]\n\n\nif __name__ == '__main__':\n word1 = raw_input(\"Enter 1st word: \")\n word2 = raw_input(\"Enter 2nd word: \")\n\n temp = Search(word1, word2)\n result = temp.astar_search()\n path = []\n\n while result is not None:\n path.insert(0, result.state)\n result = result.parent\n\n\n print \" -> \".join(path)\n" }, { "alpha_fraction": 0.5348506569862366, "alphanum_fraction": 0.5846372842788696, "avg_line_length": 22.433332443237305, "blob_id": "12822d8ca2833661f2a6b3ec087161479781878e", "content_id": "3ba50999072a195c33ab61c38ce3419aa7e21630", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 703, "license_type": "no_license", "max_line_length": 72, "num_lines": 30, "path": "/search/heuristic.py", "repo_name": "MayankAgarwal/Word-ladder", "src_encoding": "UTF-8", "text": "''' Heuristic class holds the heuristic functions used for A* search '''\n\n\ndef levenshtein_distance(word1, word2, i=None, j=None):\n '''\n Returns the levenshtein distance between the two words\n Args:\n 1) word1: 1st word\n 2) word2: 2nd word\n '''\n\n if i is None:\n i = len(word1)\n if j is None:\n j = len(word2)\n\n if min(i, j) == 0:\n return max(i, j)\n\n comp1 = levenshtein_distance(word1, word2, i-1, j) + 1\n comp2 = levenshtein_distance(word1, word2, i, j-1) + 1\n\n indicator = 1\n\n if word1[i-1] == word2[j-1]:\n indicator = 0\n\n comp3 = levenshtein_distance(word1, word2, i-1, j-1) + indicator\n\n return min(comp1, comp2, comp3)\n" }, { "alpha_fraction": 0.5940848588943481, "alphanum_fraction": 0.5962280035018921, "avg_line_length": 30.472972869873047, "blob_id": "7ca4122bad155526cf1e38683fdb1be6803ee8b7", "content_id": "c875c994ff79744f8650af88e0445f94e74dfb1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2333, "license_type": "no_license", "max_line_length": 87, "num_lines": 74, "path": "/search/node.py", "repo_name": "MayankAgarwal/Word-ladder", "src_encoding": "UTF-8", "text": "''' Search specification for Word ladder problem '''\n\nimport os\nimport re\nimport heuristic\n\nclass Node(object):\n ''' Represents a node in the word ladder graph i.e. a word '''\n\n def __init__(self, state, depth, result_state, parent=None):\n\n self.state = state # current state\n self.depth = depth # Depth of the current state in search graph\n self.result_state = result_state # Result state the search is looking for\n\n # parent node of the current state\n self.parent = parent\n\n # Heuristic distance between current state and result state\n self.h_distance = heuristic.levenshtein_distance(self.state, self.result_state)\n\n\n def is_state_result(self):\n ''' Returns True if the current state is the result state '''\n\n return self.state.strip().lower() == self.result_state.strip().lower()\n\n def __generate_adj_words_regex__(self):\n ''' \n Generates a regex that matches words adjacent (one character modification away \n from state)\n '''\n\n regex = []\n \n start_regex = r\"^\\w\" + self.state + r\"$\"\n end_regex = r\"^\" + self.state + r\"\\w$\"\n\n regex.append(start_regex)\n regex.append(end_regex)\n \n state_temp = \"^\" + self.state + \"$\"\n\n for i in xrange(1, len(state_temp)-1):\n mid_pos_regex = state_temp[0:i] + r\"\\w\" + state_temp[i+1:]\n regex.append(mid_pos_regex)\n\n return \"|\".join(regex)\n\n\n def __get_matching_words__(self, re_exp, wordlist):\n ''' Returns a list of words matching the passed regular expression '''\n\n search_regex = re.compile(re_exp, re.IGNORECASE)\n matching_words = []\n\n for word in wordlist:\n if search_regex.search(word) and word.lower() != self.state.lower():\n matching_words.append(word.strip())\n\n return matching_words\n\n\n def get_next_nodes(self, wordlist):\n ''' Returns the next nodes of this node. '''\n\n adjacent_nodes = []\n search_regex = self.__generate_adj_words_regex__()\n\n for matched_word in self.__get_matching_words__(search_regex, wordlist):\n node_temp = Node(matched_word, self.depth + 1, self.result_state, self)\n adjacent_nodes.append(node_temp)\n\n return adjacent_nodes\n " } ]
3
covertspatandemos/git_demo_2
https://github.com/covertspatandemos/git_demo_2
123fe18187af59b55839dbd93ecfef4d6d687b4b
e74641484002fa744198e6efd83dfb6f805ae5f4
7238dcf016f2fddba270c5d479bf4a297606ab52
refs/heads/main
2023-03-02T16:27:11.284023
2021-02-12T00:56:32
2021-02-12T00:56:32
338,136,419
0
0
null
2021-02-11T19:53:47
2021-02-11T23:19:55
2021-02-11T23:21:00
Python
[ { "alpha_fraction": 0.5263158082962036, "alphanum_fraction": 0.5639097690582275, "avg_line_length": 10.083333015441895, "blob_id": "b457ac1c15e8edb01ee875f8cbadfa5fd9ebd4e1", "content_id": "49b24a2d9225ad7ccc7dde55cb3ad65dc427b490", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 133, "license_type": "no_license", "max_line_length": 21, "num_lines": 12, "path": "/demo.py", "repo_name": "covertspatandemos/git_demo_2", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nprint('a')\nprint('b')\nprint('c')\nprint('w')\nprint('x')\nprint('1')\nprint('2')\nprint('3')\nprint('4')\nprint('5')\n" } ]
1
lukemadera/ml-learning
https://github.com/lukemadera/ml-learning
1e2fe5cfc897364c1e43feecde8478ca019d413a
5a6054442c85849b5f0c186c162276b38e0e4fed
d6c771fa0917faeee74d155fd39809c6d9bcc261
refs/heads/master
2022-07-09T09:45:43.667000
2019-10-26T06:08:20
2019-10-26T06:08:20
217,662,549
0
0
null
2019-10-26T05:49:46
2019-10-26T06:08:27
2022-06-21T23:14:14
Python
[ { "alpha_fraction": 0.5981665253639221, "alphanum_fraction": 0.614973247051239, "avg_line_length": 42.153846740722656, "blob_id": "1dfb43f2f868ccb0562482f165e3262ce16f26e3", "content_id": "162920a0e2b2071354acdb77f2c076180209382e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11781, "license_type": "no_license", "max_line_length": 126, "num_lines": 273, "path": "/breakout_ai_a2c.py", "repo_name": "lukemadera/ml-learning", "src_encoding": "UTF-8", "text": "import numpy as np\nimport os\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.autograd as autograd\n\n# Implementing a function to make sure the models share the same gradient\n# def ensure_shared_grads(model, shared_model):\n# for param, shared_param in zip(model.parameters(), shared_model.parameters()):\n# if shared_param.grad is not None:\n# return\n# shared_param._grad = param.grad\n\nclass ActorCritic(nn.Module):\n def __init__(self, numActions, numInputs=84):\n super(ActorCritic, self).__init__()\n\n # self.conv1 = nn.Conv2d(numInputs, 32, kernel_size=8, stride=4)\n # self.conv2 = nn.Conv2d(32, 64, kernel_size=4, stride=2)\n # self.conv3 = nn.Conv2d(64, 64, kernel_size=3, stride=1)\n\n self.conv1 = nn.Conv2d(numInputs, 32, 3, stride=2, padding=1)\n self.conv2 = nn.Conv2d(32, 32, 3, stride=2, padding=1)\n self.conv3 = nn.Conv2d(32, 32, 3, stride=2, padding=1)\n self.conv4 = nn.Conv2d(32, 32, 3, stride=2, padding=1)\n\n self.linear1 = nn.Linear(192, 512)\n\n self.actor = nn.Linear(512, numActions)\n self.critic = nn.Linear(512, 1)\n \n # In a PyTorch model, you only have to define the forward pass.\n # PyTorch computes the backwards pass for you!\n def forward(self, x):\n # Normalize image pixels (from rgb 0 to 255) to between 0 and 1.\n x = x / 255.\n x = F.relu(self.conv1(x))\n x = F.relu(self.conv2(x))\n x = F.relu(self.conv3(x))\n x = F.relu(self.conv4(x))\n x = x.view(x.size(0), -1)\n x = F.relu(self.linear1(x))\n return x\n \n # Only the Actor head\n def get_action_probs(self, x):\n x = self(x)\n actionProbs = F.softmax(self.actor(x), dim=1)\n actionProbs = torch.clamp(actionProbs, 0.0001, 0.9999)\n return actionProbs\n \n # Only the Critic head\n def getStateValue(self, x):\n x = self(x)\n stateValue = self.critic(x)\n return stateValue\n \n # Both heads\n def evaluate_actions(self, x):\n x = self(x)\n actionProbs = F.softmax(self.actor(x), dim=1)\n actionProbs = torch.clamp(actionProbs, 0.0001, 0.9999)\n stateValues = self.critic(x)\n return actionProbs, stateValues\n\nclass A2C():\n\n def __init__(self, numActions, gamma=None, learningRate=None, maxGradNorm=0.5,\n entropyCoefficient=0.01, valueLossFactor=0.5, sharedModel=None,\n sharedOptimizer=None, device='cpu'):\n self.gamma = gamma if gamma is not None else 0.99\n self.learningRate = learningRate if learningRate is not None else 0.0007\n self.maxGradNorm = maxGradNorm\n self.entropyCoefficient = entropyCoefficient\n self.valueLossFactor = valueLossFactor\n self.model = ActorCritic(numActions).to(device=device)\n self.sharedModel = sharedModel\n self.optimizer = sharedOptimizer if sharedOptimizer is not None else \\\n optim.Adam(self.model.parameters(), lr=self.learningRate)\n self.device = device\n print ('A2C hyperparameters',\n 'learningRate', self.learningRate,\n 'gamma', self.gamma,\n 'entropyCoefficient', self.entropyCoefficient,\n 'valueLossFactor', self.valueLossFactor,\n 'maxGradNorm', self.maxGradNorm)\n\n def save(self, filePath='training-runs/a2c.pth'):\n torch.save({'state_dict': self.model.state_dict(),\n 'optimizer' : self.optimizer.state_dict(),\n }, filePath)\n print(\"=> saved checkpoint... \", filePath)\n \n def load(self, filePath='training-runs/a2c.pth'):\n if os.path.isfile(filePath):\n print(\"=> loading checkpoint... \", filePath)\n checkpoint = torch.load(filePath)\n self.model.load_state_dict(checkpoint['state_dict'])\n self.optimizer.load_state_dict(checkpoint['optimizer'])\n print(\"done!\")\n else:\n print(\"no checkpoint found...\", filePath)\n\n # def syncSharedModel(self):\n # if self.sharedModel is not None:\n # # Synchronizing with the shared model\n # self.model.load_state_dict(self.sharedModel.state_dict())\n\n def getValues(self, state):\n stateTensor = torch.tensor(state, dtype=torch.float32, device=self.device)\n return self.model.get_action_probs(stateTensor)\n\n def pickAction(self, bestAction, validActions=None, randomRatio=-1):\n action = bestAction\n if randomRatio >= 0 and validActions is not None:\n randNum = random.uniform(0, 1)\n if randNum < randomRatio:\n action = np.random.choice(validActions)\n # print ('random action')\n # action = actionProbs.multinomial(num_samples=1)\n # action = action[0,0].tolist()\n\n if validActions is not None and action not in validActions:\n action = np.random.choice(validActions)\n return action\n\n def selectActions(self, states, validActions=None, randomRatio=-1):\n statesTensor = torch.tensor(states, dtype=torch.float32, device=self.device)\n actionProbs, stateValues = self.model.evaluate_actions(statesTensor)\n\n actions = []\n for item in actionProbs:\n bestAction = item.max(0)[1].tolist()\n action = self.pickAction(bestAction, validActions, randomRatio)\n actions.append(action)\n return actions, stateValues.tolist()\n\n def selectAction(self, state, validActions=None, randomRatio=-1):\n # Need to add dimension to simulate stack of states, even though just have one.\n stateTensor = torch.tensor(state, dtype=torch.float32, device=self.device)\n actionProbs, stateValues = self.model.evaluate_actions(stateTensor)\n\n _, bestAction = actionProbs.max(maxIndex)\n bestAction = bestAction[0].tolist()\n action = self.pickAction(bestAction, validActions, randomRatio)\n\n return action, stateValues\n\n def calcActualStateValues(self, rewards, dones, statesTensor):\n rewards = rewards.tolist()\n dones = dones.tolist()\n # R is the cumulative reward.\n R = []\n rewards.reverse()\n\n if dones[-1]:\n # if 0:\n nextReturn = 0\n else:\n stateTensor = statesTensor[-1].unsqueeze(0)\n nextReturn = self.model.getStateValue(stateTensor)[0][0].tolist()\n \n # Backup from last state to calculate \"true\" returns for each state in the set\n R.append(nextReturn)\n dones.reverse()\n for r in range(1, len(rewards)):\n if dones[r]:\n # if 0:\n thisReturn = 0\n else:\n thisReturn = rewards[r] + nextReturn * self.gamma\n # print ('thisReturn', thisReturn, rewards[r], nextReturn, self.gamma, rewards, r)\n R.append(thisReturn)\n nextReturn = thisReturn\n\n R.reverse()\n # print ('rewards', rewards)\n stateValuesActual = torch.tensor(R, dtype=torch.float32, device=self.device).unsqueeze(1)\n # print ('stateValuesActual', stateValuesActual)\n # print ('R', R)\n \n return stateValuesActual\n\n def learn(self, states, actions, rewards, dones, values=None):\n statesTensor = torch.tensor(states, dtype=torch.float32, device=self.device)\n # s = torch.tensor(states, dtype=torch.float32, device=self.device)\n # Need to convert from array of tensors to tensor of tensors.\n # actionProbs, stateValuesEst = self.model.evaluate_actions(torch.cat(statesTensor, 0))\n actionProbs, stateValuesEst = self.model.evaluate_actions(statesTensor)\n # print ('actionProbs', actionProbs)\n # print ('stateValuesEst', stateValuesEst)\n\n actionLogProbs = actionProbs.log()\n # print ('actionProbs', actionProbs)\n # print ('actionLogProbs', actionLogProbs)\n\n a = torch.tensor(actions, dtype=torch.int64, device=self.device).view(-1,1)\n chosenActionLogProbs = actionLogProbs.gather(1, a)\n # print ('chosenActionLogProbs', chosenActionLogProbs)\n\n versionToUse = 'v1'\n # v1 - original\n if versionToUse == 'v1':\n # Calculating the actual values.\n stateValuesActual = self.calcActualStateValues(rewards, dones, statesTensor)\n # print ('stateValuesActual', stateValuesActual)\n\n # This is also the TD (Temporal Difference) error\n advantages = stateValuesActual - stateValuesEst\n # print ('advantages', advantages)\n\n valueLoss = advantages.pow(2).mean()\n # print ('value_loss', value_loss)\n\n entropy = (actionProbs * actionLogProbs).sum(1).mean()\n # print ('entropy', entropy, actionProbs, actionLogProbs)\n actionGain = (chosenActionLogProbs * advantages).mean()\n # print ('actiongain', actionGain)\n totalLoss = self.valueLossFactor * valueLoss - \\\n actionGain - self.entropyCoefficient * entropy\n # print ('totalLoss', totalLoss, valueLoss, actionGain)\n\n # v2 - http://steven-anker.nl/blog/?p=184\n if versionToUse == 'v2':\n R = 0\n if not dones[-1]:\n stateTensor = statesTensor[-1]\n R = self.model.getStateValue(stateTensor)[0][0].tolist()\n \n n = len(statesTensor)\n VF = stateValuesEst\n RW = np.zeros(n)\n ADV = np.zeros(n)\n A = np.array(actions)\n \n for i in range(n - 1, -1, -1):\n R = rewards[i] + self.gamma * R\n RW[i] = R\n ADV[i] = R - VF[i]\n advantages = torch.from_numpy(ADV, device=self.device)\n\n # rewardsTensor = []\n # for reward in rewards:\n # print (reward, torch.tensor([reward], device=self.device))\n # rewardsTensor.append(torch.tensor(reward, device=self.device))\n rewardsTensor = list(map(lambda x: torch.tensor([x], device=self.device), rewards))\n rewardsTensor = torch.cat(rewardsTensor, 0)\n valueLoss = 0.5 * (stateValuesEst - rewardsTensor).pow(2).mean()\n # valueLoss = 0.5 * (stateValuesEst - torch.from_numpy(RW, device=self.device)).pow(2).mean()\n\n actionOneHot = chosenActionLogProbs #Is this correct??\n negLogPolicy = -1 * actionLogProbs\n # Only the output related to the action needs to be adjusted, since we only know the result of that action.\n # By multiplying the negative log of the policy output with the one hot encoded vectors, we force all outputs\n # other than the one of the action to zero.\n policyLoss = ((negLogPolicy * actionOneHot).sum(1) * advantages.float()).mean()\n entropy = (actionProbs * negLogPolicy).sum(1).mean()\n # Training works best if the value loss has less influence than the policy loss, so reduce value loss by a factor.\n # Optimizing with this loss function could result in converging too quickly to a sub optimal solution.\n # I.e. the probability of a single action is significant higher than any other, causing it to always be chosen.\n # To prevent this we add a penalty on having a high entropy.\n totalLoss = self.valueLossFactor * valueLoss + policyLoss - self.entropyCoefficient * entropy\n\n\n self.optimizer.zero_grad()\n totalLoss.backward()\n nn.utils.clip_grad_norm_(self.model.parameters(), self.maxGradNorm)\n # if self.sharedModel is not None:\n # ensure_shared_grads(self.model, self.sharedModel)\n self.optimizer.step()\n" }, { "alpha_fraction": 0.5927075147628784, "alphanum_fraction": 0.6392552256584167, "avg_line_length": 31.225000381469727, "blob_id": "790b308653e908c29047c4a51fecb250aff0af80", "content_id": "8bed23206239bb1325904dffa9d536f42424759f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2578, "license_type": "no_license", "max_line_length": 98, "num_lines": 80, "path": "/number.py", "repo_name": "lukemadera/ml-learning", "src_encoding": "UTF-8", "text": "# Decimal is causing rounding errors? E.g. 1/3 is 3.333333333334 and 1/3 of 30 is 9.9999999999990\n# We want to keep precision at a max, but don't increase precision for numbers that start as less.\n# For example, change 33.33333333333334 to 33.33333333 and keep 1 as 1 (not 1.0000000001)\n\nfrom decimal import *\n\n# decimals = 8\n\n# def set_decimals(decimals1):\n# global decimals\n# decimals = decimals1\n\n# def precision_string(decimals):\n# if decimals == 0:\n# return '1'\n# precision = '.'\n# # -1 because add a '1' at the end as last digit\n# for count in range(0, (decimals-1)):\n# precision += '0'\n# precision += '1'\n# return precision\n\n# def number(num, decimals1 = False):\n# global decimals\n# num_decimals_max = decimals1 or decimals\n# num_str = str(num)\n# index_dot = num_str.find('.')\n# if index_dot < 0:\n# num_decimals = 0\n# else:\n# num_decimals_str = len(num_str) - (index_dot + 1)\n# if num_decimals_str < num_decimals_max:\n# num_decimals = num_decimals_str\n# else:\n# num_decimals = num_decimals_max\n# precision = precision_string(num_decimals)\n# return Decimal(num).quantize(Decimal(precision), rounding=ROUND_HALF_UP)\n\n# decimal type does not store in MongoDB\ndef number(num):\n if not isinstance(num, float):\n return float(num)\n return num\n\ndef toFixed(num, precision1='.01'):\n numFixed = precision(num, precision1)\n numNoZeroes = removeZeroes(str(numFixed))\n if numNoZeroes[-1] == '.':\n return str(num)\n return numNoZeroes\n\n# '0.010000' will return a precision of 6 decimals, instead of 2! So fix by\n# removing any trailing zeroes.\ndef removeZeroes(str1):\n newStr = str1\n lastIndex = len(str1)\n for index, char in reversed(list(enumerate(str1))):\n if char != '0':\n break\n lastIndex = index\n newStr = str1[slice(0, lastIndex)]\n return newStr\n\ndef decimalCount(numString):\n index = numString.find('.')\n if index > -1:\n return len(numString) - index - 1\n return -1\n\ndef precision(num, precision1 = '.01', round1='down'):\n precision = removeZeroes(precision1)\n # See if value is already correct precision.\n if decimalCount(str(num)) == decimalCount(precision):\n return num\n\n rounding = ROUND_UP if round1 == 'up' else ROUND_DOWN\n newVal = float(Decimal(num).quantize(Decimal(precision), rounding=rounding))\n if newVal == 0.0:\n newVal = float(Decimal(num).quantize(Decimal(precision), rounding=ROUND_UP))\n return newVal\n" }, { "alpha_fraction": 0.5141242742538452, "alphanum_fraction": 0.7062146663665771, "avg_line_length": 16.700000762939453, "blob_id": "963a2503fdc424e812740020bf9e04afd3f3c7c6", "content_id": "b4c0cf62fb9ce46acb761f109fee60794676f312", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 177, "license_type": "no_license", "max_line_length": 24, "num_lines": 10, "path": "/requirements.txt", "repo_name": "lukemadera/ml-learning", "src_encoding": "UTF-8", "text": "aiohttp==3.3.1\ndateparser==0.7.0\nnumpy==1.17.2\npython-dateutil==2.6.1\npython-socketio==1.9.0\npytz==2017.2\nPyYAML==5.1.2\ntorch==1.2.0\ntorchvision==0.4.0\nwebsocket-client==0.40.0\n" }, { "alpha_fraction": 0.5525180101394653, "alphanum_fraction": 0.633093535900116, "avg_line_length": 68.5999984741211, "blob_id": "be42972833953ed687b10ceb62579072f730ef92", "content_id": "58ee91d155e5b61abfa0da040a86e067eeb9a116", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 695, "license_type": "no_license", "max_line_length": 164, "num_lines": 10, "path": "/TODO.md", "repo_name": "lukemadera/ml-learning", "src_encoding": "UTF-8", "text": "- breakout\n - check / copy over any other breakout specific model params\n - training run tracking (want 80M steps, or 1600 runs at 50k steps each):\n - 50k steps: 1.95, 6.0 (avg tot, max)\n - 100k steps: 1.77, 7\n - 200k steps: 1.69, 7\n - 300k steps: 1.48, 7\n - .. going much slower than the tensorflow 1.14 version? And / or not improving? Switch back to tensorflow and / or fix code / model (is something off?)\n - try running on Dani or Eric's computer and see how much faster it runs.\n - on my macbook pro for the pytorch version it takes about 0.02 sec / step, 1.76 min / 1000 batches, ~33 min for 20k batches (100k steps)." }, { "alpha_fraction": 0.5924946069717407, "alphanum_fraction": 0.6081997156143188, "avg_line_length": 35.660606384277344, "blob_id": "5e7aa470de3fded0ec941f21feda986a4a5ffa7f", "content_id": "842e50c3510862b59e4313b7e3fcb2599beda0b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6049, "license_type": "no_license", "max_line_length": 117, "num_lines": 165, "path": "/breakout_run_train.py", "repo_name": "lukemadera/ml-learning", "src_encoding": "UTF-8", "text": "import gym\nimport logging\nimport numpy as np\nimport torch\nimport time\n\nimport breakout_ai_a2c as ai_a2c\nimport date_time\nimport number\nfrom subproc_vec_env import SubprocVecEnv\nfrom atari_wrappers import make_atari, wrap_deepmind, Monitor\n\ndef updateState(obs, state, nc):\n # Do frame-stacking here instead of the FrameStack wrapper to reduce IPC overhead\n state = np.roll(state, shift=-nc, axis=3)\n state[:, :, :, -nc:] = obs\n return state\n\ndef runTrain(gymId='BreakoutNoFrameskip-v4', numEnvs=16, seed=0, filePathBrain='training/breakout-v1.pth',\n numSteps=5, numBatches=20000, outputBatchInterval=1000, joinEnvs=1, epsilon=0.00001):\n def make_env(rank):\n def _thunk():\n env = make_atari(gymId)\n env.seed(seed + rank)\n gym.logger.setLevel(logging.WARN)\n env = wrap_deepmind(env)\n\n # wrap the env one more time for getting total reward\n env = Monitor(env, rank)\n return env\n return _thunk\n\n print ('training starting', numBatches, outputBatchInterval,\n 'epsilon', epsilon)\n env = SubprocVecEnv([make_env(i) for i in range(numEnvs)])\n\n numActions = env.action_space.n\n\n torchDevice = 'cpu'\n if torch.cuda.is_available():\n torchDevice = 'cuda'\n agent = ai_a2c.A2C(numActions, device=torchDevice)\n if filePathBrain:\n agent.load(filePath=filePathBrain)\n\n timingStart = date_time.now()\n batchCount = 0\n\n states, actions, rewards, dones, values = [], [], [], [], []\n for ii in range(numEnvs):\n states.append([])\n actions.append([])\n rewards.append([])\n dones.append([])\n values.append([])\n\n # Set first state.\n # Environment returns 1 frame, but we want multiple, so we stack the new\n # state on top of the past ones.\n nh, nw, nc = env.observation_space.shape\n nstack = 4\n batchStateShape = (numEnvs * numSteps, nh, nw, nc * nstack)\n emptyState = np.zeros((numEnvs, nh, nw, nc * nstack), dtype=np.uint8)\n obs = env.reset()\n # states = updateState(obs, emptyState, nc)\n lastStates = updateState(obs, emptyState, nc)\n lastDones = [False for _ in range(numEnvs)]\n\n totalRewards = []\n realTotalRewards = []\n # All actions are always valid.\n validActions = [0,1,2,3]\n\n while batchCount < numBatches:\n states, actions, rewards, dones, values = [], [], [], [], []\n stepCount = 0\n while stepCount < numSteps:\n actionsStep, valuesStep = agent.selectActions(lastStates, validActions=validActions, randomRatio=epsilon)\n # print ('actionsStep', actionsStep)\n states.append(np.copy(lastStates))\n actions.append(actionsStep)\n values.append(valuesStep)\n if stepCount > 0:\n dones.append(lastDones)\n\n # Input the action (run a step) for all environments.\n statesStep, rewardsStep, donesStep, infosStep = env.step(actionsStep)\n\n # Update state for any dones.\n for n, done in enumerate(donesStep):\n if done:\n lastStates[n] = lastStates[n] * 0\n lastStates = updateState(obs, lastStates, nc)\n\n # Update rewards for logging / tracking.\n for done, info in zip(donesStep, infosStep):\n if done:\n totalRewards.append(info['reward'])\n if info['total_reward'] != -1:\n realTotalRewards.append(info['total_reward'])\n\n lastDones = donesStep\n rewards.append(rewardsStep)\n\n stepCount += 1\n\n # Dones is one off, so add the last one.\n dones.append(lastDones)\n\n # discount/bootstrap off value fn\n # lastValues = self.agent.value(lastStates).tolist()\n # Can skip this as it is done in the learn function with calcActualStateValues?\n\n # Join all (combine batches and steps).\n states = np.asarray(states, dtype='float32').swapaxes(1, 0).reshape(batchStateShape)\n actions = np.asarray(actions).swapaxes(1, 0).flatten()\n rewards = np.asarray(rewards).swapaxes(1, 0).flatten()\n dones = np.asarray(dones).swapaxes(1, 0).flatten()\n values = np.asarray(values).swapaxes(1, 0).flatten()\n agent.learn(states, actions, rewards, dones, values)\n\n batchCount += 1\n\n if batchCount % outputBatchInterval == 0:\n runTime = date_time.diff(date_time.now(), timingStart, 'minutes')\n totalSteps = batchCount * numSteps\n runTimePerStep = runTime / totalSteps\n runTimePerStepUnit = 'minutes'\n if runTimePerStep < 0.02:\n runTimePerStep *= 60\n runTimePerStepUnit = 'seconds'\n print (batchCount, numBatches, '(batch done)',\n number.toFixed(runTime), 'run time minutes,', totalSteps,\n 'steps,', number.toFixed(runTimePerStep), runTimePerStepUnit, 'per step')\n\n r = totalRewards[-100:] # get last 100\n tr = realTotalRewards[-100:]\n if len(r) == 100:\n print(\"avg reward (last 100):\", np.mean(r))\n if len(tr) == 100:\n print(\"avg total reward (last 100):\", np.mean(tr))\n print(\"max (last 100):\", np.max(tr))\n\n # Only save periodically as well.\n if filePathBrain:\n agent.save(filePathBrain)\n\n env.close()\n\n if filePathBrain:\n agent.save(filePathBrain)\n\n runTime = date_time.diff(date_time.now(), timingStart, 'minutes')\n totalSteps = numBatches * numSteps\n runTimePerStep = runTime / totalSteps\n runTimePerStepUnit = 'minutes'\n if runTimePerStep < 0.02:\n runTimePerStep *= 60\n runTimePerStepUnit = 'seconds'\n print ('training done:', number.toFixed(runTime), 'run time minutes,', totalSteps,\n 'steps,', number.toFixed(runTimePerStep), runTimePerStepUnit, 'per step')\n\n return None\n\nrunTrain(filePathBrain='training/breakout-v1-2.pth', epsilon=0.0001)\n" }, { "alpha_fraction": 0.6078886389732361, "alphanum_fraction": 0.633565366268158, "avg_line_length": 37.94578170776367, "blob_id": "41cf328059bc252d97480f77ef673e8c98488337", "content_id": "48decb988a6e1af31eb45eb3158d4beaef84a8d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6465, "license_type": "no_license", "max_line_length": 117, "num_lines": 166, "path": "/date_time.py", "repo_name": "lukemadera/ml-learning", "src_encoding": "UTF-8", "text": "import datetime\nimport dateutil.parser\nimport dateparser\nimport math\nimport pytz\n\ndef now(tz = 'UTC', microseconds = False):\n # return pytz.utc.localize(datetime.datetime.utcnow())\n dt = datetime.datetime.now(pytz.timezone(tz))\n if not microseconds:\n dt = dt.replace(microsecond = 0)\n return dt\n\ndef now_string(format = '%Y-%m-%d %H:%M:%S %z', tz = 'UTC'):\n return string(now(tz), format)\n\ndef arrayString(datetimes, format = '%Y-%m-%d %H:%M:%S %z'):\n return list(map(lambda datetime1: string(datetime1, format), datetimes))\n\ndef arrayStringFields(array1, fields=[], format = '%Y-%m-%d %H:%M:%S %z'):\n def mapString1(obj1):\n return dictStringFields(obj1, fields, format)\n\n return list(map(mapString1, array1))\n\ndef dictStringFields(object1, fields=[], format = '%Y-%m-%d %H:%M:%S %z'):\n newObject = {}\n for key in object1:\n if key in fields:\n newObject[key] = string(object1[key], format)\n else:\n newObject[key] = object1[key]\n return newObject\n\ndef string(datetime1, format = '%Y-%m-%d %H:%M:%S %z'):\n # return datetime1.strftime('%Y-%m-%d %H:%M:%S %z')\n # Much more performant.\n return datetime1.isoformat()\n\ndef stringFormat(datetime1, format = '%Y-%m-%d %H:%M:%S %z'):\n return datetime1.strftime('%Y-%m-%d %H:%M:%S %z')\n\n# def from_string(datetime_string, format = '%Y-%m-%d %H:%M:%S %z'):\n# return datetime.strptime(datetime_string, format)\ndef from_string(dt_string):\n return dateutil.parser.parse(dt_string)\n\ndef remove_seconds(datetime1):\n return datetime1.replace(second = 0, microsecond = 0)\n\ndef remove_microseconds(datetime1):\n return datetime1.replace(microsecond = 0)\n\n# Sets seconds (and microseconds) to 0.\ndef remove_seconds_string(datetime_string, format_in = '%Y-%m-%d %H:%M:%S %z', format_out = '%Y-%m-%d %H:%M:%S %z'):\n datetime1 = from_string(datetime_string)\n datetime1 = remove_seconds(datetime1)\n return string(datetime1, format_out)\n\ndef diff(datetime1, datetime2, unit='minutes'):\n if datetime2 > datetime1:\n dt_diff = datetime2 - datetime1\n else:\n dt_diff = datetime1 - datetime2\n # Note only total_seconds works - otherwise it just gives the remainer\n # (e.g. if more than one hour, time will be 1 hour and 5 seconds, not 3605 seconds).\n # https://stackoverflow.com/questions/2788871/date-difference-in-minutes-in-python\n if unit == 'seconds':\n return float(dt_diff.total_seconds())\n if unit == 'minutes':\n return float(dt_diff.total_seconds() / 60)\n elif unit == 'hours':\n return float(dt_diff.total_seconds() / (60*60))\n # Unlike seconds, apparently days will not cut off weeks and months, so this\n # still works if more than 7 days.\n elif unit == 'days':\n return float(dt_diff.days)\n return None\n\ndef to_biggest_unit(value, unit = 'minutes'):\n if unit == 'minutes':\n if value < 60:\n return {\n 'value': math.floor(value),\n 'unit': 'minutes'\n }\n if value < (60 * 24):\n return {\n 'value': math.floor(value / 60),\n 'unit': 'hours'\n }\n if value < (60 * 24 * 28):\n return {\n 'value': math.floor(value / 60 / 24),\n 'unit': 'days'\n }\n return None\n\n# Note this will not handle intervals larger than the size of the\n# next bigger unit (e.g. >60 minutes). So 90 minutes (1.5 hours) for example,\n# could not be done with this; need whole numbers of each unit.\n# E.g. turn 10:51 into 10:45 if interval is 15 minutes.\ndef floor_time_interval(datetime1, interval, unit = 'minutes'):\n if unit == 'seconds':\n seconds = math.floor(datetime1.second / interval) * interval\n return datetime1.replace(second = seconds, microsecond = 0)\n elif unit == 'minutes':\n minutes = math.floor(datetime1.minute / interval) * interval\n return datetime1.replace(minute = minutes, second = 0, microsecond = 0)\n elif unit == 'hours':\n hours = math.floor(datetime1.hour / interval) * interval\n return datetime1.replace(hour = hours, minute = 0, second = 0, microsecond = 0)\n elif unit == 'days':\n days = math.floor(datetime1.day / interval) * interval\n return datetime1.replace(day = days, hour = 0, minute = 0, second = 0, microsecond = 0)\n elif unit == 'months':\n months = math.floor(datetime1.month / interval) * interval\n return datetime1.replace(month = months, day = 0, hour = 0, minute = 0, second = 0, microsecond = 0)\n elif unit == 'years':\n years = math.floor(datetime1.year / interval) * interval\n return datetime1.replace(year = years, month = 0, day = 0, hour = 0, minute = 0, second = 0, microsecond = 0)\n return None\n\ndef nextMonth(datetime1, hour=0, minute=0):\n currentMonth = datetime1.month\n currentYear = datetime1.year\n if currentMonth == 12:\n nextMonth = 1\n nextYear = currentYear + 1\n else:\n nextMonth = currentMonth + 1\n nextYear = currentYear\n nextDatetime = datetime.datetime(nextYear, nextMonth, 1, hour, minute, 0, \\\n tzinfo=pytz.timezone('UTC'))\n return nextDatetime\n\ndef previousMonth(datetime1, hour=0, minute=0):\n currentMonth = datetime1.month\n currentYear = datetime1.year\n if currentMonth == 1:\n previousMonth = 12\n previousYear = currentYear - 1\n else:\n previousMonth = currentMonth - 1\n previousYear = currentYear\n previousDatetime = datetime.datetime(previousYear, previousMonth, 1, hour, minute, 0, \\\n tzinfo=pytz.timezone('UTC'))\n return previousDatetime\n\ndef dateToMilliseconds(date_str):\n \"\"\"Convert UTC date to milliseconds\n If using offset strings add \"UTC\" to date string e.g. \"now UTC\", \"11 hours ago UTC\"\n See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/\n :param date_str: date in readable format, i.e. \"January 01, 2018\", \"11 hours ago UTC\", \"now UTC\"\n :type date_str: str\n \"\"\"\n # get epoch value in UTC\n epoch = datetime.datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc)\n # parse our date string\n d = dateparser.parse(date_str)\n # if the date is not timezone aware apply UTC timezone\n if d.tzinfo is None or d.tzinfo.utcoffset(d) is None:\n d = d.replace(tzinfo=pytz.utc)\n\n # return the difference in time\n return int((d - epoch).total_seconds() * 1000.0)\n" }, { "alpha_fraction": 0.5772727131843567, "alphanum_fraction": 0.5984848737716675, "avg_line_length": 26.216495513916016, "blob_id": "cf7e7fe048deb24d52610cbc3d6173a52467f4ba", "content_id": "3f3d1c1bb33d91a180eaeab1dfa24269b208041b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2640, "license_type": "no_license", "max_line_length": 95, "num_lines": 97, "path": "/lodash.py", "repo_name": "lukemadera/ml-learning", "src_encoding": "UTF-8", "text": "import copy\nimport random\n\ndef findIndex(array1, key, value):\n return find_index(array1, key, value)\n\ndef find_index(array1, key, value):\n for index, arr_item in enumerate(array1):\n if key in arr_item and arr_item[key] == value:\n return index\n return -1\n\ndef extend_object(default, new):\n final = {}\n # Go through defaults first\n for key in default:\n if key not in new:\n final[key] = default[key]\n else:\n final[key] = new[key]\n # In case any keys in new but not in default, add them\n for key in new:\n if key not in final:\n final[key] = new[key]\n return final\n\ndef sort2D(array1, key, order = 'ascending'):\n if len(array1) < 2:\n return array1\n\n # def compare(a, b):\n # aVal = a[key]\n # bVal = b[key]\n # if aVal == bVal:\n # return 0\n # if (aVal > bVal and order == 'ascending') or (aVal < bVal and order == 'descending'):\n # return 1\n # return -1\n def getValue(item):\n return item[key]\n\n reverse = True if order == 'descending' else False\n return sorted(array1, key=getValue, reverse=reverse)\n\ndef omit(object1, keys = []):\n new_object = {}\n for key in object1:\n if key not in keys:\n new_object[key] = object1[key]\n return new_object\n\ndef pick(object1, keys = []):\n new_object = {}\n for key in object1:\n if key in keys:\n new_object[key] = object1[key]\n return new_object\n\ndef map_pick(array1, keys = []):\n def pick1(obj1):\n return pick(obj1, keys)\n\n return list(map(pick1, array1))\n\ndef mapOmit(array1, omitKeys = []):\n def omit1(obj1):\n return omit(obj1, omitKeys)\n\n return list(map(omit1, array1))\n\ndef get_key_array(items, key, skipEmpty=0, emptyValue=None):\n if skipEmpty:\n return list(map(lambda item: item[key] if key in item else emptyValue, items))\n else:\n return list(map(lambda item: item[key], items))\n\n# def append_if_unique(array1, value):\n# if value not in array1:\n# array1.append(value)\n\ndef random_string(length = 10):\n text = ''\n chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\n chars_length = len(chars)\n counter = 0\n while counter < length:\n index = random.randint(0, (chars_length - 1))\n text = text + chars[index]\n counter = counter + 1\n return text\n\ndef removeArrayIndices(array, indices):\n array1 = copy.deepcopy(array)\n for index, item in reversed(list(enumerate(array1))):\n if index in indices:\n del array1[index]\n return array1\n" } ]
7
Zagrebelin/intranet
https://github.com/Zagrebelin/intranet
a0e648789abb9ab87c2fff6a1d4aee6555a293f5
3ca727dac29a1db8597acf8d78e74c9e69ea8a5d
eea96733d52c9f64a6f0fe9d7123c16f59dae791
refs/heads/master
2017-12-04T01:32:49.126627
2016-10-30T08:15:28
2016-10-30T08:15:28
12,025,614
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6510435938835144, "alphanum_fraction": 0.6627609133720398, "avg_line_length": 29.344444274902344, "blob_id": "5c183e831327eea6c13acda232aaff17d222a189", "content_id": "6d3ef85ced45112a41285292d0dabc6e9d66d3fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2835, "license_type": "no_license", "max_line_length": 111, "num_lines": 90, "path": "/intranet/fiber/models.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "from jsonfield import JSONField\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.urlresolvers import reverse\nfrom django.db import models\n\n\nclass Room(models.Model):\n name = models.CharField(max_length=100)\n background = models.ImageField()\n\n def __str__(self):\n return self.name\n\n\nclass Cabinet(models.Model):\n name = models.CharField(max_length=50)\n short_name = models.CharField(max_length=50, blank=True, null=True)\n room = models.ForeignKey(Room)\n position = JSONField(default={\"x\": 0, \"y\": 0, \"width\": 50, \"height\": 50})\n\n def __str__(self):\n return self.name\n\n def display_name(self):\n if self.short_name:\n return self.short_name\n return self.name\n\n\nclass EndPoint(models.Model):\n pigtail = models.CharField(max_length=5, default='FC')\n connected = models.ForeignKey('EndPoint', null=True, on_delete=models.SET_NULL)\n\n parent_ct = models.ForeignKey(ContentType, null=True)\n parent_id = models.PositiveIntegerField(null=True)\n parent = GenericForeignKey('parent_ct', 'parent_id')\n\n def __str__(self):\n return str(self.parent)\n\n\nclass Odf(models.Model):\n name = models.CharField('Название кросса', max_length=150, blank=False, help_text='Что-то типа \"8A19 F02\"')\n cabinet = models.ForeignKey(Cabinet, null=True)\n pigtail = models.CharField(max_length=5, default='FC', choices=(('LC', 'LC'), ('FC', 'FC'), ('SC', 'SC')))\n\n col_per_group = models.IntegerField(\"Количество портов в горизонтальном ряду\", default=8,\n help_text='Рекомендуется не больше 8, влияет только на отображение')\n\n def get_absolute_url(self):\n return reverse('fiber:odf_detail', kwargs={'id': self.id})\n\n def __str__(self):\n return self.name\n\n\nclass OdfPort(models.Model):\n parent = models.ForeignKey(Odf)\n name = models.CharField(max_length=20)\n index = models.IntegerField()\n front = models.ForeignKey(EndPoint, related_name='front')\n back = models.ForeignKey(EndPoint, related_name='back')\n\n def __str__(self):\n return \"%s %s\" % (self.parent, self.name)\n\n\nclass Equipment(models.Model):\n cabinet = models.ForeignKey(Cabinet, null=True)\n hostname = models.CharField(max_length=150)\n\n def __str__(self):\n return self.hostname\n\n @property\n def name(self):\n return self.hostname\n\n @name.setter\n def name(self, value):\n self.hostname = value\n\n\nclass EquipmentPort(models.Model):\n parent = models.ForeignKey(Equipment)\n name = models.CharField(max_length=50)\n\n def __str__(self):\n return \"%s %s\" % (self.parent, self.name)\n" }, { "alpha_fraction": 0.5198135375976562, "alphanum_fraction": 0.5477855205535889, "avg_line_length": 29.64285659790039, "blob_id": "75511b442c14ec577a60a0f2d3fa1e20a7960d3e", "content_id": "fb5c5963d1870c9ff75d6ea04f79436b1a5694f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "no_license", "max_line_length": 68, "num_lines": 14, "path": "/intranet/sd_api/urls.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, url\nfrom .views import hash_release, hash_lock, hash_check\n# api:\n# GET hash/lock/{hash} -> \"200 OK\" or \"409 Conflict\"\n# GET hash/release/{hash} -> \"200 OK\"\n# GET check/ -> \"200 OK\"\n\n\n\nurlpatterns = [\n url(r\"^hash/lock/(?P<hash>.*)$\", hash_lock),\n url(r\"^hash/release/(?P<hash>.*)$\", hash_release),\n url(r\"^check/$\", hash_check),\n]\n" }, { "alpha_fraction": 0.5920796394348145, "alphanum_fraction": 0.6191300749778748, "avg_line_length": 40.443946838378906, "blob_id": "8d89a5000cc32e767542b8f7a26842a121cbd8f3", "content_id": "4ec803c87eeda2054ac6b6bcd318426536f92b89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9724, "license_type": "no_license", "max_line_length": 127, "num_lines": 223, "path": "/intranet/fiber/tests/test_view.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom uuid import uuid4\nfrom django.core.urlresolvers import reverse\nfrom django.test import TestCase, TransactionTestCase\nfrom ..tools import create_endpoints\nfrom ..models import Odf, OdfPort, EndPoint, Cabinet, Room\n\ndef create_odf(name, first, last):\n room = Room.objects.create(name=name)\n cabinet = Cabinet.objects.create(name=name, room=room)\n odf = Odf.objects.create(cabinet=cabinet, name=name)\n create_endpoints(odf, first, last)\n return odf\n\n\nclass FiberViewTest(TestCase):\n def test_index(self):\n rsp = self.client.get('/fiber/')\n self.assertEqual(rsp.status_code, 200)\n\n def test_odf_detail(self):\n name = uuid4().hex\n odf = create_odf(name, first=1, last=10)\n rsp = self.client.get(odf.get_absolute_url())\n self.assertEqual(rsp.status_code, 200)\n\n\nclass FiberCreateTestCase(TestCase):\n def setUp(self):\n self.room = Room.objects.create(name='room')\n self.cabinet = Cabinet.objects.create(name='foo cab', room=self.room)\n self.url = reverse('fiber:odf_create', kwargs={'cabinet': self.cabinet.id})\n\n def test_get(self):\n rsp = self.client.get(self.url)\n self.assertEqual(rsp.status_code, 200)\n\n def test_post(self):\n self.assertEqual(0, Odf.objects.count())\n\n name = uuid4().hex\n rsp = self.client.post(self.url, data={\n 'name': name,\n 'first_port': 1,\n 'last_port': 16,\n 'col_per_group': 5,\n 'pigtail': 'LC',\n 'cabinet': self.cabinet.id\n }, follow=True)\n\n self.assertEqual(rsp.status_code, 200)\n self.assertEqual(1, Odf.objects.count(), msg='Объект не создался')\n odf = Odf.objects.first()\n self.assertEqual(name, odf.name, msg='У ODFа неправильное имя')\n self.assertEqual(16, odf.odfport_set.count(), msg='У ODF неправильное количество портов')\n self.assertEqual('LC', odf.pigtail, msg='у ODF неправильный пигтейл')\n\n\nclass FiberMultiCreateTestCase(TransactionTestCase):\n def setUp(self):\n self.room = Room.objects.create(name='room')\n self.cabinet = Cabinet.objects.create(name='foo cab', room=self.room)\n self.url = reverse('fiber:odf_create_multi', kwargs={'cabinet': self.cabinet.id})\n\n def test_get(self):\n rsp = self.client.get(self.url)\n self.assertEqual(rsp.status_code, 200)\n\n def test_post(self):\n self.assertEqual(0, Odf.objects.count())\n rsp = self.client.post(self.url, data={\n 'odf_lines': '8A01 F01, 1, 16\\n8A01F02, 1,24,FC',\n 'cabinet': self.cabinet.id,\n }, follow=False)\n self.assertRedirects(rsp, reverse('fiber:cabinet_detail', kwargs={'pk':self.cabinet.id}))\n self.assertEqual(2, Odf.objects.count())\n\n first, second = Odf.objects.all()\n self.assertEqual(first.name, '8A01 F01')\n self.assertEqual(first.pigtail, 'LC')\n self.assertEqual(16, OdfPort.objects.filter(parent=first).count())\n self.assertEqual(16, EndPoint.objects.filter(front__parent=first).count())\n\n self.assertEqual(second.name, '8A01F02')\n self.assertEqual(second.pigtail, 'FC')\n self.assertEqual(24, OdfPort.objects.filter(parent=second).count())\n self.assertEqual(24, EndPoint.objects.filter(front__parent=second).count())\n\n def test_post_alot(self):\n self.assertEqual(0, Odf.objects.count())\n self.assertEqual(0, OdfPort.objects.count())\n lines = ['8A01 F%d, 1, 96' % x for x in range(20)]\n lines = \"\\n\".join(lines)\n t1 = datetime.now()\n rsp = self.client.post(self.url, data={\n 'odf_lines': lines,\n 'cabinet': self.cabinet.id,\n }, follow=False)\n t2 = datetime.now()\n seconds = (t2-t1).seconds\n self.assertRedirects(rsp, reverse('fiber:cabinet_detail', kwargs={'pk':self.cabinet.id}))\n self.assertEqual(20*96, OdfPort.objects.count())\n self.assertLessEqual(seconds, 5, msg='Too slow')\n\n\n\nclass FiberConnecttoTestCase(TestCase):\n def test_get_1(self):\n odf1 = create_odf(name='First', first=1, last=4)\n odf2 = create_odf(name='Second', first=1, last=4)\n url = reverse('fiber:odf_connect')\n rsp = self.client.get(url)\n self.assertEqual(200, rsp.status_code)\n\n def test_get_2(self):\n odf1 = create_odf(name='First', first=1, last=4)\n odf2 = create_odf(name='Second', first=1, last=4)\n url = reverse('fiber:odf_connect') + '?odf1=%d' % odf1.id\n rsp = self.client.get(url)\n self.assertEqual(200, rsp.status_code)\n\n def test_post_1(self):\n odf1 = create_odf(name='First', first=1, last=4)\n odf2 = create_odf(name='Second', first=11, last=14)\n url = reverse('fiber:odf_connect') + '?odf1=%d' % odf1.id\n self._test_post(url, odf1, odf2)\n\n def test_post_2(self):\n odf1 = create_odf(name='First', first=1, last=4)\n odf2 = create_odf(name='Second', first=11, last=14)\n url = reverse('fiber:odf_connect')\n self._test_post(url, odf1, odf2)\n\n def _test_post(self, url, odf1, odf2):\n rsp = self.client.post(url, data={\n 'odf1': odf1.id,\n 'odf2': odf2.id,\n 'port_1': 1,\n 'port_2': 11,\n 'count': 4\n }, follow=True)\n\n self.assertEqual(200, rsp.status_code)\n odf1 = Odf.objects.get(id=odf1.id)\n odf2 = Odf.objects.get(id=odf2.id)\n eps1 = EndPoint.objects.filter(back__parent=odf1)\n eps2 = EndPoint.objects.filter(back__parent=odf2)\n for ep in eps1:\n self.assertIsNotNone(ep.connected)\n self.assertTrue(ep.connected in eps2)\n for ep in eps2:\n self.assertIsNotNone(ep.connected)\n self.assertTrue(ep.connected in eps1)\n\n for ep in EndPoint.objects.filter(front__parent=odf1):\n self.assertIsNone(ep.connected)\n for ep in EndPoint.objects.filter(front__parent=odf2):\n self.assertIsNone(ep.connected)\n\n\nclass OdfMarkBusyTestCase(TestCase):\n def setUp(self):\n assert Odf.objects.count() == 0\n\n # создаём odf на три порта, создаём затычку для пустого порта, 14 и 16 фронт-порты одфа соединяем с этой затычкой\n odf = create_odf(name='odf', first=14, last=16)\n empty = EndPoint.objects.create(pigtail='EMPTY')\n for port in odf.odfport_set.filter(index__in=[14, 16]):\n port.front.connected = empty\n port.front.save()\n\n # чтобы было с чем работать в test_... методах\n self.odf = odf\n self.i14 = self.odf.odfport_set.get(index=14).id\n self.i15 = self.odf.odfport_set.get(index=15).id\n self.i16 = self.odf.odfport_set.get(index=16).id\n\n def test_get(self):\n # проверяем, чтобы в контексте была форма, а у формы было три чекбокса, а 14 и 16 чекбоксы - подняты, а ещё были лабелы\n # то есть, что форма адекватно соотвествует кроссу.\n url = reverse('fiber:odf_markbusy', kwargs={'id': self.odf.id})\n rsp = self.client.get(url)\n self.assertEqual(200, rsp.status_code)\n self.assertTrue('form' in rsp.context, msg='В контексте должна быть форма')\n form = rsp.context['form']\n self.assertEqual(3, len(form.fields), msg='В форме должно быть 3 филда')\n print(form.fields)\n self.assertTrue(form.fields['cb_%d' % self.i14].initial)\n self.assertFalse(form.fields['cb_%d' % self.i15].initial)\n self.assertTrue(form.fields['cb_%d' % self.i16].initial)\n self.assertEqual('14', form.fields['cb_%d' % self.i14].label)\n self.assertEqual('15', form.fields['cb_%d' % self.i15].label)\n self.assertEqual('16', form.fields['cb_%d' % self.i16].label)\n\n def test_post_true(self):\n # в форме включаем все чекбоксы и смотрим, что у соотвествующих odfport.front стало connected is not None\n url = reverse('fiber:odf_markbusy', kwargs={'id': self.odf.id})\n rsp = self.client.get(url)\n self.assertEqual(200, rsp.status_code)\n rsp = self.client.post(url, data={\n 'cb_%d' % self.i14: 1,\n 'cb_%d' % self.i15: 1,\n 'cb_%d' % self.i16: 1,\n }, follow=True)\n\n self.assertIsNotNone(OdfPort.objects.get(id=self.i14).front.connected)\n self.assertIsNotNone(OdfPort.objects.get(id=self.i15).front.connected)\n self.assertIsNotNone(OdfPort.objects.get(id=self.i16).front.connected)\n\n def test_post_false(self):\n # в форме выключаем все чекбоксы и смотрим, что у соотвествующих odfport.front стало connected is None\n url = reverse('fiber:odf_markbusy', kwargs={'id': self.odf.id})\n rsp = self.client.get(url)\n self.assertEqual(200, rsp.status_code)\n rsp = self.client.post(url, data={\n# 'cb_%d' % self.i14: 0,\n# 'cb_%d' % self.i15: 0,\n# 'cb_%d' % self.i16: 0,\n }, follow=True)\n self.assertEqual(200, rsp.status_code)\n self.assertIsNone(OdfPort.objects.get(id=self.i14).front.connected)\n self.assertIsNone(OdfPort.objects.get(id=self.i15).front.connected)\n self.assertIsNone(OdfPort.objects.get(id=self.i16).front.connected)\n" }, { "alpha_fraction": 0.6206896305084229, "alphanum_fraction": 0.6206896305084229, "avg_line_length": 28, "blob_id": "bc3934d78ed051a2e6b8495ffa65240c06c2b2f5", "content_id": "5d3c5f0bb7597784530f5de4cffb45fa5ffe779b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29, "license_type": "no_license", "max_line_length": 28, "num_lines": 1, "path": "/intranet/sd_api/__init__.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "__author__ = 'Zagrebelin-PI'\n" }, { "alpha_fraction": 0.7442622780799866, "alphanum_fraction": 0.7442622780799866, "avg_line_length": 33, "blob_id": "a7bb1015187e041e698cc4af2bf08ed93a2cabf6", "content_id": "a351cd43135c6f13291eeadcdf7d360acf8781ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 305, "license_type": "no_license", "max_line_length": 69, "num_lines": 9, "path": "/intranet/prm/admin.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\n# Register your models here.\nfrom .models import Node, Element, Subrack\n\n\nadmin.site.register(Node, list_display=('code', 'city', 'address'))\nadmin.site.register(Element, list_display=('node', 'code'))\nadmin.site.register(Subrack, list_display=('element','display_name'))" }, { "alpha_fraction": 0.5406413078308105, "alphanum_fraction": 0.5600298047065735, "avg_line_length": 29.477272033691406, "blob_id": "f449617a8ceed1da45ac92241eeba75d154dbfc8", "content_id": "ecb1de5f96062e56aebca9dba6505d79f2100219", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1416, "license_type": "no_license", "max_line_length": 106, "num_lines": 44, "path": "/intranet/prm/migrations/0003_auto_20141125_1105.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('prm', '0002_auto_20141028_1447'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='element',\n name='code',\n field=models.CharField(verbose_name='Название элемента', max_length=100),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='node',\n name='address',\n field=models.TextField(verbose_name='Адрес'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='node',\n name='city',\n field=models.TextField(verbose_name='Географиеское наименование'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='subrack',\n name='old_name',\n field=models.CharField(verbose_name='Старое название', null=True, blank=True, max_length=100),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='subrack',\n name='type',\n field=models.CharField(verbose_name='Тип оборудования', max_length=100),\n preserve_default=True,\n ),\n ]\n" }, { "alpha_fraction": 0.5273142457008362, "alphanum_fraction": 0.5324082374572754, "avg_line_length": 34.69279098510742, "blob_id": "411bfa04332ca2155b10683899ce9b9538f40959", "content_id": "300d506d50c01a83cc5b7b24925db7c8e632221f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11582, "license_type": "no_license", "max_line_length": 120, "num_lines": 319, "path": "/intranet/cwdm/views.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "# Create your views here.\nimport random\n\nfrom braces.views import JSONResponseMixin, CsrfExemptMixin, PrefetchRelatedMixin\nfrom django.core.urlresolvers import reverse\nfrom django.views.generic import ListView, DetailView, View, UpdateView, FormView\nfrom django.views.generic.detail import SingleObjectMixin\n\nfrom .forms import LineForm, TransitFormset, EquipmentFormset\nfrom .models import Line, Connection, lambdas, ElementInLine\n\n\nclass netsnmp:\n class Varbind:\n def __init__(self, *args, **kwargs):\n pass\n\n @classmethod\n def snmpget(cls, *args, **kwargs):\n return None\n\n\nclass IndexView(PrefetchRelatedMixin, ListView):\n template_name = \"cwdm/index.html\"\n model = Line\n prefetch_related = ['elementinline_set']\n\n\nclass EditLineView(UpdateView):\n model = Line\n form_class = LineForm\n\n def get_context_data(self, **kwargs):\n rc = super(EditLineView, self).get_context_data(**kwargs)\n rc['lambdas'] = lambdas\n rc['elements'] = self.object.elementinline_set.all().order_by('order')\n return rc\n\n def get_success_url(self):\n return self.request.path\n\n\nclass GraphLineView(DetailView):\n model = Line\n template_name = 'cwdm/line.html'\n\n\nclass OpticalPowers(CsrfExemptMixin, JSONResponseMixin, View):\n \"\"\"\n Приходит список такого вида: <id>_down, <id>_up, где id - это Connection, а up/down - направление этого\n Connection.\n\n На выходе такой json:\n {\n <id>_up: {\n 'error': ошибка или None\n 'line': {\n 'exist': boolean,\n 'slot': int,\n 'port': string,\n 'vendor': string,\n 'model': string,\n 'los': boolean,\n 'los_enabled': boolean,\n 'rx': <float>,\n 'tx': <float>,\n 'media': [optical|electrical|None]\n },\n 'client_1': {rx, tx, los, media},\n 'client_2': ...\n }\n }\n\n \"\"\"\n\n def post(self, request, *args, **kwargs):\n self.random = request.POST.get('random', 'false')\n if self.random == 'session':\n self.random = request.session.get('_cwdm_optical_random', False)\n elif self.random == 'true':\n self.random = True\n elif self.random == 'false':\n self.random = False\n else:\n self.random = False\n request.session['_cwdm_optical_random'] = self.random\n\n rc = {}\n ids = request.POST.getlist('ids[]')\n ids = set(ids)\n for id in ids: # id = '123_up'\n conn_id, direction = id.split('_') # conn_id=123, direction='up'\n conn = Connection.objects.get(id=conn_id)\n side = getattr(conn, direction)\n ip = conn.element.ip\n slot = side.slot\n board = side.board\n if self.random:\n rc[id] = self.read_optical_for_line_and_clients_random(ip, slot, board)\n else:\n rc[id] = self.read_optical_for_line_and_clients_new(ip, slot, board)\n if 'line' not in rc[id] and 'error' not in rc[id]:\n if side.port.lower() != 'client':\n line_port = side.port.lower()\n else:\n line_port = 'client_1'\n rc[id]['line'] = rc[id][line_port]\n\n return self.render_json_response(rc)\n\n def read_optical_for_line_and_clients_random(self, ip, slot, board: str):\n def sfp_random(port):\n if random.random() > 0.3:\n return {\n 'exist': True,\n 'vendor': 'Blabla',\n 'model': 'foo',\n 'rx': random.uniform(-25, 5),\n 'tx': random.uniform(-25, 5),\n 'connector': random.choice(('LC', '')),\n 'los': random.choice((True, False)),\n 'los_enabled': random.choice((True, False)),\n 'media': random.choice(('optical', 'electrical')),\n 'slot': slot,\n 'port': port,\n }\n else:\n return {\n 'exist': False,\n }\n\n ports = {\n '1ge': ['line_a', 'line_b', 'client_1'],\n '2ge': ['line', 'client_1', 'client_2'],\n '4ge': ['line_a', 'line_b', 'client_1', 'client_2', 'client_3', 'client_4'],\n '10g': ['line_a', 'line_b', 'client_1']\n }\n return {\n port: sfp_random(port) for port in ports.get(board.lower(), [])\n }\n\n def read_optical_for_line_and_clients_new(self, ip, slot, board):\n import requests\n url = 'http://10.178.227.142:50005/cwdm/optical/{ip}-{slot}-{board}.json'.format(ip=ip, slot=slot, board=board)\n resp = requests.get(url)\n ret = {}\n js = resp.json()\n if js['Status'] == 'Ok':\n for j in js['Sfps']:\n key = j['Key'].lower()\n value = j['Value']\n ret[key] = {\n 'vendor': value['Vendor'],\n 'model': value['PartNumber'],\n 'rx': value['Rx'],\n 'tx': value['Tx'],\n 'los': value['Los'],\n 'los_enabled': value['LosEnabled'],\n 'slot': slot,\n 'port': key,\n }\n ret[key]['media'] = 'optical' if 'LC' in value['Connector'] else 'electrical'\n ret[key]['exist'] = bool(ret[key]['vendor'])\n elif js['Status'] == 'Error':\n ret['error'] = js['Message']\n return ret\n\n\nclass NetworkViewJson(CsrfExemptMixin, JSONResponseMixin, View):\n \"\"\"\n Отдаёт конфигурацию сети.\n На выходе json такого вида:\n message: {\n used_wls: [1310,1470,...] # номера лямбд, которые используются в этой стеи\n elements: ['Name1', 'Name2'...] # названия сетевых элементов в порядке распложения в сети\n connections: [\n ],\n transits: [],\n eqs: [{\n id: connection_id,\n dir: up/down,\n port: line/client_1/client_2...,\n description: ''\n },\n ]\n\n\n }\n \"\"\"\n\n def get(self, request, *args, **kwargs):\n return self.get_network_info(request.GET.get('id', None))\n\n def post(self, request, *args, **kwargs):\n return self.get_network_info(request.POST.get('id', None))\n\n def get_network_info(self, line_id):\n try:\n line = Line.objects.get(id=line_id)\n except Line.DoesNotExist:\n rc = {'status': 'error', 'message': 'Line not found' % id}\n else:\n elements = line.elementinline_set.order_by('order')\n used_wls = set()\n self.connections = {}\n for element in elements:\n for connection in element.connection_set.all():\n self.connections[\"%s %d up\" % (element.name, connection.wavelength)] = self.build_connection_info(\n connection, 'up')\n self.connections[\"%s %d down\" % (element.name, connection.wavelength)] = self.build_connection_info(\n connection, 'down')\n used_wls.add(connection.wavelength)\n used_wls = list(used_wls)\n used_wls.sort()\n transits = list(map(self.build_transit_info, line.transit_set.all()))\n eqs = list(map(self.build_eqs_info, line.equipment_set.all()))\n rc = {'status': 'success', 'message': {\n 'used_wls': used_wls,\n 'elements': [{'label': e.name, 'ip': e.ip, 'hostname': e.hostname} for e in elements],\n 'connections': self.connections,\n 'transits': transits,\n 'eqs': eqs,\n }}\n return self.render_json_response(rc)\n\n def build_transit_info(self, t):\n a = ('{element} {wl} {dir}'.format(element=t.a_element.name, wl=t.a_wl, dir=t.a_direciton), t.a_port)\n z = ('{element} {wl} {dir}'.format(element=t.z_element.name, wl=t.z_wl, dir=t.z_direciton), t.z_port)\n return (a, z)\n\n def build_eqs_info(self, eq):\n p = '{element} {wl} {dir}'.format(element=eq.element.name, wl=eq.wl, dir=eq.direciton)\n return {\n 'id': self.connections[p]['id'],\n 'dir': eq.direciton,\n 'port': eq.port,\n 'description': eq.description\n }\n\n def build_connection_info(self, con, direction):\n side = getattr(con, direction)\n if not side:\n return None\n rc = {}\n rc['id'] = con.id\n rc['is_transit'] = side.is_transit\n rc['slot'] = side.slot\n rc['has_client'] = side.has_client\n rc['board'] = side.board\n return rc\n\n\nclass FormsetLineView(SingleObjectMixin, FormView):\n model = Line\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n return super().get(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n return super().post(request, *args, **kwargs)\n\n def form_valid(self, form):\n form.save()\n rc = super().form_valid(form)\n return rc\n\n def get_success_url(self):\n return self.request.path\n\n\nclass EditTransitLineView(FormsetLineView):\n template_name = 'cwdm/line_edittransit.html'\n form_class = TransitFormset\n\n def get_form(self, form_class=None):\n form = super().get_form(form_class)\n for child in form.forms:\n child.fields['a_element'].queryset = self.object.elementinline_set.all().order_by('order')\n child.fields['z_element'].queryset = self.object.elementinline_set.all().order_by('order')\n child.fields['a_element'].label_from_instance = lambda e: e.name\n child.fields['z_element'].label_from_instance = lambda e: e.name\n return form\n\n def get_form_kwargs(self):\n kwargs = super().get_form_kwargs()\n kwargs['queryset'] = self.object.transit_set.all()\n kwargs['instance'] = self.object\n return kwargs\n\n\nclass EditEquipmentLineView(FormsetLineView):\n template_name = 'cwdm/line_editequipment.html'\n form_class = EquipmentFormset\n\n def get_form(self, form_class=None):\n form = super().get_form(form_class)\n for child in form.forms:\n child.fields['element'].queryset = self.object.elementinline_set.all().order_by('order')\n child.fields['element'].label_from_instance = lambda e: e.name\n return form\n\n def get_form_kwargs(self):\n kwargs = super().get_form_kwargs()\n kwargs['queryset'] = self.object.equipment_set.all()\n kwargs['instance'] = self.object\n return kwargs\n\n\nclass ElementsViewJson(CsrfExemptMixin, JSONResponseMixin, View):\n def get(self, request, *a, **kwargs):\n elements = ElementInLine.objects.all()\n elements = elements.order_by('line__name', 'line_id', 'order')\n elements = elements.values('hostname', 'name', 'ip', 'line__name', 'line_id')\n elements = list(elements)\n for e in elements:\n e['link'] = reverse(\"cwdm:line\", kwargs={'pk':e['line_id']})\n return self.render_json_response(elements)\n" }, { "alpha_fraction": 0.6160337328910828, "alphanum_fraction": 0.6223628520965576, "avg_line_length": 28.625, "blob_id": "06cc2ddbeb2d143e77d44c28355eb7981cc5c573", "content_id": "ec56cf1a9b970abb60aff850ac0b460493be578e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 474, "license_type": "no_license", "max_line_length": 98, "num_lines": 16, "path": "/intranet/fiber/tools.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "__author__ = 'pavel'\n\nfrom .models import EndPoint, Odf, OdfPort\n\n\n\ndef create_endpoints(odf, first, last, template=\"%02d\"):\n for idx in range(first, last + 1):\n a = EndPoint.objects.create(pigtail=odf.pigtail)\n z = EndPoint.objects.create(pigtail=odf.pigtail)\n port = OdfPort.objects.create(parent=odf, name=template % idx, index=idx, front=a, back=z)\n a.parent = port\n z.parent = port\n a.save()\n z.save()\n return odf\n" }, { "alpha_fraction": 0.662162184715271, "alphanum_fraction": 0.662162184715271, "avg_line_length": 17.5, "blob_id": "d6c4909b5d4685106c6d9c5fea457ddbad0e18cc", "content_id": "82b668697cb584b8a49c44be707cab58d6c9f1ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 74, "license_type": "no_license", "max_line_length": 26, "num_lines": 4, "path": "/intranet/fiber/tests/__init__.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "__author__ = 'pavel'\n\nfrom .test_create import *\nfrom .test_view import *\n" }, { "alpha_fraction": 0.6240900158882141, "alphanum_fraction": 0.6333553791046143, "avg_line_length": 28.63725471496582, "blob_id": "17138dc715cde5b198bae6e2e397fc01bed76eb7", "content_id": "ab2dfdf3ad7a0c5303aaba51e294d975d2772c0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3022, "license_type": "no_license", "max_line_length": 62, "num_lines": 102, "path": "/intranet/sd_api/tests.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "import uuid\nimport time\nfrom datetime import timedelta\nfrom django.test import SimpleTestCase\n\nfrom .models import HashLock\n\n\nclass ApiLockTestCase(SimpleTestCase):\n url_lock_tpl = '/sd_api/hash/lock/%s'\n url_release_tpl = '/sd_api/hash/release/%s'\n url_lock = None\n url_release = None\n\n def setUp(self):\n x = uuid.uuid4()\n self.url_lock = self.url_lock_tpl % str(x)\n self.url_release = self.url_release_tpl % str(x)\n\n def test_lock(self):\n response = self.client.get(self.url_lock)\n self.assertEqual(response.status_code, 200)\n\n def test_lock_release(self):\n response = self.client.get(self.url_lock)\n response = self.client.get(self.url_release)\n self.assertEqual(response.status_code, 200)\n\n def test_lock_release_lock(self):\n response = self.client.get(self.url_lock)\n response = self.client.get(self.url_release)\n response = self.client.get(self.url_lock)\n self.assertEqual(response.status_code, 200)\n\n def test_lock_lock(self):\n response = self.client.get(self.url_lock)\n response = self.client.get(self.url_lock)\n self.assertEqual(response.status_code, 409)\n\n def test_release(self):\n response = self.client.get(self.url_release)\n self.assertEqual(response.status_code, 200)\n\n def test_expired(self):\n response = self.client.get(self.url_lock+'?seconds=2')\n time.sleep(3)\n response = self.client.get(self.url_lock)\n self.assertEqual(response.status_code, 200)\n\nfrom .views import Lock\n\n\nclass LockTestCase(SimpleTestCase):\n url_lock_tpl = '/sd_api/hash/lock/%s'\n url_release_tpl = '/sd_api/hash/release/%s'\n url_lock = None\n url_release = None\n\n def setUp(self):\n self.x = uuid.uuid4()\n self.url_lock = self.url_lock_tpl % str(self.x)\n self.url_release = self.url_release_tpl % str(self.x)\n\n def test_lock(self):\n response = Lock.lock(self.x)\n self.assertTrue(response)\n\n def test_lock_release(self):\n Lock.lock(self.x)\n Lock.release(self.x)\n self.assertTrue(True)\n\n def test_lock_release_lock(self):\n Lock.lock(self.x)\n Lock.release(self.x)\n actual = Lock.lock(self.x)\n self.assertTrue(actual)\n\n def test_lock_lock(self):\n Lock.lock(self.x)\n actual = Lock.lock(self.x)\n self.assertFalse(actual)\n\n def test_release(self):\n Lock.release(self.x)\n self.assertTrue(True)\n\n def test_expired(self):\n Lock.lock(self.x, timedelta(seconds=2))\n time.sleep(3)\n actual = Lock.lock(self.x)\n self.assertTrue(actual)\n\n def test_acquired_fail(self):\n Lock.lock(self.x, timedelta(minutes=1))\n actual = Lock.acquire(self.x, timedelta(seconds=3))\n self.assertFalse(actual)\n\n def test_acquired_success(self):\n Lock.lock(self.x, timedelta(seconds=3))\n actual = Lock.acquire(self.x, timedelta(minutes=1))\n self.assertTrue(actual)" }, { "alpha_fraction": 0.5287128686904907, "alphanum_fraction": 0.5960395932197571, "avg_line_length": 23.047618865966797, "blob_id": "045fefe1351496df0547c83b2f80fbe0783daf61", "content_id": "4716152e1684f63e02af7a8a18079e861f8da9dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 505, "license_type": "no_license", "max_line_length": 65, "num_lines": 21, "path": "/intranet/cwdm/migrations/0012_elementinline_hostname.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.7 on 2016-10-28 20:32\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('cwdm', '0011_auto_20160704_2138'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='elementinline',\n name='hostname',\n field=models.CharField(default='xxx', max_length=50),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.6544916033744812, "alphanum_fraction": 0.6712734699249268, "avg_line_length": 29.57575798034668, "blob_id": "cf37be9c480aa144fac444e7da196fa8d9dffd43", "content_id": "e12f9d241ee4889bfced6fd0ee0cb3e3adac1399", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1088, "license_type": "no_license", "max_line_length": 89, "num_lines": 33, "path": "/intranet/prm/models.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "#encoding: utf-8\n\nfrom django.db import models\n\n# Create your models here.\nclass Node(models.Model):\n city = models.TextField(\"Географиеское наименование\")\n address = models.TextField(\"Адрес\")\n code = models.CharField(max_length=10)\n\n def __unicode__(self):\n return self.code\n\n\nclass Element(models.Model):\n node = models.ForeignKey(Node)\n code = models.CharField(\"Название элемента\", max_length=100)\n\n def __unicode__(self):\n return \"%s_%s\" % (self.node.code, self.code)\n\n\nclass Subrack(models.Model):\n element = models.ForeignKey(Element)\n addon = models.CharField(max_length=20,blank=True, null=True)\n old_name = models.CharField(\"Старое название\", max_length=100, blank=True, null=True)\n type = models.CharField(\"Тип оборудования\", max_length=100)\n new_name = models.CharField(max_length=100, blank=True, null=True)\n\n def display_name(self):\n if self.new_name:\n return self.new_name\n return \"%s%s\" % (self.element, self.addon)\n " }, { "alpha_fraction": 0.6145291328430176, "alphanum_fraction": 0.6297757625579834, "avg_line_length": 32.99390411376953, "blob_id": "36a59374c89ae20bf57ffb52cd56ae0f1a98147b", "content_id": "989069bfbbe280bb765ba9f7ccbe9b086ad93ac9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5640, "license_type": "no_license", "max_line_length": 116, "num_lines": 164, "path": "/intranet/cwdm/models.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "#encoding: utf-8\nfrom logging import debug\n\nimport re\nfrom django.core.urlresolvers import reverse\nfrom django.db import models\n\n\n# таблица: длины волн по горизонтали\n# узлы по вертикали\n# в ячейках два интерфейса (up, down).\n\nlambdas = [1310, 1450, 1470, 1490, 1510, 1530, 1550, 1570, 1590, 1610]\nports = ['a', 'b', 'client', 'line', 'client1', 'client2']\nsfps = ['line', 'client_1', 'client_2', 'client_3', 'client_4']\n\ndef build_connection_choices():\n rc = [('', '---')]\n for slot in range(1, 17):\n s = []\n for port in ports:\n key = '%d%s' % (slot, port)\n value = '%d-%s' % (slot, port)\n s.append((key, value))\n rc.append((slot, s))\n return rc\nconnection_choices = build_connection_choices()\n\n\nclass Line(models.Model):\n name = models.CharField(max_length=50)\n\n def __str__(self):\n return self.name\n\n def get_absolute_url(self):\n return reverse(\"cwdm:line\", args=[self.id,])\n\n def save(self, *args, **kwargs):\n created = self.id is None\n super().save(*args, **kwargs)\n if created and self.id is not None:\n for prop in LineProperty.objects.all():\n LinePropertyBinding.objects.create(prop=prop, line=self, value=prop.default)\n\n class Meta:\n ordering = ['name', ]\n\n\nclass LineProperty(models.Model):\n title = models.CharField(max_length=30)\n slug = models.SlugField()\n default = models.CharField(max_length=30, default='')\n\n def save(self, force_insert=False, force_update=False, using=None,\n update_fields=None):\n created = self.id is None\n super().save(force_insert=force_update, force_update=force_update, using=using, update_fields=update_fields)\n if created and self.id is not None:\n for line in Line.objects.all():\n LinePropertyBinding.objects.create(prop=self, line=line, value=self.default)\n\n def __str__(self):\n return self.title\n\nclass LinePropertyBinding(models.Model):\n prop = models.ForeignKey(LineProperty)\n line = models.ForeignKey(Line)\n value = models.CharField(max_length=30)\n\n\nclass ElementInLine(models.Model):\n name = models.CharField(max_length=50)\n ip = models.GenericIPAddressField()\n line = models.ForeignKey(Line)\n order = models.IntegerField()\n hostname = models.CharField(max_length=50)\n\n def __unicode__(self):\n return \"%s (#%d from %s)\" % (self.name, self.order, self.line.name)\n\n def __str__(self):\n return self.name\n\n\nvalid_boards = ('1GE', '2GE', '4GE')\n\nclass ConnectionSide(models.Model):\n slot = models.PositiveIntegerField(blank=True, null=True)\n board = models.CharField(max_length=10, blank=True, null=True, choices=[(b,b) for b in valid_boards])\n port = models.CharField(max_length=10, blank=True, null=True)\n has_client = models.BooleanField(blank=True, default=True)\n is_transit = models.BooleanField(blank=True, default=False)\n\n def __str__(self):\n if self.is_transit:\n return 'Transit'\n\n return \"{slot} {board} {port}\".format(slot=self.slot, board=self.board, port=self.port)\n\n\nclass Connection(models.Model):\n wavelength = models.IntegerField(choices=[(l,l) for l in lambdas])\n element = models.ForeignKey(ElementInLine)\n up = models.ForeignKey(ConnectionSide, null=True, blank=True, related_name='up', on_delete=models.PROTECT)\n down = models.ForeignKey(ConnectionSide, null=True, blank=True, related_name='down')\n\n @property\n def up_has_client(self):\n debug(self.up)\n if 'client' in self.up:\n return False\n if not self.up:\n return False\n if self.up and self.down and self.up_board()==self.down_board():\n return False\n return True\n\n @property\n def down_has_client(self):\n if 'client' in self.down:\n return False\n if not self.down:\n return False\n if self.up and self.down and self.up_board()==self.down_board():\n return False\n return True\n\n def up_board(self):\n ma = re.match(\"^(\\d+)\", self.up)\n if not ma:\n raise ValueError(\"%s is invalid port format\" % self.up)\n return int(ma.groups()[0])\n\n def down_board(self):\n ma = re.match(\"^(\\d+)\", self.down)\n if not ma:\n raise ValueError(\"%s is invalid port format\" % self.down)\n return int(ma.groups()[0])\n\n def __unicode__(self):\n return \"%d %s\"%(self.wavelength, self.element)\n\n\nclass Transit(models.Model):\n line = models.ForeignKey(Line)\n a_element = models.ForeignKey(ElementInLine, related_name='a')\n a_wl = models.IntegerField(choices=((l,l) for l in lambdas))\n a_direciton = models.CharField(max_length=10, choices=(('up', 'up'), ('down', 'down')))\n a_port = models.CharField(max_length=10, choices=((s,s) for s in sfps))\n\n z_element = models.ForeignKey(ElementInLine, related_name='z')\n z_wl = models.IntegerField(choices=((l,l) for l in lambdas))\n z_direciton = models.CharField(max_length=10, choices=(('up', 'up'), ('down', 'down')))\n z_port = models.CharField(max_length=10, choices=((s,s) for s in sfps))\n\n\nclass Equipment(models.Model):\n line = models.ForeignKey(Line)\n element = models.ForeignKey(ElementInLine)\n wl = models.IntegerField(choices=((l,l) for l in lambdas))\n direciton = models.CharField(max_length=10, choices=(('up', 'up'), ('down', 'down')))\n port = models.CharField(max_length=10, choices=((s,s) for s in sfps))\n description = models.CharField(max_length=50)\n" }, { "alpha_fraction": 0.5142857432365417, "alphanum_fraction": 0.5206349492073059, "avg_line_length": 22.296297073364258, "blob_id": "e96a72907ad203201a258254e7e36508ee15bd06", "content_id": "f25aaecd1d7405fce5a8e1a7a9c67b6b15ed2353", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 643, "license_type": "no_license", "max_line_length": 84, "num_lines": 27, "path": "/intranet/cwdm/templates/cwdm/index.html", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "{% extends \"cwdm/base.html\" %}\n\n{%block content %}\n<ol class=\"breadcrumb\">\n <li><a href=\"/\">Home</a></li>\n <li class=\"active\">CWDM</li>\n</ol>\n\n<div class=\"pull-right\">\n<input type=\"search\" class=\"form-control\" placeholder=\"Поиск...\" id=\"searchbox\">\n</div>\n\n\n<h1>CWDM</h1>\n<h2>Все линии</h2>\n {% for line in line_list %}\n <p>\n <a href=\"{% url 'cwdm:line' line.id %}\"><strong>{{ line.name }}</strong></a>\n {% with line.elementinline_set.all as elements %}\n {% if elements %}\n ({{ elements|join:\", \" }})\n {% endif %}\n {% endwith %}\n </p>\n {% endfor %}\n\n{% endblock %}\n\n" }, { "alpha_fraction": 0.5789473652839661, "alphanum_fraction": 0.5789473652839661, "avg_line_length": 12, "blob_id": "cd6f4a8710f7e43596db0ee52f9ab1933bafc9bb", "content_id": "7284f4289f036e32295435aa66b5e1ca3e46dc7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 38, "license_type": "no_license", "max_line_length": 20, "num_lines": 3, "path": "/intranet/prm/urls.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "__author__ = 'pavel'\n\nurlpatterns = []" }, { "alpha_fraction": 0.5174548625946045, "alphanum_fraction": 0.595178484916687, "avg_line_length": 56.50757598876953, "blob_id": "d6c59e487ca8abccc024b94c104d56583814dcaa", "content_id": "875785fb4b34c0f38726cf496b2b5dba020444a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7602, "license_type": "no_license", "max_line_length": 119, "num_lines": 132, "path": "/intranet/fiber/migrations/0002_create_8a_502_fixtures.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport os\nfrom django.core.files import File\n\nfrom django.db import models, migrations\nimport jsonfield.fields\n\n\ndef create_8a(apps, schema_editor):\n Room = apps.get_model(\"fiber\", \"Room\")\n Cabinet = apps.get_model(\"fiber\", \"Cabinet\")\n db_alias = schema_editor.connection.alias\n\n room = Room.objects.using(db_alias).create(name='8A', background='images/8a.png')\n back_name = os.path.join('intranet', 'fiber', 'fixtures', 'images', '8a.png')\n room.background.save('8a.png', File(open(back_name, 'rb')))\n Cabinet.objects.using(db_alias).bulk_create([\n Cabinet(position={\"y\": 125, \"height\": 61, \"width\": 76, \"x\": 283}, name=\"8A01\", room=room),\n Cabinet(position={\"y\": 125, \"height\": 61, \"width\": 76, \"x\": 102}, name=\"8A02\", room=room),\n Cabinet(position={\"y\": 185, \"height\": 61, \"width\": 76, \"x\": 283}, name=\"8A03\", room=room),\n Cabinet(position={\"y\": 185, \"height\": 61, \"width\": 76, \"x\": 102}, name=\"8A04\", room=room),\n Cabinet(position={\"y\": 245, \"height\": 61, \"width\": 76, \"x\": 283}, name=\"8A05\", room=room),\n Cabinet(position={\"y\": 245, \"height\": 61, \"width\": 76, \"x\": 102}, name=\"8A06\", room=room),\n Cabinet(position={\"y\": 305, \"height\": 61, \"width\": 76, \"x\": 283}, name=\"8A07\", room=room),\n Cabinet(position={\"y\": 305, \"height\": 61, \"width\": 76, \"x\": 102}, name=\"8A08\", room=room),\n Cabinet(position={\"y\": 365, \"height\": 61, \"width\": 76, \"x\": 283}, name=\"8A09\", room=room),\n Cabinet(position={\"y\": 365, \"height\": 61, \"width\": 76, \"x\": 102}, name=\"8A10\", room=room),\n Cabinet(position={\"y\": 425, \"height\": 61, \"width\": 76, \"x\": 283}, name=\"8A11\", room=room),\n Cabinet(position={\"y\": 425, \"height\": 61, \"width\": 76, \"x\": 102}, name=\"8A12\", room=room),\n Cabinet(position={\"y\": 485, \"height\": 61, \"width\": 76, \"x\": 283}, name=\"8A13\", room=room),\n Cabinet(position={\"y\": 485, \"height\": 61, \"width\": 76, \"x\": 102}, name=\"8A14\", room=room),\n Cabinet(position={\"y\": 485, \"height\": 61, \"width\": 76, \"x\": 102}, name=\"8A14\", room=room),\n Cabinet(position={\"y\": 545, \"height\": 61, \"width\": 76, \"x\": 283}, name=\"8A15\", room=room),\n Cabinet(position={\"y\": 545, \"height\": 61, \"width\": 76, \"x\": 102}, name=\"8A16\", room=room),\n Cabinet(position={\"x\": 0, \"height\": 23, \"width\": 49, \"y\": 394, 'rotate':1}, name=\"8A19\", room=room),\n Cabinet(position={\"x\": 0, \"height\": 23, \"width\": 49, \"y\": 345, \"rotate\": 1}, name=\"8A20\", room=room),\n Cabinet(position={\"x\": 0, \"height\": 23, \"width\": 49, \"y\": 297, \"rotate\": 1}, name=\"8A21\", room=room),\n Cabinet(position={\"x\": 13, \"height\": 23, \"width\": 23, \"y\": 262}, name=\"8A26\", room=room),\n Cabinet(position={\"x\": 13, \"height\": 23, \"width\": 23, \"y\": 239}, name=\"8A27\", room=room),\n ])\n\n\ndef delete_8a(apps, schema_editor):\n Room = apps.get_model(\"fiber\", \"Room\")\n EndPoint = apps.get_model(\"fiber\", \"EndPoint\")\n db_alias = schema_editor.connection.alias\n\n Room.objects.using(db_alias).filter(name='8A').delete()\n\n\ndef create_502(apps, schema_editor):\n Room = apps.get_model(\"fiber\", \"Room\")\n Cabinet = apps.get_model(\"fiber\", \"Cabinet\")\n db_alias = schema_editor.connection.alias\n\n room = Room.objects.using(db_alias).create(name='502')\n back_name = os.path.join('intranet', 'fiber', 'fixtures', 'images', '502.png')\n room.background.save('502.png', File(open(back_name, 'rb')))\n\n Cabinet.objects.using(db_alias).bulk_create([\n Cabinet(name=\"TT120 #1\", short_name=\"1\", position={\"height\": 24, \"width\": 24, \"y\": 295, \"x\": 158}, room=room),\n Cabinet(name=\"TT120 #2\", short_name=\"2\", position={\"height\": 24, \"width\": 24, \"y\": 295, \"x\": 134}, room=room),\n Cabinet(name=\"TT120 #3\", short_name=\"3\", position={\"height\": 24, \"width\": 24, \"y\": 295, \"x\": 110}, room=room),\n Cabinet(name=\"TT120 #5\", short_name=\"5\", position={\"height\": 24, \"width\": 24, \"y\": 295, \"x\": 86}, room=room),\n Cabinet(name=\"TT120 #6\", short_name=\"6\", position={\"height\": 24, \"width\": 24, \"y\": 295, \"x\": 62}, room=room),\n Cabinet(name=\"TT120 #7\", short_name=\"7\", position={\"height\": 24, \"width\": 24, \"y\": 319, \"x\": 134}, room=room),\n Cabinet(name=\"TT120 #8\", short_name=\"8\", position={\"height\": 24, \"width\": 24, \"y\": 319, \"x\": 158}, room=room),\n Cabinet(name=\"TT120 #9\", short_name=\"9\", position={\"height\": 24, \"width\": 24, \"y\": 319, \"x\": 110}, room=room),\n Cabinet(name=\"TT120 #10\", short_name=\"10\", position={\"height\": 24, \"width\": 24, \"y\": 319, \"x\": 86}, room=room),\n Cabinet(name=\"TT120 #11\", short_name=\"11\", position={\"height\": 24, \"width\": 24, \"y\": 319, \"x\": 62}, room=room),\n Cabinet(name=\"DWDM-3\", short_name=\"DW-3\", position={\"height\": 25, \"x\": 480, \"width\": 50, \"y\": 219}, room=room),\n Cabinet(name=\"DWDM-4\", short_name=\"DW-4\", position={\"height\": 25, \"x\": 530, \"width\": 50, \"y\": 219}, room=room),\n Cabinet(name=\"DWDM-5\", short_name=\"DW-5\", position={\"height\": 25, \"x\": 580, \"width\": 50, \"y\": 219}, room=room),\n Cabinet(name=\"DWDM-6\", short_name=\"DW-6\", position={\"height\": 25, \"x\": 630, \"width\": 50, \"y\": 219}, room=room),\n Cabinet(name=\"DWDM-7\", short_name=\"DW-7\", position={\"height\": 25, \"x\": 680, \"width\": 50, \"y\": 219}, room=room),\n Cabinet(name=\"DWDM-8\", short_name=\"DW-8\", position={\"height\": 25, \"x\": 730, \"width\": 50, \"y\": 219}, room=room),\n Cabinet(name=\"DWDM-9\", short_name=\"DW-9\", position={\"height\": 25, \"x\": 780, \"width\": 50, \"y\": 219}, room=room),\n Cabinet(name=\"DWDM-10\", short_name=\"DW-10\", position={\"height\": 25, \"x\": 830, \"width\": 50, \"y\": 219},\n room=room),\n Cabinet(name=\"DWDM-11\", short_name=\"DW-11\", position={\"height\": 25, \"x\": 480, \"width\": 50, \"y\": 194},\n room=room),\n Cabinet(name=\"Вятка\", short_name=\"\", position={\"height\": 25, \"x\": -5, \"width\": 53, \"rotate\": 1, \"y\": 243},\n room=room),\n ])\n\n\ndef delete_502(apps, schema_editor):\n Room = apps.get_model(\"fiber\", \"Room\")\n Cabinet = apps.get_model(\"fiber\", \"Cabinet\")\n db_alias = schema_editor.connection.alias\n\n Room.objects.using(db_alias).filter(name='502').delete()\n\n\ndef create_dummy(apps, schema_editor):\n Equipment = apps.get_model('fiber', 'Equipment')\n EquipmentPort = apps.get_model('fiber', 'EquipmentPort')\n EndPoint = apps.get_model('fiber', 'EndPoint')\n db_alias = schema_editor.connection.alias\n\n eq = Equipment.objects.using(db_alias).create(hostname='Dummy')\n port = EquipmentPort.objects.using(db_alias).create(name='Занято', parent=eq)\n endpoint = EndPoint.objects.using(db_alias).create(pigtail='EMPTY')\n endpoint.parent=port\n endpoint.save()\n\ndef delete_dummy(apps, schema_editor):\n Equipment = apps.get_model('fiber', 'Equipment')\n EquipmentPort = apps.get_model('fiber', 'EquipmentPort')\n EndPoint = apps.get_model('fiber', 'EndPoint')\n db_alias = schema_editor.connection.alias\n\n eps = EndPoint.objects.using(db_alias).filter(pigtail='EMPTY')\n ports = EquipmentPort.objects.using(db_alias).filter(id__in=[ep.parent_id for ep in eps])\n eqs = Equipment.objects.using(db_alias).filter(id__in=[port.parent_id for port in ports])\n\n eqs.delete()\n ports.delete()\n eps.delete()\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('fiber', '0001_initial')\n ]\n\n operations = [\n migrations.RunPython(create_8a, delete_8a),\n migrations.RunPython(create_502, delete_502),\n migrations.RunPython(create_dummy, delete_dummy)\n ]\n" }, { "alpha_fraction": 0.6711656451225281, "alphanum_fraction": 0.6809815764427185, "avg_line_length": 39.75, "blob_id": "673167851627bddfaef0aae4a06ed434e41c3c20", "content_id": "efa48974cf4137d9c57c35045f9cc4577d7dd753", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 815, "license_type": "no_license", "max_line_length": 128, "num_lines": 20, "path": "/intranet/fiber/tests/test_create.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "__author__ = 'pavel'\n\nfrom django.test import TestCase\nfrom ..models import EndPoint, Odf, OdfPort, Cabinet, Room\nfrom ..tools import create_endpoints\n\n\n\nclass CreateOdfTest(TestCase):\n def test_create_via_odf(self):\n assert Odf.objects.count() == 0\n\n odf = Odf.objects.create(name='ODF', cabinet=Cabinet.objects.create(name='foo cab', room=Room.objects.create(name='x')))\n create_endpoints(odf=odf, first=1, last=8)\n self.assertEqual(1, Odf.objects.count())\n odf = Odf.objects.get(id=odf.id)\n self.assertEqual(8, odf.odfport_set.count())\n self.assertEqual(8, OdfPort.objects.filter(parent=odf).count())\n self.assertEqual(8, EndPoint.objects.filter(front__parent=odf).count())\n self.assertEqual(8, EndPoint.objects.filter(back__parent=odf).count())\n" }, { "alpha_fraction": 0.7201645970344543, "alphanum_fraction": 0.7201645970344543, "avg_line_length": 29.375, "blob_id": "c155dbf1c07c259c3a601153832aaa884c61abaa", "content_id": "314fd6c34af858835619ceaa2505416ae9b868f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 243, "license_type": "no_license", "max_line_length": 64, "num_lines": 8, "path": "/manage.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nfrom envs import read_environment_from_file\nimport sys\n\nif __name__ == \"__main__\":\n read_environment_from_file()\n from django.core.management import execute_from_command_line\n execute_from_command_line(sys.argv)\n" }, { "alpha_fraction": 0.7104072570800781, "alphanum_fraction": 0.7129929065704346, "avg_line_length": 32.60869598388672, "blob_id": "386b21d99b639d2706732e90ecf46197afa6e1f7", "content_id": "6bd9d889e1c5dd3464e6999a060ee2e2090c2131", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2622, "license_type": "no_license", "max_line_length": 121, "num_lines": 46, "path": "/intranet/fiber/readme.rst", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "Волокна и кроссы\n================\n\n\nПроект должен дать ответ на вопросы\n-----------------------------------\n- С каким портом какого оборудования связан порт X.\n- Через какие кроссы проходит линк с порта Х до порта Y.\n- С какими кроссами связан кросс Х.\n\n\nВьюхи для просмотра\n--------------------\n\n- Список линков с фильтром по типу\n- Список оборудовования\n- Все порты одного девайса с соседями по линку. Про порт информация:\n название порта; патчкорды, которые в него входят; линки, которые через него проходят\n\n\n\nВьюхи для редактирования\n------------------------\n\n- добавить кросс\n- добавить оборудование\n- добавить один или несколько портов на оборудовании\n- сделать линк\n- несколько линков (выбираем порты на двух железяках, оно делает пачку линков)\n\n\nСписок линков с фильтром по типу\n--------------------------------\nСписок оборудований. Возле каждого кнопка \"развернуть\".\nПри разворачивании аяксом подгружаем группы портов, возле каждой кнопка \"развернуть\".\nПри разворачивании аяксом подгружаем порты, возле каждого какая-то информация про линки.\n\n\nstep-by-step\n============\n1. Кросс. Порты на нём, вьюшка для просмотра кросса.\n2. Соединение двух кроссов. Вьюшка для кросса и его окружения.\n3. Порт на оборудовании, rx\\tx, соединение кросса и оборудования. Вьюшка для окружения оборуования.\n4. end-to-end линк. Вьюшка для окружения оборудования (непосредственные соседи по патчкордам, нечто на конце патчкордов),\n вьюшка для кроссов (слева - сосед и далекий конец, справа - сосед и дальний конец),\n вьюшка для линка (где его носит).\n\n" }, { "alpha_fraction": 0.5751100182533264, "alphanum_fraction": 0.5809763073921204, "avg_line_length": 32.731449127197266, "blob_id": "c41a29c31d9af7788127fb5e072fd29a0fb018cb", "content_id": "a0b866d75a6742c20d38b74b7c50539dcd48a422", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9549, "license_type": "no_license", "max_line_length": 109, "num_lines": 283, "path": "/intranet/fiber/views.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "from collections import namedtuple\nimport math\n\nfrom django.core.urlresolvers import reverse\nfrom django.db import transaction\nfrom django.db.models import Count\nfrom django.views.generic import FormView, TemplateView\nfrom django.views.generic import DetailView\nfrom django.views.generic import ListView\nfrom django.views.generic import CreateView\nfrom django.http import HttpResponseRedirect\n\nfrom formtools.wizard.views import NamedUrlSessionWizardView\n\nfrom .forms import OdfMultiCreateForm, OdfConnectToForm, OdfCreateForm, OdfMarkBusyForm\nfrom .tools import create_endpoints\nfrom .models import Odf, EndPoint, Room, Cabinet\nfrom . import forms\n\n\nclass OdfCreateView(CreateView):\n model = Odf\n form_class = OdfCreateForm\n template_name = 'fiber/odf/form.html'\n\n def get(self, request, cabinet):\n self.cabinet_id = cabinet\n return super().get(request)\n\n def post(self, request, cabinet):\n self.cabinet_id = cabinet\n return super().post(request)\n\n def form_valid(self, form):\n rc = super().form_valid(form)\n create_endpoints(odf=self.object,\n first=form.cleaned_data['first_port'],\n last=form.cleaned_data['last_port'])\n return rc\n\n def get_initial(self):\n print(dir(self.request))\n initial = super().get_initial()\n initial['cabinet'] = self.cabinet_id\n return initial\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n f = context['form']['cabinet']\n context['cabinet'] = Cabinet.objects.get(pk=f.value())\n return context\n\n\nclass OdfMultiCreateView(FormView):\n form_class = OdfMultiCreateForm\n template_name = 'fiber/odf/multi_create.html'\n\n def get(self, request, cabinet):\n self.cabinet_id = cabinet\n return super().get(request)\n\n def post(self, request, cabinet):\n self.cabinet_id = cabinet\n return super().post(request)\n\n @transaction.atomic\n def form_valid(self, form):\n odf_lines = form.data['odf_lines']\n lines = odf_lines.split('\\n')\n self.cabinet = form.cleaned_data['cabinet']\n for line in lines:\n parts = line.split(',')\n parts = map(str.strip, parts)\n name, first, last, *pigtail = parts\n if pigtail:\n pigtail = pigtail[0]\n else:\n pigtail = 'LC'\n odf = Odf.objects.create(name=name, cabinet=self.cabinet, pigtail=pigtail)\n create_endpoints(odf, int(first), int(last))\n return super().form_valid(form)\n\n def get_success_url(self):\n return reverse('fiber:cabinet_detail', kwargs={'pk': self.cabinet.id})\n\n def get_initial(self):\n initial = super().get_initial()\n initial['cabinet'] = self.cabinet_id\n return initial\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n f = context['form']['cabinet']\n context['cabinet'] = Cabinet.objects.get(pk=f.value())\n return context\n\n\nclass OdfDetailView(DetailView):\n model = Odf\n pk_url_kwarg = 'id'\n template_name = 'fiber/odf/detail.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context.update(build_remotes(self.object))\n return context\n\n\nPair = namedtuple('Pair', ['remote', 'local', 'local_connected', 'remote_connected', ])\n\n\ndef build_remotes(odf):\n ports = odf.odfport_set \\\n .select_related('front', 'back', 'back__connected', 'front__connected') \\\n .prefetch_related('back__connected__parent',\n 'back__connected__parent__parent',\n 'back__connected__parent__front',\n 'back__connected__parent__front__connected',\n 'front__connected__parent',\n 'front__connected__parent__parent') \\\n .order_by('index') \\\n .all()\n rc = {}\n previous_name = None\n remotes = []\n remote = None\n for port in ports: # port - это OdfPort.\n if port.back.connected:\n remote_port = port.back.connected.parent\n remote_parent = remote_port.parent\n remote_parent_name = remote_parent.name\n remote_port_name = remote_port.name\n remote_front = port.back.connected.parent.front.connected\n else:\n remote_port = None\n remote_parent = None\n remote_parent_name = ''\n remote_port_name = ''\n remote_front = None\n remote_parent_name = \"\"\n if remote_parent_name != previous_name:\n if remote:\n cnt = math.ceil(remote['count'] / odf.col_per_group) * odf.col_per_group - remote['count']\n remote['extra'] = range(cnt)\n pairs = []\n remote = {\n 'name': remote_parent_name,\n 'pairs': pairs,\n 'count': 0,\n 'rows': None,\n 'extra': 0,\n 'remote': remote_parent,\n }\n remotes.append(remote)\n previous_name = remote_parent_name\n pairs.append(Pair(\n local=port.name,\n remote=remote_port_name,\n local_connected=port.front.connected,\n remote_connected=remote_front))\n remote['count'] += 1\n if remote:\n cnt = math.ceil(remote['count'] / odf.col_per_group) * odf.col_per_group - remote['count']\n remote['extra'] = range(cnt)\n\n for remote in remotes:\n remote['rows'] = math.ceil(remote['count'] / odf.col_per_group)\n print(remotes)\n rc['total_rows'] = sum(r['rows'] for r in remotes)\n rc['remotes'] = remotes\n return rc\n\n\nclass OdfBusyView(FormView):\n form_class = OdfMarkBusyForm\n template_name = 'fiber/odf/markbusy.html'\n\n def get(self, request, id, *args, **kwargs):\n self.object = Odf.objects.get(pk=id)\n return super().get(request, *args, **kwargs)\n\n def post(self, request, id, *args, **kwargs):\n self.object = Odf.objects.get(pk=id)\n return super().post(request, *args, **kwargs)\n\n def get_form_kwargs(self):\n kwargs = super().get_form_kwargs()\n ids = []\n for port in self.object.odfport_set.select_related('front').all().order_by('index'):\n ids.append({\n 'initial': port.front.connected_id is not None,\n 'label': port.name,\n 'id': port.id,\n 'index': port.index,\n })\n kwargs['ids'] = ids\n return kwargs\n\n def get_success_url(self):\n return self.object.get_absolute_url()\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['odf'] = self.object\n context['port_count'] = self.object.odfport_set.count()\n return context\n\n def form_valid(self, form):\n empty = EndPoint.objects.get(pigtail='EMPTY')\n for port in self.object.odfport_set.all():\n if form.cleaned_data['cb_%d' % port.id]:\n port.front.connected = empty\n else:\n port.front.connected = None\n port.front.save()\n return super().form_valid(form)\n\n\nclass IndexView(ListView):\n template_name = 'fiber/index.html'\n model = Room\n\n\nclass RoomAsMap(DetailView):\n model = Room\n template_name = 'fiber/room/as_map.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['cabinets'] = self.object.cabinet_set.all()\n return context\n\n\nclass CabinetDetailView(DetailView):\n model = Cabinet\n template_name = 'fiber/cabinet/detail.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['odfs'] = [\n {'odf': odf, 'remotes': build_remotes(odf)} for odf in self.object.odf_set.order_by('name').all()\n ]\n context['eqs'] = self.object.equipment_set.all()\n return context\n\n\nclass OdfConnectToView(NamedUrlSessionWizardView):\n form_list = [forms.OdfConnectForm1, forms.OdfConnectForm2]\n template_name = 'fiber/odf/connect_wizard_form.html'\n\n def get_form_kwargs(self, step=None):\n kwargs = super().get_form_kwargs(step)\n if step == '1':\n zero = self.storage.get_step_data('0')\n odf_1_id = int(zero['0-odf1'])\n odf_2_id = int(zero['0-odf2'])\n odf_1 = Odf.objects.get(id=odf_1_id)\n odf_2 = Odf.objects.get(id=odf_2_id)\n kwargs['odf_1'] = odf_1\n kwargs['odf_2'] = odf_2\n return kwargs\n\n def done(self, form_list, **kwargs):\n cleaned_data = [form.cleaned_data for form in form_list]\n odf1 = cleaned_data[0]['odf1']\n odf2 = cleaned_data[0]['odf2']\n start_1 = int(cleaned_data[1]['port_1'])\n start_2 = int(cleaned_data[1]['port_2'])\n for x in range(cleaned_data[1]['count']):\n idx_1 = start_1 + x\n idx_2 = start_2 + x\n port_1 = odf1.odfport_set.get(index=idx_1)\n port_2 = odf2.odfport_set.get(index=idx_2)\n ep_1 = port_1.back\n ep_2 = port_2.back\n ep_1.connected = ep_2\n ep_1.save()\n ep_2.connected = ep_1\n ep_2.save()\n return HttpResponseRedirect(odf1.get_absolute_url())\n\n\nconnect_wizard = OdfConnectToView.as_view(url_name='fiber:odf_connect_step')\n" }, { "alpha_fraction": 0.5083406567573547, "alphanum_fraction": 0.5302897095680237, "avg_line_length": 34.59375, "blob_id": "6b9018b9e2cb9269fa261e0320f8d155cad76ca4", "content_id": "1b855e2fb32c2ef3d181d28cfdbbc8dcad1d3809", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1139, "license_type": "no_license", "max_line_length": 114, "num_lines": 32, "path": "/intranet/cwdm/migrations/0007_transit.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('cwdm', '0006_auto_20150207_2348'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Transit',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('a_wl', models.IntegerField()),\n ('a_direciton', models.CharField(max_length=10)),\n ('a_port', models.CharField(max_length=10)),\n ('z_wl', models.IntegerField()),\n ('z_direciton', models.CharField(max_length=10)),\n ('z_port', models.CharField(max_length=10)),\n ('a_element', models.ForeignKey(to='cwdm.ElementInLine', related_name='a')),\n ('line', models.ForeignKey(to='cwdm.Line')),\n ('z_element', models.ForeignKey(to='cwdm.ElementInLine', related_name='z')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n" }, { "alpha_fraction": 0.4855112135410309, "alphanum_fraction": 0.5418261289596558, "avg_line_length": 35.58000183105469, "blob_id": "468924c7860bcc22a009e837c846e68bfb1b10eb", "content_id": "c802e85415a598650b57bc5a1388504244768e6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1829, "license_type": "no_license", "max_line_length": 188, "num_lines": 50, "path": "/intranet/cwdm/migrations/0006_auto_20150207_2348.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('cwdm', '0005_auto_20141205_1018'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='LineProperty',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('title', models.CharField(max_length=30)),\n ('default', models.CharField(default='', max_length=30)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='LinePropertyBinding',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('value', models.CharField(max_length=30)),\n ('line', models.ForeignKey(to='cwdm.Line')),\n ('prop', models.ForeignKey(to='cwdm.LineProperty')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AlterField(\n model_name='connection',\n name='up',\n field=models.ForeignKey(to='cwdm.ConnectionSide', related_name='up', null=True, blank=True, on_delete=django.db.models.deletion.PROTECT),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='connection',\n name='wavelength',\n field=models.IntegerField(choices=[(1310, 1310), (1450, 1450), (1470, 1470), (1490, 1490), (1510, 1510), (1530, 1530), (1550, 1550), (1570, 1570), (1590, 1590), (1610, 1610)]),\n preserve_default=True,\n ),\n ]\n" }, { "alpha_fraction": 0.514633059501648, "alphanum_fraction": 0.5229626297950745, "avg_line_length": 40.51401901245117, "blob_id": "8a443feb8ee839ed0bca170cc55172bf6961b90f", "content_id": "aa15117316970897a6cd5d5829f00927b5685d3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4546, "license_type": "no_license", "max_line_length": 191, "num_lines": 107, "path": "/intranet/fiber/migrations/0001_initial.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport jsonfield.fields\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('contenttypes', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Cabinet',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ('short_name', models.CharField(null=True, blank=True, max_length=50)),\n ('position', jsonfield.fields.JSONField(default={'height': 50, 'x': 0, 'y': 0, 'width': 50})),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='EndPoint',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('pigtail', models.CharField(default='FC', max_length=5)),\n ('parent_id', models.PositiveIntegerField(null=True)),\n ('connected', models.ForeignKey(to='fiber.EndPoint', on_delete=django.db.models.deletion.SET_NULL, null=True)),\n ('parent_ct', models.ForeignKey(to='contenttypes.ContentType', null=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Equipment',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('hostname', models.CharField(max_length=150)),\n ('cabinet', models.ForeignKey(to='fiber.Cabinet', null=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='EquipmentPort',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ('parent', models.ForeignKey(to='fiber.Equipment')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Odf',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(verbose_name='Название кросса', max_length=150, help_text='Что-то типа \"8A19 F02\"')),\n ('pigtail', models.CharField(default='FC', choices=[('LC', 'LC'), ('FC', 'FC'), ('SC', 'SC')], max_length=5)),\n ('col_per_group', models.IntegerField(default=8, verbose_name='Количество портов в горизонтальном ряду', help_text='Рекомендуется не больше 8, влияет только на отображение')),\n ('cabinet', models.ForeignKey(to='fiber.Cabinet', null=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='OdfPort',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=20)),\n ('index', models.IntegerField()),\n ('back', models.ForeignKey(related_name='back', to='fiber.EndPoint')),\n ('front', models.ForeignKey(related_name='front', to='fiber.EndPoint')),\n ('parent', models.ForeignKey(to='fiber.Odf')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Room',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=100)),\n ('background', models.ImageField(upload_to='')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='cabinet',\n name='room',\n field=models.ForeignKey(to='fiber.Room'),\n preserve_default=True,\n ),\n ]\n" }, { "alpha_fraction": 0.5489361882209778, "alphanum_fraction": 0.5510638356208801, "avg_line_length": 28.4375, "blob_id": "e6bda3e73db12f5427d2adb8393b3c3ded8c3034", "content_id": "96af9343cccfcf15d3469fbc7e0cb084f5698f53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 470, "license_type": "no_license", "max_line_length": 55, "num_lines": 16, "path": "/envs.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "import os\n\ndef read_environment_from_file():\n if not os.path.exists('environment.txt'):\n print(\"Environment file not found!\")\n else:\n with open('environment.txt') as f:\n envs = f.readlines()\n envs = (e.strip() for e in envs)\n envs = (e.split('=', 1) for e in envs if e)\n for name, value in envs:\n os.environ.setdefault(name, value)\n\n\nif __name__==\"__main__\":\n read_environment_from_file()" }, { "alpha_fraction": 0.7261146306991577, "alphanum_fraction": 0.7452229261398315, "avg_line_length": 30.399999618530273, "blob_id": "b0d923e19a92f70a26ec70479b3634dfdc7b3f85", "content_id": "2dff8db0f4edd781cafb13b76a3dc0bbd8683a96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 157, "license_type": "no_license", "max_line_length": 56, "num_lines": 5, "path": "/intranet/sd_api/models.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass HashLock(models.Model):\n hash = models.CharField(unique=True, max_length=100)\n expired_at = models.DateTimeField()\n" }, { "alpha_fraction": 0.6885592937469482, "alphanum_fraction": 0.6885592937469482, "avg_line_length": 23.842105865478516, "blob_id": "c7b3d558db8f5fbf037dc6efc394a88c7e245b62", "content_id": "e0b70b27a535fa537279095a2dd13f2c0154b48b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 472, "license_type": "no_license", "max_line_length": 60, "num_lines": 19, "path": "/intranet/fiber/admin.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "import inspect\n\nfrom django.db.models import Model\nfrom django.contrib.admin import site\nfrom django.contrib.admin.sites import AlreadyRegistered\nfrom . import models\n\nsite.register(models.Cabinet, list_display=('name', 'room'))\n\n\nfor name in dir(models):\n model = getattr(models, name)\n if not inspect.isclass(model):\n continue\n if issubclass(model, Model):\n try:\n site.register(model)\n except AlreadyRegistered:\n pass\n" }, { "alpha_fraction": 0.6123204231262207, "alphanum_fraction": 0.6205920577049255, "avg_line_length": 40.76363754272461, "blob_id": "81d8ce50bc4ddb1b1254cc4ac18604be91d71a36", "content_id": "3dcabd554f1e9021c08e0470c0e164492b572f95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4770, "license_type": "no_license", "max_line_length": 154, "num_lines": 110, "path": "/intranet/fiber/forms.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "from itertools import groupby\nfrom django import forms\nfrom django.forms import widgets, models\nfrom .models import Odf\nfrom .models import Cabinet\n\n\nclass OdfCreateForm(forms.ModelForm):\n first_port = forms.IntegerField(label='Номер первого порта', initial=1, min_value=0,\n help_text='Скорее всего, 1 (или 0)')\n last_port = forms.IntegerField(label='Номер последнего порта', initial=16, min_value=0)\n cabinet = forms.ModelChoiceField(queryset=Cabinet.objects, widget=forms.HiddenInput())\n\n class Meta:\n model = Odf\n fields = ['cabinet', 'name', 'pigtail', 'col_per_group']\n\n\nclass OdfMultiCreateForm(forms.Form):\n odf_lines = forms.CharField(widget=forms.Textarea,\n help_text=\"Строка за строкой, через запятую: название кросса, номер первого порта, номер последнего порта, тип разъёмов. \\\n Например, \\\"8A16 F01, 1, 32, LC\\\"\")\n cabinet = forms.ModelChoiceField(queryset=Cabinet.objects)\n\n\nclass OdfConnectToForm(forms.Form):\n odf1 = forms.ModelChoiceField(Odf.objects)\n odf2 = forms.ModelChoiceField(Odf.objects)\n port_1 = forms.IntegerField(initial=1)\n port_2 = forms.IntegerField(initial=1)\n count = forms.IntegerField()\n\n\nclass OdfMarkBusyForm(forms.Form):\n def __init__(self, ids, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for value in ids:\n f = forms.BooleanField(required=False, initial=value['initial'], label=value['label'])\n self.fields['cb_%d' % value['id']] = f\n f.index = value['index']\n print(self.initial)\n\n\nclass GroupedModelChoiceField(forms.ModelChoiceField):\n def __init__(self, queryset, group_by_field, group_label=None, *args, **kwargs):\n \"\"\"\n group_by_field is the name of a field on the model\n group_label is a function to return a label for each choice group\n \"\"\"\n super(GroupedModelChoiceField, self).__init__(queryset, *args, **kwargs)\n self.group_by_field = group_by_field\n if group_label is None:\n self.group_label = lambda group: group\n else:\n self.group_label = group_label\n\n def _get_choices(self):\n \"\"\"\n Exactly as per ModelChoiceField except returns new iterator class\n \"\"\"\n if hasattr(self, '_choices'):\n return self._choices\n return GroupedModelChoiceIterator(self)\n\n choices = property(_get_choices, forms.ModelChoiceField._set_choices)\n\n\nclass GroupedModelChoiceIterator(models.ModelChoiceIterator):\n def __iter__(self):\n if self.field.empty_label is not None:\n yield (u\"\", self.field.empty_label)\n if self.field.cache_choices:\n if self.field.choice_cache is None:\n self.field.choice_cache = [\n (self.field.group_label(group), [self.choice(ch) for ch in choices])\n for group, choices in groupby(self.queryset.all(),\n key=lambda row: getattr(row, self.field.group_by_field))\n ]\n for choice in self.field.choice_cache:\n yield choice\n else:\n for group, choices in groupby(self.queryset.all(),\n key=lambda row: getattr(row, self.field.group_by_field)):\n yield (self.field.group_label(group), [self.choice(ch) for ch in choices])\n\n\nclass OdfConnectForm1(forms.Form):\n odf1 = GroupedModelChoiceField(Odf.objects, group_by_field='cabinet')\n odf2 = GroupedModelChoiceField(Odf.objects, group_by_field='cabinet')\n\n\nclass OdfConnectForm2(forms.Form):\n port_1 = forms.ChoiceField(widget=widgets.RadioSelect, initial=0)\n port_2 = forms.ChoiceField(widget=widgets.RadioSelect, initial=0)\n count = forms.IntegerField(label='Сколько портов подряд связывать', initial=1)\n\n def __init__(self, odf_1, odf_2, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self._odf_to_field(odf_1, 'port_1')\n self._odf_to_field(odf_2, 'port_2')\n\n def _odf_to_field(self, odf, name):\n ps = odf.odfport_set.prefetch_related('back__connected__parent__parent').select_related(\n 'back__connected__parent__parent__name').all()\n self.fields[name].choices = [\n (p.index, p.name + ' (%s)' % p.back.connected.parent.parent.name if p.back.connected_id else p.name) for p\n in ps]\n self.fields[name].label = odf.name\n self.fields[name].initial = self.fields[name].choices[0][0]\n" }, { "alpha_fraction": 0.7041420340538025, "alphanum_fraction": 0.7041420340538025, "avg_line_length": 49.70000076293945, "blob_id": "1298c724102b52acb49e83632ebf217ba73f2595", "content_id": "d8ca31b48f377da2692ee02671e1ba758b303a32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1014, "license_type": "no_license", "max_line_length": 93, "num_lines": 20, "path": "/intranet/urls.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.views.generic import TemplateView\nfrom django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = [\n url(r\"^accounts/\", include(\"django.contrib.auth.urls\", namespace='auth')),\n url(r\"^cwdm/\", include(\"intranet.cwdm.urls\", namespace='cwdm')),\n url(r\"^syslog/\", TemplateView.as_view(template_name='syslog_moved.html'), name='syslog'),\n url(r\"^prm/\", include(\"intranet.prm.urls\", namespace='prm')),\n url(r\"^sd_api/\", include(\"intranet.sd_api.urls\", namespace='sd_api')),\n url(r\"^fiber/\", include(\"intranet.fiber.urls\", namespace='fiber')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^ip/', TemplateView.as_view(template_name=\"ip.html\"), name=\"ip_calc\"),\n url(r\"^$\", TemplateView.as_view(template_name=\"index.html\"), )\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n" }, { "alpha_fraction": 0.6632841229438782, "alphanum_fraction": 0.6632841229438782, "avg_line_length": 44.20833206176758, "blob_id": "5b8360884b40426214d025207ea310c4c74e1e71", "content_id": "6893b9a907e6d94993bd4d575a6778e3e9a3e225", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1084, "license_type": "no_license", "max_line_length": 116, "num_lines": 24, "path": "/intranet/fiber/urls.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, url\nfrom django.views.generic import ListView\nfrom django.views.generic import DetailView\nfrom django.views.generic import TemplateView\nfrom .models import Odf\nfrom . import views\n\n\nurlpatterns = [\n url(r'odf/connect/$', views.connect_wizard, name='odf_connect'),\n url(r'^odf/connect/(?P<step>.+)/$', views.connect_wizard, name='odf_connect_step'),\n url(r'odf/(?P<id>.*)/busy/$', views.OdfBusyView.as_view(), name='odf_markbusy'),\n url(r'odf/(?P<id>.*)/$', views.OdfDetailView.as_view(), name='odf_detail'),\n\n url(r'eq/(?P<id>.*)/$', views.OdfDetailView.as_view(), name='eq_detail'),\n\n url(r'room/(?P<pk>.*)/$', views.RoomAsMap.as_view(), name='room_asmap'),\n\n url(r'cabinet/(?P<cabinet>.*)/create-odf/$', views.OdfCreateView.as_view(), name='odf_create'),\n url(r'cabinet/(?P<cabinet>.*)/multi-create-odf/$', views.OdfMultiCreateView.as_view(), name='odf_create_multi'),\n url(r'cabinet/(?P<pk>.*)/$', views.CabinetDetailView.as_view(), name='cabinet_detail'),\n\n url(r\"^$\", views.IndexView.as_view(), name='index')\n]" }, { "alpha_fraction": 0.5351985692977905, "alphanum_fraction": 0.5351985692977905, "avg_line_length": 23.600000381469727, "blob_id": "b371371c2b7f37d4474e3f35b9c222569111e78b", "content_id": "e9f34e085fd859ecb6c49804e7d301461705f9c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1108, "license_type": "no_license", "max_line_length": 70, "num_lines": 45, "path": "/intranet/cwdm/static/js/line_filter.js", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "\nfunction buildFilters(filters){\n var rc = {}\n filters.each(function(){\n var self = $(this);\n var name = self.data('propName');\n var value = this.value;\n if (value==\"\")\n return;\n rc[name] = value;\n });\n return rc;\n}\n\nfunction applyFilters(filters, items){\n var fs = buildFilters(filters);\n var toShow = Array();\n var toHide = Array();\n items.each(function(){\n var item = $(this);\n var visible = true;\n for(var f in fs){\n var value = fs[f];\n var attr = this.getAttribute('data-prop-'+f);\n if((attr!=null) && attr!=value)\n visible = false;\n }\n if(visible)\n toShow.push(item);\n else\n toHide.push(item);\n });\n\n toShow.forEach(function(item){item.slideDown();})\n toHide.forEach(function(item){item.slideUp();})\n}\n\nfunction instalFilters(filters, items){\n filters.change(function(){\n applyFilters(filters, items);\n });\n}\n\n$(function(){\n instalFilters($(\"select.filter-parameter\"), $(\"div.filter-item\"));\n});\n" }, { "alpha_fraction": 0.675151526927948, "alphanum_fraction": 0.675151526927948, "avg_line_length": 58, "blob_id": "c2db8cf72fd66aa5abdb19e736c9e38f5f7d32cc", "content_id": "732b86db7b6ce04425ef19affedf71be0ed93751", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 825, "license_type": "no_license", "max_line_length": 113, "num_lines": 14, "path": "/intranet/cwdm/urls.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, url\nfrom .views import IndexView, OpticalPowers, EditLineView, NetworkViewJson, GraphLineView, EditTransitLineView, \\\n EditEquipmentLineView, ElementsViewJson\n\nurlpatterns = [\n url(r\"^networks.json$\", NetworkViewJson.as_view(), name='ajax_network'),\n url(r\"^optical_powers.json$\",OpticalPowers.as_view(), name=\"ajax_powers\"),\n url(r\"^elements.json$\", ElementsViewJson.as_view(), name=\"ajax_elements\"),\n url(r\"^(?P<pk>.+)/edit/$\", EditLineView.as_view(), name=\"edit_line\"),\n url(r\"^(?P<pk>.+)/transit/$\", EditTransitLineView.as_view(), name=\"transit_line\"),\n url(r\"^(?P<pk>.+)/equipment/$\", EditEquipmentLineView.as_view(), name=\"equipment_line\"),\n url(r\"^(?P<pk>\\d+)/$\", GraphLineView.as_view(), name=\"line\"),\n url(r\"^$\", IndexView.as_view(), name=\"index\"),\n]" }, { "alpha_fraction": 0.4283792972564697, "alphanum_fraction": 0.522864818572998, "avg_line_length": 44.75384521484375, "blob_id": "23f2b3e82866baede0c51dfe368869dbe1930bf0", "content_id": "beaf02c98e8011a48131d9a59ff8eae82864fb24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2974, "license_type": "no_license", "max_line_length": 194, "num_lines": 65, "path": "/intranet/cwdm/migrations/0008_auto_20150406_1635.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('cwdm', '0007_transit'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Equipment',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),\n ('wl', models.IntegerField(choices=[(1310, 1310), (1450, 1450), (1470, 1470), (1490, 1490), (1510, 1510), (1530, 1530), (1550, 1550), (1570, 1570), (1590, 1590), (1610, 1610)])),\n ('direciton', models.CharField(choices=[('up', 'up'), ('down', 'down')], max_length=10)),\n ('port', models.CharField(choices=[('line', 'line'), ('client_1', 'client_1'), ('client_2', 'client_2'), ('client_3', 'client_3'), ('client_4', 'client_4')], max_length=10)),\n ('description', models.TextField()),\n ('element', models.ForeignKey(to='cwdm.ElementInLine')),\n ('line', models.ForeignKey(to='cwdm.Line')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AlterField(\n model_name='transit',\n name='a_direciton',\n field=models.CharField(choices=[('up', 'up'), ('down', 'down')], max_length=10),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='transit',\n name='a_port',\n field=models.CharField(choices=[('line', 'line'), ('client_1', 'client_1'), ('client_2', 'client_2'), ('client_3', 'client_3'), ('client_4', 'client_4')], max_length=10),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='transit',\n name='a_wl',\n field=models.IntegerField(choices=[(1310, 1310), (1450, 1450), (1470, 1470), (1490, 1490), (1510, 1510), (1530, 1530), (1550, 1550), (1570, 1570), (1590, 1590), (1610, 1610)]),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='transit',\n name='z_direciton',\n field=models.CharField(choices=[('up', 'up'), ('down', 'down')], max_length=10),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='transit',\n name='z_port',\n field=models.CharField(choices=[('line', 'line'), ('client_1', 'client_1'), ('client_2', 'client_2'), ('client_3', 'client_3'), ('client_4', 'client_4')], max_length=10),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='transit',\n name='z_wl',\n field=models.IntegerField(choices=[(1310, 1310), (1450, 1450), (1470, 1470), (1490, 1490), (1510, 1510), (1530, 1530), (1550, 1550), (1570, 1570), (1590, 1590), (1610, 1610)]),\n preserve_default=True,\n ),\n ]\n" }, { "alpha_fraction": 0.6576354503631592, "alphanum_fraction": 0.6576354503631592, "avg_line_length": 26.066667556762695, "blob_id": "b7115f0f5e8de6c152c9dcd17baa554453bfe650", "content_id": "71d8ab17e7237f5ece0e524083e14846b333cfc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 406, "license_type": "no_license", "max_line_length": 56, "num_lines": 15, "path": "/intranet/cwdm/templatetags/cwdm.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "from logging import debug\nfrom django import template\nfrom django.utils.safestring import mark_safe\n\nregister = template.Library()\n\[email protected]_tag\ndef form_field(form, element, l, mode, *args, **kwargs):\n key = \"%d-%d-%s\" % (element.id, l, mode)\n f = form[key]\n attrs = kwargs\n if f.errors:\n attrs['has_error'] = 'True'\n ret = f.as_widget(attrs=attrs)\n return mark_safe(ret)\n" }, { "alpha_fraction": 0.49626246094703674, "alphanum_fraction": 0.5614618062973022, "avg_line_length": 43.592594146728516, "blob_id": "189180c9ed5e5657a743dfb3828313bd4a508533", "content_id": "7f2165a041487d84ead254f63d1f90ce9b1c80e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2408, "license_type": "no_license", "max_line_length": 262, "num_lines": 54, "path": "/intranet/prm/migrations/0001_initial.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Element',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('code', models.CharField(max_length=100, verbose_name=b'\\xd0\\x9d\\xd0\\xb0\\xd0\\xb7\\xd0\\xb2\\xd0\\xb0\\xd0\\xbd\\xd0\\xb8\\xd0\\xb5 \\xd1\\x8d\\xd0\\xbb\\xd0\\xb5\\xd0\\xbc\\xd0\\xb5\\xd0\\xbd\\xd1\\x82\\xd0\\xb0')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Node',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('city', models.TextField(verbose_name=b'\\xd0\\x93\\xd0\\xb5\\xd0\\xbe\\xd0\\xb3\\xd1\\x80\\xd0\\xb0\\xd1\\x84\\xd0\\xb8\\xd0\\xb5\\xd1\\x81\\xd0\\xba\\xd0\\xbe\\xd0\\xb5 \\xd0\\xbd\\xd0\\xb0\\xd0\\xb8\\xd0\\xbc\\xd0\\xb5\\xd0\\xbd\\xd0\\xbe\\xd0\\xb2\\xd0\\xb0\\xd0\\xbd\\xd0\\xb8\\xd0\\xb5')),\n ('address', models.TextField(verbose_name=b'\\xd0\\x90\\xd0\\xb4\\xd1\\x80\\xd0\\xb5\\xd1\\x81')),\n ('code', models.CharField(max_length=10)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Subrack',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('old_name', models.CharField(max_length=100, null=True, verbose_name=b'\\xd0\\xa1\\xd1\\x82\\xd0\\xb0\\xd1\\x80\\xd0\\xbe\\xd0\\xb5 \\xd0\\xbd\\xd0\\xb0\\xd0\\xb7\\xd0\\xb2\\xd0\\xb0\\xd0\\xbd\\xd0\\xb8\\xd0\\xb5', blank=True)),\n ('type', models.CharField(max_length=100, verbose_name=b'\\xd0\\xa2\\xd0\\xb8\\xd0\\xbf \\xd0\\xbe\\xd0\\xb1\\xd0\\xbe\\xd1\\x80\\xd1\\x83\\xd0\\xb4\\xd0\\xbe\\xd0\\xb2\\xd0\\xb0\\xd0\\xbd\\xd0\\xb8\\xd1\\x8f')),\n ('new_name', models.CharField(max_length=100)),\n ('element', models.ForeignKey(to='prm.Element')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='element',\n name='node',\n field=models.ForeignKey(to='prm.Node'),\n preserve_default=True,\n ),\n ]\n" }, { "alpha_fraction": 0.5529366135597229, "alphanum_fraction": 0.5633693933486938, "avg_line_length": 33.47999954223633, "blob_id": "98103cb4d8b4fc57c26a98574a091951c8bb9f4b", "content_id": "3cc8de92182107dc1e33b3aaaff901fb8f3e8755", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2588, "license_type": "no_license", "max_line_length": 140, "num_lines": 75, "path": "/intranet/cwdm/migrations/0003_auto_20141205_0958.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\ndef create_connectionSides(apps, schema_editor):\n def convert_string_to_side(str):\n slot, board, port = str.split()\n slot = int(slot)\n return {'slot': slot, 'board': board, 'port': port, 'is_transit': False, 'has_client': True}\n\n Connection = apps.get_model('cwdm', 'Connection')\n ConnectionSide = apps.get_model('cwdm', 'ConnectionSide')\n\n for con in Connection.objects.all():\n up = down = None\n if con.up:\n up = ConnectionSide(**convert_string_to_side(con.up))\n print(up)\n if con.down:\n down = ConnectionSide(**convert_string_to_side(con.down))\n print(down)\n if up and down:\n up.has_client = not down.port.startswith('Client')\n down.has_client = not up.port.startswith('Client')\n if up:\n up.save()\n con.side_up = up\n if down:\n down.save()\n con.side_down = down\n con.save()\n\n\ndef create_connectionstring(apps, schema_editor):\n pass\n\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('cwdm', '0002_auto_20141125_1105'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ConnectionSide',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('slot', models.PositiveIntegerField(blank=True, null=True)),\n ('board', models.CharField(choices=[('1GE', '1GE'), ('2GE', '2GE'), ('4GE', '4GE')], blank=True, null=True, max_length=10)),\n ('port', models.CharField(blank=True, null=True, max_length=10)),\n ('has_client', models.BooleanField(default=True)),\n ('is_transit', models.BooleanField(default=False)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='connection',\n name='side_down',\n field=models.ForeignKey(to='cwdm.ConnectionSide', related_name='down', blank=True, null=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='connection',\n name='side_up',\n field=models.ForeignKey(to='cwdm.ConnectionSide', related_name='up', blank=True, null=True),\n preserve_default=True,\n ),\n migrations.RunPython(create_connectionSides, create_connectionstring)\n ]\n\n\n" }, { "alpha_fraction": 0.5298869013786316, "alphanum_fraction": 0.5460420250892639, "avg_line_length": 22.80769157409668, "blob_id": "f1eeabe0d7b938e11b1bc13570cd97d36737272d", "content_id": "26e6c6ba676c65671cee4ecad8c7a7a6d680c226", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 619, "license_type": "no_license", "max_line_length": 74, "num_lines": 26, "path": "/intranet/prm/migrations/0002_auto_20141028_1447.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('prm', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='subrack',\n name='addon',\n field=models.CharField(max_length=20, null=True, blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='subrack',\n name='new_name',\n field=models.CharField(max_length=100, null=True, blank=True),\n preserve_default=True,\n ),\n ]\n" }, { "alpha_fraction": 0.663239061832428, "alphanum_fraction": 0.6691365242004395, "avg_line_length": 32.91794967651367, "blob_id": "7d9b2d147d3b49a4158c15f11149443cacff4d67", "content_id": "a079b59f744216c537d8b23aaff071a28a45bba2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6613, "license_type": "no_license", "max_line_length": 110, "num_lines": 195, "path": "/intranet/settings/base.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "# Django settings for app project.\nimport os\n\nproject = lambda *x: os.path.normpath(os.path.join(os.path.abspath(os.path.dirname(__file__)), \"..\", *x))\nroot = lambda *x: os.path.normpath(os.path.join(project(\"..\"), *x))\n\nDEBUG = False\n\nADMINS = (\n # ('Your Name', '[email protected]'),\n)\n\nMANAGERS = ADMINS\n\nDATABASES = {}\nDATABASES[\"default\"] = {\n 'ENGINE': os.getenv('DJANGO_DB_ENGINE', ''), # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': os.getenv('DJANGO_DB_NAME', ''), # Or path to database file if using sqlite3.\n 'USER': os.getenv('DJANGO_DB_USER', ''), # Not used with sqlite3.\n 'PASSWORD': os.getenv('DJANGO_DB_PASSWORD', ''), # Not used with sqlite3.\n 'HOST': os.getenv('DJANGO_DB_HOST', ''), # Set to empty string for localhost. Not used with sqlite3.\n 'PORT': os.getenv('DJANGO_DB_PORT', ''), # Set to empty string for default. Not used with sqlite3.\n}\n\n# Hosts/domain names that are valid for this site; required if DEBUG is False\n# See https://docs.djangoproject.com/en/1.4/ref/settings/#allowed-hosts\nALLOWED_HOSTS = []\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\nTIME_ZONE = 'Asia/Yekaterinburg'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'ru-ru'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale.\nUSE_L10N = True\n\n# If you set this to False, Django will not use timezone-aware datetimes.\nUSE_TZ = True\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/home/media/media.lawrence.com/media/\"\nMEDIA_ROOT = root(\"media\")\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash.\n# Examples: \"http://media.lawrence.com/media/\", \"http://example.com/media/\"\nMEDIA_URL = \"/media/\"\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/home/media/media.lawrence.com/static/\"\nSTATIC_ROOT = root(\"static\")\n\n# URL prefix for static files.\n# Example: \"http://media.lawrence.com/static/\"\nSTATIC_URL = '/static/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n # project(\"static\"),\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'sass_processor.finders.CssFinder',\n\n # 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = os.getenv(\"DJANGO_SECRET_KEY\", \"foobar\")\n\nMIDDLEWARE_CLASSES = [\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n # Uncomment the next line for simple clickjacking protection:\n # 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'intranet.urls'\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = 'intranet.wsgi.application'\n\nINSTALLED_APPS = [\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n \"django.contrib.admin\",\n # Uncomment the next line to enable admin documentation:\n # 'django.contrib.admindocs',\n \"bootstrap3\",\n 'fixture_media',\n 'intranet.cwdm',\n 'intranet.design',\n 'intranet.prm',\n 'intranet.sd_api',\n 'intranet.fiber',\n 'sass_processor',\n]\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = root('static')\nMEDIA_URL = '/media/'\nMEDIA_ROOT = root('media')\n\nBOOTSTRAP_BASE_URL = STATIC_URL\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [project(\"templates\"), ],\n 'OPTIONS': {\n 'context_processors': [\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n 'django.core.context_processors.tz',\n 'django.contrib.messages.context_processors.messages',\n \"django.core.context_processors.request\",\n ],\n 'loaders': [\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n ],\n 'debug': DEBUG\n }\n }\n]\n\nTEST_RUNNER = 'intranet.testrunners.ManagedModelTestRunner'\n\nSASS_PROCESSOR_INCLUDE_DIRS = (\n project('design', 'scss'),\n project('node_modules'),\n)\nSASS_OUTPUT_STYLE = 'compact'\n\nCWDM_ADAPTER_URL_TEMPLATE = 'http://10.178.227.142:50005/cwdm/optical/{ip}-{slot}-{board}.json'" }, { "alpha_fraction": 0.7829076647758484, "alphanum_fraction": 0.7829076647758484, "avg_line_length": 28.91176414489746, "blob_id": "c8cb5f4cf1eee50ed13f330bbaf13c9bb4612129", "content_id": "82ab06bbbce55e35162510f4ddb3f79357c2d978", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1018, "license_type": "no_license", "max_line_length": 111, "num_lines": 34, "path": "/intranet/cwdm/admin.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import ElementInLine, Line, Connection, ConnectionSide, LineProperty, LinePropertyBinding, Transit\n\n\nclass ConnectionAdmin(admin.TabularInline):\n model = Connection\n\n\nclass ElementInLineAdmin(admin.TabularInline):\n model = ElementInLine\n inlines = [ConnectionAdmin]\n\nclass LinePropertyBindingInlineAdmin(admin.TabularInline):\n model = LinePropertyBinding\n def has_add_permission(self, request):\n return False\n def has_delete_permission(self, request, obj=None):\n return False\n class Meta:\n allow_create = False\n\nclass LinePropertyAdmin(admin.ModelAdmin):\n inlines = [LinePropertyBindingInlineAdmin]\n\nclass LineAdmin(admin.ModelAdmin):\n inlines = [ElementInLineAdmin, LinePropertyBindingInlineAdmin]\n\n\nadmin.site.register(ElementInLine)\nadmin.site.register(Line, LineAdmin)\nadmin.site.register(Connection)\nadmin.site.register(ConnectionSide)\nadmin.site.register(Transit)\nadmin.site.register(LineProperty, LinePropertyAdmin)\n\n" }, { "alpha_fraction": 0.46172598004341125, "alphanum_fraction": 0.5012189149856567, "avg_line_length": 33.18333435058594, "blob_id": "719291924c0fc447136e51924a04f7c2aa709f84", "content_id": "2335997db5ab529e772d521861b37a8faa39812a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2051, "license_type": "no_license", "max_line_length": 188, "num_lines": 60, "path": "/intranet/cwdm/migrations/0001_initial.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Connection',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('wavelength', models.IntegerField(choices=[(1310, 1310), (1470, 1470), (1490, 1490), (1510, 1510), (1530, 1530), (1550, 1550), (1570, 1570), (1590, 1590), (1610, 1610)])),\n ('up', models.CharField(max_length=50, null=True, blank=True)),\n ('down', models.CharField(max_length=50, null=True, blank=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='ElementInLine',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ('ip', models.IPAddressField()),\n ('order', models.IntegerField()),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Line',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ],\n options={\n 'ordering': ['name'],\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='elementinline',\n name='line',\n field=models.ForeignKey(to='cwdm.Line'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='connection',\n name='element',\n field=models.ForeignKey(to='cwdm.ElementInLine'),\n preserve_default=True,\n ),\n ]\n" }, { "alpha_fraction": 0.6284008026123047, "alphanum_fraction": 0.6357000470161438, "avg_line_length": 24.116666793823242, "blob_id": "e71b5f5606918c6d8b5d0d093a865a97deb4367e", "content_id": "767364afc55427776e63c8912422c85b6e4f5bf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1507, "license_type": "no_license", "max_line_length": 70, "num_lines": 60, "path": "/intranet/sd_api/views.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "from datetime import timedelta\nimport time\n\nfrom django.http import HttpResponse\nfrom django.db import IntegrityError\nfrom django.utils import timezone\n\nfrom .models import HashLock\n\n\nclass Lock(object):\n @staticmethod\n def lock(name, delta=None):\n if delta is None:\n delta = timedelta(minutes=1)\n now = timezone.now()\n HashLock.objects.filter(expired_at__lt=now).delete()\n try:\n HashLock.objects.create(hash=name, expired_at=now + delta)\n return True\n except IntegrityError:\n return False\n\n @staticmethod\n def release(name):\n HashLock.objects.filter(hash=name).delete()\n\n @staticmethod\n def acquire(name, timeout):\n end = timezone.now()+timeout\n while timezone.now()<end:\n time.sleep(0.1)\n if Lock.lock(name):\n return True\n return False\n\n\nclass HttpResponseConflict(HttpResponse):\n status_code = 409\n\n\ndef hash_release(request, hash, *args, **kwargs):\n Lock.release(hash)\n return HttpResponse()\n\n\ndef hash_lock(request, hash, *args, **kwargs):\n minutes = int(request.GET.get('minutes', 0))\n seconds = int(request.GET.get('seconds', 0))\n if minutes == 0 and seconds == 0:\n minutes = 1\n delta = timedelta(minutes=minutes, seconds=seconds)\n if Lock.lock(hash, delta):\n return HttpResponse()\n else:\n return HttpResponseConflict()\n\n\ndef hash_check(request, *args, **kwargs):\n return HttpResponse()\n" }, { "alpha_fraction": 0.5656035542488098, "alphanum_fraction": 0.5754945278167725, "avg_line_length": 40.63865661621094, "blob_id": "98226c9e1a8386835e7ca728078f2dbda6f60e28", "content_id": "50bd0d9d101a91f3159726a8e289b946b96df67f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5051, "license_type": "no_license", "max_line_length": 123, "num_lines": 119, "path": "/intranet/cwdm/forms.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "# encoding:utf-8\n\nfrom itertools import chain\n\nfrom django import forms\nfrom django.core.exceptions import ValidationError\nfrom django.forms import ModelForm, inlineformset_factory\nfrom .models import Line, lambdas, Connection, ConnectionSide, Transit, Equipment\n\nport_choises = [\n (None, '-----'),\n ('1GE', (('1GE Line_A', 'Line-A'), ('1GE Line_B', 'Line-B'), ('1GE Client', 'Client'))),\n ('2GE', (('2GE Line', 'Line'), ('2GE Client_1', 'Client-1'), ('2GE Client_2', 'Client-2'))),\n ('4GE', (('4GE Line_A', 'Line-A'), ('4GE Line_B', 'Line-B'), ('4GE Client_1', 'Client-1'),\n ('4GE Client_2', 'Client-2'), ('4GE Client_3', 'Client-3'), ('4GE Client_4', 'Client-4'))),\n ('10G', (('10G Line_A', 'Line-A'), ('10G Line_B', 'Line-B'), ('10G Client', 'Client'))),\n\n (u'СП', (('Sp A', u'Порт №1'), ('Sp B', u'Порт №2')))]\n\n\nclass ConnectionSideWidget(forms.MultiWidget):\n def __init__(self):\n widgets = [\n forms.CheckboxInput(attrs={'title': 'Транзит'}),\n forms.CheckboxInput(attrs={'title': 'Есть клиенты'}),\n forms.TextInput(attrs={'title': 'Слот'}),\n forms.Select(choices=port_choises)\n ]\n super().__init__(widgets)\n\n def decompress(self, value):\n if value:\n if value.is_transit:\n return value.is_transit, value.has_client, None, None\n else:\n return value.is_transit, value.has_client, value.slot, \"%s %s\" % (value.board, value.port)\n else:\n return None, None, None, None\n\n def render(self, *args, **kwargs):\n attrs = kwargs['attrs']\n has_error = attrs.get('has_error', False)\n rc = super().render(*args, **kwargs)\n if has_error:\n return \"<div style='background-color:rgb(253, 228, 228)'>\" + rc + \"</div>\"\n else:\n return \"<div>\" + rc + \"</div>\"\n\n def format_output(self, rendered_widgets):\n return \"%s<div>%s</div>\" % (rendered_widgets[0], ''.join(rendered_widgets[1:]))\n\n\nclass ConnectionSideField(forms.Field):\n def validate(self, value):\n super().validate(value)\n if not value:\n return\n if value.is_transit and (value.board or value.port or value.slot):\n raise ValidationError(\"Или transit, или плата/порт\")\n if value.is_transit and value.has_client:\n raise ValidationError(\"Или transit, или клиенты\")\n if not value.is_transit and not (value.slot and value.board and value.slot):\n raise ValidationError(\"Слот/Плата/порт\")\n if value.has_client and not (value.slot and value.board and value.slot):\n raise ValidationError(\"Клиент и Слот/Плата/порт\")\n\n def to_python(self, value):\n is_transit, has_client, slot, board_port = value\n if board_port:\n board, port = board_port.split()\n else:\n board = port = None\n if not slot:\n slot = None\n if is_transit or slot or board or port:\n side = ConnectionSide.objects.create(is_transit=is_transit, has_client=has_client, slot=slot, board=board,\n port=port)\n return side\n return None\n\n\nclass LineForm(ModelForm):\n class Meta:\n model = Line\n fields = ['name', ]\n\n def __init__(self, *args, **kwargs):\n super(LineForm, self).__init__(*args, **kwargs)\n elements = self.instance.elementinline_set.all()\n connections = [e.connection_set.prefetch_related('up','down').all() for e in self.instance.elementinline_set.all()]\n connections = list(chain(*connections))\n for c in connections:\n key = \"%d-%d\" % (c.element_id, c.wavelength)\n self.initial[key + '-up'] = c.up\n self.initial[key + '-down'] = c.down\n\n for element in elements:\n for wavelength in lambdas:\n key = \"%d-%d\" % (element.id, wavelength)\n self.fields[key + '-up'] = ConnectionSideField(required=False, widget=ConnectionSideWidget)\n self.fields[key + '-down'] = ConnectionSideField(required=False, widget=ConnectionSideWidget)\n\n def save(self, commit=True):\n rc = super(LineForm, self).save(commit)\n elements = self.instance.elementinline_set.all()\n Connection.objects.filter(element__pk__in=elements).delete()\n for element in elements:\n for l in lambdas:\n key = \"%d-%d\" % (element.id, l)\n if not self.cleaned_data[key + '-up'] and not self.cleaned_data[key + '-down']:\n continue\n up = self.cleaned_data[key + '-up']\n down = self.cleaned_data[key + '-down']\n Connection(wavelength=l, element=element, up=up, down=down).save()\n return rc\n\n\nTransitFormset = inlineformset_factory(Line, Transit, exclude=[])\nEquipmentFormset = inlineformset_factory(Line, Equipment, exclude=[])" }, { "alpha_fraction": 0.6602316498756409, "alphanum_fraction": 0.6640926599502563, "avg_line_length": 15.125, "blob_id": "6e2791a33c0437e5e3f910efef3cb37fa9f2fc78", "content_id": "3db60a2740acb45c3886e6985ad0a1027e6323ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 259, "license_type": "no_license", "max_line_length": 54, "num_lines": 16, "path": "/intranet/settings/development.py", "repo_name": "Zagrebelin/intranet", "src_encoding": "UTF-8", "text": "from .base import *\n\n\nTEMPLATES[0]['OPTIONS']['debug'] = DEBUG = True\n\nMIDDLEWARE_CLASSES += [\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n]\n\nINSTALLED_APPS += [\n \"debug_toolbar\",\n]\n\nDEBUG_TOOLBAR_CONFIG = {\n \"INTERCEPT_REDIRECTS\": False,\n}\n\n" } ]
42
andrew-li729/CIS-2348-Homework-3
https://github.com/andrew-li729/CIS-2348-Homework-3
e14c5cfa74c764dfb28d2a896466630ea950d4b3
cdf9cd8376fdd22e96b3c36fc3c9ba1295da4d5d
8b120f54051a640baa33802b1df1c29967c6f1e5
refs/heads/master
2023-01-09T02:03:57.646744
2020-10-30T23:48:21
2020-10-30T23:48:21
307,790,634
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5733333230018616, "alphanum_fraction": 0.5968627333641052, "avg_line_length": 33.43243408203125, "blob_id": "bb993ae078116520ef99a815d92489030be8e7ff", "content_id": "7ca14683f9b621e7bef0968e5a599f47537afb14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1275, "license_type": "no_license", "max_line_length": 99, "num_lines": 37, "path": "/Lab_10.11.py", "repo_name": "andrew-li729/CIS-2348-Homework-3", "src_encoding": "UTF-8", "text": "# Andrew Li\n# 1824794\nclass FoodItem:\n def __init__(self, name=\"None\", fat=0, carbs=0, protein=0):\n self.name = name\n self.fat = fat\n self.carbs = carbs\n self.protein = protein\n\n def get_calories(self, num_servings):\n # Calorie formula\n calories = ((self.fat * 9) + (self.carbs * 4) + (self.protein * 4)) * num_servings;\n return calories\n\n def print_info(self):\n print('Nutritional information per serving of {}:'.format(self.name))\n print(' Fat: {:.2f} g'.format(self.fat))\n print(' Carbohydrates: {:.2f} g'.format(self.carbs))\n print(' Protein: {:.2f} g'.format(self.protein))\n\n\nif __name__ == '__main__':\n name = input()\n fat = float(input())\n carbs = float(input())\n protein = float(input())\n num_servings = float(input())\n\n food_1 = FoodItem()\n total_calories1 = food_1.get_calories(num_servings)\n food_1.print_info()\n print(\"Number of calories for {:.2f} serving(s): {:.2f}\".format(num_servings, total_calories1))\n print()\n food2 = FoodItem(name, fat, carbs, protein)\n total_calories2 = food2.get_calories(num_servings)\n food2.print_info()\n print(\"Number of calories for {:.2f} serving(s): {:.2f}\".format(num_servings, total_calories2))\n\n" }, { "alpha_fraction": 0.5594391822814941, "alphanum_fraction": 0.563783586025238, "avg_line_length": 34.914894104003906, "blob_id": "d8e98981b9ca2c1f577e8a54c1de4481280a91f0", "content_id": "812160a93c18fcf95ca54a34a5102154891afeb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5064, "license_type": "no_license", "max_line_length": 114, "num_lines": 141, "path": "/Lab_10.19.py", "repo_name": "andrew-li729/CIS-2348-Homework-3", "src_encoding": "UTF-8", "text": "# Andrew Li\n# 1824794\n\nclass ItemToPurchase:\n def __init__(self, item_name=\"none\", item_price=0, item_quantity=0, item_description=\"none\"):\n self.item_name = item_name\n self.item_price = item_price\n self.item_quantity = item_quantity\n self.item_description = item_description\n\n def print_item_cost(self):\n print(\"{} {} @ ${:.0f} = ${:.0f}\".format(self.item_name, self.item_quantity, self.item_price,\n self.item_price * self.item_quantity))\n\n def print_item_description(self):\n print(self.item_description)\n\n def compute_total(self):\n return self.item_price * self.item_quantity\n\n\nclass ShoppingCart:\n def __init__(self, customer_name=\"none\", current_date=\"January 1, 2016\"):\n self.customer_name = customer_name\n self.current_date = current_date\n self.cart_items = []\n\n def add_item(self):\n print('ADD ITEM TO CART')\n item_name = str(input('Enter the item name:\\n'))\n item_description = str(input('Enter the item description:\\n'))\n item_price = int(input('Enter the item price:\\n'))\n item_quantity = int(input('Enter the item quantity:\\n'))\n\n self.cart_items.append(ItemToPurchase(item_name, item_price, item_quantity, item_description))\n\n def remove_item(self, item_name):\n flag = None\n item_string = item_name\n for item in self.cart_items:\n if item_string == item.item_name:\n flag = True\n del self.cart_items[self.cart_items.index(item)]\n break\n else:\n flag = False\n if not flag:\n print(\"Item not found in cart. Nothing removed.\")\n\n def modify_item(self, ItemToPurchase):\n item_string = ItemToPurchase\n new_quantity = int(input(\"Enter the new quantity:\\n\"))\n flag = None\n for item in self.cart_items:\n if item_string == item.item_name:\n item.item_quantity = new_quantity\n flag = True\n break\n else:\n flag = False\n if not flag:\n print(\"Item not found in cart. Nothing modified.\")\n\n def get_num_items_in_cart(self):\n num_items = 0\n for item in self.cart_items:\n num_items += item.item_quantity\n return num_items\n\n def get_cost_of_cart(self):\n total = 0\n for item in self.cart_items:\n cost = item.item_price * item.item_quantity\n total += cost\n return total\n\n def print_total(self):\n if not self.cart_items:\n print(\"{}'s Shopping Cart - {}\".format(self.customer_name, self.current_date))\n print(\"Number of Items: {}\\n\".format(self.get_num_items_in_cart()))\n print(\"SHOPPING CART IS EMPTY\\n\")\n print(\"Total: ${}\".format(self.get_cost_of_cart()))\n\n else:\n print(\"{}'s Shopping Cart - {}\".format(self.customer_name, self.current_date))\n print(\"Number of Items: {}\\n\".format(self.get_num_items_in_cart()))\n for item in self.cart_items:\n print(\"{} {} @ ${:.0f} = ${:.0f}\".format(item.item_name, item.item_quantity, item.item_price,\n item.item_price * item.item_quantity))\n print()\n print(\"Total: ${}\".format(self.get_cost_of_cart()))\n\n def print_descriptions(self):\n print(\"{}'s Shopping Cart - {}\\n\".format(self.customer_name, self.current_date))\n print(\"Item Descriptions\")\n for item in self.cart_items:\n print(\"{}: {}\".format(item.item_name, item.item_description))\n\n\ndef print_menu(cart):\n option = \"\"\n print(\"MENU\")\n print(\"a - Add item to cart\")\n print(\"r - Remove item from cart\")\n print(\"c - Change item quantity\")\n print(\"i - Output items' descriptions\")\n print(\"o - Output shopping cart\")\n print(\"q - Quit\\n\")\n\n while option != 'a' and option != 'o' and option != 'i' and option != 'r' and option != 'c' and option != 'q':\n option = input('Choose an option:\\n')\n if option == 'a':\n cart.add_item()\n if option == \"r\":\n print(\"REMOVE ITEM FROM CART\")\n cart.remove_item(input(\"Enter name of item to remove:\\n\"))\n if option == \"c\":\n print(\"CHANGE ITEM QUANTITY\")\n cart.modify_item(input(\"Enter the item name:\\n\"))\n if option == \"i\":\n print(\"OUTPUT ITEMS' DESCRIPTIONS\")\n cart.print_descriptions()\n if option == \"o\":\n print(\"OUTPUT SHOPPING CART\")\n cart.print_total()\n return option\n\n\nif __name__ == '__main__':\n # initialize and print customer name and date\n name = input(\"Enter customer's name:\\n\")\n date = input(\"Enter today's date:\\n\")\n print()\n print(\"Customer name:\", name)\n print(\"Today's date:\", date)\n option = \"\"\n # create ShoppingCart object\n cart1 = ShoppingCart(customer_name=name, current_date=date)\n while option != \"q\":\n print(\"\")\n option = print_menu(cart1)\n" }, { "alpha_fraction": 0.5856930017471313, "alphanum_fraction": 0.5901639461517334, "avg_line_length": 29.5, "blob_id": "f0e1e7ffa50f65c7bc375d903210de3277b4774d", "content_id": "fa80173c6cd73d6079131d3c88d654a7ec050bc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2013, "license_type": "no_license", "max_line_length": 114, "num_lines": 66, "path": "/Lab_11.27.py", "repo_name": "andrew-li729/CIS-2348-Homework-3", "src_encoding": "UTF-8", "text": "# Andrew Li\n# 1824794\n\nplayer_dict = {}\nkey_list = []\noption = ''\n\n# gets user input and adds to dictionary\nfor i in range(1, 6):\n jersey_num = input(\"Enter player {}'s jersey number:\\n\".format(i))\n player_rating = input(\"Enter player {}'s rating:\\n\".format(i))\n print()\n player_dict[jersey_num] = player_rating\n# print(player_dict)\n\n# adds dict keys to list to be able to be sorted\nfor key in player_dict:\n key_list.append(key)\n\n\ndef print_roster():\n key_list.sort(key=int)\n # print(key_list) # for debugging\n\n # prints roster created from user inputs\n\n print(\"ROSTER\")\n for key in key_list:\n print(\"Jersey number: {}, Rating: {}\".format(key, player_dict[key]))\n\n\nprint_roster()\nwhile option != 'q':\n option = ''\n print(\"\\nMENU\")\n print(\"a - Add player\")\n print(\"d - Remove player\")\n print(\"u - Update player rating\")\n print(\"r - Output players above a rating\")\n print(\"o - Output roster\")\n print(\"q - Quit\\n\")\n\n while option != 'a' and option != 'd' and option != 'u' and option != 'r' and option != 'o' and option != 'q':\n option = input('Choose an option:\\n')\n if option == 'a':\n new_jersey = input(\"Enter a new player's jersey number:\\n\")\n new_rating = input(\"Enter the player's rating:\\n\")\n player_dict[new_jersey] = new_rating\n key_list.append(new_jersey)\n\n if option == \"d\":\n key_to_delete = input(\"Enter a jersey number:\\n\")\n del player_dict[key_to_delete]\n key_list.remove(key_to_delete)\n if option == \"u\":\n jersey_num = input(\"Enter a jersey number:\\n\")\n player_rating = input(\"Enter a new rating for player:\\n\")\n player_dict[jersey_num] = player_rating\n if option == \"r\":\n rating = input(\"Enter a rating:\\n\")\n print(\"\\nABOVE\", rating)\n for key in key_list:\n if player_dict[key] > rating:\n print(\"Jersey number: {}, Rating: {}\".format(key, player_dict[key]))\n if option == \"o\":\n print_roster()\n" }, { "alpha_fraction": 0.56175297498703, "alphanum_fraction": 0.5976095795631409, "avg_line_length": 19.91666603088379, "blob_id": "9785a510263202c018131ad09bce21afe151aa4a", "content_id": "a3f78412c3e9aa98243cbf27a5450e624806a2b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 251, "license_type": "no_license", "max_line_length": 38, "num_lines": 12, "path": "/Lab_11.18.py", "repo_name": "andrew-li729/CIS-2348-Homework-3", "src_encoding": "UTF-8", "text": "# Andrew Li\n# 1824794\n\ninput_list = input().split(\" \")\nfor i in range(0, len(input_list)):\n input_list[i] = int(input_list[i])\ninput_list.sort()\n# print(input_list) # for debugging\n\nfor num in input_list:\n if num >= 0:\n print(num, end=' ')\n" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.6302521228790283, "avg_line_length": 15.714285850524902, "blob_id": "2d559aaf31268a54d198c727b19e065025b7d2af", "content_id": "cd5bee6c5e125e386cdf539dffab87a91d641c18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 119, "license_type": "no_license", "max_line_length": 39, "num_lines": 7, "path": "/Lab_11.22.py", "repo_name": "andrew-li729/CIS-2348-Homework-3", "src_encoding": "UTF-8", "text": "# Andrew Li\n# 1824794\n\ninput_list = input().split(\" \")\n\nfor word in input_list:\n print(word, input_list.count(word))\n\n\n" }, { "alpha_fraction": 0.6051364541053772, "alphanum_fraction": 0.6308186054229736, "avg_line_length": 32.67567443847656, "blob_id": "a83b8f0557bfd7ca15f1b3659eef831ee666cb51", "content_id": "446ebe2bcea53eb500616c519921b3819bd6ac6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1246, "license_type": "no_license", "max_line_length": 140, "num_lines": 37, "path": "/Lab_10.17.py", "repo_name": "andrew-li729/CIS-2348-Homework-3", "src_encoding": "UTF-8", "text": "# Andrew Li\n# 1824794\n\nclass ItemToPurchase:\n def __init__(self, item_name=\"none\", item_price=0, item_quantity=0):\n self.item_name = item_name\n self.item_price = item_price\n self.item_quantity = item_quantity\n\n def print_item_cost(self):\n print(\"{} {} @ ${:.0f} = ${:.0f}\".format(self.item_name, self.item_quantity, self.item_price, self.item_price * self.item_quantity))\n\n def compute_total(self):\n return self.item_price * self.item_quantity\n\n\nif __name__ == '__main__':\n print(\"Item 1\")\n item1_name = input(\"Enter the item name:\\n\")\n item1_price = float(input(\"Enter the item price:\\n\"))\n item1_quantity = int(input(\"Enter the item quantity:\\n\"))\n item1 = ItemToPurchase(item1_name, item1_price, item1_quantity)\n print()\n\n print(\"Item 2\")\n item2_name = input(\"Enter the item name:\\n\")\n item2_price = float(input(\"Enter the item price:\\n\"))\n item2_quantity = int(input(\"Enter the item quantity:\\n\"))\n item2 = ItemToPurchase(item2_name, item2_price, item2_quantity)\n print()\n\n print(\"TOTAL COST\")\n item1.print_item_cost()\n item2.print_item_cost()\n total = item1.compute_total() + item2.compute_total()\n print()\n print(\"Total: ${:.0f}\".format(total))\n" } ]
6
grizzlypeaksoftware/tankbot
https://github.com/grizzlypeaksoftware/tankbot
fbe07575b8114125268ef3972cfc8f0ce92b0765
db430558e72da0227e1ba6f75d9b6f267a6d1fe7
8309d4530205569e5c06c39b096fc63a8947f782
refs/heads/master
2020-12-02T00:34:31.370808
2020-01-07T05:01:25
2020-01-07T05:01:25
230,830,970
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6351144909858704, "alphanum_fraction": 0.6778625845909119, "avg_line_length": 14.423529624938965, "blob_id": "1bfa413701ff2560eeb55089bb7b674bc3c914f7", "content_id": "d3b57720553172381371db4486bef341cb637c6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1310, "license_type": "no_license", "max_line_length": 51, "num_lines": 85, "path": "/tankbot.py", "repo_name": "grizzlypeaksoftware/tankbot", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nfrom time import sleep\n\ndef Init():\n\tGPIO.setwarnings(False)\n\tGPIO.setmode(GPIO.BOARD)\n\n\tGPIO.setup(3,GPIO.OUT,initial=GPIO.LOW) #blue\n\tGPIO.setup(5,GPIO.OUT,initial=GPIO.LOW) #green\n\tGPIO.setup(16,GPIO.OUT,initial=GPIO.LOW) #yellow \n\tGPIO.setup(18,GPIO.OUT,initial=GPIO.LOW) #orange\n\n\tWelcome()\n\ndef Welcome():\n\tStop()\n\tForward()\n\tsleep(.5)\n\tReverse()\n\tsleep(.5)\n\tRight()\n\tsleep(1)\n\tLeft()\n\tsleep(1)\n\tStop()\n\ndef No():\n\tStop()\n\tRight()\n\tsleep(.25)\n\tLeft()\n\tsleep(.25)\n\tRight()\n\tsleep(.25)\n\tLeft()\n\tsleep(.25)\n\tStop()\n\ndef Yes():\n\tStop()\n\tForward()\n\tsleep(.25)\n\tReverse()\n\tsleep(.25)\n\tForward()\n\tsleep(.25)\n\tReverse()\n\tsleep(.25)\n\tStop()\n\ndef Forward():\n\tGPIO.output(3,GPIO.LOW)\n\tGPIO.output(5,GPIO.HIGH)\n\tGPIO.output(16,GPIO.LOW)\n\tGPIO.output(18,GPIO.HIGH)\n\ndef Reverse():\n\tGPIO.output(3,GPIO.HIGH)\n\tGPIO.output(5,GPIO.LOW)\n\tGPIO.output(16,GPIO.HIGH)\n\tGPIO.output(18,GPIO.LOW)\n\ndef Left():\n\tGPIO.output(3,GPIO.LOW)\n\tGPIO.output(5,GPIO.HIGH)\n\tGPIO.output(16,GPIO.HIGH)\n\tGPIO.output(18,GPIO.LOW)\n\ndef Right():\n\tGPIO.output(3,GPIO.HIGH)\n\tGPIO.output(5,GPIO.LOW)\n\tGPIO.output(16,GPIO.LOW)\n\tGPIO.output(18,GPIO.HIGH)\n\ndef Stop():\n\t#print(\"Stop Tankbot\")\n\tGPIO.output(3,GPIO.LOW)\n\tGPIO.output(5,GPIO.LOW)\n\tGPIO.output(16,GPIO.LOW)\n\tGPIO.output(18,GPIO.LOW)\n\n\n\ndef Close():\n\tGPIO.cleanup()" }, { "alpha_fraction": 0.646080732345581, "alphanum_fraction": 0.6496437191963196, "avg_line_length": 19.790122985839844, "blob_id": "00db0e9dd60d0b2bc52b00acd202ca6c08da8812", "content_id": "190ce77dadc968541bed61fedbece97979e5ddca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1684, "license_type": "no_license", "max_line_length": 69, "num_lines": 81, "path": "/bot.py", "repo_name": "grizzlypeaksoftware/tankbot", "src_encoding": "UTF-8", "text": "import tankbot\nimport keyboard\nimport time as _time\n\ntankbot.Init()\n\nrecorded = []\nrecording_started = False\n\ndef ControlSwitch(key, event):\n\tglobal recording_started\n\n\t#print(key)\n\t#print(event.event_type)\n\n\tif key == \"s\":\n\t\ttankbot.Stop()\n\tif key == \"up\":\n\t\ttankbot.Forward()\n\tif key == \"down\":\n\t\ttankbot.Reverse()\n\tif key == \"right\":\n\t\ttankbot.Right()\n\tif key == \"left\":\n\t\ttankbot.Left()\t\n\tif key == \"1\":\n\t\ttankbot.No()\t\n\tif key == \"2\":\n\t\ttankbot.Yes()\t\n\tif key == \"3\":\n\t\ttankbot.Welcome()\t\n\tif key == \"f1\":\n\t\tkeyboard.start_recording()\n\t\trecording_started = True\n\tif key == \"f2\":\n\t\ttry:\n\t\t\tif recording_started == True:\n\t\t\t\trecording_started = False\n\t\t\t\tPlayback(keyboard.stop_recording())\n\t\t\telse:\n\t\t\t\tPlayback(recorded)\n\t\texcept Exception as inst:\n\t\t\tprint(type(inst)) # the exception instance\n\t\t\tprint(inst.args) # arguments stored in .args\n\t\t\tprint(inst) # __str__ allows args to be printed directly,\n\tif key == \"q\":\n\t\ttankbot.Stop()\n\t\treturn False\n\treturn True\n\n\ndef Playback(rec):\n\tlast_time = None \n\tglobal recorded\n\trecorded = rec\n\n\tfor event in rec:\n\t\tif last_time is not None:\n\t\t\t_time.sleep(event.time - last_time)\n\t\tlast_time = event.time\n\t\tkey = event.scan_code or event.name\n\t\tif event.name != \"f2\":\n\t\t\tcheck = ControlSwitch(event.name, event)\n\n\ncontinueLoop = True\n\nwhile continueLoop:\n\ttry:\n\t\tkey = keyboard.read_key()\n\t\tevent = keyboard.read_event()\n\n\t\tif event.event_type == \"up\":\n\t\t\tcontinueLoop = ControlSwitch(key, event)\n\n\texcept Exception as inst:\n\t\t\tprint(type(inst)) # the exception instance\n\t\t\tprint(inst.args) # arguments stored in .args\n\t\t\tprint(inst) # __str__ allows args to be printed directly,\n\t\ntankbot.Close()\n" } ]
2
lopuhin/scrapy-s3-bench
https://github.com/lopuhin/scrapy-s3-bench
e3e3ffbf9dcbda7d47c8c70cc09d0a7b30aaaa7e
cc3eb21b5d0faafc725096e45b9d775af11721b9
867fa210c152475595fa09f0f8927eccba86eefd
refs/heads/master
2021-01-20T20:36:22.245126
2016-08-11T13:14:20
2016-08-11T13:14:20
65,555,101
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6006289124488831, "alphanum_fraction": 0.606918215751648, "avg_line_length": 27.909090042114258, "blob_id": "a90830942a203ec90ea8396099a7030c19a29b1b", "content_id": "db292e68ce0c497ccba2cf8cca213b9a967dd063", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 318, "license_type": "no_license", "max_line_length": 74, "num_lines": 11, "path": "/README.rst", "repo_name": "lopuhin/scrapy-s3-bench", "src_encoding": "UTF-8", "text": "Scrapy S3 file pipeline benchmark\n=================================\n\nRun::\n\n scrapy crawl spider \\\n -s FILES_STORE=s3://some-bucket/some-prefix/ \\\n -s AWS_ACCESS_KEY_ID=some-key \\\n -s AWS_SECRET_ACCESS_KEY=some-secret\n\nFor reproducible runs, clean storage (or change location) before each run!\n" }, { "alpha_fraction": 0.6219931244850159, "alphanum_fraction": 0.7027491331100464, "avg_line_length": 19.068965911865234, "blob_id": "36a0ca941c299d6fc6c85f6e4013bbed6b8fd3c1", "content_id": "bfaaf8f13c63d2d3c923542657c55567e09525db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 582, "license_type": "no_license", "max_line_length": 60, "num_lines": 29, "path": "/s3bench/settings.py", "repo_name": "lopuhin/scrapy-s3-bench", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nBOT_NAME = 's3bench'\n\nSPIDER_MODULES = ['s3bench.spiders']\nNEWSPIDER_MODULE = 's3bench.spiders'\n\nUSER_AGENT = (\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/51.0.2704.84 Safari/537.36')\n\nROBOTSTXT_OBEY = False\n\nCONCURRENT_REQUESTS = 32\nCONCURRENT_REQUESTS_PER_DOMAIN = 4\n\nDOWNLOAD_MAXSIZE = 1*1024*1024\n\nITEM_PIPELINES = {'scrapy.pipelines.files.FilesPipeline': 1}\n\nCOOKIES_ENABLED = False\n\nTELNETCONSOLE_ENABLED = False\n\nCLOSESPIDER_TIMEOUT = 30\nDOWNLOAD_TIMEOUT = 15\n\nLOG_LEVEL = 'INFO'\n" }, { "alpha_fraction": 0.5586034655570984, "alphanum_fraction": 0.561097264289856, "avg_line_length": 28.163637161254883, "blob_id": "724caff41b180c51121819091a02df031fd507ee", "content_id": "8ce820001cad8e125494b6290d9e7e2e9b6b95a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1604, "license_type": "no_license", "max_line_length": 79, "num_lines": 55, "path": "/s3bench/spiders.py", "repo_name": "lopuhin/scrapy-s3-bench", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport os.path\n\nimport scrapy\nfrom scrapy.linkextractors import LinkExtractor\nimport vmprof\n\n\nclass Spider(scrapy.Spider):\n name = 'spider'\n\n def __init__(self):\n with open(os.path.join(\n os.path.dirname(__file__), '..', 'top-1k.txt')) as f:\n self.start_urls = ['http://{}'.format(line.strip()) for line in f]\n\n self.le = LinkExtractor()\n self.images_le = LinkExtractor(\n tags=['img'], attrs=['src'], deny_extensions=[])\n self.files_le = LinkExtractor(\n tags=['a'], attrs=['href'], deny_extensions=[])\n\n # Set up profiling\n self.profile_filename = _get_prof_filename('vmprof')\n self.profile = open(self.profile_filename, 'wb')\n vmprof.enable(self.profile.fileno())\n\n super(Spider, self).__init__()\n\n def parse(self, response):\n get_urls = lambda le: {link.url for link in le.extract_links(response)}\n page_urls = get_urls(self.le)\n for url in page_urls:\n yield scrapy.Request(url)\n file_urls = (\n get_urls(self.images_le) | get_urls(self.files_le) - page_urls)\n yield {\n 'url': response.url,\n 'file_urls': file_urls,\n }\n\n def closed(self, _):\n vmprof.disable()\n self.profile.close()\n self.logger.info('vmprof saved to {}'.format(self.profile_filename))\n\n\ndef _get_prof_filename(prefix):\n i = 1\n while True:\n filename = '{}_{}.vmprof'.format(prefix, i)\n if not os.path.exists(filename):\n return filename\n i += 1\n" } ]
3
akabaker/firmware_state
https://github.com/akabaker/firmware_state
287332d8014ab32bae606a8e767c89b3b1520aea
62ca4a9072d11cdb352482b489233168cd19f7d7
610f728b86f55683afac01c6a726429b14343393
refs/heads/master
2020-04-05T02:10:46.283160
2010-12-24T22:15:44
2010-12-24T22:15:44
1,155,333
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6632739901542664, "alphanum_fraction": 0.6661012172698975, "avg_line_length": 25.200000762939453, "blob_id": "77020b37bf40a086bb8a0495666fcdec83a2c333", "content_id": "59658e9e8495d725367b2641944cc23dbf11473c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3537, "license_type": "no_license", "max_line_length": 117, "num_lines": 135, "path": "/firmwarestate.py", "repo_name": "akabaker/firmware_state", "src_encoding": "UTF-8", "text": "#!/usr/bin/python -tt\nfrom elementtree import ElementTree\nfrom subprocess import Popen, PIPE\nfrom urllib2 import urlopen, URLError, HTTPError\nfrom socket import gethostname\nfrom email import MIMEMultipart, MIMEText\nimport smtplib\nimport yaml\nimport re\n\nclass Omreport:\n\t\"\"\"\n\tUse omreport to determine if system firmware is up-to-date\n\n\t\"\"\"\n\n\tdef __init__(self):\n\t\t\"\"\"\n\t\tGrab XML output from omreport and store it\n\n\t\t\"\"\"\n\n\t\tself.storage_tree = self._system_xml('storage controller')\n\t\tself.system_tree = self._system_xml('system summary')\n\t\tself.model = self._system_model()\n\t\tself.hostname = gethostname()\n\t\t\n\tdef _system_xml(self, report):\n\t\t\"\"\"\n\n\t\tCall omreport and storage output as an element tree\n\t\t@param: Report is a string, command line options for omreport\n\n\t\t\"\"\"\n\n\t\ttry:\n\t\t\toutput = Popen('/opt/dell/srvadmin/bin/omreport %s -fmt xml' % (report), stdout=PIPE, shell=True).communicate()[0]\n\t\texcept OSError, e:\n\t\t\tprint \"Execution failure: %s\" % (e)\n\t\t\treturn\n\t\ttry:\n\t\t\troot = ElementTree.fromstring(output)\n\t\t\ttree = ElementTree.ElementTree(root)\n\t\texcept Exception, e:\n\t\t\tprint \"Exception: %s\" % (e)\n\t\t\treturn\n\t\treturn tree\n\t\n\tdef _system_model(self):\n\t\t\"\"\"\n\n\t\tUse facter to determine productname, i.e., r710, 2950 ,etc\n\n\t\t\"\"\"\n\n\t\ttry:\n\t\t\toutput = Popen(\"facter | awk '/productname/ {print $NF}'\", stdout=PIPE, shell=True).communicate()[0]\n\t\texcept OSError, e:\n\t\t\tprint \"Execution failure: %s\" % (e)\n\t\t\treturn\n\t\treturn output.strip()\n\ndef notify(om, yaml_data, mail_config):\n\n\ttmpl = '-%s out of date, system version: %s -- latest version: %s <br>'\n\tmsg = \"<strong>%s</strong>: <br>\" % (om.hostname)\n\n\tif 'bios' in om.errors:\n\t\tmsg += (tmpl) % ('BIOS', om.bios_ver, yaml_data['bios'])\n\n\tif 'perc' in om.errors:\n\t\tfor (key, val) in om.outofdate.items():\n\t\t\tmsg += (tmpl) % (key, val, yaml_data['percs'][key])\n\n\tmessage = MIMEMultipart.MIMEMultipart('alternative')\n\tmessage['from'] = mail_config['from']\n\tmessage['to'] = mail_config['to']\n\tmessage['subject'] = mail_config['subject']\n\tbody = MIMEText.MIMEText(msg, 'html')\n\tmessage.attach(body)\n\ts = smtplib.SMTP('localhost')\n\ts.sendmail(message['from'], message['to'], message.as_string())\n\ts.quit()\n\ndef main(types, mail_config):\n\t\"\"\"\n\n\tParams: dict that contains the name of controller type, dict containing mail configuration\n\tGather omreport data and compare to yaml data corresponding to this machines model\n\n\t\"\"\"\n\n\tom = Omreport()\n\tom.errors = []\n\tom.percs = {}\n\tom.outofdate = {}\n\tpattern = re.compile(r'%s' % (types['controller']), re.I)\n\turl = \"http://rhn.missouri.edu/pub/dell-yaml/%s.yaml\" % (om.model)\n\ttry:\n\t\treq = urlopen(url)\n\texcept URLError, e:\n\t\tprint (\"URLError: %s\") % (e)\n\texcept HTTPError, e:\n\t\tprint (\"HTTPError: %s\") % (e)\n\n\tyaml_data = yaml.load(req)\n\t# Gather PERC name and firmware version\n\tfor node in om.storage_tree.findall('//DCStorageObject'):\n\t\tperc_name = node.find('Name').text\n\t\tperc_ver = node.find('FirmwareVer').text\n\t\tom.percs[perc_name] = perc_ver\n\n\t# BIOS version is easy\n\tom.bios_ver = om.system_tree.find('//SystemBIOS/Version').text\n\t\n\t# Compare with yaml_data\n\tfor perc_name, version in om.percs.items():\n\t\tif version < yaml_data['percs'][perc_name]:\n\t\t\tom.errors.append('perc')\n\t\t\tom.outofdate[perc_name] = version\n\n\tif om.bios_ver < yaml_data['bios']:\n\t\tom.errors.append('bios')\n\t\n\tif om.errors:\n\t\tnotify(om, yaml_data, mail_config)\n\nif __name__ == \"__main__\":\n\ttypes = {'controller': 'perc'}\n\tmail_config = {\n\t\t'subject': 'Firmware_report',\n\t\t'to': '[email protected]',\n\t\t'from': 'root@%s' % (gethostname()),\n\t}\n\tmain(types, mail_config)\n" } ]
1
Leovilhena/mailbox2fs
https://github.com/Leovilhena/mailbox2fs
e4000a306e94d38e34cc3eaa964ef5dbf651400d
4f856cffcb38ab23a516598a0c0e6eb975cd523c
2de2552feaaceeded69f7fb6e6d3aead1e89e0c4
refs/heads/master
2022-12-21T07:09:50.918887
2020-09-13T22:41:06
2020-09-13T22:55:06
295,244,735
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7744510769844055, "alphanum_fraction": 0.78143709897995, "avg_line_length": 37.42307662963867, "blob_id": "252493936e801a05523f2d6124f4a81a52d4f21d", "content_id": "90d500ab37aa27496da1d6d415888e41af831130", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1002, "license_type": "no_license", "max_line_length": 129, "num_lines": 26, "path": "/README.md", "repo_name": "Leovilhena/mailbox2fs", "src_encoding": "UTF-8", "text": "# Exposing Mailbox as a Filesystem \n\nThis is the version development version for the task found at mailbox2f file.\nThere goal is to create a synthetic (pseudo) filesystem from your mailbox in read-only mode accessed via WebDav with NGINX.\n\n\nHow to run:\n\n```bash\n./run.sh\n```\n- You'll be prompt for username and password (not echoed to the terminal) regarding Fastmail.\n- There are more environment variables available to be set if needed (ex.: Other mail services). Please check the main.py script.\n\n\nHow to set App passwords: \n\nhttps://www.fastmail.com/help/clients/apppassword.html?u=9e2140d7\n\n\nConsiderations:\n\n- This is a development version which still lacks some security features.\n- The NGINX latest version was not working with WebDav, so I had to build it from the source code with WebDav and\nWebDav extension module. Both repositories were downloaded and saved into nginx/repositories folder as git submodules.\n- This new NGINX Dockerfile was based on the original one with a few changes.\n\n\n " }, { "alpha_fraction": 0.5935162305831909, "alphanum_fraction": 0.6209476590156555, "avg_line_length": 21.27777862548828, "blob_id": "7697af306e3db95c66224f0f6878f4c9b92de8e3", "content_id": "f28c8a34445352b824366c0f1062ad07862bcbbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 401, "license_type": "no_license", "max_line_length": 92, "num_lines": 18, "path": "/app/Dockerfile", "repo_name": "Leovilhena/mailbox2fs", "src_encoding": "UTF-8", "text": "FROM python:3.8-alpine\n\nLABEL maintainer=\"Leonardo Silva Vilhena <[email protected]>\"\n\nRUN set -x \\\n && addgroup -g 101 -S python \\\n && adduser -S -D -H -u 101 -h /usr/src/app -s /sbin/nologin -G python -g python python \\\n && mkdir /mailbox \\\n && chown python:python /mailbox \\\n && chmod 777 /mailbox\n\nWORKDIR /usr/src/app\n\nCOPY --chown=python:python main.py .\n\nUSER python:python\n\nCMD [ \"python\", \"./main.py\" ]\n" }, { "alpha_fraction": 0.6298959851264954, "alphanum_fraction": 0.634262204170227, "avg_line_length": 32.13616943359375, "blob_id": "fbb581ed875486be47fdaa307d474443109ab04a", "content_id": "38a4188906f74becf3ad11228b013c5468d918a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7787, "license_type": "no_license", "max_line_length": 112, "num_lines": 235, "path": "/app/main.py", "repo_name": "Leovilhena/mailbox2fs", "src_encoding": "UTF-8", "text": "import os\nimport email\nimport imaplib\nimport logging\nimport traceback\nfrom time import sleep\nfrom typing import Tuple\nfrom pathlib import Path\nfrom functools import wraps\n\n# Global variables\nSERVER = os.environ.get('FASTMAIL_IMAP_HOST', 'imap.fastmail.com')\nPORT = os.environ.get('FASTMAIL_IMAP_PORT', 993)\nUSER = os.environ.get('FASTMAIL_USER')\nPASSWORD = Path('/run/secrets/fastmail_passwd').read_text()\nREFRESH_RATE = int(os.environ.get('REFRESH_RATE', 10))\nUID_SET = set()\nMAILBOX_PATH = os.environ.get('MAILBOX_PATH', '/mailbox')\nMAILBOX_HOME = os.environ.get('MAILBOX_HOME', 'home')\n# Logging config\nlogging.basicConfig(format='[*] %(levelname)s: %(message)s', level=os.environ.get(\"LOGLEVEL\", \"INFO\"))\n\n\ndef log(msg):\n \"\"\"\n Decoratorm for printing a message before running function\n :param msg: Message to be printed before running function\n \"\"\"\n def decorator(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n logging.info(msg)\n return func(*args, **kwargs)\n return wrapper\n return decorator\n\n\ndef set_uid_track_file(file: str = '.uid_track') -> None:\n \"\"\"\n Creates or loads a .uid_track file to prevent emails to be written twice.\n If the app restarts (or simply fetches again emails), it will assume that the emails\n written on the volume are new ones, hence, assigning [number] sufix to them.\n By tracking their uid we prevent them to be doubly written.\n \"\"\"\n global UID_SET\n file = os.path.join(MAILBOX_PATH, file)\n try:\n with open(file, 'r') as fd:\n UID_SET = set(line.strip() for line in fd.readlines())\n except FileNotFoundError:\n pass\n\n\n@log('Connecting to IMAP server')\ndef get_imap_connection() -> imaplib.IMAP4_SSL:\n \"\"\"\n Get IMAP4 connection object with 'INBOX' mailbox selected\n\n :return: maplib.IMAP4_SSL object\n \"\"\"\n connection = imaplib.IMAP4_SSL(SERVER, PORT)\n connection.login(USER, PASSWORD)\n connection.select() # selects INBOX by default\n\n return connection\n\n\n@log('Parsing header fields')\ndef parse_header_fields(connection: imaplib.IMAP4_SSL, email_index: str) -> Tuple[str, str, tuple, str]:\n \"\"\"\n Parses HEADER fields sender, subject, date and Message-Id (as uid) from RFC822 standard\n\n :param connection: Connection to IMAP server\n :param email_index: Number from index list of emails\n :return: (sender, subject, date, uid)\n \"\"\"\n typ, data = connection.fetch(email_index, '(RFC822)')\n if typ != 'OK':\n raise imaplib.IMAP4.error(f'Server replied with {typ} on email {email_index} while parsing the headers')\n\n msg = email.message_from_bytes(data[0][1])\n sender = email.utils.parseaddr(msg['From'])[1]\n subject = msg[\"Subject\"]\n date = email.utils.parsedate(msg['date'])\n uid = msg['Message-ID']\n\n return sender, subject, date, uid\n\n\n@log('Parsing email body')\ndef parse_body(connection: imaplib.IMAP4_SSL, email_index: str) -> str:\n \"\"\"\n Parses email body without attachments\n\n :param connection: Connection to IMAP server\n :param email_index: Number from index list of emails\n :return: body str\n \"\"\"\n typ, data = connection.fetch(email_index, '(UID BODY[TEXT])')\n if typ != 'OK':\n raise imaplib.IMAP4.error(f'Server replied with {typ} on email {email_index} while parsing the body')\n\n body = email.message_from_bytes(data[0][1]).as_string()\n body = remove_html_from_body(body)\n return body\n\n\n@log('Erasing HTML from raw email body')\ndef remove_html_from_body(body: str) -> str:\n \"\"\"\n Email body is duplicated with HTML part, this function removes the HTML part if exists and it's duplicated.\n\n :param body: email body\n :return: body str\n \"\"\"\n body_split = body.split('\\n')\n uid = body_split[1]\n index = len(body_split)\n for i, line in enumerate(body_split):\n if uid == line:\n index = i\n parsed_body = '\\n'.join(body_split[:index])\n if parsed_body:\n return parsed_body\n\n return body\n\n\n@log('Writing to file')\ndef write_to_file(file: str, body: str, uid: str, index: int = 0) -> str:\n \"\"\"\n Write body content to file and name it after it's subject\n If the file doesn't exist the algorithm will create a new file with a number between square brackets\n based on their uid.\n\n :param file: email file name\n :param body: email body\n :param uid: email unique identifier\n :param index: index to be added to file name if it already exists\n :return: final email file name str\n \"\"\"\n\n _file = os.path.join(MAILBOX_PATH, file)\n if not os.path.isfile(_file):\n logging.info(f'New email: {_file}')\n with open(_file, 'w+') as fd:\n fd.write(body)\n update_uid_track_file(uid)\n else:\n file_split = file.rsplit('[', 1)[0]\n new_index = index + 1\n new_file = f'{file_split}[{new_index}]' # format \"subject[1]\"\n file = write_to_file(file=new_file, body=body, uid=uid, index=new_index) # recursion\n\n return file\n\n\n@log('Adding new uid to uid_track file')\ndef update_uid_track_file(uid: str, file: str = '.uid_track') -> None:\n \"\"\"\n Updates uid_track file with newly fetched uid's\n\n :param uid: email unique identifier\n :param file: uid_track file path\n \"\"\"\n file = os.path.join(MAILBOX_PATH, file)\n with open(file, 'a+') as fd:\n fd.write(f'{uid}\\n')\n logging.info(f'New {uid} added')\n UID_SET.add(uid)\n\n\n@log('Creating fs hardlink tree')\ndef create_fs_hardlink_tree(email_path: str, dest: str) -> None:\n \"\"\"\n Create directories and hardlinks at their end's according to their destination.\n\n :param email_path: path to where email is saved\n :param dest: path to where the hardlink will be created\n \"\"\"\n if not os.path.isdir(dest):\n logging.info(f'Directory at {dest} already exists. Nothing to do')\n os.makedirs(dest)\n\n dest_path = os.path.join(dest, email_path)\n src_path = os.path.join(MAILBOX_PATH, email_path)\n print(f'[*****] Path is {dest_path}')\n if not os.path.isfile(dest_path):\n logging.info(f'Creating path at {dest_path}')\n Path(src_path).link_to(dest_path)\n\n\ndef main():\n try:\n connection = get_imap_connection()\n typ, _data = connection.search(None, 'ALL')\n if typ != 'OK':\n raise imaplib.IMAP4.error(f'Server replied with {typ}')\n\n # Loop on every email fetched\n for email_index in _data[0].split():\n # Parse data\n sender, subject, date, uid = parse_header_fields(connection, email_index)\n\n if uid in UID_SET:\n logging.info('No new emails')\n continue\n # Parse body\n body = parse_body(connection, email_index)\n\n # create file at base level MAILBOX_PATH\n file = f'{sender}-{subject}'\n email_path = write_to_file(file=file, body=body, uid=uid)\n\n # create dir and symlink to email for /timeline/{year}/{month}/{day}/\n dest_date = os.path.join(MAILBOX_PATH, MAILBOX_HOME, 'timeline/{}/{}/{}/'.format(*date))\n create_fs_hardlink_tree(email_path=email_path, dest=dest_date)\n\n # create dir and symlink to email for /sender/{email}/\n dest_sender = os.path.join(MAILBOX_PATH, MAILBOX_HOME, 'sender/{}/'.format(sender))\n create_fs_hardlink_tree(email_path=email_path, dest=dest_sender)\n\n # TODO '/topics/{IMAP folder path}/'\n\n _ = connection.close() # ('OK', [b'Completed'])\n _ = connection.logout() # ('BYE', [b'LOGOUT received'])\n except imaplib.IMAP4.error:\n traceback.print_exc(limit=1)\n\n\nif __name__ == '__main__':\n set_uid_track_file()\n while True:\n main()\n sleep(REFRESH_RATE)\n" }, { "alpha_fraction": 0.6205211877822876, "alphanum_fraction": 0.6275787353515625, "avg_line_length": 22.628204345703125, "blob_id": "477cdfd479558c6ccb1b04d5a78b99b1d6e4acd3", "content_id": "a3b0965119f7237276f26e1ea3776ddd6a1dde8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1842, "license_type": "no_license", "max_line_length": 91, "num_lines": 78, "path": "/nginx/Dockerfile", "repo_name": "Leovilhena/mailbox2fs", "src_encoding": "UTF-8", "text": "FROM alpine:3\n\nLABEL maintainer=\"Leonardo Silva Vilhena <[email protected]>\"\n\nRUN set -x \\\n && apk update \\\n && apk upgrade \\\n && apk add --no-cache \\\n g++ \\\n openssl-dev \\\n zlib-dev \\\n libxslt-dev \\\n geoip-dev \\\n make\n\nRUN set -x \\\n && addgroup -g 101 -S nginx \\\n && adduser -S -D -H -u 101 -h /var/cache/nginx -s /sbin/nologin -G nginx -g nginx nginx\n\nCOPY --chown=nginx:nginx repositories/nginx /nginx\nCOPY --chown=nginx:nginx repositories/nginx-dav-ext-module /nginx/nginx-dav-ext-module\n\nWORKDIR nginx\n\nRUN set -x \\\n && /nginx/auto/configure --prefix=/opt/nginx \\\n --with-compat \\\n --with-http_addition_module \\\n --with-http_auth_request_module \\\n --with-http_dav_module \\\n --with-http_degradation_module \\\n --with-http_flv_module \\\n --with-http_geoip_module \\\n --with-http_gunzip_module \\\n --with-http_gzip_static_module \\\n --with-http_mp4_module \\\n --with-http_realip_module \\\n --with-http_secure_link_module \\\n --with-http_slice_module \\\n --with-http_ssl_module \\\n --with-http_stub_status_module \\\n --with-http_sub_module \\\n --with-http_v2_module \\\n --with-pcre-jit \\\n --with-threads \\\n --without-http_rewrite_module \\\n --without-http_geo_module \\\n --add-module=nginx-dav-ext-module\n\nRUN set -x \\\n && make \\\n && make install\n\nRUN set -x \\\n && ln -sf /dev/stdout /opt/nginx/logs/access.log \\\n && ln -sf /dev/stderr /opt/nginx/logs/error.log \\\n && mkdir /docker-entrypoint.d\n\nRUN set -x \\\n && apk del \\\n g++ \\\n make\n\nCOPY config/nginx.conf /opt/nginx/conf/nginx.conf\nCOPY --chown=nginx:nginx scripts/docker-entrypoint.sh /\n\nRUN chmod +x /docker-entrypoint.sh\nRUN chown -R nginx:nginx /opt/nginx/\n\nUSER nginx:nginx\n\nENTRYPOINT [\"/docker-entrypoint.sh\"]\n\nEXPOSE 8080\n\nSTOPSIGNAL SIGTERM\n\nCMD [\"/opt/nginx/sbin/nginx\", \"-g\", \"daemon off;\"]" }, { "alpha_fraction": 0.6980392336845398, "alphanum_fraction": 0.6980392336845398, "avg_line_length": 22.18181800842285, "blob_id": "a1e115ea5687a40ad0b2511a1745e27b5be10277", "content_id": "f437bc10c50680420ba570d09bffd70303f323e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 255, "license_type": "no_license", "max_line_length": 54, "num_lines": 11, "path": "/run.sh", "repo_name": "Leovilhena/mailbox2fs", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nread -p \"Enter Fastmail username: \" FASTMAIL_USER\nread -s -p \"Enter Fastmail password: \" FASTMAIL_PASSWD\n\nexport FASTMAIL_USER=\"${FASTMAIL_USER}\"\necho -n \"${FASTMAIL_PASSWD}\" > ./.fmpasswd\ndocker-compose up --build\n\nrm ./.fmpasswd\n#rm ./.env\n" } ]
5
yoongyo/TsF
https://github.com/yoongyo/TsF
007cbf62abfa3f7c7001418a856119542300382d
60df29e63e0dd1955e39938ae14424d8aabcf184
a2abd9db249957d4e2754a46c7c67bcd1969c993
refs/heads/master
2020-03-22T21:58:20.564102
2018-07-14T17:20:47
2018-07-14T17:20:47
140,725,273
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.420645147562027, "alphanum_fraction": 0.420645147562027, "avg_line_length": 20.52777862548828, "blob_id": "6593919c19ae09c2b1267eb638c7ad4a42bd3e7e", "content_id": "7a18bdc9d30a376d8c5c765c8b53d49c91b47bbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 775, "license_type": "no_license", "max_line_length": 40, "num_lines": 36, "path": "/ch1/travel/forms.py", "repo_name": "yoongyo/TsF", "src_encoding": "UTF-8", "text": "from .models import Post\nfrom django import forms\n\n\n\nclass PostForm(forms.ModelForm):\n class Meta:\n model = Post\n fields = [\n 'title',\n 'Tourtype',\n 'Country',\n 'City',\n 'Language',\n 'DetailContent',\n 'BriefContent',\n 'HashTag',\n 'MeetingPoint',\n 'MeetingTime',\n 'Map',\n 'Direction',\n 'CourseName',\n 'Duration',\n 'Price',\n 'Minimum',\n 'Maximum',\n 'Price_include',\n 'NotDate',\n 'GuestInfo',\n ]\n\n def save(self, commit=True):\n post = Post(**self.cleaned_data)\n if commit:\n post.save()\n return post\n" } ]
1
moozer/ProItsScripts
https://github.com/moozer/ProItsScripts
a9e3f644eb605a65b750542e87e458590a8d8f3f
48031f075657bcbefd0b1aaad84ee9b21f5fddc4
3b966ae2fb5a27fb947ab8ce50ae040ffc1b980c
refs/heads/master
2016-09-06T19:08:47.918440
2013-12-06T15:03:25
2013-12-06T15:03:25
14,331,378
0
1
null
2013-11-12T12:19:12
2013-12-06T15:04:04
2013-12-06T15:04:04
PHP
[ { "alpha_fraction": 0.5673575401306152, "alphanum_fraction": 0.5731865167617798, "avg_line_length": 29.27450942993164, "blob_id": "350ada293c14da4b9b3ce5d2cfc2a656b2710e43", "content_id": "9cb6398e20e59f11622681d756bb48488df126ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1544, "license_type": "no_license", "max_line_length": 109, "num_lines": 51, "path": "/scripts/PushToFtp.py", "repo_name": "moozer/ProItsScripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# pushes data to a given server\n\nfrom ftplib import FTP, FTP_TLS\nimport sys\nimport os\nimport paramiko\n\nFilesToPut = ['../php/basedata.php']\n\ndef Push( FtpServer, Username, Password, uploadlist = FilesToPut, port = 21, passive = False, Sftp = False ):\n print \"Login to %s:%s using %s:%s (%s)\"%(FtpServer, port, Username, 'xxx', \n\t\t\t\t'passive' if passive else 'active')\n \n if Sftp:\n paramiko.util.log_to_file('/tmp/paramiko.log')\n transport = paramiko.Transport((FtpServer,int(port)))\n transport.connect(username = Username, password = Password)\n sftp = paramiko.SFTPClient.from_transport(transport)\n \n for f in uploadlist:\n\t\t print \"uploading %s\"%f\t\t\n\t\t sftp.put(f, os.path.basename(f))\n sftp.close()\n transport.close()\n\n else:\n ftp = FTP()\n ftp.connect( FtpServer, port )\n ftp.login( Username, Password ) \n\t ftp.set_pasv( passive )\n for f in uploadlist:\n\t\t print \"uploading %s\"%f\t\t\n\t\t fp = open( f, 'rb')\n\t\t ftp.storbinary('STOR %s'%os.path.basename(f), fp) # send the file\n \n ftp.quit()\n\nif __name__ == \"__main__\":\n\tif len(sys.argv) < 5:\n\t\tprint >> sys.stderr, \"usage %s <server> <port> <username> <password>\"%sys.argv[0]\n\t\texit( 1 )\n\n\tFtpServer = sys.argv[1]\n\tPort = sys.argv[2]\n\tUsername = sys.argv[3]\n\tPasswd = sys.argv[4]\n\n\tPush( FtpServer, Username, Passwd, port = Port )\n\tprint >> sys.stderr, \"Done\"\n" }, { "alpha_fraction": 0.6233183741569519, "alphanum_fraction": 0.6352765560150146, "avg_line_length": 16.473684310913086, "blob_id": "dadb1a768ec80b7bfcbd7b7e156d9a00b228ced9", "content_id": "39445b9a4e7ebbcbc10c9d4b17d0e59d14b28ac9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 669, "license_type": "no_license", "max_line_length": 117, "num_lines": 38, "path": "/scripts/CheckBaseData.py", "repo_name": "moozer/ProItsScripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n\nimport sys\nimport urllib2\nimport json\n\n\ndef FetchBaseData( URL ):\n\t\n\tprint 'Fetching basedata from %s :'%(URL,)\n\n\t# fetch data\n\treq = urllib2.Request(URL)\n\tresponse = urllib2.urlopen(req)\n\tjsondata = response.read() \n\tresponse.close()\n\n\t# parsing json\n\tdata = json.loads( jsondata )\n\n\tprint 'Data fetched: hostname: %s, php version: %s, timestamp: %s'%(data['hostname'], data['version'], data['date'])\n\n\treturn data\n\nif __name__ == '__main__':\n\n\t# command line args.\n\tif len(sys.argv) < 3:\n\t print \"usage %s <id> <URL>\"%sys.argv[0]\n\t exit( 1 )\n\n\tGroupId = sys.argv[1]\n\tURL = sys.argv[2]\n\n\n\t# parsing json\n\tdata = FetchBaseData( URL )\n\n\n\n\n\n" }, { "alpha_fraction": 0.6649746298789978, "alphanum_fraction": 0.6920473575592041, "avg_line_length": 24.65217399597168, "blob_id": "598c008f056cf9d50baf8f47603838db96722ed9", "content_id": "0fbea0bc00ac1c80182cbb3f1d516c66e7eb128f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 591, "license_type": "no_license", "max_line_length": 102, "num_lines": 23, "path": "/scripts/ReadAllBase.py", "repo_name": "moozer/ProItsScripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# reads config and pushes data\n\nimport ConfigParser\nfrom CheckBaseData import FetchBaseData \n\nGrouplist = \"../grouplist.txt\"\nGroupNames = [\"Group01\", \"Group02\", \"Group03\", \"Group04\", \"Group05\", \"Group06\", \"Group07\", \"Group08\" ]\n\n\nif __name__ == \"__main__\":\n\t#config = ConfigParser.ConfigParser()\n\tconfig = ConfigParser.SafeConfigParser()\n\tconfig.read( Grouplist )\n\n\tfor group in GroupNames:\n\t\tprint \"Group: %s\"%group\n\t\ttry:\n\t\t\tWebUrl = config.get(group, 'weburl' )\n\t\t\tFetchBaseData( WebUrl+'basedata.php')\n\t\texcept Exception, e:\n\t\t\tprint \"Something went wrong: %s\"%e\n\n" }, { "alpha_fraction": 0.6339066624641418, "alphanum_fraction": 0.7174447178840637, "avg_line_length": 9.945945739746094, "blob_id": "5e7e7d15fc0bc242963b52714aadb7ccef6f6793", "content_id": "a592ca53a4407021b7380cfd3c0bd502788139d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 407, "license_type": "no_license", "max_line_length": 74, "num_lines": 37, "path": "/README.md", "repo_name": "moozer/ProItsScripts", "src_encoding": "UTF-8", "text": "ProItsScripts\n=============\n\nscripts and php related to project its\n\nA file called groulist.txt must exists with the follwoing minimal content.\n\nThis is aconfig file with these categories\n\n[Group01]\n\n[Group02]\n\n[Group03]\n\n[Group04]\n\n[Group05]\n\n[Group06]\n\n[Group07]\n\n[Group08]\n\nEach category must a least contain\n\n\n[Group01]\n\nip=192.168.1.2\n\nuser=myusername\n\npass=mypassword\n\nweburl=http://192.168.1.2/web\n\n\n" }, { "alpha_fraction": 0.5144927501678467, "alphanum_fraction": 0.5144927501678467, "avg_line_length": 26.600000381469727, "blob_id": "228be5d41e78f41f151a15335ab4374d583ac913", "content_id": "b1e0e9c47a85baa1b550fc91c1bc44359af0033f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 138, "license_type": "no_license", "max_line_length": 46, "num_lines": 5, "path": "/php/basedata.php", "repo_name": "moozer/ProItsScripts", "src_encoding": "UTF-8", "text": "{\n\t\"date\": \"<?php echo date('Y-m-d H:i:s'); ?>\",\n\t\"hostname\": \"<?php echo gethostname(); ?>\",\n\t\"version\": \"<?php echo phpversion(); ?>\"\n}\n" }, { "alpha_fraction": 0.6393782496452332, "alphanum_fraction": 0.6580311059951782, "avg_line_length": 30.09677505493164, "blob_id": "13b79d95e3abd550693a3f797a8b739fff21e543", "content_id": "e14cab98bc5a6d24a1b7d20496c375de6f1173f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 965, "license_type": "no_license", "max_line_length": 102, "num_lines": 31, "path": "/scripts/PushAll.py", "repo_name": "moozer/ProItsScripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# reads config and pushes data\n\nimport ConfigParser\nfrom PushToFtp import Push\n\nGrouplist = \"../grouplist.txt\"\nGroupNames = [\"Group01\", \"Group02\", \"Group03\", \"Group04\", \"Group05\", \"Group06\", \"Group07\", \"Group08\" ]\n\n\nif __name__ == \"__main__\":\n\t#config = ConfigParser.ConfigParser()\n\tconfig = ConfigParser.SafeConfigParser( {'port': '21', 'passive': False, 'sftp': False })\n\tconfig.read( Grouplist )\n\n\tfor group in GroupNames:\n\t\tprint \"Group: %s\"%group\n\t\ttry:\n\t\t\tUsername = config.get(group, 'user' )\n\t\t\tFtpServer = config.get(group, 'ip' )\n\t\t\tPasswd = config.get(group, 'pass' )\n\t\t\tWebUrl = config.get(group, 'weburl' )\n\t\t\tport = config.get(group, 'port' )\n\t\t\tpassive = config.get(group, 'passive' )\n\t\t\tsftp = config.get(group, 'sftp')\n\t\t\tPush( FtpServer, Username, Passwd, port=port, \n\t\t\t\tpassive=True if passive == 'True' else False,\n\t\t\t\tSftp=True if sftp == 'True' else False)\n\t\texcept Exception, e:\n\t\t\tprint \"Something went wrong: %s\"%e\n\n" }, { "alpha_fraction": 0.5892857313156128, "alphanum_fraction": 0.59375, "avg_line_length": 14.928571701049805, "blob_id": "aa0271ae8e2208798e0881751c86031b69ca6ac4", "content_id": "99bd60ea8c078f3c6f1de44025a26b10250c9bd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 224, "license_type": "no_license", "max_line_length": 30, "num_lines": 14, "path": "/scripts/RunAll.sh", "repo_name": "moozer/ProItsScripts", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\n# files...\nDATE=$(date \"+%y%m%d\")\nWebLog=\"$HOME/${DATE}_web.log\"\nFtpLog=\"$HOME/${DATE}_ftp.log\"\n\ncd $(dirname $(realpath $0))\n\ndate >> $FtpLog\n./PushAll.py >> $FtpLog\n\ndate >> $WebLog\n./ReadAllBase.py >> $WebLog\n\n" } ]
7
stvncrn/stockx_api_ref
https://github.com/stvncrn/stockx_api_ref
2f251008b10401d0946e08ee93b627dd1ffecd45
9ab9bdbab690375802a6df164c126865e2011bd1
5151f3e44acd15e1adc8587827be65562f06fee4
refs/heads/master
2021-10-19T13:02:40.734388
2019-02-21T04:43:59
2019-02-21T04:43:59
171,801,494
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6611418128013611, "alphanum_fraction": 0.6611418128013611, "avg_line_length": 59.11111068725586, "blob_id": "4fe5754cd34ea77de15e8bd804852d48a3e50a62", "content_id": "f98c8aa345cb7599c0621c6e8b76402204fe17c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 543, "license_type": "no_license", "max_line_length": 161, "num_lines": 9, "path": "/sdk/php/StockX-SDK-PHP/lib/docs/Model/CustomersIdSellingCurrent.md", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# CustomersIdSellingCurrent\n\n## Properties\nName | Type | Description | Notes\n------------ | ------------- | ------------- | -------------\n**paging** | [**\\StockX\\Client\\Model\\CustomersIdSellingCurrentPaging**](CustomersIdSellingCurrentPaging.md) | | \n**pagination** | [**\\StockX\\Client\\Model\\CustomersIdSellingCurrentPagination**](CustomersIdSellingCurrentPagination.md) | | \n\n[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)\n\n\n" }, { "alpha_fraction": 0.5562387704849243, "alphanum_fraction": 0.5588009357452393, "avg_line_length": 15.751072883605957, "blob_id": "a98204eca74554c9fed756d8b30386be61f5cb7a", "content_id": "99066e0c40b079a1eb75705c8f1041dda9ddced7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3903, "license_type": "no_license", "max_line_length": 110, "num_lines": 233, "path": "/sdk/php/StockX-SDK-PHP/lib/test/Api/StockXApiTest.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * StockXApiTest\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Please update the test case below to test the endpoint.\n */\n\nnamespace StockX\\Client;\n\nuse \\StockX\\Client\\Configuration;\nuse \\StockX\\Client\\ApiException;\nuse \\StockX\\Client\\ObjectSerializer;\n\n/**\n * StockXApiTest Class Doc Comment\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass StockXApiTest extends \\PHPUnit_Framework_TestCase\n{\n\n /**\n * Setup before running any test cases\n */\n public static function setUpBeforeClass()\n {\n }\n\n /**\n * Setup before running each test case\n */\n public function setUp()\n {\n }\n\n /**\n * Clean up after running each test case\n */\n public function tearDown()\n {\n }\n\n /**\n * Clean up after running all test cases\n */\n public static function tearDownAfterClass()\n {\n }\n\n /**\n * Test case for deletePortfolio\n *\n * Deletes a portfolio item from the market with the specified id..\n *\n */\n public function testDeletePortfolio()\n {\n }\n\n /**\n * Test case for deleteWebhook\n *\n * .\n *\n */\n public function testDeleteWebhook()\n {\n }\n\n /**\n * Test case for getOpenOrders\n *\n * .\n *\n */\n public function testGetOpenOrders()\n {\n }\n\n /**\n * Test case for getPortfolio\n *\n * Returns a market portfolio identified by request parameters..\n *\n */\n public function testGetPortfolio()\n {\n }\n\n /**\n * Test case for getPortfolioItem\n *\n * .\n *\n */\n public function testGetPortfolioItem()\n {\n }\n\n /**\n * Test case for getProductById\n *\n * .\n *\n */\n public function testGetProductById()\n {\n }\n\n /**\n * Test case for getProductMarketData\n *\n * Provides historical market data for a given product..\n *\n */\n public function testGetProductMarketData()\n {\n }\n\n /**\n * Test case for getSubscriptions\n *\n * .\n *\n */\n public function testGetSubscriptions()\n {\n }\n\n /**\n * Test case for getWebhook\n *\n * .\n *\n */\n public function testGetWebhook()\n {\n }\n\n /**\n * Test case for getWebhooks\n *\n * .\n *\n */\n public function testGetWebhooks()\n {\n }\n\n /**\n * Test case for login\n *\n * Attempts to log the user in with a username and password..\n *\n */\n public function testLogin()\n {\n }\n\n /**\n * Test case for lookupProduct\n *\n * .\n *\n */\n public function testLookupProduct()\n {\n }\n\n /**\n * Test case for newPortfolioAsk\n *\n * Creates a new seller ask on the market for a given product..\n *\n */\n public function testNewPortfolioAsk()\n {\n }\n\n /**\n * Test case for newPortfolioBid\n *\n * Creates a new buyer bid on the market for a given product..\n *\n */\n public function testNewPortfolioBid()\n {\n }\n\n /**\n * Test case for postWebhooks\n *\n * .\n *\n */\n public function testPostWebhooks()\n {\n }\n\n /**\n * Test case for search\n *\n * Searches for products by keyword..\n *\n */\n public function testSearch()\n {\n }\n}\n" }, { "alpha_fraction": 0.6777725219726562, "alphanum_fraction": 0.6785568594932556, "avg_line_length": 34.65324401855469, "blob_id": "d20236f9b9c92abb076bd980974ce1d803b58a28", "content_id": "62118050ee9986539cfcc4c81a85887ad5cd423e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 31875, "license_type": "no_license", "max_line_length": 189, "num_lines": 894, "path": "/sdk/php/StockX-SDK-PHP/lib/docs/Api/StockXApi.md", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# StockX\\Client\\StockXApi\n\nAll URIs are relative to *https://gateway.stockx.com/public*\n\nMethod | HTTP request | Description\n------------- | ------------- | -------------\n[**deletePortfolio**](StockXApi.md#deletePortfolio) | **DELETE** /v1/portfolio/{id} | Deletes a portfolio item from the market with the specified id.\n[**deleteWebhook**](StockXApi.md#deleteWebhook) | **DELETE** /webhook/v1/webhooks/{id} | \n[**getOpenOrders**](StockXApi.md#getOpenOrders) | **GET** /v1/customers/{id}/selling/current | \n[**getPortfolio**](StockXApi.md#getPortfolio) | **POST** /v1/portfolio | Returns a market portfolio identified by request parameters.\n[**getPortfolioItem**](StockXApi.md#getPortfolioItem) | **GET** /v1/portfolioitems/{id} | \n[**getProductById**](StockXApi.md#getProductById) | **GET** /v1/products/{id} | \n[**getProductMarketData**](StockXApi.md#getProductMarketData) | **GET** /v1/products/{productId}/market | Provides historical market data for a given product.\n[**getSubscriptions**](StockXApi.md#getSubscriptions) | **GET** /webhook/v1/subscriptions | \n[**getWebhook**](StockXApi.md#getWebhook) | **GET** /webhook/v1/webhooks/{id} | \n[**getWebhooks**](StockXApi.md#getWebhooks) | **GET** /webhook/v1/webhooks | \n[**login**](StockXApi.md#login) | **POST** /v1/login | Attempts to log the user in with a username and password.\n[**lookupProduct**](StockXApi.md#lookupProduct) | **GET** /product/lookup | \n[**newPortfolioAsk**](StockXApi.md#newPortfolioAsk) | **POST** /v1/portfolio/ask | Creates a new seller ask on the market for a given product.\n[**newPortfolioBid**](StockXApi.md#newPortfolioBid) | **POST** /v1/portfolio/bid | Creates a new buyer bid on the market for a given product.\n[**postWebhooks**](StockXApi.md#postWebhooks) | **POST** /webhook/v1/webhooks | \n[**search**](StockXApi.md#search) | **GET** /v2/search | Searches for products by keyword.\n\n\n# **deletePortfolio**\n> \\StockX\\Client\\Model\\PortfolioIdDelResponse deletePortfolio($id, $portfolio)\n\nDeletes a portfolio item from the market with the specified id.\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n$id = \"id_example\"; // string | The id of the portfolio item to delete.\n$portfolio = new \\StockX\\Client\\Model\\PortfolioIdDelRequest(); // \\StockX\\Client\\Model\\PortfolioIdDelRequest | The request information for the portfolio delete operation.\n\ntry {\n $result = $apiInstance->deletePortfolio($id, $portfolio);\n print_r($result);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->deletePortfolio: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **id** | **string**| The id of the portfolio item to delete. |\n **portfolio** | [**\\StockX\\Client\\Model\\PortfolioIdDelRequest**](../Model/PortfolioIdDelRequest.md)| The request information for the portfolio delete operation. |\n\n### Return type\n\n[**\\StockX\\Client\\Model\\PortfolioIdDelResponse**](../Model/PortfolioIdDelResponse.md)\n\n### Authorization\n\n[api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n# **deleteWebhook**\n> deleteWebhook($id)\n\n\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n$id = \"id_example\"; // string | \n\ntry {\n $apiInstance->deleteWebhook($id);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->deleteWebhook: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **id** | **string**| |\n\n### Return type\n\nvoid (empty response body)\n\n### Authorization\n\n[api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n# **getOpenOrders**\n> \\StockX\\Client\\Model\\CustomersIdSellingCurrent getOpenOrders($id)\n\n\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: JWT\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('jwt-authorization', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('jwt-authorization', 'Bearer');\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n$id = \"id_example\"; // string | The customer id to lookup open orders with.\n\ntry {\n $result = $apiInstance->getOpenOrders($id);\n print_r($result);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->getOpenOrders: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **id** | **string**| The customer id to lookup open orders with. |\n\n### Return type\n\n[**\\StockX\\Client\\Model\\CustomersIdSellingCurrent**](../Model/CustomersIdSellingCurrent.md)\n\n### Authorization\n\n[JWT](../../README.md#JWT), [api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n# **getPortfolio**\n> \\StockX\\Client\\Model\\PortfolioResponse getPortfolio($portfolio)\n\nReturns a market portfolio identified by request parameters.\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n$portfolio = new \\StockX\\Client\\Model\\PortfolioRequest(); // \\StockX\\Client\\Model\\PortfolioRequest | Requests parameters for looking up a market portfolio.\n\ntry {\n $result = $apiInstance->getPortfolio($portfolio);\n print_r($result);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->getPortfolio: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **portfolio** | [**\\StockX\\Client\\Model\\PortfolioRequest**](../Model/PortfolioRequest.md)| Requests parameters for looking up a market portfolio. |\n\n### Return type\n\n[**\\StockX\\Client\\Model\\PortfolioResponse**](../Model/PortfolioResponse.md)\n\n### Authorization\n\n[api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n# **getPortfolioItem**\n> \\StockX\\Client\\Model\\PortfolioitemsIdGetResponse getPortfolioItem($id)\n\n\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: JWT\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('jwt-authorization', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('jwt-authorization', 'Bearer');\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n$id = \"id_example\"; // string | The id of the portfolio item to lookup.\n\ntry {\n $result = $apiInstance->getPortfolioItem($id);\n print_r($result);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->getPortfolioItem: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **id** | **string**| The id of the portfolio item to lookup. |\n\n### Return type\n\n[**\\StockX\\Client\\Model\\PortfolioitemsIdGetResponse**](../Model/PortfolioitemsIdGetResponse.md)\n\n### Authorization\n\n[JWT](../../README.md#JWT), [api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n# **getProductById**\n> \\StockX\\Client\\Model\\ProductResponse getProductById($id, $include)\n\n\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: JWT\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('jwt-authorization', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('jwt-authorization', 'Bearer');\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n$id = \"id_example\"; // string | The id of the product to return.\n$include = \"include_example\"; // string | \n\ntry {\n $result = $apiInstance->getProductById($id, $include);\n print_r($result);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->getProductById: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **id** | **string**| The id of the product to return. |\n **include** | **string**| | [optional]\n\n### Return type\n\n[**\\StockX\\Client\\Model\\ProductResponse**](../Model/ProductResponse.md)\n\n### Authorization\n\n[JWT](../../README.md#JWT), [api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n# **getProductMarketData**\n> \\StockX\\Client\\Model\\MarketData getProductMarketData($product_id, $sku)\n\nProvides historical market data for a given product.\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: JWT\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('jwt-authorization', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('jwt-authorization', 'Bearer');\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n$product_id = \"product_id_example\"; // string | The product's product UUID\n$sku = \"sku_example\"; // string | The product's SKU\n\ntry {\n $result = $apiInstance->getProductMarketData($product_id, $sku);\n print_r($result);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->getProductMarketData: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **product_id** | **string**| The product&#39;s product UUID |\n **sku** | **string**| The product&#39;s SKU | [optional]\n\n### Return type\n\n[**\\StockX\\Client\\Model\\MarketData**](../Model/MarketData.md)\n\n### Authorization\n\n[JWT](../../README.md#JWT), [api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n# **getSubscriptions**\n> \\StockX\\Client\\Model\\SubscriptionsResponse getSubscriptions()\n\n\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n\ntry {\n $result = $apiInstance->getSubscriptions();\n print_r($result);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->getSubscriptions: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\nThis endpoint does not need any parameter.\n\n### Return type\n\n[**\\StockX\\Client\\Model\\SubscriptionsResponse**](../Model/SubscriptionsResponse.md)\n\n### Authorization\n\n[api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n# **getWebhook**\n> \\StockX\\Client\\Model\\WebhooksIdGetResponse getWebhook($id)\n\n\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n$id = \"id_example\"; // string | \n\ntry {\n $result = $apiInstance->getWebhook($id);\n print_r($result);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->getWebhook: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **id** | **string**| |\n\n### Return type\n\n[**\\StockX\\Client\\Model\\WebhooksIdGetResponse**](../Model/WebhooksIdGetResponse.md)\n\n### Authorization\n\n[api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n# **getWebhooks**\n> \\StockX\\Client\\Model\\WebhooksGetResponse getWebhooks()\n\n\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n\ntry {\n $result = $apiInstance->getWebhooks();\n print_r($result);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->getWebhooks: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\nThis endpoint does not need any parameter.\n\n### Return type\n\n[**\\StockX\\Client\\Model\\WebhooksGetResponse**](../Model/WebhooksGetResponse.md)\n\n### Authorization\n\n[api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n# **login**\n> \\StockX\\Client\\Model\\LoginResponse login($login)\n\nAttempts to log the user in with a username and password.\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n$login = new \\StockX\\Client\\Model\\LoginRequest(); // \\StockX\\Client\\Model\\LoginRequest | Object that contains the user's authentication credentials.'\n\ntry {\n $result = $apiInstance->login($login);\n print_r($result);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->login: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **login** | [**\\StockX\\Client\\Model\\LoginRequest**](../Model/LoginRequest.md)| Object that contains the user&#39;s authentication credentials.&#39; |\n\n### Return type\n\n[**\\StockX\\Client\\Model\\LoginResponse**](../Model/LoginResponse.md)\n\n### Authorization\n\n[api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n# **lookupProduct**\n> \\StockX\\Client\\Model\\ProductInfo lookupProduct($identifier, $size)\n\n\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: JWT\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('jwt-authorization', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('jwt-authorization', 'Bearer');\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n$identifier = \"identifier_example\"; // string | The product identifier to lookup, e.g. (air-jordan-1-retro-high-off-white-chicago)\n$size = \"size_example\"; // string | The size of the product.\n\ntry {\n $result = $apiInstance->lookupProduct($identifier, $size);\n print_r($result);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->lookupProduct: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **identifier** | **string**| The product identifier to lookup, e.g. (air-jordan-1-retro-high-off-white-chicago) | [optional]\n **size** | **string**| The size of the product. | [optional]\n\n### Return type\n\n[**\\StockX\\Client\\Model\\ProductInfo**](../Model/ProductInfo.md)\n\n### Authorization\n\n[JWT](../../README.md#JWT), [api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n# **newPortfolioAsk**\n> \\StockX\\Client\\Model\\PortfolioResponse newPortfolioAsk($portfolio)\n\nCreates a new seller ask on the market for a given product.\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n$portfolio = new \\StockX\\Client\\Model\\PortfolioRequest(); // \\StockX\\Client\\Model\\PortfolioRequest | The portfolio request representing the ask to place on the market.\n\ntry {\n $result = $apiInstance->newPortfolioAsk($portfolio);\n print_r($result);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->newPortfolioAsk: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **portfolio** | [**\\StockX\\Client\\Model\\PortfolioRequest**](../Model/PortfolioRequest.md)| The portfolio request representing the ask to place on the market. |\n\n### Return type\n\n[**\\StockX\\Client\\Model\\PortfolioResponse**](../Model/PortfolioResponse.md)\n\n### Authorization\n\n[api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n# **newPortfolioBid**\n> \\StockX\\Client\\Model\\PortfolioResponse newPortfolioBid($portfolio)\n\nCreates a new buyer bid on the market for a given product.\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n$portfolio = new \\StockX\\Client\\Model\\PortfolioRequest(); // \\StockX\\Client\\Model\\PortfolioRequest | The portfolio request representing the bid to place on the market.\n\ntry {\n $result = $apiInstance->newPortfolioBid($portfolio);\n print_r($result);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->newPortfolioBid: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **portfolio** | [**\\StockX\\Client\\Model\\PortfolioRequest**](../Model/PortfolioRequest.md)| The portfolio request representing the bid to place on the market. |\n\n### Return type\n\n[**\\StockX\\Client\\Model\\PortfolioResponse**](../Model/PortfolioResponse.md)\n\n### Authorization\n\n[api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n# **postWebhooks**\n> \\StockX\\Client\\Model\\WebhooksPostResponse postWebhooks($portfolio)\n\n\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n$portfolio = new \\StockX\\Client\\Model\\WebhooksPostRequest(); // \\StockX\\Client\\Model\\WebhooksPostRequest | \n\ntry {\n $result = $apiInstance->postWebhooks($portfolio);\n print_r($result);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->postWebhooks: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **portfolio** | [**\\StockX\\Client\\Model\\WebhooksPostRequest**](../Model/WebhooksPostRequest.md)| |\n\n### Return type\n\n[**\\StockX\\Client\\Model\\WebhooksPostResponse**](../Model/WebhooksPostResponse.md)\n\n### Authorization\n\n[api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n# **search**\n> \\StockX\\Client\\Model\\SearchResults search($query)\n\nSearches for products by keyword.\n\n### Example\n```php\n<?php\nrequire_once(__DIR__ . '/vendor/autoload.php');\n\n// Configure API key authorization: JWT\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('jwt-authorization', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('jwt-authorization', 'Bearer');\n// Configure API key authorization: api_key\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', 'YOUR_API_KEY');\n// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n// $config = StockX\\Client\\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-api-key', 'Bearer');\n\n$apiInstance = new StockX\\Client\\Api\\StockXApi(\n // If you want use custom http client, pass your client which implements `GuzzleHttp\\ClientInterface`.\n // This is optional, `GuzzleHttp\\Client` will be used as default.\n new GuzzleHttp\\Client(),\n $config\n);\n$query = \"query_example\"; // string | The phrase or keyword to search with.\n\ntry {\n $result = $apiInstance->search($query);\n print_r($result);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->search: ', $e->getMessage(), PHP_EOL;\n}\n?>\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **query** | **string**| The phrase or keyword to search with. |\n\n### Return type\n\n[**\\StockX\\Client\\Model\\SearchResults**](../Model/SearchResults.md)\n\n### Authorization\n\n[JWT](../../README.md#JWT), [api_key](../../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)\n\n" }, { "alpha_fraction": 0.6812933087348938, "alphanum_fraction": 0.6997690796852112, "avg_line_length": 19.66666603088379, "blob_id": "e56a4b7dfd3d98d6444b568c0fc2b5b727f07e09", "content_id": "02213b2639f37b12cee181bf66fc690c44dbb95b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 433, "license_type": "no_license", "max_line_length": 65, "num_lines": 21, "path": "/sdk/python/src/example_constants.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\nclass ExampleConstants:\n\n AWS_API_KEY = \"<API Key>\"\n\n STOCKX_USERNAME = \"<StockX Username>\"\n\n STOCKX_PASSWORD = \"<StockX Password>\"\n\n DEMO_PRODUCT_ID = \"air-jordan-1-retro-high-off-white-chicago\"\n\n DEMO_CUSTOMER_ID = \"1471698\"\n\n ENABLE_DEBUG = True\n\n JWT_HEADER = \"Jwt-Authorization\"" }, { "alpha_fraction": 0.5616855621337891, "alphanum_fraction": 0.5724881887435913, "avg_line_length": 36.826255798339844, "blob_id": "ce0e86f56ac88cde3107ae397dd343c4d45b8960", "content_id": "db6859fec9d2b0e933267eb512d93e7f39ec4911", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 58782, "license_type": "no_license", "max_line_length": 176, "num_lines": 1554, "path": "/sdk/python/lib/build/lib/io_stockx/api/stock_x_api.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nfrom __future__ import absolute_import\n\nimport re # noqa: F401\n\n# python 2 and python 3 compatibility library\nimport six\n\nfrom io_stockx.api_client import ApiClient\n\n\nclass StockXApi(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n Ref: https://github.com/swagger-api/swagger-codegen\n \"\"\"\n\n def __init__(self, api_client=None):\n if api_client is None:\n api_client = ApiClient()\n self.api_client = api_client\n\n def delete_portfolio(self, id, portfolio, **kwargs): # noqa: E501\n \"\"\"Deletes a portfolio item from the market with the specified id. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.delete_portfolio(id, portfolio, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str id: The id of the portfolio item to delete. (required)\n :param PortfolioIdDelRequest portfolio: The request information for the portfolio delete operation. (required)\n :return: PortfolioIdDelResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.delete_portfolio_with_http_info(id, portfolio, **kwargs) # noqa: E501\n else:\n (data) = self.delete_portfolio_with_http_info(id, portfolio, **kwargs) # noqa: E501\n return data\n\n def delete_portfolio_with_http_info(self, id, portfolio, **kwargs): # noqa: E501\n \"\"\"Deletes a portfolio item from the market with the specified id. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.delete_portfolio_with_http_info(id, portfolio, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str id: The id of the portfolio item to delete. (required)\n :param PortfolioIdDelRequest portfolio: The request information for the portfolio delete operation. (required)\n :return: PortfolioIdDelResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['id', 'portfolio'] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method delete_portfolio\" % key\n )\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'id' is set\n if ('id' not in params or\n params['id'] is None):\n raise ValueError(\"Missing the required parameter `id` when calling `delete_portfolio`\") # noqa: E501\n # verify the required parameter 'portfolio' is set\n if ('portfolio' not in params or\n params['portfolio'] is None):\n raise ValueError(\"Missing the required parameter `portfolio` when calling `delete_portfolio`\") # noqa: E501\n\n collection_formats = {}\n\n path_params = {}\n if 'id' in params:\n path_params['id'] = params['id'] # noqa: E501\n\n query_params = []\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n if 'portfolio' in params:\n body_params = params['portfolio']\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # HTTP header `Content-Type`\n header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/v1/portfolio/{id}', 'DELETE',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='PortfolioIdDelResponse', # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def delete_webhook(self, id, **kwargs): # noqa: E501\n \"\"\"delete_webhook # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.delete_webhook(id, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str id: (required)\n :return: None\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.delete_webhook_with_http_info(id, **kwargs) # noqa: E501\n else:\n (data) = self.delete_webhook_with_http_info(id, **kwargs) # noqa: E501\n return data\n\n def delete_webhook_with_http_info(self, id, **kwargs): # noqa: E501\n \"\"\"delete_webhook # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.delete_webhook_with_http_info(id, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str id: (required)\n :return: None\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['id'] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method delete_webhook\" % key\n )\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'id' is set\n if ('id' not in params or\n params['id'] is None):\n raise ValueError(\"Missing the required parameter `id` when calling `delete_webhook`\") # noqa: E501\n\n collection_formats = {}\n\n path_params = {}\n if 'id' in params:\n path_params['id'] = params['id'] # noqa: E501\n\n query_params = []\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/webhook/v1/webhooks/{id}', 'DELETE',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type=None, # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def get_open_orders(self, id, **kwargs): # noqa: E501\n \"\"\"get_open_orders # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_open_orders(id, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str id: The customer id to lookup open orders with. (required)\n :return: CustomersIdSellingCurrent\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.get_open_orders_with_http_info(id, **kwargs) # noqa: E501\n else:\n (data) = self.get_open_orders_with_http_info(id, **kwargs) # noqa: E501\n return data\n\n def get_open_orders_with_http_info(self, id, **kwargs): # noqa: E501\n \"\"\"get_open_orders # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_open_orders_with_http_info(id, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str id: The customer id to lookup open orders with. (required)\n :return: CustomersIdSellingCurrent\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['id'] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method get_open_orders\" % key\n )\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'id' is set\n if ('id' not in params or\n params['id'] is None):\n raise ValueError(\"Missing the required parameter `id` when calling `get_open_orders`\") # noqa: E501\n\n collection_formats = {}\n\n path_params = {}\n if 'id' in params:\n path_params['id'] = params['id'] # noqa: E501\n\n query_params = []\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['JWT', 'api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/v1/customers/{id}/selling/current', 'GET',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='CustomersIdSellingCurrent', # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def get_portfolio(self, portfolio, **kwargs): # noqa: E501\n \"\"\"Returns a market portfolio identified by request parameters. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_portfolio(portfolio, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param PortfolioRequest portfolio: Requests parameters for looking up a market portfolio. (required)\n :return: PortfolioResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.get_portfolio_with_http_info(portfolio, **kwargs) # noqa: E501\n else:\n (data) = self.get_portfolio_with_http_info(portfolio, **kwargs) # noqa: E501\n return data\n\n def get_portfolio_with_http_info(self, portfolio, **kwargs): # noqa: E501\n \"\"\"Returns a market portfolio identified by request parameters. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_portfolio_with_http_info(portfolio, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param PortfolioRequest portfolio: Requests parameters for looking up a market portfolio. (required)\n :return: PortfolioResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['portfolio'] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method get_portfolio\" % key\n )\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'portfolio' is set\n if ('portfolio' not in params or\n params['portfolio'] is None):\n raise ValueError(\"Missing the required parameter `portfolio` when calling `get_portfolio`\") # noqa: E501\n\n collection_formats = {}\n\n path_params = {}\n\n query_params = []\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n if 'portfolio' in params:\n body_params = params['portfolio']\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # HTTP header `Content-Type`\n header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/v1/portfolio', 'POST',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='PortfolioResponse', # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def get_portfolio_item(self, id, **kwargs): # noqa: E501\n \"\"\"get_portfolio_item # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_portfolio_item(id, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str id: The id of the portfolio item to lookup. (required)\n :return: PortfolioitemsIdGetResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.get_portfolio_item_with_http_info(id, **kwargs) # noqa: E501\n else:\n (data) = self.get_portfolio_item_with_http_info(id, **kwargs) # noqa: E501\n return data\n\n def get_portfolio_item_with_http_info(self, id, **kwargs): # noqa: E501\n \"\"\"get_portfolio_item # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_portfolio_item_with_http_info(id, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str id: The id of the portfolio item to lookup. (required)\n :return: PortfolioitemsIdGetResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['id'] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method get_portfolio_item\" % key\n )\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'id' is set\n if ('id' not in params or\n params['id'] is None):\n raise ValueError(\"Missing the required parameter `id` when calling `get_portfolio_item`\") # noqa: E501\n\n collection_formats = {}\n\n path_params = {}\n if 'id' in params:\n path_params['id'] = params['id'] # noqa: E501\n\n query_params = []\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['JWT', 'api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/v1/portfolioitems/{id}', 'GET',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='PortfolioitemsIdGetResponse', # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def get_product_by_id(self, id, **kwargs): # noqa: E501\n \"\"\"get_product_by_id # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_product_by_id(id, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str id: The id of the product to return. (required)\n :param str include:\n :return: ProductResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.get_product_by_id_with_http_info(id, **kwargs) # noqa: E501\n else:\n (data) = self.get_product_by_id_with_http_info(id, **kwargs) # noqa: E501\n return data\n\n def get_product_by_id_with_http_info(self, id, **kwargs): # noqa: E501\n \"\"\"get_product_by_id # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_product_by_id_with_http_info(id, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str id: The id of the product to return. (required)\n :param str include:\n :return: ProductResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['id', 'include'] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method get_product_by_id\" % key\n )\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'id' is set\n if ('id' not in params or\n params['id'] is None):\n raise ValueError(\"Missing the required parameter `id` when calling `get_product_by_id`\") # noqa: E501\n\n collection_formats = {}\n\n path_params = {}\n if 'id' in params:\n path_params['id'] = params['id'] # noqa: E501\n\n query_params = []\n if 'include' in params:\n query_params.append(('include', params['include'])) # noqa: E501\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['JWT', 'api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/v1/products/{id}', 'GET',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='ProductResponse', # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def get_product_market_data(self, product_id, **kwargs): # noqa: E501\n \"\"\"Provides historical market data for a given product. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_product_market_data(product_id, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str product_id: The product's product UUID (required)\n :param str sku: The product's SKU\n :return: MarketData\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.get_product_market_data_with_http_info(product_id, **kwargs) # noqa: E501\n else:\n (data) = self.get_product_market_data_with_http_info(product_id, **kwargs) # noqa: E501\n return data\n\n def get_product_market_data_with_http_info(self, product_id, **kwargs): # noqa: E501\n \"\"\"Provides historical market data for a given product. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_product_market_data_with_http_info(product_id, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str product_id: The product's product UUID (required)\n :param str sku: The product's SKU\n :return: MarketData\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['product_id', 'sku'] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method get_product_market_data\" % key\n )\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'product_id' is set\n if ('product_id' not in params or\n params['product_id'] is None):\n raise ValueError(\"Missing the required parameter `product_id` when calling `get_product_market_data`\") # noqa: E501\n\n collection_formats = {}\n\n path_params = {}\n if 'product_id' in params:\n path_params['productId'] = params['product_id'] # noqa: E501\n\n query_params = []\n if 'sku' in params:\n query_params.append(('sku', params['sku'])) # noqa: E501\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # HTTP header `Content-Type`\n header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['JWT', 'api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/v1/products/{productId}/market', 'GET',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='MarketData', # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def get_subscriptions(self, **kwargs): # noqa: E501\n \"\"\"get_subscriptions # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_subscriptions(async=True)\n >>> result = thread.get()\n\n :param async bool\n :return: SubscriptionsResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.get_subscriptions_with_http_info(**kwargs) # noqa: E501\n else:\n (data) = self.get_subscriptions_with_http_info(**kwargs) # noqa: E501\n return data\n\n def get_subscriptions_with_http_info(self, **kwargs): # noqa: E501\n \"\"\"get_subscriptions # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_subscriptions_with_http_info(async=True)\n >>> result = thread.get()\n\n :param async bool\n :return: SubscriptionsResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = [] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method get_subscriptions\" % key\n )\n params[key] = val\n del params['kwargs']\n\n collection_formats = {}\n\n path_params = {}\n\n query_params = []\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/webhook/v1/subscriptions', 'GET',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='SubscriptionsResponse', # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def get_webhook(self, id, **kwargs): # noqa: E501\n \"\"\"get_webhook # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_webhook(id, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str id: (required)\n :return: WebhooksIdGetResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.get_webhook_with_http_info(id, **kwargs) # noqa: E501\n else:\n (data) = self.get_webhook_with_http_info(id, **kwargs) # noqa: E501\n return data\n\n def get_webhook_with_http_info(self, id, **kwargs): # noqa: E501\n \"\"\"get_webhook # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_webhook_with_http_info(id, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str id: (required)\n :return: WebhooksIdGetResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['id'] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method get_webhook\" % key\n )\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'id' is set\n if ('id' not in params or\n params['id'] is None):\n raise ValueError(\"Missing the required parameter `id` when calling `get_webhook`\") # noqa: E501\n\n collection_formats = {}\n\n path_params = {}\n if 'id' in params:\n path_params['id'] = params['id'] # noqa: E501\n\n query_params = []\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/webhook/v1/webhooks/{id}', 'GET',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='WebhooksIdGetResponse', # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def get_webhooks(self, **kwargs): # noqa: E501\n \"\"\"get_webhooks # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_webhooks(async=True)\n >>> result = thread.get()\n\n :param async bool\n :return: WebhooksGetResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.get_webhooks_with_http_info(**kwargs) # noqa: E501\n else:\n (data) = self.get_webhooks_with_http_info(**kwargs) # noqa: E501\n return data\n\n def get_webhooks_with_http_info(self, **kwargs): # noqa: E501\n \"\"\"get_webhooks # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.get_webhooks_with_http_info(async=True)\n >>> result = thread.get()\n\n :param async bool\n :return: WebhooksGetResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = [] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method get_webhooks\" % key\n )\n params[key] = val\n del params['kwargs']\n\n collection_formats = {}\n\n path_params = {}\n\n query_params = []\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/webhook/v1/webhooks', 'GET',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='WebhooksGetResponse', # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def login(self, login, **kwargs): # noqa: E501\n \"\"\"Attempts to log the user in with a username and password. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.login(login, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param LoginRequest login: Object that contains the user's authentication credentials.' (required)\n :return: LoginResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.login_with_http_info(login, **kwargs) # noqa: E501\n else:\n (data) = self.login_with_http_info(login, **kwargs) # noqa: E501\n return data\n\n def login_with_http_info(self, login, **kwargs): # noqa: E501\n \"\"\"Attempts to log the user in with a username and password. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.login_with_http_info(login, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param LoginRequest login: Object that contains the user's authentication credentials.' (required)\n :return: LoginResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['login'] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method login\" % key\n )\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'login' is set\n if ('login' not in params or\n params['login'] is None):\n raise ValueError(\"Missing the required parameter `login` when calling `login`\") # noqa: E501\n\n collection_formats = {}\n\n path_params = {}\n\n query_params = []\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n if 'login' in params:\n body_params = params['login']\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # HTTP header `Content-Type`\n header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/v1/login', 'POST',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='LoginResponse', # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def lookup_product(self, **kwargs): # noqa: E501\n \"\"\"lookup_product # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.lookup_product(async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str identifier: The product identifier to lookup, e.g. (air-jordan-1-retro-high-off-white-chicago)\n :param str size: The size of the product.\n :return: ProductInfo\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.lookup_product_with_http_info(**kwargs) # noqa: E501\n else:\n (data) = self.lookup_product_with_http_info(**kwargs) # noqa: E501\n return data\n\n def lookup_product_with_http_info(self, **kwargs): # noqa: E501\n \"\"\"lookup_product # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.lookup_product_with_http_info(async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str identifier: The product identifier to lookup, e.g. (air-jordan-1-retro-high-off-white-chicago)\n :param str size: The size of the product.\n :return: ProductInfo\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['identifier', 'size'] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method lookup_product\" % key\n )\n params[key] = val\n del params['kwargs']\n\n collection_formats = {}\n\n path_params = {}\n\n query_params = []\n if 'identifier' in params:\n query_params.append(('identifier', params['identifier'])) # noqa: E501\n if 'size' in params:\n query_params.append(('size', params['size'])) # noqa: E501\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['JWT', 'api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/product/lookup', 'GET',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='ProductInfo', # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def new_portfolio_ask(self, portfolio, **kwargs): # noqa: E501\n \"\"\"Creates a new seller ask on the market for a given product. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.new_portfolio_ask(portfolio, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param PortfolioRequest portfolio: The portfolio request representing the ask to place on the market. (required)\n :return: PortfolioResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.new_portfolio_ask_with_http_info(portfolio, **kwargs) # noqa: E501\n else:\n (data) = self.new_portfolio_ask_with_http_info(portfolio, **kwargs) # noqa: E501\n return data\n\n def new_portfolio_ask_with_http_info(self, portfolio, **kwargs): # noqa: E501\n \"\"\"Creates a new seller ask on the market for a given product. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.new_portfolio_ask_with_http_info(portfolio, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param PortfolioRequest portfolio: The portfolio request representing the ask to place on the market. (required)\n :return: PortfolioResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['portfolio'] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method new_portfolio_ask\" % key\n )\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'portfolio' is set\n if ('portfolio' not in params or\n params['portfolio'] is None):\n raise ValueError(\"Missing the required parameter `portfolio` when calling `new_portfolio_ask`\") # noqa: E501\n\n collection_formats = {}\n\n path_params = {}\n\n query_params = []\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n if 'portfolio' in params:\n body_params = params['portfolio']\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # HTTP header `Content-Type`\n header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/v1/portfolio/ask', 'POST',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='PortfolioResponse', # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def new_portfolio_bid(self, portfolio, **kwargs): # noqa: E501\n \"\"\"Creates a new buyer bid on the market for a given product. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.new_portfolio_bid(portfolio, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param PortfolioRequest portfolio: The portfolio request representing the bid to place on the market. (required)\n :return: PortfolioResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.new_portfolio_bid_with_http_info(portfolio, **kwargs) # noqa: E501\n else:\n (data) = self.new_portfolio_bid_with_http_info(portfolio, **kwargs) # noqa: E501\n return data\n\n def new_portfolio_bid_with_http_info(self, portfolio, **kwargs): # noqa: E501\n \"\"\"Creates a new buyer bid on the market for a given product. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.new_portfolio_bid_with_http_info(portfolio, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param PortfolioRequest portfolio: The portfolio request representing the bid to place on the market. (required)\n :return: PortfolioResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['portfolio'] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method new_portfolio_bid\" % key\n )\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'portfolio' is set\n if ('portfolio' not in params or\n params['portfolio'] is None):\n raise ValueError(\"Missing the required parameter `portfolio` when calling `new_portfolio_bid`\") # noqa: E501\n\n collection_formats = {}\n\n path_params = {}\n\n query_params = []\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n if 'portfolio' in params:\n body_params = params['portfolio']\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # HTTP header `Content-Type`\n header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/v1/portfolio/bid', 'POST',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='PortfolioResponse', # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def post_webhooks(self, portfolio, **kwargs): # noqa: E501\n \"\"\"post_webhooks # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.post_webhooks(portfolio, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param WebhooksPostRequest portfolio: (required)\n :return: WebhooksPostResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.post_webhooks_with_http_info(portfolio, **kwargs) # noqa: E501\n else:\n (data) = self.post_webhooks_with_http_info(portfolio, **kwargs) # noqa: E501\n return data\n\n def post_webhooks_with_http_info(self, portfolio, **kwargs): # noqa: E501\n \"\"\"post_webhooks # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.post_webhooks_with_http_info(portfolio, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param WebhooksPostRequest portfolio: (required)\n :return: WebhooksPostResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['portfolio'] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method post_webhooks\" % key\n )\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'portfolio' is set\n if ('portfolio' not in params or\n params['portfolio'] is None):\n raise ValueError(\"Missing the required parameter `portfolio` when calling `post_webhooks`\") # noqa: E501\n\n collection_formats = {}\n\n path_params = {}\n\n query_params = []\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n if 'portfolio' in params:\n body_params = params['portfolio']\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # HTTP header `Content-Type`\n header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/webhook/v1/webhooks', 'POST',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='WebhooksPostResponse', # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def search(self, query, **kwargs): # noqa: E501\n \"\"\"Searches for products by keyword. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.search(query, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str query: The phrase or keyword to search with. (required)\n :return: SearchResults\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async'):\n return self.search_with_http_info(query, **kwargs) # noqa: E501\n else:\n (data) = self.search_with_http_info(query, **kwargs) # noqa: E501\n return data\n\n def search_with_http_info(self, query, **kwargs): # noqa: E501\n \"\"\"Searches for products by keyword. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async=True\n >>> thread = api.search_with_http_info(query, async=True)\n >>> result = thread.get()\n\n :param async bool\n :param str query: The phrase or keyword to search with. (required)\n :return: SearchResults\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['query'] # noqa: E501\n all_params.append('async')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method search\" % key\n )\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'query' is set\n if ('query' not in params or\n params['query'] is None):\n raise ValueError(\"Missing the required parameter `query` when calling `search`\") # noqa: E501\n\n collection_formats = {}\n\n path_params = {}\n\n query_params = []\n if 'query' in params:\n query_params.append(('query', params['query'])) # noqa: E501\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # HTTP header `Content-Type`\n header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['JWT', 'api_key'] # noqa: E501\n\n return self.api_client.call_api(\n '/v2/search', 'GET',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='SearchResults', # noqa: E501\n auth_settings=auth_settings,\n async=params.get('async'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n" }, { "alpha_fraction": 0.5419734120368958, "alphanum_fraction": 0.5422827005386353, "avg_line_length": 22.946666717529297, "blob_id": "e8923ecd0277471275aa2a0ccb1c50423b0f9f61", "content_id": "c280cd945df7f6cfe1e1c82125e0a2486d853a38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 32330, "license_type": "no_license", "max_line_length": 145, "num_lines": 1350, "path": "/sdk/php/StockX-SDK-PHP/lib/lib/Model/CustomerObject.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * CustomerObject\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Do not edit the class manually.\n */\n\nnamespace StockX\\Client\\Model;\n\nuse \\ArrayAccess;\nuse \\StockX\\Client\\ObjectSerializer;\n\n/**\n * CustomerObject Class Doc Comment\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass CustomerObject implements ModelInterface, ArrayAccess\n{\n const DISCRIMINATOR = null;\n\n /**\n * The original name of the model.\n *\n * @var string\n */\n protected static $swaggerModelName = 'Customer Object';\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerTypes = [\n 'id' => 'string',\n 'uuid' => 'string',\n 'first_name' => 'string',\n 'last_name' => 'string',\n 'full_name' => 'string',\n 'email' => 'string',\n 'username' => 'string',\n 'email_verified' => 'bool',\n 'default_size' => 'string',\n 'categories' => 'string[]',\n 'default_category' => 'string',\n 'vacation_date' => 'string',\n 'is_active' => 'bool',\n 'flagged' => 'bool',\n 'hide_portfolio_banner' => 'bool',\n 'refer_url' => 'string',\n 'created_at' => 'string',\n 'created_at_time' => 'float',\n 'is_trader' => 'bool',\n 'ship_by_date' => 'bool',\n 'is_buying' => 'bool',\n 'is_selling' => 'bool',\n 'billing' => '\\StockX\\Client\\Model\\BillingObject',\n 'shipping' => '\\StockX\\Client\\Model\\CustomerObjectShipping',\n 'cc_only' => '\\StockX\\Client\\Model\\BillingObject',\n 'merchant' => '\\StockX\\Client\\Model\\CustomerObjectMerchant',\n 'promotion_code' => 'string',\n 'paypal_emails' => 'string',\n 'authorization_method' => 'string',\n 'security_override' => 'bool',\n 'team_member' => 'bool',\n 'password_locked' => 'bool',\n 'address_normalize_override' => 'bool',\n 'early_payout_enabled' => 'bool',\n 'early_payout_eligible' => 'bool',\n 'security' => '\\StockX\\Client\\Model\\CustomerObjectSecurity'\n ];\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerFormats = [\n 'id' => null,\n 'uuid' => null,\n 'first_name' => null,\n 'last_name' => null,\n 'full_name' => null,\n 'email' => null,\n 'username' => null,\n 'email_verified' => null,\n 'default_size' => null,\n 'categories' => null,\n 'default_category' => null,\n 'vacation_date' => null,\n 'is_active' => null,\n 'flagged' => null,\n 'hide_portfolio_banner' => null,\n 'refer_url' => null,\n 'created_at' => null,\n 'created_at_time' => null,\n 'is_trader' => null,\n 'ship_by_date' => null,\n 'is_buying' => null,\n 'is_selling' => null,\n 'billing' => null,\n 'shipping' => null,\n 'cc_only' => null,\n 'merchant' => null,\n 'promotion_code' => null,\n 'paypal_emails' => null,\n 'authorization_method' => null,\n 'security_override' => null,\n 'team_member' => null,\n 'password_locked' => null,\n 'address_normalize_override' => null,\n 'early_payout_enabled' => null,\n 'early_payout_eligible' => null,\n 'security' => null\n ];\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerTypes()\n {\n return self::$swaggerTypes;\n }\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerFormats()\n {\n return self::$swaggerFormats;\n }\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @var string[]\n */\n protected static $attributeMap = [\n 'id' => 'id',\n 'uuid' => 'uuid',\n 'first_name' => 'firstName',\n 'last_name' => 'lastName',\n 'full_name' => 'fullName',\n 'email' => 'email',\n 'username' => 'username',\n 'email_verified' => 'emailVerified',\n 'default_size' => 'defaultSize',\n 'categories' => 'categories',\n 'default_category' => 'defaultCategory',\n 'vacation_date' => 'vacationDate',\n 'is_active' => 'isActive',\n 'flagged' => 'flagged',\n 'hide_portfolio_banner' => 'hidePortfolioBanner',\n 'refer_url' => 'referUrl',\n 'created_at' => 'createdAt',\n 'created_at_time' => 'createdAtTime',\n 'is_trader' => 'isTrader',\n 'ship_by_date' => 'shipByDate',\n 'is_buying' => 'isBuying',\n 'is_selling' => 'isSelling',\n 'billing' => 'Billing',\n 'shipping' => 'Shipping',\n 'cc_only' => 'CCOnly',\n 'merchant' => 'Merchant',\n 'promotion_code' => 'promotionCode',\n 'paypal_emails' => 'paypalEmails',\n 'authorization_method' => 'authorizationMethod',\n 'security_override' => 'securityOverride',\n 'team_member' => 'teamMember',\n 'password_locked' => 'passwordLocked',\n 'address_normalize_override' => 'addressNormalizeOverride',\n 'early_payout_enabled' => 'earlyPayoutEnabled',\n 'early_payout_eligible' => 'earlyPayoutEligible',\n 'security' => 'security'\n ];\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @var string[]\n */\n protected static $setters = [\n 'id' => 'setId',\n 'uuid' => 'setUuid',\n 'first_name' => 'setFirstName',\n 'last_name' => 'setLastName',\n 'full_name' => 'setFullName',\n 'email' => 'setEmail',\n 'username' => 'setUsername',\n 'email_verified' => 'setEmailVerified',\n 'default_size' => 'setDefaultSize',\n 'categories' => 'setCategories',\n 'default_category' => 'setDefaultCategory',\n 'vacation_date' => 'setVacationDate',\n 'is_active' => 'setIsActive',\n 'flagged' => 'setFlagged',\n 'hide_portfolio_banner' => 'setHidePortfolioBanner',\n 'refer_url' => 'setReferUrl',\n 'created_at' => 'setCreatedAt',\n 'created_at_time' => 'setCreatedAtTime',\n 'is_trader' => 'setIsTrader',\n 'ship_by_date' => 'setShipByDate',\n 'is_buying' => 'setIsBuying',\n 'is_selling' => 'setIsSelling',\n 'billing' => 'setBilling',\n 'shipping' => 'setShipping',\n 'cc_only' => 'setCcOnly',\n 'merchant' => 'setMerchant',\n 'promotion_code' => 'setPromotionCode',\n 'paypal_emails' => 'setPaypalEmails',\n 'authorization_method' => 'setAuthorizationMethod',\n 'security_override' => 'setSecurityOverride',\n 'team_member' => 'setTeamMember',\n 'password_locked' => 'setPasswordLocked',\n 'address_normalize_override' => 'setAddressNormalizeOverride',\n 'early_payout_enabled' => 'setEarlyPayoutEnabled',\n 'early_payout_eligible' => 'setEarlyPayoutEligible',\n 'security' => 'setSecurity'\n ];\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @var string[]\n */\n protected static $getters = [\n 'id' => 'getId',\n 'uuid' => 'getUuid',\n 'first_name' => 'getFirstName',\n 'last_name' => 'getLastName',\n 'full_name' => 'getFullName',\n 'email' => 'getEmail',\n 'username' => 'getUsername',\n 'email_verified' => 'getEmailVerified',\n 'default_size' => 'getDefaultSize',\n 'categories' => 'getCategories',\n 'default_category' => 'getDefaultCategory',\n 'vacation_date' => 'getVacationDate',\n 'is_active' => 'getIsActive',\n 'flagged' => 'getFlagged',\n 'hide_portfolio_banner' => 'getHidePortfolioBanner',\n 'refer_url' => 'getReferUrl',\n 'created_at' => 'getCreatedAt',\n 'created_at_time' => 'getCreatedAtTime',\n 'is_trader' => 'getIsTrader',\n 'ship_by_date' => 'getShipByDate',\n 'is_buying' => 'getIsBuying',\n 'is_selling' => 'getIsSelling',\n 'billing' => 'getBilling',\n 'shipping' => 'getShipping',\n 'cc_only' => 'getCcOnly',\n 'merchant' => 'getMerchant',\n 'promotion_code' => 'getPromotionCode',\n 'paypal_emails' => 'getPaypalEmails',\n 'authorization_method' => 'getAuthorizationMethod',\n 'security_override' => 'getSecurityOverride',\n 'team_member' => 'getTeamMember',\n 'password_locked' => 'getPasswordLocked',\n 'address_normalize_override' => 'getAddressNormalizeOverride',\n 'early_payout_enabled' => 'getEarlyPayoutEnabled',\n 'early_payout_eligible' => 'getEarlyPayoutEligible',\n 'security' => 'getSecurity'\n ];\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @return array\n */\n public static function attributeMap()\n {\n return self::$attributeMap;\n }\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @return array\n */\n public static function setters()\n {\n return self::$setters;\n }\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @return array\n */\n public static function getters()\n {\n return self::$getters;\n }\n\n /**\n * The original name of the model.\n *\n * @return string\n */\n public function getModelName()\n {\n return self::$swaggerModelName;\n }\n\n \n\n \n\n /**\n * Associative array for storing property values\n *\n * @var mixed[]\n */\n protected $container = [];\n\n /**\n * Constructor\n *\n * @param mixed[] $data Associated array of property values\n * initializing the model\n */\n public function __construct(array $data = null)\n {\n $this->container['id'] = isset($data['id']) ? $data['id'] : null;\n $this->container['uuid'] = isset($data['uuid']) ? $data['uuid'] : null;\n $this->container['first_name'] = isset($data['first_name']) ? $data['first_name'] : null;\n $this->container['last_name'] = isset($data['last_name']) ? $data['last_name'] : null;\n $this->container['full_name'] = isset($data['full_name']) ? $data['full_name'] : null;\n $this->container['email'] = isset($data['email']) ? $data['email'] : null;\n $this->container['username'] = isset($data['username']) ? $data['username'] : null;\n $this->container['email_verified'] = isset($data['email_verified']) ? $data['email_verified'] : null;\n $this->container['default_size'] = isset($data['default_size']) ? $data['default_size'] : null;\n $this->container['categories'] = isset($data['categories']) ? $data['categories'] : null;\n $this->container['default_category'] = isset($data['default_category']) ? $data['default_category'] : null;\n $this->container['vacation_date'] = isset($data['vacation_date']) ? $data['vacation_date'] : null;\n $this->container['is_active'] = isset($data['is_active']) ? $data['is_active'] : null;\n $this->container['flagged'] = isset($data['flagged']) ? $data['flagged'] : null;\n $this->container['hide_portfolio_banner'] = isset($data['hide_portfolio_banner']) ? $data['hide_portfolio_banner'] : null;\n $this->container['refer_url'] = isset($data['refer_url']) ? $data['refer_url'] : null;\n $this->container['created_at'] = isset($data['created_at']) ? $data['created_at'] : null;\n $this->container['created_at_time'] = isset($data['created_at_time']) ? $data['created_at_time'] : null;\n $this->container['is_trader'] = isset($data['is_trader']) ? $data['is_trader'] : null;\n $this->container['ship_by_date'] = isset($data['ship_by_date']) ? $data['ship_by_date'] : null;\n $this->container['is_buying'] = isset($data['is_buying']) ? $data['is_buying'] : null;\n $this->container['is_selling'] = isset($data['is_selling']) ? $data['is_selling'] : null;\n $this->container['billing'] = isset($data['billing']) ? $data['billing'] : null;\n $this->container['shipping'] = isset($data['shipping']) ? $data['shipping'] : null;\n $this->container['cc_only'] = isset($data['cc_only']) ? $data['cc_only'] : null;\n $this->container['merchant'] = isset($data['merchant']) ? $data['merchant'] : null;\n $this->container['promotion_code'] = isset($data['promotion_code']) ? $data['promotion_code'] : null;\n $this->container['paypal_emails'] = isset($data['paypal_emails']) ? $data['paypal_emails'] : null;\n $this->container['authorization_method'] = isset($data['authorization_method']) ? $data['authorization_method'] : null;\n $this->container['security_override'] = isset($data['security_override']) ? $data['security_override'] : null;\n $this->container['team_member'] = isset($data['team_member']) ? $data['team_member'] : null;\n $this->container['password_locked'] = isset($data['password_locked']) ? $data['password_locked'] : null;\n $this->container['address_normalize_override'] = isset($data['address_normalize_override']) ? $data['address_normalize_override'] : null;\n $this->container['early_payout_enabled'] = isset($data['early_payout_enabled']) ? $data['early_payout_enabled'] : null;\n $this->container['early_payout_eligible'] = isset($data['early_payout_eligible']) ? $data['early_payout_eligible'] : null;\n $this->container['security'] = isset($data['security']) ? $data['security'] : null;\n }\n\n /**\n * Show all the invalid properties with reasons.\n *\n * @return array invalid properties with reasons\n */\n public function listInvalidProperties()\n {\n $invalidProperties = [];\n\n return $invalidProperties;\n }\n\n /**\n * Validate all the properties in the model\n * return true if all passed\n *\n * @return bool True if all properties are valid\n */\n public function valid()\n {\n\n return true;\n }\n\n\n /**\n * Gets id\n *\n * @return string\n */\n public function getId()\n {\n return $this->container['id'];\n }\n\n /**\n * Sets id\n *\n * @param string $id id\n *\n * @return $this\n */\n public function setId($id)\n {\n $this->container['id'] = $id;\n\n return $this;\n }\n\n /**\n * Gets uuid\n *\n * @return string\n */\n public function getUuid()\n {\n return $this->container['uuid'];\n }\n\n /**\n * Sets uuid\n *\n * @param string $uuid uuid\n *\n * @return $this\n */\n public function setUuid($uuid)\n {\n $this->container['uuid'] = $uuid;\n\n return $this;\n }\n\n /**\n * Gets first_name\n *\n * @return string\n */\n public function getFirstName()\n {\n return $this->container['first_name'];\n }\n\n /**\n * Sets first_name\n *\n * @param string $first_name first_name\n *\n * @return $this\n */\n public function setFirstName($first_name)\n {\n $this->container['first_name'] = $first_name;\n\n return $this;\n }\n\n /**\n * Gets last_name\n *\n * @return string\n */\n public function getLastName()\n {\n return $this->container['last_name'];\n }\n\n /**\n * Sets last_name\n *\n * @param string $last_name last_name\n *\n * @return $this\n */\n public function setLastName($last_name)\n {\n $this->container['last_name'] = $last_name;\n\n return $this;\n }\n\n /**\n * Gets full_name\n *\n * @return string\n */\n public function getFullName()\n {\n return $this->container['full_name'];\n }\n\n /**\n * Sets full_name\n *\n * @param string $full_name full_name\n *\n * @return $this\n */\n public function setFullName($full_name)\n {\n $this->container['full_name'] = $full_name;\n\n return $this;\n }\n\n /**\n * Gets email\n *\n * @return string\n */\n public function getEmail()\n {\n return $this->container['email'];\n }\n\n /**\n * Sets email\n *\n * @param string $email email\n *\n * @return $this\n */\n public function setEmail($email)\n {\n $this->container['email'] = $email;\n\n return $this;\n }\n\n /**\n * Gets username\n *\n * @return string\n */\n public function getUsername()\n {\n return $this->container['username'];\n }\n\n /**\n * Sets username\n *\n * @param string $username username\n *\n * @return $this\n */\n public function setUsername($username)\n {\n $this->container['username'] = $username;\n\n return $this;\n }\n\n /**\n * Gets email_verified\n *\n * @return bool\n */\n public function getEmailVerified()\n {\n return $this->container['email_verified'];\n }\n\n /**\n * Sets email_verified\n *\n * @param bool $email_verified email_verified\n *\n * @return $this\n */\n public function setEmailVerified($email_verified)\n {\n $this->container['email_verified'] = $email_verified;\n\n return $this;\n }\n\n /**\n * Gets default_size\n *\n * @return string\n */\n public function getDefaultSize()\n {\n return $this->container['default_size'];\n }\n\n /**\n * Sets default_size\n *\n * @param string $default_size default_size\n *\n * @return $this\n */\n public function setDefaultSize($default_size)\n {\n $this->container['default_size'] = $default_size;\n\n return $this;\n }\n\n /**\n * Gets categories\n *\n * @return string[]\n */\n public function getCategories()\n {\n return $this->container['categories'];\n }\n\n /**\n * Sets categories\n *\n * @param string[] $categories categories\n *\n * @return $this\n */\n public function setCategories($categories)\n {\n $this->container['categories'] = $categories;\n\n return $this;\n }\n\n /**\n * Gets default_category\n *\n * @return string\n */\n public function getDefaultCategory()\n {\n return $this->container['default_category'];\n }\n\n /**\n * Sets default_category\n *\n * @param string $default_category default_category\n *\n * @return $this\n */\n public function setDefaultCategory($default_category)\n {\n $this->container['default_category'] = $default_category;\n\n return $this;\n }\n\n /**\n * Gets vacation_date\n *\n * @return string\n */\n public function getVacationDate()\n {\n return $this->container['vacation_date'];\n }\n\n /**\n * Sets vacation_date\n *\n * @param string $vacation_date vacation_date\n *\n * @return $this\n */\n public function setVacationDate($vacation_date)\n {\n $this->container['vacation_date'] = $vacation_date;\n\n return $this;\n }\n\n /**\n * Gets is_active\n *\n * @return bool\n */\n public function getIsActive()\n {\n return $this->container['is_active'];\n }\n\n /**\n * Sets is_active\n *\n * @param bool $is_active is_active\n *\n * @return $this\n */\n public function setIsActive($is_active)\n {\n $this->container['is_active'] = $is_active;\n\n return $this;\n }\n\n /**\n * Gets flagged\n *\n * @return bool\n */\n public function getFlagged()\n {\n return $this->container['flagged'];\n }\n\n /**\n * Sets flagged\n *\n * @param bool $flagged flagged\n *\n * @return $this\n */\n public function setFlagged($flagged)\n {\n $this->container['flagged'] = $flagged;\n\n return $this;\n }\n\n /**\n * Gets hide_portfolio_banner\n *\n * @return bool\n */\n public function getHidePortfolioBanner()\n {\n return $this->container['hide_portfolio_banner'];\n }\n\n /**\n * Sets hide_portfolio_banner\n *\n * @param bool $hide_portfolio_banner hide_portfolio_banner\n *\n * @return $this\n */\n public function setHidePortfolioBanner($hide_portfolio_banner)\n {\n $this->container['hide_portfolio_banner'] = $hide_portfolio_banner;\n\n return $this;\n }\n\n /**\n * Gets refer_url\n *\n * @return string\n */\n public function getReferUrl()\n {\n return $this->container['refer_url'];\n }\n\n /**\n * Sets refer_url\n *\n * @param string $refer_url refer_url\n *\n * @return $this\n */\n public function setReferUrl($refer_url)\n {\n $this->container['refer_url'] = $refer_url;\n\n return $this;\n }\n\n /**\n * Gets created_at\n *\n * @return string\n */\n public function getCreatedAt()\n {\n return $this->container['created_at'];\n }\n\n /**\n * Sets created_at\n *\n * @param string $created_at created_at\n *\n * @return $this\n */\n public function setCreatedAt($created_at)\n {\n $this->container['created_at'] = $created_at;\n\n return $this;\n }\n\n /**\n * Gets created_at_time\n *\n * @return float\n */\n public function getCreatedAtTime()\n {\n return $this->container['created_at_time'];\n }\n\n /**\n * Sets created_at_time\n *\n * @param float $created_at_time created_at_time\n *\n * @return $this\n */\n public function setCreatedAtTime($created_at_time)\n {\n $this->container['created_at_time'] = $created_at_time;\n\n return $this;\n }\n\n /**\n * Gets is_trader\n *\n * @return bool\n */\n public function getIsTrader()\n {\n return $this->container['is_trader'];\n }\n\n /**\n * Sets is_trader\n *\n * @param bool $is_trader is_trader\n *\n * @return $this\n */\n public function setIsTrader($is_trader)\n {\n $this->container['is_trader'] = $is_trader;\n\n return $this;\n }\n\n /**\n * Gets ship_by_date\n *\n * @return bool\n */\n public function getShipByDate()\n {\n return $this->container['ship_by_date'];\n }\n\n /**\n * Sets ship_by_date\n *\n * @param bool $ship_by_date ship_by_date\n *\n * @return $this\n */\n public function setShipByDate($ship_by_date)\n {\n $this->container['ship_by_date'] = $ship_by_date;\n\n return $this;\n }\n\n /**\n * Gets is_buying\n *\n * @return bool\n */\n public function getIsBuying()\n {\n return $this->container['is_buying'];\n }\n\n /**\n * Sets is_buying\n *\n * @param bool $is_buying is_buying\n *\n * @return $this\n */\n public function setIsBuying($is_buying)\n {\n $this->container['is_buying'] = $is_buying;\n\n return $this;\n }\n\n /**\n * Gets is_selling\n *\n * @return bool\n */\n public function getIsSelling()\n {\n return $this->container['is_selling'];\n }\n\n /**\n * Sets is_selling\n *\n * @param bool $is_selling is_selling\n *\n * @return $this\n */\n public function setIsSelling($is_selling)\n {\n $this->container['is_selling'] = $is_selling;\n\n return $this;\n }\n\n /**\n * Gets billing\n *\n * @return \\StockX\\Client\\Model\\BillingObject\n */\n public function getBilling()\n {\n return $this->container['billing'];\n }\n\n /**\n * Sets billing\n *\n * @param \\StockX\\Client\\Model\\BillingObject $billing billing\n *\n * @return $this\n */\n public function setBilling($billing)\n {\n $this->container['billing'] = $billing;\n\n return $this;\n }\n\n /**\n * Gets shipping\n *\n * @return \\StockX\\Client\\Model\\CustomerObjectShipping\n */\n public function getShipping()\n {\n return $this->container['shipping'];\n }\n\n /**\n * Sets shipping\n *\n * @param \\StockX\\Client\\Model\\CustomerObjectShipping $shipping shipping\n *\n * @return $this\n */\n public function setShipping($shipping)\n {\n $this->container['shipping'] = $shipping;\n\n return $this;\n }\n\n /**\n * Gets cc_only\n *\n * @return \\StockX\\Client\\Model\\BillingObject\n */\n public function getCcOnly()\n {\n return $this->container['cc_only'];\n }\n\n /**\n * Sets cc_only\n *\n * @param \\StockX\\Client\\Model\\BillingObject $cc_only cc_only\n *\n * @return $this\n */\n public function setCcOnly($cc_only)\n {\n $this->container['cc_only'] = $cc_only;\n\n return $this;\n }\n\n /**\n * Gets merchant\n *\n * @return \\StockX\\Client\\Model\\CustomerObjectMerchant\n */\n public function getMerchant()\n {\n return $this->container['merchant'];\n }\n\n /**\n * Sets merchant\n *\n * @param \\StockX\\Client\\Model\\CustomerObjectMerchant $merchant merchant\n *\n * @return $this\n */\n public function setMerchant($merchant)\n {\n $this->container['merchant'] = $merchant;\n\n return $this;\n }\n\n /**\n * Gets promotion_code\n *\n * @return string\n */\n public function getPromotionCode()\n {\n return $this->container['promotion_code'];\n }\n\n /**\n * Sets promotion_code\n *\n * @param string $promotion_code promotion_code\n *\n * @return $this\n */\n public function setPromotionCode($promotion_code)\n {\n $this->container['promotion_code'] = $promotion_code;\n\n return $this;\n }\n\n /**\n * Gets paypal_emails\n *\n * @return string\n */\n public function getPaypalEmails()\n {\n return $this->container['paypal_emails'];\n }\n\n /**\n * Sets paypal_emails\n *\n * @param string $paypal_emails paypal_emails\n *\n * @return $this\n */\n public function setPaypalEmails($paypal_emails)\n {\n $this->container['paypal_emails'] = $paypal_emails;\n\n return $this;\n }\n\n /**\n * Gets authorization_method\n *\n * @return string\n */\n public function getAuthorizationMethod()\n {\n return $this->container['authorization_method'];\n }\n\n /**\n * Sets authorization_method\n *\n * @param string $authorization_method authorization_method\n *\n * @return $this\n */\n public function setAuthorizationMethod($authorization_method)\n {\n $this->container['authorization_method'] = $authorization_method;\n\n return $this;\n }\n\n /**\n * Gets security_override\n *\n * @return bool\n */\n public function getSecurityOverride()\n {\n return $this->container['security_override'];\n }\n\n /**\n * Sets security_override\n *\n * @param bool $security_override security_override\n *\n * @return $this\n */\n public function setSecurityOverride($security_override)\n {\n $this->container['security_override'] = $security_override;\n\n return $this;\n }\n\n /**\n * Gets team_member\n *\n * @return bool\n */\n public function getTeamMember()\n {\n return $this->container['team_member'];\n }\n\n /**\n * Sets team_member\n *\n * @param bool $team_member team_member\n *\n * @return $this\n */\n public function setTeamMember($team_member)\n {\n $this->container['team_member'] = $team_member;\n\n return $this;\n }\n\n /**\n * Gets password_locked\n *\n * @return bool\n */\n public function getPasswordLocked()\n {\n return $this->container['password_locked'];\n }\n\n /**\n * Sets password_locked\n *\n * @param bool $password_locked password_locked\n *\n * @return $this\n */\n public function setPasswordLocked($password_locked)\n {\n $this->container['password_locked'] = $password_locked;\n\n return $this;\n }\n\n /**\n * Gets address_normalize_override\n *\n * @return bool\n */\n public function getAddressNormalizeOverride()\n {\n return $this->container['address_normalize_override'];\n }\n\n /**\n * Sets address_normalize_override\n *\n * @param bool $address_normalize_override address_normalize_override\n *\n * @return $this\n */\n public function setAddressNormalizeOverride($address_normalize_override)\n {\n $this->container['address_normalize_override'] = $address_normalize_override;\n\n return $this;\n }\n\n /**\n * Gets early_payout_enabled\n *\n * @return bool\n */\n public function getEarlyPayoutEnabled()\n {\n return $this->container['early_payout_enabled'];\n }\n\n /**\n * Sets early_payout_enabled\n *\n * @param bool $early_payout_enabled early_payout_enabled\n *\n * @return $this\n */\n public function setEarlyPayoutEnabled($early_payout_enabled)\n {\n $this->container['early_payout_enabled'] = $early_payout_enabled;\n\n return $this;\n }\n\n /**\n * Gets early_payout_eligible\n *\n * @return bool\n */\n public function getEarlyPayoutEligible()\n {\n return $this->container['early_payout_eligible'];\n }\n\n /**\n * Sets early_payout_eligible\n *\n * @param bool $early_payout_eligible early_payout_eligible\n *\n * @return $this\n */\n public function setEarlyPayoutEligible($early_payout_eligible)\n {\n $this->container['early_payout_eligible'] = $early_payout_eligible;\n\n return $this;\n }\n\n /**\n * Gets security\n *\n * @return \\StockX\\Client\\Model\\CustomerObjectSecurity\n */\n public function getSecurity()\n {\n return $this->container['security'];\n }\n\n /**\n * Sets security\n *\n * @param \\StockX\\Client\\Model\\CustomerObjectSecurity $security security\n *\n * @return $this\n */\n public function setSecurity($security)\n {\n $this->container['security'] = $security;\n\n return $this;\n }\n /**\n * Returns true if offset exists. False otherwise.\n *\n * @param integer $offset Offset\n *\n * @return boolean\n */\n public function offsetExists($offset)\n {\n return isset($this->container[$offset]);\n }\n\n /**\n * Gets offset.\n *\n * @param integer $offset Offset\n *\n * @return mixed\n */\n public function offsetGet($offset)\n {\n return isset($this->container[$offset]) ? $this->container[$offset] : null;\n }\n\n /**\n * Sets value based on offset.\n *\n * @param integer $offset Offset\n * @param mixed $value Value to be set\n *\n * @return void\n */\n public function offsetSet($offset, $value)\n {\n if (is_null($offset)) {\n $this->container[] = $value;\n } else {\n $this->container[$offset] = $value;\n }\n }\n\n /**\n * Unsets offset.\n *\n * @param integer $offset Offset\n *\n * @return void\n */\n public function offsetUnset($offset)\n {\n unset($this->container[$offset]);\n }\n\n /**\n * Gets the string presentation of the object\n *\n * @return string\n */\n public function __toString()\n {\n if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print\n return json_encode(\n ObjectSerializer::sanitizeForSerialization($this),\n JSON_PRETTY_PRINT\n );\n }\n\n return json_encode(ObjectSerializer::sanitizeForSerialization($this));\n }\n}\n\n\n" }, { "alpha_fraction": 0.5959345698356628, "alphanum_fraction": 0.608099102973938, "avg_line_length": 29.807241439819336, "blob_id": "e6cd019b93347fa19e82568f701523cfe5cf7551", "content_id": "3ff63f8a699e7f1a4cc0bf7326071fbc87376e13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31485, "license_type": "no_license", "max_line_length": 822, "num_lines": 1022, "path": "/sdk/python/lib/io_stockx/models/market_data_market.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass MarketDataMarket(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'product_id': 'int',\n 'sku_uuid': 'str',\n 'product_uuid': 'str',\n 'lowest_ask': 'int',\n 'lowest_ask_size': 'str',\n 'parent_lowest_ask': 'int',\n 'number_of_asks': 'int',\n 'sales_this_period': 'int',\n 'sales_last_period': 'int',\n 'highest_bid': 'int',\n 'highest_bid_size': 'str',\n 'number_of_bids': 'int',\n 'annual_high': 'int',\n 'annual_low': 'int',\n 'deadstock_range_low': 'int',\n 'deadstock_range_high': 'int',\n 'volatility': 'float',\n 'deadstock_sold': 'int',\n 'price_premium': 'float',\n 'average_deadstock_price': 'int',\n 'last_sale': 'int',\n 'last_sale_size': 'str',\n 'sales_last72_hours': 'int',\n 'change_value': 'int',\n 'change_percentage': 'float',\n 'abs_change_percentage': 'float',\n 'total_dollars': 'int',\n 'updated_at': 'int',\n 'last_lowest_ask_time': 'int',\n 'last_highest_bid_time': 'int',\n 'last_sale_date': 'str',\n 'created_at': 'str',\n 'deadstock_sold_rank': 'int',\n 'price_premium_rank': 'int',\n 'average_deadstock_price_rank': 'int',\n 'featured': 'str'\n }\n\n attribute_map = {\n 'product_id': 'productId',\n 'sku_uuid': 'skuUuid',\n 'product_uuid': 'productUuid',\n 'lowest_ask': 'lowestAsk',\n 'lowest_ask_size': 'lowestAskSize',\n 'parent_lowest_ask': 'parentLowestAsk',\n 'number_of_asks': 'numberOfAsks',\n 'sales_this_period': 'salesThisPeriod',\n 'sales_last_period': 'salesLastPeriod',\n 'highest_bid': 'highestBid',\n 'highest_bid_size': 'highestBidSize',\n 'number_of_bids': 'numberOfBids',\n 'annual_high': 'annualHigh',\n 'annual_low': 'annualLow',\n 'deadstock_range_low': 'deadstockRangeLow',\n 'deadstock_range_high': 'deadstockRangeHigh',\n 'volatility': 'volatility',\n 'deadstock_sold': 'deadstockSold',\n 'price_premium': 'pricePremium',\n 'average_deadstock_price': 'averageDeadstockPrice',\n 'last_sale': 'lastSale',\n 'last_sale_size': 'lastSaleSize',\n 'sales_last72_hours': 'salesLast72Hours',\n 'change_value': 'changeValue',\n 'change_percentage': 'changePercentage',\n 'abs_change_percentage': 'absChangePercentage',\n 'total_dollars': 'totalDollars',\n 'updated_at': 'updatedAt',\n 'last_lowest_ask_time': 'lastLowestAskTime',\n 'last_highest_bid_time': 'lastHighestBidTime',\n 'last_sale_date': 'lastSaleDate',\n 'created_at': 'createdAt',\n 'deadstock_sold_rank': 'deadstockSoldRank',\n 'price_premium_rank': 'pricePremiumRank',\n 'average_deadstock_price_rank': 'averageDeadstockPriceRank',\n 'featured': 'featured'\n }\n\n def __init__(self, product_id=None, sku_uuid=None, product_uuid=None, lowest_ask=None, lowest_ask_size=None, parent_lowest_ask=None, number_of_asks=None, sales_this_period=None, sales_last_period=None, highest_bid=None, highest_bid_size=None, number_of_bids=None, annual_high=None, annual_low=None, deadstock_range_low=None, deadstock_range_high=None, volatility=None, deadstock_sold=None, price_premium=None, average_deadstock_price=None, last_sale=None, last_sale_size=None, sales_last72_hours=None, change_value=None, change_percentage=None, abs_change_percentage=None, total_dollars=None, updated_at=None, last_lowest_ask_time=None, last_highest_bid_time=None, last_sale_date=None, created_at=None, deadstock_sold_rank=None, price_premium_rank=None, average_deadstock_price_rank=None, featured=None): # noqa: E501\n \"\"\"MarketDataMarket - a model defined in Swagger\"\"\" # noqa: E501\n\n self._product_id = None\n self._sku_uuid = None\n self._product_uuid = None\n self._lowest_ask = None\n self._lowest_ask_size = None\n self._parent_lowest_ask = None\n self._number_of_asks = None\n self._sales_this_period = None\n self._sales_last_period = None\n self._highest_bid = None\n self._highest_bid_size = None\n self._number_of_bids = None\n self._annual_high = None\n self._annual_low = None\n self._deadstock_range_low = None\n self._deadstock_range_high = None\n self._volatility = None\n self._deadstock_sold = None\n self._price_premium = None\n self._average_deadstock_price = None\n self._last_sale = None\n self._last_sale_size = None\n self._sales_last72_hours = None\n self._change_value = None\n self._change_percentage = None\n self._abs_change_percentage = None\n self._total_dollars = None\n self._updated_at = None\n self._last_lowest_ask_time = None\n self._last_highest_bid_time = None\n self._last_sale_date = None\n self._created_at = None\n self._deadstock_sold_rank = None\n self._price_premium_rank = None\n self._average_deadstock_price_rank = None\n self._featured = None\n self.discriminator = None\n\n if product_id is not None:\n self.product_id = product_id\n if sku_uuid is not None:\n self.sku_uuid = sku_uuid\n if product_uuid is not None:\n self.product_uuid = product_uuid\n if lowest_ask is not None:\n self.lowest_ask = lowest_ask\n if lowest_ask_size is not None:\n self.lowest_ask_size = lowest_ask_size\n if parent_lowest_ask is not None:\n self.parent_lowest_ask = parent_lowest_ask\n if number_of_asks is not None:\n self.number_of_asks = number_of_asks\n if sales_this_period is not None:\n self.sales_this_period = sales_this_period\n if sales_last_period is not None:\n self.sales_last_period = sales_last_period\n if highest_bid is not None:\n self.highest_bid = highest_bid\n if highest_bid_size is not None:\n self.highest_bid_size = highest_bid_size\n if number_of_bids is not None:\n self.number_of_bids = number_of_bids\n if annual_high is not None:\n self.annual_high = annual_high\n if annual_low is not None:\n self.annual_low = annual_low\n if deadstock_range_low is not None:\n self.deadstock_range_low = deadstock_range_low\n if deadstock_range_high is not None:\n self.deadstock_range_high = deadstock_range_high\n if volatility is not None:\n self.volatility = volatility\n if deadstock_sold is not None:\n self.deadstock_sold = deadstock_sold\n if price_premium is not None:\n self.price_premium = price_premium\n if average_deadstock_price is not None:\n self.average_deadstock_price = average_deadstock_price\n if last_sale is not None:\n self.last_sale = last_sale\n if last_sale_size is not None:\n self.last_sale_size = last_sale_size\n if sales_last72_hours is not None:\n self.sales_last72_hours = sales_last72_hours\n if change_value is not None:\n self.change_value = change_value\n if change_percentage is not None:\n self.change_percentage = change_percentage\n if abs_change_percentage is not None:\n self.abs_change_percentage = abs_change_percentage\n if total_dollars is not None:\n self.total_dollars = total_dollars\n if updated_at is not None:\n self.updated_at = updated_at\n if last_lowest_ask_time is not None:\n self.last_lowest_ask_time = last_lowest_ask_time\n if last_highest_bid_time is not None:\n self.last_highest_bid_time = last_highest_bid_time\n if last_sale_date is not None:\n self.last_sale_date = last_sale_date\n if created_at is not None:\n self.created_at = created_at\n if deadstock_sold_rank is not None:\n self.deadstock_sold_rank = deadstock_sold_rank\n if price_premium_rank is not None:\n self.price_premium_rank = price_premium_rank\n if average_deadstock_price_rank is not None:\n self.average_deadstock_price_rank = average_deadstock_price_rank\n if featured is not None:\n self.featured = featured\n\n @property\n def product_id(self):\n \"\"\"Gets the product_id of this MarketDataMarket. # noqa: E501\n\n\n :return: The product_id of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._product_id\n\n @product_id.setter\n def product_id(self, product_id):\n \"\"\"Sets the product_id of this MarketDataMarket.\n\n\n :param product_id: The product_id of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._product_id = product_id\n\n @property\n def sku_uuid(self):\n \"\"\"Gets the sku_uuid of this MarketDataMarket. # noqa: E501\n\n\n :return: The sku_uuid of this MarketDataMarket. # noqa: E501\n :rtype: str\n \"\"\"\n return self._sku_uuid\n\n @sku_uuid.setter\n def sku_uuid(self, sku_uuid):\n \"\"\"Sets the sku_uuid of this MarketDataMarket.\n\n\n :param sku_uuid: The sku_uuid of this MarketDataMarket. # noqa: E501\n :type: str\n \"\"\"\n\n self._sku_uuid = sku_uuid\n\n @property\n def product_uuid(self):\n \"\"\"Gets the product_uuid of this MarketDataMarket. # noqa: E501\n\n\n :return: The product_uuid of this MarketDataMarket. # noqa: E501\n :rtype: str\n \"\"\"\n return self._product_uuid\n\n @product_uuid.setter\n def product_uuid(self, product_uuid):\n \"\"\"Sets the product_uuid of this MarketDataMarket.\n\n\n :param product_uuid: The product_uuid of this MarketDataMarket. # noqa: E501\n :type: str\n \"\"\"\n\n self._product_uuid = product_uuid\n\n @property\n def lowest_ask(self):\n \"\"\"Gets the lowest_ask of this MarketDataMarket. # noqa: E501\n\n\n :return: The lowest_ask of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._lowest_ask\n\n @lowest_ask.setter\n def lowest_ask(self, lowest_ask):\n \"\"\"Sets the lowest_ask of this MarketDataMarket.\n\n\n :param lowest_ask: The lowest_ask of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._lowest_ask = lowest_ask\n\n @property\n def lowest_ask_size(self):\n \"\"\"Gets the lowest_ask_size of this MarketDataMarket. # noqa: E501\n\n\n :return: The lowest_ask_size of this MarketDataMarket. # noqa: E501\n :rtype: str\n \"\"\"\n return self._lowest_ask_size\n\n @lowest_ask_size.setter\n def lowest_ask_size(self, lowest_ask_size):\n \"\"\"Sets the lowest_ask_size of this MarketDataMarket.\n\n\n :param lowest_ask_size: The lowest_ask_size of this MarketDataMarket. # noqa: E501\n :type: str\n \"\"\"\n\n self._lowest_ask_size = lowest_ask_size\n\n @property\n def parent_lowest_ask(self):\n \"\"\"Gets the parent_lowest_ask of this MarketDataMarket. # noqa: E501\n\n\n :return: The parent_lowest_ask of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._parent_lowest_ask\n\n @parent_lowest_ask.setter\n def parent_lowest_ask(self, parent_lowest_ask):\n \"\"\"Sets the parent_lowest_ask of this MarketDataMarket.\n\n\n :param parent_lowest_ask: The parent_lowest_ask of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._parent_lowest_ask = parent_lowest_ask\n\n @property\n def number_of_asks(self):\n \"\"\"Gets the number_of_asks of this MarketDataMarket. # noqa: E501\n\n\n :return: The number_of_asks of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._number_of_asks\n\n @number_of_asks.setter\n def number_of_asks(self, number_of_asks):\n \"\"\"Sets the number_of_asks of this MarketDataMarket.\n\n\n :param number_of_asks: The number_of_asks of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._number_of_asks = number_of_asks\n\n @property\n def sales_this_period(self):\n \"\"\"Gets the sales_this_period of this MarketDataMarket. # noqa: E501\n\n\n :return: The sales_this_period of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._sales_this_period\n\n @sales_this_period.setter\n def sales_this_period(self, sales_this_period):\n \"\"\"Sets the sales_this_period of this MarketDataMarket.\n\n\n :param sales_this_period: The sales_this_period of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._sales_this_period = sales_this_period\n\n @property\n def sales_last_period(self):\n \"\"\"Gets the sales_last_period of this MarketDataMarket. # noqa: E501\n\n\n :return: The sales_last_period of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._sales_last_period\n\n @sales_last_period.setter\n def sales_last_period(self, sales_last_period):\n \"\"\"Sets the sales_last_period of this MarketDataMarket.\n\n\n :param sales_last_period: The sales_last_period of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._sales_last_period = sales_last_period\n\n @property\n def highest_bid(self):\n \"\"\"Gets the highest_bid of this MarketDataMarket. # noqa: E501\n\n\n :return: The highest_bid of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._highest_bid\n\n @highest_bid.setter\n def highest_bid(self, highest_bid):\n \"\"\"Sets the highest_bid of this MarketDataMarket.\n\n\n :param highest_bid: The highest_bid of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._highest_bid = highest_bid\n\n @property\n def highest_bid_size(self):\n \"\"\"Gets the highest_bid_size of this MarketDataMarket. # noqa: E501\n\n\n :return: The highest_bid_size of this MarketDataMarket. # noqa: E501\n :rtype: str\n \"\"\"\n return self._highest_bid_size\n\n @highest_bid_size.setter\n def highest_bid_size(self, highest_bid_size):\n \"\"\"Sets the highest_bid_size of this MarketDataMarket.\n\n\n :param highest_bid_size: The highest_bid_size of this MarketDataMarket. # noqa: E501\n :type: str\n \"\"\"\n\n self._highest_bid_size = highest_bid_size\n\n @property\n def number_of_bids(self):\n \"\"\"Gets the number_of_bids of this MarketDataMarket. # noqa: E501\n\n\n :return: The number_of_bids of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._number_of_bids\n\n @number_of_bids.setter\n def number_of_bids(self, number_of_bids):\n \"\"\"Sets the number_of_bids of this MarketDataMarket.\n\n\n :param number_of_bids: The number_of_bids of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._number_of_bids = number_of_bids\n\n @property\n def annual_high(self):\n \"\"\"Gets the annual_high of this MarketDataMarket. # noqa: E501\n\n\n :return: The annual_high of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._annual_high\n\n @annual_high.setter\n def annual_high(self, annual_high):\n \"\"\"Sets the annual_high of this MarketDataMarket.\n\n\n :param annual_high: The annual_high of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._annual_high = annual_high\n\n @property\n def annual_low(self):\n \"\"\"Gets the annual_low of this MarketDataMarket. # noqa: E501\n\n\n :return: The annual_low of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._annual_low\n\n @annual_low.setter\n def annual_low(self, annual_low):\n \"\"\"Sets the annual_low of this MarketDataMarket.\n\n\n :param annual_low: The annual_low of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._annual_low = annual_low\n\n @property\n def deadstock_range_low(self):\n \"\"\"Gets the deadstock_range_low of this MarketDataMarket. # noqa: E501\n\n\n :return: The deadstock_range_low of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._deadstock_range_low\n\n @deadstock_range_low.setter\n def deadstock_range_low(self, deadstock_range_low):\n \"\"\"Sets the deadstock_range_low of this MarketDataMarket.\n\n\n :param deadstock_range_low: The deadstock_range_low of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._deadstock_range_low = deadstock_range_low\n\n @property\n def deadstock_range_high(self):\n \"\"\"Gets the deadstock_range_high of this MarketDataMarket. # noqa: E501\n\n\n :return: The deadstock_range_high of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._deadstock_range_high\n\n @deadstock_range_high.setter\n def deadstock_range_high(self, deadstock_range_high):\n \"\"\"Sets the deadstock_range_high of this MarketDataMarket.\n\n\n :param deadstock_range_high: The deadstock_range_high of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._deadstock_range_high = deadstock_range_high\n\n @property\n def volatility(self):\n \"\"\"Gets the volatility of this MarketDataMarket. # noqa: E501\n\n\n :return: The volatility of this MarketDataMarket. # noqa: E501\n :rtype: float\n \"\"\"\n return self._volatility\n\n @volatility.setter\n def volatility(self, volatility):\n \"\"\"Sets the volatility of this MarketDataMarket.\n\n\n :param volatility: The volatility of this MarketDataMarket. # noqa: E501\n :type: float\n \"\"\"\n\n self._volatility = volatility\n\n @property\n def deadstock_sold(self):\n \"\"\"Gets the deadstock_sold of this MarketDataMarket. # noqa: E501\n\n\n :return: The deadstock_sold of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._deadstock_sold\n\n @deadstock_sold.setter\n def deadstock_sold(self, deadstock_sold):\n \"\"\"Sets the deadstock_sold of this MarketDataMarket.\n\n\n :param deadstock_sold: The deadstock_sold of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._deadstock_sold = deadstock_sold\n\n @property\n def price_premium(self):\n \"\"\"Gets the price_premium of this MarketDataMarket. # noqa: E501\n\n\n :return: The price_premium of this MarketDataMarket. # noqa: E501\n :rtype: float\n \"\"\"\n return self._price_premium\n\n @price_premium.setter\n def price_premium(self, price_premium):\n \"\"\"Sets the price_premium of this MarketDataMarket.\n\n\n :param price_premium: The price_premium of this MarketDataMarket. # noqa: E501\n :type: float\n \"\"\"\n\n self._price_premium = price_premium\n\n @property\n def average_deadstock_price(self):\n \"\"\"Gets the average_deadstock_price of this MarketDataMarket. # noqa: E501\n\n\n :return: The average_deadstock_price of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._average_deadstock_price\n\n @average_deadstock_price.setter\n def average_deadstock_price(self, average_deadstock_price):\n \"\"\"Sets the average_deadstock_price of this MarketDataMarket.\n\n\n :param average_deadstock_price: The average_deadstock_price of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._average_deadstock_price = average_deadstock_price\n\n @property\n def last_sale(self):\n \"\"\"Gets the last_sale of this MarketDataMarket. # noqa: E501\n\n\n :return: The last_sale of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._last_sale\n\n @last_sale.setter\n def last_sale(self, last_sale):\n \"\"\"Sets the last_sale of this MarketDataMarket.\n\n\n :param last_sale: The last_sale of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._last_sale = last_sale\n\n @property\n def last_sale_size(self):\n \"\"\"Gets the last_sale_size of this MarketDataMarket. # noqa: E501\n\n\n :return: The last_sale_size of this MarketDataMarket. # noqa: E501\n :rtype: str\n \"\"\"\n return self._last_sale_size\n\n @last_sale_size.setter\n def last_sale_size(self, last_sale_size):\n \"\"\"Sets the last_sale_size of this MarketDataMarket.\n\n\n :param last_sale_size: The last_sale_size of this MarketDataMarket. # noqa: E501\n :type: str\n \"\"\"\n\n self._last_sale_size = last_sale_size\n\n @property\n def sales_last72_hours(self):\n \"\"\"Gets the sales_last72_hours of this MarketDataMarket. # noqa: E501\n\n\n :return: The sales_last72_hours of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._sales_last72_hours\n\n @sales_last72_hours.setter\n def sales_last72_hours(self, sales_last72_hours):\n \"\"\"Sets the sales_last72_hours of this MarketDataMarket.\n\n\n :param sales_last72_hours: The sales_last72_hours of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._sales_last72_hours = sales_last72_hours\n\n @property\n def change_value(self):\n \"\"\"Gets the change_value of this MarketDataMarket. # noqa: E501\n\n\n :return: The change_value of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._change_value\n\n @change_value.setter\n def change_value(self, change_value):\n \"\"\"Sets the change_value of this MarketDataMarket.\n\n\n :param change_value: The change_value of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._change_value = change_value\n\n @property\n def change_percentage(self):\n \"\"\"Gets the change_percentage of this MarketDataMarket. # noqa: E501\n\n\n :return: The change_percentage of this MarketDataMarket. # noqa: E501\n :rtype: float\n \"\"\"\n return self._change_percentage\n\n @change_percentage.setter\n def change_percentage(self, change_percentage):\n \"\"\"Sets the change_percentage of this MarketDataMarket.\n\n\n :param change_percentage: The change_percentage of this MarketDataMarket. # noqa: E501\n :type: float\n \"\"\"\n\n self._change_percentage = change_percentage\n\n @property\n def abs_change_percentage(self):\n \"\"\"Gets the abs_change_percentage of this MarketDataMarket. # noqa: E501\n\n\n :return: The abs_change_percentage of this MarketDataMarket. # noqa: E501\n :rtype: float\n \"\"\"\n return self._abs_change_percentage\n\n @abs_change_percentage.setter\n def abs_change_percentage(self, abs_change_percentage):\n \"\"\"Sets the abs_change_percentage of this MarketDataMarket.\n\n\n :param abs_change_percentage: The abs_change_percentage of this MarketDataMarket. # noqa: E501\n :type: float\n \"\"\"\n\n self._abs_change_percentage = abs_change_percentage\n\n @property\n def total_dollars(self):\n \"\"\"Gets the total_dollars of this MarketDataMarket. # noqa: E501\n\n\n :return: The total_dollars of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._total_dollars\n\n @total_dollars.setter\n def total_dollars(self, total_dollars):\n \"\"\"Sets the total_dollars of this MarketDataMarket.\n\n\n :param total_dollars: The total_dollars of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._total_dollars = total_dollars\n\n @property\n def updated_at(self):\n \"\"\"Gets the updated_at of this MarketDataMarket. # noqa: E501\n\n\n :return: The updated_at of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._updated_at\n\n @updated_at.setter\n def updated_at(self, updated_at):\n \"\"\"Sets the updated_at of this MarketDataMarket.\n\n\n :param updated_at: The updated_at of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._updated_at = updated_at\n\n @property\n def last_lowest_ask_time(self):\n \"\"\"Gets the last_lowest_ask_time of this MarketDataMarket. # noqa: E501\n\n\n :return: The last_lowest_ask_time of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._last_lowest_ask_time\n\n @last_lowest_ask_time.setter\n def last_lowest_ask_time(self, last_lowest_ask_time):\n \"\"\"Sets the last_lowest_ask_time of this MarketDataMarket.\n\n\n :param last_lowest_ask_time: The last_lowest_ask_time of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._last_lowest_ask_time = last_lowest_ask_time\n\n @property\n def last_highest_bid_time(self):\n \"\"\"Gets the last_highest_bid_time of this MarketDataMarket. # noqa: E501\n\n\n :return: The last_highest_bid_time of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._last_highest_bid_time\n\n @last_highest_bid_time.setter\n def last_highest_bid_time(self, last_highest_bid_time):\n \"\"\"Sets the last_highest_bid_time of this MarketDataMarket.\n\n\n :param last_highest_bid_time: The last_highest_bid_time of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._last_highest_bid_time = last_highest_bid_time\n\n @property\n def last_sale_date(self):\n \"\"\"Gets the last_sale_date of this MarketDataMarket. # noqa: E501\n\n\n :return: The last_sale_date of this MarketDataMarket. # noqa: E501\n :rtype: str\n \"\"\"\n return self._last_sale_date\n\n @last_sale_date.setter\n def last_sale_date(self, last_sale_date):\n \"\"\"Sets the last_sale_date of this MarketDataMarket.\n\n\n :param last_sale_date: The last_sale_date of this MarketDataMarket. # noqa: E501\n :type: str\n \"\"\"\n\n self._last_sale_date = last_sale_date\n\n @property\n def created_at(self):\n \"\"\"Gets the created_at of this MarketDataMarket. # noqa: E501\n\n\n :return: The created_at of this MarketDataMarket. # noqa: E501\n :rtype: str\n \"\"\"\n return self._created_at\n\n @created_at.setter\n def created_at(self, created_at):\n \"\"\"Sets the created_at of this MarketDataMarket.\n\n\n :param created_at: The created_at of this MarketDataMarket. # noqa: E501\n :type: str\n \"\"\"\n\n self._created_at = created_at\n\n @property\n def deadstock_sold_rank(self):\n \"\"\"Gets the deadstock_sold_rank of this MarketDataMarket. # noqa: E501\n\n\n :return: The deadstock_sold_rank of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._deadstock_sold_rank\n\n @deadstock_sold_rank.setter\n def deadstock_sold_rank(self, deadstock_sold_rank):\n \"\"\"Sets the deadstock_sold_rank of this MarketDataMarket.\n\n\n :param deadstock_sold_rank: The deadstock_sold_rank of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._deadstock_sold_rank = deadstock_sold_rank\n\n @property\n def price_premium_rank(self):\n \"\"\"Gets the price_premium_rank of this MarketDataMarket. # noqa: E501\n\n\n :return: The price_premium_rank of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._price_premium_rank\n\n @price_premium_rank.setter\n def price_premium_rank(self, price_premium_rank):\n \"\"\"Sets the price_premium_rank of this MarketDataMarket.\n\n\n :param price_premium_rank: The price_premium_rank of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._price_premium_rank = price_premium_rank\n\n @property\n def average_deadstock_price_rank(self):\n \"\"\"Gets the average_deadstock_price_rank of this MarketDataMarket. # noqa: E501\n\n\n :return: The average_deadstock_price_rank of this MarketDataMarket. # noqa: E501\n :rtype: int\n \"\"\"\n return self._average_deadstock_price_rank\n\n @average_deadstock_price_rank.setter\n def average_deadstock_price_rank(self, average_deadstock_price_rank):\n \"\"\"Sets the average_deadstock_price_rank of this MarketDataMarket.\n\n\n :param average_deadstock_price_rank: The average_deadstock_price_rank of this MarketDataMarket. # noqa: E501\n :type: int\n \"\"\"\n\n self._average_deadstock_price_rank = average_deadstock_price_rank\n\n @property\n def featured(self):\n \"\"\"Gets the featured of this MarketDataMarket. # noqa: E501\n\n\n :return: The featured of this MarketDataMarket. # noqa: E501\n :rtype: str\n \"\"\"\n return self._featured\n\n @featured.setter\n def featured(self, featured):\n \"\"\"Sets the featured of this MarketDataMarket.\n\n\n :param featured: The featured of this MarketDataMarket. # noqa: E501\n :type: str\n \"\"\"\n\n self._featured = featured\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, MarketDataMarket):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.6266666650772095, "alphanum_fraction": 0.634871780872345, "avg_line_length": 33.82143020629883, "blob_id": "a218ae915f94945bac928e16fc9cd1c81c11552f", "content_id": "4956f4e70cfb8103211f144fca59c7e14c7108f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 975, "license_type": "no_license", "max_line_length": 90, "num_lines": 28, "path": "/sdk/csharp/src/IO.StockX.Examples/ExampleConstants.cs", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "\nnamespace Example\n{\n static public class ExampleConstants\n {\n /** The AWS API key provided by StockX to access StockX APIs. */\n public const string AWS_API_KEY = \"<Your AWS API Key>\";\n\n /** The StockX base url to call */\n public const string STOCKX_ENDPOINT = \"https://gateway.stockx.com/stage\";\n\n /** The StockX account password to authenticate with. */\n public const string STOCKX_USERNAME = \"<StockX account username>\";\n\n /** The StockX account password to authenticate with. */\n public const string STOCKX_PASSWORD = \"<StockX account password>\";\n\n /** The product ID to lookup */\n public const string DEMO_PRODUCT_ID = \"air-jordan-1-retro-high-off-white-chicago\";\n\n /** The custoner ID to lookup orders for. */\n public const string DEMO_CUSTOMER_ID = \"1471698\";\n\n /** JWT bearer token header name. */\n public const string JWT_HEADER = \"Jwt-Authorization\";\n\n }\n\n}" }, { "alpha_fraction": 0.6761252284049988, "alphanum_fraction": 0.6790606379508972, "avg_line_length": 29.08823585510254, "blob_id": "92745ffcbd2069d193679f650aa615aa23db9ef0", "content_id": "200860345867cf2715f8af36ecb971a96f8766b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1022, "license_type": "no_license", "max_line_length": 80, "num_lines": 34, "path": "/sdk/php/StockX-SDK-PHP/src/LoginExample.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n\nrequire_once(__DIR__ . '/../lib/vendor/autoload.php');\nrequire_once('LoginUtil.php');\nrequire_once('ExampleConstants.php');\nrequire_once('JWTHeaderSelector.php');\n\n$client = new GuzzleHttp\\Client();\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()\n->setApiKey('x-api-key', ExampleConstants::$AWS_API_KEY)\n->setHost(Environment::$ENDPOINT_SANDBOX);\n\n$headerSelector = new JWTHeaderSelector();\n\n$api = new StockX\\Client\\Api\\StockXApi(\n $client,\n $config,\n $headerSelector\n );\n\n$login = new \\StockX\\Client\\Model\\LoginRequest();\n$login->setEmail(ExampleConstants::$STOCKX_USERNAME);\n$login->setPassword(ExampleConstants::$STOCKX_PASSWORD);\n\ntry {\n $result = $api->loginWithHttpInfo($login);\n $jwtHeader = $result[2][ExampleConstants::$JWT_HEADER][0];\n $headerSelector->setToken($jwtHeader);\n \n $user = $result[0][\"customer\"];\n print_r(\"User logged in: \" . $user[\"full_name\"]);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->login: ', $e->getMessage(), PHP_EOL;\n}" }, { "alpha_fraction": 0.5598522424697876, "alphanum_fraction": 0.5711492300033569, "avg_line_length": 26.72891616821289, "blob_id": "a0791202a50a088ce7f013d0eb750f78625d2875", "content_id": "347e0f559a8ee4b999a4010761a4d272a4d2d6be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4603, "license_type": "no_license", "max_line_length": 176, "num_lines": 166, "path": "/sdk/python/lib/build/lib/io_stockx/models/product_info_attributes.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom io_stockx.models.product_info_attributes_traits import ProductInfoAttributesTraits # noqa: F401,E501\n\n\nclass ProductInfoAttributes(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'product_uuid': 'str',\n 'sku': 'str',\n 'traits': 'ProductInfoAttributesTraits'\n }\n\n attribute_map = {\n 'product_uuid': 'product_uuid',\n 'sku': 'sku',\n 'traits': 'traits'\n }\n\n def __init__(self, product_uuid=None, sku=None, traits=None): # noqa: E501\n \"\"\"ProductInfoAttributes - a model defined in Swagger\"\"\" # noqa: E501\n\n self._product_uuid = None\n self._sku = None\n self._traits = None\n self.discriminator = None\n\n if product_uuid is not None:\n self.product_uuid = product_uuid\n if sku is not None:\n self.sku = sku\n if traits is not None:\n self.traits = traits\n\n @property\n def product_uuid(self):\n \"\"\"Gets the product_uuid of this ProductInfoAttributes. # noqa: E501\n\n\n :return: The product_uuid of this ProductInfoAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._product_uuid\n\n @product_uuid.setter\n def product_uuid(self, product_uuid):\n \"\"\"Sets the product_uuid of this ProductInfoAttributes.\n\n\n :param product_uuid: The product_uuid of this ProductInfoAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._product_uuid = product_uuid\n\n @property\n def sku(self):\n \"\"\"Gets the sku of this ProductInfoAttributes. # noqa: E501\n\n\n :return: The sku of this ProductInfoAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._sku\n\n @sku.setter\n def sku(self, sku):\n \"\"\"Sets the sku of this ProductInfoAttributes.\n\n\n :param sku: The sku of this ProductInfoAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._sku = sku\n\n @property\n def traits(self):\n \"\"\"Gets the traits of this ProductInfoAttributes. # noqa: E501\n\n\n :return: The traits of this ProductInfoAttributes. # noqa: E501\n :rtype: ProductInfoAttributesTraits\n \"\"\"\n return self._traits\n\n @traits.setter\n def traits(self, traits):\n \"\"\"Sets the traits of this ProductInfoAttributes.\n\n\n :param traits: The traits of this ProductInfoAttributes. # noqa: E501\n :type: ProductInfoAttributesTraits\n \"\"\"\n\n self._traits = traits\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ProductInfoAttributes):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.568405032157898, "alphanum_fraction": 0.5700982213020325, "avg_line_length": 15.778409004211426, "blob_id": "9ac91a4617f7281acc7de96dc08f6acf27b5e50d", "content_id": "5ec281bedf14762d48ad6e2695950eb1e4e76e02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5906, "license_type": "no_license", "max_line_length": 110, "num_lines": 352, "path": "/sdk/php/StockX-SDK-PHP/lib/test/Model/ProductResponseProductChildrenPRODUCTIDTest.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * ProductResponseProductChildrenPRODUCTIDTest\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Please update the test case below to test the model.\n */\n\nnamespace StockX\\Client;\n\n/**\n * ProductResponseProductChildrenPRODUCTIDTest Class Doc Comment\n *\n * @category Class */\n// * @description ProductResponseProductChildrenPRODUCTID\n/**\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass ProductResponseProductChildrenPRODUCTIDTest extends \\PHPUnit_Framework_TestCase\n{\n\n /**\n * Setup before running any test case\n */\n public static function setUpBeforeClass()\n {\n }\n\n /**\n * Setup before running each test case\n */\n public function setUp()\n {\n }\n\n /**\n * Clean up after running each test case\n */\n public function tearDown()\n {\n }\n\n /**\n * Clean up after running all test cases\n */\n public static function tearDownAfterClass()\n {\n }\n\n /**\n * Test \"ProductResponseProductChildrenPRODUCTID\"\n */\n public function testProductResponseProductChildrenPRODUCTID()\n {\n }\n\n /**\n * Test attribute \"id\"\n */\n public function testPropertyId()\n {\n }\n\n /**\n * Test attribute \"uuid\"\n */\n public function testPropertyUuid()\n {\n }\n\n /**\n * Test attribute \"brand\"\n */\n public function testPropertyBrand()\n {\n }\n\n /**\n * Test attribute \"category\"\n */\n public function testPropertyCategory()\n {\n }\n\n /**\n * Test attribute \"charity_condition\"\n */\n public function testPropertyCharityCondition()\n {\n }\n\n /**\n * Test attribute \"colorway\"\n */\n public function testPropertyColorway()\n {\n }\n\n /**\n * Test attribute \"condition\"\n */\n public function testPropertyCondition()\n {\n }\n\n /**\n * Test attribute \"country_of_manufacture\"\n */\n public function testPropertyCountryOfManufacture()\n {\n }\n\n /**\n * Test attribute \"gender\"\n */\n public function testPropertyGender()\n {\n }\n\n /**\n * Test attribute \"content_group\"\n */\n public function testPropertyContentGroup()\n {\n }\n\n /**\n * Test attribute \"minimum_bid\"\n */\n public function testPropertyMinimumBid()\n {\n }\n\n /**\n * Test attribute \"media\"\n */\n public function testPropertyMedia()\n {\n }\n\n /**\n * Test attribute \"name\"\n */\n public function testPropertyName()\n {\n }\n\n /**\n * Test attribute \"primary_category\"\n */\n public function testPropertyPrimaryCategory()\n {\n }\n\n /**\n * Test attribute \"secondary_category\"\n */\n public function testPropertySecondaryCategory()\n {\n }\n\n /**\n * Test attribute \"product_category\"\n */\n public function testPropertyProductCategory()\n {\n }\n\n /**\n * Test attribute \"release_date\"\n */\n public function testPropertyReleaseDate()\n {\n }\n\n /**\n * Test attribute \"retail_price\"\n */\n public function testPropertyRetailPrice()\n {\n }\n\n /**\n * Test attribute \"shoe\"\n */\n public function testPropertyShoe()\n {\n }\n\n /**\n * Test attribute \"short_description\"\n */\n public function testPropertyShortDescription()\n {\n }\n\n /**\n * Test attribute \"style_id\"\n */\n public function testPropertyStyleId()\n {\n }\n\n /**\n * Test attribute \"ticker_symbol\"\n */\n public function testPropertyTickerSymbol()\n {\n }\n\n /**\n * Test attribute \"title\"\n */\n public function testPropertyTitle()\n {\n }\n\n /**\n * Test attribute \"data_type\"\n */\n public function testPropertyDataType()\n {\n }\n\n /**\n * Test attribute \"type\"\n */\n public function testPropertyType()\n {\n }\n\n /**\n * Test attribute \"size_title\"\n */\n public function testPropertySizeTitle()\n {\n }\n\n /**\n * Test attribute \"size_descriptor\"\n */\n public function testPropertySizeDescriptor()\n {\n }\n\n /**\n * Test attribute \"size_all_descriptor\"\n */\n public function testPropertySizeAllDescriptor()\n {\n }\n\n /**\n * Test attribute \"url_key\"\n */\n public function testPropertyUrlKey()\n {\n }\n\n /**\n * Test attribute \"year\"\n */\n public function testPropertyYear()\n {\n }\n\n /**\n * Test attribute \"shipping_group\"\n */\n public function testPropertyShippingGroup()\n {\n }\n\n /**\n * Test attribute \"a_lim\"\n */\n public function testPropertyALim()\n {\n }\n\n /**\n * Test attribute \"meta\"\n */\n public function testPropertyMeta()\n {\n }\n\n /**\n * Test attribute \"parent_id\"\n */\n public function testPropertyParentId()\n {\n }\n\n /**\n * Test attribute \"parent_uuid\"\n */\n public function testPropertyParentUuid()\n {\n }\n\n /**\n * Test attribute \"market\"\n */\n public function testPropertyMarket()\n {\n }\n\n /**\n * Test attribute \"size_sort_order\"\n */\n public function testPropertySizeSortOrder()\n {\n }\n\n /**\n * Test attribute \"shoe_size\"\n */\n public function testPropertyShoeSize()\n {\n }\n\n /**\n * Test attribute \"upc\"\n */\n public function testPropertyUpc()\n {\n }\n}\n" }, { "alpha_fraction": 0.6272727251052856, "alphanum_fraction": 0.6272727251052856, "avg_line_length": 22.783782958984375, "blob_id": "ac10129ebc6d34303ebe9e10b1cc8033d3fe8096", "content_id": "202176cfa4c70b71e8f522ccecf1efde10fc63ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 880, "license_type": "no_license", "max_line_length": 79, "num_lines": 37, "path": "/sdk/java/io.stockx.sdk.examples/src/main/java/io/stockx/sdk/examples/base/Environment.java", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "package io.stockx.sdk.examples.base;\n\n/**\n * <p>\n * Environment defines the various gateway instances that StockX exposes to end\n * users.\n * </p>\n */\npublic enum Environment {\n /** Pre-staging environment. */\n SANDBOX(\"https://gateway.stockx.com/sandbox\"),\n\n /** The staging pre-production environment. */\n STAGING(\"https://gateway.stockx.com/stage\"),\n\n /** The production API gateway. */\n PUBLIC(\"https://gateway.stockx.com/public\");\n\n /** The URL associated with the given target environment. */\n private final String url;\n\n private Environment(String url) {\n this.url = url;\n }\n\n /**\n * <p>\n * Returns a String representing the URL used to access the environment.\n * </p>\n * \n * @return a String representing the URL of the supplied environment\n */\n public String getUrl() {\n return this.url;\n }\n\n}\n" }, { "alpha_fraction": 0.6859503984451294, "alphanum_fraction": 0.6859503984451294, "avg_line_length": 29.25, "blob_id": "44bfed7a3c831ade87a7da0dc0efc63c74ba5070", "content_id": "7e3f0844e75e48e61b6946f69d2443209a1a040a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 121, "license_type": "no_license", "max_line_length": 66, "num_lines": 4, "path": "/swagger/copy.sh", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nrm -rf ../sdk/php/StockX-SDK-PHP/client/\ncp -R src-gen/php/StockXClient/. ../sdk/php/StockX-SDK-PHP/client/\n" }, { "alpha_fraction": 0.5768675804138184, "alphanum_fraction": 0.587395429611206, "avg_line_length": 27.65289306640625, "blob_id": "3ff69455bca41ff20beec90ae6c62cc6836137d4", "content_id": "fe1d16bb5c1a272027ca4ba308d716eecc47a844", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6934, "license_type": "no_license", "max_line_length": 176, "num_lines": 242, "path": "/sdk/python/lib/io_stockx/models/portfolio_request_portfolio_item.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass PortfolioRequestPortfolioItem(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'amount': 'str',\n 'expires_at': 'str',\n 'matched_with_date': 'str',\n 'condition': 'str',\n 'action': 'int',\n 'sku_uuid': 'str'\n }\n\n attribute_map = {\n 'amount': 'amount',\n 'expires_at': 'expiresAt',\n 'matched_with_date': 'matchedWithDate',\n 'condition': 'condition',\n 'action': 'action',\n 'sku_uuid': 'skuUuid'\n }\n\n def __init__(self, amount=None, expires_at=None, matched_with_date=None, condition=None, action=None, sku_uuid=None): # noqa: E501\n \"\"\"PortfolioRequestPortfolioItem - a model defined in Swagger\"\"\" # noqa: E501\n\n self._amount = None\n self._expires_at = None\n self._matched_with_date = None\n self._condition = None\n self._action = None\n self._sku_uuid = None\n self.discriminator = None\n\n if amount is not None:\n self.amount = amount\n if expires_at is not None:\n self.expires_at = expires_at\n if matched_with_date is not None:\n self.matched_with_date = matched_with_date\n if condition is not None:\n self.condition = condition\n if action is not None:\n self.action = action\n if sku_uuid is not None:\n self.sku_uuid = sku_uuid\n\n @property\n def amount(self):\n \"\"\"Gets the amount of this PortfolioRequestPortfolioItem. # noqa: E501\n\n\n :return: The amount of this PortfolioRequestPortfolioItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._amount\n\n @amount.setter\n def amount(self, amount):\n \"\"\"Sets the amount of this PortfolioRequestPortfolioItem.\n\n\n :param amount: The amount of this PortfolioRequestPortfolioItem. # noqa: E501\n :type: str\n \"\"\"\n\n self._amount = amount\n\n @property\n def expires_at(self):\n \"\"\"Gets the expires_at of this PortfolioRequestPortfolioItem. # noqa: E501\n\n\n :return: The expires_at of this PortfolioRequestPortfolioItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._expires_at\n\n @expires_at.setter\n def expires_at(self, expires_at):\n \"\"\"Sets the expires_at of this PortfolioRequestPortfolioItem.\n\n\n :param expires_at: The expires_at of this PortfolioRequestPortfolioItem. # noqa: E501\n :type: str\n \"\"\"\n\n self._expires_at = expires_at\n\n @property\n def matched_with_date(self):\n \"\"\"Gets the matched_with_date of this PortfolioRequestPortfolioItem. # noqa: E501\n\n\n :return: The matched_with_date of this PortfolioRequestPortfolioItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._matched_with_date\n\n @matched_with_date.setter\n def matched_with_date(self, matched_with_date):\n \"\"\"Sets the matched_with_date of this PortfolioRequestPortfolioItem.\n\n\n :param matched_with_date: The matched_with_date of this PortfolioRequestPortfolioItem. # noqa: E501\n :type: str\n \"\"\"\n\n self._matched_with_date = matched_with_date\n\n @property\n def condition(self):\n \"\"\"Gets the condition of this PortfolioRequestPortfolioItem. # noqa: E501\n\n\n :return: The condition of this PortfolioRequestPortfolioItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._condition\n\n @condition.setter\n def condition(self, condition):\n \"\"\"Sets the condition of this PortfolioRequestPortfolioItem.\n\n\n :param condition: The condition of this PortfolioRequestPortfolioItem. # noqa: E501\n :type: str\n \"\"\"\n\n self._condition = condition\n\n @property\n def action(self):\n \"\"\"Gets the action of this PortfolioRequestPortfolioItem. # noqa: E501\n\n\n :return: The action of this PortfolioRequestPortfolioItem. # noqa: E501\n :rtype: int\n \"\"\"\n return self._action\n\n @action.setter\n def action(self, action):\n \"\"\"Sets the action of this PortfolioRequestPortfolioItem.\n\n\n :param action: The action of this PortfolioRequestPortfolioItem. # noqa: E501\n :type: int\n \"\"\"\n\n self._action = action\n\n @property\n def sku_uuid(self):\n \"\"\"Gets the sku_uuid of this PortfolioRequestPortfolioItem. # noqa: E501\n\n\n :return: The sku_uuid of this PortfolioRequestPortfolioItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._sku_uuid\n\n @sku_uuid.setter\n def sku_uuid(self, sku_uuid):\n \"\"\"Sets the sku_uuid of this PortfolioRequestPortfolioItem.\n\n\n :param sku_uuid: The sku_uuid of this PortfolioRequestPortfolioItem. # noqa: E501\n :type: str\n \"\"\"\n\n self._sku_uuid = sku_uuid\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, PortfolioRequestPortfolioItem):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.631441056728363, "alphanum_fraction": 0.6384279727935791, "avg_line_length": 28.384614944458008, "blob_id": "30be5fad0c397a6c876bcac946e619c0baf926bc", "content_id": "a590e2e6cdb3cb43dfba5357aad7142066df0b45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1145, "license_type": "no_license", "max_line_length": 81, "num_lines": 39, "path": "/sdk/php/StockX-SDK-PHP/src/ExampleConstants.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n\n/**\n * <p>Contains common values used across examples.</p>\n */\nclass ExampleConstants {\n \n /** The AWS API key provided by StockX to access StockX APIs. */\n public static $AWS_API_KEY = \"e1DqFdSKT9Ew6ozFEzTs77lJdSytDTb7VMQa9Opj\";\n \n /** The StockX account username to authenticate with. */\n public static $STOCKX_USERNAME = \"[email protected]\";\n \n /** The StockX account password to authenticate with. */\n public static $STOCKX_PASSWORD = \"pys2010#1\";\n \n /** The product ID to lookup */\n public static $DEMO_PRODUCT_ID = \"air-jordan-1-retro-high-off-white-chicago\";\n \n /** The custoner ID to lookup orders for. */\n public static $DEMO_CUSTOMER_ID = \"1471698\";\n \n /** Whether to output debug information to console. */\n public static $ENABLE_DEBUG = false;\n \n /** JWT bearer token header name. */\n public static $JWT_HEADER = \"Jwt-Authorization\";\n \n}\n\nclass Environment {\n \n public static $ENDPOINT_PUBLIC = \"https://gateway.stockx.com/public\";\n \n public static $ENDPOINT_SANDBOX = \"https://gateway.stockx.com/sandbox\";\n \n public static $ENDPOINT_STAGING = \"https://gateway.stockx.com/stage\";\n \n}" }, { "alpha_fraction": 0.5305333137512207, "alphanum_fraction": 0.5322666764259338, "avg_line_length": 22.254262924194336, "blob_id": "40e3bd481eb1107d02524d1923b2d09c9c6b38bb", "content_id": "036c6bc7944027e7427c5174b590be52d11bf4b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 30000, "license_type": "no_license", "max_line_length": 136, "num_lines": 1290, "path": "/sdk/php/StockX-SDK-PHP/lib/lib/Model/SearchHit.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * SearchHit\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Do not edit the class manually.\n */\n\nnamespace StockX\\Client\\Model;\n\nuse \\ArrayAccess;\nuse \\StockX\\Client\\ObjectSerializer;\n\n/**\n * SearchHit Class Doc Comment\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass SearchHit implements ModelInterface, ArrayAccess\n{\n const DISCRIMINATOR = null;\n\n /**\n * The original name of the model.\n *\n * @var string\n */\n protected static $swaggerModelName = 'SearchHit';\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerTypes = [\n 'name' => 'string',\n 'brand' => 'string',\n 'thumbnail_url' => 'string',\n 'media' => '\\StockX\\Client\\Model\\SearchHitMedia',\n 'url' => 'string',\n 'release_date' => 'string',\n 'categories' => 'string[]',\n 'product_category' => 'string',\n 'ticker_symbol' => 'string',\n 'style_id' => 'string',\n 'make' => 'string',\n 'model' => 'string',\n 'short_description' => 'string',\n 'gender' => 'string',\n 'colorway' => 'string',\n 'price' => 'int',\n 'description' => 'string',\n 'highest_bid' => 'string',\n 'total_dollars' => 'string',\n 'lowest_ask' => 'string',\n 'last_sale' => 'string',\n 'sales_last_72' => 'int',\n 'deadstock_sold' => 'int',\n 'quality_bid' => 'int',\n 'active' => 'int',\n 'new_release' => 'string',\n 'searchable_traits' => '\\StockX\\Client\\Model\\SearchHitSearchableTraits',\n 'object_id' => 'string',\n 'annual_high' => 'string',\n 'annual_low' => 'string',\n 'deadstock_range_low' => 'string',\n 'deadstock_range_high' => 'string',\n 'average_deadstock_price' => 'string',\n 'change_value' => 'string'\n ];\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerFormats = [\n 'name' => null,\n 'brand' => null,\n 'thumbnail_url' => null,\n 'media' => null,\n 'url' => null,\n 'release_date' => null,\n 'categories' => null,\n 'product_category' => null,\n 'ticker_symbol' => null,\n 'style_id' => null,\n 'make' => null,\n 'model' => null,\n 'short_description' => null,\n 'gender' => null,\n 'colorway' => null,\n 'price' => null,\n 'description' => null,\n 'highest_bid' => null,\n 'total_dollars' => null,\n 'lowest_ask' => null,\n 'last_sale' => null,\n 'sales_last_72' => null,\n 'deadstock_sold' => null,\n 'quality_bid' => null,\n 'active' => null,\n 'new_release' => null,\n 'searchable_traits' => null,\n 'object_id' => null,\n 'annual_high' => null,\n 'annual_low' => null,\n 'deadstock_range_low' => null,\n 'deadstock_range_high' => null,\n 'average_deadstock_price' => null,\n 'change_value' => null\n ];\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerTypes()\n {\n return self::$swaggerTypes;\n }\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerFormats()\n {\n return self::$swaggerFormats;\n }\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @var string[]\n */\n protected static $attributeMap = [\n 'name' => 'name',\n 'brand' => 'brand',\n 'thumbnail_url' => 'thumbnail_url',\n 'media' => 'media',\n 'url' => 'url',\n 'release_date' => 'release_date',\n 'categories' => 'categories',\n 'product_category' => 'product_category',\n 'ticker_symbol' => 'ticker_symbol',\n 'style_id' => 'style_id',\n 'make' => 'make',\n 'model' => 'model',\n 'short_description' => 'short_description',\n 'gender' => 'gender',\n 'colorway' => 'colorway',\n 'price' => 'price',\n 'description' => 'description',\n 'highest_bid' => 'highest_bid',\n 'total_dollars' => 'total_dollars',\n 'lowest_ask' => 'lowest_ask',\n 'last_sale' => 'last_sale',\n 'sales_last_72' => 'sales_last_72',\n 'deadstock_sold' => 'deadstock_sold',\n 'quality_bid' => 'quality_bid',\n 'active' => 'active',\n 'new_release' => 'new_release',\n 'searchable_traits' => 'searchable_traits',\n 'object_id' => 'objectID',\n 'annual_high' => 'annual_high',\n 'annual_low' => 'annual_low',\n 'deadstock_range_low' => 'deadstock_range_low',\n 'deadstock_range_high' => 'deadstock_range_high',\n 'average_deadstock_price' => 'average_deadstock_price',\n 'change_value' => 'change_value'\n ];\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @var string[]\n */\n protected static $setters = [\n 'name' => 'setName',\n 'brand' => 'setBrand',\n 'thumbnail_url' => 'setThumbnailUrl',\n 'media' => 'setMedia',\n 'url' => 'setUrl',\n 'release_date' => 'setReleaseDate',\n 'categories' => 'setCategories',\n 'product_category' => 'setProductCategory',\n 'ticker_symbol' => 'setTickerSymbol',\n 'style_id' => 'setStyleId',\n 'make' => 'setMake',\n 'model' => 'setModel',\n 'short_description' => 'setShortDescription',\n 'gender' => 'setGender',\n 'colorway' => 'setColorway',\n 'price' => 'setPrice',\n 'description' => 'setDescription',\n 'highest_bid' => 'setHighestBid',\n 'total_dollars' => 'setTotalDollars',\n 'lowest_ask' => 'setLowestAsk',\n 'last_sale' => 'setLastSale',\n 'sales_last_72' => 'setSalesLast72',\n 'deadstock_sold' => 'setDeadstockSold',\n 'quality_bid' => 'setQualityBid',\n 'active' => 'setActive',\n 'new_release' => 'setNewRelease',\n 'searchable_traits' => 'setSearchableTraits',\n 'object_id' => 'setObjectId',\n 'annual_high' => 'setAnnualHigh',\n 'annual_low' => 'setAnnualLow',\n 'deadstock_range_low' => 'setDeadstockRangeLow',\n 'deadstock_range_high' => 'setDeadstockRangeHigh',\n 'average_deadstock_price' => 'setAverageDeadstockPrice',\n 'change_value' => 'setChangeValue'\n ];\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @var string[]\n */\n protected static $getters = [\n 'name' => 'getName',\n 'brand' => 'getBrand',\n 'thumbnail_url' => 'getThumbnailUrl',\n 'media' => 'getMedia',\n 'url' => 'getUrl',\n 'release_date' => 'getReleaseDate',\n 'categories' => 'getCategories',\n 'product_category' => 'getProductCategory',\n 'ticker_symbol' => 'getTickerSymbol',\n 'style_id' => 'getStyleId',\n 'make' => 'getMake',\n 'model' => 'getModel',\n 'short_description' => 'getShortDescription',\n 'gender' => 'getGender',\n 'colorway' => 'getColorway',\n 'price' => 'getPrice',\n 'description' => 'getDescription',\n 'highest_bid' => 'getHighestBid',\n 'total_dollars' => 'getTotalDollars',\n 'lowest_ask' => 'getLowestAsk',\n 'last_sale' => 'getLastSale',\n 'sales_last_72' => 'getSalesLast72',\n 'deadstock_sold' => 'getDeadstockSold',\n 'quality_bid' => 'getQualityBid',\n 'active' => 'getActive',\n 'new_release' => 'getNewRelease',\n 'searchable_traits' => 'getSearchableTraits',\n 'object_id' => 'getObjectId',\n 'annual_high' => 'getAnnualHigh',\n 'annual_low' => 'getAnnualLow',\n 'deadstock_range_low' => 'getDeadstockRangeLow',\n 'deadstock_range_high' => 'getDeadstockRangeHigh',\n 'average_deadstock_price' => 'getAverageDeadstockPrice',\n 'change_value' => 'getChangeValue'\n ];\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @return array\n */\n public static function attributeMap()\n {\n return self::$attributeMap;\n }\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @return array\n */\n public static function setters()\n {\n return self::$setters;\n }\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @return array\n */\n public static function getters()\n {\n return self::$getters;\n }\n\n /**\n * The original name of the model.\n *\n * @return string\n */\n public function getModelName()\n {\n return self::$swaggerModelName;\n }\n\n \n\n \n\n /**\n * Associative array for storing property values\n *\n * @var mixed[]\n */\n protected $container = [];\n\n /**\n * Constructor\n *\n * @param mixed[] $data Associated array of property values\n * initializing the model\n */\n public function __construct(array $data = null)\n {\n $this->container['name'] = isset($data['name']) ? $data['name'] : null;\n $this->container['brand'] = isset($data['brand']) ? $data['brand'] : null;\n $this->container['thumbnail_url'] = isset($data['thumbnail_url']) ? $data['thumbnail_url'] : null;\n $this->container['media'] = isset($data['media']) ? $data['media'] : null;\n $this->container['url'] = isset($data['url']) ? $data['url'] : null;\n $this->container['release_date'] = isset($data['release_date']) ? $data['release_date'] : null;\n $this->container['categories'] = isset($data['categories']) ? $data['categories'] : null;\n $this->container['product_category'] = isset($data['product_category']) ? $data['product_category'] : null;\n $this->container['ticker_symbol'] = isset($data['ticker_symbol']) ? $data['ticker_symbol'] : null;\n $this->container['style_id'] = isset($data['style_id']) ? $data['style_id'] : null;\n $this->container['make'] = isset($data['make']) ? $data['make'] : null;\n $this->container['model'] = isset($data['model']) ? $data['model'] : null;\n $this->container['short_description'] = isset($data['short_description']) ? $data['short_description'] : null;\n $this->container['gender'] = isset($data['gender']) ? $data['gender'] : null;\n $this->container['colorway'] = isset($data['colorway']) ? $data['colorway'] : null;\n $this->container['price'] = isset($data['price']) ? $data['price'] : null;\n $this->container['description'] = isset($data['description']) ? $data['description'] : null;\n $this->container['highest_bid'] = isset($data['highest_bid']) ? $data['highest_bid'] : null;\n $this->container['total_dollars'] = isset($data['total_dollars']) ? $data['total_dollars'] : null;\n $this->container['lowest_ask'] = isset($data['lowest_ask']) ? $data['lowest_ask'] : null;\n $this->container['last_sale'] = isset($data['last_sale']) ? $data['last_sale'] : null;\n $this->container['sales_last_72'] = isset($data['sales_last_72']) ? $data['sales_last_72'] : null;\n $this->container['deadstock_sold'] = isset($data['deadstock_sold']) ? $data['deadstock_sold'] : null;\n $this->container['quality_bid'] = isset($data['quality_bid']) ? $data['quality_bid'] : null;\n $this->container['active'] = isset($data['active']) ? $data['active'] : null;\n $this->container['new_release'] = isset($data['new_release']) ? $data['new_release'] : null;\n $this->container['searchable_traits'] = isset($data['searchable_traits']) ? $data['searchable_traits'] : null;\n $this->container['object_id'] = isset($data['object_id']) ? $data['object_id'] : null;\n $this->container['annual_high'] = isset($data['annual_high']) ? $data['annual_high'] : null;\n $this->container['annual_low'] = isset($data['annual_low']) ? $data['annual_low'] : null;\n $this->container['deadstock_range_low'] = isset($data['deadstock_range_low']) ? $data['deadstock_range_low'] : null;\n $this->container['deadstock_range_high'] = isset($data['deadstock_range_high']) ? $data['deadstock_range_high'] : null;\n $this->container['average_deadstock_price'] = isset($data['average_deadstock_price']) ? $data['average_deadstock_price'] : null;\n $this->container['change_value'] = isset($data['change_value']) ? $data['change_value'] : null;\n }\n\n /**\n * Show all the invalid properties with reasons.\n *\n * @return array invalid properties with reasons\n */\n public function listInvalidProperties()\n {\n $invalidProperties = [];\n\n return $invalidProperties;\n }\n\n /**\n * Validate all the properties in the model\n * return true if all passed\n *\n * @return bool True if all properties are valid\n */\n public function valid()\n {\n\n return true;\n }\n\n\n /**\n * Gets name\n *\n * @return string\n */\n public function getName()\n {\n return $this->container['name'];\n }\n\n /**\n * Sets name\n *\n * @param string $name name\n *\n * @return $this\n */\n public function setName($name)\n {\n $this->container['name'] = $name;\n\n return $this;\n }\n\n /**\n * Gets brand\n *\n * @return string\n */\n public function getBrand()\n {\n return $this->container['brand'];\n }\n\n /**\n * Sets brand\n *\n * @param string $brand brand\n *\n * @return $this\n */\n public function setBrand($brand)\n {\n $this->container['brand'] = $brand;\n\n return $this;\n }\n\n /**\n * Gets thumbnail_url\n *\n * @return string\n */\n public function getThumbnailUrl()\n {\n return $this->container['thumbnail_url'];\n }\n\n /**\n * Sets thumbnail_url\n *\n * @param string $thumbnail_url thumbnail_url\n *\n * @return $this\n */\n public function setThumbnailUrl($thumbnail_url)\n {\n $this->container['thumbnail_url'] = $thumbnail_url;\n\n return $this;\n }\n\n /**\n * Gets media\n *\n * @return \\StockX\\Client\\Model\\SearchHitMedia\n */\n public function getMedia()\n {\n return $this->container['media'];\n }\n\n /**\n * Sets media\n *\n * @param \\StockX\\Client\\Model\\SearchHitMedia $media media\n *\n * @return $this\n */\n public function setMedia($media)\n {\n $this->container['media'] = $media;\n\n return $this;\n }\n\n /**\n * Gets url\n *\n * @return string\n */\n public function getUrl()\n {\n return $this->container['url'];\n }\n\n /**\n * Sets url\n *\n * @param string $url url\n *\n * @return $this\n */\n public function setUrl($url)\n {\n $this->container['url'] = $url;\n\n return $this;\n }\n\n /**\n * Gets release_date\n *\n * @return string\n */\n public function getReleaseDate()\n {\n return $this->container['release_date'];\n }\n\n /**\n * Sets release_date\n *\n * @param string $release_date release_date\n *\n * @return $this\n */\n public function setReleaseDate($release_date)\n {\n $this->container['release_date'] = $release_date;\n\n return $this;\n }\n\n /**\n * Gets categories\n *\n * @return string[]\n */\n public function getCategories()\n {\n return $this->container['categories'];\n }\n\n /**\n * Sets categories\n *\n * @param string[] $categories categories\n *\n * @return $this\n */\n public function setCategories($categories)\n {\n $this->container['categories'] = $categories;\n\n return $this;\n }\n\n /**\n * Gets product_category\n *\n * @return string\n */\n public function getProductCategory()\n {\n return $this->container['product_category'];\n }\n\n /**\n * Sets product_category\n *\n * @param string $product_category product_category\n *\n * @return $this\n */\n public function setProductCategory($product_category)\n {\n $this->container['product_category'] = $product_category;\n\n return $this;\n }\n\n /**\n * Gets ticker_symbol\n *\n * @return string\n */\n public function getTickerSymbol()\n {\n return $this->container['ticker_symbol'];\n }\n\n /**\n * Sets ticker_symbol\n *\n * @param string $ticker_symbol ticker_symbol\n *\n * @return $this\n */\n public function setTickerSymbol($ticker_symbol)\n {\n $this->container['ticker_symbol'] = $ticker_symbol;\n\n return $this;\n }\n\n /**\n * Gets style_id\n *\n * @return string\n */\n public function getStyleId()\n {\n return $this->container['style_id'];\n }\n\n /**\n * Sets style_id\n *\n * @param string $style_id style_id\n *\n * @return $this\n */\n public function setStyleId($style_id)\n {\n $this->container['style_id'] = $style_id;\n\n return $this;\n }\n\n /**\n * Gets make\n *\n * @return string\n */\n public function getMake()\n {\n return $this->container['make'];\n }\n\n /**\n * Sets make\n *\n * @param string $make make\n *\n * @return $this\n */\n public function setMake($make)\n {\n $this->container['make'] = $make;\n\n return $this;\n }\n\n /**\n * Gets model\n *\n * @return string\n */\n public function getModel()\n {\n return $this->container['model'];\n }\n\n /**\n * Sets model\n *\n * @param string $model model\n *\n * @return $this\n */\n public function setModel($model)\n {\n $this->container['model'] = $model;\n\n return $this;\n }\n\n /**\n * Gets short_description\n *\n * @return string\n */\n public function getShortDescription()\n {\n return $this->container['short_description'];\n }\n\n /**\n * Sets short_description\n *\n * @param string $short_description short_description\n *\n * @return $this\n */\n public function setShortDescription($short_description)\n {\n $this->container['short_description'] = $short_description;\n\n return $this;\n }\n\n /**\n * Gets gender\n *\n * @return string\n */\n public function getGender()\n {\n return $this->container['gender'];\n }\n\n /**\n * Sets gender\n *\n * @param string $gender gender\n *\n * @return $this\n */\n public function setGender($gender)\n {\n $this->container['gender'] = $gender;\n\n return $this;\n }\n\n /**\n * Gets colorway\n *\n * @return string\n */\n public function getColorway()\n {\n return $this->container['colorway'];\n }\n\n /**\n * Sets colorway\n *\n * @param string $colorway colorway\n *\n * @return $this\n */\n public function setColorway($colorway)\n {\n $this->container['colorway'] = $colorway;\n\n return $this;\n }\n\n /**\n * Gets price\n *\n * @return int\n */\n public function getPrice()\n {\n return $this->container['price'];\n }\n\n /**\n * Sets price\n *\n * @param int $price price\n *\n * @return $this\n */\n public function setPrice($price)\n {\n $this->container['price'] = $price;\n\n return $this;\n }\n\n /**\n * Gets description\n *\n * @return string\n */\n public function getDescription()\n {\n return $this->container['description'];\n }\n\n /**\n * Sets description\n *\n * @param string $description description\n *\n * @return $this\n */\n public function setDescription($description)\n {\n $this->container['description'] = $description;\n\n return $this;\n }\n\n /**\n * Gets highest_bid\n *\n * @return string\n */\n public function getHighestBid()\n {\n return $this->container['highest_bid'];\n }\n\n /**\n * Sets highest_bid\n *\n * @param string $highest_bid highest_bid\n *\n * @return $this\n */\n public function setHighestBid($highest_bid)\n {\n $this->container['highest_bid'] = $highest_bid;\n\n return $this;\n }\n\n /**\n * Gets total_dollars\n *\n * @return string\n */\n public function getTotalDollars()\n {\n return $this->container['total_dollars'];\n }\n\n /**\n * Sets total_dollars\n *\n * @param string $total_dollars total_dollars\n *\n * @return $this\n */\n public function setTotalDollars($total_dollars)\n {\n $this->container['total_dollars'] = $total_dollars;\n\n return $this;\n }\n\n /**\n * Gets lowest_ask\n *\n * @return string\n */\n public function getLowestAsk()\n {\n return $this->container['lowest_ask'];\n }\n\n /**\n * Sets lowest_ask\n *\n * @param string $lowest_ask lowest_ask\n *\n * @return $this\n */\n public function setLowestAsk($lowest_ask)\n {\n $this->container['lowest_ask'] = $lowest_ask;\n\n return $this;\n }\n\n /**\n * Gets last_sale\n *\n * @return string\n */\n public function getLastSale()\n {\n return $this->container['last_sale'];\n }\n\n /**\n * Sets last_sale\n *\n * @param string $last_sale last_sale\n *\n * @return $this\n */\n public function setLastSale($last_sale)\n {\n $this->container['last_sale'] = $last_sale;\n\n return $this;\n }\n\n /**\n * Gets sales_last_72\n *\n * @return int\n */\n public function getSalesLast72()\n {\n return $this->container['sales_last_72'];\n }\n\n /**\n * Sets sales_last_72\n *\n * @param int $sales_last_72 sales_last_72\n *\n * @return $this\n */\n public function setSalesLast72($sales_last_72)\n {\n $this->container['sales_last_72'] = $sales_last_72;\n\n return $this;\n }\n\n /**\n * Gets deadstock_sold\n *\n * @return int\n */\n public function getDeadstockSold()\n {\n return $this->container['deadstock_sold'];\n }\n\n /**\n * Sets deadstock_sold\n *\n * @param int $deadstock_sold deadstock_sold\n *\n * @return $this\n */\n public function setDeadstockSold($deadstock_sold)\n {\n $this->container['deadstock_sold'] = $deadstock_sold;\n\n return $this;\n }\n\n /**\n * Gets quality_bid\n *\n * @return int\n */\n public function getQualityBid()\n {\n return $this->container['quality_bid'];\n }\n\n /**\n * Sets quality_bid\n *\n * @param int $quality_bid quality_bid\n *\n * @return $this\n */\n public function setQualityBid($quality_bid)\n {\n $this->container['quality_bid'] = $quality_bid;\n\n return $this;\n }\n\n /**\n * Gets active\n *\n * @return int\n */\n public function getActive()\n {\n return $this->container['active'];\n }\n\n /**\n * Sets active\n *\n * @param int $active active\n *\n * @return $this\n */\n public function setActive($active)\n {\n $this->container['active'] = $active;\n\n return $this;\n }\n\n /**\n * Gets new_release\n *\n * @return string\n */\n public function getNewRelease()\n {\n return $this->container['new_release'];\n }\n\n /**\n * Sets new_release\n *\n * @param string $new_release new_release\n *\n * @return $this\n */\n public function setNewRelease($new_release)\n {\n $this->container['new_release'] = $new_release;\n\n return $this;\n }\n\n /**\n * Gets searchable_traits\n *\n * @return \\StockX\\Client\\Model\\SearchHitSearchableTraits\n */\n public function getSearchableTraits()\n {\n return $this->container['searchable_traits'];\n }\n\n /**\n * Sets searchable_traits\n *\n * @param \\StockX\\Client\\Model\\SearchHitSearchableTraits $searchable_traits searchable_traits\n *\n * @return $this\n */\n public function setSearchableTraits($searchable_traits)\n {\n $this->container['searchable_traits'] = $searchable_traits;\n\n return $this;\n }\n\n /**\n * Gets object_id\n *\n * @return string\n */\n public function getObjectId()\n {\n return $this->container['object_id'];\n }\n\n /**\n * Sets object_id\n *\n * @param string $object_id object_id\n *\n * @return $this\n */\n public function setObjectId($object_id)\n {\n $this->container['object_id'] = $object_id;\n\n return $this;\n }\n\n /**\n * Gets annual_high\n *\n * @return string\n */\n public function getAnnualHigh()\n {\n return $this->container['annual_high'];\n }\n\n /**\n * Sets annual_high\n *\n * @param string $annual_high annual_high\n *\n * @return $this\n */\n public function setAnnualHigh($annual_high)\n {\n $this->container['annual_high'] = $annual_high;\n\n return $this;\n }\n\n /**\n * Gets annual_low\n *\n * @return string\n */\n public function getAnnualLow()\n {\n return $this->container['annual_low'];\n }\n\n /**\n * Sets annual_low\n *\n * @param string $annual_low annual_low\n *\n * @return $this\n */\n public function setAnnualLow($annual_low)\n {\n $this->container['annual_low'] = $annual_low;\n\n return $this;\n }\n\n /**\n * Gets deadstock_range_low\n *\n * @return string\n */\n public function getDeadstockRangeLow()\n {\n return $this->container['deadstock_range_low'];\n }\n\n /**\n * Sets deadstock_range_low\n *\n * @param string $deadstock_range_low deadstock_range_low\n *\n * @return $this\n */\n public function setDeadstockRangeLow($deadstock_range_low)\n {\n $this->container['deadstock_range_low'] = $deadstock_range_low;\n\n return $this;\n }\n\n /**\n * Gets deadstock_range_high\n *\n * @return string\n */\n public function getDeadstockRangeHigh()\n {\n return $this->container['deadstock_range_high'];\n }\n\n /**\n * Sets deadstock_range_high\n *\n * @param string $deadstock_range_high deadstock_range_high\n *\n * @return $this\n */\n public function setDeadstockRangeHigh($deadstock_range_high)\n {\n $this->container['deadstock_range_high'] = $deadstock_range_high;\n\n return $this;\n }\n\n /**\n * Gets average_deadstock_price\n *\n * @return string\n */\n public function getAverageDeadstockPrice()\n {\n return $this->container['average_deadstock_price'];\n }\n\n /**\n * Sets average_deadstock_price\n *\n * @param string $average_deadstock_price average_deadstock_price\n *\n * @return $this\n */\n public function setAverageDeadstockPrice($average_deadstock_price)\n {\n $this->container['average_deadstock_price'] = $average_deadstock_price;\n\n return $this;\n }\n\n /**\n * Gets change_value\n *\n * @return string\n */\n public function getChangeValue()\n {\n return $this->container['change_value'];\n }\n\n /**\n * Sets change_value\n *\n * @param string $change_value change_value\n *\n * @return $this\n */\n public function setChangeValue($change_value)\n {\n $this->container['change_value'] = $change_value;\n\n return $this;\n }\n /**\n * Returns true if offset exists. False otherwise.\n *\n * @param integer $offset Offset\n *\n * @return boolean\n */\n public function offsetExists($offset)\n {\n return isset($this->container[$offset]);\n }\n\n /**\n * Gets offset.\n *\n * @param integer $offset Offset\n *\n * @return mixed\n */\n public function offsetGet($offset)\n {\n return isset($this->container[$offset]) ? $this->container[$offset] : null;\n }\n\n /**\n * Sets value based on offset.\n *\n * @param integer $offset Offset\n * @param mixed $value Value to be set\n *\n * @return void\n */\n public function offsetSet($offset, $value)\n {\n if (is_null($offset)) {\n $this->container[] = $value;\n } else {\n $this->container[$offset] = $value;\n }\n }\n\n /**\n * Unsets offset.\n *\n * @param integer $offset Offset\n *\n * @return void\n */\n public function offsetUnset($offset)\n {\n unset($this->container[$offset]);\n }\n\n /**\n * Gets the string presentation of the object\n *\n * @return string\n */\n public function __toString()\n {\n if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print\n return json_encode(\n ObjectSerializer::sanitizeForSerialization($this),\n JSON_PRETTY_PRINT\n );\n }\n\n return json_encode(ObjectSerializer::sanitizeForSerialization($this));\n }\n}\n\n\n" }, { "alpha_fraction": 0.652340292930603, "alphanum_fraction": 0.6670591831207275, "avg_line_length": 29.070796966552734, "blob_id": "8e5e551d5e28c43e698bab448dcbfbc1615f2d40", "content_id": "5d0d448d2a54187ce3951ad00e9577f55ad69bc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Maven POM", "length_bytes": 3397, "license_type": "no_license", "max_line_length": 100, "num_lines": 113, "path": "/sdk/java/io.stockx.sdk/pom.xml", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<groupId>io.stockx</groupId>\n\t\t<artifactId>io.stockx.sdk.parent</artifactId>\n\t\t<version>0.0.1-SNAPSHOT</version>\n\t</parent>\n\t<artifactId>io.stockx.sdk</artifactId>\n\t<packaging>jar</packaging>\n\n\t<properties>\n\t\t<java.version>1.7</java.version>\n\t\t<maven.compiler.source>${java.version}</maven.compiler.source>\n\t\t<maven.compiler.target>${java.version}</maven.compiler.target>\n\t\t<gson-fire-version>1.8.0</gson-fire-version>\n\t\t<swagger-core-version>1.5.15</swagger-core-version>\n\t\t<okhttp-version>2.7.5</okhttp-version>\n\t\t<gson-version>2.8.1</gson-version>\n\t\t<threetenbp-version>1.3.5</threetenbp-version>\n\t\t<maven-plugin-version>1.0.0</maven-plugin-version>\n\t\t<junit-version>4.12</junit-version>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>io.swagger</groupId>\n\t\t\t<artifactId>swagger-annotations</artifactId>\n\t\t\t<version>${swagger-core-version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.squareup.okhttp</groupId>\n\t\t\t<artifactId>okhttp</artifactId>\n\t\t\t<version>${okhttp-version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.squareup.okhttp</groupId>\n\t\t\t<artifactId>logging-interceptor</artifactId>\n\t\t\t<version>${okhttp-version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.google.code.gson</groupId>\n\t\t\t<artifactId>gson</artifactId>\n\t\t\t<version>${gson-version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>io.gsonfire</groupId>\n\t\t\t<artifactId>gson-fire</artifactId>\n\t\t\t<version>${gson-fire-version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.threeten</groupId>\n\t\t\t<artifactId>threetenbp</artifactId>\n\t\t\t<version>${threetenbp-version}</version>\n\t\t</dependency>\n\t\t<!-- test dependencies -->\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>${junit-version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.codehaus.mojo</groupId>\n\t\t\t\t<artifactId>build-helper-maven-plugin</artifactId>\n\t\t\t\t<version>3.0.0</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<id>add-source</id>\n\t\t\t\t\t\t<phase>generate-sources</phase>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>add-source</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<sources>\n\t\t\t\t\t\t\t\t<source>../../../swagger/src-gen/java/src/main/java/</source>\n\t\t\t\t\t\t\t</sources>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-shade-plugin</artifactId>\n\t\t\t\t<version>2.3</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<!-- Run shade goal on package phase -->\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<phase>package</phase>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>shade</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<transformers>\n\t\t\t\t\t\t\t\t<!-- add Main-Class to manifest file -->\n\t\t\t\t\t\t\t\t<!-- <transformer\n\t\t\t\t\t\t\t\t\timplementation=\"org.apache.maven.plugins.shade.resource.ManifestResourceTransformer\">\n\t\t\t\t\t\t\t\t\t<mainClass>com.mkyong.core.utils.App</mainClass>\n\t\t\t\t\t\t\t\t</transformer> -->\n\t\t\t\t\t\t\t</transformers>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n</project>" }, { "alpha_fraction": 0.7256532311439514, "alphanum_fraction": 0.7256532311439514, "avg_line_length": 30.22222137451172, "blob_id": "c8121e40f703450b9d8fee9913af30e928dbfd66", "content_id": "a4807990e098807ae22166bfcef4eabcde789f22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 842, "license_type": "no_license", "max_line_length": 96, "num_lines": 27, "path": "/sdk/nodejs/search_example.js", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "var StockX = require('stock_x_api');\n\nvar exampleConstants = new ExampleConstants();\n\nvar defaultClient = StockX.ApiClient.instance;\n\tdefaultClient.basePath = 'https://gateway.stockx.com/stage';\n\nvar apiKey = defaultClient.authentications['api_key'];\n\tapiKey.apiKey = exampleConstants.AWS_API_KEY;\n\nvar stockx = new StockX.StockXApi();\n\nvar login = new StockX.LoginRequest();\n\tlogin.email = exampleConstants.STOCKX_USERNAME;\n\tlogin.password = exampleConstants.STOCKX_PASSWORD;\n\nstockx.loginWithHttpInfo(login)\n\t.then(res => {\n\t\tdefaultClient.defaultHeaders['jwt-authorization'] = res.response.headers['jwt-authorization'];\n\t\treturn res.data.Customer;\n\t}).then(customer => {\n\t\treturn stockx.search('yeezy');\n\t}).then(result => {\n\t\tconsole.log('Search successful: ' + JSON.stringify(result));\n\t}).catch(err => {\n\t\tconsole.log('Error performing search: ' + err);\n\t});" }, { "alpha_fraction": 0.5537968277931213, "alphanum_fraction": 0.5553267002105713, "avg_line_length": 24.175556182861328, "blob_id": "9ecce85fb79cedecd4a4d5c3610558b62f232b7b", "content_id": "f45860251b96c1ad34767a5704b8f4c8ccc81770", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 33989, "license_type": "no_license", "max_line_length": 151, "num_lines": 1350, "path": "/sdk/php/StockX-SDK-PHP/lib/lib/Model/MarketDataMarket.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * MarketDataMarket\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Do not edit the class manually.\n */\n\nnamespace StockX\\Client\\Model;\n\nuse \\ArrayAccess;\nuse \\StockX\\Client\\ObjectSerializer;\n\n/**\n * MarketDataMarket Class Doc Comment\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass MarketDataMarket implements ModelInterface, ArrayAccess\n{\n const DISCRIMINATOR = null;\n\n /**\n * The original name of the model.\n *\n * @var string\n */\n protected static $swaggerModelName = 'MarketData_Market';\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerTypes = [\n 'product_id' => 'int',\n 'sku_uuid' => 'string',\n 'product_uuid' => 'string',\n 'lowest_ask' => 'int',\n 'lowest_ask_size' => 'string',\n 'parent_lowest_ask' => 'int',\n 'number_of_asks' => 'int',\n 'sales_this_period' => 'int',\n 'sales_last_period' => 'int',\n 'highest_bid' => 'int',\n 'highest_bid_size' => 'string',\n 'number_of_bids' => 'int',\n 'annual_high' => 'int',\n 'annual_low' => 'int',\n 'deadstock_range_low' => 'int',\n 'deadstock_range_high' => 'int',\n 'volatility' => 'float',\n 'deadstock_sold' => 'int',\n 'price_premium' => 'float',\n 'average_deadstock_price' => 'int',\n 'last_sale' => 'int',\n 'last_sale_size' => 'string',\n 'sales_last72_hours' => 'int',\n 'change_value' => 'int',\n 'change_percentage' => 'float',\n 'abs_change_percentage' => 'float',\n 'total_dollars' => 'int',\n 'updated_at' => 'int',\n 'last_lowest_ask_time' => 'int',\n 'last_highest_bid_time' => 'int',\n 'last_sale_date' => 'string',\n 'created_at' => 'string',\n 'deadstock_sold_rank' => 'int',\n 'price_premium_rank' => 'int',\n 'average_deadstock_price_rank' => 'int',\n 'featured' => 'string'\n ];\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerFormats = [\n 'product_id' => null,\n 'sku_uuid' => null,\n 'product_uuid' => null,\n 'lowest_ask' => null,\n 'lowest_ask_size' => null,\n 'parent_lowest_ask' => null,\n 'number_of_asks' => null,\n 'sales_this_period' => null,\n 'sales_last_period' => null,\n 'highest_bid' => null,\n 'highest_bid_size' => null,\n 'number_of_bids' => null,\n 'annual_high' => null,\n 'annual_low' => null,\n 'deadstock_range_low' => null,\n 'deadstock_range_high' => null,\n 'volatility' => null,\n 'deadstock_sold' => null,\n 'price_premium' => null,\n 'average_deadstock_price' => null,\n 'last_sale' => null,\n 'last_sale_size' => null,\n 'sales_last72_hours' => null,\n 'change_value' => null,\n 'change_percentage' => null,\n 'abs_change_percentage' => null,\n 'total_dollars' => null,\n 'updated_at' => null,\n 'last_lowest_ask_time' => null,\n 'last_highest_bid_time' => null,\n 'last_sale_date' => null,\n 'created_at' => null,\n 'deadstock_sold_rank' => null,\n 'price_premium_rank' => null,\n 'average_deadstock_price_rank' => null,\n 'featured' => null\n ];\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerTypes()\n {\n return self::$swaggerTypes;\n }\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerFormats()\n {\n return self::$swaggerFormats;\n }\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @var string[]\n */\n protected static $attributeMap = [\n 'product_id' => 'productId',\n 'sku_uuid' => 'skuUuid',\n 'product_uuid' => 'productUuid',\n 'lowest_ask' => 'lowestAsk',\n 'lowest_ask_size' => 'lowestAskSize',\n 'parent_lowest_ask' => 'parentLowestAsk',\n 'number_of_asks' => 'numberOfAsks',\n 'sales_this_period' => 'salesThisPeriod',\n 'sales_last_period' => 'salesLastPeriod',\n 'highest_bid' => 'highestBid',\n 'highest_bid_size' => 'highestBidSize',\n 'number_of_bids' => 'numberOfBids',\n 'annual_high' => 'annualHigh',\n 'annual_low' => 'annualLow',\n 'deadstock_range_low' => 'deadstockRangeLow',\n 'deadstock_range_high' => 'deadstockRangeHigh',\n 'volatility' => 'volatility',\n 'deadstock_sold' => 'deadstockSold',\n 'price_premium' => 'pricePremium',\n 'average_deadstock_price' => 'averageDeadstockPrice',\n 'last_sale' => 'lastSale',\n 'last_sale_size' => 'lastSaleSize',\n 'sales_last72_hours' => 'salesLast72Hours',\n 'change_value' => 'changeValue',\n 'change_percentage' => 'changePercentage',\n 'abs_change_percentage' => 'absChangePercentage',\n 'total_dollars' => 'totalDollars',\n 'updated_at' => 'updatedAt',\n 'last_lowest_ask_time' => 'lastLowestAskTime',\n 'last_highest_bid_time' => 'lastHighestBidTime',\n 'last_sale_date' => 'lastSaleDate',\n 'created_at' => 'createdAt',\n 'deadstock_sold_rank' => 'deadstockSoldRank',\n 'price_premium_rank' => 'pricePremiumRank',\n 'average_deadstock_price_rank' => 'averageDeadstockPriceRank',\n 'featured' => 'featured'\n ];\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @var string[]\n */\n protected static $setters = [\n 'product_id' => 'setProductId',\n 'sku_uuid' => 'setSkuUuid',\n 'product_uuid' => 'setProductUuid',\n 'lowest_ask' => 'setLowestAsk',\n 'lowest_ask_size' => 'setLowestAskSize',\n 'parent_lowest_ask' => 'setParentLowestAsk',\n 'number_of_asks' => 'setNumberOfAsks',\n 'sales_this_period' => 'setSalesThisPeriod',\n 'sales_last_period' => 'setSalesLastPeriod',\n 'highest_bid' => 'setHighestBid',\n 'highest_bid_size' => 'setHighestBidSize',\n 'number_of_bids' => 'setNumberOfBids',\n 'annual_high' => 'setAnnualHigh',\n 'annual_low' => 'setAnnualLow',\n 'deadstock_range_low' => 'setDeadstockRangeLow',\n 'deadstock_range_high' => 'setDeadstockRangeHigh',\n 'volatility' => 'setVolatility',\n 'deadstock_sold' => 'setDeadstockSold',\n 'price_premium' => 'setPricePremium',\n 'average_deadstock_price' => 'setAverageDeadstockPrice',\n 'last_sale' => 'setLastSale',\n 'last_sale_size' => 'setLastSaleSize',\n 'sales_last72_hours' => 'setSalesLast72Hours',\n 'change_value' => 'setChangeValue',\n 'change_percentage' => 'setChangePercentage',\n 'abs_change_percentage' => 'setAbsChangePercentage',\n 'total_dollars' => 'setTotalDollars',\n 'updated_at' => 'setUpdatedAt',\n 'last_lowest_ask_time' => 'setLastLowestAskTime',\n 'last_highest_bid_time' => 'setLastHighestBidTime',\n 'last_sale_date' => 'setLastSaleDate',\n 'created_at' => 'setCreatedAt',\n 'deadstock_sold_rank' => 'setDeadstockSoldRank',\n 'price_premium_rank' => 'setPricePremiumRank',\n 'average_deadstock_price_rank' => 'setAverageDeadstockPriceRank',\n 'featured' => 'setFeatured'\n ];\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @var string[]\n */\n protected static $getters = [\n 'product_id' => 'getProductId',\n 'sku_uuid' => 'getSkuUuid',\n 'product_uuid' => 'getProductUuid',\n 'lowest_ask' => 'getLowestAsk',\n 'lowest_ask_size' => 'getLowestAskSize',\n 'parent_lowest_ask' => 'getParentLowestAsk',\n 'number_of_asks' => 'getNumberOfAsks',\n 'sales_this_period' => 'getSalesThisPeriod',\n 'sales_last_period' => 'getSalesLastPeriod',\n 'highest_bid' => 'getHighestBid',\n 'highest_bid_size' => 'getHighestBidSize',\n 'number_of_bids' => 'getNumberOfBids',\n 'annual_high' => 'getAnnualHigh',\n 'annual_low' => 'getAnnualLow',\n 'deadstock_range_low' => 'getDeadstockRangeLow',\n 'deadstock_range_high' => 'getDeadstockRangeHigh',\n 'volatility' => 'getVolatility',\n 'deadstock_sold' => 'getDeadstockSold',\n 'price_premium' => 'getPricePremium',\n 'average_deadstock_price' => 'getAverageDeadstockPrice',\n 'last_sale' => 'getLastSale',\n 'last_sale_size' => 'getLastSaleSize',\n 'sales_last72_hours' => 'getSalesLast72Hours',\n 'change_value' => 'getChangeValue',\n 'change_percentage' => 'getChangePercentage',\n 'abs_change_percentage' => 'getAbsChangePercentage',\n 'total_dollars' => 'getTotalDollars',\n 'updated_at' => 'getUpdatedAt',\n 'last_lowest_ask_time' => 'getLastLowestAskTime',\n 'last_highest_bid_time' => 'getLastHighestBidTime',\n 'last_sale_date' => 'getLastSaleDate',\n 'created_at' => 'getCreatedAt',\n 'deadstock_sold_rank' => 'getDeadstockSoldRank',\n 'price_premium_rank' => 'getPricePremiumRank',\n 'average_deadstock_price_rank' => 'getAverageDeadstockPriceRank',\n 'featured' => 'getFeatured'\n ];\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @return array\n */\n public static function attributeMap()\n {\n return self::$attributeMap;\n }\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @return array\n */\n public static function setters()\n {\n return self::$setters;\n }\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @return array\n */\n public static function getters()\n {\n return self::$getters;\n }\n\n /**\n * The original name of the model.\n *\n * @return string\n */\n public function getModelName()\n {\n return self::$swaggerModelName;\n }\n\n \n\n \n\n /**\n * Associative array for storing property values\n *\n * @var mixed[]\n */\n protected $container = [];\n\n /**\n * Constructor\n *\n * @param mixed[] $data Associated array of property values\n * initializing the model\n */\n public function __construct(array $data = null)\n {\n $this->container['product_id'] = isset($data['product_id']) ? $data['product_id'] : null;\n $this->container['sku_uuid'] = isset($data['sku_uuid']) ? $data['sku_uuid'] : null;\n $this->container['product_uuid'] = isset($data['product_uuid']) ? $data['product_uuid'] : null;\n $this->container['lowest_ask'] = isset($data['lowest_ask']) ? $data['lowest_ask'] : null;\n $this->container['lowest_ask_size'] = isset($data['lowest_ask_size']) ? $data['lowest_ask_size'] : null;\n $this->container['parent_lowest_ask'] = isset($data['parent_lowest_ask']) ? $data['parent_lowest_ask'] : null;\n $this->container['number_of_asks'] = isset($data['number_of_asks']) ? $data['number_of_asks'] : null;\n $this->container['sales_this_period'] = isset($data['sales_this_period']) ? $data['sales_this_period'] : null;\n $this->container['sales_last_period'] = isset($data['sales_last_period']) ? $data['sales_last_period'] : null;\n $this->container['highest_bid'] = isset($data['highest_bid']) ? $data['highest_bid'] : null;\n $this->container['highest_bid_size'] = isset($data['highest_bid_size']) ? $data['highest_bid_size'] : null;\n $this->container['number_of_bids'] = isset($data['number_of_bids']) ? $data['number_of_bids'] : null;\n $this->container['annual_high'] = isset($data['annual_high']) ? $data['annual_high'] : null;\n $this->container['annual_low'] = isset($data['annual_low']) ? $data['annual_low'] : null;\n $this->container['deadstock_range_low'] = isset($data['deadstock_range_low']) ? $data['deadstock_range_low'] : null;\n $this->container['deadstock_range_high'] = isset($data['deadstock_range_high']) ? $data['deadstock_range_high'] : null;\n $this->container['volatility'] = isset($data['volatility']) ? $data['volatility'] : null;\n $this->container['deadstock_sold'] = isset($data['deadstock_sold']) ? $data['deadstock_sold'] : null;\n $this->container['price_premium'] = isset($data['price_premium']) ? $data['price_premium'] : null;\n $this->container['average_deadstock_price'] = isset($data['average_deadstock_price']) ? $data['average_deadstock_price'] : null;\n $this->container['last_sale'] = isset($data['last_sale']) ? $data['last_sale'] : null;\n $this->container['last_sale_size'] = isset($data['last_sale_size']) ? $data['last_sale_size'] : null;\n $this->container['sales_last72_hours'] = isset($data['sales_last72_hours']) ? $data['sales_last72_hours'] : null;\n $this->container['change_value'] = isset($data['change_value']) ? $data['change_value'] : null;\n $this->container['change_percentage'] = isset($data['change_percentage']) ? $data['change_percentage'] : null;\n $this->container['abs_change_percentage'] = isset($data['abs_change_percentage']) ? $data['abs_change_percentage'] : null;\n $this->container['total_dollars'] = isset($data['total_dollars']) ? $data['total_dollars'] : null;\n $this->container['updated_at'] = isset($data['updated_at']) ? $data['updated_at'] : null;\n $this->container['last_lowest_ask_time'] = isset($data['last_lowest_ask_time']) ? $data['last_lowest_ask_time'] : null;\n $this->container['last_highest_bid_time'] = isset($data['last_highest_bid_time']) ? $data['last_highest_bid_time'] : null;\n $this->container['last_sale_date'] = isset($data['last_sale_date']) ? $data['last_sale_date'] : null;\n $this->container['created_at'] = isset($data['created_at']) ? $data['created_at'] : null;\n $this->container['deadstock_sold_rank'] = isset($data['deadstock_sold_rank']) ? $data['deadstock_sold_rank'] : null;\n $this->container['price_premium_rank'] = isset($data['price_premium_rank']) ? $data['price_premium_rank'] : null;\n $this->container['average_deadstock_price_rank'] = isset($data['average_deadstock_price_rank']) ? $data['average_deadstock_price_rank'] : null;\n $this->container['featured'] = isset($data['featured']) ? $data['featured'] : null;\n }\n\n /**\n * Show all the invalid properties with reasons.\n *\n * @return array invalid properties with reasons\n */\n public function listInvalidProperties()\n {\n $invalidProperties = [];\n\n return $invalidProperties;\n }\n\n /**\n * Validate all the properties in the model\n * return true if all passed\n *\n * @return bool True if all properties are valid\n */\n public function valid()\n {\n\n return true;\n }\n\n\n /**\n * Gets product_id\n *\n * @return int\n */\n public function getProductId()\n {\n return $this->container['product_id'];\n }\n\n /**\n * Sets product_id\n *\n * @param int $product_id product_id\n *\n * @return $this\n */\n public function setProductId($product_id)\n {\n $this->container['product_id'] = $product_id;\n\n return $this;\n }\n\n /**\n * Gets sku_uuid\n *\n * @return string\n */\n public function getSkuUuid()\n {\n return $this->container['sku_uuid'];\n }\n\n /**\n * Sets sku_uuid\n *\n * @param string $sku_uuid sku_uuid\n *\n * @return $this\n */\n public function setSkuUuid($sku_uuid)\n {\n $this->container['sku_uuid'] = $sku_uuid;\n\n return $this;\n }\n\n /**\n * Gets product_uuid\n *\n * @return string\n */\n public function getProductUuid()\n {\n return $this->container['product_uuid'];\n }\n\n /**\n * Sets product_uuid\n *\n * @param string $product_uuid product_uuid\n *\n * @return $this\n */\n public function setProductUuid($product_uuid)\n {\n $this->container['product_uuid'] = $product_uuid;\n\n return $this;\n }\n\n /**\n * Gets lowest_ask\n *\n * @return int\n */\n public function getLowestAsk()\n {\n return $this->container['lowest_ask'];\n }\n\n /**\n * Sets lowest_ask\n *\n * @param int $lowest_ask lowest_ask\n *\n * @return $this\n */\n public function setLowestAsk($lowest_ask)\n {\n $this->container['lowest_ask'] = $lowest_ask;\n\n return $this;\n }\n\n /**\n * Gets lowest_ask_size\n *\n * @return string\n */\n public function getLowestAskSize()\n {\n return $this->container['lowest_ask_size'];\n }\n\n /**\n * Sets lowest_ask_size\n *\n * @param string $lowest_ask_size lowest_ask_size\n *\n * @return $this\n */\n public function setLowestAskSize($lowest_ask_size)\n {\n $this->container['lowest_ask_size'] = $lowest_ask_size;\n\n return $this;\n }\n\n /**\n * Gets parent_lowest_ask\n *\n * @return int\n */\n public function getParentLowestAsk()\n {\n return $this->container['parent_lowest_ask'];\n }\n\n /**\n * Sets parent_lowest_ask\n *\n * @param int $parent_lowest_ask parent_lowest_ask\n *\n * @return $this\n */\n public function setParentLowestAsk($parent_lowest_ask)\n {\n $this->container['parent_lowest_ask'] = $parent_lowest_ask;\n\n return $this;\n }\n\n /**\n * Gets number_of_asks\n *\n * @return int\n */\n public function getNumberOfAsks()\n {\n return $this->container['number_of_asks'];\n }\n\n /**\n * Sets number_of_asks\n *\n * @param int $number_of_asks number_of_asks\n *\n * @return $this\n */\n public function setNumberOfAsks($number_of_asks)\n {\n $this->container['number_of_asks'] = $number_of_asks;\n\n return $this;\n }\n\n /**\n * Gets sales_this_period\n *\n * @return int\n */\n public function getSalesThisPeriod()\n {\n return $this->container['sales_this_period'];\n }\n\n /**\n * Sets sales_this_period\n *\n * @param int $sales_this_period sales_this_period\n *\n * @return $this\n */\n public function setSalesThisPeriod($sales_this_period)\n {\n $this->container['sales_this_period'] = $sales_this_period;\n\n return $this;\n }\n\n /**\n * Gets sales_last_period\n *\n * @return int\n */\n public function getSalesLastPeriod()\n {\n return $this->container['sales_last_period'];\n }\n\n /**\n * Sets sales_last_period\n *\n * @param int $sales_last_period sales_last_period\n *\n * @return $this\n */\n public function setSalesLastPeriod($sales_last_period)\n {\n $this->container['sales_last_period'] = $sales_last_period;\n\n return $this;\n }\n\n /**\n * Gets highest_bid\n *\n * @return int\n */\n public function getHighestBid()\n {\n return $this->container['highest_bid'];\n }\n\n /**\n * Sets highest_bid\n *\n * @param int $highest_bid highest_bid\n *\n * @return $this\n */\n public function setHighestBid($highest_bid)\n {\n $this->container['highest_bid'] = $highest_bid;\n\n return $this;\n }\n\n /**\n * Gets highest_bid_size\n *\n * @return string\n */\n public function getHighestBidSize()\n {\n return $this->container['highest_bid_size'];\n }\n\n /**\n * Sets highest_bid_size\n *\n * @param string $highest_bid_size highest_bid_size\n *\n * @return $this\n */\n public function setHighestBidSize($highest_bid_size)\n {\n $this->container['highest_bid_size'] = $highest_bid_size;\n\n return $this;\n }\n\n /**\n * Gets number_of_bids\n *\n * @return int\n */\n public function getNumberOfBids()\n {\n return $this->container['number_of_bids'];\n }\n\n /**\n * Sets number_of_bids\n *\n * @param int $number_of_bids number_of_bids\n *\n * @return $this\n */\n public function setNumberOfBids($number_of_bids)\n {\n $this->container['number_of_bids'] = $number_of_bids;\n\n return $this;\n }\n\n /**\n * Gets annual_high\n *\n * @return int\n */\n public function getAnnualHigh()\n {\n return $this->container['annual_high'];\n }\n\n /**\n * Sets annual_high\n *\n * @param int $annual_high annual_high\n *\n * @return $this\n */\n public function setAnnualHigh($annual_high)\n {\n $this->container['annual_high'] = $annual_high;\n\n return $this;\n }\n\n /**\n * Gets annual_low\n *\n * @return int\n */\n public function getAnnualLow()\n {\n return $this->container['annual_low'];\n }\n\n /**\n * Sets annual_low\n *\n * @param int $annual_low annual_low\n *\n * @return $this\n */\n public function setAnnualLow($annual_low)\n {\n $this->container['annual_low'] = $annual_low;\n\n return $this;\n }\n\n /**\n * Gets deadstock_range_low\n *\n * @return int\n */\n public function getDeadstockRangeLow()\n {\n return $this->container['deadstock_range_low'];\n }\n\n /**\n * Sets deadstock_range_low\n *\n * @param int $deadstock_range_low deadstock_range_low\n *\n * @return $this\n */\n public function setDeadstockRangeLow($deadstock_range_low)\n {\n $this->container['deadstock_range_low'] = $deadstock_range_low;\n\n return $this;\n }\n\n /**\n * Gets deadstock_range_high\n *\n * @return int\n */\n public function getDeadstockRangeHigh()\n {\n return $this->container['deadstock_range_high'];\n }\n\n /**\n * Sets deadstock_range_high\n *\n * @param int $deadstock_range_high deadstock_range_high\n *\n * @return $this\n */\n public function setDeadstockRangeHigh($deadstock_range_high)\n {\n $this->container['deadstock_range_high'] = $deadstock_range_high;\n\n return $this;\n }\n\n /**\n * Gets volatility\n *\n * @return float\n */\n public function getVolatility()\n {\n return $this->container['volatility'];\n }\n\n /**\n * Sets volatility\n *\n * @param float $volatility volatility\n *\n * @return $this\n */\n public function setVolatility($volatility)\n {\n $this->container['volatility'] = $volatility;\n\n return $this;\n }\n\n /**\n * Gets deadstock_sold\n *\n * @return int\n */\n public function getDeadstockSold()\n {\n return $this->container['deadstock_sold'];\n }\n\n /**\n * Sets deadstock_sold\n *\n * @param int $deadstock_sold deadstock_sold\n *\n * @return $this\n */\n public function setDeadstockSold($deadstock_sold)\n {\n $this->container['deadstock_sold'] = $deadstock_sold;\n\n return $this;\n }\n\n /**\n * Gets price_premium\n *\n * @return float\n */\n public function getPricePremium()\n {\n return $this->container['price_premium'];\n }\n\n /**\n * Sets price_premium\n *\n * @param float $price_premium price_premium\n *\n * @return $this\n */\n public function setPricePremium($price_premium)\n {\n $this->container['price_premium'] = $price_premium;\n\n return $this;\n }\n\n /**\n * Gets average_deadstock_price\n *\n * @return int\n */\n public function getAverageDeadstockPrice()\n {\n return $this->container['average_deadstock_price'];\n }\n\n /**\n * Sets average_deadstock_price\n *\n * @param int $average_deadstock_price average_deadstock_price\n *\n * @return $this\n */\n public function setAverageDeadstockPrice($average_deadstock_price)\n {\n $this->container['average_deadstock_price'] = $average_deadstock_price;\n\n return $this;\n }\n\n /**\n * Gets last_sale\n *\n * @return int\n */\n public function getLastSale()\n {\n return $this->container['last_sale'];\n }\n\n /**\n * Sets last_sale\n *\n * @param int $last_sale last_sale\n *\n * @return $this\n */\n public function setLastSale($last_sale)\n {\n $this->container['last_sale'] = $last_sale;\n\n return $this;\n }\n\n /**\n * Gets last_sale_size\n *\n * @return string\n */\n public function getLastSaleSize()\n {\n return $this->container['last_sale_size'];\n }\n\n /**\n * Sets last_sale_size\n *\n * @param string $last_sale_size last_sale_size\n *\n * @return $this\n */\n public function setLastSaleSize($last_sale_size)\n {\n $this->container['last_sale_size'] = $last_sale_size;\n\n return $this;\n }\n\n /**\n * Gets sales_last72_hours\n *\n * @return int\n */\n public function getSalesLast72Hours()\n {\n return $this->container['sales_last72_hours'];\n }\n\n /**\n * Sets sales_last72_hours\n *\n * @param int $sales_last72_hours sales_last72_hours\n *\n * @return $this\n */\n public function setSalesLast72Hours($sales_last72_hours)\n {\n $this->container['sales_last72_hours'] = $sales_last72_hours;\n\n return $this;\n }\n\n /**\n * Gets change_value\n *\n * @return int\n */\n public function getChangeValue()\n {\n return $this->container['change_value'];\n }\n\n /**\n * Sets change_value\n *\n * @param int $change_value change_value\n *\n * @return $this\n */\n public function setChangeValue($change_value)\n {\n $this->container['change_value'] = $change_value;\n\n return $this;\n }\n\n /**\n * Gets change_percentage\n *\n * @return float\n */\n public function getChangePercentage()\n {\n return $this->container['change_percentage'];\n }\n\n /**\n * Sets change_percentage\n *\n * @param float $change_percentage change_percentage\n *\n * @return $this\n */\n public function setChangePercentage($change_percentage)\n {\n $this->container['change_percentage'] = $change_percentage;\n\n return $this;\n }\n\n /**\n * Gets abs_change_percentage\n *\n * @return float\n */\n public function getAbsChangePercentage()\n {\n return $this->container['abs_change_percentage'];\n }\n\n /**\n * Sets abs_change_percentage\n *\n * @param float $abs_change_percentage abs_change_percentage\n *\n * @return $this\n */\n public function setAbsChangePercentage($abs_change_percentage)\n {\n $this->container['abs_change_percentage'] = $abs_change_percentage;\n\n return $this;\n }\n\n /**\n * Gets total_dollars\n *\n * @return int\n */\n public function getTotalDollars()\n {\n return $this->container['total_dollars'];\n }\n\n /**\n * Sets total_dollars\n *\n * @param int $total_dollars total_dollars\n *\n * @return $this\n */\n public function setTotalDollars($total_dollars)\n {\n $this->container['total_dollars'] = $total_dollars;\n\n return $this;\n }\n\n /**\n * Gets updated_at\n *\n * @return int\n */\n public function getUpdatedAt()\n {\n return $this->container['updated_at'];\n }\n\n /**\n * Sets updated_at\n *\n * @param int $updated_at updated_at\n *\n * @return $this\n */\n public function setUpdatedAt($updated_at)\n {\n $this->container['updated_at'] = $updated_at;\n\n return $this;\n }\n\n /**\n * Gets last_lowest_ask_time\n *\n * @return int\n */\n public function getLastLowestAskTime()\n {\n return $this->container['last_lowest_ask_time'];\n }\n\n /**\n * Sets last_lowest_ask_time\n *\n * @param int $last_lowest_ask_time last_lowest_ask_time\n *\n * @return $this\n */\n public function setLastLowestAskTime($last_lowest_ask_time)\n {\n $this->container['last_lowest_ask_time'] = $last_lowest_ask_time;\n\n return $this;\n }\n\n /**\n * Gets last_highest_bid_time\n *\n * @return int\n */\n public function getLastHighestBidTime()\n {\n return $this->container['last_highest_bid_time'];\n }\n\n /**\n * Sets last_highest_bid_time\n *\n * @param int $last_highest_bid_time last_highest_bid_time\n *\n * @return $this\n */\n public function setLastHighestBidTime($last_highest_bid_time)\n {\n $this->container['last_highest_bid_time'] = $last_highest_bid_time;\n\n return $this;\n }\n\n /**\n * Gets last_sale_date\n *\n * @return string\n */\n public function getLastSaleDate()\n {\n return $this->container['last_sale_date'];\n }\n\n /**\n * Sets last_sale_date\n *\n * @param string $last_sale_date last_sale_date\n *\n * @return $this\n */\n public function setLastSaleDate($last_sale_date)\n {\n $this->container['last_sale_date'] = $last_sale_date;\n\n return $this;\n }\n\n /**\n * Gets created_at\n *\n * @return string\n */\n public function getCreatedAt()\n {\n return $this->container['created_at'];\n }\n\n /**\n * Sets created_at\n *\n * @param string $created_at created_at\n *\n * @return $this\n */\n public function setCreatedAt($created_at)\n {\n $this->container['created_at'] = $created_at;\n\n return $this;\n }\n\n /**\n * Gets deadstock_sold_rank\n *\n * @return int\n */\n public function getDeadstockSoldRank()\n {\n return $this->container['deadstock_sold_rank'];\n }\n\n /**\n * Sets deadstock_sold_rank\n *\n * @param int $deadstock_sold_rank deadstock_sold_rank\n *\n * @return $this\n */\n public function setDeadstockSoldRank($deadstock_sold_rank)\n {\n $this->container['deadstock_sold_rank'] = $deadstock_sold_rank;\n\n return $this;\n }\n\n /**\n * Gets price_premium_rank\n *\n * @return int\n */\n public function getPricePremiumRank()\n {\n return $this->container['price_premium_rank'];\n }\n\n /**\n * Sets price_premium_rank\n *\n * @param int $price_premium_rank price_premium_rank\n *\n * @return $this\n */\n public function setPricePremiumRank($price_premium_rank)\n {\n $this->container['price_premium_rank'] = $price_premium_rank;\n\n return $this;\n }\n\n /**\n * Gets average_deadstock_price_rank\n *\n * @return int\n */\n public function getAverageDeadstockPriceRank()\n {\n return $this->container['average_deadstock_price_rank'];\n }\n\n /**\n * Sets average_deadstock_price_rank\n *\n * @param int $average_deadstock_price_rank average_deadstock_price_rank\n *\n * @return $this\n */\n public function setAverageDeadstockPriceRank($average_deadstock_price_rank)\n {\n $this->container['average_deadstock_price_rank'] = $average_deadstock_price_rank;\n\n return $this;\n }\n\n /**\n * Gets featured\n *\n * @return string\n */\n public function getFeatured()\n {\n return $this->container['featured'];\n }\n\n /**\n * Sets featured\n *\n * @param string $featured featured\n *\n * @return $this\n */\n public function setFeatured($featured)\n {\n $this->container['featured'] = $featured;\n\n return $this;\n }\n /**\n * Returns true if offset exists. False otherwise.\n *\n * @param integer $offset Offset\n *\n * @return boolean\n */\n public function offsetExists($offset)\n {\n return isset($this->container[$offset]);\n }\n\n /**\n * Gets offset.\n *\n * @param integer $offset Offset\n *\n * @return mixed\n */\n public function offsetGet($offset)\n {\n return isset($this->container[$offset]) ? $this->container[$offset] : null;\n }\n\n /**\n * Sets value based on offset.\n *\n * @param integer $offset Offset\n * @param mixed $value Value to be set\n *\n * @return void\n */\n public function offsetSet($offset, $value)\n {\n if (is_null($offset)) {\n $this->container[] = $value;\n } else {\n $this->container[$offset] = $value;\n }\n }\n\n /**\n * Unsets offset.\n *\n * @param integer $offset Offset\n *\n * @return void\n */\n public function offsetUnset($offset)\n {\n unset($this->container[$offset]);\n }\n\n /**\n * Gets the string presentation of the object\n *\n * @return string\n */\n public function __toString()\n {\n if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print\n return json_encode(\n ObjectSerializer::sanitizeForSerialization($this),\n JSON_PRETTY_PRINT\n );\n }\n\n return json_encode(ObjectSerializer::sanitizeForSerialization($this));\n }\n}\n\n\n" }, { "alpha_fraction": 0.5643353462219238, "alphanum_fraction": 0.5777852535247803, "avg_line_length": 26.881250381469727, "blob_id": "7f5839c713085dab3006abf2bc22beae07b554d8", "content_id": "a0fcf9e0ed524fd894c6175d66b05e33489e424a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8922, "license_type": "no_license", "max_line_length": 202, "num_lines": 320, "path": "/sdk/python/lib/io_stockx/models/address_object.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass AddressObject(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'first_name': 'str',\n 'last_name': 'str',\n 'telephone': 'str',\n 'street_address': 'str',\n 'extended_address': 'str',\n 'locality': 'str',\n 'region': 'str',\n 'postal_code': 'str',\n 'country_code_alpha2': 'str'\n }\n\n attribute_map = {\n 'first_name': 'firstName',\n 'last_name': 'lastName',\n 'telephone': 'telephone',\n 'street_address': 'streetAddress',\n 'extended_address': 'extendedAddress',\n 'locality': 'locality',\n 'region': 'region',\n 'postal_code': 'postalCode',\n 'country_code_alpha2': 'countryCodeAlpha2'\n }\n\n def __init__(self, first_name=None, last_name=None, telephone=None, street_address=None, extended_address=None, locality=None, region=None, postal_code=None, country_code_alpha2=None): # noqa: E501\n \"\"\"AddressObject - a model defined in Swagger\"\"\" # noqa: E501\n\n self._first_name = None\n self._last_name = None\n self._telephone = None\n self._street_address = None\n self._extended_address = None\n self._locality = None\n self._region = None\n self._postal_code = None\n self._country_code_alpha2 = None\n self.discriminator = None\n\n if first_name is not None:\n self.first_name = first_name\n if last_name is not None:\n self.last_name = last_name\n if telephone is not None:\n self.telephone = telephone\n if street_address is not None:\n self.street_address = street_address\n if extended_address is not None:\n self.extended_address = extended_address\n if locality is not None:\n self.locality = locality\n if region is not None:\n self.region = region\n if postal_code is not None:\n self.postal_code = postal_code\n if country_code_alpha2 is not None:\n self.country_code_alpha2 = country_code_alpha2\n\n @property\n def first_name(self):\n \"\"\"Gets the first_name of this AddressObject. # noqa: E501\n\n\n :return: The first_name of this AddressObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._first_name\n\n @first_name.setter\n def first_name(self, first_name):\n \"\"\"Sets the first_name of this AddressObject.\n\n\n :param first_name: The first_name of this AddressObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._first_name = first_name\n\n @property\n def last_name(self):\n \"\"\"Gets the last_name of this AddressObject. # noqa: E501\n\n\n :return: The last_name of this AddressObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._last_name\n\n @last_name.setter\n def last_name(self, last_name):\n \"\"\"Sets the last_name of this AddressObject.\n\n\n :param last_name: The last_name of this AddressObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._last_name = last_name\n\n @property\n def telephone(self):\n \"\"\"Gets the telephone of this AddressObject. # noqa: E501\n\n\n :return: The telephone of this AddressObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._telephone\n\n @telephone.setter\n def telephone(self, telephone):\n \"\"\"Sets the telephone of this AddressObject.\n\n\n :param telephone: The telephone of this AddressObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._telephone = telephone\n\n @property\n def street_address(self):\n \"\"\"Gets the street_address of this AddressObject. # noqa: E501\n\n\n :return: The street_address of this AddressObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._street_address\n\n @street_address.setter\n def street_address(self, street_address):\n \"\"\"Sets the street_address of this AddressObject.\n\n\n :param street_address: The street_address of this AddressObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._street_address = street_address\n\n @property\n def extended_address(self):\n \"\"\"Gets the extended_address of this AddressObject. # noqa: E501\n\n\n :return: The extended_address of this AddressObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._extended_address\n\n @extended_address.setter\n def extended_address(self, extended_address):\n \"\"\"Sets the extended_address of this AddressObject.\n\n\n :param extended_address: The extended_address of this AddressObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._extended_address = extended_address\n\n @property\n def locality(self):\n \"\"\"Gets the locality of this AddressObject. # noqa: E501\n\n\n :return: The locality of this AddressObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._locality\n\n @locality.setter\n def locality(self, locality):\n \"\"\"Sets the locality of this AddressObject.\n\n\n :param locality: The locality of this AddressObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._locality = locality\n\n @property\n def region(self):\n \"\"\"Gets the region of this AddressObject. # noqa: E501\n\n\n :return: The region of this AddressObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._region\n\n @region.setter\n def region(self, region):\n \"\"\"Sets the region of this AddressObject.\n\n\n :param region: The region of this AddressObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._region = region\n\n @property\n def postal_code(self):\n \"\"\"Gets the postal_code of this AddressObject. # noqa: E501\n\n\n :return: The postal_code of this AddressObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._postal_code\n\n @postal_code.setter\n def postal_code(self, postal_code):\n \"\"\"Sets the postal_code of this AddressObject.\n\n\n :param postal_code: The postal_code of this AddressObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._postal_code = postal_code\n\n @property\n def country_code_alpha2(self):\n \"\"\"Gets the country_code_alpha2 of this AddressObject. # noqa: E501\n\n\n :return: The country_code_alpha2 of this AddressObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._country_code_alpha2\n\n @country_code_alpha2.setter\n def country_code_alpha2(self, country_code_alpha2):\n \"\"\"Sets the country_code_alpha2 of this AddressObject.\n\n\n :param country_code_alpha2: The country_code_alpha2 of this AddressObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._country_code_alpha2 = country_code_alpha2\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, AddressObject):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.5730298757553101, "alphanum_fraction": 0.584578812122345, "avg_line_length": 20.489051818847656, "blob_id": "0d755536e1d4012e6b67f5261f9c1137ad6616d5", "content_id": "411f994fa5351bd7016fe7753d44bb985c65009c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2944, "license_type": "no_license", "max_line_length": 176, "num_lines": 137, "path": "/sdk/python/lib/test/test_stock_x_api.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nfrom __future__ import absolute_import\n\nimport unittest\n\nimport io_stockx\nfrom io_stockx.api.stock_x_api import StockXApi # noqa: E501\nfrom io_stockx.rest import ApiException\n\n\nclass TestStockXApi(unittest.TestCase):\n \"\"\"StockXApi unit test stubs\"\"\"\n\n def setUp(self):\n self.api = io_stockx.api.stock_x_api.StockXApi() # noqa: E501\n\n def tearDown(self):\n pass\n\n def test_delete_portfolio(self):\n \"\"\"Test case for delete_portfolio\n\n Deletes a portfolio item from the market with the specified id. # noqa: E501\n \"\"\"\n pass\n\n def test_delete_webhook(self):\n \"\"\"Test case for delete_webhook\n\n \"\"\"\n pass\n\n def test_get_open_orders(self):\n \"\"\"Test case for get_open_orders\n\n \"\"\"\n pass\n\n def test_get_portfolio(self):\n \"\"\"Test case for get_portfolio\n\n Returns a market portfolio identified by request parameters. # noqa: E501\n \"\"\"\n pass\n\n def test_get_portfolio_item(self):\n \"\"\"Test case for get_portfolio_item\n\n \"\"\"\n pass\n\n def test_get_product_by_id(self):\n \"\"\"Test case for get_product_by_id\n\n \"\"\"\n pass\n\n def test_get_product_market_data(self):\n \"\"\"Test case for get_product_market_data\n\n Provides historical market data for a given product. # noqa: E501\n \"\"\"\n pass\n\n def test_get_subscriptions(self):\n \"\"\"Test case for get_subscriptions\n\n \"\"\"\n pass\n\n def test_get_webhook(self):\n \"\"\"Test case for get_webhook\n\n \"\"\"\n pass\n\n def test_get_webhooks(self):\n \"\"\"Test case for get_webhooks\n\n \"\"\"\n pass\n\n def test_login(self):\n \"\"\"Test case for login\n\n Attempts to log the user in with a username and password. # noqa: E501\n \"\"\"\n pass\n\n def test_lookup_product(self):\n \"\"\"Test case for lookup_product\n\n \"\"\"\n pass\n\n def test_new_portfolio_ask(self):\n \"\"\"Test case for new_portfolio_ask\n\n Creates a new seller ask on the market for a given product. # noqa: E501\n \"\"\"\n pass\n\n def test_new_portfolio_bid(self):\n \"\"\"Test case for new_portfolio_bid\n\n Creates a new buyer bid on the market for a given product. # noqa: E501\n \"\"\"\n pass\n\n def test_post_webhooks(self):\n \"\"\"Test case for post_webhooks\n\n \"\"\"\n pass\n\n def test_search(self):\n \"\"\"Test case for search\n\n Searches for products by keyword. # noqa: E501\n \"\"\"\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.5675238370895386, "alphanum_fraction": 0.5693220496177673, "avg_line_length": 15.800603866577148, "blob_id": "8e38866c70a39812a80cd529353fdcee96f67c51", "content_id": "015f7955cfbccf58bfd5f03c84ba2bbe9b568091", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5561, "license_type": "no_license", "max_line_length": 110, "num_lines": 331, "path": "/sdk/php/StockX-SDK-PHP/lib/test/Model/CustomerObjectTest.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * CustomerObjectTest\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Please update the test case below to test the model.\n */\n\nnamespace StockX\\Client;\n\n/**\n * CustomerObjectTest Class Doc Comment\n *\n * @category Class */\n// * @description CustomerObject\n/**\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass CustomerObjectTest extends \\PHPUnit_Framework_TestCase\n{\n\n /**\n * Setup before running any test case\n */\n public static function setUpBeforeClass()\n {\n }\n\n /**\n * Setup before running each test case\n */\n public function setUp()\n {\n }\n\n /**\n * Clean up after running each test case\n */\n public function tearDown()\n {\n }\n\n /**\n * Clean up after running all test cases\n */\n public static function tearDownAfterClass()\n {\n }\n\n /**\n * Test \"CustomerObject\"\n */\n public function testCustomerObject()\n {\n }\n\n /**\n * Test attribute \"id\"\n */\n public function testPropertyId()\n {\n }\n\n /**\n * Test attribute \"uuid\"\n */\n public function testPropertyUuid()\n {\n }\n\n /**\n * Test attribute \"first_name\"\n */\n public function testPropertyFirstName()\n {\n }\n\n /**\n * Test attribute \"last_name\"\n */\n public function testPropertyLastName()\n {\n }\n\n /**\n * Test attribute \"full_name\"\n */\n public function testPropertyFullName()\n {\n }\n\n /**\n * Test attribute \"email\"\n */\n public function testPropertyEmail()\n {\n }\n\n /**\n * Test attribute \"username\"\n */\n public function testPropertyUsername()\n {\n }\n\n /**\n * Test attribute \"email_verified\"\n */\n public function testPropertyEmailVerified()\n {\n }\n\n /**\n * Test attribute \"default_size\"\n */\n public function testPropertyDefaultSize()\n {\n }\n\n /**\n * Test attribute \"categories\"\n */\n public function testPropertyCategories()\n {\n }\n\n /**\n * Test attribute \"default_category\"\n */\n public function testPropertyDefaultCategory()\n {\n }\n\n /**\n * Test attribute \"vacation_date\"\n */\n public function testPropertyVacationDate()\n {\n }\n\n /**\n * Test attribute \"is_active\"\n */\n public function testPropertyIsActive()\n {\n }\n\n /**\n * Test attribute \"flagged\"\n */\n public function testPropertyFlagged()\n {\n }\n\n /**\n * Test attribute \"hide_portfolio_banner\"\n */\n public function testPropertyHidePortfolioBanner()\n {\n }\n\n /**\n * Test attribute \"refer_url\"\n */\n public function testPropertyReferUrl()\n {\n }\n\n /**\n * Test attribute \"created_at\"\n */\n public function testPropertyCreatedAt()\n {\n }\n\n /**\n * Test attribute \"created_at_time\"\n */\n public function testPropertyCreatedAtTime()\n {\n }\n\n /**\n * Test attribute \"is_trader\"\n */\n public function testPropertyIsTrader()\n {\n }\n\n /**\n * Test attribute \"ship_by_date\"\n */\n public function testPropertyShipByDate()\n {\n }\n\n /**\n * Test attribute \"is_buying\"\n */\n public function testPropertyIsBuying()\n {\n }\n\n /**\n * Test attribute \"is_selling\"\n */\n public function testPropertyIsSelling()\n {\n }\n\n /**\n * Test attribute \"billing\"\n */\n public function testPropertyBilling()\n {\n }\n\n /**\n * Test attribute \"shipping\"\n */\n public function testPropertyShipping()\n {\n }\n\n /**\n * Test attribute \"cc_only\"\n */\n public function testPropertyCcOnly()\n {\n }\n\n /**\n * Test attribute \"merchant\"\n */\n public function testPropertyMerchant()\n {\n }\n\n /**\n * Test attribute \"promotion_code\"\n */\n public function testPropertyPromotionCode()\n {\n }\n\n /**\n * Test attribute \"paypal_emails\"\n */\n public function testPropertyPaypalEmails()\n {\n }\n\n /**\n * Test attribute \"authorization_method\"\n */\n public function testPropertyAuthorizationMethod()\n {\n }\n\n /**\n * Test attribute \"security_override\"\n */\n public function testPropertySecurityOverride()\n {\n }\n\n /**\n * Test attribute \"team_member\"\n */\n public function testPropertyTeamMember()\n {\n }\n\n /**\n * Test attribute \"password_locked\"\n */\n public function testPropertyPasswordLocked()\n {\n }\n\n /**\n * Test attribute \"address_normalize_override\"\n */\n public function testPropertyAddressNormalizeOverride()\n {\n }\n\n /**\n * Test attribute \"early_payout_enabled\"\n */\n public function testPropertyEarlyPayoutEnabled()\n {\n }\n\n /**\n * Test attribute \"early_payout_eligible\"\n */\n public function testPropertyEarlyPayoutEligible()\n {\n }\n\n /**\n * Test attribute \"security\"\n */\n public function testPropertySecurity()\n {\n }\n}\n" }, { "alpha_fraction": 0.6161925792694092, "alphanum_fraction": 0.6205689311027527, "avg_line_length": 17.88429832458496, "blob_id": "99c8023fc361ebb15fe7a65fe2bb424f4b635b05", "content_id": "c175e6573ade439238c1254fa07a3e0c8ccae00d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2285, "license_type": "no_license", "max_line_length": 110, "num_lines": 121, "path": "/sdk/php/StockX-SDK-PHP/lib/test/Model/PortfolioRequestPortfolioItemTest.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * PortfolioRequestPortfolioItemTest\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Please update the test case below to test the model.\n */\n\nnamespace StockX\\Client;\n\n/**\n * PortfolioRequestPortfolioItemTest Class Doc Comment\n *\n * @category Class */\n// * @description PortfolioRequestPortfolioItem\n/**\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass PortfolioRequestPortfolioItemTest extends \\PHPUnit_Framework_TestCase\n{\n\n /**\n * Setup before running any test case\n */\n public static function setUpBeforeClass()\n {\n }\n\n /**\n * Setup before running each test case\n */\n public function setUp()\n {\n }\n\n /**\n * Clean up after running each test case\n */\n public function tearDown()\n {\n }\n\n /**\n * Clean up after running all test cases\n */\n public static function tearDownAfterClass()\n {\n }\n\n /**\n * Test \"PortfolioRequestPortfolioItem\"\n */\n public function testPortfolioRequestPortfolioItem()\n {\n }\n\n /**\n * Test attribute \"amount\"\n */\n public function testPropertyAmount()\n {\n }\n\n /**\n * Test attribute \"expires_at\"\n */\n public function testPropertyExpiresAt()\n {\n }\n\n /**\n * Test attribute \"matched_with_date\"\n */\n public function testPropertyMatchedWithDate()\n {\n }\n\n /**\n * Test attribute \"condition\"\n */\n public function testPropertyCondition()\n {\n }\n\n /**\n * Test attribute \"action\"\n */\n public function testPropertyAction()\n {\n }\n\n /**\n * Test attribute \"sku_uuid\"\n */\n public function testPropertySkuUuid()\n {\n }\n}\n" }, { "alpha_fraction": 0.537683367729187, "alphanum_fraction": 0.537683367729187, "avg_line_length": 40.14583206176758, "blob_id": "78e994b008c62ad501d23c247e12d0078fedbb31", "content_id": "87961bf5ae16458c59d99257e94998e0397bb457", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1977, "license_type": "no_license", "max_line_length": 161, "num_lines": 48, "path": "/sdk/python/lib/docs/PortfolioIdDelResponsePortfolioItemProduct.md", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# PortfolioIdDelResponsePortfolioItemProduct\n\n## Properties\nName | Type | Description | Notes\n------------ | ------------- | ------------- | -------------\n**id** | **str** | | \n**uuid** | **str** | | \n**brand** | **str** | | \n**category** | **str** | | \n**charity_condition** | **int** | | \n**colorway** | **str** | | \n**condition** | **str** | | \n**country_of_manufacture** | **str** | | \n**gender** | **str** | | \n**content_group** | **str** | | \n**minimum_bid** | **int** | | \n**media** | [**PortfolioIdDelResponsePortfolioItemProductMedia**](PortfolioIdDelResponsePortfolioItemProductMedia.md) | | \n**name** | **str** | | \n**primary_category** | **str** | | \n**secondary_category** | **str** | | \n**product_category** | **str** | | \n**release_date** | **str** | | \n**retail_price** | **int** | | \n**shoe** | **str** | | \n**short_description** | **str** | | \n**style_id** | **str** | | \n**ticker_symbol** | **str** | | \n**title** | **str** | | \n**data_type** | **str** | | \n**type** | **int** | | \n**size_title** | **str** | | \n**size_descriptor** | **str** | | \n**size_all_descriptor** | **str** | | \n**url_key** | **str** | | \n**year** | **str** | | \n**shipping_group** | **str** | | \n**a_lim** | **int** | | \n**meta** | [**PortfolioIdDelResponsePortfolioItemProductMeta**](PortfolioIdDelResponsePortfolioItemProductMeta.md) | | \n**shipping** | [**PortfolioIdDelResponsePortfolioItemProductShipping**](PortfolioIdDelResponsePortfolioItemProductShipping.md) | | \n**children** | **object** | | \n**parent_id** | **str** | | \n**parent_uuid** | **str** | | \n**size_sort_order** | **int** | | \n**shoe_size** | **str** | | \n**market** | [**PortfolioIdDelResponsePortfolioItemProductMarket**](PortfolioIdDelResponsePortfolioItemProductMarket.md) | | \n**upc** | **str** | | \n\n[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)\n\n\n" }, { "alpha_fraction": 0.6600384712219238, "alphanum_fraction": 0.6908274292945862, "avg_line_length": 32.91304397583008, "blob_id": "a57ab6d207f724e8c342dc522a4b61aad89ee6ae", "content_id": "156ee2d900e1819df4852954f246a3c143f51b99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1559, "license_type": "no_license", "max_line_length": 90, "num_lines": 46, "path": "/sdk/php/StockX-SDK-PHP/src/PortfolioBidExample.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n\nrequire_once(__DIR__ . '/../lib/vendor/autoload.php');\nrequire_once('LoginUtil.php');\nrequire_once('ExampleConstants.php');\nrequire_once('JWTHeaderSelector.php');\n\n$client = new GuzzleHttp\\Client();\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()\n->setApiKey('x-api-key', ExampleConstants::$AWS_API_KEY)\n->setHost(Environment::$ENDPOINT_STAGING);\n\n$headerSelector = new JWTHeaderSelector();\n\n$api = new StockX\\Client\\Api\\StockXApi(\n $client,\n $config,\n $headerSelector\n);\n\ntry {\n LoginUtil::login($api, $headerSelector,\n ExampleConstants::$STOCKX_USERNAME,\n ExampleConstants::$STOCKX_PASSWORD);\n \n $portfolioItemReq = new StockX\\Client\\Model\\PortfolioRequestPortfolioItem();\n $portfolioItemReq->setAmount(\"25\");\n $portfolioItemReq->setSkuUuid(\"bae25b67-a721-4f57-ad5a-79973c7d0a5c\");\n $portfolioItemReq->setMatchedWithDate(\"2018-12-12T05:00:00+0000\");\n $portfolioItemReq->setCondition(\"2000\");\n $portfolioItemReq->setAction(1000);\n \n $customer = new StockX\\Client\\Model\\CustomerObject();\n $customer->setDefaultSize(\"7\");\n \n $portfolioReq = new StockX\\Client\\Model\\PortfolioRequest();\n $portfolioReq->setPortfolioItem($portfolioItemReq);\n $portfolioReq->setCustomer($customer);\n $portfolioReq->setTimezone(\"America/Detroit\");\n \n $bidResp = $api->newPortfolioBid($portfolioReq);\n \n print_r($bidResp);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->newPortfolioBid: ', $e->getMessage(), PHP_EOL;\n}" }, { "alpha_fraction": 0.6004570126533508, "alphanum_fraction": 0.6126735806465149, "avg_line_length": 30.960674285888672, "blob_id": "4fc0ad957fae983a4a91a2a55d6a5b44c0d8d8b5", "content_id": "593cfc777adb5a7f24b42c5097c1a0a8826fc81d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11378, "license_type": "no_license", "max_line_length": 198, "num_lines": 356, "path": "/sdk/python/lib/io_stockx/models/portfolio_id_del_response_portfolio_item_merchant.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass PortfolioIdDelResponsePortfolioItemMerchant(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'id': 'int',\n 'customer_id': 'int',\n 'is_robot': 'int',\n 'name': 'str',\n 'paypal_email': 'str',\n 'take': 'float',\n 'created_at': 'str',\n 'created_at_time': 'int',\n 'updated_at': 'str',\n 'updated_at_time': 'int'\n }\n\n attribute_map = {\n 'id': 'id',\n 'customer_id': 'customerId',\n 'is_robot': 'isRobot',\n 'name': 'name',\n 'paypal_email': 'paypalEmail',\n 'take': 'take',\n 'created_at': 'createdAt',\n 'created_at_time': 'createdAtTime',\n 'updated_at': 'updatedAt',\n 'updated_at_time': 'updatedAtTime'\n }\n\n def __init__(self, id=None, customer_id=None, is_robot=None, name=None, paypal_email=None, take=None, created_at=None, created_at_time=None, updated_at=None, updated_at_time=None): # noqa: E501\n \"\"\"PortfolioIdDelResponsePortfolioItemMerchant - a model defined in Swagger\"\"\" # noqa: E501\n\n self._id = None\n self._customer_id = None\n self._is_robot = None\n self._name = None\n self._paypal_email = None\n self._take = None\n self._created_at = None\n self._created_at_time = None\n self._updated_at = None\n self._updated_at_time = None\n self.discriminator = None\n\n self.id = id\n self.customer_id = customer_id\n self.is_robot = is_robot\n self.name = name\n self.paypal_email = paypal_email\n self.take = take\n self.created_at = created_at\n self.created_at_time = created_at_time\n self.updated_at = updated_at\n self.updated_at_time = updated_at_time\n\n @property\n def id(self):\n \"\"\"Gets the id of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n\n\n :return: The id of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :rtype: int\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id):\n \"\"\"Sets the id of this PortfolioIdDelResponsePortfolioItemMerchant.\n\n\n :param id: The id of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :type: int\n \"\"\"\n if id is None:\n raise ValueError(\"Invalid value for `id`, must not be `None`\") # noqa: E501\n\n self._id = id\n\n @property\n def customer_id(self):\n \"\"\"Gets the customer_id of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n\n\n :return: The customer_id of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :rtype: int\n \"\"\"\n return self._customer_id\n\n @customer_id.setter\n def customer_id(self, customer_id):\n \"\"\"Sets the customer_id of this PortfolioIdDelResponsePortfolioItemMerchant.\n\n\n :param customer_id: The customer_id of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :type: int\n \"\"\"\n if customer_id is None:\n raise ValueError(\"Invalid value for `customer_id`, must not be `None`\") # noqa: E501\n\n self._customer_id = customer_id\n\n @property\n def is_robot(self):\n \"\"\"Gets the is_robot of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n\n\n :return: The is_robot of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :rtype: int\n \"\"\"\n return self._is_robot\n\n @is_robot.setter\n def is_robot(self, is_robot):\n \"\"\"Sets the is_robot of this PortfolioIdDelResponsePortfolioItemMerchant.\n\n\n :param is_robot: The is_robot of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :type: int\n \"\"\"\n if is_robot is None:\n raise ValueError(\"Invalid value for `is_robot`, must not be `None`\") # noqa: E501\n\n self._is_robot = is_robot\n\n @property\n def name(self):\n \"\"\"Gets the name of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n\n\n :return: The name of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this PortfolioIdDelResponsePortfolioItemMerchant.\n\n\n :param name: The name of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :type: str\n \"\"\"\n if name is None:\n raise ValueError(\"Invalid value for `name`, must not be `None`\") # noqa: E501\n\n self._name = name\n\n @property\n def paypal_email(self):\n \"\"\"Gets the paypal_email of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n\n\n :return: The paypal_email of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :rtype: str\n \"\"\"\n return self._paypal_email\n\n @paypal_email.setter\n def paypal_email(self, paypal_email):\n \"\"\"Sets the paypal_email of this PortfolioIdDelResponsePortfolioItemMerchant.\n\n\n :param paypal_email: The paypal_email of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :type: str\n \"\"\"\n if paypal_email is None:\n raise ValueError(\"Invalid value for `paypal_email`, must not be `None`\") # noqa: E501\n\n self._paypal_email = paypal_email\n\n @property\n def take(self):\n \"\"\"Gets the take of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n\n\n :return: The take of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :rtype: float\n \"\"\"\n return self._take\n\n @take.setter\n def take(self, take):\n \"\"\"Sets the take of this PortfolioIdDelResponsePortfolioItemMerchant.\n\n\n :param take: The take of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :type: float\n \"\"\"\n if take is None:\n raise ValueError(\"Invalid value for `take`, must not be `None`\") # noqa: E501\n\n self._take = take\n\n @property\n def created_at(self):\n \"\"\"Gets the created_at of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n\n\n :return: The created_at of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :rtype: str\n \"\"\"\n return self._created_at\n\n @created_at.setter\n def created_at(self, created_at):\n \"\"\"Sets the created_at of this PortfolioIdDelResponsePortfolioItemMerchant.\n\n\n :param created_at: The created_at of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :type: str\n \"\"\"\n if created_at is None:\n raise ValueError(\"Invalid value for `created_at`, must not be `None`\") # noqa: E501\n\n self._created_at = created_at\n\n @property\n def created_at_time(self):\n \"\"\"Gets the created_at_time of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n\n\n :return: The created_at_time of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :rtype: int\n \"\"\"\n return self._created_at_time\n\n @created_at_time.setter\n def created_at_time(self, created_at_time):\n \"\"\"Sets the created_at_time of this PortfolioIdDelResponsePortfolioItemMerchant.\n\n\n :param created_at_time: The created_at_time of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :type: int\n \"\"\"\n if created_at_time is None:\n raise ValueError(\"Invalid value for `created_at_time`, must not be `None`\") # noqa: E501\n\n self._created_at_time = created_at_time\n\n @property\n def updated_at(self):\n \"\"\"Gets the updated_at of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n\n\n :return: The updated_at of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :rtype: str\n \"\"\"\n return self._updated_at\n\n @updated_at.setter\n def updated_at(self, updated_at):\n \"\"\"Sets the updated_at of this PortfolioIdDelResponsePortfolioItemMerchant.\n\n\n :param updated_at: The updated_at of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :type: str\n \"\"\"\n if updated_at is None:\n raise ValueError(\"Invalid value for `updated_at`, must not be `None`\") # noqa: E501\n\n self._updated_at = updated_at\n\n @property\n def updated_at_time(self):\n \"\"\"Gets the updated_at_time of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n\n\n :return: The updated_at_time of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :rtype: int\n \"\"\"\n return self._updated_at_time\n\n @updated_at_time.setter\n def updated_at_time(self, updated_at_time):\n \"\"\"Sets the updated_at_time of this PortfolioIdDelResponsePortfolioItemMerchant.\n\n\n :param updated_at_time: The updated_at_time of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501\n :type: int\n \"\"\"\n if updated_at_time is None:\n raise ValueError(\"Invalid value for `updated_at_time`, must not be `None`\") # noqa: E501\n\n self._updated_at_time = updated_at_time\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, PortfolioIdDelResponsePortfolioItemMerchant):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.6993007063865662, "alphanum_fraction": 0.7090908885002136, "avg_line_length": 14.543478012084961, "blob_id": "d480b733154efeacf72b5b07091fa190f9628148", "content_id": "e1715ef98a87b93b8f244f61a8d538d79bb8a1d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 715, "license_type": "no_license", "max_line_length": 99, "num_lines": 46, "path": "/README.md", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# StockX Public API\n\n### Production\nAPI\n```\nhttps://gateway.stockx.com/public\n```\n\nSite\n```\nhttps://stockx.com\n```\n\n\n### Sandbox\nAPI\n```\nhttps://gateway.stockx.com/sandbox\n```\n\nSite\n```\nhttps://sandbox.stockx.com\n```\n\n\n### API Docs\n[Swagger API Docs](https://app.swaggerhub.com/apis/StockX2/StockX_API/final32218.2)\n\n\n\n### Examples\n- [New Lowest Ask](https://github.com/stockx/PublicAPI/tree/master/examples/place_new_lowest_ask)\n- [Get Current Orders](https://github.com/stockx/PublicAPI/tree/master/examples/get_current_orders)\n\n## SDK\n\nStockX SDKs provide easy access to StockX APIs for many popular languages, including:\n\n- C#\n- Java\n- Javascript/Node.js\n- PHP\n- Python\n\nSDKs are located in the /sdk directory.\n" }, { "alpha_fraction": 0.6114016771316528, "alphanum_fraction": 0.6417363882064819, "avg_line_length": 37.2400016784668, "blob_id": "f16920c9e0ade1bcde925b62a089d34b05ed4544", "content_id": "5854ac8d3e204b9b88adeacb3871ce84d1090bf3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1912, "license_type": "no_license", "max_line_length": 107, "num_lines": 50, "path": "/sdk/java/io.stockx.sdk.examples/src/main/java/io/stockx/sdk/examples/endpoints/PortfolioBidExample.java", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "package io.stockx.sdk.examples.endpoints;\n\nimport static io.stockx.sdk.examples.base.LoginUtil.login;\n\nimport io.stockx.client.ApiClient;\nimport io.stockx.client.ApiException;\nimport io.stockx.client.api.StockXApi;\nimport io.stockx.client.model.CustomerObject;\nimport io.stockx.client.model.PortfolioRequest;\nimport io.stockx.client.model.PortfolioRequestPortfolioItem;\nimport io.stockx.client.model.PortfolioResponse;\nimport io.stockx.sdk.examples.base.Environment;\nimport io.stockx.sdk.examples.base.ExampleConstants;\nimport io.stockx.sdk.examples.base.StockXClient;\n\npublic class PortfolioBidExample {\n\n public static void main(String[] args) {\n\n ApiClient apiClient = StockXClient.create(ExampleConstants.AWS_API_KEY, Environment.STAGING, true);\n\n StockXApi stockx = new StockXApi(apiClient);\n\n try {\n // Login to the StockX framework - see LoginExample for how this works\n login(stockx, ExampleConstants.STOCKX_USERNAME, ExampleConstants.STOCKX_PASSWORD);\n\n PortfolioRequestPortfolioItem item = new PortfolioRequestPortfolioItem()\n .amount(\"25\")\n .skuUuid(\"bae25b67-a721-4f57-ad5a-79973c7d0a5c\")\n .matchedWithDate(\"2018-12-12T05:00:00+0000\")\n .expiresAt(\"2018-12-12T12:39:07+00:00\");\n\n CustomerObject cust = new CustomerObject();\n cust.setDefaultSize(\"7\");\n\n PortfolioRequest request = new PortfolioRequest()\n .portfolioItem(item)\n .customer(cust)\n .timezone(\"America/Detroit\");\n\n PortfolioResponse bidResp = stockx.newPortfolioBid(request);\n System.out.println(\"Bid Created: \" + bidResp);\n\n } catch (ApiException e) {\n e.printStackTrace();\n }\n }\n\n}\n" }, { "alpha_fraction": 0.6774495840072632, "alphanum_fraction": 0.7051101922988892, "avg_line_length": 30.382352828979492, "blob_id": "63f3d45663bd56188ea33c9e1f71df852502503a", "content_id": "96880d88140b49cdb8d82d15080e3ff1fdf22d06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2133, "license_type": "no_license", "max_line_length": 96, "num_lines": 68, "path": "/sdk/nodejs/place_new_lowest_ask_example.js", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "var StockX = require('stock_x_api');\n\nvar exampleConstants = new ExampleConstants();\n\nvar defaultClient = StockX.ApiClient.instance;\n\tdefaultClient.basePath = 'https://gateway.stockx.com/stage';\n\nvar apiKey = defaultClient.authentications['api_key'];\n\tapiKey.apiKey = exampleConstants.AWS_API_KEY;\n\nvar stockx = new StockX.StockXApi();\n\nvar login = new StockX.LoginRequest();\n\tlogin.email = exampleConstants.STOCKX_USERNAME;\n\tlogin.password = exampleConstants.STOCKX_PASSWORD;\n\nvar customer;\n\nstockx.loginWithHttpInfo(login)\n\t.then(res => {\n\t\tdefaultClient.defaultHeaders['jwt-authorization'] = res.response.headers['jwt-authorization'];\n\t\tcustomer = res.data.Customer;\n\t\treturn customer;\n\t}).then(customer => {\n\t\t// Search for a type of product\n\t\treturn stockx.search('Jordan Retro Black Cat');\n\t}).then(search => {\n\t\t// Lookup the first product returned from the search\n\t\tvar firstHit = search.hits[0];\n\t\t\n\t\tvar opts = {};\n\t\t\topts['identifier'] = firstHit.style_id;\n\t\t\topts['size'] = '11';\n\t\t\n\t\treturn stockx.lookupProduct(opts);\n\t}).then(product => {\n\t\t// Get the current market data for the product (highest bid info, etc.)\n\t\tvar data = product.data[0];\n\t\tvar attributes = data.attributes;\n\t\tvar id = data.id;\n\t\tvar uuid = attributes.product_uuid;\n\t\t\n\t\t// Get the product market data\n\t\treturn stockx.getProductMarketData(id, uuid);\n\t}).then(marketData => {\n\t\t// Get the lowest ask for the product and increment it\n\t\tvar lowestAsk = marketData.Market.lowestAsk;\n\t\tlowestAsk--;\n\t\t\n\t\t// Create a portfolio item request with a higher bid\n\t\tvar item = new StockX.PortfolioRequestPortfolioItem()\n\t\t\titem.amount = lowestAsk;\n\t\t\titem.skuUuid = 'bae25b67-a721-4f57-ad5a-79973c7d0a5c';\n\t\t\titem.matchedWithDate = '2018-12-12T05:00:00+0000';\n\t\t\titem.expiresAt = '2018-12-12T12:39:07+00:00';\n\t\t\n\t\tvar request = new StockX.PortfolioRequest()\n\t\t\trequest.PortfolioItem = item;\n\t\t\trequest.Customer = customer;\n\t\t\trequest.timezone = 'America/Detroit';\n\t\t\n\t\t// Submit the ask\n\t\treturn stockx.newPortfolioAsk(request);\n\t}).then(ask => {\n\t\tconsole.log('Ask successfully placed: ' + JSON.stringify(ask));\n\t}).catch(err => {\n\t\tconsole.log('Error placing ask: ' + err);\n\t});" }, { "alpha_fraction": 0.5614168643951416, "alphanum_fraction": 0.5640830397605896, "avg_line_length": 15.564668655395508, "blob_id": "e47ddaca0b2aa1dae1b8b312e160222d40b2cbe3", "content_id": "fd941a050d5099517d14ca33c5ca5846fd67c059", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5251, "license_type": "no_license", "max_line_length": 110, "num_lines": 317, "path": "/sdk/php/StockX-SDK-PHP/lib/test/Model/SearchHitTest.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * SearchHitTest\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Please update the test case below to test the model.\n */\n\nnamespace StockX\\Client;\n\n/**\n * SearchHitTest Class Doc Comment\n *\n * @category Class */\n// * @description SearchHit\n/**\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass SearchHitTest extends \\PHPUnit_Framework_TestCase\n{\n\n /**\n * Setup before running any test case\n */\n public static function setUpBeforeClass()\n {\n }\n\n /**\n * Setup before running each test case\n */\n public function setUp()\n {\n }\n\n /**\n * Clean up after running each test case\n */\n public function tearDown()\n {\n }\n\n /**\n * Clean up after running all test cases\n */\n public static function tearDownAfterClass()\n {\n }\n\n /**\n * Test \"SearchHit\"\n */\n public function testSearchHit()\n {\n }\n\n /**\n * Test attribute \"name\"\n */\n public function testPropertyName()\n {\n }\n\n /**\n * Test attribute \"brand\"\n */\n public function testPropertyBrand()\n {\n }\n\n /**\n * Test attribute \"thumbnail_url\"\n */\n public function testPropertyThumbnailUrl()\n {\n }\n\n /**\n * Test attribute \"media\"\n */\n public function testPropertyMedia()\n {\n }\n\n /**\n * Test attribute \"url\"\n */\n public function testPropertyUrl()\n {\n }\n\n /**\n * Test attribute \"release_date\"\n */\n public function testPropertyReleaseDate()\n {\n }\n\n /**\n * Test attribute \"categories\"\n */\n public function testPropertyCategories()\n {\n }\n\n /**\n * Test attribute \"product_category\"\n */\n public function testPropertyProductCategory()\n {\n }\n\n /**\n * Test attribute \"ticker_symbol\"\n */\n public function testPropertyTickerSymbol()\n {\n }\n\n /**\n * Test attribute \"style_id\"\n */\n public function testPropertyStyleId()\n {\n }\n\n /**\n * Test attribute \"make\"\n */\n public function testPropertyMake()\n {\n }\n\n /**\n * Test attribute \"model\"\n */\n public function testPropertyModel()\n {\n }\n\n /**\n * Test attribute \"short_description\"\n */\n public function testPropertyShortDescription()\n {\n }\n\n /**\n * Test attribute \"gender\"\n */\n public function testPropertyGender()\n {\n }\n\n /**\n * Test attribute \"colorway\"\n */\n public function testPropertyColorway()\n {\n }\n\n /**\n * Test attribute \"price\"\n */\n public function testPropertyPrice()\n {\n }\n\n /**\n * Test attribute \"description\"\n */\n public function testPropertyDescription()\n {\n }\n\n /**\n * Test attribute \"highest_bid\"\n */\n public function testPropertyHighestBid()\n {\n }\n\n /**\n * Test attribute \"total_dollars\"\n */\n public function testPropertyTotalDollars()\n {\n }\n\n /**\n * Test attribute \"lowest_ask\"\n */\n public function testPropertyLowestAsk()\n {\n }\n\n /**\n * Test attribute \"last_sale\"\n */\n public function testPropertyLastSale()\n {\n }\n\n /**\n * Test attribute \"sales_last_72\"\n */\n public function testPropertySalesLast72()\n {\n }\n\n /**\n * Test attribute \"deadstock_sold\"\n */\n public function testPropertyDeadstockSold()\n {\n }\n\n /**\n * Test attribute \"quality_bid\"\n */\n public function testPropertyQualityBid()\n {\n }\n\n /**\n * Test attribute \"active\"\n */\n public function testPropertyActive()\n {\n }\n\n /**\n * Test attribute \"new_release\"\n */\n public function testPropertyNewRelease()\n {\n }\n\n /**\n * Test attribute \"searchable_traits\"\n */\n public function testPropertySearchableTraits()\n {\n }\n\n /**\n * Test attribute \"object_id\"\n */\n public function testPropertyObjectId()\n {\n }\n\n /**\n * Test attribute \"annual_high\"\n */\n public function testPropertyAnnualHigh()\n {\n }\n\n /**\n * Test attribute \"annual_low\"\n */\n public function testPropertyAnnualLow()\n {\n }\n\n /**\n * Test attribute \"deadstock_range_low\"\n */\n public function testPropertyDeadstockRangeLow()\n {\n }\n\n /**\n * Test attribute \"deadstock_range_high\"\n */\n public function testPropertyDeadstockRangeHigh()\n {\n }\n\n /**\n * Test attribute \"average_deadstock_price\"\n */\n public function testPropertyAverageDeadstockPrice()\n {\n }\n\n /**\n * Test attribute \"change_value\"\n */\n public function testPropertyChangeValue()\n {\n }\n}\n" }, { "alpha_fraction": 0.5305817723274231, "alphanum_fraction": 0.5315763354301453, "avg_line_length": 45.72093200683594, "blob_id": "43d852a9b86a5a8de487aa547166eff10283e331", "content_id": "91011ab4dc002d7c5aa36e962ee3df11d466478f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2011, "license_type": "no_license", "max_line_length": 161, "num_lines": 43, "path": "/sdk/php/StockX-SDK-PHP/lib/docs/Model/MarketDataMarket.md", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# MarketDataMarket\n\n## Properties\nName | Type | Description | Notes\n------------ | ------------- | ------------- | -------------\n**product_id** | **int** | | [optional] \n**sku_uuid** | **string** | | [optional] \n**product_uuid** | **string** | | [optional] \n**lowest_ask** | **int** | | [optional] \n**lowest_ask_size** | **string** | | [optional] \n**parent_lowest_ask** | **int** | | [optional] \n**number_of_asks** | **int** | | [optional] \n**sales_this_period** | **int** | | [optional] \n**sales_last_period** | **int** | | [optional] \n**highest_bid** | **int** | | [optional] \n**highest_bid_size** | **string** | | [optional] \n**number_of_bids** | **int** | | [optional] \n**annual_high** | **int** | | [optional] \n**annual_low** | **int** | | [optional] \n**deadstock_range_low** | **int** | | [optional] \n**deadstock_range_high** | **int** | | [optional] \n**volatility** | **float** | | [optional] \n**deadstock_sold** | **int** | | [optional] \n**price_premium** | **float** | | [optional] \n**average_deadstock_price** | **int** | | [optional] \n**last_sale** | **int** | | [optional] \n**last_sale_size** | **string** | | [optional] \n**sales_last72_hours** | **int** | | [optional] \n**change_value** | **int** | | [optional] \n**change_percentage** | **float** | | [optional] \n**abs_change_percentage** | **float** | | [optional] \n**total_dollars** | **int** | | [optional] \n**updated_at** | **int** | | [optional] \n**last_lowest_ask_time** | **int** | | [optional] \n**last_highest_bid_time** | **int** | | [optional] \n**last_sale_date** | **string** | | [optional] \n**created_at** | **string** | | [optional] \n**deadstock_sold_rank** | **int** | | [optional] \n**price_premium_rank** | **int** | | [optional] \n**average_deadstock_price_rank** | **int** | | [optional] \n**featured** | **string** | | [optional] \n\n[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)\n\n\n" }, { "alpha_fraction": 0.5339347124099731, "alphanum_fraction": 0.5347937941551208, "avg_line_length": 20.551851272583008, "blob_id": "808677fb1195b7fedb7906b2fe6d40029082203c", "content_id": "5d457a6a170b2d3520dafcc7a30c03614aa278e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 11640, "license_type": "no_license", "max_line_length": 110, "num_lines": 540, "path": "/sdk/php/StockX-SDK-PHP/lib/lib/Model/ProductResponseProductMeta.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * ProductResponseProductMeta\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Do not edit the class manually.\n */\n\nnamespace StockX\\Client\\Model;\n\nuse \\ArrayAccess;\nuse \\StockX\\Client\\ObjectSerializer;\n\n/**\n * ProductResponseProductMeta Class Doc Comment\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass ProductResponseProductMeta implements ModelInterface, ArrayAccess\n{\n const DISCRIMINATOR = null;\n\n /**\n * The original name of the model.\n *\n * @var string\n */\n protected static $swaggerModelName = 'product_response_Product_meta';\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerTypes = [\n 'charity' => 'bool',\n 'raffle' => 'bool',\n 'mobile_only' => 'bool',\n 'restock' => 'bool',\n 'deleted' => 'bool',\n 'hidden' => 'bool',\n 'lock_buying' => 'bool',\n 'lock_selling' => 'bool',\n 'redirected' => 'bool'\n ];\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerFormats = [\n 'charity' => null,\n 'raffle' => null,\n 'mobile_only' => null,\n 'restock' => null,\n 'deleted' => null,\n 'hidden' => null,\n 'lock_buying' => null,\n 'lock_selling' => null,\n 'redirected' => null\n ];\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerTypes()\n {\n return self::$swaggerTypes;\n }\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerFormats()\n {\n return self::$swaggerFormats;\n }\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @var string[]\n */\n protected static $attributeMap = [\n 'charity' => 'charity',\n 'raffle' => 'raffle',\n 'mobile_only' => 'mobile_only',\n 'restock' => 'restock',\n 'deleted' => 'deleted',\n 'hidden' => 'hidden',\n 'lock_buying' => 'lock_buying',\n 'lock_selling' => 'lock_selling',\n 'redirected' => 'redirected'\n ];\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @var string[]\n */\n protected static $setters = [\n 'charity' => 'setCharity',\n 'raffle' => 'setRaffle',\n 'mobile_only' => 'setMobileOnly',\n 'restock' => 'setRestock',\n 'deleted' => 'setDeleted',\n 'hidden' => 'setHidden',\n 'lock_buying' => 'setLockBuying',\n 'lock_selling' => 'setLockSelling',\n 'redirected' => 'setRedirected'\n ];\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @var string[]\n */\n protected static $getters = [\n 'charity' => 'getCharity',\n 'raffle' => 'getRaffle',\n 'mobile_only' => 'getMobileOnly',\n 'restock' => 'getRestock',\n 'deleted' => 'getDeleted',\n 'hidden' => 'getHidden',\n 'lock_buying' => 'getLockBuying',\n 'lock_selling' => 'getLockSelling',\n 'redirected' => 'getRedirected'\n ];\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @return array\n */\n public static function attributeMap()\n {\n return self::$attributeMap;\n }\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @return array\n */\n public static function setters()\n {\n return self::$setters;\n }\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @return array\n */\n public static function getters()\n {\n return self::$getters;\n }\n\n /**\n * The original name of the model.\n *\n * @return string\n */\n public function getModelName()\n {\n return self::$swaggerModelName;\n }\n\n \n\n \n\n /**\n * Associative array for storing property values\n *\n * @var mixed[]\n */\n protected $container = [];\n\n /**\n * Constructor\n *\n * @param mixed[] $data Associated array of property values\n * initializing the model\n */\n public function __construct(array $data = null)\n {\n $this->container['charity'] = isset($data['charity']) ? $data['charity'] : null;\n $this->container['raffle'] = isset($data['raffle']) ? $data['raffle'] : null;\n $this->container['mobile_only'] = isset($data['mobile_only']) ? $data['mobile_only'] : null;\n $this->container['restock'] = isset($data['restock']) ? $data['restock'] : null;\n $this->container['deleted'] = isset($data['deleted']) ? $data['deleted'] : null;\n $this->container['hidden'] = isset($data['hidden']) ? $data['hidden'] : null;\n $this->container['lock_buying'] = isset($data['lock_buying']) ? $data['lock_buying'] : null;\n $this->container['lock_selling'] = isset($data['lock_selling']) ? $data['lock_selling'] : null;\n $this->container['redirected'] = isset($data['redirected']) ? $data['redirected'] : null;\n }\n\n /**\n * Show all the invalid properties with reasons.\n *\n * @return array invalid properties with reasons\n */\n public function listInvalidProperties()\n {\n $invalidProperties = [];\n\n return $invalidProperties;\n }\n\n /**\n * Validate all the properties in the model\n * return true if all passed\n *\n * @return bool True if all properties are valid\n */\n public function valid()\n {\n\n return true;\n }\n\n\n /**\n * Gets charity\n *\n * @return bool\n */\n public function getCharity()\n {\n return $this->container['charity'];\n }\n\n /**\n * Sets charity\n *\n * @param bool $charity charity\n *\n * @return $this\n */\n public function setCharity($charity)\n {\n $this->container['charity'] = $charity;\n\n return $this;\n }\n\n /**\n * Gets raffle\n *\n * @return bool\n */\n public function getRaffle()\n {\n return $this->container['raffle'];\n }\n\n /**\n * Sets raffle\n *\n * @param bool $raffle raffle\n *\n * @return $this\n */\n public function setRaffle($raffle)\n {\n $this->container['raffle'] = $raffle;\n\n return $this;\n }\n\n /**\n * Gets mobile_only\n *\n * @return bool\n */\n public function getMobileOnly()\n {\n return $this->container['mobile_only'];\n }\n\n /**\n * Sets mobile_only\n *\n * @param bool $mobile_only mobile_only\n *\n * @return $this\n */\n public function setMobileOnly($mobile_only)\n {\n $this->container['mobile_only'] = $mobile_only;\n\n return $this;\n }\n\n /**\n * Gets restock\n *\n * @return bool\n */\n public function getRestock()\n {\n return $this->container['restock'];\n }\n\n /**\n * Sets restock\n *\n * @param bool $restock restock\n *\n * @return $this\n */\n public function setRestock($restock)\n {\n $this->container['restock'] = $restock;\n\n return $this;\n }\n\n /**\n * Gets deleted\n *\n * @return bool\n */\n public function getDeleted()\n {\n return $this->container['deleted'];\n }\n\n /**\n * Sets deleted\n *\n * @param bool $deleted deleted\n *\n * @return $this\n */\n public function setDeleted($deleted)\n {\n $this->container['deleted'] = $deleted;\n\n return $this;\n }\n\n /**\n * Gets hidden\n *\n * @return bool\n */\n public function getHidden()\n {\n return $this->container['hidden'];\n }\n\n /**\n * Sets hidden\n *\n * @param bool $hidden hidden\n *\n * @return $this\n */\n public function setHidden($hidden)\n {\n $this->container['hidden'] = $hidden;\n\n return $this;\n }\n\n /**\n * Gets lock_buying\n *\n * @return bool\n */\n public function getLockBuying()\n {\n return $this->container['lock_buying'];\n }\n\n /**\n * Sets lock_buying\n *\n * @param bool $lock_buying lock_buying\n *\n * @return $this\n */\n public function setLockBuying($lock_buying)\n {\n $this->container['lock_buying'] = $lock_buying;\n\n return $this;\n }\n\n /**\n * Gets lock_selling\n *\n * @return bool\n */\n public function getLockSelling()\n {\n return $this->container['lock_selling'];\n }\n\n /**\n * Sets lock_selling\n *\n * @param bool $lock_selling lock_selling\n *\n * @return $this\n */\n public function setLockSelling($lock_selling)\n {\n $this->container['lock_selling'] = $lock_selling;\n\n return $this;\n }\n\n /**\n * Gets redirected\n *\n * @return bool\n */\n public function getRedirected()\n {\n return $this->container['redirected'];\n }\n\n /**\n * Sets redirected\n *\n * @param bool $redirected redirected\n *\n * @return $this\n */\n public function setRedirected($redirected)\n {\n $this->container['redirected'] = $redirected;\n\n return $this;\n }\n /**\n * Returns true if offset exists. False otherwise.\n *\n * @param integer $offset Offset\n *\n * @return boolean\n */\n public function offsetExists($offset)\n {\n return isset($this->container[$offset]);\n }\n\n /**\n * Gets offset.\n *\n * @param integer $offset Offset\n *\n * @return mixed\n */\n public function offsetGet($offset)\n {\n return isset($this->container[$offset]) ? $this->container[$offset] : null;\n }\n\n /**\n * Sets value based on offset.\n *\n * @param integer $offset Offset\n * @param mixed $value Value to be set\n *\n * @return void\n */\n public function offsetSet($offset, $value)\n {\n if (is_null($offset)) {\n $this->container[] = $value;\n } else {\n $this->container[$offset] = $value;\n }\n }\n\n /**\n * Unsets offset.\n *\n * @param integer $offset Offset\n *\n * @return void\n */\n public function offsetUnset($offset)\n {\n unset($this->container[$offset]);\n }\n\n /**\n * Gets the string presentation of the object\n *\n * @return string\n */\n public function __toString()\n {\n if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print\n return json_encode(\n ObjectSerializer::sanitizeForSerialization($this),\n JSON_PRETTY_PRINT\n );\n }\n\n return json_encode(ObjectSerializer::sanitizeForSerialization($this));\n }\n}\n\n\n" }, { "alpha_fraction": 0.6373937726020813, "alphanum_fraction": 0.6600566506385803, "avg_line_length": 17.578947067260742, "blob_id": "0da4f9d4be20f31b6641a7b0077d3065fe03c341", "content_id": "385aad6c03b9e8a3f358b6df252e538a7203af48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 353, "license_type": "no_license", "max_line_length": 69, "num_lines": 19, "path": "/sdk/nodejs/example_constants.js", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "\nclass ExampleConstants {\n\n\tconstructor() {\n\t\tthis.AWS_API_KEY = \"<API Key>\";\n\n\t\tthis.STOCKX_USERNAME = \"<StockX Username>\";\n\n\t\tthis.STOCKX_PASSWORD = \"<StockX Password>\";\n\n\t\tthis.DEMO_PRODUCT_ID = \"air-jordan-1-retro-high-off-white-chicago\";\n\n\t\tthis.DEMO_CUSTOMER_ID = \"1471698\";\n\n\t\tthis.ENABLE_DEBUG = true;\n\n\t\tthis.JWT_HEADER = \"Jwt-Authorization\";\n\t}\n\t\n}" }, { "alpha_fraction": 0.623836100101471, "alphanum_fraction": 0.635940432548523, "avg_line_length": 25.530864715576172, "blob_id": "dce08a0fc6edb443183a19d14007f101a0ba3cb0", "content_id": "3558fc3260b73885cb4428a21caa256e40fb2d95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Maven POM", "length_bytes": 2148, "license_type": "no_license", "max_line_length": 100, "num_lines": 81, "path": "/sdk/java/io.stockx.sdk.examples/pom.xml", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>io.stockx</groupId>\n\t\t<artifactId>io.stockx.sdk.parent</artifactId>\n\t\t<version>0.0.1-SNAPSHOT</version>\n\t\t<relativePath>../pom.xml</relativePath>\n\t</parent>\n\n\t<artifactId>io.stockx.sdk.examples</artifactId>\n\t<packaging>jar</packaging>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-clean-plugin</artifactId>\n\t\t\t\t<version>3.1.0</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<filesets>\n\t\t\t\t\t\t<fileset>\n\t\t\t\t\t\t\t<directory>lib</directory>\n\t\t\t\t\t\t\t<includes>\n\t\t\t\t\t\t\t\t<include>*</include>\n\t\t\t\t\t\t\t</includes>\n\t\t\t\t\t\t\t<followSymlinks>false</followSymlinks>\n\t\t\t\t\t\t</fileset>\n\t\t\t\t\t</filesets>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-dependency-plugin</artifactId>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<phase>generate-sources</phase>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>copy-dependencies</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<artifactItems>\n\t\t\t\t\t\t\t\t<artifactItem>\n\t\t\t\t\t\t\t\t\t<groupId>io.stockx</groupId>\n\t\t\t\t\t\t\t\t\t<artifactId>io.stockx.sdk</artifactId>\n\t\t\t\t\t\t\t\t\t<version>${project.version}</version>\n\t\t\t\t\t\t\t\t\t<type>jar</type>\n\t\t\t\t\t\t\t\t\t<overWrite>true</overWrite>\n\t\t\t\t\t\t\t\t\t<outputDirectory>lib</outputDirectory>\n\t\t\t\t\t\t\t\t</artifactItem>\n\t\t\t\t\t\t\t</artifactItems>\n\t\t\t\t\t\t\t<outputDirectory>lib</outputDirectory>\n\t\t\t\t\t\t\t<overWriteReleases>false</overWriteReleases>\n\t\t\t\t\t\t\t<overWriteSnapshots>true</overWriteSnapshots>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-source-plugin</artifactId>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<id>attach-sources</id>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>io.stockx</groupId>\n\t\t\t<artifactId>io.stockx.sdk</artifactId>\n\t\t\t<version>0.0.1-SNAPSHOT</version>\n\t\t</dependency>\n\t</dependencies>\n</project>" }, { "alpha_fraction": 0.5676382780075073, "alphanum_fraction": 0.5779147744178772, "avg_line_length": 27.168420791625977, "blob_id": "3a15ee812145b62192264944481e2b3dce2bee6e", "content_id": "c5863d7541f79c6b1a7686a908e5c1d5b04c2041", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5352, "license_type": "no_license", "max_line_length": 176, "num_lines": 190, "path": "/sdk/python/lib/build/lib/io_stockx/models/search_hit_searchable_traits.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass SearchHitSearchableTraits(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'style': 'str',\n 'colorway': 'str',\n 'retail_price': 'int',\n 'release_date': 'str'\n }\n\n attribute_map = {\n 'style': 'Style',\n 'colorway': 'Colorway',\n 'retail_price': 'Retail Price',\n 'release_date': 'Release Date'\n }\n\n def __init__(self, style=None, colorway=None, retail_price=None, release_date=None): # noqa: E501\n \"\"\"SearchHitSearchableTraits - a model defined in Swagger\"\"\" # noqa: E501\n\n self._style = None\n self._colorway = None\n self._retail_price = None\n self._release_date = None\n self.discriminator = None\n\n if style is not None:\n self.style = style\n if colorway is not None:\n self.colorway = colorway\n if retail_price is not None:\n self.retail_price = retail_price\n if release_date is not None:\n self.release_date = release_date\n\n @property\n def style(self):\n \"\"\"Gets the style of this SearchHitSearchableTraits. # noqa: E501\n\n\n :return: The style of this SearchHitSearchableTraits. # noqa: E501\n :rtype: str\n \"\"\"\n return self._style\n\n @style.setter\n def style(self, style):\n \"\"\"Sets the style of this SearchHitSearchableTraits.\n\n\n :param style: The style of this SearchHitSearchableTraits. # noqa: E501\n :type: str\n \"\"\"\n\n self._style = style\n\n @property\n def colorway(self):\n \"\"\"Gets the colorway of this SearchHitSearchableTraits. # noqa: E501\n\n\n :return: The colorway of this SearchHitSearchableTraits. # noqa: E501\n :rtype: str\n \"\"\"\n return self._colorway\n\n @colorway.setter\n def colorway(self, colorway):\n \"\"\"Sets the colorway of this SearchHitSearchableTraits.\n\n\n :param colorway: The colorway of this SearchHitSearchableTraits. # noqa: E501\n :type: str\n \"\"\"\n\n self._colorway = colorway\n\n @property\n def retail_price(self):\n \"\"\"Gets the retail_price of this SearchHitSearchableTraits. # noqa: E501\n\n\n :return: The retail_price of this SearchHitSearchableTraits. # noqa: E501\n :rtype: int\n \"\"\"\n return self._retail_price\n\n @retail_price.setter\n def retail_price(self, retail_price):\n \"\"\"Sets the retail_price of this SearchHitSearchableTraits.\n\n\n :param retail_price: The retail_price of this SearchHitSearchableTraits. # noqa: E501\n :type: int\n \"\"\"\n\n self._retail_price = retail_price\n\n @property\n def release_date(self):\n \"\"\"Gets the release_date of this SearchHitSearchableTraits. # noqa: E501\n\n\n :return: The release_date of this SearchHitSearchableTraits. # noqa: E501\n :rtype: str\n \"\"\"\n return self._release_date\n\n @release_date.setter\n def release_date(self, release_date):\n \"\"\"Sets the release_date of this SearchHitSearchableTraits.\n\n\n :param release_date: The release_date of this SearchHitSearchableTraits. # noqa: E501\n :type: str\n \"\"\"\n\n self._release_date = release_date\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, SearchHitSearchableTraits):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.7609170079231262, "alphanum_fraction": 0.7609170079231262, "avg_line_length": 69.46154022216797, "blob_id": "d52b5f608ef108a68c367f0cb638eaae9f1988ba", "content_id": "8202d831914c773843d9d3d734ac5e9b5b7d81e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 916, "license_type": "no_license", "max_line_length": 121, "num_lines": 13, "path": "/swagger/build.sh", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nrm -rf src-gen\nmkdir src-gen\n\njava -jar bin/swagger-codegen-cli.jar generate -c config/config.go.json -i swagger.json -l go -o src-gen/go\njava -jar bin/swagger-codegen-cli.jar generate -c config/config.csharp.json -i swagger.json -l csharp -o src-gen/csharp\njava -jar bin/swagger-codegen-cli.jar generate -c config/config.java.json -i swagger.json -l java -o src-gen/java\njava -jar bin/swagger-codegen-cli.jar generate -i swagger.json -l html -o src-gen/html\njava -jar bin/swagger-codegen-cli.jar generate -c config/config.php.json -i swagger.json -l php -o src-gen/php\njava -jar bin/swagger-codegen-cli.jar generate -c config/config.node.json -i swagger.json -l javascript -o src-gen/nodejs\njava -jar bin/swagger-codegen-cli.jar generate -c config/config.python.json -i swagger.json -l python -o src-gen/python\njava -jar bin/swagger-codegen-cli.jar generate -i swagger.json -l jmeter -o src-gen/jmeter\n" }, { "alpha_fraction": 0.7879902124404907, "alphanum_fraction": 0.7879902124404907, "avg_line_length": 29.22222137451172, "blob_id": "63db42fdd63427f88118421df72eda904ff438a7", "content_id": "1c105e18d4c422d8ec44c39aaf1e31b51ce684d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 816, "license_type": "no_license", "max_line_length": 119, "num_lines": 27, "path": "/sdk/nodejs/README.md", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# StockX Public API - Javascript Library\n\n## Summary\n\nThis project provides a StockX javascript library for accessing StockX's public API.\n\n## Usage\n\n* Link the supplied node module to your the project\n* Update the example_constants.js source file to include your API Key (supplied by StockX) and your account credentials\n* Execute the supplied examples in src/ with the javascript interpreter\n\n### Examples\n\nThis project provides the following examples of using the StockX Javascript Library:\n\n* Logging into the StockX API\n* Querying for open orders\n* Querying for market data about a product\n* Looking up product information\n* Searching the product catalog via general queries\n* Placing bids as a buyer\n* Placing asks as a seller\n\n### Directories\n\n/lib - contains a javascript library providing StockX API access\n" }, { "alpha_fraction": 0.5781726837158203, "alphanum_fraction": 0.5880452394485474, "avg_line_length": 28.32105255126953, "blob_id": "6f44fd3f88a44071f2e5c2d980dca52cfeb65e4f", "content_id": "eeeb041a30ef93a61a83255da5d34eddbe2ead63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5571, "license_type": "no_license", "max_line_length": 176, "num_lines": 190, "path": "/sdk/python/lib/io_stockx/models/customer_object_merchant.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass CustomerObjectMerchant(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'merchant_id': 'str',\n 'paypal_email': 'str',\n 'preferred_payout': 'str',\n 'account_name': 'str'\n }\n\n attribute_map = {\n 'merchant_id': 'merchantId',\n 'paypal_email': 'paypalEmail',\n 'preferred_payout': 'preferredPayout',\n 'account_name': 'accountName'\n }\n\n def __init__(self, merchant_id=None, paypal_email=None, preferred_payout=None, account_name=None): # noqa: E501\n \"\"\"CustomerObjectMerchant - a model defined in Swagger\"\"\" # noqa: E501\n\n self._merchant_id = None\n self._paypal_email = None\n self._preferred_payout = None\n self._account_name = None\n self.discriminator = None\n\n if merchant_id is not None:\n self.merchant_id = merchant_id\n if paypal_email is not None:\n self.paypal_email = paypal_email\n if preferred_payout is not None:\n self.preferred_payout = preferred_payout\n if account_name is not None:\n self.account_name = account_name\n\n @property\n def merchant_id(self):\n \"\"\"Gets the merchant_id of this CustomerObjectMerchant. # noqa: E501\n\n\n :return: The merchant_id of this CustomerObjectMerchant. # noqa: E501\n :rtype: str\n \"\"\"\n return self._merchant_id\n\n @merchant_id.setter\n def merchant_id(self, merchant_id):\n \"\"\"Sets the merchant_id of this CustomerObjectMerchant.\n\n\n :param merchant_id: The merchant_id of this CustomerObjectMerchant. # noqa: E501\n :type: str\n \"\"\"\n\n self._merchant_id = merchant_id\n\n @property\n def paypal_email(self):\n \"\"\"Gets the paypal_email of this CustomerObjectMerchant. # noqa: E501\n\n\n :return: The paypal_email of this CustomerObjectMerchant. # noqa: E501\n :rtype: str\n \"\"\"\n return self._paypal_email\n\n @paypal_email.setter\n def paypal_email(self, paypal_email):\n \"\"\"Sets the paypal_email of this CustomerObjectMerchant.\n\n\n :param paypal_email: The paypal_email of this CustomerObjectMerchant. # noqa: E501\n :type: str\n \"\"\"\n\n self._paypal_email = paypal_email\n\n @property\n def preferred_payout(self):\n \"\"\"Gets the preferred_payout of this CustomerObjectMerchant. # noqa: E501\n\n\n :return: The preferred_payout of this CustomerObjectMerchant. # noqa: E501\n :rtype: str\n \"\"\"\n return self._preferred_payout\n\n @preferred_payout.setter\n def preferred_payout(self, preferred_payout):\n \"\"\"Sets the preferred_payout of this CustomerObjectMerchant.\n\n\n :param preferred_payout: The preferred_payout of this CustomerObjectMerchant. # noqa: E501\n :type: str\n \"\"\"\n\n self._preferred_payout = preferred_payout\n\n @property\n def account_name(self):\n \"\"\"Gets the account_name of this CustomerObjectMerchant. # noqa: E501\n\n\n :return: The account_name of this CustomerObjectMerchant. # noqa: E501\n :rtype: str\n \"\"\"\n return self._account_name\n\n @account_name.setter\n def account_name(self, account_name):\n \"\"\"Sets the account_name of this CustomerObjectMerchant.\n\n\n :param account_name: The account_name of this CustomerObjectMerchant. # noqa: E501\n :type: str\n \"\"\"\n\n self._account_name = account_name\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, CustomerObjectMerchant):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.6455479264259338, "alphanum_fraction": 0.6720890402793884, "avg_line_length": 36.69355010986328, "blob_id": "e7f3c8a6881f98ef7d1e905d72244c42c66ff067", "content_id": "3624140195f2b1a482db878bc7293cb14e8d7023", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2336, "license_type": "no_license", "max_line_length": 90, "num_lines": 62, "path": "/sdk/php/StockX-SDK-PHP/src/PlaceNewHighestBidExample.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n\nrequire_once(__DIR__ . '/../lib/vendor/autoload.php');\nrequire_once('LoginUtil.php');\nrequire_once('ExampleConstants.php');\nrequire_once('JWTHeaderSelector.php');\n\n$client = new GuzzleHttp\\Client();\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()\n ->setApiKey('x-api-key', ExampleConstants::$AWS_API_KEY)\n ->setHost(Environment::$ENDPOINT_STAGING);\n\n$headerSelector = new JWTHeaderSelector();\n\n$api = new StockX\\Client\\Api\\StockXApi(\n $client,\n $config,\n $headerSelector\n );\n\ntry {\n // Login to the StockX framework - see LoginExample for how this works\n $customer = LoginUtil::login($api, $headerSelector,\n ExampleConstants::$STOCKX_USERNAME,\n ExampleConstants::$STOCKX_PASSWORD);\n\n // Search for a given product and lookup its styleid\n $firstResult = $api->search(\"Jordan Retro Black Cat2\")->getHits()[0];\n $styleId = $firstResult->getStyleId();\n \n // Look up the product info by style id and size\n $productInfo = $api->lookupProduct($styleId, \"11\");\n \n $productId = $productInfo[\"data\"][0][\"id\"];\n $productUuid = $productInfo[\"data\"][0][\"attributes\"][\"product_uuid\"];\n \n // Lookup the current market data for the product\n $marketData = $api->getProductMarketData($productId, $productUuid);\n \n // Get the current highest bid and increment it\n $highestBid = $marketData[\"market\"][\"highest_bid\"];\n $highestBid++;\n \n // Create a portfolio item request with a higher bid\n $portfolioItemReq = new StockX\\Client\\Model\\PortfolioRequestPortfolioItem();\n $portfolioItemReq->setAmount($highestBid);\n $portfolioItemReq->setSkuUuid(\"bae25b67-a721-4f57-ad5a-79973c7d0a5c\");\n $portfolioItemReq->setMatchedWithDate(\"2018-12-12T05:00:00+0000\");\n $portfolioItemReq->setExpiresAt(\"2018-12-12T12:39:07+00:00\");\n \n $portfolioReq = new StockX\\Client\\Model\\PortfolioRequest();\n $portfolioReq->setPortfolioItem($portfolioItemReq);\n $portfolioReq->setCustomer($customer[0][\"customer\"]);\n $portfolioReq->setTimezone(\"America/Detroit\");\n \n // Submit the bid\n $bidResp = $api->newPortfolioBid($portfolioReq);\n \n print_r($bidResp);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->newPortfolioBid: ', $e->getMessage(), PHP_EOL;\n}" }, { "alpha_fraction": 0.7671860456466675, "alphanum_fraction": 0.7708524465560913, "avg_line_length": 35.36666488647461, "blob_id": "21197a532523100e3a00e172cfed4ceb57aca1fc", "content_id": "6bdfbf29c02df9d971c0fa481b393b1386429caf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1091, "license_type": "no_license", "max_line_length": 115, "num_lines": 30, "path": "/sdk/csharp/README.md", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# StockX Public API - .NET 4.5 C# Library\n\n## Summary\n\nThis project provides a StockX .NET assembly for accessing StockX's public API.\n\n## Usage\n\n* Add the supplied assemblies from /lib to your project (visual studio solution, make file, etc)\n* Update the ExampleConstants source file to include your API Key (supplied by StockX) and your account credentials\n* Compile the examples in your project (or run the supplied bash script - requires Mono)\n* In the bash script, the compiled .NET example binaries are placed in /bin\n* Execute an example with (e.g. mono bin/ExampleName.exe)\n\n### Examples\n\nThis project provides the following examples of using the StockX .NET Library:\n\n* Logging into the StockX API\n* Querying for open orders\n* Querying for market data about a product\n* Looking up product information\n* Searching the product catalog via general queries\n* Placing bids as a buyer\n* Placing asks as a seller\n\n### Directories\n\n/lib - contains the cross platform StockX .NET 4.5 assembly and other required assemblies\n/src - contains examples of interacting with the StockX API with C#\n" }, { "alpha_fraction": 0.6573033928871155, "alphanum_fraction": 0.6573033928871155, "avg_line_length": 27.74193572998047, "blob_id": "fafca9c2b5085484f17c6695288208898b48c210", "content_id": "e8ccb9d2f451766735c0f42a8c2bf50bcdd4d570", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 890, "license_type": "no_license", "max_line_length": 89, "num_lines": 31, "path": "/sdk/php/StockX-SDK-PHP/src/SearchExample.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n\nrequire_once(__DIR__ . '/../lib/vendor/autoload.php');\nrequire_once('LoginUtil.php');\nrequire_once('ExampleConstants.php');\nrequire_once('JWTHeaderSelector.php');\n\n$client = new GuzzleHttp\\Client();\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()\n->setApiKey('x-api-key', ExampleConstants::$AWS_API_KEY)\n->setHost(Environment::$ENDPOINT_STAGING);\n\n$headerSelector = new JWTHeaderSelector();\n\n$api = new StockX\\Client\\Api\\StockXApi(\n $client,\n $config,\n $headerSelector\n );\n\ntry {\n LoginUtil::login($api, $headerSelector, \n ExampleConstants::$STOCKX_USERNAME, \n ExampleConstants::$STOCKX_PASSWORD);\n \n $searchResult = $api->search(\"yeezy\", null);\n \n print_r($searchResult);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->getProductById: ', $e->getMessage(), PHP_EOL;\n}" }, { "alpha_fraction": 0.5077342987060547, "alphanum_fraction": 0.5077342987060547, "avg_line_length": 41.19230651855469, "blob_id": "95c3ba318289c707172bb96a4166fa2a30f83d02", "content_id": "58232ff18410d04c4816b539ff47a1bc46883754", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1099, "license_type": "no_license", "max_line_length": 161, "num_lines": 26, "path": "/sdk/python/lib/docs/ProductInfoProductAttributes.md", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# ProductInfoProductAttributes\n\n## Properties\nName | Type | Description | Notes\n------------ | ------------- | ------------- | -------------\n**product_category** | **str** | | [optional] \n**url_key** | **str** | | [optional] \n**slug** | **str** | | [optional] \n**brand** | **str** | | [optional] \n**ticker** | **str** | | [optional] \n**style_id** | **str** | | [optional] \n**model** | **str** | | [optional] \n**name** | **str** | | [optional] \n**title** | **str** | | [optional] \n**size_locale** | **str** | | [optional] \n**size_title** | **str** | | [optional] \n**size_descriptor** | **str** | | [optional] \n**size_all_descriptor** | **str** | | [optional] \n**gender** | **str** | | [optional] \n**condition** | **str** | | [optional] \n**minimum_bid** | **int** | | [optional] \n**uniq_bids** | **bool** | | [optional] \n**primary_category** | **str** | | [optional] \n**secondary_category** | **str** | | [optional] \n\n[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)\n\n\n" }, { "alpha_fraction": 0.5566408634185791, "alphanum_fraction": 0.5712928771972656, "avg_line_length": 26.299999237060547, "blob_id": "015ee99be07b9d55cc8ea895b9bd4c56d0da6281", "content_id": "d95836644ef80b873a35bd70e4fc1d1a711eb439", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7371, "license_type": "no_license", "max_line_length": 176, "num_lines": 270, "path": "/sdk/python/lib/build/lib/io_stockx/models/billing_object.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom io_stockx.models.address_object import AddressObject # noqa: F401,E501\n\n\nclass BillingObject(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'card_type': 'str',\n 'token': 'str',\n 'last4': 'str',\n 'account_email': 'str',\n 'expiration_date': 'str',\n 'cardholder_name': 'str',\n 'address': 'AddressObject'\n }\n\n attribute_map = {\n 'card_type': 'cardType',\n 'token': 'token',\n 'last4': 'last4',\n 'account_email': 'accountEmail',\n 'expiration_date': 'expirationDate',\n 'cardholder_name': 'cardholderName',\n 'address': 'Address'\n }\n\n def __init__(self, card_type=None, token=None, last4=None, account_email=None, expiration_date=None, cardholder_name=None, address=None): # noqa: E501\n \"\"\"BillingObject - a model defined in Swagger\"\"\" # noqa: E501\n\n self._card_type = None\n self._token = None\n self._last4 = None\n self._account_email = None\n self._expiration_date = None\n self._cardholder_name = None\n self._address = None\n self.discriminator = None\n\n if card_type is not None:\n self.card_type = card_type\n if token is not None:\n self.token = token\n if last4 is not None:\n self.last4 = last4\n if account_email is not None:\n self.account_email = account_email\n if expiration_date is not None:\n self.expiration_date = expiration_date\n if cardholder_name is not None:\n self.cardholder_name = cardholder_name\n if address is not None:\n self.address = address\n\n @property\n def card_type(self):\n \"\"\"Gets the card_type of this BillingObject. # noqa: E501\n\n\n :return: The card_type of this BillingObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._card_type\n\n @card_type.setter\n def card_type(self, card_type):\n \"\"\"Sets the card_type of this BillingObject.\n\n\n :param card_type: The card_type of this BillingObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._card_type = card_type\n\n @property\n def token(self):\n \"\"\"Gets the token of this BillingObject. # noqa: E501\n\n\n :return: The token of this BillingObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._token\n\n @token.setter\n def token(self, token):\n \"\"\"Sets the token of this BillingObject.\n\n\n :param token: The token of this BillingObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._token = token\n\n @property\n def last4(self):\n \"\"\"Gets the last4 of this BillingObject. # noqa: E501\n\n\n :return: The last4 of this BillingObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._last4\n\n @last4.setter\n def last4(self, last4):\n \"\"\"Sets the last4 of this BillingObject.\n\n\n :param last4: The last4 of this BillingObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._last4 = last4\n\n @property\n def account_email(self):\n \"\"\"Gets the account_email of this BillingObject. # noqa: E501\n\n\n :return: The account_email of this BillingObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._account_email\n\n @account_email.setter\n def account_email(self, account_email):\n \"\"\"Sets the account_email of this BillingObject.\n\n\n :param account_email: The account_email of this BillingObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._account_email = account_email\n\n @property\n def expiration_date(self):\n \"\"\"Gets the expiration_date of this BillingObject. # noqa: E501\n\n\n :return: The expiration_date of this BillingObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._expiration_date\n\n @expiration_date.setter\n def expiration_date(self, expiration_date):\n \"\"\"Sets the expiration_date of this BillingObject.\n\n\n :param expiration_date: The expiration_date of this BillingObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._expiration_date = expiration_date\n\n @property\n def cardholder_name(self):\n \"\"\"Gets the cardholder_name of this BillingObject. # noqa: E501\n\n\n :return: The cardholder_name of this BillingObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._cardholder_name\n\n @cardholder_name.setter\n def cardholder_name(self, cardholder_name):\n \"\"\"Sets the cardholder_name of this BillingObject.\n\n\n :param cardholder_name: The cardholder_name of this BillingObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._cardholder_name = cardholder_name\n\n @property\n def address(self):\n \"\"\"Gets the address of this BillingObject. # noqa: E501\n\n\n :return: The address of this BillingObject. # noqa: E501\n :rtype: AddressObject\n \"\"\"\n return self._address\n\n @address.setter\n def address(self, address):\n \"\"\"Sets the address of this BillingObject.\n\n\n :param address: The address of this BillingObject. # noqa: E501\n :type: AddressObject\n \"\"\"\n\n self._address = address\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, BillingObject):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.5833333134651184, "alphanum_fraction": 0.5860477685928345, "avg_line_length": 16.37735939025879, "blob_id": "d93218d4b3b7a6e4a9f94637e9a3f54f019ee591", "content_id": "8c7aacc51c81bcb813184e5c982a9fb896b138c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3684, "license_type": "no_license", "max_line_length": 110, "num_lines": 212, "path": "/sdk/php/StockX-SDK-PHP/lib/test/Model/ProductInfoProductAttributesTest.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * ProductInfoProductAttributesTest\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Please update the test case below to test the model.\n */\n\nnamespace StockX\\Client;\n\n/**\n * ProductInfoProductAttributesTest Class Doc Comment\n *\n * @category Class */\n// * @description ProductInfoProductAttributes\n/**\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass ProductInfoProductAttributesTest extends \\PHPUnit_Framework_TestCase\n{\n\n /**\n * Setup before running any test case\n */\n public static function setUpBeforeClass()\n {\n }\n\n /**\n * Setup before running each test case\n */\n public function setUp()\n {\n }\n\n /**\n * Clean up after running each test case\n */\n public function tearDown()\n {\n }\n\n /**\n * Clean up after running all test cases\n */\n public static function tearDownAfterClass()\n {\n }\n\n /**\n * Test \"ProductInfoProductAttributes\"\n */\n public function testProductInfoProductAttributes()\n {\n }\n\n /**\n * Test attribute \"product_category\"\n */\n public function testPropertyProductCategory()\n {\n }\n\n /**\n * Test attribute \"url_key\"\n */\n public function testPropertyUrlKey()\n {\n }\n\n /**\n * Test attribute \"slug\"\n */\n public function testPropertySlug()\n {\n }\n\n /**\n * Test attribute \"brand\"\n */\n public function testPropertyBrand()\n {\n }\n\n /**\n * Test attribute \"ticker\"\n */\n public function testPropertyTicker()\n {\n }\n\n /**\n * Test attribute \"style_id\"\n */\n public function testPropertyStyleId()\n {\n }\n\n /**\n * Test attribute \"model\"\n */\n public function testPropertyModel()\n {\n }\n\n /**\n * Test attribute \"name\"\n */\n public function testPropertyName()\n {\n }\n\n /**\n * Test attribute \"title\"\n */\n public function testPropertyTitle()\n {\n }\n\n /**\n * Test attribute \"size_locale\"\n */\n public function testPropertySizeLocale()\n {\n }\n\n /**\n * Test attribute \"size_title\"\n */\n public function testPropertySizeTitle()\n {\n }\n\n /**\n * Test attribute \"size_descriptor\"\n */\n public function testPropertySizeDescriptor()\n {\n }\n\n /**\n * Test attribute \"size_all_descriptor\"\n */\n public function testPropertySizeAllDescriptor()\n {\n }\n\n /**\n * Test attribute \"gender\"\n */\n public function testPropertyGender()\n {\n }\n\n /**\n * Test attribute \"condition\"\n */\n public function testPropertyCondition()\n {\n }\n\n /**\n * Test attribute \"minimum_bid\"\n */\n public function testPropertyMinimumBid()\n {\n }\n\n /**\n * Test attribute \"uniq_bids\"\n */\n public function testPropertyUniqBids()\n {\n }\n\n /**\n * Test attribute \"primary_category\"\n */\n public function testPropertyPrimaryCategory()\n {\n }\n\n /**\n * Test attribute \"secondary_category\"\n */\n public function testPropertySecondaryCategory()\n {\n }\n}\n" }, { "alpha_fraction": 0.7032967209815979, "alphanum_fraction": 0.7179487347602844, "avg_line_length": 27.736841201782227, "blob_id": "d0ffb22ed782fc46f15fcd18d77f366642fedf0a", "content_id": "b6b7b8a90ed4d58edfb7613d4504582f7563a61f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 546, "license_type": "no_license", "max_line_length": 93, "num_lines": 19, "path": "/sdk/java/io.stockx.sdk.examples/src/main/java/io/stockx/sdk/examples/base/ExampleConstants.java", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "package io.stockx.sdk.examples.base;\n\npublic class ExampleConstants {\n\n public static final String AWS_API_KEY = \"<API Key>\";\n\n public static final String STOCKX_USERNAME = \"<StockX Username>\";\n\n public static final String STOCKX_PASSWORD = \"<StockX Password>\";\n\n public static final String DEMO_PRODUCT_ID = \"air-jordan-1-retro-high-off-white-chicago\";\n\n public static final String DEMO_CUSTOMER_ID = \"1471698\";\n\n public static final boolean ENABLE_DEBUG = true;\n\n public static final String JWT_HEADER = \"Jwt-Authorization\";\n\n}\n" }, { "alpha_fraction": 0.7376811504364014, "alphanum_fraction": 0.7376811504364014, "avg_line_length": 36.912086486816406, "blob_id": "63463929e627433c19d7db4a794875369095f407", "content_id": "ae887622e605ae396ab30c522fb8a63b61a4de9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3450, "license_type": "no_license", "max_line_length": 102, "num_lines": 91, "path": "/sdk/csharp/build.sh", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\necho \"Building GetProductInfoExample\"\nmcs src/IO.StockX.Examples/ExampleConstants.cs src/IO.StockX.Examples/GetProductInfoExample.cs \\\n -out:bin/GetProductInfoExample.exe \\\n -r:lib/IO.StockX.dll \\\n -r:lib/JsonSubTypes.dll \\\n -r:lib/Newtonsoft.Json.dll \\\n -r:lib/RestSharp.dll \\\n -r:System.ComponentModel.DataAnnotations.dll \\\n -r:System.Runtime.Serialization.dll\n\necho \"Building LoginExample\"\nmcs src/IO.StockX.Examples/ExampleConstants.cs src/IO.StockX.Examples/LoginExample.cs \\\n -out:bin/LoginExample.exe \\\n -r:lib/IO.StockX.dll \\\n -r:lib/JsonSubTypes.dll \\\n -r:lib/Newtonsoft.Json.dll \\\n -r:lib/RestSharp.dll \\\n -r:System.ComponentModel.DataAnnotations.dll \\\n -r:System.Runtime.Serialization.dll\n\necho \"Building PortfolioAskExample\"\nmcs src/IO.StockX.Examples/ExampleConstants.cs src/IO.StockX.Examples/PortfolioAskExample.cs \\\n -out:bin/PortfolioAskExample.exe \\\n -r:lib/IO.StockX.dll \\\n -r:lib/JsonSubTypes.dll \\\n -r:lib/Newtonsoft.Json.dll \\\n -r:lib/RestSharp.dll \\\n -r:System.ComponentModel.DataAnnotations.dll \\\n -r:System.Runtime.Serialization.dll\n\necho \"Building PortfolioBidExample\"\nmcs src/IO.StockX.Examples/ExampleConstants.cs src/IO.StockX.Examples/PortfolioBidExample.cs \\\n -out:bin/PortfolioBidExample.exe \\\n -r:lib/IO.StockX.dll \\\n -r:lib/JsonSubTypes.dll \\\n -r:lib/Newtonsoft.Json.dll \\\n -r:lib/RestSharp.dll \\\n -r:System.ComponentModel.DataAnnotations.dll \\\n -r:System.Runtime.Serialization.dll\n\necho \"Building GetOpenOrdersExample\"\nmcs src/IO.StockX.Examples/ExampleConstants.cs src/IO.StockX.Examples/GetOpenOrdersExample.cs \\\n -out:bin/GetOpenOrdersExample.exe \\\n -r:lib/IO.StockX.dll \\\n -r:lib/JsonSubTypes.dll \\\n -r:lib/Newtonsoft.Json.dll \\\n -r:lib/RestSharp.dll \\\n -r:System.ComponentModel.DataAnnotations.dll \\\n -r:System.Runtime.Serialization.dll\n\necho \"Building GetProductMarketDataExample\"\nmcs src/IO.StockX.Examples/ExampleConstants.cs src/IO.StockX.Examples/GetProductMarketDataExample.cs \\\n -out:bin/GetProductMarketDataExample.exe \\\n -r:lib/IO.StockX.dll \\\n -r:lib/JsonSubTypes.dll \\\n -r:lib/Newtonsoft.Json.dll \\\n -r:lib/RestSharp.dll \\\n -r:System.ComponentModel.DataAnnotations.dll \\\n -r:System.Runtime.Serialization.dll\n\necho \"Building SearchExample\"\nmcs src/IO.StockX.Examples/ExampleConstants.cs src/IO.StockX.Examples/SearchExample.cs \\\n -out:bin/SearchExample.exe \\\n -r:lib/IO.StockX.dll \\\n -r:lib/JsonSubTypes.dll \\\n -r:lib/Newtonsoft.Json.dll \\\n -r:lib/RestSharp.dll \\\n -r:System.ComponentModel.DataAnnotations.dll \\\n -r:System.Runtime.Serialization.dll\n\necho \"Building PlaceNewHighestBidExample\"\nmcs src/IO.StockX.Examples/ExampleConstants.cs src/IO.StockX.Examples/PlaceNewHighestBidExample.cs \\\n -out:bin/PlaceNewHighestBidExample.exe \\\n -r:lib/IO.StockX.dll \\\n -r:lib/JsonSubTypes.dll \\\n -r:lib/Newtonsoft.Json.dll \\\n -r:lib/RestSharp.dll \\\n -r:System.ComponentModel.DataAnnotations.dll \\\n -r:System.Runtime.Serialization.dll\n\necho \"Building PlaceNewLowestAskExample\"\nmcs src/IO.StockX.Examples/ExampleConstants.cs src/IO.StockX.Examples/PlaceNewLowestAskExample.cs \\\n -out:bin/PlaceNewLowestAskExample.exe \\\n -r:lib/IO.StockX.dll \\\n -r:lib/JsonSubTypes.dll \\\n -r:lib/Newtonsoft.Json.dll \\\n -r:lib/RestSharp.dll \\\n -r:System.ComponentModel.DataAnnotations.dll \\\n -r:System.Runtime.Serialization.dll\n" }, { "alpha_fraction": 0.5439630746841431, "alphanum_fraction": 0.5549858808517456, "avg_line_length": 26.864286422729492, "blob_id": "00cc888fdb7ccd5f4429f82b21cd65bd6c58e2fe", "content_id": "d862ffa3d9c9f6a7d6dde381e61997931a41041c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3901, "license_type": "no_license", "max_line_length": 176, "num_lines": 140, "path": "/sdk/python/lib/build/lib/io_stockx/models/portfolio_id_del_request.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass PortfolioIdDelRequest(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'chain_id': 'str',\n 'notes': 'str'\n }\n\n attribute_map = {\n 'chain_id': 'chain_id',\n 'notes': 'notes'\n }\n\n def __init__(self, chain_id=None, notes=None): # noqa: E501\n \"\"\"PortfolioIdDelRequest - a model defined in Swagger\"\"\" # noqa: E501\n\n self._chain_id = None\n self._notes = None\n self.discriminator = None\n\n self.chain_id = chain_id\n self.notes = notes\n\n @property\n def chain_id(self):\n \"\"\"Gets the chain_id of this PortfolioIdDelRequest. # noqa: E501\n\n\n :return: The chain_id of this PortfolioIdDelRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._chain_id\n\n @chain_id.setter\n def chain_id(self, chain_id):\n \"\"\"Sets the chain_id of this PortfolioIdDelRequest.\n\n\n :param chain_id: The chain_id of this PortfolioIdDelRequest. # noqa: E501\n :type: str\n \"\"\"\n if chain_id is None:\n raise ValueError(\"Invalid value for `chain_id`, must not be `None`\") # noqa: E501\n\n self._chain_id = chain_id\n\n @property\n def notes(self):\n \"\"\"Gets the notes of this PortfolioIdDelRequest. # noqa: E501\n\n\n :return: The notes of this PortfolioIdDelRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._notes\n\n @notes.setter\n def notes(self, notes):\n \"\"\"Sets the notes of this PortfolioIdDelRequest.\n\n\n :param notes: The notes of this PortfolioIdDelRequest. # noqa: E501\n :type: str\n \"\"\"\n if notes is None:\n raise ValueError(\"Invalid value for `notes`, must not be `None`\") # noqa: E501\n\n self._notes = notes\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, PortfolioIdDelRequest):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.5447452068328857, "alphanum_fraction": 0.5535235404968262, "avg_line_length": 28.078014373779297, "blob_id": "63b8b6a9969126d639fb22d2e5c3d7741b289a23", "content_id": "05c8eed2b028b75586b58fad087ef05701ed2a94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4101, "license_type": "no_license", "max_line_length": 136, "num_lines": 141, "path": "/examples/place_new_lowest_ask/index.js", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "const superagent = require('superagent');\n\n// Customize these string values for your account and environment.\nconst API_KEY = 'API_Key_Given_By_StockX_Engineering';\nconst EMAIL = 'Email_Address';\nconst PASSWORD = 'Password';\nconst ENV = 'stage'; // Options: 'sandbox', 'stage', 'public'\n\nconst URL = `https://gateway.stockx.com/${ENV}`;\n\nclass ProductAsk {\n run() {\n this._login().then(loginData => {\n // Login and set the jwt for authorization.\n this.jwt = loginData.header['jwt-authorization'];\n\n // Find the Jordan Retro Black Cat sneaker.\n return this._findProduct('Jordan%206%20Retro%20Black%20Cat');\n\n }).then(productSearchResults => {\n // Pull the first item from the search results.\n const myProduct = productSearchResults[0];\n\n // Get the product information from the style_id of the product.\n return this._getProduct(mySneaker.style_id, 11)\n\n }).then(product => {\n // Get the up to date pricing information for the product.\n return this._getProductPriceData(product.attributes.product_uuid, product.id)\n\n }).then(data => {\n // Grab the lowest ask and subtract a dollar from it.\n const lowestAsk = data.Market.lowestAsk - 1;\n\n // Place the new lowest ask. Date must be in the future.\n return this._placeAsk(data.Market.skuUuid, '2018-12-12T12:39:07+00:00', lowestAsk);\n\n }).then(data => {\n // Log for success.\n console.log('Successfully placed the ask');\n\n }).catch(err => {\n // Log for error.\n console.error(err);\n })\n }\n\n // Login with API Key, email address, and password to retrieve a JWT.\n _login() {\n return new Promise((resolve, reject) => {\n superagent\n .post(`${URL}/v1/login`)\n .send({ email: EMAIL, password: PASSWORD })\n .set('x-api-key', API_KEY)\n .end((err, res) => {\n if(err) {\n reject(err);\n }else{\n resolve(res);\n }\n });\n })\n }\n\n // Retrieve an array of items based on the product query string, searching all products across StockX.com\n _findProduct(productQuery) {\n return new Promise((resolve, reject) => {\n superagent\n .get(`${URL}/v2/search?query=${productQuery}`)\n .set('x-api-key', API_KEY)\n .end((err, res) => {\n if(err) {\n reject(err);\n }else{\n resolve(res.body.hits);\n }\n });\n })\n }\n\n //This lookups up a product based on style id and size.\n _getProduct(styleId, size) {\n return new Promise((resolve, reject) => {\n superagent\n .get(`${URL}/product/lookup?identifier=${styleId}&size=${size}`)\n .set('x-api-key', API_KEY)\n .end((err, res) => {\n if(err) {\n reject(err);\n }else{\n resolve(res.body.data[0]);\n }\n })\n });\n }\n\n // This returns market data. You will need the product's uuid and sku to retreive it.\n _getProductPriceData(id, sku) {\n return new Promise((resolve, reject) => {\n superagent\n .get(`${URL}/v1/products/${id}/market?children=${sku}`)\n .set('jwt-authorization', this.jwt)\n .set('x-api-key', API_KEY)\n .end((err, res) => {\n if(err) {\n reject(err);\n }else{\n resolve(res.body);\n }\n })\n });\n }\n\n // The product's sku is required to place an ask. This is the unique id of the sneaker + size. You can get this via product data call.\n _placeAsk(sku, expiresAt, amount) {\n return new Promise((resolve, reject) => {\n superagent\n .post(`${URL}/v1/portfolio/ask`)\n .set('x-api-key', API_KEY)\n .set('jwt-authorization', this.jwt)\n .send({\n \"PortfolioItem\": {\n \"amount\": amount.toString(),\n \"expiresAt\": expiresAt,\n \"skuUuid\": sku\n }\n })\n .end((err, res) => {\n if(err) {\n reject(err);\n }else{\n resolve(res);\n }\n });\n });\n }\n}\n\nconst productAsk = new ProductAsk();\n\nproductAsk.run();\n\n" }, { "alpha_fraction": 0.5928270220756531, "alphanum_fraction": 0.5935302376747131, "avg_line_length": 32.093021392822266, "blob_id": "320359c7c4502e33358ca1b387050ea52d264560", "content_id": "759c07ead5fa66d6fa7279acf5f2f4fa618d9cf3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1422, "license_type": "no_license", "max_line_length": 109, "num_lines": 43, "path": "/sdk/csharp/src/IO.StockX.Examples/ProductLookupExample.cs", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "using System;\nusing System.Diagnostics;\nusing IO.StockX.Api;\nusing IO.StockX.Client;\nusing IO.StockX.Model;\n\nnamespace Example\n{\n /**\n * <p>Demonstrates looking up a specific product on the market.</p>\n */\n public class GetProductInfoExample\n {\n static public void Main()\n {\n // Configure API key authorization: api_key\n Configuration.Default.AddApiKey(\"x-api-key\", ExampleConstants.AWS_API_KEY);\n\n var stockx = new StockXApi();\n stockx.Configuration.BasePath = ExampleConstants.STOCKX_ENDPOINT;\n \n var login = new LoginRequest(ExampleConstants.STOCKX_USERNAME, ExampleConstants.STOCKX_PASSWORD);\n \n try\n {\n // Login and fetch the jwt header for authentication use in the request\n ApiResponse<LoginResponse> result = stockx.LoginWithHttpInfo(login);\n var jwt = result.Headers[ExampleConstants.JWT_HEADER];\n\n stockx.Configuration.DefaultHeader[\"jwt-authorization\"] = jwt;\n\n var productInfo = stockx.LookupProduct(\"nike\", \"7\");\n\n Console.WriteLine(productInfo);\n }\n catch (Exception e)\n {\n Console.WriteLine(e.ToString());\n Console.WriteLine(\"Exception when calling StockXApi.LookupProduct: \" + e.Message );\n }\n }\n }\n}" }, { "alpha_fraction": 0.7798264622688293, "alphanum_fraction": 0.7798264622688293, "avg_line_length": 31.928571701049805, "blob_id": "c271b564f8e413161d82530dc62e3e789032511f", "content_id": "f4fb833e1341022562ccde0152912de5f6eba1e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 922, "license_type": "no_license", "max_line_length": 119, "num_lines": 28, "path": "/sdk/python/README.md", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# StockX Public API - Python Library\n\n## Summary\n\nThis project provides a StockX python library for accessing StockX's public API.\n\n## Usage\n\n* Install the supplied library in /lib with `python setup.py install --user`\n* Update the example_constants.py source file to include your API Key (supplied by StockX) and your account credentials\n* Execute the supplied examples in src/ with the python interpreter `python ./example_script.py`\n\n### Examples\n\nThis project provides the following examples of using the StockX Python Library:\n\n* Logging into the StockX API\n* Querying for open orders\n* Querying for market data about a product\n* Looking up product information\n* Searching the product catalog via general queries\n* Placing bids as a buyer\n* Placing asks as a seller\n\n### Directories\n\n/lib - contains a python library providing StockX API access\n/src - contains examples of interacting with the StockX API with Python\n" }, { "alpha_fraction": 0.638603150844574, "alphanum_fraction": 0.6476718783378601, "avg_line_length": 37.08247375488281, "blob_id": "ada8c6b7f679c7d1337142e45f8b92d3b6f41fc3", "content_id": "7b7d3faa061cdbb34f468bf5d18e9fc8568b5ab5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7388, "license_type": "no_license", "max_line_length": 176, "num_lines": 194, "path": "/sdk/python/lib/build/lib/io_stockx/models/portfolio_id_del_response_portfolio_item_product_shipping.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass PortfolioIdDelResponsePortfolioItemProductShipping(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'total_days_to_ship': 'int',\n 'has_additional_days_to_ship': 'bool',\n 'delivery_days_lower_bound': 'int',\n 'delivery_days_upper_bound': 'int'\n }\n\n attribute_map = {\n 'total_days_to_ship': 'totalDaysToShip',\n 'has_additional_days_to_ship': 'hasAdditionalDaysToShip',\n 'delivery_days_lower_bound': 'deliveryDaysLowerBound',\n 'delivery_days_upper_bound': 'deliveryDaysUpperBound'\n }\n\n def __init__(self, total_days_to_ship=None, has_additional_days_to_ship=None, delivery_days_lower_bound=None, delivery_days_upper_bound=None): # noqa: E501\n \"\"\"PortfolioIdDelResponsePortfolioItemProductShipping - a model defined in Swagger\"\"\" # noqa: E501\n\n self._total_days_to_ship = None\n self._has_additional_days_to_ship = None\n self._delivery_days_lower_bound = None\n self._delivery_days_upper_bound = None\n self.discriminator = None\n\n self.total_days_to_ship = total_days_to_ship\n self.has_additional_days_to_ship = has_additional_days_to_ship\n self.delivery_days_lower_bound = delivery_days_lower_bound\n self.delivery_days_upper_bound = delivery_days_upper_bound\n\n @property\n def total_days_to_ship(self):\n \"\"\"Gets the total_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501\n\n\n :return: The total_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501\n :rtype: int\n \"\"\"\n return self._total_days_to_ship\n\n @total_days_to_ship.setter\n def total_days_to_ship(self, total_days_to_ship):\n \"\"\"Sets the total_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping.\n\n\n :param total_days_to_ship: The total_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501\n :type: int\n \"\"\"\n if total_days_to_ship is None:\n raise ValueError(\"Invalid value for `total_days_to_ship`, must not be `None`\") # noqa: E501\n\n self._total_days_to_ship = total_days_to_ship\n\n @property\n def has_additional_days_to_ship(self):\n \"\"\"Gets the has_additional_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501\n\n\n :return: The has_additional_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._has_additional_days_to_ship\n\n @has_additional_days_to_ship.setter\n def has_additional_days_to_ship(self, has_additional_days_to_ship):\n \"\"\"Sets the has_additional_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping.\n\n\n :param has_additional_days_to_ship: The has_additional_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501\n :type: bool\n \"\"\"\n if has_additional_days_to_ship is None:\n raise ValueError(\"Invalid value for `has_additional_days_to_ship`, must not be `None`\") # noqa: E501\n\n self._has_additional_days_to_ship = has_additional_days_to_ship\n\n @property\n def delivery_days_lower_bound(self):\n \"\"\"Gets the delivery_days_lower_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501\n\n\n :return: The delivery_days_lower_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501\n :rtype: int\n \"\"\"\n return self._delivery_days_lower_bound\n\n @delivery_days_lower_bound.setter\n def delivery_days_lower_bound(self, delivery_days_lower_bound):\n \"\"\"Sets the delivery_days_lower_bound of this PortfolioIdDelResponsePortfolioItemProductShipping.\n\n\n :param delivery_days_lower_bound: The delivery_days_lower_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501\n :type: int\n \"\"\"\n if delivery_days_lower_bound is None:\n raise ValueError(\"Invalid value for `delivery_days_lower_bound`, must not be `None`\") # noqa: E501\n\n self._delivery_days_lower_bound = delivery_days_lower_bound\n\n @property\n def delivery_days_upper_bound(self):\n \"\"\"Gets the delivery_days_upper_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501\n\n\n :return: The delivery_days_upper_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501\n :rtype: int\n \"\"\"\n return self._delivery_days_upper_bound\n\n @delivery_days_upper_bound.setter\n def delivery_days_upper_bound(self, delivery_days_upper_bound):\n \"\"\"Sets the delivery_days_upper_bound of this PortfolioIdDelResponsePortfolioItemProductShipping.\n\n\n :param delivery_days_upper_bound: The delivery_days_upper_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501\n :type: int\n \"\"\"\n if delivery_days_upper_bound is None:\n raise ValueError(\"Invalid value for `delivery_days_upper_bound`, must not be `None`\") # noqa: E501\n\n self._delivery_days_upper_bound = delivery_days_upper_bound\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, PortfolioIdDelResponsePortfolioItemProductShipping):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.6342609524726868, "alphanum_fraction": 0.6472184062004089, "avg_line_length": 33.464942932128906, "blob_id": "82fd0f22b78c058f1227ad16eac3c276fd53fc76", "content_id": "55c6adf9f148a0666ac524da80b512a9ed55516d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 41289, "license_type": "no_license", "max_line_length": 719, "num_lines": 1198, "path": "/sdk/python/lib/build/lib/io_stockx/models/portfolioitems_id_get_response_portfolio_item_product.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom io_stockx.models.portfolio_id_del_response_portfolio_item_product_media import PortfolioIdDelResponsePortfolioItemProductMedia # noqa: F401,E501\nfrom io_stockx.models.portfolio_id_del_response_portfolio_item_product_meta import PortfolioIdDelResponsePortfolioItemProductMeta # noqa: F401,E501\nfrom io_stockx.models.portfolio_id_del_response_portfolio_item_product_shipping import PortfolioIdDelResponsePortfolioItemProductShipping # noqa: F401,E501\nfrom io_stockx.models.portfolioitems_id_get_response_portfolio_item_product_market import PortfolioitemsIdGetResponsePortfolioItemProductMarket # noqa: F401,E501\n\n\nclass PortfolioitemsIdGetResponsePortfolioItemProduct(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'id': 'str',\n 'uuid': 'str',\n 'brand': 'str',\n 'category': 'str',\n 'charity_condition': 'int',\n 'colorway': 'str',\n 'condition': 'str',\n 'country_of_manufacture': 'str',\n 'gender': 'str',\n 'content_group': 'str',\n 'minimum_bid': 'int',\n 'media': 'PortfolioIdDelResponsePortfolioItemProductMedia',\n 'name': 'str',\n 'primary_category': 'str',\n 'secondary_category': 'str',\n 'product_category': 'str',\n 'release_date': 'str',\n 'retail_price': 'int',\n 'shoe': 'str',\n 'short_description': 'str',\n 'style_id': 'str',\n 'ticker_symbol': 'str',\n 'title': 'str',\n 'data_type': 'str',\n 'type': 'int',\n 'size_title': 'str',\n 'size_descriptor': 'str',\n 'size_all_descriptor': 'str',\n 'url_key': 'str',\n 'year': 'str',\n 'shipping_group': 'str',\n 'a_lim': 'int',\n 'meta': 'PortfolioIdDelResponsePortfolioItemProductMeta',\n 'shipping': 'PortfolioIdDelResponsePortfolioItemProductShipping',\n 'children': 'object',\n 'parent_id': 'str',\n 'parent_uuid': 'str',\n 'size_sort_order': 'int',\n 'shoe_size': 'str',\n 'market': 'PortfolioitemsIdGetResponsePortfolioItemProductMarket',\n 'upc': 'str'\n }\n\n attribute_map = {\n 'id': 'id',\n 'uuid': 'uuid',\n 'brand': 'brand',\n 'category': 'category',\n 'charity_condition': 'charityCondition',\n 'colorway': 'colorway',\n 'condition': 'condition',\n 'country_of_manufacture': 'countryOfManufacture',\n 'gender': 'gender',\n 'content_group': 'contentGroup',\n 'minimum_bid': 'minimumBid',\n 'media': 'media',\n 'name': 'name',\n 'primary_category': 'primaryCategory',\n 'secondary_category': 'secondaryCategory',\n 'product_category': 'productCategory',\n 'release_date': 'releaseDate',\n 'retail_price': 'retailPrice',\n 'shoe': 'shoe',\n 'short_description': 'shortDescription',\n 'style_id': 'styleId',\n 'ticker_symbol': 'tickerSymbol',\n 'title': 'title',\n 'data_type': 'dataType',\n 'type': 'type',\n 'size_title': 'sizeTitle',\n 'size_descriptor': 'sizeDescriptor',\n 'size_all_descriptor': 'sizeAllDescriptor',\n 'url_key': 'urlKey',\n 'year': 'year',\n 'shipping_group': 'shippingGroup',\n 'a_lim': 'aLim',\n 'meta': 'meta',\n 'shipping': 'shipping',\n 'children': 'children',\n 'parent_id': 'parentId',\n 'parent_uuid': 'parentUuid',\n 'size_sort_order': 'sizeSortOrder',\n 'shoe_size': 'shoeSize',\n 'market': 'market',\n 'upc': 'upc'\n }\n\n def __init__(self, id=None, uuid=None, brand=None, category=None, charity_condition=None, colorway=None, condition=None, country_of_manufacture=None, gender=None, content_group=None, minimum_bid=None, media=None, name=None, primary_category=None, secondary_category=None, product_category=None, release_date=None, retail_price=None, shoe=None, short_description=None, style_id=None, ticker_symbol=None, title=None, data_type=None, type=None, size_title=None, size_descriptor=None, size_all_descriptor=None, url_key=None, year=None, shipping_group=None, a_lim=None, meta=None, shipping=None, children=None, parent_id=None, parent_uuid=None, size_sort_order=None, shoe_size=None, market=None, upc=None): # noqa: E501\n \"\"\"PortfolioitemsIdGetResponsePortfolioItemProduct - a model defined in Swagger\"\"\" # noqa: E501\n\n self._id = None\n self._uuid = None\n self._brand = None\n self._category = None\n self._charity_condition = None\n self._colorway = None\n self._condition = None\n self._country_of_manufacture = None\n self._gender = None\n self._content_group = None\n self._minimum_bid = None\n self._media = None\n self._name = None\n self._primary_category = None\n self._secondary_category = None\n self._product_category = None\n self._release_date = None\n self._retail_price = None\n self._shoe = None\n self._short_description = None\n self._style_id = None\n self._ticker_symbol = None\n self._title = None\n self._data_type = None\n self._type = None\n self._size_title = None\n self._size_descriptor = None\n self._size_all_descriptor = None\n self._url_key = None\n self._year = None\n self._shipping_group = None\n self._a_lim = None\n self._meta = None\n self._shipping = None\n self._children = None\n self._parent_id = None\n self._parent_uuid = None\n self._size_sort_order = None\n self._shoe_size = None\n self._market = None\n self._upc = None\n self.discriminator = None\n\n self.id = id\n self.uuid = uuid\n self.brand = brand\n self.category = category\n self.charity_condition = charity_condition\n self.colorway = colorway\n self.condition = condition\n self.country_of_manufacture = country_of_manufacture\n self.gender = gender\n self.content_group = content_group\n self.minimum_bid = minimum_bid\n self.media = media\n self.name = name\n self.primary_category = primary_category\n self.secondary_category = secondary_category\n self.product_category = product_category\n self.release_date = release_date\n self.retail_price = retail_price\n self.shoe = shoe\n self.short_description = short_description\n self.style_id = style_id\n self.ticker_symbol = ticker_symbol\n self.title = title\n self.data_type = data_type\n self.type = type\n self.size_title = size_title\n self.size_descriptor = size_descriptor\n self.size_all_descriptor = size_all_descriptor\n self.url_key = url_key\n self.year = year\n self.shipping_group = shipping_group\n self.a_lim = a_lim\n self.meta = meta\n self.shipping = shipping\n self.children = children\n self.parent_id = parent_id\n self.parent_uuid = parent_uuid\n self.size_sort_order = size_sort_order\n self.shoe_size = shoe_size\n self.market = market\n self.upc = upc\n\n @property\n def id(self):\n \"\"\"Gets the id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id):\n \"\"\"Sets the id of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param id: The id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if id is None:\n raise ValueError(\"Invalid value for `id`, must not be `None`\") # noqa: E501\n\n self._id = id\n\n @property\n def uuid(self):\n \"\"\"Gets the uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._uuid\n\n @uuid.setter\n def uuid(self, uuid):\n \"\"\"Sets the uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param uuid: The uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if uuid is None:\n raise ValueError(\"Invalid value for `uuid`, must not be `None`\") # noqa: E501\n\n self._uuid = uuid\n\n @property\n def brand(self):\n \"\"\"Gets the brand of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The brand of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._brand\n\n @brand.setter\n def brand(self, brand):\n \"\"\"Sets the brand of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param brand: The brand of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if brand is None:\n raise ValueError(\"Invalid value for `brand`, must not be `None`\") # noqa: E501\n\n self._brand = brand\n\n @property\n def category(self):\n \"\"\"Gets the category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._category\n\n @category.setter\n def category(self, category):\n \"\"\"Sets the category of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param category: The category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if category is None:\n raise ValueError(\"Invalid value for `category`, must not be `None`\") # noqa: E501\n\n self._category = category\n\n @property\n def charity_condition(self):\n \"\"\"Gets the charity_condition of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The charity_condition of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: int\n \"\"\"\n return self._charity_condition\n\n @charity_condition.setter\n def charity_condition(self, charity_condition):\n \"\"\"Sets the charity_condition of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param charity_condition: The charity_condition of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: int\n \"\"\"\n if charity_condition is None:\n raise ValueError(\"Invalid value for `charity_condition`, must not be `None`\") # noqa: E501\n\n self._charity_condition = charity_condition\n\n @property\n def colorway(self):\n \"\"\"Gets the colorway of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The colorway of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._colorway\n\n @colorway.setter\n def colorway(self, colorway):\n \"\"\"Sets the colorway of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param colorway: The colorway of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if colorway is None:\n raise ValueError(\"Invalid value for `colorway`, must not be `None`\") # noqa: E501\n\n self._colorway = colorway\n\n @property\n def condition(self):\n \"\"\"Gets the condition of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The condition of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._condition\n\n @condition.setter\n def condition(self, condition):\n \"\"\"Sets the condition of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param condition: The condition of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if condition is None:\n raise ValueError(\"Invalid value for `condition`, must not be `None`\") # noqa: E501\n\n self._condition = condition\n\n @property\n def country_of_manufacture(self):\n \"\"\"Gets the country_of_manufacture of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The country_of_manufacture of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._country_of_manufacture\n\n @country_of_manufacture.setter\n def country_of_manufacture(self, country_of_manufacture):\n \"\"\"Sets the country_of_manufacture of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param country_of_manufacture: The country_of_manufacture of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if country_of_manufacture is None:\n raise ValueError(\"Invalid value for `country_of_manufacture`, must not be `None`\") # noqa: E501\n\n self._country_of_manufacture = country_of_manufacture\n\n @property\n def gender(self):\n \"\"\"Gets the gender of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The gender of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._gender\n\n @gender.setter\n def gender(self, gender):\n \"\"\"Sets the gender of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param gender: The gender of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if gender is None:\n raise ValueError(\"Invalid value for `gender`, must not be `None`\") # noqa: E501\n\n self._gender = gender\n\n @property\n def content_group(self):\n \"\"\"Gets the content_group of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The content_group of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._content_group\n\n @content_group.setter\n def content_group(self, content_group):\n \"\"\"Sets the content_group of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param content_group: The content_group of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if content_group is None:\n raise ValueError(\"Invalid value for `content_group`, must not be `None`\") # noqa: E501\n\n self._content_group = content_group\n\n @property\n def minimum_bid(self):\n \"\"\"Gets the minimum_bid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The minimum_bid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: int\n \"\"\"\n return self._minimum_bid\n\n @minimum_bid.setter\n def minimum_bid(self, minimum_bid):\n \"\"\"Sets the minimum_bid of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param minimum_bid: The minimum_bid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: int\n \"\"\"\n if minimum_bid is None:\n raise ValueError(\"Invalid value for `minimum_bid`, must not be `None`\") # noqa: E501\n\n self._minimum_bid = minimum_bid\n\n @property\n def media(self):\n \"\"\"Gets the media of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The media of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: PortfolioIdDelResponsePortfolioItemProductMedia\n \"\"\"\n return self._media\n\n @media.setter\n def media(self, media):\n \"\"\"Sets the media of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param media: The media of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: PortfolioIdDelResponsePortfolioItemProductMedia\n \"\"\"\n if media is None:\n raise ValueError(\"Invalid value for `media`, must not be `None`\") # noqa: E501\n\n self._media = media\n\n @property\n def name(self):\n \"\"\"Gets the name of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The name of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param name: The name of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if name is None:\n raise ValueError(\"Invalid value for `name`, must not be `None`\") # noqa: E501\n\n self._name = name\n\n @property\n def primary_category(self):\n \"\"\"Gets the primary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The primary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._primary_category\n\n @primary_category.setter\n def primary_category(self, primary_category):\n \"\"\"Sets the primary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param primary_category: The primary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if primary_category is None:\n raise ValueError(\"Invalid value for `primary_category`, must not be `None`\") # noqa: E501\n\n self._primary_category = primary_category\n\n @property\n def secondary_category(self):\n \"\"\"Gets the secondary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The secondary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._secondary_category\n\n @secondary_category.setter\n def secondary_category(self, secondary_category):\n \"\"\"Sets the secondary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param secondary_category: The secondary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if secondary_category is None:\n raise ValueError(\"Invalid value for `secondary_category`, must not be `None`\") # noqa: E501\n\n self._secondary_category = secondary_category\n\n @property\n def product_category(self):\n \"\"\"Gets the product_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The product_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._product_category\n\n @product_category.setter\n def product_category(self, product_category):\n \"\"\"Sets the product_category of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param product_category: The product_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if product_category is None:\n raise ValueError(\"Invalid value for `product_category`, must not be `None`\") # noqa: E501\n\n self._product_category = product_category\n\n @property\n def release_date(self):\n \"\"\"Gets the release_date of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The release_date of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._release_date\n\n @release_date.setter\n def release_date(self, release_date):\n \"\"\"Sets the release_date of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param release_date: The release_date of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if release_date is None:\n raise ValueError(\"Invalid value for `release_date`, must not be `None`\") # noqa: E501\n\n self._release_date = release_date\n\n @property\n def retail_price(self):\n \"\"\"Gets the retail_price of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The retail_price of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: int\n \"\"\"\n return self._retail_price\n\n @retail_price.setter\n def retail_price(self, retail_price):\n \"\"\"Sets the retail_price of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param retail_price: The retail_price of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: int\n \"\"\"\n if retail_price is None:\n raise ValueError(\"Invalid value for `retail_price`, must not be `None`\") # noqa: E501\n\n self._retail_price = retail_price\n\n @property\n def shoe(self):\n \"\"\"Gets the shoe of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The shoe of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._shoe\n\n @shoe.setter\n def shoe(self, shoe):\n \"\"\"Sets the shoe of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param shoe: The shoe of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if shoe is None:\n raise ValueError(\"Invalid value for `shoe`, must not be `None`\") # noqa: E501\n\n self._shoe = shoe\n\n @property\n def short_description(self):\n \"\"\"Gets the short_description of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The short_description of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._short_description\n\n @short_description.setter\n def short_description(self, short_description):\n \"\"\"Sets the short_description of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param short_description: The short_description of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if short_description is None:\n raise ValueError(\"Invalid value for `short_description`, must not be `None`\") # noqa: E501\n\n self._short_description = short_description\n\n @property\n def style_id(self):\n \"\"\"Gets the style_id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The style_id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._style_id\n\n @style_id.setter\n def style_id(self, style_id):\n \"\"\"Sets the style_id of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param style_id: The style_id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if style_id is None:\n raise ValueError(\"Invalid value for `style_id`, must not be `None`\") # noqa: E501\n\n self._style_id = style_id\n\n @property\n def ticker_symbol(self):\n \"\"\"Gets the ticker_symbol of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The ticker_symbol of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._ticker_symbol\n\n @ticker_symbol.setter\n def ticker_symbol(self, ticker_symbol):\n \"\"\"Sets the ticker_symbol of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param ticker_symbol: The ticker_symbol of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if ticker_symbol is None:\n raise ValueError(\"Invalid value for `ticker_symbol`, must not be `None`\") # noqa: E501\n\n self._ticker_symbol = ticker_symbol\n\n @property\n def title(self):\n \"\"\"Gets the title of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The title of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._title\n\n @title.setter\n def title(self, title):\n \"\"\"Sets the title of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param title: The title of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if title is None:\n raise ValueError(\"Invalid value for `title`, must not be `None`\") # noqa: E501\n\n self._title = title\n\n @property\n def data_type(self):\n \"\"\"Gets the data_type of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The data_type of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._data_type\n\n @data_type.setter\n def data_type(self, data_type):\n \"\"\"Sets the data_type of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param data_type: The data_type of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if data_type is None:\n raise ValueError(\"Invalid value for `data_type`, must not be `None`\") # noqa: E501\n\n self._data_type = data_type\n\n @property\n def type(self):\n \"\"\"Gets the type of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The type of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: int\n \"\"\"\n return self._type\n\n @type.setter\n def type(self, type):\n \"\"\"Sets the type of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param type: The type of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: int\n \"\"\"\n if type is None:\n raise ValueError(\"Invalid value for `type`, must not be `None`\") # noqa: E501\n\n self._type = type\n\n @property\n def size_title(self):\n \"\"\"Gets the size_title of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The size_title of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._size_title\n\n @size_title.setter\n def size_title(self, size_title):\n \"\"\"Sets the size_title of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param size_title: The size_title of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if size_title is None:\n raise ValueError(\"Invalid value for `size_title`, must not be `None`\") # noqa: E501\n\n self._size_title = size_title\n\n @property\n def size_descriptor(self):\n \"\"\"Gets the size_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The size_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._size_descriptor\n\n @size_descriptor.setter\n def size_descriptor(self, size_descriptor):\n \"\"\"Sets the size_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param size_descriptor: The size_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if size_descriptor is None:\n raise ValueError(\"Invalid value for `size_descriptor`, must not be `None`\") # noqa: E501\n\n self._size_descriptor = size_descriptor\n\n @property\n def size_all_descriptor(self):\n \"\"\"Gets the size_all_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The size_all_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._size_all_descriptor\n\n @size_all_descriptor.setter\n def size_all_descriptor(self, size_all_descriptor):\n \"\"\"Sets the size_all_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param size_all_descriptor: The size_all_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if size_all_descriptor is None:\n raise ValueError(\"Invalid value for `size_all_descriptor`, must not be `None`\") # noqa: E501\n\n self._size_all_descriptor = size_all_descriptor\n\n @property\n def url_key(self):\n \"\"\"Gets the url_key of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The url_key of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._url_key\n\n @url_key.setter\n def url_key(self, url_key):\n \"\"\"Sets the url_key of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param url_key: The url_key of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if url_key is None:\n raise ValueError(\"Invalid value for `url_key`, must not be `None`\") # noqa: E501\n\n self._url_key = url_key\n\n @property\n def year(self):\n \"\"\"Gets the year of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The year of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._year\n\n @year.setter\n def year(self, year):\n \"\"\"Sets the year of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param year: The year of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if year is None:\n raise ValueError(\"Invalid value for `year`, must not be `None`\") # noqa: E501\n\n self._year = year\n\n @property\n def shipping_group(self):\n \"\"\"Gets the shipping_group of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The shipping_group of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._shipping_group\n\n @shipping_group.setter\n def shipping_group(self, shipping_group):\n \"\"\"Sets the shipping_group of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param shipping_group: The shipping_group of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if shipping_group is None:\n raise ValueError(\"Invalid value for `shipping_group`, must not be `None`\") # noqa: E501\n\n self._shipping_group = shipping_group\n\n @property\n def a_lim(self):\n \"\"\"Gets the a_lim of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The a_lim of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: int\n \"\"\"\n return self._a_lim\n\n @a_lim.setter\n def a_lim(self, a_lim):\n \"\"\"Sets the a_lim of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param a_lim: The a_lim of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: int\n \"\"\"\n if a_lim is None:\n raise ValueError(\"Invalid value for `a_lim`, must not be `None`\") # noqa: E501\n\n self._a_lim = a_lim\n\n @property\n def meta(self):\n \"\"\"Gets the meta of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The meta of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: PortfolioIdDelResponsePortfolioItemProductMeta\n \"\"\"\n return self._meta\n\n @meta.setter\n def meta(self, meta):\n \"\"\"Sets the meta of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param meta: The meta of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: PortfolioIdDelResponsePortfolioItemProductMeta\n \"\"\"\n if meta is None:\n raise ValueError(\"Invalid value for `meta`, must not be `None`\") # noqa: E501\n\n self._meta = meta\n\n @property\n def shipping(self):\n \"\"\"Gets the shipping of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The shipping of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: PortfolioIdDelResponsePortfolioItemProductShipping\n \"\"\"\n return self._shipping\n\n @shipping.setter\n def shipping(self, shipping):\n \"\"\"Sets the shipping of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param shipping: The shipping of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: PortfolioIdDelResponsePortfolioItemProductShipping\n \"\"\"\n if shipping is None:\n raise ValueError(\"Invalid value for `shipping`, must not be `None`\") # noqa: E501\n\n self._shipping = shipping\n\n @property\n def children(self):\n \"\"\"Gets the children of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The children of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: object\n \"\"\"\n return self._children\n\n @children.setter\n def children(self, children):\n \"\"\"Sets the children of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param children: The children of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: object\n \"\"\"\n if children is None:\n raise ValueError(\"Invalid value for `children`, must not be `None`\") # noqa: E501\n\n self._children = children\n\n @property\n def parent_id(self):\n \"\"\"Gets the parent_id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The parent_id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._parent_id\n\n @parent_id.setter\n def parent_id(self, parent_id):\n \"\"\"Sets the parent_id of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param parent_id: The parent_id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if parent_id is None:\n raise ValueError(\"Invalid value for `parent_id`, must not be `None`\") # noqa: E501\n\n self._parent_id = parent_id\n\n @property\n def parent_uuid(self):\n \"\"\"Gets the parent_uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The parent_uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._parent_uuid\n\n @parent_uuid.setter\n def parent_uuid(self, parent_uuid):\n \"\"\"Sets the parent_uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param parent_uuid: The parent_uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if parent_uuid is None:\n raise ValueError(\"Invalid value for `parent_uuid`, must not be `None`\") # noqa: E501\n\n self._parent_uuid = parent_uuid\n\n @property\n def size_sort_order(self):\n \"\"\"Gets the size_sort_order of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The size_sort_order of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: int\n \"\"\"\n return self._size_sort_order\n\n @size_sort_order.setter\n def size_sort_order(self, size_sort_order):\n \"\"\"Sets the size_sort_order of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param size_sort_order: The size_sort_order of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: int\n \"\"\"\n if size_sort_order is None:\n raise ValueError(\"Invalid value for `size_sort_order`, must not be `None`\") # noqa: E501\n\n self._size_sort_order = size_sort_order\n\n @property\n def shoe_size(self):\n \"\"\"Gets the shoe_size of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The shoe_size of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._shoe_size\n\n @shoe_size.setter\n def shoe_size(self, shoe_size):\n \"\"\"Sets the shoe_size of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param shoe_size: The shoe_size of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if shoe_size is None:\n raise ValueError(\"Invalid value for `shoe_size`, must not be `None`\") # noqa: E501\n\n self._shoe_size = shoe_size\n\n @property\n def market(self):\n \"\"\"Gets the market of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The market of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: PortfolioitemsIdGetResponsePortfolioItemProductMarket\n \"\"\"\n return self._market\n\n @market.setter\n def market(self, market):\n \"\"\"Sets the market of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param market: The market of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: PortfolioitemsIdGetResponsePortfolioItemProductMarket\n \"\"\"\n if market is None:\n raise ValueError(\"Invalid value for `market`, must not be `None`\") # noqa: E501\n\n self._market = market\n\n @property\n def upc(self):\n \"\"\"Gets the upc of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n\n\n :return: The upc of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :rtype: str\n \"\"\"\n return self._upc\n\n @upc.setter\n def upc(self, upc):\n \"\"\"Sets the upc of this PortfolioitemsIdGetResponsePortfolioItemProduct.\n\n\n :param upc: The upc of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501\n :type: str\n \"\"\"\n if upc is None:\n raise ValueError(\"Invalid value for `upc`, must not be `None`\") # noqa: E501\n\n self._upc = upc\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, PortfolioitemsIdGetResponsePortfolioItemProduct):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.5474137663841248, "alphanum_fraction": 0.5474137663841248, "avg_line_length": 47.511627197265625, "blob_id": "9aab0ccc5980ddfb0a16cd55dd7cf86d9a6583e2", "content_id": "db97f7d502de728b1ad6680078f4c786e16320c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2088, "license_type": "no_license", "max_line_length": 161, "num_lines": 43, "path": "/sdk/python/lib/docs/CustomerObject.md", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# CustomerObject\n\n## Properties\nName | Type | Description | Notes\n------------ | ------------- | ------------- | -------------\n**id** | **str** | | [optional] \n**uuid** | **str** | | [optional] \n**first_name** | **str** | | [optional] \n**last_name** | **str** | | [optional] \n**full_name** | **str** | | [optional] \n**email** | **str** | | [optional] \n**username** | **str** | | [optional] \n**email_verified** | **bool** | | [optional] \n**default_size** | **str** | | [optional] \n**categories** | **list[str]** | | [optional] \n**default_category** | **str** | | [optional] \n**vacation_date** | **str** | | [optional] \n**is_active** | **bool** | | [optional] \n**flagged** | **bool** | | [optional] \n**hide_portfolio_banner** | **bool** | | [optional] \n**refer_url** | **str** | | [optional] \n**created_at** | **str** | | [optional] \n**created_at_time** | **float** | | [optional] \n**is_trader** | **bool** | | [optional] \n**ship_by_date** | **bool** | | [optional] \n**is_buying** | **bool** | | [optional] \n**is_selling** | **bool** | | [optional] \n**billing** | [**BillingObject**](BillingObject.md) | | [optional] \n**shipping** | [**CustomerObjectShipping**](CustomerObjectShipping.md) | | [optional] \n**cc_only** | [**BillingObject**](BillingObject.md) | | [optional] \n**merchant** | [**CustomerObjectMerchant**](CustomerObjectMerchant.md) | | [optional] \n**promotion_code** | **str** | | [optional] \n**paypal_emails** | **str** | | [optional] \n**authorization_method** | **str** | | [optional] \n**security_override** | **bool** | | [optional] \n**team_member** | **bool** | | [optional] \n**password_locked** | **bool** | | [optional] \n**address_normalize_override** | **bool** | | [optional] \n**early_payout_enabled** | **bool** | | [optional] \n**early_payout_eligible** | **bool** | | [optional] \n**security** | [**CustomerObjectSecurity**](CustomerObjectSecurity.md) | | [optional] \n\n[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)\n\n\n" }, { "alpha_fraction": 0.7820512652397156, "alphanum_fraction": 0.7820512652397156, "avg_line_length": 29.64285659790039, "blob_id": "8b419313737626cb7dbc736c296d6387d0fdc601", "content_id": "32bdc3161ef52a4d598254161ffecad0515ffe62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 858, "license_type": "no_license", "max_line_length": 119, "num_lines": 28, "path": "/sdk/php/README.md", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# StockX Public API - PHP Library\n\n## Summary\n\nThis project provides a StockX PHP library for accessing StockX's public API.\n\n## Usage\n\n* Link the supplied PHP composer module to your the project\n* Update the ExampleConstants.php source file to include your API Key (supplied by StockX) and your account credentials\n* Execute the supplied examples in src/ with the php interpreter\n\n### Examples\n\nThis project provides the following examples of using the StockX PHP Library:\n\n* Logging into the StockX API\n* Querying for open orders\n* Querying for market data about a product\n* Looking up product information\n* Searching the product catalog via general queries\n* Placing bids as a buyer\n* Placing asks as a seller\n\n### Directories\n\n/lib - contains a PHP library providing StockX API access\n/src - contains examples of interacting with the StockX API with PHP\n" }, { "alpha_fraction": 0.5789929032325745, "alphanum_fraction": 0.5814154744148254, "avg_line_length": 16.45921516418457, "blob_id": "d0c29214b68532e5eaffdf3fdc834de6eb15e9d2", "content_id": "15dda9d3da34e3329952bc1202279b87645a04f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5779, "license_type": "no_license", "max_line_length": 110, "num_lines": 331, "path": "/sdk/php/StockX-SDK-PHP/lib/test/Model/MarketDataMarketTest.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * MarketDataMarketTest\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Please update the test case below to test the model.\n */\n\nnamespace StockX\\Client;\n\n/**\n * MarketDataMarketTest Class Doc Comment\n *\n * @category Class */\n// * @description MarketDataMarket\n/**\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass MarketDataMarketTest extends \\PHPUnit_Framework_TestCase\n{\n\n /**\n * Setup before running any test case\n */\n public static function setUpBeforeClass()\n {\n }\n\n /**\n * Setup before running each test case\n */\n public function setUp()\n {\n }\n\n /**\n * Clean up after running each test case\n */\n public function tearDown()\n {\n }\n\n /**\n * Clean up after running all test cases\n */\n public static function tearDownAfterClass()\n {\n }\n\n /**\n * Test \"MarketDataMarket\"\n */\n public function testMarketDataMarket()\n {\n }\n\n /**\n * Test attribute \"product_id\"\n */\n public function testPropertyProductId()\n {\n }\n\n /**\n * Test attribute \"sku_uuid\"\n */\n public function testPropertySkuUuid()\n {\n }\n\n /**\n * Test attribute \"product_uuid\"\n */\n public function testPropertyProductUuid()\n {\n }\n\n /**\n * Test attribute \"lowest_ask\"\n */\n public function testPropertyLowestAsk()\n {\n }\n\n /**\n * Test attribute \"lowest_ask_size\"\n */\n public function testPropertyLowestAskSize()\n {\n }\n\n /**\n * Test attribute \"parent_lowest_ask\"\n */\n public function testPropertyParentLowestAsk()\n {\n }\n\n /**\n * Test attribute \"number_of_asks\"\n */\n public function testPropertyNumberOfAsks()\n {\n }\n\n /**\n * Test attribute \"sales_this_period\"\n */\n public function testPropertySalesThisPeriod()\n {\n }\n\n /**\n * Test attribute \"sales_last_period\"\n */\n public function testPropertySalesLastPeriod()\n {\n }\n\n /**\n * Test attribute \"highest_bid\"\n */\n public function testPropertyHighestBid()\n {\n }\n\n /**\n * Test attribute \"highest_bid_size\"\n */\n public function testPropertyHighestBidSize()\n {\n }\n\n /**\n * Test attribute \"number_of_bids\"\n */\n public function testPropertyNumberOfBids()\n {\n }\n\n /**\n * Test attribute \"annual_high\"\n */\n public function testPropertyAnnualHigh()\n {\n }\n\n /**\n * Test attribute \"annual_low\"\n */\n public function testPropertyAnnualLow()\n {\n }\n\n /**\n * Test attribute \"deadstock_range_low\"\n */\n public function testPropertyDeadstockRangeLow()\n {\n }\n\n /**\n * Test attribute \"deadstock_range_high\"\n */\n public function testPropertyDeadstockRangeHigh()\n {\n }\n\n /**\n * Test attribute \"volatility\"\n */\n public function testPropertyVolatility()\n {\n }\n\n /**\n * Test attribute \"deadstock_sold\"\n */\n public function testPropertyDeadstockSold()\n {\n }\n\n /**\n * Test attribute \"price_premium\"\n */\n public function testPropertyPricePremium()\n {\n }\n\n /**\n * Test attribute \"average_deadstock_price\"\n */\n public function testPropertyAverageDeadstockPrice()\n {\n }\n\n /**\n * Test attribute \"last_sale\"\n */\n public function testPropertyLastSale()\n {\n }\n\n /**\n * Test attribute \"last_sale_size\"\n */\n public function testPropertyLastSaleSize()\n {\n }\n\n /**\n * Test attribute \"sales_last72_hours\"\n */\n public function testPropertySalesLast72Hours()\n {\n }\n\n /**\n * Test attribute \"change_value\"\n */\n public function testPropertyChangeValue()\n {\n }\n\n /**\n * Test attribute \"change_percentage\"\n */\n public function testPropertyChangePercentage()\n {\n }\n\n /**\n * Test attribute \"abs_change_percentage\"\n */\n public function testPropertyAbsChangePercentage()\n {\n }\n\n /**\n * Test attribute \"total_dollars\"\n */\n public function testPropertyTotalDollars()\n {\n }\n\n /**\n * Test attribute \"updated_at\"\n */\n public function testPropertyUpdatedAt()\n {\n }\n\n /**\n * Test attribute \"last_lowest_ask_time\"\n */\n public function testPropertyLastLowestAskTime()\n {\n }\n\n /**\n * Test attribute \"last_highest_bid_time\"\n */\n public function testPropertyLastHighestBidTime()\n {\n }\n\n /**\n * Test attribute \"last_sale_date\"\n */\n public function testPropertyLastSaleDate()\n {\n }\n\n /**\n * Test attribute \"created_at\"\n */\n public function testPropertyCreatedAt()\n {\n }\n\n /**\n * Test attribute \"deadstock_sold_rank\"\n */\n public function testPropertyDeadstockSoldRank()\n {\n }\n\n /**\n * Test attribute \"price_premium_rank\"\n */\n public function testPropertyPricePremiumRank()\n {\n }\n\n /**\n * Test attribute \"average_deadstock_price_rank\"\n */\n public function testPropertyAverageDeadstockPriceRank()\n {\n }\n\n /**\n * Test attribute \"featured\"\n */\n public function testPropertyFeatured()\n {\n }\n}\n" }, { "alpha_fraction": 0.5830118656158447, "alphanum_fraction": 0.5954314470291138, "avg_line_length": 27.77312469482422, "blob_id": "b4e137e5143953f100bd4a85f44d01140b9ea212", "content_id": "644cd6764839060791d609f8e7e4ee76839bbc32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29550, "license_type": "no_license", "max_line_length": 707, "num_lines": 1027, "path": "/sdk/python/lib/io_stockx/models/customer_object.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom io_stockx.models.billing_object import BillingObject # noqa: F401,E501\nfrom io_stockx.models.customer_object_merchant import CustomerObjectMerchant # noqa: F401,E501\nfrom io_stockx.models.customer_object_security import CustomerObjectSecurity # noqa: F401,E501\nfrom io_stockx.models.customer_object_shipping import CustomerObjectShipping # noqa: F401,E501\n\n\nclass CustomerObject(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'id': 'str',\n 'uuid': 'str',\n 'first_name': 'str',\n 'last_name': 'str',\n 'full_name': 'str',\n 'email': 'str',\n 'username': 'str',\n 'email_verified': 'bool',\n 'default_size': 'str',\n 'categories': 'list[str]',\n 'default_category': 'str',\n 'vacation_date': 'str',\n 'is_active': 'bool',\n 'flagged': 'bool',\n 'hide_portfolio_banner': 'bool',\n 'refer_url': 'str',\n 'created_at': 'str',\n 'created_at_time': 'float',\n 'is_trader': 'bool',\n 'ship_by_date': 'bool',\n 'is_buying': 'bool',\n 'is_selling': 'bool',\n 'billing': 'BillingObject',\n 'shipping': 'CustomerObjectShipping',\n 'cc_only': 'BillingObject',\n 'merchant': 'CustomerObjectMerchant',\n 'promotion_code': 'str',\n 'paypal_emails': 'str',\n 'authorization_method': 'str',\n 'security_override': 'bool',\n 'team_member': 'bool',\n 'password_locked': 'bool',\n 'address_normalize_override': 'bool',\n 'early_payout_enabled': 'bool',\n 'early_payout_eligible': 'bool',\n 'security': 'CustomerObjectSecurity'\n }\n\n attribute_map = {\n 'id': 'id',\n 'uuid': 'uuid',\n 'first_name': 'firstName',\n 'last_name': 'lastName',\n 'full_name': 'fullName',\n 'email': 'email',\n 'username': 'username',\n 'email_verified': 'emailVerified',\n 'default_size': 'defaultSize',\n 'categories': 'categories',\n 'default_category': 'defaultCategory',\n 'vacation_date': 'vacationDate',\n 'is_active': 'isActive',\n 'flagged': 'flagged',\n 'hide_portfolio_banner': 'hidePortfolioBanner',\n 'refer_url': 'referUrl',\n 'created_at': 'createdAt',\n 'created_at_time': 'createdAtTime',\n 'is_trader': 'isTrader',\n 'ship_by_date': 'shipByDate',\n 'is_buying': 'isBuying',\n 'is_selling': 'isSelling',\n 'billing': 'Billing',\n 'shipping': 'Shipping',\n 'cc_only': 'CCOnly',\n 'merchant': 'Merchant',\n 'promotion_code': 'promotionCode',\n 'paypal_emails': 'paypalEmails',\n 'authorization_method': 'authorizationMethod',\n 'security_override': 'securityOverride',\n 'team_member': 'teamMember',\n 'password_locked': 'passwordLocked',\n 'address_normalize_override': 'addressNormalizeOverride',\n 'early_payout_enabled': 'earlyPayoutEnabled',\n 'early_payout_eligible': 'earlyPayoutEligible',\n 'security': 'security'\n }\n\n def __init__(self, id=None, uuid=None, first_name=None, last_name=None, full_name=None, email=None, username=None, email_verified=None, default_size=None, categories=None, default_category=None, vacation_date=None, is_active=None, flagged=None, hide_portfolio_banner=None, refer_url=None, created_at=None, created_at_time=None, is_trader=None, ship_by_date=None, is_buying=None, is_selling=None, billing=None, shipping=None, cc_only=None, merchant=None, promotion_code=None, paypal_emails=None, authorization_method=None, security_override=None, team_member=None, password_locked=None, address_normalize_override=None, early_payout_enabled=None, early_payout_eligible=None, security=None): # noqa: E501\n \"\"\"CustomerObject - a model defined in Swagger\"\"\" # noqa: E501\n\n self._id = None\n self._uuid = None\n self._first_name = None\n self._last_name = None\n self._full_name = None\n self._email = None\n self._username = None\n self._email_verified = None\n self._default_size = None\n self._categories = None\n self._default_category = None\n self._vacation_date = None\n self._is_active = None\n self._flagged = None\n self._hide_portfolio_banner = None\n self._refer_url = None\n self._created_at = None\n self._created_at_time = None\n self._is_trader = None\n self._ship_by_date = None\n self._is_buying = None\n self._is_selling = None\n self._billing = None\n self._shipping = None\n self._cc_only = None\n self._merchant = None\n self._promotion_code = None\n self._paypal_emails = None\n self._authorization_method = None\n self._security_override = None\n self._team_member = None\n self._password_locked = None\n self._address_normalize_override = None\n self._early_payout_enabled = None\n self._early_payout_eligible = None\n self._security = None\n self.discriminator = None\n\n if id is not None:\n self.id = id\n if uuid is not None:\n self.uuid = uuid\n if first_name is not None:\n self.first_name = first_name\n if last_name is not None:\n self.last_name = last_name\n if full_name is not None:\n self.full_name = full_name\n if email is not None:\n self.email = email\n if username is not None:\n self.username = username\n if email_verified is not None:\n self.email_verified = email_verified\n if default_size is not None:\n self.default_size = default_size\n if categories is not None:\n self.categories = categories\n if default_category is not None:\n self.default_category = default_category\n if vacation_date is not None:\n self.vacation_date = vacation_date\n if is_active is not None:\n self.is_active = is_active\n if flagged is not None:\n self.flagged = flagged\n if hide_portfolio_banner is not None:\n self.hide_portfolio_banner = hide_portfolio_banner\n if refer_url is not None:\n self.refer_url = refer_url\n if created_at is not None:\n self.created_at = created_at\n if created_at_time is not None:\n self.created_at_time = created_at_time\n if is_trader is not None:\n self.is_trader = is_trader\n if ship_by_date is not None:\n self.ship_by_date = ship_by_date\n if is_buying is not None:\n self.is_buying = is_buying\n if is_selling is not None:\n self.is_selling = is_selling\n if billing is not None:\n self.billing = billing\n if shipping is not None:\n self.shipping = shipping\n if cc_only is not None:\n self.cc_only = cc_only\n if merchant is not None:\n self.merchant = merchant\n if promotion_code is not None:\n self.promotion_code = promotion_code\n if paypal_emails is not None:\n self.paypal_emails = paypal_emails\n if authorization_method is not None:\n self.authorization_method = authorization_method\n if security_override is not None:\n self.security_override = security_override\n if team_member is not None:\n self.team_member = team_member\n if password_locked is not None:\n self.password_locked = password_locked\n if address_normalize_override is not None:\n self.address_normalize_override = address_normalize_override\n if early_payout_enabled is not None:\n self.early_payout_enabled = early_payout_enabled\n if early_payout_eligible is not None:\n self.early_payout_eligible = early_payout_eligible\n if security is not None:\n self.security = security\n\n @property\n def id(self):\n \"\"\"Gets the id of this CustomerObject. # noqa: E501\n\n\n :return: The id of this CustomerObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id):\n \"\"\"Sets the id of this CustomerObject.\n\n\n :param id: The id of this CustomerObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._id = id\n\n @property\n def uuid(self):\n \"\"\"Gets the uuid of this CustomerObject. # noqa: E501\n\n\n :return: The uuid of this CustomerObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._uuid\n\n @uuid.setter\n def uuid(self, uuid):\n \"\"\"Sets the uuid of this CustomerObject.\n\n\n :param uuid: The uuid of this CustomerObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._uuid = uuid\n\n @property\n def first_name(self):\n \"\"\"Gets the first_name of this CustomerObject. # noqa: E501\n\n\n :return: The first_name of this CustomerObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._first_name\n\n @first_name.setter\n def first_name(self, first_name):\n \"\"\"Sets the first_name of this CustomerObject.\n\n\n :param first_name: The first_name of this CustomerObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._first_name = first_name\n\n @property\n def last_name(self):\n \"\"\"Gets the last_name of this CustomerObject. # noqa: E501\n\n\n :return: The last_name of this CustomerObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._last_name\n\n @last_name.setter\n def last_name(self, last_name):\n \"\"\"Sets the last_name of this CustomerObject.\n\n\n :param last_name: The last_name of this CustomerObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._last_name = last_name\n\n @property\n def full_name(self):\n \"\"\"Gets the full_name of this CustomerObject. # noqa: E501\n\n\n :return: The full_name of this CustomerObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._full_name\n\n @full_name.setter\n def full_name(self, full_name):\n \"\"\"Sets the full_name of this CustomerObject.\n\n\n :param full_name: The full_name of this CustomerObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._full_name = full_name\n\n @property\n def email(self):\n \"\"\"Gets the email of this CustomerObject. # noqa: E501\n\n\n :return: The email of this CustomerObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._email\n\n @email.setter\n def email(self, email):\n \"\"\"Sets the email of this CustomerObject.\n\n\n :param email: The email of this CustomerObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._email = email\n\n @property\n def username(self):\n \"\"\"Gets the username of this CustomerObject. # noqa: E501\n\n\n :return: The username of this CustomerObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._username\n\n @username.setter\n def username(self, username):\n \"\"\"Sets the username of this CustomerObject.\n\n\n :param username: The username of this CustomerObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._username = username\n\n @property\n def email_verified(self):\n \"\"\"Gets the email_verified of this CustomerObject. # noqa: E501\n\n\n :return: The email_verified of this CustomerObject. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._email_verified\n\n @email_verified.setter\n def email_verified(self, email_verified):\n \"\"\"Sets the email_verified of this CustomerObject.\n\n\n :param email_verified: The email_verified of this CustomerObject. # noqa: E501\n :type: bool\n \"\"\"\n\n self._email_verified = email_verified\n\n @property\n def default_size(self):\n \"\"\"Gets the default_size of this CustomerObject. # noqa: E501\n\n\n :return: The default_size of this CustomerObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._default_size\n\n @default_size.setter\n def default_size(self, default_size):\n \"\"\"Sets the default_size of this CustomerObject.\n\n\n :param default_size: The default_size of this CustomerObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._default_size = default_size\n\n @property\n def categories(self):\n \"\"\"Gets the categories of this CustomerObject. # noqa: E501\n\n\n :return: The categories of this CustomerObject. # noqa: E501\n :rtype: list[str]\n \"\"\"\n return self._categories\n\n @categories.setter\n def categories(self, categories):\n \"\"\"Sets the categories of this CustomerObject.\n\n\n :param categories: The categories of this CustomerObject. # noqa: E501\n :type: list[str]\n \"\"\"\n\n self._categories = categories\n\n @property\n def default_category(self):\n \"\"\"Gets the default_category of this CustomerObject. # noqa: E501\n\n\n :return: The default_category of this CustomerObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._default_category\n\n @default_category.setter\n def default_category(self, default_category):\n \"\"\"Sets the default_category of this CustomerObject.\n\n\n :param default_category: The default_category of this CustomerObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._default_category = default_category\n\n @property\n def vacation_date(self):\n \"\"\"Gets the vacation_date of this CustomerObject. # noqa: E501\n\n\n :return: The vacation_date of this CustomerObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._vacation_date\n\n @vacation_date.setter\n def vacation_date(self, vacation_date):\n \"\"\"Sets the vacation_date of this CustomerObject.\n\n\n :param vacation_date: The vacation_date of this CustomerObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._vacation_date = vacation_date\n\n @property\n def is_active(self):\n \"\"\"Gets the is_active of this CustomerObject. # noqa: E501\n\n\n :return: The is_active of this CustomerObject. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._is_active\n\n @is_active.setter\n def is_active(self, is_active):\n \"\"\"Sets the is_active of this CustomerObject.\n\n\n :param is_active: The is_active of this CustomerObject. # noqa: E501\n :type: bool\n \"\"\"\n\n self._is_active = is_active\n\n @property\n def flagged(self):\n \"\"\"Gets the flagged of this CustomerObject. # noqa: E501\n\n\n :return: The flagged of this CustomerObject. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._flagged\n\n @flagged.setter\n def flagged(self, flagged):\n \"\"\"Sets the flagged of this CustomerObject.\n\n\n :param flagged: The flagged of this CustomerObject. # noqa: E501\n :type: bool\n \"\"\"\n\n self._flagged = flagged\n\n @property\n def hide_portfolio_banner(self):\n \"\"\"Gets the hide_portfolio_banner of this CustomerObject. # noqa: E501\n\n\n :return: The hide_portfolio_banner of this CustomerObject. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._hide_portfolio_banner\n\n @hide_portfolio_banner.setter\n def hide_portfolio_banner(self, hide_portfolio_banner):\n \"\"\"Sets the hide_portfolio_banner of this CustomerObject.\n\n\n :param hide_portfolio_banner: The hide_portfolio_banner of this CustomerObject. # noqa: E501\n :type: bool\n \"\"\"\n\n self._hide_portfolio_banner = hide_portfolio_banner\n\n @property\n def refer_url(self):\n \"\"\"Gets the refer_url of this CustomerObject. # noqa: E501\n\n\n :return: The refer_url of this CustomerObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._refer_url\n\n @refer_url.setter\n def refer_url(self, refer_url):\n \"\"\"Sets the refer_url of this CustomerObject.\n\n\n :param refer_url: The refer_url of this CustomerObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._refer_url = refer_url\n\n @property\n def created_at(self):\n \"\"\"Gets the created_at of this CustomerObject. # noqa: E501\n\n\n :return: The created_at of this CustomerObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._created_at\n\n @created_at.setter\n def created_at(self, created_at):\n \"\"\"Sets the created_at of this CustomerObject.\n\n\n :param created_at: The created_at of this CustomerObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._created_at = created_at\n\n @property\n def created_at_time(self):\n \"\"\"Gets the created_at_time of this CustomerObject. # noqa: E501\n\n\n :return: The created_at_time of this CustomerObject. # noqa: E501\n :rtype: float\n \"\"\"\n return self._created_at_time\n\n @created_at_time.setter\n def created_at_time(self, created_at_time):\n \"\"\"Sets the created_at_time of this CustomerObject.\n\n\n :param created_at_time: The created_at_time of this CustomerObject. # noqa: E501\n :type: float\n \"\"\"\n\n self._created_at_time = created_at_time\n\n @property\n def is_trader(self):\n \"\"\"Gets the is_trader of this CustomerObject. # noqa: E501\n\n\n :return: The is_trader of this CustomerObject. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._is_trader\n\n @is_trader.setter\n def is_trader(self, is_trader):\n \"\"\"Sets the is_trader of this CustomerObject.\n\n\n :param is_trader: The is_trader of this CustomerObject. # noqa: E501\n :type: bool\n \"\"\"\n\n self._is_trader = is_trader\n\n @property\n def ship_by_date(self):\n \"\"\"Gets the ship_by_date of this CustomerObject. # noqa: E501\n\n\n :return: The ship_by_date of this CustomerObject. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._ship_by_date\n\n @ship_by_date.setter\n def ship_by_date(self, ship_by_date):\n \"\"\"Sets the ship_by_date of this CustomerObject.\n\n\n :param ship_by_date: The ship_by_date of this CustomerObject. # noqa: E501\n :type: bool\n \"\"\"\n\n self._ship_by_date = ship_by_date\n\n @property\n def is_buying(self):\n \"\"\"Gets the is_buying of this CustomerObject. # noqa: E501\n\n\n :return: The is_buying of this CustomerObject. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._is_buying\n\n @is_buying.setter\n def is_buying(self, is_buying):\n \"\"\"Sets the is_buying of this CustomerObject.\n\n\n :param is_buying: The is_buying of this CustomerObject. # noqa: E501\n :type: bool\n \"\"\"\n\n self._is_buying = is_buying\n\n @property\n def is_selling(self):\n \"\"\"Gets the is_selling of this CustomerObject. # noqa: E501\n\n\n :return: The is_selling of this CustomerObject. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._is_selling\n\n @is_selling.setter\n def is_selling(self, is_selling):\n \"\"\"Sets the is_selling of this CustomerObject.\n\n\n :param is_selling: The is_selling of this CustomerObject. # noqa: E501\n :type: bool\n \"\"\"\n\n self._is_selling = is_selling\n\n @property\n def billing(self):\n \"\"\"Gets the billing of this CustomerObject. # noqa: E501\n\n\n :return: The billing of this CustomerObject. # noqa: E501\n :rtype: BillingObject\n \"\"\"\n return self._billing\n\n @billing.setter\n def billing(self, billing):\n \"\"\"Sets the billing of this CustomerObject.\n\n\n :param billing: The billing of this CustomerObject. # noqa: E501\n :type: BillingObject\n \"\"\"\n\n self._billing = billing\n\n @property\n def shipping(self):\n \"\"\"Gets the shipping of this CustomerObject. # noqa: E501\n\n\n :return: The shipping of this CustomerObject. # noqa: E501\n :rtype: CustomerObjectShipping\n \"\"\"\n return self._shipping\n\n @shipping.setter\n def shipping(self, shipping):\n \"\"\"Sets the shipping of this CustomerObject.\n\n\n :param shipping: The shipping of this CustomerObject. # noqa: E501\n :type: CustomerObjectShipping\n \"\"\"\n\n self._shipping = shipping\n\n @property\n def cc_only(self):\n \"\"\"Gets the cc_only of this CustomerObject. # noqa: E501\n\n\n :return: The cc_only of this CustomerObject. # noqa: E501\n :rtype: BillingObject\n \"\"\"\n return self._cc_only\n\n @cc_only.setter\n def cc_only(self, cc_only):\n \"\"\"Sets the cc_only of this CustomerObject.\n\n\n :param cc_only: The cc_only of this CustomerObject. # noqa: E501\n :type: BillingObject\n \"\"\"\n\n self._cc_only = cc_only\n\n @property\n def merchant(self):\n \"\"\"Gets the merchant of this CustomerObject. # noqa: E501\n\n\n :return: The merchant of this CustomerObject. # noqa: E501\n :rtype: CustomerObjectMerchant\n \"\"\"\n return self._merchant\n\n @merchant.setter\n def merchant(self, merchant):\n \"\"\"Sets the merchant of this CustomerObject.\n\n\n :param merchant: The merchant of this CustomerObject. # noqa: E501\n :type: CustomerObjectMerchant\n \"\"\"\n\n self._merchant = merchant\n\n @property\n def promotion_code(self):\n \"\"\"Gets the promotion_code of this CustomerObject. # noqa: E501\n\n\n :return: The promotion_code of this CustomerObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._promotion_code\n\n @promotion_code.setter\n def promotion_code(self, promotion_code):\n \"\"\"Sets the promotion_code of this CustomerObject.\n\n\n :param promotion_code: The promotion_code of this CustomerObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._promotion_code = promotion_code\n\n @property\n def paypal_emails(self):\n \"\"\"Gets the paypal_emails of this CustomerObject. # noqa: E501\n\n\n :return: The paypal_emails of this CustomerObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._paypal_emails\n\n @paypal_emails.setter\n def paypal_emails(self, paypal_emails):\n \"\"\"Sets the paypal_emails of this CustomerObject.\n\n\n :param paypal_emails: The paypal_emails of this CustomerObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._paypal_emails = paypal_emails\n\n @property\n def authorization_method(self):\n \"\"\"Gets the authorization_method of this CustomerObject. # noqa: E501\n\n\n :return: The authorization_method of this CustomerObject. # noqa: E501\n :rtype: str\n \"\"\"\n return self._authorization_method\n\n @authorization_method.setter\n def authorization_method(self, authorization_method):\n \"\"\"Sets the authorization_method of this CustomerObject.\n\n\n :param authorization_method: The authorization_method of this CustomerObject. # noqa: E501\n :type: str\n \"\"\"\n\n self._authorization_method = authorization_method\n\n @property\n def security_override(self):\n \"\"\"Gets the security_override of this CustomerObject. # noqa: E501\n\n\n :return: The security_override of this CustomerObject. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._security_override\n\n @security_override.setter\n def security_override(self, security_override):\n \"\"\"Sets the security_override of this CustomerObject.\n\n\n :param security_override: The security_override of this CustomerObject. # noqa: E501\n :type: bool\n \"\"\"\n\n self._security_override = security_override\n\n @property\n def team_member(self):\n \"\"\"Gets the team_member of this CustomerObject. # noqa: E501\n\n\n :return: The team_member of this CustomerObject. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._team_member\n\n @team_member.setter\n def team_member(self, team_member):\n \"\"\"Sets the team_member of this CustomerObject.\n\n\n :param team_member: The team_member of this CustomerObject. # noqa: E501\n :type: bool\n \"\"\"\n\n self._team_member = team_member\n\n @property\n def password_locked(self):\n \"\"\"Gets the password_locked of this CustomerObject. # noqa: E501\n\n\n :return: The password_locked of this CustomerObject. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._password_locked\n\n @password_locked.setter\n def password_locked(self, password_locked):\n \"\"\"Sets the password_locked of this CustomerObject.\n\n\n :param password_locked: The password_locked of this CustomerObject. # noqa: E501\n :type: bool\n \"\"\"\n\n self._password_locked = password_locked\n\n @property\n def address_normalize_override(self):\n \"\"\"Gets the address_normalize_override of this CustomerObject. # noqa: E501\n\n\n :return: The address_normalize_override of this CustomerObject. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._address_normalize_override\n\n @address_normalize_override.setter\n def address_normalize_override(self, address_normalize_override):\n \"\"\"Sets the address_normalize_override of this CustomerObject.\n\n\n :param address_normalize_override: The address_normalize_override of this CustomerObject. # noqa: E501\n :type: bool\n \"\"\"\n\n self._address_normalize_override = address_normalize_override\n\n @property\n def early_payout_enabled(self):\n \"\"\"Gets the early_payout_enabled of this CustomerObject. # noqa: E501\n\n\n :return: The early_payout_enabled of this CustomerObject. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._early_payout_enabled\n\n @early_payout_enabled.setter\n def early_payout_enabled(self, early_payout_enabled):\n \"\"\"Sets the early_payout_enabled of this CustomerObject.\n\n\n :param early_payout_enabled: The early_payout_enabled of this CustomerObject. # noqa: E501\n :type: bool\n \"\"\"\n\n self._early_payout_enabled = early_payout_enabled\n\n @property\n def early_payout_eligible(self):\n \"\"\"Gets the early_payout_eligible of this CustomerObject. # noqa: E501\n\n\n :return: The early_payout_eligible of this CustomerObject. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._early_payout_eligible\n\n @early_payout_eligible.setter\n def early_payout_eligible(self, early_payout_eligible):\n \"\"\"Sets the early_payout_eligible of this CustomerObject.\n\n\n :param early_payout_eligible: The early_payout_eligible of this CustomerObject. # noqa: E501\n :type: bool\n \"\"\"\n\n self._early_payout_eligible = early_payout_eligible\n\n @property\n def security(self):\n \"\"\"Gets the security of this CustomerObject. # noqa: E501\n\n\n :return: The security of this CustomerObject. # noqa: E501\n :rtype: CustomerObjectSecurity\n \"\"\"\n return self._security\n\n @security.setter\n def security(self, security):\n \"\"\"Sets the security of this CustomerObject.\n\n\n :param security: The security of this CustomerObject. # noqa: E501\n :type: CustomerObjectSecurity\n \"\"\"\n\n self._security = security\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, CustomerObject):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.5411954522132874, "alphanum_fraction": 0.5444265007972717, "avg_line_length": 29.899999618530273, "blob_id": "20a385e06c8089673e56dd6d5f34c50706edaa2e", "content_id": "64a1027447b08dd12b9a8d5ce44e1454d6b326e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 619, "license_type": "no_license", "max_line_length": 88, "num_lines": 20, "path": "/sdk/php/StockX-SDK-PHP/src/LoginUtil.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n\nclass LoginUtil {\n \n public static function login($api, $headerSelector, $username, $password) {\n $login = new \\StockX\\Client\\Model\\LoginRequest();\n $login->setEmail($username);\n $login->setPassword($password);\n \n try {\n $result = $api->loginWithHttpInfo($login);\n $jwtHeader = $result[2][\"Jwt-Authorization\"][0];\n $headerSelector->setToken($jwtHeader);\n \n return $result;\n } catch (Exception $e) {\n echo 'Exception when calling StockXApi->login: ', $e->getMessage(), PHP_EOL;\n }\n }\n}\n\n" }, { "alpha_fraction": 0.6936238408088684, "alphanum_fraction": 0.6945168972015381, "avg_line_length": 30.99314308166504, "blob_id": "74480bff4f8abb8201f9a584bfed9f4e4e4b7e62", "content_id": "c3c12b07a244969d1652fcfdacadb3cd3b44cd9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27995, "license_type": "no_license", "max_line_length": 180, "num_lines": 875, "path": "/sdk/python/lib/docs/StockXApi.md", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# io_stockx.StockXApi\n\nAll URIs are relative to *https://gateway.stockx.com/public*\n\nMethod | HTTP request | Description\n------------- | ------------- | -------------\n[**delete_portfolio**](StockXApi.md#delete_portfolio) | **DELETE** /v1/portfolio/{id} | Deletes a portfolio item from the market with the specified id.\n[**delete_webhook**](StockXApi.md#delete_webhook) | **DELETE** /webhook/v1/webhooks/{id} | \n[**get_open_orders**](StockXApi.md#get_open_orders) | **GET** /v1/customers/{id}/selling/current | \n[**get_portfolio**](StockXApi.md#get_portfolio) | **POST** /v1/portfolio | Returns a market portfolio identified by request parameters.\n[**get_portfolio_item**](StockXApi.md#get_portfolio_item) | **GET** /v1/portfolioitems/{id} | \n[**get_product_by_id**](StockXApi.md#get_product_by_id) | **GET** /v1/products/{id} | \n[**get_product_market_data**](StockXApi.md#get_product_market_data) | **GET** /v1/products/{productId}/market | Provides historical market data for a given product.\n[**get_subscriptions**](StockXApi.md#get_subscriptions) | **GET** /webhook/v1/subscriptions | \n[**get_webhook**](StockXApi.md#get_webhook) | **GET** /webhook/v1/webhooks/{id} | \n[**get_webhooks**](StockXApi.md#get_webhooks) | **GET** /webhook/v1/webhooks | \n[**login**](StockXApi.md#login) | **POST** /v1/login | Attempts to log the user in with a username and password.\n[**lookup_product**](StockXApi.md#lookup_product) | **GET** /product/lookup | \n[**new_portfolio_ask**](StockXApi.md#new_portfolio_ask) | **POST** /v1/portfolio/ask | Creates a new seller ask on the market for a given product.\n[**new_portfolio_bid**](StockXApi.md#new_portfolio_bid) | **POST** /v1/portfolio/bid | Creates a new buyer bid on the market for a given product.\n[**post_webhooks**](StockXApi.md#post_webhooks) | **POST** /webhook/v1/webhooks | \n[**search**](StockXApi.md#search) | **GET** /v2/search | Searches for products by keyword.\n\n\n# **delete_portfolio**\n> PortfolioIdDelResponse delete_portfolio(id, portfolio)\n\nDeletes a portfolio item from the market with the specified id.\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nid = 'id_example' # str | The id of the portfolio item to delete.\nportfolio = io_stockx.PortfolioIdDelRequest() # PortfolioIdDelRequest | The request information for the portfolio delete operation.\n\ntry:\n # Deletes a portfolio item from the market with the specified id.\n api_response = api_instance.delete_portfolio(id, portfolio)\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->delete_portfolio: %s\\n\" % e)\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **id** | **str**| The id of the portfolio item to delete. | \n **portfolio** | [**PortfolioIdDelRequest**](PortfolioIdDelRequest.md)| The request information for the portfolio delete operation. | \n\n### Return type\n\n[**PortfolioIdDelResponse**](PortfolioIdDelResponse.md)\n\n### Authorization\n\n[api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n# **delete_webhook**\n> delete_webhook(id)\n\n\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nid = 'id_example' # str | \n\ntry:\n api_instance.delete_webhook(id)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->delete_webhook: %s\\n\" % e)\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **id** | **str**| | \n\n### Return type\n\nvoid (empty response body)\n\n### Authorization\n\n[api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n# **get_open_orders**\n> CustomersIdSellingCurrent get_open_orders(id)\n\n\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: JWT\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['jwt-authorization'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['jwt-authorization'] = 'Bearer'\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nid = 'id_example' # str | The customer id to lookup open orders with.\n\ntry:\n api_response = api_instance.get_open_orders(id)\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->get_open_orders: %s\\n\" % e)\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **id** | **str**| The customer id to lookup open orders with. | \n\n### Return type\n\n[**CustomersIdSellingCurrent**](CustomersIdSellingCurrent.md)\n\n### Authorization\n\n[JWT](../README.md#JWT), [api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n# **get_portfolio**\n> PortfolioResponse get_portfolio(portfolio)\n\nReturns a market portfolio identified by request parameters.\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nportfolio = io_stockx.PortfolioRequest() # PortfolioRequest | Requests parameters for looking up a market portfolio.\n\ntry:\n # Returns a market portfolio identified by request parameters.\n api_response = api_instance.get_portfolio(portfolio)\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->get_portfolio: %s\\n\" % e)\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **portfolio** | [**PortfolioRequest**](PortfolioRequest.md)| Requests parameters for looking up a market portfolio. | \n\n### Return type\n\n[**PortfolioResponse**](PortfolioResponse.md)\n\n### Authorization\n\n[api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n# **get_portfolio_item**\n> PortfolioitemsIdGetResponse get_portfolio_item(id)\n\n\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: JWT\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['jwt-authorization'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['jwt-authorization'] = 'Bearer'\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nid = 'id_example' # str | The id of the portfolio item to lookup.\n\ntry:\n api_response = api_instance.get_portfolio_item(id)\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->get_portfolio_item: %s\\n\" % e)\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **id** | **str**| The id of the portfolio item to lookup. | \n\n### Return type\n\n[**PortfolioitemsIdGetResponse**](PortfolioitemsIdGetResponse.md)\n\n### Authorization\n\n[JWT](../README.md#JWT), [api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n# **get_product_by_id**\n> ProductResponse get_product_by_id(id, include=include)\n\n\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: JWT\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['jwt-authorization'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['jwt-authorization'] = 'Bearer'\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nid = 'id_example' # str | The id of the product to return.\ninclude = 'include_example' # str | (optional)\n\ntry:\n api_response = api_instance.get_product_by_id(id, include=include)\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->get_product_by_id: %s\\n\" % e)\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **id** | **str**| The id of the product to return. | \n **include** | **str**| | [optional] \n\n### Return type\n\n[**ProductResponse**](ProductResponse.md)\n\n### Authorization\n\n[JWT](../README.md#JWT), [api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n# **get_product_market_data**\n> MarketData get_product_market_data(product_id, sku=sku)\n\nProvides historical market data for a given product.\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: JWT\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['jwt-authorization'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['jwt-authorization'] = 'Bearer'\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nproduct_id = 'product_id_example' # str | The product's product UUID\nsku = 'sku_example' # str | The product's SKU (optional)\n\ntry:\n # Provides historical market data for a given product.\n api_response = api_instance.get_product_market_data(product_id, sku=sku)\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->get_product_market_data: %s\\n\" % e)\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **product_id** | **str**| The product&#39;s product UUID | \n **sku** | **str**| The product&#39;s SKU | [optional] \n\n### Return type\n\n[**MarketData**](MarketData.md)\n\n### Authorization\n\n[JWT](../README.md#JWT), [api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n# **get_subscriptions**\n> SubscriptionsResponse get_subscriptions()\n\n\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\n\ntry:\n api_response = api_instance.get_subscriptions()\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->get_subscriptions: %s\\n\" % e)\n```\n\n### Parameters\nThis endpoint does not need any parameter.\n\n### Return type\n\n[**SubscriptionsResponse**](SubscriptionsResponse.md)\n\n### Authorization\n\n[api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n# **get_webhook**\n> WebhooksIdGetResponse get_webhook(id)\n\n\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nid = 'id_example' # str | \n\ntry:\n api_response = api_instance.get_webhook(id)\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->get_webhook: %s\\n\" % e)\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **id** | **str**| | \n\n### Return type\n\n[**WebhooksIdGetResponse**](WebhooksIdGetResponse.md)\n\n### Authorization\n\n[api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n# **get_webhooks**\n> WebhooksGetResponse get_webhooks()\n\n\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\n\ntry:\n api_response = api_instance.get_webhooks()\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->get_webhooks: %s\\n\" % e)\n```\n\n### Parameters\nThis endpoint does not need any parameter.\n\n### Return type\n\n[**WebhooksGetResponse**](WebhooksGetResponse.md)\n\n### Authorization\n\n[api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n# **login**\n> LoginResponse login(login)\n\nAttempts to log the user in with a username and password.\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nlogin = io_stockx.LoginRequest() # LoginRequest | Object that contains the user's authentication credentials.'\n\ntry:\n # Attempts to log the user in with a username and password.\n api_response = api_instance.login(login)\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->login: %s\\n\" % e)\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **login** | [**LoginRequest**](LoginRequest.md)| Object that contains the user&#39;s authentication credentials.&#39; | \n\n### Return type\n\n[**LoginResponse**](LoginResponse.md)\n\n### Authorization\n\n[api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n# **lookup_product**\n> ProductInfo lookup_product(identifier=identifier, size=size)\n\n\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: JWT\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['jwt-authorization'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['jwt-authorization'] = 'Bearer'\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nidentifier = 'identifier_example' # str | The product identifier to lookup, e.g. (air-jordan-1-retro-high-off-white-chicago) (optional)\nsize = 'size_example' # str | The size of the product. (optional)\n\ntry:\n api_response = api_instance.lookup_product(identifier=identifier, size=size)\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->lookup_product: %s\\n\" % e)\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **identifier** | **str**| The product identifier to lookup, e.g. (air-jordan-1-retro-high-off-white-chicago) | [optional] \n **size** | **str**| The size of the product. | [optional] \n\n### Return type\n\n[**ProductInfo**](ProductInfo.md)\n\n### Authorization\n\n[JWT](../README.md#JWT), [api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: Not defined\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n# **new_portfolio_ask**\n> PortfolioResponse new_portfolio_ask(portfolio)\n\nCreates a new seller ask on the market for a given product.\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nportfolio = io_stockx.PortfolioRequest() # PortfolioRequest | The portfolio request representing the ask to place on the market.\n\ntry:\n # Creates a new seller ask on the market for a given product.\n api_response = api_instance.new_portfolio_ask(portfolio)\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->new_portfolio_ask: %s\\n\" % e)\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **portfolio** | [**PortfolioRequest**](PortfolioRequest.md)| The portfolio request representing the ask to place on the market. | \n\n### Return type\n\n[**PortfolioResponse**](PortfolioResponse.md)\n\n### Authorization\n\n[api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n# **new_portfolio_bid**\n> PortfolioResponse new_portfolio_bid(portfolio)\n\nCreates a new buyer bid on the market for a given product.\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nportfolio = io_stockx.PortfolioRequest() # PortfolioRequest | The portfolio request representing the bid to place on the market.\n\ntry:\n # Creates a new buyer bid on the market for a given product.\n api_response = api_instance.new_portfolio_bid(portfolio)\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->new_portfolio_bid: %s\\n\" % e)\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **portfolio** | [**PortfolioRequest**](PortfolioRequest.md)| The portfolio request representing the bid to place on the market. | \n\n### Return type\n\n[**PortfolioResponse**](PortfolioResponse.md)\n\n### Authorization\n\n[api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n# **post_webhooks**\n> WebhooksPostResponse post_webhooks(portfolio)\n\n\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nportfolio = io_stockx.WebhooksPostRequest() # WebhooksPostRequest | \n\ntry:\n api_response = api_instance.post_webhooks(portfolio)\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->post_webhooks: %s\\n\" % e)\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **portfolio** | [**WebhooksPostRequest**](WebhooksPostRequest.md)| | \n\n### Return type\n\n[**WebhooksPostResponse**](WebhooksPostResponse.md)\n\n### Authorization\n\n[api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n# **search**\n> SearchResults search(query)\n\nSearches for products by keyword.\n\n### Example\n```python\nfrom __future__ import print_function\nimport time\nimport io_stockx\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: JWT\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['jwt-authorization'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['jwt-authorization'] = 'Bearer'\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\nconfiguration.api_key['x-api-key'] = 'YOUR_API_KEY'\n# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed\n# configuration.api_key_prefix['x-api-key'] = 'Bearer'\n\n# create an instance of the API class\napi_instance = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nquery = 'query_example' # str | The phrase or keyword to search with.\n\ntry:\n # Searches for products by keyword.\n api_response = api_instance.search(query)\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->search: %s\\n\" % e)\n```\n\n### Parameters\n\nName | Type | Description | Notes\n------------- | ------------- | ------------- | -------------\n **query** | **str**| The phrase or keyword to search with. | \n\n### Return type\n\n[**SearchResults**](SearchResults.md)\n\n### Authorization\n\n[JWT](../README.md#JWT), [api_key](../README.md#api_key)\n\n### HTTP request headers\n\n - **Content-Type**: application/json\n - **Accept**: application/json\n\n[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)\n\n" }, { "alpha_fraction": 0.8707143068313599, "alphanum_fraction": 0.8721428513526917, "avg_line_length": 72.68421173095703, "blob_id": "18d972de1822129482ab9cb2c15f4d744258b912", "content_id": "32730d43efd267a832bf4656280f9fa5f84971d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5600, "license_type": "no_license", "max_line_length": 176, "num_lines": 76, "path": "/sdk/python/lib/build/lib/io_stockx/models/__init__.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n# flake8: noqa\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nfrom __future__ import absolute_import\n\n# import models into model package\nfrom io_stockx.models.address_object import AddressObject\nfrom io_stockx.models.billing_object import BillingObject\nfrom io_stockx.models.customer_object import CustomerObject\nfrom io_stockx.models.customer_object_merchant import CustomerObjectMerchant\nfrom io_stockx.models.customer_object_security import CustomerObjectSecurity\nfrom io_stockx.models.customer_object_shipping import CustomerObjectShipping\nfrom io_stockx.models.customers_id_selling_current import CustomersIdSellingCurrent\nfrom io_stockx.models.customers_id_selling_current_pagination import CustomersIdSellingCurrentPagination\nfrom io_stockx.models.customers_id_selling_current_paging import CustomersIdSellingCurrentPaging\nfrom io_stockx.models.login_request import LoginRequest\nfrom io_stockx.models.login_response import LoginResponse\nfrom io_stockx.models.market_data import MarketData\nfrom io_stockx.models.market_data_market import MarketDataMarket\nfrom io_stockx.models.portfolio_id_del_request import PortfolioIdDelRequest\nfrom io_stockx.models.portfolio_id_del_response import PortfolioIdDelResponse\nfrom io_stockx.models.portfolio_id_del_response_portfolio_item import PortfolioIdDelResponsePortfolioItem\nfrom io_stockx.models.portfolio_id_del_response_portfolio_item_merchant import PortfolioIdDelResponsePortfolioItemMerchant\nfrom io_stockx.models.portfolio_id_del_response_portfolio_item_product import PortfolioIdDelResponsePortfolioItemProduct\nfrom io_stockx.models.portfolio_id_del_response_portfolio_item_product_market import PortfolioIdDelResponsePortfolioItemProductMarket\nfrom io_stockx.models.portfolio_id_del_response_portfolio_item_product_media import PortfolioIdDelResponsePortfolioItemProductMedia\nfrom io_stockx.models.portfolio_id_del_response_portfolio_item_product_meta import PortfolioIdDelResponsePortfolioItemProductMeta\nfrom io_stockx.models.portfolio_id_del_response_portfolio_item_product_shipping import PortfolioIdDelResponsePortfolioItemProductShipping\nfrom io_stockx.models.portfolio_id_del_response_portfolio_item_tracking import PortfolioIdDelResponsePortfolioItemTracking\nfrom io_stockx.models.portfolio_request import PortfolioRequest\nfrom io_stockx.models.portfolio_request_portfolio_item import PortfolioRequestPortfolioItem\nfrom io_stockx.models.portfolio_response import PortfolioResponse\nfrom io_stockx.models.portfolio_response_portfolio_item import PortfolioResponsePortfolioItem\nfrom io_stockx.models.portfolio_response_portfolio_item_product import PortfolioResponsePortfolioItemProduct\nfrom io_stockx.models.portfolio_response_portfolio_item_product_market import PortfolioResponsePortfolioItemProductMarket\nfrom io_stockx.models.portfolio_response_portfolio_item_product_media import PortfolioResponsePortfolioItemProductMedia\nfrom io_stockx.models.portfolio_response_portfolio_item_tracking import PortfolioResponsePortfolioItemTracking\nfrom io_stockx.models.portfolioitems_id_get_response import PortfolioitemsIdGetResponse\nfrom io_stockx.models.portfolioitems_id_get_response_portfolio_item import PortfolioitemsIdGetResponsePortfolioItem\nfrom io_stockx.models.portfolioitems_id_get_response_portfolio_item_product import PortfolioitemsIdGetResponsePortfolioItemProduct\nfrom io_stockx.models.portfolioitems_id_get_response_portfolio_item_product_market import PortfolioitemsIdGetResponsePortfolioItemProductMarket\nfrom io_stockx.models.product_info import ProductInfo\nfrom io_stockx.models.product_info_attributes import ProductInfoAttributes\nfrom io_stockx.models.product_info_attributes_traits import ProductInfoAttributesTraits\nfrom io_stockx.models.product_info_data import ProductInfoData\nfrom io_stockx.models.product_info_meta import ProductInfoMeta\nfrom io_stockx.models.product_info_product import ProductInfoProduct\nfrom io_stockx.models.product_info_product_attributes import ProductInfoProductAttributes\nfrom io_stockx.models.product_lookup_response import ProductLookupResponse\nfrom io_stockx.models.product_response import ProductResponse\nfrom io_stockx.models.product_response_product import ProductResponseProduct\nfrom io_stockx.models.product_response_product_children import ProductResponseProductChildren\nfrom io_stockx.models.product_response_product_children_productid import ProductResponseProductChildrenPRODUCTID\nfrom io_stockx.models.product_response_product_children_productid_market import ProductResponseProductChildrenPRODUCTIDMarket\nfrom io_stockx.models.product_response_product_media import ProductResponseProductMedia\nfrom io_stockx.models.product_response_product_meta import ProductResponseProductMeta\nfrom io_stockx.models.search_hit import SearchHit\nfrom io_stockx.models.search_hit_media import SearchHitMedia\nfrom io_stockx.models.search_hit_searchable_traits import SearchHitSearchableTraits\nfrom io_stockx.models.search_results import SearchResults\nfrom io_stockx.models.subscriptions_response import SubscriptionsResponse\nfrom io_stockx.models.webhooks_get_response import WebhooksGetResponse\nfrom io_stockx.models.webhooks_id_get_response import WebhooksIdGetResponse\nfrom io_stockx.models.webhooks_post_request import WebhooksPostRequest\nfrom io_stockx.models.webhooks_post_response import WebhooksPostResponse\n" }, { "alpha_fraction": 0.5569105744361877, "alphanum_fraction": 0.5569105744361877, "avg_line_length": 29, "blob_id": "55b93b5180473fed51d65ce27f1aa232fdd2adf6", "content_id": "ff0e4f35f5fa6bfd3b089e51455113d9cdff2233", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1230, "license_type": "no_license", "max_line_length": 109, "num_lines": 41, "path": "/sdk/csharp/src/IO.StockX.Examples/SearchExample.cs", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "using System;\nusing System.Diagnostics;\nusing IO.StockX.Api;\nusing IO.StockX.Client;\nusing IO.StockX.Model;\n\nnamespace Example\n{\n /**\n * <p>Demonstrates retrieving information StockX products from a general query.</p>\n */\n public class GetProductInfoExample\n {\n static public void Main()\n {\n // Configure API key authorization: api_key\n Configuration.Default.AddApiKey(\"x-api-key\", ExampleConstants.AWS_API_KEY);\n\n var stockx = new StockXApi();\n stockx.Configuration.BasePath = ExampleConstants.STOCKX_ENDPOINT;\n \n var login = new LoginRequest(ExampleConstants.STOCKX_USERNAME, ExampleConstants.STOCKX_PASSWORD);\n \n try\n {\n // Login\n stockx.Login(login);\n \n // Lookup the supplied product by its product ID\n var search = stockx.Search(\"jeezy\");\n\n Console.WriteLine(search);\n }\n catch (Exception e)\n {\n Console.WriteLine(e.ToString());\n Console.WriteLine(\"Exception when calling StockXApi.Search: \" + e.Message );\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5466150641441345, "alphanum_fraction": 0.5491681694984436, "avg_line_length": 21.481481552124023, "blob_id": "2e1dcf906f4003678e452f732f2a94f6fcb038a2", "content_id": "a1322ffd7e838094c52fa73fe0294fb604c9d6b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 12142, "license_type": "no_license", "max_line_length": 124, "num_lines": 540, "path": "/sdk/php/StockX-SDK-PHP/lib/lib/Model/AddressObject.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * AddressObject\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Do not edit the class manually.\n */\n\nnamespace StockX\\Client\\Model;\n\nuse \\ArrayAccess;\nuse \\StockX\\Client\\ObjectSerializer;\n\n/**\n * AddressObject Class Doc Comment\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass AddressObject implements ModelInterface, ArrayAccess\n{\n const DISCRIMINATOR = null;\n\n /**\n * The original name of the model.\n *\n * @var string\n */\n protected static $swaggerModelName = 'Address Object';\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerTypes = [\n 'first_name' => 'string',\n 'last_name' => 'string',\n 'telephone' => 'string',\n 'street_address' => 'string',\n 'extended_address' => 'string',\n 'locality' => 'string',\n 'region' => 'string',\n 'postal_code' => 'string',\n 'country_code_alpha2' => 'string'\n ];\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerFormats = [\n 'first_name' => null,\n 'last_name' => null,\n 'telephone' => null,\n 'street_address' => null,\n 'extended_address' => null,\n 'locality' => null,\n 'region' => null,\n 'postal_code' => null,\n 'country_code_alpha2' => null\n ];\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerTypes()\n {\n return self::$swaggerTypes;\n }\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerFormats()\n {\n return self::$swaggerFormats;\n }\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @var string[]\n */\n protected static $attributeMap = [\n 'first_name' => 'firstName',\n 'last_name' => 'lastName',\n 'telephone' => 'telephone',\n 'street_address' => 'streetAddress',\n 'extended_address' => 'extendedAddress',\n 'locality' => 'locality',\n 'region' => 'region',\n 'postal_code' => 'postalCode',\n 'country_code_alpha2' => 'countryCodeAlpha2'\n ];\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @var string[]\n */\n protected static $setters = [\n 'first_name' => 'setFirstName',\n 'last_name' => 'setLastName',\n 'telephone' => 'setTelephone',\n 'street_address' => 'setStreetAddress',\n 'extended_address' => 'setExtendedAddress',\n 'locality' => 'setLocality',\n 'region' => 'setRegion',\n 'postal_code' => 'setPostalCode',\n 'country_code_alpha2' => 'setCountryCodeAlpha2'\n ];\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @var string[]\n */\n protected static $getters = [\n 'first_name' => 'getFirstName',\n 'last_name' => 'getLastName',\n 'telephone' => 'getTelephone',\n 'street_address' => 'getStreetAddress',\n 'extended_address' => 'getExtendedAddress',\n 'locality' => 'getLocality',\n 'region' => 'getRegion',\n 'postal_code' => 'getPostalCode',\n 'country_code_alpha2' => 'getCountryCodeAlpha2'\n ];\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @return array\n */\n public static function attributeMap()\n {\n return self::$attributeMap;\n }\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @return array\n */\n public static function setters()\n {\n return self::$setters;\n }\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @return array\n */\n public static function getters()\n {\n return self::$getters;\n }\n\n /**\n * The original name of the model.\n *\n * @return string\n */\n public function getModelName()\n {\n return self::$swaggerModelName;\n }\n\n \n\n \n\n /**\n * Associative array for storing property values\n *\n * @var mixed[]\n */\n protected $container = [];\n\n /**\n * Constructor\n *\n * @param mixed[] $data Associated array of property values\n * initializing the model\n */\n public function __construct(array $data = null)\n {\n $this->container['first_name'] = isset($data['first_name']) ? $data['first_name'] : null;\n $this->container['last_name'] = isset($data['last_name']) ? $data['last_name'] : null;\n $this->container['telephone'] = isset($data['telephone']) ? $data['telephone'] : null;\n $this->container['street_address'] = isset($data['street_address']) ? $data['street_address'] : null;\n $this->container['extended_address'] = isset($data['extended_address']) ? $data['extended_address'] : null;\n $this->container['locality'] = isset($data['locality']) ? $data['locality'] : null;\n $this->container['region'] = isset($data['region']) ? $data['region'] : null;\n $this->container['postal_code'] = isset($data['postal_code']) ? $data['postal_code'] : null;\n $this->container['country_code_alpha2'] = isset($data['country_code_alpha2']) ? $data['country_code_alpha2'] : null;\n }\n\n /**\n * Show all the invalid properties with reasons.\n *\n * @return array invalid properties with reasons\n */\n public function listInvalidProperties()\n {\n $invalidProperties = [];\n\n return $invalidProperties;\n }\n\n /**\n * Validate all the properties in the model\n * return true if all passed\n *\n * @return bool True if all properties are valid\n */\n public function valid()\n {\n\n return true;\n }\n\n\n /**\n * Gets first_name\n *\n * @return string\n */\n public function getFirstName()\n {\n return $this->container['first_name'];\n }\n\n /**\n * Sets first_name\n *\n * @param string $first_name first_name\n *\n * @return $this\n */\n public function setFirstName($first_name)\n {\n $this->container['first_name'] = $first_name;\n\n return $this;\n }\n\n /**\n * Gets last_name\n *\n * @return string\n */\n public function getLastName()\n {\n return $this->container['last_name'];\n }\n\n /**\n * Sets last_name\n *\n * @param string $last_name last_name\n *\n * @return $this\n */\n public function setLastName($last_name)\n {\n $this->container['last_name'] = $last_name;\n\n return $this;\n }\n\n /**\n * Gets telephone\n *\n * @return string\n */\n public function getTelephone()\n {\n return $this->container['telephone'];\n }\n\n /**\n * Sets telephone\n *\n * @param string $telephone telephone\n *\n * @return $this\n */\n public function setTelephone($telephone)\n {\n $this->container['telephone'] = $telephone;\n\n return $this;\n }\n\n /**\n * Gets street_address\n *\n * @return string\n */\n public function getStreetAddress()\n {\n return $this->container['street_address'];\n }\n\n /**\n * Sets street_address\n *\n * @param string $street_address street_address\n *\n * @return $this\n */\n public function setStreetAddress($street_address)\n {\n $this->container['street_address'] = $street_address;\n\n return $this;\n }\n\n /**\n * Gets extended_address\n *\n * @return string\n */\n public function getExtendedAddress()\n {\n return $this->container['extended_address'];\n }\n\n /**\n * Sets extended_address\n *\n * @param string $extended_address extended_address\n *\n * @return $this\n */\n public function setExtendedAddress($extended_address)\n {\n $this->container['extended_address'] = $extended_address;\n\n return $this;\n }\n\n /**\n * Gets locality\n *\n * @return string\n */\n public function getLocality()\n {\n return $this->container['locality'];\n }\n\n /**\n * Sets locality\n *\n * @param string $locality locality\n *\n * @return $this\n */\n public function setLocality($locality)\n {\n $this->container['locality'] = $locality;\n\n return $this;\n }\n\n /**\n * Gets region\n *\n * @return string\n */\n public function getRegion()\n {\n return $this->container['region'];\n }\n\n /**\n * Sets region\n *\n * @param string $region region\n *\n * @return $this\n */\n public function setRegion($region)\n {\n $this->container['region'] = $region;\n\n return $this;\n }\n\n /**\n * Gets postal_code\n *\n * @return string\n */\n public function getPostalCode()\n {\n return $this->container['postal_code'];\n }\n\n /**\n * Sets postal_code\n *\n * @param string $postal_code postal_code\n *\n * @return $this\n */\n public function setPostalCode($postal_code)\n {\n $this->container['postal_code'] = $postal_code;\n\n return $this;\n }\n\n /**\n * Gets country_code_alpha2\n *\n * @return string\n */\n public function getCountryCodeAlpha2()\n {\n return $this->container['country_code_alpha2'];\n }\n\n /**\n * Sets country_code_alpha2\n *\n * @param string $country_code_alpha2 country_code_alpha2\n *\n * @return $this\n */\n public function setCountryCodeAlpha2($country_code_alpha2)\n {\n $this->container['country_code_alpha2'] = $country_code_alpha2;\n\n return $this;\n }\n /**\n * Returns true if offset exists. False otherwise.\n *\n * @param integer $offset Offset\n *\n * @return boolean\n */\n public function offsetExists($offset)\n {\n return isset($this->container[$offset]);\n }\n\n /**\n * Gets offset.\n *\n * @param integer $offset Offset\n *\n * @return mixed\n */\n public function offsetGet($offset)\n {\n return isset($this->container[$offset]) ? $this->container[$offset] : null;\n }\n\n /**\n * Sets value based on offset.\n *\n * @param integer $offset Offset\n * @param mixed $value Value to be set\n *\n * @return void\n */\n public function offsetSet($offset, $value)\n {\n if (is_null($offset)) {\n $this->container[] = $value;\n } else {\n $this->container[$offset] = $value;\n }\n }\n\n /**\n * Unsets offset.\n *\n * @param integer $offset Offset\n *\n * @return void\n */\n public function offsetUnset($offset)\n {\n unset($this->container[$offset]);\n }\n\n /**\n * Gets the string presentation of the object\n *\n * @return string\n */\n public function __toString()\n {\n if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print\n return json_encode(\n ObjectSerializer::sanitizeForSerialization($this),\n JSON_PRETTY_PRINT\n );\n }\n\n return json_encode(ObjectSerializer::sanitizeForSerialization($this));\n }\n}\n\n\n" }, { "alpha_fraction": 0.550959587097168, "alphanum_fraction": 0.552151620388031, "avg_line_length": 20.505128860473633, "blob_id": "d574fc6a3e62355c529648c0e14734fa8a77872f", "content_id": "44e97ffd7275932581514e12ca7c163d8bb40656", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 8389, "license_type": "no_license", "max_line_length": 110, "num_lines": 390, "path": "/sdk/php/StockX-SDK-PHP/lib/lib/Model/SearchHitSearchableTraits.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * SearchHitSearchableTraits\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Do not edit the class manually.\n */\n\nnamespace StockX\\Client\\Model;\n\nuse \\ArrayAccess;\nuse \\StockX\\Client\\ObjectSerializer;\n\n/**\n * SearchHitSearchableTraits Class Doc Comment\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass SearchHitSearchableTraits implements ModelInterface, ArrayAccess\n{\n const DISCRIMINATOR = null;\n\n /**\n * The original name of the model.\n *\n * @var string\n */\n protected static $swaggerModelName = 'SearchHit_searchable_traits';\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerTypes = [\n 'style' => 'string',\n 'colorway' => 'string',\n 'retail_price' => 'int',\n 'release_date' => 'string'\n ];\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerFormats = [\n 'style' => null,\n 'colorway' => null,\n 'retail_price' => null,\n 'release_date' => null\n ];\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerTypes()\n {\n return self::$swaggerTypes;\n }\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerFormats()\n {\n return self::$swaggerFormats;\n }\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @var string[]\n */\n protected static $attributeMap = [\n 'style' => 'Style',\n 'colorway' => 'Colorway',\n 'retail_price' => 'Retail Price',\n 'release_date' => 'Release Date'\n ];\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @var string[]\n */\n protected static $setters = [\n 'style' => 'setStyle',\n 'colorway' => 'setColorway',\n 'retail_price' => 'setRetailPrice',\n 'release_date' => 'setReleaseDate'\n ];\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @var string[]\n */\n protected static $getters = [\n 'style' => 'getStyle',\n 'colorway' => 'getColorway',\n 'retail_price' => 'getRetailPrice',\n 'release_date' => 'getReleaseDate'\n ];\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @return array\n */\n public static function attributeMap()\n {\n return self::$attributeMap;\n }\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @return array\n */\n public static function setters()\n {\n return self::$setters;\n }\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @return array\n */\n public static function getters()\n {\n return self::$getters;\n }\n\n /**\n * The original name of the model.\n *\n * @return string\n */\n public function getModelName()\n {\n return self::$swaggerModelName;\n }\n\n \n\n \n\n /**\n * Associative array for storing property values\n *\n * @var mixed[]\n */\n protected $container = [];\n\n /**\n * Constructor\n *\n * @param mixed[] $data Associated array of property values\n * initializing the model\n */\n public function __construct(array $data = null)\n {\n $this->container['style'] = isset($data['style']) ? $data['style'] : null;\n $this->container['colorway'] = isset($data['colorway']) ? $data['colorway'] : null;\n $this->container['retail_price'] = isset($data['retail_price']) ? $data['retail_price'] : null;\n $this->container['release_date'] = isset($data['release_date']) ? $data['release_date'] : null;\n }\n\n /**\n * Show all the invalid properties with reasons.\n *\n * @return array invalid properties with reasons\n */\n public function listInvalidProperties()\n {\n $invalidProperties = [];\n\n return $invalidProperties;\n }\n\n /**\n * Validate all the properties in the model\n * return true if all passed\n *\n * @return bool True if all properties are valid\n */\n public function valid()\n {\n\n return true;\n }\n\n\n /**\n * Gets style\n *\n * @return string\n */\n public function getStyle()\n {\n return $this->container['style'];\n }\n\n /**\n * Sets style\n *\n * @param string $style style\n *\n * @return $this\n */\n public function setStyle($style)\n {\n $this->container['style'] = $style;\n\n return $this;\n }\n\n /**\n * Gets colorway\n *\n * @return string\n */\n public function getColorway()\n {\n return $this->container['colorway'];\n }\n\n /**\n * Sets colorway\n *\n * @param string $colorway colorway\n *\n * @return $this\n */\n public function setColorway($colorway)\n {\n $this->container['colorway'] = $colorway;\n\n return $this;\n }\n\n /**\n * Gets retail_price\n *\n * @return int\n */\n public function getRetailPrice()\n {\n return $this->container['retail_price'];\n }\n\n /**\n * Sets retail_price\n *\n * @param int $retail_price retail_price\n *\n * @return $this\n */\n public function setRetailPrice($retail_price)\n {\n $this->container['retail_price'] = $retail_price;\n\n return $this;\n }\n\n /**\n * Gets release_date\n *\n * @return string\n */\n public function getReleaseDate()\n {\n return $this->container['release_date'];\n }\n\n /**\n * Sets release_date\n *\n * @param string $release_date release_date\n *\n * @return $this\n */\n public function setReleaseDate($release_date)\n {\n $this->container['release_date'] = $release_date;\n\n return $this;\n }\n /**\n * Returns true if offset exists. False otherwise.\n *\n * @param integer $offset Offset\n *\n * @return boolean\n */\n public function offsetExists($offset)\n {\n return isset($this->container[$offset]);\n }\n\n /**\n * Gets offset.\n *\n * @param integer $offset Offset\n *\n * @return mixed\n */\n public function offsetGet($offset)\n {\n return isset($this->container[$offset]) ? $this->container[$offset] : null;\n }\n\n /**\n * Sets value based on offset.\n *\n * @param integer $offset Offset\n * @param mixed $value Value to be set\n *\n * @return void\n */\n public function offsetSet($offset, $value)\n {\n if (is_null($offset)) {\n $this->container[] = $value;\n } else {\n $this->container[$offset] = $value;\n }\n }\n\n /**\n * Unsets offset.\n *\n * @param integer $offset Offset\n *\n * @return void\n */\n public function offsetUnset($offset)\n {\n unset($this->container[$offset]);\n }\n\n /**\n * Gets the string presentation of the object\n *\n * @return string\n */\n public function __toString()\n {\n if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print\n return json_encode(\n ObjectSerializer::sanitizeForSerialization($this),\n JSON_PRETTY_PRINT\n );\n }\n\n return json_encode(ObjectSerializer::sanitizeForSerialization($this));\n }\n}\n\n\n" }, { "alpha_fraction": 0.5348133444786072, "alphanum_fraction": 0.5635721683502197, "avg_line_length": 36.41509246826172, "blob_id": "fd7f4234f5b81ba2a8f0c32af6e8dd6e45a42f49", "content_id": "c39fdbd6b2212b79d4a1b3bc824952732aaa8df9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1982, "license_type": "no_license", "max_line_length": 109, "num_lines": 53, "path": "/sdk/csharp/src/IO.StockX.Examples/PortfolioAskExample.cs", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "using System;\nusing System.Diagnostics;\nusing IO.StockX.Api;\nusing IO.StockX.Client;\nusing IO.StockX.Model;\n\nnamespace Example\n{\n public class PortfolioAskExample\n {\n static public void Main()\n {\n // Configure API key authorization: api_key\n Configuration.Default.AddApiKey(\"x-api-key\", ExampleConstants.AWS_API_KEY);\n\n var stockx = new StockXApi();\n stockx.Configuration.BasePath = ExampleConstants.STOCKX_ENDPOINT;\n \n var login = new LoginRequest(ExampleConstants.STOCKX_USERNAME, ExampleConstants.STOCKX_PASSWORD);\n \n try\n {\n // Login and fetch the jwt header for authentication use in the request\n ApiResponse<LoginResponse> result = stockx.LoginWithHttpInfo(login);\n var jwt = result.Headers[ExampleConstants.JWT_HEADER];\n\n stockx.Configuration.DefaultHeader[\"jwt-authorization\"] = jwt;\n\n var item = new PortfolioRequestPortfolioItem();\n item.Amount = \"25\";\n item.SkuUuid = \"bae25b67-a721-4f57-ad5a-79973c7d0a5c\";\n item.MatchedWithDate = \"2018-12-12T05:00:00+0000\";\n item.ExpiresAt = \"2018-12-12T12:39:07+00:00\";\n\n var request = new PortfolioRequest();\n request.PortfolioItem = item;\n request.Customer = result.Data.Customer;\n request.Timezone = \"America/Detroit\";\n \n // Create a new portfolio ask\n var askResp = stockx.NewPortfolioAsk(request);\n\n // Print the result of the ask call\n Console.WriteLine(askResp);\n } \n catch (Exception e)\n {\n Console.WriteLine(e.ToString());\n Console.WriteLine(\"Exception when calling StockXApi.NewPortfolioAsk: \" + e.Message );\n }\n }\n }\n}" }, { "alpha_fraction": 0.7197265625, "alphanum_fraction": 0.740234375, "avg_line_length": 35.60714340209961, "blob_id": "cef0651200801d464afd8f4ff4b30af2c7db2e7f", "content_id": "14260e702e7bac7b5a8346a2fbd372b16d4a7416", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1024, "license_type": "no_license", "max_line_length": 123, "num_lines": 28, "path": "/sdk/nodejs/get_product_market_data_example.js", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "var StockX = require('stock_x_api');\n\nvar exampleConstants = new ExampleConstants();\n\nvar defaultClient = StockX.ApiClient.instance;\n\tdefaultClient.basePath = 'https://gateway.stockx.com/stage';\n\nvar apiKey = defaultClient.authentications['api_key'];\n\tapiKey.apiKey = exampleConstants.AWS_API_KEY;\n\nvar stockx = new StockX.StockXApi();\n\nvar login = new StockX.LoginRequest();\n\tlogin.email = exampleConstants.STOCKX_USERNAME;\n\tlogin.password = exampleConstants.STOCKX_PASSWORD;\n\nstockx.loginWithHttpInfo(login)\n\t.then(res => {\n\t\tdefaultClient.defaultHeaders['jwt-authorization'] = res.response.headers['jwt-authorization'];\n\t\treturn res.data.Customer;\n\t}).then(customer => {\n\t\t// Lookup the supplied product by its product ID\n\t\treturn stockx.getProductMarketData('7f9c67ff-2cd4-4e27-8b64-518900a1bc0b', 'air-jordan-1-retro-high-off-white-chicago');\t\n\t}).then(search => {\n\t\tconsole.log('Product market data lookup successful: ' + JSON.stringify(search));\n\t}).catch(err => {\n\t\tconsole.log('Error performing product market data lookup: ' + err);\n\t});" }, { "alpha_fraction": 0.521221399307251, "alphanum_fraction": 0.5215339660644531, "avg_line_length": 24.0344295501709, "blob_id": "4699df37c508071f51a0c35bfab146d0f8d7ee2b", "content_id": "3fa87185e2cc83b9136dcc5827ff8917e52360e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 31996, "license_type": "no_license", "max_line_length": 127, "num_lines": 1278, "path": "/sdk/php/StockX-SDK-PHP/lib/lib/Model/PortfolioitemsIdGetResponsePortfolioItem.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * PortfolioitemsIdGetResponsePortfolioItem\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Do not edit the class manually.\n */\n\nnamespace StockX\\Client\\Model;\n\nuse \\ArrayAccess;\nuse \\StockX\\Client\\ObjectSerializer;\n\n/**\n * PortfolioitemsIdGetResponsePortfolioItem Class Doc Comment\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass PortfolioitemsIdGetResponsePortfolioItem implements ModelInterface, ArrayAccess\n{\n const DISCRIMINATOR = null;\n\n /**\n * The original name of the model.\n *\n * @var string\n */\n protected static $swaggerModelName = 'portfolioitems_id_get_response_PortfolioItem';\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerTypes = [\n 'chain_id' => 'string',\n 'customer_id' => 'int',\n 'inventory_id' => 'string',\n 'product_id' => 'string',\n 'sku_uuid' => 'string',\n 'merchant_id' => 'int',\n 'condition' => 'int',\n 'action' => 'int',\n 'action_by' => 'int',\n 'amount' => 'int',\n 'expires_at' => 'string',\n 'expires_at_time' => 'int',\n 'gain_loss_dollars' => 'int',\n 'gain_loss_percentage' => 'int',\n 'market_value' => 'string',\n 'matched_state' => 'int',\n 'purchase_date' => 'string',\n 'purchase_date_time' => 'int',\n 'state' => 'int',\n 'text' => 'string',\n 'created_at' => 'string',\n 'created_at_time' => 'int',\n 'can_edit' => 'bool',\n 'can_delete' => 'bool',\n 'tracking' => '\\StockX\\Client\\Model\\PortfolioIdDelResponsePortfolioItemTracking',\n 'meta' => 'object',\n 'product' => '\\StockX\\Client\\Model\\PortfolioitemsIdGetResponsePortfolioItemProduct',\n 'merchant' => '\\StockX\\Client\\Model\\PortfolioIdDelResponsePortfolioItemMerchant'\n ];\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerFormats = [\n 'chain_id' => null,\n 'customer_id' => null,\n 'inventory_id' => null,\n 'product_id' => null,\n 'sku_uuid' => null,\n 'merchant_id' => null,\n 'condition' => null,\n 'action' => null,\n 'action_by' => null,\n 'amount' => null,\n 'expires_at' => null,\n 'expires_at_time' => null,\n 'gain_loss_dollars' => null,\n 'gain_loss_percentage' => null,\n 'market_value' => null,\n 'matched_state' => null,\n 'purchase_date' => null,\n 'purchase_date_time' => null,\n 'state' => null,\n 'text' => null,\n 'created_at' => null,\n 'created_at_time' => null,\n 'can_edit' => null,\n 'can_delete' => null,\n 'tracking' => null,\n 'meta' => null,\n 'product' => null,\n 'merchant' => null\n ];\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerTypes()\n {\n return self::$swaggerTypes;\n }\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerFormats()\n {\n return self::$swaggerFormats;\n }\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @var string[]\n */\n protected static $attributeMap = [\n 'chain_id' => 'chainId',\n 'customer_id' => 'customerId',\n 'inventory_id' => 'inventoryId',\n 'product_id' => 'productId',\n 'sku_uuid' => 'skuUuid',\n 'merchant_id' => 'merchantId',\n 'condition' => 'condition',\n 'action' => 'action',\n 'action_by' => 'actionBy',\n 'amount' => 'amount',\n 'expires_at' => 'expiresAt',\n 'expires_at_time' => 'expiresAtTime',\n 'gain_loss_dollars' => 'gainLossDollars',\n 'gain_loss_percentage' => 'gainLossPercentage',\n 'market_value' => 'marketValue',\n 'matched_state' => 'matchedState',\n 'purchase_date' => 'purchaseDate',\n 'purchase_date_time' => 'purchaseDateTime',\n 'state' => 'state',\n 'text' => 'text',\n 'created_at' => 'createdAt',\n 'created_at_time' => 'createdAtTime',\n 'can_edit' => 'canEdit',\n 'can_delete' => 'canDelete',\n 'tracking' => 'Tracking',\n 'meta' => 'meta',\n 'product' => 'product',\n 'merchant' => 'Merchant'\n ];\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @var string[]\n */\n protected static $setters = [\n 'chain_id' => 'setChainId',\n 'customer_id' => 'setCustomerId',\n 'inventory_id' => 'setInventoryId',\n 'product_id' => 'setProductId',\n 'sku_uuid' => 'setSkuUuid',\n 'merchant_id' => 'setMerchantId',\n 'condition' => 'setCondition',\n 'action' => 'setAction',\n 'action_by' => 'setActionBy',\n 'amount' => 'setAmount',\n 'expires_at' => 'setExpiresAt',\n 'expires_at_time' => 'setExpiresAtTime',\n 'gain_loss_dollars' => 'setGainLossDollars',\n 'gain_loss_percentage' => 'setGainLossPercentage',\n 'market_value' => 'setMarketValue',\n 'matched_state' => 'setMatchedState',\n 'purchase_date' => 'setPurchaseDate',\n 'purchase_date_time' => 'setPurchaseDateTime',\n 'state' => 'setState',\n 'text' => 'setText',\n 'created_at' => 'setCreatedAt',\n 'created_at_time' => 'setCreatedAtTime',\n 'can_edit' => 'setCanEdit',\n 'can_delete' => 'setCanDelete',\n 'tracking' => 'setTracking',\n 'meta' => 'setMeta',\n 'product' => 'setProduct',\n 'merchant' => 'setMerchant'\n ];\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @var string[]\n */\n protected static $getters = [\n 'chain_id' => 'getChainId',\n 'customer_id' => 'getCustomerId',\n 'inventory_id' => 'getInventoryId',\n 'product_id' => 'getProductId',\n 'sku_uuid' => 'getSkuUuid',\n 'merchant_id' => 'getMerchantId',\n 'condition' => 'getCondition',\n 'action' => 'getAction',\n 'action_by' => 'getActionBy',\n 'amount' => 'getAmount',\n 'expires_at' => 'getExpiresAt',\n 'expires_at_time' => 'getExpiresAtTime',\n 'gain_loss_dollars' => 'getGainLossDollars',\n 'gain_loss_percentage' => 'getGainLossPercentage',\n 'market_value' => 'getMarketValue',\n 'matched_state' => 'getMatchedState',\n 'purchase_date' => 'getPurchaseDate',\n 'purchase_date_time' => 'getPurchaseDateTime',\n 'state' => 'getState',\n 'text' => 'getText',\n 'created_at' => 'getCreatedAt',\n 'created_at_time' => 'getCreatedAtTime',\n 'can_edit' => 'getCanEdit',\n 'can_delete' => 'getCanDelete',\n 'tracking' => 'getTracking',\n 'meta' => 'getMeta',\n 'product' => 'getProduct',\n 'merchant' => 'getMerchant'\n ];\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @return array\n */\n public static function attributeMap()\n {\n return self::$attributeMap;\n }\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @return array\n */\n public static function setters()\n {\n return self::$setters;\n }\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @return array\n */\n public static function getters()\n {\n return self::$getters;\n }\n\n /**\n * The original name of the model.\n *\n * @return string\n */\n public function getModelName()\n {\n return self::$swaggerModelName;\n }\n\n \n\n \n\n /**\n * Associative array for storing property values\n *\n * @var mixed[]\n */\n protected $container = [];\n\n /**\n * Constructor\n *\n * @param mixed[] $data Associated array of property values\n * initializing the model\n */\n public function __construct(array $data = null)\n {\n $this->container['chain_id'] = isset($data['chain_id']) ? $data['chain_id'] : null;\n $this->container['customer_id'] = isset($data['customer_id']) ? $data['customer_id'] : null;\n $this->container['inventory_id'] = isset($data['inventory_id']) ? $data['inventory_id'] : null;\n $this->container['product_id'] = isset($data['product_id']) ? $data['product_id'] : null;\n $this->container['sku_uuid'] = isset($data['sku_uuid']) ? $data['sku_uuid'] : null;\n $this->container['merchant_id'] = isset($data['merchant_id']) ? $data['merchant_id'] : null;\n $this->container['condition'] = isset($data['condition']) ? $data['condition'] : null;\n $this->container['action'] = isset($data['action']) ? $data['action'] : null;\n $this->container['action_by'] = isset($data['action_by']) ? $data['action_by'] : null;\n $this->container['amount'] = isset($data['amount']) ? $data['amount'] : null;\n $this->container['expires_at'] = isset($data['expires_at']) ? $data['expires_at'] : null;\n $this->container['expires_at_time'] = isset($data['expires_at_time']) ? $data['expires_at_time'] : null;\n $this->container['gain_loss_dollars'] = isset($data['gain_loss_dollars']) ? $data['gain_loss_dollars'] : null;\n $this->container['gain_loss_percentage'] = isset($data['gain_loss_percentage']) ? $data['gain_loss_percentage'] : null;\n $this->container['market_value'] = isset($data['market_value']) ? $data['market_value'] : null;\n $this->container['matched_state'] = isset($data['matched_state']) ? $data['matched_state'] : null;\n $this->container['purchase_date'] = isset($data['purchase_date']) ? $data['purchase_date'] : null;\n $this->container['purchase_date_time'] = isset($data['purchase_date_time']) ? $data['purchase_date_time'] : null;\n $this->container['state'] = isset($data['state']) ? $data['state'] : null;\n $this->container['text'] = isset($data['text']) ? $data['text'] : null;\n $this->container['created_at'] = isset($data['created_at']) ? $data['created_at'] : null;\n $this->container['created_at_time'] = isset($data['created_at_time']) ? $data['created_at_time'] : null;\n $this->container['can_edit'] = isset($data['can_edit']) ? $data['can_edit'] : null;\n $this->container['can_delete'] = isset($data['can_delete']) ? $data['can_delete'] : null;\n $this->container['tracking'] = isset($data['tracking']) ? $data['tracking'] : null;\n $this->container['meta'] = isset($data['meta']) ? $data['meta'] : null;\n $this->container['product'] = isset($data['product']) ? $data['product'] : null;\n $this->container['merchant'] = isset($data['merchant']) ? $data['merchant'] : null;\n }\n\n /**\n * Show all the invalid properties with reasons.\n *\n * @return array invalid properties with reasons\n */\n public function listInvalidProperties()\n {\n $invalidProperties = [];\n\n if ($this->container['chain_id'] === null) {\n $invalidProperties[] = \"'chain_id' can't be null\";\n }\n if ($this->container['customer_id'] === null) {\n $invalidProperties[] = \"'customer_id' can't be null\";\n }\n if ($this->container['inventory_id'] === null) {\n $invalidProperties[] = \"'inventory_id' can't be null\";\n }\n if ($this->container['product_id'] === null) {\n $invalidProperties[] = \"'product_id' can't be null\";\n }\n if ($this->container['sku_uuid'] === null) {\n $invalidProperties[] = \"'sku_uuid' can't be null\";\n }\n if ($this->container['merchant_id'] === null) {\n $invalidProperties[] = \"'merchant_id' can't be null\";\n }\n if ($this->container['condition'] === null) {\n $invalidProperties[] = \"'condition' can't be null\";\n }\n if ($this->container['action'] === null) {\n $invalidProperties[] = \"'action' can't be null\";\n }\n if ($this->container['action_by'] === null) {\n $invalidProperties[] = \"'action_by' can't be null\";\n }\n if ($this->container['amount'] === null) {\n $invalidProperties[] = \"'amount' can't be null\";\n }\n if ($this->container['expires_at'] === null) {\n $invalidProperties[] = \"'expires_at' can't be null\";\n }\n if ($this->container['expires_at_time'] === null) {\n $invalidProperties[] = \"'expires_at_time' can't be null\";\n }\n if ($this->container['gain_loss_dollars'] === null) {\n $invalidProperties[] = \"'gain_loss_dollars' can't be null\";\n }\n if ($this->container['gain_loss_percentage'] === null) {\n $invalidProperties[] = \"'gain_loss_percentage' can't be null\";\n }\n if ($this->container['market_value'] === null) {\n $invalidProperties[] = \"'market_value' can't be null\";\n }\n if ($this->container['matched_state'] === null) {\n $invalidProperties[] = \"'matched_state' can't be null\";\n }\n if ($this->container['purchase_date'] === null) {\n $invalidProperties[] = \"'purchase_date' can't be null\";\n }\n if ($this->container['purchase_date_time'] === null) {\n $invalidProperties[] = \"'purchase_date_time' can't be null\";\n }\n if ($this->container['state'] === null) {\n $invalidProperties[] = \"'state' can't be null\";\n }\n if ($this->container['text'] === null) {\n $invalidProperties[] = \"'text' can't be null\";\n }\n if ($this->container['created_at'] === null) {\n $invalidProperties[] = \"'created_at' can't be null\";\n }\n if ($this->container['created_at_time'] === null) {\n $invalidProperties[] = \"'created_at_time' can't be null\";\n }\n if ($this->container['can_edit'] === null) {\n $invalidProperties[] = \"'can_edit' can't be null\";\n }\n if ($this->container['can_delete'] === null) {\n $invalidProperties[] = \"'can_delete' can't be null\";\n }\n if ($this->container['tracking'] === null) {\n $invalidProperties[] = \"'tracking' can't be null\";\n }\n if ($this->container['meta'] === null) {\n $invalidProperties[] = \"'meta' can't be null\";\n }\n if ($this->container['product'] === null) {\n $invalidProperties[] = \"'product' can't be null\";\n }\n if ($this->container['merchant'] === null) {\n $invalidProperties[] = \"'merchant' can't be null\";\n }\n return $invalidProperties;\n }\n\n /**\n * Validate all the properties in the model\n * return true if all passed\n *\n * @return bool True if all properties are valid\n */\n public function valid()\n {\n\n if ($this->container['chain_id'] === null) {\n return false;\n }\n if ($this->container['customer_id'] === null) {\n return false;\n }\n if ($this->container['inventory_id'] === null) {\n return false;\n }\n if ($this->container['product_id'] === null) {\n return false;\n }\n if ($this->container['sku_uuid'] === null) {\n return false;\n }\n if ($this->container['merchant_id'] === null) {\n return false;\n }\n if ($this->container['condition'] === null) {\n return false;\n }\n if ($this->container['action'] === null) {\n return false;\n }\n if ($this->container['action_by'] === null) {\n return false;\n }\n if ($this->container['amount'] === null) {\n return false;\n }\n if ($this->container['expires_at'] === null) {\n return false;\n }\n if ($this->container['expires_at_time'] === null) {\n return false;\n }\n if ($this->container['gain_loss_dollars'] === null) {\n return false;\n }\n if ($this->container['gain_loss_percentage'] === null) {\n return false;\n }\n if ($this->container['market_value'] === null) {\n return false;\n }\n if ($this->container['matched_state'] === null) {\n return false;\n }\n if ($this->container['purchase_date'] === null) {\n return false;\n }\n if ($this->container['purchase_date_time'] === null) {\n return false;\n }\n if ($this->container['state'] === null) {\n return false;\n }\n if ($this->container['text'] === null) {\n return false;\n }\n if ($this->container['created_at'] === null) {\n return false;\n }\n if ($this->container['created_at_time'] === null) {\n return false;\n }\n if ($this->container['can_edit'] === null) {\n return false;\n }\n if ($this->container['can_delete'] === null) {\n return false;\n }\n if ($this->container['tracking'] === null) {\n return false;\n }\n if ($this->container['meta'] === null) {\n return false;\n }\n if ($this->container['product'] === null) {\n return false;\n }\n if ($this->container['merchant'] === null) {\n return false;\n }\n return true;\n }\n\n\n /**\n * Gets chain_id\n *\n * @return string\n */\n public function getChainId()\n {\n return $this->container['chain_id'];\n }\n\n /**\n * Sets chain_id\n *\n * @param string $chain_id chain_id\n *\n * @return $this\n */\n public function setChainId($chain_id)\n {\n $this->container['chain_id'] = $chain_id;\n\n return $this;\n }\n\n /**\n * Gets customer_id\n *\n * @return int\n */\n public function getCustomerId()\n {\n return $this->container['customer_id'];\n }\n\n /**\n * Sets customer_id\n *\n * @param int $customer_id customer_id\n *\n * @return $this\n */\n public function setCustomerId($customer_id)\n {\n $this->container['customer_id'] = $customer_id;\n\n return $this;\n }\n\n /**\n * Gets inventory_id\n *\n * @return string\n */\n public function getInventoryId()\n {\n return $this->container['inventory_id'];\n }\n\n /**\n * Sets inventory_id\n *\n * @param string $inventory_id inventory_id\n *\n * @return $this\n */\n public function setInventoryId($inventory_id)\n {\n $this->container['inventory_id'] = $inventory_id;\n\n return $this;\n }\n\n /**\n * Gets product_id\n *\n * @return string\n */\n public function getProductId()\n {\n return $this->container['product_id'];\n }\n\n /**\n * Sets product_id\n *\n * @param string $product_id product_id\n *\n * @return $this\n */\n public function setProductId($product_id)\n {\n $this->container['product_id'] = $product_id;\n\n return $this;\n }\n\n /**\n * Gets sku_uuid\n *\n * @return string\n */\n public function getSkuUuid()\n {\n return $this->container['sku_uuid'];\n }\n\n /**\n * Sets sku_uuid\n *\n * @param string $sku_uuid sku_uuid\n *\n * @return $this\n */\n public function setSkuUuid($sku_uuid)\n {\n $this->container['sku_uuid'] = $sku_uuid;\n\n return $this;\n }\n\n /**\n * Gets merchant_id\n *\n * @return int\n */\n public function getMerchantId()\n {\n return $this->container['merchant_id'];\n }\n\n /**\n * Sets merchant_id\n *\n * @param int $merchant_id merchant_id\n *\n * @return $this\n */\n public function setMerchantId($merchant_id)\n {\n $this->container['merchant_id'] = $merchant_id;\n\n return $this;\n }\n\n /**\n * Gets condition\n *\n * @return int\n */\n public function getCondition()\n {\n return $this->container['condition'];\n }\n\n /**\n * Sets condition\n *\n * @param int $condition condition\n *\n * @return $this\n */\n public function setCondition($condition)\n {\n $this->container['condition'] = $condition;\n\n return $this;\n }\n\n /**\n * Gets action\n *\n * @return int\n */\n public function getAction()\n {\n return $this->container['action'];\n }\n\n /**\n * Sets action\n *\n * @param int $action action\n *\n * @return $this\n */\n public function setAction($action)\n {\n $this->container['action'] = $action;\n\n return $this;\n }\n\n /**\n * Gets action_by\n *\n * @return int\n */\n public function getActionBy()\n {\n return $this->container['action_by'];\n }\n\n /**\n * Sets action_by\n *\n * @param int $action_by action_by\n *\n * @return $this\n */\n public function setActionBy($action_by)\n {\n $this->container['action_by'] = $action_by;\n\n return $this;\n }\n\n /**\n * Gets amount\n *\n * @return int\n */\n public function getAmount()\n {\n return $this->container['amount'];\n }\n\n /**\n * Sets amount\n *\n * @param int $amount amount\n *\n * @return $this\n */\n public function setAmount($amount)\n {\n $this->container['amount'] = $amount;\n\n return $this;\n }\n\n /**\n * Gets expires_at\n *\n * @return string\n */\n public function getExpiresAt()\n {\n return $this->container['expires_at'];\n }\n\n /**\n * Sets expires_at\n *\n * @param string $expires_at expires_at\n *\n * @return $this\n */\n public function setExpiresAt($expires_at)\n {\n $this->container['expires_at'] = $expires_at;\n\n return $this;\n }\n\n /**\n * Gets expires_at_time\n *\n * @return int\n */\n public function getExpiresAtTime()\n {\n return $this->container['expires_at_time'];\n }\n\n /**\n * Sets expires_at_time\n *\n * @param int $expires_at_time expires_at_time\n *\n * @return $this\n */\n public function setExpiresAtTime($expires_at_time)\n {\n $this->container['expires_at_time'] = $expires_at_time;\n\n return $this;\n }\n\n /**\n * Gets gain_loss_dollars\n *\n * @return int\n */\n public function getGainLossDollars()\n {\n return $this->container['gain_loss_dollars'];\n }\n\n /**\n * Sets gain_loss_dollars\n *\n * @param int $gain_loss_dollars gain_loss_dollars\n *\n * @return $this\n */\n public function setGainLossDollars($gain_loss_dollars)\n {\n $this->container['gain_loss_dollars'] = $gain_loss_dollars;\n\n return $this;\n }\n\n /**\n * Gets gain_loss_percentage\n *\n * @return int\n */\n public function getGainLossPercentage()\n {\n return $this->container['gain_loss_percentage'];\n }\n\n /**\n * Sets gain_loss_percentage\n *\n * @param int $gain_loss_percentage gain_loss_percentage\n *\n * @return $this\n */\n public function setGainLossPercentage($gain_loss_percentage)\n {\n $this->container['gain_loss_percentage'] = $gain_loss_percentage;\n\n return $this;\n }\n\n /**\n * Gets market_value\n *\n * @return string\n */\n public function getMarketValue()\n {\n return $this->container['market_value'];\n }\n\n /**\n * Sets market_value\n *\n * @param string $market_value market_value\n *\n * @return $this\n */\n public function setMarketValue($market_value)\n {\n $this->container['market_value'] = $market_value;\n\n return $this;\n }\n\n /**\n * Gets matched_state\n *\n * @return int\n */\n public function getMatchedState()\n {\n return $this->container['matched_state'];\n }\n\n /**\n * Sets matched_state\n *\n * @param int $matched_state matched_state\n *\n * @return $this\n */\n public function setMatchedState($matched_state)\n {\n $this->container['matched_state'] = $matched_state;\n\n return $this;\n }\n\n /**\n * Gets purchase_date\n *\n * @return string\n */\n public function getPurchaseDate()\n {\n return $this->container['purchase_date'];\n }\n\n /**\n * Sets purchase_date\n *\n * @param string $purchase_date purchase_date\n *\n * @return $this\n */\n public function setPurchaseDate($purchase_date)\n {\n $this->container['purchase_date'] = $purchase_date;\n\n return $this;\n }\n\n /**\n * Gets purchase_date_time\n *\n * @return int\n */\n public function getPurchaseDateTime()\n {\n return $this->container['purchase_date_time'];\n }\n\n /**\n * Sets purchase_date_time\n *\n * @param int $purchase_date_time purchase_date_time\n *\n * @return $this\n */\n public function setPurchaseDateTime($purchase_date_time)\n {\n $this->container['purchase_date_time'] = $purchase_date_time;\n\n return $this;\n }\n\n /**\n * Gets state\n *\n * @return int\n */\n public function getState()\n {\n return $this->container['state'];\n }\n\n /**\n * Sets state\n *\n * @param int $state state\n *\n * @return $this\n */\n public function setState($state)\n {\n $this->container['state'] = $state;\n\n return $this;\n }\n\n /**\n * Gets text\n *\n * @return string\n */\n public function getText()\n {\n return $this->container['text'];\n }\n\n /**\n * Sets text\n *\n * @param string $text text\n *\n * @return $this\n */\n public function setText($text)\n {\n $this->container['text'] = $text;\n\n return $this;\n }\n\n /**\n * Gets created_at\n *\n * @return string\n */\n public function getCreatedAt()\n {\n return $this->container['created_at'];\n }\n\n /**\n * Sets created_at\n *\n * @param string $created_at created_at\n *\n * @return $this\n */\n public function setCreatedAt($created_at)\n {\n $this->container['created_at'] = $created_at;\n\n return $this;\n }\n\n /**\n * Gets created_at_time\n *\n * @return int\n */\n public function getCreatedAtTime()\n {\n return $this->container['created_at_time'];\n }\n\n /**\n * Sets created_at_time\n *\n * @param int $created_at_time created_at_time\n *\n * @return $this\n */\n public function setCreatedAtTime($created_at_time)\n {\n $this->container['created_at_time'] = $created_at_time;\n\n return $this;\n }\n\n /**\n * Gets can_edit\n *\n * @return bool\n */\n public function getCanEdit()\n {\n return $this->container['can_edit'];\n }\n\n /**\n * Sets can_edit\n *\n * @param bool $can_edit can_edit\n *\n * @return $this\n */\n public function setCanEdit($can_edit)\n {\n $this->container['can_edit'] = $can_edit;\n\n return $this;\n }\n\n /**\n * Gets can_delete\n *\n * @return bool\n */\n public function getCanDelete()\n {\n return $this->container['can_delete'];\n }\n\n /**\n * Sets can_delete\n *\n * @param bool $can_delete can_delete\n *\n * @return $this\n */\n public function setCanDelete($can_delete)\n {\n $this->container['can_delete'] = $can_delete;\n\n return $this;\n }\n\n /**\n * Gets tracking\n *\n * @return \\StockX\\Client\\Model\\PortfolioIdDelResponsePortfolioItemTracking\n */\n public function getTracking()\n {\n return $this->container['tracking'];\n }\n\n /**\n * Sets tracking\n *\n * @param \\StockX\\Client\\Model\\PortfolioIdDelResponsePortfolioItemTracking $tracking tracking\n *\n * @return $this\n */\n public function setTracking($tracking)\n {\n $this->container['tracking'] = $tracking;\n\n return $this;\n }\n\n /**\n * Gets meta\n *\n * @return object\n */\n public function getMeta()\n {\n return $this->container['meta'];\n }\n\n /**\n * Sets meta\n *\n * @param object $meta meta\n *\n * @return $this\n */\n public function setMeta($meta)\n {\n $this->container['meta'] = $meta;\n\n return $this;\n }\n\n /**\n * Gets product\n *\n * @return \\StockX\\Client\\Model\\PortfolioitemsIdGetResponsePortfolioItemProduct\n */\n public function getProduct()\n {\n return $this->container['product'];\n }\n\n /**\n * Sets product\n *\n * @param \\StockX\\Client\\Model\\PortfolioitemsIdGetResponsePortfolioItemProduct $product product\n *\n * @return $this\n */\n public function setProduct($product)\n {\n $this->container['product'] = $product;\n\n return $this;\n }\n\n /**\n * Gets merchant\n *\n * @return \\StockX\\Client\\Model\\PortfolioIdDelResponsePortfolioItemMerchant\n */\n public function getMerchant()\n {\n return $this->container['merchant'];\n }\n\n /**\n * Sets merchant\n *\n * @param \\StockX\\Client\\Model\\PortfolioIdDelResponsePortfolioItemMerchant $merchant merchant\n *\n * @return $this\n */\n public function setMerchant($merchant)\n {\n $this->container['merchant'] = $merchant;\n\n return $this;\n }\n /**\n * Returns true if offset exists. False otherwise.\n *\n * @param integer $offset Offset\n *\n * @return boolean\n */\n public function offsetExists($offset)\n {\n return isset($this->container[$offset]);\n }\n\n /**\n * Gets offset.\n *\n * @param integer $offset Offset\n *\n * @return mixed\n */\n public function offsetGet($offset)\n {\n return isset($this->container[$offset]) ? $this->container[$offset] : null;\n }\n\n /**\n * Sets value based on offset.\n *\n * @param integer $offset Offset\n * @param mixed $value Value to be set\n *\n * @return void\n */\n public function offsetSet($offset, $value)\n {\n if (is_null($offset)) {\n $this->container[] = $value;\n } else {\n $this->container[$offset] = $value;\n }\n }\n\n /**\n * Unsets offset.\n *\n * @param integer $offset Offset\n *\n * @return void\n */\n public function offsetUnset($offset)\n {\n unset($this->container[$offset]);\n }\n\n /**\n * Gets the string presentation of the object\n *\n * @return string\n */\n public function __toString()\n {\n if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print\n return json_encode(\n ObjectSerializer::sanitizeForSerialization($this),\n JSON_PRETTY_PRINT\n );\n }\n\n return json_encode(ObjectSerializer::sanitizeForSerialization($this));\n }\n}\n\n\n" }, { "alpha_fraction": 0.5838561654090881, "alphanum_fraction": 0.5847925543785095, "avg_line_length": 24.78985595703125, "blob_id": "6cf85a23fe3d6db7f8927a3deea756f614c1405c", "content_id": "cfdb64b18257ad49d50673983c9db9e1ac7a8b3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 10679, "license_type": "no_license", "max_line_length": 148, "num_lines": 414, "path": "/sdk/php/StockX-SDK-PHP/lib/lib/Model/PortfolioIdDelResponsePortfolioItemProductShipping.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * PortfolioIdDelResponsePortfolioItemProductShipping\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Do not edit the class manually.\n */\n\nnamespace StockX\\Client\\Model;\n\nuse \\ArrayAccess;\nuse \\StockX\\Client\\ObjectSerializer;\n\n/**\n * PortfolioIdDelResponsePortfolioItemProductShipping Class Doc Comment\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass PortfolioIdDelResponsePortfolioItemProductShipping implements ModelInterface, ArrayAccess\n{\n const DISCRIMINATOR = null;\n\n /**\n * The original name of the model.\n *\n * @var string\n */\n protected static $swaggerModelName = 'portfolio_id_del_response_PortfolioItem_product_shipping';\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerTypes = [\n 'total_days_to_ship' => 'int',\n 'has_additional_days_to_ship' => 'bool',\n 'delivery_days_lower_bound' => 'int',\n 'delivery_days_upper_bound' => 'int'\n ];\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerFormats = [\n 'total_days_to_ship' => null,\n 'has_additional_days_to_ship' => null,\n 'delivery_days_lower_bound' => null,\n 'delivery_days_upper_bound' => null\n ];\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerTypes()\n {\n return self::$swaggerTypes;\n }\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerFormats()\n {\n return self::$swaggerFormats;\n }\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @var string[]\n */\n protected static $attributeMap = [\n 'total_days_to_ship' => 'totalDaysToShip',\n 'has_additional_days_to_ship' => 'hasAdditionalDaysToShip',\n 'delivery_days_lower_bound' => 'deliveryDaysLowerBound',\n 'delivery_days_upper_bound' => 'deliveryDaysUpperBound'\n ];\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @var string[]\n */\n protected static $setters = [\n 'total_days_to_ship' => 'setTotalDaysToShip',\n 'has_additional_days_to_ship' => 'setHasAdditionalDaysToShip',\n 'delivery_days_lower_bound' => 'setDeliveryDaysLowerBound',\n 'delivery_days_upper_bound' => 'setDeliveryDaysUpperBound'\n ];\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @var string[]\n */\n protected static $getters = [\n 'total_days_to_ship' => 'getTotalDaysToShip',\n 'has_additional_days_to_ship' => 'getHasAdditionalDaysToShip',\n 'delivery_days_lower_bound' => 'getDeliveryDaysLowerBound',\n 'delivery_days_upper_bound' => 'getDeliveryDaysUpperBound'\n ];\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @return array\n */\n public static function attributeMap()\n {\n return self::$attributeMap;\n }\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @return array\n */\n public static function setters()\n {\n return self::$setters;\n }\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @return array\n */\n public static function getters()\n {\n return self::$getters;\n }\n\n /**\n * The original name of the model.\n *\n * @return string\n */\n public function getModelName()\n {\n return self::$swaggerModelName;\n }\n\n \n\n \n\n /**\n * Associative array for storing property values\n *\n * @var mixed[]\n */\n protected $container = [];\n\n /**\n * Constructor\n *\n * @param mixed[] $data Associated array of property values\n * initializing the model\n */\n public function __construct(array $data = null)\n {\n $this->container['total_days_to_ship'] = isset($data['total_days_to_ship']) ? $data['total_days_to_ship'] : null;\n $this->container['has_additional_days_to_ship'] = isset($data['has_additional_days_to_ship']) ? $data['has_additional_days_to_ship'] : null;\n $this->container['delivery_days_lower_bound'] = isset($data['delivery_days_lower_bound']) ? $data['delivery_days_lower_bound'] : null;\n $this->container['delivery_days_upper_bound'] = isset($data['delivery_days_upper_bound']) ? $data['delivery_days_upper_bound'] : null;\n }\n\n /**\n * Show all the invalid properties with reasons.\n *\n * @return array invalid properties with reasons\n */\n public function listInvalidProperties()\n {\n $invalidProperties = [];\n\n if ($this->container['total_days_to_ship'] === null) {\n $invalidProperties[] = \"'total_days_to_ship' can't be null\";\n }\n if ($this->container['has_additional_days_to_ship'] === null) {\n $invalidProperties[] = \"'has_additional_days_to_ship' can't be null\";\n }\n if ($this->container['delivery_days_lower_bound'] === null) {\n $invalidProperties[] = \"'delivery_days_lower_bound' can't be null\";\n }\n if ($this->container['delivery_days_upper_bound'] === null) {\n $invalidProperties[] = \"'delivery_days_upper_bound' can't be null\";\n }\n return $invalidProperties;\n }\n\n /**\n * Validate all the properties in the model\n * return true if all passed\n *\n * @return bool True if all properties are valid\n */\n public function valid()\n {\n\n if ($this->container['total_days_to_ship'] === null) {\n return false;\n }\n if ($this->container['has_additional_days_to_ship'] === null) {\n return false;\n }\n if ($this->container['delivery_days_lower_bound'] === null) {\n return false;\n }\n if ($this->container['delivery_days_upper_bound'] === null) {\n return false;\n }\n return true;\n }\n\n\n /**\n * Gets total_days_to_ship\n *\n * @return int\n */\n public function getTotalDaysToShip()\n {\n return $this->container['total_days_to_ship'];\n }\n\n /**\n * Sets total_days_to_ship\n *\n * @param int $total_days_to_ship total_days_to_ship\n *\n * @return $this\n */\n public function setTotalDaysToShip($total_days_to_ship)\n {\n $this->container['total_days_to_ship'] = $total_days_to_ship;\n\n return $this;\n }\n\n /**\n * Gets has_additional_days_to_ship\n *\n * @return bool\n */\n public function getHasAdditionalDaysToShip()\n {\n return $this->container['has_additional_days_to_ship'];\n }\n\n /**\n * Sets has_additional_days_to_ship\n *\n * @param bool $has_additional_days_to_ship has_additional_days_to_ship\n *\n * @return $this\n */\n public function setHasAdditionalDaysToShip($has_additional_days_to_ship)\n {\n $this->container['has_additional_days_to_ship'] = $has_additional_days_to_ship;\n\n return $this;\n }\n\n /**\n * Gets delivery_days_lower_bound\n *\n * @return int\n */\n public function getDeliveryDaysLowerBound()\n {\n return $this->container['delivery_days_lower_bound'];\n }\n\n /**\n * Sets delivery_days_lower_bound\n *\n * @param int $delivery_days_lower_bound delivery_days_lower_bound\n *\n * @return $this\n */\n public function setDeliveryDaysLowerBound($delivery_days_lower_bound)\n {\n $this->container['delivery_days_lower_bound'] = $delivery_days_lower_bound;\n\n return $this;\n }\n\n /**\n * Gets delivery_days_upper_bound\n *\n * @return int\n */\n public function getDeliveryDaysUpperBound()\n {\n return $this->container['delivery_days_upper_bound'];\n }\n\n /**\n * Sets delivery_days_upper_bound\n *\n * @param int $delivery_days_upper_bound delivery_days_upper_bound\n *\n * @return $this\n */\n public function setDeliveryDaysUpperBound($delivery_days_upper_bound)\n {\n $this->container['delivery_days_upper_bound'] = $delivery_days_upper_bound;\n\n return $this;\n }\n /**\n * Returns true if offset exists. False otherwise.\n *\n * @param integer $offset Offset\n *\n * @return boolean\n */\n public function offsetExists($offset)\n {\n return isset($this->container[$offset]);\n }\n\n /**\n * Gets offset.\n *\n * @param integer $offset Offset\n *\n * @return mixed\n */\n public function offsetGet($offset)\n {\n return isset($this->container[$offset]) ? $this->container[$offset] : null;\n }\n\n /**\n * Sets value based on offset.\n *\n * @param integer $offset Offset\n * @param mixed $value Value to be set\n *\n * @return void\n */\n public function offsetSet($offset, $value)\n {\n if (is_null($offset)) {\n $this->container[] = $value;\n } else {\n $this->container[$offset] = $value;\n }\n }\n\n /**\n * Unsets offset.\n *\n * @param integer $offset Offset\n *\n * @return void\n */\n public function offsetUnset($offset)\n {\n unset($this->container[$offset]);\n }\n\n /**\n * Gets the string presentation of the object\n *\n * @return string\n */\n public function __toString()\n {\n if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print\n return json_encode(\n ObjectSerializer::sanitizeForSerialization($this),\n JSON_PRETTY_PRINT\n );\n }\n\n return json_encode(ObjectSerializer::sanitizeForSerialization($this));\n }\n}\n\n\n" }, { "alpha_fraction": 0.7373493909835815, "alphanum_fraction": 0.7477911710739136, "avg_line_length": 30.125, "blob_id": "ae88418ccfdaa4b357a2491f6450dbcda55b1c21", "content_id": "70349029e12c1a2fda692df5935e893f4c6c12f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1245, "license_type": "no_license", "max_line_length": 176, "num_lines": 40, "path": "/sdk/python/lib/build/lib/test/test_portfolio_id_del_response_portfolio_item_product_media.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nfrom __future__ import absolute_import\n\nimport unittest\n\nimport io_stockx\nfrom io_stockx.models.portfolio_id_del_response_portfolio_item_product_media import PortfolioIdDelResponsePortfolioItemProductMedia # noqa: E501\nfrom io_stockx.rest import ApiException\n\n\nclass TestPortfolioIdDelResponsePortfolioItemProductMedia(unittest.TestCase):\n \"\"\"PortfolioIdDelResponsePortfolioItemProductMedia unit test stubs\"\"\"\n\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n def testPortfolioIdDelResponsePortfolioItemProductMedia(self):\n \"\"\"Test PortfolioIdDelResponsePortfolioItemProductMedia\"\"\"\n # FIXME: construct object with mandatory attributes with example values\n # model = io_stockx.models.portfolio_id_del_response_portfolio_item_product_media.PortfolioIdDelResponsePortfolioItemProductMedia() # noqa: E501\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.7726847529411316, "alphanum_fraction": 0.7736201882362366, "avg_line_length": 35.86206817626953, "blob_id": "1e8b897b2674921dde12955070c3b9da92923899", "content_id": "acdebb94debeaad81951a0aa5abf0371ca850e1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1069, "license_type": "no_license", "max_line_length": 127, "num_lines": 29, "path": "/sdk/java/README.md", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# StockX Public API - Java 8+ Library\n\n## Summary\n\nThis project provides a StockX Java assembly for accessing StockX's public API.\n\n## Usage\n\n* Add the StockX Jar from io.stock.sdk.examples/lib to your classpath (e.g. java -cp 'lib/io.stockx.sdk-x.x.x.jar')\n* The library is distributed as a fat jar, meaning all dependencies are within the library\n* Update the ExampleConstants source file to include your API Key (supplied by StockX) and your account credentials\n* Execute the examples with (e.g. java -cp lib/io.stockx.sdk-x.x.x-x.jar io.stockx.sdk.examples.endpoint.GetProductInfoExample)\n\n### Examples\n\nThis project provides the following examples of using the StockX Java Library:\n\n* Logging into the StockX API\n* Querying for open orders\n* Querying for market data about a product\n* Looking up product information\n* Searching the product catalog via general queries\n* Placing bids as a buyer\n* Placing asks as a seller\n\n### Directories\n\n/lib - contains the cross platform StockX Java library\n/src - contains examples of interacting with the StockX API with Java\n" }, { "alpha_fraction": 0.5764006972312927, "alphanum_fraction": 0.5785229206085205, "avg_line_length": 16.134546279907227, "blob_id": "c9a01688ae94dc3ac43ed8b1e2eaf4c24f4c2c01", "content_id": "7e85fa8fa48b8b0398c8f41e4e7c1fd8d382d4db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4712, "license_type": "no_license", "max_line_length": 110, "num_lines": 275, "path": "/sdk/php/StockX-SDK-PHP/lib/test/Model/PortfolioIdDelResponsePortfolioItemTest.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * PortfolioIdDelResponsePortfolioItemTest\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Please update the test case below to test the model.\n */\n\nnamespace StockX\\Client;\n\n/**\n * PortfolioIdDelResponsePortfolioItemTest Class Doc Comment\n *\n * @category Class */\n// * @description PortfolioIdDelResponsePortfolioItem\n/**\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass PortfolioIdDelResponsePortfolioItemTest extends \\PHPUnit_Framework_TestCase\n{\n\n /**\n * Setup before running any test case\n */\n public static function setUpBeforeClass()\n {\n }\n\n /**\n * Setup before running each test case\n */\n public function setUp()\n {\n }\n\n /**\n * Clean up after running each test case\n */\n public function tearDown()\n {\n }\n\n /**\n * Clean up after running all test cases\n */\n public static function tearDownAfterClass()\n {\n }\n\n /**\n * Test \"PortfolioIdDelResponsePortfolioItem\"\n */\n public function testPortfolioIdDelResponsePortfolioItem()\n {\n }\n\n /**\n * Test attribute \"chain_id\"\n */\n public function testPropertyChainId()\n {\n }\n\n /**\n * Test attribute \"customer_id\"\n */\n public function testPropertyCustomerId()\n {\n }\n\n /**\n * Test attribute \"inventory_id\"\n */\n public function testPropertyInventoryId()\n {\n }\n\n /**\n * Test attribute \"product_id\"\n */\n public function testPropertyProductId()\n {\n }\n\n /**\n * Test attribute \"sku_uuid\"\n */\n public function testPropertySkuUuid()\n {\n }\n\n /**\n * Test attribute \"merchant_id\"\n */\n public function testPropertyMerchantId()\n {\n }\n\n /**\n * Test attribute \"condition\"\n */\n public function testPropertyCondition()\n {\n }\n\n /**\n * Test attribute \"action\"\n */\n public function testPropertyAction()\n {\n }\n\n /**\n * Test attribute \"action_by\"\n */\n public function testPropertyActionBy()\n {\n }\n\n /**\n * Test attribute \"amount\"\n */\n public function testPropertyAmount()\n {\n }\n\n /**\n * Test attribute \"expires_at\"\n */\n public function testPropertyExpiresAt()\n {\n }\n\n /**\n * Test attribute \"expires_at_time\"\n */\n public function testPropertyExpiresAtTime()\n {\n }\n\n /**\n * Test attribute \"gain_loss_dollars\"\n */\n public function testPropertyGainLossDollars()\n {\n }\n\n /**\n * Test attribute \"gain_loss_percentage\"\n */\n public function testPropertyGainLossPercentage()\n {\n }\n\n /**\n * Test attribute \"market_value\"\n */\n public function testPropertyMarketValue()\n {\n }\n\n /**\n * Test attribute \"matched_state\"\n */\n public function testPropertyMatchedState()\n {\n }\n\n /**\n * Test attribute \"purchase_date\"\n */\n public function testPropertyPurchaseDate()\n {\n }\n\n /**\n * Test attribute \"purchase_date_time\"\n */\n public function testPropertyPurchaseDateTime()\n {\n }\n\n /**\n * Test attribute \"state\"\n */\n public function testPropertyState()\n {\n }\n\n /**\n * Test attribute \"text\"\n */\n public function testPropertyText()\n {\n }\n\n /**\n * Test attribute \"notes\"\n */\n public function testPropertyNotes()\n {\n }\n\n /**\n * Test attribute \"created_at_time\"\n */\n public function testPropertyCreatedAtTime()\n {\n }\n\n /**\n * Test attribute \"can_edit\"\n */\n public function testPropertyCanEdit()\n {\n }\n\n /**\n * Test attribute \"can_delete\"\n */\n public function testPropertyCanDelete()\n {\n }\n\n /**\n * Test attribute \"tracking\"\n */\n public function testPropertyTracking()\n {\n }\n\n /**\n * Test attribute \"meta\"\n */\n public function testPropertyMeta()\n {\n }\n\n /**\n * Test attribute \"product\"\n */\n public function testPropertyProduct()\n {\n }\n\n /**\n * Test attribute \"merchant\"\n */\n public function testPropertyMerchant()\n {\n }\n}\n" }, { "alpha_fraction": 0.517203688621521, "alphanum_fraction": 0.5182960033416748, "avg_line_length": 43.60975646972656, "blob_id": "d8d0c5ea88b7bb9b08a7b90637afe7562e78c4a6", "content_id": "06644d166ef0ffb72549e806ae47c2bade2120c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1831, "license_type": "no_license", "max_line_length": 161, "num_lines": 41, "path": "/sdk/python/lib/docs/SearchHit.md", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# SearchHit\n\n## Properties\nName | Type | Description | Notes\n------------ | ------------- | ------------- | -------------\n**name** | **str** | | [optional] \n**brand** | **str** | | [optional] \n**thumbnail_url** | **str** | | [optional] \n**media** | [**SearchHitMedia**](SearchHitMedia.md) | | [optional] \n**url** | **str** | | [optional] \n**release_date** | **str** | | [optional] \n**categories** | **list[str]** | | [optional] \n**product_category** | **str** | | [optional] \n**ticker_symbol** | **str** | | [optional] \n**style_id** | **str** | | [optional] \n**make** | **str** | | [optional] \n**model** | **str** | | [optional] \n**short_description** | **str** | | [optional] \n**gender** | **str** | | [optional] \n**colorway** | **str** | | [optional] \n**price** | **int** | | [optional] \n**description** | **str** | | [optional] \n**highest_bid** | **str** | | [optional] \n**total_dollars** | **str** | | [optional] \n**lowest_ask** | **str** | | [optional] \n**last_sale** | **str** | | [optional] \n**sales_last_72** | **int** | | [optional] \n**deadstock_sold** | **int** | | [optional] \n**quality_bid** | **int** | | [optional] \n**active** | **int** | | [optional] \n**new_release** | **str** | | [optional] \n**searchable_traits** | [**SearchHitSearchableTraits**](SearchHitSearchableTraits.md) | | [optional] \n**object_id** | **str** | | [optional] \n**annual_high** | **str** | | [optional] \n**annual_low** | **str** | | [optional] \n**deadstock_range_low** | **str** | | [optional] \n**deadstock_range_high** | **str** | | [optional] \n**average_deadstock_price** | **str** | | [optional] \n**change_value** | **str** | | [optional] \n\n[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)\n\n\n" }, { "alpha_fraction": 0.557607114315033, "alphanum_fraction": 0.5731167197227478, "avg_line_length": 32.04878234863281, "blob_id": "52d7435b95d04fd173e03c5880f07606f74fda37", "content_id": "230924cdaafa9c5e541433d1253066d9eff5a028", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1354, "license_type": "no_license", "max_line_length": 147, "num_lines": 41, "path": "/sdk/csharp/src/IO.StockX.Examples/GetProductMarketDataExample.cs", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "using System;\nusing System.Diagnostics;\nusing IO.StockX.Api;\nusing IO.StockX.Client;\nusing IO.StockX.Model;\n\nnamespace Example\n{\n /**\n * <p>Demonstrates retrieving information about a StockX product.</p>\n */\n public class GetProductMarketDataExample\n {\n static public void Main()\n {\n // Configure API key authorization: api_key\n Configuration.Default.AddApiKey(\"x-api-key\", ExampleConstants.AWS_API_KEY);\n\n var stockx = new StockXApi();\n stockx.Configuration.BasePath = ExampleConstants.STOCKX_ENDPOINT;\n \n var login = new LoginRequest(ExampleConstants.STOCKX_USERNAME, ExampleConstants.STOCKX_PASSWORD);\n \n try\n {\n // Login\n stockx.Login(login);\n \n // Lookup the supplied product by its product ID\n var marketData = stockx.GetProductMarketData(\"7f9c67ff-2cd4-4e27-8b64-518900a1bc0b\", \"air-jordan-1-retro-high-off-white-chicago\");\t\n \n Console.WriteLine(marketData);\n }\n catch (Exception e)\n {\n Console.WriteLine(e.ToString());\n Console.WriteLine(\"Exception when calling StockXApi.GetProductMarketData: \" + e.Message );\n }\n }\n }\n}" }, { "alpha_fraction": 0.5625798106193542, "alphanum_fraction": 0.5625798106193542, "avg_line_length": 43.68571472167969, "blob_id": "b480b1ec8fd0228269974789a6e8c3fdcbd3093d", "content_id": "91f580b77ee401379b671609c8d8a44b0d6c69ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1566, "license_type": "no_license", "max_line_length": 161, "num_lines": 35, "path": "/sdk/php/StockX-SDK-PHP/lib/docs/Model/PortfolioitemsIdGetResponsePortfolioItem.md", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# PortfolioitemsIdGetResponsePortfolioItem\n\n## Properties\nName | Type | Description | Notes\n------------ | ------------- | ------------- | -------------\n**chain_id** | **string** | | \n**customer_id** | **int** | | \n**inventory_id** | **string** | | \n**product_id** | **string** | | \n**sku_uuid** | **string** | | \n**merchant_id** | **int** | | \n**condition** | **int** | | \n**action** | **int** | | \n**action_by** | **int** | | \n**amount** | **int** | | \n**expires_at** | **string** | | \n**expires_at_time** | **int** | | \n**gain_loss_dollars** | **int** | | \n**gain_loss_percentage** | **int** | | \n**market_value** | **string** | | \n**matched_state** | **int** | | \n**purchase_date** | **string** | | \n**purchase_date_time** | **int** | | \n**state** | **int** | | \n**text** | **string** | | \n**created_at** | **string** | | \n**created_at_time** | **int** | | \n**can_edit** | **bool** | | \n**can_delete** | **bool** | | \n**tracking** | [**\\StockX\\Client\\Model\\PortfolioIdDelResponsePortfolioItemTracking**](PortfolioIdDelResponsePortfolioItemTracking.md) | | \n**meta** | **object** | | \n**product** | [**\\StockX\\Client\\Model\\PortfolioitemsIdGetResponsePortfolioItemProduct**](PortfolioitemsIdGetResponsePortfolioItemProduct.md) | | \n**merchant** | [**\\StockX\\Client\\Model\\PortfolioIdDelResponsePortfolioItemMerchant**](PortfolioIdDelResponsePortfolioItemMerchant.md) | | \n\n[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)\n\n\n" }, { "alpha_fraction": 0.5892711877822876, "alphanum_fraction": 0.6182606220245361, "avg_line_length": 29.016260147094727, "blob_id": "0dce91fed4d393a796911a1ec28acab609b3e116", "content_id": "08922516f49026cd8d44f8e9978d5ecd081f6133", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3691, "license_type": "no_license", "max_line_length": 98, "num_lines": 123, "path": "/sdk/php/StockX-SDK-PHP/src/PlaceNewLowestAskExample.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n\nerror_reporting(E_ALL);\nini_set('display_errors', 1);\n\nrequire_once(__DIR__ . '/../lib/vendor/autoload.php');\nrequire_once('LoginUtil.php');\nrequire_once('ExampleConstants.php');\nrequire_once('JWTHeaderSelector.php');\n\nfunction gen_uuid() {\n return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',\n // 32 bits for \"time_low\"\n mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),\n\n // 16 bits for \"time_mid\"\n mt_rand( 0, 0xffff ),\n\n // 16 bits for \"time_hi_and_version\",\n // four most significant bits holds version number 4\n mt_rand( 0, 0x0fff ) | 0x4000,\n\n // 16 bits, 8 bits for \"clk_seq_hi_res\",\n // 8 bits for \"clk_seq_low\",\n // two most significant bits holds zero and one for variant DCE1.1\n mt_rand( 0, 0x3fff ) | 0x8000,\n\n // 48 bits for \"node\"\n mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )\n );\n}\n\n$client = new GuzzleHttp\\Client();\n$config = StockX\\Client\\Configuration::getDefaultConfiguration()\n ->setApiKey('x-api-key', ExampleConstants::$AWS_API_KEY)\n ->setHost(Environment::$ENDPOINT_PUBLIC);\n // ->setHost(Environment::$ENDPOINT_STAGING);\n\n\n$headerSelector = new JWTHeaderSelector();\n\n$api = new StockX\\Client\\Api\\StockXApi(\n $client,\n $config,\n $headerSelector\n );\n\ntry {\n // Login to the StockX framework - see LoginExample for how this works\n $customer = LoginUtil::login($api, $headerSelector,\n ExampleConstants::$STOCKX_USERNAME,\n ExampleConstants::$STOCKX_PASSWORD);\n\n // Search for a given product and lookup its styleid\n $firstResult = $api->search(\"Air Jordan 13 Retro Men (white / true red-black)\")->getHits()[0];\n print_r($firstResult);\n // return;\n\n echo '<br/><br/>';\n\n $styleId = $firstResult->getStyleId();\n print_r($styleId);\n\n \n // Look up the product info by style id and size\n $productInfo = $api->lookupProduct($styleId, \"11\");\n\n echo '<br/></br>';\n\n print_r($productInfo);\n\n echo '<br/><br/>';\n\n //echo $productInfo->getSku().'<br/>';\n\n $productId = $productInfo[\"data\"][0][\"id\"];\n $productUuid = $productInfo[\"data\"][0][\"attributes\"][\"product_uuid\"];\n\n echo $productId.'<br/>';\n echo $productUuid.'<br/>';\n\n \n // Lookup the current market data for the product\n $marketData = $api->getProductMarketData($productId, $productUuid);\n\n print_r($marketData);\n\n echo '<br/><br/>';\n \n // Get the current highest bid and decrement it\n $lowestAsk = $marketData[\"market\"][\"lowest_ask\"];\n $lowestAsk--;\n\n echo $lowestAsk.'<br/>';\n\n $lowestAsk = 240;\n\n echo '<br/><br/>';\n\n //return;\n \n // Create a portfolio item request with a lower ask\n $portfolioItemReq = new StockX\\Client\\Model\\PortfolioRequestPortfolioItem();\n $portfolioItemReq->setAmount($lowestAsk);\n $portfolioItemReq->setSkuUuid($productId);\n //$portfolioItemReq->setSkuUuid(gen_uuid());\n $portfolioItemReq->setMatchedWithDate(\"2019-02-20T20:00:00+0000\");\n $portfolioItemReq->setExpiresAt(\"2019-03-19T20:00:00+00:00\");\n $portfolioItemReq->setCondition(\"New\");\n // $portfolioItemReq->\n \n $portfolioReq = new StockX\\Client\\Model\\PortfolioRequest();\n $portfolioReq->setPortfolioItem($portfolioItemReq);\n $portfolioReq->setCustomer($customer[0][\"customer\"]);\n $portfolioReq->setTimezone(\"America/Los_Angeles\");\n \n // Submit the ask\n $askResp = $api->newPortfolioAsk($portfolioReq);\n \n print_r($askResp);\n} catch (Exception $e) {\n echo 'Exception when calling StockXApi->newPortfolioAsk: ', $e->getMessage(), PHP_EOL;\n}" }, { "alpha_fraction": 0.6131221652030945, "alphanum_fraction": 0.6265172958374023, "avg_line_length": 31.914894104003906, "blob_id": "53d38abb7ce0fae949270d75c68c7da1beb51e09", "content_id": "bab9ca575a6124de6ccd8eb288b87f0489e0e9f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27846, "license_type": "no_license", "max_line_length": 515, "num_lines": 846, "path": "/sdk/python/lib/build/lib/io_stockx/models/portfolio_id_del_response_portfolio_item.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom io_stockx.models.portfolio_id_del_response_portfolio_item_merchant import PortfolioIdDelResponsePortfolioItemMerchant # noqa: F401,E501\nfrom io_stockx.models.portfolio_id_del_response_portfolio_item_product import PortfolioIdDelResponsePortfolioItemProduct # noqa: F401,E501\nfrom io_stockx.models.portfolio_id_del_response_portfolio_item_tracking import PortfolioIdDelResponsePortfolioItemTracking # noqa: F401,E501\n\n\nclass PortfolioIdDelResponsePortfolioItem(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'chain_id': 'str',\n 'customer_id': 'int',\n 'inventory_id': 'str',\n 'product_id': 'str',\n 'sku_uuid': 'str',\n 'merchant_id': 'int',\n 'condition': 'int',\n 'action': 'int',\n 'action_by': 'int',\n 'amount': 'int',\n 'expires_at': 'str',\n 'expires_at_time': 'int',\n 'gain_loss_dollars': 'int',\n 'gain_loss_percentage': 'int',\n 'market_value': 'str',\n 'matched_state': 'int',\n 'purchase_date': 'str',\n 'purchase_date_time': 'int',\n 'state': 'int',\n 'text': 'str',\n 'notes': 'str',\n 'created_at_time': 'int',\n 'can_edit': 'bool',\n 'can_delete': 'bool',\n 'tracking': 'PortfolioIdDelResponsePortfolioItemTracking',\n 'meta': 'object',\n 'product': 'PortfolioIdDelResponsePortfolioItemProduct',\n 'merchant': 'PortfolioIdDelResponsePortfolioItemMerchant'\n }\n\n attribute_map = {\n 'chain_id': 'chainId',\n 'customer_id': 'customerId',\n 'inventory_id': 'inventoryId',\n 'product_id': 'productId',\n 'sku_uuid': 'skuUuid',\n 'merchant_id': 'merchantId',\n 'condition': 'condition',\n 'action': 'action',\n 'action_by': 'actionBy',\n 'amount': 'amount',\n 'expires_at': 'expiresAt',\n 'expires_at_time': 'expiresAtTime',\n 'gain_loss_dollars': 'gainLossDollars',\n 'gain_loss_percentage': 'gainLossPercentage',\n 'market_value': 'marketValue',\n 'matched_state': 'matchedState',\n 'purchase_date': 'purchaseDate',\n 'purchase_date_time': 'purchaseDateTime',\n 'state': 'state',\n 'text': 'text',\n 'notes': 'notes',\n 'created_at_time': 'createdAtTime',\n 'can_edit': 'canEdit',\n 'can_delete': 'canDelete',\n 'tracking': 'Tracking',\n 'meta': 'meta',\n 'product': 'product',\n 'merchant': 'Merchant'\n }\n\n def __init__(self, chain_id=None, customer_id=None, inventory_id=None, product_id=None, sku_uuid=None, merchant_id=None, condition=None, action=None, action_by=None, amount=None, expires_at=None, expires_at_time=None, gain_loss_dollars=None, gain_loss_percentage=None, market_value=None, matched_state=None, purchase_date=None, purchase_date_time=None, state=None, text=None, notes=None, created_at_time=None, can_edit=None, can_delete=None, tracking=None, meta=None, product=None, merchant=None): # noqa: E501\n \"\"\"PortfolioIdDelResponsePortfolioItem - a model defined in Swagger\"\"\" # noqa: E501\n\n self._chain_id = None\n self._customer_id = None\n self._inventory_id = None\n self._product_id = None\n self._sku_uuid = None\n self._merchant_id = None\n self._condition = None\n self._action = None\n self._action_by = None\n self._amount = None\n self._expires_at = None\n self._expires_at_time = None\n self._gain_loss_dollars = None\n self._gain_loss_percentage = None\n self._market_value = None\n self._matched_state = None\n self._purchase_date = None\n self._purchase_date_time = None\n self._state = None\n self._text = None\n self._notes = None\n self._created_at_time = None\n self._can_edit = None\n self._can_delete = None\n self._tracking = None\n self._meta = None\n self._product = None\n self._merchant = None\n self.discriminator = None\n\n self.chain_id = chain_id\n self.customer_id = customer_id\n self.inventory_id = inventory_id\n self.product_id = product_id\n self.sku_uuid = sku_uuid\n self.merchant_id = merchant_id\n self.condition = condition\n self.action = action\n self.action_by = action_by\n self.amount = amount\n self.expires_at = expires_at\n self.expires_at_time = expires_at_time\n self.gain_loss_dollars = gain_loss_dollars\n self.gain_loss_percentage = gain_loss_percentage\n self.market_value = market_value\n self.matched_state = matched_state\n self.purchase_date = purchase_date\n self.purchase_date_time = purchase_date_time\n self.state = state\n self.text = text\n self.notes = notes\n self.created_at_time = created_at_time\n self.can_edit = can_edit\n self.can_delete = can_delete\n self.tracking = tracking\n self.meta = meta\n self.product = product\n self.merchant = merchant\n\n @property\n def chain_id(self):\n \"\"\"Gets the chain_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The chain_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._chain_id\n\n @chain_id.setter\n def chain_id(self, chain_id):\n \"\"\"Sets the chain_id of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param chain_id: The chain_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: str\n \"\"\"\n if chain_id is None:\n raise ValueError(\"Invalid value for `chain_id`, must not be `None`\") # noqa: E501\n\n self._chain_id = chain_id\n\n @property\n def customer_id(self):\n \"\"\"Gets the customer_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The customer_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: int\n \"\"\"\n return self._customer_id\n\n @customer_id.setter\n def customer_id(self, customer_id):\n \"\"\"Sets the customer_id of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param customer_id: The customer_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: int\n \"\"\"\n if customer_id is None:\n raise ValueError(\"Invalid value for `customer_id`, must not be `None`\") # noqa: E501\n\n self._customer_id = customer_id\n\n @property\n def inventory_id(self):\n \"\"\"Gets the inventory_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The inventory_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._inventory_id\n\n @inventory_id.setter\n def inventory_id(self, inventory_id):\n \"\"\"Sets the inventory_id of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param inventory_id: The inventory_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: str\n \"\"\"\n if inventory_id is None:\n raise ValueError(\"Invalid value for `inventory_id`, must not be `None`\") # noqa: E501\n\n self._inventory_id = inventory_id\n\n @property\n def product_id(self):\n \"\"\"Gets the product_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The product_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._product_id\n\n @product_id.setter\n def product_id(self, product_id):\n \"\"\"Sets the product_id of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param product_id: The product_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: str\n \"\"\"\n if product_id is None:\n raise ValueError(\"Invalid value for `product_id`, must not be `None`\") # noqa: E501\n\n self._product_id = product_id\n\n @property\n def sku_uuid(self):\n \"\"\"Gets the sku_uuid of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The sku_uuid of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._sku_uuid\n\n @sku_uuid.setter\n def sku_uuid(self, sku_uuid):\n \"\"\"Sets the sku_uuid of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param sku_uuid: The sku_uuid of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: str\n \"\"\"\n if sku_uuid is None:\n raise ValueError(\"Invalid value for `sku_uuid`, must not be `None`\") # noqa: E501\n\n self._sku_uuid = sku_uuid\n\n @property\n def merchant_id(self):\n \"\"\"Gets the merchant_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The merchant_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: int\n \"\"\"\n return self._merchant_id\n\n @merchant_id.setter\n def merchant_id(self, merchant_id):\n \"\"\"Sets the merchant_id of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param merchant_id: The merchant_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: int\n \"\"\"\n if merchant_id is None:\n raise ValueError(\"Invalid value for `merchant_id`, must not be `None`\") # noqa: E501\n\n self._merchant_id = merchant_id\n\n @property\n def condition(self):\n \"\"\"Gets the condition of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The condition of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: int\n \"\"\"\n return self._condition\n\n @condition.setter\n def condition(self, condition):\n \"\"\"Sets the condition of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param condition: The condition of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: int\n \"\"\"\n if condition is None:\n raise ValueError(\"Invalid value for `condition`, must not be `None`\") # noqa: E501\n\n self._condition = condition\n\n @property\n def action(self):\n \"\"\"Gets the action of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The action of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: int\n \"\"\"\n return self._action\n\n @action.setter\n def action(self, action):\n \"\"\"Sets the action of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param action: The action of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: int\n \"\"\"\n if action is None:\n raise ValueError(\"Invalid value for `action`, must not be `None`\") # noqa: E501\n\n self._action = action\n\n @property\n def action_by(self):\n \"\"\"Gets the action_by of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The action_by of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: int\n \"\"\"\n return self._action_by\n\n @action_by.setter\n def action_by(self, action_by):\n \"\"\"Sets the action_by of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param action_by: The action_by of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: int\n \"\"\"\n if action_by is None:\n raise ValueError(\"Invalid value for `action_by`, must not be `None`\") # noqa: E501\n\n self._action_by = action_by\n\n @property\n def amount(self):\n \"\"\"Gets the amount of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The amount of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: int\n \"\"\"\n return self._amount\n\n @amount.setter\n def amount(self, amount):\n \"\"\"Sets the amount of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param amount: The amount of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: int\n \"\"\"\n if amount is None:\n raise ValueError(\"Invalid value for `amount`, must not be `None`\") # noqa: E501\n\n self._amount = amount\n\n @property\n def expires_at(self):\n \"\"\"Gets the expires_at of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The expires_at of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._expires_at\n\n @expires_at.setter\n def expires_at(self, expires_at):\n \"\"\"Sets the expires_at of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param expires_at: The expires_at of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: str\n \"\"\"\n if expires_at is None:\n raise ValueError(\"Invalid value for `expires_at`, must not be `None`\") # noqa: E501\n\n self._expires_at = expires_at\n\n @property\n def expires_at_time(self):\n \"\"\"Gets the expires_at_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The expires_at_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: int\n \"\"\"\n return self._expires_at_time\n\n @expires_at_time.setter\n def expires_at_time(self, expires_at_time):\n \"\"\"Sets the expires_at_time of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param expires_at_time: The expires_at_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: int\n \"\"\"\n if expires_at_time is None:\n raise ValueError(\"Invalid value for `expires_at_time`, must not be `None`\") # noqa: E501\n\n self._expires_at_time = expires_at_time\n\n @property\n def gain_loss_dollars(self):\n \"\"\"Gets the gain_loss_dollars of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The gain_loss_dollars of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: int\n \"\"\"\n return self._gain_loss_dollars\n\n @gain_loss_dollars.setter\n def gain_loss_dollars(self, gain_loss_dollars):\n \"\"\"Sets the gain_loss_dollars of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param gain_loss_dollars: The gain_loss_dollars of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: int\n \"\"\"\n if gain_loss_dollars is None:\n raise ValueError(\"Invalid value for `gain_loss_dollars`, must not be `None`\") # noqa: E501\n\n self._gain_loss_dollars = gain_loss_dollars\n\n @property\n def gain_loss_percentage(self):\n \"\"\"Gets the gain_loss_percentage of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The gain_loss_percentage of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: int\n \"\"\"\n return self._gain_loss_percentage\n\n @gain_loss_percentage.setter\n def gain_loss_percentage(self, gain_loss_percentage):\n \"\"\"Sets the gain_loss_percentage of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param gain_loss_percentage: The gain_loss_percentage of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: int\n \"\"\"\n if gain_loss_percentage is None:\n raise ValueError(\"Invalid value for `gain_loss_percentage`, must not be `None`\") # noqa: E501\n\n self._gain_loss_percentage = gain_loss_percentage\n\n @property\n def market_value(self):\n \"\"\"Gets the market_value of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The market_value of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._market_value\n\n @market_value.setter\n def market_value(self, market_value):\n \"\"\"Sets the market_value of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param market_value: The market_value of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: str\n \"\"\"\n if market_value is None:\n raise ValueError(\"Invalid value for `market_value`, must not be `None`\") # noqa: E501\n\n self._market_value = market_value\n\n @property\n def matched_state(self):\n \"\"\"Gets the matched_state of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The matched_state of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: int\n \"\"\"\n return self._matched_state\n\n @matched_state.setter\n def matched_state(self, matched_state):\n \"\"\"Sets the matched_state of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param matched_state: The matched_state of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: int\n \"\"\"\n if matched_state is None:\n raise ValueError(\"Invalid value for `matched_state`, must not be `None`\") # noqa: E501\n\n self._matched_state = matched_state\n\n @property\n def purchase_date(self):\n \"\"\"Gets the purchase_date of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The purchase_date of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._purchase_date\n\n @purchase_date.setter\n def purchase_date(self, purchase_date):\n \"\"\"Sets the purchase_date of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param purchase_date: The purchase_date of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: str\n \"\"\"\n if purchase_date is None:\n raise ValueError(\"Invalid value for `purchase_date`, must not be `None`\") # noqa: E501\n\n self._purchase_date = purchase_date\n\n @property\n def purchase_date_time(self):\n \"\"\"Gets the purchase_date_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The purchase_date_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: int\n \"\"\"\n return self._purchase_date_time\n\n @purchase_date_time.setter\n def purchase_date_time(self, purchase_date_time):\n \"\"\"Sets the purchase_date_time of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param purchase_date_time: The purchase_date_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: int\n \"\"\"\n if purchase_date_time is None:\n raise ValueError(\"Invalid value for `purchase_date_time`, must not be `None`\") # noqa: E501\n\n self._purchase_date_time = purchase_date_time\n\n @property\n def state(self):\n \"\"\"Gets the state of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The state of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: int\n \"\"\"\n return self._state\n\n @state.setter\n def state(self, state):\n \"\"\"Sets the state of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param state: The state of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: int\n \"\"\"\n if state is None:\n raise ValueError(\"Invalid value for `state`, must not be `None`\") # noqa: E501\n\n self._state = state\n\n @property\n def text(self):\n \"\"\"Gets the text of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The text of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._text\n\n @text.setter\n def text(self, text):\n \"\"\"Sets the text of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param text: The text of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: str\n \"\"\"\n if text is None:\n raise ValueError(\"Invalid value for `text`, must not be `None`\") # noqa: E501\n\n self._text = text\n\n @property\n def notes(self):\n \"\"\"Gets the notes of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The notes of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._notes\n\n @notes.setter\n def notes(self, notes):\n \"\"\"Sets the notes of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param notes: The notes of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: str\n \"\"\"\n if notes is None:\n raise ValueError(\"Invalid value for `notes`, must not be `None`\") # noqa: E501\n\n self._notes = notes\n\n @property\n def created_at_time(self):\n \"\"\"Gets the created_at_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The created_at_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: int\n \"\"\"\n return self._created_at_time\n\n @created_at_time.setter\n def created_at_time(self, created_at_time):\n \"\"\"Sets the created_at_time of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param created_at_time: The created_at_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: int\n \"\"\"\n if created_at_time is None:\n raise ValueError(\"Invalid value for `created_at_time`, must not be `None`\") # noqa: E501\n\n self._created_at_time = created_at_time\n\n @property\n def can_edit(self):\n \"\"\"Gets the can_edit of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The can_edit of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._can_edit\n\n @can_edit.setter\n def can_edit(self, can_edit):\n \"\"\"Sets the can_edit of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param can_edit: The can_edit of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: bool\n \"\"\"\n if can_edit is None:\n raise ValueError(\"Invalid value for `can_edit`, must not be `None`\") # noqa: E501\n\n self._can_edit = can_edit\n\n @property\n def can_delete(self):\n \"\"\"Gets the can_delete of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The can_delete of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._can_delete\n\n @can_delete.setter\n def can_delete(self, can_delete):\n \"\"\"Sets the can_delete of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param can_delete: The can_delete of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: bool\n \"\"\"\n if can_delete is None:\n raise ValueError(\"Invalid value for `can_delete`, must not be `None`\") # noqa: E501\n\n self._can_delete = can_delete\n\n @property\n def tracking(self):\n \"\"\"Gets the tracking of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The tracking of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: PortfolioIdDelResponsePortfolioItemTracking\n \"\"\"\n return self._tracking\n\n @tracking.setter\n def tracking(self, tracking):\n \"\"\"Sets the tracking of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param tracking: The tracking of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: PortfolioIdDelResponsePortfolioItemTracking\n \"\"\"\n if tracking is None:\n raise ValueError(\"Invalid value for `tracking`, must not be `None`\") # noqa: E501\n\n self._tracking = tracking\n\n @property\n def meta(self):\n \"\"\"Gets the meta of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The meta of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: object\n \"\"\"\n return self._meta\n\n @meta.setter\n def meta(self, meta):\n \"\"\"Sets the meta of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param meta: The meta of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: object\n \"\"\"\n if meta is None:\n raise ValueError(\"Invalid value for `meta`, must not be `None`\") # noqa: E501\n\n self._meta = meta\n\n @property\n def product(self):\n \"\"\"Gets the product of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The product of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: PortfolioIdDelResponsePortfolioItemProduct\n \"\"\"\n return self._product\n\n @product.setter\n def product(self, product):\n \"\"\"Sets the product of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param product: The product of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: PortfolioIdDelResponsePortfolioItemProduct\n \"\"\"\n if product is None:\n raise ValueError(\"Invalid value for `product`, must not be `None`\") # noqa: E501\n\n self._product = product\n\n @property\n def merchant(self):\n \"\"\"Gets the merchant of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n\n\n :return: The merchant of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :rtype: PortfolioIdDelResponsePortfolioItemMerchant\n \"\"\"\n return self._merchant\n\n @merchant.setter\n def merchant(self, merchant):\n \"\"\"Sets the merchant of this PortfolioIdDelResponsePortfolioItem.\n\n\n :param merchant: The merchant of this PortfolioIdDelResponsePortfolioItem. # noqa: E501\n :type: PortfolioIdDelResponsePortfolioItemMerchant\n \"\"\"\n if merchant is None:\n raise ValueError(\"Invalid value for `merchant`, must not be `None`\") # noqa: E501\n\n self._merchant = merchant\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, PortfolioIdDelResponsePortfolioItem):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.5888352394104004, "alphanum_fraction": 0.6001669764518738, "avg_line_length": 27.908620834350586, "blob_id": "67ce5813661d2e9666fadefe780946a898ca820c", "content_id": "032966485960a3fe2f4cdfde9e501d7994e3f318", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16767, "license_type": "no_license", "max_line_length": 354, "num_lines": 580, "path": "/sdk/python/lib/io_stockx/models/product_info_product_attributes.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass ProductInfoProductAttributes(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'product_category': 'str',\n 'url_key': 'str',\n 'slug': 'str',\n 'brand': 'str',\n 'ticker': 'str',\n 'style_id': 'str',\n 'model': 'str',\n 'name': 'str',\n 'title': 'str',\n 'size_locale': 'str',\n 'size_title': 'str',\n 'size_descriptor': 'str',\n 'size_all_descriptor': 'str',\n 'gender': 'str',\n 'condition': 'str',\n 'minimum_bid': 'int',\n 'uniq_bids': 'bool',\n 'primary_category': 'str',\n 'secondary_category': 'str'\n }\n\n attribute_map = {\n 'product_category': 'product_category',\n 'url_key': 'url_key',\n 'slug': 'slug',\n 'brand': 'brand',\n 'ticker': 'ticker',\n 'style_id': 'style_id',\n 'model': 'model',\n 'name': 'name',\n 'title': 'title',\n 'size_locale': 'size_locale',\n 'size_title': 'size_title',\n 'size_descriptor': 'size_descriptor',\n 'size_all_descriptor': 'size_all_descriptor',\n 'gender': 'gender',\n 'condition': 'condition',\n 'minimum_bid': 'minimum_bid',\n 'uniq_bids': 'uniq_bids',\n 'primary_category': 'primary_category',\n 'secondary_category': 'secondary_category'\n }\n\n def __init__(self, product_category=None, url_key=None, slug=None, brand=None, ticker=None, style_id=None, model=None, name=None, title=None, size_locale=None, size_title=None, size_descriptor=None, size_all_descriptor=None, gender=None, condition=None, minimum_bid=None, uniq_bids=None, primary_category=None, secondary_category=None): # noqa: E501\n \"\"\"ProductInfoProductAttributes - a model defined in Swagger\"\"\" # noqa: E501\n\n self._product_category = None\n self._url_key = None\n self._slug = None\n self._brand = None\n self._ticker = None\n self._style_id = None\n self._model = None\n self._name = None\n self._title = None\n self._size_locale = None\n self._size_title = None\n self._size_descriptor = None\n self._size_all_descriptor = None\n self._gender = None\n self._condition = None\n self._minimum_bid = None\n self._uniq_bids = None\n self._primary_category = None\n self._secondary_category = None\n self.discriminator = None\n\n if product_category is not None:\n self.product_category = product_category\n if url_key is not None:\n self.url_key = url_key\n if slug is not None:\n self.slug = slug\n if brand is not None:\n self.brand = brand\n if ticker is not None:\n self.ticker = ticker\n if style_id is not None:\n self.style_id = style_id\n if model is not None:\n self.model = model\n if name is not None:\n self.name = name\n if title is not None:\n self.title = title\n if size_locale is not None:\n self.size_locale = size_locale\n if size_title is not None:\n self.size_title = size_title\n if size_descriptor is not None:\n self.size_descriptor = size_descriptor\n if size_all_descriptor is not None:\n self.size_all_descriptor = size_all_descriptor\n if gender is not None:\n self.gender = gender\n if condition is not None:\n self.condition = condition\n if minimum_bid is not None:\n self.minimum_bid = minimum_bid\n if uniq_bids is not None:\n self.uniq_bids = uniq_bids\n if primary_category is not None:\n self.primary_category = primary_category\n if secondary_category is not None:\n self.secondary_category = secondary_category\n\n @property\n def product_category(self):\n \"\"\"Gets the product_category of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The product_category of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._product_category\n\n @product_category.setter\n def product_category(self, product_category):\n \"\"\"Sets the product_category of this ProductInfoProductAttributes.\n\n\n :param product_category: The product_category of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._product_category = product_category\n\n @property\n def url_key(self):\n \"\"\"Gets the url_key of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The url_key of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._url_key\n\n @url_key.setter\n def url_key(self, url_key):\n \"\"\"Sets the url_key of this ProductInfoProductAttributes.\n\n\n :param url_key: The url_key of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._url_key = url_key\n\n @property\n def slug(self):\n \"\"\"Gets the slug of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The slug of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._slug\n\n @slug.setter\n def slug(self, slug):\n \"\"\"Sets the slug of this ProductInfoProductAttributes.\n\n\n :param slug: The slug of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._slug = slug\n\n @property\n def brand(self):\n \"\"\"Gets the brand of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The brand of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._brand\n\n @brand.setter\n def brand(self, brand):\n \"\"\"Sets the brand of this ProductInfoProductAttributes.\n\n\n :param brand: The brand of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._brand = brand\n\n @property\n def ticker(self):\n \"\"\"Gets the ticker of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The ticker of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._ticker\n\n @ticker.setter\n def ticker(self, ticker):\n \"\"\"Sets the ticker of this ProductInfoProductAttributes.\n\n\n :param ticker: The ticker of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._ticker = ticker\n\n @property\n def style_id(self):\n \"\"\"Gets the style_id of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The style_id of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._style_id\n\n @style_id.setter\n def style_id(self, style_id):\n \"\"\"Sets the style_id of this ProductInfoProductAttributes.\n\n\n :param style_id: The style_id of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._style_id = style_id\n\n @property\n def model(self):\n \"\"\"Gets the model of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The model of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._model\n\n @model.setter\n def model(self, model):\n \"\"\"Sets the model of this ProductInfoProductAttributes.\n\n\n :param model: The model of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._model = model\n\n @property\n def name(self):\n \"\"\"Gets the name of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The name of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this ProductInfoProductAttributes.\n\n\n :param name: The name of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._name = name\n\n @property\n def title(self):\n \"\"\"Gets the title of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The title of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._title\n\n @title.setter\n def title(self, title):\n \"\"\"Sets the title of this ProductInfoProductAttributes.\n\n\n :param title: The title of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._title = title\n\n @property\n def size_locale(self):\n \"\"\"Gets the size_locale of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The size_locale of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._size_locale\n\n @size_locale.setter\n def size_locale(self, size_locale):\n \"\"\"Sets the size_locale of this ProductInfoProductAttributes.\n\n\n :param size_locale: The size_locale of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._size_locale = size_locale\n\n @property\n def size_title(self):\n \"\"\"Gets the size_title of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The size_title of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._size_title\n\n @size_title.setter\n def size_title(self, size_title):\n \"\"\"Sets the size_title of this ProductInfoProductAttributes.\n\n\n :param size_title: The size_title of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._size_title = size_title\n\n @property\n def size_descriptor(self):\n \"\"\"Gets the size_descriptor of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The size_descriptor of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._size_descriptor\n\n @size_descriptor.setter\n def size_descriptor(self, size_descriptor):\n \"\"\"Sets the size_descriptor of this ProductInfoProductAttributes.\n\n\n :param size_descriptor: The size_descriptor of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._size_descriptor = size_descriptor\n\n @property\n def size_all_descriptor(self):\n \"\"\"Gets the size_all_descriptor of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The size_all_descriptor of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._size_all_descriptor\n\n @size_all_descriptor.setter\n def size_all_descriptor(self, size_all_descriptor):\n \"\"\"Sets the size_all_descriptor of this ProductInfoProductAttributes.\n\n\n :param size_all_descriptor: The size_all_descriptor of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._size_all_descriptor = size_all_descriptor\n\n @property\n def gender(self):\n \"\"\"Gets the gender of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The gender of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._gender\n\n @gender.setter\n def gender(self, gender):\n \"\"\"Sets the gender of this ProductInfoProductAttributes.\n\n\n :param gender: The gender of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._gender = gender\n\n @property\n def condition(self):\n \"\"\"Gets the condition of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The condition of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._condition\n\n @condition.setter\n def condition(self, condition):\n \"\"\"Sets the condition of this ProductInfoProductAttributes.\n\n\n :param condition: The condition of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._condition = condition\n\n @property\n def minimum_bid(self):\n \"\"\"Gets the minimum_bid of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The minimum_bid of this ProductInfoProductAttributes. # noqa: E501\n :rtype: int\n \"\"\"\n return self._minimum_bid\n\n @minimum_bid.setter\n def minimum_bid(self, minimum_bid):\n \"\"\"Sets the minimum_bid of this ProductInfoProductAttributes.\n\n\n :param minimum_bid: The minimum_bid of this ProductInfoProductAttributes. # noqa: E501\n :type: int\n \"\"\"\n\n self._minimum_bid = minimum_bid\n\n @property\n def uniq_bids(self):\n \"\"\"Gets the uniq_bids of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The uniq_bids of this ProductInfoProductAttributes. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._uniq_bids\n\n @uniq_bids.setter\n def uniq_bids(self, uniq_bids):\n \"\"\"Sets the uniq_bids of this ProductInfoProductAttributes.\n\n\n :param uniq_bids: The uniq_bids of this ProductInfoProductAttributes. # noqa: E501\n :type: bool\n \"\"\"\n\n self._uniq_bids = uniq_bids\n\n @property\n def primary_category(self):\n \"\"\"Gets the primary_category of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The primary_category of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._primary_category\n\n @primary_category.setter\n def primary_category(self, primary_category):\n \"\"\"Sets the primary_category of this ProductInfoProductAttributes.\n\n\n :param primary_category: The primary_category of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._primary_category = primary_category\n\n @property\n def secondary_category(self):\n \"\"\"Gets the secondary_category of this ProductInfoProductAttributes. # noqa: E501\n\n\n :return: The secondary_category of this ProductInfoProductAttributes. # noqa: E501\n :rtype: str\n \"\"\"\n return self._secondary_category\n\n @secondary_category.setter\n def secondary_category(self, secondary_category):\n \"\"\"Sets the secondary_category of this ProductInfoProductAttributes.\n\n\n :param secondary_category: The secondary_category of this ProductInfoProductAttributes. # noqa: E501\n :type: str\n \"\"\"\n\n self._secondary_category = secondary_category\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ProductInfoProductAttributes):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.5299749970436096, "alphanum_fraction": 0.5303040146827698, "avg_line_length": 22.022727966308594, "blob_id": "b4272d83db6fc18cf04cc747ca8dad8c9916e68b", "content_id": "5229620865cf7ee25370e546ea60f2f3a777bd13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 30392, "license_type": "no_license", "max_line_length": 133, "num_lines": 1320, "path": "/sdk/php/StockX-SDK-PHP/lib/lib/Model/ProductResponseProduct.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * ProductResponseProduct\n *\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Do not edit the class manually.\n */\n\nnamespace StockX\\Client\\Model;\n\nuse \\ArrayAccess;\nuse \\StockX\\Client\\ObjectSerializer;\n\n/**\n * ProductResponseProduct Class Doc Comment\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass ProductResponseProduct implements ModelInterface, ArrayAccess\n{\n const DISCRIMINATOR = null;\n\n /**\n * The original name of the model.\n *\n * @var string\n */\n protected static $swaggerModelName = 'product_response_Product';\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerTypes = [\n 'id' => 'string',\n 'uuid' => 'string',\n 'brand' => 'string',\n 'category' => 'string',\n 'charity_condition' => 'int',\n 'colorway' => 'string',\n 'condition' => 'string',\n 'country_of_manufacture' => 'string',\n 'gender' => 'string',\n 'content_group' => 'string',\n 'minimum_bid' => 'int',\n 'media' => '\\StockX\\Client\\Model\\ProductResponseProductMedia',\n 'name' => 'string',\n 'primary_category' => 'string',\n 'secondary_category' => 'string',\n 'product_category' => 'string',\n 'release_date' => 'string',\n 'retail_price' => 'int',\n 'shoe' => 'string',\n 'short_description' => 'string',\n 'style_id' => 'string',\n 'ticker_symbol' => 'string',\n 'title' => 'string',\n 'data_type' => 'string',\n 'type' => 'int',\n 'size_title' => 'string',\n 'size_descriptor' => 'string',\n 'size_all_descriptor' => 'string',\n 'url_key' => 'string',\n 'year' => 'string',\n 'shipping_group' => 'string',\n 'a_lim' => 'int',\n 'meta' => '\\StockX\\Client\\Model\\ProductResponseProductMeta',\n 'children' => '\\StockX\\Client\\Model\\ProductResponseProductChildren',\n 'market' => '\\StockX\\Client\\Model\\ProductResponseProductChildrenPRODUCTIDMarket'\n ];\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @var string[]\n */\n protected static $swaggerFormats = [\n 'id' => null,\n 'uuid' => null,\n 'brand' => null,\n 'category' => null,\n 'charity_condition' => null,\n 'colorway' => null,\n 'condition' => null,\n 'country_of_manufacture' => null,\n 'gender' => null,\n 'content_group' => null,\n 'minimum_bid' => null,\n 'media' => null,\n 'name' => null,\n 'primary_category' => null,\n 'secondary_category' => null,\n 'product_category' => null,\n 'release_date' => null,\n 'retail_price' => null,\n 'shoe' => null,\n 'short_description' => null,\n 'style_id' => null,\n 'ticker_symbol' => null,\n 'title' => null,\n 'data_type' => null,\n 'type' => null,\n 'size_title' => null,\n 'size_descriptor' => null,\n 'size_all_descriptor' => null,\n 'url_key' => null,\n 'year' => null,\n 'shipping_group' => null,\n 'a_lim' => null,\n 'meta' => null,\n 'children' => null,\n 'market' => null\n ];\n\n /**\n * Array of property to type mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerTypes()\n {\n return self::$swaggerTypes;\n }\n\n /**\n * Array of property to format mappings. Used for (de)serialization\n *\n * @return array\n */\n public static function swaggerFormats()\n {\n return self::$swaggerFormats;\n }\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @var string[]\n */\n protected static $attributeMap = [\n 'id' => 'id',\n 'uuid' => 'uuid',\n 'brand' => 'brand',\n 'category' => 'category',\n 'charity_condition' => 'charityCondition',\n 'colorway' => 'colorway',\n 'condition' => 'condition',\n 'country_of_manufacture' => 'countryOfManufacture',\n 'gender' => 'gender',\n 'content_group' => 'contentGroup',\n 'minimum_bid' => 'minimumBid',\n 'media' => 'media',\n 'name' => 'name',\n 'primary_category' => 'primaryCategory',\n 'secondary_category' => 'secondaryCategory',\n 'product_category' => 'productCategory',\n 'release_date' => 'releaseDate',\n 'retail_price' => 'retailPrice',\n 'shoe' => 'shoe',\n 'short_description' => 'shortDescription',\n 'style_id' => 'styleId',\n 'ticker_symbol' => 'tickerSymbol',\n 'title' => 'title',\n 'data_type' => 'dataType',\n 'type' => 'type',\n 'size_title' => 'sizeTitle',\n 'size_descriptor' => 'sizeDescriptor',\n 'size_all_descriptor' => 'sizeAllDescriptor',\n 'url_key' => 'urlKey',\n 'year' => 'year',\n 'shipping_group' => 'shippingGroup',\n 'a_lim' => 'aLim',\n 'meta' => 'meta',\n 'children' => 'children',\n 'market' => 'market'\n ];\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @var string[]\n */\n protected static $setters = [\n 'id' => 'setId',\n 'uuid' => 'setUuid',\n 'brand' => 'setBrand',\n 'category' => 'setCategory',\n 'charity_condition' => 'setCharityCondition',\n 'colorway' => 'setColorway',\n 'condition' => 'setCondition',\n 'country_of_manufacture' => 'setCountryOfManufacture',\n 'gender' => 'setGender',\n 'content_group' => 'setContentGroup',\n 'minimum_bid' => 'setMinimumBid',\n 'media' => 'setMedia',\n 'name' => 'setName',\n 'primary_category' => 'setPrimaryCategory',\n 'secondary_category' => 'setSecondaryCategory',\n 'product_category' => 'setProductCategory',\n 'release_date' => 'setReleaseDate',\n 'retail_price' => 'setRetailPrice',\n 'shoe' => 'setShoe',\n 'short_description' => 'setShortDescription',\n 'style_id' => 'setStyleId',\n 'ticker_symbol' => 'setTickerSymbol',\n 'title' => 'setTitle',\n 'data_type' => 'setDataType',\n 'type' => 'setType',\n 'size_title' => 'setSizeTitle',\n 'size_descriptor' => 'setSizeDescriptor',\n 'size_all_descriptor' => 'setSizeAllDescriptor',\n 'url_key' => 'setUrlKey',\n 'year' => 'setYear',\n 'shipping_group' => 'setShippingGroup',\n 'a_lim' => 'setALim',\n 'meta' => 'setMeta',\n 'children' => 'setChildren',\n 'market' => 'setMarket'\n ];\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @var string[]\n */\n protected static $getters = [\n 'id' => 'getId',\n 'uuid' => 'getUuid',\n 'brand' => 'getBrand',\n 'category' => 'getCategory',\n 'charity_condition' => 'getCharityCondition',\n 'colorway' => 'getColorway',\n 'condition' => 'getCondition',\n 'country_of_manufacture' => 'getCountryOfManufacture',\n 'gender' => 'getGender',\n 'content_group' => 'getContentGroup',\n 'minimum_bid' => 'getMinimumBid',\n 'media' => 'getMedia',\n 'name' => 'getName',\n 'primary_category' => 'getPrimaryCategory',\n 'secondary_category' => 'getSecondaryCategory',\n 'product_category' => 'getProductCategory',\n 'release_date' => 'getReleaseDate',\n 'retail_price' => 'getRetailPrice',\n 'shoe' => 'getShoe',\n 'short_description' => 'getShortDescription',\n 'style_id' => 'getStyleId',\n 'ticker_symbol' => 'getTickerSymbol',\n 'title' => 'getTitle',\n 'data_type' => 'getDataType',\n 'type' => 'getType',\n 'size_title' => 'getSizeTitle',\n 'size_descriptor' => 'getSizeDescriptor',\n 'size_all_descriptor' => 'getSizeAllDescriptor',\n 'url_key' => 'getUrlKey',\n 'year' => 'getYear',\n 'shipping_group' => 'getShippingGroup',\n 'a_lim' => 'getALim',\n 'meta' => 'getMeta',\n 'children' => 'getChildren',\n 'market' => 'getMarket'\n ];\n\n /**\n * Array of attributes where the key is the local name,\n * and the value is the original name\n *\n * @return array\n */\n public static function attributeMap()\n {\n return self::$attributeMap;\n }\n\n /**\n * Array of attributes to setter functions (for deserialization of responses)\n *\n * @return array\n */\n public static function setters()\n {\n return self::$setters;\n }\n\n /**\n * Array of attributes to getter functions (for serialization of requests)\n *\n * @return array\n */\n public static function getters()\n {\n return self::$getters;\n }\n\n /**\n * The original name of the model.\n *\n * @return string\n */\n public function getModelName()\n {\n return self::$swaggerModelName;\n }\n\n \n\n \n\n /**\n * Associative array for storing property values\n *\n * @var mixed[]\n */\n protected $container = [];\n\n /**\n * Constructor\n *\n * @param mixed[] $data Associated array of property values\n * initializing the model\n */\n public function __construct(array $data = null)\n {\n $this->container['id'] = isset($data['id']) ? $data['id'] : null;\n $this->container['uuid'] = isset($data['uuid']) ? $data['uuid'] : null;\n $this->container['brand'] = isset($data['brand']) ? $data['brand'] : null;\n $this->container['category'] = isset($data['category']) ? $data['category'] : null;\n $this->container['charity_condition'] = isset($data['charity_condition']) ? $data['charity_condition'] : null;\n $this->container['colorway'] = isset($data['colorway']) ? $data['colorway'] : null;\n $this->container['condition'] = isset($data['condition']) ? $data['condition'] : null;\n $this->container['country_of_manufacture'] = isset($data['country_of_manufacture']) ? $data['country_of_manufacture'] : null;\n $this->container['gender'] = isset($data['gender']) ? $data['gender'] : null;\n $this->container['content_group'] = isset($data['content_group']) ? $data['content_group'] : null;\n $this->container['minimum_bid'] = isset($data['minimum_bid']) ? $data['minimum_bid'] : null;\n $this->container['media'] = isset($data['media']) ? $data['media'] : null;\n $this->container['name'] = isset($data['name']) ? $data['name'] : null;\n $this->container['primary_category'] = isset($data['primary_category']) ? $data['primary_category'] : null;\n $this->container['secondary_category'] = isset($data['secondary_category']) ? $data['secondary_category'] : null;\n $this->container['product_category'] = isset($data['product_category']) ? $data['product_category'] : null;\n $this->container['release_date'] = isset($data['release_date']) ? $data['release_date'] : null;\n $this->container['retail_price'] = isset($data['retail_price']) ? $data['retail_price'] : null;\n $this->container['shoe'] = isset($data['shoe']) ? $data['shoe'] : null;\n $this->container['short_description'] = isset($data['short_description']) ? $data['short_description'] : null;\n $this->container['style_id'] = isset($data['style_id']) ? $data['style_id'] : null;\n $this->container['ticker_symbol'] = isset($data['ticker_symbol']) ? $data['ticker_symbol'] : null;\n $this->container['title'] = isset($data['title']) ? $data['title'] : null;\n $this->container['data_type'] = isset($data['data_type']) ? $data['data_type'] : null;\n $this->container['type'] = isset($data['type']) ? $data['type'] : null;\n $this->container['size_title'] = isset($data['size_title']) ? $data['size_title'] : null;\n $this->container['size_descriptor'] = isset($data['size_descriptor']) ? $data['size_descriptor'] : null;\n $this->container['size_all_descriptor'] = isset($data['size_all_descriptor']) ? $data['size_all_descriptor'] : null;\n $this->container['url_key'] = isset($data['url_key']) ? $data['url_key'] : null;\n $this->container['year'] = isset($data['year']) ? $data['year'] : null;\n $this->container['shipping_group'] = isset($data['shipping_group']) ? $data['shipping_group'] : null;\n $this->container['a_lim'] = isset($data['a_lim']) ? $data['a_lim'] : null;\n $this->container['meta'] = isset($data['meta']) ? $data['meta'] : null;\n $this->container['children'] = isset($data['children']) ? $data['children'] : null;\n $this->container['market'] = isset($data['market']) ? $data['market'] : null;\n }\n\n /**\n * Show all the invalid properties with reasons.\n *\n * @return array invalid properties with reasons\n */\n public function listInvalidProperties()\n {\n $invalidProperties = [];\n\n return $invalidProperties;\n }\n\n /**\n * Validate all the properties in the model\n * return true if all passed\n *\n * @return bool True if all properties are valid\n */\n public function valid()\n {\n\n return true;\n }\n\n\n /**\n * Gets id\n *\n * @return string\n */\n public function getId()\n {\n return $this->container['id'];\n }\n\n /**\n * Sets id\n *\n * @param string $id id\n *\n * @return $this\n */\n public function setId($id)\n {\n $this->container['id'] = $id;\n\n return $this;\n }\n\n /**\n * Gets uuid\n *\n * @return string\n */\n public function getUuid()\n {\n return $this->container['uuid'];\n }\n\n /**\n * Sets uuid\n *\n * @param string $uuid uuid\n *\n * @return $this\n */\n public function setUuid($uuid)\n {\n $this->container['uuid'] = $uuid;\n\n return $this;\n }\n\n /**\n * Gets brand\n *\n * @return string\n */\n public function getBrand()\n {\n return $this->container['brand'];\n }\n\n /**\n * Sets brand\n *\n * @param string $brand brand\n *\n * @return $this\n */\n public function setBrand($brand)\n {\n $this->container['brand'] = $brand;\n\n return $this;\n }\n\n /**\n * Gets category\n *\n * @return string\n */\n public function getCategory()\n {\n return $this->container['category'];\n }\n\n /**\n * Sets category\n *\n * @param string $category category\n *\n * @return $this\n */\n public function setCategory($category)\n {\n $this->container['category'] = $category;\n\n return $this;\n }\n\n /**\n * Gets charity_condition\n *\n * @return int\n */\n public function getCharityCondition()\n {\n return $this->container['charity_condition'];\n }\n\n /**\n * Sets charity_condition\n *\n * @param int $charity_condition charity_condition\n *\n * @return $this\n */\n public function setCharityCondition($charity_condition)\n {\n $this->container['charity_condition'] = $charity_condition;\n\n return $this;\n }\n\n /**\n * Gets colorway\n *\n * @return string\n */\n public function getColorway()\n {\n return $this->container['colorway'];\n }\n\n /**\n * Sets colorway\n *\n * @param string $colorway colorway\n *\n * @return $this\n */\n public function setColorway($colorway)\n {\n $this->container['colorway'] = $colorway;\n\n return $this;\n }\n\n /**\n * Gets condition\n *\n * @return string\n */\n public function getCondition()\n {\n return $this->container['condition'];\n }\n\n /**\n * Sets condition\n *\n * @param string $condition condition\n *\n * @return $this\n */\n public function setCondition($condition)\n {\n $this->container['condition'] = $condition;\n\n return $this;\n }\n\n /**\n * Gets country_of_manufacture\n *\n * @return string\n */\n public function getCountryOfManufacture()\n {\n return $this->container['country_of_manufacture'];\n }\n\n /**\n * Sets country_of_manufacture\n *\n * @param string $country_of_manufacture country_of_manufacture\n *\n * @return $this\n */\n public function setCountryOfManufacture($country_of_manufacture)\n {\n $this->container['country_of_manufacture'] = $country_of_manufacture;\n\n return $this;\n }\n\n /**\n * Gets gender\n *\n * @return string\n */\n public function getGender()\n {\n return $this->container['gender'];\n }\n\n /**\n * Sets gender\n *\n * @param string $gender gender\n *\n * @return $this\n */\n public function setGender($gender)\n {\n $this->container['gender'] = $gender;\n\n return $this;\n }\n\n /**\n * Gets content_group\n *\n * @return string\n */\n public function getContentGroup()\n {\n return $this->container['content_group'];\n }\n\n /**\n * Sets content_group\n *\n * @param string $content_group content_group\n *\n * @return $this\n */\n public function setContentGroup($content_group)\n {\n $this->container['content_group'] = $content_group;\n\n return $this;\n }\n\n /**\n * Gets minimum_bid\n *\n * @return int\n */\n public function getMinimumBid()\n {\n return $this->container['minimum_bid'];\n }\n\n /**\n * Sets minimum_bid\n *\n * @param int $minimum_bid minimum_bid\n *\n * @return $this\n */\n public function setMinimumBid($minimum_bid)\n {\n $this->container['minimum_bid'] = $minimum_bid;\n\n return $this;\n }\n\n /**\n * Gets media\n *\n * @return \\StockX\\Client\\Model\\ProductResponseProductMedia\n */\n public function getMedia()\n {\n return $this->container['media'];\n }\n\n /**\n * Sets media\n *\n * @param \\StockX\\Client\\Model\\ProductResponseProductMedia $media media\n *\n * @return $this\n */\n public function setMedia($media)\n {\n $this->container['media'] = $media;\n\n return $this;\n }\n\n /**\n * Gets name\n *\n * @return string\n */\n public function getName()\n {\n return $this->container['name'];\n }\n\n /**\n * Sets name\n *\n * @param string $name name\n *\n * @return $this\n */\n public function setName($name)\n {\n $this->container['name'] = $name;\n\n return $this;\n }\n\n /**\n * Gets primary_category\n *\n * @return string\n */\n public function getPrimaryCategory()\n {\n return $this->container['primary_category'];\n }\n\n /**\n * Sets primary_category\n *\n * @param string $primary_category primary_category\n *\n * @return $this\n */\n public function setPrimaryCategory($primary_category)\n {\n $this->container['primary_category'] = $primary_category;\n\n return $this;\n }\n\n /**\n * Gets secondary_category\n *\n * @return string\n */\n public function getSecondaryCategory()\n {\n return $this->container['secondary_category'];\n }\n\n /**\n * Sets secondary_category\n *\n * @param string $secondary_category secondary_category\n *\n * @return $this\n */\n public function setSecondaryCategory($secondary_category)\n {\n $this->container['secondary_category'] = $secondary_category;\n\n return $this;\n }\n\n /**\n * Gets product_category\n *\n * @return string\n */\n public function getProductCategory()\n {\n return $this->container['product_category'];\n }\n\n /**\n * Sets product_category\n *\n * @param string $product_category product_category\n *\n * @return $this\n */\n public function setProductCategory($product_category)\n {\n $this->container['product_category'] = $product_category;\n\n return $this;\n }\n\n /**\n * Gets release_date\n *\n * @return string\n */\n public function getReleaseDate()\n {\n return $this->container['release_date'];\n }\n\n /**\n * Sets release_date\n *\n * @param string $release_date release_date\n *\n * @return $this\n */\n public function setReleaseDate($release_date)\n {\n $this->container['release_date'] = $release_date;\n\n return $this;\n }\n\n /**\n * Gets retail_price\n *\n * @return int\n */\n public function getRetailPrice()\n {\n return $this->container['retail_price'];\n }\n\n /**\n * Sets retail_price\n *\n * @param int $retail_price retail_price\n *\n * @return $this\n */\n public function setRetailPrice($retail_price)\n {\n $this->container['retail_price'] = $retail_price;\n\n return $this;\n }\n\n /**\n * Gets shoe\n *\n * @return string\n */\n public function getShoe()\n {\n return $this->container['shoe'];\n }\n\n /**\n * Sets shoe\n *\n * @param string $shoe shoe\n *\n * @return $this\n */\n public function setShoe($shoe)\n {\n $this->container['shoe'] = $shoe;\n\n return $this;\n }\n\n /**\n * Gets short_description\n *\n * @return string\n */\n public function getShortDescription()\n {\n return $this->container['short_description'];\n }\n\n /**\n * Sets short_description\n *\n * @param string $short_description short_description\n *\n * @return $this\n */\n public function setShortDescription($short_description)\n {\n $this->container['short_description'] = $short_description;\n\n return $this;\n }\n\n /**\n * Gets style_id\n *\n * @return string\n */\n public function getStyleId()\n {\n return $this->container['style_id'];\n }\n\n /**\n * Sets style_id\n *\n * @param string $style_id style_id\n *\n * @return $this\n */\n public function setStyleId($style_id)\n {\n $this->container['style_id'] = $style_id;\n\n return $this;\n }\n\n /**\n * Gets ticker_symbol\n *\n * @return string\n */\n public function getTickerSymbol()\n {\n return $this->container['ticker_symbol'];\n }\n\n /**\n * Sets ticker_symbol\n *\n * @param string $ticker_symbol ticker_symbol\n *\n * @return $this\n */\n public function setTickerSymbol($ticker_symbol)\n {\n $this->container['ticker_symbol'] = $ticker_symbol;\n\n return $this;\n }\n\n /**\n * Gets title\n *\n * @return string\n */\n public function getTitle()\n {\n return $this->container['title'];\n }\n\n /**\n * Sets title\n *\n * @param string $title title\n *\n * @return $this\n */\n public function setTitle($title)\n {\n $this->container['title'] = $title;\n\n return $this;\n }\n\n /**\n * Gets data_type\n *\n * @return string\n */\n public function getDataType()\n {\n return $this->container['data_type'];\n }\n\n /**\n * Sets data_type\n *\n * @param string $data_type data_type\n *\n * @return $this\n */\n public function setDataType($data_type)\n {\n $this->container['data_type'] = $data_type;\n\n return $this;\n }\n\n /**\n * Gets type\n *\n * @return int\n */\n public function getType()\n {\n return $this->container['type'];\n }\n\n /**\n * Sets type\n *\n * @param int $type type\n *\n * @return $this\n */\n public function setType($type)\n {\n $this->container['type'] = $type;\n\n return $this;\n }\n\n /**\n * Gets size_title\n *\n * @return string\n */\n public function getSizeTitle()\n {\n return $this->container['size_title'];\n }\n\n /**\n * Sets size_title\n *\n * @param string $size_title size_title\n *\n * @return $this\n */\n public function setSizeTitle($size_title)\n {\n $this->container['size_title'] = $size_title;\n\n return $this;\n }\n\n /**\n * Gets size_descriptor\n *\n * @return string\n */\n public function getSizeDescriptor()\n {\n return $this->container['size_descriptor'];\n }\n\n /**\n * Sets size_descriptor\n *\n * @param string $size_descriptor size_descriptor\n *\n * @return $this\n */\n public function setSizeDescriptor($size_descriptor)\n {\n $this->container['size_descriptor'] = $size_descriptor;\n\n return $this;\n }\n\n /**\n * Gets size_all_descriptor\n *\n * @return string\n */\n public function getSizeAllDescriptor()\n {\n return $this->container['size_all_descriptor'];\n }\n\n /**\n * Sets size_all_descriptor\n *\n * @param string $size_all_descriptor size_all_descriptor\n *\n * @return $this\n */\n public function setSizeAllDescriptor($size_all_descriptor)\n {\n $this->container['size_all_descriptor'] = $size_all_descriptor;\n\n return $this;\n }\n\n /**\n * Gets url_key\n *\n * @return string\n */\n public function getUrlKey()\n {\n return $this->container['url_key'];\n }\n\n /**\n * Sets url_key\n *\n * @param string $url_key url_key\n *\n * @return $this\n */\n public function setUrlKey($url_key)\n {\n $this->container['url_key'] = $url_key;\n\n return $this;\n }\n\n /**\n * Gets year\n *\n * @return string\n */\n public function getYear()\n {\n return $this->container['year'];\n }\n\n /**\n * Sets year\n *\n * @param string $year year\n *\n * @return $this\n */\n public function setYear($year)\n {\n $this->container['year'] = $year;\n\n return $this;\n }\n\n /**\n * Gets shipping_group\n *\n * @return string\n */\n public function getShippingGroup()\n {\n return $this->container['shipping_group'];\n }\n\n /**\n * Sets shipping_group\n *\n * @param string $shipping_group shipping_group\n *\n * @return $this\n */\n public function setShippingGroup($shipping_group)\n {\n $this->container['shipping_group'] = $shipping_group;\n\n return $this;\n }\n\n /**\n * Gets a_lim\n *\n * @return int\n */\n public function getALim()\n {\n return $this->container['a_lim'];\n }\n\n /**\n * Sets a_lim\n *\n * @param int $a_lim a_lim\n *\n * @return $this\n */\n public function setALim($a_lim)\n {\n $this->container['a_lim'] = $a_lim;\n\n return $this;\n }\n\n /**\n * Gets meta\n *\n * @return \\StockX\\Client\\Model\\ProductResponseProductMeta\n */\n public function getMeta()\n {\n return $this->container['meta'];\n }\n\n /**\n * Sets meta\n *\n * @param \\StockX\\Client\\Model\\ProductResponseProductMeta $meta meta\n *\n * @return $this\n */\n public function setMeta($meta)\n {\n $this->container['meta'] = $meta;\n\n return $this;\n }\n\n /**\n * Gets children\n *\n * @return \\StockX\\Client\\Model\\ProductResponseProductChildren\n */\n public function getChildren()\n {\n return $this->container['children'];\n }\n\n /**\n * Sets children\n *\n * @param \\StockX\\Client\\Model\\ProductResponseProductChildren $children children\n *\n * @return $this\n */\n public function setChildren($children)\n {\n $this->container['children'] = $children;\n\n return $this;\n }\n\n /**\n * Gets market\n *\n * @return \\StockX\\Client\\Model\\ProductResponseProductChildrenPRODUCTIDMarket\n */\n public function getMarket()\n {\n return $this->container['market'];\n }\n\n /**\n * Sets market\n *\n * @param \\StockX\\Client\\Model\\ProductResponseProductChildrenPRODUCTIDMarket $market market\n *\n * @return $this\n */\n public function setMarket($market)\n {\n $this->container['market'] = $market;\n\n return $this;\n }\n /**\n * Returns true if offset exists. False otherwise.\n *\n * @param integer $offset Offset\n *\n * @return boolean\n */\n public function offsetExists($offset)\n {\n return isset($this->container[$offset]);\n }\n\n /**\n * Gets offset.\n *\n * @param integer $offset Offset\n *\n * @return mixed\n */\n public function offsetGet($offset)\n {\n return isset($this->container[$offset]) ? $this->container[$offset] : null;\n }\n\n /**\n * Sets value based on offset.\n *\n * @param integer $offset Offset\n * @param mixed $value Value to be set\n *\n * @return void\n */\n public function offsetSet($offset, $value)\n {\n if (is_null($offset)) {\n $this->container[] = $value;\n } else {\n $this->container[$offset] = $value;\n }\n }\n\n /**\n * Unsets offset.\n *\n * @param integer $offset Offset\n *\n * @return void\n */\n public function offsetUnset($offset)\n {\n unset($this->container[$offset]);\n }\n\n /**\n * Gets the string presentation of the object\n *\n * @return string\n */\n public function __toString()\n {\n if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print\n return json_encode(\n ObjectSerializer::sanitizeForSerialization($this),\n JSON_PRETTY_PRINT\n );\n }\n\n return json_encode(ObjectSerializer::sanitizeForSerialization($this));\n }\n}\n\n\n" }, { "alpha_fraction": 0.6998320817947388, "alphanum_fraction": 0.7262804508209229, "avg_line_length": 32.54929733276367, "blob_id": "ad880be503b46542f4b09c9aeaad01f198308edb", "content_id": "62cc9c2832dc58144fb70430d549152c271d1aba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2382, "license_type": "no_license", "max_line_length": 113, "num_lines": 71, "path": "/sdk/python/src/place_new_lowest_ask_example.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "from __future__ import print_function\n\nimport time\nimport io_stockx\nfrom example_constants import ExampleConstants\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\n\nconfiguration.host = \"https://gateway.stockx.com/stage\"\nconfiguration.api_key['x-api-key'] = ExampleConstants.AWS_API_KEY\n\n# create an instance of the API class\nstockx = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nlogin = io_stockx.LoginRequest(email=ExampleConstants.STOCKX_USERNAME, password=ExampleConstants.STOCKX_PASSWORD)\n\ntry:\n # Attempts to log the user in with a username and password.\n api_response = stockx.login_with_http_info(login)\n\n # Get the customer object after login\n customer = api_response[0]\n\n # Get the login's assigned jwt token\n jwt_token = api_response[2]['Jwt-Authorization']\n\n # Use the jwt token to authenticate future requests\n stockx.api_client.set_default_header('jwt-authorization', jwt_token)\n\n # Search for a type of product\n search_result = stockx.search('Jordan Retro Black Cat')\n\n first_hit = search_result.hits[0]\n style_id = first_hit.style_id\n\n # Lookup the first product returned from the search\n product = stockx.lookup_product(identifier=style_id, size='11')\n\n # Get the current market data for the product (highest bid info, etc.)\n attributes = product.data[0].attributes\n id = product.data[0].id\n uuid = attributes.product_uuid\n\n # Get the product market data\n market_data = stockx.get_product_market_data(id, sku=uuid)\n\n # Get the lowest ask for the product and decrement it\n lowest_ask = market_data.market.lowest_ask\n lowest_ask += 1\n\n # Create a portfolio item request with a higher bid\n item = io_stockx.PortfolioRequestPortfolioItem()\n\n item.amount = lowest_ask\n item.sku_uuid = \"bae25b67-a721-4f57-ad5a-79973c7d0a5c\"\n item.matched_with_date = \"2018-12-12T05:00:00+0000\"\n item.expires_at = \"2018-12-12T12:39:07+00:00\"\n\n request = io_stockx.PortfolioRequest()\n request.portfolio_item = item\n request.customer = customer\n request.timezone = \"America/Detroit\"\n\n # Submit the ask\n ask_resp = stockx.new_portfolio_ask(request)\n\n pprint(ask_resp)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->new_portfolio_ask: %s\\n\" % e)\n" }, { "alpha_fraction": 0.7819277048110962, "alphanum_fraction": 0.7819277048110962, "avg_line_length": 35.08695602416992, "blob_id": "d5e2883a40935cc7aa3d4796fd09e7e53fc18cda", "content_id": "2c51dd384e1d959c6c25511751a434e17ba2a0b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 830, "license_type": "no_license", "max_line_length": 113, "num_lines": 23, "path": "/sdk/python/src/login.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport time\nimport io_stockx\nfrom example_constants import ExampleConstants\nfrom io_stockx.rest import ApiException\nfrom pprint import pprint\n\n# Configure API key authorization: api_key\nconfiguration = io_stockx.Configuration()\n\nconfiguration.host = \"https://gateway.stockx.com/stage\"\nconfiguration.api_key['x-api-key'] = ExampleConstants.AWS_API_KEY\n\n# create an instance of the API class\nstockx = io_stockx.StockXApi(io_stockx.ApiClient(configuration))\nlogin = io_stockx.LoginRequest(email=ExampleConstants.STOCKX_USERNAME, password=ExampleConstants.STOCKX_PASSWORD)\n\ntry:\n # Attempts to log the user in with a username and password.\n api_response = stockx.login(login)\n pprint(api_response)\nexcept ApiException as e:\n print(\"Exception when calling StockXApi->login: %s\\n\" % e)\n" }, { "alpha_fraction": 0.5595355033874512, "alphanum_fraction": 0.5737953186035156, "avg_line_length": 26.171634674072266, "blob_id": "544e8ca4b528e6a35193a5886a1ab808cb5c8af4", "content_id": "d95d2054a918ff656f5d7e294d13fc7ce372a6a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26438, "license_type": "no_license", "max_line_length": 639, "num_lines": 973, "path": "/sdk/python/lib/io_stockx/models/search_hit.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom io_stockx.models.search_hit_media import SearchHitMedia # noqa: F401,E501\nfrom io_stockx.models.search_hit_searchable_traits import SearchHitSearchableTraits # noqa: F401,E501\n\n\nclass SearchHit(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'name': 'str',\n 'brand': 'str',\n 'thumbnail_url': 'str',\n 'media': 'SearchHitMedia',\n 'url': 'str',\n 'release_date': 'str',\n 'categories': 'list[str]',\n 'product_category': 'str',\n 'ticker_symbol': 'str',\n 'style_id': 'str',\n 'make': 'str',\n 'model': 'str',\n 'short_description': 'str',\n 'gender': 'str',\n 'colorway': 'str',\n 'price': 'int',\n 'description': 'str',\n 'highest_bid': 'str',\n 'total_dollars': 'str',\n 'lowest_ask': 'str',\n 'last_sale': 'str',\n 'sales_last_72': 'int',\n 'deadstock_sold': 'int',\n 'quality_bid': 'int',\n 'active': 'int',\n 'new_release': 'str',\n 'searchable_traits': 'SearchHitSearchableTraits',\n 'object_id': 'str',\n 'annual_high': 'str',\n 'annual_low': 'str',\n 'deadstock_range_low': 'str',\n 'deadstock_range_high': 'str',\n 'average_deadstock_price': 'str',\n 'change_value': 'str'\n }\n\n attribute_map = {\n 'name': 'name',\n 'brand': 'brand',\n 'thumbnail_url': 'thumbnail_url',\n 'media': 'media',\n 'url': 'url',\n 'release_date': 'release_date',\n 'categories': 'categories',\n 'product_category': 'product_category',\n 'ticker_symbol': 'ticker_symbol',\n 'style_id': 'style_id',\n 'make': 'make',\n 'model': 'model',\n 'short_description': 'short_description',\n 'gender': 'gender',\n 'colorway': 'colorway',\n 'price': 'price',\n 'description': 'description',\n 'highest_bid': 'highest_bid',\n 'total_dollars': 'total_dollars',\n 'lowest_ask': 'lowest_ask',\n 'last_sale': 'last_sale',\n 'sales_last_72': 'sales_last_72',\n 'deadstock_sold': 'deadstock_sold',\n 'quality_bid': 'quality_bid',\n 'active': 'active',\n 'new_release': 'new_release',\n 'searchable_traits': 'searchable_traits',\n 'object_id': 'objectID',\n 'annual_high': 'annual_high',\n 'annual_low': 'annual_low',\n 'deadstock_range_low': 'deadstock_range_low',\n 'deadstock_range_high': 'deadstock_range_high',\n 'average_deadstock_price': 'average_deadstock_price',\n 'change_value': 'change_value'\n }\n\n def __init__(self, name=None, brand=None, thumbnail_url=None, media=None, url=None, release_date=None, categories=None, product_category=None, ticker_symbol=None, style_id=None, make=None, model=None, short_description=None, gender=None, colorway=None, price=None, description=None, highest_bid=None, total_dollars=None, lowest_ask=None, last_sale=None, sales_last_72=None, deadstock_sold=None, quality_bid=None, active=None, new_release=None, searchable_traits=None, object_id=None, annual_high=None, annual_low=None, deadstock_range_low=None, deadstock_range_high=None, average_deadstock_price=None, change_value=None): # noqa: E501\n \"\"\"SearchHit - a model defined in Swagger\"\"\" # noqa: E501\n\n self._name = None\n self._brand = None\n self._thumbnail_url = None\n self._media = None\n self._url = None\n self._release_date = None\n self._categories = None\n self._product_category = None\n self._ticker_symbol = None\n self._style_id = None\n self._make = None\n self._model = None\n self._short_description = None\n self._gender = None\n self._colorway = None\n self._price = None\n self._description = None\n self._highest_bid = None\n self._total_dollars = None\n self._lowest_ask = None\n self._last_sale = None\n self._sales_last_72 = None\n self._deadstock_sold = None\n self._quality_bid = None\n self._active = None\n self._new_release = None\n self._searchable_traits = None\n self._object_id = None\n self._annual_high = None\n self._annual_low = None\n self._deadstock_range_low = None\n self._deadstock_range_high = None\n self._average_deadstock_price = None\n self._change_value = None\n self.discriminator = None\n\n if name is not None:\n self.name = name\n if brand is not None:\n self.brand = brand\n if thumbnail_url is not None:\n self.thumbnail_url = thumbnail_url\n if media is not None:\n self.media = media\n if url is not None:\n self.url = url\n if release_date is not None:\n self.release_date = release_date\n if categories is not None:\n self.categories = categories\n if product_category is not None:\n self.product_category = product_category\n if ticker_symbol is not None:\n self.ticker_symbol = ticker_symbol\n if style_id is not None:\n self.style_id = style_id\n if make is not None:\n self.make = make\n if model is not None:\n self.model = model\n if short_description is not None:\n self.short_description = short_description\n if gender is not None:\n self.gender = gender\n if colorway is not None:\n self.colorway = colorway\n if price is not None:\n self.price = price\n if description is not None:\n self.description = description\n if highest_bid is not None:\n self.highest_bid = highest_bid\n if total_dollars is not None:\n self.total_dollars = total_dollars\n if lowest_ask is not None:\n self.lowest_ask = lowest_ask\n if last_sale is not None:\n self.last_sale = last_sale\n if sales_last_72 is not None:\n self.sales_last_72 = sales_last_72\n if deadstock_sold is not None:\n self.deadstock_sold = deadstock_sold\n if quality_bid is not None:\n self.quality_bid = quality_bid\n if active is not None:\n self.active = active\n if new_release is not None:\n self.new_release = new_release\n if searchable_traits is not None:\n self.searchable_traits = searchable_traits\n if object_id is not None:\n self.object_id = object_id\n if annual_high is not None:\n self.annual_high = annual_high\n if annual_low is not None:\n self.annual_low = annual_low\n if deadstock_range_low is not None:\n self.deadstock_range_low = deadstock_range_low\n if deadstock_range_high is not None:\n self.deadstock_range_high = deadstock_range_high\n if average_deadstock_price is not None:\n self.average_deadstock_price = average_deadstock_price\n if change_value is not None:\n self.change_value = change_value\n\n @property\n def name(self):\n \"\"\"Gets the name of this SearchHit. # noqa: E501\n\n\n :return: The name of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this SearchHit.\n\n\n :param name: The name of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._name = name\n\n @property\n def brand(self):\n \"\"\"Gets the brand of this SearchHit. # noqa: E501\n\n\n :return: The brand of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._brand\n\n @brand.setter\n def brand(self, brand):\n \"\"\"Sets the brand of this SearchHit.\n\n\n :param brand: The brand of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._brand = brand\n\n @property\n def thumbnail_url(self):\n \"\"\"Gets the thumbnail_url of this SearchHit. # noqa: E501\n\n\n :return: The thumbnail_url of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._thumbnail_url\n\n @thumbnail_url.setter\n def thumbnail_url(self, thumbnail_url):\n \"\"\"Sets the thumbnail_url of this SearchHit.\n\n\n :param thumbnail_url: The thumbnail_url of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._thumbnail_url = thumbnail_url\n\n @property\n def media(self):\n \"\"\"Gets the media of this SearchHit. # noqa: E501\n\n\n :return: The media of this SearchHit. # noqa: E501\n :rtype: SearchHitMedia\n \"\"\"\n return self._media\n\n @media.setter\n def media(self, media):\n \"\"\"Sets the media of this SearchHit.\n\n\n :param media: The media of this SearchHit. # noqa: E501\n :type: SearchHitMedia\n \"\"\"\n\n self._media = media\n\n @property\n def url(self):\n \"\"\"Gets the url of this SearchHit. # noqa: E501\n\n\n :return: The url of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._url\n\n @url.setter\n def url(self, url):\n \"\"\"Sets the url of this SearchHit.\n\n\n :param url: The url of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._url = url\n\n @property\n def release_date(self):\n \"\"\"Gets the release_date of this SearchHit. # noqa: E501\n\n\n :return: The release_date of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._release_date\n\n @release_date.setter\n def release_date(self, release_date):\n \"\"\"Sets the release_date of this SearchHit.\n\n\n :param release_date: The release_date of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._release_date = release_date\n\n @property\n def categories(self):\n \"\"\"Gets the categories of this SearchHit. # noqa: E501\n\n\n :return: The categories of this SearchHit. # noqa: E501\n :rtype: list[str]\n \"\"\"\n return self._categories\n\n @categories.setter\n def categories(self, categories):\n \"\"\"Sets the categories of this SearchHit.\n\n\n :param categories: The categories of this SearchHit. # noqa: E501\n :type: list[str]\n \"\"\"\n\n self._categories = categories\n\n @property\n def product_category(self):\n \"\"\"Gets the product_category of this SearchHit. # noqa: E501\n\n\n :return: The product_category of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._product_category\n\n @product_category.setter\n def product_category(self, product_category):\n \"\"\"Sets the product_category of this SearchHit.\n\n\n :param product_category: The product_category of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._product_category = product_category\n\n @property\n def ticker_symbol(self):\n \"\"\"Gets the ticker_symbol of this SearchHit. # noqa: E501\n\n\n :return: The ticker_symbol of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._ticker_symbol\n\n @ticker_symbol.setter\n def ticker_symbol(self, ticker_symbol):\n \"\"\"Sets the ticker_symbol of this SearchHit.\n\n\n :param ticker_symbol: The ticker_symbol of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._ticker_symbol = ticker_symbol\n\n @property\n def style_id(self):\n \"\"\"Gets the style_id of this SearchHit. # noqa: E501\n\n\n :return: The style_id of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._style_id\n\n @style_id.setter\n def style_id(self, style_id):\n \"\"\"Sets the style_id of this SearchHit.\n\n\n :param style_id: The style_id of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._style_id = style_id\n\n @property\n def make(self):\n \"\"\"Gets the make of this SearchHit. # noqa: E501\n\n\n :return: The make of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._make\n\n @make.setter\n def make(self, make):\n \"\"\"Sets the make of this SearchHit.\n\n\n :param make: The make of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._make = make\n\n @property\n def model(self):\n \"\"\"Gets the model of this SearchHit. # noqa: E501\n\n\n :return: The model of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._model\n\n @model.setter\n def model(self, model):\n \"\"\"Sets the model of this SearchHit.\n\n\n :param model: The model of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._model = model\n\n @property\n def short_description(self):\n \"\"\"Gets the short_description of this SearchHit. # noqa: E501\n\n\n :return: The short_description of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._short_description\n\n @short_description.setter\n def short_description(self, short_description):\n \"\"\"Sets the short_description of this SearchHit.\n\n\n :param short_description: The short_description of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._short_description = short_description\n\n @property\n def gender(self):\n \"\"\"Gets the gender of this SearchHit. # noqa: E501\n\n\n :return: The gender of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._gender\n\n @gender.setter\n def gender(self, gender):\n \"\"\"Sets the gender of this SearchHit.\n\n\n :param gender: The gender of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._gender = gender\n\n @property\n def colorway(self):\n \"\"\"Gets the colorway of this SearchHit. # noqa: E501\n\n\n :return: The colorway of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._colorway\n\n @colorway.setter\n def colorway(self, colorway):\n \"\"\"Sets the colorway of this SearchHit.\n\n\n :param colorway: The colorway of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._colorway = colorway\n\n @property\n def price(self):\n \"\"\"Gets the price of this SearchHit. # noqa: E501\n\n\n :return: The price of this SearchHit. # noqa: E501\n :rtype: int\n \"\"\"\n return self._price\n\n @price.setter\n def price(self, price):\n \"\"\"Sets the price of this SearchHit.\n\n\n :param price: The price of this SearchHit. # noqa: E501\n :type: int\n \"\"\"\n\n self._price = price\n\n @property\n def description(self):\n \"\"\"Gets the description of this SearchHit. # noqa: E501\n\n\n :return: The description of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._description\n\n @description.setter\n def description(self, description):\n \"\"\"Sets the description of this SearchHit.\n\n\n :param description: The description of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._description = description\n\n @property\n def highest_bid(self):\n \"\"\"Gets the highest_bid of this SearchHit. # noqa: E501\n\n\n :return: The highest_bid of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._highest_bid\n\n @highest_bid.setter\n def highest_bid(self, highest_bid):\n \"\"\"Sets the highest_bid of this SearchHit.\n\n\n :param highest_bid: The highest_bid of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._highest_bid = highest_bid\n\n @property\n def total_dollars(self):\n \"\"\"Gets the total_dollars of this SearchHit. # noqa: E501\n\n\n :return: The total_dollars of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._total_dollars\n\n @total_dollars.setter\n def total_dollars(self, total_dollars):\n \"\"\"Sets the total_dollars of this SearchHit.\n\n\n :param total_dollars: The total_dollars of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._total_dollars = total_dollars\n\n @property\n def lowest_ask(self):\n \"\"\"Gets the lowest_ask of this SearchHit. # noqa: E501\n\n\n :return: The lowest_ask of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._lowest_ask\n\n @lowest_ask.setter\n def lowest_ask(self, lowest_ask):\n \"\"\"Sets the lowest_ask of this SearchHit.\n\n\n :param lowest_ask: The lowest_ask of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._lowest_ask = lowest_ask\n\n @property\n def last_sale(self):\n \"\"\"Gets the last_sale of this SearchHit. # noqa: E501\n\n\n :return: The last_sale of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._last_sale\n\n @last_sale.setter\n def last_sale(self, last_sale):\n \"\"\"Sets the last_sale of this SearchHit.\n\n\n :param last_sale: The last_sale of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._last_sale = last_sale\n\n @property\n def sales_last_72(self):\n \"\"\"Gets the sales_last_72 of this SearchHit. # noqa: E501\n\n\n :return: The sales_last_72 of this SearchHit. # noqa: E501\n :rtype: int\n \"\"\"\n return self._sales_last_72\n\n @sales_last_72.setter\n def sales_last_72(self, sales_last_72):\n \"\"\"Sets the sales_last_72 of this SearchHit.\n\n\n :param sales_last_72: The sales_last_72 of this SearchHit. # noqa: E501\n :type: int\n \"\"\"\n\n self._sales_last_72 = sales_last_72\n\n @property\n def deadstock_sold(self):\n \"\"\"Gets the deadstock_sold of this SearchHit. # noqa: E501\n\n\n :return: The deadstock_sold of this SearchHit. # noqa: E501\n :rtype: int\n \"\"\"\n return self._deadstock_sold\n\n @deadstock_sold.setter\n def deadstock_sold(self, deadstock_sold):\n \"\"\"Sets the deadstock_sold of this SearchHit.\n\n\n :param deadstock_sold: The deadstock_sold of this SearchHit. # noqa: E501\n :type: int\n \"\"\"\n\n self._deadstock_sold = deadstock_sold\n\n @property\n def quality_bid(self):\n \"\"\"Gets the quality_bid of this SearchHit. # noqa: E501\n\n\n :return: The quality_bid of this SearchHit. # noqa: E501\n :rtype: int\n \"\"\"\n return self._quality_bid\n\n @quality_bid.setter\n def quality_bid(self, quality_bid):\n \"\"\"Sets the quality_bid of this SearchHit.\n\n\n :param quality_bid: The quality_bid of this SearchHit. # noqa: E501\n :type: int\n \"\"\"\n\n self._quality_bid = quality_bid\n\n @property\n def active(self):\n \"\"\"Gets the active of this SearchHit. # noqa: E501\n\n\n :return: The active of this SearchHit. # noqa: E501\n :rtype: int\n \"\"\"\n return self._active\n\n @active.setter\n def active(self, active):\n \"\"\"Sets the active of this SearchHit.\n\n\n :param active: The active of this SearchHit. # noqa: E501\n :type: int\n \"\"\"\n\n self._active = active\n\n @property\n def new_release(self):\n \"\"\"Gets the new_release of this SearchHit. # noqa: E501\n\n\n :return: The new_release of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._new_release\n\n @new_release.setter\n def new_release(self, new_release):\n \"\"\"Sets the new_release of this SearchHit.\n\n\n :param new_release: The new_release of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._new_release = new_release\n\n @property\n def searchable_traits(self):\n \"\"\"Gets the searchable_traits of this SearchHit. # noqa: E501\n\n\n :return: The searchable_traits of this SearchHit. # noqa: E501\n :rtype: SearchHitSearchableTraits\n \"\"\"\n return self._searchable_traits\n\n @searchable_traits.setter\n def searchable_traits(self, searchable_traits):\n \"\"\"Sets the searchable_traits of this SearchHit.\n\n\n :param searchable_traits: The searchable_traits of this SearchHit. # noqa: E501\n :type: SearchHitSearchableTraits\n \"\"\"\n\n self._searchable_traits = searchable_traits\n\n @property\n def object_id(self):\n \"\"\"Gets the object_id of this SearchHit. # noqa: E501\n\n\n :return: The object_id of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._object_id\n\n @object_id.setter\n def object_id(self, object_id):\n \"\"\"Sets the object_id of this SearchHit.\n\n\n :param object_id: The object_id of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._object_id = object_id\n\n @property\n def annual_high(self):\n \"\"\"Gets the annual_high of this SearchHit. # noqa: E501\n\n\n :return: The annual_high of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._annual_high\n\n @annual_high.setter\n def annual_high(self, annual_high):\n \"\"\"Sets the annual_high of this SearchHit.\n\n\n :param annual_high: The annual_high of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._annual_high = annual_high\n\n @property\n def annual_low(self):\n \"\"\"Gets the annual_low of this SearchHit. # noqa: E501\n\n\n :return: The annual_low of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._annual_low\n\n @annual_low.setter\n def annual_low(self, annual_low):\n \"\"\"Sets the annual_low of this SearchHit.\n\n\n :param annual_low: The annual_low of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._annual_low = annual_low\n\n @property\n def deadstock_range_low(self):\n \"\"\"Gets the deadstock_range_low of this SearchHit. # noqa: E501\n\n\n :return: The deadstock_range_low of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._deadstock_range_low\n\n @deadstock_range_low.setter\n def deadstock_range_low(self, deadstock_range_low):\n \"\"\"Sets the deadstock_range_low of this SearchHit.\n\n\n :param deadstock_range_low: The deadstock_range_low of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._deadstock_range_low = deadstock_range_low\n\n @property\n def deadstock_range_high(self):\n \"\"\"Gets the deadstock_range_high of this SearchHit. # noqa: E501\n\n\n :return: The deadstock_range_high of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._deadstock_range_high\n\n @deadstock_range_high.setter\n def deadstock_range_high(self, deadstock_range_high):\n \"\"\"Sets the deadstock_range_high of this SearchHit.\n\n\n :param deadstock_range_high: The deadstock_range_high of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._deadstock_range_high = deadstock_range_high\n\n @property\n def average_deadstock_price(self):\n \"\"\"Gets the average_deadstock_price of this SearchHit. # noqa: E501\n\n\n :return: The average_deadstock_price of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._average_deadstock_price\n\n @average_deadstock_price.setter\n def average_deadstock_price(self, average_deadstock_price):\n \"\"\"Sets the average_deadstock_price of this SearchHit.\n\n\n :param average_deadstock_price: The average_deadstock_price of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._average_deadstock_price = average_deadstock_price\n\n @property\n def change_value(self):\n \"\"\"Gets the change_value of this SearchHit. # noqa: E501\n\n\n :return: The change_value of this SearchHit. # noqa: E501\n :rtype: str\n \"\"\"\n return self._change_value\n\n @change_value.setter\n def change_value(self, change_value):\n \"\"\"Sets the change_value of this SearchHit.\n\n\n :param change_value: The change_value of this SearchHit. # noqa: E501\n :type: str\n \"\"\"\n\n self._change_value = change_value\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, SearchHit):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.5314270257949829, "alphanum_fraction": 0.5430266857147217, "avg_line_length": 25.47857093811035, "blob_id": "c501974f3ec8e5552216011c4cbcb3920ec868ed", "content_id": "e0a2f9fed632813812368cb8dd1476f6e86fa672", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3707, "license_type": "no_license", "max_line_length": 176, "num_lines": 140, "path": "/sdk/python/lib/build/lib/io_stockx/models/search_results.py", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\n\"\"\"\n StockX API\n\n PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501\n\n OpenAPI spec version: 1.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom io_stockx.models.search_hit import SearchHit # noqa: F401,E501\n\n\nclass SearchResults(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'hits': 'list[SearchHit]',\n 'nb_hits': 'int'\n }\n\n attribute_map = {\n 'hits': 'hits',\n 'nb_hits': 'nbHits'\n }\n\n def __init__(self, hits=None, nb_hits=None): # noqa: E501\n \"\"\"SearchResults - a model defined in Swagger\"\"\" # noqa: E501\n\n self._hits = None\n self._nb_hits = None\n self.discriminator = None\n\n if hits is not None:\n self.hits = hits\n if nb_hits is not None:\n self.nb_hits = nb_hits\n\n @property\n def hits(self):\n \"\"\"Gets the hits of this SearchResults. # noqa: E501\n\n\n :return: The hits of this SearchResults. # noqa: E501\n :rtype: list[SearchHit]\n \"\"\"\n return self._hits\n\n @hits.setter\n def hits(self, hits):\n \"\"\"Sets the hits of this SearchResults.\n\n\n :param hits: The hits of this SearchResults. # noqa: E501\n :type: list[SearchHit]\n \"\"\"\n\n self._hits = hits\n\n @property\n def nb_hits(self):\n \"\"\"Gets the nb_hits of this SearchResults. # noqa: E501\n\n\n :return: The nb_hits of this SearchResults. # noqa: E501\n :rtype: int\n \"\"\"\n return self._nb_hits\n\n @nb_hits.setter\n def nb_hits(self, nb_hits):\n \"\"\"Sets the nb_hits of this SearchResults.\n\n\n :param nb_hits: The nb_hits of this SearchResults. # noqa: E501\n :type: int\n \"\"\"\n\n self._nb_hits = nb_hits\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, SearchResults):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n" }, { "alpha_fraction": 0.48539823293685913, "alphanum_fraction": 0.4876147508621216, "avg_line_length": 33.130821228027344, "blob_id": "14da549a385bf3cae51bf217886184bbfae23260", "content_id": "cf3c048476dd4645fa89a2d0d774bac4c524a266", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 146626, "license_type": "no_license", "max_line_length": 141, "num_lines": 4296, "path": "/sdk/php/StockX-SDK-PHP/lib/lib/Api/StockXApi.php", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "<?php\n/**\n * StockXApi\n * PHP version 5\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\n\n/**\n * StockX API\n *\n * Provides access to StockX's public services, allowing end users to query for product and order information.\n *\n * OpenAPI spec version: final32218.2\n * \n * Generated by: https://github.com/swagger-api/swagger-codegen.git\n * Swagger Codegen version: 2.3.1\n */\n\n/**\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen\n * Do not edit the class manually.\n */\n\nnamespace StockX\\Client\\Api;\n\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\ClientInterface;\nuse GuzzleHttp\\Exception\\RequestException;\nuse GuzzleHttp\\Psr7\\MultipartStream;\nuse GuzzleHttp\\Psr7\\Request;\nuse GuzzleHttp\\RequestOptions;\nuse StockX\\Client\\ApiException;\nuse StockX\\Client\\Configuration;\nuse StockX\\Client\\HeaderSelector;\nuse StockX\\Client\\ObjectSerializer;\n\n/**\n * StockXApi Class Doc Comment\n *\n * @category Class\n * @package StockX\\Client\n * @author Swagger Codegen team\n * @link https://github.com/swagger-api/swagger-codegen\n */\nclass StockXApi\n{\n /**\n * @var ClientInterface\n */\n protected $client;\n\n /**\n * @var Configuration\n */\n protected $config;\n\n /**\n * @param ClientInterface $client\n * @param Configuration $config\n * @param HeaderSelector $selector\n */\n public function __construct(\n ClientInterface $client = null,\n Configuration $config = null,\n HeaderSelector $selector = null\n ) {\n $this->client = $client ?: new Client();\n $this->config = $config ?: new Configuration();\n $this->headerSelector = $selector ?: new HeaderSelector();\n }\n\n /**\n * @return Configuration\n */\n public function getConfig()\n {\n return $this->config;\n }\n\n /**\n * Operation deletePortfolio\n *\n * Deletes a portfolio item from the market with the specified id.\n *\n * @param string $id The id of the portfolio item to delete. (required)\n * @param \\StockX\\Client\\Model\\PortfolioIdDelRequest $portfolio The request information for the portfolio delete operation. (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return \\StockX\\Client\\Model\\PortfolioIdDelResponse\n */\n public function deletePortfolio($id, $portfolio)\n {\n list($response) = $this->deletePortfolioWithHttpInfo($id, $portfolio);\n return $response;\n }\n\n /**\n * Operation deletePortfolioWithHttpInfo\n *\n * Deletes a portfolio item from the market with the specified id.\n *\n * @param string $id The id of the portfolio item to delete. (required)\n * @param \\StockX\\Client\\Model\\PortfolioIdDelRequest $portfolio The request information for the portfolio delete operation. (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of \\StockX\\Client\\Model\\PortfolioIdDelResponse, HTTP status code, HTTP response headers (array of strings)\n */\n public function deletePortfolioWithHttpInfo($id, $portfolio)\n {\n $returnType = '\\StockX\\Client\\Model\\PortfolioIdDelResponse';\n $request = $this->deletePortfolioRequest($id, $portfolio);\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n case 200:\n $data = ObjectSerializer::deserialize(\n $e->getResponseBody(),\n '\\StockX\\Client\\Model\\PortfolioIdDelResponse',\n $e->getResponseHeaders()\n );\n $e->setResponseObject($data);\n break;\n }\n throw $e;\n }\n }\n\n /**\n * Operation deletePortfolioAsync\n *\n * Deletes a portfolio item from the market with the specified id.\n *\n * @param string $id The id of the portfolio item to delete. (required)\n * @param \\StockX\\Client\\Model\\PortfolioIdDelRequest $portfolio The request information for the portfolio delete operation. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function deletePortfolioAsync($id, $portfolio)\n {\n return $this->deletePortfolioAsyncWithHttpInfo($id, $portfolio)\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation deletePortfolioAsyncWithHttpInfo\n *\n * Deletes a portfolio item from the market with the specified id.\n *\n * @param string $id The id of the portfolio item to delete. (required)\n * @param \\StockX\\Client\\Model\\PortfolioIdDelRequest $portfolio The request information for the portfolio delete operation. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function deletePortfolioAsyncWithHttpInfo($id, $portfolio)\n {\n $returnType = '\\StockX\\Client\\Model\\PortfolioIdDelResponse';\n $request = $this->deletePortfolioRequest($id, $portfolio);\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'deletePortfolio'\n *\n * @param string $id The id of the portfolio item to delete. (required)\n * @param \\StockX\\Client\\Model\\PortfolioIdDelRequest $portfolio The request information for the portfolio delete operation. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function deletePortfolioRequest($id, $portfolio)\n {\n // verify the required parameter 'id' is set\n if ($id === null) {\n throw new \\InvalidArgumentException(\n 'Missing the required parameter $id when calling deletePortfolio'\n );\n }\n // verify the required parameter 'portfolio' is set\n if ($portfolio === null) {\n throw new \\InvalidArgumentException(\n 'Missing the required parameter $portfolio when calling deletePortfolio'\n );\n }\n\n $resourcePath = '/v1/portfolio/{id}';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n\n // path params\n if ($id !== null) {\n $resourcePath = str_replace(\n '{' . 'id' . '}',\n ObjectSerializer::toPathValue($id),\n $resourcePath\n );\n }\n\n // body params\n $_tempBody = null;\n if (isset($portfolio)) {\n $_tempBody = $portfolio;\n }\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n ['application/json']\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'DELETE',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Operation deleteWebhook\n *\n * @param string $id id (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return void\n */\n public function deleteWebhook($id)\n {\n $this->deleteWebhookWithHttpInfo($id);\n }\n\n /**\n * Operation deleteWebhookWithHttpInfo\n *\n * @param string $id (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of null, HTTP status code, HTTP response headers (array of strings)\n */\n public function deleteWebhookWithHttpInfo($id)\n {\n $returnType = '';\n $request = $this->deleteWebhookRequest($id);\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n return [null, $statusCode, $response->getHeaders()];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n }\n throw $e;\n }\n }\n\n /**\n * Operation deleteWebhookAsync\n *\n * \n *\n * @param string $id (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function deleteWebhookAsync($id)\n {\n return $this->deleteWebhookAsyncWithHttpInfo($id)\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation deleteWebhookAsyncWithHttpInfo\n *\n * \n *\n * @param string $id (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function deleteWebhookAsyncWithHttpInfo($id)\n {\n $returnType = '';\n $request = $this->deleteWebhookRequest($id);\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n return [null, $response->getStatusCode(), $response->getHeaders()];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'deleteWebhook'\n *\n * @param string $id (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function deleteWebhookRequest($id)\n {\n // verify the required parameter 'id' is set\n if ($id === null) {\n throw new \\InvalidArgumentException(\n 'Missing the required parameter $id when calling deleteWebhook'\n );\n }\n\n $resourcePath = '/webhook/v1/webhooks/{id}';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n\n // path params\n if ($id !== null) {\n $resourcePath = str_replace(\n '{' . 'id' . '}',\n ObjectSerializer::toPathValue($id),\n $resourcePath\n );\n }\n\n // body params\n $_tempBody = null;\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n []\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'DELETE',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Operation getOpenOrders\n *\n * @param string $id The customer id to lookup open orders with. (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return \\StockX\\Client\\Model\\CustomersIdSellingCurrent\n */\n public function getOpenOrders($id)\n {\n list($response) = $this->getOpenOrdersWithHttpInfo($id);\n return $response;\n }\n\n /**\n * Operation getOpenOrdersWithHttpInfo\n *\n * @param string $id The customer id to lookup open orders with. (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of \\StockX\\Client\\Model\\CustomersIdSellingCurrent, HTTP status code, HTTP response headers (array of strings)\n */\n public function getOpenOrdersWithHttpInfo($id)\n {\n $returnType = '\\StockX\\Client\\Model\\CustomersIdSellingCurrent';\n $request = $this->getOpenOrdersRequest($id);\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n case 200:\n $data = ObjectSerializer::deserialize(\n $e->getResponseBody(),\n '\\StockX\\Client\\Model\\CustomersIdSellingCurrent',\n $e->getResponseHeaders()\n );\n $e->setResponseObject($data);\n break;\n }\n throw $e;\n }\n }\n\n /**\n * Operation getOpenOrdersAsync\n *\n * \n *\n * @param string $id The customer id to lookup open orders with. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getOpenOrdersAsync($id)\n {\n return $this->getOpenOrdersAsyncWithHttpInfo($id)\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation getOpenOrdersAsyncWithHttpInfo\n *\n * \n *\n * @param string $id The customer id to lookup open orders with. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getOpenOrdersAsyncWithHttpInfo($id)\n {\n $returnType = '\\StockX\\Client\\Model\\CustomersIdSellingCurrent';\n $request = $this->getOpenOrdersRequest($id);\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'getOpenOrders'\n *\n * @param string $id The customer id to lookup open orders with. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function getOpenOrdersRequest($id)\n {\n // verify the required parameter 'id' is set\n if ($id === null) {\n throw new \\InvalidArgumentException(\n 'Missing the required parameter $id when calling getOpenOrders'\n );\n }\n\n $resourcePath = '/v1/customers/{id}/selling/current';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n\n // path params\n if ($id !== null) {\n $resourcePath = str_replace(\n '{' . 'id' . '}',\n ObjectSerializer::toPathValue($id),\n $resourcePath\n );\n }\n\n // body params\n $_tempBody = null;\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n []\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('jwt-authorization');\n if ($apiKey !== null) {\n $headers['jwt-authorization'] = $apiKey;\n }\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'GET',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Operation getPortfolio\n *\n * Returns a market portfolio identified by request parameters.\n *\n * @param \\StockX\\Client\\Model\\PortfolioRequest $portfolio Requests parameters for looking up a market portfolio. (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return \\StockX\\Client\\Model\\PortfolioResponse\n */\n public function getPortfolio($portfolio)\n {\n list($response) = $this->getPortfolioWithHttpInfo($portfolio);\n return $response;\n }\n\n /**\n * Operation getPortfolioWithHttpInfo\n *\n * Returns a market portfolio identified by request parameters.\n *\n * @param \\StockX\\Client\\Model\\PortfolioRequest $portfolio Requests parameters for looking up a market portfolio. (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of \\StockX\\Client\\Model\\PortfolioResponse, HTTP status code, HTTP response headers (array of strings)\n */\n public function getPortfolioWithHttpInfo($portfolio)\n {\n $returnType = '\\StockX\\Client\\Model\\PortfolioResponse';\n $request = $this->getPortfolioRequest($portfolio);\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n case 200:\n $data = ObjectSerializer::deserialize(\n $e->getResponseBody(),\n '\\StockX\\Client\\Model\\PortfolioResponse',\n $e->getResponseHeaders()\n );\n $e->setResponseObject($data);\n break;\n }\n throw $e;\n }\n }\n\n /**\n * Operation getPortfolioAsync\n *\n * Returns a market portfolio identified by request parameters.\n *\n * @param \\StockX\\Client\\Model\\PortfolioRequest $portfolio Requests parameters for looking up a market portfolio. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getPortfolioAsync($portfolio)\n {\n return $this->getPortfolioAsyncWithHttpInfo($portfolio)\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation getPortfolioAsyncWithHttpInfo\n *\n * Returns a market portfolio identified by request parameters.\n *\n * @param \\StockX\\Client\\Model\\PortfolioRequest $portfolio Requests parameters for looking up a market portfolio. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getPortfolioAsyncWithHttpInfo($portfolio)\n {\n $returnType = '\\StockX\\Client\\Model\\PortfolioResponse';\n $request = $this->getPortfolioRequest($portfolio);\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'getPortfolio'\n *\n * @param \\StockX\\Client\\Model\\PortfolioRequest $portfolio Requests parameters for looking up a market portfolio. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function getPortfolioRequest($portfolio)\n {\n // verify the required parameter 'portfolio' is set\n if ($portfolio === null) {\n throw new \\InvalidArgumentException(\n 'Missing the required parameter $portfolio when calling getPortfolio'\n );\n }\n\n $resourcePath = '/v1/portfolio';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n\n\n // body params\n $_tempBody = null;\n if (isset($portfolio)) {\n $_tempBody = $portfolio;\n }\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n ['application/json']\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'POST',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Operation getPortfolioItem\n *\n * @param string $id The id of the portfolio item to lookup. (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return \\StockX\\Client\\Model\\PortfolioitemsIdGetResponse\n */\n public function getPortfolioItem($id)\n {\n list($response) = $this->getPortfolioItemWithHttpInfo($id);\n return $response;\n }\n\n /**\n * Operation getPortfolioItemWithHttpInfo\n *\n * @param string $id The id of the portfolio item to lookup. (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of \\StockX\\Client\\Model\\PortfolioitemsIdGetResponse, HTTP status code, HTTP response headers (array of strings)\n */\n public function getPortfolioItemWithHttpInfo($id)\n {\n $returnType = '\\StockX\\Client\\Model\\PortfolioitemsIdGetResponse';\n $request = $this->getPortfolioItemRequest($id);\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n case 200:\n $data = ObjectSerializer::deserialize(\n $e->getResponseBody(),\n '\\StockX\\Client\\Model\\PortfolioitemsIdGetResponse',\n $e->getResponseHeaders()\n );\n $e->setResponseObject($data);\n break;\n }\n throw $e;\n }\n }\n\n /**\n * Operation getPortfolioItemAsync\n *\n * \n *\n * @param string $id The id of the portfolio item to lookup. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getPortfolioItemAsync($id)\n {\n return $this->getPortfolioItemAsyncWithHttpInfo($id)\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation getPortfolioItemAsyncWithHttpInfo\n *\n * \n *\n * @param string $id The id of the portfolio item to lookup. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getPortfolioItemAsyncWithHttpInfo($id)\n {\n $returnType = '\\StockX\\Client\\Model\\PortfolioitemsIdGetResponse';\n $request = $this->getPortfolioItemRequest($id);\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'getPortfolioItem'\n *\n * @param string $id The id of the portfolio item to lookup. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function getPortfolioItemRequest($id)\n {\n // verify the required parameter 'id' is set\n if ($id === null) {\n throw new \\InvalidArgumentException(\n 'Missing the required parameter $id when calling getPortfolioItem'\n );\n }\n\n $resourcePath = '/v1/portfolioitems/{id}';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n\n // path params\n if ($id !== null) {\n $resourcePath = str_replace(\n '{' . 'id' . '}',\n ObjectSerializer::toPathValue($id),\n $resourcePath\n );\n }\n\n // body params\n $_tempBody = null;\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n []\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('jwt-authorization');\n if ($apiKey !== null) {\n $headers['jwt-authorization'] = $apiKey;\n }\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'GET',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Operation getProductById\n *\n * @param string $id The id of the product to return. (required)\n * @param string $include include (optional)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return \\StockX\\Client\\Model\\ProductResponse\n */\n public function getProductById($id, $include = null)\n {\n list($response) = $this->getProductByIdWithHttpInfo($id, $include);\n return $response;\n }\n\n /**\n * Operation getProductByIdWithHttpInfo\n *\n * @param string $id The id of the product to return. (required)\n * @param string $include (optional)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of \\StockX\\Client\\Model\\ProductResponse, HTTP status code, HTTP response headers (array of strings)\n */\n public function getProductByIdWithHttpInfo($id, $include = null)\n {\n $returnType = '\\StockX\\Client\\Model\\ProductResponse';\n $request = $this->getProductByIdRequest($id, $include);\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n case 200:\n $data = ObjectSerializer::deserialize(\n $e->getResponseBody(),\n '\\StockX\\Client\\Model\\ProductResponse',\n $e->getResponseHeaders()\n );\n $e->setResponseObject($data);\n break;\n }\n throw $e;\n }\n }\n\n /**\n * Operation getProductByIdAsync\n *\n * \n *\n * @param string $id The id of the product to return. (required)\n * @param string $include (optional)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getProductByIdAsync($id, $include = null)\n {\n return $this->getProductByIdAsyncWithHttpInfo($id, $include)\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation getProductByIdAsyncWithHttpInfo\n *\n * \n *\n * @param string $id The id of the product to return. (required)\n * @param string $include (optional)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getProductByIdAsyncWithHttpInfo($id, $include = null)\n {\n $returnType = '\\StockX\\Client\\Model\\ProductResponse';\n $request = $this->getProductByIdRequest($id, $include);\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'getProductById'\n *\n * @param string $id The id of the product to return. (required)\n * @param string $include (optional)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function getProductByIdRequest($id, $include = null)\n {\n // verify the required parameter 'id' is set\n if ($id === null) {\n throw new \\InvalidArgumentException(\n 'Missing the required parameter $id when calling getProductById'\n );\n }\n\n $resourcePath = '/v1/products/{id}';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n // query params\n if ($include !== null) {\n $queryParams['include'] = ObjectSerializer::toQueryValue($include);\n }\n\n // path params\n if ($id !== null) {\n $resourcePath = str_replace(\n '{' . 'id' . '}',\n ObjectSerializer::toPathValue($id),\n $resourcePath\n );\n }\n\n // body params\n $_tempBody = null;\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n []\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('jwt-authorization');\n if ($apiKey !== null) {\n $headers['jwt-authorization'] = $apiKey;\n }\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'GET',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Operation getProductMarketData\n *\n * Provides historical market data for a given product.\n *\n * @param string $product_id The product&#39;s product UUID (required)\n * @param string $sku The product&#39;s SKU (optional)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return \\StockX\\Client\\Model\\MarketData\n */\n public function getProductMarketData($product_id, $sku = null)\n {\n list($response) = $this->getProductMarketDataWithHttpInfo($product_id, $sku);\n return $response;\n }\n\n /**\n * Operation getProductMarketDataWithHttpInfo\n *\n * Provides historical market data for a given product.\n *\n * @param string $product_id The product&#39;s product UUID (required)\n * @param string $sku The product&#39;s SKU (optional)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of \\StockX\\Client\\Model\\MarketData, HTTP status code, HTTP response headers (array of strings)\n */\n public function getProductMarketDataWithHttpInfo($product_id, $sku = null)\n {\n $returnType = '\\StockX\\Client\\Model\\MarketData';\n $request = $this->getProductMarketDataRequest($product_id, $sku);\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n case 200:\n $data = ObjectSerializer::deserialize(\n $e->getResponseBody(),\n '\\StockX\\Client\\Model\\MarketData',\n $e->getResponseHeaders()\n );\n $e->setResponseObject($data);\n break;\n }\n throw $e;\n }\n }\n\n /**\n * Operation getProductMarketDataAsync\n *\n * Provides historical market data for a given product.\n *\n * @param string $product_id The product&#39;s product UUID (required)\n * @param string $sku The product&#39;s SKU (optional)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getProductMarketDataAsync($product_id, $sku = null)\n {\n return $this->getProductMarketDataAsyncWithHttpInfo($product_id, $sku)\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation getProductMarketDataAsyncWithHttpInfo\n *\n * Provides historical market data for a given product.\n *\n * @param string $product_id The product&#39;s product UUID (required)\n * @param string $sku The product&#39;s SKU (optional)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getProductMarketDataAsyncWithHttpInfo($product_id, $sku = null)\n {\n $returnType = '\\StockX\\Client\\Model\\MarketData';\n $request = $this->getProductMarketDataRequest($product_id, $sku);\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'getProductMarketData'\n *\n * @param string $product_id The product&#39;s product UUID (required)\n * @param string $sku The product&#39;s SKU (optional)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function getProductMarketDataRequest($product_id, $sku = null)\n {\n // verify the required parameter 'product_id' is set\n if ($product_id === null) {\n throw new \\InvalidArgumentException(\n 'Missing the required parameter $product_id when calling getProductMarketData'\n );\n }\n\n $resourcePath = '/v1/products/{productId}/market';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n // query params\n if ($sku !== null) {\n $queryParams['sku'] = ObjectSerializer::toQueryValue($sku);\n }\n\n // path params\n if ($product_id !== null) {\n $resourcePath = str_replace(\n '{' . 'productId' . '}',\n ObjectSerializer::toPathValue($product_id),\n $resourcePath\n );\n }\n\n // body params\n $_tempBody = null;\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n ['application/json']\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('jwt-authorization');\n if ($apiKey !== null) {\n $headers['jwt-authorization'] = $apiKey;\n }\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'GET',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Operation getSubscriptions\n *\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return \\StockX\\Client\\Model\\SubscriptionsResponse\n */\n public function getSubscriptions()\n {\n list($response) = $this->getSubscriptionsWithHttpInfo();\n return $response;\n }\n\n /**\n * Operation getSubscriptionsWithHttpInfo\n *\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of \\StockX\\Client\\Model\\SubscriptionsResponse, HTTP status code, HTTP response headers (array of strings)\n */\n public function getSubscriptionsWithHttpInfo()\n {\n $returnType = '\\StockX\\Client\\Model\\SubscriptionsResponse';\n $request = $this->getSubscriptionsRequest();\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n case 200:\n $data = ObjectSerializer::deserialize(\n $e->getResponseBody(),\n '\\StockX\\Client\\Model\\SubscriptionsResponse',\n $e->getResponseHeaders()\n );\n $e->setResponseObject($data);\n break;\n }\n throw $e;\n }\n }\n\n /**\n * Operation getSubscriptionsAsync\n *\n * \n *\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getSubscriptionsAsync()\n {\n return $this->getSubscriptionsAsyncWithHttpInfo()\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation getSubscriptionsAsyncWithHttpInfo\n *\n * \n *\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getSubscriptionsAsyncWithHttpInfo()\n {\n $returnType = '\\StockX\\Client\\Model\\SubscriptionsResponse';\n $request = $this->getSubscriptionsRequest();\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'getSubscriptions'\n *\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function getSubscriptionsRequest()\n {\n\n $resourcePath = '/webhook/v1/subscriptions';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n\n\n // body params\n $_tempBody = null;\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n []\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'GET',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Operation getWebhook\n *\n * @param string $id id (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return \\StockX\\Client\\Model\\WebhooksIdGetResponse\n */\n public function getWebhook($id)\n {\n list($response) = $this->getWebhookWithHttpInfo($id);\n return $response;\n }\n\n /**\n * Operation getWebhookWithHttpInfo\n *\n * @param string $id (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of \\StockX\\Client\\Model\\WebhooksIdGetResponse, HTTP status code, HTTP response headers (array of strings)\n */\n public function getWebhookWithHttpInfo($id)\n {\n $returnType = '\\StockX\\Client\\Model\\WebhooksIdGetResponse';\n $request = $this->getWebhookRequest($id);\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n case 200:\n $data = ObjectSerializer::deserialize(\n $e->getResponseBody(),\n '\\StockX\\Client\\Model\\WebhooksIdGetResponse',\n $e->getResponseHeaders()\n );\n $e->setResponseObject($data);\n break;\n }\n throw $e;\n }\n }\n\n /**\n * Operation getWebhookAsync\n *\n * \n *\n * @param string $id (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getWebhookAsync($id)\n {\n return $this->getWebhookAsyncWithHttpInfo($id)\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation getWebhookAsyncWithHttpInfo\n *\n * \n *\n * @param string $id (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getWebhookAsyncWithHttpInfo($id)\n {\n $returnType = '\\StockX\\Client\\Model\\WebhooksIdGetResponse';\n $request = $this->getWebhookRequest($id);\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'getWebhook'\n *\n * @param string $id (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function getWebhookRequest($id)\n {\n // verify the required parameter 'id' is set\n if ($id === null) {\n throw new \\InvalidArgumentException(\n 'Missing the required parameter $id when calling getWebhook'\n );\n }\n\n $resourcePath = '/webhook/v1/webhooks/{id}';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n\n // path params\n if ($id !== null) {\n $resourcePath = str_replace(\n '{' . 'id' . '}',\n ObjectSerializer::toPathValue($id),\n $resourcePath\n );\n }\n\n // body params\n $_tempBody = null;\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n []\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'GET',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Operation getWebhooks\n *\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return \\StockX\\Client\\Model\\WebhooksGetResponse\n */\n public function getWebhooks()\n {\n list($response) = $this->getWebhooksWithHttpInfo();\n return $response;\n }\n\n /**\n * Operation getWebhooksWithHttpInfo\n *\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of \\StockX\\Client\\Model\\WebhooksGetResponse, HTTP status code, HTTP response headers (array of strings)\n */\n public function getWebhooksWithHttpInfo()\n {\n $returnType = '\\StockX\\Client\\Model\\WebhooksGetResponse';\n $request = $this->getWebhooksRequest();\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n case 200:\n $data = ObjectSerializer::deserialize(\n $e->getResponseBody(),\n '\\StockX\\Client\\Model\\WebhooksGetResponse',\n $e->getResponseHeaders()\n );\n $e->setResponseObject($data);\n break;\n }\n throw $e;\n }\n }\n\n /**\n * Operation getWebhooksAsync\n *\n * \n *\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getWebhooksAsync()\n {\n return $this->getWebhooksAsyncWithHttpInfo()\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation getWebhooksAsyncWithHttpInfo\n *\n * \n *\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function getWebhooksAsyncWithHttpInfo()\n {\n $returnType = '\\StockX\\Client\\Model\\WebhooksGetResponse';\n $request = $this->getWebhooksRequest();\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'getWebhooks'\n *\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function getWebhooksRequest()\n {\n\n $resourcePath = '/webhook/v1/webhooks';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n\n\n // body params\n $_tempBody = null;\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n []\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'GET',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Operation login\n *\n * Attempts to log the user in with a username and password.\n *\n * @param \\StockX\\Client\\Model\\LoginRequest $login Object that contains the user&#39;s authentication credentials.&#39; (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return \\StockX\\Client\\Model\\LoginResponse\n */\n public function login($login)\n {\n list($response) = $this->loginWithHttpInfo($login);\n return $response;\n }\n\n /**\n * Operation loginWithHttpInfo\n *\n * Attempts to log the user in with a username and password.\n *\n * @param \\StockX\\Client\\Model\\LoginRequest $login Object that contains the user&#39;s authentication credentials.&#39; (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of \\StockX\\Client\\Model\\LoginResponse, HTTP status code, HTTP response headers (array of strings)\n */\n public function loginWithHttpInfo($login)\n {\n $returnType = '\\StockX\\Client\\Model\\LoginResponse';\n $request = $this->loginRequest($login);\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n case 200:\n $data = ObjectSerializer::deserialize(\n $e->getResponseBody(),\n '\\StockX\\Client\\Model\\LoginResponse',\n $e->getResponseHeaders()\n );\n $e->setResponseObject($data);\n break;\n }\n throw $e;\n }\n }\n\n /**\n * Operation loginAsync\n *\n * Attempts to log the user in with a username and password.\n *\n * @param \\StockX\\Client\\Model\\LoginRequest $login Object that contains the user&#39;s authentication credentials.&#39; (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function loginAsync($login)\n {\n return $this->loginAsyncWithHttpInfo($login)\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation loginAsyncWithHttpInfo\n *\n * Attempts to log the user in with a username and password.\n *\n * @param \\StockX\\Client\\Model\\LoginRequest $login Object that contains the user&#39;s authentication credentials.&#39; (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function loginAsyncWithHttpInfo($login)\n {\n $returnType = '\\StockX\\Client\\Model\\LoginResponse';\n $request = $this->loginRequest($login);\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'login'\n *\n * @param \\StockX\\Client\\Model\\LoginRequest $login Object that contains the user&#39;s authentication credentials.&#39; (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function loginRequest($login)\n {\n // verify the required parameter 'login' is set\n if ($login === null) {\n throw new \\InvalidArgumentException(\n 'Missing the required parameter $login when calling login'\n );\n }\n\n $resourcePath = '/v1/login';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n\n\n // body params\n $_tempBody = null;\n if (isset($login)) {\n $_tempBody = $login;\n }\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n ['application/json']\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'POST',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Operation lookupProduct\n *\n * @param string $identifier The product identifier to lookup, e.g. (air-jordan-1-retro-high-off-white-chicago) (optional)\n * @param string $size The size of the product. (optional)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return \\StockX\\Client\\Model\\ProductInfo\n */\n public function lookupProduct($identifier = null, $size = null)\n {\n list($response) = $this->lookupProductWithHttpInfo($identifier, $size);\n return $response;\n }\n\n /**\n * Operation lookupProductWithHttpInfo\n *\n * @param string $identifier The product identifier to lookup, e.g. (air-jordan-1-retro-high-off-white-chicago) (optional)\n * @param string $size The size of the product. (optional)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of \\StockX\\Client\\Model\\ProductInfo, HTTP status code, HTTP response headers (array of strings)\n */\n public function lookupProductWithHttpInfo($identifier = null, $size = null)\n {\n $returnType = '\\StockX\\Client\\Model\\ProductInfo';\n $request = $this->lookupProductRequest($identifier, $size);\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n case 200:\n $data = ObjectSerializer::deserialize(\n $e->getResponseBody(),\n '\\StockX\\Client\\Model\\ProductInfo',\n $e->getResponseHeaders()\n );\n $e->setResponseObject($data);\n break;\n }\n throw $e;\n }\n }\n\n /**\n * Operation lookupProductAsync\n *\n * \n *\n * @param string $identifier The product identifier to lookup, e.g. (air-jordan-1-retro-high-off-white-chicago) (optional)\n * @param string $size The size of the product. (optional)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function lookupProductAsync($identifier = null, $size = null)\n {\n return $this->lookupProductAsyncWithHttpInfo($identifier, $size)\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation lookupProductAsyncWithHttpInfo\n *\n * \n *\n * @param string $identifier The product identifier to lookup, e.g. (air-jordan-1-retro-high-off-white-chicago) (optional)\n * @param string $size The size of the product. (optional)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function lookupProductAsyncWithHttpInfo($identifier = null, $size = null)\n {\n $returnType = '\\StockX\\Client\\Model\\ProductInfo';\n $request = $this->lookupProductRequest($identifier, $size);\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'lookupProduct'\n *\n * @param string $identifier The product identifier to lookup, e.g. (air-jordan-1-retro-high-off-white-chicago) (optional)\n * @param string $size The size of the product. (optional)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function lookupProductRequest($identifier = null, $size = null)\n {\n\n $resourcePath = '/product/lookup';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n // query params\n if ($identifier !== null) {\n $queryParams['identifier'] = ObjectSerializer::toQueryValue($identifier);\n }\n // query params\n if ($size !== null) {\n $queryParams['size'] = ObjectSerializer::toQueryValue($size);\n }\n\n\n // body params\n $_tempBody = null;\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n []\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('jwt-authorization');\n if ($apiKey !== null) {\n $headers['jwt-authorization'] = $apiKey;\n }\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'GET',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Operation newPortfolioAsk\n *\n * Creates a new seller ask on the market for a given product.\n *\n * @param \\StockX\\Client\\Model\\PortfolioRequest $portfolio The portfolio request representing the ask to place on the market. (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return \\StockX\\Client\\Model\\PortfolioResponse\n */\n public function newPortfolioAsk($portfolio)\n {\n list($response) = $this->newPortfolioAskWithHttpInfo($portfolio);\n return $response;\n }\n\n /**\n * Operation newPortfolioAskWithHttpInfo\n *\n * Creates a new seller ask on the market for a given product.\n *\n * @param \\StockX\\Client\\Model\\PortfolioRequest $portfolio The portfolio request representing the ask to place on the market. (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of \\StockX\\Client\\Model\\PortfolioResponse, HTTP status code, HTTP response headers (array of strings)\n */\n public function newPortfolioAskWithHttpInfo($portfolio)\n {\n $returnType = '\\StockX\\Client\\Model\\PortfolioResponse';\n $request = $this->newPortfolioAskRequest($portfolio);\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n case 200:\n $data = ObjectSerializer::deserialize(\n $e->getResponseBody(),\n '\\StockX\\Client\\Model\\PortfolioResponse',\n $e->getResponseHeaders()\n );\n $e->setResponseObject($data);\n break;\n }\n throw $e;\n }\n }\n\n /**\n * Operation newPortfolioAskAsync\n *\n * Creates a new seller ask on the market for a given product.\n *\n * @param \\StockX\\Client\\Model\\PortfolioRequest $portfolio The portfolio request representing the ask to place on the market. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function newPortfolioAskAsync($portfolio)\n {\n return $this->newPortfolioAskAsyncWithHttpInfo($portfolio)\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation newPortfolioAskAsyncWithHttpInfo\n *\n * Creates a new seller ask on the market for a given product.\n *\n * @param \\StockX\\Client\\Model\\PortfolioRequest $portfolio The portfolio request representing the ask to place on the market. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function newPortfolioAskAsyncWithHttpInfo($portfolio)\n {\n $returnType = '\\StockX\\Client\\Model\\PortfolioResponse';\n $request = $this->newPortfolioAskRequest($portfolio);\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'newPortfolioAsk'\n *\n * @param \\StockX\\Client\\Model\\PortfolioRequest $portfolio The portfolio request representing the ask to place on the market. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function newPortfolioAskRequest($portfolio)\n {\n // verify the required parameter 'portfolio' is set\n if ($portfolio === null) {\n throw new \\InvalidArgumentException(\n 'Missing the required parameter $portfolio when calling newPortfolioAsk'\n );\n }\n\n $resourcePath = '/v1/portfolio/ask';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n\n\n // body params\n $_tempBody = null;\n if (isset($portfolio)) {\n $_tempBody = $portfolio;\n }\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n ['application/json']\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'POST',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Operation newPortfolioBid\n *\n * Creates a new buyer bid on the market for a given product.\n *\n * @param \\StockX\\Client\\Model\\PortfolioRequest $portfolio The portfolio request representing the bid to place on the market. (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return \\StockX\\Client\\Model\\PortfolioResponse\n */\n public function newPortfolioBid($portfolio)\n {\n list($response) = $this->newPortfolioBidWithHttpInfo($portfolio);\n return $response;\n }\n\n /**\n * Operation newPortfolioBidWithHttpInfo\n *\n * Creates a new buyer bid on the market for a given product.\n *\n * @param \\StockX\\Client\\Model\\PortfolioRequest $portfolio The portfolio request representing the bid to place on the market. (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of \\StockX\\Client\\Model\\PortfolioResponse, HTTP status code, HTTP response headers (array of strings)\n */\n public function newPortfolioBidWithHttpInfo($portfolio)\n {\n $returnType = '\\StockX\\Client\\Model\\PortfolioResponse';\n $request = $this->newPortfolioBidRequest($portfolio);\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n case 200:\n $data = ObjectSerializer::deserialize(\n $e->getResponseBody(),\n '\\StockX\\Client\\Model\\PortfolioResponse',\n $e->getResponseHeaders()\n );\n $e->setResponseObject($data);\n break;\n }\n throw $e;\n }\n }\n\n /**\n * Operation newPortfolioBidAsync\n *\n * Creates a new buyer bid on the market for a given product.\n *\n * @param \\StockX\\Client\\Model\\PortfolioRequest $portfolio The portfolio request representing the bid to place on the market. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function newPortfolioBidAsync($portfolio)\n {\n return $this->newPortfolioBidAsyncWithHttpInfo($portfolio)\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation newPortfolioBidAsyncWithHttpInfo\n *\n * Creates a new buyer bid on the market for a given product.\n *\n * @param \\StockX\\Client\\Model\\PortfolioRequest $portfolio The portfolio request representing the bid to place on the market. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function newPortfolioBidAsyncWithHttpInfo($portfolio)\n {\n $returnType = '\\StockX\\Client\\Model\\PortfolioResponse';\n $request = $this->newPortfolioBidRequest($portfolio);\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'newPortfolioBid'\n *\n * @param \\StockX\\Client\\Model\\PortfolioRequest $portfolio The portfolio request representing the bid to place on the market. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function newPortfolioBidRequest($portfolio)\n {\n // verify the required parameter 'portfolio' is set\n if ($portfolio === null) {\n throw new \\InvalidArgumentException(\n 'Missing the required parameter $portfolio when calling newPortfolioBid'\n );\n }\n\n $resourcePath = '/v1/portfolio/bid';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n\n\n // body params\n $_tempBody = null;\n if (isset($portfolio)) {\n $_tempBody = $portfolio;\n }\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n ['application/json']\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'POST',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Operation postWebhooks\n *\n * @param \\StockX\\Client\\Model\\WebhooksPostRequest $portfolio portfolio (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return \\StockX\\Client\\Model\\WebhooksPostResponse\n */\n public function postWebhooks($portfolio)\n {\n list($response) = $this->postWebhooksWithHttpInfo($portfolio);\n return $response;\n }\n\n /**\n * Operation postWebhooksWithHttpInfo\n *\n * @param \\StockX\\Client\\Model\\WebhooksPostRequest $portfolio (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of \\StockX\\Client\\Model\\WebhooksPostResponse, HTTP status code, HTTP response headers (array of strings)\n */\n public function postWebhooksWithHttpInfo($portfolio)\n {\n $returnType = '\\StockX\\Client\\Model\\WebhooksPostResponse';\n $request = $this->postWebhooksRequest($portfolio);\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n case 200:\n $data = ObjectSerializer::deserialize(\n $e->getResponseBody(),\n '\\StockX\\Client\\Model\\WebhooksPostResponse',\n $e->getResponseHeaders()\n );\n $e->setResponseObject($data);\n break;\n }\n throw $e;\n }\n }\n\n /**\n * Operation postWebhooksAsync\n *\n * \n *\n * @param \\StockX\\Client\\Model\\WebhooksPostRequest $portfolio (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function postWebhooksAsync($portfolio)\n {\n return $this->postWebhooksAsyncWithHttpInfo($portfolio)\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation postWebhooksAsyncWithHttpInfo\n *\n * \n *\n * @param \\StockX\\Client\\Model\\WebhooksPostRequest $portfolio (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function postWebhooksAsyncWithHttpInfo($portfolio)\n {\n $returnType = '\\StockX\\Client\\Model\\WebhooksPostResponse';\n $request = $this->postWebhooksRequest($portfolio);\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'postWebhooks'\n *\n * @param \\StockX\\Client\\Model\\WebhooksPostRequest $portfolio (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function postWebhooksRequest($portfolio)\n {\n // verify the required parameter 'portfolio' is set\n if ($portfolio === null) {\n throw new \\InvalidArgumentException(\n 'Missing the required parameter $portfolio when calling postWebhooks'\n );\n }\n\n $resourcePath = '/webhook/v1/webhooks';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n\n\n // body params\n $_tempBody = null;\n if (isset($portfolio)) {\n $_tempBody = $portfolio;\n }\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n ['application/json']\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'POST',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Operation search\n *\n * Searches for products by keyword.\n *\n * @param string $query The phrase or keyword to search with. (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return \\StockX\\Client\\Model\\SearchResults\n */\n public function search($query)\n {\n list($response) = $this->searchWithHttpInfo($query);\n return $response;\n }\n\n /**\n * Operation searchWithHttpInfo\n *\n * Searches for products by keyword.\n *\n * @param string $query The phrase or keyword to search with. (required)\n *\n * @throws \\StockX\\Client\\ApiException on non-2xx response\n * @throws \\InvalidArgumentException\n * @return array of \\StockX\\Client\\Model\\SearchResults, HTTP status code, HTTP response headers (array of strings)\n */\n public function searchWithHttpInfo($query)\n {\n $returnType = '\\StockX\\Client\\Model\\SearchResults';\n $request = $this->searchRequest($query);\n\n try {\n $options = $this->createHttpClientOption();\n try {\n $response = $this->client->send($request, $options);\n } catch (RequestException $e) {\n throw new ApiException(\n \"[{$e->getCode()}] {$e->getMessage()}\",\n $e->getCode(),\n $e->getResponse() ? $e->getResponse()->getHeaders() : null,\n $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null\n );\n }\n\n $statusCode = $response->getStatusCode();\n\n if ($statusCode < 200 || $statusCode > 299) {\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $request->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n\n } catch (ApiException $e) {\n switch ($e->getCode()) {\n case 200:\n $data = ObjectSerializer::deserialize(\n $e->getResponseBody(),\n '\\StockX\\Client\\Model\\SearchResults',\n $e->getResponseHeaders()\n );\n $e->setResponseObject($data);\n break;\n }\n throw $e;\n }\n }\n\n /**\n * Operation searchAsync\n *\n * Searches for products by keyword.\n *\n * @param string $query The phrase or keyword to search with. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function searchAsync($query)\n {\n return $this->searchAsyncWithHttpInfo($query)\n ->then(\n function ($response) {\n return $response[0];\n }\n );\n }\n\n /**\n * Operation searchAsyncWithHttpInfo\n *\n * Searches for products by keyword.\n *\n * @param string $query The phrase or keyword to search with. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Promise\\PromiseInterface\n */\n public function searchAsyncWithHttpInfo($query)\n {\n $returnType = '\\StockX\\Client\\Model\\SearchResults';\n $request = $this->searchRequest($query);\n\n return $this->client\n ->sendAsync($request, $this->createHttpClientOption())\n ->then(\n function ($response) use ($returnType) {\n $responseBody = $response->getBody();\n if ($returnType === '\\SplFileObject') {\n $content = $responseBody; //stream goes to serializer\n } else {\n $content = $responseBody->getContents();\n if ($returnType !== 'string') {\n $content = json_decode($content);\n }\n }\n\n return [\n ObjectSerializer::deserialize($content, $returnType, []),\n $response->getStatusCode(),\n $response->getHeaders()\n ];\n },\n function ($exception) {\n $response = $exception->getResponse();\n $statusCode = $response->getStatusCode();\n throw new ApiException(\n sprintf(\n '[%d] Error connecting to the API (%s)',\n $statusCode,\n $exception->getRequest()->getUri()\n ),\n $statusCode,\n $response->getHeaders(),\n $response->getBody()\n );\n }\n );\n }\n\n /**\n * Create request for operation 'search'\n *\n * @param string $query The phrase or keyword to search with. (required)\n *\n * @throws \\InvalidArgumentException\n * @return \\GuzzleHttp\\Psr7\\Request\n */\n protected function searchRequest($query)\n {\n // verify the required parameter 'query' is set\n if ($query === null) {\n throw new \\InvalidArgumentException(\n 'Missing the required parameter $query when calling search'\n );\n }\n\n $resourcePath = '/v2/search';\n $formParams = [];\n $queryParams = [];\n $headerParams = [];\n $httpBody = '';\n $multipart = false;\n\n // query params\n if ($query !== null) {\n $queryParams['query'] = ObjectSerializer::toQueryValue($query);\n }\n\n\n // body params\n $_tempBody = null;\n\n if ($multipart) {\n $headers = $this->headerSelector->selectHeadersForMultipart(\n ['application/json']\n );\n } else {\n $headers = $this->headerSelector->selectHeaders(\n ['application/json'],\n ['application/json']\n );\n }\n\n // for model (json/xml)\n if (isset($_tempBody)) {\n // $_tempBody is the method argument, if present\n $httpBody = $_tempBody;\n // \\stdClass has no __toString(), so we should encode it manually\n if ($httpBody instanceof \\stdClass && $headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($httpBody);\n }\n } elseif (count($formParams) > 0) {\n if ($multipart) {\n $multipartContents = [];\n foreach ($formParams as $formParamName => $formParamValue) {\n $multipartContents[] = [\n 'name' => $formParamName,\n 'contents' => $formParamValue\n ];\n }\n // for HTTP post (form)\n $httpBody = new MultipartStream($multipartContents);\n\n } elseif ($headers['Content-Type'] === 'application/json') {\n $httpBody = \\GuzzleHttp\\json_encode($formParams);\n\n } else {\n // for HTTP post (form)\n $httpBody = \\GuzzleHttp\\Psr7\\build_query($formParams);\n }\n }\n\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('jwt-authorization');\n if ($apiKey !== null) {\n $headers['jwt-authorization'] = $apiKey;\n }\n // this endpoint requires API key authentication\n $apiKey = $this->config->getApiKeyWithPrefix('x-api-key');\n if ($apiKey !== null) {\n $headers['x-api-key'] = $apiKey;\n }\n\n $defaultHeaders = [];\n if ($this->config->getUserAgent()) {\n $defaultHeaders['User-Agent'] = $this->config->getUserAgent();\n }\n\n $headers = array_merge(\n $defaultHeaders,\n $headerParams,\n $headers\n );\n\n $query = \\GuzzleHttp\\Psr7\\build_query($queryParams);\n return new Request(\n 'GET',\n $this->config->getHost() . $resourcePath . ($query ? \"?{$query}\" : ''),\n $headers,\n $httpBody\n );\n }\n\n /**\n * Create http client option\n *\n * @throws \\RuntimeException on file opening failure\n * @return array of http client options\n */\n protected function createHttpClientOption()\n {\n $options = [];\n if ($this->config->getDebug()) {\n $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');\n if (!$options[RequestOptions::DEBUG]) {\n throw new \\RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile());\n }\n }\n\n return $options;\n }\n}\n" }, { "alpha_fraction": 0.5490401387214661, "alphanum_fraction": 0.5699825286865234, "avg_line_length": 37.716217041015625, "blob_id": "d405c578f268116d22652862752eeaea2d4c1f6b", "content_id": "9b425e78f0bce7cfdb1ba3de29392267b33b3fa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2865, "license_type": "no_license", "max_line_length": 109, "num_lines": 74, "path": "/sdk/csharp/src/IO.StockX.Examples/PlaceNewLowestAskExample.cs", "repo_name": "stvncrn/stockx_api_ref", "src_encoding": "UTF-8", "text": "using System;\nusing System.Diagnostics;\nusing IO.StockX.Api;\nusing IO.StockX.Client;\nusing IO.StockX.Model;\n\nnamespace Example\n{\n /**\n * <p>Demonstrates creating a new lower asking price for a product as a seller.</p>\n */\n public class PlaceNewLowestAskExample\n {\n static public void Main()\n {\n // Configure API key authorization: api_key\n Configuration.Default.AddApiKey(\"x-api-key\", ExampleConstants.AWS_API_KEY);\n\n var stockx = new StockXApi();\n stockx.Configuration.BasePath = ExampleConstants.STOCKX_ENDPOINT;\n \n var login = new LoginRequest(ExampleConstants.STOCKX_USERNAME, ExampleConstants.STOCKX_PASSWORD);\n \n try\n {\n // Login and fetch the jwt header for authentication use in the request\n ApiResponse<LoginResponse> result = stockx.LoginWithHttpInfo(login);\n var jwt = result.Headers[ExampleConstants.JWT_HEADER];\n\n stockx.Configuration.DefaultHeader[\"jwt-authorization\"] = jwt;\n \n // Find a product with search\n var search = stockx.Search(\"Jordan Retro Black Cat\");\n\n // Lookup the product's data by its search id\n var firstResultStyle = search.Hits[0].StyleId;\n\n var productInfo = stockx.LookupProduct(firstResultStyle, \"11\");\n\n // Get the market data (highest bids, lowest asks, etc) about the product\n var id = productInfo.Data[0].Id;\n var productUuid = productInfo.Data[0].Attributes.ProductUuid;\n\n var marketData = stockx.GetProductMarketData(id, productUuid);\n\n // Get the lowest ask and increment it\n var lowestAsk = marketData.Market.LowestAsk;\n lowestAsk++;\n\n // Create a portfolio item request with a higher bid\n var item = new PortfolioRequestPortfolioItem();\n item.Amount = lowestAsk.ToString();\n item.SkuUuid = \"bae25b67-a721-4f57-ad5a-79973c7d0a5c\";\n item.MatchedWithDate = \"2018-12-12T05:00:00+0000\";\n item.ExpiresAt = \"2018-12-12T12:39:07+00:00\";\n\n var request = new PortfolioRequest();\n request.PortfolioItem = item;\n request.Customer = result.Data.Customer;\n request.Timezone = \"America/Detroit\";\n\n // Submit the ask\n var askResp = stockx.NewPortfolioAsk(request);\n\n Console.WriteLine(askResp);\n }\n catch (Exception e)\n {\n \tConsole.WriteLine(e.ToString());\n Console.WriteLine(\"Exception when creating new lowest ask: \" + e.Message );\n }\n }\n }\n}\n" } ]
82
joshling1919/django_polls
https://github.com/joshling1919/django_polls
94f8f54fb791ab5d5606684e067a31b2d091836d
83fcfa54f1fc20eca27f6ee1add9821a02c19294
8ae4b111265131817a29616b839fea853748a0d2
refs/heads/master
2022-05-18T02:33:01.179327
2020-04-19T20:56:11
2020-04-19T20:56:11
257,067,849
0
0
null
2020-04-19T18:02:03
2020-04-16T00:31:39
2020-04-16T00:31:37
null
[ { "alpha_fraction": 0.7400793433189392, "alphanum_fraction": 0.75, "avg_line_length": 27, "blob_id": "49afa2a0a0017e6b160c02e8956625e685ab9958", "content_id": "3fd7d92190106bf1acd75f659a31ff0cc9841c67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 504, "license_type": "no_license", "max_line_length": 63, "num_lines": 18, "path": "/mysite/survey/views.py", "repo_name": "joshling1919/django_polls", "src_encoding": "UTF-8", "text": "from django.http import HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, render\nfrom django.urls import reverse\nfrom django.views import generic\nfrom django.utils import timezone\n\nfrom .models import Answer, Question\n\n\ndef index(request):\n latest_question_list = Question.objects.order_by('id')[:20]\n context = {'latest_question_list': latest_question_list}\n return render(request, 'survey/index.html', context)\n\n\ndef process(request):\n print('Made it!')\n return \"Hi!\"\n" } ]
1
jlamonade/splitteroni
https://github.com/jlamonade/splitteroni
50dca4ae383e705048271c644ae270b7292710b0
fc2be8cfdf4a3462b808f89c445a81900c51791d
6f19ecb043426faf33b20f0e8facd60c9fe1eec3
refs/heads/master
2023-01-01T18:42:51.609736
2020-10-27T20:34:54
2020-10-27T20:34:54
300,116,094
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.662209689617157, "alphanum_fraction": 0.6643208861351013, "avg_line_length": 34.474998474121094, "blob_id": "ab14d98824a49169775e05c2e70ad76c1972e3eb", "content_id": "a90f7d6c693007c694b54e819e03810cd69d6565", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1421, "license_type": "no_license", "max_line_length": 104, "num_lines": 40, "path": "/pages/tests.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "from django.test import TestCase\nfrom django.urls import reverse, resolve\nfrom django.contrib.auth import get_user_model\nfrom .views import HomePageView\n\n\n# Create your tests here.\nclass HomepageTests(TestCase):\n\n def setUp(self):\n url = reverse('home')\n self.response = self.client.get(url)\n self.user = get_user_model().objects.create_user(\n username='testuser',\n email='[email protected]',\n password='testpass',\n )\n\n def test_homepage_status_code(self):\n self.assertEqual(self.response.status_code, 200)\n\n def test_homepage_template(self):\n self.assertTemplateUsed(self.response, 'home.html')\n\n def test_homepage_contains_correct_html_while_logged_out(self):\n self.assertContains(self.response, 'Create a new split. Log in or sign up to save your splits.')\n self.assertContains(self.response, 'Sign up')\n\n def test_homepage_contains_correct_html_while_logged_in(self):\n self.client.login(email='[email protected]', password='testpass')\n self.assertContains(self.response, 'Create a new split.')\n\n def test_homepage_does_not_contain_incorrect_html(self):\n self.assertNotContains(self.response, 'Should not contain this')\n\n def test_homepage_url_resolves_homepageview(self):\n view = resolve('/')\n self.assertEqual(\n view.func.__name__, HomePageView.as_view().__name__\n )\n\n\n" }, { "alpha_fraction": 0.6309919953346252, "alphanum_fraction": 0.6453062295913696, "avg_line_length": 39.328857421875, "blob_id": "64de3df77c6e17feb14b6ef88586154c1668f1a3", "content_id": "6c28bf217587ce7436db9af0942cf662ab37236b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6008, "license_type": "no_license", "max_line_length": 98, "num_lines": 149, "path": "/splitter/tests.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "from django.test import TestCase, RequestFactory\nfrom django.urls import reverse\nfrom django.contrib.auth import get_user_model\nfrom decimal import Decimal\n\nfrom .models import Bill, Person, Item\n\n\n# Create your tests here.\nclass SplitterTests(TestCase):\n\n def setUp(self):\n self.user = get_user_model().objects.create_user(\n username='testuser',\n email='[email protected]',\n password='testpass',\n )\n self.bill = Bill.objects.create(\n title='testbill',\n tip=12.00,\n tax=13.00,\n owner=self.user,\n )\n self.person = Person.objects.create(\n name='testperson',\n bill=self.bill\n )\n self.item = Item.objects.create(\n title='testitem',\n price=14.00,\n person=self.person,\n bill=self.bill,\n )\n self.shared_item = Item.objects.create(\n title='testshareditem',\n price=15.00,\n bill=self.bill,\n shared=True,\n )\n # Testing tax percent/amount\n self.bill_two = Bill.objects.create(\n title='testbill2',\n tip_percent=15,\n tax_percent=8.875,\n owner=self.user,\n )\n self.item_two = Item.objects.create(\n title='testitem2',\n price=14.00,\n bill=self.bill_two,\n shared=True,\n )\n self.bill_total = self.item.price + self.shared_item.price + self.bill.tax + self.bill.tip\n self.shared_item_total = self.bill.tip + self.bill.tax + self.shared_item.price\n self.bill_detail_response = self.client.get(self.bill.get_absolute_url())\n self.bill_two_response = self.client.get(self.bill_two.get_absolute_url())\n\n def test_bill_object(self):\n self.assertEqual(self.bill.title, 'testbill')\n self.assertEqual(self.bill.tip, 12.00)\n self.assertEqual(self.bill.tax, 13.00)\n self.assertEqual(self.bill.owner, self.user)\n\n def test_bill_list_view_for_logged_in_user(self):\n self.client.login(email='[email protected]', password='testpass')\n response = self.client.get(reverse('bill-list'))\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, 'testbill'.title())\n self.assertTemplateUsed(response, 'splitter/bill_list.html')\n\n def test_bill_list_view_for_logged_out_users(self):\n response = self.client.get(reverse('bill-list'))\n self.assertEqual(response.status_code, 200)\n\n def test_bill_detail_view(self):\n no_response = self.client.get('/bill/12345/')\n self.assertEqual(self.bill_detail_response.status_code, 200)\n self.assertEqual(no_response.status_code, 404)\n self.assertContains(self.bill_detail_response, 'testbill'.title())\n self.assertContains(self.bill_detail_response, '12.00')\n self.assertContains(self.bill_detail_response, '13.00')\n self.assertContains(self.bill_detail_response, self.item.price)\n self.assertContains(self.bill_detail_response, self.shared_item.price)\n self.assertContains(self.bill_detail_response, self.bill_total)\n self.assertTemplateUsed(self.bill_detail_response, 'splitter/bill_detail.html')\n\n def test_person_object(self):\n self.assertEqual(self.person.name, 'testperson')\n self.assertEqual(self.person.bill, self.bill)\n\n def test_person_object_in_bill_detail_view(self):\n self.assertContains(self.bill_detail_response, 'testperson'.title())\n\n def test_item_object(self):\n self.assertEqual(self.item.title, 'testitem')\n self.assertEqual(self.item.price, 14.00)\n self.assertEqual(self.item.bill, self.bill)\n self.assertEqual(self.item.person, self.person)\n\n def test_item_object_in_bill_detail_view(self):\n self.assertContains(self.bill_detail_response, 'testitem')\n self.assertContains(self.bill_detail_response, 14.00)\n\n def test_shared_item_object(self):\n self.assertEqual(self.shared_item.title, 'testshareditem')\n self.assertEqual(self.shared_item.price, 15.00)\n self.assertEqual(self.shared_item.bill, self.bill)\n\n def test_shared_item_object_in_bill_detail_view(self):\n self.assertContains(self.bill_detail_response, 'testshareditem')\n self.assertContains(self.bill_detail_response, 15.00)\n\n def test_bill_model_methods(self):\n \"\"\"Tests for Bill model methods.\"\"\"\n\n # Bill.get_order_total()\n self.assertEqual(self.bill.get_order_grand_total(), self.bill_total)\n\n # Bill.get_shared_items_total()\n self.assertEqual(self.bill.get_shared_items_total(), self.shared_item.price)\n\n def test_person_model_methods(self):\n \"\"\"Tests for Person model methods.\"\"\"\n\n # Person.get_shared_items_split()\n self.assertEqual(self.person.get_shared_items_split(), self.shared_item_total)\n\n # Person.get_person_total()\n self.assertEqual(self.person.get_person_total(), self.bill.get_order_grand_total())\n\n def test_bill_calculate_tax(self):\n self.assertContains(self.bill_two_response, Decimal(self.bill_two.get_tax_amount()))\n self.assertContains(self.bill_two_response, self.bill_two.tax_percent)\n self.bill_two.tax = 12.00\n self.assertContains(self.bill_two_response, Decimal(self.bill_two.tax))\n\n def test_bill_calculate_tip(self):\n self.assertContains(self.bill_two_response, Decimal(self.bill_two.get_tip_amount()))\n self.assertContains(self.bill_two_response, self.bill_two.tip_percent)\n self.bill_two.tip = 12.00\n self.assertContains(self.bill_two_response, Decimal(self.bill_two.tip))\n\n def test_bill_saves_session(self):\n self.client.session.create()\n self.bill_three = Bill.objects.create(\n title='testbill3',\n session=self.client.session.session_key,\n )\n self.assertEqual(self.bill_three.session, self.client.session.session_key)" }, { "alpha_fraction": 0.6460518836975098, "alphanum_fraction": 0.6460518836975098, "avg_line_length": 33.18867874145508, "blob_id": "00a795e77204e8d10849954bf4580162462f60ee", "content_id": "cd74fc86a79abaab7376f08b84035b9d2116074e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1811, "license_type": "no_license", "max_line_length": 100, "num_lines": 53, "path": "/splitter/urls.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom .views import (\n BillCreateView,\n BillDetailView,\n PersonCreateView,\n PersonDeleteView,\n BillListView,\n ItemCreateView,\n ItemDeleteView,\n SharedItemCreateView,\n BillUpdateView,\n BillUpdateTaxPercentView,\n BillUpdateTaxAmountView,\n BillUpdateTipAmountView,\n BillUpdateTipPercentView,\n BillDeleteView,\n)\n\n\nurlpatterns = [\n # Bill links\n path('new/', BillCreateView.as_view(), name='bill-create'),\n path('<uuid:pk>/', BillDetailView.as_view(), name='bill-detail'),\n path('archive/', BillListView.as_view(), name='bill-list'),\n path('<uuid:pk>/update/', BillUpdateView.as_view(), name='bill-update'),\n path('<uuid:pk>/update-tax-percent/',\n BillUpdateTaxPercentView.as_view(),\n name='bill-update-tax-percent'),\n path('<uuid:pk>/update-tax-amount/',\n BillUpdateTaxAmountView.as_view(),\n name='bill-update-tax-amount'),\n path('<uuid:pk>/update-tip-amount/', BillUpdateTipAmountView.as_view(), name='bill-update-tip'),\n path('<uuid:pk>/update-tip-percent/',\n BillUpdateTipPercentView.as_view(),\n name='bill-update-tip-percent'),\n path('<uuid:pk>/delete/', BillDeleteView.as_view(), name='bill-delete'),\n\n # Person links\n path('<uuid:pk>/add-person/', PersonCreateView.as_view(), name='person-create'),\n path('person/<uuid:pk>/delete/', PersonDeleteView.as_view(), name='person-delete'),\n\n # Item links\n path('<uuid:bill_id>/<uuid:person_id>/add-item/',\n ItemCreateView.as_view(),\n name='item-create'\n ),\n path('<uuid:bill_id>/add-shared-item/',\n SharedItemCreateView.as_view(),\n name='shared-item-create'\n ),\n path('item/<uuid:pk>/item-delete/', ItemDeleteView.as_view(), name='item-delete'),\n]" }, { "alpha_fraction": 0.5055508017539978, "alphanum_fraction": 0.5059778094291687, "avg_line_length": 25.625, "blob_id": "607dc95db15747db3290b5ee01a84542871c7b40", "content_id": "51d4dc199c1a6f93c57388e50017ae4411bcae63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2342, "license_type": "no_license", "max_line_length": 111, "num_lines": 88, "path": "/splitter/forms.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "from django.forms import forms, ModelForm\nfrom django.utils.translation import gettext_lazy as _\n\nfrom .models import Bill\n\n\nclass BillCreateForm(ModelForm):\n class Meta:\n model = Bill\n fields = ('title', 'tax_percent', 'tip_percent',)\n labels = {\n 'title': _('Name'),\n }\n help_texts = {\n 'title': _('The current date and time will be used if name field is empty.'),\n 'tax_percent': _('Please enter a percentage value. You can leave this blank and change it later.'),\n 'tip_percent': _('Please enter a percentage value. You can leave this blank and change it later.'),\n }\n error_messages = {\n 'title': {\n 'max_length': _(\"Name is too long.\"),\n },\n 'tax_percent': {\n 'max_digits': _(\"Too many digits.\")\n },\n 'tip_percent': {\n 'max_digits': _(\"Too many digits.\")\n }\n }\n\n\nclass BillUpdateForm(ModelForm):\n\n class Meta:\n model = Bill\n fields = ('title',)\n labels = {\n 'title': _('Name'),\n }\n\n\nclass BillUpdateTaxPercentForm(ModelForm):\n\n # def __init__(self, *args, **kwargs):\n # initial = kwargs.get('initial', {})\n # initial['tax'] = 0\n # kwargs['initial'] = initial\n # super(BillUpdateTaxPercentForm, self).__init__(*args, **kwargs)\n\n class Meta:\n model = Bill\n fields = ('tax_percent',)\n help_texts = {\n 'tax_percent': _('Please enter a percent(%) amount.')\n }\n\n\nclass BillUpdateTaxAmountForm(ModelForm):\n class Meta:\n model = Bill\n fields = ('tax',)\n help_texts = {\n 'tax': _('Please enter a currency amount.')\n }\n\n\nclass BillUpdateTipForm(ModelForm):\n class Meta:\n model = Bill\n fields = ('tip',)\n labels = {\n 'tip': _('Tip/Service Charge'),\n }\n help_texts = {\n 'tip': _('Please enter currency amount.')\n }\n\n\nclass BillUpdateTipPercentForm(ModelForm):\n class Meta:\n model = Bill\n fields = ('tip_percent',)\n labels = {\n 'tip_percent': _('Tip/Service Charge Percent'),\n }\n help_texts = {\n 'tip': _('Please enter a percent(%) amount.')\n }" }, { "alpha_fraction": 0.6038797497749329, "alphanum_fraction": 0.6129971146583557, "avg_line_length": 32.47402572631836, "blob_id": "056d8b828a3b3d982ffecbb8777c0e0c99c730a5", "content_id": "c3c4902e73e6763bfb90b697ee5be876861b8f6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5155, "license_type": "no_license", "max_line_length": 96, "num_lines": 154, "path": "/splitter/models.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "import uuid\nfrom django.db import models\nfrom django.contrib.auth import get_user_model\nfrom django.urls import reverse\nfrom decimal import Decimal\n\nfrom .utils import _check_tip_tax_then_add\n\n\n# Create your models here.\nclass Bill(models.Model):\n id = models.UUIDField(\n primary_key=True,\n default=uuid.uuid4,\n editable=False\n )\n title = models.CharField(max_length=50, blank=True, null=True)\n owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, blank=True)\n session = models.CharField(max_length=40, null=True, blank=True)\n date_created = models.DateTimeField(auto_now_add=True)\n tip = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)\n tip_percent = models.DecimalField(max_digits=10, decimal_places=3, blank=True, null=True)\n tax = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)\n tax_percent = models.DecimalField(max_digits=10, decimal_places=5, blank=True, null=True)\n\n class Meta:\n indexes = [\n models.Index(fields=['id'], name='id_index'),\n ]\n\n def __str__(self):\n if not self.title:\n return self.date_created.strftime(\"%m/%d/%y %I:%M%p\")\n else:\n return self.title.title()\n\n def get_tax_amount(self):\n subtotal = self.get_order_subtotal()\n if self.tax_percent:\n tax_amount = (subtotal * (Decimal(self.tax_percent / 100)))\n bill = Bill.objects.get(id=self.id)\n bill.tax = tax_amount\n bill.save()\n return Decimal(tax_amount).quantize(Decimal('.01'))\n elif self.tax:\n return Decimal(self.tax).quantize(Decimal('.01'))\n else:\n return 0\n\n def get_tip_amount(self):\n subtotal = self.get_order_subtotal() + self.get_tax_amount()\n if self.tip_percent:\n tip_amount = (subtotal * (Decimal(self.tip_percent / 100)))\n bill = Bill.objects.get(id=self.id)\n bill.tip = tip_amount\n bill.save()\n return Decimal(tip_amount).quantize(Decimal('.01'))\n elif self.tip:\n return Decimal(self.tip).quantize(Decimal('.01'))\n else:\n return 0\n\n def get_order_grand_total(self):\n # Returns the sum of all items including tax and tip\n total = _check_tip_tax_then_add(self) + self.get_order_subtotal()\n return Decimal(total)\n\n def get_order_subtotal(self):\n total = 0\n items = Item.objects.filter(bill=self)\n for item in items:\n total += Decimal(item.price)\n return Decimal(total)\n\n def get_shared_items_total(self):\n # Returns sum of shared items only\n total = 0\n items = Item.objects.filter(shared=True, bill=self)\n for item in items:\n total += Decimal(item.price)\n return Decimal(total)\n\n def get_absolute_url(self):\n return reverse('bill-detail', args=[self.id])\n\n\nclass Person(models.Model):\n id = models.UUIDField(\n primary_key=True,\n default=uuid.uuid4,\n editable=False\n )\n name = models.CharField(max_length=30)\n bill = models.ForeignKey(Bill, on_delete=models.CASCADE, related_name='people')\n\n class Meta:\n verbose_name_plural = 'people'\n indexes = [\n models.Index(fields=['id'], name='person_id_index'),\n ]\n\n def __str__(self):\n return self.name.title()\n\n def get_shared_items_split(self):\n # Returns the amount every person owes inside the shared items including tax and tip\n total = _check_tip_tax_then_add(self.bill)\n person_count = self.bill.people.all().count()\n items = self.bill.items.filter(shared=True)\n for item in items:\n total += Decimal(item.price)\n split_amount = Decimal(total / person_count)\n return Decimal(split_amount)\n\n def get_person_total(self):\n # Returns the sum of the person's items and their share of the shared items total\n total = 0\n items = Item.objects.filter(person=self)\n for item in items:\n total += Decimal(item.price)\n return Decimal(total + self.get_shared_items_split()).quantize(Decimal('.01'))\n\n def get_absolute_url(self):\n return reverse('bill-detail', args=[self.bill.id])\n\n\nclass Item(models.Model):\n id = models.UUIDField(\n primary_key=True,\n default=uuid.uuid4,\n editable=False\n )\n title = models.CharField(max_length=50, blank=True, null=True)\n price = models.DecimalField(max_digits=15, decimal_places=2)\n person = models.ForeignKey(\n Person,\n on_delete=models.CASCADE,\n related_name='items',\n blank=True,\n null=True\n )\n bill = models.ForeignKey(Bill, on_delete=models.CASCADE, related_name='items')\n shared = models.BooleanField(default=False)\n\n class Meta:\n indexes = [\n models.Index(fields=['id'], name='item_id_index'),\n ]\n\n def __str__(self):\n return self.title\n\n def get_absolute_url(self):\n return reverse('bill-detail', args=[self.bill.id])\n" }, { "alpha_fraction": 0.45818182826042175, "alphanum_fraction": 0.6290909051895142, "avg_line_length": 18.64285659790039, "blob_id": "0c0856604b4772c796efbacd43d9e093f3702e60", "content_id": "970b9583228e6d6ac7481f2ff24a3162d050a4dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 275, "license_type": "no_license", "max_line_length": 48, "num_lines": 14, "path": "/splitter/migrations/0005_merge_20201009_1438.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.2 on 2020-10-09 14:38\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('splitter', '0004_auto_20201008_2206'),\n ('splitter', '0004_auto_20201009_1430'),\n ]\n\n operations = [\n ]\n" }, { "alpha_fraction": 0.5096524953842163, "alphanum_fraction": 0.5694980621337891, "avg_line_length": 23.66666603088379, "blob_id": "9eb1468c48a3edc48479d31a0a690a3e6e4273d4", "content_id": "8a98c017d59850c64f8e2e71f5f61922104214f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 518, "license_type": "no_license", "max_line_length": 70, "num_lines": 21, "path": "/splitter/migrations/0007_auto_20201009_1606.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.2 on 2020-10-09 16:06\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('splitter', '0006_auto_20201009_1603'),\n ]\n\n operations = [\n migrations.AddIndex(\n model_name='item',\n index=models.Index(fields=['id'], name='item_id_index'),\n ),\n migrations.AddIndex(\n model_name='person',\n index=models.Index(fields=['id'], name='person_id_index'),\n ),\n ]\n" }, { "alpha_fraction": 0.45818182826042175, "alphanum_fraction": 0.6290909051895142, "avg_line_length": 18.64285659790039, "blob_id": "d5da2fd1f6e8e755a6a7522e85e3cd986d67e0d5", "content_id": "a39073b0047f630c5c9f7b1931792e03181bf8c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 275, "license_type": "no_license", "max_line_length": 48, "num_lines": 14, "path": "/splitter/migrations/0009_merge_20201012_2025.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.2 on 2020-10-12 20:25\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('splitter', '0008_auto_20201011_1907'),\n ('splitter', '0008_auto_20201011_0301'),\n ]\n\n operations = [\n ]\n" }, { "alpha_fraction": 0.7967032790184021, "alphanum_fraction": 0.7967032790184021, "avg_line_length": 25, "blob_id": "0a8d58d20aabebd3e220ab038d2b78b9489d0fe4", "content_id": "2e3372a1df1350247fbed28a0fbb3564ac3e5fab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 182, "license_type": "no_license", "max_line_length": 38, "num_lines": 7, "path": "/splitter/admin.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Bill, Person, Item\n\n# Register your models here.\nadmin.site.register(Bill)\nadmin.site.register(Person)\nadmin.site.register(Item)\n" }, { "alpha_fraction": 0.7049801349639893, "alphanum_fraction": 0.712739109992981, "avg_line_length": 28.02094268798828, "blob_id": "ec7250512f81faaebb2305b070c989634980c855", "content_id": "63af69882a05c1c6833f5556c379d7b397a9a3a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5542, "license_type": "no_license", "max_line_length": 96, "num_lines": 191, "path": "/config/settings.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "\"\"\"\nDjango settings for config project.\nGenerated by 'django-admin startproject' using Django 3.1.1.\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/3.1/topics/settings/\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/3.1/ref/settings/\n\"\"\"\n\nfrom pathlib import Path\nfrom environs import Env\n\nenv = Env()\nenv.read_env()\n\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = env(\"DJANGO_SECRET_KEY\")\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = env.bool(\"DJANGO_DEBUG\", default=False)\n\nALLOWED_HOSTS = env.list(\"DJANGO_ALLOWED_HOSTS\", default=[])\n\n# Application definition\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'whitenoise.runserver_nostatic',\n 'django.contrib.staticfiles',\n 'django.contrib.sites',\n\n # Third party apps\n 'crispy_forms',\n 'allauth',\n 'allauth.account',\n 'debug_toolbar',\n\n # My apps\n 'users',\n 'pages',\n 'splitter',\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\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 'debug_toolbar.middleware.DebugToolbarMiddleware',\n]\n\n# # Cache settings\n# CACHE_MIDDLEWARE_ALIAS = 'default'\n# CACHE_MIDDLEWARE_SECONDS = 604800\n# CACHE_MIDDLEWARE_KEY_PREFIX = ''\n\nROOT_URLCONF = 'config.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [str(BASE_DIR.joinpath('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 = 'config.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/3.1/ref/settings/#databases\n\nDATABASES = {\n 'default': env.dj_db_url(\n \"DATABASE_URL\", default=\"postgres://postgres@db/postgres\")\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/3.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/3.1/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\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/3.1/howto/static-files/\n\n# Static file settings\nSTATIC_URL = '/static/'\nSTATICFILES_DIRS = (str(BASE_DIR.joinpath('static')),)\nSTATIC_ROOT = str(BASE_DIR.joinpath('staticfiles'))\nSTATICFILES_FINDERS = [\n \"django.contrib.staticfiles.finders.FileSystemFinder\",\n \"django.contrib.staticfiles.finders.AppDirectoriesFinder\",\n]\nSTATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'\n\nAUTH_USER_MODEL = 'users.CustomUser'\n\n# Crispy settings\nCRISPY_TEMPLATE_PACK = 'bootstrap4'\n\n# django-allauth config\nLOGIN_REDIRECT_URL = 'home'\nACCOUNT_LOGOUT_REDIRECT_URL = 'home'\nSITE_ID = 1\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n 'allauth.account.auth_backends.AuthenticationBackend',\n)\nEMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND',\n default='django.core.mail.backends.console.EmailBackend')\nACCOUNT_USERNAME_REQUIRED = False\nACCOUNT_EMAIL_REQUIRED = True\nACCOUNT_AUTHENTICATION_METHOD = \"email\"\nACCOUNT_UNIQUE_EMAIL = True\nACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False\n\n\n# Email settings\nDEFAULT_FROM_EMAIL = '[email protected]'\nEMAIL_HOST = 'smtp.sendgrid.net'\nEMAIL_HOST_USER = 'apikey'\nEMAIL_HOST_PASSWORD = env(\"DJANGO_EMAIL_HOST_PASSWORD\", default='')\nEMAIL_PORT = 587\nEMAIL_USE_TLS = True\n\n# django-debug-toolbar\nimport socket\nhostname, _, ips = socket.gethostbyname_ex(socket.gethostname())\nINTERNAL_IPS = [ip[:-1] + \"1\" for ip in ips]\n\n# Security settings\nSECURE_SSL_REDIRECT = env.bool(\"DJANGO_SECURE_SSL_REDIRECT\", default=True)\nSECURE_HSTS_SECONDS = env.int(\"DJANGO_SECURE_HSTS_SECONDS\", default=2592000)\nSECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(\"DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS\", default=True)\nSECURE_HSTS_PRELOAD = env.bool(\"DJANGO_SECURE_HSTS_PRELOAD\", default=True)\nSESSION_COOKIE_SECURE = env.bool(\"DJANGO_SESSION_COOKIE_SECURE\", default=True)\nCSRF_COOKIE_SECURE = env.bool(\"DJANGO_CSRF_COOKIE_SECURE\", default=True)\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')" }, { "alpha_fraction": 0.5173674821853638, "alphanum_fraction": 0.5594149827957153, "avg_line_length": 22.782608032226562, "blob_id": "b4e95c74a7de4a3fcd0f6c7a2b65e03f7a9b436b", "content_id": "c524d65024946f5eb938c169346601d2caf607dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 547, "license_type": "no_license", "max_line_length": 73, "num_lines": 23, "path": "/splitter/migrations/0002_auto_20201007_2310.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.2 on 2020-10-08 03:10\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('splitter', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='item',\n name='title',\n field=models.CharField(blank=True, max_length=50, null=True),\n ),\n migrations.AlterField(\n model_name='person',\n name='name',\n field=models.CharField(max_length=30),\n ),\n ]\n" }, { "alpha_fraction": 0.5787781476974487, "alphanum_fraction": 0.5787781476974487, "avg_line_length": 25, "blob_id": "0086a79320254d85fb3ac41e4ad515dfcfc5700d", "content_id": "8c1c4eb5fd26300ed9b22e649ca7ef9c4b97e74d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 311, "license_type": "no_license", "max_line_length": 74, "num_lines": 12, "path": "/templates/about.html", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "{% extends '_base.html' %}\n\n{% block title %}About{% endblock title %}\n\n{% block content %}\n <p>\n This webapp was made in Python, Django, and styled with Bootstrap.\n <a href=\"https://github.com/jlamonade/splitteroni\">\n Check out the repo.\n </a>\n </p>\n{% endblock content %}" }, { "alpha_fraction": 0.7467761039733887, "alphanum_fraction": 0.7608440518379211, "avg_line_length": 30.592592239379883, "blob_id": "0fcdfe3c4f00354c7c3dcce869ebd475be5128f4", "content_id": "26e5816604892d7d218c4720287ec9fbacf4bff2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 853, "license_type": "no_license", "max_line_length": 138, "num_lines": 27, "path": "/README.md", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "# Splitteroni\n\nThis is a simple no non-sense bill splitter web app that I created because I didn't like the other bill splitter apps currently available.\n\n## Running the project\n\n1. Clone this repo to `~/splitteroni`\n1. Install dependencies: `pipenv install`\n1. Create a virtual environment: `virtualenv venv -p python3.8`\n1. Activate the environment: `. venv/bin/activate`\n1. Update config/settings.py by adding your own django secret key\n1. Start Django internal test server: `python manage.py runserver`\n1. Make the first migration: `python manage.py migrate`\n1. Create the superuser: `python manage.py createsuperuser`\n\n## Non-pip dependencies\n\n- `python3.8`\n- `postgresql`\n\n## Deployment\n\n- Prior to deployment you'll need to enter your own django secret key into docker-compose-public.yml\n```\nenvironment:\n \"DJANGO_SECRET_KEY=enter_key_here\"\n```\n" }, { "alpha_fraction": 0.5382716059684753, "alphanum_fraction": 0.5901234745979309, "avg_line_length": 21.5, "blob_id": "c3a50a99429ca90f29d4dfeff76adaaadfa11431", "content_id": "483021741a1dfb089f463fb253a90aa6f8ddd91f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 405, "license_type": "no_license", "max_line_length": 73, "num_lines": 18, "path": "/splitter/migrations/0012_bill_session.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.2 on 2020-10-16 21:25\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('splitter', '0011_bill_tip_percent'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='bill',\n name='session',\n field=models.CharField(blank=True, max_length=40, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6160990595817566, "alphanum_fraction": 0.6222910284996033, "avg_line_length": 23.846153259277344, "blob_id": "994bccf3e571940ad462ddcf74e8fe72207f2f1e", "content_id": "e0ff29b8731a4bae6e26917fe9cb0967c1bd23a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 323, "license_type": "no_license", "max_line_length": 87, "num_lines": 13, "path": "/splitter/utils.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "from decimal import Decimal\n\n\ndef _check_tip_tax_then_add(self):\n # Checks to see if tip or tax is null before adding them to total else it returns 0\n total = 0\n tip = self.get_tip_amount()\n tax = self.get_tax_amount()\n if tip:\n total += tip\n if tax:\n total += tax\n return Decimal(total)\n" }, { "alpha_fraction": 0.7582417726516724, "alphanum_fraction": 0.7582417726516724, "avg_line_length": 17.200000762939453, "blob_id": "102762b8f967b51f3f85c660343c5d0b73b76bc8", "content_id": "ce34ad81080c33fa60e9ef2e59d00b1ce85ac5d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 91, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/splitter/apps.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass SplitterConfig(AppConfig):\n name = 'splitter'\n" }, { "alpha_fraction": 0.5265588760375977, "alphanum_fraction": 0.6050808429718018, "avg_line_length": 23.05555534362793, "blob_id": "7d0bff951acb13786f2a45b38c2bff12c839914f", "content_id": "f7d7bbb42ca33137b551204c6fd31039ecfe088f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 433, "license_type": "no_license", "max_line_length": 94, "num_lines": 18, "path": "/splitter/migrations/0010_bill_tax_percent.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.2 on 2020-10-12 14:37\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('splitter', '0009_merge_20201012_2025'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='bill',\n name='tax_percent',\n field=models.DecimalField(blank=True, decimal_places=5, max_digits=10, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5769911408424377, "alphanum_fraction": 0.5915929079055786, "avg_line_length": 43.313724517822266, "blob_id": "9f0389f6facbb49a9cf2423c839a80e7c4369790", "content_id": "2589f7b0a7cb7aae9f54350d5d00e39f686ce7db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2260, "license_type": "no_license", "max_line_length": 158, "num_lines": 51, "path": "/splitter/migrations/0001_initial.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.2 on 2020-10-08 02:57\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport uuid\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='Bill',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('title', models.CharField(blank=True, max_length=50, null=True)),\n ('date_created', models.DateTimeField(auto_now_add=True)),\n ('tip', models.DecimalField(blank=True, decimal_places=2, max_digits=15)),\n ('tax', models.DecimalField(blank=True, decimal_places=2, max_digits=15)),\n ('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Person',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=20)),\n ('bill', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='people', to='splitter.bill')),\n ],\n options={\n 'verbose_name_plural': 'people',\n },\n ),\n migrations.CreateModel(\n name='Item',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('title', models.CharField(max_length=50)),\n ('price', models.DecimalField(decimal_places=2, max_digits=15)),\n ('shared', models.BooleanField(default=False)),\n ('bill', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='splitter.bill')),\n ('person', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='items', to='splitter.person')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.7332974076271057, "alphanum_fraction": 0.7419180870056152, "avg_line_length": 45.375, "blob_id": "0e3c41cae841f0e4cdc9ae2a80cb5d6898619049", "content_id": "c382a05c9736f7715e0425b8475d1c6fb3d345d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1856, "license_type": "no_license", "max_line_length": 116, "num_lines": 40, "path": "/TODO.txt", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "High Priority\n\n# Increase efficiency by only calling up functions only when things are changed in the DB.\n\n!! COMPLETED\n# Assign session variables into user sessions so that only they can view their bill.\n # Consider allowing the anonymous user to create an account and save their current session.\n # Create a new session when user creates a new split and assign the value to a session key.\n # https://stackoverflow.com/questions/39181655/sometimes-request-session-session-key-is-none\n # https://stackoverflow.com/questions/13938805/django-storing-anonymous-user-data\n\n# Write tests for session usage\n\n!! SEMI COMPLETED\n# Allow user to input tax percentage at split creation.\n # Consider how to switch between tax amount versus tax percentage.\n # How to have percentage and amount input on same form line?\n # Maybe only have one method of input\n # Tax percentage localization? Will users enter their current location? Google Maps API to pull in GPS data?\n // Added ability to change from percentage calculation and manually entering amount.\n // Might want to think about the UX of this method\n // Write tests for new feature\n # Think about how to implement tax amount and percent into the same view/form.\n\nLower priority\n\n# Allow users to input items before assigning them to people.\n # Have all items on one card and give each line the ability to assign them to people.\n # Consider changing shared items to a general list of items.\n # All items are created with the shared BooleanField set to True\n # BooleanField set to false after assignment.\n\n# Consider reversing the logic.\n # Having an initial split total and each new item subtracts from the total.\n\n!! COMPLETED\n# Add separate buttons for editing tax and tip?\n\n!! COMPLETED\n# Change Tip to Tip/Service Charge?\n\n" }, { "alpha_fraction": 0.5054054260253906, "alphanum_fraction": 0.5891891717910767, "avg_line_length": 20.764705657958984, "blob_id": "d5400ed44923fe485651c8aaadaa2adb7638b8bd", "content_id": "28aad204c0b470b92bcbbddd980edd8f7dfba563", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 370, "license_type": "no_license", "max_line_length": 63, "num_lines": 17, "path": "/splitter/migrations/0006_auto_20201009_1603.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.2 on 2020-10-09 16:03\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('splitter', '0005_merge_20201009_1438'),\n ]\n\n operations = [\n migrations.AddIndex(\n model_name='bill',\n index=models.Index(fields=['id'], name='id_index'),\n ),\n ]\n" }, { "alpha_fraction": 0.6438584923744202, "alphanum_fraction": 0.651201605796814, "avg_line_length": 30.703702926635742, "blob_id": "ee2db26c1f5b7527902f165e96fcfc2e55f16fa7", "content_id": "441f4a2aeec2e314df46ab5b33242c6cb41593f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5992, "license_type": "no_license", "max_line_length": 104, "num_lines": 189, "path": "/splitter/views.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "from django.views.generic import CreateView, DetailView, DeleteView, ListView, UpdateView\nfrom django.shortcuts import get_object_or_404\nfrom django.urls import reverse_lazy\nfrom django.http import Http404\nfrom decimal import Decimal\n\nfrom .models import Bill, Person, Item\nfrom .forms import (BillCreateForm,\n BillUpdateForm,\n BillUpdateTaxPercentForm,\n BillUpdateTaxAmountForm,\n BillUpdateTipForm,\n BillUpdateTipPercentForm)\n# from .mixins import BillUpdateViewMixin\n\n\n# Create your views here.\nclass BillCreateView(CreateView):\n template_name = 'splitter/bill_create.html'\n form_class = BillCreateForm\n\n def form_valid(self, form):\n if self.request.user.is_authenticated:\n form.instance.owner = self.request.user\n return super().form_valid(form)\n else:\n self.request.session.create()\n form.instance.session = self.request.session.session_key\n return super().form_valid(form)\n\n\nclass BillDetailView(DetailView):\n model = Bill\n template_name = 'splitter/bill_detail.html'\n context_object_name = 'bill'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['people'] = Person.objects.filter(\n bill=self.object.id)\n context['shared_items'] = Item.objects.filter(bill=self.object.id, shared=True)\n if self.object.tax_percent:\n context['tax_percentage'] = Decimal(self.object.tax_percent).quantize(Decimal('0.001'))\n if self.object.tip_percent:\n context['tip_percentage'] = Decimal(self.object.tip_percent.quantize(Decimal('0')))\n return context\n\n def get_object(self, queryset=None):\n pk = self.kwargs.get('pk')\n obj = get_object_or_404(Bill, id=pk)\n if self.request.user.is_authenticated and self.request.user == obj.owner:\n return obj\n elif self.request.session.session_key == obj.session:\n return obj\n else:\n raise Http404\n\n\nclass PersonCreateView(CreateView):\n model = Person\n template_name = 'splitter/person_create.html'\n fields = ('name',)\n\n def form_valid(self, form):\n bill = get_object_or_404(Bill, id=self.kwargs['pk'])\n form.instance.bill = bill\n return super().form_valid(form)\n\n\nclass BillDeleteView(DeleteView):\n model = Bill\n template_name = 'splitter/bill_delete.html'\n\n def get_success_url(self):\n return reverse_lazy('bill-list')\n\n\nclass BillListView(ListView):\n template_name = 'splitter/bill_list.html'\n context_object_name = 'bills'\n\n def get_queryset(self):\n if self.request.user.is_authenticated:\n qs = Bill.objects.filter(owner=self.request.user).order_by('-date_created')\n elif self.request.session.session_key:\n qs = Bill.objects.filter(session=self.request.session.session_key).order_by('-date_created')\n else:\n qs = None\n return qs\n\n\nclass PersonDeleteView(DeleteView):\n model = Person\n template_name = 'splitter/person_delete.html'\n\n def get_success_url(self):\n return reverse_lazy('bill-detail', args=[self.object.bill.id])\n\n\nclass ItemCreateView(CreateView):\n model = Item\n template_name = 'splitter/item_create.html'\n fields = ('title', 'price',)\n\n def form_valid(self, form):\n bill = get_object_or_404(Bill, id=self.kwargs['bill_id'])\n person = get_object_or_404(Person, id=self.kwargs['person_id'])\n form.instance.bill = bill\n form.instance.person = person\n return super().form_valid(form)\n\n\nclass SharedItemCreateView(CreateView):\n model = Item\n template_name = \"splitter/item_create.html\"\n fields = ('title', 'price',)\n\n def form_valid(self, form):\n bill = get_object_or_404(Bill, id=self.kwargs['bill_id'])\n form.instance.bill = bill\n form.instance.shared = True\n return super().form_valid(form)\n\n\nclass ItemDeleteView(DeleteView):\n model = Item\n template_name = 'splitter/item_delete.html'\n\n def get_success_url(self):\n return reverse_lazy('bill-detail', args=[self.object.bill.id])\n\n\nclass BillUpdateView(UpdateView):\n model = Bill\n template_name = 'splitter/bill_update.html'\n form_class = BillUpdateForm\n\n def form_valid(self, form):\n bill = get_object_or_404(Bill, id=self.kwargs['pk'])\n form.instance.bill = bill\n return super().form_valid(form)\n\n\nclass BillUpdateTaxPercentView(UpdateView):\n model = Bill\n form_class = BillUpdateTaxPercentForm\n template_name = 'splitter/bill_update_tax_percent.html'\n\n def form_valid(self, form):\n bill = get_object_or_404(Bill, id=self.kwargs['pk'])\n form.instance.bill = bill\n form.instance.tax = None\n return super().form_valid(form)\n\n\nclass BillUpdateTaxAmountView(UpdateView):\n model = Bill\n form_class = BillUpdateTaxAmountForm\n template_name = 'splitter/bill_update_tax_amount.html'\n\n def form_valid(self, form):\n bill = get_object_or_404(Bill, id=self.kwargs['pk'])\n form.instance.bill = bill\n form.instance.tax_percent = None\n return super().form_valid(form)\n\n\nclass BillUpdateTipAmountView(UpdateView):\n model = Bill\n form_class = BillUpdateTipForm\n template_name = 'splitter/bill_update_tip.html'\n\n def form_valid(self, form):\n bill = get_object_or_404(Bill, id=self.kwargs['pk'])\n form.instance.bill = bill\n form.instance.tip_percent = None\n return super().form_valid(form)\n\n\nclass BillUpdateTipPercentView(UpdateView):\n model = Bill\n form_class = BillUpdateTipPercentForm\n template_name = 'splitter/bill_update_tip_percent.html'\n\n def form_valid(self, form):\n bill = get_object_or_404(Bill, id=self.kwargs['pk'])\n form.instance.bill = bill\n form.instance.tip = None\n return super().form_valid(form)\n" }, { "alpha_fraction": 0.6229187250137329, "alphanum_fraction": 0.6258569955825806, "avg_line_length": 31.95161247253418, "blob_id": "edee675829fc2cd6c5584a5e9bb54f83770c8007", "content_id": "2a90e75a2a4bc35197249a37c533555e158006b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2042, "license_type": "no_license", "max_line_length": 72, "num_lines": 62, "path": "/users/tests.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "from django.test import TestCase\nfrom django.contrib.auth import get_user_model\nfrom django.urls import reverse, resolve\nfrom .forms import CustomUserCreationForm, CustomUserChangeForm\n\n\n# Create your tests here.\nclass CustomUserTests(TestCase):\n\n def test_create_user(self):\n User = get_user_model()\n user = User.objects.create(\n username='test',\n email='[email protected]',\n password='test123',\n )\n self.assertEqual(user.username, 'test')\n self.assertEqual(user.email, '[email protected]')\n self.assertTrue(user.is_active)\n self.assertFalse(user.is_staff)\n self.assertFalse(user.is_superuser)\n\n def test_create_superuser(self):\n User = get_user_model()\n super_user = User.objects.create_superuser(\n username='superuser',\n email='[email protected]',\n password='super123',\n )\n self.assertEqual(super_user.username, 'superuser')\n self.assertEqual(super_user.email, '[email protected]')\n self.assertTrue(super_user.is_active)\n self.assertTrue(super_user.is_staff)\n self.assertTrue(super_user.is_superuser)\n\n\nclass SignupPageTests(TestCase):\n\n username = 'testuser'\n email = '[email protected]'\n\n def setUp(self):\n url = reverse('account_signup')\n self.response = self.client.get(url)\n\n def test_signup_template(self):\n self.assertEqual(self.response.status_code, 200)\n self.assertTemplateUsed(self.response, 'account/signup.html')\n self.assertContains(self.response, 'Sign up')\n self.assertNotContains(self.response, 'Should not contain this')\n\n def test_signup_form(self):\n new_user = get_user_model().objects.create_user(\n self.username, self.email\n )\n self.assertEqual(get_user_model().objects.all().count(), 1)\n self.assertEqual(\n get_user_model().objects.all()[0].username, 'testuser'\n )\n self.assertEqual(\n get_user_model().objects.all()[0].email, '[email protected]'\n )" }, { "alpha_fraction": 0.528124988079071, "alphanum_fraction": 0.589062511920929, "avg_line_length": 26.826086044311523, "blob_id": "8bc61d5a3f9c44a0ac6470671284079628957a53", "content_id": "a6e9ed8738a87011dcec612a68f81d970f25e030", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 640, "license_type": "no_license", "max_line_length": 105, "num_lines": 23, "path": "/splitter/migrations/0004_auto_20201008_2206.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.2 on 2020-10-09 02:06\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('splitter', '0003_auto_20201007_2339'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='bill',\n name='tax',\n field=models.DecimalField(blank=True, decimal_places=2, default=0, max_digits=15, null=True),\n ),\n migrations.AlterField(\n model_name='bill',\n name='tip',\n field=models.DecimalField(blank=True, decimal_places=2, default=0, max_digits=15, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5511627793312073, "alphanum_fraction": 0.6023255586624146, "avg_line_length": 22.88888931274414, "blob_id": "1766bb5505b4055f1758fc0f87faa870549c7b4f", "content_id": "2f122cf7d9efab50c6ec4a937aa1381d625a97b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 94, "num_lines": 18, "path": "/splitter/migrations/0011_bill_tip_percent.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.2 on 2020-10-15 04:19\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('splitter', '0010_bill_tax_percent'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='bill',\n name='tip_percent',\n field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5242718458175659, "alphanum_fraction": 0.5841423869132996, "avg_line_length": 25.869565963745117, "blob_id": "e5f5094fe7233a6b97cd86ee72617bb3024028f9", "content_id": "c7d89b7b6eeea9e6c61519edc4a568f7a613059e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 618, "license_type": "no_license", "max_line_length": 94, "num_lines": 23, "path": "/splitter/migrations/0003_auto_20201007_2339.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.2 on 2020-10-08 03:39\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('splitter', '0002_auto_20201007_2310'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='bill',\n name='tax',\n field=models.DecimalField(blank=True, decimal_places=2, max_digits=15, null=True),\n ),\n migrations.AlterField(\n model_name='bill',\n name='tip',\n field=models.DecimalField(blank=True, decimal_places=2, max_digits=15, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6287128925323486, "alphanum_fraction": 0.6435643434524536, "avg_line_length": 32.83333206176758, "blob_id": "d76509df7da9c4dd9b508cf44821ac0296ca05ad", "content_id": "527fab5d06c71547ce9062761bd3402f78badf20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 202, "license_type": "no_license", "max_line_length": 60, "num_lines": 6, "path": "/splitter/mixins.py", "repo_name": "jlamonade/splitteroni", "src_encoding": "UTF-8", "text": "class BillUpdateViewMixin(object):\n\n def form_valid(self, form):\n bill = get_object_or_404(Bill, id=self.kwargs['pk'])\n form.instance.bill = bill\n return super().form_valid(form)" } ]
26
sergiypotapov/Selenium2
https://github.com/sergiypotapov/Selenium2
136d0fd5f207bb33f52d1996b7b20f278b347177
34b929fcc0da3c9de133362b12aa07a8774fe9c8
737577c50815a792f1142c286e6454e504f07a91
refs/heads/master
2021-01-10T04:15:07.500384
2016-02-08T16:23:18
2016-02-08T16:23:18
51,311,630
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6319499015808105, "alphanum_fraction": 0.6413469314575195, "avg_line_length": 38.90625, "blob_id": "029e9a5df9e7c18f1be4efb3d482a417f94717db", "content_id": "19964e4696057a5874e8a176fc4394b4b00c4bae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1277, "license_type": "no_license", "max_line_length": 123, "num_lines": 32, "path": "/separate_tests.py", "repo_name": "sergiypotapov/Selenium2", "src_encoding": "UTF-8", "text": "__author__ = 'spotapov'\nimport unittest\nimport string\nimport random\nfrom selenium import webdriver\n\nclass HomePageTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n # create a FF window\n cls.driver = webdriver.Firefox()\n cls.driver.implicitly_wait(30)\n cls.driver.maximize_window()\n\n #go to app HomePage\n cls.driver.get(\"http://enterprise-demo.user.magentotrial.com//\")\n\n def test_full_cart(self):\n # insert some goods to the cart\n self.driver.get(\"http://enterprise-demo.user.magentotrial.com/bowery-chino-pants-545.html\")\n\n color = self.driver.find_element_by_xpath(\"//img[@alt='Charcoal']\")\n color.click()\n size = self.driver.find_element_by_xpath(\"//*[@title='32']\")\n size.click()\n add_to_cart = self.driver.find_element_by_class_name(\"add-to-cart-buttons\")\n add_to_cart.click()\n cart = self.driver.find_element_by_css_selector(\"#header > div > div.skip-links > div > div > a > span.icon\")\n # click on cart\n cart.click()\n self.assertTrue(\"Bowery Chino Pants\", self.driver.find_element_by_xpath(\"//*[@id='cart-sidebar']/li/div/p/a\").text)\n self.assertTrue(\"$140.00\", self.driver.find_element_by_class_name(\"price\").text)\n" }, { "alpha_fraction": 0.551369845867157, "alphanum_fraction": 0.5821917653083801, "avg_line_length": 15.166666984558105, "blob_id": "8bee0dda19ba6a0fafad025d7872509ec5eeb306", "content_id": "7c057ae3c5dcd014406416cdb359bf94c374656d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 292, "license_type": "no_license", "max_line_length": 51, "num_lines": 18, "path": "/text.py", "repo_name": "sergiypotapov/Selenium2", "src_encoding": "UTF-8", "text": "__author__ = 'spotapov'\nimport string\nimport random\n\n#makes random string of 129 characters\ndef big_text():\n text = ''\n l = 0\n for i in range(0,129):\n text += random.choice(string.ascii_letters)\n print(text)\n\n for k in text:\n l = l + 1\n print(l)\n\n\nbig_text()\n\n" }, { "alpha_fraction": 0.6365880966186523, "alphanum_fraction": 0.6430976390838623, "avg_line_length": 40.22222137451172, "blob_id": "b12d0b4890ddea3efd25a9dc566142ee2e080420", "content_id": "393a2e56671750e9e52fed22161bcd6511cfb949", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4455, "license_type": "no_license", "max_line_length": 123, "num_lines": 108, "path": "/magento.py", "repo_name": "sergiypotapov/Selenium2", "src_encoding": "UTF-8", "text": "__author__ = 'spotapov'\nimport unittest\nimport string\nimport random\nfrom selenium import webdriver\n\nclass HomePageTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n # create a FF window\n cls.driver = webdriver.Firefox()\n cls.driver.implicitly_wait(30)\n cls.driver.maximize_window()\n\n #go to app HomePage\n cls.driver.get(\"http://enterprise-demo.user.magentotrial.com//\")\n\n def test_search_text_field_max(self):\n self.driver.get(\"http://enterprise-demo.user.magentotrial.com//\")\n # get search text box\n search_field = self.driver.find_element_by_id(\"search\")\n # check that max attribute is 128\n self.assertEqual(\"128\", search_field.get_attribute(\"maxlength\"))\n\n def test_search_text_really_128_max(self):\n self.driver.get(\"http://enterprise-demo.user.magentotrial.com//\")\n # get search text box\n search_field = self.driver.find_element_by_id(\"search\")\n\n\n text = ''\n for i in range(0,129):\n text +=random.choice(string.ascii_letters)\n\n search_field.send_keys(text)\n entered_text = search_field.get_attribute(\"value\")\n self.assertNotEqual(text,entered_text)\n\n def test_search_button_enabled(self):\n self.driver.get(\"http://enterprise-demo.user.magentotrial.com//\")\n # get search button\n search_button = self.driver.find_element_by_class_name(\"button\")\n self.assertTrue(search_button.is_enabled())\n\n def test_account_link_is_visible(self):\n self.driver.get(\"http://enterprise-demo.user.magentotrial.com//\")\n # get link ACCOUNT\n account_link = self.driver.find_element_by_link_text(\"ACCOUNT\")\n self.assertTrue(account_link.is_displayed())\n\n def test_number_of_links_with_account(self):\n self.driver.get(\"http://enterprise-demo.user.magentotrial.com//\")\n # get all links which have Account text\n account_links = self.driver.find_elements_by_partial_link_text(\"ACCO\")\n print(account_links)\n self.assertEqual(2, len(account_links))\n for i in account_links:\n self.assertTrue(i.is_displayed())\n\n def test_if_there_are_3_banners(self):\n self.driver.get(\"http://enterprise-demo.user.magentotrial.com//\")\n # get promo banners\n banner_list = self.driver.find_element_by_class_name(\"promos\")\n print(banner_list)\n banners = banner_list.find_elements_by_tag_name(\"img\")\n self.assertEqual(3, len(banners))\n\n def test_gift_promo(self):\n self.driver.get(\"http://enterprise-demo.user.magentotrial.com//\")\n gift_promo = self.driver.find_element_by_xpath(\"//img[@alt='Physical & Virtual Gift Cards']\")\n self.assertTrue(gift_promo.is_displayed())\n gift_promo.click()\n # check vip promo is displayed\n self.assertEqual(\"Gift Card\", self.driver.title)\n\n def test_shopping_cart_status(self):\n self.driver.get(\"http://enterprise-demo.user.magentotrial.com//\")\n # get shopping cart\n cart = self.driver.find_element_by_css_selector(\"div.header-minicart span.icon\")\n cart.click()\n # get message\n message = self.driver.find_element_by_css_selector(\"p.empty\").text\n self.assertEqual(message, \"You have no items in your shopping cart.\")\n close = self.driver.find_element_by_css_selector(\"div.minicart-wrapper a.close.skip-link-close\")\n close.click()\n\n def test_full_cart(self):\n # insert some goods to the cart\n self.driver.get(\"http://enterprise-demo.user.magentotrial.com/bowery-chino-pants-545.html\")\n\n color = self.driver.find_element_by_xpath(\"//img[@alt='Charcoal']\")\n color.click()\n size = self.driver.find_element_by_xpath(\"//*[@title='32']\")\n size.click()\n add_to_cart = self.driver.find_element_by_class_name(\"add-to-cart-buttons\")\n add_to_cart.click()\n cart = self.driver.find_element_by_css_selector(\"#header > div > div.skip-links > div > div > a > span.icon\")\n # click on cart\n cart.click()\n self.assertTrue(\"Bowery Chino Pants\", self.driver.find_element_by_xpath(\"//*[@id='cart-sidebar']/li/div/p/a\").text)\n self.assertTrue(\"$140.00\", self.driver.find_element_by_class_name(\"price\").text)\n\n @classmethod\n def tearDownClass(cls):\n #close bro\n cls.driver.quit()\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n\n\n\n" } ]
3
kumarkapil/MyVision
https://github.com/kumarkapil/MyVision
7ef019ea52fe3df15ad993dfe672d6c248233865
4d1527825125c6ae68998cd6ae84c611584d208a
5173a79ff0497363c584987e7e6730e19efc7234
refs/heads/master
2022-10-13T18:10:47.059541
2020-06-06T21:53:53
2020-06-06T21:53:53
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5200673341751099, "alphanum_fraction": 0.5242772698402405, "avg_line_length": 25.007299423217773, "blob_id": "54cc8b995740602030def93d9794754a369c5233", "content_id": "db3e718fa98b63183b2016f304eb68ecf61afa92", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3563, "license_type": "permissive", "max_line_length": 84, "num_lines": 137, "path": "/MyVision/engine/Engine.py", "repo_name": "kumarkapil/MyVision", "src_encoding": "UTF-8", "text": "from tqdm import tqdm\nimport torch\nimport numpy as np\n\nfrom tabulate import tabulate\n\nfrom ..utils import Meters\nfrom MyVision import metrics\n\nimport os\nimport time\nfrom itertools import chain\nimport abc\n\n\nclass Trainer:\n def __init__(\n self,\n train_loader,\n val_loader,\n test_loader,\n device,\n loss,\n optimizer,\n model,\n lr_scheduler,\n accumulation_steps=1,\n ):\n self.train_loader = train_loader\n self.val_loader = val_loader\n self.test_loader = test_loader\n self.device = device\n self.criterion = loss\n self.optimizer = optimizer\n self.model = model\n self.lr_scheduler = lr_scheduler\n self.accumulation_steps = accumulation_steps\n\n def train(self):\n losses = Meters.AverageMeter(\"Loss\", \":.4e\")\n\n self.model.train()\n\n tl = tqdm(self.train_loader)\n for batch_idx, (images, targets) in enumerate(tl, 1):\n\n self.optimizer.zero_grad()\n\n images = images.to(self.device)\n targets = targets.to(self.device)\n\n outputs = self.model(images)\n\n loss = self.criterion(outputs, targets)\n\n loss.backward()\n\n if batch_idx % self.accumulation_steps == 0:\n self.optimizer.step()\n\n losses.update(val=loss.item(), n=images.size(0))\n\n return losses.avg\n\n def validate(self):\n losses = Meters.AverageMeter(\"Loss\", \":.4e\")\n\n self.model.eval()\n\n predictions = []\n gts = []\n\n vl = tqdm(self.val_loader)\n for batch_idx, (images, targets) in enumerate(vl, 1):\n images = images.to(self.device)\n targets = targets.to(self.device)\n\n outputs = self.model(images)\n\n loss = self.criterion(outputs, targets)\n\n predictions = chain(predictions, outputs.detach().cpu().numpy())\n gts = chain(gts, targets.detach().cpu().numpy())\n\n losses.update(val=loss.item(), n=images.size(0))\n\n return np.array(list(predictions)), np.array(list(gts)), losses.avg\n\n def fit(self, epochs, metric):\n\n best_loss = 1\n table_list = []\n\n for epoch in range(epochs):\n\n train_loss = self.train()\n\n preds, gts, valid_loss = self.validate()\n\n if valid_loss < best_loss:\n\n if not os.path.exists(\"models\"):\n os.mkdir(\"models\")\n print(\"[SAVING].....\")\n torch.save(\n self.model.state_dict(), f\"models\\\\best_model-({epoch}).pth.tar\"\n )\n\n if len(np.unique(preds)) > 2:\n\n multiclass_metrics = [\"accuracy\"]\n\n preds = [np.argmax(p) for p in preds]\n\n score = metrics.ClassificationMetrics()(\n metric, y_true=gts, y_pred=preds, y_proba=None\n )\n else:\n binary_metrics = [\"auc\", \"f1\", \"recall\", \"precision\"]\n\n preds = [1 if p >= 0.5 else 0 for p in preds]\n\n score = metrics.ClassificationMetrics()(\n metric, y_true=gts, y_pred=preds, y_proba=None\n )\n\n table_list.append((epoch, train_loss, valid_loss, score))\n\n print(\n tabulate(\n table_list,\n headers=(\"Epoch\", \"Train loss\", \"Validation loss\", metric),\n )\n )\n\n if self.lr_scheduler:\n self.lr_scheduler.step(score)\n" }, { "alpha_fraction": 0.49462366104125977, "alphanum_fraction": 0.698924720287323, "avg_line_length": 16, "blob_id": "4807f790f106ec2628a99cdc0e96c4be3ecb0896", "content_id": "a1f97ec8f0ceb11504e657bc69dab2b033aba2a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 186, "license_type": "permissive", "max_line_length": 26, "num_lines": 11, "path": "/requirements.txt", "repo_name": "kumarkapil/MyVision", "src_encoding": "UTF-8", "text": "torchvision~=0.6.0\ntqdm~=4.45.0\nnumpy~=1.16.6\npandas~=1.0.3\nscikit-learn~=0.22.2.post1\npillow~=7.1.1\nmyvision~=0.0.1\nsetuptools~=46.1.3\ntorch~=1.5.0\nalbumentations~=0.4.3\ntabulate~=0.8.7" }, { "alpha_fraction": 0.5304961204528809, "alphanum_fraction": 0.5446062684059143, "avg_line_length": 26.81012725830078, "blob_id": "f9828cc56b8e1680f0ee07b37d30411417387652", "content_id": "a61ff6220c96923c57bda41d8a91c2d4201e2b7c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4394, "license_type": "permissive", "max_line_length": 83, "num_lines": 158, "path": "/MyVision/dataset/Dataset.py", "repo_name": "kumarkapil/MyVision", "src_encoding": "UTF-8", "text": "import torch\nfrom torch.utils.data import Dataset\nfrom PIL import Image, ImageFile\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport albumentations as A\nimport torchvision.transforms as transforms\n\n\nimport operator\n\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\n\nclass DatasetUtils:\n \"\"\"\n This class contains utilities for making a Pytorch Dataset. \n \"\"\"\n\n def __init__(\n self, train_df, image_path_column, target_column, train_tfms, valid_tfms\n ):\n self.train_df = train_df\n self.image_path_column = image_path_column\n self.target_column = target_column\n self.train_tfms = train_tfms\n self.valid_tfms = valid_tfms\n\n def splitter(self, valid_size=0.25):\n train_images, valid_images, train_labels, valid_labels = train_test_split(\n self.train_df[self.image_path_column],\n self.train_df[self.target_column],\n test_size=valid_size,\n random_state=42,\n )\n return (\n train_images.values,\n train_labels.values,\n valid_images.values,\n valid_labels.values,\n )\n\n def make_dataset(\n self, resize, train_idx=None, val_idx=None, valid_size=0.25, is_CV=None\n ):\n if is_CV:\n train_dataset = CVDataset(\n train_df,\n train_idx,\n self.image_path_column,\n self.target_column,\n transform=self.train_tfms,\n resize=resize,\n )\n\n valid_dataset = CVDataset(\n train_df,\n val_idx,\n self.image_path_column,\n self.target_column,\n transform=self.valid_tfms,\n resize=resize,\n )\n else:\n\n (\n train_image_paths,\n train_labels,\n valid_image_paths,\n valid_labels,\n ) = self.splitter(valid_size=valid_size)\n\n train_dataset = SimpleDataset(\n train_image_paths, train_labels, transform=self.train_tfms\n )\n\n valid_dataset = SimpleDataset(\n valid_image_paths, valid_labels, transform=self.valid_tfms\n )\n\n return train_dataset, valid_dataset\n\n\nclass SimpleDataset(Dataset):\n def __init__(self, image_paths, targets, transform=None, resize=224):\n self.image_paths = image_paths\n self.targets = targets\n self.default_tfms = transforms.Compose(\n [\n transforms.Resize((resize, resize)),\n transforms.ToTensor(),\n transforms.Normalize(\n mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]\n ),\n ]\n )\n self.transform = transform\n\n def __getitem__(self, index: int):\n image = Image.open(self.image_paths[index])\n target = self.targets[index]\n\n if self.transform:\n image = self.transform(image)\n\n image = self.default_tfms(image)\n\n target = torch.tensor(target)\n\n return image, target\n\n def __len__(self):\n return len(self.image_paths)\n\n\nclass CVDataset(Dataset):\n def __init__(\n self,\n df: pd.DataFrame,\n indices: np.ndarray,\n image_paths,\n target_cols,\n transform=None,\n resize=224,\n ):\n self.df = df\n self.indices = indices\n self.transform = transform\n self.default_tfms = transforms.Compose(\n [\n transforms.Resize((resize, resize)),\n transforms.ToTensor(),\n transforms.Normalize(\n mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]\n ),\n ]\n )\n self.image_paths = image_paths\n self.target_cols = target_cols\n\n def __getitem__(self, idx: int):\n image_ids = operator.itemgetter(*self.indices)(self.df[[self.image_paths]])\n labels = operator.itemgetter(*self.indices)(self.df[[self.target_cols]])\n\n image = Image.open(image_ids[idx])\n label = torch.tensor(labels[idx])\n\n if self.transform:\n image = self.transform(image)\n\n image = self.default_tfms(image)\n\n return image, label\n\n def __len__(self):\n return len(self.indices)\n" }, { "alpha_fraction": 0.6593592166900635, "alphanum_fraction": 0.6661045551300049, "avg_line_length": 27.238094329833984, "blob_id": "4fa565063fa4133be211b01e3a985f13b404ce49", "content_id": "38057621f8203c50262dce7782d115fe8ac83aca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 593, "license_type": "permissive", "max_line_length": 71, "num_lines": 21, "path": "/MyVision/utils/LabelUtils.py", "repo_name": "kumarkapil/MyVision", "src_encoding": "UTF-8", "text": "import pandas as pd\n\n\ndef make_multiclass_labels(df, label_column, start_from):\n \"\"\"\n Takes in a pandas dataframe, the label column & a start index.\n makes the categorical labels into integers\n You can specify which index to start labelling from 0 or 1.\n returns a dictionary mapping the label to it's integer value.\n\n :param df: pd.Dataframe\n :param label_column: str\n :param start_from: int(0 or 1)\n\n :return: Dict\n \"\"\"\n label_dict = {}\n for k, v in enumerate(df[label_column].unique(), start=start_from):\n label_dict[v] = k\n\n return label_dict\n" }, { "alpha_fraction": 0.7260273694992065, "alphanum_fraction": 0.7447729110717773, "avg_line_length": 37.5, "blob_id": "cab0c3704d25127c71d7f41c7f3f87989b52c4e2", "content_id": "9f617d00f7190789c73538c75eea7946a4a61838", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1387, "license_type": "permissive", "max_line_length": 221, "num_lines": 36, "path": "/README.md", "repo_name": "kumarkapil/MyVision", "src_encoding": "UTF-8", "text": "[![HitCount](http://hits.dwyl.com/Abhiswain97/MyVision.svg)](http://hits.dwyl.com/Abhiswain97/MyVision)\n[![PyPI version](https://badge.fury.io/py/MyVision.svg)](https://badge.fury.io/py/MyVision)\n\n[![Downloads](https://pepy.tech/badge/myvision)](https://pepy.tech/project/myvision)\n[![Downloads](https://pepy.tech/badge/myvision/month)](https://pepy.tech/project/myvision/month)\n[![Downloads](https://pepy.tech/badge/myvision/week)](https://pepy.tech/project/myvision/week)\n\n# MyVision: Eveything I love about PyTorch\n\nMy goal is to make my DL work-flow simple and \"Do more with less code\".\nSo, have a look at the source code modify it as u like, go crazy with customizations.\nI will keep updating it, as I learn more things. :D \n\nTo download do: \n```\npip install MyVision\n```\n\nOR \n\nDownload a binary: [Download](https://github.com/Abhiswain97/MyVision/releases)\n\n## Documentation:\n\nRefer to \n[![MNIST.ipynb](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1Gbz7edT2-1jupG8UGNg850tlc6rG_u1H#scrollTo=caiCEj_Os-93) for complete explanation on how to use `Trainer`.\n<br>\nCan also be launched using: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/Abhiswain97/MyVision/master)\n\n## Coming soon.... \n\nExplanation on how to use `DatasetUtils`\n\n## First proper release with all the features working \n\nJune 6, 2020 \n" } ]
5
kamalbec2005/PyVocabi
https://github.com/kamalbec2005/PyVocabi
927996a2639bf7b682df65f1736df05dffc0c5ca
2e44c8204098a2ebfea7980a24d01f395728a2f1
0c864b6a1f80246bb11622bd5f71f84c6af5b99b
refs/heads/master
2020-03-30T00:34:48.748336
2018-09-27T05:14:46
2018-09-27T05:14:46
150,531,775
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6315789222717285, "alphanum_fraction": 0.6315789222717285, "avg_line_length": 11.666666984558105, "blob_id": "89f7bfd2e369904c6d79fec5e35ffea75b98dbfe", "content_id": "423d7e55ec82779bd61cc8f00c524c2d7e10c499", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 38, "license_type": "no_license", "max_line_length": 29, "num_lines": 3, "path": "/main.py", "repo_name": "kamalbec2005/PyVocabi", "src_encoding": "UTF-8", "text": "'''\nProject: To build vocabulary.\n'''\n" } ]
1
tia-cima/reverse_shell_it
https://github.com/tia-cima/reverse_shell_it
38221a11fd236c3b53f3dda85aa95a67336ad587
0cd31d767c97decf6c1880943ad414da592fc875
cc26d07997044474d5faf63a09109eed5b92a388
refs/heads/main
2023-01-23T18:47:34.586561
2020-11-25T12:24:43
2020-11-25T12:24:43
315,931,215
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5106241703033447, "alphanum_fraction": 0.5272244215011597, "avg_line_length": 30.042552947998047, "blob_id": "f0aadea973ca9fb4d9e0bb49c2551ae149c197ad", "content_id": "05803b77d666218b404275793ad67d0db3f523c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1509, "license_type": "no_license", "max_line_length": 142, "num_lines": 47, "path": "/client.py", "repo_name": "tia-cima/reverse_shell_it", "src_encoding": "UTF-8", "text": "import socket, sys, time\r\n\r\ndef comandi(s):\r\n while(True):\r\n try:\r\n print('''\r\n\r\n Digita un qualsiasi comando.\r\n Per uscire dal server e dal progrmma premi \"ctrl + c\"\r\n\r\n ''')\r\n com = input(\"\\n--> \")\r\n s.send(com.encode())\r\n dati = s.recv(1048000)\r\n print(str(dati, \"utf-8\"))\r\n continue \r\n except KeyboardInterrupt:\r\n print(\"uscita dal server in corso...\")\r\n s.close()\r\n time.sleep(4)\r\n sys.exit(0)\r\n\r\n except UnicodeDecodeError:\r\n print(\"ATTENZIONE\\nil comando inserito non supporta la codifica utf-8, di conseguenza verrà ritornata la sua versione originale.\")\r\n print(dati)\r\n\r\n \r\ndef conne_server(indirizzo):\r\n try:\r\n s = socket.socket()\r\n s.connect(indirizzo)\r\n print(f\"conne stabilita con il server all'indirizzo: {indirizzo}\")\r\n except socket.error as errore:\r\n print(f\"qualcosa è andato storto durnte la connesione\\n{errore}\")\r\n retry = input(\"riprovare? Y/N: \")\r\n if retry == \"Y\" or retry == \"y\":\r\n conne_server(indirizzo)\r\n else:\r\n print(\"nessuna connessione stabilita. uscita..\")\r\n sys.exit(0)\r\n comandi(s)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \r\n print(\"Attesa di una connessione al server...\")\r\n conne_server((\"192.168.1.1\", 15000)) # devi cambiare l'indirizzo ip se è differente\r\n" }, { "alpha_fraction": 0.5541211366653442, "alphanum_fraction": 0.5779542922973633, "avg_line_length": 30.419355392456055, "blob_id": "04d24d69cda9778ad59f9d9a47115b50ec7e9906", "content_id": "cc926d63e9c782a73b78587633015eb7e7e3555f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1009, "license_type": "no_license", "max_line_length": 100, "num_lines": 31, "path": "/server.py", "repo_name": "tia-cima/reverse_shell_it", "src_encoding": "UTF-8", "text": "import sys, socket, subprocess, time, os\r\n\r\ndef ricevi(conn):\r\n while(True):\r\n richiesta = conn.recv(1048000)\r\n cmd = richiesta.decode()\r\n if cmd.startswith(\"cd \"):\r\n os.chdir(cmd)\r\n s.send(b\"$ \")\r\n continue\r\n \r\n risposta = subprocess.run(cmd, shell = True, capture_output = True)\r\n data = risposta.stdout + risposta.stderr\r\n conn.send(data)\r\n\r\ndef conne_client(indirizzo, backlog = 1):\r\n try:\r\n s = socket.socket()\r\n s.bind(indirizzo)\r\n s.listen(backlog)\r\n print(\"server in ascolto\")\r\n except socket.error as errore:\r\n print(f\"frate qualcosa non va.\\nforse c'è un altro server aperto \\ncodice erorre: {errore}\")\r\n time.sleep(15)\r\n sys.exit(0)\r\n \r\n conn, indirizzo_client = s.accept()\r\n print(f\"conne stabilita con il client: {indirizzo_client}\")\r\n ricevi(conn)\r\n\r\nconne_client((\"192.168.1.1\", 15000)) # devi cambiare l'indirizzo ip se è differente\r\n\r\n" }, { "alpha_fraction": 0.8002528548240662, "alphanum_fraction": 0.8053097128868103, "avg_line_length": 97.875, "blob_id": "bc83966e4ed58ad5ef905d062b24a7f1a9b0ddea", "content_id": "aafebab7ebe39abfc1d9e7212129860dffe68527", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 804, "license_type": "no_license", "max_line_length": 317, "num_lines": 8, "path": "/README.md", "repo_name": "tia-cima/reverse_shell_it", "src_encoding": "UTF-8", "text": "# reverse_shell_it\n(ITA) Reverse shell molto semplice, scritta sfruttando le librerie socket e subprocess di python, da utilizzare in LAN.\n\nPermette al client, la macchina che ha in esecuzione il file client.py, di scrivere e inviare comandi alla macchina “vittima”, che ha quindi in esecuzione il file server.py, che saranno poi interpretati da quest’ultima. Il client riceverà poi, dalla macchina “attaccata”, l’output del comando precedentemente inviato.\n\nSi tratta di script molto semplici che funzionano esclusivamente in LAN, ma che permettono di eseguire qualsiasi tipo di comando e di ricevere il relativo output anche se quest'ultimo non dovesse supportare la codifica UTF-8.\n\nPuoi guardare lo speed coding di questo script (in italiano) a questo link: https://youtu.be/36bqbftsU7Y\n" } ]
3
jasondentler/zeus-sensors
https://github.com/jasondentler/zeus-sensors
709d93c294d15c69ad39936167836b41ce0789f9
8c7d8a7c35d85b381311b8103242dc537d75eab8
563247b842be5aab78bbea780d81be682f897022
refs/heads/master
2020-04-16T07:47:43.888574
2019-01-12T14:57:51
2019-01-12T14:57:51
165,399,868
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.7321428656578064, "alphanum_fraction": 0.7678571343421936, "avg_line_length": 27, "blob_id": "1b24ca5848c067f458212208e4841d1b518d0b7a", "content_id": "dfabb00ffcc11b4a835110bb7c4332f146b146ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 56, "license_type": "no_license", "max_line_length": 40, "num_lines": 2, "path": "/README.md", "repo_name": "jasondentler/zeus-sensors", "src_encoding": "UTF-8", "text": "# zeus-sensors\nSensors for K40 laser &amp; Raspberry Pi\n" }, { "alpha_fraction": 0.6718533039093018, "alphanum_fraction": 0.7018616199493408, "avg_line_length": 29.226890563964844, "blob_id": "afd0678c54e3b24c6ff6a1744078fe9d82ec278e", "content_id": "1a3b31728bc21b712fbdd22414ed5b7d97f1ebfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3599, "license_type": "no_license", "max_line_length": 132, "num_lines": 119, "path": "/flow.py", "repo_name": "jasondentler/zeus-sensors", "src_encoding": "UTF-8", "text": "import os\nimport time\nimport math\nimport pygame, sys\nfrom pygame.locals import *\nimport RPi.GPIO as GPIO\n\nboardRevision = GPIO.RPI_REVISION\nGPIO.setmode(GPIO.BCM) # use real GPIO numbering\nGPIO.setup(17,GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\npygame.init()\n\nVIEW_WIDTH = 0\nVIEW_HEIGHT = 0\npygame.display.set_caption('Flow')\n\npouring = False\nlastPinState = False\npinState = 0\nlastPinChange = int(time.time() * 1000)\npourStart = 0\npinChange = lastPinChange\npinDelta = 0\nhertz = 0\nflow = 0\nlitersPoured = 0\npintsPoured = 0\ntweet = ''\nBLACK = (0,0,0)\nWHITE = (255, 255, 255)\n\nwindowSurface = pygame.display.set_mode((VIEW_WIDTH,VIEW_HEIGHT), FULLSCREEN, 32)\nFONTSIZE = 48\nLINEHEIGHT = 52\nbasicFont = pygame.font.SysFont(None, FONTSIZE)\n\ndef renderThings(lastPinChange, pinChange, pinDelta, hertz, flow, pintsPoured, pouring, pourStart, tweet, windowSurface, basicFont):\n # Clear the screen\n windowSurface.fill(BLACK)\n \n # Draw LastPinChange\n text = basicFont.render('Last Pin Change: '+time.strftime('%H:%M:%S', time.localtime(lastPinChange/1000)), True, WHITE, BLACK)\n textRect = text.get_rect()\n windowSurface.blit(text, (40,1*LINEHEIGHT))\n \n # Draw PinChange\n text = basicFont.render('Pin Change: '+time.strftime('%H:%M:%S', time.localtime(pinChange/1000)), True, WHITE, BLACK)\n textRect = text.get_rect()\n windowSurface.blit(text, (40,2*LINEHEIGHT))\n \n # Draw PinDelta\n text = basicFont.render('Pin Delta: '+str(pinDelta) + ' ms', True, WHITE, BLACK)\n textRect = text.get_rect()\n windowSurface.blit(text, (40,3*LINEHEIGHT))\n \n # Draw hertz\n text = basicFont.render('Hertz: '+str(hertz) + 'Hz', True, WHITE, BLACK)\n textRect = text.get_rect()\n windowSurface.blit(text, (40,4*LINEHEIGHT))\n\n # Draw instantaneous speed\n text = basicFont.render('Flow: '+str(flow) + ' L/sec', True, WHITE, BLACK)\n textRect = text.get_rect()\n windowSurface.blit(text, (40,5*LINEHEIGHT))\n\n # Draw Liters Poured\n text = basicFont.render('Pints Poured: '+str(pintsPoured) + ' pints', True, WHITE, BLACK)\n textRect = text.get_rect()\n windowSurface.blit(text, (40,6*LINEHEIGHT))\n \n # Draw Pouring\n text = basicFont.render('Pouring: '+str(pouring), True, WHITE, BLACK)\n textRect = text.get_rect()\n windowSurface.blit(text, (40,7*LINEHEIGHT))\n\n # Draw Pour Start\n text = basicFont.render('Last Pour Started At: '+time.strftime('%H:%M:%S', time.localtime(pourStart/1000)), True, WHITE, BLACK)\n textRect = text.get_rect()\n windowSurface.blit(text, (40,8*LINEHEIGHT))\n \n # Draw Tweet\n text = basicFont.render('Tweet: '+str(tweet), True, WHITE, BLACK)\n textRect = text.get_rect()\n windowSurface.blit(text, (40,9*LINEHEIGHT))\n\n # Display everything\n pygame.display.flip()\n\nwhile True:\n\tcurrentTime = int(time.time() * 1000)\n\tif GPIO.input(17):\n\t\tpinState = True\n\telse:\n\t\tpinState = False\n\n\tfor event in pygame.event.get():\n\t\tif event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):\n\t\t\tpygame.quit()\n\t\t\tsys.exit()\n\n# If we have changed pin states low to high...\n\tif(pinState != lastPinState and pinState == True):\n\t\tif(pouring == False):\n\t\t\tpourStart = currentTime\n\t\tpouring = True\n\t\t# get the current time\n\t\tpinChange = currentTime\n\t\tpinDelta = pinChange - lastPinChange\n\t\tif (pinDelta < 1000):\n\t\t\t# calculate the instantaneous speed\n\t\t\thertz = 1000.0000 / pinDelta\n\t\t\tflow = hertz / (60 * 7.5) # L/s\n\t\t\tlitersPoured += flow * (pinDelta / 1000.0000)\n\t\t\tpintsPoured = litersPoured * 2.11338\n\n\trenderThings(lastPinChange, pinChange, pinDelta, hertz, flow, pintsPoured, pouring, pourStart, tweet, windowSurface, basicFont)\n\tlastPinChange = pinChange\n\tlastPinState = pinState\n\n\n" }, { "alpha_fraction": 0.6013363003730774, "alphanum_fraction": 0.6291759610176086, "avg_line_length": 20.35714340209961, "blob_id": "8d783b0ff869656531906636dbf759cc70368aa2", "content_id": "b0b9493f054a4d5636ca0970762146ea2d09639c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 898, "license_type": "no_license", "max_line_length": 43, "num_lines": 42, "path": "/therm.py", "repo_name": "jasondentler/zeus-sensors", "src_encoding": "UTF-8", "text": "import os\nimport glob\nimport time\n\nos.system('modprobe w1-gpio')\nos.system('modprobe w1-therm')\n\nbase_dir = '/sys/bus/w1/devices/'\n\ndef get_devices():\n\tdevices = glob.glob(base_dir + '28*')\n\tfor device in devices:\n\t\tyield device + '/w1_slave'\n\ndef read_temp_raw():\n\tdevices = get_devices()\n\tfor device in devices:\n\t\tf = open(device, 'r')\n\t\tlines = f.readlines()\n\t\tf.close()\n\t\tyield device, lines\n\ndef read_temp():\n\tdata = read_temp_raw()\n\tfor item in data:\n\t\tdevice, lines = item\n\t\tif lines[0].strip()[-3:] != 'YES':\n\t\t\tprint('Device ' + device + ' not ready')\n\t\t\tcontinue;\n\t\tprint('Read device ' + device)\n\t\tequals_pos = lines[1].find('t=')\n\t\tif equals_pos != -1:\n\t\t\ttemp_string = lines[1][equals_pos+2:]\n\t\t\ttemp_c = float(temp_string) / 1000.0\n\t\t\ttemp_f = temp_c * 9.0 / 5.0 + 32.0\n\t\t\tyield device, temp_c, temp_f\n\nwhile True:\n\tdata = read_temp()\n\tfor item in data:\n\t\tprint(item)\n\ttime.sleep(1)\n\n" } ]
3
SSRomanSS/flask_blog
https://github.com/SSRomanSS/flask_blog
67c1aec88df65f24e23399af98bb4b303df1d090
6800396877f484b1bdeee2aa2a4d0ef62050f8cc
edde344a0ba86801167ad9b4a63f00e8278d0da1
refs/heads/master
2023-03-31T16:17:03.521882
2021-04-04T15:20:48
2021-04-04T15:20:48
352,268,861
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6226415038108826, "alphanum_fraction": 0.6226415038108826, "avg_line_length": 20.200000762939453, "blob_id": "c3cef61327a2768ae6ae9b6d2dfd333adecec606", "content_id": "9fb55272829adc196b4d6d1d8439d9eded38bedd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 106, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/manage.py", "repo_name": "SSRomanSS/flask_blog", "src_encoding": "UTF-8", "text": "from blog import app, db, manager\nfrom blog.models import *\n\nif __name__ == '__main__':\n manager.run()\n" }, { "alpha_fraction": 0.7728482484817505, "alphanum_fraction": 0.7728482484817505, "avg_line_length": 25.690475463867188, "blob_id": "1f7c365080f55779f4d427d3b1d80046c1c10e74", "content_id": "85add0d9fc2f1189d4608d7db0b957a2bb0ddd69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1127, "license_type": "no_license", "max_line_length": 71, "num_lines": 42, "path": "/blog/__init__.py", "repo_name": "SSRomanSS/flask_blog", "src_encoding": "UTF-8", "text": "from flask import Flask, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate, MigrateCommand\nfrom flask_script import Manager\nfrom flask_login import LoginManager\nfrom flask_bootstrap import Bootstrap\nfrom flask_moment import Moment\nfrom flask_babel import Babel, lazy_gettext as _l\nfrom flask_admin import Admin\nfrom flask_admin.contrib.sqla import ModelView\n\nfrom config import Config\n\n\napp = Flask(__name__)\napp.config.from_object(Config)\n\nlogin = LoginManager(app)\nlogin.login_view = 'login'\nlogin.login_message = _l('Please log in to access this page')\nlogin.login_message_category = 'info'\n\nbootstrap = Bootstrap(app)\nmoment = Moment(app)\nbabel = Babel(app)\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\nmanager = Manager(app)\nmanager.add_command('db', MigrateCommand)\n\n\[email protected]\ndef get_locale():\n return request.accept_languages.best_match(app.config['LANGUAGES'])\n\n# from blog import routes, models, errors\nfrom blog.models import User, Post\n\n# Admin Panel\nadmin = Admin(app)\nadmin.add_view(ModelView(User, db.session))\nadmin.add_view(ModelView(Post, db.session))\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.773809552192688, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 20, "blob_id": "8385e94725645cd9f38ab0059964a0491833dddc", "content_id": "3251ab3dbe86d509e6b6098edb2dee2964d1c41d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 84, "license_type": "no_license", "max_line_length": 28, "num_lines": 4, "path": "/set_flask_app.sh", "repo_name": "SSRomanSS/flask_blog", "src_encoding": "UTF-8", "text": "#!/bin/sh\nexport FLASK_APP=run.py\nexport FLASK_ENV=development\nexport FLASK_DEBUG=1\n" }, { "alpha_fraction": 0.6471251249313354, "alphanum_fraction": 0.6696730256080627, "avg_line_length": 25.878787994384766, "blob_id": "4daefb5fc4d12e608c15ec1f53e4ed443aa9f2da", "content_id": "dad3b4fce3e8ef0c05624f55aecf5737666bdcbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 887, "license_type": "no_license", "max_line_length": 65, "num_lines": 33, "path": "/migrations/versions/89b140c56c4d_fix_create_followers_relationship.py", "repo_name": "SSRomanSS/flask_blog", "src_encoding": "UTF-8", "text": "\"\"\"fix create followers relationship\n\nRevision ID: 89b140c56c4d\nRevises: 7d84ff36825f\nCreate Date: 2021-03-30 14:57:47.528704\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '89b140c56c4d'\ndown_revision = '7d84ff36825f'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('followed_followers',\n sa.Column('followed_id', sa.Integer(), nullable=True),\n sa.Column('follower_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['followed_id'], ['users.id'], ),\n sa.ForeignKeyConstraint(['follower_id'], ['users.id'], )\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('followed_followers')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.5907473564147949, "alphanum_fraction": 0.5907473564147949, "avg_line_length": 17.733333587646484, "blob_id": "15b3f5c701c2defe3fd7c7ac64c9f45ab76a88c2", "content_id": "3e5e04eb2bed81beb03be395d96168b273d42d16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 281, "license_type": "no_license", "max_line_length": 51, "num_lines": 15, "path": "/run.py", "repo_name": "SSRomanSS/flask_blog", "src_encoding": "UTF-8", "text": "from blog import app, db\nfrom blog import routes, models, errors, set_logger\n\n\[email protected]_context_processor\ndef make_shell_context():\n return {\n 'db': db,\n 'User': models.User,\n 'Post': models.Post\n }\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n" }, { "alpha_fraction": 0.6207332611083984, "alphanum_fraction": 0.6725663542747498, "avg_line_length": 25.366666793823242, "blob_id": "14c71032088c4b2d425030c4a8a5d1abf2d59935", "content_id": "39eb62e949cd504ce7713acf2db1d395012992bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 791, "license_type": "no_license", "max_line_length": 87, "num_lines": 30, "path": "/migrations/versions/5e12ea69ab10_add_two_new_column_to_user.py", "repo_name": "SSRomanSS/flask_blog", "src_encoding": "UTF-8", "text": "\"\"\"Add two new column to User\n\nRevision ID: 5e12ea69ab10\nRevises: a89dbfef15cc\nCreate Date: 2021-03-29 20:46:23.445651\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '5e12ea69ab10'\ndown_revision = 'a89dbfef15cc'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('users', sa.Column('about_me', sa.String(length=160), nullable=True))\n op.add_column('users', sa.Column('last_seen', sa.DateTime(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('users', 'last_seen')\n op.drop_column('users', 'about_me')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.650040864944458, "alphanum_fraction": 0.6524938941001892, "avg_line_length": 38.45161437988281, "blob_id": "4f22bd0e54c5f0c3e08906b6a6ba531eb07dba10", "content_id": "2576d8d79afb443b919e6324895281d43e381504", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6115, "license_type": "no_license", "max_line_length": 118, "num_lines": 155, "path": "/blog/routes.py", "repo_name": "SSRomanSS/flask_blog", "src_encoding": "UTF-8", "text": "from datetime import datetime\n\nfrom flask import render_template, flash, redirect, url_for, request\nfrom flask_login import current_user, login_user, logout_user, login_required\nfrom flask_babel import _\nfrom werkzeug.urls import url_parse\n\nfrom blog import app, db\nfrom blog.forms import LoginForm, RegisterForm, EditProfileForm, PostForm, EmptyForm\nfrom blog.models import User, Post\n\n\[email protected]_request\ndef before_request():\n if current_user.is_authenticated:\n current_user.last_seen = datetime.utcnow()\n db.session.commit()\n\n\[email protected]('/', methods=['GET', 'POST'])\n@login_required\ndef index():\n form = PostForm()\n if form.validate_on_submit():\n post = Post(body=form.post.data, author=current_user)\n db.session.add(post)\n db.session.commit()\n flash(_('Your post is live now!'), 'info')\n return redirect(url_for('index'))\n page = request.args.get('page', 1, type=int)\n posts = current_user.get_followed_posts().paginate(page, app.config['POST_PER_PAGE'], False)\n next_url = url_for('index', page=posts.next_num) if posts.has_next else None\n prev_url = url_for('index', page=posts.prev_num) if posts.has_prev else None\n app.logger.info('message')\n return render_template('index.html', posts=posts.items, form=form, next_url=next_url, prev_url=prev_url)\n\n\[email protected]('/explore')\n@login_required\ndef explore():\n page = request.args.get('page', 1, type=int)\n posts = Post.query.order_by(Post.timestamp.desc()).paginate(page, app.config['POST_PER_PAGE'], False)\n next_url = url_for('index', page=posts.next_num) if posts.has_next else None\n prev_url = url_for('index', page=posts.prev_num) if posts.has_prev else None\n return render_template('index.html', posts=posts.items, next_url=next_url, prev_url=prev_url)\n\n\[email protected]('/login', methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(username=form.username.data).first_or_404()\n if not user or not user.check_password(form.password.data):\n flash('Invalid username or password', 'error')\n return redirect(url_for('login'))\n login_user(user, remember=form.remember_me.data)\n flash(f'Login successful for {user.username} ({user.email})', 'success')\n next_page = request.args.get('next')\n if not next_page or url_parse(next_page).netloc != '':\n next_page = url_for('index')\n return redirect(next_page)\n return render_template('login.html', title='Sign In', form=form)\n\n\[email protected]('/register', methods=['GET', 'POST'])\ndef register():\n if current_user.is_authenticated:\n redirect(url_for('index'))\n form = RegisterForm()\n if form.validate_on_submit():\n user = User(username=form.username.data, email=form.email.data)\n user.set_password(form.password.data)\n db.session.add(user)\n db.session.commit()\n flash('Congratulations, you successfully registered!', 'success')\n return redirect(url_for('index'))\n form = RegisterForm()\n return render_template('register.html', title='Registration', form=form)\n\n\[email protected]('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('index'))\n\n\[email protected]('/user/<username>')\n@login_required\ndef user(username):\n user = User.query.filter_by(username=username).first_or_404()\n page = request.args.get('page', 1, type=int)\n if user == current_user:\n posts = user.get_followed_posts().paginate(page, app.config['POST_PER_PAGE'], False)\n else:\n posts = user.posts.order_by(Post.timestamp.desc()).paginate(page, app.config['POST_PER_PAGE'], False)\n next_url = url_for('user', username=user.username, page=posts.next_num) if posts.has_next else None\n prev_url = url_for('user', username=user.username, page=posts.prev_num) if posts.has_prev else None\n form = EmptyForm()\n return render_template('user.html', user=user, form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)\n\n\[email protected]('/edit_profile', methods=['GET', 'POST'])\n@login_required\ndef edit_profile():\n form = EditProfileForm(formdata=request.form, obj=current_user)\n if form.validate_on_submit():\n form.populate_obj(current_user)\n db.session.commit()\n flash('Profile successfully updated', 'success')\n return redirect(url_for('user', username=current_user.username))\n return render_template('edit_profile.html', title='Edit Profile', form=form)\n\n\[email protected]('/follow/<username>', methods=['POST'])\n@login_required\ndef follow(username):\n form = EmptyForm()\n if form.validate_on_submit():\n user = User.query.filter_by(username=username).first_or_404()\n if not user:\n flash(f'User {username} is not found', 'info')\n return redirect(url_for('index'))\n elif user == current_user:\n flash('You cannot follow yourself', 'info')\n return redirect(url_for('user', username=username))\n else:\n current_user.follow(user)\n db.session.commit()\n flash(f'You are following {username}!', 'success')\n return redirect(url_for('user', username=username))\n else:\n return redirect(url_for('index'))\n\n\[email protected]('/unfollow/<username>', methods=['POST'])\n@login_required\ndef unfollow(username):\n form = EmptyForm()\n if form.validate_on_submit():\n user = User.query.filter_by(username=username).first_or_404()\n if not user:\n flash(f'User {username} is not found', 'info')\n return redirect(url_for('index'))\n elif user == current_user:\n flash('You cannot unfollow yourself', 'info')\n return redirect(url_for('user', username=username))\n else:\n current_user.unfollow(user)\n db.session.commit()\n flash(f'You are unfollowing {username}!', 'info')\n return redirect(url_for('user', username=username))\n else:\n return redirect(url_for('index'))\n" } ]
7
Ren-Roros-Digital/django-admin-export-xlsx
https://github.com/Ren-Roros-Digital/django-admin-export-xlsx
acd002b0d43a4210135dc00807e3f098e4c00173
da8f66c9263e89b76ea1169ef0ad378d858937d8
677882a943d7a2804303c38f1d8c44333f6cc60d
refs/heads/main
2023-04-20T05:51:24.353687
2021-04-21T10:30:50
2021-04-21T10:30:50
360,123,954
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6015424132347107, "alphanum_fraction": 0.6143959164619446, "avg_line_length": 20.61111068725586, "blob_id": "3f3ca63c2f57df56b06a96dbe36fa860b8e03ed3", "content_id": "a16a10460b03ffd02c3e9b6093f4bb973c4dfb52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 389, "license_type": "permissive", "max_line_length": 66, "num_lines": 18, "path": "/README.rst", "repo_name": "Ren-Roros-Digital/django-admin-export-xlsx", "src_encoding": "UTF-8", "text": "Django Admin Export xlsx\n========================\n\n| All credit goes to the autor of \n| https://www.djangosnippets.org/snippets/10681/\n\nUsage\n-----\n\n| https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/\n\n.. code:: python\n\n from export_xlsx import export_as_xls\n\n class <arbitraryAdminClass>(admin.ModelAdmin):\n ...\n actions [export_as_xls]\n" }, { "alpha_fraction": 0.6228492856025696, "alphanum_fraction": 0.6266345381736755, "avg_line_length": 34.87654495239258, "blob_id": "25639827171707c24ba9b1901c44bf614581fb5d", "content_id": "564e2355603edf00dff2994270fb9b51ea5800c5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2906, "license_type": "permissive", "max_line_length": 109, "num_lines": 81, "path": "/export_xlsx/actions.py", "repo_name": "Ren-Roros-Digital/django-admin-export-xlsx", "src_encoding": "UTF-8", "text": "from openpyxl import Workbook\nfrom django.core.exceptions import PermissionDenied\nfrom django.http import HttpResponse\nfrom datetime import datetime, date\nfrom openpyxl.styles import Font\nfrom unidecode import unidecode\n\nclass ExportExcelAction:\n @classmethod\n def generate_header(cls, admin, model, list_display):\n def default_format(value):\n return value.replace('_', ' ').upper()\n\n header = []\n for field_display in list_display:\n is_model_field = field_display in [f.name for f in model._meta.fields]\n is_admin_field = hasattr(admin, field_display)\n if is_model_field:\n field = model._meta.get_field(field_display)\n field_name = getattr(field, 'verbose_name', field_display)\n header.append(default_format(field_name))\n elif is_admin_field:\n field = getattr(admin, field_display)\n field_name = getattr(field, 'short_description', default_format(field_display))\n header.append(default_format(field_name))\n else:\n header.append(default_format(field_display))\n return header\n\ndef style_output_file(file):\n black_font = Font(color='000000', bold=True)\n for cell in file[\"1:1\"]:\n cell.font = black_font\n\n for column_cells in file.columns:\n length = max(len((cell.value)) for cell in column_cells)\n length += 10\n file.column_dimensions[column_cells[0].column_letter].width = length\n\n return file\n\ndef convert_data_date(value):\n return value.strftime('%d.%m.%Y')\n\ndef convert_boolean_field(value):\n if value:\n return 'Yes'\n return 'No'\n\n\ndef export_as_xls(self, request, queryset):\n if not request.user.is_staff:\n raise PermissionDenied\n opts = self.model._meta\n field_names = self.list_display\n file_name = unidecode(opts.verbose_name)\n wb = Workbook()\n ws = wb.active\n ws.append(ExportExcelAction.generate_header(self, self.model, field_names))\n\n for obj in queryset:\n row = []\n for field in field_names:\n is_admin_field = hasattr(self, field)\n if is_admin_field:\n value = getattr(self, field)(obj)\n else:\n value = getattr(obj, field)\n if isinstance(value, datetime) or isinstance(value, date):\n value = convert_data_date(value)\n elif isinstance(value, bool):\n value = convert_boolean_field(value)\n row.append(str(value))\n ws.append(row)\n\n ws = style_output_file(ws)\n response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')\n response['Content-Disposition'] = f'attachment; filename={file_name}.xlsx'\n wb.save(response)\n return response\nexport_as_xls.short_description = \"Export as excel\"\n" }, { "alpha_fraction": 0.5963488817214966, "alphanum_fraction": 0.610547661781311, "avg_line_length": 26.38888931274414, "blob_id": "27f852abe08c58f78023adac23d6f3a759673353", "content_id": "ab18a5711a22118acf0972d46dca4a7f8b956a79", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 493, "license_type": "permissive", "max_line_length": 71, "num_lines": 18, "path": "/setup.py", "repo_name": "Ren-Roros-Digital/django-admin-export-xlsx", "src_encoding": "UTF-8", "text": "from setuptools import setup\n\nsetup(\n name='django-admin-export-xlsx',\n version='1.0.0',\n author='Rune Hansén Steinnes',\n author_email='[email protected]',\n packages=['export_xlsx'],\n url='http://github.com/Ren-Roros-Digital/django-admin-export-xlsx',\n license='LICENSE.txt',\n description='Admin action to export xlsx from list_display',\n long_description=open('README.rst').read(),\n install_requires=[\n \"Django >= 3\",\n \"unidecode >=1.2\",\n \"openpyxl >= 3\",\n ],\n)\n" } ]
3
furotsu/turret_game
https://github.com/furotsu/turret_game
0e496ecdb8bccfca1d5d89320281023fcfc2803c
b68bc10cd4f026ed13ba3691dc3d7a38cff19d81
e0ae8aefb05f1fad892f3608ff2f83f17d323657
refs/heads/master
2021-01-13T22:55:38.721646
2020-02-23T13:16:04
2020-02-23T13:16:04
242,520,843
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5685047507286072, "alphanum_fraction": 0.5774996876716614, "avg_line_length": 33.71040725708008, "blob_id": "d71b9586dc9331820facadfad72192447fdae657", "content_id": "9107e78a0801a8076be7d95a90044973f52ca173", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7671, "license_type": "no_license", "max_line_length": 118, "num_lines": 221, "path": "/player.py", "repo_name": "furotsu/turret_game", "src_encoding": "UTF-8", "text": "import pygame\nimport sys\nimport math\nfrom random import randint, choice\nfrom constants import *\n\n\nclass Player(pygame.sprite.Sprite):\n def __init__(self, pos_x, pos_y, screen):\n super(Player, self).__init__()\n self.screen = screen\n self.original_image = pygame.image.load(player_img).convert_alpha() # we should rotate original image instead\n self.image = self.original_image # of current to keep it quality\n self.rect = self.image.get_rect().move((pos_x, pos_y))\n\n self.charger = pygame.Surface((0, CHARGER_HEIGHT))\n self.charger.fill(pygame.Color('sienna2'))\n self.shot_power = 0\n self.cooldown = pygame.Surface((COOLDOWN_WIDTH, 0))\n self.cooldown.fill(YELLOW)\n self.shot_cooldown = 0\n\n self.current_angle = START_CANNON_ANGLE\n self.motion = STOP\n self.missile = None\n self.already_shoot = False\n self.is_charging = False\n self.increase_shot_power = True\n\n def draw(self):\n self.screen.blit(self.image, self.rect)\n\n def shoot(self):\n self.already_shoot = True\n self.missile = Missile(self.current_angle + 15, MISSILE_POS_X, MISSILE_POS_Y, self.shot_power,\n self.screen)\n\n def get_missile_rect(self):\n if self.already_shoot:\n return self.missile.rect\n else:\n return None\n\n def action(self, event):\n \"\"\"processing pressed button \"\"\"\n if event.type == pygame.QUIT:\n sys.exit()\n else:\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n self.motion = UP\n elif event.key == pygame.K_DOWN:\n self.motion = DOWN\n elif event.key == pygame.K_SPACE and not self.shot_cooldown:\n self.motion = STOP\n self.is_charging = True\n elif event.type == pygame.KEYUP:\n if event.key in [pygame.K_UP, pygame.K_DOWN]:\n self.motion = STOP\n elif event.key == pygame.K_SPACE and not self.shot_cooldown:\n self.is_charging = False\n self.shoot()\n self.shot_cooldown = COOLDOWN\n self.shot_power = 0\n\n def draw_game_elements(self):\n self.screen.fill(WHITE)\n self.draw()\n if self.is_charging:\n self.draw_charger()\n self.draw_trajectory()\n if self.shot_cooldown:\n self.draw_cooldown()\n if self.already_shoot:\n self.missile.draw()\n\n def update_game_elements(self):\n self.update_player(self.motion)\n if self.is_charging:\n self.update_charger()\n elif self.already_shoot:\n self.update_missile()\n\n def update_missile(self):\n self.missile.update_velocity()\n self.missile.move()\n\n def update_player(self, angle):\n self.image = pygame.transform.rotate(self.original_image, self.current_angle + angle)\n x, y, = self.rect.center\n self.current_angle += angle\n self.rect = self.image.get_rect() # make image rotate around its center\n self.rect.center = (x, y) # and preventing it from moving around screen\n self.update_cooldown()\n\n def update_charger(self):\n self.check_power_limits()\n if self.increase_shot_power:\n self.shot_power += POWER_CHARGE\n else:\n self.shot_power -= POWER_CHARGE\n self.charger = pygame.transform.scale(self.charger, (self.shot_power, CHARGER_HEIGHT))\n\n def update_cooldown(self):\n if self.shot_cooldown != 0:\n self.shot_cooldown -= 1\n self.cooldown = pygame.transform.scale(self.cooldown, (COOLDOWN_WIDTH, self.shot_cooldown))\n\n def check_power_limits(self):\n if self.shot_power >= MAX_SHOT_POWER:\n self.increase_shot_power = False\n elif self.shot_power <= 0:\n self.increase_shot_power = True\n\n def draw_charger(self):\n self.screen.blit(self.charger, (PLAYER_POS_X, PLAYER_POS_Y - 80))\n\n def draw_cooldown(self):\n self.screen.blit(self.cooldown, (PLAYER_POS_X + 80, PLAYER_POS_Y - 100))\n\n def draw_trajectory(self):\n time = 2\n if self.shot_power != 0:\n velocity_x = self.shot_power * math.cos((self.current_angle + 15) * math.pi / 180)\n velocity_y = -self.shot_power * math.sin((self.current_angle + 15) * math.pi / 180)\n while time != 20:\n pos_x = int(MISSILE_POS_X + velocity_x * time)\n pos_y = int(MISSILE_POS_Y + velocity_y * time - (ACCELERATION * time ** 2) / 2)\n pygame.draw.circle(self.screen, RED, (pos_x, pos_y), 10)\n time += 1\n\n\nclass Missile(pygame.sprite.Sprite):\n def __init__(self, angle, pos_x, pos_y, shot_power, screen):\n super(Missile, self).__init__()\n self.image = pygame.image.load(missile_img).convert_alpha()\n self.screen = screen\n self.velocity_x = shot_power * math.cos(angle * math.pi / 180)\n self.velocity_y = -shot_power * math.sin(angle * math.pi / 180)\n self.rect = self.image.get_rect().move((pos_x, pos_y))\n\n def update_velocity(self):\n self.velocity_y -= ACCELERATION\n\n def move(self):\n self.rect.x += self.velocity_x\n self.rect.y += self.velocity_y\n\n def draw(self):\n self.screen.blit(self.image, self.rect)\n\n\nclass Enemies(pygame.sprite.Sprite):\n def __init__(self, screen, *groups):\n super(Enemies, self).__init__()\n self.image = choice([enemy1_img, enemy2_img, enemy3_img])\n self.image = pygame.image.load(self.image).convert_alpha()\n self.rect = self.image.get_rect().move((randint(500, 700), -20))\n self.screen = screen\n self.velocity_x = ENEMY_VELOCITY_X\n self.velocity_y = ENEMY_VELOCITY_Y\n\n def move(self):\n self.rect.x += self.velocity_x\n self.rect.y += self.velocity_y\n\n def draw(self):\n self.screen.blit(self.image, self.rect)\n\n def check_destiny(self):\n if display_height + 100 >= self.rect.y >= display_height:\n self.rect.y = display_height + 1000\n return True\n return False\n\n\nclass AlienArmy:\n def __init__(self, player, screen):\n self.enemies = []\n self.screen = screen\n self.time_before_new_enemy = 3\n self.player = player\n self.kill_count = 0\n\n def update_enemies(self): # move enemies and check for collide with missile\n self.check_army_integrity()\n for enemy in self.enemies:\n enemy.move()\n enemy.draw()\n self.enemy_hit(self.player.get_missile_rect()) # check if enemy hit by missile and kill it if positive\n\n def defeat(self): # check if player lost of not\n for enemy in self.enemies:\n if enemy.check_destiny():\n return True\n return False\n\n def enemy_hit(self, missile):\n if missile is None:\n return\n counter = 0\n for enemy in self.enemies:\n if missile.colliderect(enemy):\n self.kill_enemy(counter)\n counter += 1\n\n def add_enemy(self):\n self.enemies.append(Enemies(self.screen))\n\n def check_army_integrity(self):\n if self.time_before_new_enemy == 0:\n self.add_enemy()\n self.time_before_new_enemy = TIME_BETWEEN_ENEMIES\n self.time_before_new_enemy -= 1\n\n def kill_enemy(self, pos):\n self.enemies.pop(pos)\n self.kill_count += 1\n\n def renew_kill_count(self):\n self.kill_count = 0\n" }, { "alpha_fraction": 0.6108033061027527, "alphanum_fraction": 0.6108033061027527, "avg_line_length": 25.740739822387695, "blob_id": "16bc7a5c1008382debe570eac14b47dded085a55", "content_id": "f9e8b42ec26ed041d6d38b5f54e06155da65b3c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 722, "license_type": "no_license", "max_line_length": 66, "num_lines": 27, "path": "/menu.py", "repo_name": "furotsu/turret_game", "src_encoding": "UTF-8", "text": "import pygame\nfrom constants import *\n\n\nclass MenuButton:\n \"\"\"Create a button \"\"\"\n\n def __init__(self, pos_x, pos_y, image, button_type):\n self.button_type = button_type\n self.image = pygame.image.load(image).convert_alpha()\n self.size = self.image.get_rect().size\n self.rect_pos = self.image.get_rect().move((pos_x, pos_y))\n\n def draw(self, screen):\n screen.blit(self.image, self.rect_pos)\n\n\nclass MainMenu:\n \"\"\"manage all of the buttons in menu \"\"\"\n \n def __init__(self, screen, *buttons):\n self.buttons = buttons\n self.screen = screen\n\n def draw(self):\n for button in self.buttons:\n self.screen.blit(button.image, button.rect_pos)\n" }, { "alpha_fraction": 0.644444465637207, "alphanum_fraction": 0.644444465637207, "avg_line_length": 14.166666984558105, "blob_id": "899bc3e30af2277b5123c0cbdfaf806c47aa3378", "content_id": "79d138efc7634f3fa86a2ff66469ce55268006d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 90, "license_type": "no_license", "max_line_length": 23, "num_lines": 6, "path": "/terrain.py", "repo_name": "furotsu/turret_game", "src_encoding": "UTF-8", "text": "import pygame\nfrom constants import *\n\nclass Terrain:\n def __init__(self):\n pass" }, { "alpha_fraction": 0.5600000023841858, "alphanum_fraction": 0.5648484826087952, "avg_line_length": 21.91666603088379, "blob_id": "e764377f4ca83cc80916dcdcff42a88b154f01f1", "content_id": "13828018d0d66406a9ca39d35a88f919072511a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 825, "license_type": "no_license", "max_line_length": 69, "num_lines": 36, "path": "/main.py", "repo_name": "furotsu/turret_game", "src_encoding": "UTF-8", "text": "import pygame\nfrom controller import *\nfrom menu import *\nfrom constants import *\n\n\ndef main():\n pygame.init()\n\n screen = pygame.display.set_mode((display_width, display_height))\n\n pygame.display.set_caption(\"Cannon defend v0.08\")\n\n clock = pygame.time.Clock()\n\n controller = Controller(screen, pygame.time.Clock())\n\n while True:\n\n controller.set_menu()\n\n while not controller.game_started: # main menu loop\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return 0\n else:\n controller.menu_action(event)\n controller.draw_new_screen()\n pygame.display.flip()\n clock.tick(FPS)\n\n controller.start_game()\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5961251854896545, "alphanum_fraction": 0.6229507923126221, "avg_line_length": 32.54999923706055, "blob_id": "cde7025d6b2e147de0c88adca5d3c47cc71a4999", "content_id": "9dbe3b0b1aaad306d3d33a47ea55977721964ce4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 671, "license_type": "no_license", "max_line_length": 95, "num_lines": 20, "path": "/death_screen.py", "repo_name": "furotsu/turret_game", "src_encoding": "UTF-8", "text": "import pygame\nfrom constants import *\n\n\nclass Death_screen:\n def __init__(self, screen, *buttons):\n self.main_block = pygame.Surface((display_width - 200, display_height - 100))\n self.main_block.fill(pygame.Color('sienna2'))\n self.screen = screen\n self.buttons = buttons\n\n def draw(self, score):\n font = pygame.font.Font('freesansbold.ttf', 16)\n self.draw_main_block()\n self.screen.blit(font.render(\"Your score is: {}\".format(score), True, BLACK), (80, 70))\n for button in self.buttons:\n button.draw(self.screen)\n\n def draw_main_block(self):\n self.screen.blit(self.main_block, (100, 50))\n" }, { "alpha_fraction": 0.5585400462150574, "alphanum_fraction": 0.5658081769943237, "avg_line_length": 33.02688217163086, "blob_id": "4aac5915ae2446a220a0c0d87b32aca045145dca", "content_id": "adebcd08bd3ec9197ade65c828a47fa78ac0fe99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6329, "license_type": "no_license", "max_line_length": 118, "num_lines": 186, "path": "/controller.py", "repo_name": "furotsu/turret_game", "src_encoding": "UTF-8", "text": "import pygame\nimport sys\nimport menu\nimport player\nimport leaderboard\nimport death_screen\nimport terrain\nfrom constants import *\n\n\nclass Controller:\n \"\"\"\n Class that control all game actions\n \"\"\"\n\n def __init__(self, screen, clock):\n self.screen = screen\n self.clock = clock\n\n self.game_started = False\n\n self.quit_button = menu.MenuButton(display_width / 2 - 150, display_height / 2, quit_button_img, \"quit\")\n self.start_button = menu.MenuButton(display_width / 2 - 150, display_height / 4, start_button_img, \"start\")\n self.leaderboard_button = menu.MenuButton(display_width / 2 - 450, display_height / 6, leaderboard_button_img,\n \"leaderboard\")\n self.back_button = menu.MenuButton(display_width / 4, display_height - 100, back_button_img, \"back\")\n\n self.menu_table = menu.MainMenu(self.screen, self.quit_button, self.start_button, self.leaderboard_button)\n self.leaderboard_table = leaderboard.Leaderboard(leaderboard_storage, screen)\n self.create_start_leaderboard()\n\n self.death_screen_table = death_screen.Death_screen(screen, self.back_button)\n\n self.game_surface = terrain.Terrain()\n self.player = player.Player(PLAYER_POS_X, PLAYER_POS_Y, self.screen)\n\n self.army = player.AlienArmy(self.player, self.screen)\n\n def menu_action(self, event):\n if event.type == pygame.MOUSEBUTTONDOWN:\n for button in self.menu_table.buttons:\n if button.rect_pos.collidepoint(event.pos): # trigger pressed button\n self.trigger(button)\n else:\n pass\n\n def back_button_action(self, event):\n if event.type == pygame.MOUSEBUTTONDOWN and self.back_button.rect_pos.collidepoint(event.pos):\n self.back_pressed()\n\n def trigger(self, button):\n if button.button_type == \"quit\":\n self.quit_pressed()\n elif button.button_type == \"start\":\n self.start_pressed()\n elif button.button_type == \"leaderboard\":\n self.leaderboard_pressed()\n self.show_leaderboard()\n\n def quit_pressed(self):\n sys.exit()\n\n def start_pressed(self):\n self.game_started = True # make main game loop in main.py start\n\n def leaderboard_pressed(self):\n self.leaderboard_table.closed = False\n\n def back_pressed(self):\n if not self.leaderboard_table.closed:\n self.leaderboard_table.closed = True\n self.leaderboard_table.renew_board()\n elif self.game_started:\n self.game_started = False\n\n def show_leaderboard(self):\n self.leaderboard_table.generate_text()\n self.leaderboard_table.render_text()\n\n while not self.leaderboard_table.closed:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n else:\n self.back_button_action(event)\n\n self.screen.fill(WHITE)\n self.leaderboard_table.draw()\n self.draw_back_button()\n pygame.display.flip()\n self.clock.tick(FPS)\n\n def create_start_leaderboard(self):\n for key, item in computer_scores.items():\n self.leaderboard_table.add_score(key, item)\n\n def draw_back_button(self):\n self.back_button.draw(self.screen)\n\n def draw_new_screen(self):\n self.screen.fill(WHITE)\n self.set_menu()\n\n def set_menu(self):\n self.menu_table.draw()\n\n def start_game(self):\n self.player_name = self.get_player_name()\n self.screen.fill(WHITE)\n self.game_loop()\n\n def get_player_name(self):\n player_name = \"\"\n flag = True\n while flag:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_0:\n return player_name\n elif event.key == pygame.K_BACKSPACE:\n player_name = player_name[:-1] # delete last element of name if backspace pressed\n elif 97 <= event.key <= 122:\n player_name += chr(event.key)\n else:\n pass\n self.display_player_name(player_name)\n\n def display_player_name(self, player_name):\n font = pygame.font.Font('freesansbold.ttf', 16)\n left = (display_width / 2) - 250\n top = (display_height / 2) - 100\n self.screen.fill(WHITE)\n pygame.draw.rect(self.screen, YELLOW, (left, top, 320, 150))\n self.screen.blit(font.render(player_name, True, BLACK), (left + 80, top + 70))\n pygame.display.flip()\n\n def game_over(self):\n self.leaderboard_table.add_score(self.player_name, self.army.kill_count)\n self.death_screen_table.draw(self.army.kill_count)\n self.army.renew_kill_count()\n while self.game_started:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n else:\n self.back_button_action(event)\n pygame.display.flip()\n\n def check_for_pause(self, event):\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n self.pause_game()\n\n def pause_game(self):\n while True:\n self.draw_back_button()\n pygame.display.flip()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n return\n\n def game_loop(self):\n self.player.draw()\n\n while self.game_started:\n\n for event in pygame.event.get():\n self.player.action(event)\n self.check_for_pause(event)\n\n self.player.update_game_elements()\n self.player.draw_game_elements()\n\n self.army.update_enemies()\n\n if self.army.defeat():\n self.game_over()\n\n pygame.display.flip()\n\n self.clock.tick(FPS)\n" }, { "alpha_fraction": 0.5847299695014954, "alphanum_fraction": 0.5940409898757935, "avg_line_length": 34.77777862548828, "blob_id": "488d35e6f2fdde2f0943986b12522861830d787a", "content_id": "1a77e7653b261b95f026abfd60bba0d189fe69b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1611, "license_type": "no_license", "max_line_length": 106, "num_lines": 45, "path": "/leaderboard.py", "repo_name": "furotsu/turret_game", "src_encoding": "UTF-8", "text": "import shelve\nimport pygame\nfrom constants import *\n\n\nclass Leaderboard:\n def __init__(self, filename, screen):\n self.file = shelve.open(filename)\n self.closed = True\n self.screen = screen\n self.sorted_leaderboard = []\n self.text = []\n self.rendered_text = []\n self.sorted_leaderboard = []\n\n def draw(self): # draw scores one by one\n counter = 0\n for score in self.rendered_text:\n self.screen.blit(score, (display_width / 4, 20 + counter)) # make indent between scores\n counter += 20\n\n def generate_text(self): # get scores by one and add it to a str list\n self.sort_leaderboard()\n for i in range(len(self.sorted_leaderboard), 0, -1):\n player_name = self.sorted_leaderboard[i - 1][0]\n score = self.sorted_leaderboard[i - 1][1]\n self.text.append(\"{} |==| {}\".format(player_name, score))\n\n def render_text(self):\n font = pygame.font.Font('freesansbold.ttf', 16)\n for score in self.text:\n self.rendered_text.append(font.render(score, True, BLACK, WHITE))\n\n def add_score(self, player_name, score):\n if player_name in self.file.keys() and score > self.file[player_name]:\n self.file[player_name] = score\n elif player_name not in self.file.keys():\n self.file[player_name] = score\n\n def renew_board(self):\n self.text = []\n self.rendered_text = []\n\n def sort_leaderboard(self):\n self.sorted_leaderboard = [(k, v) for k, v in sorted(self.file.items(), key=lambda item: item[1])]\n\n" }, { "alpha_fraction": 0.5776347517967224, "alphanum_fraction": 0.658085286617279, "avg_line_length": 21.581817626953125, "blob_id": "a068c1739390c44c20452fbc63e9d405a6503204", "content_id": "3edd52790a04242abf8b960818cab7df70b4f34f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1243, "license_type": "no_license", "max_line_length": 71, "num_lines": 55, "path": "/constants.py", "repo_name": "furotsu/turret_game", "src_encoding": "UTF-8", "text": "import os.path\n\ndisplay_height = 600\ndisplay_width = 1000\n\nCHARGER_HEIGHT = 60\nCOOLDOWN_WIDTH = 50\n\nPLAYER_POS_X = 50\nPLAYER_POS_Y = 430\nSTART_CANNON_ANGLE = 25\n\nMISSILE_POS_X = 70\nMISSILE_POS_Y = 470\nACCELERATION = -2\nMAX_SHOT_POWER = 50\nPOWER_CHARGE = 5\nCOOLDOWN = 40\n\nENEMY_VELOCITY_X = 0\nENEMY_VELOCITY_Y = 4\nTIME_BETWEEN_ENEMIES = 100\n\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nYELLOW = (255, 255, 51)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\n\nSTOP = 0\nUP = 1\nDOWN = -1\n\nFPS = 30\n\n# extracting images from their folders\nstart_button_img = os.path.join(\"data\", \"start_button.png\")\nquit_button_img = os.path.join(\"data\", \"quit_button.png\")\nleaderboard_button_img = os.path.join(\"data\", \"leaderboard_button.png\")\nback_button_img = os.path.join(\"data\", \"back_button.png\")\nplayer_img = os.path.join(\"data\", \"player_image.png\")\nmissile_img = os.path.join(\"data\", \"missile_image.png\")\nenemy1_img = os.path.join(\"data\", \"enemy1.png\")\nenemy2_img = os.path.join(\"data\", \"enemy2.png\")\nenemy3_img = os.path.join(\"data\", \"enemy3.png\")\n\nleaderboard_storage = os.path.join(\"data\", \"leaderboard.db\")\ncomputer_scores = dict([\n (\"Vlad\", 100000),\n (\"Misha\", 5000),\n (\"Arthur\", 2500),\n (\"Max\", 2000),\n (\"Kirrilishche\", 10)\n])\n\n" } ]
8
BlastTNG/flight
https://github.com/BlastTNG/flight
50801f63f875b36404850d28f0097a12ccf3cafc
4be73eb6d43c2250a34ca6e1bd1a0937f50aa4c7
fe8b5096b1ebc8eb81a4eff960659dbcb144eb0b
refs/heads/master
2023-05-25T12:35:42.042136
2023-05-23T17:59:17
2023-05-23T17:59:17
41,045,504
2
2
null
null
null
null
null
[ { "alpha_fraction": 0.6568225622177124, "alphanum_fraction": 0.6732054352760315, "avg_line_length": 23.93010711669922, "blob_id": "417f764a896e30967dab758245277b74853c09c0", "content_id": "1da1d8aac7344d678dfdc03b165783571d918b02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4639, "license_type": "no_license", "max_line_length": 125, "num_lines": 186, "path": "/starcam/imageviewer.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include \"imageviewer.h\"\n#include <sstream>\n#include <qapplication.h>\n#include <qimage.h>\n#include <qlabel.h>\n#include <qstring.h>\n#include <qpainter.h>\n#include <qtimer.h>\n#include <qcursor.h>\n#include \"blobimage.h\"\n\n#define VIEWER_DEBUG 0\n#if VIEWER_DEBUG\n#include <iostream>\n#endif\n\n/*\n\n Image Viewer:\n \n constructor, creates a widget for displaying a BlobImage of width w and height h\n image will be set to refresh after a time of msec milliseconds\n parent widget is for Qt purposese, and name used internally only\n \n*/\nImageViewer::ImageViewer(int w, int h, int img_w, int img_h, int msec/*=10*/, QWidget* parent/*=0*/, const char * name/*=0*/)\n\t: QWidget(parent, name)\n{\n#if VIEWER_DEBUG\n\tcerr << \"[Viewer debug]: constructing with w=\" << w << \" h=\" << h << \" msec=\" << msec << endl;\n#endif\n\tthis->setBaseSize(w, h);\n\tthis->setPalette(QPalette(QColor(0, 0, 0)));\n \tthis->setCursor(QCursor(Qt::BlankCursor));\n\t\n\tqimg = new QImage(img_w, img_h, 8, 256);\n\tfor (int i=0; i<256; i++) //make image greyscale\n\t\tqimg->setColor(i, qRgb(i, i, i));\n\t\n\tbimg = NULL; //no image has been loaded\n\tneedsRepaint = false; //no need until first load\n\tautoBR = FALSE; //remembers last used value\n\tloading = false; //not in the process of loading an image\n\t\n\trefreshTimer = new QTimer(this, \"refresh timer\");\n\tconnect(refreshTimer, SIGNAL(timeout()), this, SLOT(refresh()));\n\trefreshTimer->start(msec);\n\t\n}\n\n/*\n\n ~ImageViewer:\n \n destructor, cleans up image data (label is taken care of by Qt)\n \n*/\nImageViewer::~ImageViewer()\n{\n#if VIEWER_DEBUG\n\tcerr << \"[Viewer debug]: in destructor\" << endl;\n#endif\n\tdelete qimg;\n}\n\n/*\n\n load:\n \n loads a BlobImage into the window, converts from 16bpp to 8bp, repaints\n if autoBR is TRUE, will find a recommended background and range value for the image\n reasonable values for background and range are needed for good converion\n \n*/\nvoid ImageViewer::load(BlobImage* img, bool in_autoBR/*=FALSE*/)\n{\n#if VIEWER_DEBUG\n\tcerr << \"[Viewer debug]: loading an image\" << endl;\n#endif\n\tloading = true;\n\tbimg = img;\n\tautoBR = in_autoBR;\n\tif (autoBR) img->AutoBackgroundAndRange();\n\tunsigned short background = img->GetBackground();\n\tunsigned short range = img->GetRange();\n\tunsigned short *data16 = img->GetImagePointer();\n\t\n\tfor (int i=0; i<bimg->GetHeight(); i++) {\n\t\tunsigned char *qline = qimg->scanLine(i);\n\t\tunsigned short *bline = data16 + i*bimg->GetWidth();\n\t\tfor (int j=0; j<bimg->GetWidth(); j++)\n\t\t\t*(qline+j) = conv16to8(*(bline+j),background, range);\n\t}\n\tbimg->setChanged(false);\n\tneedsRepaint = true;\n\tloading = false;\n\t\n}\n\n/*\n\n conv16to8:\n \n converts a 16bpp pixel value to an 8bpp one for given image background and range\n \n*/\nunsigned char ImageViewer::conv16to8(unsigned short val16, unsigned short back, \n\t\t\t\t\t\t\t unsigned short range)\n{\n\tunsigned char result;\n\tif (val16 <= back) result = (unsigned char)0;\n\telse if (val16 >= back + range) result = (unsigned char)255;\n\telse result = (unsigned char)((val16 - back) * 255 / range);\n\t\n\treturn result;\n}\n\n/*\n\n setRefreshTime:\n \n sets the refresh interval to msec milliseconds\n \n*/\nvoid ImageViewer::setRefreshTime(int msec)\n{\n\trefreshTimer->changeInterval(msec);\n}\n\n/*\n\n refresh:\n \n public slot for refreshing the image\n \n*/\nvoid ImageViewer::refresh()\n{\n#if VIEWER_DEBUG\n\tstatic int count = 1;\n#endif\n\tif (loading) return; //do nothing while an image is loading\n\n\tif (bimg && bimg->isChanged()) //check if changed without load\n\t\tload(bimg, autoBR);\n\tif (needsRepaint && bimg) {\n#if VIEWER_DEBUG\n\t cerr << \"[Viewer debug]: \" << count++ << \" repainting the image. \" << endl;\n#endif\n\t\trepaint();\n\t\tneedsRepaint = 0;\n\t}\n}\n\n/*\n\n paintEvent:\n \n unoptimized paint function that redraws entire image on every repaint\n \n*/\nvoid ImageViewer::paintEvent(QPaintEvent*)\n{\n\tQPainter p(this);\n\tQImage scaled_img = qimg->smoothScale(width(), height(), QImage::ScaleMin);\n\tQRect img_rect = this->rect();\n\timg_rect.setWidth(scaled_img.width());\n\timg_rect.setHeight(scaled_img.height());\n\tstruct tm timestruct = bimg->CSBIGImg::GetImageStartTime();\n\tstring CamName = bimg->CSBIGImg::GetObserver(); \n\tQString timestring;\n\tQString IDstring;\n\tostringstream sout;\n\tostringstream sout2;\n\tsout << ((timestruct.tm_hour<10)?\"0\":\"\") << timestruct.tm_hour << \":\"\n\t\t << ((timestruct.tm_min<10)?\"0\":\"\") << timestruct.tm_min << \":\"\n\t\t << ((timestruct.tm_sec<10)?\"0\":\"\") << timestruct.tm_sec;\n\tsout2 << CamName;\n\ttimestring = sout.str();\n\tIDstring = sout2.str();\n\tp.drawImage(img_rect, scaled_img);\n\tp.setPen(Qt::red);\n\tp.setFont(QFont(\"Arial\",12));\n\tp.drawText(30,30,IDstring);\n\tp.drawText(30,50,timestring);\n}\n\n\n" }, { "alpha_fraction": 0.703942060470581, "alphanum_fraction": 0.703942060470581, "avg_line_length": 23.860000610351562, "blob_id": "c1729bacf573db0ee7cd4c6e3d351d0646cb5564", "content_id": "6f92b437d8abc3f8a7dca153654d0366257e93f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1243, "license_type": "no_license", "max_line_length": 77, "num_lines": 50, "path": "/starcam/camcommserver.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#ifndef CAMCOMMSERVER_H\n#define CAMCOMMSERVER_H\n\n#include <string>\n#include <pthread.h>\n#include \"camstruct.h\"\n#include \"camcommunicator.h\"\n\n/**\n * @author Steve Benton\n * Class which handles multiple connections on server side of CamCommunicator\n * Deprecates the openHost logic in CamCommunicator.\n */\n\nclass CamCommServer {\npublic:\n //struct that contains all information for a single connection\n struct camConnection {\n CamCommunicator* comm;\n camConnection *prev, *next;\n pthread_t thread;\n string (*interpreter)(string);\n };\n\n CamCommServer(short int port = DEFAULT_CAM_PORT);\n ~CamCommServer();\n void closeConnection();\n \n int startServer(string (*interpretFunction)(string));\n int sendAll(string msg);\n\n //accessors\n void setPort(short int newport) { listenPort = newport; }\n\n //run the connection in a thread\n void runConnection(camConnection* conn);\n\nprivate:\n int serverFD; //file descriptor for listening socket\n int listenPort; //port to listen on\n camConnection *first, *last; //doubly-linked list of connections\n int count; //number of connections\n\n //maintaining the list\n void add(camConnection* addee);\n void remove(camConnection* removee);\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.5033017992973328, "alphanum_fraction": 0.5296176075935364, "avg_line_length": 33.74657440185547, "blob_id": "5c690dacaf9b917d73e59d30fe9345054d380955", "content_id": "1d1ce2eab662f71204405accc9933d237133fd51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 20292, "license_type": "no_license", "max_line_length": 158, "num_lines": 584, "path": "/naivepol/naivepol.cc", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <cctype>\n#include <matpack.h>\n#include <mpview.h>\n#include <wordexp.h>\n#include <string>\n#include <algorithm>\n\n#include <blasttools/blasttools.h>\n\nusing namespace std;\nusing namespace MATPACK;\n\n#define FLAG \"_f_10_CBN\" // Flag extension to use\n#define BOLO \"CALIB\" // Bolometer extention to use\n#define POINTING \"FK5_23_MV_19_CS\"\n#define CALP \"_cp_21_mdt\"\n#define TOD_OFFS 0\n#define ZERO_COLD_ENC 0.451545\n\n#ifdef SCOFFSFILE\n#undef SCOFFSFILE\n#endif\n\n#ifdef BOLO_TABLE\n#undef BOLO_TABLE\n#endif\n\n#define SCOFFSFILE \"sc_offs_mcm_19_MV_16_CS_modforblast06.txt\"\n#define BOLO_TABLE \"bolotable_blastpol_20101224_modforblast06.txt\"\n//#define SCOFFSFILE \"sc_offs_kir.txt\"\n//#define BOLO_TABLE \"bolo_table_kir.txt\"\n\n#ifndef DATA_DIR\n#define DATA_DIR \"/data\"\n#endif\n\ntypedef struct {\n int f0, nf;\n} range_t;\n\nvoid Usage(char* name)\n{\n cerr << name << \" : bins up a naive map\" << endl << endl;\n\n cerr << name << \" [-F <file name>] [-f <first frame>] [-l <last frame> | -n <numframes>]\" << endl;\n cerr << \"\\t[-r <firstframe:numframes>] [-y <channel>] \" << endl;\n cerr << \"\\t[-C <Colour(250, 350 or 500)>] [-o <fits file name>]\" << endl;\n cerr << \"\\t[-s <ra(h):dec(deg):size(deg)>] [-c <smooth angle(arcsec)>]\" << endl;\n cerr << \"\\t[-p <pixel angle(arcsec)>] [-B <bolo suffix>] [-K <flag suffix>]\" << endl;\n cerr << \"\\t[-P <pointing suffix>] [-O <offs file>] [-D <yaw:pitch (asec)>\" << endl;\n cerr << \"\\t[-h <freq (Hz)>] [-t <tod_offs (smaples)>] [-T] [-k] [-e] [-G] [-g] [-d] [-k]\" << endl;\n\n cerr << endl;\n cerr << \"Parameters:\" << endl;\n cerr << \"-F /data/blast_2005.z : Data repository to use\" << endl;\n cerr << \"-f framenum : Starting frame\" << endl; \n cerr << \"-l lastframe : End frame (as opposite to -n)\" << endl; \n cerr << \"-n number of frames : Number of frames to use (as opposite to -l)\" << endl; \n cerr << \"-r framenum:number_of_frames : Frame range can be given also in this way \" << endl;\n cerr << \"-y channel : Channel name (can specify more than one. \" << endl;\n cerr << \" Eg. -y N16C5 -y N15C10 -y ...\" << endl; \n cerr << \"-C colour : use this option if you want to bin a full array.\" << endl;\n cerr << \" : Eg. -C 250 for a full 250 map\" << endl;\n cerr << \" this option is an alternative to a -y list of\" << endl;\n cerr << \" channels to use\" << endl; \n cerr << endl;\n cerr << \"-p ang(arcsec) : Set the pixel size to ang (default 10\\\") \" << endl;\n cerr << \"-s ra(h):dec(deg):size(deg) : If this option is set, map is drawn to have\" << endl;\n cerr << \"-A ra(h):dec(deg):Xc:Yc:npix_x:npix_y : If this option is set, map is drawn to have\" << endl;\n cerr << \" ra,dec at pixel Xc, Yc and will be\" << endl ;\n cerr << \" npix_x X npix_y pixels wide\" << endl ;\n cerr << \"-c ang(arcsec) : Smooth the map with a gaussian of ang FWHM. \" << endl;\n cerr << \"-o filename : Output int filename. \\\".fits\\\" extention is added.\"<< endl;\n cerr << \" : Use \\\\!filename to override \" << endl;\n cerr << \"-B bolo_suffix : defaults to \" << BOLO << endl;\n cerr << \"-K flag_suffix : defaults to \" << FLAG << endl;\n cerr << \"-P pointing_suffix : defaults to \" << POINTING << endl;\n cerr << \"-O offset filename : defaults to \" << SCOFFSFILE << endl;\n cerr << \"-D yaw:pitch (arcsec) : yaw and pitch (xel, el) pointing offset\" << endl;\n cerr << \"-h freq(Hz) : High pass the data at the given frequency.\" << endl;\n cerr << \"-t tod_offs(samples) : TOD to pointing solution offs (default \" << TOD_OFFS << \")\" << endl;\n cerr << \"-L : Use Alt-Az coordinates\" << endl;\n cerr << \"-w : use weights - Each data stream is weighted\" << endl;\n cerr << \" by 1/noise as listed in \"<< endl;\n cerr << \" : \" << BOLO_TABLE << endl;\n cerr << \"-T : use telescope coordinates\" << endl;\n cerr << \"-k : Enable bolometer flagging\" << endl;\n cerr << \"-e : Enable pointing solution flagging\" << endl;\n cerr << \"-G : Use galactic coordinates\" << endl;\n cerr << \"-x : Calibrate with responsivity in \" << BOLO_TABLE << endl;\n cerr << \"-m : Calibrate with calpulse using \" << CALP << endl;\n cerr << \"-d : Despike Bolometers \" << endl;\n cerr << endl;\n cerr << \"EXAMPLES\" << endl;\n cerr << name << \" -F /data/blast_2005.z -f 657000 -l 689000 -y N7C13 \\n\\t -o \\\\!CRL2688\" << endl; \n cerr << \" make a single pixel map of CRL2688 in CRL26688_flux.fits\" << endl;\n cerr << endl;\n cerr << name << \" -F /data/blast_2005.z -f 657000 -l 689000 -y N7C13 -y N7C14 -y N9C20 \\n\\t -o \\\\!CRL_2688\" << endl; \n cerr << \" make a 3 pixels map of CRL2688 in CRL26688_flux.fits\" << endl;\n cerr << endl;\n cerr << name << \" -F /data/blast_2005.z -f 657000 -l 689000 -C 250 \\n\\t -o \\\\!CRL_2688 -p 10 -c 20\" << endl; \n cerr << \" make a full 250 map of CRL2688 with 10\\\" pixel, convolve with 20\\\" FWHM\" << endl;\n cerr << endl;\n cerr << name << \" -F /mnt/blast_pol/map_maker_data/ -f 732000 -l 736704 -C 500 -L -B \"\" -h 0.3 -t -6 -d -o \\\\!test -A 7.385:-25.8:250:250:500:500\" << endl;\n cerr << \" test map for naivepol\" << endl;\n exit(0);\n}\n\nstring to_lower(string s) {\n transform(s.begin(), s.end(), s.begin(), (int(*)(int))std::tolower);\n return s;\n}\n\n\nchar* ShellExpand(const char* argument)\n{\n char* ptr = NULL;\n wordexp_t expansion;\n\n /* shell expand the path, if necessary */\n if (wordexp(argument, &expansion, 0) != 0) {\n cerr << \"unable to expand file path\" << endl;\n exit(0);\n }\n\n if (expansion.we_wordc > 1) {\n cerr << \"cannot handle multiple expansion of \" << argument << endl;\n exit(0);\n }\n\n ptr = strdup(expansion.we_wordv[0]);\n\n /* clean up */\n wordfree(&expansion);\n\n return ptr;\n}\n\nint main(int argc, char *argv[])\n{\n const string data_etc = ShellExpand(DATA_DIR) + string(\"/etc/\");\n\n int retval;\n \n string filename = \"\";\n int fframe = 0;\n int lframe = -1;\n int nframes = -1;\n\n string fits = \"\";\n bool save = false;\n bool gauss_fit = false;\n bool map_rel_source = false;\n bool map_astrometry = false;\n bool telescope_coordinates = false;\n bool use_pointing_flags = false;\n bool use_bolo_flags = false;\n bool bolo_despike = false;\n bool galactic_coord = false;\n bool altaz_coord = false;\n bool weight_from_file = false;\n bool calibrate = false;\n bool calpulse = false;\n double source_ra = -100.0;\n double source_dec = -100.0;\n double crpix_x = -100.0;\n double crpix_y = -100.0;\n \n double smooth_angle = -1.0;\n double map_size = DEG2RAD(14.0/60.0);\n int npix_x = 0;\n int npix_y = 0;\n double pixel_size = ASEC2RAD(10.0);\n double highpassfrq = -1.0;\n double d_pitch = 0.0;\n double d_yaw = 0.0;\n string bolo_suffix = BOLO;\n string flag_suffix = FLAG;\n string calpulse_suffix = CALP;\n string pointing_suffix = POINTING;\n string offs_filename = data_etc+ShellExpand(SCOFFSFILE);\n int tod_offs = TOD_OFFS;\n \n const string bolo_table_filename = data_etc+BOLO_TABLE;\n BoloInfo binfo((char *)bolo_table_filename.c_str());\n \n list<range_t>::const_iterator irg;\n list<range_t> range;\n\n list<string>::const_iterator ich;\n list<string> channel;\n \n while ( (retval = getopt(argc, argv, \"F:f:l:y:n:o:c:s:A:r:C:p:B:K:O:P:D:h:t:LmTkedgGwx\")) != -1) {\n switch (retval) {\n case 'F':\n filename = ShellExpand(optarg);\n break;\n case 'f':\n fframe = atoi(optarg);\n break;\n case 'l':\n lframe = atoi(optarg);\n break;\n case 'n':\n nframes = atoi(optarg);\n break;\n case 'y':\n channel.push_back(optarg);\n break;\n case 'C':\n if(strncmp(optarg, \"500\", 3) == 0) channel = binfo.b500;\n else if(strncmp(optarg, \"350\", 3) == 0) channel = binfo.b350;\n else if(strncmp(optarg, \"250\", 3) == 0) channel = binfo.b250;\n break;\n case 'o': \n save = true;\n fits = optarg;\n break;\n case 'g':\n gauss_fit = true;\n break;\n case 'c':\n smooth_angle = atof(optarg);\n break;\n case 'p':\n pixel_size = ASEC2RAD(atof(optarg));\n break;\n case 's':\n if(sscanf(optarg, \"%lf:%lf:%lf\", &source_ra, &source_dec, &map_size) != 3) Usage(argv[0]);\n source_ra *= M_PI/12.0;\n source_dec *= M_PI/180.0;\n map_size *= M_PI/180.0;\n map_rel_source = true;\n break;\n case 'A':\n if(sscanf(optarg, \"%lf:%lf:%lf:%lf:%d:%d\", &source_ra, &source_dec, &crpix_x, &crpix_y, &npix_x, &npix_y) != 6) \n\tUsage(argv[0]);\n source_ra *= M_PI/12.0;\n source_dec *= M_PI/180.0;\n map_astrometry = true;\n break;\n case 'r':\t\t\t\t\t\n range_t rtmp;\n if(sscanf(optarg, \"%d:%d\", &rtmp.f0, &rtmp.nf) != 2) Usage(argv[0]);\n range.push_back(rtmp);\n break;\n case 'B':\n bolo_suffix = optarg;\n break;\n case 'K':\n flag_suffix = optarg;\n break;\n case 'P':\n pointing_suffix = optarg;\n break;\n case 'L':\n altaz_coord = true;\n break;\n case 'O':\n offs_filename = ShellExpand(optarg);\n break;\n case 'D':\n if(sscanf(optarg, \"%lf:%lf\", &d_yaw, &d_pitch) != 2) Usage(argv[0]);\n d_yaw *= M_PI/180.0/3600.0;\n d_pitch *= M_PI/180.0/3600.0;\n break;\n case 'T':\n telescope_coordinates = true;\n break;\n case 'd':\n bolo_despike = true;\n break;\n case 'k':\n use_bolo_flags = true;\n break; \n case 'e':\n use_pointing_flags = true;\n break; \n case 'G':\n galactic_coord = true;\n break; \n case 'h':\n highpassfrq = atof(optarg);\n break;\n case 'w':\n weight_from_file = true;\n break;\n case 'x':\n calibrate = true;\n break;\n case 't':\n tod_offs = atoi(optarg);\n break;\n case 'm':\n calpulse = true;\n calpulse_suffix = CALP;\n break;\n }\n }\n \n if(filename[0] == 0) Usage(argv[0]);\n if(channel.size() == 0) Usage(argv[0]);\n if(range.size() == 0) {\n if(lframe == -1) {\n if(nframes == -1) nframes = GetFrames(filename) - fframe;\n lframe = fframe + nframes - 1;\n } else {\n nframes = lframe - fframe + 1;\n }\n range_t rtmp;\n rtmp.f0 = fframe; rtmp.nf = nframes;\n range.push_back(rtmp);\n }\n\n cerr << \"Reading... \" << endl;\n\n for(irg = range.begin(); irg != range.end(); irg++) {\n cerr << \"\\tfrom frame: \" << irg->f0 << \" to frame: \" << irg->f0 + irg->nf - 1 ;\n cerr << \" (\" << irg->nf << \").\" << endl;\n }\n\n cerr << \" Using bolos: \" << bolo_suffix << endl;\n cerr << \" Pointing: \" << pointing_suffix << endl;\n cerr << \" BoloTable: \" << bolo_table_filename << endl;\n cerr << \" StarCameraOffset: \" << offs_filename << endl;\n cerr << \" Using pointing flags: \" << ((use_pointing_flags) ? \"YES\" : \"NO\") << endl;\n if(use_bolo_flags)\n cerr << \" BoloFlags: \" << flag_suffix << endl;\n\n Map map;\n Data* Yaw; \n Data* Pitch;\n Data* Roll;\n Data* Yaw_r;\n Data* Pitch_r;\n Data* Roll_r;\n char* PFlag = NULL;\n\n irg = range.begin();\n map.Info(filename, irg->f0, irg->nf, binfo.Color(*(channel.begin())));\n \n if(map_rel_source) {\n int type = (galactic_coord) ? MAP_IS_GAL : MAP_IS_RADEC;\n map.OpenPol(pixel_size, source_ra, source_dec, map_size, type);\n } else if(map_astrometry) {\n int type = (galactic_coord) ? MAP_IS_GAL : MAP_IS_RADEC;\n map.OpenPol(pixel_size, source_ra, source_dec, crpix_x, crpix_y, npix_x, npix_y, type);\n } else {\n cerr << \"You must define a map opening method.\" << endl;\n Usage(argv[0]);\n }\n\n cerr << \"Binning map ... \" << endl;\n for(irg = range.begin(); irg != range.end(); irg++) {\n\n // Polarization angle = 2 * (theta-chi) - ro_roll + [0 1]*!pi/2 + PA\n Data* AngPol = new Data(filename, string(\"POT_HWPR\"), irg->f0, irg->nf);\n *AngPol = 4.0*M_PI*(ZERO_COLD_ENC - (*AngPol)); // 2 * (theta-theta0); chi has yet to be implemented\n AngPol->ReGrid(20);\n cerr << \"Reading Pointing Solution ... \" << flush;\n if(galactic_coord) {\n Yaw = new Data(filename, string(\"GLON_\") + pointing_suffix, irg->f0, irg->nf);\n Pitch = new Data(filename, string(\"GLAT_\") + pointing_suffix, irg->f0, irg->nf);\n Roll = new Data(filename, string(\"GPHI_\") + pointing_suffix, irg->f0, irg->nf);\n *Yaw *= M_PI/180.0;\n *Pitch *= M_PI/180.0;\n *Roll *= M_PI/180.0;\n } else if (altaz_coord) {\n Yaw = new Data(filename, string(\"AZ\"), irg->f0, irg->nf);\n Pitch = new Data(filename, string(\"EL\"), irg->f0, irg->nf);\n Roll = new Data(Yaw->Lo(), Yaw->Hi(), 0.0);\n\n Data *Lst = new Data(filename, string(\"LST\"), irg->f0, irg->nf);\n Data *Lat = new Data(filename, string(\"LAT\"), irg->f0, irg->nf);\n\n *Yaw *= M_PI/180.0;\n *Pitch *= M_PI/180.0;\n *Roll *= M_PI/180.0;\n *Lst *= M_PI/12.0;\n *Lat *= M_PI/180.0;\n\t\n double ra_temp, dec_temp;\n for (int k = Yaw->Lo(); k <= Yaw->Hi(); k++) {\n\tRaDec((*Yaw)[k], (*Pitch)[k], (*Lat)[k / 20], (*Lst)[k / 20], &ra_temp, &dec_temp); //LST and LAT are slow channels\n\t(*Yaw)[k] = ra_temp;\n\t(*Pitch)[k] = dec_temp;\n (*Roll)[k] = Pa((*Yaw)[k], (*Pitch)[k], (*Lst)[k / 20], (*Lat)[k / 20]);\n }\n\n delete Lst;\n delete Lat;\n\n } else {\n Yaw = new Data(filename, string(\"RA_\") + pointing_suffix, irg->f0, irg->nf);\n Pitch = new Data(filename, string(\"DEC_\") + pointing_suffix, irg->f0, irg->nf);\n Roll = new Data(filename, string(\"PHI_\") + pointing_suffix, irg->f0, irg->nf);\n *Yaw *= M_PI/12.0;\n *Pitch *= M_PI/180.0;\n *Roll *= M_PI/180.0;\n } \n\n *AngPol += *Roll; // Add Roll to polarization angle.(if PA > 0 CCW and roll angle > 0 CW)\n // Parallactic angle = the angle as seen from the target between zenith and NCP, measured positive westward of meridian\n\n if(use_pointing_flags) {\n string flag = \"FLAG_\" + pointing_suffix;\n PFlag = new char [Yaw->Elements()];\n get_data(filename, irg->f0, 0, Yaw->Elements(), PFlag, flag, UInt8);\n }\n\n Yaw_r = new Data(Yaw->Lo(), Yaw->Hi());\n Pitch_r = new Data(Yaw->Lo(), Yaw->Hi());\n Roll_r = new Data(Yaw->Lo(), Yaw->Hi());\n \n cerr << \"done.\" << endl;\n \n for(ich = channel.begin(); ich != channel.end(); ich++) {\n cerr << \"Reading channel \" << setw(6) << *ich << \"... \" << flush;\n Data* Bolo = new Data(filename, *ich + bolo_suffix, irg->f0, irg->nf);\n char *Flag = new char [Bolo->Elements()];\n \n if(use_bolo_flags) {\n\tstring flag = to_lower(*ich)+flag_suffix;\n\tget_data(filename, irg->f0, 0, Bolo->Elements(), Flag, flag, UInt8);\n } else {\n\tmemset(Flag, 0, Bolo->Elements());\n }\n\n if(use_pointing_flags) {\n\tfor(int idx = 0; idx < Bolo->Elements(); idx++)\n\t Flag[idx] |= PFlag[idx];\n }\n\n if(bolo_despike) {\n \tcerr << \"despiking... \";\n\tBolo->CRDespike(Flag, 4.5, 4.0, 5.0, 100);\n\tBolo->FillSpike(Flag);\n }\n\n Flag -= Bolo->Lo();\n\n if(highpassfrq > 0.0) {\n\t\n\tcerr << \"PoliSub... \"<< flush;\n\tVector* X = new Vector(Bolo->Lo(), Bolo->Hi(), 0.0);\n\tdouble* Y = new double [5];\n\tdouble x;\n\tint idx;\n\n\tfor(idx = X->Lo(); idx <= X->Hi(); idx++) (*X)[idx] = (double)idx/(double)X->Elements();\n\tpolyfit(X->Store(), Bolo->Store(), Bolo->Elements(), 5, Y, Flag);\n\t\n\tfor(idx = Bolo->Lo(); idx <= Bolo->Hi(); idx++) {\n\t x = (*X)[idx];\n\t (*Bolo)[idx] -= (((Y[4]*x + Y[3])*x +Y[2])*x + Y[1])*x + Y[0];\n\t}\n\tdelete X;\n\tdelete Y;\n }\n\n if(calpulse) {\n\tcerr << \"CalPulse... \" << flush;\n\tstring calp = to_lower(*ich)+calpulse_suffix;\n\n\tData *CP = new \tData(filename, calp, irg->f0, irg->nf);\n\tfor(int idx = Bolo->Lo(); idx <= Bolo->Hi(); idx++)\n\t (*Bolo)[idx] *= (*CP)[idx/FAST_PER_SLOW];\n\tdelete CP;\n }\n\n if(highpassfrq > 0.0) {\n\tcerr << \"prepare fft... \" << flush; \n\tBolo->PrepareFFTVectorExtrap(0);\n //Bolo->PrepareFFTVector(100); // **LORENZO** 100 is the number of frames read before and after for padding\n\tcerr << \"highpassing... \" << flush; \n\tBolo->HighPass(highpassfrq);\n\tBolo->RecoverFFTVector();\n }\n\n if(calibrate) {\n\tcerr << \"calibrating... \" << flush;\n\tBolo->Calibrate( -binfo.Resp(*ich) , 0.0);\n } else {\n\tBolo->Calibrate(-1.0, 0.0);\n }\n\n cerr << \"Rotating PS... \" << flush;\n double bs_yaw, bs_pitch;\n SCOffset(binfo.Color(*ich), irg->f0, bs_yaw, bs_pitch, offs_filename.c_str());\n binfo.SCOffset(bs_pitch+d_pitch, bs_yaw+d_yaw); \n\n binfo.Rotate(*ich, *Yaw, *Pitch, *Roll, *Yaw_r, *Pitch_r, *Roll_r);\n \n double weight = (weight_from_file) ? 1.0/binfo.Noise(*ich) : 1.0;\n\n cerr << \"binning (w = \" << weight << \") ... \" << flush;\n //map.ChannelAdd(*Bolo, Flag, *Yaw_r, *Pitch_r, *Roll_r, tod_offs, telescope_coordinates, weight);\n *AngPol += binfo.Ang(*ich)*M_PI/180.0; // Add detector grid angle (as per bolotable) to polarization angle.\n //cerr << binfo.Ang(*ich)*M_PI/180.0 << endl;\n map.ChannelAddPol(*Bolo, *AngPol, Flag, *Yaw_r, *Pitch_r, *Roll_r, tod_offs, telescope_coordinates, weight);\n\n cerr << \"done.\" << endl; \n \n delete[] Flag;\n delete Bolo;\n }\n\n delete AngPol;\n\n if (use_pointing_flags) delete[] PFlag;\n delete Yaw; delete Pitch; delete Roll;\n delete Yaw_r; delete Pitch_r; delete Roll_r;\n }\n map.ClosePol();\n\n cerr << \"Variance in the map : \" << map.Variance(ASEC2RAD(300)) << endl;\n\n if(smooth_angle > 0.0) {\n cerr << \"Convolving whith a gaussian of \" << smooth_angle << \" arcsec fwhm\\n\";\n map.Convolve(ASEC2RAD(smooth_angle));\n }\n\n if(save) {\n cerr << \"Writing to fits: \" << fits << endl;\n map.WriteToFitsPol(fits, SAVE_FLUX);\n map.WriteToFitsPol(fits, SAVE_Q);\n map.WriteToFitsPol(fits, SAVE_U);\n map.WriteToFitsPol(fits, SAVE_NOISE);\n map.WriteToFitsPol(fits, SAVE_NOISE_Q);\n map.WriteToFitsPol(fits, SAVE_NOISE_U);\n map.WriteToFitsPol(fits, SAVE_HITS);\n }\n\n if(gauss_fit) {\n Vector param;\n GaussFit(map, param, 10);\n \n double fwhm = 2.354*sqrt(1.0/param[2]);\n\n double x_c = param[0];\n double y_c = param[1];\n\n map.xy2tp(x_c, y_c);\n tp2s(x_c, y_c, map.XiC(), map.EtaC());\n \n cerr << \"Gaussian fit paramenters x0 y0 fwhm Amp offs | xi0 eta0 fwhm flux\\n\";\n cout << param[0] << \" \" << param[1] << \" \" << fwhm << \" \" << param[3] << \" \" << param[4] << \" \";\n cout << \" | \" ;\n cout << RAD2DEG(x_c) << \" \" << RAD2DEG(y_c) << \" \" << RAD2ASEC(fwhm*map.XScale()) << \" \";\n cout << map.Flux(1.5*fwhm) << endl;\n\n if(1) {\n int idx;\n double arg;\n ofstream outtxt;\n outtxt.open(\"gfit_yaw.dat\");\n for(idx = map.Rlo(); idx <= map.Rhi(); idx++) {\n outtxt << map[idx][(int)nearbyint(param[1])] << \" \";\n\targ = 0.5 * (SQR(idx-param[0]) + SQR((int)param[1]-param[1])) * param[2];\n\touttxt << param[3]*exp(-arg) + param[4] << \" \"; \n\touttxt << map.Hits(idx, (int)nearbyint(param[1])) << \" \"; \n\touttxt << map.Sd(idx, (int)nearbyint(param[1])) << endl; \n }\n\n outtxt.close();\n outtxt.open(\"gfit_pitch.dat\");\n for(idx = map.Clo(); idx <= map.Chi(); idx++) {\n\touttxt << map[(int)nearbyint(param[0])][idx] << \" \";\n\targ = 0.5 * (SQR((int)param[0]-param[0]) + SQR(idx-param[1])) * param[2];\n\touttxt << param[3]*exp(-arg) + param[4] << \" \";\n\touttxt << map.Hits((int)nearbyint(param[0]), idx) << \" \"; \n\touttxt << map.Sd((int)nearbyint(param[0]), idx) << endl; \n }\n outtxt.close();\n }\n \n \n }\n \n \n\n return 0;\n}\n" }, { "alpha_fraction": 0.6845169067382812, "alphanum_fraction": 0.7112922072410583, "avg_line_length": 23.514286041259766, "blob_id": "47adbb8157c35e53a864310e9e68d69bf8eb306e", "content_id": "9bf92dcde0c9812160c09a48b0d06891ad2ff05b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 860, "license_type": "no_license", "max_line_length": 98, "num_lines": 35, "path": "/stars/code/parameters/general.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef PARAMETERS__GENERAL_H\n#define PARAMETERS__GENERAL_H\n\n#include \"group.h\"\n#include <string>\n\nnamespace Parameters\n{\n class General;\n}\n\nclass Parameters::General: public Group\n{\n public:\n General( std::string stars_absolute_dir);\n void add_bypass_with_blobs();\n void load(int argc, char* argv[]);\n\n std::string stars_dir;\n static const unsigned int max_num_bypass_blobs = 100;\n static const unsigned int max_exposure_time_cs = 128;\n\n\tstatic const int image_width = 1392; // These are assumed defaults -- They are probably not right\n\tstatic const int image_height = 1040;\n\tstatic const int image_depth = 16384;\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.6689655184745789, "alphanum_fraction": 0.6712643504142761, "avg_line_length": 24.52941131591797, "blob_id": "d86542fb50bc9dbf2a216f09be7a97774ea12a5c", "content_id": "1dc45d61945b199d94f5558ef0ee56a5e866de4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 435, "license_type": "no_license", "max_line_length": 61, "num_lines": 17, "path": "/sedpy/replacetables", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nDATABASE=spider\nDESCRIPTION_FILE=spider.txt\n\n[ -d out ] || mkdir out\n./sedparser.py $DESCRIPTION_FILE\nif [ \"$?\" -eq 0 ]\nthen\n [ -d /data/sedweb ] || mkdir /data/sedweb\n [ -d /data/sedweb/out ] || mkdir /data/sedweb/out\n cp out/* /data/sedweb/out/\n echo \"**Enter sql root password to update tables**\"\n mysql $DATABASE -u root -p < replacetables.sql > sqlout.txt\nelse\n echo \"Parsing failed, not updating database\"\nfi\n\n" }, { "alpha_fraction": 0.5516756176948547, "alphanum_fraction": 0.5686876177787781, "avg_line_length": 32.405982971191406, "blob_id": "f5dfdf1e3c7d424bea9299e9d4bf21cdce548bea", "content_id": "b603f41a218ce9a408123c0a3eb363e888f97b27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7819, "license_type": "no_license", "max_line_length": 122, "num_lines": 234, "path": "/stars/code/solving/statistician.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"statistician.h\"\n#include <boost/format.hpp>\n#include \"../shared/image/stats.h\"\n#include \"../shared/image/status.h\"\n#include \"../shared/image/leveled.h\"\n#include \"../shared/general/main_settings.h\"\n#include \"../tools/stats.h\"\n#include \"../parameters/manager.h\"\n#include \"logger.h\"\n\nusing namespace Solving;\n\n#define shared_stats (*(Shared::Image::stats_solver_for_main.w))\n#define shared_status (*(Shared::Image::status_solver_for_main.w))\n#define shared_leveled (*(Shared::Image::leveled.w))\n#define shared_main_settings (*(Shared::General::main_settings_main_for_solver.r))\n\nStatistician::Statistician(Parameters::Manager& params):\n saturation_limit(params.general.try_get(\"solver.general.saturation_limit\", 1.0))\n{\n cell_size = 16;\n}\n\nvoid Statistician::get_cell_stats(Shared::Image::Raw& raw, int icell, int jcell,\n double& mean, double& stdev, int& num_saturated)\n{\n bool pixel_saturated = false;\n int num_pixels_in_cell = cell_size*cell_size;\n if (num_pixels_in_cell < 1) {\n return;\n }\n mean = 0;\n num_saturated = 0;\n for (int j = jcell*cell_size; j < (jcell+1)*cell_size; j++) {\n for (int i = icell*cell_size; i < (icell+1)*cell_size; i++) {\n mean += raw.pixels[j*raw.width+i];\n pixel_saturated = false;\n for (unsigned int k=0; k<raw.num_exposures && k<raw.max_num_exposures && !pixel_saturated; k++) {\n if (raw.separate_buffers[k][j*raw.width+i] >= raw.single_depth-1) {\n pixel_saturated = true;\n }\n }\n if (pixel_saturated) {\n num_saturated++;\n }\n }\n }\n mean /= num_pixels_in_cell;\n stdev = 0;\n for (int j = jcell*cell_size; j < (jcell+1)*cell_size; j++) {\n for (int i = icell*cell_size; i < (icell+1)*cell_size; i++) {\n stdev += pow(mean - raw.pixels[j*raw.width+i], 2);\n }\n }\n if (num_pixels_in_cell >= 2) {\n stdev /= double(cell_size*cell_size-1.0);\n }\n stdev = sqrt(stdev);\n}\n\nvoid Statistician::get_stats(Shared::Image::Raw& raw)\n{\n using namespace Shared::Image;\n using std::vector;\n\n double mean=0, stdev=0;\n int num_saturated = 0;\n int num_saturated_in_cell = 0;\n vector <double> means;\n vector <double> noises;\n vector <double> gains;\n int num_icells = int( floor( double(raw.width) /double(cell_size) ) );\n int num_jcells = int( floor( double(raw.height)/double(cell_size) ) );\n for (int jcell=0; jcell < num_jcells; jcell++) {\n for (int icell=0; icell < num_icells; icell++) {\n get_cell_stats(raw, icell, jcell, mean, stdev, num_saturated_in_cell);\n num_saturated += num_saturated_in_cell;\n means.push_back(mean);\n noises.push_back(stdev);\n if (mean > 100 && num_saturated_in_cell == 0) {\n gains.push_back(pow(stdev, 2) / mean);\n }\n }\n }\n sort(noises.begin(), noises.end());\n sort(gains.begin(), gains.end());\n if (means.size() > 0) {\n shared_stats.mean_known = true;\n shared_stats.mean = get_mean(means);\n }\n else {\n shared_stats.mean_known = false;\n shared_stats.mean = 0.0;\n }\n if (noises.size() > 0){\n shared_stats.noise_known = true;\n shared_stats.noise = noises[int(floor(noises.size()/2.0))];\n }\n else{\n shared_stats.noise_known = false;\n shared_stats.noise = 1.0;\n }\n shared_stats.num_pixels_saturated = num_saturated;\n shared_stats.fraction_pixels_saturated = double(num_saturated) / double(raw.width*raw.height);\n\n double gain_ideal = 4096./100000.;\n unsigned int bottom_index = int(floor(gains.size()*0.0/6.0));\n unsigned int top_index = int(floor(gains.size()*1.0/6.0));\n double total = 0;\n if (top_index - bottom_index > 100) {\n for (unsigned int i=bottom_index; i<top_index; i++) {\n total += gains[i];\n }\n shared_stats.gain_known = true;\n shared_stats.gain = total/double(top_index-bottom_index);\n } else {\n shared_stats.gain_known = false;\n shared_stats.gain = gain_ideal;\n }\n shared_stats.gaindb = 20*log10( shared_stats.gain / gain_ideal );\n stats_solver_for_main.share();\n\n if (shared_stats.fraction_pixels_saturated > saturation_limit) {\n shared_status.stage = Status::done;\n shared_status.reason_for_being_done = Status::saturated;\n }\n}\n\nvoid Statistician::get_default_display_bounds(Shared::Image::Raw& raw, double& default_lower_bound, double& default_width)\n{\n int lower_bound = 0;\n int upper_bound = raw.depth;\n unsigned int* histogram = new unsigned int[raw.depth];\n int histogram_skip = 4;\n int num_pixels = raw.width * raw.height / (histogram_skip * histogram_skip);\n {\n for (int i=0; i<raw.depth; i++){\n histogram[i] = 0;\n }\n unsigned short pixel;\n for (int j = 0; j < raw.height; j+=histogram_skip) {\n for (int i = 0; i < raw.width; i+=histogram_skip) {\n pixel = raw.pixels[j*raw.width+i];\n if (pixel >= 0 && pixel < raw.depth) {\n histogram[pixel]++;\n }\n }\n }\n\n lower_bound = 0;\n int sum = 0;\n while ((sum < 0.01*num_pixels) && (lower_bound < raw.depth)) {\n sum += histogram[lower_bound];\n lower_bound++;\n }\n lower_bound -= 2;\n\n upper_bound = raw.depth-1;\n sum = 0;\n while ((sum < 0.01*num_pixels) && (upper_bound >= 0)) {\n sum += histogram[upper_bound];\n upper_bound--;\n }\n upper_bound += 2;\n\n if (upper_bound <= lower_bound) {\n lower_bound = 0;\n upper_bound = raw.depth;\n }\n }\n delete [] histogram;\n default_lower_bound = double(lower_bound);\n default_width = double(upper_bound - lower_bound)*1.3;\n}\n\nvoid Statistician::make_display_data(Shared::Image::Raw& raw)\n{\n volatile double value = 0;\n double lower_bound = 0;\n double width = raw.depth;\n get_default_display_bounds(raw, lower_bound, width);\n\n double brightness = shared_main_settings.display_image_brightness;\n logger.log(format(\"using image brightness %f\") % brightness);\n if (brightness > 1.0) {\n double upper_bound = lower_bound + width;\n width *= brightness;\n lower_bound = upper_bound - width;\n }\n if (brightness > 0.0 && brightness < 1.0) {\n width /= brightness;\n }\n\n int k=0;\n for (int j=0; j<raw.height; j++) {\n for (int i=0; i<raw.width; i++) {\n value = raw.pixels[j*raw.width+i];\n value = floor(255.0*(value - lower_bound)/width);\n if (value < 0.0) {\n value = 0.0;\n }\n if (value > 255.0) {\n value = 255.0;\n }\n for (k=0; k<3; k++) {\n shared_leveled.pixels[(j*raw.width+i)*4+k] = (char) value;\n }\n shared_leveled.pixels[(j*raw.width+i)*4+3] = (char) 255;\n }\n }\n\n shared_leveled.counter_stars = raw.counter_stars;\n shared_leveled.valid = true;\n Shared::Image::leveled.share();\n}\n\nvoid Statistician::print_stats()\n{\n if (shared_stats.mean_known) {\n logger.log(format(\"stats: mean: %0.2f\") % shared_stats.mean);\n }\n if (shared_stats.noise_known) {\n logger.log(format(\"stats: noise: %0.2f\") % shared_stats.noise);\n }\n if (shared_stats.gain_known) {\n logger.log(format(\"stats: gain: %0.2f gaindb: %0.2f\") % shared_stats.gain % shared_stats.gaindb);\n }\n}\n\n" }, { "alpha_fraction": 0.4526241719722748, "alphanum_fraction": 0.4660091698169708, "avg_line_length": 35.8701286315918, "blob_id": "8c5b37e20d4fb7844ce02a77a2a650f222eca26b", "content_id": "78d00669bdc6e2f60955930aa2bdf66c4e643f62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2839, "license_type": "no_license", "max_line_length": 77, "num_lines": 77, "path": "/defricher/defricher_utils.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * defricher_utils.h: \n *\n * This software is copyright (C) 2013-2014 Seth Hillbrand\n *\n * This file is part of defricher, created for the BLASTPol Project.\n *\n * defricher 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 2 of the License, or\n * (at your option) any later version.\n *\n * defricher 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 defricher; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Apr 6, 2015 by Seth Hillbrand\n */\n\n#ifndef DEFRICHER_UTILS_H_\n#define DEFRICHER_UTILS_H_\n\n#include <stdbool.h>\n#include <blast.h>\n\n#define defricher_fatal(fmt,...) \\\n do { \\\n bprintf(fatal, fmt, ##__VA_ARGS__); \\\n }while(0)\n#define defricher_tfatal(fmt,...) \\\n do { \\\n bprintf(tfatal, fmt, ##__VA_ARGS__); \\\n }while(0)\n#define defricher_err(fmt,...) \\\n do { \\\n bprintf(err, fmt, ##__VA_ARGS__); \\\n }while(0)\n#define defricher_info(fmt,...) \\\n do { \\\n bprintf(info, fmt, ##__VA_ARGS__); \\\n }while(0)\n#define defricher_warn(fmt,...) \\\n do { \\\n bprintf(warning,fmt, ##__VA_ARGS__); \\\n }while(0)\n#define defricher_startup(fmt,...) \\\n do { \\\n bprintf(startup, fmt, ##__VA_ARGS__); \\\n }while(0)\n#define defricher_nolog(fmt,...) \\\n do { \\\n bprintf(nolog,fmt, ##__VA_ARGS__); \\\n }while(0)\n#define defricher_mem(fmt,...) \\\n do { \\\n bprintf(mem, fmt, ##__VA_ARGS__); \\\n }while(0)\n#define defricher_dbg(fmt,...) \\\n do { \\\n bprintf(dbg, fmt, ##__VA_ARGS__); \\\n }while(0)\n\n#define defricher_strerr(fmt,...) \\\n do { \\\n berror(err, fmt, ##__VA_ARGS__); \\\n }while(0)\n\nint defricher_mkdir_file(const char *m_filename, bool m_file_appended);\n\n\n#endif /* DEFRICHER_UTILS_H_ */\n" }, { "alpha_fraction": 0.7440601587295532, "alphanum_fraction": 0.7446616291999817, "avg_line_length": 35.53845977783203, "blob_id": "ec6f037675ebd30262ab677056ba9f65b11d53aa", "content_id": "37e1045f068507395fb1993bdd58edac4f30db94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3325, "license_type": "no_license", "max_line_length": 90, "num_lines": 91, "path": "/starcam/blobimage.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//extend CSBIGImg to add blob finding functionality\n\n#ifndef BLOBIMAGE_H\n#define BLOBIMAGE_H\n\n#include <string>\n#include <sys/time.h>\n#include \"csbigimg.h\"\n#include \"csbigimgdefs.h\"\n#include \"frameblob.h\"\n#include \"camconfig.h\"\n#include \"camstruct.h\"\n#include \"pyramid.h\"\n\n//flag for compiling with use of lost in space star matching\n#define USE_PYRAMID 0\n\n/**\n\t@author Steve Benton <[email protected]>\n*/\n\nclass BlobImage : public CSBIGImg\n{\nprivate:\n\tframeblob m_cBlob; //object for blob finding in the image\n\tstring m_sBadpixFilename; //name of file containing coordinates of bad pixels on CCD\n\ttimeval m_sImageStartTime; //privde higher resolution timestamps than CSBIGImg does\n\tunsigned long m_nTimeError;//upper bound on imprecision of image start time (us)\n\tstring m_sCamID; //identifies camera that took picture\n\tbool m_bIsChanged; //allows viewer to tell if contents have changed\n\tunsigned long int m_iFrame;//frame number\n#if USE_PYRAMID\t\n\tPyramid m_cPyramid; //object for pattern recognition\n\tdouble m_dMatchTol; //tolerance value (focal plane distance) for pattern matchcing\n\tdouble m_dPlatescale; //conversion factor between pixel position and radians of sky\n#endif\n\t\npublic:\n\tBlobImage(BlobImageConfigParams params = defaultImageParams);\n\tBlobImage(int height, int width, BlobImageConfigParams params = defaultImageParams);\n ~BlobImage();\n\t\n\t//overridden (or overloaded) parent methods\n\tvoid Init(BlobImageConfigParams params = defaultImageParams);\n\tMY_LOGICAL AllocateImageBuffer(int height, int width);\n\tvoid DeleteImageData();\n\tSBIG_FILE_ERROR OpenImage(const char *pFullPath);\n\tvoid SetImageStartTime(void); //set start time to current time\n\tvoid SetImageStartTime(timeval* ref); //sets start time and error based on ref\n\ttimeval GetImageStartTime(void) { return m_sImageStartTime; }\n\t\n\t//image processing methods\n//\tvoid InitFrameblob(); //no longer needed\n\tvoid copyImageFrom(const unsigned short*);\n\tSBIG_FILE_ERROR FixBadpix(string filename);\n\tint findBlobs();\n\tint crapifyImage();\n\tint highPassFilter(int box_size, int n_boxes);\n#if USE_PYRAMID\n\tint matchStars(solution_t **sol);\n#endif\n\t\n\t//accessors\n\tframeblob* getFrameBlob(void) { return &m_cBlob; }\n\tstring getBadpixFilename(void) { return m_sBadpixFilename; }\n\tvoid setBadpixFilename(string name) { m_sBadpixFilename = name; }\n\tvoid setBadpixFilename(const char* name);\n\tvoid setCameraID(string in_id) { m_sCamID = in_id; }\n\tstring getCameraID(void) { return m_sCamID; }\n\tbool isChanged() { return m_bIsChanged; }\n\tvoid setChanged(bool flag) { m_bIsChanged = flag; }\n\tvoid setFrameNum(unsigned long int frameNum) { m_iFrame = frameNum; }\n#if USE_PYRAMID\n\tPyramid* getPyramid() { return &m_cPyramid; }\n\tvoid setMatchTol(double tol) { m_dMatchTol = tol; }\n\tdouble getMatchTol(void) { return m_dMatchTol; }\n\tvoid setPlatescale(double scale) { m_dPlatescale = scale; }\n\tdouble getPlatescale(void) { return m_dPlatescale; } \n#endif\n\t\n\tStarcamReturn* createReturnStruct(StarcamReturn* arg);\n\t\n\t//functions to help in testing the blob finder\n\tvoid drawBox(double x, double y, double side, int bnum, bool willChange=true);\n\tstring createFilename();\n\tstring createDirectory(string root, int boxflag);\n\tSBIG_FILE_ERROR SaveImageIn(string root=\"/usr/local/starcam/pictures/\", int boxflag=0);\n\t\n};\n\n#endif\n" }, { "alpha_fraction": 0.5730389952659607, "alphanum_fraction": 0.5833724737167358, "avg_line_length": 26.649351119995117, "blob_id": "fc5834d62e54d000bd58cb640c6b37a8eb40bff0", "content_id": "dd48b615ad7c509a7f5f326cae1388b6252fa8fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4258, "license_type": "no_license", "max_line_length": 136, "num_lines": 154, "path": "/linklistcheck/linklistcheck.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n#include <errno.h>\n#include <netdb.h>\n#include <signal.h>\n#include <string.h>\n#include <time.h>\n#include <unistd.h>\n#include <inttypes.h>\n#include <getopt.h>\n\n#include <sys/socket.h>\n#include <sys/syslog.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/stat.h>\n#include <dirent.h>\n\n#include <netinet/in.h>\n#include <arpa/inet.h>\n\n#include <pthread.h> // threads\n#include <openssl/md5.h>\n\n#include \"blast.h\"\n#include \"calibrate.h\"\n#include \"channels_tng.h\"\n#include \"linklist.h\"\n#include \"linklist_compress.h\"\n#include \"linklist_writer.h\"\n#include \"linklist_connect.h\"\n\nint main(int argc, char *argv[])\n{\n if (argc == 1) {\n printf(\"Need to specify linklist directory\\n\");\n return 1;\n }\n char * linklistdir = argv[1];\n\n\tint i, r;\n\n int show_sizes = 1;\n int show_all_tlms = 1;\n int show_checksums = 1;\n char specific_channel[80] = {0};\n\n for (i = 2; i < argc; i++) {\n if (strcmp(argv[i], \"--sizes-only\") == 0) {\n show_all_tlms = 0;\n } else if (strcmp(argv[i], \"--channel\") == 0) {\n sprintf(specific_channel, \"%s\", argv[++i]); \n show_checksums = 0;\n } else {\n printf(\"Unrecognized option \\\"%s\\\"\\n\", argv[i]);\n exit(2);\n }\n }\n\n uint8_t format_serial[MD5_DIGEST_LENGTH] = {0};\n linklist_t *ll_array[MAX_NUM_LINKLIST_FILES] = {NULL};\n superframe_entry_t * superframe_list = NULL;\n\n channels_initialize(channel_list);\n\n printf(\"Superframe size = %d, count = %d, serial = %.8lx\\n\", superframe->size, superframe->n_entries, superframe->serial);\n\n write_superframe_format(superframe, \"superframe.txt\");\n superframe_t * testsf = parse_superframe_format(\"superframe.txt\"); \n write_superframe_format(testsf, \"superframe.txt\");\n printf(\"Parsed size = %d, count = %d serial = %.8lx\\n\", testsf->size, testsf->n_entries, testsf->serial);\n\n\tif (load_all_linklists(superframe, linklistdir, ll_array, 0) < 0)\n {\n printf(\"Unable to load linklists\\n\");\n exit(3);\n }\n generate_housekeeping_linklist(linklist_find_by_name(ALL_TELEMETRY_NAME, ll_array), ALL_TELEMETRY_NAME);\n printf(\"Generate hk linklist\\n\");\n\n // check the parser and writer\n\tlinklist_t * ll = ll_array[0]; \n r = 0;\n while (ll) {\n printf(\"Checking %s...\\n\", ll->name);\n write_linklist_format(ll, ll->name);\n linklist_t * temp_ll = parse_linklist_format_opt(superframe, ll->name, LL_NO_AUTO_CHECKSUM);\n printf(\"0x%.4x == 0x%.4x\\n\", *(uint32_t *) ll->serial, *(uint32_t *) temp_ll->serial);\n\n delete_linklist(temp_ll);\n ll = ll_array[++r];\n } \n\n\n printf(\"------------------------ LINKLIST START ------------------------\\n\");\n\n\tll = ll_array[0]; \n r = 0;\n\n\twhile (ll)\n\t{\n\t\tint runningsum = 0;\n\n\t\tprintf(\"\\n================LINKLIST \\\"%s\\\"==================\\n\",ll->name);\n\n\t // print result\n if (show_all_tlms) {\n\t\t\tfor (i=0;i<ll->n_entries;i++)\n\t\t\t{\n\t\t\t\tif (ll->items[i].tlm != NULL)\n\t\t\t\t{\n if ((strlen(specific_channel) > 0) && (strncmp(specific_channel, ll->items[i].tlm->field, strlen(specific_channel)))) {\n continue;\n }\n\n\t\t\t\t\tprintf(\"name = %s, start = %d, blk_size = %d, num = %d, comp_type = %s, sf_start = %d, sf_skip = %d\\n\",\n\t\t\t\t\t (ll->items[i].tlm->field[0]) ? ll->items[i].tlm->field : \"BLOCK\", ll->items[i].start, \n\t\t\t\t\t ll->items[i].blk_size, ll->items[i].num, (ll->items[i].comp_type == NO_COMP) ? \"NONE\" : compRoutine[ll->items[i].comp_type].name, \n\t\t\t\t\t ll->items[i].tlm->start, ll->items[i].tlm->skip);\n\t\t\t\t\trunningsum += ll->items[i].blk_size;\n\t\t\t\t}\n\t\t\t\telse if (show_checksums)\n\t\t\t\t{\n\t\t\t\t\tprintf(\"//--------CHECKSUM (over %d bytes)---------//\\n\",runningsum);\n\t\t\t\t\trunningsum = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprintf(\"Number of data blocks: %d\\n\",ll->num_blocks);\n\n\t\t\tfor (i=0;i<ll->num_blocks;i++)\n\t\t\t{\n\t\t\t\tprintf(\"%s, id=%d, alloc_size = %d\\n\",ll->blocks[i].name, ll->blocks[i].id,ll->blocks[i].alloc_size);\n\t\t\t}\n }\n if (show_sizes) {\n\n\t\t\tprintf(\"Serial: \");\n\t\t\tfor (i=0;i<MD5_DIGEST_LENGTH;i++) printf(\"%x\",ll->serial[i]);\n\t\t\tprintf(\"\\n\");\n\t\t\tprintf(\"n_entries = %d, blk_size = %d\\n\",ll->n_entries,ll->blk_size);\n\t\t\tll = ll_array[++r];\n }\n\t}\n\n\n printf(\"\\n===================GENERAL INFO====================\\n\");\n\n\tprintf(\"allframe_size = %d\\n\",superframe->allframe_size);\n\n}\n" }, { "alpha_fraction": 0.6428571343421936, "alphanum_fraction": 0.6535714268684387, "avg_line_length": 15.352941513061523, "blob_id": "aaae5294135ba3ec391e5d1da9ca95fbfe6e384e", "content_id": "d38140fcaaa6a14ef0b2f346a7f63583ee7a2966", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 280, "license_type": "no_license", "max_line_length": 67, "num_lines": 17, "path": "/xymap/Makefile", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "CPP = g++\nLIBS = -lgetdata++ #-lX11 -lXpm -lblas -lblast -lmatpack -lcfitsio \nCPPFLAGS = -O3 -Wall -g\n\n\nall: lockinmap\n\nlockinmap: lockinmap.o\n\t$(CPP) $(CPPFLAGS) lockinmap.o $(LIBS) -o lockinmap\n\nlockinmap.o : iirfilter.h\n\nclean:\n\trm -f lockinmap *.o\n\t\npurge: clean\n\trm -f *~\n\t\n" }, { "alpha_fraction": 0.6918553709983826, "alphanum_fraction": 0.7206010222434998, "avg_line_length": 36.33333206176758, "blob_id": "1271f8789e48564f4b10fe19b0dee27eaa209f0e", "content_id": "64bdb7e68eb020e680f050967af8f0beb2d5628f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4592, "license_type": "no_license", "max_line_length": 108, "num_lines": 123, "path": "/liblinklist/linklist_compress.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * linklist_compress.h: \n *\n * This software is copyright \n * (C) 2015-2018 University of Toronto, Toronto, ON\n *\n * This file is part of the SuperBIT project, modified and adapted for BLAST-TNG.\n *\n * linklist 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 2 of the License, or\n * (at your option) any later version.\n *\n * linklist 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Jan 25, 2018 by Javier Romualdez\n */\n\n\n#ifndef LINKLIST_COMPRESS_H_\n#define LINKLIST_COMPRESS_H_\n\n#include <inttypes.h>\n#include \"linklist.h\"\n\n#define ALLFRAME_SERIAL 0x42424242\n#define LINKLIST_FILESAVE_DIR \"/data/etc/downloaded_files\"\n#define LINKLIST_MISSED_PKTS_FILE LINKLIST_FILESAVE_DIR \"/missed_pkts.log\"\n\n#define BLOCK_FILE_MASK 0x80000000\n#define BLOCK_PREEMPT_ID 0x1badface\n\n#define BLOCK_OVERRIDE_CURRENT 0x01\n#define BLOCK_NO_DOWNSTREAM_FILE 0x02\n#define BLOCK_PREEMPT_FILE 0x04\n\n#define STREAM_MUST_SEND 0x01\n#define STREAM_DONT_CLEAR 0x02\n\n#ifdef __cplusplus\n\nextern \"C\"{\n\n#endif\n\nenum dataCompressTypes {\n FIXED_PT_16BIT, // fixed point 16 bit compression\n FIXED_PT_32BIT, // fixed point 32 bit compression\n MEAN_FLOAT_DELTA_8BIT, // 8 bit derivative compression\n MEAN_FLOAT_8BIT, // 8 bit moving average compression\n\n NUM_COMPRESS_TYPES\n};\n\nstruct dataCompressor {\n int id;\n char name[80];\n int (*compressFunc) (uint8_t *, linkentry_t *, uint8_t *);\n int (*decompressFunc) (uint8_t *, linkentry_t *, uint8_t *);\n};\n\nextern struct dataCompressor compRoutine[NUM_COMPRESS_TYPES+1];\n\n#define COMPRESS(x) (int)x, #x\n#define LL_CHANNEL_DATA(_chan) _chan->var\n\n#define LL_IGNORE_CHECKSUM 0x80\nint compress_linklist(uint8_t *, linklist_t *, uint8_t *);\nint compress_linklist_opt(uint8_t *, linklist_t *, uint8_t *, uint32_t, int);\nint compress_linklist_internal(uint64_t, linklist_t *, uint8_t *);\nint compress_linklist_internal_opt(uint64_t, linklist_t *, uint8_t *, uint32_t, int);\ndouble decompress_linklist(uint8_t *, linklist_t * , uint8_t *);\ndouble decompress_linklist_opt(uint8_t *, linklist_t *, uint8_t *, uint32_t, int);\ndouble decompress_linklist_internal(uint64_t, linklist_t * , uint8_t *);\ndouble decompress_linklist_internal_opt(uint64_t, linklist_t *, uint8_t *, uint32_t, int);\n\nuint8_t * allocate_superframe(superframe_t *);\nint write_allframe(uint8_t *, superframe_t *, uint8_t *);\nint read_allframe(uint8_t *, superframe_t *, uint8_t *);\nvoid packetize_block(struct block_container * , uint8_t *);\nvoid depacketize_block(struct block_container * , uint8_t *);\nunsigned int linklist_blocks_queued(linklist_t *);\nvoid packetize_stream(struct stream_container * , uint8_t *);\nvoid depacketize_stream(struct stream_container * , uint8_t *);\nint assign_file_to_stream(stream_t *, char *, int, int);\nint assign_file_to_streamlist(stream_t **, char *, int, int);\nint remove_file_from_stream(stream_t *);\nint remove_file_from_streamlist(stream_t **);\nint seek_file_in_stream(stream_t *, int, int);\nint seek_file_in_streamlist(stream_t **, int, int);\nvoid write_next_stream(stream_t *, uint8_t *, unsigned int, unsigned int);\nvoid write_next_streamlist(stream_t **, uint8_t *, unsigned int, unsigned int);\nvoid stop_current_stream(stream_t *);\nvoid stop_current_streamlist(stream_t **);\n\nblock_t * block_find_by_name(linklist_t *, char *);\nint linklist_send_file_by_block(linklist_t *, char *, char *, int32_t, int);\nint linklist_send_file_by_block_ind(linklist_t *, char *, char *, int32_t, int, unsigned int, unsigned int);\n\nstream_t * stream_find_by_name(linklist_t *, char *);\nstream_t ** linklist_get_streamlist(linklist_t **, char *);\nint linklist_assign_file_to_stream(linklist_t *, char *, char *, int, int);\nint linklist_remove_file_from_stream(linklist_t *, char *);\nint linklist_seek_file_in_stream(linklist_t *, char *, int, int);\nvoid linklist_write_next_stream(linklist_t *, char *, uint8_t *, unsigned int, unsigned int);\nvoid linklist_stop_current_stream(linklist_t *, char *);\n\nFILE * fpreopenb(char *);\nuint8_t randomized_buffer(uint8_t *, unsigned int, unsigned int);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* LINKLIST_H_ */\n" }, { "alpha_fraction": 0.695305585861206, "alphanum_fraction": 0.6988485455513, "avg_line_length": 18.789474487304688, "blob_id": "1ca0ebf56d5f0abc43b68058ff7c727373f8b89f", "content_id": "e32eae53665cf5e619105cd62a3ea6633345bf92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1130, "license_type": "no_license", "max_line_length": 83, "num_lines": 57, "path": "/stars/code/solving/solver.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__SOLVER_H\n#define SOLVING__SOLVER_H\n\n#include <boost/thread/thread.hpp>\n#include \"finding/finder.h\"\n#include \"matching/matcher.h\"\n#include \"refitting/refitter.h\"\n#include \"statistician.h\"\n#include \"autofocus_helper.h\"\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Solving\n{\n class Solver;\n}\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n}\n\nclass Solving::Solver\n{\n public:\n Solver(Parameters::Manager& params, Shared::Image::Raw& solvers_working_image);\n void solve();\n void solve_thread_function();\n void wait_for_quit();\n\n private:\n Shared::Image::Raw* working_image;\n Finding::Finder blob_finder;\n Matching::Matcher pattern_matcher;\n Statistician statistician;\n Refitting::Refitter refitter;\n AutofocusHelper autofocus_helper;\n bool quit_after_one;\n double quit_after_one_delay;\n\n boost::thread solve_thread;\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.6417771577835083, "alphanum_fraction": 0.6464294195175171, "avg_line_length": 29.92086410522461, "blob_id": "c25217c796ea167366c6454d9e65a3e0fa0f0e8e", "content_id": "386b7d53a200121012a0130c1e107a8c9404159f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4300, "license_type": "no_license", "max_line_length": 99, "num_lines": 139, "path": "/stars/code/star_camera.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"star_camera.h\"\n#include <string>\n#include \"preprocessor.h\"\n#include \"imaging/camera_empty.h\"\n#include \"imaging/camera_windows.h\"\n#include \"imaging/camera_filesystem.h\"\n#include \"parameters/manager.h\"\n#include \"networking/network_manager.h\"\n#include \"displaying/manager.h\"\n#include \"housekeeping/housekeeper.h\"\n#include \"logger_main.h\"\n#include \"tools/quick_cout.h\"\n#include \"shared/update.h\"\n#include \"shared/general/main_settings.h\"\n#include \"shared/general/shutdown.h\"\n#include \"shared/general/quit.h\"\n\nusing Main::logger;\n#define shared_main_settings (*(Shared::General::main_settings_net_for_main.r))\n#define shared_shutdown (*(Shared::General::shutdown_for_main.r))\n\nStarCamera::StarCamera(Parameters::Manager& params, Shared::Image::Raw& solvers_working_image):\n lens(params), solver(params, solvers_working_image)\n{\n update_period = 1.0 / params.general.try_get(\"main.update_frequency\", 20.0);\n framerate_counter = 0;\n std::string input_device_str = params.general.try_get(\"imaging.camera.device\", string(\"none\"));\n input_device = input_device_none;\n if (input_device_str == \"camera_windows\") {\n input_device = input_device_camera_windows;\n }\n if (input_device_str == \"camera_filesystem\") {\n input_device = input_device_camera_filesystem;\n }\n camera = NULL;\n}\n\nvoid StarCamera::pick_camera(Parameters::Manager& params)\n{\n switch (input_device) {\n case input_device_camera_windows:\n #if PREPROCESSOR_USING_CAMERA\n camera = new Imaging::CameraWindows(params, &io_card);\n #endif\n break;\n case input_device_camera_filesystem:\n camera = new Imaging::CameraFilesystem(params);\n logger.log(\"using camera_filesystem\");\n break;\n case input_device_none:\n camera = NULL;\n break;\n }\n}\n\nvoid StarCamera::update_framerate()\n{\n if (framerate_timer.started()) {\n framerate_counter++;\n if (framerate_timer.time() > 5.0) {\n double framerate = double(framerate_counter) / framerate_timer.time();\n //logger.log(format(\"framerate is %d\")%framerate);\n framerate_timer.start();\n framerate_counter = 0;\n }\n } else {\n framerate_timer.start();\n framerate_counter = 0;\n }\n}\n\nvoid StarCamera::set_thread_priority()\n{\n #ifdef WIN32\n DWORD thread_priority;\n thread_priority = GetThreadPriority(GetCurrentThread());\n SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);\n thread_priority = GetThreadPriority(GetCurrentThread());\n logger.log(format(\"main has thread priority %i\")%thread_priority);\n #endif\n}\n\nvoid StarCamera::update_main()\n{\n Shared::update(Shared::ThreadNames::main);\n if (shared_shutdown.shutdown_now) {\n Shared::General::quit = true;\n }\n logger.update();\n}\n\nvoid StarCamera::run(Parameters::Manager& params)\n{\n Displaying::DisplayManager display_manager(params);\n display_manager.draw();\n\n\tio_card.dmm_initialize();\n\n pick_camera(params);\n Housekeeping::Housekeeper housekeeper(params, &io_card);\n Networking::NetworkManager network_manager;\n\n //set_thread_priority();\n\n display_manager.draw();\n update_timer.start();\n display_timer.start();\n while (!Shared::General::quit) {\n if (update_timer.time() > update_period) {\n double time_passed_since_last_update = update_timer.time();\n update_timer.start();\n update_main();\n display_manager.process_events();\n display_manager.update_zoom(time_passed_since_last_update);\n housekeeper.update();\n }\n if (display_timer.time() > shared_main_settings.display_period) {\n update_framerate();\n display_timer.start();\n display_manager.draw();\n }\n usleep(2000);\n }\n display_manager.draw();\n\n if (camera) {\n camera->wait_for_quit();\n }\n solver.wait_for_quit();\n lens.wait_for_quit();\n network_manager.wait_for_quit();\n display_manager.wait_for_quit();\n}\n\n" }, { "alpha_fraction": 0.5885328650474548, "alphanum_fraction": 0.6053962707519531, "avg_line_length": 23.70833396911621, "blob_id": "618b76aa1834150c798230cf63a458014798df9f", "content_id": "ae0ad9e74973afb347a3efb27395c869815f7c88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 593, "license_type": "no_license", "max_line_length": 82, "num_lines": 24, "path": "/starcam/focusstruct.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* focusstruct.h\n * struct of blob positions and fluxes during autoFocus (in mycam.cpp)\n */\n\n\n#ifndef FOCUSSTRUCT_H\n#define FOCUSSTRUCT_H\n\n#ifdef __cplusplus\n#include <string>\n#include <sys/time.h>\n\nusing namespace std;\n\nstruct focusStruct {\n\tint focpos;\t\t\t//distance to infinity when the image was taken\n\tint numblobs; //number of blobs found (or 15 if larger than 15)\n\tint flux[15]; //flux of blob\n\tdouble x[15]; //position of centroid\n\tdouble y[15]; //...\n};\n#endif //__cplusplus\n\n#endif //FOCUSSTRUCT_H\n" }, { "alpha_fraction": 0.6053921580314636, "alphanum_fraction": 0.6264005899429321, "avg_line_length": 27.549999237060547, "blob_id": "05f6a1b1035aa1c924a407962a749b0dce640526", "content_id": "dc3538023c7f16326548dab48b58ca4a07a2f59a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2856, "license_type": "no_license", "max_line_length": 125, "num_lines": 100, "path": "/owl/POwlAnimation.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"POwlAnimation.h\"\n#include \"PMainWindow.h\"\n#include \"PMdiArea.h\"\n\n#include <QMainWindow>\n#include <QPainter>\n\nPOwlAnimation::POwlAnimation(int font_height) : _lastNFrames(0), _nUpdates(0), _label(new QLabel), _stage(0), _H(font_height)\n{\n _moveThingy=QPoint(-1,-1);\n for(int i=0;i<4;i++) {\n _pixMaps[i] = QIcon(\":/icons/icons/Owl\"+QString::number(i)+\".svg\").pixmap(_H*4,_H*4);\n\n }\n _pixMaps[4]=QIcon(\":/icons/icons/Owl-empty.svg\").pixmap(_H*4,_H*4);\n\n _label->setPixmap(_pixMaps[4]);\n setLayout(new QHBoxLayout);\n layout()->addWidget(_label);\n layout()->setAlignment(_label,Qt::AlignCenter);\n}\n\nPOwlAnimation::~POwlAnimation()\n{\n PMainWindow* np=PMainWindow::me;\n np->_owlList.removeOne(this);\n}\n\nvoid POwlAnimation::gdUpdate(GetData::Dirfile* dirFile,int lastNFrames, int dt)\n{\n\n if (dt < 2) {\n if(lastNFrames!=_lastNFrames) {\n _nUpdates++;\n if (_nUpdates>1) {\n //qsrand(dirFile->NFrames());\n _stage=qrand()%4;\n } else {\n _stage = 4;\n }\n _label->setPixmap(_pixMaps[_stage]);\n _lastNFrames=lastNFrames;\n }\n } else {\n _stage=-1;\n QPixmap branch = _pixMaps[4];\n\n if (_nUpdates>1) {\n QPainter p(&branch);\n p.drawText(QPoint(4,60), QString(\"%1s\").arg(dt));\n }\n _label->setPixmap(branch);\n }\n //QRect R = geometry();\n //R.setWidth(100);\n //setGeometry(R);\n}\n\nQSize POwlAnimation::sizeHint()\n{\n return QSize(95,120);\n}\n\nconst int& POwlAnimation::stage() const\n{\n return _stage;\n}\n\n\nvoid POwlAnimation::mouseMoveEvent(QMouseEvent *ev)\n{\n if (PMainWindow::me->mouseInactive()) return;\n\n if(ev->buttons()&Qt::LeftButton&&_moveThingy!=QPoint(-1,-1)) {\n QPoint p1=parentWidget()->mapFromGlobal(ev->globalPos()); //setGeometry refers to parent's (x,y)\n setGeometry((p1.x()-_moveThingy.x())/_H*_H,(p1.y()-_moveThingy.y())/_H*_H,\n geometry().width()/_H*_H,geometry().height()/_H*_H);\n }\n}\n\n" }, { "alpha_fraction": 0.5919062495231628, "alphanum_fraction": 0.6096198558807373, "avg_line_length": 24.044368743896484, "blob_id": "193abb6da838de43c771f57cdbd006569a1588c0", "content_id": "64fdce2c7a13a2e5d8c77f4365e75aa87b659ed2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7340, "license_type": "no_license", "max_line_length": 99, "num_lines": 293, "path": "/stars/code/displaying/block.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"block.h\"\n\n#if defined(_MSC_VER)\n #include <windows.h>\n#endif\n#include <boost/lexical_cast.hpp>\n#ifndef _MSC_VER\n #include \"GL/glext.h\"\n#endif\n#include \"color.h\"\n#include \"glhelper.h\"\n\nusing namespace Displaying;\nusing std::string;\n\nBlock::Block()\n{\n current_size.w = 200;\n current_size.h = 200;\n requested_size = current_size;\n padding = 5.0;\n text_height = 20.0;\n\n color_permanent = Color(1.0, 1.0, 1.0, 1.0);\n color_temporary = Color(1.0, 1.0, 1.0, 1.0);\n color_use_temporary = false;\n\n text_scaling_permanent = 0.55;\n text_scaling_temporary = 0.55;\n text_scaling_use_temporary = false;\n\n rjust_permanent = false;\n rjust_width_permanent = 50.0;\n rjust_temporary = false;\n rjust_width_temporary = 50.0;\n rjust_use_temporary = false;\n\n change_size(140, 2*padding+1*text_height);\n\n}\n\nBlock::~Block()\n{\n}\n\nvoid Block::init(string title_, Textures& textures_)\n{\n title = title_;\n textures = &textures_;\n}\n\nvoid Block::set_title(string title_)\n{\n title = title_;\n}\n\nvoid Block::draw_text(string text, Position& pos, bool hold_temporary)\n{\n Color color = color_permanent;\n double text_scaling = text_scaling_permanent;\n bool rjust = rjust_permanent;\n double rjust_width = rjust_width_permanent;\n if (color_use_temporary) {\n color = color_temporary;\n }\n if (text_scaling_use_temporary) {\n text_scaling = text_scaling_temporary;\n }\n if (rjust_use_temporary) {\n rjust = rjust_temporary;\n rjust_width = rjust_width_temporary;\n }\n if (!hold_temporary)\n {\n color_use_temporary = false;\n text_scaling_use_temporary = false;\n rjust_use_temporary = false;\n }\n double xshift = 0.0;\n if (rjust) {\n std::pair<int, int> text_size;\n textures->font.GetStringSize(text.c_str(), &text_size);\n xshift = (rjust_width - (text_size.first * text_scaling));\n }\n textures->font.Begin(); // Bind 0\n GL::Color4f(color.values[0], color.values[1], color.values[2], color.values[3]);\n textures->font.DrawString(text, (float) text_scaling, (float) (pos.x + xshift), (float) pos.y);\n glBindTexture(GL_TEXTURE_2D, 0); // unBind 0\n}\n\nvoid Block::get_text_size(string text, double& width, double& height)\n{\n double text_scaling = text_scaling_permanent;\n if (text_scaling_use_temporary) {\n text_scaling = text_scaling_temporary;\n }\n std::pair<int, int> text_size;\n textures->font.GetStringSize(text.c_str(), &text_size);\n width = text_size.first * text_scaling;\n height = text_size.second * text_scaling;\n}\n\nvoid Block::begin_draw(Position& pos, double flip_scaling)\n{\n glPushMatrix();\n glTranslatef((GLfloat) pos.x, (GLfloat) pos.y, (GLfloat) 0.0);\n glTranslatef((GLfloat) 1.0, (GLfloat) ((1.0-flip_scaling)/2.0*height()), 0.0f);\n glScalef(1.0f, (GLfloat) flip_scaling, 1.0f);\n}\n\nvoid Block::end_draw()\n{\n glPopMatrix();\n}\n\nvoid Block::draw_border()\n{\n glDisable(GL_TEXTURE_2D);\n glPushMatrix();\n GL::Color4f(0.3, 0.3, 0.6, 1);\n glBegin(GL_LINE_LOOP);\n glVertex2f(0.0, 0.0);\n glVertex2f(0.0, (GLfloat) current_size.h);\n glVertex2f((GLfloat) current_size.w, (GLfloat) current_size.h);\n glVertex2f((GLfloat) current_size.w, 0.0);\n glEnd();\n glPopMatrix();\n glEnable(GL_TEXTURE_2D);\n}\n\nvoid Block::draw_value(DynamicValue& value, Position pos)\n{\n int width = 60;\n string str;\n if (value.known) {\n str = value.name + \": \";\n set_color(value.color, true);\n set_rjust(width, true);\n draw_text(str, pos);\n pos.x += width;\n str = value.value;\n set_color(value.color, true);\n draw_text(str, pos);\n } else {\n str = value.name + \": \";\n set_color(value.color*0.5, true);\n set_rjust(width, true);\n draw_text(str, pos);\n }\n\n}\n\nvoid Block::draw_title()\n{\n Position pos = {padding, current_size.h-padding};\n draw_text(title, pos);\n}\n\nvoid Block::set_color(Color color, bool just_once)\n{\n if (just_once) {\n color_temporary = color;\n color_use_temporary = true;\n } else {\n color_permanent = color;\n color_use_temporary = false;\n }\n}\n\nvoid Block::set_text_scaling(double scaling, bool just_once)\n{\n if (just_once) {\n text_scaling_temporary = scaling;\n text_scaling_use_temporary = true;\n } else {\n text_scaling_permanent = scaling;\n text_scaling_use_temporary = false;\n }\n}\n\nvoid Block::set_rjust(double width, bool just_once)\n{\n if (just_once) {\n rjust_temporary = true;\n rjust_width_temporary = width;\n rjust_use_temporary = true;\n } else {\n rjust_permanent = true;\n rjust_width_permanent = width;\n rjust_use_temporary = false;\n }\n}\n\nvoid Block::scale_color(double scaling)\n{\n if (color_use_temporary) {\n color_temporary.values[0] *= scaling;\n color_temporary.values[1] *= scaling;\n color_temporary.values[2] *= scaling;\n } else {\n color_permanent.values[0] *= scaling;\n color_permanent.values[1] *= scaling;\n color_permanent.values[2] *= scaling;\n }\n}\n\n\nvoid Block::apply_flip_scaling(Position& position, double flip_scaling)\n{\n glScalef(1.0f, (GLfloat) flip_scaling, 1.0f);\n //position.y += height()*(1.0 - flip_scaling)/2.0;\n position.y += 100;\n}\n\nvoid Block::change_size(Size new_size, bool slow)\n{\n change_size(new_size.w, new_size.h, slow);\n}\n\nvoid Block::change_size(double width, double height, bool slow)\n{\n requested_size.w = width;\n requested_size.h = height;\n if (!slow) {\n previous_size = requested_size;\n current_size = requested_size;\n sizing_finished = true;\n } else {\n previous_size = current_size;\n sizing_finished = false;\n sizing_timer.start();\n update_size(slow);\n }\n}\n\nvoid Block::update_size(bool slow)\n{\n if (!slow) {\n previous_size = requested_size;\n current_size = requested_size;\n sizing_finished = true;\n } else {\n double period = 0.5;\n if (sizing_timer.time() > period) {\n previous_size = requested_size;\n current_size = requested_size;\n sizing_finished = true;\n } else {\n double fraction = 1.0 - exp(-3.0*sizing_timer.time()/period) + exp(-3.0);\n current_size.w = previous_size.w + (requested_size.w-previous_size.w)*fraction;\n current_size.h = previous_size.h + (requested_size.h-previous_size.h)*fraction;\n }\n }\n}\n\nbool Block::size_update_finished()\n{\n if (sizing_finished || sizing_timer.time() > 3) {\n return true;\n }\n return false;\n}\n\ndouble Block::width()\n{\n return current_size.w;\n}\n\ndouble Block::height()\n{\n return current_size.h;\n}\n\nSize Block::size()\n{\n return current_size;\n}\n\nvoid Block::draw(Position& position, double flip_scaling)\n{\n glBindTexture(GL_TEXTURE_2D, textures->get(Textures::basic_drawing)); // Bind 1\n begin_draw(position);\n draw_border();\n draw_title();\n end_draw();\n glBindTexture(GL_TEXTURE_2D, 0); // unBind 1\n}\n\n" }, { "alpha_fraction": 0.6781609058380127, "alphanum_fraction": 0.6823406219482422, "avg_line_length": 20.75, "blob_id": "88abc8c71660ecb7064d3ee11c798d858f39210b", "content_id": "49e5cead36b474056484566bf3417698eed45b58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 958, "license_type": "no_license", "max_line_length": 73, "num_lines": 44, "path": "/stars/code/displaying/texture.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__TEXTURE_H\n#define DISPLAYING__TEXTURE_H\n\n#include <string>\n#include \"utilities.h\"\n#include \"GL/glu.h\"\n\nnamespace Displaying\n{\n class Texture;\n}\n\nclass Displaying::Texture\n{\n\n public:\n Texture();\n void init(int new_size, bool display_enabled);\n void init(bool display_enabled);\n void destroy(bool display_enabled);\n ~Texture();\n void size_to_at_least(int min_size);\n int bind_blank(int new_size, bool black);\n void bind_data(char* data, int width, int height);\n //void load_png(string file_name);\n void load_tiff(std::string file_name);\n void draw(Size size, double opacity);\n void draw(Size size);\n GLuint id;\n\n private:\n int size;\n double used_width, used_height;\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.6565656661987305, "alphanum_fraction": 0.6767676472663879, "avg_line_length": 27.238094329833984, "blob_id": "c81ca06f5022c8e5c3a80f4ab4ac01f6f8f9bd1e", "content_id": "1e983774f618f39b7bab5a983eaa84d68bf592fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 595, "license_type": "no_license", "max_line_length": 73, "num_lines": 21, "path": "/stars/code/solving/attitude.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"attitude.h\"\n#include \"../tools/angles.h\"\n\nvoid Solving::clear_solution_attitude(SolutionAttitude& attitude)\n{\n attitude.valid = false;\n attitude.ra = 0.0;\n attitude.dec = 0.0;\n attitude.roll = 0.0;\n attitude.sigma_ra = M_PI;\n attitude.sigma_dec = M_PI;\n attitude.sigma_roll = M_PI;\n attitude.sigma_pointing = M_PI;\n attitude.iplatescale = from_arcsec(9.5);\n}\n\n" }, { "alpha_fraction": 0.5706332921981812, "alphanum_fraction": 0.5741127133369446, "avg_line_length": 14.12631607055664, "blob_id": "8e4798c28b7d74a4ab3e2e8e029279e9d42507a3", "content_id": "9917512ebd1432236832ba0c519aaeebde0793d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1437, "license_type": "no_license", "max_line_length": 73, "num_lines": 95, "path": "/starcam/bloblist.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n\tbloblist.cpp\n\n\tImplementation of bloblist class\n\n*/\n\n#include \"bloblist.h\"\n\nbloblist::bloblist( int flux_in, double x_in, double y_in ) {\n flux = flux_in;\n x = x_in;\n y = y_in;\n \n type = 0;\n \n nextblob = NULL;\n prevblob = NULL;\n \n snr = 1;\n mean = 0;\n}\n\nbloblist::~bloblist() {\n}\n\n// --- Set blob properties ----------------------------------------------\n\nvoid bloblist::setflux( int flux_in ) {\n\tflux = flux_in;\n}\n\nvoid bloblist::setx( double x_in ) {\n\tx = x_in;\n}\n\nvoid bloblist::sety( double y_in ) {\n\ty = y_in;\n}\n\nvoid bloblist::settype( int type_in ) {\n\tif( (type_in >= 0) && (type_in <= 2) ) type = type_in;\n}\n\nvoid bloblist::setsnr( double snr_in ) {\n\tsnr = snr_in;\n}\n\nvoid bloblist::setmean( double mean_in ) {\n\tmean = mean_in;\n}\n\n// --- Get blob properties ----------------------------------------------\n\nint bloblist::getflux() {\n\treturn flux;\n}\n\ndouble bloblist::getx() {\n\treturn x;\n}\n\ndouble bloblist::gety() {\n\treturn y;\n}\n\nint bloblist::gettype() {\n\treturn type;\n}\n\ndouble bloblist::getsnr() {\n\treturn snr;\n}\n\ndouble bloblist::getmean() {\n\treturn mean;\n}\n\n// --- Linked list head/tail pointers -----------------------------------\n\nvoid bloblist::setnextblob( bloblist *nextblob_in ) {\n\tnextblob = nextblob_in;\n}\n\nvoid bloblist::setprevblob( bloblist *prevblob_in ) {\n\tprevblob = prevblob_in;\n}\n\nbloblist *bloblist::getnextblob() {\n\treturn nextblob;\n}\n\nbloblist *bloblist::getprevblob() {\n\treturn prevblob;\n}\n" }, { "alpha_fraction": 0.4670785963535309, "alphanum_fraction": 0.48271867632865906, "avg_line_length": 41.80165100097656, "blob_id": "5c20db8b32898e8f546b1f0caaf09a30f5c4e7ee", "content_id": "fceec650d6050380bdca3d13fdee093b0dd3f0f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5179, "license_type": "no_license", "max_line_length": 98, "num_lines": 121, "path": "/common/include/derived.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* derived.h: a list of derived channels\n *\n * This software is copyright (C) 2004-2010 University of Toronto\n *\n * This file is part mcp licensed under the GNUGeneral Public License.\n *\n * You should have received a copy of the GNU General Public License\n * along with this software; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#ifndef INCLUDE_DERIVED_H\n#define INCLUDE_DERIVED_H\n#include <stdint.h>\n\n#ifndef FIELD_LEN\n# define FIELD_LEN 32\n#endif\n#ifndef UNITS_LEN\n# define UNITS_LEN 48\n#endif\n\n#pragma pack(push, 1)\n\ntypedef struct {\n char type;\n union {\n struct { /* BITS */\n /* type Should = 'b' for bits */\n char field[FIELD_LEN]; /* Derived Channel Name */\n char source[FIELD_LEN]; /* Source Channel Name */\n char offset; /* Fisrt Bit */\n char length; /* Number of Bits */\n } bitword;\n struct { /* LINTERP */\n /* type Should = 't' for linterp */\n char field[FIELD_LEN]; /* Derived Channel Name */\n char source[FIELD_LEN]; /* Source Channel Name */\n char lut[256]; /* Look-up table filename */\n } linterp;\n struct { /* LINCOM */\n /* type Should = 'c' for lincom */\n char field[FIELD_LEN]; /* Derived Channel Name */\n char source[FIELD_LEN]; /* Source Channel Name */\n double m_c2e; /* slope */\n double b_e2e; /* intercept */\n } lincom;\n struct { /* 2 FIELD LINCOM */\n /* type Should = '2' for lincom2 */\n char field[FIELD_LEN]; /* Derived Channel Name */\n char source[FIELD_LEN]; /* Source Channel Name */\n char source2[FIELD_LEN]; /* Source Channel Name */\n double m_c2e; /* slope */\n double b_e2e; /* intercept */\n double m2_c2e; /* slope */\n double b2_e2e; /* intercept */\n } lincom2;\n struct {\n /* type Should = '#' for comment */\n char text[343]; /* comment */\n } comment;\n struct {\n /* type should be 'u' for units */\n char source[FIELD_LEN]; /* the channel we are adding metadata for */\n char quantity[UNITS_LEN]; /* the quantity -eg, \"Temperature\" */\n char units[UNITS_LEN]; /* the Units -eg \"^oC\" */\n } units;\n struct {\n /* type should be 'p' for phase */\n char field[FIELD_LEN]; /* Derived Channel Name */\n char source[FIELD_LEN]; /* Source Channel Name */\n int shift; /* Phase shift in frames */\n } phase;\n struct {\n /* type should be 'r' for reciprocal */\n char field[FIELD_LEN]; /* Derived Channel Name */\n char source[FIELD_LEN]; /* Source Channel Name */\n double dividend; /* Dividend */\n } recip;\n struct { /* MULTIPLY or DIVIDE */\n /* type '*' for multiply, '/' for divide */\n char field[FIELD_LEN]; /* Derived Channel Name */\n char source[FIELD_LEN]; /* 1st Source Channel, dividend for divide*/\n char source2[FIELD_LEN]; /* 2nd Source Channel, divisor for divide */\n } math;\n struct { /* MPLEX */\n /* type 'x' for mplex */\n char field[FIELD_LEN]; /* derived channel name */\n char source[FIELD_LEN]; /* source channel */\n char index[FIELD_LEN]; /* multiplex index channel */\n int value; /* mulitplex index value to extract */\n int max; /* max multiplex index range (0 if unknown) */\n } mplex;\n };\n} derived_tng_t;\n\ntypedef struct {\n uint32_t magic;\n uint8_t version;\n uint32_t length;\n uint32_t crc;\n derived_tng_t data[0];\n} derived_header_t;\n#pragma pack(pop)\n\n#define DERIVED_EOC_MARKER '!'\n#define LINCOM(f, s, m, b) {.type = 'c', .lincom = { f , s , m , b }}\n#define LINCOM2(f, s1, m1, b1, s2, m2, b2) {.type = '2', .lincom2 = { f, s1, s2, m1, b1, m2, b2 }}\n#define LINTERP(f, s, l) {.type = 't', .linterp = { f , s , l }}\n#define BITWORD(f, s, o, l) {.type = 'b', .bitword = { f , s , o, l }}\n#define COMMENT(c) {.type = '#', .comment = { c }}\n#define UNITS(s, q, u) {.type = 'u', .units = { s , q , u}}\n#define PHASE(f, s, p) {.type = 'p', .phase = { f, s, p }}\n#define RECIP(f, s, d) {.type = 'r', .recip = { f, s, d }}\n#define DIVIDE(f, s1, s2) {.type = '/', .math = { f, s1, s2 }}\n#define MULTIPLY(f, s1, s2) {.type = '*', .math = { f, s1, s2 }}\n#define MPLEX(f, s, i, v, m) {.type = 'x', .mplex = { f, s, i, v, m }}\n#define END_OF_DERIVED_CHANNELS {.type = DERIVED_EOC_MARKER}\n\n#endif\n" }, { "alpha_fraction": 0.6601859927177429, "alphanum_fraction": 0.6766694784164429, "avg_line_length": 21.53333282470703, "blob_id": "85261e53dbf7efb810705f21d19a1fc371e1438f", "content_id": "5f35aca7ef1d88dad2e0cfcd1d511e291cc69d21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2366, "license_type": "no_license", "max_line_length": 80, "num_lines": 105, "path": "/common/include/frameread.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* frameread: reads mcp-style framefiles\n *\n * This software is copyright (C) 2004 University of Toronto\n * \n * frameread 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 2 of the License, or\n * (at your option) any later version.\n * \n * frameread 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 frameread; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n#ifndef FRAMEREAD_H\n#define FRAMEREAD_H\n\n#define FR_DONE 0 /* nothing left in file and not in persist mode */\n#define FR_MORE_IN_FILE 1 /* current chunk has increased in size */\n#define FR_NEW_CHUNK 2 /* current chunk done, new chunk found */\n#define FR_CURFILE_CHANGED 3 /* no new chunk, curfile points to new file */\n\n/* Don't use PATH_MAX. It isn't. */\n#define FR_PATH_MAX 8192\n\n#include <dirent.h> /* for MAXNAMELEN on BSD */\n#ifndef NAME_MAX\n#ifdef MAXNAMELEN\n#define NAME_MAX MAXNAMELEN\n#else\n#define NAME_MAX 255 /* iunno */\n#endif\n#endif\n\n#define GPB_LEN (FR_PATH_MAX * 4)\n#define FILENAME_LEN (FR_PATH_MAX + NAME_MAX + 1)\n\n#ifdef HAVE_STDINT_H\n#include <stdint.h>\ntypedef uint16_t chunkindex_t;\n#elif SIZEOF_UNSIGNED == 4\ntypedef unsigned chunkindex_t;\n#elif SIZEOF_UNSIGNED_SHORT == 4\ntypedef uint16_t chunkindex_t;\n#elif SIZEOF_UNSIGNED_LONG == 4\ntypedef unsigned long chunkindex_t;\n#else\ntypedef unsigned chunkindex_t;\n#endif\n\nunsigned long long GetFrameFileSize(\n const char*,\n int\n );\n\nint GetNextChunk(\n char*,\n int\n );\n\nchar* GetSpecFile(\n char*,\n const char*,\n const char*\n );\n\nvoid PathSplit_r(\n const char*,\n char*,\n char*\n );\n\nint ReconstructChannelLists(\n const char*,\n const char*\n );\n\nlong int SetStartChunk(\n long int,\n char*,\n int\n );\n\nint StaticSourcePart(\n char*,\n const char*,\n chunkindex_t*,\n int\n );\n\nint StreamToNextChunk(\n int,\n char*,\n int,\n int*,\n const char*,\n char*\n );\n\n#endif\n" }, { "alpha_fraction": 0.5507853627204895, "alphanum_fraction": 0.5832460522651672, "avg_line_length": 18.46938705444336, "blob_id": "b5a30e835f46b0425c310b990d9e974f27cbebcf", "content_id": "65990ee2ccbf26906746efaacccb53eab688b929", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 956, "license_type": "no_license", "max_line_length": 73, "num_lines": 49, "path": "/stars/code/displaying/color.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"color.h\"\n\nusing namespace Displaying;\n\nColor::Color()\n{\n values[0] = 1.0;\n values[1] = 1.0;\n values[2] = 1.0;\n values[3] = 1.0;\n}\n\nColor::Color(double r, double g, double b, double a)\n{\n values[0] = r;\n values[1] = g;\n values[2] = b;\n values[3] = a;\n}\n\nColor& Color::operator=(const Color &rhs)\n{\n if (this != &rhs) {\n values[0] = rhs.values[0];\n values[1] = rhs.values[1];\n values[2] = rhs.values[2];\n values[3] = rhs.values[3];\n }\n return *this;\n}\n\nColor& Color::operator*=(const double &scale)\n{\n values[0] *= scale;\n values[1] *= scale;\n values[2] *= scale;\n return *this;\n}\n\nconst Color Color::operator*(const double &scale) const\n{\n return Color(*this) *= scale;\n}\n\n" }, { "alpha_fraction": 0.5644586086273193, "alphanum_fraction": 0.578720211982727, "avg_line_length": 31.793846130371094, "blob_id": "ee8f04e1179b0f0b9654853f0869b04287fce438", "content_id": "33c7b989bc3673c543c766341179d08e64f91c4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10658, "license_type": "no_license", "max_line_length": 182, "num_lines": 325, "path": "/defricher/defricher.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* defricher: converts BLASTPol-TNG framefiles into dirfiles\n *\n * This file is copyright (C) 2015 Seth Hillbrand\n *\n * Based on previous work copyright (C) 2004-2005, 2013 D. V. Wiebe\n * Also (C) 2005-2010 Matthew Truch.\n * \n * This file is part of defricher.\n * \n * defricher 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 2 of the License, or\n * (at your option) any later version.\n * \n * defricher 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 defricher; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#ifdef HAVE_CONFIG_H\n# include \"defricher_config.h\"\n#endif\n\n#include <libgen.h>\n#include <stdlib.h> /* ANSI C std library (atoi, exit, realpath) */\n#include <signal.h> /* ANSI C signals (SIG(FOO), sigemptyset, sigaddset) */\n#include <string.h> /* ANSI C strings (strcat, memcpy, &c.) */\n#include <sys/stat.h> /* SYSV stat (stat, struct stat S_IS(FOO)) */\n#include <unistd.h> /* UNIX std library (fork, chdir, setsid, usleep &c.) */\n#include <wordexp.h> /* POSIX-shell-like word expansion (wordexp) */\n#include <errno.h>\n#include <stdio.h>\n#include <execinfo.h>\n#include <signal.h>\n\n#include <glib.h>\n#include <mosquitto.h>\n#include <getdata.h>\n\n#include <blast.h>\n#include <blast_time.h>\n#include <channels_tng.h>\n\n\n#include \"defricher.h\"\n#include \"defricher_writer.h\"\n#include \"defricher_netreader.h\"\n\nchar **remaining_args = NULL;\n\nstatic GOptionEntry cmdline_options[] =\n{\n { \"autoreconnect\", 0, 0, G_OPTION_ARG_NONE, &rc.auto_reconnect, \"Automatically reconnect when dropped\", NULL},\n { \"daemonize\", 0, 0, G_OPTION_ARG_NONE, &rc.daemonise, \"Fork to the background on startup\", NULL},\n { \"force\", 'f', 0, G_OPTION_ARG_NONE, &rc.force_stdio, \"Overwrite destination file if exists\", NULL},\n { \"linklist\", 'l', 0, G_OPTION_ARG_STRING, &rc.linklist_file, \"Use NAME in linklist mode. Will only receive data specified in linklist\", NULL},\n { \"output-dirfile\", 'o', 0, G_OPTION_ARG_STRING, &rc.output_dirfile, \"Use NAME as the output Dirfile name\", NULL},\n { G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &remaining_args, \"<SOURCE> <TELEMETRY (lab/pilot/highrate/biphase)> [OUTPUT DIRFILE]\", NULL},\n {NULL}\n};\n\n\n/* state structs */\nstruct ri_struct ri;\nstruct rc_struct rc;\n\nstruct Fifo fifo_data[RATE_END] = {{0}};\n\nstatic const double TC = 1.7;\nstatic pthread_t writer_thread;\nstatic pthread_t reader_thread;\n\nvoid log_handler(const gchar* log_domain, GLogLevelFlags log_level,\n const gchar* message, gpointer user_data)\n{\n printf(\"%s\\n\", message);\n}\n\nvoid shutdown_defricher(int sig) {\n fprintf(stderr, \"Shutting down Defricher on signal %d\", sig);\n ri.writer_done = true;\n ri.reader_done = true;\n}\n\nvoid segv_handler(int sig) {\n void *array[10];\n size_t size;\n \n // get void*'s for all entries on the stack\n size = backtrace(array, 10);\n \n // print out all the frames to stderr\n fprintf(stderr, \"Error: signal %d:\\n\", sig);\n backtrace_symbols_fd(array, size, STDERR_FILENO);\n exit(1);\n}\n\n/// TODO: Test ability to write to output location on startup\n\nstatic char* resolve_output_dirfile(char* m_dirfile, const char* parent)\n{\n char *parent_part;\n char dirfile_part[FR_PATH_MAX];\n char path[FR_PATH_MAX];\n wordexp_t expansion;\n\n /* is dirfile a relative path? if so, we don't have to do anything */\n if (m_dirfile[0] != '/' && m_dirfile[0] != '~') {\n /* check string sizes */\n if (strlen(parent) + 1 + strlen(m_dirfile) >= FR_PATH_MAX)\n bprintf(fatal, \"output m_dirfile path is too long\\n\");\n\n strcpy(path, parent);\n strcat(path, m_dirfile);\n }\n else\n strcpy(path, m_dirfile);\n\n if (path[strlen(path) - 1] == '/')\n path[strlen(path) - 1] = 0;\n\n /* shell expand the path, if necessary */\n if (wordexp(path, &expansion, 0) != 0)\n berror(fatal, \"unable to expand output dirfile path `%s'\", path);\n\n if (expansion.we_wordc > 1)\n bprintf(fatal, \"cannot handle multiple expansion of `%s'\", path);\n\n /* repace path with the output of the shell expansion */\n strcpy(path, expansion.we_wordv[0]);\n\n wordfree(&expansion);\n\n /* realpath() will fail with a non-existant path, so strip off dirfile name */\n parent_part = dirname(path);\n\n /* canonicalise the path */\n if (realpath(parent_part, m_dirfile) == NULL)\n berror(fatal, \"cannot resolve output m_dirfile path `%s'\", parent_part);\n\n /* add back m_dirfile name */\n if (m_dirfile[strlen(m_dirfile) - 1] != '/')\n strcat(m_dirfile, \"/\");\n strcat(m_dirfile, dirfile_part);\n\n return m_dirfile;\n}\n\nstatic void defricher_defaults(struct rc_struct* m_rc)\n{\n asprintf(&(m_rc->dest_dir), \"/data/defricher\");\n asprintf(&(m_rc->source), \"fc1\");\n asprintf(&(m_rc->telemetry), \"lab\");\n asprintf(&(m_rc->symlink_name), \"/data/etc/defricher.cur\");\n}\n\n\nvoid parse_cmdline(int argc, char** argv, struct rc_struct* m_rc)\n{\n\n GError *error = NULL;\n GOptionContext *context;\n\n context = g_option_context_new(\"\");\n g_option_context_set_summary(context, \"Converts BLASTPol-TNG framefiles from SOURCE into dirfiles\\ndefricher <SOURCE> <TELEMETRY (lab/pilot/highrate/biphase)> [OUTPUT DIRFILE]\");\n g_option_context_set_description(context, \"Please report any errors or bugs to <[email protected]>\");\n g_option_context_add_main_entries(context, cmdline_options, NULL);\n\n if (!g_option_context_parse (context, &argc, &argv, &error))\n {\n g_error(\"option parsing failed: %s\\n\", error->message);\n exit (1);\n }\n\n /* fix up daemon mode */\n if (m_rc->daemonise)\n m_rc->persist = m_rc->silent = m_rc->force_stdio = 1;\n\n if (remaining_args && remaining_args[0]) {\n g_debug(\"Source is %s\", remaining_args[0]);\n free(m_rc->source);\n asprintf(&(m_rc->source), \"%s\", remaining_args[0]);\n\n if (remaining_args[1]) {\n g_debug(\"Telemetry is %s\", remaining_args[1]);\n char *possible_telemetries[4] = {\"lab\", \"highrate\", \"biphase\", \"pilot\"};\n bool valid_telemetry = false;\n for(int i = 0; i < 4; ++i)\n {\n if(!strcmp(possible_telemetries[i], remaining_args[1]))\n {\n free(m_rc->telemetry);\n asprintf(&(m_rc->telemetry), \"%s\", remaining_args[1]);\n valid_telemetry = true;\n break;\n }\n }\n if (!valid_telemetry) {\n g_error(\"Wrong argument for telemetry: %s. Please choose between lab, highrate, pilot, or biphase\", remaining_args[1]);\n }\n }\n\n if (remaining_args[2]) {\n g_debug(\"Dest is %s\", remaining_args[2]);\n free(m_rc->dest_dir);\n asprintf(&(m_rc->dest_dir), \"%s\", remaining_args[2]);\n if (m_rc->dest_dir[strlen(m_rc->dest_dir) - 1] == '/') m_rc->dest_dir[strlen(m_rc->dest_dir) - 1] = '\\0';\n }\n }\n\n /* Fix up output_dirfile, if present */\n if (m_rc->output_dirfile) {\n m_rc->output_dirfile = resolve_output_dirfile(m_rc->output_dirfile, m_rc->dest_dir);\n }\n\n g_option_context_free(context);\n}\n\n\n\nint main(int argc, char** argv)\n{\n struct timeval now;\n double delta;\n double ofr = 200;\n double ifr = 200;\n double nf = 0;\n\n /* Load the hard-coded defaults if not over-written by command line */\n defricher_defaults(&rc);\n\n /* fill rc struct from command line */\n parse_cmdline(argc, argv, &rc);\n\n if (rc.daemonise) {\n int pid;\n FILE* stream;\n\n /* Fork to background */\n if ((pid = fork()) != 0) {\n if (pid == -1)\n g_critical(\"unable to fork to background\");\n\n if ((stream = fopen(\"/var/run/decomd.pid\", \"w\")) == NULL)\n g_error(\"unable to write PID to disk\");\n else {\n fprintf(stream, \"%i\\n\", pid);\n fflush(stream);\n fclose(stream);\n }\n printf(\"PID = %i\\n\", pid);\n exit(0);\n }\n rc.force_stdio = 0;\n\n /* Daemonise */\n chdir(\"/\");\n freopen(\"/dev/null\", \"r\", stdin);\n freopen(\"/dev/null\", \"w\", stdout);\n freopen(\"/dev/null\", \"w\", stderr);\n setsid();\n }\n\n /* Start */\n\n /* Initialise things */\n ri.read = ri.wrote = ri.old_total = ri.lw = ri.frame_rate_reset = 0;\n ri.tty = 0;\n delta = 1;\n gettimeofday(&ri.last, &rc.tz);\n\n /* set up signal masks */\n signal(SIGBUS, segv_handler);\n signal(SIGILL, segv_handler);\n\n signal(SIGINT, shutdown_defricher);\n signal(SIGQUIT, shutdown_defricher);\n\n /* Spawn client/reader and writer */\n writer_thread = defricher_writer_init();\n reader_thread = netreader_init(rc.source, rc.telemetry);\n\n /* Main status loop -- if we're in silent mode we skip this entirely and\n * just wait for the read and write threads to exit */\n if (!rc.silent)\n do {\n if (!ri.tty) {\n gettimeofday(&now, &rc.tz);\n delta = (now.tv_sec - ri.last.tv_sec) + (now.tv_usec - ri.last.tv_usec) / 1000000.;\n nf = (ri.wrote - ri.lw);\n ri.last = now;\n ri.lw = ri.wrote;\n ofr = nf / TC + ofr * (1 - delta / TC);\n nf = (ri.read - ri.lr);\n ri.lr = ri.read;\n ifr = nf / TC + ifr * (1 - delta / TC);\n if (ri.frame_rate_reset) {\n ri.frame_rate_reset = 0;\n ofr = 200;\n ifr = 200;\n }\n#ifndef DEBUG\n printf(\"%s R:[%i] %.*f W:[%i] %.*f Hz\\r\", rc.output_dirfile, ri.read,\n \t\t(ifr > 100) ? 1 : (ifr > 10) ? 2 : 3, ifr,\n \t\tri.wrote,\n \t\t(ofr > 100) ? 1 : (ofr > 10) ? 2 : 3, ofr);\n fflush(stdout);\n usleep(1000);\n#endif\n }\n usleep(500000);\n } while (!ri.writer_done);\n pthread_join(reader_thread, NULL);\n pthread_join(writer_thread, NULL);\n if (!rc.silent) {\n bprintf(info, \"%s R:[%i] W:[%i] %.*f Hz\", rc.output_dirfile, ri.read, ri.wrote, (ofr > 100) ? 1 : (ofr > 10) ? 2 : 3, ofr);\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.5763443112373352, "alphanum_fraction": 0.6313176155090332, "avg_line_length": 55.61415100097656, "blob_id": "3578bbac99aa4650114d9ff2b37045fe5f7fdac0", "content_id": "5b420d98c48350913e5b06d9943f62185e2d336b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 60011, "license_type": "no_license", "max_line_length": 93, "num_lines": 1060, "path": "/blast_config/derived.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* derived.c: a list of derived channels\n *\n * This software is copyright (C) 2002-2010 University of Toronto\n *\n * This file is part of the BLAST flight code licensed under the GNU\n * General Public License.\n *\n * You should have received a copy of the GNU General Public License\n * along with this software; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n/* !XXX!!XXX!!XXX!!XXX!!XXX!! BIG ALL CAPS WARNING !!XXX!!XXX!!XXX!!XXX!!XXX!!\n *\n * IF YOU ADD, MODIFY, OR DELETE *ANY* CHANNELS IN THIS FILE YOU *MUST*\n * RECOMPILE AND RESTART THE DECOM DAEMON (DECOMD) ON ARWEN!\n *\n * !XXX!!XXX!!XXX!!XXX!!XXX!! BIG ALL CAPS WARNING !!XXX!!XXX!!XXX!!XXX!!XXX!!\n */\n\n#include \"derived.h\"\n\n/* Don's Handy Guide to adding derived channels:\n *\n * There are seven types of derived channels which can be added to the format\n * file. Channel names are, of course, case sensitive. On start-up, both\n * mcp and decomd run sanity checks on the channel lists, including the derived\n * channel list. The checks will fail for the derived channel list if either\n * a source channel doesn't exist or a derived channel has a name already in\n * use. Listed below are the derived channel types and their arguments. If\n * more derived channel types are desired, please ask me to add them. --dvw\n *\n * o LINCOM: Single field calibration. Arguments:\n * 1. Derived Channel Name (string)\n * 2. Source Channel Name (string)\n * 3. Calibration Slope (double)\n * 4. Calibration Intercept (double)\n * o LINCOM2: Two field linear combination\n * 1. Derived Channel Name (string)\n * 2. Source 1 Channel Name (string)\n * 3. Source 1 Calibration Slope (double)\n * 4. Source 1 Calibration Intercept (double)\n * 5. Source 2 Channel Name (string)\n * 6. Source 2 Calibration Slope (double)\n * 7. Source 2 Calibration Intercept (double)\n * o LINTERP: Linearly interpolated look up table\n * 1. Derived Channel Name (string)\n * 2. Source Channel Name (string)\n * 3. Full Path to Look Up Table File (string)\n * o BITS: A bit channel extracted from a larger source channel\n * 1. Derived Channel Name (string)\n * 2. Source Channel Name (string)\n * 3. First bit of the bitword, numbered from zero (integer)\n * 4. Length of the bitword (integer)\n * o COMMENT: A literal comment to be inserted into the format file\n * 1. Comment Text (string) -- there is no need to include the comment\n * delimiter (#).\n * o UNITS: meta data defining units and quantity for existing fields\n * 1. Source Channel Name (string)\n * 2. String for the quantity (eg \"Temperature\")\n * 3. String for the Units (eg, \"^oC\")\n *\n *\n * In addition to the derived channels derived below, defile will add the\n * \"Nice CPU Values\" (to wit: CPU_SEC, CPU_HOUR, etc.), properly offset to the\n * start of the file, to the end of the format file.\n */\n\n#define LUT_DIR \"/data/etc/blast/\"\n\nderived_tng_t derived_list[] = {\n /* Pointing */\n COMMENT(\"Microsecond Resolution Time\"),\n LINCOM2(\"Time\", \"time_usec\", 1.0E-6, 0, \"time\", 1, 0),\n UNITS(\"Time\", \"Time\", \"s\"),\n\n COMMENT(\"General BLAST Status\"),\n BITWORD(\"SOUTH_I_AM\", \"status_mcc\", 0, 1),\n BITWORD(\"AT_FLOAT\", \"status_mcc\", 1, 1),\n BITWORD(\"UPLINK_SCHED\", \"status_mcc\", 2, 1),\n BITWORD(\"BLAST_SUCKS\", \"status_mcc\", 3, 1),\n BITWORD(\"SCHEDULE\", \"status_mcc\", 4, 3),\n BITWORD(\"INCHARGE\", \"status_mcc\", 7, 1),\n BITWORD(\"SLOT_SCHED\", \"status_mcc\", 8, 8),\n\n BITWORD(\"STATUS_ISC_ETH\", \"status_eth\", 2, 2),\n BITWORD(\"STATUS_OSC_ETH\", \"status_eth\", 4, 2),\n BITWORD(\"STATUS_SBSC_ETH\", \"status_eth\", 6, 2),\n\n#ifndef BOLOTEST\n COMMENT(\"Pointing Stuff\"),\n LINCOM(\"X_H_P\", \"x_p\", 0.0003662109375, 0),\n\n BITWORD(\"VETO_EL_MOTOR_ENC\", \"veto_sensor\", 0, 1),\n BITWORD(\"VETO_XSC0\", \"veto_sensor\", 1, 1),\n// BITWORD(\"VETO_EL_ENC\", \"veto_sensor\", 2, 1),\n// (LMF 2018-12-20 not needed. Can be used for another sensor.)\n BITWORD(\"VETO_MAG1\", \"veto_sensor\", 3, 1),\n BITWORD(\"VETO_MAG2\", \"veto_sensor\", 4, 1),\n BITWORD(\"VETO_EL_CLIN\", \"veto_sensor\", 5, 1),\n BITWORD(\"VETO_XSC1\", \"veto_sensor\", 6, 1),\n BITWORD(\"IS_SCHED\", \"veto_sensor\", 7, 1),\n BITWORD(\"AZ_AUTO_GYRO\", \"veto_sensor\", 8, 1),\n BITWORD(\"EL_AUTO_GYRO\", \"veto_sensor\", 9, 1),\n BITWORD(\"DISABLE_EL\", \"veto_sensor\", 10, 1),\n BITWORD(\"DISABLE_AZ\", \"veto_sensor\", 11, 1),\n BITWORD(\"FORCE_EL\", \"veto_sensor\", 12, 1),\n BITWORD(\"VETO_PSS\", \"veto_sensor\", 13, 1),\n BITWORD(\"VETO_DGPS\", \"veto_sensor\", 14, 1),\n COMMENT(\"ACS Digital Signals\"),\n\n /* charge controller (CC) faults and alarms */\n COMMENT(\"Charge Controller Bitfields\"),\n\n BITWORD(\"F_OVERCURRENT_CC1\", \"fault_cc1\", 0, 1),\n BITWORD(\"F_FET_SHORT_CC1\", \"fault_cc1\", 1, 1),\n BITWORD(\"F_SOFTWARE_BUG_CC1\", \"fault_cc1\", 2, 1),\n BITWORD(\"F_BATT_HVD_CC1\", \"fault_cc1\", 3, 1),\n BITWORD(\"F_ARR_HVD_CC1\", \"fault_cc1\", 4, 1),\n BITWORD(\"F_DIP_CHANGED_CC1\", \"fault_cc1\", 5, 1),\n BITWORD(\"F_SETTING_CHANGE_CC1\", \"fault_cc1\", 6, 1),\n BITWORD(\"F_RTS_SHORT_CC1\", \"fault_cc1\", 7, 1),\n BITWORD(\"F_RTS_DISCONN_CC1\", \"fault_cc1\", 8, 1),\n BITWORD(\"F_EEPROM_LIM_CC1\", \"fault_cc1\", 9, 1),\n BITWORD(\"F_SLAVE_TO_CC1\", \"fault_cc1\", 10, 1),\n\n BITWORD(\"F_OVERCURRENT_CC2\", \"fault_cc2\", 0, 1),\n BITWORD(\"F_FET_SHORT_CC2\", \"fault_cc2\", 1, 1),\n BITWORD(\"F_SOFTWARE_BUG_CC2\", \"fault_cc2\", 2, 1),\n BITWORD(\"F_BATT_HVD_CC2\", \"fault_cc2\", 3, 1),\n BITWORD(\"F_ARR_HVD_CC2\", \"fault_cc2\", 4, 1),\n BITWORD(\"F_DIP_CHANGED_CC2\", \"fault_cc2\", 5, 1),\n BITWORD(\"F_SETTING_CHANGE_CC2\", \"fault_cc2\", 6, 1),\n BITWORD(\"F_RTS_SHORT_CC2\", \"fault_cc2\", 7, 1),\n BITWORD(\"F_RTS_DISCONN_CC2\", \"fault_cc2\", 8, 1),\n BITWORD(\"F_EEPROM_LIM_CC2\", \"fault_cc2\", 9, 1),\n BITWORD(\"F_SLAVE_TO_CC2\", \"fault_cc2\", 10, 1),\n\n BITWORD(\"A_RTS_OPEN_CC1\", \"alarm_cc1\", 0, 1),\n BITWORD(\"A_RTS_SHORT_CC1\", \"alarm_cc1\", 1, 1),\n BITWORD(\"A_RTS_DISCONN_CC1\", \"alarm_cc1\", 2, 1),\n BITWORD(\"A_TSENSE_OPEN_CC1\", \"alarm_cc1\", 3, 1),\n BITWORD(\"A_TSENSE_SHORT_CC1\", \"alarm_cc1\", 4, 1),\n BITWORD(\"A_HITEMP_LIM_CC1\", \"alarm_cc1\", 5, 1),\n BITWORD(\"A_CURRENT_LIM_CC1\", \"alarm_cc1\", 6, 1),\n BITWORD(\"A_CURRENT_OFFSET_CC1\", \"alarm_cc1\", 7, 1),\n BITWORD(\"A_BATT_RANGE_CC1\", \"alarm_cc1\", 8, 1),\n BITWORD(\"A_BATTSENSE_DISC_CC1\", \"alarm_cc1\", 9, 1),\n BITWORD(\"A_UNCALIB_CC1\", \"alarm_cc1\", 10, 1),\n BITWORD(\"A_RTS_MISWIRE_CC1\", \"alarm_cc1\", 11, 1),\n BITWORD(\"A_HVD_CC1\", \"alarm_cc1\", 12, 1),\n BITWORD(\"A_SYS_MISWIRE_CC1\", \"alarm_cc1\", 14, 1),\n BITWORD(\"A_FET_OPEN_CC1\", \"alarm_cc1\", 15, 1),\n\n BITWORD(\"A_RTS_OPEN_CC2\", \"alarm_cc2\", 0, 1),\n BITWORD(\"A_RTS_SHORT_CC2\", \"alarm_cc2\", 1, 1),\n BITWORD(\"A_RTS_DISCONN_CC2\", \"alarm_cc2\", 2, 1),\n BITWORD(\"A_TSENSE_OPEN_CC2\", \"alarm_cc2\", 3, 1),\n BITWORD(\"A_TSENSE_SHORT_CC2\", \"alarm_cc2\", 4, 1),\n BITWORD(\"A_HITEMP_LIM_CC2\", \"alarm_cc2\", 5, 1),\n BITWORD(\"A_CURRENT_LIM_CC2\", \"alarm_cc2\", 6, 1),\n BITWORD(\"A_CURRENT_OFFSET_CC2\", \"alarm_cc2\", 7, 1),\n BITWORD(\"A_BATT_RANGE_CC2\", \"alarm_cc2\", 8, 1),\n BITWORD(\"A_BATTSENSE_DISC_CC2\", \"alarm_cc2\", 9, 1),\n BITWORD(\"A_UNCALIB_CC2\", \"alarm_cc2\", 10, 1),\n BITWORD(\"A_RTS_MISWIRE_CC2\", \"alarm_cc2\", 11, 1),\n BITWORD(\"A_HVD_CC2\", \"alarm_cc2\", 12, 1),\n BITWORD(\"A_SYS_MISWIRE_CC2\", \"alarm_cc2\", 14, 1),\n BITWORD(\"A_FET_OPEN_CC2\", \"alarm_cc2\", 15, 1),\n\n BITWORD(\"A_VP12_OFF_CC1\", \"alarm_cc1\", 16, 1),\n BITWORD(\"C_A_HI_INPUT_LIM_CC1\", \"alarm_cc1\", 17, 1),\n BITWORD(\"C_A_ADC_MAX_IN_CC1\", \"alarm_cc1\", 18, 1),\n BITWORD(\"C_A_RESET_CC1\", \"alarm_cc1\", 19, 1),\n\n BITWORD(\"A_VP12_OFF_CC2\", \"alarm_cc2\", 16, 1),\n BITWORD(\"C_A_HI_INPUT_LIM_CC2\", \"alarm_cc2\", 17, 1),\n BITWORD(\"C_A_ADC_MAX_IN_CC2\", \"alarm_cc2\", 18, 1),\n BITWORD(\"C_A_RESET_CC2\", \"alarm_cc2\", 19, 1),\n\n BITWORD(\"ACT0_INIT_ACTBUS\", \"status_actbus\", 0, 1),\n BITWORD(\"ACT1_INIT_ACTBUS\", \"status_actbus\", 1, 1),\n BITWORD(\"ACT2_INIT_ACTBUS\", \"status_actbus\", 2, 1),\n BITWORD(\"BAL_INIT_ACTBUS\", \"status_actbus\", 3, 1),\n BITWORD(\"LOCK_INIT_ACTBUS\", \"status_actbus\", 4, 1),\n BITWORD(\"HWPR_INIT_ACTBUS\", \"status_actbus\", 5, 1),\n BITWORD(\"SHUTTER_INIT_ACTBUS\", \"status_actbus\", 6, 1),\n BITWORD(\"PUMPED_POT_INIT_ACTBUS\", \"status_actbus\", 7, 1),\n BITWORD(\"PUMP_VALVE_INIT_ACTBUS\", \"status_actbus\", 8, 1),\n BITWORD(\"FILL_VALVE_INIT_ACTBUS\", \"status_actbus\", 9, 1),\n\n BITWORD(\"DIR_BAL\", \"status_bal\", 0, 2),\n BITWORD(\"INIT_BAL\", \"status_bal\", 2, 1),\n BITWORD(\"DO_MOVE_BAL\", \"status_bal\", 3, 1),\n BITWORD(\"MOVING_BAL\", \"status_bal\", 4, 1),\n BITWORD(\"MODE_BAL\", \"status_bal\", 5, 2),\n\n #endif\n\n COMMENT(\"Lock Motor/Actuators\"),\n BITWORD(\"LS_OPEN_LOCK\", \"state_lock\", 0, 1),\n BITWORD(\"LS_CLOSED_LOCK\", \"state_lock\", 1, 1),\n BITWORD(\"LS_DRIVE_OFF_LOCK\", \"state_lock\", 2, 1),\n BITWORD(\"LS_POT_RAIL_LOCK\", \"state_lock\", 3, 1),\n BITWORD(\"LS_DRIVE_EXT_LOCK\", \"state_lock\", 4, 1),\n BITWORD(\"LS_DRIVE_RET_LOCK\", \"state_lock\", 5, 1),\n BITWORD(\"LS_DRIVE_STP_LOCK\", \"state_lock\", 6, 1),\n BITWORD(\"LS_DRIVE_JIG_LOCK\", \"state_lock\", 7, 1),\n BITWORD(\"LS_DRIVE_UNK_LOCK\", \"state_lock\", 8, 1),\n BITWORD(\"LS_EL_OK_LOCK\", \"state_lock\", 9, 1),\n BITWORD(\"LS_IGNORE_EL_LOCK\", \"state_lock\", 10, 1),\n BITWORD(\"LS_DRIVE_FORCE_LOCK\", \"state_lock\", 11, 1),\n\n COMMENT(\"Aalborg Valves\"),\n BITWORD(\"OPENED_1_AALBORG\", \"state_1_aalborg\", 0, 1),\n BITWORD(\"CLOSED_1_AALBORG\", \"state_1_aalborg\", 1, 1),\n BITWORD(\"OPENING_1_AALBORG\", \"state_1_aalborg\", 2, 1),\n BITWORD(\"CLOSING_1_AALBORG\", \"state_1_aalborg\", 3, 1),\n BITWORD(\"NOT_CLOSED_1_AALBORG\", \"state_1_aalborg\", 4, 1),\n BITWORD(\"UNK_1_AALBORG\", \"state_1_aalborg\", 5, 1),\n\n BITWORD(\"OPENED_2_AALBORG\", \"state_2_aalborg\", 0, 1),\n BITWORD(\"CLOSED_2_AALBORG\", \"state_2_aalborg\", 1, 1),\n BITWORD(\"OPENING_2_AALBORG\", \"state_2_aalborg\", 2, 1),\n BITWORD(\"CLOSING_2_AALBORG\", \"state_2_aalborg\", 3, 1),\n BITWORD(\"NOT_CLOSED_2_AALBORG\", \"state_2_aalborg\", 4, 1),\n BITWORD(\"UNK_2_AALBORG\", \"state_2_aalborg\", 5, 1),\n\n BITWORD(\"OPENED_3_AALBORG\", \"state_3_aalborg\", 0, 1),\n BITWORD(\"CLOSED_3_AALBORG\", \"state_3_aalborg\", 1, 1),\n BITWORD(\"OPENING_3_AALBORG\", \"state_3_aalborg\", 2, 1),\n BITWORD(\"CLOSING_3_AALBORG\", \"state_3_aalborg\", 3, 1),\n BITWORD(\"NOT_CLOSED_3_AALBORG\", \"state_3_aalborg\", 4, 1),\n BITWORD(\"UNK_3_AALBORG\", \"state_3_aalborg\", 5, 1),\n\n BITWORD(\"OPENED_GOAL_1_AALBORG\", \"goal_1_aalborg\", 0, 1),\n BITWORD(\"CLOSED_GOAL_1_AALBORG\", \"goal_1_aalborg\", 1, 1),\n BITWORD(\"OPENED_GOAL_2_AALBORG\", \"goal_2_aalborg\", 0, 1),\n BITWORD(\"CLOSED_GOAL_2_AALBORG\", \"goal_2_aalborg\", 1, 1),\n BITWORD(\"OPENED_GOAL_3_AALBORG\", \"goal_3_aalborg\", 0, 1),\n BITWORD(\"CLOSED_GOAL_3_AALBORG\", \"goal_3_aalborg\", 1, 1),\n\n// ),\n\n /* Secondary Focus */\n COMMENT(\"Secondary Focus\"),\n LINCOM2(\"REL_FOCUS_SF\", \"CORRECTION_SF\", 1, 0, \"OFFSET_SF\", 1, 0),\n LINCOM2(\"VETO_SF\", \"WAIT_SF\", 1, 0, \"AGE_SF\", -1, 0),\n\n LINCOM2(\"Pos_0_act\", \"POS_0_ACT\", 1, 0, \"OFFSET_0_ACT\", 1, 0),\n LINCOM2(\"Pos_1_act\", \"POS_1_ACT\", 1, 0, \"OFFSET_1_ACT\", 1, 0),\n LINCOM2(\"Pos_2_act\", \"POS_2_ACT\", 1, 0, \"OFFSET_2_ACT\", 1, 0),\n LINCOM2(\"Enc_0_act\", \"ENC_0_ACT\", 1, 0, \"OFFSET_0_ACT\", 1, 0),\n LINCOM2(\"Enc_1_act\", \"ENC_1_ACT\", 1, 0, \"OFFSET_1_ACT\", 1, 0),\n LINCOM2(\"Enc_2_act\", \"ENC_2_ACT\", 1, 0, \"OFFSET_2_ACT\", 1, 0),\n LINCOM2(\"Lvdt_0_act\", \"LVDT_0_ACT\", 1, 0, \"OFFSET_0_ACT\", 1, 0),\n LINCOM2(\"Lvdt_1_act\", \"LVDT_1_ACT\", 1, 0, \"OFFSET_1_ACT\", 1, 0),\n LINCOM2(\"Lvdt_2_act\", \"LVDT_2_ACT\", 1, 0, \"OFFSET_2_ACT\", 1, 0),\n LINCOM2(\"Goal_0_act\", \"GOAL_0_ACT\", 1, 0, \"OFFSET_0_ACT\", 1, 0),\n LINCOM2(\"Goal_1_act\", \"GOAL_1_ACT\", 1, 0, \"OFFSET_1_ACT\", 1, 0),\n LINCOM2(\"Goal_2_act\", \"GOAL_2_ACT\", 1, 0, \"OFFSET_2_ACT\", 1, 0),\n LINCOM2(\"Dr_0_act\", \"DR_0_ACT\", 1, 0, \"OFFSET_0_ACT\", 1, 0),\n LINCOM2(\"Dr_1_act\", \"DR_1_ACT\", 1, 0, \"OFFSET_1_ACT\", 1, 0),\n LINCOM2(\"Dr_2_act\", \"DR_2_ACT\", 1, 0, \"OFFSET_2_ACT\", 1, 0),\n\n BITWORD(\"TRIM_WAIT_ACT\", \"flags_act\", 0, 1),\n BITWORD(\"TRIMMED_ACT\", \"flags_act\", 1, 1),\n BITWORD(\"BUSY_0_ACT\", \"flags_act\", 2, 1),\n BITWORD(\"BUSY_1_ACT\", \"flags_act\", 3, 1),\n BITWORD(\"BUSY_2_ACT\", \"flags_act\", 4, 1),\n BITWORD(\"BAD_MOVE_ACT\", \"flags_act\", 5, 1),\n\n BITWORD(\"LATCHED_DATA_CRC_EL\", \"latched_fault_el\", 0, 1),\n BITWORD(\"LATCHED_AMP_INT_EL\", \"latched_fault_el\", 1, 1),\n BITWORD(\"LATCHED_SHORT_CIRC_EL\", \"latched_fault_el\", 2, 1),\n BITWORD(\"LATCHED_AMP_OVER_T_EL\", \"latched_fault_el\", 3, 1),\n BITWORD(\"LATCHED_MOTOR_OVER_T_EL\", \"latched_fault_el\", 4, 1),\n BITWORD(\"LATCHED_OVERVOLT_EL\", \"latched_fault_el\", 5, 1),\n BITWORD(\"LATCHED_UNDERVOLT_EL\", \"latched_fault_el\", 6, 1),\n BITWORD(\"LATCHED_FEEDBACK_EL\", \"latched_fault_el\", 7, 1),\n BITWORD(\"LATCHED_PHASING_ERR_EL\", \"latched_fault_el\", 8, 1),\n BITWORD(\"LATCHED_TRACKING_ERR_EL\", \"latched_fault_el\", 9, 1),\n BITWORD(\"LATCHED_OVERCURRENT_EL\", \"latched_fault_el\", 10, 1),\n BITWORD(\"LATCHED_FPGA_FAIL_EL\", \"latched_fault_el\", 11, 1),\n BITWORD(\"LATCHED_CMD_INPUT_LOST_EL\", \"latched_fault_el\", 12, 1),\n BITWORD(\"LATCHED_FPGA_FAIL2_EL\", \"latched_fault_el\", 13, 1),\n BITWORD(\"LATCHED_SAFETY_CIRC_EL\", \"latched_fault_el\", 14, 1),\n BITWORD(\"LATCHED_CONT_CURRENT_EL\", \"latched_fault_el\", 15, 1),\n\n BITWORD(\"LATCHED_DATA_CRC_PIV\", \"latched_fault_piv\", 0, 1),\n BITWORD(\"LATCHED_AMP_INT_PIV\", \"latched_fault_piv\", 1, 1),\n BITWORD(\"LATCHED_SHORT_CIRC_PIV\", \"latched_fault_piv\", 2, 1),\n BITWORD(\"LATCHED_AMP_OVER_T_PIV\", \"latched_fault_piv\", 3, 1),\n BITWORD(\"LATCHED_MOTOR_OVER_T_PIV\", \"latched_fault_piv\", 4, 1),\n BITWORD(\"LATCHED_OVERVOLT_PIV\", \"latched_fault_piv\", 5, 1),\n BITWORD(\"LATCHED_UNDERVOLT_PIV\", \"latched_fault_piv\", 6, 1),\n BITWORD(\"LATCHED_FEEDBACK_PIV\", \"latched_fault_piv\", 7, 1),\n BITWORD(\"LATCHED_PHASING_ERR_PIV\", \"latched_fault_piv\", 8, 1),\n BITWORD(\"LATCHED_TRACKING_ERR_PIV\", \"latched_fault_piv\", 9, 1),\n BITWORD(\"LATCHED_OVERCURRENT_PIV\", \"latched_fault_piv\", 10, 1),\n BITWORD(\"LATCHED_FPGA_FAIL_PIV\", \"latched_fault_piv\", 11, 1),\n BITWORD(\"LATCHED_CMD_INPUT_LOST_PIV\", \"latched_fault_piv\", 12, 1),\n BITWORD(\"LATCHED_FPGA_FAIL2_PIV\", \"latched_fault_piv\", 13, 1),\n BITWORD(\"LATCHED_SAFETY_CIRC_PIV\", \"latched_fault_piv\", 14, 1),\n BITWORD(\"LATCHED_CONT_CURRENT_PIV\", \"latched_fault_piv\", 15, 1),\n\n BITWORD(\"LATCHED_DATA_CRC_RW\", \"latched_fault_rw\", 0, 1),\n BITWORD(\"LATCHED_AMP_INT_RW\", \"latched_fault_rw\", 1, 1),\n BITWORD(\"LATCHED_SHORT_CIRC_RW\", \"latched_fault_rw\", 2, 1),\n BITWORD(\"LATCHED_AMP_OVER_T_RW\", \"latched_fault_rw\", 3, 1),\n BITWORD(\"LATCHED_MOTOR_OVER_T_RW\", \"latched_fault_rw\", 4, 1),\n BITWORD(\"LATCHED_OVERVOLT_RW\", \"latched_fault_rw\", 5, 1),\n BITWORD(\"LATCHED_UNDERVOLT_RW\", \"latched_fault_rw\", 6, 1),\n BITWORD(\"LATCHED_FEEDBACK_RW\", \"latched_fault_rw\", 7, 1),\n BITWORD(\"LATCHED_PHASING_ERR_RW\", \"latched_fault_rw\", 8, 1),\n BITWORD(\"LATCHED_TRACKING_ERR_RW\", \"latched_fault_rw\", 9, 1),\n BITWORD(\"LATCHED_OVERCURRENT_RW\", \"latched_fault_rw\", 10, 1),\n BITWORD(\"LATCHED_FPGA_FAIL_RW\", \"latched_fault_rw\", 11, 1),\n BITWORD(\"LATCHED_CMD_INPUT_LOST_RW\", \"latched_fault_rw\", 12, 1),\n BITWORD(\"LATCHED_FPGA_FAIL2_RW\", \"latched_fault_rw\", 13, 1),\n BITWORD(\"LATCHED_SAFETY_CIRC_RW\", \"latched_fault_rw\", 14, 1),\n BITWORD(\"LATCHED_CONT_CURRENT_RW\", \"latched_fault_rw\", 15, 1),\n\n BITWORD(\"ST_SHORT_CIRC_EL\", \"status_el\", 0, 1),\n BITWORD(\"ST_AMP_OVER_T_EL\", \"status_el\", 1, 1),\n BITWORD(\"ST_OVER_V_EL\", \"status_el\", 2, 1),\n BITWORD(\"ST_UNDER_V_EL\", \"status_el\", 3, 1),\n\n BITWORD(\"ST_FEEDBACK_ERR_EL\", \"status_el\", 5, 1),\n BITWORD(\"ST_MOT_PHAS_ERR_EL\", \"status_el\", 6, 1),\n BITWORD(\"ST_I_LIMITED_EL\", \"status_el\", 7, 1),\n BITWORD(\"ST_VOLT_LIM_EL\", \"status_el\", 8, 1),\n BITWORD(\"ST_LIM_SW_POS_EL\", \"status_el\", 9, 1),\n BITWORD(\"ST_LIM_SW_NEG_EL\", \"status_el\", 10, 1),\n\n BITWORD(\"ST_DISAB_HWARE_EL\", \"status_el\", 11, 1),\n BITWORD(\"ST_DISAB_SWARE_EL\", \"status_el\", 12, 1),\n BITWORD(\"ST_ATTEMPT_STOP_EL\", \"status_el\", 13, 1),\n BITWORD(\"ST_MOT_BREAK_ACT_EL\", \"status_el\", 14, 1),\n BITWORD(\"ST_PWM_OUT_DIS_EL\", \"status_el\", 15, 1),\n BITWORD(\"ST_POS_SOFT_LIM_EL\", \"status_el\", 16, 1),\n BITWORD(\"ST_NEG_SOFT_LIM_EL\", \"status_el\", 17, 1),\n BITWORD(\"ST_FOLLOW_ERR_EL\", \"status_el\", 18, 1),\n BITWORD(\"ST_FOLLOW_WARN_EL\", \"status_el\", 19, 1),\n BITWORD(\"ST_AMP_HAS_RESET_EL\", \"status_el\", 20, 1),\n BITWORD(\"ST_ENCODER_WRAP_EL\", \"status_el\", 21, 1),\n BITWORD(\"ST_AMP_FAULT_EL\", \"status_el\", 22, 1),\n BITWORD(\"ST_VEL_LIMITED_EL\", \"status_el\", 23, 1),\n BITWORD(\"ST_ACCEL_LIMITED_EL\", \"status_el\", 24, 1),\n\n BITWORD(\"ST_IN_MOTION_EL\", \"status_el\", 27, 1),\n BITWORD(\"ST_V_OUT_TRACK_W_EL\", \"status_el\", 28, 1),\n BITWORD(\"ST_PHASE_NOT_INIT_EL\", \"status_el\", 29, 1),\n\n BITWORD(\"ST_SHORT_CIRC_PIV\", \"status_piv\", 0, 1),\n BITWORD(\"ST_AMP_OVER_T_PIV\", \"status_piv\", 1, 1),\n BITWORD(\"ST_OVER_V_PIV\", \"status_piv\", 2, 1),\n BITWORD(\"ST_UNDER_V_PIV\", \"status_piv\", 3, 1),\n\n BITWORD(\"ST_FEEDBACK_ERR_PIV\", \"status_piv\", 5, 1),\n BITWORD(\"ST_MOT_PHAS_ERR_PIV\", \"status_piv\", 6, 1),\n BITWORD(\"ST_I_LIMITED_PIV\", \"status_piv\", 7, 1),\n BITWORD(\"ST_VOLT_LIM_PIV\", \"status_piv\", 8, 1),\n BITWORD(\"ST_LIM_SW_POS_PIV\", \"status_piv\", 9, 1),\n BITWORD(\"ST_LIM_SW_NEG_PIV\", \"status_piv\", 10, 1),\n\n BITWORD(\"ST_DISAB_HWARE_PIV\", \"status_piv\", 11, 1),\n BITWORD(\"ST_DISAB_SWARE_PIV\", \"status_piv\", 12, 1),\n BITWORD(\"ST_ATTEMPT_STOP_PIV\", \"status_piv\", 13, 1),\n BITWORD(\"ST_MOT_BREAK_ACT_PIV\", \"status_piv\", 14, 1),\n BITWORD(\"ST_PWM_OUT_DIS_PIV\", \"status_piv\", 15, 1),\n BITWORD(\"ST_POS_SOFT_LIM_PIV\", \"status_piv\", 16, 1),\n BITWORD(\"ST_NEG_SOFT_LIM_PIV\", \"status_piv\", 17, 1),\n BITWORD(\"ST_FOLLOW_ERR_PIV\", \"status_piv\", 18, 1),\n BITWORD(\"ST_FOLLOW_WARN_PIV\", \"status_piv\", 19, 1),\n BITWORD(\"ST_AMP_HAS_RESET_PIV\", \"status_piv\", 20, 1),\n BITWORD(\"ST_ENCODER_WRAP_PIV\", \"status_piv\", 21, 1),\n BITWORD(\"ST_AMP_FAULT_PIV\", \"status_piv\", 22, 1),\n BITWORD(\"ST_VEL_LIMITED_PIV\", \"status_piv\", 23, 1),\n BITWORD(\"ST_ACCEL_LIMITED_PIV\", \"status_piv\", 24, 1),\n\n BITWORD(\"ST_IN_MOTION_PIV\", \"status_piv\", 27, 1),\n BITWORD(\"ST_V_OUT_TRACK_W_PIV\", \"status_piv\", 28, 1),\n BITWORD(\"ST_PHASE_NOT_INIT_PIV\", \"status_piv\", 29, 1),\n\n BITWORD(\"ST_SHORT_CIRC_RW\", \"status_rw\", 0, 1),\n BITWORD(\"ST_AMP_OVER_T_RW\", \"status_rw\", 1, 1),\n BITWORD(\"ST_OVER_V_RW\", \"status_rw\", 2, 1),\n BITWORD(\"ST_UNDER_V_RW\", \"status_rw\", 3, 1),\n\n BITWORD(\"ST_FEEDBACK_ERR_RW\", \"status_rw\", 5, 1),\n BITWORD(\"ST_MOT_PHAS_ERR_RW\", \"status_rw\", 6, 1),\n BITWORD(\"ST_I_LIMITED_RW\", \"status_rw\", 7, 1),\n BITWORD(\"ST_VOLT_LIM_RW\", \"status_rw\", 8, 1),\n BITWORD(\"ST_LIM_SW_POS_RW\", \"status_rw\", 9, 1),\n BITWORD(\"ST_LIM_SW_NEG_RW\", \"status_rw\", 10, 1),\n\n BITWORD(\"ST_DISAB_HWARE_RW\", \"status_rw\", 11, 1),\n BITWORD(\"ST_DISAB_SWARE_RW\", \"status_rw\", 12, 1),\n BITWORD(\"ST_ATTEMPT_STOP_RW\", \"status_rw\", 13, 1),\n BITWORD(\"ST_MOT_BREAK_ACT_RW\", \"status_rw\", 14, 1),\n BITWORD(\"ST_PWM_OUT_DIS_RW\", \"status_rw\", 15, 1),\n BITWORD(\"ST_POS_SOFT_LIM_RW\", \"status_rw\", 16, 1),\n BITWORD(\"ST_NEG_SOFT_LIM_RW\", \"status_rw\", 17, 1),\n BITWORD(\"ST_FOLLOW_ERR_RW\", \"status_rw\", 18, 1),\n BITWORD(\"ST_FOLLOW_WARN_RW\", \"status_rw\", 19, 1),\n BITWORD(\"ST_AMP_HAS_RESET_RW\", \"status_rw\", 20, 1),\n BITWORD(\"ST_ENCODER_WRAP_RW\", \"status_rw\", 21, 1),\n BITWORD(\"ST_AMP_FAULT_RW\", \"status_rw\", 22, 1),\n BITWORD(\"ST_VEL_LIMITED_RW\", \"status_rw\", 23, 1),\n BITWORD(\"ST_ACCEL_LIMITED_RW\", \"status_rw\", 24, 1),\n\n BITWORD(\"ST_IN_MOTION_RW\", \"status_rw\", 27, 1),\n BITWORD(\"ST_V_OUT_TRACK_W_RW\", \"status_rw\", 28, 1),\n BITWORD(\"ST_PHASE_NOT_INIT_RW\", \"status_rw\", 29, 1),\n BITWORD(\"NET_ST_NODE_STATUS_RW\", \"network_status_rw\", 0, 2),\n BITWORD(\"NET_ST_SYNC_MISSING_RW\", \"network_status_rw\", 4, 1),\n BITWORD(\"NET_ST_GUARD_ERR_RW\", \"network_status_rw\", 5, 1),\n BITWORD(\"NET_ST_BUS_OFF_RW\", \"network_status_rw\", 8, 1),\n BITWORD(\"NET_ST_SYNC_TRANS_ERROR_RW\", \"network_status_rw\", 9, 1),\n BITWORD(\"NET_ST_SYNC_REC_ERROR_RW\", \"network_status_rw\", 10, 1),\n BITWORD(\"NET_ST_SYNC_TRANS_WARNING_RW\", \"network_status_rw\", 11, 1),\n BITWORD(\"NET_ST_SYNC_REC_WARNING_RW\", \"network_status_rw\", 12, 1),\n BITWORD(\"STATE_READY_EL\", \"state_el\", 0, 1),\n BITWORD(\"STATE_SWITCHED_ON_EL\", \"state_el\", 1, 1),\n BITWORD(\"STATE_OP_ENABLED_EL\", \"state_el\", 2, 1),\n BITWORD(\"STATE_FAULT_EL\", \"state_el\", 3, 1),\n BITWORD(\"STATE_VOLTAGE_ENABLED_EL\", \"state_el\", 4, 1),\n BITWORD(\"STATE_NOT_QUICK_STOP_EL\", \"state_el\", 5, 1),\n BITWORD(\"STATE_ON_DISABLE_EL\", \"state_el\", 6, 1),\n BITWORD(\"STATE_WARNING_EL\", \"state_el\", 7, 1),\n BITWORD(\"STATE_ABORTED_EL\", \"state_el\", 8, 1),\n BITWORD(\"STATE_REMOTE_EL\", \"state_el\", 9, 1),\n BITWORD(\"STATE_ON_TARGET_EL\", \"state_el\", 10, 1),\n BITWORD(\"STATE_AMP_LIMIT_EL\", \"state_el\", 11, 1),\n BITWORD(\"STATE_MOVING_EL\", \"state_el\", 14, 1),\n BITWORD(\"NET_ST_NODE_STATUS_EL\", \"network_status_el\", 0, 2),\n BITWORD(\"NET_ST_SYNC_MISSING_EL\", \"network_status_el\", 4, 1),\n BITWORD(\"NET_ST_GUARD_ERR_EL\", \"network_status_el\", 5, 1),\n BITWORD(\"NET_ST_BUS_OFF_EL\", \"network_status_el\", 8, 1),\n BITWORD(\"NET_ST_SYNC_TRANS_ERROR_EL\", \"network_status_el\", 9, 1),\n BITWORD(\"NET_ST_SYNC_REC_ERROR_EL\", \"network_status_el\", 10, 1),\n BITWORD(\"NET_ST_SYNC_TRANS_WARNING_EL\", \"network_status_el\", 11, 1),\n BITWORD(\"NET_ST_SYNC_REC_WARNING_EL\", \"network_status_el\", 12, 1),\n BITWORD(\"STATE_READY_RW\", \"state_rw\", 0, 1),\n BITWORD(\"STATE_SWITCHED_ON_RW\", \"state_rw\", 1, 1),\n BITWORD(\"STATE_OP_ENABLED_RW\", \"state_rw\", 2, 1),\n BITWORD(\"STATE_FAULT_RW\", \"state_rw\", 3, 1),\n BITWORD(\"STATE_VOLTAGE_ENABLED_RW\", \"state_rw\", 4, 1),\n BITWORD(\"STATE_NOT_QUICK_STOP_RW\", \"state_rw\", 5, 1),\n BITWORD(\"STATE_ON_DISABLE_RW\", \"state_rw\", 6, 1),\n BITWORD(\"STATE_WARNING_RW\", \"state_rw\", 7, 1),\n BITWORD(\"STATE_ABORTED_RW\", \"state_rw\", 8, 1),\n BITWORD(\"STATE_REMOTE_RW\", \"state_rw\", 9, 1),\n BITWORD(\"STATE_ON_TARGET_RW\", \"state_rw\", 10, 1),\n BITWORD(\"STATE_AMP_LIMIT_RW\", \"state_rw\", 11, 1),\n BITWORD(\"STATE_MOVING_RW\", \"state_rw\", 14, 1),\n\n BITWORD(\"STATE_READY_PIV\", \"state_piv\", 0, 1),\n BITWORD(\"STATE_SWITCHED_ON_PIV\", \"state_piv\", 1, 1),\n BITWORD(\"STATE_OP_ENABLED_PIV\", \"state_piv\", 2, 1),\n BITWORD(\"STATE_FAULT_PIV\", \"state_piv\", 3, 1),\n BITWORD(\"STATE_VOLTAGE_ENABLED_PIV\", \"state_piv\", 4, 1),\n BITWORD(\"STATE_NOT_QUICK_STOP_PIV\", \"state_piv\", 5, 1),\n BITWORD(\"STATE_ON_DISABLE_PIV\", \"state_piv\", 6, 1),\n BITWORD(\"STATE_WARNING_PIV\", \"state_piv\", 7, 1),\n BITWORD(\"STATE_ABORTED_PIV\", \"state_piv\", 8, 1),\n BITWORD(\"STATE_REMOTE_PIV\", \"state_piv\", 9, 1),\n BITWORD(\"STATE_ON_TARGET_PIV\", \"state_piv\", 10, 1),\n BITWORD(\"STATE_AMP_LIMIT_PIV\", \"state_piv\", 11, 1),\n BITWORD(\"STATE_MOVING_PIV\", \"state_piv\", 14, 1),\n BITWORD(\"NET_ST_NODE_STATUS_PIV\", \"network_status_piv\", 0, 2),\n BITWORD(\"NET_ST_SYNC_MISSING_PIV\", \"network_status_piv\", 4, 1),\n BITWORD(\"NET_ST_GUARD_ERR_PIV\", \"network_status_piv\", 5, 1),\n BITWORD(\"NET_ST_BUS_OFF_PIV\", \"network_status_piv\", 8, 1),\n BITWORD(\"NET_ST_SYNC_TRANS_ERROR_PIV\", \"network_status_piv\", 9, 1),\n BITWORD(\"NET_ST_SYNC_REC_ERROR_PIV\", \"network_status_piv\", 10, 1),\n BITWORD(\"NET_ST_SYNC_TRANS_WARNING_PIVOT\", \"network_status_piv\", 11, 1),\n BITWORD(\"NET_ST_SYNC_REC_WARNING_PIVOT\", \"network_status_piv\", 12, 1),\n BITWORD(\"MC_EC_CMD_RESET\", \"mc_cmd_status\", 0, 1),\n BITWORD(\"MC_EC_CMD_FIX_RW\", \"mc_cmd_status\", 1, 1),\n BITWORD(\"MC_EC_CMD_FIX_EL\", \"mc_cmd_status\", 2, 1),\n BITWORD(\"MC_EC_CMD_FIX_PIV\", \"mc_cmd_status\", 3, 1),\n BITWORD(\"MC_EC_CMD_FIX_HWPR\", \"mc_cmd_status\", 4, 1),\n BITWORD(\"SLAVE_INDEX_EC_HWPR\", \"status_ec_hwpr\", 0, 3),\n BITWORD(\"COMMS_OK_EC_HWPR\", \"status_ec_hwpr\", 3, 1),\n BITWORD(\"SLAVE_ERROR_EC_HWPR\", \"status_ec_hwpr\", 4, 1),\n BITWORD(\"HAS_DC_EC_HWPR\", \"status_ec_hwpr\", 5, 1),\n BITWORD(\"IS_MC_EC_HWPR\", \"status_ec_hwpr\", 6, 1),\n BITWORD(\"IS_HWPR_EC_HWPR\", \"status_ec_hwpr\", 7, 1),\n BITWORD(\"SLAVE_INDEX_EC_RW\", \"status_ec_rw\", 0, 3),\n BITWORD(\"COMMS_OK_EC_RW\", \"status_ec_rw\", 3, 1),\n BITWORD(\"SLAVE_ERROR_EC_RW\", \"status_ec_rw\", 4, 1),\n BITWORD(\"HAS_DC_EC_RW\", \"status_ec_rw\", 5, 1),\n BITWORD(\"IS_MC_EC_RW\", \"status_ec_rw\", 6, 1),\n BITWORD(\"IS_HWPR_EC_RW\", \"status_ec_rw\", 7, 1),\n BITWORD(\"SLAVE_INDEX_EC_EL\", \"status_ec_el\", 0, 3),\n BITWORD(\"COMMS_OK_EC_EL\", \"status_ec_el\", 3, 1),\n BITWORD(\"SLAVE_ERROR_EC_EL\", \"status_ec_el\", 4, 1),\n BITWORD(\"HAS_DC_EC_EL\", \"status_ec_el\", 5, 1),\n BITWORD(\"IS_MC_EC_EL\", \"status_ec_el\", 6, 1),\n BITWORD(\"IS_HWPR_EC_EL\", \"status_ec_el\", 7, 1),\n BITWORD(\"SLAVE_INDEX_EC_PIV\", \"status_ec_piv\", 0, 3),\n BITWORD(\"COMMS_OK_EC_PIV\", \"status_ec_piv\", 3, 1),\n BITWORD(\"SLAVE_ERROR_EC_PIV\", \"status_ec_piv\", 4, 1),\n BITWORD(\"HAS_DC_EC_PIV\", \"status_ec_piv\", 5, 1),\n BITWORD(\"IS_MC_EC_PIV\", \"status_ec_piv\", 6, 1),\n BITWORD(\"IS_HWPR_EC_PIV\", \"status_ec_piv\", 7, 1),\n BITWORD(\"CTL_ON_READ_PIV\", \"control_word_read_piv\", 0, 1),\n BITWORD(\"CTL_ENABLE_VOLTAGE_READ_PIV\", \"control_word_read_piv\", 1, 1),\n BITWORD(\"CTL_QUICK_STOP_READ_PIV\", \"control_word_read_piv\", 2, 1),\n BITWORD(\"CTL_ENABLE_READ_PIV\", \"control_word_read_piv\", 3, 1),\n BITWORD(\"CTL_MODE_OF_OPERATION_READ_PIV\", \"control_word_read_piv\", 4, 3),\n BITWORD(\"CTL_RESET_FAULT_READ_PIV\", \"control_word_read_piv\", 7, 1),\n BITWORD(\"CTL_HALT_READ_PIV\", \"control_word_read_piv\", 8, 1),\n BITWORD(\"CTL_ON_WRITE_PIV\", \"control_word_write_piv\", 0, 1),\n BITWORD(\"CTL_ENABLE_VOLTAGE_WRITE_PIV\", \"control_word_write_piv\", 1, 1),\n BITWORD(\"CTL_QUICK_STOP_WRITE_PIV\", \"control_word_write_piv\", 2, 1),\n BITWORD(\"CTL_ENABLE_WRITE_PIV\", \"control_word_write_piv\", 3, 1),\n BITWORD(\"CTL_MODE_OF_OPERATION_WRITE_PIV\", \"control_word_write_piv\", 4, 3),\n BITWORD(\"CTL_RESET_FAULT_WRITE_PIV\", \"control_word_write_piv\", 7, 1),\n BITWORD(\"CTL_HALT_WRITE_PIV\", \"control_word_write_piv\", 8, 1),\n BITWORD(\"CTL_ON_READ_EL\", \"control_word_read_el\", 0, 1),\n BITWORD(\"CTL_ENABLE_VOLTAGE_READ_EL\", \"control_word_read_el\", 1, 1),\n BITWORD(\"CTL_QUICK_STOP_READ_EL\", \"control_word_read_el\", 2, 1),\n BITWORD(\"CTL_ENABLE_READ_EL\", \"control_word_read_el\", 3, 1),\n BITWORD(\"CTL_MODE_OF_OPERATION_READ_EL\", \"control_word_read_el\", 4, 3),\n BITWORD(\"CTL_RESET_FAULT_READ_EL\", \"control_word_read_el\", 7, 1),\n BITWORD(\"CTL_HALT_READ_EL\", \"control_word_read_el\", 8, 1),\n BITWORD(\"CTL_ON_WRITE_EL\", \"control_word_write_el\", 0, 1),\n BITWORD(\"CTL_ENABLE_VOLTAGE_WRITE_EL\", \"control_word_write_el\", 1, 1),\n BITWORD(\"CTL_QUICK_STOP_WRITE_EL\", \"control_word_write_el\", 2, 1),\n BITWORD(\"CTL_ENABLE_WRITE_EL\", \"control_word_write_el\", 3, 1),\n BITWORD(\"CTL_MODE_OF_OPERATION_WRITE_EL\", \"control_word_write_el\", 4, 3),\n BITWORD(\"CTL_RESET_FAULT_WRITE_EL\", \"control_word_write_el\", 7, 1),\n BITWORD(\"CTL_HALT_WRITE_EL\", \"control_word_write_rw\", 8, 1),\n BITWORD(\"CTL_ON_READ_RW\", \"control_word_read_rw\", 0, 1),\n BITWORD(\"CTL_ENABLE_VOLTAGE_READ_RW\", \"control_word_read_rw\", 1, 1),\n BITWORD(\"CTL_QUICK_STOP_READ_RW\", \"control_word_read_rw\", 2, 1),\n BITWORD(\"CTL_ENABLE_READ_RW\", \"control_word_read_rw\", 3, 1),\n BITWORD(\"CTL_MODE_OF_OPERATION_READ_RW\", \"control_word_read_rw\", 4, 3),\n BITWORD(\"CTL_RESET_FAULT_READ_RW\", \"control_word_read_rw\", 7, 1),\n BITWORD(\"CTL_HALT_READ_RW\", \"control_word_read_rw\", 8, 1),\n BITWORD(\"CTL_ON_WRITE_RW\", \"control_word_write_rw\", 0, 1),\n BITWORD(\"CTL_ENABLE_VOLTAGE_WRITE_RW\", \"control_word_write_rw\", 1, 1),\n BITWORD(\"CTL_QUICK_STOP_WRITE_RW\", \"control_word_write_rw\", 2, 1),\n BITWORD(\"CTL_ENABLE_WRITE_RW\", \"control_word_write_rw\", 3, 1),\n BITWORD(\"CTL_MODE_OF_OPERATION_WRITE_RW\", \"control_word_write_rw\", 4, 3),\n BITWORD(\"CTL_RESET_FAULT_WRITE_RW\", \"control_word_write_rw\", 7, 1),\n BITWORD(\"CTL_HALT_WRITE_RW\", \"control_word_write_rw\", 8, 1),\n// /* HWPR Control Info */\n BITWORD(\"MOVE_TYPE_HWPR\", \"stat_control_hwpr\", 0, 3),\n BITWORD(\"MOVE_STAT_HWPR\", \"stat_control_hwpr\", 3, 3),\n BITWORD(\"FORK_ENGAGED_HWPR\", \"stat_control_hwpr\", 6, 1),\n BITWORD(\"DO_OVERSHOOT_HWPR\", \"stat_control_hwpr\", 7, 1),\n BITWORD(\"DONE_MOVE_HWPR\", \"stat_control_hwpr\", 8, 1),\n BITWORD(\"DONE_ALL_HWPR\", \"stat_control_hwpr\", 9, 1),\n BITWORD(\"DO_DISENGAGE_HWPR\", \"stat_control_hwpr\", 10, 1),\n BITWORD(\"DO_MAIN_MOVE_HWPR\", \"stat_control_hwpr\", 11, 1),\n\n /* CRYO */\n /*BITWORD(\"\",\"dio_heaters\",0,1) */\n BITWORD(\"POT_VALVE\", \"cryostate\", 4, 1),\n BITWORD(\"POT_DIREC\", \"cryostate\", 5, 1),\n BITWORD(\"LHE_VALVE\", \"cryostate\", 6, 1),\n BITWORD(\"CRYO_DIREC\", \"cryostate\", 7, 1),\n BITWORD(\"LN_VALVE\", \"cryostate\", 8, 1),\n BITWORD(\"AUTO_JFET_HEAT\", \"cryostate\", 9, 1),\n\n\n LINCOM2(\"SINCE_START_CYCLE\", \"TIME\", 1, 0, \"START_CYCLE\", -1, 0),\n\n\n COMMENT(\"Cryo Table Lookups\"),\n COMMENT(\"Diodes\"),\n LINCOM(\"TD_CHARCOAL_HS_INT\", \"TD_CHARCOAL_HS\", 0.199204, 0.000054),\n LINCOM(\"TD_VCS2_FILT_INT\", \"TD_VCS2_FILT\", 0.198863, -0.00015),\n LINCOM(\"TD_250FPA_INT\", \"TD_250FPA\", 0.199271, 0.000037),\n LINCOM(\"TD_HWP_INT\", \"TD_HWP\", 0.199518, -0.000016),\n LINCOM(\"TD_VCS1_HX_INT\", \"TD_VCS1_HX\", 0.199721, 0.000025),\n LINCOM(\"TD_1K_FRIDGE_INT\", \"TD_1K_FRIDGE\", 0.199697, 0.000019),\n LINCOM(\"TD_4K_PLATE_INT\", \"TD_4K_PLATE\", 0.198982, 0.000030),\n LINCOM(\"TD_VCS1_FILT_INT\", \"TD_VCS1_FILT\", 0.199619, -0.000064),\n LINCOM(\"TD_M3_INT\", \"TD_M3\", 0.199267, -0.000070),\n LINCOM(\"TD_CHARCOAL_INT\", \"TD_CHARCOAL\", 0.199082, -0.000092),\n LINCOM(\"TD_OB_FILTER_INT\", \"TD_OB_FILTER\", 0.200040, 0.000018),\n LINCOM(\"TD_VCS2_PLATE_INT\", \"TD_VCS2_PLATE\", 0.199134, -0.000079),\n LINCOM(\"TD_M4_INT\", \"TD_M4\", 0.199140, 0.000057),\n LINCOM(\"TD_4K_FILT_INT\", \"TD_4K_FILT\", 0.199656, 0.000034),\n LINCOM(\"TD_VCS2_HX_INT\", \"TD_VCS2_HX\", 0.199033, -0.000013),\n LINCOM(\"TD_VCS1_PLATE_INT\", \"TD_VCS1_PLATE\", 0.199517, -0.000026),\n LINTERP(\"Td_charcoal_hs\", \"TD_CHARCOAL_HS_INT\", LUT_DIR \"dt-simonchase.LUT\"),\n LINTERP(\"Td_vcs2_filt\", \"TD_VCS2_FILT_INT\", LUT_DIR \"dt670_orig.text\"),\n LINTERP(\"Td_250fpa\", \"TD_250FPA_INT\", LUT_DIR \"dt670_orig.text\"),\n LINTERP(\"Td_hwp\", \"TD_HWP_INT\", LUT_DIR \"dt670_orig.text\"),\n LINTERP(\"Td_vcs1_hx\", \"TD_VCS1_HX_INT\", LUT_DIR \"dt670_orig.text\"),\n LINTERP(\"Td_1k_fridge\", \"TD_1K_FRIDGE_INT\", LUT_DIR \"dt670_orig.text\"),\n LINTERP(\"Td_4k_plate\", \"TD_4K_PLATE_INT\", LUT_DIR \"dt670_orig.text\"),\n LINTERP(\"Td_vcs1_filt\", \"TD_VCS1_FILT_INT\", LUT_DIR \"dt670_orig.text\"),\n LINTERP(\"Td_m3\", \"TD_M3_INT\", LUT_DIR \"dt670_orig.text\"),\n LINTERP(\"Td_charcoal\", \"TD_CHARCOAL_INT\", LUT_DIR \"dt670_orig.text\"),\n LINTERP(\"Td_ob_filter\", \"TD_OB_FILTER_INT\", LUT_DIR \"dt670_orig.text\"),\n LINTERP(\"Td_vcs2_plate\", \"TD_VCS2_PLATE_INT\", LUT_DIR \"dt-simonchase.LUT\"),\n LINTERP(\"Td_m4\", \"TD_M4_INT\", LUT_DIR \"dt670_orig.text\"),\n LINTERP(\"Td_4k_filt\", \"TD_4K_FILT_INT\", LUT_DIR \"dt670_orig.text\"),\n LINTERP(\"Td_vcs2_hx\", \"TD_VCS2_HX_INT\", LUT_DIR \"dt670_orig.text\"),\n LINTERP(\"Td_vcs1_plate\", \"TD_VCS1_PLATE_INT\", LUT_DIR \"dt670_orig.text\"),\n\n COMMENT(\"Highbay stuff\"), // raw calibration only -- warning!\n LINCOM(\"Nitrogen_Flow\", \"N2_FLOW_V\", 20, 0), // in L/min\n LINCOM(\"He_Blowoff\", \"HE_BLOW_V\", 3, 0),\n LINCOM(\"He_Pot_Hi_Flow\", \"HE_POT_HI_FLOW_V\", 1, 0),\n LINCOM(\"He_Pot_Lo_Flow\", \"HE_POT_LO_FLOW_V\", 20, 0),\n LINCOM(\"He_Pot_Purge\", \"HE_PURGE_FLOW_V\", 200, 0), // in mL/min\n LINCOM(\"Alarm_gauge\", \"ALARM_GAUGE\", 12.367, -24.83),\n\n\n COMMENT(\"ROXes\"), // raw calibration only -- warning!\n LINCOM(\"TR_FPA_1K_INT\", \"TR_FPA_1K\", -1, 0),\n LINCOM(\"TR_250_FPA_INT\", \"TR_250_FPA\", -1, 0),\n LINCOM(\"TR_1K_PLATE_INT\", \"TR_1K_PLATE\", -1, 0),\n LINCOM(\"TR_300MK_STRAP_INT\", \"TR_300MK_STRAP\", -1, 0),\n LINCOM(\"TR_350_FPA_INT\", \"TR_350_FPA\", -1, 0),\n LINCOM(\"TR_HE4_POT_INT\", \"TR_HE4_POT\", -1, 0),\n LINCOM(\"TR_HE3_FRIDGE_INT\", \"TR_HE3_FRIDGE\", -1, 0),\n LINCOM(\"TR_500_FPA_INT\", \"TR_500_FPA\", -1, 0),\n LINCOM(\"ROX_BIAS_INT\", \"ROX_BIAS\", -1, 0),\n LINTERP(\"NOMINAL_BIAS\", \"ROX_BIAS_INT\", LUT_DIR \"Vbias_LUT.txt\"),\n LINCOM(\"ROX_BIAS_COMPARE\", \"ROX_BIAS_INT\", 3.296602587, 0),\n DIVIDE(\"TR_FPA_1K_CORRECTED\", \"TR_FPA_1K_INT\", \"ROX_BIAS_COMPARE\"),\n DIVIDE(\"TR_250_FPA_CORRECTED\", \"TR_250_FPA_INT\", \"ROX_BIAS_COMPARE\"),\n DIVIDE(\"TR_1K_PLATE_CORRECTED\", \"TR_1K_PLATE_INT\", \"ROX_BIAS_COMPARE\"),\n DIVIDE(\"TR_300MK_STRAP_CORRECTED\", \"TR_300MK_STRAP_INT\", \"ROX_BIAS_COMPARE\"),\n DIVIDE(\"TR_350_FPA_CORRECTED\", \"TR_350_FPA_INT\", \"ROX_BIAS_COMPARE\"),\n DIVIDE(\"TR_HE4_POT_CORRECTED\", \"TR_HE4_POT_INT\", \"ROX_BIAS_COMPARE\"),\n DIVIDE(\"TR_HE3_FRIDGE_CORRECTED\", \"TR_HE3_FRIDGE_INT\", \"ROX_BIAS_COMPARE\"),\n DIVIDE(\"TR_500_FPA_CORRECTED\", \"TR_500_FPA_INT\", \"ROX_BIAS_COMPARE\"),\n LINTERP(\"RR_FPA_1K\", \"TR_FPA_1K_CORRECTED\", LUT_DIR \"VR_LUT_fpa1k.txt\"),\n LINTERP(\"RR_250_FPA\", \"TR_250_FPA_CORRECTED\", LUT_DIR \"VR_LUT_fpa250.txt\"),\n LINTERP(\"RR_1K_PLATE\", \"TR_1K_PLATE_CORRECTED\", LUT_DIR \"VR_LUT_plate1k.txt\"),\n LINTERP(\"RR_300MK_STRAP\", \"TR_300MK_STRAP_CORRECTED\", LUT_DIR \"VR_LUT_strap300mk.txt\"),\n LINTERP(\"RR_350_FPA\", \"TR_350_FPA_CORRECTED\", LUT_DIR \"VR_LUT_fpa350.txt\"),\n LINTERP(\"RR_HE4_POT\", \"TR_HE4_POT_CORRECTED\", LUT_DIR \"VR_LUT_he4pot.txt\"),\n LINTERP(\"RR_HE3_FRIDGE\", \"TR_HE3_FRIDGE_CORRECTED\", LUT_DIR \"VR_LUT_he3fridge.txt\"),\n LINTERP(\"RR_500_FPA\", \"TR_500_FPA_CORRECTED\", LUT_DIR \"VR_LUT_fpa500.txt\"),\n LINCOM(\"Resistance_correction\", \"RR_300MK_STRAP\", 0.0002, 0),\n// corrected for drifts in CBOB?\n DIVIDE(\"CRR_FPA_1K\", \"RR_FPA_1K\", \"Resistance_correction\"),\n DIVIDE(\"CRR_250_FPA\", \"RR_250_FPA\", \"Resistance_correction\"),\n DIVIDE(\"CRR_1K_PLATE\", \"RR_1K_PLATE\", \"Resistance_correction\"),\n DIVIDE(\"CRR_300MK_STRAP\", \"RR_300MK_STRAP\", \"Resistance_correction\"),\n DIVIDE(\"CRR_350_FPA\", \"RR_350_FPA\", \"Resistance_correction\"),\n DIVIDE(\"CRR_HE4_POT\", \"RR_HE4_POT\", \"Resistance_correction\"),\n DIVIDE(\"CRR_HE3_FRIDGE\", \"RR_HE3_FRIDGE\", \"Resistance_correction\"),\n DIVIDE(\"CRR_500_FPA\", \"RR_500_FPA\", \"Resistance_correction\"),\n// corrected temps?\n LINTERP(\"CTr_fpa_1k\", \"CRR_FPA_1K\", LUT_DIR \"rox-raw.txt\"),\n UNITS(\"CTr_fpa_1k\", \"Temperature\", \"K\"),\n LINTERP(\"CTr_250_fpa\", \"CRR_250_FPA\" , LUT_DIR \"rox-raw.txt\"),\n UNITS(\"CTr_250_fpa\", \"Temperature\", \"K\"),\n LINTERP(\"CTr_1k_plate\", \"CRR_1K_PLATE\", LUT_DIR \"rox-raw.txt\"),\n UNITS(\"CTr_1k_plate\", \"Temperature\", \"K\"),\n LINTERP(\"CTr_300mk_strap\", \"CRR_300MK_STRAP\", LUT_DIR \"rox-raw.txt\"),\n UNITS(\"CTr_300mk_strap\", \"Temperature\", \"K\"),\n LINTERP(\"CTr_350_fpa\", \"CRR_350_FPA\" , LUT_DIR \"rox-raw.txt\"),\n UNITS(\"CTr_350_fpa\", \"Temperature\", \"K\"),\n LINTERP(\"CTr_he4_pot\", \"CRR_HE4_POT\" , LUT_DIR \"rox-raw.txt\"),\n UNITS(\"CTr_he4_pot\", \"Temperature\", \"K\"),\n LINTERP(\"CTr_he3_fridge\", \"CRR_HE3_FRIDGE\" , LUT_DIR \"rox-he3.txt\"),\n UNITS(\"CTr_he3_fridge\", \"Temperature\", \"K\"),\n LINTERP(\"CTr_500_fpa\", \"CRR_500_FPA\", LUT_DIR \"ROX_Cal_U04486.LUT\"),\n UNITS(\"CTr_500_fpa\", \"Temperature\", \"K\"),\n\n\n LINTERP(\"Tr_fpa_1k\", \"RR_FPA_1K\", LUT_DIR \"rox-raw.txt\"),\n UNITS(\"Tr_fpa_1k\", \"Temperature\", \"K\"),\n LINTERP(\"Tr_250_fpa\", \"RR_250_FPA\" , LUT_DIR \"ROX_Cal_U04486.LUT\"),\n UNITS(\"Tr_250_fpa\", \"Temperature\", \"K\"),\n LINTERP(\"Tr_1k_plate\", \"RR_1K_PLATE\", LUT_DIR \"rox-raw.txt\"),\n UNITS(\"Tr_1k_plate\", \"Temperature\", \"K\"),\n LINTERP(\"Tr_300mk_strap\", \"RR_300MK_STRAP\", LUT_DIR \"rox-raw.txt\"),\n UNITS(\"Tr_300mk_strap\", \"Temperature\", \"K\"),\n LINTERP(\"Tr_350_fpa\", \"RR_350_FPA\" , LUT_DIR \"rox-raw.txt\"),\n UNITS(\"Tr_350_fpa\", \"Temperature\", \"K\"),\n LINTERP(\"Tr_he4_pot\", \"RR_HE4_POT\" , LUT_DIR \"rox-raw.txt\"),\n UNITS(\"Tr_he4_pot\", \"Temperature\", \"K\"),\n LINTERP(\"Tr_he3_fridge\", \"RR_HE3_FRIDGE\" , LUT_DIR \"rox-he3.txt\"),\n UNITS(\"Tr_he3_fridge\", \"Temperature\", \"K\"),\n LINTERP(\"Tr_500_fpa\", \"RR_500_FPA\", LUT_DIR \"rox-raw.txt\"),\n UNITS(\"Tr_500_fpa\", \"Temperature\", \"K\"),\n // cryo labjack stuff below\n LINCOM(\"Helium_level_inches\", \"LEVEL_SENSOR_READ\", 4.598, 28.307),\n LINTERP(\"Helium_volume_liters\", \"Helium_level_inches\", LUT_DIR \"LevelSensor_Volume.LUT\"),\n LINCOM(\"Alarm_gauge_pressure\", \"ALARM_GAUGE\", 12.367, -24.83),\n // Roach Channels\n BITWORD(\"SCAN_RETUNE_TOP_TRIGGER_ROACH\", \"scan_retune_trigger_roach\", 0, 1),\n BITWORD(\"SCAN_RETUNE_BOTTOM_TRIGGER_ROACH\", \"scan_retune_trigger_roach\", 1, 1),\n BITWORD(\"HAS_QDR_CAL_ROACH1\", \"status_roach1\", 0, 1),\n BITWORD(\"FULL_LOOP_FAIL_ROACH1\", \"status_roach1\", 1, 1),\n BITWORD(\"HAS_TARG_TONES_ROACH1\", \"status_roach1\", 2, 1),\n BITWORD(\"IS_STREAMING_ROACH1\", \"status_roach1\", 3, 1),\n BITWORD(\"IS_SWEEPING_ROACH1\", \"status_roach1\", 4, 2),\n BITWORD(\"HAS_VNA_SWEEP_ROACH1\", \"status_roach1\", 6, 1),\n BITWORD(\"HAS_TARG_SWEEP_ROACH1\", \"status_roach1\", 7, 1),\n BITWORD(\"WRITE_FLAG_ROACH1\", \"status_roach1\", 8, 1),\n BITWORD(\"HAS_REF_PARAMS_ROACH1\", \"status_roach1\", 9, 1),\n BITWORD(\"EXT_REF_ROACH1\", \"status_roach1\", 10, 1),\n BITWORD(\"HAS_VNA_TONES_ROACH1\", \"status_roach1\", 11, 1),\n BITWORD(\"SWEEP_FAIL_ROACH1\", \"status_roach1\", 12, 1),\n BITWORD(\"QDR_CAL_FAIL_ROACH1\", \"status_roach1\", 13, 1),\n BITWORD(\"FIRMWARE_UPLOAD_FAIL_ROACH1\", \"status_roach1\", 14, 1),\n BITWORD(\"HAS_FIRMWARE_ROACH1\", \"status_roach1\", 15, 1),\n BITWORD(\"TONE_FINDING_ERROR_ROACH1\", \"status_roach1\", 16, 2),\n BITWORD(\"KATCP_CONNECT_ERROR_ROACH1\", \"status_roach1\", 18, 1),\n BITWORD(\"IS_COMPRESSING_ROACH1\", \"status_roach1\", 19, 1),\n BITWORD(\"DOING_FULL_LOOP_ROACH1\", \"status_roach1\", 20, 1),\n BITWORD(\"DOING_FIND_KIDS_LOOP_ROACH1\", \"status_roach1\", 21, 1),\n BITWORD(\"IS_FINDING_KIDS_ROACH1\", \"status_roach1\", 22, 1),\n BITWORD(\"TRNAROUND_LOOP_FAIL_ROACH1\", \"status_roach1\", 23, 1),\n BITWORD(\"DOING_TURNAROUND_LOOP_ROACH1\", \"status_roach1\", 24, 1),\n BITWORD(\"AUTO_ALLOW_TRNAROUND_LOOP_ROACH1\", \"status_roach1\", 25, 1),\n BITWORD(\"ALLOW_CHOP_LO_ROACH1\", \"status_roach1\", 26, 1),\n // BITWORD(\"IS_CHOPPING_LO_ROACH1\", \"status_roach1\", 27, 1),\n BITWORD(\"PI_REBOOT_WARNING_ROACH1\", \"status_roach1\", 28, 1),\n BITWORD(\"DATA_STREAM_ERROR_ROACH1\", \"status_roach1\", 29, 1),\n BITWORD(\"WAITING_FOR_LAMP_ROACH1\", \"status_roach1\", 30, 1),\n BITWORD(\"HAS_LAMP_CONTROL_ROACH1\", \"status_roach1\", 31, 1),\n\n BITWORD(\"HAS_QDR_CAL_ROACH2\", \"status_roach2\", 0, 1),\n BITWORD(\"FULL_LOOP_FAIL_ROACH2\", \"status_roach2\", 1, 1),\n BITWORD(\"HAS_TARG_TONES_ROACH2\", \"status_roach2\", 2, 1),\n BITWORD(\"IS_STREAMING_ROACH2\", \"status_roach2\", 3, 1),\n BITWORD(\"IS_SWEEPING_ROACH2\", \"status_roach2\", 4, 2),\n BITWORD(\"HAS_VNA_SWEEP_ROACH2\", \"status_roach2\", 6, 1),\n BITWORD(\"HAS_TARG_SWEEP_ROACH2\", \"status_roach2\", 7, 1),\n BITWORD(\"WRITE_FLAG_ROACH2\", \"status_roach2\", 8, 1),\n BITWORD(\"HAS_REF_PARAMS_ROACH2\", \"status_roach2\", 9, 1),\n BITWORD(\"EXT_REF_ROACH2\", \"status_roach2\", 10, 1),\n BITWORD(\"HAS_VNA_TONES_ROACH2\", \"status_roach2\", 11, 1),\n BITWORD(\"SWEEP_FAIL_ROACH2\", \"status_roach2\", 12, 1),\n BITWORD(\"QDR_CAL_FAIL_ROACH2\", \"status_roach2\", 13, 1),\n BITWORD(\"FIRMWARE_UPLOAD_FAIL_ROACH2\", \"status_roach2\", 14, 1),\n BITWORD(\"HAS_FIRMWARE_ROACH2\", \"status_roach2\", 15, 1),\n BITWORD(\"TONE_FINDING_ERROR_ROACH2\", \"status_roach2\", 16, 2),\n BITWORD(\"KATCP_CONNECT_ERROR_ROACH2\", \"status_roach2\", 18, 1),\n BITWORD(\"IS_COMPRESSING_ROACH2\", \"status_roach2\", 19, 1),\n BITWORD(\"DOING_FULL_LOOP_ROACH2\", \"status_roach2\", 20, 1),\n BITWORD(\"DOING_FIND_KIDS_LOOP_ROACH2\", \"status_roach2\", 21, 1),\n BITWORD(\"IS_FINDING_KIDS_ROACH2\", \"status_roach2\", 22, 1),\n BITWORD(\"TRNAROUND_LOOP_FAIL_ROACH2\", \"status_roach2\", 23, 1),\n BITWORD(\"DOING_TURNAROUND_LOOP_ROACH2\", \"status_roach2\", 24, 1),\n BITWORD(\"AUTO_ALLOW_TRNAROUND_LOOP_ROACH2\", \"status_roach2\", 25, 1),\n BITWORD(\"ALLOW_CHOP_LO_ROACH2\", \"status_roach2\", 26, 1),\n // BITWORD(\"IS_CHOPPING_LO_ROACH2\", \"status_roach2\", 27, 1),\n BITWORD(\"PI_REBOOT_WARNING_ROACH2\", \"status_roach2\", 28, 1),\n BITWORD(\"DATA_STREAM_ERROR_ROACH2\", \"status_roach2\", 29, 1),\n BITWORD(\"WAITING_FOR_LAMP_ROACH2\", \"status_roach2\", 30, 1),\n BITWORD(\"HAS_LAMP_CONTROL_ROACH2\", \"status_roach2\", 31, 1),\n\n BITWORD(\"HAS_QDR_CAL_ROACH3\", \"status_roach3\", 0, 1),\n BITWORD(\"FULL_LOOP_FAIL_ROACH3\", \"status_roach3\", 1, 1),\n BITWORD(\"HAS_TARG_TONES_ROACH3\", \"status_roach3\", 2, 1),\n BITWORD(\"IS_STREAMING_ROACH3\", \"status_roach3\", 3, 1),\n BITWORD(\"IS_SWEEPING_ROACH3\", \"status_roach3\", 4, 2),\n BITWORD(\"HAS_VNA_SWEEP_ROACH3\", \"status_roach3\", 6, 1),\n BITWORD(\"HAS_TARG_SWEEP_ROACH3\", \"status_roach3\", 7, 1),\n BITWORD(\"WRITE_FLAG_ROACH3\", \"status_roach3\", 8, 1),\n BITWORD(\"HAS_REF_PARAMS_ROACH3\", \"status_roach3\", 9, 1),\n BITWORD(\"EXT_REF_ROACH3\", \"status_roach3\", 10, 1),\n BITWORD(\"HAS_VNA_TONES_ROACH3\", \"status_roach3\", 11, 1),\n BITWORD(\"SWEEP_FAIL_ROACH3\", \"status_roach3\", 12, 1),\n BITWORD(\"QDR_CAL_FAIL_ROACH3\", \"status_roach3\", 13, 1),\n BITWORD(\"FIRMWARE_UPLOAD_FAIL_ROACH3\", \"status_roach3\", 14, 1),\n BITWORD(\"HAS_FIRMWARE_ROACH3\", \"status_roach3\", 15, 1),\n BITWORD(\"TONE_FINDING_ERROR_ROACH3\", \"status_roach3\", 16, 2),\n BITWORD(\"KATCP_CONNECT_ERROR_ROACH3\", \"status_roach3\", 18, 1),\n BITWORD(\"IS_COMPRESSING_ROACH3\", \"status_roach3\", 19, 1),\n BITWORD(\"DOING_FULL_LOOP_ROACH3\", \"status_roach3\", 20, 1),\n BITWORD(\"DOING_FIND_KIDS_LOOP_ROACH3\", \"status_roach3\", 21, 1),\n BITWORD(\"IS_FINDING_KIDS_ROACH3\", \"status_roach3\", 22, 1),\n BITWORD(\"TRNAROUND_LOOP_FAIL_ROACH3\", \"status_roach3\", 23, 1),\n BITWORD(\"DOING_TURNAROUND_LOOP_ROACH3\", \"status_roach3\", 24, 1),\n BITWORD(\"AUTO_ALLOW_TRNAROUND_LOOP_ROACH3\", \"status_roach3\", 25, 1),\n BITWORD(\"ALLOW_CHOP_LO_ROACH3\", \"status_roach3\", 26, 1),\n // BITWORD(\"IS_CHOPPING_LO_ROACH3\", \"status_roach3\", 27, 1),\n BITWORD(\"PI_REBOOT_WARNING_ROACH3\", \"status_roach3\", 28, 1),\n BITWORD(\"DATA_STREAM_ERROR_ROACH3\", \"status_roach3\", 29, 1),\n BITWORD(\"WAITING_FOR_LAMP_ROACH3\", \"status_roach3\", 30, 1),\n BITWORD(\"HAS_LAMP_CONTROL_ROACH3\", \"status_roach3\", 31, 1),\n\n BITWORD(\"HAS_QDR_CAL_ROACH4\", \"status_roach4\", 0, 1),\n BITWORD(\"FULL_LOOP_FAIL_ROACH4\", \"status_roach4\", 1, 1),\n BITWORD(\"HAS_TARG_TONES_ROACH4\", \"status_roach4\", 2, 1),\n BITWORD(\"IS_STREAMING_ROACH4\", \"status_roach4\", 3, 1),\n BITWORD(\"IS_SWEEPING_ROACH4\", \"status_roach4\", 4, 2),\n BITWORD(\"HAS_VNA_SWEEP_ROACH4\", \"status_roach4\", 6, 1),\n BITWORD(\"HAS_TARG_SWEEP_ROACH4\", \"status_roach4\", 7, 1),\n BITWORD(\"WRITE_FLAG_ROACH4\", \"status_roach4\", 8, 1),\n BITWORD(\"HAS_REF_PARAMS_ROACH4\", \"status_roach4\", 9, 1),\n BITWORD(\"EXT_REF_ROACH4\", \"status_roach4\", 10, 1),\n BITWORD(\"HAS_VNA_TONES_ROACH4\", \"status_roach4\", 11, 1),\n BITWORD(\"SWEEP_FAIL_ROACH4\", \"status_roach4\", 12, 1),\n BITWORD(\"QDR_CAL_FAIL_ROACH4\", \"status_roach4\", 13, 1),\n BITWORD(\"FIRMWARE_UPLOAD_FAIL_ROACH4\", \"status_roach4\", 14, 1),\n BITWORD(\"HAS_FIRMWARE_ROACH4\", \"status_roach4\", 15, 1),\n BITWORD(\"TONE_FINDING_ERROR_ROACH4\", \"status_roach4\", 16, 2),\n BITWORD(\"KATCP_CONNECT_ERROR_ROACH4\", \"status_roach4\", 18, 1),\n BITWORD(\"IS_COMPRESSING_ROACH4\", \"status_roach4\", 19, 1),\n BITWORD(\"DOING_FULL_LOOP_ROACH4\", \"status_roach4\", 20, 1),\n BITWORD(\"DOING_FIND_KIDS_LOOP_ROACH4\", \"status_roach4\", 21, 1),\n BITWORD(\"IS_FINDING_KIDS_ROACH4\", \"status_roach4\", 22, 1),\n BITWORD(\"TRNAROUND_LOOP_FAIL_ROACH4\", \"status_roach4\", 23, 1),\n BITWORD(\"DOING_TURNAROUND_LOOP_ROACH4\", \"status_roach4\", 24, 1),\n BITWORD(\"AUTO_ALLOW_TRNAROUND_LOOP_ROACH4\", \"status_roach4\", 25, 1),\n BITWORD(\"ALLOW_CHOP_LO_ROACH4\", \"status_roach4\", 26, 1),\n // BITWORD(\"IS_CHOPPING_LO_ROACH4\", \"status_roach4\", 27, 1),\n BITWORD(\"PI_REBOOT_WARNING_ROACH4\", \"status_roach4\", 28, 1),\n BITWORD(\"DATA_STREAM_ERROR_ROACH4\", \"status_roach4\", 29, 1),\n BITWORD(\"WAITING_FOR_LAMP_ROACH4\", \"status_roach4\", 30, 1),\n BITWORD(\"HAS_LAMP_CONTROL_ROACH4\", \"status_roach4\", 31, 1),\n\n BITWORD(\"HAS_QDR_CAL_ROACH5\", \"status_roach5\", 0, 1),\n BITWORD(\"FULL_LOOP_FAIL_ROACH5\", \"status_roach5\", 1, 1),\n BITWORD(\"HAS_TARG_TONES_ROACH5\", \"status_roach5\", 2, 1),\n BITWORD(\"IS_STREAMING_ROACH5\", \"status_roach5\", 3, 1),\n BITWORD(\"IS_SWEEPING_ROACH5\", \"status_roach5\", 4, 2),\n BITWORD(\"HAS_VNA_SWEEP_ROACH5\", \"status_roach5\", 6, 1),\n BITWORD(\"HAS_TARG_SWEEP_ROACH5\", \"status_roach5\", 7, 1),\n BITWORD(\"WRITE_FLAG_ROACH5\", \"status_roach5\", 8, 1),\n BITWORD(\"HAS_REF_PARAMS_ROACH5\", \"status_roach5\", 9, 1),\n BITWORD(\"EXT_REF_ROACH5\", \"status_roach5\", 10, 1),\n BITWORD(\"HAS_VNA_TONES_ROACH5\", \"status_roach5\", 11, 1),\n BITWORD(\"SWEEP_FAIL_ROACH5\", \"status_roach5\", 12, 1),\n BITWORD(\"QDR_CAL_FAIL_ROACH5\", \"status_roach5\", 13, 1),\n BITWORD(\"FIRMWARE_UPLOAD_FAIL_ROACH5\", \"status_roach5\", 14, 1),\n BITWORD(\"HAS_FIRMWARE_ROACH5\", \"status_roach5\", 15, 1),\n BITWORD(\"TONE_FINDING_ERROR_ROACH5\", \"status_roach5\", 16, 2),\n BITWORD(\"KATCP_CONNECT_ERROR_ROACH5\", \"status_roach5\", 18, 1),\n BITWORD(\"IS_COMPRESSING_ROACH5\", \"status_roach5\", 19, 1),\n BITWORD(\"DOING_FULL_LOOP_ROACH5\", \"status_roach5\", 20, 1),\n BITWORD(\"DOING_FIND_KIDS_LOOP_ROACH5\", \"status_roach5\", 21, 1),\n BITWORD(\"IS_FINDING_KIDS_ROACH5\", \"status_roach5\", 22, 1),\n BITWORD(\"TRNAROUND_LOOP_FAIL_ROACH5\", \"status_roach5\", 23, 1),\n BITWORD(\"DOING_TURNAROUND_LOOP_ROACH5\", \"status_roach5\", 24, 1),\n BITWORD(\"AUTO_ALLOW_TRNAROUND_LOOP_ROACH5\", \"status_roach5\", 25, 1),\n BITWORD(\"ALLOW_CHOP_LO_ROACH5\", \"status_roach5\", 26, 1),\n // BITWORD(\"IS_CHOPPING_LO_ROACH5\", \"status_roach5\", 27, 1),\n BITWORD(\"PI_REBOOT_WARNING_ROACH5\", \"status_roach5\", 28, 1),\n BITWORD(\"DATA_STREAM_ERROR_ROACH5\", \"status_roach5\", 29, 1),\n BITWORD(\"WAITING_FOR_LAMP_ROACH5\", \"status_roach5\", 30, 1),\n BITWORD(\"HAS_LAMP_CONTROL_ROACH5\", \"status_roach5\", 31, 1),\n\n // clinometer channels\n LINCOM(\"Clin_of_x\", \"CLIN_OF_X\", 10, 0),\n LINCOM(\"Clin_of_y\", \"CLIN_OF_Y\", 10, 0),\n LINCOM(\"Clin_of_t\", \"CLIN_OF_T\", 100, 273.15),\n LINCOM(\"Clin_if_x\", \"CLIN_IF_X\", 10, 0),\n LINCOM(\"Clin_if_y\", \"CLIN_IF_Y\", 10, 0),\n LINCOM(\"Clin_if_t\", \"CLIN_IF_T\", 100, 273.15),\n\n // status channels\n BITWORD(\"Hd_pv_status\", \"of_status\", 0, 1),\n BITWORD(\"Eth_switch_status\", \"of_status\", 1, 1),\n BITWORD(\"Fc1_status\", \"of_status\", 2, 1),\n BITWORD(\"Xsc1_status\", \"of_status\", 3, 1),\n BITWORD(\"Fc2_status\", \"of_status\", 4, 1),\n BITWORD(\"Xsc0_status\", \"of_status\", 5, 1),\n BITWORD(\"Gyros_status\", \"of_status\", 6, 1),\n BITWORD(\"Data_transmit_status\", \"of_status\", 7, 1),\n BITWORD(\"Elmot_status\", \"of_status\", 8, 1),\n BITWORD(\"Pivot_status\", \"of_status\", 9, 1),\n BITWORD(\"Mag_status\", \"of_status\", 10, 1),\n BITWORD(\"Rw_status\", \"of_status\", 11, 1),\n BITWORD(\"Steppers_status\", \"of_status\", 12, 1),\n BITWORD(\"Clino_status\", \"of_status\", 13, 1),\n BITWORD(\"Gps_timing_status\", \"of_status\", 15, 1),\n // thermistors below!\n LINTERP(\"Rt_therm1\", \"THERMISTOR_1\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm2\", \"THERMISTOR_2\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm3\", \"THERMISTOR_3\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm4\", \"THERMISTOR_4\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm5\", \"THERMISTOR_5\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm6\", \"THERMISTOR_6\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm7\", \"THERMISTOR_7\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm8\", \"THERMISTOR_8\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm9\", \"THERMISTOR_9\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm10\", \"THERMISTOR_10\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm11\", \"THERMISTOR_11\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm12\", \"THERMISTOR_12\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm13\", \"THERMISTOR_13\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm14\", \"THERMISTOR_14\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm15\", \"THERMISTOR_15\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm16\", \"THERMISTOR_16\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm17\", \"THERMISTOR_17\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm18\", \"THERMISTOR_18\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm19\", \"THERMISTOR_19\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm20\", \"THERMISTOR_20\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm21\", \"THERMISTOR_21\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm22\", \"THERMISTOR_22\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm23\", \"THERMISTOR_23\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm24\", \"THERMISTOR_24\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm25\", \"THERMISTOR_25\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm26\", \"THERMISTOR_26\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm27\", \"THERMISTOR_27\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm28\", \"THERMISTOR_28\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm29\", \"THERMISTOR_29\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm30\", \"THERMISTOR_30\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm31\", \"THERMISTOR_31\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm32\", \"THERMISTOR_32\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm33\", \"THERMISTOR_33\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm34\", \"THERMISTOR_34\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm35\", \"THERMISTOR_35\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm36\", \"THERMISTOR_36\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm37\", \"THERMISTOR_37\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm38\", \"THERMISTOR_38\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm39\", \"THERMISTOR_39\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm40\", \"THERMISTOR_40\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm41\", \"THERMISTOR_41\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm42\", \"THERMISTOR_42\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm43\", \"THERMISTOR_43\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm44\", \"THERMISTOR_44\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm45\", \"THERMISTOR_45\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm46\", \"THERMISTOR_46\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm47\", \"THERMISTOR_47\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm48\", \"THERMISTOR_48\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm49\", \"THERMISTOR_49\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm50\", \"THERMISTOR_50\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm51\", \"THERMISTOR_51\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm52\", \"THERMISTOR_52\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm53\", \"THERMISTOR_53\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm54\", \"THERMISTOR_54\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm55\", \"THERMISTOR_55\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm56\", \"THERMISTOR_56\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm57\", \"THERMISTOR_57\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm58\", \"THERMISTOR_58\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm59\", \"THERMISTOR_59\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm60\", \"THERMISTOR_60\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm61\", \"THERMISTOR_61\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm62\", \"THERMISTOR_62\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm63\", \"THERMISTOR_63\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm64\", \"THERMISTOR_64\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm65\", \"THERMISTOR_65\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm66\", \"THERMISTOR_66\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm67\", \"THERMISTOR_67\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm68\", \"THERMISTOR_68\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm69\", \"THERMISTOR_69\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm70\", \"THERMISTOR_70\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm71\", \"THERMISTOR_71\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm72\", \"THERMISTOR_72\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm73\", \"THERMISTOR_73\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Rt_therm74\", \"THERMISTOR_74\", LUT_DIR \"Thermistor_VtoR.lut\"),\n\n LINTERP(\"Micro_rt_therm1\", \"MICRO_THERMISTOR_1\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Micro_rt_therm2\", \"MICRO_THERMISTOR_2\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Micro_rt_therm3\", \"MICRO_THERMISTOR_3\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Micro_rt_therm4\", \"MICRO_THERMISTOR_4\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Micro_rt_therm5\", \"MICRO_THERMISTOR_5\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Micro_rt_therm6\", \"MICRO_THERMISTOR_6\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Micro_rt_therm7\", \"MICRO_THERMISTOR_7\", LUT_DIR \"Thermistor_VtoR.lut\"),\n LINTERP(\"Micro_rt_therm8\", \"MICRO_THERMISTOR_8\", LUT_DIR \"Thermistor_VtoR.lut\"),\n\n LINTERP(\"Tt_if_front\", \"Rt_therm1\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_if_back\", \"Rt_therm2\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_lock_motor\", \"Rt_therm3\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_if_starboard\", \"Rt_therm4\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_if_plate\", \"Rt_therm5\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_if_port\", \"Rt_therm6\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_cryostat_front\", \"Rt_therm7\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_roach_top\", \"Rt_therm8\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_roach_port\", \"Rt_therm9\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_roach_starboard\", \"Rt_therm10\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_if_power_bob\", \"Rt_therm11\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_if_eth_switch\", \"Rt_therm12\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_rec_power\", \"Rt_therm13\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_rec\", \"Rt_therm14\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_timing_box\", \"Rt_therm15\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_sc1\", \"Rt_therm16\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_sc2\", \"Rt_therm17\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_fc2\", \"Rt_therm18\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_gyro_2\", \"Rt_therm19\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_bal_sys\", \"Rt_therm20\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_cryostat_lid\", \"Rt_therm21\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_of_port\", \"Rt_therm22\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_m1_back_port\", \"Rt_therm23\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_ob_back_port\", \"Rt_therm24\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_m1_front_bottom\", \"Rt_therm25\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_strut_3_far\", \"Rt_therm26\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_strut_2_mid\", \"Rt_therm27\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_m1_back_top\", \"Rt_therm29\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_if_lj_bob\", \"Rt_therm30\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_ob_front_port\", \"Rt_therm31\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_of_front\", \"Rt_therm32\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_of_batt_port\", \"Rt_therm33\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_el_motor\", \"Rt_therm34\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_gyro_1\", \"Rt_therm35\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_of_port_deck\", \"Rt_therm36\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_m2_back\", \"Rt_therm37\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_m1_back_bottom\", \"Rt_therm38\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_sunshield_rear\", \"Rt_therm39\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_hdd_1\", \"Rt_therm40\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_solar_1_br\", \"Rt_therm41\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_solar_2_tr\", \"Rt_therm42\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_m1_back_starboard\", \"Rt_therm43\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_sunshield_chin\", \"Rt_therm44\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_of_port_aframe\", \"Rt_therm45\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_of_starboard\", \"Rt_therm46\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_rw_motor\", \"Rt_therm47\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_of_gps\", \"Rt_therm48\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_of_power_box\", \"Rt_therm49\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_m2_push_plate\", \"Rt_therm50\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_ob_front_starboard\", \"Rt_therm51\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_if_batt_starboard\", \"Rt_therm52\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_strut_3_near\", \"Rt_therm53\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_solar_1_tl\", \"Rt_therm54\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_solar_2_bl\", \"Rt_therm55\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_pivot\", \"Rt_therm56\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_ob_back_starboard\", \"Rt_therm57\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_hdd_2\", \"Rt_therm58\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_m2_act\", \"Rt_therm59\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_roach2_fpga\", \"Rt_therm63\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_roach5_fpga\", \"Rt_therm64\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_roach4_fpga\", \"Rt_therm65\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_roach1_fpga\", \"Rt_therm66\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_roach3_fpga\", \"Rt_therm67\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_roach4_ppc\", \"Rt_therm68\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_roach1_ppc\", \"Rt_therm69\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_roach3_ppc\", \"Rt_therm70\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_roach2_ppc\", \"Rt_therm71\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_roach5_ppc\", \"Rt_therm72\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_of_lj_1\", \"Rt_therm73\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_of_lj_2\", \"Rt_therm74\", LUT_DIR \"Thermistor_RtoT.lut\"),\n\n LINTERP(\"Tt_if_aalborg\", \"Micro_rt_therm1\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_aalborg_a\", \"Micro_rt_therm2\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_aalborg_b\", \"Micro_rt_therm3\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_science_sphere\", \"Micro_rt_therm4\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_pump_b\", \"Micro_rt_therm5\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_pump_a\", \"Micro_rt_therm6\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_pv_b\", \"Micro_rt_therm7\", LUT_DIR \"Thermistor_RtoT.lut\"),\n LINTERP(\"Tt_pv_a\", \"Micro_rt_therm8\", LUT_DIR \"Thermistor_RtoT.lut\"),\n\n BITWORD(\"Labjack0_conn_status\", \"labjack_conn_status\", 0, 1),\n BITWORD(\"Labjack1_conn_status\", \"labjack_conn_status\", 1, 1),\n BITWORD(\"Labjack2_conn_status\", \"labjack_conn_status\", 2, 1),\n BITWORD(\"Labjack3_conn_status\", \"labjack_conn_status\", 3, 1),\n BITWORD(\"Labjack4_conn_status\", \"labjack_conn_status\", 4, 1),\n BITWORD(\"Labjack5_conn_status\", \"labjack_conn_status\", 5, 1),\n BITWORD(\"Labjack6_conn_status\", \"labjack_conn_status\", 6, 1),\n BITWORD(\"Labjack7_conn_status\", \"labjack_conn_status\", 7, 1),\n BITWORD(\"Labjack8_conn_status\", \"labjack_conn_status\", 8, 1),\n BITWORD(\"Labjack9_conn_status\", \"labjack_conn_status\", 9, 1),\n BITWORD(\"Labjack10_conn_status\", \"labjack_conn_status\", 10, 1),\n\n BITWORD(\"TRIGGER_XSC0\", \"trigger_xsc\", 0, 1),\n BITWORD(\"TRIGGER_XSC1\", \"trigger_xsc\", 1, 1),\n BITWORD(\"TRIGGER_STATE_XSC\", \"trigger_xsc\", 2, 6),\n\n END_OF_DERIVED_CHANNELS\n};\n" }, { "alpha_fraction": 0.5668032765388489, "alphanum_fraction": 0.5864754319190979, "avg_line_length": 30.28205108642578, "blob_id": "6975386b623d91109a7fecbcec3e4e5a37302c5f", "content_id": "a11c6b8ef3879e46c62c4b54dd1cb57ed384d14e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2440, "license_type": "no_license", "max_line_length": 120, "num_lines": 78, "path": "/owl/PMap.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#ifndef PMAP_H\n#define PMAP_H\n\n#include <QObject>\n#include \"PObject.h\"\n#include \"PStyle.h\"\n#include <QMap>\n#include <QColor>\n\nclass PMap : public QObject, public PObject\n{\n Q_OBJECT\npublic:\n QMap<int,QString> _map;\n friend QDataStream& operator<<(QDataStream& a,PMap& b);\n friend QDataStream& operator>>(QDataStream&a,PMap&b);\n QString get(int num) {\n QString x=_map.value(num,QString::number(num));\n while(x.contains(\"[\")) { //regex would kinda be cool.\n int n=x.indexOf(\"]\",x.indexOf(\"[\"));\n if(n==-1) n=9999999;\n n-=x.indexOf(\"[\");\n x.remove(x.indexOf(\"[\"),n+1);\n }\n return x;\n }\n PStyle* style(int num,PStyle* def) {\n QString x=_map.value(num,QString((char)31));\n if(x.size()==1&&x[0]==(char)32) {\n return def;\n }\n if(!x.contains(\"[style\")) {\n return def;\n } else {\n QString v=x;\n v.remove(0,x.indexOf(\"[style=\")+4);\n if((v.indexOf(\"]\")!=-1)) {\n v.remove(v.indexOf(\"]\"),999999);\n }\n for(int i=0;i<PStyle::_u.size();i++) {\n if(v.contains(PStyle::_u[i]->idText())) {\n return PStyle::_u[i];\n }\n }\n }\n return def;\n }\n\npublic slots:\n void set(int num,QString val) { _map.insert(num,(val==\"Hopefully, nobody will put this in as a value.\")?\":P\":val); }\n void reset() { _map.clear(); }\n};\n\nQDataStream& operator<<(QDataStream& a,PMap& b);\nQDataStream& operator>>(QDataStream&a,PMap&b);\n\n#endif // PMAP_H\n" }, { "alpha_fraction": 0.6951379776000977, "alphanum_fraction": 0.7003942131996155, "avg_line_length": 20.742856979370117, "blob_id": "727bdbe323056bd306ae2963bbe1bcc1ac391a85", "content_id": "b91566e182ea2553bc05ccd49b7ecd2e86cc3d53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 762, "license_type": "no_license", "max_line_length": 73, "num_lines": 35, "path": "/stars/code/imaging/autofocuser.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef IMAGING__AUTOFOCUSER_H\n#define IMAGING__AUTOFOCUSER_H\n\n#include \"../tools/timing.h\"\n\nnamespace Imaging\n{\n class Autofocuser;\n}\n\nclass Imaging::Autofocuser\n{\n public:\n Autofocuser();\n void make_focus_request();\n void end_run(bool use_solution);\n void update();\n\n int run_counter;\n int abort_counter;\n int last_counter_stars;\n bool waiting_for_image_since_focus_change;\n Tools::Timer time_since_last_finish;\n Tools::Timer time_since_image_captured_at_last_focus;\n Tools::Timer autofocus_run_time;\n};\n\n#endif\n" }, { "alpha_fraction": 0.5696202516555786, "alphanum_fraction": 0.5830574631690979, "avg_line_length": 32.54901885986328, "blob_id": "a9b14d3d35cd1fef93ccdab60bd785e8e1714d5a", "content_id": "22256d9966e2994fddecbed6d9667f9bfdb0e590", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5135, "license_type": "no_license", "max_line_length": 178, "num_lines": 153, "path": "/groundhog/blast/main.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <math.h>\n#include <arpa/inet.h> // socket stuff\n#include <netinet/in.h> // socket stuff\n#include <sys/types.h> // socket types\n#include <sys/socket.h> // socket stuff\n#include <sys/stat.h>\n#include <dirent.h>\n#include <unistd.h>\n#include <signal.h>\n#include <string.h>\n#include <pthread.h> // threads\n#include <float.h>\n#include <ctype.h>\n\n#include \"groundhog.h\"\n#include \"linklist_connect.h\"\n\nextern struct TlmReport pilot_report;\nextern struct TlmReport bi0_report;\nextern struct TlmReport highrate_report;\nextern struct TlmReport sbd_report;\n\nvoid groundhog_write_calspecs(char *fname) {\n channels_write_calspecs(fname, derived_list);\n}\n\nint main(int argc, char * argv[]) {\n // set the directory in which to save raw linklist files received from the payload\n sprintf(archive_dir, \"/data/groundhog\");\n\n // initialize the main telemetry superframe\n channels_initialize(channel_list);\n\n // initialize the linklists derived from the superframe\n linklist_t ** ll_list = calloc(MAX_NUM_LINKLIST_FILES, sizeof(linklist_t *));\n load_all_linklists(superframe, DEFAULT_LINKLIST_DIR, ll_list, LL_INCLUDE_ALLFRAME);\n generate_housekeeping_linklist(linklist_find_by_name(ALL_TELEMETRY_NAME, ll_list), ALL_TELEMETRY_NAME);\n linklist_generate_lookup(ll_list); \n write_linklist_format(linklist_find_by_name(ALL_TELEMETRY_NAME, ll_list), DEFAULT_LINKLIST_DIR ALL_TELEMETRY_NAME \".auto\");\n\n channels_write_calspecs(\"test.cs\", derived_list);\n\n int pilot_on = 1;\n int bi0_on = 1;\n int highrate_on = 1;\n int daemon = 0;\n\n for (int i = 1; i < argc; i++) {\n if (strcmp(argv[i], \"-no_pilot\") == 0) pilot_on = 0;\n else if (strcmp(argv[i], \"-no_bi0\") == 0) bi0_on = 0;\n else if (strcmp(argv[i], \"-no_highrate\") == 0) highrate_on = 0;\n else if (strcmp(argv[i], \"-pilot_only\") == 0) bi0_on = highrate_on = 0;\n else if (strcmp(argv[i], \"-bi0_only\") == 0) highrate_on = pilot_on = 0;\n else if (strcmp(argv[i], \"-highrate_only\") == 0) pilot_on = bi0_on = 0;\n else if (strcmp(argv[i], \"-d\") == 0) daemon = 1;\n else if (strcmp(argv[i], \"-quiet\") == 0) verbose = 0;\n else if (strcmp(argv[i], \"-verbose\") == 0) verbose = 1;\n else {\n blast_err(\"Unrecognized option \\\"%s\\\"\", argv[i]);\n exit(1);\n }\n }\n\n if (daemon) {\n daemonize();\n }\n\n // setup pilot receive udp struct\n struct UDPSetup pilot_setup = {\"Pilot\", \n PILOT_ADDR, \n PILOT_PORT, \n PILOT_MAX_SIZE, \n PILOT_MAX_PACKET_SIZE,\n PILOT};\n\n struct UDPSetup pilot_setup2 = {\"Pilot 2\", \n PILOT_ADDR, \n PILOT_PORT+1, \n PILOT_MAX_SIZE, \n PILOT_MAX_PACKET_SIZE,\n PILOT};\n\n // Receiving data from telemetry\n pthread_t pilot_receive_worker[2];\n pthread_t biphase_receive_worker;\n pthread_t highrate_receive_worker;\n pthread_t direct_receive_worker;\n\n // Serving up data received via telemetry\n pthread_t server_thread;\n\n if (pilot_on) {\n pthread_create(&pilot_receive_worker[0], NULL, (void *) &udp_receive, (void *) &pilot_setup);\n pthread_create(&pilot_receive_worker[1], NULL, (void *) &udp_receive, (void *) &pilot_setup2);\n }\n\n if (bi0_on) {\n pthread_create(&biphase_receive_worker, NULL, (void *) &biphase_receive, NULL);\n }\n\n if (highrate_on) {\n pthread_create(&highrate_receive_worker, NULL, (void *) &highrate_receive, (void *) 0);\n pthread_create(&direct_receive_worker, NULL, (void *) &highrate_receive, (void *) 1);\n }\n\n // start the server thread for mole clients\n pthread_create(&server_thread, NULL, (void *) &linklist_server, NULL);\n\n sleep(1);\n printf(\"\\n\\n\\n\");\n\n char fn_str[1024] = \"\";\n int len = 0, prev_len = 0;\n\n // print out the reports\n while (true) {\n\n sprintf(fn_str, BLU \" Pilot: %s %s [%\" PRIu64 \"];\" GRN \" BI0: %s %s [%\" PRIu64 \"];\" YLW \" Highrate: %s %s [%\" PRIu64 \"];\" RED \" SBD: %s %s [%\" PRIu64 \"];\" NOR \" \", \n (pilot_report.ll) ? pilot_report.ll->name : \"(NULL)\", \n (pilot_report.allframe) ? \"AF\" : \" \",\n pilot_report.framenum,\n\n (bi0_report.ll) ? bi0_report.ll->name : \"(NULL)\", \n (bi0_report.allframe) ? \"AF\" : \" \",\n bi0_report.framenum,\n\n (highrate_report.ll) ? highrate_report.ll->name : \"(NULL)\", \n (highrate_report.allframe) ? \"AF\" : \" \",\n highrate_report.framenum,\n\n (sbd_report.ll) ? sbd_report.ll->name : \"(NULL)\", \n (sbd_report.allframe) ? \"AF\" : \" \",\n sbd_report.framenum\n );\n\n // print enough characters to overwrite the previous line\n len = strlen(fn_str);\n for (int i = len; i < prev_len; i++) fn_str[i] = ' ';\n fn_str[(len > prev_len) ? len : prev_len] = '\\0'; // terminate\n prev_len = len;\n\n fprintf(stdout, \"%s\\r\", fn_str);\n fflush(stdout); \n\n usleep(200000);\n }\n\n return 0;\n}\n\n\n" }, { "alpha_fraction": 0.6483007073402405, "alphanum_fraction": 0.6611740589141846, "avg_line_length": 27.144927978515625, "blob_id": "33ff77cf8fa29519fce5f3228d106fe6f9458fcf", "content_id": "49b19d18f37beccd2c366750a8b668e2e0abe576", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1942, "license_type": "no_license", "max_line_length": 79, "num_lines": 69, "path": "/owl/PObject.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#ifndef POBJECT_H\n#define POBJECT_H\n\n#include <QStringList>\n#include <QDebug>\n\nclass PMainWindow;\n\nclass PObject\n{\n static bool isLoading;\npublic:\n int _id;\n friend QDataStream& operator<<(QDataStream& a,PObject& b);\n friend QDataStream& operator>>(QDataStream& a,PObject& b);\n friend QVariant save(PObject&);\n friend void load(QVariant v,PObject& b);\n friend void load(QVariant v,PMainWindow& b);\n friend class PMainWindow;\n static QMap<int, PObject*> _u;\n\n PObject(int id=qrand()) {\n if (isLoading) return;\n\n _id = id;\n while (_u.contains(_id)) {\n qDebug()<<\"Broken random number generator?\";\n id=qrand();\n }\n _u.insert(id,this);\n }\n\n virtual ~PObject() {\n if((_id !=0) && _u.contains(_id)) {\n _u[_id]=0;\n }\n }\n\n bool isCurrentObject();\n QString idText() const { return \"(P\"+QString::number(_id)+\")\"; }\n const int& id() const { return _id; }\n virtual void activate() {}\n};\n\nQDataStream& operator<<(QDataStream& a,PObject& b);\nQDataStream& operator>>(QDataStream& a,PObject& b);\n\n#endif // POBJECT_H\n" }, { "alpha_fraction": 0.5322840213775635, "alphanum_fraction": 0.55620276927948, "avg_line_length": 22.388404846191406, "blob_id": "b5a2ead389cbaa54964f5d6a44e07967a11dbb9f", "content_id": "db5a0c2a6f02c5ad76dad3284284477d387c776d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8069, "license_type": "no_license", "max_line_length": 119, "num_lines": 345, "path": "/sched_upload/sched_upload.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <termios.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n\n#define LOS 0\n#define TDRSS 1\n#define IRIDIUM 2\n#define DEFAULT 3\n\n#define SIPCOM1 0x9\n#define SIPCOM2 0xC\n\n#define MAX_RTIME 65536.0\n#define MAX_DAYS 26.0\n\n#define MAX_SCHED_PER_CHUNK 59\n//#define MAX_SCHED_PER_CHUNK 7\n#define HEADER_LEN 4\n\n#define COMMAND_TTY \"/dev/ttyCMD\"\n\nstruct SchedStruct {\n int index;\n int day;\n double hour;\n int reduced_time;\n};\n\nstruct SchedStruct schedule[10000];\n\nstruct HeaderStruct {\n unsigned char s;\n unsigned char link;\n unsigned char route;\n unsigned char size;\n\n unsigned char command;\n unsigned char slot;\n unsigned char i_chunk;\n unsigned char n_chunk;\n unsigned char n_sched;\n unsigned char route_d;\n} header;\n \nvoid usage(char *message) {\n fprintf(stderr, \"%s\\n\", message);\n \n fprintf(stderr, \"usage: sched_upload [-s <compressed sched>] [-f] [-l|-i] [-1|-2] <slot>\\n\"\n\t\t \" -s <compressed sched>: compressed schedule file. default: /data/etc/sched.S\\n\"\n\t\t \" -f <chunk>: fix - upload chunk <chunk> only.\\n\"\n\t\t \" -l: los upload\\n\"\n\t\t \" -i: iridium upload - default\\n\"\n\t\t \" -t: iridium upload\\n\"\n\t\t \" -1: route to com1\\n\"\n\t\t \" -2: route to com2 - default\\n\"\n\t\t \" <slot>: index of slot to upload into.\\n\"\n );\n exit(0);\n}\n\n\nint bc_setserial(void) {\n int fd;\n struct termios term; \n\n if( (fd = open(COMMAND_TTY, O_RDWR)) < 0 ) {\n perror(\"Unable to open serial port\");\n exit(2);\n }\n\n if( tcgetattr(fd, &term) ) {\n perror(\"Unable to get serial device attributes\");\n exit(2);\n }\n\n term.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);\n term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);\n term.c_iflag |= INPCK;\n term.c_cc[VMIN] = 0;\n term.c_cc[VTIME] = 0;\n\n term.c_cflag &= ~(CSTOPB | CSIZE);\n term.c_oflag &= ~(OPOST);\n term.c_cflag |= CS8;\n\n if(cfsetospeed(&term, B2400)) { /* <======= SET THE SPEED HERE */\n perror(\"error setting serial output speed\");\n exit(2);\n }\n if(cfsetispeed(&term, B2400)) { /* <======= SET THE SPEED HERE */\n perror(\"error setting serial input speed\");\n exit(2);\n }\n\n if( tcsetattr(fd, TCSANOW, &term) ) {\n perror(\"Unable to set serial attributes\");\n exit(2);\n }\n\n return fd;\n}\n\nint main(int argc, char *argv[]) {\n char sched[1024];\n char instr[1024];\n int do_fix = 0;\n int do_sleep = 0;\n unsigned int pause = 0;\n int fix_chunk;\n int sipcom = DEFAULT;\n int link = DEFAULT;\n int slot = -1;\n int i,j,k;\n int tmp;\n FILE *fp;\n int n_sched;\n int n_chunk;\n int n_sched_in_chunk;\n int datasize;\n unsigned short idata[MAX_SCHED_PER_CHUNK*2];\n unsigned char footer = 0x03;\n int tty_fd;\n int bytes_written;\n int n;\n int counter;\n unsigned char buf[3];\n\n \n if (argc == 1) usage(\"Not enough entries\");\n \n for (i=1; i<argc; i++) {\n if (argv[i][0] == '-') {\n switch (argv[i][1]) {\n\tcase 'h':\n\t usage(\"Help:\");\n\t break;\n\tcase 's':\n\t if (i+1<argc) {\n\t strncpy(sched, argv[i+1], 1024);\n\t ++i;\n\t } else {\n\t usage(\"no argument for -s\");\n\t }\n\t break;\n\tcase 'f':\n if (i+1<argc) {\n fix_chunk = atoi(argv[i+1]);\n ++i;\n } else {\n usage(\"no argument for -f\");\n }\n\t do_fix = 1;\n \n\t break;\n\tcase 'z':\n if (i+1<argc) {\n pause = atoi(argv[i+1]);\n ++i;\n } else {\n usage(\"set a delay time between sending chunks (s) -z\");\n }\n\t do_sleep = 1;\n\t break;\n\tcase 'l':\n\t if (link == DEFAULT) {\n\t link = LOS;\n\t } else {\n\t usage(\"los: link already set\");\n\t }\n\t break;\n\tcase 'i':\n\t if (link == DEFAULT) {\n\t link = IRIDIUM;\n\t } else {\n\t usage(\"iridium: link already set\");\n\t }\n\t break;\n\tcase 't':\n\t if (link == DEFAULT) {\n\t link = TDRSS;\n\t } else {\n\t usage(\"iridium: link already set\");\n\t }\n\t break;\n\tcase '1':\n\t if (sipcom == DEFAULT) {\n\t sipcom = SIPCOM1;\n\t } else {\n\t usage(\"sipcom1: destination already set\");\n\t }\n\t break;\n\tcase '2':\n\t if (sipcom == DEFAULT) {\n\t sipcom = SIPCOM2;\n\t } else {\n\t usage(\"sipcom2: destination already set\");\n\t }\n\t break;\t \n\tdefault:\n\t usage(\"unknown option\");\n\t break;\n }\n } else {\n if (slot == -1) {\t\n slot = atoi(argv[i]);\n } else {\n\tusage(\"slot already set\");\n }\n }\n }\n \n if (link==DEFAULT) link = IRIDIUM;\n if (sipcom == DEFAULT) sipcom = SIPCOM2;\n if (slot==-1) usage(\"slot not set\");\n\n /* read compressed file */\n fp = fopen(sched, \"r\");\n\n if (fp==NULL) {\n fprintf(stderr, \"sched_upload: Could not open sched file %s.\\n\", sched);\n exit(0);\n }\n \n i=0;\n while (fgets(instr, 1024, fp)!=NULL) {\n if (sscanf(instr, \"%d %d %lg\", &schedule[i].index, &schedule[i].day, &schedule[i].hour) == 3) {\n schedule[i].reduced_time = ((double)schedule[i].day + schedule[i].hour/24.0)*MAX_RTIME/MAX_DAYS;\n i++;\n }\n }\n n_sched = i;\n \n n_chunk = (n_sched-1)/MAX_SCHED_PER_CHUNK + 1;\n \n if ((tty_fd = bc_setserial()) < 0) {\n perror(\"Unable to open serial port\");\n exit(2);\n }\n \n while( read(tty_fd, buf, 3) >0 ) {\n }\n \n for (i=0; i<n_chunk; i++) {\n if (do_fix) {\n i = fix_chunk;\n if (i>=n_chunk) {\n fprintf(stderr, \"invalid chunk: %d > %d\\n\", fix_chunk, n_chunk-1);\n exit(0);\n }\n if (i<0) {\n fprintf(stderr, \"invalid chunk: %d <0\\n\", fix_chunk);\n exit(0);\n }\n }\n if (i<n_chunk-1) {\n n_sched_in_chunk = MAX_SCHED_PER_CHUNK;\n } else {\n n_sched_in_chunk = n_sched - i*MAX_SCHED_PER_CHUNK;\n }\n \n datasize = n_sched_in_chunk * 4 + 6;\n if (datasize<22) datasize = 22;\n \n /* csbf header */\n header.s = 0x10;\n header.link = link;\n header.route = sipcom;\n header.size = datasize;\n /* our header - part of datasize */\n header.command = 0xfe;\n header.slot = ((slot & 0x0f)) << 4 | 0x0f; // the command is 0xffe, so the bottom nibble of slot must be set to 0xf\n header.i_chunk = i;\n header.n_chunk = n_chunk;\n header.n_sched = n_sched_in_chunk;\n header.route_d = sipcom;\n \n // build data packet\n for (j = 0; j < n_sched_in_chunk; j++) {\n idata[j*2] = schedule[i*MAX_SCHED_PER_CHUNK+j].reduced_time;\n idata[j*2+1] = schedule[i*MAX_SCHED_PER_CHUNK+j].index;\n }\n for (j=n_sched_in_chunk; j<MAX_SCHED_PER_CHUNK; j++) {\n idata[j*2] = 0;\n idata[j*2+1] = 0;\n }\n\n // write the data\n bytes_written = 0;\n bytes_written += write(tty_fd, (unsigned char *)(&header), sizeof(header)); // csbf header + our header\n bytes_written += write(tty_fd, (unsigned char *)idata, datasize-6); // the schedule file\n bytes_written += write(tty_fd, &footer, 1); // footer\n \n \n printf(\"written %d out of %d\\n\", bytes_written, datasize+5);\n /* Read acknowledgement */\n n = 0;\n counter = 0;\n while( ((n += read(tty_fd, buf + n, 3 - n)) != 3) &&(counter++<2000)) {\n usleep(10000);\n }\n if (n!=3) {\n fprintf(stderr, \"aborting: acknowledgement not received\\n\");\n exit(0);\n }\n if ((buf[0]==0xfa) && (buf[1]==0xf3)) {\n if (buf[2]==0x00) {\n } else if (buf[2]==0x0a) {\n\tfprintf(stderr,\"aborting: command not sent - GSE operator disabled science from sending commands\\n\");\n\texit(0);\n } else if (buf[2]==0x0b) {\n\tfprintf(stderr,\"aborting: command not sent - Routing address does not match the selected link\\n\");\n\texit(0);\n } else if (buf[2]==0x0c) {\n\tfprintf(stderr,\"aborting: command not sent - The link selected was not enabled\\n\");\n\texit(0);\n }\telse {\n\tfprintf(stderr,\"aborting: command not sent - error %x\\n\", buf[2]);\n\texit(0);\n }\n } else {\n fprintf(stderr, \"aborting: mangled response: %x %x %x\\n\", buf[0], buf[1], buf[2]);\n exit(0);\n }\n \n printf(\"packet %d sent: %d out of %d bytes\\n\", i, bytes_written, sizeof(header)+datasize-6+1);\n \n if (do_sleep) {\n sleep(pause);\n }\n if (do_fix) {\n break;\n }\n //sleep(11);\n }\n\n close(tty_fd);\n \n return 0;\n}\n" }, { "alpha_fraction": 0.6862208843231201, "alphanum_fraction": 0.6938307881355286, "avg_line_length": 40.90711975097656, "blob_id": "2b6151a310f7d24c255057c882b2186464ca36f8", "content_id": "c252b93e3d98dc0bac4fc691fa72281d96c38d4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13535, "license_type": "no_license", "max_line_length": 394, "num_lines": 323, "path": "/balloon_cam/locator.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//locator.cpp\n\n#include \"stdafx.h\"\n#include \"locator.h\"\n\n\nLocator::Locator(int xSize, int ySize, int pixelSize, int nSigma, Camera* camera){//constructor\n\ttotalPixels = xSize * ySize;\n\txPixels = xSize;\n\tyPixels = ySize;\n\tthis->camera = camera;\n\tpixelDataSize = pixelSize;\n\tif((pixelDataSize%8) != 0){\n\t\tprintf(\"The pixel size is not a multiple of 8, which will cause undefined behaviour in locator. Don't trust the output.\\n\");\n\t}\n\n\tif(pixelDataSize > 32){//otherwise ints will be too small to contain it\n\t\tprintf(\"The pixel data size is too large for locator to handle. Please reduce it.\\n\");\n\t}\n\tsrand((int)time(NULL));//starts the random generator\n\tlastBlob.size = 0;\n\tblobVector = std::vector<blob>();\n\tsigmaNumber = nSigma;\n}\n\n\nblob Locator::locate(){\n\treturn locate(camera->capture());\n}\n\nblob Locator::locate(void* address){//find the largest blob in a picture given an address\n\tdouble average = 0;\n\tdouble stdDev = 0;\n\tunsigned char* pixelAddress;\n\tint temp;\n\tunsigned int pixelValue;\n\tblob tempBlob;\n\ttempBlob.size = 0;\n\tstd::vector<blob> foundBlobs;//a list of all the blobs that have been found\n\n\tfor(int i = 0; i<(totalPixels/1000); i++){//calculates the average and stdDev of a sample of the image, should be representitive\n\t\tpixelAddress = (unsigned char*)((unsigned long long)address + ((rand()%totalPixels)*pixelDataSize/8));//picks a random pixel\n\t\tpixelValue = 0;\n\t\t\n\t\tfor(int j = 0; j<pixelDataSize/8; j++){\n\t\t\tpixelValue += (*(unsigned char*)((unsigned long long)pixelAddress + j)) *(int) pow((float)2, j*pixelDataSize);//adds the value of the next byte to the total\n\t\t}\n\n\t\taverage += pixelValue;\n\t\tstdDev += (int)pow((float)pixelValue, 2);\n\t}\n\n\taverage = average/(totalPixels/1000);\n\tstdDev = sqrt(stdDev/(totalPixels/1000) - pow(average, 2));\n\n\taverageValue = average;\n\tstandardDeviation = stdDev;\n\tif(standardDeviation < 2){//if the image is too uniform, any non white pixel can show up - this fixes this issue (kind of a hack)\n\t\tstandardDeviation = 2;\n\t\tstdDev = 2;\n\t}\n\t\n\tif(lastBlob.size == 0){//if we have never found the blob before, look at the whole picture\n\t\tblob maxBlob;\n\t\tmaxBlob.size = 0;\n\t\tpixelAddress = (unsigned char*)address;//the pixel we are looking at\n\t\tfor(int i = 0; i<totalPixels; i++){\n\t\t\tpixelValue =(*pixelAddress);//the intensity of that pixel\n\t\t\tif(abs(pixelValue - average) >= sigmaNumber*stdDev){//if the pixel is significant\n\t\t\t\tif(!blobWasFound(pixelAddress, address, foundBlobs)){//if a blob has not already been found containing this pixel\n\t\t\t\t\ttempBlob = detectBlob(pixelAddress, address);//returns the blob object containing the pixel in question\n\t\t\t\t\tfoundBlobs.push_back(tempBlob);//adds the blob to the list\n\t\t\t\t\tif(tempBlob.size > maxBlob.size){//calculates the biggest blob. For a real application, should probably find the second biggest\n\t\t\t\t\t\tmaxBlob = tempBlob;//so as to correct of the blimp\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tpixelAddress += 1;\n\t\t}\n\t\tlastBlob = maxBlob;\n\n\t\tblobVector.push_back(lastBlob);//archives the blob in case we are interested\n\t\tif((lastBlob.centroid.x == 0)&&(lastBlob.centroid.y == 0)){//if for some reason the blob cannot be found\n\t\t\tprintf(\"blob not found anywhere. Returning 0, 0\\n\");\n\t\t\tlastBlob.size = 0;\n\t\t}\n\t\treturn lastBlob;//returns the largest blob\n\t\n\t}else{//otherwise start looking at the previous location in a snake-like pattern\n\n\t\tint step = 1;\n\t\tunsigned long long startLocation = (unsigned long long) address + (xPixels*lastBlob.centroid.y + lastBlob.centroid.x)*(pixelDataSize/8);//starts at the center of the last blob\n\t\tint index = (xPixels*lastBlob.centroid.y + lastBlob.centroid.x)*(pixelDataSize/8);//makes an int of the above value\n\t\t//printf(\"starting at: %d, %d\\n\", index %xPixels , index /xPixels);\n\t\tbool stillLooking = true;\n\t\n\t\twhile(stillLooking){\n\t\t\tfor(int x = 1; x<=step; x++){\n\t\t\t\t\n\t\t\t\tif(step%2 == 1){//calculates the correct direction\n\t\t\t\t\ttemp = 1;\n\t\t\t\t}else{\n\t\t\t\t\ttemp = -1;\n\t\t\t\t}\n\t\t\t\tstartLocation += temp*(pixelDataSize/8);//caculates the current pixel\n\t\t\t\tindex = (int) (startLocation - (unsigned long long)address);\n\t\t\t\t//printf(\"looking at %d, %d\\n\", index%xPixels, index /xPixels);\n\t\t\t\tif((startLocation > (unsigned long long) address + totalPixels*(pixelDataSize/8))||(startLocation < (unsigned long long)address)){//ensures the value is still valid\n\t\t\t\t\tprintf(\"Search has gone out of bounds in the x direction. Terminating\\n\");\n\t\t\t\t\tstillLooking = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tpixelAddress = (unsigned char*)(startLocation);\n\t\t\t\tpixelValue = 0;\n\t\t\t\tfor(int j = 0; j<pixelDataSize/8; j++){//gets the value of the pixel \n\t\t\t\t\tpixelValue += (*(unsigned char*)((unsigned long long)pixelAddress + j)) *(int) pow((float)2, j*pixelDataSize);//adds the value of the next byte to the total\n\t\t\t\t}\n\n\t\t\t\tif((abs(pixelValue - average) > (sigmaNumber*stdDev))&&(!blobWasFound(pixelAddress, address, foundBlobs))){//if the pixel is significant and has not been found\n\t\t\t\t\ttempBlob = detectBlob(pixelAddress, address);//detects the blob\n\t\t\t\t\tfoundBlobs.push_back(tempBlob);//adds it to the list\n\t\t\t\t}\n\n\t\t\t\tif(abs(tempBlob.size - lastBlob.size) < (lastBlob.size/4)&&(tempBlob.size != 0)){//if we are pretty sure this is the right blob\n\t\t\t\t\tblobVector.push_back(tempBlob);//archives the blob\n\t\t\t\t\treturn tempBlob;//returns it\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!stillLooking){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t//this bit is the same as the previous bit except in the y direction instead of the x\n\n\t\t\tfor(int y = 1; y<=step; y++){//figures out the direction\n\t\t\t\tif(step % 2 == 1){\n\t\t\t\t\ttemp = 1;\n\t\t\t\t}else{\n\t\t\t\t\ttemp = -1;\n\t\t\t\t}\n\n\t\t\t\tstartLocation += xPixels*temp*(pixelDataSize/8);//calculates the correct pixel\n\t\t\t\tindex = (int)(startLocation - (unsigned long long)address);\n\t\t\t\t//printf(\"looking at %d, %d\\n\", index%xPixels, index/xPixels);\n\t\t\t\tif((startLocation > (unsigned long long) address + totalPixels*(pixelDataSize/8))||(startLocation < (unsigned long long)address)){//checks that the address is valid\n\t\t\t\t\tprintf(\"Search has gone out of bounds in the y direction. Terminating\\n\");\n\t\t\t\t\tstillLooking = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tpixelAddress = (unsigned char*)(startLocation);\n\t\t\t\tpixelValue = 0;\n\t\t\t\tfor(int j = 0; j<pixelDataSize/8; j++){//gets the pixel value\n\t\t\t\t\tpixelValue += ( *(unsigned char*)((unsigned long long)pixelAddress + j)) * (int)pow((float)2, j*pixelDataSize);//adds the value of the next byte to the total\n\t\t\t\t}\n\n\t\t\t\tif((abs(pixelValue - average) > (sigmaNumber*stdDev))&&(!blobWasFound(pixelAddress, address, foundBlobs))){//if the pixel is significant and hasn't been found\n\t\t\t\t\ttempBlob = detectBlob(pixelAddress, address);//detct the blob\n\t\t\t\t\tfoundBlobs.push_back(tempBlob);//add to the list \n\t\t\t\t}\n\n\t\t\t\tif(abs(tempBlob.size - lastBlob.size) < (lastBlob.size/4)&&(tempBlob.size != 0)){//if we are pretty sure this is the right blob\n\t\t\t\t\tblobVector.push_back(tempBlob);\n\t\t\t\t\treturn tempBlob;\n\t\t\t\t}\n\t\t\t}\n\t\t\tstep++;\n\t\t\tif(step > 250){//if we are outside of the region close to the previous bolb, it is a good guess that we are lost and should start from scratch\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tlastBlob.size = 0;//if we did not find a blob for whatever reason, start over with no prior knowledge\n\t\tlastBlob.centroid.x = NULL;\n\t\tlastBlob.centroid.y = NULL;\n\t\tprintf(\"No blob found near previous blob. Conducting thorough search\\n\");\n\t\treturn locate(address);\n\t}\n}\n\n\nvoid Locator::writeData(){//writes out a formatted summary of the blobs that have been found\n\tFILE** file = NULL;\n\tfopen_s(file, \"BlobSummary.txt\", \"w\");\n\tfprintf(*file, \"Image Number\\tX Value\\tY Value\\tSize\\tSource X\\tSource Y\\n\");\n\tblob current;\n\tfor(int i =0; i<(int)blobVector.size(); i++){\n\t\tcurrent = blobVector.at(i);\n\t\tfprintf(*file, \"%d\\t\\t%d\\t%d\\t%d\\t%d\\t%d\\n\", i, current.centroid.x, current.centroid.y, current.size, current.source.x, current.source.y);\n\t}\n\tfclose(*file);\n}\n\n\nbool Locator::blobWasFound(void* pixel, void* address, std::vector<blob> foundBlobs){//checks to determine if a blob was already found using the pixel in question\n\tint pixelNum = (int)((unsigned long long int)pixel - (unsigned long long int)address);//the int location of the pixel\n\tdouble x = pixelNum % xPixels;\n\tdouble y = (double)(pixelNum / xPixels);\n\tdouble ycenter;\n\tdouble xcenter;\n\tdouble ymin;\n\tdouble xmin;\n\tdouble ymax;\n\tdouble xmax;\n\n\tfor(unsigned int i = 0; i<foundBlobs.size(); i++){//goes through the list of blobs\n\t\tycenter = foundBlobs[i].centroid.y;\n\t\txcenter = foundBlobs[i].centroid.x;\n\t\txmax = foundBlobs[i].max.x;\n\t\txmin = foundBlobs[i].min.x;\n\t\tymax = foundBlobs[i].max.y;\n\t\tymin = foundBlobs[i].min.y;\n\t\t\n\t\t/* Checks if the pixel falls within the area of the blob. The condition being used assumes a rectangular blob, which seems to work well enough\n\t\tfor small blobs. The condition commented out assumes a oval blob, which is more accurate, but more fiddly to try and get it to work right*/\n\n\t\t//if(\t((y - ycenter) * (y - ycenter)/((xmax - xmin)*(xmax - xmin)/4)) + (x - xcenter)*(x - xcenter)/((ymax - ymin)*(ymax - ymin)/4) < 4){\n\t\tif( (y <= ymax + 1)&&(y >= ymin - 1)&&(x <= xmax + 1)&&(x >= xmin - 1)){\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n\nblob Locator::detectBlob (void* pixel, void* picture){//determines the dimentions and centroid of the blob containing the pixel given\n\tblob returnBlob;\n\tbool edgeSeeker = true;\n\tunsigned char* rightPointer;\n\tunsigned char* leftPointer;\n\tunsigned char* storedRight;\n\tunsigned char* storedLeft;\n\tint offset = 0;\n\tbool leftEdge = false;\n\tbool rightEdge = false;\n\n\twhile(edgeSeeker){//while we are still looking for the edge\n\t\trightPointer = (unsigned char*) pixel + offset;//moves the right pointer right\n\t\tleftPointer = (unsigned char*) pixel - offset;//moves the left pointer left\n\n\t\tif((!rightEdge)&&((abs(*rightPointer - averageValue) < sigmaNumber*standardDeviation)||(rightPointer > ((unsigned char*)picture + xPixels*yPixels)))){\n\t\t\tstoredRight = rightPointer - 1;//if the pixel is no longer significant, we have found the edge of the blob\n\t\t\trightEdge = true;\n\t\t}\n\t\tif((!leftEdge)&&((abs(*leftPointer - averageValue) < sigmaNumber*standardDeviation)||(leftPointer < (unsigned char*)picture))){\n\t\t\tstoredLeft = leftPointer + 1;//same as above but for the left side\n\t\t\tleftEdge = true;\n\t\t}\n\t\toffset ++;\n\n\t\tif((leftEdge) && (rightEdge)){//if we have found both the right and left edges\n\t\t\tedgeSeeker = false;//move on\n\t\t}\n\t}\n\t//calculates the middle of the two edges found above\n\tunsigned char* centerLine = (unsigned char*) (((unsigned long long int)storedRight + (unsigned long long int)storedLeft)/2);\n\n\tedgeSeeker = true;\n\tunsigned char* topPointer;\n\tunsigned char* bottomPointer;\n\tunsigned char* storedTop;\n\tunsigned char* storedBottom;\n\toffset = 0;\n\tbool foundTop = false;\n\tbool foundBottom = false;\n\n\twhile (edgeSeeker){\n\n\t\ttopPointer = centerLine - offset*xPixels;//starts at the middle line calculated above, moves up\n\t\tbottomPointer = centerLine + offset*xPixels;//and down\n\t\tif((!foundTop)&&((abs(*topPointer - averageValue) < sigmaNumber*standardDeviation)||(topPointer < (unsigned char*)picture))){\n\t\t\tstoredTop = topPointer + xPixels;//looks for the top edge as before\n\t\t\tfoundTop = true;\n\t\t}\n\t\tif((!foundBottom)&&((abs(*bottomPointer - averageValue) < sigmaNumber*standardDeviation)||(bottomPointer > (unsigned char*)picture + xPixels*yPixels))){\n\t\t\tstoredBottom = bottomPointer - xPixels;//looks for the bottom edge\n\t\t\tfoundBottom = true;\n\t\t}\n\t\tif(foundTop && foundBottom){//if we have found the top and bottom\n\t\t\tedgeSeeker = false;//move on\n\t\t}\n\t\toffset ++;\n\t}\n\treturnBlob.max.y = (int)(( storedBottom - (unsigned char*) picture )/xPixels);//stores the top and bottom\n\treturnBlob.min.y = (int)((storedTop - (unsigned char*) picture)/xPixels);\n\n\t//calculates the vertical center of the blob using the top and bottom edges\n\tcenterLine = (unsigned char*)((unsigned long long int)storedTop + ((((int)(storedBottom - storedTop)/xPixels)/2)*xPixels));\n\tedgeSeeker = true;\n\toffset = 0;\n\tleftEdge = false;\n\trightEdge = false;\n\twhile(edgeSeeker){\n\t\n\t\tleftPointer = centerLine - offset;//looks left\n\t\trightPointer = centerLine + offset;//and right\n\t\n\t\tif((!rightEdge)&&((abs(*rightPointer - averageValue) < sigmaNumber*standardDeviation)|| (rightPointer > ((unsigned char*)picture + xPixels*yPixels)))){\n\t\t\tstoredRight = rightPointer - 1;//looks for the right edge \n\t\t\trightEdge = true;\n\t\t}\n\t\tif((!leftEdge)&&((abs(*leftPointer - averageValue) < sigmaNumber*standardDeviation)|| (leftPointer < (unsigned char*)picture))){\n\t\t\tstoredLeft = leftPointer + 1;//looks for the left edge\n\t\t\tleftEdge = true;\n\t\t}\n\t\toffset ++;\n\n\t\tif((leftEdge) && (rightEdge)){//if we found both edges\n\t\t\tedgeSeeker = false;//move on\n\t\t}\n\t}\n\n\treturnBlob.max.x = (int) ((storedRight - (unsigned char*) picture) % xPixels);//stores the right edge\n\treturnBlob.min.x = (int) ((storedLeft - (unsigned char*) picture) % xPixels);//and the left\n\n\treturnBlob.centroid.x = (returnBlob.max.x + returnBlob.min.x)/2;//calculates the horisontal center\n\treturnBlob.centroid.y = (returnBlob.max.y + returnBlob.min.y)/2;//and the vertical center\n\t//calculates the approximate area\n\treturnBlob.size = (int) (3.14/4.0 * ((double)((returnBlob.max.x - returnBlob.min.x + 1)*(returnBlob.max.y - returnBlob.min.y + 1))));\n\n\t//printf(\"Blob found at %d, %d (center x = %d, y = %d), height: %d, width %d, size %d\\n\", (int)((unsigned long long int)pixel - (unsigned long long int)picture)%xPixels, (int)((unsigned long long int)pixel - (unsigned long long int)picture)/xPixels, returnBlob.centroid.x, returnBlob.centroid.y, 1+ returnBlob.max.y - returnBlob.min.y, 1+ returnBlob.max.x - returnBlob.min.x, returnBlob.size);\n\treturn returnBlob;\n}" }, { "alpha_fraction": 0.6879240274429321, "alphanum_fraction": 0.6933514475822449, "avg_line_length": 17.897436141967773, "blob_id": "2c70d512776397f32c74a19afc842ea29abf4040", "content_id": "da2ea665b428154294f0286bf889b7c643177235", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 738, "license_type": "no_license", "max_line_length": 73, "num_lines": 39, "path": "/stars/code/shared/image/matching.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__IMAGE__MATCHING_H\n#define SHARED__IMAGE__MATCHING_H\n\n#include <vector>\n#include \"../circular_buffer.h\"\n#include \"../../solving/base_set.h\"\n\nnamespace Shared\n{\nnamespace Image\n{\n\nclass Matching\n{\n public:\n Matching();\n Matching& operator=(const Matching& rhs);\n void init(Parameters::Manager& params);\n\n int counter_stars;\n int triplet_counter;\n std::vector< ::Solving::BaseSet > base_sets;\n};\n\n// writes: solver\n// reads: main\nextern Shared::CircularBuffer <Matching> matching;\n\n}\n}\n\n#endif\n" }, { "alpha_fraction": 0.6418209075927734, "alphanum_fraction": 0.7053526639938354, "avg_line_length": 18.598039627075195, "blob_id": "69c7d617f787cdca06a4a571812259c8b5ca86c6", "content_id": "c2b2eba434232e454c3d201bc6b48c7d1f0eb265", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1999, "license_type": "no_license", "max_line_length": 80, "num_lines": 102, "path": "/starcam/csbigimgdefs.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#ifndef CSBIGIMGDEFS_H\n#define CSBIGIMGDEFS_H\n\n// Compile Time Options\n#define\tINCLUDE_FITSIO\t0\t\t/* set to 1 to compile and link with FITSIO Library */\n\n/*\n\n Exposure State Field Defines\n\n*/\n#define ES_ABG_MASK\t\t\t\t0x0003\n#define ES_ABG_UNKNOWN\t\t\t0x0000\n#define ES_ABG_LOW\t\t\t\t0x0001\n#define ES_ABG_CLOCKED\t\t\t0x0002\n#define ES_ABG_MID\t\t\t\t0x0003\n\n#define ES_ABG_RATE_MASK\t\t0x00C0\n#define ES_ABG_RATE_FIXED\t\t0x0000\n#define ES_ABG_RATE_LOW\t\t\t0x0040\n#define ES_ABG_RATE_MED\t\t\t0x0080\n#define ES_ABG_RATE_HI\t\t\t0x00C0\n\n#define ES_DCS_MASK\t\t\t\t0x000c\n#define ES_DCS_UNKNOWN\t\t\t0x0000\n#define ES_DCS_ENABLED\t\t\t0x0004\n#define ES_DCS_DISABLED\t\t\t0x0008\n\n#define ES_DCR_MASK\t\t\t\t0x0030\n#define ES_DCR_UNKNOWN\t\t\t0x0000\n#define ES_DCR_ENABLED\t\t\t0x0010\n#define ES_DCR_DISABLED\t\t\t0x0020\n\n#define ES_AUTOBIAS_MASK\t\t0x0100\n#define ES_AUTOBIAS_ENABLED\t\t0x0100\n#define ES_AUTOBIAS_DISABLED\t0x0000\n\ntypedef enum { SBIF_COMPRESSED,\n SBIF_UNCOMPRESSED,\n\t\t\t SBIF_FITS,\n\t\t\t SBIF_DEFAULT \n} SBIG_IMAGE_FORMAT;\n\ntypedef enum\n{\n SBFE_NO_ERROR,\n SBFE_OPEN_ERROR,\n SBRE_CLOSE_ERROR,\n SBFE_READ_ERROR,\n SBFE_WRITE_ERROR,\n SBFE_FORMAT_ERROR,\n SBFE_MEMORY_ERROR,\n SBFE_FITS_HEADER_ERROR\n} SBIG_FILE_ERROR;\n\n//from .cpp file:\n#define FILE_VERSION\t3\t\t/* current header version written */\n#define DATA_VERSION\t1\t\t/* current data version written */\n#define HEADER_LEN\t\t2048\n#define VERSION_STR\t\t\"1.1\"\t/* version of this class */\n#ifndef PI\n#define PI\t3.1415926535\n#endif\ntypedef enum\n{\n\tHH_FILE_VERSION,\n\tHH_DATA_VERSION,\n\tHH_EXPOSURE,\n\tHH_FOCAL_LENGTH,\n\tHH_APERTURE,\n\tHH_RESPONSE_FACTOR,\n\tHH_NOTE,\n\tHH_BACKGROUND,\n\tHH_RANGE,\n\tHH_HEIGHT,\n\tHH_WIDTH,\n\tHH_DATE,\n\tHH_TIME,\n\tHH_EXPOSURE_STATE,\n\tHH_TEMPERATURE,\n\tHH_NUMBER_EXPOSURES,\n\tHH_EACH_EXPOSURE,\n\tHH_HISTORY,\n\tHH_OBSERVER,\n\tHH_X_PIXEL_SIZE,\n\tHH_Y_PIXEL_SIZE,\n\tHH_PEDESTAL,\n\tHH_E_GAIN,\n\tHH_USER_1,\n\tHH_USER_2,\n\tHH_USER_3,\n\tHH_USER_4,\n\tHH_FILTER,\n\tHH_READOUT_MODE,\n\tHH_TRACK_TIME,\n\tHH_SAT_LEVEL,\n\tHH_END\n} SBIG_HEADER_HEADING;\n\n\n\n#endif //CSBIGIMGDEFS_H\n" }, { "alpha_fraction": 0.6328125, "alphanum_fraction": 0.6686481237411499, "avg_line_length": 26.643192291259766, "blob_id": "914f6f3ece5ebf034a3e1e13db97bca4688005fa", "content_id": "f390c76ed94eb7cf8f4af5d2e7bc2996214ae746", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5889, "license_type": "no_license", "max_line_length": 85, "num_lines": 213, "path": "/stars/code/networking/xsc_protocol/xsc_protocol.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"xsc_protocol.h\"\n#include <string.h>\n\n#if defined(_MSC_VER) && _MSC_VER >= 1400\n#pragma warning(push)\n#pragma warning(disable:4996)\n#endif\n\n#define PI 3.141592653589793\n\nvoid xsc_clear_horizontal(XSCHorizontal* horizontal)\n{\n horizontal->valid = false;\n horizontal->lat = 0.0;\n horizontal->lst = 0.0;\n}\n\nvoid xsc_clear_image_blob(XSCImageBlob* blob)\n{\n blob->x = 0.0;\n blob->y = 0.0;\n blob->flux = 0.0;\n blob->peak_to_flux = 0.0;\n}\n\nvoid xsc_clear_image_blobs(XSCImageBlobs* blobs)\n{\n unsigned int i = 0;\n blobs->counter_stars = -1;\n blobs->num_blobs = 0;\n for (i=0; i<XSC_BLOBS_ARRAY_SIZE; i++) {\n xsc_clear_image_blob(&blobs->blobs[i]);\n }\n}\n\nvoid xsc_clear_server_data(XSCServerData* server_data)\n{\n xsc_clear_image_blobs(&server_data->blobs);\n server_data->xsc_protocol_version = 0;\n}\n\n\n\nvoid xsc_clear_filters(XSCFilters* filters)\n{\n filters->hor_location_limit_enabled = true;\n filters->hor_location_limit_radius = 3;\n filters->hor_location_limit_az = 0;\n filters->hor_location_limit_el = 0;\n\n filters->hor_roll_limit_enabled = true;\n filters->hor_roll_limit_min = -PI/2.0;\n filters->hor_roll_limit_max = PI/2.0;\n\n filters->hor_el_limit_enabled = true;\n filters->hor_el_limit_min = 0.0;\n filters->hor_el_limit_max = PI/4.0;\n\n filters->eq_location_limit_enabled = false;\n filters->eq_location_limit_radius = 30;\n filters->eq_location_limit_ra = 0;\n filters->eq_location_limit_dec = 0;\n\n filters->matching_pointing_error_threshold = (10.0 / 3600.0) * (PI / 180.0);\n filters->matching_fit_error_threshold_px = 2000.0;\n filters->matching_num_matched = 4;\n}\n\nvoid xsc_clear_solver_mask(XSCSolverMask* mask)\n{\n mask->enabled = false;\n mask->field0 = 0x00000000;\n mask->field1 = 0x00000000;\n mask->field2 = 0x00000000;\n}\n\nvoid xsc_clear_brightness(XSCBrightness* brightness)\n{\n brightness->counter = 0;\n brightness->enabled = true;\n brightness->level_kepsa = 0.0;\n brightness->gain_db = 0.0;\n brightness->actual_exposure = 0.120;\n brightness->simulated_exposure = 0.120;\n}\n\nvoid xsc_clear_shutdown(XSCShutdown* shutdown)\n{\n shutdown->counter = 0;\n shutdown->shutdown_now = false;\n shutdown->include_restart = false;\n}\n\nvoid xsc_clear_network_reset(XSCNetworkReset* network_reset)\n{\n network_reset->reset_now = false;\n network_reset->reset_on_lull_enabled = true;\n network_reset->reset_on_lull_delay = 2.0*3600.0;\n}\n\nvoid xsc_clear_main_settings(XSCMainSettings* main_settings)\n{\n main_settings->counter = 0;\n main_settings->display_frequency = 10.0;\n main_settings->display_fullscreen = true;\n main_settings->display_image_only = false;\n main_settings->display_solving_filters = false;\n main_settings->display_image_brightness = 1.0;\n main_settings->display_zoom_x = 320;\n main_settings->display_zoom_y = 240;\n main_settings->display_zoom_magnitude = 1.0;\n}\n\nvoid xsc_clear_solver(XSCSolver* solver)\n{\n solver->enabled = true;\n solver->timeout = 30.0;\n xsc_clear_solver_mask(&solver->mask);\n\n solver->snr_threshold = 1.0;\n solver->max_num_blobs = 10;\n solver->robust_mode_enabled = false;\n solver->fitting_method = xC_solver_fitting_method_none;\n solver->cell_size = 128;\n solver->max_num_blobs_per_cell = 2;\n\n solver->pattern_matcher_enabled = true;\n solver->display_star_names = false;\n solver->match_tolerance_px = 6.0;\n solver->iplatescale_min = 4.5572E-5;\n solver->iplatescale_max = 4.6542E-5;\n solver->platescale_always_fixed = false;\n solver->iplatescale_fixed = 4.60573E-5;\n\n xsc_clear_filters(&solver->filters);\n}\n\nvoid xsc_clear_client_data(XSCClientData* client_data)\n{\n client_data->in_charge = false;\n client_data->counter_fcp = -1;\n\n client_data->quit_counter = 0;\n xsc_clear_shutdown(&client_data->shutdown);\n xsc_clear_network_reset(&client_data->network_reset);\n xsc_clear_main_settings(&client_data->main_settings);\n client_data->image_client_enabled = true;\n\n client_data->multi_triggering_readout_delay = 1.0;\n\n client_data->set_focus_value = 0;\n client_data->set_focus_incremental_value = 0;\n client_data->define_focus_value = 0;\n client_data->autofocus_search_min = 500;\n client_data->autofocus_search_max = 2000;\n client_data->autofocus_search_step = 10;\n client_data->abort_autofocus_still_use_solution = false;\n client_data->autofocus_display_mode = xC_autofocus_display_mode_auto;\n client_data->set_aperture_value = 0;\n client_data->set_gain_value = 0.0;\n client_data->define_aperture_value = 0;\n\n xsc_clear_brightness(&client_data->brightness);\n\n xsc_clear_solver(&client_data->solver);\n\n xsc_clear_horizontal(&client_data->horizontal);\n\n client_data->xsc_protocol_version = 0;\n}\n\nstatic void decrement_is_new_countdown(unsigned int* countdown)\n{\n if (*countdown > 0) {\n (*countdown)--;\n }\n}\n\nvoid xsc_decrement_is_new_countdowns(XSCClientData* client_data)\n{\n unsigned int i=0;\n for (i=0; i<xC_num_command_admins; i++) {\n decrement_is_new_countdown(&client_data->command_admins[i].is_new_countdown);\n }\n}\n\nvoid xsc_zero_command_admins(xsc_command_admin_t* admins)\n{\n unsigned int i=0;\n for (i=0; i<xC_num_command_admins; i++) {\n admins[i].is_new_countdown = 0;\n admins[i].counter = 0;\n }\n}\n\nvoid xsc_init_server_data(XSCServerData* server_data)\n{\n memset(server_data, 0, sizeof(XSCServerData));\n server_data->channels.ctr_stars = -1;\n server_data->channels.image_ctr_fcp = -1;\n server_data->channels.image_ctr_stars = -1;\n}\n\n\n#if defined(_MSC_VER) && _MSC_VER >= 1400\n#pragma warning(pop)\n#endif\n" }, { "alpha_fraction": 0.6656221747398376, "alphanum_fraction": 0.6709937453269958, "avg_line_length": 35.59016418457031, "blob_id": "0340f8a2ecbd280106feb206c73c00f92b6ba263", "content_id": "a403e56f6a4be7430e1918108f9b59d651265277", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2235, "license_type": "no_license", "max_line_length": 116, "num_lines": 61, "path": "/stars/code/tools/ccd_projection.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"ccd_projection.h\"\n#include \"slalib.h\"\n#include \"refraction.h\"\n#include \"../shared/solving/filters.h\"\n#include \"../shared/solving/settings.h\"\n\nvoid Tools::ccd_projection(double ra, double dec, double center_ra, double center_dec,\n double platescale, double cos_roll, double sin_roll, double& x, double& y,\n bool flipped_coordinate_system)\n{\n int status = 0;\n double u = 0;\n double v = 0;\n Slalib::slaDs2tp(ra, dec, center_ra, center_dec, &u, &v, &status);\n if (flipped_coordinate_system) {\n u = -u;\n }\n u *= platescale;\n v *= platescale;\n x = cos_roll * u - sin_roll * v;\n y = sin_roll * u + cos_roll * v;\n}\n\nvoid Tools::ccd_projection(double ra, double dec, double center_ra, double center_dec,\n double platescale, double roll, double& x, double& y, bool flipped_coordinate_system)\n{\n double cos_roll = cos(roll);\n double sin_roll = sin(roll);\n ccd_projection(ra, dec, center_ra, center_dec, platescale, cos_roll, sin_roll, x, y, flipped_coordinate_system);\n}\n\nvoid Tools::get_refraction_corrected_equatorial(double ra, double dec,\n Shared::Solving::Refraction& settings, Shared::Solving::Filters& filters,\n double& ra_corrected, double& dec_corrected)\n{\n if (settings.enabled && filters.horizontal_known()) {\n double az = 0.0;\n double el = 0.0;\n get_refraction_corrected_horizontal(ra, dec, settings, filters, az, el);\n horizontal_to_equatorial(az, el, filters.lat(), filters.lst(), ra_corrected, dec_corrected);\n } else {\n ra_corrected = ra;\n dec_corrected = dec;\n }\n}\n\nvoid Tools::get_refraction_corrected_horizontal(double ra, double dec,\n Shared::Solving::Refraction& settings, Shared::Solving::Filters& filters,\n double& az_corrected, double &el_corrected)\n{\n equatorial_to_horizontal(ra, dec, filters.lat(), filters.lst(), az_corrected, el_corrected);\n if (settings.enabled) {\n el_corrected += Tools::refraction_angle(el_corrected, settings.pressure_mbar, settings.temperature);\n }\n}\n\n\n" }, { "alpha_fraction": 0.6670311689376831, "alphanum_fraction": 0.6670311689376831, "avg_line_length": 19.098901748657227, "blob_id": "29e47b087887f72636f8ef4bc290929a99b1410b", "content_id": "bc6573083cdfb9ea56c6e2b0146dc9ab4fb9739f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1829, "license_type": "no_license", "max_line_length": 92, "num_lines": 91, "path": "/guaca/options.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#ifndef OPTIONS_H\n#define OPTIONS_H\n\n#include <QObject>\n#include <QWidget>\n#include <QDialog>\n#include <QAbstractButton>\n#include <QMessageBox>\n#include <QDebug>\n#include <QCheckBox>\n#include <QTableWidget>\n#include <QSettings>\n#include <QFile>\n#include <QCompleter>\n#include <QFileSystemModel>\n\n#include \"logscroll.h\"\n\nnamespace Ui {\nclass Options;\n}\n\nclass Helper {\n public:\n Helper(QTableWidget *tw, int index);\n Helper(QString cmdname, QString args, bool terminal);\n ~Helper();\n\n Logscroll * log;\n\n QString cmdname;\n QString args;\n bool terminal;\n};\n\nclass Options : public QDialog\n{\n Q_OBJECT\npublic:\n explicit Options(QWidget *parent = nullptr);\n ~Options();\n\n void start_helpers();\n void start_a_helper(Helper * helper);\n void show_helpers();\n void hide_helpers();\n void load_options();\n void restore_options();\n void default_options();\n void apply_options();\n void save_options();\n void enable_options();\n void disable_options();\n unsigned int add_helper(QString cmdname, QString args, bool terminal, unsigned int row);\n unsigned int remove_helper(unsigned int row);\n\n\n bool server;\n bool client;\n bool backup;\n bool no_checksums;\n bool mole_terminal;\n\n unsigned int server_port;\n unsigned int client_port;\n\n bool auto_live;\n QString live_name;\n QString mole_dir;\n QString raw_dir;\n\nprivate:\n QWidget * main;\n Ui::Options * ui;\n std::vector<Helper *> helpers;\n QSettings settings;\n QCompleter * completer;\n QFileSystemModel * fsmodel;\n\nsignals:\n\npublic slots:\n\nprivate slots:\n void on_addHelper_clicked();\n void on_deleteHelper_clicked();\n void on_buttonBox_clicked(QAbstractButton *button);\n void on_auto_live_toggled(bool checked);\n};\n\n#endif // OPTIONS_H\n" }, { "alpha_fraction": 0.5479219555854797, "alphanum_fraction": 0.5805767774581909, "avg_line_length": 28.848100662231445, "blob_id": "752eafd117dfa913b9d2a2f44f6591fdb91f2d5b", "content_id": "c7458ecd2a35178d4c5bc404be0dc355e693d78b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2358, "license_type": "no_license", "max_line_length": 90, "num_lines": 79, "path": "/common/include/FIFO.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \"Copyright 2017 Javier Romualdez\"\n * -----------------------------------------------------------------------\n * ----------------------------- BIT ADCS FIFO ---------------------------\n * -----------------------------------------------------------------------\n * This program is distributed under the GNU General Public License (GPL)\n * Version 2 or higher.\n *\n * The following was developed in the QNX Momentics IDE and compiled on\n * using QNX RTOS version 6.5.\n *\n * ------------------------- Description -------------------------------\n * This code includes all necessary routines and data structures for the\n * circular FIFO buffer used on BIT for ground telemetry links.\n *\n * ---------------------------- Author ---------------------------------\n * L. Javier Romualdez (B.Eng Aerospace)\n * Institute for Aerospace Studies (UTIAS)\n * University of Toronto\n *\n * Created: November 21, 2013\n *\n * Copyright 2013 Javier Romualdez\n *\n * -------------------------- Revisions --------------------------------\n *\n */\n\n#ifndef INCLUDE_FIFO_H_\n#define INCLUDE_FIFO_H_\n\n#define MEMALLOC 0x01\n#define PACKET_HEADER_SIZE 12 // header size for packets [bytes]\n#define MAX_TELEM_FIFO_SIZE 20000\t// maximum number of telemetry entries in the FIFO\n\n#ifndef MIN\n#define MIN(a, b) ((a) < (b) ? (a) : (b))\n#endif\n#ifndef MAX\n#define MAX(a, b) ((a) > (b) ? (a) : (b))\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\nstruct Fifo\n{\n\tunsigned int start, end;\n\tunsigned int length, maxsize;\n\n\tuint32_t *frame_num;\n\tuint8_t *flags;\n\tuint32_t *size;\n\tuint8_t **buffer;\n};\n\n// some function prototypes\nint allocFifo(struct Fifo *, unsigned int, unsigned int);\nint freeFifo(struct Fifo *);\nint fifoIsEmpty(struct Fifo *);\nint incrementFifo(struct Fifo *);\nint decrementFifo(struct Fifo *);\nvoid clearFifo(struct Fifo *);\nuint8_t *getFifoRead(struct Fifo *);\nuint8_t *getFifoLastRead(struct Fifo *);\nuint8_t *getFifoWrite(struct Fifo *);\nint setFifoWrite(struct Fifo *, uint8_t *);\nint getFifoSize(struct Fifo *);\nuint8_t * packetizeBuffer(uint8_t *, uint32_t, uint32_t *, uint16_t *, uint16_t *);\nint depacketizeBuffer(uint8_t *, uint32_t *, uint32_t, uint16_t *, uint16_t *, uint8_t *);\nuint8_t writePacketHeader(uint8_t *, uint16_t, uint64_t, uint16_t, uint16_t);\nuint8_t readPacketHeader(uint8_t *, uint16_t *, uint64_t *, uint16_t *, uint16_t *);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* INCLUDE_FIFO_H_ */\n" }, { "alpha_fraction": 0.6135401725769043, "alphanum_fraction": 0.6191819310188293, "avg_line_length": 27.360000610351562, "blob_id": "ee2328831e3dcbd23e05931124062fa0fb0c8ca3", "content_id": "143ce505226baedf2532438446d3d8b6ec02aafc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 710, "license_type": "no_license", "max_line_length": 86, "num_lines": 25, "path": "/stars/code/parameters/group.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"group.h\"\n\nusing namespace Parameters;\nusing Main::logger;\n\ndouble Group::try_get(std::string name, double default_value)\n{\n double value = default_value;\n try {\n if (map.count(name)) {\n value = double(map[name].as<float>());\n } else {\n logger.log(format(\"failed to get parameter %s: not found in map\") % name);\n }\n } catch(std::exception& e) {\n logger.log(format(\"failed to get parameter %s: %s\") % name % e.what());\n }\n return value;\n}\n" }, { "alpha_fraction": 0.656862735748291, "alphanum_fraction": 0.6718569993972778, "avg_line_length": 27.42622947692871, "blob_id": "914e6fd756d6a11cd3373a653d122c140e0d292f", "content_id": "4c0cb33f5157ef72de97b8af18c8094949bba1c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1734, "license_type": "no_license", "max_line_length": 71, "num_lines": 61, "path": "/common/include/xsc_fifo.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/**\n * @file fifo.h\n *\n * @date Feb 14, 2011\n * @author seth\n *\n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2010 Columbia University\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n\n#ifndef INCLUDE_XSC_FIFO_H_\n#define INCLUDE_XSC_FIFO_H_\n#include <unistd.h>\n#include <atomic.h>\n#include <stdbool.h>\n\ntypedef struct xsc_fifo_node\n{\n struct xsc_fifo_node *next;\n void *data;\n} __attribute__((packed)) xsc_fifo_node_t;\n\ntypedef struct fifo\n{\n xsc_fifo_node_t *head;\n intptr_t pop_count;\n xsc_fifo_node_t *tail;\n intptr_t push_count;\n} __attribute__((packed, aligned(ALIGN_SIZE))) xsc_fifo_t;\n\nbool xsc_fifo_push(xsc_fifo_t *m_fifo, void *m_data);\nvoid *xsc_fifo_pop(xsc_fifo_t *m_fifo);\nxsc_fifo_t *xsc_fifo_new();\nvoid xsc_fifo_free(xsc_fifo_t *m_fifo, void (*m_free)(void*) );\n\nstatic inline intptr_t fifo_count(xsc_fifo_t *m_fifo)\n{\n if (!m_fifo) return 0;\n return (m_fifo->push_count - m_fifo->pop_count);\n}\n\n#define END_FIFO(...) NULL\n\n#endif /* XSC_FIFO_H_ */\n" }, { "alpha_fraction": 0.59099942445755, "alphanum_fraction": 0.5975192785263062, "avg_line_length": 40.355262756347656, "blob_id": "46d274512c5661a0c2b1c4cf6ee8cbf4c6ec328b", "content_id": "65d192b5e9a7323cad95e9c39df9917481b018b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12577, "license_type": "no_license", "max_line_length": 87, "num_lines": 304, "path": "/sedpy/sedobjects.py", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#!/usr/bin/env /usr/bin/python\n\n#TODO: can keep UID fixed, but should update the time\n#to get time: datetime.utcnow().replace(microsecond=0).isoformat(' ')\nUID_UTIME = \"1\\t2008-08-08 08:08:08\" #for spider \"sbenton\" has UID 1\n#UID_UTIME = \"23\\t2008-08-08 08:08:08\"\t#for BLASTpol \"sbenton\" has UID 23\n\nclass Failure(Exception):\n \"\"\"exception to use for failures in parsing and matching\"\"\"\n def __init__(self, msg, linenum=0):\n self.errstr = msg\n self.msg=\"Error: %s\" % msg\n if linenum > 0: self.msg += \" (%d)\"%linenum\n\n def __str__(self):\n return self.msg\n\nclass Connector:\n \"\"\"contains information about objects in the connector and congender tables\"\"\"\n #file objects to write output to\n connout = open('out/connector', 'w')\n gconnout = open('out/congender', 'w')\n\n def __init__(self, type, matetype, count, desc, alpha, bcd, mMate, fMate):\n #need to find reference to mate\n self.type = type\n self.matetype = matetype\n self.desc = desc\n self.count = int(count)\n #alpha and bcd will wither be None or a non-empty string\n self.flags = {'alpha': 'N', 'bcd': 'N'}\n if (alpha): self.flags['alpha'] = 'Y';\n if (bcd): self.flags['bcd'] = 'Y';\n #gender contains 'M' or 'F' for mating pair, 'X' used to simplify comparison\n self.genders = {'M': 'X', 'F': 'X', 'X':'u'}\n if mMate: self.genders['M'] = mMate.upper()\n if fMate: self.genders['F'] = fMate.upper()\n self.mate = None #object reference #needed\n\n def gendersMatch(self, other):\n \"\"\"ensure genders are unused or properly matched between two connectors\"\"\"\n return (other.genders[self.genders['M']] in 'uM' \\\n\tand other.genders[self.genders['F']] in 'uF' \\\n\tand self.genders[other.genders['M']] in 'uM' \\\n\tand self.genders[other.genders['F']] in 'uF')\n\n def __str__(self):\n \"\"\"return a string representing the connector\"\"\"\n if self.flags['alpha'] == \"Y\": alpha = \" alpha\"\n else: alpha = \"\"\n if self.flags['bcd'] == \"Y\": bcd = \" bcd\"\n else: bcd = \"\"\n if self.genders['M'] == 'X': male = \"\"\n else: male = \" M-%s\" % self.genders['M']\n if self.genders['F'] == 'X': female = \"\"\n else: female = \" F-%s\" % self.genders['F']\n return '%s -> %s %d \"%s\"%s%s%s%s' % (self.type, self.matetype,\n\tself.count, self.desc, alpha, bcd, male, female)\n\n def __eq__(self, other):\n \"\"\"equality comparison\"\"\"\n if hasattr(other, 'type'): return self.type == other.type\n else: return self.type == other\n\n def toInfile(self):\n self.__class__.connout.write('%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n'%(self.type, \\\n\tself.desc, self.count, self.flags['alpha'], self.flags['bcd'], \\\n\tself.mate.type, UID_UTIME))\n if self.genders['M'] != 'X':\n self.__class__.gconnout.write(\"%s\\tM\\t%s\\t\\\\N\\t\\\\N\\t\\\\N\\t\\\\N\\t%s\\n\"%\\\n\t (self.type, self.genders['M'], UID_UTIME))\n if self.genders['F'] != 'X':\n self.__class__.gconnout.write(\"%s\\tF\\t%s\\t\\\\N\\t\\\\N\\t\\\\N\\t\\\\N\\t%s\\n\"%\\\n\t (self.type, self.genders['F'], UID_UTIME))\n\nclass Component:\n \"\"\"contains information about objects in the component table\"\"\"\n compout = open('out/component', 'w')\n\n def __init__(self, ref, name, partOf):\n #need to populate jack and line lists\n self.ref = ref\n self.name = name\n self.partOf = partOf\n self.jacks = [] #needed\n self.lines = [] #needed\n\n def __str__(self):\n if self.partOf: partof = \" < %s\" % self.partOf\n else: partof = \"\"\n return '%s \"%s\"%s' % (self.ref, self.name, partof)\n\n def __eq__(self, other):\n if hasattr(other, 'ref'): return self.ref == other.ref\n else: return self.ref == other\n\n def toInfile(self):\n if self.partOf is None: partOf = \"\\N\"\n else: partOf = self.partOf\n self.__class__.compout.write(\"%s\\t%s\\t%s\\t%s\\n\" % (self.ref,\\\n\tself.name, partOf, UID_UTIME))\n\nclass Cable:\n \"\"\"entries for the cable table. most are implicit p2p cables\"\"\"\n cabout = open('out/cable', 'w')\n\n def __init__(self, ref, label, length):\n #need to change p2p for implicit cables, populate jacks and lines lists\n self.number = 0 #needed\n if ref and ref[0] == \"&\":\t#try to infer number from ref\n if ref[1] == \"C\": number = int(ref[2:])\n else: number = int(ref[1:])\n if number > 0:\n\tself.number = number\n self.ref = ref #internal use only\n self.label = label\n self.length = length and int(length) #short circuit avoids casting None\n self.p2p = 'N' #is this a sensible default? #needed\n self.jacks = [] #needed\n self.lines = [] #needed\n\n def __str__(self):\n if self.number > 0: ref = \"&C%d\" % self.number\n else: ref = self.ref\n if self.length > 0: length = \" %d\" % self.length\n else: length = \"\"\n return 'CABLE %s \"%s\"%s' % (ref, self.label, length)\n\n def __eq__(self, other):\n if hasattr(other, 'ref'): return self.ref == other.ref\n else: return self.ref == other\n\n def toInfile(self):\n if self.length is None or self.length < 0: lenstr = \"\\\\N\"\n else: lenstr = self.length.str()\n self.__class__.cabout.write(\"%s\\t%s\\t%s\\t%s\\t%s\\n\" % (self.number,\\\n\tself.label, self.p2p, lenstr, UID_UTIME))\n\nclass Jack:\n \"\"\"contains information for jack table\"\"\"\n jackout = open('out/jack', 'w')\n\n def __init__(self, internal, ref, label, conn_str, dest_part, \\\n dest_jack, c_num, c_desc, c_len):\n #need to populate pins list, find references to location, destination, conn\n #need to set placeholder and cablemaster where appropriate\n self.number = 0 #needed\n #try to infer number from ref\n if ref and ref[0] == \"&\":\n if ref[1] == \"J\": number = int(ref[2:])\n else: number = int(ref[1:])\n if number > 0:\n\tself.number = number\n self.internal = internal #either None or 'IN'\n self.ref = ref #internal use only (matched in LINEs)\n self.label = label\n self.conn_str = conn_str #contains: \"conn_type/gender\"\n self.gender = self.conn_str[-1].upper()\n self.conn = None #object reference #needed\n self.dest_str = dest_part\n self.dest_jack = dest_jack #only needed for indistinguishable jacks\n self.location = None #object reference #needed\n self.dest = None #object reference\t #needed\n if c_desc is not None: #allows \"\"\n self.cable = Cable(c_num, c_desc, c_len)\n self.cable.p2p = 'Y'\n else: self.cable = None\n self.pins = [] #needed\n self.mate = None #object reference #needed\n self.placeholder = False #in direct connection, one of pair is placeholder\n self.cablemaster = False #in cable pair, cable shared but only 1 is master\n \n def canMate(self, other):\n #check cable use and length\n if (self.cable is not None and other.cable is not None):\n if (self.cable.length and other.cable.length and \\\n\t self.cable.length != other.cable.length): return False\n elif self.cable is not None or other.cable is not None: return False\n #check that connectors match properly\n if self.cable is not None: #for cables, ends must be same type or mates\n if (self.conn.mate == other.conn and other.conn.mate == self.conn) or \\\n\t self.conn == other.conn: return True\n else: #no cable means must be mates, and must have genders match\n if self.conn.mate == other.conn and other.conn.mate == self.conn and \\\n\t self.conn.genders[self.gender] == other.gender and \\\n\t other.conn.genders[other.gender] == self.gender: return True\n return False\n\n def __str__(self):\n if self.internal: internal = \" IN\"\n else: internal = \"\"\n if self.number > 0: ref = \"&J%d\" % self.number\n else: ref = self.ref\n if self.conn: connector = \"%s/%s\" % (self.conn.type, self.gender)\n else: connector = self.conn_str\n if self.dest:\n if hasattr(self.dest, 'number') and self.dest.number > 0:\n\tdest = \"&C%d\" % self.dest.number\n else: dest = self.dest.ref #component or unnumbered cable\n else: dest = self.dest_str\n if self.mate:\n if self.mate.number > 0: destjack = \"&J%d\" % self.mate.number\n else: destjack = self.mate.ref\n elif self.dest_jack: destjack = self.dest_jack\n else: destjack = \"\"\n if destjack: destination = \"%s/%s\" % (dest, destjack)\n else: destination = dest\n if self.cable:\n if self.cable.number > 0: cref = \" &C%d\" % self.cable.number\n #elif self.cable.ref: cref = \" %s\" % self.cable.ref #shouldn't happen\n else: cref = \"\"\n if self.cable.length: length = \" %d\" % self.cable.length\n else: length = \"\"\n cable = ' CABLE%s \"%s\"%s' % (cref, self.cable.label, length)\n else: cable = \"\"\n return 'JACK%s %s \"%s\" %s -> %s%s' % (internal, ref, self.label,\n\tconnector, destination, cable)\n\n def __eq__(self, other):\n if hasattr(other, 'ref'): return self.ref == other.ref\n else: return self.ref == other\n\n def toInfile(self):\n if self.placeholder: return #don't write placeholders\n if self.cable is not None: dest = self.cable.number #implicit cable\n elif hasattr(self.dest, 'p2p'): dest = self.dest.number #explicit cable\n else: dest = self.dest.ref #mates directly to component\n if hasattr(self.location, 'p2p'): location = self.location.number\n else: location = self.location.ref\n if self.internal: internal = 'Y'\n else: internal = 'N'\n self.__class__.jackout.write(\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\"%(\\\n\tself.number, self.gender, internal, location, self.conn.type, dest,\\\n\tself.label, UID_UTIME))\n \nimport re\nclass Line:\n \"\"\"contains information on the line table\"\"\"\n pinRE = re.compile(r'\\(((?:&J?\\d{1,5})|[a-z0-9]+)[;,]((?:\\s*[A-Za-z0-9]{1,3},?)*)\\)')\n count = 1\n lineout = open('out/line', 'w')\n\n def __init__(self, desc, pin_str):\n #pin_str takes further processing, need to fill in owner (comp or cable)\n self.number = self.__class__.count\n self.__class__.count += 1\n self.desc = desc\n self.pinnums = []; #internal reference\n self.jacknums = []; #internal reference\n for match in self.__class__.pinRE.finditer(pin_str):\n for pin in match.group(2).replace(',',' ').split():\n\tself.jacknums.append(match.group(1))\n\tself.pinnums.append(pin)\n self.owner = None #object reference #needed\n self.autogen = False #set to true for automatically generated lines #needed\n #autogen lines will only connect to a single pin\n\n def __str__(self):\n old_jacknum = self.jacknums[0]\n pintok = [\"(%s;\"%old_jacknum]\n for jacknum, pinnum in zip(self.jacknums, self.pinnums):\n if jacknum != old_jacknum:\n\tpintok.append(\"),(%s;\" % jacknum)\n\told_jacknum = jacknum\n if pintok[-1][-1] != ';': pintok.append(',')\n pintok.append(pinnum)\n pintok.append(\")\")\n return 'LINE \"%s\" %s' % (self.desc, \"\".join(pintok))\n #return str((self.number, self.desc, zip(self.jacknums, self.pinnums)))\n\n def __eq__(self, other):\n \"\"\"doesn't quite test equality in this case: more like overlap\"\"\"\n if self.autogen or other.autogen: return False #autogens don't count\n for jackpin in zip(self.jacknums, self.pinnums):\n if jackpin in zip(other.jacknums, other.pinnums): return True\n return False\n\n def toInfile(self):\n if hasattr(self.owner,'p2p'): #owner is a cable, so use its number\n owner = self.owner.number\n else: owner = self.owner.ref #it is a component\n self.__class__.lineout.write(\"%s\\t%s\\t%s\\t%s\\n\"%(self.number,\\\n\tself.desc, owner, UID_UTIME))\n\nclass Pin:\n \"\"\"info for the pin table, is inferred from lines and jacks\"\"\"\n pinout = open('out/pin', 'w')\n\n def __init__(self, number, desc, jack, bline, cline):\n self.number = number #not necessarily a number; 3-digit string\n self.desc = desc\n #jack and lines are all object references instead of numbers\n self.jack = jack #object reference\n self.lines = {'box': bline, 'cable': cline}\n\n def __eq__(self, other):\n #should only be used from within a given jack\n if hasattr(other, 'number'): return self.number == other.number\n else: return self.number == other\n\n def toInfile(self):\n self.__class__.pinout.write(\"%s\\t%s\\t%s\\t%s\\t%s\\tN\\tN\\t%s\\n\"%(self.number,\\\n\tself.jack.number, self.desc, self.lines['box'].number,\\\n\tself.lines['cable'].number, UID_UTIME))\n \n" }, { "alpha_fraction": 0.6650943160057068, "alphanum_fraction": 0.6707547307014465, "avg_line_length": 22.55555534362793, "blob_id": "6a895d26184e13f5b619017bdcfacf9a67555832", "content_id": "9aea39def3d7ef49f00b900e45c36077204c8fe5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1061, "license_type": "no_license", "max_line_length": 110, "num_lines": 45, "path": "/stars/code/solving/finding/estimator.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__FINDING__ESTIMATOR_H\n#define SOLVING__FINDING__ESTIMATOR_H\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n}\n\nnamespace Solving\n{\n class Blob;\n\n namespace Finding\n {\n class Estimator;\n }\n}\n\nclass Solving::Finding::Estimator\n{\n public:\n Blob estimate_blob(Shared::Image::Raw& image, Blob& blob, bool& valid);\n\n private:\n void get_square_stats(Shared::Image::Raw& image, int x, int y, int halfwidth, double& mean, double& stdev,\n bool& valid, int& numvals, bool include_center);\n void estimate_flux_and_stdev(Shared::Image::Raw& image, int x, int y, int hw,\n double& flux, double& stdev, double& prob_of_something);\n void calculate_basic_flux_and_base(Shared::Image::Raw& image, Blob& blob);\n\n double neighbor_means[8];\n double neighbor_stdevs[8];\n};\n\n#endif\n" }, { "alpha_fraction": 0.6208277940750122, "alphanum_fraction": 0.6291722059249878, "avg_line_length": 33.83720779418945, "blob_id": "16673837b6e6fd5a0182e7d5556136ddf01c0b3e", "content_id": "93ecde0af2ee70b3343c04c56cf6c1b734193dfc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2996, "license_type": "no_license", "max_line_length": 103, "num_lines": 86, "path": "/owl/PMdiArea.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"PMdiArea.h\"\n#include \"PMainWindow.h\"\n\nvoid PMdiArea::dragEnterEvent(QDragEnterEvent *ev)\n{\n if(ev->mimeData()->hasFormat(\"application/x-qabstractitemmodeldatalist\"))\n {\n QByteArray encoded = ev->mimeData()->data(\"application/x-qabstractitemmodeldatalist\");\n QDataStream stream(&encoded, QIODevice::ReadOnly);\n\n int row, col;\n QMap<int, QVariant> roleDataMap;\n stream >> row >> col >> roleDataMap;\n if((!row||row==6)&&!col) { //HACKHACKHACKHACK!!!\n ev->acceptProposedAction();\n }\n }\n}\n\nvoid PMdiArea::dropEvent(QDropEvent *ev)\n{\n if(ev->mimeData()->hasFormat(\"application/x-qabstractitemmodeldatalist\"))\n {\n QByteArray encoded = ev->mimeData()->data(\"application/x-qabstractitemmodeldatalist\");\n QDataStream stream(&encoded, QIODevice::ReadOnly);\n\n int row, col;\n QMap<int, QVariant> roleDataMap;\n stream >> row >> col >> roleDataMap;\n if(!row&&!col) { //HACKHACKHACKHACK!!!\n createPBox(ev->pos().x(),ev->pos().y());\n } else if(row==6&&!col) { //HACKHACKHACKHACK!!!\n createOwl(ev->pos().x(),ev->pos().y());\n }\n }\n}\n\nvoid PMdiArea::createPBox(int x,int y,PBox*c_pbox)\n{\n PBox* pbox=c_pbox?c_pbox:new PBox(\"New Box\", font());\n pbox->setParent(this);\n\n if (c_pbox) {\n pbox->setGeometry(c_pbox->geometry().x()/_H*_H,c_pbox->geometry().y()/_H*_H,\n c_pbox->geometry().width()/_H*_H,c_pbox->geometry().height()/_H*_H);\n } else {\n pbox->setGeometry(x/_H*_H,y/_H*_H,pbox->width()/_H*_H,pbox->height()/_H*_H);\n pbox->adjustSize();\n }\n dynamic_cast<PMainWindow*>(PMainWindow::me)->_pboxList.push_back(pbox);\n pbox->show();\n emit newBox(pbox);\n}\n\nvoid PMdiArea::createOwl(int x,int y,POwlAnimation*c_owl)\n{\n POwlAnimation* owl=c_owl?c_owl:new POwlAnimation(_H);\n owl->setParent(this);\n if(!c_owl) {\n owl->setGeometry(x/_H*_H,y/_H*_H,owl->sizeHint().width()/_H*_H,owl->sizeHint().height()/_H*_H);\n }\n dynamic_cast<PMainWindow*>(PMainWindow::me)->_owlList.push_back(owl);\n owl->show();\n emit newOwl(owl);\n}\n" }, { "alpha_fraction": 0.6672828197479248, "alphanum_fraction": 0.6765249371528625, "avg_line_length": 10.510638236999512, "blob_id": "316713877ccdd81cd366b47241b0ff3990608fab", "content_id": "cd6229ceaa3296842c96118f6c81f5817e19d7b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 541, "license_type": "no_license", "max_line_length": 34, "num_lines": 47, "path": "/balloon_cam/server/server.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//server.h\n\n#pragma once\n\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <time.h>\n#include <stdlib.h>\n#include <string.h>\n#include <errno.h>\n#include <unistd.h>\n#include <sys/time.h>\n\n#define DEFAULT_PORT \"31337\"\n\nclass Server {\n\npublic:\n\n\tServer();\n\n\t~Server();\n\n\tvoid runLoop();\n\nprivate:\n\n\tvoid sendData(timeval);\n\n\tchar* recieveData();\n\n\tvoid init();\n\n\tvoid passData(int, int, timeval);\n\n\taddrinfo* servInfo;\n\n\tint socketFileDescriptor;\n\n\ttimeval lagTime;\n\n\tint lag;\n\n\tvoid updateLag();\n};\n" }, { "alpha_fraction": 0.5705209374427795, "alphanum_fraction": 0.5967810153961182, "avg_line_length": 40.421051025390625, "blob_id": "4516b67c96e37fbefc26627ce13c20ebd49ccaa3", "content_id": "de04aaf247a1b9e04f563e32d804b421a509c23f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2361, "license_type": "no_license", "max_line_length": 100, "num_lines": 57, "path": "/common/include/blast_file_format.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * blast_file_format.h:\n *\n * This software is copyright (C) 2017 Seth Hillbrand\n *\n * This file is part of blast_comms, created for the BLASTPol Project.\n *\n * blast_comms 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 2 of the License, or\n * (at your option) any later version.\n *\n * blast_comms 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 blast_comms; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: May 25, 2017 by Seth Hillbrand\n */\n\n#ifndef INCLUDE_BLAST_FILE_FORMAT_H_\n#define INCLUDE_BLAST_FILE_FORMAT_H_\n\n#include <stdint.h>\n#include <lookup.h>\n\n#define _BLAST_FILE_TYPES(x, _) \\\n _(x, FRAME_1HZ) \\\n _(x, FRAME_5HZ) \\\n _(x, FRAME_20HZ) \\\n _(x, FRAME_100HZ) \\\n _(x, FRAME_200HZ) \\\n _(x, FRAME_244HZ) \\\n _(x, FRAME_FORMAT) \\\n _(x, KID) \\\n\ntypedef struct blast_file_packet\n{\n uint8_t magic; /**< magic = 0xEB for all packets */\n uint32_t version:4; /**< version Currently at 1 */\n uint32_t type:4; /**< type The type of data in this packet */\n uint32_t index; /**< index Monotonically incrementing num (all types) */\n uint32_t time; /**< time UNIX time */\n uint32_t time_ns; /**< time_ns Nanoseconds since last second */\n uint32_t length; /**< length Number of bytes in the packet */\n} __attribute__((packed)) blast_file_packet_t; /** 18 bytes */\n\n#define BLAST_FILE_PACKET_FULL_LENGTH(_ptr) (sizeof(blast_file_packet_t) + (_ptr)->length + 4)\n#define BLAST_FILE_PACKET_PAYLOAD(_ptr) ((uint8_t*)(((blast_file_packet_t*)(_ptr))+1))\n#define BLAST_FILE_PACKET_CRC(_ptr) (*(uint32_t*)(&BLAST_FILE_PACKET_PAYLOAD(_ptr)[(_ptr)->length]))\n\n#endif /* INCLUDE_BLAST_FILE_FORMAT_H_ */\n" }, { "alpha_fraction": 0.7361918687820435, "alphanum_fraction": 0.742732584476471, "avg_line_length": 35.69333267211914, "blob_id": "67352a03921b0cfbe461685adc299e6803cf2b3a", "content_id": "368dad41ea7da3f4a1ccf3cf00f2adab654209be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2752, "license_type": "no_license", "max_line_length": 93, "num_lines": 75, "path": "/liblinklist/linklist_writer.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#ifndef INCLUDE_LINKLIST_WRITER_H\n#define INCLUDE_LINKLIST_WRITER_H\n\n#include <inttypes.h>\n#include \"linklist.h\"\n\n#define LL_RAWFILE_DUMMY 0x8\n#define LL_DIRFILE_NUM_EXTRA 3 // the number of extra ll_dirfile-specific fields are included\n#define LL_FRAMEBIN_NAME \"ll_frame_tally\"\n#define LL_FRAMEBIN_READ_BLOCK_SIZE 4096\n\nstruct linklist_dirfile {\n char filename[LINKLIST_MAX_FILENAME_SIZE];\n unsigned int framenum;\n linklist_t * ll;\n uint8_t * map;\n FILE * format;\n FILE ** bin;\n FILE ** blockbin;\n FILE ** streambin;\n FILE ** extrabin;\n FILE * framebin;\n\n float data_integrity;\n uint32_t local_time;\n\n uint8_t tally_word;\n unsigned int * missing_blks_start;\n unsigned int * missing_blks_end;\n unsigned int n_missing_blks;\n unsigned int n_missing_blks_alloc;\n};\n\nstruct linklist_rawfile {\n char basename[LINKLIST_MAX_FILENAME_SIZE];\n unsigned int framenum; // current frame number\n unsigned int fileindex; // current file index for rawfile chunks\n unsigned int framesize; // size [Bytes] of a frame\n unsigned int fpf; // number of frames per rawfile chunk\n int isseekend; // file index for the end of the rawfile (i.e. last chunk)\n linklist_t * ll;\n FILE * fp;\n};\n\ntypedef struct linklist_dirfile linklist_dirfile_t;\ntypedef struct linklist_rawfile linklist_rawfile_t;\ntypedef struct linklist_dirfile_meta linklist_dirfile_meta_t;\n\nint seek_linklist_dirfile(linklist_dirfile_t *, unsigned int);\nint flush_linklist_dirfile(linklist_dirfile_t *);\n\nlinklist_dirfile_t * open_linklist_dirfile(char *, linklist_t *);\nlinklist_dirfile_t * open_linklist_dirfile_opt(char *, linklist_t *, unsigned int);\nvoid close_and_free_linklist_dirfile(linklist_dirfile_t *);\ndouble write_linklist_dirfile(linklist_dirfile_t *, uint8_t *);\ndouble write_linklist_dirfile_opt(linklist_dirfile_t *, uint8_t *, unsigned int);\nvoid map_frames_linklist_dirfile(linklist_dirfile_t *);\n\nint seek_linklist_rawfile(linklist_rawfile_t *, unsigned int);\nint seekend_linklist_rawfile(linklist_rawfile_t *);\nint flush_linklist_rawfile(linklist_rawfile_t *);\nint tell_linklist_rawfile(linklist_rawfile_t *);\n\nlinklist_rawfile_t * open_linklist_rawfile(char *, linklist_t *);\nlinklist_rawfile_t * open_linklist_rawfile_opt(char *, linklist_t *, unsigned int);\nvoid close_and_free_linklist_rawfile(linklist_rawfile_t *);\nint write_linklist_rawfile(linklist_rawfile_t *, uint8_t *);\nint write_linklist_rawfile_opt(linklist_rawfile_t *, uint8_t *, unsigned int);\nint write_linklist_rawfile_with_allframe(linklist_rawfile_t *, uint8_t *, uint8_t *);\nint read_linklist_rawfile(linklist_rawfile_t *, uint8_t *);\n\nvoid make_linklist_rawfile_name(linklist_t *, char *);\nvoid create_rawfile_symlinks(linklist_rawfile_t *, char *);\n\n#endif /* INCLUDE_LINKLIST_WRITER_H */\n" }, { "alpha_fraction": 0.665105402469635, "alphanum_fraction": 0.6733021140098572, "avg_line_length": 18.409090042114258, "blob_id": "99551a6f6bafc06f29b53cdadcb5e9c6fa59ba55", "content_id": "5dba9e682b0cceffac6b3f835ff11ab6fc24dc97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 855, "license_type": "no_license", "max_line_length": 73, "num_lines": 44, "path": "/stars/code/imaging/commands.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef IMAGING__COMMANDS_H\n#define IMAGING__COMMANDS_H\n\nnamespace Imaging\n{\n namespace LensCommands\n {\n\nenum commands_t {\n flush_birger = 0,\n init_focus,\n get_focus,\n set_focus,\n set_focus_incremental,\n load_focus,\n save_focus,\n init_aperture,\n get_aperture,\n set_aperture,\n load_aperture,\n save_aperture,\n version_string,\n define_aperture,\n define_focus,\n stop_aperture,\n stop_focus,\n set_aperture_velocity,\n set_focus_velocity,\n set_aperture_current,\n\tclearing_read_buffer // This needs to be the last command\n};\nstatic const unsigned int num_commands = 22;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.7029703259468079, "alphanum_fraction": 0.7128713130950928, "avg_line_length": 20.263158798217773, "blob_id": "c5c6393d9329d8cd5436f251a43e044eec1e20bf", "content_id": "cd71b47d92e3c22177f004ab82d4b86c3c11058a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 405, "license_type": "no_license", "max_line_length": 73, "num_lines": 19, "path": "/stars/code/solving/logger.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__LOGGER_H\n#define SOLVING__LOGGER_H\n\n#include \"../logging/logger.h\"\n\nnamespace Solving\n{\n // To be used only by the solver thread\n extern Logging::Logger logger;\n}\n\n#endif\n" }, { "alpha_fraction": 0.6949408650398254, "alphanum_fraction": 0.6962690353393555, "avg_line_length": 44.88088607788086, "blob_id": "bc8f06657d83f08733b27fd54c75a20e680b4e64", "content_id": "23ea72f1885886f6f210acf300c575e06eb7e5c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 16565, "license_type": "no_license", "max_line_length": 132, "num_lines": 361, "path": "/stars/code/networking/unloading.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"connection.h\"\n#include <boost/bind.hpp>\n#include <boost/format.hpp>\n#include \"logger.h\"\n#include \"../tools/angles.h\"\n#include \"../shared/lens/requests.h\"\n#include \"../shared/lens/results.h\"\n#include \"../imaging/commands.h\"\n#include \"../shared/solving/filters.h\"\n#include \"../shared/solving/settings.h\"\n#include \"../shared/solving/mask.h\"\n#include \"../shared/network/packets.h\"\n#include \"../shared/network/client.h\"\n#include \"../shared/network/image_client_settings.h\"\n#include \"../shared/camera/requests.h\"\n#include \"../shared/camera/results.h\"\n#include \"../shared/housekeeping/housekeeper.h\"\n#include \"../shared/autofocus/requests.h\"\n#include \"../shared/simulations/brightness.h\"\n#include \"../shared/general/main_settings.h\"\n#include \"../shared/general/shutdown.h\"\n#include \"../shared/general/network_reset.h\"\n#include \"../shared/general/quit.h\"\n#include \"../tools/quick_cout.h\"\n\n#define shared_lens_requests (*(Shared::Lens::fcp_requests_network_to_main.w))\n#define shared_lens_results (*(Shared::Lens::fcp_results_main_to_network.r))\n#define shared_packets (*(Shared::Network::packets.w))\n#define shared_image_client1_settings (*(Shared::Network::image_client_settings1.w))\n#define shared_image_client2_settings (*(Shared::Network::image_client_settings2.w))\n#define shared_housekeeper (*(Shared::Housekeeping::housekeeper_for_camera.w))\n#define shared_camera_requests (*(Shared::Camera::requests_for_main.w))\n#define shared_camera_results (*(Shared::Camera::results_for_network.r))\n#define shared_filters (*(Shared::Solving::filters_net_to_main.w))\n#define shared_solving_settings (*(Shared::Solving::settings.w))\n#define shared_mask (*(Shared::Solving::mask_network_for_solver.w))\n#define shared_autofocus_requests (*(Shared::Autofocus::requests_network_to_main.w))\n#define shared_brightness (*(Shared::Simulations::brightness.w))\n#define shared_shutdown (*(Shared::General::shutdown_for_main.w))\n#define shared_network_reset (*(Shared::General::network_reset_for_net_reset.w))\n#define shared_main_settings (*(Shared::General::main_settings_net_for_main.w))\n#define shared_client (*(Shared::Network::client_for_main.w))\n\nusing namespace Networking;\n\nbool Connection::check_command(unsigned int command_index)\n{\n if (command_index < xC_num_command_admins) {\n if (client_data.command_admins[command_index].is_new_countdown > 0) {\n if (local_command_admins[command_index].counter != client_data.command_admins[command_index].counter)\n {\n local_command_admins[command_index].counter = client_data.command_admins[command_index].counter;\n logger.log(format(\"network unloading: received command %i\") % command_index);\n return true;\n }\n }\n }\n else {\n logger.log(format(\"warning: tried to access command (%u) outside of array (size %u)\")\n % command_index % (unsigned int) xC_num_command_admins);\n }\n return false;\n}\n\nvoid Connection::unload_client_data_lens_and_camera()\n{\n using namespace Imaging::LensCommands;\n bool passed_something = false;\n\n passed_something = false;\n if (check_command(xC_flush_birger)) {\n shared_lens_requests.commands[flush_birger].counter = client_data.command_admins[xC_flush_birger].counter;\n passed_something = true;\n }\n if (check_command(xC_init_focus)) {\n shared_lens_requests.commands[init_focus].counter = client_data.command_admins[xC_init_focus].counter;\n passed_something = true;\n }\n if (check_command(xC_get_focus)) {\n shared_lens_requests.commands[get_focus].counter = client_data.command_admins[xC_get_focus].counter;\n passed_something = true;\n }\n if (check_command(xC_stop_focus)) {\n shared_lens_requests.commands[stop_focus].counter = client_data.command_admins[xC_stop_focus].counter;\n passed_something = true;\n }\n if (check_command(xC_set_focus)) {\n shared_lens_requests.commands[set_focus].counter = client_data.command_admins[xC_set_focus].counter;\n shared_lens_requests.commands[set_focus].value = client_data.set_focus_value;\n passed_something = true;\n }\n if (check_command(xC_set_focus_incremental)) {\n shared_lens_requests.commands[set_focus_incremental].counter = client_data.command_admins[xC_set_focus_incremental].counter;\n shared_lens_requests.commands[set_focus_incremental].value = client_data.set_focus_incremental_value;\n passed_something = true;\n }\n if (check_command(xC_define_focus)) {\n shared_lens_requests.commands[define_focus].counter = client_data.command_admins[xC_define_focus].counter;\n shared_lens_requests.commands[define_focus].value = client_data.define_focus_value;\n passed_something = true;\n }\n if (check_command(xC_init_aperture)) {\n shared_lens_requests.commands[init_aperture].counter = client_data.command_admins[xC_init_aperture].counter;\n passed_something = true;\n }\n if (check_command(xC_get_aperture)) {\n shared_lens_requests.commands[get_aperture].counter = client_data.command_admins[xC_get_aperture].counter;\n passed_something = true;\n }\n if (check_command(xC_stop_aperture)) {\n shared_lens_requests.commands[stop_aperture].counter = client_data.command_admins[xC_stop_aperture].counter;\n passed_something = true;\n }\n if (check_command(xC_set_aperture)) {\n shared_lens_requests.commands[set_aperture].counter = client_data.command_admins[xC_set_aperture].counter;\n shared_lens_requests.commands[set_aperture].value = client_data.set_aperture_value;\n passed_something = true;\n }\n if (check_command(xC_define_aperture)) {\n shared_lens_requests.commands[define_aperture].counter = client_data.command_admins[xC_define_aperture].counter;\n shared_lens_requests.commands[define_aperture].value = client_data.define_aperture_value;\n passed_something = true;\n }\n if (passed_something) {\n Shared::Lens::fcp_requests_network_to_main.share();\n }\n\n passed_something = false;\n if (check_command(xC_get_gain)) {\n shared_camera_requests.get_gain.counter = client_data.command_admins[xC_get_gain].counter;\n passed_something = true;\n }\n if (check_command(xC_set_gain)) {\n shared_camera_requests.set_gain.counter = client_data.command_admins[xC_set_gain].counter;\n shared_camera_requests.set_gain.value = client_data.set_gain_value;\n passed_something = true;\n }\n if (check_command(xC_multi_triggering)) {\n shared_camera_requests.multi_triggering_delay = client_data.multi_triggering_readout_delay;\n passed_something = true;\n }\n if (passed_something) {\n Shared::Camera::requests_for_main.share();\n }\n}\n\nvoid Connection::unload_client_data_autofocus()\n{\n bool passed_something = false;\n if (check_command(xC_run_autofocus)) {\n passed_something = true;\n shared_autofocus_requests.run_counter = client_data.command_admins[xC_run_autofocus].counter;\n }\n if (check_command(xC_set_autofocus_range)) {\n passed_something = true;\n shared_autofocus_requests.focus_search_min = client_data.autofocus_search_min;\n shared_autofocus_requests.focus_search_max = client_data.autofocus_search_max;\n shared_autofocus_requests.focus_search_step = client_data.autofocus_search_step;\n }\n if (check_command(xC_abort_autofocus)) {\n passed_something = true;\n shared_autofocus_requests.abort_counter = client_data.command_admins[xC_abort_autofocus].counter;\n shared_autofocus_requests.abort_still_use_solution = client_data.abort_autofocus_still_use_solution;\n }\n if (check_command(xC_autofocus_display_mode)) {\n passed_something = true;\n shared_autofocus_requests.display_mode = client_data.autofocus_display_mode;\n }\n if (passed_something) {\n Shared::Autofocus::requests_network_to_main.share();\n }\n}\n\nvoid Connection::unload_client_data_solver()\n{\n bool share_solving_settings = false;\n if (check_command(xC_solver_general)) {\n shared_solving_settings.enabled = client_data.solver.enabled;\n shared_solving_settings.timeout = client_data.solver.timeout;\n share_solving_settings = true;\n }\n if (check_command(xC_solver_abort)) {\n shared_solving_settings.abort_counter = client_data.command_admins[xC_solver_abort].counter;\n share_solving_settings = true;\n }\n if (check_command(xC_solver_mask)) {\n shared_mask.enabled = client_data.solver.mask.enabled;\n shared_mask.fields[0] = client_data.solver.mask.field0;\n shared_mask.fields[1] = client_data.solver.mask.field1;\n shared_mask.fields[2] = client_data.solver.mask.field2;\n Shared::Solving::mask_network_for_solver.share();\n }\n if (check_command(xC_solver_blob_finder)) {\n shared_solving_settings.snr_threshold = client_data.solver.snr_threshold;\n shared_solving_settings.max_num_blobs = client_data.solver.max_num_blobs;\n shared_solving_settings.robust_mode_enabled = client_data.solver.robust_mode_enabled;\n shared_solving_settings.fitting_method = client_data.solver.fitting_method;\n share_solving_settings = true;\n }\n if (check_command(xC_solver_blob_cells)) {\n shared_solving_settings.cell_size = client_data.solver.cell_size;\n shared_solving_settings.max_num_blobs_per_cell = client_data.solver.max_num_blobs_per_cell;\n share_solving_settings = true;\n }\n if (check_command(xC_solver_pattern_matcher)) {\n shared_solving_settings.pattern_matcher_enabled = client_data.solver.pattern_matcher_enabled;\n shared_solving_settings.display_names = client_data.solver.display_star_names;\n shared_solving_settings.match_tolerance_px = client_data.solver.match_tolerance_px;\n shared_solving_settings.iplatescale_min = client_data.solver.iplatescale_min;\n shared_solving_settings.iplatescale_max = client_data.solver.iplatescale_max;\n shared_solving_settings.platescale_always_fixed = client_data.solver.platescale_always_fixed;\n shared_solving_settings.iplatescale_fixed = client_data.solver.iplatescale_fixed;\n share_solving_settings = true;\n }\n if (share_solving_settings) {\n Shared::Solving::settings.share();\n }\n}\n\nvoid Connection::unload_client_data_solver_filters()\n{\n bool passed_something = false;\n\n if (client_data.horizontal.valid) {\n shared_filters.horizontal_from_fcp.age.start();\n shared_filters.horizontal_from_fcp.lat = client_data.horizontal.lat;\n shared_filters.horizontal_from_fcp.lst = client_data.horizontal.lst;\n passed_something = true;\n }\n\n if (check_command(xC_solver_filter_hor_location)) {\n shared_filters.horizontal_location.enabled = client_data.solver.filters.hor_location_limit_enabled;\n shared_filters.horizontal_location.radius = client_data.solver.filters.hor_location_limit_radius;\n passed_something = true;\n }\n if (shared_filters.horizontal_location.enabled) {\n shared_filters.horizontal_location.az = client_data.solver.filters.hor_location_limit_az;\n shared_filters.horizontal_location.el = client_data.solver.filters.hor_location_limit_el;\n passed_something = true;\n }\n\n if (check_command(xC_solver_filter_hor_roll)) {\n shared_filters.horizontal_roll_limit.enabled = client_data.solver.filters.hor_roll_limit_enabled;\n shared_filters.horizontal_roll_limit.min_roll = client_data.solver.filters.hor_roll_limit_min;\n shared_filters.horizontal_roll_limit.max_roll = client_data.solver.filters.hor_roll_limit_max;\n passed_something = true;\n }\n\n if (check_command(xC_solver_filter_hor_el)) {\n shared_filters.horizontal_elevation_limit.enabled = client_data.solver.filters.hor_el_limit_enabled;\n shared_filters.horizontal_elevation_limit.min_el = client_data.solver.filters.hor_el_limit_min;\n shared_filters.horizontal_elevation_limit.max_el = client_data.solver.filters.hor_el_limit_max;\n passed_something = true;\n }\n\n if (check_command(xC_solver_filter_eq_location)) {\n shared_filters.equatorial_location.enabled = client_data.solver.filters.eq_location_limit_enabled;\n shared_filters.equatorial_location.radius = client_data.solver.filters.eq_location_limit_radius;\n passed_something = true;\n }\n if (shared_filters.equatorial_location.enabled) {\n shared_filters.equatorial_location.ra = client_data.solver.filters.eq_location_limit_ra;\n shared_filters.equatorial_location.dec = client_data.solver.filters.eq_location_limit_dec;\n passed_something = true;\n }\n\n if (check_command(xC_solver_filter_matching)) {\n shared_filters.matching.pointing_error_threshold = client_data.solver.filters.matching_pointing_error_threshold;\n shared_filters.matching.fit_error_threshold_px = client_data.solver.filters.matching_fit_error_threshold_px;\n shared_filters.matching.num_matched = client_data.solver.filters.matching_num_matched;\n passed_something = true;\n }\n\n if (passed_something) {\n Shared::Solving::filters_net_to_main.share();\n }\n}\n\nvoid Connection::unload_main_and_display_settings()\n{\n bool passed_something = false;\n if (check_command(xC_main_settings)) {\n shared_main_settings.display_period = 1.0 / client_data.main_settings.display_frequency;\n shared_main_settings.display_fullscreen = client_data.main_settings.display_fullscreen;\n shared_main_settings.display_fullscreen_counter++;\n shared_main_settings.display_image_only = client_data.main_settings.display_image_only;\n shared_main_settings.display_solving_filters = client_data.main_settings.display_solving_filters;\n shared_main_settings.display_image_brightness = client_data.main_settings.display_image_brightness;\n passed_something = true;\n }\n if (check_command(xC_display_zoom)) {\n shared_main_settings.display_zoom_x = client_data.main_settings.display_zoom_x;\n shared_main_settings.display_zoom_y = client_data.main_settings.display_zoom_y;\n shared_main_settings.display_zoom_magnitude = client_data.main_settings.display_zoom_magnitude;\n passed_something = true;\n }\n if (passed_something) {\n Shared::General::main_settings_net_for_main.share();\n }\n}\n\nvoid Connection::unload_client_data()\n{\n if (check_command(xC_quit)) {\n Shared::General::quit = true;\n }\n\n if (shared_client.counter_fcp != client_data.counter_fcp) {\n shared_client.counter_fcp = client_data.counter_fcp;\n Shared::Network::client_for_main.share();\n }\n\n if (check_command(xC_shutdown)) {\n shared_shutdown.shutdown_now = client_data.shutdown.shutdown_now;\n shared_shutdown.include_restart = client_data.shutdown.include_restart;\n Shared::General::shutdown_for_main.share();\n }\n\n unload_main_and_display_settings();\n unload_client_data_lens_and_camera();\n unload_client_data_autofocus();\n\n if (check_command(xC_image_client)) {\n shared_image_client1_settings.enabled = client_data.image_client_enabled;\n shared_image_client2_settings.enabled = client_data.image_client_enabled;\n Shared::Network::image_client_settings1.share();\n Shared::Network::image_client_settings2.share();\n }\n\n if (check_command(xC_brightness)) {\n shared_brightness = client_data.brightness;\n Shared::Simulations::brightness.share();\n }\n\n unload_client_data_solver();\n unload_client_data_solver_filters();\n\n if (check_command(xC_network_reset)) {\n if (client_data.network_reset.reset_now) {\n shared_network_reset.reset_now_counter++;\n }\n shared_network_reset.reset_on_lull_enabled = client_data.network_reset.reset_on_lull_enabled;\n shared_network_reset.reset_on_lull_delay = client_data.network_reset.reset_on_lull_delay;\n Shared::General::network_reset_for_net_reset.share();\n }\n\tstatic int heater_state = -1;\n\n\tif (client_data.heater_state != heater_state) {\n\t\tlogger.log(\"Heater state is \" + std::to_string(client_data.heater_state));\n\t}\n\n\theater_state = client_data.heater_state;\n\tshared_housekeeper.heater_state = heater_state;\n\n}\n\n" }, { "alpha_fraction": 0.5801820755004883, "alphanum_fraction": 0.5957633256912231, "avg_line_length": 27.84848403930664, "blob_id": "d77ea921a29d24899b310d19be659ef6e39b5eb1", "content_id": "80a517005ce702b5720d075b57f448ed42f52222", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5712, "license_type": "no_license", "max_line_length": 101, "num_lines": 198, "path": "/starcam/testcomm.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//test program to communicate as the \"flight computer\" would (can use GUI or terminal)\n\n#include <iostream>\n#include <string>\n#include <string.h>\n#include <stdio.h>\n#include <sstream>\n#include <unistd.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <arpa/inet.h>\n#include <netdb.h> //for gethostbyname\n#include <cstdlib>\n#include \"camcommunicator.h\"\nextern \"C\" {\n#include \"udp.h\"\n}\n\n//these are reversed because the files are named from starcam perspective\nconst char* defaultCommTarget = \"192.168.1.11\"; //THEGOOD\n//const char* defaultCommTarget = \"192.168.1.12\"; //THEBAD\n//const char* defaultCommTarget = \"192.168.1.13\"; //THEUGLY\n\n#define SC_TIMEOUT 100 /* milliseconds */\n#define USE_COMMAND_GUI 0\n\n#if USE_COMMAND_GUI\n#include <qapplication.h>\n#include \"commandgui.h\"\n\nint main(int argc, char *argv[])\n{\n\tconst char* commTarget;\n\tif (argc == 1) {\n\t cout << \"Connecting to default host: \" << defaultCommTarget << endl;\n\t commTarget = defaultCommTarget;\n\t}\n\telse if (argc == 2) {\n\t commTarget = argv[1];\n\t cout << \"Connecting to host: \" << commTarget << endl;\n\t}\n\tQApplication a(argc, argv);\n\tCommandGUI gui(0, \"gui\", commTarget);\n\ta.setMainWidget(&gui);\n\tgui.setGeometry(100, 100, 600, 400);\n\tgui.show();\n\treturn a.exec();\n}\n\n#endif\n\n#if USE_COMMAND_GUI == 0\n//#include <unistd.h>\n//#include <fcntl.h>\n#include <pthread.h>\n#include \"camcommunicator.h\"\n#include \"camconfig.h\"\n\nstatic string ParseReturn(string rtnStr);\nstatic void* readLoop(void* arg);\nstatic void* sendLoop(void* arg);\nconst char* SCcmd = \"Oconf\";;\nint SCcmd_flag = 1;\n\nint main(int argc, char *argv[])\n\t\t\n{\n pthread_t readthread;\n pthread_t sendthread;\n pthread_create(&readthread, NULL, &readLoop, NULL);\n pthread_create(&sendthread, NULL, &sendLoop, NULL);\n\n pthread_join(readthread, NULL);\n pthread_join(sendthread, NULL);\n\n return 0;\n}\n\nvoid* sendLoop(void* arg)\n{\n int sock;\n string::size_type pos;\n string sought = \"\\n\";\n\n\t/* create a socket */\n sock = udp_bind_port(SC_PORT_GOOD, 1);\n\n if (sock == -1)\n cout << \"Unable to bind to port\" << endl;\n\n\twhile (1) {\n while (SCcmd_flag == 0) {\n sleep(1);\n }\n string cmd = string(SCcmd);\n //remove all newlines and add a single one at the end\n pos = cmd.find(sought, 0);\n while (pos != string::npos) {\n cmd.replace(pos, sought.size(), \"\");\n pos = cmd.find(sought, pos - sought.size());\n }\n cmd += \"\\n\";\n if (udp_bcast(sock, GOOD_PORT, strlen(cmd.c_str()), cmd.c_str(), 0))\n cout << \"error broadcasting command\" << endl;\n// cout << \"sent\" << endl;\n SCcmd_flag = 0;\n }\n return NULL;\n}\n\nvoid* readLoop(void* arg)\n{\n int sock, port;\n char peer[UDP_MAXHOST];\n char buf[UDP_MAXSIZE];\n string rtn_str = \"\";\n string line = \"\";\n string sought = \"\\n\";\n string::size_type pos;\n int recvlen;\n\n /* create a socket */\n sock = udp_bind_port(SC_PORT, 1);\n\n if (sock == -1)\n cout << \"Unable to bind to port\" << endl;\n\n\twhile (1) {\n rtn_str = \"\";\n\t\trecvlen = udp_recv(sock, SC_TIMEOUT, peer, &port, UDP_MAXSIZE, buf);\n// if (recvlen >= 0) {\n// buf[recvlen] = 0;\t/* expect a printable string - terminate it */\n// printf(\"received message: \\\"%s\\\"\\n\", buf);\n// }\n buf[recvlen] = '\\0';\n line += buf;\n while ((pos = line.find(\"\\n\",0)) != string::npos) {\n rtn_str = ParseReturn(line.substr(0,pos));\n line = line.substr(pos+1, line.length()-(pos+1));\n }\n }\n\treturn NULL;\n}\n\nstatic string ParseReturn(string rtnStr)\n{\n char buf[UDP_MAXSIZE];\n int expInt, expTime;\n int focusRes, moveTol;\n int maxBlobs, grid, threshold, minBlobDist;\n if (rtnStr.substr(0,5) == \"<str>\") { //response is string\n cout << \"Command returned string: \" << rtnStr << endl;\n\t\tstring Rstr = rtnStr.substr(5, rtnStr.size() - 11);\n\t\tif (Rstr[0] == 'E') //it is an errori\n cout << \"ERROR: \" << Rstr.substr(6, Rstr.size()-6).c_str() << endl;\n\t\telse if (Rstr.substr(0,6) == \"<conf>\") //contains config data\n { \n cout << \"config data\" << endl;\n\t\t\tRstr = Rstr.substr(6, Rstr.size()-6);\n istringstream sin;\n sin.str(Rstr);\n double temp; //value sent for expTime is a double\n sin >> expInt >> temp >> focusRes >> moveTol >> maxBlobs >> grid >> threshold >> minBlobDist;\n expTime = (int)(temp * 1000);\n cout << \"--- Exposure Interval = \" << expInt << endl\n << \"--- Exposure Time = \" << expTime << endl\n << \"--- Focus Resolution = \" << focusRes << endl\n << \"--- Move tolerance = \" << moveTol << endl\n << \"--- Max blobs = \" << maxBlobs << endl\n << \"--- Grid = \" << grid << endl\n << \"--- Threshold = \" << threshold << endl\n << \"--- Mib blob dist = \" << minBlobDist << endl;\n }\n } else { //otherwise it is a return struct\n StarcamReturn rtn;\n CamCommunicator::interpretReturn(rtnStr, &rtn);\n cout << \"\\n\\nObtained a picture return signal from camera #\" << rtn.camID << endl\n\t\t \t<< \"... mapmean =\" << rtn.mapmean << endl\n\t\t \t<< \"... sigma=\" << rtn.sigma << endl\n\t\t \t<< \"... exposuretime=\" << rtn.exposuretime << endl\n\t\t \t<< \"... imagestarttime=\" << rtn.imagestarttime.tv_sec << \"s \" \n\t\t\t<< rtn.imagestarttime.tv_usec << \"us\" << endl\n\t\t\t \t<< \"... ccdtemperature=\" << rtn.ccdtemperature << endl\n\t\t\t \t<< \"... focusposition=\" << rtn.focusposition << endl\n\t\t \t<< \"... numblobs=\" << rtn.numblobs << endl;\n }\n //reprompt\n\t\t cout << \"\\nEnter a string to send to the star camera (Ctrl-C quits): \";\n\t\t cin.getline(buf, 256);\n\t\t cout << \"Sending command: \" << buf << endl;\n SCcmd_flag = 1;\n SCcmd = buf;\n return \"\"; //doesn't send a response back to camera \n}\n\n#endif //if USE_COMMAND_GUI == 0\n" }, { "alpha_fraction": 0.7114093899726868, "alphanum_fraction": 0.7114093899726868, "avg_line_length": 11.5, "blob_id": "fbd7aeacc15ac77ddf998fc994f799a14ff6ac3b", "content_id": "e64b9acde50aa379c41dc005fc70e8bc8f917c2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 149, "license_type": "no_license", "max_line_length": 64, "num_lines": 12, "path": "/balloon_cam/motor.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//motor.h\n\n#ifndef MOTOR_H\n#define MOTOR_H\n\n#include \"locator.h\"\n\nMotor();\n\nvoid move(coords current);//moves the camera to the new location\n\n/#endif" }, { "alpha_fraction": 0.41540566086769104, "alphanum_fraction": 0.47666361927986145, "avg_line_length": 23.65168571472168, "blob_id": "4b28ea94b324355a98892c64720b2f9d351fe39a", "content_id": "f89d722acfcbff0bac81a768a334dda60f8c44e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10970, "license_type": "no_license", "max_line_length": 80, "num_lines": 445, "path": "/mccview/mccview.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* MCCview\n *\n * Copyright (C) 2013 D. V. Wiebe\n *\n * Usage of this software is permitted provided that this license is retained\n * with the software, so that any entity that uses this software is notified of\n * this license.\n *\n * DISCLAIMER: THIS SOFTWARE IS WITHOUT WARRANTY.\n */\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <getdata.h>\n#include <stdint.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <time.h>\n#include <ncurses.h>\n\n#define DRIVE0_UNMAP 0x0004\n#define DRIVE0_MASK 0x0007\n#define DRIVE1_UNMAP 0x0020\n#define DRIVE1_MASK 0x0038\n#define DRIVE2_UNMAP 0x0080\n#define DRIVE2_MASK 0x00C0\n\nint first = 1;\n\nstruct fft { const char *fmt; gd_type_t type; };\n\n#define NF 21\nstatic const struct fft ff[NF] = {\n {\"TIME_MCC%i\", GD_UINT64}, /* 0 */\n {\"TILE_HEATER_MCE%i\", GD_UINT16}, /* 1 */\n {\"DF_0_MCC%i\", GD_FLOAT64}, /* 2 */\n {\"DF_1_MCC%i\", GD_FLOAT64}, /* 3 */\n {\"DF_2_MCC%i\", GD_FLOAT64}, /* 4 */\n {\"DF_3_MCC%i\", GD_FLOAT64}, /* 5 */\n {\"state_mpc%i\", GD_UINT16}, /* 6 */\n {\"GOAL_MPC%i\", GD_UINT16}, /* 7 */\n {\"task_mpc%i\", GD_UINT16}, /* 8 */\n {\"DTASK_MPC%i\", GD_UINT16}, /* 9 */\n {\"T_MCC%i\", GD_FLOAT64}, /* 10 */\n {\"T_MCE%i\", GD_FLOAT64}, /* 11 */\n {\"ramp_count_mce%i\", GD_UINT16}, /* 12 */\n {\"DRIVE_MAP_MPC%i\", GD_UINT16}, /* 13 */\n {\"last_tune_mpc%i\", GD_UINT16}, /* 14 */\n {\"last_iv_mpc%i\", GD_UINT16}, /* 15 */\n {\"used_tune_mpc%i\", GD_UINT16}, /* 16 */\n {\"clamp_count_mce%i\", GD_UINT16}, /* 17 */\n {\"ref_tune_mpc%i\", GD_UINT16}, /* 18 */\n {\"tune_stat_mpc%i\", GD_UINT16}, /* 19 */\n {\"UPTIME_MPC%i\", GD_FLOAT64}, /* 20 */\n};\n\n#define NGF 14\nstatic const struct fft gf[NGF] = {\n {\"mce_blob\", GD_UINT16}, /* 0 */\n {\"blob_num_mpc\", GD_UINT16}, /* 1 */\n {\"reporting_mpcs\", GD_UINT16}, /* 2 */\n {\"alive_mpcs\", GD_UINT16}, /* 3 */\n {\"squid_veto_mpc\", GD_UINT16}, /* 4 */\n {\"BSET_NUM\", GD_UINT16}, /* 5 */\n {\"data_mode_mce\", GD_UINT16}, /* 6 */\n {\"UPPER_START_DMB\", GD_UINT16}, /* 7 */\n {\"UPPER_NBITS_DMB\", GD_UINT16}, /* 8 */\n {\"LOWER_START_DMB\", GD_UINT16}, /* 9 */\n {\"LOWER_NBITS_DMB\", GD_UINT16}, /* 10 */\n {\"mce_power\", GD_UINT16}, /* 11 */\n {\"sync_veto_mpc\", GD_UINT16}, /* 12 */\n {\"therm_veto_mpc\", GD_UINT16}, /* 13 */\n};\n\nunion du {\n double f64;\n uint64_t u64;\n};\nstatic union du d[6][NF];\nstatic union du gd[NGF];\n\n#define N_DTASKS 19\nconst char *dtasks[] = {\"idle\", \"setdir\", \"dsp_rst\", \"mce_rst\", \"reconfig\",\n \"start_acq\", \"fakestop\", \"empty\", \"status\", \"acq_cnf\", \"tuning\", \"del_acq\",\n \"iv_curve\", \"stop\", \"stop_mce\", \"lcloop\", \"bstep\", \"bramp\", \"kick\"\n};\n#define N_GOALS 9\nconst char *goals[] = {\"pause\", \"tune\", \"iv\", \"stop\", \"lcloop\", \"cycle\",\n \"acq\", \"bstep\", \"bramp\"};\n#define N_MODES 7\nconst char *modes[] = {\"none\", \"tuning\", \"iv_curve\", \"lcloop\", \"running\",\n \"bstep\", \"bramp\"};\n#define N_STATES 9\nconst char *states[N_STATES] = {\"POW\", \"DRI\", \"ACT\", \"COM\", \"SYN\", \"CFG\",\n \"BIA\", \"ACF\", \"RET\"};\n\nint sslen;\n\n#define NSS 16\nconst char *ssf[NSS] = {\n \"bc2:flux_fb(16)\",\n \"bc2:flux_fb(17)\",\n \"bc2:flux_fb(18)\",\n \"bc2:flux_fb(19)\",\n \"bc2:flux_fb(20)\",\n \"bc2:flux_fb(21)\",\n \"bc2:flux_fb(22)\",\n \"bc2:flux_fb(23)\",\n \"bc2:flux_fb(24)\",\n \"bc2:flux_fb(25)\",\n \"bc2:flux_fb(26)\",\n \"bc2:flux_fb(27)\",\n \"bc2:flux_fb(28)\",\n \"bc2:flux_fb(29)\",\n \"bc2:flux_fb(30)\",\n \"bc2:flux_fb(31)\"\n};\nint ssn[NSS][6];\nint sso;\nuint16_t *ssv;\n\nint ptot_count = 0;\n#define PTOT (NF * 6 + NGF + 0 * NSS)\n#define update_ptot() do { \\\n if (first) { printf(\"\\rinit %i/%i \", ++ptot_count, PTOT); fflush(stdout); } \\\n} while(0)\n\nstatic char drivemap(uint64_t map, int n)\n{\n if (n == 0) {\n if (map & DRIVE0_UNMAP)\n return '!';\n return (map & DRIVE0_MASK) + '0';\n } else if (n == 1) {\n if (map & DRIVE1_UNMAP)\n return '!';\n return ((map & DRIVE1_MASK) >> 3) + '0';\n } else {\n if (map & DRIVE2_UNMAP)\n return '!';\n return ((map & DRIVE2_MASK) >> 6) + '0';\n }\n}\n\nint mce_power(int x)\n{\n if (x == 1 || x == 2)\n return !(gd[11].u64 & 0x1);\n if (x == 3 || x == 5)\n return !(gd[11].u64 & 0x2);\n return !(gd[11].u64 & 0x4);\n}\n\nstatic char bits[NGF][7];\nchar *vetobits(int q, int t)\n{\n int i;\n\n for (i = 0; i < 6; ++i)\n bits[q][i] = '.';\n\n /* power veto */\n for (i = 0; i < 6; ++i)\n if (!mce_power(i))\n bits[q][i] = 'p';\n\n /* thermal veto */\n for (i = 0; i < 6; ++i)\n if (gd[t].u64 & (1U << i))\n bits[q][i] = 't';\n\n /* user veto */\n for (i = 0; i < 6; ++i)\n if (gd[q].u64 & (1U << i))\n bits[q][i] = 'V';\n\n return bits[q];\n}\n\nchar *mcebits(int n)\n{\n int i;\n\n for (i = 0; i < 6; ++i)\n bits[n][i] = (gd[n].u64 & (1U << i)) ? i + '1' : '.';\n return bits[n];\n}\n\nvoid ss_init(void)\n{\n#if 0\n int i;\n FILE *stream = fopen(\"/data/etc/spider/format.mce_mplex\", \"r\");\n char buffer[1024];\n\n if (stream == NULL) {\n perror(\"Unable to read format.mce_mplex\");\n exit(1);\n }\n\n while (fgets(buffer, 1024, stream)) {\n if (buffer[0] == '#' || buffer[0] == '/')\n continue;\n\n /* initialise the length */\n if (sslen == 0) {\n sslen = atoi(buffer + 42);\n if (sslen % 20)\n sslen = (1 + sslen / 20);\n else\n sslen = sslen / 20;\n\n ssv = malloc(sizeof(uint16_t) * sslen * 20);\n memset(ssv, 0, sizeof(uint16_t) * sslen * 20);\n update_ptot();\n }\n\n /* is this a match? */\n for (i = 0; i < NSS; ++i) {\n size_t len = strlen(ssf[i]);\n if (strncmp(buffer + 3, ssf[i], len) == 0) {\n ssn[i][buffer[1] - '1'] = atoi(buffer + 30 + len);\n update_ptot();\n }\n }\n }\n\n fclose(stream);\n#endif\n}\n\nvoid update_ss(DIRFILE *D, off_t lf, off_t fn)\n{\n}\n\nchar Abuffer[100];\nconst char *A(const char **v, int i, int l)\n{\n if (i >= l) {\n sprintf(Abuffer, \"(%i)\", i);\n return Abuffer;\n }\n return v[i];\n}\n\nchar delta_t_buffer[100];\nconst char *delta_t(double hours)\n{\n int d = hours / 24;\n int h = hours - d * 24;\n int m = (hours - d * 24 - h) * 60;\n if (d > 0)\n sprintf(delta_t_buffer, \"% 2i %02i:%02i\", d, h, m);\n else\n sprintf(delta_t_buffer, \" %02i:%02i\", h, m);\n\n return delta_t_buffer;\n}\n\nint main(int argc, char **argv)\n{\n unsigned state[6];\n char field[100];\n int f, x;\n size_t n;\n off_t fn, lf = 0;\n\n DIRFILE *D = gd_open((argc > 1) ? argv[1] : \"/data/etc/defile.lnk\",\n GD_RDONLY | GD_VERBOSE);\n if (!D)\n return 1;\n if (gd_error(D))\n return 1;\n\n ss_init();\n\n for (;;) {\n fn = gd_nframes64(D) - 4;\n if (fn < 1) {\n fprintf(stderr, \"\\nNo data.\\n\");\n return 1;\n }\n update_ss(D, lf, fn);\n\n for (f = 0; f < NGF; ++f) {\n if (gf[f].type == GD_UINT16)\n n = gd_getdata(D, gf[f].fmt, fn, 0, 0, 1, GD_UINT64, &gd[f].u64);\n else if (gf[f].type == GD_UINT64)\n n = gd_getdata(D, gf[f].fmt, fn, 0, 0, 1, GD_UINT64, &gd[f].u64);\n else if (gf[f].type == GD_FLOAT64)\n n = gd_getdata(D, gf[f].fmt, fn, 0, 0, 1, GD_FLOAT64, &gd[f].f64);\n\n update_ptot();\n\n if (gd_error(D)) {\n if (!first)\n endwin();\n return 1;\n }\n }\n\n for (x = 0; x < 6; ++x) {\n for (f = 0; f < NF; ++f) {\n sprintf(field, ff[f].fmt, x + 1);\n if (ff[f].type == GD_UINT16)\n n = gd_getdata(D, field, fn, 0, 0, 1, GD_UINT64, &d[x][f].u64);\n else if (ff[f].type == GD_UINT64)\n n = gd_getdata(D, field, fn, 0, 0, 1, GD_UINT64, &d[x][f].u64);\n else if (ff[f].type == GD_FLOAT64)\n n = gd_getdata(D, field, fn, 0, 0, 1, GD_FLOAT64, &d[x][f].f64);\n\n update_ptot();\n\n if (gd_error(D)) {\n if (!first)\n endwin();\n return 1;\n }\n if (n == 0)\n d[x][f].u64 = 0;\n }\n }\n\n if (first) {\n puts(\"\");\n initscr();\n noecho();\n keypad(stdscr, TRUE);\n cbreak();\n first = 0;\n }\n\n printw(\"Frame: %lli blob#%-6llu mce_blob:0x%04llX reporting:%s \"\n \"alive:%s veto:%s sync_veto:%s bset:%03llu dmode:%02llu \"\n \"bits:%02llu+%02llu/%02llu+%02llu\\n\", (long long)fn, gd[1].u64,\n gd[0].u64, mcebits(2), mcebits(3), vetobits(4, 13), mcebits(12),\n gd[5].u64, gd[6].u64, gd[7].u64, gd[8].u64, gd[9].u64, gd[10].u64);\n for (x = 0; x < 6; ++x)\n printw(\" X%i \", x + 1);\n printw(\"\\n\");\n\n for (x = 0; x < 6; ++x) {\n time_t t = d[x][0].u64;\n char ct[100];\n strcpy(ct, asctime(gmtime(&t)));\n ct[20] = 0;\n printw(\" %-22s\", ct);\n }\n printw(\"\\n\");\n\n /* add MCE power to the bottom of the state bitmap */\n for (x = 0; x < 6; ++x)\n state[x] = (unsigned)(d[x][6].u64 << 1) | (mce_power(x) ? 1 : 0);\n\n for (x = 0; x < 6; ++x)\n printw(\"uptime: %12s \", delta_t(d[x][20].f64));\n printw(\"\\n\");\n\n for (f = 0; f < 4; ++f) {\n for (x = 0; x < 6; ++x)\n printw(\" free%i: %11.3f GB \", f, d[x][2 + f].f64 / 1e9);\n printw(\"\\n\");\n }\n\n for (x = 0; x < 6; ++x)\n printw(\" d map: %c%c%c \",\n drivemap(d[x][13].u64, 0),\n drivemap(d[x][13].u64, 1),\n drivemap(d[x][13].u64, 2));\n printw(\"\\n\");\n\n for (f = 0; f < N_STATES; f += 3) {\n unsigned b = 1 << f;\n for (x = 0; x < 6; ++x)\n printw(\" %6s %3s %3s %3s \",\n (f == 3) ? \"state:\" : \"\",\n (state[x] & b) ? states[f] : \"...\",\n (state[x] & (b << 1)) ? states[f + 1] : \"...\",\n (state[x] & (b << 2)) ? states[f + 2] : \"...\");\n printw(\"\\n\");\n }\n\n for (x = 0; x < 6; ++x)\n printw(\" mode: %12s \", A(modes, d[x][6].u64 >> 8, N_MODES));\n printw(\"\\n\");\n\n for (x = 0; x < 6; ++x)\n printw(\" goal: %12s \", A(goals, d[x][7].u64, N_GOALS));\n printw(\"\\n\");\n\n for (x = 0; x < 6; ++x)\n printw(\" task: 0x%04X \", d[x][8].u64);\n printw(\"\\n\");\n\n for (x = 0; x < 6; ++x)\n printw(\" dtask: %12s \", A(dtasks, d[x][9].u64, N_DTASKS));\n printw(\"\\n\");\n\n for (x = 0; x < 6; ++x)\n printw(\" T mcc: %10.2f oC \", d[x][10].f64);\n printw(\"\\n\");\n\n for (x = 0; x < 6; ++x)\n printw(\" T mce: %10.2f oC \", d[x][11].f64);\n printw(\"\\n\");\n\n for (x = 0; x < 6; ++x)\n printw(\" ramp: %3llu \", d[x][12].u64);\n printw(\"\\n\");\n\n for (x = 0; x < 6; ++x)\n printw(\" clamp: %3llu \", d[x][17].u64);\n printw(\"\\n\");\n\n for (x = 0; x < 6; ++x)\n printw(\"used tune: %5llu \", d[x][16].u64);\n printw(\"\\n\");\n\n for (x = 0; x < 6; ++x)\n printw(\"last tune: %5llu \", d[x][14].u64);\n printw(\"\\n\");\n\n for (x = 0; x < 6; ++x)\n printw(\" ref tune: %5llu \", d[x][18].u64);\n printw(\"\\n\");\n\n for (x = 0; x < 6; ++x)\n printw(\"tune stat: %04llx \", d[x][19].u64);\n printw(\"\\n\");\n\n for (x = 0; x < 6; ++x)\n printw(\"last iv: %5llu \", d[x][15].u64);\n printw(\"\\n\");\n\n for (x = 0; x < 6; ++x)\n printw(\"heater: %11.3f V \", f, d[x][1].f64);\n printw(\"\\n\");\n\n refresh();\n usleep(500000);\n clear();\n }\n}\n" }, { "alpha_fraction": 0.6972704529762268, "alphanum_fraction": 0.7005789875984192, "avg_line_length": 29.200000762939453, "blob_id": "60934d317094aa9cbfc151cbdeddb7c7d33c2ac5", "content_id": "26ac3f4c79cef86bd319ff34241df9e54ab63cd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1210, "license_type": "no_license", "max_line_length": 94, "num_lines": 40, "path": "/stars/code/tools/ccd_projection.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef TOOLS__CCD_PROJECTION_H\n#define TOOLS__CCD_PROJECTION_H\n\nnamespace Shared\n{\n namespace Solving\n {\n struct Refraction;\n class Filters;\n }\n}\n\nnamespace Tools\n{\n\n void ccd_projection(double ra, double dec, double center_ra, double center_dec,\n double platescale, double cos_roll, double sin_roll, double& x, double& y,\n bool flipped_coordinate_system);\n\n void ccd_projection(double ra, double dec, double center_ra, double center_dec,\n double platescale, double roll, double& x, double& y, bool flipped_coordinate_system);\n\n void get_refraction_corrected_equatorial(double ra, double dec,\n Shared::Solving::Refraction& settings, Shared::Solving::Filters& filters,\n double& ra_corrected, double& dec_corrected);\n\n void get_refraction_corrected_horizontal(double ra, double dec,\n Shared::Solving::Refraction& settings, Shared::Solving::Filters& filters,\n double& az_corrected, double &el_corrected);\n\n}\n\n#endif\n\n" }, { "alpha_fraction": 0.5625, "alphanum_fraction": 0.5788934230804443, "avg_line_length": 20.19565200805664, "blob_id": "f5cc6d4cc092475a9e9e79a73a043a30d5d6e425", "content_id": "4fb8684688ef36f3e7bac8a3a12c9dac2b3959c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 977, "license_type": "no_license", "max_line_length": 73, "num_lines": 46, "path": "/stars/code/housekeeping/measurement.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"measurement.h\"\n\nusing namespace Housekeeping;\n\nMeasurement::Measurement()\n{\n channel = 0;\n name = \"\";\n scale = 1.0;\n offset = 0.0;\n units = \"\";\n for (unsigned int i=0; i<num_values; i++) {\n values[i] = 0.0;\n }\n next_write_index = 0;\n valid = false;\n}\n\nvoid Measurement::add_value(double value)\n{\n values[next_write_index] = value;\n next_write_index++;\n if (next_write_index == num_values) {\n valid = true;\n }\n next_write_index %= num_values;\n}\n\nbool Measurement::get_value(double& value)\n{\n value = 0.0;\n if (valid) {\n for (unsigned int i=0; i<num_values; i++) {\n value += values[i];\n }\n value /= num_values;\n value = value*scale + offset;\n }\n return valid;\n}\n\n" }, { "alpha_fraction": 0.548054039478302, "alphanum_fraction": 0.5758538246154785, "avg_line_length": 27.93678092956543, "blob_id": "27cec2ad06aca7ec57c32756b5231e0435e79d1f", "content_id": "c78f1dd2e8d8bb4cdab2a04284ad43329a2101da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5037, "license_type": "no_license", "max_line_length": 112, "num_lines": 174, "path": "/stars/code/displaying/texture.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"texture.h\"\n#if defined(_MSC_VER)\n #define NOMINMAX\n #include <windows.h>\n#endif\n#include <cstdlib>\n#include \"math.h\"\n#include <tiffio.h>\n#include \"GL/gl.h\"\n#include \"glhelper.h\"\n#include \"../logger_main.h\"\n\nusing namespace Displaying;\nusing Main::logger;\nusing std::min;\nusing std::max;\n\n\nTexture::Texture()\n{\n size = 0;\n used_width = 1.0;\n used_height = 1.0;\n}\n\nvoid Texture::init(int new_size, bool display_enabled)\n{\n if (display_enabled) {\n\t\tglGenTextures(1, &id);\n size_to_at_least(new_size);\n }\n}\n\nvoid Texture::init(bool display_enabled)\n{\n init(64, display_enabled);\n}\n\nvoid Texture::destroy(bool display_enabled)\n{\n if (display_enabled) {\n glDeleteTextures(1, &id);\n }\n}\n\nTexture::~Texture()\n{\n}\n\nvoid Texture::size_to_at_least(int min_size)\n{\n if (size < min_size) {\n int max_exp = 13;\t//changed from 13\n int exp = 6;\n while ((exp < max_exp) && (int(pow(2.0, exp)) < min_size)) exp++;\n int new_size = int(pow(2.0, exp));\n if (bind_blank(new_size, false)) {\n size = new_size;\n }\n }\n}\n\nint Texture::bind_blank(int new_size, bool black)\n{\n char* data;\n\tint maxval;\n data = (char*) malloc(sizeof(char)*new_size*new_size*4);\n for(int j=0; j<new_size; j++){\n for(int i=0; i<new_size; i++){\n data[(j*new_size+i)*4+0] = 0;\n data[(j*new_size+i)*4+1] = 0;\n data[(j*new_size+i)*4+2] = 0;\n if (black) {\n data[(j*new_size+i)*4+3] = char(255);\n } else {\n data[(j*new_size+i)*4+3] = 0; // why?\n }\n }\n }\n glBindTexture(GL_TEXTURE_2D, id); // Bind 0\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxval);\t\t//added by KNS\n\t\tif (new_size <= maxval) {\t\t\t\t\t\t//added by KNS\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, new_size, new_size,\n //0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, data);\n 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, data);\n\t\t}\n\t\telse logger.log(format(\"Could not bind image of size %d > max %d\") % new_size % maxval);\n\tfree(data);\n if (!glGetError()) return 1;\n return 0;\n}\n\nvoid Texture::bind_data(char* data, int width, int height)\n{\n\tGLenum error;\n \tsize_to_at_least(max(width, height));\n\tglBindTexture(GL_TEXTURE_2D, id); // Bind 1\n\tif ((error = glGetError()) != GL_NO_ERROR) logger.log(format(\"glBindTexture failed: %s\") % error);\n\n glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height,\n //GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, data);\n GL_BGRA_EXT, GL_UNSIGNED_BYTE, data);\n\tif ((error = glGetError())) logger.log(format(\"glTexSubImage failed for %d x %d: %s\") %width % height % error);\n\t\n\tused_width = double(width) / double(size);\n\tused_height = double(height) / double(size);\n \n glBindTexture(GL_TEXTURE_2D, 0); // unBind 1\n}\n\nvoid Texture::load_tiff(std::string filename)\n{\n TIFF* image = TIFFOpen(filename.c_str(), \"r\");\n if (image) {\n uint32 width = 0;\n uint32 height = 0;\n size_t num_pixels;\n uint32* raster;\n\n TIFFGetField(image, TIFFTAG_IMAGEWIDTH, &width);\n TIFFGetField(image, TIFFTAG_IMAGELENGTH, &height);\n num_pixels = width * height;\n raster = (uint32*) _TIFFmalloc(num_pixels * sizeof(uint32));\n if (raster != NULL) {\n if (TIFFReadRGBAImage(image, width, height, raster, 0)) {\n glBindTexture(GL_TEXTURE_2D, id); // Bind 2\n size_to_at_least(max(width, height));\n glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height,\n GL_RGBA, GL_UNSIGNED_BYTE, raster);\n if (!glGetError()) {\n used_width = double(width) / double(size);\n used_height = double(height) / double(size);\n }\n glBindTexture(GL_TEXTURE_2D, 0); // unBind 2\n }\n _TIFFfree(raster);\n }\n TIFFClose(image);\n }\n else {\n logger.log(format(\"Warning: could not load %s\") % filename);\n }\n}\n\nvoid Texture::draw(Size draw_size, double opacity) {\n glPushMatrix();\n Displaying::GL::Color4f(1.0, 1.0, 1.0, opacity);\n glBindTexture(GL_TEXTURE_2D, id); // Bind 3\n glBegin(GL_QUADS);\n glTexCoord2d(0.0, 0.0);\n glVertex2d(1.0, 1.0);\n glTexCoord2d(0.0, used_height);\n glVertex2d(1.0, draw_size.h-1.0);\n glTexCoord2d(used_width, used_height);\n glVertex2d(draw_size.w-1.0, draw_size.h-1.0);\n glTexCoord2d(used_width, 0.0);\n glVertex2d(draw_size.w-1.0, 1.0);\n glEnd();\n glBindTexture(GL_TEXTURE_2D, 0); // unBind 3\n glPopMatrix();\n}\n\nvoid Texture::draw(Size draw_size)\n{\n draw(draw_size, 1.0);\n}\n\n" }, { "alpha_fraction": 0.7133890986442566, "alphanum_fraction": 0.7217572927474976, "avg_line_length": 18.040000915527344, "blob_id": "f3c78e7c03ee5c724f2ff427df507895c84188ba", "content_id": "42ce8ac5ef49b9eb4d5ebd65fcb482823fa060fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 479, "license_type": "no_license", "max_line_length": 73, "num_lines": 25, "path": "/stars/code/parameters/housekeeping.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef PARAMETERS__HOUSEKEEPING_H\n#define PARAMETERS__HOUSEKEEPING_H\n\n#include \"group.h\"\n\nnamespace Parameters\n{\n class Housekeeping;\n}\n\nclass Parameters::Housekeeping: public Group\n{\n public:\n Housekeeping();\n void load(std::string filename);\n};\n\n#endif\n\n\n" }, { "alpha_fraction": 0.5461093783378601, "alphanum_fraction": 0.5610662698745728, "avg_line_length": 33.65182876586914, "blob_id": "82dab101d49d3c0a9041423e54ecdc608e41d54c", "content_id": "9d65f7624351c8918049b1be0fa961f0d19814c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 21796, "license_type": "no_license", "max_line_length": 162, "num_lines": 629, "path": "/defricher/defricher_writer.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * dirfile_writer.c: \n *\n * This software is copyright (C) 2013-2014 Seth Hillbrand\n *\n * This file is part of defricher, created for the BLASTPol Project.\n *\n * defricher 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 2 of the License, or\n * (at your option) any later version.\n *\n * defricher 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 defricher; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Apr 3, 2015 by Seth Hillbrand\n */\n\n#include <stdint.h>\n#include <stdbool.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <float.h>\n#include <math.h>\n#include <pthread.h>\n#include <getdata.h>\n#include <string.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <errno.h>\n#include <glib.h>\n\n#include <channels_tng.h>\n#include <channel_macros.h>\n#include <derived.h>\n#include <blast.h>\n\n#include \"FIFO.h\"\n#include \"linklist.h\"\n\n#include \"defricher.h\"\n#include \"defricher_utils.h\"\n#include \"defricher_data.h\"\n\nextern struct ri_struct ri;\n\nchannel_t *channels = NULL;\nchannel_t *new_channels = NULL;\nderived_tng_t *derived_channels = NULL;\n\nstatic GAsyncQueue *packet_queue = NULL;\ntypedef union {\n gpointer ptr;\n struct {\n uint8_t rate;\n uint16_t _dummy;\n };\n} queue_data_t;\n\nstatic int dirfile_offset = -1;\nstatic int dirfile_create_new = 0;\nstatic int dirfile_update_derived = 0;\nstatic bool dirfile_ready = false;\nstatic int dirfile_frames_written = 0;\n\nstatic void defricher_add_derived(DIRFILE *m_file, derived_tng_t *m_derived)\n{\n char lincom2_fields[2][FIELD_LEN];\n const char *lincom2_ptrs[2] = { lincom2_fields[0], lincom2_fields[1] };\n double lincom2_m[2];\n double lincom2_b[2];\n const char *lincom_name;\n\n for (derived_tng_t *derived = m_derived; derived && derived->type != DERIVED_EOC_MARKER; derived++) {\n switch (derived->type) {\n case 'w':\n case 'b':\n gd_add_bit(m_file, derived->bitword.field, derived->bitword.source, derived->bitword.offset, derived->bitword.length, 0);\n break;\n case 't':\n gd_add_linterp(m_file, derived->linterp.field, derived->linterp.source, derived->linterp.lut, 0);\n break;\n case 'c':\n lincom_name = derived->lincom.source;\n gd_add_lincom(m_file, derived->lincom.field, 1, &lincom_name, &derived->lincom.m_c2e, &derived->lincom.b_e2e, 0);\n break;\n case '2':\n strcpy(lincom2_fields[0], derived->lincom2.source);\n strcpy(lincom2_fields[1], derived->lincom2.source2);\n lincom2_b[0] = derived->lincom2.b_e2e;\n lincom2_b[1] = derived->lincom2.b2_e2e;\n lincom2_m[0] = derived->lincom2.m_c2e;\n lincom2_m[1] = derived->lincom2.m2_c2e;\n\n gd_add_lincom(m_file, derived->lincom2.field, 2, lincom2_ptrs, lincom2_m, lincom2_b, 0);\n break;\n case '#':\n break;\n case 'u':\n ///TODO: Remove this break after getdata library updated to avoid segfault here\n break;\n if (derived->units.units[0])\n gd_madd_string(m_file, derived->units.source, \"units\", derived->units.units);\n if (derived->units.quantity[0])\n gd_madd_string(m_file, derived->units.source, \"quantity\", derived->units.quantity);\n break;\n case 'p':\n gd_add_phase(m_file, derived->phase.field, derived->phase.source, derived->phase.shift, 0);\n break;\n case 'r':\n gd_add_recip(m_file, derived->recip.field, derived->recip.source, derived->recip.dividend, 0);\n break;\n case '*':\n gd_add_multiply(m_file, derived->math.field, derived->math.source, derived->math.source2, 0);\n break;\n case '/':\n gd_add_divide(m_file, derived->math.field, derived->math.source, derived->math.source2, 0);\n break;\n case 'x':\n gd_add_mplex(m_file, derived->mplex.field, derived->mplex.source, derived->mplex.index, derived->mplex.value, derived->mplex.max, 0);\n break;\n default:\n defricher_warn(\"Unknown type %c\", derived->type);\n break;\n }\n }\n gd_metaflush(m_file);\n}\n\n//TODO: Fix get_new_dirfilename to take options into account\nstatic char *defricher_get_new_dirfilename(void)\n{\n char *filename = NULL;\n static time_t start_time = 0;\n static uint32_t chunk = 0;\n\n if (!start_time) start_time = time(NULL);\n if (asprintf(&filename, \"%s/%lu_%03X.dirfile\", rc.dest_dir, start_time, chunk++) < 0)\n {\n defricher_fatal(\"Could not allocate memory for filename!\");\n filename=NULL;\n }\n\n return filename;\n}\nstatic void defricher_update_current_link(const char *m_name)\n{\n unlink(rc.symlink_name);\n\n defricher_mkdir_file(rc.symlink_name,1);\n if (symlink(m_name, rc.symlink_name))\n defricher_strerr(\"Could not create symlink from %s to %s\", m_name, rc.symlink_name);\n}\n\nstatic void defricher_free_channels_list (channel_t *m_channel_list)\n{\n if (!m_channel_list) return;\n\n for (channel_t *channel = m_channel_list; channel->field[0]; channel++) {\n defricher_cache_node_t *node = (defricher_cache_node_t*)channel->var;\n if ( node &&\n node->magic == BLAST_MAGIC32)\n {\n if (node->output.fp) {\n if (fclose(node->output.fp))\n defricher_strerr(\"Could not close %s\", node->output.name?node->output.name:\"UNK\");\n node->output.fp = NULL;\n }\n free(node);\n channel->var = NULL;\n }\n\n }\n}\n\n\nstatic int defricher_update_cache_fp(DIRFILE *m_dirfile, channel_t *m_channel_list)\n{\n char *filename;\n char error_str[2048];\n\n for (channel_t *channel = m_channel_list; channel->field[0]; channel++) {\n defricher_cache_node_t *outfile_node = channel->var;\n if (outfile_node && outfile_node->magic == BLAST_MAGIC32) {\n filename = gd_raw_filename(m_dirfile, outfile_node->output.name);\n if (!filename) {\n gd_error_string(m_dirfile, error_str, 2048);\n defricher_err(\"Could not get filename for %s: %s\", outfile_node->output.name, error_str);\n return -1;\n }\n outfile_node->output.fp = fopen(filename, \"w+\");\n\n if (!outfile_node->output.fp) {\n defricher_err(\"Could not open %s\", filename);\n free(filename);\n switch(errno) {\n case ELOOP:\n defricher_err(\"Too many loops in the directory %s. Please remove the directory and try again.\", outfile_node->output.name);\n break;\n case EPERM:\n case EACCES:\n defricher_err(\"Could not create %s. Please check that you have permission to write to the parent directory.\", outfile_node->output.name);\n break;\n case EMFILE:\n defricher_err(\"Too many open files. Typically this happens when your system limit is too low.\");\n defricher_err(\"\\tOn Linux and Mac, you can check the number of open files you allow by typing 'ulimit -n' in a terminal.\");\n defricher_err(\"\\tAs a general rule of thumb, you should allocate at least 65536.\");\n defricher_err(\"\\tTo do this on Linux, you can put `* soft nofiles 65536` and `* hard nofiles 65536` in /etc/security/limits.conf\");\n defricher_err(\"\\tTo do this on Mac, you can put `limit maxfiles 65536` in /etc/launchd.conf\");\n defricher_err(\"\\tOn both systems, you can then reboot for the changes to take effect\");\n break;\n case ENOSPC:\n defricher_err(\"No more space on device. Please clear additional storage space and try again.\");\n break;\n default:\n defricher_strerr(\"Unhandled error while opened files.\");\n break;\n }\n return -1;\n }\n free(filename);\n outfile_node->output.offset = 0;\n }\n }\n return 0;\n}\nstatic inline gd_type_t defricher_get_gd_type(const E_TYPE m_type)\n{\n gd_type_t type = GD_UNKNOWN;\n switch (m_type) {\n case TYPE_INT8:\n type = GD_INT8;\n break;\n case TYPE_UINT8:\n type = GD_UINT8;\n break;\n case TYPE_INT16:\n type = GD_INT16;\n break;\n case TYPE_UINT16:\n type = GD_UINT16;\n break;\n case TYPE_INT32:\n type = GD_INT32;\n break;\n case TYPE_UINT32:\n type = GD_UINT32;\n break;\n case TYPE_INT64:\n type = GD_INT64;\n break;\n case TYPE_UINT64:\n type = GD_UINT64;\n break;\n case TYPE_FLOAT:\n type = GD_FLOAT32;\n break;\n case TYPE_DOUBLE:\n type = GD_FLOAT64;\n break;\n default:\n defricher_err( \"Unknown type %d\", m_type);\n }\n return type;\n}\n\nstatic inline int defricher_get_rate(const E_RATE m_rate)\n{\n E_RATE rate = -1;\n switch (m_rate) {\n case RATE_1HZ:\n rate = 1;\n break;\n case RATE_5HZ:\n rate = 5;\n break;\n case RATE_100HZ:\n rate = 100;\n break;\n case RATE_200HZ:\n rate = 200;\n break;\n case RATE_244HZ:\n rate = 244;\n break;\n case RATE_488HZ:\n rate = 488;\n break;\n default:\n defricher_err( \"Unknown rate %d\", m_rate);\n }\n return rate;\n}\n\nstatic void defricher_transfer_channel_list(channel_t *m_channel_list)\n{\n for (channel_t *channel = m_channel_list; channel->field[0]; channel++) {\n gd_type_t type;\n defricher_cache_node_t *node = balloc(fatal, sizeof(defricher_cache_node_t));\n node->magic = BLAST_MAGIC32;\n node->raw_data = channel->var;\n node->output.name = channel->field;\n node->output.desc = NULL;\n node->output.lastval = 0;\n node->output.offset = 0;\n\n type = defricher_get_gd_type(channel->type);\n node->output.element_size = GD_SIZE(type);\n node->output.is_float = type & GD_IEEE754;\n node->output.is_signed = type & GD_SIGNED;\n\n node->output.rate = defricher_get_rate(channel->rate);\n channel->var = node;\n }\n}\n\nstatic DIRFILE *defricher_init_new_dirfile(const char *m_name, channel_t *m_channel_list)\n{\n DIRFILE *new_file;\n gd_type_t type;\n char tmp_str[512];\n double m,b;\n\n defricher_info(\"Intializing %s\", m_name);\n if (defricher_mkdir_file(m_name, true) < 0)\n {\n defricher_strerr(\"Could not make directory for %s\", m_name);\n return false;\n }\n\n new_file = gd_open(m_name, GD_CREAT|GD_RDWR|GD_PRETTY_PRINT|GD_VERBOSE);\n if (gd_error(new_file) == GD_E_OK)\n {\n m = 1e-5;\n b = 0.0;\n\n gd_alter_endianness(new_file, GD_BIG_ENDIAN, 0, 0);\n \n for (channel_t *channel = m_channel_list; channel->field[0]; channel++) {\n \n defricher_cache_node_t *node = (defricher_cache_node_t*)channel->var;\n\n type = defricher_get_gd_type(channel->type);\n \n if (gd_add_raw(new_file, node->output.name, type, node->output.rate, 0))\n {\n gd_error_string(new_file, tmp_str, 512);\n defricher_err( \"Could not add %s: %s\", node->output.name, tmp_str);\n }\n else\n {\n snprintf(tmp_str, 128, \"%s\", node->output.name);\n m = channel->m_c2e;\n b = channel->b_e2e;\n\n /// By default we set the converted field to upper case\n for (int i = 0; tmp_str[i]; i++) tmp_str[i] = toupper(tmp_str[i]);\n /// If our scale/offset are unity/zero respectively, tell defile to use the easier zero-phase\n if (fabs(m - 1.0) <= DBL_EPSILON && fabs(b - 0.0) <= DBL_EPSILON)\n gd_add_phase(new_file, tmp_str, node->output.name, 0, 0);\n else\n gd_add_lincom(new_file, tmp_str, 1, (const char **)&(node->output.name), &m, &b, 0);\n }\n }\n\n gd_reference(new_file, \"mcp_200hz_framecount\");\n gd_alter_frameoffset(new_file, dirfile_offset, GD_ALL_FRAGMENTS, 0);\n gd_metaflush(new_file);\n }\n else\n {\n gd_error_string(new_file, tmp_str, 512);\n defricher_fatal(\"Could not open %s as DIRFILE: %s\", m_name, tmp_str);\n gd_close(new_file);\n return NULL;\n }\n\n return new_file;\n}\n\nbool ready_to_read(uint16_t m_rate) {\n if (dirfile_offset < 0) {\n if (m_rate == RATE_1HZ) {\n channel_t *frame_offset = channels_find_by_name(\"mcp_1hz_framecount\");\n if (frame_offset) {\n defricher_cache_node_t *outfile_node = frame_offset->var;\n dirfile_offset = be32toh(*outfile_node->_32bit_data);\n defricher_info(\"Setting offset to %d\", dirfile_offset);\n\t\twhile(!dirfile_ready) {\n\t\t\tsleep(1);\n\t\t}\n\t\treturn true;\n } else {\n defricher_err(\"Missing \\\"mcp_1hz_framecount\\\" channel. Please report this!\");\n dirfile_offset = 0;\n\t\treturn false;\n }\n } else {\n /**\n * We are looking for the 1Hz packet to mark the start of a new frame. Until we receive\n * it, we discard the extra sub-frames.\n */\n return false;\n }\n }\n return true;\n}\n\nvoid defricher_queue_packet(uint16_t m_rate)\n{\n queue_data_t new_pkt = {._dummy = (1<<15)}; //Set this bit to avoid glib assertions\n new_pkt.rate = m_rate;\n g_async_queue_push(packet_queue, new_pkt.ptr);\n}\n\nstatic inline int defricher_new_framenum(uint16_t m_rate)\n{\n char *frame_counter_channel_name;\n\tblast_tmp_sprintf(frame_counter_channel_name, \"mcp_%dhz_framecount\", defricher_get_rate(m_rate));\n\tchannel_t *frame_counter_Addr = channels_find_by_name(frame_counter_channel_name);\n\tdefricher_cache_node_t *framenum_node = frame_counter_Addr->var;\n\treturn be32toh(*framenum_node->_32bit_data);\n}\n\nstatic inline int defricher_get_last_framenum(uint16_t m_rate)\n{\n char *frame_counter_channel_name;\n\tblast_tmp_sprintf(frame_counter_channel_name, \"mcp_%dhz_framecount\", defricher_get_rate(m_rate));\n\tchannel_t *frame_counter_Addr = channels_find_by_name(frame_counter_channel_name);\n defricher_cache_node_t *outfile_node = frame_counter_Addr->var;\n\treturn outfile_node->output.lastval;\n}\n\nstatic int defricher_write_packet(uint16_t m_rate)\n{\n static bool dirfile_have_warned = false;\n static bool write_have_warned = false;\n\n char *frame_counter_channel_name;\n\n if (ri.writer_done) {\n if (!write_have_warned) defricher_info(\"Not writing frame due to shutdown request\");\n write_have_warned = true;\n return -1;\n }\n\n if (!dirfile_ready) {\n if (!dirfile_have_warned) defricher_info(\"Discarding frame due to DIRFILE not being ready for writing\");\n dirfile_have_warned = 1;\n return -1;\n }\n\n // Writing new frame data to dirfile\n if (m_rate == RATE_200HZ) ri.wrote ++;\n for (channel_t *channel = channels; channel->field[0]; channel++) {\n if (channel->rate != m_rate) continue;\n defricher_cache_node_t *outfile_node = channel->var;\n // Filling in last value to use for missed frames\n blast_tmp_sprintf(frame_counter_channel_name, \"mcp_%dhz_framecount\", defricher_get_rate(m_rate));\n if (!strcmp(channel->field, frame_counter_channel_name)) {\n outfile_node->output.lastval = (int32_t) be32toh(*(outfile_node->_32bit_data));\n }\n if (outfile_node && outfile_node->magic == BLAST_MAGIC32 && outfile_node->output.fp ) {\n if (fwrite(outfile_node->raw_data, outfile_node->output.element_size, 1, outfile_node->output.fp) != 1) {\n defricher_err( \"Could not write to %s\", outfile_node->output.name);\n continue;\n }\n }\n }\n\n dirfile_frames_written++;\n return 0;\n}\n\nstatic void *defricher_write_loop(void *m_arg)\n{\n DIRFILE *dirfile = NULL;\n char *dirfile_name = NULL;\n int queue_length = 0;\n\n bprintf(info, \"Starting Defricher Write task\\n\");\n\n while (!ri.writer_done)\n {\n if (ri.new_channels) {\n ri.channels_ready = false;\n ri.new_channels = false;\n if (channels_initialize(new_channels) < 0) {\n defricher_err(\"Could not initialize channels\");\n free(new_channels);\n new_channels = NULL;\n for (int rate = 0; rate < RATE_END; rate++) {\n freeFifo(&fifo_data[rate]);\n }\n\n } else {\n defricher_free_channels_list(channels);\n if (channels) free(channels);\n channels = new_channels;\n new_channels = NULL;\n defricher_transfer_channel_list(channels);\n\n /* Parse the linklist, if present, and put into linklist mode */\n\t\t\t\t\t\t\t\tif (rc.linklist_file) {\n\t\t\t\t\t\t\t\t\trc.ll = parse_linklist_format(superframe, rc.linklist_file);\n\t\t\t\t\t\t\t\t}\n\n // initialize FIFO buffer\n int rate;\n int num_elements_in_fifo = 1;\n for (rate = 0; rate < RATE_END; rate++) {\n if (rate == 0) {\n num_elements_in_fifo = 5;\n } else {\n num_elements_in_fifo = defricher_get_rate(rate)*2;\n }\n allocFifo(&fifo_data[rate], num_elements_in_fifo, frame_size[rate]);\n }\n\n ri.channels_ready = true;\n dirfile_create_new = 1;\n dirfile_offset = -1;\n dirfile_ready = false;\n }\n \n\n }\n if (dirfile_create_new && dirfile_offset >= 0) {\n dirfile_name = rc.output_dirfile;\n rc.output_dirfile = defricher_get_new_dirfilename();\n BLAST_SAFE_FREE(dirfile_name);\n\n if (dirfile) gd_close(dirfile);\n dirfile = NULL;\n\n if (!(dirfile = defricher_init_new_dirfile(rc.output_dirfile, channels))) {\n defricher_err( \"Not creating new DIRFILE %s\", rc.output_dirfile);\n sleep(1);\n continue;\n }\n if (defricher_update_cache_fp(dirfile, channels) < 0) {\n defricher_err(\"Could not open all files for writing. Please report this error to Seth ([email protected])\");\n ri.writer_done = true;\n } else {\n dirfile_create_new = 0;\n dirfile_ready = true;\n ri.symlink_updated = false;\n dirfile_frames_written = 0;\n }\n }\n\n /// We wait until a frame is written to the dirfile before updating the link (for KST)\n if (dirfile_frames_written > 400 && !ri.symlink_updated) {\n defricher_update_current_link(rc.output_dirfile);\n ri.symlink_updated = true;\n }\n\n if (dirfile_ready && dirfile_update_derived) {\n defricher_add_derived(dirfile, derived_channels);\n dirfile_update_derived = 0;\n }\n\n while((queue_length = g_async_queue_length(packet_queue))) {\n queue_data_t pkt;\n\n if ((pkt.ptr = g_async_queue_pop(packet_queue))) {\n // transfer data from the fifo to channels data\n\t\t\t\t\t\t\t\tchannels_store_data(pkt.rate, getFifoRead(&fifo_data[pkt.rate]), frame_size[pkt.rate]); \n\t\t\t\t\t\t\t\tdecrementFifo(&fifo_data[pkt.rate]);\n\t\t\t\t\t\t\t\tdefricher_write_packet(pkt.rate);\n }\n usleep(100);\n }\n usleep(100);\n }\n\n if (dirfile) gd_close(dirfile);\n defricher_free_channels_list(channels);\n if (channels) free(channels);\n if (derived_channels) free(derived_channels);\n if (packet_queue) g_async_queue_unref(packet_queue);\n\n return NULL;\n}\n\nvoid defricher_request_new_dirfile(void)\n{\n dirfile_create_new = 1;\n}\n\nvoid defricher_request_updated_derived(void)\n{\n dirfile_update_derived = 1;\n}\n\n/**\n * Initializes the Defricher writing variables and loop\n * @return\n */\npthread_t defricher_writer_init(void)\n{\n size_t stack_size;\n pthread_attr_t attr;\n pthread_t write_thread;\n\n pthread_attr_init(&attr);\n pthread_attr_getstacksize(&attr, &stack_size);\n\n /**\n * GetData requires a rather large stack, on top of our own usage, so we set a\n * minimum of 2MB here to guard against smashing\n */\n if (stack_size < (1<<21)) {\n stack_size = (1<<21);\n pthread_attr_setstacksize(&attr, stack_size);\n }\n\n packet_queue = g_async_queue_new();\n if (!pthread_create(&write_thread, &attr, &defricher_write_loop, NULL))\n return write_thread;\n return 0;\n}\n" }, { "alpha_fraction": 0.5653928518295288, "alphanum_fraction": 0.5955376029014587, "avg_line_length": 31.9140625, "blob_id": "62f94cdf7c5f5c41ad47b0bb539a492603d37d82", "content_id": "a02572e071eafac9bdaadf4cd0184300738259df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4213, "license_type": "no_license", "max_line_length": 103, "num_lines": 128, "path": "/starcam/pyramid.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include \"stdint.h\"\n\n#ifndef __PYRAMID__H\n#define __PYRAMID__H\n\n#ifdef _WINDOWS_ // If in windows change packing order of frames to have\n#pragma pack(2) // same packing as Linux\n#endif\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\n#ifndef M_PI_2\n#define M_PI_2 1.57079632679489661923\n#endif\n\n#define CSI 1.0E-10\n#define MAXSOLUTION 200\n#define MAXBLOBS 100\n\n//type for entries in the star catalogue\ntypedef struct {\n double ra; //right ascension\n double dec; //declination\n float mag; //(apparent) magnitude\n} gsc_t;\n\n//type for entries in star pair & distance catalogue\ntypedef struct {\n //uint32_t I, J; //catalog indexes of each star in pair\n //uint32_t K; // ?????\n uint32_t I, J; //catalog indexes of each star in pair\n uint32_t K; // ?????\n double d; //distance between stars (on focal plane?)\n} rec_t;\n\n//type for pattern matching solutions\ntypedef struct {\n //uint32_t I[MAXBLOBS]; // Ignore - index into master catalogue\n //uint32_t B[MAXBLOBS]; // Blob index corresponding to C \n uint32_t I[MAXBLOBS]; // Ignore - index into master catalogue\n uint32_t B[MAXBLOBS]; // Blob index corresponding to C \n gsc_t* C[MAXBLOBS]; // Matched Star catalogue\n int flag;\n //uint32_t n;\n uint32_t n;\n} solution_t;\n\n//type for ???????\ntypedef struct {\n rec_t *r;\n uint32_t flag;\n} match_t;\n\n\nclass Pyramid {\n public:\n Pyramid();\n Pyramid(double fov, const char *catalogname, const char *katalogname);\n void Init(double fov, const char *catalogname, const char *katalogname);\n ~Pyramid(); \n \n int BuildCatalog(double ra0, double dec0, double r0);\n\n\n int Match(double*, double*, double, uint32_t);\n int GetSolution(double, double*, double*, int, solution_t**, int*, \n double*, double*, double*);\n\n int GetTestStars(double, double, double *, double *, \n uint32_t *, uint32_t);\n \n double Ra(int I) {return gsc[I].ra;}\n double Dec(int I) {return gsc[I].dec;}\n private:\n void SwapColumns(double *matrix, int ,int ,int, int);\n double* Product(double *matrix1, double *matrix2, int ,int , int);\n void Transpose(double *matrix, int ,int);\n double Determinant3x3(double *matrix);\n void GetCenter(double*, double*, int ,double&, double&, double&);\n double dist(double&, double&, double&, double&);\n double cdist(double&, double&, double&, double&);\n int GetIdx(double, double, uint32_t&, uint32_t&);\n int GetTriangle(uint32_t&, uint32_t&, \n uint32_t&, uint32_t n = 0); \n int s2tp(double, double, double, double, double&, double&);\n void tp2s(double&, double&, double, double, double, double);\n\n int StarPair(double* x, double*, uint32_t, double, solution_t*, uint32_t&); \n\n int StarTriangle(uint32_t, uint32_t, uint32_t,\n double, double, double, double, solution_t*, uint32_t&);\n\n int StarPyramid(uint32_t , double, double, double, double, solution_t*);\n\n\n int CheckSpecularTriangle(double*, double*, solution_t*);\n // ***********************************************\n\n //uint32_t ngsc; // number of starts in catalog\n uint32_t ngsc; // number of starts in catalog\n gsc_t *gsc; // pointd to the guide star catalog\n // sorted in increasing declination\n\n //uint32_t nrec; //size of pair & distance catalogue\n uint32_t nrec; //size of pair & distance catalogue\n rec_t *rec; // the catalogue itself\n\n\n solution_t *solution; //array of possible pattern-matching solutions\n int nsolution; //number of possible solutions\n\n int nkmap;\n int kidx;\n \n double c_fov; // cos(fov);\n double fov; // field of view (intest of length or width) in radians of sky\n\n double m, q; //coefficients of a linear distance vs index trend for the rec array (?)\n\n char *catalog; //star catalogue filename\n char *katalog; //pair & distance catalogue filename\n\n};\n\n\n#endif\n" }, { "alpha_fraction": 0.6558477878570557, "alphanum_fraction": 0.6746875643730164, "avg_line_length": 25.53960418701172, "blob_id": "d2187342ef731ea0eecd9b0853fb592e58d2ac15", "content_id": "468fc7e5bae7424ecdeda150b2678e1bbeb2ae60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5361, "license_type": "no_license", "max_line_length": 134, "num_lines": 202, "path": "/balloon_cam/server/server.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//server.cpp\n\n#include \"server.h\"\n\nServer::Server(){\n\tinit();\n}\n\nvoid Server::init(){\n\taddrinfo hints;\n\taddrinfo* serverInfo = (addrinfo *)malloc(sizeof(addrinfo));\n\n\tmemset(&hints, 0, sizeof(hints));\n\thints.ai_family = AF_INET;\n\thints.ai_socktype = SOCK_STREAM;\n\thints.ai_flags = AI_PASSIVE;\n\t//gets the address info for the laptop at 192.168.1.104\n\tint status = getaddrinfo(\"192.168.1.119\", DEFAULT_PORT, &hints, &serverInfo);\n\n\tif(status != 0){\n\t\tprintf(\"getaddrinfo fails, error %s\\n\", gai_strerror(status));\n\t\treturn;\n\t}\n\t//copies the data into the member variables\n\tservInfo = new addrinfo();\n\n\tmemcpy(servInfo, serverInfo, sizeof(*serverInfo));\n\n\tservInfo->ai_addr = new sockaddr();\n\n\tmemcpy(servInfo->ai_addr, serverInfo->ai_addr, sizeof(sockaddr));\n\t//calls socket to create an outgoing socket \n\tint socketFD = socket(servInfo->ai_family, servInfo->ai_socktype, servInfo->ai_protocol);\n\t//frees the now useless addrinfo struct\n\tfreeaddrinfo(serverInfo);\n\n\tif(socketFD == -1){\n\t\tprintf(\"Socket has failed.\\n\");\n\t}\n\n\tsocketFileDescriptor = socketFD;\n\t//sets a send timeout limit, otherwise it can hang perpetually\n\ttimeval timeLim;\n\ttimeLim.tv_sec = 30;\n\ttimeLim.tv_usec = 0;\n\n\tstatus = setsockopt(socketFileDescriptor, SOL_SOCKET, SO_SNDTIMEO, (void *) &timeLim, sizeof(timeval));\n\t\n\tif(status == -1){\n\t\tprintf(\"Setting the send timeout has failed. Error: %s\\n\",strerror(errno));\n\t}\n\n\tstatus = setsockopt(socketFileDescriptor, SOL_SOCKET, SO_RCVTIMEO, (void*) &timeLim, sizeof(timeval));\n\t\n\tif(status == -1){\n\t\tprintf(\"Setting the recieve timeout has failed. Error: %s\\n\", strerror(errno));\n\t}\n\n\t//conects to the laptop with information given in the addrinfo struct\n\tstatus = connect(socketFileDescriptor, servInfo->ai_addr, servInfo->ai_addrlen);\n\n\tif(status != 0){\n\t\tprintf(\"Connect has failed. Error: %s\\n\", strerror(errno));\n\t}\n\n\tlag = 0;\n\tlagTime.tv_usec = 0;\n\tlagTime.tv_sec = 0;\n}\n\nServer::~Server(){\n\n\tdelete servInfo->ai_addr;\n\tdelete servInfo;\n\n}\n\nvoid Server::runLoop(){\n\ntimeval timeValue;\nchar* data;\nbool resend = false;\nint x;\nint y;\ntimeval returnedTime;\n\n\n\twhile(true){\n\n\t\t//sleep(1);//for testng only. Otherwise it is way too fast\n\t\tif(!resend){\n\t\t\t//NOTE: TO BE REPLACED WITH SYSTEM CALL TO BLAST BUS SOMEHOW\n\t\t\tgettimeofday(&timeValue, NULL);//gets a time value\n\t\t\t\n\t\t\tif(abs(lagTime.tv_sec - timeValue.tv_sec) > 300){\n\t\t\t\tupdateLag();\n\t\t\t\tgettimeofday(&timeValue, NULL);\n\t\t\t}\n\t\t}\n\t\tprintf(\"sending data: %ld seconds, %ld microseconds\\n\", timeValue.tv_sec, timeValue.tv_usec);\n\t\tsendData(timeValue);//sends the query time to the laptop\n\t\tresend = false;\t\t\n\t\t\n\t\tdata = recieveData();//recieves the response\n\n\t\tif(!strcmp(data, \"resend\\n\")){//if there was a resend request\n\t\t\tprintf(\"Resending old data\\n\");\n\t\t\tresend = true;\n\t\t\tfree(data);\n\t\t\tcontinue;\n\t\t}else{\n\t\t\tif(!strcmp(data, \"\")){//if there was an error\n\t\t\t\tprintf(\"Exiting\\n\");\n\t\t\t\tfree(data);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t//extracts data from the string\n\t\t\tsscanf(data, \"X=%d;Y=%d;s=%ld;us=%ld\\n\", &x, &y, &returnedTime.tv_sec, &returnedTime.tv_usec);\n\t\t\tpassData(x, y, returnedTime);//passes data back to the blast bus\n\t\t\tfree(data);\n\t\t}\n\t}\n}\n\nvoid Server::sendData(timeval time){\n\t\n\tchar* buffer = (char*)malloc(100);\n\tsprintf(buffer,\"%ld s; %ld us;\\n\\0\", time.tv_sec, time.tv_usec);\n\t//sends data as a string\n\tint bytesSent = send(socketFileDescriptor, buffer, strlen(buffer), 0);\n\t//notifies that there was an error in sending. Does not retry, as this will \n\t//screw up the retry request\n\tif(bytesSent != strlen(buffer)){\n\t\tprintf(\"Not all data sent. Expect a retry request.\\n\");\n\t}\n\tfree(buffer);\n\n}\n\nchar* Server::recieveData(){\n\t//recieves data into a buffer\n\tchar* buffer = (char*) malloc(1000);\n\tint status = recv(socketFileDescriptor, buffer, 1000, 0);\n\t//makes damn sure there is a null character in there somewhere\n\t*(buffer + 999) = '\\0';\n\t*(buffer + status) = '\\0';\n\n\t//NOTE: RAND IS HERE FOR TESTING PURPOSES. REMOVE IT BEFORE USE \n\tif((status < 0)/*||(rand() %10 < 2)*/){//if there was an error\n\t\tprintf(\"Recieve has failed. Error: %s\\n\", strerror(errno));\n\t\tfree(buffer);\n\t\ttimeval fakeTime;\n\t\tfakeTime.tv_sec = -2;\n\t\tsendData(fakeTime);//send a retry request\n\t\treturn recieveData();\n\t}\t\t\n\tif(status == 0){//if the connection has closed from the other end\n\t\tprintf(\"Client has closed the connection\\n\");\n\t\tfree(buffer);\n\t\tchar* fakeString = new char();//fakes a return value\n\t\treturn fakeString;\n\t}\n\tif(strchr(buffer, '\\n') != NULL){//otherwise, if the string is properly formatted\n\t\treturn buffer;\n\t}\n}\n\n//NOTE: DUMMY IMPLEMENTATION. TO BE REPLACED WITH SOME SORT OF SYSTEM CALL\n\nvoid Server::passData(int x, int y, timeval t){\n\n\tprintf(\"Data callibrated: X = %d, y = %d, s = %ld, us = %ld\\n\", x, y, t.tv_sec + ((lag/2)/1000000), t.tv_usec + ((lag/2) % 1000000));\n\n}\n\n\nvoid Server::updateLag(){\n\ttimeval fakeTime;\n\tfakeTime.tv_sec = -3;\n\tfakeTime.tv_usec = 0;\n\tchar* returnedData;\n\ttimeval sysTime1;\n\ttimeval sysTime2;\n\tlag = 0;\n\tfor(int i = 0; i< 10; i++){\n\t\t\n\t\tgettimeofday(&sysTime1, NULL);\n\t\tsendData(fakeTime);\n\t\treturnedData = recieveData();\n\t\tif(strcmp(returnedData, \"ping\\n\")){\n\t\t\tprintf(\"Ping not returned, instead got: %s\\n\", returnedData);\n\t\t}\n\n\t\tgettimeofday(&sysTime2, NULL);\n\t\tlag += ((sysTime2.tv_sec - sysTime1.tv_sec)*1000000 + (sysTime2.tv_usec - sysTime1.tv_usec));\n\t}\n\n\tlag /= 10;\n\tprintf(\"Lag found to be %d us\\n\", lag);\n\tlagTime = sysTime2;\n\n}\n" }, { "alpha_fraction": 0.5038976669311523, "alphanum_fraction": 0.5188886523246765, "avg_line_length": 37.880828857421875, "blob_id": "551a514fbaaff6ca04a1ea94bb329068750cf5fc", "content_id": "a8fb075884d708ca17824dc2e347767148b0d620", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15009, "license_type": "no_license", "max_line_length": 180, "num_lines": 386, "path": "/groundhog/blast/highrate.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <math.h>\n#include <fcntl.h>\n#include <stdbool.h>\n#include <arpa/inet.h> // socket stuff\n#include <netinet/in.h> // socket stuff\n#include <stdio.h> // socket stuff\n#include <sys/types.h> // socket types\n#include <sys/socket.h> // socket stuff\n#include <sys/stat.h>\n#include <dirent.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <signal.h>\n#include <stdlib.h>\n#include <string.h>\n#include <pthread.h> // threads\n#include <openssl/md5.h>\n#include <float.h>\n#include <time.h>\n#include <sys/time.h>\n\n#include \"groundhog.h\"\n\nstruct TlmReport highrate_report = {0};\nstruct TlmReport sbd_report = {0};\n\nenum HeaderType{NONE, TD_HK, TD_OMNI_HGA, IRID_HK, IRID_DIAL, PAYLOAD};\n\nstruct CSBFHeader {\n uint8_t route;\n uint8_t origin;\n uint8_t comm;\n uint8_t zero;\n uint16_t size;\n\n uint8_t checksum;\n enum HeaderType mode;\n uint8_t sync;\n\n char namestr[80];\n};\n\n\nchar * comm_label[2] = {\"COMM1\", \"COMM2\"};\n\nenum HeaderType read_csbf_header(struct CSBFHeader * header, uint8_t byte) {\n header->mode = NONE;\n\n if ((header->sync == 0) && (byte == HIGHRATE_SYNC1)) {\n header->sync++;\n } else if (header->sync == 1) {\n switch (byte) {\n case LOWRATE_COMM1_SYNC2 :\n case LOWRATE_COMM2_SYNC2 :\n case HIGHRATE_TDRSS_SYNC2 :\n case HIGHRATE_IRIDIUM_SYNC2 :\n header->route = byte;\n header->sync++;\n break;\n default :\n header->sync = 0;\n }\n } else if (header->sync == 2) {\n header->origin = byte & 0x07; // bits 0-2 == 0 is hk, == 1 is low rate, == 2 is high rate\n header->comm = ((byte & 0x08) >> 3); // bit 3 == 0 is comm1, == 1 is comm2\n header->checksum = byte; \n\n header->sync++;\n } else if (header->sync == 3) {\n header->zero = byte;\n header->checksum += byte;\n\n header->sync++; \n } else if (header->sync == 4) { // size MSB\n header->size = byte << 8;\n header->checksum += byte;\n\n header->sync++;\n } else if (header->sync == 5) { // size LSB\n header->size += byte;\n header->checksum += byte; \n\n if (header->zero) {\n header->mode = PAYLOAD;\n } else if (header->route == HIGHRATE_IRIDIUM_SYNC2) {\n switch (header->origin) {\n case 0x01:\n case 0x00:\n header->mode = IRID_HK;\n sprintf(header->namestr, \"Iridium HK %s\", comm_label[header->comm]);\n break;\n case 0x02:\n header->mode = IRID_DIAL;\n sprintf(header->namestr, \"Iridium Dialup %s\", comm_label[header->comm]);\n break;\n default:\n blast_info(\"Unrecognized Iridium origin byte 0x%x\\n\", header->origin+(header->comm << 3));\n \n }\n } else if (header->route == HIGHRATE_TDRSS_SYNC2) {\n switch (header->origin) {\n case 0x01:\n case 0x00:\n header->mode = TD_HK;\n sprintf(header->namestr, \"TDRSS HK %s\", comm_label[header->comm]);\n break;\n case 0x02:\n header->mode = TD_OMNI_HGA;\n sprintf(header->namestr, \"TDRSS Omni/HGA %s\", comm_label[header->comm]);\n break;\n default:\n blast_info(\"Unrecognized TDRSS origin byte 0x%x\\n\", header->origin+(header->comm << 3));\n \n }\n }\n header->sync = 0;\n }\n return header->mode;\n}\n\n// grabs a packet from the gse stripped of it gse header\nvoid read_gse_sync_frame(int fd, uint8_t * buffer, struct CSBFHeader * header) {\n uint8_t byte = 0;\n unsigned int bytes_read = 0;\n memset(header, 0, sizeof(struct CSBFHeader));\n\n while (true) {\n if (read(fd, &byte, 1) == 1) {\n if (header->mode == NONE) {\n read_csbf_header(header, byte);\n } else if (header->mode != PAYLOAD) { // end of gse/payload header\n if (bytes_read < header->size) { // keep reading to the buffer \n buffer[bytes_read++] = byte;\n header->checksum += byte;\n } else {\n if (header->checksum == byte) { // done reading \n // printf(\"Received gse packet size %d (0x%x == 0x%x)\\n\", header->size, byte, header->checksum); \n return;\n } else {\n blast_info(\"[%s] Bad checksum 0x%.2x != 0x%.2x\", header->namestr, header->checksum, byte);\n }\n bytes_read = 0;\n memset(header, 0, sizeof(struct CSBFHeader));\n }\n } else { // payload packet, so ignore\n bytes_read = 0;\n memset(header, 0, sizeof(struct CSBFHeader));\n }\n } else { // nothing read\n usleep(1000);\n }\n }\n}\n\n// grabs a packet from the gse stripped of it gse header\nvoid read_gse_sync_frame_direct(int fd, uint8_t * buffer, unsigned int length) {\n uint8_t byte = 0;\n unsigned int bytes_read = 0;\n\n while (true) {\n if (read(fd, &byte, 1) == 1) {\n buffer[bytes_read++] = byte;\n\n if (bytes_read >= length) { // done reading from the buffer \n return;\n }\n } else { // nothing read\n usleep(1000);\n }\n }\n}\n\nvoid highrate_receive(void *arg) {\n // Open serial port\n unsigned int serial_mode = (unsigned long long) arg;\n comms_serial_t *serial = comms_serial_new(NULL);\n char linkname[80];\n if (serial_mode) { // direct\n comms_serial_connect(serial, DIRECT_PORT);\n sprintf(linkname, \"TDRSSDirect\");\n } else { // highrate\n comms_serial_connect(serial, HIGHRATE_PORT);\n sprintf(linkname, \"SerHighRate\");\n }\n comms_serial_setspeed(serial, B115200);\n int fd = serial->sock->fd; \n\n linklist_t * ll = NULL;\n linklist_t * sbd_ll = NULL;\n\n // open a file to save all the raw linklist data\n linklist_rawfile_t * ll_rawfile = NULL;\n linklist_rawfile_t * sbd_ll_rawfile = NULL;\n uint32_t ser = 0, prev_ser = 0, sbd_ser = 0, sbd_prev_ser = 0;\n\n // packet sizes\n unsigned int payload_packet_size = (HIGHRATE_DATA_PACKET_SIZE+CSBF_HEADER_SIZE+1)*2;\n uint16_t datasize = HIGHRATE_DATA_PACKET_SIZE-PACKET_HEADER_SIZE;\n uint32_t buffer_size = ((HIGHRATE_MAX_SIZE-1)/datasize+1)*datasize;\n\n // buffer allocations\n uint8_t *payload_packet = calloc(1, payload_packet_size);\n uint8_t *csbf_header = payload_packet+0;\n uint8_t *header_buffer = csbf_header+CSBF_HEADER_SIZE;\n uint8_t *data_buffer = header_buffer+PACKET_HEADER_SIZE;\n // uint8_t *csbf_checksum = header_buffer+HIGHRATE_DATA_PACKET_SIZE;\n\n // packetization variables\n uint32_t *serial_number = 0;\n uint16_t *i_pkt, *n_pkt;\n uint32_t *frame_number;\n uint32_t transmit_size;\n uint8_t *compbuffer = calloc(1, buffer_size);\n\n uint8_t *local_allframe = calloc(1, superframe->allframe_size);\n\n struct CSBFHeader gse_packet_header = {0};\n uint8_t * gse_packet = calloc(1, 4096);\n unsigned int gse_read = 0;\n\n struct CSBFHeader payload_packet_header = {0};\n unsigned int payload_read = 0;\n unsigned int payload_copy = 0;\n uint8_t payload_packet_lock = 0;\n uint16_t payload_size = 0;\n\n int retval = 0;\n uint32_t recv_size = 0;\n int64_t framenum = 0;\n int af = 0;\n\n char * source_str = NULL;\n\n while (true) {\n // printf(\"-------------START (lock = %d)---------\\n\", payload_packet_lock);\n\n // get the sync frame from the gse\n if (serial_mode) { // direct\n // mimic the return header values for highrate\n gse_packet_header.size = 2048;\n gse_packet_header.origin = 0xe;\n sprintf(gse_packet_header.namestr, \"TDRSS Direct\");\n\n read_gse_sync_frame_direct(fd, gse_packet, gse_packet_header.size);\n } else { // highrate\n read_gse_sync_frame(fd, gse_packet, &gse_packet_header);\n }\n\n gse_read = 0;\n source_str = gse_packet_header.namestr;\n\n /* \n for (int i = 0; i < gse_packet_header.size; i++) {\n if (i%32 == 0) printf(\"\\n%.3d : \", i/32);\n printf(\"0x%.2x \", gse_packet[i]);\n }\n printf(\"\\n\");\n */\n\n // printf(\"Got a GSE packet size %d origin 0x%x\\n\", gse_packet_header.size, gse_packet_header.origin);\n \n while (gse_read < gse_packet_header.size) { // read all the gse data\n\n if ((gse_packet_header.mode != TD_HK) && (gse_packet_header.mode != IRID_HK)) { // packet not from the hk stack (origin != 0)\n if (payload_packet_lock) { // locked onto payload header \n payload_copy = MIN(payload_size-payload_read, gse_packet_header.size-gse_read);\n \n if (payload_read+payload_copy > payload_packet_size) {\n blast_err(\"Received more data (%d) than expected (%d). Losing lock\\n\", payload_read+payload_copy, payload_packet_size);\n payload_packet_lock = 0;\n continue;\n }\n\n memcpy(payload_packet+payload_read, gse_packet+gse_read, payload_copy);\n\n gse_read += payload_copy; // update bytes read from gse\n // printf(\"Copied %d bytes to location %d. %d bytes left to read\\n\", payload_copy, payload_read, gse_packet_header.size-gse_read);\n payload_read += payload_copy; // update bytes read to to payload packet\n\n if (payload_read == payload_size) { // read all of the payload packet\n // printf(\"Got the entire payload message\\n\");\n // reset bookkeeping variables\n payload_read = 0;\n payload_packet_lock = 0;\n memset(&payload_packet_header, 0, sizeof(struct CSBFHeader));\n\n // process the packet\n readHeader(header_buffer, &serial_number, &frame_number, &i_pkt, &n_pkt);\n\n // hijack frame number for transmit size\n transmit_size = *frame_number;\n\n if (!(ll = linklist_lookup_by_serial(*serial_number))) {\n blast_err(\"[%s] Could not find linklist with serial 0x%.4x\", source_str, *serial_number);\n continue; \n }\n ser = *serial_number;\n\n // blast_info(\"Transmit size=%d, blk_size=%d, payload_size=%d, datasize=%d, i=%d, n=%d\", transmit_size, ll->blk_size, payload_size, datasize, *i_pkt, *n_pkt);\n\n retval = depacketizeBuffer(compbuffer, &recv_size, \n HIGHRATE_DATA_PACKET_SIZE-PACKET_HEADER_SIZE,\n i_pkt, n_pkt, data_buffer);\n\n memset(payload_packet, 0, payload_packet_size);\n\n // the packet is complete, so decompress\n if ((retval == 0) && (ll != NULL))\n {\n if (groundhog_check_for_fileblocks(ll, FILE_LINKLIST)) {\n // unpack and extract to disk\n framenum = groundhog_unpack_fileblocks(ll, transmit_size, compbuffer, NULL,\n NULL, NULL, NULL, GROUNDHOG_EXTRACT_TO_DISK);\n } else { // write the linklist data to disk\n // set flags for data extraction\n unsigned int flags = 0;\n if (ser != prev_ser) flags |= GROUNDHOG_OPEN_NEW_RAWFILE;\n prev_ser = ser;\n\n // process the linklist and write the data to disk\n framenum = groundhog_process_and_write(ll, transmit_size, compbuffer,\n local_allframe, linkname, \n source_str, &ll_rawfile, flags);\n }\n // fill out the telemetry report\n highrate_report.ll = ll;\n highrate_report.framenum = abs(framenum);\n highrate_report.allframe = af; \n\n memset(compbuffer, 0, buffer_size);\n recv_size = 0;\n }\n }\n } else if (!payload_packet_lock) { // search for payload header\n read_csbf_header(&payload_packet_header, gse_packet[gse_read++]);\n if (payload_packet_header.mode == PAYLOAD) {\n payload_size = payload_packet_header.size+CSBF_HEADER_SIZE+1; // payload includes the header and checksum\n payload_packet_lock = 1;\n payload_read = CSBF_HEADER_SIZE;\n // printf(\"Found a payload header @ %d size %d bytes\\n\", gse_read, payload_size);\n }\n } \n \n } else if ((gse_packet_header.origin == 0) || (gse_packet_header.origin == 1)) { // housekeeping packet\n gse_read += gse_packet_header.size;\n\n // short burst data (sbd) packets are simple:\n // 4 bytes for the linklist serial followed by the data\n if (!(*(uint32_t *) gse_packet)) {\n blast_info(\"[%s] Empty HK packet\", source_str);\n continue;\n }\n \n if (!(sbd_ll = linklist_lookup_by_serial(*(uint32_t *) gse_packet))) {\n blast_err(\"[%s] Could not find linklist with serial 0x%.4x\", source_str, *(uint32_t *) gse_packet);\n continue; \n }\n sbd_ser = *(uint32_t *) gse_packet;\n\n // set flags for data extraction\n unsigned int flags = 0;\n if (sbd_ser != sbd_prev_ser) flags |= GROUNDHOG_OPEN_NEW_RAWFILE;\n sbd_prev_ser = sbd_ser;\n\n // TODO(javier): check this with sipsim or real sip\n blast_info(\"[%s] Received packet \\\"%s\\\" from HK stack (size=%d)\\n\", source_str, sbd_ll->name, gse_packet_header.size);\n\n // process the linklist and write the data to disk\n framenum = groundhog_process_and_write(sbd_ll, MIN(gse_packet_header.size, sbd_ll->blk_size), \n gse_packet+sizeof(uint32_t), local_allframe,\n \"ShortBurst\", source_str, &sbd_ll_rawfile, flags);\n // fill out the telemetry report\n sbd_report.ll = sbd_ll;\n sbd_report.framenum = abs(framenum);\n sbd_report.allframe = 0; \n /*\n if (*(uint32_t *) gse_packet == SLOWDLSYNCWORD) {\n \n } else {\n blast_info(\"[%s] Bad syncword 0x%.08x\\n\", source_str, *(uint32_t *) gse_packet);\n }\n */\n }\n }\n }\n}\n\n" }, { "alpha_fraction": 0.6499229669570923, "alphanum_fraction": 0.6576235294342041, "avg_line_length": 23.678361892700195, "blob_id": "49b6c4243637f3cc1fec974d3a42a9efcd3b91d1", "content_id": "9df3712b98a9460d82341851dd67b6387c4ae3de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8441, "license_type": "no_license", "max_line_length": 96, "num_lines": 342, "path": "/starcam/fifocommunicator.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//this class is no longer being used. instead use CamCommunicator with a localhost socket\n\n#include <string>\n#include <sstream>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/select.h>\n#include \"fifocommunicator.h\"\n\n#define FIFO_DEBUG 0\n#if FIFO_DEBUG\n#include <iostream>\n#endif\n\n#define FIFO_BUF_SIZE 255\n\n/*\n\n FIFOCommunicator:\n \n Default constructor. Initializes variables\n \n*/\nFIFOCommunicator::FIFOCommunicator()\n{\n\tInit();\n}\n\n/*\n\n FIFOCommunicator:\n \n Useful constructor. Initializes variables and opens read and write FIFOs\n \n*/\nFIFOCommunicator::FIFOCommunicator(string fifoInName, string fifoOutName)\n{\n\tInit();\n\topenFifos(fifoInName, fifoOutName);\n}\n\n/*\n\n Init:\n \n initializes member variables\n \n*/\nvoid FIFOCommunicator::Init()\n{\n#if FIFO_DEBUG\n\tcout << \"[FIFO debug]: in Init method\" << endl;\n#endif\n\tm_sFifoInName = \"\";\n\tm_sFifoOutName = \"\";\n\tm_nFifoInFD = -1;\n\tm_nFifoOutFD = -1;\n\tm_nErrorFlag = 0;\n}\n\n/*\n\n openFifos:\n \n opens fifoInName for reading and fifoOutName for writing. \n returns -1 on error or 0 on success\n \n*/\nint FIFOCommunicator::openFifos(string fifoInName, string fifoOutName)\n{\n#if FIFO_DEBUG\n\tcout << \"[FIFO debug]: in openFifos method\" << endl;\n#endif\n\tif (closeFifos() < 0) //close old connections\n\t\treturn m_nErrorFlag = -1;\n\tm_sFifoInName = fifoInName;\n\tm_sFifoOutName = fifoOutName;\n#if FIFO_DEBUG\n\tcout << \"[FIFO debug]: attempting to open RDONLY: \" << m_sFifoInName << endl;\n#endif\n\tif ((m_nFifoInFD = open(m_sFifoInName.c_str(), O_RDONLY)) < 0) {\n\t\tInit(); //reset member variables\n\t\treturn m_nErrorFlag = -1;\n\t}\n#if FIFO_DEBUG\n\tcout << \"[FIFO debug]: attempting to open WRONLY: \" << m_sFifoOutName << endl;\n#endif\n\tif ((m_nFifoOutFD = open(m_sFifoOutName.c_str(), O_WRONLY)) < 0) {\n\t\tclose(m_nFifoInFD); //don't open just one FIFO when other fails\n\t\tInit();\n\t\treturn m_nErrorFlag = -1;\n\t}\n\treturn m_nErrorFlag = 0;\n}\n\n/*\n\n openOppositeFifos:\n \n for use on \"flight computer\"\n opens fifoInName for writing and fifoOutName for reading. \n does this in opposite order of openFifos to prevent both blocking\n returns -1 on error or 0 on success\n \n*/\nint FIFOCommunicator::openOppositeFifos(string fifoInName, string fifoOutName)\n{\n#if FIFO_DEBUG\n\tcout << \"[FIFO debug]: in openFifos method\" << endl;\n#endif\n\tif (closeFifos() < 0) //close old connections\n\t\treturn m_nErrorFlag = -1;\n\tm_sFifoInName = fifoInName;\n\tm_sFifoOutName = fifoOutName;\n#if FIFO_DEBUG\n\tcout << \"[FIFO debug]: attempting to open WRONLY: \" << m_sFifoOutName << endl;\n#endif\n\tif ((m_nFifoOutFD = open(m_sFifoOutName.c_str(), O_WRONLY)) < 0) {\n\t\tInit(); //reset member variables\n\t\treturn m_nErrorFlag = -1;\n\t}\n#if FIFO_DEBUG\n\tcout << \"[FIFO debug]: attempting to open RDONLY: \" << m_sFifoInName << endl;\n#endif\n\tif ((m_nFifoInFD = open(m_sFifoInName.c_str(), O_RDONLY)) < 0) {\n\t\tclose(m_nFifoOutFD); //don't open just one FIFO when other fails\n\t\tInit();\n\t\treturn m_nErrorFlag = -1;\n\t}\n\treturn m_nErrorFlag = 0;\n}\n\n/*\n\n closeFifos:\n \n closes FIFOs if they have been previously opened\n \n*/\nint FIFOCommunicator::closeFifos()\n{\n#if FIFO_DEBUG\n\tcout << \"[FIFO debug]: in closeFifos method\" << endl;\n#endif\n\tif (m_nFifoInFD != -1 && close(m_nFifoInFD) < 0) {\n\t\treturn m_nErrorFlag = -1;\n\t}\n\tif (m_nFifoOutFD != -1 && close(m_nFifoOutFD) < 0) {\n\t\treturn m_nErrorFlag = -1;\n\t}\n\tInit(); //reset member variables\n\treturn m_nErrorFlag = 0;\n}\n\n/*\n\n ~FIFOCommunicator:\n \n Default destructor. Closes FIFOs\n \n*/\nFIFOCommunicator::~FIFOCommunicator()\n{\n\tcloseFifos();\n}\n\t\n/*\n\n readLoop:\n \n Infinite loop that reads and then interprets commands via interpretFunction\n Designed to run concurrently with pictureLoop and processingLoop (in starcam.cpp)\n If it returns at all then an error has occured\n The interpret function returns a string to be sent back to flight computer\n \n*/\nvoid FIFOCommunicator::readLoop(string (*interpretFunction)(string))\n{\n#if FIFO_DEBUG\n\tcout << \"[FIFO debug]: in readLoop method\" << endl;\n#endif\n\tfd_set input;\n\tchar buf[FIFO_BUF_SIZE];\n\tstring line = \"\";\n\tstring rtnStr;\n\tint n;\n\tstring::size_type pos;\n\tif (m_nFifoInFD == -1) return; //FIFO isn't open\n\t\n\twhile (1) {\n\t\tFD_ZERO(&input);\n\t\tFD_SET(m_nFifoInFD, &input);\n\t\tif (select(m_nFifoInFD+1, &input, NULL, NULL, NULL) < 0) //won't time out\n\t\t\treturn;\n\t\tif (!FD_ISSET(m_nFifoInFD, &input)) return; //should always be false\n\t\tif ((n = read(m_nFifoInFD, buf, FIFO_BUF_SIZE-1)) < 0) return;\n\t\tbuf[n] = '\\0';\n#if FIFO_DEBUG\n\tcout << \"[FIFO debug]: readloop just read \" << n << \" bytes: \" << buf << endl;\n#endif\n\t\tline += buf;\n\t\twhile ((pos = line.find(\"\\n\",0)) != string::npos) {\n\t\t\t//interpret the command and send a return value\n\t\t\tif ((rtnStr = (*interpretFunction)(line.substr(0,pos))) != \"\") //don't send blank return\n\t\t\t\tif (sendReturnString(rtnStr) < 0) return;\n\t\t\tline = line.substr(pos+1, line.length()-(pos+1)); //set line to text after \"\\n\"\n\t\t}\n\t}\n}\n\t\n/*\n\n looplessRead:\n \n similar to readLoop above but performs only read without looping\n allows user to handle looping and responses, etc.\n \n*/\nstring FIFOCommunicator::looplessRead()\n{\n\tfd_set input;\n\tchar buf[FIFO_BUF_SIZE];\n\tint n;\n\tif (m_nFifoInFD == -1) return \"\"; //FIFO isn't open\n\t\n\tFD_ZERO(&input);\n\tFD_SET(m_nFifoInFD, &input);\n\tif (select(m_nFifoInFD+1, &input, NULL, NULL, NULL) < 0) //won't time out\n\t\treturn \"\";\n\tif (!FD_ISSET(m_nFifoInFD, &input)) return \"\"; //should always be false\n\tif ((n = read(m_nFifoInFD, buf, FIFO_BUF_SIZE-1)) < 0) return \"\";\n\tbuf[n] = '\\0';\n#if FIFO_DEBUG\n\tcout << \"[FIFO debug]: read just read \" << n << \" bytes: \" << buf << endl;\n#endif\n\treturn (string)buf;\n}\n\t\n/*\n\n sendReturn:\n \n Sends data in rtn back to \"flight computer\"\n returns number of characters written or -1 on error\n \n*/\nint FIFOCommunicator::sendReturn(const StarcamReturn* rtn)\n{\n#if FIFO_DEBUG\n\tcout << \"[FIFO debug]: in sendReturn method\" << endl;\n#endif\n\tostringstream sout;\n\tsout << rtn->mapmean << \" \" << rtn->sigma << \" \" << rtn->exposuretime << \" \" \n\t\t << rtn->imagestarttime.tv_sec << \" \" << rtn->imagestarttime.tv_usec \n\t\t << \" \" << rtn->cameraID << \" \" << rtn->ccdtemperature << \" \" << rtn->numblobs << \" \";\n\t\n\tfor (int i=0; i<rtn->numblobs; i++)\n\t{\n\t\tsout << rtn->flux[i] << \" \" << rtn->mean[i] << \" \" << rtn->snr[i] << \" \" \n\t\t\t << rtn->x[i] << \" \" << rtn->y[i] << \" \";\n\t}\n\t\n\tstring output = sout.str();\n#if FIFO_DEBUG\n\tcout << \"[FIFO debug]: return value is \" << output.length() << \" chars:\\n\" << output << endl;\n#endif\n\treturn sendCommand(output);\n}\n\n/*\n\n sendReturnString:\n \n sends a string return value from a command\n value is surrounded by <str></str> tags to identify it as a string\n \n*/\nint FIFOCommunicator::sendReturnString(string returnStr)\n{\n\tstring newstr = (string)\"<str>\" + returnStr + \"</str>\";\n\treturn sendCommand(newstr);\n}\n\t\n/*\n\n interpretReturn:\n \n For use on \"flight computer\". Interprets data sent via sendReturn\n pass pointer to already declared struct to populate\n \n*/\nStarcamReturn* FIFOCommunicator::interpretReturn(string returnString, StarcamReturn* rtn)\n{\n#if FIFO_DEBUG\n\tcout << \"[FIFO debug]: in interpretReturn method\" << endl;\n#endif\n\tistringstream sin;\n\tsin.str(returnString);\n\t\n\tsin >> rtn->mapmean >> rtn->sigma >> rtn->exposuretime >> rtn->imagestarttime.tv_sec\n\t\t>> rtn->imagestarttime.tv_usec >> rtn->cameraID >> rtn->ccdtemperature >> rtn->numblobs;\n\t\n\tint top = 15;\n\tif (rtn->numblobs < 15) top = rtn->numblobs;\n\tfor (int i=0; i<top; i++)\n\t{\n\t\tsin >> rtn->flux[i] >> rtn->mean[i] >> rtn->snr[i] >> rtn->x[i] >> rtn->y[i];\n\t}\n\t\n\treturn rtn;\n}\n\n/*\n\n sendCommand:\n \n for use predominantly on \"flight computer\". sends a command string over fifo\n returns -1 on error, number of characters written otherwise\n \n*/\nint FIFOCommunicator::sendCommand(string cmd)\n{\n#if FIFO_DEBUG\n\tcout << \"[FIFO debug]: in sendCommand method with: \" << cmd << endl;\n#endif\n\tfd_set output;\n\tif (m_nFifoOutFD == -1) return -1; //FIFO isn't open\n\tif (cmd.find(\"\\n\", 0) == string::npos) cmd += \"\\n\"; //terminate command if it isn't already\n\t\n\tFD_ZERO(&output);\n\tFD_SET(m_nFifoOutFD, &output);\n\tif (select(m_nFifoOutFD+1, NULL, &output, NULL, NULL) < 0) //doesn't time out\n\t\treturn -1;\n\tif (!FD_ISSET(m_nFifoOutFD, &output)) return -1; //should always be false\n\treturn write(m_nFifoOutFD, cmd.c_str(), cmd.length());\n}\n\nint FIFOCommunicator::sendCommand(const char* cmd) //in case flight wants to use C only\n{\n\tstring str_cmd = cmd;\n\treturn sendCommand(str_cmd);\n}\n\n" }, { "alpha_fraction": 0.6062691807746887, "alphanum_fraction": 0.6281615495681763, "avg_line_length": 34.8898811340332, "blob_id": "c0fa38c98f762ff97f1f6ed08c83b9a86c3031aa", "content_id": "f1d45b8c9477a26263d12125feca43f507ccd999", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12059, "license_type": "no_license", "max_line_length": 97, "num_lines": 336, "path": "/liblinklist/linklist.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * linklist.h: \n *\n * This software is copyright \n * (C) 2015-2018 University of Toronto, Toronto, ON\n *\n * This file is part of the SuperBIT project, modified and adapted for BLAST-TNG.\n *\n * linklist 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 2 of the License, or\n * (at your option) any later version.\n *\n * linklist 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Jan 25, 2018 by Javier Romualdez\n */\n\n#ifndef LINKLIST_H_\n#define LINKLIST_H_\n\n#define NO_COMP 0xff\n#define MAX_NUM_LINKLIST_FILES 128 \n#define LINK_HASH_MULT 233\n#define MIN_CHKSM_SPACING 200 // number of bytes after which a checksum is automatically appended\n#define PACKET_HEADER_SIZE 12\n\n#define MAX_DATA_BLOCKS 20 // maximum data blocks per linklist\n#define DEF_BLOCK_ALLOC 10000 // default block buffer size [bytes] \n\n#define MAX_DATA_STREAMS 20 // maximum data streams per linklist\n#define DEF_STREAM_ALLOC 10000 // default stream buffer size [bytes]\n\n#define ALL_FRAME_SERIAL 0x42424242\n#define LL_PARSE_CHECKSUM \"_TLM_CHECKSUM_\" \n#define DEFAULT_LINKLIST_DIR \"/data/etc/linklists/\"\n#define ALL_TELEMETRY_NAME \"all_telemetry.ll\"\n#define FILE_LINKLIST \"z_file_dl.ll\"\n\n#define LINKLIST_MAX_FILENAME_SIZE 1024\n#define LINKLIST_SHORT_FILENAME_SIZE 64\n#define SUPERFRAME_EXT \".sf.bin\"\n#define SUPERFRAME_FORMAT_EXT \".sf.format\"\n#define LINKLIST_EXT \".ll.bin\"\n#define LINKLIST_FORMAT_EXT \".ll.format\"\n#define CALSPECS_FORMAT_EXT \".cs.format\"\n\n#define LINKLIST_FILE_SERIAL_IND \"# Serial=\"\n#define LINKLIST_FILE_SIZE_IND \"# Blk Size=\"\n#define LINKLIST_FRAMES_PER_FILE_IND \"# Frames per file=\"\n\n#define LL_NO_AUTO_CHECKSUM 0x01\n#define LL_INCLUDE_ALLFRAME 0x02\n#define LL_VERBOSE 0x08\n#define LL_AUTO_FLOAT_COMP 0x10\n\n#define SUPERFRAME_ENDIAN_IND \"/ENDIAN\"\n#define SUPERFRAME_ENDIAN_LITTLE \"little\"\n#define SUPERFRAME_ENDIAN_BIG \"big\"\n\n#define SF_USE_BIG_ENDIAN 0x04\n\n#define SUPERFRAME_READY 0x1\n#define COMPFRAME_READY 0x2\n\n#ifndef MIN\n#define MIN(a,b) ((a) < (b) ? (a) : (b))\n#endif\n\n#define SF_FIELD_LEN 80\n#define SF_UNITS_LEN 80\n\n#include <stdio.h>\n#include <openssl/md5.h>\n#include <inttypes.h>\n\n#ifdef __cplusplus\n\nextern \"C\"{\n\n#endif\n\nenum SFType\n{\n // these are standard types\n SF_UINT8, SF_UINT16, SF_UINT32, SF_UINT64,\n SF_INT8, SF_INT16, SF_INT32, SF_INT64,\n SF_FLOAT32, SF_FLOAT64, \n\n // these define extended items (blocks, streams, etc)\n SF_NUM, SF_INF \n};\n\nstruct linklist_struct;\nstruct link_entry;\nstruct block_container;\nstruct stream_container;\nstruct sf_entry;\nstruct superframe_struct;\n\nstruct sf_entry \n{\n char field[SF_FIELD_LEN]; // name of entry for FileFormats and CalSpecs\n uint8_t type; // Type of data stored\n uint32_t spf; // Samples per frame\n uint32_t start; // Start location of first sample in the superframe\n uint32_t skip; // Bytes to skip between samples\n double min; // min data value (for compression routines)\n double max; // max data value (for compression routines)\n char quantity[SF_UNITS_LEN]; // eg, \"Temperature\" or \"Angular Velocity\"\n char units[SF_UNITS_LEN]; // eg, \"K\" or \"^o/s\"\n void *var; // Pointer to data\n uint32_t cur; // optional current index for adding item to the telemetry frame\n struct superframe_struct * superframe; // Pointer to corresponding superframe\n};\n\nstruct superframe_struct\n{\n unsigned int n_entries;\n unsigned int size;\n uint64_t serial;\n\n struct sf_entry * entries;\n struct sf_entry ** hash_table;\n unsigned int hash_table_size;\n unsigned int allframe_size;\n\n double (*datatodouble)(uint8_t *, uint8_t);\n int (*doubletodata)(uint8_t *, double, uint8_t);\n\n int flags; // superframe-specific flags (endianess, etc)\n\n char calspecs[LINKLIST_MAX_FILENAME_SIZE];\n};\n\nstruct link_entry\n{ \n uint32_t start; // start byte for entry in compressed frame\n uint8_t comp_type; // compression type\n uint32_t blk_size; // size/allocation of entry in compressed frame\n uint32_t num; // number of samples per compressed frame\n double compvars[20]; // compression variable scratchpad\n struct sf_entry * tlm; // pointer to corresponding entry from superframe\n struct linklist_struct * linklist; // pointer to corresponding linklist\n};\n\nstruct linklist_struct\n{\n char name[LINKLIST_SHORT_FILENAME_SIZE]; // name of the linklist file\n uint32_t n_entries; // number of entries in the list\n uint32_t blk_size; // size of entire compressed frame\n uint8_t serial[MD5_DIGEST_LENGTH]; // serial/id number for list\n struct link_entry * items; // pointer to entries in the list\n int flags; // flags for checksums, auto increment, etc\n struct superframe_struct * superframe; // pointer to corresponding superframe\n\n // extended items:\n // - blocks: packetized data reassembled when data is decompressed (fixed size)\n // - e.g. file downlinks\n // - e.g. science image or full frame image downloads\n // - streams: packetized data assembled as a continuous data stream (infinite size)\n // - e.g. streaming logs to a file on the ground station\n // - e.g. image streams (ITS) for thumbnails\n struct block_container * blocks; // pointer to blocks\n unsigned int num_blocks; // number of data block fields\n struct stream_container * streams; // pointer to streams\n unsigned int num_streams; // number of data stream fields\n\n uint8_t * internal_buffer; // buffer for storing compressed data (optional)\n uint64_t internal_id; // id number for current stored compressed data (optional)\n};\n\nstruct block_container\n{\n char name[LINKLIST_SHORT_FILENAME_SIZE];\n struct link_entry * le;\n uint32_t id;\n uint32_t i, n, num;\n unsigned int flags;\n uint32_t curr_size;\n uint32_t alloc_size;\n uint8_t * buffer;\n\n char filename[LINKLIST_MAX_FILENAME_SIZE];\n FILE *fp;\n};\n\ntypedef struct\n{\n unsigned int data_size;\n unsigned int loc;\n unsigned int alloc_size;\n unsigned int flags;\n uint8_t * buffer;\n} substream_t;\n\nstruct stream_container\n{\n char name[LINKLIST_SHORT_FILENAME_SIZE];\n struct link_entry * le;\n uint8_t curr;\n uint8_t next;\n substream_t buffers[2];\n\n char filename[LINKLIST_MAX_FILENAME_SIZE];\n FILE *fp;\n};\n\ntypedef struct linklist_struct linklist_t;\ntypedef struct link_entry linkentry_t;\ntypedef struct block_container block_t;\ntypedef struct stream_container stream_t;\ntypedef struct sf_entry superframe_entry_t;\ntypedef struct superframe_struct superframe_t;\n\nextern const char * SF_TYPES_STR[]; \nextern char archive_dir[LINKLIST_MAX_FILENAME_SIZE];\n\n/**\n * These intermediate types are necessary to allow GCC to use its strict-aliasing\n * optimization without breaking our big-endian/little-endian conversion logic\n */\ntypedef uint32_t __attribute__((__may_alias__)) u32_a;\ntypedef uint64_t __attribute__((__may_alias__)) u64_a;\n\n# define beftoh(x) ({ \\\n float _tmp; \\\n u32_a *infloat = (u32_a*)&(x); \\\n u32_a *outfloat = (u32_a*)(&_tmp);\\\n *outfloat = be32toh(*infloat); \\\n _tmp; \\\n })\n# define bedtoh(x) ({ \\\n double _tmp; \\\n u64_a *infloat = (u64_a*)&(x); \\\n u64_a *outfloat = (u64_a*)(&_tmp);\\\n *outfloat = be64toh(*infloat); \\\n _tmp; \\\n })\n# define htobed(in,out) { \\\n double in_dbl = (in); \\\n u64_a *indouble = (u64_a*)&in_dbl;\\\n u64_a *outdouble = (u64_a*)&(out);\\\n *outdouble = htobe64(*indouble); \\\n }\n# define htobef(in,out) { \\\n float in_flt = (in); \\\n u32_a *infloat = (u32_a*)&in_flt; \\\n u32_a *outfloat = (u32_a*)&(out); \\\n *outfloat = htobe32(*infloat); \\\n }\n# define leftoh(x) ({ \\\n float _tmp; \\\n u32_a *infloat = (u32_a*)&(x); \\\n u32_a *outfloat = (u32_a*)(&_tmp);\\\n *outfloat = le32toh(*infloat); \\\n _tmp; \\\n })\n# define ledtoh(x) ({ \\\n double _tmp; \\\n u64_a *infloat = (u64_a*)&(x); \\\n u64_a *outfloat = (u64_a*)(&_tmp);\\\n *outfloat = le64toh(*infloat); \\\n _tmp; \\\n })\n# define ltobed(in,out) { \\\n double in_dbl = (in); \\\n u64_a *indouble = (u64_a*)&in_dbl;\\\n u64_a *outdouble = (u64_a*)&(out);\\\n *outdouble = ltobe64(*indouble); \\\n }\n# define ltobef(in,out) { \\\n float in_flt = (in); \\\n u32_a *infloat = (u32_a*)&in_flt; \\\n u32_a *outfloat = (u32_a*)&(out); \\\n *outfloat = ltobe32(*infloat); \\\n }\n\n#define STR(s) #s\n\nlinklist_t * parse_linklist_format(superframe_t *, char *);\nlinklist_t * parse_linklist_format_opt(superframe_t *, char *, int);\nvoid write_linklist_format(linklist_t *, char *);\nvoid write_linklist_format_opt(linklist_t *, char *, int);\nlinklist_t * generate_superframe_linklist(superframe_t *);\nlinklist_t * generate_superframe_linklist_opt(superframe_t *, int);\nsuperframe_t * parse_superframe_format(char *);\nsuperframe_t * parse_superframe_format_opt(char *, int);\nvoid delete_superframe(superframe_t *);\nvoid write_superframe_format(superframe_t *, const char *);\nvoid linklist_assign_datatodouble(superframe_t *, double (*func)(uint8_t *, uint8_t));\nvoid linklist_assign_doubletodata(superframe_t *, int (*func)(uint8_t *, double, uint8_t));\nuint64_t generate_superframe_serial(superframe_t *); \nsuperframe_t * linklist_build_superframe(superframe_entry_t *,\n double (*datatodouble)(uint8_t *, uint8_t), \n int (*doubletodata)(uint8_t *, double, uint8_t),\n unsigned int);\n\nsuperframe_entry_t * superframe_find_by_name(superframe_t *, const char *);\nuint32_t superframe_find_index_by_name(superframe_t *, const char *);\nuint32_t get_superframe_entry_size(superframe_entry_t *);\nconst char * get_sf_type_string(uint8_t);\nuint8_t get_sf_type_int(char *);\nint read_linklist_formatfile_comment(char *, char *, const char *);\nint superframe_entry_get_index(superframe_entry_t *, superframe_entry_t *);\n\nint linklist_generate_lookup(linklist_t **);\nlinklist_t * linklist_lookup_by_serial(uint16_t);\nlinklist_t * linklist_duplicate(linklist_t *);\nvoid delete_linklist(linklist_t *);\nint load_all_linklists(superframe_t *, char *, linklist_t **, unsigned int);\nint load_all_linklists_opt(superframe_t *, char *, linklist_t **, unsigned int, char **);\nlinklist_t * linklist_find_by_name(char *, linklist_t **);\nint linklist_find_id_by_name(char *, linklist_t **);\nblock_t * linklist_find_block_by_pointer(linklist_t *, linkentry_t *);\nstream_t * linklist_find_stream_by_pointer(linklist_t *, linkentry_t *);\n\n// linklist print overrides\nextern int (*linklist_info)(const char *, ...);\nextern int (*linklist_err)(const char *, ...);\nextern int (*linklist_warn)(const char *, ...);\nextern int (*linklist_fatal)(const char *, ...);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* LINKLIST_H_ */\n" }, { "alpha_fraction": 0.6331263184547424, "alphanum_fraction": 0.6542443037033081, "avg_line_length": 36.734375, "blob_id": "179ac49c08dc860a2954c9d74b9ed4108930313c", "content_id": "094e70770185811aaabd68b826c91c172716977e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2415, "license_type": "no_license", "max_line_length": 124, "num_lines": 64, "path": "/common/include/atomic.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/**\n * @file atomic.h\n *\n * @date Feb 14, 2011\n * @author seth\n *\n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2010-2015 Seth Hillbrand\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n\n#ifndef BLAST_ATOMIC_H_\n#define BLAST_ATOMIC_H_\n#include <stdint.h>\n#include <malloc.h>\n\n#define CACHE_LINE_SIZE 64\n\n#define BLAST_ATOMIC_MEM_BLOCK() __asm__ __volatile__ (\"mfence\" ::: \"memory\")\n#define BLAST_ATOMIC_STORE_MEM_BLOCK() __asm__ __volatile__ (\"mfence\" ::: \"memory\")\n\n#define BLAST_ATOMIC_BURY(_p) ((void *)(((uintptr_t)(_p)) | 1))\n#define BLAST_ATOMIC_UNBURY(_p) ((void *)(((uintptr_t)(_p)) & ~1))\n#define BLAST_ATOMIC_IS_BURIED(_p) (((uintptr_t)(_p)) & 1)\n\n/**\n * If our pointers are 64-bits, we need to use a 128-bit compare and swap for the double-word. Otherwise, we can\n * use standard 64-bit\n */\n#if INTPTR_MAX == INT64_MAX\n#define ALIGN_SIZE 16\n typedef int __attribute__ ((mode (TI), may_alias)) dbl_ptr;\n#else\n#define ALIGN_SIZE 8\n typedef uint64_t __attribute__ ((may_alias)) dbl_ptr;\n#endif\n\n#define CAS(_ptr, _oldval, _newval) __sync_val_compare_and_swap ((typeof(_oldval)*)(_ptr), _oldval, _newval)\n#define CAS_BOOL(_ptr, _oldval, _newval) __sync_bool_compare_and_swap ((typeof(_oldval)*)(_ptr), _oldval, _newval)\n#define CAS2(_ptr, _oldval, _newval) CAS((dbl_ptr*)(_ptr), *((dbl_ptr *)(&(_oldval))), *((dbl_ptr *)(&(_newval))))\n#define CAS2_BOOL(_ptr, _oldval, _newval) CAS_BOOL((dbl_ptr*)(_ptr), *((dbl_ptr *)(&(_oldval))), *((dbl_ptr *)(&(_newval))))\n\n#define PAD_WRAP(_x) char __pad ## _x [CACHE_LINE_SIZE]\n#define ALIGNED_MALLOC(_s) ((void *)(memalign(CACHE_LINE_SIZE*2, (_s))))\n\n#define ADD_TO(_v,_x) __sync_add_and_fetch(&(_v), (typeof(_v))(_x))\n\n#endif /* BLAST_ATOMIC_H_ */\n" }, { "alpha_fraction": 0.5525898337364197, "alphanum_fraction": 0.559659481048584, "avg_line_length": 45.51677703857422, "blob_id": "15ab33fa94e309f1075fb3b7f1466486f186b4f0", "content_id": "c247f90906b1c3ad4777f3131437356b31503eb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6931, "license_type": "no_license", "max_line_length": 177, "num_lines": 149, "path": "/common/include/lookup.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/**\n * @file lookup.h\n *\n * @date Sep 1, 2010\n * @author Seth Hillbrand\n *\n * @brief This file was part of FCP, created for the EBEX project\n *\n * @details This file defines macros that create standardized\n * and expandable lookup tables.\n *\n * This software is copyright (C) 2010 Columbia University, 2014\n * California State University, Sacramento\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n/**\n * We purposefully avoid the file-wide #ifndef BLAST_LOOKUP_H\n */\n\n#ifndef BLAST_LOOKUP_TABLE_TEXT_SIZE\n# define BLAST_LOOKUP_TABLE_TEXT_SIZE 32\n#endif\n\n/**\n * There are three basic versions:\n * 1) Standard - This is just an enum and descriptive string. For many applications, this\n * is sufficient. You will get an array of enumerations, each of which define\n * the array index to the corresponding string.\n * 2) Function - This extends the Standard version to include a call-back function whose\n * definition is required. The call-back function can handle processing specific\n * actions that should be associated with each enumeration. This would be useful\n * in command processing, for example.\n * 3) Bitfield - This extends the Standard version to include a longer description field and\n * an bitfield integer (user-defined). You should choose an integer representation\n * sufficiently long to represent all possible values. Thus, if you have 16 or\n * more entries, you should choose uint32_t. 32 or more entries: uint64_t.\n *\n */\n\n#ifndef _BLAST_ENUM_TYPEDEF\n#define _BLAST_ENUM_TYPEDEF(_prefix) \\\n typedef enum _prefix \\\n { \\\n _ ## _prefix ## S(_prefix,_BLAST_ENUM_LIST) \\\n _BLAST_ENUM_LIST(_prefix,END) \\\n } E_ ## _prefix\n#endif\n\n#ifndef _BLAST_LOOKUP_TABLE_DECLARATION\n#define _BLAST_LOOKUP_TABLE_DECLARATION(_prefix, _struct_list, _type) \\\n _type _prefix ##_LOOKUP_T __attribute__((unused)) \\\n _prefix ##_LOOKUP_TABLE[_prefix ## _END + 1] = \\\n {_ ## _prefix ## S(_prefix,_struct_list) \\\n _BLAST_BASE_STRUCT_LIST(_prefix,END) \\\n }\n#endif\n\n#ifndef _BLAST_LOOKUP_TABLE_TYPEDEF\n#define _BLAST_LOOKUP_TABLE_TYPEDEF(_prefix, _extras) \\\n typedef struct _prefix ## _LOOKUP \\\n { \\\n const char text[BLAST_LOOKUP_TABLE_TEXT_SIZE]; \\\n E_ ## _prefix position; \\\n _extras \\\n } _prefix ##_LOOKUP_T\n#endif\n\n#ifndef BLAST_GENERIC_LOOKUP_TABLE\n#define BLAST_GENERIC_LOOKUP_TABLE(_prefix, _type, _tabledef, _listdef, ...) \\\n _BLAST_ENUM_TYPEDEF(_prefix); \\\n _BLAST_LOOKUP_TABLE_TYPEDEF(_prefix,_tabledef); \\\n __VA_ARGS__ \\\n _BLAST_LOOKUP_TABLE_DECLARATION(_prefix,_listdef, _type)\n#endif\n\n#ifndef BLAST_FUNCTION_LOOKUP_TABLE\n#define BLAST_FUNCTION_LOOKUP_TABLE(_prefix, _type) \\\n _ ## _prefix ## S(_prefix, _BLAST_FUNCTION_DEF ) \\\n BLAST_GENERIC_LOOKUP_TABLE( _prefix, \\\n _type, \\\n void* (*function) (void*);, \\\n _BLAST_FUNCTION_STRUCT_LIST, )\n#endif\n\n#ifndef BLAST_HASH_LOOKUP_TABLE\n#define BLAST_HASH_LOOKUP_TABLE(_prefix, _type) BLAST_GENERIC_LOOKUP_TABLE(_prefix, _type, hash_t hash;, _BLAST_HASH_STRUCT_LIST, )\n#endif\n\n#ifndef BLAST_BITFIELD_LOOKUP_TABLE\n#define BLAST_BITFIELD_LOOKUP_TABLE(_prefix, _fieldtype, _type) BLAST_GENERIC_LOOKUP_TABLE(_prefix, _type, char desc[128];_fieldtype bitfield;, _BLAST_BITFIELD_STRUCT_LIST, )\n#endif\n\n/**\n * @param _prefix is a unique identifier for the table and enumeration names. You should have a\n * #define already created with the _prefix name but pre-pended by an underscore '_' and\n * suffixed with an 'S'.\n * @param _type is an optional specifier that is valid for a struct. Examples might be 'const' or\n * 'static' or some combination. This will be prepended to the lookup table declaration\n *\n */\n#ifndef BLAST_LOOKUP_TABLE\n#define BLAST_LOOKUP_TABLE(_prefix, _type,...) \\\n _BLAST_ENUM_TYPEDEF(_prefix); \\\n _BLAST_LOOKUP_TABLE_TYPEDEF(_prefix, ); \\\n _BLAST_LOOKUP_TABLE_DECLARATION(_prefix,_BLAST_BASE_STRUCT_LIST, _type)\n#endif\n\n#ifndef _BLAST_FUNCTION_DEF\n# define _BLAST_FUNCTION_DEF(_prefix,_ref) void *_prefix ## _ ## _ref ## _CALLBACK(void *);\n#endif\n\n#ifndef _BLAST_ENUM_LIST\n# define _BLAST_ENUM_LIST(_prefix,_ref,...) _prefix ## _ ## _ref,\n#endif\n\n#ifndef _BLAST_BASE_STRUCT_ENTRY\n# define _BLAST_BASE_STRUCT_ENTRY(_prefix,_ref) .text= #_ref \"\\0\", .position= _BLAST_ENUM_LIST(_prefix, _ref)\n#endif\n\n#ifndef _BLAST_BASE_STRUCT_LIST\n# define _BLAST_BASE_STRUCT_LIST(_prefix,_ref,...) {_BLAST_BASE_STRUCT_ENTRY(_prefix,_ref)},\n#endif\n\n#ifndef _BLAST_FUNCTION_STRUCT_LIST\n# define _BLAST_FUNCTION_STRUCT_LIST(_prefix,_ref,...) {_BLAST_BASE_STRUCT_ENTRY(_prefix,_ref) _prefix ## _ ## _ref ## _CALLBACK},\n#endif\n\n#ifndef _BLAST_HASH_STRUCT_LIST\n# define _BLAST_HASH_STRUCT_LIST(_prefix,_ref,...) {_BLAST_BASE_STRUCT_ENTRY(_prefix,_ref) .hash = 0},\n#endif\n\n#ifndef _BLAST_BITFIELD_STRUCT_LIST\n# define _BLAST_BITFIELD_STRUCT_LIST(_prefix,_ref,_desc,...) {_BLAST_BASE_STRUCT_ENTRY(_prefix,_ref) .desc= #_desc \"\\0\", .bitfield= 1<<_BLAST_ENUM_LIST(_prefix, _ref)},\n#endif\n" }, { "alpha_fraction": 0.6240375638008118, "alphanum_fraction": 0.6330459117889404, "avg_line_length": 32.04325866699219, "blob_id": "0daa2a7eaddfceee8cebec5ff8258a653b102959", "content_id": "eba15fd9c4fcea33f1815ce7c6485f965e26cae8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12988, "license_type": "no_license", "max_line_length": 125, "num_lines": 393, "path": "/starcam/clensadapter.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include \"clensadapter.h\"\n#include <sys/select.h>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <cmath>\n#include <stdio.h> /* standard input and output */\n#include <unistd.h> /* UNIX standard function definitions */\n#include <fcntl.h> /* File control definitions */\n#include <termios.h> /* POSIX terminal control definitions */\n#include <stdlib.h>\n#include <sys/ioctl.h>\n\n#define LENS_DEBUG 0\n#define OLD_LENS 1\n\n\nusing namespace std;\n\nconst string command_string[] = {\"\",\"id\",\"hv\",\"br\",\"bs\",\"rm\",\"xm\",\"sn\",\"vn\",\"vs\",\"lv\",\n\t\"mi\",\"mz\",\"fa\",\"mf\",\"pf\",\"fd\",\"sf\",\"dz\",\"in\",\"da\",\"mo\",\"mc\",\"ma\",\"mn\",\"pa\",\"is\",\"df\"\n}; //two character command strings corresponing to the LENS_COMMAND enum\n\n//indicates if a command needs a value parameter (1) or not (0); corresponds to LENS_COMMAND enum\nconst short needs_param[] = {0,0,0,1,0,1,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,1,1,0,0,0};\n\nconst string error_str[] = {\"No error\", \"Could not parse command\", \"Lens set to manual focus\",\n\t\"No lens present\", \"Distance information not available\", \"Lens not initialized\",\n\t\"Invalid baud rate\", \"No shutter present\", \"Insufficient power\", \"Invalid library\",\n\t\"Lens communication error\", \"Bad Parameter\", \"Connection error\", \"Connection Timeout\",\n\t\"Non-lens error in autofocus\"\n}; //string descriptions corresponding to LENS_ERROR enum\n\n/*\n\tCLensAdapter:\n\t\tdefault constructor. Doesn't establish a connection\n*/\nCLensAdapter::CLensAdapter()\n{\n\tInit();\n}\n\n/*\n\tCLensAdapter:\n\t\tconstructor that explicitly specifies the device name\n\t\tbe sure to check afterwards for an error in establishing a connection\n*/\nCLensAdapter::CLensAdapter(string deviceName)\n{\n\tInit();\n\topenConnection(deviceName);\n}\n\n/*\n\t~CLensAdapter:\n\t\tdefault destructor. closes the connection\n*/\nCLensAdapter::~CLensAdapter()\n{\n\tcloseConnection();\n}\n\n/*\n\tInit:\n\t\tsets default values of class members\n*/\nvoid CLensAdapter::Init(LensAdapterConfigParams params/*=defaultCameraParams.lensParams*/)\n{\n#if LENS_DEBUG\n\tcout << \"[Lens Debug]: Inside the Init method\" << endl;\n#endif\n\tm_eLastCommand = params.lastCommand;\n\tm_eLastError = params.lastError;\n\tm_nPortFD = params.portFD;\n\tm_sSerialDeviceName = params.deviceName;\n\tm_nFocalRange = params.focalRange;\n\tm_nFocusTol = params.focusTol;\n}\n/* original method has been replaced\nvoid CLensAdapter::Init()\n{\n\tm_eLastCommand = LC_NULL;\n\tm_eLastError = LE_NO_ERROR;\n\tm_nPortFD = -1;\n\tm_sSerialDeviceName = \"\";\n}\n*/\n\n/*\n\topenConnection:\n\t\topens a connection to file named deviceName in /dev/\n*/\nLENS_ERROR CLensAdapter::openConnection(string deviceName)\n{\n#if LENS_DEBUG\n\tcout << \"[Lens Debug]: Inside the openConnection method\" << endl;\n#endif\n\tm_sSerialDeviceName = deviceName;\n\tm_nPortFD = open(deviceName.c_str(), O_RDWR | O_NOCTTY | O_NDELAY);\n\tif (m_nPortFD == -1) { //open failed\n\t\tm_sSerialDeviceName = \"\";\n\t\treturn (m_eLastError = LE_CONNECTION_ERROR);\n\t}\n\t\n\t//set baud rate, character size, and parity\n\tstruct termios options;\n\ttcgetattr(m_nPortFD, &options);\n\tcfsetispeed(&options, B19200); //input speed\n\tcfsetospeed(&options, B19200); //outpur speed\n\t/* Original options...didn't work right\n\toptions.c_cflag |= (CLOCAL | CREAD); //set local mode and enable receive\n\toptions.c_cflag &= ~PARENB; //no parity\n\toptions.c_cflag &= ~CSTOPB; //1 stop bit \n\toptions.c_cflag &= ~CSIZE; //mask character size\n\toptions.c_cflag |= CS8; //8-bit characters\n\toptions.c_cflag &= ~CRTSCTS; //disable hardware flow control\n\toptions.c_lflag |= ICANON; //enable canonical (line-based) mode\n\toptions.c_iflag &= ~(IXON | IXOFF | IXANY); //disable software flow control\n\toptions.c_iflag |= INLCR;*/\n\t\n\toptions.c_iflag = 0;\n\toptions.c_iflag = ICRNL; //map '\\r' to '\\n' on input\n\toptions.c_oflag = 0;\n\toptions.c_cflag &= ~(CSTOPB | CSIZE);\n\toptions.c_cflag |= CS8;\n\toptions.c_lflag = 0;\n\toptions.c_lflag |= ICANON; //enable canonical (line-based) mode\n\n\n\ttcsetattr(m_nPortFD, TCSANOW, &options); //apply changes\n\n\t//flush the buffer (in case of unclean shutdown)\n\tif (tcflush(m_nPortFD, TCIOFLUSH) < 0) {\n#if LENS_DEBUG\n\t\tcout << \"[Lens Debug]: failed to flush buffer\" << endl;\n#endif\n\t}\n\t\n\treturn (m_eLastError = LE_NO_ERROR);\n}\n\n/*\n\tcloseConnection:\n\t\tcloses the current connection\n*/\nLENS_ERROR CLensAdapter::closeConnection()\n{\n#if LENS_DEBUG\n\tcout << \"[Lens Debug]: Inside the closeConnection method\" << endl;\n#endif\n\tif (close(m_nPortFD) < 0)\n\t\treturn (m_eLastError = LE_CONNECTION_ERROR);\n\tm_nPortFD = -1;\n\tm_sSerialDeviceName = \"\";\t\n\treturn (m_eLastError = LE_NO_ERROR);\n}\n\n/*\n\n getErrorString:\n \n returns a string description of the error err\n \n*/\nstring CLensAdapter::getErrorString(LENS_ERROR err)\n{\n\treturn error_str[(int) err];\n}\n\n/*\n\n findFocalRange:\n \n sets focus to zero and then infinity to find the range of motor counts while focussing\n sets the member m_nFocalRange when this is found\n \n*/\nLENS_ERROR CLensAdapter::findFocalRange()\n{\n\tLENS_ERROR err = LE_NO_ERROR;\n\tstring lens_return_str, range_str;\n\tunsigned int end_pos;\n\tif (m_nPortFD == -1) //check if there is an open connection\n\t\treturn (m_eLastError = LE_CONNECTION_ERROR);\n\t\n\tif ((err = this->runCommand(LC_MOVE_FOCUS_ZERO,lens_return_str)) != LE_NO_ERROR) \n\t\treturn err;\n\tcout << \"erase me: mz gave: \" << lens_return_str << endl;\n\tif ((err = this->runCommand(LC_MOVE_FOCUS_INFINITY,lens_return_str)) != LE_NO_ERROR) \n\t\treturn err;\n\tcout << \"erase me: mi gave: \" << lens_return_str << endl;\n\t\n\t//if no error occured, lens_return_str should be \"OK\\nDONExxx,1\\n\" where xxx == focal range\n\tend_pos = lens_return_str.find(\",\",0);\n\tif (end_pos == string::npos) return (m_eLastError = LE_BAD_PARAM);\n\trange_str = lens_return_str.substr(4, end_pos-4);\n\tm_nFocalRange = atoi(range_str.c_str());\n\t\n\treturn LE_NO_ERROR;\n}\n\n/*\n\trunCommand:\n\t\tsends the string cmd and records response in return_value\n\t\tshould only ever be called by other forms of the runCommand function\n\t\t\n*/\nLENS_ERROR CLensAdapter::runCommand(string cmd, string &return_value)\n{\n#if LENS_DEBUG\n\tcout << \"[Lens Debug]: Inside the major runCommand method\" << endl;\n#endif\n\tint n=1;\n\tunsigned int end_pos;\n\tstring err_code_str;\n\tchar buf[255]; //input buffer\n\tstring first, second;\n\tfd_set input, output;\n\tstruct timeval timeout;\n\tstring cmdNoR = cmd;\n\tif (cmd.find(\"\\r\") == string::npos) cmd += \"\\r\"; //insert carriage return as needed\n\t\n#if LENS_DEBUG\n\tcout << \"[Lens Debug]: performing write of command: \" << cmd << endl;\n#endif\n\ttimeout.tv_sec = 10;\n\ttimeout.tv_usec = 0;\n\tFD_ZERO(&output);\n#if LENS_DEBUG\n\tcout << \"[Lens Debug]: adding fd=\" << m_nPortFD << \" to output set... \" << endl;\n#endif\n\tFD_SET(m_nPortFD, &output);\n\tn = select(m_nPortFD+1, NULL, &output, NULL, &timeout);\n\tif (n < 0) return (m_eLastError = LE_COMMUNICATION_ERROR);\n\tif (n == 0) return (m_eLastError = LE_TIMEOUT);\n\tif (FD_ISSET(m_nPortFD, &output)) {\n#if LENS_DEBUG\n\t\tcout << \"[Lens Debug]: calling write method... \" << endl;\n#endif\n\t\tn = write(m_nPortFD, cmd.c_str(), cmd.length()); //if no error or timeout, then able to write\n\t\tif (n < 0) return (m_eLastError = LE_COMMUNICATION_ERROR);\n\t}\n\telse return (m_eLastError = LE_COMMUNICATION_ERROR);\n#if LENS_DEBUG\n\tcout << \"[Lens Debug]: performing read of return value... \" << endl;\n#endif\n\ttimeout.tv_sec = 10;\n\ttimeout.tv_usec = 0;\n\tFD_ZERO(&input);\n\tFD_SET(m_nPortFD, &input);\n\tn = select(m_nPortFD+1, &input, NULL, NULL, &timeout);\n\tif (n < 0) return (m_eLastError = LE_COMMUNICATION_ERROR);\n\tif (n == 0) return (m_eLastError = LE_TIMEOUT);\n\tif (FD_ISSET(m_nPortFD, &input)) {\n#if LENS_DEBUG\n\t\tcout << \"[Lens Debug]: calling read... \" << endl;\n#endif\n\t\tn = read(m_nPortFD, buf, 254);\n\t\tif (n < 0) return (m_eLastError = LE_COMMUNICATION_ERROR);\n\t\tbuf[n] = '\\0';\n\t\tfirst = buf;\n#if LENS_DEBUG\n\t\tcout << \"[Lens Debug]: read line of output: \" << first << endl;\n#endif\n\t}\n\treturn_value = first;\n\t\n\t//check return value for an error code\n\tif (first.find(\"ERR\", 0) == 0) { //an error occured in processing the command\n\t\tend_pos = first.find(\"\\n\",0);\n\t\tif (end_pos == string::npos) return (m_eLastError = LE_COMMUNICATION_ERROR);\n\t\terr_code_str = first.substr(3,end_pos-3);\n\t\treturn (m_eLastError = (LENS_ERROR)atoi(err_code_str.c_str()));\n\t}\n#if OLD_LENS\n if ((first.find(cmdNoR))!=(string::npos)) {\n for (int i=0; i<2; i++) { //repeat to first read command echo and then \"OK\"\n#if LENS_DEBUG\n cout << \"[Lens Debug]: performing more read (OK, then return value... \" << endl;\n#endif\n timeout.tv_sec = 10;\n timeout.tv_usec = 0;\n FD_ZERO(&input);\n FD_SET(m_nPortFD, &input);\n n = select(m_nPortFD+1, &input, NULL, NULL, &timeout);\n if (n < 0) return (m_eLastError = LE_COMMUNICATION_ERROR);\n if (n == 0) return (m_eLastError = LE_TIMEOUT);\n if (FD_ISSET(m_nPortFD, &input)) {\n#if LENS_DEBUG\n cout << \"[Lens Debug]: calling read... \" << endl;\n#endif\n n = read(m_nPortFD, buf, 254); //in canonical mode, should read until \\r\n if (n < 0) return (m_eLastError = LE_COMMUNICATION_ERROR);\n buf[n] = '\\0'; //turn buffer into a C-style string\n second = buf; //first line of result (should read \"OK\")\n#if LENS_DEBUG\n cout << \"[Lens Debug]: read line of output: \" << second << endl;\n#endif\n }\n }\n return_value = second;\n }\n#endif\t\n\treturn (m_eLastError = LE_NO_ERROR);\n}\n\n/*\n\trunCommand:\n\t\truns the command cmd as long as it needs no parameter\n\t\treturn_value is set to the string returned from the adapter\n*/\nLENS_ERROR CLensAdapter::runCommand(LENS_COMMAND cmd, string &return_value)\n{\n#if LENS_DEBUG\n\tcout << \"[Lens Debug]: Inside the minor runCommand method (no parameter)\" << endl;\n#endif\n\tif (needs_param[(int)cmd]) return (m_eLastError = LE_BAD_PARAM);\n\tm_eLastCommand = cmd;\n\tstring str_cmd = command_string[(int)cmd];\n\treturn runCommand(str_cmd, return_value);\n}\n\n/*\n\trunCommand:\n\t\truns the command cmd that requires a paramter value (val)\n\t\treturn_value is set to the string returned from the adapter\n*/\nLENS_ERROR CLensAdapter::runCommand(LENS_COMMAND cmd, int val, string &return_value)\n{\n#if LENS_DEBUG\n\tcout << \"[Lens Debug]: Inside the minor runCommand method (with paramter)\" << endl;\n#endif\n\tostringstream sout;\n\tif (!needs_param[(int)cmd]) return (m_eLastError = LE_BAD_PARAM);\n\tm_eLastCommand = cmd;\n\tsout << command_string[(int)cmd] << val;\n\treturn runCommand(sout.str(), return_value);\n}\n\n/*\n\n preciseMove:\n \n moves the focus incrementally by a precise number of counts\n will perfrm multiple moves when a move misses slightly\n will allow a miss tolerance of tol\n if the lens reaches a stop, indicates unmoved counts in remaining\n when forced is nonzero (TRUE) will ignore stops until not moving\n*/\nLENS_ERROR CLensAdapter::preciseMove(int counts, int &remaining, int forced/*=0*/)\n{\n\tstring return_str, counts_str, stop_str; //values returned by move function\n\tunsigned int sep_pos; //position of separator \",\" in return_str\n\tLENS_ERROR err;\n\tremaining = counts;\n\tint moved_by; //the amount moved in each iteration\n\tint stop_flag = 0; //set when a stop is hit\n\tint no_move_cnt = 0; //counts number of times didn't move\n\t\n\twhile (abs(remaining) > (int)m_nFocusTol) {\n\t\t//move by amount remaining\n\t\tif ((err = runCommand(LC_MOVE_FOCUS_INC,remaining,return_str)) != LE_NO_ERROR)\n\t\t\treturn err;\n\t\tsep_pos = return_str.find(\",\",0);\n\t\tif (sep_pos == string::npos) return (m_eLastError = LE_BAD_PARAM);\n\t\tcounts_str = return_str.substr(4,sep_pos-4);\n\t\tstop_str = return_str.substr(sep_pos+1,1);\n#if LENS_DEBUG\n\t\tcout << \"[Lens Debug]: preciseMove moved by \" << counts_str << \" counts\";\n\t\tcout << \" and \" << ((stop_str == \"1\")?\"\":\"did not \") << \"hit a stop.\" << endl;\n#endif\n\t\tmoved_by = atoi(counts_str.c_str());\n\t\tremaining -= moved_by;\n\t\tif (stop_str == \"1\") { //a stop is hit (\"0\" otherwise)\n\t\t\tif (forced) {\n\t\t\t\t//forced case, return when stop hit and move by 0 four times in a row \n\t\t\t\tif (moved_by == 0) no_move_cnt++;\n\t\t\t\telse no_move_cnt = 0;\n\t\t\t\tif (no_move_cnt > 4) return LE_NO_ERROR;\n\t\t\t} else {\n\t\t\t\t//unforced case, return when a stop hit twice (avoids spurious stops)\n\t\t\t\tif (stop_flag)\n\t\t\t\t\treturn LE_NO_ERROR; //if a stop is hit twice in a row, return\n\t\t\t\telse stop_flag = 1;\n\t\t\t}\n\t\t} else { //if a stop wasn't hit, reset both the forced and unforced indicators\n\t\t\tstop_flag = 0;\n\t\t\tno_move_cnt = 0;\n\t\t}\n\t}\n\t\n\treturn LE_NO_ERROR;\n}\n\n\n" }, { "alpha_fraction": 0.6277555227279663, "alphanum_fraction": 0.6440380811691284, "avg_line_length": 29.473281860351562, "blob_id": "bfc04fd34b57e3bcca8a3bcacae60db38af877b9", "content_id": "767dbfd3833eff77fb4c58bf494154b63715dbf6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3992, "license_type": "no_license", "max_line_length": 80, "num_lines": 131, "path": "/interloquendi/rendezvous.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* interloquendi: copies a mcp frame file to a TCP port\n *\n * This software is copyright (C) 2004 University of Toronto\n * \n * This file is part of interloquendi.\n * \n * interloquendi 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 2 of the License, or\n * (at your option) any later version.\n * \n * interloquendi 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 interloquendi; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <arpa/inet.h>\n#include <netdb.h>\n#include <string.h>\n#include <stdio.h>\n#include <unistd.h>\n\n#include \"quendiclient.h\"\n#include \"quenya.h\"\n#include \"blast.h\"\n\n/* In interloquendi.c */\nint MakeListener(int);\n\nint InitRendezvous(const char* host, int port, const char* masq_in)\n{\n char buffer[2000];\n struct sockaddr_in addr;\n const char* herr;\n int n, sock, rsock;\n char *ptr1 = NULL, *ptr2;\n char masq[2000];\n struct hostent* thishost;\n socklen_t addrlen = sizeof(addr);\n\n /* No rendezvous host means no rendezvousing */\n if (host[0] == '\\0')\n return 0;\n\n sock = MakeSock();\n\n if ((herr = ResolveHost(host, &addr, 0)) != NULL) \n bprintf(fatal, \"Unable to resolve upstream rendezvous server: %s\", herr);\n\n bprintf(info, \"Rendezvousing with %s:%i...\\n\", inet_ntoa(addr.sin_addr),\n ntohs(addr.sin_port));\n\n if ((n = connect(sock, (struct sockaddr*)&addr, sizeof(addr))) != 0)\n berror(fatal, \"Rendezvous failed\");\n\n if (masq_in[0] == '\\0') {\n getsockname(sock, (struct sockaddr*)&addr, &addrlen);\n thishost = gethostbyaddr((const char*)&addr.sin_addr, sizeof(addr.sin_addr),\n AF_INET);\n if (thishost == NULL && h_errno) {\n bprintf(warning, \"gethostbyaddr: %s\", hstrerror(h_errno));\n thishost = NULL;\n }\n strcpy(masq, thishost ? thishost->h_name : inet_ntoa(addr.sin_addr));\n }\n\n n = 0;\n for (ptr2 = masq; *ptr2 != '\\0'; ++ptr2)\n if (*ptr2 == ':') {\n n = 1;\n break;\n }\n\n if (!n)\n sprintf(ptr2, \":%i\", port);\n\n switch(n = GetServerResponse(sock, buffer)) {\n case -3:\n bprintf(fatal, \"Unexpected disconnect by upstream server.\\n\");\n case QUENYA_RESPONSE_SERVICE_READY:\n for (ptr1 = buffer; *ptr1 != ' '; ++ptr1);\n *(ptr1++) = 0;\n for (ptr2 = ptr1; *ptr2 != '/'; ++ptr2);\n *(ptr2++) = 0;\n *(strchr(ptr2, ' ')) = 0;\n\n bprintf(info, \"Connected to %s on %s speaking quenya version %s.\\n\",\n ptr1, buffer, ptr2);\n break;\n default:\n bprintf(fatal, \"Unexpected response from server on connect: %i\\n\", n);\n }\n\n strcpy(buffer, \"IDEN interloquendi\\r\\n\");\n if (write(sock, buffer, strlen(buffer)) < 0)\n berror(err, \"Failed to write to socket\");\n switch (n = GetServerResponse(sock, buffer)) {\n case -3:\n bprintf(fatal, \"Unexpected disconnect by upstream server.\\n\");\n case QUENYA_RESPONSE_ACCESS_GRANTED:\n break;\n default:\n bprintf(fatal, \"Unexpected response from server after IDEN: %i\\n\", n);\n }\n\n /* Open Rendezvous Port */\n rsock = MakeListener(port);\n\n /* Negotiate Rendezvous */\n sprintf(buffer, \"RDVS %s\\r\\n\", masq);\n if (write(sock, buffer, strlen(buffer)) < 0)\n berror(err, \"Failed to write to socket\");\n switch (n = GetServerResponse(sock, buffer)) {\n case -3:\n bprintf(fatal, \"Unexpected disconnect by upstream server.\\n\");\n case QUENYA_RESPONSE_OPEN_ERROR:\n bprintf(fatal, \"Unable to establish rendezvous with upstream server.\\n\");\n case QUENYA_RESPONSE_PORT_OPENED:\n break;\n default:\n bprintf(fatal, \"Unexpected response from server after RDVS: %i\\n\", n);\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.4975285828113556, "alphanum_fraction": 0.5182883739471436, "avg_line_length": 30.193832397460938, "blob_id": "9d2af77d4b9f15ad39ce30011bf4677fe8044b30", "content_id": "0e2fc6b0f2a74a55ed126b2d8ce94fb9edccfbd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7081, "license_type": "no_license", "max_line_length": 91, "num_lines": 227, "path": "/starcam/camconfig.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* camconfig.h\n defines structures of data used to configure starcam operation\n defines global variables to contain data, and constants with default values\n*/\n\n#ifndef CAMCONFIG_H\n#define CAMCONFIG_H\n\n#include <string>\n#include \"clensadapterdefs.h\"\n#include \"sbigudrv.h\"\n#include \"csbigimgdefs.h\"\n#include \"camstruct.h\"\n\nusing namespace std;\n\n#ifndef INVALID_HANDLE_VALUE //used by CSBIGCam\n#define INVALID_HANDLE_VALUE -1\n#endif\n//constant used for MyCam\n#define INVALID_USB_NUM -1\n\ntypedef unsigned short int MAPTYPE; //used in frameblob\n\nstruct LensAdapterConfigParams {\n\tLENS_COMMAND lastCommand;\n\tLENS_ERROR lastError;\n\tint portFD;\n\tstring deviceName;\n\tint focalRange;\n\tunsigned int focusTol;\n};\n\nstruct SBIGCamConfigParams {\n\tPAR_ERROR lastError;\n\tPAR_COMMAND lastCommand;\n\tshort drvHandle;\n\tCAMERA_TYPE cameraType;\n\tCCD_REQUEST activeCCD;\n\tdouble exposureTime;\n\tunsigned short readoutMode;\n\tABG_STATE7 ABGState;\n\tint subframeLeft, subframeTop, subframeWidth, subframeHeight;\n};\n\nstruct FrameBlobConfigParams {\n\tMAPTYPE* map;\n\tunsigned int bits;\n\tunsigned int xpix;\n\tunsigned int ypix;\n\tdouble platescale;\n\tdouble gain;\n\tdouble readoutOffset;\n\tdouble readoutNoise;\n\tdouble mapmean;\n\tdouble sigma;\n\tMAPTYPE satval;\n\tunsigned int grid;\n\tdouble threshold;\n\tint disttol;\n\tunsigned int maxblobs;\n\tdouble stddev;\n};\n\nstruct SBIGImgConfigParams {\n\tint height, width;\n\tunsigned short* pImg;\n\tdouble CCDTemperature;\n\tdouble exposureTime;\n\tdouble eachExposure;\n\tdouble trackExposure;\n\tdouble focalLength;\n\tdouble apertureArea;\n\tdouble responseFactor;\n\tdouble pixelHeight, pixelWidth;\n\tdouble eGain;\n\tunsigned short background;\n\tunsigned short range;\n\tunsigned short numberExposures;\n\tunsigned short saturationLevel;\n\tunsigned short pedestal;\n\tunsigned short exposureState;\n\tunsigned short readoutMode;\n\tstring note;\n\tstring observer;\n\tstring history;\n\tstring filter;\n\tstring software;\n\tstring cameraModel;\n\tSBIG_IMAGE_FORMAT defaultImageFormat;\n\tint subframeTop, subframeLeft;\n\tunsigned short horizontalBinning, verticalBinning;\n// #if INCLUDE_FITSIO\n// \tstring FITSObject;\n// \tstring FITSTelescope;\n// \tdouble apertureDiameter;\n// #endif\n};\n\nstruct PyramidConfigParams {\n double fov;\n char *catalogname;\n char *katalogname;\n} ;\n\nstruct ViewerConfigParams {\n\tint refreshTime;\n\tint width, height;\n};\n\nstruct MyCamConfigParams {\n\tLensAdapterConfigParams lensParams;\n\tSBIGCamConfigParams SBIGParams;\n\tint USBNum;\n\tint pictureInterval;\n\tunsigned int focusResolution;\n\tunsigned int focusRange;\n};\n\nstruct BlobImageConfigParams {\n\tFrameBlobConfigParams blobParams;\n\tSBIGImgConfigParams SBIGParams;\n PyramidConfigParams pyrParams;\n\tViewerConfigParams viewerParams;\n\tstring badpixFilename;\n\tunsigned long timeError;\n\tdouble matchTol;\n\tdouble platescale;\n};\n\n//create global constants of default values. These are a centralized source of all defaults\nstatic const MyCamConfigParams defaultCameraParams = {\n\t{ //lens params:\n\t\tLC_NULL, //lastCommand\n\t\tLE_NO_ERROR, //lastError\n\t\t-1, //portFD\n\t\t\"\", //deviceName\n\t\t-1, //focalRange\n\t\t1 //focusTol\n\t},\n\t{ //SBIG camera params:\n\t\tCE_NO_ERROR, //lastError\n\t\tCC_NULL, //lastCommand\n\t\tINVALID_HANDLE_VALUE, //drvHandle\n\t\tNO_CAMERA, //cameraType\n\t\tCCD_IMAGING, //activeCCD\n\t\t1, //exposureTime\n\t\t0, //readoutMode\n\t\tABG_CLK_MED7, //ABGState\n\t\t0, 0, 0, 0 //subframe left, top, width, height\n//\t\t100, 100, 100, 100 //subframe left, top, width, height\n\t},\n\tINVALID_USB_NUM, //USBNum\n\t0, //pictureInterval\n\t100 //focusResolution\n};\n\nstatic const BlobImageConfigParams defaultImageParams = {\n\t{ //frame blob params:\n\t\tNULL, //map\n\t\t16, //bits\n\t\tCAM_WIDTH, //xpix\n\t\tCAM_HEIGHT, //ypix\n\t\t6.19/60.0/60.0, //platescale\n\t\t1, //gain\n\t\t0, //readoutOffset\n\t\t0, //readoutNoise\n\t\t0, //mapmean\n\t\t1, //sigma\n\t\t65535, //satval\n\t\t20, //grid\n\t\t5.0, //threshold\n\t\t20*20, //disttol\n\t\t99, //maxblobs\n\t\t0 //stddev\n\t},\n\t{ //SBIG image params:\n\t\t0, 0, //height, width\n\t\tNULL, //pImg\n\t\t25, //CCDTemperature\n\t\t0.1, //exposureTime\n\t\t0.1, //eachExposure\n\t\t0, //trackExposure\n\t\t7.87, //focalLength\n\t\t24.84, //apertureArea\n\t\t2000.0, //responseFactor\n\t\t0.009, 0.009, //pixelHeight, pixelWidth\n\t\t1.48, //eGain\n\t\t0, //background\n\t\t65535, //range\n\t\t1, //numberExposures\n\t\t65535, //saturationLevel\n\t\t0, //pedestal\n\t\tES_ABG_LOW | ES_ABG_RATE_FIXED | ES_DCS_ENABLED | ES_DCR_DISABLED |\\\n\t\t\t\tES_AUTOBIAS_ENABLED, //exposureState\n\t\t0, //readoutMode\n\t\t\"\", //note\n\t\t\"THE GOOD\", \t//observer\n\t\t\"0\", //history\n\t\t\"None\", //filter\n\t\t\"Starcam control\", //software\n\t\t\"ST-402\", //cameraModel\n\t\tSBIF_COMPRESSED, //defaultImageFormat\n\t\t0, 0, //subframeTop, subframeLeft\n\t\t1, 1 //horizontalBinning, verticalBinning\n// #if INCLUDE_FITSIO\n// \t\t,\"\", //FITSObject\n// \t\t\"\", //FITSTelescope\n// \t\t2.81 //apertureDiameter\n// #endif\n\t},\n { //pyramid params\n 0.035, //fov\n\t\t(char*)\"/home/spider/pyramid/pyr_mag8/gsc_mag08_res20.bin\", //catalogname\n\t\t(char*)\"/home/spider/pyramid/pyr_mag8/k.bin\" //katalogname\n },\n\t{ //viewer params\n\t\t10, //refreshTime\n\t\t1530, 1020 //width, height\n\t},\n\t\"\", //badpixFilename\n\t0, //timeError\n\t8.0e-5, //matchTol\n\t3.001e-5 //platescale\t\n};\n\n#endif //CAMCONFIG_H\n" }, { "alpha_fraction": 0.6344085931777954, "alphanum_fraction": 0.6344085931777954, "avg_line_length": 8.300000190734863, "blob_id": "fa11db3b4772bf6507014e8de683a765057c3e3d", "content_id": "bfc608db924ec99d08b1b6545c74b7aa32280650", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 93, "license_type": "no_license", "max_line_length": 19, "num_lines": 10, "path": "/balloon_cam/server/main.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include \"server.h\"\n\nint main(){\n\n\tsrand(time(NULL));\n\tServer server;\n\n\tserver.runLoop();\n\n}\n" }, { "alpha_fraction": 0.671147882938385, "alphanum_fraction": 0.7052740454673767, "avg_line_length": 25.135135650634766, "blob_id": "295877035bcfa6101baa8294d879affeda619fa0", "content_id": "11fdbc08e393de8637f63a96bf14a9c175607950", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 967, "license_type": "no_license", "max_line_length": 78, "num_lines": 37, "path": "/common/include/slowdl.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* slowdl.h: contains the slow channel defines\n *\n * This software is copyright (C) 2013 University of Toronto\n *\n * This file is part of mcp/pcm licensed under the GNU General Public License.\n *\n * You should have received a copy of the GNU General Public License\n * along with this software; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n#ifndef INCLUDE_SLOWDL_H\n#define INCLUDE_SLOWDL_H\n\n#include \"channels_tng.h\"\n\n#define SLOWDLSYNCWORD 0xeb90a174\n\n#define SDL_RAW 0\n#define SDL_SCALE 1\n#define SDL_LOG 2\nstruct SlowDlStruct {\n char name[256];\n char type; // c s S u U (c is signed char)\n char encode; // RAW or Scale\n double min;\n double max;\n // 'private' variables: set by updateSlowDL\n channel_t *bi0s;\n double X[3]; // data as read by ReadCalData\n unsigned iX[3]; // data as read by ReadData\n int i_read; // for buffer\n};\n\nvoid updateSlowDL();\n\n#endif /* INCLUDE_SLOWDL_H */\n" }, { "alpha_fraction": 0.5166190266609192, "alphanum_fraction": 0.5642954111099243, "avg_line_length": 35.135868072509766, "blob_id": "b515675d5551b2d299cb0170a0b1496eccfbbdff", "content_id": "959f53a9ef02aac2489fde636f48d16cca908228", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6649, "license_type": "no_license", "max_line_length": 78, "num_lines": 184, "path": "/minicp_config/command_list.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* command_list.c: Spider command specification file\n *\n * This software is copyright (C) 2002-20010 University of Toronto\n *\n * This file is part of the BLAST flight code licensed under the GNU\n * General Public License.\n *\n * You should have received a copy of the GNU General Public License\n * along with this software; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n/* !XXX!!XXX!!XXX!!XXX!!XXX!! BIG ALL CAPS WARNING !!XXX!!XXX!!XXX!!XXX!!XXX!!\n *\n * IF YOU ADD, MODIFY, OR DELETE *ANY* COMMANDS IN THIS FILE YOU *MUST*\n * RECOMPILE AND REINSTALL BLASTCMD ON ARWEN/WIDOW/!\n *\n * !XXX!!XXX!!XXX!!XXX!!XXX!! BIG ALL CAPS WARNING !!XXX!!XXX!!XXX!!XXX!!XXX!!\n */\n\n#include \"command_list.h\"\n\nconst char *command_list_serial = \"$Revision: 1.12 $\";\n\n//these must correspond to #defines in header\n/*const char *GroupNames[N_GROUPS] = {\n \"AzEl Gadget\", \"Balance\", \"Cooling\", \n \"Pointing Sensor Trims\", \"Aux. Electronics\", \"Bias\",\n \"Pointing Sensor Vetos\", \"Actuators\", \"Cal Lamp\",\n \"Pointing Motor Gains\", \"Secondary Focus\", \"Cryo Heat\",\n \"Subsystem Power\", \"Lock Motor\", \"Cryo Control\",\n \"Telemetry\", \"SC Miscellaneous\", \"Free for use 1\",\n \"X-Y Stage\", \"SC Modes\", \"Free for use 2\",\n \"Miscellaneous\", \"SC Parameters\", \"Free for use 3\"\n};*/\n\nconst char *GroupNames[N_GROUPS] = {\n \"Az-El Gadget\", \"Bias\",\n \"Subsystem Power\", \"Miscellaneous\" \n};\n\n//echoes as string; makes enum name the command name string\n#define COMMAND(x) (int)x, #x\n\nstruct scom scommands[N_SCOMMANDS] = {\n {COMMAND(az_el_disable), \"Az-El mount emergency shutdown!\", GR_AZEL},\n {COMMAND(xyzzy), \"nothing happens here\", GR_MISC}\n};\n\n/* parameter type:\n * i : parameter is 15 bit unnormalised integer\n * l : parameter is 30 bit unnormalised integer\n * f : parameter is 15 bit renormalised floating point\n * d : parameter is 30 bit renormalised floating point\n * s : parameter is 7-bit character string\n */\nstruct mcom mcommands[N_MCOMMANDS] = {\n {COMMAND(dac1_ampl), \"Set bias signal amplitude on MB #1\", GR_BIAS, 2,\n {\n {\"Which (0-31,32=all)\", 0, 32, 'i', \"\"},\n {\"Amplitude (full=32767)\", 1, MAX_15BIT, 'i', \"\"}\n }\n },\n {COMMAND(dac1_phase), \"Set lock-in phase on MB #1\", GR_BIAS, 2,\n {\n {\"Which (0-31,32=all)\", 0, 32, 'i', \"\"},\n {\"Phase (degrees)\", 0, 360, 'f', \"\"}\n }\n },\n {COMMAND(bias1_step), \"step through different bias levels on MB #1\",\n GR_BIAS, 5,\n {\n {\"Start (full=32767)\", 0, MAX_15BIT, 'i', \"STEP_START_BIAS\"},\n {\"End (full=32767)\", 0, MAX_15BIT, 'i', \"STEP_END_BIAS\"},\n {\"N steps\", 1, MAX_15BIT, 'i', \"STEP_NSTEPS_BIAS\"},\n {\"Time per step (ms)\", 100, MAX_15BIT, 'i', \"STEP_TIME_BIAS\"},\n {\"Which (0-31,32=all)\", 0, 32, 'i', \"STEP_WHICH_BIAS\"},\n }\n },\n {COMMAND(phase1_step), \"step through different phases on MB #1\",\n GR_BIAS, 4,\n {\n {\"Start (degrees)\", 0, 360, 'f', \"STEP_START_PHASE\"},\n {\"End (degrees)\", 0, 360, 'f', \"STEP_END_PHASE\"},\n {\"N steps\", 1, MAX_15BIT, 'i', \"STEP_NSTEPS_PHASE\"},\n {\"Time per step (ms)\", 100, MAX_15BIT, 'i', \"STEP_TIME_PHASE\"},\n }\n },\n\n {COMMAND(dac2_ampl), \"Set bias signal amplitude on MB #2\", GR_BIAS, 2,\n {\n {\"Which (0-31,32=all)\", 0, 32, 'i', \"\"},\n {\"Amplitude (full=32767)\", 1, MAX_15BIT, 'i', \"\"}\n }\n },\n {COMMAND(dac2_phase), \"Set lock-in phase on MB #2\", GR_BIAS, 2,\n {\n {\"Which (0-31,32=all)\", 0, 32, 'i', \"\"},\n {\"Phase (degrees)\", 0, 360, 'f', \"\"}\n }\n },\n {COMMAND(bias2_step), \"step through different bias levels on MB #2\",\n GR_BIAS, 5,\n {\n {\"Start (full=32767)\", 0, MAX_15BIT, 'i', \"STEP_START_BIAS\"},\n {\"End (full=32767)\", 0, MAX_15BIT, 'i', \"STEP_END_BIAS\"},\n {\"N steps\", 1, MAX_15BIT, 'i', \"STEP_NSTEPS_BIAS\"},\n {\"Time per step (ms)\", 100, MAX_15BIT, 'i', \"STEP_TIME_BIAS\"},\n {\"Which (0-31,32=all)\", 0, 32, 'i', \"STEP_WHICH_BIAS\"},\n }\n },\n {COMMAND(phase2_step), \"step through different phases on MB #2\",\n GR_BIAS, 4,\n {\n {\"Start (degrees)\", 0, 360, 'f', \"STEP_START_PHASE\"},\n {\"End (degrees)\", 0, 360, 'f', \"STEP_END_PHASE\"},\n {\"N steps\", 1, MAX_15BIT, 'i', \"STEP_NSTEPS_PHASE\"},\n {\"Time per step (ms)\", 100, MAX_15BIT, 'i', \"STEP_TIME_PHASE\"},\n }\n },\n\n {COMMAND(reset_adc), \"Reset an ADC motherboard\", GR_POWER, 1,\n {\n {\"Node number\", 0, 64, 'i', \"\"}\n }\n },\n {COMMAND(az_el_raster), \"Az-El mount raster scan\", GR_AZEL, 9,\n { \n {\"az raster centre (deg)\", -180.0, 180.0, 'f', \"AZ\"}, \n {\"el raster centre (deg)\", -5.0, 85.0, 'f', \"EL\"}, \n {\"az raster scan width (deg)\", 0.0, 180.0, 'f', \"WIDTH_AZ\"}, \n {\"el raster height (deg)\", 0.0, 90.0, 'f', \"HEIGHT_EL\"},\n {\"az raster scan speed (deg/s)\", 0.0, 5.0, 'f', \"V_AZ\"}, \n {\"el raster scan speed (deg/s)\", 0.0, 5.0, 'f', \"V_EL\"},\n {\"az raster acceleration (deg/s^2)\", 0.0, 5.0, 'f', \"A_AZ\"},\n {\"el raster acceleration (deg/s^2)\", 0.0, 5.0, 'f', \"A_EL\"},\n {\"el raster no. of steps\", 0, MAX_15BIT, 'i', \"N_EL\"},\n\n }\n },\n {COMMAND(az_el_goto), \"Az-El mount goto mode\", GR_AZEL, 6,\n {\n {\"az goto acceleration (deg/s^2)\", 0.0, 5.0, 'f', \"A_AZ\"},\n {\"el goto acceleration (deg/s^2)\", 0.0, 5.0, 'f', \"A_EL;\"},\n {\"az goto speed (deg/s)\", 0.0, 5.0, 'f', \"V_AZ\"},\n {\"el goto speed (deg/s)\", 0.0, 5.0, 'f', \"V_EL\"},\n {\"az goto position (deg)\", -180, 180.0, 'f', \"AZ\"}, \n {\"el goto position (deg)\", -5.0, 85.0, 'f', \"EL\"} \n }\n },\n {COMMAND(az_el_set), \"Input Az-El mount starting angles\", GR_AZEL, 2,\n {\n {\"starting azimuth (deg)\", -180.0, 180.0, 'f', \"AZ_NOW\"},\n {\"starting elevation (deg)\", -10.0, 86.0, 'f', \"EL_NOW\"},\n }\n }, \n {COMMAND(plugh), \"A hollow voice says \\\"Plugh\\\".\", GR_MISC, 1,\n {\n {\"Plover\", 0, MAX_15BIT, 'i', \"PLOVER\"}\n }\n }\n};\n\n/* validate parameters of an mcom -- called by spidercmd before tranmitting a\n * command and by pcm after decoding one. Inputs:\n *\n * cmd: command number\n * [irs]values: mcp-style parsed parameters\n * buflen size of the err_buffer\n * err_buffer a place to write the error string\n *\n * Return value:\n *\n * 0: if parameters are okay; err_buffer ignored.\n * !0: if parameters are not okay. In this case a descriptive error message\n * should be written to err_buffer.\n */\nint mcom_validate(enum multiCommand cmd, const int *ivalues,\n const double *rvalues, char svalues[][CMD_STRING_LEN], size_t buflen,\n char *err_buffer)\n{\n return 0; /* no checks -- everything passes */\n}\n" }, { "alpha_fraction": 0.6397188305854797, "alphanum_fraction": 0.6454305648803711, "avg_line_length": 30.164382934570312, "blob_id": "35c13183f7c1829e1f1204e6babdff444eaea607", "content_id": "d2bff49962fb93cc349cc69aaa213fa96780732a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2277, "license_type": "no_license", "max_line_length": 102, "num_lines": 73, "path": "/stars/code/shared/lens/results.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"results.h\"\n\nusing namespace Shared::Lens;\n\nResults::Results()\n{\n device_name = \"\";\n device_found = false;\n focus_value = 0;\n focus_found = false;\n aperture_value = 0;\n aperture_found = false;\n for (unsigned int i=0; i<num_commands; i++) {\n command_counters[i] = 0;\n }\n max_exposure_and_readout_time = 0.500;\n}\n\nResults& Results::operator=(const Results &rhs)\n{\n if (this != &rhs) {\n device_name = rhs.device_name;\n device_found = rhs.device_found;\n focus_value = rhs.focus_value;\n focus_found = rhs.focus_found;\n aperture_value = rhs.aperture_value;\n aperture_found = rhs.aperture_found;\n for (unsigned int i=0; i<num_commands; i++) {\n command_counters[i] = rhs.command_counters[i];\n }\n max_exposure_and_readout_time = rhs.max_exposure_and_readout_time;\n }\n return *this;\n}\n\nbool Results::is_focus_valid(Requests& requests)\n{\n if (!focus_found) {\n return false;\n }\n using namespace Imaging::LensCommands;\n if (command_counters[init_focus] == requests.commands[init_focus].counter &&\n command_counters[get_focus] == requests.commands[get_focus].counter &&\n command_counters[set_focus] == requests.commands[set_focus].counter &&\n command_counters[set_focus_incremental] == requests.commands[set_focus_incremental].counter &&\n command_counters[define_focus] == requests.commands[define_focus].counter)\n {\n return true;\n }\n return false;\n}\n\nbool Results::is_aperture_valid(Requests& requests)\n{\n if (!aperture_found) {\n return false;\n }\n using namespace Imaging::LensCommands;\n if (command_counters[init_aperture] == requests.commands[init_aperture].counter &&\n command_counters[get_aperture] == requests.commands[get_aperture].counter &&\n command_counters[define_aperture] == requests.commands[define_aperture].counter &&\n command_counters[set_aperture] == requests.commands[set_aperture].counter)\n {\n return true;\n }\n return false;\n}\n\n" }, { "alpha_fraction": 0.6504854559898376, "alphanum_fraction": 0.6532593369483948, "avg_line_length": 22.225807189941406, "blob_id": "3514a0281abbc7170b37bf3cd90238609081c33b", "content_id": "1064bd63daead13fddb9e0fd052d85be68c545a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2163, "license_type": "no_license", "max_line_length": 78, "num_lines": 93, "path": "/stars/code/solving/finding/badpix.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * Added by Krystle Sy to remove bad pixels.\n */\n\n#include \"badpix.h\"\n#include \"../blob.h\"\n#include \"../logger.h\"\n#include \"../../shared/image/stats.h\"\n#include \"../../shared/image/raw.h\"\n#include \"../../shared/solving/settings.h\"\n#include \"../../tools/math.h\"\n#include \"../../parameters/manager.h\"\n#include \"../../parameters/housekeeping.h\"\n#include <boost/format.hpp>\n#include <boost/filesystem/operations.hpp>\n#include <iostream>\n#include <fstream>\n\nusing namespace Solving::Finding;\nusing namespace std;\nusing Solving::Blob;\nusing std::vector;\nusing std::string;\n\n#define shared_stats (*(Shared::Image::stats_solver_for_main.r))\n#define shared_settings (*(Shared::Solving::settings.r))\n#define shared_housekeeper (*(Shared::Housekeeping::housekeeper_for_camera.w))\n\n\nBadpix::Badpix(Parameters::Manager& params)\n{\n\timage_width = params.general.image_width;\n\timage_height = params.general.image_height;\n\tsatval = params.general.image_depth;\n\t \n }\n\nBadpix::~Badpix(void)\n{\t\n}\n\nint Badpix::load_badpix(std::string fname) {\n\tstring thisline;\n\tint count; // Number of elements read from the current line\n\tint x, y; // coordinates of the bad pixel in this line\n\tbadpixels badpair;\n\n\t// Read through file line-by-line reading in pixel coordinates.\n\t// Use the badpairs vector to dynamically add coordinates as we\n\t// read them in. \n\n\n\tifstream badfile(fname);\n\tif (badfile.is_open())\n\t{\n\t\tnumbadpix = 0;\n\n\t\twhile (getline(badfile, thisline)) {\n\t\t\tcount = sscanf_s(thisline.c_str(), \"%i %i\", &x, &y);\n\t\t\tif (count == 2) { // If we read in a coordinate pair\n\t\t\t\tif (x <= image_width){\n\t\t\t\t\tbadpair.xpix = x;\n\t\t\t\t\tif (y <= image_height) {\n\t\t\t\t\t\tbadpair.ypix = (image_height - y - 1);\n\t\t\t\t\t\tbadpairs.push_back(badpair);\n\t\t\t\t\t\tnumbadpix++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tbadfile.close();\n\n\tlogger.log(format(\"Opened bad pixel file with %i bad pixels.\")\n\t\t% int(numbadpix));\n\n\treturn 1;\n}\n\n\n\nvoid Badpix::fix_badpix(Shared::Image::Raw& image) {\n\tint i, k;\n\n\tif (&badpixlist != NULL) {\n\t\tshort val = (short)shared_stats.mean;\n\t\tfor (i = 0, k = 0; i < (int)numbadpix; i++) {\n\t\t\tk = badpairs[i].ypix * image.width + badpairs[i].xpix;\n\t\t\timage.pixels[k] = val;\n\t\t}\n\t}\n}\n\n\n\n" }, { "alpha_fraction": 0.6449820399284363, "alphanum_fraction": 0.6564236879348755, "avg_line_length": 29.287128448486328, "blob_id": "9555146ff1dd51941c7a5b3bb15671391dddb38b", "content_id": "f9b442d45ad97a8cec4d0ca07696f96486ff6820", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3059, "license_type": "no_license", "max_line_length": 102, "num_lines": 101, "path": "/owl/PStyle.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"PObject.h\"\n\n#include <QColor>\n#include <QStringList>\n#include <QFont>\n#include <QPalette>\n#include <QTimer>\n\n#ifndef PFORMAT_H\n#define PFORMAT_H\n\nclass PStyleNotifier : public QObject\n{\n Q_OBJECT\npublic:\n bool on;\n static PStyleNotifier* me;\n PStyleNotifier() { on=1;}\npublic slots:\n void disable() { on=0; }\n void enable() { on=1; }\n void notifyChange();\nsignals:\n void change();\n};\n\nclass PStyle : public QObject, public PObject\n{\n Q_OBJECT\nprotected:\n QString _name;\n bool _bold, _italic;\n QColor _bg,_fg;\n bool _linked; /**Set this to true if this PStyle is shared between objects*/\n\npublic:\n bool _dirty;\n friend QDataStream& operator<<(QDataStream& a,PStyle& b);\n friend QDataStream& operator>>(QDataStream& a,PStyle& b);\n friend QVariant save(PStyle&);\n friend void load(QVariant v,PStyle&);\n\n static PStyle* noStyle;\n static QList<PStyle*> _u;\n PStyle(QString name,bool bold=0,bool italic=0,QColor bg=\"white\",QColor fg=\"black\",bool linked=0) :\n _name(name), _bold(bold), _italic(italic),_bg(bg),_fg(fg),_linked(linked), _dirty(1)\n { if(linked) _u.push_back(this); }\n QString name() const { return _name; }\n bool isBold() const { return _bold; }\n bool isItalic() const { return _italic; }\n QColor bgColour() const { return _bg; }\n QColor fgColour() const { return _fg; }\n bool isLinked() const { return _linked; }\n\npublic slots:\n void setName(const QString& name) { _name=name; _dirty=1; }\n void setBold(const bool& t) { _bold=t; _dirty=1; }\n void setItalic(const bool& t) { _italic=t; _dirty=1; }\n void setBg(const QColor& c) { _bg=c; _dirty=1; }\n void setFg(const QColor& c) { _fg=c; _dirty=1; }\n};\n\ntemplate<class T> void applyStyle(T* obj,PStyle* s)\n{\n QFont f=obj->font();\n //f.setFamily(\"Droid Sans\");\n f.setBold(s->isBold());\n f.setItalic(s->isItalic());\n if(obj->font()!=f) obj->setFont(f);\n QPalette p=obj->palette();\n p.setColor(obj->foregroundRole(),s->fgColour());\n p.setColor(obj->backgroundRole(),s->bgColour());\n if(obj->palette()!=p)\n {\n obj->setPalette(p);\n obj->setAutoFillBackground(s->bgColour()!=\"white\");\n }\n}\n\n#endif // PFORMAT_H\n" }, { "alpha_fraction": 0.5744616985321045, "alphanum_fraction": 0.5807860493659973, "avg_line_length": 23.23357582092285, "blob_id": "5c4d20ac92f699e916a181bcb318bfb85e9a3ff2", "content_id": "6dac6e3d7d8f635ff45a79e1a639beca3878a9b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6641, "license_type": "no_license", "max_line_length": 114, "num_lines": 274, "path": "/common/blast.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* blast.c: the BLAST flight code common functions\n *\n * This software is copyright (C) 2004-2010 University of Toronto\n *\n * This software 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 2 of the License, or\n * (at your option) any later version.\n *\n * This software 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 this software; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <stdlib.h> /* ANSI C std library (exit, realloc, free) */\n#include <errno.h> /* ANSI C library errors (errno) */\n#include <pthread.h> /* POSIX threads (pthread_exit) */\n#include <stdio.h> /* ANSI C std io library (FILE, stderr, stdout) */\n#include <string.h> /* ANSI C strings (strlen, strncat, strdup, &c.) */\n#include <syslog.h> /* BSD system logger (openlog, syslog, closelog) */\n\n#include \"blast.h\"\n\n/* BUOS (BLAST Unified Output Scheme) */\nstatic int __buos_disable_exit = 0;\nstatic int __buos_allow_mem = 0;\nstatic void (*__buos_real_bputs)(buos_t, const char*) = NULL;\n\nvoid bputs_stdio(buos_t l, const char* s)\n{\n FILE* stream = stderr;\n\n switch (l) {\n case none:\n return;\n case mem:\n if (l == mem && !__buos_allow_mem)\n return;\n case info:\n case startup:\n case sched:\n stream = stdout;\n case warning:\n case err:\n case tfatal:\n case fatal:\n fputs(s, stream);\n if (s[strlen(s) - 1] != '\\n')\n fputs(\"\\n\", stream);\n }\n\n if (!__buos_disable_exit) {\n if (l == fatal)\n exit(1);\n else if (l == tfatal)\n pthread_exit(NULL);\n }\n}\n\nvoid bputs_syslog(buos_t l, const char* s)\n{\n int level = LOG_INFO;\n\n switch (l) {\n case none:\n return;\n case info:\n level = LOG_INFO;\n break;\n case warning:\n level = LOG_WARNING;\n break;\n case err:\n level = LOG_ERR;\n break;\n case tfatal:\n level = LOG_CRIT;\n break;\n case fatal:\n level = LOG_ALERT;\n break;\n case startup:\n level = LOG_NOTICE;\n break;\n case mem:\n case sched:\n level = LOG_DEBUG;\n break;\n }\n\n if (l != mem || __buos_allow_mem) syslog(level, \"%s\", s);\n\n if (!__buos_disable_exit) {\n if (l == fatal)\n exit(1);\n else if (l == tfatal) pthread_exit(NULL);\n }\n}\n\nvoid bputs(buos_t l, const char* s)\n{\n if (__buos_real_bputs)\n (*__buos_real_bputs)(l, s);\n else\n bputs_stdio(l, s);\n}\n\nvoid bprintf(buos_t l, const char* fmt, ...)\n{\n char message[BUOS_MAX];\n va_list argptr;\n\n va_start(argptr, fmt);\n vsnprintf(message, BUOS_MAX, fmt, argptr);\n va_end(argptr);\n\n bputs(l, message);\n}\n\nvoid berror(buos_t l, const char* fmt, ...)\n{\n char message[BUOS_MAX];\n va_list argptr;\n int error = errno;\n\n va_start(argptr, fmt);\n vsnprintf(message, BUOS_MAX, fmt, argptr);\n va_end(argptr);\n\n /* add a colon */\n strncat(message, \": \", BUOS_MAX - strlen(message));\n\n message[BUOS_MAX - 1] = '\\0';\n /* copy error message into remainder of string -- Note: sterror is reentrant\n * despite what strerror(3) insinuates (and strerror_r is horribly b0rked) */\n strncat(message, strerror(error), BUOS_MAX - strlen(message));\n message[BUOS_MAX - 1] = '\\0';\n\n bputs(l, message);\n}\n\nvoid buos_allow_mem(void)\n{\n __buos_allow_mem = 1;\n}\n\nvoid buos_disallow_mem(void)\n{\n __buos_allow_mem = 0;\n}\n\nvoid buos_disable_exit(void)\n{\n __buos_disable_exit = 1;\n}\n\nvoid buos_enable_exit(void)\n{\n __buos_disable_exit = 0;\n}\n\nvoid buos_use_func(void (*puts_func)(buos_t, const char*))\n{\n __buos_real_bputs = puts_func;\n}\n\nvoid buos_use_syslog(void)\n{\n __buos_real_bputs = bputs_syslog;\n}\n\nvoid buos_use_stdio(void)\n{\n __buos_real_bputs = bputs_stdio;\n}\n\n/* BLAMM (BLAST Memory Manager) definitions */\nvoid *_balloc(buos_t l, size_t s, const char* f, int w, const char* n)\n{\n void *p;\n\n p = malloc(s);\n blast_mem(\"malloced %u bytes in %s as %p\", (unsigned)s, f, p);\n\n if (p == NULL)\n berror(l, \"unable to malloc %u bytes at %s:%i in %s\", (unsigned)s, n, w, f);\n\n return p;\n}\n\nvoid *_reballoc(buos_t l, void* p, size_t s, const char* f, int w,\n const char* n)\n{\n void *q;\n\n q = realloc(p, s);\n blast_mem(\"realloced %u bytes from %p in %s as %p\", (unsigned)s, p, f, q);\n\n if (q == NULL)\n berror(l, \"unable to realloc %u bytes from %p at %s:%i in %s\", (unsigned)s,\n p, n, w, f);\n\n return q;\n}\n\nvoid _bfree(buos_t l, void* p, const char* f, int w, const char* n)\n{\n blast_mem(\"freeing %p in %s\", p, f);\n free(p);\n}\n\nchar* _bstrdup(buos_t l, const char* s, const char* f, int w, const char* n)\n{\n char *q;\n\n q = strdup(s);\n blast_mem(\"strduped `%s' in %s as %p\", s, f, q);\n\n if (q == NULL)\n berror(l, \"unable to strdup `%s' at %s:%i in %s\", s, n, w, f);\n\n return q;\n}\n\nvoid _basprintf(buos_t l, char **m_dest, const char *m_fmt, const char *m_fn, int m_line, const char *m_file, ...)\n{\n va_list argptr;\n int retval;\n\n va_start(argptr, m_file);\n retval = vasprintf(m_dest, m_fmt, argptr);\n va_end(argptr);\n\n if (retval < 0) {\n berror(l, \"%s:%d (%s): Unable to create string with format '%s'\", m_fn, m_line, m_file, m_fmt);\n *m_dest = NULL;\n }\n}\n\nchar* _bstrndup(buos_t m_level, const char* m_src, size_t m_len, const char* m_fnname, int m_lineno,\n const char* m_filename)\n{\n char *dest_ptr;\n\n size_t len = strnlen(m_src, m_len) + 1;\n dest_ptr = _balloc(m_level, len, m_filename, m_lineno, m_fnname);\n\n blast_mem(\"strnduped `%s' in %s as %p\", m_src, m_fnname, dest_ptr);\n\n if (dest_ptr == NULL)\n berror(m_level, \"unable to strndup `%s' at %s:%i in %s\", m_src, m_filename, m_lineno, m_fnname);\n else\n dest_ptr[len - 1] = '\\0';\n\n return (char*) memcpy(dest_ptr, m_src, len);\n}\n\nvoid *_memdup(buos_t l, const void *m_src, size_t n, const char* m_func, int m_line, const char *m_file)\n{\n void *dest;\n\n dest = _balloc(l, n, m_func, m_line, m_file);\n if (dest == NULL)\n bprintf(l, \"Previous balloc error originated from _memdup\");\n else\n memcpy(dest, m_src, n);\n return dest;\n}\n\n" }, { "alpha_fraction": 0.5473440885543823, "alphanum_fraction": 0.5626952648162842, "avg_line_length": 38.783782958984375, "blob_id": "5ddf4050539edec9c120fbfc6d72672b12c873a3", "content_id": "f0aa47024b1f5022d16e72cbca214fd5645ed9e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7361, "license_type": "no_license", "max_line_length": 151, "num_lines": 185, "path": "/groundhog/blast/biphase.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <unistd.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <syslog.h>\n#include <signal.h>\n#include <libgen.h>\n#include <sys/ioctl.h>\n#include <sys/socket.h>\n#include <sys/time.h>\n#include <sys/statvfs.h>\n#include <arpa/inet.h>\n#include <netinet/in.h>\n#include <netinet/tcp.h>\n#include <pthread.h>\n\n#include \"groundhog.h\"\n\n#define BIPHASE_FRAME_SIZE_BYTES (BI0_FRAME_SIZE*2)\n#define BIPHASE_PACKET_SIZE (BIPHASE_FRAME_SIZE_BYTES-2-PACKET_HEADER_SIZE)\n#define BIPHASE_PACKET_WORD_START (7)\n\n#define DEV \"/dev/decom_pci\"\n\nstruct TlmReport bi0_report = {0};\n\nvoid print_packet(uint8_t * packet, size_t length) {\n printf(\"Packet Received is: \\n\");\n for (int i = 0; i < length; i++) {\n printf(\"%04x \", *(packet + i));\n }\n}\n\nvoid get_stripped_packet(bool *normal_polarity, uint8_t *receive_buffer_stripped, const uint16_t *receive_buffer, \n const uint16_t *anti_receive_buffer, linklist_t **ll, uint32_t **frame_number, \n uint16_t **i_pkt, uint16_t **n_pkt) {\n\n uint32_t *serial;\n\n if (*normal_polarity) {\n // Reading the header\n readHeader((uint8_t *) (receive_buffer+1), &serial, frame_number, i_pkt, n_pkt);\n // Checking for polarity\n if ((*ll = linklist_lookup_by_serial(*serial))) {\n // blast_dbg(\"\\n=== I found a linklist with serial %x, counter: %x, i_pkt: %d, n_pkt: %d==\\n\", *serial, *frame_number, **i_pkt, **n_pkt);\n *normal_polarity = true;\n memcpy(receive_buffer_stripped, receive_buffer+BIPHASE_PACKET_WORD_START, BIPHASE_PACKET_SIZE);\n // print_packet(receive_buffer_stripped, BIPHASE_PACKET_SIZE);\n } else if ((*ll = linklist_lookup_by_serial((uint16_t) ~(*serial)))) {\n *normal_polarity = false;\n }\n }\n if (!(*normal_polarity)) {\n // Reading the header\n readHeader((uint8_t *) (anti_receive_buffer+1), &serial, frame_number, i_pkt, n_pkt);\n // Checking for polarity\n if ((*ll = linklist_lookup_by_serial(*serial))) {\n // blast_dbg(\"Inverted 1: I found a linklist with serial %x, counter: %d, i_pkt: %d, n_pkt: %d\\n\", *serial, *frame_number, **i_pkt, **n_pkt);\n *normal_polarity = false;\n memcpy(receive_buffer_stripped, anti_receive_buffer+BIPHASE_PACKET_WORD_START, BIPHASE_PACKET_SIZE);\n // print_packet(receive_buffer_stripped, BIPHASE_PACKET_SIZE);\n } else if ((*ll = linklist_lookup_by_serial((uint16_t) ~(*serial)))) {\n *normal_polarity = true;\n readHeader((uint8_t *) (receive_buffer+1), &serial, frame_number, i_pkt, n_pkt);\n // blast_dbg(\"Inverted 2: I found a linklist with serial %x, counter: %d, i_pkt: %d, n_pkt: %d\\n\", *serial, *frame_number, **i_pkt, **n_pkt);\n memcpy(receive_buffer_stripped, receive_buffer+BIPHASE_PACKET_WORD_START, BIPHASE_PACKET_SIZE);\n // print_packet(receive_buffer_stripped, BIPHASE_PACKET_SIZE);\n }\n }\n}\n\nvoid biphase_receive(void *args)\n{\n\n int decom_fp;\n int i_word = 0;\n const uint16_t sync_word = 0xeb90;\n uint16_t raw_word_in;\n uint32_t transmit_size;\n\n uint16_t receive_buffer[2*BI0_FRAME_SIZE];\n uint16_t anti_receive_buffer[2*BI0_FRAME_SIZE];\n uint8_t receive_buffer_stripped[BIPHASE_PACKET_SIZE];\n uint8_t *compbuffer = calloc(1, BI0_MAX_BUFFER_SIZE);\n uint32_t compbuffer_size = 0;\n\n linklist_t *ll = NULL;\n uint16_t *i_pkt;\n uint16_t *n_pkt;\n uint32_t *frame_number;\n int retval;\n\n uint8_t *local_allframe = calloc(1, superframe->allframe_size);\n\n // open a file to save all the raw linklist data\n linklist_rawfile_t * ll_rawfile = NULL;\n uint32_t prev_serial = 0;\n\n bool normal_polarity = true;\n\n // buos_use_stdio();\n\n /* Open Decom */\n if ((decom_fp = open(DEV, O_RDONLY | O_NONBLOCK)) == -1) {\n berror(fatal, \"fatal error opening \" DEV);\n }\n\n /* Initialise Decom */\n ioctl(decom_fp, DECOM_IOC_RESET);\n //ioctl(decom_fp, DECOM_IOC_FRAMELEN, BI0_FRAME_SIZE);\n ioctl(decom_fp, DECOM_IOC_FRAMELEN, 2*BI0_FRAME_SIZE-1);\n\n /* set up our outputs */\n openlog(\"decomd\", LOG_PID, LOG_DAEMON);\n // buos_use_syslog();\n int64_t framenum = 0;\n int af = 0;\n\n while(true) {\n while ((read(decom_fp, &raw_word_in, sizeof(uint16_t))) > 0) {\n // Fill receive and anti receive\n receive_buffer[i_word] = raw_word_in;\n anti_receive_buffer[i_word] = ~raw_word_in;\n if (i_word == 0) {\n // Beginning of packet?\n ioctl(decom_fp, DECOM_IOC_NUM_UNLOCKED);\n if ((raw_word_in != sync_word) && (raw_word_in != (uint16_t) ~sync_word)) {\n // This was not the beginning actually\n i_word = 0;\n continue;\n }\n // printf(\"\\n=== Frame Start ==\\n\");\n } else if ((i_word) == (BI0_FRAME_SIZE-1)) {\n get_stripped_packet(&normal_polarity, receive_buffer_stripped, receive_buffer, anti_receive_buffer, \n &ll, &frame_number, &i_pkt, &n_pkt);\n retval = depacketizeBuffer(compbuffer, &compbuffer_size, \n BIPHASE_PACKET_SIZE-BI0_ZERO_PADDING, \n i_pkt, n_pkt, receive_buffer_stripped);\n memset(receive_buffer_stripped, 0, BIPHASE_PACKET_SIZE);\n\n \n if ((retval == 0) && (ll != NULL)) {\n // hijack the frame number for transmit size\n transmit_size = *frame_number;\n\n // blast_info(\"Transmit size=%d, blk_size=%d\", transmit_size, ll->blk_size);\n // The compressed linklist has been fully reconstructed\n // blast_info(\"[Biphase] Received linklist with serial_number 0x%x\\n\", *(uint32_t *) ll->serial);\n\n if (groundhog_check_for_fileblocks(ll, FILE_LINKLIST)) {\n // this is a file that has been downlinked, so unpack and extract to disk\n framenum = groundhog_unpack_fileblocks(ll, transmit_size, compbuffer, NULL,\n NULL, NULL, NULL, GROUNDHOG_EXTRACT_TO_DISK);\n } else { // write the linklist data to disk\n // set flags for data extraction\n unsigned int flags = 0;\n if (*(uint32_t *) ll->serial != prev_serial) flags |= GROUNDHOG_OPEN_NEW_RAWFILE;\n prev_serial = *(uint32_t *) ll->serial;\n\n // process the linklist and write the data to disk\n framenum = groundhog_process_and_write(ll, transmit_size, compbuffer,\n local_allframe, \"BI0\", \"Biphase\",\n &ll_rawfile, flags);\n }\n\n // fill out the telemetry report\n bi0_report.ll = ll;\n bi0_report.framenum = abs(framenum); \n bi0_report.allframe = af; \n\n memset(compbuffer, 0, BI0_MAX_BUFFER_SIZE);\n compbuffer_size = 0;\n }\n }\n i_word++;\n i_word = (i_word % BI0_FRAME_SIZE);\n //printf(\"%04x \", raw_word_in);\n }\n usleep(100);\n }\n}\n\n" }, { "alpha_fraction": 0.6890756487846375, "alphanum_fraction": 0.6890756487846375, "avg_line_length": 13.13559341430664, "blob_id": "3d91856bd099d9420850e9f1d5a5f273af443ff4", "content_id": "eba873de671cffc511f830938f47aa0e3d5fa70e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 833, "license_type": "no_license", "max_line_length": 62, "num_lines": 59, "path": "/balloon_cam/locator.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//locator.h\n//a class for locating a blob in the image file\n\n#pragma once\n\n#include <vector>\n#include \"camera.h\"\n\nstruct coords{//the coordinates of the object\n\tint x;\n\tint y;\n};\n\nstruct blob{//a structure representing a blob\n\tcoords centroid;\n\tint size;\n\tcoords source;\n\tcoords max;\n\tcoords min;\n};\n\nclass Locator{\n\n\tpublic:\n\n\t\tLocator(int, int, int, int, Camera*);\n\n\t\tblob locate(void*);//finds coordinates given an image\n\n\t\tblob locate();\n\n\t\tvoid writeData();//writes out a text file of the coordinates\n\t\t\n\tprivate:\n\n\t\tint totalPixels;\n\n\t\tint xPixels;\n\n\t\tint yPixels;\n\t\t\n\t\tint pixelDataSize;\n\n\t\tint sigmaNumber;\n\n\t\tdouble averageValue;\n\n\t\tdouble standardDeviation;\n\n\t\tblob lastBlob;\n\t\t\n\t\tstd::vector<blob> blobVector;\n\n\t\tblob detectBlob(void *, void *);\n\n\t\tbool blobWasFound(void*, void*, std::vector<blob>);\n\n\t\tCamera* camera;\n};" }, { "alpha_fraction": 0.6820491552352905, "alphanum_fraction": 0.6960582137107849, "avg_line_length": 32.099998474121094, "blob_id": "798fec7d06a017738e3373b7cde9b72d8e17cc29", "content_id": "26bd9cfa4c73b3dce799b4738cac96afffc000d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7281, "license_type": "no_license", "max_line_length": 143, "num_lines": 220, "path": "/balloon_cam/pixelFixer.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//pixelFivxer.cpp\n//a class that decides on the bad pixels in the camera and saves them into the correction table\n\n#include \"stdafx.h\"\n#include \"pixelFixer.h\"\n\nPixelFixer::PixelFixer(int width, int height, int colourDepth){\n\txSize = width;\n\tySize = height;\n\t\n\tif(colourDepth%8 != 0){\n\t\tprintf(\"Pixel size is not a multiple of 8. This causes pixel fixer to be incorrect. Ignore it.\\n\");\n\t}\n\n\tpixelSize = colourDepth;\n}\n\nWORD* PixelFixer::generateBadPixelTable(char* directory){\n\n\tWIN32_FIND_DATA data;\n\tHANDLE handle;\n\n\tstd::vector<double> pixelVector;\n\tpixelVector.resize(xSize*ySize, 0);\n\tchar newDirectory[100];\n\tsprintf_s(newDirectory, 100, \"%s/LensOn*.bmp\" ,directory);//makes a search string for the files we want\n\n\twchar_t* filePath = (wchar_t *) malloc (200);\n\n\tMultiByteToWideChar(CP_ACP, MB_COMPOSITE, newDirectory, -1, filePath, 200);//converts the filename to the correct format\n\n\thandle = FindFirstFile(filePath, &data);//finds the first file in the directory\n\n\tfree(filePath);\n\tchar* fileName = (char *) malloc (200);\n\tchar* newFileName =(char*) malloc(200);\n\tint exposureTime;\n\n\tif(handle != INVALID_HANDLE_VALUE){//if the first file exists\n\t\t\n\t\tWideCharToMultiByte(CP_ACP, 0, data.cFileName, -1, fileName, 200, NULL, NULL);\n\n\t\tsscanf_s(fileName, \"LensOn%d.bmp\", &exposureTime);\n\n\t\tsprintf_s(newFileName, 200, \"%s/%s\", directory, fileName);\n\n\t\tpixelVector = detectWeirdPixels(pixelVector, newFileName, exposureTime);//calls the helper method to put the data from the file into a vector\n\t}else{\n\t\tprintf(\"Data files cannot be opened in generateBadPixelTable. Error Code %d\\n\", GetLastError());\n\t\treturn NULL;\n\t}\n\n\tint count = 1;\n\n\twhile(FindNextFile(handle, &data)){//while there are more files\n\t\tWideCharToMultiByte(CP_ACP, 0, data.cFileName, -1, fileName, 200, NULL, NULL);\n\t\tsprintf_s(newFileName, 200, \"%s/%s\", directory, fileName);\n\t\tsscanf_s(fileName, \"LensOn%d.bmp\", &exposureTime);\n\t\tpixelVector = detectWeirdPixels(pixelVector, newFileName, exposureTime);//repeat the above process\n\t\tcount ++;\n\t}\n\tfree(fileName);\n\tfree(newFileName);\n\n\tchar* charValues =(char *) malloc(pixelVector.size());\n\n\tFILE* textFile; \n\tfopen_s(&textFile, \"signaltonoise.txt\", \"w\");//makes a file with the S/N data for plotting\n\tfprintf(textFile, \"X\\t\\tY\\t\\tIntensity\\n\");\n\n\tfor(unsigned int i = 0; i<pixelVector.size(); i++){\n\t\tpixelVector[i] /= count;\n\t\tfprintf(textFile, \"%5d\\t%5d\\t%5d\\n\", i%xSize, i/xSize, (int) pixelVector[i]);//prints the data into the file\n\t\t*(char *)((unsigned long long int)charValues + i) = (char)(int)pixelVector[i];//puts the data into a block of memory to generate the image\n\t}\n\n\tfclose(textFile);\n\tdouble average =0;\n\tdouble stdDev = 0;\n\tchar compositeFilename[100];\n\tsprintf_s(compositeFilename, 100, \"%s/Composite.bmp\" ,directory);\n\n\tstd::fstream file = std::fstream(compositeFilename , std::ios_base::in | std::ios_base::binary);//opens the old composite image for reading\n\tif(!file.is_open()){\n\t\tprintf(\"File was not opened in detectWeirdPixels\\n\");\n\t}\n\n\tchar* header = (char* ) malloc(14);//gets from it the relevant values\n\tfile.read(header, 14);\n\tunsigned int offset = (unsigned int) *((int*)((long long int)header + 10));\n\tunsigned int size = (unsigned int) *((int*)((long long int)header + 2));\n\tfree(header);\n\n\tfile.seekg(0);\n\n\tchar* fullHeader = (char*) malloc(offset);\n\tfile.read(fullHeader, offset);//reads out the header from the file\n\n\tfile.seekg(size - offset - xSize*ySize*pixelSize/8);\n\n\tchar* footer = (char*) malloc(size - offset -xSize*ySize*pixelSize/8);//reads out the footer from the file\n\tfile.read(footer, size - offset - xSize*ySize*pixelSize/8);\n\n\tfile.close();//closes the file\n\n\tfile.open(compositeFilename, std::ios_base::out | std::ios_base::binary);//opens the fil for writing\n\n\tfile.write(fullHeader, offset);//writes the header to the file\n\tif(file.bad()){\n\t\tprintf(\"Something went wrong with writing composite file header\\n\");\n\t}\n\n\tfile.write(charValues, pixelVector.size());//writes the data to the file\n\tif(file.bad()){\n\t\tprintf(\"Something went wrong with writing composite file data\\n\");\n\t}\n\n\tfile.write(footer, size - offset -xSize*ySize*pixelSize/8);//writes the footer to the file\n\tif(file.bad()){\n\t\tprintf(\"Something went wrong with writing composite file footer\\n\");\n\t}\n\n\tfile.close();\n\n\tfree(charValues);\n\tfree(fullHeader);\n\tfree(footer);\n\n\tfor(unsigned int i = 0; i<pixelVector.size(); i++){//calculates the average and stdDev of the pixels\n\t\taverage += pixelVector[i];\n\t\tstdDev += pixelVector[i] * pixelVector[i];\n\t}\n\taverage = average/pixelVector.size();\n\tstdDev = sqrt(stdDev/pixelVector.size() - average*average);\n\n\tdouble noiseAverage = 0;\n\tdouble noiseStdDev = 0;\n\tint noiseCount = 0;\n\n\tfor(unsigned int i = 0; i < pixelVector.size(); i++){//calculates the average and stdDev of only the non zero pixels\n\t\tif(abs(pixelVector[i] - average) > stdDev){\n\t\t\tnoiseAverage += pixelVector[i];\n\t\t\tnoiseStdDev += pixelVector[i] * pixelVector[i];\n\t\t\tnoiseCount ++;\n\t\t}\n\t}\n\n\tnoiseAverage /= noiseCount;\n\tnoiseStdDev = sqrt(noiseStdDev/noiseCount - noiseAverage*noiseAverage);\n\t\n\tstd::vector<WORD> badPixels;\n\tbadPixels.push_back(0);\n\tWORD badCount = 0;\n\n\tfor(unsigned int i = 0; i<pixelVector.size(); i++){\n\t\tif((abs(pixelVector[i] - /*noiseA*/ average) > 50* /*noiseS*/ stdDev) /*&&(abs(pixelVector[i] - average) > stdDev)*/){\n\t\t\tbadCount ++;//increments the count of bad pixels\n\n\t\t\tbadPixels.push_back(i%xSize);//puts the x coordinate in the array\n\t\t\tbadPixels.push_back(i/xSize);//puts the y coordinate in the array\n\t\t\t\n\t\t\tprintf(\"Bad pixel found at x = %d, y = %d\\n\", i%xSize, i/xSize);\n\t\t}\n\t}\n\tprintf(\"Found %d bad pixels.\\n\", badCount);\n\tbadPixels[0] = badCount;\n\tWORD* returnValue =(WORD *) malloc(badPixels.size()*sizeof(WORD));\n\n\tfor(unsigned int i =0; i<badPixels.size(); i++){\n\t\t*(WORD*)((unsigned long long int)returnValue + (i)*sizeof(WORD)) = badPixels[i];\n\t}\n\treturn returnValue;//returns the array of bad pixels so that they can be corrected for\n}\n\nstd::vector<double> PixelFixer::detectWeirdPixels(std::vector<double> data, char* filename, int weight){\n\n\tstd::fstream file = std::fstream(filename, std::ios_base::in | std::ios_base::binary);\n\tif(!file.is_open()){\n\t\tprintf(\"File was not opened in detectWeirdPixels\\n\");\n\t}\n\t\n\tchar* header = (char* ) malloc(14);//ignores the header file\n\tfile.read(header, 14);\n\tint offset = (int) *((int*)((long long int)header + 10));\n\tfree(header);\n\n\tfile.ignore(offset - 14);\n\n\tchar* pixels = (char*)malloc(xSize*ySize*pixelSize/8);\n\tfile.read(pixels, xSize*ySize*pixelSize/8);\n\tfile.close();\n\n\tdouble average = 0;\n\tdouble stdDev = 0;\n\n\tstd::vector<int> tempVector;\n\ttempVector.reserve(xSize*ySize);\n\tunsigned int temp;\n\n\tfor(int i =0; i<(xSize*ySize*pixelSize/8);){//goes through each pixel \n\t\ttemp = 0;\n\t\tfor(int j = 0; j<pixelSize/8; j++){\n\t\t\ttemp += (*((unsigned char*)(unsigned long long int)pixels + i)) * (int)pow((double)2, pixelSize/8 - j - 1);\n\t\t\ti++;\n\t\t}\n\t\ttempVector.push_back(temp);\n\t\taverage += temp;\n\t}\n\n\taverage = average/(xSize*ySize);\n\tfree(pixels);\n\n\tstd::vector<double> returnValue;\n\treturnValue.resize(xSize*ySize);\n\n\tfor(int i = 0; i < (xSize * ySize); i++){\n\t\treturnValue[i] = data[i] + abs(tempVector[i] - average)/weight * 350;//adds each \"badness\" value in turn to the old vector of badness\n\t}\n\treturn returnValue;//then returns it\n}" }, { "alpha_fraction": 0.8279569745063782, "alphanum_fraction": 0.8279569745063782, "avg_line_length": 54.599998474121094, "blob_id": "0c13ff42f4b9105b0865706ea998b459413d7eac", "content_id": "d13e8682c8644bcdec90e3be8c48d06a3a43fd52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 279, "license_type": "no_license", "max_line_length": 87, "num_lines": 5, "path": "/test_programs/README.md", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "This directory contains any/all test programs that are used to verify functionality of \ncomponents on the BLASTPol system but are not used in flight.\n\nThe programs in this direction should reference libraries in the main BLAST system but\nnot implement functionality themselves.\n\n" }, { "alpha_fraction": 0.42550647258758545, "alphanum_fraction": 0.4419111907482147, "avg_line_length": 31.776689529418945, "blob_id": "56e4f29ff53af5ee17b7e87dd5c1bab55b254fb4", "content_id": "15d1a732f97907e3a7e7fdd845f23efc99549a0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 33466, "license_type": "no_license", "max_line_length": 120, "num_lines": 1021, "path": "/stars/code/solving/finding_new/background.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * background.cpp\n * Based on sextractor (C) 1993-2011 Emmanuel Bertin -- IAP/CNRS/UPMC\n */\n\n#include\t<math.h>\n#include\t<stdio.h>\n#include\t<stdlib.h>\n#include\t<string.h>\n\n#include\t\"back.h\"\n#include\t\"field.h\"\n\n\nvoid makeback(picstruct *field)\n{\n backstruct *backmesh, *wbackmesh, *bm, *wbm;\n float *buf, *wbuf, *buft, *wbuft;\n OFF_T fcurpos, wfcurpos, wfcurpos2, fcurpos2, bufshift, jumpsize;\n size_t bufsize, bufsize2, size, meshsize;\n int i, j, k, m, n, step, nlines, w, bw, bh, nx, ny, nb, lflag, nr;\n float *ratio, *ratiop, *weight, *sigma, sratio, sigfac;\n\n w = field->width;\n bw = field->backw;\n bh = field->backh;\n nx = field->nbackx;\n ny = field->nbacky;\n nb = field->nback;\n\n NFPRINTF(OUTPUT, \"Setting up background maps\");\n\n /* Decide if it is worth displaying progress each 16 lines */\n\n lflag = (field->width * field->backh >= (size_t)65536);\n\n /* Allocate a correct amount of memory to store pixels */\n\n bufsize = (OFF_T)w * bh;\n meshsize = (size_t)bufsize;\n nlines = 0;\n if (bufsize > (size_t)BACK_BUFSIZE) {\n nlines = BACK_BUFSIZE / w;\n step = (field->backh - 1) / nlines + 1;\n bufsize = (size_t)(nlines = field->backh / step) * w;\n bufshift = (step / 2) * (OFF_T)w;\n jumpsize = (step - 1) * (OFF_T)w;\n }\n else bufshift = jumpsize = 0; /* to avoid gcc -Wall warnings */\n\n /* Allocate some memory */\n QMALLOC(backmesh, backstruct, nx); /* background information */\n QMALLOC(buf, float, bufsize); /* pixel buffer */\n free(field->back);\n QMALLOC(field->back, float, nb); /* background map */\n free(field->backline);\n QMALLOC(field->backline, float, w); /* current background line */\n free(field->sigma);\n QMALLOC(field->sigma, float, nb); /* sigma map */\n\n wbackmesh = NULL;\n wbuf = NULL;\n\n /* Loop over the data packets */\n\n for (j = 0; j < ny; j++) {\n if (lflag && j)\n NPRINTF(OUTPUT, \"\\33[1M> Setting up background map at line:%5d\\n\\33[1A\", j * bh);\n if (!nlines) {\n /*---- The image is small enough so that we can make exhaustive stats */\n if (j == ny - 1 && field->npix % bufsize) bufsize = field->npix % bufsize;\n read_body(field->tab, buf, bufsize);\n\n /*---- Build the histograms */\n backstat(backmesh, wbackmesh, buf, wbuf, bufsize, nx, w, bw, 0.0);\n bm = backmesh;\n for (m = nx; m--; bm++)\n if (bm->mean <= -BIG)\n bm->histo = NULL;\n else\n QCALLOC(bm->histo, int, bm->nlevels);\n\n backhisto(backmesh, wbackmesh, buf, wbuf, bufsize, nx, w, bw, 0.0);\n }\n else {\n /*---- Image size too big, we have to skip a few data !*/\n QFTELL(field->file, fcurpos2, field->filename);\n if (j == ny - 1 && (n = field->height % field->backh)) {\n meshsize = n * (size_t)w;\n nlines = BACK_BUFSIZE / w;\n step = (n - 1) / nlines + 1;\n bufsize = (nlines = n / step) * (size_t)w;\n bufshift = (step / 2) * (OFF_T)w;\n jumpsize = (step - 1) * (OFF_T)w;\n free(buf);\n QMALLOC(buf, float, bufsize); /* pixel buffer */\n }\n\n /*---- Read and skip, read and skip, etc... */\n QFSEEK(field->file, bufshift*(OFF_T)field->bytepix, SEEK_CUR, field->filename);\n buft = buf;\n for (i = nlines; i--; buft += w) {\n read_body(field->tab, buft, w);\n if (i)\n QFSEEK(field->file, jumpsize*(OFF_T)field->bytepix, SEEK_CUR, field->filename);\n }\n\n backstat(backmesh, wbackmesh, buf, wbuf, bufsize, nx, w, bw, 0.0);\n QFSEEK(field->file, fcurpos2, SEEK_SET, field->filename);\n bm = backmesh;\n for (m = nx; m--; bm++)\n if (bm->mean <= -BIG)\n bm->histo = NULL;\n else\n QCALLOC(bm->histo, int, bm->nlevels);\n /*---- Build (progressively this time) the histograms */\n for (size = meshsize, bufsize2 = bufsize; size > 0; size -= bufsize2) {\n if (bufsize2 > size) bufsize2 = size;\n read_body(field->tab, buf, bufsize2);\n backhisto(backmesh, wbackmesh, buf, wbuf, bufsize2, nx, w, bw, 0.0);\n }\n }\n\n /*-- Compute background statistics from the histograms */\n bm = backmesh;\n for (m = 0; m < nx; m++, bm++) {\n k = m + nx * j;\n backguess(bm, field->back + k, field->sigma + k);\n free(bm->histo);\n }\n }\n\n /* Free memory */\n free(buf);\n free(backmesh);\n\n /* Go back to the original position */\n QFSEEK(field->file, fcurpos, SEEK_SET, field->filename);\n\n /* Median-filter and check suitability of the background map */\n NFPRINTF(OUTPUT, \"Filtering background map(s)\");\n filterback(field);\n\n /* Compute 2nd derivatives along the y-direction */\n NFPRINTF(OUTPUT, \"Computing background d-map\");\n free(field->dback);\n field->dback = makebackspline(field, field->back);\n NFPRINTF(OUTPUT, \"Computing background-noise d-map\");\n free(field->dsigma);\n field->dsigma = makebackspline(field, field->sigma);\n /* If asked for, force the backmean parameter to the supplied value */\n if (field->back_type == BACK_ABSOLUTE) field->backmean = (float)prefs.back_val[\n (field->flags & DETECT_FIELD) ? 0 : 1];\n\n /* Set detection/measurement threshold */\n if (prefs.ndthresh > 1) {\n double dval;\n\n if (fabs(dval = prefs.dthresh[0] - prefs.dthresh[1]) > 70.0) error(\n EXIT_FAILURE, \"*Error*: I cannot deal with such extreme thresholds!\", \"\");\n\n field->dthresh = field->pixscale * field->pixscale * pow(10.0, -0.4 * dval);\n }\n else if (prefs.thresh_type[0] == THRESH_ABSOLUTE)\n field->dthresh = prefs.dthresh[0];\n else field->dthresh = prefs.dthresh[0] * field->backsig;\n if (prefs.nthresh > 1) {\n double dval;\n\n if (fabs(dval = prefs.thresh[0] - prefs.thresh[1]) > 70.0) error(\n EXIT_FAILURE, \"*Error*: I cannot deal with such extreme thresholds!\", \"\");\n\n field->thresh = field->pixscale * field->pixscale * pow(10.0, -0.4 * dval);\n }\n else if (prefs.thresh_type[1] == THRESH_ABSOLUTE)\n field->thresh = prefs.thresh[0];\n else field->thresh = prefs.thresh[0] * field->backsig;\n\n#ifdef\tQUALITY_CHECK\n printf(\"%-10g %-10g %-10g\\n\", field->backmean, field->backsig,\n (field->flags & DETECT_FIELD) ? field->dthresh : field->thresh);\n#endif\n if (field->dthresh <= 0.0 || field->thresh <= 0.0) error(EXIT_FAILURE,\n \"*Error*: I cannot deal with zero or negative thresholds!\",\n \"\");\n\n if (prefs.detect_type == PHOTO && field->backmean + 3 * field->backsig > 50 * field->ngamma) error(\n EXIT_FAILURE, \"*Error*: The density range of this image is too large for \", \"PHOTO mode\");\n\n return;\n}\n\n/******************************** backstat **********************************/\n/*\nCompute robust statistical estimators in a row of meshes.\n*/\nvoid backstat(backstruct *backmesh, backstruct *wbackmesh, float *buf, float *wbuf, size_t bufsize, int n, int w,\n int bw, float wthresh)\n\n{\n backstruct *bm, *wbm;\n double pix, wpix, sig, mean, wmean, sigma, wsigma, step;\n float *buft, *wbuft, lcut, wlcut, hcut, whcut;\n int m, h, x, y, offset;\n\n h = bufsize / w;\n bm = backmesh;\n wbm = wbackmesh;\n offset = w - bw;\n step = sqrt(2 / PI) * QUANTIF_NSIGMA / QUANTIF_AMIN;\n wmean = wsigma = wlcut = whcut = 0.0; /* to avoid gcc -Wall warnings */\n for (m = n; m--; bm++, buf += bw) {\n int npix = 0;\n int wnpix;\n int lastbite;\n if (!m && (lastbite = w % bw)) {\n bw = lastbite;\n offset = w - bw;\n }\n mean = sigma = 0.0;\n buft = buf;\n /*-- We separate the weighted case at this level to avoid penalty in CPU */\n if (wbackmesh) {\n wmean = wsigma = 0.0;\n wbuft = wbuf;\n for (y = h; y--; buft += offset, wbuft += offset)\n for (x = bw; x--;) {\n pix = *(buft++);\n if ((wpix = *(wbuft++)) < wthresh && pix > -BIG) {\n wmean += wpix;\n wsigma += wpix * wpix;\n mean += pix;\n sigma += pix * pix;\n npix++;\n }\n }\n }\n else for (y = h; y--; buft += offset)\n for (x = bw; x--;)\n if ((pix = *(buft++)) > -BIG) {\n mean += pix;\n sigma += pix * pix;\n npix++;\n }\n /*-- If not enough valid pixels, discard this mesh */\n if ((float)npix < (float)(bw * h * BACK_MINGOODFRAC)) {\n bm->mean = bm->sigma = -BIG;\n if (wbackmesh) {\n wbm->mean = wbm->sigma = -BIG;\n wbm++;\n wbuf += bw;\n }\n continue;\n }\n if (wbackmesh) {\n wmean /= (double)npix;\n wsigma = (sig = wsigma / npix - wmean * wmean) > 0.0 ? sqrt(sig) : 0.0;\n wlcut = wbm->lcut = (float)(wmean - 2.0 * wsigma);\n whcut = wbm->hcut = (float)(wmean + 2.0 * wsigma);\n }\n mean /= (double)npix;\n sigma = (sig = sigma / npix - mean * mean) > 0.0 ? sqrt(sig) : 0.0;\n lcut = bm->lcut = (float)(mean - 2.0 * sigma);\n hcut = bm->hcut = (float)(mean + 2.0 * sigma);\n mean = sigma = 0.0;\n npix = wnpix = 0;\n buft = buf;\n if (wbackmesh) {\n wmean = wsigma = 0.0;\n wbuft = wbuf;\n for (y = h; y--; buft += offset, wbuft += offset)\n for (x = bw; x--;) {\n pix = *(buft++);\n if ((wpix = *(wbuft++)) < wthresh && pix <= hcut && pix >= lcut) {\n mean += pix;\n sigma += pix * pix;\n npix++;\n if (wpix <= whcut && wpix >= wlcut) {\n wmean += wpix;\n wsigma += wpix * wpix;\n wnpix++;\n }\n }\n }\n }\n else for (y = h; y--; buft += offset)\n for (x = bw; x--;) {\n pix = *(buft++);\n if (pix <= hcut && pix >= lcut) {\n mean += pix;\n sigma += pix * pix;\n npix++;\n }\n }\n\n bm->npix = npix;\n mean /= (double)npix;\n sig = sigma / npix - mean * mean;\n sigma = sig > 0.0 ? sqrt(sig) : 0.0;\n bm->mean = mean;\n bm->sigma = sigma;\n if ((bm->nlevels = (int)(step * npix + 1)) > QUANTIF_NMAXLEVELS) bm->nlevels = QUANTIF_NMAXLEVELS;\n bm->qscale = sigma > 0.0 ? 2 * QUANTIF_NSIGMA * sigma / bm->nlevels : 1.0;\n bm->qzero = mean - QUANTIF_NSIGMA * sigma;\n if (wbackmesh) {\n wbm->npix = wnpix;\n wmean /= (double)wnpix;\n sig = wsigma / wnpix - wmean * wmean;\n wsigma = sig > 0.0 ? sqrt(sig) : 0.0;\n wbm->mean = wmean;\n wbm->sigma = wsigma;\n if ((wbm->nlevels = (int)(step * wnpix + 1)) > QUANTIF_NMAXLEVELS) wbm->nlevels = QUANTIF_NMAXLEVELS;\n wbm->qscale = wsigma > 0.0 ? 2 * QUANTIF_NSIGMA * wsigma / wbm->nlevels : 1.0;\n wbm->qzero = wmean - QUANTIF_NSIGMA * wsigma;\n wbm++;\n wbuf += bw;\n }\n }\n\n return;\n}\n\n/******************************** backhisto *********************************/\n/*\nCompute robust statistical estimators in a row of meshes.\n*/\nvoid backhisto(backstruct *backmesh, backstruct *wbackmesh, float *buf, float *wbuf, size_t bufsize, int n, int w,\n int bw, float wthresh)\n{\n backstruct *bm, *wbm;\n float *buft, *wbuft;\n float qscale, wqscale, cste, wcste, wpix;\n int *histo, *whisto;\n int h, x, y, nlevels, wnlevels, lastbite, offset, bin;\n\n h = bufsize / w;\n bm = backmesh;\n wbm = wbackmesh;\n offset = w - bw;\n for (int m = 0; m++ < n; bm++, buf += bw) {\n if (m == n && (lastbite = w % bw)) {\n bw = lastbite;\n offset = w - bw;\n }\n /*-- Skip bad meshes */\n if (bm->mean <= -BIG) {\n if (wbackmesh) {\n wbm++;\n wbuf += bw;\n }\n continue;\n }\n nlevels = bm->nlevels;\n histo = bm->histo;\n qscale = bm->qscale;\n cste = 0.499999 - bm->qzero / qscale;\n buft = buf;\n if (wbackmesh) {\n wnlevels = wbm->nlevels;\n whisto = wbm->histo;\n wqscale = wbm->qscale;\n wcste = 0.499999 - wbm->qzero / wqscale;\n wbuft = wbuf;\n for (y = h; y--; buft += offset, wbuft += offset)\n for (x = bw; x--;) {\n bin = (int)(*(buft++) / qscale + cste);\n if ((wpix = *(wbuft++)) < wthresh && bin < nlevels && bin >= 0) {\n (*(histo + bin))++;\n bin = (int)(wpix / wqscale + wcste);\n if (bin >= 0 && bin < wnlevels) (*(whisto + bin))++;\n }\n }\n wbm++;\n wbuf += bw;\n }\n else for (y = h; y--; buft += offset)\n for (x = bw; x--;) {\n bin = (int)(*(buft++) / qscale + cste);\n if (bin >= 0 && bin < nlevels) (*(histo + bin))++;\n }\n }\n\n return;\n}\n\n/******************************* backguess **********************************/\n/*\nEstimate the background from a histogram;\n*/\nfloat backguess(backstruct *bkg, float *mean, float *sigma)\n\n#define\tEPS\t(1e-4)\t/* a small number */\n\n{\n int *histo, *hilow, *hihigh, *histot;\n double ftemp, mea, sig, sig1, med, dpix;\n int lcut, hcut, nlevelsm1, pix;\n\n /* Leave here if the mesh is already classified as `bad' */\n if (bkg->mean <= -BIG) {\n *mean = *sigma = -BIG;\n return -BIG;\n }\n\n histo = bkg->histo;\n hcut = nlevelsm1 = bkg->nlevels - 1;\n lcut = 0;\n\n sig = 10.0 * nlevelsm1;\n sig1 = 1.0;\n mea = med = bkg->mean;\n for (int n = 100; n-- && (sig >= 0.1) && (fabs(sig / sig1 - 1.0) > EPS);) {\n unsigned long lowsum, highsum, sum;\n sig1 = sig;\n sum = mea = sig = 0.0;\n lowsum = highsum = 0;\n histot = hilow = histo + lcut;\n hihigh = histo + hcut;\n for (int i = lcut; i <= hcut; i++) {\n if (lowsum < highsum)\n lowsum += *(hilow++);\n else highsum += *(hihigh--);\n sum += (pix = *(histot++));\n mea += (dpix = (double)(pix * i));\n sig += dpix * i;\n }\n\n if (hihigh >= histo) {\n med =\n ((hihigh - histo) + 0.5\n + ((double)highsum - lowsum) / (2.0 * (*hilow > *hihigh ? *hilow : *hihigh)));\n }\n else {\n med = 0.0;\n }\n\n if (sum) {\n mea /= (double)sum;\n sig = sig / sum - mea * mea;\n }\n sig = sig > 0.0 ? sqrt(sig) : 0.0;\n lcut = (ftemp = med - 3.0 * sig) > 0.0 ? (int)(ftemp > 0.0 ? ftemp + 0.5 : ftemp - 0.5) : 0;\n hcut = (ftemp = med + 3.0 * sig) < nlevelsm1 ? (int)(ftemp > 0.0 ? ftemp + 0.5 : ftemp - 0.5) : nlevelsm1;\n }\n\n if (fabs(sig) > 0.0 && fabs((mea - med) / sig) < 0.3) {\n *mean = bkg->qzero + (2.5 * med - 1.5 * mea) * bkg->qscale;\n }\n else {\n *mean = bkg->qzero + mea * bkg->qscale;\n }\n\n *sigma = sig * bkg->qscale;\n\n return *mean;\n}\n\n/******************************* filterback *********************************/\n/*\nMedian filtering of the background map to remove the contribution from bright\nsources.\n*/\nvoid filterback(picstruct *field)\n\n{\n float *back, *sigma, *back2, *sigma2, *bmask, *smask, *sigmat, d2, d2min, fthresh, med, val, sval;\n int i, j, px, py, np, nx, ny, npx, npx2, npy, npy2, dpx, dpy, x, y, nmin;\n\n fthresh = prefs.backfthresh;\n nx = field->nbackx;\n ny = field->nbacky;\n np = field->nback;\n npx = field->nbackfx / 2;\n npy = field->nbackfy / 2;\n npy *= nx;\n\n QMALLOC(bmask, float, (2 * npx + 1) * (2 * npy + 1));\n QMALLOC(smask, float, (2 * npx + 1) * (2 * npy + 1));\n QMALLOC(back2, float, np);\n QMALLOC(sigma2, float, np);\n\n back = field->back;\n sigma = field->sigma;\n val = sval = 0.0; /* to avoid gcc -Wall warnings */\n\n /* Look for `bad' meshes and interpolate them if necessary */\n for (i = 0, py = 0; py < ny; py++)\n for (px = 0; px < nx; px++, i++)\n if ((back2[i] = back[i]) <= -BIG) {\n /*------ Seek the closest valid mesh */\n d2min = BIG;\n nmin = 0.0;\n for (j = 0, y = 0; y < ny; y++)\n for (x = 0; x < nx; x++, j++)\n if (back[j] > -BIG) {\n d2 = (float)(x - px) * (x - px) + (y - py) * (y - py);\n if (d2 < d2min) {\n val = back[j];\n sval = sigma[j];\n nmin = 1;\n d2min = d2;\n }\n else if (d2 == d2min) {\n val += back[j];\n sval += sigma[j];\n nmin++;\n }\n }\n back2[i] = nmin ? val / nmin : 0.0;\n sigma[i] = nmin ? sval / nmin : 1.0;\n }\n memcpy(back, back2, (size_t)np * sizeof(float));\n\n /* Do the actual filtering */\n for (py = 0; py < np; py += nx) {\n npy2 = np - py - nx;\n if (npy2 > npy) npy2 = npy;\n if (npy2 > py) npy2 = py;\n for (px = 0; px < nx; px++) {\n npx2 = nx - px - 1;\n if (npx2 > npx) npx2 = npx;\n if (npx2 > px) npx2 = px;\n i = 0;\n for (dpy = -npy2; dpy <= npy2; dpy += nx) {\n y = py + dpy;\n for (dpx = -npx2; dpx <= npx2; dpx++) {\n x = px + dpx;\n bmask[i] = back[x + y];\n smask[i++] = sigma[x + y];\n }\n }\n if (fabs((med = fqmedian(bmask, i)) - back[px + py]) >= fthresh) {\n back2[px + py] = med;\n sigma2[px + py] = fqmedian(smask, i);\n }\n else {\n back2[px + py] = back[px + py];\n sigma2[px + py] = sigma[px + py];\n }\n }\n }\n\n free(bmask);\n free(smask);\n memcpy(back, back2, np * sizeof(float));\n field->backmean = fqmedian(back2, np);\n free(back2);\n memcpy(sigma, sigma2, np * sizeof(float));\n field->backsig = fqmedian(sigma2, np);\n\n if (field->backsig <= 0.0) {\n sigmat = sigma2 + np;\n for (i = np; i-- && *(--sigmat) > 0.0;)\n ;\n if (i >= 0 && i < (np - 1))\n field->backsig = fqmedian(sigmat + 1, np - 1 - i);\n else {\n if (field->flags & (DETECT_FIELD | MEASURE_FIELD)) warning(\"Image contains mainly constant data; \",\n \"I'll try to cope with that...\");\n field->backsig = 1.0;\n }\n }\n\n free(sigma2);\n\n return;\n}\n\n/******************************** localback *********************************/\n/*\nCompute Local background if possible.\n*/\nfloat localback(picstruct *field, objstruct *obj)\n\n{\n static backstruct backmesh;\n int bxmin, bxmax, bymin, bymax, ixmin, ixmax, iymin, iymax, bxnml, bynml, oxsize, oysize, npix, i, x, y, w, sh, pbs;\n float bkg = 0.0;\n float bqs, cste;\n float *backpix, *strip, *st, pix;\n\n strip = field->strip;\n w = field->width;\n sh = field->stripheight;\n pbs = prefs.pback_size;\n\n /* Estimate background in a 'rectangular annulus' around the object */\n oxsize = obj->xmax - obj->xmin + 1;\n oysize = obj->ymax - obj->ymin + 1;\n bxnml = oxsize < w / 2 ? oxsize / 4 : (w - oxsize) / 4;\n bynml = oysize < field->height / 2 ? oysize / 4 : (field->height - oysize) / 4;\n bxmin = (ixmin = obj->xmin - bxnml) - pbs;\n bxmax = (ixmax = obj->xmax + 1 + bxnml) + pbs;\n bymin = (iymin = obj->ymin - bynml) - pbs;\n bymax = (iymax = obj->ymax + 1 + bynml) + pbs;\n\n if (bymin >= field->ymin && bymax < field->ymax && bxmin >= 0 && bxmax < w) {\n float *bp;\n npix = (bxmax - bxmin) * (bymax - bymin) - (ixmax - ixmin) * (iymax - iymin);\n\n QMALLOC(backpix, float, npix);\n bp = backpix;\n\n /*--store all the pixels*/\n npix = 0;\n for (y = bymin; y < bymax; y++) {\n st = strip + (y % sh) * w + bxmin;\n for (x = pbs; x--;)\n if ((pix = *(st++)) > -BIG) {\n *(bp++) = pix;\n npix++;\n }\n st += ixmax - ixmin;\n for (x = pbs; x--;)\n if ((pix = *(st++)) > -BIG) {\n *(bp++) = pix;\n npix++;\n }\n }\n\n for (y = bymin; y < iymin; y++) {\n st = strip + (y % sh) * w + ixmin;\n for (x = ixmax - ixmin; x--;)\n if ((pix = *(st++)) > -BIG) {\n *(bp++) = pix;\n npix++;\n }\n }\n for (y = iymax; y < bymax; y++) {\n st = strip + (y % sh) * w + ixmin;\n for (x = ixmax - ixmin; x--;)\n if ((pix = *(st++)) > -BIG) {\n *(bp++) = pix;\n npix++;\n }\n }\n\n if (npix) {\n int *back_mesh_histogram;\n int bmn;\n\n backstat(&backmesh, NULL, backpix, NULL, npix, 1, 1, 1, 0.0);\n QCALLOC(backmesh.histo, int, backmesh.nlevels);\n back_mesh_histogram = backmesh.histo;\n bmn = backmesh.nlevels;\n cste = 0.499999 - backmesh.qzero / (bqs = backmesh.qscale);\n bp = backpix;\n for (i = npix; i--;) {\n int bin;\n bin = (int)(*(bp++) / bqs + cste);\n if (bin >= 0 && bin < bmn) (*(back_mesh_histogram + bin))++;\n }\n backguess(&backmesh, &bkg, &obj->sigbkg);\n obj->bkg += (obj->dbkg = bkg);\n free(backmesh.histo);\n }\n else {\n obj->dbkg = 0.0;\n obj->sigbkg = field->backsig;\n }\n free(backpix);\n }\n else {\n obj->dbkg = bkg = 0.0;\n obj->sigbkg = field->backsig;\n }\n\n return bkg;\n}\n\n/************************************ back ***********************************/\n/*\nreturn background at position x,y (linear interpolation between background\nmap vertices).\n*/\nfloat back(picstruct *field, int x, int y)\n\n{\n int nx, ny, xl, yl, pos;\n double dx, dy, cdx;\n float *b, b0, b1, b2, b3;\n\n b = field->back;\n nx = field->nbackx;\n ny = field->nbacky;\n\n dx = (double)x / field->backw - 0.5;\n dy = (double)y / field->backh - 0.5;\n dx -= (xl = (int)dx);\n dy -= (yl = (int)dy);\n\n if (xl < 0) {\n xl = 0;\n dx -= 1.0;\n }\n else if (xl >= nx - 1) {\n xl = nx < 2 ? 0 : nx - 2;\n dx += 1.0;\n }\n\n if (yl < 0) {\n yl = 0;\n dy -= 1.0;\n }\n else if (yl >= ny - 1) {\n yl = ny < 2 ? 0 : ny - 2;\n dy += 1.0;\n }\n\n pos = yl * nx + xl;\n cdx = 1 - dx;\n\n b0 = *(b += pos); /* consider when nbackx or nbacky = 1 */\n b1 = nx < 2 ? b0 : *(++b);\n b2 = ny < 2 ? *b : *(b += nx);\n b3 = nx < 2 ? *b : *(--b);\n\n return (float)((1 - dy) * (cdx * b0 + dx * b1) + dy * (dx * b2 + cdx * b3));\n}\n\n/******************************* makebackspline ******************************/\n/*\nPre-compute 2nd derivatives along the y direction at background nodes.\n*/\nfloat *makebackspline(picstruct *field, float *map)\n\n{\n int x, y, nbx, nby, nbym1;\n float *dmap, *dmapt, *mapt, *u, temp;\n\n nbx = field->nbackx;\n nby = field->nbacky;\n nbym1 = nby - 1;\n QMALLOC(dmap, float, field->nback);\n for (x = 0; x < nbx; x++) {\n mapt = map + x;\n dmapt = dmap + x;\n if (nby > 1) {\n QMALLOC(u, float, nbym1); /* temporary array */\n *dmapt = *u = 0.0; /* \"natural\" lower boundary condition */\n mapt += nbx;\n for (y = 1; y < nbym1; y++, mapt += nbx) {\n temp = -1 / (*dmapt + 4);\n *(dmapt += nbx) = temp;\n temp *= *(u++) - 6 * (*(mapt + nbx) + *(mapt - nbx) - 2 * *mapt);\n *u = temp;\n }\n *(dmapt += nbx) = 0.0; /* \"natural\" upper boundary condition */\n for (y = nby - 2; y--;) {\n temp = *dmapt;\n dmapt -= nbx;\n *dmapt = (*dmapt * temp + *(u--)) / 6.0;\n }\n free(u);\n }\n else *dmapt = 0.0;\n }\n\n return dmap;\n}\n\n/******************************* subbackline *********************************/\n/*\nInterpolate background at line y (bicubic spline interpolation between\nbackground map vertices) and subtract it from the current line.\n*/\nvoid subbackline(picstruct *field, int y, float *line)\n\n{\n int i, j, x, yl, nbx, nbxm1, nby, nx, width, ystep, changepoint;\n float dx, dx0, dy, dy3, cdx, cdy, cdy3, temp, xstep, *node, *nodep, *dnode, *blo, *bhi, *dblo, *dbhi, *u;\n float *backline, bval;\n\n width = field->width;\n backline = field->backline;\n\n if (field->back_type == BACK_ABSOLUTE) {\n /*-- In absolute background mode, just subtract a cste */\n bval = field->backmean;\n for (i = width; i--;)\n *(line++) -= ((*backline++) = bval);\n return;\n }\n\n nbx = field->nbackx;\n nbxm1 = nbx - 1;\n nby = field->nbacky;\n if (nby > 1) {\n dy = (float)y / field->backh - 0.5;\n dy -= (yl = (int)dy);\n if (yl < 0) {\n yl = 0;\n dy -= 1.0;\n }\n else if (yl >= nby - 1) {\n yl = nby < 2 ? 0 : nby - 2;\n dy += 1.0;\n }\n /*-- Interpolation along y for each node */\n cdy = 1 - dy;\n dy3 = (dy * dy * dy - dy);\n cdy3 = (cdy * cdy * cdy - cdy);\n ystep = nbx * yl;\n blo = field->back + ystep;\n bhi = blo + nbx;\n dblo = field->dback + ystep;\n dbhi = dblo + nbx;\n QMALLOC(node, float, nbx); /* Interpolated background */\n nodep = node;\n for (x = nbx; x--;)\n *(nodep++) = cdy * *(blo++) + dy * *(bhi++) + cdy3 * *(dblo++) + dy3 * *(dbhi++);\n\n /*-- Computation of 2nd derivatives along x */\n QMALLOC(dnode, float, nbx); /* 2nd derivative along x */\n if (nbx > 1) {\n QMALLOC(u, float, nbxm1); /* temporary array */\n *dnode = *u = 0.0; /* \"natural\" lower boundary condition */\n nodep = node + 1;\n for (x = nbxm1; --x; nodep++) {\n temp = -1 / (*(dnode++) + 4);\n *dnode = temp;\n temp *= *(u++) - 6 * (*(nodep + 1) + *(nodep - 1) - 2 * *nodep);\n *u = temp;\n }\n *(++dnode) = 0.0; /* \"natural\" upper boundary condition */\n for (x = nbx - 2; x--;) {\n temp = *(dnode--);\n *dnode = (*dnode * temp + *(u--)) / 6.0;\n }\n free(u);\n dnode--;\n }\n }\n else {\n /*-- No interpolation and no new 2nd derivatives needed along y */\n node = field->back;\n dnode = field->dback;\n }\n\n /*-- Interpolation along x */\n if (nbx > 1) {\n nx = field->backw;\n xstep = 1.0 / nx;\n changepoint = nx / 2;\n dx = (xstep - 1) / 2; /* dx of the first pixel in the row */\n dx0 = ((nx + 1) % 2) * xstep / 2; /* dx of the 1st pixel right to a bkgnd node */\n blo = node;\n bhi = node + 1;\n dblo = dnode;\n dbhi = dnode + 1;\n for (x = i = 0, j = width; j--; i++, dx += xstep) {\n if (i == changepoint && x > 0 && x < nbxm1) {\n blo++;\n bhi++;\n dblo++;\n dbhi++;\n dx = dx0;\n }\n cdx = 1 - dx;\n *(line++) -= (*(backline++) = (float)(cdx * (*blo + (cdx * cdx - 1) * *dblo)\n + dx * (*bhi + (dx * dx - 1) * *dbhi)));\n if (i == nx) {\n x++;\n i = 0;\n }\n }\n }\n else for (j = width; j--;)\n *(line++) -= (*(backline++) = (float)*node);\n\n if (nby > 1) {\n free(node);\n free(dnode);\n }\n\n return;\n}\n\n/******************************* backrmsline ********************************\nPROTO void backrmsline(picstruct *field, int y, float *line)\nPURPOSE Bicubic-spline interpolation of the background noise along the current\nscanline (y).\nINPUT Measurement or detection field pointer,\nCurrent line position.\nWhere to put the data.\nOUTPUT -.\nNOTES Most of the code is a copy of subbackline(), for optimization reasons.\nAUTHOR E. Bertin (IAP & Leiden & ESO)\nVERSION 02/02/98\n***/\nvoid backrmsline(picstruct *field, int y, float *line)\n\n{\n int i, j, x, yl, nbx, nbxm1, nby, nx, width, ystep, changepoint;\n float dx, dx0, dy, dy3, cdx, cdy, cdy3, temp, xstep, *node, *nodep, *dnode, *blo, *bhi, *dblo, *dbhi, *u;\n\n nbx = field->nbackx;\n nbxm1 = nbx - 1;\n nby = field->nbacky;\n if (nby > 1) {\n dy = (float)y / field->backh - 0.5;\n dy -= (yl = (int)dy);\n if (yl < 0) {\n yl = 0;\n dy -= 1.0;\n }\n else if (yl >= nby - 1) {\n yl = nby < 2 ? 0 : nby - 2;\n dy += 1.0;\n }\n /*-- Interpolation along y for each node */\n cdy = 1 - dy;\n dy3 = (dy * dy * dy - dy);\n cdy3 = (cdy * cdy * cdy - cdy);\n ystep = nbx * yl;\n blo = field->sigma + ystep;\n bhi = blo + nbx;\n dblo = field->dsigma + ystep;\n dbhi = dblo + nbx;\n QMALLOC(node, float, nbx); /* Interpolated background */\n nodep = node;\n for (x = nbx; x--;)\n *(nodep++) = cdy * *(blo++) + dy * *(bhi++) + cdy3 * *(dblo++) + dy3 * *(dbhi++);\n\n /*-- Computation of 2nd derivatives along x */\n QMALLOC(dnode, float, nbx); /* 2nd derivative along x */\n if (nbx > 1) {\n QMALLOC(u, float, nbxm1); /* temporary array */\n *dnode = *u = 0.0; /* \"natural\" lower boundary condition */\n nodep = node + 1;\n for (x = nbxm1; --x; nodep++) {\n temp = -1 / (*(dnode++) + 4);\n *dnode = temp;\n temp *= *(u++) - 6 * (*(nodep + 1) + *(nodep - 1) - 2 * *nodep);\n *u = temp;\n }\n *(++dnode) = 0.0; /* \"natural\" upper boundary condition */\n for (x = nbx - 2; x--;) {\n temp = *(dnode--);\n *dnode = (*dnode * temp + *(u--)) / 6.0;\n }\n free(u);\n dnode--;\n }\n }\n else {\n /*-- No interpolation and no new 2nd derivatives needed along y */\n node = field->sigma;\n dnode = field->dsigma;\n }\n\n /*-- Interpolation along x */\n width = field->width;\n if (nbx > 1) {\n nx = field->backw;\n xstep = 1.0 / nx;\n changepoint = nx / 2;\n dx = (xstep - 1) / 2; /* dx of the first pixel in the row */\n dx0 = ((nx + 1) % 2) * xstep / 2; /* dx of the 1st pixel right to a bkgnd node */\n blo = node;\n bhi = node + 1;\n dblo = dnode;\n dbhi = dnode + 1;\n for (x = i = 0, j = width; j--; i++, dx += xstep) {\n if (i == changepoint && x > 0 && x < nbxm1) {\n blo++;\n bhi++;\n dblo++;\n dbhi++;\n dx = dx0;\n }\n cdx = 1 - dx;\n *(line++) = (float)(cdx * (*blo + (cdx * cdx - 1) * *dblo) + dx * (*bhi + (dx * dx - 1) * *dbhi));\n if (i == nx) {\n x++;\n i = 0;\n }\n }\n }\n else for (j = width; j--;)\n *(line++) = (float)*node;\n\n if (nby > 1) {\n free(node);\n free(dnode);\n }\n\n return;\n}\n\n/********************************* copyback **********************************/\n/*\nCopy sub-structures related to background procedures (mainly freeing memory).\n*/\nvoid copyback(picstruct *infield, picstruct *outfield)\n\n{\n QMEMCPY(infield->back, outfield->back, float, infield->nback);\n QMEMCPY(infield->dback, outfield->dback, float, infield->nback);\n QMEMCPY(infield->sigma, outfield->sigma, float, infield->nback);\n QMEMCPY(infield->dsigma, outfield->dsigma, float, infield->nback);\n QMEMCPY(infield->backline, outfield->backline, float, infield->width);\n\n return;\n}\n\n/********************************* endback ***********************************/\n/*\nTerminate background procedures (mainly freeing memory).\n*/\nvoid endback(picstruct *field)\n\n{\n free(field->back);\n free(field->dback);\n free(field->sigma);\n free(field->dsigma);\n free(field->backline);\n\n return;\n}\n\n" }, { "alpha_fraction": 0.5919400453567505, "alphanum_fraction": 0.600648045539856, "avg_line_length": 24.458763122558594, "blob_id": "195a4d73e25cf3f832af9cc15c3665751f11779c", "content_id": "1396904404159888b6b808089e9a7eaea552c9dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4938, "license_type": "no_license", "max_line_length": 111, "num_lines": 194, "path": "/stars/code/imaging/badpix.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * Added by Krystle Sy to remove bad pixels.\n */\n\n#include \"badpix.h\"\n#include \"../../shared/image/raw.h\"\n#include \"../../tools/math.h\"\n#include \"../../parameters/manager.h\"\n#include \"../logger.h\"\n\n\nusing namespace Solving::Finding;\nusing namespace boost::filesystem;\nusing std::vector;\nusing std::string;\n\n#define shared_settings (*(Shared::Solving::settings.r))\n#define shared_blobs (*(Shared::Image::blobs_solver_for_main.w))\n\nBadpix::badpix(Parameters::Manager& params)\n{\n image_width = params.general.image_width;\n image_height = params.general.image_height;\n //map = map_in;\n //xpix = xpix_in;\n //ypix = ypix_in;\n //bits = bits_in;\n //platescale = platescale_in;\n //npix = xpix*ypix;\n //\n //// Blob list pointers initialized to 0\n //numblobs = 0;\n //maxblobs = 0;\n //\n //firstblob = NULL;\n //lastblob = NULL;\n //thisblob = NULL;\n //\n //// Set the gridsearch array to NULL to check at the end if allocated\n //searchgrid = NULL;\n //meangrid = NULL;\n //\n //// Map statistics defaults\n //mapmean=0;\n //sigma=1;\n //satval = 16383; // numerical value of a saturated pixel\n //satcol = new int[xpix]; // array contains # sat pixels each column\n //\n //gain=1;\n //readout_offset=0;\n //readout_noise=0;\n\n //// Defaults for search parameters\n //grid = 32; // pixels/side in coarse grid search\n //threshold = 5; // N sigma threshold criterion\n //disttol = 30*30; // distance^2 tolerance for adjacent sources\n //\n //badpixels = NULL;\n\n}\n\nBadpix::~badpix(void)\n{\n\t delete[] badpixels;\n}\n\nint Badpix::load_badpix(char *fname) {\n FILE *badfile;\n Blob *firstbad, *thisbad, *nextbad, *lastbad; // bad pixel list\n char thisline[81];\n int count; // Number of elements read from the current line\n int i, x, y; // coordinates of the bad pixel in this line\n \n \n badfile = housekeeping.load(system_complete(stars_dir + badpixlist).string());\n\n if( (badfile == NULL )\n return 0;\n \n // Read through file line-by-line reading in pixel coordinates.\n // Use the blob linked-list to dynamically add coordinates as we\n // read them in. At the end, put the array indices calculated from the\n // pixel coordinates into an array for quick access when we process\n // frames.\n \n numbadpix = 0; \n firstbad = NULL; \n \n //params.general.try_get(\"solver.blob_finder.badpixfilename\", string(\"E:\\stars\\settings\\badpixels_ISC.cam\"));\n\n while( fgets(thisline,80,badfile) != NULL ) {\n count = sscanf(thisline,\"%i %i\",&x, &y);\n if( count == 2 ) { // If we read in a coordinate pair\n numbadpix ++;\n thisbad = new blob((double)x, (double)(ypix - y - 1),0);\n \n if( firstbad == NULL ) { // If first bad pixel in the list\n firstbad = thisbad;\n } else { // adding on new bad pixel to list\n lastbad->setnextblob(thisbad);\n thisbad->setprevblob(lastbad);\n }\n \n lastbad = thisbad;\n }\n }\n \n fclose(badfile);\n \n // Now traverse (and delete) linked list, calculating pixel coordinates\n \n badpixels = new unsigned int[numbadpix];\n thisbad = firstbad; // start at the beginning of the list\n \n i = 0;\n \n //printf(\"badpixels: %i\\n\",numbadpix);\n while( thisbad != NULL ) {\n badpixels[i] = (unsigned int) thisbad->gety()*xpix + \n (unsigned int) thisbad->getx();\n \n i++;\n nextbad = thisbad->getnextblob(); // get next blob\n delete thisbad; // delete the current one\n thisbad = nextbad; // move along\n }\n \n logger.log(format(\"Opened bad pixel file: %s with %i bad pixels.\\n\"\n % fname % numbadpix));\n\n return 1;\n}\n\n\n\nvoid Badpix::fix_badpix(MAPTYPE val) {\n int i;\n \n if( badpixels != NULL ) \n for( i=0; i<(int)numbadpix; i++ ) { \n map[badpixels[i]] = val;\n }\n}\n\nvoid Badpix::calc_mapstat() {\n unsigned int i, j, count,index;\n \n // initialize variables\n \n mapmean = 0;\n count = 0;\n memset(satcol,0,image_width*sizeof(int));\n \n for( j=0; j<image_height; j++ ) { // j=row\n index = j*image_width; // inner loop columns to speed up addressing\n for( i=0; i<image_width; i++ ) {\n //printf(\"%i \",map[index]);\n \n if( map[index] > satval ) satcol[i]++; // if bad pixel\n else { // otherwise contributes to mean\n if( map[index] != satval ) { // pixel isn't bad\n mapmean += map[index];\n count ++;\n }\n }\n index++;\n }\n }\n \n if( count > 0 ) mapmean = mapmean / (double) count; // prevent / zero\n if( mapmean < 1 ) mapmean = 1; // prevent 0 means\n}\n\ndouble Badpix::get_mapmean() {\n if( mapmean == 0 ) calc_mapstat();\n return mapmean;\n}\n\nvoid Badpix::setnextblob( Blob *nextblob_in ) {\n nextblob = nextblob_in;\n}\n\n\nvoid Badpix::setprevblob( bloblist *prevblob_in ) {\n prevblob = prevblob_in;\n}\n\nBlob *blob::getnextblob() {\n return nextblob;\n}\n\nBlob *blob::getprevblob() {\n return prevblob;\n}" }, { "alpha_fraction": 0.666077733039856, "alphanum_fraction": 0.6766784191131592, "avg_line_length": 16.6875, "blob_id": "4f93f8dc518f04bea252c363a21fa336e3355644", "content_id": "d48753668b0993c8cb1aa93df0df8926c9acd228", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 567, "license_type": "no_license", "max_line_length": 73, "num_lines": 32, "path": "/stars/code/displaying/glhelper.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__GL_HELPER_H\n#define DISPLAYING__GL_HELPER_H\n\n#if defined(_MSC_VER)\n #include <windows.h>\n#endif\n#include \"GL/gl.h\"\n#include \"GL/glu.h\"\n\nnamespace Displaying\n{\n namespace GL\n {\n\ninline void Color4f(double r, double g, double b, double a)\n{\n glColor4f((GLfloat) r, (GLfloat) g, (GLfloat) b, (GLfloat) a);\n}\n\n\n }\n}\n\n\n#endif\n" }, { "alpha_fraction": 0.5497278571128845, "alphanum_fraction": 0.5809005498886108, "avg_line_length": 27.85714340209961, "blob_id": "c7bf2be06b4cd06f3fcc9da05343933e37b6ff39", "content_id": "e4da7286f91d86b4276626b1c37f553f61e039bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2022, "license_type": "no_license", "max_line_length": 122, "num_lines": 70, "path": "/stars/code/displaying/base_set.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"base_set.h\"\n#include \"blob.h\"\n\nusing namespace Displaying;\nusing std::vector;\n\nBaseSet::BaseSet(Solving::BaseSet base_set_): base_set(base_set_)\n{\n timer.start();\n aged = false;\n}\n\nvoid BaseSet::draw_lines(vector<Blob>& display_blobs, double progress, bool done, double global_brightness, int num_blobs)\n{\n double padding = 10.0;\n if (progress == 1.0 || done) {\n double brightness = 0.2;\n if (!aged) {\n double age = timer.time()+0.25;\n brightness = std::max(brightness, exp(-age/1.5));\n if (age > 3.0) {\n aged = true;\n }\n }\n glColor4d(0.0, 1.0, 0.5, brightness*global_brightness);\n }\n else {\n\t\tglColor4d(0.0, 1.0, 0.5, 1.0*global_brightness);\n timer.start();\n }\n glBegin(GL_LINES);\n double x0, y0, dx, dy, length, progress_short;\n int i, j;\n for (i=0; i<(num_blobs*(num_blobs-1)/2); i++) {\n j = (i+1)%num_blobs;\n x0 = display_blobs[base_set.ids[i]].x;\n y0 = display_blobs[base_set.ids[i]].y;\n dx = display_blobs[base_set.ids[j]].x - x0;\n dy = display_blobs[base_set.ids[j]].y - y0;\n\n length = sqrt(pow(dx, 2.0) + pow(dy, 2.0));\n progress_short = progress * (1.0 - 2.0*padding/length);\n x0 += dx/length*padding;\n y0 += dy/length*padding;\n\n glVertex2d(x0, y0);\n glVertex2d(x0+dx*progress_short, y0+dy*progress_short);\n\n }\n glEnd();\n}\n\nvoid BaseSet::draw(vector<Blob>& display_blobs, double progress, bool done, double global_brightness)\n{\n int num_blobs = 0;\n if (base_set.type == Solving::BaseSet::triplet) {\n num_blobs = 3;\n }\n if (base_set.type == Solving::BaseSet::pair) {\n num_blobs = 2;\n }\n draw_lines(display_blobs, progress, done, global_brightness, num_blobs);\n\n}\n\n" }, { "alpha_fraction": 0.6744444370269775, "alphanum_fraction": 0.6822222471237183, "avg_line_length": 18.424461364746094, "blob_id": "8922094ac447fd42d248a69f9eee5a24de53ce5c", "content_id": "bf17e1d666f25891a89058663328540c68e9df1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2700, "license_type": "no_license", "max_line_length": 64, "num_lines": 139, "path": "/guaca/mainwindow.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#ifndef MAINWINDOW_H\n#define MAINWINDOW_H\n\n#include <stdint.h>\n#include <QMainWindow>\n#include <QMessageBox>\n#include <QTimer>\n#include <QInputDialog>\n#include <QtConcurrent/QtConcurrent>\n#include <QTest>\n#include <QCloseEvent>\n#include <QListWidgetItem>\n#include <QAction>\n#include <QMenu>\n#include <QComboBox>\n\n#include \"options.h\"\n#include \"server.h\"\n\n#define MAX_NUM_LINKFILE 256\n#define MAXLINELENGTH 256\n#define IMAGE_IND_OFF 0\n#define IMAGE_LOOP_LOW 19\n#define IMAGE_LOOP_HIGH 23\n#define IMAGE_TOTAL 32\n\nclass HostMenu : public QMenu\n{\n Q_OBJECT\n\npublic:\n explicit HostMenu(QComboBox *parent);\n ~HostMenu();\n\nprivate:\n QAction *new_item;\n QAction *modify_item;\n QAction *delete_item;\n QAbstractItemView* view;\n QComboBox *combo;\n\n bool eventFilter(QObject *o, QEvent *e);\n\nprivate slots:\n void list_context_menu(QPoint pos);\n void handle_host_menu(QAction *);\n};\n\nnamespace Ui {\n class MainWindow;\n}\n\nclass MainWindow : public QMainWindow\n{\n Q_OBJECT\n\npublic:\n explicit MainWindow(QWidget *parent = 0);\n ~MainWindow();\n bool mole_active;\n\nprivate slots:\n void on_toggleMole_clicked();\n\n void dancing();\n\n int make_listfiles();\n\n void on_linkSelect_currentIndexChanged(const QString &arg1);\n\n bool change_remote_host(const QString &arg);\n\n void on_actionClose_triggered();\n\n void on_actionSlave_to_triggered();\n\n void on_actionAbout_triggered();\n\n void on_actionAbout_Qt_triggered();\n\n void on_actionOptions_triggered();\n\n void on_actionPurge_old_data_triggered();\n\n void on_actionClear_remote_hosts_triggered();\n\n void on_hosts_activated(int index);\n\n void on_linkSelect_activated(const QString &arg1);\n\n void on_multiLinkSelect_itemSelectionChanged();\n\n void on_computeFrameMap_clicked();\n\nprivate:\n int num_linkfile;\n QString linkfile[MAX_NUM_LINKFILE];\n Ui::MainWindow *ui;\n Options *options;\n HostMenu *host_menu;\n std::vector<Logscroll *> mole_logs;\n\n Server *server;\n bool still_dancing;\n QSettings settings;\n bool servermode;\n\n void freeze();\n void unfreeze();\n void start_a_mole(int );\n void stop_all_moles();\n int get_server_data();\n void savePosition();\n void auto_select_link();\n\n void saveConfig();\n void loadConfig();\n void defaultConfig();\n\n void closeEvent(QCloseEvent *event);\n\n QIcon qi[IMAGE_TOTAL];\n QSize qs;\n\n QTimer * _ut, * _ut_listfiles;\n int image_i, inc;\n char buf[MAXLINELENGTH+5];\n uint64_t prev_size;\n uint64_t logend;\n bool data_incoming;\n\n int host_index;\n QString linkItem;\n QStringList linkSelect;\n bool has_warned;\n QString last_msg;\n};\n\n#endif // MAINWINDOW_H\n" }, { "alpha_fraction": 0.5908311605453491, "alphanum_fraction": 0.5967504978179932, "avg_line_length": 29.429813385009766, "blob_id": "dce3c5afd6c5c4ec35cdbddb23a41401e7207e46", "content_id": "808547f9b541bfd98e02f944637636bfdf859320", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 24496, "license_type": "no_license", "max_line_length": 115, "num_lines": 805, "path": "/blast_comms/comms_netsock.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/**\n * @file comms_netsock.c\n *\n * @date Jan 16, 2011\n * @author seth\n *\n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2010 Columbia University\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <errno.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <netdb.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <arpa/inet.h>\n\n#include <blast.h>\n#include <comms_netsock.h>\n\nstatic int comms_sock_raw_read(comms_socket_t *m_sock, void *m_buf, size_t m_len);\nstatic int comms_sock_raw_write(comms_socket_t *m_sock, const void *m_buf, size_t m_len);\nstatic int comms_sock_get_addrinfo(const char *m_hostname, uint32_t m_port, bool m_udp, struct addrinfo **m_ai);\nstatic socket_t comms_sock_bind(const char *m_hostname, uint32_t m_port, bool m_tcp);\nstatic socket_t comms_sock_connect_fd(const char *m_hostname, uint32_t m_port, bool m_udp);\nstatic int comms_sock_poll(comms_net_async_handle_t *m_handle, socket_t m_fd, uint16_t m_events, void *m_sock);\n\n/**\n * Retrieves the address info structure for the given hostname:port combination. This assumes a TCP/IP\n * connection\n * @param m_hostname Destination hostname in either DNS or xx.xx.xx.xx format\n * @param m_port Port number for the service\n * @param m_udp True if the port is a UDP port\n * @param m_ai Double pointer that will be allocated by by getaddrinfo()\n * @return return code from getaddrinfo\n */\nstatic int comms_sock_get_addrinfo(const char *m_hostname, uint32_t m_port, bool m_udp, struct addrinfo **m_ai)\n{\n char *service = NULL;\n struct addrinfo request = { 0 };\n int retval = 0;\n\n log_enter();\n\n if (!m_udp) {\n request.ai_protocol = IPPROTO_TCP;\n request.ai_socktype = SOCK_STREAM;\n } else {\n request.ai_protocol = IPPROTO_UDP;\n request.ai_socktype = SOCK_DGRAM;\n }\n\n request.ai_family = PF_UNSPEC;\n request.ai_flags = AI_PASSIVE;\n if (m_port) {\n blast_tmp_sprintf(service, \"%hu\", m_port);\n request.ai_flags = AI_NUMERICSERV;\n }\n retval = getaddrinfo(m_hostname, service, &request, m_ai);\n log_leave();\n\n return retval;\n}\n\n/**\n * Connects an allocated socket to a given remote host:port combination\n * @param m_hostname\n * @param m_port\n * @return\n */\nstatic socket_t comms_sock_connect_fd(const char *m_hostname, uint32_t m_port, bool m_udp)\n{\n socket_t sock = -1;\n int retval;\n struct addrinfo *addrinfo_group;\n struct addrinfo *ai;\n\n log_enter();\n\n retval = comms_sock_get_addrinfo(m_hostname, m_port, m_udp, &addrinfo_group);\n if (retval != 0) {\n blast_err(\"Failed to resolve hostname %s (%s)\", m_hostname, gai_strerror(retval));\n log_leave();\n return NETSOCK_ERR;\n }\n\n for (ai = addrinfo_group; ai != NULL; ai = ai->ai_next) {\n /* create socket */\n sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);\n if (sock < 0) {\n blast_err(\"Socket create failed: %s\", strerror(errno));\n continue;\n }\n\n fcntl(sock, F_SETFL, O_NONBLOCK);\n\n if (!m_udp) connect(sock, ai->ai_addr, ai->ai_addrlen);\n break;\n }\n\n freeaddrinfo(addrinfo_group);\n log_leave();\n\n return sock;\n}\n\n/**\n * Binds a socket structure to a specific host:port combination.\n * @param m_hostname\n * @param m_port Port number to connect\n * @param m_udp If false, build a stream-based tcp connection\n * @return\n */\nstatic socket_t comms_sock_bind(const char *m_hostname, uint32_t m_port, bool m_udp)\n{\n socket_t sock = -1;\n int retval;\n struct addrinfo *addrinfo_group;\n struct addrinfo *ai;\n int sock_opt = 1;\n\n log_enter();\n\n retval = comms_sock_get_addrinfo(m_hostname, m_port, m_udp, &addrinfo_group);\n if (retval != 0) {\n blast_err(\"Failed to resolve hostname %s (%s)\", m_hostname, gai_strerror(retval));\n log_leave();\n return NETSOCK_ERR;\n }\n\n for (ai = addrinfo_group; ai != NULL; ai = ai->ai_next) {\n /* create socket */\n sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);\n if (sock < 0) {\n blast_err(\"Socket create failed: %s\", strerror(errno));\n continue;\n }\n\n if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &sock_opt, sizeof(sock_opt)) < 0) {\n freeaddrinfo(addrinfo_group);\n close(sock);\n log_leave();\n blast_err(\"Couldn't reuse socket for port %d\", m_port);\n return NETSOCK_ERR;\n }\n\n if (bind(sock, ai->ai_addr, ai->ai_addrlen)) {\n freeaddrinfo(addrinfo_group);\n close(sock);\n log_leave();\n blast_err(\"Couldn't bind to socket for port %d\", m_port);\n return NETSOCK_ERR;\n }\n\n break;\n }\n\n freeaddrinfo(addrinfo_group);\n log_leave();\n\n return sock;\n}\n\n/**\n * Joins an comms_socket to a multicast group. Typical groups will be specified in in.h as\n * INADDR_UNSPEC_GROUP, INADDR_ALLHOSTS_GROUP, INADDR_ALLRTRS_GROUP or INADDR_MAX_LOCAL_GROUP,\n * corresponding to 224.0.0.0, .1, .2, .255.\n * @param m_socket A bound comms_socket\n * @param m_group\n * @return\n */\nint comms_sock_join_mcast(comms_socket_t *m_socket, in_addr_t m_group)\n{\n struct ip_mreq multicast_req = { { 0 }, { 0 } };\n\n multicast_req.imr_multiaddr.s_addr = m_group;\t\t/// Group membership\n multicast_req.imr_interface.s_addr = INADDR_ANY;\t/// Local interface address (any)\n\n if (setsockopt(m_socket->fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &multicast_req, sizeof(multicast_req))) {\n blast_strerror(\"Cannot join multicast group!\");\n return NETSOCK_ERR;\n }\n\n return NETSOCK_OK;\n}\n\nint comms_sock_set_buffer(comms_socket_t *m_socket, int m_size)\n{\n if (setsockopt(m_socket->fd, SOL_SOCKET, SO_RCVBUF, &m_size, sizeof(int))) {\n blast_strerror(\"Cannot set socket receive buffer!\");\n return NETSOCK_ERR;\n }\n\n return NETSOCK_OK;\n}\n\nstatic int comms_sock_listen_generic(comms_socket_t *m_socket, const char *m_hostname, uint32_t m_port, bool m_udp)\n{\n socket_t fd;\n\n BLAST_SAFE_FREE(m_socket->host);\n if (!m_hostname) {\n m_socket->host = strdup(\"0.0.0.0\");\n } else {\n m_socket->host = strdup(m_hostname);\n }\n\n m_socket->port = m_port;\n\n if ((fd = comms_sock_bind(m_socket->host, m_port, m_udp)) == NETSOCK_ERR) {\n BLAST_SAFE_FREE(m_socket->host);\n return NETSOCK_ERR;\n }\n\n comms_sock_set_fd(m_socket, fd);\n\n if (listen(fd, 16)) {\n close(fd);\n BLAST_SAFE_FREE(m_socket->host);\n return NETSOCK_ERR;\n }\n\n return NETSOCK_OK;\n}\n/**\n * Starts listening on a given port.\n * @param m_socket Pointer to an allocated socket\n * @param m_hostname Hostname on which to listen for connections (or NULL for default)\n * @param m_port Numerical port to listen on.\n * @return NETSOCK_ERR on failure, NETSOCK_OK on success\n */\nint comms_sock_listen(comms_socket_t *m_socket, const char *m_hostname, uint32_t m_port)\n{\n return comms_sock_listen_generic(m_socket, m_hostname, m_port, false);\n}\n\n/**\n * Starts listening on a given port for UDP\n * @param m_socket Pointer to an allocated socket\n * @param m_hostname Hostname on which to listen for connections (or NULL for ALL)\n * @param m_port Numerical port to listen on.\n * @return NETSOCK_ERR on failure, NETSOCK_OK on success\n */\nint comms_sock_listen_udp(comms_socket_t *m_socket, const char *m_hostname, uint32_t m_port)\n{\n return comms_sock_listen_generic(m_socket, m_hostname, m_port, true);\n}\n\n/**\n * Accepts the next connection available on a listening socket. This call will block until the connection\n * is available. This is a cancellation point for pthreads.\n * @param m_socket\n * @return\n */\nsocket_t comms_sock_accept(comms_socket_t *m_socket)\n{\n socket_t fd = 0;\n struct sockaddr_in sa;\n socklen_t sl = sizeof(sa);\n\n if ((fd = accept(m_socket->fd, &sa, &sl)) < 0) {\n m_socket->last_errno = errno;\n switch (m_socket->last_errno) {\n case EAGAIN:\n return NETSOCK_AGAIN;\n case EMFILE:\n case ENFILE:\n blast_err(\"WARNING! File number limitations have been reached! \");\n return NETSOCK_ERR;\n default:\n blast_strerror(\"Could not accept new connection\");\n return NETSOCK_ERR;\n }\n }\n\n fcntl(fd, F_SETFL, O_NONBLOCK);\n\n if (m_socket->host) free(m_socket->host);\n memcpy(&m_socket->addr, &sa, sl);\n m_socket->host = strdup(inet_ntoa(sa.sin_addr));\n\n blast_info(\"Received connection from %s\", m_socket->host);\n return fd;\n}\n/**\n * Allocates space for a new socket structure\n * @return Pointer to the allocated structure or NULL on failure\n */\ncomms_socket_t *comms_sock_new(void)\n{\n comms_socket_t *sock;\n\n sock = (comms_socket_t *) calloc(1, sizeof(struct comms_socket));\n if (!sock) return NULL;\n\n log_enter();\n\n sock->can_read = false;\n sock->can_write = false;\n sock->have_exception = false;\n sock->poll_handle = NULL;\n sock->state = NETSOCK_STATE_NONE;\n sock->fd = INVALID_SOCK;\n sock->last_errno = -1;\n sock->is_socket = true;\n sock->in_buffer = netbuf_new(1, 4 * 1024 * 1024);\n if (!sock->in_buffer) {\n BLAST_SAFE_FREE(sock);\n blast_err(\"Could not allocate in_buffer\");\n return NULL;\n }\n sock->out_buffer = netbuf_new(1, 1024 * 1024);\n if (!sock->out_buffer) {\n netbuf_free(sock->in_buffer);\n BLAST_SAFE_FREE(sock);\n log_leave(\"Could not allocate out_buffer\");\n return NULL;\n }\n\n log_leave();\n return sock;\n}\n\n/**\n * Takes a double-pointer to a socket and ensures that it is in a pristine state, ready for a new connection.\n * @param m_sock Double pointer to a socket\n */\nvoid comms_sock_reset(comms_socket_t **m_sock)\n{\n log_enter();\n if (!(*m_sock)) {\n *m_sock = comms_sock_new();\n return;\n }\n comms_sock_close(*m_sock);\n\n (*m_sock)->fd = INVALID_SOCK;\n (*m_sock)->last_errno = -1;\n (*m_sock)->is_socket = true;\n netbuf_reinit((*m_sock)->in_buffer);\n netbuf_reinit((*m_sock)->out_buffer);\n (*m_sock)->can_read = false;\n (*m_sock)->can_write = false;\n (*m_sock)->have_exception = false;\n BLAST_ZERO((*m_sock)->callbacks);\n (*m_sock)->poll_handle = comms_sock_get_poll_handle(*m_sock);\n (*m_sock)->state = NETSOCK_STATE_NONE;\n (*m_sock)->flags = 0;\n log_leave();\n}\n\nvoid comms_sock_set_flags(comms_socket_t *m_sock, int m_flags)\n{\n m_sock->flags = m_flags;\n}\n\nstatic inline bool comms_sock_is_open(comms_socket_t *s)\n{\n return (s->fd != INVALID_SOCK);\n}\n\n/**\n * Main routine providing callback handling for asynchronous socket connections.\n * @param m_handle Pointer to the asynchronous handler\n * @param m_fd File descriptor for the network socket\n * @param m_events Received events flags\n * @param m_sock Pointer to the comms_socket structure\n * @return NETSOCK_OK on success, NETSOCK_ERR on failure\n */\nstatic int comms_sock_poll(comms_net_async_handle_t *m_handle, socket_t m_fd, uint16_t m_events, void *m_sock)\n{\n comms_socket_t *sock = (comms_socket_t*) m_sock;\n char buffer[COMMS_NETSOCK_BUF_SIZE];\n int retval = 0;\n socklen_t errlen = sizeof(sock->last_errno);\n\n log_enter();\n if (!comms_sock_is_open(sock)) {\n log_leave();\n return NETSOCK_ERR;\n }\n\n if (m_events & POLLERR) {\n /**\n * If we catch an error while connecting, we use getsockopt to try and determine the cause of the error.\n * The connected callback in then fired with NETSOCK_ERR\n */\n if (sock->state == NETSOCK_STATE_CONNECTING) {\n sock->state = NETSOCK_STATE_ERROR;\n blast_err(\"Got error while connecting to %s\", sock->host);\n if (sock->is_socket) getsockopt(m_fd, SOL_SOCKET, SO_ERROR, (void *) &sock->last_errno, &errlen);\n\n comms_sock_close(sock);\n if (sock->callbacks.connected) {\n sock->callbacks.connected(NETSOCK_ERR, sock->last_errno, sock->callbacks.priv);\n }log_leave();\n return NETSOCK_ERR;\n }\n /**\n * If we catch an error and we are not trying to connect, then we fall through to the POLLIN handler to\n * process the error\n */\n\n comms_net_async_del_events(m_handle, POLLERR);\n m_events |= POLLIN;\n }\n if (m_events & (POLLIN | POLLPRI)) {\n sock->can_read = true;\n retval = comms_sock_raw_read(sock, buffer, sizeof(buffer));\n /**\n * Caught an error. Likely broken pipe. Errno is stored in the sock struct.\n */\n if (retval < 0) {\n retval = -1;\n if (m_handle) {\n comms_net_async_del_events(m_handle, POLLIN | POLLERR);\n }\n if (sock->callbacks.error) {\n sock->callbacks.error(sock->last_errno, sock->callbacks.priv);\n }\n }\n\n /**\n * No more data are available. This is the EOF condition\n */\n if (retval == 0) {\n comms_net_async_del_events(m_handle, POLLIN);\n m_events |= POLLHUP;\n }\n\n /**\n * Got actual data. Buffer it and pass on to the user callback function\n */\n if (retval > 0) {\n size_t written = netbuf_write(sock->in_buffer, buffer, retval);\n size_t to_write = retval - written;\n if (sock->callbacks.data) {\n void *data;\n size_t len = netbuf_peek(sock->in_buffer, &data);\n\n if (len) {\n retval = sock->callbacks.data(data, len, sock->callbacks.priv);\n\n if (retval > 0) netbuf_eat(sock->in_buffer, retval);\n\n if (netbuf_bytes_available(sock->in_buffer)) comms_net_async_add_events(m_handle, POLLIN);\n free(data);\n }\n }\n /// If we didn't get everything in, try one more time\n if (to_write) {\n if (netbuf_write(sock->in_buffer, buffer + written, to_write)) blast_warn(\n \"Discarding data due to overfull in_buffer on %s\", sock->host ? sock->host : \"(NULL)\");\n }\n }\n }\n if (m_events & POLLHUP) {\n if (sock->callbacks.finished) {\n void *data;\n size_t len = netbuf_peek(sock->in_buffer, &data);\n\n if (len) {\n sock->callbacks.finished(data, len, sock->callbacks.priv);\n if (sock->in_buffer) netbuf_eat(sock->in_buffer, len);\n free(data);\n }\n sock->state = NETSOCK_STATE_CLOSED;\n }log_leave();\n return NETSOCK_OK;\n }\n if (m_events & POLLOUT) {\n if (sock->state == NETSOCK_STATE_CONNECTING) {\n sock->state = NETSOCK_STATE_CONNECTED;\n comms_net_async_set_events(m_handle, POLLPRI | POLLIN | POLLOUT);\n fcntl(sock->fd, F_SETFL, 0);\n\n if (sock->callbacks.connected) {\n sock->callbacks.connected(NETSOCK_OK, 0, sock->callbacks.priv);\n }\n\n log_leave();\n return NETSOCK_OK;\n }\n\n sock->can_write = true;\n comms_net_async_del_events(m_handle, POLLOUT);\n\n if (netbuf_bytes_available(sock->out_buffer)) {\n comms_sock_flush(sock);\n } else if (sock->callbacks.control) {\n sock->callbacks.control(NETSOCK_WRITABLE, sock->callbacks.priv);\n }\n }\n\n log_leave();\n return retval;\n}\n\ncomms_net_async_handle_t *comms_sock_get_poll_handle(comms_socket_t *m_sock)\n{\n log_enter();\n if (!m_sock->poll_handle) {\n m_sock->poll_handle = comms_net_async_handler_new(m_sock->fd, 0, comms_sock_poll, m_sock);\n }log_leave();\n return m_sock->poll_handle;\n}\n\nvoid comms_sock_free(comms_socket_t *m_sock)\n{\n log_enter();\n if (!m_sock) {\n log_leave(\"No socket\");\n return;\n }\n\n comms_sock_close(m_sock);\n netbuf_free(m_sock->in_buffer);\n netbuf_free(m_sock->out_buffer);\n BLAST_SAFE_FREE(m_sock->host);\n BLAST_SAFE_FREE(m_sock);\n log_leave(\"Freed\");\n}\n\nvoid comms_sock_close(comms_socket_t *m_sock)\n{\n log_enter();\n if (comms_sock_is_open(m_sock)) {\n if (close(m_sock->fd) == -1) m_sock->last_errno = errno;\n\n m_sock->fd = INVALID_SOCK;\n m_sock->state = NETSOCK_STATE_CLOSED;\n }\n if (m_sock->poll_handle) {\n comms_net_async_handler_free(m_sock->poll_handle);\n m_sock->poll_handle = NULL;\n }log_leave(\"Closed\");\n}\n\nvoid comms_sock_set_fd(comms_socket_t *m_sock, socket_t m_fd)\n{\n log_enter();\n m_sock->fd = m_fd;\n if (m_sock->poll_handle) {\n comms_net_async_set_sock(m_sock->poll_handle, m_fd);\n }\n\n log_leave();\n}\n\nstatic int comms_sock_raw_read(comms_socket_t *m_sock, void *m_buf, size_t m_len)\n{\n int retval = NETSOCK_ERR;\n\n log_enter();\n if (m_sock->have_exception) {\n log_leave();\n return NETSOCK_ERR;\n }\n if (m_sock->is_socket) {\n m_sock->addrlen = sizeof(m_sock->addr);\n retval = recvfrom(m_sock->fd, m_buf, m_len, 0, &m_sock->addr, &m_sock->addrlen);\n } else {\n retval = read(m_sock->fd, m_buf, m_len);\n }\n\n m_sock->last_errno = errno;\n m_sock->can_read = false;\n\n if (retval < 0) {\n m_sock->have_exception = true;\n }\n\n log_leave();\n return retval;\n}\n\nstatic int comms_sock_raw_write(comms_socket_t *m_sock, const void *m_buf, size_t m_len)\n{\n ssize_t retval = NETSOCK_ERR;\n\n log_enter();\n if (m_sock->have_exception) {\n log_leave();\n return NETSOCK_ERR;\n }\n\n if (m_sock->is_socket) {\n if (m_sock->udp) {\n retval = sendto(m_sock->fd, m_buf, m_len, m_sock->flags, &m_sock->addr, m_sock->addrlen);\n } else {\n /// Cap the maximum we send at any given point to the default segment size for TCP\n m_len = min(m_len, DEFAULT_MTU);\n retval = send(m_sock->fd, m_buf, m_len, m_sock->flags);\n }\n } else {\n retval = write(m_sock->fd, m_buf, m_len);\n }\n\n m_sock->last_errno = errno;\n\n if (m_sock->poll_handle) {\n comms_net_async_add_events(m_sock->poll_handle, POLLOUT);\n }\n if (retval < 0) {\n m_sock->have_exception = true;\n }\n\n log_leave();\n return retval;\n}\n\nint comms_sock_write(comms_socket_t *m_sock, const void *m_buf, size_t m_len)\n{\n if (m_len) {\n if (!m_sock) return NETSOCK_ERR;\n\n if (m_sock->state != NETSOCK_STATE_CONNECTING && m_sock->state != NETSOCK_STATE_CONNECTED) {\n blast_err(\"Can not write to socket %s in state %d\", m_sock->host ? m_sock->host : \"(Unknown host)\",\n m_sock->state);\n return NETSOCK_ERR;\n }\n if (!netbuf_write(m_sock->out_buffer, m_buf, m_len)) {\n blast_err(\"Could not buffer data on %s\", m_sock->host ? m_sock->host : \"(NULL)\");\n return NETSOCK_ERR;\n }\n if (m_sock->state == NETSOCK_STATE_CONNECTED) return comms_sock_flush(m_sock);\n }\n\n return NETSOCK_OK;\n}\n\nint comms_sock_flush(comms_socket_t *m_sock)\n{\n uint32_t len;\n int retval;\n\n log_enter();\n\n if (!comms_sock_is_open(m_sock)) {\n blast_err(\"Could not write to closed socket %s\", m_sock->host ? m_sock->host : \"(Unknown host)\");\n\n log_leave();\n return NETSOCK_ERR;\n }\n\n len = netbuf_bytes_available(m_sock->out_buffer);\n if (m_sock->poll_handle && len > 0) {\n if (!__sync_lock_test_and_set(&m_sock->can_write, false)) {\n comms_net_async_add_events(m_sock->poll_handle, POLLOUT);\n log_leave();\n return NETSOCK_AGAIN;\n }\n\n void *data;\n len = netbuf_peek(m_sock->out_buffer, &data);\n\n if (len) {\n retval = comms_sock_raw_write(m_sock, data, len);\n free(data);\n if (retval < 0) {\n comms_sock_close(m_sock);\n blast_err(\"Could not write socket: %s\", strerror(m_sock->last_errno));\n log_leave();\n return NETSOCK_ERR;\n }\n netbuf_eat(m_sock->out_buffer, retval);\n }\n }\n\n /**\n * If we have data left to write to the socket, then we force the POLLOUT event to allow\n * our async handler to catch and process the data in the next poll call.\n */\n len = netbuf_bytes_available(m_sock->out_buffer);\n if (m_sock->poll_handle && len > 0) {\n comms_net_async_add_events(m_sock->poll_handle, POLLOUT);\n log_leave();\n return NETSOCK_AGAIN;\n }\n\n log_leave();\n return NETSOCK_OK;\n}\n\nstatic int comms_sock_connect_generic(comms_socket_t *m_sock, const char *m_hostname, uint32_t m_port, bool m_udp)\n{\n socket_t fd;\n log_enter();\n\n if (!m_sock || m_sock->state != NETSOCK_STATE_NONE) return NETSOCK_ERR;\n fd = comms_sock_connect_fd(m_hostname, m_port, m_udp);\n\n if (fd == INVALID_SOCK) return NETSOCK_ERR;\n comms_sock_set_fd(m_sock, fd);\n\n BLAST_SAFE_FREE(m_sock->host);\n m_sock->host = strdup(m_hostname);\n m_sock->port = m_port;\n m_sock->udp = m_udp;\n\n m_sock->state = NETSOCK_STATE_CONNECTING;\n\n comms_net_async_set_events(comms_sock_get_poll_handle(m_sock), POLLOUT);\n log_leave();\n return NETSOCK_OK;\n}\n\nint comms_sock_reconnect(comms_socket_t *m_sock)\n{\n socket_t fd;\n\n if (!m_sock) return NETSOCK_ERR;\n if (m_sock->state != NETSOCK_STATE_CLOSED && m_sock->state != NETSOCK_STATE_ERROR) {\n blast_err(\"Could not reconnect socket (%s) in state %d\", m_sock->host ? m_sock->host : \"unknown host\",\n m_sock->state);\n }\n if (!m_sock->host) {\n blast_err(\"Could not reconnect socket without host\");\n return NETSOCK_ERR;\n }\n\n fd = comms_sock_connect_fd(m_sock->host, m_sock->port, m_sock->udp);\n\n if (fd == INVALID_SOCK) return NETSOCK_ERR;\n comms_sock_set_fd(m_sock, fd);\n\n m_sock->state = NETSOCK_STATE_CONNECTING;\n\n comms_net_async_set_events(comms_sock_get_poll_handle(m_sock), POLLOUT);\n log_leave();\n return NETSOCK_OK;\n}\n\nint comms_sock_connect(comms_socket_t *m_sock, const char *m_hostname, uint32_t m_port)\n{\n return comms_sock_connect_generic(m_sock, m_hostname, m_port, false);\n}\n\nint comms_sock_connect_udp(comms_socket_t *m_sock, const char *m_hostname, uint32_t m_port)\n{\n return comms_sock_connect_generic(m_sock, m_hostname, m_port, true);\n}\n\n/**\n * Sets up a multicast listening port.\n * @param m_sock Allocated socket\n * @param m_hostname Should be \"224.0.0.x\" where x is between 0 and 255\n * @param m_port Multicast port number\n * @return NETSOCK_OK on success, NETSOCK_ERR on failure\n */\nint comms_sock_multicast_listen(comms_socket_t *m_sock, const char *m_hostname, uint32_t m_port)\n{\n socket_t fd;\n in_addr_t group;\n int loop = 0;\n log_enter();\n\n if (!m_sock || m_sock->state != NETSOCK_STATE_NONE) return NETSOCK_ERR;\n fd = comms_sock_bind(\"0.0.0.0\", m_port, true);\n if (fd == INVALID_SOCK) return NETSOCK_ERR;\n\n comms_sock_set_fd(m_sock, fd);\n if ((group = inet_addr(m_hostname)) == INADDR_NONE) return NETSOCK_ERR;\n\n if (comms_sock_join_mcast(m_sock, group) == NETSOCK_ERR) return NETSOCK_ERR;\n\n setsockopt(m_sock->fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));\n\n BLAST_SAFE_FREE(m_sock->host);\n\n m_sock->addr.sin_family = AF_INET;\n m_sock->addr.sin_addr.s_addr = group;\n m_sock->addr.sin_port = htons(m_port);\n m_sock->addrlen = sizeof(m_sock->addr);\n\n m_sock->host = strdup(m_hostname);\n m_sock->port = m_port;\n m_sock->udp = 1;\n\n m_sock->state = NETSOCK_STATE_CONNECTING;\n\n comms_net_async_set_events(comms_sock_get_poll_handle(m_sock), POLLOUT);\n log_leave();\n return NETSOCK_OK;\n}\n" }, { "alpha_fraction": 0.6782077550888062, "alphanum_fraction": 0.6924643516540527, "avg_line_length": 13.028571128845215, "blob_id": "2b70ea197c2eef261c1b7dca07d58c74bdf9c5db", "content_id": "d9c9f2ebad5b63a4798b4d1bbfeaf6f273495f93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 491, "license_type": "no_license", "max_line_length": 47, "num_lines": 35, "path": "/guaca/server.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#ifndef SERVER_H\n#define SERVER_H\n\n#include <QObject>\n#include <QWidget>\n#include <QTcpSocket>\n#include <QTcpServer>\n\n#define SLAVEPORT 40004\n\nclass Server : public QObject\n{\n Q_OBJECT\n\npublic:\n explicit Server(QObject *parent = nullptr);\n ~Server();\n\n bool getServerData(QString host);\n\npublic slots:\n void sendServerData();\n\nprivate:\n QTcpServer *tcpserver;\n};\n\n#pragma pack(push, 1)\nstruct SharedData {\n uint8_t mole_active;\n};\n#pragma pack(pop)\n\n\n#endif // SERVER_H\n" }, { "alpha_fraction": 0.7036082744598389, "alphanum_fraction": 0.7139175534248352, "avg_line_length": 19.421052932739258, "blob_id": "fd6082d8d29f807042930bc1111af6956f657387", "content_id": "c4cddb15558fde2db42b17145adab7679e62e564", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 389, "license_type": "no_license", "max_line_length": 73, "num_lines": 19, "path": "/stars/code/logger_main.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef LOGGER_MAIN_H\n#define LOGGER_MAIN_H\n\n#include \"logging/logger.h\"\n\nnamespace Main\n{\n // To be used only by the main thread\n extern Logging::Logger logger;\n}\n\n#endif\n" }, { "alpha_fraction": 0.6989644765853882, "alphanum_fraction": 0.706360936164856, "avg_line_length": 31.16666603088379, "blob_id": "48d7b675b850beb84786622b56d90b95b6c69573", "content_id": "0581e64ce354e2443b794f0170c2d7687967a0dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1353, "license_type": "no_license", "max_line_length": 104, "num_lines": 42, "path": "/stars/code/solving/finding/smoother.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"smoother.h\"\n#include <math.h>\n#include \"../update.h\"\n#include \"../../shared/image/raw.h\"\n#include \"../../parameters/manager.h\"\n#include \"../../tools/correlate.h\"\n#include \"../../tools/psf.h\"\n\n#include \"../../tools/quick_cout.h\"\n\nusing namespace Solving::Finding;\nusing namespace Tools::PSF;\nusing std::vector;\n\nSmoother::Smoother(Parameters::Manager& params)\n{\n\timage_width = params.general.try_get(\"imaging.camera_real.image_width\", params.general.image_width);\n\timage_height = params.general.try_get(\"imaging.camera_real.image_height\", params.general.image_height);\n scratch = new double[image_width*image_height];\n}\n\nSmoother::~Smoother()\n{\n delete [] scratch;\n}\n\nvoid Smoother::make_smooth(Shared::Image::Raw& image, double *pixels_smoothed, int halfwidth,\n double sigma)\n{\n int length = 2*halfwidth+1;\n double* gauss = new double[length];\n Tools::PSF::get_kernel_separated_gauss(gauss, halfwidth, sigma);\n Tools::correlate2d(image.pixels, gauss, scratch, halfwidth, 0, image_width, image_height);\n Tools::correlate2d(scratch, gauss, pixels_smoothed, 0, halfwidth, image_width, image_height);\n delete [] gauss;\n}\n\n" }, { "alpha_fraction": 0.7461669445037842, "alphanum_fraction": 0.7538330554962158, "avg_line_length": 33.52941131591797, "blob_id": "785c457a46faaf084d31b7c118de48812101768b", "content_id": "f7847b521132c28d7525da54593022f7dd0f2a53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1174, "license_type": "no_license", "max_line_length": 71, "num_lines": 34, "path": "/common/include/command_common.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* mcp: the BLAST master control program\n *\n * commands.c: functions for listening to and processing commands\n *\n * This software is copyright (C) 2002-2010 University of Toronto\n *\n * This file is part of mcp.\n *\n * mcp 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp 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 mcp; if not, write to the Free Software Foundation, Inc.,\n *\n */\n#ifndef INCLUDE_COMMAND_COMMON_H\n#define INCLUDE_COMMAND_COMMON_H\n\n#include \"command_list.h\"\n\nint SIndex(enum singleCommand command);\nconst char* SName(enum singleCommand command);\nint MIndex(enum multiCommand command);\nconst char* MName(enum multiCommand command);\nconst char* CommandName(int is_multi, int command);\n\n#endif\n" }, { "alpha_fraction": 0.6992753744125366, "alphanum_fraction": 0.6992753744125366, "avg_line_length": 10.541666984558105, "blob_id": "7b74379b60d685ae1645404fd5ea0db8a0c193f3", "content_id": "b564a151da92ed4231ead211b1e51107706e8373", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 276, "license_type": "no_license", "max_line_length": 72, "num_lines": 24, "path": "/balloon_cam/pixelfixer.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//pixelFixer.h\n\n#pragma once\n\n#include \"stdafx.h\"\n\nclass PixelFixer {\n\npublic:\n\t\n\tPixelFixer(int, int, int);\n\n\tWORD* generateBadPixelTable(char*);\n\nprivate:\n\n\tstd::vector<double> detectWeirdPixels(std::vector<double>, char*, int);\n\n\tint xSize;\n\n\tint ySize;\n\n\tint pixelSize;\n};" }, { "alpha_fraction": 0.6941935420036316, "alphanum_fraction": 0.6967741847038269, "avg_line_length": 20.83098602294922, "blob_id": "0ff16a9928ae6d6a3627dd457998867fc48b22ed", "content_id": "23b41ab154b3a2e197631f6a593a0a5168057536", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1551, "license_type": "no_license", "max_line_length": 82, "num_lines": 71, "path": "/stars/code/solving/autofocus_helper.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__AUTOFOCUS_HELPER_H\n#define SOLVING__AUTOFOCUS_HELPER_H\n\n#include <vector>\n#include \"../shared/autofocus/datapoints.h\"\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n}\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Solving\n{\n class AutofocusDatapoint;\n class AutofocusHelper;\n class Blob;\n class Solution;\n}\n\nclass Solving::AutofocusDatapoint\n{\n public:\n AutofocusDatapoint();\n AutofocusDatapoint& operator=(const AutofocusDatapoint& rhs);\n static bool sort_by_focus(AutofocusDatapoint first, AutofocusDatapoint second)\n {\n return first.focus < second.focus;\n }\n\n Shared::Autofocus::datapoints_t type;\n int star_id;\n double focus;\n double value;\n Tools::Timer age;\n};\n\n\nclass Solving::AutofocusHelper\n{\n public:\n AutofocusHelper(Parameters::Manager& params);\n ~AutofocusHelper();\n void update_and_share();\n void extract_sobel_datapoint(Shared::Image::Raw& image);\n void extract_brightest_blob_datapoint(Shared::Image::Raw& image,\n std::vector<Solving::Blob>& blobs);\n void extract_star_datapoints(Shared::Image::Raw& image, Solution& solution);\n void set_fully_solved(int counter_stars);\n\n std::vector<AutofocusDatapoint> datapoints;\n int image_width;\n int image_height;\n double* scratch;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6804123520851135, "alphanum_fraction": 0.6890034079551697, "avg_line_length": 19.785715103149414, "blob_id": "c2837558402b3fef55ab6af20deacb32026fedd1", "content_id": "4905208382729280de90d221026084b1decef13f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 583, "license_type": "no_license", "max_line_length": 73, "num_lines": 28, "path": "/stars/code/displaying/color.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__COLOR_H\n#define DISPLAYING__COLOR_H\n\nnamespace Displaying\n{\n class Color;\n}\n\nclass Displaying::Color\n{\n public:\n Color();\n Color(double r, double g, double b, double a);\n Color& operator=(const Color &rhs);\n Color& operator*=(const double &scale);\n const Color operator*(const double &scale) const;\n\n double values[4];\n};\n\n#endif\n" }, { "alpha_fraction": 0.4881732165813446, "alphanum_fraction": 0.506186306476593, "avg_line_length": 25.423076629638672, "blob_id": "5d84990631a9c7757c2c5d7f186b73008063b212", "content_id": "f1024acce6a3afd18c7b3560d3c501b2a5d6edb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5496, "license_type": "no_license", "max_line_length": 116, "num_lines": 208, "path": "/katie/katie.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "// GPL V2+\n// (C) Javier Romuldez, 2016 - 2018\n// (C) C. Barth Netterfield 2018\n\n#define KATIE_VERSION \"2.0\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <getopt.h>\n#include <signal.h>\n#include <string.h>\n\n#define NAMELEN 100\n\n#define IDLE_SYNC 150\n\n#define NOR \"\\x1B[0m\"\n#define RED \"\\x1B[31;1m\"\n#define GRN \"\\x1B[32;1m\"\n#define YLW \"\\x1B[33;1m\"\n#define BLU \"\\x1B[34;1m\"\n#define MAG \"\\x1B[35;1m\"\n#define CYN \"\\x1B[36;1m\"\n#define NOC \"\\x1B[?25l\"\n#define CUR \"\\x1B[?25h\"\n\nchar filename[NAMELEN];\nchar dataname[NAMELEN];\n\nchar bit_filename[NAMELEN] = \"/data/etc/mole.lnk\";\nchar bit_dataname[NAMELEN] = \"ifc_log\";\nchar bit_colortag[NAMELEN] = \"\\n[] \";\n\nchar spider_filename[NAMELEN] = \"/data/etc/defile.lnk\";\nchar spider_tdrssname[NAMELEN] = \"/data/etc/tdrss.lnk\";\nchar spider_dataname[NAMELEN] = \"logstream\";\nchar spider_colortag[NAMELEN] = \" \\n\";\n\nchar blast_filename[NAMELEN] = \"/data/etc/mole.lnk\";\nchar blast_dataname[NAMELEN] = \"chatter\";\nchar blast_colortag[NAMELEN] = \" \\n\";\n\n\nvoid usage(char *exe)\n{\n fprintf(stderr, \"%s [-s|-b] [-b|-k] [-d <DIRFILE>] [-c <FIELD>]\\n\", exe);\n fprintf(stderr, \"Translate FIELD from DIRFILE into ASCII on stdout.\\n\");\n fprintf(stderr, \"-d <PATH_TO_DIRFILE>\\n\");\n fprintf(stderr, \"-c <FIELD>\\n\");\n fprintf(stderr, \"-B BLAST: same as -d %s -c %s\\n\", blast_filename, blast_dataname);\n fprintf(stderr, \"-s Spider: same as -d %s -c %s\\n\", spider_filename, spider_dataname);\n fprintf(stderr, \"-t Spider TDRSS: same as -d %s -c %s\\n\", spider_tdrssname, spider_dataname);\n fprintf(stderr, \"-b superBIT: same as -d %s -c %s\\n\", bit_filename, bit_dataname);\n fprintf(stderr, \"-k color (default)\\n\");\n fprintf(stderr, \"-m monochrome\\n\");\n \n fprintf(stderr, \"This is katie version %s\\n\", KATIE_VERSION);\n fprintf(stderr, \"This is FREE software (GPL) with NO WARRANTY\\n\");\n exit(-1);\n}\n\nint main(int argc, char **argv)\n{\n char c;\n char bname[NAMELEN];\n int is_color = 1;\n int sync = 0;\n char * color_tag = spider_colortag;\n \n\n // FIXME: sticky defaults\n snprintf(filename, NAMELEN, \"%s\", spider_filename);\n snprintf(dataname, NAMELEN, \"%s\", spider_dataname);\n \n while ((c = getopt(argc, argv, \"d:c:sbtmkB\")) != -1) {\n switch (c) {\n case 'd':\n snprintf(filename, NAMELEN, \"%s\", optarg);\n break;\n case 'c':\n snprintf(dataname, NAMELEN, \"%s\", optarg);\n break;\n case 's':\n snprintf(filename, NAMELEN, \"%s\", spider_filename);\n snprintf(dataname, NAMELEN, \"%s\", spider_dataname);\n color_tag = spider_colortag;\n break;\n case 't':\n snprintf(filename, NAMELEN, \"%s\", spider_tdrssname);\n snprintf(dataname, NAMELEN, \"%s\", spider_dataname);\n break;\n case 'b':\n snprintf(filename, NAMELEN, \"%s\", bit_filename);\n snprintf(dataname, NAMELEN, \"%s\", bit_dataname);\n color_tag = bit_colortag;\n break;\n case 'B':\n snprintf(filename, NAMELEN, \"%s\", blast_filename);\n snprintf(dataname, NAMELEN, \"%s\", blast_dataname);\n color_tag = blast_colortag;\n break;\n case 'k':\n is_color = 1;\n break;\n case 'm':\n is_color = 0;\n break;\n default:\n usage(argv[0]);\n break;\n }\n }\n \n sprintf(bname,\"%s/%s\",filename,dataname);\n \n if (access(filename,F_OK) != 0) {\n printf(\"Cannot find dirfile %s\\n\",filename);\n exit(-1);\n } else if (access(bname,F_OK) != 0) {\n printf(\"Cannot find \\\"%s\\\" in dirfile %s\\n\",dataname,filename);\n exit(-1);\n }\n \n FILE * df = fopen(bname,\"rb\");\n printf(\"Reading \\\"%s\\\" from %s\\n\",dataname,filename);\n\n int i = 0, j = 0;\n int new_state = 0;\n char state_c = color_tag[0];\n int color_tag_len = strlen(color_tag);\n \n fseek(df,0,SEEK_END);\n while (1) {\n while ((c = fgetc(df)) != EOF) {\n i = 0;\n// if ((c >= 0x20) || (c == '\\n')) printf(\"%c\",c);\n\n new_state = 0;\n for (j = 0; j < color_tag_len; j++) {\n if (c == color_tag[(j+1)%color_tag_len] && state_c == color_tag[j]) {\n new_state = 1;\n break;\n }\n }\n if (new_state) {\n state_c = c;\n }\n\n if (is_color) {\n if (state_c == color_tag[color_tag_len-1]) {\n if (c == '*' || c == '!' || c == '$') {\n printf(RED);\n }\n if (c == '+' || c == '#') {\n printf(CYN);\n }\n if (c == ':') {\n printf(YLW);\n }\n if (c == '=') {\n printf(MAG);\n }\n if (c == '&') {\n printf(BLU);\n }\n }\n if (c == '\\n') {\n printf(NOR);\n }\n }\n if (c >= 0x20 || c == '\\n') {\n if (is_color) {\n if (sync > IDLE_SYNC) {\n printf(CUR);\n }\n if (state_c == color_tag[color_tag_len-1] && c != state_c) {\n state_c = color_tag[0];\n }\n }\n putchar(c);\n sync = 0;\n } else {\n sync++;\n if (is_color) {\n if (sync % IDLE_SYNC == 0) {\n printf(\"%s\", (sync / IDLE_SYNC) & 0x1 ? NOC : CUR);\n fflush(stdout);\n }\n }\n }\n fflush(stdout);\n }\n if (i >= 10) {\n fclose(df);\n fopen(bname,\"rb\");\n fseek(df,0,SEEK_END);\n i = 0;\n }\n i++;\n usleep(100000); // zzzz.....\n }\n \n fclose(df);\n \n return 0;\n}\n" }, { "alpha_fraction": 0.672739565372467, "alphanum_fraction": 0.6889338493347168, "avg_line_length": 28.058822631835938, "blob_id": "f603495ffe3df47051f6eaed3d467156b494bbfd", "content_id": "c391cb92e71f675421740bc5eeabacf98477731d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1482, "license_type": "no_license", "max_line_length": 104, "num_lines": 51, "path": "/owl/PMultiDataItem.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"PMultiDataItem.h\"\n#include \"PStyle.h\"\n\n#include <unistd.h>\n\nvoid PMultiDataItem::gdUpdate(GetData::Dirfile* dirFile,int lastNFrames)\n{\n double indata;\n bool ok;\n\n indata = gdReadRawData(dirFile, lastNFrames, ok);\n\n if (ok) {\n QString x=_map->get(indata);\n if (_data->text()!=x) {\n _data->setText(x);\n _serverDirty=-1;\n } else {\n _serverDirty--;\n }\n\n PStyle* nstyle=_map->style(indata,_defaultDataStyle);\n\n if(nstyle!=_lastNStyle|| //the reason this works is because PStyleChooser works via reference to ptr\n nstyle->_dirty) {\n applyStyle(this,nstyle);\n _lastNStyle=nstyle;\n }\n }\n}\n" }, { "alpha_fraction": 0.6245532035827637, "alphanum_fraction": 0.6318339705467224, "avg_line_length": 35.45849609375, "blob_id": "caccae39c2ac054948d09ca476d6de39c406fcff", "content_id": "4de7eccca7e60d45d43181d559d06b796b9e52e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 37771, "license_type": "no_license", "max_line_length": 168, "num_lines": 1036, "path": "/starcam/starcam.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <cstdlib>\n#include <cstdarg>\n#include <string.h>\n#include <stdio.h>\n#include <fstream>\n#include <sstream>\n#include <unistd.h>\n#include <iostream>\n#include <fcntl.h>\n#include <errno.h>\n#include <pthread.h>\n#include <sched.h>\n#include <sys/io.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <arpa/inet.h>\n#include <netdb.h> //for gethostbyname\n#include \"mycam.h\"\n#include \"blobimage.h\"\n#include \"frameblob.h\"\n#include \"bloblist.h\"\n#include \"camcommunicator.h\"\n#include \"sbigudrv.h\"\n#include \"csbigimgdefs.h\"\n#include \"camconfig.h\"\n#include \"pyramid.h\"\n\nextern \"C\" {\n#include \"udp.h\"\n}\n\n//#include \"clensadapter.h\"\n\nusing namespace std;\n\n#define SC_TIMEOUT 100 /* milliseconds */\n//enable display of debugging info to console\n#define STARCAM_DEBUG 0\n#define SC_THREAD_DEBUG 0\n\n//enable use of image viewer window\n//this no longer starts the window, only writes a file for it to use\n#define USE_IMAGE_VIEWER 1\n\n//0=no saving, 1=save raw image, 2=save version with boxes too\n#define SAVE_SC_IMAGES 1\n\n#define NUMIMGS 50\n\n//camera and image objects (and associated mutexes)\nMyCam globalCam;\nBlobImage globalImages[2]; //one image can be processed while other is obtained\npthread_mutex_t camLock = PTHREAD_MUTEX_INITIALIZER;\npthread_mutex_t imageLock[2] = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER};\npthread_mutex_t viewerLock = PTHREAD_MUTEX_INITIALIZER;\n\n//flags, etc. for synchronizing image exposure and processing\nint globalImageReadyFlags[2] = {0, 0}; // 1 when an image is ready, 0 when processing complete\npthread_mutex_t imageReadyLock[2] = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER};\npthread_cond_t imageReadyCond[2] = {PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER};\npthread_cond_t processingCompleteCond[2] = {PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER};\n//camera trigger flags, etc.\nint globalCameraTriggerFlag = 0;\npthread_mutex_t cameraTriggerLock = PTHREAD_MUTEX_INITIALIZER;\npthread_cond_t cameraTriggerCond = PTHREAD_COND_INITIALIZER;\nextern int copyFlag;\n\n//image viewer\n#if USE_IMAGE_VIEWER\nconst char* viewerPath = \"/data/etc/current_bad.sbig\";\nconst char* tmpviewerPath = \"/data/etc/tmp_bad.sbig\";\nbool showBoxes = true;\n#endif\n\n//function declarations\nvoid* pictureLoop(void* arg);\nvoid* processingLoop(void* arg);\nvoid* ReadLoop(void* arg);\nvoid* CopyLoop(void* arg);\nstring interpretCommand(string cmd);\nvoid powerCycle();\nvoid lock(pthread_mutex_t* mutex, const char* lockname, const char* funcname);\nvoid unlock(pthread_mutex_t* mutex, const char* lockname, const char* funcname);\nvoid wait(pthread_cond_t* cond, pthread_mutex_t* mutex, const char* condname, \n const char* lockname, const char* funcname);\nint initCommands();\nint maintainInitFile(string cmd, string val);\n\n//any command that changes starcam from its default state will be stored here to\n//be executed at start time and resume previous operating state\nconst char* initFilename = \"/data/etc/init.txt\";\nconst char* badpixFilename = \"/data/etc/badpix.txt\";\nconst string adapterPath = \"/dev/ttyACM0\";\nconst string imgPath = \"/data/rawdir\"; //path to save images in\n\n//logging function to clean up a bunch of the messy #ifs\nenum loglevel {debug, data, info, warning, error};\nvoid sclog(loglevel level, char* fmt, ...)\n{\n time_t T;\n time(&T);\n char msg[1024];\n va_list argptr;\n va_start(argptr, fmt);\n vsnprintf(msg, 1024, fmt, argptr);\n va_end(argptr);\n\n switch (level) {\n case debug:\n case data:\n#if STARCAM_DEBUG\n cerr << \"[Starcam debug]: \" << msg << \" \" << ctime(&T);\n cerr.flush();\n#endif\n break;\n case info:\n cout << \"--Starcam--\" << msg << \" \" << ctime(&T);\n cout.flush();\n break;\n case warning:\n cerr << \"==Starcam Warning==\" << msg << \" \" << ctime(&T);\n cerr.flush();\n break;\n case error:\n cerr << \"**Starcam ERROR**\" << msg << \" \" << ctime(&T);\n cerr.flush();\n break;\n }\n}\n\nPAR_ERROR openCameras()\n{\n PAR_ERROR err;\n static int crashcount = 0;\n sclog(info, (char*)\"Opening the camera driver.\");\n if ((err = globalCam.OpenDriver()) != CE_NO_ERROR)\n return err;\n\n //query the usb bus for possible cameras..for some reason screws up the next step, comment out when not needed\n \tcout << \"[Starcam debug]: Querying the USB bus for usable devices...\" << endl;\n \tQueryUSBResults qur; //results structure\n \tif ((err= globalCam.QueryUSB(qur)) != CE_NO_ERROR)\n \t\treturn err;\n \tcout << \"...search for a camera was \" << ((qur.camerasFound)?\"successful\":\"unsuccessful\") << endl;\n\n sclog(info, (char*)\"Opening the camera device.\");\n if ((err = globalCam.OpenUSBDevice(0)) != CE_NO_ERROR) {\n\tcrashcount ++;\n\tif (crashcount == 5) {\n \t\tcout << \"[Starcam debug]: EXITING!!!!...\" << endl;\n \t \tcrashcount = 0;\n\t\texit(1);\n\t}\n \treturn err;\n }\n sclog(info, (char*)\"Attempting to establish link to camera.\");\n for (int i=0; i<6; i++) {\n sclog(info, (char*)\" ...attempt %d\", i);\n if ((err = globalCam.EstablishLink()) == CE_NO_ERROR) break;\n }\n if (err != CE_NO_ERROR)\n return err;\n\n return CE_NO_ERROR;\n}\n\nint main(int argc, char *argv[])\n{\n //set up the camera\n PAR_ERROR err;\n LENS_ERROR lerr;\n\n if ((err = openCameras()) != CE_NO_ERROR)\n return err;\n\n sclog(info,(char*)\"Opening a connection to the lens adapter...\");\n if ((lerr = globalCam.getLensAdapter()->openConnection(adapterPath)) != LE_NO_ERROR)\n return lerr;\n\n //initialize the images\n for (int i=0; i<2; i++) {\n globalImages[i].setBadpixFilename(badpixFilename);\n globalImages[i].getFrameBlob()->load_badpix(badpixFilename);\n }\n\n //run the stored initialization commands\n if (initCommands() < 0) return -1;\n\n //start threads for picture taking, image processing, and command reading\n int threaderr;\n pthread_t threads[4];\n pthread_attr_t scheduleAttr;\n struct sched_param scheduleParams;\n pthread_attr_init(&scheduleAttr);\n if (pthread_attr_setschedpolicy(&scheduleAttr, SCHED_FIFO) !=0) return -1;\n pthread_attr_getschedparam(&scheduleAttr, &scheduleParams);\n\n scheduleParams.sched_priority+=2;\n if (pthread_attr_setschedparam(&scheduleAttr, &scheduleParams) != 0) return -1;\n pthread_create(&threads[0], &scheduleAttr, &pictureLoop, NULL);\n\n scheduleParams.sched_priority--; //run processing at default priority, lower than pictures\n if (pthread_attr_setschedparam(&scheduleAttr, &scheduleParams) != 0) return -1;\n pthread_create(&threads[1], &scheduleAttr, &processingLoop, NULL);//comm);//\n\n scheduleParams.sched_priority+=2; //run command reading at highest priority\n if (pthread_attr_setschedparam(&scheduleAttr, &scheduleParams) != 0) return -1;\n pthread_create(&threads[2], &scheduleAttr, &ReadLoop, NULL);//comm);\n\n scheduleParams.sched_priority--;\n if (pthread_attr_setschedparam(&scheduleAttr, &scheduleParams) != 0) return -1;\n pthread_create(&threads[3], &scheduleAttr, &CopyLoop, NULL);//comm);//\n\n sclog(info, (char*)\"Waiting for threads to complete...ie never\");\n //wait for threads to return\n for (int i=0; i<4; i++)\n threaderr = pthread_join(threads[i], NULL);\n\n // shut down cameras if threads return (an error has occured)\n sclog(info, (char*)\"All threads have returned...there are errors somehwere...go find them\");\n\n if ((err = globalCam.CloseDevice()) != CE_NO_ERROR )\n return err;\n if ( (err = globalCam.CloseDriver()) != CE_NO_ERROR )\n return err;\n\n return EXIT_SUCCESS;\n}\n\nvoid* CopyLoop(void* arg)\n{\n sclog(info, (char*)\"Starting up Copy Loop\");\n while(1) {\n while (!copyFlag) {\n usleep(10000);\n }\n system(\"mv /data/etc/tmp_bad.sbig /data/etc/current_bad.sbig\");\n system(\"cat /data/etc/current_bad.sbig | ssh [email protected] -c arcfour 'cat > /data/etc/tmp_bad.sbig && mv /data/etc/tmp_bad.sbig /data/etc/current_bad.sbig'\");\n copyFlag=0;\n }\n return NULL;\n}\n\n/*\n\npictureLoop:\n\nTakes pictures in an infinite loop in response to either a timer or a trigger\nDesigned to run concurrently with processingLoop and readLoop\nMight have to wait for image processing in progress to complete\n\n*/\nvoid* pictureLoop(void* arg)\n{\n sclog(info, (char*)\"Starting up picture loop\");\n\n int imageIndex = 0; //index in image array to use\n int interval; //local storage of picture interval (in us)\n static PAR_ERROR err = CE_NO_ERROR; //static enum lets a pointer to it be returned\n int failureCount = 0;\n while (1) {\n //depending on picture interval, either sleep or wait for trigger\n lock(&camLock, \"camLock\", \"pictureLoop\");\n interval = globalCam.getPictureInterval() * 1000;\n unlock(&camLock, \"camLock\", \"pictureLoop\");\n if (interval == 0) { //camera is in triggered mode, wait for trigger\n lock(&cameraTriggerLock, \"cameraTriggerLock\", \"pictureLoop\");\n while (!globalCameraTriggerFlag) {\n // \t\t\t\t\tpthread_cond_wait(&cameraTriggerCond, &cameraTriggerLock);\n wait(&cameraTriggerCond, &cameraTriggerLock, \"cameraTriggerCond\",\n \"cameraTriggerLock\", \"pictureLoop\");\n }\n globalCameraTriggerFlag = 0; //unset flag before continuing\n unlock(&cameraTriggerLock, \"cameraTriggerLock\", \"pictureLoop\");\n }\n else { //camera is in timed mode\n usleep(interval);\n }\n\n //wait for image to finish being processed\n lock(&imageReadyLock[imageIndex], \"imageReadyLock\", \"pictureLoop\");\n while (globalImageReadyFlags[imageIndex] == 1) {\n // \t\t\t\tpthread_cond_wait(&processingCompleteCond[imageIndex], \n // \t\t\t\t\t\t\t\t &imageReadyLock[imageIndex]);\n wait(&processingCompleteCond[imageIndex], &imageReadyLock[imageIndex],\n \t \"processingCompleteCond\", \"imageReadyLock\", \"pictureLoop\");\n }\n unlock(&imageReadyLock[imageIndex], \"imageReadyLock\", \"pictureLoop\");\n\n //grab new image (lock camera so settings can't change during exposure)\n lock(&camLock, \"camLock\", \"pictureLoop\");\n sclog(info, (char*)\"grabbing image.\");\n err = globalCam.GrabImage(&globalImages[imageIndex], SBDF_LIGHT_ONLY);\n if (err != CE_NO_ERROR) {\n failureCount++;\n if (failureCount == 3) {\n\tsclog(error, (char*)\"pictureLoop: repeated errors: %s, restarting camera.\", globalCam.GetErrorString(err).c_str());\n\tpowerCycle();\n }\n else if (failureCount > 5) {\n\tsclog(error, (char*)\"pictureLoop: too many repeated errors: %s\", globalCam.GetErrorString(err).c_str());\n\texit(1);\n }\n else sclog(warning, (char*)\"pictureLoop: error: %s\", globalCam.GetErrorString(err).c_str());\n }\n else failureCount = 0;\n unlock(&camLock, \"camLock\", \"pictureLoop\");\n\n //trigger processing of this image\n lock(&imageReadyLock[imageIndex], \"imageReadyLock\", \"pictureLoop\");\n globalImageReadyFlags[imageIndex] = 1;\n unlock(&imageReadyLock[imageIndex], \"imageReadyLock\", \"pictureLoop\");\n pthread_cond_signal(&imageReadyCond[imageIndex]);\n\n\n //move on to next image while this one is being processed\n imageIndex = (imageIndex == 0)?1:0;\n }\n\n return NULL; //should never reach here\n}\n\n/*\n\nprocessingLoop:\n\nIn an infinito loop processes images as they become available\nDesigned to run concurrently with pictureLoop and readLoop\n\n*/\nvoid* processingLoop(void* arg)\n{\n sclog(info, (char*)\"Starting up image processing loop\");\n int imageIndex = 0;\n static SBIG_FILE_ERROR err;\n static int imgcounter = 0;\n\n int sock;\n sock = udp_bind_port(GBU_PORT,1);\n if (sock == -1)\n cout << \"unable to bind to port\" << endl;\n string rtn_str = \"\";\n\tstring sought = \"\\n\";\n\n while (1) {\n //wait for image to be available for processing\n lock(&imageReadyLock[imageIndex], \"imageReadyLock\", \"processingLoop\");\n while (globalImageReadyFlags[imageIndex] == 0) {\n // \t\t\t\tpthread_cond_wait(&imageReadyCond[imageIndex], \n // \t\t\t\t\t\t\t\t &imageReadyLock[imageIndex]);\n wait(&imageReadyCond[imageIndex], &imageReadyLock[imageIndex],\n\t \"imageReadyCond\", \"imageReadyLock\", \"processingLoop\");\n }\n unlock(&imageReadyLock[imageIndex], \"imageReadyLock\", \"processingLoop\");\n\n //process the image\n lock(&imageLock[imageIndex], \"imageLock\", \"processingLoop\");\n //save the file\n globalImages[imageIndex].AutoBackgroundAndRange();\n#if SAVE_SC_IMAGES\n sclog(debug, \"processingLoop: Saving image in: %s\", imgPath.c_str());\n imgcounter++;\n if (imgcounter == NUMIMGS) {\n \terr = globalImages[imageIndex].SaveImageIn(imgPath, 0);\n \tif (err != SBFE_NO_ERROR) {\n \t sclog(warning, \"processingLoop: File error during boxless write: %d\", err);\n \t}\n\timgcounter = 0;\n }\n#endif\n\n#if USE_IMAGE_VIEWER\n if (!showBoxes) {\n sclog(debug, (char*)\"processingLoop: Saving viewer image in: %s\", tmpviewerPath);\n err = globalImages[imageIndex].SaveImage(tmpviewerPath);\n if (err != SBFE_NO_ERROR) {\n\tsclog(warning, (char*)\"processingLoop: File error during viewer write: %d\", err);\n }\n }\n#endif\n\n //process the image\n globalImages[imageIndex].findBlobs();\n frameblob* fblob = globalImages[imageIndex].getFrameBlob();\n bloblist* blobs;\n int num = 1;\n if (STARCAM_DEBUG || showBoxes || SAVE_SC_IMAGES == 2) { //add boxes or output blob data\n sclog(data, (char*)\"processingLoop: Found %d blobs.\", fblob->get_numblobs());\n sclog(data, (char*)\"processingLoop: Their locations (x,y) are: \");\n if (fblob->get_numblobs()) {\n\tblobs = fblob->getblobs();\n\twhile (blobs != NULL) {\n\t sclog(data, (char*)\"processingLoop: ...(%g,%g)\", blobs->getx(), blobs->gety());\n\t if (showBoxes || SAVE_SC_IMAGES == 2)\n\t globalImages[imageIndex].drawBox(blobs->getx(), blobs->gety(), 40, num);\n\t blobs = blobs->getnextblob();\n\t num++;\n\t}\n }\n }\n#if SAVE_SC_IMAGES == 2\n sclog(debug, \"processignLoop: Saving image with boxes in: %s\", imgPath.c_str());\n err = globalImages[imageIndex].SaveImageIn(imgPath, 1);\n if (err != SBFE_NO_ERROR) {\n sclog(warning, \"processingLoop: File error during box write: %d\", err);\n }\n#endif\n\n#if USE_IMAGE_VIEWER\n if (showBoxes) {\n \tsclog(debug, (char*)\"processingLoop: Saving viewer image in: %s\", tmpviewerPath);\n \terr = globalImages[imageIndex].SaveImage(tmpviewerPath);\n\tif (err != SBFE_NO_ERROR)\n\t\tsclog(warning, (char*)\"processingLoop: File error during boxed viewer write: %d\", err);\n }\n#endif\n\n#if USE_PYRAMID\n if ((fblob->get_numblobs())>4) {\n\tcout << \"\\nPerforming Star matching...\" << endl;\n\tsolution_t* sol;\n\tcout << \"\\nGoing into matchStars...\" << endl;\n\tint nsol = globalImages[imageIndex].matchStars(&sol);\n\tcout << \"\\nStar matching found: \" << nsol << \" solutions and \" << sol[0].n << \" stars\" << endl;\n\tif (nsol > 0) {\n\t \t\tcout << \" \" << 0 << \":\\tn=\" << sol[0].n << \", brightest: ra=\" << sol[0].C[0]->ra*180/M_PI << \" dec=\" << sol[0].C[0]->dec*180/M_PI << endl;\n\t\t\tfor (int k=0; k<sol[0].n; k++)\n\t\t\t\tcout << \" \" << k << \" ra: \" << sol[0].C[k]->ra*180/M_PI << \" dec: \" << sol[0].C[k]->dec*180/M_PI << endl; \n \t}\n \telse cout << endl;\n }\n#endif\n\n //send a return value to the flight computer\n sclog(debug, (char*)\"processingLoop: sending image return value.\");\n StarcamReturn returnStruct;\n globalImages[imageIndex].createReturnStruct(&returnStruct);\n rtn_str = CamCommunicator::buildReturn(&returnStruct);\n //remove all newlines and add a single one at the end\n\t string::size_type pos = rtn_str.find(sought, 0);\n\t while (pos != string::npos) {\n rtn_str.replace(pos, sought.size(), \"\");\n pos = rtn_str.find(sought, pos - sought.size());\n }\n rtn_str += \"\\n\";\n udp_bcast(sock, SC_PORT, strlen(rtn_str.c_str()), rtn_str.c_str(), 0);\n cout << \"PLOOP BROADCASTING string \" << rtn_str << endl;\n copyFlag=1;\n unlock(&imageLock[imageIndex], \"imageLock\", \"processingLoop\");\n\n //signal that processing is complete\n lock(&imageReadyLock[imageIndex], \"imageReadyLock\", \"processingLoop\");\n globalImageReadyFlags[imageIndex] = 0;\n unlock(&imageReadyLock[imageIndex], \"imageReadyLock\", \"processingLoop\");\n pthread_cond_signal(&processingCompleteCond[imageIndex]);\n\n\n imageIndex = (imageIndex == 0)?1:0;\n }\n return NULL;\n}\n\n/*\n * ReadLoop:\n *\n * starts the server that listens for new socket connections\n * the interpretCommand function is used by the server to interpret any \n * received commands\n */\nvoid* ReadLoop(void* arg)\n{\n int sock, port;\n char peer[UDP_MAXHOST];\n\tchar buf[UDP_MAXSIZE];\t// receive buffer\n\tint recvlen;\t\t\t// # bytes received\n\tstring line = \"\";\n string sought = \"\\n\";\n string rtnStr = \"\";\n string returnString = \"\";\n\tstring::size_type pos;\n\n /* create a socket */\n sock = udp_bind_port(BAD_PORT, 1);\n\n if (sock == -1)\n cout << \"Unable to bind to port\" << endl;\n\n while(1) {\n recvlen = udp_recv(sock, SC_TIMEOUT, peer, &port, UDP_MAXSIZE, buf);\n buf[recvlen] = '\\0';\n line += buf;\n while ((pos = line.find(\"\\n\",0)) != string::npos) {\n if ((rtnStr = (*interpretCommand)(line.substr(0,pos))) != \"\") {//don't send blank returin\n returnString = CamCommunicator::buildReturnString(rtnStr);\n string::size_type pos = returnString.find(sought, 0);\n\twhile (pos != string::npos) {\n returnString.replace(pos, sought.size(), \"\");\n pos = returnString.find(sought, pos - sought.size());\n }\n returnString += \"\\n\";\n if (udp_bcast(sock, SC_PORT, strlen(returnString.c_str()), returnString.c_str(), 0))\n perror(\"sendto\");\n cout << \"ReadLoop BROADCASTING string \" << returnString << endl;\n }\n line = line.substr(pos+1, line.length()-(pos+1)); //set line to text after \"\\n\"\n\t\t}\n }\n return NULL;\n}\n\n/*\n\ninterpretCommand:\n\ninterprets a command\nreturns a string to be sent back to flight computer\nwhen unsuccessful, the return string should start with \"Error:\"\nwhen successful, return \"<command echo> successful\"\n\nany part of the public interface of one of the global objects can be exposed\nto flight computer by adding an entry here\n\n*/\nstring interpretCommand(string cmd)\n{\n sclog(info, (char*)\"Interpreting command: \\\"%s\\\"\", cmd.c_str());\n //separate command part of cmd from the value part\n string::size_type valPos = cmd.find(\"=\", 0);\n string valStr = \"\";\n istringstream sin; //for reading value portion of command\n int imageIndex = 0;\n if (valPos != string::npos) { //cmd contains a value part\n valStr = cmd.substr(valPos+1, cmd.length()-(valPos+1));\n sin.str(valStr);\n cmd = cmd.substr(0, valPos);\n }\n if (cmd[0] == 'C') //command is for the camera\n {\n if (cmd == \"CtrigExp\") { //trigger a camera exposure\n if (globalCam.getPictureInterval() != 0) \n\t return \"Error: Not in triggered-exposure mode\";\n lock(&cameraTriggerLock, \"cameraTriggerLock\", \"interpretCommand\");\n globalCameraTriggerFlag = 1;\n pthread_cond_signal(&cameraTriggerCond);\n unlock(&cameraTriggerLock, \"cameraTriggerLock\", \"interpretCommand\");\n return (cmd + \" successful\");\n }\n else if (cmd == \"CtrigFocus\") { //trigger autofocus\n LENS_ERROR err;\n lock(&camLock, \"camLock\", \"interpretCommand\");\n //also don't allow processing to take place\n lock(&imageLock[0], \"imageLock\", \"interpretCommand\");\n lock(&imageLock[1], \"imageLock\", \"interpretCommand\");\n BlobImage img;\n err = globalCam.autoFocus(&globalImages[imageIndex], 0, imgPath);\n unlock(&imageLock[1], \"imageLock\", \"interpretCommand\");\n unlock(&imageLock[0], \"imageLock\", \"interpretCommand\");\n unlock(&camLock, \"camLock\", \"interpretCommand\");\n if (err != LE_NO_ERROR)\n\t return (string)\"Error: Autofocus returned: \" + CLensAdapter::getErrorString(err);\n else return (cmd + \" successful\");\n }\n else if (cmd == \"CtrigFocusF\") { //trigger forced move autofocus\n LENS_ERROR err;\n lock(&camLock, \"camLock\", \"interpretCommand\");\n //also don't allow processing to take place\n lock(&imageLock[0], \"imageLock\", \"interpretCommand\");\n lock(&imageLock[1], \"imageLock\", \"interpretCommand\");\n BlobImage img;\n err = globalCam.autoFocus(&img, 1, imgPath);\n unlock(&imageLock[1], \"imageLock\", \"interpretCommand\");\n unlock(&imageLock[0], \"imageLock\", \"interpretCommand\");\n unlock(&camLock, \"camLock\", \"interpretCommand\");\n if (err != LE_NO_ERROR)\n\t return (string)\"Error: Autofocus returned: \" + CLensAdapter::getErrorString(err);\n else return (cmd + \" successful\");\n }\n else if (cmd == \"CsetExpTime\") { //set exposure time\n if (valStr == \"\" || valStr == \" \")\n\t return (string)\"Error: the command \" + cmd + \" requires a value\";\n double expTime;\n sin >> expTime;\n expTime /= 1000.0; //changed to using ms\n lock(&camLock, \"camLock\", \"interpretCommand\");\n globalCam.SetExposureTime(expTime);\n unlock(&camLock, \"camLock\", \"interpretCommand\");\n if (maintainInitFile(cmd, valStr) == 0)\n\t return (cmd + \" successful\");\n else return (string)\"Error: \" + cmd + \"=\" + valStr + \" failed to update init file\";\n }\n else if (cmd == \"CsetExpInt\") { //set exposure interval (0 for triggered)\n if (valStr == \"\" || valStr == \" \")\n\t return (string)\"Error: the command \" + cmd + \" requires a value\";\n //if previously in triggered mode, trigger any waiting exposure\n //when switching back to triggered mode, this may cause an extra exposure\n if (globalCam.getPictureInterval() == 0) {\n\t lock(&cameraTriggerLock, \"cameraTriggerLock\", \"interpretCommand\");\n\t globalCameraTriggerFlag = 1;\n\t pthread_cond_signal(&cameraTriggerCond);\n\t unlock(&cameraTriggerLock, \"cameraTriggerLock\", \"interpretCommand\");\n }\n int expInt;\n sin >> expInt;\n lock(&camLock, \"camLock\", \"interpretCommand\");\n globalCam.setPictureInterval(expInt);\n unlock(&camLock, \"camLock\", \"interpretCommand\");\n if (maintainInitFile(cmd, valStr) == 0)\n\t return (cmd + \" successful\");\n else return (string)\"Error: \" + cmd + \"=\" + valStr + \" failed to update init file\";\n }\n else if (cmd == \"CsetFocRsln\") { //set focus resolution\n if (valStr == \"\" || valStr == \" \")\n\t return (string)\"Error: the command \" + cmd + \" requires a value\";\n unsigned int resolution;\n sin >> resolution;\n if (resolution == 0) return \"Error: focus resolution must be nonzero.\";\n lock(&camLock, \"camLock\", \"interpretCommand\");\n globalCam.setFocusResolution(resolution);\n unlock(&camLock, \"camLock\", \"interpretCommand\");\n if (maintainInitFile(cmd, valStr) == 0)\n\t return (cmd + \" successful\");\n else return (string)\"Error: \" + cmd + \"=\" + valStr + \" failed to update init file\";\n }\n else if (cmd == \"CsetFocRnge\") { //set focus range\n if (valStr == \"\" || valStr == \" \")\n\t return (string)\"Error: the command \" + cmd + \" requires a value\";\n unsigned int range;\n sin >> range;\n if (range == 0) return \"Error: focus range must be nonzero.\";\n lock(&camLock, \"camLock\", \"interpretCommand\");\n globalCam.setFocusRange(range);\n unlock(&camLock, \"camLock\", \"interpretCommand\");\n if (maintainInitFile(cmd, valStr) == 0)\n\t return (cmd + \" successful\");\n else return (string)\"Error: \" + cmd + \"=\" + valStr + \" failed to update init file\";\n }\n else if (cmd == \"Cpower\") {\n lock(&camLock, \"camLock\", \"interpretCommand\");\n powerCycle();\n unlock(&camLock, \"camlock\", \"interpretCommand\");\n return (cmd + \" successful\");\n }\n else {\n sclog(warning, (char*)\"interpretCommand: bad camera command\");\n return (string)\"Error: Failed to parse camera command: \" + cmd;\n }\n }\n else if (cmd[0] == 'I') //command is for images\n {\n //TODO this needs to be adapted for two cameras (one file for each camera)\n if (cmd == \"IsetBadpix\") { //set a bad pixel, value should have form \"x y\"\n if (valStr == \"\" || valStr == \" \")\n\t return (string)\"Error: the command \" + cmd + \" requires a value\";\n int x, y, camnum;\n sin >> camnum >> x >> y;\n ofstream fout(badpixFilename, ios::out | ios::app);\n if (!fout) return \"Error: failed to open bad pixel file\";\n fout << x << \" \" << y << \"\\n\"; //assume same entry won't be made multiple times\n fout.close();\n //reload bad pixels into map (in frameblob)\n for (int i=0; i<2; i++) {\n\t lock(&imageLock[i], \"imageLock\", \"interpretCommand\");\n\t globalImages[i].getFrameBlob()->load_badpix(badpixFilename);\n\t unlock(&imageLock[i], \"imageLock\", \"interpretCommand\");\n }\n return (cmd + \" successful\");\n }\n else if (cmd == \"IsetMaxBlobs\") { //set maximum number of blobs that will be found\n if (valStr == \"\" || valStr == \" \")\n\t return (string)\"Error: the command \" + cmd + \" requires a value\";\n unsigned int maxblobs;\n sin >> maxblobs;\n for (int i=0; i<2; i++) {\n\t lock(&imageLock[i], \"imageLock\", \"interpretCommand\");\n\t globalImages[i].getFrameBlob()->set_maxblobs(maxblobs);\n\t unlock(&imageLock[i], \"imageLock\", \"interpretCommand\");\n }\n if (maintainInitFile(cmd, valStr) == 0)\n\t return (cmd + \" successful\");\n else return (string)\"Error: \" + cmd + \"=\" + valStr + \" failed to update init file\";\n }\n else if (cmd == \"IsetGrid\") { //set grid size for blob detection\n if (valStr == \"\" || valStr == \" \")\n\t return (string)\"Error: the command \" + cmd + \" requires a value\";\n unsigned int grid;\n sin >> grid;\n for (int i=0; i<2; i++) {\n\t lock(&imageLock[i], \"imageLock\", \"interpretCommand\");\n\t globalImages[i].getFrameBlob()->set_grid(grid);\n\t unlock(&imageLock[i], \"imageLock\", \"interpretCommand\");\n }\n if (maintainInitFile(cmd, valStr) == 0)\n\t return (cmd + \" successful\");\n else return (string)\"Error: \" + cmd + \"=\" + valStr + \" failed to update init file\";\n }\n else if (cmd == \"IsetThreshold\") { //set threshold (in # sigma) for blob detection\n if (valStr == \"\" || valStr == \" \")\n\t return (string)\"Error: the command \" + cmd + \" requires a value\";\n double threshold;\n sin >> threshold;\n for (int i=0; i<2; i++) {\n\t lock(&imageLock[i], \"imageLock\", \"interpretCommand\");\n\t globalImages[i].getFrameBlob()->set_threshold(threshold);\n\t unlock(&imageLock[i], \"imageLock\", \"interpretCommand\");\n }\n if (maintainInitFile(cmd, valStr) == 0)\n\t return (cmd + \" successful\");\n else return (string)\"Error: \" + cmd + \"=\" + valStr + \" failed to update init file\";\n }\n else if (cmd == \"IsetDisttol\") { //set minimum distance squared (pixels) between blobs\n if (valStr == \"\" || valStr == \" \")\n\t return (string)\"Error: the command \" + cmd + \" requires a value.\";\n int disttol;\n sin >> disttol;\n for (int i=0; i<2; i++) {\n\t lock(&imageLock[i], \"imageLock\", \"interpretCommand\");\n\t globalImages[i].getFrameBlob()->set_disttol(disttol);\n\t unlock(&imageLock[i], \"imageLock\", \"interpretCommand\");\n }\n if (maintainInitFile(cmd, valStr) == 0)\n\t return (cmd + \" successful\");\n else return (string)\"Error: \" + cmd + \"=\" + valStr + \" failed to update init file\";\n }\n else {\n sclog(warning, (char*)\"interpretCommand: bad image command\");\n return (string)\"Error: failed to parse image command: \" + cmd;\n }\n }\n else if (cmd[0] == 'L') //command is for the lens\n {\n if (cmd == \"Lmove\") { //make a precise (proportional feedback) move\n if (valStr == \"\" || valStr == \" \")\n\t return (string)\"Error: the command \" + cmd + \" requires a value\";\n int counts, remaining;\n sin >> counts;\n lock(&camLock, \"camLock\", \"interpretCommand\");\n LENS_ERROR err = globalCam.getLensAdapter()->preciseMove(counts, remaining, 0);\n unlock(&camLock, \"camLock\", \"interpretCommand\");\n sclog(data, (char*)\"interpretCommand: Lens move of: %d counts has %d left\", counts, remaining);\n if (err == LE_NO_ERROR) return (cmd + \" successful\");\n else return (string)\"Error: Move returned \" + CLensAdapter::getErrorString(err);\n } \n else if (cmd == \"Lforce\") { //make a forced move (ignore \"false\" stops)\n if (valStr == \"\" || valStr == \" \")\n\t return (string)\"Error: the command \" + cmd + \" requires a value\";\n int counts, remaining;\n sin >> counts;\n lock(&camLock, \"camLock\", \"interpretCommand\");\n LENS_ERROR err = globalCam.getLensAdapter()->preciseMove(counts, remaining, 1);\n unlock(&camLock, \"camLock\", \"interpretCommand\");\n sclog(data, (char*)\"interpretCommand: Forced lens move of: %d counts has %d left\", counts, remaining);\n if (err == LE_NO_ERROR) return (cmd + \" successful\");\n else return (string)\"Error: Forced move returned \" + CLensAdapter::getErrorString(err);\n } \n else if (cmd == \"LsetTol\") { //set tolerance of precise moves\n if (valStr == \"\" || valStr == \" \")\n\t return (string)\"Error: the command \" + cmd + \" requires a value\";\n unsigned int tol;\n sin >> tol;\n lock(&camLock, \"camLock\", \"interpretCommand\");\n globalCam.getLensAdapter()->setFocusTol(tol);\n unlock(&camLock, \"camLock\", \"interpretCommand\");\n if (maintainInitFile(cmd, valStr) == 0)\n\t return (cmd + \" successful\");\n else return (string)\"Error: \" + cmd + \"=\" + valStr + \" failed to update init file\";\n } \n else if (cmd == \"L\") { //try to send arbitrary lens command\n string returnVal;\n sin >> cmd; //read the lens command\n lock(&camLock, \"camLock\", \"interpretCommand\");\n globalCam.getLensAdapter()->runCommand(cmd, returnVal);\n unlock(&camLock, \"camLock\", \"interpretCommand\");\n sclog(data, (char*)\"interpretCommand: Lens command: \\\"%s\\\" returned \\\"%s\\\"\", cmd.c_str(), returnVal.c_str());\n return (cmd + \" returned: \" + returnVal);\n }\n else {\n sclog(warning, (char*)\"interpretCommand: bad lens command\");\n return (string)\"Error: failed to parse lens command: \" + cmd;\n }\n }\n else if (cmd[0] == 'O') //overall commands\n {\n if (cmd == \"Oconf\") { //send back current operating configuration\n ostringstream sout;\n sout << \"<conf>\";\n lock(&camLock, \"camLock\", \"interpretCommand\");\n sout << globalCam.getPictureInterval() << \" \"\n\t << globalCam.GetExposureTime() << \" \"\n\t << globalCam.getFocusResolution() << \" \"\n//\t << globalCam.getFocusRange() << \" \"\n\t << globalCam.getLensAdapter()->getFocusTol() << \" \";\n unlock(&camLock, \"camLock\", \"interpretCommand\");\n lock(&imageLock[0], \"imageLock\", \"interpretCommand\");\n sout << globalImages[0].getFrameBlob()->get_maxblobs() << \" \"\n\t << globalImages[0].getFrameBlob()->get_grid() << \" \"\n\t << globalImages[0].getFrameBlob()->get_threshold() << \" \"\n\t << globalImages[0].getFrameBlob()->get_disttol();\n unlock(&imageLock[0], \"imageLock\", \"interpretCommand\");\n return sout.str();\n }\n else if (cmd == \"Oviewer\") { //switch which camera's image is shown by the viewer\n if (valStr == \"\" || valStr == \" \")\n return (string)\"Error: the command \" + cmd + \" requires a value\";\n int which;\n sin >> which;\n if (which == 0) {\n if (system(\"ln -s -f /data/etc/current_good.sbig /data/etc/current_new.sbig\") < 0)\n return (cmd + \" unable to create link\");\n system(\"mv /data/etc/current_new.sbig /data/etc/current.sbig\");\n return (cmd + \" successful\");\n } else if (which == 1) {\n if (system(\"ln -s -f /data/etc/current_bad.sbig /data/etc/current_new.sbig\") < 0)\n return (cmd + \" unable to create link\");\n system(\"mv /data/etc/current_new.sbig /data/etc/current.sbig\");\n return (cmd + \" successful\");\n } else if (which == 2) {\n if (system(\"ln -s -f /data/etc/current_ugly.sbig /data/etc/current_new.sbig\") < 0)\n return (cmd + \" unable to create link\");\n system(\"mv /data/etc/current_new.sbig /data/etc/current.sbig\");\n return (cmd + \" successful\");\n } else return (string)\"Error: \" + cmd + \" invalid value\";\n }\n else if (cmd == \"OshowBox\") {\n#if USE_IMAGE_VIEWER\n if (valStr == \"\" || valStr == \" \")\n\t return (string)\"Error: the command \" + cmd + \" requires a value.\";\n\t sin >> showBoxes;\n if (maintainInitFile(cmd, valStr) == 0)\n\t return (cmd + \" successful\");\n else return (string)\"Error: \" + cmd + \"=\" + valStr + \" failed to update init file\";\n#else\n return (cmd + \"successful, not implemented\");\n#endif\n }\n else {\n sclog(warning, (char*)\"interpretCommand: bad overall command\");\n return (string)\"Error: failed to parse overall command: \" + cmd;\n }\n }\n else {\n sclog(warning, (char*)\"interpretCommand: Unknown device specifier: '%c'\", cmd[0]);\n return (string)\"Error: Unknown device specifier (1st char)\" + cmd.substr(0,1);\n }\n\n return \"Error: execution should never reach here!!\";\n}\n\n/*\n * powerCycle:\n *\n * uses a switch on the parallel port to power cycle the star cameras\n */\nvoid powerCycle()\n{\n static bool hasperms = false;\n\n if (!hasperms) {\n if (ioperm(0x378, 0x0F, 1) != 0) {\n sclog(warning, (char*)\"powerCycle couldn't set port permissions...are you root?\");\n return;\n }\n else hasperms = true;\n }\n\n sclog(info, (char*)\"Power cycling the cameras!\");\n if (globalCam.CloseDevice() != CE_NO_ERROR)\n sclog(warning, (char*)\"Trouble safely shutting down camera, proceeding anyway.\");\n if (globalCam.CloseDriver() != CE_NO_ERROR)\n sclog(warning, (char*)\"Trouble safely shutting down driver\");\n\n outb(0xFF, 0x378);\n usleep(1000000);\n outb(0x00, 0x378);\n\n PAR_ERROR err;\n sleep(3);\n while ((err = openCameras()) != CE_NO_ERROR) {\n sclog(error, (char*)\"Problem reconnecting to camera: %s\", globalCam.GetErrorString(err).c_str());\n sleep(5);\n }\n sclog(info, (char*)\"Star camera reconnected\");\n}\n\n/*\n\nlock:\n\nsimply calls pthread_mutex_lock, but provides debugging information\n\n*/\nvoid lock(pthread_mutex_t* mutex, const char* lockname, const char* funcname)\n{\n#if SC_THREAD_DEBUG\n cout << \"[Starcam debug]: \" << funcname << \": Waiting for \" << lockname << endl;\n#endif\n pthread_mutex_lock(mutex);\n#if SC_THREAD_DEBUG\n cout << \"[Starcam debug]: \" << funcname << \": Obtained \" << lockname << endl;\n#endif\n}\n\n/*\n\nunlock:\n\nsimply calls pthread_mutex_unlock but provides debugging information\n\n*/\nvoid unlock(pthread_mutex_t* mutex, const char* lockname, const char* funcname)\n{\n#if SC_THREAD_DEBUG\n cout << \"[Starcam debug]: \" << funcname << \": Releasing \" << lockname << endl;\n#endif\n pthread_mutex_unlock(mutex);\n}\n\n/*\n\nwait:\n\nsimply calls pthread_cond_wait, but provides debuging information\n\n*/\nvoid wait(pthread_cond_t* cond, pthread_mutex_t* mutex, const char* condname, \n const char* lockname, const char* funcname)\n{\n#if SC_THREAD_DEBUG\n cout << \"[Starcam debug]: \" << funcname << \": Waiting for \" << condname \n << \" and releasing \" << lockname << endl;\n#endif\n pthread_cond_wait(cond, mutex);\n}\n\n\n/*\n\ninitCommands:\n\nreads and executes commands stored in the init command file\nwhen an error occurs, -1 is returned otherwise returns 0\n\n*/\nint initCommands()\n{\n sclog(info, (char*)\"Running stored initialization commands\");\n //open file for reading...if it fails try creating it\n ifstream fin(initFilename, ios::in);\n if (!fin) {\n //try creating the file (by opening for writing)\n ofstream temp(initFilename, ios::out);\n if (!temp) return -1;\n temp.close();\n fin.open(initFilename, ios::in);\n if (!fin) return -1;\n }\n\n char buf[256];\n string cmd, retVal;\n\n while (!fin.eof())\n {\n fin.getline(buf, 256);\n cmd = buf;\n //check for empty file before running commands\n if (cmd == \"\") return 0;\n retVal = interpretCommand(cmd);\n sclog(debug, (char*)\"init command returned: %s\", retVal.c_str());\n if (retVal.substr(0,5) == \"Error\") {\n return -1;\n }\n }\n\n fin.close();\n return 0;\n}\n\n/*\n\nmaintainInitFile:\n\nwhen commands are executed that change starcam state, they need to be stored\nso if program needs to restart it's state will be unchanged\nThis function maintains the file so that it has the minimum necessary number of\ncommands that need to be read and excuted.\nReturns -1 if an error occurs, 0 otherwise\n\n*/\nint maintainInitFile(string cmd, string val)\n{\n //open file for reading...if it fails try creating it\n ifstream fin(initFilename, ios::in);\n if (!fin) {\n //try creating the file (by opening for writing)\n ofstream temp(initFilename, ios::out);\n if (!temp) return -1;\n temp.close();\n fin.open(initFilename, ios::in);\n if (!fin) return -1;\n }\n\n ostringstream sout; //what will be output to file at end\n int found = 0; //indicates if command was found in file\n char buf[256];\n string cmd_in;\n string::size_type valPos; //position of command-value separator in commands\n\n //read in file contents and replace exisitng version of cmd if found\n while (!fin.eof())\n {\n fin.getline(buf, 256);\n cmd_in = buf;\n valPos = cmd_in.find(\"=\", 0);\n if (valPos != string::npos) cmd_in = cmd_in.substr(0,valPos);\n if (cmd == cmd_in)\n { //cmd was found in the file, only keep the new version\n sout << cmd << ((val.length()!=0)?\"=\":\"\") << val << \"\\n\";\n found = 1;\n } else if (cmd_in != \"\") {\n sout << buf << \"\\n\";\n }\n }\n fin.close();\n if (!found) sout << cmd << ((val.length()!=0)?\"=\":\"\") << val << \"\\n\";\n\n //output the revised contents to file\n ofstream fout(initFilename, ios::out | ios::trunc);\n if (!fout) return -1;\n fout << sout.str();\n fout.close();\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6535142064094543, "alphanum_fraction": 0.6596794128417969, "avg_line_length": 16.255319595336914, "blob_id": "440e6b3655bd11b42d2cdfa4291be452a5f6658d", "content_id": "f995b117cbc3317df1ece10200d6955da562acb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 812, "license_type": "no_license", "max_line_length": 73, "num_lines": 47, "path": "/stars/code/solving/finding/leveler.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__FINDING__LEVELER_H\n#define SOLVING__FINDING__LEVELER_H\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n}\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Solving\n{\n namespace Finding\n {\n class Leveler;\n }\n}\n\nclass Solving::Finding::Leveler\n{\n public:\n Leveler(Parameters::Manager& params);\n ~Leveler();\n void level(Shared::Image::Raw& image, unsigned short leveled[]);\n\n private:\n bool is_inbounds(int& i, int& j, int& width, int& height);\n\n int image_width;\n int image_height;\n unsigned short* coarse4;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6790540814399719, "alphanum_fraction": 0.6959459185600281, "avg_line_length": 20.071428298950195, "blob_id": "4639cc8eb61864a4f740f2471a8c1a7534d1cc09", "content_id": "3e7d0dca050a62c7ab692cadb7c11a15930ff5aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 297, "license_type": "no_license", "max_line_length": 73, "num_lines": 14, "path": "/stars/code/shared/network/client.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"client.h\"\n\nusing namespace Shared::Network;\n\nClient::Client()\n{\n counter_fcp = -1;\n}\n\n" }, { "alpha_fraction": 0.6459963917732239, "alphanum_fraction": 0.648404598236084, "avg_line_length": 27.620689392089844, "blob_id": "3f3bcda9f9510919113088599da02755b4d5ca91", "content_id": "07775c65632ac0bfd59379f8ed4f481472f164a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1662, "license_type": "no_license", "max_line_length": 73, "num_lines": 58, "path": "/stars/code/solving/update.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"update.h\"\n#include \"../shared/update.h\"\n#include \"../shared/image/status.h\"\n#include \"../shared/solving/settings.h\"\n#include \"../shared/general/quit.h\"\n#include \"logger.h\"\n\n#define shared_status (*(Shared::Image::status_solver_for_main.w))\n#define shared_settings (*(Shared::Solving::settings.r))\n\nvoid Solving::update_shared()\n{\n Shared::update(Shared::ThreadNames::solver);\n logger.update();\n}\n\nbool Solving::done()\n{\n using namespace Shared::Image;\n\n if (Shared::General::quit) {\n return true;\n }\n\n if (shared_status.stage == Status::done) {\n return true;\n }\n\n update_shared();\n\n if (shared_status.abort_counter != shared_settings.abort_counter) {\n shared_status.abort_counter = shared_settings.abort_counter;\n shared_status.stage = Status::done;\n shared_status.reason_for_being_done = Status::aborted;\n Shared::Image::status_solver_for_main.share();\n return true;\n }\n\n if (shared_status.age.time() > shared_settings.timeout) {\n shared_status.stage = Status::done;\n shared_status.reason_for_being_done = Status::timed_out;\n Shared::Image::status_solver_for_main.share();\n return true;\n }\n if (!shared_settings.enabled) {\n shared_status.stage = Status::done;\n shared_status.reason_for_being_done = Status::not_solving;\n Shared::Image::status_solver_for_main.share();\n return true;\n }\n return false;\n}\n\n" }, { "alpha_fraction": 0.5580000281333923, "alphanum_fraction": 0.5781052708625793, "avg_line_length": 38.579166412353516, "blob_id": "d7204810d58e26dde4465991ba6323b63e6c7fc8", "content_id": "333d4412d040fe01bde01e3d7e89027c9bc9912f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9501, "license_type": "no_license", "max_line_length": 143, "num_lines": 240, "path": "/stars/code/displaying/autofocus.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"autofocus.h\"\n#if defined(_MSC_VER)\n #include <windows.h>\n#endif\n#include <boost/format.hpp>\n#include <limits>\n#include \"GL/gl.h\"\n#include \"GL/glu.h\"\n#include \"glhelper.h\"\n#include \"block.h\"\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include \"../shared/autofocus/results.h\"\n#include \"../shared/autofocus/requests.h\"\n#include \"../shared/autofocus/datapoints.h\"\n#include \"../tools/quick_cout.h\"\n\nusing namespace Displaying;\nusing namespace Shared::Autofocus;\nusing std::min;\n#define shared_results (*(results_solver_to_main.r))\n#define shared_requests (*(requests_network_to_main.r))\n#define shared_datapoints (*(datapoints_lens_to_main.r))\n\nAutofocus::Autofocus()\n{\n change_size(200, 100);\n}\n\nbool Autofocus::display_enabled()\n{\n if (shared_requests.display_mode == xC_autofocus_display_mode_auto) {\n if (shared_results.mode != Results::mode_not_running) {\n return true;\n }\n }\n if (shared_requests.display_mode == xC_autofocus_display_mode_on) {\n return true;\n }\n return false;\n}\n\nvoid Autofocus::get_plot_ranges(double& value_min, double& value_max, double& focus_min,\n double& focus_max, datapoints_t metric_type, bool any_metric_except_sobel)\n{\n value_min = std::numeric_limits<double>::infinity();\n value_max = 0.0;\n focus_min = shared_requests.focus_search_min;\n focus_max = shared_requests.focus_search_max;\n for (unsigned int i=0; i<shared_datapoints.curves.size(); i++) {\n if (shared_datapoints.curves[i].type == metric_type || (any_metric_except_sobel && shared_datapoints.curves[i].type != metric_sobel)) {\n for (unsigned int j=0; j<shared_datapoints.curves[i].points.size(); j++) {\n if (shared_datapoints.curves[i].points[j].value > value_max) {\n value_max = shared_datapoints.curves[i].points[j].value;\n }\n if (shared_datapoints.curves[i].points[j].value < value_min) {\n value_min = shared_datapoints.curves[i].points[j].value;\n }\n if (shared_datapoints.curves[i].points[j].focus > focus_max) {\n focus_max = shared_datapoints.curves[i].points[j].focus;\n }\n if (shared_datapoints.curves[i].points[j].focus < focus_min) {\n focus_min = shared_datapoints.curves[i].points[j].focus;\n }\n }\n }\n }\n}\n\nvoid Autofocus::set_curve_color_and_width(datapoints_t metric_type)\n{\n switch (metric_type) {\n case metric_brightest_blob_flux:\n GL::Color4f(0.33, 0.33, 0.75, 1.0);\n glLineWidth(2.0);\n break;\n case metric_star_flux:\n GL::Color4f(0.5, 0.0, 0.15, 1.0);\n glLineWidth(1.0);\n break;\n case metric_sobel:\n GL::Color4f(0.0, 0.5, 0.1, 1.0);\n glLineWidth(2.0);\n break;\n default:\n GL::Color4f(0.2, 0.2, 0.2, 1.0);\n glLineWidth(1.0);\n break;\n }\n}\n\nvoid Autofocus::plot_curves(double value_min, double value_max, double focus_min, double focus_max,\n double plot_offset, datapoints_t metric_type, double plot_width, double plot_height)\n{\n for (unsigned int i=0; i<shared_datapoints.curves.size(); i++) {\n if (shared_datapoints.curves[i].type == metric_type) {\n set_curve_color_and_width(shared_datapoints.curves[i].type);\n glBegin(GL_LINE_STRIP);\n\n double curve_progress = 2.0*shared_datapoints.curves[i].age_since_last_datapoint_added.time();\n curve_progress *= plot_width;\n bool last_point_was_displayable = false;\n double last_x = 0.0;\n double last_y = 0.0;\n for (unsigned int j=0; j<shared_datapoints.curves[i].points.size(); j++) {\n double focus = shared_datapoints.curves[i].points[j].focus;\n double value = shared_datapoints.curves[i].points[j].value;\n double x = (focus-focus_min) / (focus_max-focus_min);\n double y = (value-value_min) / (value_max-value_min) + plot_offset;\n x *= plot_width;\n y *= plot_height;\n if (x <= curve_progress) {\n glVertex2d(x, y);\n last_point_was_displayable = true;\n last_x = x;\n last_y = y;\n }\n if (x > curve_progress && last_point_was_displayable) {\n last_point_was_displayable = false;\n double cropped_x = min(x, curve_progress);\n double fraction = (cropped_x - last_x) / (x - last_x);\n double cropped_y = (y-last_y)*fraction + last_y;\n glVertex2d(cropped_x, cropped_y);\n }\n }\n glEnd();\n glLineWidth(2.0);\n }\n }\n double point_halfsize = 1.25;\n for (unsigned int i=0; i<shared_datapoints.curves.size(); i++) {\n if (shared_datapoints.curves[i].type == metric_type) {\n set_curve_color_and_width(shared_datapoints.curves[i].type);\n\n double curve_progress = 2.0*shared_datapoints.curves[i].age_since_last_datapoint_added.time();\n curve_progress *= plot_width;\n for (unsigned int j=0; j<shared_datapoints.curves[i].points.size(); j++) {\n double focus = shared_datapoints.curves[i].points[j].focus;\n double value = shared_datapoints.curves[i].points[j].value;\n double x = (focus-focus_min) / (focus_max-focus_min);\n double y = (value-value_min) / (value_max-value_min) + plot_offset;\n x *= plot_width;\n y *= plot_height;\n if (x <= curve_progress) {\n glBegin(GL_POLYGON);\n glVertex2f((GLfloat) (x - point_halfsize), (GLfloat) (y - point_halfsize));\n glVertex2f((GLfloat) (x - point_halfsize), (GLfloat) (y + point_halfsize));\n glVertex2f((GLfloat) (x + point_halfsize), (GLfloat) (y + point_halfsize));\n glVertex2f((GLfloat) (x + point_halfsize), (GLfloat) (y - point_halfsize));\n glEnd();\n }\n }\n }\n }\n}\n\nvoid Autofocus::draw(Position &position)\n{\n if (shared_results.mode == Results::mode_running) {\n set_title(\"Autofocus (running)\");\n } else if (shared_results.mode == Results::mode_finished_and_gracing) {\n set_title(\"Autofocus (finished)\");\n }\n\n glBindTexture(GL_TEXTURE_2D, textures->get(Textures::basic_drawing)); // Bind 0\n GL::Color4f(1.0, 1.0, 1.0, 1.0);\n begin_draw(position);\n draw_border();\n draw_title();\n\n double plot_padding = 10.0;\n double plot_width = width() - 2.0*plot_padding;\n double plot_height = height() - 2.0*plot_padding - 2.0*text_height;\n double plot_offset = 2.0 / plot_height;\n\n\tglDisable(GL_TEXTURE_2D);\n glPushMatrix();\n glTranslatef((GLfloat) plot_padding, (GLfloat) (text_height+plot_padding), 0.0f);\n GL::Color4f(1.0, 1.0, 1.0, 1.0);\n glBegin(GL_LINES);\n glVertex2d(0.0, 0.0);\n glVertex2d(0.0, (GLfloat) plot_height);\n glVertex2d(0.0, 0.0);\n glVertex2d((GLfloat) plot_width, 0.0);\n glEnd();\n\n double value_min, value_max, focus_min, focus_max;\n double focus_min_all, focus_max_all;\n get_plot_ranges(value_min, value_max, focus_min_all, focus_max_all, metric_brightest_blob_flux, true);\n\n get_plot_ranges(value_min, value_max, focus_min, focus_max, metric_star_flux);\n plot_curves(0.0, value_max*1.1, focus_min_all, focus_max_all, plot_offset,\n metric_star_flux, plot_width, plot_height);\n\n get_plot_ranges(value_min, value_max, focus_min, focus_max, metric_brightest_blob_flux);\n plot_curves(0.0, value_max*1.1, focus_min_all, focus_max_all, plot_offset,\n metric_brightest_blob_flux, plot_width, plot_height);\n\n if (shared_results.best_focus_known) {\n GL::Color4f(0.95, 0.09, 0.87, 1.0);\n double focus_x = (shared_results.best_focus - focus_min_all) / (focus_max_all - focus_min_all);\n focus_x *= plot_width;\n double arrow_y = -21.0;\n glBegin(GL_LINES);\n glVertex2d((GLfloat) focus_x, arrow_y);\n glVertex2d((GLfloat) focus_x, arrow_y+17.0);\n glVertex2d((GLfloat) focus_x-5.0, arrow_y+11.0);\n glVertex2d((GLfloat) focus_x, arrow_y+17.0);\n glVertex2d((GLfloat) focus_x+5.0, arrow_y+11.0);\n glVertex2d((GLfloat) focus_x, arrow_y+17.0);\n glEnd();\n }\n\n glPopMatrix();\n\tglEnable(GL_TEXTURE_2D);\n\n Position text_pos;\n std::string focus_str;\n double focus_str_width = 1.0;\n double focus_str_heigth = 1.0;\n\n focus_str = (boost::format(\"%i\")%focus_min).str();\n text_pos.x = plot_padding;\n text_pos.y = plot_padding + text_height;\n draw_text(focus_str, text_pos);\n focus_str = (boost::format(\"%i\")%focus_max).str();\n get_text_size(focus_str, focus_str_width, focus_str_heigth);\n text_pos.x = plot_padding + plot_width - focus_str_width;\n text_pos.y = plot_padding + text_height;\n draw_text(focus_str, text_pos);\n\n end_draw();\n glBindTexture(GL_TEXTURE_2D, 0); // unBind 0\n}\n\n" }, { "alpha_fraction": 0.6733181476593018, "alphanum_fraction": 0.6755986213684082, "avg_line_length": 23.02739715576172, "blob_id": "2438dd9db17f189af65643002e4d938047f06884", "content_id": "288d15211c04d9fecf84649faffc377167ab0a8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1755, "license_type": "no_license", "max_line_length": 83, "num_lines": 73, "path": "/stars/code/parameters/group.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef PARAMETERS__GROUP_H\n#define PARAMETERS__GROUP_H\n\n#include <string>\n#include <boost/program_options.hpp>\n#include <typeinfo>\n#include \"../logger_main.h\"\n\n#ifdef _MSC_VER\n #define typeof decltype\n#endif\n\nnamespace Parameters\n{\n class Group;\n}\n\nclass Parameters::Group\n{\n public:\n void load(std::string filename);\n double try_get(std::string name, double default_value);\n\ttemplate <class T> T try_get(std::string name, T default_value);\n\ttemplate <class T> void try_set(std::string name, T value);\n boost::program_options::variables_map map;\n protected:\n boost::program_options::options_description options;\n};\n\n// if (typeid(variable) == typeid(double)) use overloaded function in cpp file\ntemplate <typename T>\nT Parameters::Group::try_get(std::string name, T default_value)\n{\n\tT value = default_value;\n\ttry {\n\t\tif (map.count(name)) {\n\t\t\tvalue = map[name].as<typeof(default_value)>();\n\t\t}\n\t\telse {\n\t\t\tMain::logger.log(format(\"failed to set parameter %s: not found in map\") % name);\n\t\t}\n\t}\n\tcatch (std::exception& e) {\n\t\tMain::logger.log(format(\"failed to set parameter %s: %s\") % name % e.what());\n\t}\n\treturn value;\n}\n\ntemplate <typename T>\nvoid Parameters::Group::try_set(std::string name, T value)\n{\n\ttry {\n\t\tif (map.count(name)) {\n\t\t\tmap[name].value() = boost::any(value);\n\t\t}\n\t\telse {\n\t\t\tMain::logger.log(format(\"failed to set parameter %s: not found in map\") % name);\n\t\t}\n\t}\n\tcatch (std::exception& e) {\n\t\tMain::logger.log(format(\"failed to set parameter %s: %s\") % name % e.what());\n\t}\n\treturn value;\n}\n\n#endif\n" }, { "alpha_fraction": 0.7123287916183472, "alphanum_fraction": 0.7232876420021057, "avg_line_length": 19.27777862548828, "blob_id": "93eefda9ab526650501ff81b7c1b70d4f9c4c224", "content_id": "c68081b61bb152de579b31bdb7c1db09416a9226", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 366, "license_type": "no_license", "max_line_length": 73, "num_lines": 18, "path": "/stars/code/shared/update.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__UPDATE_H\n#define SHARED__UPDATE_H\n\n#include \"thread_names.h\"\n\nnamespace Shared\n{\n void update(ThreadNames::Name thread_name);\n}\n\n#endif\n" }, { "alpha_fraction": 0.6821800470352173, "alphanum_fraction": 0.6913655996322632, "avg_line_length": 20.207792282104492, "blob_id": "0764f2fc6014b2b64581c3d6f60339f4e3166727", "content_id": "94ebf8466eeb75459cb8b2de3ed9446e015fa28b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1634, "license_type": "no_license", "max_line_length": 80, "num_lines": 77, "path": "/stars/code/shared/solving/settings.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__SOLVING__SETTINGS_H\n#define SHARED__SOLVING__SETTINGS_H\n\n#include <string>\n#include \"../circular_buffer.h\"\nextern \"C\" {\n#include \"../../networking/xsc_protocol/xsc_protocol.h\"\n}\n\nnamespace Shared\n{\n namespace Solving\n {\n\nstruct Refraction\n{\n Refraction(): enabled(false), pressure_mbar(1013.25), temperature(296.15) {}\n bool enabled;\n double pressure_mbar;\n double temperature;\n};\n\nclass Settings\n{\n public:\n Settings();\n void init(Parameters::Manager& params);\n Settings& operator=(const Settings& rhs);\n\n enum PrecessionEpochSourceType {\n precession_none,\n precession_system_time,\n precession_manual\n };\n\n bool enabled;\n double timeout;\n\n int abort_counter;\n\n double snr_threshold;\n int max_num_blobs;\n bool robust_mode_enabled;\n xsc_solver_fitting_method_t fitting_method;\n unsigned int cell_size;\n unsigned int max_num_blobs_per_cell;\n\n bool pattern_matcher_enabled;\n bool display_names;\n double match_tolerance_px;\n double iplatescale_min;\n double iplatescale_max;\n bool platescale_always_fixed;\n double iplatescale_fixed;\n\n bool debug_timing;\n std::string catalog;\n Refraction refraction;\n PrecessionEpochSourceType precession_epoch_source;\n double precession_manual_epoch;\n};\n\n// writes: network\n// reads: solver\nextern Shared::CircularBuffer <Settings> settings;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.702521026134491, "alphanum_fraction": 0.7092437148094177, "avg_line_length": 18.19354820251465, "blob_id": "0bfc2cd99b2a6e03f1dc5e6dbbfa31a256328826", "content_id": "5b3f97d22cabf82525d55f93f3db5c597b530824", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 596, "license_type": "no_license", "max_line_length": 73, "num_lines": 31, "path": "/stars/code/parameters/manager.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef PARAMETERS__MANAGER_H\n#define PARAMETERS__MANAGER_H\n\n#include <string>\n#include \"general.h\"\n#include \"housekeeping.h\"\n\nnamespace Parameters\n{\n class Manager;\n}\n\nclass Parameters::Manager\n{\n public:\n Manager(std::string stars_absolute_dir);\n void load(int argc, char* argv[]);\n\n std::string stars_dir;\n General general;\n Housekeeping housekeeping;\n};\n\n#endif\n" }, { "alpha_fraction": 0.632326066493988, "alphanum_fraction": 0.6393823623657227, "avg_line_length": 38.75247573852539, "blob_id": "00fbd5150acc9662e21da55ca7357755347050d8", "content_id": "c33114248cf2c33ea756aceb30419425460db0ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12047, "license_type": "no_license", "max_line_length": 153, "num_lines": 303, "path": "/stars/code/shared/solving/filters.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"filters.h\"\n#include <boost/algorithm/string.hpp>\n#include \"settings.h\"\n#include \"../../parameters/manager.h\"\n#include \"../../tools/angles.h\"\n#include \"../../solving/solution.h\"\n#include \"../../logging/logger.h\"\n\nusing namespace Shared::Solving;\n#define shared_settings (*(Shared::Solving::settings.r))\n\nFilters::Filters()\n{\n horizontal_from_fcp_age_limit = 5*60.0;\n image_width = 0;\n image_height = 0;\n}\n\nvoid Filters::init(Parameters::Manager& params)\n{\n\timage_width = params.general.try_get(\"imaging.camera_real.image_width\", params.general.image_width);\n\timage_height = params.general.try_get(\"imaging.camera_real.image_height\", params.general.image_height);\n\n double angle = 0;\n horizontal_from_settings.enabled = params.general.try_get(\"solver.filters.horizontal_source.settings.enabled\", false);\n angle = params.general.try_get(\"solver.filters.horizontal_source.settings.lat_degrees\", 0.0);\n horizontal_from_settings.lat = from_degrees(angle);\n angle = params.general.try_get(\"solver.filters.horizontal_source.settings.lst_hours\", 0.0);\n horizontal_from_settings.lst = from_hours(angle);\n\n horizontal_from_fits.enabled = params.general.try_get(\"solver.filters.horizontal_source.fits.enabled\", false);\n horizontal_from_fcp.enabled = params.general.try_get(\"solver.filters.horizontal_source.fcp.enabled\", true);\n\n horizontal_location.enabled = params.general.try_get(\"solver.filters.horizontal.location_limit.enabled\", false);\n angle = params.general.try_get(\"solver.filters.horizontal.location_limit.radius_degrees\", 30.0);\n horizontal_location.radius = from_degrees(angle);\n angle = params.general.try_get(\"solver.filters.horizontal.location_limit.az_degrees\", 0.0);\n horizontal_location.az = from_degrees(angle);\n angle = params.general.try_get(\"solver.filters.horizontal.location_limit.el_degrees\", 0.0);\n horizontal_location.el = from_degrees(angle);\n\n horizontal_roll_limit.enabled = params.general.try_get(\"solver.filters.horizontal.roll_limit.enabled\", false);\n angle = params.general.try_get(\"solver.filters.horizontal.roll_limit.min_degrees\", -180.0);\n horizontal_roll_limit.min_roll = from_degrees(angle);\n angle = params.general.try_get(\"solver.filters.horizontal.roll_limit.max_degrees\", 180.0);\n horizontal_roll_limit.max_roll = from_degrees(angle);\n\n horizontal_elevation_limit.enabled = params.general.try_get(\"solver.filters.horizontal.elevation_limit.enabled\", false);\n angle = params.general.try_get(\"solver.filters.horizontal.elevation_limit.min_degrees\", 10.0);\n horizontal_elevation_limit.min_el = from_degrees(angle);\n angle = params.general.try_get(\"solver.filters.horizontal.elevation_limit.max_degrees\", 80.0);\n horizontal_elevation_limit.max_el = from_degrees(angle);\n\n equatorial_location.enabled = params.general.try_get(\"solver.filters.equatorial.location_limit.enabled\", false);\n angle = params.general.try_get(\"solver.filters.equatorial.location_limit.radius_degrees\", 30.0);\n equatorial_location.radius = from_degrees(angle);\n angle = params.general.try_get(\"solver.filters.equatorial.location_limit.ra_degrees\", 0.0);\n equatorial_location.ra = from_degrees(angle);\n angle = params.general.try_get(\"solver.filters.equatorial.location_limit.dec_degrees\", 0.0);\n equatorial_location.dec = from_degrees(angle);\n\n equatorial_roll_limit.enabled = params.general.try_get(\"solver.filters.equatorial.roll_limit.enabled\", false);\n angle = params.general.try_get(\"solver.filters.equatorial.roll_limit.min_degrees\", -180.0);\n equatorial_roll_limit.min_roll = from_degrees(angle);\n angle = params.general.try_get(\"solver.filters.equatorial.roll_limit.max_degrees\", 180.0);\n equatorial_roll_limit.max_roll = from_degrees(angle);\n\n matching.pointing_error_threshold = from_arcsec(params.general.try_get(\"solver.filters.matching.pointing_error_threshold_arcsec\", 10.0));\n matching.fit_error_threshold_px = params.general.try_get(\"solver.filters.matching.fit_error_threshold_px\", 2000.0);\n matching.num_matched = params.general.try_get(\"solver.filters.matching.num_matched\", (unsigned int) 8);\n}\n\nFilters& Filters::operator=(const Filters &rhs)\n{\n if (this != &rhs) {\n image_width = rhs.image_width;\n image_height = rhs.image_height;\n horizontal_from_fcp_age_limit = rhs.horizontal_from_fcp_age_limit;\n horizontal_from_settings = rhs.horizontal_from_settings;\n horizontal_from_fits = rhs.horizontal_from_fits;\n horizontal_from_fcp = rhs.horizontal_from_fcp;\n horizontal_elevation_limit = rhs.horizontal_elevation_limit;\n horizontal_roll_limit = rhs.horizontal_roll_limit;\n horizontal_location = rhs.horizontal_location;\n equatorial_location = rhs.equatorial_location;\n matching = rhs.matching;\n }\n return *this;\n}\n\nbool Filters::try_get_horizontal(double& lat, double& lst)\n{\n if (horizontal_from_fcp.enabled && horizontal_from_fcp.age.time() < horizontal_from_fcp_age_limit) {\n lat = horizontal_from_fcp.lat;\n lst = horizontal_from_fcp.lst;\n return true;\n }\n if (horizontal_from_settings.enabled) {\n lat = horizontal_from_settings.lat;\n lst = horizontal_from_settings.lst;\n return true;\n }\n if (horizontal_from_fits.enabled && horizontal_from_fits.valid) {\n lat = horizontal_from_fits.lat;\n lst = horizontal_from_fits.lst;\n return true;\n }\n return false;\n}\n\ndouble Filters::lat() const\n{\n if (horizontal_from_fcp.enabled && horizontal_from_fcp.age.time() < horizontal_from_fcp_age_limit) {\n return horizontal_from_fcp.lat;\n }\n if (horizontal_from_settings.enabled) {\n return horizontal_from_settings.lat;\n }\n if (horizontal_from_fits.enabled && horizontal_from_fits.valid) {\n return horizontal_from_fits.lat;\n }\n return 0.0;\n}\n\ndouble Filters::lst() const\n{\n if (horizontal_from_fcp.enabled && horizontal_from_fcp.age.time() < horizontal_from_fcp_age_limit) {\n return horizontal_from_fcp.lst;\n }\n if (horizontal_from_settings.enabled) {\n return horizontal_from_settings.lst;\n }\n if (horizontal_from_fits.enabled && horizontal_from_fits.valid) {\n return horizontal_from_fits.lst;\n }\n return 0.0;\n}\n\nbool Filters::horizontal_known() const\n{\n if (horizontal_from_fcp.enabled && horizontal_from_fcp.age.time() < horizontal_from_fcp_age_limit) {\n return true;\n }\n if (horizontal_from_settings.enabled) {\n return true;\n }\n if (horizontal_from_fits.enabled && horizontal_from_fits.valid) {\n return true;\n }\n return false;\n}\n\nbool Filters::horizontal_known_and_filters_enabled() const\n{\n if (horizontal_known()) {\n if (horizontal_elevation_limit.enabled || horizontal_roll_limit.enabled ||\n horizontal_location.enabled)\n {\n return true;\n }\n }\n return false;\n}\n\nbool Filters::check_object(double ra, double dec, double max_distance)\n{\n if (equatorial_location.enabled) {\n if (!angles_within(ra, dec, equatorial_location.ra, equatorial_location.dec,\n equatorial_location.radius + max_distance)) {\n return false;\n }\n }\n if (horizontal_location.enabled || horizontal_elevation_limit.enabled) {\n bool horizontal_known = false;\n double lat = 0;\n double lst = 0;\n horizontal_known = try_get_horizontal(lat, lst);\n if (horizontal_known) {\n double az = 0;\n double el = 0;\n equatorial_to_horizontal(ra, dec, lat, lst, az, el);\n if (horizontal_elevation_limit.enabled) {\n if (el < (horizontal_elevation_limit.min_el - max_distance) ||\n el > (horizontal_elevation_limit.max_el + max_distance))\n {\n return false;\n }\n }\n if (horizontal_location.enabled) {\n if (!angles_within(az, el, horizontal_location.az, horizontal_location.el,\n horizontal_location.radius + max_distance)) {\n return false;\n }\n }\n }\n }\n return true;\n}\n\nbool Filters::check_field_star(double ra, double dec, double iplatescale_max)\n{\n double corner_distance = sqrt(double(pow(image_width, 2.0)) + double(pow(image_height, 2.0)))/2.0;\n corner_distance *= iplatescale_max;\n return check_object(ra, dec, corner_distance);\n}\n\nbool Filters::check_roll_limit(RollLimit& roll_limit, double roll)\n{\n double adjusted_roll = \n (roll_limit.min_roll + M_PI) +\n #if _MSC_VER\n fmod(roll-(roll_limit.min_roll+M_PI), 2.0*M_PI);\n #else\n remainder(roll-(roll_limit.min_roll+M_PI), 2.0*M_PI);\n #endif\n if (adjusted_roll < roll_limit.min_roll || adjusted_roll > roll_limit.max_roll) {\n return false;\n }\n return true;\n}\n\nbool Filters::check_solution(::Solving::Solution& solution, Logging::Logger& logger, bool final_check)\n{\n bool debug = false;\n\n // both checks:\n // 1) equatorial attitude\n // 2) horizontal attitude\n\n // final check adds:\n // 3) platescale\n // 4) error\n // 5) matched_blobs.size()\n // 5) matched_blobs.size() / num_blobs_total\n\n\n if (solution.equatorial.valid) {\n if (!check_object(solution.equatorial.ra, solution.equatorial.dec, 0)) {\n // Checks equatorial location (guess) and horizontal location (guess and elevation limit)\n if (debug) {\n logger.log(\"rejected solution based on location\");\n }\n return false;\n }\n if (equatorial_roll_limit.enabled) {\n if (!check_roll_limit(equatorial_roll_limit, solution.equatorial.roll)) {\n if (debug) {\n logger.log(\"rejected solution based on equatorial roll limit\");\n }\n return false;\n }\n }\n }\n\n if (solution.horizontal.valid) {\n if (horizontal_roll_limit.enabled) {\n if (!check_roll_limit(horizontal_roll_limit, solution.horizontal.roll)) {\n if (debug) {\n logger.log(\"rejected solution based on horizontal roll limit\");\n }\n return false;\n }\n }\n }\n\n if (final_check) {\n if (solution.equatorial.valid) {\n if (solution.equatorial.iplatescale < shared_settings.iplatescale_min || solution.equatorial.iplatescale > shared_settings.iplatescale_max) {\n if (debug) {\n logger.log(format(\"rejected solution based on iplatescale (%f arcsec/px)\") % to_arcsec(solution.equatorial.iplatescale));\n }\n return false;\n }\n if (solution.equatorial.sigma_pointing > matching.pointing_error_threshold) {\n if (debug) {\n logger.log(format(\"rejected solution based on pointing_error (%f arcsec)\") % to_arcsec(solution.equatorial.sigma_pointing));\n }\n return false;\n }\n if (solution.equatorial.fit_error > matching.fit_error_threshold_px) {\n if (debug) {\n logger.log(format(\"rejected solution based on fit_error (%f px)\") % solution.equatorial.fit_error);\n }\n return false;\n }\n }\n if (solution.matched_blobs.size() < matching.num_matched) {\n if (debug) {\n logger.log(format(\"rejected solution on num_match condition, matched %i of %i (requires %i)\")\n % solution.matched_blobs.size() % solution.num_blobs_total % matching.num_matched);\n }\n return false;\n }\n }\n \n return true;\n}\n\n" }, { "alpha_fraction": 0.5912106037139893, "alphanum_fraction": 0.5966595411300659, "avg_line_length": 28.378190994262695, "blob_id": "a4369687a43ddf0c8502658ed2ff3999d1ffed00", "content_id": "55201386b0affae0cac4eee4a5ddec693c3ed1e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 25326, "license_type": "no_license", "max_line_length": 105, "num_lines": 862, "path": "/blast_comms/comms_netbuf.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/**\n * @file comms_netbuf.c\n *\n * @date Jan 16, 2011\n * @author Seth Hillbrand\n * \n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2010-2015 Seth Hillbrand\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <assert.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <stddef.h>\n#include <pthread.h>\n\n#include <blast.h>\n#include <comms_netbuf.h>\n\n\n#define likely(cond) __builtin_expect(!!(cond), 1)\n#define unlikely(cond) __builtin_expect((cond), 0)\n#define DEFAULT_MINCAP 32\n\nstatic inline __attribute__((pure)) size_t netbuf_elem_size(netbuf_t* p)\n{\n return p->elem_size;\n}\n\ntypedef struct {\n char *buffer;\n char *bufend;\n char *begin;\n char *end;\n size_t elem_size;\n} buf_snapshot_t;\n\nstatic inline buf_snapshot_t make_snapshot(netbuf_t* p)\n{\n return (buf_snapshot_t) {\n .buffer = p->buffer,\n .bufend = p->bufend,\n .begin = p->begin,\n .end = p->end,\n .elem_size = netbuf_elem_size(p),\n };\n}\n\n// Returns the maximum number of bytes the buffer can hold, excluding the\n// sentinel element.\nstatic inline size_t capacity(buf_snapshot_t s)\n{\n return s.bufend - s.buffer - s.elem_size;\n}\n\n// Does the buffer wrap around?\n// true -> wrap\n// false -> nowrap\nstatic inline bool wraps_around(buf_snapshot_t s)\n{\n return unlikely(s.begin >= s.end);\n}\n\n// Returns the number of bytes currently in use in the buffer, excluding the\n// sentinel element.\nstatic inline size_t bytes_in_use(buf_snapshot_t s)\n{\n return (wraps_around(s)\n // v right half v v left half v\n ? ((s.end - s.buffer) + (s.bufend - s.begin))\n : (s.end - s.begin))\n // exclude the sentinel element.\n - s.elem_size;\n}\n\nstatic inline char* wrap_ptr_if_necessary(char* buffer,\n char* p,\n char* bufend)\n{\n if (p >= bufend) {\n size_t diff = p - bufend;\n return buffer + diff;\n } else {\n return p;\n }\n}\n\nstatic inline char* rev_wrap_ptr_if_necessary(char* buffer,\n char* p,\n char* bufend)\n{\n if (p < buffer) {\n size_t diff = buffer - p;\n return bufend - diff;\n } else {\n return p;\n }\n}\n\nstatic inline void* offset_memcpy(void* restrict dest, const void* restrict src, size_t n)\n{\n memcpy(dest, src, n);\n return (char*) dest + n;\n}\n\nstatic size_t __attribute__((const)) next_pow2(size_t n)\n{\n if (unlikely(!n)) return 2;\n\n // If when we round up we will overflow our size_t\n if (unlikely(n >= ((~(size_t )0 >> 1) + 1))) return n;\n\n // Algorithm idea from\n // https://groups.google.com/d/msg/comp.lang.python/xNOq4N-RffU/HObqrKz59sQJ\n n--;\n\n for (size_t shift = 1; shift < (sizeof n) * 8; shift <<= 1)\n n |= n >> shift;\n\n n++;\n\n return n;\n}\n\n#define in_bounds(left, x, right) ((x) >= (left) && (x) <= (right))\n\n\nstatic inline void check_invariants(netbuf_t* p)\n{\n if (p == NULL) return;\n\n if (p->buffer == NULL) {\n assert(p->consumer_refcount == 0);\n return;\n } else {\n assert(p->consumer_refcount != 0);\n }\n\n buf_snapshot_t s = make_snapshot(p);\n\n assert(s.begin);\n assert(s.end);\n assert(s.bufend);\n\n assert(p->elem_size != 0);\n\n assert(bytes_in_use(s) <= capacity(s) && \"There are more elements in the buffer than its capacity.\");\n\n assert(in_bounds(s.buffer, s.begin, s.bufend));\n assert(in_bounds(s.buffer, s.end, s.bufend));\n\n if (s.begin == s.end)\n assert(bytes_in_use(s) == capacity(s));\n\n assert(in_bounds(DEFAULT_MINCAP*p->elem_size, p->min_cap, p->max_cap));\n assert(in_bounds(p->min_cap, capacity(s) + p->elem_size, p->max_cap));\n}\n\n\nstatic inline void lock_pipe(netbuf_t* p)\n{\n pthread_mutex_lock(&p->end_lock);\n pthread_mutex_lock(&p->begin_lock);\n check_invariants(p);\n}\n\nstatic inline void unlock_pipe(netbuf_t* p)\n{\n check_invariants(p);\n pthread_mutex_unlock(&p->begin_lock);\n pthread_mutex_unlock(&p->end_lock);\n}\n\n// runs some code while automatically locking and unlocking the pipe. If `break'\n// is used, the pipe will be unlocked before control returns from the macro.\n#define WHILE_LOCKED(stuff) do { \\\n lock_pipe(m_buf); \\\n do { stuff; } while (0); \\\n unlock_pipe(m_buf); \\\n } while (0)\n\nnetbuf_t* netbuf_new(size_t elem_size, size_t limit)\n{\n assert(elem_size != 0);\n\n if (elem_size == 0)\n return NULL;\n\n netbuf_t* p = malloc(sizeof *p);\n\n assert(DEFAULT_MINCAP >= 1);\n\n size_t cap = DEFAULT_MINCAP * elem_size;\n char* buf = malloc(cap);\n\n // Change the limit from being in \"elements\" to being in \"bytes\", and make\n // room for the sentinel element.\n limit = (limit + 1) * elem_size;\n\n if (unlikely(p == NULL || buf == NULL))\n return free(p), free(buf), NULL;\n\n *p = (netbuf_t) {\n .elem_size = elem_size,\n .min_cap = cap,\n .max_cap = limit ? next_pow2(max(limit, cap)) : ~(size_t)0,\n\n .buffer = buf,\n .bufend = buf + cap,\n .begin = buf,\n .end = buf + elem_size,\n\n // Since we're issuing a netbuf_t, it counts as both a producer and a\n // consumer since it can issue new instances of both. Therefore, the\n // refcounts both start at 1; not the intuitive 0.\n .producer_refcount = 1,\n .consumer_refcount = 1,\n };\n\n pthread_mutex_init(&p->begin_lock, NULL);\n pthread_mutex_init(&p->end_lock, NULL);\n\n pthread_cond_init(&p->just_pushed, NULL);\n pthread_cond_init(&p->just_popped, NULL);\n\n check_invariants(p);\n\n return p;\n}\n\nnetbuf_t* netbuf_producer_new(netbuf_t* p)\n{\n pthread_mutex_lock(&p->begin_lock);\n p->producer_refcount++;\n pthread_mutex_unlock(&p->begin_lock);\n\n return (netbuf_t*)p;\n}\n\nnetbuf_t* netbuf_consumer_new(netbuf_t* p)\n{\n pthread_mutex_lock(&p->end_lock);\n p->consumer_refcount++;\n pthread_mutex_unlock(&p->end_lock);\n\n return (netbuf_t*)p;\n}\n\nstatic void deallocate(netbuf_t* p)\n{\n assert(p->producer_refcount == 0);\n assert(p->consumer_refcount == 0);\n\n pthread_mutex_destroy(&p->begin_lock);\n pthread_mutex_destroy(&p->end_lock);\n\n pthread_cond_destroy(&p->just_pushed);\n pthread_cond_destroy(&p->just_popped);\n\n free(p->buffer);\n free(p);\n}\n\nvoid netbuf_free(netbuf_t* p)\n{\n size_t new_producer_refcount,\n new_consumer_refcount;\n\n pthread_mutex_lock(&p->begin_lock);\n assert(p->producer_refcount > 0);\n new_producer_refcount = --p->producer_refcount;\n pthread_mutex_unlock(&p->begin_lock);\n\n pthread_mutex_lock(&p->end_lock);\n assert(p->consumer_refcount > 0);\n new_consumer_refcount = --p->consumer_refcount;\n pthread_mutex_unlock(&p->end_lock);\n\n if (unlikely(new_consumer_refcount == 0)) {\n p->buffer = (free(p->buffer), NULL);\n\n if (likely(new_producer_refcount > 0))\n pthread_cond_broadcast(&p->just_popped);\n else\n deallocate(p);\n } else {\n if (unlikely(new_producer_refcount == 0)) pthread_cond_broadcast(&p->just_pushed);\n }\n}\n\nvoid netbuf_producer_free(netbuf_t* p)\n{\n size_t new_producer_refcount;\n\n pthread_mutex_lock(&p->begin_lock);\n assert(p->producer_refcount > 0);\n new_producer_refcount = --p->producer_refcount;\n pthread_mutex_unlock(&p->begin_lock);\n\n if (unlikely(new_producer_refcount == 0)) {\n size_t consumer_refcount;\n\n pthread_mutex_lock(&p->end_lock);\n consumer_refcount = p->consumer_refcount;\n pthread_mutex_unlock(&p->end_lock);\n\n // If there are still consumers, wake them up if they're waiting on\n // input from a producer. Otherwise, since we're the last handle\n // altogether, we can free the pipe.\n if (likely(consumer_refcount > 0))\n pthread_cond_broadcast(&p->just_pushed);\n else\n deallocate(p);\n }\n}\n\nvoid netbuf_consumer_free(netbuf_t* p)\n{\n size_t new_consumer_refcount;\n\n pthread_mutex_lock(&p->end_lock);\n new_consumer_refcount = --p->consumer_refcount;\n pthread_mutex_unlock(&p->end_lock);\n\n if (unlikely(new_consumer_refcount == 0)) {\n size_t producer_refcount;\n\n pthread_mutex_lock(&p->begin_lock);\n producer_refcount = p->producer_refcount;\n pthread_mutex_unlock(&p->begin_lock);\n\n // If there are still producers, wake them up if they're waiting on\n // room to free up from a consumer. Otherwise, since we're the last\n // handle altogether, we can free the pipe.\n if (likely(producer_refcount > 0))\n pthread_cond_broadcast(&p->just_popped);\n else\n deallocate(p);\n }\n}\n\n// Returns the end of the buffer (buf + number_of_bytes_copied).\nstatic inline char* copy_netbuf_into_new_buf(buf_snapshot_t s, char* restrict buf) {\n if (wraps_around(s)) {\n buf = offset_memcpy(buf, s.begin, s.bufend - s.begin);\n buf = offset_memcpy(buf, s.buffer, s.end - s.buffer);\n } else {\n buf = offset_memcpy(buf, s.begin, s.end - s.begin);\n }\n\n return buf;\n}\n\n\n// Returns the number of bytes copied\nstatic inline size_t copy_netbuf_data(buf_snapshot_t s, char* restrict buf) {\n size_t retval = 0;\n\n if (wraps_around(s)) {\n buf = offset_memcpy(buf, s.begin + s.elem_size, s.bufend - s.begin - s.elem_size);\n retval = s.bufend - s.begin - s.elem_size;\n\n buf = offset_memcpy(buf, s.buffer, s.end - s.buffer);\n retval += (s.end - s.buffer - s.elem_size);\n } else {\n buf = offset_memcpy(buf, s.begin + s.elem_size, s.end - s.begin - s.elem_size);\n retval = s.end - s.begin - s.elem_size;\n }\n\n return retval;\n}\n\n// Resizes the buffer to make room for at least 'new_size' elements, returning\n// an updated snapshot of the pipe state.\n//\n// The new size MUST be bigger than the number of elements currently in the\n// pipe.\n//\n// The pipe must be fully locked on entrance to this function.\nstatic buf_snapshot_t resize_buffer(netbuf_t* p, size_t new_size)\n{\n check_invariants(p);\n\n const size_t max_cap = p->max_cap,\n min_cap = p->min_cap,\n elem_size = netbuf_elem_size(p);\n\n assert(new_size >= bytes_in_use(make_snapshot(p)));\n\n if (unlikely(new_size >= max_cap)) new_size = max_cap;\n\n if (new_size <= min_cap) return make_snapshot(p);\n\n char* new_buf = malloc(new_size + elem_size);\n p->end = copy_netbuf_into_new_buf(make_snapshot(p), new_buf);\n\n p->begin =\n p->buffer = (free(p->buffer), new_buf);\n\n p->bufend = new_buf + new_size + elem_size;\n\n check_invariants(p);\n\n return make_snapshot(p);\n}\n\nstatic inline buf_snapshot_t validate_size(netbuf_t* p, buf_snapshot_t s, size_t new_bytes)\n{\n size_t elem_size = netbuf_elem_size(p);\n size_t cap = capacity(s);\n size_t bytes_needed = bytes_in_use(s) + new_bytes;\n\n if (unlikely(bytes_needed > cap)) {\n // upgrade our lock, then re-check. By taking both locks (end and begin)\n // in order, we have an equivalent operation to lock_pipe().\n {\n pthread_mutex_lock(&p->begin_lock);\n\n s = make_snapshot(p);\n bytes_needed = bytes_in_use(s) + new_bytes;\n size_t elems_needed = bytes_needed / elem_size;\n\n if (likely(bytes_needed > cap))\n s = resize_buffer(p, next_pow2(elems_needed) * elem_size);\n }\n\n // Unlock the pipe if requested.\n pthread_mutex_unlock(&p->begin_lock);\n }\n\n return s;\n}\n\n// Runs the actual push, assuming there is enough room in the buffer.\n//\n// Returns the new 'end' pointer.\nstatic inline char* process_push(buf_snapshot_t s,\n const void* restrict elems,\n size_t bytes_to_copy\n )\n{\n assert(bytes_to_copy != 0);\n\n // This shouldn't be necessary.\n // s.end = wrap_ptr_if_necessary(s.buffer, s.end, s.bufend);\n assert(s.end != s.bufend);\n\n // If we currently have a nowrap buffer, we may have to wrap the new\n // elements. Copy as many as we can at the end, then start copying into the\n // beginning. This basically reduces the problem to only deal with wrapped\n // buffers, which can be dealt with using a single offset_memcpy.\n if (!wraps_around(s)) {\n size_t at_end = min(bytes_to_copy, (size_t) (s.bufend - s.end));\n\n s.end = offset_memcpy(s.end, elems, at_end);\n\n elems = (const char*) elems + at_end;\n bytes_to_copy -= at_end;\n }\n\n // Now copy any remaining data...\n if (unlikely(bytes_to_copy)) {\n s.end = wrap_ptr_if_necessary(s.buffer, s.end, s.bufend);\n s.end = offset_memcpy(s.end, elems, bytes_to_copy);\n }\n\n s.end = wrap_ptr_if_necessary(s.buffer, s.end, s.bufend);\n\n // ...and update the end pointer!\n return s.end;\n}\n\n// Will spin until there is enough room in the buffer to push any elements.\n// Returns the number of elements currently in the buffer. `end_lock` should be\n// locked on entrance to this function.\nstatic inline buf_snapshot_t wait_for_room(netbuf_t* m_buf, size_t* max_cap)\n{\n buf_snapshot_t s = make_snapshot(m_buf);\n\n size_t bytes_used = bytes_in_use(s);\n\n size_t consumer_refcount = m_buf->consumer_refcount;\n\n *max_cap = m_buf->max_cap;\n\n for (; unlikely(bytes_used == *max_cap) && likely(consumer_refcount > 0);\n s = make_snapshot(m_buf),\n bytes_used = bytes_in_use(s),\n consumer_refcount = m_buf->consumer_refcount,\n *max_cap = m_buf->max_cap)\n pthread_cond_wait(&m_buf->just_popped, &m_buf->end_lock);\n\n return s;\n}\n\nsize_t __netbuf_write(netbuf_t* m_buf,\n const void* restrict m_src,\n size_t m_count)\n{\n size_t elem_size = netbuf_elem_size(m_buf);\n\n if (unlikely(m_count == 0))\n return 0;\n\n size_t pushed = 0;\n\n { pthread_mutex_lock(&m_buf->end_lock);\n buf_snapshot_t s = make_snapshot(m_buf);\n size_t max_cap = m_buf->max_cap;\n\n // if no more consumers...\n if (unlikely(m_buf->consumer_refcount == 0)) {\n pthread_mutex_unlock(&m_buf->end_lock);\n return 0;\n }\n\n s = validate_size(m_buf, s, m_count);\n\n // Finally, we can now begin with pushing as many elements into the\n // queue as possible.\n m_buf->end = process_push(s, m_src,\n pushed = min(m_count, max_cap - bytes_in_use(s)));\n } pthread_mutex_unlock(&m_buf->end_lock);\n\n assert(pushed > 0);\n\n // Signal if we've only pushed one element, broadcast if we've pushed more.\n if (unlikely(pushed == elem_size))\n pthread_cond_signal(&m_buf->just_pushed);\n else\n pthread_cond_broadcast(&m_buf->just_pushed);\n\n return pushed;\n}\n\nsize_t netbuf_write(netbuf_t* m_buf, const void* restrict m_src, size_t m_count)\n{\n m_count *= netbuf_elem_size(m_buf);\n return __netbuf_write(m_buf, m_src, m_count);\n}\n\n\n#ifdef NETBUF_DEBUG\n#include <stdio.h>\nvoid netbuf_debug_int(netbuf_t* p, const char* id)\n{\n char debug_string[1025];\n int len = 0;\n len = snprintf(debug_string, sizeof(debug_string), \"%s: [ \", id);\n for (int* ptr = (int*)p->buffer; ptr != (int*)p->bufend; ++ptr) {\n len += snprintf(debug_string + len, 1024 - len, \"%i \", *ptr);\n if (len > 1024) break;\n }\n if (len <=1024) snprintf(debug_string + len, sizeof(debug_string + len), \"]\");\n blast_dbg(\"%s\", debug_string);\n blast_dbg(\"begin: %lu end: %lu\\n\", p->begin - p->buffer, p->end - p->buffer);\n}\nvoid netbuf_debug_string(netbuf_t* p, const char* id)\n{\n char debug_string[1025];\n int len = 0;\n len = snprintf(debug_string, sizeof(debug_string), \"%s: [ \", id);\n for (char* ptr = (char*)p->buffer; ptr != (char*)p->bufend; ++ptr) {\n len += snprintf(debug_string + len, 1024 - len, \"%c \", *ptr);\n if (len > 1024) break;\n }\n if (len <=1024) snprintf(debug_string + len, sizeof(debug_string + len), \"]\");\n blast_dbg(\"%s\", debug_string);\n blast_dbg(\"begin: %lu end: %lu\\n\", p->begin - p->buffer, p->end - p->buffer);\n}\n#endif\n\n\n// Waits for at least one element to be in the pipe. p->begin_lock must be\n// locked when entering this function, and a new, valid snapshot is returned.\nstatic inline buf_snapshot_t wait_for_elements(netbuf_t* p, bool m_immediate)\n{\n buf_snapshot_t s = make_snapshot(p);\n\n size_t bytes_used = bytes_in_use(s);\n\n if (m_immediate && !bytes_used) return s;\n\n for (; unlikely(bytes_used == 0) && likely(p->producer_refcount > 0);\n s = make_snapshot(p),\n bytes_used = bytes_in_use(s))\n pthread_cond_wait(&p->just_pushed, &p->begin_lock);\n\n return s;\n}\n\n// wow, I didn't even intend for the name to work like that...\n// returns a new snapshot, with the updated changes also reflected onto the\n// pipe.\nstatic inline buf_snapshot_t pop_without_locking(buf_snapshot_t s,\n void* restrict target,\n size_t bytes_to_copy,\n char** begin // [out]\n )\n{\n assert(s.begin != s.bufend);\n\n size_t elem_size = s.elem_size;\n\n // Copy either as many bytes as requested, or the available bytes in the RHS\n // of a wrapped buffer - whichever is smaller.\n {\n size_t first_bytes_to_copy = min(bytes_to_copy, (size_t)(s.bufend - s.begin - elem_size));\n\n target = offset_memcpy(target, s.begin + elem_size, first_bytes_to_copy);\n\n bytes_to_copy -= first_bytes_to_copy;\n\n s.begin += first_bytes_to_copy;\n s.begin = wrap_ptr_if_necessary(s.buffer, s.begin, s.bufend);\n }\n\n if (unlikely(bytes_to_copy > 0)) {\n s.begin += elem_size;\n s.begin = wrap_ptr_if_necessary(s.buffer, s.begin, s.bufend);\n\n memcpy(target, s.begin, bytes_to_copy);\n\n s.begin += bytes_to_copy;\n s.begin = wrap_ptr_if_necessary(s.buffer, s.begin, s.bufend);\n\n s.begin -= elem_size;\n s.begin = rev_wrap_ptr_if_necessary(s.buffer, s.begin, s.bufend);\n }\n\n // Since we cached begin on the stack, we need to reflect our changes back\n // on the pipe.\n *begin = s.begin;\n\n return s;\n}\n\n// If the buffer is shrunk to something a lot smaller than our current\n// capacity, resize it to something sane. This function must be entered with\n// only p->begin_lock locked, and will automatically unlock p->begin_lock on\n// exit.\nstatic inline void trim_buffer(netbuf_t* p, buf_snapshot_t s)\n{\n size_t cap = capacity(s);\n\n // We have a sane size. We're done here.\n if (likely(bytes_in_use(s) > cap / 4)) {\n pthread_mutex_unlock(&p->begin_lock);\n return;\n }\n\n // Okay, we need to resize now. Upgrade our lock so we can check again. The\n // weird lock/unlock order is to make sure we always acquire the end_lock\n // before begin_lock. Deadlock can arise otherwise.\n pthread_mutex_unlock(&p->begin_lock);\n pthread_mutex_lock(&p->end_lock);\n pthread_mutex_lock(&p->begin_lock);\n\n s = make_snapshot(p);\n cap = capacity(s);\n\n // To conserve space like the good computizens we are, we'll shrink\n // our buffer if our memory usage efficiency drops below 25%. However,\n // since shrinking/growing the buffer is the most expensive part of a push\n // or pop, we only shrink it to bring us up to a 50% efficiency. A common\n // pipe usage pattern is sudden bursts of pushes and pops. This ensures it\n // doesn't get too time-inefficient.\n if (likely(bytes_in_use(s) <= cap / 4))\n resize_buffer(p, cap / 2);\n\n // All done. Unlock the pipe. The reason we don't let the calling function\n // unlock begin_lock is so that we can do it BEFORE end_lock. This prevents\n // the lock order from being fudged.\n pthread_mutex_unlock(&p->begin_lock);\n pthread_mutex_unlock(&p->end_lock);\n}\n\n// Performs the actual pop, except `requested' is now in bytes as opposed to\n// elements.\n//\n// This will behave eagerly, returning as many elements that it can into\n// `target' as it can fill right now.\nstatic inline size_t __netbuf_pop(netbuf_t* p, void* restrict target, size_t requested,\nbool m_nowait)\n{\n if (unlikely(requested == 0)) return 0;\n\n size_t popped = 0;\n\n {\n pthread_mutex_lock(&p->begin_lock);\n buf_snapshot_t s = wait_for_elements(p, m_nowait);\n size_t bytes_used = bytes_in_use(s);\n\n if (unlikely(bytes_used == 0)) {\n pthread_mutex_unlock(&p->begin_lock);\n return 0;\n }\n\n check_invariants(p);\n\n s = pop_without_locking(s, target, popped = min(requested, bytes_used), &p->begin);\n\n check_invariants(p);\n\n trim_buffer(p, s);\n } // p->begin_lock was unlocked by trim_buffer.\n\n assert(popped);\n\n if (unlikely(popped == netbuf_elem_size(p)))\n pthread_cond_signal(&p->just_popped);\n else\n pthread_cond_broadcast(&p->just_popped);\n\n return popped;\n}\n\nstatic size_t __netbuf_read(netbuf_t *p, void *m_target, size_t m_count, bool m_nonblock)\n{\n size_t elem_size = netbuf_elem_size(p);\n size_t bytes_left = m_count * elem_size;\n size_t bytes_popped = 0;\n size_t ret = -1;\n\n do {\n ret = __netbuf_pop(p, m_target, bytes_left, m_nonblock);\n m_target = (void*) ((char*) m_target + ret);\n bytes_popped += ret;\n bytes_left -= ret;\n } while (ret && bytes_left);\n\n return bytes_popped / elem_size;\n}\n\nsize_t netbuf_read(netbuf_t* p, void* m_target, size_t count)\n{\n return __netbuf_read(p, m_target, count, true);\n}\n\nsize_t netbuf_read_wait(netbuf_t *p, void *m_target, size_t count)\n{\n return __netbuf_read(p, m_target, count, false);\n}\n\nsize_t netbuf_peek_noalloc(netbuf_t *m_buf, void *m_target, size_t m_size)\n{\n void *dest = m_target;\n buf_snapshot_t s = make_snapshot(m_buf);\n size_t bytes_to_copy = min(m_size, bytes_in_use(s));\n\n if (wraps_around(s) && (bytes_to_copy > (s.bufend - s.begin))) {\n dest = offset_memcpy(dest, s.begin + s.elem_size, s.bufend - s.begin - s.elem_size);\n bytes_to_copy -= (s.bufend - s.begin);\n\n memcpy(dest, s.buffer, bytes_to_copy);\n } else {\n memcpy(dest, s.begin + s.elem_size, bytes_to_copy);\n }\n\n return bytes_to_copy;\n}\n\nsize_t netbuf_peek(netbuf_t *m_buf, void **m_target)\n{\n size_t retval;\n\n pthread_mutex_lock(&m_buf->begin_lock);\n buf_snapshot_t s = make_snapshot(m_buf);\n size_t bytes_used = bytes_in_use(s); /// Add the sentinel element back here\n\n if (unlikely(bytes_used == 0)) {\n pthread_mutex_unlock(&m_buf->begin_lock);\n *m_target = NULL;\n return 0;\n }\n\n check_invariants(m_buf);\n *m_target = calloc(bytes_used, 1);\n retval = copy_netbuf_data(s, *m_target);\n\n pthread_mutex_unlock(&m_buf->begin_lock);\n\n return retval;\n}\n\nvoid netbuf_reserve(netbuf_t *m_buf, size_t m_count)\n{\n m_count *= netbuf_elem_size(m_buf); // now `count' is in \"bytes\" instead of \"elements\".\n\n if (m_count == 0) m_count = DEFAULT_MINCAP;\n\n size_t max_cap = m_buf->max_cap;\n\n WHILE_LOCKED(if(unlikely(m_count <= bytes_in_use(make_snapshot(m_buf)))) break;\n\n m_buf->min_cap = min(m_count, max_cap); resize_buffer(m_buf, m_count););\n}\n\nvoid netbuf_eat(netbuf_t *m_buf, size_t m_len)\n{\n buf_snapshot_t s;\n\n pthread_mutex_lock(&m_buf->begin_lock);\n\n if (unlikely(m_len == 0)) {\n pthread_mutex_unlock(&m_buf->begin_lock);\n return;\n }\n s = make_snapshot(m_buf);\n check_invariants(m_buf);\n {\n size_t first_bytes_to_copy = min(m_len, (size_t )(s.bufend - s.begin - s.elem_size));\n\n m_len -= first_bytes_to_copy;\n\n s.begin += first_bytes_to_copy;\n s.begin = wrap_ptr_if_necessary(s.buffer, s.begin, s.bufend);\n }\n\n if (unlikely(m_len > 0)) {\n s.begin += s.elem_size;\n s.begin = wrap_ptr_if_necessary(s.buffer, s.begin, s.bufend);\n\n s.begin += m_len;\n s.begin = wrap_ptr_if_necessary(s.buffer, s.begin, s.bufend);\n\n s.begin -= s.elem_size;\n s.begin = rev_wrap_ptr_if_necessary(s.buffer, s.begin, s.bufend);\n }\n\n m_buf->begin = s.begin;\n check_invariants(m_buf);\n\n trim_buffer(m_buf, s); // Unlocks begin_lock\n}\n\n\nvoid netbuf_reinit(netbuf_t *m_buf)\n{\n buf_snapshot_t s = make_snapshot(m_buf);\n size_t bytes_used = bytes_in_use(s);\n\n netbuf_eat(m_buf, bytes_used);\n}\n\n\n" }, { "alpha_fraction": 0.6977077126502991, "alphanum_fraction": 0.7012894153594971, "avg_line_length": 19.8358211517334, "blob_id": "6249c025fa60504f0ba0fd632e0cc8edb8d1e971", "content_id": "e9672fa0e9e0e78327b9b84fccb478e596b803dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1397, "license_type": "no_license", "max_line_length": 131, "num_lines": 67, "path": "/stars/code/shared/image/solution_summary.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__IMAGE__SOLUTION_H\n#define SHARED__IMAGE__SOLUTION_H\n\n#include \"../circular_buffer.h\"\n#include <vector>\n#include <string>\n#include \"../../solving/attitude.h\"\n\nnamespace Solving\n{\n class Solution;\n}\n\nnamespace Shared\n{\n namespace Network\n {\n class Image;\n }\n\n namespace Image\n {\n\nstruct BlobName\n{\n int blob_id;\n std::string name;\n double mag;\n};\n\nclass SolutionSummary\n{\n public:\n SolutionSummary();\n SolutionSummary& operator=(const SolutionSummary& rhs);\n SolutionSummary& operator=(const ::Solving::Solution& rhs);\n\n int counter_stars;\n ::Solving::SolutionAttitude equatorial;\n ::Solving::SolutionAttitude horizontal;\n double solving_time;\n int num_blobs_total;\n int num_blobs_matched;\n double measured_exposure; // this is the estimated exposure time assuming fully open aperture and gain 0 dB for the EBEX camera\n std::vector<BlobName> blob_names;\n};\n\n// writes: solver\n// reads: main\nextern Shared::CircularBufferPass <SolutionSummary> solution_summary_for_main;\n\n// writes: main\n// reads: network\nextern Shared::CircularBuffer <SolutionSummary> solution_summary_main_for_net;\n\n }\n}\n\n\n#endif\n" }, { "alpha_fraction": 0.6703829169273376, "alphanum_fraction": 0.6742607951164246, "avg_line_length": 20.47916603088379, "blob_id": "bec7e54430f5116557b6842e52a1107319fa7ea7", "content_id": "1e6af531902bba28d8e24ef37f013bf718000a34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2064, "license_type": "no_license", "max_line_length": 73, "num_lines": 96, "path": "/stars/code/displaying/visual.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__VISUAL_H\n#define DISPLAYING__VISUAL_H\n\n#include <stdio.h>\n#include <string>\n#include <math.h>\n#include \"texture.h\"\n#include \"block.h\"\n#include \"base_set.h\"\n#include \"blob.h\"\n#include \"utilities.h\"\n#include \"../tools/timing.h\"\n\nnamespace Displaying\n{\n class Visual;\n}\n\nnamespace Parameters\n{\n class Manager;\n}\n\nclass Displaying::Visual: public Block\n{\n public:\n\n enum texture_status_types {\n no_image,\n image_not_rendered,\n image_rendered\n };\n\n Visual(Parameters::Manager& params);\n ~Visual();\n void init(std::string title, Textures& textures_);\n void clear();\n\n void draw3d(Position& pos, Size& scaling);\n void update_size(Size max_size);\n void update();\n void set_start_image();\n\n void draw_flash(double age);\n void draw_loading_screen();\n void draw_blob_stripe(double intercept);\n void draw_blobs(double age, double stripe_progress);\n void draw_base_sets(double stripe_progress);\n void draw_mask();\n void draw(Position &pos, double flip_scaling=1.0);\n\n private:\n bool display_enabled;\n std::string stars_dir;\n\n double main_window_height_;\n double some_height_;\n Size image_size;\n\n std::vector<Blob> display_blobs_;\n Tools::Timer blobs_timer;\n int base_blobs[3];\n double base_progress;\n std::vector<BaseSet> display_base_sets;\n Tools::Timer image_age_timer;\n Tools::Timer rendered_image_timer;\n Tools::Timer rendered_solution_timer;\n\n texture_status_types texture_status;\n int frame_number;\n\n bool loading_screen_begun;\n Tools::Timer loading_screen_timer;\n\n int current_id;\n int last_blobs_counter_stars;\n\n int counter_stars_for_last_blob_names;\n\n Texture loading_screen;\n Texture flash;\n Texture mask;\n Texture white;\n Texture rendered_image;\n Texture canvas;\n\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.3896232843399048, "alphanum_fraction": 0.42351654171943665, "avg_line_length": 40.40329360961914, "blob_id": "a95878bc412006e93f2f279530d8d78a2fd2c4e1", "content_id": "e513eee6912c6c3edb45832a29f17372c59596d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10061, "license_type": "no_license", "max_line_length": 93, "num_lines": 243, "path": "/common/include/channel_macros.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * channel_macros.h: \n *\n * This software is copyright \n * (C) 2013-2014 California State University, Sacramento\n *\n * This file is part of mcp, created for the BLASTPol Project.\n *\n * mcp 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Aug 19, 2014 by seth\n */\n\n#ifndef INCLUDE_CHANNEL_MACROS_H_\n#define INCLUDE_CHANNEL_MACROS_H_\n\n#include <stdint.h>\n\n/**\n * These intermediate types are necessary to allow GCC to use its strict-aliasing\n * optimization without breaking our big-endian/little-endian conversion logic\n */\ntypedef uint32_t __attribute__((__may_alias__)) u32_a;\ntypedef uint64_t __attribute__((__may_alias__)) u64_a;\n\ntypedef struct channel channel_t;\n\n# ifndef _BSD_SOURCE\n# define _BSD_SOURCE /* Define this for endian-conversion macros */\n# endif\n#include <portable_endian.h>\n\n# if __BYTE_ORDER == __LITTLE_ENDIAN\n# define beftoh(x) ({ \\\n float _tmp; \\\n u32_a *infloat = (u32_a*)&(x); \\\n u32_a *outfloat = (u32_a*)(&_tmp);\\\n *outfloat = be32toh(*infloat); \\\n _tmp; \\\n })\n# define bedtoh(x) ({ \\\n double _tmp; \\\n u64_a *infloat = (u64_a*)&(x); \\\n u64_a *outfloat = (u64_a*)(&_tmp);\\\n *outfloat = be64toh(*infloat); \\\n _tmp; \\\n })\n# define htobed(in,out) { \\\n double in_dbl = (in); \\\n u64_a *indouble = (u64_a*)&in_dbl;\\\n u64_a *outdouble = (u64_a*)&(out);\\\n *outdouble = htobe64(*indouble); \\\n }\n# define htobef(in,out) { \\\n float in_flt = (in); \\\n u32_a *infloat = (u32_a*)&in_flt; \\\n u32_a *outfloat = (u32_a*)&(out); \\\n *outfloat = htobe32(*infloat); \\\n }\n\n# ifndef htobe16\n# define htobe16(x) __bswap_16 (x)\n# endif\n# ifndef htobe32\n# define htobe32(x) __bswap_32 (x)\n# endif\n# ifndef htobe64\n# define htobe64(x) __bswap_64 (x)\n# endif\n\n# else\n# define beftoh(x) (x)\n# define bedtoh(x) (x)\n# define htobef(in,out) ((out)=(in))\n# define htobed(in,out) ((out)=(in))\n\n# ifndef htobe16\n# define htobe16(x) (x)\n# endif\n# ifndef htobe32\n# define htobe32(x) (x)\n# endif\n# ifndef htobe64\n# define htobe64(x) (x)\n# endif\n\n# endif\n\n/**\n * If you know what type of data you are getting, these macros are preferable to the\n * type-agnostic one below. However, be warned that if you change the type of the variable\n * in tx_struct, we can't protect you with these.\n */\n#define GET_UINT8(_ch) *(uint8_t*)((_ch)->var)\n#define GET_INT8(_ch) *(int8_t*)((_ch)->var)\n#define GET_UINT16(_ch) be16toh(*(uint16_t*)((_ch)->var))\n#define GET_INT16(_ch) (int16_t)be16toh(*(uint16_t*)((_ch)->var))\n#define GET_UINT32(_ch) be32toh(*(uint32_t*)((_ch)->var))\n#define GET_INT32(_ch) (int32_t)be32toh(*(int32_t*)((_ch)->var))\n#define GET_UINT64(_ch) be64toh(*(uint64_t*)((_ch)->var))\n#define GET_INT64(_ch) (int64_t)be64toh(*(int64_t*)((_ch)->var))\n#define GET_FLOAT(_ch) beftoh(*(u32_a*)_ch->var)\n#define GET_DOUBLE(_ch) bedtoh(*(u64_a*)_ch->var)\n\n/**\n * Provides a type-agnostic return function\n */\n#define GET_VALUE(channel,out) \\\n({ \\\n channel_t *_ch = channel; \\\n if (!_ch) \\\n blast_fatal(#channel \" is NULL! Fix!\"); \\\n switch (_ch->type) { \\\n case TYPE_INT8: \\\n (out) = *(int8_t*)_ch->var; \\\n break; \\\n case TYPE_UINT8: \\\n (out) = *(uint8_t*)_ch->var; \\\n break; \\\n case TYPE_INT16: \\\n (out) = (int16_t)be16toh(*(uint16_t*)_ch->var); \\\n break; \\\n case TYPE_UINT16: \\\n (out) = be16toh(*(uint16_t*)_ch->var); \\\n break; \\\n case TYPE_INT32: \\\n (out) = (int32_t)be32toh(*(uint32_t*)_ch->var); \\\n break; \\\n case TYPE_UINT32: \\\n (out) = be32toh(*(uint32_t*)_ch->var); \\\n break; \\\n case TYPE_INT64: \\\n (out) = (int64_t)be64toh(*(uint64_t*)_ch->var); \\\n break; \\\n case TYPE_UINT64: \\\n (out) = be64toh(*(uint64_t*)_ch->var); \\\n break; \\\n case TYPE_FLOAT: \\\n (out) = beftoh(*(uint32_t*)_ch->var); \\\n break; \\\n case TYPE_DOUBLE: \\\n (out) = bedtoh(*(uint64_t*)_ch->var); \\\n break; \\\n default: \\\n out = (typeof(out))-1.0; \\\n blast_err(\"Invalid type %d\", _ch->type); \\\n } \\\n})\n\n/**\n * If you know what type of data you are setting, these macros are preferable to the\n * type-agnostic one below. However, be warned that if you change the type of the variable\n * in tx_struct, we can't protect you with these.\n */\n#define SET_UINT8(_ch,_val) (*(uint8_t*)((_ch)->var) = (_val))\n#define SET_INT8(_ch,_val) (*(int8_t*)((_ch)->var) = (_val))\n#define SET_UINT16(_ch,_val) ({uint16_t _x = _val;(*(uint16_t*)((_ch)->var) = htobe16(_x));})\n#define SET_INT16(_ch,_val) ({int16_t _x = _val;(*(uint16_t*)((_ch)->var) = htobe16(_x));})\n#define SET_UINT32(_ch,_val) ({uint32_t _x = _val;(*(uint32_t*)((_ch)->var) = htobe32(_x));})\n#define SET_INT32(_ch,_val) ({int32_t _x = _val;(*(uint32_t*)((_ch)->var) = htobe32(_x));})\n#define SET_UINT64(_ch,_val) ({uint64_t _x = _val;(*(uint64_t*)((_ch)->var) = htobe64(_x));})\n#define SET_INT64(_ch,_val) ({int64_t _x = _val;(*(uint64_t*)((_ch)->var) = htobe64(_x));})\n#define SET_FLOAT(_ch,_val) htobef(_val,*(uint32_t*)((_ch)->var))\n#define SET_DOUBLE(_ch,_val) htobed(_val,*(uint64_t*)((_ch)->var))\n\n#define SET_SCALED_VALUE(_channel,_val) \\\n({ \\\n channel_t *__ch = (_channel); \\\n double _new_val = (_val) - __ch->b_e2e; \\\n _new_val = _new_val / __ch->m_c2e; \\\n SET_VALUE(__ch,_new_val); \t\\\n})\n\n#define GET_SCALED_VALUE(_channel,val) \\\n({ \\\n channel_t *__ch = (_channel); \\\n double _new_val; \\\n GET_VALUE(__ch,_new_val); \t \\\n _new_val = _new_val * __ch->m_c2e; \\\n _new_val = _new_val + __ch->b_e2e; \\\n (val) = _new_val; \\\n})\n\n/**\n * Provides a type-agnostic value setting function\n */\n#define SET_VALUE(channel,in) \\\n({ \\\n channel_t *_ch = channel; \\\n typeof(in) _in = (in); \\\n uint32_t in32u = (uint32_t)_in; \\\n int32_t in32i = (int32_t)_in; \\\n uint16_t in16u = (uint16_t)_in; \\\n int16_t in16i = (int16_t)_in; \\\n switch (_ch->type) { \\\n case TYPE_INT8: \\\n *(int8_t*)_ch->var = (_in); \\\n break; \\\n case TYPE_UINT8: \\\n *(uint8_t*)_ch->var = (_in); \\\n break; \\\n case TYPE_INT16: \\\n *(uint16_t*)_ch->var = htobe16(in16i); \\\n break; \\\n case TYPE_UINT16: \\\n *(uint16_t*)_ch->var = htobe16(in16u); \\\n break; \\\n case TYPE_INT32: \\\n *(uint32_t*)_ch->var = htobe32(in32i); \\\n break; \\\n case TYPE_UINT32: \\\n *(uint32_t*)_ch->var = htobe32(in32u); \\\n break; \\\n case TYPE_INT64: \\\n *(uint64_t*)_ch->var = htobe64(in); \\\n break; \\\n case TYPE_UINT64: \\\n *(uint64_t*)_ch->var = htobe64(in); \\\n break; \\\n case TYPE_FLOAT: \\\n htobef(_in, _ch->var); \\\n break; \\\n case TYPE_DOUBLE: \\\n htobed(_in, _ch->var); \\\n break; \\\n default: \\\n blast_err(\"Invalid type %d\", _ch->type); \\\n } \\\n})\n#endif /* CHANNEL_MACROS_H_ */\n" }, { "alpha_fraction": 0.5949074029922485, "alphanum_fraction": 0.6736111044883728, "avg_line_length": 16.239999771118164, "blob_id": "0e282ddf2ba6c9148f6e471cb3006db91ad2683a", "content_id": "e4057abb01d8aa6239daae7209e19c53b97b1bf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 432, "license_type": "no_license", "max_line_length": 30, "num_lines": 25, "path": "/stars/utilities/imports/python/angles.py", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "from pylab import pi\n\ndef from_hours(angle):\n return angle*pi/12.\n\ndef to_hours(angle):\n return angle*12./pi\n\ndef from_degrees(angle):\n return angle*pi/180.\n\ndef to_degrees(angle):\n return angle*180./pi\n\ndef to_arcmin(angle):\n return angle*180./pi*60.\n\ndef from_arcmin(angle):\n return angle/60.*pi/180.\n\ndef to_arcsec(angle):\n return angle*180./pi*3600.\n\ndef from_arcsec(angle):\n return angle/3600.*pi/180.\n\n" }, { "alpha_fraction": 0.6947115659713745, "alphanum_fraction": 0.7131410241127014, "avg_line_length": 23.47058868408203, "blob_id": "1b439632adbc1d1e0969bb2bbfbd47311b59cc9c", "content_id": "216c31e766d368323c2aa543774677d31c60a8c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1248, "license_type": "no_license", "max_line_length": 71, "num_lines": 51, "path": "/common/include/log.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* mcp: the BLAST master control program\n *\n * This software is copyright (C) 2002-2006 University of Toronto\n *\n * This file is part of mcp.\n *\n * mcp 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#ifndef INCLUDE_LOG_H\n#define INCLUDE_LOG_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nstruct LOGGER\n{\n FILE * f;\n char * buffer;\n int loc;\n unsigned int blksize;\n int n;\n int isinit;\n};\n\n\nvoid initLogger(struct LOGGER *, char *, int);\nint readLogger(struct LOGGER *, char *);\nvoid resetLogger(struct LOGGER *);\nvoid closeLogger(struct LOGGER *);\n\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* INCLUDE_LOG_H */\n" }, { "alpha_fraction": 0.5633155703544617, "alphanum_fraction": 0.5895603895187378, "avg_line_length": 32.78325271606445, "blob_id": "3c486c651e2fa75b8e08d9835369d3cea568d9c9", "content_id": "8d23c462204d22581e98765c2de32b33818ee682", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13718, "license_type": "no_license", "max_line_length": 130, "num_lines": 406, "path": "/stars/code/displaying/visual.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"visual.h\"\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include <boost/filesystem/operations.hpp>\n#include \"../parameters/manager.h\"\n#include \"../shared/general/main_settings.h\"\n#include \"../shared/image/blobs.h\"\n#include \"../shared/image/leveled.h\"\n#include \"../shared/image/matching.h\"\n#include \"../shared/image/matching_progress.h\"\n#include \"../shared/image/status.h\"\n#include \"../shared/image/solution_summary.h\"\n#include \"../shared/solving/mask.h\"\n#include \"../logger_main.h\"\n\nusing namespace Displaying;\nusing std::max;\nusing std::min;\nusing std::string;\nusing Main::logger;\n#define shared_blobs (*(Shared::Image::blobs_solver_for_main.r))\n#define shared_matching (*(Shared::Image::matching.r))\n#define shared_match_progress (*(Shared::Image::matching_progress.r))\n#define shared_leveled (*(Shared::Image::leveled.r))\n#define shared_progress (*(Shared::Image::matching_progress.r))\n#define shared_status (*(Shared::Image::status_solver_for_main.r))\n#define shared_solution (*(Shared::Image::solution_summary_for_main.r))\n#define shared_mask (*(Shared::Solving::mask_solver_for_main.r))\n#define shared_main_settings (*(Shared::General::main_settings_net_for_main.r))\n\n// Disable warnings about conversions between GLfloat and double\n#ifdef _MSC_VER\n #pragma warning(disable:4244)\n #pragma warning(disable:4305)\n#endif\n\nVisual::Visual(Parameters::Manager& params)\n{\n display_enabled = params.general.try_get(\"main.display_enabled\", true);\n stars_dir = params.stars_dir;\n change_size(1024, 1024);\n main_window_height_ = 50;\n some_height_ = 50;\n base_blobs[0] = -1;\n base_blobs[1] = -1;\n base_blobs[2] = -1;\n base_progress = 0.0;\n display_blobs_.clear();\n frame_number = -1;\n display_base_sets.clear();\n texture_status = no_image;\n image_size.w = 600;\n image_size.h = 400;\n current_id = -1;\n last_blobs_counter_stars = -1;\n counter_stars_for_last_blob_names = -1;\n\n loading_screen_begun = false;\n}\n\nVisual::~Visual()\n{\n loading_screen.destroy(display_enabled);\n flash.destroy(display_enabled);\n mask.destroy(display_enabled);\n white.destroy(display_enabled);\n rendered_image.destroy(display_enabled);\n canvas.destroy(display_enabled);\n}\n\nvoid Visual::init(std::string title, Textures& textures_)\n{\n using namespace boost::filesystem;\n Block::init(title, textures_);\n loading_screen.init(display_enabled);\n loading_screen.load_tiff(system_complete(stars_dir + \"resources/edge2.tiff\").string());\n flash.init(display_enabled);\n flash.load_tiff(system_complete(stars_dir + \"resources/flash.tiff\").string());\n mask.init(display_enabled);\n mask.load_tiff(system_complete(stars_dir + \"resources/mask.tiff\").string());\n white.init(display_enabled);\n white.load_tiff(system_complete(stars_dir + \"resources/white.tiff\").string());\n rendered_image.init(display_enabled);\n canvas.init(display_enabled);\n}\n\nvoid Visual::clear()\n{\n display_blobs_.clear();\n base_blobs[0] = -1;\n base_blobs[1] = -1;\n base_blobs[2] = -1;\n base_progress = 0.0;\n display_base_sets.clear();\n image_age_timer.start();\n rendered_image_timer.start();\n texture_status = no_image;\n frame_number = -1;\n}\n\n\nvoid Visual::update_size(Size max_size)\n{\n Size new_size;\n new_size.w = min(max_size.w, max_size.h * image_size.w/image_size.h);\n new_size.h = min(max_size.h, max_size.w * image_size.h/image_size.w);\n Block::change_size(new_size);\n}\n\nvoid Visual::update()\n{\n using namespace Shared::Image;\n\n if (current_id != shared_status.counter_stars) {\n clear();\n current_id = shared_status.counter_stars;\n texture_status = image_not_rendered;\n image_age_timer = shared_status.age;\n image_size.w = shared_status.width;\n image_size.h = shared_status.height;\n display_blobs_.clear();\n }\n\n if (texture_status == image_not_rendered && shared_leveled.valid) {\n if (shared_leveled.counter_stars == shared_status.counter_stars) {\n rendered_image.bind_data(shared_leveled.pixels,\n shared_status.width, shared_status.height);\n rendered_image_timer.start();\n display_base_sets.clear();\n texture_status = image_rendered;\n }\n }\n if (texture_status == image_rendered) {\n if (shared_blobs.counter_stars != last_blobs_counter_stars) {\n display_blobs_.clear();\n for (unsigned int i=0; i<shared_blobs.blobs.size(); i++) {\n display_blobs_.push_back(Blob(shared_blobs.blobs[i].u, shared_blobs.blobs[i].v, i));\n }\n blobs_timer.start();\n last_blobs_counter_stars = shared_blobs.counter_stars;\n }\n if (display_blobs_.size() == shared_blobs.blobs.size()) {\n if (shared_matching.counter_stars == shared_status.counter_stars) {\n if (display_base_sets.size() != shared_matching.base_sets.size()) {\n for (unsigned int i=display_base_sets.size(); i<shared_matching.base_sets.size(); i++) {\n display_base_sets.push_back(BaseSet(shared_matching.base_sets[i]));\n base_progress = 0.0;\n }\n }\n if (shared_match_progress.counter_stars == shared_status.counter_stars &&\n shared_match_progress.triplet_counter == shared_matching.triplet_counter) {\n base_progress = shared_match_progress.progress;\n }\n }\n }\n if (shared_solution.counter_stars == shared_blobs.counter_stars && shared_solution.blob_names.size() > 0\n && shared_solution.counter_stars != counter_stars_for_last_blob_names) {\n counter_stars_for_last_blob_names = shared_solution.counter_stars;\n rendered_solution_timer.start();\n for (unsigned int i=0; i<shared_solution.blob_names.size(); i++) {\n for (unsigned int j=0; j<display_blobs_.size(); j++) {\n if (shared_solution.blob_names[i].blob_id == display_blobs_[j].blob_num) {\n display_blobs_[j].name = shared_solution.blob_names[i].name;\n }\n }\n }\n }\n }\n}\n\n\nvoid Visual::draw3d(Position& pos, Size& scaling)\n{\n glBindTexture(GL_TEXTURE_2D, textures->get(Textures::drawing_3d)); // Bind 0\n\tglDisable(GL_TEXTURE_2D);\n glPushMatrix();\n glViewport(pos.x*scaling.w, pos.y*scaling.h,\n width()*scaling.w, height()*scaling.h);\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluPerspective(45.0, width()/(height()-some_height_), 0.1, 100.0);\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n gluLookAt(0.0, 1.5, -3.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);\n\n static double angle = 0.0;\n angle += 3.0;\n glRotatef(angle,0.0,1.0,0.0);\n glBegin(GL_TRIANGLES);\n glColor3f(1.0f,0.0f,0.0f);\n glVertex3f( 0.0f, 1.0f, 0.0f);\n glColor3f(0.0f,1.0f,0.0f);\n glVertex3f(-1.0f,-1.0f, 0.0f);\n glColor3f(0.0f,0.0f,1.0f);\n glVertex3f( 1.0f,-1.0f, 0.0f);\n glEnd();\n\n glPopMatrix();\n\tglEnable(GL_TEXTURE_2D);\n glBindTexture(GL_TEXTURE_2D, 0); // unBind 0\n\n}\n\nvoid Visual::draw_flash(double age)\n{\n double opacity = 0.75*max(0.0, 1.0 - 2.0*age);\n opacity = 1.0;\n flash.draw(size(), opacity);\n}\n\nvoid Visual::draw_mask()\n{\n glPushMatrix();\n glBindTexture(GL_TEXTURE_2D, textures->get(Textures::basic_drawing)); // Bind 1\n glScalef(width()/image_size.w, height()/image_size.h, 1);\n\n Size block_dimensions;\n block_dimensions.w = shared_mask.block_size;\n block_dimensions.h = shared_mask.block_size;\n for (int j=0; j<shared_mask.num_blocks_y; j++) {\n for (int i=0; i<shared_mask.num_blocks_x; i++) {\n if (shared_mask.block_masked(i, j)) {\n glPushMatrix();\n glTranslatef(shared_mask.block_size*i, shared_mask.block_size*j, 0);\n mask.draw(block_dimensions, 0.50);\n glPopMatrix();\n }\n }\n }\n\n glBindTexture(GL_TEXTURE_2D, 0); // unBind 1\n glPopMatrix();\n}\n\nvoid Visual::draw_loading_screen()\n{\n if (!loading_screen_timer.started()) {\n loading_screen_timer.start();\n }\n loading_screen.draw(size());\n\n double age = loading_screen_timer.time() - 0.5;\n double speed = 0.2;\n Position pos;\n string words = \"\";\n\n words = \"Star Tracking\";\n pos.x = 70.0 + 30.0*(1.0 - exp(-age*speed));\n pos.y = 242.0;\n if (age <= 0.8) {\n pos.x -= exp( -20.0*(age - 0.8) ) - 1.0;\n }\n set_color(Color(1.0, 1.0, 1.0, 1.0));\n set_text_scaling(0.75, true);\n draw_text(words, pos);\n\n pos.x = 155.0 - 15.0*(1.0 - exp(-age*speed));\n pos.y = 210.0;\n words = \"Attitude Reconstruction Software\";\n if (age <= 1.0) {\n pos.x += exp( -20.0*(age - 1.0) ) - 1.0;\n }\n set_color(Color(1.0, 1.0, 1.0, 1.0));\n set_text_scaling(0.65, true);\n draw_text(words, pos);\n}\n\nvoid Visual::draw_blob_stripe(double intercept)\n{\n if (intercept < shared_status.width + shared_status.height) {\n glLineWidth(8.0);\n\t\tglDisable(GL_TEXTURE_2D);\n glPushMatrix();\n glColor4f(0.3, 0.0, 1.0, 0.7);\n glBegin(GL_LINES);\n {\n double x0, y0, x1, y1;\n if (intercept < shared_status.height) {\n x0 = 0.0;\n y0 = intercept;\n } else {\n x0 = intercept - shared_status.height;\n y0 = shared_status.height;\n }\n if (intercept < shared_status.width) {\n x1 = intercept;\n y1 = 0.0;\n } else {\n x1 = shared_status.width;\n y1 = intercept - shared_status.width;\n }\n glVertex2d(x0, y0);\n glVertex2d(x1, y1);\n }\n glEnd();\n glPopMatrix();\n\t\tglEnable(GL_TEXTURE_2D);\n glLineWidth(2.0);\n }\n}\n\nvoid Visual::draw_blobs(double age, double stripe_progress)\n{\n glPushMatrix();\n glBindTexture(GL_TEXTURE_2D, textures->get(Textures::basic_drawing)); // Bind 2\n glScalef(width()/image_size.w, height()/image_size.h, 1);\n\n Position pos;\n double width = 0.0;\n double height = 050;\n\n Size my_size = size();\n double intercept = stripe_progress * (shared_status.width + shared_status.height);\n draw_blob_stripe(intercept);\n for (unsigned int i=0; i<display_blobs_.size(); i++) {\n bool named = false;\n if (display_blobs_[i].name.size() > 0 && display_blobs_[i].born) {\n named = true;\n }\n display_blobs_[i].draw(my_size, age, intercept, shared_blobs.blobs[i].matched, named);\n }\n set_text_scaling(2.0);\n //double color_scaling = pow(sin(rendered_solution_timer.time()*1.5), 2.0);\n double color_scaling = sin(rendered_solution_timer.time()*3.0-M_PI/2.0)/2.0 + 0.5;\n set_color(Color(1.0, 1.0, 0, color_scaling));\n for (unsigned int i=0; i<display_blobs_.size(); i++) {\n if (display_blobs_[i].name.size() > 0 && display_blobs_[i].born) {\n get_text_size(display_blobs_[i].name.c_str(), width, height);\n if (display_blobs_[i].x + width > image_size.w) {\n pos.x = display_blobs_[i].x - width - 10.0;\n } else {\n pos.x = display_blobs_[i].x + 10.0;\n }\n if (display_blobs_[i].y - height < 0) {\n pos.y = display_blobs_[i].y + 25.0 + height;\n } else {\n pos.y = display_blobs_[i].y + -25.0;\n }\n draw_text(display_blobs_[i].name, pos);\n }\n }\n glBindTexture(GL_TEXTURE_2D, 0); // unBind 2\n glPopMatrix();\n}\n\nvoid Visual::draw_base_sets(double stripe_progress)\n{\n using namespace Shared::Image;\n\tglDisable(GL_TEXTURE_2D);\n glPushMatrix();\n glBindTexture(GL_TEXTURE_2D, textures->get(Textures::basic_drawing)); // Bind 3\n glScalef(width()/image_size.w, height()/image_size.h, 1);\n unsigned int num_sets = display_base_sets.size();\n double global_brightness = max(min(stripe_progress*0.5-0.3, 1.0), 0.0);\n if (num_sets > 0) {\n for (unsigned int i=0; i<num_sets-1; i++) {\n display_base_sets[i].draw(display_blobs_, 1.0, true, global_brightness);\n }\n display_base_sets[num_sets-1].draw(display_blobs_, base_progress, shared_status.stage == Status::done, global_brightness);\n }\n glBindTexture(GL_TEXTURE_2D, 0); // unBind 3\n glPopMatrix();\n\tglEnable(GL_TEXTURE_2D);\n}\n\nvoid Visual::draw(Position &pos, double flip_scaling)\n{\n glColor4f(1.0, 1.0, 1.0, 1.0);\n begin_draw(pos, flip_scaling);\n draw_border();\n\n if (texture_status == no_image) {\n draw_loading_screen();\n }\n else if (texture_status == image_rendered) {\n rendered_image.draw(size());\n\n if (!shared_main_settings.display_image_only) {\n draw_mask();\n\n if (shared_blobs.counter_stars == shared_status.counter_stars) {\n double blobs_age = blobs_timer.time();\n double stripe_progress = blobs_age*1.5;\n draw_blobs(blobs_age, stripe_progress);\n draw_base_sets(stripe_progress);\n }\n }\n\n double rendered_image_age = rendered_image_timer.time();\n if (rendered_image_age <= 0.5) {\n //draw_flash(rendered_image_age);\n }\n }\n else {\n white.draw(size(), 0.75);\n rendered_image_timer.start();\n }\n\n end_draw();\n}\n\n" }, { "alpha_fraction": 0.6113743782043457, "alphanum_fraction": 0.6279621124267578, "avg_line_length": 23.104761123657227, "blob_id": "abb5bdd908f9bf7cfd3a380ab730a4f57cdff7e1", "content_id": "72e3a091463b5662e501cdd14e03c69efb837851", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2532, "license_type": "no_license", "max_line_length": 74, "num_lines": 105, "path": "/common/log.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* mcp: the BLAST master control program\n *\n * This software is copyright (C) 2018-2019 Javier Romualdez, University of Toronto\n *\n * This file is part of mcp.\n *\n * mcp 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <stdio.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <stdint.h>\n#include <signal.h>\n#include <stdlib.h>\n#include <sys/io.h>\n#include <string.h>\n#include <time.h>\n\n#include \"log.h\"\n\n#ifndef MIN\n#define MIN(a, b) ((a) < (b) ? (a) : (b))\n#endif\n\n#ifndef MAX\n#define MAX(a, b) ((a) > (b) ? (a) : (b))\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nvoid initLogger(struct LOGGER * log, char * filename, int size)\n{\n closeLogger(log);\n\n log->f = fopen(filename, \"r\");\n\n if (log->f != NULL) {\n log->buffer = (char *) calloc(1, MAX(2048, size));\n log->loc = 0;\n log->blksize = size;\n log->n = 0;\n log->isinit = 1;\n\n // seek to the end of the file\n resetLogger(log);\n }\n}\nint readLogger(struct LOGGER * log, char * buffer)\n{\n if (!log->isinit) return -1;\n\n int cpy = 0;\n if (log->loc < log->n) { // data in the buffer still\n memset(buffer, 0, log->blksize); // reset\n cpy = MIN((int) log->n-log->loc, (int) log->blksize); // amount to cpy\n\n // printf(\"%d %d %d %d\\n\",log->loc, log->n, log->cpy, log->blksize);\n memcpy(buffer, log->buffer+log->loc, cpy);\n log->loc += cpy;\n } else { // data can be read from file\n size_t lenl = 2048;\n memset(buffer, 0, log->blksize); // reset again\n if (log->f != NULL) {\n fflush(log->f); // flush the buffer\n log->n = getline(&log->buffer, &lenl, log->f);\n }\n log->loc = 0;\n }\n return cpy;\n}\n\nvoid resetLogger(struct LOGGER * log)\n{\n if (log->isinit) {\n fseek(log->f, 0, SEEK_END);\n }\n}\n\nvoid closeLogger(struct LOGGER * log)\n{\n if (log->f) fclose(log->f);\n if (log->buffer) free(log->buffer);\n log->isinit = 0;\n}\n\n#ifdef __cplusplus\n}\n#endif\n\n" }, { "alpha_fraction": 0.7011986374855042, "alphanum_fraction": 0.7054794430732727, "avg_line_length": 11.98888874053955, "blob_id": "3cd0d6f930fa8652bcb2dfbb467d8128f8871aa9", "content_id": "d0ded2d8e97f9586c06e8cc8134a8c3029b0db2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1168, "license_type": "no_license", "max_line_length": 51, "num_lines": 90, "path": "/balloon_cam/cameraCommunicator.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//cameraCommunicator.h\n\n#pragma once\n\n#include \"stdafx.h\"\n#include \"locator.h\"\n\n#define DEFAULT_PORT \"31337\"\n\nclass CameraCommunicator {\n\npublic:\n\n\tCameraCommunicator(){};\n\n\tCameraCommunicator(Locator*);\n\n\t~CameraCommunicator();\n\n\tint addConnection(std::string);\n\n\tvoid removeConnection(std::string);\n\nprivate:\n\n\tvoid init(Locator*);\n\n\tint numConnections;\n\n\tLocator* locator;\n\n\tclass NetworkConnection{\n\n\tpublic:\n\n\t\tNetworkConnection(){};\n\t\t\n\t\tNetworkConnection(SOCKET, sockaddr, Locator *);\n\n\t\t~NetworkConnection();\n\t\t\n\t\tint loop();\n\n\t\tvoid endLoop();\n\n\t\tvoid setHostId(std::string data){hostId = data;};\n\n\t\tstd::string getHostId(){return hostId;};\n\n\t\tbool isLooping(){return looping;};\n\t\t\n\t\tvoid communicate();\n\n\tprivate:\n\n\t\ttimeval getData();\n\n\t\tint sendData(timeval, blob);\n\n\t\tSOCKET socketFileDescriptor;\n\n\t\tsockaddr* servInfo;\n\n\t\tstd::string hostId;\n\n\t\tbool looping;\n\n\t\tHANDLE threadHandle;\n\n\t\tDWORD threadId;\n\t\n\t\tstatic DWORD WINAPI communicate(void *);\n\n\t\tLocator* locator;\n\n\t\tbool pleaseStop;\n\n\t\tvoid log(timeval, timeval);\n\n\t};\n\n\tNetworkConnection* connection;\n\n\tstd::vector<NetworkConnection*>* list;\n\n\tSOCKET socketFileDescriptor;\n\n\taddrinfo* servInfo;\n\n};" }, { "alpha_fraction": 0.5503921508789062, "alphanum_fraction": 0.5625489950180054, "avg_line_length": 33.69047546386719, "blob_id": "139dd356ea85b178715c48bb26456a081460889b", "content_id": "689dc8ae5dd9764e2f9a80cb3242b25a2fe0d338", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10200, "license_type": "no_license", "max_line_length": 143, "num_lines": 294, "path": "/defricher/defricher_netreader.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * defricher_netreader.c: \n *\n * This software is copyright (C) 2013-2014 Seth Hillbrand\n *\n * This file is part of defricher, created for the BLASTPol Project.\n *\n * defricher 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 2 of the License, or\n * (at your option) any later version.\n *\n * defricher 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 defricher; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Apr 6, 2015 by Seth Hillbrand\n */\n\n#include <limits.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n#include <pthread.h>\n#include <unistd.h>\n\n#include <mosquitto.h>\n\n#include <lookup.h>\n#include \"blast.h\"\n#include \"channels_tng.h\"\n#include \"FIFO.h\"\n#include \"linklist_writer.h\"\n\n#include \"defricher.h\"\n#include \"defricher_utils.h\"\n#include \"defricher_writer.h\"\n\n#include \"defricher_data.h\"\n\n#ifndef HOST_NAME_MAX\n #define HOST_NAME_MAX 255\n#endif\n\nstatic struct mosquitto *mosq;\n\nstatic char client_id[HOST_NAME_MAX+1] = {0};\nstatic char remote_host[HOST_NAME_MAX+1] = {0};\nstatic int port = 1883;\nstatic int keepalive = 15;\n\nstatic void frame_handle_data(const char *m_rate, const void *m_data, const int m_len)\n{\n RATE_LOOKUP_T *rate;\n\n if (!m_rate) {\n defricher_err(\"Err in pointers\");\n return;\n }\n if (!m_len) {\n defricher_warn(\"Zero-length string for frame\");\n return;\n }\n\n for (rate = RATE_LOOKUP_TABLE; rate->position < RATE_END; rate++) {\n if (strncasecmp(rate->text, m_rate, BLAST_LOOKUP_TABLE_TEXT_SIZE) == 0) break;\n }\n if (rate->position == RATE_END) {\n defricher_err(\"Did not recognize rate %s!\\n\", m_rate);\n return;\n }\n\n if (ready_to_read(rate->position)) {\n channels_check_size_of_frame(rate->position, m_len);\n memcpy(getFifoWrite(&fifo_data[rate->position]), m_data, m_len);\n incrementFifo(&fifo_data[rate->position]);\n defricher_queue_packet(rate->position);\n }\n}\n\nstatic void frame_handle_linklist_data(uint8_t * m_data, unsigned int m_len) {\n if (m_len != rc.ll->blk_size) {\n defricher_err(\"Packet data size mismatch: expected %d bytes and received %d bytes\", rc.ll->blk_size, m_len);\n return;\n }\n\n static int counter = 0;\n static int first_time = 1;\n static linklist_dirfile_t * ll_dirfile = NULL;\n if (first_time) {\n ll_dirfile = open_linklist_dirfile(\"test.DIR\", rc.ll);\n first_time = 0;\n }\n\n write_linklist_dirfile(ll_dirfile, m_data);\n // defricher_info(\"Received data from %s (size %d == %d, frame = %d)\\n\", rc.linklist_file, rc.ll->blk_size, m_len, counter);\n}\n\nstatic void frame_message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message)\n{\n char **topics;\n int count;\n static uint32_t last_crc = 0;\n static uint32_t last_derived_crc = 0;\n char *telemetry = (char *) userdata;\n bool correct_topic = false;\n \n if(message->payloadlen){\n if (mosquitto_sub_topic_tokenise(message->topic, &topics, &count) == MOSQ_ERR_SUCCESS) {\n if (strcmp(telemetry, \"lab\") == 0) {\n correct_topic = (!rc.ll && (count == 4) && topics[0] && strcmp(topics[0], \"frames\") == 0);\n } else {\n correct_topic = (!rc.ll && (count == 3) && topics[0] && strcmp(topics[0], \"frames\") == 0 && strcmp(topics[1], telemetry) == 0);\n }\n if (correct_topic) {\n if (ri.channels_ready) {\n if (!strcasecmp(topics[count-1], \"200HZ\")) ri.read ++;\n frame_handle_data(topics[count-1], message->payload, message->payloadlen);\n }\n }\n if (strcmp(telemetry, \"lab\") == 0) {\n correct_topic = ((count == 3) && topics[0] && strcmp(topics[0], \"channels\") == 0);\n } else {\n correct_topic = ((count == 2) && topics[0] && strcmp(topics[0], \"channels\") == 0 && strcmp(topics[1], telemetry) == 0);\n }\n if (correct_topic) {\n if (((channel_header_t*)message->payload)->crc != last_crc && !ri.new_channels) {\n defricher_info( \"Received updated Channels. Ready to initialize new DIRFILE!\");\n if (channels_read_map(message->payload, message->payloadlen, &new_channels) > 0 ) {\n defricher_startup(\"Ready to init channels\");\n ri.new_channels = true;\n last_crc = ((channel_header_t*)message->payload)->crc;\n }\n }\n }\n if (strcmp(telemetry, \"lab\") == 0) {\n correct_topic = ((count == 3) && topics[0] && strcmp(topics[0], \"derived\") == 0);\n } else {\n correct_topic = ((count == 2) && topics[0] && strcmp(topics[0], \"derived\") == 0 && strcmp(topics[1], telemetry) == 0);\n }\n if (correct_topic) {\n if (((derived_header_t*)message->payload)->crc != last_derived_crc) {\n defricher_info( \"Received updated Derived Channels.\");\n if (channels_read_derived_map(message->payload, message->payloadlen, &derived_channels) > 0 ) {\n defricher_request_updated_derived();\n last_derived_crc = ((derived_header_t*)message->payload)->crc;\n }\n }\n }\n if (strcmp(telemetry, \"lab\") == 0) {\n correct_topic = false;\n } else {\n correct_topic = (rc.ll && (count == 2) && topics[0] && strcmp(topics[0], \"linklists\") == 0); \n }\n if (correct_topic) {\n if (ri.channels_ready) {\n ri.read += 200;\n frame_handle_linklist_data(message->payload, message->payloadlen);\n }\n }\n mosquitto_sub_topic_tokens_free(&topics, count);\n }\n\n }\n fflush(stdout);\n}\n\nstatic void frame_connect_callback(struct mosquitto *mosq, void *userdata, int result)\n{\n if(!result){\n /* Subscribe to broker information topics on successful connect. */\n mosquitto_subscribe(mosq, NULL, \"$SYS/#\", 2);\n }else{\n defricher_strerr( \"Connect failed\");\n }\n}\n\nstatic void frame_log_callback(struct mosquitto *mosq, void *userdata, int level, const char *str)\n{\n if (level & MOSQ_LOG_ERR)\n defricher_err( \"%s\\n\", str);\n else if (level & MOSQ_LOG_WARNING)\n defricher_warn( \"%s\\n\", str);\n}\n\n\nstatic void *netreader_routine(void *m_arg)\n{\n int ret;\n\n defricher_info( \"Starting Framing task\\n\");\n\n while (!ri.reader_done)\n {\n ret = mosquitto_loop(mosq, 100, 1);\n switch(ret) {\n case MOSQ_ERR_SUCCESS:\n break;\n case MOSQ_ERR_NO_CONN:\n if (rc.auto_reconnect){\n sleep(5);\n defricher_warn(\"No connection to %s. Retrying...\", remote_host);\n mosquitto_reconnect(mosq);\n } else {\n defricher_err(\"Not connected to %s. Quitting.\", remote_host);\n ri.reader_done = 1;\n ri.writer_done = 1;\n }\n break;\n case MOSQ_ERR_CONN_LOST:\n if (rc.auto_reconnect){\n defricher_warn(\"Lost connection to %s. Trying to reconnect...\", remote_host);\n mosquitto_reconnect(mosq);\n } else {\n defricher_err(\"Lost connection to %s\", remote_host);\n ri.reader_done = 1;\n ri.writer_done = 1;\n }\n break;\n default:\n defricher_err(\"Received %d from mosquitto_loop, corresponding to %s\", ret, mosquitto_strerror(ret));\n sleep(1);\n break;\n }\n fflush(NULL);\n }\n\n mosquitto_destroy(mosq);\n mosquitto_lib_cleanup();\n return NULL;\n}\n\n/**\n * Initializes the mosquitto library and associated framing routines.\n * @return\n */\npthread_t netreader_init(const char *m_host, char *m_telemetry)\n{\n pthread_t netread_thread;\n\n gethostname(client_id, HOST_NAME_MAX);\n strncpy(remote_host, m_host, HOST_NAME_MAX);\n\n mosquitto_lib_init();\n mosq = mosquitto_new(client_id, true, NULL);\n if (!mosq) {\n defricher_strerr(\"mosquitto_new() failed\");\n return 0;\n }\n mosquitto_log_callback_set(mosq, frame_log_callback);\n\n mosquitto_connect_callback_set(mosq, frame_connect_callback);\n mosquitto_message_callback_set(mosq, frame_message_callback);\n mosquitto_user_data_set(mosq, (void *) m_telemetry);\n// mosquitto_subscribe_callback_set(mosq, frame_subscribe_callback);\n\n if (mosquitto_connect(mosq, remote_host, port, keepalive)) {\n defricher_strerr(\"Unable to connect.\\n\");\n return 0;\n }\n \n char framename[32] = {0};\n\n if (rc.linklist_file) { // linklist mode\n int i;\n for (i = strlen(rc.linklist_file)-1; i >=0 ; i--) {\n if (rc.linklist_file[i] == '/') break;\n }\n sprintf(framename, \"linklists/%s\", rc.linklist_file+i+1); \n } else { // normal full channel mode\n if (strcmp(m_telemetry, \"lab\") == 0) {\n sprintf(framename, \"frames/#\");\n } else {\n sprintf(framename, \"frames/%s/#\", m_telemetry);\n }\n }\n\n\t\tmosquitto_subscribe(mosq, NULL, framename, 2);\n mosquitto_subscribe(mosq, NULL, \"channels/#\", 2);\n mosquitto_subscribe(mosq, NULL, \"derived/#\", 2);\n\n\t\tprintf(\"Subscribed to \\\"%s\\\"\\n\", framename);\n\n if (!pthread_create(&netread_thread, NULL, &netreader_routine, NULL))\n return netread_thread;\n return 0;\n}\n\n" }, { "alpha_fraction": 0.6909254193305969, "alphanum_fraction": 0.6936208605766296, "avg_line_length": 24.88372039794922, "blob_id": "4ccbb21b5d1acc1d56bdac67c01ac6d715ca39c9", "content_id": "15bd1aefbb21941617c271002b397de297994f9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1113, "license_type": "no_license", "max_line_length": 78, "num_lines": 43, "path": "/liblinklist/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "set(LL_SOURCES\n ${LL_SOURCES}\n ${CMAKE_CURRENT_SOURCE_DIR}/linklist.c\n ${CMAKE_CURRENT_SOURCE_DIR}/linklist_compress.c\n ${CMAKE_CURRENT_SOURCE_DIR}/linklist_writer.c\n ${CMAKE_CURRENT_SOURCE_DIR}/linklist_connect.c\n)\n\nset(LL_HEADERS\n ${LL_HEADERS}\n ${CMAKE_CURRENT_SOURCE_DIR}/linklist.h\n ${CMAKE_CURRENT_SOURCE_DIR}/linklist_compress.h\n ${CMAKE_CURRENT_SOURCE_DIR}/linklist_writer.h\n ${CMAKE_CURRENT_SOURCE_DIR}/linklist_connect.h\n)\n\nIF(BUILD_LIBRARY)\n\t\tproject(linklist)\n\t\tcmake_minimum_required(VERSION 2.8.8)\n\t\tinclude(GNUInstallDirs)\n set(CMAKE_POSITION_INDEPENDENT_CODE ON)\n\n\t\tadd_library(linklist STATIC\n\t\t\t\t${LL_SOURCES}\n\t\t\t\t${LL_HEADERS}\n\t\t)\n\n\t\ttarget_include_directories(linklist PRIVATE .)\n\n\t\tinstall(TARGETS linklist DESTINATION ${CMAKE_INSTALL_LIBDIR})\n IF(CUSTOM_INSTALL)\n\t\t install(TARGETS linklist DESTINATION ${CUSTOM_INSTALL}) \n ELSE()\n\t\t install(FILES ${HEADERS} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/linklist)\n ENDIF()\nELSE()\n\t\tset(LL_HEADERS\n\t\t\t\t${LL_HEADERS}\n PARENT_SCOPE)\n\t\tset(LL_SOURCES\n\t\t\t\t${LL_SOURCES}\n PARENT_SCOPE)\nENDIF()\n" }, { "alpha_fraction": 0.6857671141624451, "alphanum_fraction": 0.6902033090591431, "avg_line_length": 30.080459594726562, "blob_id": "4d7b6e7e16d802450f400f65813a564a5f3cf950", "content_id": "d547846136691edc608bd9cb9da1768ede257678", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2706, "license_type": "no_license", "max_line_length": 98, "num_lines": 87, "path": "/stars/code/cataloging/abstract_catalog_manager.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef CATALOGING__ABSTRACT_CATALOG_MANAGER_H\n#define CATALOGING__ABSTRACT_CATALOG_MANAGER_H\n\n#include <vector>\n#include <array>\n#include <boost/filesystem/fstream.hpp>\n#include \"../solving/solution.h\"\n#include \"../solving/star.h\"\n#include \"../solving/blob.h\"\n#include \"../shared/solving/filters.h\"\n#include \"../shared/solving/settings.h\"\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Cataloging\n{\n class Region;\n class AbstractCatalogManager;\n namespace fs = boost::filesystem;\n}\n\nnamespace Logging\n{\n class Logger;\n}\n\nclass Cataloging::Region\n{\n public:\n Region();\n std::vector<Solving::Star> stars;\n double ra, dec;\n};\n\nclass Cataloging::AbstractCatalogManager\n{\n public:\n AbstractCatalogManager(Parameters::Manager& params, bool enabled, std::string catalog_path_,\n Logging::Logger& logger_);\n virtual ~AbstractCatalogManager();\n void init();\n Region load_region(fs::path filename);\n void load_regions();\n bool in_range(double value, double min, double max);\n std::vector<Solving::Solution> load_triplets_from_file(std::vector<Solving::Blob>& base_blobs,\n int leg0, int leg1,\n double leg0min, double leg0max, double leg1min,\n double leg1max, double leg2min, double leg2max, Shared::Solving::Filters& filters);\n std::vector<Solving::Solution> load_solutions_from_triplet(std::vector<Solving::Blob>& blobs,\n Shared::Solving::Filters& filters);\n std::vector<Solving::Solution> load_pairs_from_file(std::vector<Solving::Blob>& base_blobs,\n int leg, double leg_min, double leg_max, Shared::Solving::Filters& filters);\n std::vector<Solving::Solution> load_solutions_from_pair(std::vector<Solving::Blob>& blobs,\n Shared::Solving::Filters& filters);\n std::vector<Solving::Star> get_stars_near(double ra, double dec);\n double get_epoch();\n void precess_if_desired(double epoch, float& ra, float& dec);\n void precess_if_desired(double epoch, double& ra, double& dec);\n void fill_stars_in_fov(::Solving::Solution& solution, Shared::Image::Raw& image,\n Shared::Solving::Refraction& refraction_settings);\n void get_star_name(int id, std::string& name, double& mag);\n\n protected:\n virtual bool abort();\n Logging::Logger *logger;\n\n private:\n int image_width;\n int image_height;\n fs::path catalog_path;\n\tstd::vector<std::pair<double, std::string>> star_names;\n std::vector<Region> regions;\n double mag_limit;\n\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.37612614035606384, "alphanum_fraction": 0.43918919563293457, "avg_line_length": 21.200000762939453, "blob_id": "8e58bd6c21aebe88f2a1cbdce6e6ad94bc3f4d9c", "content_id": "82deac35004da5c34dd6ba734cc52968b0b7584b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 444, "license_type": "no_license", "max_line_length": 63, "num_lines": 20, "path": "/starcam/powercycle.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <errno.h>\n#include <unistd.h>\n#include <sys/io.h>\n\nint main(void)\n{\n if (ioperm(0x378, 0x0F, 1) != 0) {\t\n perror(\"Unable to power cycle\");\n }\n\n printf(\"================================================\\n\");\n printf(\"== Power Cycling the Camera ==\\n\");\n printf(\"================================================\\n\");\n outb(0xFF, 0x378);\n usleep(2000000);\n outb(0x00, 0x378);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.4470588266849518, "alphanum_fraction": 0.45490196347236633, "avg_line_length": 29, "blob_id": "6354f0b983e5011e30bfa1eb8c4ef7c3a99caf4e", "content_id": "b9210ccbb0dc1ecf90f9747b4a741e588db7468a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 510, "license_type": "no_license", "max_line_length": 49, "num_lines": 17, "path": "/untarloop/untarloop.sh", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#!/bin/bash\ninotifywait -m ./ -e create -e moved_to |\n while read path action file; do\n if [ ${file:0:10} = \"file_block\" ]; then \n inotifywait -e close_write $file\n echo \"Untarring..'$file'\"\n tar -xf $file\n echo \"Done\"\n rm $file\n elif [ ${file: -6} = \"tar.gz\" ]; then \n #inotifywait -e close $file\n echo \"Untarring..'$file'\"\n tar -xf $file\n echo \"Done\"\n rm $file\n fi\n done\n" }, { "alpha_fraction": 0.6993464231491089, "alphanum_fraction": 0.7040998339653015, "avg_line_length": 23.75, "blob_id": "27f11fb1b7aee1b270dd312a7486c9895596e8e2", "content_id": "9cf5293c10a421ec864de5946a84b41a3e3d2704", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1684, "license_type": "no_license", "max_line_length": 93, "num_lines": 68, "path": "/stars/code/imaging/abstract_camera.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef IMAGING__ABSTRACT_CAMERA_H\n#define IMAGING__ABSTRACT_CAMERA_H\n\n#include <string>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include \"fake_sky.h\"\n#include \"../tools/timing.h\"\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Imaging\n{\n class AbstractCamera;\n}\n\nclass Imaging::AbstractCamera\n{\n public:\n AbstractCamera(Parameters::Manager& params);\n virtual ~AbstractCamera();\n void update();\n void fill_general_admin();\n void fill_real_camera_admin(boost::posix_time::ptime& timestamp, bool multiple_triggers);\n void save_image(unsigned short* pixels, int buffer_num, bool multiple_triggers);\n void share_image();\n bool enough_space_to_save_images();\n bool need_to_try_camera_ready();\n virtual void wait_for_quit();\n\n protected:\n virtual bool init_camera() = 0;\n virtual void clean_up_camera() = 0;\n virtual void read_image_if_available() = 0;\n\n static const unsigned int max_num_buffers = 4;\n\n bool enabled;\n bool internal_triggering;\n double internal_exposure_time;\n double internal_period;\n std::string output_dir;\n\n bool camera_ready;\n Tools::Timer check_camera_ready_timer;\n double check_camera_ready_period;\n double max_exposure_time;\n\n unsigned short* intermediate_buffer;\n unsigned short* buffers[max_num_buffers];\n unsigned int num_buffers_filled;\n\n int image_width, image_height;\n\tint last_lens_requests_focus_counter;\n\n FakeSky fake_sky;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6996527910232544, "alphanum_fraction": 0.7065972089767456, "avg_line_length": 17.54838752746582, "blob_id": "519c7f6b219f1efc8f6e19a1171b12c28c2f55a2", "content_id": "3ac8e31f49912aadce8cb0fdf1d628bb69909f4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 577, "license_type": "no_license", "max_line_length": 73, "num_lines": 31, "path": "/stars/code/displaying/network.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__NETWORK_H\n#define DISPLAYING__NETWORK_H\n\n#include \"block.h\"\n#include \"dynamic_value.h\"\n\nnamespace Displaying\n{\n class Network;\n}\n\nclass Displaying::Network: public Block\n{\n public:\n Network();\n void draw_packets();\n void draw(Position& position);\n\n private:\n DynamicValue counter_fcp;\n DynamicValue counter_stars;\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.5889967679977417, "alphanum_fraction": 0.6159654855728149, "avg_line_length": 24.75, "blob_id": "e14f5a8a1e779fe614f406d3d41b8ba3a17e1584", "content_id": "b1b05e047c9e26da47fd167cef1cebe4eaf0152b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 928, "license_type": "no_license", "max_line_length": 88, "num_lines": 36, "path": "/stars/code/tools/psf.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"psf.h\"\n#include \"quick_cout.h\"\n#include <cstdio>\n#include <algorithm>\n\nusing std::vector;\nusing std::min;\nusing std::max;\nusing namespace Tools::PSF;\n\nvoid Tools::PSF::get_kernel_separated_gauss(double *gauss, int halfwidth, double size)\n{\n int i;\n double u, sigma, total;\n sigma = size;\n total = 0;\n for(i=0; i<halfwidth*2+1; i++){\n u = i - halfwidth;\n gauss[i] = exp(-(u*u)/(2.0*sigma*sigma)) / (2.0*M_PI*sigma*sigma);\n total += gauss[i];\n }\n for(i=0; i<halfwidth*2+1; i++){\n gauss[i] /= total;\n }\n}\n\ndouble Tools::PSF::gaussian(double A, double sigma, double x, double y)\n{\n return A*exp(-0.5*(pow(x/sigma, 2.0)+pow(y/sigma, 2.0)))/(2.0*M_PI*pow(sigma, 2.0));\n}\n" }, { "alpha_fraction": 0.5429995656013489, "alphanum_fraction": 0.671790599822998, "avg_line_length": 33.71154022216797, "blob_id": "68553a055cc475d4ce339a3b4c00feb717f04871", "content_id": "5d8b5f4073f303707d84e78b98702d09fa5e106f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7221, "license_type": "no_license", "max_line_length": 112, "num_lines": 208, "path": "/blast_config/include/calibrate.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "\n/* calibrate.h: field calibrations for the BLASTBus (formerly in channels.h)\n *\n * This software is copyright (C) 2011 University of Toronto\n *\n * This file is part of the BLAST flight code licensed under the GNU\n * General Public License.\n *\n * You should have received a copy of the GNU General Public License\n * along with this software; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n\n#ifndef CALIBRATE_H\n#define CALIBRATE_H\n\n/* Fix things up so we can include this in C++ applications */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* BLASTBus frame sample rate */\n#define SR (100)\n\n/**\n * Scaling factors for each motor. These are hard-wired based on the encoder/resolver\n */\n#define RW_ENCODER_COUNTS (1 << 21)\n#define RW_COUNTS_PER_REV (1 << 13)\n#define PIV_RESOLVER_COUNTS (1 << 14)\n\n#define EL_LOAD_ENCODER_COUNTS (1 << 26) /* This is the External, absolute encoder mounted on the inner frame */\n#define EL_LOAD_COUNTS_PER_REV (1 << 26)\n//#define EL_MOTOR_ENCODER_COUNTS 655360 /* This is (1 << 19) / 0.8 to correct for the gearbox */\n#define EL_MOTOR_ENCODER_COUNTS (1 << 19) /* No gearbox */\n#define EL_MOTOR_COUNTS_PER_REV (1 << 19)\n\n#define RW_ENCODER_SCALING (360.0 / RW_ENCODER_COUNTS)\n#define EL_MOTOR_ENCODER_SCALING ((-1.0)*360.0 / EL_MOTOR_ENCODER_COUNTS)\n#define EL_LOAD_ENCODER_SCALING (360.0 / EL_LOAD_ENCODER_COUNTS)\n#define PIV_RESOLVER_SCALING (360.0 / PIV_RESOLVER_COUNTS)\n#define EL_MOTOR_CURRENT_SCALING (-1.0) /* So that current > 0 -> El increase */\n\n/* Gains and offsets for ideal analog cards: cal = (counts + B)*M */\n#define M_32PRE (10.24/2147483648.0)\n#define B_32PRE\t(-2147483648.0)\n#define M_16PRE (10.24/32768.0)\n#define B_16PRE (-32768.0)\n\n\n/* Gains and offsets to normalize to -1 to 1: cal = (counts + B)*M */\n#define M_32UNI (1.0/2147483648.0)\n#define B_32UNI (-2147483648.0)\n#define M_16UNI (1.0/32768.0)\n#define B_16UNI (-32768.0)\n\n/* Gains and offsets for the labjack AIN channels: cal = (counts + B)*M */\n#define M_16LJAIN (10.8/32768.0)\n#define B_16LJAIN (-10.8)\n\n/* Gains and offsets for the roaches: */\n#define M_32LOFREQ (0.00001)\n#define B_32LOFREQ (750)\n#define M_16LOFREQ (0.001)\n#define B_16LOFREQ (750)\n#define M_16RFREQ (100.0/32768) // kHz\n#define B_16RFREQ (-100.0)\n#define M_32RFREQ (100000.0/(1 << 31)) // kHz\n#define B_32RFREQ (-100000.0)\n#define M_16R_DB (50.0/65536) // kHz\n#define B_16R_DB (0.0)\n\n/* Gains and offsets for pointing sensors: */\n#define M_16MAG (1.0/15000.0)\n\n/* bare thermometer conversion to Volts. No negative values allowed */\n#define M_16T (4.096/32768.0/2.0)\n#define B_16T (0.0)\n/* AD590 calibrations. To Kelvin */\n#define M_16_AD590\t(M_16T/2.2E-3)\n#define B_16_AD590\t(B_16T)\n\n/* offset of encoder. Reset if encoder has been unmounted. */\n/* This is the elevation at which the encoder wraps around */\n#define ENC_RAW_EL_OFFSET (321.74) //LMF 17-Dec-2018\n /* Note this is referenced relative to lock pin hole 25*/\n// #define ENC_RAW_EL_OFFSET (291.84) //PCA 11-May-2017\n// /* Note this is referenced relative to lock pin hole 0*/\n\n/* to get proper wrapping in KST, the encoder elevation type should be\n * 'u' for 135 <= ENC_EL_RAW_OFFSET < 315 and 's' otherwise */\n#define ENC_ELEV_TYPE 'u'\n\n#define ROX_C2V (5.43736e-07/256.0)\n#define ROX_OFFSET (-1.1403)\n\n#define STAGE_X_THROW 78500\n#define STAGE_Y_THROW 78250\n\n#define ACTENC_TO_UM 1.05833333333 /* mm/enc.counts = 24000 counts/inch */\n//#define ACTENC_OFFSET 1000000 /* this number should be arbitrarily larger than\n //the maximum throw */\n\n//ideal calibrations NB: LVDT and ENC have different signs\n#define LVDT63_ADC_TO_ENC -0.75 /* adc counts to encoder counts */\n#define LVDT64_ADC_TO_ENC -0.75 /* adc counts to encoder counts */\n#define LVDT65_ADC_TO_ENC -0.75 /* adc counts to encoder counts */\n//LVDT flat fielding sjb: 28 Nov 2010\n#define LVDT63_ZERO 64389 /* in encoder counts */\n#define LVDT64_ZERO 65240 /* in encoder counts */\n#define LVDT65_ZERO 65536 /* in encoder counts */\n\n/* Thermal model numbers, from EP */\n#define T_PRIMARY_FOCUS 296.15 /* = 23C */\n#define T_SECONDARY_FOCUS 296.15 /* = 23C */\n#define POSITION_FOCUS 33333 /* absolute counts */\n\n#ifndef CAM_WIDTH\n#define CAM_WIDTH 1530.0 //should always be the larger dimension\n#endif\n\n#define H2LI (4294967296.0/24.0)\n#define LI2H (1.0/H2LI)\n#define DEG2LI (4294967296.0/360.0)\n#define LI2DEG (1.0/DEG2LI)\n#define RAD2LI (4294967296.0/2/M_PI)\n#define DEG2I (65536.0/360.0)\n#define I2DEG (1.0/DEG2I)\n#define RAD2I (65536.0/2/M_PI)\n#define H2I (65536.0/24.0)\n#define I2H (1.0/H2I)\n#define VEL2I (65536.0/10.0)\n#define I2VEL (1.0/VEL2I)\n\n/* Cryo preamp channel Voltage calibration */\n/* Measured by Tristan @ Penn, September 29 2009 */\n#define CRYO_A2_M ( 4.805248E-9)\n#define CRYO_A2_B (-1.032198E1 )\n/* Cryo Diode Voltage Calibration */\n/* Modified by Ian Summer 2017 */\n#define CRYO_D_M ( 10.34/32768)\n#define CRYO_D_B (-10.5869)\n/* modified Ian and Mark Palestine */\n#define CRYO_R_M ( 1.034/32768 )\n#define CRYO_R_B (-1.05869 )\n/* M3 was not measured (spider cable broken) so is an estimate */\n#define CRYO_M3_M (1.1319609e-05)\n#define CRYO_M3_B (-24293.822)\n/* Current ranges +/-15 Amps*/\n#define CUR15_M (15/32768.0)\n#define CUR15_B (-15.0)\n\n#define CURLOOP_CONV (50.0/8.0) /* 50 Amps = 8.0V */\n/* Current sensor ranges +/-67.5 Amps*/\n#define CURLOOP_D_M (10.8/32768.0*50.0/8.0)\n#define CURLOOP_D_B (-67.5)\n\n\n// Conversion factors for the rotated/calibrated gyros\n// (GY_IFEL, GY_IFYAW, GY_IFROLL).\n// Any correction to these belongs in ACS1, not here\n#define DPS_TO_GY16 1000.0 // 1 gyro bit == 0.001 dps \n#define GY16_TO_DPS (1.0/DPS_TO_GY16)\n#define GY16_OFFSET 32768.0\n\n// Conversion factors for raw 32 bit digital gyro chanels\n// put any correction to these directly in tx_struct.c\n// these should only appear in tx_struct.c\n#define DGY32_TO_DPS (60.0E-6 * 4.0/256.0)\n#define DPS_TO_DGY32 (1.0/DGY32_TO_DPS)\n#define DGY32_OFFSET (32768.0*65536.0)\n\n// Conversion factors for the Pivot motor control loop.\n// Used in motors.c and tx_struct.c\n#define PIV_I_TO_DAC 3255.029 \n#define DAC_TO_PIV_I 1.0/PIV_I_TO_DAC\n\n#define PIV_DAC_OFF (-1)*102 // 31mV Analog Input voltage offset\n // as measured by the pivot controller\n#define PIV_DEAD_BAND 162.75 // 50mV*3.255029 DAC cts/mV\n\n/* zero point (in counts) of i_el */\n#define I_EL_ZERO 32638\n\n/**\n * UEI internal monitoring channels\n */\n#define UEI_VOLT_M (0.000000149*23.1) /// 149 nV * 23.1V scaler\n#define UEI_VOLT_B (-8388608.0 * UEI_VOLT_M) /// 2^23 (24-bit ADC)\n\n#define UEI_TEMP_M (0.000000149*339) /// 149 nV * 339V scaler\n#define UEI_TEMP_B (-8388608.0 * UEI_TEMP_M) /// 2^23 (24-bit ADC)\n\n#define UEI_INTVOLT_M (0.000000149*45.3) /// 149 nV * 45.3V scaler\n#define UEI_INTVOLT_B (-8388608.0 * UEI_INTVOLT_M) /// 2^23 (24-bit ADC)\n\n#define UEI_CURRENT_M (0.000000149*12) /// 149 nV * 12V scaler\n#define UEI_CURRENT_B (-8388608.0 * UEI_CURRENT_M) /// 2^23 (24-bit ADC)\n\n#define LOCKIN_C2V (6.90336327e-7)\n#define LOCKIN_OFFSET (-5.78715355)\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n" }, { "alpha_fraction": 0.6871609687805176, "alphanum_fraction": 0.6962025165557861, "avg_line_length": 24.5230770111084, "blob_id": "b46d01827a1ef9a2d8890ce2a453f4b1f5e67e7a", "content_id": "c9bed4265805615290b2624e6b76fa6cb76ccde2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1659, "license_type": "no_license", "max_line_length": 71, "num_lines": 65, "path": "/common/command_common.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* mcp: the BLAST master control program\n *\n * commands.c: functions for listening to and processing commands\n *\n * This software is copyright (C) 2002-2010 University of Toronto\n *\n * This file is part of mcp.\n *\n * mcp 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp 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 mcp; if not, write to the Free Software Foundation, Inc.,\n *\n */\n#include \"command_common.h\"\n#include \"command_list.h\"\n\nstatic const char *UnknownCommand = \"Unknown Command\";\n\nint SIndex(enum singleCommand command)\n{\n int i;\n\n for (i = 0; i < N_SCOMMANDS; i++)\n if (scommands[i].command == command)\n return i;\n\n return -1;\n}\n\nconst char* SName(enum singleCommand command)\n{\n int i = SIndex(command);\n return (i == -1) ? UnknownCommand : scommands[i].name;\n}\n\nint MIndex(enum multiCommand command)\n{\n int i;\n\n for (i = 0; i < N_MCOMMANDS; i++)\n if (mcommands[i].command == command)\n return i;\n\n return -1;\n}\n\nconst char* MName(enum multiCommand command)\n{\n int i = MIndex(command);\n return (i == -1) ? UnknownCommand : mcommands[i].name;\n}\n\nconst char* CommandName(int is_multi, int command)\n{\n return (is_multi) ? MName(command) : SName(command);\n}\n" }, { "alpha_fraction": 0.6704961061477661, "alphanum_fraction": 0.6778067946434021, "avg_line_length": 23.55128288269043, "blob_id": "08fcb0202abc52c5c5bb34fd57c951f22a9181f5", "content_id": "b9b411c823d0118053d5baefb9c5fc4290d4d869", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3830, "license_type": "no_license", "max_line_length": 150, "num_lines": 156, "path": "/stars/code/dmm.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "\n#include <string>\n#include <windows.h>\n\n#include \"logger_main.h\"\n#include \"dmm.h\"\n\nusing Main::logger;\n\ndmm::dmm()\n{\n\tmemset(&dsccb, 0, sizeof(dsccb));\n\tdsccb.base_address = 0x300;\n\tdsccb.int_level = 3;\n\tdscb = 0;\n\n\tinitialized = false;\n}\n\n\ndmm::~dmm()\n{\n\tif (initialized) dscFree();\n\tinitialized = false;\n\n}\n\nvoid dmm::dmm_initialize()\n{\n\tERRPARAMS errorParams; // structure for returning error code and error string\n\tstring logerror = \"\";\n\tlogger.log(format(\"Initializing DMM-XT\").str());\n\n\tif (!initialized) {\n\t\tif (dscInit(DSC_VERSION) != DE_NONE) {\n\t\t\tdscGetLastError(&errorParams);\n\t\t\tlogerror = (format(\"dscInit error: %s (%s)\") % dscGetErrorString(errorParams.ErrCode) % errorParams.errstring).str();\n\t\t\tlogger.log(logerror);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (dscInitBoard(DSC_DMM, &dsccb, &dscb) != DE_NONE) {\n\t\tdscGetLastError(&errorParams);\n\t\tlogerror = (format(\"dscInitBoard error: %s (%s)\") % dscGetErrorString(errorParams.ErrCode) % errorParams.errstring).str();\n\t\tlogger.log(logerror);\n\t\tdscFree();\n\t\tinitialized = false;\n\t\treturn;\n\t}\n\n\tdscadsettings.range = RANGE_5;\n\tdscadsettings.polarity = UNIPOLAR;\n\tdscadsettings.gain = GAIN_1;\n\tdscadsettings.load_cal = (BYTE)TRUE;\n\tdscadsettings.current_channel = 0;\n\n\tdscadscan.low_channel = 0;\n\tdscadscan.high_channel = 15;\n\n\tif (dscADSetSettings(dscb, &dscadsettings) != DE_NONE)\n\t{\n\t\tdscGetLastError(&errorParams);\n\t\tlogerror += (format(\"dscADSetSettings error: %s (%s)\") % dscGetErrorString(errorParams.ErrCode) % errorParams.errstring).str();\n\t\tlogger.log(logerror);\n\t\tdscFreeBoard(dscb);\n\t\tdscFree();\n\t\tinitialized = false;\n\t\treturn;\n\t}\n\n\tinitialized = true;\n}\n\nvoid dmm::dmm_scan(double *values)\n{\n\tERRPARAMS errorParams; // structure for returning error code and error string\n\tstring logerror = \"\";\n\tDSCSAMPLE buf[16];\n\t\n\tif (!initialized) return;\n\n\tif (dscADScan(dscb, &dscadscan, buf) != DE_NONE)\n\t{\n\t\tdscGetLastError(&errorParams);\n\t\tlogerror = (format(\"dscADScan error: %s (%s)\") % dscGetErrorString(errorParams.ErrCode) % errorParams.errstring).str();\n\t\tlogger.log(logerror);\n\t}\n\n\tfor (unsigned int i = 0; i < 16; i++) {\n\t\tif (dscADCodeToVoltage(dscb, dscadsettings, buf[i], &values[i]) != DE_NONE) {\n\t\t\tdscGetLastError(&errorParams);\n\t\t\tlogerror = (format(\"dscADCodeToVoltage error on channel %d : %s (%s)\") % i % dscGetErrorString(errorParams.ErrCode) % errorParams.errstring).str();\n\t\t\tlogger.log(logerror);\n\t\t\tvalues[i] = nan(\"\");\n\t\t}\n\n\t}\n}\n\nvoid dmm::cycle_camera(void)\n{\n\n\tBYTE dscbresult;\t //variable for error handling\n\tstatic const BYTE port = 0;\n\tstatic const BYTE bit = 2;\n\n\tif (!initialized)\n\t{\n\t\tlogger.log(\"Not cycling camera because DMM board not initialized\\n\");\n\t\treturn;\n\t}\n\n\tlogger.log(format(\"Power cycling the camera...\"));\n\tif ((dscbresult = dscDIOClearBit(dscb, port, bit)) != DE_NONE)\n\t{\n\t\tlogger.log(format(\"failed to clear power cycle bit %d: %s \\n\") %bit % dscGetErrorString(dscbresult));\n\t\treturn;\n\t}\n\tSleep(200);\n\tif ((dscbresult = dscDIOSetBit(dscb, port, bit)) != DE_NONE)\n\t{\n\t\tlogger.log(format(\"failed to set power cycle bit %d: %s \\n\") % bit % dscGetErrorString(dscbresult));\n\t\treturn;\n\t}\n\tSleep(500);\n\tif ((dscbresult = dscDIOClearBit(dscb, port, bit)) != DE_NONE)\n\t{\n\t\tlogger.log(format(\"failed to clear power cycle bit %d: %s \\n\") % bit % dscGetErrorString(dscbresult));\n\t}\n}\n\nvoid dmm::heat_camera(bool enable)\n{\n\tBYTE dscbresult;\t //variable for error handling\n\tstatic const BYTE port = 0;\n\tstatic const BYTE bit = 1;\n\n\tif (!initialized) return;\n\n\tif (enable)\n\t{\n\t\tif ((dscbresult = dscDIOSetBit(dscb, port, bit)) != DE_NONE)\n\t\t{\n\t\t\tlogger.log(format(\"failed to set heater bit: %s\\n\") % dscGetErrorString(dscbresult));\n\t\t\treturn;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif ((dscbresult = dscDIOClearBit(dscb, port, bit)) != DE_NONE)\n\t\t{\n\t\t\tlogger.log(format(\"failed to clear heater bit: %s\\n\") % dscGetErrorString(dscbresult));\n\t\t\treturn;\n\t\t}\n\t}\n}" }, { "alpha_fraction": 0.5659509301185608, "alphanum_fraction": 0.60429447889328, "avg_line_length": 18.440298080444336, "blob_id": "7e7cce05b74a65ed7fce07a530720fe878954877", "content_id": "804ad0c6907a2eb2ae0f12d9bbfe0008996fdbf4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2609, "license_type": "no_license", "max_line_length": 86, "num_lines": 134, "path": "/stars/code/tools/timing.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"timing.h\"\n#include <boost/format.hpp>\n\nusing namespace Tools;\nusing std::string;\nusing boost::format;\n\n/*\nboost::system_time Tools::relative_time(double seconds)\n{\n return boost::get_system_time() + boost::posix_time::milliseconds(seconds*1000.0);\n}\n*/\n\n#ifdef _MSC_VER\nvoid usleep(int useconds)\n{\n Sleep(useconds/1000);\n}\n#endif\n\n\nTimer::Timer()\n{\n started_ = false;\n}\n\nbool Timer::started()\n{\n return started_;\n}\n\nvoid Timer::reset()\n{\n started_ = false;\n}\n\nTimer& Timer::operator=(const Timer &rhs)\n{\n if (this != &rhs) {\n started_ = rhs.started_;\n m_depart = rhs.m_depart;\n }\n return *this;\n}\n\ndouble Time::to_years(double time)\n{\n return time / (3600.0*24.0*365.0);\n}\n\ndouble Time::from_years(double time)\n{\n return time * (3600.0*24.0*365.0);\n}\n\ndouble Time::to_days(double time)\n{\n return time / (3600.0*24.0);\n}\n\ndouble Time::from_days(double time)\n{\n return time * (3600.0*24.0);\n}\n\ndouble Time::to_hours(double time)\n{\n return time / (3600.0);\n}\n\ndouble Time::from_hours(double time)\n{\n return time * (3600.0);\n}\n\ndouble Time::to_minutes(double time)\n{\n return time / (60.0);\n}\n\ndouble Time::from_minutes(double time)\n{\n return time * (60.0);\n}\n\ndouble Time::to_seconds(double time)\n{\n return time;\n}\n\ndouble Time::from_seconds(double time)\n{\n return time;\n}\n\ndouble Time::to_milliseconds(double time)\n{\n return time * (1000.0);\n}\n\ndouble Time::from_milliseconds(double time)\n{\n return time / (1000.0);\n}\n\nstring Time::time_string(double time)\n{\n string outstring = \"\";\n if (time == std::numeric_limits<double>::infinity()) {\n outstring = \"inf time\";\n } else if (time > from_years(999.0)) {\n outstring = (format(\"%.0e y\") % to_years(time)).str();\n } else if (time > from_years(1.0)) {\n outstring = (format(\"%.1f yr\") % to_years(time)).str();\n } else if (time > from_days(1.0)) {\n outstring = (format(\"%.1f dy\") % to_days(time)).str();\n } else if (time > from_hours(1.0)) {\n outstring = (format(\"%.1f hr\") % to_hours(time)).str();\n } else if (time > from_minutes(1.0)) {\n outstring = (format(\"%.1f mi\") % to_minutes(time)).str();\n } else if (time > from_seconds(1.0)) {\n outstring = (format(\"%.1f s\") % to_seconds(time)).str();\n } else {\n outstring = (format(\"%.1f ms\") % to_milliseconds(time)).str();\n }\n return outstring;\n}\n\n\n\n" }, { "alpha_fraction": 0.6786678433418274, "alphanum_fraction": 0.6858685612678528, "avg_line_length": 24.813953399658203, "blob_id": "3abd6ae77fb43db9a6a1b5fcd5d6f1e065a54b99", "content_id": "968cc16a9719672567ca64e105d972cec590361b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1112, "license_type": "no_license", "max_line_length": 121, "num_lines": 43, "path": "/stars/code/displaying/textures.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"textures.h\"\n#include <boost/filesystem/operations.hpp>\n#include \"../parameters/manager.h\"\n\nusing namespace Displaying;\n\nTextures::Textures(Parameters::Manager& params)\n{\n display_enabled = params.general.try_get(\"main.display_enabled\", true);\n stars_dir = params.stars_dir;\n}\n\nTextures::~Textures()\n{\n if (display_enabled) {\n font.Destroy();\n }\n for (int i=0; i<num_textures; i++) {\n textures[i].destroy(display_enabled);\n }\n}\n\nvoid Textures::init()\n{\n using namespace boost::filesystem;\n\ttextures[basic_drawing].init(display_enabled);\n textures[font_texture].init(display_enabled);\n //textures[drawing_3d].init(display_enabled);\n if (display_enabled) {\n font.Create(system_complete(stars_dir + \"resources/fonts/arial24_with_degrees.glf\").string(), get(font_texture));\n }\n}\n\nGLuint Textures::get(texture_name name)\n{\n return textures[name].id;\n}\n\n" }, { "alpha_fraction": 0.5984691381454468, "alphanum_fraction": 0.614149808883667, "avg_line_length": 34.73532485961914, "blob_id": "0b11570aa94d6d3179be50183043452b706328b1", "content_id": "f59144bff0d573438901d5f72b4a2032e2e367eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 32269, "license_type": "no_license", "max_line_length": 121, "num_lines": 903, "path": "/common/channels_tng.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * channels_v2.c: \n *\n * This software is copyright \n * (C) 2013-2014 California State University, Sacramento\n *\n * This file is part of mcp, created for the BLASTPol Project.\n *\n * mcp 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Aug 5, 2014 by seth\n */\n\n/**\n * Code Overview:\n *\n * This file provides the interface to the Channels structure for BLAST-TNG.\n *\n * Channels lives in tx_struct_tng.c and list all known channels for the experiment.\n * On startup, the channels structure is read and separated into a number of distinct\n * frames based on rate. Thus there is a 1Hz frame, a 5Hz frame, a 100Hz frame,\n * etc. The frames are packed structures, ordered first by their source.\n *\n * Each frame also has a small header that records the timestamp and computer id.\n *\n * On MCP, there are frame structures for each computer (UEI1, UEI2, FC1, FC2, SC1, SC2).\n * The data are populated by listening to the MQTT server.\n *\n *\n */\n#include <stdint.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <glib.h>\n#include <math.h>\n#include <ctype.h>\n\n#include \"blast.h\"\n#include \"PMurHash.h\"\n#include \"channels_tng.h\"\n#include \"derived.h\"\n#include \"linklist.h\"\n\nchar * ROACH_TYPES[NUM_RTYPES] = {\"i\", \"q\", \"df\"};\nstatic GHashTable *frame_table = NULL;\nstatic int channel_count[RATE_END][TYPE_END] = {{0}};\nint channels_count = 0;\n\nvoid *channel_data[RATE_END] = {0};\nsize_t frame_size[RATE_END] = {0};\nstatic void *channel_ptr[RATE_END] = {0};\n\n// conversion from channel type to superframe type\nuint8_t superframe_type_array[TYPE_END+1] = {\n SF_UINT8, SF_UINT16, SF_UINT32, SF_UINT64,\n SF_INT8, SF_INT16, SF_INT32, SF_INT64,\n SF_FLOAT32, SF_FLOAT64, SF_NUM\n};\nunsigned int superframe_offset[RATE_END] = {0};\nsuperframe_t * superframe = NULL;\n\nsize_t channel_size(channel_t *m_channel)\n{\n size_t retsize = 0;\n switch (m_channel->type) {\n case TYPE_INT8:\n case TYPE_UINT8:\n retsize = 1;\n break;\n case TYPE_INT16:\n case TYPE_UINT16:\n retsize = 2;\n break;\n case TYPE_INT32:\n case TYPE_UINT32:\n case TYPE_FLOAT:\n retsize = 4;\n break;\n case TYPE_INT64:\n case TYPE_UINT64:\n case TYPE_DOUBLE:\n retsize = 8;\n break;\n default:\n blast_fatal(\"Invalid Channel size!\");\n }\n return retsize;\n}\nunsigned int get_spf(unsigned int rate)\n{\n switch (rate) {\n case RATE_1HZ:\n return 1;\n case RATE_5HZ:\n return 5;\n case RATE_100HZ:\n return 100;\n case RATE_200HZ:\n return 200;\n case RATE_244HZ:\n return 244;\n case RATE_488HZ:\n return 488;\n default:\n blast_err(\"Invalid rate %d\", rate);\n return 0;\n }\n}\n\nstatic guint channel_hash(gconstpointer m_data)\n{\n const char *field_name = (const char*)m_data;\n\n return PMurHash32(BLAST_MAGIC32, field_name, strnlen(field_name, FIELD_LEN));\n}\n\nstatic void channel_map_fields(gpointer m_key, gpointer m_channel, gpointer m_userdata)\n{\n channel_t *channel = (channel_t*)m_channel;\n\n /// If channel is invalid, do not process\n if (!channel->field[0]) return;\n\n /**\n * channel_ptr maintains the current location in the array of the next free element.\n * We assign this location to the channel pointer, allowing us to reference the\n * individual location in the future based on a lookup in the hash table.\n */\n if (channel->rate < RATE_END) {\n if (!channel_ptr[channel->rate]) {\n blast_fatal(\"Invalid Channel setup\");\n }\n channel->var = channel_ptr[channel->rate];\n channel_ptr[channel->rate] += channel_size(channel);\n } else {\n blast_fatal(\"Could not map %d to rate!\", channel->rate);\n }\n}\n\n/**\n * Takes an aligned channel list and re-packs it into a packed structure for sharing over\n * MQTT.\n * @param m_channel_list Pointer to the aligned channel list\n * @return Newly allocated channel_header_t structure or NULL on failure\n */\nchannel_header_t *channels_create_map(channel_t *m_channel_list)\n{\n channel_header_t *new_pkt = NULL;\n size_t channel_count;\n\n for (channel_count = 0; m_channel_list[channel_count].field[0]; channel_count++)\n continue;\n channel_count++; // Add one extra channel to allow for the NULL terminating field\n\n new_pkt = balloc(err, sizeof(channel_header_t) + sizeof(struct channel_packed) * channel_count);\n if (!new_pkt) return NULL;\n memset(new_pkt, 0, sizeof(channel_header_t) + sizeof(struct channel_packed) * channel_count);\n\n new_pkt->magic = BLAST_MAGIC32;\n new_pkt->version = BLAST_TNG_CH_VERSION;\n new_pkt->length = channel_count;\n new_pkt->crc = 0;\n\n /**\n * Copy over the data values one at a time from the aligned to the packed structure\n */\n for (size_t i = 0; i < channel_count; i++) {\n memcpy(new_pkt->data[i].field, m_channel_list[i].field, FIELD_LEN);\n new_pkt->data[i].m_c2e = m_channel_list[i].m_c2e;\n new_pkt->data[i].b_e2e = m_channel_list[i].b_e2e;\n new_pkt->data[i].type = m_channel_list[i].type;\n new_pkt->data[i].rate = m_channel_list[i].rate;\n memcpy(new_pkt->data[i].quantity, m_channel_list[i].quantity, UNITS_LEN);\n memcpy(new_pkt->data[i].units, m_channel_list[i].units, UNITS_LEN);\n }\n\n new_pkt->crc = PMurHash32(BLAST_MAGIC32, new_pkt, sizeof(channel_header_t) +\n sizeof(struct channel_packed) * channel_count);\n\n return new_pkt;\n}\n\n/**\n * Takes an aligned channel list for a single down sample rate and re-packs it into a\n * packed structure for sharing over MQTT or writing as a head in the data files stored\n * on the external HDs.\n * @param m_channel_list Pointer to the aligned channel list\n * @param m_rate Pointer to the aligned channel list\n * @return Newly allocated channel_header_t structure or NULL on failure\n */\nchannel_header_t *channels_create_rate_map(channel_t *m_channel_list, E_RATE m_rate)\n{\n channel_header_t *new_pkt = NULL;\n size_t channels_count, total_channels_count;\n uint32_t i_channels, i_rate = 0;\n\n\tfor (total_channels_count = 0; m_channel_list[total_channels_count].field[0]; total_channels_count++)\n continue;\n total_channels_count++; // Add one extra channel to allow for the NULL terminating field\n\n\tchannels_count = (channel_count[m_rate][TYPE_INT8]+channel_count[m_rate][TYPE_UINT8]) +\n 2 * (channel_count[m_rate][TYPE_INT16]+channel_count[m_rate][TYPE_UINT16]) +\n 4 * (channel_count[m_rate][TYPE_INT32]+channel_count[m_rate][TYPE_UINT32] +\n channel_count[m_rate][TYPE_FLOAT]) +\n 8 * (channel_count[m_rate][TYPE_INT64]+channel_count[m_rate][TYPE_UINT64] +\n channel_count[m_rate][TYPE_DOUBLE]);\n new_pkt = balloc(err, sizeof(channel_header_t) + sizeof(struct channel_packed) * channels_count);\n if (!new_pkt) return NULL;\n memset(new_pkt, 0, sizeof(channel_header_t) + sizeof(struct channel_packed) * channels_count);\n\n new_pkt->magic = BLAST_MAGIC32;\n new_pkt->version = BLAST_TNG_CH_VERSION;\n new_pkt->length = channels_count;\n new_pkt->crc = 0;\n\n /**\n * Copy over the data values one at a time from the aligned to the packed structure\n */\n for (i_channels = 0; i_channels < total_channels_count; i_channels++) {\n \tif (m_channel_list[i_channels].rate == m_rate) {\n\t \tif (i_rate >= channels_count) {\n \t\t\tblast_err(\"More channels found with rate index %i (>=%i) than allocated (%i)\",\n \t\t\t\t\t (uint16_t) m_rate, (uint32_t) i_rate, (uint32_t) total_channels_count);\n \t\t\treturn(new_pkt);\n \t\t}\n \t memcpy(new_pkt->data[i_rate].field, m_channel_list[i_channels].field, FIELD_LEN);\n new_pkt->data[i_rate].m_c2e = m_channel_list[i_channels].m_c2e;\n new_pkt->data[i_rate].b_e2e = m_channel_list[i_channels].b_e2e;\n new_pkt->data[i_rate].type = m_channel_list[i_channels].type;\n new_pkt->data[i_rate].rate = m_channel_list[i_channels].rate;\n memcpy(new_pkt->data[i_rate].quantity, m_channel_list[i_channels].quantity, UNITS_LEN);\n memcpy(new_pkt->data[i_rate].units, m_channel_list[i_channels].units, UNITS_LEN);\n i_rate++;\n \t}\n\t}\n new_pkt->crc = PMurHash32(BLAST_MAGIC32, new_pkt, sizeof(channel_header_t) +\n sizeof(struct channel_packed) * channels_count);\n\n return new_pkt;\n}\n\n/**\n * Takes an aligned channel list and re-packs it into a packed structure for sharing over\n * MQTT.\n * @param m_channel_list Pointer to the aligned channel list\n * @return Newly allocated channel_header_t structure or NULL on failure\n */\nderived_header_t *channels_create_derived_map(derived_tng_t *m_derived)\n{\n derived_header_t *new_pkt = NULL;\n size_t channel_count;\n\n for (channel_count = 0; m_derived[channel_count].type != DERIVED_EOC_MARKER; channel_count++)\n continue;\n channel_count++; // Add one extra channel to allow for the NULL terminating field\n\n new_pkt = balloc(err, sizeof(derived_header_t) + sizeof(derived_tng_t) * channel_count);\n if (!new_pkt) return NULL;\n memset(new_pkt, 0, sizeof(derived_header_t) + sizeof(derived_tng_t) * channel_count);\n\n new_pkt->magic = BLAST_MAGIC32;\n new_pkt->version = BLAST_TNG_CH_VERSION | 0x20; // 0x20 marks the packet as a derived packet\n new_pkt->length = channel_count;\n new_pkt->crc = 0;\n\n /**\n * Copy over the data values. Union structure is already packed.\n */\n memcpy(new_pkt->data, m_derived, channel_count * sizeof(derived_tng_t));\n\n\n new_pkt->crc = PMurHash32(BLAST_MAGIC32, new_pkt, sizeof(derived_header_t) + sizeof(derived_tng_t) * channel_count);\n\n return new_pkt;\n}\n\n/**\n * Translates a stored channel map to the channel_list structure\n * @param m_map Pointer to the #channel_header_t structure storing our packet\n * @param m_len Length in bytes of the packet passed via m_map\n * @param m_channel_list Double pointer to where we will store the channel_list\n * @return -1 on failure, positive number of channels read otherwise\n */\nint channels_read_map(channel_header_t *m_map, size_t m_len, channel_t **m_channel_list)\n{\n uint32_t crcval = m_map->crc;\n\n if (m_map->version != BLAST_TNG_CH_VERSION) {\n blast_err(\"Unknown derived channels version %d\", m_map->version);\n return -1;\n }\n\n if (m_len < sizeof(channel_header_t)) {\n blast_err(\"Invalid size %zu for channel packet\", m_len);\n return -1;\n }\n\n if (m_len != sizeof(channel_header_t) + m_map->length * sizeof(struct channel_packed)) {\n blast_err(\" m-Map has length %u\", m_map->length);\n blast_err(\"struct channelpacked has size %zu\", sizeof(struct channel_packed));\n blast_err(\"channel header has size %zu\", sizeof(channel_header_t));\n blast_err(\"Length of data packet %zu does not match header data %zu\",\n m_len, sizeof(channel_header_t) + m_map->length * sizeof(struct channel_packed));\n return -1;\n }\n\n m_map->crc = 0;\n if (crcval != PMurHash32(BLAST_MAGIC32, m_map, m_len)) {\n blast_err(\"CRC match failed!\");\n return -1;\n }\n m_map->crc = crcval;\n\n *m_channel_list = calloc(m_map->length, sizeof(channel_t));\n if (!(*m_channel_list)) return -1;\n\n /**\n * Copy over the data values one at a time from the packed to the aligned structure\n */\n for (size_t channel_count = 0; channel_count < m_map->length; channel_count++) {\n memcpy((*m_channel_list)[channel_count].field, m_map->data[channel_count].field, FIELD_LEN);\n (*m_channel_list)[channel_count].m_c2e = m_map->data[channel_count].m_c2e;\n (*m_channel_list)[channel_count].b_e2e = m_map->data[channel_count].b_e2e;\n (*m_channel_list)[channel_count].type = m_map->data[channel_count].type;\n (*m_channel_list)[channel_count].rate = m_map->data[channel_count].rate;\n memcpy((*m_channel_list)[channel_count].quantity, m_map->data[channel_count].quantity, UNITS_LEN);\n memcpy((*m_channel_list)[channel_count].units, m_map->data[channel_count].units, UNITS_LEN);\n (*m_channel_list)[channel_count].var = NULL;\n }\n\n return m_map->length;\n}\n\n/**\n * Translates a stored derived packet to the derived structure\n * @param m_map Pointer to the #derived_header_t structure storing our packet\n * @param m_len Length in bytes of the packet passed via m_map\n * @param m_channel_list Double pointer to where we will store the channel_list\n * @return -1 on failure, positive number of channels read otherwise\n */\nint channels_read_derived_map(derived_header_t *m_map, size_t m_len, derived_tng_t **m_channel_list)\n{\n uint32_t crcval = m_map->crc;\n\n if (m_map->version != (BLAST_TNG_CH_VERSION | 0x20)) { // 0x20 marks the packet as a derived packet\n blast_err(\"Unknown channels version %d\", m_map->version);\n return -1;\n }\n\n if (m_len < sizeof(derived_header_t)) {\n blast_err(\"Invalid size %zu for derived packet\", m_len);\n return -1;\n }\n\n if (m_len != sizeof(derived_header_t) + m_map->length * sizeof(derived_tng_t)) {\n blast_err(\"Length of data packet %zu does not match header data %zu\",\n m_len, sizeof(derived_header_t) + m_map->length * sizeof(derived_tng_t));\n return -1;\n }\n\n m_map->crc = 0;\n if (crcval != PMurHash32(BLAST_MAGIC32, m_map, m_len)) {\n blast_err(\"CRC match failed!\");\n return -1;\n }\n m_map->crc = crcval;\n\n *m_channel_list = balloc(err, sizeof(derived_tng_t) * m_map->length);\n if (!(*m_channel_list)) return -1;\n\n\n memcpy(*m_channel_list, m_map->data, sizeof(derived_tng_t) * m_map->length);\n\n return m_map->length;\n}\n\nchannel_t *channels_find_by_name(const char *m_name)\n{\n channel_t *retval = (channel_t*)g_hash_table_lookup(frame_table, m_name);\n\n if (!retval) blast_err(\"Could not find %s!\\n\", m_name);\n return retval;\n}\n\nint channels_check_size_of_frame(E_RATE m_rate, size_t m_len)\n{\n\tif (m_len != frame_size[m_rate]) {\n\t\tblast_err(\"Size mismatch storing data for %s! Got %zu bytes, expected %zu\",\n\t\t RATE_LOOKUP_TABLE[m_rate].text, m_len, frame_size[m_rate]);\n\t\treturn -1;\n\t}\n return 0;\n}\n\nint channels_store_data(E_RATE m_rate, const void *m_data, size_t m_len)\n{\n\tif (m_len != frame_size[m_rate]) {\n\t\tblast_err(\"Size mismatch storing data for %s! Got %zu bytes, expected %zu\",\n\t\t RATE_LOOKUP_TABLE[m_rate].text, m_len, frame_size[m_rate]);\n\t\treturn -1;\n\t}\n\n\tmemcpy(channel_data[m_rate], m_data, m_len);\n\treturn 0;\n}\n\n/**\n * Initialize the channels structure and associated hash tables.\n * @return 0 on success. -1 otherwise\n */\nint channels_initialize(const channel_t * const m_channel_list)\n{\n const channel_t *channel;\n\n if (frame_table) g_hash_table_destroy(frame_table);\n frame_table = g_hash_table_new(channel_hash, g_str_equal);\n\n if (frame_table == NULL) return -1;\n\n for (int j = 0; j < RATE_END; j++) {\n for (int k = 0; k < TYPE_END; k++) {\n channel_count[j][k] = 0;\n }\n if (channel_data[j]) {\n free(channel_data[j]);\n channel_data[j] = NULL;\n }\n }\n\n /**\n * First Pass: Add each entry in the channels array to a hash table for later lookup.\n * Then count each type of channel, separating by source, variable type and rate\n */\n channels_count = 0;\n for (channel = m_channel_list; channel->field[0]; channel++) {\n g_hash_table_insert(frame_table, (gpointer)channel->field, (gpointer)channel);\n if (channel->rate < RATE_END && channel->type < TYPE_END) {\n channel_count[channel->rate][channel->type]++;\n } else {\n blast_fatal(\"Could not map %d and %d to rate and type!, %s\", channel->rate, channel->type, channel->field);\n return 1;\n }\n channels_count++;\n }\n\n /**\n * Second Pass: Allocate a set of packed arrays representing the data frames for each source/rate.\n * We also set channel_ptr, our placeholder for the next free element in the array, to the first entry in each frame.\n */\n\n for (int rate = 0; rate < RATE_END; rate++) {\n frame_size[rate] = (channel_count[rate][TYPE_INT8]+channel_count[rate][TYPE_UINT8]) +\n 2 * (channel_count[rate][TYPE_INT16]+channel_count[rate][TYPE_UINT16]) +\n 4 * (channel_count[rate][TYPE_INT32]+channel_count[rate][TYPE_UINT32] +\n channel_count[rate][TYPE_FLOAT]) +\n 8 * (channel_count[rate][TYPE_INT64]+channel_count[rate][TYPE_UINT64] +\n channel_count[rate][TYPE_DOUBLE]);\n\n if (frame_size[rate]) {\n /**\n * Ensure that we can dereference the data without knowing its type by\n * taking at least 8 bytes\n */\n size_t allocated_size = MAX(frame_size[rate], sizeof(uint64_t));\n channel_data[rate] = calloc(1, allocated_size);\n blast_info(\"Allocating %zu bytes for %u channels at %s\", frame_size[rate],\n (channel_count[rate][TYPE_INT8]+channel_count[rate][TYPE_UINT8]) +\n (channel_count[rate][TYPE_INT16]+channel_count[rate][TYPE_UINT16]) +\n (channel_count[rate][TYPE_INT32]+channel_count[rate][TYPE_UINT32] +\n channel_count[rate][TYPE_FLOAT]) +\n (channel_count[rate][TYPE_INT64]+channel_count[rate][TYPE_UINT64] +\n channel_count[rate][TYPE_DOUBLE]),\n RATE_LOOKUP_TABLE[rate].text);\n } else {\n channel_data[rate] = NULL;\n }\n channel_ptr[rate] = channel_data[rate];\n }\n\n /**\n * Third Pass: Iterate over the hash table and assign the lookup pointers to their place in the frame.\n */\n g_hash_table_foreach(frame_table, channel_map_fields, NULL);\n\n // generate superframe\n superframe = channels_generate_superframe(m_channel_list);\n\n blast_startup(\"Successfully initialized Channels data structures\");\n return 0;\n}\n\nint get_roach_index(unsigned int roach, unsigned int kid, unsigned int rtype) {\n if (roach > NUM_ROACHES) {\n blast_err(\"Invalid roach %d\", roach);\n return -1;\n }\n if (kid >= NUM_KIDS) {\n blast_err(\"Invalid kid %d\", kid);\n return -1;\n }\n if (rtype >= NUM_RTYPES) {\n blast_err(\"Invalid rtype %d\", rtype);\n return -1;\n }\n\n return kid+(roach-1)*NUM_KIDS+rtype*NUM_ROACHES*NUM_KIDS;\n}\n\nvoid read_roach_index(unsigned int *roach, unsigned int *kid, unsigned int *rtype, unsigned int roach_index) {\n if (rtype) *rtype = roach_index/(NUM_ROACHES*NUM_KIDS);\n roach_index %= NUM_ROACHES*NUM_KIDS;\n\n if (roach) *roach = roach_index/(NUM_KIDS)+1;\n roach_index %= NUM_KIDS;\n\n if (kid) *kid = roach_index;\n\n if (*roach > NUM_ROACHES) {\n blast_err(\"Invalid roach %d\", *roach);\n *roach = 1;\n }\n if (*kid >= NUM_KIDS) {\n blast_err(\"Invalid kid %d\", *kid);\n *kid = 0;\n }\n if (*rtype >= NUM_RTYPES) {\n blast_err(\"Invalid rtype %d\", *rtype);\n *rtype = 0;\n }\n}\n\n#define MAX_ROACH_NAME 64\n\nvoid make_name_from_roach_index(unsigned int roach_index, char * name) {\n unsigned int roach = 0, kid = 0, rtype = 0;\n read_roach_index(&roach, &kid, &rtype, roach_index);\n\n if (roach > NUM_ROACHES) {\n blast_err(\"Invalid roach %d\", roach);\n return;\n }\n if (kid >= NUM_KIDS) {\n blast_err(\"Invalid kid %d\", kid);\n return;\n }\n if (rtype >= NUM_RTYPES) {\n blast_err(\"Invalid rtype %d\", rtype);\n return;\n }\n\n snprintf(name, MAX_ROACH_NAME, \"%s_kid%.04d_roach%.01d\", ROACH_TYPES[rtype], kid, roach);\n}\n\nlinklist_t * generate_housekeeping_linklist(linklist_t * ll_hk, char * name) {\n int i;\n int count = 0;\n unsigned int blk_size = 0;\n\n for (i = 0; i < ll_hk->n_entries; i++) {\n if (ll_hk->items[i].tlm) {\n if ((strncmp(ll_hk->items[i].tlm->field+2, \"kid\", 3) == 0) &&\n (strncmp(ll_hk->items[i].tlm->field+10, \"roach\", 5) == 0)) {\n // linklist_info(\"Starting to ignore fields after %s\\n\", ll_hk->items[i].tlm->field);\n break;\n }\n }\n blk_size += ll_hk->items[i].blk_size;\n count++;\n }\n\n // modify the linklist name\n strncpy(ll_hk->name, name, 63);\n\n // modify the linklist size\n ll_hk->n_entries = count;\n\n // modify the linklist bulk size\n ll_hk->blk_size = blk_size;\n\n // modify the serial\n /*\n for (i = 0; i < MD5_DIGEST_LENGTH; i++) {\n if (!name[i]) break;\n ll_hk->serial[i] ^= name[i];\n }\n */\n\n return ll_hk;\n}\n\n#define EXTRA_SF_ENTRIES 2\n\nsuperframe_t * channels_generate_superframe(const channel_t * const m_channel_list) {\n superframe_entry_t * sf = calloc(channels_count+EXTRA_SF_ENTRIES+1, sizeof(superframe_entry_t));\n\n unsigned int sf_size = 0;\n\n int rate = 0;\n for (rate = 0; rate < RATE_END; rate++) {\n superframe_offset[rate] = sf_size;\n sf_size += frame_size[rate]*get_spf(rate);\n }\n\n int i = 0;\n const channel_t *channel;\n for (channel = m_channel_list; channel->field[0]; channel++) {\n strncpy(sf[i].field, channel->field, FIELD_LEN-1);\n sf[i].type = superframe_type_array[channel->type];\n sf[i].spf = get_spf(channel->rate);\n sf[i].start = (int64_t) (channel->var-channel_data[channel->rate])+superframe_offset[channel->rate];\n sf[i].skip = frame_size[channel->rate];\n if (strlen(channel->quantity)) strncpy(sf[i].quantity, channel->quantity, UNITS_LEN-1);\n if (strlen(channel->units)) strncpy(sf[i].units, channel->units, UNITS_LEN-1);\n sf[i].var = channel->var;\n\n i++;\n }\n\n // null terminate\n sf[i].field[0] = '\\0';\n\n return linklist_build_superframe(sf, &channel_data_to_double, &channel_double_to_data, SF_USE_BIG_ENDIAN);\n}\n\n/**\n * add_frame_to_superframe\n * \n * Takes a BLAST frame at a given rate and copies it to the superframe.\n * -> frame: BLAST frame to be copied to the superframe\n * -> rate: the rate type for the BLAST frame\n */\nunsigned int add_frame_to_superframe(void * frame, E_RATE rate, void * superframe, unsigned int * frame_location)\n{\n if (!superframe) {\n blast_err(\"Superframe is not allocated. Fix!\");\n return 0;\n }\n if (!frame) {\n blast_err(\"Frame pointer is NULL. Fix!\");\n return 0;\n }\n\n // clear the frame if wrapping has occurred (ensures no split data)\n if (*frame_location == 0) {\n memset(superframe+superframe_offset[rate], 0, frame_size[rate]*get_spf(rate));\n }\n\n // copy the frame to the superframe\n memcpy(superframe+superframe_offset[rate]+frame_size[rate]*(*frame_location), frame, frame_size[rate]);\n\n // update the frame location\n *frame_location = ((*frame_location)+1)%get_spf(rate);\n\n // return the next frame location in the superframe\n return *frame_location;\n}\n\n/**\n * extract_frame_from_superframe\n * \n * Extracts a BLAST frame at a given rate from superframe and copies it to a given buffer.\n * -> frame: BLAST frame to be copied from the superframe\n * -> rate: the rate type for the BLAST frame\n */\nunsigned int extract_frame_from_superframe(void * frame, E_RATE rate, void * superframe, unsigned int * frame_location)\n{\n if (!superframe) {\n blast_err(\"Superframe is not allocated. Fix!\");\n return 0;\n }\n if (!frame) {\n blast_err(\"Frame pointer is NULL. Fix!\");\n return 0;\n }\n\n // copy the frame from the superframe\n memcpy(frame, superframe+superframe_offset[rate]+frame_size[rate]*(*frame_location), frame_size[rate]);\n\n // update the frame location\n *frame_location = ((*frame_location)+1)%get_spf(rate);\n\n // return the next frame location in the superframe\n return *frame_location;\n}\n\ndouble channel_data_to_double(uint8_t * data, uint8_t type)\n{\n switch (type) {\n case SF_FLOAT64 : return bedtoh(*((double *) data));\n case SF_FLOAT32 : return beftoh(*((float *) data));\n case SF_INT16 : return (int16_t) be16toh(*((int16_t *) data));\n case SF_UINT16 : return be16toh(*((uint16_t *) data));\n case SF_INT32 : return (int32_t) be32toh(*((int32_t *) data));\n case SF_UINT32 : return be32toh(*((uint32_t *) data));\n case SF_INT8 : return *((int8_t *) data);\n case SF_UINT8 : return *((uint8_t *) data);\n default : return 0;\n }\n return 0;\n}\nint channel_double_to_data(uint8_t * data, double dub, uint8_t type)\n{\n if (type == SF_FLOAT64) {\n htobed(dub, *(uint64_t*) data);\n return 8;\n } else if (type == SF_FLOAT32) {\n htobef(dub, *(uint32_t*) data)\n return 4;\n } else if (type == SF_INT16) {\n int16_t s = dub;\n *(int16_t*) data = htobe16(s);\n return 2;\n } else if (type == SF_UINT16) {\n uint16_t u = dub;\n *(uint16_t*) data = htobe16(u);\n return 2;\n } else if (type == SF_INT32) {\n int32_t i = dub;\n *(int32_t*) data = htobe32(i);\n return 4;\n } else if (type == SF_UINT32) {\n uint32_t i = dub;\n *(uint32_t*) data = htobe32(i);\n return 4;\n } else if (type == SF_INT8) {\n *(int8_t*) data = dub;\n return 1;\n } else if (type == SF_UINT8) {\n *(uint8_t*) data = dub;\n return 1;\n }\n return 0;\n}\n\nvoid channels_write_calspecs_item(FILE *calspecsfile, derived_tng_t *derived) {\n int j;\n\n switch (derived->type) {\n case 'w':\n case 'b':\n fprintf(calspecsfile, \"%s BIT %s %u %u\\n\", derived->bitword.field, derived->bitword.source,\n derived->bitword.offset, derived->bitword.length);\n break;\n case 't':\n fprintf(calspecsfile, \"%s LINTERP %s %s\\n\", derived->linterp.field, derived->linterp.source,\n derived->linterp.lut);\n break;\n case 'c':\n fprintf(calspecsfile, \"%s LINCOM 1 %s %.16f %.16f\\n\", derived->lincom.field,\n derived->lincom.source, derived->lincom.m_c2e, derived->lincom.b_e2e);\n break;\n case '2':\n fprintf(calspecsfile, \"%s LINCOM 2 %s %.16f %.16f %s %.16f %.16f\\n\", derived->lincom2.field,\n derived->lincom2.source, derived->lincom2.m_c2e, derived->lincom2.b_e2e,\n derived->lincom2.source2, derived->lincom2.m2_c2e, derived->lincom2.b2_e2e);\n break;\n case '#':\n break;\n case 'u':\n if (derived->units.quantity[0]) {\n fprintf(calspecsfile, \"%s/quantity STRING \\\"\", derived->units.source);\n for (j = 0; j < strlen(derived->units.quantity); j++) {\n if (derived->units.quantity[j] == 92) fprintf(calspecsfile, \"\\\\\"); // fix getdata escape\n fprintf(calspecsfile, \"%c\", derived->units.quantity[j]);\n }\n fprintf(calspecsfile, \"\\\"\\n\");\n }\n if (derived->units.units[0]) {\n fprintf(calspecsfile, \"%s/units STRING \\\"\", derived->units.source);\n for (j = 0; j < strlen(derived->units.units); j++) {\n if (derived->units.units[j] == 92) fprintf(calspecsfile, \"\\\\\"); // fix getdata escape\n fprintf(calspecsfile, \"%c\", derived->units.units[j]);\n }\n fprintf(calspecsfile, \"\\\"\\n\");\n }\n break;\n case 'p':\n fprintf(calspecsfile, \"%s PHASE %s %d\\n\", derived->phase.field, derived->phase.source, derived->phase.shift);\n break;\n case 'r':\n fprintf(calspecsfile, \"%s RECIP %s %.16f\\n\", derived->recip.field, derived->recip.source,\n derived->recip.dividend);\n break;\n case '*':\n fprintf(calspecsfile, \"%s MULTIPLY %s %s\\n\", derived->math.field, derived->math.source, derived->math.source2);\n break;\n case '/':\n fprintf(calspecsfile, \"%s DIVIDE %s %s\\n\", derived->math.field, derived->math.source, derived->math.source2);\n break;\n case 'x':\n fprintf(calspecsfile, \"%s MPLEX %s %s %d %d\\n\", derived->mplex.field, derived->mplex.source,\n derived->mplex.index, derived->mplex.value, derived->mplex.max);\n break;\n default:\n blast_warn(\"Unknown type %c\", derived->type);\n break;\n }\n}\n\nvoid channels_write_calspecs(char * fname, derived_tng_t *m_derived)\n{\n FILE * calspecsfile = fopen(fname, \"w\");\n if (!calspecsfile) {\n blast_err(\"Could not open \\\"%s\\\" as calspecs file\\n\", fname);\n return;\n }\n\n for (derived_tng_t *derived = m_derived; derived && derived->type != DERIVED_EOC_MARKER; derived++) {\n channels_write_calspecs_item(calspecsfile, derived);\n }\n\n derived_tng_t derived = {0};\n char tmp_str[128] = {0};\n for (channel_t *channel = channel_list; channel->field[0]; channel++) {\n snprintf(tmp_str, sizeof(tmp_str), \"%s\", channel->field);\n double m = channel->m_c2e;\n double b = channel->b_e2e;\n\n // don't do roach channels; we have something special for that (see below)\n if ((strstr(tmp_str, \"roach\") != NULL) && (strstr(tmp_str, \"kid\") != NULL)) {\n continue;\n }\n\n /// By default we set the converted field to upper case\n for (int i = 0; tmp_str[i]; i++) tmp_str[i] = toupper(tmp_str[i]);\n /// If our scale/offset are unity/zero respectively, tell defile to use the easier zero-phase\n if (fabs(m - 1.0) <= DBL_EPSILON && fabs(b - 0.0) <= DBL_EPSILON) {\n derived.type = 'p';\n snprintf(derived.phase.field, sizeof(tmp_str), \"%s\", tmp_str);\n snprintf(derived.phase.source, sizeof(tmp_str), \"%s\", channel->field);\n derived.phase.shift = 0;\n } else {\n derived.type = 'c';\n snprintf(derived.lincom.field, sizeof(tmp_str), \"%s\", tmp_str);\n snprintf(derived.lincom.source, sizeof(tmp_str), \"%s\", channel->field);\n derived.lincom.m_c2e = m;\n derived.lincom.b_e2e = b;\n }\n channels_write_calspecs_item(calspecsfile, &derived);\n }\n\n // something special: generate an array of derived fields for each roach channel\n // multiplex roach index fields will point to the corresponding name for display in kst\n fprintf(calspecsfile, ROACH_NAME_SARRAY \" SARRAY\");\n\n int kid = 0, roach = 1, rtype = 0;\n for (rtype = 0; rtype < NUM_RTYPES; rtype++) {\n for (roach = 1; roach <= NUM_ROACHES; roach++) {\n for (kid = 0; kid < NUM_KIDS; kid++) {\n char tlm_name[64] = {0};\n unsigned int index = get_roach_index(roach, kid, rtype);\n make_name_from_roach_index(index, tlm_name);\n for (int i = 0; tlm_name[i]; i++) tlm_name[i] = toupper(tlm_name[i]);\n fprintf(calspecsfile, \" '%s'\", tlm_name);\n }\n }\n }\n fprintf(calspecsfile, \"\\n\");\n for (int i = 0; i < NUM_ROACH_TLM; i++) {\n char c = 65+i;\n fprintf(calspecsfile, \"KID%c_ROACHN_NAME SINDIR kid%c_roachN_index \" ROACH_NAME_SARRAY \"\\n\", c, c);\n }\n // link multiplexed fields to derived fields\n for (rtype = 0; rtype < NUM_RTYPES; rtype++) {\n for (roach = 1; roach <= NUM_ROACHES; roach++) {\n for (kid = 0; kid < NUM_KIDS; kid++) {\n int index = get_roach_index(roach, kid, rtype);\n derived.type = 'x';\n make_name_from_roach_index(index, derived.mplex.field);\n for (int i = 0; derived.mplex.field[i]; i++) {\n derived.mplex.field[i] = toupper(derived.mplex.field[i]);\n }\n char c = 65+((roach-1)*3)+rtype;\n snprintf(derived.mplex.source, sizeof(derived.mplex.source), \"kid%c_roachN\", c);\n snprintf(derived.mplex.index, sizeof(derived.mplex.index), \"kid%c_roachN_index\", c);\n derived.mplex.value = index;\n derived.mplex.max = 0;\n\n channels_write_calspecs_item(calspecsfile, &derived);\n }\n }\n }\n\n\n\n\n fflush(calspecsfile);\n fclose(calspecsfile);\n}\n" }, { "alpha_fraction": 0.6639260053634644, "alphanum_fraction": 0.6767728924751282, "avg_line_length": 26.02777862548828, "blob_id": "f043ebe0fcc57d3b6dfa8ab8e71636d62d1104b1", "content_id": "035b1715d3dd83505bb0c0e495028d6adf313bdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1946, "license_type": "no_license", "max_line_length": 106, "num_lines": 72, "path": "/common/include/sip.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* mcp: the BLAST master control program\n *\n * sip.h list of functions for listening to and processing sip data (in sip.c)\n *\n * This software is copyright (C) 2002-2012 University of Toronto\n *\n * This file is part of mcp and pcm\n *\n * mcp and pcm are 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp and pcm are 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n\n\n#ifndef INCLUDE_SIP_H\n#define INCLUDE_SIP_H\n\n/**********************************************/\n/* SIPDataStruct */\n/* Purpose: Store data from the SIP */\n/* Source: Commands thread (commands.c) */\n/* Used: Main thread */\n// TODO(lmf): These structure definitions have been moved to /git/flight/mcp/include/blast_sip_interface.h\n// if not needed delete these lines.\nstruct GPSposStruct {\n double lat; // probably degrees\n double lon; // probably degrees\n double alt;\n};\n\nstruct MKSaltStruct {\n float hi;\n float med;\n float lo;\n};\n\nstruct TimeStruct {\n int UTC;\n int CPU;\n};\n\nstruct MKScalStruct {\n float m_hi, m_med, m_lo;\n float b_hi, b_med, b_lo;\n};\n\nstruct SIPDataStruct {\n struct GPSposStruct GPSpos;\n struct TimeStruct GPStime;\n struct MKSaltStruct MKSalt;\n char GPSstatus1;\n char GPSstatus2;\n struct MKScalStruct MKScal;\n};\n\nextern struct SIPDataStruct SIPData;\n\nvoid WatchPort(void* parameter);\n\n#endif\n" }, { "alpha_fraction": 0.41981613636016846, "alphanum_fraction": 0.4310520887374878, "avg_line_length": 32.74137878417969, "blob_id": "7f97f2a81c26d3dd499d28d7e1b6a88ef7b72d58", "content_id": "0fbc796cc4bfc106f8ff487a87856f817f732a87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1959, "license_type": "no_license", "max_line_length": 99, "num_lines": 58, "path": "/stars/code/tools/correlate.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\nnamespace Tools\n{\n\ntemplate <typename T>\nvoid correlate2d(T data[], double psf[], double outdata[],\n int halfwidth, int halfheight, int width, int height)\n{\n\tint i, j, u, v, iu, jv;\n\tint psfwidth, psfheight;\n\tdouble result;\n\tpsfwidth = 2*halfwidth + 1;\n\tpsfheight = 2*halfheight + 1;\n\n\tfor(j=0; j<height; j++){\n for(i=0; i<width; i++){\n result = 0;\n if( (i >= halfwidth) && (i < (width-halfwidth)) &&\n (j >= halfheight) && (j < (height-halfheight)) ){\n for(v=0; v<psfheight; v++){\n for(u=0; u<psfwidth; u++){\n iu = i - halfwidth + u;\n jv = j - halfheight + v;\n result += (psf[v*psfwidth+u] * data[jv*width+iu]);\n }\n }\n } else{\n // this looks like mirroring\n for(v=0; v<psfheight; v++){\n for(u=0; u<psfwidth; u++){\n iu = i - halfwidth + u;\n jv = j - halfheight + v;\n if(iu < 0)\n iu = -iu;\n else if(iu >= width)\n iu = (width-1) - (iu - (width-1));\n if(jv < 0)\n jv = -jv;\n else if(jv >= height)\n jv = (height-1) - (jv - (height-1));\n result += (psf[v*psfwidth+u] * data[jv*width+iu]);\n }\n }\n }\n outdata[j*width+i] = result;\n }\n\t}\n}\n\nvoid add_single_pixel_correlation(unsigned short indata[], double outdata[], int width, int height,\n int pixel_x, int pixel_y, double pixel_value);\n\n}\n\n" }, { "alpha_fraction": 0.6162626147270203, "alphanum_fraction": 0.6178932785987854, "avg_line_length": 50.099998474121094, "blob_id": "dabd54a44bcf2b26c7d838c73c5a8c9085dff521", "content_id": "e5ba99f3df3fc201b43523ae3079cd33a564d5dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9200, "license_type": "no_license", "max_line_length": 115, "num_lines": 180, "path": "/stars/code/parameters/general.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"general.h\"\n#include <fstream>\n#include <boost/filesystem/operations.hpp>\n#include \"../logger_main.h\"\n\nusing namespace Parameters;\nusing namespace boost::program_options;\nusing Main::logger;\n\nGeneral::General(std::string stars_absolute_dir)\n{\n using std::string;\n\n stars_dir = stars_absolute_dir;\n\n options.add_options()\n (\"main.which_sensor\", value<string>(), \"\")\n (\"main.parse_custom_settings\", value<bool>(), \"\")\n (\"main.update_frequency\", value<float>(), \"\")\n (\"main.display_frequency\", value<float>(), \"\")\n (\"main.display_enabled\", value<bool>(), \"\")\n (\"main.display_fullscreen\", value<bool>(), \"\")\n (\"main.display_image_brightness\", value<float>(), \"\")\n (\"main.output_dir\", value<string>(), \"\")\n (\"main.network_reset_on_lull_enabled\", value<bool>(), \"\")\n (\"main.network_device_name\", value<string>(), \"\")\n (\"imaging.camera.device\", value<string>(), \"\")\n (\"imaging.camera.enabled\", value<bool>(), \"\")\n (\"imaging.camera_real.internal_triggering\", value<bool>(), \"\")\n\t\t(\"imaging.camera_real.internal_exposure_time\", value<float>(), \"\")\n\t\t(\"imaging.camera_real.internal_period\", value<float>(), \"\")\n\t\t(\"imaging.camera_real.image_width\", value<int>(), \"\")\n\t\t(\"imaging.camera_real.image_height\", value<int>(), \"\")\n\t\t(\"imaging.camera_real.image_depth\", value<int>(), \"\")\n (\"imaging.camera_filesystem.startup_delay\", value<float>(), \"\")\n (\"imaging.camera_filesystem.loading_period\", value<float>(), \"The time between files.\")\n (\"imaging.camera_filesystem.dirname\", value<string>(), \"\")\n (\"imaging.camera_filesystem.load_single_image\", value<bool>(), \"\")\n (\"imaging.camera_filesystem.single_image_filename\", value<string>(), \"\")\n (\"imaging.camera_filesystem.stack_parts\", value<bool>(), \"\")\n (\"imaging.camera_filesystem.flip_vertically\", value<bool>(), \"\")\n (\"imaging.camera_filesystem.repeat\", value<bool>(), \"\")\n (\"imaging.camera_filesystem.resave_images\", value<bool>(), \"\")\n (\"imaging.camera_filesystem.quit_after_one\", value<bool>(), \"\")\n (\"imaging.camera_filesystem.quit_after_one_delay\", value<float>(), \"\")\n (\"imaging.image_client.enabled\", value<bool>(), \"\")\n (\"imaging.lens.enabled\", value<bool>(), \"\")\n (\"imaging.lens.init_on_startup\", value<bool>(), \"\")\n (\"imaging.autofocus.focus_search_min\", value<int>(), \"\")\n (\"imaging.autofocus.focus_search_max\", value<int>(), \"\")\n (\"imaging.autofocus.focus_search_step\", value<int>(), \"\")\n (\"imaging.brightness_simulator.allow_enable\", value<bool>(), \"\")\n (\"imaging.brightness_simulator.enabled\", value<bool>(), \"\")\n (\"imaging.brightness_simulator.level_kepsa\", value<float>(), \"\")\n (\"imaging.brightness_simulator.gain_db\", value<float>(), \"\")\n (\"imaging.brightness_simulator.actual_exposure\", value<float>(), \"\")\n (\"imaging.brightness_simulator.simulated_exposure\", value<float>(), \"\")\n (\"imaging.selective_mask.enabled\", value<bool>(), \"\")\n (\"imaging.selective_mask.field0\", value<unsigned int>(), \"\")\n (\"imaging.selective_mask.field1\", value<unsigned int>(), \"\")\n (\"imaging.selective_mask.field2\", value<unsigned int>(), \"\")\n (\"solver.general.enabled\", value<bool>(), \"\")\n (\"solver.general.timeout\", value<float>(), \"\")\n (\"solver.general.debug_timing\", value<bool>(), \"\")\n (\"solver.general.saturation_limit\", value<float>(), \"\")\n (\"solver.blob_finder.snr_threshold\", value<float>(), \"\")\n (\"solver.blob_finder.max_num_blobs\", value<int>(), \"\")\n (\"solver.blob_finder.robust_mode_enabled\", value<bool>(), \"\")\n (\"solver.blob_finder.fitting_method\", value<string>(), \"\")\n (\"solver.blob_finder.cell_size\", value<unsigned int>(), \"\")\n (\"solver.blob_finder.max_num_blobs_per_cell\", value<unsigned int>(), \"\")\n\t\t(\"solver.blob_finder.badpixfilename\", value<string>(), \"\")\n (\"solver.pattern_matcher.enabled\", value<bool>(), \"\")\n (\"solver.pattern_matcher.display_names\", value<bool>(), \"\")\n (\"solver.pattern_matcher.catalog\", value<string>(), \"\")\n (\"solver.pattern_matcher.match_tolerance_px\", value<float>(), \"\")\n (\"solver.pattern_matcher.iplatescale_min\", value<float>(), \"\")\n (\"solver.pattern_matcher.iplatescale_max\", value<float>(), \"\")\n (\"solver.pattern_matcher.platescale_always_fixed\", value<bool>(), \"\")\n (\"solver.pattern_matcher.iplatescale_fixed\", value<float>(), \"\")\n (\"solver.pattern_matcher.precession_from\", value<string>(), \"\")\n (\"solver.pattern_matcher.precession_manual_epoch\", value<float>(), \"\")\n (\"solver.refraction.enabled\", value<bool>(), \"\")\n (\"solver.refraction.pressure_mbar\", value<float>(), \"\")\n (\"solver.refraction.temperature\", value<float>(), \"\")\n (\"solver.filters.horizontal.location_limit.enabled\", value<bool>(), \"\")\n (\"solver.filters.horizontal.location_limit.radius_degrees\", value<float>(), \"\")\n (\"solver.filters.horizontal.location_limit.az_degrees\", value<float>(), \"\")\n (\"solver.filters.horizontal.location_limit.el_degrees\", value<float>(), \"\")\n (\"solver.filters.horizontal.roll_limit.enabled\", value<bool>(), \"\")\n (\"solver.filters.horizontal.roll_limit.min_degrees\", value<float>(), \"\")\n (\"solver.filters.horizontal.roll_limit.max_degrees\", value<float>(), \"\")\n (\"solver.filters.horizontal.elevation_limit.enabled\", value<bool>(), \"\")\n (\"solver.filters.horizontal.elevation_limit.min_degrees\", value<float>(), \"\")\n (\"solver.filters.horizontal.elevation_limit.max_degrees\", value<float>(), \"\")\n (\"solver.filters.equatorial.location_limit.enabled\", value<bool>(), \"\")\n (\"solver.filters.equatorial.location_limit.radius_degrees\", value<float>(), \"\")\n (\"solver.filters.equatorial.location_limit.ra_degrees\", value<float>(), \"\")\n (\"solver.filters.equatorial.location_limit.dec_degrees\", value<float>(), \"\")\n (\"solver.filters.equatorial.roll_limit.enabled\", value<bool>(), \"\")\n (\"solver.filters.equatorial.roll_limit.min_degrees\", value<float>(), \"\")\n (\"solver.filters.equatorial.roll_limit.max_degrees\", value<float>(), \"\")\n (\"solver.filters.horizontal_source.settings.enabled\", value<bool>(), \"\")\n (\"solver.filters.horizontal_source.settings.lat_degrees\", value<float>(), \"\")\n (\"solver.filters.horizontal_source.settings.lst_hours\", value<float>(), \"\")\n (\"solver.filters.horizontal_source.fits.enabled\", value<bool>(), \"\")\n (\"solver.filters.horizontal_source.fcp.enabled\", value<bool>(), \"\")\n (\"solver.filters.matching.pointing_error_threshold_arcsec\", value<float>(), \"\")\n (\"solver.filters.matching.fit_error_threshold_px\", value<float>(), \"\")\n (\"solver.filters.matching.num_matched\", value<unsigned int>(), \"\")\n ;\n add_bypass_with_blobs();\n\n}\n\nvoid General::add_bypass_with_blobs()\n{\n options.add_options()\n (\"solver.blob_finder.bypass_with_blobs.enabled\", value<bool>(), \"\")\n (\"solver.blob_finder.bypass_with_blobs.num_blobs\", value<unsigned int>(), \"\")\n ;\n for (unsigned int i=0; i<max_num_bypass_blobs; i++) {\n options.add_options()\n ((boost::format(\"solver.blob_finder.bypass_with_blobs.blob%d.x\") %i).str().c_str(), value<float>(), \"\")\n ((boost::format(\"solver.blob_finder.bypass_with_blobs.blob%d.y\") %i).str().c_str(), value<float>(), \"\")\n ;\n }\n}\n\nvoid General::load(int argc, char* argv[])\n{\n using namespace boost::filesystem;\n bool parse_custom_settings = true;\n\n try {\n store(parse_command_line(argc, argv, options,\n command_line_style::default_style & ~command_line_style::allow_guessing), map);\n } catch(std::exception& e) {\n logger.log(format(\"Caught exception parsing command line options: %s\") % e.what());\n }\n\n notify(map);\n if (map.count(\"main.parse_custom_settings\")) {\n if (!map[\"main.parse_custom_settings\"].as<bool>()) {\n parse_custom_settings = false;\n }\n }\n\n if (parse_custom_settings) {\n std::ifstream infile0(system_complete(stars_dir + \"settings/custom.txt\").string().c_str());\n\t\t logger.log(format(\"%s\") % system_complete(stars_dir + \"settings/custom.txt\").string().c_str());\n try {\n store(parse_config_file(infile0, options), map);\n } catch(std::exception& e) {\n logger.log(format(\"Caught exception parsing config file: %s\") % e.what());\n }\n infile0.close();\n }\n\n std::ifstream infile1(system_complete(stars_dir + \"settings/flight.txt\").string().c_str());\n\tif (!infile1) {\n\t\tlogger.log(\"Could not open flight.txt\");\n\t}\n\telse\n try {\n\t\tstore(parse_config_file(infile1, options), map);\n } catch(std::exception& e) {\n logger.log(format(\"Caught exception parsing config file: %s\") % e.what());\n }\n infile1.close();\n\n notify(map);\n\n}\n\n" }, { "alpha_fraction": 0.5884907841682434, "alphanum_fraction": 0.6072204113006592, "avg_line_length": 30.75, "blob_id": "f8b655e4fee7b43af9d32074616f1fb84bf80a3b", "content_id": "27147254ef3dab427e486640eeeddf1acaaec059", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3685, "license_type": "no_license", "max_line_length": 96, "num_lines": 116, "path": "/stars/code/solving/matching/fluxer.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"fluxer.h\"\n#include <levmar.h>\n#include <cstdlib>\n#include <cmath>\n#include \"../../tools/timing.h\"\n#include \"../solution.h\"\n#include \"../blob.h\"\n#include \"../star.h\"\n#include \"../logger.h\"\n\n#include \"../../tools/quick_cout.h\"\n\nusing namespace Solving::Matching;\nusing namespace Solving;\nusing std::vector;\n\nnamespace levmar_fluxer\n{\n\nvoid error_function(double* params, double* blob_fluxes, int num_params, int num_blobs,\n void* data)\n{\n additional_data* adata = (additional_data*) data;\n double* star_fluxes = adata->star_fluxes;\n double* errors = adata->errors;\n\n for (unsigned int i = 0; i < (unsigned int) num_blobs; i++) {\n blob_fluxes[i] = star_fluxes[i] * params[0] / errors[i];\n }\n}\n\n}\n\nFluxer::Fluxer(): max_num_blobs(100)\n{\n int max_num_params = 1;\n workspace = (double *) malloc((LM_DIF_WORKSZ(max_num_params, max_num_blobs) +\n max_num_params*max_num_params) * sizeof(double));\n covar = workspace + LM_DIF_WORKSZ(max_num_params, max_num_blobs);\n adata.star_fluxes = new double[max_num_blobs];\n adata.errors = new double[max_num_blobs];\n blob_fluxes = new double[max_num_blobs];\n params = new double[max_num_params];\n info = new double[LM_INFO_SZ];\n}\n\nFluxer::~Fluxer()\n{\n delete [] info;\n delete [] params;\n delete [] blob_fluxes;\n delete [] adata.errors;\n delete [] adata.star_fluxes;\n free(workspace);\n}\n\nvoid Fluxer::fit(Solution& solution, vector<Blob>& blobs, vector<Star>& stars, bool print)\n{\n if (blobs.size() < 1 || (blobs.size() != stars.size())) {\n logger.log(format(\"fluxer: warning: blobs.size = %i, stars.size = %i\")\n % blobs.size() % stars.size());\n return;\n }\n\n int num_saturated_blobs = 0;\n unsigned int brightest_star_index = 0;\n unsigned int j=0;\n for (unsigned int i=0; i<blobs.size() && j<max_num_blobs; i++) {\n if (blobs[i].saturated) {\n num_saturated_blobs++;\n } else {\n double error = fabs(stars[i].mag)*0.0001;\n if (error <= 0) {\n error = 1000000.0;\n }\n adata.errors[j] = error;\n blob_fluxes[j] = blobs[i].flux / error;\n adata.star_fluxes[j] = stars[i].mag;\n if (adata.star_fluxes[j] > adata.star_fluxes[brightest_star_index]) {\n brightest_star_index = j;\n }\n j++;\n }\n }\n unsigned int num_blobs = j;\n unsigned int num_params = 1;\n\n logger.log(format(\"fluxer: ignoring %d saturated blobs\") % num_saturated_blobs);\n logger.log(format(\"fluxer: fitting %d matched blobs\") % num_blobs);\n if (num_blobs < 1) {\n logger.log(\"fluxer: warning: not enough blobs to fit\");\n return;\n }\n\n params[0] = blob_fluxes[brightest_star_index] / adata.star_fluxes[brightest_star_index];\n dlevmar_dif(levmar_fluxer::error_function, params, blob_fluxes, num_params,\n num_blobs, 100, NULL, info, workspace, covar, (void*) &adata);\n\n logger.log(format(\"fluxer: found best fit line %.4e ADU/(e/m^2/s)\") % params[0]);\n\n // params[0] is in ADU / (electrons / m^s / s)\n // s = [(ADU/e) * m^2 * s] / (ADU/e) / (m^2)\n\tdouble gain = 0.008192; //Previous value: 0.04096 11-17-15: Adjusting to match observed offset\n double aperture = 0.009696;\n\n solution.measured_exposure = params[0] / gain / aperture;\n logger.log(format(\"fluxer: found best fit exposure %.0f ms\")\n % Time::to_milliseconds(solution.measured_exposure));\n\n}\n\n" }, { "alpha_fraction": 0.6463742256164551, "alphanum_fraction": 0.6732318997383118, "avg_line_length": 28.786666870117188, "blob_id": "635ab7e7990bfabccc2830974dbe10cdda500de5", "content_id": "066932d51780ef3eeb3571d1e116368300214a97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2234, "license_type": "no_license", "max_line_length": 102, "num_lines": 75, "path": "/groundhog/groundhog_funcs.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#ifndef INCLUDE_GROUNDHOG_H\n#define INCLUDE_GROUNDHOG_H\n\n#include <stdarg.h>\n\n#define NOR \"\\x1B[0m\"\n#define RED \"\\x1B[31;1m\"\n#define GRN \"\\x1B[32;1m\"\n#define YLW \"\\x1B[33;1m\"\n#define BLU \"\\x1B[34;1m\"\n#define MAG \"\\x1B[35;1m\"\n#define CYN \"\\x1B[36;1m\"\n#define NOC \"\\x1B[?25l\"\n#define CUR \"\\x1B[?25h\"\n\n#define GROUNDHOG_LOG \"/data/etc/groundhog.log\"\n\n// groundhog linklist\n#include \"linklist.h\"\n#include \"linklist_writer.h\"\n#include \"linklist_compress.h\"\n\n#define GROUNDHOG_OPEN_NEW_RAWFILE 0x01\n#define GROUNDHOG_REUSE_VALID_RAWFILE 0x02\n#define GROUNDHOG_EXTRACT_TO_DISK 0x04\n\nextern superframe_t * superframe;\nextern int verbose;\n\n// groundhog helper functions\nvoid daemonize();\nlinklist_rawfile_t * groundhog_open_rawfile(linklist_rawfile_t *, linklist_t *, char *, int);\nint groundhog_check_for_fileblocks(linklist_t * ll, char *);\nint groundhog_unpack_fileblocks(linklist_t * ll, unsigned int transmit_size, uint8_t * compbuffer,\n uint8_t * local_allframe, char * filename_str, char * disp_str, \n linklist_rawfile_t ** ll_rawfile, unsigned int flags);\nint64_t groundhog_process_and_write(linklist_t * ll, unsigned int transmit_size, uint8_t * compbuffer,\n uint8_t * local_allframe, char * filename_str, char * disp_str,\n linklist_rawfile_t ** ll_rawfile, unsigned int flags);\n\n// groundhog required functions (to be defined in the groundhog main c file)\nvoid groundhog_write_calspecs(char * fname);\n\nstruct UDPSetup {\n char name[80];\n char addr[80];\n unsigned int port;\n unsigned int maxsize;\n unsigned int packetsize;\n int downlink_index;\n};\n\nstruct TlmReport {\n linklist_t * ll;\n uint64_t framenum;\n uint64_t prev_framenum;\n uint64_t stale;\n int allframe;\n int type;\n};\n\nstruct LinklistState {\n uint32_t serial;\n char symname[LINKLIST_MAX_FILENAME_SIZE];\n linklist_rawfile_t * ll_rawfile;\n};\n\n// BLAST print functions (required)\n// must define groundhog_info, _warn, and _fatal\n#define groundhog_info(fmt, ...) printf(fmt, ##__VA_ARGS__)\n#define groundhog_warn(fmt, ...) printf(fmt, ##__VA_ARGS__)\n#define groundhog_fatal(fmt, ...) printf(fmt, ##__VA_ARGS__); exit(2)\n\n\n#endif\n" }, { "alpha_fraction": 0.6431419253349304, "alphanum_fraction": 0.6626794338226318, "avg_line_length": 33.59310531616211, "blob_id": "697654ace8677c40e2ccbe5b9cafcac22c242594", "content_id": "9abb52907fa5ae75694ce8aeef9db0fb95a7a7f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5016, "license_type": "no_license", "max_line_length": 101, "num_lines": 145, "path": "/common/include/channels_tng.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * channels_v2.h: \n *\n * This software is copyright \n * (C) 2013-2014 California State University, Sacramento\n *\n * This file is part of mcp, created for the BLASTPol Project.\n *\n * mcp 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Aug 5, 2014 by seth\n */\n\n#ifndef INCLUDE_CHANNELS_TNG_H\n#define INCLUDE_CHANNELS_TNG_H\n\n#include <stdint.h>\n#include <stdlib.h>\n\n#include \"channel_macros.h\"\n#include \"lookup.h\"\n#include \"linklist.h\"\n\n#define FIELD_LEN 32\n#define UNITS_LEN 48\n#define BLAST_TNG_CH_VERSION 1\n\n#define NUM_KIDS 1024\n#define NUM_ROACHES 5\n#define NUM_RTYPES 3\n#define NUM_ROACH_TLM 15\n#define ROACH_NAME_SARRAY \"ROACH_NAMES\"\n\n#include \"derived.h\"\n\n#define _RATES(x, _)\t\\\n\t_(x, 1HZ)\t\t\t\t\t\\\n\t_(x, 5HZ)\t\t\t\t\t\\\n\t_(x, 100HZ)\t\t\t\t\t\\\n\t_(x, 200HZ) \\\n\t_(x, 244HZ) \\\n _(x, 488HZ)\n\nBLAST_LOOKUP_TABLE(RATE, static);\n\n#define _TYPES(x, _)\t\\\n\t_(x, UINT8)\t\t\\\n\t_(x, UINT16)\t\\\n\t_(x, UINT32)\t\\\n\t_(x, UINT64)\t\\\n\t_(x, INT8)\t\t\\\n\t_(x, INT16)\t\t\\\n\t_(x, INT32)\t\t\\\n\t_(x, INT64)\t\t\\\n\t_(x, FLOAT)\t\t\\\n\t_(x, DOUBLE)\nBLAST_LOOKUP_TABLE(TYPE, static);\n\n\nstruct channel {\n char field[FIELD_LEN]; /// name of channel for FileFormats and CalSpecs\n double m_c2e; /// Conversion from counts to engineering units is\n double b_e2e; /// e = c * m_c2e + b_e2e\n E_TYPE type; /// Type of data stored\n E_RATE rate; /// Rate at which the channel is recorded\n char quantity[UNITS_LEN]; /// eg, \"Temperature\" or \"Angular Velocity\"\n char units[UNITS_LEN]; /// eg, \"K\" or \"^o/s\"\n void *var; /// Pointer to the variable in the current frame\n} __attribute__((aligned));\n\n/**\n * These next two structures are packed for network transmission and disk storage. Do\n * not use them for working with structures\n */\n#pragma pack(push, 1)\nstruct channel_packed {\n char field[FIELD_LEN]; /// name of channel for FileFormats and CalSpecs\n double m_c2e; /// Conversion from counts to engineering units is\n double b_e2e; /// e = c * m_c2e + b_e2e\n int8_t type; /// Type of data stored\n int8_t rate; /// Rate at which the channel is recorded\n char quantity[UNITS_LEN]; /// eg, \"Temperature\" or \"Angular Velocity\"\n char units[UNITS_LEN]; /// eg, \"K\" or \"^o/s\"\n};\n\ntypedef struct {\n uint32_t magic;\n uint8_t version;\n uint32_t length;\n uint32_t crc;\n struct channel_packed data[0];\n} channel_header_t;\n#pragma pack(pop)\n\n#pragma pack(push, 1)\ntypedef struct {\n uint64_t timestamp;\n uint8_t source;\n} frame_header_t;\n#pragma pack(pop)\n\nextern void *channel_data[RATE_END];\nextern size_t frame_size[RATE_END];\nextern channel_t channel_list[];\nextern derived_tng_t derived_list[];\nextern int channels_count;\nextern superframe_t * superframe;\n\nint channels_initialize(const channel_t * const m_channel_list);\nchannel_t *channels_find_by_name(const char *m_name);\nint channels_store_data(E_RATE m_rate, const void *m_data, size_t m_len);\nint channels_check_size_of_frame(E_RATE m_rate, size_t m_len);\nint channels_read_map(channel_header_t *m_map, size_t m_len, channel_t **m_channel_list);\nchannel_header_t *channels_create_map(channel_t *m_channel_list);\nchannel_header_t *channels_create_rate_map(channel_t *m_channel_list, E_RATE m_rate);\nsize_t channel_size(channel_t *);\nunsigned int add_frame_to_superframe(void * , E_RATE , void *, unsigned int *);\nunsigned int extract_frame_from_superframe(void * , E_RATE , void *, unsigned int *);\nunsigned int get_spf(unsigned int);\n\nint channels_read_derived_map(derived_header_t *m_map, size_t m_len, derived_tng_t **m_channel_list);\nderived_header_t *channels_create_derived_map(derived_tng_t *m_derived);\nsuperframe_t * channels_generate_superframe(const channel_t * const m_channel_list);\nvoid make_name_from_roach_index(unsigned int , char * name);\nint get_roach_index(unsigned int , unsigned int , unsigned int);\nvoid read_roach_index(unsigned int *, unsigned int *, unsigned int *, unsigned int);\nlinklist_t * generate_housekeeping_linklist(linklist_t * , char *);\nvoid channels_write_calspecs(char *, derived_tng_t *);\ndouble channel_data_to_double(uint8_t * data, uint8_t type);\nint channel_double_to_data(uint8_t * data, double dub, uint8_t type);\n\n#endif /* CHANNELS_V2_H_ */\n" }, { "alpha_fraction": 0.6775793433189392, "alphanum_fraction": 0.6815476417541504, "avg_line_length": 18.764705657958984, "blob_id": "52bace722ffde8270f656beb34b99b7059e7ba30", "content_id": "ba7ff8603333d292aaafb7cb86f07d865fdd7fac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1009, "license_type": "no_license", "max_line_length": 73, "num_lines": 51, "path": "/stars/code/shared/image/stats.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__IMAGE__STATS_H\n#define SHARED__IMAGE__STATS_H\n\n#include \"../circular_buffer.h\"\n\nnamespace Shared\n{\n namespace Image\n {\n\nclass Stats\n{\n public:\n Stats();\n Stats& operator=(const Stats& rhs);\n void init(Parameters::Manager& params);\n void clear(int counter_stars_);\n\n int counter_stars;\n bool mean_known;\n double mean;\n bool noise_known;\n double noise;\n bool gain_known;\n double gain;\n double gaindb;\n int num_pixels_saturated;\n double fraction_pixels_saturated;\n bool autofocus_metric_valid;\n double autofocus_metric;\n};\n\n// writes: solver\n// reads: main\nextern Shared::CircularBufferPass <Stats> stats_solver_for_main;\n\n// writes: main\n// reads: net\nextern Shared::CircularBuffer <Stats> stats_main_for_net;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.6291549801826477, "alphanum_fraction": 0.6471766233444214, "avg_line_length": 27.05617904663086, "blob_id": "6ccdc6c9d68a703756e63e3a63a0123bcf45a2ad", "content_id": "e244187214627bb44eb62e670fa22b7fe3fd05e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2497, "license_type": "no_license", "max_line_length": 98, "num_lines": 89, "path": "/owl/main.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl is written by Joshua Netterfield ([email protected])\n * and is copyright (C) 2011 University of Toronto.\n *\n * It is a successor to Palantir, which was written by Adam Hincks, et al.\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n * owl is also used by BIT!! \n */\n\n#include <QApplication>\n#include <QStyleFactory>\n#include <time.h>\n#include \"PMainWindow.h\"\n#include <QTime>\n#include <iostream>\n#include <QDebug>\n#ifdef __APPLE__\n#include <python2.6/Python.h>\n#else\n#include <python2.7/Python.h> // Replace python2.7 with your version of Python\n#endif\n\nvoid usage(QString appname) {\n std::cout<<\"usage: \"<<qPrintable(appname)<<\" [--fs <fontsize>] [--new | <filename>]\"<<std::endl;\n exit(1);\n}\n\nint main(int argc, char* argv[]) {\n\n QApplication app(argc, argv);\n\n QString filename(\"__lastfile\");\n\n app.setStyle(QStyleFactory::create(\"GTK+\"));\n app.setWindowIcon(QIcon(\":icons/icons/Owl0.svg\"));\n\n\n if (app.arguments().size() > 6) {\n usage(app.arguments()[0]);\n }\n\n int font_size = app.font().pointSize();\n\n for (int i_arg=1; i_arg<app.arguments().size(); i_arg++) {\n if (app.arguments().at(i_arg) == \"--new\") {\n filename.clear();\n } else if (app.arguments().at(i_arg) == \"--fs\") {\n if (++i_arg <app.arguments().size()) {\n font_size = app.arguments().at(i_arg).toInt();\n } else {\n usage(app.arguments()[0]);\n }\n } else if (app.arguments().at(i_arg).startsWith('-')) {\n usage(app.arguments()[0]);\n } else {\n filename = app.arguments().at(i_arg);\n }\n }\n\n time_t seconds= time (NULL);\n qsrand((seconds*1000+QTime::currentTime().msec())%RAND_MAX); // For unique ids.\n\n Py_Initialize();\n PMainWindow *mw = new PMainWindow(font_size, filename);\n\n if (filename.isEmpty()) {\n mw->setMDIMinSize(1900, 1200);\n }\n\n app.exec();\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5472118854522705, "alphanum_fraction": 0.6057992577552795, "avg_line_length": 26.674896240234375, "blob_id": "af8f01d9d713f42378323f4082913f19d0346d1a", "content_id": "90d4f19c3949b3bb6e61013e7a066194bab01d64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6725, "license_type": "no_license", "max_line_length": 98, "num_lines": 243, "path": "/xymap/iirfilter.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <deque>\n#include <vector>\n#include <complex>\n\n#ifndef _IIRFILTER_H\n#define _IIRFILTER_H\n\nusing std::deque;\nusing std::vector;\n\ntypedef std::complex<double> complex;\n\n/* \n * allows for definition of general recursive/IIR filters\n *\n * Probably doesn't need to be a template, but I was experimenting\n * now you can filter a series of vectors! (or rather float/long double/complex)\n *\n */\ntemplate<class T> class IIRFilter {\n public:\n IIRFilter(unsigned int order);\n\n //do fitlering by calling your instance with most recent input\n T operator() (T x);\n\n //clear the filter history\n void clear();\n\n //evaluate transfer function at complex point z\n complex transfer(complex z);\n\n //function generates data stream containing impulse and frequency response\n //clears filter both before and after\n int FilterResponse(const char* out, double max_f=0.5, unsigned int n=100);\n\n protected:\n //to be used in derived class constructors\n void setCoefficients(vector<double> na, vector<double> nb);\n\n private:\n deque<T> x0;\t//last filter input\n deque<T> y0;\t//last filter output\n vector<double> a;\t//coefficients to multiply y0\n vector<double> b;\t//coefficients to multiply x, x0\n unsigned int order;\t//order of the filter\n};\n\n/* \n * A few sample filter types. Analytic forms for a few low-order Bessel filters\n *\n * TODO: it would be great to use numerically designed filters\n *\n */\n\n//1st order bessel low-pass, with knee frequency f (in sample rate units)\ntemplate <class T> class BesselLP1 : public IIRFilter<T> {\n public:\n BesselLP1(double f);\n};\n\n//1st order bessel high-pass, with knee frequency f (in sample rate units)\ntemplate <class T> class BesselHP1 : public IIRFilter<T> {\n public:\n BesselHP1(double f);\n};\n\n//4th order bessel low-pass, with knee frequency f (in sample rate units)\ntemplate <class T> class BesselLP4 : public IIRFilter<T> {\n public:\n BesselLP4(double f);\n};\n\n\n/*******************************************************************************\n * IMPLEMENTATION\n * g++ doesn't support 'export' for template implementations in another file\n * so, all the implementations are here\n ******************************************************************************/\n\n#include <iostream>\n#include <fstream>\n#include <numeric>\n#include <cmath>\n#include \"iirfilter.h\"\n\nusing std::cerr;\nusing std::endl;\n\ntemplate<class T> IIRFilter<T>::IIRFilter(unsigned int order)\n{\n this->order = order;\n x0.resize(order, 0.0);\n y0.resize(order, 0.0);\n a.resize(order, 0.0);\n b.resize(order+1, 0.0); //includes coefficient for new inupt x\n}\n\ntemplate<class T> T IIRFilter<T>::operator() (T x)\n{\n T y = b[0]*x;\n //cerr << \"y = (\" << b[0] << \")*x[n]\" << endl;\n for (unsigned int i=0; i<order; i++) {\n y += b[i+1] * x0[i];\n y -= a[i] * y0[i];\n //cerr << \" + (\" << b[i+1] << \")*x[n-\" << i+1 << \"]\";\n //cerr << \" - (\" << a[i] << \")*y[n-\" << i+1 << \"]\" << endl;\n }\n\n x0.pop_back();\n x0.push_front(x);\n y0.pop_back();\n y0.push_front(y);\n\n return y;\n}\n\ntemplate<class T> void IIRFilter<T>::clear() {\n x0.resize(order, T());\n y0.resize(order, T());\n}\n\ntemplate<class T> complex IIRFilter<T>::transfer(complex z)\n{\n complex numer = pow(z,4)*b[0];\n complex denom = pow(z,4);\n for (unsigned int i=0; i<order; i++) {\n numer += b[i+1]*pow(z,order-1-i);\n denom += a[i]*pow(z,order-1-i);\n }\n\n return numer/denom;\n}\n\ntemplate<class T> int IIRFilter<T>::FilterResponse(const char* out, double max_f, unsigned int n)\n{\n std::ofstream oo(out);\n if (!oo) {\n cerr << \"Couldn't open FilterResponse output file\" << endl;\n return 1;\n }\n this->clear();\n\n oo << \"INDEX\\timpulse\\tfreq\\tgain\\tphase\" << endl;\n for (unsigned int i=0; i<n; i++) {\n oo << i+1 << \"\\t\";\t\t\t\t//INDEX\n oo << (*this)((i==0)?1.0:0.0) << \"\\t\";\t//impulse response\n //frequency goes up to Nyquist (0.5 in sample frequency units)\n double freq = (double)i*max_f/(double)n;\n oo << freq << \"\\t\";\t\t\t\t//frequency (in sample units)\n complex resp = transfer(complex(cos(2*M_PI*freq),sin(2*M_PI*freq)));\n oo << abs(resp) << \"\\t\";\t\t\t//gain\n oo << arg(resp) << \"\\n\";\t\t\t//phase\n }\n\n this->clear();\n return 0;\n}\n\ntemplate<class T> \nvoid IIRFilter<T>::setCoefficients(vector<double> na, vector<double> nb)\n{\n if (na.size() != order || nb.size() != order+1) {\n cerr << \"Invalid size of coefficient vector\\n\" << endl;\n return;\n }\n a = na;\n b = nb;\n}\n\n\n\n//The filter forms below were solved analytically using a bilinear transform\n\n//bessel scale factors\n//convert normalization from unit delay at f=0 to 3dB attenutation at 1rad/s\nconst double norm_bessel_O1 = 1.0;\nconst double norm_bessel_O2 = 1.36165412871613;\nconst double norm_bessel_O3 = 1.75567236868121;\nconst double norm_bessel_O4 = 2.11391767490422;\nconst double norm_bessel_O5 = 2.42741070215263;\nconst double norm_bessel_O6 = 2.70339506120292;\nconst double norm_bessel_O7 = 2.95172214703872;\nconst double norm_bessel_O8 = 3.17961723751065;\nconst double norm_bessel_O9 = 3.39169313891166;\nconst double norm_bessel_O10 = 3.59098059456916;\n\ntemplate<class T> BesselLP1<T>::BesselLP1(double f) : IIRFilter<T>(1)\n{\n vector<double> a(1), b(2);\n double alpha = M_PI*f/norm_bessel_O1;\n alpha = tan(alpha); //pre-warp\n a[0] = (alpha-1.0)/(1.0+alpha);\n b[0] = alpha/(1.0+alpha);\n b[1] = alpha/(1.0+alpha);\n this->setCoefficients(a, b);\n}\n\ntemplate<class T> BesselHP1<T>::BesselHP1(double f) : IIRFilter<T>(1)\n{\n vector<double> a(1), b(2);\n double alpha = M_PI*f/norm_bessel_O1;\n alpha = tan(alpha); //pre-warp\n a[0] = (alpha-1.0)/(1.0+alpha);\n b[0] = 1.0/(1.0+alpha);\n b[1] = -1.0/(1.0+alpha);\n this->setCoefficients(a, b);\n}\n\ntemplate<class T> BesselLP4<T>::BesselLP4(double f) : IIRFilter<T>(4)\n{\n vector<double> a(4), b(5);\n double alpha = M_PI*f/norm_bessel_O4;\n alpha = tan(alpha); //pre-warp\n double denom = (1.0 + 1.0/alpha + 45.0/105.0/pow(alpha,2) \n + 10.0/105.0/pow(alpha,3) + 1.0/105.0/pow(alpha,4));\n\n a[0] = (4.0 + 2.0/alpha \n - 20.0/105.0/pow(alpha,3) - 4.0/105.0/pow(alpha,4))/denom;\n a[1] = (6.0 - 90.0/105.0/pow(alpha,2) + 6.0/105.0/pow(alpha,4))/denom;\n a[2] = (4.0 - 2.0/alpha \n + 20.0/105.0/pow(alpha,3) - 4.0/105.0/pow(alpha,4))/denom;\n a[3] = (1.0 - 1.0/alpha + 45.0/105.0/pow(alpha,2) \n - 10.0/105.0/pow(alpha,3) + 1.0/105.0/pow(alpha,4))/denom;\n\n b[0] = 1.0/denom;\n b[1] = 4.0/denom;\n b[2] = 6.0/denom;\n b[3] = 4.0/denom;\n b[4] = 1.0/denom;\n\n /*\n cerr << \"y = (\" << b[0] << \")*x[n]\" << endl;\n for (unsigned int i=0; i<4; i++) {\n cerr << \" + (\" << b[i+1] << \")*x[n-\" << i+1 << \"]\";\n cerr << \" - (\" << a[i] << \")*y[n-\" << i+1 << \"]\" << endl;\n }\n */\n\n this->setCoefficients(a, b);\n}\n\n#endif\n" }, { "alpha_fraction": 0.7071005702018738, "alphanum_fraction": 0.7130177617073059, "avg_line_length": 18.852941513061523, "blob_id": "ac1e6bbd0da448eb7f7bc2c5aef6eb236dcafc0e", "content_id": "2d3b98475b9e4fa06b9c09dbed4ab9219eae3552", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 677, "license_type": "no_license", "max_line_length": 73, "num_lines": 34, "path": "/stars/code/displaying/housekeeping.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__HOUSEKEEPING_H\n#define DISPLAYING__HOUSEKEEPING_H\n\n#include <vector>\n#include \"block.h\"\n#include \"dynamic_value.h\"\n#include \"utilities.h\"\n#include \"../tools/timing.h\"\n\nnamespace Displaying\n{\n class Housekeeping;\n}\n\nclass Displaying::Housekeeping: public Block\n{\n public:\n Housekeeping();\n void update();\n void draw(Position &position);\n\n private:\n std::vector<DynamicValue> measurements;\n Tools::Timer disk_timer;\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.6320868730545044, "alphanum_fraction": 0.6417370438575745, "avg_line_length": 25.74193572998047, "blob_id": "9bfe31dc9b54f6f85740a9a8710ca39afb492a45", "content_id": "da75c25e2848ac57c3b87d4e2a61392fe42248f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 829, "license_type": "no_license", "max_line_length": 134, "num_lines": 31, "path": "/sched_upload/Makefile", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "all: sched_upload sanity\n\n# the name of the BLAST-etc project in the repository\nBLASTETC = blast_etc\n\n# a list of all the remote projects needed to build\nREMOTEPROJ = $(BLASTETC)\n\nETC_DATA = sched.library\n\ninclude ../common/Makefile.update\n\n../common/Makefile.update:\n\t@echo \"ERROR: **************************************************************\"\n\t@echo \"Common build files not found; unable to continue. Try:\"\n\t@echo \" ( cd .. && svn co `svn info --non-interactive | awk ' /URL/ { print $$2 } ' | sed -e 's/trunk\\/.*/trunk\\/common/'` common )\"\n\t@false\n\nsched_upload: sched_upload.c\n\tgcc -O3 -o sched_upload sched_upload.c -lm\n\nsanity: sanity.c\n\tgcc -o sanity sanity.c\n\ninstall: sched_upload sanity\n\tinstall -m 755 sched_upload /usr/local/bin\n\tinstall -m 755 sanity /usr/local/bin\n\nclean:\n\trm -f sched_upload sanity\n\trm -f *.o\n" }, { "alpha_fraction": 0.6868787407875061, "alphanum_fraction": 0.6898608207702637, "avg_line_length": 24.137500762939453, "blob_id": "24c95c7fa1647d2ff4173d96be0732a1e8d0a5e8", "content_id": "d7727421dc0e66b263cf44d593a0d75a590aa2e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2013, "license_type": "no_license", "max_line_length": 171, "num_lines": 80, "path": "/stars/code/solving/finding/finder.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__FINDING__FINDER_H\n#define SOLVING__FINDING__FINDER_H\n\n#include <vector>\n#include \"estimator.h\"\n#include \"leveler.h\"\n#include \"smoother.h\"\n#include \"fitter.h\"\n#include \"pedestal_fitter.h\"\n#include \"badpix.h\"\n#include \"../../shared/image/raw.h\"\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n}\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Solving\n{\n namespace Finding\n {\n class Finder;\n }\n}\n\nclass Solving::Finding::Finder\n{\n public:\n Finder(Parameters::Manager& params);\n ~Finder();\n std::vector<Blob> fit_blobs(Shared::Image::Raw& image, std::vector<Blob> &blobs);\n bool is_local_max_in_smooth(int x, int y);\n std::vector<Blob> find_blobs(Shared::Image::Raw& image, double noise);\n\n private:\n std::vector<Blob> search_for_peaks_in_cell(unsigned int cell_size, unsigned int ucell, unsigned int vcell, double threshold, double noise, unsigned int max_num_blobs);\n std::vector<Blob> search_for_peaks(int halfwidth, double noise);\n bool are_duplicates(Blob& blob0, Blob& blob1);\n std::vector<Blob> unique(std::vector<Blob>& original_blobs);\n std::vector<Blob> estimate_blobs(Shared::Image::Raw& image, std::vector<Blob> possible_blobs);\n void print_blobs (std::vector<Blob>& blobs);\n void crop_vector(std::vector<Blob>& blobs, unsigned int num);\n\n int image_width;\n int image_height;\n double* pixels_smoothed;\n unsigned short* pixels_leveled;\n\t//const char* badpixlist;\n\tint satval;\n\t//unsigned short satval;\n\tint mapmeans;\n\t//double mapmean;\n\tstd::string badpixlist;\n Smoother smoother;\n Estimator estimator;\n\tBadpix badpix;\n Leveler leveler;\n Fitter fitter;\n PedestalFitter pedestal_fitter;\n\n bool bypass_blobs_enabled;\n std::vector<Blob> bypass_blobs;\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.6103573441505432, "alphanum_fraction": 0.6233518123626709, "avg_line_length": 35.082759857177734, "blob_id": "a028dae79b4e3cf5501b6cbad1133919d07d2cd4", "content_id": "986248534f423ccf03cd97376c20a5d38307c8c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5234, "license_type": "no_license", "max_line_length": 139, "num_lines": 145, "path": "/stars/code/networking/image_client.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"image_client.h\"\n#include <boost/bind.hpp>\n#include \"ebex_images.h\"\n#include \"logger.h\"\n#include \"../shared/general/quit.h\"\n#include \"../shared/image/raw.h\"\n#include \"../shared/network/image_client_settings.h\"\n#include \"../shared/update.h\"\n#include \"../tools/quick_cout.h\"\n\nusing namespace NetworkingImageClient;\nusing namespace boost::asio::ip;\n\nImageClient::ImageClient(boost::asio::io_service& io_service, int which_fc):\n socket(io_service),\n read_timer(io_service)\n{\n Shared::ThreadNames::Name thread_name = Shared::ThreadNames::nobody;\n if (which_fc == 1)\n {\n shared_image = (Shared::Image::raw_for_image_client1.r);\n shared_settings = Shared::Network::image_client_settings1.r;\n logger = &logger1;\n server_ip = \"192.168.1.3\";\n thread_name = Shared::ThreadNames::net_image_client1;\n }\n else if (which_fc == 2)\n {\n shared_image = Shared::Image::raw_for_image_client2.r;\n shared_settings = Shared::Network::image_client_settings2.r;\n logger = &logger2;\n server_ip = \"192.168.1.4\";\n thread_name = Shared::ThreadNames::net_image_client2;\n }\n else\n {\n logger1.log(\"which_fc invalid\");\n logger2.log(\"which_fc invalid\");\n return;\n }\n logger->log(format(\"image_client initialized for fc%i\") % which_fc);\n\n counter_stars = -1;\n data_size = shared_image->width * shared_image->height * sizeof(unsigned short);\n current_exposure = 0;\n\n header = (ebex_images_header_t*) malloc(sizeof(ebex_images_header_t) + data_size);\n if (header == NULL) {\n logger->log(\"unable to allocate memory for image_client buffer\");\n return;\n }\n\n while (!Shared::General::quit) {\n Shared::update(thread_name);\n if (which_fc == 1)\n {\n shared_image = (Shared::Image::raw_for_image_client1.r);\n shared_settings = Shared::Network::image_client_settings1.r;\n }\n else if (which_fc == 2)\n {\n shared_image = Shared::Image::raw_for_image_client2.r;\n shared_settings = Shared::Network::image_client_settings2.r;\n }\n\n if (counter_stars != shared_image->counter_stars) {\n counter_stars = shared_image->counter_stars;\n if (shared_settings->enabled) {\n usleep(1000000);\n write_image(io_service);\n }\n }\n usleep(1000000);\n }\n}\n\nImageClient::~ImageClient()\n{\n free(header);\n}\n\nvoid ImageClient::write_image(boost::asio::io_service& io_service)\n{\n tcp::endpoint endpoint(address(address_v4::from_string(server_ip)), EBEX_IMAGES_PORT);\n boost::system::error_code error;\n socket.connect(endpoint, error);\n if (!error) {\n logger->log(format(\"connected to %s\") % server_ip);\n current_exposure = 0;\n write_exposure();\n io_service.run();\n socket.close();\n io_service.reset();\n logger->log(\"connection closed\");\n } else {\n logger->log(format(\"error connecting to %s\") % boost::system::system_error(error).what());\n }\n}\n\nvoid ImageClient::write_exposure()\n{\n if (current_exposure < shared_image->num_exposures) {\n header->magic = ebex_images_magic;\n header->length = data_size;\n std::string filename = (format(\"%s_p%i.raw\") % shared_image->filename_base % current_exposure).str();\n if (current_exposure == 0 && shared_image->num_exposures == 1) {\n filename = (format(\"%s.raw\") % shared_image->filename_base).str();\n }\n strncpy(header->filename, filename.c_str(), 63);\n header->filename[63] = '\\0';\n memcpy(header+1, shared_image->separate_buffers[current_exposure], data_size);\n logger->log(format(\"sending image %s\") % filename);\n boost::asio::async_write(socket, boost::asio::buffer(header, sizeof(ebex_images_header_t)+data_size),\n boost::bind(&ImageClient::handle_write, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));\n }\n}\n\nvoid ImageClient::handle_write(const boost::system::error_code& error, size_t bytes_transferred)\n{\n current_exposure++;\n boost::asio::async_read(socket, boost::asio::buffer(&read_buffer, sizeof(read_buffer)),\n boost::bind(&ImageClient::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));\n read_timer.expires_from_now(boost::posix_time::milliseconds(1000));\n read_timer.async_wait(boost::bind(&ImageClient::write_exposure, this));\n}\n\nvoid ImageClient::handle_read(const boost::system::error_code& error, size_t bytes_transferred)\n{\n string result_string = \"got async_read error\";\n if (!error) {\n if (read_buffer.result == ebex_images_result_success) {\n result_string = \"image stored successfully\";\n } else {\n result_string = (format(\"image storage error: %i\") % int(read_buffer.result)).str();\n }\n }\n logger->log(format(\"%s\") % result_string);\n read_timer.cancel();\n}\n\n" }, { "alpha_fraction": 0.6822115182876587, "alphanum_fraction": 0.7124999761581421, "avg_line_length": 23.47058868408203, "blob_id": "d384f29622b825379389f26234dd542be2eac201", "content_id": "3a8d2a1ca3ae3e487bac913d5eeedb56ff0c3532", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2080, "license_type": "no_license", "max_line_length": 78, "num_lines": 85, "path": "/stars/code/networking/ebex_images.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/**\n * @file ebex_images.h\n *\n * @date Aug 6, 2012\n * @author seth\n *\n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2011 Columbia University\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#ifndef EBEX_IMAGES_H_\n#define EBEX_IMAGES_H_\n#ifdef __cplusplus\nextern \"C\" {\n#else\n#include <stdbool.h>\n#endif\n#include <stdint.h>\n\n#define EBEX_IMAGES_PORT 33789\nstatic const uint32_t ebex_images_magic = 0xCDEDBD15;\nstatic const uint32_t ebex_images_max_packet_size = 12 * 1024 * 1024; /// 12MB\n\n#ifdef _MSC_VER\n#pragma pack(push, header_packing, 1)\n#endif\ntypedef struct\n{\n\tuint32_t \tmagic;\n\tuint32_t \tlength;\t\t\t///!< length of data in bytes exclusive of header\n\tchar\t\tfilename[64];\n\tuint8_t \tdata[];\n}\n#ifdef __GNUC__\n__attribute__((packed))\n#elif defined (_MSC_VER)\n#pragma pack(pop, header_packing)\n#endif\nebex_images_header_t;\n\n#ifdef _MSC_VER\n#pragma pack(push, result_packing, 1)\n#endif\ntypedef struct\n{\n\tint32_t\t\tresult;\n}\n#ifdef __GNUC__\n__attribute__((packed))\n#elif defined (_MSC_VER)\n#pragma pack(pop, result_packing)\n#endif\nebex_images_result_t;\n\ntypedef enum\n{\n\tebex_images_result_disk_error = -3,\n\tebex_images_result_out_of_memory = -2,\n\tebex_images_result_incompressible = -1,\n\tebex_images_result_success = 0\n} e_ebex_images_result;\n\nbool ebex_images_init_server(void);\nvoid ebex_images_shutdown_server(void);\n\n#ifdef __cplusplus\n}\n#endif\n#endif /* EBEX_IMAGES_H_ */\n" }, { "alpha_fraction": 0.5022371411323547, "alphanum_fraction": 0.536689043045044, "avg_line_length": 32.35820770263672, "blob_id": "fd0a5a457aa5f6561d2acdabd5325a6d5853caba", "content_id": "c7308f0454980c2edab5c4a663760d63c6c01f36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4470, "license_type": "no_license", "max_line_length": 112, "num_lines": 134, "path": "/test_programs/mpsse/test_biphase_old.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <sys/time.h>\n\n#include \"mpsse.h\"\n#include \"blast.h\"\n\n#define IFACE_A 0;\n#define IFACE_B 1;\n#define IFACE_C 2;\n#define IFACE_D 3;\n\nvoid send_biphase_writes();\nvoid send_bitbang_value();\n\nint main() \n{\n send_biphase_writes();\n}\n\n\nvoid send_biphase_writes() {\n\n\tstruct mpsse_ctx *ctx; \n\tconst uint16_t vid = 1027;\n\tconst uint16_t pid = 24593;\n\tconst char *serial = NULL;\n\tconst char *description = NULL;\n\t//int channel = IFACE_B;\n\tint channel = IFACE_A;\n\n\n\tctx = mpsse_open(&vid, &pid, description, serial, channel);\n\n if (false) {\n\n // Setting pins high and low manually \n\n uint8_t data = 0x00;\n uint8_t data_to_read = 0x00;\n uint8_t dir = 0xFF; // direction output for all bits\n // uint8_t dir = 0x00; // direction input for all bits\n while(true) { \n\n blast_dbg(\"== - Begin flushing - ==\");\n mpsse_flush(ctx);\n blast_dbg(\"== - Done flushing - ==\");\n data = 0xFF; // settings all bits to high\n blast_dbg(\"== Setting data high ==\");\n mpsse_set_data_bits_low_byte(ctx, data, dir);\n mpsse_set_data_bits_high_byte(ctx, data, dir);\n blast_dbg(\"== - Begin flushing - ==\");\n mpsse_flush(ctx);\n blast_dbg(\"== - Done flushing - ==\");\n mpsse_read_data_bits_high_byte(ctx, &data_to_read);\n blast_dbg(\"high pins read: %02x\", data_to_read);\n mpsse_read_data_bits_low_byte(ctx, &data_to_read);\n blast_dbg(\"low pins read: %02x\", data_to_read);\n usleep(1000000);\n data = 0x00; // setting all bits to low\n blast_dbg(\"== Setting data low ==\");\n mpsse_set_data_bits_low_byte(ctx, data, dir);\n mpsse_set_data_bits_high_byte(ctx, data, dir);\n blast_dbg(\"== - Begin flushing - ==\");\n mpsse_flush(ctx);\n blast_dbg(\"== - Done flushing - ==\");\n mpsse_read_data_bits_high_byte(ctx, &data_to_read);\n blast_dbg(\"high pins read: %02x\", data_to_read);\n mpsse_read_data_bits_low_byte(ctx, &data_to_read);\n blast_dbg(\"low pins read: %02x\", data_to_read);\n usleep(1000000);\n }\n\n } else {\n\n // Writing an array of data (0xABABABABAB...) through the bipase write functions\n\n uint16_t *data_to_write = NULL;\n //uint32_t bytes_to_write = 1535; //\n uint32_t bytes_to_write = 625; // That is the correct rate for code running at 100 Hz to write at 1 Mbps\n //uint32_t bytes_to_write = 32; \n //uint32_t bytes_to_write = 16000; //\n unsigned size_of_frame = bytes_to_write; //8192; // in bytes\n int frequency = 50000;\n int i = 0;\n struct timeval begin, end;\n\n\n uint8_t data = 0x00;\n uint8_t dir = 0xFF; // direction output for all bits\n //uint8_t dir = 0x00; // direction input for all bits\n\n mpsse_set_data_bits_low_byte(ctx, data, dir);\n mpsse_set_data_bits_high_byte(ctx, data, dir);\n data_to_write = malloc(size_of_frame); \n if (data_to_write) {\n for (int i = 0; i < ((int) size_of_frame/2); i++) {\n *(data_to_write+i) = 0xFFFF;\n }\n } else {\n mpsse_close(ctx); \n }\n\n //mpsse_rtck_config(ctx, false);\n mpsse_set_frequency(ctx, frequency);\n mpsse_flush(ctx);\n usleep(1000);\n\n //while(i <= 1) {\n while(true) {\n gettimeofday(&begin, NULL);\n blast_dbg(\"I am about to call mpsse_biphase_write_data, i=%d\", i);\n mpsse_biphase_write_data(ctx, data_to_write, bytes_to_write);\n //mpsse_clock_data_out(ctx, data_to_write, offset, bytes_to_write*8, NEG_EDGE_OUT | MSB_FIRST);\n blast_dbg(\"Flushing the buffer\");\n mpsse_flush(ctx);\n i += 1;\n //offset += bytes_to_write;\n //if (offset >= size_of_frame) {\n // offset = 0;\n // i = 0;\n //}\n //usleep(4096); //4096 to be exact, because it takes 4096 us to send 512 bytes at 1 Mb/s\n //usleep(10000); // should write 1.25 KB per 0.01 second at 1 MBps\n gettimeofday(&end, NULL);\n blast_dbg(\"It took %f second to run\", (end.tv_usec - begin.tv_usec)/1000000.0);\n } \n }\n if (ctx) {\n mpsse_close(ctx);\n }\n}\n" }, { "alpha_fraction": 0.5368068218231201, "alphanum_fraction": 0.5593990087509155, "avg_line_length": 30.79037857055664, "blob_id": "e2b3769df4990970c5543d31f1fcc15736fe60a5", "content_id": "3f7816780412e629d592739a24e5c5ddd6f6c5ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9252, "license_type": "no_license", "max_line_length": 128, "num_lines": 291, "path": "/stars/code/solving/refitting/shape_fitter.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"shape_fitter.h\"\n#include <levmar.h>\n#include <cmath>\n#include <cstdlib>\n#include \"../../shared/image/raw.h\"\n\n#include \"../../tools/quick_cout.h\"\n\nusing namespace Solving;\nusing namespace Solving::Refitting;\n\n\n/*\n#include \"../../shared/solving/settings.h\"\n\nusing std::min;\nusing std::max;\n\n#define shared_settings (*(Shared::Solving::settings.r))\n*/\n\n\nnamespace levmar_c_functions_shape\n{\n\nint max_num_blobs = 1;\n\nstruct gaussian_additional_data\n{\n int* us;\n int* vs;\n double* pedestals;\n unsigned int* which_blobs;\n};\n\n// params[0] = shared sigma\n// params[1] = blob0.A_un (un-normalized A)\n// params[2] = blob0.mu_u\n// params[3] = blob0.mu_v\n// params[4] = blob1.A\n// params[5] = blob1.mu_u\n// params[6] = blob1.mu_v\n// ...\n\nvoid gaussian(double* params, double* pixels, int num_params, int num_pixels, void* data)\n{\n gaussian_additional_data* additional_data = (gaussian_additional_data*) data;\n int* us = additional_data->us;\n int* vs = additional_data->vs;\n double* pedestals = additional_data->pedestals;\n unsigned int* which_blobs = additional_data->which_blobs;\n\n double sigma_sq = pow(params[0], 2.0);\n double mu_u = 0.0;\n double mu_v = 0.0;\n double A_un = 1.0;\n unsigned int which_blob = 0;\n for (int i=0; i<num_pixels; i++) {\n which_blob = which_blobs[i];\n A_un = params[which_blob*3+1];\n mu_u = params[which_blob*3+2];\n mu_v = params[which_blob*3+3];\n pixels[i] = A_un * exp(-(pow(us[i]-mu_u, 2.0) + pow(vs[i]-mu_v, 2.0)) / (2.0*sigma_sq));\n pixels[i] += pedestals[i];\n }\n}\n\n}\n\nShapeFitter::ShapeFitter()\n{\n max_num_blobs = levmar_c_functions_shape::max_num_blobs;\n int max_halfwidth = 30;\n max_num_pixels = (max_halfwidth*2+1)*(max_halfwidth*2+1)*max_num_blobs;\n pixels = new double[max_num_pixels];\n us = new int[max_num_pixels];\n vs = new int[max_num_pixels];\n pedestals = new double[max_num_pixels];\n which_blobs = new unsigned int[max_num_pixels];\n\n int max_num_params = 3*max_num_blobs+1;\n workspace = (double *) malloc((LM_DIF_WORKSZ(max_num_params, max_num_pixels)+max_num_params*max_num_params)*sizeof(double));\n covar = workspace + LM_DIF_WORKSZ(max_num_params, max_num_pixels);\n}\n\nShapeFitter::~ShapeFitter()\n{\n delete [] pixels;\n delete [] us;\n delete [] vs;\n delete [] pedestals;\n delete [] which_blobs;\n free(workspace);\n}\n\ndouble ShapeFitter::get_covar(int num_params, int param)\n{\n if (param > num_params) {\n return 0.0;\n }\n return sqrt(covar[param*num_params+param]);\n}\n\nvoid ShapeFitter::fit_gaussian(Shared::Image::Raw& image, std::vector<Blob>& blobs)\n{\n int halfwidth = 10;\n int pixel_i = 0;\n int blob_i = 0;\n unsigned int* original_blob_indices = new unsigned int[max_num_blobs];\n for (unsigned int i = 0; i < blobs.size() && blob_i < max_num_blobs; i++) {\n //if (blob has a good enough snr) {\n if (true) {\n int blob_u = blobs[i].u;\n int blob_v = blobs[i].v;\n for (int u = blob_u-halfwidth; u <= blob_u+halfwidth; u++) {\n for (int v = blob_v-halfwidth; v <= blob_v+halfwidth; v++) {\n if (pixel_i < max_num_pixels && image.is_inbounds(u, v)) {\n pixels[pixel_i] = double(image.get_pixel(u, v));\n us[pixel_i] = u;\n vs[pixel_i] = v;\n pedestals[pixel_i] = 0.0;\n pedestals[pixel_i] += blobs[i].pedestal_params[0]*double(u);\n pedestals[pixel_i] += blobs[i].pedestal_params[1]*double(v);\n pedestals[pixel_i] += blobs[i].pedestal_params[2];\n\n\n pedestals[pixel_i] = 0.8;\n\n\n which_blobs[pixel_i] = blob_i;\n pixel_i++;\n }\n }\n }\n original_blob_indices[blob_i] = i;\n blob_i++;\n }\n }\n int num_pixels = pixel_i;\n int num_blobs = blob_i;\n levmar_c_functions_shape::gaussian_additional_data additional_data;\n additional_data.us = us;\n additional_data.vs = vs;\n additional_data.pedestals = pedestals;\n additional_data.which_blobs = which_blobs;\n\n int num_params = 3*num_blobs+1;\n double* params = new double[num_params];\n params[0] = 2.5;\n for (int blob_i=0; blob_i<num_blobs; blob_i++) {\n params[3*blob_i+1] = blobs[original_blob_indices[blob_i]].flux;\n params[3*blob_i+2] = double(blobs[original_blob_indices[blob_i]].u);\n params[3*blob_i+3] = double(blobs[original_blob_indices[blob_i]].v);\n }\n\n dlevmar_dif(levmar_c_functions_shape::gaussian, params, pixels, num_params, num_pixels,\n 1000, NULL, NULL, workspace, covar, (void*) &additional_data);\n\n/*\n for (int i=0; i<num_params*num_params; i++) {\n cout << \"covar[\" << i << \"] \" << covar[i] << endl;\n }\n*/\n\n /*\n cout << \"shape gives shared_sigma \" << params[0];\n cout << \" +/- \" << get_covar(num_params, 0) << endl;\n for (int blob_i=0; blob_i<num_blobs; blob_i++) {\n cout << \"blob fit with A \" << params[3*blob_i+1];\n cout << \" +/- \" << get_covar(num_params, 3*blob_i+1) << \" \";\n cout << \" and u,v \" << params[3*blob_i+2] << \" \" << params[3*blob_i+3];\n cout << \" (errors) \";\n cout << get_covar(num_params, 3*blob_i+2) << \" \";\n cout << get_covar(num_params, 3*blob_i+3) << endl;\n }\n */\n\n\n delete [] params;\n delete [] original_blob_indices;\n}\n\n/*\n\nvoid Fitter::fit_gaussian(Shared::Image::Raw& image, Blob& blob)\n{\n\n int num_params = 5;\n double* params = new double[num_params];\n params[0] = blob.flux; // A / sqrt(2*pi*sigma*sigma)\n params[1] = double(blob.u); // mu_x\n params[2] = double(blob.v); // mu_y\n params[3] = 3.0; // sigma\n params[4] = 0; // base\n\n dlevmar_dif(levmar_c_functions::gaussian, params, pixels, num_params, num_pixels,\n 100, NULL, NULL, workspace, covar, (void*) &additional_data);\n\n blob.x = params[1] - (double(image.width)-1.0)/2.0;\n blob.y = params[2] - (double(image.height)-1.0)/2.0;\n blob.sigma_x = params[3];\n blob.fit_error_x = sqrt(covar[1*num_params+1]);\n blob.fit_error_y = sqrt(covar[2*num_params+2]);\n\n delete [] params;\n}\n\nvoid Fitter::fit_double_gaussian(Shared::Image::Raw& image, Blob& blob)\n{\n int halfwidth = 10;\n int i = 0;\n for (int u = blob.u-halfwidth; u <= blob.u+halfwidth; u++) {\n for (int v = blob.v-halfwidth; v <= blob.v+halfwidth; v++) {\n if (i < max_num_pixels && image.is_inbounds(u, v)) {\n pixels[i] = double(image.get_pixel(u, v));\n us[i] = u;\n vs[i] = v;\n i++;\n }\n }\n }\n int num_pixels = i;\n levmar_c_functions::gaussian_additional_data additional_data;\n additional_data.us = us;\n additional_data.vs = vs;\n\n int num_params = 9;\n double* params = new double[num_params];\n params[0] = blob.flux; // A1 / sqrt(2*pi*sigma1*sigma1)\n params[1] = double(blob.u); // mu1_x\n params[2] = double(blob.v); // mu1_y\n params[3] = 3.0; // sigma1\n params[4] = blob.flux/5.0; // A2 / sqrt(2*pi*sigma2*sigma2)\n params[5] = double(blob.u+5); // mu2_x\n params[6] = double(blob.v+0); // mu2_y\n params[7] = 3.0; // sigma2\n params[8] = 0; // base\n\n dlevmar_dif(levmar_c_functions::double_gaussian, params, pixels, num_params, num_pixels,\n 30, NULL, NULL, workspace, covar, (void*) &additional_data);\n\n if (params[0] >= params[4]) {\n blob.x = params[1] - (double(image.width)-1.0)/2.0;\n blob.y = params[2] - (double(image.height)-1.0)/2.0;\n blob.sigma_x = params[3];\n } else {\n blob.x = params[5] - (double(image.width)-1.0)/2.0;\n blob.y = params[6] - (double(image.height)-1.0)/2.0;\n blob.sigma_x = params[7];\n }\n\n delete [] params;\n}\n\nBlob Fitter::fit(Shared::Image::Raw& image, Blob& blob)\n{\n using namespace Shared::Solving;\n double original_x = double(blob.u) - (double(image.width)-1.0)/2.0;\n double original_y = double(blob.v) - (double(image.height)-1.0)/2.0;\n switch (shared_settings.fitting_method) {\n\n case Settings::fitting_gaussian:\n fit_gaussian(image, blob);\n break;\n\n case Settings::fitting_double_gaussian:\n fit_double_gaussian(image, blob);\n break;\n\n case Settings::fitting_none:\n default:\n blob.x = double(blob.u) - (double(image.width)-1.0)/2.0;\n blob.y = double(blob.v) - (double(image.height)-1.0)/2.0;\n break;\n\n }\n double distance_moved_squared = pow(original_x - blob.x, 2.0) + pow(original_y - blob.y, 2.0);\n if (distance_moved_squared < 20*20 && image.is_xy_inbounds(blob.x, blob.y)) {\n blob.fit_was_good = true;\n } else {\n blob.fit_was_good = false;\n }\n return blob;\n}\n*/\n" }, { "alpha_fraction": 0.6616541147232056, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 12.199999809265137, "blob_id": "d43f0d345d1596ab5d1f67c42efc05e8b88d1429", "content_id": "a92bdae470a0644841b284b6264ea13792a20e17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 133, "license_type": "no_license", "max_line_length": 36, "num_lines": 10, "path": "/katie/Makefile", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "all: katie\n\nkatie: katie.c\n\tgcc -Wall -g -o katie katie.c\n\ninstall: katie\n\tinstall -m 755 katie /usr/local/bin\n\nclean:\n\trm -f katie\n\n" }, { "alpha_fraction": 0.6487528085708618, "alphanum_fraction": 0.6630918383598328, "avg_line_length": 32.30158615112305, "blob_id": "e9063a0d572201601998d38225fd40586e3f13c5", "content_id": "aa52d29d42d9670c956bdc2ca5ebb301e5a8d970", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 25176, "license_type": "no_license", "max_line_length": 136, "num_lines": 756, "path": "/starcam/mycam.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//\n// C++ Implementation: mycam\n//\n// Description: \n//\n//\n// Author: Steve Benton <[email protected]>, (C) 2006\n//\n// Copyright: See COPYING file that comes with this distribution\n//\n//\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <time.h>\n#include <unistd.h>\n#include <sys/time.h>\n#include \"mycam.h\"\n#include \"sbigudrv.h\"\n#include \"csbigcam.h\"\n#include \"clensadapter.h\"\n#include \"blobimage.h\"\n#include \"focusstruct.h\"\n#include \"camcommunicator.h\"\n\nextern \"C\" {\n#include \"udp.h\"\n}\n\n#define MYCAM_DEBUG 0\n#define MYCAM_TIMING 0\n#define AUTOFOCUS_DEBUG 1\n\n//minimum step size in autofocus, only used when suspect stickiness\n#define MIN_AUTO_STEP 10\n\nint copyFlag = 0;\n\nusing namespace std;\n//use same constructors as CSBIGCam, make sure proper Init is called though.\nMyCam::MyCam() : CSBIGCam() { Init(); }\nMyCam::MyCam(OpenDeviceParams odp) : CSBIGCam(odp) { Init(); }\nMyCam::MyCam(SBIG_DEVICE_TYPE dev) : CSBIGCam(dev) { Init(); }\n\n\n//perform same operations as the CSBIGCam destructor\nMyCam::~MyCam()\n{\n\tCloseDevice();\n\tCloseDriver();\n\tm_cAdapter.closeConnection();\n}\n\n/*\n \n Init:\n\t \n Initialize the base variables. Most of this is done my parent class.\n \n*/\nvoid MyCam::Init(MyCamConfigParams params/*=defaultCameraParams*/)\n{\n\tCSBIGCam::Init(params.SBIGParams);\n\tm_cAdapter.Init(params.lensParams);\n\tm_nUSBNum = params.USBNum;\n\tm_nPictureInterval = params.pictureInterval;\n\tm_nFocusResolution = params.focusResolution;\n\tm_nFocusRange = params.focusRange;\n\tm_iFrame = 0;\n}\n/* original version has been replaced\nvoid MyCam::Init()\n{\n\tCSBIGCam::Init();\n\tm_nUSBNum = INVALID_USB_NUM;\n\tm_dPictureInterval = 0;\n}\n*/\n\n/*\n\n QueryUSB:\n\n Runs the CC_QUERY_USB command against the universal driver\n \n*/\nPAR_ERROR MyCam::QueryUSB(QueryUSBResults &qur)\n{\n\treturn CSBIGCam::SBIGUnivDrvCommand(CC_QUERY_USB, NULL, &qur);\n}\n\n/*\n\n OpenUSBDevice:\n \n Opens a device on USB with \"port\" number num.\n Num should be the index of a QueryUSBResults.usbInfo with cameraFound == TRUE\n \n*/\nPAR_ERROR MyCam::OpenUSBDevice(int num)\n{\n\tOpenDeviceParams odp;\n\tm_nUSBNum = (num < 0 || num > 3)?INVALID_USB_NUM:num;\n\tswitch (num) {\n\t\tcase 0:\t\todp.deviceType=DEV_USB1; break;\n\t\tcase 1:\t\todp.deviceType=DEV_USB2; break;\n\t\tcase 2:\t\todp.deviceType=DEV_USB3; break;\n\t\tcase 3:\t\todp.deviceType=DEV_USB4; break;\n\t\tdefault:\todp.deviceType=DEV_NONE; break;\n\t}\n\treturn CSBIGCam::SBIGUnivDrvCommand(CC_OPEN_DEVICE, &odp, NULL);\n}\n\n/*\n\n autoFocus:\n \n enter a focus mode that maximizes flux of brightest star in FOV\n steps down from focus at infinity in steps of (total range / m_nFocusResolution)\n a BlobImage is passed to avoid time consuming initialization of a new one\n will stop after decreasing for 3 consecutive measurements, or no longer identifying blob\n when forced is non-zero (TRUE), stops will be ignored until moving is impossible\n path is the location of files used by image viewer\n //TODO can add sub-step interpolation of maximum\n \n*/\n//LENS_ERROR MyCam::autoFocus(BlobImage *img, int forced/*=0*/, const char* path/*=NULL*/)\nLENS_ERROR MyCam::autoFocus(BlobImage *img, int forced/*=0*/, string path)\n{\n\tframeblob *blob = img->getFrameBlob();\n\tStarcamReturn returnStruct;\n bloblist* focblobs;\n\tif (!forced) //can actually measure focal range\n\t\tif (m_cAdapter.findFocalRange() != LE_NO_ERROR) return m_cAdapter.getLastError();\n\tint range = (forced)?3270:m_cAdapter.getFocalRange();\n\tint step = range / m_nFocusResolution; //number of motor counts between measurements\n\tint numsteps = m_nFocusResolution/m_nFocusRange; \n\tfocusStruct focuser[numsteps];\n\t//check if motor \"stickiness\" may have confused things\n\tif (forced && step < MIN_AUTO_STEP) step = MIN_AUTO_STEP;\n#if AUTOFOCUS_DEBUG\n\tcout << \"[autoFocus debug]: range=\" << range <<\" res=\" << m_nFocusResolution << \"step=\" << step << endl;\n#endif\n\tint remaining = 0;\t//distance remainder returned from preciseMove\n\tint toInf = 0;\n\tint endpos = 0;\n\tint j=0;\n\t//focusing stuff:\n\tint m=1,n=0,o=0,p=0;\n\tint atfocus=0;\n\tint nblobhere = 0;\n\tint nblobplus = 0;\n\tint nblobminus = 0;\n\tdouble xhere = 0;\n\tdouble xplus = 0;\n\tdouble xminus = 0;\n\tdouble yhere = 0;\n\tdouble yplus = 0;\n\tdouble yminus = 0;\n\tint maxflux = 0;\n\n int sock;\n sock = udp_bind_port(FOCUS_PORT,1);\n if (sock == -1)\n cout << \"unable to bind to port\" << endl;\n string rtn_str = \"\";\n\tstring sought = \"\\n\";\n\n\tfor (int i=0; i < numsteps; i++) {\n//#if AUTOFOCUS_DEBUG\n//\t\tcout << \"[autoFocus debug]: taking exposure\" << endl;\n//#endif\n\t\tif (this->GrabImage(img, SBDF_LIGHT_ONLY) != CE_NO_ERROR) {\n#if AUTOFOCUS_DEBUG\n\t\t\tcout << \"[autoFocus debug]: grabImage failed in autoFocus\" << endl;\n#endif\n\t\t\treturn LE_AUTOFOCUS_ERROR;\n\t\t}\n\n\t\timg->findBlobs();\n\t\tfocuser[i].numblobs = (blob->get_numblobs() > 15)?15:blob->get_numblobs();\n\n#if AUTOFOCUS_DEBUG\n\t\tcout << \"autofocus: Found \" << blob->get_numblobs() << \" blobs\" << endl;\n#endif\n \t\tif (blob->get_numblobs()) {\n\t\t\tfocblobs = blob->getblobs();\n\t\t\twhile ((focblobs != NULL) && (j<15)) { //keep 15 blobs per images in focusStruct\n#if AUTOFOCUS_DEBUG\n\t\t\t\tcout << \"autofocus: ...\" << focblobs->getx() << \" \" << focblobs->gety() << \" \" << focblobs->getflux() << endl;\n#endif\n\t\t\t\tfocuser[i].flux[j] = focblobs->getflux();\n\t\t\t\tfocuser[i].x[j] = focblobs->getx();\n\t\t\t\tfocuser[i].y[j] = focblobs->gety();\n\t\t\t\timg->drawBox(focblobs->getx(), focblobs->gety(), 40, j+1);\n\t\t\t\tfocblobs = focblobs->getnextblob();\n\t\t\t\tj++;\n\t\t\t}\n\t\tj=0;\n\t\t}\n\n#if AUTOFOCUS_DEBUG\n\t\tcout << \"[autoFocus debug]: saving focus image in : \" << path << endl;\n#endif\n\t\tif (img->SaveImageIn(path) != SBFE_NO_ERROR) {\n#if AUTOFOCUS_DEBUG\n\t\t cerr << \"[autoFocus debug]: autoFocus failed to save image\" << endl;\n#endif\n\t\t}\n\t\tif (img->SaveImage(\"/data/etc/tmp_bad.sbig\") != SBFE_NO_ERROR) {\n#if AUTOFOCUS_DEBUG\n\t\t cerr << \"[autoFocus debug]: autoFocus failed to save viewer image\" << endl;\n#endif\n\t\t}\n copyFlag = 1;\n\t\timg->createReturnStruct(&returnStruct);\n rtn_str = CamCommunicator::buildReturn(&returnStruct);\n //remove all newlines and add a single one at the end\n\t string::size_type pos = rtn_str.find(sought, 0);\n\t while (pos != string::npos) {\n rtn_str.replace(pos, sought.size(), \"\");\n pos = rtn_str.find(sought, pos - sought.size());\n }\n rtn_str += \"\\n\";\n udp_bcast(sock, SC_PORT, strlen(rtn_str.c_str()), rtn_str.c_str(), 0);\n cout << \"AUTOFOCUS BROADCASTING string \" << rtn_str << endl;\n\n\t\tfocuser[i].focpos = toInf;\n\t\t//move to next location\n\t\tif (m_cAdapter.preciseMove(-step, remaining, forced) != LE_NO_ERROR)\n\t\t\treturn m_cAdapter.getLastError();\n\n\t\ttoInf += step + remaining;\n\t\tif (i==(numsteps-1)) endpos = toInf;\n\t}\n close(sock);\n\n\twhile (m<(numsteps-1)) { //loop over all images\n\t\tnblobhere = focuser[m].numblobs;\n\t\tnblobplus = focuser[m+1].numblobs; //#blobs in next img\n\t\tnblobminus = focuser[m-1].numblobs;//#blobs in prev img\n\t\twhile (n<nblobhere) { //loop over all blobs in this image\n\t\t\txhere = focuser[m].x[n];\n\t\t\tyhere = focuser[m].y[n];\n\t\t\twhile (o<nblobplus) { //loop over all blobs in next image\n\t\t\t\txplus = focuser[m+1].x[o];\n\t\t \t\typlus = focuser[m+1].y[o];\n\t\t\t\tif ((abs(xplus-xhere) < 20) && (abs(yplus-yhere) < 20)) { \n\t\t\t\t\t//if meets test in next image, check prev image:\n\t\t\t\t\twhile (p<nblobminus) { //loop over all blobs in prev image\t\n\t\t\t\t\t\txminus = focuser[m-1].x[p];\n\t\t\t\t\t\tyminus = focuser[m-1].y[p];\n\t\t \t\t\t\tif ((abs(xminus-xhere) < 20) && (abs(yminus-yhere) < 20)) {\n\t\t\t\t\t\t\tif ((focuser[m].flux[n] > focuser[m+1].flux[o]) &&\n\t\t\t\t\t\t\t (focuser[m].flux[n] > focuser[m-1].flux[p])) {\n\t\t\t\t\t\t\t\tif ((focuser[m].flux[n]) > maxflux) {\n\t\t\t\t\t\t\t\t\tmaxflux = focuser[m].flux[n];\n\t\t\t\t\t\t\t\t\tatfocus = m;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tp++;//go to next blob in prev image \n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\to++;//go to next blob in next image \n\t\t\t}\n\t\t\to=0;\n\t\t\tp=0;\n\t\t\tn++;//go to next blob in this image...\t\n\t\t}\n\t\tn=0;\n\t\tm++;//go to next image...\t\t\n\t}\t\n#if AUTOFOCUS_DEBUG\n\tcerr << \"maxflux = \" << maxflux << \", focus position = \" << focuser[atfocus].focpos << endl;\n#endif\n\t//move back to focus position\n\tint toFocus = endpos - focuser[atfocus].focpos;\n#if AUTOFOCUS_DEBUG\n\tcerr << \"at endpos: \" << endpos << \", need to move \" << toFocus << \" steps toFocus (=endpos-focpos)\" << endl;\n#endif\n\tif (m_cAdapter.preciseMove(toFocus, remaining, forced) != LE_NO_ERROR)\n\t\treturn m_cAdapter.getLastError();\n\treturn LE_NO_ERROR;\n\n}\n\n//Original autofocus function: needlessly complicated\n// LENS_ERROR MyCam::autoFocus()\n// {\n// \tif (m_cAdapter.getFocalRange() == -1) //if focal range isn't defined yet, find it\n// \t\tif (m_cAdapter.findFocalRange() != LE_NO_ERROR) \n// \t\t\treturn m_cAdapter.getLastError();\n// \t\n// \tint totalRange = m_cAdapter.getFocalRange();\n// \tint step_size = totalRange / 16; //initial size of focus steps\n// \tint move; //amount to move by (to improve focus)\n// \tint position = totalRange - step_size; //position of the lens center spot\n// \tint offset = 0; //position of lens relative to center sopt\n// \tint remaining; //return value for preciseMove\n// \tstring return_str; //return value from lens commands\n// \tBlobImage img;\n// \tframeblob *blob = img.getFrameBlob();\n// \tint smaller, center, larger; //blob flux at three focus positions\n// \t\n// \t//move lens to initial center position\n// \tif (m_cAdapter.runCommand(LC_MOVE_FOCUS_INFINITY, return_str) != LE_NO_ERROR)\n// \t\treturn m_cAdapter.getLastError();\n// \tif (m_cAdapter.preciseMove(-step_size, remaining) != LE_NO_ERROR)\n// \t\treturn m_cAdapter.getLastError();\n// \toffset -= remaining;\n// \t\n// \tfor (int i=0; i<10; i++) { //limit the number of iterations\n// \t\t//find intensity of brightest blob at center position\n// \t\tif ( (this->GrabImage(&img, SBDF_LIGHT_ONLY)) != CE_NO_ERROR )\n// \t\t\treturn LE_AUTOFOCUS_ERROR;\n// \t\timg.findBlobs();\n// \t\tif (blob->get_numblobs())\n// \t\t\tcenter = blob->getblobs()->getflux(); //flux of brightest blob\n// \t\telse\n// \t\t\tcenter = -1;\n// \t\t\n// \t\t//find intensity of brightest blob at smaller (closer to zero) position\n// \t\tif (m_cAdapter.preciseMove(-step_size, remaining) != LE_NO_ERROR)\n// \t\t\treturn m_cAdapter.getLastError();\n// \t\toffset += -step_size - remaining;\n// \t\tif ( (this->GrabImage(&img, SBDF_LIGHT_ONLY)) != CE_NO_ERROR )\n// \t\t\treturn LE_AUTOFOCUS_ERROR;\n// \t\timg.findBlobs();\n// \t\tif (blob->get_numblobs())\n// \t\t\tsmaller = blob->getblobs()->getflux();\n// \t\telse\n// \t\t\tsmaller = -1;\n// \n// \t\t//find intensity of brightest blob at larger (closer to infinity) position\n// \t\tif (m_cAdapter.preciseMove(2*step_size, remaining) != LE_NO_ERROR)\n// \t\t\treturn m_cAdapter.getLastError();\n// \t\toffset += 2*step_size - remaining;\n// \t\tif ( (this->GrabImage(&img, SBDF_LIGHT_ONLY)) != CE_NO_ERROR )\n// \t\t\treturn LE_AUTOFOCUS_ERROR;\n// \t\timg.findBlobs();\n// \t\tif (blob->get_numblobs())\n// \t\t\tlarger = blob->getblobs()->getflux();\n// \t\telse\n// \t\t\tlarger = -1;\n// \t\t\n// \t\t//find how far to move (relative to center) the lens to improve focus\n// \t\t//first check cases where blobs were not found in all the images\n// \t\tif (center == -1) {\n// \t\t\tif (smaller == -1 && larger == -1) //no blobs were found anywhere\n// \t\t\t\tmove = step_size;\n// \t\t\telse move = (smaller >= larger)?-step_size:step_size;\n// \t\t} \n// \t\telse { //blob found at center\n// \t\t\tif (smaller == -1 && larger == -1) {\n// \t\t\t\tstep_size /= 2;\n// \t\t\t\tmove = 0;\n// \t\t\t}\n// \t\t\telse if (smaller == -1 || larger == -1) \n// \t\t\t\tmove = (smaller == -1)?step_size:-step_size;\n// \t\t\telse { //blobs were found at each position (assume they are the same ones)\n// \t\t\t\t//check concavity of flux profile\n// \t\t\t\tif (2*center > smaller + larger) {\n// \t\t\t\t\t//concave down...use quadratic interpolation\n// \t\t\t\t\tmove = (smaller - larger)/2/(smaller + larger - 2*center) * step_size;\n// \t\t\t\t\tstep_size /= 2;\n// \t\t\t\t}\n// \t\t\t\t//otherwise move toward the largest of the sides\n// \t\t\t\telse move = (smaller >= larger)?-step_size:step_size;\n// \t\t\t}\n// \t\t}\n// \t\twhile (position + move - totalRange > (int)m_cAdapter.getFocusTol()\n// \t\t\t\t\t || position + move < (int)m_cAdapter.getFocusTol())\n// \t\t{ //if position + move exceeds top or bottom of range, only go half as far \n// \t\t\tmove /= 2;\n// \t\t\tstep_size /= 2;\n// \t\t}\n// \t\tm_cAdapter.preciseMove(move-offset, remaining);\n// \t\toffset = move - remaining;\n// \t}\n// \t\n// \treturn LE_NO_ERROR;\n// }\n\n/*\n \n hex2double:\n\t \n Convert the passed hex value to double.\n The hex value is assumed to be in the\n format: XXXXXX.XX\n\t \n*/\nstatic double hex2double(unsigned long ul)\n{\n\tdouble res, mult;\n\tint i;\n\t\n\tres = 0.0;\n\tmult = 1.0;\n\tfor (i=0; i<8; i++)\n\t{\n\t\tres += mult * (double)(ul & 0x0F);\n\t\tul >>= 4;\n\t\tmult *= 10.0;\n\t}\n\treturn res / 100.0;\n\t\n}\n\n\n/*\n\n GrabImage:\n \n Overrides the CSBIGCam function to use BlobImage and provide better header information\n Note: Could get lens information from adapter, but that seems unnecessary unless\n the aperture will be changing in flight. Otherwise setting correct default is sufficient.\n \n*/\nPAR_ERROR MyCam::GrabImage(BlobImage *pImg, SBIG_DARK_FRAME dark)\n{\n#if MYCAM_DEBUG\n\tcout << \"[MyCam debug]: inside GrabImage.\" << endl;\n#endif\t\n\ttimeval reference; //used for exposure time, not just debugging\n#if MYCAM_TIMING\n\ttimeval reference2, grabstart, grabstop; //structs for retrieving time information\n\tunsigned int elapsed; //used to hold time in us between timevals\n\tgettimeofday(&grabstart, NULL);\n\tgettimeofday(&reference, NULL);\n\tdouble expTime, readTime, totalTime;\n#endif\n\tint left, top, width, height;\n\tGetCCDInfoResults0 gcir;\n\tGetCCDInfoParams gcip;\n\tdouble ccdTemp;\n\tdouble foclen;\n\tstring lens_ret_str, foc_str;\n\tdouble focpos;\n\tunsigned short vertNBinning, hBin, vBin;\n\tunsigned short rm;\n\tstring s;\n\tunsigned short es;\n\tMY_LOGICAL expComp;\n\tPAR_ERROR err;\n\tStartReadoutParams srp;\n\tint i;\n\tReadoutLineParams rlp;\n\tint subFrameWidth, subFrameHeight, subFrameTop, subFrameLeft;\n\tCSBIGCam::GetSubFrame(subFrameLeft, subFrameTop, subFrameWidth, subFrameHeight);\n\t//NNG CSBIGCam::SetDriverControl(DCP_HIGH_THROUGHPUT, TRUE);\n\t// Get the image dimensions\n\tvertNBinning = CSBIGCam::GetReadoutMode() >> 8;\n\tif ( vertNBinning == 0 )\n\t\tvertNBinning = 1;\n\trm = CSBIGCam::GetReadoutMode() & 0xFF;\n\thBin = vBin = 1;\n\tif ( rm < 3 )\n\t\thBin = vBin = (rm + 1);\n\telse if ( rm < 6 ) {\n\t\thBin = (rm - 5);\n\t\tvBin = vertNBinning;\n\t} else if ( rm < 9 )\n\t\thBin = vBin = (rm - 8);\n\telse if ( rm == 9 )\n\t\thBin = vBin = 9;\n\tgcip.request = (CSBIGCam::GetActiveCCD() == CCD_IMAGING ? CCD_INFO_IMAGING : CCD_INFO_TRACKING);\n\tif ( SBIGUnivDrvCommand(CC_GET_CCD_INFO, &gcip, &gcir) != CE_NO_ERROR )\n\t\treturn CSBIGCam::GetError();\n\tif ( rm >= gcir.readoutModes )\n\t\treturn CE_BAD_PARAMETER;\n\tif ( subFrameWidth == 0 || subFrameHeight == 0 ) {\n\t\tleft = top = 0;\n\t\twidth = gcir.readoutInfo[rm].width;\n\t\theight = gcir.readoutInfo[rm].height / vertNBinning;\n\t} else {\n\t\tleft = subFrameLeft;\n\t\ttop = subFrameTop;\n\t\twidth = subFrameWidth;\n\t\theight = subFrameHeight;\n\t}\n\n\t// try to allocate the image buffer\n\tif ( !pImg->AllocateImageBuffer(height, width) )\n\t\treturn CE_MEMORY_ERROR;\n\tpImg->SetImageModified(TRUE); //used by csbigimg in refrence to saving, not viewing\n\n\t// initialize some image header params\n\tif ( CSBIGCam::GetCCDTemperature(ccdTemp) != CE_NO_ERROR )\n\t\treturn CSBIGCam::GetError();\n\tpImg->setCameraID(this->getSerialNum());\n\tpImg->setFrameNum(m_iFrame++);\n\tpImg->SetCCDTemperature(ccdTemp);\n\t//command returns: \"xxxmm,f28\", where xxx=foclen\n\tif ((m_cAdapter.runCommand(LC_IDENTIFY_LENS, lens_ret_str)) == LE_NO_ERROR){\n\t\tfoc_str = lens_ret_str.substr(0,3);\n\t\tfoclen = atof(foc_str.c_str());\n\t\tpImg->SetFocalLength(foclen);\n\t}\n\tif ((m_cAdapter.runCommand(LC_GET_FOCUS_POSITION, lens_ret_str)) == LE_NO_ERROR){\n\t\tfocpos = atof(lens_ret_str.c_str());\n\t\tpImg->SetApertureArea(focpos); // change header to put focus position where \"Aperture\" used to be\n\t}\n\tpImg->SetEachExposure(CSBIGCam::GetExposureTime());\n\tpImg->SetEGain(hex2double(gcir.readoutInfo[rm].gain));\n\tpImg->SetPixelHeight(hex2double(gcir.readoutInfo[rm].pixelHeight) * vertNBinning / 1000.0);\n\tpImg->SetPixelWidth(hex2double(gcir.readoutInfo[rm].pixelWidth) / 1000.0);\n\tes = ES_DCS_ENABLED | ES_DCR_DISABLED | ES_AUTOBIAS_ENABLED;\n\tif ( CSBIGCam::GetCameraType() == ST5C_CAMERA )\n\t\tes |= (ES_ABG_CLOCKED | ES_ABG_RATE_MED);\n\telse if ( CSBIGCam::GetCameraType() == ST237_CAMERA )\n\t\tes |= (ES_ABG_CLOCKED | ES_ABG_RATE_FIXED);\n\telse if ( CSBIGCam::GetActiveCCD() == CCD_TRACKING )\n\t\tes |= (ES_ABG_CLOCKED | ES_ABG_RATE_MED);\n\telse\n\t\tes |= ES_ABG_LOW;\n\tpImg->SetExposureState(es);\n\tpImg->SetExposureTime(CSBIGCam::GetExposureTime());\n\tpImg->SetNumberExposures(1);\n\tpImg->SetReadoutMode(CSBIGCam::GetReadoutMode());\n\ts = GetCameraTypeString();\n\tif ( CSBIGCam::GetCameraType() == ST5C_CAMERA || ( CSBIGCam::GetCameraType() == ST237_CAMERA && s.find(\"ST-237A\", 0) == string::npos) )\n\t\tpImg->SetSaturationLevel(4095);\n\telse\n\t\tpImg->SetSaturationLevel(65535);\n\ts = gcir.name;\n\t//add identifier to camera name (distinguish two cameras)\n\tostringstream sout;\n\tstring IDNum = pImg->getCameraID();\n\t//NNG sout << s << \" #\" << m_nUSBNum;\n\tsout << s << \" #\" << IDNum;\n\tpImg->SetCameraModel(sout.str());\n\tpImg->SetBinning(hBin, vBin);\n\tpImg->SetSubFrame(left, top);\n\t\n\t// end any exposure in case one in progress\n\tCSBIGCam::EndExposure();\n\tif ( CSBIGCam::GetError() != CE_NO_ERROR && CSBIGCam::GetError() != CE_NO_EXPOSURE_IN_PROGRESS )\n\t\treturn CSBIGCam::GetError();\n\t\n\t// start the exposure\n#if MYCAM_DEBUG\n\tcout << \"[MyCam debug]: starting 1st exposure (may not be a 2nd).\" << endl;\n#endif\t\n#if MYCAM_TIMING\n\tgettimeofday(&reference2, NULL);\n\telapsed = (reference2.tv_sec - reference.tv_sec)*1000000 + reference2.tv_usec - reference.tv_usec;\n\tcout << \"[MyCam timing]: time for all steps up to exposure: \" << elapsed/1000.0 << \"ms\" << endl;\n#endif\n\tgettimeofday(&reference, NULL); //find a reference time before exposure, not part of debugging\n\tif ( CSBIGCam::StartExposure(dark == SBDF_LIGHT_ONLY ? SC_OPEN_SHUTTER : SC_CLOSE_SHUTTER) != CE_NO_ERROR )\n\t\treturn CSBIGCam::GetError();\n\t//it turns out this command will typically be ~300ms after reference is taken\n\tpImg->SetImageStartTime(&reference);\n\n\t// wait for exposure to complete (sleep for most of the time, allow 5ms leeway)\n// #if MYCAM_DEBUG\n// \tcout << \"[MyCam debug]: waiting for exposure, sleeping for: \" \n// \t\t << (int)(CSBIGCam::GetExposureTime()*1000000 - 25000)/1000.0 << \"ms\" << endl;\n// #endif\t\n// \tusleep((int)(CSBIGCam::GetExposureTime()*1000000) - 25000); //sleep for 10ms less than exposure time\n\tdo {\n\t} while ((err = CSBIGCam::IsExposureComplete(expComp)) == CE_NO_ERROR && !expComp ); //spend remainder of exposure testing for end\n\tCSBIGCam::EndExposure();\n\tif ( err != CE_NO_ERROR )\n\t\treturn err;\n\tif ( CSBIGCam::GetError() != CE_NO_ERROR )\n\t\treturn CSBIGCam::GetError();\n#if MYCAM_TIMING\n\tgettimeofday(&reference2, NULL);\n\telapsed = (reference2.tv_sec - reference.tv_sec)*1000000 + reference2.tv_usec - reference.tv_usec;\n\tcout << \"[MyCam timing]: time for exposure: \" << elapsed/1000.0 << \"ms\" << endl;\n\texpTime = elapsed/1000.0;\n\tgettimeofday(&reference, NULL); //reset reference time\n#endif\n\t\n\t// readout the CCD\n\tsrp.ccd = CSBIGCam::GetActiveCCD();\n\tsrp.left = left;\n\tsrp.top = top;\n\tsrp.height = height;\n\tsrp.width = width;\n\tsrp.readoutMode = CSBIGCam::GetReadoutMode();\n#if MYCAM_DEBUG\n\tcout << \"[MyCam debug]: starting to read out CCD\" << endl;\n#endif\t\n\tif ( (err = CSBIGCam::StartReadout(srp)) == CE_NO_ERROR ) {\n\t\trlp.ccd = CSBIGCam::GetActiveCCD();\n\t\trlp.pixelStart = left;\n\t\trlp.pixelLength = width;\n\t\trlp.readoutMode = CSBIGCam::GetReadoutMode();\n\t\tfor (i=0; i<height && err==CE_NO_ERROR; i++ )\n\t\t\terr = CSBIGCam::ReadoutLine(rlp, FALSE, pImg->GetImagePointer() + (long)i * width);\n\t}\n\tCSBIGCam::EndReadout();\n\tif ( err != CE_NO_ERROR )\n\t\treturn err;\n\tif ( CSBIGCam::GetError() != CE_NO_ERROR )\n\t\treturn CSBIGCam::GetError();\n\tpImg->setChanged(true);\n#if MYCAM_TIMING\n\tgettimeofday(&reference2, NULL);\n\telapsed = (reference2.tv_sec - reference.tv_sec)*1000000 + reference2.tv_usec - reference.tv_usec;\n\tcout << \"[MyCam timing]: time for readout: \" << elapsed/1000.0 << \"ms\" << endl;\n\treadTime = elapsed/1000.0;\n\tgettimeofday(&reference, NULL); //reset reference time\n#endif\n\n\t// we're done unless we wanted a dark also image\n\tif ( dark == SBDF_DARK_ALSO ) {\n\t// start the light exposure\n#if MYCAM_DEBUG\n\t\tcout << \"[MyCam debug]: starting 2nd exposure.\" << endl;\n#endif\t\n\t\tgettimeofday(&reference, NULL);\n\t\tif ( CSBIGCam::StartExposure(SC_OPEN_SHUTTER) != CE_NO_ERROR )\n\t\t\treturn CSBIGCam::GetError();\n\t\tpImg->SetImageStartTime(&reference);\n\t\t\t\n\t\t// wait for exposure to complete (sleep for most of the time, allow 5ms leeway)\n#if MYCAM_DEBUG\n\t\tcout << \"[MyCam debug]: waiting for exposure, sleeping for: \" \n\t\t \t << (int)(CSBIGCam::GetExposureTime()*1000000 - 10000)/1000.0 << \"ms\" << endl;\n#endif\t\n\t\tusleep((int)(CSBIGCam::GetExposureTime()*1000000) - 10000);\n\t\tdo {\n\t\t} while ((err = CSBIGCam::IsExposureComplete(expComp)) == CE_NO_ERROR && !expComp );\n\t\tCSBIGCam::EndExposure();\n\t\tif ( err != CE_NO_ERROR )\n\t\t\treturn err;\n\t\tif ( CSBIGCam::GetError() != CE_NO_ERROR )\n\t\t\treturn CSBIGCam::GetError();\n\t\t// readout the CCD\n\t\t\t\n\t\tsrp.ccd = CSBIGCam::GetActiveCCD();\n\t\tsrp.left = left;\n\t\tsrp.top = top;\n\t\tsrp.height = height;\n\t\tsrp.width = width;\n\t\tsrp.readoutMode = CSBIGCam::GetReadoutMode();\n\t\tif ( (err = CSBIGCam::StartReadout(srp)) == CE_NO_ERROR ) {\n\t\t\trlp.ccd = CSBIGCam::GetActiveCCD();\n\t\t\trlp.pixelStart = left;\n\t\t\trlp.pixelLength = width;\n\t\t\trlp.readoutMode = CSBIGCam::GetReadoutMode();\n\t\t\tfor (i=0; i<height && err==CE_NO_ERROR; i++ )\n\t\t\t\terr = CSBIGCam::ReadoutLine(rlp, TRUE, pImg->GetImagePointer() + (long)i * width);\n\t\t}\n\t\tCSBIGCam::EndReadout();\n\t\tif ( err != CE_NO_ERROR )\n\t\t\treturn err;\n\t\tif ( CSBIGCam::GetError() != CE_NO_ERROR )\n\t\t\treturn CSBIGCam::GetError();\n\t\tpImg->setChanged(true);\n\n\t\t// record dark subtraction in history\n\t\tif ( CSBIGCam::GetCameraType() == ST5C_CAMERA || CSBIGCam::GetCameraType() == ST237_CAMERA )\n\t\t\tpImg->SetHistory(\"f\");\n\t\telse\n\t\t\tpImg->SetHistory(\"R\");\n\t}\n#if MYCAM_TIMING\n\tgettimeofday(&reference2, NULL);\n\tgettimeofday(&grabstop, NULL);\n\telapsed = (reference2.tv_sec - reference.tv_sec)*1000000 + reference2.tv_usec - reference.tv_usec;\n\tcout << \"[MyCam timing]: time for second exposure (as applicable): \" << elapsed/1000.0 << \"ms\" << endl;\n\tunsigned int duration = (grabstop.tv_sec - grabstart.tv_sec)*1000000 + grabstop.tv_usec - grabstart.tv_usec;\n\tcout << \"[MyCam timing]: grab image took total time of \" << duration/1000.0 << \"ms\" << endl;\n\ttotalTime = duration/1000.0;\n\t//don't write timing data to a file any more\n//\tofstream fout(\"/home/steve/starcam/thesis/sources/timing.txt\", ios::out | ios::app);\n//\tif (!fout) cerr << \"Error: failed to open time recording file\";\n//\tfout << expTime << \"\\t\\t\" << readTime << \"\\t\\t\" << totalTime << endl;\n//\tfout.close();\n#endif\n\n\treturn CE_NO_ERROR;\t\n\t\n}\n\n/*\n \n\tStartExposure:\n\t\t\n\tStart an exposure in the camera. Should be matched\n\twith an EndExposure call.\n\toverrides CSBIGCam routine to try and add speed improvements\n\t\n*/\nPAR_ERROR MyCam::StartExposure(SHUTTER_COMMAND shutterState)\n{\n\tStartExposureParams sep;\n\t\n//\tsep.ccd = CSBIGCam::GetActiveCCD();\n\t//adding START_SKIP_VDD should speed up the process, but may result in a glow on the side of the image\n\tsep.ccd = CSBIGCam::GetActiveCCD() + START_SKIP_VDD;\n\tsep.exposureTime = (unsigned long)(CSBIGCam::GetExposureTime() * 100.0 + 0.5 + EXP_SEND_TRIGGER_OUT);\n\tif ( sep.exposureTime < 1 )\n\t\tsep.exposureTime = 1;\n\tsep.abgState = CSBIGCam::GetABGState();\n\t\n\tsep.openShutter = shutterState;\n\t//can try manually opening the shutter, and the leaving the state the same in CC_START_EXPOSURE\n\t//this would probably be best if coupled with not closing the shutter diring readout (may screw things up)\n// \tsep.openShutter = SC_LEAVE_SHUTTER;\n// \tMiscellaneousControlParams mcp;\n// \tmcp.fanEnable=TRUE;\n// \tmcp.shutterCommand=SC_OPEN_SHUTTER;\n// \tmcp.ledState=LED_ON;\n// \tif (CSBIGCam::SBIGUnivDrvCommand(CC_MISCELLANEOUS_CONTROL, &mcp, NULL) != CE_NO_ERROR)\n// \t\treturn CSBIGCam::GetError();\t\n\t\n\tif ( CSBIGCam::CheckLink() )\n\t\treturn CSBIGCam::SBIGUnivDrvCommand(CC_START_EXPOSURE, &sep, NULL);\n\telse\n\t\treturn CSBIGCam::GetError();\n}\n\n/*\n \n\tEndExposure:\n\t\t\n\tEnd or abort an exposure in the camera. Should be\n\tmatched to a StartExposure but no damage is done\n\tby calling it by itself if you don't know if an\n\texposure was started for example.\n\toverrides CSBIGCam routine to try and add speed improvements\n\t\n*/\nPAR_ERROR MyCam::EndExposure(void)\n{\n\tEndExposureParams eep;\n\t\n\teep.ccd = CSBIGCam::GetActiveCCD();\n\t//can try skipping wait for mottor to stop (should be coupled with manual motor control above)\n// \teep.ccd = CSBIGCam::GetActiveCCD() + END_SKIP_DELAY;\n\t\n\tif ( CSBIGCam::CheckLink() )\n\t\treturn CSBIGCam::SBIGUnivDrvCommand(CC_END_EXPOSURE, &eep, NULL);\n\telse\n\t\treturn CSBIGCam::GetError();\n}\n\nstring MyCam::getSerialNum()\n{\n\tGetCCDInfoParams gcip;\n\tGetCCDInfoResults2 gcir;\n\n\tgcip.request = 2; //extended info\n\t\n\tif ( CSBIGCam::SBIGUnivDrvCommand(CC_GET_CCD_INFO, &gcip, &gcir) == CE_NO_ERROR )\n\t\treturn (string)gcir.serialNumber;\n\telse return \"unknown\";\n}\n" }, { "alpha_fraction": 0.5585533976554871, "alphanum_fraction": 0.5717566013336182, "avg_line_length": 31.849056243896484, "blob_id": "c9c74fac16ab36c594ece501ee038988bd4313d3", "content_id": "705d40118f45aacd57f79da54cf42f640e9b011a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1743, "license_type": "no_license", "max_line_length": 83, "num_lines": 53, "path": "/stars/code/housekeeping/disk.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"housekeeper.h\"\n#include <boost/filesystem.hpp>\n#include <limits>\n#include \"logger.h\"\n\n// This file exists because boost/filesystem.hpp and cbw.h don't play well together\n\nusing namespace Housekeeping;\n\nvoid Housekeeper::get_disk()\n{\n using namespace boost::filesystem;\n double giga = pow(2.0, 30.0);\n try {\n space_info info = space(path(output_dir));\n disk_space = info.available/giga;\n last_successful_disk_space_timer.start();\n\n if (timer_since_first_disk_space_measurement.started()) {\n if (disk_space == disk_space_first_measurement) {\n disk_time = std::numeric_limits<double>::infinity();\n } else {\n disk_time = timer_since_first_disk_space_measurement.time() *\n disk_space / (disk_space_first_measurement - disk_space);\n if (disk_time < 0) {\n disk_time = std::numeric_limits<double>::infinity();\n }\n }\n disk_time_valid = true;\n } else {\n timer_since_first_disk_space_measurement.start();\n disk_space_first_measurement = disk_space;\n }\n\n string logdata = \"disk\";\n logdata += (format(\" %.3d GB\")%disk_space).str();\n if (disk_time_valid) {\n logdata += (format(\" %.3d days\")%(disk_time/(24.0*3600.0))).str();\n }\n if (write_disk_counter == 0) {\n logger.log(logdata);\n }\n write_disk_counter = (write_disk_counter+1)%1;\n\n } catch (...) {\n }\n}\n\n" }, { "alpha_fraction": 0.6774193644523621, "alphanum_fraction": 0.6881720423698425, "avg_line_length": 45.5, "blob_id": "9062c4b57f6288bbc7c8dac5158ee1706aa8f705", "content_id": "8be65c5bc40b66a49607a0061a40c19248aaadaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 93, "license_type": "no_license", "max_line_length": 75, "num_lines": 2, "path": "/cow/GNUmakefile", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "SVN_REVISION=$(shell svn info src/cow.cpp | awk '/^Revision/ { print $$2}')\ninclude Makefile\n" }, { "alpha_fraction": 0.6621325016021729, "alphanum_fraction": 0.6621325016021729, "avg_line_length": 24.322221755981445, "blob_id": "5d9ab39ded5c3856aae30129924212a4b17cdb52", "content_id": "522f8572ab35c02d58bfe4257095e85e17420daf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2279, "license_type": "no_license", "max_line_length": 126, "num_lines": 90, "path": "/guaca/logscroll.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include \"logscroll.h\"\n#include \"ui_logscroll.h\"\n\nLogscroll::Logscroll(QWidget *parent, QString cmd, bool save_position) :\n QWidget(parent),\n ui(new Ui::Logscroll)\n{\n ui->setupUi(this);\n this->save_position = save_position;\n\n process = NULL;\n cmdstring = cmd;\n startProcess();\n\n QSettings settings(\"guacamole\", \"guaca\");\n restoreGeometry(settings.value(cmdstring).toByteArray());\n}\n\nLogscroll::~Logscroll()\n{\n qDebug() << \"Destroying log\";\n savePosition();\n stopProcess();\n if (ui) delete ui;\n ui = NULL;\n printf(\"Destroyed log\\n\");\n}\n\nvoid Logscroll::stopProcess() {\n if (process) {\n process->kill();\n delete process;\n }\n process = NULL;\n}\n\nbool Logscroll::doneProcess() {\n return (process->state() == QProcess::NotOpen);\n}\n\nvoid Logscroll::startProcess() {\n stopProcess();\n\n process = new QProcess(this);\n\n connect(process, &QProcess::readyReadStandardOutput, this, &Logscroll::processStandardOutput);\n connect(process, &QProcess::readyReadStandardError, this, &Logscroll::processStandardError);\n connect(process, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), this, &Logscroll::close);\n\n process->start(cmdstring);\n qDebug() << \"Starting process: \" + cmdstring;\n}\n\nvoid Logscroll::savePosition()\n{\n if (save_position) {\n QSettings settings(\"guacamole\", \"guaca\");\n settings.setValue(cmdstring, saveGeometry());\n }\n}\n\nvoid Logscroll::closeEvent(QCloseEvent *event)\n{\n qDebug() << cmdstring << \" told to close\";\n savePosition();\n QWidget::closeEvent(event);\n}\n\nvoid Logscroll::processStandardOutput() {\n ui->logText->moveCursor(QTextCursor::End);\n latest_str = process->readAllStandardOutput();\n ui->logText->insertPlainText(latest_str);\n if (*latest_str.end() == '\\r') {\n printf(\"line!\\n\");\n ui->logText->moveCursor(QTextCursor::StartOfLine);\n }\n ui->logText->moveCursor (QTextCursor::End);\n}\n\n\nvoid Logscroll::processStandardError() {\n ui->logText->moveCursor(QTextCursor::End);\n latest_str = process->readAllStandardError();\n ui->logText->insertPlainText(latest_str);\n ui->logText->moveCursor(QTextCursor::End);\n}\n\nQString Logscroll::get_latest_str() {\n return latest_str;\n}\n" }, { "alpha_fraction": 0.5513219833374023, "alphanum_fraction": 0.565140962600708, "avg_line_length": 27.907621383666992, "blob_id": "26c6692b7607d4642a2ae9721083b57f67e33e1c", "content_id": "6ae96ab2e807d71dab5974b9db648d265087eadc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12519, "license_type": "no_license", "max_line_length": 114, "num_lines": 433, "path": "/common/FIFO.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \"Copyright 2017 Javier Romualdez\"\n *\n * -----------------------------------------------------------------------\n * ----------------------------- BIT ADCS FIFO ---------------------------\n * -----------------------------------------------------------------------\n * This program is distributed under the GNU General Public License (GPL)\n * Version 2 or higher.\n *\n * The following was developed in the QNX Momentics IDE and compiled on\n * using QNX RTOS version 6.5.\n *\n * ------------------------- Description -------------------------------\n * This code includes all necessary routines and data structures for the\n * circular FIFO buffer used on BIT for ground telemetry links.\n *\n * ---------------------------- Author ---------------------------------\n * L. Javier Romualdez (B.Eng Aerospace)\n * Institute for Aerospace Studies (UTIAS)\n * University of Toronto\n *\n * Created: November 21, 2013\n *\n * Copyright 2013 Javier Romualdez\n *\n * -------------------------- Revisions --------------------------------\n *\n */\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <pthread.h>\n#include <unistd.h>\n#include <string.h>\n#include <math.h>\n#include <stdint.h>\n#include \"FIFO.h\"\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifndef MIN\n#define MIN(a, b) ((a) < (b) ? (a) : (b))\n#endif\n\n/* -------------------------\n * ------- allocFifo -------\n * -------------------------\n *\n * This function allocates memory for the specified FIFO, which includes\n * sizes, flags, and buffers.\n *\n * Parameters:\n * --------------------------\n * fifo:\t\tA pointer to the FIFO to allocate memory for.\n * length:\t\tThe number of elements in the FIFO\n * maxsize:\t\tThe maximum size of each element in the FIFO. If the maxsize\n * \t\t\t\tis set to 0, each buffer pointer will be NULL. This is\n * \t\t\t\tdesirable if the FIFO only points to buffer elements without\n * \t\t\t\tcopying data.\n *\n*/\nint allocFifo(struct Fifo *fifo, unsigned int length, unsigned int maxsize) {\n\tunsigned int i;\n\n\tfifo->length = length;\n\tfifo->maxsize = maxsize;\n\tfifo->start = 0;\n\tfifo->end = 0;\n\tfifo->size = (uint32_t *) calloc(length, sizeof(uint32_t));\n\tfifo->frame_num = (uint32_t *) calloc(length, sizeof(uint32_t));\n\tfifo->flags = (uint8_t *) calloc(length, sizeof(uint8_t));\n\tfifo->buffer = (uint8_t **) calloc(length, sizeof(uint8_t*));\n\n\tif (maxsize != 0) {\n\t\tfor (i = 0; i < length; i++) {\n\t\t\tfifo->buffer[i] = (uint8_t *) calloc(maxsize, sizeof(uint8_t));\n\t\t\tfifo->flags[i] = MEMALLOC;\n\t\t}\n\t}\n\n\treturn 1;\n}\n\n/* -------------------------\n * ------- freeFifo --------\n * -------------------------\n *\n * This function frees memory for the specified FIFO, including all memory\n * allocated to FIFO elements.\n *\n * Parameters:\n * --------------------------\n * fifo:\t\tA pointer to the FIFO to free memory.\n *\n*/\nint freeFifo(struct Fifo *fifo) {\n\tunsigned int i;\n\tfor (i = 0; i < fifo->length; i++) {\n\t\tif (fifo->flags[i] & MEMALLOC) free(fifo->buffer[i]);\n\t}\n\tfree(fifo->flags);\n\tfree(fifo->size);\n\tfree(fifo->frame_num);\n\tfree(fifo->buffer);\n\treturn 1;\n}\n\n\n/* -------------------------\n * ------ fifoIsEmpty ------\n * -------------------------\n *\n * This function returns 1 the FIFO is empty and 0 if it isn't...\n *\n * Parameters:\n * --------------------------\n * fifo:\t\tA pointer to the FIFO in question.\n *\n*/\nint fifoIsEmpty(struct Fifo * fifo) {\n\tif ((fifo->start == fifo->end) && (fifo->length > 1)) return 1;\n\treturn 0;\n}\n\n\n\n/* -------------------------\n * ----- incrementFifo -----\n * -------------------------\n *\n * This function takes a FIFO and increments the end of the buffer by 1.\n * As a result, the buffer is incremented in a way that newest data is added to\n * the tail of the buffer.\n *\n * Parameters:\n * --------------------------\n * fifo:\t\tA pointer to the FIFO to increment.\n *\n*/\nint incrementFifo(struct Fifo * fifo) {\n\tif ((fifo->end+1)%(fifo->length) == fifo->start) {\n\t\t// printf(\"Dump FIFO!\\n\");\n\t\treturn -1; // can't increment because will overflow\n\t\t// decrementFifo(fifo); // OR dump the oldest measurement\n\t}\n\tfifo->end = (fifo->end+1)%(fifo->length); // update FIFO end\n\tif (fifo->flags[fifo->end] & MEMALLOC) {\n memset(fifo->buffer[fifo->end], 0, fifo->maxsize);\n fifo->flags[fifo->end] = MEMALLOC; // clear flags\n } else {\n fifo->flags[fifo->end] = 0; // clear flags\n }\n fifo->size[fifo->end] = 0; // clear size\n fifo->frame_num[fifo->end] = 0; // clear the frame number\n\t// if (fifoIsEmpty(fifo)) printf(\"SOMETHING IS VERY WRONG!!!\\n\");\n\treturn 1;\n}\n\n\n/* -------------------------\n * ----- decrementFifo -----\n * -------------------------\n *\n * This function takes a FIFO and increments the start of the buffer by 1.\n * As a result, the buffer is incremented in a way that oldest data is removed\n * from the head of the FIFO.\n *\n * Parameters:\n * --------------------------\n * fifo:\t\tA pointer to the FIFO to decrement.\n *\n*/\nint decrementFifo(struct Fifo * fifo) {\n\tif (fifoIsEmpty(fifo)) {\n\t\tprintf(\"Cannot decrement empty FIFO!\\n\");\n\t\treturn -1;\n\t} else {\n\t\tif (fifo->flags[fifo->start] & MEMALLOC) {\n\t\t\t// memset(fifo->buffer[fifo->start], 0, fifo->maxsize);\n\t\t\t// fifo->flags[fifo->start] = MEMALLOC; // clear flags\n\t\t} else {\n\t\t\t// fifo->flags[fifo->start] = 0; // clear flags\n\t\t}\n\t\t// fifo->size[fifo->start] = 0; // clear size\n\t\t// fifo->frame_num[fifo->start] = 0; // clear the frame number\n\t\tfifo->start = (fifo->start+1)%(fifo->length); // update FIFO\n\t}\n\treturn 1;\n}\n\n/* ------------------------\n * ------ clearFifo -------\n * ------------------------\n *\n * This function clears all pending data in the FIFO\n *\n * Parameters:\n * -------------------------\n * fifo: A pointer to the FIFO to be cleared\n *\n*/\n\nvoid clearFifo(struct Fifo *fifo) {\n fifo->start = fifo->end;\n}\n\nint getFifoSize(struct Fifo *fifo) {\n int end = fifo->end;\n int start = fifo->start;\n int diff = end-start;\n return (diff < 0) ? diff + fifo->length : diff;\n}\n\n/* -------------------------\n * ------ getFifoRead ------\n * -------------------------\n *\n * This function returns a pointer to the oldest element in the FIFO to\n * be read.\n *\n * Parameters:\n * --------------------------\n * fifo:\t\tA pointer to the FIFO to read.\n *\n*/\nuint8_t * getFifoRead(struct Fifo * fifo) {\n\treturn fifo->buffer[fifo->start];\n}\n\n/* -----------------------------\n * ------ getFifoLastRead ------\n * -----------------------------\n *\n * This function returns a pointer to the second oldest element in the\n * FIFO to be read. Returns NULL if there is only one sample in the FIFO\n * (i.e no last sample).\n *\n * Parameters:\n * --------------------------\n * fifo:\t\tA pointer to the FIFO to read.\n *\n*/\nuint8_t * getFifoLastRead(struct Fifo * fifo) {\n\tunsigned int last = (fifo->start+fifo->length-1)%fifo->length; // get last element circularly\n\tif ((last == fifo->end) || fifoIsEmpty(fifo)) {\n return NULL; // not enough data in the FIFO\n\t} else {\n return fifo->buffer[last];\n }\n}\n\n/* -------------------------\n * ------ getFifoWrite -----\n * -------------------------\n *\n * This function returns a pointer to the newest element in the FIFO to\n * be written to. Note that this function only returns a valid pointer for\n * a FIFO that has memory allocated to it (maxsize != 0).\n *\n * Parameters:\n * --------------------------\n * fifo:\t\tA pointer to the FIFO to be written to.\n *\n*/\nuint8_t * getFifoWrite(struct Fifo * fifo) {\n\tif (fifo->maxsize == 0) {\n\t\tprintf(\"Cannot get write address for unallocated FIFO\\n\");\n\t\tprintf(\"Point to data with setFifoWrite()\\n\");\n\t\treturn NULL;\n\t}\n\treturn fifo->buffer[fifo->end];\n}\n\n/* -------------------------\n * ------ setFifoWrite -----\n * -------------------------\n *\n * This function sets the pointer for the newest element in the FIFO to be\n * written to. Note that this funcion is only successful for a FIFO that\n * is unallocated (maxsize == 0).\n *\n * Parameters:\n * --------------------------\n * fifo:\t\tA pointer to the FIFO.\n * buffer: \t\tA pointer to the external buffer containing data to be\n * \t\t\t\tadded to the FIFO.\n *\n*/\nint setFifoWrite(struct Fifo * fifo, uint8_t *buffer) {\n\tif (fifo->maxsize != 0) {\n\t\tprintf(\"Cannot set write address for allocated FIFO\\n\");\n\t\tprintf(\"Get write address with getFifoWrite()\\n\");\n\t\treturn -1;\n\t}\n\tfifo->buffer[fifo->end] = buffer;\n\n\treturn 1;\n}\n\n\n/* -------------------------\n * ---- packetizeBuffer ----\n * -------------------------\n *\n * This function takes a buffer and splits it into n packets of a given size.\n * Returns the location in the buffer for the ith packet.\n *\n * Parameters:\n * --------------------------\n * buffer: A pointer to the buffer to be packetized.\n * buffer_size: The total size of the buffer to be packetized.\n * packet_size: A pointer to the size of packets from the buffer.\n This value will be updated to reflect the size of the packet to\n be read from the buffer.\n * i_pkt: A pointer to the packet number to be written.\n * n_pkt: A pointer to the total number of packets required. If i_pkt=0, the number\n * of packets will be written based on the total buffer size and packet size.\n *\n *\n*/\nuint8_t * packetizeBuffer(uint8_t * buffer, uint32_t buffer_size, uint32_t * packet_size,\n uint16_t * i_pkt, uint16_t * n_pkt) {\n // compute the total number of packets if necessary\n if (*i_pkt == 0) *n_pkt = (buffer_size-1)/(*packet_size)+1;\n\n // reached the end of the buffer\n if (*i_pkt >= *n_pkt) return NULL;\n\n // get the packet_size\n uint32_t read_size = MIN(*packet_size, buffer_size-((*i_pkt)*(*packet_size)));\n uint8_t * retval = buffer+(*packet_size)*(*i_pkt);\n\n // update packet size and location\n *packet_size = read_size;\n\n return retval;\n}\n\n/* -------------------------\n * --- depacketizeBuffer ---\n * -------------------------\n *\n * This function takes sequential n packets and assembles them into a main buffer.\n * Data for the ith packet (i<n) is written to an output buffer. Returns the\n * location in the buffer for the ith packet.\n *\n * Parameters:\n * --------------------------\n * buffer: A pointer to the buffer containing depacketized data.\n * buffer_size: A pointer to the total size of the buffer to be packetized.\n This value is updated as packets are added.\n * packet_size: The size of packet to add to the buffer.\n * i_pkt: A pointer to the packet number to be written. This value will be\n * incremented on successful execution of this function.\n * n_pkt: A pointer to the total number of packets required.\n *\n *\n*/\nint depacketizeBuffer(uint8_t * buffer, uint32_t * buffer_size, uint32_t packet_size,\n uint16_t * i_pkt, uint16_t * n_pkt, uint8_t * packet) {\n // check for invalid pointers\n if (!buffer || !packet || !buffer_size || !i_pkt || !n_pkt) return -1;\n\n // nonsense values for i_pkt\n if ((*i_pkt)*packet_size > *buffer_size) return -1;\n\n // get the packet_size\n uint8_t * retval = buffer+packet_size*(*i_pkt);\n\n // copy the data to the buffer\n memcpy(retval, packet, packet_size);\n\n // update packet size and location\n *buffer_size += packet_size;\n *i_pkt += 1;\n\n // reached the end of the buffer\n if (*i_pkt >= *n_pkt) return 0;\n\n\n return 1;\n}\n\n/* telemetry packet header (12 bytes)\n * ----------------\n * [0-1] = unique sender recver serial\n * [2-6] = auxilliary data\n * [7-8] = packet number\n * [9-10] = total number of packets\n * [11] = checksum (XOR of all preceding bytes)\n */\nuint8_t writePacketHeader(uint8_t * header, uint16_t serial, uint64_t aux_data, uint16_t i_pkt, uint16_t n_pkt)\n{\n int j;\n uint8_t checksum = 0;\n aux_data &= 0x000000ffffffffff; // will only copy 1st 5 bytes of aux data\n\n // build header\n memcpy(header+0, &serial, 2);\n memcpy(header+2, &aux_data, 5);\n memcpy(header+7, &i_pkt, 2);\n memcpy(header+9, &n_pkt, 2);\n\n for (j = 0; j < (PACKET_HEADER_SIZE-1); j++) checksum ^= header[j]; // check the checksum\n header[j] = checksum;\n\n // return the checksum\n return checksum;\n}\n\nuint8_t readPacketHeader(uint8_t * header, uint16_t *serial, uint64_t *aux_data, uint16_t *i_pkt, uint16_t *n_pkt)\n{\n int j;\n uint8_t checksum = 0;\n *aux_data = 0; // zero out aux data before copying\n\n // extract header\n memcpy(serial, header+0, 2);\n memcpy(aux_data, header+2, 5);\n memcpy(i_pkt, header+7, 2);\n memcpy(n_pkt, header+9, 2);\n\n for (j = 0; j < PACKET_HEADER_SIZE-1; j++) checksum ^= header[j]; // check the checksum\n checksum ^= header[j];\n\n // non-zero implies data error\n return checksum;\n}\n\n#ifdef __cplusplus\n}\n\n#endif\n\n\n" }, { "alpha_fraction": 0.6468401551246643, "alphanum_fraction": 0.654275119304657, "avg_line_length": 21.375, "blob_id": "de51b79493aec322a01fe8f5637d311ed272cbe2", "content_id": "f83d986a5ce12ff7e3a4647bea06fc7735e18241", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 539, "license_type": "no_license", "max_line_length": 73, "num_lines": 24, "path": "/stars/code/shared/network/packets.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"packets.h\"\n\nusing namespace Shared::Network;\n\nPackets::Packets()\n{\n in_charge = false;\n}\n\nPackets& Packets::operator=(const Packets &rhs)\n{\n if (this != &rhs) {\n in_charge = rhs.in_charge;\n time_since_sent = rhs.time_since_sent;\n time_since_received = rhs.time_since_received;\n }\n return *this;\n}\n\n" }, { "alpha_fraction": 0.7118155360221863, "alphanum_fraction": 0.7233429551124573, "avg_line_length": 20.6875, "blob_id": "35cad65b9d7165ed3d29a125e7a9192393c23046", "content_id": "7ef5f193b80e667e2d073c1e806217c460ca83b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 348, "license_type": "no_license", "max_line_length": 73, "num_lines": 16, "path": "/stars/code/tools/quick_cout.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef TOOLS__QUICK_COUT_H\n#define TOOLS__QUICK_COUT_H\n\n#include <cstdio>\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n#endif\n" }, { "alpha_fraction": 0.6593886613845825, "alphanum_fraction": 0.6681222915649414, "avg_line_length": 34.75, "blob_id": "e96c80b8dd2240220fba90ff0a14666c808c4037", "content_id": "c3dbaa98f2b038464a2bd9daf48003e3be86128e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1145, "license_type": "no_license", "max_line_length": 82, "num_lines": 32, "path": "/stars/utilities/fluxer/plot_last_fit.py", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\nimport os\nimport pylab as pl\nimport stars_log_parser as parser\n\ndef plot_fluxes(solution):\n print \"plotting flux for\", solution.filename\n print \"solution had fit %d blobs and ignored %d blobs\" \\\n % (solution.fluxer.num_blobs_fit, solution.fluxer.num_blobs_ignored)\n print \"solution had best fit exposure\", solution.fluxer.best_fit_exposure, \"s\"\n star_fluxes = map(lambda match: match.star.flux, solution.matches)\n blob_fluxes = map(lambda match: match.blob.flux, solution.matches)\n pl.plot(star_fluxes, blob_fluxes, 'o')\n xlim = list(pl.xlim())\n xlim[0] = 0\n max_x = max(star_fluxes) * 1.1\n xlim[1] = max_x\n ylim = list(pl.ylim())\n ylim[0] = 0\n pl.plot([0, max_x], [0, max_x*solution.fluxer.best_fit_line], '-')\n pl.xlim((xlim))\n pl.ylim((ylim))\n pl.xlabel(\"star flux (electrons / m^s / s)\")\n pl.ylabel(\"blob flux (ADU)\")\n\nlast_solving_logname = parser.get_last_logname(\"../../output_dir/logs\", \"solving\")\nprint \"using\", last_solving_logname\nprint \"using last solution\"\nsolutions = parser.get_solutions(last_solving_logname)\nplot_fluxes(solutions[-1])\npl.show()\n\n" }, { "alpha_fraction": 0.588087797164917, "alphanum_fraction": 0.6089703440666199, "avg_line_length": 26.31884002685547, "blob_id": "d3a040fe6677155803e873d9c5e308e3fda17927", "content_id": "df631c40c327e9550b6b2019a5dbabd0f41ed631", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 41470, "license_type": "no_license", "max_line_length": 116, "num_lines": 1518, "path": "/starcam/csbigimg.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*$T csbigimg.cpp GC 1.139 01/12/05 00:02:24 */\n\n/*\n\n\tcsbigimg.cpp - SBIG Image Class\n\n\t1. This software (c)2004-2005 Santa Barbara Instrument Group.\n\t2. This free software is provided as an example of how\n\tto communicate with SBIG cameras. It is provided AS-IS\n\twithout any guarantees by SBIG of suitability for a\n\tparticular purpose and without any guarantee to be\n\tbug-free. If you use it you agree to these terms and\n\tagree to do so at your own risk.\n\t3. Any distribution of this source code to include these\n\tterms.\n\n\tRevision History\n\tDate\t\tModification\n\t=========================================================\n\t1/26/04\t\tInitial release\n\n\t1/9/05\t\tAdded OpenImage() and ParseHeader() methods\n\t\t\t\tfor reading SBIG Compressed and Uncompressed\n\t\t\t\timages.\n\t\t\t\tAdded missing Get/SetFilter() and\n\t\t\t\tGet/SetSoftware() functions\n\t\t\t\tAdded AutoBackgroundAndRange() method\n\n\t1/10/05\t\tAdded VerticalFlip() and HorizontalFlip()\n\t\t\t\tChanged way we keep track of image start time\n\t\t\t\tby using a struct tm instead of a time_t since\n\t\t\t\treading headers is now required\n\n\t1/11/05\t\tAdded SaveFITS() routine. Saves files in FITS\n\t\t\t\tformat using the CFITSIO library. CLC.\n\n\t1/12/05\t\tAdded History2FITS() routine. Generates a FITS\n\t\t\t\tHISTORY card for each history element. CLC.\n\n\t1/14/05\t\tRemoved debug printf's from SaveFITS() routine.\n\t\t\t\tAllocateImageBuffer allocated 2x as much memory as\n\t\t\t\tneeded (looks like a cut & paste error from C code).\n\t\t\t\tFixed. CLC.\n\n\t1/17/05\t\tAdded the Get/SetSubFrame() methods for specifying\n\t\t\t\t top-left corner of partial frames\n\t\t\t\tAdded the Get/SetBinning() methods for specifying\n\t\t\t\t the binning used to acquire the image\n\n\t2/18/05\t\tFixed bugs in ParseHeader() that would fail or bomb\n\t\t\t\t on old headers\n\n*/\n#include \"csbigimg.h\"\n#include <stdio.h>\n#include <string.h>\n#include <string>\n/*\n\nLocal Constants\n\n*/\nstatic const char\t*HEADER_KEYWORDS[] =\n{\n\t\"File_version = \",\n\t\"Data_version = \",\n\t\"Exposure = \",\n\t\"Focal_length = \",\n\t\"Aperture = \",\n\t\"Response_factor = \",\n\t\"Note = \",\n\t\"Background = \",\n\t\"Range = \",\n\t\"Height = \",\n\t\"Width = \",\n\t\"Date = \",\n\t\"Time = \",\n\t\"Exposure_state = \",\n\t\"Temperature = \",\n\t\"Number_exposures = \",\n\t\"Each_exposure = \",\n\t\"History = \",\n\t\"Observer = \",\n\t\"X_pixel_size = \",\n\t\"Y_pixel_size = \",\n\t\"Pedestal = \",\n\t\"E_gain = \",\n\t\"User_1 = \",\n\t\"User_2 = \",\n\t\"User_3 = \",\n\t\"User_4 = \",\n\t\"Filter = \",\n\t\"Readout_mode = \",\n\t\"Track_time = \",\n\t\"Sat_level = \",\n\t\"End\"\n};\n\n/*\n\n CSBIGImg:\n\n Standard constructor. Init member variables.\n\n*/\nCSBIGImg::CSBIGImg(void)\n{\n\tInit();\n}\n\n/*\n\n CSBIGImg:\n\n Alternate constructor. Try to allocate the image buffer.\n\n*/\nCSBIGImg::CSBIGImg(int height, int width)\n{\n\tInit();\n\tAllocateImageBuffer(height, width);\n}\n\n/*\n\n ~CSBIGImg:\n\n Deallocate the image buffer.\n\n*/\nCSBIGImg::~CSBIGImg(void)\n{\n\tDeleteImageData();\n}\n\n/*\n\n Init:\n\n Initialize the member variables with reasonable default values.\n\n*/\nvoid CSBIGImg::Init(SBIGImgConfigParams params/*=defaultImageParams.SBIGParams*/)\n{\n\ttime_t\ttm;\n\n\tm_nHeight = params.height;\n\tm_nWidth = params.width;\n\tm_pImage = params.pImg;\n\tm_dCCDTemperature = params.CCDTemperature;\n\tm_dExposureTime = params.exposureTime;\n\tm_dEachExposure = params.eachExposure;\n\tm_dTrackExposure = params.trackExposure;\n\tm_dFocalLength = params.focalLength;\n\tm_dApertureArea = params.apertureArea;\n\tm_dResponseFactor = params.responseFactor;\n\tm_dPixelHeight = params.pixelHeight;\n\tm_dPixelWidth = params.pixelWidth;\n\tm_dEGain = params.eGain;\n\tm_uBackground = params.background;\n\tm_uRange = params.range;\n\tm_uNumberExposures = params.numberExposures;\n\tm_uSaturationLevel = params.saturationLevel;\n\tm_uPedestal = params.pedestal;\n\tm_uExposureState = params.exposureState;\n\tm_uReadoutMode = params.readoutMode;\n\tm_cImageNote = params.note;\n\tm_cObserver = params.observer;\n\tm_cHistory = params.history;\n\tm_cFilter = params.filter;\n\tm_cSoftware = params.software;\n\tm_cCameraModel = params.cameraModel;\n\tm_nDefaultImageFormat = params.defaultImageFormat;\n\tm_nSubFrameTop = params.subframeTop;\n\tm_nSubFrameLeft = params.subframeLeft;\n\tm_uHorizontalBinning = params.horizontalBinning;\n\tm_uVerticalBinning = params.verticalBinning;\n#if INCLUDE_FITSIO\n\tm_cFITSObject = params.FITSObject;\n\tm_cFITSTelescope = params.FITSTelescope;\n\tm_dApertureDiameter = params.apertureDiameter;\n#endif\n\ttm = time(NULL);\n\tSetImageStartTime(tm);\n\tm_bImageModified = TRUE;\n}\n/* original method has been replaced\nvoid CSBIGImg::Init(void)\n{\n\tstring\ts1, s2;\n\ttime_t\ttm;\n\n\tm_nHeight = m_nWidth = 0;\n\tm_pImage = NULL;\n\ttm = time(NULL);\n\tSetImageStartTime(tm);\n\tm_dCCDTemperature = 25.0;\n\tm_dExposureTime = m_dEachExposure = 1.0;\n\tm_dTrackExposure = 0.0;\n\tm_dFocalLength = 80.0;\n\tm_dApertureArea = PI * 4.0 * 4.0;\n\tm_dResponseFactor = 2000.0;\n\tm_dPixelHeight = m_dPixelWidth = 0.009;\n\tm_dEGain = 2.3;\n\tm_uBackground = 0;\n\tm_uRange = 65535;\n\tm_uNumberExposures = 1;\n\tm_uSaturationLevel = 65535;\n\tm_uPedestal = 0;\n\tm_uExposureState = ES_ABG_LOW | ES_ABG_RATE_FIXED | ES_DCS_ENABLED | ES_DCR_DISABLED | ES_AUTOBIAS_ENABLED;\n\tm_uReadoutMode = 0;\n\tm_cImageNote = \"\";\n\tm_cObserver = \"Image acquired with CSBIGImg\";\n\tm_cHistory = \"0\";\n\tm_cFilter = \"None\";\n\ts1 = \"CSBIGImg Ver \";\n\ts2 = VERSION_STR;\n\tm_cSoftware = s1 + s2;\n\tm_cCameraModel = \"ST-7\";\n\tm_bImageModified = TRUE;\n\tm_nDefaultImageFormat = SBIF_UNCOMPRESSED;\n\tm_nSubFrameTop = m_nSubFrameLeft = 0;\n\tm_uHorizontalBinning = m_uVerticalBinning = 1;\n#if INCLUDE_FITSIO\n\tm_cFITSObject = \"\";\n\tm_cFITSTelescope = \"\";\n\tm_dApertureDiameter = 4.0;\n#endif\n}\n*/\n\n/* */\nvoid CSBIGImg::DeleteImageData(void)\n{\n\tif (m_pImage)\n\t\tdelete[] m_pImage;\n\tm_pImage = NULL;\n}\n\n/*\n\n SetImageStartTime:\n\n This set of overloaded functions records the time the\n image started. Each is defined separately below:\n\n SetImageStartTime(void)\n Set to the current time.\n\n SetImageStartTime(struct tm *pStartTime)\n SetImageStartTime(time_t startTime)\n SetImageStartTime(int mm, int dd, int yy, int hr, int min, int sec)\n Set to the passed time in it's individual format.\n\n*/\nvoid CSBIGImg::SetImageStartTime(void)\n{\n\tSetImageStartTime(time(NULL));\n}\n\nvoid CSBIGImg::SetImageStartTime(struct tm *pStartTime)\n{\n\tmemcpy(&m_sDecodedImageStartTime, pStartTime, sizeof(struct tm));\n}\n\nvoid CSBIGImg::SetImageStartTime(time_t startTime)\n{\n\t/*~~~~~~~~~~~~~*/\n\tstruct tm\t*plt;\n\t/*~~~~~~~~~~~~~*/\n\n\tplt = gmtime(&startTime);\n\tmemcpy(&m_sDecodedImageStartTime, plt, sizeof(struct tm));\n}\n\nvoid CSBIGImg::SetImageStartTime(int mm, int dd, int yy, int hr, int min, int sec)\n{\n\tm_sDecodedImageStartTime.tm_mon = mm - 1;\t\t// month in struct tm is 0 - 11, not 1 - 12\n\tm_sDecodedImageStartTime.tm_mday = dd;\n\tm_sDecodedImageStartTime.tm_year = yy - 1900;\t// year is zero based in 1900\n\tm_sDecodedImageStartTime.tm_hour = hr;\n\tm_sDecodedImageStartTime.tm_min = min;\n\tm_sDecodedImageStartTime.tm_sec = sec;\n}\n\n/*\n\n GetSubFrame:\n SetSubFrame:\n\n For partial frame images these contain the coordinate\n of the upper-left most pixel.\n\n*/\nvoid CSBIGImg::SetSubFrame(int nLeft, int nTop)\n{\n\tm_nSubFrameLeft = nLeft;\n\tm_nSubFrameTop = nTop;\n}\n\nvoid CSBIGImg::GetSubFrame(int &nLeft, int &nTop)\n{\n\tnLeft = m_nSubFrameLeft;\n\tnTop = m_nSubFrameTop;\n}\n\n/*\n\n GetBinning:\n SetBinning:\n\n These contain the binning used to \n acquire the image.\n\n*/\nvoid CSBIGImg::SetBinning(unsigned short uHoriz, unsigned short uVert)\n{\n\tm_uHorizontalBinning = uHoriz;\n\tm_uVerticalBinning = uVert;\n}\n\nvoid CSBIGImg::GetBinning(unsigned short &uHoriz, unsigned short &uVert)\n{\n\tuHoriz = m_uHorizontalBinning;\n\tuVert = m_uVerticalBinning;\n}\n\n/*\n\n AddHistory:\n\n Add the passed char to the history string and if it's\n only the '0' char in the string remove it.\n\n*/\nvoid CSBIGImg::AddHistory(string str)\n{\n\tif ( m_cHistory.length() == 1 && m_cHistory[0] == '0' )\n\t\tm_cHistory = str;\n\telse\n\t\tm_cHistory += str;\n}\n\n/*\n\n SaveImage:\n\n Save the image in passed path and format.\n Returns any file errors that occur.\n\n*/\nSBIG_FILE_ERROR CSBIGImg::SaveImage(const char *pFullPath, SBIG_IMAGE_FORMAT fmt /* = SBIF_DEFAULT */ )\n{\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\tchar\t\t\theader[HEADER_LEN];\n\tSBIG_FILE_ERROR res;\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\tif (fmt == SBIF_DEFAULT)\n\t\tfmt = m_nDefaultImageFormat;\n\tswitch (fmt) {\n\t\tcase SBIF_COMPRESSED:\n\t\t\tres = SaveCompressedImage(pFullPath, header);\n\t\t\tbreak;\n\n\t\tcase SBIF_UNCOMPRESSED:\n\t\t\tres = SaveUncompressedImage(pFullPath, header);\n\t\t\tbreak;\n\n\t\tcase SBIF_FITS:\n#if INCLUDE_FITSIO\n\t\t\t/* save file in FITS format */\n\t\t\tres = SaveFITS(pFullPath);\n#else\n\t\t\treturn SBFE_FORMAT_ERROR;\n#endif\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tres = SBFE_FORMAT_ERROR;\n\t\t\tbreak;\n\t}\n\n\tif (res == SBFE_NO_ERROR) {\n\t\tSetImageModified(FALSE);\n\t\tm_nDefaultImageFormat = fmt;\n\t}\n\n\treturn res;\n}\n\n/*\n\n SaveCompressedImage:\n\n Create and write the image header then compress and write each\n row in the image.\n\n*/\nSBIG_FILE_ERROR CSBIGImg::SaveCompressedImage(const char *pFullPath, char *pHeader)\n{\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\tSBIG_FILE_ERROR res;\n\tFILE\t\t\t*fp;\n\tint\t\t\t\ti, cmpWidth;\n\tunsigned char\t*pCmpData;\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n\tCreateSBIGHeader(pHeader, TRUE);\n\tres = SBFE_MEMORY_ERROR;\n\tpCmpData = new unsigned char[m_nWidth * 2 + 2];\n\tif (pCmpData) {\n\t\tres = SBFE_OPEN_ERROR;\n\t\tif ((fp = fopen(pFullPath, \"wb\")) != 0) {\n\t\t\tres = SBFE_WRITE_ERROR;\n\t\t\tif (fwrite(pHeader, HEADER_LEN, 1, fp) == 1) {\n\t\t\t\tfor (i = 0; i < m_nHeight; i++) {\n\t\t\t\t\tcmpWidth = CompressSBIGData(pCmpData, i);\n\t\t\t\t\tif (fwrite(pCmpData, 1, cmpWidth, fp) != (size_t) cmpWidth)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (i == m_nHeight)\n\t\t\t\t\tres = SBFE_NO_ERROR;\n\t\t\t\tfclose(fp);\n\t\t\t}\n\t\t}\n\n\t\tdelete[] pCmpData;\n\t}\n\treturn res;\n}\n\n/*\n\n SaveUncompressedImage:\n\n Create and write the image header then write the image\n data. We save the image as unsigned shorts but since this\n can run on machines with different byte order make the\n file byte order comply with the Intel byte order (low\n byte first).\n\n*/\nSBIG_FILE_ERROR CSBIGImg::SaveUncompressedImage(const char *pFullPath, char *pHeader)\n{\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\tFILE\t\t\t*fp;\n\tSBIG_FILE_ERROR res;\n\tint\t\t\t\ti;\n\tunsigned char\t*pRevData;\n\tunsigned short\tbyteTest = 0x1234;\n\tMY_LOGICAL\t\treverseBytes;\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n\tCreateSBIGHeader(pHeader, FALSE);\n\tres = SBFE_OPEN_ERROR;\n\tif ((fp = fopen(pFullPath, \"wb\")) != 0) {\n\t\tres = SBFE_WRITE_ERROR;\n\t\tif (fwrite(pHeader, HEADER_LEN, 1, fp) == 1) {\n\t\t\treverseBytes = *((unsigned char *) &byteTest) != 0x34;\n\t\t\tif (reverseBytes) {\n\t\t\t\tpRevData = new unsigned char[m_nWidth * 2];\n\t\t\t\tif (pRevData) {\n\t\t\t\t\tfor (i = 0; i < m_nHeight; i++) {\n\t\t\t\t\t\tIntelCopyBytes(pRevData, i);\n\t\t\t\t\t\tif (fwrite(pRevData, 2 * m_nWidth, 1, fp) != 1)\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tdelete pRevData;\n\t\t\t\t\tif (i == m_nHeight)\n\t\t\t\t\t\tres = SBFE_NO_ERROR;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tres = SBFE_MEMORY_ERROR;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fwrite(m_pImage, 2 * m_nWidth, m_nHeight, fp) == (size_t) m_nHeight)\n\t\t\t\t\tres = SBFE_NO_ERROR;\n\t\t\t}\n\t\t}\n\n\t\tfclose(fp);\n\t}\n\treturn res;\n}\n\n/*\n OpenImage:\n\n Open the image in the passed path.\n Returns any file errors that occur.\n\n*/\nSBIG_FILE_ERROR CSBIGImg::OpenImage(const char *pFullPath)\n{\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\tchar\t\t\theader[HEADER_LEN];\n\tFILE\t\t\t*fh;\n\tSBIG_FILE_ERROR res;\n\tMY_LOGICAL\t\tisCompressed;\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n\tif ((fh = fopen(pFullPath, \"rb\")) == NULL)\n\t\treturn SBFE_OPEN_ERROR;\n\telse {\n\t\tdo {\t// allow break out\n\t\t\t// read and pars header\n\t\t\tres = SBFE_FORMAT_ERROR;\n\t\t\tif (fread(header, 1, HEADER_LEN, fh) != HEADER_LEN)\n\t\t\t\tbreak;\n\t\t\tif (!ParseHeader(header, isCompressed))\n\t\t\t\tbreak;\n\n\t\t\t// allocate image buffer\n\t\t\tres = SBFE_MEMORY_ERROR;\n\t\t\tif (!AllocateImageBuffer(m_nHeight, m_nWidth))\n\t\t\t\tbreak;\n\n\t\t\tif (isCompressed)\n\t\t\t\tres = ReadCompressedImage(fh);\n\t\t\telse\n\t\t\t\tres = ReadUncompressedImage(fh);\n\n\t\t\tif (res != SBFE_NO_ERROR) {\n\t\t\t\tdelete m_pImage;\n\t\t\t\tm_pImage = NULL;\n\t\t\t}\n\t\t} while (FALSE);\n\t}\n\n\tfclose(fh);\n\tif (res == SBFE_NO_ERROR) {\n\t\tSetImageModified(FALSE);\n\t\tm_nDefaultImageFormat = isCompressed ? SBIF_COMPRESSED : SBIF_UNCOMPRESSED;\n\t}\n\n\treturn res;\n}\n\n/*\n\n ReadCompressedImage:\n\n Read from the file and uncompress a compressed image.\n\n*/\nSBIG_FILE_ERROR CSBIGImg::ReadCompressedImage(FILE *fh)\n{\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\tSBIG_FILE_ERROR res;\n\tint\t\t\t\ti, j;\n\tunsigned char\t*pcb = NULL, *pc, code;\n\tunsigned short\t*pVid, vid;\n\tunsigned short\tdelta;\n\tunsigned short\tlen;\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n\t// read compressed image data\n\tdo {\t\t\t\t\t// allow break out\n\t\t// allocate a row buffer\n\t\tres = SBFE_MEMORY_ERROR;\n\t\tpcb = new unsigned char[2 * m_nWidth];\n\t\tif (pcb == NULL)\n\t\t\tbreak;\n\n\t\t// fprintf(stderr, \"\\nCSBIGImg::OpenImage():Allocated row buffer\");\n\t\t// read each row in turn\n\t\tres = SBFE_FORMAT_ERROR;\n\t\tfor (i = 0; i < m_nHeight;) {\n\n\t\t\t// read the first 2 bytes which are the length of the compressed data\n\t\t\tpVid = m_pImage + (long)i * m_nWidth;\n\t\t\tif (fread(pcb, sizeof(unsigned short), 1, fh) != 1)\n\t\t\t\tbreak;\n\t\t\tlen = *((unsigned short *)pcb);\n\n\t\t\t// fprintf(stderr, \"\\nCSBIGImg::OpenImage():Row %d len = %u\", i, len);\n\t\t\t// check the length for invalid or uncompressed\n\t\t\tif (len > 2 * m_nWidth)\n\t\t\t\tbreak;\t// row too long for compressed data\n\t\t\telse if (len < m_nWidth + 1)\n\t\t\t\tbreak;\t// row too short for compressed data\n\t\t\telse if (len == 2 * m_nWidth) {\n\n\t\t\t\t// see if an uncompressed row\n\t\t\t\t// fprintf(stderr, \"\\nCSBIGImg::OpenImage():Row %d reading uncompressed data\", i);\n\t\t\t\tif (fread(pVid, 2, m_nWidth, fh) != (size_t) m_nWidth)\n\t\t\t\t\tbreak;\n\t\t\t\t// fprintf(stderr, \"\\nCSBIGImg::OpenImage():Row %d uncompressed data read\", i);\n\t\t\t\ti++;\t// goto next row\n\t\t\t}\n\t\t\telse {\n\n\t\t\t\t// compressed data, read the rest of the line\n\t\t\t\t// fprintf(stderr, \"\\nCSBIGImg::OpenImage():Row %d reading compressed data\", i);\n\t\t\t\tif (fread(pcb, 1, len, fh) != (size_t) len)\n\t\t\t\t\tbreak;\n\t\t\t\t// fprintf(stderr, \"\\nCSBIGImg::OpenImage():Row %d compressed data read\", i);\n\t\t\t\tpc = pcb;\n\t\t\t\tvid = *pc++;\t\t\t\t\t// first pixel is 2 bytes, lsb first\n\t\t\t\tvid += (*pc++) << 8;\n\t\t\t\tlen -= 2;\n\t\t\t\t*pVid++ = vid;\n\t\t\t\tfor (j = 1; j < m_nWidth && len > 0; j++) {\n\t\t\t\t\tcode = *pc++;\n\t\t\t\t\tlen--;\n\t\t\t\t\tif (code == 0x80) {\n\n\t\t\t\t\t\t// 0x80 means pixel in next 2 bytes\n\t\t\t\t\t\tif (len < 2)\n\t\t\t\t\t\t\tbreak;\t\t\t\t// whoops, buffer underflow, format error\n\t\t\t\t\t\tvid = *pc++;\t\t\t// ls byte first\n\t\t\t\t\t\tvid += (*pc++) << 8;\n\t\t\t\t\t\tlen -= 2;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\n\t\t\t\t\t\t// byte read is an 8 bit signed delta\n\t\t\t\t\t\tdelta = code;\n\t\t\t\t\t\tif (code & 0x80)\n\t\t\t\t\t\t\tdelta += 0xFF00;\t// sign extend\n\t\t\t\t\t\tvid += delta;\n\t\t\t\t\t}\n\n\t\t\t\t\t*pVid++ = vid;\n\t\t\t\t}\n\n\t\t\t\tif (j != m_nWidth || len != 0)\n\t\t\t\t\tbreak;\t\t\t\t\t\t// again a format error\n\t\t\t\ti++;\t\t\t// goto next row\n\t\t\t}\t\t\t\t\t// compressed row\n\n\t\t\tif (i == m_nHeight) // made it through without error\n\t\t\t\tres = SBFE_NO_ERROR;\n\t\t}\t\t\t\t\t\t// for i=0 to height\n\t} while (FALSE);\n\tif (pcb)\n\t\tdelete[] pcb;\n\treturn res;\n}\n\n/*\n\n ReadUncompressedImage:\n\n Read an uncompressed image which is written as\n an array of unsigned shorts in Intel byte order\n (low byte first). If after reading the data the\n byte order needs to be reversed do so.\n\n*/\nSBIG_FILE_ERROR CSBIGImg::ReadUncompressedImage(FILE *fh)\n{\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\tSBIG_FILE_ERROR res;\n\tint\t\t\t\ti;\n\tunsigned short\t*pVid;\n\tunsigned short\tbyteTest = 0x1234;\n\tMY_LOGICAL\t\treverseBytes;\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n\t// read uncompressed data which is a simple binary image\n\tif (fread(m_pImage, 2 * m_nWidth, m_nHeight, fh) != (size_t) m_nHeight)\n\t\tres = SBFE_FORMAT_ERROR;\n\telse {\n\t\treverseBytes = *((unsigned char *) &byteTest) != 0x34;\n\t\tif (reverseBytes) {\n\t\t\tfor (i=0; i<m_nHeight; i++) {\n\t\t\t\tpVid = m_pImage + (long)i*m_nWidth;\n\t\t\t\tIntelCopyBytes((unsigned char *)pVid, i);\n\t\t\t}\n\t\t}\n\t\tres = SBFE_NO_ERROR;\n\t}\n\treturn res;\n}\n\n/*\n\n AllocateImageBuffer:\n\n Delete any existing buffer then try to allocate one of the\n given size. Returns TRUE if successful.\n\n*/\nMY_LOGICAL CSBIGImg::AllocateImageBuffer(int height, int width)\n{\n\tif (m_pImage)\n\t\tdelete[] m_pImage;\n\tm_nHeight = m_nWidth = 0;\n\tif (height > 0 && width > 0) {\n\t\tm_pImage = new unsigned short[(long)height * width]; //CLC\n\t\tif (m_pImage) {\n\t\t\tm_nHeight = height;\n\t\t\tm_nWidth = width;\n\t\t}\n\t\tmemset(m_pImage, 0, 2L * m_nHeight * m_nWidth);\n\t}\n\treturn m_pImage != NULL;\n}\n\n/* */\nvoid CSBIGImg::CreateSBIGHeader(char *pHeader, MY_LOGICAL isCompressed)\n{\n\t/*~~~~~~~~~~~~~*/\n\tchar\t\t*p;\n\tstruct tm\t*plt;\n\t/*~~~~~~~~~~~~~*/\n\n\tplt = &m_sDecodedImageStartTime;\n\tmemset(pHeader, 0, HEADER_LEN);\n\tp = pHeader;\n\tp += sprintf(p, \"SBIG %sImage\\n\\r\", isCompressed ? \"Compressed \" : \"\");\n\tp += sprintf(p, \"%s%d\\n\\r\", HEADER_KEYWORDS[HH_FILE_VERSION], FILE_VERSION);\n\tp += sprintf(p, \"%s%d\\n\\r\", HEADER_KEYWORDS[HH_DATA_VERSION], DATA_VERSION);\n\tp += sprintf(p,\n\t\t\t\t \"%s%ld\\n\\r\",\n\t\t\t\t HEADER_KEYWORDS[HH_EXPOSURE],\n\t\t\t\t m_dExposureTime < 0.01 ? 1 : (long)(m_dExposureTime * 100.0 + 0.5));\n\tp += sprintf(p, \"%s%1.3lf\\n\\r\", HEADER_KEYWORDS[HH_FOCAL_LENGTH], m_dFocalLength);\n\tp += sprintf(p, \"%s%1.4lf\\n\\r\", HEADER_KEYWORDS[HH_APERTURE], m_dApertureArea);\n\tp += sprintf(p, \"%s%1.3lf\\n\\r\", HEADER_KEYWORDS[HH_RESPONSE_FACTOR], m_dResponseFactor);\n\tp += sprintf(p, \"%s%s\\n\\r\", HEADER_KEYWORDS[HH_NOTE], m_cImageNote.length() == 0 ? \"-\" : m_cImageNote.c_str());\n\tp += sprintf(p, \"%s%u\\n\\r\", HEADER_KEYWORDS[HH_BACKGROUND], m_uBackground);\n\tp += sprintf(p, \"%s%u\\n\\r\", HEADER_KEYWORDS[HH_RANGE], m_uRange);\n\tp += sprintf(p, \"%s%d\\n\\r\", HEADER_KEYWORDS[HH_HEIGHT], m_nHeight);\n\tp += sprintf(p, \"%s%d\\n\\r\", HEADER_KEYWORDS[HH_WIDTH], m_nWidth);\n\tp += sprintf(p,\n\t\t\t\t \"%s%02d/%02d/%02d\\n\\r\",\n\t\t\t\t HEADER_KEYWORDS[HH_DATE],\n\t\t\t\t plt->tm_mon + 1,\n\t\t\t\t plt->tm_mday,\n\t\t\t\t plt->tm_year % 100);\n\tp += sprintf(p, \"%s%02d:%02d:%02d\\n\\r\", HEADER_KEYWORDS[HH_TIME], plt->tm_hour, plt->tm_min, plt->tm_sec);\n\tp += sprintf(p, \"%s%u\\n\\r\", HEADER_KEYWORDS[HH_EXPOSURE_STATE], m_uExposureState);\n\tp += sprintf(p, \"%s%1.2lf\\n\\r\", HEADER_KEYWORDS[HH_TEMPERATURE], m_dCCDTemperature);\n\tp += sprintf(p, \"%s%d\\n\\r\", HEADER_KEYWORDS[HH_NUMBER_EXPOSURES], m_uNumberExposures);\n\tp += sprintf(p,\n\t\t\t\t \"%s%ld\\n\\r\",\n\t\t\t\t HEADER_KEYWORDS[HH_EACH_EXPOSURE],\n\t\t\t\t m_dEachExposure < 0.01 ? 1 : (long)(m_dEachExposure * 100.0 + 0.5));\n\tp += sprintf(p, \"%s%s\\n\\r\", HEADER_KEYWORDS[HH_HISTORY], m_cHistory.c_str());\n\tp += sprintf(p, \"%s%s\\n\\r\", HEADER_KEYWORDS[HH_OBSERVER], m_cObserver.length() == 0 ? \"-\" : m_cObserver.c_str());\n\tp += sprintf(p, \"%s%1.4lf\\n\\r\", HEADER_KEYWORDS[HH_X_PIXEL_SIZE], m_dPixelWidth);\n\tp += sprintf(p, \"%s%1.4lf\\n\\r\", HEADER_KEYWORDS[HH_Y_PIXEL_SIZE], m_dPixelHeight);\n\tp += sprintf(p, \"%s%u\\n\\r\", HEADER_KEYWORDS[HH_PEDESTAL], m_uPedestal);\n\tp += sprintf(p, \"%s%1.2lf\\n\\r\", HEADER_KEYWORDS[HH_E_GAIN], m_dEGain);\n\n\t/* create user parameters */\n\tp += sprintf(p, \"%s%s\\n\\r\", HEADER_KEYWORDS[HH_USER_1], m_cSoftware.length() == 0 ? \"-\" : m_cSoftware.c_str());\n\tp += sprintf(p,\n\t\t\t\t \"%s%s\\n\\r\",\n\t\t\t\t HEADER_KEYWORDS[HH_USER_2],\n\t\t\t\t m_cCameraModel.length() == 0 ? \"-\" : m_cCameraModel.c_str());\n\tp += sprintf(p,\n\t\t\t\t \"%sExposure = %1.3lf, Each_exposure = %1.3lf\\n\\r\",\n\t\t\t\t HEADER_KEYWORDS[HH_USER_3],\n\t\t\t\t m_dExposureTime,\n\t\t\t\t m_dEachExposure);\n\tp += sprintf(p, \"%s%s%d\\n\\r\",HEADER_KEYWORDS[HH_USER_4], \"Y2KYear = \", plt->tm_year + 1900);\n\n\t/* create filter string */\n\tp += sprintf(p, \"%s%s\\n\\r\", HEADER_KEYWORDS[HH_FILTER], m_cFilter.length() == 0 ? \"-\" : m_cFilter.c_str());\n\n\t/* create readout mode */\n\tp += sprintf(p, \"%s%u\\n\\r\", HEADER_KEYWORDS[HH_READOUT_MODE], m_uReadoutMode);\n\n\t/* create track time */\n\tp += sprintf(p,\n\t\t\t\t \"%s%ld\\n\\r\",\n\t\t\t\t HEADER_KEYWORDS[HH_TRACK_TIME],\n\t\t\t\t m_dTrackExposure < 0.01 ? 0 : (long)(m_dTrackExposure * 100.0 + 0.5));\n\n\t/* create saturation level */\n\tp += sprintf(p, \"%s%u\\n\\r\", HEADER_KEYWORDS[HH_SAT_LEVEL], m_uSaturationLevel);\n\tp += sprintf(p, \"%s\\n\\r%c\", HEADER_KEYWORDS[HH_END], 0x1a);\n}\n\n/* */\nMY_LOGICAL CSBIGImg::ParseHeader(char *pHeader, MY_LOGICAL &isCompressed)\n{\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\tchar\t\t\t*p, *p1;\n\tchar const\t\t*ph;\n\tMY_LOGICAL\t\tres = FALSE;\n\tint\t\t\t\ti, mm, dd, yy, hh, ss;\n\tdouble\t\t\td, d2;\n\tchar\t\t\ts[80], model[80];\n\tlong\t\t\tl;\n\tunsigned int\tu;\n\tstruct tm\t\ttm;\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n\tp = pHeader;\n\tph = \"Start of Header\";\n\tdo\n\t{\t// allow break to exit this loop\n\t\t// get the first line in the header\n\t\tif (sscanf(p, \"%79[^\\n]\", s) < 1)\n\t\t\tbreak;\n\n\t\t// fprintf(stderr,\"\\nCSBIGImg::ParseHeader():Got first line:%s\", s);\n\t\t// First word is either the Camera Model or \"SBIG\"\n\t\t// detect the optional camera model starting the first line\n\t\tSetCameraModel(\"ST-7\"); // init to default\n\t\tif (sscanf(s, \"%s\", model) < 1)\n\t\t\tbreak;\n\n\t\t// fprintf(stderr,\"\\nCSBIGImg::ParseHeader():Got model:%s\", model);\n\t\tif (strcmp(model, \"SBIG\") != 0)\n\t\t\tSetCameraModel(model);\n\n\t\t// If the image is compressed the next word will be \"Compressed\"\n\t\tisCompressed = FALSE;\n\t\tif (strcmp(s + strlen(model) + 1, \"Compressed Image\") == 0)\n\t\t\tisCompressed = TRUE;\n\t\telse if (strcmp(s + strlen(model) + 1, \"Image\") != 0)\n\t\t\tbreak;\n\n\t\t// fprintf(stderr,\"\\nCSBIGImg::ParseHeader():Got compressed:%s\", isCompressed ? \"Yes\" : \"No\");\n\t\t// Get File Version\n\t\tph = HEADER_KEYWORDS[HH_FILE_VERSION];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%d\", &i) != 1 || i<0 || i > FILE_VERSION)\n\t\t\tbreak;\n\n\t\t// Get Data Version\n\t\tph = HEADER_KEYWORDS[HH_DATA_VERSION];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%d\", &i) != 1 || i != DATA_VERSION)\n\t\t\tbreak;\n\n\t\t// Get Exposure\n\t\tph = HEADER_KEYWORDS[HH_EXPOSURE];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%ld\", &l) != 1)\n\t\t\tbreak;\n\t\tif (l < 1)\n\t\t\tl = 1;\n\t\tSetExposureTime((double)l / 100.0);\n\n\t\t// Get Focal Length\n\t\tph = HEADER_KEYWORDS[HH_FOCAL_LENGTH];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%lf\", &d) != 1)\n\t\t\tbreak;\n\t\tif (d < 0.001)\n\t\t\td = 0.001;\n\t\tSetFocalLength(d);\n\n\t\t// Get Aperture\n\t\tph = HEADER_KEYWORDS[HH_APERTURE];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%lf\", &d) != 1)\n\t\t\tbreak;\n\t\tif (d < 0.001)\n\t\t\td = 0.001;\n\t\tSetApertureArea(d);\n\n\t\t// Get Response Factor\n\t\tph = HEADER_KEYWORDS[HH_RESPONSE_FACTOR];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%lf\", &d) != 1)\n\t\t\tbreak;\n\t\tif (d < 0.001)\n\t\t\td = 0.001;\n\t\tSetResponseFactor(d);\n\n\t\t// Get Note\n\t\tph = HEADER_KEYWORDS[HH_NOTE];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%70[^\\n]\", s) != 1)\n\t\t\tbreak;\n\t\tif (strlen(s) == 1 && s[0] == '-')\n\t\t\ts[0] = 0;\n\t\tSetImageNote(s);\n\n\t\t// Get Background\n\t\tph = HEADER_KEYWORDS[HH_BACKGROUND];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%ld\", &l) != 1)\n\t\t\tbreak;\n\t\tSetBackground(l < 0 ? 0 : l > 65535 ? 65535 : l);\n\n\t\t// Get Range\n\t\tph = HEADER_KEYWORDS[HH_RANGE];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%ld\", &l) != 1)\n\t\t\tbreak;\n\t\tSetRange(l < 1 ? 1 : l > 65535 ? 65535 : l);\n\n\t\t// Get Height\n\t\tph = HEADER_KEYWORDS[HH_HEIGHT];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%d\", &m_nHeight) != 1)\n\t\t\tbreak;\n\n\t\t// Get Width\n\t\tph = HEADER_KEYWORDS[HH_WIDTH];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%d\", &m_nWidth) != 1)\n\t\t\tbreak;\n\n\t\t// Get Date\n\t\tph = HEADER_KEYWORDS[HH_DATE];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%[^\\n]\", s) != 1)\n\t\t\tbreak;\n\t\tif (sscanf(s, \"%d%*c%d%*c%d\", &mm, &dd, &yy) != 3)\n\t\t\tbreak;\n\t\ttm.tm_mon = mm - 1;\n\t\ttm.tm_mday = dd;\n\t\ttm.tm_year = (yy <= 85 ? yy + 100 : (yy < 100 ? yy : yy - 1900));\n\n\t\t// fprintf(stderr,\"\\nCSBIGImg::ParseHeader():Date = %s\", s);\n\t\t// Get Time\n\t\tph = HEADER_KEYWORDS[HH_TIME];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%[^\\n]\", s) != 1)\n\t\t\tbreak;\n\t\tif (sscanf(s, \"%d:%d:%d\", &hh, &mm, &ss) != 3)\n\t\t\tbreak;\n\t\ttm.tm_hour = hh;\n\t\ttm.tm_min = mm;\n\t\ttm.tm_sec = ss;\n\t\tSetImageStartTime(&tm);\n\n\t\t//\t\tfprintf(stderr,\"\\nCSBIGImg::ParseHeader():Time = %s\", s);\n\t\t// Get Exposure State\n\t\tph = HEADER_KEYWORDS[HH_EXPOSURE_STATE];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%u\", &u) != 1)\n\t\t\tbreak;\n\t\tSetExposureState(u);\n\n\t\t// Get Temperature\n\t\tph = HEADER_KEYWORDS[HH_TEMPERATURE];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%lf\", &d) != 1)\n\t\t\tbreak;\n\t\tSetCCDTemperature(d);\n\n\t\t// Get Number Exposures\n\t\tph = HEADER_KEYWORDS[HH_NUMBER_EXPOSURES];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%ld\", &l) != 1)\n\t\t\tbreak;\n\t\tSetNumberExposures((l < 1 ? 1 : (l > 65535 ? 65535 : l)));\n\n\t\t// Get Each Exposure\n\t\tph = HEADER_KEYWORDS[HH_EACH_EXPOSURE];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%ld\", &l) != 1)\n\t\t\tbreak;\n\t\tl = (l < 1 ? 1 : l);\n\t\tSetEachExposure((double)l / 100.0);\n\n\t\t// Get History\n\t\tph = HEADER_KEYWORDS[HH_HISTORY];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%68[^\\n]\", s) != 1)\n\t\t\tbreak;\n\t\tif (strlen(s) == 1 && s[0] == '-')\n\t\t\ts[0] = 0;\n\t\tSetHistory(s);\n\n\t\t// Get Observer\n\t\tph = HEADER_KEYWORDS[HH_OBSERVER];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%67[^\\n]\", s) != 1)\n\t\t\tbreak;\n\t\tif (strlen(s) == 1 && s[0] == '-')\n\t\t\ts[0] = 0;\n\t\tSetObserver(s);\n\n\t\t// Get X Pixel Size\n\t\tph = HEADER_KEYWORDS[HH_X_PIXEL_SIZE];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%lf\", &d) != 1)\n\t\t\tbreak;\n\t\tif (d < 0.0001)\n\t\t\td = 0.0001;\n\t\tSetPixelWidth(d);\n\n\t\t// Get Y Pixel Size\n\t\tph = HEADER_KEYWORDS[HH_Y_PIXEL_SIZE];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%lf\", &d) != 1)\n\t\t\tbreak;\n\t\tif (d < 0.0001)\n\t\t\td = 0.0001;\n\t\tSetPixelHeight(d);\n\n\t\t// Get Pedestal\n\t\tph = HEADER_KEYWORDS[HH_PEDESTAL];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%ld\", &l) != 1)\n\t\t\tbreak;\n\t\tSetPedestal((l < 1 ? 1 : (l > 65535 ? 65535 : l)));\n\n\t\t// Get E Gain\n\t\tph = HEADER_KEYWORDS[HH_E_GAIN];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\t\tif (sscanf(p += strlen(ph), \"%lf\", &d) != 1)\n\t\t\tbreak;\n\t\tif (d < 0.01)\n\t\t\td = 0.01;\n\t\tSetEGain(d);\n\n\t\t// the following parameters are optional so don't bail\n\t\t// if they aren't found and initialize them to some\n\t\t// reasonable value\n\t\tSetSoftware(\"\");\n\t\tSetFilter(\"Unknown\");\n\t\tSetTrackExposure(0.0);\n\t\tSetSaturationLevel(65535);\n\n\t\t// Get User 1 = Software Version\n\t\tph = HEADER_KEYWORDS[HH_USER_1];\n\t\tif ((p1 = strstr(p, ph)) != NULL)\n\t\t\tif (sscanf(p = p1 + strlen(ph), \"%64[^\\n]\", s) == 1)\n\t\t\t\tif (strlen(s) > 1 || s[0] != '-')\n\t\t\t\t\tSetSoftware(s);\n\n\t\t// Get User 2 = Camera Model\n\t\tph = HEADER_KEYWORDS[HH_USER_2];\n\t\tif ((p1 = strstr(p, ph)) != NULL)\n\t\t\tif (sscanf(p = p1 + strlen(ph), \"%64[^\\n]\", s) == 1)\n\t\t\t\tif (strlen(s) > 1 || s[0] != '-')\n\t\t\t\t\tSetCameraModel(s);\n\n\t\t// Get User 3 = Expanded Exposure, Each Exposure\n\t\tph = HEADER_KEYWORDS[HH_USER_3];\n\t\tif ((p1 = strstr(p, ph)) != NULL) {\n\t\t\tif (sscanf(p = p1 + strlen(ph), \"%64[^\\n]\", s) == 1) {\n\t\t\t\tif (strlen(s) > 1 || s[0] != '-') {\n\t\t\t\t\tif (sscanf(s, \"Exposure = %lf, Each_exposure = %lf\", &d, &d2) == 2) {\n\t\t\t\t\t\tSetExposureTime(d < 0.001 ? 0.001 : d);\n\t\t\t\t\t\tSetEachExposure(d2 < 0.001 ? 0.001 : d2);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Get User 4 = Y2K Year\n\t\tph = HEADER_KEYWORDS[HH_USER_4];\n\t\tif ((p1 = strstr(p, ph)) != NULL) {\n\t\t\tif (sscanf(p = p1 + strlen(ph), \"%64[^\\n]\", s) == 1) {\n\t\t\t\tif (strlen(s) > 1 || s[0] != '-') {\n\t\t\t\t\tif (sscanf(s, \"Y2K%*cear = %d\", &i) == 1) {\n\t\t\t\t\t\ttm.tm_year = i - 1900;\n\t\t\t\t\t\tSetImageStartTime(&tm);\n\n\t\t\t\t\t\t// fprintf(stderr,\"\\nCSBIGImg::ParseHeader():User_4 = %s, Year = %d\", s, i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Get Filter\n\t\tph = HEADER_KEYWORDS[HH_FILTER];\n\t\tif ((p1 = strstr(p, ph)) != NULL)\n\t\t\tif (sscanf(p = p1 + strlen(ph), \"%64[^\\n]\", s) == 1)\n\t\t\t\tif (strlen(s) > 1 || s[0] != '-')\n\t\t\t\t\tSetFilter(s);\n\n\t\t// Get Readout Mode\n\t\tph = HEADER_KEYWORDS[HH_READOUT_MODE];\n\t\tif ((p1 = strstr(p, ph)) != NULL)\n\t\t\tif (sscanf(p = p1 + strlen(ph), \"%ld\", &l) == 1)\n\t\t\t\tSetReadoutMode((l < 0 ? 0 : (l > 65535 ? 65535 : l)));\n\n\t\t// Get Track Exposure\n\t\tph = HEADER_KEYWORDS[HH_TRACK_TIME];\n\t\tif ((p1 = strstr(p, ph)) != NULL)\n\t\t\tif (sscanf(p = p1 + strlen(ph), \"%ld\", &l) == 1) {\n\t\t\t\tl = (l < 0 ? 0 : l);\n\t\t\t\tSetTrackExposure((double)l / 100.0);\n\t\t\t}\n\n\t\t// Get Saturation Level\n\t\tph = HEADER_KEYWORDS[HH_SAT_LEVEL];\n\t\tif ((p1 = strstr(p, ph)) != NULL)\n\t\t\tif (sscanf(p = p1 + strlen(ph), \"%ld\", &l) == 1)\n\t\t\t\tSetSaturationLevel((l < 0 ? 0 : (l > 65535 ? 65535 : l)));\n\n\t\t// Make sure there's an End\n\t\tph = HEADER_KEYWORDS[HH_END];\n\t\tif ((p = strstr(p, ph)) == NULL)\n\t\t\tbreak;\n\n\t\t// if we go here the header is valid\n\t\tres = TRUE;\n\t} while (FALSE);\n\n\t// fprintf(stderr,\"\\nCSBIGImg::ParseHeader():Last header parsed = %s\", ph);\n\treturn res;\n}\n\n/*\n\n\tCompressSBIGData:\n\n\tCompress the imgRow row of pixel data into the pCmpData buffer,\n\treturning the length of the combressed data in bytes.\n\n*/\nint CSBIGImg::CompressSBIGData(unsigned char *pCmpData, int imgRow)\n{\n\t/*~~~~~~~~~~~~~~~~~~~~~~*/\n\tunsigned short\tus, *pImg;\n\tunsigned char\t*puc;\n\tint\t\t\t\tcmpLen, i;\n\tlong\t\t\tdelta;\n\t/*~~~~~~~~~~~~~~~~~~~~~~*/\n\n\tpImg = m_pImage + (long)imgRow * m_nWidth;\n\tpuc = pCmpData + 2;\t\t\t\t\t\t// offset passed length\n\tcmpLen = 0;\n\n\t// encode first pixel as is\n\tus = *pImg++;\n\t*puc++ = (unsigned char)(us & 0xFF);\t// ls byte first\n\t*puc++ = (unsigned char)(us >> 8);\n\tcmpLen += 2;\n\n\t// compress remaining pixels\n\tfor (i = 1; i < m_nWidth; i++) {\n\t\tdelta = (long)(*pImg) - us;\n\t\tus = *pImg++;\n\t\tif (delta >= -127 && delta <= 127) {\n\n\t\t\t// encode pixel as delta;\n\t\t\t*puc++ = (unsigned char)delta;\n\t\t\tcmpLen++;\n\t\t\tif (cmpLen >= 2 * m_nWidth)\t\t// make syre don't overwrite buffer\n\t\t\t\tbreak;\n\t\t}\n\t\telse {\n\n\t\t\t// encode pixel directly\n\t\t\tif (cmpLen + 3 >= 2 * m_nWidth)\n\t\t\t\tbreak;\n\t\t\t*puc++ = 0x80;\n\t\t\t*puc++ = (unsigned char)(us & 0xFF);\t// ls byte first\n\t\t\t*puc++ = (unsigned char)(us >> 8);\n\t\t\tcmpLen += 3;\n\t\t}\n\t}\n\n\tif (i < m_nWidth) {\n\n\t\t// compressed data is longer, simply copy uncompressed data\n\t\t// note we don't use memcpy here because the the byte order\n\t\t// in memory may be different that ls then ms required by\n\t\t// the file\n\t\tIntelCopyBytes(pCmpData + 2, imgRow);\n\t\tcmpLen = 2 * m_nWidth;\n\t}\n\n\t// encode length at start of buffer\n\tpCmpData[0] = (unsigned char)(cmpLen & 0xFF);\t// ls byte of len\n\tpCmpData[1] = (unsigned char)(cmpLen >> 8);\n\treturn cmpLen + 2;\n}\n\n/*\n\n\tIntelCopyBytes:\n\n\tCopy the imgRow row of pixels to the passed buffer\n\tpreserving the Intel byte order (ls them ms).\n\n*/\nvoid CSBIGImg::IntelCopyBytes(unsigned char *pRevData, int imgRow)\n{\n\t/*~~~~~~~~~~~~~~~~~~~~~~*/\n\tint\t\t\t\ti;\n\tunsigned short\tus, *pImg;\n\tunsigned char\t*puc;\n\t/*~~~~~~~~~~~~~~~~~~~~~~*/\n\n\tpImg = m_pImage + (long)imgRow * m_nWidth;\n\tpuc = pRevData;\n\tfor (i = 0; i < m_nWidth; i++) {\n\t\tus = *pImg++;\n\t\t*puc++ = (unsigned char)(us & 0xFF);\t// ls byte first\n\t\t*puc++ = (unsigned char)(us >> 8);\n\t}\n}\n\n/*\n\n\tAutoBackgroundAndRange:\n\n\tBy making a histogram of the image set the\n\tBackground and Range for auto-contrast.\n\n\tThis has no affect on the actual pixel data.\n\n*/\nvoid CSBIGImg::AutoBackgroundAndRange(void)\n{\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\tunsigned long\thist[4096];\n\tint\t\t\t\ti, j;\n\tunsigned short\t*pVid;\n\tunsigned long\ttotalPixels, histSum;\n\tunsigned long\ts20, s99;\n\tunsigned short\tp20, p99;\n\tlong\t\t\tback, range;\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\t// skip if no image data\n\tif (m_pImage == NULL)\n\t\treturn;\n\n\t// calculate the pixel histogram with 4096 bins\n\tmemset(hist, 0, sizeof(hist));\n\tpVid = m_pImage;\n\tfor (i = 0; i < m_nHeight; i++)\n\t\tfor (j = 0; j < m_nWidth; j++)\n\t\t\thist[(*pVid++) >> 4]++;\n\n\t// integrate the histogram and find the 20% and 99% points\n\ttotalPixels = (unsigned long)m_nWidth * m_nHeight;\n\ts20 = (20 * totalPixels) / 100;\n\ts99 = (99 * totalPixels) / 100;\n\thistSum = 0;\n\tp20 = p99 = 65535;\n\tfor (i = 0; i < 4096; i++) {\n\t\thistSum += hist[i];\n\t\tif (histSum >= s20 && p20 == 65535)\n\t\t\tp20 = i;\n\t\tif (histSum >= s99 && p99 == 65535)\n\t\t\tp99 = i;\n\t}\n\n\t// set the range to 110% of the difference between\n\t// the 99% and 20% histogram points, not letting\n\t// it be too low or overflow unsigned short\n\trange = (16L * (p99 - p20) * 11) / 10;\n\tif (range < 64)\n\t\trange = 64;\n\telse if (range > 65535)\n\t\trange = 65535;\n\n\t// set the background to the 20% point lowered\n\t// by 10% of the range so it's not completely\n\t// black. Also check for overrange and don't\n\t// let a saturated image show up a black\n\tback = 16L * p20 - range / 10;\n\tif (back < 0)\n\t\tback = 0;\n\telse if (p20 >= 4080)\t// saturated image?\n\t\tback = 16L * 4080 - range;\n\tm_uBackground = (unsigned short)back;\n\tm_uRange = (unsigned short)range;\n}\n\n/*\n\n\tHorizontalFlip:\n\n\tFlip the image horizontally about the center.\n\n*/\nvoid CSBIGImg::HorizontalFlip(void)\n{\n\t/*~~~~~~~~~~~~~~~~~~~~~~~*/\n\tint\t\t\t\ti, j;\n\tunsigned short\t*pVid, vid;\n\t/*~~~~~~~~~~~~~~~~~~~~~~~*/\n\n\tif (m_pImage == NULL)\n\t\treturn;\n\n\tfor (i = 0; i < m_nHeight; i++) {\n\t\tpVid = m_pImage + (long)i * m_nWidth;\n\t\tfor (j = 0; j < m_nWidth / 2; j++) {\n\t\t\tvid = pVid[j];\n\t\t\tpVid[j] = pVid[m_nWidth - 1 - j];\n\t\t\tpVid[m_nWidth - 1 - j] = vid;\n\t\t}\n\t}\n\n\tm_cHistory += \"L\";\t// per SBIG Image Format Doc\n\tSetImageModified(TRUE);\n}\n\n/*\n\n\tVerticalFlip:\n\n\tFlip the image vertically about the center.\n\n*/\nvoid CSBIGImg::VerticalFlip(void)\n{\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\tint\t\t\t\ti, j;\n\tunsigned short\t*pVid1, *pVid2, vid;\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n\tif (m_pImage == NULL)\n\t\treturn;\n\n\tfor (j = 0; j < m_nWidth; j++) {\n\t\tfor (i = 0; i < m_nHeight / 2; i++) {\n\t\t\tpVid1 = m_pImage + (long)i * m_nWidth + j;\n\t\t\tpVid2 = m_pImage + (long)(m_nHeight - i - 1) * m_nWidth + j;\n\t\t\tvid = *pVid1;\n\t\t\t*pVid1 = *pVid2;\n\t\t\t*pVid2 = vid;\n\t\t}\n\t}\n\n\tm_cHistory += \"M\";\t// per SBIG Image Format doc\n\tSetImageModified(TRUE);\n}\n#if INCLUDE_FITSIO\n/*\n\n FITS Utilities\n\n These are only compiled if the INCLUDE_FITSIO compile\n time option is set. They depend on the CFITSIO library\n which can be found at:\n\n <http://heasarc.gsfc.nasa.gov/docs/software/fitsio/fitsio.html>\n\n*/\n\n/*\n\n SaveFITS:\n\n Save a image file in FITS format. Uses routines from\n the CFITSIO lib.\n\n */\nSBIG_FILE_ERROR CSBIGImg::SaveFITS(const char *filename)\n{\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\tfitsfile\t*fptr;\n\tint\t\t\tstatus = 0;\n\tlong\t\tnaxes[2] = { m_nWidth, m_nHeight }; //image width by height\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n\tremove(filename);\t// Delete old file if it already exists\n\tif (fits_create_file(&fptr, filename, &status)) { // create new FITS file\n\t\treturn SBFE_OPEN_ERROR;\n }\n\n\tif (fits_create_img(fptr, USHORT_IMG, 2, naxes, &status)) {\n\t\treturn SBFE_OPEN_ERROR;\n }\n\n\t/*\n * write the array of unsigned integers to the FITS file\n */\n\tif (fits_write_img(fptr, TUSHORT, 1, m_nHeight * m_nWidth, m_pImage, &status))\n\t\treturn SBFE_WRITE_ERROR;\n\n char timeBuf[128], dateBuf[128], expStateBuf[5];\n\tstruct tm\t*plt = &m_sDecodedImageStartTime;\n\ttime_t curTime = time(NULL);\n\tsprintf(timeBuf,\"%04d-%02d-%02dT%02d.%02d.%02d.000\",\n\t\t\t\t plt->tm_year+1900,\n\t\t\t\t plt->tm_mon + 1,\n\t\t\t\t plt->tm_mday,\n\t\t\t\t plt->tm_hour,\n\t\t\t\t plt->tm_min,\n\t\t\t\t plt->tm_sec);\n\tplt = gmtime(&curTime);\n\tsprintf(dateBuf,\"%04d-%02d-%02d\",\n\t\t\t\t plt->tm_year+1900,\n\t\t\t\t plt->tm_mon + 1,\n\t\t\t\t plt->tm_mday);\n\tsprintf(expStateBuf,\"%X\", m_uExposureState);\n\n status = 0;\n\n char *cmt1 = \"SBIG FITS header format per:\";\n char *cmt2 = \" http://www.sbig.com/pdffiles/SBFITSEXT_1r0.pdf\";\n\tlong fitsPedestal = (long)m_uPedestal - 100;\n\tlong fitsWhite = (long)m_uBackground + m_uRange;\n\tdouble pixWidth = m_dPixelWidth*1000.0;\n\tdouble pixHeight = m_dPixelHeight*1000.0;\n\tdouble focalLen\t = m_dFocalLength * 25.4;\n\tdouble apDiam = m_dApertureDiameter * 25.4;\n\tdouble apArea = m_dApertureArea * 25.4 * 25.4;\n\n fits_update_key(fptr, TSTRING, \"COMMENT\", (void *)cmt1, \"\", &status);\n fits_update_key(fptr, TSTRING, \"COMMENT\", (void *)cmt2, \"\", &status);\n\n fits_write_key(fptr, TSTRING, \"OBJECT\", (void *)m_cFITSObject.c_str(), \"\", &status);\n fits_write_key(fptr, TSTRING, \"TELESCOP\", (void *)m_cFITSTelescope.c_str(), \"\", &status);\n fits_write_key(fptr, TSTRING, \"INSTRUME\", (void *)m_cCameraModel.c_str(), \"Camera Model\", &status);\n fits_write_key(fptr, TSTRING, \"OBSERVER\", (void *)m_cObserver.c_str(), \"\", &status);\n\tfits_write_key(fptr, TSTRING, \"DATE-OBS\", (void *)timeBuf, \"GMT START OF EXPOSURE\", &status);\n fits_write_key(fptr, TDOUBLE, \"EXPTIME\", (void *)&m_dExposureTime, \"EXPOSURE IN SECONDS\", &status);\n fits_write_key(fptr, TDOUBLE, \"CCD-TEMP\", (void *)&m_dCCDTemperature, \"CCD TEMP IN DEGREES C\", &status);\n fits_write_key(fptr, TDOUBLE, \"XPIXSZ\", (void *)&pixWidth, \"PIXEL WIDTH IN MICRONS\", &status);\n fits_write_key(fptr, TDOUBLE, \"YPIXSZ\", (void *)&pixHeight, \"PIXEL HEIGHT IN MICRONS\", &status);\n fits_write_key(fptr, TUSHORT, \"XBINNING\", (void *)&m_uHorizontalBinning, \"HORIZONTAL BINNING FACTOR\", &status);\n fits_write_key(fptr, TUSHORT, \"YBINNING\", (void *)&m_uVerticalBinning, \"VERTICAL BINNING FACTOR\", &status);\n fits_write_key(fptr, TINT, \"XORGSUBF\", (void *)&m_nSubFrameLeft, \"SUB_FRAME ORIGIN X_POS\", &status);\n fits_write_key(fptr, TINT, \"YORGSUBF\", (void *)&m_nSubFrameTop, \"SUB_FRAME ORIGIN Y_POS\", &status);\n fits_write_key(fptr, TDOUBLE, \"EGAIN\", (void *)&m_dEGain, \"ELECTRONS PER ADU\", &status);\n fits_write_key(fptr, TDOUBLE, \"FOCALLEN\", (void *)&focalLen, \"FOCAL LENGTH IN MM\", &status);\n fits_write_key(fptr, TDOUBLE, \"APTDIA\", (void *)&apDiam, \"APERTURE DIAMETER IN MM\", &status);\n fits_write_key(fptr, TDOUBLE, \"APTAREA\", (void *)&apArea, \"APERTURE AREA IN SQ-MM\", &status);\n fits_write_key(fptr, TUSHORT, \"CBLACK\", (void *)&m_uBackground, \"BLACK ADU FOR DISPLAY\", &status);\n fits_write_key(fptr, TLONG, \"CWHITE\", (void *)&fitsWhite, \"WHITE ADU FOR DISPLAY\", &status);\n fits_write_key(fptr, TLONG, \"PEDESTAL\", (void *)&fitsPedestal, \"ADD TO ADU FOR 0-BASE\", &status);\n fits_write_key(fptr, TUSHORT, \"DATAMAX\", (void *)&m_uSaturationLevel, \"SATURATION LEVEL\", &status);\n fits_write_key(fptr, TSTRING, \"SBSTDVER\", (void *)\"SBFITSEXT Version 1.0\", \"SBIG FITS EXTENSIONS VER\", &status);\n fits_write_key(fptr, TSTRING, \"SWACQUIR\", (void *)m_cSoftware.c_str(), \"DATA ACQ SOFTWARE\", &status);\n fits_write_key(fptr, TSTRING, \"SWCREATE\", (void *)m_cSoftware.c_str(), \"\", &status);\n\tfits_write_key(fptr, TSTRING, \"FILTER\", (void *)m_cFilter.c_str(), \"OPTICAL FILTER NAME\", &status);\n fits_write_key(fptr, TUSHORT, \"SNAPSHOT\", (void *)&m_uNumberExposures, \"NUMBER IMAGES COADDED\", &status);\n\tfits_write_key(fptr, TSTRING, \"DATE\", (void *)dateBuf, \"GMT DATE WHEN THIS FILE CREATED\", &status);\n fits_write_key(fptr, TUSHORT, \"RESMODE\", (void *)&m_uReadoutMode, \"RESOLUTION MODE\", &status);\n\tfits_write_key(fptr, TSTRING, \"EXPSTATE\", (void *)expStateBuf, \"EXPOSURE STATE (HEX)\", &status);\n fits_write_key(fptr, TDOUBLE, \"RESPONSE\", (void *)&m_dResponseFactor, \"CCD RESPONSE FACTOR\", &status);\n\tfits_write_key(fptr, TSTRING, \"NOTE\", (void *)m_cImageNote.c_str(), \"\", &status);\n\n if (status != 0)\n\t\treturn SBFE_FITS_HEADER_ERROR;\n\n if (History2FITS(fptr) != SBFE_NO_ERROR)\n\t\treturn SBFE_FITS_HEADER_ERROR;\n\n\tif (fits_close_file(fptr, &status)) \t\t\t\t// close the file\n\t\treturn SBRE_CLOSE_ERROR;\n\n\treturn SBFE_NO_ERROR;\n}\n\n/*\n\n History2FITS:\n \n Generates a FITS HISTORY card for each history element.\n\n*/\nstatic const char HISTORY_CHARS[] = \"@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvw\";\nstatic const char *HISTORY_PHRASES[] = {\n\t\"Unknown Modification\", \"Image Co-Addition\", \"Scale ADU Values\",\"Crop Image\",\n\t\"Dark Subtraction\", \"Remove Cool Pixels\", \"Flat Field\", \"Smooth Pixels\",\n\t\"Sharpen Pixels\", \"Pseudo Flat Field\", \"Quantize ADU Values\", \"Remove Warm Pixels\",\n\t\"Flip Horizontally\", \"Flip Vertically\", \"Zoom In\", \"Further Additional Modifications\",\n\t\"Log Scale ADU Values\", \"Combine Pixels\", \"Auto Dark Subtraction\", \"Replicate Pixels\",\n\t\"Clip ADU Values\", \"Compress Dynamic Range\", \"RGB Merge Version 2\",\n\t\"RGB Merge Version 3\", \"Translate Image\", \"Invert ADU Values\", \"Sharpen Pixels Asymmetrically\",\n\t\"Expand Dynamic Range\", \"Modernize\", \"Resample Pixel Size\", \"Average Images\",\n\t\"Add/Subtract ADU Constant\", \"Multiply/Divide ADU by Constant\",\n\t\"Enlarge Image\", \"Reduce Image\",\n\t\"Repair Column\", \"Adaptive Dark Subtraction\", \"Make Pseudo 3-D Image\",\n\t\"Auto Dark Subtraction with Hot Pixel Removal\",\"Dark Subtraction with Hot Pixel Removal\",\n\t\"LR Deconvolve Image\",\"Spatial Median Filter\", \"Set ADU Saturation Level\",\n\t\"DDP Image\", \"Rotate Image\", \"Fix TDI Background\", \"ME CCD Spike Removal\",\n\t\"Fix Bloomed Stars\", \"Remove Image Gradient\",\n\t\"Extract RGB\", \"Extract Luminance\", \"Rotate Clockwise\", \"Rotate Counter-Clockwise\",\n\t\"Median Combine 3 Images\", \"Rotate 180\", \"Raw Single Shot Color\"};\nSBIG_FILE_ERROR CSBIGImg::History2FITS(fitsfile\t*fptr)\n{\n\tint\t\t\tstatus = 0;\n const char *msg, *p;\n char\t\tc, *cp = (char*)m_cHistory.c_str();\n\tint\t\t\tindex;\n\tMY_LOGICAL\tfirst = TRUE;\n\n while (*cp) {\n\t\tc = *cp++;\n\t\tif ( (p=strchr(HISTORY_CHARS, c)) != NULL ) {\n\t\t\tindex = (p - HISTORY_CHARS)/sizeof(const char);\n\t\t\tmsg = HISTORY_PHRASES[index];\n\t\t} else if ( c == '0' )\n\t\t\tcontinue;\n\t\telse\n\t\t\tmsg = \"???\";\n\n\t\tif ( first )\n\t\t\tfits_write_key(fptr, TSTRING, \"SWMODIFY\", (void *)m_cSoftware.c_str(), \"\", &status);\n\t\tfirst = FALSE;\n\n\t if (fits_write_history(fptr,msg,&status)) {\n\t\t return SBFE_FITS_HEADER_ERROR;\n }\n }\n\treturn SBFE_NO_ERROR;\n}\n#endif\n" }, { "alpha_fraction": 0.6673728823661804, "alphanum_fraction": 0.6779661178588867, "avg_line_length": 20.409090042114258, "blob_id": "294b5c0b46219a66eceed493e3d1b701b2cc7524", "content_id": "11bb529188f78f11002b05478e0c3aaaa47f0669", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 473, "license_type": "no_license", "max_line_length": 73, "num_lines": 22, "path": "/stars/code/shared/autofocus/latest_image.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"latest_image.h\"\n\nusing namespace Shared::Autofocus;\n\nLatestImage::LatestImage()\n{\n counter_stars = -1;\n}\n\nLatestImage& LatestImage::operator=(const LatestImage &rhs)\n{\n if (this != &rhs) {\n counter_stars = rhs.counter_stars;\n }\n return *this;\n}\n\n" }, { "alpha_fraction": 0.6806201338768005, "alphanum_fraction": 0.6837209463119507, "avg_line_length": 18.846153259277344, "blob_id": "5e1c6b16320f38157307a81f6dcdec21a15a770e", "content_id": "f386572d29921aa57d60b03b5d46da35a2ac7afe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1291, "license_type": "no_license", "max_line_length": 87, "num_lines": 65, "path": "/stars/code/star_camera.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#ifndef STAR_CAMERA_H\n#define STAR_CAMERA_H\n\n#include \"tools/timing.h\"\n#include \"imaging/lens.h\"\n#include \"solving/solver.h\"\n#include \"dmm.h\"\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Imaging\n{\n class AbstractCamera;\n};\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n}\n\nclass StarCamera\n{\n public:\n StarCamera(Parameters::Manager& params, Shared::Image::Raw& solvers_working_image);\n void pick_camera(Parameters::Manager& params);\n void update_framerate();\n void set_thread_priority();\n void update_main();\n\tvoid initialize_ADCard();\n void run(Parameters::Manager& params);\n\n enum InputDeviceType {\n input_device_camera_windows,\n input_device_camera_filesystem,\n input_device_none\n };\n\n private:\n Imaging::AbstractCamera* camera;\n Imaging::Lens lens;\n Solving::Solver solver;\n\n Tools::Timer update_timer;\n Tools::Timer display_timer;\n double update_period;\n Tools::Timer framerate_timer;\n unsigned int framerate_counter;\n InputDeviceType input_device;\n\n\tdmm io_card;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6483454704284668, "alphanum_fraction": 0.65507572889328, "avg_line_length": 21, "blob_id": "0f22e0630dac5d3f521b00c1b808ecc3b5b65168", "content_id": "123ac22f94bac01ad40b19a2f46c2a168b44c2e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1784, "license_type": "no_license", "max_line_length": 73, "num_lines": 81, "path": "/stars/code/solving/blob.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__BLOB_H\n#define SOLVING__BLOB_H\n\n#include <string>\n\nnamespace Logging\n{\n class Logger;\n}\n\nnamespace Solving\n{\n class Blob;\n}\n\nclass Solving::Blob\n{\n public:\n Blob();\n void print(Logging::Logger& logger, std::string prefix);\n\n static bool sort_by_correlated_peak(Blob first, Blob second)\n {\n return first.correlated_peak > second.correlated_peak;\n }\n static bool sort_by_flux_confidence(Blob first, Blob second)\n {\n return first.flux_confidence > second.flux_confidence;\n }\n static bool sort_by_flux(Blob first, Blob second)\n {\n return first.flux > second.flux;\n }\n\n // stage 1, found while searching cells for peaks\n int u; // ccd pixel indices\n int v; // ccd pixel indices\n double correlated_peak;\n\n // stage 2, found from estimation\n double flux;\n double approximate_size;\n double base;\n double noise;\n double flux_confidence;\n bool saturated;\n double snr;\n double peak;\n double peak_to_flux;\n\n // stage 2.5, found from pedestal fitting (z=au+bv+c, params=[a,b,c])\n double pedestal_params[3];\n\n // stage 3, found from fit\n double x; // ccd coordinates, relative to center\n double y; // ccd coordinates, relative to center\n double sigma_x;\n double sigma_y;\n double fit_error_x;\n double fit_error_y;\n double est_flux;\n int num_fitting_iterations;\n bool fit_was_good;\n\n // stage 4, assigned at the end of blob finding\n int id;\n double image_noise;\n\n // stage 5, after matches\n bool matched;\n\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.6758241653442383, "alphanum_fraction": 0.6868131756782532, "avg_line_length": 18.157894134521484, "blob_id": "10b18e70dbdac807c33ea68b97bed606a507503d", "content_id": "0ff14cfdb1c763f12af6308d7f6e83c08c3ba028", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 365, "license_type": "no_license", "max_line_length": 73, "num_lines": 19, "path": "/stars/code/shared/general/quit.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__GENERAL__QUIT_H\n#define SHARED__GENERAL__QUIT_H\n\nnamespace Shared\n{\n namespace General\n {\n extern bool quit;\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.6482861638069153, "alphanum_fraction": 0.6751117706298828, "avg_line_length": 19.33333396911621, "blob_id": "5afff0a16bf76d26eeffd5c81435a30d96401acb", "content_id": "b8a1c71511e62eec5024a205b97cb176c9e5cd74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 671, "license_type": "no_license", "max_line_length": 60, "num_lines": 33, "path": "/blastd/Makefile", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "ALL = rnc tdrsslogger dnc tea lnc\n#\nall: $(ALL)\n\nrnc:rnc.c\n\tgcc -Wall rnc.c -o rnc\n\ndnc:rnc.c\n\tgcc -Wall rnc.c -o dnc\n\ntea:rnc.c\n\tgcc -Wall rnc.c -o tea\n\nlnc:rnc.c\n\tgcc -Wall rnc.c -o lnc\n#\ntdrsslogger: tdrsslogger.c\n\tgcc -Wall tdrsslogger.c -o tdrsslogger\n#\n\ninstall:tdrsslogger tea dnc rnc lnc\n\tinstall -m 700 -o root -g root tdrsslogger /usr/local/sbin\n\tinstall -m 700 -o root -g root rnc /usr/local/sbin\n\tinstall -m 700 -o root -g root dnc /usr/local/sbin\n\tinstall -m 700 -o root -g root tea /usr/local/sbin\n\tinstall -m 700 -o root -g root lnc /usr/local/sbin\n\tinstall -m 700 -o root -g root doRestart /usr/local/sbin\n\t\nclean:\t\n\trm -f $(ALL)\n\npurge:\n\trm -f *~\n" }, { "alpha_fraction": 0.577522873878479, "alphanum_fraction": 0.5965226888656616, "avg_line_length": 33.22085952758789, "blob_id": "78b7f286f39ddd4bc076c0b0983cdb2a4e491864", "content_id": "c085df8e3eb6b1099cf60f797f618910da297e1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5580, "license_type": "no_license", "max_line_length": 100, "num_lines": 163, "path": "/stars/code/housekeeping/housekeeper.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"housekeeper.h\"\n\n#include <fstream>\n#include <boost/format.hpp>\n#include \"../parameters/manager.h\"\n#include \"../shared/housekeeping/housekeeper.h\"\n#include \"logger.h\"\n\n\nusing namespace Housekeeping;\nusing std::string;\n\n#define shared_housekeeper (*(Shared::Housekeeping::housekeeper_for_camera.w))\n\nHousekeeper::Housekeeper(Parameters::Manager& params, dmm *card)\n{\n\tdisk_space = 0.0;\n disk_space_first_measurement = 0.0;\n disk_time = 0.0;\n disk_time_valid = false;\n for (int channel_num=0; channel_num<16; channel_num++) {\n add_channel(params.housekeeping.map, channel_num);\n }\n output_dir = params.general.try_get(\"main.output_dir\", string(\"C:\\\\stars_data\"));\t\n write_temps_counter = 0;\n write_disk_counter = 0;\n\t\n\tad_card = card;\n}\n\nvoid Housekeeper::add_channel(variables_map map, int channel_num)\n{\n string field_name = (boost::format(\"channel%01d.name\") % channel_num).str();\n string field_type = (boost::format(\"channel%01d.type\") % channel_num).str();\n string field_resistor_value = (boost::format(\"channel%01d.resistor_value\") % channel_num).str();\n string field_voltage = (boost::format(\"channel%01d.voltage\") % channel_num).str();\n Measurement measurement;\n string type = \"\";\n measurement.channel = channel_num;\n\tlogger.log(\"I am in add_channel\");\n if (map.count(field_name)) {\n measurement.name = map[field_name].as<string>();\n } else {\n return;\n }\n if (map.count(field_type)) {\n type = map[field_type].as<string>();\n if (type == \"temperature\" && map.count(field_resistor_value)) {\n measurement.scale = 1000000.0 / (map[field_resistor_value].as<float>());\n // measurement.offset = -273.15;\n\t\t\t// measurement.scale = 1;\n\t\t\tmeasurement.offset = 0;\n\t\t\tmeasurement.units = \" C\";\n } else if (type == \"pressure\" && map.count(field_voltage)) {\n measurement.scale = 1.0 / (0.004 * 101.325 * (map[field_voltage].as<float>()));\n measurement.offset = 0.04 / (0.004 * 101.325);\n\t\t\t// measurement.scale = 1;\n\t\t\t// measurement.offset = 0;\n measurement.units = \" a\";\n } else {\n return;\n }\n }\n measurements.push_back(measurement);\n\n}\n\nvoid Housekeeper::update_shared()\n{\n if (shared_housekeeper.measurements.size() != measurements.size()+1) {\n shared_housekeeper.measurements.clear();\n for (unsigned int i=0; i<measurements.size()+2; i++) {\n Shared::Housekeeping::Measurement shared_measurement;\n shared_housekeeper.measurements.push_back(shared_measurement);\n }\n }\n for (unsigned int i=0; i<2; i++) {\n if (i==0 && last_successful_disk_space_timer.time() < 120.0) {\n shared_housekeeper.measurements[i].name = \"disk\";\n shared_housekeeper.measurements[i].units = \" G\";\n shared_housekeeper.measurements[i].value = disk_space;\n shared_housekeeper.measurements[i].valid = true;\n } else if (i==1 && disk_time_valid) {\n shared_housekeeper.measurements[i].name = \"disktime\";\n shared_housekeeper.measurements[i].units = \" days\";\n shared_housekeeper.measurements[i].value = disk_time;\n shared_housekeeper.measurements[i].valid = true;\n } else {\n shared_housekeeper.measurements[i].name = \"disk\";\n shared_housekeeper.measurements[i].units = \" G\";\n shared_housekeeper.measurements[i].value = 0.0;\n shared_housekeeper.measurements[i].valid = false;\n }\n }\n for (unsigned int i=0; i<measurements.size(); i++) {\n shared_housekeeper.measurements[i+2].name = measurements[i].name;\n shared_housekeeper.measurements[i+2].units = measurements[i].units;\n shared_housekeeper.measurements[i+2].valid =\n measurements[i].get_value(shared_housekeeper.measurements[i+2].value);\n }\n Shared::Housekeeping::housekeeper_for_camera.share();\n}\n\nvoid Housekeeper::update()\n{\n if (last_temps_measurement_timer.time() > 0.5) {\n last_temps_measurement_timer.start();\n #if HAVEDAQ\n\t\t\ttry {\n\t\t\t\tdouble values[16] = { 0.0 };\n\t\t\t\tint channel;\n string logdata = \"temps=> \";\n\t\t\t\tstring logerror = \"\";\n\n\t\t\t\tad_card->dmm_scan(values);\n\n\t\t\t\tfor (unsigned int i = 0; i < 16; i++) {\n\t\t\t\t\tlogdata += std::to_string(i) + \": \" + std::to_string(values[i]) + \" \";\n\t\t\t\t}\n\n for (unsigned int i=0; i<measurements.size(); i++) {\n channel = measurements[i].channel;\n\t\t\t\t\tmeasurements[i].add_value(values[channel]);\n }\n \n\n\t\t\t\tint heater_state = shared_housekeeper.heater_state;\n\t\t\t\tif (heater_state > 0) {\n\t\t\t\t\tad_card->heat_camera(true);\n\t\t\t\t\tlogdata += \"Heating\";\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tad_card->heat_camera(false);\n\t\t\t\t\tlogdata += \"Not Heating\";\n\t\t\t\t}\n\t\t\t\tif (write_temps_counter == 0) {\n\t\t\t\t\tlogger.log(logdata);\n\t\t\t\t}\n\t\t\t\twrite_temps_counter = (write_temps_counter + 1) % 10;\n } catch (...) {\n }\n #else\n for (unsigned int i=0; i<measurements.size(); i++) {\n //measurements[i].add_value(double(i)*0.01+2.0);\n }\n #endif\n update_shared();\n }\n\n if (last_disk_measurement_timer.time() > 5.0) {\n last_disk_measurement_timer.start();\n get_disk();\n update_shared();\n }\n\n logger.update();\n};\n\n" }, { "alpha_fraction": 0.5829079747200012, "alphanum_fraction": 0.5904986262321472, "avg_line_length": 35.555023193359375, "blob_id": "05df1892ce675779bd30a157f6c5547fee30a4f1", "content_id": "cecf3103a3f0bf1004c98631331aa9101ed37a9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7641, "license_type": "no_license", "max_line_length": 99, "num_lines": 209, "path": "/stars/utilities/imports/python/stars_log_parsing.py", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "import os\nfrom angles import *\n\ndef get_last_logname(logs_dirname, logtype):\n for date_dirname in reversed(sorted(os.listdir(logs_dirname))):\n if os.path.isdir(os.path.join(logs_dirname, date_dirname)):\n for filename in reversed(sorted(os.listdir(os.path.join(logs_dirname, date_dirname)))):\n if filename.endswith(logtype+\".log\"):\n return os.path.join(logs_dirname, date_dirname, filename)\n return None\n\nclass Coordinates():\n def __init__(self):\n self.ra = None\n self.dec = None\n self.az = None\n self.el = None\n self.roll = None\n self.filled = False\n def set_equatorial(self, ra, dec, roll):\n self.ra = ra\n self.dec = dec\n self.roll = roll\n self.filled = True\n def set_horizontal(self, az, el, roll):\n self.az = az\n self.el = el\n self.roll = roll\n self.filled = True\n def __repr__(self):\n if self.filled:\n s = \"Coordinates\\n\"\n if self.ra:\n s += \" equatorial: %s\" % str(map(to_degrees, [self.ra, self.dec, self.roll]))\n if self.az:\n s += \" horizontal: %s\" % str(map(to_degrees, [self.az, self.el, self.roll]))\n return s\n\nclass Attitude():\n def __init__(self):\n self.equatorial = Coordinates()\n self.equatorial_errors = Coordinates()\n self.horizontal = Coordinates()\n self.horizontal_errors = Coordinates()\n\nclass ImageStats():\n pass\n\nclass HorizontalInfo():\n pass\n\nclass Solution:\n def __init__(self):\n self.fluxer = Fluxer()\n self.blobs = []\n self.stars = []\n self.matches = []\n self.image_stats = ImageStats()\n self.attitude = Attitude()\n self.horizontal_info = HorizontalInfo()\n def add_match(self, line):\n blob_id = int(line.split()[7])\n star_id = int(line.split()[12])\n star_fitted_x = float(line.split()[16])\n star_fitted_y = float(line.split()[17])\n blob = None\n for solution_blob in self.blobs:\n if solution_blob.id == blob_id:\n blob = solution_blob\n star = None\n for solution_star in self.stars:\n if solution_star.id == star_id:\n star = solution_star\n star.fitted_x = star_fitted_x\n star.fitted_y = star_fitted_y\n self.matches.append(Match(blob, star))\n def __str__(self):\n s = \"solution for image \" + str(self.filename)\n s += \" matching \" + str(len(self.matches))\n return s\n def __repr__(self):\n return str(self)\n\nclass Match:\n def __init__(self, blob, star):\n self.blob = blob\n self.star = star\n\nclass Fluxer:\n def __init__(self):\n self.best_fit_line = None\n self.best_fit_exposure = None\n self.num_blobs_fit = None\n self.num_blobs_ignored = None\n\nclass Blob:\n def __init__(self, from_line=None):\n if from_line != None:\n self.unload_line(from_line)\n def unload_line(self, line):\n self.id = int(line.split()[8])\n self.x = float(line.split()[10])\n self.y = float(line.split()[11])\n self.flux = float(line.split()[13])\n saturated = line.split()[15]\n self.saturated = False\n if saturated in [\"1\"]:\n self.saturated = True\n def __str__(self):\n s = \"blob with\"\n for attribute in [\"id\", \"x\", \"y\", \"flux\", \"saturated\"]:\n s += \" %s %d\" % (attribute, getattr(self, attribute))\n return s\n\nclass Star:\n def __init__(self, from_line=None):\n if from_line != None:\n self.unload_line(from_line)\n def unload_line(self, line):\n self.id = int(line.split()[6])\n self.ra = from_degrees(float(line.split()[9]))\n self.dec = from_degrees(float(line.split()[12]))\n self.flux = float(line.split()[14])\n def __str__(self):\n s = \"star with\"\n for attribute in [\"id\", \"ra\", \"dec\", \"flux\"]:\n s += \" %s %d\" % (attribute, getattr(self, attribute))\n return s\n\ndef add_line_to_fluxer(fluxer, line):\n if \"fluxer: found best fit line\" in line:\n fluxer.best_fit_line = float(line.split()[8])\n if \"fluxer: found best fit exposure\" in line:\n fluxer.best_fit_exposure = float(line.split()[8])/1000.0\n if \"fluxer: ignoring\" in line:\n fluxer.num_blobs_ignored = int(line.split()[5])\n if \"fluxer: fitting\" in line:\n fluxer.num_blobs_fit = int(line.split()[5])\n\ndef add_line_to_solution(line, solution):\n if \"starting to solve image\" in line:\n solution.filename = line.split()[7]\n if \"fluxer:\" in line:\n add_line_to_fluxer(solution.fluxer, line)\n if \"finder: found blob with id\" in line:\n solution.blobs.append(Blob(from_line=line))\n if \"solution: star id\" in line:\n solution.stars.append(Star(from_line=line))\n if \"solution: blob with\" in line and \"matches star\" in line:\n solution.add_match(line)\n if \"solution: equatorial attitude (deg)\" in line:\n solution.attitude.equatorial.set_equatorial(\\\n *map(from_degrees, map(float, line.split()[7:10])))\n if \"solution: equatorial errors (arcsec)\" in line:\n solution.attitude.equatorial_errors.set_equatorial(\\\n *map(from_arcsec, map(float, line.split()[7:10])))\n if \"solution: equatorial pointing error (arcsec)\" in line:\n solution.attitude.equatorial_pointing_error = from_arcsec(float(line.split()[8]))\n if \"solution: horizontal attitude (deg)\" in line:\n solution.attitude.horizontal.set_horizontal(\\\n *map(from_degrees, map(float, line.split()[7:10])))\n if \"solution: horizontal errors (arcsec)\" in line:\n solution.attitude.horizontal_errors.set_horizontal(\\\n *map(from_arcsec, map(float, line.split()[7:10])))\n if \"solution: equatorial iplatescale (arcsec/px)\" in line:\n solution.iplatescale = from_arcsec(float(line.split()[7]))\n if \"stats: mean\" in line:\n solution.image_stats.mean = float(line.split()[5])\n if \"stats: noise\" in line:\n solution.image_stats.noise = float(line.split()[5])\n if \"solution fitter: final pass used lat\" in line:\n solution.horizontal_info.lat = from_degrees(float(line.split()[9]))\n solution.horizontal_info.lst = from_hours(float(line.split()[12]))\n\ndef get_solutions_from_output(output):\n solutions = []\n in_solution = False\n for line in output:\n if \"starting to solve image\" in line:\n solutions.append(Solution())\n in_solution = True\n if \"finished solving image\" in line:\n in_solution = False\n if in_solution:\n add_line_to_solution(line, solutions[-1])\n return solutions\n\ndef get_solutions(log):\n if log.endswith(\".log\") and \"STARS is running\" not in log:\n output = open(log).readlines()\n else:\n output = log.split(\"\\n\")\n return get_solutions_from_output(output)\n\ndef get_last_solution(log, imagename=None):\n solutions = get_solutions(log)\n if len(solutions) > 0 and solutions[-1].attitude.equatorial.filled:\n if imagename == None or solutions[-1].filename == imagename:\n return solutions[-1]\n return None\n\ndef get_solutions_with_matches_from_dir(dirname):\n solutions = []\n for filename in sorted(os.listdir(dirname)):\n possible_solutions = get_solutions(os.path.join(dirname, filename))\n for possible_solution in possible_solutions:\n if len(possible_solution.matches) > 0:\n solutions.append(possible_solution)\n return solutions\n\n" }, { "alpha_fraction": 0.40819671750068665, "alphanum_fraction": 0.6827868819236755, "avg_line_length": 23.897958755493164, "blob_id": "53a781081fa248b52fb8dc707be5a2edbcb35505", "content_id": "ffe4c00823896c3269b19aa5e126a9ca8b67d06c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1220, "license_type": "no_license", "max_line_length": 62, "num_lines": 49, "path": "/xymap/domaps", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nf0=2522600\nnf=115160\nBOLOTABLE=\"/data/etc/bolo_table.txt\"\nDATA=\"/data/rawdir/1265241500.x_2517021\"\n\n#used to build channel list by parsing bolotable\n#COLOR=350\n#export COLOR\n#ch=`eval cat $BOLOTABLE | \n\t#awk '{\n\t\t#col = tolower($4); \n\t\t#if(index($1, \"N\")) \n\t\t\t#if(col == ENVIRON[\"COLOR\"]) \n\t\t\t\t#printf(\"%s \", $1)\n\t#}'`\n\n#manual channel list\n#ch=\"N17C00 N17C01 N17C02 N17C03 N17C04 N17C05 N17C06 N17C07 \\\n#\tN17C08 N17C09 N17C10 N17C11 N17C12 N17C13 N17C14 N17C15 \\\n#\tN17C16 N17C17 N17C18 N17C19 N17C20 N17C21 N17C22 N17C23 \\\n#\tN18C00 N18C01 N18C02 N18C03 N18C04 N18C05 N18C06 N18C07 \\\n#\tN18C08 N18C09 N18C10 N18C11 N18C12 N18C13 N18C14 N18C15 \\\n#\tN18C16 N18C17 N18C18 N18C19 N18C20 N18C21 N18C22 N18C23 \\\n#\tN19C00 N19C01 N19C02 N19C03 N19C04 N19C05 N19C06 N19C07 \\\n#\tN19C08 N19C09 N19C10 N19C11 N19C12 N19C13 N19C14 N19C15 \\\n#\tN19C16 N19C17 N19C18 N19C19 N19C20 N19C21 N19C22 N19C23\"\n\n#single detector case, for testing\nch=\"N17C09\"\n\nfor i in $ch \ndo\n\tCOM=\"./lockinmap -f $DATA -r $f0:$nf -d $i\"\n\techo $COM \n\t$COM > tmp.dat\n\techo plotting...\n\tgnuplot doplot\n\t\n\tfname=`eval echo $i | \n\t awk '{\n\t\tgsub(\"N\", \"\");\n\t\tsplit($0, A, \"C\");\n \t\tprintf(\"%d%02d.png\", A[1], A[2]);\n\t \n\t }'`\n \tmv map.png $fname\ndone\n" }, { "alpha_fraction": 0.6379310488700867, "alphanum_fraction": 0.6482758522033691, "avg_line_length": 21.269229888916016, "blob_id": "cf038e95d2b218ad5d6f201b46d6f6a521bd9db0", "content_id": "a754c689bf688ce660c92e8f5ce6f01156b79ed2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 581, "license_type": "no_license", "max_line_length": 73, "num_lines": 26, "path": "/stars/code/shared/image/matching.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"matching.h\"\n\nusing namespace Shared::Image;\n\nMatching::Matching()\n{\n counter_stars = -1;\n triplet_counter = -1;\n base_sets.clear();\n}\n\nMatching& Matching::operator=(const Matching &rhs)\n{\n if (this != &rhs) {\n counter_stars = rhs.counter_stars;\n triplet_counter = rhs.triplet_counter;\n base_sets = rhs.base_sets;\n }\n return *this;\n}\n\n" }, { "alpha_fraction": 0.4597839117050171, "alphanum_fraction": 0.48403361439704895, "avg_line_length": 25.528661727905273, "blob_id": "8c2d183f774fa49564aea5721481dc9d193c91fb", "content_id": "c2a84b0ffc870f327fe70e99cd656e886941a42d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8330, "license_type": "no_license", "max_line_length": 140, "num_lines": 314, "path": "/blastd/tdrsslogger.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <termios.h>\n#include <time.h>\n#include <syslog.h>\n#include <sys/ioctl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n\n#define RAWDIR \"/data/rawdir\"\n\n#define FIFODEPTH 16384\n#define NDATA 8192\nunsigned char data[2][NDATA];\n\n// port 0 is tdrss highgain. Port 1 is tdrss omni, iridium dialup, and slow packets\n#define FIRSTPORT 0\n#define LASTPORT 1\n\nchar *ttydev[2] = {\"/dev/ttyHIGAIN\", \"/dev/ttyOMNI\"};\nchar *linkfile[5] = {\"/data/etc/highgain.lnk\",\"/data/etc/omni.lnk\", \"/data/etc/iromni.lnk\", \"/data/etc/tdomni.lnk\", \"/data/etc/irslow.lnk\"};\nchar *ext[5]={\"highgain\", \"omni\", \"iromni\", \"tdomni\", \"irslow\"};\n\nint n_tdomni = 0;\nint n_iromni = 0;\nint n_slow = 0;\nint n_junk = 0;\n\nenum ModeType{LOST, JUNK, IROMNI, TDOMNI, IRSLOW};\n\nstruct fifoStruct {\n char d[FIFODEPTH];\n int i_in; // points at next place to write\n int i_out; // points at next place to read\n};\n\nstruct fifoStruct parseFifo;\n\n//*********************************************************\n// insert data into the fifo\n//*********************************************************\nvoid push(struct fifoStruct *fs, unsigned char x[], int size) {\n int i;\n for (i=0; i<size; i++) {\n fs->d[fs->i_in] = x[i];\n fs->i_in++;\n if (fs->i_in>=FIFODEPTH) {\n fs->i_in = 0;\n }\n }\n}\n\n//*********************************************************\n// return data w/out removing it\n//*********************************************************\nvoid peek(struct fifoStruct *fs, unsigned char x[], int size) {\n // warning: no error checking. Use nFifo first to make\n // sure you don't wrap the fifo.\n int i;\n int i_out = fs->i_out;\n\n for (i=0; i< size; i++) {\n x[i] = fs->d[i_out];\n i_out++;\n if (i_out >= FIFODEPTH) {\n i_out = 0;\n }\n }\n}\n\n//*********************************************************\n// advance the fifo pointer (removes data)\n//*********************************************************\nvoid advance(struct fifoStruct *fs, int size) {\n fs->i_out += size;\n if (fs->i_out >= FIFODEPTH) {\n fs->i_out -= FIFODEPTH;\n }\n}\n\n//*********************************************************\n// remove data from the fifo\n//*********************************************************\nvoid pop(struct fifoStruct *fs, unsigned char x[], int size) {\n peek(fs, x, size);\n advance(fs,size);\n}\n\n//*********************************************************\n// how many bytes are availible in the fifo\n//*********************************************************\nint nFifo(struct fifoStruct *fs) {\n int n;\n\n n = fs->i_in - fs->i_out;\n if (n < 0) n+= FIFODEPTH;\n\n return n;\n}\n\n//*********************************************************\n// OpenSerial: open serial port\n//*********************************************************\nint OpenSerial(char* device) {\n int fd;\n struct termios term;\n\n if ((fd = open(device, O_RDWR | O_NONBLOCK)) < 0) {\n syslog(LOG_ERR | LOG_DAEMON, \"Unable to open serial port.\\n\");\n fprintf(stderr, \"Unable to open serial port %s.\\n\", device);\n exit(1);\n }\n if (tcgetattr(fd, &term)) {\n syslog(LOG_ERR | LOG_DAEMON, \"Unable to get serial device attributes.\");\n return -1;\n }\n\n term.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);\n term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);\n term.c_iflag |= INPCK;\n term.c_cc[VMIN] = 0;\n term.c_cc[VTIME] = 0;\n\n term.c_cflag &= ~(CSTOPB | CSIZE);\n term.c_oflag &= ~(OPOST);\n term.c_cflag |= CS8;\n\n cfmakeraw(&term);\n\n if (cfsetospeed(&term, B115200)) { // Baud\n syslog(LOG_ERR | LOG_DAEMON, \"Error setting serial output speed.\");\n return -1;\n }\n if (cfsetispeed(&term, B115200)) { // Baud\n syslog(LOG_ERR | LOG_DAEMON, \"Error setting serial output speed.\");\n return -1;\n }\n if(tcsetattr(fd, TCSANOW, &term)) {\n syslog(LOG_ERR | LOG_DAEMON, \"Unable to set serial attributes.\");\n return -1;\n }\n\n syslog(LOG_INFO | LOG_DAEMON, \"%s open\\n\", device);\n return fd;\n}\n\n//*********************************************************\n// Initialize stream files...\n//*********************************************************\nint InitialiseStreamFile(int i) {\n int fd;\n \n char filename[255];\n static time_t filetime = 0;\n \n if (filetime==0) {\n filetime = time(NULL);\n }\n \n sprintf(filename, \"%s/%lu.%s\", RAWDIR, filetime, ext[i]);\n \n if( (fd = open(filename, O_WRONLY | O_CREAT, 00644)) < 0 ) {\n syslog(LOG_ERR | LOG_DAEMON, \"Error opening data file\\n\");\n fprintf(stderr, \"Error opening data file %s\\n\", filename);\n exit(0);\n }\n \n unlink(linkfile[i]);\n if (symlink(filename, linkfile[i])<0) {\n fprintf(stderr, \"tdrsslogger: could not create link from `%s' to `%s'\",\n filename, linkfile[i]);\n exit(0);\n }\n \n return fd;\n}\n\n//*********************************************************\n// Return header type\n//*********************************************************\nenum ModeType isHeader(unsigned char *D) {\n int size;\n\n if (D[0]!=0xfa) return LOST;\n if ((D[1]&0xf8)!=0xf8) return LOST;\n if (D[1]==0xf8) return LOST;\n if (D[1]==0xf9) return LOST;\n if (D[1]==0xfe) return LOST; // FIXME: do these ever actually happen?\n if (D[3] != 0) return LOST;\n //if ((D[2] & 0xf0) !=0) return LOST;\n\n size = (int)D[5] + (int)D[4]*256;\n\n if (size > 4096) return LOST;\n\n if (D[1]==0xfd) { // iridium\n if ((D[2]&0x03) == 0x01) return IRSLOW;\n if ((D[2]&0x03) == 0x02) return IROMNI;\n }\n if (D[1]==0xff) { // tdrss\n if ((D[2]&0x03) == 0x01) return IRSLOW; // FIXME: change for real use\n if ((D[2]&0x03) == 0x02) return TDOMNI;\n }\n \n return (JUNK);\n}\n\n \n//*********************************************************\n// Sparate omni data into separate streams\n//*********************************************************\nvoid processOmniData() {\n\n static int first_time = 1;\n static int fd[3];\n static enum ModeType mode = LOST;\n int i;\n unsigned char data_in[16384];\n static int size = 0;\n \n if (first_time) {\n first_time = 0;\n\n for (i=0; i<3; i++) {\n fd[i] = InitialiseStreamFile(i+2);\n }\n } // end first time\n\n while ((mode == LOST) && (nFifo(&parseFifo)>=6)) {\n peek(&parseFifo, data_in, 6);\n mode = isHeader(data_in);\n if (mode != LOST) {\n size = data_in[4]*256 + data_in[5];\n advance(&parseFifo, 6);\n } else {\n advance(&parseFifo, 1);\n }\n } // end while lost\n if ((mode != LOST) && (nFifo(&parseFifo)>=size+1)) {\n pop(&parseFifo, data_in, size+1);\n if (mode == TDOMNI) {\n write(fd[1], data_in, size);\n n_tdomni++;\n } else if (mode == IROMNI) {\n write(fd[0], data_in, size);\n n_iromni++;\n } else if (mode == IRSLOW) {\n write(fd[2], data_in, size);\n n_slow++;\n } else {\n n_junk++;\n }\n mode = LOST;\n }\n}\n\n//*********************************************************\n// Main loop\n//*********************************************************\nint main(void) {\n int tty[2];\n int fd[2];\n int b_in[2];\n int bytes_read[2] = {0,0};\n time_t t0[2], t[2], dt[2];\n double rate[2] = {0,0};\n int bytes0[2] = {0,0};\n time_t last_t=0;\n\n int i;\n\n for (i=FIRSTPORT; i<=LASTPORT; i++) {\n if( (tty[i] = OpenSerial(ttydev[i])) < 0) return 1;\n if( (fd[i] = InitialiseStreamFile(i)) < 0 ) return 1;\n\n bytes0[i] = 0;\n rate[i] = 0;\n t0[i] = time(NULL);\n }\n \n while (1) {\n for (i=FIRSTPORT; i<=LASTPORT; i++) {\n b_in[i] = read(tty[i], data[i], NDATA);\n\n if (b_in[i]>0) {\n bytes_read[i]+=b_in[i];\n write(fd[i], data[i], b_in[i]);\n if (i==1) {\n push(&parseFifo, data[i], b_in[i]); // send data to the parse thread\n }\n t[i] = time(NULL);\n dt[i] = t[i] - t0[i];\n if (dt[i]>=20) {\n rate[i] = (double)(bytes_read[i] - bytes0[i])/(double)dt[i];\n t0[i] = t[i];\n bytes0[i] = bytes_read[i];\n }\n if (t[i]-last_t > 10) {\n last_t = t[i];\n printf(\"High Gain: %7d bytes at %5.0fbps Omni: %6d bytes Packets: omni: %d dialup: %d slow: %d junk: %d at %s\",\n bytes_read[0], rate[0]*8.0, bytes_read[1], n_tdomni, n_iromni, n_slow, n_junk, ctime(t+i));\n fflush(stdout);\n }\n }\n } // next port\n \n processOmniData();\n \n usleep(10000);\n } // continue while 1\n return 0; // can't get here\n}\n" }, { "alpha_fraction": 0.5595075488090515, "alphanum_fraction": 0.6196990609169006, "avg_line_length": 30.7391300201416, "blob_id": "bfaf5fd43ad51ead512a98217ab8e50aa3cb21fc", "content_id": "353343d091827a179af927648bdbbe6a01a3dcce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 732, "license_type": "no_license", "max_line_length": 73, "num_lines": 23, "path": "/stars/code/tools/refraction.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"refraction.h\"\n#include <math.h>\n#include \"angles.h\"\n\ndouble Tools::refraction_angle(double el, double P_mbar, double T)\n{\n // Duffet-Smith - Practical Astronomy\n // better than 6 arcsec\n if (el > from_degrees(19.225)) {\n return from_degrees(0.00452 * P_mbar * tan(M_PI/2.0 - el) / T);\n } else {\n el = to_degrees(el);\n double numer = P_mbar * (0.1594 + 0.0196*el + 0.00002*el*el);\n double denom = T * (1 + 0.505*el + 0.0845*el*el);\n return from_degrees(numer / denom);\n }\n}\n\n" }, { "alpha_fraction": 0.7132866978645325, "alphanum_fraction": 0.7132866978645325, "avg_line_length": 32.64706039428711, "blob_id": "a0c5d887fee904fa9010bd95174c80d15569c206", "content_id": "d03ace46393d5658712596199a74653b9d54981c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 572, "license_type": "no_license", "max_line_length": 55, "num_lines": 17, "path": "/blast_comms/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "set(COMMS_SRCS\n ${COMMS_SRCS}\n ${CMAKE_CURRENT_SOURCE_DIR}/comms_netasync.c\n ${CMAKE_CURRENT_SOURCE_DIR}/comms_netbuf.c\n ${CMAKE_CURRENT_SOURCE_DIR}/comms_netsock.c\n ${CMAKE_CURRENT_SOURCE_DIR}/comms_serial.c\n PARENT_SCOPE\n)\nset(COMMS_HEADERS\n ${COMMS_HEADERS}\n ${CMAKE_CURRENT_SOURCE_DIR}/include/comms_common.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/comms_netasync.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/comms_netbuf.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/comms_netsock.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/comms_serial.h\n PARENT_SCOPE\n)\n" }, { "alpha_fraction": 0.6159169673919678, "alphanum_fraction": 0.6349480748176575, "avg_line_length": 22.1200008392334, "blob_id": "cc6ca18b13d05be4b354ed29dfeb91e072342c9a", "content_id": "9393b18111b1f27a550e739cdcac3b87a97332ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 578, "license_type": "no_license", "max_line_length": 73, "num_lines": 25, "path": "/naivepol/Makefile", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "CPP = g++ -O3 \nLIBS = -lX11 -lXpm -lblas -lblast -lmatpack -lcfitsio -lgetdata\nSLIBS = -lX11 -lXpm -lblas -lblast -lcfitsio\nINC_DIR = /usr/local/include/matpack\nLIB_DIR = /usr/X11R6/lib\n\nall:naivepol\nnaivepol:naivepol.cc\n\t$(CPP) -Wall -I$(INC_DIR) [email protected] -o $@ -L$(LIB_DIR) $(LIBS)\n\nnaivemapkir:naivemapkir.cc\n\t$(CPP) -Wall -I$(INC_DIR) [email protected] -o $@ -L$(LIB_DIR) $(LIBS)\n\nmapoffs:mapoffs.cc map.o\n\t$(CPP) -Wall -I$(INC_DIR) [email protected] map.o -o $@ -L$(LIB_DIR) $(LIBS) -lblast\n\n\ninstall: \n\tinstall -D -m 755 naivepol /usr/local/bin/naivepol\n\nclean:\n\trm -f naivepol\n\npurge:\n\trm -f *~\n" }, { "alpha_fraction": 0.6782072186470032, "alphanum_fraction": 0.6849167943000793, "avg_line_length": 29.540983200073242, "blob_id": "44ca4015572b607b28dd3c6a5df93c6a6747ffe3", "content_id": "1893654a7a3dbd76b39946bb1f73b0b9cff0f156", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 3726, "license_type": "no_license", "max_line_length": 101, "num_lines": 122, "path": "/test_programs/synclink/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "# Helper function to add preprocesor definition of FILE_BASENAME\n# to pass the filename without directory path for debugging use.\n#\n# Example:\n#\n# define_file_basename_for_sources(my_target)\n#\n# Will add -DFILE_BASENAME=\"filename\" for each source file depended on\n# by my_target, where filename is the name of the file.\n#\nfunction(define_file_basename_for_sources targetname)\n get_target_property(source_files \"${targetname}\" SOURCES)\n foreach(sourcefile ${source_files})\n # Get source file's current list of compile definitions.\n get_property(defs SOURCE \"${sourcefile}\"\n PROPERTY COMPILE_DEFINITIONS)\n # Add the FILE_BASENAME=filename compile definition to the list.\n get_filename_component(basename \"${sourcefile}\" NAME)\n list(APPEND defs \"__FILENAME__=\\\"${basename}\\\"\")\n # Set the updated compile definitions on the source file.\n set_property(\n SOURCE \"${sourcefile}\"\n PROPERTY COMPILE_DEFINITIONS ${defs})\n endforeach()\nendfunction()\n\nproject (test_biphase)\n\ncmake_minimum_required (VERSION 2.8.8)\n\nSET (CMAKE_C_FLAGS \"-Wall -std=gnu99 -mcx16\")\nSET (CMAKE_C_FLAGS_DEBUG \"-O0 -fno-omit-frame-pointer -ggdb\")\nSET (CMAKE_C_FLAGS_MINSIZEREL \"-Os -DNDEBUG\")\nSET (CMAKE_C_FLAGS_RELEASE \"-O3 -DNDEBUG\")\nSET (CMAKE_C_FLAGS_RELWITHDEBINFO \"-O2 -g\")\n\nSET (CMAKE_CXX_FLAGS \"-Wall\")\nSET (CMAKE_CXX_FLAGS_DEBUG \"-g\")\nSET (CMAKE_CXX_FLAGS_MINSIZEREL \"-Os -DNDEBUG\")\nSET (CMAKE_CXX_FLAGS_RELEASE \"-O3 -DNDEBUG\")\nSET (CMAKE_CXX_FLAGS_RELWITHDEBINFO \"-O2 -g\") \n\n# Set global definitions\nadd_definitions(-D_GNU_SOURCE)\n\n# Find external libs\nfind_package(PkgConfig)\n\n# Find Threading lib\nfind_package (Threads REQUIRED)\nfind_package(OpenSSL REQUIRED)\n\n# Find ExternalProject module\ninclude (ExternalProject)\n\n# Used to check contents of header files\ninclude (CheckLibraryExists)\n\n\n# Find libusb \npkg_check_modules(PC_USB QUIET libusb-1.0)\nset(USB_DEFINITIONS ${PC_USB_CFLAGS_OTHER})\n\nfind_path(USB_INCLUDE_DIR libusb-1.0/libusb.h\n HINTS ${PC_USB_INCLUDEDIR} ${PC_USB_INCLUDE_DIRS}\n REQUIRED)\n\nfind_library(USB_LIBRARY NAMES usb-1.0 libusb-1.0\n HINTS ${PC_USB_LIBDIR} ${PC_USB_LIBRARY_DIRS} REQUIRED)\nIF(NOT USB_INCLUDE_DIR)\n MESSAGE(FATAL_ERROR \"Did not find libusb.h. Is libusb-1.0-0-dev installed?\")\nENDIF()\nIF(NOT USB_LIBRARY) \n MESSAGE(FATAL_ERROR \"Did not find libusb-1.0. Please install this using apt-get.\")\nENDIF()\ninclude_directories(${USB_INCLUDE_DIR})\n\n# configure a header file to pass some of the CMake settings to the source code\nconfigure_file (\n \"${PROJECT_SOURCE_DIR}/test_biphase_config.h.in\"\n \"${PROJECT_BINARY_DIR}/include/test_biphase_config.h\"\n )\n\n# add the binary tree to the search path for include files so that we will find test_biphase_config.h\ninclude_directories (\"${PROJECT_BINARY_DIR}\")\n\nset(COMMON_DIR \"${PROJECT_SOURCE_DIR}/../../common\")\nset(SYNCLINK_DIR \"${PROJECT_SOURCE_DIR}/../../external_libs/synclink\")\n\ninclude_directories (\n \"${PROJECT_SOURCE_DIR}/include\"\n \"${COMMON_DIR}/include\"\n \"${SYNCLINK_DIR}\"\n )\n\n\n# add blast objects\nadd_library(blast_obj OBJECT \n ${COMMON_DIR}/blast.c \n ${COMMON_DIR}/include/blast.h\n )\ndefine_file_basename_for_sources(blast_obj)\n\n# add crc objects\nadd_library(crc_obj OBJECT \n ${COMMON_DIR}/crc.c \n ${COMMON_DIR}/include/crc.h\n )\ndefine_file_basename_for_sources(crc_obj)\n\t\nadd_executable (test_biphase \n test_biphase.c\n $<TARGET_OBJECTS:blast_obj>\n $<TARGET_OBJECTS:crc_obj>\n ) \n\ndefine_file_basename_for_sources(test_biphase)\n\ntarget_link_libraries(test_biphase \n ${USB_LIBRARY}\n ssl crypto \n m)\n" }, { "alpha_fraction": 0.6111374497413635, "alphanum_fraction": 0.6229857802391052, "avg_line_length": 31.705427169799805, "blob_id": "459b105828dc7df1b762ecc322db497385476cf1", "content_id": "b802b0b7ac7b9b206b7ac7163012f178422b6792", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4221, "license_type": "no_license", "max_line_length": 96, "num_lines": 129, "path": "/stars/code/networking/connection.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"connection.h\"\n#include <boost/bind.hpp>\n#include <string>\n#include \"../tools/angles.h\"\n#include \"../imaging/commands.h\"\n#include \"../shared/update.h\"\n#include \"../shared/network/packets.h\"\n\n#include \"../tools/quick_cout.h\"\n\n#define XSC_PROTOCOL_VERSION 3\n\n#define shared_packets_from_fc1 (*(Shared::Network::packets_from_fc1.w))\n#define shared_packets_from_fc2 (*(Shared::Network::packets_from_fc2.w))\n\nusing namespace Networking;\nusing boost::asio::ip::tcp;\n\nConnection::Connection(boost::asio::io_service& io_service):\n socket_(io_service),\n write_timer(io_service)\n{\n}\n\nvoid Connection::start()\n{\n xsc_clear_server_data(&server_data);\n xsc_init_server_data(&server_data);\n xsc_clear_client_data(&client_data);\n xsc_zero_command_admins(local_command_admins);\n\n std::string client_address = socket_.remote_endpoint().address().to_string();\n if (strcmp(client_address.c_str(), \"192.168.1.3\") == 0) {\n client_name = client_name_fc1;\n } else if (strcmp(client_address.c_str(), \"192.168.1.4\") == 0) {\n client_name = client_name_fc2;\n } else {\n client_name = client_name_unknown;\n }\n\n write_timer.expires_from_now(boost::posix_time::milliseconds(250));\n write_timer.async_wait(boost::bind(&Connection::write_server_data, shared_from_this()));\n\n first_packet = true;\n read_client_data();\n}\n\ntcp::socket& Connection::socket()\n{\n return socket_;\n}\n\n\n// ----------------\n// write server\n// ----------------\n\nvoid Connection::write_server_data(/*boost::system::error_code& error*/)\n{\n load_server_data();\n server_data.xsc_protocol_version = XSC_PROTOCOL_VERSION;\n boost::asio::async_write(socket_, boost::asio::buffer(&server_data, sizeof(server_data)),\n boost::bind(&Connection::handle_write, shared_from_this(),\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n}\n\nvoid Connection::handle_write(const boost::system::error_code& error, size_t bytes_transferred)\n{\n if (!error) {\n if (client_name == client_name_fc1) {\n shared_packets_from_fc1.time_since_sent.start();\n Shared::Network::packets_from_fc1.share();\n } else if (client_name == client_name_fc2) {\n shared_packets_from_fc2.time_since_sent.start();\n Shared::Network::packets_from_fc2.share();\n }\n write_timer.expires_from_now(boost::posix_time::milliseconds(500));\n write_timer.async_wait(boost::bind(&Connection::write_server_data, shared_from_this()));\n }\n}\n\n\n// ----------------\n// read client\n// ----------------\n\nvoid Connection::read_client_data()\n{\n boost::asio::async_read(socket_, boost::asio::buffer(&client_data, sizeof(client_data)),\n boost::bind(&Connection::handle_read, shared_from_this(),\n boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n}\n\nvoid Connection::handle_read(const boost::system::error_code& error, size_t bytes_transferred)\n{\n if (!error && client_data.xsc_protocol_version == XSC_PROTOCOL_VERSION) {\n\n if (client_data.in_charge) {\n if (first_packet) {\n first_packet = false;\n for (unsigned int i=0; i<xC_num_command_admins; i++) {\n local_command_admins[i].counter = client_data.command_admins[i].counter;\n }\n }\n unload_client_data();\n }\n\n if (client_name == client_name_fc1) {\n shared_packets_from_fc1.time_since_received.start();\n shared_packets_from_fc1.in_charge = client_data.in_charge;\n Shared::Network::packets_from_fc1.share();\n } else if (client_name == client_name_fc2) {\n shared_packets_from_fc2.time_since_received.start();\n shared_packets_from_fc2.in_charge = client_data.in_charge;\n Shared::Network::packets_from_fc2.share();\n }\n\n Shared::update(Shared::ThreadNames::net_client);\n read_client_data();\n }\n}\n\n" }, { "alpha_fraction": 0.5823842287063599, "alphanum_fraction": 0.5930144190788269, "avg_line_length": 31.899999618530273, "blob_id": "b063c185faa0a366a1ad93b711fb2ea40f701517", "content_id": "2304a7758d031a1e013bbdcc6a569df96aa4f8a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1318, "license_type": "no_license", "max_line_length": 83, "num_lines": 40, "path": "/stars/code/tools/correlate.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"correlate.h\"\n#include <algorithm>\n\nusing std::min;\nusing std::max;\n\nvoid Tools::add_single_pixel_correlation(unsigned short indata[], double outdata[],\n int width, int height, int pixel_x, int pixel_y, double pixel_value)\n{\n int u_offset = -pixel_x;\n int v_offset = -pixel_y;\n\n // at umin, u = umin and u_out = umin + u_offset\n // -> if the minimum were when u = 0, then umin = 0\n // -> if the minimum were when u_out = 0, then umin = 0 - u_offset\n int umin = max(0, 0 - u_offset);\n int vmin = max(0, 0 - v_offset);\n\n // at umax, u = umax and u_out = umax + u_offset\n // -> if the maximum were when u = width, then umax = width\n // -> if the maximum were when u_out = width, then umax = width - u_offset\n int umax = min(width, width - u_offset);\n int vmax = min(height, height - v_offset);\n\n int u_out = 0;\n int v_out = 0;\n for(int v=vmin; v<vmax; v++) {\n for(int u=umin; u<umax; u++) {\n u_out = u + u_offset;\n v_out = v + v_offset;\n outdata[v_out*width+u_out] += double(indata[v*width+u])*pixel_value;\n }\n }\n}\n\n" }, { "alpha_fraction": 0.682539701461792, "alphanum_fraction": 0.6970899701118469, "avg_line_length": 25.034482955932617, "blob_id": "aaf39153fd13013d97d6fd554f5eb77969863550", "content_id": "cd63853670afc82f3062e62e6ebbea97b613873a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 757, "license_type": "no_license", "max_line_length": 95, "num_lines": 29, "path": "/stars/code/shared/general/network_reset.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"network_reset.h\"\n#include \"../../parameters/manager.h\"\n\nusing namespace Shared::General;\n\nNetworkReset::NetworkReset()\n{\n reset_now_counter = 0;\n reset_on_lull_enabled = true;\n reset_on_lull_delay = 12.0*60.0;\n device_name = \"\";\n}\n\nvoid NetworkReset::init(Parameters::Manager& params)\n{\n reset_on_lull_enabled = params.general.try_get(\"main.network_reset_on_lull_enabled\", true);\n device_name = params.general.try_get(\"main.network_device_name\", string(\"\"));\n}\n\nNetworkResetStatus::NetworkResetStatus()\n{\n resetting = false;\n}\n\n" }, { "alpha_fraction": 0.5597467422485352, "alphanum_fraction": 0.575046181678772, "avg_line_length": 41.122222900390625, "blob_id": "211eca04b319357fb1489e7071295b2f4f8c2d4a", "content_id": "04c828d680956dcffbb99003d05a0d4ade02cc82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3791, "license_type": "no_license", "max_line_length": 160, "num_lines": 90, "path": "/defricher/defricher_data.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * defricher_data.h: \n *\n * This software is copyright (C) 2013-2014 Seth Hillbrand\n *\n * This file is part of defricher, created for the BLASTPol Project.\n *\n * defricher 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 2 of the License, or\n * (at your option) any later version.\n *\n * defricher 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 defricher; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Apr 3, 2015 by Seth Hillbrand\n */\n\n#ifndef DEFRICHER_DATA_H_\n#define DEFRICHER_DATA_H_\n\n\n#include <stdbool.h>\n#include <time.h>\n\n#include <lookup.h>\n#include <blast_time.h>\n\n#define FILE_HASH 0\n\n#define _DEFRICHER_CACHE_TYPES(x,_) \\\n _(x, fc) \\\n _(x, roach) \\\n _(x, uei)\nBLAST_LOOKUP_TABLE(DEFRICHER_CACHE_TYPE, static);\n\ntypedef struct defricher_file_data\n{\n char *name; /**< name Stream name - filename in the DIRFILE */\n char *desc; /**< desc Description of the channel */\n FILE *fp; /**< fp File pointer to write in DIRFILE */\n off_t offset; /**< offset Current offset (from 0) in the file */\n size_t element_size; /**< element_size Size in bytes of each data value */\n bool is_signed; /**< is_signed if true, the integer is signed */\n bool is_float; /**< is_float if true, the stream is floating pointer */\n uint32_t rate; /**< rate Number of samples per frame (current 1s frames) of the file */\n uint64_t lastval; /**< lastval The last value written to disk (for filling) */\n} defricher_output_file_data_t;\n\n\ntypedef struct defricher_periodic_data\n{\n uint32_t hash; /**< hash The hash (without mods) of the periodic data name */\n struct timespec time; /**< time The starting index of the node. This is EBEX time */\n uint32_t value; /**< value The previous value of the node. If the reading changes from this value, a packet is generated */\n} __attribute__((packed)) defricher_periodic_data_t;\n\ntypedef struct defricher_stream_data\n{\n uint32_t hash; /**< hash The hash (without mods) of the stream name */\n blast_time_t time; /**< time The starting time of the node. */\n uint16_t produced; /**< produced Number of bytes in #buffer ready for compression/downlink */\n uint8_t buffer[]; /**< buffer Holds cached data */\n} __attribute__((packed)) defricher_stream_data_t;\n\ntypedef struct defricher_cache_node\n{\n uint32_t magic; /**< magic The BLAST MAGIC word allowing quick check of type */\n E_DEFRICHER_CACHE_TYPE type;\n defricher_output_file_data_t output;\n union\n {\n void *raw_data;\n uint64_t *_64bit_data;\n uint32_t *_32bit_data;\n uint16_t *_16bit_data;\n defricher_stream_data_t *input_stream;\n defricher_periodic_data_t *input_periodic;\n };\n} defricher_cache_node_t;\n\n\n#endif /* DEFRICHER_DATA_H_ */\n" }, { "alpha_fraction": 0.6934523582458496, "alphanum_fraction": 0.7053571343421936, "avg_line_length": 18.764705657958984, "blob_id": "66da810bf432df0980f852e41a0c506be656fb68", "content_id": "a653cb9d30bc6767bffe079ec629069778e7000f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 337, "license_type": "no_license", "max_line_length": 73, "num_lines": 17, "path": "/stars/code/solving/update.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__UPDATE_H\n#define SOLVING__UPDATE_H\n\nnamespace Solving\n{\n void update_shared();\n bool done();\n}\n\n#endif\n" }, { "alpha_fraction": 0.7204782962799072, "alphanum_fraction": 0.726457417011261, "avg_line_length": 36.22222137451172, "blob_id": "09ba77bc07c9a20a94cb21ad441352252e35aa46", "content_id": "2301aa4f6391eb86b60512a9d26946869e10a23e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 669, "license_type": "no_license", "max_line_length": 91, "num_lines": 18, "path": "/news/news.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#define FIFODEPTH 2048\n\nstruct fifoStruct {\n char d[FIFODEPTH];\n int i_in; // points at next place to write\n int i_out; // points at next place to read\n};\n\nvoid convertToUpper(char *in, char *out);\nvoid convertToLower(char *in, char *out);\nvoid push(struct fifoStruct *fs, char x[], int size);\nvoid peek(struct fifoStruct *fs, char x[], int size);\nvoid pop(struct fifoStruct *fs, char x[], int size);\nvoid advance(struct fifoStruct *fs, int size);\nvoid advance(struct fifoStruct *fs, int size);\nint nFifo(struct fifoStruct *fs);\nint party_connect(char *hostname, int port);\nint BlockingRead(int minRead, struct fifoStruct *fs, int tty_fd, char *hostname, int port);" }, { "alpha_fraction": 0.617201566696167, "alphanum_fraction": 0.620908796787262, "avg_line_length": 37.692623138427734, "blob_id": "d98a90bfafd58f7bb8125f3df43ee9740d2b7f4b", "content_id": "7edb0ceb638d01ce37b51c50a43fac0f810c1564", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9441, "license_type": "no_license", "max_line_length": 135, "num_lines": 244, "path": "/groundhog/groundhog_funcs.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <unistd.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <syslog.h>\n#include <signal.h>\n#include <libgen.h>\n#include <sys/ioctl.h>\n#include <sys/socket.h>\n#include <sys/time.h>\n#include <sys/statvfs.h>\n#include <arpa/inet.h>\n#include <netinet/in.h>\n#include <netinet/tcp.h>\n#include <pthread.h>\n\n#include \"groundhog_funcs.h\"\n\nint verbose = 1;\nint system_idled = 0;\nsigset_t signals;\n\nvoid clean_up(void) {\n unlink(\"/var/run/groundhog.pid\");\n // closelog();\n}\n\nvoid daemonize()\n{\n\tint pid;\n\tFILE* stream;\n\n\tif ((pid = fork()) != 0) {\n\t\tif (pid == -1) {\n\t\t\tgroundhog_fatal(\"unable to fork to background\\n\");\n\t\t}\n\t\tif ((stream = fopen(\"/var/run/groundhog.pid\", \"w\")) == NULL) {\n\t\t\tgroundhog_fatal(\"unable to write PID to disk\\n\");\n\t\t} else {\n\t\t\tfprintf(stream, \"%i\\n\", pid);\n\t\t\tfflush(stream);\n\t\t\tfclose(stream);\n\t\t}\n\t\t// closelog();\n\t\tgroundhog_info(\"PID = %i\\n\", pid);\n\t\texit(0);\n\t}\n\tatexit(clean_up);\n\n\t/* Daemonise */\n\tchdir(\"/\");\n\tfreopen(\"/dev/null\", \"r\", stdin);\n\tfreopen(GROUNDHOG_LOG, \"a\", stdout);\n\tsetvbuf(stdout,NULL,_IONBF,0);\n\tfreopen(\"/dev/null\", \"w\", stderr);\n\tsetsid();\n}\n// -------------------------------------- //\n// --- groundhog_check_for_fileblocks --- //\n// -------------------------------------- //\n/* This function returns non-zero when a file download linklist has been \n * received.\n * \n * ll - the linklist for the received data\n * ll_name - the name of the file download linklist\n * \n */\nint groundhog_check_for_fileblocks(linklist_t * ll, char * ll_name) {\n return (!strcmp(ll->name, ll_name));\n}\n\n// ------------------------------------//\n// --- groundhog_unpack_fileblocks --- //\n// ------------------------------------//\n/* This function unpacks telemetry data that has been downlinked as file blocks,\n * which are packets that comprise parts of a larger file to be assembled by\n * groundhog. If file data is in the telemetry stream, this function will loop\n * through the buffer extracting parts of the files and writing them to disk.\n * \n * ll - the linklist for the received data\n * transmit_size - the size of the buffer received\n * buffer - the buffer received with packed linklist file blocks\n * local_allframe - a pointer to the allframe data\n * - if NULL, allframe data will not be written or extracted\n * filename_str - the prefix for the name of the rawfile to be opened.\n * - a timestamp will be appended to this file name\n * - if NULL, a linklist rawfile will not be created\n * disp_str - in verbose mode, a modifier for the string printed to stdout\n * - if NULL, no string will be printed to stdout\n * ll_rawfile - a pointer to the linklist rawfile pointer\n * - is updated when a new file is created\n * flags - special flags controlling linklist rawfile handling\n * - if GROUNDHOG_OPEN_NEW_RAWFILE, a new linklist rawfile\n * will be opened\n * - if GROUNDHOG_REUSE_VALID_RAWFILE, the last rawfile used\n * that matches the filename_str will be re-opened only if\n * GROUNDHOG_OPEN_NEW_RAWFILE is specified\n * - if GROUNDHOG_EXTRACT_TO_DISK, then the compressed data\n * will be decompressed and extracted to the disk\n * * currently, only file blocks are extracted to disk *\n *\n */\nint groundhog_unpack_fileblocks(linklist_t * ll, unsigned int transmit_size, uint8_t * compbuffer,\n uint8_t * local_allframe, char * filename_str, char * disp_str,\n linklist_rawfile_t ** ll_rawfile, unsigned int flags) {\n\tunsigned int bytes_unpacked = 0;\n\twhile ((bytes_unpacked+ll->blk_size) <= transmit_size) {\n\t\t// write the rawfile to disk \n\t\tgroundhog_process_and_write(ll, ll->blk_size, compbuffer+bytes_unpacked, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlocal_allframe, filename_str, disp_str, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tll_rawfile, flags);\n\t\tbytes_unpacked += ll->blk_size;\n\t}\n\treturn (ll->blocks[0].i*100/ll->blocks[0].n);\n}\n\nvoid groundhog_make_symlink_name(char *fname, char *symname) {\n sprintf(fname, \"%s/%s_live\", archive_dir, symname);\n}\n\n// ------------------------------------//\n// --- groundhog_process_and_write --- //\n// ------------------------------------//\n/* This function unpacks telemetry data that has been downlinked as linklist data.\n * Data will be written to a linklist rawfile with automatic handling of allframe\n * data. The return value will be the current framenumber, where a negative \n * framenumber implies an allframe had been received.\n * \n * ll - the linklist for the received data\n * transmit_size - the size of the buffer received\n * compbuffer - the buffer received with linklist data\n * local_allframe - a pointer to the allframe data\n * - if NULL, allframe data will not be written or extracted\n * filename_str - the prefix for the name of the rawfile to be opened.\n * - a timestamp will be appended to this file name\n * - if NULL, a linklist rawfile will not be created\n * disp_str - in verbose mode, a modifier for the string printed to stdout\n * - if NULL, no string will be printed to stdout\n * ll_rawfile - a pointer to the linklist rawfile pointer\n * - is updated when a new file is created\n * flags - special flags controlling linklist rawfile handling\n * - if GROUNDHOG_OPEN_NEW_RAWFILE, a new linklist rawfile\n * will be opened\n * - if GROUNDHOG_REUSE_VALID_RAWFILE, the last rawfile used\n * that matches the filename_str will be re-opened only if\n * GROUNDHOG_OPEN_NEW_RAWFILE is specified\n *\n */\nint64_t groundhog_process_and_write(linklist_t * ll, unsigned int transmit_size, uint8_t * compbuffer,\n uint8_t * local_allframe, char * filename_str, char * disp_str,\n linklist_rawfile_t ** ll_rawfile, unsigned int flags) {\n // process the linklist and write the data to disk\n int af = read_allframe(NULL, ll->superframe, compbuffer);\n int retval = 0;\n\n if ((flags & GROUNDHOG_OPEN_NEW_RAWFILE) && filename_str) {\n *ll_rawfile = groundhog_open_rawfile(*ll_rawfile, ll, filename_str, flags);\n }\n\n if (af > 0) { // an allframe was received\n if (verbose && disp_str) groundhog_info(\"[%s] Received an allframe :)\\n\", disp_str);\n if (local_allframe) memcpy(local_allframe, compbuffer, ll->superframe->allframe_size);\n\n if (*ll_rawfile) retval = tell_linklist_rawfile(*ll_rawfile)*-1;\n else retval = 0;\n } else if (af == 0) { // just a regular frame (< 0 indicates problem reading allframe)\n if (verbose && disp_str) groundhog_info(\"[%s] Received linklist \\\"%s\\\"\\n\", disp_str, ll->name);\n\n // check for consistency in transmit size with linklist bulk size\n if (transmit_size > ll->blk_size) {\n groundhog_warn(\"groundhog_process_and_write: Packet size mismatch blk_size=%d, transmit_size=%d\\n\", ll->blk_size, transmit_size);\n transmit_size = ll->blk_size;\n }\n\n // write the linklist data to disk\n if (ll_rawfile) {\n write_linklist_rawfile_with_allframe(*ll_rawfile, compbuffer, local_allframe);\n flush_linklist_rawfile(*ll_rawfile);\n\n retval = tell_linklist_rawfile(*ll_rawfile);\n }\n\t\t// unpack and extract to disk\n // only extracting file blocks to disk at the moment\n if (flags & GROUNDHOG_EXTRACT_TO_DISK) {\n int id = 1-ll->internal_id;\n\t\t decompress_linklist_internal(id, ll, compbuffer);\n }\n }\n return retval;\n}\n\nlinklist_rawfile_t * groundhog_open_rawfile(linklist_rawfile_t * ll_rawfile, linklist_t *ll, char * symname, int flags) {\n if (ll_rawfile) {\n close_and_free_linklist_rawfile(ll_rawfile);\n ll_rawfile = NULL;\n } \n char sname[LINKLIST_MAX_FILENAME_SIZE];\n char filename[LINKLIST_MAX_FILENAME_SIZE];\n int newfile = 1;\n\n\tgroundhog_make_symlink_name(sname, symname);\n\n if (flags & GROUNDHOG_REUSE_VALID_RAWFILE) { // option to reuse file, so check symlink\n // do a search for the linklist format\n\t\tstrcat(sname, LINKLIST_FORMAT_EXT);\n\n // if path exists, check if serials match\n\t\tif (realpath(sname, filename)) { \n\t\t\tuint32_t serial = read_linklist_formatfile_comment(filename, LINKLIST_FILE_SERIAL_IND, \"%x\");\n\t\t\tif (serial == *(uint32_t *) ll->serial) {\n // serials match, so don't need to make a new file\n\t\t\t\tnewfile = 0;\n\t\t\t} \n\t\t} \n // undo strcat on sname \n char * ext = strstr(sname, LINKLIST_FORMAT_EXT);\n if (ext) ext[0] = '\\0';\n }\n\n if (newfile) {\n // make a new filename\n make_linklist_rawfile_name(ll, filename);\n groundhog_info(\"Opening new file \\\"%s\\\"\\n\", filename);\n } else {\n // remove the file extension from the existing filename\n char * ext = strstr(filename, LINKLIST_FORMAT_EXT);\n if (ext) ext[0] = '\\0';\n groundhog_info(\"Opening existing file \\\"%s\\\"\\n\", filename);\n }\n \n // open the rawfile and create symlinks\n ll_rawfile = open_linklist_rawfile(filename, ll);\n create_rawfile_symlinks(ll_rawfile, sname);\n\n // generate the calspecs file\n sprintf(sname, \"%s\" CALSPECS_FORMAT_EXT, filename);\n groundhog_write_calspecs(sname);\n\n return ll_rawfile;\n}\n" }, { "alpha_fraction": 0.5322580933570862, "alphanum_fraction": 0.5483871102333069, "avg_line_length": 28.445833206176758, "blob_id": "44462b7e265a97d3e50ea103339ee8d40d00f63e", "content_id": "c1bd68102c3579163ca0efde3dad71491bdcba78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7069, "license_type": "no_license", "max_line_length": 126, "num_lines": 240, "path": "/stars/code/solving/finding/estimator.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"estimator.h\"\n#if defined(_MSC_VER)\n #include <windows.h>\n#endif\n#include <list>\n#include <vector>\n#include <limits>\n#include <algorithm>\n#include \"../blob.h\"\n#include \"../../tools/math.h\"\n#include \"../../shared/image/raw.h\"\n#include \"../../shared/solving/settings.h\"\n#include \"../logger.h\"\n\nusing namespace Solving::Finding;\nusing Solving::Blob;\nusing std::min;\nusing std::max;\n\n#define shared_settings (*(Shared::Solving::settings.r))\n\nstruct neighbor\n{\n double mean;\n double stdev;\n};\n\nvoid Estimator::get_square_stats(Shared::Image::Raw& image, int square_u, int square_v,\n int halfwidth, double& mean, double& stdev, bool& valid, int& numvals, bool include_center)\n{\n int umin, umax, vmin, vmax = 0;\n double flux = 0;\n\n int padding=1;\n umin = max(square_u-halfwidth, padding);\n umax = min(square_u+halfwidth, image.width-1-padding);\n vmin = max(square_v-halfwidth, padding);\n vmax = min(square_v+halfwidth, image.height-1-padding);\n\n flux = 0;\n numvals = 0;\n for (int v=vmin; v<=vmax; v++) {\n for (int u=umin; u<=umax; u++) {\n if (include_center || (u != square_u || v != square_v)) {\n flux += image.pixels[v*image.width+u];\n numvals++;\n }\n }\n }\n if (numvals < 2) {\n valid = false;\n return;\n }\n mean = flux / numvals;\n stdev = 0.0;\n for (int v=vmin; v<=vmax; v++) {\n for (int u=umin; u<=umax; u++) {\n if (include_center || (u != square_u || v != square_v)) {\n stdev += pow(image.pixels[v*image.width+u] - mean, 2);\n }\n }\n }\n stdev = sqrt( stdev/(numvals-1) );\n valid = true;\n return;\n\n}\n\nvoid Estimator::estimate_flux_and_stdev(Shared::Image::Raw& image, int u, int v, int hw,\n double& flux, double& stdev, double& prob_of_something)\n{\n double neighbor_mean = 0.0;\n double neighbor_stdev = 0.0;\n double base = 0.0;\n bool valid = false;\n int num_vals = 0;\n\n unsigned int num_neighbors = 0;\n for (int j=-1; j<=1; j++) {\n for (int i=-1; i<=1; i++) {\n if (i!=0 || j!=0) {\n get_square_stats(image, u+i*(2*hw+1), v+j*(2*hw+1), hw, neighbor_mean, neighbor_stdev, valid, num_vals, true);\n if (valid && num_neighbors<8 && num_vals>0) {\n neighbor_means[num_neighbors] = neighbor_mean;\n neighbor_stdevs[num_neighbors] = max(neighbor_stdev, 0.5/double(num_vals));\n num_neighbors++;\n }\n }\n }\n }\n\n if (num_neighbors >= 2) {\n unsigned int i0 = -1;\n unsigned int i1 = -1;\n double mean0 = -std::numeric_limits<double>::infinity();\n double mean1 = -std::numeric_limits<double>::infinity();\n for (unsigned int i=0; i<num_neighbors; i++) {\n if (neighbor_means[i] > mean1) {\n i1 = i;\n mean1 = neighbor_means[i];\n }\n if (mean1 > mean0) {\n std::swap(mean0, mean1);\n std::swap(i0, i1);\n }\n }\n base = (neighbor_means[i0] + neighbor_means[i1])/2.0;\n stdev = (neighbor_stdevs[i0] + neighbor_stdevs[i1])/2.0;\n }\n else if (num_neighbors == 1) {\n base = neighbor_means[0];\n stdev = neighbor_stdevs[0];\n }\n else {\n prob_of_something = 0.0;\n return;\n }\n\n double center_mean = 0.0;\n double center_stdev = 0.5;\n get_square_stats(image, u, v, hw, center_mean, center_stdev, valid, num_vals, false);\n if (!valid) {\n prob_of_something = 0.0;\n return;\n }\n flux = max(0.0, (center_mean - flux)*num_vals);\n\n double effective_sigma = stdev / sqrt(double(num_vals));\n prob_of_something = max(0.0, (center_mean-base)/effective_sigma);\n}\n\nvoid Estimator::calculate_basic_flux_and_base(Shared::Image::Raw& image, Blob& blob)\n{\n\n int hw;\n int umin, umax, vmin, vmax;\n double blob_width_squared, distance_squared;\n\n double approximate_size = max(blob.approximate_size, 4.0);\n blob_width_squared = pow(approximate_size*1.5, 2.);\n hw = int(round(approximate_size*3.0));\n umin = max(blob.u-hw, 0);\n umax = min(blob.u+hw, image.width);\n vmin = max(blob.v-hw, 0);\n vmax = min(blob.v+hw, image.height);\n\n double base = 0.0;\n double flux = 0.0;\n int base_counter = 0;\n int flux_counter = 0;\n bool saturated = false;\n double peak = 0.0;\n for (int u=umin; u<umax; u++) {\n for (int v=vmin; v<vmax; v++) {\n if (image.pixels[v*image.width+u] >= (image.depth-1)) {\n saturated = true;\n }\n if (image.pixels[v*image.width+u] > peak) {\n peak = image.pixels[v*image.width+u];\n }\n distance_squared = pow(double(u-blob.u), 2) + pow(double(v-blob.v), 2);\n if (distance_squared < blob_width_squared) {\n flux += image.pixels[v*image.width+u];\n flux_counter++;\n }\n else {\n base += image.pixels[v*image.width+u];\n base_counter++;\n }\n }\n }\n blob.saturated = saturated;\n if (base_counter > 0) {\n blob.base = base/base_counter;\n }\n else {\n logger.log(\"finder: estimator: warning: base not estimated\");\n blob.base = 0.0;\n }\n blob.peak = peak - blob.base;\n blob.flux = flux - (blob.base*flux_counter);\n blob.peak_to_flux = 0.0;\n if (blob.flux > 0.0) {\n blob.peak_to_flux = blob.peak / blob.flux;\n }\n blob.snr = blob.flux / blob.noise;\n}\n\nBlob Estimator::estimate_blob(Shared::Image::Raw& image, Blob& blob, bool& valid) {\n std::list<Blob> blobs;\n double flux, sigma, confidence_metric;\n bool saturated = false;\n\n int minhw = 2;\n int maxhw = 4;\n if (shared_settings.robust_mode_enabled) {\n maxhw = 15;\n }\n\n for (int hw=minhw; hw<maxhw; hw+=1) {\n estimate_flux_and_stdev(image, blob.u, blob.v, hw, flux, sigma, confidence_metric);\n\n Blob new_blob;\n new_blob.u = blob.u;\n new_blob.v = blob.v;\n new_blob.correlated_peak = blob.correlated_peak;\n new_blob.flux = flux;\n new_blob.approximate_size = hw;\n new_blob.base = 0.0;\n new_blob.noise = sigma;\n new_blob.flux_confidence = confidence_metric;\n new_blob.saturated = saturated;\n blobs.push_back(new_blob);\n }\n\n blobs.sort(Blob::sort_by_flux_confidence);\n Blob return_blob;\n return_blob = *blobs.begin();\n\n if (return_blob.flux_confidence > 4.0) {\n valid = true;\n }\n else {\n valid = false;\n }\n calculate_basic_flux_and_base(image, return_blob);\n if (return_blob.snr >= shared_settings.snr_threshold) {\n valid = true;\n }\n else {\n valid = false;\n }\n return return_blob;\n}\n\n" }, { "alpha_fraction": 0.6107056140899658, "alphanum_fraction": 0.6155717968940735, "avg_line_length": 20.421052932739258, "blob_id": "f457c3dd7ef81740bcc23c6ed98308552d952307", "content_id": "0172e31f34d8135ec35f61c88b4f4d1e81f4b8bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 411, "license_type": "no_license", "max_line_length": 62, "num_lines": 19, "path": "/test_programs/synclink/support/Makefile", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": " #DEBUG=1\n \n CFLAGS := -Wall -Wstrict-prototypes -fomit-frame-pointer\n ifdef DEBUG\n CFLAGS += -g -O\n else\n CFLAGS += -O2\n endif\n \n all : test_biphase\n \ntest_biphase: test_biphase_noblast.c ./synclink.h\n\t\t gcc $(CFLAGS) -I ../ -o test_biphase test_biphase_noblast.c\n \n CLEAN_TARGETS = *~ core test_biphase *.o\n clean:\n\t\t @for f in $(CLEAN_TARGETS) ; do \\\n\t\t\t find . -name \"$$f\" | xargs rm -f ; \\\n\t\t done;\n \n\n" }, { "alpha_fraction": 0.7466216087341309, "alphanum_fraction": 0.7601351141929626, "avg_line_length": 48.33333206176758, "blob_id": "8f6f1c4af225034ee590b0c19d346f9bf5379865", "content_id": "6db0efbfaba5da2c0423a02bb39c36a93fdaec1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 296, "license_type": "no_license", "max_line_length": 73, "num_lines": 6, "path": "/upload_linklists.sh", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\nsudo rsync -avz --delete blast_config/linklists/ /data/etc/linklists/\nrsync -avz --delete blast_config/linklists/ fc1:/data/etc/linklists/\nrsync -avz --delete blast_config/linklists/ fc2:/data/etc/linklists/\n#rsync -avz --delete blast_config/linklists fc1user@fc1mustang:/data/etc/\n" }, { "alpha_fraction": 0.6993111968040466, "alphanum_fraction": 0.7217729687690735, "avg_line_length": 28.03478240966797, "blob_id": "3f39442c6145977f110a431bbb150d38deeaf121", "content_id": "7586dbb183dfeab0c8d5a7f3eb06b68053ecf1b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3339, "license_type": "no_license", "max_line_length": 80, "num_lines": 115, "path": "/common/include/netcmd.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* narsil: groundstation BLAST command software\n *\n * This software is copyright (C) 2005 University of Toronto\n * \n * This file 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 2 of the License, or\n * (at your option) any later version.\n * \n * This file 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 blastcmd; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#ifndef NETCMD_H\n#define NETCMD_H\n\n/* OSX doesn't support MSG_NOSIGNAL (it never signals) */\n#ifdef __APPLE__\n#include <sys/socket.h>\n#ifndef MSG_NOSIGNAL\n#define MSG_NOSIGNAL 0\n#endif\n#endif\n#include <sys/types.h>\n\n/*\n * Definition of command structures (formerly in command_list.h)\n */\n#define MAX_N_PARAMS 14 /* narsil REALLY likes this to be even */\n#define CMD_STRING_LEN 32 /* max length of command string */\n#define SIZE_NAME 80 /* max length for command name, */\n#define SIZE_ABOUT 80 /* ... description, */\n#define SIZE_PARNAME 80 /* ... and paramenter name */\n#define SIZE_CMDPARNAME (SIZE_NAME+SIZE_PARNAME+2)\n#define CONFIRM 0x80000000 /* group bit if command needs confirm */\n\n#define DEF_NOT_FOUND (-9999.0)\n\n#pragma pack(4) //32-bit and 64-bit sytems disagree on packing\nstruct scom {\n int command; //really enum singleCommand where appropriate\n char name[SIZE_NAME];\n char about[SIZE_ABOUT];\n unsigned int group;\n};\n\nstruct par {\n char name[SIZE_PARNAME];\n double min;\n double max;\n char type;\n char field[20];\n union {\n const char **nt; /* name look-up for integer parameters; NULL teriminated */\n unsigned long long strut; /* for 32-/64-bit compatiblity */\n };\n int index_serial;\n};\n\nstruct mcom {\n int command; //really enum multiCommand where appropriate\n char name[SIZE_NAME];\n char about[SIZE_ABOUT];\n unsigned int group;\n char numparams;\n struct par params[MAX_N_PARAMS];\n};\n#pragma pack() //return to default packing\n\n/*\n * Client (blastcmd, narsil) interface to NetCmd protocol\n * Server interface located in blastcmd's daemon.c\n *\n */\n#define SOCK_PORT 41414\n\n#define CMD_NONE 0\n#define CMD_ERRR 1\n#define CMD_USER 2\n#define CMD_PING 3\n#define CMD_LURK 4\n#define CMD_LIST 5\n#define CMD_CONN 6\n#define CMD_BCMD 7\n#define CMD_LIMT 8\n#define CMD_SENT 9\n\nextern unsigned short client_n_scommands;\nextern unsigned short client_n_mcommands;\nextern struct scom *client_scommands;\nextern struct mcom *client_mcommands;\nextern char client_command_list_serial[1024];\n\nextern int client_n_groups;\nextern char **client_group_names;\n\nint NetCmdConnect(const char*, int, int);\nvoid NetCmdDrop(void);\nvoid NetCmdSend(const char*);\nint NetCmdReceive(int, size_t, char*);\nint NetCmdSendAndReceive(const char*, int, size_t, char*);\nint NetCmdGetCmdList(void);\nint NetCmdGetGroupNames(void);\nint NetCmdTakeConn(int);\nint NetCmdGetDefault(double *val, const char *cmdstr);\nconst char* NetCmdBanner(void);\nint NetCmdPing(void);\n#endif\n" }, { "alpha_fraction": 0.6463009119033813, "alphanum_fraction": 0.6612635254859924, "avg_line_length": 30.657894134521484, "blob_id": "530b0a5eea7679ff414eeaffdb1045aa9d9172ef", "content_id": "af618ab27dcc727464a89c498f97808a2e9bbbaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4812, "license_type": "no_license", "max_line_length": 147, "num_lines": 152, "path": "/scripts_gse/sonos_mon.py", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport time\nimport numpy as np\nfrom datetime import datetime\nimport pygetdata as gd\nimport soco\n\nDEVICE_ADDRESS = \"192.168.0.140\"\nDATAFILE = \"/data/etc/mole.lnk\"\n\nsonos = soco.SoCo(DEVICE_ADDRESS)\n#sonos = soco.discovery.any_soco()\ndf = gd.dirfile(DATAFILE, gd.RDONLY)\n\n# find the tracks\n\ndef get_current_track_title():\n return sonos.get_current_track_info()['title']\n\nclass AutoSonos:\n def __init__(self, trackname, fieldname, trueval=None):\n self.trackname = trackname\n self.fieldname = fieldname\n self.trueval = trueval\n self.timeout = 0\n self.lastval = 0\n self.framenum = 0\n self.changed = False\n self.timesteady = 0\n\n self.update()\n self.track = sonos.music_library.get_tracks(search_term=self.trackname)[0]\n\n # Checks to see if there is new data in the dirfile\n # Increments a timeout when there is no new data\n def has_update(self):\n num = df.eof(self.fieldname)\n retval = False\n if (num != self.framenum):\n self.timeout = 0\n retval = True\n else:\n self.timeout += 1\n self.framenum = num\n return retval\n\n # General command to be called always in the loop\n # Loads data from dirfile if necessary\n def update(self):\n if (self.has_update()):\n val = df.getdata(self.fieldname,\n first_frame=0,\n first_sample=self.framenum-1,\n num_frames=0,\n num_samples=1)[0]\n if (val != self.lastval):\n self.changed = True\n self.timesteady = 0\n else:\n self.changed = False\n self.timesteady += 1\n self.lastval = val \n\n # Queues the assigned song\n # If the song is already playing, doesn't try to play again \n # If persist=True, will play even if queue is stopped\n def trigger(self, persist=True, volume=None):\n if (get_current_track_title() != self.track.title) or (persist and sonos.get_current_transport_info()['current_transport_state'] != 'PLAYING'):\n if (sonos.get_current_transport_info()['current_transport_state'] == 'PLAYING'): sonos.pause()\n sonos.add_to_queue(self.track, 1) # add to queue indexing by 1\n sonos.play_from_queue(0, True) # play from queue indexing from 0\n if volume is not None:\n sonos.ramp_to_volume(volume)\n print(\"Playing \" + self.track.title)\n return 1\n return 0\n\n # Checks if the value in the dirfile has reached the assigned value\n def truestate(self):\n return self.lastval == self.trueval\n\n\n# Looks at field \"STATE_POTVALVE\" and .truestate() == True when STATE_POTVALVE == 1\n# When the .trigger() function is called, will play the requested song on the SONOS\nPotvalveOpen = AutoSonos(\"Flagpole Sitta\", \"STATE_POTVALVE\", 1)\nPotvalveOpen2 = AutoSonos(\"Ooh Pot Valve Open\", \"STATE_POTVALVE\", 1)\nPotvalveYell = True\nPotvavleSong = False\n\nHWPMove = AutoSonos(\"You Spin Me Round\", \"MOVE_STAT_HWPR\", 1)\n\nLunch = AutoSonos(\"Sandstorm\", \"TIME\")\nLeave = AutoSonos(\"End of the World as\", \"TIME\")\n\nwhile True:\n song_requested = False\n\n # Potvalve open\n # Logic is in the main loop\n PotvalveOpen.update() # must always be called in the loop\n \n # If the truestate is reached and has been true for 20 second, then trigger the song\n if (PotvalveOpen2.truestate() and (PotvalveOpen.timesteady >= 20) and (PotvalveYell == True)):\n print(\"Potvalve is OPEN!\")\n if not song_requested: \n PotvalveOpen.trigger()\n song_requested = True\n PotvalveYell = False\n PotvavleSong = True\n\n # If the truestate is reached and has been true for 20 second, then trigger the song\n if (PotvalveOpen.truestate() and (PotvalveOpen.timesteady >= 20) and (PotvalveSong == True)):\n print(\"Potvalve is OPEN!\")\n if not song_requested: \n PotvalveOpen.trigger()\n song_requested = True\n PotvalveYell = True\n PotvavleSong = False\n\n # If the HWP move state is 1 we are in state \"ready\" so we are sending a move command\n if (HWPMove.truestate()):\n print(\"Half-wave plate is moving!\")\n if not song_requested:\n HWPMove.trigger()\n song_requested = True\n\n # time to leave\n Leave.update()\n date = datetime.utcfromtimestamp(Leave.lastval)\n if ((date.hour+13)%24 == 17) and (15 <= date.minute <= 25):\n print(\"Time to leave!\")\n if not song_requested: \n Leave.trigger(volume=65)\n song_requested = True\n\n # lunch\n Lunch.update()\n date = datetime.utcfromtimestamp(Lunch.lastval)\n if ((date.hour+13)%24 == 11) and (date.minute >= 56) and (date.second >= 17) and (datetime.today().isoweekday() != 7):\n print(\"Lunchtime!\")\n if not song_requested: \n Lunch.trigger(volume=50)\n song_requested = True\n\n\n # reload the datafile if necessary\n if (Lunch.timeout > 5):\n df.close()\n df = gd.dirfile(DATAFILE, gd.RDONLY)\n print(\"Reloading \\\"\" + DATAFILE + \"\\\"\")\n\n time.sleep(1)\n" }, { "alpha_fraction": 0.5740511417388916, "alphanum_fraction": 0.5950907468795776, "avg_line_length": 24.925132751464844, "blob_id": "39c2ed9c70cbe35a096b4af39ffafd8c4233d78e", "content_id": "0306dfd1f5b86f9a9b4b3854b98c8c10b51bf20a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4848, "license_type": "no_license", "max_line_length": 79, "num_lines": 187, "path": "/common/quendiclient.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* quendiclient: quendi client routines\n *\n * This software is copyright (C) 2004-2005 D. V. Wiebe\n * \n * This 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 2 of the License, or\n * (at your option) any later version.\n * \n * This software 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 this software; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <stdlib.h> /* ANSI C std library (atoi) */\n#include <arpa/inet.h> /* IP4 specification (inet_aton, inet_ntoa) */\n#include <errno.h> /* ANSI C library errors (errno) */\n#include <netinet/in.h> /* For IPPROTO_TCP */\n#include <netinet/tcp.h> /* For TCP_NODELAY */\n#include <netdb.h> /* DNS queries (gethostbyname, hstrerror, h_errno) */\n#include <string.h> /* ANSI C strings (strcat, strdup, &c.) */\n#include <unistd.h> /* UNIX std library (read, write, close, sleep) */\n\n#include \"blast.h\"\n#include \"quenya.h\"\n\n#define QUENDI_PORT 44144\n\nint GetServerResponse(int sock, char* buffer)\n{\n static char extra[2000] = \"\";\n char cbuf[4000];\n char* ptr;\n int n, overrun;\n char* response;\n\n// if (buffer != NULL) printf(\"<-- %s\\n\", buffer);\n\n strcpy(cbuf, extra);\n response = cbuf + strlen(cbuf);\n \n if (strchr(cbuf, '\\n') == NULL) {\n n = read(sock, response, 2000);\n\n if (n < 0)\n berror(fatal, \"Read error\");\n\n if (n == 0 && errno != EAGAIN) {\n blast_err(\"Unexpected server disconnect.\\n\");\n return -3;\n }\n\n response[1999] = 0;\n } else\n n = 0;\n\n for (ptr = cbuf; *ptr; ++ptr)\n if (*ptr == '\\r') {\n *ptr = '\\0';\n overrun = n - (ptr - response) - 2;\n if (overrun > 0) {\n memcpy(extra, ptr + 2, overrun);\n extra[n - (ptr - response) - 2] = 0;\n } else\n extra[0] = 0;\n\n break;\n }\n\n if (buffer != NULL)\n strcpy(buffer, cbuf);\n\n if (cbuf[3] != ' ')\n return -2;\n\n n = atoi(cbuf);\n\n// printf(\"--> %s\\n\", cbuf);\n\n if (n == 0)\n blast_fatal(\"Indecypherable server response: %s\\n\", cbuf);\n\n if (buffer != NULL)\n strcpy(buffer, cbuf + 4);\n\n return n;\n}\n\nint MakeSock(void)\n{\n int sock, n;\n\n if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)\n berror(fatal, \"socket\");\n\n n = 1;\n if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) != 0)\n berror(fatal, \"setsockopt\");\n\n n = 1;\n if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &n, sizeof(n)) != 0)\n berror(fatal, \"setsockopt\");\n\n return sock;\n}\n\nint OpenDataPort(int csock, const struct sockaddr_in *rc_addr, int* dsock)\n{\n char buffer[2000];\n int n;\n char *ptr1 = NULL, *ptr2;\n struct sockaddr_in dp_addr;\n\n *dsock = MakeSock();\n strcpy(buffer, \"OPEN\\r\\n\");\n if (write(csock, buffer, strlen(buffer)) < 0)\n berror(err, \"Failed to write to socket\");\n switch (n = GetServerResponse(csock, buffer)) {\n case -3:\n return -1;\n case QUENYA_RESPONSE_LISTENING:\n for (ptr1 = buffer; *ptr1 != '@'; ++ptr1);\n *(ptr1++) = 0;\n for (ptr2 = ptr1; *ptr2 != ':'; ++ptr2);\n *(ptr2++) = 0;\n *(strchr(ptr2, ' ')) = 0;\n\n memcpy(&dp_addr, rc_addr, sizeof(dp_addr));\n dp_addr.sin_family = AF_INET;\n dp_addr.sin_port = htons(atoi(ptr2));\n// inet_aton(ptr1, &dp_addr.sin_addr);\n sleep(1);\n\n if ((n = connect(*dsock, (struct sockaddr*)&dp_addr, sizeof(dp_addr)))\n != 0)\n berror(fatal, \"d-Connect failed\");\n break;\n default:\n blast_fatal(\"Unexpected response from server after OPEN: %i\\n\", n);\n return -1;\n }\n\n switch (n = GetServerResponse(csock, buffer)) {\n case -3: /* disconnect */\n return -1;\n case QUENYA_RESPONSE_PORT_OPENED:\n break;\n default:\n blast_err(\"Unexpected response from server after OPEN/2: %i\\n\", n);\n return -1;\n }\n\n return 0;\n}\n\nconst char* ResolveHost(const char* host, struct sockaddr_in* addr, int forced)\n{\n struct hostent* the_host;\n char* ptr;\n\n if ((ptr = strchr(host, ':')) != NULL) {\n if ((addr->sin_port = htons(atoi(ptr + 1))) == htons(0))\n addr->sin_port = htons(QUENDI_PORT);\n *ptr = '\\0';\n } else\n addr->sin_port = htons(QUENDI_PORT);\n\n the_host = gethostbyname(host);\n\n if (the_host == NULL) {\n if (forced)\n blast_fatal(\"host lookup failed: %s\\n\", hstrerror(h_errno));\n\n return hstrerror(h_errno);\n }\n\n addr->sin_family = AF_INET;\n memcpy(&(addr->sin_addr.s_addr), the_host->h_addr, the_host->h_length);\n\n return NULL;\n}\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6768447756767273, "avg_line_length": 25.200000762939453, "blob_id": "d05c8b3ad21e0f4a512ce36fc3d6d533c5cfbdaf", "content_id": "a659693aa05fefc0ec94a2b03307e887798741c5", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Shell", "length_bytes": 393, "license_type": "no_license", "max_line_length": 61, "num_lines": 15, "path": "/guaca/configure", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#!/bin/sh\necho This script ignores all parameters.\necho To change where guaca will be installed, edit guaca.pro!\necho\nopt=\"\"\nif [ \"x`which qmake 2>/dev/null`\" != \"x\" ]; then\n echo \"executing: \\\"qmake $opt\\\"\"\n qmake $opt || exit 1\nelse\n echo \"ERROR: Can't find qmake-qt4 nor qmake in your path!\"\n exit 1\nfi\necho \necho Great! That seemed to work.\necho Now run \\\"make\\\" and \\\"make install\\\"!\n" }, { "alpha_fraction": 0.7078189253807068, "alphanum_fraction": 0.7242798209190369, "avg_line_length": 25.88888931274414, "blob_id": "5dc009e3882775481fec85fb9fcbe6e4f2f46b53", "content_id": "c43a5ad73a6fa4d22e7fce0cbf9aeb2a6e766e41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 244, "license_type": "no_license", "max_line_length": 73, "num_lines": 9, "path": "/stars/code/shared/result.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"result.h\"\n\nusing namespace Shared;\n\n" }, { "alpha_fraction": 0.6283213496208191, "alphanum_fraction": 0.6395748853683472, "avg_line_length": 30.058252334594727, "blob_id": "d7ba5f399c6a0d70ce88170b3e5de1012f204798", "content_id": "9cfefe82a2ef26fa8ecc2120e64d332bfa2304bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3199, "license_type": "no_license", "max_line_length": 106, "num_lines": 103, "path": "/groundhog/blast/pilot.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <math.h>\n#include <stdbool.h>\n#include <arpa/inet.h> // socket stuff\n#include <netinet/in.h> // socket stuff\n#include <stdio.h> // socket stuff\n#include <sys/types.h> // socket types\n#include <sys/socket.h> // socket stuff\n#include <sys/stat.h>\n#include <dirent.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <signal.h>\n#include <stdlib.h>\n#include <string.h>\n#include <pthread.h> // threads\n#include <openssl/md5.h>\n#include <float.h>\n#include <time.h>\n#include <sys/time.h>\n\n#include \"groundhog_funcs.h\"\n#include \"bitserver.h\"\n\nstruct TlmReport pilot_report = {0};\n\nvoid udp_receive(void *arg) {\n\n struct UDPSetup * udpsetup = (struct UDPSetup *) arg;\n\n struct BITRecver udprecver = {0};\n uint8_t * recvbuffer = NULL;\n uint32_t serial = 0, prev_serial = 0;\n linklist_t * ll = NULL;\n int32_t blk_size = 0;\n uint32_t recv_size = 0;\n uint32_t transmit_size = 0;\n int64_t framenum = 0;\n int af = 0;\n\n uint8_t *local_allframe = calloc(1, superframe->allframe_size);\n\n // open a file to save all the raw linklist data\n linklist_rawfile_t * ll_rawfile = NULL;\n\n uint8_t * compbuffer = calloc(1, udpsetup->maxsize);\n\n // initialize UDP connection via bitserver/BITRecver\n initBITRecver(&udprecver, udpsetup->addr, udpsetup->port, 10, udpsetup->maxsize, udpsetup->packetsize);\n\n int bad_serial_count = 0;\n\n while (true) {\n do {\n // get the linklist serial for the data received\n recvbuffer = getBITRecverAddr(&udprecver, &recv_size);\n serial = *(uint32_t *) recvbuffer;\n if (!(ll = linklist_lookup_by_serial(serial))) {\n removeBITRecverAddr(&udprecver);\n if (verbose) groundhog_info(\"[%s] Receiving bad serial packets (0x%x)\\n\", udpsetup->name, serial);\n bad_serial_count++;\n } else {\n bad_serial_count = 0;\n break;\n }\n } while (true);\n\n // set the linklist serial\n setBITRecverSerial(&udprecver, serial);\n\n // receive the data from payload via bitserver\n blk_size = recvFromBITRecver(&udprecver, compbuffer, udpsetup->maxsize, 0);\n if (blk_size < 0) {\n groundhog_info(\"Malformed packed received on Pilot\\n\");\n continue;\n }\n\n // hijacking frame number for transmit size\n transmit_size = udprecver.frame_num; \n\n if (groundhog_check_for_fileblocks(ll, FILE_LINKLIST)) {\n // unpack and extract to disk\n framenum = groundhog_unpack_fileblocks(ll, transmit_size, compbuffer, NULL,\n NULL, NULL, NULL, GROUNDHOG_EXTRACT_TO_DISK);\n } else { // write the linklist data to disk\n // set flags for data extraction\n unsigned int flags = 0;\n if (serial != prev_serial) flags |= GROUNDHOG_OPEN_NEW_RAWFILE;\n prev_serial = serial;\n\n // process the linklist and write the data to disk\n framenum = groundhog_process_and_write(ll, transmit_size, compbuffer, local_allframe,\n udpsetup->name, udpsetup->name, &ll_rawfile, flags);\n }\n\n // fill out the telemetry report\n pilot_report.ll = ll;\n pilot_report.framenum = abs(framenum); \n pilot_report.allframe = af; \n\n memset(compbuffer, 0, udpsetup->maxsize);\n \n }\n}\n" }, { "alpha_fraction": 0.5123791694641113, "alphanum_fraction": 0.5312426090240479, "avg_line_length": 25.506250381469727, "blob_id": "c7ed90ee08a6ddab4f557c1a09fc4488c9eb4569", "content_id": "73d45492c869f26530a4b50e414c934353fe64e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4241, "license_type": "no_license", "max_line_length": 89, "num_lines": 160, "path": "/common/slowdl.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* slowdl.c: contains code for handling th 255 byte packets\n *\n * This software is copyright (C) 2013 University of Toronto\n *\n * This file is part of mcp/pcm licensed under the GNU General Public License.\n *\n * You should have received a copy of the GNU General Public License\n * along with this software; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n#include <math.h>\n\n#include \"blast.h\"\n\n#include \"slowdl.h\"\n#include \"tx.h\"\n\n\nextern struct SlowDlStruct slowDLList[];\n\nint slow_dl_read_index = 0;\n\n// read and store the data for use by the writer thread.\n// this runs in the main loop.\nvoid updateSlowDL() {\n int i_ch;\n static int first_time = 1;\n int i_w;\n\n if (first_time) {\n int size = 0;\n for (i_ch = 0; slowDLList[i_ch].name[0] != '\\0'; i_ch++) {\n slowDLList[i_ch].bi0s = channels_find_by_name(slowDLList[i_ch].name);\n switch (slowDLList[i_ch].type) {\n case 'c':\n size++;\n break;\n case 's':\n case 'u':\n size += 2;\n break;\n case 'S':\n case 'U':\n size += 4;\n break;\n default:\n blast_fatal(\"%c: unknown var type in slow dl field %s\",\n slowDLList[i_ch].type, slowDLList[i_ch].name);\n break;\n }\n if (size > 255) {\n blast_fatal(\"slow downlink structure too large (%d > 255)\", size);\n }\n }\n blast_info(\"slow downlink packet %d/255\", size);\n first_time = 0;\n }\n\n i_w = slow_dl_read_index+1;\n if (i_w == 3) i_w = 0;\n\n for (i_ch = 0; slowDLList[i_ch].name[0] != '\\0'; i_ch++) {\n if (slowDLList[i_ch].encode == SDL_RAW) {\n GET_VALUE(slowDLList[i_ch].bi0s, slowDLList[i_ch].iX[i_w]);\n // slowDLList[i_ch].iX[i_w] = ReadData(slowDLList[i_ch].bi0s);\n } else if (slowDLList[i_ch].encode == SDL_SCALE) {\n GET_SCALED_VALUE(slowDLList[i_ch].bi0s, slowDLList[i_ch].X[i_w]);\n // slowDLList[i_ch].X[i_w] = ReadCalData(slowDLList[i_ch].bi0s);\n } else if (slowDLList[i_ch].encode == SDL_LOG) {\n GET_SCALED_VALUE(slowDLList[i_ch].bi0s, slowDLList[i_ch].X[i_w]);\n // slowDLList[i_ch].X[i_w] = ReadCalData(slowDLList[i_ch].bi0s);\n }\n }\n slow_dl_read_index = i_w;\n}\n\n// convert and copy the data from the slowDLList into a char buffer\n// runs in the sip thread - called on demand\nvoid fillDLData(unsigned char *b, int len) {\n int i_r;\n int i_ch;\n uint16_t *u;\n unsigned *U;\n double x;\n unsigned char *b_end;\n\n b_end = b+len-4; // FIXME: wasted space if last field is not 32bit.\n\n i_r = slow_dl_read_index;\n\n U = (unsigned *)b;\n *U = SLOWDLSYNCWORD;\n b+=4;\n\n for (i_ch = 0; (slowDLList[i_ch].name[0] != '\\0') && (b < b_end); i_ch++) {\n if ((slowDLList[i_ch].encode == SDL_SCALE) || (slowDLList[i_ch].encode == SDL_LOG)) {\n double min, max;\n\n min = slowDLList[i_ch].min;\n max = slowDLList[i_ch].max;\n x = slowDLList[i_ch].X[i_r];\n\n if (slowDLList[i_ch].encode == SDL_LOG) {\n min = log(min);\n max = log(max);\n x = log(x);\n }\n\n /* scale between 0 and 1 */\n x = (x - min)/(max - min);\n if (x > 1.0) x = 1.0;\n if (x < 0) x = 0;\n\n /* scale to fit in unsigned type. s vs u is ignored. */\n switch (slowDLList[i_ch].type) {\n case 'c':\n slowDLList[i_ch].iX[i_r] = ((double)0xff)*x;\n break;\n case 's':\n case 'u':\n slowDLList[i_ch].iX[i_r] = ((double)0xffff)*x;\n break;\n case 'S':\n case 'U':\n slowDLList[i_ch].iX[i_r] = ((double)0xffffffff)*x;\n break;\n default:\n // should be impossible\n break;\n }\n }\n\n switch (slowDLList[i_ch].type) {\n case 'c':\n *b = (unsigned char)(0xff & slowDLList[i_ch].iX[i_r]);\n b++;\n break;\n case 's':\n case 'u':\n u = (uint16_t *)b;\n *u = (uint16_t )(0xffff & slowDLList[i_ch].iX[i_r]);\n b+=2;\n break;\n case 'S':\n case 'U':\n U = (unsigned *)b;\n *U = slowDLList[i_ch].iX[i_r];\n b+=4;\n break;\n default:\n // 'impossible' error.\n break;\n }\n }\n while (b < b_end) {\n *b = i_ch++;\n b++;\n }\n}\n" }, { "alpha_fraction": 0.6205698251724243, "alphanum_fraction": 0.6400278210639954, "avg_line_length": 32.46511459350586, "blob_id": "4acb08c74884bbc71fddd78124d2568b57bb49d4", "content_id": "f74c86dba12b29efab86ce049a2a8cb544c67f7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1439, "license_type": "no_license", "max_line_length": 82, "num_lines": 43, "path": "/common/include/camstruct.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* camstruct.h\n * struct of return values from star camera\n */\n\n\n#ifndef CAMSTRUCT_H\n#define CAMSTRUCT_H\n\n//camera related defines\n#define CAM_WIDTH 1530.0 //should always be the larger dimension\n#define CAM_HEIGHT 1020.0\n\n#ifdef __cplusplus\n#include <string>\n#include <sys/time.h>\n\nusing namespace std;\n\nstruct StarcamReturn {\n\t//image info\n\tunsigned long int frameNum; //frame number\n\tdouble mapmean; //mean value of image map\n\tdouble sigma; //error level (stnadard deviation) of map\n\tdouble exposuretime; //exposure duration in seconds\n\ttimeval imagestarttime; //time set immediately after exposure started\n\tstring camID; //some number to uniquely identify camera\n\tdouble ccdtemperature; //CCD temperature measured by camera's sensor\n\tuint16_t cputemperature; //cpu temperature measured by sensors\n\tdouble focusposition;\t\t//focus position\n\t\n\t//blob info (on 15 brightest blobs)\n\tint numblobs; //number of blobs found (or 15 if larger than 15)\n\tint flux[15]; //flux of blob\n\tdouble mean[15]; //men value around blob\n\tdouble snr[15]; //SNR of blob\n\tdouble x[15]; //position of centroid\n\tdouble y[15]; //...\n\t\n\t//pointing info won't be included since only coarse pointing needed in flight\n};\n#endif //__cplusplus\n\n#endif //CAMSTRUCT_H\n" }, { "alpha_fraction": 0.5326738953590393, "alphanum_fraction": 0.6674233675003052, "avg_line_length": 30.953367233276367, "blob_id": "ed0d06e941c3a796f249e522a169babf18916384", "content_id": "304e24c06ad62076ef62d6e18f553f7a198b3e74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6167, "license_type": "no_license", "max_line_length": 87, "num_lines": 193, "path": "/common/include/conversions.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * @file conversions.h\n *\n * @date Jun 12, 2011\n * @author seth\n *\n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2010 Columbia University\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#ifndef INCLUDE_CONVERT_H_\n#define INCLUDE_CONVERT_H_\n\n#include <time.h>\n#include <math.h>\n\n#define RX_CONVERT(TYPE, VAL) ((VAL) * CONVERT_##TYPE##_M + CONVERT_##TYPE##_B)\n#define TX_CONVERT(TYPE, VAL) (((VAL) - CONVERT_##TYPE##_B) / CONVERT_##TYPE##_M)\n\n#define NARROW_MAX (65535.0)\n#define WIDE_MAX (4294967295.0)\n#define WIDE_SIGNED_MAX (2147483646.0)\n#define CONVERT_MICROSECONDS_M (1000000.0/NARROW_MAX)\n#define CONVERT_MICROSECONDS_B (0.0)\n#define CONVERT_VEL_M (6500.0/NARROW_MAX)\n#define CONVERT_VEL_B (0.0)\n#define CONVERT_TEMP_M (473.15/NARROW_MAX)\n#define CONVERT_TEMP_B (-273.15)\n#define CONVERT_PRES_M (5.0/NARROW_MAX)\n#define CONVERT_PRES_B (0.0)\n#define CONVERT_GB_M (2000.0/NARROW_MAX)\n#define CONVERT_GB_B (0.0)\n#define CONVERT_GAIN_M (128.0/WIDE_SIGNED_MAX)\n#define CONVERT_GAIN_B (0.0)\n#define CONVERT_STATS_DEPTH_M ((8.0*16384)/NARROW_MAX)\n#define CONVERT_STATS_DEPTH_B (-1.0)\n#define CONVERT_STATS_4000_M ((4001.0)/NARROW_MAX)\n#define CONVERT_STATS_4000_B (-1.0)\n#define CONVERT_DISK_SPACE_TB_M (20000.0/NARROW_MAX)\n#define CONVERT_DISK_SPACE_TB_B (0.0)\n#define CONVERT_ANGLE_M ((4.0*M_PI/2.0)/NARROW_MAX)\n#define CONVERT_ANGLE_B (-M_PI/2.0)\n#define CONVERT_WIDE_ANGLE_M ((4.0*M_PI)/WIDE_MAX)\n#define CONVERT_WIDE_ANGLE_B (-2*M_PI)\n#define CONVERT_WIDE_ANGLE_DEG_M ((4.0*180.0/2.0)/WIDE_MAX)\n#define CONVERT_WIDE_ANGLE_DEG_B (0.0)\n#define CONVERT_ANGLE_DEG_M ((4.0*180.0/2.0)/NARROW_MAX)\n#define CONVERT_ANGLE_DEG_B (0.0)\n#define CONVERT_BLOB_POS_M (1536.0/NARROW_MAX)\n#define CONVERT_BLOB_POS_B (-768.0)\n#define CONVERT_FEW_SECONDS_M (300.0/NARROW_MAX)\n#define CONVERT_FEW_SECONDS_B (0.0)\n#define CONVERT_0_TO_10_M (10.0/NARROW_MAX)\n#define CONVERT_0_TO_10_B (0.0)\n#define CONVERT_0_TO_20_M (20.0/NARROW_MAX)\n#define CONVERT_0_TO_20_B (0.0)\n#define CONVERT_BATTV_M (100.0/NARROW_MAX)\n#define CONVERT_BATTV_B (0.0)\n#define CONVERT_BATTI_M (200.0/NARROW_MAX)\n#define CONVERT_BATTI_B (-100.0)\n#define CONVERT_UNITY_M 1.0\n#define CONVERT_UNITY_B 0.0\n\n#define H2LI (4294967296.0/24.0)\n#define LI2H (1.0/H2LI)\n#define SEC2LI (4294967296.0/(24.0*3600.0))\n#define LI2SEC (1.0/SEC2LI)\n#define DEG2LI (4294967296.0/360.0)\n#define LI2DEG (1.0/DEG2LI)\n#define RAD2LI (4294967296.0/2/M_PI)\n#define DEG2I (65536.0/360.0)\n#define I2DEG (1.0/DEG2I)\n#define RAD2I (65536.0/2/M_PI)\n#define H2I (65536.0/24.0)\n#define I2H (1.0/H2I)\n#define VEL2I (65536.0/10.0)\n#define I2VEL (1.0/VEL2I)\n\n#define H2LI (4294967296.0/24.0)\n#define LI2H (1.0/H2LI)\n#define DEG2LI (4294967296.0/360.0)\n#define LI2DEG (1.0/DEG2LI)\n#define RAD2LI (4294967296.0/2/M_PI)\n#define DEG2I (65536.0/360.0)\n#define I2DEG (1.0/DEG2I)\n#define RAD2I (65536.0/2/M_PI)\n#define H2I (65536.0/24.0)\n#define I2H (1.0/H2I)\n#define VEL2I (65536.0/10.0)\n#define I2VEL (1.0/VEL2I)\n\n#define SOLV2I_M (0.1)\n#define SOLV2I_B (-250)\n#define SOLV2V_M (0.001*50.9/3.9)\n#define SOLV2THERM (0.001/5.0*6200)\n\n#define DEG2RAD (M_PI/180.0)\n#define DEG2HR (1/15.0) /* 1/15 */\n#define SEC2HR (1/3600.0) /* 1/3600 */\n#define DAY2SEC 86400.0 /* 3600*24 */\n#define SEC2DAY (1/DAY2SEC) /* 1/3600/24 */\n#define HR2RAD (M_PI/12.0) /* 15*PI/180 */\n#define RAD2HR (12.0/M_PI) /* 12/PI */\n#define ARCMIN2RAD (DEG2RAD/60.0) /* DEG2RAD/60. */\n#define RAD2SEC (180. * 3600. / M_PI / 15.) /* radians to seconds (of time) */\n#define SEC2RAD (1. / RAD2SEC)\n#define RAD2ARCMIN (60.0/DEG2RAD) /* 60/DEG2RAD. */\n#define RAD2ARCSEC (60.0*RAD2ARCMIN) /* 60*60/DEG2RAD. */\n#define ARCMIN2DEG (1.0/60.0) /* 1/60 */\n#define DEG2ARCMIN 60.0000000000 /* 60 */\n#define ARCMIN2ARCSEC 60.0000000000 /* 60 */\n#define ARCSEC2ARCMIN 1.66666666667e-2 /* 1/60 */\n#define ARCSEC2RAD 4.8481368111e-6 /* 2PI/360/60/60 */\n#define MARCSEC2RAD 4.8481368111e-9 /* 1e-3 * 2PI/360/60/60 */\n#define UARCSEC2RAD 4.8481368111e-12 /* 1e-6 * 2PI/360/60/60 */\n\n#define RAD2DEG (180.0/M_PI) /* 180./PI */\n#define HR2DEG 15.0000000000 /* 15 */\n#define FSKY2SQDEG 41252.9612494 /* 360*360/PI */\n#define SQDEG2FSKY 2.42406840555e-5 /* PI/360/360 */\n\n#define CONVERT_SIDSLOPE_M (2000.0/NARROW_MAX) /*(NARROW_MAX/2000.0)*/\n#define CONVERT_SIDSLOPE_B 0\n#define CONVERT_GRTSLOPE_M (-30.0/NARROW_MAX) /*(NARROW_MAX/30.0)*/\n#define CONVERT_GRTSLOPE_B 0\n\nstatic inline double from_hours(double angle)\n{\n return angle*M_PI/12.0;\n}\n\nstatic inline double to_hours(double angle)\n{\n return angle*12.0/M_PI;\n}\n\nstatic inline double from_degrees(double angle)\n{\n return angle*M_PI/180.;\n}\n\nstatic inline double to_degrees(double angle)\n{\n return angle*180./M_PI;\n}\n\nstatic inline double from_arcmin(double angle)\n{\n return (angle/60.)*M_PI/180.;\n}\n\nstatic inline double to_arcmin(double angle)\n{\n return angle*(180./M_PI)*60.0;\n}\n\nstatic inline double from_arcsec(double angle)\n{\n return (angle/3600.)*M_PI/180.;\n}\n\nstatic inline double to_arcsec(double angle)\n{\n return angle*(180./M_PI)*3600.0;\n}\n\nstatic inline double from_seconds(time_t time)\n{\n return ((double) time)*M_PI/(12.0*3600.0);\n}\n\nstatic inline time_t to_seconds(double angle)\n{\n return (time_t) ((angle/M_PI)*(12.0*3600.0));\n}\n\n#endif /* INCLUDE_CONVERT_H_ */\n" }, { "alpha_fraction": 0.6374307870864868, "alphanum_fraction": 0.6422253251075745, "avg_line_length": 32.885154724121094, "blob_id": "30d1f8344cfe6e19cf9a01d686e2533fb8ed2ec9", "content_id": "ee19d9e539f5926e0c15e575076cf8fc9cc10988", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12097, "license_type": "no_license", "max_line_length": 133, "num_lines": 357, "path": "/guaca/options.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include \"options.h\"\n#include \"ui_options.h\"\n\n#define LL_DEFAULT_LIVE_SUFFIX \"_live\"\n#define GUACA_DEFAULT_PORT 40204\n#define MOLE_DIR_DEFAULT \"/data/mole\"\n#define RAW_DIR_DEFAULT \"/data/rawdir\"\n\nextern char configdir[128];\n\n#define new_key \"options/customized_2019\"\n#define old_key \"options/customized\"\n\nOptions::Options(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::Options),\n settings(\"guacamole\", \"guaca\")\n{\n ui->setupUi(this);\n main = parent;\n\n // remove old key\n if (settings.contains(old_key)) {\n qDebug() << \"Deleting old options\";\n settings.remove(old_key);\n }\n\n // check new key\n if (settings.contains(new_key)) {\n qDebug() << \"Restoring saved options\";\n restore_options();\n } else {\n qDebug() << \"Using default options\";\n default_options();\n }\n\n ui->client_port->setValidator(new QIntValidator(0, 65535, this) );\n ui->server_port->setValidator(new QIntValidator(0, 65535, this) );\n\n on_buttonBox_clicked(ui->buttonBox->button(QDialogButtonBox::Save));\n if (auto_live) ui->live_name->setEnabled(true);\n else ui->live_name->setDisabled(true);\n\n completer = new QCompleter(this);\n fsmodel = new QFileSystemModel(completer);\n fsmodel->setRootPath(\"\");\n completer->setModel(fsmodel);\n completer->setCompletionMode(QCompleter::PopupCompletion);\n ui->mole_dir->setCompleter(completer);\n ui->raw_dir->setCompleter(completer);\n\n restoreGeometry(settings.value(\"options\").toByteArray());\n}\n\nOptions::~Options() {\n // save the geometry of the options window\n settings.setValue(\"options\", saveGeometry());\n\n for (unsigned int i=0; i<helpers.size(); i++) {\n if (helpers[i]) delete helpers[i];\n helpers[i] = NULL;\n }\n qDebug() << \"Destroying options\";\n if (ui) delete ui;\n ui = NULL;\n if (fsmodel) delete fsmodel;\n fsmodel = NULL;\n if (completer) delete completer;\n completer = NULL;\n}\n\nunsigned int Options::add_helper(QString cmdname, QString args, bool terminal, unsigned int row) {\n ui->tableWidget->insertRow(row);\n ui->tableWidget->setItem(row, 0, new QTableWidgetItem(cmdname));\n ui->tableWidget->setItem(row, 1, new QTableWidgetItem(args));\n\n QWidget *checkBoxWidget = new QWidget();\n QHBoxLayout *layoutCheckBox = new QHBoxLayout(checkBoxWidget); // create a layer with reference to the widget\n QCheckBox * cb = new QCheckBox();\n layoutCheckBox->addWidget(cb); // Set the checkbox in the layer\n layoutCheckBox->setAlignment(Qt::AlignCenter); // Center the checkbox\n layoutCheckBox->setContentsMargins(0,0,0,0); // Set the zero padding\n cb->setChecked(terminal);\n\n // Set the checkbox in the second column\n ui->tableWidget->setCellWidget(row,2,cb);\n\n return row;\n}\n\nunsigned int Options::remove_helper(unsigned int row) {\n ui->tableWidget->removeRow(row);\n return row;\n}\n\nvoid Options::save_options()\n{\n unsigned int i = 0;\n for (i=0; i<helpers.size(); i++) {\n QString prefix = \"options/row\" + QString::number(i) + \"/\";\n settings.setValue(prefix + \"cmdname\", helpers[i]->cmdname);\n settings.setValue(prefix + \"args\", helpers[i]->args);\n settings.setValue(prefix + \"terminal\", helpers[i]->terminal);\n }\n // remove the last entry to signal end of list\n QString prefix = \"options/row\" + QString::number(i) + \"/\";\n settings.remove(prefix + \"cmdname\");\n settings.remove(prefix + \"args\");\n settings.remove(prefix + \"terminal\");\n\n // save mole options\n settings.setValue(\"options/server\", server);\n settings.setValue(\"options/client\", client);\n settings.setValue(\"options/backup\", backup);\n settings.setValue(\"options/no_checksums\", no_checksums);\n settings.setValue(\"options/mole_terminal\", mole_terminal);\n\n settings.setValue(\"options/server_port\", server_port);\n settings.setValue(\"options/client_port\", client_port);\n settings.setValue(\"options/live_name\", live_name);\n settings.setValue(\"options/auto_live\", auto_live);\n settings.setValue(\"options/mole_dir\", mole_dir);\n settings.setValue(\"options/raw_dir\", raw_dir);\n\n settings.setValue(new_key, true);\n}\n\nvoid Options::restore_options()\n{\n unsigned int i = 0;\n QString prefix = \"options/row\" + QString::number(i) + \"/\";\n while (settings.contains(prefix + \"cmdname\")) {\n QString cmdname = QVariant(settings.value(prefix + \"cmdname\")).toString();\n QString args = QVariant(settings.value(prefix + \"args\")).toString();\n bool terminal = QVariant(settings.value(prefix + \"terminal\")).toBool();\n add_helper(cmdname, args, terminal, ui->tableWidget->rowCount());\n prefix = \"options/row\" + QString::number(++i) + \"/\";\n }\n ui->server->setChecked(QVariant(settings.value(\"options/server\", QVariant(false))).toBool());\n ui->client->setChecked(QVariant(settings.value(\"options/client\", QVariant(true))).toBool());\n ui->backup->setChecked(QVariant(settings.value(\"options/backup\", QVariant(false))).toBool());\n ui->checksum->setChecked(QVariant(settings.value(\"options/no_checksums\", QVariant(false))).toBool());\n ui->mole_terminal->setChecked(QVariant(settings.value(\"options/mole_terminal\", QVariant(false))).toBool());\n\n ui->server_port->setText(QString::number(QVariant(settings.value(\"options/server_port\", QVariant(GUACA_DEFAULT_PORT))).toInt()));\n ui->client_port->setText(QString::number(QVariant(settings.value(\"options/client_port\", QVariant(GUACA_DEFAULT_PORT))).toInt()));\n ui->live_name->setText(QVariant(settings.value(\"options/live_name\", QVariant(MOLE_DIR_DEFAULT))).toString());\n ui->auto_live->setChecked(QVariant(settings.value(\"options/auto_live\", QVariant(true))).toBool());\n ui->mole_dir->setText(QVariant(settings.value(\"options/mole_dir\", QVariant(MOLE_DIR_DEFAULT))).toString());\n ui->raw_dir->setText(QVariant(settings.value(\"options/raw_dir\", QVariant(RAW_DIR_DEFAULT))).toString());\n}\n\nvoid Options::default_options()\n{\n // purge all leftover helpers\n ui->tableWidget->setRowCount(0);\n\n add_helper(\"its\", \"-B\", false, ui->tableWidget->rowCount());\n add_helper(\"katie\", \"-b -m -c mcc_log\", true, ui->tableWidget->rowCount());\n add_helper(\"katie\", \"-b -m -c ifc_log\", true, ui->tableWidget->rowCount());\n\n // default mole options\n ui->server->setChecked(false);\n ui->client->setChecked(true);\n ui->backup->setChecked(false);\n ui->checksum->setChecked(false);\n ui->mole_terminal->setChecked(false);\n\n ui->server_port->setText(QString::number(GUACA_DEFAULT_PORT));\n ui->client_port->setText(QString::number(GUACA_DEFAULT_PORT));\n ui->live_name->setText(QString(LL_DEFAULT_LIVE_SUFFIX));\n ui->auto_live->setChecked(true);\n ui->mole_dir->setText(MOLE_DIR_DEFAULT);\n ui->raw_dir->setText(RAW_DIR_DEFAULT);\n}\n\nvoid Options::load_options()\n{\n // purge all leftover helpers\n ui->tableWidget->setRowCount(0);\n\n // add all helpers\n for (unsigned int i=0; i<helpers.size(); i++) {\n add_helper(helpers[i]->cmdname, helpers[i]->args, helpers[i]->terminal, ui->tableWidget->rowCount());\n }\n\n // sets mole options\n ui->server->setChecked(server);\n ui->client->setChecked(client);\n ui->backup->setChecked(backup);\n ui->checksum->setChecked(no_checksums);\n ui->mole_terminal->setChecked(mole_terminal);\n\n ui->server_port->setText(QString::number(server_port));\n ui->client_port->setText(QString::number(client_port));\n ui->live_name->setText(live_name);\n ui->auto_live->setChecked(auto_live);\n ui->mole_dir->setText(mole_dir);\n ui->raw_dir->setText(raw_dir);\n}\n\nvoid Options::apply_options() {\n // apply new helpers\n int num_rows = ui->tableWidget->rowCount();\n for (int i=0; i<num_rows; i++) {\n Helper *h = new Helper(ui->tableWidget, i);\n helpers.push_back(h);\n // qDebug() << helpers[i].cmdname + \" \" + helpers[i].args;\n }\n\n // apply new options\n server = ui->server->isChecked();\n client = ui->client->isChecked();\n backup = ui->backup->isChecked();\n no_checksums = ui->checksum->isChecked();\n mole_terminal = ui->mole_terminal->isChecked();\n\n // apply port (0 is not allowed)\n server_port = ui->server_port->text().toInt();\n server_port = (!server_port) ? 40204 : server_port;\n client_port = ui->client_port->text().toInt();\n client_port = (!client_port) ? 40204 : client_port;\n\n live_name = ui->live_name->text();\n auto_live = ui->auto_live->isChecked();\n mole_dir = ui->mole_dir->text();\n mole_dir = (mole_dir.isEmpty()) ? MOLE_DIR_DEFAULT : mole_dir;\n raw_dir = ui->raw_dir->text();\n raw_dir = (raw_dir.isEmpty()) ? RAW_DIR_DEFAULT : raw_dir;\n}\n\nvoid Options::enable_options() {\n ui->checksum->setEnabled(true);\n ui->server->setEnabled(true);\n ui->client->setEnabled(true);\n ui->backup->setEnabled(true);\n ui->mole_terminal->setEnabled(true);\n\n ui->client_port->setEnabled(true);\n ui->server_port->setEnabled(true);\n\n ui->auto_live->setEnabled(true);\n if (auto_live) ui->live_name->setEnabled(true);\n ui->mole_dir->setEnabled(true);\n ui->raw_dir->setEnabled(true);\n}\n\nvoid Options::disable_options() {\n ui->checksum->setDisabled(true);\n ui->server->setDisabled(true);\n ui->client->setDisabled(true);\n ui->backup->setDisabled(true);\n ui->mole_terminal->setDisabled(true);\n\n ui->client_port->setDisabled(true);\n ui->server_port->setDisabled(true);\n\n ui->auto_live->setDisabled(true);\n ui->live_name->setDisabled(true);\n ui->mole_dir->setDisabled(true);\n ui->raw_dir->setDisabled(true);\n}\n\nvoid Options::start_helpers() {\n for (unsigned int i=0; i<helpers.size(); i++) {\n // close any straggling logscrolls\n if (helpers[i]->log) delete helpers[i]->log;\n helpers[i]->log = NULL;\n start_a_helper(helpers[i]);\n }\n}\n\nvoid Options::start_a_helper(Helper * helper) {\n // open new logscroll\n QString helper_cmd = helper->cmdname + \" \"+\n helper->args;\n helper->log = new Logscroll(NULL, helper_cmd);\n helper->log->setWindowTitle(helper_cmd);\n if (helper->terminal) {\n helper->log->show();\n }\n}\n\nvoid Options::show_helpers() {\n for (unsigned int i=0; i<helpers.size(); i++) {\n if (helpers[i]->log->doneProcess()) {\n start_a_helper(helpers[i]);\n }\n if (helpers[i]->terminal) {\n helpers[i]->log->show();\n }\n }\n}\n\nvoid Options::hide_helpers() {\n for (unsigned int i=0; i<helpers.size(); i++) {\n helpers[i]->log->hide();\n }\n}\n\nHelper::Helper(QTableWidget *tw, int index) {\n cmdname = tw->item(index,0)->text();\n args = tw->item(index,1)->text();\n QCheckBox *cb = qobject_cast<QCheckBox*>(tw->cellWidget(index,2));\n terminal = cb->isChecked();\n this->log = NULL;\n}\n\nHelper::Helper(QString cmdname, QString args, bool terminal) {\n this->cmdname = cmdname;\n this->args = args;\n this->terminal = terminal;\n this->log = NULL;\n}\n\nHelper::~Helper() {\n qDebug() << \"Destroying helper\";\n if (log) delete log;\n log = NULL;\n}\n\n\nvoid Options::on_addHelper_clicked()\n{\n add_helper(\"\", \"\", false, ui->tableWidget->currentRow()+1);\n}\n\nvoid Options::on_deleteHelper_clicked()\n{\n remove_helper(ui->tableWidget->currentRow());\n}\n\nvoid Options::on_buttonBox_clicked(QAbstractButton *button)\n{\n if (button != ui->buttonBox->button(QDialogButtonBox::Close)) {\n // clear old helpers\n for (unsigned int i=0; i<helpers.size(); i++) {\n if (helpers[i]) delete helpers[i];\n helpers[i] = NULL;\n }\n helpers.clear();\n if (button == ui->buttonBox->button(QDialogButtonBox::Save)) {\n apply_options();\n } else if (button == ui->buttonBox->button(QDialogButtonBox::RestoreDefaults)) {\n default_options();\n }\n save_options();\n start_helpers();\n }\n}\n\nvoid Options::on_auto_live_toggled(bool checked)\n{\n auto_live = checked;\n if (checked) ui->live_name->setEnabled(true);\n else ui->live_name->setDisabled(true);\n}\n" }, { "alpha_fraction": 0.49511194229125977, "alphanum_fraction": 0.5206559300422668, "avg_line_length": 32.01041793823242, "blob_id": "6ef250755c81ed0f8318eed0097d4ea5a7444cd0", "content_id": "b59ff293642377abdfce22099c265a997ed7499d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3172, "license_type": "no_license", "max_line_length": 104, "num_lines": 96, "path": "/stars/code/solving/finding/leveler.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"leveler.h\"\n#include \"../../shared/image/raw.h\"\n#include \"../../tools/math.h\"\n#include \"../../parameters/manager.h\"\n#include \"../logger.h\"\n\nusing namespace Solving::Finding;\n\nLeveler::Leveler(Parameters::Manager& params)\n{\n\timage_width = params.general.try_get(\"imaging.camera_real.image_width\", params.general.image_width);\n\timage_height = params.general.try_get(\"imaging.camera_real.image_height\", params.general.image_height);\n int max_coarse4_width = int(floor(image_width/4.0));\n int max_coarse4_height = int(floor(image_height/4.0));\n coarse4 = new unsigned short[max_coarse4_width*max_coarse4_height];\n}\n\nLeveler::~Leveler()\n{\n delete [] coarse4;\n}\n\nbool Leveler::is_inbounds(int& i, int& j, int& width, int& height)\n{\n if ((i<0) || (i>=width))\n return false;\n if ((j<0) || (j>=height))\n return false;\n return true;\n}\n\nvoid Leveler::level(Shared::Image::Raw& image, unsigned short leveled[])\n{\n double value = 0.0;\n double counter = 0.0;\n int subj, subi = 0;\n\n memcpy(leveled, image.pixels, image_height * image_width * sizeof(uint16_t));\n\n int coarse4_width = int(floor(image_width/4.0));\n int coarse4_height = int(floor(image_height/4.0));\n\n for (int j=0; j<coarse4_height; j++) {\n for (int i=0; i<coarse4_width; i++) {\n value = 0;\n for (subj=0; subj<4; subj++) {\n for (subi=0; subi<4; subi++) {\n value += image.pixels[(4*j+subj)*image_width + (4*i+subi)];\n }\n }\n value = round(value/16.0);\n coarse4[j*coarse4_width + i] = (unsigned short) value;\n }\n }\n for (int j=0; j<coarse4_height; j++) {\n for (int i=0; i<coarse4_width; i++) {\n value = 0;\n counter = 0;\n for (subj=j-4; subj<=j+4; subj+=8) {\n for (subi=i-3; subi<=i+3; subi++) {\n if (is_inbounds(subi, subj, coarse4_width, coarse4_height)) {\n value += coarse4[subj*coarse4_width + subi];\n counter++;\n }\n }\n }\n for (subi=i-4; subi<=i+4; subi+=8) {\n for (subj=j-3; subj<=j+3; subj++) {\n if (is_inbounds(subi, subj, coarse4_width, coarse4_height)) {\n value += coarse4[subj*coarse4_width + subi];\n counter++;\n }\n }\n }\n if (counter > 0) {\n value = round(value/counter);\n }\n for (subj=0; subj<4; subj++) {\n for (subi=0; subi<4; subi++) {\n leveled[(4*j+subj)*image_width + (4*i+subi)] = (unsigned short) value;\n }\n }\n }\n }\n if ((coarse4_height*4 != image_height) ||\n (coarse4_width*4 != image_width)) {\n logger.log(\"finder: leveler: warning: image dimensions not a multiple of 4\");\n }\n\n}\n\n\n" }, { "alpha_fraction": 0.4558303952217102, "alphanum_fraction": 0.48763251304626465, "avg_line_length": 15.529411315917969, "blob_id": "da494f051c2ccebddcf7240d7a5bca174c781919", "content_id": "9490c1d6aaeb29a05ff0d0c9cecb516b5c7a2dcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 283, "license_type": "no_license", "max_line_length": 45, "num_lines": 17, "path": "/sched_upload/sanity.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nvoid main() {\n char line[1024];\n int i=0;\n int row;\n\n while (fgets(line, 1020, stdin)!=NULL) {\n sscanf(line, \"%d\", &row);\n if (i!=row) {\n printf(\"Error line %d (%d)\\n\", i, row);\n i=row;\n }\n i++;\n }\n printf(\"checked %d rows\\n\", i);\n}\n\n\n" }, { "alpha_fraction": 0.6014044880867004, "alphanum_fraction": 0.605477511882782, "avg_line_length": 32.58490753173828, "blob_id": "550e287c9d2239fb8159a0772e2deb5337591707", "content_id": "5a85de52abe079072c717d6660599b2ec01776da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14240, "license_type": "no_license", "max_line_length": 137, "num_lines": 424, "path": "/blast_comms/comms_netasync.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/**\n * @file comms_netasync.c\n *\n * @date Jan 16, 2011\n * @author seth\n *\n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2010-2015 Seth Hillbrand\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <errno.h>\n#include <poll.h>\n#include <stdint.h>\n#include <pthread.h>\n#include <string.h>\n\n#include <blast.h>\n#include <comms_common.h>\n#include <comms_netasync.h>\n#include <comms_netsock.h>\n\n/**\n * Creates a new asynchronous handler for a given socket that will respond to specific events.\n * @param m_fd Number of a previously allocated socket\n * @param m_events Bitfield of poll events that this handler can process\n * @param m_process Pointer to the callback function that will process the event\n * @param m_priv Pointer to unspecified private data that will also be provided to the callback function\n * @return Pointer to the new asynchronous handler or NULL on failure\n */\ncomms_net_async_handle_t *comms_net_async_handler_new(socket_t m_fd, uint16_t m_events,\n comms_net_async_callback_t m_process, void *m_priv)\n{\n comms_net_async_handle_t *handle = NULL;\n log_enter();\n\n handle = calloc(sizeof(struct comms_net_async_handle), 1);\n if (handle) {\n handle->fd = m_fd;\n handle->events = m_events;\n handle->process = m_process;\n handle->priv = m_priv;\n }\n\n log_leave();\n return handle;\n}\n\n/**\n * Frees the memory associated with the asynchronous handler after disconnecting its context\n * @param m_handle Pointer to the async handler\n */\nvoid comms_net_async_handler_free(comms_net_async_handle_t *m_handle)\n{\n log_enter();\n if (m_handle && m_handle->ctx) {\n comms_net_async_handler_disconnect_ctx(m_handle);\n m_handle->ctx = NULL;\n }\n\n BLAST_SAFE_FREE(m_handle);\n log_leave(\"Freed\");\n}\n\nvoid comms_net_async_set_sock(comms_net_async_handle_t *m_handle, socket_t m_fd)\n{\n log_enter();\n if (m_handle->ctx != NULL) {\n m_handle->ctx->pollfds[m_handle->index].fd = m_fd;\n } else {\n m_handle->fd = m_fd;\n } log_leave();\n}\n\nvoid comms_net_async_set_events(comms_net_async_handle_t *m_handle, uint16_t m_events)\n{\n log_enter();\n m_handle->events = m_events;\n if (m_handle->ctx != NULL) {\n m_handle->ctx->pollfds[m_handle->index].events = m_events;\n } log_leave();\n}\n\nvoid comms_net_async_add_events(comms_net_async_handle_t *m_handle, uint16_t m_events)\n{\n log_enter();\n if (m_handle->ctx) {\n __sync_or_and_fetch(&(m_handle->ctx->pollfds[m_handle->index].events), m_events);\n } log_leave();\n}\n\nvoid comms_net_async_del_events(comms_net_async_handle_t *m_handle, uint16_t m_events)\n{\n log_enter();\n if (m_handle->ctx) {\n __sync_and_and_fetch(&(m_handle->ctx->pollfds[m_handle->index].events), ~m_events);\n } log_leave();\n}\n\nsocket_t comms_net_async_sock(comms_net_async_handle_t *m_handle)\n{\n log_enter();\n if (m_handle->ctx != NULL) {\n return m_handle->ctx->pollfds[m_handle->index].fd;\n }\n\n log_leave();\n return m_handle->fd;\n}\n\nvoid comms_net_async_set_callback(comms_net_async_handle_t *m_handle, comms_net_async_callback_t m_callback,\n void *m_priv)\n{\n log_enter();\n if (m_callback) {\n m_handle->process = m_callback;\n m_handle->priv = m_priv;\n } log_leave();\n}\n\ncomms_net_async_ctx_t *comms_net_async_ctx_new(size_t m_step_size)\n{\n comms_net_async_ctx_t *ctx;\n log_enter();\n\n ctx = (comms_net_async_ctx_t*) calloc(sizeof(comms_net_async_ctx_t), 1);\n if (ctx) {\n ctx->step_size = m_step_size ? m_step_size : BLAST_NET_DEFAULT_CTX_STEP;\n pthread_mutex_init(&ctx->mutex, NULL);\n }\n\n log_leave();\n return ctx;\n}\n\n/**\n * Frees all memory associated with the context, including the context itself. The calling function should\n * set #m_ctx to NULL following this function call.\n * @param m_ctx Pointer to the context to free\n */\nvoid comms_net_async_ctx_free(comms_net_async_ctx_t *m_ctx)\n{\n comms_net_async_handle_t *handle = NULL;\n\n if (!m_ctx) return;\n\n log_enter();\n if (m_ctx->num_handlers) {\n while (m_ctx->num_fds) {\n handle = m_ctx->async_handlers[0];\n\n if (handle->process && handle->process(handle, m_ctx->pollfds[0].fd, POLLERR, handle->priv) < 0) {\n blast_err(\"POLLERR handler failed while freeing asynchronous context\");\n }\n comms_net_async_handler_disconnect_ctx(handle);\n }\n\n BLAST_SAFE_FREE(m_ctx->async_handlers);\n BLAST_SAFE_FREE(m_ctx->pollfds);\n }\n\n BLAST_SAFE_FREE(m_ctx);\n log_leave(\"Success\");\n}\n\n/**\n * Resizes the asynchronous handler array. This can resize up or down in value.\n * @param m_ctx Pointer to the polling context\n * @param m_size Number of asynchronous handlers (and sockets) to allocate in the context\n * @return NETSOCK_OK on success, NETSOCK_ERR on failure\n */\nstatic int comms_net_async_ctx_resize(comms_net_async_ctx_t *m_ctx, size_t m_size)\n{\n comms_net_async_handle_t **handle = NULL;\n struct pollfd *poll_fds = NULL;\n\n log_enter();\n if (!pthread_mutex_lock(&m_ctx->mutex)) {\n if (!m_size) {\n blast_err(\"Tried to resize async context to zero! You really want comms_net_async_ctx_free()\");\n log_leave(\"Invalid m_size\");\n return NETSOCK_ERR;\n } else {\n if (!(handle = (comms_net_async_handle_t**) reballoc(err, m_ctx->async_handlers,\n sizeof(comms_net_async_handle_t*) * m_size))) {\n pthread_mutex_unlock(&m_ctx->mutex);\n log_leave(\"Could not allocate space for asynchronous handler array\");\n return NETSOCK_ERR;\n }\n\n blast_dbg(\"Allocated space for %d handles at %p\", (int) m_size, (void*) handle);\n\n if (!(poll_fds = (struct pollfd *) reballoc(err, m_ctx->pollfds, sizeof(struct pollfd) * m_size))) {\n m_ctx->async_handlers = (comms_net_async_handle_t**) reballoc(\n err, m_ctx->async_handlers, sizeof(comms_net_async_handle_t*) * m_ctx->num_handlers);\n\n pthread_mutex_unlock(&m_ctx->mutex);\n log_leave(\"Could not re-allocate space for polling socket array\");\n return NETSOCK_ERR;\n }\n blast_dbg(\"Allocated space for %d poll file descriptors at %p\", (int) m_size, (void*) poll_fds);\n }\n\n m_ctx->async_handlers = handle;\n m_ctx->pollfds = poll_fds;\n m_ctx->num_handlers = m_size;\n\n pthread_mutex_unlock(&m_ctx->mutex);\n }\n\n log_leave(\"Success\");\n return NETSOCK_OK;\n}\n\n/**\n * Adds an allocated asynchronous handler to a known context\n * @param m_ctx Pointer to a previously allocated context\n * @param m_async Pointer to the asynchronous handler to add to #m_ctx\n * @return NETSOCK_ERR on failure NETSOCK_OK on success\n */\nstatic int comms_net_async_ctx_add(comms_net_async_ctx_t *m_ctx, comms_net_async_handle_t *m_handle)\n{\n socket_t fd;\n\n log_enter();\n if (!m_ctx || !m_handle) {\n log_leave(\"Passed NULL pointer\");\n return NETSOCK_ERR;\n }\n\n if (m_handle->ctx) {\n log_leave(\"Asynchronous handler context already allocated\");\n return NETSOCK_ERR;\n }\n\n if (m_ctx->num_fds == m_ctx->num_handlers && comms_net_async_ctx_resize(m_ctx,\n m_ctx->num_handlers + m_ctx->step_size)\n < 0) {\n log_leave(\"Could not resize context handler array\");\n return NETSOCK_ERR;\n }\n\n fd = m_handle->fd;\n m_handle->index = m_ctx->num_fds++;\n\n m_ctx->async_handlers[m_handle->index] = m_handle;\n m_ctx->pollfds[m_handle->index].fd = fd;\n m_ctx->pollfds[m_handle->index].events = m_handle->events;\n m_ctx->pollfds[m_handle->index].revents = 0;\n m_handle->ctx = m_ctx;\n\n log_leave(\"Success. %p ctx has %d fds\", m_ctx, m_ctx->num_fds);\n return NETSOCK_OK;\n}\n\n/**\n * Convenience function to add an allocated comms_socket to an allocated polling context without\n * first going through a handle\n * @param m_ctx Pointer to the destination polling context\n * @param m_sock Pointer to the allocated #comms_socket structure\n * @return NETSOCK_OK on success. NETSOCK_ERR on failure\n */\nint comms_net_async_ctx_add_sock(comms_net_async_ctx_t *m_ctx, struct comms_socket *m_sock)\n{\n comms_net_async_handle_t *poll_handle = NULL;\n int retval = NETSOCK_ERR;\n\n log_enter();\n if (!m_ctx || !m_sock) {\n log_leave(\"Received NULL pointer\");\n return NETSOCK_ERR;\n }\n poll_handle = comms_sock_get_poll_handle(m_sock);\n\n if (!poll_handle) {\n log_leave(\"Could not get socket polling handle\");\n return NETSOCK_ERR;\n }\n\n retval = comms_net_async_ctx_add(m_ctx, poll_handle);\n log_leave(\"Returning %d\", (int)retval);\n return retval;\n}\n\n/**\n * Removes an asynchronous handler from the polling context array. The handler's socket value is\n * properly reset. Both the handler and polling context remain valid at the end of this function.\n * @param m_handle Pointer to the asynchronous handler that should be removed from the context.\n */\nvoid comms_net_async_handler_disconnect_ctx(comms_net_async_handle_t *m_handle)\n{\n size_t fd_index;\n comms_net_async_ctx_t *handler_context = NULL;\n\n log_enter();\n if (!m_handle) {\n log_leave(\"NULL Pointer\");\n return;\n }\n\n handler_context = m_handle->ctx;\n if (!handler_context) {\n log_leave(\"Handle not currently connected to context.\");\n return;\n }\n\n if (!pthread_mutex_lock(&handler_context->mutex)) {\n if (handler_context->num_handlers <= m_handle->index || handler_context->async_handlers[m_handle->index]\n != m_handle) {\n /**\n * In the case that a user passes\n */\n blast_err(\"Mis-formed context/handle pairing. Attempting to clean. You may have leaked memory.\");\n m_handle->ctx = NULL;\n for (fd_index = 0; fd_index < handler_context->num_handlers; fd_index++) {\n if (handler_context->async_handlers[fd_index] == m_handle) {\n m_handle->index = fd_index;\n m_handle->ctx = handler_context;\n }\n }\n\n if (!m_handle->ctx) {\n blast_err(\"No match found in context handler\");\n pthread_mutex_unlock(&handler_context->mutex);\n log_leave();\n return;\n }\n }\n\n fd_index = m_handle->index;\n\n m_handle->fd = handler_context->pollfds[fd_index].fd;\n m_handle->ctx = NULL;\n handler_context->num_fds--;\n\n /**\n * If we have removed a socket from the middle of the pollfds array, take the last socket (and its handler) in the array and move\n * it into the now empty slot.\n */\n if (handler_context->num_fds > 0 && handler_context->num_fds != fd_index) {\n handler_context->pollfds[fd_index] = handler_context->pollfds[handler_context->num_fds];\n handler_context->async_handlers[fd_index] = handler_context->async_handlers[handler_context->num_fds];\n handler_context->async_handlers[fd_index]->index = fd_index;\n }\n\n log_leave(\"Success %p ctx now has %d fds\", handler_context, handler_context->num_fds);\n pthread_mutex_unlock(&handler_context->mutex);\n }\n}\n\n/**\n * Provides an asynchronous wrapper to poll a group of associated sockets and individually\n * handle their returns.\n * @param m_ctx Pointer to a previously allocated asynchronous polling context\n * @param m_timeout Number of milliseconds after which to timeout the poll event\n * @return zero on success, -1 on error\n */\nint comms_net_async_poll(comms_net_async_ctx_t *m_ctx, int m_timeout)\n{\n int retval = 0;\n int event_count = 0;\n size_t i = 0;\n size_t num_fd = m_ctx->num_fds;\n int16_t recv_events = 0;\n struct pollfd *pollfds;\n comms_net_async_handle_t **async_handlers;\n\n log_enter();\n if (!num_fd) {\n log_leave(\"No sockets to poll in ctx %p\", m_ctx);\n return 0;\n }\n\n if (!pthread_mutex_lock(&m_ctx->mutex)) {\n pollfds = alloca(sizeof(struct pollfd) * num_fd);\n async_handlers = alloca(sizeof(comms_net_async_handle_t*) * num_fd);\n memcpy(pollfds, m_ctx->pollfds, sizeof(struct pollfd) * num_fd);\n memcpy(async_handlers, m_ctx->async_handlers, sizeof(comms_net_async_handle_t*) * num_fd);\n pthread_mutex_unlock(&m_ctx->mutex);\n\n if ((retval = poll(pollfds, num_fd, m_timeout)) <= 0) {\n log_leave(\"No Events. Polling Retval=%d\", retval);\n return (retval ? -1 : 0);\n }\n\n event_count = retval;\n\n while (event_count && i < num_fd) {\n pthread_testcancel();\n if (!pollfds[i].revents) {\n i++;\n continue;\n }\n event_count--;\n\n recv_events = pollfds[i].revents;\n pollfds[i].revents = 0;\n\n if ((recv_events & pollfds[i].events) && async_handlers[i] && async_handlers[i]->process) {\n async_handlers[i]->process(async_handlers[i], pollfds[i].fd, recv_events, async_handlers[i]->priv);\n }\n\n i++;\n }\n }\n\n log_leave(\"Processed %d events in ctx %p\", (int) retval, m_ctx);\n return retval;\n}\n" }, { "alpha_fraction": 0.5308679938316345, "alphanum_fraction": 0.5308679938316345, "avg_line_length": 38.421688079833984, "blob_id": "d92cbdfc46e637ec115e3cab6d1730baee1189e9", "content_id": "e18c2c532e8ca776c0ec60f79aaf2315f1da1637", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3272, "license_type": "no_license", "max_line_length": 106, "num_lines": 83, "path": "/check_commanding.py", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#! /usr/bin/python\n\nheader_file = \"./blast_config/include/command_list.h\"\nstart = False\nheader_single_commands = []\nfor line in open(header_file, 'r'):\n if line.startswith(\"enum singleCommand\"):\n start = True\n if start:\n if \"}\" in line:\n break\n line = line.replace(\"\\n\", '')\n line = line.replace(\" \", '')\n line = line.replace(\"\\t\", '')\n words = line.split(\",\")\n header_single_commands.extend(words)\n\nstart = False\nheader_multi_commands = []\nfor line in open(header_file, 'r'):\n if line.startswith(\"enum multiCommand\"):\n start = True\n if start:\n if \"}\" in line:\n break\n line = line.replace(\"\\n\", '')\n line = line.replace(\" \", '')\n line = line.replace(\"\\t\", '')\n words = line.split(\",\")\n header_multi_commands.extend(words)\n\nheader_single_commands = [element for element in header_single_commands if not element.startswith(\"enum\")]\nheader_single_commands = [element for element in header_single_commands if (element != \"\")]\nheader_multi_commands = [element for element in header_multi_commands if not element.startswith(\"enum\")]\nheader_multi_commands = [element for element in header_multi_commands if (element != \"\")]\n\n#print header_single_commands\n#print header_multi_commands\n\n#command_list_file = \"./blast_config/command_list.c\"\ncommand_list_file = \"./mcp/commanding/commands.c\"\n\nif False:\n s_commands_not_in_main_list = []\n start = False;\n for single_command in header_single_commands:\n command_found = False\n for line in open(command_list_file, 'r'):\n if \"MultiCommand\" in line:\n start = True\n if start:\n #if \"COMMAND\" in line:\n if \"case\" in line:\n if single_command in line:\n command_found = True\n print 'I found command', single_command, 'in line: ', line\n if start and (\"default:\" in line):\n start = False\n if not command_found:\n s_commands_not_in_main_list.append(single_command)\n\n#print 'single commands in MultiCommands in commands.c file:', s_commands_not_in_main_list\n\nif True:\n m_commands_not_in_main_list = []\n start = False;\n for multi_command in header_multi_commands:\n command_found = False\n for line in open(command_list_file, 'r'):\n #if \"COMMAND\" in line:\n if \"SingleCommand\" in line:\n start = True\n if start:\n if \"case\" in line:\n if multi_command in line:\n command_found = True\n print 'I found command', multi_command, 'in line: ', line\n if start and (\"default:\" in line):\n start = False\n if not command_found:\n m_commands_not_in_main_list.append(multi_command)\n\n #print '\\nmulti commands in SingleCommand in command.c file:', m_commands_not_in_main_list\n" }, { "alpha_fraction": 0.6857143044471741, "alphanum_fraction": 0.6924369931221008, "avg_line_length": 17.5625, "blob_id": "037c00a5dd40cd60f7f88995a9afa5c6210371ec", "content_id": "b99dee35da70ca96b8f38f8e9f254c5cbe574953", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 596, "license_type": "no_license", "max_line_length": 73, "num_lines": 32, "path": "/stars/code/displaying/lens.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__LENS_H\n#define DISPLAYING__LENS_H\n\n#include \"block.h\"\n#include \"dynamic_value.h\"\n\nnamespace Displaying\n{\n class Lens;\n}\n\nclass Displaying::Lens: public Displaying::Block\n{\n public:\n Lens();\n //void update(State::Lens& state);\n void update();\n void draw(Position& position);\n\n private:\n DynamicValue focus;\n DynamicValue aperture;\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.6472049951553345, "alphanum_fraction": 0.6521739363670349, "avg_line_length": 28.814815521240234, "blob_id": "b39b96342a502537a9fed1bddc2e3def65f5b015", "content_id": "35fe66e8da454ed9ad954466a3586093b283df6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 805, "license_type": "no_license", "max_line_length": 75, "num_lines": 27, "path": "/linklistcheck/Makefile", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "EXECUTABLE = linklistcheck \nLINKLIST_DIR = ../liblinklist\nINCLUDEDIRS = -I ../liblinklist/ -I ../common/include/ -I../mcp/include/ \\\n\t\t\t-I ../blast_config/include/ -I $(LINKLIST_DIR)/\nSOURCES = ../common/CRC_func.c ../common/channels_tng.c \\\n\t\t\t../common/blast.c ../common/PMurHash.c ../blast_config/tx_struct_tng.c \\\n\t\t\t$(LINKLIST_DIR)/linklist.c $(LINKLIST_DIR)/linklist_compress.c \\\n\t\t\t$(LINKLIST_DIR)/linklist_writer.c $(LINKLIST_DIR)/linklist_connect.c \\\n\t\t\tlinklistcheck.c\n\nCFLAGS = `pkg-config --cflags glib-2.0` $(INCLUDEDIRS) \nLIBS = -lssl -lcrypto -lpthread `pkg-config --libs glib-2.0`\n\nOBJECTS = $(SOURCES:.c=.o)\n\nall: $(EXECUTABLE) $(OBJECTS)\n\n$(EXECUTABLE): $(OBJECTS)\n\tgcc $(SOURCES) $(CFLAGS) -o $@ $(LIBS)\n\n.cpp.o:\n\tgcc $(CFLAGS) $< -o $@\n\n.PHONY: clean\n\nclean: \n\trm -f *.o $(EXECUTABLE)\n" }, { "alpha_fraction": 0.6549349427223206, "alphanum_fraction": 0.6748278737068176, "avg_line_length": 30.095237731933594, "blob_id": "076b6f9e06cf0b806abd9e2c04327a7bec563833", "content_id": "2cc36dfbefea780724a6c563d06e0fdc15bf7cd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1308, "license_type": "no_license", "max_line_length": 90, "num_lines": 42, "path": "/stars/code/shared/autofocus/requests.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"requests.h\"\n#include \"../../parameters/manager.h\"\n\nusing namespace Shared::Autofocus;\n\nRequests::Requests()\n{\n run_counter = 0;\n focus_search_min = 2300;\n focus_search_max = 3300;\n focus_search_step = 10;\n abort_counter = 0;\n abort_still_use_solution = false;\n display_mode = xC_autofocus_display_mode_auto;\n}\n\nvoid Requests::init(Parameters::Manager& params)\n{\n focus_search_min = params.general.try_get(\"imaging.autofocus.focus_search_min\", 2300);\n focus_search_max = params.general.try_get(\"imaging.autofocus.focus_search_max\", 3300);\n focus_search_step = params.general.try_get(\"imaging.autofocus.focus_search_step\", 10);\n}\n\nRequests& Requests::operator=(const Requests &rhs)\n{\n if (this != &rhs) {\n run_counter = rhs.run_counter;\n focus_search_min = rhs.focus_search_min;\n focus_search_max = rhs.focus_search_max;\n focus_search_step = rhs.focus_search_step;\n abort_counter = rhs.abort_counter;\n abort_still_use_solution = rhs.abort_still_use_solution;\n display_mode = rhs.display_mode;\n }\n return *this;\n}\n\n" }, { "alpha_fraction": 0.6796714663505554, "alphanum_fraction": 0.6878849864006042, "avg_line_length": 13.757575988769531, "blob_id": "4465e43662451f67d7790908d9fa690a45473bee", "content_id": "ba740031e6725c8403617a8089f558ef7ca9afe8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 488, "license_type": "no_license", "max_line_length": 73, "num_lines": 33, "path": "/stars/code/displaying/utilities.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__UTILITIES_H\n#define DISPLAYING__UTILITIES_H\n\n#if defined(_MSC_VER)\n #include <windows.h>\n#endif\n#include \"GL/gl.h\"\n\nnamespace Displaying\n{\n\nstruct Position\n{\n GLdouble x;\n GLdouble y;\n};\n\nstruct Size\n{\n GLdouble w;\n GLdouble h;\n};\n\n}\n\n#endif\n" }, { "alpha_fraction": 0.6736068725585938, "alphanum_fraction": 0.7207593321800232, "avg_line_length": 30.403846740722656, "blob_id": "8dfec24cb30f6eecc2407fa35925cbf7f9482adf", "content_id": "35887ba81001d34a92112c31785faafcd3841563", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1633, "license_type": "no_license", "max_line_length": 89, "num_lines": 52, "path": "/common/include/crc.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/**\n * @file crc.h\n *\n * @date Aug 5, 2015\n * @author seth\n *\n * @brief This file is part of MCP, created for the BLASTPol project\n *\n * This software is copyright (C) 2011-2015 University of Pennsylvania\n *\n * MCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * MCP 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 MCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#ifndef INCLUDE_CRC_H\n#define INCLUDE_CRC_H\n\n#include <stdint.h>\n#include <portable_endian.h>\n#include <blast_compiler.h>\n#define CRCPOLY_LE 0xedb88320\n#define CRCPOLY_BE 0x04c11db7\n\n#ifdef CRC16_SEED\n#undef CRC16_SEED\n#endif\n#define CRC16_SEED 0xEB90\n\nextern uint32_t crc32_le(uint32_t crc, unsigned char const *p, size_t len);\nextern uint32_t crc32_be(uint32_t crc, unsigned char const *p, size_t len);\n\n#if __BYTE_ORDER == __LITTLE_ENDIAN\n# define crc32(seed, data, length) crc32_le(seed, (unsigned char const *)(data), length)\n#else\n# define crc32(seed, data, length) crc32_be(seed, (unsigned char const *)(data), length)\n#endif\n\nuint16_t __pure crc16(uint16_t crc, void const *p, size_t len);\n\n#endif /* _LINUX_CRC32_H */\n" }, { "alpha_fraction": 0.3805498778820038, "alphanum_fraction": 0.385893315076828, "avg_line_length": 46.65277862548828, "blob_id": "a7d8373d8ecd503252075243857c5ac95c2ddf8d", "content_id": "d0720e2b41b9a2e3f537665b4c31fde28ceb3ffd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10293, "license_type": "no_license", "max_line_length": 117, "num_lines": 216, "path": "/owl/PDotPal.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"PDotPal.h\"\n#include \"PExtrema.h\"\n#include \"PMainWindow.h\"\n#include \"PDirfileDataItem.h\"\n#include \"PTimeDataItem.h\"\n#include <QFile>\n#include <QDomElement>\n#include <QMessageBox>\n\nPDotPal::PDotPal(QString filen)\n{\n QMessageBox::information(0,\"Notice\",\"Opening .pal files is not fully supported. Not all data will be imported.\");\n QDomDocument doc(\"mydocument\");\n QFile file(filen);\n if (!file.open(QIODevice::ReadOnly))\n return;\n if (!doc.setContent(&file)) {\n file.close();\n return;\n }\n file.close();\n\n QDomElement docElem = doc.documentElement();\n\n QDomNode n = docElem.firstChild();\n while(!n.isNull()) {\n QDomElement e = n.toElement(); // try to convert the node to an element.\n\n /////////////////////////////////////////////////////////////////////////////////\n if(!e.isNull()&&e.tagName().toUpper()==\"SETTINGS\") {\n QDomNode nn=e.childNodes().at(0);\n while(!nn.isNull()) {\n QDomElement ee=nn.toElement();\n\n /////////////////////////////////////////////////////////////////////////////////\n if(!ee.isNull()&&ee.tagName().toUpper()==\"TEXTSTYLE\") {\n QString sName=ee.attribute(\"name\");\n QColor sFGColor=ee.attribute(\"colour\",\"black\");\n QColor sBGColor=ee.attribute(\"backcolour\",\"white\");\n if(sName==\"xhiwarn\") sName=\"xhigh\";\n if(sName==\"hiwarn\") sName=\"high\";\n if(sName==\"lowarn\") sName=\"low\";\n if(sName==\"xlowarn\") sName=\"xlow\";\n bool isBold=(ee.attribute(\"bold\",\"false\")==\"true\");\n new PStyle(sName,isBold,0,sBGColor,sFGColor,1);\n }\n\n /////////////////////////////////////////////////////////////////////////////////\n if(!ee.isNull()&&ee.tagName().toUpper()==\"EXTREMA\") {\n QString eName=ee.attribute(\"name\");\n double eHigh=1.0,eLow=-1.0,eXHigh=2.0,eXLow=-2.0;\n\n QDomNode nnn=ee.childNodes().at(0);\n while(!nnn.isNull()) {\n QDomElement eee=nnn.toElement();\n\n /////////////////////////////////////////////////////////////////////////////////\n if(!eee.isNull()&&eee.tagName().toUpper()==\"HI\") {\n eHigh=eee.attribute(\"value\").toDouble();\n /////////////////////////////////////////////////////////////////////////////////\n } else if(!eee.isNull()&&eee.tagName().toUpper()==\"XHI\") {\n eXHigh=eee.attribute(\"value\").toDouble();\n /////////////////////////////////////////////////////////////////////////////////\n } else if(!eee.isNull()&&eee.tagName().toUpper()==\"LO\") {\n eLow=eee.attribute(\"value\").toDouble();\n /////////////////////////////////////////////////////////////////////////////////\n } else if(!eee.isNull()&&eee.tagName().toUpper()==\"XLO\") {\n eXLow=eee.attribute(\"value\").toDouble();\n }\n\n nnn=nnn.nextSibling();\n }\n PExtrema*p=new PExtrema;\n p->setName(eName);\n p->_low=eLow;\n p->_high=eHigh;\n p->_xlow=eXLow;\n p->_xhigh=eXHigh;\n }\n nn=nn.nextSibling();\n }\n /////////////////////////////////////////////////////////////////////////////////\n } else if(!e.isNull()&&e.tagName().toUpper()==\"BOX\") {\n _pbox.push_back(new PBox(\"DOTPAL BOX\"));\n _pbox.back()->setBoxTitle(e.attribute(\"caption\"),1);\n// _pbox.back()->setColour(e.attribute(\"colour\"),1);\n\n QDomNode nn=e.childNodes().at(0);\n while(!nn.isNull()) {\n QDomElement ee=nn.toElement();\n\n /////////////////////////////////////////////////////////////////////////////////\n if(!ee.isNull()&&ee.tagName().toUpper()==\"MULTI\") {\n PMultiDataItem* pmdi=new PMultiDataItem(_pbox.back(),\"DOTPAL PMDI\");\n pmdi->setCaption(ee.attribute(\"caption\",\"DOTPAL_NOCAPTION\"),1);\n\n QDomNode nnn=ee.childNodes().at(0);\n while(!nnn.isNull()) {\n QDomElement eee=nnn.toElement();\n\n /////////////////////////////////////////////////////////////////////////////////\n if(!eee.isNull()&&eee.tagName().toUpper()==\"DATUM\") {\n pmdi->setSource(eee.attribute(\"src\"),1);\n QDomNode nnnn=eee.childNodes().at(0);\n while(!nnnn.isNull()) {\n QDomElement eeee=nnnn.toElement();\n\n /////////////////////////////////////////////////////////////////////////////////\n if(!eeee.isNull()&&eeee.tagName().toUpper()==\"WORD\") {\n QString style=eeee.attribute(\"textstyle\",\"defbox\");\n QString idText=\"INVALID!!!\";\n for(int i=0;i<PStyle::_u.size();i++) {\n if(style==PStyle::_u[i]->name()) {\n idText=PStyle::_u[i]->idText();\n }\n }\n pmdi->_map->set(\n eeee.attribute(\"value\").toInt(),\n eeee.attribute(\"caption\")+\n \" [style=\\\"\"+style+\"\\\" \"+idText+\"]\");\n }\n nnnn=nnnn.nextSibling();\n }\n }\n\n nnn=nnn.nextSibling();\n }\n _pbox.back()->addProperty(pmdi);\n /////////////////////////////////////////////////////////////////////////////////\n } else if(!ee.isNull()&&ee.tagName().toUpper()==\"NUMBER\") {\n PNumberDataItem* pndi=new PNumberDataItem(_pbox.back(),\"DOTPAL PNDI\");\n _pbox.back()->addProperty(pndi);\n pndi->setCaption(ee.attribute(\"caption\"),1);\n\n QDomNode nnn=ee.childNodes().at(0);\n while(!nnn.isNull()) {\n QDomElement eee=nnn.toElement();\n\n /////////////////////////////////////////////////////////////////////////////////\n if(!eee.isNull()&&eee.tagName().toUpper()==\"DATUM\") {\n pndi->setSource(eee.attribute(\"src\"),1);\n pndi->setFormat(eee.attribute(\"format\"),1);\n QString extremaName=eee.attribute(\"extrema\",\"unknown\");\n if(extremaName!=\"unknown\") {\n for(int i=0;i<PExtrema::_u.size();i++) {\n if(PExtrema::_u[i]->name()==extremaName) {\n pndi->_extrema=PExtrema::_u[i];\n }\n }\n }\n }\n\n nnn=nnn.nextSibling();\n }\n /////////////////////////////////////////////////////////////////////////////////\n } else if(!ee.isNull()&&ee.tagName().toUpper()==\"CURDIR\") {\n PDirfileDataItem* pddi=new PDirfileDataItem(_pbox.back(),\"DOTPAL PDDI\");\n _pbox.back()->addProperty(pddi);\n pddi->setCaption(ee.attribute(\"caption\"),1);\n /////////////////////////////////////////////////////////////////////////////////\n } else if(!ee.isNull()&&ee.tagName().toUpper()==\"DATETIME\") {\n PTimeDataItem* ptdi=new PTimeDataItem(_pbox.back(),\"DOTPAL PTDI\");\n _pbox.back()->addProperty(ptdi);;\n ptdi->setCaption(ee.attribute(\"caption\"),1);\n\n QDomNode nnn=ee.childNodes().at(0);\n while(!nnn.isNull()) {\n QDomElement eee=nnn.toElement();\n\n /////////////////////////////////////////////////////////////////////////////////\n if(!eee.isNull()&&eee.tagName().toUpper()==\"DATUM\") {\n ptdi->setSource(eee.attribute(\"src\"),1);\n ptdi->setFormat(eee.attribute(\"format\"),1);\n }\n\n nnn=nnn.nextSibling();\n }\n }\n nn=nn.nextSibling();\n }\n }\n\n\n n = n.nextSibling();\n }\n\n // Here we append a new element to the end of the document\n QDomElement elem = doc.createElement(\"img\");\n elem.setAttribute(\"src\", \"myimage.png\");\n docElem.appendChild(elem);\n\n for(int i=0;i<PExtrema::_u.size();i++) {\n PMainWindow::me->recognizeExtrema(PExtrema::_u[i]);\n }\n}\n" }, { "alpha_fraction": 0.5616915225982666, "alphanum_fraction": 0.6348258852958679, "avg_line_length": 26.148649215698242, "blob_id": "64a4a10400a25c00504e77371fc462a60ca570fc", "content_id": "493ab34652fc34d12f0846d0b6f6094a5e4e5fa3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2010, "license_type": "no_license", "max_line_length": 75, "num_lines": 74, "path": "/stars/code/tools/slalib.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#ifndef TOOLS_SLALIB_H\n#define TOOLS_SLALIB_H\n\n#include <math.h>\n#include <ctype.h>\n#include <string.h>\n\nnamespace Slalib\n{\n\n// Routines lifted from SLALib\n\n/* 2pi */\n#define D2PI 6.2831853071795864769252867665590057683943387987502\n\n\n/* pi/(180*3600): arcseconds to radians */\n#define DAS2R 4.8481368110953599358991410235794797595635330237270e-6\n\n/* dmod(A,B) - A modulo B (double) */\n#define dmod(A,B) ((B)!=0.0?((A)*(B)>0.0?(A)-(B)*floor((A)/(B))\\\n :(A)+(B)*floor(-(A)/(B))):(A))\n\n// Normalize angle to range 0-2PI\ndouble slaDranrm ( double angle );\nfloat slaRanorm ( float angle );\n\n// Calculate map centre \nvoid slaTps2c ( double xi, double eta, double ra, double dec,\n double *raz1, double *decz1,\n double *raz2, double *decz2, int *n );\n\n// Dependencies for precess\nvoid slaPrebn ( double bep0, double bep1, double rmatp[3][3] );\n\nvoid slaDmxv ( double dm[3][3], double va[3], double vb[3] );\n\nvoid slaDeuler ( char *order, double phi, double theta,\n double psi, double rmat[3][3] );\n\nvoid slaDcs2c ( double a, double b, double v[3] );\n\nvoid slaDcc2s ( double v[3], double *a, double *b );\n\nvoid slaPrec ( double ep0, double ep1, double rmatp[3][3] );\n\n// Precess coordinates\nvoid slaPreces ( char sys[3], double ep0, double ep1,\n double *ra, double *dc );\n\n// Date and epoch routines\nvoid slaCaldj ( int iy, int im, int id, double *djm, int *j );\n\nvoid slaCldj ( int iy, int im, int id, double *djm, int *j );\n\ndouble slaEpj ( double date );\n\n// Other stuff\n\nvoid slaDtp2s ( double xi, double eta, double raz, double decz,\n double *ra, double *dec );\n\nvoid slaDs2tp ( double ra, double dec, double raz, double decz,\n double *xi, double *eta, int *j );\n\nvoid slaDh2e ( double az, double el, double phi, double *ha, double *dec );\n\nvoid slaDe2h ( double ha, double dec, double phi, double *az, double *el );\n\ndouble slaPa ( double ha, double dec, double phi );\n\n}\n\n#endif\n\n" }, { "alpha_fraction": 0.603960394859314, "alphanum_fraction": 0.606245219707489, "avg_line_length": 24.25, "blob_id": "9cf6cf03284de2aaf34e2f7e36c1c17cb237610f", "content_id": "4bbe73dbee084fd03e7aadb99262699986bfaccf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1313, "license_type": "no_license", "max_line_length": 75, "num_lines": 52, "path": "/starcam/bloblist.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n\tbloblist.h\n\n\tlinked list of blobs\n*/\n\n#include <stdio.h>\n\n#ifndef BLOBLIST_H\n#define BLOBLIST_H\n\nclass bloblist {\n public:\n bloblist(int flux_in, double x_in, double y_in); // Node creator\n ~bloblist(); // Node destructor\n \n // Set blob properties\n void setflux( int flux_in );\n void setx( double x_in );\n void sety( double y_in );\n void settype( int type_in );\n void setsnr( double snr_in );\n void setmean( double mean_in );\n \n // Retrieve blob properties \n int getflux();\n double getx();\n double gety();\n int gettype();\n double getsnr();\n double getmean();\n \n // Pointers to next and previous blobs (for traversal purposes)\n void setnextblob( bloblist *nextblob_in );\n void setprevblob( bloblist *prevblob_in );\n bloblist *getnextblob();\n bloblist *getprevblob();\n \n private:\n bloblist *nextblob; // head/tail pointers for\n bloblist *prevblob; // the list.\n \n int type;\t // 0=undefined, 1=point, 2=extended\n \n int flux; // Flux in this blob\n double x; // x pixel coordinate of centroid \n double y; // y pixel coordinate of centroid\n double snr; // the SNR of this blob\n double mean; // mean level in the vicinity of the blob \n};\n\n#endif //BLOBLIST_H\n" }, { "alpha_fraction": 0.5409496426582336, "alphanum_fraction": 0.578063428401947, "avg_line_length": 31.36912727355957, "blob_id": "656401b628c78170255874e47687a1a14caf4f05", "content_id": "c92b3f5468d7dc0a9724d871832de36530806b5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4823, "license_type": "no_license", "max_line_length": 159, "num_lines": 149, "path": "/test_programs/mpsse/test_libusb.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <signal.h>\n#include <sys/time.h>\n#include <libusb-1.0/libusb.h>\n\n#include \"mpsse.h\"\n#include \"blast.h\"\n#include \"crc.h\"\n\n#define IFACE_A 0;\n#define IFACE_B 1;\n#define IFACE_C 2;\n#define IFACE_D 3;\n\nvoid send_biphase_writes();\nvoid send_bitbang_value();\n\nstruct mpsse_ctx *ctx; \n\nstatic LIBUSB_CALL void demo_cb(struct libusb_transfer * write_transfer) {\n\n printf(\"I am demo_cb, about to resubmit transfer\\n\");\n libusb_submit_transfer(write_transfer);\n\n}\n\nint main(int argc, char *argv[]) {\n\n\tconst uint16_t vid = 1027;\n\tconst uint16_t pid = 24593;\n\tconst char *serial = NULL;\n\tconst char *description = NULL;\n\tint channel = IFACE_A;\n int counter = 0;\n int frequency = 0;\n uint16_t frame_counter = 0;\n\n\n // The first open is a hack to make sure the chip is properly closed and reset\n\tctx = mpsse_open(&vid, &pid, description, serial, channel);\n usleep(1000);\n mpsse_reset_purge_close(ctx);\n usleep(1000);\n \n // This is now the real open \n\tctx = mpsse_open(&vid, &pid, description, serial, channel);\n usleep(1000);\n\n // Writing an array of data (0xFFFFFFFF...) through the bipase write functions\n\n uint16_t *data_to_write = NULL;\n uint16_t *inverse_data_to_write = NULL;\n size_t bytes_to_write = 1248+3; \n if (argc == 2) {\n frequency = atoi(argv[1]);\n } else {\n frequency = 1000000;\n }\n struct timeval begin, end;\n\n printf(\"The clock is set at %d bps\\n\", frequency);\n\n\n uint8_t data = 0x00;\n uint8_t dir = 0xFF; // direction output for all bits\n // uint8_t dir = 0xBF; // 0b10111111 pin 6 = input/read\n uint16_t crc_calculated;\n\n mpsse_set_data_bits_low_byte(ctx, data, dir);\n mpsse_set_data_bits_high_byte(ctx, data, dir);\n mpsse_flush(ctx);\n usleep(1000);\n mpsse_set_frequency(ctx, frequency);\n mpsse_flush(ctx);\n usleep(1000);\n\n // libubs stuff\n struct libusb_transfer *write_transfer = NULL;\n write_transfer = libusb_alloc_transfer(0);\n\n data_to_write = malloc(bytes_to_write); \n if (data_to_write) {\n *data_to_write = 0xDF11;\n *(data_to_write+1) = 0xEB04;\n *(data_to_write+2) = 0x0090;\n for (int i = 3; i < ((int) bytes_to_write/2); i++) {\n *(data_to_write+i) = 0xFFFF;\n // *(data_to_write+i) = i;\n }\n } else {\n mpsse_close(ctx); \n return 0;\n }\n inverse_data_to_write = malloc(bytes_to_write); \n if (inverse_data_to_write) {\n *inverse_data_to_write = 0xdf11;\n *(inverse_data_to_write+1) = 0x1404;\n *(inverse_data_to_write+2) = 0x006F;\n for (int i = 3; i < ((int) bytes_to_write/2); i++) {\n *(inverse_data_to_write+i) = 0xFFFF;\n // *(inverse_data_to_write+i) = i;\n }\n } else {\n mpsse_close(ctx); \n return 0;\n }\n\n libusb_fill_bulk_transfer(write_transfer, ctx->usb_dev, ctx->out_ep, (void *) data_to_write, bytes_to_write, demo_cb, write_transfer, 2000);\n libusb_submit_transfer(write_transfer);\n\n int last_word = ((int) bytes_to_write/2) - 1;\n int retval = 0;\n\n for (int j=0; j>-1; j++) {\n data_to_write[10] = frame_counter;\n gettimeofday(&begin, NULL);\n if (j%2 == 0) {\n crc_calculated = crc16(CRC16_SEED, data_to_write, bytes_to_write-2);\n *(data_to_write+last_word) = crc_calculated; // I know 0xAB40 is the CRC if no counter in the frame\n write_transfer->buffer = (void *) data_to_write;\n blast_info(\"==== Array to send ====\");\n for (int i = 0; i < ((int) bytes_to_write); i++) {\n printf(\"%02x \", *(((uint8_t *) (data_to_write))+i));\n }\n } else {\n inverse_data_to_write[10] = frame_counter;\n crc_calculated = crc16(CRC16_SEED, data_to_write, bytes_to_write-2);\n *(inverse_data_to_write+last_word) = crc_calculated; // I know 0xAB40 is the CRC if no counter in the frame\n write_transfer->buffer = (void *) inverse_data_to_write;\n blast_info(\"==== Array to send ====\");\n for (int i = 0; i < ((int) bytes_to_write); i++) {\n printf(\"%02x \", *(((uint8_t *) (inverse_data_to_write))+i));\n }\n }\n retval = libusb_handle_events(ctx->usb_ctx);\n printf(\"Handle events returned: %s\\n\", libusb_strerror(retval));\n gettimeofday(&end, NULL);\n if ((counter % 1) == 0) {\n blast_info(\"The CRC calculated is %04x\", crc_calculated);\n blast_dbg(\"It took %f second to write %zd bytes\", (end.tv_sec+(end.tv_usec/1000000.0) - (begin.tv_sec+(begin.tv_usec/1000000.0))), bytes_to_write);\n }\n counter += 1;\n frame_counter++;\n } \n // libusb_free_transfer(write_transfer);\n}\n" }, { "alpha_fraction": 0.7040923237800598, "alphanum_fraction": 0.708289623260498, "avg_line_length": 18.4489803314209, "blob_id": "95718ed12135d3a662d07e7f8f8f8c98eacfdeee", "content_id": "5f7ee0a041e312fb7e0ab518b640a7d7179c242c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 954, "license_type": "no_license", "max_line_length": 81, "num_lines": 49, "path": "/stars/code/shared/general/network_reset.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__GENERAL__NETWORK_RESET_H\n#define SHARED__GENERAL__NETWORK_RESET_H\n\n#include <string>\n#include \"../circular_buffer.h\"\n\nnamespace Shared\n{\n namespace General\n {\n\nclass NetworkReset\n{\n public:\n NetworkReset();\n void init(Parameters::Manager& params);\n\n int reset_now_counter;\n bool reset_on_lull_enabled;\n double reset_on_lull_delay;\n std::string device_name;\n};\n\nclass NetworkResetStatus\n{\n public:\n NetworkResetStatus();\n bool resetting;\n};\n\n// writes: net_client\n// reads: net_reset\nextern Shared::CircularBuffer <NetworkReset> network_reset_for_net_reset;\n\n// writes: net_reset\n// reads: main\nextern Shared::CircularBuffer <NetworkResetStatus> network_reset_status_for_main;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.658257782459259, "alphanum_fraction": 0.6732361316680908, "avg_line_length": 32.3815803527832, "blob_id": "c09592d633c9c078a0f57091a2f73cbe7931ad4f", "content_id": "0138e634a082a88615547aa67bfbace209460e06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2537, "license_type": "no_license", "max_line_length": 111, "num_lines": 76, "path": "/owl/PServer.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include <QDebug>\n#include \"PServer.h\"\n\nPServer::PServer(QString ckey) : _sema(\"_owlSema\"+ckey,1,QSystemSemaphore::Create), _smemHtml(\"_owlHtml\"+ckey),\n _smemCSS(\"_owlCSS\"+ckey),_smemLayout(\"_owlLayout\"+ckey),_smemData(\"_owlData\"+ckey), key(ckey)\n{\n _sema.acquire();\n}\n\nPServer::~PServer() {\n _sema.release();\n if(_smemHtml.isAttached()) _smemHtml.detach();\n if(_smemCSS.isAttached()) _smemCSS.detach();\n if(_smemLayout.isAttached()) _smemLayout.detach();\n if(_smemData.isAttached()) _smemData.detach();\n}\n\nvoid PServer::clockOn(const QString& html,const QString&css,const QString&layout,const QString&data) {\n qDebug() << \"pserver clockon\";\n if(_smemHtml.isAttached()) _smemHtml.detach();\n if(_smemCSS.isAttached()) _smemCSS.detach();\n if(_smemLayout.isAttached()) _smemLayout.detach();\n if(_smemData.isAttached()) _smemData.detach();\n\n _smemHtml.create(html.size()+1);\n _smemCSS.create(css.size()+1);\n _smemLayout.create(layout.size()+1);\n _smemData.create(data.size()+1);\n\n _smemHtml.lock();\n _smemCSS.lock();\n _smemLayout.lock();\n _smemData.lock();\n\n memcpy(_smemHtml.data(),html.toLatin1().data(),html.size()+1);\n memcpy(_smemCSS.data(),css.toLatin1().data(),css.size()+1);\n memcpy(_smemLayout.data(),layout.toLatin1().data(),layout.size()+1);\n memcpy(_smemData.data(),data.toLatin1().data(),data.size()+1);\n\n _smemHtml.unlock();\n _smemCSS.unlock();\n _smemLayout.unlock();\n _smemData.unlock();\n\n _sema.release();\n QTimer::singleShot(30,this,SLOT(clockOff()));\n}\n\nvoid PServer::clockOff() {\n _sema.acquire();\n _smemHtml.detach();\n _smemCSS.detach();\n _smemLayout.detach();\n _smemData.detach();\n}\n" }, { "alpha_fraction": 0.6920415163040161, "alphanum_fraction": 0.6940187811851501, "avg_line_length": 27.885713577270508, "blob_id": "05692b761153ad1087b1bbf7b9b53505e7c96307", "content_id": "58ec3697e0422978a1218582c0b34e042338e122", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2024, "license_type": "no_license", "max_line_length": 101, "num_lines": 70, "path": "/stars/code/solving/matching/matcher.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__MATCHING__MATCHER_H\n#define SOLVING__MATCHING__MATCHER_H\n\n#include <math.h>\n#include <vector>\n#include <boost/math/distributions.hpp>\n#include \"../../tools/slalib.h\"\n#include \"fluxer.h\"\n#include \"catalog_manager.h\"\n#include \"solution_fitter.h\"\n#include \"../solution.h\"\n#include \"../base_set.h\"\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n}\n\nnamespace Solving\n{\n namespace Matching\n {\n class Matcher;\n }\n}\n\nclass Solving::Matching::Matcher\n{\n public:\n Matcher(Parameters::Manager& params);\n void init();\n void print_solutions(std::vector<Solution>& solutions);\n std::vector<Star> match_stars_to_blob(Solution& solution, Blob& blob, std::vector<Star>& stars,\n Shared::Image::Raw& image);\n void match_blobs_to_stars(std::vector<Blob>& blobs, Solution& solution, std::vector<Star>& stars,\n Shared::Image::Raw& image);\n void perform_matches(std::vector<Blob>& blobs, Solution& solution, Shared::Image::Raw& image);\n void calculate_pvalue(Solution& solution);\n bool get_next_base_set(BaseSet& base_set, int num_blobs, bool reset=false);\n void inform_blobs_of_matches(Solution& solution);\n void get_blob_names(Solution& solution);\n void fill_solutions_for_next_base_set(std::vector<Solution>& solutions,\n Shared::Image::Raw& image, BaseSet& base_set, std::vector<Blob>& blobs);\n bool match(std::vector<Blob>& blobs, Shared::Image::Raw& image, Solution& solution);\n\n private:\n Solving::Matching::CatalogManager catalog_manager;\n PatternMatching::SolutionFitter solution_fitter;\n Fluxer fluxer;\n int image_width, image_height, image_hyp;\n int result_update_success_counter, result_update_failure_counter;\n int base_set_counter;\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.598488450050354, "alphanum_fraction": 0.7458667755126953, "avg_line_length": 43.0625, "blob_id": "92b27643d8600889d6d56f91123aa8f0e3999ce3", "content_id": "49fa565946d7ca2e22c84a9678cf6676d1321c3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2117, "license_type": "no_license", "max_line_length": 177, "num_lines": 48, "path": "/scripts_commanding/xsc_initialization_cmds.sh", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "# LAT and LON of the high bay at Penn\nblastcmd @192.168.1.3 pos_set 39.9526 284.8110\n\n# xsc_is_new_window_period which valid_period_cs\nblastcmd @192.168.1.3 xsc_is_new_window_period 0 1500\nblastcmd @192.168.1.3 xsc_is_new_window_period 1 1500\n\n# xsc_exposure_timing which exposure_cs grace_period_s (!!) share_delay_cs\nblastcmd @192.168.1.3 xsc_exposure_timing 0 12 15 200\nblastcmd @192.168.1.3 xsc_exposure_timing 1 12 15 200\n\n# xsc_solver_general which enabled timeout_s\nblastcmd @192.168.1.3 xsc_solver_general 0 1 10\nblastcmd @192.168.1.3 xsc_solver_general 1 1 10\n\n##### Triggering ######\n\n# xsc_trigger_threshold which enabled max_streaking_px # trigger only when conditions are met\nblastcmd @192.168.1.3 xsc_trigger_threshold 0 1 10\nblastcmd @192.168.1.3 xsc_trigger_threshold 1 1 10\n\n# xsc_scan_force_trigger which[doesnt apply] enabled # Force triggering at turnaround\nblastcmd @192.168.1.3 xsc_scan_force_trigger 0 0\n\n######### Solving and Filters ##########\n# xsc_filter_hor_location which enabled radius_degrees\nblastcmd @192.168.1.3 xsc_filter_hor_location 0 1 30\nblastcmd @192.168.1.3 xsc_filter_hor_location 1 1 30\n\n# xsc_filter_hor_roll which enabled min_deg max_deg\nblastcmd @192.168.1.3 xsc_filter_hor_roll 0 1 -173 -163\nblastcmd @192.168.1.3 xsc_filter_hor_roll 1 1 -103 -93\n\n# xsc_filter_el which enabled min_deg max_deg\nblastcmd @192.168.1.3 xsc_filter_el 0 0 5 30\nblastcmd @192.168.1.3 xsc_filter_el 1 1 5 30\n\n# xsc_blob_finding which snr_thresh max_num_blobs robust_mode_enabled fitting_method\nblastcmd @192.168.1.3 xsc_blob_finding 0 10 15 1 0\nblastcmd @192.168.1.3 xsc_blob_finding 1 10 15 1 0\n\n# xsc_pattern_matching which enabled display_star_name match_tol_px iplatescale_min_arcsec iplatescale_max_arcsec platescale_always_fixed platescale_fixed # platescale ~6.4\"/pix\nblastcmd @192.168.1.3 xsc_pattern_matching 0 1 0 5 6.5 6.7 0 0\nblastcmd @192.168.1.3 xsc_pattern_matching 1 1 0 5 6.5 6.7 0 0\n\n# xsc_filter_matching which error_threshold_arcsec fit_error_thresh_px num_matched \nblastcmd @192.168.1.3 xsc_filter_matching 0 6 10 8\nblastcmd @192.168.1.3 xsc_filter_matching 1 6 10 8\n\n\n" }, { "alpha_fraction": 0.5395021438598633, "alphanum_fraction": 0.5661976933479309, "avg_line_length": 26.582090377807617, "blob_id": "57e7918873462df5f474690cd5e1b3162b59780c", "content_id": "b82c8add479638205aa0c3e8e34271042a2e1f77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5544, "license_type": "no_license", "max_line_length": 80, "num_lines": 201, "path": "/xymap/lockinmap.cc", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <complex>\n#include <cstring>\n#include <cstdlib>\n#include <cstdio>\n#include <unistd.h>\n#include <getdata/dirfile.h>\n#include \"iirfilter.h\"\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing GetData::Dirfile;\ntypedef std::complex<double> complex; \n\nconst double f_samp = 4.0E6/384.0/104.0; //sample frequency\nconst double s2cm = 25.4/4000.0;\t //stage steps to cm\n//TODO can use DELAY to acount for phase lags, seems to work fine without\nconst int DELAY = 0;\n\nvoid Usage(char* name)\n{\n cerr << name << \" -f <file name> -d <detector field name>\";\n cerr << \"-r <first_frame:numframes>\" << endl;\n cerr << \"\\t[ -x <x_field> ] [ -y <y_field> ] [ -c <chop_ref_field> ]\" << endl;\n cerr << \"Must specify at least -f -d -r\" << endl;\n exit(1);\n}\n\ncomplex pll(double ref)\n{\n static double period = 20.0;\n static double phase = 0.0;\n \n static double T = 0.0;\n\n static int ref_edge = 0;\n static int pll_edge = 0;\n \n static double ph = 0.0;\n static double dph = 0.0;\n \n static BesselHP1<double> fref(0.0125/f_samp);\n static BesselLP1<double> fperiod(0.15/f_samp);\n static BesselLP1<double> fphase(0.15/f_samp);\n \n double ref_ = fref(ref);\n ph += dph;\n T += 1.0; \n double pll_ref = cos(ph);\n \n if(ref_edge == 0 && ref_ >= 0.0) {\n period = fperiod(T);\n ref_edge = 1;\n dph = (2.0*M_PI)/period;\n T = 0.0; \n } else if(ref_edge == 1 && ref_ < 0.0 && T > 1.0) {\n ref_edge = 0;\n }\n\n\n if(pll_edge == 0 && (pll_ref >= 0.0)) {\n phase = fphase(T*dph);\n pll_edge = 1;\n } else if(pll_edge == 1 && (pll_ref < 0.0)) {\n pll_edge = 0;\n }\n\n return complex( ((cos(ph+phase) > 0.0) ? 1 : -1),\n\t ((sin(ph+phase) > 0.0) ? 1 : -1) );\n}\n\nint main(int argc, char* argv[])\n{\n string filename = \"\", field = \"\", xfield = \"\", yfield = \"\", reffield = \"\";\n int fframe = -1, nframes = -1;\n int retval;\n\n /* parse command line arguments */\n while ( (retval = getopt(argc, argv, \"f:d:r:x:y:c:\")) != -1) {\n switch (retval) {\n case 'f':\n filename = optarg;\n break;\n case 'd':\n field = optarg;\n break;\n case 'x':\n xfield = optarg;\n break;\n case 'y':\n yfield = optarg;\n break;\n case 'c':\n reffield = optarg;\n break;\n case 'r':\n *index(optarg, ':') = ' ';\n if(sscanf(optarg, \"%d %d\", &fframe, &nframes) != 2) Usage(argv[0]);\n break;\n }\n }\n \n if(filename[0] == '\\0') Usage(argv[0]);\n if(field[0] == '\\0') Usage(argv[0]);\n if (xfield[0] == '\\0') xfield = \"STAGE_X\";\n if (yfield[0] == '\\0') yfield = \"STAGE_Y\";\n if (reffield[0] == '\\0') reffield = \"CHOPPER\";\n if(fframe < 0 || nframes <= 0) Usage(argv[0]);\n \n cerr << \"Reading field \\\"\" << field << \"\\\" of: \" << filename << endl;\n cerr << \"for: \" << nframes << \" frames from: \" << fframe\n << \" to: \" << fframe+nframes << endl;\n cerr << \"Lock into reference \\\"\" << reffield << \"\\\", position fields: \\\"\"\n << xfield <<\"\\\" and \\\"\" << yfield << \"\\\"\" << endl;\n\n /* read required fields from the dirfile */\n Dirfile df(filename.c_str(), GD_RDONLY);\n if (df.Error()) {\n cerr << \"Error opening dirfile: \" << df.ErrorString() << endl;\n return 1;\n }\n\n unsigned int spf = df.SamplesPerFrame(field.c_str());\n if (df.Error()) {\n cerr << \"Error sizing getdata storage: \" << df.ErrorString() << endl;\n return 1;\n }\n if (spf != df.SamplesPerFrame(xfield.c_str())\n || spf != df.SamplesPerFrame(yfield.c_str())\n || spf != df.SamplesPerFrame(reffield.c_str())) {\n cerr << \"Fixme: I don't support different sample rates for D, X, Y, ref\\n\";\n return 1;\n }\n unsigned int Dsize = nframes*spf;\n double* D = new double[Dsize];\n double* X = new double[Dsize];\n double* Y = new double[Dsize];\n double* ref = new double[Dsize];\n double* amp = new double[Dsize];\n\n df.GetData(field.c_str(), fframe, 0, nframes, 0, GetData::Float64, D);\n if (df.Error()) {\n cerr << \"Error getting detector: \" << df.ErrorString() << endl;\n return 1;\n }\n df.GetData(xfield.c_str(), fframe, 0, nframes, 0, GetData::Float64, X);\n if (df.Error()) {\n cerr << \"Error getting X: \" << df.ErrorString() << endl;\n return 1;\n }\n df.GetData(yfield.c_str(), fframe, 0, nframes, 0, GetData::Float64, Y);\n if (df.Error()) {\n cerr << \"Error getting Y: \" << df.ErrorString() << endl;\n return 1;\n }\n df.GetData(reffield.c_str(), fframe, 0, nframes, 0, GetData::Float64, ref);\n if (df.Error()) {\n cerr << \"Error getting ref: \" << df.ErrorString() << endl;\n return 1;\n }\n\n /* filter, lock-in, etc. */\n //define fileter functions HP for pre-lockin and LP for post lock-in\n BesselHP1<double> filt_d(0.15/f_samp);\n BesselLP4<complex> filt_li(0.39/f_samp);\n double max_amp = 0.0;\n double max_y = 0.0;\n for(unsigned int i = 0; i < Dsize; i++) {\n\n complex pll_ref = pll(ref[i]);\n double data = filt_d(D[i]);\n amp[i] = abs(filt_li(data*pll_ref));\n\n //find maxima, for normalizing output\n if (amp[i] > max_amp) max_amp = amp[i];\n if (Y[i] > max_y) max_y = Y[i];\n }\n\n /* output (a subset of results */\n cout << std::setprecision(10);\n for(unsigned int i = 2000; i < Dsize; i+= 64) {\n //output an INDEX field to compare results relative to dirfile\n //cout << fframe + (double)i/spf << \" \";\n cout << X[i+DELAY]*s2cm << \" \" << (max_y - Y[i+DELAY])*s2cm \n\t << \" \" << amp[i]/max_amp << endl;\n } \n\n delete[] D;\n delete[] X;\n delete[] Y;\n delete[] ref;\n delete[] amp;\n return 0;\n}\n" }, { "alpha_fraction": 0.6934673190116882, "alphanum_fraction": 0.6984924674034119, "avg_line_length": 17.090909957885742, "blob_id": "3f5802e0f51b3bd96f9abf6204091546aad4cf24", "content_id": "584154b6085309f36eaaa4051a06ccbef23ac504", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 797, "license_type": "no_license", "max_line_length": 73, "num_lines": 44, "path": "/stars/code/imaging/camera_empty.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"../preprocessor.h\"\n#if (!PREPROCESSOR_USING_CAMERA)\n\n#pragma once\n#ifndef IMAGING__CAMERA_LINUX_H\n#define IMAGING__CAMERA_LINUX_H\n\n#include <boost/thread/thread.hpp>\n#include \"abstract_camera.h\"\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Imaging\n{\n class Camera;\n}\n\nclass Imaging::Camera: public Imaging::AbstractCamera\n{\n public:\n Camera(Parameters::Manager& params);\n bool init_camera();\n void clean_up_camera();\n void read_image_if_available();\n void thread_function();\n void wait_for_quit();\n\n private:\n\n boost::thread thread;\n};\n\n#endif\n\n#endif\n" }, { "alpha_fraction": 0.7004310488700867, "alphanum_fraction": 0.7090517282485962, "avg_line_length": 17.520000457763672, "blob_id": "f0ade9dbb23e3d0967145897d10a90712766e695", "content_id": "6f1945dd8ab9b5c051d0511e7b80d38e29f221fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 465, "license_type": "no_license", "max_line_length": 73, "num_lines": 25, "path": "/stars/code/displaying/quit_box.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__QUIT_BOX_H\n#define DISPLAYING__QUIT_BOX_H\n\n#include \"block.h\"\n\nnamespace Displaying\n{\n class QuitBox;\n}\n\nclass Displaying::QuitBox: public Displaying::Block\n{\n public:\n QuitBox();\n void draw(Position& position);\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.5620891451835632, "alphanum_fraction": 0.5729242563247681, "avg_line_length": 26.167585372924805, "blob_id": "e4a8147fe5787caeb86d987943dd87c31bff2c0d", "content_id": "b1d5def7e01beba018bdec2fc2eaeb82a1d66999", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 24642, "license_type": "no_license", "max_line_length": 97, "num_lines": 907, "path": "/starcam/frameblob.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n\tframeblob.cpp\n\n\tclass for locating blobs in a bitmap\n \n\tDepends on bloblist class.\n*/\n\n#include \"frameblob.h\"\n#include <cmath>\n\n#include <string>\n#include <sstream>\n#include <fstream>\n#include <time.h>\n#include <unistd.h>\n#include <sys/time.h>\n#define FRAMEBLOB_DEBUG 0\n#if FRAMEBLOB_DEBUG\n#include <iostream>\n#endif\n\n// ---------- Class constructor -----------------------------------------\n\nframeblob::frameblob( void ) {\n}\n\n/* no longer desired, just use defuault constructor and call commonconstructor\nframeblob::frameblob( MAPTYPE *map_in, unsigned int xpix_in, unsigned \n\t\t int ypix_in, unsigned int bits_in, \n\t\t double platescale_in ) {\n commonconstructor( map_in, xpix_in, ypix_in, bits_in, platescale_in );\n}\n*/\n\nvoid frameblob::commonconstructor(FrameBlobConfigParams params/*=defaultImageParams.blobParams*/)\n{\n#if FRAMEBLOB_DEBUG\n\tcout << \"[frameblob debug]: in commonconstructor method...\" << endl;\n#endif\n\tmap = params.map;\n\txpix = params.xpix;\n\typix = params.ypix;\n\tbits = params.bits;\n\tplatescale = params.platescale;\n\tnpix = xpix*ypix;\n\tmapmean=params.mapmean;\n\tsigma=params.sigma;\n\tsatval = params.satval; // numerical value of a saturated pixel\n\tsatcol = new int[xpix]; // array contains # sat pixels each column\n\tgain=params.gain;\n\treadout_offset=params.readoutOffset;\n\treadout_noise=params.readoutNoise;\n\tgrid = params.grid; // pixels/side in coarse grid search\n\tthreshold = params.threshold; // N sigma threshold criterion\n\tdisttol = params.disttol; // distance^2 tolerance for adjacent sources\n\tmaxblobs = params.maxblobs;\n\tstddev = params.stddev;\n \n\t// initialize linked lists and arrays\n\tnumblobs = 0;\n\tfirstblob = NULL;\n\tlastblob = NULL;\n\tthisblob = NULL;\n\tsearchgrid = NULL;\n\tmeangrid = NULL;\n\tbadpixels = NULL;\n}\n/*original method has been replaced\nvoid frameblob::commonconstructor( MAPTYPE *map_in, \n\t\t\t\t unsigned int xpix_in, \n\t\t\t\t unsigned int ypix_in, \n\t\t\t\t unsigned int bits_in, \n\t\t\t\t double platescale_in ) {\n // set up map parameters\n map = map_in;\n xpix = xpix_in;\n ypix = ypix_in;\n bits = bits_in;\n platescale = platescale_in;\n npix = xpix*ypix;\n \n // Blob list pointers initialized to 0\n numblobs = 0;\n maxblobs = 0;\n \n firstblob = NULL;\n lastblob = NULL;\n thisblob = NULL;\n \n // Set the gridsearch array to NULL to check at the end if allocated\n searchgrid = NULL;\n meangrid = NULL;\n \n // Map statistics defaults\n mapmean=0;\n sigma=1;\n satval = 65535; // numerical value of a saturated pixel\n satcol = new int[xpix]; // array contains # sat pixels each column\n \n gain=1;\n readout_offset=0;\n readout_noise=0;\n\n // Defaults for search parameters\n grid = 32; // pixels/side in coarse grid search\n threshold = 5; // N sigma threshold criterion\n disttol = 30*30; // distance^2 tolerance for adjacent sources\n \n badpixels = NULL;\n\n}\n*/\n\n// set the pointer to the map\nvoid frameblob::set_map( MAPTYPE *in_map ) {\n#if FRAMEBLOB_DEBUG\n\tcout << \"[frameblob debug]: in set_map method...\" << endl;\n#endif\n\tmap = in_map;\n}\n\n// set the pointer to the map, as well as map dimensions\nvoid frameblob::set_map( MAPTYPE *in_map, int height, int width ) {\n#if FRAMEBLOB_DEBUG\n\tcout << \"[frameblob debug]: in set_map... h=\" << height << \" w=\" << width << endl;\n#endif\n\typix = height;\n\txpix = width;\n\tnpix = height*width;\n\tsatcol = new int[xpix]; // array contains # sat pixels each column\n\tmap = in_map;\n\t\n\t//initialize some variables for the new map\n\tmapmean = 0;\n\tstddev = 0;\n}\n\n// ---------- Class Destructor ------------------------------------------\n\nframeblob::~frameblob() {\n clearblobs();\n \n delete[] searchgrid;\n delete[] meangrid;\n delete[] badpixels;\n delete[] satcol;\n}\n\n// ---------- Add blob to list ------------------------------------------\n\nvoid frameblob::addblob( int flux, double x, double y ) {\n#if FRAMEBLOB_DEBUG\n\tcout << \"[frameblob debug]: in addblob method...\" << endl;\n#endif\n // Only add a new blob if we haven't exceeded the maximum number, or if\n // we can have an unlimited number (maxblob=0)\n \n //printf(\"nblobs: %i maxblobs: %i\\n\",numblobs,maxblobs);\n \n if( (maxblobs == 0) || (numblobs < maxblobs) ) {\n thisblob = new bloblist(flux, x, y);\n \n if( lastblob == NULL ) { // make new starting blob if empty list\n firstblob = thisblob;\n lastblob = thisblob;\t\t\n numblobs = 1;\n } else { // otherwise add to the end\n lastblob->setnextblob( thisblob );\n thisblob->setprevblob( lastblob );\n numblobs++;\n }\n \n lastblob = thisblob; // new end of list\n }\n}\n\n// ---------- Delete blob from list -------------------------------------\n\nvoid frameblob::deleteblob( bloblist *killblob ) {\n#if FRAMEBLOB_DEBUG\n\tcout << \"[frameblob debug]: in deleteblob method...\" << endl;\n#endif\n bloblist *prev, *next;\n\n prev = killblob->getprevblob();\n next = killblob->getnextblob();\n\n // Set the head/tail pointers for surrounding blobs to skip this one\n\n if( prev == NULL ) { // if 1st blob in list\n\n if( next == NULL ) { // if was only blob in list\n firstblob = NULL;\n lastblob = NULL;\n } else { // otherwise next is new start\n firstblob = next;\n next->setprevblob(NULL);\n }\n } else {\n if( next == NULL ) { // was last element in multi-blob list\n prev->setnextblob(NULL);\n lastblob = prev;\n } else { // somewhere in the middle of a list\n prev->setnextblob(next);\n next->setprevblob(prev);\n }\n }\n \n // Delete this blob\n\n delete killblob;\n \n // Decrement the blob counter\n \n numblobs --;\n}\n\n// ---------- Clear whole blob list -------------------------------------\n\nvoid frameblob::clearblobs() {\n#if FRAMEBLOB_DEBUG\n\tcout << \"[frameblob debug]: in clearblobs method...\" << endl;\n#endif\n bloblist *nextblob;\n thisblob = firstblob; // start at the beginning of the list\n while( thisblob != NULL ) {\n nextblob = thisblob->getnextblob(); // get next blob\n delete thisblob; // delete the current one\n thisblob = nextblob; // move along\n }\n\n firstblob=NULL;\n lastblob=NULL;\n thisblob=NULL;\n numblobs = 0;\n}\n\n// ---------- Return start of blob list ---------------------------------\n\nbloblist *frameblob::getblobs() { // pointer to first blob\n return firstblob;\n}\n\n// ---------- Sort the blob list in descending flux order ---------------\n\nvoid frameblob::sortblobs() {\n#if FRAMEBLOB_DEBUG\n\tcout << \"[frameblob debug]: in sortblobs method...\" << endl;\n#endif\n bloblist *nextblob, *startblob, *endblob;\n int flag=1; // if set, list is still out of order\n \n if( numblobs > 0 ) {\n while( flag == 1 ) {\n flag=0;\n thisblob = firstblob;\n nextblob = thisblob->getnextblob();\n \n while( nextblob != NULL ) { // Traverse list, swap if out of order\n\tif( nextblob->getflux() > thisblob->getflux() ) { \n\t flag=1; // list still out of order\n\t \n\t startblob = thisblob->getprevblob();\n\t endblob = nextblob->getnextblob();\n\t \n\t // Change the forward pointers\n\t if( startblob != NULL ) startblob->setnextblob(nextblob);\n\t else firstblob = nextblob; // since start of list changed\n\t nextblob->setnextblob(thisblob);\n\t thisblob->setnextblob(endblob);\n\t \n\t // Change the backward pointers\n\t if( endblob != NULL ) endblob->setprevblob(thisblob);\n\t else lastblob = thisblob;\n\t thisblob->setprevblob(nextblob);\n\t nextblob->setprevblob(startblob);\n\t \n\t nextblob = endblob;\n\t} else thisblob = nextblob;\n\t\n\tnextblob = thisblob->getnextblob();\n }\n }\n }\n}\n\n// set a maximum number of blobs\nvoid frameblob::set_maxblobs(unsigned int in_maxblobs) {\n maxblobs = in_maxblobs;\n}\n\n// ---------- Deal with bad (extra noisey) pixels -----------------------\n\n// Load bad pixel map from file. returns -1 on error, 1 for success\n\nint frameblob::load_badpix(const char *fname) {\n#if FRAMEBLOB_DEBUG\n\tcout << \"[frameblob debug]: in load_badpix method...\" << endl;\n#endif\n FILE *badfile;\n bloblist *firstbad, *thisbad, *nextbad, *lastbad; // bad pixel list\n char thisline[81];\n int count; // Number of elements read from the current line\n int i, x, y; // coordinates of the bad pixel in this line\n \n if( (badfile = fopen( fname, \"r\" )) == NULL )\n return -1;\n \n // Read through file line-by-line reading in pixel coordinates.\n // Use the blob linked-list to dynamically add coordinates as we\n // read them in. At the end, put the array indices calculated from the\n // pixel coordinates into an array for quick access when we process\n // frames.\n \n numbadpix = 0; \n firstbad = NULL; \n lastbad = NULL;\n \n while( fgets(thisline,80,badfile) != NULL ) {\n count = sscanf(thisline,\"%i %i\",&x, &y);\n \n if( count == 2 ) { // If we read in a coordinate pair\n numbadpix ++;\n thisbad = new bloblist(0, (double)x, (double)y);\n \n if( firstbad == NULL ) { // If first bad pixel in the list\n\tfirstbad = thisbad;\n } else { // adding on new bad pixel to list\n\tlastbad->setnextblob(thisbad);\n\tthisbad->setprevblob(lastbad);\n }\n \n lastbad = thisbad;\n }\n }\n \n fclose(badfile);\n \n // Now traverse (and delete) linked list, calculating pixel coordinates\n \n badpixels = new unsigned int[numbadpix];\n thisbad = firstbad; // start at the beginning of the list\n \n i = 0;\n \n //printf(\"badpixels: %i\\n\",numbadpix);\n while( thisbad != NULL ) {\n\n badpixels[i] = (unsigned int) thisbad->gety()*xpix + \n (unsigned int) thisbad->getx();\n i++;\n nextbad = thisbad->getnextblob(); // get next blob\n delete thisbad; // delete the current one\n thisbad = nextbad; // move along\n }\n \n printf(\"Opened bad pixel file: %s with %i bad pixels.\\n\",\n\t fname,numbadpix);\n\n return 1;\n}\n\n\n// Set bad pixels to a value\n\nvoid frameblob::fix_badpix(MAPTYPE val) {\n#if FRAMEBLOB_DEBUG\n cout << \"[frameblob debug]: in fix_badpix method...\" << endl;\n#endif\n int i;\n\n if (badpixels != NULL) {\n for( i=0; i<(int)numbadpix; i++ ) { \n map[badpixels[i]] = val;\n }\n }\n}\n\n// ---------- Search Parameters -----------------------------------------\n\nvoid frameblob::set_satval( MAPTYPE in_satval ) {\n satval = in_satval;\n}\n\nvoid frameblob::set_grid( unsigned int in_grid ) {\n grid = in_grid;\n}\n\nvoid frameblob::set_threshold( double in_threshold ) {\n threshold = in_threshold;\n \n if( threshold < 0.2 ) threshold = 0.2; // place a hard limit\n}\n\nvoid frameblob::set_disttol( int in_disttol ) {\n disttol = in_disttol*in_disttol;\n}\n\nint frameblob::get_disttol(void) { \n return (int) sqrt((double) disttol); \n}\n\n\n// ---------- Calculate map statistics: mean/# saturated pixels/column --\n\nvoid frameblob::calc_mapstat() {\n#if FRAMEBLOB_DEBUG\n\tcout << \"[frameblob debug]: in calc_mapstat method...\" << endl;\n#endif\n unsigned int i, j, count,index;\n \n // initialize variables\n \n mapmean = 0;\n count = 0;\n memset(satcol,0,xpix*sizeof(int));\n\n unsigned int randx = rand() % (xpix-100);\n unsigned int randy = rand() % (ypix-100);\n\n for( j=randy; j<(randy+100); j++ ) { // j=row\n index = j*100; // inner loop columns to speed up addressing\n for( i=randx; i<(randx+100); i++ ) {\n/*\n for( j=0; j<ypix; j++ ) { // j=row\n index = j*xpix; // inner loop columns to speed up addressing\n for( i=0; i<xpix; i++ ) {\n*/\n if( map[index] > satval ) satcol[i]++; // if bad pixel\n else { // otherwise contributes to mean\n\tif( map[index] != satval ) { // pixel isn't bad\n\t mapmean += map[index];\n\t count ++;\n\t}\n }\n index++;\n }\n }\n \n if( count > 0 ) mapmean = mapmean / (double) count; // prevent / zero\n if( mapmean < 1 ) mapmean = 1;\t\t // prevent 0 means\n}\n\ndouble frameblob::get_mapmean() {\n if( mapmean == 0 ) calc_mapstat();\n return mapmean;\n}\n\ndouble frameblob::get_sigma() {\n return sigma;\n}\n\n\n// ---------- Search grid for coarse cells with sources -----------------\n\nvoid frameblob::calc_searchgrid() {\n#if FRAMEBLOB_DEBUG\n\tcout << \"[frameblob debug]: in the calc_searchgrid method...\" << endl;\n#endif\n// First calculate dimensions of the searchgrid array\n \n unsigned int xfull, yfull, xextra, yextra, xdim, ydim;\n \n xfull = xpix / grid; // # of full-sized cells\n yfull = ypix / grid;\t\n xextra = xpix % grid; // # extra pixels in small edge cells\n yextra = ypix % grid;\n \n xgrid = (xfull + (xextra>0)); // total # grid cells \n ygrid = (yfull + (yextra>0));\n ngrid = (xgrid+xextra) * ygrid;\n \n // unallocate searchgrid and meangrid before we start in case we have \n // run this function several times \n \n delete[] searchgrid;\n delete[] meangrid;\n \n searchgrid = new double[ngrid]; // S/N of brightest pixel/grid cell\n meangrid = new double[ngrid]; // array of grid cell means \n \n // Allocate an array to contain all the GRID*GRID elements within this\n // grid cell of our input map\n \n MAPTYPE *cell;\n cell = new MAPTYPE[grid*grid];\n \n MAPTYPE pix;\t\t // current pixel values\n MAPTYPE max;\t\t // the maximum value pixel in the cell\n int total; // running total elements in cell (big number)\n \n double meancell ; // cell mean\n double level;\t // max adjusted by centre value\n double sn;\t // signal to noise level of brightest pixel\n double x = 0;\t \t // x and y pixel positions for brightest pixels\n double y = 0;\t \t // for the large input map \n \n unsigned int i, j, k, l, mapindex, cellindex;\n int startx, endx, starty, endy;\n double thisflux;\n double M[D][D]; // small map centred over blob candidate\n double xcen, ycen, nap;\n int clip_startx, clip_endx, clip_starty, clip_endy;\n// int count=0;\n \n clearblobs(); // Make sure we don't have old blobs sitting around\n \n for( i=0; i<xgrid; i++ ) \n for( j=0; j<ygrid; j++ ) { \n // Sum all the elements within this cell of the input map.\n // Also make a list of the elements in the cell\n \n cellindex = 0;\n total = 0;\n max = 0;\n \n // Pixel dimensions of grid cell. grix*grid unless edge\n if( i==xfull ) xdim = xextra;\n else xdim = grid;\n if( j==yfull ) ydim = yextra;\n else ydim = grid;\n \n \n for( k=0; k<xdim; k++ ) \n\tfor( l=0; l<ydim; l++ ) {\n\t mapindex = (j*grid+l)*xpix + (i*grid+k);\n\t pix = map[mapindex];\n\t \n\t cell[cellindex] = pix;\n\t total += pix;\n\t \n\t // Check for greatest pixel brightness\n\t if( pix > max ) {\n\t x = (double) (i*grid + k); // store pixel coordinates\n\t y = (double) (j*grid + l);\t// of brightest pixel\t \n\t max = pix; \n\t }\t\t\t\t\t\n\t cellindex ++; // end of loop = # pixels in cell\n\t}\n \n // Get the mean for this cell\n meancell = (double) total / (cellindex);\n \n // Level is the brightness of a pixel - the mean level for the cell\n level = (double) max - meancell; \n \n // Calculate the sample variance about the central value\n\tif( mapmean == 0 ) calc_mapstat(); // Calculate the map mean\n\tif (stddev == 0) calc_stddev();\n\tsigma = stddev;\n/* Don't use noise model any more, finding map standard deviation is fast enough and much better\n\t if( mapmean < readout_offset ) sigma = readout_noise;\n else sigma = (double)sqrt(gain*(mapmean-readout_offset) + \n\t\t\t\treadout_noise*readout_noise); // Poisson\n if( sigma < 1 ) sigma = 1; // prevent 0 sigmas\n*/\n \n sn = level/sigma;\n \n // Store information about this grid cell\n searchgrid[j*xgrid+i] = sn; // s/n brightest pixel in cell\n meangrid[j*xgrid+i] = meancell; // mean of this cell\n \n // If we got a pixel > threshold sigma, possibly a source\n if( sn >= threshold ) {\n\t//printf(\"%i \",count);\n\t//count ++;\n\t\n\t// --------------------------------------------------------------\n\t// Decide if this is a single-point spike or a real source\n\t\n\tstartx = (int) x - 1; // Aperture boundaries\n\tstarty = (int) y - 1;\n\tendx = (int) x + 1;\n\tendy = (int) y + 1;\n\t\n\tif( startx < 0 ) startx = 0; // clipping map boundaries\n\tif( endx >= (int) xpix ) endx = xpix-1;\n\tif( starty < 0 ) starty = 0;\n\tif( endy >= (int) ypix ) endy = ypix-1;\n\t\n\tthisflux = 0.;\n\t\n\tnap = (double) (endx-startx+1)*(endy-starty+1); // pixels in ap.\n\n\t// add up flux centred over bright pixel\n\tfor( k=(unsigned int)startx; k<=(unsigned int)endx; k++ )\n\t\tfor( l=(unsigned int)starty; l<=(unsigned int)endy; l++ )\n\t thisflux += (double) map[l*xpix + k];\n\t\n\t// remove flux centre pixel and check remaining flux \n\t// exceeds the theoretical flux from pure noise \n\t// (check extendedness)\n\tthisflux -= max;\n\n\t// remove the baseline for the remaining pixels\n\tthisflux -= ((nap-1)*meancell);\n\n\t// Extended case\n\tif( (thisflux/(sqrt(nap-1)*sigma)) >= threshold ) {\t \n\t // ------------------------------------------------------------\n\t // Re-calculate the baseline over perimeter of a larger box\n\t \n\t startx = (int) x - D/2; // box boundary\n\t starty = (int) y - D/2;\n\t endx = startx + D-1;\n\t endy = starty + D-1;\n\t \n\t if( startx < 0 ) startx = 0; // clipping for boundaries\n\t if( endx >= (int) xpix ) endx = xpix-1;\n\t if( starty < 0 ) starty = 0;\n\t if( endy >= (int) ypix ) endy = ypix-1;\n\t \n\t meancell = 0;\n\t for( k=(unsigned int)startx; k<=(unsigned int)endx; k++ )\n\t meancell += (double) map[starty*xpix + k] + \n\t (double) map[endy*xpix + k];\n\t \n\t for( l=(unsigned int)starty+1; l<=(unsigned int)endy-1; l++ )\n\t meancell += (double) map[l*xpix + startx] + \n\t (double) map[l*xpix + endx];\n\t \n\t meancell /= ( 2*(endx-startx) + 2*(endy-starty) );\n\t \n // ------------------------------------------------------------\n\t // Centroid the blob\n\t \n\t startx = (int) x - D/2; \n\t starty = (int) y - D/2;\n\t endx = startx + D-1;\n\t endy = starty + D-1;\n\t \n\t if( startx < 0 ) clip_startx = 0; // clipping for boundaries\n\t else clip_startx = startx;\n\t \n\t if( endx >= (int) xpix ) clip_endx = xpix-1;\n\t else clip_endx = endx;\n\t \n\t if( starty < 0 ) clip_starty = 0;\n\t else clip_starty = starty;\n\t \n\t if( endy >= (int) ypix ) clip_endy = ypix-1;\n\t else clip_endy = endy;\n\t \n\t // boundary case\n\t if( (startx != clip_startx) || (starty != clip_starty) ||\n\t (endx != clip_endx) || (endy != clip_endy) ) {\n\t \n\t // fill the sub-map with the mean value\n\t for( k=0; k<D; k++ )\n\t for( l=0; l<D; l++ )\n\t\tM[k][l] = (double) meancell;\n\t \n\t // paste in the useful part of the map\n\t\tfor( k=(unsigned int)clip_startx-startx; k<(unsigned int)clip_endx-startx; k++ )\n\t\t\tfor( l=(unsigned int)clip_starty-starty; l<(unsigned int)clip_endy-starty; l++ )\n\t\tM[k][l] = (double) map[(l+clip_starty)*xpix + \n\t\t\t\t k+clip_startx];\n\t }\n\t \n\t // normal case\n\t else {\n\t for( k=0; k<D; k++ )\n\t for( l=0; l<D; l++ )\n\t\tM[k][l] = (double) map[(l+starty)*xpix + k+startx];\n\t }\n\t \n\t // Find the centroid in this small map\n\t findCentre( &xcen, &ycen, &thisflux, M );\n\t \n\t // Correct for the baseline and final check realness\n\t thisflux = thisflux - meancell;\n\t \n\t //printf(\"Flux: %lf Sigma: %lf\\n\",\n\t //thisflux,sqrt(convweight)*sigma);\n\n\t // Add to the list if significant\n\t if( thisflux/(sqrt(convweight)*sigma) >= threshold ) {\n\t addblob( (int)thisflux, x+xcen+0.5, y+ycen+0.5 ); \n\t thisblob->setmean(meancell);\n\t thisblob->setsnr( (double)thisflux / \n\t\t\t (sqrt(convweight)*sigma) );\n\t }\n\t}\n\t\n\t// --------------------------------------------------------------\n }\n }\n \n // clean up\n delete[] cell;\n}\n\n// ---------- Barth's improved convolution centroid finder --------------\n\ndouble frameblob::convolve(double x, double y, double *noise, \n\t\t\t double M[D][D]) {\n int i, j;\n int xi, yi;\n double dx2, dy2, r2;\n double T=0, Tw = 0, w;\n \n *noise = 0; // Added by EC - calculate expected noise in the aperture\n \n for (i=-R-1; i<=R+1; i++) {\n\txi = (int)floor(x + i+0.5);\n dx2 = x-(double)xi;\n dx2*=dx2;\n\n if (xi<0) xi = 0;\n if (xi>D-1) xi = D-1;\n\n for (j=-R-1; j<=R+1; j++) {\n\t yi = (int)floor(y + j+0.5);\n dy2 = y-(double)yi;\n dy2*=dy2;\n \n if (yi<0) yi = 0;\n if (yi>D-1) yi = D-1;\n \n r2 = dx2 + dy2;\n \n if (r2>R*R) {\n w = 0;\n } else {\n w = (-r2 + R*R)/R*R;\n }\n \n Tw+=w;\n T+=w*M[xi][yi];\n \n *noise += w*w;\n }\n }\n \n *noise /= Tw*Tw; // multiple by sigma^2 in a pixel to get \n // sigma^2 in aperture\n return (T/Tw);\n}\n\nvoid frameblob::findCentre(double *x, double *y, double *z, \n\t\t\t double M[D][D]) {\n double z1, z2, z3;\n double C;\n int j;\n double dp, sx, sy;\n double w;\n \n *x = *y = 0.0;\n \n C = floor( (double) D/2); // centre of map - our starting guess\n \n sx = sy = 1.0;\n double find_stddev(void);\n\n for (j=0; j<10; j++) {\n // last find best x along best y row\n z1 = convolve(C-sx+*x, C+*y, &w, M);\n z2 = convolve(C+*x, C+*y, &convweight, M);\n z3 = convolve(C+sx+*x, C+*y, &w, M);\n \n if (z2 > (z1 + z3)/2) {\n dp = (z1-z2)/(z1+z3-z2-z2) - 0.5;\n \n /* only believe if we bounded the max */\n if (dp>1) {\n dp = sx;\n } else if (dp<-1) {\n dp = -sx;\n } else {\n dp *= sx;\n sx*=0.7;\n }\n } else {\n if (z1>z3) dp = -sx;\n else dp = sx;\n }\n *x += dp;\n \n //fprintf(stderr, \"x: %g %g %g %g\\n\", *x, z1, z2, z3);\n \n // now find best y along best x row\n z1 = convolve(C+*x, C-sy+*y, &w, M);\n z2 = convolve(C+*x, C+*y, &convweight, M);\n z3 = convolve(C+*x, C+sy+*y, &w, M);\n \n if (z2 > (z1 + z3)/2) {\n dp = (z1-z2)/(z1+z3-z2-z2) - 0.5;\n \n /* only believe if we bounded the max */\n if (dp>1) {\n dp = sy;\n } else if (dp<-1) {\n dp = -sy;\n } else {\n dp *= sy;\n sy*=0.7;\n }\n } else {\n if (z1>z3) dp = -sy;\n else dp = sy;\n }\n \n *y += dp;\n \n //fprintf(stderr, \"x: %g y: %g %g | %g %g %g\\n\",\n // *x, *y, dp, z1, z2, z3);\n if (sy<0.2 && sx < 0.2) break;\n }\n \n *z = z2;\n}\n\n// ---------- Set the gain and other noise statistics parameters --------\n\nvoid frameblob::set_gain( double in_gain ) {\n gain = in_gain;\n}\n\nvoid frameblob::set_readout_offset( double in_readout_offset ) {\n readout_offset = in_readout_offset;\n}\n\nvoid frameblob::set_readout_noise( double in_readout_noise ) {\n readout_noise = in_readout_noise;\n}\n\n// ---------- Check for multiple sources --------------------------------\n\nvoid frameblob::fix_multiple() {\n#if FRAMEBLOB_DEBUG\n\tcout << \"[frameblob debug]: in fix_multiple method...\" << endl;\n#endif\n int ref_x, ref_y, ref_dist, ref_flux;\n //int maxflux;\n \n bloblist *refblob, *compareblob;\n bloblist *nextcomp;\n \n // Traverse blob list\n refblob = firstblob;\n while( refblob != NULL ) {\n ref_x = (int) refblob->getx();\n ref_y = (int) refblob->gety();\n ref_flux = refblob->getflux();\n \n // Compare each blob to the reference\n compareblob = firstblob;\n while( compareblob != NULL ) {\n nextcomp = compareblob->getnextblob();\n if( compareblob != refblob ) {\n\tref_dist = (ref_x-(int)compareblob->getx()) *\n\t (ref_x-(int)compareblob->getx()) + \n\t (ref_y-(int) compareblob->gety()) *\n\t (ref_y-(int)compareblob->gety());\n\t\n\t// if blob is close to the reference and fainter, delete it\n\tif( (ref_dist <= disttol) && (compareblob->getflux() <= \n\t\t\t\t ref_flux) )\n\t deleteblob(compareblob);\n }\n compareblob = nextcomp;\n }\n refblob = refblob->getnextblob();\n }\n}\n\n//compute and return the map standard deviation\ndouble frameblob::calc_stddev(void)\n{\n#if FRAMEBLOB_DEBUG\n\tcout << \"[frameblob debug]: in find_stddev method...\" << endl;\n#endif\n\n if (mapmean == 0) calc_mapstat();\n unsigned int i, j, count = 0, index;\n stddev = 0;\n\n unsigned int xrand = rand() % (xpix-100);\n unsigned int yrand = rand() % (ypix-100);\n\n for( j=yrand; j<(yrand+100); j++ ) { // j=row\n index = j*100; // inner loop columns to speed up addressing\n for( i=xrand; i<(xrand+100); i++ ) {\n/* \n for( j=0; j<ypix; j++ ) { // j=row\n\t index = j*xpix; // inner loop columns to speed up addressing\n\t for( i=0; i<xpix; i++ ) {\n*/\n //printf(\"%i \",map[index]);\n \n\t\t if( map[index] <= satval ) { \n\t\t\t if( map[index] != satval ) { // pixel isn't bad\n\t\t\t\t stddev += ((double)map[index] - mapmean)*((double)map[index] - mapmean);\n\t\t\t\t count ++;\n\t\t\t }\n\t\t }\n\t\t index++;\n\t }\n }\n\t\n if( count > 0 ) stddev = stddev / (double) count; // prevent / zero\n stddev = sqrt(stddev);\n if (stddev < 1) stddev = 1; //prevent 0 standard deviation\n return stddev;\n}\n\n" }, { "alpha_fraction": 0.6636771559715271, "alphanum_fraction": 0.6636771559715271, "avg_line_length": 19.363636016845703, "blob_id": "00f647f12a0d91ccf4b90bb2eb86c1bd2f548236", "content_id": "7096b4eb8e52a958fc3915265ae913ab40851d54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 223, "license_type": "no_license", "max_line_length": 42, "num_lines": 11, "path": "/external_libs/soem/osal/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "set(OSAL_SRCS\n ${OSAL_SRCS}\n ${CMAKE_CURRENT_SOURCE_DIR}/osal.c\n PARENT_SCOPE\n)\nset(OSAL_HEADERS\n ${OSAL_HEADERS}\n ${CMAKE_CURRENT_SOURCE_DIR}/osal.h\n ${CMAKE_CURRENT_SOURCE_DIR}/osal_defs.h\n PARENT_SCOPE\n)" }, { "alpha_fraction": 0.5877577662467957, "alphanum_fraction": 0.6053093671798706, "avg_line_length": 34.88976287841797, "blob_id": "e1113f22f78e8145d31b4ba39490c417b4dd1846", "content_id": "b38e4db7cd5484f8b2bd799c7814f83b6e7b56fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4558, "license_type": "no_license", "max_line_length": 80, "num_lines": 127, "path": "/common/include/blast_compiler.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * blast_compiler.h: \n *\n * This software is copyright \n * (C) 2013-2014 California State University, Sacramento\n *\n * This file is part of mcp, created for the BLASTPol Project.\n *\n * mcp 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Feb 18, 2015 by seth\n */\n\n#ifndef BLAST_COMPILER_H_\n#define BLAST_COMPILER_H_\n\n#include <portable_endian.h>\n\n#define likely(x) __builtin_expect(!!(x), 1)\n#define unlikely(x) __builtin_expect(!!(x), 0)\n\n#ifndef __bswap_constant_32\n /* Swap bytes in 32 bit value. */\n #define __bswap_constant_32(x) \\\n ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) |\t\t \\\n (((x) & 0x0000ff00) << 8) | (((x) & 0x000000ff) << 24))\n#endif\n\n#if __BYTE_ORDER == __LITTLE_ENDIAN\n# define tole(x) (x)\n# define tobe(x) __bswap_constant_32(x)\n#else\n# define tole(x) __bswap_constant_32(x)\n# define tobe(x) (x)\n#endif\n\n/* Are two types/vars the same type (ignoring qualifiers)? */\n#ifndef __same_type\n# define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))\n#endif\n\n#ifndef __compiletime_warning\n# define __compiletime_warning(message)\n#endif\n#ifndef __compiletime_error\n# define __compiletime_error(message)\n# define __compiletime_error_fallback(condition) \\\n do { ((void)sizeof(char[1 - 2 * condition])); } while (0)\n#else\n# define __compiletime_error_fallback(condition) do { } while (0)\n#endif\n\n#define __compiletime_assert(condition, msg, prefix, suffix) \\\n do { \\\n bool __cond = !(condition); \\\n extern void prefix ## suffix(void) __compiletime_error(msg); \\\n if (__cond) \\\n prefix ## suffix(); \\\n __compiletime_error_fallback(__cond); \\\n } while (0)\n\n#define _compiletime_assert(condition, msg, prefix, suffix) \\\n __compiletime_assert(condition, msg, prefix, suffix)\n\n/**\n * compiletime_assert - break build and emit msg if condition is false\n * @condition: a compile-time constant condition to check\n * @msg: a message to emit if condition is false\n *\n * In tradition of POSIX assert, this macro will break the build if the\n * supplied condition is *false*, emitting the supplied error message if the\n * compiler has support to do so.\n */\n#define compiletime_assert(condition, msg) \\\n _compiletime_assert(condition, msg, __compiletime_assert_, __LINE__)\n\n#ifndef __always_inline\n #define __always_inline __inline __attribute__((always_inline))\n#endif\n#define __deprecated __attribute__((deprecated))\n#define __packed __attribute__((packed))\n#ifndef __weak\n #define __weak __attribute__((weak))\n#endif\n\n/*\n * From the GCC manual:\n *\n * Many functions have no effects except the return value and their\n * return value depends only on the parameters and/or global\n * variables. Such a function can be subject to common subexpression\n * elimination and loop optimization just as an arithmetic operator\n * would be.\n * [...]\n */\n#ifndef __pure\n #define __pure __attribute__((pure))\n#endif\n#define __aligned(x) __attribute__((aligned(x)))\n#define __printf(a, b) __attribute__((format(printf, a, b)))\n#define __scanf(a, b) __attribute__((format(scanf, a, b)))\n#ifndef __noinline\n #define __noinline __attribute__((noinline))\n#endif\n#define __maybe_unused __attribute__((unused))\n#define __always_unused __attribute__((unused))\n/*\n * A trick to suppress uninitialized variable warning without generating any\n * code\n */\n#define uninitialized_var(x) x = x\n\n\n#endif /* BLAST_COMPILER_H_ */\n" }, { "alpha_fraction": 0.6692190170288086, "alphanum_fraction": 0.6753445863723755, "avg_line_length": 15.743589401245117, "blob_id": "e5df774adbf7b367658e6f8718791a4f5fe5add9", "content_id": "719160d9e49544e27b35d51245048a8f36d0240d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 654, "license_type": "no_license", "max_line_length": 73, "num_lines": 39, "path": "/stars/code/solving/refitting/refitter.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__REFITTING__REFITTER_H\n#define SOLVING__REFITTING__REFITTER_H\n\n#include \"shape_fitter.h\"\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n}\n\nnamespace Solving\n{\n class Solution;\n namespace Refitting\n {\n class Refitter;\n }\n}\n\nclass Solving::Refitting::Refitter\n{\n public:\n void fit(Solution& solution, Shared::Image::Raw& image);\n\n private:\n ShapeFitter shape_fitter;\n};\n\n#endif\n" }, { "alpha_fraction": 0.7011908292770386, "alphanum_fraction": 0.7078371644020081, "avg_line_length": 34.05825424194336, "blob_id": "a163fc8c2279d8ea255ca97199c34ef829cc23a4", "content_id": "7cc847f344130ceb0df207fc2f386c9acb95e7f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3612, "license_type": "no_license", "max_line_length": 105, "num_lines": 103, "path": "/stars/code/imaging/lens.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef IMAGING__LENS_H\n#define IMAGING__LENS_H\n\n#pragma warning(push)\n#pragma warning(disable: 4996) // disable warning from boost::is_any_of\n#include <boost/asio.hpp>\n#pragma warning(pop)\n#include <vector>\n#include <string>\n#include <boost/thread/thread.hpp>\n#include \"autofocuser.h\"\n#include \"commands.h\"\n#include \"../tools/timing.h\"\n\n// Sending commands over the serial port\n// * process_requests calls send_message with a message string\n// * send_message calls clear_read_buffer\n// * clear_read_buffer calls asynchronous read with 0.100 s timeout\n// * clear_read_buffer sleeps 0.500 s\n// * send_message calls write\n// * send_message calls asynchronous read with a (unspecified here to avoid header compilation) timeout\n// * send_message sleeps 2000 ms by default or wait_ms milliseconds if specified\n\n// Example of interthread communication\n// A get_focus request comes from fcp into the networking thread.\n// * networking/connection.cpp passes request to imaging/camera_shell.cpp\n// * via Shared::Lens::requests_for_camera\n// * imaging/camera_shell.cpp passes request to imaging/lens.cpp\n// * via Shared::Lens::requests_for_lens\n// * lens.cpp decides if there's a new get_focus request\n// * by comparing class member request_counter_get_focus to Shared::Lens::requests_for_lens\n// * acts on the new request\n// * lens.cpp gets the result of the new get_focus request\n// * sets results_for_camera.get_focus.counter = requests_for_lens.get_focus.counter\n// * puts the new value into Shared::Lens::results_for_camera\n// * imaging/lens.cpp passes result to imaging/camera_shell.cpp\n// * via Shared::Lens::results_for_camera\n// * imaging/camera_shell.cpp passes result to networking/connection.cpp\n// * via Shared::Lens::results_for_network\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Imaging\n{\n using namespace LensCommands;\n class Lens;\n}\n\nclass Imaging::Lens\n{\n public:\n Lens(Parameters::Manager& params);\n ~Lens();\n void init();\n void parse_birger_result(std::string line, commands_t command);\n void process_request(commands_t command, std::string message,\n bool initiate_get_focus, bool initiate_get_aperture);\n void process_request(commands_t command, std::string message,\n bool initiate_get_focus, bool initiate_get_aperture, bool use_value);\n void process_requests();\n void send_message(std::string message, commands_t command, int wait_ms=2000);\n void handle_read_timeout(const boost::system::error_code& error);\n void handle_read(commands_t command, const boost::system::error_code& error, size_t size);\n void clear_read_buffer();\n void check_device(std::string device_name);\n void find_device();\n void connect();\n void update();\n void run();\n void wait_for_quit();\n int get_wait_ms(commands_t command, int command_value);\n\n private:\n Autofocuser autofocuser;\n\n boost::asio::io_service io;\n boost::asio::serial_port port;\n boost::asio::deadline_timer read_timeout;\n bool enabled;\n bool init_on_startup;\n std::string which_sensor;\n Tools::Timer find_device_timer;\n double find_device_period;\n std::vector<std::string> device_names;\n int baud_rate;\n boost::asio::streambuf instream;\n int command_fcp_counters[num_commands];\n int command_stars_counters[num_commands];\n\n boost::thread thread;\n};\n\n#endif\n" }, { "alpha_fraction": 0.5168295502662659, "alphanum_fraction": 0.5551031231880188, "avg_line_length": 24.23287582397461, "blob_id": "63bfb35c7747c67b7c0df9cc6dfc8bdefd48ba5b", "content_id": "2c653ffa292084dacfcd128267c3f3a2f4cd58f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3684, "license_type": "no_license", "max_line_length": 119, "num_lines": 146, "path": "/common/fir.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* mcp: the BLAST master control program\n *\n * This software is copyright (C) 2005-2006 University of Toronto\n * (C) 2015-2016 University of Pennsylvania\n *\n * This file is part of mcp.\n *\n * mcp 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <float.h>\n\n#include \"blast.h\"\n#include \"fir.h\"\n\nstatic double sinc(double x)\n{\n return abs(x) <= DBL_EPSILON ? 1.0f : sin(M_PI * x) / (M_PI * x);\n}\nstatic double rect(double n, double N, double alpha)\n{\n (void)alpha;\n return n >= 0.0 && n < N ? 1.0 : 0.0;\n}\nstatic double hann(double n, double N, double alpha)\n{\n (void)alpha;\n return 0.5 * (1.0 - cos(2.0 * M_PI * n / (N - 1.0)));\n}\nstatic double hamming(double n, double N, double alpha)\n{\n (void)alpha;\n return 0.54 - 0.46 * cos(2.0 * M_PI * n / (N - 1.0));\n}\nstatic double lanczos(double n, double N, double alpha)\n{\n (void)alpha;\n return sinc(2.0 * n / (N - 1.0) - 1.0);\n}\nstatic double gauss(double n, double N, double o)\n{\n return exp(- 1.0/2.0 * pow((n - (N - 1.0) / 2.0) / (o * (N - 1.0) / 2.0), 2.0));\n}\nstatic double blackman(double n, double N, double alpha)\n{\n return 0.5 * (1.0 - alpha) - 0.5 * cos(2.0 * M_PI * n / (N - 1.0)) + 0.5 * alpha * cos(4.0 * M_PI * n / (N - 1.0));\n}\nstatic double old_blast(double n, double N, double alpha)\n{\n (void) alpha;\n return exp(- pow((n - N / 2.0) / (N / 4.5), 2.0));\n}\n\ntypedef double (*window_fn)(double, double, double);\nstatic window_fn window_filt[] = {\n [wind_oldblast] = old_blast,\n [wind_blackman] = blackman,\n [wind_gauss] = gauss,\n [wind_lanczos] = lanczos,\n [wind_hamming] = hamming,\n [wind_hann] = hann,\n [wind_rect] = rect\n};\n\nvoid init_fir(fir_t *fs, int N, int window, double alpha)\n{\n int i;\n double sw = 0.0;\n\n for (i = 0; i < NSTAGE; i++) {\n fs->sum[i] = 0;\n fs->i_w[i] = i * N / NSTAGE;\n }\n\n fs->out = 0;\n fs->ns = N;\n\n fs->w = (double *) balloc(fatal, N * sizeof(double));\n\n if (window < wind_oldblast || window > wind_rect) window = wind_oldblast;\n for (i = 0; i < N; i++) {\n fs->w[i] = window_filt[window](i, N, alpha);\n sw += fs->w[i];\n }\n for (i = 0; i < N; i++) {\n fs->w[i] /= sw;\n }\n}\n\nvoid deinit_fir(fir_t *fs)\n{\n bfree(err, fs->w);\n}\n\ndouble fir_filter(double x, fir_t *fs)\n{\n int i, i_stage;\n\n for (i_stage = 0; i_stage < NSTAGE; i_stage++) {\n i = fs->i_w[i_stage];\n\n fs->sum[i_stage] += fs->w[i] * x;\n\n i++;\n if (i >= fs->ns) {\n fs->out = fs->sum[i_stage];\n i = 0;\n fs->sum[i_stage] = 0;\n }\n fs->i_w[i_stage] = i;\n }\n return (fs->out);\n}\n\n#if 0\nint main()\n{\n double x;\n struct FirStruct fs;\n int i;\n\n init_fir(&fs, 100.0 * 30.0 * 60.0);\n\n for (i = 0; i < 1000000; i++) {\n x = sin(2.0 * M_PI * (double) i / 4000) + sin(2.0 * M_PI * (double) i / 8000);\n printf(\"%g %g\\n\", x, fir_filter(x, &fs));\n }\n return (0);\n}\n#endif\n" }, { "alpha_fraction": 0.6704288721084595, "alphanum_fraction": 0.678329586982727, "avg_line_length": 22.945945739746094, "blob_id": "56060ca0bb6ac6194cc233c1de755a9e2f331273", "content_id": "6e5c760f4d0277de5f6f3696865fe73210e87c5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 886, "license_type": "no_license", "max_line_length": 74, "num_lines": 37, "path": "/starcam/fixbadpixel.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* fixbadpixel.cpp\n *\n * utility program to apply a bad pixel file to an image\n * also high-pass filters\n *\n */\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <fstream>\n\n#include \"blobimage.h\"\n#include \"camstruct.h\"\n\nusing namespace std;\n\nconst char* badpixfilename = \"/tmp/badpix.txt\";\nconst char* outfilename = \"/tmp/fixed.sbig\";\nconst unsigned int box_size = 15;\nconst unsigned int n_boxes = 3;\n\nint main(int argc, char* argv[])\n{\n if (argc != 2) {\n cerr << \"Must specify an image file as parameter\" << endl;\n }\n cout << \"Opening Image File \" << argv[1] << endl;\n BlobImage bimg(CAM_HEIGHT, CAM_WIDTH);\n bimg.OpenImage(argv[1]);\n bimg.FixBadpix(\"/tmp/badpix.txt\");\t //don't test already detected blobs\n bimg.highPassFilter(box_size, n_boxes);\n\n cout << \"Saving corrected image to \" << outfilename << endl;\n bimg.SaveImage(outfilename);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.7006880640983582, "alphanum_fraction": 0.7052752375602722, "avg_line_length": 18.81818199157715, "blob_id": "b47a0beed3422fe552228ad85956e24d0dd319f3", "content_id": "8455196ce3b271809b9a825ce1943e47e62104dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 873, "license_type": "no_license", "max_line_length": 73, "num_lines": 44, "path": "/stars/code/shared/simulations/brightness.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__SIMULATIONS__BRIGHTNESS_H\n#define SHARED__SIMULATIONS__BRIGHTNESS_H\n\n#include \"../circular_buffer.h\"\n\nstruct XSCBrightness;\n\nnamespace Shared\n{\n namespace Simulations\n {\n\nclass Brightness\n{\n public:\n Brightness();\n Brightness& operator=(const Brightness& rhs);\n Brightness& operator=(const XSCBrightness& rhs);\n void init(Parameters::Manager& params);\n\n int counter;\n bool allow_enable;\n bool enabled;\n double level_kepsa;\n double gain_db;\n double actual_exposure;\n double simulated_exposure;\n};\n\n// writes: network\n// reads: camera\nextern Shared::CircularBuffer <Brightness> brightness;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.6734693646430969, "alphanum_fraction": 0.68483966588974, "avg_line_length": 26.886178970336914, "blob_id": "5e3c99631892d7ec4c09113811e505d5acae3211", "content_id": "e04cdee243f9f46f986ebcd21a4a3cce97cc32d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3430, "license_type": "no_license", "max_line_length": 81, "num_lines": 123, "path": "/defricher/defricher.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* defile: converts BLAST-type framefiles into dirfiles\n *\n * This software is copyright (C) 2004-2005 D. V. Wiebe\n * \n * This file is part of defile.\n * \n * defile 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 2 of the License, or\n * (at your option) any later version.\n * \n * defile 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 defile; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#ifndef DEFILE_H\n#define DEFILE_H\n\n#include <stdbool.h>\n#include <sys/time.h> /* SYSV time (struct timeval, struct timezone) */\n#include <netinet/in.h> /* ARPA Internet specification (struct sockaddr_in) */\n\n/* Don't use PATH_MAX. It isn't. */\n#define FR_PATH_MAX 8192\n\n#include <dirent.h> /* for MAXNAMELEN on BSD */\n#include \"linklist.h\"\n#ifndef NAME_MAX\n#ifdef MAXNAMELEN\n#define NAME_MAX MAXNAMELEN\n#else\n#define NAME_MAX 255 /* iunno */\n#endif\n#endif\n\n\n#if FIELD_LEN < 6\n# define FIELD_MAX 6\n#else\n# define FIELD_MAX FIELD_LEN\n#endif\n\nstruct rc_struct {\n int auto_reconnect, daemonise, force_quenya, force_stdio, flakey_source,\n framefile, gzip_output, persist, quenya, remount, silent, write_curfile,\n extra_format;\n int write_mode; /* 0 = normal ; 1 = overwrite ; 2 = resume */\n\n struct sockaddr_in addr;\n int csock, dsock;\n\n int sufflen;\n long int resume_at;\n int source_is_curfile;\n char* symlink_name;\n char* remount_dir;\n char* output_curfile;\n char* output_dirfile;\n char* source;\n char* dest_dir;\n char* linklist_file;\n\n struct timezone tz;\n char* chunk;\n char* dirfile;\n char* dirname;\n char* hostname;\n char* telemetry; // lab, highrate, biphase, pilot\n\n linklist_t *ll;\n};\n\nstruct ri_struct {\n int read;\n int chunk_total;\n int old_total;\n int reader_done;\n\n struct timeval last; // Last time written to dirfile\n int lw; // Total number of samples written previously\n int lr; // Total number of samples written previously\n int wrote; // Current number of samples written\n bool new_channels; // Have we received a new channels structure?\n bool channels_ready; // Is the channels structure initialized?\n bool symlink_updated; // Is the symbolic link current with the new dirfile?\n bool writer_done;\n bool tty; // Boolean is there a message for output?\n bool frame_rate_reset; // Boolean to reset the framerate to the default\n};\n\n/* interthread communication */\nextern struct rc_struct rc;\nextern struct ri_struct ri;\n\n#include \"FIFO.h\"\nextern struct Fifo fifo_data[RATE_END];\n\nextern sigset_t signals;\n\n#ifdef DEBUG\n# define dtracevoid() printf(\"%s()\\n\", __FUNCTION__)\n# define dtrace(fmt, ...) printf(\"%s(\" fmt \")\\n\", __FUNCTION__, __VA_ARGS__)\n# define dreturn(fmt, val) printf(\"%s = \" fmt \"\\n\", __FUNCTION__, val)\n#if DEBUG & 0x1\n# define DEBUG_FASTSAME\n#endif\n#if DEBUG & 0x2\n# define DEBUG_SEQUENCING\n#endif\n#else /* not debug */\n# define dtracevoid()\n# define dtrace(...)\n# define dreturn(...)\n#endif /* defined DEBUG */\n\n#endif\n" }, { "alpha_fraction": 0.636449933052063, "alphanum_fraction": 0.6753678321838379, "avg_line_length": 25.012346267700195, "blob_id": "2c86c9e6abd6049cfd776eb21f24a7d2aaf7f6a2", "content_id": "1fbdfaa4e53aaf3392201e978e584cb0d5d875d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2107, "license_type": "no_license", "max_line_length": 85, "num_lines": 81, "path": "/common/CRC_func.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * CRC.c: \n *\n * This software is copyright \n * (C) 2015-2018 University of Toronto, Toronto, ON\n *\n * This file is part of the SuperBIT project, modified and adapted for BLAST-TNG.\n *\n * linklist 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 2 of the License, or\n * (at your option) any later version.\n *\n * linklist 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Jan 25, 2018 by Javier Romualdez\n */\n\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <string.h>\n#include <math.h>\n#include <stdint.h>\n\n#include \"CRC_func.h\" // CRC checks and generators for message validation\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nuint16_t *crctable = NULL;\n\n// generates and returns a CRC table for serial validation of DPRALTE\nuint16_t *mk_crctable(uint16_t poly, uint16_t (*crcfn)(uint16_t, uint16_t, uint16_t))\n{\n\tuint16_t *crctable;\n\tint i;\n\tif ((crctable = (uint16_t *)malloc(256*sizeof(unsigned))) == NULL) {\n\t\treturn NULL;\n\t}\n\tfor (i = 0; i < 256; i++) {\n\t\tcrctable[i] = (*crcfn)(i, poly, 0);\n\t}\n\treturn crctable;\n}\n\n// generator for CRC table\nuint16_t crchware(uint16_t data, uint16_t genpoly, uint16_t accum)\n{\n\tstatic int i;\n\tdata <<= 8;\n\tfor (i = 8; i > 0; i--) {\n\t if ((data ^ accum) & 0x8000) {\n accum = (accum << 1) ^ genpoly;\n\t } else {\n accum <<= 1;\n }\n\t data <<= 1;\n\t}\n\treturn accum;\n}\n\n// checks/generates a CRC value for received/sent message\nvoid crccheck(uint16_t data, uint16_t *accumulator, uint16_t *crctable)\n{\n\t*accumulator = (*accumulator << 8) ^ crctable[(*accumulator >> 8) ^ data];\n}\n\n#ifdef __cplusplus\n}\n#endif\n" }, { "alpha_fraction": 0.7439786195755005, "alphanum_fraction": 0.7618197798728943, "avg_line_length": 37.655174255371094, "blob_id": "2ba06cbd43134b62f493972bf23ff214c22ca269", "content_id": "c6a4648ea8312fb8b94a02ae49df06f528420e20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1122, "license_type": "no_license", "max_line_length": 101, "num_lines": 29, "path": "/stars/code/tools/angles.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef TOOLS__ANGLES_H\n#define TOOLS__ANGLES_H\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\ndouble from_hours(double angle);\ndouble to_hours(double angle);\ndouble from_degrees(double angle);\ndouble to_degrees(double angle);\ndouble from_arcsec(double angle);\ndouble to_arcsec(double angle);\ndouble from_arcmin(double angle);\ndouble to_arcmin(double angle);\ndouble great_circle(double ra0, double dec0, double ra1, double dec1);\nbool angles_within_basic(double ra0, double dec0, double ra1, double dec1, double distance);\nbool angles_within(double ra0, double dec0, double ra1, double dec1, double distance);\ndouble tanplane_distance(double x0, double y0, double x1, double y1, double iplatescale);\nvoid equatorial_to_horizontal(double ra, double dec, double lat, double lst, double &az, double &el);\nvoid horizontal_to_equatorial(double az, double el, double lat, double lst, double& ra, double& dec);\n\n#endif\n" }, { "alpha_fraction": 0.4763064384460449, "alphanum_fraction": 0.5006555318832397, "avg_line_length": 25.430692672729492, "blob_id": "8e57844b5515b82a4e4d552b1ebd70a36e61399c", "content_id": "fb2df853c23a90d865d3f1b70640e0e455184275", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5339, "license_type": "no_license", "max_line_length": 91, "num_lines": 202, "path": "/news/rumor.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <termios.h>\n#include <time.h>\n#include <math.h>\n#include <string.h>\n#include <ctype.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <netdb.h>\n#include <sys/ioctl.h>\n#include <time.h>\n#include <stdint.h>\n\n#include <getdata.h>\n\n#include \"include/slowdl.h\"\n#include \"news.h\"\n\n#define RAWDIR \"/data/rawdir\"\n\n#define LNKFILE \"/data/etc/rumor.lnk\"\n\n#define PORT 11111\n\nextern struct SlowDlStruct slowDLList[];\n\nint tty_fd;\nchar hostname[255];\n\nvoid Usage() {\n printf(\"rumor <hostname>\\n Connects to an lnc server at hostname to\\n\"\n \"download and append to a dirfile.\\n\");\n exit(0);\n}\n\nint main(int argc, char *argv[]) {\n char dirfilename[1024];\n int i_ch;\n char fieldlist[255][255];\n DIRFILE *df_out;\n int fp_lnc;\n int n_read = 0;\n struct fifoStruct fs;\n \n int i_frame = 0;\n \n uint8_t c_in;\n int16_t s_in;\n uint16_t u_in;\n int32_t S_in;\n uint32_t U_in;\n double x_in;\n \n time_t t;\n\n fs.i_in = fs.i_out = 0;\n\n if (argc!=2) Usage();\n if (argv[1][0]=='-') Usage();\n \n strncpy(hostname, argv[1], 250);\n \n sprintf(dirfilename, \"%s/%lu.l\", RAWDIR, time(NULL));\n df_out = gd_open(dirfilename, GD_RDWR | GD_UNENCODED | GD_CREAT | GD_TRUNC);\n /* add fields to dirfile */\n for (i_ch =0; slowDLList[i_ch].name[0] != '\\0'; i_ch++) {\n convertToUpper(slowDLList[i_ch].name, fieldlist[i_ch]);\n if (slowDLList[i_ch].encode == SDL_SCALE) {\n gd_add_raw(df_out, fieldlist[i_ch], GD_FLOAT64, 1, 0);\n } else {\n switch (slowDLList[i_ch].type) {\n case 'c':\n gd_add_raw(df_out, fieldlist[i_ch], GD_UINT8, 1, 0);\n break;\n case 's':\n gd_add_raw(df_out, fieldlist[i_ch], GD_INT16, 1, 0);\n break;\n case 'u':\n gd_add_raw(df_out, fieldlist[i_ch], GD_UINT16, 1, 0);\n break;\n case 'S':\n gd_add_raw(df_out, fieldlist[i_ch], GD_INT32, 1, 0);\n break;\n case 'U':\n gd_add_raw(df_out, fieldlist[i_ch], GD_UINT32, 1, 0);\n break;\n default:\n break; // shouldn't be possible\n }\n } \n }\n gd_flush(df_out, NULL);\n \n unlink(LNKFILE);\n if (symlink(dirfilename, LNKFILE)<0) {\n fprintf(stderr, \"could not create link from `%s' to `%s'\",\n dirfilename, LNKFILE);\n exit(0);\n }\n\n strncpy(hostname, argv[1], 250);\n \n fp_lnc = party_connect(hostname, PORT);\n \n while (1) {\n do {\n if (nFifo(&fs)<4) {\n n_read += BlockingRead(4, &fs, fp_lnc, hostname, PORT);\n }\n peek(&fs, (char *)&U_in, 4);\n advance(&fs, 1);\n } while (U_in != SLOWDLSYNCWORD);\n \n advance(&fs, 4-1);\n \n for (i_ch =0; slowDLList[i_ch].name[0] != '\\0'; i_ch++) {\n // read the word\n switch (slowDLList[i_ch].type) {\n case 'c':\n if (nFifo(&fs)<1) {\n n_read += BlockingRead(1, &fs, fp_lnc, hostname, PORT);\n }\n pop(&fs, (char *)&c_in, 1);\n break;\n case 's':\n if (nFifo(&fs)<2) {\n n_read += BlockingRead(2, &fs, fp_lnc, hostname, PORT);\n }\n pop(&fs, (char *)&s_in, 2);\n break;\n case 'u':\n if (nFifo(&fs)<2) {\n n_read += BlockingRead(2, &fs, fp_lnc, hostname, PORT);\n }\n pop(&fs, (char *)&u_in, 2);\n break;\n case 'S':\n if (nFifo(&fs)<4) {\n n_read += BlockingRead(4, &fs, fp_lnc, hostname, PORT);\n }\n pop(&fs, (char *)&S_in, 4);\n break;\n case 'U':\n if (nFifo(&fs)<4) {\n n_read += BlockingRead(4, &fs, fp_lnc, hostname, PORT);\n }\n pop(&fs, (char *)&U_in, 4);\n break;\n default:\n break;\n }\n // write the word\n if (slowDLList[i_ch].encode == SDL_SCALE) {\n switch (slowDLList[i_ch].type) {\n case 'c':\n x_in = (double)c_in / (double)0xff;\n break;\n case 'u':\n x_in = (double)u_in / (double)0xffff;\n break;\n case 'U':\n x_in = (double)U_in / (double)0xffff;\n break;\n default: // not allowed\n break;\n }\n x_in = slowDLList[i_ch].min + x_in * (slowDLList[i_ch].max - slowDLList[i_ch].min);\n gd_putdata(df_out, fieldlist[i_ch], i_frame, 0, 1, 0, GD_FLOAT64, &x_in);\n } else {\n switch (slowDLList[i_ch].type) {\n case 'c':\n gd_putdata(df_out, fieldlist[i_ch], i_frame, 0, 1, 0, GD_UINT8, &c_in);\n break;\n case 's':\n gd_putdata(df_out, fieldlist[i_ch], i_frame, 0, 1, 0, GD_INT16, &s_in);\n break;\n case 'u':\n gd_putdata(df_out, fieldlist[i_ch], i_frame, 0, 1, 0, GD_UINT16, &u_in);\n break;\n case 'S':\n gd_putdata(df_out, fieldlist[i_ch], i_frame, 0, 1, 0, GD_INT32, &S_in);\n break;\n case 'U':\n gd_putdata(df_out, fieldlist[i_ch], i_frame, 0, 1, 0, GD_UINT32, &U_in);\n break;\n default: // shouldn't happen\n break;\n }\n }\n } // next i_ch;\n t = time(NULL);\n printf(\"%s: frame %4d - %s\", argv[0], i_frame, ctime(&t)); \n i_frame++;\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.6956018805503845, "alphanum_fraction": 0.6979166865348816, "avg_line_length": 22.671232223510742, "blob_id": "92e0310377c2ae3a5a35d45c6eb4bad468424315", "content_id": "5d5365541abeb0a38dcec4c70f19263133feea66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1729, "license_type": "no_license", "max_line_length": 74, "num_lines": 73, "path": "/stars/code/imaging/camera_filesystem.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef IMAGING__CAMERA_FILESYSTEM_H\n#define IMAGING__CAMERA_FILESYSTEM_H\n\n#include \"abstract_camera.h\"\n#include <string>\n#include <vector>\n#include <fitsio.h>\n#include <boost/thread/thread.hpp>\n#include <boost/filesystem/path.hpp>\n#include \"../tools/timing.h\"\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Imaging\n{\n struct Fileset;\n class CameraFilesystem;\n namespace fs = boost::filesystem;\n}\n\nclass Imaging::CameraFilesystem: public Imaging::AbstractCamera\n{\n public:\n CameraFilesystem(Parameters::Manager& params);\n ~CameraFilesystem();\n void add_fileset(fs::path path);\n void try_add_fileset(fs::path path);\n void build_filename_list();\n bool init_camera();\n void clean_up_camera();\n void resave_image(std::string filename);\n void convert_according_to_comment(double& x, std::string comment);\n void read_keys(std::string full_filename);\n bool add_pixels(std::string full_filename, unsigned int exposure_num);\n void read_image_if_available();\n void thread_function();\n void wait_for_quit();\n\n private:\n\n std::string dirname;\n bool load_single_image;\n std::string single_image_filename;\n bool stack_parts;\n std::vector<Fileset>* filesets;\n int fileset_index;\n bool resave_images;\n std::string output_dir;\n\n bool flip_vertically;\n\n unsigned short* temp_pixels;\n\n bool first_run;\n bool repeat;\n double startup_delay;\n Tools::Timer startup_timer;\n double loading_period;\n\n boost::thread thread;\n};\n\n#endif\n" }, { "alpha_fraction": 0.7213406562805176, "alphanum_fraction": 0.7237134575843811, "avg_line_length": 35.247310638427734, "blob_id": "eb3c553c5a8a1c4f87849c027b71df8a64319f6f", "content_id": "0fc65b93b3a4ff20145227894b77edc617798ab5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6744, "license_type": "no_license", "max_line_length": 73, "num_lines": 186, "path": "/stars/code/shared/update.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"update.h\"\n#include \"shared_list.h\"\n\nusing namespace Shared;\n\nvoid Shared::update(ThreadNames::Name thread_name)\n{\n\n Autofocus::datapoints_solver_to_lens.retry_share(thread_name);\n Autofocus::datapoints_solver_to_lens.update_and_pass_to(\n\n Autofocus::datapoints_lens_to_main, thread_name);\n Autofocus::datapoints_lens_to_main.update(thread_name);\n\n Autofocus::latest_image.retry_share(thread_name);\n Autofocus::latest_image.update(thread_name);\n\n Autofocus::requests_network_to_main.retry_share(thread_name);\n Autofocus::requests_network_to_main.update_and_pass_to(\n\n Autofocus::requests_main_to_lens, thread_name);\n Autofocus::requests_main_to_lens.update(thread_name);\n\n Autofocus::results_lens_to_solver.retry_share(thread_name);\n Autofocus::results_lens_to_solver.update_and_pass_to(\n\n Autofocus::results_solver_to_main, thread_name);\n Autofocus::results_solver_to_main.update_and_pass_to(\n\n Autofocus::results_main_to_network, thread_name);\n Autofocus::results_main_to_network.update(thread_name);\n\n Camera::requests_for_main.retry_share(thread_name);\n Camera::requests_for_main.update_and_pass_to(\n\n Camera::requests_for_camera, thread_name);\n Camera::requests_for_camera.update(thread_name);\n\n Camera::results_for_main.retry_share(thread_name);\n Camera::results_for_main.update_and_pass_to(\n\n Camera::results_for_network, thread_name);\n Camera::results_for_network.update(thread_name);\n\n General::main_settings_net_for_main.retry_share(thread_name);\n General::main_settings_net_for_main.update_and_pass_to(\n\n General::main_settings_main_for_solver, thread_name);\n General::main_settings_main_for_solver.update(thread_name);\n\n General::shutdown_for_main.retry_share(thread_name);\n General::shutdown_for_main.update(thread_name);\n\n General::network_reset_for_net_reset.retry_share(thread_name);\n General::network_reset_for_net_reset.update(thread_name);\n\n General::network_reset_status_for_main.retry_share(thread_name);\n General::network_reset_status_for_main.update(thread_name);\n\n Housekeeping::housekeeper_for_camera.retry_share(thread_name);\n Housekeeping::housekeeper_for_camera.update_and_pass_to(\n\n Housekeeping::housekeeper_for_network, thread_name);\n Housekeeping::housekeeper_for_network.update(thread_name);\n\n Image::blobs_solver_for_main.retry_share(thread_name);\n Image::blobs_solver_for_main.update_and_pass_to(\n\n Image::blobs_main_for_net, thread_name);\n Image::blobs_main_for_net.update(thread_name);\n\n Image::leveled.retry_share(thread_name);\n Image::leveled.update(thread_name);\n\n Image::matching.retry_share(thread_name);\n Image::matching.update(thread_name);\n\n Image::matching_progress.retry_share(thread_name);\n Image::matching_progress.update(thread_name);\n\n Image::raw_from_camera.retry_share(thread_name);\n Image::raw_from_camera.update(thread_name);\n\n Image::raw_for_image_client1.retry_share(thread_name);\n Image::raw_for_image_client1.update(thread_name);\n\n Image::raw_for_image_client2.retry_share(thread_name);\n Image::raw_for_image_client2.update(thread_name);\n\n Image::solution_summary_for_main.retry_share(thread_name);\n Image::solution_summary_for_main.update_and_pass_to(\n\n Image::solution_summary_main_for_net, thread_name);\n Image::solution_summary_main_for_net.update(thread_name);\n\n Image::stats_solver_for_main.retry_share(thread_name);\n Image::stats_solver_for_main.update_and_pass_to(\n\n Image::stats_main_for_net, thread_name);\n Image::stats_main_for_net.update(thread_name);\n\n Image::status_solver_for_main.retry_share(thread_name);\n Image::status_solver_for_main.update_and_pass_to(\n\n Image::status_main_for_camera, thread_name);\n Image::status_main_for_camera.update_and_pass_to(\n\n Image::status_camera_for_network, thread_name);\n Image::status_camera_for_network.update(thread_name);\n\n Lens::fcp_requests_network_to_main.retry_share(thread_name);\n Lens::fcp_requests_network_to_main.update_and_pass_to(\n\n Lens::fcp_requests_main_to_camera, thread_name);\n Lens::fcp_requests_main_to_camera.update_and_pass_to(\n\n Lens::fcp_requests_camera_to_lens, thread_name);\n Lens::fcp_requests_camera_to_lens.update(thread_name);\n\n Lens::stars_requests_lens_to_main.retry_share(thread_name);\n Lens::stars_requests_lens_to_main.update_and_pass_to(\n\n Lens::stars_requests_main_to_camera, thread_name);\n Lens::stars_requests_main_to_camera.update_and_pass_to(\n\n Lens::stars_requests_camera_to_lens, thread_name);\n Lens::stars_requests_camera_to_lens.update(thread_name);\n\n Lens::fcp_results_lens_to_camera.retry_share(thread_name);\n Lens::fcp_results_lens_to_camera.update_and_pass_to(\n\n Lens::fcp_results_camera_to_main, thread_name);\n Lens::fcp_results_camera_to_main.update_and_pass_to(\n\n Lens::fcp_results_main_to_network, thread_name);\n Lens::fcp_results_main_to_network.update(thread_name);\n\n Lens::stars_results_lens_to_camera.retry_share(thread_name);\n Lens::stars_results_lens_to_camera.update_and_pass_to(\n\n Lens::stars_results_camera_to_main, thread_name);\n Lens::stars_results_camera_to_main.update(thread_name);\n\n Network::client_for_main.retry_share(thread_name);\n Network::client_for_main.update_and_pass_to(\n\n Network::client_for_camera, thread_name);\n Network::client_for_camera.update(thread_name);\n\n Network::packets_from_fc1.retry_share(thread_name);\n Network::packets_from_fc1.update(thread_name);\n\n Network::packets_from_fc2.retry_share(thread_name);\n Network::packets_from_fc2.update(thread_name);\n\n Network::image_client_settings1.retry_share(thread_name);\n Network::image_client_settings1.update(thread_name);\n\n Network::image_client_settings2.retry_share(thread_name);\n Network::image_client_settings2.update(thread_name);\n\n Simulations::brightness.retry_share(thread_name);\n Simulations::brightness.update(thread_name);\n\n Solving::filters_net_to_main.retry_share(thread_name);\n Solving::filters_net_to_main.update_and_pass_to(\n\n Solving::filters_main_to_camera, thread_name);\n Solving::filters_main_to_camera.update(thread_name);\n\n Solving::mask_network_for_solver.retry_share(thread_name);\n Solving::mask_network_for_solver.update_and_pass_to(\n\n Solving::mask_solver_for_main, thread_name);\n Solving::mask_solver_for_main.update(thread_name);\n\n Solving::settings.retry_share(thread_name);\n Solving::settings.update(thread_name);\n\n}\n\n" }, { "alpha_fraction": 0.6149603128433228, "alphanum_fraction": 0.6217857003211975, "avg_line_length": 43.599998474121094, "blob_id": "bd13d0f8e54a887640595cc8ad10eeb48bb177c5", "content_id": "3ef49019a57c40c57c91009da797c1009fdc50af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 25201, "license_type": "no_license", "max_line_length": 141, "num_lines": 565, "path": "/stars/code/imaging/lens.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"lens.h\"\n#include <boost/format.hpp>\n#include <boost/algorithm/string.hpp>\n#include <sstream>\n#include <vector>\n#include <math.h>\n#include \"../parameters/manager.h\"\n#include \"../shared/update.h\"\n#include \"../shared/lens/requests.h\"\n#include \"../shared/lens/results.h\"\n#include \"../shared/general/quit.h\"\n#include \"logger_lens.h\"\n\nusing namespace Imaging;\nusing Lensing::logger;\n\n#define shared_fcp_requests (*(Shared::Lens::fcp_requests_camera_to_lens.r))\n#define shared_fcp_results (*(Shared::Lens::fcp_results_lens_to_camera.w))\n#define shared_stars_write_requests (*(Shared::Lens::stars_requests_lens_to_main.w))\n#define shared_stars_requests (*(Shared::Lens::stars_requests_camera_to_lens.r))\n#define shared_stars_results (*(Shared::Lens::stars_results_lens_to_camera.w))\n\n#define STR_HELPER(x) #x\n#define STR(x) STR_HELPER(x)\n#define FOCUS_MAX_WAIT_FOR_MOVE 70000 // maximum wait time [ms] for focus over entire range\n#define FOCUS_MAX_RANGE_FOR_MOVE 3500 // maximum range of focus\n#define APERTURE_MAX_WAIT_FOR_MOVE 12000 // maximum wait time [ms] for aperture over entire range\n#define APERTURE_MAX_RANGE_FOR_MOVE 650 // maximum range of aperture\n\nstring string_to_hex(string instring)\n{\n string outstring = \"\";\n for (unsigned int i=0; i<instring.size(); i++) {\n if (i > 0) {\n outstring += \" \";\n }\n outstring += (format(\"%|02X|\")%((int) (unsigned char) instring[i])).str();\n }\n return outstring;\n}\n\nLens::Lens(Parameters::Manager& params): port(io), read_timeout(io),\n enabled(params.general.try_get(\"imaging.lens.enabled\", true)),\n init_on_startup(params.general.try_get(\"imaging.lens.init_on_startup\", false)),\n #pragma warning(push)\n #pragma warning(disable: 4355)\n thread(boost::bind(&Lens::run, this))\n #pragma warning(pop)\n{\n\twhich_sensor.assign(params.general.try_get(\"main.which_sensor\", std::string(\"(sensor name)\")));\n}\n\nLens::~Lens()\n{\n}\n\nvoid Lens::init()\n{\n find_device_period = 60.0;\n baud_rate = 9600;\n for (unsigned int i=0; i<num_commands; i++) {\n command_fcp_counters[i] = 0;\n command_stars_counters[i] = 0;\n }\n for (unsigned int i=2; i<=12; i++) {\n device_names.push_back((format(\"COM%d\")%i).str());\n }\n device_names.push_back(\"/dev/ttyS0\");\n device_names.push_back(\"/dev/ttyS1\");\n device_names.push_back(\"/dev/ttyS2\");\n device_names.push_back(\"/dev/ttyACM\");\n device_names.push_back(\"/dev/ttyACM0\");\n device_names.push_back(\"/dev/ttyACM1\");\n device_names.push_back(\"/dev/ttyACM2\");\n device_names.push_back(\"/dev/ttyUSB\");\n device_names.push_back(\"/dev/ttyUSB0\");\n device_names.push_back(\"/dev/ttyUSB1\");\n device_names.push_back(\"/dev/ttyUSB2\");\n}\n\nvoid Lens::parse_birger_result(string full_line, commands_t command)\n{\n using std::vector;\n using std::stringstream;\n\n int int0 = 0;\n string line;\n string found_value;\n uint8_t status_byte = (full_line.size() > 3) ? ((uint8_t) full_line[3]) & 0xf : 0;\n if (full_line.size() > 4) {\n line = full_line.substr(4, string::npos);\n } else {\n line = full_line;\n }\n string message;\n\n logger.log(format(\"recieved birger message for command callback %i\")%command);\n logger.log( \" message (str) \" + line);\n logger.log( \" message (hex) \" + string_to_hex(line));\n logger.log( \"I am done printing the hex \");\n\n switch (status_byte) {\n case 0: // no error\n break;\n case 1: // init error\n logger.log(\"[EZ Stepper] Initialization error\");\n break;\n case 2: // bad command\n logger.log(\"[EZ Stepper] Bad command\");\n break;\n case 3: // bad operand\n logger.log(\"[EZ Stepper] Bad operand\");\n break;\n case 5: // communications error\n logger.log(\"[EZ Stepper] Communications error\");\n break;\n case 7: // not initialized\n logger.log(\"[EZ Stepper] Not initialized\");\n break;\n case 9: // overload error\n logger.log(\"[EZ Stepper] Overload error\");\n break;\n case 11: // move not allowed\n logger.log(\"[EZ Stepper] Move not allowed\");\n break;\n case 15: // command overflow\n logger.log(\"[EZ Stepper] Command overflow\");\n break;\n default: // unknown error\n logger.log(format(\"[EZ Stepper] Unknown error code %d\") % status_byte);\n \n }\n\n switch (command) {\n case flush_birger:\n break;\n case get_focus:\n shared_fcp_results.command_counters[init_focus] = shared_fcp_requests.commands[init_focus].counter;\n shared_fcp_results.command_counters[get_focus] = shared_fcp_requests.commands[get_focus].counter;\n shared_fcp_results.command_counters[stop_focus] = shared_fcp_requests.commands[stop_focus].counter;\n shared_fcp_results.command_counters[define_focus] = shared_fcp_requests.commands[define_focus].counter;\n shared_fcp_results.command_counters[set_focus] = shared_fcp_requests.commands[set_focus].counter;\n shared_fcp_results.command_counters[set_focus_incremental] = shared_fcp_requests.commands[set_focus_incremental].counter;\n shared_stars_results.command_counters[init_focus] = shared_stars_requests.commands[init_focus].counter;\n shared_stars_results.command_counters[get_focus] = shared_stars_requests.commands[get_focus].counter;\n shared_stars_results.command_counters[stop_focus] = shared_stars_requests.commands[stop_focus].counter;\n shared_stars_results.command_counters[define_focus] = shared_stars_requests.commands[define_focus].counter;\n shared_stars_results.command_counters[set_focus] = shared_stars_requests.commands[set_focus].counter;\n shared_stars_results.command_counters[set_focus_incremental] = shared_stars_requests.commands[set_focus_incremental].counter;\n {\n\n found_value = line.substr(0, line.length()-2);\n if (found_value.length() > 0) {\n int0 = atoi(found_value.c_str());\n shared_fcp_results.focus_value = int0;\n shared_fcp_results.focus_found = true;\n shared_stars_results.focus_value = int0;\n shared_stars_results.focus_found = true;\n logger.log(format(\"focus found: %i\")%(int0));\n shared_stars_write_requests.commands[save_focus].value = shared_stars_results.focus_value;\n }\n }\n Shared::Lens::fcp_results_lens_to_camera.share();\n Shared::Lens::stars_results_lens_to_camera.share();\n break;\n case init_focus:\n break;\n case set_focus:\n shared_fcp_results.command_counters[init_focus] = shared_fcp_requests.commands[init_focus].counter;\n shared_fcp_results.command_counters[get_focus] = shared_fcp_requests.commands[get_focus].counter;\n shared_fcp_results.command_counters[stop_focus] = shared_fcp_requests.commands[stop_focus].counter;\n shared_fcp_results.command_counters[define_focus] = shared_fcp_requests.commands[define_focus].counter;\n shared_fcp_results.command_counters[set_focus] = shared_fcp_requests.commands[set_focus].counter;\n shared_fcp_results.command_counters[set_focus_incremental] = shared_fcp_requests.commands[set_focus_incremental].counter;\n shared_stars_results.command_counters[init_focus] = shared_stars_requests.commands[init_focus].counter;\n shared_stars_results.command_counters[get_focus] = shared_stars_requests.commands[get_focus].counter;\n shared_stars_results.command_counters[stop_focus] = shared_stars_requests.commands[stop_focus].counter;\n shared_stars_results.command_counters[define_focus] = shared_stars_requests.commands[define_focus].counter;\n shared_stars_results.command_counters[set_focus] = shared_stars_requests.commands[set_focus].counter;\n shared_stars_results.command_counters[set_focus_incremental] = shared_stars_requests.commands[set_focus_incremental].counter;\n Shared::Lens::fcp_results_lens_to_camera.share();\n Shared::Lens::stars_results_lens_to_camera.share();\n break;\n case save_focus:\n\t\t case save_aperture:\n\t\t\tshared_fcp_results.command_counters[command] = shared_fcp_requests.commands[command].counter;\n\t\t\tshared_stars_results.command_counters[command] = shared_stars_requests.commands[command].counter;\n\t\t\tShared::Lens::fcp_results_lens_to_camera.share();\n\t\t\tShared::Lens::stars_results_lens_to_camera.share();\n case set_focus_incremental:\n break;\n case get_aperture:\n shared_fcp_results.command_counters[init_aperture] = shared_fcp_requests.commands[init_aperture].counter;\n shared_fcp_results.command_counters[get_aperture] = shared_fcp_requests.commands[get_aperture].counter;\n shared_fcp_results.command_counters[stop_aperture] = shared_fcp_requests.commands[stop_aperture].counter;\n shared_fcp_results.command_counters[set_aperture] = shared_fcp_requests.commands[set_aperture].counter;\n shared_fcp_results.command_counters[define_aperture] = shared_fcp_requests.commands[define_aperture].counter;\n shared_stars_results.command_counters[init_aperture] = shared_stars_requests.commands[init_aperture].counter;\n shared_stars_results.command_counters[get_aperture] = shared_stars_requests.commands[get_aperture].counter;\n shared_stars_results.command_counters[stop_aperture] = shared_stars_requests.commands[stop_aperture].counter;\n shared_stars_results.command_counters[set_aperture] = shared_stars_requests.commands[set_aperture].counter;\n shared_stars_results.command_counters[define_aperture] = shared_stars_requests.commands[define_aperture].counter;\n {\n string found_value = line.substr(0, line.length() - 2);\n if (found_value.length() > 0) {\n int0 = atoi(found_value.c_str());\n logger.log(format(\"aperture found: %i\") % (int0));\n shared_fcp_results.aperture_value = int0;\n shared_fcp_results.aperture_found = true;\n shared_stars_results.aperture_value = int0;\n shared_stars_results.aperture_found = true;\n shared_stars_write_requests.commands[save_aperture].value = shared_stars_results.aperture_value;\n }\n }\n Shared::Lens::fcp_results_lens_to_camera.share();\n Shared::Lens::stars_results_lens_to_camera.share();\n break;\n case init_aperture:\n break;\n case set_aperture:\n shared_fcp_results.command_counters[init_aperture] = shared_fcp_requests.commands[init_aperture].counter;\n shared_fcp_results.command_counters[get_aperture] = shared_fcp_requests.commands[get_aperture].counter;\n shared_fcp_results.command_counters[stop_aperture] = shared_fcp_requests.commands[stop_aperture].counter;\n shared_fcp_results.command_counters[set_aperture] = shared_fcp_requests.commands[set_aperture].counter;\n shared_fcp_results.command_counters[define_aperture] = shared_fcp_requests.commands[define_aperture].counter;\n shared_stars_results.command_counters[init_aperture] = shared_stars_requests.commands[init_aperture].counter;\n shared_stars_results.command_counters[get_aperture] = shared_stars_requests.commands[get_aperture].counter;\n shared_stars_results.command_counters[stop_aperture] = shared_stars_requests.commands[stop_aperture].counter;\n shared_stars_results.command_counters[set_aperture] = shared_stars_requests.commands[set_aperture].counter;\n shared_stars_results.command_counters[define_aperture] = shared_stars_requests.commands[define_aperture].counter;\n Shared::Lens::fcp_results_lens_to_camera.share();\n Shared::Lens::stars_results_lens_to_camera.share();\n break;\n case version_string:\n {\n vector<string> words;\n boost::split(words, line, boost::is_any_of(\" \"));\n if (words.size() == 6) {\n if (words[0].compare(\"EZStepper\") == 0) {\n logger.log(\"device found\");\n shared_fcp_results.device_found = true;\n shared_stars_results.device_found = true;\n }\n }\n }\n break;\n case load_aperture:\n break;\n case load_focus:\n break;\n case clearing_read_buffer:\n if (line.size() > 0) {\n logger.log(format(\"clearing read buffer returned %d characters\")%line.size());\n }\n break;\n case define_focus:\n break;\n case define_aperture:\n break;\n case stop_focus:\n break;\n case stop_aperture:\n break;\n case set_aperture_velocity:\n break;\n case set_focus_velocity:\n break;\n case set_aperture_current:\n break;\n default:\n break;\n }\n}\n\nint Lens::get_wait_ms(commands_t command, int command_value)\n{\n\tdouble wait_ms = 2000;\n\n\tif ((command == init_aperture)) {\n\t\twait_ms = APERTURE_MAX_WAIT_FOR_MOVE * 2;\n\t}\n\telse if ((command == init_focus)) {\n\t\twait_ms = FOCUS_MAX_WAIT_FOR_MOVE * 2;\n\t}\n\telse if ((command == set_aperture)) {\n\t\twait_ms = (shared_stars_results.aperture_value - command_value) *\n\t\t\tAPERTURE_MAX_WAIT_FOR_MOVE / APERTURE_MAX_RANGE_FOR_MOVE;\n\t}\n\telse if ((command == set_focus)) {\n\t\twait_ms = (shared_stars_results.focus_value - command_value) *\n\t\t\tFOCUS_MAX_WAIT_FOR_MOVE / FOCUS_MAX_RANGE_FOR_MOVE;\n\t}\n\telse if ((command == set_focus_incremental)) {\n\t\twait_ms = command_value * FOCUS_MAX_WAIT_FOR_MOVE / FOCUS_MAX_RANGE_FOR_MOVE;\n\t}\n\twait_ms = (int)((wait_ms > 0) ? wait_ms : -wait_ms);\n\tlogger.log(format(\"choosing wait_ms = %d ms for command %d\") % wait_ms % command);\n\treturn wait_ms;\n}\n\nvoid Lens::process_request(commands_t command, string message,\n bool initiate_get_focus, bool initiate_get_aperture)\n{\n int command_value = 0;\n\n if (command_fcp_counters[command] != shared_fcp_requests.commands[command].counter ||\n command_stars_counters[command] != shared_stars_requests.commands[command].counter)\n {\n logger.log(format(\"initiating lens request (%i) because counters don't match:\") % command);\n logger.log(format(\" (fcp counters) %i %i\") % command_fcp_counters[command] % shared_fcp_requests.commands[command].counter);\n logger.log(format(\" (stars counters) %i %i\") % command_stars_counters[command] % shared_stars_requests.commands[command].counter);\n\n\t\tif (command_fcp_counters[command] != shared_fcp_requests.commands[command].counter) {\n\t\t\tcommand_value = shared_fcp_requests.commands[command].value;\n\t\t}\n\t\telse if (command_stars_counters[command] != shared_stars_requests.commands[command].counter) {\n\t\t\tcommand_value = shared_stars_requests.commands[command].value;\n\t\t}\n\t\telse {\n\t\t\tlogger.log(\"Counters are inconsistent so command_value set to 0\");\n\t\t\tcommand_value = 0;\n\t\t}\n\n command_fcp_counters[command] = shared_fcp_requests.commands[command].counter;\n command_stars_counters[command] = shared_stars_requests.commands[command].counter;\n if (initiate_get_focus) {\n shared_stars_write_requests.commands[get_focus].counter++;\n Shared::Lens::stars_requests_lens_to_main.share();\n }\n if (initiate_get_aperture) {\n shared_stars_write_requests.commands[get_aperture].counter++;\n Shared::Lens::stars_requests_lens_to_main.share();\n }\n\n send_message(message, command, get_wait_ms(command, command_value));\n\n\t\tif (command == get_focus) {\n\t\t\tshared_stars_write_requests.commands[save_focus].counter++;\n\t\t\tShared::Lens::stars_requests_lens_to_main.share();\n\t\t}\n\t\tif (command == get_aperture) {\n\t\t\tshared_stars_write_requests.commands[save_aperture].counter++;\n\t\t\tShared::Lens::stars_requests_lens_to_main.share();\n\t\t}\n logger.log(\"send_message returned\");\n }\n}\n\nvoid Lens::process_request(commands_t command, string message,\n bool initiate_get_focus, bool initiate_get_aperture, bool use_value)\n{\n if (use_value) {\n if (command_fcp_counters[command] != shared_fcp_requests.commands[command].counter) {\n int value = shared_fcp_requests.commands[command].value;\n if (command == set_focus_incremental) { \n if (value < 0) {\n value = -value;\n message[2] = 'D';\n }\n }\n process_request(command, (format(message)%value).str(), initiate_get_focus, initiate_get_aperture);\n }\n else if (command_stars_counters[command] != shared_stars_requests.commands[command].counter) {\n int value = shared_stars_requests.commands[command].value;\n if (command == set_focus_incremental) { \n if (value < 0) {\n value = -value;\n message[2] = 'D';\n }\n }\n process_request(command, (format(message)%value).str(), initiate_get_focus, initiate_get_aperture);\n }\n }\n}\n\nvoid Lens::process_requests()\n{\n process_request(flush_birger, \"\\r\", false, false);\n process_request(init_focus, \"/2z\" STR(FOCUS_MAX_RANGE_FOR_MOVE) // define max position \n \"D\" STR(FOCUS_MAX_RANGE_FOR_MOVE) // decrement to zero\n \"M\" STR(FOCUS_MAX_WAIT_FOR_MOVE) // wait to move\n \"z0R\\r\", true, false); // define zero position\n process_request(get_focus, \"/2?8\\r\", false, false);\n process_request(set_focus, \"/2A%dR\\r\", true, false, true);\n process_request(stop_focus, \"/2TR\\r\", true, false);\n process_request(set_focus_incremental, \"/2P%dR\\r\", true, false, true);\n process_request(init_aperture, \"/1z\" STR(APERTURE_MAX_RANGE_FOR_MOVE) // define max position\n \"D\" STR(APERTURE_MAX_RANGE_FOR_MOVE) // decrement to zero\n \"M\" STR(APERTURE_MAX_WAIT_FOR_MOVE) // wait to move\n \"z0R\\r\", false, true); // define zero position\n process_request(get_aperture, \"/1?8\\r\", false, false);\n process_request(set_aperture, \"/1A%dR\\r\", false, true, true);\n process_request(stop_aperture, \"/1TR\\r\", false, true);\n process_request(save_aperture, \"/1s1z%dR\\r\", false, false, true);\n process_request(save_focus, \"/2s1z%dR\\r\", false, false, true);\n process_request(define_focus, \"/2z%dR\\r\", true, false, true);\n process_request(define_aperture, \"/1z%dR\\r\", false, true, true);\n}\n\nvoid Lens::send_message(string message, commands_t command, int wait_ms)\n{\n try {\n if (port.is_open()) {\n clear_read_buffer();\n logger.log(\"sending motor command (str) \" + message.substr(0, message.size()-1));\n io.reset();\n boost::asio::write(port, boost::asio::buffer(message.c_str(), message.size()));\n read_timeout.expires_from_now(boost::posix_time::milliseconds(8000));\n boost::asio::async_read_until(port, instream, '\\r',\n boost::bind(&Lens::handle_read, this, command, boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n read_timeout.async_wait(boost::bind(&Lens::handle_read_timeout, this, boost::asio::placeholders::error));\n io.run();\n usleep(wait_ms*1000);\n } else {\n logger.log(\"port closed, wanted to send \" + message.substr(0, message.size()-1));\n }\n } catch (boost::system::system_error&) {}\n}\n\nvoid Lens::handle_read_timeout(const boost::system::error_code& error)\n{\n if (!error) {\n port.cancel();\n }\n}\n\nvoid Lens::handle_read(commands_t command, const boost::system::error_code& error, size_t size)\n{\n if (!error && size) {\n std::istream is(&instream);\n string line = \"\";\n bool end_of_file = false;\n while (!end_of_file) {\n end_of_file = getline(is, line).eof();\n parse_birger_result(line, command);\n }\n read_timeout.cancel();\n }\n}\n\nvoid Lens::clear_read_buffer()\n{\n // This calls asynchronous send with a 0.1 s timeout\n // calling function sleeps for 0.5 s\n io.reset();\n read_timeout.expires_from_now(boost::posix_time::milliseconds(100));\n boost::asio::async_read(port, instream,\n boost::bind(&Lens::handle_read, this, clearing_read_buffer, boost::asio::placeholders::error,\n boost::asio::placeholders::bytes_transferred));\n read_timeout.async_wait(boost::bind(&Lens::handle_read_timeout, this, boost::asio::placeholders::error));\n io.run();\n usleep(500);\n}\n\nvoid Lens::check_device(string device_name)\n{\n try {\n port.open(device_name);\n port.set_option(boost::asio::serial_port_base::baud_rate(baud_rate));\n\t\tport.set_option(boost::asio::serial_port_base::flow_control(boost::asio::serial_port::flow_control::none));\n\t\tport.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port::parity::none));\n\t\tport.set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port::stop_bits::one));\n\t\tport.set_option(boost::asio::serial_port_base::character_size(8));\n\n logger.log(format(\"trying device %s\")%device_name.c_str());\n if (port.is_open()) {\n string message = \"/1&\\r\";\n logger.log(format(\"attempting message /1& to %s\") %(device_name.c_str()));\n send_message(message, version_string);\n }\n port.close();\n if (shared_fcp_results.device_found) {\n shared_fcp_results.device_found = true;\n shared_stars_results.device_found = true;\n shared_fcp_results.device_name = device_name;\n shared_stars_results.device_name = device_name;\n Shared::Lens::fcp_results_lens_to_camera.share();\n Shared::Lens::stars_results_lens_to_camera.share();\n }\n } catch (boost::system::system_error&) {}\n find_device_timer.start();\n}\n\nvoid Lens::find_device()\n{\n shared_fcp_results.device_found = false;\n Shared::Lens::fcp_results_lens_to_camera.share();\n for (unsigned int i=0; !shared_fcp_results.device_found && i<device_names.size(); i++) {\n check_device(device_names[i]);\n }\n}\n\nvoid Lens::connect()\n{\n string message;\n port.open(shared_fcp_results.device_name);\n port.set_option(boost::asio::serial_port_base::baud_rate(baud_rate));\n\tport.set_option(boost::asio::serial_port_base::flow_control(boost::asio::serial_port::flow_control::none));\n\tport.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port::parity::none));\n\tport.set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port::stop_bits::one));\n\tport.set_option(boost::asio::serial_port_base::character_size(8));\n if (init_on_startup) {\n shared_stars_write_requests.commands[init_focus].counter++;\n shared_stars_write_requests.commands[init_aperture].counter++;\n } else {\n message = \"/1V50R\\r\";\n send_message(message, set_aperture_velocity);\n message = \"/2V50R\\r\";\n send_message(message, set_focus_velocity);\n message = \"/1e1R\\r\";\n send_message(message, load_aperture);\n message = \"/2e1R\\r\";\n send_message(message, load_focus);\n if (which_sensor.compare(\"xsc1\") == 0) {\n logger.log(\"Setting higher current for xsc1 aperture\");\n message = \"/1m70R\\r\";\n send_message(message, set_aperture_current);\n }\n shared_stars_write_requests.commands[get_focus].counter++;\n shared_stars_write_requests.commands[get_aperture].counter++;\n }\n Shared::Lens::stars_requests_lens_to_main.share();\n}\n\nvoid Lens::update()\n{\n Shared::update(Shared::ThreadNames::lens);\n logger.update();\n}\n\nvoid Lens::run()\n{\n init();\n while (!Shared::General::quit) {\n update();\n autofocuser.update();\n if (enabled) {\n //if (true) {\n if (!shared_fcp_results.device_found && (find_device_timer.time() > find_device_period)) {\n find_device();\n find_device_timer.start();\n if (shared_fcp_results.device_found) {\n connect();\n }\n }\n process_requests();\n }\n usleep(200000);\n }\n try {\n port.close();\n } catch (boost::system::system_error&) {}\n}\n\nvoid Lens::wait_for_quit()\n{\n thread.join();\n}\n\n" }, { "alpha_fraction": 0.6223929524421692, "alphanum_fraction": 0.636663019657135, "avg_line_length": 26.57575798034668, "blob_id": "d27044f2389abb6ef67598e766cb848f4118b22e", "content_id": "5c9d26ce4e76dde20e2220a99504cd7d9cce01a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 911, "license_type": "no_license", "max_line_length": 103, "num_lines": 33, "path": "/stars/utilities/ebex_images/convert_raw_to_fits.py", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\nimport os\nimport pylab\nimport pyfits\n\nimage_width = 1536\nimage_height = 1024\n\ndef convert(infilename):\n infile = open(infilename, \"r\")\n contents = infile.read()\n infile.close()\n flat_data = pylab.fromstring(contents, \"uint16\")\n if len(flat_data) != image_width*image_height:\n print \"data has length\", len(flat_data), \"which does not match\", image_width, \"*\", image_height\n exit()\n\n data = []\n for j in range(image_height):\n data.append(flat_data[j*image_width: (j+1)*image_width])\n data = pylab.array(data)\n\n header = pyfits.core.Header()\n header.update(\"SIMPLE\", \"T\")\n header.update(\"BITPIX\", 16)\n header.update(\"EXTEND\", \"T\")\n pyfits.writeto(infilename.replace(\".raw\", \".fits\"), data, header)\n\nfor filename in os.listdir(\".\"):\n if filename.endswith(\".raw\"):\n print \"converting\", filename\n convert(filename)\n\n" }, { "alpha_fraction": 0.6811926364898682, "alphanum_fraction": 0.6926605701446533, "avg_line_length": 17.16666603088379, "blob_id": "47ecf902558b0dbc2b477a1eb5101b70b704f528", "content_id": "d197a6da57d93480bc05edaac8612d75ee9b6c67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 437, "license_type": "no_license", "max_line_length": 73, "num_lines": 24, "path": "/stars/code/solving/base_set.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__BASE_SET_H\n#define SOLVING__BASE_SET_H\n\nnamespace Solving\n{\n class BaseSet;\n}\n\nclass Solving::BaseSet\n{\n public:\n unsigned int ids[3];\n enum base_type {pair, triplet};\n base_type type;\n};\n\n#endif\n" }, { "alpha_fraction": 0.5885553956031799, "alphanum_fraction": 0.596883237361908, "avg_line_length": 33.645713806152344, "blob_id": "ac0d88cb4c649c47465c4c841b73b6b2c7ac0fa5", "content_id": "35f0e7a95ca83233332446de268322f6ab5f1302", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12129, "license_type": "no_license", "max_line_length": 111, "num_lines": 350, "path": "/stars/code/solving/matching/matcher.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"matcher.h\"\n#include \"../update.h\"\n#include \"../../tools/angles.h\"\n#include \"../../tools/ccd_projection.h\"\n#include \"../../shared/general/quit.h\"\n#include \"../../shared/image/blobs.h\"\n#include \"../../shared/image/matching.h\"\n#include \"../../shared/image/matching_progress.h\"\n#include \"../../shared/image/raw.h\"\n#include \"../../shared/image/solution_summary.h\"\n#include \"../../shared/image/status.h\"\n#include \"../../shared/solving/settings.h\"\n#include \"../../parameters/manager.h\"\n#include \"../logger.h\"\n\nusing namespace Solving;\nusing namespace Solving::Matching;\nusing std::vector;\nusing std::numeric_limits;\n\n#define shared_blobs (*(Shared::Image::blobs_solver_for_main.w))\n#define shared_matching (*(Shared::Image::matching.w))\n#define shared_progress (*(Shared::Image::matching_progress.w))\n#define shared_solution_for_main (*(Shared::Image::solution_summary_for_main.w))\n#define shared_status (*(Shared::Image::status_solver_for_main.w))\n#define shared_settings (*(Shared::Solving::settings.r))\n\nMatcher::Matcher(Parameters::Manager& params):\n catalog_manager(params, shared_settings.enabled, shared_settings.catalog)\n{\n image_width = params.general.image_width;\n image_height = params.general.image_height;\n result_update_success_counter = 0;\n result_update_failure_counter = 0;\n base_set_counter = 0;\n}\n\nvoid Matcher::init()\n{\n catalog_manager.init();\n}\n\nbool is_inbounds_centered(double& u, double& v, double& width, double& height)\n{\n // this should be put in tools, as should angdist func\n if ((u > width/2.0) || (u < -width/2.0)) {\n return false;\n }\n if ((v > height/2.0) || (v < -height/2.0)) {\n return false;\n }\n return true;\n}\n\nvoid rotate(double& x, double& y, double& cos_theta, double& sin_theta)\n{\n double temp_x, temp_y;\n temp_x = x*cos_theta - y*sin_theta;\n temp_y = x*sin_theta + y*cos_theta;\n x = temp_x;\n y = temp_y;\n}\n\nbool good_for_debug(Solution& solution)\n{\n return true;\n\n vector<int> ids;\n ids.push_back(132);\n ids.push_back(364);\n\n unsigned int num_matching_ids = 0;\n for (unsigned int i=0; i<3; i++) {\n for (unsigned int j=0; j<ids.size(); j++) {\n if (solution.base_stars[i].id == ids[j]) {\n num_matching_ids++;\n }\n }\n }\n if (num_matching_ids == ids.size()) {\n return true;\n }\n else {\n return false;\n }\n\n}\n\nvector<Star> Matcher::match_stars_to_blob(Solution& solution, Blob& blob, vector<Star>& stars,\n Shared::Image::Raw& image)\n{\n vector<Star> matched_stars;\n double u = 0.0;\n double v = 0.0;\n double star_ra = 0.0;\n double star_dec = 0.0;\n double cos_roll = cos(solution.equatorial.roll);\n double sin_roll = sin(solution.equatorial.roll);\n double distance = 0.0;\n double width = image_width;\n double height = image_height;\n\tdouble hyp = sqrt(width*width + height*height) * solution.equatorial.iplatescale;\n double tolerance_squared = pow(shared_settings.match_tolerance_px, 2.0);\n double distance_squared = numeric_limits<double>::infinity();\n double best_distance_squared = numeric_limits<double>::infinity();\n unsigned int best_i = -1;\n for (unsigned int i=0; i<stars.size(); i++) {\n distance = great_circle(solution.equatorial.ra, solution.equatorial.dec, stars[i].ra, stars[i].dec);\n\t\t\n if (distance < hyp) {\n Tools::get_refraction_corrected_equatorial(stars[i].ra, stars[i].dec,\n shared_settings.refraction, image.filters, star_ra, star_dec);\n Tools::ccd_projection(star_ra, star_dec, solution.equatorial.ra, solution.equatorial.dec,\n 1.0/solution.equatorial.iplatescale, cos_roll, sin_roll, u, v, true);\n if (is_inbounds_centered(u, v, width, height)) {\n distance_squared = pow(blob.x-u, 2) + pow(blob.y-v, 2);\n if (distance_squared < best_distance_squared) {\n best_distance_squared = distance_squared;\n best_i = i;\n }\n }\n }\n }\n if (best_distance_squared < tolerance_squared) {\n matched_stars.push_back(stars[best_i]);\n }\n return matched_stars;\n}\n\nvoid Matcher::match_blobs_to_stars(vector<Blob>& blobs, Solution& solution, vector<Star>& stars,\n Shared::Image::Raw& image)\n{\n vector<Star> temp_matched_stars;\n for (unsigned int i=0; i<blobs.size(); i++) {\n temp_matched_stars = match_stars_to_blob(solution, blobs[i], stars, image);\n if (temp_matched_stars.size() > 0) {\n solution.matched_blobs.push_back(blobs[i]);\n solution.matched_stars.push_back(temp_matched_stars[0]);\n }\n }\n}\n\nvoid Matcher::perform_matches(vector<Blob>& blobs, Solution& solution, Shared::Image::Raw& image)\n{\n //vector<Star> stars;\n //stars = catalog_manager.get_stars_near(solution.ra, solution.dec);\n //sort(stars.begin(), stars.end(), Star::sort_by_mag);\n solution.num_blobs_total = blobs.size();\n match_blobs_to_stars(blobs, solution, solution.stars_in_fov, image);\n}\n\nvoid Matcher::print_solutions(vector<Solution>& solutions)\n{\n logger.log(format(\"there are %d solutions\") % solutions.size());\n for (unsigned int i=0; i<5 && i<solutions.size(); i++) {\n solutions[i].print(logger, true);\n }\n}\n\n/*\nvoid Matcher::calculate_pvalue(Solution& solution)\n{\n int N = solution.matched_blobs.size();\n double dof = 2*N-3; // if platescale varies its not 3\n\n if ((solution.chi_squared > 0) && (dof >= 1)) {\n }\n else {\n solution.pvalue = 0.0;\n return;\n }\n\n boost::math::chi_squared chi_squared_distribution(dof);\n solution.pvalue = 1 - boost::math::cdf(chi_squared_distribution, solution.chi_squared);\n solution.c1value = dof / sqrt(solution.chi_squared/dof);\n}\n*/\n\nbool Matcher::get_next_base_set(BaseSet& base_set, int num_blobs, bool reset)\n{\n if (reset) {\n base_set_counter = 0;\n shared_matching.counter_stars = shared_status.counter_stars;\n shared_matching.base_sets.clear();\n }\n\n base_set.ids[0] = 0;\n base_set.ids[1] = 1;\n base_set.ids[2] = 2;\n base_set.type = BaseSet::triplet;\n\n int counter = 0;\n int n = std::min(7, num_blobs);\n\n for (int i = 0; i < n - 2; i++) {\n for (int j = i + 1; j < n - 1; j++) {\n\t\t\tfor (int k = j + 1; k < n; k++) {\n if (counter == base_set_counter) {\n base_set.ids[0] = i;\n base_set.ids[1] = j;\n base_set.ids[2] = k;\n base_set.type = BaseSet::triplet;\n base_set_counter++;\n return false;\n }\n counter++;\n }\n }\n }\n\n n = num_blobs;\n\tfor (int i = 0; i < n - 1; i++) {\n\t\tfor (int j = i + 1; j < n; j++) {\n if (counter == base_set_counter) {\n base_set.ids[0] = i;\n base_set.ids[1] = j;\n base_set.ids[2] = 0;\n base_set.type = BaseSet::pair;\n base_set_counter++;\n return false;\n }\n counter++;\n }\n }\n\n return true;\n}\n\nvoid Matcher::inform_blobs_of_matches(Solution& solution)\n{\n for (unsigned int i=0; i<shared_blobs.blobs.size(); i++) {\n for (unsigned int j=0; j<solution.matched_blobs.size() && !shared_blobs.blobs[i].matched; j++) {\n if (solution.matched_blobs[j].id == shared_blobs.blobs[i].id) {\n shared_blobs.blobs[i].matched = true;\n }\n }\n }\n}\n\nvoid Matcher::get_blob_names(Solution& solution)\n{\n if (solution.matched_stars.size() > 0) {\n int i = 0;\n std::string name = \"\";\n double mag = 0.0;\n logger.log(\"getting brightnes star name\");\n catalog_manager.get_star_name(solution.matched_stars[i].id, name, mag);\n logger.log(format(\"got brightnes star name: %s\") % name);\n if (name.size() > 0) {\n Shared::Image::BlobName blob_name;\n blob_name.blob_id = solution.matched_blobs[i].id;\n blob_name.name = name;\n blob_name.mag = mag;\n shared_solution_for_main.blob_names.push_back(blob_name);\n }\n }\n}\n\nvoid Matcher::fill_solutions_for_next_base_set(vector<Solution>& solutions,\n Shared::Image::Raw& image, BaseSet& base_set, vector<Blob>& blobs)\n{\n solutions.clear();\n vector<Blob> base_blobs;\n if (base_set.type == BaseSet::pair && blobs.size() > base_set.ids[1]) {\n base_blobs.clear();\n base_blobs.push_back(blobs[base_set.ids[0]]);\n base_blobs.push_back(blobs[base_set.ids[1]]);\n\n shared_matching.counter_stars = shared_status.counter_stars;\n shared_matching.triplet_counter = base_set_counter;\n shared_matching.base_sets.push_back(base_set);\n Shared::Image::matching.share();\n\n shared_progress.triplet_counter = base_set_counter;\n shared_progress.progress = 0.0;\n Shared::Image::matching_progress.share();\n\n solutions = catalog_manager.load_solutions_from_pair(base_blobs, image.filters);\n\n } else if (base_set.type == BaseSet::triplet && blobs.size() > base_set.ids[2]) {\n base_blobs.clear();\n base_blobs.push_back(blobs[base_set.ids[0]]);\n base_blobs.push_back(blobs[base_set.ids[1]]);\n base_blobs.push_back(blobs[base_set.ids[2]]);\n\n shared_matching.counter_stars = shared_status.counter_stars;\n shared_matching.triplet_counter = base_set_counter;\n shared_matching.base_sets.push_back(base_set);\n Shared::Image::matching.share();\n\n shared_progress.triplet_counter = base_set_counter;\n shared_progress.progress = 0.0;\n Shared::Image::matching_progress.share();\n\n solutions = catalog_manager.load_solutions_from_triplet(base_blobs, image.filters);\n }\n}\n\nbool Matcher::match(vector<Blob>& blobs, Shared::Image::Raw& image, Solution& solution)\n{\n bool solution_found = false;\n\n bool out_of_base_sets = false;\n vector<Solution> solutions;\n BaseSet base_set;\n out_of_base_sets = get_next_base_set(base_set, blobs.size(), true);\n do {\n fill_solutions_for_next_base_set(solutions, image, base_set, blobs);\n for (unsigned int i=0; i<solutions.size() && !done() && !solution_found; i++) {\n shared_progress.counter_stars = shared_matching.counter_stars;\n shared_progress.progress = double(i)/double(solutions.size());\n Shared::Image::matching_progress.share();\n\n solution_fitter.fit(solutions[i].base_blobs, solutions[i].base_stars,\n solutions[i], image);\n\n catalog_manager.fill_stars_in_fov(solutions[i], image, shared_settings.refraction);\n perform_matches(blobs, solutions[i], image);\n\n if (solutions[i].matched_blobs.size() >= 2) {\n solution_fitter.fit(solutions[i].matched_blobs, solutions[i].matched_stars,\n solutions[i], image);\n if (image.filters.check_solution(solutions[i], logger, true)) {\n logger.log(\"solution found\");\n solution_found = true;\n solution = solutions[i];\n solution_fitter.fit(solution.matched_blobs, solution.matched_stars, solution, image, true);\n fluxer.fit(solution, solution.matched_blobs, solution.matched_stars);\n }\n }\n }\n out_of_base_sets = get_next_base_set(base_set, blobs.size());\n } while (!out_of_base_sets && !done() && !solution_found);\n //} while (false);\n\n if (solution_found) {\n shared_status.reason_for_being_done = Shared::Image::Status::solved;\n } else if (out_of_base_sets) {\n shared_status.reason_for_being_done = Shared::Image::Status::tried_all_patterns;\n }\n Shared::Image::status_solver_for_main.share();\n\n return solution_found;\n}\n\n\n" }, { "alpha_fraction": 0.6857143044471741, "alphanum_fraction": 0.6857143044471741, "avg_line_length": 22.33333396911621, "blob_id": "18c160842042758713bb85f568e59f1a3fa8a6b8", "content_id": "a3023a15f77f173096f9845755ed82f3200e0022", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 280, "license_type": "no_license", "max_line_length": 46, "num_lines": 12, "path": "/external_libs/mpsse/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "set(MPSSE_SRCS\n ${MPSSE_SRCS}\n ${CMAKE_CURRENT_SOURCE_DIR}/mpsse.c\n ${CMAKE_CURRENT_SOURCE_DIR}/binarybuffer.c\n PARENT_SCOPE\n)\nset(MPSSE_HEADERS\n ${MPSSE_HEADERS}\n ${CMAKE_CURRENT_SOURCE_DIR}/mpsse.h\n ${CMAKE_CURRENT_SOURCE_DIR}/binarybuffer.h\n PARENT_SCOPE\n)\n" }, { "alpha_fraction": 0.6580281853675842, "alphanum_fraction": 0.6646009683609009, "avg_line_length": 23.204545974731445, "blob_id": "d103d6c2b998da2a77c3fd5e9e16cdee486da756", "content_id": "7197b6a63198fead5a7202a06cb3c37be7e9458e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5325, "license_type": "no_license", "max_line_length": 106, "num_lines": 220, "path": "/cow/src/cow.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* cow (previously known as narsil): GUI commanding front-end\n *\n * This software is copyright (C) 2002-2005 University of Toronto\n *\n * This file is part of cow.\n *\n * cow 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 2 of the License, or\n * (at your option) any later version.\n *\n * cow 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 cow; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n// ***************************************************\n// * Programmed by Adam Hincks *\n// * Later poked at a bit by D.V.Wiebe *\n// * further desecrated by cbn *\n// * Commanding hacked to hell by M.D.P.Truch *\n// * \"Ported\" to qt4 by drmrshdw *\n// ***************************************************\n\n#ifndef COW_H\n#define COW_H\n\nextern \"C\" {\n#include \"../common/include/netcmd.h\"\n}\n\n#include <QVariant>\n#include <QDialog>\n#include <QString>\n#include <QSpinBox>\n#include <QMainWindow>\n#include <QLineEdit>\n#include <limits>\n#include <limits.h>\n#include <QMap>\n\n#include <sys/types.h>\n\n#include <getdata/dirfile.h>\n\nusing namespace GetData;\n\nclass QVBoxLayout;\nclass QHBoxLayout;\nclass QGridLayout;\nclass QTextEdit;\nclass QGroupBox;\nclass CowOmniBox;\nclass QFrame;\nclass QLabel;\nclass QLineEdit;\nclass QListWidget;\nclass QListBoxItem;\nclass QPushButton;\nclass QRadioButton;\nclass QSpinBox;\nclass QPixmap;\nclass QCheckBox;\nclass QComboBox;\nclass QMultiLineEdit;\n\nclass KstFile;\nclass CowDoubleEntry;\n\nclass Defaults\n{\npublic:\n Defaults();\n void Set(int, int, QString);\n int asInt(int, int);\n double asDouble(int, int);\n const char* asString(int, int);\n void Save();\n\nprivate:\n double *rdefaults[MAX_N_PARAMS];\n int *idefaults[MAX_N_PARAMS];\n char (*sdefaults[MAX_N_PARAMS])[CMD_STRING_LEN];\n};\n\nextern Defaults *defaults;\n\nclass MainForm : public QMainWindow\n{\n Q_OBJECT\n\npublic:\n MainForm(const char *cf, const QString &herdfile, int link, QWidget* parent = 0, const char* name = 0,\n Qt::WindowFlags fl = 0);\n ~MainForm();\n\n QFrame *NTopFrame;\n QFrame *NBotFrame;\n QLineEdit *NCurFile;\n QPushButton *NHost;\n\n QTabWidget *TabWidget;\n QWidget *tab1;\n QGridLayout *tab1Layout;\n\n QWidget *tab2;\n QGridLayout *tab2Layout;\n\n QGroupBox *NGroupsBox;\n QRadioButton **NGroups;\n\n QGroupBox *HerdGroupBox;\n QRadioButton **HerdGroups;\n\n QPushButton *NSendButton;\n //QLabel *NSettingsLabel;\n QPushButton *QuitButton;\n CowOmniBox* NOmniBox;\n QListWidget *NCommandList;\n QLabel *NAboutLabel;\n QLabel *NParamLabels[MAX_N_PARAMS];\n QWidget *NParamFields[MAX_N_PARAMS];\n QLabel *NWaitImage;\n QCheckBox *NVerbose;\n QComboBox *NSendMethod;\n QComboBox *NSendRoute;\n QTextEdit *NLog;\n //QPushButton *NCloseSettingsWindow;\n\n QWidget *centralWidget;\n QVBoxLayout *theVLayout;\n QHBoxLayout *theHLayout;\n QStatusBar *theStatusBar;\n\n void TurnOn(void);\n void TurnOff(void);\n QTimer *timer;\n QTimer *ping_timer;\n\npublic:\n struct OmniPair\n {\n QString name;\n int group;\n };\nprotected:\n\n QList<OmniPair> OmniList;\n QGridLayout *NGroupsLayout;\n QGridLayout *HerdGroupsLayout;\n\n void keyPressEvent(QKeyEvent *);\n\nprivate:\n void PopulateOmnibox();\n int GroupSIndexes(int group, int *indexes);\n int GroupMIndexes(int group, int *indexes);\n int GetGroup();\n int LinkChanged();\n int SIndex(QString cmd);\n int MIndex(QString cmd);\n char *LongestParam();\n void ReadLog(QTextEdit *dest);\n void WriteCmd(QTextEdit *dest, const char *request);\n void WriteErr(QTextEdit *dest, const char *message, int retstatus);\n void WriteErr(QTextEdit *dest, int retstatus);\n void WriteLog(const char *request);\n\n void ReadHerdFile(const QString &herdfile);\n\n QStringList ListOfHerds;\n QHash<QString, QStringList> HerdHash;\n\n QLabel* ConnBanner;\n\n int ReceivePackets(int, int);\n\n int lastmcmd;\n QString curfile;\n Dirfile *_dirfile;\n\n int fid;\n bool sending;\n\n int pong;\n int verbose;\n int framenum;\n int numframes;\n int dir;\n QPixmap *Images[6];\n\n QMap<int,int> index_defaults;\n\npublic slots:\n void OmniParse(QString filter=\"__AUTODETECT__\");\n void OmniSync();\n void ChangeCommandList(bool really=true);\n void IndexComboChanged(int i) {ChooseCommand(true, i);}\n void ChooseCommand(bool index_combo_changed=false, int combo_index = 0);\n void Quit();\n void SendCommand();\n void Tick();\n void Ping();\n void ChangeHost();\n void ServerDropped();\n void nOmniBox_completerActivated(const QString & text);\n void nOmniBox_textEdited(const QString & text);\n //void testTextChanged(const QString & text); //for debugging\n //void testCursorPositionChanged(int o, int n); //for debugging\n};\n\n#endif\n\n// vim: ts=2 sw=2 et\n" }, { "alpha_fraction": 0.662162184715271, "alphanum_fraction": 0.6681681871414185, "avg_line_length": 16.972972869873047, "blob_id": "3d1e27f7aed19766ddf2b08099c84f40cef8c869", "content_id": "58f97e9070475e2700904126535c64210b819564", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 667, "license_type": "no_license", "max_line_length": 73, "num_lines": 37, "path": "/stars/code/solving/star.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__STAR_H\n#define SOLVING__STAR_H\n\n#include <string>\n\nnamespace Logging\n{\n class Logger;\n}\n\nnamespace Solving\n{\n class Star;\n}\n\nclass Solving::Star\n{\n public:\n Star(int id_, double ra_, double dec_, double mag_);\n Star();\n static bool sort_by_mag(Star first, Star second);\n void print(Logging::Logger& logger, std::string prefix);\n\n int id;\n double ra, dec, mag;\n double fitted_x;\n double fitted_y;\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.5183494091033936, "alphanum_fraction": 0.5337392091751099, "avg_line_length": 29.958114624023438, "blob_id": "9891fb11ab232959f8c2afa3a4cf7a1af4b04f3e", "content_id": "fc506ec0f759bb63503c607cc4e53777bcf015eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5913, "license_type": "no_license", "max_line_length": 111, "num_lines": 191, "path": "/common/mputs.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* mputs.c: BUOS backend for mcp/pcm/mpc\n *\n * This software is copyright (C) 2002-2013 University of Toronto\n *\n * This 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 2 of the License, or\n * (at your option) any later version.\n *\n * This 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 this program; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys/syscall.h>\n#include <sys/time.h>\n#include <time.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <pthread.h>\n\n#include \"mputs.h\"\n#include \"crc.h\"\n\n/* multilog! */\n#define MAX_LOGFILES 11\nstatic int n_logfiles = 1;\nstatic FILE* logfiles[11] = { 0 };\n\n/* tid to name lookup list */\n#define stringify_(x) #x\n#define stringify(x) stringify_(x)\n#define TID_NAME_LEN 6\n#define TID_NAME_FMT \"%\" stringify(TID_NAME_LEN) \"s\"\nstatic struct tid_name {\n int tid;\n char name[TID_NAME_LEN+1];\n struct tid_name* next;\n} *threadNames = NULL;\n\n/* This function can be used to name a thread */\nvoid nameThread(const char* name)\n{\n struct tid_name* new_node = (struct tid_name*)malloc(sizeof(struct tid_name));\n new_node->tid = syscall(SYS_gettid);\n strncpy(new_node->name, name, TID_NAME_LEN);\n new_node->name[TID_NAME_LEN] = '\\0';\n new_node->next = threadNames;\n threadNames = new_node;\n}\n\noff_t openMCElog(const char *file)\n{\n off_t offset = -1;\n struct stat statbuf;\n\n if (n_logfiles < MAX_LOGFILES) {\n if ((logfiles[n_logfiles] = fopen(file, \"a\")) == NULL) {\n berror(err, \"Can't open log file %s\", file);\n } else {\n if (fstat(fileno(logfiles[n_logfiles]), &statbuf) == 0)\n offset = (off_t)statbuf.st_size;\n\n fputs(\"!!!!!! LOG RESTART !!!!!!\\n\", logfiles[n_logfiles++]);\n }\n }\n\n return offset;\n}\n\nstatic char failed_lookup_buffer[TID_NAME_LEN+1];\nstatic char* threadNameLookup(int tid)\n{\n struct tid_name* p;\n for (p = threadNames; p != NULL; p = p->next)\n if (p->tid == tid) return p->name;\n\n // not found, just print tid\n snprintf(failed_lookup_buffer, TID_NAME_LEN, \"%u\", (unsigned) tid);\n failed_lookup_buffer[TID_NAME_LEN] = '\\0';\n return failed_lookup_buffer;\n}\n\n\n#define MPRINT_BUFFER_SIZE 1024\n#define MAX_MPRINT_STRING \\\n( \\\n MPRINT_BUFFER_SIZE /* buffer length */ \\\n - 6 /* 2*(marker+space) + EOL + NUL */ \\\n - 24 /* date \"YYYY-MM-DD HH:MM:SS.mmm \" */ \\\n - TID_NAME_LEN - 2 /* thread name \"ThName: \" */ \\\n)\n\n/* I/O function to be used by bputs, bprintf, etc. To use it, add\n *\n * buos_use_func(mputs);\n *\n * to your initialization code.\n */\nvoid mputs(buos_t flag, const char* message) {\n char *buffer;\n static struct timeval last_time = {0};\n static uint32_t last_crc = 0;\n static int repeat_count = 0;\n uint32_t crc;\n\n struct timeval t;\n struct tm now;\n static const char month[12][4] = {\n \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\",\n \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"\n };\n static const char marker[mem + 1] = {\n [err] = '*',\n [fatal] = '!',\n [info] = '-',\n [sched] = '#',\n [startup] = '>',\n [tfatal] = '$',\n [warning] = '=',\n [mem] = '@',\n [none] = '?'\n };\n int tid = syscall(SYS_gettid);\n int i;\n\n /// Set this here to ensure it is correct when we write.\n logfiles[0] = stdout;\n\n if (flag == none || flag == mem) return;\n\n /* time */\n gettimeofday(&t, NULL);\n t.tv_sec += TEMPORAL_OFFSET;\n gmtime_r(&t.tv_sec, &now);\n\n blast_tmp_sprintf(buffer,\n \"%c%3s-%02d-%02d \" // marker, Month-Day-Year\n \"%02d:%02d:%02d.%03d%c \" // Hours:Minutes:Seconds, Marker\n TID_NAME_FMT \": \" // Thread name\n \"%s\\n\", // Message\n marker[flag], month[now.tm_mon], now.tm_mday, now.tm_year - 100,\n now.tm_hour, now.tm_min, now.tm_sec, (int)(t.tv_usec/1000), marker[flag],\n threadNameLookup(tid),\n message);\n\n crc = crc32(BLAST_MAGIC32, message, strlen(message));\n\n if (crc != last_crc || t.tv_sec - last_time.tv_sec > 10) {\n for (i = 0; i < n_logfiles; ++i) {\n if (repeat_count) {\n fprintf(logfiles[i],\n \"%40s Last message repeats %d times\\n\", \" \", repeat_count);\n }\n fputs(buffer, logfiles[i]);\n fflush(logfiles[i]);\n }\n repeat_count = 0;\n\n if (flag == fatal) {\n for (i = 0; i < n_logfiles; ++i) {\n fputs(\"!! Last error is FATAL. Cannot continue.\\n\", logfiles[i]);\n fflush(logfiles[i]);\n }\n exit(1);\n }\n\n if (flag == tfatal) {\n for (i = 0; i < n_logfiles; ++i) {\n fprintf(logfiles[i], \"$$ Last error is THREAD FATAL. Thread [\" TID_NAME_FMT \" (%5i)] exits.\\n\",\n threadNameLookup(tid), tid);\n fflush(logfiles[i]);\n }\n pthread_exit(NULL);\n }\n } else {\n repeat_count++;\n }\n last_crc = crc;\n last_time.tv_sec = t.tv_sec;\n}\n" }, { "alpha_fraction": 0.766749382019043, "alphanum_fraction": 0.767852246761322, "avg_line_length": 31.675676345825195, "blob_id": "03b28656307d83a2aad7df5496d9fb67e164db83", "content_id": "97aaa69b38e3af73be782ca6433dc5c9428edb1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3627, "license_type": "no_license", "max_line_length": 93, "num_lines": 111, "path": "/starcam/csbigcam.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n\n\tcsbigcam.h - Contains the interface to the csbigcam\n\t\t\t\t camera class\n\n*/\n#ifndef _CSBIGCAM_\n#define _CSBIGCAM_\n\n#ifndef _PARDRV_\n #include \"sbigudrv.h\"\n#endif\n\n#ifndef _CSBIGIMG_\n #include \"csbigimg.h\"\n#endif\n\n#include <string>\n#include \"camconfig.h\"\n\nusing namespace std;\n\ntypedef enum {RELAY_XPLUS, RELAY_XMINUS, RELAY_YPLUS, RELAY_YMINUS } CAMERA_RELAY;\ntypedef enum {SBDF_LIGHT_ONLY, SBDF_DARK_ONLY, SBDF_DARK_ALSO } SBIG_DARK_FRAME;\n\nclass CSBIGCam {\nprivate:\n\tPAR_ERROR m_eLastError;\n\tPAR_COMMAND m_eLastCommand;\n\tshort m_nDrvHandle;\n\tCAMERA_TYPE m_eCameraType;\n\tCCD_REQUEST m_eActiveCCD;\n\tdouble m_dExposureTime;\n\tunsigned short m_uReadoutMode;\n\tABG_STATE7 m_eABGState;\n\tint m_nSubFrameLeft, m_nSubFrameTop, m_nSubFrameWidth, m_nSubFrameHeight;\n\npublic:\n\t// Constructors/Destructors\n\tCSBIGCam();\n\tCSBIGCam(OpenDeviceParams odp);\n\tCSBIGCam(SBIG_DEVICE_TYPE dev);\n\t~CSBIGCam();\n\tvoid Init(SBIGCamConfigParams params = defaultCameraParams.SBIGParams);\n\n\t// Error Reporting Routines\n\tPAR_ERROR GetError();\n\tstring GetErrorString();\n\tstring GetErrorString(PAR_ERROR err);\n\tPAR_COMMAND GetCommand();\n\n\t// Accessor Functions\n\tdouble GetExposureTime(void) { return m_dExposureTime; }\n\tvoid SetExposureTime(double exp) { m_dExposureTime = exp; }\n\tCCD_REQUEST GetActiveCCD(void) { return m_eActiveCCD; }\n\tvoid SetActiveCCD(CCD_REQUEST ccd) { m_eActiveCCD = ccd; }\n\tunsigned short GetReadoutMode(void) { return m_uReadoutMode; }\n\tvoid SetReadoutMode(unsigned short rm) { m_uReadoutMode = rm; }\n\tCAMERA_TYPE GetCameraType(void) { return m_eCameraType; }\n\tABG_STATE7 GetABGState(void) { return m_eABGState; }\n\tvoid SetABGState(ABG_STATE7 abgState) { m_eABGState = abgState; }\n\tvoid SetSubFrame(int nLeft, int nTop, int nWidth, int nHeight);\n\tvoid GetSubFrame(int &nLeft, int &nTop, int &nWidth, int &nHeight);\n\n\t// Driver/Device Routines\n\tPAR_ERROR OpenDriver();\n\tPAR_ERROR CloseDriver();\n\tPAR_ERROR OpenDevice(OpenDeviceParams odp);\n\tPAR_ERROR CloseDevice();\n\tPAR_ERROR GetDriverInfo(DRIVER_REQUEST request, GetDriverInfoResults0 &gdir);\n\tPAR_ERROR SetDriverControl(DRIVER_CONTROL_PARAM ctrlpram, unsigned long ctrlval);\n\n\t// High-Level Exposure Related Commands\n\tPAR_ERROR GrabImage(CSBIGImg *pImg, SBIG_DARK_FRAME dark);\n\n\t// Low-Level Exposure Related Commands\n\tPAR_ERROR StartExposure(SHUTTER_COMMAND shutterState);\n\tPAR_ERROR EndExposure(void);\n\tPAR_ERROR IsExposureComplete(MY_LOGICAL &complete);\n\tPAR_ERROR StartReadout(StartReadoutParams srp);\n\tPAR_ERROR EndReadout(void);\n\tPAR_ERROR ReadoutLine(ReadoutLineParams rlp, MY_LOGICAL darkSubtract, unsigned short *dest);\n\tPAR_ERROR DumpLines(unsigned short noLines);\n\n\t//Temperature Related Commands\n\tPAR_ERROR GetCCDTemperature(double &ccdTemp);\n\tPAR_ERROR SetTemperatureRegulation(MY_LOGICAL enable, double setpoint);\n\tPAR_ERROR QueryTemperatureStatus(MY_LOGICAL &enabled, double &ccdTemp,\n\t\tdouble &setpointTemp, double &percentTE);\n\n\t// Control Related Commands\n\tPAR_ERROR ActivateRelay(CAMERA_RELAY relay, double time);\n\tPAR_ERROR IsRelayActive(CAMERA_RELAY relay, MY_LOGICAL &active);\n\tPAR_ERROR AOTipTilt(AOTipTiltParams attp);\n\tPAR_ERROR CFWCommand(CFWParams cfwp, CFWResults &cfwr);\n\n\t// General Purpose Commands\n\tPAR_ERROR EstablishLink(void);\n\tstring GetCameraTypeString(void);\n\tPAR_ERROR GetFullFrame(int &nWidth, int &nHeight);\n\n\t// Utility functions\n\tMY_LOGICAL CheckLink(void);\n\tunsigned short DegreesCToAD(double degC, MY_LOGICAL ccd = TRUE);\n\tdouble ADToDegreesC(unsigned short ad, MY_LOGICAL ccd = TRUE);\n\n\t// Allows access directly to driver\n\tPAR_ERROR SBIGUnivDrvCommand(short command, void *Params, void *Results);\n};\n\n#endif /* #ifndef _CSBIGCAM_ */\n" }, { "alpha_fraction": 0.7100371718406677, "alphanum_fraction": 0.7130111455917358, "avg_line_length": 21.79660987854004, "blob_id": "c6181ce1eddbad58575318a97a06fef79bc6ff07", "content_id": "31e922efc64bbcb684277a7521e306f97ef68d82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1346, "license_type": "no_license", "max_line_length": 73, "num_lines": 59, "path": "/stars/code/housekeeping/housekeeper.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef HOUSEKEEPING__HOUSEKEEPER_H\n#define HOUSEKEEPING__HOUSEKEEPER_H\n\n#include <boost/program_options.hpp>\n#include \"measurement.h\"\n#include \"../tools/timing.h\"\n#include \"../star_camera.h\"\n#include <string>\n\n#if HAVEDAQ\n#include \"../dmm.h\"\n#endif\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Housekeeping\n{\n using namespace boost::program_options;\n class Housekeeper;\n}\n\nclass Housekeeping::Housekeeper\n{\n public:\n Housekeeper(Parameters::Manager& params, dmm *card);\n void add_channel(variables_map map, int channel_num);\n void update_shared();\n void get_disk();\n void update();\n\tvoid heat_camera();\n\n private:\n Tools::Timer last_temps_measurement_timer;\n Tools::Timer last_disk_measurement_timer;\n Tools::Timer last_successful_disk_space_timer;\n Tools::Timer timer_since_first_disk_space_measurement;\n double disk_space;\n double disk_space_first_measurement;\n double disk_time;\n bool disk_time_valid;\n unsigned int write_temps_counter;\n unsigned int write_disk_counter;\n std::vector<Measurement> measurements;\n\tstd::string output_dir;\n\t\n\tdmm *ad_card;\n};\n\n#endif\n" }, { "alpha_fraction": 0.7015523314476013, "alphanum_fraction": 0.7145718336105347, "avg_line_length": 30.203125, "blob_id": "ddcdef22e7072fa11a3bc17ba26a2fa6a364e76c", "content_id": "6643feff9a71af5e27ebf6f07bb293f034d2b18d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1997, "license_type": "no_license", "max_line_length": 101, "num_lines": 64, "path": "/owl/POwlAnimation.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include <QWidget>\n#include <QDataStream>\n#include <QLabel>\n#include <QHBoxLayout>\n#include <getdata/dirfile.h>\n#include \"PObject.h\"\n#include <QMouseEvent>\n#include <QPoint>\n\n#ifndef OWLBOX_H\n#define OWLBOX_H\n\nclass POwlAnimation : public QWidget, public PObject\n{\n Q_OBJECT\n int _lastNFrames;\n int _nUpdates;\n QPixmap _pixMaps[5];\n QLabel* _label;\n int _stage;\n QPoint _moveThingy;\n int _H;\npublic:\n friend QDataStream& operator<<(QDataStream&a,POwlAnimation&b);\n friend QDataStream& operator>>(QDataStream&a,POwlAnimation&b);\n\n POwlAnimation(int font_height);\n ~POwlAnimation();\n void gdUpdate(GetData::Dirfile* dirFile,int lastNFrames, int dt);\n QSize sizeHint();\n const int& stage() const;\n void mousePressEvent(QMouseEvent *ev) { _moveThingy=mapFromGlobal(ev->globalPos()); activate(); }\n void mouseReleaseEvent(QMouseEvent *) { _moveThingy=QPoint(-1,-1); }\n void mouseMoveEvent(QMouseEvent *);\n void activate() { emit activated(); }\nsignals:\n void activated();\n};\n\nQDataStream& operator<<(QDataStream&a,POwlAnimation&b);\nQDataStream& operator>>(QDataStream&a,POwlAnimation&b);\n\n#endif // OWLBOX_H\n" }, { "alpha_fraction": 0.7182130813598633, "alphanum_fraction": 0.7285223603248596, "avg_line_length": 21.384614944458008, "blob_id": "4d4bdcb0c89866e44da1375de019f0f385c8050d", "content_id": "08d632073dfaaef2832ccff89e9b5af68814d4fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 583, "license_type": "no_license", "max_line_length": 73, "num_lines": 26, "path": "/stars/code/networking/logger.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef NETWORKING__LOGGER_H\n#define NETWORKING__LOGGER_H\n\n#include \"../logging/logger.h\"\n\nnamespace Networking\n{\n // To be used only by the network thread\n extern Logging::Logger logger;\n}\n\nnamespace NetworkingImageClient\n{\n // To be used only by the NetworkingImageClient thread\n extern Logging::Logger logger1;\n extern Logging::Logger logger2;\n}\n\n#endif\n" }, { "alpha_fraction": 0.5923741459846497, "alphanum_fraction": 0.6021121740341187, "avg_line_length": 34.735294342041016, "blob_id": "80fe1f2e5b1309c07dc137833f79d9662893020c", "content_id": "fbf607b957400e7f726b34fef534c82ab24ffb8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7292, "license_type": "no_license", "max_line_length": 105, "num_lines": 204, "path": "/stars/code/solving/autofocus_helper.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"autofocus_helper.h\"\n#include \"blob.h\"\n#include \"solution.h\"\n#include \"../shared/image/raw.h\"\n#include \"../shared/image/stats.h\"\n#include \"../shared/autofocus/datapoints.h\"\n#include \"../shared/autofocus/results.h\"\n#include \"../tools/timing.h\"\n#include \"../tools/correlate.h\"\n#include \"../parameters/manager.h\"\n\nusing namespace Solving;\nusing std::vector;\n#define shared_datapoints (*(Shared::Autofocus::datapoints_solver_to_lens.w))\n#define shared_stats (*(Shared::Image::stats_solver_for_main.w))\n#define shared_results (*(Shared::Autofocus::results_lens_to_solver.r))\n\nAutofocusDatapoint::AutofocusDatapoint()\n{\n type = Shared::Autofocus::metric_brightest_blob_flux;\n star_id = 0;\n focus = 0.0;\n value = 0.0;\n}\n\nAutofocusDatapoint& AutofocusDatapoint::operator=(const AutofocusDatapoint &rhs)\n{\n if (this != &rhs) {\n type = rhs.type;\n star_id = rhs.star_id;\n focus = rhs.focus;\n value = rhs.value;\n age = rhs.age;\n }\n return *this;\n}\n\nAutofocusHelper::AutofocusHelper(Parameters::Manager& params)\n{\n datapoints.clear();\n\timage_width = params.general.try_get(\"imaging.camera_real.image_width\", params.general.image_width);\n\timage_height = params.general.try_get(\"imaging.camera_real.image_height\", params.general.image_height);\n scratch = new double[image_width*image_height];\n}\n\nAutofocusHelper::~AutofocusHelper()\n{\n delete [] scratch;\n}\n\nvoid AutofocusHelper::update_and_share()\n{\n using namespace Shared::Autofocus;\n double max_age = Time::from_minutes(30.0);\n\n\n // only keep data points that are younger than the last autofocus run and younger than max_age\n std::vector<AutofocusDatapoint> temp_datapoints = datapoints;\n datapoints.clear();\n for (unsigned int i=0; i<temp_datapoints.size(); i++) {\n if (temp_datapoints[i].age.time() < max_age &&\n temp_datapoints[i].age.time() < shared_results.age_of_last_run.time())\n {\n datapoints.push_back(temp_datapoints[i]);\n }\n }\n sort(datapoints.begin(), datapoints.end(),\n AutofocusDatapoint::sort_by_focus);\n\n shared_datapoints.curves.clear();\n for (unsigned int i=0; i<datapoints.size(); i++) {\n datapoints_t type = datapoints[i].type;\n int star_id = datapoints[i].star_id;\n double focus = datapoints[i].focus;\n double value = datapoints[i].value;\n Tools::Timer age = datapoints[i].age;\n\n bool curve_found = false;\n for (unsigned int j=0; j<shared_datapoints.curves.size(); j++) {\n if (shared_datapoints.curves[j].type == type &&\n (shared_datapoints.curves[j].type == metric_brightest_blob_flux ||\n shared_datapoints.curves[j].star_id == star_id))\n {\n curve_found = true;\n shared_datapoints.curves[j].points.push_back(CurvePoint(focus, value));\n if (age.time() < shared_datapoints.curves[j].age_since_last_datapoint_added.time()) {\n shared_datapoints.curves[j].age_since_last_datapoint_added = age;\n }\n }\n }\n if (!curve_found) {\n Curve curve;\n curve.type = type;\n curve.star_id = star_id;\n curve.points.push_back(CurvePoint(focus, value));\n curve.age_since_last_datapoint_added = age;\n shared_datapoints.curves.push_back(curve);\n }\n }\n sort(shared_datapoints.curves.begin(), shared_datapoints.curves.end(),\n Curve::sort_by_type);\n\n datapoints_solver_to_lens.share();\n}\n\nvoid AutofocusHelper::extract_sobel_datapoint(Shared::Image::Raw& image)\n{\n double sum_x = 0.0;\n double kernel_x[9] = {-1.0, 0.0, 1.0, -2.0, 0.0, 2.0, -1.0, 0.0, 1.0};\n Tools::correlate2d(image.pixels, kernel_x, scratch, 1, 1, image_width, image_height);\n for (int j=0; j<image_height; j++) {\n for (int i=0; i<image_width; i++) {\n sum_x += scratch[j*image.width+i];\n }\n }\n sum_x = fabs(sum_x);\n /*\n // only do the x kernel because there can be significant variations across rows due to readout\n double sum_y = 0.0; \n double kernel_y[9] = {1.0, 2.0, 1.0, 0.0, 0.0, 0.0, -1.0, -2.0, -1.0};\n Tools::correlate2d(image.pixels, kernel_y, scratch, 1, 1, image_width, image_height);\n for (int j=0; j<image_height; j++) {\n for (int i=0; i<image_width; i++) {\n sum_y += scratch[j*image.width+i];\n }\n }\n sum_y = fabs(sum_y);\n */\n AutofocusDatapoint datapoint;\n datapoint.type = Shared::Autofocus::metric_sobel;\n datapoint.focus = image.focus;\n datapoint.value = sum_x;\n datapoint.age = image.age;\n if (shared_results.mode == Shared::Autofocus::Results::mode_running) {\n datapoints.push_back(datapoint);\n update_and_share();\n }\n}\n\nvoid AutofocusHelper::extract_brightest_blob_datapoint(Shared::Image::Raw& image, vector<Blob>& blobs)\n{\n if (image.focus_known) {\n double peak = 0.0;\n bool at_least_one_blob = false;\n for (unsigned int i=0; i<blobs.size(); i++) {\n if (!blobs[i].saturated) {\n at_least_one_blob = true;\n if (blobs[i].peak > peak) {\n peak = blobs[i].peak;\n }\n }\n }\n if (at_least_one_blob) {\n AutofocusDatapoint datapoint;\n datapoint.type = Shared::Autofocus::metric_brightest_blob_flux;\n datapoint.focus = image.focus;\n datapoint.value = peak;\n datapoint.age = image.age;\n if (shared_results.mode == Shared::Autofocus::Results::mode_running) {\n datapoints.push_back(datapoint);\n update_and_share();\n shared_stats.autofocus_metric_valid = true;\n shared_stats.autofocus_metric = datapoint.value;\n Shared::Image::stats_solver_for_main.share();\n }\n }\n }\n}\n\nvoid AutofocusHelper::extract_star_datapoints(Shared::Image::Raw& image, Solution& solution)\n{\n if (image.focus_known) {\n bool at_least_one_star = false;\n for (unsigned int i=0; i<solution.matched_stars.size() && i<solution.matched_blobs.size(); i++) {\n at_least_one_star = true;\n AutofocusDatapoint datapoint;\n datapoint.type = Shared::Autofocus::metric_star_flux;\n datapoint.star_id = solution.matched_stars[i].id;\n datapoint.focus = image.focus;\n datapoint.value = solution.matched_blobs[i].peak;\n datapoint.age = image.age;\n if (shared_results.mode == Shared::Autofocus::Results::mode_running) {\n datapoints.push_back(datapoint);\n }\n }\n if (at_least_one_star) {\n if (shared_results.mode == Shared::Autofocus::Results::mode_running) {\n update_and_share();\n }\n }\n }\n}\n\nvoid AutofocusHelper::set_fully_solved(int counter_stars)\n{\n shared_datapoints.last_fully_solved_counter_stars = counter_stars;\n Shared::Autofocus::datapoints_solver_to_lens.share();\n}\n\n" }, { "alpha_fraction": 0.569270670413971, "alphanum_fraction": 0.5778889656066895, "avg_line_length": 32.50621032714844, "blob_id": "47ff63b47b5167b8a28dfeb961f75f71f2421fdb", "content_id": "82ac0e96462bb25a8374d7a89dd9970e65e969f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10792, "license_type": "no_license", "max_line_length": 171, "num_lines": 322, "path": "/stars/code/solving/finding/finder.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"finder.h\"\n#include <cstdio>\n#include <limits>\n#include <algorithm>\n#include <boost/math/special_functions/erf.hpp>\n#include \"../../tools/math.h\"\n#include \"../../shared/image/blobs.h\"\n#include \"../../shared/image/raw.h\"\n#include \"../../shared/solving/settings.h\"\n#include \"../../shared/solving/mask.h\"\n#include \"../update.h\"\n#include \"../../parameters/manager.h\"\n#include \"../../parameters/housekeeping.h\"\n#include \"../logger.h\"\n\n#include \"../../tools/quick_cout.h\"\n\nusing namespace Solving::Finding;\nusing Solving::Blob;\nusing std::vector;\nusing std::max;\nusing std::min;\n\n#define shared_settings (*(Shared::Solving::settings.r))\n#define shared_mask (*(Shared::Solving::mask_network_for_solver.r))\n#define shared_blobs (*(Shared::Image::blobs_solver_for_main.w))\n\nFinder::Finder(Parameters::Manager& params):\n smoother(params), leveler(params), badpix(params)\n{\n\timage_width = params.general.try_get(\"imaging.camera_real.image_width\", params.general.image_width);\n\timage_height = params.general.try_get(\"imaging.camera_real.image_height\", params.general.image_height);\n pixels_smoothed = new double[image_width*image_height];\n pixels_leveled = new unsigned short[image_width*image_height];\n bypass_blobs_enabled = params.general.try_get(\"solver.blob_finder.bypass_with_blobs.enabled\", false);\n\tbypass_blobs.clear();\n\tbadpixlist = params.general.try_get(\"solver.blob_finder.badpixfilename\", string(\"badpixels_ISC.cam\"));\n\tbadpix.load_badpix(badpixlist);\n\tsatval = 16383; \n\t//mapmean = 0;\n\n if (bypass_blobs_enabled) {\n unsigned int num_blobs = params.general.try_get(\"solver.blob_finder.bypass_with_blobs.num_blobs\", (unsigned int) 0);\n for (unsigned int i=0; i<num_blobs; i++) {\n Blob blob;\n blob.x = params.general.try_get((boost::format(\"solver.blob_finder.bypass_with_blobs.blob%d.x\") %i).str(), 0.0);\n blob.y = params.general.try_get((boost::format(\"solver.blob_finder.bypass_with_blobs.blob%d.y\") %i).str(), 0.0);\n blob.u = int(round(blob.x + (double(image_width)-1.0)/2.0));\n blob.v = int(round(blob.y + (double(image_height)-1.0)/2.0));\n\t\t\t//blob.saturated = \n bypass_blobs.push_back(blob);\n }\n }\n}\n\nFinder::~Finder()\n{\n delete [] pixels_smoothed;\n delete [] pixels_leveled;\n}\n\nvector<Blob> Finder::fit_blobs(Shared::Image::Raw& image, vector<Blob> &blobs) {\n vector<Blob> fitted_blobs;\n for (unsigned int i=0; i<blobs.size(); i++) {\n Blob fitted_blob = fitter.fit(image, blobs[i]);\n if (fitted_blob.fit_was_good) {\n fitted_blobs.push_back(fitted_blob);\n }\n }\n return fitted_blobs;\n}\n\nbool Finder::is_local_max_in_smooth(int x, int y)\n{\n if ((x>0 && x<image_width-1) && (y>0 && y<image_height-1)) {\n for (int dx=-1; dx<=1; dx++) {\n for (int dy=-1; dy<=1; dy++) {\n if (dx != 0 || dy != 0) {\n if (pixels_smoothed[(y+dy)*image_width+(x+dx)] > pixels_smoothed[y*image_width+x]) {\n return false;\n }\n }\n }\n }\n }\n else{\n for (int dx=-1; dx<=1; dx++) {\n for (int dy=-1; dy<=1; dy++) {\n if (dx != 0 || dy != 0) {\n if ((x+dx) >= 0 && (x+dx) < image_width &&\n (y+dy) >= 0 && (y+dy) < image_height) {\n if (pixels_smoothed[(y+dy)*image_width+(x+dx)] > pixels_smoothed[y*image_width+x]) {\n return false;\n }\n }\n }\n }\n }\n }\n return true;\n}\n\nvector<Blob> Finder::search_for_peaks_in_cell(unsigned int cell_size, unsigned int ucell, unsigned int vcell, double threshold, double noise, unsigned int max_num_blobs) {\n unsigned int validity_padding = 5;\n unsigned int umin, umax, vmin, vmax;\n vector<Blob> cellblobs;\n\n umin = max(ucell, validity_padding);\n umax = min(ucell+cell_size, image_width-validity_padding);\n vmin = max(vcell, validity_padding);\n vmax = min(vcell+cell_size, image_height-validity_padding);\n for (unsigned int v=vmin; v<vmax; v++) {\n for (unsigned int u=umin; u<umax; u++) {\n if (pixels_smoothed[v*image_width+u] > pixels_leveled[v*image_width+u]+threshold*noise) {\n if (is_local_max_in_smooth(u, v)) {\n Blob new_blob;\n new_blob.u = u;\n new_blob.v = v;\n new_blob.correlated_peak = pixels_smoothed[v*image_width+u]\n - pixels_leveled[v*image_width+u];\n cellblobs.push_back(new_blob);\n u++;\n }\n }\n }\n }\n sort(cellblobs.begin(), cellblobs.end(), Blob::sort_by_correlated_peak);\n if (cellblobs.size() > max_num_blobs) {\n cellblobs.resize(max_num_blobs);\n }\n return cellblobs;\n}\n\nvector<Blob> Finder::search_for_peaks(int halfwidth, double noise) {\n unsigned int ucell, vcell;\n double threshold;\n vector<Blob> blobs, cell_blobs;\n int cell_skip = shared_settings.cell_size;\n\n //threshold = 3.0 / (2*halfwidth+1);\n threshold = shared_settings.snr_threshold;\n\n for (vcell=0; vcell<(unsigned int)image_height; vcell+=cell_skip) {\n for (ucell=0; ucell<(unsigned int)image_width; ucell+=cell_skip) {\n if (!shared_mask.cell_masked(ucell, vcell)) {\n cell_blobs = search_for_peaks_in_cell(cell_skip, ucell, vcell, threshold, noise, shared_settings.max_num_blobs_per_cell); \n blobs.insert(blobs.end(), cell_blobs.begin(), cell_blobs.end());\n }\n }\n }\n return blobs;\n}\n\nbool Finder::are_duplicates(Blob& blob0, Blob& blob1)\n{\n int max_hw = 20;\n if (abs(blob0.u - blob1.u) > max_hw) return false;\n if (abs(blob0.v - blob1.v) > max_hw) return false;\n\n double distance;\n distance = sqrt(pow(double(blob0.u-blob1.u), 2) + pow(double(blob0.v-blob1.v), 2));\n if (distance < abs(blob0.approximate_size)*1.5) {\n return true;\n }\n if (distance < abs(blob1.approximate_size)*1.5) {\n return true;\n }\n return false;\n}\n\nvector<Blob> Finder::unique(vector<Blob>& original_blobs)\n{\n vector<Blob> blobs;\n for (unsigned int i=0; i<original_blobs.size(); i++) {\n bool duplicate_found = false;\n for (unsigned int j=0; j<blobs.size() && !duplicate_found; j++) {\n if (are_duplicates(original_blobs[i], blobs[j])) {\n duplicate_found = true;\n if (Blob::sort_by_flux_confidence(original_blobs[i], blobs[j])) {\n blobs[j] = original_blobs[i];\n }\n }\n }\n if (!duplicate_found) {\n blobs.push_back(original_blobs[i]);\n }\n }\n return blobs;\n}\n\nvector<Blob> Finder::estimate_blobs(Shared::Image::Raw& image, vector<Blob> possible_blobs)\n{\n\n vector<Blob> blobs;\n bool valid;\n Blob new_blob;\n for (unsigned int i=0; i<possible_blobs.size(); i++) {\n new_blob = estimator.estimate_blob(image, possible_blobs[i], valid);\n if (valid) {\n blobs.push_back(new_blob);\n }\n }\n return blobs;\n}\n\n\nvoid Finder::print_blobs (vector<Blob>& blobs)\n{\n logger.log(format(\"finder: found %d blobs\")%blobs.size());\n for (unsigned int i=0; i<blobs.size() && i<100; i++) {\n blobs[i].print(logger, \"finder: found blob with \");\n }\n}\n\nvoid Finder::crop_vector(vector<Blob>& blobs, unsigned int num) {\n if (blobs.size() > num) {\n blobs.resize(num);\n }\n}\n\nvector<Blob> Finder::find_blobs(Shared::Image::Raw& image, double noise)\n{\n\n Tools::Timer timer;\n double sigma = 0.0;\n int halfwidth = 1;\n vector<Blob> blobs, possible_blobs;\n blobs.clear();\n possible_blobs.clear();\n\n if (bypass_blobs_enabled) {\n return bypass_blobs;\n }\n\n\t//bad pixel removal goes here\n\ttimer.start();\n\tif(!done()) {\n\t\tbadpix.fix_badpix(image);\t\t\t\n\t}\n\t \t\n\tlogger.log(format(\"finder: fixing bad pixels took %s s\")%timer.time());\n\n timer.start();\n if (!done()) {\n leveler.level(image, pixels_leveled);\n }\n logger.log(format(\"finder: leveling took %s s\")%timer.time());\n\n if (!done()) {\n timer.start();\n halfwidth = 1;\n sigma = 1.0;\n smoother.make_smooth(image, pixels_smoothed, 1, sigma);\n logger.log(format(\"finder: smoothing image took %s s\") % timer.time());\n timer.start();\n possible_blobs = search_for_peaks(halfwidth, noise);\n blobs.insert(blobs.end(), possible_blobs.begin(), possible_blobs.end());\n logger.log(format(\"finder: finding possible small blobs took %s s\")%timer.time());\n }\n\n if (!done() && shared_settings.robust_mode_enabled) {\n\n timer.start();\n halfwidth = 5;\n sigma = 3.5;\n smoother.make_smooth(image, pixels_smoothed, halfwidth, sigma);\n possible_blobs = search_for_peaks(halfwidth, noise);\n blobs.insert(blobs.end(), possible_blobs.begin(), possible_blobs.end());\n halfwidth = 30;\n sigma = 15.0;\n smoother.make_smooth(image, pixels_smoothed, halfwidth, sigma);\n possible_blobs = search_for_peaks(halfwidth, noise);\n blobs.insert(blobs.end(), possible_blobs.begin(), possible_blobs.end());\n logger.log(format(\"finder: finding possible large blobs took %s s\")%timer.time());\n }\n\n if (!done()) {\n\n timer.start();\n if (!done()) {\n blobs = estimate_blobs(image, blobs);\n sort(blobs.begin(), blobs.end(), Blob::sort_by_flux_confidence);\n blobs = unique(blobs);\n }\n logger.log(format(\"finder: estimating blobs took %s s\")%timer.time());\n\n timer.start();\n if (!done()) {\n pedestal_fitter.fit_pedestals(image, blobs);\n }\n logger.log(format(\"finder: fitting pedestals took %s s\")%timer.time());\n\n }\n\n timer.start();\n if (!done()) {\n blobs = fit_blobs(image, blobs);\n }\n logger.log(format(\"finder: fitting blobs took %s s\")%timer.time());\n\n timer.start();\n if (!done()) {\n\t\tsort(blobs.begin(), blobs.end(), Blob::sort_by_flux);\n\t\tcrop_vector(blobs, shared_settings.max_num_blobs);\n for (unsigned int i=0; i<blobs.size(); i++) {\n blobs[i].id = i;\n blobs[i].image_noise = noise;\n }\n logger.log(format(\"finder: sorting and assigning took %s s\")%timer.time());\n print_blobs(blobs);\n return blobs;\n }\n\n blobs.clear();\n return blobs;\n}\n\n\n" }, { "alpha_fraction": 0.47404035925865173, "alphanum_fraction": 0.5665600299835205, "avg_line_length": 33.88412094116211, "blob_id": "db672f55ab87b98c879e21546097c4d97ec18521", "content_id": "7fa63345e1994b29373dcc960d8dee7a5f371484", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8128, "license_type": "no_license", "max_line_length": 258, "num_lines": 233, "path": "/test_programs/synclink/test_biphase.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <memory.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <signal.h>\n#include <termios.h>\n#include <errno.h>\n#include <sys/ioctl.h>\n#include <sys/time.h>\n#include <linux/types.h>\n\n#include \"synclink.h\"\n#include \"blast.h\"\n#include \"crc.h\"\n\nint send_biphase_writes();\n\n\nint main() \n{\n send_biphase_writes();\n}\n\n\nvoid reverse_bits(const size_t bytes_to_write, const uint16_t *msb_data, uint16_t *lsb_data_out) {\n\n static const unsigned char BitReverseTable256[] = \n {\n 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, \n 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, \n 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, \n 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, \n 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, \n 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,\n 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, \n 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,\n 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,\n 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, \n 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,\n 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,\n 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, \n 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,\n 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, \n 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF\n };\n uint16_t lsb;\n uint16_t msb;\n for (int i = 0; i < ((int) bytes_to_write/2); i++) {\n msb = *(msb_data+i);\n lsb = (BitReverseTable256[msb & 0xff] << 8) | \n (BitReverseTable256[(msb >> 8) & 0xff]);\n *(lsb_data_out+i) = lsb;\n }\n}\n\nint send_biphase_writes() {\n\n int fd;\n int rc;\n int sigs;\n MGSL_PARAMS params; \n\n int counter = 0;\n struct timeval begin, end;\n uint16_t crc_calculated;\n uint16_t small_counter=0;\n\n /* Open device */\n fd = open(\"/dev/ttyMicrogate\", O_RDWR, 0);\n if (fd < 0) {\n blast_err(\"open error=%d %s\", errno, strerror(errno));\n return fd;\n }\n usleep(1000);\n close(fd);\n fd = open(\"/dev/ttyMicrogate\", O_RDWR, 0);\n usleep(1000);\n rc = ioctl(fd, MGSL_IOCGSTATS, 0);\n if (rc < 0) {\n blast_err(\"ioctl(MGSL_IOCGSTATS) error=%d %s\", errno, strerror(errno));\n return rc;\n }\n // Disable transmitter\n int enable = 0;\n rc = ioctl(fd, MGSL_IOCTXENABLE, enable);\n if (rc < 0) {\n blast_err(\"ioctl(MGSL_IOCRXENABLE) error=%d %s\", errno, strerror(errno));\n return rc;\n }\n\n /* Set parameters */\n rc = ioctl(fd, MGSL_IOCGPARAMS, &params);\n if (rc < 0) {\n blast_err(\"ioctl(MGSL_IOCGPARAMS) error=%d %s\", errno, strerror(errno));\n return rc;\n }\n params.mode = MGSL_MODE_RAW;\n params.loopback = 0;\n params.flags = HDLC_FLAG_RXC_BRG + HDLC_FLAG_TXC_BRG;\n params.encoding = HDLC_ENCODING_BIPHASE_LEVEL;\n //params.encoding = HDLC_ENCODING_NRZ;\n params.clock_speed = 1000000;\n params.crc_type = HDLC_CRC_NONE;\n params.addr_filter = 0xff;\n params.preamble = HDLC_PREAMBLE_PATTERN_NONE;\n\n rc = ioctl(fd, MGSL_IOCSPARAMS, &params);\n if (rc < 0) {\n blast_err(\"ioctl(MGSL_IOCSPARAMS) error=%d %s\", errno, strerror(errno));\n return rc;\n }\n int mode = MGSL_INTERFACE_RS422;\n // mode += MGSL_INTERFACE_MSB_FIRST;\n rc = ioctl(fd, MGSL_IOCSIF, mode);\n if (rc < 0) {\n blast_err(\"ioctl(MGSL_IOCSIF) error=%d %s\", errno, strerror(errno));\n return rc;\n }\n\n int idlemode;\n rc = ioctl(fd, MGSL_IOCGTXIDLE, &idlemode);\n blast_info(\"The current idlemode is %04x\", idlemode);\n // idlemode = HDLC_TXIDLE_ZEROS;\n idlemode = HDLC_TXIDLE_CUSTOM_16+0x0000;\n blast_info(\"Setting mode to %04x\", idlemode);\n rc = ioctl(fd, MGSL_IOCSTXIDLE, idlemode);\n rc = ioctl(fd, MGSL_IOCGTXIDLE, &idlemode);\n blast_info(\"The new idlemode is %04x\", idlemode);\n\n // Making an array of data (0xFFFFFFFF...) with sync word and CRC\n uint16_t *data_to_write = NULL;\n uint16_t *lsb_data_to_write = NULL;\n size_t bytes_to_write = 1248; \n\n\n data_to_write = malloc(bytes_to_write); \n lsb_data_to_write = malloc(bytes_to_write*2); \n if (data_to_write) {\n *data_to_write = 0xEB90;\n for (int i = 1; i < ((int) bytes_to_write/2); i++) {\n *(data_to_write+i) = i;\n //*(data_to_write+i) = 0xffff;\n }\n } else {\n close(fd); \n return 0;\n }\n\n int last_word = ((int) bytes_to_write/2) - 1;\n\n // reverse_bits(bytes_to_write, data_to_write, lsb_data_to_write);\n\n // Blocking mode for read and writes\n fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);\n // fcntl(fd, F_SETFL, fcntl(fd, F_GETFL));\n // Request to Send and Data Terminal Ready\n sigs = TIOCM_RTS + TIOCM_DTR;\n rc = ioctl(fd, TIOCMBIS, &sigs);\n if (rc < 0) {\n blast_err(\"assert DTR/RTS error = %d %s\", errno, strerror(errno));\n return rc;\n }\n\n // Enable transmitter\n enable = 1;\n rc = ioctl(fd, MGSL_IOCTXENABLE, enable);\n if (rc < 0) {\n blast_err(\"ioctl(MGSL_IOCRXENABLE) error=%d %s\", errno, strerror(errno));\n return rc;\n }\n\n // set fd options for termios\n system(\"stty --file=/dev/ttyMicrogate 921600 -icanon -echo -echoctl -echonl -isig -noflsh -iexten -onlcr -opost -olcuc -onocr -ocrnl -onlret -icrnl -inpck -istrip -iuclc -ixoff -ixon -igncr -hupcl cs8 -parenb -cstopb -crtscts clocal cread min 1 time 0\");\n\n sleep(3);\n for (int j=0; j>-1; j++) {\n int count = 2496;\n while (count >= 2496) { \n ioctl(fd, TIOCOUTQ, &count);\n usleep(500);\n }\n if (count < 1248) printf(\"Low count (%d)!!\\n\", count);\n data_to_write[2] = small_counter;\n if (j%2 == 0) {\n data_to_write[0] = 0xEB90;\n data_to_write[1] = 0xFFFF;\n } else {\n data_to_write[1] = 0xF1FF;\n data_to_write[0] = 0x146F;\n }\n\t\t\t\tcrc_calculated = 0;\n\t\t\t\tfor (int k=0; k<(bytes_to_write/2)-1; k++) {\n crc_calculated ^= data_to_write[k];\n\t\t\t\t}\n small_counter ++;\n *(data_to_write+last_word) = crc_calculated;\n reverse_bits(bytes_to_write, data_to_write, lsb_data_to_write);\n gettimeofday(&begin, NULL);\n rc = write(fd, lsb_data_to_write, bytes_to_write);\n if (rc < 0) {\n blast_err(\"write error=%d %s. rc=%d. Sleeping 0.05s\", errno, strerror(errno), rc); \n usleep(50000);\n // return rc;\n } else {\n /*\n printf(\"\\n\");\n for (int k=0; k<((int) bytes_to_write/2); k++) {\n if (!(k%32)) printf(\"\\n\");\n printf(\"%04x \", data_to_write[k]);\n }\n */\n }\n // printf(\"\\nWrote %d bytes (%d in buffer)\\n\", rc, count);\n // rc = tcdrain(fd);\n gettimeofday(&end, NULL);\n /*\n if ((counter % 10) == 0) {\n blast_info(\"The CRC calculated is %04x\", crc_calculated);\n blast_dbg(\"It took %f second to write %zd bytes\", (end.tv_usec - begin.tv_usec)/1000000.0, bytes_to_write);\n }\n */\n counter += 1;\n // sleep(1);\n // usleep(100);\n } \n // Closing\n // sigs = TIOCM_RTS + TIOCM_DTR;\n // rc = ioctl(fd, TIOCMBIC, &sigs);\n // close(fd);\n return 0;\n}\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7534482479095459, "avg_line_length": 27.292682647705078, "blob_id": "fd4b2eaabdb868380e9ae811e0fc24887d86cf03", "content_id": "7b233b19accfad1975d1a4a158bfea92e699a93c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1161, "license_type": "no_license", "max_line_length": 73, "num_lines": 41, "path": "/stars/code/shared/shared_list.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__SHARED_LIST_H\n#define SHARED__SHARED_LIST_H\n\n#include \"thread_names.h\"\n#include \"housekeeping/housekeeper.h\"\n#include \"image/blobs.h\"\n#include \"image/leveled.h\"\n#include \"image/matching.h\"\n#include \"image/matching_progress.h\"\n#include \"image/raw.h\"\n#include \"image/solution_summary.h\"\n#include \"image/stats.h\"\n#include \"image/status.h\"\n#include \"lens/requests.h\"\n#include \"lens/results.h\"\n#include \"network/packets.h\"\n#include \"network/client.h\"\n#include \"network/image_client_settings.h\"\n#include \"camera/requests.h\"\n#include \"camera/results.h\"\n#include \"simulations/brightness.h\"\n#include \"solving/settings.h\"\n#include \"solving/filters.h\"\n#include \"solving/mask.h\"\n#include \"autofocus/datapoints.h\"\n#include \"autofocus/requests.h\"\n#include \"autofocus/results.h\"\n#include \"autofocus/latest_image.h\"\n#include \"general/shutdown.h\"\n#include \"general/network_reset.h\"\n#include \"general/main_settings.h\"\n#include \"general/quit.h\"\n\n#endif\n" }, { "alpha_fraction": 0.6925373077392578, "alphanum_fraction": 0.7044776082038879, "avg_line_length": 21.266666412353516, "blob_id": "03dc34439a125683281af7f1f86585cad4d4498a", "content_id": "c1a7f02a3ea07f03f4ea198978ff23a46dcc2b1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 336, "license_type": "no_license", "max_line_length": 73, "num_lines": 15, "path": "/stars/code/shared/general/shutdown.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"shutdown.h\"\n\nusing namespace Shared::General;\n\nShutdown::Shutdown()\n{\n shutdown_now = false;\n include_restart = false;\n}\n\n" }, { "alpha_fraction": 0.6260504126548767, "alphanum_fraction": 0.6365545988082886, "avg_line_length": 18.79166603088379, "blob_id": "3bc87c83d8700a6041dd5279c044106fe5c52ad8", "content_id": "6fe3e1f7c6b64913b4305053c96b09215909647c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 477, "license_type": "no_license", "max_line_length": 73, "num_lines": 24, "path": "/stars/code/shared/image/blobs.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"blobs.h\"\n\nusing namespace Shared::Image;\n\nBlobs::Blobs()\n{\n counter_stars = -1;\n blobs.clear();\n}\n\nBlobs& Blobs::operator=(const Blobs&rhs)\n{\n if (this != &rhs) {\n counter_stars = rhs.counter_stars;\n blobs = rhs.blobs;\n }\n return *this;\n}\n\n" }, { "alpha_fraction": 0.6010737419128418, "alphanum_fraction": 0.6237869262695312, "avg_line_length": 30.653594970703125, "blob_id": "39f2c91896084abe832448a5851824af0b49fe15", "content_id": "80126e36a0b4a38d870967ed26daf5e9678e2443", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4843, "license_type": "no_license", "max_line_length": 115, "num_lines": 153, "path": "/common/include/blast_time.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * blast_time.h: \n *\n * This software is copyright (C) 2013-2014 Seth Hillbrand\n *\n * This file is part of blast_common, created for the BLASTPol Project.\n *\n * blast_common 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 2 of the License, or\n * (at your option) any later version.\n *\n * blast_common 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 blast_common; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Mar 31, 2015 by Seth Hillbrand\n */\n\n#ifndef INCLUDE_BLAST_TIME_H\n#define INCLUDE_BLAST_TIME_H\n\n#include <time.h>\n#include <stdint.h>\n\ntypedef union\n{\n uint64_t qword;\n struct\n {\n uint32_t seconds; /**< seconds - Number of seconds since the epoch */\n uint32_t nanoseconds; /**< nanoseconds - Number of nanoseconds since the last second */\n } timespec; /**< timespec - Because the system standard timespec might not be 32/32 bits */\n} __attribute__((packed)) blast_time_t;\n\n/* Parameters used to convert the timespec values: */\n#define MSEC_PER_SEC 1000L\n#define USEC_PER_MSEC 1000L\n#define NSEC_PER_USEC 1000L\n#define NSEC_PER_MSEC 1000000L\n#define USEC_PER_SEC 1000000L\n#define NSEC_PER_SEC 1000000000L\n#define FSEC_PER_SEC 1000000000000000LL\n\n#define TIME_T_MAX (time_t)((1UL << ((sizeof(time_t) << 3) - 1)) - 1)\n\n// Add specified amount of ns to timespec\nstatic inline void timespec_add_ns(struct timespec *m_time, unsigned int m_ns)\n{\n m_ns += m_time->tv_nsec;\n while (m_ns >= NSEC_PER_SEC) {\n m_ns -= NSEC_PER_SEC;\n m_time->tv_sec++;\n }\n m_time->tv_nsec = m_ns;\n}\n\nstatic inline int timespec_equal(const struct timespec *a,\n const struct timespec *b)\n{\n return (a->tv_sec == b->tv_sec) && (a->tv_nsec == b->tv_nsec);\n}\n\n/*\n * lhs < rhs: return <0\n * lhs == rhs: return 0\n * lhs > rhs: return >0\n */\nstatic inline int timespec_compare(const struct timespec *lhs, const struct timespec *rhs)\n{\n if (lhs->tv_sec < rhs->tv_sec)\n return -1;\n if (lhs->tv_sec > rhs->tv_sec)\n return 1;\n return lhs->tv_nsec - rhs->tv_nsec;\n}\n\nstatic inline int timeval_compare(const struct timeval *lhs, const struct timeval *rhs)\n{\n if (lhs->tv_sec < rhs->tv_sec)\n return -1;\n if (lhs->tv_sec > rhs->tv_sec)\n return 1;\n return lhs->tv_usec - rhs->tv_usec;\n}\n\nstatic inline void set_normalized_timespec(struct timespec *ts, time_t sec, int64_t nsec)\n{\n while (nsec >= NSEC_PER_SEC) {\n /*\n * The following asm() prevents the compiler from\n * optimising this loop into a modulo operation. See\n * also __iter_div_u64_rem() in include/linux/time.h\n */\n asm(\"\" : \"+rm\"(nsec));\n nsec -= NSEC_PER_SEC;\n ++sec;\n }\n while (nsec < 0) {\n asm(\"\" : \"+rm\"(nsec));\n nsec += NSEC_PER_SEC;\n --sec;\n }\n ts->tv_sec = sec;\n ts->tv_nsec = nsec;\n}\n/*\n * Add two timespec values and do a safety check for overflow.\n * It's assumed that both values are valid (>= 0)\n */\nstatic inline struct timespec timespec_add(const struct timespec lhs,\n const struct timespec rhs)\n{\n struct timespec res;\n\n set_normalized_timespec(&res, lhs.tv_sec + rhs.tv_sec,\n lhs.tv_nsec + rhs.tv_nsec);\n\n if (res.tv_sec < lhs.tv_sec || res.tv_sec < rhs.tv_sec)\n res.tv_sec = TIME_T_MAX;\n\n return res;\n}\n\n/**\n * Convert a BLAST time into standard POSIX timespec structure\n * @param m_ts Pointer to timespec structure\n * @param m_blast Pointer to blast time structure\n */\nstatic inline void blast_time_to_timespec(struct timespec *m_ts, blast_time_t *m_blast)\n{\n set_normalized_timespec(m_ts, m_blast->timespec.seconds, m_blast->timespec.nanoseconds);\n}\n\n/**\n * Convert a POSIX timespec structure into BLAST time\n * @param m_blast Pointer to blast time structure\n * @param m_ts Pointer to timespec structure\n */\nstatic inline void timespec_to_blast_time(blast_time_t *m_blast, struct timespec *m_ts)\n{\n /// Ensure that the nanoseconds fit into 32-bits first\n set_normalized_timespec(m_ts, m_ts->tv_sec, m_ts->tv_nsec);\n m_blast->timespec.seconds = m_ts->tv_sec;\n m_blast->timespec.nanoseconds = m_ts->tv_nsec;\n}\n#endif /* INCLUDE_BLAST_TIME_H_ */\n" }, { "alpha_fraction": 0.6804407835006714, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 17.615385055541992, "blob_id": "236f612ba5389443ba1fc987a0fdb7a296c20a6b", "content_id": "a1248f205e75b1a3dd6178a7d9a388bc3fb2e9ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 726, "license_type": "no_license", "max_line_length": 89, "num_lines": 39, "path": "/guaca/logscroll.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#ifndef LOGSCROLL_H\n#define LOGSCROLL_H\n\n#include <QProcess>\n#include <QDebug>\n#include <QWidget>\n#include <QSettings>\n\nnamespace Ui {\nclass Logscroll;\n}\n\nclass Logscroll : public QWidget\n{\n Q_OBJECT\n\npublic:\n explicit Logscroll(QWidget *parent = 0, QString cmd = \"\", bool save_position = true);\n QString get_latest_str();\n void startProcess();\n void stopProcess();\n bool doneProcess();\n ~Logscroll();\n\nprivate:\n QString cmdstring;\n Ui::Logscroll *ui;\n QProcess * process;\n QString latest_str;\n bool save_position;\n void closeEvent(QCloseEvent *event);\n void savePosition();\n\nprivate slots:\n void processStandardOutput();\n void processStandardError();\n};\n\n#endif // LOGSCROLL_H\n" }, { "alpha_fraction": 0.6509130001068115, "alphanum_fraction": 0.655209481716156, "avg_line_length": 17.6200008392334, "blob_id": "d4f95cb758aee3ebaf4f8851eb70deb238ca8064", "content_id": "88f7006984467cdf25c985303e59da78defb4033", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 932, "license_type": "no_license", "max_line_length": 84, "num_lines": 50, "path": "/stars/code/solving/refitting/shape_fitter.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__REFITTING__SHAPE_FITTER_H\n#define SOLVING__REFITTING__SHAPE_FITTER_H\n\n#include <vector>\n#include \"../blob.h\"\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n}\n\nnamespace Solving\n{\n namespace Refitting\n {\n class ShapeFitter;\n }\n}\n\nclass Solving::Refitting::ShapeFitter\n{\n public:\n ShapeFitter();\n ~ShapeFitter();\n double get_covar(int num_params, int param);\n void fit_gaussian(Shared::Image::Raw& image, std::vector<Solving::Blob>& blobs);\n\n private:\n int max_num_blobs;\n int max_num_pixels;\n double* pixels;\n int* us;\n int* vs;\n double* pedestals;\n unsigned int* which_blobs;\n double* workspace;\n double* covar;\n};\n\n#endif\n" }, { "alpha_fraction": 0.7130600810050964, "alphanum_fraction": 0.7168732285499573, "avg_line_length": 29.823530197143555, "blob_id": "301432898ecd7d9cf2b2cb337a51f86de7da81ef", "content_id": "90a826ee6cb89b054f13c2e8f2920a70ee84d03f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1050, "license_type": "no_license", "max_line_length": 100, "num_lines": 34, "path": "/stars/code/displaying/autofocus.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__AUTOFOCUS_H\n#define DISPLAYING__AUTOFOCUS_H\n\n#include \"block.h\"\n#include \"../shared/autofocus/datapoints.h\"\n\nnamespace Displaying\n{\n class Autofocus;\n}\n\nclass Displaying::Autofocus: public Displaying::Block\n{\n public:\n Autofocus();\n void update();\n bool display_enabled();\n void get_plot_ranges(double& value_min, double& value_max, double& focus_min, double& focus_max,\n Shared::Autofocus::datapoints_t metric_type, bool any_metric_except_sobel=false);\n void set_curve_color_and_width(Shared::Autofocus::datapoints_t metric_type);\n void plot_curves(double value_min, double value_max, double focus_min, double focus_max,\n double plot_offset, Shared::Autofocus::datapoints_t metric_type, double plot_width,\n double plot_height);\n void draw(Position& position);\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.6859999895095825, "alphanum_fraction": 0.6940000057220459, "avg_line_length": 15.666666984558105, "blob_id": "b89d38b71755103398fc14ec4d638d8b4e6dd0a2", "content_id": "c5d2eeff3c65b9749c416a259cd423fb8762ccc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 501, "license_type": "no_license", "max_line_length": 73, "num_lines": 30, "path": "/stars/code/shared/housekeeping/measurement.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__HOUSEKEEPING__MEASUREMENT_H\n#define SHARED__HOUSEKEEPING__MEASUREMENT_H\n\n#include <string>\n\nnamespace Shared\n{\n namespace Housekeeping\n {\n\nclass Measurement\n{\n public:\n std::string name;\n std::string units;\n double value;\n bool valid;\n};\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.6749688386917114, "alphanum_fraction": 0.6799501776695251, "avg_line_length": 18.119047164916992, "blob_id": "784222b03588106f1ab1e541f6766b254c0f274a", "content_id": "a1c56af62be2a6f35d9b4a0cdfcadc229a1d2529", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 804, "license_type": "no_license", "max_line_length": 73, "num_lines": 42, "path": "/stars/code/shared/image/blobs.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__IMAGE__BLOBS_H\n#define SHARED__IMAGE__BLOBS_H\n\n#include <vector>\n#include \"../circular_buffer.h\"\n#include \"../../solving/blob.h\"\n\nnamespace Shared\n{\n namespace Image\n {\n\nclass Blobs\n{\n public:\n Blobs();\n Blobs& operator=(const Blobs& rhs);\n void init(Parameters::Manager& params);\n\n int counter_stars;\n std::vector< ::Solving::Blob > blobs;\n};\n\n// writes: solver\n// reads: main\nextern Shared::CircularBufferPass <Blobs> blobs_solver_for_main;\n\n// writes: main\n// reads: network\nextern Shared::CircularBuffer <Blobs> blobs_main_for_net;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.6762790679931641, "alphanum_fraction": 0.6800000071525574, "avg_line_length": 23.43181800842285, "blob_id": "f8e64c653b4798f7f815846bfd3c2fbc702de8e0", "content_id": "56fbac36fa664ecf06729922345948afc41808ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1075, "license_type": "no_license", "max_line_length": 84, "num_lines": 44, "path": "/guaca/server.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include \"server.h\"\n\n// Starts a tcp server that sends config data to any client that connects\nServer::Server(QObject * parent) :\n QObject(parent)\n{\n // set up the server\n tcpserver = new QTcpServer();\n connect(tcpserver, SIGNAL(newConnection()), this, SLOT(sendServerData()));\n\n if (!tcpserver->listen(QHostAddress::Any, SLAVEPORT)) {\n qDebug() << \"Server could not start on port \" << QString::number(SLAVEPORT);\n }\n}\n\nServer::~Server() {\n if (tcpserver) delete tcpserver;\n}\n\nvoid Server::sendServerData() {\n // need to grab the socket\n QTcpSocket *socket = tcpserver->nextPendingConnection();\n if (!socket) return;\n\n // socket->write();\n\n socket->flush();\n socket->waitForBytesWritten(3000);\n\n socket->close();\n}\n\n/*\n * Connects to a server guaca and slaves to it by retrieving\n * the configuration file and applying those settings.\n * Configuration includes current state of mole options\n * as well as whether or not mole clients have been\n * initialized.\n */\n\nbool Server::getServerData(QString host)\n{\n return true;\n}\n" }, { "alpha_fraction": 0.7026049494743347, "alphanum_fraction": 0.7123733758926392, "avg_line_length": 27.79166603088379, "blob_id": "74c7a094193c9542461668966117deb51b589d84", "content_id": "60fee92eb684141e887a262263b933bdcfe5ecc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2764, "license_type": "no_license", "max_line_length": 79, "num_lines": 96, "path": "/owl/PBox.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include <QWidget>\n#include \"PObject.h\"\n#include \"PAbstractDataItem.h\"\n#include \"PNumberDataItem.h\"\n#include \"PBitMultiDataItem.h\"\n#include \"PMultiDataItem.h\"\n#include \"PStyle.h\"\n#include <QDataStream>\n#include <QDragEnterEvent>\n#include <QMap>\n#include <getdata/dirfile.h>\n\n#ifndef PBOX_H\n#define PBOX_H\n\nclass PBoxTitle;\n\nclass PBox : public QFrame, public PObject\n{\n Q_OBJECT\n PStyle* _pstyle;\n PStyle* _lastPStyle;\n QVBoxLayout* _layout;\n QString _boxTitle;\n PBoxTitle* _pbt;\n int _geoMode;\n friend class PBoxTitle;\n int _H;\n\npublic:\n bool _dirty;\n friend QDataStream& operator<<(QDataStream&a,PBox&b);\n friend QDataStream& operator>>(QDataStream&a,PBox&b);\n friend QVariant save(PBox&);\n friend void load(QVariant v,PBox&b);\n friend class PDotPal;\n friend class PMainWindow;\n\n QList<PAbstractDataItem*> _dataItems;\n PBox(QString boxTitle, const QFont &F, QWidget*p=0);\n ~PBox();\n const QString& boxTitle() const { return _boxTitle; }\n const PStyle* getStyle() const { return _pstyle; }\n\n int getWhereToInsert(QPoint p);\n\npublic slots:\n void setBoxTitle(const QString& boxTitle,bool force=0);\n void gdUpdate(GetData::Dirfile* dirFile,int lastNFrames);\n virtual void activate() { emit activated(); }\n void checkActivationState();\n void styleLogic();\n\nsignals:\n void textChanged(QString);\n\nprotected:\n void dragEnterEvent(QDragEnterEvent *ev);\n void dropEvent(QDropEvent *ev);\n void addProperty(QString property,int pos=-1);\n void addProperty(PAbstractDataItem* padi,int pos=-1);\n void addTitle(PBoxTitle* _pbt);\n void mousePressEvent(QMouseEvent *);\n void mouseReleaseEvent(QMouseEvent *);\n void mouseMoveEvent(QMouseEvent *);\n\nsignals:\n void activated();\n void newChild(PAbstractDataItem* padi);\n};\n\nQDataStream& operator<<(QDataStream&a,PBox&b);\nQDataStream& operator>>(QDataStream&a,PBox&b);\n\n#endif // PBOX_H\n" }, { "alpha_fraction": 0.6773566603660583, "alphanum_fraction": 0.6845480799674988, "avg_line_length": 30.55828285217285, "blob_id": "0248fe08cac5ddd6983275fd57e5fc95bb5222f4", "content_id": "613414578421e352520e5e5b38aeb79340a9afb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 5145, "license_type": "no_license", "max_line_length": 178, "num_lines": 163, "path": "/test_programs/mpsse/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "# Helper function to add preprocesor definition of FILE_BASENAME\n# to pass the filename without directory path for debugging use.\n#\n# Example:\n#\n# define_file_basename_for_sources(my_target)\n#\n# Will add -DFILE_BASENAME=\"filename\" for each source file depended on\n# by my_target, where filename is the name of the file.\n#\nfunction(define_file_basename_for_sources targetname)\n get_target_property(source_files \"${targetname}\" SOURCES)\n foreach(sourcefile ${source_files})\n # Get source file's current list of compile definitions.\n get_property(defs SOURCE \"${sourcefile}\"\n PROPERTY COMPILE_DEFINITIONS)\n # Add the FILE_BASENAME=filename compile definition to the list.\n get_filename_component(basename \"${sourcefile}\" NAME)\n list(APPEND defs \"__FILENAME__=\\\"${basename}\\\"\")\n # Set the updated compile definitions on the source file.\n set_property(\n SOURCE \"${sourcefile}\"\n PROPERTY COMPILE_DEFINITIONS ${defs})\n endforeach()\nendfunction()\n\nproject (test_biphase)\nproject (test_libusb)\n\ncmake_minimum_required (VERSION 2.8.8)\n\nSET (CMAKE_C_FLAGS \"-Wall -std=gnu99 -mcx16\")\nSET (CMAKE_C_FLAGS_DEBUG \"-O0 -fno-omit-frame-pointer -ggdb\")\nSET (CMAKE_C_FLAGS_MINSIZEREL \"-Os -DNDEBUG\")\nSET (CMAKE_C_FLAGS_RELEASE \"-O3 -DNDEBUG\")\nSET (CMAKE_C_FLAGS_RELWITHDEBINFO \"-O2 -g\")\n\nSET (CMAKE_CXX_FLAGS \"-Wall\")\nSET (CMAKE_CXX_FLAGS_DEBUG \"-g\")\nSET (CMAKE_CXX_FLAGS_MINSIZEREL \"-Os -DNDEBUG\")\nSET (CMAKE_CXX_FLAGS_RELEASE \"-O3 -DNDEBUG\")\nSET (CMAKE_CXX_FLAGS_RELWITHDEBINFO \"-O2 -g\") \n\n# Set global definitions\nadd_definitions(-D_GNU_SOURCE)\n\n# Find external libs\nfind_package(PkgConfig)\n\n# Find Threading lib\nfind_package (Threads REQUIRED)\nfind_package(OpenSSL REQUIRED)\n\n# Find ExternalProject module\ninclude (ExternalProject)\n\n# Used to check contents of header files\ninclude (CheckLibraryExists)\n\n\n# Find libusb \npkg_check_modules(PC_USB QUIET libusb-1.0)\nset(USB_DEFINITIONS ${PC_USB_CFLAGS_OTHER})\n\nfind_path(USB_INCLUDE_DIR libusb-1.0/libusb.h\n HINTS ${PC_USB_INCLUDEDIR} ${PC_USB_INCLUDE_DIRS}\n REQUIRED)\n\nfind_library(USB_LIBRARY NAMES usb-1.0 libusb-1.0\n HINTS ${PC_USB_LIBDIR} ${PC_USB_LIBRARY_DIRS} REQUIRED)\nIF(NOT USB_INCLUDE_DIR)\n MESSAGE(FATAL_ERROR \"Did not find libusb.h. Is libusb-1.0-0-dev installed?\")\nENDIF()\nIF(NOT USB_LIBRARY) \n MESSAGE(FATAL_ERROR \"Did not find libusb-1.0. Please install this using apt-get.\")\nENDIF()\ninclude_directories(${USB_INCLUDE_DIR})\n\n# configure a header file to pass some of the CMake settings to the source code\nconfigure_file (\n \"${PROJECT_SOURCE_DIR}/test_biphase_config.h.in\"\n \"${PROJECT_BINARY_DIR}/include/test_biphase_config.h\"\n )\n\n# add the binary tree to the search path for include files so that we will find test_biphase_config.h\ninclude_directories (\"${PROJECT_BINARY_DIR}\")\n\nset(COMMON_DIR \"${PROJECT_SOURCE_DIR}/../../common\")\nset(MPSSE_DIR \"${PROJECT_SOURCE_DIR}/../../external_libs/mpsse\")\n\ninclude_directories (\n \"${PROJECT_SOURCE_DIR}/include\"\n \"${COMMON_DIR}/include\"\n \"${MPSSE_DIR}\"\n )\n\n\n# add MPSSE Files\nadd_subdirectory(${MPSSE_DIR} \"${PROJECT_BINARY_DIR}/mpsse\")\n\nadd_library (mpsse OBJECT ${MPSSE_SRCS} ${MPSSE_HEADERS})\ndefine_file_basename_for_sources(mpsse)\n\n# add blast objects\nadd_library(blast_obj OBJECT \n ${COMMON_DIR}/blast.c \n ${COMMON_DIR}/include/blast.h\n )\ndefine_file_basename_for_sources(blast_obj)\n\n# add crc objects\nadd_library(crc_obj OBJECT \n ${COMMON_DIR}/crc.c \n ${COMMON_DIR}/include/crc.h\n )\ndefine_file_basename_for_sources(crc_obj)\n\t\nadd_executable (test_biphase \n test_biphase.c\n $<TARGET_OBJECTS:mpsse>\n $<TARGET_OBJECTS:blast_obj>\n $<TARGET_OBJECTS:crc_obj>\n ) \n\nadd_executable (test_libusb \n test_libusb.c\n $<TARGET_OBJECTS:mpsse>\n $<TARGET_OBJECTS:blast_obj>\n $<TARGET_OBJECTS:crc_obj>\n ) \n\ndefine_file_basename_for_sources(test_biphase)\ndefine_file_basename_for_sources(test_libusb)\n\ntarget_link_libraries(test_biphase \n ${USB_LIBRARY}\n ssl crypto \n m)\n\ntarget_link_libraries(test_libusb \n ${USB_LIBRARY}\n ssl crypto \n m)\n\n#set(check_files ${POINTING_SRCS} ${MOTOR_SRCS} \n#\t\t${SENSOR_SRCS} ${CMD_SRCS} ${MCP_COMMS_SRCS} ${HOUSEKEEPING_SRCS} \n#\t\t${FRAME_SRCS} ${MCP_COMMON_SRCS} ${COMMS_SRCS} ${ROACH_SRCS} \n#\t\tmcp.c tx.c\n#\t\t${POINTING_HEADERS} ${MOTOR_HEADERS} ${SENSOR_HEADERS} ${CMD_HEADERS} ${MCP_COMMS_HEADERS} \n#\t\t${HOUSEKEEPING_HEADERS} ${FRAME_HEADERS} ${MCP_COMMON_HEADERS} ${COMMS_HEADERS}\n#\t\t${ROACH_HEADERS}\n#\t ${PROJECT_SOURCE_DIR}/include/mcp.h\n#\t ${PROJECT_SOURCE_DIR}/include/tx.h\n#\t)\n#list(REMOVE_ITEM check_files ${PROJECT_SOURCE_DIR}/sensors/geomag2015.c ${PROJECT_SOURCE_DIR}/sensors/../include/geomag2015.h ${PROJECT_SOURCE_DIR}/sensors/../include/EGM9615.h)\n#string(REGEX REPLACE \"[ ]*[a-zA-Z/]*PMurHash.[ch][ ]*\" \" \" check_files \"${check_files}\")\n\n#add_custom_command(TARGET test_biphase PRE_BUILD\n#\tCOMMAND /bin/echo ${check_files}\n#\t#WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}\n#\tCOMMENT \"Checking Code Style\"\n#\tVERBATIM\n#\t)\n\n" }, { "alpha_fraction": 0.622519850730896, "alphanum_fraction": 0.632440447807312, "avg_line_length": 25.513158798217773, "blob_id": "efdb92c4cec46d9d961312db3d371a049b126fa5", "content_id": "14e7e55db8bc2db53285e47038419fae5c7018ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2017, "license_type": "no_license", "max_line_length": 104, "num_lines": 76, "path": "/stars/code/shared/solving/mask.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"mask.h\"\n#include <math.h>\n#include <boost/format.hpp>\n#include \"../../parameters/manager.h\"\n\nusing namespace Shared::Solving;\n\nMask::Mask()\n{\n enabled = false;\n counter = 0;\n for (int i=0; i<num_fields; i++) {\n fields[i] = 0;\n }\n\n block_size = 128; // needs to be an integer multiple of cell_size\n bits_per_word = 32;\n num_blocks_x = 0;\n num_blocks_y = 0;\n}\n\nvoid Mask::init(Parameters::Manager& params)\n{\n\tint image_height;\n\tint image_width;\n\n enabled = params.general.try_get(\"imaging.selective_mask.enabled\", false);\n for (int i=0; i<num_fields; i++) {\n fields[i] = params.general.try_get((boost::format(\"imaging.selective_mask.field%d\")%i).str(),\n (unsigned int) 0);\n }\n\timage_width = params.general.try_get(\"imaging.camera_real.image_width\", params.general.image_width);\n\timage_height = params.general.try_get(\"imaging.camera_real.image_height\", params.general.image_height);\n\n num_blocks_x = image_width / block_size;\n num_blocks_y = image_height / block_size;\n}\n\nMask& Mask::operator=(const Mask &rhs)\n{\n if (this != &rhs) {\n enabled = rhs.enabled;\n counter = rhs.counter;\n memcpy(fields, rhs.fields, sizeof(uint32_t)*num_fields);\n }\n return *this;\n}\n\nbool Mask::cell_masked(unsigned int corner_x, unsigned int corner_y)\n{\n if (!enabled) {\n return false;\n }\n return block_masked(corner_x/block_size, corner_y/block_size);\n}\n\nbool Mask::block_masked(unsigned int i, unsigned int j)\n{\n if (!enabled) {\n return false;\n }\n int n = j*num_blocks_x + i;\n int field_num = int(floor((double) n / (double) bits_per_word));\n int field_bit = n - field_num * bits_per_word;\n int value = (fields[field_num] >> field_bit) & 1;\n\tif (value == 1) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n" }, { "alpha_fraction": 0.6988071799278259, "alphanum_fraction": 0.7027832865715027, "avg_line_length": 21.863636016845703, "blob_id": "9959b74dae4a3dd402d2cfdaf15a9cda730e3b33", "content_id": "97e7ae22c75c5fccf50b7666a212cb3a725f6d07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1007, "license_type": "no_license", "max_line_length": 113, "num_lines": 44, "path": "/stars/code/solving/statistician.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVER__STATISTICIAN_H\n#define SOLVER__STATISTICIAN_H\n\n#include <vector>\n#include <algorithm>\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include \"../shared/image/raw.h\"\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Solving\n{\n class Statistician;\n}\n\nclass Solving::Statistician\n{\n public:\n Statistician(Parameters::Manager& params);\n void get_stats(Shared::Image::Raw& raw);\n void make_display_data(Shared::Image::Raw& raw);\n void print_stats();\n\n private:\n void get_cell_stats(Shared::Image::Raw& raw, int icell, int jcell, double& mean, double& stdev,\n int& num_saturated);\n void get_default_display_bounds(Shared::Image::Raw& raw, double& default_lower_bound, double& default_width);\n\n double saturation_limit;\n int cell_size;\n};\n\n#endif\n" }, { "alpha_fraction": 0.4954312741756439, "alphanum_fraction": 0.533331036567688, "avg_line_length": 27.07774543762207, "blob_id": "0952833f213d8512c9ab881cafb3814d61fb4595", "content_id": "07aed190a3f5ecb53aa47476020e6f7cc5bb9c17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 28892, "license_type": "no_license", "max_line_length": 79, "num_lines": 1029, "path": "/stars/code/tools/slalib.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "# include \"slalib.h\"\n\nnamespace Slalib\n{\n\n//-----------------------------------------------------------------------------\n// Routines lifted from SLALib\n\ndouble slaDranrm ( double angle )\n/*\n** - - - - - - - - - -\n** s l a D r a n r m\n** - - - - - - - - - -\n**\n** Normalize angle into range 0-2 pi.\n**\n** (double precision)\n**\n** Given:\n** angle double the angle in radians\n**\n** The result is angle expressed in the range 0-2 pi (double).\n**\n** Defined in slamac.h: D2PI, dmod\n**\n** Last revision: 19 March 1996\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n double w;\n\n w = dmod ( angle, D2PI );\n return ( w >= 0.0 ) ? w : w + D2PI;\n}\n\nfloat slaRanorm ( float angle )\n/*\n** - - - - - - - - - -\n** s l a R a n o r m\n** - - - - - - - - - -\n**\n** Normalize angle into range 0-2 pi.\n**\n** (single precision)\n**\n** Given:\n** angle double the angle in radians\n**\n** The result is angle expressed in the range 0-2 pi (single\n** precision).\n**\n** Last revision: 15 July 1993\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n return (float) slaDranrm ( (double) angle );\n}\n\nvoid slaTps2c ( double xi, double eta, double ra, double dec,\n double *raz1, double *decz1,\n double *raz2, double *decz2, int *n )\n/*\n** - - - - - - - - -\n** s l a T p s 2 c\n** - - - - - - - - -\n**\n** From the tangent plane coordinates of a star of known RA,Dec,\n** determine the RA,Dec of the tangent point.\n**\n** (single precision)\n**\n** Given:\n** xi,eta float tangent plane rectangular coordinates\n** ra,dec float spherical coordinates\n**\n** Returned:\n** *raz1,*decz1 float spherical coordinates of TP, solution 1\n** *raz2,*decz2 float spherical coordinates of TP, solution 2\n** *n int number of solutions:\n** 0 = no solutions returned (note 2)\n** 1 = only the first solution is useful (note 3)\n** 2 = both solutions are useful (note 3)\n**\n** Notes:\n**\n** 1 The raz1 and raz2 values are returned in the range 0-2pi.\n**\n** 2 Cases where there is no solution can only arise near the poles.\n** For example, it is clearly impossible for a star at the pole\n** itself to have a non-zero xi value, and hence it is\n** meaningless to ask where the tangent point would have to be\n** to bring about this combination of xi and dec.\n**\n** 3 Also near the poles, cases can arise where there are two useful\n** solutions. The argument n indicates whether the second of the\n** two solutions returned is useful; n=1 indicates only one useful\n** solution, the usual case; under these circumstances, the second\n** solution corresponds to the \"over-the-pole\" case, and this is\n** reflected in the values of raz2 and decz2 which are returned.\n**\n** 4 The decz1 and decz2 values are returned in the range +/-pi, but\n** in the usual, non-pole-crossing, case, the range is +/-pi/2.\n**\n** 5 This routine is the spherical equivalent of the routine slaTpv2c.\n**\n** Called: slaRanorm\n**\n** Last revision: 5 June 1995\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n double x2, y2, sd, cd, sdf, r2, r, s, c;\n\n x2 = xi * xi;\n y2 = eta * eta;\n sd = (double) sin ( (double) dec );\n cd = (double) cos ( (double) dec );\n sdf = sd * (double) sqrt ( (double) ( 1.0f + x2 + y2 ) );\n r2 = cd * cd * ( 1.0f + y2 ) - sd * sd * x2;\n if ( r2 >= 0.0f ) {\n r = (double) sqrt ( (double) r2 );\n s = sdf - eta * r;\n c = sdf * eta + r;\n if ( xi == 0.0f && r == 0.0f ) {\n r = 1.0f;\n }\n *raz1 = slaDranrm ( ra - (double) atan2 ( (double) xi, (double) r ) );\n *decz1 = (double) atan2 ( (double) s, (double) c );\n r = -r;\n s = sdf - eta * r;\n c = sdf * eta + r;\n *raz2 = slaDranrm ( ra - (double) atan2 ( (double) xi, (double) r ) );\n *decz2 = (double) atan2 ( (double) s, (double) c );\n *n = ( fabs ( (double) sdf ) < 1.0 ) ? 1 : 2;\n } else {\n *n = 0;\n }\n}\n\nvoid slaPrebn ( double bep0, double bep1, double rmatp[3][3] )\n/*\n** - - - - - - - - -\n** s l a P r e b n\n** - - - - - - - - -\n**\n** Generate the matrix of precession between two epochs,\n** using the old, pre-IAU1976, Bessel-Newcomb model, using\n** Kinoshita's formulation (double precision)\n**\n** Given:\n** BEP0 double beginning Besselian epoch\n** BEP1 double ending Besselian epoch\n**\n** Returned:\n** RMATP double[3][3] precession matrix\n**\n** The matrix is in the sense v(bep1) = rmatp * v(bep0)\n**\n** Reference:\n** Kinoshita, H. (1975) 'Formulas for precession', SAO Special\n** Report No. 364, Smithsonian Institution Astrophysical\n** Observatory, Cambridge, Massachusetts.\n**\n** Called: slaDeuler\n**\n** Defined in slamac.h: DAS2R\n**\n** Last revision: 30 October 1993\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n double bigt, t, tas2r, w, zeta, z, theta;\n\n/* Interval between basic epoch B1850.0 and beginning epoch in TC */\n bigt = ( bep0 - 1850.0 ) / 100.0;\n\n/* Interval over which precession required, in tropical centuries */\n t = ( bep1 - bep0 ) / 100.0;\n\n/* Euler angles */\n tas2r = t * DAS2R;\n w = 2303.5548 + ( 1.39720 + 0.000059 * bigt ) * bigt;\n zeta = (w + ( 0.30242 - 0.000269 * bigt + 0.017996 * t ) * t ) * tas2r;\n z = (w + ( 1.09478 + 0.000387 * bigt + 0.018324 * t ) * t ) * tas2r;\n theta = ( 2005.1125 + ( - 0.85294 - 0.000365* bigt ) * bigt +\n ( - 0.42647 - 0.000365 * bigt - 0.041802 * t ) * t ) * tas2r;\n\n/* Rotation matrix */\n char ZYZ[] = \"ZYZ\";\n slaDeuler ( ZYZ, -zeta, theta, -z, rmatp );\n}\n\n\nvoid slaDmxv ( double dm[3][3], double va[3], double vb[3] )\n/*\n** - - - - - - - -\n** s l a D m x v\n** - - - - - - - -\n**\n** Performs the 3-d forward unitary transformation:\n** vector vb = matrix dm * vector va\n**\n** (double precision)\n**\n** Given:\n** dm double[3][3] matrix\n** va double[3] vector\n**\n** Returned:\n** vb double[3] result vector\n**\n** Note: va and vb may be the same array.\n**\n** Last revision: 6 November 1999\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n int i, j;\n double w, vw[3];\n\n/* Matrix dm * vector va -> vector vw */\n for ( j = 0; j < 3; j++ ) {\n w = 0.0;\n for ( i = 0; i < 3; i++ ) {\n w += dm[j][i] * va[i];\n }\n vw[j] = w;\n }\n\n/* Vector vw -> vector vb */\n for ( j = 0; j < 3; j++ ) {\n vb[j] = vw[j];\n }\n}\n\nvoid slaDeuler ( char *order, double phi, double theta,\n double psi, double rmat[3][3] )\n/*\n** - - - - - - - - - -\n** s l a D e u l e r\n** - - - - - - - - - -\n**\n** Form a rotation matrix from the Euler angles - three successive\n** rotations about specified Cartesian axes.\n**\n** (double precision)\n**\n** Given:\n** *order char specifies about which axes the rotations occur\n** phi double 1st rotation (radians)\n** theta double 2nd rotation ( \" )\n** psi double 3rd rotation ( \" )\n**\n** Returned:\n** rmat double[3][3] rotation matrix\n**\n** A rotation is positive when the reference frame rotates\n** anticlockwise as seen looking towards the origin from the\n** positive region of the specified axis.\n**\n** The characters of order define which axes the three successive\n** rotations are about. A typical value is 'zxz', indicating that\n** rmat is to become the direction cosine matrix corresponding to\n** rotations of the reference frame through phi radians about the\n** old z-axis, followed by theta radians about the resulting x-axis,\n** then psi radians about the resulting z-axis.\n**\n** The axis names can be any of the following, in any order or\n** combination: x, y, z, uppercase or lowercase, 1, 2, 3. Normal\n** axis labelling/numbering conventions apply; the xyz (=123)\n** triad is right-handed. Thus, the 'zxz' example given above\n** could be written 'zxz' or '313' (or even 'zxz' or '3xz'). Order\n** is terminated by length or by the first unrecognized character.\n**\n** Fewer than three rotations are acceptable, in which case the later\n** angle arguments are ignored. Zero rotations leaves rmat set to the\n** identity matrix.\n**\n** Last revision: 9 December 1996\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n int j, i, l, n, k;\n double result[3][3], rotn[3][3], angle, s, c , w, wm[3][3];\n char axis;\n\n/* Initialize result matrix */\n for ( j = 0; j < 3; j++ ) {\n for ( i = 0; i < 3; i++ ) {\n result[i][j] = ( i == j ) ? 1.0 : 0.0;\n }\n }\n\n/* Establish length of axis string */\n l = strlen ( order );\n\n/* Look at each character of axis string until finished */\n for ( n = 0; n < 3; n++ ) {\n if ( n <= l ) {\n\n /* Initialize rotation matrix for the current rotation */\n for ( j = 0; j < 3; j++ ) {\n for ( i = 0; i < 3; i++ ) {\n rotn[i][j] = ( i == j ) ? 1.0 : 0.0;\n }\n }\n\n /* Pick up the appropriate Euler angle and take sine & cosine */\n switch ( n ) {\n case 0 :\n angle = phi;\n break;\n case 1 :\n angle = theta;\n break;\n default:\n angle = psi;\n break;\n }\n s = sin ( angle );\n c = cos ( angle );\n\n /* Identify the axis */\n axis = order[n];\n if ( ( axis == 'X' ) || ( axis == 'x' ) || ( axis == '1' ) ) {\n\n /* Matrix for x-rotation */\n rotn[1][1] = c;\n rotn[1][2] = s;\n rotn[2][1] = -s;\n rotn[2][2] = c;\n }\n else if ( ( axis == 'Y' ) || ( axis == 'y' ) || ( axis == '2' ) ) {\n\n /* Matrix for y-rotation */\n rotn[0][0] = c;\n rotn[0][2] = -s;\n rotn[2][0] = s;\n rotn[2][2] = c;\n }\n else if ( ( axis == 'Z' ) || ( axis == 'z' ) || ( axis == '3' ) ) {\n\n /* Matrix for z-rotation */\n rotn[0][0] = c;\n rotn[0][1] = s;\n rotn[1][0] = -s;\n rotn[1][1] = c;\n } else {\n\n /* Unrecognized character - fake end of string */\n l = 0;\n }\n\n /* Apply the current rotation (matrix rotn x matrix result) */\n for ( i = 0; i < 3; i++ ) {\n for ( j = 0; j < 3; j++ ) {\n w = 0.0;\n for ( k = 0; k < 3; k++ ) {\n w += rotn[i][k] * result[k][j];\n }\n wm[i][j] = w;\n }\n }\n for ( j = 0; j < 3; j++ ) {\n for ( i= 0; i < 3; i++ ) {\n result[i][j] = wm[i][j];\n }\n }\n }\n }\n\n/* Copy the result */\n for ( j = 0; j < 3; j++ ) {\n for ( i = 0; i < 3; i++ ) {\n rmat[i][j] = result[i][j];\n }\n }\n}\n\n\nvoid slaDcs2c ( double a, double b, double v[3] )\n/*\n** - - - - - - - - -\n** s l a D c s 2 c\n** - - - - - - - - -\n**\n** Spherical coordinates to direction cosines.\n**\n** (double precision)\n**\n** Given:\n** a,b double spherical coordinates in radians\n** (RA,Dec), (long,lat) etc\n**\n** Returned:\n** v double[3] x,y,z unit vector\n**\n** The spherical coordinates are longitude (+ve anticlockwise\n** looking from the +ve latitude pole) and latitude. The\n** Cartesian coordinates are right handed, with the x axis\n** at zero longitude and latitude, and the z axis at the\n** +ve latitude pole.\n**\n** Last revision: 31 October 1993\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n double cosb;\n\n cosb = cos ( b );\n v[0] = cos ( a ) * cosb;\n v[1] = sin ( a ) * cosb;\n v[2] = sin ( b );\n}\n\n\nvoid slaDcc2s ( double v[3], double *a, double *b )\n/*\n** - - - - - - - - -\n** s l a D c c 2 s\n** - - - - - - - - -\n**\n** Direction cosines to spherical coordinates.\n**\n** (double precision)\n**\n** Given:\n** v double[3] x,y,z vector\n**\n** Returned:\n** *a,*b double spherical coordinates in radians\n**\n** The spherical coordinates are longitude (+ve anticlockwise\n** looking from the +ve latitude pole) and latitude. The\n** Cartesian coordinates are right handed, with the x axis\n** at zero longitude and latitude, and the z axis at the\n** +ve latitude pole.\n**\n** If v is null, zero a and b are returned.\n** At either pole, zero a is returned.\n**\n** Last revision: 31 October 1993\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n double x, y, z, r;\n\n x = v[0];\n y = v[1];\n z = v[2];\n r = sqrt ( x * x + y * y );\n\n *a = ( r != 0.0 ) ? atan2 ( y, x ) : 0.0;\n *b = ( z != 0.0 ) ? atan2 ( z, r ) : 0.0;\n}\n\nvoid slaPrec ( double ep0, double ep1, double rmatp[3][3] )\n/*\n** - - - - - - - -\n** s l a P r e c\n** - - - - - - - -\n**\n** Form the matrix of precession between two epochs (IAU 1976, FK5).\n**\n** (double precision)\n**\n** Given:\n** ep0 double beginning epoch\n** ep1 double ending epoch\n**\n** Returned:\n** rmatp double[3][3] precession matrix\n**\n** Notes:\n**\n** 1) The epochs are TDB (loosely ET) Julian epochs.\n**\n** 2) The matrix is in the sense v(ep1) = rmatp * v(ep0) .\n**\n** 3) Though the matrix method itself is rigorous, the precession\n** angles are expressed through canonical polynomials which are\n** valid only for a limited time span. There are also known\n** errors in the IAU precession rate. The absolute accuracy\n** of the present formulation is better than 0.1 arcsec from\n** 1960AD to 2040AD, better than 1 arcsec from 1640AD to 2360AD,\n** and remains below 3 arcsec for the whole of the period\n** 500BC to 3000AD. The errors exceed 10 arcsec outside the\n** range 1200BC to 3900AD, exceed 100 arcsec outside 4200BC to\n** 5600AD and exceed 1000 arcsec outside 6800BC to 8200AD.\n** The SLALIB routine slaPrecl implements a more elaborate\n** model which is suitable for problems spanning several\n** thousand years.\n**\n** References:\n** Lieske,J.H., 1979. Astron. Astrophys.,73,282.\n** equations (6) & (7), p283.\n** Kaplan,G.H., 1981. USNO circular no. 163, pa2.\n**\n** Called: slaDeuler\n**\n** Defined in slamac.h: DAS2R\n**\n** Last revision: 10 July 1994\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n double t0, t, tas2r, w, zeta, z, theta;\n\n/* Interval between basic epoch J2000.0 and beginning epoch (JC) */\n t0 = ( ep0 - 2000.0 ) / 100.0;\n\n/* Interval over which precession required (JC) */\n t = ( ep1 - ep0 ) / 100.0;\n\n/* Euler angles */\n tas2r = t * DAS2R;\n w = 2306.2181 + ( ( 1.39656 - ( 0.000139 * t0 ) ) * t0 );\n zeta = (w + ( ( 0.30188 - 0.000344 * t0 ) + 0.017998 * t ) * t ) * tas2r;\n z = (w + ( ( 1.09468 + 0.000066 * t0 ) + 0.018203 * t ) * t ) * tas2r;\n theta = ( ( 2004.3109 + ( - 0.85330 - 0.000217 * t0 ) * t0 )\n + ( ( -0.42665 - 0.000217 * t0 ) - 0.041833 * t ) * t ) * tas2r;\n\n/* Rotation matrix */\n char ZYZ[] = \"ZYZ\";\n slaDeuler ( ZYZ, -zeta, theta, -z, rmatp );\n}\n\n\nvoid slaPreces ( char sys[3], double ep0, double ep1,\n double *ra, double *dc )\n/*\n** - - - - - - - - - -\n** s l a P r e c e s\n** - - - - - - - - - -\n**\n** Precession - either FK4 (Bessel-Newcomb, pre-IAU1976) or\n** FK5 (Fricke, post-IAU1976) as required.\n**\n** Given:\n** sys char[] precession to be applied: \"FK4\" or \"FK5\"\n** ep0,ep1 double starting and ending epoch\n** ra,dc double RA,Dec, mean equator & equinox of epoch ep0\n**\n** Returned:\n** *ra,*dc double RA,Dec, mean equator & equinox of epoch ep1\n**\n** Called: slaDranrm, slaPrebn, slaPrec, slaDcs2c,\n** slaDmxv, slaDcc2s\n**\n** Notes:\n**\n** 1) The epochs are Besselian if sys='FK4' and Julian if 'FK5'.\n** For example, to precess coordinates in the old system from\n** equinox 1900.0 to 1950.0 the call would be:\n** slaPreces ( \"FK4\", 1900.0, 1950.0, &ra, &dc )\n**\n** 2) This routine will not correctly convert between the old and\n** the new systems - for example conversion from B1950 to J2000.\n** For these purposes see slaFk425, slaFk524, slaFk45z and\n** slaFk54z.\n**\n** 3) If an invalid sys is supplied, values of -99.0,-99.0 will\n** be returned for both ra and dc.\n**\n** Last revision: 22 December 1993\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n double pm[3][3], v1[3], v2[3];\n\n/* Validate sys */\n if ( ( toupper ( sys[0] ) != 'F' )\n || ( toupper ( sys[1] ) != 'K' )\n || ( sys[2] != '4' && sys[2] != '5' ) ) {\n *ra = -99.0; /* Error */\n *dc = -99.0;\n } else {\n\n /* Generate appropriate precession matrix */\n if ( sys[2] == '4' )\n slaPrebn ( ep0, ep1, pm );\n else\n slaPrec ( ep0, ep1, pm );\n\n /* Convert RA,Dec to x,y,z */\n slaDcs2c ( *ra, *dc, v1 );\n\n /* Precess */\n slaDmxv ( pm, v1, v2 );\n\n /* Back to RA,Dec */\n slaDcc2s ( v2, ra, dc );\n *ra = slaDranrm ( *ra );\n }\n}\n\nvoid slaCaldj ( int iy, int im, int id, double *djm, int *j )\n/*\n** - - - - - - - - -\n** s l a C a l d j\n** - - - - - - - - -\n**\n** Gregorian calendar to Modified Julian Date.\n**\n** (Includes century default feature: use slaCldj for years\n** before 100AD.)\n**\n** Given:\n** iy,im,id int year, month, day in Gregorian calendar\n**\n** Returned:\n** *djm double Modified Julian Date (JD-2400000.5) for 0 hrs\n** *j int status:\n** 0 = ok\n** 1 = bad year (MJD not computed)\n** 2 = bad month (MJD not computed)\n** 3 = bad day (MJD computed)\n**\n** Acceptable years are 00-49, interpreted as 2000-2049,\n** 50-99, \" \" 1950-1999,\n** 100 upwards, interpreted literally.\n**\n** Called: slaCldj\n**\n** Last revision: 21 October 1993\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n int ny;\n\n/* Default century if appropriate */\n if ( ( iy >= 0 ) && ( iy <= 49 ) )\n ny = iy + 2000;\n else if ( ( iy >= 50 ) && ( iy <= 99 ) )\n ny = iy + 1900;\n else\n ny = iy;\n\n/* Modified Julian Date */\n slaCldj ( ny, im, id, djm, j );\n}\n\nvoid slaCldj ( int iy, int im, int id, double *djm, int *j )\n/*\n** - - - - - - - -\n** s l a C l d j\n** - - - - - - - -\n**\n** Gregorian calendar to Modified Julian Date.\n**\n** Given:\n** iy,im,id int year, month, day in Gregorian calendar\n**\n** Returned:\n** *djm double Modified Julian Date (JD-2400000.5) for 0 hrs\n** *j int status:\n** 0 = OK\n** 1 = bad year (MJD not computed)\n** 2 = bad month (MJD not computed)\n** 3 = bad day (MJD computed)\n**\n** The year must be -4699 (i.e. 4700BC) or later.\n**\n** The algorithm is derived from that of Hatcher 1984 (QJRAS 25, 53-55).\n**\n** Last revision: 29 August 1994\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n long iyL, imL;\n\n/* Month lengths in days */\n static int mtab[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n\n/* Validate year */\n if ( iy < -4699 ) { *j = 1; return; }\n\n/* Validate month */\n if ( ( im < 1 ) || ( im > 12 ) ) { *j = 2; return; }\n\n/* Allow for leap year */\n mtab[1] = ( ( ( iy % 4 ) == 0 ) &&\n ( ( ( iy % 100 ) != 0 ) || ( ( iy % 400 ) == 0 ) ) ) ?\n 29 : 28;\n\n/* Validate day */\n *j = ( id < 1 || id > mtab[im-1] ) ? 3 : 0;\n\n/* Lengthen year and month numbers to avoid overflow */\n iyL = (long) iy;\n imL = (long) im;\n\n/* Perform the conversion */\n *djm = (double)\n ( ( 1461L * ( iyL - ( 12L - imL ) / 10L + 4712L ) ) / 4L\n + ( 306L * ( ( imL + 9L ) % 12L ) + 5L ) / 10L\n - ( 3L * ( ( iyL - ( 12L - imL ) / 10L + 4900L ) / 100L ) ) / 4L\n + (long) id - 2399904L );\n}\n\ndouble slaEpj ( double date )\n/*\n** - - - - - - -\n** s l a E p j\n** - - - - - - -\n**\n** Conversion of Modified Julian Date to Julian epoch.\n**\n** (double precision)\n**\n** Given:\n** date double Modified Julian Date (JD - 2400000.5)\n**\n** The result is the Julian epoch.\n**\n** Reference:\n** Lieske,J.H., 1979. Astron. Astrophys.,73,282.\n**\n** Last revision: 31 October 1993\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n return 2000.0 + ( date - 51544.5 ) / 365.25;\n}\n\nvoid slaDtp2s ( double xi, double eta, double raz, double decz,\n double *ra, double *dec )\n/*\n** - - - - - - - - -\n** s l a D t p 2 s\n** - - - - - - - - -\n**\n** Transform tangent plane coordinates into spherical.\n**\n** (double precision)\n**\n** Given:\n** xi,eta double tangent plane rectangular coordinates\n** raz,decz double spherical coordinates of tangent point\n**\n** Returned:\n** *ra,*dec double spherical coordinates (0-2pi,+/-pi/2)\n**\n** Called: slaDranrm\n**\n** Last revision: 3 June 1995\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n double sdecz, cdecz, denom;\n\n sdecz = sin ( decz );\n cdecz = cos ( decz );\n denom = cdecz - eta * sdecz;\n *ra = slaDranrm ( atan2 ( xi, denom ) + raz );\n *dec = atan2 ( sdecz + eta * cdecz, sqrt ( xi * xi + denom * denom ) );\n}\n\n\nvoid slaDs2tp ( double ra, double dec, double raz, double decz,\n double *xi, double *eta, int *j )\n/*\n** - - - - - - - - -\n** s l a D s 2 t p\n** - - - - - - - - -\n**\n** Projection of spherical coordinates onto tangent plane\n** ('gnomonic' projection - 'standard coordinates').\n**\n** (double precision)\n**\n** Given:\n** ra,dec double spherical coordinates of point to be projected\n** raz,decz double spherical coordinates of tangent point\n**\n** Returned:\n** *xi,*eta double rectangular coordinates on tangent plane\n** *j int status: 0 = OK, star on tangent plane\n** 1 = error, star too far from axis\n** 2 = error, antistar on tangent plane\n** 3 = error, antistar too far from axis\n**\n** Last revision: 18 July 1996\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n#define TINY 1e-6\n{\n double sdecz, sdec, cdecz, cdec, radif, sradif, cradif, denom;\n\n\n/* Trig functions */\n sdecz = sin ( decz );\n sdec = sin ( dec );\n cdecz = cos ( decz );\n cdec = cos ( dec );\n radif = ra - raz;\n sradif = sin ( radif );\n cradif = cos ( radif );\n\n/* Reciprocal of star vector length to tangent plane */\n denom = sdec * sdecz + cdec * cdecz * cradif;\n\n/* Handle vectors too far from axis */\n if ( denom > TINY ) {\n *j = 0;\n } else if ( denom >= 0.0 ) {\n *j = 1;\n denom = TINY;\n } else if ( denom > -TINY ) {\n *j = 2;\n denom = -TINY;\n } else {\n *j = 3;\n }\n\n /* Compute tangent plane coordinates (even in dubious cases) */\n *xi = cdec * sradif / denom;\n *eta = ( sdec * cdecz - cdec * sdecz * cradif ) / denom;\n}\n\nvoid slaDh2e ( double az, double el, double phi, double *ha, double *dec )\n/*\n** - - - - - - - -\n** s l a D h 2 e\n** - - - - - - - -\n**\n** Horizon to equatorial coordinates: Az,El to HA,Dec\n**\n** (double precision)\n**\n** Given:\n** az double azimuth\n** el double elevation\n** phi double observatory latitude\n**\n** Returned:\n** *ha double hour angle\n** *dec double declination\n**\n** Notes:\n**\n** 1) All the arguments are angles in radians.\n**\n** 2) The sign convention for azimuth is north zero, east +pi/2.\n**\n** 3) HA is returned in the range +/-pi. Declination is returned\n** in the range +/-pi/2.\n**\n** 4) The is latitude is (in principle) geodetic. In critical\n** applications, corrections for polar motion should be applied.\n**\n** 5) In some applications it will be important to specify the\n** correct type of elevation in order to produce the required\n** type of HA,Dec. In particular, it may be important to\n** distinguish between the elevation as affected by refraction,\n** which will yield the \"observed\" HA,Dec, and the elevation\n** in vacuo, which will yield the \"topocentric\" HA,Dec. If the\n** effects of diurnal aberration can be neglected, the\n** topocentric HA,Dec may be used as an approximation to the\n** \"apparent\" HA,Dec.\n**\n** 6) No range checking of arguments is done.\n**\n** 7) In applications which involve many such calculations, rather\n** than calling the present routine it will be more efficient to\n** use inline code, having previously computed fixed terms such\n** as sine and cosine of latitude.\n**\n** Last revision: 21 February 1996\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n double sa, ca, se, ce, sp, cp, x, y, z, r;\n\n/* Useful trig functions */\n sa = sin ( az );\n ca = cos ( az );\n se = sin ( el );\n ce = cos ( el );\n sp = sin ( phi );\n cp = cos ( phi );\n\n/* HA,Dec as x,y,z */\n x = - ca * ce * sp + se * cp;\n y = - sa * ce;\n z = ca * ce * cp + se * sp;\n\n/* To spherical */\n r = sqrt ( x * x + y * y );\n *ha = ( r == 0.0 ) ? 0.0 : atan2 ( y, x ) ;\n *dec = atan2 ( z, r );\n}\n\nvoid slaDe2h ( double ha, double dec, double phi, double *az, double *el )\n/*\n** - - - - - - - -\n** s l a D e 2 h\n** - - - - - - - -\n**\n** Equatorial to horizon coordinates: HA,Dec to Az,El\n**\n** (double precision)\n**\n** Given:\n** ha double hour angle\n** dec double declination\n** phi double observatory latitude\n**\n** Returned:\n** *az double azimuth\n** *el double elevation\n**\n** Notes:\n**\n** 1) All the arguments are angles in radians.\n**\n** 2) Azimuth is returned in the range 0-2pi; north is zero,\n** and east is +pi/2. Elevation is returned in the range\n** +/-pi/2.\n**\n** 3) The latitude must be geodetic. In critical applications,\n** corrections for polar motion should be applied.\n**\n** 4) In some applications it will be important to specify the\n** correct type of hour angle and declination in order to\n** produce the required type of azimuth and elevation. In\n** particular, it may be important to distinguish between\n** elevation as affected by refraction, which would\n** require the \"observed\" HA,Dec, and the elevation\n** in vacuo, which would require the \"topocentric\" HA,Dec.\n** If the effects of diurnal aberration can be neglected, the\n** \"apparent\" HA,Dec may be used instead of the topocentric\n** HA,Dec.\n**\n** 5) No range checking of arguments is carried out.\n**\n** 6) In applications which involve many such calculations, rather\n** than calling the present routine it will be more efficient to\n** use inline code, having previously computed fixed terms such\n** as sine and cosine of latitude, and (for tracking a star)\n** sine and cosine of declination.\n**\n** Defined in slamac.h: D2PI\n**\n** Last revision: 10 July 1994\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n double sh, ch, sd, cd, sp, cp, x, y, z, r, a;\n\n/* Useful trig functions */\n sh = sin ( ha );\n ch = cos ( ha );\n sd = sin ( dec );\n cd = cos ( dec );\n sp = sin ( phi );\n cp = cos ( phi );\n\n/* Az,El as x,y,z */\n x = - ch * cd * sp + sd * cp;\n y = - sh * cd;\n z = ch * cd * cp + sd * sp;\n\n/* To spherical */\n r = sqrt ( x * x + y * y );\n a = ( r == 0.0 ) ? 0.0 : atan2 ( y, x ) ;\n *az = ( a < 0.0 ) ? a + D2PI : a;\n *el = atan2 ( z, r );\n}\n\ndouble slaPa ( double ha, double dec, double phi )\n/*+\n** - - - - - -\n** s l a P a\n** - - - - - -\n**\n** HA, Dec to Parallactic Angle.\n**\n** (double precision)\n**\n** Given:\n** ha d hour angle in radians (geocentric apparent)\n** dec d declination in radians (geocentric apparent)\n** phi d observatory latitude in radians (geodetic)\n**\n** The result is in the range -pi to +pi\n**\n** Notes:\n**\n** 1) The parallactic angle at a point in the sky is the position\n** angle of the vertical, i.e. the angle between the direction to\n** the pole and to the zenith. In precise applications care must\n** be taken only to use geocentric apparent HA,Dec and to consider\n** separately the effects of atmospheric refraction and telescope\n** mount errors.\n**\n** 2) At the pole a zero result is returned.\n**\n** Last revision: 16 August 1994\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n{\n double cp, cqsz, sqsz;\n\n cp = cos ( phi );\n sqsz = cp * sin ( ha );\n cqsz = sin ( phi ) * cos ( dec) - cp * sin ( dec) * cos ( ha );\n return ( ( sqsz != 0.0 || cqsz != 0.0 ) ? atan2 ( sqsz, cqsz ) : 0.0 );\n}\n\n}\n" }, { "alpha_fraction": 0.6953312754631042, "alphanum_fraction": 0.7064881324768066, "avg_line_length": 35.753944396972656, "blob_id": "9e268c4021f8fcf9a771e5e1d33ca50071e17b55", "content_id": "9a5aceca3530fc32995b3e88b0f7883164321723", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11652, "license_type": "no_license", "max_line_length": 102, "num_lines": 317, "path": "/starcam/commandgui.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include \"commandgui.h\"\n#include <string>\n#include <sstream>\n#include <qlabel.h>\n#include <qlistbox.h>\n#include <qlineedit.h>\n#include <qtextedit.h>\n#include <qpushbutton.h>\n#include <qlayout.h>\n#include \"camcommunicator.h\"\n#include \"camconfig.h\"\n\n#define COMMAND_DEBUG 0\n#if COMMAND_DEBUG\n#include <iostream>\nusing namespace std;\n#endif\n\n//definitions of string arrays for use in the GUI\n//to add a command, it must appear in interpretCommand in starcam.cpp\n//to use it in this GUI, add it to the three lists below, and to the enum in header\n//(NB: it must appear in the same location in all lists)\n//Finally, the list entry must be added in the constructor\n//Yes, I know this is a lot to ask, this system is not perfectly designed\n\n//command strings as recognized by the star camera\nconst QString CameraCmdStrs[] = { \"CtrigExp\", \"CtrigFocus\", \"CtrigFocusF\", \"CsetExpTime\",\n\t\"CsetExpInt\", \"CsetFocRsln\", \"Cpower\" };\nconst QString ImageCmdStrs[] = { \"IsetBadpix\", \"IsetMaxBlobs\", \"IsetGrid\",\n\t\"IsetThreshold\", \"IsetDisttol\" };\nconst QString LensCmdStrs[] = { \"Lmove\", \"Lforce\", \"LsetTol\", \"L\" };\nconst QString OverCmdStrs[] = { \"Oconf\", \"OshowBox\" };\n\t\n//descriptions of star camera commands\nconst QString CameraCmdDescs[] = { \"Triggers camera exposure (if in triggered mode)\",\n\t\"Triggers camera autofocus (takes a couple of minutes)\",\n\t\"Triggers camera autofocus; forced moves (takes a couple of minutes)\",\n\t\"Sets duration of exposures\", \"Sets interval between exposures\",\n\t\"Sets the resolution (step size) for autofocus\",\n\t\"Power cycles the star cameras\"\n};\nconst QString ImageCmdDescs[] = { \"Identifies a bad pixel on CCD, will be set to map mean\",\n\t\"Sets maximum number of blobs to identify per image\",\n\t\"Sets the grid size for blob finding\",\n\t\"Sets the #-sigma threshold for a blob to be considered a star\",\n\t\"Sets the closest two stars can be together to be identified as distinct\"\n};\nconst QString LensCmdDescs[] = { \"Makes a precise move of the lens (proportional feedback)\",\n\t\"Similar to move, except ignores lens stops (which may be false when cold)\",\n\t\"Sets allowable miss tolerance of precise moves\",\n\t\"Execute an arbitrary command recognized by the lens adapter\"\n};\nconst QString OverCmdDescs[] = { \"Sends a request for configuration state data\",\n\t\"Toggle whether boxes are drawn in the image viewer images\"\n};\n\n//descriptions of the value needed for the command, \"\" for no value\nconst QString CameraValDescs[] = { \"\", \"\", \"\", \"(double) Exposure duration in ms (default: 100)\",\n\t\"(int) interval between exposures in ms, 0 indicates triggered-mode (default: 0)\",\n\t\"(int) number of steps in total focal range during autofocus (default: 100)\",\n\t\"\"\n};\nconst QString ImageValDescs[] = { \n\t\"(space-separated ints) <cam #> <x> <y> (\\\"0 0\\\" is top left)\",\n\t\"(int) maximum number of blobs (default: 99)\",\n\t\"(int) size of grid square in pixels (default: 20)\",\n\t\"(double) number of standard deviation above mean flux (default: 5.0)\",\n\t\"(int) square of minimum pixel distance between two blobs (default: 400)\"\n};\nconst QString LensValDescs[] = { \"(int) motor counts to move by (total range ~2100)\",\n\t\"(int) motor counts to move by (total range ~2100)\",\n\t\"(int) motor counts away from ideal location allowed (default: 1)\",\n\t\"(string) any command recognized by the lens adapter\"\n};\nconst QString OverValDescs[] = { \"\",\n\t\"(int/bool) evaluates to 'true' means boxes are on\"\n};\n\n\n\nCommandGUI::CommandGUI(QWidget *parent, const char *name, const char* commTarget /*=\"aragog.spider\"*/)\n : QWidget(parent, name)\n{\n\tcommand = new QLabel(CameraCmdStrs[TrigExp], this, \"command\");\n\tcommand->setFont(QFont(\"Arial\", 10, QFont::Bold));\n\tdescription = new QLabel(CameraCmdDescs[TrigExp], this, \"description\");\n\tdescription->setFont(QFont(\"Arial\", 10, QFont::Bold));\n\t\n\tvalDesc = new QLabel(\"\", this, \"description\");\n\tvalDesc->setFont(QFont(\"Arial\", 10, QFont::Bold));\n\tvalDesc->setAlignment(Qt::AlignTop | Qt::AlignLeft | Qt::WordBreak);\n\tvalDesc->setMinimumSize(150,50);\t\n\tvalue = new QLineEdit(this, \"value\");\n\tvalue->hide();\n\tvalue->setMinimumWidth(140);\n\tconnect(value, SIGNAL(textChanged(const QString&)), this, SLOT(valueChanged(const QString&)));\n\tvalLabel = new QLabel(\"Value:\", this, \"vallabel\");\n\tvalLabel->setFont(QFont(\"Arial\", 12, QFont::Bold));\n\tvalLabel->setMinimumSize(valLabel->sizeHint());\n\tvalLabel->hide();\n\n\tdeviceBox = new QListBox(this, \"deviceBox\");\n\tdeviceBox->insertItem(\"Camera Commands\", Camera);\n\tdeviceBox->insertItem(\"Image Commands\", Image);\n\tdeviceBox->insertItem(\"Lens Commands\", Lens);\n\tdeviceBox->insertItem(\"Overall Commands\", Overall);\n\tdeviceBox->setSelected(Camera, TRUE);\n\tdeviceBox->setMinimumSize(150,100);\n\tconnect(deviceBox, SIGNAL(highlighted(int)), this, SLOT(deviceSelected(int)));\n\t\n\tcamCmds = new QListBox(this, \"camCmds\");\n\tcamCmds->insertItem(CameraCmdStrs[TrigExp], TrigExp);\n\tcamCmds->insertItem(CameraCmdStrs[TrigFocus], TrigFocus);\n\tcamCmds->insertItem(CameraCmdStrs[TrigFocusF], TrigFocusF);\n\tcamCmds->insertItem(CameraCmdStrs[SetExpTime], SetExpTime);\n\tcamCmds->insertItem(CameraCmdStrs[SetExpInt], SetExpInt);\n\tcamCmds->insertItem(CameraCmdStrs[SetFocRsln], SetFocRsln);\n\tcamCmds->insertItem(CameraCmdStrs[Power], Power);\n\tcamCmds->setSelected(TrigExp, TRUE);\n\tcamCmds->setMinimumSize(150,100);\n\tconnect(camCmds, SIGNAL(highlighted(int)), this, SLOT(commandSelected(int)));\n\n\timgCmds = new QListBox(this, \"imgCmds\");\n\timgCmds->insertItem(ImageCmdStrs[SetBadpix], SetBadpix);\n\timgCmds->insertItem(ImageCmdStrs[SetMaxBlobs], SetMaxBlobs);\n\timgCmds->insertItem(ImageCmdStrs[SetGrid], SetGrid);\n\timgCmds->insertItem(ImageCmdStrs[SetThreshold], SetThreshold);\n\timgCmds->insertItem(ImageCmdStrs[SetDisttol], SetDisttol);\n\timgCmds->setSelected(SetBadpix, TRUE);\n\timgCmds->setMinimumSize(150,100);\n\tconnect(imgCmds, SIGNAL(highlighted(int)), this, SLOT(commandSelected(int)));\n\t\n\tlensCmds = new QListBox(this, \"lensCmds\");\n\tlensCmds->insertItem(LensCmdStrs[Move], Move);\n\tlensCmds->insertItem(LensCmdStrs[Force], Force);\n\tlensCmds->insertItem(LensCmdStrs[SetTol], SetTol);\n\tlensCmds->insertItem(LensCmdStrs[Other], Other);\n\tlensCmds->setSelected(Move, TRUE);\n\tlensCmds->setMinimumSize(150,100);\n\tconnect(lensCmds, SIGNAL(highlighted(int)), this, SLOT(commandSelected(int)));\n\t\n\toverCmds = new QListBox(this, \"overCmds\");\n\toverCmds->insertItem(OverCmdStrs[Conf], Conf);\n\toverCmds->insertItem(OverCmdStrs[showBox], showBox);\n\toverCmds->setSelected(Move, TRUE);\n\toverCmds->setMinimumSize(150,100);\n\tconnect(overCmds, SIGNAL(highlighted(int)), this, SLOT(commandSelected(int)));\n\t\n\treturnPane = new QTextEdit(this, \"returnPane\");\n\treturnPane->setTextFormat(LogText);\n\treturnPane->setMinimumHeight(150);\n\t\n\tQVBoxLayout *vl = new QVBoxLayout(this, 0, 1, \"vlayout\");\n\t\n\tQHBoxLayout *hl = new QHBoxLayout(vl, 2, \"choicelayout\");\n\thl->addWidget(deviceBox, 1);\t\n\tQGridLayout *gl = new QGridLayout(hl, 1, 1, -1, \"singlegrid\");\n\tgl->addWidget(camCmds, 0, 0);\n\tgl->addWidget(imgCmds, 0, 0);\n\tgl->addWidget(lensCmds, 0, 0);\n\tgl->addWidget(overCmds, 0, 0);\n\tcamCmds->raise(); //show camera commands by default\n\tcamCmds->setFocus();\n\tdeviceIndex = (int)Camera;\n\tcurrentCmds = camCmds;\n\tcommandIndex = (int)TrigExp;\n\thl->setStretchFactor(gl, 1);\n\tQVBoxLayout *vl2 = new QVBoxLayout(hl, 2, \"vallayout\");\n\tvl2->addWidget(valLabel,0);\n\tvl2->addWidget(value,0);\n\tvl2->addWidget(valDesc,0);\n\tvl2->addStretch(1);\n\thl->setStretchFactor(vl2, 10);\n\tvl->setStretchFactor(hl, 1);\n\t\n\thl = new QHBoxLayout(vl, 2, \"cmdlayout\");\n\tQLabel *label = new QLabel(\"Command:\", this, \"cmdlabel\");\n\tlabel->setFont(QFont(\"Arial\", 12, QFont::Bold));\n\thl->addWidget(label, 0);\n\thl->addWidget(command, 1, Qt::AlignLeft | Qt::AlignVCenter);\n\tQPushButton *button = new QPushButton(\"Send\", this, \"sendbutton\");\n\tconnect(button, SIGNAL(pressed()), this, SLOT(sendCommand()));\n\thl->addWidget(button, 0);\n\tvl->setStretchFactor(hl, 0);\n\t\n\tvl->addWidget(description, 0);\n\t\n\tvl->addWidget(returnPane, 2);\n\t\n\tif (comm.openClient(commTarget) < 0) {\n#if COMMAND_DEBUG\n\t\tcerr << \"[CommandGUI debug]: error opening communications client\" << endl;\n#endif\n\t}\n\tkeepReading = TRUE;\n\treader.setCommander(this);\n\treader.start();\n\t\n}\n\nvoid CommandGUI::deviceSelected(int device)\n{\n#if COMMAND_DEBUG\n\tcerr << \"[CommandGUI debug]: selected device number: \" << device << endl;\n#endif\n\tif (device == deviceIndex) return; //only do stuff on change\n\tdeviceIndex = device;\n\tcurrentCmds = (device == Camera)?camCmds:(device == Image)?imgCmds:\n\t (device == Lens)?lensCmds:overCmds;\n\tcurrentCmds->raise();\n\tcurrentCmds->setFocus();\n\tint idx = currentCmds->index(currentCmds->selectedItem());\n\tif (idx == -1) return; //this not expected to occur\n\tcommandIndex = -1; //ensures that changes are made in commandSelected call\t\n\tcommandSelected(idx);\n}\n\nvoid CommandGUI::commandSelected(int cmd)\n{\n#if COMMAND_DEBUG\n\tcerr << \"[CommandGUI debug]: selected command number: \" << cmd << endl;\n#endif\n\tif (cmd == commandIndex) return;\n\tcommandIndex = cmd;\n\tcommand->setText(currentCmds->selectedItem()->text());\n\tconst QString* cmdDescArray = (deviceIndex == Camera)?CameraCmdDescs:\n\t\t\t(deviceIndex == Image)?ImageCmdDescs:\n\t\t\t(deviceIndex == Lens)?LensCmdDescs:OverCmdDescs;\n\tdescription->setText(cmdDescArray[cmd]);\n\tconst QString* valDescArray = (deviceIndex == Camera)?CameraValDescs:\n\t\t\t(deviceIndex == Image)?ImageValDescs:\n\t\t\t(deviceIndex == Lens)?LensValDescs:OverValDescs;\n\tif (valDescArray[cmd][0] == '\\0') { //val with no description means no value\n\t\tvalDesc->hide();\n\t\tvalue->hide();\n\t\tvalLabel->hide();\n\t} else {\n\t\tvalDesc->show();\n\t\tvalDesc->setText(valDescArray[cmd]);\n\t\tvalue->show();\n\t\tvalue->setText(\"\");\n\t\tvalLabel->show();\n\t}\n}\n\nvoid CommandGUI::valueChanged(const QString&)\n{\n#if COMMAND_DEBUG\n\tcerr << \"[CommandGUI debug]: value changed\" << endl;\n#endif\n\tQString str = currentCmds->selectedItem()->text();\n\tstr += \"=\";\n\tstr += value->text();\n\tcommand->setText(str);\n}\n\nvoid CommandGUI::sendCommand()\n{\n#if COMMAND_DEBUG\n\tcerr << \"[CommandGUI debug]: sending a command\" << endl;\n#endif\n\tQString str = \"Sending the command: \";\n\tstr += command->text();\n\treturnPane->append(str);\n\t\n\tcomm.sendCommand(command->text().ascii());\n}\n\n//appends a return value to returnPane, str should be exactly as read\nvoid CommandGUI::showReturnVal(QString &str)\n{\n\tif (str.find(\"<str>\") == 0) {\n\t\tstr = str.remove(\"<str>\");\n\t\tstr = str.remove(\"</str>\");\n\t\treturnPane->append(\"Obtained return string: \" + str);\n\t} else {\n\t\tStarcamReturn rtn;\n\t\tCamCommunicator::interpretReturn((string)str.ascii(), &rtn);\n\t\tostringstream sout;\n\t\tsout << \"\\n\\nObtained a picture return signal from camera #\" << rtn.camID << \"\\n\"\n\t\t\t << \"... mapmean =\" << rtn.mapmean << \"\\n\"\n\t\t\t << \"... sigma=\" << rtn.sigma << \"\\n\"\n\t\t\t << \"... exposuretime=\" << rtn.exposuretime << \"\\n\"\n\t\t\t << \"... imagestarttime=\" << rtn.imagestarttime.tv_sec << \"s \" \n\t\t\t\t << rtn.imagestarttime.tv_usec << \"us\\n\"\n\t\t\t << \"... ccdtemperature=\" << rtn.ccdtemperature << \"\\n\"\n\t\t\t << \"... focusposition=\" << rtn.focusposition << \"\\n\"\n\t\t\t << \"... numblobs=\" << rtn.numblobs;\n\t\treturnPane->append(sout.str().c_str());\n\t}\n}\n\n//destructor: causes read thread to end\nCommandGUI::~CommandGUI()\n{\n\tkeepReading = FALSE;\n\treader.terminate();\n}\n\n//\"infinite\" loop to run in another thread and read responses\nvoid ReadThread::run()\n{\n\tif (commander == NULL) return;\n\tstring line = \"\";\n\tQString qline;\n\tstring::size_type pos;\n\twhile (commander->keepReading) {\n\t\tmsleep(500);\n\t\tline += commander->comm.looplessRead();\n\t\twhile ((pos = line.find(\"\\n\",0)) != string::npos) {\n\t\t\tqline = line.substr(0,pos).c_str();\n\t\t\tcommander->showReturnVal(qline);\n\t\t\tline = line.substr(pos+1, line.length()-(pos+1)); //set line to text after \"\\n\"\n\t\t}\n\n\t}\n}\n\n" }, { "alpha_fraction": 0.7071651220321655, "alphanum_fraction": 0.7133956551551819, "avg_line_length": 21.13793182373047, "blob_id": "9d479f1e16d2f568cc58a5dc3e9b987febcda9b2", "content_id": "cfea4f36a78c0c4aaa04063bb03281d2fe89f264", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 643, "license_type": "no_license", "max_line_length": 99, "num_lines": 29, "path": "/stars/code/networking/server.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef NETWORKING__SERVER_H\n#define NETWORKING__SERVER_H\n\n#include <boost/asio.hpp>\n#include \"connection.h\"\n\nnamespace Networking\n{\n class Server;\n}\n\nclass Networking::Server\n{\n public:\n Server(boost::asio::io_service& io_service, int port);\n void start_accept();\n void handle_accept(Connection::pointer new_connection, const boost::system::error_code& error);\n\n boost::asio::ip::tcp::acceptor acceptor;\n};\n\n#endif\n" }, { "alpha_fraction": 0.5099368691444397, "alphanum_fraction": 0.5555295944213867, "avg_line_length": 34.94117736816406, "blob_id": "3b1afb1ed791836690fd0981c5398b95d64aa9be", "content_id": "90d5accd1cf96c1c1a46f41d326b18ad0cc745b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4277, "license_type": "no_license", "max_line_length": 80, "num_lines": 119, "path": "/sedpy/lineparser.py", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#!/usr/bin/env /usr/bin/python\n\nimport re\nfrom sedobjects import *\n\n#LABEL -> MATE pins \"description\" [alpha] [bcd] [M-Mmate] [F-Fmate]\nconnRE = re.compile(r'^'\n r'([A-Z0-9_]{1,16})\\s+->\\s+' #LABEL\n r'([A-Z0-9_]{1,16})\\s+'\t #MATE\n r'(\\d{1,3})\\s+'\t\t #pins\n r'\"([^\"]{1,255})\"'\t\t #description\n r'(?:\\s*(alpha))?'\t\t #alpha\n r'(?:\\s*(bcd))?'\t\t #bcd\n r'(?:\\s+M-([mMfF]))?'\t #mmate\n r'(?:\\s+F-([mMfF]))?'\t #fmate\n r'$')\n\n#CMPNAME \"Description of the COMPONENT\" [< PARTOF]\ncompRE = re.compile(r'^'\n r'([A-Z_][A-Z0-9_]{0,7})\\s+' #CMPNAME\n r'\"([^\"]{1,65})\"'\t\t #description\n r'(?:\\s+<\\s+([A-Z0-9_]{1,8}))?' #PARTOF\n r'$')\n\n#JACK [IN] [&]ref \"label\" CONN/G -> DEST[/jack] [CABLE [&C##] \"[desc]\" [len]]\njackRE = re.compile(r'^JACK'\n '(?:\\s*(IN))?\\s+'\t\t\t#IN\n r'((?:&J?\\d{1,5})|[a-z0-9]+)\\s+'\t#ref\n r'\"([^\"]{1,32})\"\\s+'\t\t#label\n r'([A-Z0-9_]{1,16}/[mMfF])\\s+->\\s+'\t#CONN/G\n r'(&?[A-Z0-9_]{1,8})'\t\t#DEST\n r'(?:/((?:&J?\\d{1,5})|[a-z0-9]+))?'\t#/jack\n r'(?:\\s+CABLE'\t\t\t#CABLE\n r'(?:\\s+(&C?[0-9]{1,8}))?\\s+'\t# &C##\n r'\"([^\"]{0,64})\"'\t\t\t# desc\n r'(?:\\s+(\\d+))?'\t\t\t# len\n r')?$')\n\n#LINE \"description\" (jack;pin[,pin2,...])[,(jack;pin[,pin2,...]), ...]\nlineRE = re.compile(r'^LINE\\s+'\n r'\"([^\"]{1,64})\"\\s+'\t\t #description\n r'((?:'\n r'\\((?:(?:&J?\\d{1,5})|[a-z0-9]+)[;,]' #jack\n r'(?:\\s*[A-Za-z0-9]{1,3},?)*\\),?\\s*' #pin\n r')+)$')\n\n#CABLE [&]C## \"description\" [len]\ncableRE = re.compile(r'^CABLE\\s+'\n r'(&?C?[0-9]{1,8})\\s+' #C##\n r'\"([^\"]{1,64})\"'\t #description\n r'(?:\\s+([0-9]+))?'\t #len\n r'$')\n\n#lookup table of regular expressions corresponding to object classes\nRElookup = {Connector: connRE, Component: compRE, Jack: jackRE, \n Line: lineRE, Cable: cableRE}\n\ndef parse(type, line):\n \"\"\"parses the string: line into an object of class: type and returns it\"\"\"\n match = RElookup[type].match(line)\n if match:\n return type(*match.groups())\n else:\n return None\n\n\nif __name__ == \"__main__\":\n print \"\\nCONNECTOR tests\"\n conn1 = ('TYPE -> MATE 10 \"TYPE has 10 male pins that go with female MATE\" '\n 'alpha bcd M-F')\n conn2 = 'CONN -> CONN 0 \"A connector with variable num of pins\" alpha F-F'\n conn3 = 'COMM -> COMM 0 \"A connector with non-alphanumeric pins\" F-F'\n conn4 = 'TEST -> TEST 10 \"A connector to test jack mating\" M-F F-M'\n print (conn1), '\\n', parse(Connector,conn1)\n print (conn2), '\\n', parse(Connector, conn2)\n print (conn3), '\\n', parse(Connector, conn3)\n test_connector = parse(Connector, conn4)\n test_connector.mate = test_connector\n print (conn4), '\\n', test_connector\n\n print \"\\nCOMPONENT tests\"\n comp1 = 'COMPA \"COMPA is part of COMP1\" < COMP1'\n comp2 = 'COMP1 \"COMP1 is not part of anything\"'\n comp3 = 'some random string that does not match' #bad declaration\n print (comp1), '\\n', parse(Component,comp1)\n print (comp2), '\\n', parse(Component,comp2)\n print (comp3), '\\n', parse(Component,comp3)\n\n print \"\\nCABLE tests\"\n cab1 = 'CABLE 12345 \"This cable has no length\"'\n cab2 = 'CABLE &C12346 \"This cable is 350mm long\" 350'\n print (cab1), '\\n', parse(Cable, cab1)\n print (cab2), '\\n', parse(Cable, cab2)\n\n print \"\\n JACK tests\"\n jack1 = 'JACK 1 \"connects to COMPA with no cable\" CONN/M -> COMPA'\n jack2 = 'JACK &J2 \"now has cable\" CONN2/F -> COMPB/2 CABLE &C4 \"cable, len=?\"'\n jack3 = 'JACK j3 \"now has cable\" CONN2/F -> COMPB CABLE \"cable, len=300\" 300'\n jack4 = 'JACK 4 \"cable desc is blank\" TEST/M -> COMP CABLE \"\"'\n jack5 = 'JACK 5 \"a possible mate for jack 4\" TEST/M -> COMP CABLE \"soemthing\"'\n print (jack1), '\\n', parse(Jack, jack1)\n print (jack2), '\\n', parse(Jack, jack2)\n print (jack3), '\\n', parse(Jack, jack3)\n j4 = parse(Jack, jack4)\n j4.conn = test_connector\n print (jack4), '\\n', j4\n j5 = parse(Jack, jack5)\n j5.conn = test_connector\n print (jack5), '\\n', j5\n if j5.canMate(j4): print \"It CAN mate with jack 4\"\n else: print \"It CAN NOT mate with jack 4\"\n\n print \"\\nLINE tests\"\n line1 = 'LINE \"this line has one pin\" (&J22,1)'\n line2 = 'LINE \"this one has 4 pins\" (0,1),(0,2),(1,A),(1,C)'\n line3 = 'LINE \"shortform for above\" (0;1,2),(1;A,C)'\n print (line1), '\\n', parse(Line, line1)\n print (line2), '\\n', parse(Line, line2)\n print (line3), '\\n', parse(Line, line3)\n" }, { "alpha_fraction": 0.5582278370857239, "alphanum_fraction": 0.5734177231788635, "avg_line_length": 23.6875, "blob_id": "456312087f697f6db131b43400587c1fa06f10cf", "content_id": "11c204b4d580dc205a5a362450c43fb045e22da4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1580, "license_type": "no_license", "max_line_length": 89, "num_lines": 64, "path": "/owl/owl-cgi/main.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <QSharedMemory>\n#include <QSystemSemaphore>\n#include <QFile>\n#include <QByteArray>\n#include <QStringList>\n#include <argp.h>\n#include <time.h>\n#include <unistd.h>\n\nusing namespace std;\n\nint fail() {\n cout<<\"Content-type: text/plain\\n\\n\";\n cout<<\"owl-cgi : retrives data from a running owl session.\\n\";\n cout<<\"For use as a CGI script with argument 'key:object' where object is one of:\\n\";\n cout<<\"'html', 'css', 'data', 'layout'\\n\";\n return 1;\n}\n\nint main(int argc, char** argv) {\n\n if(argc!=2) return fail();\n\n QStringList args=QString(argv[1]).split(':');\n if(args.size()!=2) return fail();\n\n QSystemSemaphore sema(\"_owlSema\"+args[0],1);\n sema.acquire(); //!!\n\n QSharedMemory* smem=0;\n if(args[1]==\"html\") {\n cout<<\"Content-type: text/html\\n\\n\";\n smem=new QSharedMemory(\"_owlHtml\"+args[0]);\n } else if(args[1]==\"css\") {\n cout<<\"Content-type: text/plain\\n\\n\";\n smem=new QSharedMemory(\"_owlCSS\"+args[0]);\n } else if(args[1]==\"data\") {\n cout<<\"Content-type: application/json\\n\\n\";\n smem=new QSharedMemory(\"_owlData\"+args[0]);\n } else if(args[1]==\"layout\") {\n cout<<\"Content-type: text/xml\\n\\n\";\n smem=new QSharedMemory(\"_owlLayout\"+args[0]);\n }\n\n int i=0;\n if(!smem||!smem->attach()) {\n sema.release();\n if(++i==100) {\n return fail();\n }\n usleep(1000);\n }\n\n smem->lock();\n cout<<(char*)smem->data();\n smem->unlock();\n smem->detach();\n delete smem;\n\n sema.release();\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6753585338592529, "alphanum_fraction": 0.6805736422538757, "avg_line_length": 19.1842098236084, "blob_id": "87ceececf453d0fde1b48bd7a8daac968f4c0724", "content_id": "f1f694c1f3a61e6ef655a7c8593842fc6815175f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 768, "license_type": "no_license", "max_line_length": 90, "num_lines": 38, "path": "/stars/code/displaying/blob.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__BLOB_H\n#define DISPLAYING__BLOB_H\n\n#include <string>\n#include \"utilities.h\"\n#include \"../tools/timing.h\"\n\nnamespace Displaying\n{\n class Blob;\n}\n\nclass Displaying::Blob\n{\n public:\n Blob(double x_, double y_, int blob_num_);\n void draw(Size& size_, double global_age, double intercept, bool matched, bool named);\n double x, y;\n int blob_num;\n std::string name;\n double born;\n\n private:\n double halfsize;\n double birth_angle;\n double rotation_speed;\n double birth_time;\n Tools::Timer timer;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6909090876579285, "alphanum_fraction": 0.6939393877983093, "avg_line_length": 22.571428298950195, "blob_id": "7ab48d50aa3b0913520bbdff011d844f59d38fb9", "content_id": "5f814a9b7d1b4a8c6324de6693d52a1e04e9eff5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 330, "license_type": "no_license", "max_line_length": 58, "num_lines": 14, "path": "/blastd/doRestart", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n# restart the blastpol groundstation\n#\n\nkillall tdrsslogger rnc dnc tea lnc\n\n/usr/local/sbin/tdrsslogger >& /data/etc/tdrsslogger.log &\n/usr/local/sbin/rnc >& /data/etc/rnc.log &\n/usr/local/sbin/dnc >& /data/etc/dnc.log &\n/usr/local/sbin/tea >& /data/etc/tea.log &\n/usr/local/sbin/lnc >& /data/etc/lnc.log &\n\nexit 0\n" }, { "alpha_fraction": 0.6881377696990967, "alphanum_fraction": 0.6938775777816772, "avg_line_length": 21.08450698852539, "blob_id": "9600eb357dc3d1a3c50e112eda21fc8dc174fae6", "content_id": "541f695e1e658f068de51c1deda9397733cb2cbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1569, "license_type": "no_license", "max_line_length": 81, "num_lines": 71, "path": "/stars/code/shared/lens/results.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__LENS__RESULTS_H\n#define SHARED__LENS__RESULTS_H\n\n#include \"../circular_buffer.h\"\n#include <string>\n#include \"../../imaging/commands.h\"\n#include \"../../tools/timing.h\"\n#include \"requests.h\"\n\nnamespace Shared\n{\n namespace Lens\n {\n\nclass Results\n{\n public:\n Results();\n Results& operator=(const Results& rhs);\n bool is_focus_valid(Requests& requests);\n bool is_aperture_valid(Requests& requests);\n\n static const unsigned int num_commands = Imaging::LensCommands::num_commands;\n int focus_value;\n bool focus_found;\n int aperture_value;\n bool aperture_found;\n int command_counters[num_commands];\n double max_exposure_and_readout_time;\n std::string device_name;\n bool device_found;\n};\n\n\n// path: 0\n// writes: lens\n// reads: camera\nextern Shared::CircularBufferPass <Results> fcp_results_lens_to_camera;\n\n// path: 0\n// writes: camera\n// reads: main\nextern Shared::CircularBufferPass <Results> fcp_results_camera_to_main;\n\n// path: 0\n// writes: main\n// reads: network\nextern Shared::CircularBuffer <Results> fcp_results_main_to_network;\n\n\n// path: 1\n// writes: lens\n// reads: camera\nextern Shared::CircularBufferPass <Results> stars_results_lens_to_camera;\n\n// path: 1\n// writes: camera\n// reads: main\nextern Shared::CircularBuffer <Results> stars_results_camera_to_main;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.7118644118309021, "alphanum_fraction": 0.7273180484771729, "avg_line_length": 33.58620834350586, "blob_id": "bb8ba793620b9182e96ef93fcca98f16422a39e5", "content_id": "63da0c9dbd27771c1b212e2ecb5758e016b2e100", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2006, "license_type": "no_license", "max_line_length": 82, "num_lines": 58, "path": "/blast_comms/include/comms_serial.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/**\n * @file comms_serial.h\n *\n * @date 2011-02-07\n * @author Seth Hillbrand\n *\n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2011-2015 Seth Hillbrand\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#ifndef INCLUDE_COMMS_SERIAL_H_\n#define INCLUDE_COMMS_SERIAL_H_\n#include <stdbool.h>\n#include <stddef.h>\n#include <termios.h>\n\n#include <comms_common.h>\n#include <comms_netsock.h>\n#include <pthread.h>\n\ntypedef struct comms_serial\n{\n\tcomms_socket_t *sock;\n\tstruct termios term;\n\tpthread_mutex_t mutex;\n} comms_serial_t;\n\n\ncomms_serial_t *comms_serial_new(void *m_data);\nvoid comms_serial_reset(comms_serial_t **m_serial);\nvoid comms_serial_free(void *m_serial);\nvoid comms_serial_close(comms_serial_t *m_serial);\nvoid comms_serial_set_fd(comms_serial_t *m_serial, socket_t m_fd);\nint comms_serial_write(comms_serial_t *m_serial, const void *m_buf, size_t m_len);\nint comms_serial_flush(comms_serial_t *m_serial);\nbool comms_serial_setspeed(comms_serial_t *m_serial, speed_t m_speed);\nint comms_serial_set_baud_base(comms_serial_t *m_serial, int m_base);\nint comms_serial_set_baud_divisor(comms_serial_t *m_serial, int m_speed);\n\nint comms_serial_connect(comms_serial_t *m_serial, const char *m_terminal);\nint comms_fifo_connect(comms_serial_t *m_serial, const char *m_fifo, int m_flags);\n#endif /* COMMS_SERIAL_H_ */\n" }, { "alpha_fraction": 0.6933085322380066, "alphanum_fraction": 0.7007434964179993, "avg_line_length": 16.899999618530273, "blob_id": "73ff9d4b6222ee59857cdce9b88e356bc30b26b1", "content_id": "1b16cca7378acbf416d8466ae77c191a5c81af2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 539, "license_type": "no_license", "max_line_length": 73, "num_lines": 30, "path": "/stars/code/displaying/camera.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__CAMERA_H\n#define DISPLAYING__CAMERA_H\n\n#include \"block.h\"\n#include \"dynamic_value.h\"\n\nnamespace Displaying\n{\n class Camera;\n}\n\nclass Displaying::Camera: public Displaying::Block\n{\n public:\n Camera();\n void update();\n void draw(Position& position);\n\n private:\n DynamicValue gain;\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.7029411792755127, "alphanum_fraction": 0.70686274766922, "avg_line_length": 19.816326141357422, "blob_id": "2ac976849bc45f7ff8ec5a1399f6d844bc4964ed", "content_id": "70498805758c1a556846f2b22eb4f7362f06a258", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1021, "license_type": "no_license", "max_line_length": 73, "num_lines": 49, "path": "/stars/code/displaying/image.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__IMAGE_H\n#define DISPLAYING__IMAGE_H\n\n#include \"block.h\"\n\nnamespace Displaying\n{\n class Image;\n}\n\nclass Displaying::Image: public Block\n{\n public:\n Image();\n void update();\n void draw(Position& position);\n\n private:\n bool currently_solving;\n DynamicValue age;\n DynamicValue counter_stars;\n DynamicValue counter_fcp;\n DynamicValue lat;\n DynamicValue lst;\n DynamicValue mean;\n DynamicValue noise;\n DynamicValue gain;\n DynamicValue num_pixels_saturated;\n DynamicValue stage;\n DynamicValue ra;\n DynamicValue dec;\n DynamicValue az;\n DynamicValue el;\n DynamicValue hroll;\n DynamicValue matched;\n DynamicValue measured_exposure;\n DynamicValue pointing_error;\n DynamicValue fit_error;\n DynamicValue platescale;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6147351861000061, "alphanum_fraction": 0.6174902319908142, "avg_line_length": 52.57619094848633, "blob_id": "c0452359c967d639834740c57d661fa94509d54c", "content_id": "09ec319d531e23757b8153feb5c4bb724b907287", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11253, "license_type": "no_license", "max_line_length": 112, "num_lines": 210, "path": "/stars/code/main.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include <string.h>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#ifndef _MSC_VER\n #include <signal.h>\n#endif\n#include \"star_camera.h\"\n#include \"parameters/manager.h\"\n#include \"shared/shared_list.h\"\n#include \"tools/timing.h\"\n#include \"logging/logger.h\"\n#include \"solving/logger.h\"\n#include \"housekeeping/logger.h\"\n#include \"imaging/logger_lens.h\"\n#include \"imaging/logger_camera.h\"\n#include \"networking/logger.h\"\n#include \"logger_main.h\"\n\n#define shared_shutdown (*(Shared::General::shutdown_for_main.r))\n#define CBuf CircularBuffer\n#define CBufP CircularBufferPass\n\n// Every logger's update function should be regularly called by its owner (thread)\nLogging::Logger Solving::logger(\"solving\", true);\nLogging::Logger Housekeeping::logger(\"hk\", false);\nLogging::Logger Imaging::Lensing::logger(\"lens\", true);\nLogging::Logger Imaging::Cameraing::logger(\"cam\", true);\nLogging::Logger Main::logger(\"main\", true);\nLogging::Logger Networking::logger(\"network\", true);\nLogging::Logger NetworkingImageClient::logger1(\"nic1\", true);\nLogging::Logger NetworkingImageClient::logger2(\"nic2\", true);\n\nnamespace Shared\n{\nusing namespace ThreadNames;\nCBufP <Autofocus::Datapoints> Autofocus::datapoints_solver_to_lens (solver, lens);\nCBuf <Autofocus::Datapoints> Autofocus::datapoints_lens_to_main (lens, main);\nCBuf <Autofocus::LatestImage> Autofocus::latest_image (camera, lens);\nCBufP <Autofocus::Requests> Autofocus::requests_network_to_main (net_client, main);\nCBuf <Autofocus::Requests> Autofocus::requests_main_to_lens (main, lens);\nCBufP <Autofocus::Results> Autofocus::results_lens_to_solver (lens, solver);\nCBufP <Autofocus::Results> Autofocus::results_solver_to_main (solver, main);\nCBuf <Autofocus::Results> Autofocus::results_main_to_network (main, net_server);\nCBufP <Camera::Requests> Camera::requests_for_main (net_client, main);\nCBuf <Camera::Requests> Camera::requests_for_camera (main, camera);\nCBufP <Camera::Results> Camera::results_for_main (camera, main);\nCBuf <Camera::Results> Camera::results_for_network (main, net_server);\nCBufP <General::MainSettings> General::main_settings_net_for_main (net_client, main);\nCBuf <General::MainSettings> General::main_settings_main_for_solver (main, solver);\nCBuf <General::Shutdown> General::shutdown_for_main (net_client, main);\nCBuf <General::NetworkReset> General::network_reset_for_net_reset (net_client, net_reset);\nCBuf <General::NetworkResetStatus> General::network_reset_status_for_main (net_reset, main);\nCBufP <Housekeeping::Housekeeper> Housekeeping::housekeeper_for_camera (main, camera);\nCBuf <Housekeeping::Housekeeper> Housekeeping::housekeeper_for_network (camera, net_server);\nCBufP <Image::Blobs> Image::blobs_solver_for_main (solver, main);\nCBuf <Image::Blobs> Image::blobs_main_for_net (main, net_server);\nCBuf <Image::Leveled> Image::leveled (solver, main);\nCBuf <Image::Matching> Image::matching (solver, main);\nCBuf <Image::MatchingProgress> Image::matching_progress (solver, main);\nCBuf <Image::Raw> Image::raw_from_camera (camera, solver);\nCBuf <Image::Raw> Image::raw_for_image_client1 (camera, net_image_client1);\nCBuf <Image::Raw> Image::raw_for_image_client2 (camera, net_image_client2);\nCBufP <Image::SolutionSummary> Image::solution_summary_for_main (solver, main);\nCBuf <Image::SolutionSummary> Image::solution_summary_main_for_net (main, net_server);\nCBufP <Image::Stats> Image::stats_solver_for_main (solver, main);\nCBuf <Image::Stats> Image::stats_main_for_net (main, net_server);\nCBufP <Image::Status> Image::status_solver_for_main (solver, main);\nCBufP <Image::Status> Image::status_main_for_camera (main, camera);\nCBuf <Image::Status> Image::status_camera_for_network (camera, net_server);\nCBufP <Lens::Requests> Lens::fcp_requests_network_to_main (net_client, main);\nCBufP <Lens::Requests> Lens::fcp_requests_main_to_camera (main, camera);\nCBuf <Lens::Requests> Lens::fcp_requests_camera_to_lens (camera, lens);\nCBufP <Lens::Requests> Lens::stars_requests_lens_to_main (lens, main);\nCBufP <Lens::Requests> Lens::stars_requests_main_to_camera (main, camera);\nCBuf <Lens::Requests> Lens::stars_requests_camera_to_lens (camera, lens);\nCBufP <Lens::Results> Lens::fcp_results_lens_to_camera (lens, camera);\nCBufP <Lens::Results> Lens::fcp_results_camera_to_main (camera, main);\nCBuf <Lens::Results> Lens::fcp_results_main_to_network (main, net_server);\nCBufP <Lens::Results> Lens::stars_results_lens_to_camera (lens, camera);\nCBuf <Lens::Results> Lens::stars_results_camera_to_main (camera, main);\nCBufP <Network::Client> Network::client_for_main (net_client, main);\nCBuf <Network::Client> Network::client_for_camera (main, camera);\nCBuf <Network::Packets> Network::packets_from_fc1 (net_client, main);\nCBuf <Network::Packets> Network::packets_from_fc2 (net_client, main);\nCBuf <Network::ImageClientSettings> Network::image_client_settings1 (net_client, net_image_client1);\nCBuf <Network::ImageClientSettings> Network::image_client_settings2 (net_client, net_image_client2);\nCBuf <Simulations::Brightness> Simulations::brightness (net_client, camera);\nCBufP <Solving::Filters> Solving::filters_net_to_main (net_client, main);\nCBuf <Solving::Filters> Solving::filters_main_to_camera (main, camera);\nCBufP <Solving::Mask> Solving::mask_network_for_solver (net_client, solver);\nCBuf <Solving::Mask> Solving::mask_solver_for_main (solver, main);\nCBuf <Solving::Settings> Solving::settings (net_client, solver);\nbool General::quit;\n}\n\nvoid init_loggers(Parameters::Manager& params, boost::posix_time::ptime& birthtime, Tools::Timer& age)\n{\n Solving::logger.init(params, birthtime, age);\n Housekeeping::logger.init(params, birthtime, age);\n Imaging::Lensing::logger.init(params, birthtime, age);\n Imaging::Cameraing::logger.init(params, birthtime, age);\n Main::logger.init(params, birthtime, age);\n Networking::logger.init(params, birthtime, age);\n NetworkingImageClient::logger1.init(params, birthtime, age);\n NetworkingImageClient::logger2.init(params, birthtime, age);\n}\n\nvoid init_shared_objects(Parameters::Manager& params)\n{\n Shared::Solving::settings.init(params);\n Shared::Solving::filters_net_to_main.init(params);\n Shared::Solving::filters_main_to_camera.init(params);\n Shared::Solving::mask_network_for_solver.init(params);\n Shared::Solving::mask_solver_for_main.init(params);\n Shared::Simulations::brightness.init(params);\n Shared::Image::raw_from_camera.init(params);\n Shared::Image::raw_for_image_client1.init(params);\n Shared::Image::raw_for_image_client2.init(params);\n Shared::Image::leveled.init(params);\n Shared::Autofocus::requests_network_to_main.init(params);\n Shared::Autofocus::requests_main_to_lens.init(params);\n Shared::Network::image_client_settings1.init(params);\n Shared::Network::image_client_settings2.init(params);\n Shared::General::main_settings_net_for_main.init(params);\n Shared::General::main_settings_main_for_solver.init(params);\n Shared::General::network_reset_for_net_reset.init(params);\n Shared::General::quit = false;\n}\n\nvoid kill_handler(int signal)\n{\n Main::logger.log(format(\"caught signal %d\") % signal);\n Shared::General::quit = true;\n}\n\nvoid register_kill_handler()\n{\n\t#ifndef _MSC_VER\n\t\tstruct sigaction handler;\n\t\thandler.sa_handler = kill_handler;\n\t\tsigemptyset(&handler.sa_mask);\n\t\thandler.sa_flags = 0;\n\t\tsigaction(SIGINT, &handler, NULL);\n\t\tsigaction(SIGTERM, &handler, NULL);\n\t#endif\n}\n\nvoid shutdown_if_requested()\n{\n\t#ifdef _MSC_VER\n if (shared_shutdown.shutdown_now) {\n HANDLE hToken;\n TOKEN_PRIVILEGES tkp;\n if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {\n return;\n }\n LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);\n tkp.PrivilegeCount = 1;\n tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;\n AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);\n if (GetLastError() != ERROR_SUCCESS) {\n return;\n }\n UINT restart_flag = EWX_POWEROFF;\n if (shared_shutdown.include_restart) {\n Main::logger.log(\"STARS is finishing, requesting shutdown with restart\");\n restart_flag = EWX_REBOOT;\n } else {\n Main::logger.log(\"STARS is finishing, requesting shutdown without restart\");\n restart_flag = EWX_POWEROFF;\n }\n if(!ExitWindowsEx(restart_flag | EWX_FORCEIFHUNG, SHTDN_REASON_MAJOR_OTHER)) {\n Main::logger.log(\"ExitWindows call was unsuccessful\");\n } else {\n Main::logger.log(\"ExitWindows call was successful\");\n }\n }\n #endif\n}\n\nint main(int argc, char* argv[]){\n Tools::Timer age;\n age.start();\n boost::posix_time::ptime birthtime = boost::posix_time::microsec_clock::local_time();\n\t\n\t#ifdef _MSC_VER\n std::string stars_absolute_dir = \"C:/stars_data/\";\n #else\n std::string stars_absolute_dir = \"../../\";\n #endif\n Parameters::Manager params(stars_absolute_dir);\n params.load(argc, argv);\n init_loggers(params, birthtime, age);\n params.load(argc, argv);\n Main::logger.log(\"STARS is running\");\n register_kill_handler();\n init_shared_objects(params);\n Shared::Image::Raw solvers_working_image;\n solvers_working_image.init(params);\n StarCamera star_camera(params, solvers_working_image);\n star_camera.run(params);\n shutdown_if_requested();\n Main::logger.log(\"STARS is finished\");\n return 0;\n}\n\n" }, { "alpha_fraction": 0.6251788139343262, "alphanum_fraction": 0.633762538433075, "avg_line_length": 14.19565200805664, "blob_id": "7aa24b0da0c64f55d9913f0b124dae525362ff5b", "content_id": "d5f601695155de392aafd28ec4b9f80826b45120", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 700, "license_type": "no_license", "max_line_length": 73, "num_lines": 46, "path": "/stars/code/shared/request.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__REQUEST_H\n#define SHARED__REQUEST_H\n\nnamespace Shared\n{\n\n\ntemplate <class T>\nclass Request\n{\n public:\n Request();\n Request& operator=(const Request& rhs);\n\n int counter;\n T value;\n};\n\ntemplate <class T>\nRequest<T>::Request()\n{\n counter = 0;\n value = 0;\n}\n\ntemplate <class T>\nRequest<T>& Request<T>::operator=(const Request<T> &rhs)\n{\n if (this != &rhs) {\n counter = rhs.counter;\n value = rhs.value;\n }\n return *this;\n}\n\n\n}\n\n#endif\n" }, { "alpha_fraction": 0.6319656372070312, "alphanum_fraction": 0.6368172764778137, "avg_line_length": 37.16402053833008, "blob_id": "9f0ae9803640173eb814c2e34525b01985f8568e", "content_id": "f2cd25380a0def6dc70271c820812030a7aba7dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7215, "license_type": "no_license", "max_line_length": 124, "num_lines": 189, "path": "/stars/code/imaging/autofocuser.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"autofocuser.h\"\n#include <limits>\n#include \"logger_lens.h\"\n#include \"commands.h\"\n#include \"../tools/math.h\"\n#include \"../shared/autofocus/datapoints.h\"\n#include \"../shared/autofocus/requests.h\"\n#include \"../shared/autofocus/latest_image.h\"\n#include \"../shared/autofocus/results.h\"\n#include \"../shared/lens/requests.h\"\n#include \"../shared/lens/results.h\"\n\nusing namespace Imaging;\nusing namespace Shared::Autofocus;\nusing Lensing::logger;\n#define shared_datapoints (*(datapoints_solver_to_lens.r))\n#define shared_requests (*(requests_main_to_lens.r))\n#define shared_latest_image (*(latest_image.r))\n#define shared_results (*(results_lens_to_solver.w))\n#define shared_lens_results (*(Shared::Lens::stars_results_camera_to_main.r))\n#define shared_lens_requests (*(Shared::Lens::stars_requests_lens_to_main.w))\n\nAutofocuser::Autofocuser()\n{\n run_counter = 0;\n //run_counter = -1; // HACK TO MAKE IT RUN\n abort_counter = 0;\n last_counter_stars = -1;\n waiting_for_image_since_focus_change = false;\n}\n\nvoid Autofocuser::make_focus_request()\n{\n logger.log(format(\"autofocuser requesting focus %i\")%shared_results.current_focus_requested);\n shared_lens_requests.commands[LensCommands::set_focus].counter++;\n shared_lens_requests.commands[LensCommands::set_focus].value =\n shared_results.current_focus_requested;\n Shared::Lens::stars_requests_lens_to_main.share();\n waiting_for_image_since_focus_change = true;\n}\n\nvoid Autofocuser::end_run(bool use_solution)\n{\n logger.log(format(\"autofocuser at end of run found %i curves\")%shared_datapoints.curves.size());\n time_since_last_finish.start();\n shared_results.mode = Results::mode_finished_and_gracing;\n results_lens_to_solver.share();\n\n if (!use_solution) {\n return;\n }\n\n int best_star_flux_curve_index = -1;\n double best_star_flux_peak = -std::numeric_limits<double>::infinity();\n int brightest_blob_curve_index = -1;\n\n for (unsigned int i=0; i<shared_datapoints.curves.size(); i++) {\n double focus = 0.0;\n double value = 0.0;\n if (shared_datapoints.curves[i].get_peak(focus, value)) {\n if (shared_datapoints.curves[i].type == metric_brightest_blob_flux) {\n brightest_blob_curve_index = i;\n shared_datapoints.curves[i].log(logger);\n }\n if (shared_datapoints.curves[i].type == metric_star_flux) {\n if (value > best_star_flux_peak) {\n best_star_flux_peak = value;\n best_star_flux_curve_index = i;\n }\n }\n }\n }\n\n double best_focus = 0.0;\n double best_value = 0.0;\n bool best_focus_found = false;\n if (best_star_flux_curve_index > -1 && best_star_flux_curve_index < (signed int) shared_datapoints.curves.size())\n {\n shared_datapoints.curves[best_star_flux_curve_index].get_peak(best_focus, best_value);\n shared_datapoints.curves[best_star_flux_curve_index].log(logger);\n best_focus_found = true;\n logger.log(format(\"autofocuser found best focus %i from the best star_flux metric\")%best_focus);\n }\n else if (brightest_blob_curve_index > -1 && brightest_blob_curve_index < (signed int) shared_datapoints.curves.size())\n {\n shared_datapoints.curves[brightest_blob_curve_index].get_peak(best_focus, best_value);\n best_focus_found = true;\n logger.log(format(\"autofocuser found best focus %i from brightest_blob metric\")%best_focus);\n }\n if (best_focus_found) {\n shared_results.best_focus_known = true;\n shared_results.best_focus = int(round(best_focus));\n shared_results.current_focus_requested = shared_results.best_focus;\n results_lens_to_solver.share();\n make_focus_request();\n waiting_for_image_since_focus_change = false;\n }\n\n}\n\nvoid Autofocuser::update()\n{\n\n // begin the run\n if (shared_requests.run_counter != run_counter) {\n logger.log(\"autofocuser beginning run\");\n run_counter = shared_requests.run_counter;\n last_counter_stars = shared_latest_image.counter_stars;\n shared_results.mode = Results::mode_running;\n autofocus_run_time.start();\n shared_results.current_focus_requested = shared_requests.focus_search_min;\n shared_results.age_of_last_run.start();\n shared_results.best_focus_known = false;\n results_lens_to_solver.share();\n make_focus_request();\n\n }\n\n if (shared_results.mode == Results::mode_running) {\n\n // if the camera just received a new image\n if ((shared_latest_image.counter_stars != last_counter_stars) || (!waiting_for_image_since_focus_change)) {\n last_counter_stars = shared_latest_image.counter_stars;\n waiting_for_image_since_focus_change = false;\n\n\t\t\t// make sure we moved to the previous position\n\t\t\tif (shared_lens_results.focus_value == shared_results.current_focus_requested) {\n\t\t\t\t// take a focus step if we're not at the max focus\n\t\t\t\tif (shared_results.current_focus_requested < shared_requests.focus_search_max) {\n\t\t\t\t\tshared_results.current_focus_requested += shared_requests.focus_search_step;\n\t\t\t\t\tresults_lens_to_solver.share();\n\t\t\t\t\tmake_focus_request();\n\t\t\t\t}\n\t\t\t}\n }\n\n // end the run if we're at the max focus and we're not waiting for an image\n if (shared_results.current_focus_requested >= shared_requests.focus_search_max &&\n !waiting_for_image_since_focus_change)\n {\n if (!time_since_image_captured_at_last_focus.started()) {\n time_since_image_captured_at_last_focus.start();\n }\n\n // and either the solver finished with the latest image\n if (shared_datapoints.last_fully_solved_counter_stars >= last_counter_stars)\n {\n logger.log(\"autofocus: ending run because solver is finished with the latest image\");\n end_run(true);\n }\n // or it's been 30 seconds since capturing an image at the last focus\n else if (time_since_image_captured_at_last_focus.time() > 30)\n {\n logger.log(\"autofocus: ending run because it's been 30 seconds since capturing an image at the last focus\");\n end_run(true);\n }\n }\n else {\n time_since_image_captured_at_last_focus.reset();\n }\n\n if (autofocus_run_time.time() > 60.0*20.0) {\n end_run(false);\n }\n\n }\n\n if (shared_requests.abort_counter != abort_counter) {\n abort_counter = shared_requests.abort_counter;\n if (shared_results.mode == Results::mode_running) {\n end_run(shared_requests.abort_still_use_solution);\n }\n }\n\n // end the grace period\n if (shared_results.mode == Results::mode_finished_and_gracing) {\n if (time_since_last_finish.time() > 30) {\n shared_results.mode = Results::mode_not_running;\n results_lens_to_solver.share();\n }\n }\n\n}\n\n" }, { "alpha_fraction": 0.6924882531166077, "alphanum_fraction": 0.6953051686286926, "avg_line_length": 28.58333396911621, "blob_id": "a1c73035b72e8e57c9ee63e119eba9c28d729a07", "content_id": "832290d50a5087a79b9da1516909861b777554e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2131, "license_type": "no_license", "max_line_length": 88, "num_lines": 72, "path": "/stars/code/networking/connection.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef NETWORKING__CONNECTION_H\n#define NETWORKING__CONNECTION_H\n\n#include <boost/shared_ptr.hpp>\n#include <boost/enable_shared_from_this.hpp>\n#include <boost/asio.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include \"../tools/timing.h\"\nextern \"C\" {\n#include \"xsc_protocol/xsc_protocol.h\"\n}\n\nnamespace Networking\n{\n typedef enum {\n client_name_fc1,\n client_name_fc2,\n client_name_unknown\n } client_name_t;\n\n class Connection;\n}\n\nclass Networking::Connection: public boost::enable_shared_from_this<Connection>\n{\n public:\n typedef boost::shared_ptr<Connection> pointer;\n static pointer create(boost::asio::io_service& io_service)\n {\n return pointer(new Connection(io_service));\n }\n boost::asio::ip::tcp::socket& socket();\n void start();\n\n private:\n Connection(boost::asio::io_service& io_service);\n\n void load_server_data_housekeeping();\n void load_server_data_camera_and_lens();\n void load_server_data_image();\n void load_server_data();\n void write_server_data(/*boost::system::error_code& error*/);\n void handle_write(const boost::system::error_code& error, size_t bytes_transferred);\n\n bool check_command(unsigned int command_index);\n void unload_client_data_lens_and_camera();\n void unload_client_data_autofocus();\n void unload_client_data_solver();\n void unload_client_data_solver_filters();\n void unload_main_and_display_settings();\n void unload_client_data();\n void read_client_data();\n void handle_read(const boost::system::error_code& error, size_t bytes_transferred);\n\n boost::asio::ip::tcp::socket socket_;\n client_name_t client_name;\n XSCClientData client_data;\n XSCServerData server_data;\n xsc_command_admin_t local_command_admins[xC_num_command_admins];\n bool ready_to_read, ready_to_write;\n boost::asio::deadline_timer write_timer;\n bool first_packet;\n};\n\n#endif\n" }, { "alpha_fraction": 0.7133105993270874, "alphanum_fraction": 0.7252559661865234, "avg_line_length": 39.41379165649414, "blob_id": "f94d68e67455a71f3dbf2b27aec77bbc311ac828", "content_id": "da16b8cfbb53dceb807b9558b61a4c6c475fb01c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1172, "license_type": "no_license", "max_line_length": 183, "num_lines": 29, "path": "/restart_blastgs.sh", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#! /bin/bash\nREPO_DIR=\"~/flight_master\"\nGROUNDHOG_BUILD_DIR=\"$REPO_DIR/groundhog/build\"\nBLASTCMD_BUILD_DIR=\"$REPO_DIR/blastcmd\"\n\nif [ -z \"$2\" ]\nthen\n GIT_BRANCH=\"master\"\nelse\n GIT_BRANCH=\"$2\"\nfi\n\nGIT_PULL_CMD=\"cd $REPO_DIR; git pull; git checkout $GIT_BRANCH; git pull origin $GIT_BRANCH\"\n\nGROUNDHOG_BUILD_CMD=\"cd $GROUNDHOG_BUILD_DIR; cmake ../; make clean all; sudo make install\"\nGROUNDHOG_RESTART_CMD=\"sudo pkill groundhog\"\n\nBLASTCMD_BUILD_CMD=\"cd $BLASTCMD_BUILD_DIR; make; sudo make install\"\nBLASTCMD_RESTART_CMD=\"sudo pkill blastcmd\"\nBLASTCMD_UPLOAD=\"cd $BLASTCMD_BUILD_DIR; scp blastcmd fc1user@fc1:~/; scp blastcmd fc1user@fc2:~/\"\nBLASTCMD_INSTALL_FC=\"cd; install -m 755 -p blastcmd /usr/local/bin/\"\n\nKILL_MCP=\"sudo kill -INT \\$(pidof mcp) > /dev/null 2>&1\"\n\nLINKLIST_UPDATE_CMD=\"cd $REPO_DIR; ./upload_linklists.sh\"\nBLASTCMD_RESTART_FC=\"ssh -t fc1 '$BLASTCMD_INSTALL_FC; $BLASTCMD_RESTART_CMD'; $KILL_MCP; ssh -t fc2 '$BLASTCMD_INSTALL_FC; $BLASTCMD_RESTART_CMD'; $KILL_MCP\"\n\n\nssh -t blast@$1 \"$GIT_PULL_CMD; $LINKLIST_UPDATE_CMD; $GROUNDHOG_BUILD_CMD; $GROUNDHOG_RESTART_CMD; $BLASTCMD_BUILD_CMD; $BLASTCMD_RESTART_CMD; $BLASTCMD_UPLOAD; $BLASTCMD_RESTART_FC\"\n" }, { "alpha_fraction": 0.6749049425125122, "alphanum_fraction": 0.6787072420120239, "avg_line_length": 18.849056243896484, "blob_id": "35c2177670166bf2c64b3d6a82f9d7de8353f4e5", "content_id": "b83f2630c85e93b78b7cda64262c888e8576dbcf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1053, "license_type": "no_license", "max_line_length": 73, "num_lines": 53, "path": "/stars/code/shared/autofocus/results.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__AUTOFOCUS__RESULTS_H\n#define SHARED__AUTOFOCUS__RESULTS_H\n\n#include \"../circular_buffer.h\"\n#include \"../../tools/timing.h\"\n\nnamespace Shared\n{\n namespace Autofocus\n {\n\nclass Results\n{\n public:\n Results();\n Results& operator=(const Results& rhs);\n\n enum mode_t {\n mode_not_running,\n mode_running,\n mode_finished_and_gracing\n };\n\n mode_t mode;\n int current_focus_requested;\n Tools::Timer age_of_last_run;\n bool best_focus_known;\n int best_focus;\n};\n\n// writes: lens\n// reads: solver\nextern Shared::CircularBufferPass <Results> results_lens_to_solver;\n\n// writes: solver\n// reads: main\nextern Shared::CircularBufferPass <Results> results_solver_to_main;\n\n// writes: main\n// reads: network\nextern Shared::CircularBuffer <Results> results_main_to_network;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.6651860475540161, "alphanum_fraction": 0.6711729168891907, "avg_line_length": 37.735660552978516, "blob_id": "b94ffb054fcf976b4c9a2ed5db648375cdacfa13", "content_id": "a021932b57c8b2a859952c58ba8d8621e9d9c1d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15534, "license_type": "no_license", "max_line_length": 80, "num_lines": 401, "path": "/sedpy/sedparser.py", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#!/usr/bin/env /usr/bin/python\n\nimport sys\nimport os\nimport os.path\n\n#create output directory, needed before sedobjects imported\nif not os.path.isdir(\"out\"):\n os.mkdir(\"out\", 0755)\n\nfrom sedobjects import *\nimport lineparser #provides lineparser.parse(Type, string)\n\ndefaultfile = \"description.txt\"\n\nconnectors = [] #list of connectors\ncontainers = [] #list of components and cables\nexpected = [] #list of parts that have ben referenced but not declared\n\n################################################################################\n# things to do after the list is fully parsed, mated, and checked\n\ndef writeInfiles():\n \"\"\"from connectors, containers lists creates database infiles\"\"\"\n for conn in connectors:\n conn.toInfile()\n for cont in containers:\n #print \"writing\", cont.ref\n for line in cont.lines: line.toInfile()\n for jack in cont.jacks:\n #print \"writing\", jack.ref, \"with dest\", jack.dest.ref\n if not jack.placeholder:\n\tfor pin in jack.pins: pin.toInfile()\n\tjack.toInfile()\n\tif jack.cable and jack.cablemaster:\n\t jack.cable.toInfile()\n\t for cline in jack.cable.lines: cline.toInfile()\n cont.toInfile()\n\ndef countConnectors():\n \"\"\"count how many of each connector type and gender are used as jacks\"\"\"\n f = open(\"out/connector_count.txt\", 'w')\n countconn = {} #counts how many of each connector\n for conn in connectors: countconn[conn.type] = {'M': 0, 'F': 0}\n for cont in containers:\n for jack in cont.jacks:\n if not jack.placeholder:\n\tname = jack.conn.type\n\tgender = jack.gender\n\tmatename = jack.conn.mate.type\n\tmategender = jack.conn.genders[jack.gender]\n\tcountconn[name][gender] += 1\n\tcountconn[matename][mategender] += 1\n f.write(\"%10s%10s%10s\\n\" % (\"Jack Type\", \"# Male\", \"# Female\"))\n for conn in connectors:\n if countconn[conn.type]['M'] > 0 or countconn[conn.type]['F'] > 0:\n f.write(\"%10s%10s%10s\\n\" % (conn.type, \n\t countconn[conn.type]['M'], countconn[conn.type]['F']))\n\ndef rewriteDescription(filename):\n \"\"\"read and rewrite the description file, adds extra info from parsing\"\"\"\n nd = open(\"out/newdescription.txt\", 'w') #path to new description\n f = open(filename, 'r')\n startWithConnectors = True\n cont = None\n for line in f:\n sline = line.strip()\n\n if startWithConnectors: #set to false when done\n conn = lineparser.parse(Connector, sline)\n if conn is not None:\n\tnd.write(\"%s\\n\" % str(connectors[connectors.index(conn)]))\n elif sline[0] == '*' and sline == '*ENDCONNECTORLIST':\n\tstartWithConnectors = False\n\tnd.write(line)\n \n elif sline[0:4] == \"JACK\":\n #temporarily replace placeholder numbers with mate's, for writing\n jack = cont.jacks[cont.jacks.index(lineparser.parse(Jack, sline))]\n oldnumber = jack.number\n oldmnumber = jack.mate.number\n if jack.placeholder: jack.number = jack.mate.number\n if jack.mate.placeholder: jack.mate.number = jack.number\n nd.write(\" %s\\n\" % str(jack))\n jack.number = oldnumber\n jack.mate.number = oldmnumber\n\n elif sline[0:4] == \"LINE\":\n line = lineparser.parse(Line, sline)\n line = cont.lines[cont.lines.index(line)]\n #temporarily replace jack numbers with global references, for writing\n newjacknums = []\n for jacknum in line.jacknums:\n\tjack = cont.jacks[cont.jacks.index(jacknum)]\n\tif jack.placeholder: jack = jack.mate\n\tnewjacknums.append(\"&J%d\" % jack.number)\n oldjacknums = line.jacknums\n line.jacknums = newjacknums\n nd.write(\" %s\\n\" % str(line))\n line.jacknums = oldjacknums\n\n elif sline[0:5] == \"CABLE\":\n cont = containers[containers.index(lineparser.parse(Cable, sline))]\n nd.write(\"%s\\n\" % str(cont))\n\n elif sline == \"\" or sline[0] == '#':\t#blank or comment, just reprint\n nd.write(line)\n\n else: #COMPONENT\n cont = containers[containers.index(lineparser.parse(Component, sline))]\n nd.write(\"%s\\n\" % str(cont))\n\n################################################################################\n# parser logic\n\ndef mateJack(jack):\n \"\"\"tries to find mate for jack, then does some pairing operations\"\"\"\n try: jack.dest = containers[containers.index(jack.dest_str)]\n except ValueError: #couldn't find target\n if jack.dest_str not in expected:\n expected.append(Component(jack.dest_str, \"expected\", None))\n return\n if jack.dest_jack is not None: #explicitly specified mating jack\n try: jack.mate = jack.dest.jacks[jack.dest.jacks.index(jack.dest_jack)]\n except ValueError: return #no match for explicit matching jack\n else: #explicit mate found\n if jack.mate.dest_str != containers[-1].ref or\\\n\t not jack.canMate(jack.mate): raise Failure(\"Mate doesn't fit right\")\n else: #non-explicit mate, search for one amongst jacks on destination\n for tempjack in jack.dest.jacks: \n if jack.canMate(tempjack) and tempjack.dest_str == containers[-1].ref:\n\tif tempjack.mate is not None: \n\t raise Failure(\"Matching jack (%s/%s) already mated\"\n\t %(tempjack.location.ref,tempjack.ref))\n\tjack.mate = tempjack\n\tbreak\n if jack.mate is None: return #no matching jack at all on part\n jack.mate.mate = jack\n jack.mate.dest = containers[-1]\n\n #unify the cables, mate takes precedence (declared first)\n if jack.cable is not None:\n if jack.mate.cable.length is None or jack.mate.cable.length < 0: \n jack.mate.cable.length = jack.cable.length\n if jack.mate.cable.label == \"\" or jack.mate.cable.label is None:\n if jack.cable.label == \"\" or jack.cable.label is None:\n\t#make up a name since none is given\n\tjack.mate.cable.label = \"%s-%s\"%\\\n\t (jack.mate.location.ref, jack.location.ref)\n\tprint \"Warning invented cable name: %s\"% jack.mate.cable.label\n else: jack.mate.cable.label = jack.cable.label\n #compare cable numbers\n if jack.cable.ref and jack.mate.cable.ref:\n if jack.cable.ref != jack.mate.cable.ref:\n\traise Failure(\"p2p cable numbers don't match for mating jacks\")\n elif not jack.mate.cable.ref:\n jack.mate.cable.ref = jack.cable.ref\n jack.mate.cable.number = jack.cable.number\n jack.cable = jack.mate.cable #unify cable references\n jack.mate.cablemaster = True\n else: jack.placeholder = True #newer jack is always the placeholder\n\n #for pins on mate (from previous lines) add autogen lines, etc. as needed\n for pin in jack.mate.pins:\n line = pin.lines['box']\n newline = Line(line.desc, \"(%s,%s)\"%(jack.ref, pin.number))\n newline.autogen = True\n newline.owner = containers[-1]\n containers[-1].lines.append(newline)\n if jack.cable is None:\n pin.lines['cable'] = newline\n else: #cable\n cableline = Line(line.desc, \"\")\n cableline.autogen = True\n cableline.owner = jack.cable\n pin.lines['cable'] = cableline\n newpin = Pin(pin.number, line.desc, jack, newline, cableline)\n jack.pins.append(newpin)\n jack.cable.lines.append(cableline)\n\ndef addPins(line):\n \"\"\"create pins (and auto-lines) for a given line\"\"\"\n for jacknum, pinnum in zip(line.jacknums, line.pinnums):\n #find jack and perform some consistency checks\n try: jack = containers[-1].jacks[containers[-1].jacks.index(jacknum)]\n except ValueError: \n raise Failure(\"unrecognized jack: %s\"%jacknum)\n lineend = 'box'\n realjack = jack\n if jack.placeholder: #jack is placeholder in direct-connected pair\n realjack = jack.mate #use the real jack...its mate\n lineend = 'cable'\n try: #test pin number\n if jack.conn.flags['alpha'] == 'N' and ((int(pinnum) > jack.conn.count \\\n\t and jack.conn.count > 0) or int(pinnum) <= 0):\n\traise Failure(\"invalid pin number: %s\"%pinnum)\n except ValueError: \n raise Failure(\"unexpected non-numeric pin: %s\"%pinnum)\n\n if jack.mate is None: #unmated, add a dangling pin (no cline yet)\n newpin = Pin(pinnum, line.desc, jack, line, None)\n if newpin not in realjack.pins: realjack.pins.append(newpin)\n else: #already mated, need to add extra stuff\n try: #see if pin has already been generated\n\tpin = realjack.pins[realjack.pins.index(pinnum)]\n except ValueError: #pin not yet generated\n\tnewline = Line(line.desc, \"(%s,%s)\"%(jack.mate.ref,pinnum))\n\tnewline.autogen = True\n\tnewline.owner = jack.mate.location\n\tjack.mate.location.lines.append(newline)\n\tif jack.cable is None: #no cable\n\t if lineend == 'box': \n\t newpin = Pin(pinnum, line.desc, realjack, line, newline)\n\t else: newpin = Pin(pinnum, line.desc, realjack, newline, line) \n\telse: #using a cable, make another new line and pin\n\t if lineend == 'cable': raise Failure('inconsistent state')\n\t cableline = Line(line.desc, \"\")\n\t cableline.autogen = True\n\t cableline.owner = jack.cable\n\t newpin = Pin(pinnum, line.desc, jack, line, cableline)\n\t newerpin = Pin(pinnum, line.desc, jack.mate, newline, cableline)\n\t jack.cable.lines.append(cableline)\n\t if newerpin not in jack.mate.pins: jack.mate.pins.append(newerpin)\n\trealjack.pins.append(newpin)\n\n else: #pin exists\n\tif not pin.lines[lineend].autogen:\n\t raise Failure(\"line conflicts for pin (%s;%s)\"%(jacknum,pinnum))\n\tjack.location.lines.remove(pin.lines[lineend])\n\tpin.desc = line.desc\n\tpin.lines[lineend] = line\n\t#other lines exist already (?), so this case is done\n\n if line in containers[-1].lines:\n raise Failure(\"line overlaps existing one\")\n containers[-1].lines.append(line)\n\ndef sedparser(filename):\n \"\"\"main function allows calls from interactive prompt, or extra cleverness\"\"\"\n startWithConnectors = True #connector list at top. make overridable by args?\n f = open(filename, 'r')\n\n #lists of used cable and jack numbers\n used_cable_nums = []\n used_jack_nums = []\n \n #main loop, red each line of the description file in turn\n linecount = 0\n for line in f:\n linecount += 1\n #print \"On line\", linecount\n line = line.strip()\n\n #CONNECTORS\n if startWithConnectors: #set to false when done\n conn = lineparser.parse(Connector, line)\n if conn is not None: #successful\n\tif conn in connectors: raise Failure(\"connector exists\", linecount)\n\tconnectors.append(conn)\n\ttry:\n\t mate = connectors[connectors.index(conn.matetype)]\n\t #check that each gender mate is reciprocated, or unused\n\t if conn.gendersMatch(mate):\n\t conn.mate = mate\n\t mate.mate = conn\n\t else: raise Failure(\"Incompatible gender mating\", linecount)\n\texcept ValueError: pass #mate not found\n elif line[0] == '*' and line == '*ENDCONNECTORLIST':\n\tstartWithConnectors = False\n\tfor c in connectors:\n\t if c.mate is None: print \"Warning: unmated connector\", c.type\n\tprint \"Info: done parsing connectors, found\", len(connectors)\n elif line != \"\":\n\traise Failure(\"Unrecognized connector\", linecount)\n \n elif line[0:4] == \"JACK\":\n jack = lineparser.parse(Jack, line)\n if jack is None: raise Failure(\"Bad jack line\", linecount)\n if jack in containers[-1].jacks:\n\traise Failure(\"non-unique jack identifier\", linecount)\n try: \n\tjack.conn = connectors[connectors.index(jack.conn_str[:-2])]\n\tif jack.conn.genders[jack.gender] == 'X':\n\t raise Failure(\"Invalid connector gender\", linecount)\n except ValueError: raise Failure(\"Non-existant connector type\", linecount)\n if jack.internal and hasattr(containers[-1], 'p2p'):\n\traise Failure(\"Cables can't have internal jacks\", linecount)\n jack.location = containers[-1]\n containers[-1].jacks.append(jack)\n try: mateJack(jack)\n except Failure, err: raise Failure(err.errstr, linecount)\n if jack.number > 0:\n\tif not jack.number in used_jack_nums:\n\t used_jack_nums.append(jack.number)\n\telif not jack.mate or not jack.placeholder:\n\t raise Failure(\"repeated global jack number %d\"%jack.number, linecount)\n if jack.cable and jack.cable.number > 0:\n\tif not jack.cable.number in used_cable_nums:\n\t used_cable_nums.append(jack.cable.number)\n\telif not jack.mate:\n\t raise Failure(\"repeated cable number %d\"%jack.cable.number, linecount)\n\n elif line[0:4] == \"LINE\":\n line = lineparser.parse(Line, line)\n if line is None: raise Failure(\"Bad line line\", linecount)\n line.owner = containers[-1]\n try: addPins(line) #catch failures and reraise with line number\n except Failure, err: raise Failure(err.errstr, linecount)\n\n elif line[0:5] == \"CABLE\":\n cable = lineparser.parse(Cable, line)\n if cable is None: raise Failure(\"Bad cable line\", linecount)\n if cable in containers: \n\traise Failure(\"cable exists: rename or use re-edit line\", linecount)\n containers.append(cable)\n try: expected.remove(cable)\n except ValueError: pass\n if cable.number > 0:\n\tif not cable.number in used_cable_nums:\n\t used_cable_nums.append(cable.number)\n\telse:\n\t raise Failure(\"repeated cable number %d\"%cable.number, linecount)\n\n elif line != \"\" and line[0] != '#': #COMPONENT\n comp = lineparser.parse(Component, line)\n if comp is None: #check if line is a re-edit command\n\ttry:\n\t containers.append(containers.pop(containers.index(line)))\n\t print \"Info: re-editing\", line\n\t continue\n\texcept ValueError: raise Failure(\"nothing found to re-edit\", linecount)\n if comp in containers: \n\traise Failure(\"component exists: use re-edit line?\", linecount)\n containers.append(comp)\n try: expected.remove(comp)\n except ValueError: pass\n if comp.partOf is not None and comp.partOf not in containers \\\n\t and comp.partOf not in expected:\n\texpected.append(Component(comp.partOf, \"expected\", None))\n\n\n #print stats, assign cable and jack numbers, check pins and mating\n for part in expected: print part.ref\n if len(expected) > 0: raise Failure(\"above parts used but not declared\", -1)\n print \"Info: done parsing, found\", len(containers), \"components and cables:\"\n\n sf = open(\"out/stats.txt\", 'w') #print stats to statfile\n sf.write(\"%10s%10s%10s\\n\" % (\"Part\", \"Jacks\", \"Lines\"))\n all_mated = True\n cable_count = 1\n jack_count = 1\n for cont in containers:\n sf.write(\"%10s%10s%10s\\n\" % (cont.ref, len(cont.jacks), len(cont.lines)))\n #assign number to unnumbered cables\n if hasattr(cont, 'number') and cont.number <= 0:\n while cable_count in used_cable_nums: cable_count += 1\n cont.number = cable_count\n cable_count += 1\n for ijack in cont.jacks:\n #check number of pins\n if ijack.conn.count > 0 and len(ijack.pins) > ijack.conn.count:\n\traise Failure(\"Jack %s jas too many pins: %d/%d\"\\\n\t %(ijack.ref,len(ijack.pins),ijack.conn.count))\n #check for mating\n if ijack.mate is None: \n\tprint (\"\\tJack %s of %s unmated\" % (ijack.ref, cont.ref))\n\tall_mated = False\n #assign number to unnumbered jacks\n if ijack.number <= 0:\n\twhile jack_count in used_jack_nums: jack_count += 1\n\tijack.number = jack_count\n\tjack_count += 1\n #assign number to unnumbered p2p cables\n if ijack.cable and ijack.cablemaster and ijack.cable.number <= 0:\n\twhile cable_count in used_cable_nums: cable_count += 1\n\tijack.cable.number = cable_count\n\tcable_count += 1\n if not all_mated: \n raise Failure(\"Not all jacks mated, check for indistinguishable mates\")\n\n################################################################################\n# main: parse the file, and then do some extra stuff\n\nif __name__ == \"__main__\":\n try:\n #run the parser\n if len(sys.argv) == 2: filename = sys.argv[1]\n else: filename = defaultfile\n print \"Parsing file:\", filename\n sedparser(filename)\n\n #outptus\n writeInfiles()\n countConnectors()\n rewriteDescription(filename)\n\n print \"\\nAll Done!\"\n sys.exit()\n except Failure, err:\n print >>sys.stderr, err\n sys.exit(1)\n\n" }, { "alpha_fraction": 0.572749674320221, "alphanum_fraction": 0.5863131880760193, "avg_line_length": 26.483051300048828, "blob_id": "f9d270539f3580ea623803d065d8592b3f545353", "content_id": "8f61d8569588004ae6007c8a92a6033d472b6f1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3245, "license_type": "no_license", "max_line_length": 103, "num_lines": 118, "path": "/stars/code/logging/logger.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"logger.h\"\n#include <fstream>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/format.hpp>\n#include <boost/filesystem/fstream.hpp>\n#include <boost/filesystem/operations.hpp>\n#include \"../parameters/manager.h\"\n#include \"../tools/timing.h\"\n\nusing namespace Logging;\nusing std::string;\nnamespace fs = boost::filesystem;\n\nLogger::Logger(string name_)\n{\n construct(name_, false);\n}\n\nLogger::Logger(string name_, bool writing_to_stdout_)\n{\n construct(name_, writing_to_stdout_);\n}\n\nvoid Logger::construct(string name_, bool writing_to_stdout_)\n{\n age = new (std::nothrow) Tools::Timer;\n timer_since_last_flush = new (std::nothrow) Tools::Timer;\n my_stream = new (std::nothrow) std::ofstream;\n name = name_;\n writing_to_stdout = writing_to_stdout_;\n flush_period = 5.0;\n}\n\nLogger::~Logger()\n{\n my_stream->flush();\n delete age;\n delete timer_since_last_flush;\n try {\n my_stream->close();\n delete my_stream;\n } catch (const std::exception&) {}\n}\n\nvoid Logger::init(Parameters::Manager& params, boost::posix_time::ptime& birthtime, Tools::Timer& age_)\n{\n *age = age_;\n\n string output_dir;\n output_dir = params.general.try_get(\"main.output_dir\", string(\"D:\\\\\"));\t\t\n string dirname = (boost::format(\"%04d-%02d-%02d\")\n % birthtime.date().year()\n % int(birthtime.date().month())\n % birthtime.date().day()\n ).str();\n if (!fs::exists(output_dir)) {\n output_dir = \"\";\n }\n fs::path logs_dir = fs::path(output_dir) / \"logs\";\n if (!fs::exists(logs_dir)) {\n fs::create_directory(logs_dir);\n }\n fs::path dir = fs::path(output_dir) / \"logs\" / dirname;\n if (!fs::exists(dir)) {\n fs::create_directory(dir);\n }\n string leaf_filename = (boost::format(\"%04d-%02d-%02d--%02d-%02d-%02d_%s.log\")\n % birthtime.date().year()\n % int(birthtime.date().month())\n % birthtime.date().day()\n % birthtime.time_of_day().hours()\n % birthtime.time_of_day().minutes()\n % birthtime.time_of_day().seconds()\n % name\n ).str();\n string filename = (dir / leaf_filename).string();\t//changed from file_string() to string()\n\n my_stream->open(filename.c_str(), std::fstream::out | std::fstream::app);\n}\n\nvoid Logger::log(string info)\n{\n double time = age->time();\n (*my_stream) << format(\"%10.3f %4.4s - \")%time%name << info << \"\\n\";\n if (writing_to_stdout) {\n std::cout << format(\"%10.3f %4.4s - \")%time%name << info << \"\\n\";\n }\n update();\n}\n\nvoid Logger::log(boost::format& info)\n{\n double time = age->time();\n (*my_stream) << format(\"%10.3f %4.4s - \")%time%name << info << \"\\n\";\n if (writing_to_stdout) {\n std::cout << format(\"%10.3f %4.4s - \")%time%name << info << \"\\n\";\n }\n update();\n}\n\nvoid Logger::flush()\n{\n timer_since_last_flush->start();\n my_stream->flush();\n}\n\nvoid Logger::update()\n{\n if (timer_since_last_flush->time() > flush_period) {\n flush();\n }\n}\n\n" }, { "alpha_fraction": 0.7188365459442139, "alphanum_fraction": 0.7243767380714417, "avg_line_length": 18.513513565063477, "blob_id": "bbe29936f4da96257a39872d4cf73b84b251645a", "content_id": "1b7146a604209d0fe5cde2c6bf4e5a9202a4598d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 723, "license_type": "no_license", "max_line_length": 73, "num_lines": 37, "path": "/stars/code/shared/image/matching_progress.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__IMAGE__MATCHING_PROGRESS_H\n#define SHARED__IMAGE__MATCHING_PROGRESS_H\n\n#include \"../circular_buffer.h\"\n\nnamespace Shared\n{\nnamespace Image\n{\n\nclass MatchingProgress\n{\n public:\n MatchingProgress();\n MatchingProgress& operator=(const MatchingProgress& rhs);\n void init(Parameters::Manager& params);\n\n int counter_stars;\n int triplet_counter;\n double progress;\n};\n\n// writes: solver\n// reads: main\nextern Shared::CircularBuffer <MatchingProgress> matching_progress;\n\n}\n}\n\n#endif\n" }, { "alpha_fraction": 0.7030360698699951, "alphanum_fraction": 0.7172675728797913, "avg_line_length": 33, "blob_id": "2e43fe882a05a8329abad0ae4a632b70aa5f4215", "content_id": "788a3d736413a3885c31e09cd452d2461b26a087", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1054, "license_type": "no_license", "max_line_length": 119, "num_lines": 31, "path": "/balloon_cam/CameraAlignment.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "// CameraAlignment.cpp : main project file.\n\n#include \"stdafx.h\"\n#include \"cameraCommunicator.h\"\nusing namespace System;\n\nint main(array<System::String ^> ^args)\n{\n\tCamera camera = Camera();//opens a camera\n\tif(!camera.open()){//checks to ensure it's open\n\t\treturn -1;\n\t}\n\tLocator locator = Locator(camera.getXSize(), camera.getYSize(), camera.getPixelSize(), 10, &camera);//starts a locator\n\tCameraCommunicator communicator = CameraCommunicator(&locator);//and a communicator\n\tstd::string hostname = \"hog\\n\";\n\tcommunicator.addConnection(hostname);//adds a connection to the server computer\n\tprintf(\"connection added\\n\");\n\tSleep(30000);//waits a while\n\t\n\tcommunicator.removeConnection(hostname);//removes the connection\n\tvoid* pointer;\n\tblob data;\n\tfor(int i = 0; i<10; i++){\n\t\tSleep(1000);\n\t\tpointer = camera.capture();\n\t\tdata = locator.locate(pointer);\n\t\tprintf(\"blob found at: %d, %d, size: %d\\n\", data.centroid.x, data.centroid.y, data.size);\n\t}\n\tcamera.closeCamera();//closes the camera\n\tsystem(\"Pause\");//waits so that you can look at the output\n}\n" }, { "alpha_fraction": 0.6894150376319885, "alphanum_fraction": 0.6949860453605652, "avg_line_length": 20.08823585510254, "blob_id": "308997eb435a246addd957283c6d5e6242dcc6d5", "content_id": "84379b5e4ee1c50d4cdbe14a100e7825790f7a26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 719, "license_type": "no_license", "max_line_length": 73, "num_lines": 34, "path": "/stars/code/displaying/dynamic_value.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__DYNAMIC_VALUE_H\n#define DISPLAYING__DYNAMIC_VALUE_H\n\n#include <string>\n#include \"color.h\"\n\nnamespace Displaying\n{\n class DynamicValue;\n}\n\nclass Displaying::DynamicValue\n{\n public:\n DynamicValue();\n void init(std::string name_);\n void set_value(double value_, int precision);\n void set_value(double value_, std::string units, int precision);\n void set_value(std::string value_);\n\n std::string name;\n std::string value;\n bool known;\n Color color;\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.7281508445739746, "alphanum_fraction": 0.7341306209564209, "avg_line_length": 29.619718551635742, "blob_id": "630b175fedc40400ee913ccaec2431f4ecf21fcc", "content_id": "39cae4e3cd5123acbf73a7fd1389089cb97920f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2174, "license_type": "no_license", "max_line_length": 100, "num_lines": 71, "path": "/starcam/mycam.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//\n// C++ Interface: mycam\n//\n// Description: expasion upon the CSBIGCam class to add more USB support\n//\n// Author: Steve Benton <[email protected]>, (C) 2006\n//\n#ifndef STDMYCAM_H\n#define STDMYCAM_H\n\n#include <string>\n#include \"csbigcam.h\"\n#include \"sbigudrv.h\"\n#include \"clensadapter.h\"\n#include \"blobimage.h\"\n#include \"camconfig.h\"\n\nusing namespace std;\n\n/**\n\t@author Steve Benton <[email protected]>\n*/\n\nclass MyCam : public CSBIGCam\n{\nprivate:\n\tint m_nUSBNum; //the number of the USB port: one of 0, 1, 2, 3\n\tCLensAdapter m_cAdapter; //the adapter for the lens used on the camera\n\tint m_nPictureInterval; //number of milliseconds between pictures, 0 for triggered\n\tunsigned int m_nFocusResolution; //autofocus will step by (totalFocalRange)/m_nFocusResolution\n\tunsigned int m_nFocusRange; //autofocus will step through (totalFocalRange)/m_nFocusRange\n\tunsigned long int m_iFrame;//frame number, increments each grabImage\n\n\t\npublic:\n\t//constructors/destructor\n MyCam();\n\tMyCam(OpenDeviceParams odp);\n\tMyCam(SBIG_DEVICE_TYPE dev);\n ~MyCam();\n\t\n\t//overwritten functions from CSBIGCam\n\tvoid Init(MyCamConfigParams params=defaultCameraParams);\n\tPAR_ERROR GrabImage(BlobImage *img, SBIG_DARK_FRAME dark);\n\tPAR_ERROR StartExposure(SHUTTER_COMMAND shutterState);\n\tPAR_ERROR EndExposure(void);\n\t\n\t//USB utility functions\n\tPAR_ERROR QueryUSB(QueryUSBResults &qur);\n\tPAR_ERROR OpenUSBDevice(int num);\n\t\n\t//lens adapter functions\n\t//focus images go to viewer:\n\t//LENS_ERROR autoFocus(BlobImage *img, int forced = 0, const char* path = NULL);\n\t//focus images get saved:\n\tLENS_ERROR autoFocus(BlobImage *img, int forced = 0, string path = \"/data/rawdir\");\n\tCLensAdapter* getLensAdapter() { return &m_cAdapter; }\n\t\n\t//accesors\n\tvoid setPictureInterval(int in_interval) { m_nPictureInterval = (in_interval >= 0)?in_interval:0; }\n\tint getPictureInterval(void) { return m_nPictureInterval; }\n\tvoid setFocusResolution(unsigned int res) { m_nFocusResolution = res; }\n\tunsigned int getFocusResolution(void) { return m_nFocusResolution; }\n\tvoid setFocusRange(unsigned int rng) { m_nFocusRange = rng; }\n\tunsigned int getFocusRange(void) { return m_nFocusRange; }\n\n\tstring getSerialNum();\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.6073316335678101, "alphanum_fraction": 0.6230176091194153, "avg_line_length": 29.244768142700195, "blob_id": "294188827a783810aac5cbf8f17fd39b31864b1a", "content_id": "880e8cc2cbc9efff931fba3412232d62f0450662", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 52021, "license_type": "no_license", "max_line_length": 153, "num_lines": 1720, "path": "/liblinklist/linklist_compress.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * linklist_compress.c: \n *\n * This software is copyright \n * (C) 2015-2018 University of Toronto, Toronto, ON\n *\n * This file is part of the SuperBIT project, modified and adapted for BLAST-TNG.\n *\n * linklist 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 2 of the License, or\n * (at your option) any later version.\n *\n * linklist 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Jan 25, 2018 by Javier Romualdez\n */\n\n\n#include <math.h>\n#include <arpa/inet.h> // socket stuff\n#include <netinet/in.h> // socket stuff\n#include <stdio.h> // socket stuff\n#include <sys/types.h> // socket types\n#include <sys/socket.h> // socket stuff\n#include <sys/stat.h>\n#include <dirent.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <signal.h>\n#include <stdlib.h>\n#include <string.h>\n#include <errno.h>\n#include <pthread.h> // threads\n#include <openssl/md5.h>\n#include <float.h>\n\n#include \"linklist.h\"\n#include \"linklist_compress.h\"\n\n#ifdef __cplusplus\n\nextern \"C\"{\n\n#endif\n\nint decimationCompress(uint8_t * data_out, struct link_entry * le, uint8_t * data_in);\nint decimationDecompress(uint8_t * data_out, struct link_entry * le, uint8_t * data_in);\n\nextern int (*linklist_info)(const char *, ...);\nextern int (*linklist_err)(const char *, ...);\nextern int (*linklist_warn)(const char *, ...);\nextern int (*linklist_fatal)(const char *, ...);\n\nextern superframe_entry_t block_entry;\nextern superframe_entry_t stream_entry;\n\n#define LL_CRC_POLY 0x1021\nuint16_t *ll_crctable = NULL;\n\n/* block header (12 bytes)\n * ----------------\n * [0-3] = identifier (0x80000000 => file)\n * [4-5] = size of data in packet [bytes]\n * [6-8] = packet number (i)\n * [9-11] = total number of packets (n)\n */\n// generates the block header in the buffer\nint make_block_header(uint8_t * buffer, uint32_t id, uint16_t size, uint32_t i, uint32_t n)\n{\n i &= 0x00ffffff;\n n &= 0x00ffffff;\n\n memcpy(buffer+0, &id, 4); // ID\n memcpy(buffer+4, &size, 2); // size of data in packet\n memcpy(buffer+6, &i, 3); // packet number\n memcpy(buffer+9, &n, 3); // number of packets\n\n return PACKET_HEADER_SIZE;\n}\n\n// generates the block header in the buffer\nint read_block_header(uint8_t * buffer, uint32_t *id, uint16_t *size, uint32_t *i, uint32_t *n)\n{\n *i &= 0x00ffffff;\n *n &= 0x00ffffff;\n\n memcpy(id, buffer+0, 4); // ID\n memcpy(size, buffer+4, 2); // size of data in packet\n memcpy(i, buffer+6, 3); // packet number\n memcpy(n, buffer+9, 3); // number of packets\n\n return PACKET_HEADER_SIZE;\n}\n\n// generates and returns a CRC table for linlist checksum validation \nuint16_t *mk_ll_crctable(uint16_t poly, uint16_t (*crcfn)(uint16_t, uint16_t, uint16_t))\n{\n uint16_t *ll_crctable;\n int i;\n if ((ll_crctable = (uint16_t *)malloc(256*sizeof(unsigned))) == NULL) {\n return NULL;\n }\n for (i = 0; i < 256; i++) {\n ll_crctable[i] = (*crcfn)(i, poly, 0);\n }\n return ll_crctable;\n}\n\n// generator for CRC table\nuint16_t ll_crchware(uint16_t data, uint16_t genpoly, uint16_t accum)\n{\n static int i;\n data <<= 8;\n for (i = 8; i > 0; i--) {\n if ((data ^ accum) & 0x8000) {\n accum = (accum << 1) ^ genpoly;\n } else {\n accum <<= 1;\n }\n data <<= 1;\n }\n return accum;\n}\n\n// checks/generates a CRC value for received/sent message\nvoid ll_crccheck(uint16_t data, uint16_t *accumulator, uint16_t *ll_crctable)\n{\n *accumulator = (*accumulator << 8) ^ ll_crctable[(*accumulator >> 8) ^ data];\n}\n\nblock_t * block_find_by_name(linklist_t * ll, char * blockname) {\n unsigned int j;\n // find the block\n for (j = 0; j < ll->num_blocks; j++) {\n if (strcmp(blockname, ll->blocks[j].name) == 0) {\n return &ll->blocks[j];\n }\n }\n return NULL;\n}\nstream_t * stream_find_by_name(linklist_t * ll, char * streamname) {\n unsigned int j;\n // find the stream\n for (j = 0; j < ll->num_streams; j++) {\n if (strcmp(streamname, ll->streams[j].name) == 0) {\n return &ll->streams[j];\n }\n }\n return NULL;\n}\n\n// get a list of pointers to all the streams with a given name (null terminated)\nstream_t ** linklist_get_streamlist(linklist_t ** ll_array, char * streamname) {\n int i;\n int num = 0;\n stream_t ** streamlist = (stream_t **) calloc(MAX_NUM_LINKLIST_FILES, sizeof(stream_t *));\n for (i=0; ll_array[i]; i++) {\n if ((streamlist[num] = stream_find_by_name(ll_array[i], streamname))) num++;\n } \n streamlist[num] = NULL;\n return streamlist;\n}\n\n\nvoid close_block_fp(block_t * block) {\n if (!block->fp) return;\n FILE *fp = block->fp;\n block->fp = NULL;\n fclose(fp);\n}\n\nvoid close_stream_fp(stream_t * stream) {\n if (!stream->fp) return;\n FILE *fp = stream->fp;\n stream->fp = NULL;\n fclose(fp);\n}\n\n#pragma pack(push, 1) // structure packing aligns at 1 byte (no padding)\nstruct preempt_data {\n uint32_t serial;\n char filename[LINKLIST_SHORT_FILENAME_SIZE];\n};\n#pragma pack(pop) // undo custom structure packing\n\nint linklist_send_file_by_block(linklist_t * ll, char * blockname, char * filename, \n int32_t id, int flags) {\n return linklist_send_file_by_block_ind(ll, blockname, filename, id, flags, 0, 0);\n}\n\nint linklist_send_file_by_block_ind(linklist_t * ll, char * blockname, char * filename, \n int32_t id, int flags, unsigned int i, unsigned int n) {\n if (!ll) {\n linklist_err(\"linklist_send_file_by_block_ind: Invalid linklist given\\n\");\n return 0;\n }\n\n // find the block in the linklist\n block_t * theblock = block_find_by_name(ll, blockname);\n if (!theblock) {\n linklist_err(\"linklist_send_file_by_block_ind: Block \\\"%s\\\" not found in linklist \\\"%s\\\"\\n\", blockname, ll->name);\n return 0;\n }\n\n // check to see if the previous send is done\n if (!(flags & BLOCK_OVERRIDE_CURRENT) && (theblock->i < theblock->n)) {\n linklist_info(\"linklist_send_file_by_block_ind: Previous transfer for block \\\"%s\\\" is incomplete.\\n\", blockname);\n return 0;\n }\n\n // cancel any current block packetization (n < i sentinel condition)\n theblock->n = 0;\n theblock->i = 1;\n\n // check for any dangling file pointers\n if (theblock->fp) {\n close_block_fp(theblock);\n }\n \n // open the file\n FILE * fp = fopen(filename, \"rb+\");\n if (!fp) {\n linklist_err(\"linklist_send_file_by_block_ind: File \\\"%s\\\" not found\\n\", filename);\n return 0;\n }\n \n // get the size of the file\n unsigned int filesize = 0;\n fseek(fp, 0L, SEEK_END);\n filesize = ftell(fp);\n fseek(fp, 0L, SEEK_SET);\n\n // deal with empty files\n if (!filesize) {\n linklist_err(\"linklist_send_file_by_block_ind: File \\\"%s\\\" is empty\\n\", filename);\n return 0;\n }\n\n uint32_t n_total = (filesize-1)/(theblock->le->blk_size-PACKET_HEADER_SIZE)+1;\n if (n_total & 0xff000000) {\n linklist_err(\"linklist_send_file_by_block_ind: File \\\"%s\\\" is too large\\n\", filename);\n return 0;\n }\n\n // check the preempt flag for send aux data before the file\n if (flags & BLOCK_PREEMPT_FILE) {\n struct preempt_data * pd = (struct preempt_data *) theblock->buffer;\n memset(pd, 0, sizeof(struct preempt_data));\n\n pd->serial = BLOCK_PREEMPT_ID; \n int i;\n for (i=strlen(filename)-1; i>=0; i--) {\n if (filename[i] == '/') break;\n }\n strncpy(pd->filename, filename+i+1, LINKLIST_SHORT_FILENAME_SIZE-1);\n }\n\n // set the block variables to initialize transfer\n theblock->fp = fp; // non-null file desc indicates that we want to read data from file\n strcpy(theblock->filename, filename); \n theblock->num = 0;\n theblock->id = id;\n if (!(flags & BLOCK_NO_DOWNSTREAM_FILE)) {\n theblock->id |= BLOCK_FILE_MASK; // the flag/mask indicates that we want a file on the ground\n }\n theblock->curr_size = filesize;\n theblock->flags = flags;\n if (!n && !i) { // set the whole transfer\n theblock->i = 0;\n theblock->n = n_total;\n } else { // set the potential partial transfer\n theblock->i = MIN(MIN(i, n), n_total);\n theblock->n = MIN(n, n_total);\n }\n\n linklist_info(\"File \\\"%s\\\" (%d B == %d pkts) sent to linklist \\\"%s\\\" (i=%d, n=%d)\\n\", filename, filesize, n_total, ll->name, theblock->i, theblock->n);\n\n return 1;\n}\n\nint assign_file_to_streamlist(stream_t ** streamlist, char * filename, int offset, int whence) {\n int i;\n int retval = 0;\n for (i=0; streamlist[i]; i++) {\n retval += assign_file_to_stream(streamlist[i], filename, offset, whence);\n }\n return retval;\n}\n\nint remove_file_from_streamlist(stream_t ** streamlist) {\n int i;\n int retval = 0;\n for (i=0; streamlist[i]; i++) {\n retval += remove_file_from_stream(streamlist[i]);\n }\n return retval;\n}\n\nint seek_file_in_streamlist(stream_t ** streamlist, int offset, int whence) {\n int i;\n int retval = 0;\n for (i=0; streamlist[i]; i++) {\n retval += seek_file_in_stream(streamlist[i], offset, whence);\n }\n return retval;\n}\n\nvoid write_next_streamlist(stream_t ** streamlist, uint8_t * buffer, unsigned int bsize, unsigned int flags) {\n int i;\n for (i=0; streamlist[i]; i++) {\n write_next_stream(streamlist[i], buffer, bsize, flags);\n }\n}\n\nvoid stop_current_streamlist(stream_t ** streamlist) {\n int i;\n for (i=0; streamlist[i]; i++) {\n stop_current_stream(streamlist[i]);\n }\n}\n\nint linklist_assign_file_to_stream(linklist_t * ll, char * streamname, char * filename, \n int offset, int whence) {\n if (!ll) {\n linklist_err(\"linklist_assign_file_to_stream: Invalid linklist given\\n\");\n return 0;\n }\n\n // find the block in the linklist\n stream_t * thestream = stream_find_by_name(ll, streamname);\n if (!thestream) {\n linklist_err(\"linklist_assign_file_to_stream: Stream \\\"%s\\\" not found in linklist \\\"%s\\\"\\n\", streamname, ll->name);\n return 0;\n }\n\n return assign_file_to_stream(thestream, filename, offset, whence);\n}\n\nint assign_file_to_stream(stream_t * thestream, char * filename, int offset, int whence) {\n if (thestream->fp) {\n close_stream_fp(thestream);\n }\n \n // open the file\n FILE * fp = fopen(filename, \"rb+\");\n if (!fp) {\n linklist_err(\"linklist_assign_file_to_stream: File \\\"%s\\\" not found\\n\", filename);\n return 0;\n }\n \n // seek to specified location \n fseek(fp, offset, whence);\n\n // assign the stream the file descriptor\n strcpy(thestream->filename, filename); // copy the filename stripped of path\n thestream->fp = fp; \n\n return 1;\n}\n\nint linklist_remove_file_from_stream(linklist_t * ll, char * streamname) {\n if (!ll) {\n linklist_err(\"linklist_assign_file_to_stream: Invalid linklist given\\n\");\n return 0;\n }\n\n // find the block in the linklist\n stream_t * thestream = stream_find_by_name(ll, streamname);\n if (!thestream) {\n linklist_err(\"linklist_assign_file_to_stream: Stream \\\"%s\\\" not found in linklist \\\"%s\\\"\\n\", streamname, ll->name);\n return 0;\n }\n return remove_file_from_stream(thestream);\n}\n\nint remove_file_from_stream(stream_t * thestream) {\n if (thestream->fp) {\n close_stream_fp(thestream);\n thestream->filename[0] = '\\0';\n }\n return 1;\n}\n\nint linklist_seek_file_in_stream(linklist_t * ll, char * streamname, int offset, int whence) {\n if (!ll) {\n linklist_err(\"linklist_seek_file_in_stream: Invalid linklist given\\n\");\n return 0;\n }\n\n // find the block in the linklist\n stream_t * thestream = stream_find_by_name(ll, streamname);\n if (!thestream) {\n linklist_err(\"linklist_seek_file_in_stream: Stream \\\"%s\\\" not found in linklist \\\"%s\\\"\\n\", streamname, ll->name);\n return 0;\n }\n return seek_file_in_stream(thestream, offset, whence);\n}\n\nint seek_file_in_stream(stream_t * thestream, int offset, int whence) {\n int retval = 0;\n if (thestream->fp) {\n retval = fseek(thestream->fp, offset, whence);\n }\n return retval;\n}\n\nvoid linklist_write_next_stream(linklist_t * ll, char * streamname, uint8_t * buffer, unsigned int bsize, unsigned int flags) {\n if (!ll) {\n linklist_err(\"linklist_write_next_stream: Invalid linklist given\\n\");\n return;\n }\n\n // find the block in the linklist\n stream_t * thestream = stream_find_by_name(ll, streamname);\n if (!thestream) {\n linklist_err(\"linklist_write_next_stream: Stream \\\"%s\\\" not found in linklist \\\"%s\\\"\\n\", streamname, ll->name);\n return;\n }\n write_next_stream(thestream, buffer, bsize, flags);\n}\n\nvoid write_next_stream(stream_t * stream, uint8_t * buffer, unsigned int bsize, unsigned int flags) {\n unsigned int newnext = 1-stream->curr;\n substream_t * ss = &stream->buffers[newnext]; \n\n // do not overwrite data that must be sent\n if ((ss->flags & STREAM_MUST_SEND) && !(flags & STREAM_MUST_SEND)) return;\n \n // expand the buffer if necessary\n if (ss->alloc_size < bsize) {\n ss->alloc_size = bsize;\n ss->buffer = (uint8_t *) realloc(ss->buffer, ss->alloc_size);\n }\n\n // copy the data to the buffer\n memcpy(ss->buffer, buffer, bsize);\n ss->data_size = bsize;\n ss->flags = flags;\n ss->loc = 0;\n\n // queue the next buffer for writing\n stream->next = newnext; // only writing functions can modify stream->next\n}\n\nvoid linklist_stop_current_stream(linklist_t * ll, char * streamname) {\n if (!ll) {\n linklist_err(\"linklist_stop_current_stream: Invalid linklist given\\n\");\n return;\n }\n\n // find the block in the linklist\n stream_t * thestream = stream_find_by_name(ll, streamname);\n if (!thestream) {\n linklist_err(\"linklist_stop_current_stream: Stream \\\"%s\\\" not found in linklist \\\"%s\\\"\\n\", streamname, ll->name);\n return;\n }\n stop_current_stream(thestream);\n}\n\n// sets the current location to the data size to start the next stream (cancelling the current one)\nvoid stop_current_stream(stream_t * thestream) {\n int curr = thestream->curr;\n substream_t * ss = &thestream->buffers[curr];\n ss->loc = ss->data_size;\n}\n\n// randomizes/unrandomizes a buffer of a given size using a given seed\nuint8_t randomized_buffer(uint8_t * buffer, unsigned int bufsize, unsigned int seed)\n{\n srand(seed);\n unsigned int i = 0;\n unsigned int sum = 0;\n for (i = 0; i < bufsize; i++) {\n buffer[i] ^= rand();\n sum ^= buffer[i];\n }\n return sum;\n}\n\n// allocates the 1 Hz superframe needed for linklist compression\nuint8_t * allocate_superframe(superframe_t * superframe)\n{\n // allocate data and superframe offsets\n if (!superframe || !superframe->size) {\n linklist_err(\"Cannot allocate superframe\");\n return NULL;\n }\n\n uint8_t * ptr = (uint8_t *) calloc(1, superframe->size);\n\n return ptr;\n}\n\n/*\n * compress_linklist_internal\n *\n * An implementation of compress_linklist that uses an internal buffer to store\n * compressed data. Compression only occurs the data id (arg 1) is different\n * from the last time the function is called. This is useful in cases where \n * multiple routines are compressing the same linklist so that the same linklist \n * isn't compressed multiple times unnecessarily for the same data.\n */\nint compress_linklist_internal(uint64_t id, linklist_t * ll, uint8_t *buffer_in) {\n return compress_linklist_internal_opt(id, ll, buffer_in, UINT32_MAX, 0);\n}\n\nint compress_linklist_internal_opt(uint64_t id, linklist_t * ll, uint8_t *buffer_in, uint32_t maxsize, int flags) {\n // allocate the buffer if necessary\n if (!ll->internal_buffer) {\n ll->internal_buffer = (uint8_t *) calloc(1, ll->superframe->size);\n }\n\n // only compress data for new id \n if (ll->internal_id == id) return 0;\n ll->internal_id = id;\n\n return compress_linklist_opt(ll->internal_buffer, ll, buffer_in, maxsize, flags);\n}\n\n/**\n * compress_linklist\n * \n * Uses default options for compress_linklist_opt (see below) \n */\nint compress_linklist(uint8_t *buffer_out, linklist_t * ll, uint8_t *buffer_in)\n{\n return compress_linklist_opt(buffer_out, ll, buffer_in, UINT32_MAX, 0);\n}\n\n/**\n * compress_linklist_opt\n * \n * Selects entries from and compresses a superframe according to the provide\n * linklist format. Return positive number if non-zero data was written.\n * -> buffer_out: buffer in which compressed frame will be written.\n * -> ll: pointer to linklist specifying compression and entry selection\n * -> buffer_in: pointer to the superframe to be compressed. \n */\nint compress_linklist_opt(uint8_t *buffer_out, linklist_t * ll, uint8_t *buffer_in, uint32_t maxsize, int flags)\n{\n\n (void) maxsize; // unsued for now\n \n // allocate crc table if necessary\n if (ll_crctable == NULL)\n {\n if((ll_crctable = mk_ll_crctable((unsigned short)LL_CRC_POLY,ll_crchware)) == NULL)\n {\n linklist_fatal(\"mk_ll_crctable() memory allocation failed\\n\");\n }\n } \n\n unsigned int i,j;\n\n unsigned int tlm_in_start = 0;\n unsigned int tlm_out_start = 0;\n unsigned int tlm_out_size = 0;\n uint8_t * tlm_in_buf, * tlm_out_buf;\n uint8_t tlm_comp_type = 0;\n struct link_entry * tlm_le;\n uint16_t checksum = 0;\n uint8_t retval = 0;\n\n // check validity of buffers\n if (!buffer_in) {\n linklist_err(\"buffer_in is NULL\");\n return 0;\n }\n if (!buffer_out) {\n linklist_err(\"buffer_out is NULL\");\n return 0;\n }\n\n for (i=0;i<ll->n_entries;i++) {\n tlm_le = &(ll->items[i]);\n tlm_out_start = tlm_le->start;\n tlm_out_buf = buffer_out+tlm_out_start;\n\n if (tlm_le->tlm == NULL) { // checksum field\n if (!(flags & LL_IGNORE_CHECKSUM)) {\n memcpy(tlm_out_buf+0,((uint8_t*)&checksum)+1,1);\n memcpy(tlm_out_buf+1,((uint8_t*)&checksum)+0,1);\n for (j=0;j<2;j++) ll_crccheck(tlm_out_buf[j],&checksum,ll_crctable); // check the checksum\n if (checksum != 0) {\n linklist_err(\"compress_linklist: invalid checksum generated\\n\");\n }\n //linklist_info(\"Compressed checksum result for %s: %d 0x%x\\n\",name,i,checksum);\n }\n checksum = 0; // reset checksum for next block\n } else { // normal field\n if (tlm_le->tlm == &block_entry) { // data block field\n block_t * theblock = linklist_find_block_by_pointer(ll, tlm_le);\n if (theblock) packetize_block(theblock, tlm_out_buf);\n else linklist_err(\"Could not find block in linklist \\\"%s\\\"\\n\", ll->name);\n } else if (tlm_le->tlm == &stream_entry) { // data stream field\n stream_t * thestream = linklist_find_stream_by_pointer(ll, tlm_le);\n if (thestream) packetize_stream(thestream, tlm_out_buf);\n else linklist_err(\"Could not find stream in linklist \\\"%s\\\"\\n\", ll->name);\n } else { // just a normal field \n tlm_comp_type = tlm_le->comp_type;\n tlm_in_start = tlm_le->tlm->start;\n tlm_in_buf = buffer_in+tlm_in_start;\n if (tlm_comp_type != NO_COMP) { // compression\n (*compRoutine[tlm_comp_type].compressFunc)(tlm_out_buf,tlm_le,tlm_in_buf);\n } else {\n decimationCompress(tlm_out_buf,tlm_le,tlm_in_buf);\n }\n }\n\n // update checksum\n tlm_out_size = tlm_le->blk_size;\n for (j=0;j<tlm_out_size;j++) {\n ll_crccheck(tlm_out_buf[j],&checksum,ll_crctable);\n retval |= tlm_out_buf[j]; // retval is whether or not there is nonzero data\n }\n }\n }\n return retval;\n}\n\n\nuint8_t * buffer_save = NULL;\n\nint fill_linklist_with_saved(linklist_t * req_ll, unsigned int p_start, unsigned int p_end, uint8_t *buffer_out)\n{\n unsigned int i, k;\n struct link_entry * tlm_le = NULL;\n unsigned int tlm_out_start;\n unsigned int loc1, loc2;\n unsigned int tlm_out_num;\n unsigned int tlm_size;\n unsigned int tlm_out_skip;\n\n for (i=p_start;i<p_end;i++) { \n tlm_le = &(req_ll->items[i]);\n if (tlm_le->tlm != NULL) { \n if ((tlm_le->tlm != &block_entry) && (tlm_le->tlm != &stream_entry)) { // do not fill extended items (blocks, streams)\n tlm_out_start = tlm_le->tlm->start;\n tlm_out_skip = tlm_le->tlm->skip;\n tlm_out_num = tlm_le->tlm->spf;\n tlm_size = get_superframe_entry_size(tlm_le->tlm);\n // linklist_info(\"Fixing %s (start = %d)\\n\",tlm_le->tlm->field,tlm_out_start);\n for (k=0;k<tlm_out_num;k++) { \n loc1 = tlm_out_skip*k;\n loc2 = tlm_out_skip*(tlm_out_num-1);\n memcpy(buffer_out+tlm_out_start+loc1, buffer_save+tlm_out_start+loc2, tlm_size);\n }\n }\n //memset(buffer_out+tlm_le->tlm->start,0,tlm_le->tlm->size*tlm_le->tlm->num);\n }\n }\n return i;\n}\n\n/*\n * decompress_linklist_internal\n *\n * An implementation of decompress_linklist that uses an internal buffer to store\n * decompressed data. Decompression only occurs the data id (arg 1) is different\n * from the last time the function is called. This is useful in cases where \n * multiple routines are decompressing the same linklist so that the same linklist \n * isn't decompressed multiple times unnecessarily for the same data.\n */\ndouble decompress_linklist_internal(uint64_t id, linklist_t * ll, uint8_t *buffer_in) {\n return decompress_linklist_internal_opt(id, ll, buffer_in, UINT32_MAX, 0);\n}\n\ndouble decompress_linklist_internal_opt(uint64_t id, linklist_t * ll, uint8_t *buffer_in, \n uint32_t maxsize, int flags) {\n // allocate the buffer if necessary\n if (!ll->internal_buffer) {\n ll->internal_buffer = (uint8_t *) calloc(1, ll->superframe->size);\n }\n\n // only decompress data for new id \n if (ll->internal_id == id) return 0;\n ll->internal_id = id;\n\n return decompress_linklist_opt(ll->internal_buffer, ll, buffer_in, maxsize, flags);\n}\n\n/**\n * decompress_linklist\n *\n * Uses defaults for decompress_linklist_opt (see below).\n */\ndouble decompress_linklist(uint8_t * buffer_out, linklist_t * ll, uint8_t * buffer_in)\n{\n return decompress_linklist_opt(buffer_out, ll, buffer_in, UINT32_MAX, 0);\n}\n\n/**\n * decompress_linklist_opt\n * \n * Selects entries from and compresses a superframe according to the provide\n * linklist format.\n * -> buffer_out: buffer in which decompressed superframe will be written.\n If NULL, the buffer assigned to the linklist via\n assign_superframe_to_linklist will be used.\n * -> ll: pointer to linklist specifying compression and entry selection\n * -> buffer_in: pointer to the compressed frame to be decompressed. \n * -> maxsize: the maximum size of the input buffer which may be less than\n */\ndouble decompress_linklist_opt(uint8_t *buffer_out, linklist_t * ll, uint8_t *buffer_in, uint32_t maxsize, int flags)\n{\n // allocate crc table if necessary\n if (ll_crctable == NULL)\n {\n if((ll_crctable = mk_ll_crctable((unsigned short)LL_CRC_POLY,ll_crchware)) == NULL)\n {\n linklist_fatal(\"mk_ll_crctable() memory allocation failed\\n\");\n }\n } \n\n superframe_t * superframe = ll->superframe;\n\n unsigned int i, j;\n\n unsigned int tlm_in_start = 0;\n unsigned int tlm_out_start = 0;\n unsigned int tlm_in_size = 0;\n uint8_t * tlm_in_buf, * tlm_out_buf;\n uint8_t tlm_comp_type = 0;\n struct link_entry * tlm_le;\n unsigned int p_start = 0, p_end = 0;\n uint16_t checksum = 0;\n uint16_t prechecksum = 0;\n uint16_t sumcount = 0;\n double ret = 0, tot = 0;\n\n // check validity of buffers\n if (!buffer_out) {\n linklist_err(\"buffer_out is NULL\");\n return 0;\n }\n if (!buffer_in) {\n linklist_err(\"buffer_in is NULL\");\n return 0;\n }\n\n if (buffer_save == NULL) buffer_save = (uint8_t *) calloc(1, superframe->size);\n\n // extract the data to the full buffer\n for (j=0; j<ll->n_entries; j++) {\n tlm_le = &(ll->items[j]);\n tlm_in_size = tlm_le->blk_size;\n tlm_in_start = tlm_le->start;\n tlm_in_buf = buffer_in+tlm_in_start;\n\n // update checksum\n for (i=0; i<tlm_in_size; i++) {\n ll_crccheck(tlm_in_buf[i],&checksum,ll_crctable);\n prechecksum |= *(uint16_t *) &tlm_in_buf[i];\n }\n\n p_end = j;\n\n if (tlm_le->tlm == NULL) { // found a checksum field\n if (tlm_in_start > maxsize) { // max. input buffer size; the rest assumed to be garbage\n fill_linklist_with_saved(ll, p_start, p_end, buffer_out);\n break;\n } else if (checksum && !(flags & LL_IGNORE_CHECKSUM)) { // bad data block\n // clear/replace bad data from output buffer\n if (flags & LL_VERBOSE) {\n linklist_info(\"decompress_linklist: checksum failed -> bad data (block %d)\\n\", sumcount);\n }\n fill_linklist_with_saved(ll, p_start, p_end, buffer_out);\n ret++;\n } else if (!checksum && !prechecksum && !(flags & LL_IGNORE_CHECKSUM)) { // had a block of all zeros\n fill_linklist_with_saved(ll, p_start, p_end, buffer_out);\n if (flags & LL_VERBOSE) {\n linklist_info(\"decompress_linklist: block of zeros (block %d)\\n\", sumcount);\n }\n } else { // after all that, the checksum is good\n for (i=p_start; i<p_end; i++) { // decompress everything in that block\n tlm_le = &(ll->items[i]);\n tlm_in_size = tlm_le->blk_size;\n tlm_in_start = tlm_le->start;\n tlm_in_buf = buffer_in+tlm_in_start;\n\n if (tlm_le->tlm == &block_entry) { // data block entry \n block_t * theblock = linklist_find_block_by_pointer(ll, tlm_le);\n if (theblock) depacketize_block(theblock, tlm_in_buf);\n else linklist_err(\"Could not find block in linklist \\\"%s\\\"\\n\", ll->name);\n } else if (tlm_le->tlm == &stream_entry) { // data stream entry \n stream_t * thestream = linklist_find_stream_by_pointer(ll, tlm_le);\n if (thestream) depacketize_stream(thestream, tlm_in_buf);\n else linklist_err(\"Could not find stream in linklist \\\"%s\\\"\\n\", ll->name);\n } else { // just a normal field\n tlm_out_start = tlm_le->tlm->start;\n tlm_comp_type = tlm_le->comp_type;\n tlm_out_buf = buffer_out+tlm_out_start;\n\n if (tlm_comp_type != NO_COMP) { // compression\n (*compRoutine[tlm_comp_type].decompressFunc)(tlm_out_buf, tlm_le, tlm_in_buf);\n } else {\n decimationDecompress(tlm_out_buf, tlm_le, tlm_in_buf);\n }\n }\n }\n }\n\n // reset checksum\n prechecksum = 0;\n checksum = 0;\n sumcount++;\n p_start = j+1;\n tot++;\n\n }\n }\n // save the data\n memcpy(buffer_save, buffer_out, superframe->size);\n ret = (tot == 0) ? NAN : (tot-ret)/tot;\n\n return ret;\n}\n\nunsigned int linklist_blocks_queued(linklist_t * ll) {\n unsigned int i;\n unsigned int retval = 0;\n if (!ll) return retval;\n\n for (i=0; i<ll->num_blocks; i++) {\n if (ll->blocks[i].i < ll->blocks[i].n) retval++;\n }\n return retval;\n}\n\nvoid packetize_block(block_t * block, uint8_t * buffer)\n{\n if (block->fp && (block->flags & BLOCK_PREEMPT_FILE)) { // send preempt file data before the rest of the data\n int fsize = make_block_header(buffer, block->id & ~BLOCK_FILE_MASK, \n block->le->blk_size-PACKET_HEADER_SIZE, 0, 1);\n\n memcpy(buffer+fsize, block->buffer, block->le->blk_size);\n block->flags &= ~BLOCK_PREEMPT_FILE; // clear the flag so next time, actual data can be sent\n } else if (block->i < block->n) { // packets left to be sent \n unsigned int loc = (block->i*(block->le->blk_size-PACKET_HEADER_SIZE)); // location in data block\n unsigned int cpy = MIN(block->le->blk_size-PACKET_HEADER_SIZE, block->curr_size-loc);\n\n if (cpy > UINT16_MAX) {\n linklist_err(\"Block packet size %d is too large\\n\", cpy);\n return;\n }\n \n // make the header\n int fsize = make_block_header(buffer, block->id, cpy, block->i, block->n);\n \n if (loc > block->curr_size) {\n linklist_err(\"Block location %d > total size %d\", loc, block->curr_size);\n return;\n }\n\n if (block->fp) { // there is a file instead of data in a buffer\n fseek(block->fp, loc, SEEK_SET); // go to the location in the file\n int retval = 0;\n if ((retval = fread(buffer+fsize, 1, cpy, block->fp)) != (int) cpy) {\n linklist_err(\"Could only read %d/%d bytes at %d from file %s\", retval, cpy, loc, block->filename);\n }\n } else { // there is data in the buffer\n memcpy(buffer+fsize, block->buffer+loc, cpy);\n }\n\n block->i++;\n block->num++;\n } else { // no blocks left\n memset(buffer, 0, block->le->blk_size);\n if (block->fp) { // file was open, so close it\n close_block_fp(block);\n block->filename[0] = '\\0';\n }\n }\n\n}\n\n// handle for openning and appending to files even if they don't exist\nFILE * fpreopenb(char *fname)\n{\n FILE * temp = fopen(fname,\"ab\");\n if (!temp) {\n linklist_err(\"Cannot open %s (errno %d: %s) \\n\", fname, errno, strerror(errno));\n return NULL;\n }\n fclose(temp);\n return fopen(fname,\"rb+\");\n}\n\nvoid depacketize_block(block_t * block, uint8_t * buffer)\n{\n uint32_t id = 0;\n uint32_t i = 0, n = 0;\n uint16_t blksize = 0;\n static FILE * missed_pkts_fp = NULL;\n\n int fsize = read_block_header(buffer, &id, &blksize, &i, &n);\n\n // no data to read\n if (blksize == 0) {\n // close any dangling file pointers\n if (block->fp) {\n close_block_fp(block);\n block->filename[0] = '\\0';\n }\n return;\n }\n if (i >= n) { \n linklist_info(\"depacketize_block: index larger than total (%d > %d)\\n\", i, n);\n return;\n }\n // report missing block for already opened files\n if (block->i < i) {\n if (!missed_pkts_fp) {\n missed_pkts_fp = fpreopenb(LINKLIST_MISSED_PKTS_FILE);\n time_t now;\n time(&now);\n fprintf(missed_pkts_fp, \"\\n--------\\n%s--------\\n\", ctime(&now));\n } \n if (missed_pkts_fp) {\n fprintf(missed_pkts_fp, \"%s %d %d\\n\", \n (strlen(block->filename) > 0) ? block->filename : \"(missing)\", \n block->i, \n i+1);\n fflush(missed_pkts_fp);\n }\n }\n // ... and print them to terminal\n while ((block->i < i) && block->fp) {\n linklist_info(\"Missing block %d/%d\\n\", block->i+1, n);\n block->i++;\n }\n \n unsigned int loc = i*(block->le->blk_size-fsize);\n unsigned int expected_size = n*(block->le->blk_size-fsize);\n\n if (id & BLOCK_FILE_MASK) { // receiving a file\n id &= ~BLOCK_FILE_MASK; // remove the mask\n\n // a different id packet was received, so close file if that packet is open\n if ((id != block->id) || (i < block->i) || (n != block->n)) {\n close_block_fp(block);\n }\n \n // file not open yet\n if (!block->fp) {\n struct preempt_data * pd = (struct preempt_data *) block->buffer;\n if (pd->serial == BLOCK_PREEMPT_ID) { // auxiliary data has been preempted, so override file defaults\n sprintf(block->filename, \"%s/%s\", LINKLIST_FILESAVE_DIR, pd->filename); // build filename\n memset(pd, 0, sizeof(struct preempt_data));\n } else { // defaults\n sprintf(block->filename, \"%s/%s_%d\", LINKLIST_FILESAVE_DIR, block->name, id); // build filename\n }\n if (!(block->fp = fpreopenb(block->filename))) {\n linklist_err(\"Cannot open file %s\", block->filename);\n return;\n }\n linklist_info(\"File \\\"%s\\\" opened\\n\", block->filename);\n // make symlink to newest opened file\n char symname[LINKLIST_MAX_FILENAME_SIZE] = \"\";\n snprintf(symname, LINKLIST_MAX_FILENAME_SIZE, \"%s/%s.lnk\", LINKLIST_FILESAVE_DIR, block->name);\n unlink(symname);\n if (symlink(block->filename, symname) < 0) {\n linklist_err(\"Unable to form symlink %s -> %s\\n\", block->filename, symname);\n }\n }\n fseek(block->fp, loc, SEEK_SET); \n int retval = 0;\n if ((retval = fwrite(buffer+fsize, 1, blksize, block->fp)) != blksize) {\n linklist_err(\"Wrote %d != %d bytes at %d to file %s\", retval, blksize, loc, block->filename);\n }\n \n // got last packet, so close\n if ((i+1) == n) {\n linklist_info(\"Completed \\\"%s\\\"\\n\\n\", block->filename);\n close_block_fp(block);\n }\n\n } else { // just a normal block to be stored in memory\n // expand the buffer if necessary\n if (expected_size > block->alloc_size) { \n void * tp = realloc(block->buffer, expected_size);\n block->buffer = (uint8_t *) tp;\n block->alloc_size = expected_size;\n }\n memcpy(block->buffer+loc, buffer+fsize, blksize);\n }\n\n // set block variables \n block->curr_size = expected_size;\n block->i = i;\n block->n = n;\n block->id = id; \n\n block->i++;\n block->num++;\n}\n\nvoid packetize_stream(stream_t * stream, uint8_t * buffer) {\n unsigned int blk_size = stream->le->blk_size;\n unsigned int cpy = 0;\n unsigned int total = 0;\n substream_t * ss = &stream->buffers[stream->curr];\n \n memset(buffer, 0, blk_size); // always zero out the buffer\n\n while (total < blk_size) {\n // reached the end of the current buffer, so go to next one\n if (ss->loc >= ss->data_size) { \n // reset this buffer\n ss->loc = 0; \n\n // clear the data\n // if data is not cleared, it will be repeated, unless there is newer data to send\n if (!(ss->flags & STREAM_DONT_CLEAR)) {\n memset(ss->buffer, 0, ss->data_size);\n ss->data_size = 0;\n ss->flags = 0;\n }\n\n // update current read buffer\n stream->curr = stream->next; // only a reading function can modify stream->curr\n ss = &stream->buffers[stream->curr];\n\n // this buffer is the current, so it is being sent (don't need to force send again)\n ss->flags &= ~STREAM_MUST_SEND;\n\n // for file streams, overwrite buffer with file data\n if (stream->fp) {\n memset(ss->buffer, 0, ss->data_size);\n fflush(stream->fp);\n int ret = fread(ss->buffer, 1, ss->alloc_size, stream->fp);\n ss->data_size = (ret > 0) ? ret : 0;\n ss->flags = 0;\n }\n\n // escape if the next buffer has no data; otherwise continue\n if (!ss->data_size) break;\n continue;\n } \n\n // copy from the current buffer\n cpy = MIN(blk_size-total, ss->data_size-ss->loc);\n memcpy(buffer+total, ss->buffer+ss->loc, cpy); // cpy is always non-zero\n // linklist_info(\"%s\", (char *) buffer);\n\n // increment total bytes and buffer location\n ss->loc += cpy;\n total += cpy;\n }\n}\n\nvoid depacketize_stream(stream_t * stream, uint8_t * buffer) {\n write_next_stream(stream, buffer, stream->le->blk_size, 0);\n}\n\n// takes superframe at buffer in and creates an all frame in buffer out\n// all frame is 1 sample per field uncompressed\nint write_allframe(uint8_t * allframe, superframe_t * superframe, uint8_t * sf) {\n unsigned int i, j;\n int tlm_out_start = 4; // the first 4 bytes are the serial for allframes\n int tlm_in_start = 0; \n unsigned int tlm_size = 0; \n uint32_t test = ALLFRAME_SERIAL;\n uint16_t crc = 0;\n\n int wd = 1;\n if ((allframe == NULL) || (sf == NULL)) wd = 0;\n\n superframe_entry_t * ll_superframe_list = superframe->entries;\n\n // allocate crc table if necessary\n if (ll_crctable == NULL)\n {\n if ((ll_crctable = mk_ll_crctable((unsigned short)LL_CRC_POLY,ll_crchware)) == NULL)\n {\n linklist_fatal(\"mk_ll_crctable() memory allocation failed\\n\");\n ll_crctable = NULL;\n return -2;\n }\n } \n\n if (wd) memcpy(allframe, &test, 4);\n\n for (i = 0; i < superframe->n_entries; i++) {\n tlm_in_start = ll_superframe_list[i].start;\n tlm_size = get_superframe_entry_size(&ll_superframe_list[i]);\n\n if (wd) {\n memcpy(allframe+tlm_out_start, sf+tlm_in_start, tlm_size);\n for (j=0;j<tlm_size;j++) ll_crccheck(allframe[tlm_out_start+j],&crc,ll_crctable);\n }\n tlm_out_start += tlm_size;\n }\n\n if (wd) {\n // write the crc \n memcpy(allframe+2,((uint8_t*)&crc)+1,1);\n memcpy(allframe+3,((uint8_t*)&crc)+0,1);\n }\n\n return tlm_out_start;\n\n}\n\n// takes an allframe at buffer in at 1 sample per frame and writes repeated\n// samples in the superframe\nint read_allframe(uint8_t * sf, superframe_t * superframe, uint8_t * allframe) {\n unsigned int i,j;\n unsigned int tlm_out_start = 0;\n unsigned int tlm_in_start = 4;\n unsigned int tlm_num = 0;\n unsigned int tlm_skip = 0;\n unsigned int tlm_size = 0;\n int check_crc = 1;\n \n superframe_entry_t * ll_superframe_list = superframe->entries;\n\n // allocate crc table if necessary\n if (ll_crctable == NULL)\n {\n if ((ll_crctable = mk_ll_crctable((unsigned short)LL_CRC_POLY,ll_crchware)) == NULL)\n {\n linklist_fatal(\"mk_ll_crctable() memory allocation failed\\n\");\n ll_crctable = NULL;\n return -2;\n }\n } \n\n // check to see if this is actually an allframe\n if (*((uint16_t *) allframe) != (uint16_t) ALLFRAME_SERIAL) { \n return 0;\n }\n if (*((uint32_t *) allframe) == (uint32_t) ALLFRAME_SERIAL) {\n check_crc = 0;\n }\n\n uint16_t crc = 0;\n \n for (i = 0; i < superframe->n_entries; i++) { \n tlm_out_start = ll_superframe_list[i].start;\n tlm_size = get_superframe_entry_size(&ll_superframe_list[i]);\n tlm_num = ll_superframe_list[i].spf;\n tlm_skip = ll_superframe_list[i].skip;\n\n for (j=0;j<tlm_size;j++) ll_crccheck(allframe[tlm_in_start+j],&crc,ll_crctable);\n for (j = 0; j < tlm_num; j++) {\n if (sf) memcpy(sf+tlm_out_start, allframe+tlm_in_start, tlm_size);\n tlm_out_start += tlm_skip;\n }\n tlm_in_start += tlm_size;\n } \n\n // check the crc\n ll_crccheck(allframe[2], &crc, ll_crctable);\n ll_crccheck(allframe[3], &crc, ll_crctable);\n\n if (check_crc && crc)\n {\n linklist_info(\"Bad all_frame checksum\\n\");\n // give an all frame that is saved from the previous good buffer\n if (buffer_save && sf) memcpy(sf, buffer_save, superframe->size);\n return -1;\n }\n\n // set the last good buffer to the allframe\n if (buffer_save && sf) memcpy(buffer_save, sf, superframe->size);\n return (int) tlm_in_start;\n\n}\n\ndouble antiAlias(uint8_t * data_in, char type, unsigned int num, unsigned int skip,\n double (*datatodouble)(uint8_t *, uint8_t))\n{\n unsigned int i;\n double halfsum = 0;\n double ret = 0; \n\n if (num == 1) return (*datatodouble)(data_in,type);\n\n for (i=0;i<num;i++) \n {\n halfsum += (*datatodouble)(data_in+i*skip,type); \n }\n ret = halfsum/num;\n\n return ret;\n}\n\n\nint stream32bitFixedPtComp(uint8_t * data_out, struct link_entry * le, uint8_t * data_in)\n{\n int wd = 1;\n int blk_size = 0; \n double offset = 0.0, gain = 1.0;\n double temp1;\n\n char type = le->tlm->type;\n //unsigned int inputsize = get_superframe_entry_size(le->tlm);\n unsigned int inputskip = le->tlm->skip;\n unsigned int inputnum = le->tlm->spf;\n unsigned int outputnum = le->num;\n unsigned int decim = inputnum/outputnum;\n if (decim == 0) return 0;\n\n // reference the custom conversion function\n double (*datatodouble)(uint8_t *, uint8_t) = le->linklist->superframe->datatodouble; \n int (*doubletodata)(uint8_t *, double, uint8_t) = le->linklist->superframe->doubletodata; \n\n unsigned int i;\n\n if ((data_out == NULL) || (data_in == NULL)) wd = 0; // don't read/write data\n\n if (!wd)\n {\n type = '0';\n }\n\n offset = 0;\n gain = 1; \n if ((le->tlm->max != 0) || (le->tlm->min != 0))\n {\n offset = le->tlm->min;\n gain = (le->tlm->max-le->tlm->min)/((double) UINT32_MAX);\n } \n\n for (i=0;i<outputnum;i++)\n {\n if (wd)\n {\n temp1 = antiAlias(data_in+(i*decim*inputskip), type ,decim, inputskip, datatodouble);\n temp1 = (temp1-offset)/(gain);\n if (temp1 > UINT32_MAX) temp1 = UINT32_MAX;\n else if (temp1 < 0.0) temp1 = 0.0;\n (*doubletodata)(data_out+blk_size, temp1, SF_UINT32);\n }\n blk_size+=4;\n }\n\n return blk_size;\n}\n\nint stream32bitFixedPtDecomp(uint8_t * data_out, struct link_entry * le, uint8_t * data_in)\n{\n unsigned int i,j;\n int wd = 1;\n int blk_size = 0;\n double gain = 1.0, offset = 0.0;\n\n char type = le->tlm->type;\n unsigned int outputsize = get_superframe_entry_size(le->tlm);\n unsigned int outputskip = le->tlm->skip;\n unsigned int outputnum = le->tlm->spf;\n unsigned int inputnum = le->num;\n unsigned int decim = outputnum/inputnum;\n unsigned int outputstart = 0;\n\n // reference the custom conversion function\n double (*datatodouble)(uint8_t *, uint8_t) = le->linklist->superframe->datatodouble; \n int (*doubletodata)(uint8_t *, double, uint8_t) = le->linklist->superframe->doubletodata; \n\n if ((data_out == NULL) || (data_in == NULL)) wd = 0; // don't read/write data\n\n offset = 0;\n gain = 1;\n if ((le->tlm->max != 0) || (le->tlm->min != 0))\n {\n offset = le->tlm->min;\n gain = (le->tlm->max-le->tlm->min)/((double) UINT32_MAX);\n }\n\n double dataout = 0;\n uint32_t value = 0;\n\n for (i=0;i<inputnum;i++)\n {\n if (wd) \n {\n value = (*datatodouble)(&data_in[i*4], SF_UINT32);\n dataout = ((double) value)*gain+offset;\n }\n //linklist_info(\"%f \",dataout);\n for (j=0;j<decim;j++)\n {\n if (wd) (*doubletodata)(data_out+outputstart,dataout,type);\n outputstart += outputskip;\n blk_size += outputsize;\n }\n }\n //linklist_info(\"\\n\\n\");\n\n return blk_size;\n}\n\nint stream16bitFixedPtComp(uint8_t * data_out, struct link_entry * le, uint8_t * data_in)\n{\n int wd = 1;\n int blk_size = 0; \n double offset = 0.0, gain = 1.0;\n double temp1;\n\n char type = le->tlm->type;\n //unsigned int inputsize = get_superframe_entry_size(le->tlm);\n unsigned int inputskip = le->tlm->skip;\n unsigned int inputnum = le->tlm->spf;\n unsigned int outputnum = le->num;\n unsigned int decim = inputnum/outputnum;\n if (decim == 0) return 0;\n\n // reference the custom conversion function\n double (*datatodouble)(uint8_t *, uint8_t) = le->linklist->superframe->datatodouble; \n int (*doubletodata)(uint8_t *, double, uint8_t) = le->linklist->superframe->doubletodata; \n\n unsigned int i;\n\n if ((data_out == NULL) || (data_in == NULL)) wd = 0; // don't read/write data\n\n if (!wd)\n {\n type = '0';\n }\n\n offset = 0;\n gain = 1;\n if ((le->tlm->max != 0) || (le->tlm->min != 0))\n {\n offset = le->tlm->min;\n gain = (le->tlm->max-le->tlm->min)/((double) UINT16_MAX);\n } \n\n for (i=0;i<outputnum;i++)\n {\n if (wd)\n {\n temp1 = antiAlias(data_in+(i*decim*inputskip), type, decim, inputskip, datatodouble);\n temp1 = (temp1-offset)/(gain);\n if (temp1 > UINT16_MAX) temp1 = UINT16_MAX;\n else if (temp1 < 0.0) temp1 = 0.0;\n (*doubletodata)(data_out+blk_size, temp1, SF_UINT16);\n }\n blk_size+=2;\n }\n\n return blk_size;\n}\n\nint stream16bitFixedPtDecomp(uint8_t * data_out, struct link_entry * le, uint8_t * data_in)\n{\n unsigned int i,j;\n int wd = 1;\n int blk_size = 0;\n double gain = 1.0, offset = 0.0;\n\n char type = le->tlm->type;\n unsigned int outputsize = get_superframe_entry_size(le->tlm);\n unsigned int outputskip = le->tlm->skip;\n unsigned int outputnum = le->tlm->spf;\n unsigned int inputnum = le->num;\n unsigned int decim = outputnum/inputnum;\n unsigned int outputstart = 0;\n\n // reference the custom conversion function\n double (*datatodouble)(uint8_t *, uint8_t) = le->linklist->superframe->datatodouble; \n int (*doubletodata)(uint8_t *, double, uint8_t) = le->linklist->superframe->doubletodata; \n\n if ((data_out == NULL) || (data_in == NULL)) wd = 0; // don't read/write data\n\n offset = 0;\n gain = 1;\n if ((le->tlm->max != 0) || (le->tlm->min != 0))\n {\n offset = le->tlm->min;\n gain = (le->tlm->max-le->tlm->min)/((double) UINT16_MAX);\n }\n\n double dataout = 0;\n uint16_t value = 0;\n\n for (i=0;i<inputnum;i++)\n {\n if (wd) \n {\n value = (*datatodouble)(&data_in[i*2], SF_UINT16);\n dataout = ((double) value)*gain+offset;\n }\n //linklist_info(\"%f \",dataout);\n for (j=0;j<decim;j++)\n {\n if (wd) (*doubletodata)(data_out+outputstart,dataout,type);\n outputstart += outputskip;\n blk_size += outputsize;\n }\n }\n //linklist_info(\"\\n\\n\");\n\n return blk_size;\n}\nint stream8bitComp(uint8_t * data_out, struct link_entry * le, uint8_t * data_in)\n{\n int wd = 1;\n int blk_size = 8; // gain and offset are two floats\n float offset, gain;\n\n char type = le->tlm->type;\n //unsigned int inputsize = get_superframe_entry_size(le->tlm);\n unsigned int inputskip = le->tlm->skip;\n unsigned int inputnum = le->tlm->spf;\n unsigned int outputnum = le->num;\n unsigned int decim = inputnum/outputnum;\n if (decim == 0) return 0;\n\n // reference the custom conversion function\n double (*datatodouble)(uint8_t *, uint8_t) = le->linklist->superframe->datatodouble; \n int (*doubletodata)(uint8_t *, double, uint8_t) = le->linklist->superframe->doubletodata; \n\n unsigned int i;\n double min = 1.0e30, max = -1.0e30, temp1 = 0;\n\n if ((data_out == NULL) || (data_in == NULL)) wd = 0; // don't read/write data\n\n if (!wd)\n {\n type = '0';\n }\n\n // get gain and offset from first 10% of the input data \n for (i=0;i<(inputnum);i+=decim)\n {\n if (wd)\n {\n temp1 = antiAlias(data_in+(i*inputskip), type, decim, inputskip, datatodouble);\n if (temp1 < min) min = temp1;\n if (temp1 > max) max = temp1;\n }\n }\n offset = min;\n gain = (max-min)/((double) (UINT8_MAX-1)); // scale from 0x0 to 0xfe\n\n if (wd)\n {\n (*doubletodata)(data_out+0, (double) gain, SF_FLOAT32);\n (*doubletodata)(data_out+4, (double) offset, SF_FLOAT32);\n }\n\n for (i=0;i<outputnum;i++)\n {\n if (wd)\n {\n temp1 = antiAlias(data_in+(i*decim*inputskip), type, decim, inputskip, datatodouble);\n temp1 = (temp1-offset)/(gain);\n data_out[blk_size] = temp1;\n }\n blk_size++;\n }\n\n return blk_size;\n}\n\nint stream8bitDecomp(uint8_t * data_out, struct link_entry * le, uint8_t * data_in)\n{\n unsigned int i,j;\n int wd = 1;\n int blk_size = 0;\n float gain = 0;\n float offset = 0;\n\n char type = le->tlm->type;\n unsigned int outputsize = get_superframe_entry_size(le->tlm);\n unsigned int outputskip = le->tlm->skip;\n unsigned int outputnum = le->tlm->spf;\n unsigned int inputnum = le->num;\n unsigned int decim = outputnum/inputnum;\n unsigned int outputstart = 0;\n\n // reference the custom conversion function\n double (*datatodouble)(uint8_t *, uint8_t) = le->linklist->superframe->datatodouble; \n int (*doubletodata)(uint8_t *, double, uint8_t) = le->linklist->superframe->doubletodata; \n\n if ((data_out == NULL) || (data_in == NULL)) wd = 0; // don't read/write data\n\n if (wd)\n {\n gain = (*datatodouble)(data_in+0, SF_FLOAT32);\n offset = (*datatodouble)(data_in+4, SF_FLOAT32);\n }\n\n double dataout = 0;\n\n for (i=0;i<inputnum;i++)\n {\n if (wd) dataout = ((double) data_in[i+8])*gain+offset;\n //linklist_info(\"%f \",dataout);\n for (j=0;j<decim;j++)\n {\n if (wd) (*doubletodata)(data_out+outputstart,dataout,type);\n outputstart += outputskip;\n blk_size += outputsize;\n }\n }\n //linklist_info(\"\\n\\n\");\n\n return blk_size;\n}\n\n\nint stream8bitDeltaComp(uint8_t * data_out, struct link_entry * le, uint8_t * data_in)\n{\n int wd = 1;\n int blk_size = 8; // gain and offset are two floats\n double remainder = 0;\n float offset, gain;\n\n char type = le->tlm->type;\n //unsigned int inputsize = get_superframe_entry_size(le->tlm);\n unsigned int inputskip = le->tlm->skip;\n unsigned int inputnum = le->tlm->spf;\n unsigned int outputnum = le->num;\n unsigned int decim = inputnum/outputnum;\n if (decim == 0) return 0; \n\n // reference the custom conversion function\n double (*datatodouble)(uint8_t *, uint8_t) = le->linklist->superframe->datatodouble; \n int (*doubletodata)(uint8_t *, double, uint8_t) = le->linklist->superframe->doubletodata; \n\n unsigned int i;\n double temp1 = 0, temp2 = 0, dif = 0;\n double min = INT32_MAX, max= -INT32_MAX;\n\n if ((data_out == NULL) || (data_in == NULL)) wd = 0; // don't read/write data\n\n if (!wd) \n {\n type = '0';\n }\n\n // get gain and offset from first 10% of the input data \n temp1 = 0;\n for (i=0;i<(inputnum);i+=decim)\n {\n if (wd) \n {\n temp2 = antiAlias(data_in+(i*inputskip), type, decim, inputskip, datatodouble);\n dif = temp2-temp1;\n if (dif < min) min = dif;\n if (dif > max) max = dif;\n temp1 = temp2;\n }\n }\n\n offset = min;\n gain = ((double) (max-min))/((double) (UINT8_MAX-1)); // scale from 0x0 to 0xfe\n\n if (wd)\n {\n (*doubletodata)(data_out+0, (double) gain, SF_FLOAT32);\n (*doubletodata)(data_out+4, (double) offset, SF_FLOAT32);\n }\n\n temp1 = 0;\n remainder = 0;\n for (i=0;i<outputnum;i++)\n {\n if (wd) \n {\n temp2 = antiAlias(data_in+(i*decim*inputskip), type, decim, inputskip, datatodouble);\n dif = (temp2-temp1-offset)/(gain);\n data_out[blk_size] = dif+remainder;\n remainder += dif-data_out[blk_size];\n temp1 = temp2;\n }\n blk_size++;\n }\n remainder = 0;\n \n return blk_size;\n}\n\nint stream8bitDeltaDecomp(uint8_t * data_out, struct link_entry * le, uint8_t * data_in)\n{\n unsigned int i,j;\n int wd = 1;\n int blk_size = 0;\n float gain = 0;\n float offset = 0;\n\n char type = le->tlm->type;\n unsigned int outputsize = get_superframe_entry_size(le->tlm);\n unsigned int outputskip = le->tlm->skip;\n unsigned int outputnum = le->tlm->spf;\n unsigned int inputnum = le->num;\n unsigned int decim = outputnum/inputnum;\n unsigned int outputstart = 0;\n\n // reference the custom conversion function\n int (*doubletodata)(uint8_t *, double, uint8_t) = le->linklist->superframe->doubletodata; \n double (*datatodouble)(uint8_t *, uint8_t) = le->linklist->superframe->datatodouble; \n\n if ((data_out == NULL) || (data_in == NULL)) wd = 0; // don't read/write data\n\n if (wd)\n {\n gain = (*datatodouble)(data_in+0, SF_FLOAT32);\n offset = (*datatodouble)(data_in+4, SF_FLOAT32);\n }\n\n double dataout = 0;\n\n for (i=0;i<inputnum;i++)\n {\n if (wd) dataout += ((double) data_in[i+8])*gain+offset;\n //linklist_info(\"%f \",dataout);\n for (j=0;j<decim;j++)\n {\n if (wd) (*doubletodata)(data_out+outputstart,dataout,type);\n outputstart += outputskip; \n blk_size += outputsize;\n }\n }\n //linklist_info(\"\\n\\n\");\n\n return blk_size;\n}\n\n\nint decimationCompress(uint8_t * data_out, struct link_entry * le, uint8_t * data_in)\n{\n int wd = 1;\n int blk_size = 0;\n\n //unsigned int inputsize = get_superframe_entry_size(le->tlm);\n unsigned int inputskip = le->tlm->skip;\n unsigned int inputnum = le->tlm->spf;\n unsigned int inputsize = get_superframe_entry_size(le->tlm);\n unsigned int outputnum = le->num;\n unsigned int decim = inputnum/outputnum;\n unsigned int size = get_superframe_entry_size(le->tlm); \n\n // reference the custom conversion function\n int (*doubletodata)(uint8_t *, double, uint8_t) = le->linklist->superframe->doubletodata; \n\n // reference the custom conversion function\n double (*datatodouble)(uint8_t *, uint8_t) = le->linklist->superframe->datatodouble; \n\n if (decim == 0) return 0;\n unsigned int i;\n if ((data_out == NULL) || (data_in == NULL)) wd = 0; // don't read/write data\n\n uint64_t dout = 0;\n char type = le->tlm->type;\n double temp1 = 0;\n\n for (i=0;i<outputnum;i++)\n {\n if (wd)\n {\n temp1 = antiAlias(data_in+(i*decim*inputskip), type, decim, inputskip, datatodouble);\n (*doubletodata)((uint8_t *) &dout,temp1,type);\n memcpy(data_out+(i*inputsize),&dout,size);\n }\n blk_size += size;\n }\n return blk_size;\n\n}\n\nint decimationDecompress(uint8_t * data_out, struct link_entry *le, uint8_t * data_in)\n{\n unsigned int i,j;\n int wd = 1;\n int blk_size = 0;\n\n unsigned int outputskip = le->tlm->skip;\n unsigned int outputnum = le->tlm->spf;\n unsigned int inputnum = le->num;\n unsigned int decim = outputnum/inputnum;\n\n unsigned int size = get_superframe_entry_size(le->tlm);\n\n if ((data_out == NULL) || (data_in == NULL)) wd = 0; // don't read/write data\n\n for (i=0;i<inputnum;i++)\n {\n for (j=0;j<decim;j++)\n {\n if (wd) \n {\n memcpy(data_out+((i*decim+j)*outputskip),data_in+(i*size),size);\n }\n blk_size += size;\n }\n }\n\n return blk_size;\n\n}\n\n\nstruct dataCompressor compRoutine[NUM_COMPRESS_TYPES+1] = {\n {COMPRESS(FIXED_PT_16BIT), stream16bitFixedPtComp, stream16bitFixedPtDecomp},\n {COMPRESS(FIXED_PT_32BIT), stream32bitFixedPtComp, stream32bitFixedPtDecomp},\n {COMPRESS(MEAN_FLOAT_DELTA_8BIT), stream8bitDeltaComp, stream8bitDeltaDecomp},\n {COMPRESS(MEAN_FLOAT_8BIT), stream8bitComp, stream8bitDecomp},\n \n // terminator\n {0}\n};\n\n#ifdef __cplusplus\n\n}\n\n#endif\n" }, { "alpha_fraction": 0.6830986142158508, "alphanum_fraction": 0.6971830725669861, "avg_line_length": 21.421052932739258, "blob_id": "990a6c43f0735e515ec695484567d348a5948264", "content_id": "c7c65c3cc363014170f253fd77da4a221e7c82d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 427, "license_type": "no_license", "max_line_length": 73, "num_lines": 19, "path": "/stars/code/tools/windows_header.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef TOOLS__WINDOWS_HEADER_H\n#define TOOLS__WINDOWS_HEADER_H\n\n#if defined(_MSC_VER)\n #define WIN32_LEAN_AND_MEAN\n #ifndef NOMINMAX\n #define NOMINMAX\n #endif\n #include <windows.h>\n#endif\n\n#endif\n" }, { "alpha_fraction": 0.7177215218544006, "alphanum_fraction": 0.7278481125831604, "avg_line_length": 18.75, "blob_id": "9fd75851c07868e6055318c7137717dcb6de0870", "content_id": "452c8223808858bc15bb13a3761e2c594f042bb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 791, "license_type": "no_license", "max_line_length": 75, "num_lines": 40, "path": "/stars/code/shared/network/image_client_settings.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__NETWORK__IMAGE_CLIENT_SETTINGS_H\n#define SHARED__NETWORK__IMAGE_CLIENT_SETTINGS_H\n\n#include \"../circular_buffer.h\"\n\nnamespace Shared\n{\n namespace Network\n {\n\nclass ImageClientSettings\n{\n public:\n ImageClientSettings();\n void init(Parameters::Manager& params);\n\n bool enabled;\n};\n\n// writes: network\n// reads: net_image_client1\n\nextern Shared::CircularBuffer <ImageClientSettings> image_client_settings1;\n\n// writes: network\n// reads: net_image_client2\n\nextern Shared::CircularBuffer <ImageClientSettings> image_client_settings2;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.8725489974021912, "alphanum_fraction": 0.8725489974021912, "avg_line_length": 101, "blob_id": "05eba4904b09c8dbc8b466eb5d943f4baff520bd", "content_id": "cd13212afb3155c9996153b0e258b28ebf1dd74b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 102, "license_type": "no_license", "max_line_length": 101, "num_lines": 1, "path": "/sensors/README.md", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "This directory contains code implementations for each sensor system potentially used in SuperBLASTPol\n" }, { "alpha_fraction": 0.6097821593284607, "alphanum_fraction": 0.613390326499939, "avg_line_length": 38.58201217651367, "blob_id": "e40c76fa2094b55abbb59fc95af453fc7c948961", "content_id": "173180325477dd7cb72f2fb66b8b8fb8abf04300", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 7483, "license_type": "no_license", "max_line_length": 115, "num_lines": 189, "path": "/starcam/Makefile", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "SRC_DIR = .\nINCLUDE = -I $(SRC_DIR)\nLIBRARY = -L $(SRC_DIR)\nCPPFLAGS = $(INCLUDE)\n#CFLAGS = -O2 -Wall\n#LDFLAGS = $(LIBRARY)\nCFLAGS = -O0 -Wall -g #for debugging\nLDFLAGS = $(LIBRARY) -g\nLD = gcc\nCXX = g++\nMOC = moc\n\n########################################################\n# Repository object/header path munging\n#\n\nSPIDER_ONLY = 1\n\nEXPT_HEADERS = command_list.h command_struct.h pointing_struct.h\nSHARED_OBJS = blast.o camcommunicator.o udp.o\nSHARED_HEADERS = blast.h camcommunicator.h camstruct.h udp.h\n\ninclude ../common/Makefile.shared\n\n# now $(OBJS) and $(HEADERS) are defined, and $(CPPFLAGS) has been modified\n\n################################################################################\n# starcam makefile by Steve Benton\n################################################################################\nAPP_NAME = starcam\nTEST_NAME = testmain\nUSE_QT = 1 #change this to 0 to not use qt when its not available\n #probably need to change bits of code too\nO_APP = csbigcam.o csbigimg.o mycam.o clensadapter.o bloblist.o \\\nframeblob.o blobimage.o pyramid.o svd.o $(OBJS)\nO_APP_QT = imageviewer.o moc_imageviewer.o commandgui.o moc_commandgui.o\n################################################################################\n\n#different definitions for when Qt is and isn't available\nifeq ($(strip $(USE_QT)), 1)\nAPP_OBJ = $(APP_NAME).o $(O_APP) $(O_APP_QT)\nTEST_OBJ = $(TEST_NAME).o $(O_APP) $(O_APP_QT)\nQTLIB = -L/usr/share/qt3/lib -L/usr/X11R6/lib -lqt-mt -lXext -lX11\nQTINC = -I/usr/share/qt3/mkspecs/default -I/usr/include/qt3\nQTFLAGS = $(QTINC) -pipe -D_REENTRANT -DQT_NO_DEBUG -DQT_THREAD_SUPPORT \\\n\t\t-DQT_SHARED -DQT_TABLET_SUPPORT\nelse\nAPP_OBJ = $(APP_NAME).o $(O_APP)\nTEST_OBJ = $(APP_NAME).o $(O_APP)\nQTLIB =\nQTINC =\nQTFLAGS =\nendif\n\n################################################################################\n#targets for building all or part of the main program\nall:: cam comm view util test\ncam: $(APP_NAME)\ncomm: commtest\nview: scviewer\n################################################################################\n# APP_NAME\n################################################################################\n\ninstall: $(APP_NAME)\n\tinstall -m 755 $(APP_NAME) /usr/local/bin\n\tinstall -d -m 777 /data/etc\n\tinstall -d -m 777 /data/rawdir/\n\t[ -e /data/etc/init.txt ] || touch /data/etc/init.txt\n\t[ -e /data/etc/badpix.txt ] || touch /data/etc/badpix.txt\n\n\n$(APP_NAME): $(APP_OBJ)\n\t $(LD) $(LDFLAGS) $(QTLIB) -o $(APP_NAME) $(APP_OBJ) -lsbigudrv -lm -lpthread\n\t chmod a+x $(APP_NAME)\n\nstarcam.o : starcam.cpp csbigcam.h csbigimg.h mycam.h blobimage.h bloblist.h clensadapter.h frameblob.h \\\n\tcamconfig.h clensadapterdefs.h csbigimgdefs.h pyramid.h svd.h imageviewer.h $(HEADERS)\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) $(QTFLAGS) -o starcam.o -c starcam.cpp\n\ncsbigcam.o : csbigcam.h csbigcam.cpp csbigimg.h camconfig.h\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) -o csbigcam.o -c csbigcam.cpp\n\t \nmycam.o : mycam.h mycam.cpp clensadapter.h blobimage.h camconfig.h csbigcam.h\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) -o mycam.o -c mycam.cpp\n\ncsbigimg.o : csbigimg.cpp csbigimg.h camconfig.h csbigimgdefs.h\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) -o csbigimg.o -c csbigimg.cpp\n\t \nclensadapter.o : clensadapter.h clensadapter.cpp camconfig.h clensadapterdefs.h\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) -o clensadapter.o -c clensadapter.cpp\n\nbloblist.o : bloblist.h bloblist.cpp\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) -o bloblist.o -c bloblist.cpp\n\nframeblob.o : frameblob.h frameblob.cpp bloblist.h camconfig.h\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) -o frameblob.o -c frameblob.cpp\n\nblobimage.o : blobimage.h blobimage.cpp frameblob.h bloblist.h camconfig.h pyramid.h svd.h\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) -o blobimage.o -c blobimage.cpp\n\t \npyramid.o : pyramid.h pyramid.cpp\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) -O0 -o pyramid.o -c pyramid.cpp\n\t \nsvd.o : svd.h svd.cpp\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) -O0 -o svd.o -c svd.cpp\n\t \n################################################################################\n#image viewer\nVIEWER_OBJ=scviewer.o blobimage.o pyramid.o svd.o imageviewer.o moc_imageviewer.o csbigimg.o frameblob.o bloblist.o\nscviewer: $(VIEWER_OBJ)\n\t $(LD) $(LDFLAGS) $(QTLIB) -o scviewer $(VIEWER_OBJ) -lpthread\n\t chmod a+x scviewer\n\nscviewer.o : scviewer.cpp blobimage.h csbigimgdefs.h imageviewer.h\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) $(QTFLAGS) -o scviewer.o -c scviewer.cpp\n\nimageviewer.o : imageviewer.h imageviewer.cpp\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) $(QTFLAGS) -o imageviewer.o -c imageviewer.cpp\n\t \nmoc_imageviewer.cpp : imageviewer.h\n\t $(MOC) imageviewer.h -o moc_imageviewer.cpp\n\t \nmoc_imageviewer.o : imageviewer.h moc_imageviewer.cpp\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) $(QTFLAGS) -o moc_imageviewer.o -c moc_imageviewer.cpp\n\n\t \n################################################################################\n#simple test program\ntest: testmain commtest\n\ntestmain : $(TEST_OBJ)\n\t $(LD) $(LDFLAGS) $(QTLIB) -o $(TEST_NAME) $(TEST_OBJ) -lsbigudrv -lm \\\n\t\t\t-lpthread\n\t\tchmod a+x $(TEST_NAME)\n\t \ntestmain.o : testmain.cpp csbigcam.h csbigimg.h mycam.h blobimage.h bloblist.h \\\n\tclensadapter.h frameblob.h camconfig.h clensadapterdefs.h csbigimgdefs.h \\\n\tpyramid.h svd.h imageviewer.h $(HEADERS)\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) $(QTFLAGS) -o testmain.o -c testmain.cpp\n\t \n################################################################################\n#test communicator app\nCOMMTEST_OBJ=testcomm.o $(OBJS) commandgui.o moc_commandgui.o\ncommtest : $(COMMTEST_OBJ)\n\t $(LD) $(LDFLAGS) $(QTLIB) -o commtest $(COMMTEST_OBJ) -lpthread\n\t chmod a+x commtest\n\t \ntestcomm.o : testcomm.cpp camconfig.h commandgui.h $(HEADERS)\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) $(QTFLAGS) -o testcomm.o -c testcomm.cpp\n\ncommandgui.o : commandgui.h commandgui.cpp camconfig.h $(HEADERS)\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) $(QTFLAGS) -o commandgui.o -c commandgui.cpp\n\t \nmoc_commandgui.cpp : commandgui.h\n\t $(MOC) commandgui.h -o moc_commandgui.cpp\n\t \nmoc_commandgui.o : commandgui.h moc_commandgui.cpp\n\t $(CXX) $(CPPFLAGS) $(CFLAGS) $(QTFLAGS) -o moc_commandgui.o -c moc_commandgui.cpp\n\n################################################################################\n# utility programs that are not related to main functionality\nutil: powercycle findbadpixel fixbadpixel\n\n# program to power cycle the camera with a parallel port dongle\npowercycle: powercycle.c\n\n# program to analyze bad pixel data\nfindbadpixel: findbadpixel.o blobimage.o pyramid.o svd.o frameblob.o bloblist.o csbigimg.o\n\tg++ findbadpixel.o blobimage.o pyramid.o svd.o frameblob.o bloblist.o csbigimg.o -o findbadpixel\n\tchmod a+x findbadpixel\n\nfindbadpixel.o: findbadpixel.cpp blobimage.h frameblob.h bloblist.h \\\n\tcamconfig.h $(HEADERS) csbigimg.h csbigimgdefs.h\n\tg++ -O0 -I . -I ../common -L . -Wall -g -c -o findbadpixel.o findbadpixel.cpp\n\n# program to use a bad pixel file to correct a bad pixel\nfixbadpixel: fixbadpixel.o blobimage.o pyramid.o svd.o frameblob.o bloblist.o csbigimg.o\n\tg++ fixbadpixel.o blobimage.o pyramid.o svd.o frameblob.o bloblist.o csbigimg.o -o fixbadpixel\n\tchmod a+x fixbadpixel\n\nfixbadpixel.o: fixbadpixel.cpp blobimage.h frameblob.h bloblist.h camconfig.h \\\n csbigimg.h csbigimgdefs.h $(HEADERS)\n\tg++ -O0 -I . -I ../common -L . -Wall -g -c -o fixbadpixel.o fixbadpixel.cpp\n\n################################################################################\n\nclean:\n\trm -f *.o powercycle findbadpixel fixbadpixel scviewer testmain commtest starcam moc_*\n\n\n" }, { "alpha_fraction": 0.6406709551811218, "alphanum_fraction": 0.644302248954773, "avg_line_length": 31.66666603088379, "blob_id": "1245d832fe713626a44555851d0dcf0e12fc2dbf", "content_id": "b6062cedb58140bde7350435587d498d0e2345fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5784, "license_type": "no_license", "max_line_length": 104, "num_lines": 177, "path": "/stars/code/solving/solver.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"solver.h\"\n#include \"logger.h\"\n#include <cstdio>\n#include \"../tools/math.h\"\n#include <vector>\n#include <algorithm>\n#include <cstring>\n#include <boost/bind.hpp>\n#include \"update.h\"\n#include \"../shared/image/raw.h\"\n#include \"../shared/image/blobs.h\"\n#include \"../shared/image/solution_summary.h\"\n#include \"../shared/image/stats.h\"\n#include \"../shared/image/status.h\"\n#include \"../shared/general/quit.h\"\n#include \"../shared/solving/settings.h\"\n#include \"../parameters/manager.h\"\n\nusing namespace Solving;\n#define shared_status (*(Shared::Image::status_solver_for_main.w))\n#define shared_settings (*(Shared::Solving::settings.r))\n#define shared_blobs (*(Shared::Image::blobs_solver_for_main.w))\n#define shared_stats (*(Shared::Image::stats_solver_for_main.w))\n#define shared_solution_summary (*(Shared::Image::solution_summary_for_main.w))\n\nSolver::Solver(Parameters::Manager& params, Shared::Image::Raw& solvers_working_image):\n working_image(&solvers_working_image),\n blob_finder(params),\n pattern_matcher(params),\n statistician(params),\n autofocus_helper(params),\n quit_after_one(params.general.try_get(\"imaging.camera_filesystem.quit_after_one\", false)),\n quit_after_one_delay(params.general.try_get(\"imaging.camera_filesystem.quit_after_one_delay\", 1.0)),\n #pragma warning(push)\n #pragma warning(disable: 4355)\n solve_thread(boost::bind(&Solver::solve_thread_function, this))\n #pragma warning(pop)\n{\n}\n\nvoid Solver::solve()\n{\n using namespace Shared::Image;\n Tools::Timer timer;\n logger.log(format(\"starting to solve image %s\") % working_image->filename);\n\n timer.start();\n // setting up\n {\n shared_solution_summary.blob_names.clear();\n Shared::Image::solution_summary_for_main.share();\n shared_stats.clear(working_image->counter_stars);\n Shared::Image::stats_solver_for_main.share();\n Shared::Image::blobs_solver_for_main.share();\n update_shared();\n }\n\n // stats\n {\n statistician.make_display_data(*working_image);\n statistician.get_stats(*working_image);\n statistician.print_stats();\n update_shared();\n }\n autofocus_helper.extract_sobel_datapoint(*working_image);\n\n // blob finding\n if (!done()) {\n shared_status.stage = Status::blob_finding;\n status_solver_for_main.share();\n update_shared();\n\n double noise = 1.0;\n if (shared_stats.noise_known) {\n noise = shared_stats.noise;\n }\n shared_blobs.blobs.clear();\n shared_blobs.blobs = blob_finder.find_blobs(*working_image, noise);\n shared_blobs.counter_stars = working_image->counter_stars;\n Shared::Image::blobs_solver_for_main.share();\n update_shared();\n }\n\n autofocus_helper.extract_brightest_blob_datapoint(*working_image, shared_blobs.blobs);\n\n bool solution_found = false;\n Solution solution;\n\n // pattern matching\n if (!done() && shared_settings.pattern_matcher_enabled) {\n shared_status.stage = Status::pattern_matching;\n status_solver_for_main.share();\n\n solution_found = pattern_matcher.match(shared_blobs.blobs, *working_image, solution);\n update_shared();\n }\n\n // refitting\n if (!done() && solution_found) {\n shared_status.stage = Status::refitting;\n status_solver_for_main.share();\n\n refitter.fit(solution, *working_image);\n\n shared_solution_summary = solution;\n shared_solution_summary.counter_stars = shared_status.counter_stars;\n shared_solution_summary.solving_time = shared_status.age.time();\n Shared::Image::solution_summary_for_main.share();\n\n pattern_matcher.inform_blobs_of_matches(solution);\n Shared::Image::blobs_solver_for_main.share();\n }\n\n // getting blob names\n if (!done() && solution_found && shared_settings.display_names) {\n shared_status.stage = Status::getting_names;\n status_solver_for_main.share();\n\n pattern_matcher.get_blob_names(solution);\n Shared::Image::solution_summary_for_main.share();\n }\n\n if (solution_found) {\n shared_status.reason_for_being_done = Status::solved;\n solution.print(logger, true);\n autofocus_helper.extract_star_datapoints(*working_image, solution);\n }\n shared_status.stage = Status::done;\n status_solver_for_main.share();\n autofocus_helper.set_fully_solved(working_image->counter_stars);\n\n update_shared();\n\n logger.log(format(\"total time spent solving %.3f s\") % timer.time());\n logger.log(format(\"finished solving image %s\") % working_image->filename);\n logger.flush();\n}\n\nvoid Solver::solve_thread_function()\n{\n using namespace Shared::Image;\n pattern_matcher.init();\n\n while (!Shared::General::quit) {\n update_shared();\n\n if ((raw_from_camera.r->counter_stars != working_image->counter_stars) &&\n raw_from_camera.r->to_be_solved)\n {\n working_image = (raw_from_camera.r);\n shared_status = *working_image;\n shared_status.abort_counter = shared_settings.abort_counter;\n shared_status.stage = Status::doing_statistics;\n shared_status.reason_for_being_done = Status::no_reason;\n status_solver_for_main.share();\n update_shared();\n solve();\n if (quit_after_one) {\n usleep(int(round(1e6*quit_after_one_delay)));\n Shared::General::quit = true;\n }\n }\n\n usleep(100000);\n }\n}\n\nvoid Solver::wait_for_quit()\n{\n solve_thread.join();\n}\n\n" }, { "alpha_fraction": 0.704006552696228, "alphanum_fraction": 0.7072771787643433, "avg_line_length": 26.81818199157715, "blob_id": "3c6e79e9af81b19bd540172945b430c8cfe72e31", "content_id": "dd9246db2d2ed02a5d4fdf1d0543d7706e11bf19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1223, "license_type": "no_license", "max_line_length": 129, "num_lines": 44, "path": "/external_libs/soem/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "project (ethercat)\ncmake_minimum_required (VERSION 2.8)\n\n# Set global compile flags\nset(CMAKE_C_FLAGS \"-std=gnu99 -ffunction-sections -Wall -Wextra -Wno-unused-parameter -fomit-frame-pointer -fno-strict-aliasing\")\nset(CMAKE_LD_FLAGS ${CMAKE_LD_FLAGS} \"-Wl,--gc-sections\")\n\n# Find external libs\nfind_package(PkgConfig)\n\n# Find Threading lib\nfind_package (Threads)\n\n# add the binary tree to the search path for include files so that we will find mcp_config.h\ninclude_directories (\"${PROJECT_BINARY_DIR}\")\n\nset(OSAL_DIR \"${PROJECT_SOURCE_DIR}/osal\")\nset(OSHW_DIR \"${PROJECT_SOURCE_DIR}/oshw\")\nset(SOEM_DIR \"${PROJECT_SOURCE_DIR}/soem\")\n\ninclude_directories (\n \"${OSAL_DIR}\"\n \"${OSHW_DIR}\"\n \"${SOEM_DIR}\"\n )\n\n# add subobjects\nadd_subdirectory(${OSAL_DIR})\nadd_subdirectory(${OSHW_DIR})\nadd_subdirectory(${SOEM_DIR})\n\nadd_library (osal OBJECT ${OSAL_SRCS} ${OSAL_HEADERS})\nadd_library (oshw OBJECT ${OSHW_SRCS} ${OSHW_HEADERS})\nadd_library (soem OBJECT ${SOEM_SRCS} ${SOEM_HEADERS})\n \nadd_library(ethercat STATIC \n $<TARGET_OBJECTS:osal>\n $<TARGET_OBJECTS:oshw>\n $<TARGET_OBJECTS:soem>\n )\n\ntarget_link_libraries(ethercat ${CMAKE_THREAD_LIBS_INIT} rt)\n\ninstall(TARGETS ethercat DESTINATION lib)" }, { "alpha_fraction": 0.5233111381530762, "alphanum_fraction": 0.5680304765701294, "avg_line_length": 19.58823585510254, "blob_id": "6f3c8f2bc0efffc1c223db707992d5bba986e4bc", "content_id": "bd2a2f5f4e2788822db77bedf64edfc846808072", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1052, "license_type": "no_license", "max_line_length": 86, "num_lines": 51, "path": "/stars/code/solving/blob.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"blob.h\"\n#include <boost/format.hpp>\n#include \"../logging/logger.h\"\n\nusing namespace Solving;\n\nBlob::Blob()\n{\n u = -1;\n v = -1;\n x = -1;\n y = -1;\n correlated_peak = -1;\n\n flux = -1;\n approximate_size = -1;\n base = -1;\n noise = 1.0;\n flux_confidence = -1;\n saturated = false;\n snr = 0.0;\n peak = 0.0;\n\n pedestal_params[0] = 0.0;\n pedestal_params[1] = 0.0;\n pedestal_params[2] = 0.0;\n\n sigma_x = 1.0;\n sigma_y = 1.0;\n fit_error_x = 1.0;\n fit_error_y = 1.0;\n est_flux = -1;\n num_fitting_iterations = -1;\n fit_was_good = false;\n\n id = -1;\n image_noise = 1.0;\n matched = false;\n}\n\nvoid Blob::print(Logging::Logger& logger, string prefix)\n{\n logger.log(boost::format(prefix + \"id %d pos %0.2f %0.2f flux %0.2f saturated %i\")\n % id % x % y % flux % saturated);\n}\n\n" }, { "alpha_fraction": 0.5854978561401367, "alphanum_fraction": 0.5974025726318359, "avg_line_length": 31.421052932739258, "blob_id": "6dc698c8f65bc786fe49932cb620123fafd8627d", "content_id": "0f891244cefdec3edb218b506eaf7dd8dd9b6d3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1848, "license_type": "no_license", "max_line_length": 134, "num_lines": 57, "path": "/interloquendi/Makefile", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "CC = gcc\nCFLAGS = -g -O3 -Wall\nCPPFLAGS = -D__BLASTD__\nBLAST_CPPFLAGS = -DDAS_CARDS=12\n\n########################################################\n# Inputs\n#\n\nLOCAL_OBJS = interloquendi.o quendi.o rendezvous.o\nSHARED_OBJS = blast.o channels.o crc.o quendiclient.o frameread.o\nSHARED_HEADERS = frameread.h channels.h bbc_pci.h blast.h derived.h crc.h \\\n\t\t\t\t\t\t\t\t quendiclient.h quenya.h\nLOCAL_HEADERS = quendi.h\n\n########################################################\n# Run the sanity checks and prepare the build system\n#\n\ninclude ../common/Makefile.shared\n\n########################################################\n# Build Stuff\n#\n\nall:: interloquendi-blast interloquendi-spider\n\ninterloquendi-spider: $(SPIDER_OBJS)\n\t$(CC) $(SPIDER_OBJS) -lnsl -lwrap -o interloquendi-spider\n\ninterloquendi-blast: $(BLAST_OBJS)\n\t$(CC) $(BLAST_OBJS) -lnsl -lwrap -o interloquendi-blast\n\n########################################################\n# Install Stuff\n#\n\n../common/Makefile.shared:\n\t@echo \"ERROR: **************************************************************\"\n\t@echo \"Common build files not found; unable to continue. Try:\"\n\t@echo \" ( cd .. && svn co `svn info --non-interactive | awk ' /URL/ { print $$2 } ' | sed -e 's/trunk\\/.*/trunk\\/common/'` common )\"\n\t@false\n\ninstall:\n\tinstall -m 755 -o root -g root interloquendi-blast /usr/local/sbin\n\tinstall -m 755 -o root -g root interloquendi-spider /usr/local/sbin\n\tinstall -m 644 -o root -g root interloquendi.conf /etc\n\t@echo \"\\n*** NB *** On decom systems, you should run: make install-decom\"\n\ninstall-decom:\n\tinstall -m 755 -o root -g root interloquendi-blast /usr/local/sbin\n\tinstall -m 755 -o root -g root interloquendi-spider /usr/local/sbin\n\tinstall -m 644 -o root -g root interloquendi.conf.decom /etc/interloquendi.conf\n\nclean:\n\trm -f *.o interloquendi-blast interloquendi-spider\n\trm -f share/*.o\n" }, { "alpha_fraction": 0.4399746060371399, "alphanum_fraction": 0.44611474871635437, "avg_line_length": 24.2513370513916, "blob_id": "2a6a4f87023b51758591534001f1cbc843f98664", "content_id": "768d0ab0d9f458a65db89a10de29cbf4746c9d87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4723, "license_type": "no_license", "max_line_length": 92, "num_lines": 187, "path": "/news/news_utils.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <termios.h>\n#include <time.h>\n#include <math.h>\n#include <string.h>\n#include <ctype.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <netdb.h>\n#include <sys/ioctl.h>\n#include <time.h>\n\n#include \"news.h\"\n\n#define TIMEOUT 100\n\n//*********************************************************\n// \"out\" needs to be allocated before we come here.\n//*********************************************************\nvoid convertToUpper(char *in, char *out) {\n int i;\n for (i=0; in[i] != '\\0'; i++) {\n out[i] = toupper(in[i]);\n }\n out[i] = '\\0';\n}\n \n//*********************************************************\n// \"out\" needs to be allocated before we come here.\n//*********************************************************\nvoid convertToLower(char *in, char *out) {\n int i;\n for (i=0; in[i] != '\\0'; i++) {\n out[i] = tolower(in[i]);\n }\n out[i] = '\\0';\n}\n\n//*********************************************************\n// insert data into the fifo\n//*********************************************************\nvoid push(struct fifoStruct *fs, char x[], int size) {\n int i;\n for (i=0; i<size; i++) {\n fs->d[fs->i_in] = x[i];\n fs->i_in++;\n if (fs->i_in>=FIFODEPTH) {\n fs->i_in = 0;\n }\n }\n}\n\n//*********************************************************\n// return data w/out removing it\n//*********************************************************\nvoid peek(struct fifoStruct *fs, char x[], int size) {\n // warning: no error checking. Use nFifo first to make\n // sure you don't wrap the fifo.\n int i;\n int i_out = fs->i_out;\n \n for (i=0; i< size; i++) {\n x[i] = fs->d[i_out];\n i_out++;\n if (i_out >= FIFODEPTH) {\n i_out = 0;\n }\n }\n}\n\n//*********************************************************\n// advance the fifo pointer (removes data)\n//*********************************************************\nvoid advance(struct fifoStruct *fs, int size) {\n fs->i_out += size;\n if (fs->i_out >= FIFODEPTH) {\n fs->i_out -= FIFODEPTH;\n }\n}\n\n//*********************************************************\n// remove data from the fifo\n//*********************************************************\nvoid pop(struct fifoStruct *fs, char x[], int size) {\n peek(fs, x, size);\n advance(fs,size);\n}\n\n//*********************************************************\n// how many bytes are availible in the fifo\n//*********************************************************\nint nFifo(struct fifoStruct *fs) {\n int n;\n\n n = fs->i_in - fs->i_out;\n if (n < 0) n+= FIFODEPTH;\n\n return n;\n}\n\n\n//*********************************************************\n// connect to the political party server\n//*********************************************************\nint party_connect(char *hostname, int port) {\n int s;\n struct sockaddr_in sn;\n struct hostent *hostinfo;\n struct servent *sp;\n struct servent sp_real;\n int on =1 ;\n\n sp = &sp_real;\n sp->s_port = htons(port);\n\n sn.sin_family = AF_INET;\n sn.sin_port = sp->s_port;\n\n if(!inet_aton(hostname, &sn.sin_addr)) {\n hostinfo = gethostbyname(hostname);\n if (hostinfo == NULL) {\n herror(hostname);\n exit(1);\n }\n sn.sin_addr = *(struct in_addr *) hostinfo->h_addr;\n }\n\n /* Create the socket. */\n if ( (s = socket (AF_INET, SOCK_STREAM, 0)) < 0 ) {\n perror(\"socket\");\n exit(1);\n }\n /* set socket options */\n (void) setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));\n\n if (connect(s, (struct sockaddr *)&sn, sizeof (sn)) < 0) {\n perror(\"socket\");\n }\n\n return s;\n}\n\n\n//*********************************************************\n// read data, leaving at least minRead in the fifo, but without overloading the Fifo\n//*********************************************************\nint BlockingRead(int minRead, struct fifoStruct *fs, int tty_fd, char *hostname, int port) {\n int numin;\n char inbuf[FIFODEPTH];\n int numread=0;\n \n time_t t_r, t_lr;\n \n t_lr = time(NULL);\n do {\n ioctl(tty_fd, FIONREAD, &numin);\n\n // Read data from the port into the FIFO\n // don't over-fill the fifo.\n if (numin>=FIFODEPTH - nFifo(fs) - 2) {\n numin = FIFODEPTH - nFifo(fs) - 2;\n }\n if (numin) {\n if (numin>0) {\n numread = read(tty_fd, inbuf, numin);\n push(fs, inbuf, numread);\n }\n t_lr = time(NULL);\n } else {\n t_r = time(NULL);\n if ((t_r -t_lr) > TIMEOUT) {\n printf(\"No data for %us. Resetting connection.\\n\", (unsigned int)(t_r-t_lr));\n t_lr = t_r;\n shutdown(tty_fd, SHUT_RDWR);\n tty_fd = party_connect(hostname, port);\n } \n usleep(10000);\n }\n } while (nFifo(fs)<minRead);\n \n return (numread);\n}\n\n" }, { "alpha_fraction": 0.7171428799629211, "alphanum_fraction": 0.7300000190734863, "avg_line_length": 34, "blob_id": "0c12143355b41868c6dc86f45567950f39dbe229", "content_id": "119f0d5b35d2f33cdb36d49ea80522731848481e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2100, "license_type": "no_license", "max_line_length": 93, "num_lines": 60, "path": "/owl/PBitMultiDataItem.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#ifndef PBITMULTIDATAITEM_H\n#define PBITMULTIDATAITEM_H\n\n#include \"PExtremaDataItem.h\"\n\nclass PBitMultiDataItem : public PExtremaDataItem\n{\n Q_OBJECT\n int _nBits;\n QString _highWord;\n QString _lowWord;\npublic:\n friend QDataStream& operator<<(QDataStream&a,PAbstractDataItem&b);\n friend QDataStream& operator>>(QDataStream&a,PBitMultiDataItem &b);\n friend QVariant save(PAbstractDataItem&);\n friend void load(QVariant v,PBitMultiDataItem&);\n friend class PDotPal;\n friend class PMainWindow;\n PBitMultiDataItem(PBox*parent,QString caption) : PExtremaDataItem(parent,caption),\n _nBits(0) {}\n PBitMultiDataItem(PBox*parent,PBitMultiDataItem* other) : PExtremaDataItem(parent,other),\n _nBits(other->_nBits), _highWord(other->_highWord), _lowWord(other->_lowWord) {}\n virtual void gdUpdate(GetData::Dirfile* dirFile,int lastNFrames);\n QString highWord() const;\n QString lowWord() const;\n int nBits() const;\n\npublic slots:\n void setHighWord(QString highWord,bool force=0);\n void setLowWord(QString lowWord,bool force=0);\n void setNBits(int nBits,bool force=0);\n\nsignals:\n void highWordChanged(QString);\n void lowWordChanged(QString);\n void nBitsChanged(int);\n};\n\n#endif // PBITMULTIDATAITEM_H\n" }, { "alpha_fraction": 0.6420503854751587, "alphanum_fraction": 0.6820156574249268, "avg_line_length": 31.85714340209961, "blob_id": "fed4147443f758dce58a87a5abbf00ae8c7a1c54", "content_id": "0f09cbe8c2f0897095de9de276a25ada4ac9d073", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1151, "license_type": "no_license", "max_line_length": 84, "num_lines": 35, "path": "/stars/code/displaying/glfont2/fonts/editing/convert_glf_to_png.py", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\nimport pylab\nimport Image\n\nclass Header:\n pass\n\ndef parse_header(header_str):\n header = Header()\n header.tex_width = pylab.fromstring(header_str[4:8], \"int32\")[0]\n header.tex_height = pylab.fromstring(header_str[8:12], \"int32\")[0]\n header.start_char = pylab.fromstring(header_str[12:16], \"int32\")[0]\n header.end_char = pylab.fromstring(header_str[16:20], \"int32\")[0]\n return header\n\ndef load_glf(filename):\n infile = open(filename, \"r\")\n contents = infile.read()\n infile.close()\n header = parse_header(contents[0:24])\n num_chars = header.end_char - header.start_char + 1\n characters_str = contents[24: 24+num_chars*24]\n num_tex_bytes = header.tex_width * header.tex_height * 2;\n tex_bytes = contents[24+num_chars*24: 24+num_chars*24 + num_tex_bytes]\n image = Image.fromstring(\"LA\", [header.tex_width, header.tex_height], tex_bytes)\n return image\n\nfilename = \"arial24.glf\"\nimage = load_glf(filename)\n#image.show()\nimage.save(filename.replace(\".glf\", \".png\"))\n\n# To preserve transparency, edit with gimp, and when saving\n# deselect \"Save color values from transparent pixels\".\n\n" }, { "alpha_fraction": 0.5514422655105591, "alphanum_fraction": 0.5771127343177795, "avg_line_length": 23.427392959594727, "blob_id": "17f7c037ee2a15e1a051ba0ca417e8083a4f37b3", "content_id": "4b0d4ff8bb51e45ed0a39a7a228360d254dfb0c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14803, "license_type": "no_license", "max_line_length": 88, "num_lines": 606, "path": "/common/netcmd.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* netcmd: BLAST command protocol client\n *\n * This software is copyright (C) 2005 D. V. Wiebe and others\n * Parts of this software are copyright 2010 Matthew Truch\n * \n * This file is part of the BLAST flight code.\n * \n * This program 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 2 of the License, or\n * (at your option) any later version.\n * \n * This program 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 this program; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n#include <errno.h>\n#include <netdb.h>\n#include <pwd.h>\n#include <signal.h>\n#include <string.h>\n#include <unistd.h>\n\n#include <sys/socket.h>\n#include <sys/syslog.h>\n#include <sys/types.h>\n\n#include <netinet/in.h>\n#include <netinet/tcp.h>\n\n#include <arpa/inet.h>\n\n#include \"netcmd.h\"\n\nunsigned short client_n_scommands = 0;\nunsigned short client_n_mcommands = 0;\nstruct scom *client_scommands;\nstruct mcom *client_mcommands;\nchar client_command_list_serial[1024];\n\nint client_n_groups = 0;\nchar **client_group_names;\n\n#define ME_SIZE 1000\nchar me[ME_SIZE];\nchar owner[ME_SIZE];\nint is_free = -1;\nstatic int sock;\n\n#define PROTOCOL_ERROR fprintf(stderr, \"Protocol error from daemon in %s.\\n\", __func__);\n\nstatic int ReadLine(int sock, char* buffer, int bufflen)\n{\n static int prebuffer_size = 0;\n static char prebuffer[2048] = \"\";\n int i;\n\n i = recv(sock, prebuffer + prebuffer_size, 2048 - prebuffer_size,\n MSG_DONTWAIT);\n\n if (i < 0) {\n if (errno == EAGAIN && prebuffer_size != 0)\n i = 0;\n else\n return i;\n } else if (i == 0)\n return 0;\n\n prebuffer_size += i;\n\n buffer[bufflen - 1] = '\\0';\n for (i = 0; i < bufflen - 1; ++i) {\n if (prebuffer[i] == '\\r' || prebuffer[i] == '\\n' || prebuffer[i] == '\\0') {\n buffer[i] = '\\0';\n break;\n } else {\n buffer[i] = prebuffer[i];\n }\n }\n\n while ((prebuffer[i] == '\\r' || prebuffer[i] == '\\n') && i <= 2048)\n i++;\n\n memmove(prebuffer, prebuffer + i, 2048 - i);\n prebuffer_size -= i;\n\n if (prebuffer[0] == '\\0')\n prebuffer_size = 0;\n\n return strlen(buffer);\n}\n\nstatic int SetOwner(char* buffer)\n{\n int i;\n\n buffer[1023] = 0;\n for (i = 0; i < 1023; ++i)\n if (buffer[i] == '\\n' || buffer[i] == '\\r')\n buffer[i] = 0;\n\n if (strcmp(buffer, \":::free:::\") == 0) {\n is_free = 1;\n } else if (strncmp(buffer, \":::conn:::\", 10) == 0) {\n strncpy(owner, buffer + 10, ME_SIZE - 1);\n owner[ME_SIZE - 1] = 0;\n is_free = 0;\n } else if (strcmp(buffer, \":::nope:::\") == 0) {\n fprintf(stderr, \"Connection refused from this host.\\n\");\n fprintf(stderr, \"Do you need to run blastcmd-authorise?\\n\");\n return -16;\n }\n return 0;\n}\n\nvoid NetCmdDrop(void)\n{\n shutdown(sock, SHUT_RDWR);\n close(sock);\n}\n\n/* Does all non-blocking receiving. *\n * Returns integer: lower byte is which command it received. *\n * upper bytes are optional status. */\nint NetCmdReceive(int silent, size_t oob_buflen, char *oob_message)\n{\n char buffer[1024] = \"\\0\";\n int i;\n\n i = ReadLine(sock, buffer, 1024);\n buffer[1023] = '\\0';\n\n if (i <= 0) {\n if (errno == EAGAIN)\n return CMD_NONE;\n else if (i == 0) {\n /* Connection reset by peer */\n //fprintf(stderr, \"Connection reset by peer.\\n\");\n return CMD_ERRR + (14 << 8);\n } else {\n perror(\"Unable to receive\");\n return CMD_ERRR + (14 << 8);\n }\n } else if (strncmp(buffer, \":::ack:::\", 9) == 0) {\n int ack = atoi(buffer + 9);\n\n if (oob_message) {\n /* look for a message */\n char *ptr = strstr(buffer + 10, \":::\");\n if (ptr)\n strncpy(oob_message, ptr + 3, oob_buflen);\n else\n oob_message[0] = 0;\n }\n\n return CMD_BCMD + (ack << 8);\n } else if (strncmp(buffer, \":::limit:::\", 11) == 0) {\n if (!silent)\n puts(buffer + 11);\n return CMD_LIMT;\n } else if (strncmp(buffer, \":::sent:::\", 10) == 0) {\n if (!silent)\n printf(\"Packet: %s\\n\", buffer + 10);\n return CMD_SENT;\n } else if (strncmp(buffer, \":::pong:::\", 10) == 0) {\n if (!silent)\n printf(\"Pong received: %s\\n\", buffer);\n return CMD_PING;\n } else if (strncmp(buffer, \":::slink:::\", 11) == 0) {\n if (!silent)\n printf(\"Slinking: %s\\n\", buffer);\n return CMD_LURK;\n } else if (strncmp(buffer, \":::sender:::\", 12) == 0) {\n if (!silent)\n printf(\"Sender received: %s\\n\", buffer);\n return CMD_LURK;\n } else if (strncmp(buffer, \":::cmd:::\", 9) == 0) {\n if (!silent)\n printf(\"Sent Command received: %s\\n\", buffer);\n return CMD_LURK;\n } else if (strncmp(buffer, \":::rep:::\", 9) == 0) {\n if (!silent)\n printf(\"Sent Command Response received: %s\\n\", buffer);\n return CMD_LURK + (atoi(buffer + 9) << 8);\n } else if (strncmp(buffer, \":::free:::\", 10) == 0) {\n if (!silent)\n printf(\"Free received: %s\\n\", buffer);\n if (SetOwner(buffer))\n return 0x1000 | CMD_BCMD;\n return CMD_CONN;\n } else if (strncmp(buffer, \":::conn:::\", 10) == 0) {\n if (!silent)\n printf(\"Conn received: %s\\n\", buffer);\n if (SetOwner(buffer))\n return 0x1000 | CMD_BCMD;\n return CMD_CONN;\n } else {\n buffer[1023] = '\\0';\n printf(\"Unknown Reponse: 0x%X %s\\n\", buffer[0], buffer);\n }\n\n return 0;\n}\n\nvoid NetCmdSend(const char* buffer)\n{\n send(sock, buffer, strlen(buffer), MSG_NOSIGNAL);\n}\n\nint NetCmdSendAndReceive(const char *inbuf, int silent, size_t buflen,\n char *outbuf)\n{\n int ack;\n\n NetCmdSend(inbuf);\n\n do {\n ack = NetCmdReceive(silent, buflen, outbuf);\n if ((ack & 0xff) == CMD_BCMD) {\n return ack >> 8;\n } else if ((ack & 0xff) == CMD_SENT) { /* ignore packet info */\n continue;\n } else if ((ack & 0xff) == CMD_NONE)\n usleep(1000);\n else {\n PROTOCOL_ERROR;\n return 20;\n }\n } while (1);\n\n fprintf(stderr, \"Unexpected trap in NetCmdSendAndReceive. Stop.\\n\");\n abort();\n}\n\n/* read a \\n-terminated string from the server, returning a malloc'd buffer */\nstatic char *read_string(int max)\n{\n char *s = malloc(max);\n int i, n;\n char c;\n\n /* max includes the '\\0' */\n for (i = 0; i < max; ++i) {\n if ((n = read(sock, &c, 1)) <= 0) {\n perror(\"Unable to receive\");\n return NULL;\n } else if (i == max - 1 && c != '\\n')\n break;\n else if (c == '\\n') {\n s[i] = 0;\n return s;\n } else\n s[i] = c;\n }\n\n /* overrun */\n PROTOCOL_ERROR;\n return NULL;\n}\n\n// get back default of one command parameter\n// cmdstr should be <cmdname>;<parname>\nint NetCmdGetDefault(double *val, const char *cmdstr)\n{\n char buffer[1024];\n char defstr[100] = \"\";\n int len;\n int i, n;\n char c = 0;\n\n sprintf(buffer, \"::cmddef::%s\\r\\n\", cmdstr);\n send(sock, buffer, strlen(buffer), MSG_NOSIGNAL);\n\n strcpy(buffer, \":::cmddef:::\");\n\n len = strlen(buffer);\n for (i = 0; i < len; ++i) {\n if ((n = read(sock, &c, 1)) <= 0) {\n perror(\"Unable to receive\");\n goto CMDDEF_READ_ERROR;\n } else if (buffer[i] != c)\n goto CMDDEF_READ_ERROR;\n }\n\n for (i = 0; i < 100; ++i) {\n if ((n = read(sock, &c, 1)) <= 0) {\n perror(\"Unable to receive\");\n goto CMDDEF_READ_ERROR;\n } else if (i == 99 && c != '\\n')\n goto CMDDEF_READ_ERROR;\n\n if (c == '\\n') {\n defstr[i] = '\\0';\n break;\n } else if (c != '\\r')\n defstr[i] = c;\n }\n\n *val = atof(defstr);\n return 0;\n\nCMDDEF_READ_ERROR:\n PROTOCOL_ERROR;\n return 1;\n}\n\n//Blocks on reading until list comes through.\nint NetCmdGetCmdList(void)\n{\n uint16_t u16;\n int n;\n char c = 0;\n size_t i, len;\n char buffer[1024] = \"::list::\\r\\n\";\n \n send(sock, buffer, strlen(buffer), MSG_NOSIGNAL);\n\n // Read from sock: verify that \"::rev::\" is returned.\n strcpy(buffer, \":::rev:::\");\n len = strlen(buffer);\n for (i = 0; i < len; ++i) {\n if ((n = read(sock, &c, 1)) <= 0) {\n perror(\"Unable to receive\");\n goto CMDLIST_READ_ERROR;\n } else if (buffer[i] != c) \n goto CMDLIST_READ_ERROR;\n }\n\n // read command list serial number\n for (i = 0; i < 100; ++i) {\n if ((n = read(sock, &c, 1)) <= 0) {\n perror(\"Unable to receive\");\n goto CMDLIST_READ_ERROR;\n } else if (i == 99 && c != '\\n')\n goto CMDLIST_READ_ERROR;\n\n if (c == '\\n') {\n client_command_list_serial[i] = '\\0';\n break;\n } else if (c != '\\r')\n client_command_list_serial[i] = c;\n }\n\n if (read(sock, &client_n_scommands, sizeof(client_n_scommands))\n < (int)sizeof(client_n_scommands))\n {\n printf(\"Warning: NetCmdGetCmdList failed to read n_scommands\\n\");\n goto CMDLIST_READ_ERROR;\n }\n\n if (read(sock, &client_n_mcommands, sizeof(client_n_mcommands))\n < (int)sizeof(client_n_mcommands))\n {\n printf(\"Warning: NetCmdGetCmdList failed to read n_mcommands\\n\");\n goto CMDLIST_READ_ERROR;\n }\n \n if (client_n_scommands > 0xfff || client_n_mcommands > 0xfff ||\n (client_n_scommands == 0) || (client_n_mcommands == 0))\n {\n goto CMDLIST_READ_ERROR;\n }\n\n client_scommands = (struct scom*)malloc((unsigned)client_n_scommands\n * sizeof(struct scom));\n client_mcommands = (struct mcom*)malloc((unsigned)client_n_mcommands\n * sizeof(struct mcom));\n recv(sock, client_scommands, (unsigned)client_n_scommands * sizeof(struct scom),\n MSG_WAITALL);\n recv(sock, client_mcommands, (unsigned)client_n_mcommands * sizeof(struct mcom),\n MSG_WAITALL);\n\n /* read parameter value tables */\n for (;;) {\n int cmd, prm;\n if (read(sock, &u16, sizeof(uint16_t)) < 1)\n goto CMDLIST_READ_ERROR;\n\n if (u16 == 0xFFFF) /* end */\n break;\n \n cmd = u16;\n\n if (read(sock, &u16, sizeof(uint16_t)) < 1)\n goto CMDLIST_READ_ERROR;\n \n prm = u16;\n \n if (cmd >= client_n_mcommands || prm >= client_mcommands[cmd].numparams)\n goto CMDLIST_READ_ERROR;\n\n if (read(sock, &u16, sizeof(uint16_t)) < 1)\n goto CMDLIST_READ_ERROR;\n\n client_mcommands[cmd].params[prm].nt = malloc((u16 + 1) * sizeof(char*));\n for (i = 0; i < u16; ++i) {\n client_mcommands[cmd].params[prm].nt[i] = read_string(80);\n if (client_mcommands[cmd].params[prm].nt[i] == NULL)\n goto CMDLIST_READ_ERROR;\n }\n client_mcommands[cmd].params[prm].nt[u16] = NULL;\n }\n\n return 0;\n\nCMDLIST_READ_ERROR:\n PROTOCOL_ERROR;\n return -1;\n}\n\n//Blocks on reading until list comes through.\nint NetCmdGetGroupNames(void)\n{\n int j;\n char buffer[128] = \"::group::\\r\\n\";\n\n send(sock, buffer, strlen(buffer), MSG_NOSIGNAL);\n\n if (read(sock, &client_n_groups, sizeof(client_n_groups)) <\n (int)sizeof(client_n_groups))\n {\n return -1;\n }\n\n if (client_n_groups < 1 || client_n_groups > 31)\n return -1;\n\n client_group_names = (char**)malloc(client_n_groups * sizeof(char*));\n\n for (j = 0; j < client_n_groups; ++j) {\n client_group_names[j] = read_string(128);\n if (client_group_names[j] == NULL)\n return -1;\n }\n\n return 0;\n}\n\nint NetCmdTakeConn(int silent)\n{\n int ack;\n char buffer[1024] = \"::take::\\r\\n\";\n\n /* don't take it if we already have it */\n if (is_free == 0 && strcmp(owner, me) == 0)\n return 1;\n\n send(sock, buffer, strlen(buffer), MSG_NOSIGNAL);\n\n //cow didn't wait for a response before. Maybe there was a reason for that\n do {\n ack = NetCmdReceive(silent, 0, NULL);\n if ((ack & 0xff) == CMD_BCMD)\n return ack >> 8;\n else if ((ack & 0xff) == CMD_CONN)\n break;\n else if ((ack & 0xff) == CMD_NONE)\n usleep(1000);\n else {\n PROTOCOL_ERROR;\n return 0;\n }\n } while (1);\n\n return (is_free == 0 && strcmp(owner, me) == 0);\n}\n\nconst char* NetCmdBanner(void)\n{\n static char banner[1024];\n if (is_free)\n return \"The conn is free.\";\n else if (strcmp(owner, me) == 0)\n return \"I have the conn.\";\n else {\n snprintf(banner, 1023, \"%s has the conn.\", owner);\n banner[1023] = 0;\n return banner;\n }\n}\n\n/* Only used by COW/Narsil */\nint NetCmdPing(void)\n{\n char buffer[1024] = \"::ping::\\r\\n\";\n ssize_t sent;\n\n sent = send(sock, buffer, strlen(buffer), MSG_NOSIGNAL);\n\n if (sent <= 0) /* send error */\n return 1;\n\n return 0;\n}\n\n// Initialization Function... All blocking network i/o.\nint NetCmdConnect(const char* host_in, int silent, int silenter)\n{\n int i;\n char buffer[1024];\n struct hostent* the_host;\n struct sockaddr_in addr;\n struct passwd pw;\n struct passwd *pwptr;\n char host[255];\n char *user;\n int i_ch;\n int port, n;\n\n for (i_ch = 0; (host_in[i_ch]!='\\0') && (host_in[i_ch]!=':'); i_ch++) {\n host[i_ch] = host_in[i_ch];\n }\n host[i_ch] = '\\0';\n if (host_in[i_ch]==':') {\n port = atoi(host_in+i_ch+1);\n } else {\n port = SOCK_PORT;\n }\n\n /* get remote host IP */\n the_host = gethostbyname(host);\n\n if (the_host == NULL) {\n fprintf(stderr, \"host lookup failed for `%s': %s\\n\", host,\n hstrerror(h_errno));\n return -14;\n }\n\n addr.sin_port = htons(port);\n addr.sin_family = AF_INET;\n memset(addr.sin_zero, 0, sizeof(addr.sin_zero));\n memcpy(&(addr.sin_addr.s_addr), the_host->h_addr, the_host->h_length);\n\n /* set user */\n user = getenv(\"USER\"); \n if (user == NULL) {\n user = getenv(\"LOGNAME\");\n if (user == NULL) {\n getpwuid_r(getuid(), &pw, buffer, 1024, &pwptr);\n user = pw.pw_name;\n }\n }\n gethostname(host, 255);\n snprintf(me, ME_SIZE - 1, \"%s@%s.%i\", user, host, getpid());\n me[ME_SIZE - 1] = 0;\n\n sprintf(buffer, \"::user::%s\\r\\n\", me);\n\n if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {\n perror(\"Unable to create socket\");\n return -141;\n }\n\n n = 1;\n setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &n, sizeof(n));\n\n if (!silenter)\n printf(\"Connecting to %s (%s) port %i ...\\n\", host_in,\n inet_ntoa(addr.sin_addr), port);\n\n if ((i = connect(sock, (struct sockaddr*)&addr, sizeof(addr))) == -1) {\n perror(\"Unable to connect to blastcmd daemon\");\n return -141;\n }\n\n send(sock, buffer, strlen(buffer), MSG_NOSIGNAL);\n if ((i = recv(sock, buffer, 1024, 0)) <= 0) {\n perror(\"Unable to receive\");\n return -141;\n } else if (buffer[0] != ':' || buffer[1] != ':' || buffer[2] != ':') {\n PROTOCOL_ERROR;\n return -141;\n }\n\n if (SetOwner(buffer))\n return -16;\n\n if (is_free == -1) {\n PROTOCOL_ERROR;\n return -141;\n }\n\n if (!silenter)\n printf(\"Connected.\\n\");\n\n if (!silent) {\n if (is_free)\n printf(\"Conn is free.\\n\");\n else\n printf(\"%s has the conn.\\n\", owner);\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6250922679901123, "alphanum_fraction": 0.6435424089431763, "avg_line_length": 22.75438690185547, "blob_id": "76371308f9ff30b4c2ab67a05870f73d4c4a97b9", "content_id": "2d57c4cde30ac6bee1726c034ca01109ca62dd31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1356, "license_type": "no_license", "max_line_length": 73, "num_lines": 57, "path": "/stars/code/displaying/camera.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"camera.h\"\n#if defined(_MSC_VER)\n #include <windows.h>\n#endif\n#include \"GL/gl.h\"\n#include \"GL/glu.h\"\n#include \"block.h\"\n#include \"dynamic_value.h\"\n#include \"../shared/camera/requests.h\"\n#include \"../shared/camera/results.h\"\n\nusing namespace Displaying;\n\n#define shared_requests (*(Shared::Camera::requests_for_camera.w))\n#define shared_results (*(Shared::Camera::results_for_main.r))\n\nCamera::Camera()\n{\n gain.init(\"Gain\");\n Color measured_color = Color(0.5, 0.5, 1.0, 1.0);\n gain.color = measured_color;\n change_size(140, 2*padding+2*text_height);\n}\n\nvoid Camera::update()\n{\n if (shared_results.connected) {\n set_title(\"Camera (conn)\");\n } else {\n set_title(\"Camera\");\n }\n gain.set_value(shared_results.get_gain.value, 2);\n gain.known = false;\n if (shared_results.is_gain_valid(shared_requests)) {\n gain.known = true;\n }\n}\n\nvoid Camera::draw(Position &position)\n{\n update();\n glColor3f(1.0, 1.0, 1.0);\n begin_draw(position);\n draw_border();\n draw_title();\n\n Position pos = {padding+padding, height() - padding - text_height};\n draw_value(gain, pos);\n\n end_draw();\n}\n\n" }, { "alpha_fraction": 0.5848336815834045, "alphanum_fraction": 0.5920621156692505, "avg_line_length": 34.82733917236328, "blob_id": "f1eb9cbfa8464197dd28679fce07bf9cc0196067", "content_id": "8d9b8d726e429214fe45f036afa7c4af849123e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14942, "license_type": "no_license", "max_line_length": 130, "num_lines": 417, "path": "/stars/code/imaging/camera_filesystem.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"camera_filesystem.h\"\n#include <boost/algorithm/string/predicate.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/filesystem/path.hpp>\n#include <boost/filesystem/operations.hpp>\n#include \"../parameters/manager.h\"\n#include \"../shared/image/raw.h\"\n#include \"../shared/general/quit.h\"\n#include \"logger_camera.h\"\n#include \"../tools/quick_cout.h\"\n\nusing namespace Imaging;\nusing Cameraing::logger;\nusing std::string;\n\n#define shared_image (*(Shared::Image::raw_from_camera.w))\n\n\nstruct Imaging::Fileset\n{\n fs::path parent;\n string stem_base;\n string extension;\n std::vector<string> parts;\n};\n\nstatic bool fileset_sort (Fileset fileset0, Fileset fileset1)\n{\n return (fileset0.stem_base < fileset1.stem_base);\n}\n\nCameraFilesystem::CameraFilesystem(Parameters::Manager& params): AbstractCamera(params),\n dirname(params.general.try_get(\"imaging.camera_filesystem.dirname\", string(\"../images\"))),\n load_single_image(params.general.try_get(\"imaging.camera_filesystem.load_single_image\", false)),\n single_image_filename(params.general.try_get(\"imaging.camera_filesystem.single_image_filename\", string(\"test.fits\"))),\n stack_parts(params.general.try_get(\"imaging.camera_filesystem.stack_parts\", true)),\n filesets(new std::vector<Fileset>),\n fileset_index(0),\n resave_images(params.general.try_get(\"imaging.camera_filesystem.resave_images\", false)),\n output_dir(params.general.try_get(\"main.output_dir\", string(\"D:\\\\stars_data\\\\output\"))),\t\t\n flip_vertically(params.general.try_get(\"imaging.camera_filesystem.flip_vertically\", false)),\n temp_pixels(new unsigned short[shared_image.width*shared_image.height]),\n first_run(true),\n repeat(params.general.try_get(\"imaging.camera_filesystem.repeat\", false)),\n startup_delay(params.general.try_get(\"imaging.camera_filesystem.startup_delay\", 1.5)),\n loading_period(params.general.try_get(\"imaging.camera_filesystem.loading_period\", 10.0)),\n #pragma warning(push)\n #pragma warning(disable: 4355)\n thread(boost::bind(&CameraFilesystem::thread_function, this))\n #pragma warning(pop)\n{\n}\n\nCameraFilesystem::~CameraFilesystem()\n{\n delete filesets;\n delete [] temp_pixels;\n}\n\nvoid CameraFilesystem::add_fileset(fs::path path)\n{\n Fileset fileset;\n\n if (boost::algorithm::ends_with(path.string(), \".fits\") ||\n boost::algorithm::ends_with(path.string(), \".fgz\"))\n {\n fileset.parent = path.parent_path();\n\t\tfileset.stem_base = path.stem().string();\n\t\t\tfileset.extension = path.extension().string();\n }\n else if (boost::algorithm::ends_with(path.string(), \".fits.gz\"))\n {\n fileset.parent = path.parent_path();\n fs::path temp_path = path.stem();\n\t\tfileset.stem_base = temp_path.stem().string();\n fileset.extension = \".fits.gz\";\n }\n\n bool added_to_existing_fileset = false;\n if (stack_parts) {\n string::size_type part_location = fileset.stem_base.find(\"_p\", 0);\n if (part_location != string::npos) {\n string::size_type extension_location = fileset.stem_base.find(fileset.extension, part_location);\n fileset.parts.push_back(fileset.stem_base.substr(part_location+2, extension_location));\n fileset.stem_base = fileset.stem_base.substr(0, part_location);\n }\n for (unsigned int i=0; i<filesets->size(); i++) {\n if (fileset.parent == (*filesets)[i].parent && fileset.stem_base == (*filesets)[i].stem_base) {\n if (fileset.parts.size() > 0) {\n (*filesets)[i].parts.push_back(fileset.parts[0]);\n sort((*filesets)[i].parts.begin(), (*filesets)[i].parts.end());\n }\n added_to_existing_fileset = true;\n }\n }\n }\n\n if (!added_to_existing_fileset) {\n (*filesets).push_back(fileset);\n }\n}\n\nvoid CameraFilesystem::try_add_fileset(fs::path path)\n{\n try{\n if (fs::is_regular_file(path)) {\n if (boost::algorithm::ends_with(path.string(), \".fits\") ||\n boost::algorithm::ends_with(path.string(), \".fits.gz\") ||\n boost::algorithm::ends_with(path.string(), \".fgz\"))\n {\n add_fileset(path);\n }\n }\n }\n catch (const std::exception & ex) {\n logger.log(format(\"file loader: exception on %s: %s\") % path % ex.what());\n }\n}\n\nvoid CameraFilesystem::build_filename_list()\n{\n filesets->clear();\n fs::path fullpath( fs::initial_path<fs::path>() );\n fullpath = fs::system_complete(dirname);\n if (!fs::exists(fullpath)) {\n logger.log(format(\"file loader: warning: %s does not exist\") % fullpath);\n }\n else if (!fs::is_directory(fullpath)) {\n logger.log(format(\"file loader: warning: %s is not a directory\") % fullpath);\n }\n else if (fs::is_directory(fullpath)) {\n\n if (load_single_image) {\n fs::path path = fullpath / fs::path(single_image_filename);\n try_add_fileset(path);\n } else {\n fs::directory_iterator end_iter;\n for(fs::directory_iterator dir_iter(fullpath); dir_iter != end_iter; ++dir_iter){\n try_add_fileset(dir_iter->path());\n }\n }\n }\n sort((*filesets).begin(), (*filesets).end(), fileset_sort);\n logger.log(format(\"camera_filesystem found %i filesets\") % filesets->size());\n}\n\nbool CameraFilesystem::init_camera()\n{\n return false;\n}\n\nvoid CameraFilesystem::clean_up_camera()\n{\n}\n\nvoid CameraFilesystem::resave_image(string filename)\n{\n Tools::Timer timer;\n timer.start();\n fitsfile *fptr;\n int status = 0;\n long naxis = 2;\n long naxes[2] = {shared_image.width, shared_image.height};\n if (!fs::exists(output_dir)) {\n output_dir = \"\";\n }\n fs::path dir = fs::path(output_dir) / \"resaved_images\";\n if (!fs::exists(dir)) {\n fs::create_directory(dir);\n }\n string outfilename = (dir / filename).string();\t//changed from file_string by KNS\n //string outfilename = (dir / \"test1.fits.gz\").file_string();\n fits_create_file(&fptr, outfilename.c_str(), &status);\n fits_create_img(fptr, SHORT_IMG, naxis, naxes, &status);\n fits_write_img(fptr, TSHORT, 1, shared_image.width*shared_image.height, shared_image.pixels, &status);\n fits_close_file(fptr, &status);\n logger.log(format(\"file loader: done saving %s, took %f s\") % outfilename % timer.time());\n}\n\nvoid CameraFilesystem::convert_according_to_comment(double& x, string comment)\n{\n boost::to_lower(comment);\n if (comment.find(\"hours\") != string::npos) {\n x = from_hours(x);\n }\n if (comment.find(\"degrees\") != string::npos) {\n x = from_degrees(x);\n }\n}\n\nvoid CameraFilesystem::read_keys(string full_filename)\n{\n int status = -1;\n int status2 = -1;\n int int_value = -1;\n double lat = -1;\n double lst = -1;\n char comment[256];\n char comment2[256];\n fitsfile *file;\n\n if (fits_open_file(&file, full_filename.c_str(), READONLY, &status)) {\n logger.log(format(\"file loader: warning: could not open %s\") % full_filename);\n return;\n }\n\n status = -1;\n fits_read_key(file, TINT, \"FOCUS\", &int_value, NULL, &status);\n if (status == -1) {\n shared_image.focus_known = true;\n shared_image.focus = int_value;\n }\n\n status = -1;\n fits_read_key(file, TINT, \"APERTURE\", &int_value, NULL, &status);\n if (status == -1) {\n shared_image.aperture_known = true;\n shared_image.aperture = int_value;\n }\n\n status = -1;\n fits_read_key(file, TINT, \"COUNTER_STARS\", &int_value, NULL, &status);\n if (status == -1) {\n shared_image.key_counter_stars = int_value;\n }\n\n status = -1;\n fits_read_key(file, TINT, \"COUNTER_FCP\", &int_value, NULL, &status);\n if (status == -1) {\n shared_image.counter_fcp = int_value;\n }\n\n status = -1;\n fits_read_key(file, TINT, \"FRAMENUM\", &int_value, NULL, &status);\n if (status == -1) {\n shared_image.has_netisc_framenum = true;\n shared_image.netisc_framenum = int_value;\n }\n\n if (shared_image.filters.horizontal_from_fits.enabled) {\n shared_image.filters.horizontal_from_fits.valid = false;\n\n status = -1;\n fits_read_key(file, TDOUBLE, \"LAT\", &lat, comment, &status);\n status2 = -1;\n fits_read_key(file, TDOUBLE, \"LST\", &lst, comment2, &status2);\n if (status==-1 && status2==-1) {\n convert_according_to_comment(lat, string(comment));\n convert_according_to_comment(lst, \"hours\");\n shared_image.filters.horizontal_from_fits.lst = lst;\n shared_image.filters.horizontal_from_fits.lat = lat;\n shared_image.filters.horizontal_from_fits.valid = true;\n }\n status = -1;\n fits_read_key(file, TDOUBLE, \"APPROX_LAT\", &lat, comment, &status);\n status2 = -1;\n fits_read_key(file, TDOUBLE, \"APPROX_LST\", &lst, comment2, &status2);\n if (status==-1 && status2==-1) {\n convert_according_to_comment(lat, string(comment));\n convert_according_to_comment(lst, \"hours\");\n shared_image.filters.horizontal_from_fits.lst = lst;\n shared_image.filters.horizontal_from_fits.lat = lat;\n shared_image.filters.horizontal_from_fits.valid = true;\n }\n }\n\n fits_close_file(file, &status);\n}\n\nbool CameraFilesystem::add_pixels(string full_filename, unsigned int exposure_num)\n{\n bool success = false;\n fitsfile *file;\n int status = 0;\n int hdu_type, num_axes;\n long dimensions[2] = {0, 0};\n bool failed_to_open = false;\n\n if (fits_open_file(&file, full_filename.c_str(), READONLY, &status)) {\n logger.log(format(\"file loader: warning: could not open %s\") % full_filename);\n failed_to_open = true;\n }\n else if (fits_get_hdu_type(file, &hdu_type, &status)) {\n logger.log(format(\"file loader: warning: couldn't get the type of HDU for %s\") % full_filename);\n }\n else if (hdu_type != IMAGE_HDU) {\n logger.log(format(\"file loader: warning: %s is not an image type\") % full_filename);\n }\n else if (fits_get_img_dim(file, &num_axes, &status)) {\n logger.log(format(\"file loader: warning: couuld not get num_axes of %s\") % full_filename);\n }\n else if (num_axes != 2) {\n logger.log(format(\"file loader: warning: %s does not have 2 axes\") % full_filename);\n }\n else if (fits_get_img_size(file, 2, dimensions, &status)) {\n logger.log(format(\"file loader: warning: could not get dimensions of %s\") % full_filename);\n }\n else if (num_axes != 2) {\n logger.log(format(\"file loader: warning: %s does not have 2 axes\") % full_filename);\n }\n else if ((dimensions[0] != shared_image.width) || (dimensions[1] != shared_image.height)){\n logger.log(\"file loader: warning: dimensions do not match those of first image in set\");\n }\n else{\n long start[2] = {1, 1};\n fits_read_pix(file, TUSHORT, start, dimensions[0]*dimensions[1],\n NULL, temp_pixels, NULL, &status);\n for (int j=0; j<dimensions[1]; j++) {\n for (int i=0; i<dimensions[0]; i++) {\n int k = (j) * dimensions[0] + i;\n if (flip_vertically) {\n int kp = (dimensions[1]-j-1) * dimensions[0] + i;\n //shared_image.pixels[kp] += temp_pixels[k];\n shared_image.separate_buffers[exposure_num][kp] = temp_pixels[k];\n } else {\n //shared_image.pixels[k] += temp_pixels[k];\n shared_image.separate_buffers[exposure_num][k] = temp_pixels[k];\n }\n }\n }\n success = true;\n }\n if (!failed_to_open) {\n fits_close_file(file, &status);\n }\n return success;\n}\n\nvoid CameraFilesystem::read_image_if_available()\n{\n string filename, full_filename, first_full_filename;\n\n if ((*filesets).size() > 0 && (first_run || repeat)) {\n Fileset* fileset = &((*filesets)[fileset_index]);\n\n unsigned int num_exposures = 0;\n //memset(shared_image.pixels, 0, sizeof(unsigned short)*shared_image.width*shared_image.height);\n if (fileset->parts.size() > 0) {\n filename = fileset->stem_base + \"_pX\" + fileset->extension;\n for (unsigned int i=0; i < fileset->parts.size() && num_exposures < shared_image.max_num_exposures; i++)\n {\n full_filename = (fileset->parent / (fileset->stem_base + \"_p\" + fileset->parts[i] + fileset->extension)).string();\n if (i==0) {\n first_full_filename = full_filename;\n }\n if(add_pixels(full_filename, num_exposures)) {\n num_exposures++;\n }\n }\n } else {\n filename = fileset->stem_base + fileset->extension;\n full_filename = (fileset->parent / (fileset->stem_base + fileset->extension)).string();\n first_full_filename = full_filename;\n if(add_pixels(full_filename, 0)) {\n num_exposures++;\n }\n }\n\n if (num_exposures > 0) {\n shared_image.age.start();\n logger.log(format(\"loaded image %s\")%filename);\n shared_image.from_camera = false;\n shared_image.num_exposures = num_exposures;\n\n shared_image.filename = filename;\n std::vector<string> filename_parts;\n boost::split(filename_parts, filename, boost::is_any_of(\"_.\"));\n shared_image.filename_base = filename_parts[0];\n\n fill_general_admin();\n read_keys(first_full_filename);\n share_image();\n if (resave_images && enough_space_to_save_images()) {\n logger.log(format(\"resaving image %s\")%filename);\n resave_image(filename);\n }\n }\n\n if (fileset_index == (int) ((*filesets).size()-1))\n {\n first_run = false;\n }\n fileset_index = (fileset_index+1) % (*filesets).size();\n }\n}\n\nvoid CameraFilesystem::thread_function()\n{\n startup_timer.start();\n build_filename_list();\n Tools::Timer age_of_last_read_attempt;\n while (!Shared::General::quit) {\n update();\n if (enabled) {\n if ((age_of_last_read_attempt.time() > loading_period) &&\n (startup_timer.time() > startup_delay))\n {\n age_of_last_read_attempt.start();\n logger.log(\"camera_filesystem about to read_image_if_available\");\n read_image_if_available();\n }\n }\n usleep(50000);\n }\n clean_up_camera();\n}\n\nvoid CameraFilesystem::wait_for_quit()\n{\n thread.join();\n}\n\n" }, { "alpha_fraction": 0.5756802558898926, "alphanum_fraction": 0.5867347121238708, "avg_line_length": 18.600000381469727, "blob_id": "1ec0a4a8f709ed5785da93727ac6a96b6f161f6d", "content_id": "fcd31ffffa2532f983452dd9a9e13da95d4bccef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1177, "license_type": "no_license", "max_line_length": 73, "num_lines": 60, "path": "/stars/code/imaging/camera_empty.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"../preprocessor.h\"\n#if (!PREPROCESSOR_USING_CAMERA)\n\n#include \"camera_empty.h\"\n#include \"../shared/general/quit.h\"\n\nusing namespace Imaging;\n\nCamera::Camera(Parameters::Manager& params): AbstractCamera(params),\n #pragma warning(push)\n #pragma warning(disable: 4355)\n thread(boost::bind(&Camera::thread_function, this))\n #pragma warning(pop)\n{\n}\n\nbool Camera::init_camera()\n{\n return false;\n}\n\nvoid Camera::clean_up_camera()\n{\n}\n\nvoid Camera::read_image_if_available()\n{\n}\n\nvoid Camera::thread_function()\n{\n while (!Shared::General::quit) {\n update();\n if (enabled) {\n if (need_to_try_camera_ready()) {\n if (init_camera()) {\n camera_ready = true;\n }\n }\n if (camera_ready) {\n read_image_if_available();\n }\n }\n usleep(50000);\n }\n clean_up_camera();\n}\n\nvoid Camera::wait_for_quit()\n{\n thread.join();\n}\n\n#endif\n" }, { "alpha_fraction": 0.5884546637535095, "alphanum_fraction": 0.5986914038658142, "avg_line_length": 31.08465003967285, "blob_id": "a247265203853be456980cea0768dc477338de7e", "content_id": "d09b6b5c8033bced95e6c65f5bcc2d9017565bd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 28427, "license_type": "no_license", "max_line_length": 113, "num_lines": 886, "path": "/common/bitserver.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* ---------------------------------------------------------------------\n * ----------------------------- BITSERVER -----------------------------\n * ---------------------------------------------------------------------\n *\n * Copyright 2014 Javier Romualdez\n *\n * This program is distributed under the GNU General Public License (GPL)\n * Version 2 or higher.\n *\n * ------------------------- Description -------------------------------\n * The functions here enable UDP communication between various network\n * machines.\n *\n * ---------------------------- Author ---------------------------------\n * L. Javier Romualdez (B.Eng Aerospace)\n * Institute for Aerospace Studies (UTIAS)\n * University of Toronto\n *\n * Created: May 1, 2014\n *\n *\n * -------------------------- Revisions --------------------------------\n *\n */\n\n#include <arpa/inet.h> // socket stuff\n#include <netinet/in.h> // socket stuff\n#include <stdio.h>\n#include <sys/types.h>\n#include <sys/socket.h> // socket stuff\n#include <sys/stat.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <netdb.h>\n#include <pthread.h> // threads\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include \"FIFO.h\"\n#include \"CRC_func.h\"\n#include \"bitserver.h\"\n#include \"blast.h\"\n\n/* packet header (12 bytes)\n * ----------------\n * [0-3] = unique sender recver serial\n * [4-7] = frame number\n * [8-9] = packet number\n * [10-11] = total number of packets\n */\nint verbosity = 0;\n\nuint16_t writeHeader(uint8_t * header, uint32_t serial, uint32_t frame_num, uint16_t i_pkt, uint16_t n_packets) {\n // allocate crc table if necessary\n if (crctable == NULL) {\n if ((crctable = mk_crctable((uint16_t) CRC_POLY, crchware)) == NULL) {\n blast_fatal(\"mk_crctable() memory allocation failed\");\n }\n }\n\n int j;\n uint16_t checksum = 0;\n\n // build header\n *((uint32_t *) (header+0)) = serial;\n *((uint32_t *) (header+4)) = frame_num;\n *((uint16_t *) (header+8)) = i_pkt;\n *((uint16_t *) (header+10)) = n_packets;\n\n for (j = 0; j < PACKET_HEADER_SIZE; j++) crccheck(header[j], &checksum, crctable); // check the checksum\n\n return checksum;\n}\n\nuint16_t readHeader(uint8_t * header, uint32_t **ser, uint32_t **frame_num, uint16_t **i_pkt, uint16_t **n_pkt) {\n // allocate crc table if necessary\n if (crctable == NULL) {\n if ((crctable = mk_crctable((uint16_t) CRC_POLY, crchware)) == NULL) {\n blast_fatal(\"mk_crctable() memory allocation failed\");\n }\n }\n\n int j;\n uint16_t checksum = 0;\n\n // extract header\n *ser = (uint32_t *) (header+0);\n *frame_num = (uint32_t *) (header+4);\n *i_pkt = (uint16_t *) (header+8);\n *n_pkt = (uint16_t *) (header+10);\n\n for (j = 0; j < PACKET_HEADER_SIZE; j++) crccheck(header[j], &checksum, crctable); // check the checksum\n\n return checksum;\n}\n\n/* -------------------------\n * ---- sendDataThread -----\n * -------------------------\n * \n * A worker thread function that sends data to a socket from the BITSender\n * FIFO. This function will automatically divide each FIFO element into\n * packets of the desired maximum packet size (see initBITSender) and send\n * them sequentially over UDP with the appropriate headers for reassembly\n * on the receiving end.\n * \n * Parameters:\n * --------------------------\n * arg : A void pointer to the BITSender struct that this thread is \n * attached to.\n * \n*/\nvoid * sendDataThread(void *arg) {\n struct BITSender *server = (struct BITSender *) arg;\n unsigned int start, size, n_packets, packet_size, packet_maxsize;\n unsigned int i;\n uint8_t *header;\n uint32_t serial, frame_num;\n uint8_t *buffer;\n uint8_t flags;\n\n header = (uint8_t *) calloc(PACKET_HEADER_SIZE+server->packet_maxsize, 1);\n\n while (1) {\n if (!fifoIsEmpty(server->send_fifo)) { // something in the buffer\n serial = server->serial;\n start = server->send_fifo->start;\n size = server->send_fifo->size[start];\n flags = server->send_fifo->flags[start];\n frame_num = server->send_fifo->frame_num[start];\n packet_maxsize = server->packet_maxsize;\n buffer = getFifoRead(server->send_fifo);\n n_packets = (size-1)/packet_maxsize+1;\n\n if (flags & NO_HEADER) { // send packet with header\n if (n_packets > 1) {\n blast_err(\"cannot send headerless multi-packet message.\");\n } else {\n // printf(\"Sending headerless packet\\n\");\n if (sendto(server->sck, buffer, size,\n MSG_NOSIGNAL, (struct sockaddr *) &(server->send_addr),\n server->slen) < 0) {\n blast_err(\"sendTo failed (errno %d)\", errno);\n }\n }\n } else {\n i = 0;\n n_packets = 1;\n packet_size = server->packet_maxsize;\n while (i < n_packets) {\n uint8_t * pkt_buffer = packetizeBuffer(buffer, size, (uint32_t *) &packet_size,\n (uint16_t *) &i, (uint16_t *) &n_packets);\n writeHeader(header, serial, frame_num, i++, n_packets);\n // packet_size = MIN(packet_maxsize, size-(i*packet_maxsize));\n#ifdef MSG_MORE // general Linux kernel\n\n // add header to packet (adds due to MSG_MORE flag)\n if (sendto(server->sck, header, PACKET_HEADER_SIZE,\n MSG_NOSIGNAL | MSG_MORE,\n (struct sockaddr *) &(server->send_addr),\n server->slen) < 0) {\n blast_err(\"sendTo failed (errno %d)\", errno);\n }\n\n // add data to packet and send\n // if (sendto(server->sck, buffer+(i*packet_maxsize), packet_size,\n if (sendto(server->sck, pkt_buffer, packet_size,\n MSG_NOSIGNAL, (struct sockaddr *) &(server->send_addr),\n server->slen) < 0) {\n blast_err(\"sendTo failed (errno %d)\", errno);\n }\n\n#else // for QNX kernel\n\n memcpy(header+PACKET_HEADER_SIZE, buffer+(packet_maxsize*i), packet_size);\n // send packet\n if (sendto(server->sck, header, PACKET_HEADER_SIZE+packet_size,\n MSG_NOSIGNAL, (struct sockaddr *) &(server->send_addr),\n server->slen) < 0) blast_err(\"sendTo failed()\");\n // memset(header+PACKET_HEADER_SIZE, 0, packet_size); // clear data\n\n#endif\n }\n }\n decrementFifo(server->send_fifo);\n } else { // sleep the FIFO\n usleep(1000); // FIFO is sleeping\n }\n }\n\nreturn NULL;\n}\n\n/* -------------------------\n * ---- recvDataThread -----\n * -------------------------\n * \n * A worker thread function that receives data from a socket to the BITRecver\n * FIFO. This function will only add packets to the FIFO without reading\n * headers and/or reassembling packetted data. See buildBITRecverData() \n * for details on reassembling packetted data.\n * \n * Parameters:\n * --------------------------\n * arg : A void pointer to the BITRecver struct that this thread is \n * attached to.\n * \n*/\nvoid * recvDataThread(void *arg) {\n struct BITRecver * server = (struct BITRecver *) arg;\n unsigned int num_bytes;\n /*\n struct sched_param param;\n int pol = 0;\n\n pthread_t this_thread = pthread_self();\n pthread_getschedparam(this_thread, &pol, &param);\n param.sched_priority = 0;\n pthread_setschedparam(this_thread, pol, &param);\n */\n while (1) {\n num_bytes = recvfrom(server->sck, getFifoWrite(server->recv_fifo),\n UDPMAXBUFLEN, 0, (struct sockaddr*)&server->recv_addr, &server->slen);\n\n if (num_bytes <= 0) blast_err(\"recvfrom() failed!\");\n else if (num_bytes > server->packet_maxsize) {\n blast_err(\"Buffer overflow! Received %d bytes for %d byte buffer\\n\",\n num_bytes, server->packet_maxsize);\n // exit(2);\n }\n\n server->recv_fifo->size[server->recv_fifo->end] = num_bytes;\n incrementFifo(server->recv_fifo); // update the fifo\n }\n return NULL;\n}\n\n\n/* -------------------------\n * ----- initBITSender -----\n * -------------------------\n * \n * This function initializes the BITSender struct, which sets up an\n * outbound address on the specified UDP port and associates a FIFO of a\n * particular size. Note that enough memory will be allocated to accomodate\n * packet headers.\n * \n * Parameters:\n * --------------------------\n * server: A pointer to the BITSender struct to be initialized.\n * \n * send_addr: The IP address or hostname for sending data over UDP.\n * If address 255.255.255.255 is used, the sender broadcasts\n * to all addresses on the subnet at the specified port.\n * Note that in this case, my_addr is unset and the socket\n * is not bound to an address.\n * \n * port: The UDP port over which data is sent.\n * \n * fifo_length: The number of full size elements in the FIFO []\n * \n * fifo_maxsize: The maximum size of a full element in the FIFO [bytes].\n * Add data to the FIFO by requesting an address with \n * getBITSenderAddr().\n * \n * When fifo_maxsize=0, the pointers in the FIFO will be\n * set to NULL, in which case the FIFO will be in an\n * unallocated state. To add data to to this type of FIFO,\n * use setBITSenderAddr() (or equivalently setFifoWrite()).\n * \n * packet_maxsize: The maximum size of the packet to be sent over UDP.\n * If the fifo_maxsize > packet_maxsize, each FIFO element\n * will be broken up into the minimum number of packets \n * to be sent over UDP to satisfy the packet_maxsize\n * requirement.\n * \n*/\nint initBITSender(struct BITSender *server, const char *send_addr,\n unsigned int port, unsigned int fifo_length,\n unsigned int fifo_maxsize, unsigned int packet_maxsize) {\n /* ----- BEGIN UDP SOCKET SETUP ------ */\n blast_info(\"Initializing BITSender:\");\n\n if (packet_maxsize == 0) {\n blast_err(\"cannot have a zero packet size\");\n return -1;\n }\n if (fifo_length < 2) {\n blast_err(\"a fifo_length<2 will always overflow.\");\n return -1;\n }\n\n int udpbuffersize = UDPMAXBUFLEN;\n struct hostent* the_target;\n server->slen = sizeof(server->send_addr);\n\n // set up port\n if ((server->sck = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {\n blast_err(\"socket() unsuccessful\");\n return -1;\n }\n\n if (setsockopt(server->sck, SOL_SOCKET, SO_SNDBUF, &udpbuffersize,\n sizeof(udpbuffersize)) < 0) {\n blast_err(\"unable to set socket options.\");\n return -1;\n }\n int optval = 1;\n if (setsockopt(server->sck, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1) {\n blast_err(\"unable to set reusable port\");\n }\n\n if (strcmp(send_addr, \"255.255.255.255\") == 0) { // broadcaster\n int broadcast = 1;\n if (setsockopt(server->sck, SOL_SOCKET, SO_BROADCAST, &broadcast,\n sizeof(broadcast)) == -1) {\n perror(\"setsockopt (SO_BROADCAST)\");\n return -1;\n }\n blast_info(\"-> Broadcast mode\");\n } else { // non-broadcast, so bind to local address\n // set up socket address\n bzero(&(server->my_addr), sizeof(server->my_addr));\n server->my_addr.sin_family = AF_INET;\n server->my_addr.sin_port = htons(port);\n server->my_addr.sin_addr.s_addr = htonl(INADDR_ANY);\n\n if (bind(server->sck, (struct sockaddr *) &(server->my_addr),\n sizeof(server->my_addr)) < 0) {\n perror(\"bind\");\n blast_err(\"Unable to bind to socket (errno=%d)\", errno);\n }\n }\n\n // set up target address\n the_target = gethostbyname(send_addr);\n if (the_target == NULL) {\n blast_err(\"host lookup %s failed.\", send_addr);\n return -1;\n }\n\n bzero(&(server->send_addr), sizeof(server->send_addr));\n server->send_addr.sin_family = AF_INET;\n server->send_addr.sin_port = htons(port);\n memcpy(&server->send_addr.sin_addr.s_addr, the_target->h_addr,\n the_target->h_length);\n\n // set up FIFO\n server->send_fifo = (struct Fifo *) calloc(1, sizeof(struct Fifo));\n\n if (fifo_maxsize != 0) {\n allocFifo(server->send_fifo, fifo_length, fifo_maxsize+PACKET_HEADER_SIZE);\n } else {\n allocFifo(server->send_fifo, fifo_length, 0);\n }\n if (packet_maxsize > fifo_maxsize) {\n blast_err(\"cannot set packet size larger than frame size\");\n return -1;\n }\n server->packet_maxsize = packet_maxsize;\n server->serial = DEFAULT_SERIAL;\n server->frame_num = 0;\n\n blast_info(\"-> SendTo %s:%d\", send_addr, port);\n pthread_create(&server->send_thread, NULL, sendDataThread, (void *) server);\n\n return 1;\n}\n\n/* -------------------------\n * ----- initBITRecver -----\n * -------------------------\n * \n * This function initializes the BITRecver struct, which sets up an\n * outbound address on the specified UDP port and associates a FIFO of a\n * particular size. Note that enough memory will be allocated to accomodate\n * packet headers.\n * \n * Parameters:\n * --------------------------\n * server: A pointer to the BITRecievr struct to be initialized.\n * \n * recv_addr: The IP address or hostname for receiving data over UDP.\n * \n * port: The UDP port over which data is received.\n * \n * fifo_length: The number of full size elements in the FIFO []\n * \n * fifo_maxsize: The maximum size of a full element in the FIFO [bytes].\n * Read data from the FIFO by requesting an address with \n * getBITRecverAddr().\n * \n * packet_maxsize: The maximum size of the packet to be received over UDP.\n * If the fifo_maxsize > packet_maxsize, the number of \n * elements assigned to the FIFO will be the number of \n * packets required to send a full element times fifo_length.\n * \n * num_packets = (fifo_maxsize-1)/packet_maxsize+1\n *\n * \n*/\nint initBITRecver(struct BITRecver *server, const char *recv_addr,\n unsigned int port, unsigned int fifo_length,\n unsigned int fifo_maxsize, unsigned int packet_maxsize) {\n /* ----- BEGIN UDP SOCKET SETUP ------ */\n blast_info(\"Initializing BITRecver:\");\n\n if (fifo_maxsize == 0) {\n blast_err(\"cannot initialize an unallocated receiver\");\n return -1;\n }\n if (packet_maxsize == 0) {\n blast_err(\"cannot have a zero packet size\");\n return -1;\n }\n if (fifo_length < 1) {\n blast_err(\"cannot have a FIFO with 0 elements\");\n return -1;\n }\n\n int udpbuffersize = UDPMAXBUFLEN;\n struct hostent* the_target;\n server->slen = sizeof(server->recv_addr);\n\n // set up port\n if ((server->sck = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {\n blast_err(\"socket() unsuccessful\");\n return -1;\n }\n\n if (setsockopt(server->sck, SOL_SOCKET, SO_SNDBUF, &udpbuffersize,\n sizeof(udpbuffersize)) < 0) {\n blast_err(\"unable to set socket options.\");\n return -1;\n }\n int optval = 1;\n if (setsockopt(server->sck, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1) {\n blast_err(\"unable to set reusable port\");\n }\n\n // set up socket address\n bzero(&(server->my_addr), sizeof(server->my_addr));\n server->my_addr.sin_family = AF_INET;\n server->my_addr.sin_port = htons(port);\n server->my_addr.sin_addr.s_addr = htonl(INADDR_ANY);\n\n if (bind(server->sck, (struct sockaddr *) &(server->my_addr),\n sizeof(server->my_addr)) == -1) {\n blast_err(\"Bind address already in use\");\n return -1;\n }\n\n // set up target address\n the_target = gethostbyname(recv_addr);\n if (the_target == NULL) {\n blast_err(\"Host lookup %s failed.\", recv_addr);\n return -1;\n }\n\n bzero(&(server->recv_addr), sizeof(server->recv_addr));\n server->recv_addr.sin_family = AF_INET;\n server->recv_addr.sin_port = htons(port);\n memcpy(&server->recv_addr.sin_addr.s_addr, the_target->h_addr,\n the_target->h_length);\n\n // set up FIFO\n // need enough space for all packets that constitute a full element\n server->recv_fifo = (struct Fifo *) calloc(1, sizeof(struct Fifo));\n\n unsigned int num_packets = (fifo_maxsize-1)/packet_maxsize+1;\n allocFifo(server->recv_fifo, fifo_length*num_packets,\n packet_maxsize+PACKET_HEADER_SIZE);\n server->packet_maxsize = packet_maxsize+PACKET_HEADER_SIZE;\n server->serial = DEFAULT_SERIAL;\n server->frame_num = 0;\n\n blast_info(\"-> RecvFrom %s:%d\", recv_addr, port);\n pthread_create(&server->recv_thread, NULL, recvDataThread, (void *) server);\n\n\n return 1;\n}\n\n/* -------------------------\n * ---- closeBITSender -----\n * -------------------------\n * \n * This function closes the BITSender struct and deallocates all memory\n * in the FIFO.\n * \n * Parameters:\n * --------------------------\n * server: A pointer to the BITSender struct to be closed.\n * \n * \n*/\nint closeBITSender(struct BITSender *server) {\n pthread_cancel(server->send_thread);\n usleep(100000);\n close(server->sck);\n freeFifo(server->send_fifo);\n blast_info(\"Closed BITSender\");\n return 1;\n}\n\n/* -------------------------\n * ---- closeBITRecver -----\n * -------------------------\n * \n * This function closes the BITRecver struct and deallocates all memory\n * in the FIFO.\n * \n * Parameters:\n * --------------------------\n * server: A pointer to the BITRecver struct to be closed.\n * \n * \n*/\nint closeBITRecver(struct BITRecver *server) {\n pthread_cancel(server->recv_thread);\n usleep(100000);\n close(server->sck);\n freeFifo(server->recv_fifo);\n blast_info(\"Closed BITRecver\");\n return 1;\n}\n\n/* -------------------------\n * --- getBITSenderAddr ----\n * -------------------------\n * \n * This function returns a pointer to the newest element in the BITSender\n * FIFO to write to. Note that this function only returns a valid pointer for\n * a FIFO that has memory allocated to it (maxsize != 0).\n * \n * Parameters:\n * --------------------------\n * server: A pointer to the BITSender struct to be written to.\n * \n * \n*/\nuint8_t *getBITSenderAddr(struct BITSender *server) {\n return getFifoWrite(server->send_fifo);\n}\n\n/* -------------------------\n * -- setBITSenderSerial ---\n * -------------------------\n *\n * This function sets the unique serial associated with BITSender. The receiving\n * end can validate message from this BITSender based on this serial.\n *\n * Parameters:\n * --------------------------\n * server: A pointer to the BITSender.\n * serial: The 32-bit serial number assigned BITSender\n *\n*/\nint setBITSenderSerial(struct BITSender *server, uint32_t serial) {\n if (verbosity) blast_info(\"-> BITSender serial: %.08x\", serial);\n server->serial = serial;\n return 1;\n}\n\n/* -------------------------\n * -- setBITRecverSerial ---\n * -------------------------\n *\n * This function sets the unique serial associated with BITRecver. Messages\n * are validated from the sender based on this serial.\n *\n * Parameters:\n * --------------------------\n * server: A pointer to the BITRecver.\n * serial: The 32-bit serial number assigned BITRecver\n *\n*/\nint setBITRecverSerial(struct BITRecver *server, uint32_t serial) {\n if (verbosity) blast_info(\"-> BITRecver serial: %.08x\", serial);\n server->serial = serial;\n return 1;\n}\n\nint setBITSenderFramenum(struct BITSender * server, uint32_t frame_num)\n{\n server->frame_num = frame_num;\n server->send_fifo->frame_num[server->send_fifo->end] = frame_num;\n return 1;\n}\n\nint setBITRecverFramenum(struct BITRecver * server, uint32_t frame_num)\n{\n server->frame_num = frame_num;\n return 1;\n}\n\n/* -------------------------\n * --- setBITSenderAddr ----\n * -------------------------\n * \n * This function sets the pointer for the newest element in the BITSender \n * FIFO to be written to. Note that this funcion is only successful for \n * a FIFO that is unallocated (maxsize == 0).\n * \n * Parameters:\n * --------------------------\n * server: A pointer to the BITSender.\n * buffer: A pointer to the external buffer containing data to be \n * added to the FIFO.\n * \n*/\nint setBITSenderAddr(struct BITSender *server, uint8_t *buffer) {\n return setFifoWrite(server->send_fifo, buffer);\n}\n\n\n/* -------------------------\n * --- getBITRecverAddr ----\n * -------------------------\n * \n * This function returns a pointer to the oldest element in the BITRecver\n * FIFO to read from and also reports the size of the data in\n * the BITRecver FIFO. This function blocks until there is something in\n * the FIFO to read.\n * \n * Parameters:\n * --------------------------\n * server: A pointer to the BITRecver struct to be read from.\n * size: Returns the size of data in the FIFO.\n * \n * \n*/\nuint8_t *getBITRecverAddr(struct BITRecver *server, unsigned int *size) {\n while (fifoIsEmpty(server->recv_fifo)) usleep(500);\n if (size != NULL) *size = server->recv_fifo->size[server->recv_fifo->start];\n return getFifoRead(server->recv_fifo);\n}\n\n/* -------------------------\n * --- appendBITSenderAddr --\n * -------------------------\n * \n * This function clears all the metadata at the current element in the BITRecver\n * FIFO and decrements the FIFO so that the next element can be read.\n * \n * Parameters:\n * --------------------------\n * server: A pointer to the BITSender struct to clear.\n * \n * \n*/\nint appendBITSenderAddr(struct BITSender *server, unsigned int size) {\n server->send_fifo->frame_num[server->send_fifo->end]= server->frame_num;\n server->send_fifo->size[server->send_fifo->end] = size;\n server->frame_num = server->frame_num+1; // increment the frame number\n return incrementFifo(server->send_fifo);\n}\n\n\n/* -------------------------\n * --- removeBITRecverAddr --\n * -------------------------\n * \n * This function clears all the data at the current element in the BITRecver\n * FIFO and decrements the FIFO so that the next element can be read.\n * \n * Parameters:\n * --------------------------\n * server: A pointer to the BITSender struct to clear.\n * \n * \n*/\nint removeBITRecverAddr(struct BITRecver *server) {\n if (fifoIsEmpty(server->recv_fifo)) {\n blast_err(\"Nothing in the FIFO to remove!\");\n return -1;\n }\n return decrementFifo(server->recv_fifo);\n}\n\n\n/* -------------------------\n * ---- sendToBITSender ----\n * -------------------------\n * \n * This function takes a BITSender and increments the end of the FIFO by 1.\n * As a result, the buffer is incremented in a way that newest data is added to\n * the tail of the FIFO. A data size and serial will be associated with the\n * data in the FIFO as well. Returns the number of bytes sent to the FIFO.\n * \n * Parameters:\n * --------------------------\n * server: A pointer to the BITSender that will be incremented.\n * buffer: A pointer to the buffer to add to BITSender.\n * size: Size of the data written to the BITSender FIFO [bytes].\n * \n * size <= fifo_maxsize when fifo_maxsize != 0\n * \n * flags: Auxilliary flags:\n *\n * NO_HEADER\n * Send packets without header information. This is only\n * valid when fifo_maxsize <= packet_maxsize so that the maximum FIFO\n * element can fit in a single packet\n * \n*/\nint sendToBITSender(struct BITSender *server, uint8_t *buffer,\n unsigned int size, uint8_t flags) {\n if ((size > server->send_fifo->maxsize) && (server->send_fifo->maxsize != 0)) {\n blast_err(\"specified size %d is larger than maximum %d\",\n size, server->send_fifo->maxsize);\n return -1;\n }\n // assign pointer if unallocated and copy if allocated\n if (server->send_fifo->maxsize == 0) {\n setBITSenderAddr(server, buffer);\n } else {\n memcpy(getBITSenderAddr(server), buffer, size);\n }\n server->send_fifo->flags[server->send_fifo->end] |= flags; // set flags\n appendBITSenderAddr(server, size);\n return size;\n}\n\n/* -------------------------\n * ----- peekBITRecver -----\n * -------------------------\n * \n * This function returns 1 if there is data in the recv_fifo and 0 if there\n * isn't data in the recv_fifo. This can be used to check if there is data\n * before calling recvFromBITRecver.\n * \n * Parameters:\n * --------------------------\n * server: A pointer to the BITRecver.\n * \n*/\n\nint peekBITRecver(struct BITRecver *server) {\n return !(fifoIsEmpty(server->recv_fifo));\n}\n\n/* -------------------------\n * --- recvFromBITRecver ---\n * -------------------------\n * \n * This function reads packets from the BITRecver FIFO and stores them in \n * a single reassembled buffer provided by the user. The function returns\n * the total size of the reassembled message as well as the serial number\n * associated with the message. Note that there must be enough space \n * allocated by the user in the user-defined buffer to received the entire\n * message. Also note that this function is blocking (see peekBITRecver to\n * check for data before receiving).\n * \n * If the first packet received has a non-packet header, it is assumed that\n * a single message packet has been received, so the returned message consists\n * of just the one packet (no serial number).\n *\n * If packets are missed from a multipacket message, the entire message is dropped.\n * \n * On general error, the function returns -1. In the case of a serial \n * mismatch, the function returns -2.\n * \n * Parameters:\n * --------------------------\n * server: A pointer to the BITRecver that will be incremented.\n * buffer: A pointer to the buffer in which the reassembled message\n * will be stored. The buffer must be sufficiently large to\n * hold the entire reassembled message or only a partial \n * message will be received.\n * size: The size of the user-defined buffer.\n * flags: Auxilliary flags:\n *\n * NO_HEADER\n * Receive a headerless packet. This is only valid when\n * fifo_maxsize<=packet_maxsize so that the entire message\n * fits in the FIFO as a single packet.\n * \n*/\nint recvFromBITRecver(struct BITRecver *server, uint8_t *buffer,\n unsigned int size, uint8_t flags) {\n uint8_t *readbuffer;\n unsigned int totalbytes = 0;\n int tempnum = -1;\n unsigned int tempsize = 0;\n uint32_t *ser;\n uint32_t *frame_num;\n uint16_t *i_pkt;\n uint16_t *n_pkt;\n uint16_t cur = 0;\n uint8_t complete = 0;\n unsigned int offset = server->packet_maxsize-PACKET_HEADER_SIZE;\n\n while (!complete) {\n if (flags & RECV_TIMEOUT) {\n int timeout_count = 0;\n while (!peekBITRecver(server)) {\n if (timeout_count >= RECV_TIMEOUT_NUM) {\n blast_err(\"recvFrom timeout\");\n\t return -1;\n }\n timeout_count++;\n usleep(100000);\n }\n }\n readbuffer = getBITRecverAddr(server, &tempsize);\n\n if (flags & NO_HEADER) {\n // printf(\"Receiving headerless packet\\n\");\n memcpy(buffer, readbuffer, MIN(tempsize, size));\n totalbytes = MIN(tempsize, size);\n removeBITRecverAddr(server);\n break;\n } else {\n // read and verify the header\n readHeader(readbuffer, &ser, &frame_num, &i_pkt, &n_pkt);\n tempsize -= PACKET_HEADER_SIZE; // data size\n\n if (*ser != server->serial) { // matched serial\n blast_info(\"Serial mismatch: 0x%.08x != 0x%.08x\", *ser, server->serial);\n removeBITRecverAddr(server);\n return -2;\n }\n // set the frame number\n server->frame_num = *frame_num;\n server->recv_fifo->frame_num[server->recv_fifo->start] = *frame_num;\n\n // printf(\"%ld %d %d : %d\\n\",*frame_num,*i_pkt,*n_pkt,tempsize);\n\n // broken buffer breaks\n if ((offset != tempsize) && ((*i_pkt+1) != *n_pkt)) {\n blast_info(\"Packet mismatch!\");\n removeBITRecverAddr(server);\n return -1;\n }\n if ((totalbytes+tempsize) > size) {\n blast_info(\"Buffer overflow!\");\n removeBITRecverAddr(server);\n return -1;\n }\n\n // missed packet breaks\n if (tempnum == -1) { // first packet in message\n if (*i_pkt != 0) { // missed first packet, so bail\n blast_info(\"Missed first packet! Packet %d/%d, serial 0x%.08x,\"\n \"framenumber %d\", *i_pkt, *n_pkt, *ser, *frame_num);\n removeBITRecverAddr(server);\n return -1;\n } else {\n tempnum = *frame_num; // set frame number for message\n }\n } else if (cur != *i_pkt) { // missed middle packet, so bail\n blast_info(\"Missed packet %d != %d (framenum=%d)\", cur, *i_pkt, *frame_num);\n // removeBITRecverAddr(server);\n // return -1;\n }\n\n // normal breaks\n if (*frame_num != ((unsigned int) tempnum)) {\n complete = 1; // next message, so exit\n break;\n } else if ((*i_pkt+1) == *n_pkt) {\n complete = 1; // done message\n }\n\n memcpy(buffer+((*i_pkt)*offset),\n readbuffer+PACKET_HEADER_SIZE, tempsize);\n cur++;\n }\n totalbytes += tempsize;\n if (flags & DONT_REMOVE) {\n break;\n } else {\n removeBITRecverAddr(server);\n }\n }\n return totalbytes;\n}\n\n#ifdef __cplusplus\n}\n#endif\n" }, { "alpha_fraction": 0.686843752861023, "alphanum_fraction": 0.6998146772384644, "avg_line_length": 33.446807861328125, "blob_id": "fa7e492d9c79ab2ec3dd774f1477cd460bf5a9bc", "content_id": "cc86c29e905144ccf8894301df487feeb195c86d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3238, "license_type": "no_license", "max_line_length": 110, "num_lines": 94, "path": "/blast_comms/include/comms_netasync.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/**\n * @file comms_netasync.h\n *\n * @date Jan 16, 2011\n * @author seth\n *\n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2010-2015 Seth Hillbrand\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n\n#ifndef INCLUDE_COMMS_NETASYNC_H\n#define INCLUDE_COMMS_NETASYNC_H\n\n#include <poll.h>\n#include <stdint.h>\n#include <pthread.h>\n\n#include <blast.h>\n#include <comms_netasync.h>\n#include <comms_common.h>\n\n#define BLAST_NET_DEFAULT_CTX_STEP 4\n\nstruct comms_net_async_ctx;\nstruct comms_net_async_handle;\nstruct comms_socket;\n\n/**\n * Callback fired when an event is caught on the socket\n * @param m_handle Async event handler\n * @param m_socket Which socket was caught\n * @param m_events bitfield returned by poll()\n * @param m_priv Arbitrary data pointer\n * @return\n */\ntypedef int (*comms_net_async_callback_t)(struct comms_net_async_handle *m_handle,\n socket_t m_socket, uint16_t m_events, void *m_priv);\n\ntypedef struct comms_net_async_handle\n{\n struct comms_net_async_ctx *ctx;\n union\n {\n socket_t fd;\n size_t index;\n };\n uint16_t events;\n comms_net_async_callback_t process;\n void *priv;\n} comms_net_async_handle_t;\n\ntypedef struct comms_net_async_ctx\n{\n pthread_mutex_t mutex;\n comms_net_async_handle_t **async_handlers;\n size_t num_handlers;\n struct pollfd *pollfds;\n size_t num_fds;\n size_t step_size;\n} comms_net_async_ctx_t;\n\ncomms_net_async_handle_t *comms_net_async_handler_new(socket_t fd, uint16_t events,\n comms_net_async_callback_t cb, void *userdata);\nvoid comms_net_async_handler_free(comms_net_async_handle_t *p);\nvoid comms_net_async_set_events(comms_net_async_handle_t *p, uint16_t events);\nvoid comms_net_async_add_events(comms_net_async_handle_t *p, uint16_t events);\nvoid comms_net_async_del_events(comms_net_async_handle_t *p, uint16_t events);\nsocket_t comms_net_async_sock(comms_net_async_handle_t *p);\nvoid comms_net_async_set_sock(comms_net_async_handle_t *p, socket_t fd);\nvoid comms_net_async_set_callback(comms_net_async_handle_t *p, comms_net_async_callback_t cb, void *userdata);\ncomms_net_async_ctx_t *comms_net_async_ctx_new(size_t chunk_size);\nvoid comms_net_async_ctx_free(comms_net_async_ctx_t *ctx);\nint comms_net_async_ctx_add_sock(comms_net_async_ctx_t *m_ctx, struct comms_socket *m_sock);\nvoid comms_net_async_handler_disconnect_ctx(comms_net_async_handle_t *p);\nint comms_net_async_poll(comms_net_async_ctx_t *ctx, int timeout);\n\n#endif /* BLAST_NETASYNC_H_ */\n" }, { "alpha_fraction": 0.6106666922569275, "alphanum_fraction": 0.6186666488647461, "avg_line_length": 14.306122779846191, "blob_id": "6dd7ef2c5ae403ea2cff60fd15ff182784025122", "content_id": "0a1c79c81ea9da7fbbdf5a3dcdd2ab984c432abe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 751, "license_type": "no_license", "max_line_length": 73, "num_lines": 49, "path": "/stars/code/shared/result.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__RESULT_H\n#define SHARED__RESULT_H\n\nnamespace Shared\n{\n\n\ntemplate <class T>\nclass Result\n{\n public:\n Result();\n Result& operator=(const Result& rhs);\n\n bool found;\n int counter;\n T value;\n};\n\ntemplate <class T>\nResult<T>::Result()\n{\n found = false;\n counter = 0;\n value = 0;\n}\n\ntemplate <class T>\nResult<T>& Result<T>::operator=(const Result<T> &rhs)\n{\n if (this != &rhs) {\n found = rhs.found;\n counter = rhs.counter;\n value = rhs.value;\n }\n return *this;\n}\n\n\n}\n\n#endif\n" }, { "alpha_fraction": 0.5670669078826904, "alphanum_fraction": 0.5790737271308899, "avg_line_length": 30.33333396911621, "blob_id": "cd423ef9c09a7fb8f34b08948bfb1edbe29bd617", "content_id": "a47353f085160b292969057ca9e3a9f957279c59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2916, "license_type": "no_license", "max_line_length": 108, "num_lines": 93, "path": "/stars/code/displaying/housekeeping.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"housekeeping.h\"\n#if defined(_MSC_VER)\n #define NOMINMAX\n #include <windows.h>\n#endif\n#include <string>\n#include <math.h>\n#include <limits>\n#include \"GL/gl.h\"\n#include \"GL/glu.h\"\n#include \"../shared/housekeeping/housekeeper.h\"\n#include \"../tools/timing.h\"\n\nusing namespace Displaying;\nusing std::min;\nusing std::max;\n#define shared_housekeeper (*(Shared::Housekeeping::housekeeper_for_camera.w))\n\nHousekeeping::Housekeeping()\n{\n change_size(140, 2*padding+1*text_height);\n}\n\nvoid Housekeeping::update()\n{\n Color measured_color = Color(0.5, 0.5, 1.0, 1.0);\n unsigned int num_measurements = shared_housekeeper.measurements.size();\n if (measurements.size() != num_measurements) {\n measurements.clear();\n for (unsigned int i=0; i<num_measurements; i++) {\n DynamicValue measurement;\n measurement.init(shared_housekeeper.measurements[i].name);\n measurement.color = measured_color;\n measurements.push_back(measurement);\n }\n Size new_size;\n new_size.w = width();\n new_size.h = min((unsigned int) 2, num_measurements+1)*padding + (num_measurements+1-1)*text_height;\n change_size(new_size, true);\n }\n for (unsigned int i=0; i<num_measurements; i++) {\n if (shared_housekeeper.measurements[i].valid) {\n if (shared_housekeeper.measurements[i].name == \"disktime\") {\n measurements[i].set_value(Time::time_string(shared_housekeeper.measurements[i].value));\n }\n else {\n\t\t\t\tint precision = 5;\n // int precision = 1;\n if (shared_housekeeper.measurements[i].units == \" a\") {\n // precision = 2;\n }\n\t\t\t\t\n measurements[i].set_value(shared_housekeeper.measurements[i].value,\n shared_housekeeper.measurements[i].units, precision);\n }\n }\n }\n update_size(true);\n}\n\nvoid Housekeeping::draw(Position &position)\n{\n begin_draw(position);\n draw_border();\n draw_title();\n\n if (size_update_finished()) {\n Position pos = {padding+padding, height() - padding - text_height};\n if (measurements.size() >= 2) {\n if (disk_timer.time() > 4.0) {\n disk_timer.start();\n }\n if (measurements[1].known && disk_timer.time() > 2.0) {\n draw_value(measurements[1], pos);\n } else {\n draw_value(measurements[0], pos);\n }\n pos.y -= text_height;\n }\n for (unsigned int i=2; i<measurements.size(); i++) {\n draw_value(measurements[i], pos);\n pos.y -= text_height;\n }\n }\n\n end_draw();\n}\n\n" }, { "alpha_fraction": 0.638971209526062, "alphanum_fraction": 0.6453356742858887, "avg_line_length": 37.61616134643555, "blob_id": "fc5d94f64483e736cdbc07f2a8ffe646e500e135", "content_id": "aea56305fe379803fb83d087c7524eaf30123acf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11471, "license_type": "no_license", "max_line_length": 116, "num_lines": 297, "path": "/stars/code/imaging/abstract_camera.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"abstract_camera.h\"\n#ifdef _MSC_VER\n #ifndef __wtypes_h__\n #include <wtypes.h>\n #endif\n#endif\n#include <boost/format.hpp>\n#include <boost/filesystem/fstream.hpp>\n#include <boost/filesystem/operations.hpp>\n#include <fitsio.h>\n#include <string.h>\n#include <limits>\n#include \"../shared/update.h\"\n#include \"../shared/image/raw.h\"\n#include \"../shared/image/status.h\"\n#include \"../shared/autofocus/latest_image.h\"\n#include \"../shared/lens/requests.h\"\n#include \"../shared/lens/results.h\"\n#include \"../shared/solving/filters.h\"\n#include \"../shared/network/client.h\"\n#include \"../shared/camera/results.h\"\n#include \"../shared/simulations/brightness.h\"\n#include \"../shared/housekeeping/housekeeper.h\"\n#include \"../parameters/manager.h\"\n#include \"logger_camera.h\"\n\n#include \"../tools/quick_cout.h\"\n\nusing namespace Imaging;\nusing std::string;\nusing Cameraing::logger;\n\n#define shared_filters (*(Shared::Solving::filters_main_to_camera.r))\n#define shared_image (*(Shared::Image::raw_from_camera.w))\n#define shared_autofocus (*(Shared::Autofocus::latest_image.w))\n#define shared_client (*(Shared::Network::client_for_camera.r))\n#define shared_results (*(Shared::Camera::results_for_main.w))\n#define shared_fcp_lens_requests (*(Shared::Lens::fcp_requests_camera_to_lens.w))\n#define shared_fcp_lens_results (*(Shared::Lens::fcp_results_lens_to_camera.r))\n#define shared_stars_lens_requests (*(Shared::Lens::stars_requests_camera_to_lens.w))\n#define shared_stars_lens_results (*(Shared::Lens::stars_results_lens_to_camera.r))\n#define shared_status (*(Shared::Image::status_main_for_camera.r))\n#define shared_brightness (*(Shared::Simulations::brightness.r))\n#define shared_housekeeper (*(Shared::Housekeeping::housekeeper_for_camera.r))\n\nAbstractCamera::AbstractCamera(Parameters::Manager& params)\n{\n\timage_width = params.general.try_get(\"imaging.camera_real.image_width\", params.general.image_width);\n\timage_height = params.general.try_get(\"imaging.camera_real.image_height\", params.general.image_height);\n\n enabled = params.general.try_get(\"imaging.camera.enabled\", true);\n internal_triggering = params.general.try_get(\"imaging.camera_real.internal_triggering\", false);\n internal_exposure_time = params.general.try_get(\"imaging.camera_real.internal_exposure_time\", 0.120);\n internal_period = params.general.try_get(\"imaging.camera_real.internal_period\", 20.0);\n output_dir = params.general.try_get(\"main.output_dir\", string(\"C:\\\\stars_data\\\\output\"));\n\n camera_ready = false;\n check_camera_ready_period = 120.0;\n max_exposure_time = 0.500;\n\n intermediate_buffer = new unsigned short[image_width*image_height];\n memset(intermediate_buffer, 0, sizeof(unsigned short)*image_width*image_height);\n\n for (unsigned int i=0; i<max_num_buffers; i++) {\n buffers[i] = new unsigned short[image_width*image_height];\n memset(buffers[i], 0, sizeof(unsigned short)*image_width*image_height);\n }\n\n last_lens_requests_focus_counter = -1;\n}\n\nAbstractCamera::~AbstractCamera()\n{\n delete [] intermediate_buffer;\n for (unsigned int i=0; i<max_num_buffers; i++) {\n delete [] buffers[i];\n }\n}\n\nvoid AbstractCamera::update()\n{\n Shared::update(Shared::ThreadNames::camera);\n logger.update();\n}\n\nvoid AbstractCamera::fill_real_camera_admin(boost::posix_time::ptime& timestamp, bool multiple_triggers)\n{\n shared_image.from_camera = true;\n shared_image.dirname = (boost::format(\"%04d-%02d-%02d\")\n % timestamp.date().year()\n % int(timestamp.date().month())\n % timestamp.date().day()\n ).str();\n shared_image.filename_base = (boost::format(\"%04d-%02d-%02d--%02d-%02d-%02d--%03d\")\n % timestamp.date().year()\n % int(timestamp.date().month())\n % timestamp.date().day()\n % timestamp.time_of_day().hours()\n % timestamp.time_of_day().minutes()\n % timestamp.time_of_day().seconds()\n % int(timestamp.time_of_day().fractional_seconds()/1000.0)\n ).str();\n if (multiple_triggers) {\n shared_image.filename = shared_image.filename_base + \"_pX.fits\";\n }\n else {\n shared_image.filename = shared_image.filename_base + \".fits\";\n }\n\n if (shared_fcp_lens_results.is_focus_valid(shared_fcp_lens_requests) &&\n shared_stars_lens_results.is_focus_valid(shared_stars_lens_requests))\n {\n shared_image.focus_known = true;\n shared_image.focus = shared_fcp_lens_results.focus_value;\n } else {\n shared_image.focus_known = false;\n shared_image.focus = -1;\n }\n if (shared_fcp_lens_results.is_aperture_valid(shared_fcp_lens_requests) &&\n shared_stars_lens_results.is_aperture_valid(shared_stars_lens_requests))\n {\n shared_image.aperture_known = true;\n shared_image.aperture = shared_fcp_lens_results.aperture_value;\n } else {\n shared_image.aperture_known = false;\n shared_image.aperture = -1;\n }\n if (shared_results.get_gain.found) {\n shared_image.gain_known = true;\n shared_image.gain = shared_results.get_gain.value;\n } else {\n shared_image.gain_known = false;\n shared_image.gain = -1.0;\n }\n}\n\nvoid AbstractCamera::fill_general_admin()\n{\n using namespace Shared::Image;\n shared_image.filters = shared_filters;\n\t\n shared_image.counter_fcp = shared_client.counter_fcp;\n shared_image.counter_stars = shared_results.counter_stars;\n shared_results.counter_stars++;\n\tshared_image.to_be_solved = false;\n\tupdate();\n\tupdate();\n if (shared_status.stage == Status::empty || shared_status.stage == Status::done || 1) {\n shared_image.to_be_solved = true;\n\t\tlogger.log(\"Image will be solved\");\n\t}\n\telse {\n\t\tlogger.log(format(\"Image will not be solved because stage is %d\\n\") % shared_status.stage );\n\t}\n \n shared_autofocus.counter_stars = shared_image.counter_stars;\n if (shared_brightness.allow_enable && shared_brightness.enabled) {\n logger.log(\"adding fake sky brightness to image\");\n for (unsigned int i=0; i<shared_image.num_exposures; i++) {\n fake_sky.match_brightness(shared_image.separate_buffers[i],\n shared_image.width, shared_image.height, shared_image.single_depth);\n }\n }\n\n memset(shared_image.pixels, 0, sizeof(unsigned short)*shared_image.width*shared_image.height);\n for (unsigned int i=0; i<shared_image.num_exposures; i++) {\n for (int j=0; j<shared_image.width*shared_image.height; j++) {\n shared_image.pixels[j] += shared_image.separate_buffers[i][j];\n }\n }\n shared_image.depth = shared_image.single_depth*shared_image.num_exposures;\n}\n\nvoid AbstractCamera::share_image()\n{\n Shared::Image::raw_from_camera.share();\n Shared::Camera::results_for_main.share();\n Shared::Autofocus::latest_image.share();\n *(Shared::Image::raw_for_image_client1.w) = *(Shared::Image::raw_from_camera.w);\n *(Shared::Image::raw_for_image_client2.w) = *(Shared::Image::raw_from_camera.w);\n Shared::Image::raw_for_image_client1.share();\n Shared::Image::raw_for_image_client2.share();\n}\n\nbool AbstractCamera::enough_space_to_save_images()\n{\n double free_disk_space_gb = std::numeric_limits<double>::infinity();\n for (unsigned int i=0; i<shared_housekeeper.measurements.size(); i++) {\n if (shared_housekeeper.measurements[i].valid) {\n if (shared_housekeeper.measurements[i].name.compare(\"disk\") == 0) {\n free_disk_space_gb = shared_housekeeper.measurements[i].value;\n }\n }\n }\n\n if (free_disk_space_gb < 0.300) {\n logger.log(format(\"warning: not enough disk space to save images (%f GB)\") % free_disk_space_gb);\n return false;\n }\n return true;\n}\n\nvoid AbstractCamera::save_image(unsigned short* pixels, int buffer_num, bool multiple_triggers)\n{\n using namespace Shared::Image;\n namespace fs = boost::filesystem;\n fitsfile *fptr;\n int status = 0;\n long naxis = 2;\n long naxes[2] = {shared_image.width, shared_image.height};\n int unknown = -1;\n if (!fs::exists(output_dir)) {\n output_dir = \"D:/\";\n }\n fs::path images_dir = fs::path(output_dir) / \"images\";\n if (!fs::exists(images_dir)) {\n fs::create_directory(images_dir);\n }\n fs::path dir = fs::path(output_dir) / \"images\" / shared_image.dirname;\n if (!fs::exists(dir)) {\n fs::create_directory(dir);\n }\n string filename = (dir / shared_image.filename).string();\t//changed from file_string() to string() \n if (multiple_triggers) {\n/*\n string tail_filename = (boost::format(\"%s_p%i.fits.gz\")\n %shared_image.filename_base\n %buffer_num).str();\n*/\n string tail_filename = (boost::format(\"%s_p%i.fits\")\n %shared_image.filename_base\n %buffer_num).str();\n\n filename = (dir / tail_filename).string();\t//changed from file_string() to string()\n }\n logger.log(format(\"saving image %s\") % filename);\n fits_create_file(&fptr, filename.c_str(), &status);\n fits_create_img(fptr, SHORT_IMG, naxis, naxes, &status);\n fits_update_key(fptr, TSTRING, (char *)\"WHICH\", (char *)shared_image.which_sensor.c_str(), (char *)\"\", &status);\n fits_update_key(fptr, TINT, (char *)\"CT_STARS\", &shared_image.counter_stars, (char *)\"\", &status);\n fits_update_key(fptr, TINT, (char *)\"CT_MCP\", &shared_image.counter_fcp, (char *)\"\", &status);\n if (shared_image.filters.horizontal_known()) {\n double lat = to_degrees(shared_image.filters.lat());\n double lst = to_hours(shared_image.filters.lst());\n fits_update_key(fptr, TDOUBLE, (char *)\"APRX_LAT\", &lat, (char *)\"DEGREES\", &status);\n fits_update_key(fptr, TDOUBLE, (char *)\"APRX_LST\", &lst, (char *)\"HOURS\", &status);\n } else {\n fits_update_key(fptr, TINT, (char *)\"APRX_LAT\", &unknown, (char *)\"UNKNOWN\", &status);\n fits_update_key(fptr, TINT, (char *)\"APRX_LST\", &unknown, (char *)\"UNKNOWN\", &status);\n }\n\n if (shared_image.focus_known) {\n fits_update_key(fptr, TINT, (char *)\"FOCUS\", &shared_image.focus, (char *)\"ADU\", &status);\n } else {\n fits_update_key(fptr, TINT, (char *)\"FOCUS\", &unknown, (char *)\"UNKNOWN\", &status);\n }\n if (shared_image.aperture_known) {\n fits_update_key(fptr, TINT, (char *)\"APERTURE\", &shared_image.aperture, (char *)\"ADU\", &status);\n }\n else {\n fits_update_key(fptr, TINT, (char *)\"APERTURE\", &unknown, (char *)\"UNKNOWN\", &status);\n }\n if (shared_image.gain_known) {\n float gain = float(shared_image.gain);\n fits_update_key(fptr, TFLOAT, (char *)\"GAIN\", &gain, (char *)\"DB\", &status);\n }\n else {\n fits_update_key(fptr, TDOUBLE, (char *)\"GAIN\", &unknown, (char *)\"UNKNOWN\", &status);\n }\n\n fits_write_img(fptr, TSHORT, 1, shared_image.width*shared_image.height, pixels, &status);\n fits_close_file(fptr, &status);\n\n logger.log(\"done saving image\");\n}\n\nbool AbstractCamera::need_to_try_camera_ready()\n{\n if (camera_ready) {\n return false;\n }\n else if (check_camera_ready_timer.time() > check_camera_ready_period) {\n check_camera_ready_timer.start();\n return true;\n }\n return false;\n}\n\nvoid AbstractCamera::wait_for_quit()\n{\n}\n\n" }, { "alpha_fraction": 0.6486647129058838, "alphanum_fraction": 0.6522254943847656, "avg_line_length": 24.91794776916504, "blob_id": "ec8b4d82071baf76134402c3d66dcfac904507f1", "content_id": "84429d5f1dd448566a954e04f8f6da482da99f21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5056, "license_type": "no_license", "max_line_length": 141, "num_lines": 195, "path": "/stars/code/shared/circular_buffer.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__CIRCULAR_BUFFER_H\n#define SHARED__CIRCULAR_BUFFER_H\n\n// A circular buffer should be used when there are frequent reads\n// In between calls to update(), only num_free_slots calls to share() will be effective\n\n#include \"thread_names.h\"\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Shared\n{\n template <class T> class CircularBufferParent;\n template <class T> class CircularBuffer;\n template <class T> class CircularBufferPass;\n}\n\ntemplate <class T>\nclass Shared::CircularBufferParent\n{\n public:\n CircularBufferParent(ThreadNames::Name writer_thread_, ThreadNames::Name reader_thread_, int num_free_slots=2);\n ~CircularBufferParent();\n void init(Parameters::Manager& params);\n void share();\n void retry_share(ThreadNames::Name writer_thread_);\n\n T* w;\n T* r;\n int size;\n bool last_share_failed;\n T* states;\n int write_index;\n int read_index;\n ThreadNames::Name writer_thread;\n ThreadNames::Name reader_thread;\n\nprotected:\n bool update();\n};\n\ntemplate <class T>\nShared::CircularBufferParent<T>::CircularBufferParent(ThreadNames::Name writer_thread_, ThreadNames::Name reader_thread_, int num_free_slots)\n{\n if (num_free_slots < 1) {\n num_free_slots = 1;\n }\n size = num_free_slots + 2;\n last_share_failed = false;\n states = new T[size];\n\n w = &states[1];\n write_index = 1;\n r = &states[0];\n read_index = 0;\n\n writer_thread = writer_thread_;\n reader_thread = reader_thread_;\n}\n\ntemplate <class T>\nShared::CircularBufferParent<T>::~CircularBufferParent()\n{\n delete [] states;\n}\n\ntemplate <class T>\nvoid Shared::CircularBufferParent<T>::init(Parameters::Manager& params)\n{\n for (int i=0; i<size; i++) {\n states[i].init(params);\n }\n}\n\n// this function called by write-accessing thread\ntemplate <class T>\nvoid Shared::CircularBufferParent<T>::share()\n{\n int next_write_index = write_index + 1;\n if (next_write_index >= size) {\n next_write_index = 0;\n }\n if (next_write_index != read_index) {\n states[next_write_index] = states[write_index];\n w = &states[next_write_index];\n write_index = next_write_index;\n last_share_failed = false;\n } else {\n last_share_failed = true;\n }\n}\n\ntemplate <class T>\nvoid Shared::CircularBufferParent<T>::retry_share(ThreadNames::Name writer_thread_)\n{\n if (writer_thread == writer_thread_) {\n if (last_share_failed) {\n share();\n }\n }\n}\n\n\n// this function called by read-accessing thread\ntemplate <class T>\nbool Shared::CircularBufferParent<T>::update()\n{\n bool updated = false;\n int next_read_index = write_index - 1;\n if (next_read_index < 0) {\n next_read_index = size - 1;\n }\n if (next_read_index != read_index) {\n r = &states[next_read_index];\n read_index = next_read_index;\n updated = true;\n }\n return updated;\n}\n\n\n\n\n\ntemplate <class T>\nclass Shared::CircularBuffer: public Shared::CircularBufferParent<T>\n{\n public:\n CircularBuffer(ThreadNames::Name writer_thread_ = ThreadNames::nobody,\n ThreadNames::Name reader_thread_ = ThreadNames::nobody);\n bool update(ThreadNames::Name thread_name);\n};\n\ntemplate <class T>\nShared::CircularBuffer<T>::CircularBuffer(ThreadNames::Name writer_thread_,\n ThreadNames::Name reader_thread_):\n CircularBufferParent<T>(writer_thread_, reader_thread_)\n{\n}\n\ntemplate <class T>\nbool Shared::CircularBuffer<T>::update(ThreadNames::Name thread_name)\n{\n if (this->reader_thread == thread_name) {\n return CircularBufferParent<T>::update();\n }\n return false;\n}\n\n\n\n\n\ntemplate <class T>\nclass Shared::CircularBufferPass: public Shared::CircularBufferParent<T>\n{\n public:\n CircularBufferPass(ThreadNames::Name writer_thread_ = ThreadNames::nobody,\n ThreadNames::Name reader_thread_ = ThreadNames::nobody);\n void update_and_pass_to(Shared::CircularBufferParent<T>& writer, ThreadNames::Name thread_name);\n};\n\ntemplate <class T>\nShared::CircularBufferPass<T>::CircularBufferPass(ThreadNames::Name writer_thread_,\n ThreadNames::Name reader_thread_):\n CircularBufferParent<T>(writer_thread_, reader_thread_)\n{\n}\n\n// this function called by read-accessing thread of this, and the write-accessing thread of writer\ntemplate <class T>\nvoid Shared::CircularBufferPass<T>::update_and_pass_to(Shared::CircularBufferParent<T>& writer, ThreadNames::Name thread_name)\n{\n if (writer.writer_thread == thread_name && this->reader_thread == thread_name) {\n if (CircularBufferParent<T>::update()) {\n *(writer.w) = *(this->r);\n writer.share();\n } else {\n writer.retry_share(thread_name);\n }\n }\n}\n\n\n#endif\n\n" }, { "alpha_fraction": 0.6704638004302979, "alphanum_fraction": 0.6704638004302979, "avg_line_length": 20.910715103149414, "blob_id": "4c056bf13fae32f5e2442462f7a68d71899d27bd", "content_id": "2bd2c033e5d0c50277c3feb6eda64cdbe140249e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1229, "license_type": "no_license", "max_line_length": 101, "num_lines": 56, "path": "/stars/code/imaging/badpix.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#pragma once\n\n#ifndef SOLVING__FINDING__BADPIX_H\n#define SOLVING__FINDING__BADPIX_H\n\n#include <string>\n#include <vector>\n//#include \"estimator.h\"\n#include \"code/solving/finding/estimator.h\"\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n}\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Solving\n{\n namespace Finding\n {\n class Badpix;\n }\n}\n\nclass Solving::Finding::Badpix\n{\n public:\n\tBadpix(Parameters::Manager& params);\n ~Badpix();\n int load_badpix(std::string fname); // Load bad pixel map from file\n\tvoid fix_badpix(Shared::Image::Raw& image); // set bad pixels to val\n //std::vector<Blob> fit_blobs(Shared::Image::Raw& image, std::vector<Blob> &blobs);\tused as model\n\tvoid setnextblob( std::vector<Blob> &nextblob_in );\n\tvoid setprevblob( std::vector<Blob> &prevblob_in );\n\tstd::vector<Blob> getnextblob();\n\tstd::vector<Blob> getprevblob();\n\tstd::string badpixlist;\n \n private:\n \tunsigned int *badpixels; // array of indices of bad pixels in CCD frames\n\tunsigned int numbadpix; // # of bad pixels \n\tstd::vector<Blob> &nextblob; // head/tail pointers for\n\tstd::vector<Blob> &prevblob; // the list. \n\tint image_width;\n int image_height;\n \n};\n\n#endif \n\n" }, { "alpha_fraction": 0.6618589758872986, "alphanum_fraction": 0.6746794581413269, "avg_line_length": 22.961538314819336, "blob_id": "d8a4fcf09b99870c97dbffb1311beb8749070f12", "content_id": "185f47ed6cf4293f7d30050df6031721e67ab2be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 625, "license_type": "no_license", "max_line_length": 74, "num_lines": 26, "path": "/stars/code/shared/image/matching_progress.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"matching_progress.h\"\n\nusing namespace Shared::Image;\n\nMatchingProgress::MatchingProgress()\n{\n counter_stars = -1;\n triplet_counter = -1;\n progress = 0.0;\n}\n\nMatchingProgress& MatchingProgress::operator=(const MatchingProgress &rhs)\n{\n if (this != &rhs) {\n counter_stars = rhs.counter_stars;\n triplet_counter = rhs.triplet_counter;\n progress = rhs.progress;\n }\n return *this;\n}\n\n" }, { "alpha_fraction": 0.5410277843475342, "alphanum_fraction": 0.5514743328094482, "avg_line_length": 21.312030792236328, "blob_id": "c113e8b9fba5fc9021182d76a1c6759c09afe423", "content_id": "6a50bccf512f9f7580b1f5949916d62553dfe9c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5935, "license_type": "no_license", "max_line_length": 97, "num_lines": 266, "path": "/common/pq.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * pq.c\n *\n * @date Jan 31, 2011\n * @author seth\n *\n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2010 Columbia University\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * Based on fdqueue.c from the Apache httpd project. Original code is\n * licensed under Apache License version 2.0. A copy of this is\n * available at http://www.apache.org/licenses/LICENSE-2.0\n *\n */\n\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"pq.h\"\n\n\n#define LEFT(i) ((i) << 1)\n#define RIGHT(i) (((i) << 1) + 1)\n#define PARENT(i) ((i) >> 1)\n\n\npq_t *pq_init(size_t n,\n pq_cmp_pri_f cmppri, pq_get_pri_f getpri,\n pq_set_pri_f setpri, pq_get_pos_f getpos,\n pq_set_pos_f setpos)\n{\n pq_t *q;\n\n if (!(q = malloc(sizeof(pq_t)))) return NULL;\n\n /* Need to allocate n+1 elements since element 0 isn't used. */\n if (!(q->d = malloc((n + 1) * sizeof(void *)))) {\n free(q);\n return NULL;\n }\n\n q->size = 1;\n q->avail = q->step = (n + 1); /* see comment above about n+1 */\n q->cmppri = cmppri;\n q->setpri = setpri;\n q->getpri = getpri;\n q->getpos = getpos;\n q->setpos = setpos;\n\n return q;\n}\n\n\nvoid pq_free(pq_t *q)\n{\n free(q->d);\n free(q);\n}\n\n\nsize_t pq_size(pq_t *q)\n{\n /* queue element 0 exists but doesn't count since it isn't used. */\n return (q->size - 1);\n}\n\n\nstatic void bubble_up(pq_t *q, size_t i)\n{\n size_t parent_node;\n void *moving_node = q->d[i];\n pq_pri_t moving_pri = q->getpri(moving_node);\n\n for (parent_node = PARENT(i);\n ((i > 1) && q->cmppri(q->getpri(q->d[parent_node]), moving_pri));\n i = parent_node, parent_node = PARENT(i)) {\n q->d[i] = q->d[parent_node];\n q->setpos(q->d[i], i);\n }\n\n q->d[i] = moving_node;\n q->setpos(moving_node, i);\n}\n\n\nstatic size_t maxchild(pq_t *q, size_t i)\n{\n size_t child_node = LEFT(i);\n\n if (child_node >= q->size) return 0;\n\n if ((child_node + 1) < q->size &&\n q->cmppri(q->getpri(q->d[child_node]), q->getpri(q->d[child_node + 1]))) {\n child_node++; /* use right child instead of left */\n }\n\n return child_node;\n}\n\nstatic void percolate_down(pq_t *q, size_t i)\n{\n size_t child_node;\n void *moving_node = q->d[i];\n pq_pri_t moving_pri = q->getpri(moving_node);\n\n while ((child_node = maxchild(q, i)) && q->cmppri(moving_pri, q->getpri(q->d[child_node]))) {\n q->d[i] = q->d[child_node];\n q->setpos(q->d[i], i);\n i = child_node;\n }\n\n q->d[i] = moving_node;\n q->setpos(moving_node, i);\n}\n\nint pq_insert(pq_t *q, void *d)\n{\n void *tmp;\n size_t i;\n size_t newsize;\n\n if (!q) return 1;\n\n /* allocate more memory if necessary */\n if (q->size >= q->avail) {\n newsize = q->size + q->step;\n if (!(tmp = realloc(q->d, sizeof(void *) * newsize))) return 1;\n q->d = tmp;\n q->avail = newsize;\n }\n\n /* insert item */\n i = q->size++;\n q->d[i] = d;\n bubble_up(q, i);\n\n return 0;\n}\n\nvoid pq_change_priority(pq_t *q, pq_pri_t new_pri, void *d)\n{\n size_t posn;\n pq_pri_t old_pri = q->getpri(d);\n\n q->setpri(d, new_pri);\n posn = q->getpos(d);\n if (q->cmppri(old_pri, new_pri))\n bubble_up(q, posn);\n else\n percolate_down(q, posn);\n}\n\nint pq_remove(pq_t *q, void *d)\n{\n size_t posn = q->getpos(d);\n q->d[posn] = q->d[--q->size];\n if (q->cmppri(q->getpri(d), q->getpri(q->d[posn])))\n bubble_up(q, posn);\n else\n percolate_down(q, posn);\n\n return 0;\n}\n\nvoid *pq_pop(pq_t *q)\n{\n void *head;\n\n if (!q || q->size == 1) return NULL;\n\n head = q->d[1];\n q->d[1] = q->d[--q->size];\n percolate_down(q, 1);\n\n return head;\n}\n\nvoid *pq_peek(pq_t *q)\n{\n void *d;\n if (!q || q->size == 1) return NULL;\n d = q->d[1];\n return d;\n}\n\nvoid pq_dump(pq_t *q, FILE *out, pq_print_entry_f print)\n{\n int i;\n\n fprintf(stdout, \"posn\\tleft\\tright\\tparent\\tmaxchild\\t...\\n\");\n for (i = 1; i < q->size; i++) {\n fprintf(stdout, \"%d\\t%d\\t%d\\t%d\\t%ul\\t\",\n i, LEFT(i), RIGHT(i), PARENT(i), (unsigned int) maxchild(q, i));\n print(out, q->d[i]);\n }\n}\n\n\nstatic void set_pos(void *d, size_t val)\n{\n /* do nothing */\n}\n\n\nstatic void set_pri(void *d, pq_pri_t pri)\n{\n /* do nothing */\n}\n\n\nvoid pq_print(pq_t *q, FILE *out, pq_print_entry_f print)\n{\n pq_t *dup;\n void *e;\n\n dup = pq_init(q->size, q->cmppri, q->getpri, set_pri, q->getpos, set_pos);\n dup->size = q->size;\n dup->avail = q->avail;\n dup->step = q->step;\n\n memcpy(dup->d, q->d, (q->size * sizeof(void *)));\n\n while ((e = pq_pop(dup)))\n print(out, e);\n\n pq_free(dup);\n}\n\n\nstatic int subtree_is_valid(pq_t *q, int pos)\n{\n if (LEFT(pos) < q->size) {\n /* has a left child */\n if (q->cmppri(q->getpri(q->d[pos]), q->getpri(q->d[LEFT(pos)]))) return 0;\n if (!subtree_is_valid(q, LEFT(pos))) return 0;\n }\n if (RIGHT(pos) < q->size) {\n /* has a right child */\n if (q->cmppri(q->getpri(q->d[pos]), q->getpri(q->d[RIGHT(pos)]))) return 0;\n if (!subtree_is_valid(q, RIGHT(pos))) return 0;\n }\n return 1;\n}\n\n\nint pq_is_valid(pq_t *q)\n{\n return subtree_is_valid(q, 1);\n}\n" }, { "alpha_fraction": 0.6796116232872009, "alphanum_fraction": 0.6828479170799255, "avg_line_length": 18.3125, "blob_id": "f763ba73559a011476c2de48cb205718c3194197", "content_id": "2904a405594a5bc6904426a3d724d6c28cec3ab0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 618, "license_type": "no_license", "max_line_length": 48, "num_lines": 32, "path": "/owl/PStyleChooser.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#ifndef PSTYLECHOOSER_H\n#define PSTYLECHOOSER_H\n\n#include <QWidget>\n#include <QComboBox>\n#include <PStyle.h>\n\nnamespace Ui {\n class PStyleChooser;\n}\n\nclass PStyleChooser : public QWidget\n{\n Q_OBJECT\n PStyle** current;\npublic:\n explicit PStyleChooser(QWidget *parent = 0);\n ~PStyleChooser();\npublic slots:\n void setNoWidgetStyleRef() { current=0; }\n void setWidgetStyleRef(PStyle*& style);\n void select(QString s);\n void boldLogic(bool);\n void italicLogic(bool);\n void fgLogic();\n void bgLogic();\n void refresh();\nprivate:\n Ui::PStyleChooser *ui;\n};\n\n#endif // PSTYLECHOOSER_H\n" }, { "alpha_fraction": 0.5957363843917847, "alphanum_fraction": 0.6046867370605469, "avg_line_length": 33.914772033691406, "blob_id": "86c1acd921b45235f79b0b91b3ca39c30e529431", "content_id": "808929dece670bcde97e950356b2cacb554d42b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 30725, "license_type": "no_license", "max_line_length": 113, "num_lines": 880, "path": "/liblinklist/linklist_writer.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * linklist_writer.c: \n *\n * This software is copyright \n * (C) 2015-2018 University of Toronto, Toronto, ON\n *\n * This file is part of the SuperBIT project, modified and adapted for BLAST-TNG.\n *\n * linklist 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 2 of the License, or\n * (at your option) any later version.\n *\n * linklist 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: April 9, 2018 by Javier Romualdez\n */\n\n\n#include <math.h>\n#include <arpa/inet.h> // socket stuff\n#include <netinet/in.h> // socket stuff\n#include <stdio.h> // socket stuff\n#include <sys/types.h> // socket types\n#include <sys/socket.h> // socket stuff\n#include <sys/stat.h>\n#include <dirent.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <signal.h>\n#include <stdlib.h>\n#include <string.h>\n#include <pthread.h> // threads\n#include <openssl/md5.h>\n#include <float.h>\n#include <errno.h>\n\n#include \"linklist.h\"\n#include \"linklist_compress.h\"\n#include \"linklist_writer.h\"\n\n#ifdef __cplusplus\n\nextern \"C\"{\n\n#endif\n\nextern int (*linklist_info)(const char *, ...);\nextern int (*linklist_err)(const char *, ...);\nextern int (*linklist_warn)(const char *, ...);\nextern int (*linklist_fatal)(const char *, ...);\n\nextern superframe_entry_t block_entry;\nextern superframe_entry_t stream_entry;\nextern unsigned int ll_rawfile_default_fpf;\n\n// creates a symlink for the rawfile with the new name pointing to the ll_rawfile basename \nvoid create_rawfile_symlinks(linklist_rawfile_t * ll_rawfile, char * newname) {\n char filename[LINKLIST_MAX_FILENAME_SIZE*2] = {0};\n char symname[LINKLIST_MAX_FILENAME_SIZE*2] = {0};\n\n snprintf(symname, LINKLIST_MAX_FILENAME_SIZE*2, \"%s\" SUPERFRAME_FORMAT_EXT, newname);\n snprintf(filename, LINKLIST_MAX_FILENAME_SIZE*2, \"%s\" SUPERFRAME_FORMAT_EXT, ll_rawfile->basename);\n unlink(symname);\n if (symlink(filename, symname) < 0) {\n linklist_err(\"Unable to form symlink %s -> %s\\n\", filename, symname);\n }\n\n snprintf(symname, LINKLIST_MAX_FILENAME_SIZE*2, \"%s\" LINKLIST_FORMAT_EXT, newname);\n snprintf(filename, LINKLIST_MAX_FILENAME_SIZE*2, \"%s\" LINKLIST_FORMAT_EXT, ll_rawfile->basename);\n unlink(symname);\n if (symlink(filename, symname) < 0) {\n linklist_err(\"Unable to form symlink %s -> %s\\n\", filename, symname);\n }\n\n snprintf(symname, LINKLIST_MAX_FILENAME_SIZE*2, \"%s\" CALSPECS_FORMAT_EXT, newname);\n snprintf(filename, LINKLIST_MAX_FILENAME_SIZE*2, \"%s\" CALSPECS_FORMAT_EXT, ll_rawfile->basename);\n unlink(symname);\n if (symlink(filename, symname) < 0) {\n linklist_err(\"Unable to form symlink %s -> %s\\n\", filename, symname);\n }\n\n snprintf(symname, LINKLIST_MAX_FILENAME_SIZE*2, \"%s\" LINKLIST_EXT \".00\", newname);\n snprintf(filename, LINKLIST_MAX_FILENAME_SIZE*2, \"%s\" LINKLIST_EXT \".00\", ll_rawfile->basename);\n unlink(symname);\n if (symlink(filename, symname) < 0) {\n linklist_err(\"Unable to form symlink %s -> %s\\n\", filename, symname);\n }\n}\n\nvoid make_linklist_rawfile_name(linklist_t * ll, char * filename) {\n // get the date string for file saving\n time_t now = time(0);\n char datestring[LINKLIST_MAX_FILENAME_SIZE] = {0};\n struct tm * tm_t = localtime(&now);\n strftime(datestring, sizeof(datestring)-1, \"%Y-%m-%d-%H-%M-%S\", tm_t);\n char tempname[LINKLIST_MAX_FILENAME_SIZE] = {0};\n\n int i;\n // strip possible extensions in name\n for (i = 0; i < (int) strlen(ll->name); i++) {\n if (ll->name[i] == '.') break;\n }\n strncpy(tempname, ll->name, i);\n snprintf(filename, LINKLIST_MAX_FILENAME_SIZE, \"%s/%s_%s\", archive_dir, tempname, datestring);\n}\n\nint seekend_linklist_rawfile(linklist_rawfile_t * ll_rawfile) {\n // seek to the current file and file location to be written to next\n int fileindex = ll_rawfile->isseekend;\n\n if (ll_rawfile->isseekend < 0) {\n // get the directory that the binary files are located\n int i, pos;\n char filename[LINKLIST_MAX_FILENAME_SIZE] = {0};\n strcpy(filename, ll_rawfile->basename);\n for (pos = strlen(filename)-1; pos >= 0; pos--) {\n if (filename[pos] == '/') {\n filename[pos] = '\\0';\n break;\n }\n }\n\n // get list of the files in the directory\n struct dirent **dir;\n int n = scandir(filename, &dir, NULL, alphasort);\n\n // find the highest number binary fragment file with the matching name in the directory\n snprintf(filename, LINKLIST_MAX_FILENAME_SIZE, \"%s\" LINKLIST_EXT \".\", ll_rawfile->basename+pos+1);\n for (i = 0; i < n; i++) {\n if (strncmp(filename, dir[i]->d_name, strlen(filename)) == 0) {\n int tmpindex = atoi(dir[i]->d_name+strlen(filename));\n fileindex = (tmpindex > fileindex) ? tmpindex : fileindex;\n }\n }\n if (fileindex < 0) fileindex = 0; // catch exception if no files exist\n ll_rawfile->isseekend = fileindex;\n }\n\n // linklist_info(\"%d %d\\n\", fileindex);\n\n do {\n // seek to the beginning of the fragment files\n if (seek_linklist_rawfile(ll_rawfile, ll_rawfile->fpf*fileindex)) {\n return -1;\n }\n if (fseek(ll_rawfile->fp, 0, SEEK_END)) {\n return -1;\n }\n fileindex++;\n } while ((ll_rawfile->framenum = ftell(ll_rawfile->fp)/ll_rawfile->framesize) >= ll_rawfile->fpf);\n\n return 0; \n}\n\nint seek_linklist_rawfile(linklist_rawfile_t * ll_rawfile, unsigned int framenum) {\n if (!ll_rawfile) {\n linklist_err(\"Null linklist_rawfile\\n\");\n return -1;\n }\n unsigned int fileindex = framenum / ll_rawfile->fpf;\n\n if (fileindex != ll_rawfile->fileindex || !ll_rawfile->fp) {\n ll_rawfile->fileindex = fileindex;\n if ((int64_t) fileindex > ll_rawfile->isseekend) ll_rawfile->isseekend = fileindex;\n\n // close the old file \n if (ll_rawfile->fp) {\n fclose(ll_rawfile->fp);\n ll_rawfile->fp = NULL;\n }\n char filename[LINKLIST_MAX_FILENAME_SIZE*2];\n snprintf(filename, LINKLIST_MAX_FILENAME_SIZE*2, \"%s\" LINKLIST_EXT \".%.2u\", ll_rawfile->basename, fileindex);\n ll_rawfile->fp = fpreopenb(filename);\n if (!ll_rawfile->fp) {\n linklist_err(\"Could not open raw linklist binary file %s\\n\", filename);\n return -2;\n }\n }\n\n ll_rawfile->framenum = framenum % ll_rawfile->fpf;\n\n return fseek(ll_rawfile->fp, ll_rawfile->framenum*ll_rawfile->framesize, SEEK_SET);\n}\n\nlinklist_rawfile_t * open_linklist_rawfile(char * basename, linklist_t * ll) {\n return open_linklist_rawfile_opt(basename, ll, 0);\n}\n\n// flags are specific to linklist_rawfiles (separate from ll->flags)\nlinklist_rawfile_t * open_linklist_rawfile_opt(char * basename, linklist_t * ll, unsigned int flags) {\n if (!basename || (strlen(basename) == 0)) {\n linklist_err(\"Invalid rawfile basename\");\n return NULL;\n }\n\n linklist_rawfile_t * ll_rawfile = calloc(1, sizeof(linklist_rawfile_t));\n strcpy(ll_rawfile->basename, basename);\n ll_rawfile->ll = ll;\n ll_rawfile->isseekend = -1;\n\n char filename[LINKLIST_MAX_FILENAME_SIZE*2];\n snprintf(filename, LINKLIST_MAX_FILENAME_SIZE*2, \"%s\" LINKLIST_FORMAT_EXT, ll_rawfile->basename);\n\n // get the number of frames per file (fpf)\n int fpf = read_linklist_formatfile_comment(filename, LINKLIST_FRAMES_PER_FILE_IND, \"%d\");\n if (fpf > 0) ll_rawfile->fpf = fpf;\n else ll_rawfile->fpf = ll_rawfile_default_fpf;\n\n int blk_size = read_linklist_formatfile_comment(filename, LINKLIST_FILE_SIZE_IND, \"%d\");\n if (blk_size > 0) {\n ll_rawfile->framesize = blk_size;\n } else {\n if (!ll_rawfile->ll) {\n linklist_err(\"Null linklist\");\n free(ll_rawfile);\n return NULL;\n }\n ll_rawfile->framesize = ll->blk_size;\n if (ll->flags & LL_INCLUDE_ALLFRAME) ll_rawfile->framesize += ll->superframe->allframe_size;\n }\n\n if (flags & LL_RAWFILE_DUMMY) {\n // close the file descriptor\n if (ll_rawfile->fp) {\n fclose(ll_rawfile->fp);\n ll_rawfile->fp = NULL ;\n }\n } else {\n // open and seek to the beginning of the linklist rawfile\n if (seekend_linklist_rawfile(ll_rawfile) < 0) {\n free(ll_rawfile);\n return NULL;\n }\n if ((fpf < 0) || (blk_size < 0)) { // assume this is a new file, so write out the format files\n // write the superframe and linklist format files\n write_linklist_format(ll_rawfile->ll, filename);\n snprintf(filename, LINKLIST_MAX_FILENAME_SIZE*2, \"%s\" SUPERFRAME_FORMAT_EXT, ll_rawfile->basename);\n write_superframe_format(ll->superframe, filename);\n }\n }\n\n return ll_rawfile;\n}\n\nvoid close_and_free_linklist_rawfile(linklist_rawfile_t * ll_rawfile) {\n if (!ll_rawfile) return;\n if (ll_rawfile->fp) fclose(ll_rawfile->fp);\n free(ll_rawfile); \n}\n\nint tell_linklist_rawfile(linklist_rawfile_t * ll_rawfile) {\n if (!ll_rawfile) { \n linklist_err(\"Null rawfile linklist\");\n return -1;\n }\n return ll_rawfile->fileindex*ll_rawfile->fpf+ll_rawfile->framenum;\n}\n\nint flush_linklist_rawfile(linklist_rawfile_t * ll_rawfile) {\n if (!ll_rawfile) { \n linklist_err(\"Null rawfile linklist\");\n return -1;\n }\n\n unsigned int retval = 0;\n if (ll_rawfile->fp) {\n retval = fflush(ll_rawfile->fp);\n }\n\n return retval;\n}\n\nint read_linklist_rawfile(linklist_rawfile_t * ll_rawfile, uint8_t * buffer) {\n if (!ll_rawfile) { \n linklist_err(\"Null rawfile linklist\");\n return -1;\n }\n if (!buffer) { \n linklist_err(\"Null buffer\");\n return -1;\n }\n\n unsigned int retval = 0;\n unsigned int framenum = tell_linklist_rawfile(ll_rawfile);\n if (ll_rawfile->fp) {\n seek_linklist_rawfile(ll_rawfile, framenum); \n retval = fread(buffer, ll_rawfile->framesize, 1, ll_rawfile->fp);\n }\n ll_rawfile->framenum++;\n return retval;\n}\n\nint write_linklist_rawfile_with_allframe(linklist_rawfile_t * ll_rawfile, uint8_t * buffer, uint8_t * allframe) {\n if (!ll_rawfile) { \n linklist_err(\"Null rawfile linklist\");\n return -1;\n }\n if (!buffer) { \n linklist_err(\"Null buffer\");\n return -1;\n }\n\n unsigned int retval = 0;\n unsigned int framenum = tell_linklist_rawfile(ll_rawfile);\n if (ll_rawfile->fp) {\n seek_linklist_rawfile(ll_rawfile, framenum); \n retval = fwrite(buffer, ll_rawfile->ll->blk_size, 1, ll_rawfile->fp);\n if (allframe && (ll_rawfile->ll->flags & LL_INCLUDE_ALLFRAME)) {\n retval += fwrite(allframe, ll_rawfile->ll->superframe->allframe_size, 1, ll_rawfile->fp);\n }\n }\n ll_rawfile->framenum++;\n\n return retval;\n}\n\nint write_linklist_rawfile(linklist_rawfile_t * ll_rawfile, uint8_t * buffer) {\n return write_linklist_rawfile_opt(ll_rawfile, buffer, 0);\n}\n\nint write_linklist_rawfile_opt(linklist_rawfile_t * ll_rawfile, uint8_t * buffer, unsigned int flags) {\n\n (void) flags; // unused for now\n\n if (!ll_rawfile) { \n linklist_err(\"Null rawfile linklist\");\n return -1;\n }\n if (!buffer) { \n linklist_err(\"Null buffer\");\n return -1;\n }\n\n unsigned int retval = 0;\n unsigned int framenum = tell_linklist_rawfile(ll_rawfile);\n if (ll_rawfile->fp) {\n seek_linklist_rawfile(ll_rawfile, framenum); \n retval = fwrite(buffer, ll_rawfile->framesize, 1, ll_rawfile->fp);\n }\n ll_rawfile->framenum++;\n\n return retval;\n}\n\n#define N_BLOCK_DIRFILE_ENTRIES 6\n\nlinklist_dirfile_t * open_linklist_dirfile(char * dirname, linklist_t * ll) {\n return open_linklist_dirfile_opt(dirname, ll, 0);\n}\n\nlinklist_dirfile_t * open_linklist_dirfile_opt(char * dirname, linklist_t * ll, unsigned int flags) {\n if (!ll) {\n linklist_err(\"Null linklist\");\n return NULL;\n }\n if (!dirname || (strlen(dirname) == 0)) {\n linklist_err(\"Invalid dirfile name\");\n return NULL;\n }\n\n // create linklist dirfile\n linklist_dirfile_t * ll_dirfile = calloc(1, sizeof(linklist_dirfile_t));\n if (dirname[strlen(dirname)-1] == '/') dirname[strlen(dirname)-1] = '\\0';\n strcpy(ll_dirfile->filename, dirname);\n ll_dirfile->ll = ll;\n ll_dirfile->framenum = 0;\n\n // create a map for superframe entries\n ll_dirfile->map = calloc(ll->superframe->n_entries, sizeof(uint8_t));\n\n // make the dir for the dirfile\n if (mkdir(ll_dirfile->filename, 00755) < 0) {\n if (errno == EEXIST) {\n linklist_info(\"%s dirfile exists. Appending data...\\n\", ll_dirfile->filename);\n } else {\n linklist_err(\"Could not create dirfile %s (errno %d: %s)\\n\", ll_dirfile->filename, errno, strerror(errno));\n }\n } else {\n linklist_info(\"New dirfile %s.\\n\", ll_dirfile->filename);\n }\n\n // open formatfile\n char formatname[LINKLIST_MAX_FILENAME_SIZE+8] = {0};\n snprintf(formatname, LINKLIST_MAX_FILENAME_SIZE+8, \"%s/format\", ll_dirfile->filename);\n FILE * formatfile = fopen(formatname, \"w\");\n fprintf(formatfile,\"# Linklist Dirfile Format File\\n\");\n fprintf(formatfile,\"# Auto-generated by linklist_writer\\n\\n\");\n\n fprintf(formatfile, \"/VERSION 10\\n\");\n if (ll->superframe->flags & SF_USE_BIG_ENDIAN) {\n fprintf(formatfile, \"/ENDIAN big\\n\");\n } else {\n fprintf(formatfile, \"/ENDIAN little\\n\");\n }\n fprintf(formatfile, \"/PROTECT none\\n\");\n fprintf(formatfile, \"/ENCODING none\\n\");\n\n // write the filename to the dirfile\n fprintf(formatfile, \"ll_filename STRING %s\\n\", ll_dirfile->filename);\n\n // generate binary files\n int i, j;\n char binname[LINKLIST_MAX_FILENAME_SIZE*2] = {0};\n linkentry_t * tlm_le = NULL; \n int tlm_index = 0;\n superframe_entry_t * sfe = ll->superframe->entries;\n\n // map out all the linklist entries within the superframe\n for (i = 0; i < (int) ll->n_entries; i++) {\n tlm_le = &(ll->items[i]);\n if ((tlm_le->tlm) && \n (tlm_le->tlm != &block_entry) &&\n (tlm_le->tlm != &stream_entry)) {\n if ((tlm_index = superframe_entry_get_index(tlm_le->tlm, sfe)) == -1) {\n linklist_err(\"Could not get superframe index for \\\"%s\\\"\\n\", tlm_le->tlm->field);\n continue;\n }\n ll_dirfile->map[tlm_index] = 1; \n }\n }\n \n // append linklist flags\n ll->flags |= flags;\n\n // add all of the items from the superframe\n // those in the linklist are at the full rate\n // those not in the linklist are at 1 spf\n ll_dirfile->bin = (FILE **) calloc(ll->superframe->n_entries, sizeof(FILE *));\n for (i = 0; i < (int) ll->superframe->n_entries; i++) {\n // ignore extended items (blocks, streams, etc) for normal TOD \n if (sfe[i].type >= SF_NUM) continue; \n\n // add entry to format file\n fprintf(formatfile,\"%s RAW %s %d\\n\", sfe[i].field, \n get_sf_type_string(sfe[i].type), \n (ll_dirfile->map[i]) ? sfe[i].spf : 1);\n\n // add quantity\n if (strlen(sfe[i].quantity) > 0) {\n fprintf(formatfile,\"%s/quantity STRING \\\"\", sfe[i].field);\n for (j = 0; j < (int) strlen(sfe[i].quantity); j++) {\n if (sfe[i].quantity[j] == 92) fprintf(formatfile, \"\\\\\"); // fix getdata escape\n fprintf(formatfile, \"%c\", sfe[i].quantity[j]);\n }\n fprintf(formatfile,\"\\\"\\n\");\n }\n\n // add units\n if (strlen(sfe[i].units) > 0) {\n fprintf(formatfile,\"%s/units STRING \\\"\", sfe[i].field);\n for (j = 0; j < (int) strlen(sfe[i].units); j++) {\n if (sfe[i].units[j] == 92) fprintf(formatfile, \"\\\\\"); // fix getdata escape\n fprintf(formatfile, \"%c\", sfe[i].units[j]);\n }\n fprintf(formatfile,\"\\\"\\n\");\n }\n\n fflush(formatfile);\n\n // open the file if not already opened\n snprintf(binname, LINKLIST_MAX_FILENAME_SIZE*2, \"%s/%s\", ll_dirfile->filename, sfe[i].field);\n ll_dirfile->bin[i] = fpreopenb(binname); \n }\n\n // add files for blocks\n ll_dirfile->blockbin = (FILE **) calloc(ll->num_blocks*N_BLOCK_DIRFILE_ENTRIES, sizeof(FILE *));\n for (i = 0; i < (int) ll->num_blocks; i++) {\n #define WRITE_BLOCK_FORMAT_ENTRY(_FIELD) \\\n ({ \\\n fprintf(formatfile, \"%s_\" #_FIELD \" RAW %s %d\\n\", ll->blocks[i].name, \\\n get_sf_type_string(SF_UINT32), \\\n 1); \\\n fflush(formatfile); \\\n snprintf(binname, LINKLIST_MAX_FILENAME_SIZE*2, \"%s/%s_\" #_FIELD, ll_dirfile->filename, \\\n ll->blocks[i].name); \\\n ll_dirfile->blockbin[i*N_BLOCK_DIRFILE_ENTRIES+j] = fpreopenb(binname); \\\n j++; \\\n })\n j = 0;\n WRITE_BLOCK_FORMAT_ENTRY(id);\n WRITE_BLOCK_FORMAT_ENTRY(i);\n WRITE_BLOCK_FORMAT_ENTRY(n);\n WRITE_BLOCK_FORMAT_ENTRY(num);\n WRITE_BLOCK_FORMAT_ENTRY(alloc_size);\n WRITE_BLOCK_FORMAT_ENTRY(curr_size);\n }\n\n // add files for streams\n ll_dirfile->streambin = (FILE **) calloc(ll->num_streams, sizeof(FILE *));\n for (i = 0; i < (int) ll->num_streams; i++) {\n fprintf(formatfile, \"%s RAW %s %d\\n\", ll->streams[i].name,\n get_sf_type_string(SF_UINT8),\n ll->streams[i].le->blk_size);\n // open the file if not already opened\n snprintf(binname, LINKLIST_MAX_FILENAME_SIZE*2, \"%s/%s\", ll_dirfile->filename, ll->streams[i].name);\n ll_dirfile->streambin[i] = fpreopenb(binname); \n }\n\n // add files for extra linklist_writer-specific fields\n ll_dirfile->extrabin = (FILE **) calloc(LL_DIRFILE_NUM_EXTRA, sizeof(FILE *));\n #define WRITE_EXTRA_FORMAT_ENTRY(_FIELD, _TYPE) \\\n ({ \\\n fprintf(formatfile, \"ll_\" #_FIELD \" RAW %s %d\\n\", get_sf_type_string(_TYPE), 1); \\\n fflush(formatfile); \\\n snprintf(binname, LINKLIST_MAX_FILENAME_SIZE*2, \"%s/ll_\" #_FIELD, ll_dirfile->filename); \\\n ll_dirfile->extrabin[j] = fpreopenb(binname); \\\n j++; \\\n })\n j = 0;\n // can only do 4 byte data\n WRITE_EXTRA_FORMAT_ENTRY(framenum, SF_UINT32);\n WRITE_EXTRA_FORMAT_ENTRY(data_integrity, SF_FLOAT32);\n WRITE_EXTRA_FORMAT_ENTRY(local_time, SF_UINT32);\n\n // open the frame counting binary file\n snprintf(binname, LINKLIST_MAX_FILENAME_SIZE*2, \"%s/%s\", ll_dirfile->filename, LL_FRAMEBIN_NAME);\n ll_dirfile->framebin = fpreopenb(binname);\n\n // tack on calspecs file\n if (ll->superframe->calspecs[0]) {\n fprintf(formatfile, \"\\n####### Begin calspecs ######\\n\\n\");\n FILE * calspecsfile = fopen(ll->superframe->calspecs, \"rb\");\n if (!calspecsfile) {\n linklist_err(\"Could not open calspecs file \\\"%s\\\"\\n\", ll->superframe->calspecs);\n } else {\n int a;\n while (1) {\n a = fgetc(calspecsfile); \n if (!feof(calspecsfile)) fputc(a, formatfile);\n else break;\n }\n fclose(calspecsfile);\n fflush(formatfile);\n }\n }\n\n\n ll_dirfile->format = formatfile;\n ll_dirfile->tally_word = 0;\n return ll_dirfile;\n}\n\nvoid parse_calspecs(char * filename, FILE * formatfile) {\n (void) filename;\n (void) formatfile;\n}\n\nvoid close_and_free_linklist_dirfile(linklist_dirfile_t * ll_dirfile) {\n int i;\n for (i = 0; i < (int) ll_dirfile->ll->superframe->n_entries; i++) {\n if (ll_dirfile->bin[i]) fclose(ll_dirfile->bin[i]);\n }\n for (i = 0; i < (int) ll_dirfile->ll->num_blocks*N_BLOCK_DIRFILE_ENTRIES; i++) {\n if (ll_dirfile->blockbin[i]) fclose(ll_dirfile->blockbin[i]);\n }\n for (i = 0; i < (int) ll_dirfile->ll->num_streams; i++) {\n if (ll_dirfile->streambin[i]) fclose(ll_dirfile->streambin[i]);\n }\n for (i = 0; i < LL_DIRFILE_NUM_EXTRA; i++) {\n if (ll_dirfile->extrabin[i]) fclose(ll_dirfile->extrabin[i]);\n }\n if (ll_dirfile->framebin) fclose(ll_dirfile->framebin);\n if (ll_dirfile->format) fclose(ll_dirfile->format);\n if (ll_dirfile->missing_blks_start) free(ll_dirfile->missing_blks_start);\n if (ll_dirfile->missing_blks_end) free(ll_dirfile->missing_blks_end);\n ll_dirfile->n_missing_blks = 0;\n ll_dirfile->n_missing_blks_alloc = 0;\n\n free(ll_dirfile->bin);\n free(ll_dirfile->blockbin);\n free(ll_dirfile->streambin);\n free(ll_dirfile->extrabin);\n free(ll_dirfile->map);\n free(ll_dirfile);\n}\n\nint seek_linklist_dirfile(linklist_dirfile_t * ll_dirfile, unsigned int framenum) {\n int i = 0;\n unsigned int tlm_out_size = 0;\n unsigned int tlm_out_spf = 0;\n unsigned int dir_loc = 0;\n\n if (!ll_dirfile) { \n linklist_err(\"Null dirfile linklist\");\n return -1;\n }\n\n linklist_t * ll = ll_dirfile->ll;\n if (!ll) {\n linklist_err(\"Null linklist\");\n return -1;\n }\n superframe_entry_t * sfe = ll->superframe->entries;\n\n // just a normal field to be writing to the dirfile\n for (i = 0; i < (int) ll->superframe->n_entries; i++) {\n if (ll_dirfile->bin[i]) { \n tlm_out_size = get_superframe_entry_size(&sfe[i]);\n tlm_out_spf = (ll_dirfile->map[i]) ? sfe[i].spf : 1;\n\n dir_loc = framenum*tlm_out_size*tlm_out_spf;\n fseek(ll_dirfile->bin[i], dir_loc, SEEK_SET);\n }\n }\n // block-specific fields to be writing to the dirfile\n for (i=0; i<(int) (ll->num_blocks*N_BLOCK_DIRFILE_ENTRIES); i++) {\n if (ll_dirfile->blockbin[i]) {\n fseek(ll_dirfile->blockbin[i], framenum*sizeof(uint32_t), SEEK_SET);\n }\n } \n // stream-specific fields to be writing to the dirfile\n for (i=0; i<(int) ll->num_streams; i++) {\n if (ll_dirfile->streambin[i]) {\n fseek(ll_dirfile->streambin[i], framenum*ll->streams[i].le->blk_size, SEEK_SET);\n }\n }\n // ll_dirfile-specific field to be writing to the dirfile\n for (i=0; i<LL_DIRFILE_NUM_EXTRA; i++) {\n if (ll_dirfile->extrabin[i]) {\n fseek(ll_dirfile->extrabin[i], framenum*sizeof(uint32_t), SEEK_SET);\n }\n }\n // frame tally is 8 frames per byte\n if (ll_dirfile->framebin) {\n fseek(ll_dirfile->framebin, framenum / 8, SEEK_SET);\n }\n ll_dirfile->framenum = framenum;\n return 0;\n}\n\nint flush_linklist_dirfile(linklist_dirfile_t * ll_dirfile) {\n int i = 0;\n\n if (!ll_dirfile) { \n linklist_err(\"Null dirfile linklist\");\n return -1;\n }\n\n linklist_t * ll = ll_dirfile->ll;\n if (!ll) {\n linklist_err(\"Null linklist\");\n return -1;\n }\n\n // just a normal field to be writting to the dirfile\n for (i = 0; i < (int) ll->superframe->n_entries; i++) {\n if (ll_dirfile->bin[i]) { \n fflush(ll_dirfile->bin[i]);\n }\n } \n // block-specific fields to be writing to the dirfile\n for (i=0; i<(int) (ll->num_blocks*N_BLOCK_DIRFILE_ENTRIES); i++) {\n if (ll_dirfile->blockbin[i]) {\n fflush(ll_dirfile->blockbin[i]);\n }\n }\n // stream-specific fields to be writing to the dirfile\n for (i=0; i<(int) ll->num_streams; i++) {\n if (ll_dirfile->streambin[i]) {\n fflush(ll_dirfile->streambin[i]);\n }\n }\n // ll_dirfile-specific fields to be writing to the dirfile\n for (i=0; i<(int) LL_DIRFILE_NUM_EXTRA; i++) {\n if (ll_dirfile->extrabin[i]) {\n fflush(ll_dirfile->extrabin[i]);\n }\n }\n // frame tally\n if (ll_dirfile->framebin) {\n fflush(ll_dirfile->framebin);\n }\n\n return 0;\n}\n\n// writes a linklist buffer to a file\ndouble write_linklist_dirfile(linklist_dirfile_t * ll_dirfile, uint8_t * buffer) {\n return write_linklist_dirfile_opt(ll_dirfile, buffer, 0);\n}\n\ndouble write_linklist_dirfile_opt(linklist_dirfile_t * ll_dirfile, uint8_t * buffer, unsigned int flags) {\n\n if (!ll_dirfile) { \n linklist_err(\"Null dirfile linklist\");\n return -1;\n }\n if (!buffer) { \n linklist_err(\"Null buffer\");\n return -1;\n }\n linklist_t * ll = ll_dirfile->ll;\n if (!ll) {\n linklist_err(\"Null linklist\");\n return -1;\n }\n\n static uint8_t * superframe_buf = NULL;\n static int first_time = 1; \n if (first_time) {\n superframe_buf = allocate_superframe(ll->superframe);\n first_time = 0;\n }\n\n // unpack the linklist\n if (ll->flags & LL_INCLUDE_ALLFRAME) {\n read_allframe(superframe_buf, ll->superframe, buffer+ll->blk_size);\n }\n double retval = decompress_linklist_opt(superframe_buf, ll, buffer, UINT32_MAX, ll->flags | flags);\n\n // write the data to the dirfile\n superframe_entry_t * sfe = ll->superframe->entries;\n // unsigned int dir_loc = 0;\n unsigned int tlm_out_start = 0;\n unsigned int tlm_out_size = 0;\n unsigned int tlm_out_skip = 0;\n unsigned int tlm_out_spf = 0;\n\n int i = 0;\n int j = 0;\n // just a normal field to be writing to the dirfile\n for (i = 0; i < (int) ll->superframe->n_entries; i++) {\n if (ll_dirfile->bin[i]) { \n tlm_out_start = sfe[i].start;\n tlm_out_skip = sfe[i].skip;\n tlm_out_size = get_superframe_entry_size(&sfe[i]);\n\n // entries in the linklist get the full rate\n // entries not in the linklist get 1 spf\n tlm_out_spf = (ll_dirfile->map[i]) ? sfe[i].spf : 1;\n\n // dir_loc = ll_dirfile->framenum*tlm_out_size*tlm_out_spf;\n\n for (j = 0; j < (int) tlm_out_spf; j++) {\n fwrite(superframe_buf+tlm_out_start, tlm_out_size, 1, ll_dirfile->bin[i]);\n tlm_out_start += tlm_out_skip;\n }\n }\n } \n // block-specific fields to be writing to the dirfile\n for (i = 0; i < (int) ll->num_blocks; i++) {\n #define WRITE_BLOCK_ENTRY_DATA(_FIELD) \\\n ({ \\\n FILE * blockfp = ll_dirfile->blockbin[i*N_BLOCK_DIRFILE_ENTRIES+j]; \\\n if (blockfp) fwrite(&ll->blocks[i]._FIELD, sizeof(uint32_t), 1, blockfp); \\\n j++; \\\n })\n j = 0;\n WRITE_BLOCK_ENTRY_DATA(id);\n WRITE_BLOCK_ENTRY_DATA(i);\n WRITE_BLOCK_ENTRY_DATA(n);\n WRITE_BLOCK_ENTRY_DATA(num);\n WRITE_BLOCK_ENTRY_DATA(alloc_size);\n WRITE_BLOCK_ENTRY_DATA(curr_size);\n }\n // stream-specific fields to be writing to the dirfile\n for (i = 0; i < (int) ll->num_streams; i++) {\n // always look to the next buffer, never repeat (unlike packetize_stream)\n ll->streams[i].curr = ll->streams[i].next; // only a reading function can modify stream->curr\n substream_t * ss = &ll->streams[i].buffers[ll->streams[i].curr];\n fwrite(ss->buffer, ll->streams[i].le->blk_size, 1, ll_dirfile->streambin[i]); \n memset(ss->buffer, 0, ll->streams[i].le->blk_size);\n }\n // Report fields for decompressed data\n ll_dirfile->local_time = time(0);\n ll_dirfile->data_integrity = retval;\n\n // ll_dirfile-specific fields to be writing to the dirfile\n #define WRITE_EXTRA_ENTRY_DATA(_FIELD, _TYPE) \\\n ({ \\\n FILE * extrafp = ll_dirfile->extrabin[j]; \\\n if (extrafp) fwrite(&ll_dirfile->_FIELD, sizeof(_TYPE), 1, extrafp); \\\n j++; \\\n })\n j = 0;\n WRITE_EXTRA_ENTRY_DATA(framenum, uint32_t);\n WRITE_EXTRA_ENTRY_DATA(data_integrity, float);\n WRITE_EXTRA_ENTRY_DATA(local_time, uint32_t);\n\n // tally up the frames\n if (ll_dirfile->framebin) {\n // read current word, bitwise append, seek, and write\n unsigned int bit_loc = ll_dirfile->framenum % 8;\n ll_dirfile->tally_word |= 1 << bit_loc;\n\n // write the word every byte boundary\n if (bit_loc == 7) {\n fwrite(&ll_dirfile->tally_word, 1, 1, ll_dirfile->framebin);\n ll_dirfile->tally_word = 0;\n }\n }\n\n // nothing needs to be done for calspecs since it is handled by getdata :)\n\n // clear the buffer\n memset(superframe_buf, 0, ll->superframe->size);\n ll_dirfile->framenum++;\n \n return retval;\n}\n\nvoid realloc_missing_blks_linklist_dirfile(linklist_dirfile_t * ll_dirfile, unsigned int n) {\n if (ll_dirfile->n_missing_blks_alloc) {\n ll_dirfile->missing_blks_start = realloc(ll_dirfile->missing_blks_start, n*sizeof(unsigned int));\n ll_dirfile->missing_blks_end = realloc(ll_dirfile->missing_blks_end, n*sizeof(unsigned int));\n } else {\n ll_dirfile->missing_blks_start = calloc(n, sizeof(unsigned int));\n ll_dirfile->missing_blks_end = calloc(n, sizeof(unsigned int));\n }\n ll_dirfile->n_missing_blks_alloc = n;\n}\n\nvoid map_frames_linklist_dirfile(linklist_dirfile_t * ll_dirfile) {\n if (!ll_dirfile->framebin) {\n linklist_err(\"Linklist frame tally file %s/%s is not open.\\n\", ll_dirfile->filename, LL_FRAMEBIN_NAME);\n return;\n }\n\n uint8_t buffer[LL_FRAMEBIN_READ_BLOCK_SIZE] = {0};\n unsigned int bytes_read = 0;\n unsigned int total_bytes = (ll_dirfile->framenum) ? (ll_dirfile->framenum-1) / 8 + 1 : 0;\n int64_t bytes_to_read = 0;\n\n fseek(ll_dirfile->framebin, total_bytes, SEEK_SET);\n fwrite(&bytes_read, 1, 1, ll_dirfile->framebin);\n fflush(ll_dirfile->framebin);\n fseek(ll_dirfile->framebin, 0, SEEK_SET);\n\n unsigned int framenum;\n uint8_t have_data_block = 1;\n int i = 0, n = 0;\n printf(\"\\nMissing data blocks: \");\n while (bytes_read < total_bytes) {\n bytes_to_read = MIN(LL_FRAMEBIN_READ_BLOCK_SIZE, total_bytes-bytes_read);\n bytes_to_read = fread(buffer, 1, bytes_to_read, ll_dirfile->framebin);\n for (i = 0; i < bytes_to_read; i++) {\n framenum = (bytes_read + i)*8;\n if ((buffer[i] != 0xff) && have_data_block) { // bit is not set, so missing frame\n // had a block, but lost it, so new start\n if (n >= ll_dirfile->n_missing_blks_alloc) {\n realloc_missing_blks_linklist_dirfile(ll_dirfile, n+10);\n }\n ll_dirfile->missing_blks_start[n] = framenum;\n if (n != 0) printf(\" \");\n printf(\"[%d,\", ll_dirfile->missing_blks_start[n]);\n have_data_block = 0;\n } else if ((buffer[i] == 0xff) && !have_data_block) { // bit is set, so have a frame there\n // didn't have a block, but just found one\n ll_dirfile->missing_blks_end[n] = framenum;\n printf(\"%d]\", ll_dirfile->missing_blks_end[n]);\n have_data_block = 1;\n n++;\n }\n }\n bytes_read += bytes_to_read;\n }\n if (!have_data_block) {\n ll_dirfile->missing_blks_end[n] = framenum;\n printf(\"%d]\", ll_dirfile->missing_blks_end[n]);\n have_data_block = 1;\n n++;\n }\n ll_dirfile->n_missing_blks = n;\n printf(\"\\n\\n\");\n}\n\n#ifdef __cplusplus\n\n}\n\n#endif\n" }, { "alpha_fraction": 0.6861284971237183, "alphanum_fraction": 0.6867163181304932, "avg_line_length": 51.081634521484375, "blob_id": "3e182c5d013414d7a142264cac6c8cc4df85bb5c", "content_id": "4d2c6bdafb16592be0f5224b5df70b63d734af2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 5104, "license_type": "no_license", "max_line_length": 79, "num_lines": 98, "path": "/owl/README.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "Owl is a tool which can be used to display data from GetData in real-time.\nIt includes a drag-and-drop interface and a web front-end to share a\ncurrent Owl session.\n\nCOMPILING AND INSTALING\n============================================================================\nShort answer: run \"qmake-qt4 && make\". Then run \"./owl\" or copy to your\ndirectory of choice.\n\nYou can change where owl will install to by editing owl.pro.\n\nIf you want web server support (more below) you must also cd into \"owl-cgi\",\nedit owl-cgi.pro and run \"qmake-qt4 && make\" and copy it into your cgi-bin\ndirectory.\n\nSETTING UP OWL\n============================================================================\nAn owl setup is composed of a number of boxes, each which contain a number\nof data items.\n\nDuring your setup you may find it useful to move of hide the dockers. You\ncan move them by clicking and dragging or hide them by clicking on the\nrespective toolbar option.\n\nFirst in the configure box, select \"Owl\" from the combobox and enter in the\nGetData DirFile path you want to use.\n\nTo create a new box drag \"Box\" from the \"Insert\" docker to where you want it.\nYou can then drag its corners to resize it or drag the title to move it\naround. If you want to modify its settings later, click its title, or choose\nit from the configure combobox\n\nYou can remove the box, change its title and style in the \"Configure\" docker.\nMore about styles below.\n\nYou can then drag data items (Numbers, Multis, Date/Times, Dirfile names)\ninto the boxes. In the \"Configure\" docker for any type of data item you can\nremove it, change it's caption, caption style, data style (i.e., the style of\nthe data field) and in everything but the \"Dirfile Name\" type, source.\n - Numbers display a GetData source as a number. You can specify the exact\n format for the number by entering a printf string under format. As an\n extra feature, you can set the format to \"%b\" to see it as a binary field.\n It is undefined to request a type with more bytes than the source\n supports. For example, do not request a double for a float type. Numbers\n support extremas. See more below.\n - Multis implement a mapping between specific values and strings. Once a multi\n is created, in the \"format\" section of the \"Configure\" docker click\n \"New Row\". In the created row, type in the number you want to map on the\n left and the string that number represents of the right. For example,\n you may wish to map '0' (without quotes) to \"Default\" (without quotes).\n You can specify styles for a certain mapping by selecting the desired row\n and choosing a style. More on styles below.\n - Dates and times display a GetData ctime source as a date and/or time.\n You must specify a strftime string in format.\n - A \"Dirfile name\" simply displays the name of the current dirfile.\n\nIf you want to modify a data item later, just click on it.\n\nSTYLES\n============================================================================\n[No Style] [f] [b] [B] [i]\n Style name Foreground clr Background clr Bold Italic\n\nTo set the font, foreground colour or background colour of an object, select\na style the style combobox, or choose \"New Style\" to create a new one. When\nyou change a certain style, all objects with that style will also change.\n\nEXTREMAS\n============================================================================\nExtremas provide special formatting for number values that exceed or fall\nshort of a certain value. To set an extrema for a certain object, select\nthat object, and in the \"Extrema\" section of the \"Configure\" docker select\nan extrema or choose \"New Extrema\" to create a new one. When you change\nthe parameters of an extrema, all objects with that extrema will also\nchange. Below is an explanation of the parameters:\n\n - XHigh: values above this amount will be displayed with the below style.\n - High: values between this an XHigh will be displayed with the below\n style. If this value is equal to or above XHigh, it will be\n ignored.\n - XLow: values below this amount will be displayed with the below style.\n - Low: values between this and XLow will be displayed with the below\n style. If this value is equal to or below Low, it will be ignored.\n\nWEB SERVER\n============================================================================\nFor information on setting up the web-server click on the question mark in\nthe \"Web Server\" docker. A web-server can be used to share default values\nwith Cow, or to share a current session with anyone with a web browser.\n\nIMPORTING AN EXISTING PALANTIR SETUP\n============================================================================\nTo migrate from an existing palantir setup, you can click \"Open\" from the\ntoolbar and select a .pal file. The importer is designed to eliminate a lot\nof typing, but does not import all data. Owl will place all palantir boxes\nin the top left corner. Before modifying anything, save your session as an\nowl file and reopen it. Then, you should check to make sure all styles and\ndata have been correctly imported.\n" }, { "alpha_fraction": 0.5870429873466492, "alphanum_fraction": 0.6080697178840637, "avg_line_length": 22.358407974243164, "blob_id": "d189ab13e6d3e8e9f63c6e04a3f375b8f4e7ee86", "content_id": "10c5d75171c33135f140be0563df7480e8db19cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5279, "license_type": "no_license", "max_line_length": 106, "num_lines": 226, "path": "/blastd/rnc.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* This software is copyright (C) 2004 University of Toronto\n * and futher copyright 2009-2010 Matthew Truch\n * \n * This file is part of the BLASTpol software, and is heavily borrowed from BLAST\n * and interloquendi.\n * \n * You should have received a copy of the GNU General Public License\n * along with interloquendi; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#define _POSIX_C_SOURCE 199309L\n\n#include <stdlib.h>\n#include <stdio.h>\n\n#include <errno.h>\n#include <netdb.h>\nextern int h_errno;\n#include <signal.h>\n#include <string.h>\n#include <unistd.h>\n#include <sys/socket.h>\n#include <sys/syslog.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <time.h>\n\n#define RNC_SOCK_PORT 41114\n#define DNC_SOCK_PORT 14441\n#define TEA_SOCK_PORT 14141\n#define LNC_SOCK_PORT 11111\n\n#define RNC_LNKFILE \"/data/etc/highgain.lnk\"\n#define DNC_LNKFILE \"/data/etc/tdomni.lnk\"\n#define TEA_LNKFILE \"/data/etc/iromni.lnk\"\n#define LNC_LNKFILE \"/data/etc/irslow.lnk\"\n\n#define LEN 500\n#define BUF_LEN 5000\n#define PAST_SEND 100\n#define SLEEP_PERIOD 100000000\n#define NO_DATA_LIMIT 2000\n\nchar LNKFILE[4096];\nint SOCK_PORT;\n\nenum PartyType{RNC=0, DNC, TEA, LNC};\n\nenum PartyType party = RNC;\n\nvoid Connection(int csock)\n{\n struct sockaddr_in addr;\n socklen_t addrlen = sizeof(addr);\n struct hostent* thishost;\n char data_file[LEN];\n int fd;\n char data[BUF_LEN];\n off_t offset;\n size_t n_read;\n struct timespec ts;\n int no_data = 0;\n\n ts.tv_sec = 0;\n ts.tv_nsec = SLEEP_PERIOD;\n\n getsockname(csock, (struct sockaddr*)&addr, &addrlen);\n thishost = gethostbyaddr((const char*)&addr.sin_addr, sizeof(addr.sin_addr),\n AF_INET);\n if (thishost == NULL && h_errno) {\n fprintf(stderr, \"Warning: gethostbyaddr\\n\");\n thishost = NULL;\n }\n\n fd = open(LNKFILE, O_RDONLY);\n if (fd == -1) {\n fprintf(stderr, \"Couldn't open %s!\\n\", LNKFILE);\n shutdown(csock, SHUT_RDWR);\n close(csock);\n return;\n }\n\n offset = lseek(fd, 0, SEEK_END);\n if (offset > PAST_SEND)\n offset = PAST_SEND;\n lseek(fd, -offset, SEEK_END);\n fprintf(stderr, \" %s: Rewind %ld bytes\\n\", inet_ntoa(addr.sin_addr), (long)offset);\n\n /* Service Loop */\n for (;;) {\n n_read = read(fd, data, BUF_LEN);\n\n if (n_read == 0) {\n if (no_data > NO_DATA_LIMIT) {\n fprintf(stderr, \" %s: No data in %s for too long\\n\", inet_ntoa(addr.sin_addr), data_file);\n no_data = 0;\n shutdown(csock, SHUT_RDWR);\n close(csock);\n return;\n }\n no_data++;\n nanosleep(&ts, NULL);\n continue;\n }\n\n if (n_read == -1){\n fprintf(stderr, \" %s: Error reading from %s\\n\", inet_ntoa(addr.sin_addr), data_file);\n shutdown(csock, SHUT_RDWR);\n close(csock);\n return;\n }\n\n no_data = 0; /* We have data, so reset no_data counter */\n\n if (write(csock, data, n_read) != n_read) {\n fprintf(stderr, \" %s: Error writing to socket with %zd data.\\n\", inet_ntoa(addr.sin_addr), n_read);\n shutdown(csock, SHUT_RDWR);\n close(csock);\n return;\n }\n }\n}\n\nint MakeSock(void)\n{\n int sock, n;\n struct sockaddr_in addr;\n\n if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)\n {\n fprintf(stderr, \"Fatal: Socket\\n\");\n exit(-2);\n }\n\n n = 1;\n if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) != 0)\n {\n fprintf(stderr, \"Fatal: setsockopt\\n\");\n exit(-2);\n }\n\n addr.sin_family = AF_INET;\n addr.sin_port = htons(SOCK_PORT);\n addr.sin_addr.s_addr = INADDR_ANY;\n\n if (bind(sock, (struct sockaddr*)&addr, (socklen_t)sizeof(addr)) == -1)\n {\n fprintf(stderr, \"fatal: bind\\n\");\n exit(-2);\n }\n\n if (listen(sock, 10) == -1)\n {\n fprintf(stderr, \"fatal: listen\\n\");\n exit(-2);\n }\n\n fprintf(stderr, \"listening on port %i.\\n\", SOCK_PORT);\n\n return sock;\n}\n\nint main(int argc, char *argv[])\n{\n int pid;\n char *name;\n socklen_t sock, addrlen, csock;\n struct sockaddr_in addr;\n\n name = argv[0] + strlen(argv[0])-3;\n printf(\"program: %s\\n\", name);\n if (strcmp(name, \"rnc\")==0) {\n party = RNC;\n strcpy(LNKFILE, RNC_LNKFILE);\n SOCK_PORT = RNC_SOCK_PORT;\n } else if (strcmp(name, \"dnc\")==0) {\n party = DNC;\n strcpy(LNKFILE, DNC_LNKFILE);\n SOCK_PORT = DNC_SOCK_PORT;\n } else if (strcmp(name, \"tea\")==0) {\n party = TEA;\n strcpy(LNKFILE, TEA_LNKFILE);\n SOCK_PORT = TEA_SOCK_PORT;\n } else if (strcmp(name, \"lnc\")==0) {\n party = LNC;\n strcpy(LNKFILE, LNC_LNKFILE);\n SOCK_PORT = LNC_SOCK_PORT;\n } else {\n fprintf(stderr, \"unknown program: %s\\n\", name);\n exit(0);\n }\n \n /* Autoreap children */\n signal(SIGCHLD, SIG_IGN);\n\n /* initialise listener socket */\n sock = MakeSock();\n\n /* accept loop */\n for (;;) {\n addrlen = sizeof(addr);\n csock = accept(sock, (struct sockaddr*)&addr, &addrlen);\n\n if (csock == -1 && errno == EINTR)\n continue;\n else if (csock == -1)\n fprintf(stderr, \"Error: accept\\n\");\n else {\n /* fork child */\n if ((pid = fork()) == 0) {\n close(sock);\n Connection(csock);\n exit(0);\n }\n\n fprintf(stderr, \"Spawned %i to handle connect from %s\\n\", pid,\n inet_ntoa(addr.sin_addr));\n close(csock);\n }\n }\n}\n" }, { "alpha_fraction": 0.6606789827346802, "alphanum_fraction": 0.6716364026069641, "avg_line_length": 30.275279998779297, "blob_id": "987b9bd6086a2ddc5316b14e794a4b52567f0461", "content_id": "3f179baaebfcd0054cc0fbf38b21c3e371cb19b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11135, "license_type": "no_license", "max_line_length": 133, "num_lines": 356, "path": "/stars/code/imaging/camera_windows.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"../preprocessor.h\"\n#if PREPROCESSOR_USING_CAMERA\n\n#include \"camera_windows.h\"\n\n#include \"../parameters/manager.h\"\n#include \"../shared/image/raw.h\"\n#include \"../shared/camera/results.h\"\n#include \"../shared/camera/requests.h\"\n#include \"../shared/general/quit.h\"\n#include \"logger_camera.h\"\n\nusing namespace Imaging;\nusing Cameraing::logger;\n\n#define shared_image (*(Shared::Image::raw_from_camera.w))\n#define shared_requests (*(Shared::Camera::requests_for_camera.r))\n#define shared_results (*(Shared::Camera::results_for_main.w))\n\nCameraWindows::CameraWindows(Parameters::Manager& params, dmm *card): AbstractCamera(params),\n gain_min(0.0), gain_max(-1.0),\n #pragma warning(push)\n #pragma warning(disable: 4355)\n thread(boost::bind(&CameraWindows::thread_function, this))\n #pragma warning(pop)\n{\n\tio_card = card;\n}\n\nbool CameraWindows::init_camera()\n{\n\tusing namespace Shared::Image;\n\tusing std::string;\n\tunsigned long listlen = 0;\n\t\n\tisCapturing = false;\n\n\tcamerror = QCam_LoadDriver();\n\tif (camerror != qerrSuccess) {\n\t\tlogger.log(format(\"error: could not initialize camera system: %d\") % camerror);\n\t\treturn false;\n\t}\n\n\twhile (!Shared::General::quit)\n\t{\n\t\tio_card->cycle_camera();\n\n\t\tSleep(3000);\n\t\tlogger.log(format(\"Inside init_camera driver...\"));\n\n\t\tunsigned long listlen = sizeof(camlist) / sizeof(camlist[0]);\n\t\tcamerror = QCam_ListCameras(camlist, &listlen);\n\t\tif (camerror != qerrSuccess) {\n\t\t\tlogger.log(format(\"error listing cameras: %d\") % camerror);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (listlen == 0) {\n\t\t\tlogger.log(format(\"error: No cameras found in system!\"));\n\t\t\tcontinue;\n\t\t}\n\n\t\tcamerror = QCam_OpenCamera(camlist[0].cameraId, &camhandle);\n\t\tif (camerror != qerrSuccess) {\n\t\t\tlogger.log(format(\"error opening camera: %d\") % camerror);\n\t\t\tcontinue;\n\t\t}\n\n\t\tlogger.log(format(\"camera head successfully opened\"));\n\t\t\n\t\tbreak;\t\t\n\t}\n\n\tif (Shared::General::quit) return false;\n\n\tQCam_CreateCameraSettingsStruct(&settings);\n\tQCam_InitializeCameraSettings(camhandle, &settings);\n\tQCam_ReadDefaultSettings(camhandle, (QCam_Settings*)&settings);\n\t\n\tQCam_SetParam((QCam_Settings*)&settings, qprmImageFormat, qfmtMono16);\n\n\t{\n\t\tunsigned long xpix, ypix, bpp;\n\t\tQCam_GetInfo(camhandle, qinfCcdWidth, &xpix);\n\t\tQCam_GetInfo(camhandle, qinfCcdHeight, &ypix);\n\t\tQCam_GetInfo(camhandle, qinfBitDepth, &bpp);\n\t\tlogger.log(format(\"Found CCD %lu x %lu @ %lu bits\") % xpix % ypix % bpp);\n\t\tFrameSize = QCam_CalcImageSize(qfmtMono16, xpix, ypix);\n\n\t\t// Allocate memory for the frame buffers \n\n\t\tframe.pBuffer = new byte[FrameSize];\n\t\tframeBuf1 = (byte*)frame.pBuffer;\n\t\tframe.bufferSize = FrameSize;\n\t\tframe.width = xpix;\n\t\tframe.height = ypix;\n\t}\n\n\tQCam_SetParam((QCam_Settings*)&settings, qprmCoolerActive, 1);\n\tQCam_SetParam((QCam_Settings*)&settings, qprmHighSensitivityMode, 1);\n\tQCam_SetParam((QCam_Settings*)&settings, qprmBlackoutMode, 1);\n\tQCam_SetParam((QCam_Settings*)&settings, qprmDoPostProcessing, 0);\n\tQCam_SetParam((QCam_Settings*)&settings, qprmTriggerDelay, 0);\n\n\t//Set the ROI to our display size\n\tQCam_SetParam((QCam_Settings*)&settings, qprmRoiX, 0);\n\tQCam_SetParam((QCam_Settings*)&settings, qprmRoiY, 0);\n\tQCam_SetParam((QCam_Settings*)&settings, qprmRoiWidth, frame.width);\n\tQCam_SetParam((QCam_Settings*)&settings, qprmRoiHeight, frame.height);\n\n\tcamerror = QCam_SendSettingsToCam(camhandle, (QCam_Settings*)&settings);\n\tif (camerror != qerrSuccess) {\n\t\tlogger.log(format(\"error sending camera settings: %d\") % camerror);\n\t}\n\tinit_gain();\n\n\tset_trigger_mode();\n\n\tQCam_SetStreaming(camhandle, 0);\n\tlogger.log(format(\"Setting streaming off handle %u\\n\") % camhandle);\n\treturn true;\n}\n\nvoid CameraWindows::clean_up_camera()\n{\n\tif (camera_ready) {\n\t\tlogger.log(format(\"Releasing streaming on handle %u\\n\") % camhandle);\n\t\tQCam_SetStreaming(camhandle, 0);\n\t\tlogger.log(\"Releasing settings\\n\");\n\t\tQCam_ReleaseCameraSettingsStruct(&settings);\n\t\tlogger.log(\"Closing Camera\\n\");\n\t\tQCam_CloseCamera(camhandle);\n\t\tlogger.log(\"Releasing driver\\n\");\n\t\tQCam_ReleaseDriver();\n\t}\n}\n\n\nvoid CameraWindows::get_trigger_mode()\n{\n int error = 0;\n\tunsigned long trigger_mode;\n\tcamerror = QCam_GetParam((QCam_Settings*)&settings, qprmTriggerType, &trigger_mode);\n if (camerror == qerrSuccess) {\n logger.log(format(\"got trigger mode %d\") % trigger_mode);\n if ((trigger_mode == qcTriggerFreerun) || (trigger_mode == qcTriggerSoftware)) {\n internal_triggering = true;\n }\n else {\n internal_triggering = false;\n }\n }\n}\n\nvoid CameraWindows::set_trigger_mode()\n{\n int error = 0;\n unsigned long trigger_mode;\n unsigned long mode6interval = 20000;\n int polarity = 0;\n\n if (internal_triggering) {\n trigger_mode = qcTriggerFreerun;\n\t\tQCam_SetParam((QCam_Settings*)&settings, qprmTriggerDelay, unsigned long(mode6interval));\n\t\tcamerror = QCam_SetParam64((QCam_Settings*)&settings, qprm64Exposure, unsigned long(internal_exposure_time*1000000000.0));\n\t\tlogger.log(format(\"set exposure time %fs (%d)\") % internal_exposure_time % camerror);\n } else {\n\t\ttrigger_mode = qcTriggerStrobeLow;\n\t\tQCam_SetParam((QCam_Settings*)&settings, qprmTriggerDelay, 0);\n }\n\n\t//camerror = QCam_SetParam((QCam_Settings*)&settings, qprmExposure, unsigned long(internal_exposure_time*1000000.0));\n\t\n\tcamerror = QCam_SetParam((QCam_Settings*)&settings, qprmTriggerType, trigger_mode);\n\n\tcamerror = QCam_SendSettingsToCam(camhandle, (QCam_Settings*)&settings);\n\t\n if (camerror == qerrSuccess) {\n logger.log(format(\"set trigger mode %d\") % trigger_mode);\n\t}\n\telse {\n\t\tlogger.log(format(\"Error %d setting trigger\") % camerror);\n\t}\n\t\n get_trigger_mode();\n}\n\nvoid CameraWindows::read_image_if_available()\n{\n\t\t\n\t\n\tlogger.log(\"Grabbing\\n\");\n\tisCapturing = true;\n\tcamerror = QCam_GrabFrame(camhandle, &frame);\n\tisCapturing = false;\n\tlogger.log(format(\"Done grabbing (%d) frame with timestamp %u\\n\") % camerror % frame.timeStamp);\n\t\n\tif (Shared::General::quit) return;\n\n\t\n\t\tboost::posix_time::ptime timestamp = boost::posix_time::microsec_clock::local_time();\n\t\tshared_image.age.start();\n\n\t\tnum_buffers_filled = 0;\n\t\tTools::Timer series_age_timer;\n\t\tseries_age_timer.start();\n\t\t\n\t\tlogger.log(format(\"image found with number %u\") % frame.frameNumber);\n\t\t\t\n\t\tintermediate_buffer = (unsigned short*)frameBuf1;\n\n\t\tif (camerror == qerrSuccess) {\n\t\t\tlogger.log(\"downloading complete\");\n\t\t\tint k, kp = 0;\n\t\t\tfor (int j = 0; j < shared_image.height; j++) {\n\t\t\t\tk = j*shared_image.width;\n\t\t\t\tkp = (image_height - 1 - j)*shared_image.width;\n\t\t\t\tmemcpy(&(buffers[num_buffers_filled][k]), &(intermediate_buffer[kp]), 2 * shared_image.width);\n\t\t\t}\n\t\t\tnum_buffers_filled++;\n\t\t}\n\t\telse {\n\t\t\tlogger.log(format(\"Could not download image from camera: %d\\n\") % camerror);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (num_buffers_filled > 0) {\n\t\t\tbool multiple_triggers = false;\n\t\t\tif (num_buffers_filled > 1) {\n\t\t\t\tmultiple_triggers = true;\n\t\t\t}\n\t\t\tshared_image.num_exposures = num_buffers_filled;\n\t\t\tmemset(shared_image.pixels, 0, sizeof(unsigned short)*shared_image.width*shared_image.height);\n\t\t\tfor (unsigned int i = 0; i < num_buffers_filled && i < shared_image.max_num_exposures; i++) {\n\n\t\t\t\tfor (int j = 0; j < shared_image.width*shared_image.height; j++) {\n\t\t\t\t\tshared_image.pixels[j] += buffers[i][j];\n\t\t\t\t}\n\n\t\t\t\tmemcpy(shared_image.separate_buffers[i], buffers[i], sizeof(unsigned short)*shared_image.width*shared_image.height);\n\t\t\t}\n\t\t\tupdate();\n\t\t\tfill_general_admin();\n\t\t\tfill_real_camera_admin(timestamp, multiple_triggers);\n\t\t\tlogger.log(format(\"sharing image with counter_stars %d\") % shared_image.counter_stars);\n\t\t\tshare_image();\n\t\t\tif (enough_space_to_save_images()) {\n\t\t\t\tlogger.log(\"saving image(s)\");\n\t\t\t\tfor (unsigned int i = 0; i < num_buffers_filled; i++) {\n\t\t\t\t\tsave_image(buffers[i], i, multiple_triggers);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlogger.log(\"not enough space to save image(s)\");\n\t\t\t}\n\t\t}\n\t\n}\n\nvoid CameraWindows::init_gain()\n{\n\tunsigned long minval = 0;\n\tunsigned long maxval= 0;\n\tif ((QCam_GetParamMin((QCam_Settings*)&settings, qprmNormalizedGain, &minval) == qerrSuccess)\n\t\t&& (QCam_GetParamMax((QCam_Settings*)&settings, qprmNormalizedGain, &maxval) == qerrSuccess)) {\n\n logger.log(format(\"got gain properties, range is %f to %f\") % ((float)minval / 1000000.0) % ((float)maxval / 1000000.0));\t\t\t\t\n gain_min = double(maxval);\n gain_max = double(minval);\n\t}\n get_gain();\n}\n\nvoid CameraWindows::get_gain()\n{\n unsigned long gain2;\n\tfloat gain = 0;\n\tQCam_GetParam((QCam_Settings*)&settings, qprmNormalizedGain, &gain2);\n\tgain = (float (gain2))/1000000;\n logger.log(format(\"got gain %f\") % gain);\n shared_results.get_gain.found = true;\n shared_results.get_gain.counter = shared_requests.get_gain.counter;\n shared_results.get_gain.value = gain;\n Shared::Camera::results_for_main.share();\n}\n\nvoid CameraWindows::process_requests()\n{\n if (shared_requests.get_gain.counter != shared_results.get_gain.counter) {\n shared_results.get_gain.counter = shared_requests.get_gain.counter;\n get_gain();\n }\n if (shared_requests.set_gain.counter != shared_results.set_gain.counter) {\n shared_results.set_gain.counter = shared_requests.set_gain.counter;\n if (shared_requests.set_gain.value >= gain_min && shared_requests.set_gain.value <= gain_max) {\n unsigned long gainval = unsigned long(shared_requests.set_gain.value);\n logger.log(format(\"setting gain to %f\") % gainval);\n\t\t\tQCam_SetParam((QCam_Settings*)&settings, qprmNormalizedGain, gainval);\n\t\t\tQCam_SendSettingsToCam(camhandle, (QCam_Settings*)&settings);\n }\n get_gain();\n }\n}\n\nvoid CameraWindows::thread_function()\n{\n #ifdef WIN32\n DWORD thread_priority;\n\t//int wait_time = 30;\t\t\t\t//time between taking pictures, in seconds\n //thread_priority = GetThreadPriority(GetCurrentThread());\n //SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);\n //thread_priority = GetThreadPriority(GetCurrentThread());\n logger.log(format(\"main has thread priority %i\")%thread_priority);\n #endif\n\n while (!Shared::General::quit) {\n update();\n if (enabled) {\n if (need_to_try_camera_ready()) {\n if (init_camera()) {\n camera_ready = true;\n shared_results.connected = true;\n Shared::Camera::results_for_main.share();\n }\n\t\t\t}\n if (camera_ready) {\n\t\t\t\tlogger.log(\"Camera is ready, trying to read image\");\n read_image_if_available();\n process_requests();\n }\n\t\t\tif (internal_triggering) {\n\t\t\t\tfor (int i = 1; (!Shared::General::quit) && i < 100; i++) {\n\t\t\t\t\tusleep(int(internal_period * 10000));\n\t\t\t\t}\n\t\t\t}\n }\n }\n\tlogger.log(\"Cleaning up camera\");\n clean_up_camera();\n}\n\nvoid CameraWindows::wait_for_quit()\n{\n\tlogger.log(\"Abort QCam\\n\");\n\tif (isCapturing) QCam_Abort(camhandle);\n\tthread.interrupt();\n thread.join();\n}\n\n#endif\n" }, { "alpha_fraction": 0.6608505845069885, "alphanum_fraction": 0.6652126312255859, "avg_line_length": 16.30188751220703, "blob_id": "84b7725078fd20ea4684d0030dccbc0eb93868e5", "content_id": "1cf5691debc7d6fdfda1a972b4bd6def3d2ba41d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 918, "license_type": "no_license", "max_line_length": 102, "num_lines": 53, "path": "/stars/code/solving/matching/fluxer.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__MATCHING__FLUXER_H\n#define SOLVING__MATCHING__FLUXER_H\n\n#include <vector>\n\nnamespace Solving\n{\n class Solution;\n class Blob;\n class Star;\n\n namespace Matching\n {\n class Fluxer;\n }\n}\n\nnamespace levmar_fluxer\n{\n\nstruct additional_data\n{\n double* star_fluxes;\n double* errors;\n};\n\n}\n\nclass Solving::Matching::Fluxer\n{\n public:\n Fluxer();\n ~Fluxer();\n void fit(Solution& solution, std::vector<Blob>& blobs, std::vector<Star>& stars, bool print=true);\n\n private:\n unsigned int max_num_blobs;\n double* workspace;\n double* covar;\n levmar_fluxer::additional_data adata;\n double* blob_fluxes;\n double* params;\n double* info;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6691489219665527, "alphanum_fraction": 0.6803191304206848, "avg_line_length": 30.316667556762695, "blob_id": "45be676be7c7b15de9cc0156f44bfdb2b31c6bfb", "content_id": "a66ddc59493752e8b95ea1217fb2f41feb068fb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1881, "license_type": "no_license", "max_line_length": 104, "num_lines": 60, "path": "/stars/code/shared/simulations/brightness.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"brightness.h\"\n#include \"../../tools/math.h\"\n#include \"../../parameters/manager.h\"\nextern \"C\" {\n#include \"../../networking/xsc_protocol/xsc_protocol.h\"\n}\n\nusing namespace Shared::Simulations;\n\nBrightness::Brightness()\n{\n counter = 0;\n allow_enable = false;\n enabled = false;\n level_kepsa = 0.0;\n gain_db = 0.0;\n actual_exposure = 0.1;\n simulated_exposure = 0.1;\n}\n\nvoid Brightness::init(Parameters::Manager& params)\n{\n allow_enable = params.general.try_get(\"imaging.brightness_simulator.allow_enable\", false);\n enabled = params.general.try_get(\"imaging.brightness_simulator.enabled\", false);\n level_kepsa = params.general.try_get(\"imaging.brightness_simulator.level_kepsa\", 0.0);\n actual_exposure = params.general.try_get(\"imaging.brightness_simulator.actual_exposure\", 0.1);\n simulated_exposure = params.general.try_get(\"imaging.brightness_simulator.simulated_exposure\", 0.1);\n gain_db = params.general.try_get(\"imaging.brightness_simulator.gain_db\", 0.0);\n}\n\nBrightness& Brightness::operator=(const Brightness &rhs)\n{\n if (this != &rhs) {\n counter = rhs.counter;\n allow_enable = rhs.allow_enable;\n enabled = rhs.enabled;\n level_kepsa = rhs.level_kepsa;\n gain_db = rhs.gain_db;\n actual_exposure = rhs.actual_exposure;\n simulated_exposure = rhs.simulated_exposure;\n }\n return *this;\n}\n\nBrightness& Brightness::operator=(const XSCBrightness &rhs)\n{\n counter = rhs.counter;\n enabled = rhs.enabled;\n level_kepsa = rhs.level_kepsa;\n gain_db = rhs.gain_db;\n actual_exposure = rhs.actual_exposure;\n simulated_exposure = rhs.simulated_exposure;\n return *this;\n}\n\n" }, { "alpha_fraction": 0.7216054797172546, "alphanum_fraction": 0.7245943546295166, "avg_line_length": 28.64556884765625, "blob_id": "efc145844a5328fa046f09b7a6beb09302c40990", "content_id": "a5cf075a2f1222de1babf34a5ea7bafa36cec7f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2342, "license_type": "no_license", "max_line_length": 97, "num_lines": 79, "path": "/starcam/commandgui.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#ifndef COMMANDGUI_H\n#define COMMANDGUI_H\n\n#include <qwidget.h>\n#include <qthread.h>\n#include \"camcommunicator.h\"\n\n/**\n\t@author Steve Benton <[email protected]>\n\tGUI interface for starcam commands\n\twhen commands are added to starcam.cpp::interpretCommand, they sould be added here too\n*/\n\nclass QLabel;\nclass QListBox;\nclass QLineEdit;\nclass QTextEdit;\n//class QString;\nclass CommandGUI; //advance declaration for use in ReadThread\n\nclass ReadThread : public QThread\n{\n\tpublic:\n\t\tReadThread() { commander = NULL; }\n\t\tvoid setCommander(CommandGUI *cmdr) { commander = cmdr; }\n\t\tvirtual void run();\n\tprivate:\n\t\tCommandGUI *commander;\n};\n\nclass CommandGUI : public QWidget\n{\n\tQ_OBJECT\npublic:\n\tCommandGUI(QWidget* parent=0, const char *name = 0, const char* commTarget=\"aragog.spider\");\n\t~CommandGUI();\n\t\n\tvoid showReturnVal(QString&);\n\t\n\tenum Devices { Camera = 0, Image, Lens, Overall };\n\tenum CameraCmd { TrigExp = 0, TrigFocus, TrigFocusF, SetExpTime, SetExpInt, SetFocRsln, Power };\n\tenum ImageCmd { SetBadpix = 0, SetMaxBlobs, SetGrid, SetThreshold, SetDisttol};\n\tenum LensCmd { Move = 0, Force, SetTol, Other };\n\tenum OverCmd { Conf = 0, showBox };\n\t\n\tfriend class ReadThread;\n\t\npublic slots:\n\tvoid deviceSelected(int);\n\tvoid commandSelected(int);\n\tvoid valueChanged(const QString&);\n\tvoid sendCommand();\n\t\nprivate:\n\tQLabel *command; //displays the current command\n\tQLabel *description; //displays a description of the current command\n\t\n\tQLabel *valDesc; //description for extra value\n\tQLineEdit *value; //for reading extra values needed for command\n\tQLabel *valLabel; //displays \"Value\", needs to hide/shows\n\t\n\tQListBox *deviceBox; //box for selecting the device (cam, img, lens) for the command\n\tQListBox *camCmds; //list of camera commands\n\tQListBox *imgCmds; //list of image commnads\n\tQListBox *lensCmds; //list of commands for the lens\n\tQListBox *overCmds; //list of overall/general commands\n\tQListBox *currentCmds; //this will be set to whichever of the above boxes is being used\n\n\tQTextEdit *returnPane; //return values are added here\n\t\n\tint deviceIndex, commandIndex; //indexes for current selection amongst list boxes\n\t\n\tCamCommunicator comm;\n\tbool keepReading; //loop condition for read loop\n\tReadThread reader; //loops on reading responses from the flight computer\n};\n\n\n#endif\n" }, { "alpha_fraction": 0.4726051986217499, "alphanum_fraction": 0.4825560450553894, "avg_line_length": 43.604278564453125, "blob_id": "7e7e8069d3038ed20353869cfdf50e5165332cb4", "content_id": "258f14398499a13bdbc8290bb173b289b90ff0ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8341, "license_type": "no_license", "max_line_length": 118, "num_lines": 187, "path": "/common/include/blast.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* blast.h: the BLAST flight code common header\n *\n * This software is copyright (C) 2004-2010 University of Toronto\n *\n * This software 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 2 of the License, or\n * (at your option) any later version.\n *\n * This software 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 this software; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#ifndef INCLUDE_BLAST_H\n#define INCLUDE_BLAST_H\n\n#include <stdlib.h> /* free() */\n#include <stdarg.h> /* ANSI C variable arguments (va_list, va_start, va_end) */\n#include <sys/types.h> /* for size_t */\n#include <string.h> /* for memset */\n#include <errno.h> /* for errno */\n\n/* Commonly used seed values (generally SYNC words for telemetry)*/\n#define BLAST_MAGIC8 0xEB\n#define BLAST_MAGIC16 0xEB90\n#define BLAST_MAGIC32 0xEB90146F\n\n/* BUOS (BLAST Unified Output Scheme) definitions */\n#define BUOS_MAX 2048\ntypedef enum {none, info, warning, err, tfatal, fatal, startup, sched, mem}\n buos_t;\n\nvoid bputs_stdio(buos_t l, const char* s);\nvoid bputs_syslog(buos_t l, const char* s);\nvoid bprintf(buos_t, const char*, ...) __attribute__((format(printf, 2, 3)));\nvoid berror(buos_t, const char*, ...) __attribute__((format(printf, 2, 3)));\nvoid bputs(buos_t, const char*);\nvoid buos_use_func(void (*puts_func)(buos_t, const char*));\nvoid buos_use_stdio(void);\nvoid buos_use_syslog(void);\nvoid buos_disallow_mem(void);\nvoid buos_allow_mem(void);\nvoid buos_disable_exit(void);\nvoid buos_enable_exit(void);\n\n#ifndef __FILENAME__\n# define __FILENAME__ __FILE__\n#endif\n\n/* BLAMM (BLAST Memory Manager) definitions */\nvoid *_balloc(buos_t, size_t, const char*, int, const char*) __attribute__((malloc));\nvoid _bfree(buos_t, void*, const char*, int, const char*);\nvoid _basprintf(buos_t, char**, const char*, const char*, int, const char*, ...)\n __attribute__((format(printf, 3, 7), noinline));\nvoid *_reballoc(buos_t, void*, size_t, const char*, int, const char*);\nchar *_bstrdup(buos_t, const char*, const char*, int, const char*) __attribute__((malloc));\nchar *_bstrndup(buos_t, const char*, size_t n, const char*, int, const char*) __attribute__((malloc));\nvoid *_memdup(buos_t l, const void *m_src, size_t n, const char* m_func, int m_line, const char *m_file)\n __attribute__((malloc));\n\n#define balloc(lvl, size) _balloc(lvl, size, __FUNCTION__ , __LINE__ , __FILENAME__ )\n#define bfree(lvl, ptr) _bfree(lvl, ptr, __FUNCTION__ , __LINE__ , __FILENAME__ )\n#define reballoc(lvl, ptr, newsize) _reballoc(lvl, ptr, newsize, __FUNCTION__ , __LINE__ , __FILENAME__)\n#define bstrdup(lvl, ptr) _bstrdup(lvl , ptr , __FUNCTION__ , __LINE__ , __FILENAME__)\n#define bstrndup(lvl, ptr, len) _bstrndup(lvl , ptr, len , __FUNCTION__ , __LINE__ , __FILENAME__)\n#define basprintf(lvl, ptr, fmt, ...) _basprintf(lvl, ptr, fmt, __FUNCTION__ , __LINE__ , __FILENAME__, ##__VA_ARGS__)\n#define memdup(level, ptr, size) _memdup(level, ptr, size, __FUNCTION__ , __LINE__ , __FILENAME__)\n\n/** Free memory space */\n#define BLAST_SAFE_FREE(_ptr) do { if (_ptr) {bfree(mem, _ptr); (_ptr) = NULL;} } while (0)\n\n/** Zero an element */\n#define BLAST_ZERO(x) memset((void*)&(x), 0, sizeof(x))\n\n/** Zero dereferenced pointer */\n#define BLAST_ZERO_P(x) do { if (x) memset((void*)(x), 0, sizeof(*(x))); } while (0)\n\n#define blast_fatal(fmt, ...) \\\n do { \\\n bprintf(fatal, \"%s:%d (%s):\" fmt, __FILENAME__, __LINE__, __func__, ##__VA_ARGS__); \\\n }while(0)\n#define blast_tfatal(fmt, ...) \\\n do { \\\n bprintf(tfatal, \"%s:%d (%s):\" fmt, __FILENAME__, __LINE__, __func__, ##__VA_ARGS__); \\\n }while(0)\n#define blast_err(fmt, ...) \\\n do { \\\n bprintf(err, \"%s:%d (%s):\" fmt, __FILENAME__, __LINE__, __func__, ##__VA_ARGS__); \\\n }while(0)\n#define blast_info(fmt, ...) \\\n do { \\\n bprintf(info, \"%s:%d (%s):\" fmt, __FILENAME__, __LINE__, __func__, ##__VA_ARGS__); \\\n }while(0)\n#define blast_warn(fmt, ...) \\\n do { \\\n bprintf(warning, \"%s:%d (%s):\" fmt, __FILENAME__, __LINE__, __func__, ##__VA_ARGS__); \\\n }while(0)\n#define blast_startup(fmt, ...) \\\n do { \\\n bprintf(startup, \"%s:%d (%s):\" fmt, __FILENAME__, __LINE__, __func__, ##__VA_ARGS__); \\\n }while(0)\n#define blast_sched(fmt, ...) \\\n do { \\\n bprintf(sched, \"%s:%d (%s):\" fmt, __FILENAME__, __LINE__, __func__, ##__VA_ARGS__); \\\n }while(0)\n#define blast_mem(fmt, ...) \\\n do { \\\n bprintf(mem, \"%s:%d (%s):\" fmt, __FILENAME__, __LINE__, __func__, ##__VA_ARGS__); \\\n }while(0)\n#ifndef NDEBUG\n#define blast_dbg(fmt, ...) \\\n do { \\\n bprintf(info, \"%s:%d (%s):\" fmt, __FILENAME__, __LINE__, __func__, ##__VA_ARGS__); \\\n }while(0)\n#else\n#define blast_dbg(...)\n#endif\n\n\n/**\n * Prints the error message followed by an explanation of the errno code\n */\n#define blast_strerror(fmt, ...) \\\n do { \\\n blast_err(fmt \":%s\", ##__VA_ARGS__, strerror(errno)); \\\n } while (0)\n\n/**\n * Allocates a temporary, formated string on the stack. This memory will be automatically freed\n * when the function exits, so do not call free or any variant on the pointer\n */\n#define blast_tmp_sprintf(ptr, format, ...) \\\n ({ \\\n int bytes; \\\n \\\n bytes = snprintf(NULL, 0, format, ##__VA_ARGS__)+1; \\\n ptr = alloca(bytes * sizeof(char)); \\\n snprintf(ptr, bytes, format, ##__VA_ARGS__); \\\n bytes; \\\n })\n\n/**\n * Allocates a temporary, formated string on the stack. This memory will be automatically freed\n * when the function exits, so do not call free or any variant on the pointer\n */\n#define blast_tmp_vsprintf(ptr, format, ...) \\\n ({ \\\n int bytes; \\\n \\\n bytes = vsnprintf(NULL, 0, format, ##__VA_ARGS__)+1; \\\n ptr = alloca(bytes * sizeof(char)); \\\n vsnprintf(ptr, bytes, format, ##__VA_ARGS__); \\\n bytes; \\\n })\n#endif\n\n#define BLAST_SWAP(_x, _y) \\\n do { \\\n typeof(_x) _temp = (_x); \\\n (_x) = (_y); \\\n (_y) = _temp; \\\n } while (0)\n\n/** Min/Max common use */\n#undef max\n#define max(a, b) ((a) >= (b) ? (a) : (b))\n#undef min\n#define min(a, b) ((a) <= (b) ? (a) : (b))\n\n#define min_safe(x, y) ({ \\\n typeof(x) _min1 = (x); \\\n typeof(y) _min2 = (y); \\\n (void) (&_min1 == &_min2); \\\n _min1 < _min2 ? _min1 : _min2; })\n\n#define max_safe(x, y) ({ \\\n typeof(x) _max1 = (x); \\\n typeof(y) _max2 = (y); \\\n (void) (&_max1 == &_max2); \\\n _max1 > _max2 ? _max1 : _max2; })\n" }, { "alpha_fraction": 0.5950895547866821, "alphanum_fraction": 0.607521116733551, "avg_line_length": 31.425580978393555, "blob_id": "79152a35d16f67129e3223961069b1fc9da348d0", "content_id": "1c6115e389a2809a267ac5a3327ac34039b46201", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 41829, "license_type": "no_license", "max_line_length": 159, "num_lines": 1290, "path": "/liblinklist/linklist_connect.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* -----------------------------------------------------------------------\n * -------------------------- TCP Communications -------------------------\n * -----------------------------------------------------------------------\n * This program is distributed under the GNU General Public License (GPL).\n *\n * The following was developed in the QNX Momentics IDE and compiled on\n * using QNX RTOS version 6.5.\n *\n * ------------------------- Description -------------------------------\n * This is TCP network setup and configuration for communications with\n * ground station links. Contained are the functions used to transfer\n * frame files over the network along with the format files and\n * linklists required to parse the received data. The main programs that\n * use this code are mole and bittlm.\n *\n * ---------------------------- Author ---------------------------------\n * L. Javier Romualdez (B.Eng Aerospace)\n * Institute for Aerospace Studies (UTIAS)\n * University of Toronto\n *\n * Created: August 29, 2017\n *\n * Copyright 2017 Javier Romualdez\n *\n * -------------------------- Revisions --------------------------------\n *\n *\n */\n\n#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n#include <errno.h>\n#include <netdb.h>\n#include <signal.h>\n#include <string.h>\n#include <time.h>\n#include <unistd.h>\n#include <inttypes.h>\n#include <termios.h>\n\n#include <sys/socket.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/stat.h>\n#include <dirent.h>\n\n#include <netinet/in.h>\n#include <arpa/inet.h>\n\n#include <pthread.h> // threads\n#include <openssl/md5.h>\n#include <regex.h>\n\n#include \"linklist.h\"\n#include \"linklist_writer.h\"\n#include \"linklist_connect.h\"\n\n#define DATAETC \"/data/etc\"\n#define MAX_CONNECT_TRIES 5\n\n#ifndef MIN \n#define MIN(a,b) ((a) < (b) ? (a) : (b))\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nextern int (*linklist_info)(const char *, ...);\nextern int (*linklist_err)(const char *, ...);\nextern int (*linklist_warn)(const char *, ...);\nextern int (*linklist_fatal)(const char *, ...);\n\n\nuint16_t theday = 0;\nuint16_t themonth = 0;\nuint16_t theyear = 0;\nunsigned int clientport = CLIENT_TELEM_PORT;\nunsigned int serverport = CLIENT_TELEM_PORT;\n\n/* packet header (12 bytes)\n * ----------------\n * [0-3] = unique sender recver serial\n * [4-7] = frame number\n * [8-9] = packet number\n * [10-11] = total number of packets\n */\n\nvoid writeTCPHeader(uint8_t * header, uint32_t serial, uint32_t frame_num, uint16_t i_pkt, uint16_t n_packets) {\n // build header\n *((uint32_t *) (header+0)) = serial;\n *((uint32_t *) (header+4)) = frame_num;\n *((uint16_t *) (header+8)) = i_pkt;\n *((uint16_t *) (header+10)) = n_packets;\n}\n\nvoid readTCPHeader(uint8_t * header, uint32_t **ser, uint32_t **frame_num, uint16_t **i_pkt, uint16_t **n_pkt) {\n // extract header\n *ser = (uint32_t *) (header+0);\n *frame_num = (uint32_t *) (header+4);\n *i_pkt = (uint16_t *) (header+8);\n *n_pkt = (uint16_t *) (header+10);\n}\n\nstatic int one (const struct dirent *unused)\n{\n if (unused) return 1;\n return 1;\n}\n\n// opens a dialog to select file by name from the server\nvoid user_file_select(linklist_tcpconn_t * tc, char *linklistname)\n{\n char name[LINKLIST_MAX_FILENAME_SIZE][LINKLIST_SHORT_FILENAME_SIZE] = {{0}};\n int numlink = request_server_archive_list(tc,name);\n\n if (!numlink) {\n linklistname[0] = 0;\n return;\n }\n\n int i,j;\n\n\n // display all the entries that match the optionally supplied linklist name\n int match = strlen(linklistname);\n int n_match = numlink;\n char str_match[LINKLIST_MAX_FILENAME_SIZE] = {0};\n strcpy(str_match, linklistname);\n \n regex_t regex;\n\n if (match) {\n n_match = 0;\n if (regcomp(&regex, str_match, 0)) {\n linklist_err(\"Regex failed\\n\");\n return;\n }\n for (i=0;i<numlink;i++) {\n if (regexec(&regex, name[i], 0, NULL, 0) != REG_NOMATCH) {\n strncpy(linklistname, name[i], LINKLIST_MAX_FILENAME_SIZE);\n\n char temp[LINKLIST_SHORT_FILENAME_SIZE];\n snprintf(temp, LINKLIST_SHORT_FILENAME_SIZE, \"%s\", name[n_match]);\n snprintf(name[n_match], LINKLIST_SHORT_FILENAME_SIZE, \"%s\", name[i]);\n snprintf(name[i], LINKLIST_SHORT_FILENAME_SIZE, \"%s\", temp);\n\n n_match++;\n }\n }\n regfree(&regex);\n linklist_info(\"Found %d matches for regex entry \\\"%s\\\"\\n\\n\", n_match, str_match);\n }\n\n // don't have exactly 1 matching entry, so prompt user to select\n if ((n_match != 1) || (strlen(linklistname) == 0)) {\n // deal with display widths\n if (n_match) numlink = n_match;\n int n = (numlink-1)/3+1;\n int width[3] = {0};\n\n for (i=0;i<n;i++) {\n if ((int) strlen(name[i]) > width[0]) width[0] = strlen(name[i]);\n if ((int) strlen(name[i+n]) > width[1]) width[1] = strlen(name[i+n]);\n if ((int) strlen(name[i+n+n]) > width[2]) width[2] = strlen(name[i+n+n]);\n }\n for (i=0;i<3;i++) width[i] += 3;\n\n\n linklist_info(\"\\nSelect archive file:\\n\\n\");\n\n for (i=0;i<n;i++) {\n if (name[i][0]) printf(\"%.2d: %s\",i,name[i]);\n for (j = strlen(name[i]); j < width[0]; j++) printf(\" \");\n if (name[i+n][0]) printf(\"%.2d: %s\",i+n,name[i+n]);\n for (j = strlen(name[i+n]); j < width[1]; j++) printf(\" \");\n if (name[i+n+n][0]) printf(\"%.2d: %s\",i+n+n,name[i+n+n]);\n printf(\"\\n\");\n }\n\n while (1) {\n char ta[10];\n printf(\"\\nFile number: \");\n if (fscanf(stdin,\"%s\",ta) == 0) {\n linklist_err(\"Unable to parse file number\\n\");\n }\n int cn = atoi(ta);\n if ((cn >= 0) && (cn < numlink)) {\n strncpy(linklistname, name[cn], LINKLIST_MAX_FILENAME_SIZE);\n break;\n }\n linklist_info(\"\\nInvalid selection\\n\");\n } \n }\n \n linklist_info(\"Archive file \\\"%s\\\" selected\\n\", linklistname);\n}\n\nint copy_file(char *old_filename, char *new_filename)\n{\n FILE *ptr_old, *ptr_new;\n int a;\n\n if (strcmp(old_filename, new_filename) == 0) return 0;\n\n ptr_old = fopen(old_filename, \"rb\");\n ptr_new = fopen(new_filename, \"wb\");\n\n if (!ptr_old) {\n linklist_err(\"Can't open %s\\n\", old_filename);\n return -1;\n }\n\n if (!ptr_new) {\n linklist_err(\"Can't open %s\\n\", new_filename);\n fclose(ptr_old);\n return -1;\n }\n\n while (1) {\n a = fgetc(ptr_old); \n if (!feof(ptr_old)) fputc(a, ptr_new);\n else break;\n }\n\n fclose(ptr_new);\n fclose(ptr_old);\n return 0;\n}\n\n\nvoid set_linklist_client_port(unsigned int port) {\n clientport = port;\n}\nvoid set_linklist_server_port(unsigned int port) {\n serverport = port;\n}\n\n// a macro function that requests format and link files and parses them;\n// this function overwrites all previously parsed telemlist format file\n// and linklist link files\nuint32_t sync_with_server(struct TCPCONN * tc, char * selectname, char * linklistname, unsigned int flags,\n superframe_t ** sf, linklist_t ** ll)\n{\n // initiate server connection if not done already\n while (tc->fd <= 0) {\n tc->fd = connect_tcp(tc);\n sleep(1);\n }\n\n uint32_t recv_ff_serial, recv_ll_serial;\n\n char reqffname[LINKLIST_MAX_FILENAME_SIZE] = {0};\n char reqllname[LINKLIST_MAX_FILENAME_SIZE] = {0};\n char reqcsname[LINKLIST_MAX_FILENAME_SIZE] = {0};\n char pathname[LINKLIST_MAX_FILENAME_SIZE] = {0};\n int calspecs = 1;\n\n // get linklist format file\n while (1) {\n sleep(1);\n\n snprintf(reqffname, LINKLIST_MAX_FILENAME_SIZE, \"%s\" SUPERFRAME_FORMAT_EXT, selectname); // suffix for formatfile\n snprintf(reqllname, LINKLIST_MAX_FILENAME_SIZE, \"%s\" LINKLIST_FORMAT_EXT, selectname); // suffix for linkfile\n snprintf(reqcsname, LINKLIST_MAX_FILENAME_SIZE, \"%s\" CALSPECS_FORMAT_EXT, selectname); // suffix for calspecs file\n\n // get the formatfile name\n recv_ff_serial = request_server_file(tc, reqffname, flags);\n if (recv_ff_serial == 0x1badfeed) { // file not found\n linklist_err(\"Failed to recv superframe format\\n\");\n user_file_select(tc, selectname);\n continue;\n } else if (recv_ff_serial == 0) { // connection issue\n close_connection(tc);\n tc->fd = connect_tcp(tc);\n continue;\n }\n\n // get the linkfile name\n recv_ll_serial = request_server_file(tc, reqllname, flags);\n if (recv_ll_serial == 0x1badfeed) { // file not found\n linklist_err(\"Failed to recv linklist format\\n\");\n user_file_select(tc, selectname);\n continue;\n } else if (recv_ll_serial == 0) { // connection issue\n close_connection(tc);\n tc->fd = connect_tcp(tc);\n continue;\n }\n\n // get the calspecs name\n uint32_t temp_ll_serial = request_server_file(tc, reqcsname, flags);\n if (temp_ll_serial == 0x1badfeed) { // file not found\n calspecs = 0; \n } else if (temp_ll_serial == 0) { // connection issue\n close_connection(tc);\n tc->fd = connect_tcp(tc);\n continue;\n }\n\n break;\n }\n\n // parse the superframe format\n snprintf(pathname, LINKLIST_MAX_FILENAME_SIZE, \"%s/%s\", \"/tmp\", reqffname);\n if (!(*sf = parse_superframe_format(pathname))) {\n linklist_err(\"Superframe format parser error.\\n\");\n return 0;\n }\n // linklist_info(\"Parsed superframe format \\\"%s\\\"\\n\", pathname);\n unlink(pathname);\n\n // parse the linklist format\n snprintf(pathname, LINKLIST_MAX_FILENAME_SIZE, \"%s/%s\", \"/tmp\", reqllname);\n if (!(*ll = parse_linklist_format(*sf, pathname))) {\n linklist_err(\"Linklist format parser error.\\n\");\n return 0;\n }\n // linklist_info(\"Parsed linklist format \\\"%s\\\"\\n\", pathname);\n unlink(pathname);\n\n // set the name assigned by the server\n set_server_linklist_name(tc, selectname);\n // linklist_info(\"Linklist name set to %s\\n\", selectname);\n\n // request linklist name resolution if necessary (for symlinks on server)\n request_server_linklist_name(tc, linklistname, LINKLIST_MAX_FILENAME_SIZE, flags & TCPCONN_RESOLVE_NAME); \n // linklist_info(\"Linklist name resolves to %s\\n\", linklistname);\n\n // parse the calspecs format\n if (calspecs) {\n char fname[LINKLIST_MAX_FILENAME_SIZE];\n snprintf(pathname, LINKLIST_MAX_FILENAME_SIZE, \"%s/%s\", \"/tmp\", reqcsname);\n snprintf(fname, LINKLIST_MAX_FILENAME_SIZE, \"%s/%s\" CALSPECS_FORMAT_EXT, archive_dir, linklistname);\n\n if (copy_file(pathname, fname) < 0) {\n linklist_err(\"Cannot parse calspecs format \\\"%s\\\"\\n\", pathname);\n } else {\n // linklist_info(\"Parsed calspecs format \\\"%s\\\"\\n\", pathname);\n }\n strncpy((*sf)->calspecs, fname, LINKLIST_MAX_FILENAME_SIZE);\n if (strcmp(pathname, fname)) unlink(pathname);\n } else {\n (*sf)->calspecs[0] = '\\0';\n } \n\n return recv_ll_serial;\n}\n\nchar *get_real_file_name(char * real_name, char * symlink_name) \n{\n char resolved_name[LINKLIST_MAX_FILENAME_SIZE] = {0};\n char full_name[LINKLIST_MAX_FILENAME_SIZE] = {0};\n snprintf(full_name, LINKLIST_MAX_FILENAME_SIZE, \"%s/%s\" LINKLIST_EXT \".00\", archive_dir, symlink_name);\n\n if (!realpath(full_name, resolved_name)) {\n real_name[0] = '\\0';\n return NULL;\n }\n int i = 0;\n for (i = strlen(resolved_name)-1; i >= 0; i--) {\n if (resolved_name[i] == '/') break;\n }\n strncpy(real_name, resolved_name+i+1, LINKLIST_MAX_FILENAME_SIZE);\n\n // strip the file extension\n for (i = 0; i < (int) strlen(real_name); i++) {\n if (real_name[i] == '.') break;\n }\n real_name[i] = '\\0';\n\n return real_name;\n}\n\nvoid *connection_handler(void *arg)\n{\n //Get the socket descriptor\n int sock = (uintptr_t) arg;\n\n struct TCPCONN tc = {0};\n tc.fd = sock;\n\n int read_size;\n char client_message[TCP_PACKET_HEADER_SIZE];\n uint8_t header[TCP_PACKET_HEADER_SIZE] = {0};\n uint32_t *req_frame_num;\n uint32_t *req_serial;\n uint16_t *req_i;\n uint16_t *req_n;\n uint8_t *buffer = NULL;\n unsigned int buffersize = 0;\n\n int client_on = 1;\n int frame_lag = 1; \n\n char linklist_name[LINKLIST_MAX_FILENAME_SIZE] = {0};\n\n char * archive_filename;\n char archive_symlink_filename[LINKLIST_MAX_FILENAME_SIZE] = {0}; // path to the symlink\n char archive_resolved_filename[LINKLIST_MAX_FILENAME_SIZE] = {0}; // path the file that the symlink resolves to\n char linklist_resolved_name[LINKLIST_MAX_FILENAME_SIZE] = {0}; // name of the file that the symlink resolves to\n linklist_rawfile_t * archive_rawfile = NULL;\n int archive_framenum = 0;\n int archive_lag_framenum = 0;\n int client_flags = 0;\n\n linklist_info(\"::SERVER:: Accept CLIENT %d\\n\",sock);\n\n while (client_on) {\n // recv header request from client\n read_size = recv(sock, client_message, TCP_PACKET_HEADER_SIZE, 0);\n\n if (read_size <= 0) {\n linklist_info(\"::CLIENT %d:: connection dropped\\n\",sock);\n client_on = 0;\n break;\n }\n readTCPHeader((uint8_t *) client_message, &req_serial, &req_frame_num, &req_i, &req_n);\n\n // process type of request\n if (*req_serial == SERVER_LL_REQ) { // client requesting superframe/linklist format file to be sent\n // recv name: *req_frame_num is number of characters\n char req_name[LINKLIST_MAX_FILENAME_SIZE] = {0};\n read_size = recv(sock, req_name, MIN(*req_frame_num, LINKLIST_MAX_FILENAME_SIZE), 0);\n \n if (read_size <= 0) {\n linklist_err(\"::CLIENT %d:: unable to receive linklist name\\n\",sock);\n client_on = 0;\n break;\n }\n\n linklist_info(\"::CLIENT %d:: request for file transfer\\n\", sock); \n\n // strip name of slashes\n int i;\n for (i = strlen(req_name)-1; i >= 0; i--) {\n if (req_name[i] == '/') {\n req_name[i] = 0;\n break;\n }\n }\n i++;\n\n // build filename in data backup directory\n char filename[LINKLIST_MAX_FILENAME_SIZE] = {0};\n snprintf(filename, LINKLIST_MAX_FILENAME_SIZE, \"%s/%s\", archive_dir, req_name+i);\n if (send_client_file(&tc, filename, SERVER_ARCHIVE_REQ) < 0) {\n client_on = 0;\n break;\n }\n } else if (*req_serial == SERVER_ARCHIVE_LIST_REQ) { // client requesting list of archived files\n linklist_info(\"::CLIENT %d:: request for archive file list\\n\", sock);\n\n struct dirent **dir;\n int n = scandir(archive_dir, &dir, one, alphasort);\n int i;\n int ifile = 0;\n int nfile = 0;\n\n if (n < 0) {\n linklist_err(\"::CLIENT %d:: unable to open archive directory\\n\", sock);\n client_on = 0;\n break;\n }\n\n // load archive names\n for (i = 0; i < n; i++) {\n int pos;\n for (pos = 0; pos < (int) strlen(dir[i]->d_name); pos++) {\n if (dir[i]->d_name[pos] == '.') break;\n }\n char tempc[LINKLIST_MAX_FILENAME_SIZE];\n snprintf(tempc, LINKLIST_MAX_FILENAME_SIZE, LINKLIST_EXT \".00\");\n\n // look for linklist binary files\n if (strcmp(dir[i]->d_name+pos, tempc) == 0) {\n dir[i]->d_name[pos] = 0; // clear the suffix\n\n // check if corresponding superframe format and linklist format files exist\n snprintf(tempc, LINKLIST_MAX_FILENAME_SIZE, \"%s/%s\" LINKLIST_FORMAT_EXT, archive_dir, dir[i]->d_name);\n if (access(tempc, F_OK) != 0) {\n dir[i]->d_name[0] = 0;\n continue;\n }\n snprintf(tempc, LINKLIST_MAX_FILENAME_SIZE, \"%s/%s\" SUPERFRAME_FORMAT_EXT, archive_dir, dir[i]->d_name);\n if (access(tempc,F_OK) != 0) {\n dir[i]->d_name[0] = 0;\n continue;\n }\n\n // strip the forward slashes \n int j;\n for (j=strlen(dir[i]->d_name)-1;j>=0;j--) {\n if (dir[i]->d_name[j] == '/') break;\n }\n strcpy(tempc, dir[i]->d_name+j+1); // copy the abbr. name\n strcpy(dir[i]->d_name, tempc); // copy it back \n \n nfile++;\n } else {\n dir[i]->d_name[0] = 0;\n }\n }\n\n ifile = 0;\n for (i = 0; i < n; i++) {\n if (strlen(dir[i]->d_name) <= 0) continue;\n\n // respond with header for list transfer\n // format: SERVER_ARCHIVE_LIST_REQ, num chars, file index, total # of files\n writeTCPHeader(header, SERVER_ARCHIVE_LIST_REQ, strlen(dir[i]->d_name)+1, ifile, nfile);\n if (send(sock, header, TCP_PACKET_HEADER_SIZE, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"::CLIENT %d:: unable to send archive name %s\\n\", sock, dir[i]->d_name);\n client_on = 0;\n }\n // send name\n if (send(sock, dir[i]->d_name, strlen(dir[i]->d_name)+1, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"::CLIENT %d:: unable to send archive name %s\\n\", sock, dir[i]->d_name);\n client_on = 0;\n }\n ifile++;\n }\n if (!ifile && !nfile) {\n writeTCPHeader(header, SERVER_ARCHIVE_LIST_REQ, 0, 0, 0);\n if (send(sock, header, TCP_PACKET_HEADER_SIZE, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"::CLIENT %d:: unable to send archive names\\n\", sock);\n client_on = 0;\n }\n \n }\n\n linklist_info(\"::CLIENT %d:: sent %d file names\\n\", sock, nfile); \n\n } else if (*req_serial == SERVER_SET_LL_NAME_REQ) { // client wants to set the linklist name\n // recv name: *req_frame_num is number of characters\n char req_name[LINKLIST_MAX_FILENAME_SIZE] = {0};\n read_size = recv(sock, req_name, MIN(*req_frame_num, LINKLIST_MAX_FILENAME_SIZE), 0);\n\n if (read_size <= 0) {\n linklist_err(\"::CLIENT %d:: unable to receive and set linklist name\\n\", sock);\n client_on = 0;\n break;\n }\n\n // strip name of slashes\n int j;\n for (j = strlen(req_name)-1; j >= 0; j--) {\n if (req_name[j] == '/') { \n req_name[j] = 0;\n break;\n }\n }\n j++;\n\n // this name should include the linklist binary file extension (LINKLIST_EXT)\n strncpy(linklist_name, req_name+j, LINKLIST_MAX_FILENAME_SIZE);\n linklist_info(\"::CLIENT %d:: linklist name set to \\\"%s\\\"\\n\", sock, linklist_name);\n } else if (*req_serial == SERVER_LL_NAME_REQ) { // client wants the linklist name\n char send_name[LINKLIST_MAX_FILENAME_SIZE] = {0};\n if (*req_i & TCPCONN_RESOLVE_NAME) { // resolve any symlinks in linklist name if necessary\n if (!get_real_file_name(send_name, linklist_name)) {\n linklist_err(\"::CLIENT %d:: unable to resolve linklist name \\\"%s\\\"\\n\", sock, linklist_name);\n strncpy(send_name, linklist_name, LINKLIST_MAX_FILENAME_SIZE); // default to unresolved name\n }\n client_flags |= TCPCONN_RESOLVE_NAME;\n } else { // just get the linklist name\n strncpy(send_name, linklist_name, LINKLIST_MAX_FILENAME_SIZE);\n }\n // shorten the name for sending to client if necessary\n if (((*req_frame_num)-1) <= strlen(send_name)) send_name[(*req_frame_num)-1] = 0;\n writeTCPHeader(header, SERVER_LL_NAME_REQ, strlen(send_name)+1, 0, 0);\n if (send(sock, header, TCP_PACKET_HEADER_SIZE, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"::CLIENT %d:: unable to send response to linklist name\\n\", sock);\n client_on = 0;\n break;\n }\n if (send(sock, send_name, strlen(send_name)+1, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"::CLIENT %d:: unable to send linklist name %s\\n\", sock, send_name);\n client_on = 0;\n break;\n }\n linklist_info(\"::CLIENT %d:: linklist \\\"%s\\\" name sent\\n\", sock, send_name);\n } else if (*req_serial == SERVER_ARCHIVE_REQ) { // client requesting archived data\n if (!archive_rawfile) { // assume archive file has not yet been loaded\n // check if linklist_name has been loaded from format file and linklist file request\n if (strlen(linklist_name) == 0) {\n linklist_err(\"::CLIENT %d:: no archive file requested\\n\", sock);\n client_on = 0;\n break;\n }\n\n // write data file base name for archive file\n char real_name[LINKLIST_MAX_FILENAME_SIZE];\n snprintf(archive_symlink_filename, LINKLIST_MAX_FILENAME_SIZE, \"%s/%s\", archive_dir, linklist_name);\n snprintf(archive_resolved_filename, LINKLIST_MAX_FILENAME_SIZE, \"%s/%s\", archive_dir, get_real_file_name(linklist_resolved_name, linklist_name));\n\n archive_filename = (client_flags & TCPCONN_RESOLVE_NAME) ? archive_resolved_filename : archive_symlink_filename;\n strncpy(linklist_resolved_name, real_name, LINKLIST_MAX_FILENAME_SIZE);\n\n if ((archive_rawfile = open_linklist_rawfile(archive_filename, NULL)) == NULL) {\n linklist_err(\"::CLIENT %d:: unable to open archive file \\\"%s\\\"\\n\", sock, archive_filename);\n client_on = 0;\n break;\n }\n linklist_info(\"::CLIENT %d:: opening rawfile \\\"%s\\\"\\n\", sock, archive_filename);\n }\n\n // update the archived file framenumber\n char test_symlink_name[LINKLIST_MAX_FILENAME_SIZE] = {0};\n get_real_file_name(test_symlink_name, linklist_name);\n seekend_linklist_rawfile(archive_rawfile);\n archive_framenum = tell_linklist_rawfile(archive_rawfile);\n archive_lag_framenum = archive_framenum-frame_lag;\n\n // handle the type of data block request \n if (*req_i & TCPCONN_CLIENT_INIT) { // requesting a frame number initialization\n // initialize variables for live data block transfer\n linklist_info(\"::CLIENT %d:: request for initialization\\n\",sock);\n\n // respond with header for live data\n // format: serial, initialization framenm, day, year*12+month\n writeTCPHeader(header, SERVER_ARCHIVE_REQ, archive_framenum-frame_lag, theday, theyear*12+themonth);\n if (send(sock, header, TCP_PACKET_HEADER_SIZE, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"::CLIENT %d:: unable to send initialization message\\n\",sock);\n client_on = 0;\n }\n memset(header, 0, TCP_PACKET_HEADER_SIZE);\n\n linklist_info(\"::CLIENT %d:: initialized with serial 0x%x, nof %d, size %d\\n\", sock, SERVER_ARCHIVE_REQ, archive_framenum, archive_rawfile->framesize);\n } else if (strcmp(linklist_resolved_name, test_symlink_name)) { // the symlink has changed\n // respond with header for change in datafile\n linklist_info(\"::CLIENT %d:: data file symlink change\\n\", sock);\n writeTCPHeader(header, SERVER_ARCHIVE_REQ, *req_frame_num, TCPCONN_FILE_RESET, 0);\n if (send(sock, header, TCP_PACKET_HEADER_SIZE, MSG_MORE | MSG_NOSIGNAL) <= 0) {\n linklist_err(\"::CLIENT %d:: unable to send header\\n\", sock);\n client_on = 0;\n break;\n }\n close_and_free_linklist_rawfile(archive_rawfile);\n archive_rawfile = NULL;\n } else if ((archive_lag_framenum < (int) (*req_frame_num) || (archive_lag_framenum <= 0))) { // no data to read\n // respond with header for no data\n writeTCPHeader(header, SERVER_ARCHIVE_REQ, *req_frame_num, TCPCONN_NO_DATA, 0);\n if (send(sock, header, TCP_PACKET_HEADER_SIZE, MSG_MORE | MSG_NOSIGNAL) <= 0) {\n linklist_err(\"::CLIENT %d:: unable to send header\\n\", sock);\n client_on = 0;\n break;\n }\n } else {\n // respond with header for live data\n writeTCPHeader(header, SERVER_ARCHIVE_REQ, *req_frame_num, 0, 0);\n if (send(sock, header, TCP_PACKET_HEADER_SIZE, MSG_MORE | MSG_NOSIGNAL) <= 0) {\n linklist_err(\"::CLIENT %d:: unable to send header\\n\", sock);\n client_on = 0;\n break;\n }\n\n // buffer allocation \n if (buffersize < archive_rawfile->framesize) {\n if (!buffersize) { // first allocation of the buffer\n buffer = calloc(1, archive_rawfile->framesize);\n } else { // reallocation of the buffer\n buffer = realloc(buffer, archive_rawfile->framesize);\n }\n // handle buffer allocation errors\n if (!buffer) {\n linklist_err(\"::CLIENT %d:: cannot allocate buffer\\n\", sock);\n client_on = 0; \n break;\n }\n buffersize = archive_rawfile->framesize;\n }\n\n // read the file\n if (seek_linklist_rawfile(archive_rawfile, *req_frame_num) != 0) {\n linklist_err(\"::CLIENT %d:: fseek failed\\n\", sock);\n client_on = 0;\n break;\n }\n read_linklist_rawfile(archive_rawfile, buffer);\n\n // send the data \n if (send(sock, buffer, archive_rawfile->framesize, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"::CLIENT %d:: unable to send data\\n\",sock);\n break;\n }\n memset(buffer, 0, buffersize);\n }\n }\n }\n\n linklist_info(\"::SERVER:: closed connection to CLIENT %d\\n\",sock);\n\n // cleanup\n if (archive_rawfile) close_and_free_linklist_rawfile(archive_rawfile);\n archive_rawfile = NULL;\n if (buffer) free(buffer);\n buffer = NULL;\n close(sock);\n\n return 0;\n}\n\nvoid linklist_server(void * arg)\n{\n (void) arg; // not used for now\n\n int client_sock, c;\n struct sockaddr_in server , client;\n int theport = serverport;\n\n //Create socket\n int socket_desc = socket(AF_INET , SOCK_STREAM , 0);\n if (socket_desc == -1) {\n perror(\"socket could not create server socket\");\n exit(4);\n }\n\n //Prepare the sockaddr_in structure\n server.sin_family = AF_INET;\n server.sin_addr.s_addr = INADDR_ANY;\n server.sin_port = htons(theport);\n\n int tru = 1;\n setsockopt(socket_desc, SOL_SOCKET, SO_REUSEADDR, &tru, sizeof(int));\n\n //Bind\n if (bind(socket_desc, (struct sockaddr *) &server , sizeof(server)) < 0) {\n //print the error message\n perror(\"bind failed. Error\");\n return;\n }\n\n //Listen\n listen(socket_desc , 3);\n\n\n //Accept and incoming connection\n linklist_info(\"::SERVER:: Waiting for incoming connections on port %d...\\n\", theport);\n c = sizeof(struct sockaddr_in);\n pthread_t thread_id;\n\n while ((client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c))) {\n if (client_sock < 0) {\n linklist_err(\"Accept client failed\\n\");\n }\n \n uintptr_t the_sock = client_sock;\n if (pthread_create(&thread_id, NULL, connection_handler, (void*) the_sock) < 0) {\n perror(\"Could not create client thread\\n\");\n }\n }\n}\n\n// blocks until establishes a connection with the host at tc->ip\n// return the file descriptor, which is also at tc->fd\nint connect_tcp(struct TCPCONN * tc)\n{\n // start tcp client \n struct sockaddr_in server_info;\n struct hostent *he;\n int socket_fd = 0;\n int numtries = 0;\n\n int connected = 0;\n while (!connected) {\n if ((he = gethostbyname(tc->ip))==NULL) {\n linklist_err(\"Cannot get the host name \\\"%s\\\"\\n\",tc->ip);\n numtries = MAX_CONNECT_TRIES;\n if (tc->flag & TCPCONN_NOLOOP) { // non blocking mode\n return socket_fd;\n }\n goto RETRY;\n }\n\n if (!(tc->flag & TCPCONN_NOLOOP)) linklist_info(\"Connecting to %s:%d...\\n\", tc->ip, clientport);\n connected = 1; \n if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {\n fprintf(stderr, \"Socket Failure!!\\n\");\n if (tc->flag & TCPCONN_NOLOOP) { // non blocking mode\n return 0;\n }\n goto RETRY;\n }\n\n int tru = 1;\n setsockopt(socket_fd,SOL_SOCKET,SO_REUSEADDR,&tru,sizeof(int));\n\n memset(&server_info, 0, sizeof(server_info));\n server_info.sin_family = AF_INET;\n server_info.sin_port = htons(clientport);\n server_info.sin_addr = *((struct in_addr *)he->h_addr);\n\n // Set non-blocking \n /*\n long int arg = 0;\n if((arg = fcntl(socket_fd, F_GETFL, NULL)) < 0) { \n fprintf(stderr, \"Error fcntl(..., F_GETFL) (%s)\\n\", strerror(errno)); \n exit(0); \n } \n arg |= O_NONBLOCK; \n if( fcntl(socket_fd, F_SETFL, arg) < 0) { \n fprintf(stderr, \"Error fcntl(..., F_SETFL) (%s)\\n\", strerror(errno)); \n exit(0); \n } \n */\n\n // connect to the socket\n if (connect(socket_fd, (struct sockaddr *)&server_info, sizeof(struct sockaddr))<0) {\n connected = 0;\n close(socket_fd);\n socket_fd = 0;\n if (tc->flag & TCPCONN_NOLOOP) { // non blocking mode\n return socket_fd;\n }\n linklist_info(\"Connection refused...trying again\\n\");\n goto RETRY;\n }\n\n /*\n // Set to blocking mode again... \n if( (arg = fcntl(socket_fd, F_GETFL, NULL)) < 0) { \n fprintf(stderr, \"Error fcntl(..., F_GETFL) (%s)\\n\", strerror(errno)); \n exit(0); \n } \n arg &= (~O_NONBLOCK); \n if( fcntl(socket_fd, F_SETFL, arg) < 0) { \n fprintf(stderr, \"Error fcntl(..., F_SETFL) (%s)\\n\", strerror(errno)); \n exit(0); \n } \n */\n\n // break since all was well\n break;\n\n RETRY : \n sleep(2);\n numtries++;\n\n // try a new host if not in multi mole mode\n if ((numtries >= MAX_CONNECT_TRIES) && !(tc->flag & TCPCONN_LOOP)) {\n linklist_info(\"\\nTry a different host: \");\n if (fscanf(stdin,\"%s\",tc->ip) == 0) {\n linklist_err(\"Unable to parse host\\n\");\n }\n if (tc->ip[strlen(tc->ip)-1] == '\\n') tc->ip[strlen(tc->ip)-1] = 0;\n numtries = 0;\n }\n }\n\n tc->fd = socket_fd; // set the file desc\n\n return socket_fd;\n}\n\n// closes the tcp connection and sets the file descriptor to 0\nint close_connection(struct TCPCONN * tc)\n{\n if (tc->fd != 0) close(tc->fd);\n tc->fd = 0;\n return tc->fd;\n}\n\nvoid send_client_error(struct TCPCONN * tc)\n{\n uint8_t header[TCP_PACKET_HEADER_SIZE] = {0};\n\n writeTCPHeader(header,0x1badfeed, 0, 0, 1);\n if (send(tc->fd, header, TCP_PACKET_HEADER_SIZE, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"::CLIENT %d:: could not send client error\\n\", tc->fd);\n return;\n }\n}\n\n// send a file to the client\nint send_client_file(struct TCPCONN * tc, char * filename, uint32_t serial)\n{\n uint8_t header[TCP_PACKET_HEADER_SIZE] = {0};\n uint8_t buffer[LINKLIST_MAX_FILENAME_SIZE] = {0}; \n\n // open the requested file\n FILE * req_file = fopen(filename, \"r\");\n if (req_file == 0) {\n linklist_err(\"::CLIENT %d:: could not open file \\\"%s\\\"\\n\",tc->fd,filename);\n send_client_error(tc);\n return 0;\n }\n\n // get file size\n fseek(req_file,0,SEEK_END);\n unsigned int req_filesize = ftell(req_file);\n fseek(req_file, 0, SEEK_SET);\n\n // respond with header for file transfer\n // format: SERVER_LL_REQ, total file size [bytes], 4 byte linklist serial\n writeTCPHeader(header, SERVER_LL_REQ, req_filesize, (serial & 0xffff), (serial & 0xffff0000)>>16);\n if (send(tc->fd, header, TCP_PACKET_HEADER_SIZE, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"::CLIENT %d:: unable to send file transfer initialization message\\n\", tc->fd);\n fclose(req_file);\n return -1;\n }\n memset(header, 0, TCP_PACKET_HEADER_SIZE);\n\n // send raw linklist file\n unsigned int bytes_transferred = 0;\n unsigned int loc = 0, col = 0;\n while (bytes_transferred < req_filesize) {\n loc = MIN(LINKLIST_MAX_FILENAME_SIZE, req_filesize-bytes_transferred);\n col = fread(buffer, 1, loc, req_file);\n if (loc != col) {\n linklist_err(\"::CLIENT %d:: file read error\\n\", tc->fd);\n return 0;\n } else {\n if (send(tc->fd, buffer, col, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"::CLIENT %d:: file transfer interrupted\\n\", tc->fd);\n fclose(req_file);\n return -1;\n }\n bytes_transferred += col;\n memset(buffer, 0, col);\n }\n\n }\n\n fclose(req_file);\n\n linklist_info(\"::CLIENT %d:: file transfer complete (%d bytes)\\n\", tc->fd, req_filesize);\n\n return 1;\n}\n\n\n// requests a file from the server\n// file is saved at DATAETC/filename\nuint32_t request_server_file(struct TCPCONN * tc, char * filename, unsigned int flags)\n{\n int sock = tc->fd;\n uint8_t buffer[LINKLIST_MAX_FILENAME_SIZE] = {0};\n uint8_t msg[TCP_PACKET_HEADER_SIZE] = {0};\n\n uint32_t *recv_ser, *recv_filesize;\n uint16_t *recv_i, *recv_n;\n uint32_t ll_serial;\n\n char savedname[LINKLIST_MAX_FILENAME_SIZE] = {0};\n snprintf(savedname, LINKLIST_MAX_FILENAME_SIZE, \"%s/%s\", \"/tmp\", filename);\n\n // linklist_info(\"Requesting file \\\"%s\\\" from server...\\n\",filename);\n\n // send request for file by name\n writeTCPHeader(buffer, SERVER_LL_REQ, strlen(filename), flags, 0);\n if (send(sock, buffer, TCP_PACKET_HEADER_SIZE, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"request_server_file: failed to send file request message\\n\");\n return 0;\n }\n if (send(sock, filename, strlen(filename), MSG_NOSIGNAL) <= 0) {\n linklist_err(\"request_server_file: failed to send filename\\n\");\n return 0;\n }\n\n // get file info before receiving\n if (recv(sock, msg, TCP_PACKET_HEADER_SIZE, MSG_WAITALL) <= 0) {\n linklist_err(\"request_server_file: failed to recv file stats\\n\");\n return 0;\n }\n readTCPHeader(msg, &recv_ser, &recv_filesize, &recv_i, &recv_n);\n ll_serial = ((*recv_n)<<16) + (*recv_i);\n\n if (*recv_ser != SERVER_LL_REQ) { // handle error messages\n linklist_err(\"request_server_file: file \\\"%s\\\" not on server\\n\",filename);\n return *recv_ser;\n }\n\n // receive the file and write it to disk\n FILE * f = fopen(savedname,\"wb\");\n\n unsigned int bytes_recvd = 0;\n unsigned int loc = 0;\n while (bytes_recvd < *recv_filesize) {\n loc = MIN(LINKLIST_MAX_FILENAME_SIZE,(*recv_filesize)-bytes_recvd);\n if (recv(sock, buffer, loc, MSG_WAITALL) <= 0) {\n linklist_err(\"request_server_file: failed to recv file block\\n\");\n return 0;\n }\n fwrite(buffer,1,loc,f);\n bytes_recvd += loc;\n memset(buffer,0,loc);\n }\n fflush(f);\n fclose(f);\n\n //linklist_info(\"Received file \\\"%s\\\" from server (size %d)\\n\",filename,*recv_filesize);\n\n return ll_serial;\n}\n\n// initialize server connection with time and framenum info based on a linklist serial\nint64_t initialize_client_connection(struct TCPCONN * tc, uint32_t serial)\n{\n // initialize connection if not done so already\n while (tc->fd <= 0) {\n tc->fd = connect_tcp(tc);\n sleep(1);\n }\n\n uint32_t * recv_frame_num = 0;\n uint16_t * recv_i = 0, * recv_n = 0;\n uint32_t * recv_ser;\n uint8_t request_msg[TCP_PACKET_HEADER_SIZE] = {0};\n\n // initialization with serial\n writeTCPHeader(request_msg, serial, 0, TCPCONN_CLIENT_INIT, 0);\n if (send(tc->fd, request_msg, TCP_PACKET_HEADER_SIZE, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"Failed to send initialization message\\n\");\n close_connection(tc);\n tc->fd = connect_tcp(tc);\n return -1;\n }\n\n if (recv(tc->fd, request_msg, TCP_PACKET_HEADER_SIZE, MSG_WAITALL) <= 0) {\n linklist_err(\"Failed to receive initalization message\\n\");\n close_connection(tc);\n tc->fd = connect_tcp(tc);\n return -1;\n }\n readTCPHeader(request_msg, &recv_ser, &recv_frame_num, &recv_i, &recv_n);\n \n tc->theday = *recv_i;\n tc->themonth = ((*recv_n-1)%12)+1;\n tc->theyear = (*recv_n-1)/12;\n \n tc->serial = *recv_ser;\n\n return *recv_frame_num;\n}\n\nvoid request_server_linklist_name(struct TCPCONN * tc, char * linklistname, unsigned int len, unsigned int flags)\n{\n // initiate server connection if not done already\n while (tc->fd <= 0) {\n tc->fd = connect_tcp(tc);\n sleep(1);\n }\n\n uint8_t request_msg[TCP_PACKET_HEADER_SIZE] = {0};\n uint32_t *recv_serial = NULL;\n uint32_t *recv_frame_num = NULL;\n uint16_t *recv_i = NULL;\n uint16_t *recv_n = NULL;\n\n // request file list from server\n writeTCPHeader(request_msg, SERVER_LL_NAME_REQ, len-1, flags, 0);\n if (send(tc->fd, request_msg, TCP_PACKET_HEADER_SIZE, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"Failed to send link name request\\n\");\n close_connection(tc);\n tc->fd = connect_tcp(tc);\n }\n\n // receive the name\n if (recv(tc->fd, request_msg, TCP_PACKET_HEADER_SIZE, MSG_WAITALL) <= 0) {\n linklist_err(\"Failed to receive archive name header\\n\");\n close_connection(tc);\n tc->fd = connect_tcp(tc);\n return;\n }\n readTCPHeader(request_msg, &recv_serial, &recv_frame_num ,&recv_i,&recv_n);\n if (*recv_serial == SERVER_LL_NAME_REQ) {\n // recv name: *recv_frame_num is number of characters\n memset(linklistname, 0, len);\n if (*recv_frame_num > len) {\n linklist_err(\"Could not receive server linklist name of size %d for %d size buffer\\n\", *recv_frame_num, len);\n return;\n }\n int read_size = recv(tc->fd, linklistname, *recv_frame_num, 0);\n\n if (read_size <= 0) {\n linklist_err(\"Could not receive server linklist name\\n\");\n return;\n }\n } else {\n linklist_err(\"Improper response to linklist name request (0x%x)\\n\", *recv_serial);\n }\n}\n\n// manually sets the linklist name used by the server\nvoid set_server_linklist_name(struct TCPCONN * tc, char *linklistname)\n{\n // initiate server connection if not done already\n while (tc->fd <= 0) {\n tc->fd = connect_tcp(tc);\n sleep(1);\n }\n\n uint8_t request_msg[TCP_PACKET_HEADER_SIZE] = {0};\n\n // request file list from server\n writeTCPHeader(request_msg,SERVER_SET_LL_NAME_REQ,strlen(linklistname)+1,0,0);\n if (send(tc->fd, request_msg, TCP_PACKET_HEADER_SIZE, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"Failed to send link name select request\\n\");\n close_connection(tc);\n tc->fd = connect_tcp(tc);\n }\n if (send(tc->fd, linklistname, strlen(linklistname)+1, MSG_NOSIGNAL) <= 0)\n {\n linklist_err(\"Failed to send link name\\n\");\n close_connection(tc);\n tc->fd = connect_tcp(tc);\n }\n\n}\n\n// fills the name array with archived linklist names from the server\nint request_server_archive_list(struct TCPCONN * tc, char name[][LINKLIST_SHORT_FILENAME_SIZE])\n{\n // initiate server connection if not done already\n while (1) {\n tc->fd = connect_tcp(tc);\n\n uint8_t request_msg[TCP_PACKET_HEADER_SIZE] = {0};\n\n // request file list from server\n writeTCPHeader(request_msg,SERVER_ARCHIVE_LIST_REQ,0,0,0);\n if (send(tc->fd, request_msg, TCP_PACKET_HEADER_SIZE, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"Failed to send archive select request\\n\");\n close_connection(tc);\n if (tc->flag & TCPCONN_NOLOOP) return -1;\n continue;\n }\n\n uint16_t *recv_i, *recv_n;\n uint32_t *recv_ser, *recv_fn;\n\n while (1) {\n // receive name header\n if (recv(tc->fd,request_msg,TCP_PACKET_HEADER_SIZE,MSG_WAITALL) <= 0) {\n linklist_err(\"Failed to receive archive name header\\n\");\n\t\t\t\tif (tc->flag & TCPCONN_NOLOOP) return -1;\n break;\n }\n readTCPHeader(request_msg,&recv_ser,&recv_fn,&recv_i,&recv_n);\n\n // no files on server\n if (!(*recv_i) && !(*recv_n)) {\n linklist_err(\"No files avaiable on server %s\\n\", tc->ip);\n\t\t\t\tif (tc->flag & TCPCONN_NOLOOP) return -1;\n break;\n }\n\n if (*recv_fn > LINKLIST_SHORT_FILENAME_SIZE) {\n linklist_err(\"Cannot receive archive name of size %d for buffer size %d\\n\", *recv_fn, LINKLIST_SHORT_FILENAME_SIZE);\n return -1;\n }\n\n // receive name\n if (recv(tc->fd,name[*recv_i],*recv_fn,MSG_WAITALL) <= 0) {\n linklist_err(\"Failed to receive archive name\\n\");\n close_connection(tc);\n\tif (tc->flag & TCPCONN_NOLOOP) return -1;\n break; \n }\n\n // this is the end of the function\n if (((*recv_i)+1) >= *recv_n) {\n return *recv_n;\n }\n }\n\n // only get here if there was a conneciton problem\n close_connection(tc);\n linklist_err(\"Unable to connect to server\\n\");\n sleep(1);\n }\n\n // should never get here\n return 0;\n\n}\n\n// fills the name array with linklist names from the server\nint request_server_list(struct TCPCONN * tc, char name[][LINKLIST_SHORT_FILENAME_SIZE]) {\n // initiate server connection if not done already\n while (tc->fd <= 0)\n {\n tc->fd = connect_tcp(tc);\n sleep(1);\n }\n\n uint8_t request_msg[TCP_PACKET_HEADER_SIZE] = {0};\n\n // request file list from server\n writeTCPHeader(request_msg,SERVER_LL_LIST_REQ,0,0,0);\n if (send(tc->fd, request_msg, TCP_PACKET_HEADER_SIZE, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"Failed to send link select request\\n\");\n close_connection(tc);\n tc->fd = connect_tcp(tc);\n }\n\n uint16_t *recv_i, *recv_n;\n uint32_t *recv_ser, *recv_fn;\n\n\n while (1)\n {\n // receive name header\n if (recv(tc->fd,request_msg,TCP_PACKET_HEADER_SIZE,MSG_WAITALL) <= 0) {\n linklist_err(\"Failed to receive linklist name header\\n\");\n close_connection(tc);\n return 0;\n }\n readTCPHeader(request_msg,&recv_ser,&recv_fn,&recv_i,&recv_n);\n\n if (*recv_fn > LINKLIST_SHORT_FILENAME_SIZE) {\n linklist_err(\"Cannot receive archive name of size %d for buffer size %d\\n\", *recv_fn, LINKLIST_SHORT_FILENAME_SIZE);\n return 0;\n }\n\n // receive name\n if (recv(tc->fd,name[*recv_i],*recv_fn,0) <= 0) {\n linklist_err(\"Failed to receive linklist name\\n\");\n close_connection(tc);\n return 0;\n } \n\n if (*recv_n == ((*recv_i)+1)) break;\n\n }\n return *recv_n;\n}\n\n\n// requests data from the server\n// data is requested based on serial number and framenumber\n// returns the framenumber to be retrieved \nint request_data(struct TCPCONN *tc, unsigned int fn, uint16_t * flags) {\n uint8_t request_msg[TCP_PACKET_HEADER_SIZE] = {0}; \n int rsize = 0;\n\n uint32_t * recv_serial = NULL;\n uint32_t * recv_framenum = NULL;\n uint16_t * recv_i = NULL;\n uint16_t * recv_n = NULL;\n\n // request the next frame\n writeTCPHeader(request_msg, tc->serial, fn, 0, 0);\n if (send(tc->fd, request_msg, TCP_PACKET_HEADER_SIZE, MSG_NOSIGNAL) <= 0) {\n linklist_err(\"Server connection lost on send.\\n\");\n\t\tclose_connection(tc);\n\t\ttc->fd = connect_tcp(tc);\n return -1; // connection error\n }\n\n // receive header for the next frame\n if ((rsize = recv(tc->fd, request_msg, TCP_PACKET_HEADER_SIZE, MSG_WAITALL)) <= 0) {\n linklist_err(\"Server connection lost on recv.\\n\");\n\t\tclose_connection(tc);\n\t\ttc->fd = connect_tcp(tc);\n return -1; // connection error\n }\n readTCPHeader(request_msg, &recv_serial, &recv_framenum, &recv_i, &recv_n); \n \n // set the flags \n *flags = *recv_i;\n\n return *recv_framenum;\n}\n\n// retrieves data from the server and writes it to the specified buffer of size bufsize\n// data is requested based on serial number and framenumber\n// returns the number of retrieved bytes\nint retrieve_data(struct TCPCONN * tc, uint8_t * buffer, unsigned int bufsize)\n{\n int rsize = 0;\n\n // receive the next frame\n if ((rsize = recv(tc->fd, buffer, bufsize, MSG_WAITALL)) <= 0) {\n linklist_err(\"Server connection lost on recv.\\n\");\n close_connection(tc);\n tc->fd = connect_tcp(tc);\n return -1; // connection error\n }\n\n return rsize;\n}\n\n#ifdef __cplusplus\n}\n#endif\n" }, { "alpha_fraction": 0.6409574747085571, "alphanum_fraction": 0.6471630930900574, "avg_line_length": 20.485713958740234, "blob_id": "ac4cb494797d704473526bb13681200f32d597ca", "content_id": "17e8adcb390e97dafda323125614ce23ffec752d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2257, "license_type": "no_license", "max_line_length": 92, "num_lines": 105, "path": "/stars/code/tools/timing.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef TOOLS__TIMING_H\n#define TOOLS__TIMING_H\n\n#include \"windows_header.h\"\n#ifndef _MSC_VER\n #include <sys/time.h>\n#endif\n#include <boost/thread/thread_time.hpp>\n#include <limits>\n#include <string>\n\nnamespace Tools\n{\n class Timer;\n boost::system_time relative_time(double seconds);\n}\n\nnamespace Time\n{\n double to_years(double time);\n double from_years(double time);\n double to_days(double time);\n double from_days(double time);\n double to_hours(double time);\n double from_hours(double time);\n double to_minutes(double time);\n double from_minutes(double time);\n double to_seconds(double time);\n double from_seconds(double time);\n double to_milliseconds(double time);\n double from_milliseconds(double time);\n std::string time_string(double time);\n}\n\n#ifdef _MSC_VER\nvoid usleep(int useconds);\n#endif\n\n\nclass Tools::Timer\n{\n public:\n Timer();\n void start();\n double time() const;\n bool started();\n void reset();\n Timer& operator=(const Timer &rhs);\n\n private:\n #if defined(_MSC_VER)\n LARGE_INTEGER m_depart;\n #else\n timeval m_depart;\n #endif\n bool started_;\n};\n\n#if defined(_MSC_VER)\ninline void Tools::Timer::start()\n{\n started_ = true;\n QueryPerformanceCounter(&m_depart);\n}\ninline double Tools::Timer::time() const\n{\n if (started_) {\n LARGE_INTEGER now;\n LARGE_INTEGER freq;\n QueryPerformanceCounter(&now);\n QueryPerformanceFrequency(&freq);\n return (now.QuadPart - m_depart.QuadPart) / static_cast<double>(freq.QuadPart);\n }\n else {\n return std::numeric_limits<double>::infinity();\n }\n}\n#else\ninline void Tools::Timer::start()\n{\n started_ = true;\n gettimeofday(&m_depart, 0);\n}\ninline double Tools::Timer::time() const\n{\n if (started_) {\n timeval now;\n gettimeofday(&now, 0);\n return now.tv_sec - m_depart.tv_sec + (now.tv_usec - m_depart.tv_usec) / 1000000.0f;\n }\n else {\n return std::numeric_limits<double>::infinity();\n }\n}\n#endif\n\n\n#endif\n" }, { "alpha_fraction": 0.6758150458335876, "alphanum_fraction": 0.682634711265564, "avg_line_length": 39.073333740234375, "blob_id": "7238e0cfb5b32d560b2f2ca0e90b4b39c62d772a", "content_id": "d36e6b8dcb2971e405c569dec812939a794a46ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6013, "license_type": "no_license", "max_line_length": 112, "num_lines": 150, "path": "/stars/code/displaying/solving_filters.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"solving_filters.h\"\n#include \"../tools/angles.h\"\n#include \"../shared/solving/filters.h\"\n\nusing namespace Displaying;\n\n#define shared_filters (*(Shared::Solving::filters_net_to_main.r))\n\nSolvingFilters::SolvingFilters()\n{\n change_size(630, 140);\n\n Color color = Color(0.0, 1.0, 0.0, 1.0);\n\n horizontal_location_enabled.init(\"ho\");\n horizontal_location_radius.init(\"ho_rad\");\n horizontal_location_az.init(\"ho_az\");\n horizontal_location_el.init(\"ho_el\");\n horizontal_roll_limit_enabled.init(\"hroll\");\n horizontal_roll_limit_min.init(\"hroll_min\");\n horizontal_roll_limit_max.init(\"hroll_max\");\n horizontal_el_limit_enabled.init(\"el\");\n horizontal_el_limit_min.init(\"el_min\");\n horizontal_el_limit_max.init(\"el_max\");\n equatorial_location_enabled.init(\"eq\");\n equatorial_location_radius.init(\"eq_rad\");\n equatorial_location_ra.init(\"eq_ra\");\n equatorial_location_dec.init(\"eq_dec\");\n\n horizontal_location_enabled.color = color;\n horizontal_location_radius.color = color;\n horizontal_location_az.color = color;\n horizontal_location_el.color = color;\n equatorial_location_enabled.color = color;\n equatorial_location_radius.color = color;\n equatorial_location_ra.color = color;\n equatorial_location_dec.color = color;\n horizontal_roll_limit_enabled.color = color;\n horizontal_roll_limit_min.color = color;\n horizontal_roll_limit_max.color = color;\n horizontal_el_limit_enabled.color = color;\n horizontal_el_limit_min.color = color;\n horizontal_el_limit_max.color = color;\n}\n\nvoid SolvingFilters::update()\n{\n horizontal_location_enabled.known = false;\n horizontal_location_radius.known = false;\n horizontal_location_az.known = false;\n horizontal_location_el.known = false;\n if (shared_filters.horizontal_location.enabled) {\n horizontal_location_enabled.set_value(\"enabled\");\n horizontal_location_enabled.known = true;\n horizontal_location_radius.set_value(to_degrees(shared_filters.horizontal_location.radius), \"*\", 1);\n horizontal_location_radius.known = true;\n horizontal_location_az.set_value(to_degrees(shared_filters.horizontal_location.az), \"*\", 1);\n horizontal_location_az.known = true;\n horizontal_location_el.set_value(to_degrees(shared_filters.horizontal_location.el), \"*\", 1);\n horizontal_location_el.known = true;\n }\n horizontal_roll_limit_enabled.known = false;\n horizontal_roll_limit_min.known = false;\n horizontal_roll_limit_max.known = false;\n if (shared_filters.horizontal_roll_limit.enabled) {\n horizontal_roll_limit_enabled.set_value(\"enabled\");\n horizontal_roll_limit_enabled.known = true;\n horizontal_roll_limit_min.set_value(to_degrees(shared_filters.horizontal_roll_limit.min_roll), \"*\", 1);\n horizontal_roll_limit_min.known = true;\n horizontal_roll_limit_max.set_value(to_degrees(shared_filters.horizontal_roll_limit.max_roll), \"*\", 1);\n horizontal_roll_limit_max.known = true;\n }\n horizontal_el_limit_enabled.known = false;\n horizontal_el_limit_min.known = false;\n horizontal_el_limit_max.known = false;\n if (shared_filters.horizontal_elevation_limit.enabled) {\n horizontal_el_limit_enabled.set_value(\"enabled\");\n horizontal_el_limit_enabled.known = true;\n horizontal_el_limit_min.set_value(to_degrees(shared_filters.horizontal_elevation_limit.min_el), \"*\", 1);\n horizontal_el_limit_min.known = true;\n horizontal_el_limit_max.set_value(to_degrees(shared_filters.horizontal_elevation_limit.max_el), \"*\", 1);\n horizontal_el_limit_max.known = true;\n }\n equatorial_location_enabled.known = false;\n equatorial_location_radius.known = false;\n equatorial_location_ra.known = false;\n equatorial_location_dec.known = false;\n if (shared_filters.equatorial_location.enabled) {\n equatorial_location_enabled.set_value(\"enabled\");\n equatorial_location_enabled.known = true;\n equatorial_location_radius.set_value(to_degrees(shared_filters.equatorial_location.radius), \"*\", 1);\n equatorial_location_radius.known = true;\n equatorial_location_ra.set_value(to_degrees(shared_filters.equatorial_location.ra), \"*\", 1);\n equatorial_location_ra.known = true;\n equatorial_location_dec.set_value(to_degrees(shared_filters.equatorial_location.dec), \"*\", 1);\n equatorial_location_dec.known = true;\n }\n}\n\nvoid SolvingFilters::draw(Position& position)\n{\n update();\n\n begin_draw(position);\n draw_border();\n draw_title();\n\n Position pos = {padding + padding, height() - padding - text_height - 4};\n draw_value(horizontal_location_enabled, pos);\n pos.y -= text_height;\n draw_value(horizontal_location_radius, pos);\n pos.y -= text_height;\n draw_value(horizontal_location_az, pos);\n pos.y -= text_height;\n draw_value(horizontal_location_el, pos);\n\n pos.x += 160;\n pos.y = height() - padding - text_height - 4;\n draw_value(horizontal_roll_limit_enabled, pos);\n pos.y -= text_height;\n draw_value(horizontal_roll_limit_min, pos);\n pos.y -= text_height;\n draw_value(horizontal_roll_limit_max, pos);\n\n pos.x += 160;\n pos.y = height() - padding - text_height - 4;\n draw_value(horizontal_el_limit_enabled, pos);\n pos.y -= text_height;\n draw_value(horizontal_el_limit_min, pos);\n pos.y -= text_height;\n draw_value(horizontal_el_limit_max, pos);\n\n pos.x += 160;\n pos.y = height() - padding - text_height - 4;\n draw_value(equatorial_location_enabled, pos);\n pos.y -= text_height;\n draw_value(equatorial_location_radius, pos);\n pos.y -= text_height;\n draw_value(equatorial_location_ra, pos);\n pos.y -= text_height;\n draw_value(equatorial_location_dec, pos);\n\n end_draw();\n}\n\n" }, { "alpha_fraction": 0.6064374446868896, "alphanum_fraction": 0.6196049451828003, "avg_line_length": 24.296297073364258, "blob_id": "c636469182e01576951ff4f2884702d6231f0772", "content_id": "17341806cd2f8b6c68c390711ff58d88aac6444a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1368, "license_type": "no_license", "max_line_length": 73, "num_lines": 54, "path": "/stars/code/shared/image/stats.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"stats.h\"\n\nusing namespace Shared::Image;\n\nStats::Stats()\n{\n counter_stars = -1;\n mean_known = false;\n mean = 0.0;\n noise_known = false;\n noise = 1.0;\n gain_known = false;\n gain = 24.4;\n gaindb = 0.0;\n num_pixels_saturated = 0;\n fraction_pixels_saturated = 0;\n autofocus_metric_valid = false;\n autofocus_metric = 0.0;\n}\n\nStats& Stats::operator=(const Stats &rhs)\n{\n if (this != &rhs) {\n counter_stars = rhs.counter_stars;\n mean = rhs.mean;\n mean_known = rhs.mean_known;\n mean = rhs.mean;\n noise_known = rhs.noise_known;\n noise = rhs.noise;\n gain_known = rhs.gain_known;\n gain = rhs.gain;\n gaindb = rhs.gaindb;\n num_pixels_saturated = rhs.num_pixels_saturated;\n fraction_pixels_saturated = rhs.fraction_pixels_saturated;\n autofocus_metric_valid = rhs.autofocus_metric_valid;\n autofocus_metric = rhs.autofocus_metric;\n }\n return *this;\n}\n\nvoid Stats::clear(int counter_stars_)\n{\n counter_stars = counter_stars_;\n mean_known = false;\n noise_known = false;\n gain_known = false;\n autofocus_metric_valid = false;\n}\n\n" }, { "alpha_fraction": 0.6728395223617554, "alphanum_fraction": 0.6913580298423767, "avg_line_length": 17, "blob_id": "9efa1f93161ddfd19137d22a9fa23acfc51dca6e", "content_id": "7072f283566704b706002532273a14e20418213f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 162, "license_type": "no_license", "max_line_length": 38, "num_lines": 9, "path": "/mccview/Makefile", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "CC=gcc\nLDFLAGS=-lgetdata -lncurses\nCFLAGS=-Wall\n\nmccview: mccview.c\n\t${CC} ${CFLAGS} -o $@ $< ${LDFLAGS}\n\ninstall: mccview\n\tinstall -m 755 mccview /usr/local/bin\n" }, { "alpha_fraction": 0.6643059253692627, "alphanum_fraction": 0.6699716448783875, "avg_line_length": 16.649999618530273, "blob_id": "c28c50616aa718775b50bfac23fa7a7af9f2b7a6", "content_id": "d210c57cb2d6543b86707b2e361e21838a3535c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 707, "license_type": "no_license", "max_line_length": 73, "num_lines": 40, "path": "/stars/code/shared/image/leveled.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__IMAGE__LEVELED_H\n#define SHARED__IMAGE__LEVELED_H\n\n#include \"../circular_buffer.h\"\n\nnamespace Shared\n{\n namespace Image\n {\n\nclass Leveled\n{\n public:\n Leveled();\n void init(Parameters::Manager& params);\n ~Leveled();\n Leveled& operator=(const Leveled& rhs);\n\n int image_width;\n int image_height;\n char* pixels;\n bool valid;\n int counter_stars;\n};\n\n// writes: solver\n// reads: main\nextern Shared::CircularBuffer <Leveled> leveled;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.6912442445755005, "alphanum_fraction": 0.7096773982048035, "avg_line_length": 29.714284896850586, "blob_id": "0baba69f7b62a04778226891a3eefc6c3d4f2e47", "content_id": "c4f2474c77425de8d41378b495a7ff2b70acdc66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 218, "license_type": "no_license", "max_line_length": 73, "num_lines": 7, "path": "/stars/code/tools/math.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"math.h\"\n\n\n" }, { "alpha_fraction": 0.5890721082687378, "alphanum_fraction": 0.6166695356369019, "avg_line_length": 27.407766342163086, "blob_id": "e5aa3e00d80e925c1630a519fdb2cf7ebd2afe83", "content_id": "29e0f5e34c7c234ec332e7d5f85720d947cca62b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 23408, "license_type": "no_license", "max_line_length": 157, "num_lines": 824, "path": "/starcam/blobimage.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <string>\n#include <sstream>\n#include <cstdio>\n#include <ctime>\n#include <climits>\n#include <sys/time.h>\n#include <sys/stat.h>\n#include \"blobimage.h\"\n#include \"csbigimg.h\"\n#include \"frameblob.h\"\n#include \"bloblist.h\"\n#include \"pyramid.h\"\n\n#include <iostream>\n#include <fstream>\n#include <time.h>\n#include <unistd.h>\n\n#define BLOB_IMAGE_DEBUG 0\n#if BLOB_IMAGE_DEBUG\n#include <iostream>\n#endif\n\nusing namespace std;\n\n/*\n\n BlobImage:\n \n Default constructor: sets all parameters to a default value.\n \n*/\nBlobImage::BlobImage(BlobImageConfigParams params /*=defaultImageParams*/)\n#if USE_PYRAMID\t\n\t: m_cPyramid(params.pyrParams.fov, params.pyrParams.catalogname, params.pyrParams.katalogname)\n#endif\n{\n\tInit(params);\n}\n\n/*\n\n BlobImage:\n \n Alternate constructor: sets all parameters to a default value and allocated image buffer\n \n*/\nBlobImage::BlobImage(int height, int width, BlobImageConfigParams params /*=defaultImageParams*/)\n#if USE_PYRAMID\t\n\t: m_cPyramid(params.pyrParams.fov, params.pyrParams.catalogname, params.pyrParams.katalogname)\n#endif\n{\n\tInit(params);\n\tAllocateImageBuffer(height, width);\n}\n\n/*\n\n ~BlobImage:\n \n Destructor: clears image data\n \n*/\nBlobImage::~BlobImage()\n{\n\tDeleteImageData();\n}\n\n/*\n\n Init:\n \n Sets all inherited and member parameters to a default value.\n \n*/\nvoid BlobImage::Init(BlobImageConfigParams params/*=defaultImageParams*/)\n{\n#if BLOB_IMAGE_DEBUG\n\tcout << \"[Blob image debug]: in Init method...\" << endl;\n#endif\n\tCSBIGImg::Init(params.SBIGParams);\n\tm_cBlob.commonconstructor(params.blobParams);\n\tm_sBadpixFilename = params.badpixFilename;\n\tm_nTimeError = params.timeError;\n\n#if USE_PYRAMID\t\n\t//m_cPyramid.Init(params.pyrParams.fov, params.pyrParams.catalogname, params.pyrParams.katalogname);\n\t//cout << \"erase me: left Init for Pyramid\" << endl;\n\tm_dMatchTol = params.matchTol;\n\tm_dPlatescale = params.platescale;\n#endif\n}\n/* original version has been replaced\nvoid BlobImage::Init(void)\n{\n\tCSBIGImg::Init(); //perform all initialization of inherited members\n\tm_sBadpixFilename = \"\";\n}\n*/\n\n/*\n\n InitFrameblob:\n \n Sets all frameblob parameters to a default value to enable blob finding\n \n*/\n/* this function is no longer needed\nvoid BlobImage::InitFrameblob()\n{\n\tm_cBlob.commonconstructor((MAPTYPE*)CSBIGImg::GetImagePointer(), CSBIGImg::GetWidth(),\n\t\t\t\t\t\t\t CSBIGImg::GetHeight(), 16, (double)9.3/60/60);\n\tm_cBlob.set_gain(1.0/1.48); //in units/e-\n\tm_cBlob.set_readout_offset(100); //in units/pixel\n\tm_cBlob.set_readout_noise(13.8 / 1.48); //this is in units/pixel\n\tm_cBlob.set_satval((MAPTYPE)65534);\n\tm_cBlob.set_threshold(5);\n\tm_cBlob.set_disttol(30*30);\n\tm_cBlob.set_grid(30);\n\tm_cBlob.set_maxblobs(99); //set mostly to save space in the image note\n}\n*/\n\n/*\n\n AllocateImageBuffer:\n \n Overide method in CSBIGImg to keep frameblob information current\n \n*/\nMY_LOGICAL BlobImage::AllocateImageBuffer(int height, int width)\n{\n#if BLOB_IMAGE_DEBUG\n\tcout << \"[Blob image debug]: in AllocateImageBuffer method with \" \n\t\t << width << \"x\" << height << endl;\n#endif\n\tif (!CSBIGImg::AllocateImageBuffer(height, width))\n\t\treturn FALSE;\n\tm_cBlob.set_map(CSBIGImg::GetImagePointer(), height, width);\t\n\tm_bIsChanged = true;\n\treturn TRUE;\n}\n\n/*\n\n DeleteImageData:\n \n Overide method in CSBIGImg to keep frameblob information current\n \n*/\nvoid BlobImage::DeleteImageData()\n{\n#if BLOB_IMAGE_DEBUG\n\tcout << \"[Blob image debug]: in DeleteImageData method...\" << endl;\n#endif\n\tCSBIGImg::DeleteImageData();\n\tm_cBlob.set_map(NULL, 0, 0);\n}\n\n/*\n OpenImage:\n\n Overide parent method to use correct buffer allocation\n\n*/\nSBIG_FILE_ERROR BlobImage::OpenImage(const char *pFullPath)\n{\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\tchar\t\t\theader[HEADER_LEN];\n\tFILE\t\t\t*fh;\n\tSBIG_FILE_ERROR res;\n\tMY_LOGICAL\t\tisCompressed;\n\t/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n#if BLOB_IMAGE_DEBUG\n\tcout << \"[Blob image debug]: in OpenImage method...\" << endl;\n#endif\n\n\tif ((fh = fopen(pFullPath, \"rb\")) == NULL)\n\t\treturn SBFE_OPEN_ERROR;\n\telse {\n\t\tdo {\t// allow break out\n\t\t\t// read and pars header\n\t\t\tres = SBFE_FORMAT_ERROR;\n\t\t\tif (fread(header, 1, HEADER_LEN, fh) != HEADER_LEN)\n\t\t\t\tbreak;\n\t\t\tif (!CSBIGImg::ParseHeader(header, isCompressed))\n\t\t\t\tbreak;\n\n\t\t\t// allocate image buffer\n\t\t\tres = SBFE_MEMORY_ERROR;\n\t\t\tif (!AllocateImageBuffer(CSBIGImg::GetHeight(), CSBIGImg::GetWidth()))\n\t\t\t\tbreak;\n\t\t\tif (isCompressed)\n\t\t\t\tres = CSBIGImg::ReadCompressedImage(fh);\n\t\t\telse\n\t\t\t\tres = CSBIGImg::ReadUncompressedImage(fh);\n\t\t\tif (res != SBFE_NO_ERROR) {\n\t\t\t\tCSBIGImg::DeleteImageData();\n\t\t\t}\n\t\t} while (FALSE);\n\t}\n\n\tfclose(fh);\n\tif (res == SBFE_NO_ERROR) {\n\t\tCSBIGImg::SetImageModified(FALSE);\n\t\tCSBIGImg::SetDefaultImageForamt(isCompressed ? SBIF_COMPRESSED : SBIF_UNCOMPRESSED);\n\t}\n\n\tm_bIsChanged = true;\n\treturn res;\n}\n\n/*\n\n SetImageStartTime:\n \n Overrides parent method to supply more precision\n Sets the image start time to the current system time\n\n*/\nvoid BlobImage::SetImageStartTime(void)\n{\n\tgettimeofday(&m_sImageStartTime, NULL);\n\tCSBIGImg::SetImageStartTime(m_sImageStartTime.tv_sec); //set less precise time stored in parent\n}\n\n/*\n\n SetImageStartTime:\n \n same as above method, but also uses ref (found before exposure) to estimate time error\n of course, ref should refer to a time before the call to this function\n\n*/\nvoid BlobImage::SetImageStartTime(timeval* ref)\n{\n\tgettimeofday(&m_sImageStartTime, NULL);\n\tCSBIGImg::SetImageStartTime(m_sImageStartTime.tv_sec); //set less precise time stored in parent\n\tm_nTimeError = m_sImageStartTime.tv_sec - ref->tv_sec;\n\tm_nTimeError *= 1000000;\n\tm_nTimeError += m_sImageStartTime.tv_usec - ref->tv_usec;\n\t\n\t//set the image note to indicate time of exposure\n\tostringstream sout; //will contain the image note\n\tsout << \"UNIX time: \" << m_sImageStartTime.tv_sec << \"s \" << m_sImageStartTime.tv_usec\n\t\t << \"us\" << \" err <= \" << m_nTimeError << \"us\";\n\tCSBIGImg::SetImageNote(sout.str());\n}\n\n\n/*\n\n copyImageFrom:\n \n copies image (it better be the right size) from data array\n should be stored as single row-by-row array\n \n*/\nvoid BlobImage::copyImageFrom(const unsigned short* data) {\n unsigned short* img = this->GetImagePointer();\n for (int i=0; i<this->GetHeight()*this->GetWidth(); i++) {\n img[i] = data[i];\n }\n}\n\n/*\n\n setBadpixFilename:\n \n sets bad pixel filename based on C-style string\n \n*/\nvoid BlobImage::setBadpixFilename(const char* name)\n{\n\tstring name_str = name;\n\tsetBadpixFilename(name_str);\n}\n\n/*\n\n FixBadpix:\n \n Loads file of badpixels and sets their value to the map mean.\n to disable bad pixel checking, send filename \"\"\n Returns an error when loading the file fails.\n If a file of the same name is already loaded, will not load it again\n*/\nSBIG_FILE_ERROR BlobImage::FixBadpix(string filename)\n{\n#if BLOB_IMAGE_DEBUG\n\tcout << \"[Blob image debug]: in FixBadPix with: \\\"\" << filename << \"\\\"\" \n\t << \" old name \\\"\" << m_sBadpixFilename << \"\\\"\" << endl;\n#endif\n\tif (filename == \"\") {\n\t\tm_sBadpixFilename = filename;\n\t\treturn SBFE_NO_ERROR;\n\t}\n\tif (m_sBadpixFilename != filename) { //don't load file if it's same as before\n\t\tif (m_cBlob.load_badpix(filename.c_str()) < 0) {\n\t\t\treturn SBFE_OPEN_ERROR;\n\t\t}\n\t\tm_sBadpixFilename = filename;\n\t}\n\tm_cBlob.calc_mapstat();\n\tm_cBlob.fix_badpix((MAPTYPE)m_cBlob.get_mapmean());\n\treturn SBFE_NO_ERROR;\n}\n\n/*\n\n findBlobs:\n \n uses frameblob to find the blobs in the image\n sets the image note to summarize results\n returns number of blobs found or -1 on error\n \n*/\nint BlobImage::findBlobs()\n{\n#if BLOB_IMAGE_DEBUG\n\tcout << \"[Blob image debug]: in findBlobs method...\" << endl;\n#endif\n\n\tstring note = \"\";\n\tostringstream sout;\n\tint numblobs;\n\tbloblist *blobs;\n\t\n\t//crapifyImage();\n\t//find the blobs\n\tif (FixBadpix(m_sBadpixFilename) == SBFE_OPEN_ERROR)\n\t\treturn -1;\n\thighPassFilter(15,3); \n#if BLOB_IMAGE_DEBUG\n\tcout << \"[Blob image debug]: running calc_mapstat method...\" << endl;\n#endif\n\tm_cBlob.calc_mapstat();\n#if BLOB_IMAGE_DEBUG\n\tcout << \"[Blob image debug]: running calc_searchgrid method...\" << endl;\n#endif\n\tm_cBlob.calc_searchgrid();\n\tm_cBlob.fix_multiple();\n\tm_cBlob.sortblobs();\n\t\n\tnumblobs = m_cBlob.get_numblobs();\n\tblobs = m_cBlob.getblobs();\n\n\treturn numblobs;\n}\n\n/*\n crapifyImage:\n\n adds another image's value for each pixel to the current image\n\n*/\n\n\nint BlobImage::crapifyImage()\n{\n\tconst char* filename[14];\n\tfilename[0] = \"/home/spider/starcam/sbsc/13:01:41.sbig\";\n\tfilename[1] = \"/home/spider/starcam/sbsc/13:05:53.sbig\";\n\tfilename[2] = \"/home/spider/starcam/sbsc/13:10:31.sbig\";\n\tfilename[3] = \"/home/spider/starcam/sbsc/13:14:48.sbig\";\n\tfilename[4] = \"/home/spider/starcam/sbsc/13:19:20.sbig\";\n\tfilename[5] = \"/home/spider/starcam/sbsc/13:23:38.sbig\";\n\tfilename[6] = \"/home/spider/starcam/sbsc/13:27:53.sbig\";\n\tfilename[7] = \"/home/spider/starcam/sbsc/13:32:19.sbig\";\n\tfilename[8] = \"/home/spider/starcam/sbsc/13:36:30.sbig\";\n\tfilename[9] = \"/home/spider/starcam/sbsc/13:40:59.sbig\";\n\tfilename[10] = \"/home/spider/starcam/sbsc/13:45:25.sbig\";\n\tfilename[11] = \"/home/spider/starcam/sbsc/13:49:40.sbig\";\n\tfilename[12] = \"/home/spider/starcam/sbsc/13:54:03.sbig\";\n\tfilename[13] = \"/home/spider/starcam/sbsc/13:58:29.sbig\";\n\tint randi = rand()%13;\n\tBlobImage* sbscimg = new BlobImage();\n \tif (sbscimg->OpenImage(filename[randi]) != SBFE_NO_ERROR) {\n \t\tcerr << \"Error opening image: \" << filename[randi] << endl;\n \t\treturn 1;\n \t} else cout << \"Opening image: \" << filename[randi] << endl;\n \tunsigned short *img = this->GetImagePointer();\n \t/*unsigned NNG*/ int height = this->GetHeight();\n \t/*unsigned NNG*/ int width = this->GetWidth();\n \tunsigned short *crapimg = sbscimg->GetImagePointer();\n\tfor (int x=0; x<width; x++) {\n\t\tfor (int y=0; y<height; y++) {\n\t\t\timg[x+width*y]+=crapimg[x+width*y];\n\t\t}\n\t}\t\t\t\n\tdelete sbscimg;\n\treturn 1;\n}\n\n/*\n\n highPassFilter:\n\n simple (and hopefully quick, good enough) high pass filter\n operates on sqaure regions box_size on side\n averages a region n_boxes boxes on a side, and subtracts mean from central box\n probably best if box_size evenly divides image dimensions, and n_boxes is odd\n\n*/\n#include <iostream>\nusing namespace std;\nint BlobImage::highPassFilter(int box_size, int n_boxes)\n{\n#if BLOB_IMAGE_DEBUG\n\tcout << \"[Blob image debug]: in highPassFilter...\" << endl;\n#endif\n unsigned short *img = this->GetImagePointer();\n unsigned int height = this->GetHeight();\n unsigned int width = this->GetWidth();\n\n //coarse image, binned in box_size chunks\n unsigned short* c_img;\n unsigned int c_height, c_width;\n c_height = (unsigned int)ceil((double)height/(double)box_size);\n c_width = (unsigned int)ceil((double)width/(double)box_size);\n c_img = new unsigned short[c_height*c_width];\n\n //create the coarse image\n for (unsigned int c_x=0; c_x<c_width; c_x++) {\n for (unsigned int c_y=0; c_y<c_height; c_y++) {\n unsigned int sum = 0;\n unsigned int npix = 0;\n for (unsigned int x=c_x*box_size; x<(c_x+1)*(box_size); x++) {\n\tfor (unsigned int y=c_y*box_size; y<(c_y+1)*(box_size); y++) {\n\t if (x < width && y < height) {\n\t sum += img[x+y*width];\n\t npix++;\n\t }\n\t}\n }\n c_img[c_x+c_y*c_width] = (unsigned short)round((double)sum/(double)npix);\n }\n }\n \n //calculate average in n_boxes sided square around coarse pixel\n unsigned short* to_subtract;\n to_subtract = new unsigned short[c_height*c_width];\n unsigned short to_subtract_max = 0;\n for (unsigned int c_x=0; c_x<c_width; c_x++) {\n for (unsigned int c_y=0; c_y<c_height; c_y++) {\n unsigned int sum = 0;\n unsigned int npix = 0;\n unsigned short max = 0;\n\n for (int avg_x=(int)c_x-n_boxes/2; avg_x<=(int)c_x+n_boxes/2; avg_x++) {\n\tfor (int avg_y=(int)c_y-n_boxes/2; avg_y<=(int)c_y+n_boxes/2; avg_y++) {\n\t if (avg_x >= 0 && avg_x < (int)c_width && avg_y >= 0 && avg_y < (int)c_height) {\n\t unsigned short datum = c_img[avg_x + avg_y*c_width];\n\t if (datum > max) max = datum;\n\t sum += datum;\n\t npix++;\n\t }\n\t}\n }\n sum -= max; //remove brightest pixel from average\n npix--;\n unsigned short mean = (unsigned short)round((double)sum/(double)npix);\n to_subtract[c_x+c_y*c_width] = mean;\n if (mean > to_subtract_max) to_subtract_max = mean;\n }\n }\n \n //subtract the to_subtract means from the full-res image\n //also add to_subtract_max to each pixel to prevent underflow\n for (unsigned int c_x=0; c_x<c_width; c_x++) {\n for (unsigned int c_y=0; c_y<c_height; c_y++) {\n for (unsigned int x=c_x*box_size; x<(c_x+1)*(box_size); x++) {\n\tfor (unsigned int y=c_y*box_size; y<(c_y+1)*(box_size); y++) {\n\t if (x < width && y < height) {\n\t if (USHRT_MAX - img[x+y*width] < to_subtract_max - to_subtract[c_x+c_y*c_width])\n\t img[x+y*width] = USHRT_MAX;\n\t else img[x+y*width] += to_subtract_max - to_subtract[c_x+c_y*c_width];\n\t }\n\t}\n }\n }\n }\n\n delete [] c_img;\n return 1;\n}\n\n/*\n\n drawBox:\n \n draws a white square of dimension side around the point x, y\n when willChange is true, sets the images changed flag\n \n*/\nvoid BlobImage::drawBox(double x, double y, double side, int bnum, bool willChange /*=true*/)\n{\n#if BLOB_IMAGE_DEBUG\n\tcout << \"[Blob image debug]: In drawBox method.\" << endl;\n#endif\n\tMAPTYPE* map = CSBIGImg::GetImagePointer();\n\t//rather than using saturation, try just background + range\n\t//MAPTYPE sat = m_cBlob.get_satval();\n\tthis->AutoBackgroundAndRange();\n\tMAPTYPE sat = this->GetBackground() + this->GetRange();\n\tint i,j;\n\tint top = (int)(y - side/2), left = (int)(x - side/2), size = (int)side;\n\tint xdim = CSBIGImg::GetWidth(), ydim = CSBIGImg::GetHeight();\n\tint xlimit = left + size, ylimit = top + size;\n\tint first = bnum/10;\n\tint second = bnum%10;\n\tif (top < 0) top = 0;\n\tif (left < 0) left = 0;\n\tif (xlimit > xdim) xlimit = xdim;\n\tif (ylimit > ydim) ylimit = ydim;\n#if BLOB_IMAGE_DEBUG\n\tcout << \"[Blob image debug]: entering loop for: \" << top << \" < y < \" << ylimit << \" and \" \n \t\t << left << \" < x < \" << xlimit << endl;\n#endif\n\tfor (i=top; i<ylimit; i++) { //row\n\t\tfor (j=left; j<xlimit; j++) { //column\n\t\t\tif (i == top || i == (top+1) || i == (ylimit-2) || i == (ylimit-1) || \n\t\t\t j == left || j == (left+1) || j == (xlimit-2) || j == (xlimit-1)) //on edge of box\n\t\t\t\tmap[i*xdim+j] = sat;\n\t\t}\n\t}\n\tint xnum,ynum;\n\t//Draw the blob number next to the box-----------\n\tif ((first == 4) || (first == 5) || (first == 6) || (first == 8) || (first == 9)) {\n\t for (i=0; i<18; i++) {\n\t\tfor (j=0; j<6; j++) {\n\t\t\txnum = ((xlimit+2+j)>xdim) ? xdim : (xlimit+2+j);\t\n\t\t\tynum = ((top+i) > ydim) ? ydim : (top+i);\n\t\t\tmap[ynum*xdim+xnum] = sat; //left vertical top\n\t\t}\n\t }\n\t}\n\tif ((first == 2) || (first == 6) || (first == 8)) {\n\t for (i=12; i<29; i++) { \n\t\tfor (j=0; j<6; j++) {\n\t\t\txnum = ((xlimit+2+j)>xdim) ? xdim : (xlimit+2+j);\t\n\t\t\tynum = ((top+i) > ydim) ? ydim : (top+i);\t\n\t\t\tmap[ynum*xdim+xnum] = sat; //left vertical bottom\n\t\t}\n\t }\n\t}\n\tif ((first == 1) || (first == 2) || (first == 3) || (first == 4) || (first == 7) || (first == 8) || (first == 9)) {\n\t for (i=0; i<18; i++) {\n\t\tfor (j=0; j<6; j++) {\n\t\t\txnum = ((xlimit+14+j)>xdim) ? xdim : (xlimit+14+j);\t\n\t\t\tynum = ((top+i) > ydim) ? ydim : (top+i);\t\n\t\t\tmap[ynum*xdim+xnum] = sat; //right vertical top\n\t\t}\n\t }\n\t}\n\tif ((first == 1) || (first == 3) || (first == 4) || (first == 5) || (first == 6) || (first == 7) || (first == 8) || (first == 9)) {\n\t for (i=12; i<29; i++) { \n\t\tfor (j=0; j<6; j++) {\n\t\t\txnum = ((xlimit+14+j)>xdim) ? xdim : (xlimit+14+j);\t\n\t\t\tynum = ((top+i) > ydim) ? ydim : (top+i);\t\n\t\t\tmap[ynum*xdim+xnum] = sat; //right vertical bottom\n\t\t}\n\t }\n\t}\n\tif ((first == 2) || (first == 3) || (first == 5) || (first == 7) || (first == 8) || (first == 9)) {\n\t for (i=0; i<18; i++) { \n\t\tfor (j=0; j<6; j++) {\n\t\t\txnum = ((xlimit+2+i) > xdim) ? xdim : (xlimit+2+i);\n\t\t\tynum = ((top+j)>ydim) ? ydim : (top+j);\n\t\t\tmap[ynum*xdim+xnum] = sat; //top horizontal\n\t\t}\n\t }\n\t}\n\tif ((first == 2) || (first == 3) || (first == 4) || (first == 5) || (first == 6) || (first == 8) || (first == 9)) {\t\n\t for (i=0; i<18; i++) {\n\t\tfor (j=0; j<6; j++) {\n\t\t\txnum = ((xlimit+2+i) > xdim) ? xdim : (xlimit+2+i);\n\t\t\tynum = ((top+12+j)>ydim) ? ydim : (top+12+j);\n\t\t\tmap[ynum*xdim+xnum] = sat; //middle horizontal\n\t\t}\n\t }\n\t}\n\tif ((first == 2) || (first == 3) || (first == 5) || (first == 6) || (first == 8)) {\n\t for (i=0; i<18; i++) {\n\t\tfor (j=0; j<6; j++) {\n\t\t\txnum = ((xlimit+2+i) > xdim) ? xdim : (xlimit+2+i);\n\t\t\tynum = ((top+24+j) > ydim) ? ydim : (top+24+j);\n\t\t\tmap[ynum*xdim+xnum] = sat; //bottom horizontal\n\t\t}\n\t }\n\t}\n if ((second == 0) || (second == 4) || (second == 5) || (second == 6) || (second == 8) || (second == 9)) {\n for (i=0; i<18; i++) { \n\t\tfor (j=0; j<6; j++) {\n\t\t\txnum = ((xlimit+26+j)>xdim) ? xdim : (xlimit+26+j);\n\t\t\tynum = ((top+i) > ydim) ? ydim : (top+i);\t\n\t\t\tmap[ynum*xdim+xnum] = sat; //left vertical top\n\t\t}\n\t }\n }\n\tif ((second == 0) || (second == 2) || (second == 6) || (second == 8)) {\n\t for (i=12; i<29; i++) {\n\t\tfor (j=0; j<6; j++) {\n\t\t\txnum = ((xlimit+26+j)>xdim) ? xdim : (xlimit+26+j);\n\t\t\tynum = ((top+i) > ydim) ? ydim : (top+i);\t\n\t\t\tmap[ynum*xdim+xnum] = sat; //left vertical bottom\n\t\t}\n\t }\n\t}\n\tif ((second == 0) || (second == 1) || (second == 2) || (second == 3) || (second == 4) || (second == 7) || (second == 8) || (second == 9)) {\n\t for (i=0; i<18; i++) {\n\t\tfor (j=0; j<6; j++) {\n\t\t\txnum = ((xlimit+38+j)>xdim) ? xdim : (xlimit+38+j);\n\t\t\tynum = ((top+i) > ydim) ? ydim : (top+i);\t\n\t\t\tmap[ynum*xdim+xnum] = sat; //right vertical top\n\t\t}\n\t }\n\t}\n\tif ((second == 0) || (second == 1) || (second == 3) || (second == 4) || (second == 5) || (second == 6) || (second == 7) || (second == 8) || (second == 9)) {\n\t for (i=12; i<29; i++) {\n\t\tfor (j=0; j<6; j++) {\n\t\t\txnum = ((xlimit+38+j)>xdim) ? xdim : (xlimit+38+j);\n\t\t\tynum = ((top+i) > ydim) ? ydim : (top+i);\t\n\t\t\tmap[ynum*xdim+xnum] = sat; //right vertical bottom\n\t\t}\n\t }\n\t}\n\tif ((second == 0) || (second == 2) || (second == 3) || (second == 5) || (second == 7) || (second == 8) || (second == 9)) {\n\t for (i=0; i<18; i++) { \n\t\tfor (j=0; j<6; j++) {\n\t\t\txnum = ((xlimit+26+i) > xdim) ? xdim : (xlimit+26+i);\n\t\t\tynum = ((top+j)>ydim) ? ydim : (top+j);\n\t\t\tmap[ynum*xdim+xnum] = sat; //top horizontal\n\t\t}\n\t }\n\t}\n\tif ((second == 2) || (second == 3) || (second == 4) || (second == 5) || (second == 6) || (second == 8) || (second == 9)) {\t\n\t for (i=0; i<18; i++) {\n\t\tfor (j=0; j<6; j++) {\n\t\t\txnum = ((xlimit+26+i) > xdim) ? xdim : (xlimit+26+i);\n\t\t\tynum = ((top+12+j)>ydim) ? ydim : (top+12+j);\n\t\t\tmap[ynum*xdim+xnum] = sat; //middle horizontal\n\t\t}\n\t }\n\t}\n\tif ((second == 0) || (second == 2) || (second == 3) || (second == 5) || (second == 6) || (second == 8)) {\n\t for (i=0; i<18; i++) {\n\t\tfor (j=0; j<6; j++) {\n\t\t\txnum = ((xlimit+26+i) > xdim) ? xdim : (xlimit+26+i);\n\t\t\tynum = ((top+24+j)>ydim) ? ydim : (top+24+j);\n\t\t\tmap[ynum*xdim+xnum] = sat; //bottom horizontal\n\t\t}\n\t }\n\t}\n\n\tif (willChange) m_bIsChanged = 1;\n}\n\n/*\n\n createFilename:\n \n makes a filename starting at the directory root based on time picture was taken\n if bloxflag is true will add /boxes/ to end of directory (for images with boxes around blobs)\n \n*/\nstring BlobImage::createFilename()\n{\n\tostringstream sout;\n\tstruct tm timestruct = CSBIGImg::GetImageStartTime();\n\t\n\tsout << ((timestruct.tm_hour<10)?\"0\":\"\") << timestruct.tm_hour << \":\"\n\t\t << ((timestruct.tm_min<10)?\"0\":\"\") << timestruct.tm_min << \":\"\n\t\t << ((timestruct.tm_sec<10)?\"0\":\"\") << timestruct.tm_sec << \".sbig\";\n\treturn sout.str();\n}\n\n/*\n\n createDirectory:\n \n creates the directory component of the filename used in createFilename\n \n*/\nstring BlobImage::createDirectory(string root, int boxflag)\n{\n\tostringstream sout;\n\tstruct tm timestruct = CSBIGImg::GetImageStartTime();\n\t\n\tsout << root << ((root[root.length()-1]=='/')?\"\":\"/\");\n\tsout << ((timestruct.tm_mday<10)?\"0\":\"\") << timestruct.tm_mday << \"-\" \n\t\t << ((timestruct.tm_mon<9)?\"0\":\"\") << timestruct.tm_mon + 1 << ((boxflag)?\"/boxes/\":\"/\");\n\treturn sout.str();\n}\n\n/*\n\n SaveImageIn:\n \n saves the image to a path based on the image time, root path, and boxes flag\n uses default format\n \n*/\nSBIG_FILE_ERROR BlobImage::SaveImageIn(string root/*=\"/data/rawdir\"*/, int boxflag/*=0*/)\n{\n#if BLOB_IMAGE_DEBUG\n\tcout << \"[Blob image debug]: In SaveImageIn method.\" << endl;\n#endif\n\tstring filename = createFilename();\n\tstring directory = createDirectory(root, boxflag);\n\tstring total = directory + filename;\n#if BLOB_IMAGE_DEBUG\n\tcout << \"[Blob image debug]: saving image as: \" << total << endl;\n#endif\n\tSBIG_FILE_ERROR err = CSBIGImg::SaveImage(total.c_str(), CSBIGImg::GetDefaultImageFormat());\n\tif (err == SBFE_OPEN_ERROR) { //problem opening file...try creating the directory\n#if BLOB_IMAGE_DEBUG\n\t\tcout << \"[Blob image debug]: error saving, trying to create directory\" << endl;\n#endif\n\t\tif (mkdir(directory.c_str(), 0777) < 0) {\n#if BLOB_IMAGE_DEBUG\n\t\t\tcout << \"[Blob image debug]: error creating directory\" << endl;\n#endif\n\t\t\treturn err;\n\t\t}\n\t\telse //try again if creating directory succeeds\n\t\t\treturn CSBIGImg::SaveImage(total.c_str(), CSBIGImg::GetDefaultImageFormat());\n\t}\n\telse return err;\n}\n\n/*\n\n createReturnStruct:\n \n populates a struct (pointer passed as arg) with return values for flight computer\n \n*/\n#include <iostream>\nStarcamReturn* BlobImage::createReturnStruct(StarcamReturn* arg)\n{\n\targ->frameNum = m_iFrame;\n\targ->mapmean = m_cBlob.get_mapmean();\n\targ->sigma = m_cBlob.get_sigma();\n\targ->exposuretime = CSBIGImg::GetExposureTime();\n\targ->imagestarttime = GetImageStartTime();\n\targ->camID = m_sCamID;\n\targ->ccdtemperature = CSBIGImg::GetCCDTemperature();\n\targ->focusposition = CSBIGImg::GetApertureArea();\n\t\n\t//blob info (on 15 brightest blobs)\n\targ->numblobs = m_cBlob.get_numblobs();\n\tbloblist *blobs = m_cBlob.getblobs();\n\tfor (int i=0; i<15; i++) {\n\t\tif (blobs == NULL) break; //leaves higher indexes uninitialized...be careful\n\t\targ->flux[i] = blobs->getflux();\n\t\targ->mean[i] = blobs->getmean();\n\t\targ->snr[i] = blobs->getsnr();\n\t\targ->x[i] = blobs->getx();\n\t\targ->y[i] = blobs->gety();\n\t\tblobs = blobs->getnextblob();\n\t}\n\treturn arg;\n}\n\n\n#if USE_PYRAMID\n/*\n\n matchStars:\n \n performs star pattern matching, sol is returned as a pointer to the solution array\n returns number of solutions found or -1 on error\n \n*/\nint BlobImage::matchStars(solution_t **sol)\n{\n\tint nblobs = (m_cBlob.get_numblobs() > 7) ? 7 : m_cBlob.get_numblobs();\n//\tint nblobs = 5; //NNG for testing\n\tdouble *x, *y;\n\tx = new double[nblobs];\n\ty = new double[nblobs];\n\tdouble *x_p = new double [nblobs];\n \tdouble *y_p = new double [nblobs];\n\tmemset(x_p, 0, sizeof(x_p) );\n\tmemset(y_p, 0, sizeof(y_p) );\n \tdouble XC = 1530/2;\n \tdouble YC = 1020/2;\n\tbloblist *blobs = m_cBlob.getblobs();\n\tint i = 0, retval = -1;\n \tdouble ra0, dec0, r0;\n\t\n\tfor (i=0; i< nblobs; i++) {\n\t\tx[i] = blobs->getx();\n\t\ty[i] = blobs->gety();\n\t\tblobs = blobs->getnextblob();\n\t\ti++;\n\t}\n\n\t//AND change platescale to 9.44\t\n/*\tx[0]=930.157011384096;\n\ty[0]=167.158449582342;\n\tx[1]=1472.58714161560;\n\ty[1]=922.480301367182;\n\tx[2]=908.983169656947;\n\ty[2]=323.056623586626;\n\tx[3]=1129.46618620267;\n\ty[3]=677.975355808673;\n\tx[4]=330.391564235287;\n\ty[4]=825.453326589156;\n\n\tfor (i = 0; i < nblobs; i++) {\n\t\tx_p[i] = (x[i] - XC)*m_dPlatescale;\n\t\ty_p[i] = (y[i] - YC)*m_dPlatescale;\n\t}\n*/\n\tif (m_cPyramid.GetSolution(m_dMatchTol, x_p, y_p, nblobs, sol, &retval, &ra0, &dec0, &r0) < 0)\n\t\tretval = -1;\n\n\tdelete[] x;\n\tdelete[] y;\n\treturn retval;\n}\n#endif //if USE_PYRAMID\n" }, { "alpha_fraction": 0.6367461681365967, "alphanum_fraction": 0.6451612710952759, "avg_line_length": 23.55172348022461, "blob_id": "0aaa469913108f2b6bcbca6fa1b9c9efd06ca359", "content_id": "d2bee3ecc0356e9ed98877d2380208e0476637bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 714, "license_type": "no_license", "max_line_length": 73, "num_lines": 29, "path": "/stars/code/shared/autofocus/results.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"results.h\"\n\nusing namespace Shared::Autofocus;\n\nResults::Results()\n{\n mode = mode_not_running;\n current_focus_requested = 0;\n best_focus_known = false;\n best_focus = 0;\n}\n\nResults& Results::operator=(const Results &rhs)\n{\n if (this != &rhs) {\n mode = rhs.mode;\n current_focus_requested = rhs.current_focus_requested;\n age_of_last_run = rhs.age_of_last_run;\n best_focus_known = rhs.best_focus_known;\n best_focus = rhs.best_focus;\n }\n return *this;\n}\n\n" }, { "alpha_fraction": 0.566689670085907, "alphanum_fraction": 0.5767563581466675, "avg_line_length": 28.718887329101562, "blob_id": "5f2b87e65c8f28466dd50f8068a2a74f034d1313", "content_id": "6d48adb5ff176dfe50422845d657489f5c5b10e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 60896, "license_type": "no_license", "max_line_length": 138, "num_lines": 2049, "path": "/cow/src/cow.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* cow (previously known as narsil): GUI commanding front-end\n *\n * This software is copyright (C) 2002-2011 University of Toronto\n * Parts of this software are copyright 2010 Matthew Truch\n *\n * This file is part of cow.\n *\n * cow 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 2 of the License, or\n * (at your option) any later version.\n *\n * cow 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 cow; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n// ***************************************************\n// * Programmed by Adam Hincks *\n// * Later poked at a bit by D.V.Wiebe *\n// * further desecrated by cbn *\n// * Commanding hacked to hell by M.D.P.Truch *\n// * \"Ported\" to qt4 by Joshua Netterfield *\n// * Herds added by cbn *\n// ***************************************************\n\n#define _XOPEN_SOURCE 501\n#define _POSIX_C_SOURCE 200809L\n\n#include <QCompleter>\n#include <QDebug>\n#include <QApplication>\n#include <QButtonGroup>\n#include <QGroupBox>\n#include <QDir>\n#include <QFileDialog>\n#include <QFrame>\n#include <QLabel>\n#include <QLineEdit>\n#include <QPushButton>\n#include <QRadioButton>\n#include <QLayout>\n#include <QVariant>\n#include <QToolTip>\n#include <QWhatsThis>\n#include <QSpinBox>\n#include <QValidator>\n#include <QPixmap>\n#include <QCheckBox>\n#include <QComboBox>\n#include <QMessageBox>\n#include <QTextEdit>\n#include <QTimer>\n#include <QFile>\n#include <QDateTime>\n#include <QSizePolicy>\n#include <QMainWindow>\n#include <QStatusBar>\n#include <QDoubleSpinBox>\n#include <QListWidget>\n#include <QTextStream>\n#include <QInputDialog>\n#include <QSettings>\n#include <QDirModel>\n#include <QKeyEvent>\n#include <QStyleFactory>\n#include <QTabWidget>\n\n#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <sys/wait.h>\n#include <sys/types.h>\n#include <signal.h>\n#include <time.h>\n#include <pwd.h>\n\n#include \"widgets.h\"\n#include \"cow.h\"\n\n#ifndef DATA_ETC_COW_DIR\n#error Edit cow.pro to define DATA_ETC_COW_DIR !\n#endif\n\n#define PONG_MISS_MAX 5\n\n#define PADDING 3\n#define SPACING 3\n\n#define LOGFILE DATA_ETC_COW_DIR \"/log.txt\"\n#define LOGFILEDIR DATA_ETC_COW_DIR \"/log/\"\n#define HERDFILEDIR \"/data/etc/cow/\"\n\n#define DATA_DIR DATA_ETC_COW_DIR\n\n#define PING_TIME 19000\n#define WAIT_TIME 80\n\n#ifdef __APPLE__\n/* On a Mac keyboard, ⌘ (Command) is represented by ControlModifier, and\n * Control by MetaModifier\n */\n#define SEND_KEY ev->key() == Qt::Key_Enter && (ev->modifiers() & Qt::ControlModifier)\n/* For reasons of lameness, SEND_KEY_NAME must be a particular length */\n#define SEND_KEY_NAME \"Cmd-Ent\"\n#else\n#define SEND_KEY ev->key() == Qt::Key_F12 && (ev->modifiers()&Qt::ShiftModifier)\n#define SEND_KEY_NAME \"Shift-F12\"\n#endif\n\nQString blastcmd_host;\nQString herdfile;\nint stop_comms;\nint missed_pongs;\n\n/* Defaults class holds the default parameter values */\nDefaults::Defaults()\n{\n int i, j;\n int fp;\n int n_read = 0;\n\n for (i = 0; i < MAX_N_PARAMS; ++i) {\n rdefaults[i] = (double*)malloc(sizeof(double) * client_n_mcommands);\n idefaults[i] = (int*)malloc(sizeof(int) * client_n_mcommands);\n sdefaults[i] = (char(*)[CMD_STRING_LEN])malloc(sizeof(char) *\n CMD_STRING_LEN * client_n_mcommands);\n }\n\n /* Read in previous default values */\n if ((fp = open(DATA_DIR \"/prev_status\", O_RDONLY)) >= 0) {\n for (i = 0; i < MAX_N_PARAMS; ++i) {\n n_read += read(fp, rdefaults[i], sizeof(double) * client_n_mcommands);\n n_read += read(fp, idefaults[i], sizeof(int) * client_n_mcommands);\n n_read += read(fp, sdefaults[i], sizeof(char) * CMD_STRING_LEN\n * client_n_mcommands);\n }\n close(fp);\n }\n\n if (n_read != (int)(sizeof(int) + sizeof(double) + 32 * sizeof(char))\n * client_n_mcommands * MAX_N_PARAMS)\n for (i = 0; i < client_n_mcommands; i++)\n for (j = 0; j < MAX_N_PARAMS; j++)\n rdefaults[j][i] = idefaults[j][i] = sdefaults[j][i][0] = 0;\n}\n\n//-------------------------------------------------------------\n//\n// Defaults::Save: Cow remembers any values entered for the\n// next time it starts up\n//\n//-------------------------------------------------------------\n\nvoid Defaults::Save() {\n int fp, i;\n\n /* Write file with defaults */\n fp = open(DATA_DIR \"/prev_status\", O_WRONLY|O_CREAT|O_TRUNC, 0666);\n if (fp < 0)\n printf(\"Warning: could not open prev_status file\\n\");\n else {\n for (i = 0; i < MAX_N_PARAMS; ++i) {\n if (write(fp, rdefaults[i], sizeof(double) * client_n_mcommands) < 0)\n printf(\"Warning: could not write rdefults to prev_status file\\n\");\n if (write(fp, idefaults[i], sizeof(int) * client_n_mcommands) < 0)\n printf(\"Warning: could not write idefults to prev_status file\\n\");\n if (write(fp, sdefaults[i], sizeof(char) * CMD_STRING_LEN\n * client_n_mcommands) < 0)\n printf(\"Warning: could not write sdefults to prev_status file\\n\");\n }\n close(fp);\n }\n}\n\nvoid Defaults::Set(int i, int j, QString text)\n{\n idefaults[j][i] = text.toInt();\n rdefaults[j][i] = text.toDouble();\n strncpy(sdefaults[j][i], text.toLatin1(), CMD_STRING_LEN - 1);\n sdefaults[j][i][CMD_STRING_LEN - 1] = 0;\n}\n\nint Defaults::asInt(int i, int j) { return idefaults[j][i]; }\ndouble Defaults::asDouble(int i, int j) { return rdefaults[j][i]; }\nconst char* Defaults::asString(int i, int j) { return sdefaults[j][i]; }\n\n//***************************************************************************\n//**** CLASS MainForm -- main control class\n//***************************************************************************\n\n//-------------------------------------------------------------\n// GetGroup (private): checks the radio group of buttons to see\n// which group is checked\n//\n// Returns: index of the selected group\n//-------------------------------------------------------------\n\nint MainForm::GetGroup() {\n int i;\n\n if (TabWidget->currentIndex()==0) {\n for (i = 0; i < client_n_groups; i++) {\n if (NGroups[i]->isChecked()) {\n return i;\n }\n }\n } else {\n for (i=0; i<ListOfHerds.length(); i++) {\n if (HerdGroups[i]->isChecked()) {\n return i;\n }\n }\n }\n\n return 0;\n}\n\nint TheSort(const void* a, const void* b)\n{\n const char *za = (*(int*)a >= client_n_scommands) ? client_mcommands[*(int*)a\n - client_n_scommands].name : client_scommands[*(int*)a].name;\n const char *zb = (*(int*)b >= client_n_scommands) ? client_mcommands[*(int*)b\n - client_n_scommands].name : client_scommands[*(int*)b].name;\n return strcmp(za, zb);\n}\n\nvoid MainForm::OmniParse(QString x) //evil, evil function (-Joshua)\n{\n x=(x==\"__AUTODETECT__\")?NOmniBox->text():x;\n QString r=x;\n if(r.contains(' ')) r.truncate(x.indexOf(' ')+1);\n\n bool special=0;\n\n if (NOmniBox->hasFocus()) {\n TabWidget->setCurrentIndex(0);\n }\n\n if(!NOmniBox->hasFocus()||((r==x||x+\" \"==r)&&NOmniBox->oldXSize<x.size())) {\n special=1;\n }\n if(NOmniBox->hasFocus()) NOmniBox->oldXSize=x.size();\n\n //search for command, and select it if matched\n int best_i=-1;\n for(int i=0;i<OmniList.size();i++) {\n if(r==OmniList[i].name+' ') {\n if(!NGroups[OmniList[i].group]->isChecked()) {\n best_i=i;\n } else {\n best_i=-1;\n break;\n }\n }\n }\n if (TabWidget->currentIndex()==0) {\n if(best_i!=-1) {\n NGroups[OmniList[best_i].group]->toggle();\n }\n }\n\n for(int i=0;i<NCommandList->count();i++) {\n if(NCommandList->item(i)->text()+\" \"==r) {\n NCommandList->setCurrentRow(i);\n }\n }\n\n //look for command in current list, then set box colour and dis/enable Send button\n bool ok=0;\n for(int i=0;i<NCommandList->count();i++) {\n if(r==NCommandList->item(i)->text()+' ') {\n ok=1;\n break;\n }\n }\n QPalette f = NOmniBox->palette();\n if(!ok||x.contains(\" \")) {\n f.setColor(QPalette::Base,\"pink\");\n NSendButton->setEnabled(0);\n } else { //moved from questionably useful part above\n f.setColor(QPalette::Base,\"white\");\n NSendButton->setEnabled(1);\n }\n NOmniBox->setPalette(f);\n //FIXME after selecting a group, commands get erased not completed eg click \"HWPR\", type \"stop\"\n\n\n if(x.contains(' ')) {\n if(special && ok) {\n x.truncate(x.indexOf(' ')+1);\n for(int i=0;i<MAX_N_PARAMS;i++) {\n if(NParamFields[i]->isVisible()) {\n x.append(i?\" \":\"\");\n x.append(dynamic_cast<AbstractCowEntry*>(NParamFields[i])->Text());\n }\n }\n\n int cp=NOmniBox->cursorPosition();\n int sbeg=NOmniBox->selectionStart();\n int slen=NOmniBox->selectedText().size();\n if(x!=NOmniBox->text()) {\n NOmniBox->setRealText(x);\n }\n NOmniBox->setCursorPosition(cp);\n if(sbeg!=-1) {\n NOmniBox->setSelection(sbeg,slen);\n }\n }\n\n QStringList words=x.split(\" \");\n int max=MAX_N_PARAMS+1;\n for(int i=1;i<=MAX_N_PARAMS;i++) {\n if(!NParamFields[i-1]->isVisible()) {\n max=i;\n break;\n }\n if(words.size()<=i||words[i]==\"\") {\n QPalette f = NOmniBox->palette();\n f.setColor(QPalette::Base,\"pink\");\n NOmniBox->setPalette(f);\n NSendButton->setEnabled(0);\n break;\n }\n if(NParamFields[i-1]->isVisible() && !words[i].isEmpty()) {\n // words[i].replace(\"..\",\".\"); // doesn't seem to do anything...\n bool ok=dynamic_cast<CowStringEntry*>(NParamFields[i-1]);\n if(ok) {\n int j=i;\n while(++j<words.size()) {\n words[i]+=\" \"+words[j];\n }\n }\n if(!ok) {\n words[i].toDouble(&ok);\n }\n if(!ok) {\n words[i].toInt(&ok);\n }\n if(ok) {\n if(dynamic_cast<CowStringEntry*>(NParamFields[i-1])) {\n dynamic_cast<AbstractCowEntry*>(NParamFields[i-1])->SetStringValue(words[i]);\n } else if(dynamic_cast<AbstractCowEntry*>(NParamFields[i-1])->Text().toFloat()!=words[i].toFloat()){\n dynamic_cast<AbstractCowEntry*>(NParamFields[i-1])->SetStringValue(QString::number(words[i].toFloat()));\n }\n }\n }\n }\n if(words.size()&&words.back()==\"\") words.pop_back();\n if(words.size()<max) {\n QPalette f = NOmniBox->palette();\n f.setColor(QPalette::Base,\"pink\");\n NOmniBox->setPalette(f);\n NSendButton->setEnabled(0);\n }\n\n }\n}\n\nvoid MainForm::nOmniBox_completerActivated(const QString & text)\n{\n //always special when selected from completer\n NOmniBox->oldXSize = 0;\n\n OmniParse(text);\n\n}\n\n/*\n void MainForm::testTextChanged(const QString & text)\n {\n qDebug() << \"test textChanged: \" << NOmniBox->text() << \" -> \" << text;\n }\n\n void MainForm::testCursorPositionChanged(int o, int n)\n {\n qDebug() << \"cursor moved: \" << o << \" -> \" << n;\n }\n */\n\nvoid MainForm::nOmniBox_textEdited(const QString & text)\n{\n int cp=NOmniBox->cursorPosition();\n int sbeg=NOmniBox->selectionStart();\n int slen=NOmniBox->selectedText().size();\n NOmniBox->setRealText(text);\n NOmniBox->setCursorPosition(cp);\n if(sbeg!=-1) {\n NOmniBox->setSelection(sbeg,slen);\n }\n OmniParse(text);\n NOmniBox->setFocus();\n}\n\nvoid MainForm::OmniSync()\n{\n QString x=NOmniBox->text();\n QStringList words=x.split(\" \");\n for(int i=1;i<words.size();i++) {\n if((i<MAX_N_PARAMS) && NParamFields[i-1]->isVisible() && !words[i].isEmpty()) {\n // words[i].replace(\"..\",\".\"); // doesn't seem to do anything...\n words[i]=dynamic_cast<AbstractCowEntry*>(NParamFields[i-1])->Text();\n }\n }\n\n if(NOmniBox->hasFocus()) return;\n\n int cp=NOmniBox->cursorPosition();\n int sbeg=NOmniBox->selectionStart();\n int slen=NOmniBox->selectedText().size();\n NOmniBox->setRealText(words.join(\" \"));\n NOmniBox->setCursorPosition(cp);\n if(sbeg!=-1) {\n NOmniBox->setSelection(sbeg,slen);\n }\n OmniParse();\n}\n\n//-------------------------------------------------------------\n// ChangeCommandList (slot): when a new group is selected,\n// the list of commands must be cleared and the new\n// group's commands added. Triggered when a group button\n// is selected.\n//-------------------------------------------------------------\n\nvoid MainForm::ChangeCommandList(bool really) {\n if(!really) {\n return;\n }\n\n int indexes[client_n_scommands + client_n_mcommands];\n int i;\n int max;\n\n NCommandList->clearSelection();\n NCommandList->clearFocus();\n NCommandList->clear();\n\n if (TabWidget->currentIndex()==0) {\n max = GroupSIndexes(GetGroup(), indexes);\n max += GroupMIndexes(GetGroup(), &indexes[max]);\n //fprintf(stderr, \"Group count: %i\\n\", max);\n qsort(indexes, max, sizeof(int), &TheSort);\n\n for (i = 0; i < max; i++)\n if (indexes[i] >= client_n_scommands) {\n NCommandList->addItem(client_mcommands[indexes[i]\n - client_n_scommands].name);\n } else {\n NCommandList->addItem(client_scommands[indexes[i]].name);\n }\n } else {\n if (ListOfHerds.size() > 0) {\n NCommandList->addItems(HerdHash[ListOfHerds.at(GetGroup())]);\n NCommandList->setSelectionMode(QAbstractItemView::SingleSelection);\n }\n }\n ChooseCommand();\n // OmniParse();\n}\n\n// Check the dirfile name, and see if it's chagned */\nint MainForm::LinkChanged(void)\n{\n static char old_target[4096] = { 0 };\n ssize_t n;\n\n char lnkname[4096];\n char target[4096];\n strncpy(lnkname, NCurFile->text().toStdString().c_str(), 4096);\n lnkname[4095] = 0;\n\n n = readlink(lnkname, target, 4096);\n\n if (n < 0) {\n //qDebug() << \"readlink returned error\";\n old_target[0] = 0; /* forget old name */\n return 1; // assume we need to re-read\n }\n\n if (strncmp(target, old_target, n)) {\n // Link changed\n strncpy(old_target, target, n);\n old_target[n] = 0;\n return 1;\n }\n\n // No change.\n return 0;\n}\n\n//-------------------------------------------------------------\n// ChooseCommand (slot): triggered when a command is selected\n// from the list. Changes labels and shows spin-boxes\n// as appropiate for the command.\n//-------------------------------------------------------------\n\nvoid MainForm::ChooseCommand(bool index_combo_changed, int combo_index) {\n int i, index;\n double indata;\n Q_UNUSED(combo_index);\n\n if (LinkChanged()) {\n delete _dirfile;\n _dirfile = new Dirfile(NCurFile->text().toStdString().c_str(), GD_RDONLY);\n if (_dirfile->Error()) {\n delete _dirfile;\n _dirfile = NULL;\n }\n }\n\n // Remember parameter values\n if (lastmcmd != -1) {\n for (i = 0; i < client_mcommands[lastmcmd].numparams; i++)\n dynamic_cast<AbstractCowEntry*>(NParamFields[i])->RecordDefaults();\n\n defaults->Save();\n }\n\n // It can happen that this function be called with nothing selected\n if (!NCommandList->currentIndex().isValid() ||\n (!index_combo_changed && (!NCommandList->hasFocus()&&!NOmniBox->hasFocus()))) {\n NSendButton->setDisabled(true);\n lastmcmd = -1;\n NAboutLabel->setText(tr(\"No command selected.\"));\n for (i = 0; i < MAX_N_PARAMS; i++) {\n NParamLabels[i]->hide();\n NParamFields[i]->hide();\n }\n } else {\n NSendButton->setEnabled(true);\n if(!NOmniBox->text().contains(NCommandList->currentItem()->text()+\" \")) {\n NOmniBox->setRealText(NCommandList->currentItem()->text()+\" \");\n }\n NOmniBox->setCursorPosition(NOmniBox->text().size());\n if ((index = SIndex( NCommandList->currentItem()->text()) ) != -1) {\n // Set up for a single command\n NAboutLabel->setText(client_scommands[index].about);\n lastmcmd = -1;\n for (i = 0; i < MAX_N_PARAMS; i++) {\n NParamLabels[i]->hide();\n NParamFields[i]->hide();\n }\n } else if ((index = MIndex(NCommandList->currentItem()->text()))\n != -1) {\n // Set up for a multi command -- show the parameter spin boxes\n NAboutLabel->setText(client_mcommands[index].about);\n lastmcmd = index;\n\n //bool IsData = DataSource->update();\n\n int index_serial = 0;\n for (i = 0; i < MAX_N_PARAMS; i++) {\n if (i < client_mcommands[index].numparams) {\n\n NParamLabels[i]->setText(client_mcommands[index].params[i].name);\n NParamLabels[i]->show();\n\n bool typeChanged=0;\n QRect geometry=NParamFields[i]->geometry();\n if (!(dynamic_cast<CowStringEntry*>(NParamFields[i])) && client_mcommands[index].params[i].type=='s') {\n typeChanged=1;\n delete NParamFields[i];\n connect(NParamFields[i]=new CowStringEntry(NTopFrame,\"NParamLabels\"),\n SIGNAL(textEdited(QString)),this,SLOT(OmniSync()));\n } else if (client_mcommands[index].params[i].nt) {\n CowComboEntry* cce = dynamic_cast<CowComboEntry*>(NParamFields[i]);\n if (cce) {\n if (client_mcommands[index].params[i].index_serial) {\n disconnect(cce, SIGNAL(activated(int)), this, SLOT(IndexComboChanged(int)));\n }\n cce->clear();\n } else {\n typeChanged=1;\n delete NParamFields[i];\n cce=new CowComboEntry(NTopFrame,\"NParamLabels\");\n }\n if (client_mcommands[index].params[i].index_serial) {\n connect(cce, SIGNAL(activated(int)), this, SLOT(IndexComboChanged(int)));\n }\n NParamFields[i] = cce;\n for (int i_par = 0; client_mcommands[index].params[i].nt[i_par] != 0; i_par++) {\n cce->addItem(client_mcommands[index].params[i].nt[i_par]);\n }\n cce->minVal = client_mcommands[index].params[i].min;\n connect(dynamic_cast<CowComboEntry*>(NParamFields[i]),\n SIGNAL(valueEdited()),this,SLOT(OmniSync()));\n } else if (!(dynamic_cast<CowDoubleEntry*>(NParamFields[i])) && client_mcommands[index].params[i].type!='s'\n && client_mcommands[index].params[i].nt == 0) {\n typeChanged=1;\n if (NParamFields[i]->hasFocus()) {\n qDebug() << \"attempt to delete double entry which had focus! Leaking memory instead...\";\n NParamFields[i]->hide();\n } else {\n delete NParamFields[i];\n }\n NParamFields[i]=new CowDoubleEntry(NTopFrame,\"NParamLabels\");\n connect(dynamic_cast<CowDoubleEntry*>(NParamFields[i]),\n SIGNAL(valueEdited()),this,SLOT(OmniSync()));\n }\n if(typeChanged) {\n int w2 = NParamLabels[i]->width();\n\n NParamFields[i]->setFixedWidth(w2/2);\n NParamFields[i]->adjustSize();\n\n NParamFields[i]->setGeometry(geometry);\n }\n NParamFields[i]->show();\n if (i > 0) {\n setTabOrder(NParamFields[i-1], NParamFields[i]);\n } else {\n setTabOrder(NCommandList, NParamFields[i]);\n }\n dynamic_cast<AbstractCowEntry*>(NParamFields[i])->SetParentField(index, i);\n dynamic_cast<AbstractCowEntry*>(NParamFields[i])->SetType(client_mcommands[index].params[i].type);\n if (client_mcommands[index].params[i].type == 's') {\n dynamic_cast<AbstractCowEntry*>(NParamFields[i])->SetStringValue(\n client_mcommands[index].params[i].field);\n } else {\n int nf;\n if (client_mcommands[index].params[i].index_serial) {\n int i_s = client_mcommands[index].params[i].index_serial;\n CowComboEntry *cce=dynamic_cast<CowComboEntry*>(NParamFields[i]);\n if (cce) {\n if (index_combo_changed) {\n cce->SetDefaultValue(index, i);\n index_defaults.insert(i_s, cce->Text().toInt());\n } else {\n cce->SetIndex(index_defaults.value(i_s, client_mcommands[index].params[i].min) - client_mcommands[index].params[i].min);\n cce->RecordDefaults();\n cce->SetDefaultValue(index, i);\n }\n }\n } else if (_dirfile && ((nf = _dirfile->NFrames())>0) &&\n (_dirfile->GetData( client_mcommands[index].params[i].field,\n nf-1, 0, 0, 1, // 1 sample from frame nf-1\n Float64, (void*)(&indata))!=0)) {\n dynamic_cast<AbstractCowEntry*>(NParamFields[i])->SetValue(indata);\n } else {\n double d;\n char cmdstr[SIZE_CMDPARNAME];\n if (index_serial) {\n sprintf(cmdstr, \"%s;%d;%s\", client_mcommands[index].name,\n index_serial, client_mcommands[index].params[i].name);\n } else {\n // FIXME: index parameter\n sprintf(cmdstr, \"%s;%s\", client_mcommands[index].name,\n client_mcommands[index].params[i].name);\n }\n\n if (stop_comms)\n d = DEF_NOT_FOUND;\n else if (NetCmdGetDefault(&d, cmdstr)) {\n if (missed_pongs < PONG_MISS_MAX - 1)\n missed_pongs++;\n d = DEF_NOT_FOUND;\n }\n\n\n if ((d == DEF_NOT_FOUND) ||\n (client_mcommands[index].params[i].index_serial))\n {\n dynamic_cast<AbstractCowEntry*>(NParamFields[i])->SetDefaultValue(index, i);\n } else {\n dynamic_cast<AbstractCowEntry*>(NParamFields[i])->SetValue(d);\n }\n }\n if (client_mcommands[index].params[i].index_serial>0) {\n index_serial = dynamic_cast<AbstractCowEntry*>(NParamFields[i])->Text().toInt();\n }\n }\n } else {\n NParamLabels[i]->hide();\n NParamFields[i]->hide();\n }\n }\n }\n if (!NOmniBox->hasFocus()) {\n OmniParse();\n }\n //NOmniBox->setFocus();\n NOmniBox->setCursorPosition(NOmniBox->text().indexOf(\" \")+1);\n }\n}\n\n\n//-------------------------------------------------------------\n//\n// GroupSIndexes (private): creates a list of references to\n// single commands in the same group\n//\n// group: the group the commands should belong to\n// *indexes: array to build the list in\n//\n// Returns: number of single commands in the group\n//\n//-------------------------------------------------------------\n\nint MainForm::GroupSIndexes(int group, int *indexes) {\n int i;\n int num = 0;\n\n for (i = 0; i < client_n_scommands; i++)\n if (client_scommands[i].group & (1 << group))\n indexes[num++] = i;\n\n return num;\n}\n\n\n//-------------------------------------------------------------\n//\n// GroupMIndexes (private): creates a list of references to\n// multiple commands in the same group\n//\n// group: the group the commands should belong to\n// *indexes: array to build the list in\n//\n// Returns: number of multiple commands in the group\n//\n//-------------------------------------------------------------\n\nint MainForm::GroupMIndexes(int group, int *indexes) {\n int i;\n int num = 0;\n\n for (i = 0; i < client_n_mcommands; i++)\n if (client_mcommands[i].group & (1 << group))\n indexes[num++] = i + client_n_scommands;\n\n return num;\n}\n\n\n//-------------------------------------------------------------\n//\n// SIndex (private): given the command, retrieves the\n// index of the single command\n//\n// cmd: command name\n//\n// Returns: command index; -1 if not found\n//\n//-------------------------------------------------------------\n\nint MainForm::SIndex(QString cmd) {\n int i;\n\n for (i = 0; i < client_n_scommands; i++) {\n if (strcmp(client_scommands[i].name, cmd.toLatin1()) == 0)\n return i;\n }\n\n return -1;\n}\n\n\n//-------------------------------------------------------------\n//\n// MIndex (private): given the command, retrieves the\n// index of the multiple command\n//\n// cmd: command name\n//\n// Returns: command index; -1 if not found\n//\n//-------------------------------------------------------------\n\nint MainForm::MIndex(QString cmd) {\n int i;\n\n for (i = 0; i < client_n_mcommands; i++) {\n if (strcmp(client_mcommands[i].name, cmd.toLatin1()) == 0)\n return i;\n }\n\n return -1;\n}\n\n\n//-------------------------------------------------------------\n//\n// LongestParam (private): looks through all the parameters\n// from all the multiple commands for the longest\n//\n// Returns: length of the longest parameter\n//\n//-------------------------------------------------------------\n\nchar *MainForm::LongestParam() {\n unsigned int i;\n int j;\n unsigned int len = 0;\n static char lp[120];\n\n for (i = 0; i < client_n_mcommands; i++) {\n for (j = 0; j < client_mcommands[i].numparams; j++) {\n if (strlen(client_mcommands[i].params[j].name) > len) {\n len = strlen(client_mcommands[i].params[j].name);\n strcpy(lp, client_mcommands[i].params[j].name);\n }\n }\n }\n\n return lp;\n}\n\n\n//-------------------------------------------------------------\n//\n// Quit (slot): triggered when user presses quit button\n//\n//-------------------------------------------------------------\n\nvoid MainForm::Quit() {\n // Settings should be sticky\n {\n QSettings settings(\"University of Toronto\",\"cow\");\n settings.setValue(\"blastcmd_host\",QString(blastcmd_host));\n settings.setValue(\"curfile\",NCurFile->text());\n settings.setValue(\"link\",NSendMethod->currentIndex());\n settings.setValue(\"geometry\", saveGeometry());\n }\n\n int i;\n\n // Remember parameter values\n if (lastmcmd != -1) {\n for (i = 0; i < client_mcommands[lastmcmd].numparams; i++)\n dynamic_cast<AbstractCowEntry*>(NParamFields[i])->RecordDefaults();\n\n defaults->Save();\n }\n}\n\n\n//-------------------------------------------------------------\n//\n// Tick (slot): triggered by timer.\n// Animate the cool picture of THE COW;\n// Check for incoming messages and do as appropriate.\n//\n//-------------------------------------------------------------\n\nvoid MainForm::Tick() {\n timer->stop();\n\n if (framenum) {\n framenum+=dir;\n if(framenum==numframes-1) dir=-1;\n NWaitImage->setPixmap(*Images[framenum]);\n }\n\n if (!stop_comms) {\n ReceivePackets(!verbose, CMD_NONE);\n\n ConnBanner->setText(NetCmdBanner());\n }\n timer->start(WAIT_TIME);\n}\n\nint MainForm::ReceivePackets(int silent, int wait_for)\n{\n Q_UNUSED(silent);\n int returnstatus;\n char oob_message[1024];\n\n do {\n returnstatus = NetCmdReceive(!verbose, 1024, oob_message);\n if ((returnstatus & 0xFF) == CMD_PING) {\n pong = 1;\n if (missed_pongs > 0) {\n printf(\"Got a PONG from server.\\n\");\n missed_pongs = 0;\n }\n } else if (sending && ((returnstatus & 0xFF) == CMD_BCMD)) {\n if ((returnstatus >> 8) == 12)\n returnstatus = (99 << 8);\n\n if (oob_message[0])\n WriteErr(NLog, oob_message, returnstatus >> 8);\n else\n WriteErr(NLog, NULL, returnstatus >> 8);\n\n TurnOff();\n } else if ((returnstatus & 0xff) == CMD_ERRR)\n break;\n } while (returnstatus != CMD_NONE && returnstatus != wait_for && !stop_comms);\n return returnstatus;\n}\n\nvoid MainForm::Ping(void) {\n ping_timer->stop();\n if (!pong) { /* missed a pong */\n printf(\"Missed PONG #%i from server!\\n\", missed_pongs);\n if (++missed_pongs > PONG_MISS_MAX) {\n stop_comms = 1;\n ServerDropped();\n }\n }\n\n if (!NetCmdPing()) {\n /* ping succesfully sent */\n pong = 0; /* wait for next pong */\n }\n\n ping_timer->start(PING_TIME);\n}\n\n\n//-------------------------------------------------------------\n//\n// TurnOn (private): called when the user tries to send a\n// command. Most user input is suspended while the\n// command is being send.\n//\n//-------------------------------------------------------------\n\nvoid MainForm::TurnOn(void) {\n\n sending = true;\n\n for(int i=0;i<centralWidget->children().size();i++) {\n QWidget* c=dynamic_cast<QWidget*>(centralWidget->children()[i]);\n if(c) c->setEnabled(0);\n }\n for(int i=0;i<NBotFrame->children().size();i++) {\n QWidget* c=dynamic_cast<QWidget*>(NBotFrame->children()[i]);\n if(c) c->setEnabled(0);\n }\n centralWidget->setEnabled(1);\n NBotFrame->setEnabled(1);\n NSendButton->setEnabled(1);\n\n NSendButton->setText(tr(\"Cancel\"));\n}\n\n\n//-------------------------------------------------------------\n//\n// TurnOff (private): called when the command has been sent,\n// or user has cancelled\n//\n//-------------------------------------------------------------\n\nvoid MainForm::TurnOff(void) {\n sending = false;\n\n for(int i=0;i<centralWidget->children().size();i++) {\n QWidget* c=dynamic_cast<QWidget*>(centralWidget->children()[i]);\n if(c) c->setEnabled(1);\n }\n for(int i=0;i<NBotFrame->children().size();i++) {\n QWidget* c=dynamic_cast<QWidget*>(NBotFrame->children()[i]);\n if(c) c->setEnabled(1);\n }\n NSendButton->setText(tr(\"Send (\" SEND_KEY_NAME \")\"));\n}\n\n\n//-------------------------------------------------------------\n//\n// SendCommand (slot): triggered when user presses send button.\n//\n//-------------------------------------------------------------\n\nvoid MainForm::SendCommand() {\n int index, j;\n char buffer[1024];\n char request[1024];\n char sparam[CMD_STRING_LEN];\n const char link[] = \"LTIP\";\n const char route[] = \"12\";\n\n if (!sending) {\n\n // Select appropiate flags\n verbose = NVerbose->isChecked();\n\n request[0] = link[NSendMethod->currentIndex()];\n request[1] = route[NSendRoute->currentIndex()];\n request[2] = ' ';\n\n // command name\n strcpy(request + 3, NCommandList->currentItem()->text().toLatin1());\n\n // Parameters\n if ((index = MIndex(NCommandList->currentItem()->text())) != -1)\n {\n\n // Check to see if this command requires a confirm\n if (client_mcommands[index].group & CONFIRM) {\n sprintf(buffer, \"The command %s requires confirmation.\\n\"\n \"Are you sure you want to send this command?\",\n NCommandList->currentItem()->text().toStdString().c_str());\n\n if ( QMessageBox::warning(this, \"Confirm Command\", tr(buffer),\n QMessageBox::Yes, QMessageBox::Escape | QMessageBox::No |\n QMessageBox::Default) == QMessageBox::No ) {\n WriteCmd(NLog, request);\n WriteErr(NLog, 11);\n return;\n }\n }\n\n for (j = 0; j < client_mcommands[index].numparams; j++) {\n dynamic_cast<AbstractCowEntry*>(NParamFields[j])->RecordDefaults();\n if (defaults->asDouble(index, j) < client_mcommands[index].params[j].min) {\n sprintf(buffer, \"Error: Parameter \\\"%s\\\" out of range: %f < %f\",\n client_mcommands[index].params[j].name,\n defaults->asDouble(index, j),\n client_mcommands[index].params[j].min);\n WriteCmd(NLog, buffer);\n WriteErr(NLog, 10);\n return;\n } else if (defaults->asDouble(index, j) > client_mcommands[index].params[j].max) {\n sprintf(buffer, \"Error: Parameter \\\"%s\\\" out of range: %f > %f\",\n client_mcommands[index].params[j].name,\n defaults->asDouble(index, j),\n client_mcommands[index].params[j].max);\n WriteCmd(NLog, buffer);\n WriteErr(NLog, 10);\n return;\n }\n if (client_mcommands[index].params[j].type == 'i'\n || client_mcommands[index].params[j].type == 'l') {\n sprintf(buffer, \" %i\", defaults->asInt(index, j));\n } else if (client_mcommands[index].params[j].type == 's') {\n sprintf(sparam, \"%s\", defaults->asString(index, j));\n for (int ic = 0; sparam[ic] != '\\0'; ic++) {\n if (sparam[ic]==' ') sparam[ic] = '\\a';\n }\n sprintf(buffer, \" %s\", sparam);\n } else {\n sprintf(buffer, \" %f\", defaults->asDouble(index, j));\n }\n strcat(request, buffer);\n }\n } else {\n index = SIndex(NCommandList->currentItem()->text());\n\n // Check to see if this command requires a confirm\n if (client_scommands[index].group & CONFIRM) {\n sprintf(buffer, \"The command %s requires confirmation.\\n\"\n \"Are you sure you want to send this command?\",\n NCommandList->currentItem()->text().toStdString().c_str());\n\n if ( QMessageBox::warning(this, \"Confirm Command\", tr(buffer),\n QMessageBox::Yes, QMessageBox::Escape | QMessageBox::No |\n QMessageBox::Default) == QMessageBox::No ) {\n WriteCmd(NLog, request);\n WriteErr(NLog, 11);\n return;\n }\n }\n }\n\n //trigger the animation\n dir=1;\n framenum=1;\n\n /* NetCmd inhibited */\n if (stop_comms)\n return;\n\n /* Take the conn */\n /* note: loop takes place in TakeConn now. TODO implement limited attempts\n */\n if (!NetCmdTakeConn(!verbose)) { //Never got the conn.\n WriteCmd(NLog, request);\n WriteErr(NLog, 12);\n return;\n }\n\n TurnOn();\n\n // Update log file on disk\n WriteCmd(NLog, request);\n WriteLog(request);\n\n /* Send the command */\n strcat(request, \"\\r\\n\");\n NetCmdSend(request);\n } else {\n if (!stop_comms)\n NetCmdSend(\"::kill::\\r\\n\");\n }\n}\n\nvoid MainForm::ServerDropped() {\n bool ok;\n stop_comms = 1; /* The reset will restart comms */\n\n QString host=QInputDialog::getText(this,\n \"Server Dropped\",\n \"Connection to server lost. You may change \"\n \"servers at this point, if desired, or cancel to close COW\",\n QLineEdit::Normal, blastcmd_host, &ok);\n if (!ok) {\n Quit();\n qApp->exit(0);\n } else {\n blastcmd_host=host;\n Quit();\n qApp->exit(1337);\n }\n}\n\nvoid MainForm::ChangeHost() {\n bool ok;\n QString host=QInputDialog::getText(this,\n \"Change Host\", \"What host (or host:port) should cow connect to?\", \n QLineEdit::Normal, blastcmd_host, &ok);\n if(!ok) {\n return;\n } else {\n blastcmd_host=host;\n Quit();\n qApp->exit(1337);\n }\n}\n\n//-------------------------------------------------------------\n//\n// WriteCmd (private): keeps a record of the commands sent\n// with Cow; also records it in a textbox visible to\n// the user\n//\n// *dest: the textbox\n// *args: the arguments sent to blastcmd\n//\n//-------------------------------------------------------------\n\nvoid MainForm::WriteCmd(QTextEdit *dest, const char *request) {\n FILE *f;\n time_t t;\n char txt[2048];\n\n t = time(NULL);\n f = fopen(LOGFILE, \"a\");\n\n if (f == NULL) {\n QMessageBox::warning(this,\"Could not write log\",\"Could not write log. Did you forget to run \\\"make install\\\"?\");\n fprintf(stderr, \"Cow: could not write log file %s.\\n\", LOGFILE);\n return;\n }\n\n sprintf(txt, \"%s\", ctime(&t));\n fprintf(f, \"%s\", ctime(&t));\n txt[strlen(txt) - 1] = '\\0'; // Get rid of the \\n character\n dest->insertPlainText(\"\\n\"+QString(txt));\n dest->moveCursor(QTextCursor::End);\n\n sprintf(txt, \" %s\\n\", request);\n fprintf(f, \" %s\\n\", request);\n txt[strlen(txt) - 1] = '\\0'; // Get rid of the \\n character\n dest->insertPlainText(\"\\n\"+QString(txt));\n dest->moveCursor(QTextCursor::End);\n fclose(f);\n}\n\nvoid MainForm::WriteLog(const char *request) {\n QDateTime qdt;\n QString LogEntry, Group;\n int i, j;\n\n Group = client_group_names[GetGroup()];\n\n qdt = QDateTime::currentDateTime();\n\n LogEntry = NAboutLabel->text();\n LogEntry += \"\\n\";\n\n if ((j = MIndex(NCommandList->currentItem()->text()))\n != -1) {\n for (i=0; i < client_mcommands[j].numparams; i++) {\n LogEntry += QString(\"%1: %2\").\n arg(client_mcommands[j].params[i].name, 30).\n arg(dynamic_cast<AbstractCowEntry*>(NParamFields[i])->Text(), -8);\n if (i % 2 == 1)\n LogEntry += \"\\n\";\n }\n LogEntry += \"\\n\";\n }\n\n LogEntry += \"\\n\";\n\n LogEntry += &request[3];\n\n LogEntry += \"\\nTransmit via \";\n switch (NSendMethod->currentIndex()) {\n case 0:\n LogEntry+=\"Line of Sight\";\n break;\n case 1:\n LogEntry+=\"TDRSS\";\n break;\n case 2:\n LogEntry+=\"Iridium\";\n break;\n case 3:\n LogEntry+=\"Pilot\";\n break;\n }\n if (NSendMethod->currentIndex() != 3) {\n LogEntry+= \" through SIP \";\n switch (NSendRoute->currentIndex()) {\n case 0:\n LogEntry+=\"COMM 1\";\n break;\n case 1:\n LogEntry+=\"COMM 2\";\n break;\n }\n }\n\n LogEntry += \"\\n\";\n LogEntry += QString(\n \"-- Time : %1\\n\"\n \"-- Source: %2 Type: %3 Entry By: %4\\n\"\n \"-- Frame : %5 File: %6 \\n\")\n .arg(qdt.toString())\n .arg(\"Cow\",-10)\n .arg(Group, -10)\n .arg((getpwuid(getuid()))->pw_name, -10)\n .arg(_dirfile ? _dirfile->NFrames() : -1, -10)\n .arg(_dirfile ? _dirfile->Name() : \"\");\n\n LogEntry+=\"--------------------------------------------------\\n\\n\";\n\n QString logfilename = LOGFILEDIR +\n qdt.toString(\"yyyy-MM-dd.hh:mm:ss\") + \".\" +\n \"Cow.\" +\n Group.replace(\" \", \"_\")+ \".\" +\n QString((getpwuid(getuid()))->pw_name);\n\n QFile logfile(logfilename);\n\n if (logfile.open(QFile::WriteOnly)) {\n QTextStream stream(&logfile);\n stream << LogEntry;\n logfile.close();\n }\n\n}\n\nvoid MainForm::ReadHerdFile(const QString &herd_file_name)\n{\n QFile file(herd_file_name);\n\n QString herd;\n\n if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n return;\n }\n\n while (!file.atEnd()) {\n QByteArray line = file.readLine();\n if (line.contains('#')) {\n line.truncate(line.indexOf('#'));\n }\n line = line.trimmed();\n if (line.isEmpty()) {\n continue;\n }\n\n if (line.startsWith('[')) {\n if (line.endsWith(']')) {\n line.remove(0,1);\n line.chop(1);\n herd = QString(line);\n ListOfHerds.append(herd);\n }\n } else {\n HerdHash[herd].append(QString(line));\n }\n }\n}\n\n\n//-------------------------------------------------------------\n//\n// WriteErr: for when the user cancels a command or blastcmd\n// reports that it didn't go through\n//\n// *dest: textbox to write into\n// retstatus: what went wrong\n//\n//-------------------------------------------------------------\n\nvoid MainForm::WriteErr(QTextEdit *dest, const char *message, int retstatus) {\n QString txt;\n\n switch (retstatus) {\n case 99:\n txt = \" COMMAND NOT SENT: Cancelled by user.\\n\";\n break;\n case 0:\n txt = \" Command successfully sent.\\n\";\n break;\n case 1:\n txt = \" COMMAND NOT SENT: Improper syntax. (Have you compiled \"\n \"with an up-to-date verison of commands.h?)\\n\\n\";\n break;\n case 2:\n txt = \" COMMAND NOT SENT: Unable to open serial port.\\n\\n\";\n break;\n case 3:\n txt = \" COMMAND NOT SENT: Parameter out of range. (Have you \"\n \"compiled with an up-to-date version of commands.h?)\\n\";\n break;\n case 4:\n txt = \" COMMAND NOT SENT: GSE operator disabled science from \"\n \"sending commands.\\n\";\n break;\n case 5:\n txt = \" COMMAND NOT SENT: Routing address does not match the \"\n \"selected link.\\n\";\n break;\n case 6:\n txt = \" COMMAND NOT SENT: The link selected was not \"\n \"enabled.\\n\";\n break;\n case 7:\n txt = \" COMMAND NOT SENT: Unknown error from ground support \"\n \"computer (0x0d).\\n\";\n break;\n case 8:\n case 9:\n txt = \" COMMAND POSSIBLY NOT SENT: Received a garbage \"\n \"acknowledgement packet.\\n\";\n break;\n case 10:\n txt = \" COMMAND NOT SENT: Cow error: Parameter out of range.\\n\";\n break;\n case 11:\n txt = \" COMMAND NOT SENT: Command not confirmed by user.\\n\";\n break;\n case 12:\n txt = \" COMMAND NOT SENT: Unable to take the conn.\\n\";\n break;\n case 13:\n txt = \" COMMAND POSSIBLY NOT SENT: Timeout waiting for ack from GSE.\\n\";\n break;\n case 17:\n txt = \" COMMAND NOT SENT: Parameter validation failed.\\n\";\n if (message) {\n txt += \" Error: \";\n txt += message;\n txt += \"\\n\";\n }\n break;\n case 18:\n txt = \" COMMAND NOT SENT: Error forwarding command.\\n\";\n break;\n case 19:\n txt = \" COMMAND NOT SENT: Protocol error.\\n\";\n break;\n case 20:\n txt = \" COMMAND NOT SENT: Link/route pair disabled by command server.\\n\";\n break;\n default:\n txt = \" COMMAND POSSIBLY NOT SENT: Unrecognised response from server.\\n\";\n break;\n }\n\n QFile f(LOGFILE);\n if (f.open(QFile::Append | QFile::WriteOnly)) {\n QTextStream stream( &f );\n stream << txt;\n f.close();\n } else {\n fprintf(stderr, \"Cow: could not write log file %s.\\n\", LOGFILE);\n return;\n }\n\n dest->insertPlainText(\"\\n\"+QString(txt));\n dest->moveCursor(QTextCursor::End);\n}\n\nvoid MainForm::WriteErr(QTextEdit *dest, int retstatus) {\n WriteErr(dest, NULL, retstatus);\n}\n\n\n\n\n//-------------------------------------------------------------\n//\n// ReadLog (private): read in the log when Cow starts\n//\n// *dest: the textbox to write to\n//\n//-------------------------------------------------------------\n\nvoid MainForm::ReadLog(QTextEdit *dest) {\n FILE *f;\n char txt[255];\n\n f = fopen(LOGFILE, \"r\");\n dest->setText(\" \");\n\n if (f == NULL) {\n printf(\"Cow: could not read log file %s.\\n\", LOGFILE);\n return;\n }\n\n while(fgets(txt, 255, f) != NULL) {\n txt[strlen(txt) - 1] = '\\0'; // Get rid of the \\n character from each line\n dest->insertPlainText(\"\\n\"+QString(txt));\n }\n dest->insertPlainText(\"\\n\");\n dest->moveCursor(QTextCursor::End);\n}\n\nvoid MainForm::keyPressEvent(QKeyEvent *ev)\n{\n if (SEND_KEY) {\n NSendButton->animateClick(100);\n } else if(dynamic_cast<AbstractCowEntry*>(focusWidget())) {\n QMainWindow::keyPressEvent(ev);\n } else {\n NOmniBox->keyPressEvent(ev);\n }\n}\n\nbool operator<(const MainForm::OmniPair& a,const MainForm::OmniPair&b)\n{\n return a.name<b.name;\n}\n\nbool operator==(const MainForm::OmniPair& a,const MainForm::OmniPair&b)\n{\n return a.name==b.name;\n}\n\nvoid MainForm::PopulateOmnibox()\n{\n // NOmniBox->clear();\n OmniList.clear();\n\n for(int h=0;h<client_n_groups;h++)\n {\n int indexes[client_n_scommands + client_n_mcommands],max;\n\n max = GroupSIndexes(h, indexes);\n max += GroupMIndexes(h, &indexes[max]);\n\n for (int i = 0; i < max; i++) {\n OmniPair pair;\n pair.group=h;\n if (indexes[i] >= client_n_scommands) {\n pair.name=client_mcommands[indexes[i] - client_n_scommands].name;\n } else {\n pair.name=client_scommands[indexes[i]].name;\n }\n //if(!OmniList.contains(pair)) {\n OmniList.push_back(pair);\n //}\n }\n }\n\n qSort(OmniList);\n\n QStringList sl;\n for(int i=0;i<OmniList.size();i++)\n {\n sl.push_back(OmniList[i].name+\" \");\n }\n sl.removeDuplicates();\n\n if(NOmniBox->completer()) {\n delete NOmniBox->completer();\n }\n\n QCompleter *qcomp = new QCompleter(sl);\n //can conceivably use SIGNAL(highlighted) instead, but I think this behaviour is better\n connect(qcomp, SIGNAL(activated(const QString &)), this, SLOT(nOmniBox_completerActivated(const QString &)));\n NOmniBox->setCompleter(qcomp);\n}\n\n//-------------------------------------------------------------\n//\n// MainForm: constructor\n//\n//-------------------------------------------------------------\n\nMainForm::MainForm(const char *cf, const QString &herdfile, int link, QWidget* parent, const char* name,\n Qt::WindowFlags fl) : QMainWindow( parent, fl )\n{\n setObjectName(name?QString(name):\"Cow\");\n int i;\n char tmp[SIZE_NAME + SIZE_ABOUT + SIZE_PARNAME];\n QSize tempsize;\n QPoint point;\n int w1, w2, w3, h1, h2, h3;\n\n QSettings settings(\"University of Toronto\",\"cow\");\n\n restoreGeometry(settings.value(\"geometry\").toByteArray());\n\n ReadHerdFile(herdfile);\n\n _dirfile = NULL;\n\n centralWidget = new QWidget();\n theHLayout = new QHBoxLayout;\n theHLayout->addLayout(theVLayout = new QVBoxLayout());\n\n curfile = cf;\n lastmcmd = -1;\n sending = 0;\n verbose = 0;\n pong = 1;\n\n Images[0] = new QPixmap(\":/icons/lightning00.png\");\n Images[1] = new QPixmap(\":/icons/lightning03.png\");\n Images[2] = new QPixmap(\":/icons/lightning06.png\");\n Images[3] = new QPixmap(\":/icons/lightning09.png\");\n Images[4] = new QPixmap(\":/icons/lightning12.png\");\n Images[5] = new QPixmap(\":/icons/lightning15.png\");\n\n QString username = qgetenv(\"USER\");\n if (username.isEmpty())\n username = qgetenv(\"USERNAME\");\n\n // if not SJB, also work when COW_BUTT environment variable is set\n bool cowbutt = !qgetenv(\"COW_BUTT\").isNull();\n\n if (username == \"sjb\" || cowbutt) {\n Images[0] = new QPixmap(\":/icons/cow0.png\");\n Images[1] = new QPixmap(\":/icons/cow1.png\");\n Images[2] = new QPixmap(\":/icons/cow2.png\");\n Images[3] = new QPixmap(\":/icons/cow3.png\");\n Images[4] = new QPixmap(\":/icons/cow4.png\");\n Images[5] = new QPixmap(\":/icons/cow5.png\");\n }\n\n framenum = 0;\n numframes = 4;\n dir = 1;\n\n sprintf(tmp, \"Command Operations Window (COW, revision.\" COW_SVN_REVISION\n \"); Host: %s; Cmd List: %s\",\n blastcmd_host.toStdString().c_str(), client_command_list_serial);\n\n setWindowTitle(tmp);\n\n NOmniBox = new CowOmniBox(this->centralWidget);\n NOmniBox->setObjectName(\"NFilter\");\n NOmniBox->adjustSize();\n //NOmniBox->setPlaceholderText(\"Awesome Bar\");\n connect(NOmniBox,SIGNAL(textEdited(QString)),this,SLOT(nOmniBox_textEdited(QString)));\n //connect(NOmniBox,SIGNAL(textChanged(QString)),this,SLOT(testTextChanged(QString))); //for debugging\n //connect(NOmniBox,SIGNAL(cursorPositionChanged(int,int)),this,SLOT(testCursorPositionChanged(int,int)));\n theHLayout->addWidget(NOmniBox);\n\n // Lay everything out. Everything is very carefully positioned -- there are\n // no automatic spacers because with the dynamic properties of the program\n // (things popping in and out of existence as different commands are\n // chosen) things would mess up. So the code ain't too pretty . . .\n TabWidget = new QTabWidget(centralWidget);\n tab1 = new QWidget();\n\n NGroupsBox = new QGroupBox(tab1);\n NGroupsBox->setObjectName(\"NGroupsBox\");\n NGroupsBox->setFlat(true);\n //theVLayout->addWidget(NGroupsBox);\n\n NGroupsLayout = new QGridLayout(NGroupsBox);\n NGroupsLayout->setAlignment(Qt::AlignTop);\n NGroupsLayout->setSpacing(1);\n NGroupsLayout->setMargin(5);\n\n NGroups = new QRadioButton*[client_n_groups];\n for (i = 0; i < client_n_groups; i++) {\n NGroups[i] = new QRadioButton(NGroupsBox);\n //connect(NGroups[i],SIGNAL(clicked()),NOmniBox,SLOT(clear()));\n connect(NGroups[i],SIGNAL(toggled(bool)),this,SLOT(ChangeCommandList(bool)));\n NGroups[i]->setObjectName(\"QGroup\");\n NGroups[i]->setText(tr(client_group_names[i]));\n tempsize = NGroups[i]->sizeHint();\n NGroupsLayout->addWidget(NGroups[i], int(i/3), (i%3));\n }\n\n TabWidget->addTab(tab1,\"Default\");\n\n tab2 = new QWidget();\n HerdGroupBox = new QGroupBox(tab2);\n HerdGroupBox->setObjectName(\"NGroupsBox\");\n HerdGroupBox->setFlat(true);\n\n HerdGroupsLayout = new QGridLayout(HerdGroupBox);\n HerdGroupsLayout->setAlignment(Qt::AlignTop);\n HerdGroupsLayout->setSpacing(1);\n HerdGroupsLayout->setMargin(5);\n\n HerdGroups = new QRadioButton*[ListOfHerds.length()];\n for (i = 0; i < ListOfHerds.length(); i++) {\n HerdGroups[i] = new QRadioButton(HerdGroupBox);\n connect(HerdGroups[i],SIGNAL(toggled(bool)),this,SLOT(ChangeCommandList(bool)));\n //HerdGroups[i]->setObjectName(\"QGroup\");\n HerdGroups[i]->setText(ListOfHerds.at(i));\n HerdGroupsLayout->addWidget(HerdGroups[i], int(i/3), (i%3));\n }\n\n TabWidget->addTab(tab2, \"Custom\");\n\n theVLayout->addWidget(TabWidget);\n connect(TabWidget, SIGNAL(currentChanged(int)), this, SLOT(ChangeCommandList()));\n\n NTopFrame = new QFrame(this->centralWidget);\n NTopFrame->setObjectName(\"NTopFrame\");\n NTopFrame->setFrameShape(QFrame::Box);\n NTopFrame->setFrameShadow(QFrame::Sunken);\n theVLayout->addWidget(NTopFrame);\n\n\n NCommandList = new QListWidget(this->centralWidget);\n NCommandList->setSelectionMode(QAbstractItemView::SingleSelection);\n NCommandList->setObjectName(\"NCommandList\");\n NCommandList->adjustSize();\n NCommandList->setGeometry(PADDING, PADDING+120, NCommandList->width(), 0);\n connect(NCommandList, SIGNAL(currentRowChanged(int)), this, SLOT(ChooseCommand()));\n connect(NCommandList, SIGNAL(clicked(QModelIndex)), this, SLOT(ChooseCommand()));\n theHLayout->addWidget(NCommandList);\n\n w1 = 0;\n\n strcpy(tmp, LongestParam());\n for (i = 0; i < MAX_N_PARAMS; i++) {\n NParamLabels[i] = new QLabel(NTopFrame);\n NParamLabels[i]->setObjectName(\"NParamLabel\");\n NParamLabels[i]->setText(tr(tmp));\n NParamLabels[i]->setAlignment(Qt::AlignHCenter);\n NParamLabels[i]->adjustSize();\n w2 = NParamLabels[i]->width();\n\n NParamFields[i] = new CowDoubleEntry(NTopFrame, \"NParamLabels\");\n connect(dynamic_cast<CowDoubleEntry*>(NParamFields[i]),\n SIGNAL(valueEdited()),this,SLOT(OmniSync()));\n\n NParamFields[i]->setFixedWidth(w2/2);\n NParamFields[i]->adjustSize();\n\n w3 = NParamFields[i]->width();\n h2 = NParamLabels[i]->height();\n h3 = NParamFields[i]->height();\n\n point.setX(w1 + 2 * PADDING + (i % 2) * (w2 + w3 + PADDING));\n NParamLabels[i]->setGeometry(point.x(), 0, w2, h2);\n\n point.setX(w1 + PADDING + (i % 2) * (w2 + w3 + PADDING) + w2);\n NParamFields[i]->setGeometry(point.x(), 0, w3, h3);\n if (i>0) {\n setTabOrder(NParamFields[i-1], NParamFields[i]);\n }\n }\n\n memset(tmp, 'B', SIZE_ABOUT);\n tmp[SIZE_ABOUT] = '\\0';\n\n NAboutLabel = new QLabel(NTopFrame);\n NAboutLabel->setObjectName(\"NAboutLabel\");\n NAboutLabel->setFrameShape(QFrame::Box);\n NAboutLabel->setFrameShadow(QFrame::Plain);\n NAboutLabel->setText(tr(tmp));\n NAboutLabel->setWordWrap(1);\n NAboutLabel->setAlignment(Qt::AlignLeft);\n NAboutLabel->setGeometry(0, 0, 2 * (w2 + w3 + PADDING) + SPACING * 4, 0);\n tempsize = NAboutLabel->sizeHint();\n NAboutLabel->setGeometry(PADDING , PADDING*2, 2 * (w2 + w3 + PADDING)\n + SPACING * 4, tempsize.height());\n\n h1 = NAboutLabel->height()+PADDING;\n for (i = 0; i < MAX_N_PARAMS; i++) {\n w2 = NParamLabels[i]->width();\n w3 = NParamFields[i]->width();\n h2 = NParamLabels[i]->height();\n h3 = NParamFields[i]->height();\n\n point.setX(w1 + 2 * PADDING + (i%2) * (w2 + w3 + PADDING + SPACING * 4));\n point.setY(h1 + 2 * PADDING + int(i/2) * (h3 + SPACING) + int((h3 - h2)/2));\n NParamLabels[i]->setGeometry(point.x(), point.y(), w2, h2);\n\n point.setX(w1 + 3 * PADDING + i * (w2 + w3 + PADDING + SPACING * 4) + w2 -\n 2 * int(i/2) * (w2 + w3 + PADDING + SPACING * 4));\n point.setY(h1 + 2 * PADDING + int(i/2) * (h3 + SPACING));\n NParamFields[i]->setGeometry(point.x(), point.y(), w3, h3);\n\n NParamFields[i]->hide();\n NParamLabels[i]->hide();\n }\n\n NCurFile = new QLineEdit(NTopFrame);\n NCurFile->setObjectName(\"NCurFile\");\n NCurFile->setText(tr(curfile.toLatin1()));\n NCurFile->adjustSize();\n QCompleter* completer=new QCompleter;\n completer->setModel(new QDirModel(completer));\n NCurFile->setCompleter(completer);\n\n NHost = new QPushButton(NTopFrame);\n NHost->setObjectName(\"NHost\");\n NHost->setText(blastcmd_host);\n connect(NHost,SIGNAL(clicked()),this,SLOT(ChangeHost()));\n\n NSendMethod = new QComboBox(NTopFrame);\n NSendMethod->setObjectName(\"NSendMethod\");\n NSendMethod->addItem(tr(\"LOS\"));\n NSendMethod->addItem(tr(\"TDRSS\"));\n NSendMethod->addItem(tr(\"Iridum\"));\n NSendMethod->addItem(tr(\"Pilot\"));\n NSendMethod->adjustSize();\n NSendMethod->setCurrentIndex(link);\n\n NSendRoute = new QComboBox(NTopFrame);\n NSendRoute->setObjectName(\"NSendRoute\");\n NSendRoute->addItem(tr(\"COMM 1\"));\n NSendRoute->addItem(tr(\"COMM 2\"));\n NSendRoute->adjustSize();\n\n NVerbose = new QCheckBox(NTopFrame);\n NVerbose->setObjectName(\"NVerbose\");\n NVerbose->setText(tr(\"Verbose\"));\n NVerbose->setChecked(false);\n NVerbose->adjustSize();\n\n NCurFile->setGeometry(\n PADDING,\n PADDING + 2 * PADDING + h1 + (int((2 + MAX_N_PARAMS) / 2)) * (h3 + SPACING) - NCurFile->height(),\n NCurFile->width()*1.5,\n NCurFile->height());\n\n NHost->setGeometry(\n 3*PADDING+NCurFile->width(),\n PADDING + 2 * PADDING + h1 + (int((2 + MAX_N_PARAMS) / 2)) * (h3 + SPACING) - NCurFile->height(),\n NCurFile->width()*(1.0/1.5),\n NCurFile->height());\n\n NSendMethod->setGeometry(\n 4*PADDING+NCurFile->width()+NHost->width(),\n NCurFile->y(),\n NSendMethod->width(),\n NCurFile->height());\n\n NSendRoute->setGeometry(\n 5*PADDING+NCurFile->width()+NHost->width()+NSendMethod->width(),\n NCurFile->y(),\n NSendRoute->width(),\n NCurFile->height());\n\n NVerbose->setGeometry(\n 6*PADDING+NCurFile->width()+NHost->width()+NSendMethod->width()+NSendRoute->width(),\n NCurFile->y(),\n NVerbose->width(),\n NCurFile->height());\n\n NTopFrame->adjustSize();\n\n NGroupsBox->adjustSize();\n NGroupsBox->setGeometry(0,0,NTopFrame->width(), NGroupsBox->height());\n\n HerdGroupBox->adjustSize();\n HerdGroupBox->setGeometry(0,0,NTopFrame->width(), HerdGroupBox->height());\n\n int xleft = 2 * PADDING + NCommandList->width();\n int ytop = PADDING*2+25;\n int width = NTopFrame->width();\n int height = TabWidget->tabBar()->height()+NGroupsBox->height()+2*PADDING;\n\n TabWidget->adjustSize();\n TabWidget->setGeometry(xleft, ytop, width, height);\n\n NTopFrame->adjustSize();\n ytop = ytop + height;\n width = NTopFrame->width();\n height = NTopFrame->height();\n NTopFrame->setGeometry(xleft, ytop, width, height);\n\n NBotFrame = new QFrame(this->centralWidget);\n NBotFrame->setObjectName(\"NBotFrame\");\n NBotFrame->setFrameShape(QFrame::Box);\n NBotFrame->setFrameShadow(QFrame::Sunken);\n theVLayout->addWidget(NBotFrame);\n\n NSendButton = new QPushButton(NBotFrame);\n NSendButton->setObjectName(\"NSendButton\");\n NSendButton->setText(tr(\"Send (\" SEND_KEY_NAME \")\"));\n NSendButton->adjustSize();\n NSendButton->setDisabled(true);\n\n NWaitImage = new QLabel(NBotFrame);\n NWaitImage->setText(\"NWaitImage\");\n NWaitImage->setScaledContents(false);\n NWaitImage->setPixmap(*Images[0]);\n NWaitImage->adjustSize();\n NWaitImage->setGeometry(\n NTopFrame->width() - NWaitImage->width() - PADDING,\n PADDING,\n NSendButton->width(),\n NWaitImage->height());\n\n\n NSendButton->setGeometry(\n NTopFrame->width() - NWaitImage->width() - PADDING,\n PADDING+NWaitImage->height(),\n NSendButton->width(),\n NSendButton->height());\n\n NLog = new QTextEdit(NBotFrame);\n NLog->setObjectName(\"NLog\");\n NLog->setReadOnly(true);\n NLog->setGeometry(\n PADDING,\n PADDING,\n NTopFrame->width() - NWaitImage->width() - 3 * PADDING,\n PADDING + NWaitImage->height()+NSendButton->height());\n\n ReadLog(NLog);\n\n NBotFrame->adjustSize();\n\n ytop = ytop + NTopFrame->height();\n\n NBotFrame->setGeometry(xleft, ytop, NTopFrame->width(),\n NBotFrame->height());\n\n NOmniBox->setGeometry(PADDING,PADDING,NCommandList->width()+PADDING+NTopFrame->width(),25);\n\n NCommandList->setGeometry(PADDING, PADDING+NOmniBox->height()+PADDING,\n NCommandList->width(), ytop+NBotFrame->height()-25-2*PADDING);\n\n timer = new QTimer(this);\n timer->setObjectName(\"image_timer\");\n timer->start(WAIT_TIME);\n\n ChangeCommandList();\n ChooseCommand();\n\n setCentralWidget(centralWidget);\n\n theStatusBar = statusBar();\n theStatusBar->setSizeGripEnabled(false);\n\n ConnBanner = new QLabel(theStatusBar);\n ConnBanner->setText(NetCmdBanner());\n theStatusBar->addWidget(ConnBanner);\n\n w1 = NCommandList->width() + NGroupsBox->width() + 2 * PADDING + SPACING;\n h1 = NCommandList->height() + theStatusBar->height() + NOmniBox->height();\n\n setMinimumSize(w1, h1);\n setMaximumSize(w1, h1);\n\n ping_timer = new QTimer(this);\n ping_timer->setObjectName(\"ping_timer\");\n ping_timer->start(PING_TIME);\n\n PopulateOmnibox();\n\n connect(NSendButton, SIGNAL(clicked()), this, SLOT(SendCommand()));\n connect(timer, SIGNAL(timeout()), this, SLOT(Tick()));\n connect(ping_timer, SIGNAL(timeout()), this, SLOT(Ping()));\n\n NGroups[0]->setChecked(true);\n\n NOmniBox->setFocus();\n}\n\nMainForm::~MainForm()\n{\n Quit();\n delete _dirfile;\n _dirfile = NULL;\n\n for (int i = 0; i < 6; i++)\n delete Images[i];\n\n delete theVLayout;\n delete theHLayout;\n delete centralWidget;\n delete theStatusBar;\n}\n\n\n//***************************************************************************\n//**** Main()\n//***************************************************************************\n\n// Who ever though raising SIGABRT when QApplication couldn't connect to the\n// display would be a good idea?\nvoid handle_sigabrt(int sig)\n{\n Q_UNUSED(sig);\n std::cerr << \"The Cow says: \\\"I can't connect to your DISPLAY.\" << std::endl;\n std::cerr << \" Have you tried 'ssh -YC'?\\\"\" << std::endl;\n exit(1);\n}\n\nvoid USAGE() {\n fprintf(stderr, \"USAGE:\\n\"\n \"cow <command host>\\n\"\n \"or\\n\"\n \"cow <options>\\n\"\n \"\\n\"\n \"Options:\\n\"\n \"-h print this message\\n\"\n \"-c <command host>\\n\"\n \"-H <herd file>\\n\");\n exit(1);\n}\n\nDefaults *defaults;\nint main(int argc, char* argv[]) {\n\n // Catch QApplication's SIGABRT\n signal(SIGABRT, &handle_sigabrt);\n QApplication app(argc, argv);\n\n // Clear signal handler\n signal(SIGABRT, SIG_DFL);\n QApplication::setOrganizationName(\"University of Toronto\");\n QApplication::setApplicationName(\"cow\");\n\n /* Host determination */\n if (argc == 2) {\n if (argv[1][0] == '-') {\n USAGE();\n } else {\n blastcmd_host = QString(argv[1]);\n };\n } else {\n QString argv_i;\n for (int i = 1; i<argc; i++) {\n argv_i = QString(argv[i]);\n if (argv_i == \"-h\") {\n USAGE();\n } else if (argv_i == \"-c\") {\n i++;\n if (i>=argc) USAGE();\n blastcmd_host = QString(argv[i]);\n } else if (argv_i == \"-H\") {\n i++;\n if (i>=argc) USAGE();\n herdfile = QString(argv[i]);\n } else {\n USAGE();\n }\n }\n }\n\n QSettings settings(\"University of Toronto\",\"cow\");\n\n /* Link Determination */\n int link = settings.value(\"link\", 0).toInt();\n\n if (blastcmd_host.isEmpty()) {\n blastcmd_host = settings.value(\"blastcmd_host\",QString(\"widow\\0\")).toString();\n }\n\n if (herdfile.isEmpty()) {\n herdfile = settings.value(\"blastcmd_herdfile\",QString(\"widow\\0\")).toString();\n }\n\n if (!herdfile.endsWith(\".herd\")) {\n herdfile = herdfile + \".herd\";\n }\n\n if (!QFile::exists(herdfile)) {\n herdfile = QString(HERDFILEDIR) + herdfile;\n }\n\n QFileInfo herd_fileinfo(herdfile);\n\n herdfile = herd_fileinfo.canonicalFilePath();\n printf(\"%s\\n\", herdfile.toLatin1().constData());\n if (!QFile::exists(herdfile)) {\n printf(\"warning: herdfile (%s) does not exist\\n\", herdfile.toLatin1().constData());\n }\n\n settings.setValue(\"blastcmd_host\",QString(blastcmd_host));\n settings.setValue(\"blastcmd_herdfile\",QString(herdfile));\n\n int retCode=1337;\n while(retCode==1337) {\n int n;\n /* Client negotiation */\n stop_comms = 0;\n missed_pongs = 0;\n while ((n = NetCmdConnect(blastcmd_host.toStdString().c_str(), 1, 0)) < 0) {\n if (n == -16) { /* unauthorised */\n bool ok;\n blastcmd_host=QInputDialog::getText(0, \"Unauthorised\",\n \"You are not authorised to use the blastcmd daemon on \" +\n QString(blastcmd_host) + \". Try another hostname.\",\n QLineEdit::Normal,QString(blastcmd_host),&ok).toLatin1();\n if (!ok)\n exit(16);\n } else {\n //retry if connection refused (HACK! fixes bug in blastcmd\n //authentication)\n sleep(1);\n printf(\"Trying to connect one more time\\n\");\n if (NetCmdConnect(blastcmd_host.toStdString().c_str(), 1, 0) < 0) {\n bool ok;\n blastcmd_host=QInputDialog::getText(0, \"Bad host\",\n \"Could not connect to \" + QString(blastcmd_host) +\n \" or blastcmd daemon. Try another hostname.\",\n QLineEdit::Normal,QString(blastcmd_host),&ok).toLatin1();\n if (!ok)\n exit(16);\n }\n }\n }\n if (NetCmdGetCmdList())\n return -1;\n if (NetCmdGetGroupNames())\n return -1;\n\n\n defaults = new Defaults();\n\n QSettings settings;\n QString curfile=settings.value(\"curfile\",QString(\"\")).toString();\n if(curfile.isEmpty()) {\n curfile= \"/data/etc/mole.lnk\"; //QFileDialog::getExistingDirectory(0,\"Choose a curdir\");\n }\n\n\n MainForm moo(curfile.toStdString().c_str(), herdfile, link, 0, \"moo\", 0);\n moo.show();\n retCode= app.exec();\n NetCmdDrop();\n }\n return retCode;\n}\n\n// vim: ts=2 sw=2 et\n" }, { "alpha_fraction": 0.714628279209137, "alphanum_fraction": 0.7242206335067749, "avg_line_length": 20.947368621826172, "blob_id": "1de5e97dc52d85a4d9b7f2b390af307a8384f5bb", "content_id": "be89317a09884baf3a139484fc966e5f8003cff5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 418, "license_type": "no_license", "max_line_length": 73, "num_lines": 19, "path": "/stars/code/housekeeping/logger.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef HOUSEKEEPING__LOGGER_H\n#define HOUSEKEEPING__LOGGER_H\n\n#include \"../logging/logger.h\"\n\nnamespace Housekeeping\n{\n // To be used only by the housekeeper\n extern Logging::Logger logger;\n}\n\n#endif\n" }, { "alpha_fraction": 0.7008547186851501, "alphanum_fraction": 0.7008547186851501, "avg_line_length": 13.625, "blob_id": "47511e235169c5ca1b576d73ab7fe34af91718ca", "content_id": "5b3248884d993affbfcbf4855b26f52cae0d7de8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 117, "license_type": "no_license", "max_line_length": 30, "num_lines": 8, "path": "/balloon_cam/server/Makefile", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "all: server\n.PHONY: clean\n\nserver: main.o server.o\n\tg++ -o server main.o server.o\n\nclean:\n\trm server server.o main.o\n" }, { "alpha_fraction": 0.4799172282218933, "alphanum_fraction": 0.5039902925491333, "avg_line_length": 32.60706329345703, "blob_id": "c45b8797e72e46795e170249d1c8d4a24130d3c9", "content_id": "e590bfd31c7d5a4cf76735ec1468bded264e9683", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 30449, "license_type": "no_license", "max_line_length": 118, "num_lines": 906, "path": "/common/sip.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* mcp: the BLAST master control program\n *\n * commands.c: functions for listening to and processing commands\n *\n * This software is copyright (C) 2002-2010 University of Toronto\n *\n * This file is part of mcp.\n *\n * mcp 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n/* Define this symbol to have mcp log all SIP traffic */\n#undef SIP_CHATTER\n#undef VERBOSE_SIP_CHATTER\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <termios.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <math.h>\n#include <pthread.h>\n#include <limits.h>\n\n#include \"netcmd.h\"\n#include \"sip.h\"\n#include \"blast.h\"\n#include \"command_common.h\"\n#include \"command_struct.h\"\n#include \"commands.h\"\n#include \"mcp.h\"\n\n#define REQ_POSITION 0x50\n#define REQ_TIME 0x51\n#define REQ_ALTITUDE 0x52\n#define SLOWDL_SYNC 0x53\n\n#define SLOWDL_LEN 255\n\n#define SLOWDL_DLE 0x10\n#define SLOWDL_ETX 0x03\n\n/* Seconds since 0TMG jan 1 1970 */\n#define SUN_JAN_6_1980 315964800L\n/* Seconds in a week */\n#define SEC_IN_WEEK 604800L\n\n#define EXT_SLOT 1\n#define EXT_ICHUNK 2\n#define EXT_NCHUNK 3\n#define EXT_NSCHED 4\n#define EXT_ROUTE 5\n\n#define MAXLIB 65536\n\n#define MAX_RTIME 65536.0\n#define MAX_DAYS 26.0\n\nvoid nameThread(const char*); /* mcp.c */\nvoid fillDLData(unsigned char *b, int len); /* slowdl.c */\nvoid fillSBData(unsigned char *b, int len); /* highrate.c */\n\nextern pthread_mutex_t mutex;\n\nchar lst0str[82] = \"\\0\";\n\nvoid SingleCommand(enum singleCommand command, int scheduled); // commands.c\nvoid MultiCommand(enum multiCommand command, double *rvalues,\n int *ivalues, char svalues[][CMD_STRING_LEN], int scheduled); // commands.c\n\n\nint sip_setserial(const char *input_tty, int verbosity)\n{\n int fd;\n struct termios term;\n if (verbosity > 0) blast_info(\"Connecting to sip port %s...\", input_tty);\n\n if ((fd = open(input_tty, O_RDWR)) < 0) {\n if (verbosity > 0) blast_err(\"Unable to open serial port\");\n return -1;\n }\n if (tcgetattr(fd, &term)) {\n if (verbosity > 0) blast_err(\"Unable to get serial device attributes\");\n return -1;\n }\n\n term.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);\n term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);\n term.c_iflag |= INPCK;\n term.c_cc[VMIN] = 0;\n term.c_cc[VTIME] = 0;\n\n term.c_cflag &= ~(CSTOPB | CSIZE);\n term.c_oflag &= ~(OPOST);\n term.c_cflag |= CS8;\n\n if (cfsetospeed(&term, B1200)) { /* <======= SET THE SPEED HERE */\n if (verbosity > 0) blast_err(\"Error setting serial output speed\");\n if (fd >= 0) close(fd);\n return -1;\n }\n\n if (cfsetispeed(&term, B1200)) { /* <======= SET THE SPEED HERE */\n if (verbosity > 0) blast_err(\"Error setting serial input speed\");\n if (fd >= 0) close(fd);\n return -1;\n }\n\n if (tcsetattr(fd, TCSANOW, &term)) {\n if (verbosity > 0) blast_err(\"Unable to set serial attributes\");\n if (fd >= 0) close(fd);\n return -1;\n }\n return fd;\n}\n\nstatic float ParseGPS(unsigned char *data)\n{\n char exponent;\n char sign;\n uint32_t mantissa_bits;\n float mantissa;\n int i;\n\n mantissa = 0;\n mantissa_bits = 0;\n sign = 0;\n exponent = 0;\n\n /* N.B. that the data bytes are received in backwards order */\n\n if (((*(data + 3) >> 7) & 0x01) == 1) /* First bit encodes the sign */\n sign = -1;\n else\n sign = 1;\n\n exponent = ((*(data + 3) << 1) & 0xFF) + ((*(data + 2) >> 7) & 0x01) - 127;\n /* Next eight bits = exponent + 127 */\n\n /* Mantissa contained in last 23 bits */\n mantissa_bits = ((*(data + 2) & 0x7F) << 16) + (*(data + 1) << 8) + *data;\n\n for (i = 23; i >= 0; i--) { /* Construct mantissa = Sigma 2^n */\n if ((mantissa_bits >> i) & 0x01)\n mantissa += pow(2, i - 23);\n }\n\n return((mantissa + 1) * pow(2, exponent) * sign);\n}\n\nint SendRequest(int req, char tty_fd)\n{\n unsigned char buffer[3];\n\n buffer[0] = 0x10;\n buffer[1] = req;\n buffer[2] = 0x03;\n\n#ifdef VERBOSE_SIP_CHATTER\n blast_info(\"sending to SIP %02x %02x %02x\\n\",\n buffer[0], buffer[1], buffer[2]);\n#endif\n\n if (write(tty_fd, buffer, 3) < 0) {\n berror(warning, \"error sending SIP request\\n\");\n return 0;\n }\n return 1;\n}\n\n\n\nenum singleCommand SCommand(char *cmd) //---------------------\n{\n int i;\n\n for (i = 0; i < N_SCOMMANDS; i++) {\n if (strcmp(scommands[i].name, cmd) == 0)\n return scommands[i].command;\n }\n\n return -1;\n}\n\nenum multiCommand MCommand(char *cmd)\n{\n int i;\n\n for (i = 0; i < N_MCOMMANDS; i++) {\n if (strcmp(mcommands[i].name, cmd) == 0)\n return mcommands[i].command;\n }\n\n return -1;\n}\n\nstatic void SetParametersFifo(enum multiCommand command, uint16_t *dataq, double* rvalues, int* ivalues,\n char svalues[][CMD_STRING_LEN])\n{\n int i, dataqind;\n char type;\n int index = MIndex(command);\n\n char** dataqc = (char**) dataq;\n /* compute renormalised values - SIPSS FIFO version */\n blast_info(\"Multiword Command: %s (%d)\\n\", MName(command), command);\n\n for (i = dataqind = 0; i < mcommands[index].numparams; ++i) {\n type = mcommands[index].params[i].type;\n if (type == 'i') /* 15 bit unsigned integer */ {\n ivalues[i] = atoi(dataqc[dataqind++]);\n blast_info(\"param%02i: integer: %i\\n\", i, ivalues[i]);\n } else if (type == 'l') /* 30 bit unsigned integer */ {\n ivalues[i] = atoi(dataqc[dataqind++]);\n blast_info(\"param%02i: long : %i\\n\", i, ivalues[i]);\n } else if (type == 'f') /* 15 bit floating point */ {\n rvalues[i] = atof(dataqc[dataqind++]);\n blast_info(\"param%02i: float : %f\\n\", i, rvalues[i]);\n } else if (type == 'd') { /* 30 bit floating point */\n rvalues[i] = atof(dataqc[dataqind++]);\n blast_info(\"param%02i: double : %f\\n\", i, rvalues[i]);\n } else if (type == 's') { /* string */\n strncpy(svalues[i], dataqc[dataqind++], CMD_STRING_LEN - 1);\n svalues[i][CMD_STRING_LEN - 1] = 0;\n blast_info(\"param%02i: string: %s\\n\", i, svalues[i]);\n } else {\n blast_err(\"Unknown parameter type ('%c') param%02i: ignored\", type, i);\n }\n }\n}\n\nstatic void SetParameters(enum multiCommand command, uint16_t *dataq, double* rvalues, int* ivalues,\n char svalues[][CMD_STRING_LEN])\n{\n int i, dataqind;\n char type;\n int index = MIndex(command);\n double min;\n\n /* compute renormalised values */\n for (i = dataqind = 0; i < mcommands[index].numparams; ++i) {\n min = mcommands[index].params[i].min;\n type = mcommands[index].params[i].type;\n if (type == 'i') /* 16 bit unsigned integer */ {\n ivalues[i] = dataq[dataqind++] + mcommands[index].params[i].min;\n blast_info(\"param%02i: integer: %i\\n\", i, ivalues[i]);\n } else if (type == 'l') /* 32 bit unsigned integer */ {\n ivalues[i] = dataq[dataqind++] + mcommands[index].params[i].min;\n ivalues[i] += (dataq[dataqind++] << 16);\n blast_info(\"param%02i: long : %i\\n\", i, ivalues[i]);\n } else if (type == 'f') /* 16 bit floating point */ {\n rvalues[i] = (float) dataq[dataqind++] * (mcommands[index].params[i].max - min) / USHRT_MAX + min;\n blast_info(\"param%02i: float : %f\\n\", i, rvalues[i]);\n } else if (type == 'd') { /* 32 bit floating point */\n rvalues[i] = (float) ((unsigned) dataq[dataqind++] << 16); /* upper 16 bits */\n rvalues[i] += (float) dataq[dataqind++]; /* lower 16 bits */\n rvalues[i] = rvalues[i] * (mcommands[index].params[i].max - min) /\n UINT_MAX\n + min;\n blast_info(\"param%02i: double : %f\\n\", i, rvalues[i]);\n } else if (type == 's') { /* string of 7-bit characters */\n int j;\n for (j = 0; j < mcommands[index].params[i].max; ++j)\n svalues[i][j] = ((j % 2) ? dataq[dataqind++] : dataq[dataqind] >> 8) & 0x7f;\n blast_info(\"param%02i: string: %s\\n\", i, svalues[i]);\n } else {\n blast_err(\"Unknown parameter type ('%c') param%02i: ignored\", type, i);\n }\n }\n}\n\nstatic void GPSPosition(unsigned char *indata)\n{\n double lat;\n\n SIPData.GPSstatus1 = *(indata + 12);\n SIPData.GPSstatus2 = *(indata + 13);\n\n lat = ParseGPS(indata + 4);\n if (fabs(lat) > 20) {\n SIPData.GPSpos.lat = lat;\n SIPData.GPSpos.lon = ParseGPS(indata); /* sip sends east lon */\n /* end of hack */\n\n SIPData.GPSpos.alt = ParseGPS(indata + 8);\n\n// WritePrevStatus();\n }\n}\n\nvoid ScheduledCommand(struct ScheduleEvent *event)\n{\n if (event->is_multi) {\n int i;\n int index = MIndex(event->command);\n\n blast_info(\"Executing Scheduled Command: %s (%i)\\n\",\n MName(event->command), event->command);\n for (i = 0; i < mcommands[index].numparams; ++i) {\n int type = mcommands[index].params[i].type;\n if (type == 'i') /* 15 bit unsigned integer */\n blast_info(\"param%02i: integer: %i\\n\", i,\n event->ivalues[i]);\n else if (type == 'l') /* 30 bit unsigned integer */\n blast_info(\"param%02i: long : %i\\n\", i,\n event->ivalues[i]);\n else if (type == 'f') /* 15 bit floating point */\n blast_info(\"param%02i: float : %f\\n\", i,\n event->rvalues[i]);\n else if (type == 'd') /* 30 bit floating point */\n blast_info(\"param%02i: double : %f\\n\", i,\n event->rvalues[i]);\n else\n blast_err(\"Unknown parameter type ('%c') param%02i: ignored\", type, i);\n }\n MultiCommand(event->command, event->rvalues, event->ivalues, event->svalues,\n 1);\n\n } else {\n blast_info(\"Executing Scheduled Command: %s (%i)\\n\",\n SName(event->command), event->command);\n SingleCommand(event->command, 1);\n }\n}\n\nstatic void GPSTime(unsigned char *indata)\n{\n float GPStime, offset;\n int CPUtime, GPSweek;\n\n /* Send new information to CommandData */\n\n GPStime = ParseGPS(indata);\n GPSweek = *((uint16_t*)(indata + 4));\n offset = ParseGPS(indata + 6);\n CPUtime = ParseGPS(indata + 10);\n\n SIPData.GPStime.UTC = (int)(SEC_IN_WEEK * (GPSweek) + GPStime - offset) +\n SUN_JAN_6_1980;\n SIPData.GPStime.CPU = CPUtime;\n\n// WritePrevStatus();\n}\n\nstatic void MKSAltitude(unsigned char *indata)\n{\n SIPData.MKSalt.hi = ((uint16_t *)indata)[0];;\n SIPData.MKSalt.med = ((uint16_t *)indata)[1];;\n SIPData.MKSalt.lo = ((uint16_t *)indata)[2];;\n\n// WritePrevStatus();\n}\n\n/* Send TDRSS Low Rate Packet */\n\nstatic void SendDownData(char tty_fd)\n{\n unsigned char buffer[3 + SLOWDL_LEN + 1] = {0};\n\n buffer[0] = SLOWDL_DLE;\n buffer[1] = SLOWDL_SYNC;\n buffer[2] = SLOWDL_LEN;\n // updateSlowDL();\n // fillDLData(buffer+3, SLOWDL_LEN);\n fillSBData(buffer+3, SLOWDL_LEN);\n blast_info(\"Sending slowdl data\\n\");\n\n buffer[3 + SLOWDL_LEN] = SLOWDL_ETX;\n if (write(tty_fd, buffer, 3 + SLOWDL_LEN + 1) < 0) {\n berror(warning, \"Error writing to SlowDL\\n\");\n }\n}\n\n/* compute the size of the data queue for the given command */\nstatic int DataQSize(int index)\n{\n int i, size = mcommands[index].numparams;\n\n for (i = 0; i < mcommands[index].numparams; ++i)\n if (mcommands[index].params[i].type == 'd'\n || mcommands[index].params[i].type == 'l')\n size++;\n else if (mcommands[index].params[i].type == 's')\n size += (mcommands[index].params[i].max - 1) / 2;\n\n return size;\n}\n\nvoid WatchFIFO(void* void_other_ip)\n{\n unsigned char buf[1];\n char command[100];\n char pbuf[30];\n int fifo;\n\n int mcommand = -1;\n int mcommand_count = 0;\n char *mcommand_data[DATA_Q_SIZE];\n\n int i;\n char other_ip[100] = \"@localhost\";\n\n if (void_other_ip)\n snprintf(other_ip, sizeof(other_ip), \"@%s\", (char*)void_other_ip);\n\n nameThread(\"FIFO\");\n for (i = 0; i < DATA_Q_SIZE; ++i) {\n mcommand_data[i] = NULL;\n }\n\n double rvalues[MAX_N_PARAMS];\n int ivalues[MAX_N_PARAMS];\n char svalues[MAX_N_PARAMS][CMD_STRING_LEN];\n\n int index, pindex = 0;\n\n bputs(startup, \"WatchFIFO startup\\n\");\n\n if ((fifo = open(\"/data/etc/SIPSS.FIFO\", O_RDONLY | O_NONBLOCK)) == -1)\n berror(tfatal, \"Unable to open FIFO\");\n\n for (;;) {\n index = 0;\n do {\n /* Loop until data come in */\n while (read(fifo, buf, 1) <= 0)\n usleep(10000); /* sleep for 10ms */\n command[index++] = buf[0];\n }while (buf[0] != '\\n');\n command[index - 1] = command[index] = 0;\n// blast_info(\"Command received: %s\\n\", command);\n\n index = -1;\n while ((command[++index] != ' ') && command[index])\n continue;\n command[index++] = 0;\n\n pindex = 0;\n mcommand_count = 0;\n do {\n if ((command[index] == ' ' || command[index] == 0) && pindex > 0) {\n pbuf[pindex] = 0;\n mcommand_data[mcommand_count] =\n reballoc(tfatal, mcommand_data[mcommand_count], pindex + 2);\n\n strncpy(mcommand_data[mcommand_count++], pbuf, pindex + 1);\n blast_info(\"mcommand_count = %d, mcommand_data[mcommand_count] = %s\",\n mcommand_count - 1, mcommand_data[mcommand_count-1]);\n pindex = 0;\n } else {\n pbuf[pindex++] = command[index];\n }\n }while (command[index++] != 0);\n blast_info(\"%i parameters found.\\n\", mcommand_count);\n\n pthread_mutex_lock(&mutex);\n\n /* Process data */\n if (mcommand_count == 0) {\n mcommand = SCommand(command);\n SingleCommand(mcommand, 0);\n mcommand = -1;\n } else {\n mcommand = MCommand(command);\n// bputs(info, \"Multi word command received\\n\");\n printf(\"%s\\n\", command);\n if (mcommand_count == mcommands[MIndex(mcommand)].numparams) {\n SetParametersFifo(mcommand, (uint16_t*)mcommand_data, rvalues,\n ivalues, svalues);\n MultiCommand(mcommand, rvalues, ivalues, svalues, 0);\n } else {\n bputs(warning, \"Ignoring mal-formed command!\\n\");\n }\n mcommand = -1;\n }\n\n /* Relinquish control of memory */\n pthread_mutex_unlock(&mutex);\n }\n}\n\n\nstruct LibraryStruct\n{\n int n;\n int entry[MAXLIB];\n char cmd[MAXLIB][64];\n char params[MAXLIB][256];\n};\n\nstruct LibraryStruct library;\n\nvoid OpenLibrary()\n{\n FILE *fp;\n char instr[1024];\n int nf;\n int i;\n\n fp = fopen(\"/data/etc/blast/sched.library\", \"r\");\n if (fp == NULL) {\n berror(fatal, \"Could not open schedule file library.\");\n exit(0);\n }\n\n i = 0;\n while (fgets(instr, 256, fp) != NULL) {\n memset(library.params[i], 0, 256);\n nf = sscanf(instr, \"%d %s %254c\", library.entry + i, library.cmd[i], library.params[i]);\n if (nf == 2) library.params[i][0] = '\\n';\n if (nf >= 2) i++;\n }\n library.n = i;\n}\n\nvoid ProcessUplinkSched(unsigned char *extdat)\n{\n static unsigned char slot = 0xff;\n static uint16_t sched[32][64][2];\n static uint32_t chunks_received = 0;\n static unsigned char nchunk = 0;\n static unsigned char nsched[32];\n\n unsigned char slot_in, i_chunk, nchunk_in;\n uint16_t *extdat_ui;\n uint16_t entry;\n uint16_t itime;\n double day, hour;\n\n int i, i_samp;\n\n slot_in = (extdat[EXT_SLOT] & 0xf0) >> 4; // only the top nibble is the slot\n i_chunk = extdat[EXT_ICHUNK];\n nchunk_in = extdat[EXT_NCHUNK];\n\n blast_info(\"slot: %d chunk: %d nchunk: %d\", slot_in, i_chunk, nchunk_in);\n\n nsched[i_chunk] = extdat[EXT_NSCHED];\n\n if ((slot != slot_in) || (nchunk_in != nchunk)) {\n chunks_received = 0;\n for (i = nchunk_in; i < 32; i++) {\n chunks_received |= (1 << i);\n }\n slot = slot_in;\n nchunk = nchunk_in;\n }\n\n extdat_ui = (uint16_t *) (&extdat[6]);\n\n for (i = 0; i < nsched[i_chunk]; i++) {\n sched[i_chunk][i][0] = extdat_ui[i * 2];\n sched[i_chunk][i][1] = extdat_ui[i * 2 + 1];\n }\n\n chunks_received |= (1 << i_chunk);\n\n CommandData.parts_sched = chunks_received;\n CommandData.upslot_sched = slot;\n\n if (chunks_received == 0xffffffff) {\n FILE *fp;\n char filename[128];\n OpenLibrary();\n\n snprintf(filename, sizeof(filename), \"/data/etc/blast/%d.sch\", slot);\n fp = fopen(filename, \"w\");\n\n fprintf(fp, \"%s\", lst0str);\n\n for (i_chunk = 0; i_chunk < nchunk; i_chunk++) {\n for (i_samp = 0; i_samp < nsched[i_chunk]; i_samp++) {\n entry = sched[i_chunk][i_samp][1];\n itime = sched[i_chunk][i_samp][0];\n day = (double) itime * MAX_DAYS / MAX_RTIME;\n hour = (day - floor(day)) * 24.0;\n if (entry < library.n) {\n fprintf(fp, \"%s %d %.6g %s\", library.cmd[entry], (int) day, hour, library.params[entry]);\n } else {\n blast_warn(\"entry %d not in library\\n\", entry);\n }\n }\n }\n fclose(fp);\n }\n\n blast_warn(\"finished extended command\\n\" \" slot %d chunk %d n chunk %d nsched %d route %x chunks_received: %x\\n\",\n extdat[EXT_SLOT], extdat[EXT_ICHUNK], extdat[EXT_NCHUNK], extdat[EXT_NSCHED], extdat[EXT_ROUTE],\n chunks_received);\n}\n\nvoid WatchPort(void* parameter)\n{\n const char *COMM[] = { \"/dev/ttyCOMM1\", \"/dev/ttyCOMM2\" };\n const unsigned char route[2] = { 0x09, 0x0c };\n\n unsigned char buf;\n uint16_t *indatadumper;\n unsigned char indata[20];\n int readstage = 0;\n int tty_fd;\n\n intptr_t port = (intptr_t) parameter;\n\n double rvalues[MAX_N_PARAMS];\n int ivalues[MAX_N_PARAMS];\n char svalues[MAX_N_PARAMS][CMD_STRING_LEN];\n\n int mcommand = -1;\n int mcommand_count = 0;\n int dataqsize = 0;\n uint16_t mcommand_data[DATA_Q_SIZE];\n unsigned char mcommand_time = 0;\n\n int timer = 0;\n int bytecount = 0;\n int extlen = 0;\n\n unsigned char extdat[256];\n\n char tname[6];\n snprintf(tname, sizeof(tname), \"COMM%1d\", (int) (port + 1));\n nameThread(tname);\n // blast_startup(\"WatchPort startup\\n\");\n int get_serial_fd = 1;\n int has_warned = 0;\n\n uint16_t mcmd;\n\n for (;;) {\n // wait for a valid file descriptor\n \t\twhile (get_serial_fd) {\n if ((tty_fd = sip_setserial(COMM[port], !has_warned)) >= 0) {\n break;\n }\n has_warned = 1;\n sleep(5);\n }\n has_warned = 0;\n get_serial_fd = 0;\n\n /* Loop until data come in */\n while (read(tty_fd, &buf, 1) <= 0) {\n timer++;\n /** Request updated info every 50 seconds */\n if (timer == 800) {\n pthread_mutex_lock(&mutex);\n if (!SendRequest(REQ_POSITION, tty_fd)) {\n get_serial_fd = 1;\n }\n#ifdef SIP_CHATTER\n blast_info(\"Request SIP Position\\n\");\n#endif\n pthread_mutex_unlock(&mutex);\n } else if (timer == 1700) {\n pthread_mutex_lock(&mutex);\n if (!SendRequest(REQ_TIME, tty_fd)) {\n get_serial_fd = 1;\n }\n#ifdef SIP_CHATTER\n blast_info(\"Request SIP Time\\n\");\n#endif\n pthread_mutex_unlock(&mutex);\n } else if (timer > 2500) {\n pthread_mutex_lock(&mutex);\n if (!SendRequest(REQ_ALTITUDE, tty_fd)) {\n get_serial_fd = 1;\n }\n#ifdef SIP_CHATTER\n blast_info(\"Request SIP Altitude\\n\");\n#endif\n pthread_mutex_unlock(&mutex);\n timer = 0;\n }\n\n // serial connection has been lost, so break out of the loop\n if (get_serial_fd) break;\n\n usleep(10000); /* sleep for 10ms */\n }\n\n // catch io errors due to bad file descriptor\n if (get_serial_fd) {\n blast_err(\"Serial connection on %s lost\\n\", COMM[port]);\n continue;\n }\n\n#ifdef VERBOSE_SIP_CHATTER\n blast_info(\"read SIP byte %02x\\n\", buf);\n#endif\n /* Take control of memory */\n pthread_mutex_lock(&mutex);\n\n /* Process data */\n switch (readstage) {\n /* readstage: 0: waiting for packet beginning (0x10) */\n /* 1: waiting for packet type (e.g., 0x14 = command packet) */\n /* 2: waiting for command packet datum: case 0x14 */\n /* 3: waiting for request data packet end: case 0x13 */\n /* 4: waiting for GPS position datum: case 0x10 */\n /* 5: waiting for GPS time datum: case 0x11 */\n /* 6: waiting for MKS pressure datum: case 0x12 */\n\n case 0: /* waiting for packet beginning */\n if (buf == 0x10) readstage = 1;\n break;\n case 1: /* wating for packet type */\n if (buf == 0x13) { /* Send data request */\n readstage = 3;\n#ifdef SIP_CHATTER\n blast_info(\"Data request\\n\");\n#endif\n } else if (buf == 0x14) { /* Command */\n readstage = 2;\n#ifdef SIP_CHATTER\n blast_info(\"Command\\n\");\n#endif\n } else if (buf == 0x10) { /* GPS Position */\n readstage = 4;\n#ifdef SIP_CHATTER\n blast_info(\"GPS Position\\n\");\n#endif\n } else if (buf == 0x11) { /* GPS Time */\n readstage = 5;\n#ifdef SIP_CHATTER\n blast_info(\"GPS Time\\n\");\n#endif\n } else if (buf == 0x12) { /* MKS Altitude */\n readstage = 6;\n#ifdef SIP_CHATTER\n blast_info(\"MKS Altitude\\n\");\n#endif\n } else {\n blast_warn(\"Bad packet received: \" \"Unrecognised Packet Type: %02X\\n\", buf);\n readstage = 0;\n }\n break;\n case 2: /* waiting for command packet datum */\n if (bytecount == 0) { /* Look for 2nd byte of command packet = 0x02 */\n if (buf == 0x02) {\n bytecount = 1;\n } else {\n readstage = 7;\n extlen = buf;\n }\n } else if (bytecount >= 1 && bytecount <= 2) {\n /* Read the two data bytes of the command packet */\n indata[bytecount - 1] = buf;\n bytecount++;\n } else {\n bytecount = 0;\n if (buf == 0x03) {\n /* We should now be at the end of the command packet */\n readstage = 0;\n\n /* Check bits 6-8 from second data byte for type of command */\n /* Recall: 101? ???? = 0xA0 = single command */\n /* 100? ???? = 0x80 = begin multi command */\n /* 110? ???? = 0xC0 = end multi command */\n /* 0??? ???? = 0x00 = data packet in multi command */\n\n if ((indata[1] & 0xE0) == 0xA0) {\n /*** Single command ***/\n // blast_info(\"Single command received\\n\");\n // FIXME(seth): this limits # single commands to 255. use indata[1] too\n SingleCommand(indata[0] | ((indata[1] & 0x0f) << 8), 0);\n mcommand = -1;\n } else if ((indata[1] & 0xE0) == 0x80) {\n /*** Beginning of multi command ***/\n /*Grab first five bits of second byte containing command number*/\n mcommand = indata[0];\n mcommand_count = 0;\n dataqsize = DataQSize(MIndex(mcommand));\n blast_info(\"UNSUPPORTED: Multi word command %s (%d) started\\n\",\n MName(mcommand), mcommand);\n\n /* The time of sending, a \"unique\" number shared by the first */\n /* and last packed of a multi-command */\n mcommand_time = indata[1] & 0x1F;\n } else if (((indata[1] & 0x80) == 0) && (mcommand >= 0) && (mcommand_count < dataqsize)) {\n /*** Parameter values in multi-command ***/\n indatadumper = (uint16_t *) indata;\n mcommand_data[mcommand_count] = *indatadumper;\n blast_info(\"Multi word command continues...\\n\");\n mcommand_count++;\n } else if (((indata[1] & 0xE0) == 0xC0) && (mcommand == indata[0])\n && ((indata[1] & 0x1F) == mcommand_time) && (mcommand_count == dataqsize)) {\n /*** End of multi-command ***/\n blast_info(\"Multi word command ends \\n\");\n SetParameters(mcommand, (uint16_t*) mcommand_data, rvalues, ivalues, svalues);\n MultiCommand(mcommand, rvalues, ivalues, svalues, 0);\n mcommand = -1;\n mcommand_count = 0;\n mcommand_time = 0;\n } else {\n mcommand = -1;\n mcommand_count = 0;\n blast_warn(\"Command packet discarded: Bad Encoding: %04X\\n\", indata[1]);\n mcommand_time = 0;\n }\n }\n }\n break;\n case 3: /* waiting for request data packet end */\n readstage = 0;\n if (buf == 0x03) {\n SendDownData(tty_fd);\n } else {\n blast_warn(\"Bad encoding: Bad packet terminator: %02X\\n\", buf);\n }\n break;\n case 4: /* waiting for GPS position datum */\n if (bytecount < 14) { /* There are 14 data bytes for GPS position */\n indata[bytecount] = buf;\n bytecount++;\n } else {\n bytecount = 0;\n readstage = 0;\n if (buf == 0x03) {\n GPSPosition((unsigned char *) indata);\n } else {\n blast_warn(\"Bad encoding in GPS Position: \" \"Bad packet terminator: %02X\\n\", buf);\n }\n }\n break;\n case 5: /* waiting for GPS time datum: case 0x11 */\n if (bytecount < 14) { /* There are fourteen data bytes for GPS time */\n indata[bytecount] = buf;\n bytecount++;\n } else {\n bytecount = 0;\n readstage = 0;\n if (buf == 0x03) {\n GPSTime((unsigned char *) indata);\n } else {\n blast_warn(\"Bad encoding in GPS Time: \" \"Bad packet terminator: %02X\\n\", buf);\n }\n }\n break;\n case 6: /* waiting for MKS pressure datum: case 0x12 */\n if (bytecount < 6) {\n indata[bytecount] = buf;\n bytecount++;\n } else {\n bytecount = 0;\n readstage = 0;\n if (buf == 0x03) {\n MKSAltitude((unsigned char *) indata);\n } else {\n blast_warn(\"Bad encoding in MKS Altitude: \" \"Bad packet terminator: %02X\\n\", buf);\n }\n }\n break;\n case 7: // reading extended command\n if (bytecount < extlen) {\n extdat[bytecount] = buf;\n bytecount++;\n } else {\n if (buf == 0x03) {\n mcmd = (uint16_t)extdat[0] | ((uint16_t)(extdat[1] & 0x0f) << 8);\n if (mcmd == sched_packet) {\n if (extdat[EXT_ROUTE] == route[port]) {\n blast_info(\"Schedule file uplink packet detected\\n\");\n ProcessUplinkSched(extdat);\n } else {\n blast_info(\"Schedule file uplink packet bad route %d != %d\\n\", extdat[EXT_ROUTE],\n route[port]);\n }\n } else {\n if (MIndex(mcmd) < 0) {\n blast_warn(\"ignoring unknown extended command (%d)\", mcmd);\n } else {\n blast_info(\"extended command %s (%d)\", MName(mcmd), mcmd);\n SetParameters(mcmd, (uint16_t*) (extdat + 2), rvalues, ivalues, svalues);\n MultiCommand(mcmd, rvalues, ivalues, svalues, 0);\n }\n }\n } else {\n blast_warn(\"Bad encoding in extended command: \" \"Bad packet terminator: %02X\\n\", buf);\n }\n bytecount = 0;\n readstage = 0;\n }\n break;\n }\n\n /* Relinquish control of memory */\n pthread_mutex_unlock(&mutex);\n }\n}\n\n" }, { "alpha_fraction": 0.6148438453674316, "alphanum_fraction": 0.6301094889640808, "avg_line_length": 34.942237854003906, "blob_id": "8675e8f39adec2eed9fbeff1319d78a2c415f92d", "content_id": "f52b261e2a4ff48f46585c27baf126b41eaab534", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9958, "license_type": "no_license", "max_line_length": 129, "num_lines": 277, "path": "/stars/code/solving/matching/solution_fitter.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"solution_fitter.h\"\n#include <levmar.h>\n#include <cstdlib>\n#include <limits>\n#include \"../../tools/angles.h\"\n#include \"../../tools/slalib.h\"\n#include \"../../shared/solving/settings.h\"\n#include \"../../tools/ccd_projection.h\"\n#include \"../logger.h\"\n#include \"../../tools/quick_cout.h\"\n\nusing namespace Solving;\nusing namespace Solving::PatternMatching;\nusing std::vector;\n\n#define shared_settings (*(Shared::Solving::settings.r))\n\nSolutionFitter::SolutionFitter(): max_num_blobs(100)\n{\n int max_num_params = 4;\n int max_num_measurements = 2 * max_num_blobs;\n workspace = (double *) malloc((LM_DIF_WORKSZ(max_num_params, max_num_measurements) +\n max_num_params*max_num_params) * sizeof(double));\n covar = workspace + LM_DIF_WORKSZ(max_num_params, max_num_measurements);\n adata.star_data = new double[max_num_measurements];\n adata.weights = new double[max_num_measurements];\n blob_measurements = new double[max_num_measurements];\n blob_fit_positions = new double[max_num_measurements];\n params = new double[max_num_params];\n info = new double[LM_INFO_SZ];\n}\n\nSolutionFitter::~SolutionFitter()\n{\n delete [] info;\n delete [] params;\n delete [] blob_measurements;\n delete [] blob_fit_positions;\n delete [] adata.weights;\n delete [] adata.star_data;\n free(workspace);\n}\n\nnamespace levmar_solution_fitter\n{\n\nvoid error_function(double* params, double* blob_data, int num_params, int num_measurements,\n void* data)\n{\n additional_data* adata = (additional_data*) data;\n double* star_data = adata->star_data;\n double* weights = adata->weights;\n\n double platescale = 0.0;\n if (adata->platescale_fixed) {\n platescale = 1.0 / shared_settings.iplatescale_fixed;\n } else {\n platescale = params[3];\n }\n unsigned int num_blobs = num_measurements/2;\n double cos_roll = cos(params[2]);\n double sin_roll = sin(params[2]);\n\n double x = 0;\n double y = 0;\n for (unsigned int i=0; i<num_blobs; i++) {\n Tools::ccd_projection(star_data[2*i], star_data[2*i+1], params[0], params[1],\n platescale, cos_roll, sin_roll, x, y, adata->flipped_coordinate_system);\n blob_data[2*i] = x;\n blob_data[2*i+1] = y;\n blob_data[2*i] *= weights[2*i];\n blob_data[2*i+1] *= weights[2*i+1];\n }\n\n}\n\n}\n\ndouble SolutionFitter::get_fit_error(double* blob_measurements, double* blob_fit_positions, int num_measurements, int num_params)\n{\n double error_squared = 0.0;\n for (unsigned int i=0; i<(unsigned int)num_measurements; i++) {\n error_squared += pow(blob_measurements[i]-blob_fit_positions[i], 2.0);\n }\n if (num_measurements > num_params) {\n return sqrt(error_squared / (num_measurements - num_params));\n }\n return std::numeric_limits<double>::infinity();\n}\n\ndouble SolutionFitter::get_error(int num_params, double dec)\n{\n double sigma_ra = sqrt(covar[0*num_params+0]);\n double sigma_ra_scaled = sigma_ra*cos(dec);\n double sigma_dec = sqrt(covar[1*num_params+1]);\n double average_position_error = (sigma_dec + sigma_ra_scaled)/2.0;\n return average_position_error;\n}\n\nvoid SolutionFitter::init_params(double blobs[], double stars[],\n bool platescale_fixed, bool flipped_coordinate_system)\n{\n // shaves off three percent, not worth the extra complexity\n\n double bxdiffs = blobs[2]-blobs[0];\n double bydiffs = blobs[3]-blobs[1];\n double sxdiffs = stars[2]-stars[0];\n double sydiffs = stars[3]-stars[1];\n\n if (flipped_coordinate_system) {\n sxdiffs = -sxdiffs;\n }\n\n double theta = atan2(bydiffs*sxdiffs - bxdiffs*sydiffs, bxdiffs*sxdiffs + bydiffs*sydiffs);\n params[2] = theta;\n\n double cos_theta = cos(theta);\n double sin_theta = sin(theta);\n double platescale = (cos_theta*bxdiffs + sin_theta*bydiffs) / sxdiffs;\n if (!platescale_fixed) {\n params[3] = platescale;\n }\n\n params[0] = stars[0] - (cos_theta*blobs[0] + sin_theta*blobs[1]) / platescale;\n params[1] = stars[1] - (cos_theta*blobs[1] - sin_theta*blobs[0]) / platescale;\n}\n\nvoid SolutionFitter::fit_helper(vector<Blob>& blobs, vector<Star>& stars, Solution& solution,\n Shared::Image::Raw& image, bool platescale_fixed, bool do_horizontal)\n{\n unsigned int num_blobs = std::min((unsigned int) blobs.size(), max_num_blobs);\n unsigned int num_measurements = 2*num_blobs;\n unsigned int num_params = 3;\n\n for (unsigned int i=0; i<num_blobs; i++) {\n\n if (do_horizontal) {\n double az = 0;\n double el = 0;\n Tools::get_refraction_corrected_horizontal(stars[i].ra, stars[i].dec,\n shared_settings.refraction, image.filters, az, el);\n adata.star_data[2*i] = az;\n adata.star_data[2*i+1] = el;\n } else {\n double ra = 0;\n double dec = 0;\n Tools::get_refraction_corrected_equatorial(stars[i].ra, stars[i].dec,\n shared_settings.refraction, image.filters, ra, dec);\n adata.star_data[2*i] = ra;\n adata.star_data[2*i+1] = dec;\n }\n\n adata.weights[2*i] = 1.0;\n adata.weights[2*i+1] = 1.0;\n blob_measurements[2*i] = blobs[i].x * adata.weights[2*i];\n blob_measurements[2*i+1] = blobs[i].y * adata.weights[2*i+1];\n }\n if (do_horizontal) {\n adata.flipped_coordinate_system = false;\n } else {\n adata.flipped_coordinate_system = true;\n }\n adata.platescale_fixed = platescale_fixed;\n\n params[0] = adata.star_data[0];\n params[1] = adata.star_data[1];\n params[2] = 0.0;\n if (platescale_fixed) {\n num_params = 3; // ra, dec, roll\n } else {\n num_params = 4; // ra, dec, roll, platescale\n params[3] = 1.0 / from_arcsec(9.5);\n }\n\n dlevmar_dif(levmar_solution_fitter::error_function, params, blob_measurements, num_params,\n num_measurements, 100, NULL, info, workspace, covar, (void*) &adata);\n\n levmar_solution_fitter::error_function(params, blob_fit_positions, num_params, num_measurements, (void*) &adata);\n double fit_error = get_fit_error(blob_measurements, blob_fit_positions, num_measurements, num_params);\n\n // too close to flight\n // * safety check on fit_error to prevent it from cutting good solutions\n if (fit_error > 1000.0) {\n fit_error = 1000.0;\n }\n\n if (do_horizontal) {\n solution.horizontal.valid = true;\n solution.horizontal.az = params[0];\n solution.horizontal.el = params[1];\n solution.horizontal.roll = params[2];\n solution.horizontal.sigma_az = sqrt(covar[0*num_params+0]);\n solution.horizontal.sigma_el = sqrt(covar[1*num_params+1]);\n solution.horizontal.sigma_roll = sqrt(covar[2*num_params+2]);\n solution.horizontal.sigma_pointing = get_error(num_params, solution.horizontal.el);\n solution.horizontal.fit_error = fit_error;\n if (platescale_fixed) {\n solution.horizontal.iplatescale = shared_settings.iplatescale_fixed;\n } else {\n solution.horizontal.iplatescale = 1.0 / params[3];\n }\n } else {\n solution.equatorial.valid = true;\n solution.equatorial.ra = params[0];\n solution.equatorial.dec = params[1];\n solution.equatorial.roll = params[2];\n solution.equatorial.sigma_ra = sqrt(covar[0*num_params+0]);\n solution.equatorial.sigma_dec = sqrt(covar[1*num_params+1]);\n solution.equatorial.sigma_roll = sqrt(covar[2*num_params+2]);\n solution.equatorial.sigma_pointing = get_error(num_params, solution.equatorial.dec);\n solution.equatorial.fit_error = fit_error;\n if (platescale_fixed) {\n solution.equatorial.iplatescale = shared_settings.iplatescale_fixed;\n } else {\n solution.equatorial.iplatescale = 1.0 / params[3];\n }\n }\n}\n\nvoid SolutionFitter::fill_star_ccd_positions(vector<Star>& stars, Solution& solution,\n Shared::Image::Raw& image)\n{\n double x = 0;\n double y = 0;\n double star_ra = 0;\n double star_dec = 0;\n for (unsigned int i=0; i<stars.size(); i++) {\n Tools::get_refraction_corrected_equatorial(stars[i].ra, stars[i].dec, shared_settings.refraction,\n image.filters, star_ra, star_dec);\n Tools::ccd_projection(star_ra, star_dec, solution.equatorial.ra, solution.equatorial.dec,\n 1.0/solution.equatorial.iplatescale, solution.equatorial.roll, x, y, true);\n stars[i].fitted_x = x;\n stars[i].fitted_y = y;\n }\n}\n\nvoid SolutionFitter::fit(vector<Blob>& blobs, vector<Star>& stars, Solution& solution,\n Shared::Image::Raw& image, bool final_pass)\n{\n if (stars.size() != blobs.size()) {\n return;\n }\n if (blobs.size() < 2) {\n return;\n }\n bool platescale_fixed = false;\n if (blobs.size() == 2 || shared_settings.platescale_always_fixed) {\n //Shared::Solving::settings.update(); // why is this update here?\n platescale_fixed = true;\n }\n\n // fit for equatorial solution\n fit_helper(blobs, stars, solution, image, platescale_fixed, false);\n\n // fit for horizontal solution if capable\n if (image.filters.horizontal_known_and_filters_enabled() ||\n (image.filters.horizontal_known() && final_pass))\n {\n fit_helper(blobs, stars, solution, image, platescale_fixed, true);\n }\n\n // if final pass, fill star positions and print horizontal information\n if (final_pass) {\n if (image.filters.horizontal_known()) {\n logger.log(format(\n \"solution fitter: final pass used lat %.5f (deg) lst %.5f (hours)\")\n % to_degrees(image.filters.lat()) % to_hours(image.filters.lst()));\n }\n fill_star_ccd_positions(stars, solution, image);\n }\n}\n\n" }, { "alpha_fraction": 0.6957972049713135, "alphanum_fraction": 0.7128085494041443, "avg_line_length": 31.586956024169922, "blob_id": "a15e3b9ffd310be30caa6a8a29a328b206a5a127", "content_id": "2fdbfc9bf97762a9e0af7dd073085020700b8e92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2998, "license_type": "no_license", "max_line_length": 115, "num_lines": 92, "path": "/blast_comms/include/comms_netsock.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/**\n * @file comms_netsock.h\n *\n * @date Jan 17, 2011\n * @author seth\n *\n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2010-2015 Seth Hillbrand\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n\n#ifndef INCLUDE_COMMS_NETSOCK_H\n#define INCLUDE_COMMS_NETSOCK_H\n#include <stdbool.h>\n#include <netinet/in.h>\n#include <time.h>\n#include <unistd.h>\n\n#include <comms_netbuf.h>\n#include <comms_netasync.h>\n#include <lookup.h>\n#include <comms_common.h>\n\n#define COMMS_NETSOCK_BUF_SIZE 8192 /**< COMMS_NETSOCK_BUF_SIZE 8192 is the maximum size of an atomic read/write */\n\ntypedef struct comms_socket\n{\n comms_net_async_handle_t *poll_handle;\n netsock_callbacks_t callbacks;\n socket_t fd;\n\n char *host;\n uint32_t timeout;\n uint32_t port;\n\n struct sockaddr_in addr;\n socklen_t addrlen;\n\n bool is_socket;\n bool can_read;\n bool can_write;\n\n bool have_exception;\n int last_errno;\n\n int flags;\n int udp;\n\n e_comms_socket_state state;\n netbuf_t *out_buffer;\n netbuf_t *in_buffer;\n\n void *priv_data;\n} comms_socket_t;\n\ncomms_socket_t *comms_sock_new(void);\nvoid comms_sock_reset(comms_socket_t **m_sock);\nvoid comms_sock_free(comms_socket_t *m_sock);\nvoid comms_sock_close(comms_socket_t *m_sock);\nvoid comms_sock_set_fd(comms_socket_t *m_sock, socket_t m_fd);\nint comms_sock_write(comms_socket_t *m_sock, const void *m_buf, size_t m_len);\nint comms_sock_flush(comms_socket_t *m_sock);\nint comms_sock_connect(comms_socket_t *m_sock, const char *m_hostname, uint32_t m_port);\nint comms_sock_connect_udp(comms_socket_t *m_sock, const char *m_hostname, uint32_t m_port);\nint comms_sock_reconnect(comms_socket_t *m_sock);\nint comms_sock_listen(comms_socket_t *m_socket, const char *m_hostname, uint32_t m_port);\nint comms_sock_listen_udp(comms_socket_t *m_socket, const char *m_hostname, uint32_t m_port);\nsocket_t comms_sock_accept(comms_socket_t *m_socket);\nint comms_sock_multicast_listen(comms_socket_t *m_sock, const char *m_hostname, uint32_t m_port);\nint comms_sock_set_buffer(comms_socket_t *m_socket, int m_size);\nvoid comms_sock_set_flags(comms_socket_t *m_sock, int m_flags);\nint comms_sock_join_mcast(comms_socket_t *m_socket, in_addr_t m_group);\n\ncomms_net_async_handle_t *comms_sock_get_poll_handle(comms_socket_t *m_sock);\n\n#endif /* BLAST_NETSOCK_H_ */\n" }, { "alpha_fraction": 0.5963079929351807, "alphanum_fraction": 0.601854681968689, "avg_line_length": 28.970129013061523, "blob_id": "5ec118294a050b502a02e518a6f54902fc98e24d", "content_id": "ef30c931883946ec72c074b843b03be8e1bafe30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 23077, "license_type": "no_license", "max_line_length": 158, "num_lines": 770, "path": "/guaca/mainwindow.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdint.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <sys/stat.h>\n#include <netdb.h>\n#include <fcntl.h>\n#include <errno.h>\n\n#include \"../liblinklist/linklist.h\"\n#include \"../liblinklist/linklist_connect.h\"\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#define VERBOSE 0\n#define SELECTION_APPEND_TEXT \" - Custom selection... -\"\n#define GUACA_MIN_TIME_CHECK_DATA 2\n#define LINKLIST_DATEFORMAT_LENGTH 20\n\nchar archivedir[128] = \"/data/mole\";\nchar moledir[128] = \"/data/mole\";\nchar masterlink[128] = \"/data/etc/mole.lnk\";\nchar masterlist[128] = \"/data/etc/mole.lst\";\n\nvoid USAGE(void) {\n\n printf(\"\\n\\nGUI front-end for mole to conveniently grab telemetry data from server.\\n\\n\"\n \"Usage: guaca [host] [OPTION]...\\n\\n\"\n \" -h Display this message.\\n\"\n \"\\n\");\n\n exit(0);\n}\n\nint MainWindow::make_listfiles() {\n QStringList linklist_names;\n QList<QFile*> linklist_files;\n\n QDir archdir(archivedir);\n archdir.setFilter(QDir::AllDirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);\n archdir.setSorting(QDir::Name);\n\n QStringList filelist = archdir.entryList();\n\n for (int i=0; i<filelist.size(); i++) {\n int len = filelist[i].length();\n // has the correct format (i.e. ****_yyyy-mm-dd-hh-mm-ss)\n if (len > LINKLIST_DATEFORMAT_LENGTH && filelist[i][len-LINKLIST_DATEFORMAT_LENGTH] == '_') {\n // build the linklist name and find it in the list of linklist_names\n filelist[i] = archdir.absolutePath() + \"/\" + filelist[i];\n QString name = QString(filelist[i]);\n name.chop(LINKLIST_DATEFORMAT_LENGTH);\n name += \".lst\";\n int index = linklist_names.indexOf(name);\n\n // get the file handle for the given linklist name\n QFile * file;\n if (index < 0) {\n // generate a new file and append to the list\n file = new QFile();\n file->setFileName(name);\n if (!file->open(QIODevice::Truncate | QIODevice::WriteOnly)) {\n qDebug() << \"Cannot open file\" << name;\n continue;\n }\n // qDebug() << \"Opened file\" << name;\n linklist_files.append(file);\n linklist_names.append(name);\n } else {\n // grab the file from the array\n file = linklist_files[index];\n }\n file->write(filelist[i].toUtf8().data());\n file->write(\"\\n\");\n }\n }\n // cleanup files\n for (int i=0; i<linklist_files.size(); i++) {\n linklist_files[i]->flush();\n linklist_files[i]->close();\n delete linklist_files[i];\n }\n linklist_files.clear();\n linklist_names.clear();\n\n return linklist_files.size();\n}\n\n\n/*\n * A very important function that animates guaca when\n * appropriate. Also takes care of displaying logs in the\n * status bar.\n */\n\nvoid MainWindow::dancing()\n{\n int thetime = time(0);\n still_dancing = true;\n\n // get the latest text from the currently active mole process\n QString msg = \"Mole not receiving data.\\n\";\n unsigned int current_index = ui->linkSelect->currentIndex();\n if (mole_logs.size() > current_index) {\n msg = mole_logs[current_index]->get_latest_str();\n }\n\n // check the status of data based on mole terminal text\n // this sets the data incoming status\n if ((thetime-logend) > GUACA_MIN_TIME_CHECK_DATA) {\n data_incoming = (msg != last_msg);\n last_msg = msg;\n logend = thetime;\n }\n ui->statusBar->showMessage(msg);\n\n // dancing logic\n if (mole_active) {\n if (data_incoming) {\n if (image_i==IMAGE_LOOP_HIGH) inc = -1;\n else if (image_i==IMAGE_LOOP_LOW) inc = 1;\n } else {\n inc = 1;\n }\n } else {\n inc = 1;\n if (image_i==(IMAGE_IND_OFF+1)%IMAGE_TOTAL) image_i = IMAGE_IND_OFF;\n }\n\n int ss = qMin(ui->dance->width(),ui->dance->height())*15/8;\n qs = QSize(ss,ss);\n ui->dance->setPixmap(qi[image_i].pixmap(qs).scaled(ss,ss,Qt::KeepAspectRatio));\n ui->dance->show();\n\n image_i = (image_i+inc)%IMAGE_TOTAL;\n\n still_dancing = false;\n}\n\nbool HostMenu::eventFilter(QObject *o, QEvent *e) {\n (void) o;\n if (e->type() == QEvent::MouseButtonRelease) {\n if (static_cast<QMouseEvent*>(e)->button() == Qt::RightButton) {\n return true;\n }\n }\n return false;\n}\n\nvoid HostMenu::list_context_menu(QPoint pos) {\n QModelIndex index = view->indexAt(pos);\n int item = index.row();\n new_item->setData(item);\n modify_item->setData(item);\n delete_item->setData(item);\n if (item == 0) {\n delete_item->setDisabled(true);\n modify_item->setDisabled(true);\n } else {\n delete_item->setEnabled(true);\n modify_item->setEnabled(true);\n }\n if (!index.isValid()) { return; }\n this->exec(view->mapToGlobal(pos));\n}\n\nHostMenu::HostMenu(QComboBox *parent) {\n combo = parent;\n view = combo->view();\n view->viewport()->installEventFilter(this);\n view->setContextMenuPolicy(Qt::CustomContextMenu);\n\n // build the menu\n new_item = this->addAction(QString(\"New...\"));\n modify_item = this->addAction(QString(\"Modify\"));\n delete_item = this->addAction(QString(\"Delete\"));\n\n connect(this, SIGNAL(triggered(QAction*)), this, SLOT(handle_host_menu(QAction*)));\n connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(list_context_menu(QPoint)));\n}\n\nHostMenu::~HostMenu() {\n\n}\nvoid HostMenu::handle_host_menu(QAction *action) {\n int index = action->data().toInt();\n\n if (action == new_item) {\n bool ok = false;\n QString thehost = QInputDialog::getText(this, \"New remote host\", \"Enter the remote host name/IP:\", QLineEdit::Normal, NULL, &ok);\n\n if (ok) {\n // only add new host if it is not already in the list\n int existing_index = combo->findText(thehost);\n if (existing_index < 0) {\n index = index+1;\n combo->insertItem(index, thehost);\n } else {\n index = existing_index;\n }\n combo->setCurrentIndex(index);\n combo->activated(index);\n }\n } else if (action == modify_item) {\n bool ok = false;\n QString thehost = QInputDialog::getText(this, \"Modify remote host\", \"Enter the remote host name/IP:\", QLineEdit::Normal, combo->itemText(index), &ok);\n\n if (ok) {\n combo->removeItem(index);\n combo->insertItem(index, thehost);\n combo->setCurrentIndex(index);\n combo->activated(index);\n }\n\n } else if (action == delete_item) {\n if (index > 0) {\n int existing_index = combo->currentIndex();\n combo->removeItem(index);\n // check to see if the current host was removed\n if (existing_index == index) {\n combo->setCurrentIndex(index-1);\n combo->activated(index-1);\n }\n }\n }\n\n}\n\n/*\n * Main constructor: looks in the linklist directory for all the available\n * linklists and makes them selectable in the main link widget. Also starts\n * the server thread if necessary and the animation/log checking thread.\n */\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow),\n settings(\"guacamole\", \"guaca\")\n{ \n ui->setupUi(this);\n\n ui->numRewind->setValidator(new QIntValidator(0, 1e8, this) );\n ui->startFrame->setValidator(new QIntValidator(0, INT32_MAX, this) );\n ui->endFrame->setValidator(new QIntValidator(0, INT32_MAX, this) );\n\n // setup hosts combobox contextmenu\n host_menu = new HostMenu(ui->hosts);\n options = new Options(this);\n\n QSettings oldsettings(\"SuperBIT\", \"guaca\");\n if (settings.contains(\"mainwindow/customConfig\")) {\n qDebug() << \"Restoring saved config\";\n loadConfig();\n } else if (oldsettings.contains(\"mainwindow/customConfig\")) {\n qDebug() << \"Migrating to new settings\";\n QStringList items = oldsettings.allKeys();\n for (int i=0; i<items.size(); i++){\n settings.setValue(items[i], oldsettings.value(items[i]));\n qDebug() << \"Transfering \" << items[i];\n }\n oldsettings.clear();\n loadConfig();\n } else {\n qDebug() << \"Using default config\";\n defaultConfig();\n saveConfig();\n }\n\n // Parse arguments\n QStringList args = QCoreApplication::arguments();\n for (int i = 1; i < args.count(); i++) {\n if (QString(args[i]).startsWith('-')) {\n if (QString(args[i]) == \"-h\") {\n USAGE();\n } else {\n printf(\"\\n\\n\");\n qDebug() << \"Unrecognized option: \" + args[i];\n USAGE();\n }\n } else if (i == 1) { // first argument is host\n host_index = ui->hosts->findText(args.at(1));\n if (host_index < 0) {\n ui->hosts->addItem(args.at(1));\n host_index = ui->hosts->count()-1;\n }\n ui->hosts->setCurrentIndex(host_index);\n } else {\n USAGE();\n }\n }\n\n // Query remote host\n if (change_remote_host(ui->hosts->currentText())) {\n saveConfig();\n }\n\n QString base = \":/images/guaca-\";\n QString ext = \".svg\";\n\n for (int i=0; i<IMAGE_TOTAL; i++) {\n qi[i] = QIcon(base+QString::number(i)+ext);\n }\n qs = QSize(300,300);\n\n ui->dance->setAlignment(Qt::AlignCenter);\n ui->dance->setPixmap(qi[IMAGE_IND_OFF].pixmap(qs));\n ui->dance->show();\n image_i = IMAGE_IND_OFF;\n inc = 1;\n srand(time(0));\n\n mole_active = false;\n servermode = false;\n logend = time(0);\n\n // Start the config server\n server = new Server(this);\n\n _ut = new QTimer(this);\n _ut->setInterval(90);\n connect(_ut,SIGNAL(timeout()),this,SLOT(dancing()));\n _ut->start();\n\n make_listfiles();\n _ut_listfiles = new QTimer(this);\n _ut_listfiles->setInterval(5000);\n connect(_ut_listfiles,SIGNAL(timeout()),this,SLOT(make_listfiles()));\n _ut_listfiles->start();\n\n restoreGeometry(settings.value(\"mainwindow\").toByteArray());\n}\n\nMainWindow::~MainWindow()\n{\n printf(\"Destructing main window\\n\");\n saveConfig();\n\n if (options) delete options;\n options = NULL;\n if (server) delete server;\n server = NULL;\n if (ui) delete ui;\n ui = NULL;\n qDebug() << \"Closing\";\n}\n\nvoid MainWindow::closeEvent(QCloseEvent *event) {\n savePosition();\n event->accept();\n _ut->stop();\n _ut_listfiles->stop();\n while(still_dancing) QTest::qWait(90);\n if (options) delete options;\n options = NULL;\n}\n\nvoid MainWindow::savePosition()\n{\n settings.setValue(\"mainwindow\", saveGeometry());\n}\n\nvoid MainWindow::saveConfig() {\n settings.setValue(\"mainwindow/numRewind\", ui->numRewind->text().toInt());\n settings.setValue(\"mainwindow/smartRewind\", ui->smartRewind->isChecked());\n settings.setValue(\"mainwindow/startFrame\", ui->startFrame->text().toInt());\n settings.setValue(\"mainwindow/endFrame\", ui->endFrame->text().toInt());\n settings.setValue(\"mainwindow/tabSelection\", ui->tabWidget->currentIndex());\n\n QStringList hosts;\n for (int i = 1; i < ui->hosts->count(); i++) {\n hosts << ui->hosts->itemText(i);\n }\n settings.setValue(\"mainwindow/host_list\", hosts);\n settings.setValue(\"mainwindow/host_index\", ui->hosts->currentIndex());\n settings.setValue(\"mainwindow/linkItem\", linkItem);\n settings.setValue(\"mainwindow/linkSelect\", QVariant::fromValue(linkSelect));\n\n settings.setValue(\"mainwindow/customConfig\", true);\n}\n\nvoid MainWindow::loadConfig() {\n\n ui->numRewind->setText(QString::number(QVariant(settings.value(\"mainwindow/numRewind\")).toInt()));\n ui->smartRewind->setChecked(QVariant(settings.value(\"mainwindow/smartRewind\")).toBool());\n ui->startFrame->setText(QString::number(QVariant(settings.value(\"mainwindow/startFrame\")).toInt()));\n ui->endFrame->setText(QString::number(QVariant(settings.value(\"mainwindow/endFrame\")).toInt()));\n ui->tabWidget->setCurrentIndex(QVariant(settings.value(\"mainwindow/tabSelection\")).toInt());\n\n QStringList hosts = QVariant(settings.value(\"mainwindow/host_list\")).toStringList();\n for (int i = 0; i < hosts.count(); i++) {\n ui->hosts->insertItem(i+1, hosts[i]);\n }\n host_index = QVariant(settings.value(\"mainwindow/host_index\")).toInt();\n host_index = (host_index < (ui->hosts->count()-1)) ? host_index : (ui->hosts->count()-1);\n ui->hosts->setCurrentIndex(host_index);\n linkItem = QVariant(settings.value(\"mainwindow/linkItem\")).toString();\n linkSelect = QStringList(QVariant(settings.value(\"mainwindow/linkSelect\")).toStringList());\n\n}\n\nvoid MainWindow::defaultConfig() {\n qDebug() << \"Default config\";\n ui->numRewind->setText(\"100\");\n ui->smartRewind->setChecked(true);\n ui->startFrame->setText(\"\");\n ui->endFrame->setText(\"\");\n ui->tabWidget->setCurrentIndex(0);\n\n ui->hosts->setCurrentIndex(ui->hosts->count()-1);\n host_index = ui->hosts->count()-1;\n linkItem = \"default\";\n}\n\n/*\n * Unfreezes all user selectable widgets in the GUI\n */\nvoid MainWindow::unfreeze()\n{\n if (!servermode)\n {\n ui->toggleMole->setText(\"Start MOLE\");\n ui->multiLinkSelect->setEnabled(true);\n ui->numRewind->setEnabled(true);\n ui->hosts->setEnabled(true);\n ui->toggleMole->setEnabled(true);\n ui->linkSelect->setEnabled(true);\n ui->tabWidget->setEnabled(true);\n\n options->enable_options();\n }\n else\n {\n\n ui->multiLinkSelect->setDisabled(true);\n ui->numRewind->setDisabled(true);\n ui->hosts->setDisabled(true);\n ui->toggleMole->setDisabled(true);\n ui->linkSelect->setDisabled(true);\n ui->tabWidget->setDisabled(true);\n\n options->disable_options();\n }\n}\n\n/*\n * Freezes all user selectable widgets in the GUI. Leaves the\n * link selector unfrozen to allow for mole.lnk changes while\n * running.\n */\nvoid MainWindow::freeze()\n{\n ui->multiLinkSelect->setDisabled(true);\n ui->numRewind->setDisabled(true);\n ui->hosts->setDisabled(true);\n ui->tabWidget->setDisabled(true);\n ui->toggleMole->setText(\"Stop MOLE\");\n options->disable_options();\n\n if (servermode)\n {\n ui->toggleMole->setDisabled(true);\n ui->linkSelect->setDisabled(true);\n }\n}\n\n/*\n * Starts a single mole client based on the selection index from\n * the linklist selector.\n */\nvoid MainWindow::start_a_mole(int index)\n{\n QString mole_cmd = \"mole --live-name \"+ui->linkSelect->itemText(index)+\" \"+\n \"--filename \"+ui->linkSelect->itemText(index)+\" \"+\n \"@\"+ui->hosts->currentText().split(QRegExp(\"\\\\s+-\"), QString::SkipEmptyParts)[0]+\" \"+\n \"--client-port \"+QString::number(options->client_port)+\" --server-port \"+QString::number(options->server_port)+\" \"+\n \"--archive-dir \"+options->raw_dir+\" --mole-dir \"+options->mole_dir;\n\n QWidget * current_tab = ui->tabWidget->currentWidget();\n if (current_tab == ui->rewindTab) {\n if (ui->smartRewind->isChecked()) {\n mole_cmd += \" -W \";\n } else {\n mole_cmd += \" -w \";\n }\n if (!ui->numRewind->text().isEmpty()) {\n mole_cmd += ui->numRewind->text();\n } else {\n mole_cmd += \"0\";\n ui->numRewind->setText(QString::number(0));\n }\n } else if (current_tab == ui->dataSelectionTab) {\n if (!ui->startFrame->text().isEmpty()) {\n mole_cmd += \" -S \" + ui->startFrame->text();\n } else {\n mole_cmd += \"- S 0\";\n ui->startFrame->setText(QString::number(0));\n }\n if (!ui->endFrame->text().isEmpty()) {\n mole_cmd += \" -E \" + ui->endFrame->text();\n } else {\n mole_cmd += \"- E \" + QString::number(INT32_MAX);\n ui->endFrame->setText(QString::number(INT32_MAX));\n }\n } else if (current_tab == ui->dataFillTab) {\n mole_cmd += \"-M \";\n }\n\n if (options->no_checksums) mole_cmd += \" --no-check\";\n if (options->backup) mole_cmd += \" --backup\";\n if (options->server) mole_cmd += \" --server\";\n if (!options->client) mole_cmd += \" --no-client\";\n\n Logscroll * mole_log = new Logscroll(NULL, mole_cmd, false);\n mole_log->setWindowTitle(mole_cmd);\n mole_logs.push_back(mole_log);\n if (options->mole_terminal) {\n mole_log->show();\n }\n\n}\n\nvoid MainWindow::stop_all_moles() {\n\n printf(\"Stopping all moles...\\n\");\n for (unsigned int i = 0; i < mole_logs.size(); i++) {\n if (mole_logs[i]) delete mole_logs[i];\n mole_logs[i] = NULL;\n }\n mole_logs.clear();\n printf(\"All moles stopped\\n\");\n}\n\n/*\n * Toggles whether or not mole clients are active\n */\nvoid MainWindow::on_toggleMole_clicked() {\n saveConfig();\n stop_all_moles();\n\n if (mole_active) {\n // unfreeze the UI\n unfreeze();\n } else {\n // ensure there is a primary link selected before doing anything\n if (ui->linkSelect->count() == 0) {\n QMessageBox::warning(this,\"No Link Selected\",\"No primary link selected\\nPlease make a linklist(s) selection and then select primary link.\");\n return;\n }\n if (ui->tabWidget->currentWidget() == ui->dataFillTab) {\n QMessageBox::StandardButton reply = QMessageBox::question(this,\n \"Fill all data gaps?\",\n \"This will fill in all dirfile data gaps for link \" + ui->linkSelect->currentText() +\n \". Confirmed?\",\n QMessageBox::Ok |QMessageBox::Cancel);\n if (reply == QMessageBox::Cancel) {\n return;\n }\n }\n\n // freeze the UI\n freeze();\n\n // start moles\n for (int i=0;i<ui->linkSelect->count();i++) start_a_mole(i);\n\n // establish symlinks\n on_linkSelect_currentIndexChanged(ui->linkSelect->currentText());\n\n // show helper functions, if necessary\n options->show_helpers();\n }\n\n // toggle\n mole_active = !mole_active;\n}\n\n\n/*\n * Forms symlinks for a given linklist when the option is changed\n * in the linklist selector.\n */\nvoid MainWindow::on_linkSelect_currentIndexChanged(const QString &arg1)\n{\n if (arg1.length() == 0) return;\n\n QString aname = arg1;\n QString linkname = QString(moledir)+\"/\"+aname+\".lnk\";\n\n QByteArray ba = linkname.toLatin1();\n\n printf(\"%s -> %s\\n\",masterlink,ba.data());\n\n unlink(masterlink);\n if (symlink(ba.data(),masterlink) < 0)\n {\n printf(\"Symlink failed (%s->%s)\\n\",masterlink,ba.data());\n }\n // force dance check\n logend = 0;\n}\n\nbool MainWindow::change_remote_host(const QString &arg)\n{\n bool connected = false;\n\n QString hostname = arg.split(QRegExp(\"\\\\s+-\"), QString::SkipEmptyParts)[0];\n struct TCPCONN tcpconn;\n strcpy(tcpconn.ip,hostname.toLatin1().data());\n tcpconn.flag |= TCPCONN_NOLOOP;\n\n char names[LINKLIST_MAX_FILENAME_SIZE][LINKLIST_SHORT_FILENAME_SIZE] = {{0}};\n int numlink = 0;\n\n num_linkfile = 0;\n QStringList storedLinkSelect = QStringList(linkSelect);\n\n ui->multiLinkSelect->clear();\n\n // set the port\n set_linklist_client_port(options->client_port);\n\n printf(\"Attempting to connect to %s:%d...\\n\", tcpconn.ip, options->client_port);\n if ((numlink = request_server_archive_list(&tcpconn,names)) > 0)// made a connection with the server\n {\n printf(\"Got server list\\n\");\n\n for (int i=0; i<numlink; i++)\n {\n QString name = QString(names[i]);\n ui->multiLinkSelect->addItem(name);\n if ((options->auto_live && name.endsWith(options->live_name)) || storedLinkSelect.contains(name)) {\n ui->multiLinkSelect->item(i)->setSelected(true);\n }\n num_linkfile++;\n }\n linkSelect = storedLinkSelect;\n\n // auto select the active link\n auto_select_link();\n\n ui->linkDir->setText(\"Available telemetry streams from \"+QString(hostname.data()));\n connected = true;\n }\n else\n {\n QMessageBox::information(\n this,\n tr(\"Guaca-mole\"),\n \"No archive found at \" + QString(hostname.data()) + \":\" + QString::number(options->client_port) + \".\");\n }\n close_connection(&tcpconn);\n\n return connected;\n}\n\nvoid MainWindow::auto_select_link() {\n int linkIndex = ui->linkSelect->findText(linkItem);\n if (linkIndex < 0) linkIndex = 0;\n ui->linkSelect->setCurrentIndex(linkIndex);\n}\n\nvoid MainWindow::on_actionClose_triggered()\n{\n close();\n}\n\nvoid MainWindow::on_actionSlave_to_triggered()\n{\n return;\n\n bool ok;\n QString dummy;\n QString host = QInputDialog::getText(this, \"Choose Master\", \"What server should guaca connect to?\", QLineEdit::Normal, dummy, &ok);\n\n if (!ok) {\n return;\n } else {\n servermode = true;\n if (1) {\n QMessageBox::information(this,\"Guaca is slaved\",\"Guaca slaved to \\\"\"+host+\"\\\"...\",QMessageBox::Cancel);\n } else {\n QMessageBox::warning(this,\"Guaca is not slaved\",\"Could not connect to \\\"\"+host+\"\\\".\",QMessageBox::Cancel);\n }\n servermode = false;\n }\n}\n\nvoid MainWindow::on_actionAbout_triggered()\n{\n QMessageBox::about(this,\"About Guaca\",\"Guaca v1.2\\n\\nGuaca is a front end for the data acquisition client mole. \\n\"\"\"\n \"To learn more about mole functionality, see \\\"mole --help\\\"\\n\\n\"\n \"Copyright J. Romualdez 2017-2020\");\n}\n\nvoid MainWindow::on_actionAbout_Qt_triggered()\n{\n QMessageBox::aboutQt(this,\"About Qt\");\n}\n\nvoid MainWindow::on_actionOptions_triggered()\n{\n options->load_options();\n options->show();\n}\n\nvoid MainWindow::on_actionPurge_old_data_triggered()\n{\n QString deletecmd = \"find \" + QString(archivedir) + \"/. -type d -exec rm -r \\\"{}\\\" \\\\;\";\n QMessageBox::StandardButton reply = QMessageBox::question(this,\n \"Delete archived data?\",\n \"Are you sure you want to run '\" + deletecmd + \"'?\",\n QMessageBox::Yes|QMessageBox::No);\n if (reply == QMessageBox::Yes) {\n if (system(deletecmd.toLatin1().data()) < 0) {\n QMessageBox::information(\n this,\n tr(\"Guacamole!\"),\n tr(\"Couldn't clear archived data.\"));\n }\n }\n}\n\nvoid MainWindow::on_hosts_activated(int index)\n{\n if (change_remote_host(ui->hosts->itemText(index))) {\n saveConfig();\n }\n host_index = index;\n ui->hosts->setCurrentIndex(host_index);\n}\n\nvoid MainWindow::on_actionClear_remote_hosts_triggered()\n{\n while (ui->hosts->count() > 2) {\n ui->hosts->removeItem(1);\n }\n host_index = 1;\n on_hosts_activated(1);\n}\n\nvoid MainWindow::on_linkSelect_activated(const QString &arg1)\n{\n linkItem = arg1;\n}\n\n/*\n * Populates the linklist selector based on the linklists chosen from\n * the main linklist list widget.\n */\n\nvoid MainWindow::on_multiLinkSelect_itemSelectionChanged()\n{\n ui->linkSelect->clear();\n linkSelect.clear();\n\n QList<QListWidgetItem *> items = ui->multiLinkSelect->selectedItems();\n foreach(QListWidgetItem * T, items)\n {\n ui->linkSelect->addItem(T->text());\n linkSelect << T->text();\n }\n\n auto_select_link();\n}\n\n\nvoid MainWindow::on_computeFrameMap_clicked()\n{\n\n}\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 20.83333396911621, "blob_id": "233b11833c156b5c9c0d74d61d18cc98f5f10dda", "content_id": "fe7d9eb6a6b0ec0fd9b1aae6c688d9f1eee29b98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 261, "license_type": "no_license", "max_line_length": 40, "num_lines": 12, "path": "/external_libs/soem/oshw/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "set(OSHW_SRCS\n ${OSHW_SRCS}\n ${CMAKE_CURRENT_SOURCE_DIR}/oshw.c\n ${CMAKE_CURRENT_SOURCE_DIR}/nicdrv.c\n PARENT_SCOPE\n)\nset(OSHW_HEADERS\n ${OSHW_HEADERS}\n ${CMAKE_CURRENT_SOURCE_DIR}/oshw.h\n ${CMAKE_CURRENT_SOURCE_DIR}/nicdrv.h\n PARENT_SCOPE\n)" }, { "alpha_fraction": 0.688858687877655, "alphanum_fraction": 0.695652186870575, "avg_line_length": 18.36842155456543, "blob_id": "e83609a6a4eb6888a4516a6cca08eed81bf5a250", "content_id": "de77644f1b78d3a9136712a6b90f382f2998dd35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 737, "license_type": "no_license", "max_line_length": 73, "num_lines": 38, "path": "/stars/code/housekeeping/measurement.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef HOUSEKEEPING__MEASUREMENT_H\n#define HOUSEKEEPING__MEASUREMENT_H\n\n#include <string>\n\nnamespace Housekeeping\n{\n class Measurement;\n}\n\nclass Housekeeping::Measurement\n{\n public:\n Measurement();\n void add_value(double value);\n bool get_value(double& value);\n\n int channel;\n std::string name;\n double scale;\n double offset;\n std::string units;\n\n private:\n static const unsigned int num_values = 5;\n double values[num_values];\n unsigned int next_write_index;\n bool valid;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6564971804618835, "alphanum_fraction": 0.6564971804618835, "avg_line_length": 13.475409507751465, "blob_id": "c437787381a65d70d5ddafcb8fa4cf394a261262", "content_id": "cc52557d1d133e9c5eb83d210d3144a0ee34beb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 885, "license_type": "no_license", "max_line_length": 75, "num_lines": 61, "path": "/stars/code/solving/finding/badpix.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#pragma once\n\n#ifndef SOLVING__FINDING__BADPIX_H\n#define SOLVING__FINDING__BADPIX_H\n\n#include <string>\n#include <vector>\n#include <map>\n#include \"estimator.h\"\n\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n}\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Solving\n{\n\tclass Blob;\n\n namespace Finding\n {\n class Badpix;\n }\n}\n\nclass Solving::Finding::Badpix\n{\n public:\n\tBadpix(Parameters::Manager& params);\n ~Badpix();\n int load_badpix( std::string fname);// Load bad pixel map from file\n\tvoid fix_badpix(Shared::Image::Raw& image);\t // set bad pixels to map mean\n \tstd::string badpixlist;\n\tint *satcol;\n\tint satval;\n\tdouble mapmean; \n\tint mapmeans;\n\n\tstruct badpixels \n\t{\n\t\tint xpix;\n\t\tint ypix;\n\t} ;\n\n private:\n\tstd::vector<badpixels> badpairs;\n\tunsigned int numbadpix; \n\tint image_width;\n int image_height;\n };\n\n#endif \n\n" }, { "alpha_fraction": 0.5758790969848633, "alphanum_fraction": 0.582510769367218, "avg_line_length": 21.91166114807129, "blob_id": "88e6295e294a655a3e0c07f49ed80f8d4b81616f", "content_id": "fd5028ad3599d1cf0da4a7bd0d04c0989517f9e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6484, "license_type": "no_license", "max_line_length": 90, "num_lines": 283, "path": "/cow/src/widgets.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* cow: GUI commanding front-end\n *\n * This software is copyright (C) 2002-2006 University of Toronto\n * Parts of this software are copyright 2010 Matthew Truch\n *\n * This file is part of cow.\n *\n * cow 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 2 of the License, or\n * (at your option) any later version.\n *\n * cow 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 cow; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n// ***************************************************\n// * Programmed by Adam Hincks *\n// * Later poked at a bit by D.V.Wiebe *\n// * further desecrated by cbn *\n// * Commanding hacked to hell by M.D.P.Truch *\n// * \"Ported\" to qt4 by drmrshdw *\n// ***************************************************\n\n#ifndef WIDGETS_H\n#define WIDGETS_H\n\n#include \"cow.h\"\n\n#include <QLineEdit>\n#include <QTextEdit>\n#include <QDebug>\n#include <QComboBox>\n#include <QCompleter>\n\nclass AbstractCowEntry\n{\npublic:\n virtual void RecordDefaults() //fill default element\n {\n defaults->Set(command, param, Text());\n }\n\n void SetDefaultValue(int i, int j) {\n if (type == 'i' || type == 'l')\n SetValue(defaults->asInt(i, j));\n else if (type == 's')\n SetStringValue(defaults->asString(i, j));\n else\n SetValue(defaults->asDouble(i, j));\n }\n\n virtual void SetParentField(int com, int par)\n {\n command = com;\n param = par;\n }\n\n virtual void SetType(char t)=0;\n virtual void SetValue(double d)=0;\n virtual void SetStringValue(QString s)=0;\n virtual void SetIndex(int i) {Q_UNUSED(i)}\n virtual QString Text() const=0;\nprotected:\n int command, param;\n char type;\n};\n\nclass CowStringEntry : public QLineEdit, public AbstractCowEntry\n{\n Q_OBJECT\npublic:\n CowStringEntry(QWidget* parent, QString objName) : QLineEdit(parent)\n {\n setObjectName(objName);\n }\n virtual void SetType(char t)\n {\n Q_UNUSED(t);\n Q_ASSERT(t=='s');\n }\n virtual void SetValue(double d)\n {\n Q_UNUSED(d);\n qFatal(\"Depricated call to NarcilStringEntry::SetValue(...).\");\n }\n void SetStringValue(QString s)\n {\n setText(s);\n }\n QString Text() const\n {\n return text();\n }\n};\n\nclass CowComboEntry : public QComboBox, public AbstractCowEntry\n{\n Q_OBJECT\n public:\n CowComboEntry(QWidget* parent, QString objName) : QComboBox(parent)\n {\n minVal = 0;\n setObjectName(objName);\n connect(this, SIGNAL(currentIndexChanged(int)), this, SLOT(slotValueChanged()));\n }\n virtual void SetType(char t)\n {\n Q_ASSERT(t!='s');\n type = t;\n }\n virtual void SetValue(double d)\n {\n SetValue(int(d));\n }\n\n virtual void SetValue(int i)\n {\n\n i -= minVal;\n\n i = qMin(i, count()-1);\n i = qMax(i,0);\n\n setCurrentIndex(i);\n }\n\n void SetStringValue(QString s)\n {\n bool ok;\n int i = s.toInt(&ok);\n if (!ok) {\n i = findText(s);\n }\n SetValue(i);\n }\n\n virtual void SetIndex(int i)\n {\n setCurrentIndex(i);\n }\n\n QString Text() const\n {\n\n return QString::number(currentIndex() + minVal);\n }\n\n int minVal;\n\n public slots:\n void slotValueChanged()\n { //to override parent's valueChanged signal to require focus\n if (hasFocus()) {\n emit valueEdited();\n }\n }\n\n signals:\n void valueEdited();\n\n};\n\n#include <iostream>\nclass NLineEdit : public QLineEdit\n{\n Q_OBJECT\nprotected:\n void mouseDoubleClickEvent(QMouseEvent *) {\n selectAll();\n }\n};\n\nclass CowDoubleEntry : public QDoubleSpinBox, public AbstractCowEntry\n{\n Q_OBJECT\npublic:\n CowDoubleEntry(QWidget* parent, QString objName) : QDoubleSpinBox(parent)\n {\n// delete lineEdit();\n setLineEdit(new NLineEdit);\n setObjectName(objName);\n setMinimum(-__DBL_MAX__);\n setMaximum(__DBL_MAX__);\n connect(this, SIGNAL(valueChanged(double)), this, SLOT(slotValueChanged()));\n }\n\n void SetType(char t)\n {\n Q_ASSERT(t!='s');\n setDecimals(((t=='i' || t=='l') ? 0 : 5));\n type = t;\n }\n\n void SetValue(double d)\n {\n setValue(d);\n }\n\n QString Text() const\n {\n return text();\n }\n\n double value() const\n {\n Q_ASSERT(type!='s');\n return QDoubleSpinBox::value();\n }\n\n void SetStringValue(QString s)\n {\n bool ok=0;\n SetValue(s.toDouble(&ok));\n if(!ok) {\n SetValue(s.toInt(&ok));\n }\n Q_ASSERT(ok);\n }\n QValidator::State validate(QString &input, int &pos) const\n {\n if(input.indexOf('.')!=-1) {\n QString x=input;\n x.remove(0,x.indexOf('.')+1);\n input.chop(qMax(0,x.size()-decimals()));\n }\n return QDoubleSpinBox::validate(input,pos);\n }\n\npublic slots:\n void slotValueChanged()\n { //to override parent's valueChanged signal to require focus\n if (hasFocus()) {\n emit valueEdited();\n }\n }\n\nsignals:\n void valueEdited();\n\n};\n\nclass CowOmniBox : public QLineEdit\n{\n Q_OBJECT\n int oldXSize;\n\n //hack to prevent QCompleter from overwriting the box text: track real text separately\n QString _realText;\n\npublic:\n friend class MainForm;\n CowOmniBox(QWidget*p) : QLineEdit(p), oldXSize(0), _realText() {\n connect(this,SIGNAL(textChanged(QString)),this,SLOT(updateRealText()));\n connect(this,SIGNAL(realTextChanged()),this,SLOT(updateRealText()));\n }\n\n void setRealText(const QString &text) {\n _realText = text;\n setText(text);\n }\n QString & realText() { return _realText; }\n\npublic slots:\n void updateRealText() { //connect to textChanged to prevent Qt from resetting it\n if (text() != realText()) {\n setText(realText());\n emit realTextChanged();\n }\n }\n\nsignals:\n void realTextChanged();\n};\n\n#endif // WIDGETS_H\n" }, { "alpha_fraction": 0.44220617413520813, "alphanum_fraction": 0.4698527455329895, "avg_line_length": 23.650684356689453, "blob_id": "720bca14ade9f710d5c117ecb8df3bce93d22ecd", "content_id": "2699017c3d06b79de19ca4ca5aeb65f9fd1d408a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7198, "license_type": "no_license", "max_line_length": 95, "num_lines": 292, "path": "/cathy/cathy.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* cathy.c: Converts a dirfile field to a text stream on stdout\n *\n * This software is copyright (C) 2010 Matthew Truch\n *\n * This file is part of cathy licensed under the GNU\n * General Public License.\n *\n * You should have received a copy of the GNU General Public License\n * along with this software; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#define CATHY_VERSION \"1.1.0\"\n\n#define _XOPEN_SOURCE 1000\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <getdata.h>\n#include <getopt.h>\n#include <signal.h>\n\n#define DIRFILE_DEFAULT \"/data/etc/defile.lnk\"\n#define CHATTER_DEFAULT \"chatter\"\n#define OLD_DATA_LIMIT 50\n#define IDLE_SYNC 150\n\n#define NOR \"\\x1B[0m\"\n#define RED \"\\x1B[31;1m\"\n#define GRN \"\\x1B[32;1m\"\n#define YLW \"\\x1B[33;1m\"\n#define BLU \"\\x1B[34;1m\"\n#define MAG \"\\x1B[35;1m\"\n#define CYN \"\\x1B[36;1m\"\n#define NOC \"\\x1B[?25l\"\n#define CUR \"\\x1B[?25h\"\n\n\n#define BUF_LEN 1024\n\nvoid usage(char *exe)\n{\n fprintf(stderr, \"%s [-d DIRFILE] [-c CHAR_FIELD] [-r|-s] [-v|-q] [-b|-k] [-7|-8]\\n\", exe);\n fprintf(stderr, \"Translate CHAR_FIELD from DIRFILE into ASCII on stdout.\\n\");\n fprintf(stderr, \"-d PATH_TO_DIRFILE [%s]\\n\", DIRFILE_DEFAULT);\n fprintf(stderr, \"-c CHAR_FIELD [%s]\\n\", CHATTER_DEFAULT);\n fprintf(stderr, \"-r (reconnect) | -s (single shot) [-r]\\n\");\n fprintf(stderr, \"-v (verbose) | -q (quiet) [-v]\\n\");\n fprintf(stderr, \"-b (b&w) | -k (color) [auto-detect]\\n\");\n fprintf(stderr, \"-7 (7-bit ascii) | -8 (UTF-8) [-7]\\n\");\n fprintf(stderr, \"This is cathy version %s\\n\", CATHY_VERSION);\n fprintf(stderr, \"This is FREE software (GPL) with NO WARRANTY\\n\");\n exit(-1);\n}\n\nvoid clear_colors(int sig)\n{\n printf(\"%s%s\\n\", NOR, CUR);\n signal(SIGINT, SIG_DFL);\n exit(1);\n}\n\nint main (int argc, char **argv)\n{\n char char_buffer[BUF_LEN];\n char dirfile_name[BUF_LEN];\n char chatter_name[BUF_LEN];\n DIRFILE *dirfile;\n off_t nf;\n off_t nf_old = 0;\n off_t ff = -1;\n size_t n_read;\n uint16_t *data;\n off_t i;\n char a, b, prev_char;\n int c;\n int sync;\n\n unsigned int old_data = 0;\n int reload = 1;\n int verbose = 1;\n int color = isatty(fileno(stdout));\n int utf8 = 0;\n int index;\n int old_index = -1;\n\n snprintf(dirfile_name, BUF_LEN, \"%s\", DIRFILE_DEFAULT);\n snprintf(chatter_name, BUF_LEN, \"%s\", CHATTER_DEFAULT);\n\n while ((c = getopt(argc, argv, \"d:c:rqvsh?f:bk78\")) != -1)\n {\n switch (c)\n {\n case 'd':\n snprintf(dirfile_name, BUF_LEN, \"%s\", optarg);\n break;\n case 'c':\n snprintf(chatter_name, BUF_LEN, \"%s\", optarg);\n break;\n case 'r':\n reload = 1;\n break;\n case 's':\n reload = 0;\n break;\n case 'v':\n verbose = 1;\n break;\n case 'q':\n verbose = 0;\n break;\n case 'f':\n ff = (off_t)strtoll(optarg, NULL, 0);\n break;\n case 'b':\n color = 0;\n break;\n case 'k':\n color = 1;\n break;\n case '7':\n utf8 = 0;\n break;\n case '8':\n utf8 = 1;\n break;\n case 'h':\n case '?':\n default:\n usage(argv[0]);\n break;\n }\n }\n\n if (color)\n signal(SIGINT, clear_colors);\n\n while (1) /* Main Loop */\n {\n if (verbose)\n {\n fprintf(stderr, \"Reading \\\"%s\\\" from %s\\n\", chatter_name, dirfile_name);\n }\n \n dirfile = gd_open(dirfile_name, GD_RDONLY);\n if (gd_error(dirfile))\n {\n fprintf(stderr, \"GetData error: %s\\n\", gd_error_string(dirfile, char_buffer, BUF_LEN));\n gd_close(dirfile);\n exit(-1);\n }\n \n unsigned int spf = gd_spf(dirfile, chatter_name);\n if (gd_error(dirfile))\n {\n fprintf(stderr, \"GetData error: %s\\n\", gd_error_string(dirfile, char_buffer, BUF_LEN));\n gd_close(dirfile);\n exit(-2);\n }\n \n data = malloc(BUF_LEN * spf * sizeof(uint16_t));\n if (data == NULL)\n {\n fprintf(stderr, \"malloc error!\\n\");\n exit(-3);\n }\n\n if (ff < 0)\n {\n nf_old = gd_nframes(dirfile);\n if (gd_error(dirfile))\n {\n fprintf(stderr, \"GetData error: %s\\n\", gd_error_string(dirfile, char_buffer, BUF_LEN));\n gd_close(dirfile);\n exit(-4);\n }\n } else {\n nf_old = ff;\n }\n\n prev_char = '\\n';\n sync = 0;\n \n while (1) /* Data reading loop */\n {\n nf = gd_nframes(dirfile);\n if (gd_error(dirfile))\n {\n fprintf(stderr, \"GetData error: %s\\n\", gd_error_string(dirfile, char_buffer, BUF_LEN));\n gd_close(dirfile);\n if (reload)\n break;\n else\n exit(-5);\n }\n \n if (nf > nf_old)\n {\n old_data = 0;\n n_read = gd_getdata(dirfile, chatter_name, nf_old, 0, BUF_LEN, 0, GD_UINT16, data);\n nf_old += (n_read / spf);\n for (i = 0; i < n_read; i++)\n {\n if (utf8)\n {\n a = data[i] & 0xFF;\n b = (data[i] >> 8) & 0xFF;\n } else {\n a = data[i] & 0x7F;\n b = (data[i] >> 8) & 0x7F;\n index = ((data[i] & 0x80) >> 6) + ((data[i] & 0x8000) >> 15);\n if (old_index == -1 && index > 0)\n old_index = index - 1;\n if (old_index > -1) //Check that the index is sequential.\n {\n if (index == old_index) {\n old_index = index;\n continue;\n } else if (index == (old_index + 2) % 0x4) {\n if (a != 0x16 && a != 0x00 && b != 0x16 && b != 0x00)\n printf(\"__\");\n } else if (index == (old_index + 3) % 0x4) {\n if (a != 0x16 && a != 0x00 && b != 0x16 && b != 0x00)\n printf(\"____\");\n }\n old_index = index;\n }\n }\n\n if (color)\n {\n if (prev_char == '\\n' && (a == '*' || a == '!' || a == '$'))\n printf(RED);\n if (a == '\\n')\n printf(NOR);\n }\n if (a != 0x16 && a != 0x00)\n {\n if (color && sync > IDLE_SYNC)\n printf(CUR);\n putchar(a);\n prev_char = a;\n sync = 0;\n } else {\n sync++;\n }\n\n if (color)\n {\n if (prev_char == '\\n' && (b == '*' || b == '!' || b == '$'))\n printf(RED);\n if (b == '\\n')\n printf(NOR);\n }\n if (b != 0x16 && b != 0x00)\n {\n if (color && sync > IDLE_SYNC)\n printf(CUR);\n putchar(b);\n prev_char = b;\n sync = 0;\n } else {\n sync++;\n if (color)\n if (sync % IDLE_SYNC == 0)\n {\n printf(\"%s\", (sync / IDLE_SYNC) & 0x1 ? NOC : CUR);\n fflush(stdout);\n }\n }\n }\n fflush(stdout);\n } else {\n usleep(100000);\n old_data++;\n\n if (reload)\n {\n if (old_data > OLD_DATA_LIMIT)\n {\n old_data = 0;\n nf_old = 0;\n gd_close(dirfile);\n break;\n }\n }\n }\n }\n } \n return 0;\n}\n" }, { "alpha_fraction": 0.7017828226089478, "alphanum_fraction": 0.7082657814025879, "avg_line_length": 16.13888931274414, "blob_id": "bf9745319886943ea9e63f790eaaaa7129a85d5d", "content_id": "76d994ce484d11fa229396503f3653f1488501e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 618, "license_type": "no_license", "max_line_length": 73, "num_lines": 36, "path": "/stars/code/shared/network/client.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__NETWORK__CLIENT_H\n#define SHARED__NETWORK__CLIENT_H\n\n#include \"../circular_buffer.h\"\n\nnamespace Shared\n{\nnamespace Network\n{\n\nclass Client\n{\n public:\n Client();\n int counter_fcp;\n};\n\n// writes: network\n// reads: main\nextern Shared::CircularBufferPass <Client> client_for_main;\n\n// writes: main\n// reads: camera\nextern Shared::CircularBuffer <Client> client_for_camera;\n\n}\n}\n\n#endif\n" }, { "alpha_fraction": 0.6846950650215149, "alphanum_fraction": 0.6892980337142944, "avg_line_length": 18.75, "blob_id": "28aa709a478c9a96970c9f670cfa69b198c16d56", "content_id": "8d3ce492f5d1c94bab8ad7c4250cc19ea63b8c5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 870, "license_type": "no_license", "max_line_length": 73, "num_lines": 44, "path": "/stars/code/shared/camera/results.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__CAMERA__RESULTS_H\n#define SHARED__CAMERA__RESULTS_H\n\n#include \"../circular_buffer.h\"\n#include \"../result.h\"\n#include \"requests.h\"\n\nnamespace Shared\n{\n namespace Camera\n {\n\nclass Results\n{\n public:\n Results();\n Results& operator=(const Results& rhs);\n bool is_gain_valid(Requests& requests);\n\n int counter_stars;\n bool connected;\n ::Shared::Result<double> set_gain;\n ::Shared::Result<double> get_gain;\n};\n\n// writes: camera\n// reads: main\nextern Shared::CircularBufferPass <Results> results_for_main;\n\n// writes: main\n// reads: network\nextern Shared::CircularBuffer <Results> results_for_network;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.6649560332298279, "alphanum_fraction": 0.6730205416679382, "avg_line_length": 27.39583396911621, "blob_id": "735926f61944ad6d6625ce47ff725bbac4dcb945", "content_id": "5f330857181290043b01048e5dfb2a75df412f2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1365, "license_type": "no_license", "max_line_length": 75, "num_lines": 48, "path": "/stars/code/shared/image/solution_summary.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"solution_summary.h\"\n#include \"../../solving/solution.h\"\n\nusing namespace Shared::Image;\n\n\nSolutionSummary::SolutionSummary()\n{\n counter_stars = -1;\n Solving::clear_solution_attitude(equatorial);\n Solving::clear_solution_attitude(horizontal);\n solving_time = 0.0;\n num_blobs_total = 0;\n num_blobs_matched = 0;\n measured_exposure = 0.0;\n blob_names.clear();\n}\n\nSolutionSummary& SolutionSummary::operator=(const SolutionSummary& rhs)\n{\n if (this != &rhs) {\n counter_stars = rhs.counter_stars;\n equatorial = rhs.equatorial;\n horizontal = rhs.horizontal;\n solving_time = rhs.solving_time;\n num_blobs_total = rhs.num_blobs_total;\n num_blobs_matched = rhs.num_blobs_matched;\n measured_exposure = rhs.measured_exposure;\n blob_names = rhs.blob_names;\n }\n return *this;\n}\n\nSolutionSummary& SolutionSummary::operator=(const ::Solving::Solution& rhs)\n{\n equatorial = rhs.equatorial;\n horizontal = rhs.horizontal;\n num_blobs_total = rhs.num_blobs_total;\n num_blobs_matched = rhs.matched_blobs.size();\n measured_exposure = rhs.measured_exposure;\n return *this;\n}\n\n" }, { "alpha_fraction": 0.6159461140632629, "alphanum_fraction": 0.6372824311256409, "avg_line_length": 40.406978607177734, "blob_id": "2d960da3f0d5ab1c4593599f5d53d255c8d81aba", "content_id": "f30a4dca35e93ff10bfa10baa0a7cbdeb5ce0bac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3563, "license_type": "no_license", "max_line_length": 115, "num_lines": 86, "path": "/stars/code/solving/solution.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"solution.h\"\n#include \"../tools/angles.h\"\n#include <boost/format.hpp>\n#include \"../shared/image/raw.h\"\n#include \"../logging/logger.h\"\n\nusing namespace Solving;\n\nSolution::Solution()\n{\n equatorial.valid = false;\n equatorial.ra = 0.0;\n equatorial.dec = 0.0;\n equatorial.roll = 0.0;\n equatorial.sigma_ra = 2.0*M_PI;\n equatorial.sigma_dec = 2.0*M_PI;\n equatorial.sigma_roll = 2.0*M_PI;\n equatorial.sigma_pointing = 2.0*M_PI;\n equatorial.iplatescale = from_arcsec(9.5);\n\n horizontal.valid = false;\n horizontal.az = 0.0;\n horizontal.el = 0.0;\n horizontal.roll = 0.0;\n horizontal.sigma_az = 2.0*M_PI;\n horizontal.sigma_el = 2.0*M_PI;\n horizontal.sigma_roll = 2.0*M_PI;\n horizontal.sigma_pointing = 2.0*M_PI;\n horizontal.iplatescale = from_arcsec(9.5);\n\n num_blobs_total = 0;\n measured_exposure = 0.0;\n}\n\nvoid Solution::print(Logging::Logger& logger, bool print_matches, bool print_base_matches)\n{\n logger.log(format(\"solution: found %d catalog stars in fov\") % stars_in_fov.size());\n for (unsigned int i=0; i<stars_in_fov.size(); i++) {\n stars_in_fov[i].print(logger, \"solution: star \");\n }\n for (unsigned int i=0; i<matched_blobs.size() && i<matched_stars.size(); i++) {\n logger.log(format(\"solution: blob with id %d matches star with id %d and ccd pos %.2f %.2f\")\n % matched_blobs[i].id % matched_stars[i].id\n % matched_stars[i].fitted_x % matched_stars[i].fitted_y);\n }\n if (print_base_matches) {\n for (unsigned int i=0; i<base_blobs.size() && i<base_stars.size(); i++) {\n logger.log(format(\"solution: base blob with id %d matches base star with id %d\")\n % base_blobs[i].id % base_stars[i].id);\n }\n }\n logger.log(format(\"solution: matched %d of %d\") % matched_blobs.size() % num_blobs_total);\n\n if (equatorial.valid) {\n logger.log(format(\"solution: equatorial attitude (deg) %0.4f %0.4f %0.4f\")\n % to_degrees(equatorial.ra) % to_degrees(equatorial.dec) % to_degrees(equatorial.roll));\n logger.log(format(\"solution: equatorial errors (arcsec) %0.3f %0.3f %0.3f\")\n % to_arcsec(equatorial.sigma_ra) % to_arcsec(equatorial.sigma_dec) % to_arcsec(equatorial.sigma_roll));\n logger.log(format(\"solution: equatorial pointing error (arcsec) %0.3f\")\n % to_arcsec(equatorial.sigma_pointing));\n logger.log(format(\"solution: equatorial iplatescale (arcsec/px) %0.3f\")\n % to_arcsec(equatorial.iplatescale));\n }\n\n if (horizontal.valid) {\n logger.log(format(\"solution: horizontal attitude (deg) %0.4f %0.4f %0.4f\")\n % to_degrees(horizontal.az) % to_degrees(horizontal.el) % to_degrees(horizontal.roll));\n logger.log(format(\"solution: horizontal errors (arcsec) %0.3f %0.3f %0.3f\")\n % to_arcsec(horizontal.sigma_az) % to_arcsec(horizontal.sigma_el) % to_arcsec(horizontal.sigma_roll));\n logger.log(format(\"solution: horizontal pointing error (arcsec) %0.3f\")\n % to_arcsec(horizontal.sigma_pointing));\n logger.log(format(\"solution: horizontal iplatescale (arcsec/px) %0.3f\")\n % to_arcsec(horizontal.iplatescale));\n }\n}\n\nbool Solution::sort_by_num_matches(Solution first, Solution second)\n{\n return first.matched_blobs.size() > second.matched_blobs.size();\n}\n\n" }, { "alpha_fraction": 0.7257617712020874, "alphanum_fraction": 0.7396121621131897, "avg_line_length": 37.40425491333008, "blob_id": "2ead7cc0ddfd9171e9fba317a35e277abaf81202", "content_id": "4cfd40fc65abdef5ee74820716a498d6079759a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1805, "license_type": "no_license", "max_line_length": 124, "num_lines": 47, "path": "/owl/PMultiDataItem.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#ifndef PMULTIDATAITEM_H\n#define PMULTIDATAITEM_H\n\n#include \"PMap.h\"\n#include \"PAbstractDataItem.h\"\n#include <getdata/dirfile.h>\n\nclass PMultiDataItem : public PAbstractDataItem\n{\n Q_OBJECT\n PMap* _map;\n PStyle* _lastNStyle;\npublic:\n friend QDataStream& operator<<(QDataStream&a,PAbstractDataItem&b);\n friend QDataStream& operator>>(QDataStream&a,PMultiDataItem &b);\n friend QVariant save(PAbstractDataItem&);\n friend void load(QVariant v,PMultiDataItem&);\n friend class PDotPal;\n friend class PMainWindow;\n PMultiDataItem(PBox*parent,QString caption) : PAbstractDataItem(parent,caption), _map(new PMap),_lastNStyle(0) {}\n PMultiDataItem(PBox*parent,PMultiDataItem* other) : PAbstractDataItem(parent,other), _map(other->_map),_lastNStyle(0) {}\n virtual void gdUpdate(GetData::Dirfile* dirFile,int lastNFrames);\n virtual PStyle* getPrevDataStyle() { return _lastNStyle?_lastNStyle:_defaultDataStyle; }\n};\n\n#endif // PMULTIDATAITEM_H\n" }, { "alpha_fraction": 0.5612045526504517, "alphanum_fraction": 0.5705905556678772, "avg_line_length": 23.11320686340332, "blob_id": "8f74cc028f87678743accc5c5b8f0aac96a1baec", "content_id": "afa6ec74f892e718a9a945c99a7f5238466f1d43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 2557, "license_type": "no_license", "max_line_length": 134, "num_lines": 106, "path": "/news/Makefile", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "CC=gcc\nCFLAGS = -g \n\n########################################################\n# External repository dependencies\n#\n\nBLAST_ONLY=1 # we need at least one of Spider or BLAST config\n\n########################################################\n# Inputs\n#\n\nSHARED_OBJS = compressfuncs.o\nLOCAL_OBJS = news_utils.o\nEXPT_OBJS = tx_struct.o compressstruct.o derived.o slowdl_struct.o\n\nSHARED_HEADERS = include/channels_tng.h include/derived.h\n\n########################################################\n# Run the sanity checks and prepare the build system\n#\n\ninclude ../common/Makefile.shared\n\n########################################################\n# Set up targets\n#\n\nBLAST_ALL = rumor-blast\n\nifeq ($(HAVE_BLASTCONF),1)\n\tALL += $(BLAST_ALL)\nendif\n\nifeq ($(HAVE_SPIDERCONF),1)\n\tALL += $(SPIDER_ALL)\nendif\n\n########################################################\n# Build Stuff\n#\n\n.PHONY: install clean\n\nall:: $(ALL)\n\n../common/Makefile.shared:\n\t@echo \"ERROR: **************************************************************\"\n\t@echo \"Common build files not found; unable to continue. Try:\"\n\t@echo \" ( cd .. && svn co `svn info --non-interactive | awk ' /URL/ { print $$2 } ' | sed -e 's/trunk\\/.*/trunk\\/common/'` common )\"\n\t@false\n\nframelist.inc: ../spider_config/tx_struct.c tx_struct_mce.c\n\t../spider_config/make_framelist_inc > $@\n\ncompressstruct_spider.o :: framelist.inc\n\ntx_struct_spider.o :: tx_struct_mce.c\n\ntx_struct_mce.c: ../spider_config/make_tx_struct_mce \\\n\t../spider_config/tes.h\n\t../spider_config/make_tx_struct_mce > $@\n\nfox-blast: fox_blast.o $(BLAST_OBJS)\n\t$(CC) -o fox-blast $^ -lm \n\nfox-spider: fox_spider.o $(SPIDER_OBJS)\n\t$(CC) -o fox-spider $^ -lm \n\nrumor-blast: rumor.o $(BLAST_OBJS)\n\t$(CC) -o rumor-blast rumor.o $(BLAST_OBJS) -lm -lgetdata \n\nrumor-spider: rumor.o $(SPIDER_OBJS)\n\t$(CC) -o rumor-spider rumor.o $(SPIDER_OBJS) -lm -lgetdata\n\n# Hard-links\nmsnbc-blast rush-blast: fox-blast\n\tln -f $< $@\n\nmsnbc-spider rush-spider: fox-spider\n\tln -f $< $@\n\nclean:\n\trm -f $(BLAST_ALL) $(SPIDER_ALL)\n\trm -f *.o framelist.inc\n\trm -f tx_struct_mce.c\n\n########################################################\n# Install stuff\n#\n\ninstall: all\n\trm -f /usr/local/bin/fox\n\trm -f /usr/local/bin/msnbc\n\trm -f /usr/local/bin/rush\nifeq ($(HAVE_BLASTCONF),1)\n\tinstall -m 755 fox-blast /usr/local/bin\n\tinstall -m 755 msnbc-blast /usr/local/bin\n\tinstall -m 755 rush-blast /usr/local/bin\nendif\nifeq ($(HAVE_SPIDERCONF),1)\n\tinstall -m 755 fox-spider /usr/local/bin\n\tinstall -m 755 msnbc-spider /usr/local/bin\n\tinstall -m 755 rush-spider /usr/local/bin\nendif\n\n" }, { "alpha_fraction": 0.6783607602119446, "alphanum_fraction": 0.6889165043830872, "avg_line_length": 22.007143020629883, "blob_id": "10466bab13ba243dbf1dae94189ac1fb8979bb93", "content_id": "50fc3e409190a2bbb9f922882fdd9cc8a66a4606", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3222, "license_type": "no_license", "max_line_length": 110, "num_lines": 140, "path": "/stars/code/shared/solving/filters.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__SOLVING__FILTERS_H\n#define SHARED__SOLVING__FILTERS_H\n\n#include \"../circular_buffer.h\"\n#include \"../../tools/timing.h\"\n#include \"../../tools/angles.h\"\n\nnamespace Logging\n{\n class Logger;\n}\n\nnamespace Solving\n{\n class Solution;\n}\n\nnamespace Shared\n{\n namespace Solving\n {\n\nstruct HorizontalFromSettings\n{\n HorizontalFromSettings(): enabled(false), lat(0), lst(0) {}\n bool enabled;\n double lat;\n double lst;\n};\n\nstruct HorizontalFromFits\n{\n HorizontalFromFits(): enabled(false), valid(false), lat(0), lst(0) {}\n bool enabled;\n bool valid;\n double lat;\n double lst;\n};\n\nstruct HorizontalFromFCP\n{\n HorizontalFromFCP(): enabled(false), lat(0), lst(0) {}\n bool enabled;\n Tools::Timer age;\n double lat;\n double lst;\n};\n\nstruct HorizontalLocation\n{\n HorizontalLocation(): enabled(false), radius(30), az(0), el(0) {}\n bool enabled;\n double radius;\n double az;\n double el;\n};\n\nstruct RollLimit\n{\n RollLimit(): enabled(false), min_roll(0), max_roll(2.0*M_PI) {}\n bool enabled;\n double min_roll;\n double max_roll;\n};\n\nstruct HorizontalElevationLimit\n{\n HorizontalElevationLimit(): enabled(false), min_el(-M_PI/2.0), max_el(M_PI/2.0) {}\n bool enabled;\n double min_el;\n double max_el;\n};\n\nstruct EquatorialLocation\n{\n EquatorialLocation(): enabled(false), radius(30), ra(0), dec(0) {}\n bool enabled;\n double radius;\n double ra;\n double dec;\n};\n\nstruct Matching\n{\n Matching(): pointing_error_threshold(from_arcsec(10.0)), fit_error_threshold_px(2000.0), num_matched(8) {}\n double pointing_error_threshold;\n double fit_error_threshold_px;\n unsigned int num_matched;\n};\n\nclass Filters\n{\n public:\n Filters();\n void init(Parameters::Manager& params);\n Filters& operator=(const Filters& rhs);\n bool try_get_horizontal(double& lat, double& lst);\n double lat() const;\n double lst() const;\n bool horizontal_known() const;\n bool horizontal_known_and_filters_enabled() const;\n bool check_object(double ra, double dec, double max_distance);\n bool check_field_star(double ra, double dec, double platescale_max);\n bool check_roll_limit(RollLimit& roll_limit, double roll);\n bool check_solution(::Solving::Solution& solution, Logging::Logger& logger, bool final_check=false);\n\n int image_width;\n int image_height;\n double horizontal_from_fcp_age_limit;\n HorizontalFromSettings horizontal_from_settings;\n HorizontalFromFits horizontal_from_fits;\n HorizontalFromFCP horizontal_from_fcp;\n\n HorizontalLocation horizontal_location;\n RollLimit horizontal_roll_limit;\n HorizontalElevationLimit horizontal_elevation_limit;\n EquatorialLocation equatorial_location;\n RollLimit equatorial_roll_limit;\n Matching matching;\n};\n\n// writes: network\n// reads: main\nextern Shared::CircularBufferPass <Filters> filters_net_to_main;\n\n// writes: main\n// reads: camera\nextern Shared::CircularBuffer <Filters> filters_main_to_camera;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.575412929058075, "alphanum_fraction": 0.5851610898971558, "avg_line_length": 23.613332748413086, "blob_id": "f1b48eb5694777740412f04cad4bebff81a6507f", "content_id": "4a7ca853d35cb9820590582d7692b8420f7756c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3694, "license_type": "no_license", "max_line_length": 102, "num_lines": 150, "path": "/stars/code/shared/image/raw.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"raw.h\"\n#include <cstring>\n#include \"../../parameters/manager.h\"\n\nusing namespace Shared::Image;\n\nRaw::Raw()\n{\n which_sensor = \"unknown\";\n from_camera = false;\n num_exposures = 0;\n\n counter_stars = -1;\n key_counter_stars = -1;\n counter_fcp = -1;\n dirname = \"\";\n filename_base = \"\";\n filename = \"\";\n to_be_solved = false;\n\n focus_known = false;\n focus = -1;\n aperture_known = false;\n aperture = -1;\n gain_known = false;\n gain = -1.0;\n\n has_netisc_framenum = false;\n netisc_framenum = 0;\n\n width = 0;\n height = 0;\n depth = 0;\n single_depth = 0;\n}\n\nvoid Raw::init(Parameters::Manager& params)\n{\n\twidth = params.general.try_get(\"imaging.camera_real.image_width\", params.general.image_width);\n\theight = params.general.try_get(\"imaging.camera_real.image_height\", params.general.image_height);\n\tdepth = params.general.try_get(\"imaging.camera_real.image_depth\", params.general.image_depth);\n\n single_depth = depth;\n pixels = new unsigned short[width*height];\n for (unsigned int i=0; i<max_num_exposures; i++) {\n separate_buffers[i] = new unsigned short[width*height];\n }\n pixels = new unsigned short[width*height];\n which_sensor = params.general.try_get(\"main.which_sensor\", std::string(\"unknown\"));\n filters.init(params);\n}\n\nRaw::~Raw()\n{\n delete [] pixels;\n for (unsigned int i=0; i<max_num_exposures; i++) {\n delete [] separate_buffers[i];\n }\n}\n\ndouble Raw::get_pixel(int x, int y)\n{\n if (x>=0 && x<width && y>=0 && y<height) {\n return pixels[y*width + x];\n }\n return 0.0;\n}\n\nbool Raw::is_inbounds(int& x, int& y)\n{\n if (x<0 || x>=width) {\n return false;\n }\n if (y<0 || y>=height) {\n return false;\n }\n return true;\n}\n\nbool Raw::is_inbounds(double& x, double& y)\n{\n if (x<0 || x>=width) {\n return false;\n }\n if (y<0 || y>=height) {\n return false;\n }\n return true;\n}\n\nbool Raw::is_xy_inbounds(double& x, double& y)\n{\n if (x < -width/2.0 || x > width/2.0) {\n return false;\n }\n if (y < -height/2.0 || y > height/2.0) {\n return false;\n }\n return true;\n}\n\nRaw& Raw::operator=(const Raw &rhs)\n{\n if (this != &rhs) {\n which_sensor = rhs.which_sensor;\n from_camera = rhs.from_camera;\n num_exposures = rhs.num_exposures;\n\n counter_stars = rhs.counter_stars;\n key_counter_stars = rhs.key_counter_stars;\n counter_fcp = rhs.counter_fcp;\n dirname = rhs.dirname;\n filename_base = rhs.filename_base;\n filename = rhs.filename;\n age = rhs.age;\n\n to_be_solved = rhs.to_be_solved;\n width = rhs.width;\n height = rhs.height;\n depth = rhs.depth;\n single_depth = rhs.single_depth;\n memcpy(pixels, rhs.pixels, width*height*sizeof(unsigned short));\n\n for (unsigned int i=0; i<rhs.num_exposures; i++) {\n memcpy(separate_buffers[i], rhs.separate_buffers[i], width*height*sizeof(unsigned short));\n }\n\n focus_known = rhs.focus_known;\n focus= rhs.focus;\n aperture_known = rhs.aperture_known;\n aperture= rhs.aperture;\n gain_known = rhs.gain_known;\n gain = rhs.gain;\n\n has_netisc_framenum = rhs.has_netisc_framenum;\n netisc_framenum = rhs.netisc_framenum;\n\n filters = rhs.filters;\n //horizontal_known = rhs.horizontal_known;\n //lat = rhs.lat;\n //lst = rhs.lst;\n }\n return *this;\n}\n\n" }, { "alpha_fraction": 0.6416361927986145, "alphanum_fraction": 0.6579084992408752, "avg_line_length": 32.91645431518555, "blob_id": "dd5d731bb77facd792b3b15461345fd78d66be6f", "content_id": "677716250debe515adb56b9f4f9c8dd257f5423d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13397, "license_type": "no_license", "max_line_length": 106, "num_lines": 395, "path": "/blast_config/include/command_list.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* command_list.h: BLAST command specification file definitions\n *\n * This software is copyright (C) 2002-2012 University of Toronto\n *\n * This file is part of the BLAST flight code licensed under the GNU\n * General Public License.\n *\n * You should have received a copy of the GNU General Public License\n * along with this software; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#ifndef INCLUDE_COMMAND_LIST_H\n#define INCLUDE_COMMAND_LIST_H\n\n#include <limits.h>\n#include <sys/types.h>\n\n#include \"netcmd.h\" /* common parts of command defintions moved here */\n\n\n#define DATA_Q_SIZE (2 * MAX_N_PARAMS) /* maximum size of the data queue */\n\n#define MAX_15BIT (32767.) // deprecated. Probably want CMD_I_MAX instead\n#define CMD_I_MAX USHRT_MAX\n#define CMD_L_MAX UINT_MAX\n\n#define N_GROUPS 31\n\n#define GRPOS_POINT 0\n#define GRPOS_BAL 1\n#define GRPOS_HWPR 2\n#define GRPOS_TRIM 3\n#define GRPOS_ELECT 4 // empty, remove after 2018 flight? -PAW\n#define GRPOS_BIAS 5\n#define GRPOS_VETO 6\n#define GRPOS_ACT 7\n#define GRPOS_XSC_HOUSE 8\n#define GRPOS_XSC_MODE 9\n#define GRPOS_XSC_PARAM 10\n#define GRPOS_MOTOR 11\n#define GRPOS_CRYO 12\n#define GRPOS_POWER 13\n#define GRPOS_LOCK 14\n#define GRPOS_TELEM 15\n#define GRPOS_MISC 16\n#define GRPOS_FOCUS 17\n#define GRPOS_ROACH 18\n#define GRPOS_PSS 19\n\n#define GR_POINT (1 << GRPOS_POINT)\n#define GR_BAL (1 << GRPOS_BAL)\n#define GR_HWPR (1 << GRPOS_HWPR)\n#define GR_TRIM (1 << GRPOS_TRIM)\n#define GR_ELECT (1 << GRPOS_ELECT)\n#define GR_BIAS (1 << GRPOS_BIAS)\n#define GR_VETO (1 << GRPOS_VETO)\n#define GR_ACT (1 << GRPOS_ACT)\n#define GR_XSC_HOUSE (1 << GRPOS_XSC_HOUSE)\n#define GR_XSC_MODE (1 << GRPOS_XSC_MODE)\n#define GR_XSC_PARAM (1 << GRPOS_XSC_PARAM)\n#define GR_MOTOR (1 << GRPOS_MOTOR)\n#define GR_CRYO (1 << GRPOS_CRYO)\n#define GR_POWER (1 << GRPOS_POWER)\n#define GR_LOCK (1 << GRPOS_LOCK)\n#define GR_TELEM (1 << GRPOS_TELEM)\n#define GR_MISC (1 << GRPOS_MISC)\n#define GR_FOCUS (1 << GRPOS_FOCUS)\n#define GR_ROACH (1 << GRPOS_ROACH)\n#define GR_PSS (1 << GRPOS_PSS)\n\n// reserved for CONFIRM 0x80000000\n\nextern const char *command_list_serial;\nextern const char *GroupNames[N_GROUPS];\nextern const char *linklist_names[];\nextern const char *downlink_names[];\nextern const char *pilot_target_names[];\nextern const char *stream_types[];\n\n/* singleCommand enumeration. The command list here does NOT have to be in\n * order relative to the command definitions in command_list.c */\nenum singleCommand {\n az_auto_gyro, az_off, az_on,\n balance_auto, balance_off, balance_terminate,\n // cal_off, cal_on,\n hwpr_panic, el_off, el_on,\n elclin_allow, elclin_veto,\n fixed,\n l_valve_close, he_valve_on, he_valve_off, l_valve_open,\n elmotenc_allow, elmotenc_veto,\n xsc0_veto, xsc0_allow,\n xsc1_veto, xsc1_allow, dgps_veto, dgps_allow,\n mag_allow_fc1, mag_veto_fc1, mag_allow_fc2, mag_veto_fc2,\n pin_in, ramp, reset_trims,\n stop, pss_veto,\t\t trim_xsc0_to_xsc1,\n pss_allow, trim_xsc1_to_xsc0, autotrim_off,\n trim_to_xsc0, unlock, lock_off,\n force_el_on,\n actbus_cycle,\n charge_off,\t charge_on,\t\tcharge_cycle,\n\n ifroll_1_gy_allow, ifroll_1_gy_veto, ifroll_2_gy_allow, ifroll_2_gy_veto,\n ifyaw_1_gy_allow, ifyaw_1_gy_veto, ifyaw_2_gy_allow, ifyaw_2_gy_veto,\n ifel_1_gy_allow, ifel_1_gy_veto,\tifel_2_gy_allow, ifel_2_gy_veto,\n ifroll_1_gy_off, ifroll_1_gy_on,\tifroll_2_gy_off, ifroll_2_gy_on,\n ifyaw_1_gy_off, ifyaw_1_gy_on,\tifyaw_2_gy_off,\t ifyaw_2_gy_on,\n ifel_1_gy_off, ifel_1_gy_on,\tifel_2_gy_off,\t ifel_2_gy_on,\n gybox_cycle,\n reap_fc1, reap_fc2,\n xy_panic,\n trim_to_xsc1, antisun, blast_rocks, blast_sucks,\n at_float, not_at_float, el_auto_gyro,\n repoll, autofocus_allow,\n autofocus_veto, halt_fc1, halt_fc2, actbus_on,\n actbus_off, actuator_stop, restore_piv,\n reset_rw, reset_piv,\n reset_elev, reset_ethercat, rw_wake_and_wiggle,\n // hs_pot_on, hs_pot_off, bda_on, bda_off,\n hwpr_enc_on,\n hwpr_enc_off, hwpr_enc_pulse,\n vtx1_xsc0,\t vtx1_xsc1,\t\tvtx2_xsc0,\n vtx2_xsc1,\n hwpr_step, hwpr_pot_is_dead, hwpr_pot_is_alive,\n hwpr_step_off, hwpr_step_on, shutter_init, shutter_close,\n shutter_reset, shutter_open, shutter_off, shutter_open_close,\n shutter_keepopen, shutter_keepclosed,\n lock45, shutter_close_slow, heater_300mk_on, heater_300mk_off,\n charcoal_hs_on, charcoal_hs_off,\n lna350_on, lna350_off, lna250_on, lna250_off, lna500_on, lna500_off,\n // level_sensor_on, level_sensor_off,\n charcoal_on, charcoal_off,\n heater_1k_on, heater_1k_off, power_box_on, power_box_off, amp_supply_on,\n amp_supply_off, therm_readout_on, therm_readout_off, heater_supply_on,\n vent_valve_A_open, vent_valve_A_close, vent_valve_A_off, vent_valve_A_on,\n vent_valve_B_open, vent_valve_B_close, vent_valve_B_off, vent_valve_B_on,\n aalborg_vent_valve_open, aalborg_vent_valve_close,\n aalborg_pump_A_valve_open, aalborg_pump_A_valve_close,\n aalborg_pump_B_valve_open, aalborg_pump_B_valve_close,\n ln_valve_on, ln_valve_off,\n potvalve_on, potvalve_off, potvalve_open, potvalve_close,\n heater_supply_off, reboot_ljcryo1, bias_reset_rox,\n heater_sync, allow_cycle, disallow_cycle,\n\thd_pv_cycle, eth_switch_cycle, fc1_cycle, xsc1_cycle, fc2_cycle,\n\txsc0_cycle, gyros_cycle, data_transmit_cycle, elmot_cycle, pivot_cycle,\n mag_cycle, rw_cycle, steppers_cycle, clino_cycle, of_lj_cycle,\n\tgps_timing_cycle, auto_pump_cycle, if_lj_cycle, timing_dist_cycle, vtx_cycle,\n\tbi0_cycle, if_6_cycle, if_eth_switch_cycle, if_8_cycle, roach_cycle,\n\tcryo_hk_cycle, force_cycle,\n\thd_pv_on, hd_pv_off, eth_switch_on, eth_switch_off,\n\tfc1_on, fc1_off, xsc1_on, xsc1_off,\n\tfc2_on, fc2_off, xsc0_on, xsc0_off,\n\tgyros_on, gyros_off, data_transmit_on, data_transmit_off,\n\telmot_on, elmot_off, pivot_on, pivot_off,\n\tmag_on, mag_off, mag_reset, rw_on, rw_off,\n\tsteppers_on, steppers_off, clino_on, clino_off,\n\tof_lj_on, of_lj_off, gps_timing_on, gps_timing_off,\n gps_sw_reset, gps_stats, auto_pump_on, auto_pump_off, if_lj_on, if_lj_off,\n\ttiming_dist_on, timing_dist_off, bi0_on, bi0_off,\n\tvtx_on, vtx_off, if_relay_6_on, if_relay_6_off,\n\tif_eth_switch_on, if_eth_switch_off, if_relay_8_on, if_relay_8_off,\n\troach_on, roach_off, cryo_hk_on, cryo_hk_off,\n\tlevel_sensor_pulse, single_cal_pulse, heaters_off, load_curve, vtx_xsc0,\n vtx_xsc1, vna_sweep_all, targ_sweep_all, find_kids_default_all, force_pot_refill,\n center_lo_all, calc_dfs, change_amps, load_freqs_all,\n reload_vna_all, end_sweeps_all, new_ref_params_all,\n auto_find_kids_all, zero_df_all, roach_reset_all, change_freqs_all, df_targ_all, check_df_retune_all,\n check_dfsweep_retune_all, allow_watchdog, disallow_watchdog, set_attens_last_all, set_attens_min_output,\n trigger_retune_check, full_loop_default_all, set_attens_default_all, chop_lo_all, median_sweep_df_all,\n read_attens_all, read_lo_all, reset_log,\n read_pi_temp_all, stop_ir, static_ir, blue_valve_enable, blue_valve_disable, pumps_enable,\n pumps_disable, aalborg_enable, aalborg_disable, xyzzy\n};\n\n/* multiCommand enumeration. The command list here does NOT have to be in\n * order relative to the command definitions in command_list.c */\nenum multiCommand {\n az_el_goto, az_gain, az_scan, balance_gain,\n balance_manual, balance_vel, balance_i,\n bias_level_500, bias_level_350, bias_level_250, bias_level_rox,\n bias_level_x, set_tcrit_fpa,\n // fridge_cycle_params,\n box,\n // cal_repeat,\n cap, cur_mode,\n az_el_trim, drift, el_gain,\n hwpr_goto_rel, hwpr_goto_i,\n autotrim_to_sc,\n lock, phase, act_offset,\n pivot_gain, ra_dec_goto, ra_dec_set,\n pos_set,\n az_scan_accel,\n // t_gyro_set,\n highrate_bw, pilot_bw, biphase_bw,\n biphase_clk_speed, highrate_through_tdrss, set_linklists,\n request_file, set_roach_chan, set_roach_all_chan,\n set_queue_execute, reconnect_lj, set_roach_mode,\n request_stream_file, set_pilot_oth, ir_source_pulse,\n\n // t_gyro_gain,\n timeout, vcap,\n vbox, slot_sched, az_gyro_offset,\n hwpr_set_overshoot, hwpr_set_backoff,\n // jfet_set,\n hwpr_vel, hwpr_i,\n gyro_off,\t quad,\n el_gyro_offset, general, slew_veto, set_secondary,\n thermo_gain, actuator_servo, xy_goto, actuator_vel,\n xy_jump, xy_xscan, xy_yscan, xy_raster,\n actuator_i, lock_vel, lock_i, actuator_delta,\n delta_secondary, lvdt_limit, thermo_param, focus_offset,\n motors_verbose, fix_ethercat, bias_step,\n // phase_step,\n hwpr_repeat, hwpr_define_pos, hwpr_set_margin, params_test,\n hwpr_goto,\t hwpr_goto_pot, act_enc_trim, actuator_tol,\n el_scan, el_box, shutter_step, shutter_step_slow,\n shutter_i, \t shutter_vel,\n set_scan_params, mag_cal_fc1,\tmag_cal_fc2, pss_cal, pss_cal_n,\n pss_set_noise,\n pss_cal_d, pss_cal_el, pss_cal_az, pss_cal_roll, pss_cal_array_az, pss_set_imin,\n potvalve_set_thresholds, potvalve_set_tighten_move,\n potvalve_set_vel, potvalve_set_current, potvalve_set_hold_current,\n valves_set_vel, valves_set_move_i, valves_set_hold_i, valves_set_acc,\n aalborg_set_speeds, aalborg_finite_move,\n labjack9_write_reg,\n\n xsc_is_new_window_period,\n xsc_offset,\n xsc_heaters_off,\n xsc_heaters_on,\n xsc_heaters_auto,\n xsc_exposure_timing,\n xsc_multi_trigger,\n xsc_trigger_threshold,\n xsc_scan_force_trigger,\n xsc_quit,\n xsc_shutdown,\n xsc_network_reset,\n xsc_main_settings,\n xsc_display_zoom,\n xsc_image_client,\n xsc_init_focus,\n xsc_get_focus,\n xsc_set_focus,\n xsc_stop_focus,\n xsc_define_focus,\n xsc_set_focus_incremental,\n xsc_run_autofocus,\n xsc_set_autofocus_range,\n xsc_abort_autofocus,\n xsc_autofocus_display_mode,\n xsc_init_aperture,\n xsc_get_aperture,\n xsc_set_aperture,\n xsc_stop_aperture,\n xsc_define_aperture,\n xsc_get_gain,\n xsc_set_gain,\n xsc_fake_sky_brightness,\n xsc_solver_general,\n xsc_solver_abort,\n xsc_selective_mask,\n xsc_blob_finding,\n xsc_blob_cells,\n xsc_pattern_matching,\n xsc_filter_hor_location,\n xsc_filter_hor_roll,\n xsc_filter_el,\n xsc_filter_eq_location,\n xsc_filter_matching,\n vna_sweep,\n targ_sweep,\n roach_reset,\n calc_df,\n opt_tones,\n auto_retune,\n end_sweep,\n show_adc_rms,\n load_new_vna_amps,\n load_new_targ_amps,\n set_targ_sweep_span_all,\n set_targ_sweep_span,\n set_trnd_sweep_span_all,\n set_trnd_sweep_span,\n change_state,\n get_state,\n set_attens,\n test_tone,\n find_kids,\n set_rox_bias_amp,\n cal_length,\n level_length,\n send_dac,\n new_output_atten,\n cal_sweeps,\n periodic_cal,\n calc_phase_centers,\n timestream,\n cal_amps,\n refit_freqs,\n refit_freqs_all,\n targ_refit,\n targ_refit_all,\n chop_template,\n load_freqs,\n new_ref_params,\n center_lo,\n offset_lo,\n roach_ts_all,\n roach_ts,\n offset_lo_all,\n find_kids_default,\n change_amp,\n change_freq,\n set_cal_timeout,\n change_phase,\n auto_find_kids,\n offset_freq,\n set_attens_all,\n reboot_pi,\n read_attens,\n set_attens_conserve,\n set_attens_calc,\n set_lo_MHz,\n read_lo,\n roach_df_all,\n df_targ,\n roach_set_allow_trnd_sweeps,\n roach_set_allow_trnd_sweeps_all,\n full_loop,\n full_loop_all,\n full_loop_default,\n check_lamp_retune,\n check_lamp_retune_all,\n check_df_retune,\n check_dfsweep_retune,\n median_sweep_df,\n auto_correct,\n auto_correct_all,\n set_retune_type,\n set_retune_type_all,\n noise_comp,\n noise_comp_all,\n find_kids_loop,\n find_kids_loop_all,\n kill_roach,\n set_df_retune_threshold,\n set_df_retune_threshold_all,\n set_df_diff_retune_threshold,\n set_df_diff_retune_threshold_all,\n set_min_nkids,\n set_min_nkids_all,\n set_max_nkids,\n set_max_nkids_all,\n set_default_tone_power,\n set_default_tone_power_all,\n set_attens_default,\n set_find_kids_params,\n compress_roach_data,\n enable_cycle_checker,\n turnaround_loop,\n turnaround_loop_all,\n set_n_outofrange_thresh_all,\n set_n_outofrange_thresh,\n enable_chop_lo_all,\n enable_chop_lo,\n chop_lo,\n roach_has_lamp_control,\n roach_set_extref,\n roach_set_extref_all,\n enable_roach_cal_pulse,\n read_pi_temp,\n plugh, // plugh should be at the end of the list\n sched_packet = 0xffe // not really a command, more of a placeholder\n};\n\n#define N_SCOMMANDS (xyzzy + 1)\n#define N_MCOMMANDS (plugh + 2)\n\nextern struct scom scommands[N_SCOMMANDS];\n\n/* parameter type:\n * i : parameter is 15 bit unnormalised integer\n * f : parameter is 15 bit renormalised floating point\n * l : parameter is 30 bit renormalised floating point\n */\nextern struct mcom mcommands[N_MCOMMANDS];\n\n/* validator function for mcommands */\nextern int mcom_validate(enum multiCommand cmd, const int *ivalues,\n const double *rvalues, char svalues[][CMD_STRING_LEN], size_t buflen,\n char *err_buffer);\n\n#endif /* COMMAND_LIST_H */\n" }, { "alpha_fraction": 0.6706452965736389, "alphanum_fraction": 0.6803431510925293, "avg_line_length": 32.936710357666016, "blob_id": "4f3606ef97c672b7656b0fad34a4feb423738fef", "content_id": "3427194ad31cef69eb3eb60b08178c169600f449", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2681, "license_type": "no_license", "max_line_length": 134, "num_lines": 79, "path": "/owl/PWebServer.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2014 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"PWebServer.h\"\n#include \"PMainWindow.h\"\n#include <QHostAddress>\n#include <QMessageBox>\n#include <QJsonDocument>\n#include <QJsonObject>\n\nPWebServer::PWebServer(PMainWindow* parent, const int& port)\n : QObject(parent)\n , m_port(port)\n , m_server(new QWebSocketServer(\"owl\", QWebSocketServer::NonSecureMode, this))\n , m_parent(parent)\n{\n connect(m_server, SIGNAL(newConnection()), this, SLOT(handleNewConnection()));\n if (!m_server->listen(QHostAddress::Any, port)) {\n QMessageBox::warning(parent, \"Bad port\", \"Could not listen on port \" + QString::number(port) + \": \" + m_server->errorString(),\n QMessageBox::Ok);\n delete m_server;\n m_server = 0;\n } else {\n //qDebug() << \"Server is up on port\" << port;\n }\n}\n\nPWebServer::~PWebServer() {\n // QWebSocketServer does not take ownership of QWebSockets, according to QWebSocketServer::nextPendingConnection\n for (int i = 0; i < m_sockets.length(); ++i) {\n delete m_sockets[i];\n }\n}\n\nvoid PWebServer::handleNewConnection() {\n while (m_server->hasPendingConnections()) {\n QWebSocket* socket = m_server->nextPendingConnection();\n writeState(socket);\n m_sockets.push_back(socket);\n }\n}\n\nvoid PWebServer::update() {\n for (int i = 0; i < m_sockets.length(); ++i) {\n writeUpdates(m_sockets[i]);\n }\n}\n\nvoid PWebServer::writeState(QWebSocket* socket) {\n if (socket->isValid()) {\n QJsonDocument document = QJsonDocument::fromVariant(m_parent->state());\n socket->sendTextMessage(document.toJson(QJsonDocument::Compact));\n }\n}\n\nvoid PWebServer::writeUpdates(QWebSocket* socket) {\n if (socket->isValid()) {\n QJsonDocument document = QJsonDocument::fromVariant(m_parent->stateChanges());\n socket->sendTextMessage(document.toJson(QJsonDocument::Compact));\n }\n}\n" }, { "alpha_fraction": 0.4989626407623291, "alphanum_fraction": 0.5414937734603882, "avg_line_length": 24.02597427368164, "blob_id": "49b95676c8d367c8fe2acb434ae477e0b7c83af4", "content_id": "578db6f64691b7fbdb169474681472304d4a3c95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1929, "license_type": "no_license", "max_line_length": 91, "num_lines": 77, "path": "/stars/code/displaying/blob.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"blob.h\"\n#include <cstdlib>\n#include <string>\n#include <time.h>\n#include \"glhelper.h\"\n#include <math.h>\n\nusing namespace Displaying;\n\ndouble random_number()\n{\n return double(rand()/double(RAND_MAX));\n}\n\nBlob::Blob(double x_, double y_, int blob_num_)\n{\n x = x_;\n y = y_;\n halfsize = 26.0;\n birth_angle = 0.0;\n blob_num = blob_num_;\n rotation_speed = 80.0;\n birth_time = (x + y)/4000.0;\n born = false;\n timer.start();\n name = \"\";\n}\n\nvoid Blob::draw(Size& size_, double global_age, double intercept, bool matched, bool named)\n{\n if (!born) {\n if (intercept > x+y) {\n born = true;\n timer.start();\n }\n }\n if (born) {\n double age = timer.time();\n double scaling = 1.2;\n double angle = 0;\n\t\tglDisable(GL_TEXTURE_2D);\n if (matched) {\n if (named) {\n\t\t\t\tGL::Color4f(1.0, 0.8, 0.3, 1.0);\n } else {\n GL::Color4f(1.0, 0.0, 0.3, 1.0);\n }\n } else {\n scaling = age*30.0 * exp(-age*11.0) + 1.0;\n angle = birth_angle + rotation_speed*global_age;\n\t\t\tangle = fmod(angle, 360.);\n GL::Color4f(0.75, 0.75, 1.0, 1.0);\n }\n\n glPushMatrix();\n\t\tglLineWidth(2.0);\n glTranslatef((GLfloat) x, (GLfloat) y, 0);\n glRotatef((GLfloat) angle, 0, 0, 1);\n glScalef((GLfloat) scaling, (GLfloat) scaling, 1);\n\t\tglColor3f(0.75f, 0.75f, 1.0f);\n\t\t\n glBegin(GL_LINE_LOOP);\n glVertex2d(-halfsize, -halfsize);\n glVertex2d(-halfsize, halfsize);\n glVertex2d(halfsize, halfsize);\n glVertex2d(halfsize, -halfsize);\n glEnd();\n glPopMatrix();\n\t\tglEnable(GL_TEXTURE_2D);\n }\n}\n\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6879432797431946, "avg_line_length": 31.538461685180664, "blob_id": "6a80227f2a096ba5518d5d1bb6f48f4448e3c4c6", "content_id": "0f6bfdc1e7cbaed04f17c15b261a6fe6bd366a9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1269, "license_type": "no_license", "max_line_length": 79, "num_lines": 39, "path": "/owl/PDirfileDataItem.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"PDirfileDataItem.h\"\n#include \"PMainWindow.h\"\n#include <QMouseEvent>\n#include <QApplication>\n#include <QDebug>\n\nvoid PDirfileDataItem::gdUpdate(GetData::Dirfile *dirFile, int)\n{\n QString x=dirFile->Name();\n if(x.endsWith('/')) x.chop(1);\n if(x.contains('/')) {\n x.remove(0,x.lastIndexOf('/')+1);\n }\n if(_data->text()!=x) {\n _data->setText(x);\n _serverDirty=-1;\n } else --_serverDirty;\n}\n" }, { "alpha_fraction": 0.6985237002372742, "alphanum_fraction": 0.7025641202926636, "avg_line_length": 24.239215850830078, "blob_id": "aab7eafd6cdfe2eda2c03d2b7016a2b24f407bf3", "content_id": "39a3c1ce657a0cb65e36c41cfb7bdb1b92b66e9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6435, "license_type": "no_license", "max_line_length": 154, "num_lines": 255, "path": "/balloon_cam/camera.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//camera.cpp\n//a wrapper class for the camera fuctionality, used to return the pictures\n\n#include \"StdAfx.h\"\n#include \"camera.h\"\n#include \"pixelfixer.h\"\n\nCamera::Camera(){\n\tif(!initCamera()){\n\t\tprintf(\"Camera failed to initialize. Giving up.\\n\");\n\t\tisOpen = false;\n\t}else{\n\t\tisOpen = true;\n\t}\n}\n\nbool Camera::closeCamera(){\n\tis_StopLiveVideo(cameraHandle, IS_WAIT);\n\tis_ClearSequence(cameraHandle);\n\tfor(int i = 0; i<100; i++){\n\t\tis_FreeImageMem(cameraHandle, ringBuffer[i+1], i+1);//frees the memory that was used\n\t}\n\n\tis_ExitCamera(cameraHandle);//closes the camera\n\tisOpen = false;//tell the wrapper class that it is closed\n\treturn true;\n}\n\nvoid* Camera::capture(){\n\tif(!isOpen){//makes sure that the camera is still open\n\t\tprintf(\"Camera is not open for pictures. Returning.\\n\");\n\t\treturn NULL;\n\t}\n\tint status;\n\tif(memoryID != 0){\n\t\t//status = is_UnlockSeqBuf(cameraHandle, IS_IGNORE_PARAMETER, (char*)activeMemoryLocation);\n\n\t\tif(status != IS_SUCCESS){\n\t\t\tprintf(\"unlocking buffer fails\\n\");\n\t\t}\n\t}\n\n\tint memoryId;\n\tchar* currMemory;\n\tchar* lastMemory;\n\n\tstatus = is_GetActSeqBuf(cameraHandle, &memoryId, &currMemory, &lastMemory); \n\n\tif(status != IS_SUCCESS){\n\t\tprintf(\"getting buffer fails\\n\");\n\t\treturn NULL;\n\t}\n\n\tactiveMemoryLocation = lastMemory;\n\tmemoryID = memoryId;\n\tint i =0;\n\tfor(; i<=100; i++){\n\t\tif(ringBuffer[i] == lastMemory){\n\t\t\tbreak;\n\t\t}\n\t}\n\n\n\t//status = is_LockSeqBuf(cameraHandle, IS_IGNORE_PARAMETER, ringBuffer[i]);\n\n\tif(status != IS_SUCCESS){\n\t\tprintf(\"Locking buffer fails\\n\");\n\t}\n\n\treturn (void*)lastMemory;\t\n}\n\nint Camera::getXSize(){\n\treturn sensorInfo.nMaxWidth;\n}\n\nint Camera::getYSize(){\n\treturn sensorInfo.nMaxHeight;\n}\n\nint Camera::getPixelSize(){\n\treturn colourDepth;\n}\n\ndouble Camera::getExposureTime(){\n\treturn exposureTime;\n}\n\nvoid Camera::saveActiveData(){\n\tif(!isOpen){//makes sure camera is open\n\t\tprintf(\"Camera is not open to save data. Returning\\n\");\n\t\treturn;\n\t}\n\t\n\tint status;\n\t//status = is_SetImageMem(cameraHandle, (char*)activeMemoryLocation, memoryID);\n\n\tstatus = is_SaveImage(cameraHandle, NULL);//saves the image\n\tif(status == IS_NO_SUCCESS){\n\t\tprintf(\"save image fails\\n\");\n\t}\n}\n\n\nbool Camera::initCamera(){\n\n\tcameraHandle = 1;\n\n\tint status = is_InitCamera(&cameraHandle, NULL);//initiates the camera\n\tif(status != IS_SUCCESS){\n\t\tprintf(\"is_InitCamera() failed. Checking to see whether you need to upgrade firmware...\\n\");\n\t\tif (status == IS_STARTER_FW_UPLOAD_NEEDED)\n\t\t{\n\t\tprintf(\"Upgrading starter firmware. This may take a minute! Do NOT disconnect the camera from the PC or from power during this step.\\n\");\n\t\t\tstatus = is_InitCamera((HIDS*)((unsigned long) &cameraHandle | IS_ALLOW_STARTER_FW_UPLOAD), NULL); //helpful overloaded function upgrades our fw for us\n\t\t\tif (status != IS_SUCCESS)\n\t\t\t{\n\t\t\t\tprintf(\"OpenCamera() still failed. Ensure firmware is up-to-date.\\n\"); \n\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse\n\t\t\t{ //it must have returned IS_SUCCESS. Thus the new starter FW is uploaded during initialisation.\n\t\t\t\tprintf(\"Starter firmware upgraded successfully.\\n\");\n\t\t\t}\n\t\t}\n\t\telse \n\t\t{ // if the initial nRet did not return IS_SUCCESS or IS_STARTER_FW_UPLOAD_NEEDED then it returned a general error message.\n\t\t\tprintf(\"OpenCamera() returned IS_NO_SUCCESS. Check code please?\\n\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t// get sensor info:\n\tstatus = is_GetSensorInfo(cameraHandle, &sensorInfo);\n\tif (status != IS_SUCCESS) \n\t{ \n\t\tprintf(\"Failed to get sensor info!\\n\"); \n\t\treturn false;\n\t}\n\t// get board info:\n\tstatus = is_GetBoardInfo(cameraHandle, &boardInfo);\n\tif (status != IS_SUCCESS)\n\t{\n\t\tprintf(\"Failed to get board info!\\n\"); \n\t\treturn false;\n\t}\n\n\tint colourDepth;\n\tint colourMode;\n\t//gets the colour depth, and sets the camera to 8 bit greyscale\n\tis_GetColorDepth(cameraHandle, &colourDepth, &colourMode);\n\tis_SetColorMode(cameraHandle, IS_CM_MONO8);\n\n\tthis->colourDepth = 8;\n\n\t//sets the display mode to be the correct one\n\tstatus = is_SetDisplayMode(cameraHandle, IS_SET_DM_DIB);\n\n\tif(status != IS_SUCCESS){\n\t\tprintf(\"set display mode fails\\n\");\n\t\treturn false;\n\t}\n\n\tchar* memoryStartingPointer;\n\tint memoryId;\n\n\tfor(int i = 0; i< 100; i++){\n\t\tmemoryStartingPointer = NULL;\n\t\tmemoryId = 0;\n\t\t//allocates memory for a single picture\n\t\tstatus = is_AllocImageMem(cameraHandle, sensorInfo.nMaxWidth, sensorInfo.nMaxHeight, this->colourDepth, &memoryStartingPointer, &memoryId);\n\t\tif(status != IS_SUCCESS){\n\t\t\tprintf(\"Allocating image memory failed\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\tstatus = is_AddToSequence(cameraHandle, memoryStartingPointer, memoryId);\n\t\tif(status != IS_SUCCESS){\n\t\t\tprintf(\"Adding memory to buffer fails\\n\");\n\t\t\treturn false;\n\t\t}\n\t\tringBuffer[memoryId] = memoryStartingPointer;\n\t\n\t}\n\n\t//sets the memory to be the active memory\n\t//status = is_SetImageMem(cameraHandle, memoryStartingPointer, memoryId);\n\n\tif(status != IS_SUCCESS){\n\t\tprintf(\"Setting image memory failed\\n\");\n\t\treturn false;\n\t}\n\n\tmemoryID = 0;\n\n\t//sets the trigger to be off\n\tstatus = is_SetExternalTrigger(cameraHandle, IS_SET_TRIGGER_OFF);\n\t\n\tif(status != IS_SUCCESS){\n\t\tprintf(\"Set trigger fails\\n\");\n\t\treturn false;\n\t}\n\n\tint pMax;\n\tint pMin;\n\n\tstatus = is_GetPixelClockRange(cameraHandle, &pMin, &pMax);\n\tstatus = is_SetPixelClock(cameraHandle, pMax);\n\n\tif(status != IS_SUCCESS){\n\t\tprintf(\"Setting the pixel clock fails\\n\");\n\t}\n\n\tdouble fps;\n\n\tstatus = is_SetFrameRate(cameraHandle, 10.0, &fps);\n\n\tif(status != IS_SUCCESS){\n\t\tprintf(\"setting frame rate fails\\n\");\n\t\treturn false;\n\t}\n\n\tstatus = is_HotPixel(cameraHandle, IS_HOTPIXEL_GET_CAMERA_USER_LIST_EXISTS, NULL, NULL);\n\n\tif(status != IS_SUCCESS){\n\t\tprintf(\"Bad pixel correction table does not exist. Generating it from files. This could take some time.\\n\");\n\n\t\tPixelFixer pixelFixer = PixelFixer(sensorInfo.nMaxWidth, sensorInfo.nMaxHeight, this->colourDepth);\n\n\t\tWORD* badPixelTable = pixelFixer.generateBadPixelTable(\"../../Pictures\");\n\n\t\tint quantity = (int) (*badPixelTable);\n\n\t\tstatus = is_HotPixel(cameraHandle, IS_HOTPIXEL_SET_CAMERA_USER_LIST, (void*) badPixelTable, (2*quantity +1) *sizeof(WORD));\n\n\t\tif(status != IS_SUCCESS){\n\t\t\tprintf(\"Bad pixel correction table generation has failed. Sorry.\\n\");\n\t\t}\n\t}\n\t\t\n\tstatus = is_HotPixel(cameraHandle, IS_HOTPIXEL_ENABLE_CAMERA_CORRECTION, NULL, NULL);\n\n\tif(status != IS_SUCCESS){\n\t\tprintf(\"Bad pixel correction has failed. Sorry.\\n\");\n\t}\n\n\tstatus = is_CaptureVideo(cameraHandle, IS_WAIT);\n\n\tif(status != IS_SUCCESS){\n\t\tprintf(\"Video Capture fails. Sorry\\n\");\n\t\treturn false;\n\t}\n\n\treturn true;\n}" }, { "alpha_fraction": 0.5088322758674622, "alphanum_fraction": 0.5487955808639526, "avg_line_length": 38.39403533935547, "blob_id": "eefd13dc21a5edff11f17478c59dfd2741d85df2", "content_id": "afd56a87b2eb5b19230d0469212483a37bb28fb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 87180, "license_type": "no_license", "max_line_length": 120, "num_lines": 2213, "path": "/blast_config/command_list.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "\n/* command_list.c: BLAST command specification file\n *\n * This software is copyright (C) 2002-20010 University of Toronto\n *\n * This file is part of the BLAST flight code licensed under the GNU\n * General Public License.\n *\n * You should have received a copy of the GNU General Public License\n * along with this software; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n/* !XXX!!XXX!!XXX!!XXX!!XXX!! BIG ALL CAPS WARNING !!XXX!!XXX!!XXX!!XXX!!XXX!!\n *\n * IF YOU ADD, MODIFY, OR DELETE *ANY* COMMANDS IN THIS FILE YOU *MUST*\n * RECOMPILE AND REINSTALL BLASTCMD ON ARWEN/WIDOW/!\n *\n * !XXX!!XXX!!XXX!!XXX!!XXX!! BIG ALL CAPS WARNING !!XXX!!XXX!!XXX!!XXX!!XXX!!\n */\n\n#include \"include/command_list.h\"\n\nconst char *command_list_serial = \"$Revision: 5.2 $\";\n\nconst char *GroupNames[N_GROUPS] = {\n [GRPOS_POINT] = \"Pointing Modes\",\n [GRPOS_BAL] = \"Balance\",\n [GRPOS_HWPR] = \"Waveplate Rotator\",\n [GRPOS_TRIM] = \"Pointing Sensor Trims\",\n [GRPOS_ELECT] = \"Aux. Electronics\",\n [GRPOS_BIAS] = \"Bias\",\n [GRPOS_ROACH] = \"ROACH Commands\",\n [GRPOS_VETO] = \"Pointing Sensor Vetos\",\n [GRPOS_ACT] = \"Actuators\",\n [GRPOS_XSC_HOUSE] = \"XSC Housekeeping\",\n [GRPOS_XSC_MODE] = \"XSC Mode Settings\",\n [GRPOS_XSC_PARAM] = \"XSC Solving Parameters\",\n [GRPOS_MOTOR] = \"Pointing Motors\",\n [GRPOS_CRYO] = \"Cryo Control\",\n [GRPOS_POWER] = \"Subsystem Power\",\n [GRPOS_LOCK] = \"Lock Motor\",\n [GRPOS_TELEM] = \"Telemetry\",\n [GRPOS_MISC] = \"Miscellaneous\",\n [GRPOS_FOCUS] = \"Focus\",\n [GRPOS_PSS] = \"PSS\",\n };\n\n#define LINKLIST_SELECT \"Linklist\", 0, 64, 'i', \"NONE\", {linklist_names}\n\nconst char *downlink_names[] = {\"Pilot\", \"Bi0\", \"Highrate\", \"SBD\", 0};\nconst char *pilot_target_names[] = {\"highbay\", \"gollum\", \"smeagol\", \"galadriel\", 0};\nconst char *disable_enable[] = {\"Disable\", \"Enable\", 0};\nconst char *internal_external[] = {\"Internal\", \"External\", 0};\nconst char *stream_types[] = {\"$ALL_VNA_SWEEPS\", \"$ALL_TARG_SWEEPS\", \"$ALL_IQ_DATA\",\n \"$ALL_DF_DATA\", \"$ALL_LAMP_DATA\", \"$ALL_NOISE_COMP\",\n \"$ALL_BB_FREQS\", \"$ALL_DS_VNA\", 0};\nconst char *linklist_names[] = {0};\n\n\n// echoes as string; makes enum name the command name string\n#define COMMAND(x) (int)x, #x\n\nstruct scom scommands[xyzzy + 1] = {\n {COMMAND(aalborg_enable), \"enabling vent aalborg\", GR_CRYO},\n {COMMAND(aalborg_disable), \"disabling vent aalborg\", GR_CRYO},\n {COMMAND(pumps_enable), \"enabling microscroll pumps\", GR_CRYO},\n {COMMAND(pumps_disable), \"disabling microscroll pumps\", GR_CRYO},\n {COMMAND(blue_valve_enable), \"enabling blue cycling valve\", GR_CRYO},\n {COMMAND(blue_valve_disable), \"disabling blue cycling valve\", GR_CRYO},\n {COMMAND(load_curve), \"starting load curve\", GR_CRYO},\n {COMMAND(static_ir), \"starting hawkeye IR source\", GR_CRYO},\n {COMMAND(stop_ir), \"stopping hawkeye IR source\", GR_CRYO},\n {COMMAND(reboot_ljcryo1), \"rebooting labjack cryo 1\", GR_POWER},\n {COMMAND(vtx_xsc0), \"Setting video transmitter to XSC0\", GR_XSC_MODE | GR_TELEM},\n {COMMAND(vtx_xsc1), \"Setting video transmitter to XSC1\", GR_XSC_MODE | GR_TELEM},\n {COMMAND(heater_300mk_on), \"turning on 300mK heater\", GR_CRYO},\n {COMMAND(heater_300mk_off), \"turning off 300mK heater\", GR_CRYO},\n {COMMAND(charcoal_hs_on), \"turning on charcoal hs\", GR_CRYO},\n {COMMAND(charcoal_hs_off), \"turning off charcoal hs\", GR_CRYO},\n {COMMAND(single_cal_pulse), \"pulsing the cal lamp\", GR_CRYO},\n {COMMAND(lna250_on), \"turning on 250 lna\", GR_CRYO},\n {COMMAND(lna250_off), \"turning off 250 lna\", GR_CRYO},\n {COMMAND(lna350_on), \"turning on 350 lna\", GR_CRYO},\n {COMMAND(lna350_off), \"turning off 350 lna\", GR_CRYO},\n {COMMAND(lna500_on), \"turning on 500 lna\", GR_CRYO},\n {COMMAND(lna500_off), \"turning off 500 lna\", GR_CRYO},\n {COMMAND(allow_cycle), \"autocycle on\", GR_CRYO},\n {COMMAND(disallow_cycle), \"autocycle_off\", GR_CRYO},\n {COMMAND(allow_watchdog), \"pump pot watchdog on\", GR_CRYO},\n {COMMAND(disallow_watchdog), \"pump pot watchdog off\", GR_CRYO},\n {COMMAND(force_cycle), \"forcing a cycle\", GR_CRYO},\n // {COMMAND(level_sensor_on), \"turning on level sensor\", GR_CRYO},\n // {COMMAND(level_sensor_off), \"turning off level sensor\", GR_CRYO},\n {COMMAND(level_sensor_pulse), \"pulsing the level sensor\", GR_CRYO},\n {COMMAND(charcoal_on), \"turning on charcoal heater\", GR_CRYO},\n {COMMAND(charcoal_off), \"turning off charcoal heater\", GR_CRYO},\n {COMMAND(heaters_off), \"turning off the heater card channels\", GR_CRYO},\n {COMMAND(heater_1k_on), \"turning on 1K heater\", GR_CRYO},\n {COMMAND(heater_1k_off), \"turning off 1K heater\", GR_CRYO},\n {COMMAND(power_box_on), \"turning on the power box\", GR_CRYO},\n {COMMAND(power_box_off), \"turning off the power box\", GR_CRYO},\n {COMMAND(amp_supply_on), \"turning on +5V, +/-15V\", GR_CRYO},\n {COMMAND(amp_supply_off), \"turning off +5V, +/-15V\", GR_CRYO},\n {COMMAND(therm_readout_on), \"turning on 12V channels\", GR_CRYO},\n {COMMAND(therm_readout_off), \"turning off 12V channels\", GR_CRYO},\n {COMMAND(heater_supply_on), \"turning on 40V channels\", GR_CRYO},\n {COMMAND(heater_supply_off), \"turning off 40V channels\", GR_CRYO},\n {COMMAND(heater_sync), \"syncing heater command channel to input\", GR_CRYO},\n {COMMAND(bias_reset_rox), \"Attempt to restart the ALSA sound card ROX bias generation.\", GR_CRYO},\n {COMMAND(stop), \"servo off of gyros to zero speed now\", GR_POINT},\n {COMMAND(antisun), \"turn antisolar now\", GR_POINT},\n// power box OF and IF relay controls\n {COMMAND(hd_pv_cycle), \"powercycling HD PV\", GR_POWER},\n {COMMAND(eth_switch_cycle), \"powercycling Eth Switch\", GR_POWER},\n {COMMAND(fc1_cycle), \"powercycling FC1\", GR_POWER},\n {COMMAND(xsc1_cycle), \"powercycling XSC1\", GR_POWER},\n {COMMAND(fc2_cycle), \"powercycling FC2\", GR_POWER},\n {COMMAND(xsc0_cycle), \"powercycling XSC0\", GR_POWER},\n {COMMAND(gyros_cycle), \"powercycling gyros\", GR_POWER},\n {COMMAND(data_transmit_cycle), \"powercycling Data Transmit\", GR_POWER},\n {COMMAND(elmot_cycle), \"powercycling El Motor\", GR_POWER},\n {COMMAND(pivot_cycle), \"powercycling pivot\", GR_POWER},\n {COMMAND(mag_cycle), \"powercycling magnetometer\", GR_POWER},\n {COMMAND(rw_cycle), \"powercycling RW Motor\", GR_POWER},\n {COMMAND(steppers_cycle), \"powercycling steppers\", GR_POWER},\n {COMMAND(clino_cycle), \"powercycling clinometers\", GR_POWER},\n {COMMAND(of_lj_cycle), \"powercycling OF labjack\", GR_POWER},\n {COMMAND(gps_timing_cycle), \"powercycling gps timing\", GR_POWER},\n {COMMAND(hd_pv_on), \"turning on HD PV\", GR_POWER},\n {COMMAND(eth_switch_on), \"turning on Eth Switch\", GR_POWER},\n {COMMAND(fc1_on), \"turning on FC1\", GR_POWER},\n {COMMAND(xsc1_on), \"turning on XSC1\", GR_POWER},\n {COMMAND(fc2_on), \"turning on FC2\", GR_POWER},\n {COMMAND(xsc0_on), \"turning on XSC0\", GR_POWER},\n {COMMAND(gyros_on), \"turning on OF gyros\", GR_POWER},\n {COMMAND(data_transmit_on), \"turning on Data Transmit\", GR_POWER},\n {COMMAND(elmot_on), \"turning on El Motor\", GR_POWER},\n {COMMAND(pivot_on), \"turning on pivot\", GR_POWER},\n {COMMAND(mag_on), \"turning on magnetometer\", GR_POWER},\n {COMMAND(rw_on), \"turning on RW Motor\", GR_POWER},\n {COMMAND(steppers_on), \"turning on steppers\", GR_POWER},\n {COMMAND(clino_on), \"turning on clinometers\", GR_POWER},\n {COMMAND(of_lj_on), \"turning on OF labjack\", GR_POWER},\n {COMMAND(gps_timing_on), \"turning on gps timing\", GR_POWER},\n {COMMAND(gps_sw_reset), \"reset gps software\", GR_TELEM},\n {COMMAND(gps_stats), \"save gps nema + chrony stats to file at /data/etc/blast/gps/stats.txt\", GR_TELEM},\n {COMMAND(hd_pv_off), \"turning off HD PV\", GR_POWER},\n {COMMAND(eth_switch_off), \"turning off Eth Switch\", GR_POWER},\n {COMMAND(fc1_off), \"turning off FC1\", GR_POWER},\n {COMMAND(xsc1_off), \"turning off XSC1\", GR_POWER},\n {COMMAND(fc2_off), \"turning off FC2\", GR_POWER},\n {COMMAND(xsc0_off), \"turning off XSC0\", GR_POWER},\n {COMMAND(gyros_off), \"turning off OF gyros\", GR_POWER},\n {COMMAND(data_transmit_off), \"turning off Data Transmit\", GR_POWER},\n {COMMAND(elmot_off), \"turning off El Motor\", GR_POWER},\n {COMMAND(pivot_off), \"turning off pivot\", GR_POWER},\n {COMMAND(mag_off), \"turning off magnetometer\", GR_POWER},\n {COMMAND(rw_off), \"turning off RW Motor\", GR_POWER},\n {COMMAND(steppers_off), \"turning off steppers\", GR_POWER},\n {COMMAND(clino_off), \"turning off clinometers\", GR_POWER},\n {COMMAND(of_lj_off), \"turning off OF labjack\", GR_POWER},\n {COMMAND(gps_timing_off), \"turning off gps timing\", GR_POWER},\n {COMMAND(auto_pump_cycle), \"powercycling auto pump\", GR_POWER | CONFIRM},\n {COMMAND(if_lj_cycle), \"powercycling IF labjack\", GR_POWER},\n {COMMAND(timing_dist_cycle), \"powercycling timing distribution box\", GR_POWER},\n {COMMAND(vtx_cycle), \"powercycling video transmitter\", GR_POWER},\n {COMMAND(bi0_cycle), \"powercycling biphase transmitter\", GR_POWER},\n {COMMAND(if_6_cycle), \"powercycling if relay 6\", GR_POWER},\n {COMMAND(if_eth_switch_cycle), \"powercycling IF switches\", GR_POWER},\n {COMMAND(if_8_cycle), \"powercycling if relay 8\", GR_POWER},\n {COMMAND(roach_cycle), \"powercycling ROACH motel\", GR_POWER},\n {COMMAND(cryo_hk_cycle), \"powercycling cryo housekeeping\", GR_POWER},\n {COMMAND(auto_pump_on), \"turning on auto pump\", GR_POWER | CONFIRM},\n {COMMAND(if_lj_on), \"turning on IF labjack\", GR_POWER},\n {COMMAND(timing_dist_on), \"turning on timing distribution box\", GR_POWER},\n {COMMAND(bi0_on), \"turning on biphase transmitter\", GR_POWER},\n {COMMAND(vtx_on), \"turning on video transmitter\", GR_POWER},\n {COMMAND(if_relay_6_on), \"turning on IF relay 6\", GR_POWER},\n {COMMAND(if_eth_switch_on), \"turning on IF ethernet switch\", GR_POWER},\n {COMMAND(if_relay_8_on), \"turning on IF relay 8\", GR_POWER},\n {COMMAND(roach_on), \"turning on ROACH motel\", GR_POWER},\n {COMMAND(cryo_hk_on), \"turning on cryo housekeeping\", GR_POWER},\n {COMMAND(auto_pump_off), \"turning off auto pump\", GR_POWER | CONFIRM},\n {COMMAND(if_lj_off), \"turning off IF labjack\", GR_POWER},\n {COMMAND(timing_dist_off), \"turning off timing distribution box\", GR_POWER},\n {COMMAND(bi0_off), \"turning off biphase transmitter\", GR_POWER},\n {COMMAND(vtx_off), \"turning off video transmitter\", GR_POWER},\n {COMMAND(if_relay_6_off), \"turning off IF relay 6\", GR_POWER},\n {COMMAND(if_eth_switch_off), \"turning off IF ethernet switch\", GR_POWER},\n {COMMAND(if_relay_8_off), \"turning off IF relay 8\", GR_POWER},\n {COMMAND(roach_off), \"turning off ROACH motel\", GR_POWER},\n {COMMAND(cryo_hk_off), \"turning off cryo housekeeping\", GR_POWER},\n\n {COMMAND(actbus_off), \"turn off the Actuators, Lock, and HWPR\", GR_POWER | GR_LOCK | GR_ACT | GR_HWPR | CONFIRM},\n {COMMAND(actbus_on), \"turn on the Actuators, Lock, and HWPR\", GR_POWER | GR_LOCK | GR_ACT | GR_HWPR},\n {COMMAND(actbus_cycle), \"power cycle the Actuators, Lock, and HWPR\", GR_POWER | GR_LOCK | GR_ACT | GR_HWPR | CONFIRM},\n {COMMAND(charge_off), \"turn off the charge controller\", GR_POWER | CONFIRM},\n {COMMAND(charge_on), \"turn on the charge controller\", GR_POWER},\n {COMMAND(charge_cycle), \"power cycle the charge controller\", GR_POWER | CONFIRM},\n\n {COMMAND(mag_reset), \"command a reset of the magnetometer\", GR_VETO | GR_TRIM},\n {COMMAND(reset_rw), \"reset the serial connection to the RW controller\", GR_MOTOR},\n {COMMAND(reset_piv), \"reset the serial connection to the pivot controller\", GR_MOTOR},\n {COMMAND(reset_elev), \"reset the serial connection to the elev controller\", GR_MOTOR},\n {COMMAND(reset_ethercat), \"reset communications with all EtherCat devices\", GR_MOTOR},\n {COMMAND(restore_piv), \"restore the serial settings for the pivot controller\", GR_MOTOR},\n {COMMAND(az_off), \"disable az motors' gains\", GR_MOTOR},\n {COMMAND(az_on), \"enable az motors' gains\", GR_MOTOR},\n {COMMAND(el_off), \"disable el motor gains\", GR_MOTOR},\n {COMMAND(el_on), \"enable el motor gains\", GR_MOTOR},\n {COMMAND(force_el_on), \"force enable el motors despite the pin being in\", CONFIRM | GR_MOTOR},\n\n {COMMAND(elclin_veto), \"veto elevation clinometer\", GR_VETO},\n {COMMAND(elclin_allow), \"un-veto elevation clinometer\", GR_VETO},\n {COMMAND(elmotenc_veto), \"veto elevation motor encoder\", GR_VETO},\n {COMMAND(elmotenc_allow), \"un-veto elevation motor encoder\", GR_VETO},\n {COMMAND(xsc0_veto), \"veto star camera 0\", GR_VETO},\n {COMMAND(xsc0_allow), \"un-veto star camera 0\", GR_VETO},\n {COMMAND(xsc1_veto), \"veto star camera 1\", GR_VETO},\n {COMMAND(xsc1_allow), \"un-veto star camera 1\", GR_VETO},\n {COMMAND(mag_veto_fc1), \"veto magnotometer attached to fc1\", GR_VETO},\n {COMMAND(mag_allow_fc1), \"un-veto magnetometer attached to fc1\", GR_VETO},\n {COMMAND(mag_veto_fc2), \"veto magnotometer attached to fc2\", GR_VETO},\n {COMMAND(mag_allow_fc2), \"un-veto magnetometer attached to fc2\", GR_VETO},\n {COMMAND(pss_veto), \"veto pss sensor\", GR_VETO | GR_PSS},\n {COMMAND(pss_allow), \"un-veto pss sensor\", GR_VETO | GR_PSS},\n {COMMAND(dgps_veto), \"veto CSBF DGPS sensor\", GR_VETO},\n {COMMAND(dgps_allow), \"un-veto CSBF DGPS sensor\", GR_VETO},\n {COMMAND(ifroll_1_gy_allow), \"enable ifroll_1_gy\", GR_VETO},\n {COMMAND(ifroll_1_gy_veto), \"disable ifroll_1_gy\", GR_VETO},\n {COMMAND(ifroll_2_gy_allow), \"enable ifroll_2_gy\", GR_VETO},\n {COMMAND(ifroll_2_gy_veto), \"disable ifroll_2_gy\", GR_VETO},\n {COMMAND(ifyaw_1_gy_allow), \"enable ifyaw_1_gy\", GR_VETO},\n {COMMAND(ifyaw_1_gy_veto), \"disable ifyaw_1_gy\", GR_VETO},\n {COMMAND(ifyaw_2_gy_allow), \"enable ifyaw_2_gy\", GR_VETO},\n {COMMAND(ifyaw_2_gy_veto), \"disable ifyaw_2_gy\", GR_VETO},\n {COMMAND(ifel_1_gy_allow), \"enable ifel_1_gy\", GR_VETO},\n {COMMAND(ifel_1_gy_veto), \"disable ifel_1_gy\", GR_VETO},\n {COMMAND(ifel_2_gy_allow), \"enable ifel_2_gy\", GR_VETO},\n {COMMAND(ifel_2_gy_veto), \"disable ifel_2_gy\", GR_VETO},\n\n {COMMAND(az_auto_gyro), \"automatically calculate az gyro offsets\", GR_TRIM},\n {COMMAND(el_auto_gyro), \"automatically calculate el gyro offset\", GR_TRIM},\n {COMMAND(reset_trims), \"reset coarse pointing trims to zero\", GR_TRIM},\n {COMMAND(trim_to_xsc0), \"trim coarse sensors to XSC0 (disables autotrim)\", GR_TRIM},\n {COMMAND(trim_to_xsc1), \"trim coarse sensors to XSC1 (disables autotrim)\", GR_TRIM},\n {COMMAND(trim_xsc1_to_xsc0), \"trim XSC1 to XSC0\", GR_TRIM},\n {COMMAND(trim_xsc0_to_xsc1), \"trim XSC0 to XSC1\", GR_TRIM},\n {COMMAND(autotrim_off), \"disable auto-trim to XSC0/XSC1\", GR_TRIM},\n {COMMAND(fixed), \"fixed level bias\", GR_BIAS},\n {COMMAND(ramp), \"ramp bias with triangular waveform\", GR_BIAS},\n\n // {COMMAND(bda_on), \"manually turn 300mK BDA heater on\", GR_CRYO},\n // {COMMAND(bda_off), \"manually turn 300mK BDA heater off\", GR_CRYO},\n // {COMMAND(hs_pot_on), \"pot heat switch on\", GR_CRYO},\n // {COMMAND(hs_pot_off), \"pot heat switch off\", GR_CRYO},\n\n // {COMMAND(cal_on), \"calibrator on\", GR_CRYO},\n // {COMMAND(cal_off), \"calibrator off\", GR_CRYO},\n {COMMAND(hwpr_enc_on), \"HWP rotation sensor on\", GR_CRYO | GR_HWPR},\n {COMMAND(hwpr_enc_off), \"HWP rotation sensor off\", GR_CRYO | GR_HWPR},\n {COMMAND(hwpr_enc_pulse), \"HWP rotation sensor pulse\", GR_CRYO | GR_HWPR},\n\n // Old commands, should we delete? PAW 2018/03/27\n // {COMMAND(ln_valve_on), \"ln tank valve on\", GR_CRYO},\n // {COMMAND(ln_valve_off), \"ln tank valve off\", GR_CRYO},\n // {COMMAND(he_valve_on), \"he4 tank valve on\", GR_CRYO},\n // {COMMAND(he_valve_off), \"he4 tank valve off\", GR_CRYO},\n // {COMMAND(l_valve_open), \"set he4 AND ln tank valve direction open\", GR_CRYO},\n // {COMMAND(l_valve_close), \"set he4 AND ln tank valve direction close\", GR_CRYO},\n\n {COMMAND(potvalve_on), \"Turn He4 pot valve on (will accept move commands)\", GR_CRYO | CONFIRM},\n {COMMAND(potvalve_off), \"Turn He4 pot valve off (stops the motor, will not accept move commands\", GR_CRYO},\n {COMMAND(potvalve_open), \"set He4 pot valve direction open\", GR_CRYO | CONFIRM},\n {COMMAND(potvalve_close), \"set He4 pot valve direction close\", GR_CRYO | CONFIRM},\n {COMMAND(vent_valve_A_open), \"open atmospheric vent valve A\", GR_CRYO | CONFIRM},\n {COMMAND(vent_valve_A_close), \"close vent valve A\", GR_CRYO | CONFIRM},\n {COMMAND(vent_valve_A_off), \"stop atmospheric vent valve A, reset goal to 0\", GR_CRYO},\n {COMMAND(vent_valve_A_on), \"re-enable atmospheric vent valve A\", GR_CRYO | CONFIRM},\n {COMMAND(vent_valve_B_open), \"open atmospheric vent valve B\", GR_CRYO | CONFIRM},\n {COMMAND(vent_valve_B_close), \"close vent valve B\", GR_CRYO | CONFIRM},\n {COMMAND(vent_valve_B_off), \"stop atmospheric vent valve B, reset goal to 0\", GR_CRYO},\n {COMMAND(vent_valve_B_on), \"re-enable atmospheric vent valve B\", GR_CRYO | CONFIRM},\n {COMMAND(aalborg_vent_valve_open), \"open aalborg vent valve (vent main He tank to atmosphere)\", GR_CRYO | CONFIRM},\n {COMMAND(aalborg_pump_A_valve_open), \"open aalborg pump A valve (connected to pump A)\", GR_CRYO | CONFIRM},\n {COMMAND(aalborg_pump_B_valve_open), \"open aalborg pump B valve (connected to pump B)\", GR_CRYO | CONFIRM},\n {COMMAND(aalborg_vent_valve_close),\n\t \"close aalborg vent valve (between main He tank and atmosphere)\", GR_CRYO | CONFIRM},\n {COMMAND(aalborg_pump_A_valve_close), \"close aalborg pump A valve (connected to pump A)\", GR_CRYO | CONFIRM},\n {COMMAND(aalborg_pump_B_valve_close), \"close aalborg valve 1 (connected to pump B)\", GR_CRYO | CONFIRM},\n\n {COMMAND(blast_rocks), \"the receiver rocks, use the happy schedule file\",\n GR_TELEM},\n {COMMAND(blast_sucks), \"the receiver sucks, use the sad schedule file\",\n GR_TELEM},\n {COMMAND(at_float),\n \"tell the scheduler that we're at float (don't run initial float controls)\",\n GR_TELEM},\n {COMMAND(not_at_float), \"tell the scheduler that we're not at float\",\n GR_TELEM},\n\n {COMMAND(halt_fc1), \"ask MCP to halt fc1\", GR_MISC | CONFIRM},\n {COMMAND(halt_fc2), \"ask MCP to halt fc2\", GR_MISC | CONFIRM},\n {COMMAND(reap_fc1), \"ask MCP to reap the fc1 watchdog tickle\", GR_MISC | CONFIRM},\n {COMMAND(reap_fc2), \"ask MCP to reap the fc2 watchdog tickle\", GR_MISC | CONFIRM},\n {COMMAND(xy_panic), \"stop XY stage motors immediately\", GR_MISC},\n\n {COMMAND(balance_auto), \"Put balance system into auto mode\", GR_BAL},\n {COMMAND(balance_off), \"Turn off the balance motor\", GR_BAL},\n {COMMAND(balance_terminate), \"Drive balance system to lower limit, after sending lock45,\"\n\t \"before termination\", GR_BAL},\n\n {COMMAND(pin_in), \"close lock pin without checking encoder (dangerous)\",\n GR_LOCK | CONFIRM},\n {COMMAND(unlock), \"unlock the inner frame\", GR_LOCK},\n {COMMAND(lock_off), \"turn off the lock motor\", GR_LOCK},\n {COMMAND(lock45), \"Lock the inner frame at 45 degrees\", GR_LOCK},\n {COMMAND(repoll), \"force repoll of the stepper busses (act, lock, HWPR, XY)\",\n GR_LOCK | GR_ACT | GR_HWPR},\n {COMMAND(autofocus_veto), \"veto the secondary actuator system temperature\"\n \" correction mode\", GR_FOCUS},\n {COMMAND(autofocus_allow), \"allow the secondary actuator system temperature\"\n \" correction mode\", GR_FOCUS},\n {COMMAND(actuator_stop), \"stop all secondary actuators immediately\", GR_ACT},\n {COMMAND(hwpr_panic), \"stop the HWPR rotator immediately\", GR_HWPR},\n {COMMAND(hwpr_step), \"step the hwpr\", GR_HWPR},\n {COMMAND(hwpr_step_off), \"Disable half wave plate stepping\", GR_HWPR},\n {COMMAND(hwpr_step_on), \"Enable half wave plate stepping\", GR_HWPR},\n {COMMAND(hwpr_pot_is_dead), \"don't use the potentiometer when stepping the hwpr\", GR_HWPR},\n {COMMAND(hwpr_pot_is_alive), \"use the potentiometer when stepping the hwpr\", GR_HWPR},\n\n // Shutter commands\n {COMMAND(shutter_init), \"Initialize shutter move parameters\", GR_MISC},\n {COMMAND(shutter_close), \"Close shutter (will NOT keep it closed)\", GR_MISC},\n {COMMAND(shutter_reset), \"Reset shutter; shutter will open\", GR_MISC},\n {COMMAND(shutter_open), \"Open shutter\", GR_MISC},\n {COMMAND(shutter_open_close), \"DEPRECATED: If shutter is open, then open completely and then close\", GR_MISC},\n {COMMAND(shutter_off), \"Turn off shutter; shutter will fall open\", GR_MISC},\n {COMMAND(shutter_close_slow), \"DEPRECATED, use shutter_keepclosed instead: Close shutter using opto feedback\",\n\t GR_MISC},\n {COMMAND(shutter_keepopen), \"Open shutter and keep open with limit switch\", GR_MISC},\n {COMMAND(shutter_keepclosed), \"Close shutter and keep closed with limit switch\", GR_MISC},\n\n {COMMAND(vna_sweep_all), \"(All Roaches) Do VNA sweeps\", GR_ROACH},\n {COMMAND(targ_sweep_all), \"(All Roaches) Do TARG sweeps\", GR_ROACH},\n {COMMAND(find_kids_default_all), \"(All Roaches) Find frequencies using VNA sweeps\", GR_ROACH},\n {COMMAND(center_lo_all), \"(All Roaches) recenter LOs\", GR_ROACH},\n {COMMAND(calc_dfs), \"(All Roaches) Calculate df for all channels\", GR_ROACH},\n {COMMAND(change_amps), \"Writes the tone amplitudes contained in roach->last_amps\", GR_ROACH},\n {COMMAND(load_freqs_all), \"(All Roaches) Write all saved targ freqs\", GR_ROACH},\n {COMMAND(reload_vna_all), \"(All Roaches) Reload VNA freqs and VNA trf\", GR_ROACH},\n {COMMAND(end_sweeps_all), \"(All Roaches) End all sweeps\", GR_ROACH},\n {COMMAND(new_ref_params_all), \"(All Roaches) Calculates and saves ref params from last target sweep\", GR_ROACH},\n {COMMAND(set_attens_default_all), \"(All Roaches) Set all attens to default values\", GR_ROACH},\n {COMMAND(set_attens_min_output), \"(All Roaches) Set all output attens to 30 dB\", GR_ROACH},\n {COMMAND(auto_find_kids_all), \"(All Roaches) on startup, do VNA sweep, find kids and write tones\", GR_ROACH},\n {COMMAND(zero_df_all), \"(All Roaches) zero the delta fs\", GR_ROACH},\n {COMMAND(roach_reset_all), \"(All Roaches) reinitialize all Roaches from BOOT state\", GR_ROACH},\n {COMMAND(change_freqs_all), \"(All Roaches) Apply delta f to targ tones, rewrite comb\", GR_ROACH},\n {COMMAND(set_attens_last_all),\n \"(All Roaches) Set all attens to previous settings (e.g., after hard reset)\", GR_ROACH},\n {COMMAND(df_targ_all), \"(All Roaches) Calculate delta f from reference and new targ sweeps\", GR_ROACH},\n {COMMAND(check_df_retune_all), \"(All Roaches) Checks df and makes retune recommendation\", GR_ROACH},\n {COMMAND(median_sweep_df_all), \"(All Roaches) Performs a sweep and reports the median df difference\", GR_ROACH},\n {COMMAND(check_dfsweep_retune_all),\n \"(All Roaches) Checks df with sweep method and makes retune recommendation\", GR_ROACH},\n {COMMAND(chop_lo_all), \"Do a 3 point LO step for all Roaches\", GR_ROACH},\n {COMMAND(full_loop_default_all), \"(All Roaches) Performs full loop, default params\", GR_ROACH},\n {COMMAND(read_attens_all), \"(All Roaches) Reads current attenuator values\", GR_ROACH},\n {COMMAND(read_lo_all), \"(All Roaches) Reads current LO frequencies\", GR_ROACH},\n {COMMAND(read_pi_temp_all), \"(All Roaches) Reads current Pi temp\", GR_ROACH},\n {COMMAND(reset_log), \"Read the most recent log (clear cache)\", GR_MISC},\n {COMMAND(rw_wake_and_wiggle), \"Trigger a wake-and wiggle re-commutation of the reaction wheel motor.\", GR_MOTOR},\n {COMMAND(xyzzy), \"nothing happens here\", GR_MISC}\n};\n\n/* parameter type:\n * i : parameter is 16 bit unnormalised integer. Max is CMD_I_MAX\n * l : parameter is 32 bit unnormalised integer. Max is CMD_L_MAX\n * f : parameter is 16 bit renormalised floating point\n * d : parameter is 32 bit renormalised floating point\n * s : parameter is 7-bit character string JOY: actually 32 char long\n */\nstruct mcom mcommands[plugh + 2] = {\n {COMMAND(slot_sched), \"set uplinked slot to use for schedule file\",\n GR_TELEM, 1,\n {\n {\"Slot #\", 0, 250, 'i', \"SLOT_SCHED\"}\n }\n },\n\n /* pointing modes */\n {COMMAND(az_el_goto), \"goto point in azimuth and elevation\", GR_POINT, 2,\n {\n {\"Azimuth (deg)\", -360, 360, 'f', \"AZ\"},\n {\"Elevation (deg)\", 4.95, 65, 'f', \"EL\"}\n }\n },\n {COMMAND(az_el_trim), \"trim sensors to azimuth and elevation\", GR_TRIM, 2,\n {\n {\"Azimuth (deg)\", 0, 360, 'f', \"AZ\"},\n {\"Elevation (deg)\", 0, 90, 'f', \"EL\"}\n }\n },\n {COMMAND(mag_cal_fc1), \"set fc1 magnetometer calibration\", GR_TRIM, 5,\n {\n {\"Max X\", -20, 20, 'd', \"CAL_XMAX_MAG1\"},\n {\"Min X\", -20, 20, 'd', \"CAL_XMIN_MAG1\"},\n {\"Max Y\", -20, 20, 'd', \"CAL_YMAX_MAG1\"},\n {\"Min Y\", -20, 20, 'd', \"CAL_YMIN_MAG1\"},\n {\"Mag Angle Offset\", -180.0, 180.0, 'f', \"CAL_ALIGNMENT_MAG1\"}\n }\n }, // 10 10 10.5 10.34\n {COMMAND(mag_cal_fc2), \"set fc2 magnetometer calibration\", GR_TRIM, 5,\n {\n {\"Max X\", -20, 20, 'd', \"CAL_XMAX_MAG2\"},\n {\"Min X\", -20, 20, 'd', \"CAL_XMIN_MAG2\"},\n {\"Max Y\", -20, 20, 'd', \"CAL_YMAX_MAG2\"},\n {\"Min Y\", -20, 20, 'd', \"CAL_YMIN_MAG2\"},\n {\"Mag Angle Offset\", -180.0, 180.0, 'f', \"CAL_ALIGNMENT_MAG2\"}\n }\n }, // 10 10 10.5 10.34\n\n {COMMAND(pss_set_imin), \"set pss minimum current\", GR_TRIM | GR_PSS, 1,\n {\n {\"I Min\", 0.0, 20.0, 'f', \"CAL_IMIN_PSS\"}\n }\n },\n\n{COMMAND(pss_cal_n), \"set calibration for PSS N\", GR_TRIM | GR_PSS, 5,\n {\n {\"PSS number (1-6)\", 1, 6, 'i', \"NONE\"},\n {\"Distance offset\", -10.0, 10.0, 'f', \"NONE\"},\n {\"Azimuth offset\", -10.0, 10.0, 'f', \"NONE\"},\n {\"Elevation offset\", -10.0, 10.0, 'f', \"NONE\"},\n {\"Roll offset\", -180.0, 180.0, 'f', \"NONE\"},\n }\n },\n\n {COMMAND(pss_cal_d), \"set pss distance calibration (mm)\", GR_TRIM | GR_PSS, 6,\n {\n {\"Distance offset 1\", -10.0, 10.0, 'f', \"CAL_D_PSS1\"},\n {\"Distance offset 2\", -10.0, 10.0, 'f', \"CAL_D_PSS2\"},\n {\"Distance offset 3\", -10.0, 10.0, 'f', \"CAL_D_PSS3\"},\n {\"Distance offset 4\", -10.0, 10.0, 'f', \"CAL_D_PSS4\"},\n {\"Distance offset 5\", -10.0, 10.0, 'f', \"CAL_D_PSS5\"},\n {\"Distance offset 6\", -10.0, 10.0, 'f', \"CAL_D_PSS6\"},\n }\n },\n\n {COMMAND(pss_cal_az), \"set pss azimuth calibration (deg)\", GR_TRIM | GR_PSS, 6,\n {\n {\"Azimuth offset 1\", -10.0, 10.0, 'f', \"CAL_AZ_PSS1\"},\n {\"Azimuth offset 2\", -10.0, 10.0, 'f', \"CAL_AZ_PSS2\"},\n {\"Azimuth offset 3\", -10.0, 10.0, 'f', \"CAL_AZ_PSS3\"},\n {\"Azimuth offset 4\", -10.0, 10.0, 'f', \"CAL_AZ_PSS4\"},\n {\"Azimuth offset 5\", -10.0, 10.0, 'f', \"CAL_AZ_PSS5\"},\n {\"Azimuth offset 6\", -10.0, 10.0, 'f', \"CAL_AZ_PSS6\"},\n }\n },\n\n {COMMAND(pss_cal_array_az), \"set pss azimuth calibration for entire array(deg)\", GR_TRIM | GR_PSS, 1,\n {\n {\"Azimuth offset of array\", -20.0, 20.0, 'f', \"CAL_AZ_PSS_ARRAY\"},\n }\n },\n\n {COMMAND(pss_cal_el), \"set pss elevation calibration (deg)\", GR_TRIM | GR_PSS, 6,\n {\n {\"Elevation offset 1\", -10.0, 10.0, 'f', \"CAL_EL_PSS1\"},\n {\"Elevation offset 2\", -10.0, 10.0, 'f', \"CAL_EL_PSS2\"},\n {\"Elevation offset 3\", -10.0, 10.0, 'f', \"CAL_EL_PSS3\"},\n {\"Elevation offset 4\", -10.0, 10.0, 'f', \"CAL_EL_PSS4\"},\n {\"Elevation offset 5\", -10.0, 10.0, 'f', \"CAL_EL_PSS5\"},\n {\"Elevation offset 6\", -10.0, 10.0, 'f', \"CAL_EL_PSS6\"},\n }\n },\n {COMMAND(pss_set_noise), \"set pss noise level\", GR_TRIM | GR_PSS, 1,\n {\n {\"RMS deviation of summed voltages (volts)\", 0.0, 10.0, 'f', \"NOISE_PSS\"},\n }\n },\n {COMMAND(pss_cal_roll), \"set pss roll calibration (deg)\", GR_TRIM | GR_PSS, 6,\n {\n {\"Roll offset 1\", -180.0, 180.0, 'f', \"CAL_ROLL_PSS1\"},\n {\"Roll offset 2\", -180.0, 180.0, 'f', \"CAL_ROLL_PSS2\"},\n {\"Roll offset 3\", -180.0, 180.0, 'f', \"CAL_ROLL_PSS3\"},\n {\"Roll offset 4\", -180.0, 180.0, 'f', \"CAL_ROLL_PSS4\"},\n {\"Roll offset 5\", -180.0, 180.0, 'f', \"CAL_ROLL_PSS5\"},\n {\"Roll offset 6\", -180.0, 180.0, 'f', \"CAL_ROLL_PSS6\"},\n }\n },\n {COMMAND(autotrim_to_sc), \"enable auto-trim to ISC/OSC\", GR_TRIM, 3,\n {\n {\"Threshold (sigma)\", 0, 10, 'f', \"THRESH_ATRIM\"},\n {\"Good time (s)\", 0, CMD_I_MAX, 'i', \"TIME_ATRIM\"},\n {\"Set rate (deg/s)\", 0, 30, 'f', \"RATE_ATRIM\"}\n }\n },\n {COMMAND(az_gain), \"az reaction wheel gains\", GR_MOTOR, 4,\n {\n {\"Proportional Gain\", 0, CMD_I_MAX, 'd', \"g_p_az\"},\n {\"Integral Time\", 0, 200, 'd', \"g_i_az\"},\n {\"Derivative Time\", 0, 200, 'f', \"g_d_az\"},\n {\"Pointing Gain\", 0, CMD_I_MAX, 'd', \"g_pt_az\"},\n }\n },\n {COMMAND(az_scan_accel), \"set azimuth scan turnaround acceleration\", GR_MOTOR, 1,\n {\n {\"Az Acceleration\", 0.1, 2.0, 'f', \"accel_az\"}\n }\n },\n {COMMAND(set_scan_params), \"set dither index for next scan\", GR_POINT, 1,\n {\n {\"Next dither index \", 0, 200, 'i', \"next_i_dith\"}\n }\n },\n {COMMAND(az_scan), \"scan in azimuth\", GR_POINT, 4,\n {\n {\"Az centre (deg)\", -180, 360, 'f', \"AZ\"},\n {\"El centre (deg)\", 15, 65, 'f', \"EL\"},\n {\"Width (deg on sky)\", 0, 360, 'f', \"NONE\"},\n {\"Az Scan Speed (deg az/s)\", 0, 2, 'f', \"NONE\"}\n }\n },\n {COMMAND(el_scan), \"scan in azimuth\", GR_POINT, 4,\n {\n {\"Az centre (deg)\", -180, 360, 'f', \"AZ\"},\n {\"El centre (deg)\", 15, 65, 'f', \"EL\"},\n {\"Height (deg on sky)\", 0, 360, 'f', \"NONE\"},\n {\"El Scan Speed (deg az/s)\", 0, 2, 'f', \"NONE\"}\n }\n },\n {COMMAND(balance_manual), \"Manually set balance on\", GR_BAL, 1,\n {\n {\"dir (pos=1, neg=-1, off=0)\", -1, 1, 'i', \"NONE\"},\n }\n },\n {COMMAND(balance_vel), \"set the balance system velocity and acceleration\",\n GR_BAL, 2,\n {\n {\"Velocity\", 5, 500000, 'l', \"VEL_BAL\"},\n {\"Acceleration\", 1, 1000, 'i', \"ACC_BAL\"},\n }\n },\n {COMMAND(balance_i), \"set the balance system currents\", GR_BAL, 2,\n {\n {\"Move current (%)\", 0, 100, 'i', \"I_MOVE_BAL\"},\n {\"Hold current (%)\", 0, 50, 'i', \"I_HOLD_BAL\"},\n }\n },\n {COMMAND(balance_gain), \"Set balance system setpoints\", GR_BAL, 2,\n {\n {\"I_El Balance On (A)\", 0, 5, 'f', \"I_LEVEL_ON_BAL\"},\n {\"I_El Balance Off (A)\", 0, 5, 'f', \"I_LEVEL_OFF_BAL\"},\n }\n },\n {COMMAND(box), \"scan an az/el box centred on RA/Dec with el steps\", GR_POINT, 7,\n {\n {\"RA of Centre (h)\", 0, 24, 'd', \"RA\"},\n {\"Dec of Centre (deg)\", -90, 90, 'd', \"DEC\"},\n {\"Az Width (deg on sky)\", 0, 90, 'f', \"NONE\"},\n {\"El Height (deg on sky)\", 0, 45, 'f', \"NONE\"},\n {\"Az Scan Speed (deg az/s)\", 0, 2, 'f', \"NONE\"},\n {\"El Step Size (deg on sky)\", 0, 1, 'f', \"NONE\"},\n {\"No. of dither steps\", 0, 200, 'i', \"n_dith\"}\n }\n },\n {COMMAND(el_box), \"scan an az/el box centred on RA/Dec with az steps\", GR_POINT, 7,\n {\n {\"RA of Centre (h)\", 0, 24, 'd', \"RA\"},\n {\"Dec of Centre (deg)\", -90, 90, 'd', \"DEC\"},\n {\"Az Width (deg on sky)\", 0, 90, 'f', \"NONE\"},\n {\"El Height (deg on sky)\", 0, 45, 'f', \"NONE\"},\n {\"El Scan Speed (deg az/s)\", 0, 2, 'f', \"NONE\"},\n {\"Az Step Size (deg on sky)\", 0, 1, 'f', \"NONE\"},\n {\"No. of dither steps\", 0, 200, 'i', \"n_dith\"}\n }\n },\n {COMMAND(cap), \"scan a circle centred on RA/Dec with el steps\", GR_POINT, 6,\n {\n {\"RA of Centre (h)\", 0, 24, 'd', \"RA\"},\n {\"Dec of Centre (deg)\", -90, 90, 'd', \"DEC\"},\n {\"Radius (deg on sky)\", 0, 90, 'f', \"NONE\"},\n {\"Az Scan Speed (deg az/s)\", 0, 2, 'f', \"NONE\"},\n {\"El Step Size (deg on sky)\", 0, 1, 'f', \"NONE\"},\n {\"No. of dither steps\", 0, 200, 'i', \"n_dith\"}\n }\n },\n {COMMAND(drift), \"move at constant speed in az and el\", GR_POINT, 2,\n {\n {\"Az Speed (deg/s on sky)\", -2.0, 2.0, 'f', \"0.0\"},\n {\"El Speed (deg/s on sky)\", -2.0, 2.0, 'f', \"0.0\"}\n }\n },\n {COMMAND(cur_mode), \"drive motors at constant current\", GR_POINT, 3,\n {\n {\"Pivot Current (Amps)\", -20.0, 20.0, 'f', \"0.0\"},\n {\"RW Current (Amps)\", -20.0, 20.0, 'f', \"0.0\"},\n {\"Elevation Current (Amps)\", -20.0, 20.0, 'f', \"0.0\"}\n }\n },\n {COMMAND(quad), \"scan a quadrilateral region in RA/Dec (corners must be ordered)\", GR_POINT, 11,\n {\n {\"RA of Corner 1 (h)\", 0, 24, 'f', \"NONE\"},\n {\"Dec of Corner 1 (deg)\", -90, 90, 'f', \"NONE\"},\n {\"RA of Corner 2 (h)\", 0, 24, 'f', \"NONE\"},\n {\"Dec of Corner 2 (deg)\", -90, 90, 'f', \"NONE\"},\n {\"RA of Corner 3 (h)\", 0, 24, 'f', \"NONE\"},\n {\"Dec of Corner 3 (deg)\", -90, 90, 'f', \"NONE\"},\n {\"RA of Corner 4 (h)\", 0, 24, 'f', \"NONE\"},\n {\"Dec of Corner 4 (deg)\", -90, 90, 'f', \"NONE\"},\n {\"Az Scan Speed (deg az/s)\", 0, 2, 'f', \"NONE\"},\n {\"El Step Size (deg on sky)\", 0, 1, 'f', \"NONE\"},\n {\"No. of dither steps\", 0, 200, 'i', \"n_dith\"}\n }\n },\n {COMMAND(vbox), \"DEPRECATED - scan an az/el box centred on RA/Dec with el drift\", GR_POINT, 6,\n {\n {\"RA of Centre (h)\", 0, 24, 'f', \"NONE\"},\n {\"Dec of Centre (deg)\", -90, 90, 'f', \"NONE\"},\n {\"Az Width (deg on sky)\", 0, 90, 'f', \"NONE\"},\n {\"El Height (deg on sky)\", 0, 45, 'f', \"NONE\"},\n {\"Az Scan Speed (deg az/s)\", 0, 2, 'f', \"NONE\"},\n {\"El Drift Speed (deg el/s)\", 0, 2, 'f', \"NONE\"}\n }\n },\n {COMMAND(vcap), \"DEPRECATED - scan a circle centred on RA/Dec with el drift\", GR_POINT, 5,\n {\n {\"RA of Centre (h)\", 0, 24, 'f', \"NONE\"},\n {\"Dec of Centre (deg)\", -90, 90, 'f', \"NONE\"},\n {\"Radius (deg on sky)\", 0, 90, 'f', \"NONE\"},\n {\"Az Scan Speed (deg az/s)\", 0, 2, 'f', \"NONE\"},\n {\"El Drift Speed (deg el/s)\", 0, 2, 'f', \"NONE\"}\n }\n },\n {COMMAND(ra_dec_goto), \"track a location RA/Dec\", GR_POINT, 2,\n {\n {\"RA of Centre (h)\", 0, 24, 'f', \"RA\"},\n {\"Dec of Centre (deg)\", -90, 90, 'f', \"DEC\"}\n }\n },\n {COMMAND(ra_dec_set), \"define RA/Dec of current position\", GR_TRIM, 2,\n {\n {\"Current RA (h)\", 0, 24, 'f', \"RA\"},\n {\"Current Dec (deg)\", -90, 90, 'f', \"DEC\"}\n }\n },\n {COMMAND(pos_set), \"define Latitude/Longitude of current position\", GR_TRIM, 2,\n {\n {\"Current Latitude (deg)\", -90, 90, 'f', \"LAT\"},\n {\"Current Longitude (deg)\", -360, 360, 'f', \"LON\"}\n }\n },\n {COMMAND(pivot_gain), \"pivot gains\", GR_MOTOR, 6,\n {\n {\"Set Point (dps)\", -200, 200, 'f', \"SET_RW\"},\n {\"V_err Gain (prop)\", 0, CMD_L_MAX, 'd', \"G_PE_PIV\"},\n {\"V_err Integral time\", 0, CMD_L_MAX, 'd', \"G_IE_PIV\"},\n {\"V_RW Gain (prop)\", 0, CMD_L_MAX, 'd', \"G_PV_PIV\"},\n {\"V_RW Integral time\", 0, 200, 'd', \"G_IV_PIV\"},\n {\"Static Friction offset\", 0, 100, 'f', \"FRICT_OFF_PIV\"},\n }\n },\n {COMMAND(el_gain), \"elevation motor gains\", GR_MOTOR, 6,\n {\n {\"Proportional Gain\", 0, CMD_L_MAX, 'd', \"G_P_EL\"},\n {\"Integral Time\", 0, 200, 'd', \"G_I_EL\"},\n {\"Derivative Time\", 0, 200, 'd', \"G_D_EL\"},\n {\"Pointing Gain\", 0, CMD_L_MAX, 'd', \"G_PT_EL\"},\n {\"Integral Term Deadband (mA)\", 0, 500, 'f', \"G_DB_EL\"},\n {\"Static Friction offset\", 0, 100, 'f', \"FRICT_OFF_EL\"},\n }\n },\n {COMMAND(az_gyro_offset), \"manually set az gyro offsets\", GR_TRIM, 2,\n {\n {\"IF Roll Gyro offset (deg/s)\", -0.5, 0.5, 'd', \"OFFSET_IFROLL_GY\"},\n {\"IF Yaw Gyro offset (deg/s)\", -0.5, 0.5, 'd', \"OFFSET_IFYAW_GY\"}\n }\n },\n {COMMAND(el_gyro_offset), \"manually set el gyro offset\", GR_TRIM, 1,\n {\n {\"IF Elev Gyro offset (deg/s)\", -0.5, 0.5, 'd', \"OFFSET_IFEL_GY\"},\n }\n },\n{COMMAND(fix_ethercat), \"Attempt to fix EC device? (1=yes, 0=no)\", GR_MOTOR, 4,\n {\n {\"RW\", 0, 1, 'i', \"NONE\"},\n {\"El\", 0, 1, 'i', \"NONE\"},\n {\"Pivot\", 0, 1, 'i', \"NONE\"},\n {\"HWP\", 0, 1, 'i', \"NONE\"},\n }\n},\n\n {COMMAND(slew_veto), \"set the length of the gyro offset slew veto (s)\", GR_TRIM,\n 1,\n {\n {\"Slew Veto (s)\", 0., 1200., 'f', \"SVETO_LEN\"},\n }\n },\n\n /* actuator bus commands */\n {COMMAND(lock), \"lock inner frame\", GR_LOCK | GR_POINT, 1,\n {\n {\"Lock Elevation (deg)\", 5, 90, 'f', \"EL_ENC\"}\n }\n },\n {COMMAND(general), \"send a general command string to the lock or actuators\",\n GR_ACT | GR_LOCK | GR_HWPR | GR_BAL, 2,\n {\n {\"Address (1-10)\", 1, 0x2F, 'i', \"1.0\"},\n {\"Command\", 0, 32, 's', \"NONE\"},\n }\n },\n {COMMAND(lock_vel), \"set the lock motor velocity and acceleration\", GR_LOCK,\n 2,\n {\n {\"Velocity\", 5, 500000, 'l', \"VEL_LOCK\"},\n {\"Acceleration\", 1, 1000, 'i', \"ACC_LOCK\"},\n }\n },\n {COMMAND(lock_i), \"set the lock motor currents\", GR_LOCK, 2,\n {\n {\"Move current (%)\", 0, 100, 'i', \"I_MOVE_LOCK\"},\n {\"Hold current (%)\", 0, 50, 'i', \"I_HOLD_LOCK\"},\n }\n },\n {COMMAND(set_secondary), \"servo the secondary mirror to absolute position\",\n GR_FOCUS, 1,\n {\n {\"Position (per FOCUS_SF counts)\", -15000, 15000, 'i', \"FOCUS_SF\"},\n }\n },\n {COMMAND(delta_secondary), \"servo the secondary mirror by a relative amount\",\n GR_FOCUS, 1,\n {\n {\"Position (counts)\", -1000, 1000, 'i', \"0\"},\n }\n },\n {COMMAND(thermo_gain), \"set the secondary actuator system gains\", GR_FOCUS, 4,\n {\n {\"T. Primary Gain\", 1, 1000, 'f', \"G_PRIME_SF\"},\n {\"T. Secondary Gain\", 1, 1000, 'f', \"G_SECOND_SF\"},\n {\"Step Size (um)\", 10, 1000, 'i', \"STEP_SF\"},\n {\"Step Wait (min)\" , 0, 1500, 'i', \"WAIT_SF\"},\n }\n },\n {COMMAND(actuator_servo), \"servo the actuators to absolute positions\",\n GR_ACT, 3,\n {\n {\"Actuator Alpha (ENC units)\", -15000, 15000, 'i', \"ENC_0_ACT\"},\n {\"Actuator Beta (ENC units)\", -15000, 15000, 'i', \"ENC_1_ACT\"},\n {\"Actuator Gamma (ENC units)\", -15000, 15000, 'i', \"ENC_2_ACT\"}\n }\n },\n {COMMAND(focus_offset), \"set the in focus position offset relative the \"\n \"nominal focus\", GR_FOCUS, 1,\n {\n {\"Offset\", -5000, 25000, 'i', \"OFFSET_SF\"}\n }\n },\n {COMMAND(actuator_delta), \"offset the actuators to from current position\",\n GR_ACT, 3,\n {\n {\"Actuator Alpha\", -5000, 5000, 'i', \"0\"},\n {\"Actuator Beta\", -5000, 5000, 'i', \"0\"},\n {\"Actuator Gamma\", -5000, 5000, 'i', \"0\"}\n }\n },\n {COMMAND(act_offset), \"set the actuator encoder/lvdt offsets\", GR_ACT, 3,\n {\n {\"Actuator Alpha (Enc units)\", 0, 65536, 'f', \"ENC_0_ACT\"},\n {\"Actuator Beta (Enc units)\", 0, 65536, 'f', \"ENC_1_ACT\"},\n {\"Actuator Gamma (Enc units)\", 0, 65536, 'f', \"ENC_2_ACT\"}\n }\n },\n {COMMAND(act_enc_trim), \"manually set encoder and dead reckoning\", GR_ACT, 3,\n {\n {\"Actuator Alpha (Enc units)\", 0, 65536, 'f', \"DR_0_ACT\"},\n {\"Actuator Beta (Enc units)\", 0, 65536, 'f', \"DR_1_ACT\"},\n {\"Actuator Gamma (Enc units)\", 0, 65536, 'f', \"DR_2_ACT\"}\n }\n },\n {COMMAND(actuator_vel), \"set the actuator velocity and acceleration\", GR_ACT,\n 2,\n {\n {\"Velocity\", 5, 20000, 'i', \"VEL_ACT\"},\n {\"Acceleration\", 1, 20, 'i', \"ACC_ACT\"}\n }\n },\n {COMMAND(actuator_i), \"set the actuator motor currents\", GR_ACT, 2,\n {\n {\"Move current (%)\", 0, 100, 'i', \"I_MOVE_ACT\"},\n {\"Hold current (%)\", 0, 50, 'i', \"I_HOLD_ACT\"}\n }\n },\n {COMMAND(actuator_tol), \"set the tolerance for servo moves\", GR_ACT, 1,\n {\n {\"Move tolerance (~um)\", 0, 1000, 'i', \"TOL_ACT\"}\n }\n },\n {COMMAND(lvdt_limit), \"set the hard LVDT limits on actuator moves\", GR_ACT, 3,\n {\n {\"Spread limit\", 0, 5000, 'f', \"LVDT_SPREAD_ACT\"},\n {\"Lower limit\", -5000, 60000, 'f', \"LVDT_LOW_ACT\"},\n {\"Upper limit\", -5000, 60000, 'f', \"LVDT_HIGH_ACT\"}\n }\n },\n {COMMAND(thermo_param), \"set the thermal compensation parameters\", GR_FOCUS,\n 3,\n {\n {\"Temp. Spread\", 0, 100, 'f', \"SPREAD_SF\"},\n {\"Preferred T Prime\", 0, 2, 'i', \"PREF_TP_SF\"},\n {\"Preferred T Second\", 0, 2, 'i', \"PREF_TS_SF\"}\n }\n },\n {COMMAND(hwpr_vel), \"set the waveplate rotator velocity and acceleration\",\n GR_HWPR, 2,\n {\n {\"Velocity (usteps/sec)\", 5, 500000, 'l', \"VEL_HWPR\"},\n {\"Acceleration (usteps/sec^2\", 1, 1000, 'i', \"ACC_HWPR\"},\n }\n },\n {COMMAND(hwpr_i), \"set the waveplate rotator currents\", GR_HWPR, 2,\n {\n {\"Move current (%)\", 0, 100, 'i', \"I_MOVE_HWPR\"},\n {\"Hold current (%)\", 0, 50, 'i', \"I_HOLD_HWPR\"},\n }\n },\n {COMMAND(hwpr_goto), \"move the waveplate rotator to absolute position\",\n GR_HWPR, 1,\n {\n {\"destination (deg on the hwp, limits: 14547-14592)\", 14547.0, 14592.0, 'f', \"ENC_HWPR\"}\n }\n },\n {COMMAND(hwpr_goto_rel), \"move the waveplate rotator to relative position (slightly dangerous)\",\n GR_HWPR | CONFIRM, 1,\n {\n {\"delta (deg on the hwp, limits: -45 to 45)\", -45.0, 45.0, 'f', \"0\"}\n }\n },\n {COMMAND(hwpr_repeat),\n \"DEPRECATED - repeatedly cycle the hwpr through a number of positions\",\n GR_HWPR, 4,\n {\n {\"Number of step positions\", 0, MAX_15BIT, 'i', \"NONE\"},\n {\"Number of times to step\", 0, MAX_15BIT, 'i', \"NONE\"},\n {\"Time between steps (s)\", 0, MAX_15BIT, 'i', \"NONE\"},\n {\"Step size (encoder ticks)\", -MAX_15BIT/2, MAX_15BIT/2, 'i', \"NONE\"},\n }\n },\n {COMMAND(hwpr_define_pos),\n \"define the two hwpr potentiometer positions to be used for scans\",\n GR_HWPR, 2,\n {\n {\"Position 1 (deg)\", 0.0, 360.0, 'd', \"POS0_HWPR\"},\n {\"Position 2 (deg)\", 0.0, 360.0, 'd', \"POS1_HWPR\"},\n }\n },\n {COMMAND(hwpr_goto_pot),\n \"DEPRECATED - Move wave plate rotator to commanded encoder value\",\n GR_HWPR, 1,\n {\n {\"Encoder Value \", 0.0, 360.0, 'f', \"POT_HWPR\"},\n }\n },\n {COMMAND(hwpr_set_overshoot),\n \"set the overshoot in degrees on the hwp for backwards hwpr moves\",\n GR_HWPR, 1,\n {\n {\"overshoot (-7 to 7 deg)\", -7.0, 7.0, 'd', \"OVERSHOOT_HWPR\"},\n }\n },\n {COMMAND(hwpr_set_backoff),\n \"set the backoff in degrees on the input shaft for backwards hwpr moves\",\n GR_HWPR, 1,\n {\n {\"backoff (deg input shaft)\", 0.0, 120.0, 'd', \"BACKOFF_HWPR\"},\n }\n },\n {COMMAND(hwpr_goto_i),\n \"goto hwpr position (0-1)\",\n GR_HWPR, 1,\n {\n {\"hwpr position\", 0, 1, 'i', \"I_POS_RQ_HWPR\"},\n }\n },\n {COMMAND(hwpr_set_margin),\n \"Set HWPR margin for determinting which indexed position we are at\",\n GR_HWPR, 1,\n {\n {\"hwpr margin (deg)\", 0.0, 5.0, 'f', \"NONE\"},\n }\n },\n /* XY Stage */\n {COMMAND(xy_goto), \"move the X-Y translation stage to absolute position\",\n GR_MISC, 4,\n {\n {\"X destination\", 0, 8000000, 'l', \"X_STAGE\"},\n {\"Y destination\", 0, 8000000, 'l', \"Y_STAGE\"},\n {\"X speed\", 0, 100000, 'l', \"X_VEL_STAGE\"},\n {\"Y speed\", 0, 100000, 'l', \"Y_VEL_STAGE\"}\n }\n },\n {COMMAND(xy_jump), \"move the X-Y translation stage to relative position\",\n GR_MISC, 4,\n {\n {\"X delta\", -1000000, 1000000, 'l', \"0\"},\n {\"Y delta\", -1000000, 1000000, 'l', \"0\"},\n {\"X speed\", 0, 100000, 'l', \"X_VEL_STAGE\"},\n {\"Y speed\", 0, 100000, 'l', \"Y_VEL_STAGE\"}\n }\n },\n {COMMAND(xy_xscan), \"scan the X-Y translation stage in X\", GR_MISC, 3,\n {\n {\"X center\", 0, 8000000, 'l', \"X_STAGE\"},\n {\"delta X\", 0, 4000000, 'l', \"NONE\"},\n {\"X speed\", 0, 1000000, 'l', \"X_VEL_STAGE\"},\n }\n },\n {COMMAND(xy_yscan), \"scan the X-Y translation stage in Y\", GR_MISC, 3,\n {\n {\"Y center\", 0, 8000000, 'l', \"Y_STAGE\"},\n {\"delta Y\", 0, 4000000, 'l', \"NONE\"},\n {\"Y speed\", 0, 1000000, 'l', \"Y_VEL_STAGE\"},\n }\n },\n {COMMAND(xy_raster), \"raster the X-Y translation stage\", GR_MISC, 7,\n {\n {\"X center\", 0, 10000000, 'l', \"X_STAGE\"},\n {\"X Width\", 0, 8000000, 'l', \"NONE\"},\n {\"Y center\", 0, 10000000, 'l', \"Y_STAGE\"},\n {\"Y Width\", 0, 8000000, 'l', \"NONE\"},\n {\"X Velocity\", 0, 5000000, 'l', \"X_VEL_STAGE\"},\n {\"Y Velocity\", 0, 5000000, 'l', \"Y_VEL_STAGE\"},\n {\"Step Size\", 0, 4000000, 'l', \"NONE\"},\n }\n },\n\n /*******************************************************/\n /*************** Telemetry/Scheduling *****************/\n {COMMAND(timeout), \"time until schedule mode\", GR_TELEM, 1,\n {\n {\"Timeout (s)\", 2, 65535, 'f', \"TIMEOUT\"}\n }\n },\n\n {COMMAND(set_linklists), \"change linklists for downlink\", GR_TELEM, 2,\n {\n {\"Downlink\", 0, 3, 'i', \"NONE\", {downlink_names}},\n {LINKLIST_SELECT}\n }\n },\n\n {COMMAND(set_pilot_oth), \"Set the pilot target to downlink\", GR_TELEM, 1,\n {\n {\"Downlink\", 0, 3, 'i', \"NONE\", {pilot_target_names}},\n }\n },\n {COMMAND(request_file), \"Stream a file at full bw over given link\", GR_TELEM, 4,\n {\n {\"Downlink\", 0, 3, 'i', \"NONE\", {downlink_names}},\n {\"File block number\", 0, 255, 'i', \"\"},\n {\"Fragment # (1-indexed; 0=>full file)\", 0, CMD_L_MAX, 'l', \"\"},\n {\"Absolute file path\", 0, 64, 's', \"\"}\n }\n },\n {COMMAND(request_stream_file), \"Stream a file at full bw over given link (compress first!)\", GR_TELEM, 4,\n {\n {\"Downlink\", 0, 3, 'i', \"NONE\", {downlink_names}},\n {\"File block number\", 0, 255, 'i', \"\"},\n {\"Fragment # (1-indexed; 0=>full file)\", 0, CMD_L_MAX, 'l', \"\"},\n {\"Type\", 0, 64, 'l', \"NONE\", {stream_types}}\n }\n },\n {COMMAND(biphase_clk_speed), \"mpsse clock speed\", GR_TELEM, 1,\n {\n {\"Clock speed (kbps)\", 100, 2000, 'i', \"mpsse_clock_speed\"}\n }\n },\n\n {COMMAND(highrate_through_tdrss), \"Highrate downlink\", GR_TELEM, 1,\n {\n {\"TDRSS(1) or Iridium(0)\", 0, 1, 'i', \"NONE\"}\n }\n },\n\n {COMMAND(highrate_bw), \"Highrate bandwidth\", GR_TELEM, 2,\n {\n {\"Bandwidth (kbps)\", 0, 500, 'f', \"rate_highrate\"},\n {\"Allframe fraction\", 0, 1, 'f', \"aff_highrate\"}\n }\n },\n\n {COMMAND(biphase_bw), \"biphase bandwidth\", GR_TELEM, 2,\n {\n {\"Bandwidth (kbps)\", 1, 2000, 'f', \"rate_biphase\"},\n {\"Allframe fraction\", 0, 1, 'f', \"aff_biphase\"}\n }\n },\n\n {COMMAND(pilot_bw), \"pilot bandwidth\", GR_TELEM, 2,\n {\n {\"Bandwidth (kbps)\", 0, 80000, 'f', \"rate_pilot\"},\n {\"Allframe fraction\", 0, 1, 'f', \"aff_pilot\"}\n }\n },\n {COMMAND(set_roach_mode), \"0=normal, 1=delta\", GR_TELEM, 1,\n {\n {\"Roach DL mode\", 0, 1, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_roach_all_chan), \"Send lots of kids for a given roach\", GR_TELEM, 2,\n {\n {\"Roach\", 1, 5, 'i', \"NONE\"},\n {\"Number of kids\", 0, 1024, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_roach_chan), \"Select 5 I/Q/df channel triplets\", GR_TELEM, 10,\n {\n {\"Kid A-C\", 0, 1023, 'i', \"NONE\"},\n {\"Roach A-C\", 1, 5, 'i', \"NONE\"},\n {\"Kid D-F\", 0, 1023, 'i', \"NONE\"},\n {\"Roach D-F\", 1, 5, 'i', \"NONE\"},\n {\"Kid G-I\", 0, 1023, 'i', \"NONE\"},\n {\"Roach G-I\", 1, 5, 'i', \"NONE\"},\n {\"Kid J-L\", 0, 1023, 'i', \"NONE\"},\n {\"Roach J-L\", 1, 5, 'i', \"NONE\"},\n {\"Kid M-O\", 0, 1023, 'i', \"NONE\"},\n {\"Roach M-O\", 1, 5, 'i', \"NONE\"}\n }\n },\n\n /****************************************/\n /*************** Misc. *****************/\n // {COMMAND(t_gyro_gain), \"gyro box heater gains\", GR_ELECT, 3,\n // {\n // {\"Proportional Gain\", 0, MAX_15BIT, 'i', \"g_p_heat_gy\"},\n // {\"Integral Gain\", 0, MAX_15BIT, 'i', \"g_i_heat_gy\"},\n // {\"Derivative Gain\", 0, MAX_15BIT, 'i', \"g_d_heat_gy\"}\n // }\n // },\n // {COMMAND(t_gyro_set), \"gyro box temperature set point\", GR_ELECT, 1,\n // {\n // {\"Set Point (deg C)\", 0, 60, 'f', \"T_SET_GY\"}\n // }\n // },\n\n// *****************************************\n// ROACH Commands\n// *****************************************\n {COMMAND(load_new_vna_amps), \"loads new VNA amplitudes from file\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"APPLY TRF FILE[1 = default (all 1), 2 = apply trf]\", 1, 2, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_targ_sweep_span), \"set the target sweep span\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Sweep span [kHz]\", 75, 250, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_targ_sweep_span_all), \"set all the target sweep spans\", GR_ROACH, 1,\n {\n {\"Sweep span [kHz]\", 75, 250, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_trnd_sweep_span), \"set the target sweep span for turnarounds\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Sweep span [kHz]\", 75, 250, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_trnd_sweep_span_all), \"set all the target sweep spans for turnarounds\", GR_ROACH, 1,\n {\n {\"Sweep span [kHz]\", 75, 250, 'i', \"NONE\"},\n }\n },\n {COMMAND(load_new_targ_amps), \"loads new TARG amplitudes from file\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"APPLY TRF FILE[1 = default, 2 = apply trf, 3 = apply last]\", 1, 3, 'i', \"NONE\"},\n }\n },\n {COMMAND(end_sweep), \"exit sweep\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"}\n }\n },\n {COMMAND(vna_sweep), \"perform a new VNA sweep\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n }\n },\n {COMMAND(cal_sweeps), \"perform a new set of cal sweeps\", GR_ROACH, 4,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Atten step (dB)\", 0.5, 6.0, 'd', \"NONE\"},\n {\"Number of sweep points\", 5, 101, 'd', \"NONE\"},\n {\"Number of cycles (sweeps)\", 2, 20, 'i', \"NONE\"},\n }\n },\n {COMMAND(targ_sweep), \"perform a new TARG sweep\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"}\n }\n },\n {COMMAND(roach_reset), \"re-upload roach firmware & recalibrate\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"}\n }\n },\n {COMMAND(calc_df), \"Calculate df for each channel\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Channel number\", 0, 1015, 'i', \"NONE\"},\n }\n },\n {COMMAND(auto_retune), \"Initializes auto retuning\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"0 = Manually retune, 1 = Auto retune\"}\n }\n },\n {COMMAND(auto_correct), \"Causes retune functions to automatically apply correction\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"0 = Disable, 1 = Enable\"}\n }\n },\n {COMMAND(auto_correct_all), \"(All Roaches) Causes retune functions to automatically apply correction\", GR_ROACH, 1,\n {\n {\"0 = Disable, 1 = Enable\"}\n }\n },\n {COMMAND(opt_tones), \"Attempt to fine tune targ tones found by get_targ_freqs()\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"0 = Default, off, 1 = Run\", 0, 1, 'i', \"NONE\"}\n }\n },\n {COMMAND(find_kids), \"Set the parameters for the kid finding algorithm, then execute\", GR_ROACH, 4,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"smoothing scale (kHz)\", 1000.0, 100000.0, 'd', \"NONE\"},\n {\"peak threshold (dB)\", 0.1, 100.0, 'd', \"NONE\"},\n {\"spacing threshold (kHz)\", 100.0, 10000.0, 'd', \"NONE\"},\n }\n },\n {COMMAND(set_attens), \"Set attenuators\", GR_ROACH, 3,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"rf_out_level\", 0.0, 30.0, 'd', \"NONE\"},\n {\"rf_in_level\", 0.0, 30.0, 'd', \"NONE\"},\n }\n },\n {COMMAND(set_attens_conserve), \"Set attenuators, conserving total\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"rf_out_level\", 0.0, 30.0, 'd', \"NONE\"},\n }\n },\n {COMMAND(set_attens_calc), \"Set attenuators with tone power calculation\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Desired dBm per tone\", -100.0, -17.0, 'd', \"NONE\"},\n }\n },\n {COMMAND(read_attens), \"Read attenuators\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n }\n },\n {COMMAND(reboot_pi), \"Attempt to reboot unresponsive Pi\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_attens_all), \"Set all attenuators to same values (input/output)\", GR_ROACH, 2,\n {\n {\"rf_out_level\", 0.0, 30.0, 'd', \"NONE\"},\n {\"rf_in_level\", 0.0, 30.0, 'd', \"NONE\"},\n }\n },\n {COMMAND(new_output_atten), \"Set only output atten\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"new_out_atten\", 0.0, 30.0, 'd', \"NONE\"}\n }\n },\n {COMMAND(show_adc_rms), \"Print the ADC rms voltages to the log\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"}\n }\n },\n {COMMAND(test_tone), \"Writes a single test tone to the DAC comb\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Test tone in Hz, between 1 - 250 MHz\", 1.0e6, 250.0e6, 'd', \"NONE\"},\n }\n },\n {COMMAND(change_state), \"Change Roach state\", GR_ROACH, 3,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"ROACH new state\", 0, 11, 'i', \"NONE\"},\n {\"ROACH desired state\", 0, 11, 'i', \"NONE\"},\n }\n },\n {COMMAND(get_state), \"Print current Roach state to MCP log\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"}\n }\n },\n {COMMAND(calc_phase_centers), \"Calculate channel phase centers from TARG sweep\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"}\n }\n },\n {COMMAND(timestream), \"Save a short IQ timestream\", GR_ROACH, 3,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Channel no\", 0, 1000, 'i', \"NONE\"},\n {\"Number of sec to stream\", 0, 300, 'd', \"NONE\"},\n }\n },\n {COMMAND(roach_ts), \"Save IQ timestreams for one Roach\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Number of sec to stream\", 0, 300, 'd', \"NONE\"},\n }\n },\n {COMMAND(roach_ts_all), \"Save IQ timestreams for all Roaches\", GR_ROACH, 1,\n {\n {\"Number of sec to stream\", 0, 300, 'd', \"NONE\"},\n }\n },\n {COMMAND(roach_df_all), \"Save DF timestreams for all Roaches\", GR_ROACH, 1,\n {\n {\"Number of sec to stream\", 0, 300, 'd', \"NONE\"},\n }\n },\n {COMMAND(cal_amps), \"Tune channel responsivity with optical chop\", GR_ROACH, 5,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Number of seconds to avg data\", 0, 10.0, 'd', \"NONE\"},\n {\"Number of cycles for cal\", 0, 10.0, 'i', \"NONE\"},\n {\"Delta amp\", 0, 10.0, 'd', \"NONE\"},\n {\"Desired response threshold\", 0, 30000, 'i', \"NONE\"},\n }\n },\n {COMMAND(refit_freqs), \"Performs a short sweep, fits res freqs and rewrites comb\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Find on res, or find max IQ grad\", 0, 1, 'i', \"NONE\"},\n }\n },\n {COMMAND(refit_freqs_all), \"Refit freqs on all Roaches\", GR_ROACH, 1,\n {\n {\"Find on res, or find max IQ grad\", 0, 1, 'i', \"NONE\"},\n }\n },\n {COMMAND(full_loop), \"Performs full loop for single Roach (MUST HAVE VNA COMB LOADED)\", GR_ROACH, 3,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Find KIDs option (1 for default, 2 for params)\", 1, 2, 'i', \"NONE\"},\n {\"Desired dBm per tone\", -100.0, -17.0, 'd', \"NONE\"},\n }\n },\n {COMMAND(full_loop_all), \"Performs full loop for all Roaches\", GR_ROACH, 2,\n {\n {\"Find KIDs option (1 for default, 2 for params)\", 1, 2, 'i', \"NONE\"},\n {\"Desired dBm per tone\", -100.0, -17.0, 'd', \"NONE\"},\n }\n },\n {COMMAND(full_loop_default), \"Performs full loop for single Roach\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n }\n },\n {COMMAND(df_targ), \"Performs a short sweep, calculates df from ref sweep\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n }\n },\n {COMMAND(targ_refit), \"Performs a short sweep, fits res freqs and rewrites comb\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Check lamp cal\", 0, 1, 'i', \"NONE\"},\n }\n },\n {COMMAND(targ_refit_all), \"(All Roaches) Performs a short sweep, fits res freqs and rewrites comb\", GR_ROACH, 1,\n {\n {\"Check lamp cal\", 0, 1, 'i', \"NONE\"},\n }\n },\n {COMMAND(chop_template), \"Saves timestreams for all channel and calculates avg chop\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"}\n }\n },\n {COMMAND(load_freqs), \"loads a list of tone freqs from file\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"}\n }\n },\n {COMMAND(new_ref_params), \"calculates and saves ref params\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"}\n }\n },\n {COMMAND(offset_lo), \"shift LO by specified amount in Hz\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Amount to shift LO\", -1000000., 1000000., 'd', \"NONE\"},\n }\n },\n {COMMAND(offset_lo_all), \"shift all LOs by specified amount in Hz\", GR_ROACH, 1,\n {\n {\"Amount to shift LO\", -1000000.0, 1000000.0, 'd', \"NONE\"},\n }\n },\n {COMMAND(center_lo), \"recenter the LO\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"}\n }\n },\n {COMMAND(set_lo_MHz), \"set the LO frequency\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"lo freq MHz\", 100.0, 3000.0, 'd', \"NONE\"},\n }\n },\n {COMMAND(read_lo), \"Read the LO frequency\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n }\n },\n {COMMAND(read_pi_temp), \"Read Pi temp\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n }\n },\n {COMMAND(find_kids_default), \"Find res freqs from VNA sweeps using default params\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"}\n }\n },\n {COMMAND(change_amp), \"Shifts the amplitude of specified channel bias by delta amp\", GR_ROACH, 3,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Channel number\", 0, 1015, 'i', \"NONE\"},\n {\"delta_amp\", -5, 5, 'd', \"NONE\"},\n }\n },\n {COMMAND(change_freq), \"Shifts freq of single chan by m_roach->df\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Channel number\", 0, 1015, 'i', \"NONE\"},\n }\n },\n {COMMAND(change_phase), \"Shifts the phase of specified channel by delta phase\", GR_ROACH, 3,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Channel number\", 0, 1015, 'i', \"NONE\"},\n {\"delta_phase\", -3.14159, 3.14159, 'd', \"NONE\"},\n }\n },\n {COMMAND(offset_freq), \"Shifts the freq of specified channel by freq offset\", GR_ROACH, 3,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Channel number\", 0, 1015, 'i', \"NONE\"},\n {\"delta_freq\", -1000000.0, 1000000.0, 'd', \"NONE\"},\n }\n },\n {COMMAND(auto_find_kids), \"Automatically do a VNA sweep, find kids and write tonest\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"}\n }\n },\n {COMMAND(check_df_retune), \"Checks df status for each channel and makes retune recommendation\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n }\n },\n {COMMAND(median_sweep_df), \"Performs a sweep and reports the median df difference\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n }\n },\n {COMMAND(check_dfsweep_retune), \"Checks df status with sweep method and makes retune recommendation\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n }\n },\n {COMMAND(check_lamp_retune), \"Checks response to cal lamp (I,Q,df(I,Q)) and makes retune recommendation\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Number of sec to stream\", 0, 300, 'd', \"NONE\"},\n }\n },\n {COMMAND(check_lamp_retune_all),\n \"(All Roaches) Checks response to cal lamp (I,Q,df(I,Q)) and recommends retune\", GR_ROACH, 1,\n {\n {\"Number of sec to stream\", 0, 300, 'd', \"NONE\"},\n }\n },\n {COMMAND(roach_set_allow_trnd_sweeps), \"Toggle target sweeps at the end of each scan\", GR_ROACH, 3,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Top scan tuning check\", 0, 1, 'i', \"NONE\", {disable_enable}},\n {\"Bottom scan tuning check\", 0, 1, 'i', \"NONE\", {disable_enable}},\n }\n },\n {COMMAND(roach_set_allow_trnd_sweeps_all), \"Toggle target sweeps at the end of each scan\", GR_ROACH, 1,\n {\n {\"State\", 0, 1, 'i', \"NONE\", {disable_enable}}\n }\n },\n {COMMAND(set_retune_type_all), \"(All Roaches) Sets retune type (df sweep, df ts, lamp df shift)\", GR_ROACH, 1,\n {\n {\"Sets do_check_retune\", 0, 3, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_retune_type), \"Sets retune type (df sweep, df ts, lamp df shift)\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Sets do_check_retune\", 0, 3, 'i', \"NONE\"},\n }\n },\n {COMMAND(noise_comp), \"Run noise comp for one Roach\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Number of sec to stream\", 0, 300, 'd', \"NONE\"},\n }\n },\n {COMMAND(noise_comp_all), \"Run noise comp for all Roaches\", GR_ROACH, 1,\n {\n {\"Number of sec to stream\", 0, 300, 'd', \"NONE\"},\n }\n },\n {COMMAND(find_kids_loop), \"sweep and find freqs for one Roach\", GR_ROACH, 3,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Find KIDs option (1 for default, 2 for params)\", 1, 2, 'i', \"NONE\"},\n {\"Desired dBm per tone\", -100.0, -17.0, 'd', \"NONE\"},\n }\n },\n {COMMAND(find_kids_loop_all), \"sweep and find freqs for all Roaches\", GR_ROACH, 2,\n {\n {\"Find KIDs option (1 for default, 2 for params)\", 1, 2, 'i', \"NONE\"},\n {\"Desired dBm per tone\", -100.0, -17.0, 'd', \"NONE\"},\n }\n },\n {COMMAND(turnaround_loop), \"Cal pulse/df, TARG/REFIT/TARG, Cal pulse/df\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Number of sec to stream\", 0, 300, 'd', \"NONE\"},\n }\n },\n {COMMAND(turnaround_loop_all), \"(All Roaches) Cal pulse/df, TARG/REFIT/TARG, Cal pulse/df\", GR_ROACH, 1,\n {\n {\"Number of sec to stream\", 0, 300, 'd', \"NONE\"},\n }\n },\n {COMMAND(kill_roach),\n \"Shutdown Roach PPC. To bring up requires full power cycle\", CONFIRM | GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_df_retune_threshold), \"Set DF retune threshold for one Roach (Hz)\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"DF threshold (Hz)\", 2000, 120000, 'd', \"NONE\"},\n }\n },\n {COMMAND(set_df_retune_threshold_all), \"(All Roaches) Set DF retune threshold (Hz)\", GR_ROACH, 1,\n {\n {\"DF threshold (Hz)\", 2000, 120000, 'd', \"NONE\"},\n }\n },\n {COMMAND(set_df_diff_retune_threshold), \"Set DF diff retune threshold for one Roach (Hz)\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"DF diff threshold (Hz)\", 2000, 120000, 'd', \"NONE\"},\n }\n },\n {COMMAND(set_df_diff_retune_threshold_all), \"(All Roaches) Set DF diff retune threshold (Hz)\", GR_ROACH, 1,\n {\n {\"DF diff threshold (Hz)\", 2000, 120000, 'd', \"NONE\"},\n }\n },\n {COMMAND(set_min_nkids), \"Set min N KIDS found for tone finding error to go high\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Min number KIDS found\", 1, 100, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_min_nkids_all),\n \"(All Roaches) Set min N KIDS found for tone finding error to go high\", GR_ROACH, 1,\n {\n {\"Min number KIDS found\", 1, 100, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_max_nkids), \"Set max N KIDS found for tone finding error to go high\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Max number KIDS found\", 500, 900, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_max_nkids_all),\n \"(All Roaches) Set max N KIDS found for tone finding error to go high\", GR_ROACH, 1,\n {\n {\"Max number KIDS found\", 500, 900, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_n_outofrange_thresh), \"Set N channels out of range thresh\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"N out of range threshold (for retune decision)\", 0, 500, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_n_outofrange_thresh_all), \"(All Roaches) Set N channels out of range thresh\", GR_ROACH, 1,\n {\n {\"N out of range threshold (for retune decision)\", 0, 500, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_default_tone_power), \"Set default tone power (target output power in dBm/tone)\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"Desired dBm per tone\", -100.0, -17.0, 'd', \"NONE\"},\n }\n },\n {COMMAND(set_default_tone_power_all),\n \"(All Roaches) Set default tone power (target output power in dBm/tone)\", GR_ROACH, 1,\n {\n {\"Desired dBm per tone\", -100.0, -17.0, 'd', \"NONE\"},\n }\n },\n {COMMAND(set_attens_default), \"Set attenuators\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n }\n },\n {COMMAND(set_find_kids_params),\n \"Set the parameters for the kid finding algorithm. Does not execute\", GR_ROACH, 4,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"smoothing scale (kHz)\", 1000.0, 100000.0, 'd', \"NONE\"},\n {\"peak threshold (dB)\", 0.1, 100.0, 'd', \"NONE\"},\n {\"spacing threshold (kHz)\", 80.0, 10000.0, 'd', \"NONE\"},\n }\n },\n {COMMAND(compress_roach_data), \"Tarballs all files of specified type for downlink\", GR_ROACH, 1,\n {\n {\"Files to compress (before downlink)\", 0, 64, 'i', \"NONE\", {stream_types}}\n }\n },\n {COMMAND(enable_cycle_checker), \"Enables or disables cycle checker\", GR_ROACH, 1,\n {\n {\"State\", 0, 1, 'i', \"NONE\", {disable_enable}}\n }\n },\n {COMMAND(chop_lo), \"Do 3 point LO sweep\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n }\n },\n {COMMAND(enable_chop_lo_all), \"(All Roaches) Enables or disables LO chop\", GR_ROACH, 1,\n {\n {\"State\", 0, 1, 'i', \"NONE\", {disable_enable}},\n }\n },\n {COMMAND(enable_chop_lo), \"Enables or disables LO chop\", GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"State\", 0, 1, 'i', \"NONE\", {disable_enable}},\n }\n },\n {COMMAND(roach_has_lamp_control), \"Gives exclusive control of cal lamp to specified Roach\", GR_ROACH, 1,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n }\n },\n {COMMAND(roach_set_extref), \"Sets external reference for FPGA CLOCK and LO\", CONFIRM | GR_ROACH, 2,\n {\n {\"ROACH no\", 1, 5, 'i', \"NONE\"},\n {\"State\", 0, 1, 'i', \"NONE\", {internal_external}},\n }\n },\n {COMMAND(roach_set_extref_all), \"(All Roaches) Sets external reference for FPGA CLOCK and LO\",\n CONFIRM | GR_ROACH, 1,\n {\n {\"State\", 0, 1, 'i', \"NONE\", {internal_external}},\n }\n },\n {COMMAND(enable_roach_cal_pulse),\n \"(All Roaches) Enables or disables cal lamp during turnaround loop\", GR_ROACH, 1,\n {\n {\"State\", 0, 1, 'i', \"NONE\", {disable_enable}},\n }\n },\n /***************************************/\n /***************************************/\n /*************** ROX Bias *************/\n {COMMAND(set_rox_bias_amp), \"Set the ROX bias amplitude\", GR_CRYO, 1,\n {\n {\"ROX bias amplitude (0-64)\", 0, 64, 'i', \"NONE\"}\n }\n },\n /***************************************/\n /*************** Bias *****************/\n {COMMAND(bias_level_250), \"bias level 250 micron\", GR_BIAS, 1,\n {\n {\"Level\", 0, 32767, 'i', \"AMPL_250_BIAS\"}\n }\n },\n {COMMAND(bias_level_350), \"bias level 350 micron\", GR_BIAS, 1,\n {\n {\"Level\", 0, 32767, 'i', \"AMPL_350_BIAS\"}\n }\n },\n {COMMAND(bias_level_500), \"bias level 500 micron\", GR_BIAS, 1,\n {\n {\"Level\", 0, 32767, 'i', \"AMPL_500_BIAS\"}\n }\n },\n {COMMAND(bias_step), \"step through different bias levels\", GR_BIAS, 6,\n {\n {\"Start\", 0, 32767, 'i', \"STEP_START_BIAS\"},\n {\"End\", 0, 32767, 'i', \"STEP_END_BIAS\"},\n {\"N steps\", 1, 32767, 'i', \"step_nsteps_bias\"},\n {\"Time per step (ms)\", 10, 32767, 'i', \"step_time_bias\"},\n {\"Cal pulse length (ms)\", 0, 32767, 'i', \"step_pul_len_bias\"},\n {\"Array (250, 350, 500, 0=all)\", 0, 32767, 'i', \"step_array_bias\"},\n }\n },\n // {COMMAND(phase_step), \"step through different phases\", GR_BIAS, 4,\n // {\n // {\"Start\", 0, 32767, 'i', \"STEP_START_PHASE\"},\n // {\"End\", 0, 32767, 'i', \"STEP_END_PHASE\"},\n // {\"N steps\", 1, 32767, 'i', \"step_nsteps_phase\"},\n // {\"Time per step (ms)\", 1, 32767, 'i', \"step_time_phase\"},\n // }\n // },\n {COMMAND(bias_level_rox), \"bias level ROX\", GR_BIAS, 1,\n {\n {\"Level\", 0, 32767, 'i', \"AMPL_ROX_BIAS\"}\n }\n },\n {COMMAND(bias_level_x), \"bias level X (unused)\", GR_BIAS, 1,\n {\n {\"Level\", 0, 32767, 'i', \"ampl_x_bias\"}\n }\n },\n {COMMAND(phase), \"set phase shift\", GR_BIAS, 2,\n {\n {\"DAS Card (0=all)\", 0, 63, 'i', \"NONE\"},\n {\"Phase\", 0, 32767, 'i', \"NONE\"}\n }\n },\n\n /***************************************/\n /*********** Cal Lamp *****************/\n // {COMMAND(cal_repeat), \"set calibrator to automatic repeated pulse mode\", GR_CRYO, 3,\n // {\n // {\"Pulse Length (ms)\", 10, 8000, 'i', \"PULSE_CAL\"},\n // {\"Max Pulse Delay (0=never pulse) (s)\", 0, 32767, 'i', \"PERIOD_CAL\"},\n // {\"Always Pulse before HWP move (0=no, 1=yes)\", 0, 1, 'i', \"NONE\"}\n // }\n // },\n {COMMAND(cal_length), \"set length of calibration pulse\", GR_CRYO, 1,\n {\n {\"Pulse Length (ms)\", 5, 5000, 'i', \"PULSE_CAL\"}\n }\n },\n {COMMAND(set_tcrit_fpa), \"set ADC counts of fpa critical temp\", GR_CRYO, 1,\n {\n {\"ADC counts\", 0, 20000, 'i', \"ADC\"}\n }\n },\n {COMMAND(level_length), \"set length of level sensor pulse\", GR_CRYO, 1,\n {\n {\"Pulse Length (s)\", 5, 5000, 'i', \"PULSE_LEVEL\"}\n }\n },\n {COMMAND(periodic_cal), \"periodic cal pulses sent\", GR_CRYO, 3,\n {\n {\"Number of Pulses\", 1, 1000, 'i', \"NUM_PULSE\"},\n {\"Separation (in 5ms steps)\", 2, 30000, 'i', \"SEPARATION\"},\n {\"Length of Pulse (in 5ms steps)\", 2, 30000, 'i', \"LENGTH_PULSE\"},\n }\n },\n {COMMAND(set_queue_execute), \"command queue changed\", GR_CRYO, 1,\n {\n {\"Labjack to execute queue\", 0, 4, 'i', \"LJ\"},\n }\n },\n {COMMAND(reconnect_lj), \"rebooting labjack cryo 1\", GR_CRYO, 1,\n {\n {\"Labjack to reconnect\", 1, 7, 'i', \"NONE\"},\n }\n },\n {COMMAND(ir_source_pulse), \"Pulsing IR source\", GR_CRYO, 1,\n {\n {\"Length of Pulse (in 5ms steps)\", 1, 30000, 'i', \"LENGTH_PULSE\"},\n }\n },\n {COMMAND(set_cal_timeout), \"Setting timeout to cal pulse and resetting counter\", GR_CRYO, 1,\n {\n {\"Length of timeout in seconds\", 600, 216000, 'i', \"TIMEOUT_LENGTH\"},\n }\n },\n /***************************************/\n /********* Cryo heat *****************/\n {COMMAND(send_dac), \"turning on dac0 to specified voltage on specified labjack\",\n GR_CRYO, 2, {\n {\"Voltage\", 0., 5., 'f', \"VOLTS_TO_DAC\"},\n {\"Labjack - not 1\", 0, 4, 'i', \"LABJACK\"}\n }\n },\n // {COMMAND(jfet_set), \"jfet heater setpoints\", GR_CRYO, 2,\n // {\n // {\"On Point (K)\", 0, 400., 'f', \"JFET_SET_ON\"},\n // {\"Off Point (K)\", 0, 400., 'f', \"JFET_SET_OFF\"}\n // }\n // },\n\n // {COMMAND(fridge_cycle_params), \"Fridge cycle parameters\", GR_CRYO, 6,\n // {\n // {\"300mK_strap Start Temp (K)\", 0, 4., 'f', \"T_START_CYCLE\"},\n // {\"Pot Max Temp (K)\", 0, 10., 'f', \"T_POT_MAX_CYCLE\"},\n // {\"Charcoal Max Temp (K)\", 0, 70., 'f', \"T_CHAR_MAX_CYCLE\"},\n // {\"Charcoal Timeout (min)\", 0, 120., 'f', \"TIME_CHAR_CYCLE\"},\n // {\"Charcoal Settled Temp (K)\", 0, 70., 'f', \"T_CHAR_SET_CYCLE\"},\n // {\"Charcoal Settle Time (min)\", 0, 120., 'f', \"TIME_SET_CYCLE\"}\n // }\n // },\n\n {COMMAND(potvalve_set_vel), \"Set pot valve motor velocity\", GR_CRYO, 1,\n {\n {\"Velocity (microsteps/sec)\", 0, 100000, 'i', \"POTVALVE_VEL\"}\n }\n },\n\n {COMMAND(potvalve_set_hold_current), \"Set pot valve motor velocity\", GR_CRYO, 1,\n {\n {\"Hold current (% max, up to 50)\", 0, 50, 'i', \"I_HOLD_POTVALVE\"}\n }\n },\n\n {COMMAND(potvalve_set_current), \"Set pot valve open and close currents\", GR_CRYO, 2,\n {\n {\"Pot valve open current (% max)\", 0, 100, 'i', \"POTVALVE_I_OPEN\"},\n {\"Pot valve close current (% max)\", 0, 100, 'i', \"POTVALVE_I_CLOSE\"}\n }\n },\n\n {COMMAND(potvalve_set_thresholds), \"Set pumped pot valve thresholds\", GR_CRYO, 3,\n {\n {\"Closed threshold (1000-7000)\", 1000, 7000, 'i', \"THRESH_CLOS_POTVALVE\"},\n {\"Loose close threshold (7000-10000)\", 7000, 10000, 'i', \"THRESHLCLOS_POTVALVE\"},\n {\"Open threshold (10000-16000)\", 10000, 16000, 'i', \"THRESH_OPEN_POTVALVE\"},\n }\n },\n\n {COMMAND(potvalve_set_tighten_move), \"Set pumped pot tightening minimum move size (in encoder units)\", GR_CRYO, 1,\n {\n {\"Minimum size of a tightening move\", 0, 5000, 'i', \"TIGHT_MOVE_POTVALVE\"}\n }\n },\n\n {COMMAND(valves_set_vel), \"Set cryostat valves velocity\", GR_CRYO, 1,\n {\n {\"Cryostat valves velocity (microsteps/sec)\", 0, 100000, 'i', \"VEL_VALVES\"}\n }\n },\n\n {COMMAND(valves_set_move_i), \"Set cryostat valves move current\", GR_CRYO, 1,\n {\n {\"Cryostat valves move current (% max)\", 0, 100, 'i', \"I_MOVE_VALVES\"}\n }\n },\n\n {COMMAND(valves_set_hold_i), \"Set cryostat valves hold current\", GR_CRYO, 1,\n {\n {\"Cryostat valves hold current (up to 50%)\", 0, 50, 'i', \"I_HOLD_VALVES\"}\n }\n },\n\n {COMMAND(valves_set_acc), \"Set cryostat valves acceleration\", GR_CRYO, 1,\n {\n {\"Cryostat valves acceleration\", 0, 6000, 'i', \"ACC_VALVES\"}\n }\n },\n\n {COMMAND(aalborg_set_speeds), \"Set the speed for aalborg moves, 0.0 will stop the motion\", GR_CRYO, 3,\n {\n {\"Aalborg 1 speed (0.0-2.5 V)\", 0.0, 2.5, 'f', \"SPEED_1_AALBORG\"},\n {\"Aalborg 2 speed (0.0-2.5 V)\", 0.0, 2.5, 'f', \"SPEED_2_AALBORG\"},\n {\"Aalborg 3 speed (0.0-2.5 V)\", 0.0, 2.5, 'f', \"SPEED_3_AALBORG\"}\n }\n },\n {COMMAND(aalborg_finite_move), \"Move one of the Aalborgs for a finite amount of time\", GR_CRYO, 3,\n {\n {\"Which Aalborg to move (0=science sphere bypass, 1=Pump A, 2=Pump B)\", 0, 2, 'i', \"NONE\"},\n {\"Direction to move (-1=close, 1=open, 0=stop)\", -1, 1, 'i', \"NONE\"},\n {\"How long valve should move, in seconds\", 0, 60, 'i', \"NONE\"}\n }\n },\n {COMMAND(labjack9_write_reg), \"Write an arbitrary value to a modbus register on microscroll labjack (#9)\", GR_MISC, 2,\n {\n {\"Register to write to\", 1000, 30050, 'i', \"NONE\"},\n {\"Value to write\", -10.0, 10.0, 'f', \"NONE\"}\n }\n },\n\n // <!-- XSC general -->\n\n\n\n\n\n//// <!-- XSC exposure -->\n\n {COMMAND(xsc_exposure_timing), \"xsc exposure time\", GR_XSC_PARAM, 4,\n {\n {\"which\", 0, 2, 'i', \"NONE\"},\n {\"exposure time_cs (cs) [default: 12]\", 1, 100, 'l', \"NONE\"},\n {\"grace period (s) (disregards which) [default: 45.0]\", 1.0, 100.0, 'f', \"NONE\"},\n {\"post trigger counter_mcp share delay (cs) (disregards which) [default: 200]\", 1, 1000, 'l', \"NONE\"},\n },\n },\n\n\n {COMMAND(xsc_multi_trigger), \"xsc trigger timing\", GR_XSC_PARAM, 3,\n {\n {\"num triggers [default: 1]\", 0, 16, 'i', \"NONE\"},\n {\"time between triggers (cs) [default: 19]\", 1, 100, 'l', \"NONE\"},\n {\"stars readout delay (s) [default: 1.0]\", 0.1, 10.0, 'f', \"NONE\"},\n },\n },\n\n//// <!-- XSC main -->\n\n\n {COMMAND(xsc_main_settings), \"xsc main settings\", GR_XSC_PARAM, 6,\n {\n {\"which\", 0, 2, 'i', \"NONE\"},\n {\"display_frequency [default: 20.0]\", 1.0, 30.0, 'f', \"NONE\"},\n {\"display_fullscreen [default: 1]\", 0, 1, 'i', \"NONE\"},\n {\"display_image_only [default: 0]\", 0, 1, 'i', \"NONE\"},\n {\"display_solving_filters [default: 0]]\", 0, 1, 'i', \"NONE\"},\n {\"display_image_brightness [default: 1.0]\", 0.5, 4.0, 'f', \"NONE\"},\n },\n },\n\n\n {COMMAND(xsc_display_zoom), \"xsc display zoom\", GR_XSC_PARAM, 4,\n {\n {\"which\", 0, 2, 'i', \"NONE\"},\n {\"center x display pixel [default: 320]\", 0, 1000, 'i', \"NONE\"},\n {\"center y display pixel [default: 240]\", 0, 1000, 'i', \"NONE\"},\n {\"zoom [default: 1.0]\", 1.0, 4.0, 'f', \"NONE\"},\n },\n },\n\n// {COMMAND(xsc_network_reset), \"Reset the xsc network\", GR_XSC_PARAM, 4,\n// {\n// {\"which\", 0, 2, 'i', \"NONE\"},\n// {\"reset now?\", 0, 1, 'i', \"NONE\"},\n// {\"enable lull?\", 0, 1, 'i', \"NONE\"},\n// {\"lull delay\", 0.0, 30.0, 'f', \"NONE\"},\n// },\n// },\n\n\n\n//// <!-- XSC imaging (lens, camera, fake sky, masking) -->\n\n\n\n {COMMAND(xsc_run_autofocus), \"xsc run autofocus\", GR_XSC_PARAM, 1,\n {\n {\"which\", 0, 2, 'i', \"NONE\"},\n },\n },\n\n {COMMAND(xsc_set_autofocus_range), \"xsc set autofocus range\", GR_XSC_PARAM, 4,\n {\n {\"which\", 0, 2, 'i', \"NONE\"},\n {\"focus_search_min\", 0, 5000, 'l', \"NONE\"},\n {\"focus_search_max\", 0, 5000, 'l', \"NONE\"},\n {\"focus_search_step\", 1, 1000, 'l', \"NONE\"},\n },\n },\n\n {COMMAND(xsc_abort_autofocus), \"xsc abort autofocus\", GR_XSC_PARAM, 2,\n {\n {\"which\", 0, 2, 'i', \"NONE\"},\n {\"still_use_solution\", 0, 1, 'i', \"NONE\"},\n },\n },\n\n {COMMAND(xsc_autofocus_display_mode), \"xsc autofocus display mode\", GR_XSC_PARAM, 2,\n {\n {\"which\", 0, 2, 'i', \"NONE\"},\n {\"mode (0=auto, 1=on, 2=off)\", 0, 2, 'i', \"NONE\"},\n },\n },\n\n {COMMAND(xsc_get_gain), \"xsc get gain\", GR_XSC_PARAM, 0,\n {\n {\"which\", 0, 2, 'i', \"NONE\"},\n },\n },\n\n {COMMAND(xsc_set_gain), \"xsc set gain\", GR_XSC_PARAM, 0,\n {\n {\"which\", 0, 2, 'i', \"NONE\"},\n {\"position\", 0.5, 10.0, 'f', \"NONE\"},\n },\n },\n\n\n {COMMAND(xsc_fake_sky_brightness), \"xsc fake sky brightness\", GR_XSC_PARAM, 0,\n {\n {\"which\", 0, 2, 'i', \"NONE\"},\n {\"enabled\", 0, 1, 'i', \"NONE\"},\n {\"level_kepsa\", 0.0, 10000.0, 'f', \"NONE\"},\n {\"gain_db\", -50, 10, 'f', \"NONE\"},\n {\"actual exposure time (s)\", 0.01, 10.0, 'f', \"NONE\"},\n {\"simulated exposure time (s)\", 0.01, 10.0, 'f', \"NONE\"},\n },\n },\n {COMMAND(motors_verbose), \"Set verbosity of motor serial threads (0=norm, 1=verbose, 2= superverbose )\", GR_MISC, 3,\n {\n {\"Reaction Wheel\", 0, 5, 'i', \"VERBOSE_RW\"},\n {\"Elevation\", 0, 5, 'i', \"VERBOSE_EL\"},\n {\"Pivot\", 0, 5, 'i', \"VERBOSE_PIV\"}\n }\n },\n {COMMAND(shutter_step), \"DEPRECATED: set number of shutter steps to close (default 4224)\", GR_MISC, 1,\n {\n {\"Steps\", 1, 5000, 'i', \"STEPS_SHUTTER\"},\n }\n },\n {COMMAND(shutter_step_slow), \"DEPRECATED: set number of incremental shutter steps to close (default 300)\",\n\t\tGR_MISC, 1,\n {\n {\"Steps slow\", 1, 5000, 'i', \"STEPS_SLOW_SHUTTER\"},\n }\n },\n {COMMAND(shutter_i), \"set shutter move and hold currents\", GR_MISC, 2,\n {\n\t {\"Shutter move current\", 0, 42, 'i', \"I_MOVE_SHUTTER\"},\n\t {\"Shutter hold current\", 0, 42, 'i', \"I_HOLD_SHUTTER\"},\n }\n },\n {COMMAND(shutter_vel), \"set shutter velocity and acceleration\", GR_MISC, 2,\n {\n\t {\"Shutter velocity\", 0, 10000, 'i', \"VEL_SHUTTER\"},\n\t {\"Shutter acceleration\", 0, 20, 'i', \"ACC_SHUTTER\"},\n }\n },\n {COMMAND(params_test), \"Do nothing, with all paramter types\", GR_MISC, 5,\n {\n {\"i\", 0, CMD_I_MAX, 'i', \"NONE\"},\n {\"l\", 0, CMD_L_MAX, 'l', \"NONE\"},\n {\"f (-100 to +100)\", -100, 100, 'f', \"NONE\"},\n {\"d (-100 to +100)\", -100, 100, 'd', \"NONE\"},\n {\"s\", 0, 32, 's', \"NONE\"}\n }\n },\n {COMMAND(plugh), \"A hollow voice says \\\"Plugh\\\".\", GR_MISC, 1,\n {\n {\"Plover\", 0, CMD_I_MAX, 'i', \"PLOVER\"}\n }\n },\n {COMMAND(xsc_is_new_window_period), \"Set the time over which commands are valid (in centi-seconds)\",\n GR_XSC_PARAM, 2,\n {\n {\"Which\", 0, 2, 'i', \"NONE\"},\n {\"Window period\", 0, 2000, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_offset), \"Trim the star camera\", GR_XSC_PARAM|GR_TRIM, 3,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Cross-El trim\", -180, 180, 'd', \"NONE\"},\n {\"El trim\", -180, 180, 'd', \"NONE\"},\n }\n },\n\n //// <!-- XSC heaters -->\n\n {COMMAND(xsc_heaters_off), \"Turn off the XSC heater\", GR_XSC_HOUSE, 1,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_heaters_on), \"Turn on the XSC heater\", GR_XSC_HOUSE, 1,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_heaters_auto), \"Allow XSC to control its heater\", GR_XSC_HOUSE, 1,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_trigger_threshold), \"Allow XSC to trigger based on predicted px streaking\", GR_XSC_PARAM, 3,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Enabled\", 0, 1, 'i', \"NONE\"},\n {\"Blob streaking limit (pixels\", 0, 100, 'f', \"NONE\"},\n }\n },\n {COMMAND(xsc_scan_force_trigger), \"Force XSC to trigger on turnaround (ignore speed)\", GR_XSC_PARAM, 2,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Force the trigger on scan limits\", 0, 1, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_quit), \"Quit XSC\", GR_XSC_HOUSE|CONFIRM, 1,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_shutdown), \"Shutdown the XSC computer\", GR_XSC_HOUSE|CONFIRM, 2,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Restart?\", 0, 1, 'i', \"NONE\"}\n }\n },\n\n {COMMAND(xsc_image_client), \"Enable or disable sending images to mcp\", GR_XSC_MODE, 2,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Image client enabled\", 0, 1, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_init_focus), \"Initialize the focus motor\", GR_XSC_MODE, 1,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_get_focus), \"Get the absolute focus position\", GR_XSC_MODE, 1,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_set_focus), \"Set the absolute focus position\", GR_XSC_MODE, 2,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Absolute focus position\", 0, 5000, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_stop_focus), \"Stop all motion on the focus actuator\", GR_XSC_MODE, 1,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_define_focus), \"Define the value of the focus at the current position\", GR_XSC_MODE, 2,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Focus value\", 0, 5000, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_set_focus_incremental), \"Command an incremental step to the focus motor\", GR_XSC_MODE, 2,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Incremental focus steps\", -5000, 5000, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_init_aperture), \"Initialize the aperture motor\", GR_XSC_MODE, 1,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_get_aperture), \"Get Aperture\", GR_XSC_MODE, 1,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_set_aperture), \"Set the absolute aperture position\", GR_XSC_MODE, 2,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Absolute aperture position\", 0, 1000, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_stop_aperture), \"Stop all motion on the aperture actuator\", GR_XSC_MODE, 1,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_define_aperture), \"Define the value of the aperture at the current position\", GR_XSC_MODE, 2,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Aperture value\", 0, 1000, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_solver_general), \"Solver parameter settings\", GR_XSC_PARAM, 3,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Enable the solver\", 0, 1, 'i', \"NONE\"},\n {\"Set the solver timeout period (s)\", 5, 600, 'f', \"NONE\"},\n }\n },\n {COMMAND(xsc_solver_abort), \"Abort the solving the current image\", GR_XSC_MODE, 1,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"}\n }\n },\n {COMMAND(xsc_selective_mask), \"Set the XSC selective mask\", GR_XSC_PARAM, 5,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Enable selective masking\", 0, 1, 'i', \"NONE\"},\n {\"Mask field 1\", 0, CMD_L_MAX, 'l', \"NONE\"},\n {\"Mask field 2\", 0, CMD_L_MAX, 'l', \"NONE\"},\n {\"Mask field 3\", 0, CMD_L_MAX, 'l', \"NONE\"},\n }\n },\n {COMMAND(xsc_blob_finding), \"XSC blob finder settings\", GR_XSC_PARAM, 5,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"SNR Threshhold\", 0.01, 10, 'f', \"NONE\"},\n {\"Max num blobs\", 3, 100, 'i', \"NONE\"},\n {\"Enable Robust mode\", 0, 1, 'i', \"NONE\"},\n {\"Fitting method (0= none, 1=gaussian, 2=double gaussian)\", 0, 2, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_blob_cells), \"XSC blob cell settings\", GR_XSC_PARAM, 3,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Cell size (pixels, power of 2)\", 4, 512, 'i', \"NONE\"},\n {\"Max num blobs per cell (default 2)\", 1, 10, 'i', \"NONE\"},\n }\n },\n {COMMAND(xsc_pattern_matching), \"XSC pattern matching settings\", GR_XSC_PARAM, 8,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Pattern match enable\", 0, 1, 'i', \"NONE\"},\n {\"Display Star names\", 0, 1, 'i', \"NONE\"},\n {\"Match Tolerance (pixels)\", 0.01, 10, 'f', \"NONE\"},\n {\"Platescale min (\\\"/px)\", 6.0, 7.0, 'f', \"NONE\"},\n {\"Platescale max (\\\"/px)\", 6.0, 7.0, 'f', \"NONE\"},\n {\"Use fixed Platescale\", 0, 1, 'i', \"NONE\"},\n {\"Fixed Platescale (\\\"/px)\", 6.0, 7.0, 'f', \"NONE\"},\n }\n },\n {COMMAND(xsc_filter_hor_location), \"XSC Horizontal Location Filter\", GR_XSC_PARAM, 3,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Horizontal Limit Enabled\", 0, 1, 'i', \"NONE\"},\n {\"Horizontal Radius (degrees)\", 0.0, 90.0, 'f', \"NONE\"},\n }\n },\n {COMMAND(xsc_filter_eq_location), \"XSC Equatorial Location Filter\", GR_XSC_PARAM, 3,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Equatorial Limit Enabled\", 0, 1, 'i', \"NONE\"},\n {\"Equatorial Radius (degrees)\", 0.0, 90.0, 'f', \"NONE\"},\n }\n },\n {COMMAND(xsc_filter_hor_roll), \"XSC Horizontal Roll Limit\", GR_XSC_PARAM, 4,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Horizontal Roll Limit\", 0, 1, 'i', \"NONE\"},\n {\"Minimum Horizontal Roll (degrees)\", -180.0, 180.0, 'f', \"NONE\"},\n {\"Maximum Horizontal Roll (degrees)\", -180.0, 180.0, 'f', \"NONE\"},\n }\n },\n {COMMAND(xsc_filter_el), \"XSC Elevation Limit\", GR_XSC_PARAM, 4,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Elevation Limit\", 0, 1, 'i', \"NONE\"},\n {\"Minimum Elevation (degrees)\", -90.0, 90.0, 'f', \"NONE\"},\n {\"Maximum Elevation (degrees)\", -90.0, 90.0, 'f', \"NONE\"},\n }\n },\n {COMMAND(xsc_filter_matching), \"XSC Matching Filter\", GR_XSC_PARAM, 4,\n {\n {\"Which camera (0, 1, 2=both)\", 0, 2, 'i', \"NONE\"},\n {\"Pointing Error threshold (arc seconds)\", 0.01, 120, 'f', \"NONE\"},\n {\"Pixel Error threshold (pixels)\", 0.01, 20, 'f', \"NONE\"},\n {\"Minimum stars matched\", 4, 30, 'i', \"NONE\"},\n }\n }\n};\n\n/* validate parameters of an mcom -- called by spidercmd before tranmitting a\n * command and by pcm after decoding one. Inputs:\n *\n * cmd: command number\n * [irs]values: mcp-style parsed parameters\n * buflen size of the err_buffer\n * err_buffer a place to write the error string\n *\n * Return value:\n *\n * 0: if parameters are okay; err_buffer ignored.\n * !0: if parameters are not okay. In this case a descriptive error message\n * should be written to err_buffer.\n */\nint mcom_validate(enum multiCommand cmd, const int *ivalues,\n const double *rvalues, char svalues[][CMD_STRING_LEN], size_t buflen,\n char *err_buffer)\n{\n return 0; /* no checks -- everything passes */\n}\n" }, { "alpha_fraction": 0.696601927280426, "alphanum_fraction": 0.7111650705337524, "avg_line_length": 18.619047164916992, "blob_id": "4cac62cda4d6938d165aa8896c566a27e20f3448", "content_id": "e364e9d92dec8a3a7da96673192cd8731db8a97f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 413, "license_type": "no_license", "max_line_length": 73, "num_lines": 21, "path": "/stars/code/tools/math.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef TOOLS__MATH_H\n#define TOOLS__MATH_H\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\n#if 0 // Commenting out invalid overload\n#ifdef _MSC_VER\nint round(double value);\n#endif \n#endif // 0\n\n\n#endif\n" }, { "alpha_fraction": 0.586306095123291, "alphanum_fraction": 0.5966628193855286, "avg_line_length": 23.814285278320312, "blob_id": "add449b9719f838e560778a996a14a69a9cac1a7", "content_id": "99e7307d02cd407677aeb44218f4f8c9c7078307", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1739, "license_type": "no_license", "max_line_length": 73, "num_lines": 70, "path": "/stars/code/shared/image/status.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"status.h\"\n#include \"raw.h\"\n#include \"../../logging/logger.h\"\n\nusing namespace Shared::Image;\n\nStatus::Status()\n{\n counter_stars = -1;\n from_camera = false;\n abort_counter = 0;\n num_exposures = 0;\n counter_fcp = -1;\n horizontal_known = false;\n lat = 0.0;\n lst = 0.0;\n filename = \"\";\n stage = empty;\n reason_for_being_done = no_reason;\n width = 64;\n height = 64;\n depth = 64;\n}\n\nStatus& Status::operator=(const Status &rhs)\n{\n if (this != &rhs) {\n counter_stars = rhs.counter_stars;\n from_camera = rhs.from_camera;\n abort_counter = rhs.abort_counter;\n num_exposures = rhs.num_exposures;\n counter_fcp = rhs.counter_fcp;\n horizontal_known = rhs.horizontal_known;\n lat = rhs.lat;\n lst = rhs.lst;\n filename = rhs.filename;\n stage = rhs.stage;\n reason_for_being_done = rhs.reason_for_being_done;\n age = rhs.age;\n width = rhs.width;\n height = rhs.height;\n depth = rhs.depth;\n }\n return *this;\n}\n\nStatus& Status::operator=(const Raw &rhs)\n{\n counter_stars = rhs.counter_stars;\n from_camera = rhs.from_camera;\n num_exposures = rhs.num_exposures;\n counter_fcp = rhs.counter_fcp;\n horizontal_known = rhs.filters.horizontal_known();\n if (horizontal_known) {\n lat = rhs.filters.lat();\n lst = rhs.filters.lst();\n }\n filename = rhs.filename;\n age = rhs.age;\n width = rhs.width;\n height = rhs.height;\n depth = rhs.depth;\n return *this;\n}\n\n" }, { "alpha_fraction": 0.6254355311393738, "alphanum_fraction": 0.6411150097846985, "avg_line_length": 25.090909957885742, "blob_id": "bdc3cb503bd0082c539f516e4624f49cd165c11a", "content_id": "14341b44cd693b17ec73a149f6706f9bd55e25f3", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Shell", "length_bytes": 574, "license_type": "no_license", "max_line_length": 60, "num_lines": 22, "path": "/owl/configure", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#!/bin/sh\necho This script ignores all parameters.\necho To change where owl will be installed, edit owl.pro!\necho\nif [ `uname` = \"Darwin\" ]; then\n opt=\"-spec macx-g++\"\nelse\n opt=\"\"\nfi\nif [ \"x`which qmake-qt4 2>/dev/null`\" != \"x\" ]; then\n echo \"executing \\\"qmake-qt4 $opt\\\"\"\n qmake-qt4 $opt || exit 1\nelif [ \"x`which qmake 2>/dev/null`\" != \"x\" ]; then\n echo \"executing: \\\"qmake $opt\\\"\"\n qmake $opt || exit 1\nelse\n echo \"ERROR: Can't find qmake-qt4 nor qmake in your path!\"\n exit 1\nfi\necho \necho Great! That seemed to work.\necho Now run \\\"make\\\" and \\\"make install\\\"!\n" }, { "alpha_fraction": 0.6155844330787659, "alphanum_fraction": 0.6207792162895203, "avg_line_length": 16.5, "blob_id": "69ccf056155ab113a0658abb4a1f0fa04f6e1a71", "content_id": "d0c7bc59a7df5600bdc2caf50bdcff7884c65198", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 771, "license_type": "no_license", "max_line_length": 73, "num_lines": 44, "path": "/stars/code/solving/attitude.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__ATTITUDE_H\n#define SOLVING__ATTITUDE_H\n\nnamespace Solving\n{\n\nstruct SolutionAttitude\n{\n bool valid;\n union {\n double ra;\n double az;\n };\n union {\n double dec;\n double el;\n };\n double roll;\n union {\n double sigma_ra;\n double sigma_az;\n };\n union {\n double sigma_dec;\n double sigma_el;\n };\n double sigma_roll;\n double sigma_pointing;\n double fit_error;\n double iplatescale;\n};\n\nvoid clear_solution_attitude(SolutionAttitude& attitude);\n\n}\n\n#endif\n" }, { "alpha_fraction": 0.6430529952049255, "alphanum_fraction": 0.6549360156059265, "avg_line_length": 25.349397659301758, "blob_id": "a8a16a3273a765675b3a4faeac0896713ceae2da", "content_id": "b9fbaa1d699fe289d8120cc4b74c1fc8a61aaf79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2189, "license_type": "no_license", "max_line_length": 85, "num_lines": 83, "path": "/stars/code/displaying/lens.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"lens.h\"\n#if defined(_MSC_VER)\n #include <windows.h>\n#endif\n#include <cstdio>\n#include <string>\n#include <math.h>\n#include <boost/format.hpp>\n#include \"GL/gl.h\"\n#include \"GL/glu.h\"\n#include \"../shared/lens/requests.h\"\n#include \"../shared/lens/results.h\"\n\nusing namespace Displaying;\nusing std::string;\n#define shared_fcp_requests (*(Shared::Lens::fcp_requests_main_to_camera.w))\n#define shared_fcp_results (*(Shared::Lens::fcp_results_camera_to_main.r))\n#define shared_stars_requests (*(Shared::Lens::stars_requests_main_to_camera.w))\n#define shared_stars_results (*(Shared::Lens::stars_results_camera_to_main.r))\n\nLens::Lens()\n{\n string title;\n title = \"Focus\";\n focus.init(title);\n title = \"Apert\";\n aperture.init(title);\n Color measured_color = Color(0.5, 0.5, 1.0, 1.0);\n focus.color = measured_color;\n aperture.color = measured_color;\n\n change_size(140, 2*padding+3*text_height);\n}\n\nvoid Lens::update()\n{\n if (shared_fcp_results.device_found) {\n set_title((boost::format(\"Lens (%s)\")%shared_fcp_results.device_name).str());\n } else {\n set_title(string(\"Lens\"));\n }\n\n focus.set_value(shared_fcp_results.focus_value, 0);\n focus.known = false;\n aperture.set_value(shared_fcp_results.aperture_value, 0);\n aperture.known = false;\n\n if (shared_fcp_results.is_focus_valid(shared_fcp_requests) &&\n shared_stars_results.is_focus_valid(shared_stars_requests))\n {\n focus.known = true;\n }\n if (shared_fcp_results.is_aperture_valid(shared_fcp_requests) &&\n shared_stars_results.is_aperture_valid(shared_stars_requests))\n {\n aperture.known = true;\n }\n}\n\nvoid Lens::draw(Position &position)\n{\n update();\n\n glColor3f(1.0, 1.0, 1.0);\n begin_draw(position);\n\n draw_border();\n draw_title();\n\n Position pos = {padding+padding, height() - padding - text_height};\n draw_value(focus, pos);\n pos.y -= text_height;\n draw_value(aperture, pos);\n\n\n end_draw();\n}\n\n" }, { "alpha_fraction": 0.6727727055549622, "alphanum_fraction": 0.6808215379714966, "avg_line_length": 40.895347595214844, "blob_id": "363ac40cef3dece27bd236260898b07a879c6083", "content_id": "1fb7dd8a24b83b6f0bbbd4b1eb6cb218e3ecd52c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3603, "license_type": "no_license", "max_line_length": 109, "num_lines": 86, "path": "/blast_comms/include/comms_netbuf.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/**\n * @file comms_netbuf.h\n *\n * @date Jan 16, 2011\n * @author seth\n * \n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2010-2015 Seth Hillbrand\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n\n#ifndef INCLUDE_COMMS_NETBUF_H\n#define INCLUDE_COMMS_NETBUF_H\n#include <stddef.h>\n#include <stdint.h>\n#include <stdbool.h>\n#include <pthread.h>\n\nstruct netbuf_t {\n size_t elem_size; // The size of each element.\n size_t min_cap; // The smallest capacity of the buffer\n size_t max_cap; // The maximum capacity of the buffer\n\n char* buffer; // The internal buffer, holding the enqueued elements.\n char* bufend; // One past the end of the buffer, so that the actual\n // elements are stored in in interval [buffer, bufend).\n char* begin; // Always points to the sentinel element. `begin + elem_size`\n // points to the left-most element in the pipe.\n char* end; // Always points past the right-most element in the pipe.\n\n // The number of producers/consumers in the pipe.\n size_t producer_refcount, // Guarded by begin_lock.\n consumer_refcount; // Guarded by end_lock.\n\n pthread_mutex_t begin_lock;\n pthread_mutex_t end_lock;\n\n pthread_cond_t just_pushed; // Signaled immediately after a push.\n pthread_cond_t just_popped; // Signaled immediately after a pop.\n};\n\ntypedef struct netbuf_t netbuf_t;\n\n// Returns the number of bytes currently in use in the buffer, excluding the\n// sentinel element.\nstatic inline size_t netbuf_bytes_available(netbuf_t *m_buffer)\n{\n return ((m_buffer->begin >= m_buffer->end)\n ? ((m_buffer->end - m_buffer->buffer) + (m_buffer->bufend - m_buffer->begin))\n : (m_buffer->end - m_buffer->begin))\n - m_buffer->elem_size;\n}\n\nnetbuf_t* __attribute__((__malloc__, warn_unused_result)) netbuf_new(size_t elem_size, size_t limit);\nnetbuf_t* __attribute__((nonnull, warn_unused_result)) netbuf_producer_new(netbuf_t*);\nnetbuf_t* __attribute__((nonnull, warn_unused_result)) netbuf_consumer_new(netbuf_t*);\nvoid netbuf_free(netbuf_t*);\nvoid netbuf_producer_free(netbuf_t*);\nvoid netbuf_consumer_free(netbuf_t*);\nvoid netbuf_reinit(netbuf_t *m_buf);\n\nsize_t __attribute__((nonnull, warn_unused_result)) netbuf_write(netbuf_t*, const void* elems, size_t count);\nsize_t __attribute__((nonnull, warn_unused_result)) netbuf_read(netbuf_t*, void* target, size_t count);\nsize_t __attribute__((nonnull, warn_unused_result)) netbuf_read_wait(netbuf_t*, void* target, size_t count);\nsize_t __attribute__((nonnull, warn_unused_result)) netbuf_peek(netbuf_t*, void**);\nsize_t __attribute__((nonnull, warn_unused_result)) netbuf_peek_noalloc(netbuf_t*, void*, size_t);\nvoid __attribute__((nonnull)) netbuf_reserve(netbuf_t*, size_t count);\nvoid __attribute__((nonnull)) netbuf_eat(netbuf_t *m_buf, size_t m_len);\n\n#endif /* BLAST_NET_BUFFER_H_ */\n" }, { "alpha_fraction": 0.5855130553245544, "alphanum_fraction": 0.6743317246437073, "avg_line_length": 36.815216064453125, "blob_id": "9a820b2ab12980191da78813a056b060806f0841", "content_id": "fb6f998a8d2bddfc2ad77198f6cad059b3866c8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3479, "license_type": "no_license", "max_line_length": 76, "num_lines": 92, "path": "/minicp_config/command_list.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* command_list.h: Spider command specification file definitions\n *\n * This software is copyright (C) 2002-20010 University of Toronto\n *\n * This file is part of the BLAST flight code licensed under the GNU\n * General Public License.\n *\n * You should have received a copy of the GNU General Public License\n * along with this software; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#ifndef COMMAND_LIST_H\n#define COMMAND_LIST_H\n\n#include \"netcmd.h\" /* common parts of command defintions moved here */\n#include <sys/types.h>\n\n#define N_SCOMMANDS 2 /* total number of single word cmds */\n#define N_MCOMMANDS 13 /* total number of multiword commands */\n#define DATA_Q_SIZE (2 * MAX_N_PARAMS) /* maximum size of the data queue */\n\n#define MAX_15BIT (32767.)\n#define MAX_30BIT (1073741823.)\n\n//#define N_GROUPS 24\n#define N_GROUPS 4\n\n//\"not yet used\" groups leftover from BLAST, can be changed\n#define GR_AZEL 0x00000001 \n//#define GR_BAL 0x00000002 //not yet used\n//#define GR_COOL 0x00000004 //not yet used\n//#define GR_TRIM 0x00000008 //not yet used\n//#define GR_ELECT 0x00000010 //not yet used\n//#define GR_BIAS 0x00000020\n#define GR_BIAS 0x00000002\n//#define GR_VETO 0x00000040 //not yet used\n//#define GR_ACT 0x00000080 //not yet used\n//#define GR_CALLAMP 0x00000100 //not yet used\n//#define GR_GAIN 0x00000200 //not yet used\n//#define GR_FOCUS 0x00000400 //not yet used\n//#define GR_CRYO_HEAT 0x00000800 //not yet used\n//#define GR_POWER 0x00001000 //not yet used\n#define GR_POWER 0x00000004 \n//#define GR_LOCK 0x00002000 //not yet used\n//#define GR_CRYO_CONTROL 0x00004000 //not yet used\n//#define GR_TELEM 0x00008000 //not yet used\n//#define GR_SC_MISC 0x00010000 //not yet used\n//#define GR_FREE1 0x00020000 //not yet used\n//#define GR_STAGE 0x00040000 //not yet used\n//#define GR_SC_MODE 0x00080000 //not yet used\n//#define GR_FREE2 0x00100000 //not yet used\n#define GR_MISC 0x00000008\n//#define GR_SC_PARAM 0x00400000 //not yet used\n//#define GR_FREE3 0x00800000 //not yet used\n//reserved for CONFIRM 0x80000000\n\nextern const char *command_list_serial;\nextern const char *GroupNames[N_GROUPS];\n\n/* singleCommand enumeration. The command list here does NOT have to be in\n * order relative to the command definitions in command_list.c */\nenum singleCommand {\n az_el_disable,\n xyzzy\n};\n\n/* multiCommand enumeration. The command list here does NOT have to be in\n * order relative to the command definitions in command_list.c */\nenum multiCommand {\n dac1_ampl, dac1_phase, bias1_step, phase1_step,\n dac2_ampl, dac2_phase, bias2_step, phase2_step,\n az_el_raster, az_el_set,\t\taz_el_goto, reset_adc, \n plugh\n};\n\nextern struct scom scommands[N_SCOMMANDS];\n\n/* parameter type:\n * i : parameter is 15 bit unnormalised integer\n * f : parameter is 15 bit renormalised floating point\n * l : parameter is 30 bit renormalised floating point\n */\nextern struct mcom mcommands[N_MCOMMANDS];\n\n/* validator function for mcommands */\nextern int mcom_validate(enum multiCommand cmd, const int *ivalues,\n const double *rvalues, char svalues[][CMD_STRING_LEN], size_t buflen,\n char *err_buffer);\n\n#endif /* COMMAND_LIST_H */\n" }, { "alpha_fraction": 0.7038137912750244, "alphanum_fraction": 0.7062902450561523, "avg_line_length": 33.81034469604492, "blob_id": "5eca1e8f35033fb085cfd45be518d45430c0bdf9", "content_id": "27a1b23957e7894752eacc613a7002373e9e3437", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 4038, "license_type": "no_license", "max_line_length": 141, "num_lines": 116, "path": "/mole/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "# Helper function to add preprocesor definition of FILE_BASENAME\n# to pass the filename without directory path for debugging use.\n#\n# Example:\n#\n# define_file_basename_for_sources(my_target)\n#\n# Will add -DFILE_BASENAME=\"filename\" for each source file depended on\n# by my_target, where filename is the name of the file.\n#\nfunction(define_file_basename_for_sources targetname)\n get_target_property(source_files \"${targetname}\" SOURCES)\n foreach(sourcefile ${source_files})\n # Get source file's current list of compile definitions.\n get_property(defs SOURCE \"${sourcefile}\"\n PROPERTY COMPILE_DEFINITIONS)\n # Add the FILE_BASENAME=filename compile definition to the list.\n get_filename_component(basename \"${sourcefile}\" NAME)\n list(APPEND defs \"__FILENAME__=\\\"${basename}\\\"\")\n # Set the updated compile definitions on the source file.\n set_property(\n SOURCE \"${sourcefile}\"\n PROPERTY COMPILE_DEFINITIONS ${defs})\n endforeach()\nendfunction()\n\nproject (mole)\n\nfind_package(OpenSSL REQUIRED)\n\ncmake_minimum_required (VERSION 2.8.8)\n\noption(USE_CLANG \"build mole using clang\" OFF)\n\nif (USE_CLANG)\n SET (CMAKE_C_COMPILER \"/usr/bin/clang\")\n SET (CMAKE_CXX_COMPILER \"/usr/bin/clang++\")\nendif(USE_CLANG)\n\nSET (CMAKE_C_FLAGS \"-Wall -std=gnu99\")\nSET (CMAKE_C_FLAGS_DEBUG \"-g\")\nSET (CMAKE_C_FLAGS_MINSIZEREL \"-Os -DNDEBUG\")\nSET (CMAKE_C_FLAGS_RELEASE \"-O3 -DNDEBUG\")\nSET (CMAKE_C_FLAGS_RELWITHDEBINFO \"-O2 -g\")\n\nSET (CMAKE_CXX_FLAGS \"-Wall\")\nSET (CMAKE_CXX_FLAGS_DEBUG \"-g\")\nSET (CMAKE_CXX_FLAGS_MINSIZEREL \"-Os -DNDEBUG\")\nSET (CMAKE_CXX_FLAGS_RELEASE \"-O3 -DNDEBUG\")\nSET (CMAKE_CXX_FLAGS_RELWITHDEBINFO \"-O2 -g\") \n\n# Set global definitions\nadd_definitions(-D_GNU_SOURCE)\n\n# Find external libs\nfind_package(PkgConfig)\n\n# Find Threading lib\nfind_package (Threads)\n\n# Find ExternalProject module\ninclude (ExternalProject)\n\n# Find getdata \npkg_check_modules(PC_GD QUIET getdata)\n\nfind_path(GD_INCLUDE_DIR NAMES getdata.h\n HINTS ${PC_GD_INCLUDEDIR} ${PC_GD_INCLUDE_DIRS} REQUIRED)\nfind_library(GD_LIBRARY NAMES getdata\n HINTS ${PC_GD_LIBDIR} ${PC_GD_LIBRARY_DIRS} REQUIRED)\nIF(NOT GD_INCLUDE_DIR)\n MESSAGE(FATAL_ERROR \"Did not find getdata.h. Is libgetdata-dev installed?\")\nENDIF()\nIF(NOT GD_LIBRARY) \n MESSAGE(FATAL_ERROR \"Did not find libgetdata. Is libgetdata4 installed?\")\nENDIF()\ninclude_directories(${GD_INCLUDE_DIR})\n\nset(LIBLINKLIST_DIR \"${PROJECT_SOURCE_DIR}/../liblinklist\")\n\n# add machine directory for OSX builds (needs endian.h)\ninclude_directories (\"/usr/include/machine\")\n\ninclude_directories (\n \"${LIBLINKLIST_DIR}\"\n \"${PROJECT_SOURCE_DIR}\"\n )\n\n# add common linklist objects\nadd_subdirectory(${LIBLINKLIST_DIR} \"${PROJECT_BINARY_DIR}/liblinklist\")\nadd_library (liblinklist OBJECT ${LL_SOURCES} ${LL_HEADERS})\ndefine_file_basename_for_sources(liblinklist)\n\n\n# add common objects\nadd_executable (mole \n $<TARGET_OBJECTS:liblinklist>\n ${PROJECT_SOURCE_DIR}/mole.c\n ) \n\ndefine_file_basename_for_sources(mole)\n\ntarget_link_libraries(mole\n ${CMAKE_THREAD_LIBS_INIT} \n ssl crypto\n m)\n\ninstall(TARGETS mole DESTINATION bin)\ninstall(DIRECTORY DESTINATION \"/data/rawdir\"\n DIRECTORY_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_WRITE GROUP_EXECUTE WORLD_READ WORLD_WRITE WORLD_EXECUTE)\ninstall(DIRECTORY DESTINATION \"/data/mole\"\n DIRECTORY_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_WRITE GROUP_EXECUTE WORLD_READ WORLD_WRITE WORLD_EXECUTE)\ninstall(DIRECTORY DESTINATION \"/data/etc\"\n DIRECTORY_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_WRITE GROUP_EXECUTE WORLD_READ WORLD_WRITE WORLD_EXECUTE)\ninstall(DIRECTORY DESTINATION \"/data/etc/downloaded_files\"\n DIRECTORY_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_WRITE GROUP_EXECUTE WORLD_READ WORLD_WRITE WORLD_EXECUTE)\n" }, { "alpha_fraction": 0.548204779624939, "alphanum_fraction": 0.5884308218955994, "avg_line_length": 27.63809585571289, "blob_id": "d89d537d0d6ded81680dd750b58ea29d9c6ed72e", "content_id": "b73b245a81ba674907b3e71a4c1aff3bc290a50a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3009, "license_type": "no_license", "max_line_length": 100, "num_lines": 105, "path": "/stars/code/displaying/name.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#define NOMINMAX\n#include \"name.h\"\n#include \"../tools/math.h\"\n#include \"../shared/network/packets.h\"\n#include \"../shared/general/network_reset.h\"\n#include \"../tools/quick_cout.h\"\n\nusing namespace Displaying;\n\n#define shared_packets_from_fc1 (*(Shared::Network::packets_from_fc1.r))\n#define shared_packets_from_fc2 (*(Shared::Network::packets_from_fc2.r))\n#define shared_network_reset_status (*(Shared::General::network_reset_status_for_main.r))\n\nName::Name()\n{\n change_size(140, 2*padding+1*text_height);\n timer.start();\n}\n\nvoid Name::draw_packets()\n{\n Position pos = {width()-padding-55, height() - padding};\n double dim_rate = 2.0;\n\n Color gray(0.8, 0.8, 0.8, 1.0);\n Color green(0.5, 1.0, 0.5, 1.0);\n\n {\n double scale = std::max(1.0 - shared_packets_from_fc1.time_since_sent.time()*dim_rate, 0.0);\n set_color(gray*scale, true);\n draw_text(\"s\", pos);\n pos.x += 11;\n scale = std::max(1.0 - shared_packets_from_fc1.time_since_received.time()*dim_rate, 0.0);\n if (shared_packets_from_fc1.in_charge) {\n set_color(green*scale, true);\n draw_text(\"R\", pos);\n } else {\n set_color(gray*scale, true);\n draw_text(\"r\", pos);\n }\n }\n\n pos.x += 20;\n {\n double scale = std::max(1.0 - shared_packets_from_fc2.time_since_sent.time()*dim_rate, 0.0);\n set_color(gray*scale, true);\n draw_text(\"s\", pos);\n pos.x += 11;\n scale = std::max(1.0 - shared_packets_from_fc2.time_since_received.time()*dim_rate, 0.0);\n if (shared_packets_from_fc2.in_charge) {\n set_color(green*scale, true);\n draw_text(\"R\", pos);\n } else {\n set_color(gray*scale, true);\n draw_text(\"r\", pos);\n }\n }\n}\n\nvoid Name::draw_network_resetting()\n{\n double center_x = 105.0;\n double center_y = 15.0;\n double angle = timer.time()*2*M_PI*1.5;\n double phase = M_PI/2.0;\n double x1_offset = cos(angle)*20.0;\n double y1_offset = sin(angle)*3.0;\n double x2_offset = cos(angle+phase)*20.0;\n double y2_offset = sin(angle+phase)*5.0;\n\n if (timer.time() > 10000.0) {\n timer.start();\n }\n\n glPushMatrix();\n glPointSize(4.0f);\n glBegin(GL_POINTS);\n glColor4f(1.0, 0.5, 0.5, 1.0);\n glVertex2d((GLfloat) (center_x+x1_offset), (GLfloat) (center_y+y1_offset));\n glColor4f(0.0, 1.0, 0.5, 1.0);\n glVertex2d((GLfloat) (center_x+x2_offset), (GLfloat) (center_y+y2_offset));\n glEnd();\n glPointSize(1.0f);\n glPopMatrix();\n}\n\nvoid Name::draw(Position &position)\n{\n update_size();\n begin_draw(position);\n draw_border();\n draw_title();\n if (shared_network_reset_status.resetting) {\n draw_network_resetting();\n } else {\n draw_packets();\n }\n end_draw();\n}\n\n" }, { "alpha_fraction": 0.6021730303764343, "alphanum_fraction": 0.6109486222267151, "avg_line_length": 23.40816307067871, "blob_id": "69ce6057bfa896114ef933d779598670127e46c0", "content_id": "6ab51faf24852b3e0eedbad3f27b7bbabdc9a7e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2394, "license_type": "no_license", "max_line_length": 106, "num_lines": 98, "path": "/stars/code/shared/autofocus/datapoints.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"datapoints.h\"\n#include <limits>\n#include \"../../logging/logger.h\"\n\nusing namespace Shared::Autofocus;\n\nCurve::Curve()\n{\n type = metric_brightest_blob_flux;\n points.clear();\n}\n\nbool Curve::get_peak(double& focus, double& value)\n{\n\tif (points.size() < 5) {\n\t\tfocus = 0.0;\n\t\tvalue = 0.0;\n\t\treturn false;\n\t}\n\n\tunsigned int best_index = 0;\n\tdouble best_focus = points[0].focus;\n\tdouble best_value = points[0].value;\n\tfor (unsigned int i = 0; i<points.size(); i++) {\n\t\tif (points[i].value > best_value)\n\t\t{\n\t\t\tbest_value = points[i].value;\n\t\t\tbest_focus = points[i].focus;\n\t\t\tbest_index = i;\n\t\t}\n\t}\n\n\tfocus = best_focus;\n\tvalue = best_value;\n\treturn true;\n\n\tif (false) {\n\t\t// Decided that it was better to end up at something that is a max rather than at the last focus tried\n\t // check that the point is not on the edge in order to check that it's a local maximum\n \tif (best_index > 0 && best_index < points.size() - 1) {\n \t\tfocus = best_focus;\n\t \tvalue = best_value;\n\t \treturn true;\n \t}\n\t focus = 0.0;\n\t value = 0.0;\n\t return false;\n\t}\n}\n\nvoid Curve::log(Logging::Logger& logger)\n{\n switch (type) {\n case metric_brightest_blob_flux:\n logger.log(\"autofocus: metric for brightest blob\");\n break;\n case metric_star_flux:\n logger.log(format(\"autofocus: metric for star %i\") % star_id);\n break;\n case metric_sobel:\n logger.log(\"autofocus: sobel metric\");\n break;\n }\n for (unsigned int i=0; i<points.size(); i++) {\n logger.log(format(\"autofocus: datapoint: focus %f value %f\") % points[i].focus % points[i].value);\n }\n}\n\nCurve& Curve::operator=(const Curve &rhs)\n{\n if (this != &rhs) {\n type = rhs.type;\n points = rhs.points;\n age_since_last_datapoint_added = rhs.age_since_last_datapoint_added;\n }\n return *this;\n}\n\nDatapoints::Datapoints()\n{\n curves.clear();\n last_fully_solved_counter_stars = -1;\n}\n\nDatapoints& Datapoints::operator=(const Datapoints &rhs)\n{\n if (this != &rhs) {\n curves = rhs.curves;\n last_fully_solved_counter_stars = rhs.last_fully_solved_counter_stars;\n }\n return *this;\n}\n\n" }, { "alpha_fraction": 0.5377996563911438, "alphanum_fraction": 0.5558170080184937, "avg_line_length": 30.990589141845703, "blob_id": "7504522fdfd800fdcba7cc78ee7487d206b2422f", "content_id": "05cd89591e96abd66977b81eb6ea59c25dba1e91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13598, "license_type": "no_license", "max_line_length": 99, "num_lines": 425, "path": "/starcam/testmain.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <fstream>\n#include <iostream>\n#include <cstdlib>\n#include <string>\n#include <unistd.h>\n#include <fcntl.h>\n#include <qapplication.h>\n#include <pthread.h>\n#include \"mycam.h\"\n#include \"blobimage.h\"\n#include \"sbigudrv.h\"\n#include \"csbigimg.h\"\n#include \"bloblist.h\"\n#include \"clensadapter.h\"\n#include \"frameblob.h\"\n#include \"pyramid.h\"\n#include \"imageviewer.h\"\n\n#define TEST_MODE 3\n//TEST_MODES: 1 = noise calculation, 2 = adapter/focus test, 3 = blob finder test / box drawer\n// 4 = use \"testing\" main function (takes picture, processes, etc.)\n// 5 = FIFO test\n\nusing namespace std;\n\n#if TEST_MODE == 1 || TEST_MODE == 2 || TEST_MODE == 3\n///////////////////////////////////////////////////////////////////////////////////////////////////\n// Old test program //\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n#if TEST_MODE == 3\n//function for calling image viewer in a thread\nvoid* viewerExec(void* arg)\n{\n\tQApplication* a = (QApplication*)arg;\n\tstatic int res = a->exec();\n\treturn (void *)&res;\n}\n#endif\n\nint main(int argc, char *argv[])\n{\n\tifstream sbigfile;\n#if TEST_MODE == 2\n\tMyCam cam;\n\tLENS_ERROR err = LE_NO_ERROR;\n\tPAR_ERROR cerr = CE_NO_ERROR;\n\tCLensAdapter* lens = cam.getLensAdapter();\n\tstring lens_return_str;\n#elif TEST_MODE == 3\n\tImageViewer *iv;\n\tQApplication a(argc, argv);\n\tint firstTime = 1;\n\tpthread_t app_thread;\n\tbloblist *blobs;\n#endif\n\tcout << \"Initializing BlobImage object (loading catalog takes a while)...\" << endl;\n\tBlobImage img;\n\tframeblob* fblob = img.getFrameBlob();\n\t\t\n\tdo { // allow break out\n\t\t\n#if TEST_MODE == 1\n\t\tstring start_str = \"/data/rawdir/\";\n\t\tstring end_str = \".sbig\";\n\t\tstring times[] = {\"0.04\", \"0.08\", \"0.15\", \"0.5\", \"0.75\", \"1\", \"2\", \"4\", \"8\", \n\t\t\t\"15\", \"30\", \"60\"};\n\t\tint num_times = 12;\n\t\tcout << \"time\\tmean\\tsigma2\" << endl;\n\t\tfor (int i=0; i<num_times; i++)\n\t\t{\n\t\t\tstring filename = start_str + times[i] + end_str;\n\t\t\tif (img.OpenImage(filename.c_str()) != SBFE_NO_ERROR)\n\t\t\t{\n\t\t\t\tcout << \"An error occured while opening the file: \" << times[i] << end_str << endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcount_lock\n\t\t\tfblob->calc_stddev();\n\t\t\tcout << times[i] << \"\\t\" << fblob->get_mapmean() << \"\\t\" << fblob->get_stddev() << endl;\n\t\t}\n\t\t\n#elif TEST_MODE == 2\n \t\tcout << \"Opening Camera Driver...\" << endl;\n\t\tif ((cerr = cam.OpenDriver()) != CE_NO_ERROR)\n\t\t\tbreak;\n\t\tcout << \"Opening Camera Device...\" << endl;\n\t\tif ((cerr = cam.OpenUSBDevice(0)) != CE_NO_ERROR)\n\t\t\tbreak;\n\t\tcam.SetExposureTime(0.1);\n\t\tcout << \"Establishing a Link to the USB Camera...(4 tries)\" << endl;\n\t\tfor (int i=0; i<4; i++) {\n\t\t\tcout << \"...attempt \" << i + 1 << endl;\n\t\t\tif ((cerr = cam.EstablishLink()) == CE_NO_ERROR) break;\n\t\t}\n\t\tif (cerr != CE_NO_ERROR) break;\n\n\t\tint position = 0;\n// \t\tcout << \"Opening a connection to the lens adapter...\" << endl;\n// \t\tif ((err = lens->openConnection(\"/dev/ttyACM0\")) != LE_NO_ERROR)\n// \t\t\tbreak;\n// \t\t\n// \t\tcout << \"Finding focal range...\" << endl;\n// \t\tif ((err = lens->findFocalRange()) != LE_NO_ERROR) \n// \t\t\tbreak;\n// \t\tposition = lens->getFocalRange();\n// \t\tcout << \"...Focal Range is: \" << position << endl;\n\t\t\n// \t\tint remaining;\n// \t\tcout << \"Testing forced move...\" << endl;\n// \t\tlens->preciseMove(-1500, remaining, 1);\n// \t\tcout << \"...after move of -1500 there are \" << remaining << \" counts left\" << endl;\n// \t\tlens->preciseMove(-1000, remaining, 1);\n// \t\tcout << \"...after move of -1000 there are \" << remaining << \" counts left\" << endl;\n// \t\t\n// \t\treturn 0;\n// \t\t\n\t\tint numPoints = 20;\n\t\tint step = position/300;\n\t\tint remaining = 0;\n\t\tint flux;\n\t\tlens->setFocusTol(1);\n\t\t\n\t\tcout << \"Finding the brightest blob intensity at \" << numPoints << \" points...\" << endl;\n\t\tcout << \"\\nPosition\\tFlux\" << endl;\n\t\tcout << \"========================\" << endl;\n\t\tfor (int i=0; i<numPoints; i++) {\n\t\t\tif ( (cerr = cam.GrabImage(&img, SBDF_LIGHT_ONLY)) != CE_NO_ERROR )\n\t\t\t\tbreak;\n\t\t\timg.findBlobs();\n\t\t\tif (fblob->get_numblobs())\n\t\t\t\tflux = fblob->getblobs()->getflux(); //flux of brightest blob\n\t\t\telse\n\t\t\t\tflux = -1;\n\t\t\tcout << position << \"\\t\\t\" << flux << endl;\n\t\t\t\n\t\t\tlens->preciseMove(-step+remaining, remaining);\n\t\t\tposition -= step + remaining;\n\t\t}\n\t\tif (cerr != CE_NO_ERROR) break;\n\t\t\n#elif TEST_MODE == 3\n\t\tstring path = \"/data/rawdir/03-01/\";\n/*\t\tstring names[] = {\"1153prog.sbig\", \"1140ops.sbig\", \"1143prog.sbig\", \"1144prog.sbig\",\n\t\t\t\"1150prog.sbig\", \"1155prog.sbig\", \"1159prog.sbig\", \"1159bprog.sbig\", \"1200prog.sbig\",\n\t\t\t\"1200bprog.sbig\", \"1211ops.sbig\", \"1213prog.sbig\", \"1213bprog.sbig\", \"1214prog.sbig\",\n\t\t\t\"1214bprog.sbig\", \"1215prog.sbig\", \"1216prog.sbig\", \"1217prog.sbig\", \"1218prog.sbig\",\n\t\t\t\"1219prog.sbig\"};\n*/\n\t\tint num_names = 3;\n\t\tstring names[num_names];\n\t\tint read_int=0;\n\t\tsbigfile.open(\"0301b.txt\");\n\t\twhile (sbigfile >> names[read_int]){\n\t\t\t++read_int;\n\t\t}\n\t\tfor (int i=0; i<num_names; i++) {\n\t\t\tstring filename = path + names[i];\n\t\t\tcout << \"\\n\\n\\n\\nOpening the saved image: \" << filename << endl;\n\t\t\tif (img.OpenImage(filename.c_str()) != SBFE_NO_ERROR)\n\t\t\t{\n\t\t\t\tcout << \"An error occured while opening: \" << filename << endl;\n\t\t\t\tbreak;\n\t\t\t}\n/*FIXME\t\n\t\t\t//initialize the image viewer window\n\t\t\tif (firstTime) { //only do this on first loop iteration\n\t\t\t\tfirstTime = 0;\n//\t\t\t\tcout << \"Starting Image viewer application\" << endl;\n \t\t\t\tImageViewer iv(640, 480, img.GetWidth(), img.GetHeight(), 10, 0, \"viewer\");\n\t\t\t\t//FIXMEiv = new ImageViewer(img.GetWidth(), img.GetHeight(), 1000, 0, \"viewer\");\n\t\t\t\ta.setMainWidget(iv);\n\t\t\t\tiv->show();\n\t\t\t\tpthread_create(&app_thread, NULL, &viewerExec, (void*)&a);\n\t\t\t}\n*/\t\t\t\n//\t\t\tcout << \"Finding blobs\" << endl;\n\t\t\timg.findBlobs();\n\t\t\tif(fblob->get_numblobs() > 7) { \n\t\t\t\tcout << \"\\nFound \" << fblob->get_numblobs() << \" blobs, map mean = \"\n\t\t\t\t<< fblob->get_mapmean() << \" sigma = \" << fblob->get_sigma() << endl;\n\t\t\t}\n\t\t\tint num = 1;\n\t\t\tif (fblob->get_numblobs()) {\n\t\t\t\tif(fblob->get_numblobs() > 7) cout <<\"Their locations, flux and snr (x y f s) are \" << endl;\n\t\t\t\tblobs = fblob->getblobs();\n\t\t\t\twhile (blobs != NULL) {\n\t\t\t\t\tdouble x = blobs->getx();\n\t\t\t\t\tdouble y = blobs->gety();\n\t\t\t\t\tdouble f = blobs->getflux();\n\t\t\t\t\tdouble s = blobs->getsnr();\n\t\t\t\t\t//cout << \"\\t\" << x << \" \" << y << \" \" << f << \" \" << s << endl;\n\t\t\t\t\tif (fblob->get_numblobs() > 7) cout << \"\\t\" << x << \" \" << y << endl;\n\t\t\t\t\timg.drawBox(blobs->getx(), blobs->gety(), 40, num, true);\n\t\t\t\t\tblobs = blobs->getnextblob();\n\t\t\t\t\tnum++;\n\t\t\t\t}\n\t\t\t}\n/*FIXME\t\t\t\n\t\t\tiv->load(&img, TRUE);\n*/\n\t\t\t//wait for a bit and observe image\n//\t\t\tsleep(5);\n\t\t\t\n// \t\t\tfilename = path + \"boxes/\" + names[i];\n// \t\t\tcout << \"Saving image with boxes: \" << filename << endl;\n// \t\t\tif ( img.SaveImage(filename.c_str(), SBIF_COMPRESSED) != SBFE_NO_ERROR ) {\n// \t\t\t\tcout << \"error saving altered file\" << endl;\n// \t\t\t\tbreak;\n// \t\t\t}\n\t\t\t\n// \t\t\tcout << \"\\nPerforming Star matching...\" << endl;\n// \t\t\tsolution_t* sol;\n// \t\t\tint nsol = img.matchStars(&sol);\n// \t\t\tcout << \"\\nStar matching found: \" << nsol << \" solutions\";\n// \t\t\tif (nsol > 0) {\n// \t\t\t\tcout << \" with:\" << endl;\n// \t\t\t\tfor (int j=0; j<((nsol<15)?nsol:15); j++) {\n// \t\t\t\t\tcout << \" \" << j << \":\\tn=\" << sol[j].n << \", brightest star has: ra=\" \n// \t\t\t\t\t\t << sol[j].C[0]->ra << \" dec=\" << sol[j].C[0]->dec << \" mag=\" \n// \t\t\t\t\t\t << sol[j].C[0]->mag << endl;\n// \t\t\t\t\tif (nsol > 15 && j == 14)\n// \t\t\t\t\t\tcout << \" *\\tList truncated after this point...\" << endl;\n// \t\t\t\t}\n// \t\t\t}\n// \t\t\telse cout << endl;\n\t\t\t\n \t\t}\n\n\n#endif\n\t} while (0);\n#if TEST_MODE == 2\n\tif ( err != LE_NO_ERROR)\n \t\tcout << \"A Lens Error Occured: \" << lens->getErrorString(err) << endl;\n \tif (cerr != CE_NO_ERROR)\n\t\tcout << \"A Camera Error Occured: \" << cam.GetErrorString(cerr) << endl;\n#endif\n#if TEST_MODE == 3\n\tpthread_join(app_thread, NULL);\n#endif\n\n\treturn EXIT_SUCCESS;\n}\n#endif //if TEST_MODE == 1 || == 2 || == 3\n\n\n\n\n\n#if TEST_MODE == 4\n///////////////////////////////////////////////////////////////////////////////////////////////////\n// Old main program (for testing) //\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n#define OPENING_METHOD 3\n\nint main(int argc, char *argv[])\n{\n#if OPENING_METHOD == 1\n\tcout << \"Creating the MyCam Object on USB and Opening Driver, Device...\" << endl;\n\tMyCam pCam(DEV_USB);\n#else\n\tcout << \"Creating the MyCam Object on USB...\" << endl;\n\tMyCam pCam;\n#endif\n\tBlobImage img;\n\tPAR_ERROR err = CE_NO_ERROR;\n\tSBIG_FILE_ERROR ferr = SBFE_NO_ERROR;\n#if OPENING_METHOD == 3\n\tQueryUSBResults qur;\n#endif\n\tbloblist *blobs;\n\tstring lens_return_str;\n\tCLensAdapter* lens = pCam.getLensAdapter();\n\tframeblob* fblob;\n\n\n\tdo { // allow break out\n\t\t\n//there are three methods being used here to open the camera device; only one is needed\n#if OPENING_METHOD==1\n//original method: only works for a single camera\n\t\tif ( (err = pCam.GetError()) != CE_NO_ERROR )\n\t\t\tbreak;\n\t\t\n#elif OPENING_METHOD==2\n//manual one-at-a-time method. could be used to implement two cameras\n\t\tcout << \"Opening Driver...\" << endl;\n\t\tif ((err = pCam.OpenDriver()) != CE_NO_ERROR)\n\t\t\tbreak;\n\t\tcout << \"Opening Device...\" << endl;\n\t\tif ((err = pCam.OpenUSBDevice(0)) != CE_NO_ERROR)\n\t\t\tbreak;\n\n#elif OPENING_METHOD==3\n//automatic one-at-a-time-method. better way to implement multiple cameras\n\t\tif ((err = pCam.OpenDriver()) != CE_NO_ERROR)\n\t\t\tbreak;\n\t\tcout << \"Querying USB...(4 tries)\" << endl;\n\t\tfor (int i=0; i<4; i++) {\n\t\t\tcout << \"Attempt \" << i+1 << endl;\n\t\t\tif ((err = pCam.QueryUSB(qur)) == CE_NO_ERROR && qur.camerasFound)\n\t\t\t\tbreak;\n\t\t}\n\t\tif (err != CE_NO_ERROR) \n\t\t\tbreak;\n\t\tif (qur.camerasFound) {\n\t\t\tcout << \"There are \" << qur.camerasFound << \" USB Cameras.\" << endl;\n\t\t\tfor (int i=0; i<4; i++) {\n\t\t\t\tif (qur.usbInfo[i].cameraFound) {\n\t\t\t\t\tcout << \"Using Cam \" <<i<< \": Name=\" << qur.usbInfo[i].name \n\t\t\t\t\t\t\t<< \", Serial Number=\" << qur.usbInfo[i].serialNumber << endl;\n\t\t\t\t\tcout << \"Opening the device...\" << endl;\n\t\t\t\t\terr = pCam.OpenUSBDevice(i);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (pCam.GetError() != CE_NO_ERROR) //opening device failed\n\t\t\t\tbreak;\n\t\t} else {\n\t\t\tcout << \"No cameras were found on USB...\" << endl;\n\t\t\terr = CE_CAMERA_NOT_FOUND;\n\t\t\tbreak;\n\t\t}\n#endif\n\n\t\t\t\n//establish a link and do everything else\n\t\tpCam.SetExposureTime(0.1);\n\t\tcout << \"Establishing a Link to the USB Camera...(4 tries)\" << endl;\n\t\tfor (int i=0; i<4; i++) {\n\t\t\tcout << \"Attempt \" << i + 1 << endl;\n\t\t\tif ((err = pCam.EstablishLink()) == CE_NO_ERROR) break;\n\t\t}\n\t\tif (err != CE_NO_ERROR)\n\t\t\tbreak;\n\t\tcout << \"Link Established to Camera Type: \" << pCam.GetCameraTypeString() << endl;\n\n\t\t// Take a full frame image and save compressed\n\t\tcout << \"Taking full-frame light image on USB...\" << endl;\n\t\tif ( (err=pCam.GrabImage(&img, SBDF_LIGHT_ONLY)) != CE_NO_ERROR )\n\t\t\tbreak;\n/*\n\t\t//move the lens focus to test lens adapter interfaceBlobImage\n\t\tcout << \"Opening a connection to the lens adapter...\" << endl;\n\t\tif (lens->openConnection(\"/dev/ttyS0\") != LE_NO_ERROR) {\n\t\tcout << \"Error establishing link to lens adapter\" << endl;\n\t\tbreak;\n\t}\n\t\tcout << \"Finding length of lens focal axis...\" << endl;\n\t\tif (lens->findFocalRange() != LE_NO_ERROR) {\n\t\tcout << \"Error moving lens\" << endl;\n\t\tbreak;\n\t}\n\t\tcout << \" the focal axis is \" << lens->getFocalRange() << \" counts long.\" << endl;\n\t\tint move_by = -400;\n\t\tcout << \"Moving the lens focus by \" << move_by << \" counts...\" << endl;\n\t\tint remaining;\n\t\tif (lens->preciseMove(move_by, remaining) != LE_NO_ERROR) {\n\t\tcout << \"Error moving lens\" << endl;\n\t\tbreak;\n\t}\n\t\tcout << \" there are \" << remaining << \" counts to move (tolerance=1)\" << endl;\n\n\t\t//execute blob finding operations and display results\n\t\tcout << \"Processing the image (blob finding)...\" << endl;\n\t\timg.findBlobs();\n\t\tfblob = img.getFrameBlob();\n\t\tcout << \"\\nFound \" << fblob->get_numblobs() << \" blobs.\" << endl;\n\t\tif (fblob->get_numblobs()) {\n\t\tcout <<\"Their locations (x,y) are \" << endl;\n\t\tblobs = fblob->getblobs();\n\t\twhile (blobs != NULL) {\n\t\tif (blobs->gettype() == 2) //display only extended blobs\n\t\tcout << \"(\" << blobs->getx() << \",\" << blobs->gety() << \")\" << endl;\n\t\tblobs = blobs->getnextblob();\n\t}\n\t}\n\t\tblobs = NULL;*/\n\n\t\timg.AutoBackgroundAndRange(); //needed to view images on computer\n\t\tcout << \"Saving compressed full-frame image...\" << endl;\n\t\tif ( (ferr = img.SaveImage(\"temp.sbig\", SBIF_COMPRESSED)) != SBFE_NO_ERROR )\n\t\t\tbreak;\n\t\t\n// shut down cameras\n\t\tcout << \"Closing Devices...\" << endl;\n\t\tif ( (err = pCam.CloseDevice()) != CE_NO_ERROR )\n\t\t\tbreak;\n\t\tcout << \"Closing Drivers...\" << endl;\n\t\tif ( (err = pCam.CloseDriver()) != CE_NO_ERROR )\n\t\t\tbreak;\t\t\n\t} while (0);\n\tif ( err != CE_NO_ERROR )\n\t\tcout << \"Camera Error: \" << pCam.GetErrorString(err) << endl;\n\telse if ( ferr != SBFE_NO_ERROR )\n\t\tcout << \"File Error: \" << ferr << endl;\n\telse\n\t\tcout << \"SUCCESS\" << endl;\n\treturn EXIT_SUCCESS;\n}\n#endif //if TEST_MODE == 4\n\n#if TEST_MODE == 5\n///////////////////////////////////////////////////////////////////////////////////////////////////\n// FIFO tester\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\nint main(int argc, char *argv[])\n{\n\tFIFOCommunicator fifoc(\"/home/steve/starcam/readfifo\", \"/home/steve/starcam/writefifo\");\n\tif (fifoc.getErrorFlag() == -1) \n\t\tcout << \"An error occured while opening the fifos.\" << endl;\n\telse fifoc.readLoop();\n\tcout << \"Read loop returned...an error has occured\" << endl;\n\treturn 0;\n}\n\n#endif //TEST_MODE == 5\n" }, { "alpha_fraction": 0.6601830720901489, "alphanum_fraction": 0.6653317809104919, "avg_line_length": 20.580245971679688, "blob_id": "5c610f852a9ce4e59ec7d17aecb5ebcee63322c7", "content_id": "03e046eccc4be9cab27c3b94d93725cf5c34a140", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1749, "license_type": "no_license", "max_line_length": 73, "num_lines": 81, "path": "/stars/code/shared/image/raw.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__IMAGE__RAW_H\n#define SHARED__IMAGE__RAW_H\n\n#include <string>\n#include \"../circular_buffer.h\"\n#include \"../../tools/timing.h\"\n#include \"../solving/filters.h\"\n\nnamespace Shared\n{\n namespace Image\n {\n\nclass Raw\n{\n public:\n Raw();\n ~Raw();\n void init(Parameters::Manager& params);\n double get_pixel(int x, int y);\n Raw& operator=(const Raw& rhs);\n bool is_inbounds(int& x, int& y);\n bool is_inbounds(double& x, double& y);\n bool is_xy_inbounds(double& x, double& y);\n\n std::string which_sensor;\n bool from_camera;\n unsigned int num_exposures;\n int counter_fcp;\n int counter_stars;\n int key_counter_stars;\n std::string dirname;\n std::string filename_base;\n std::string filename;\n Tools::Timer age;\n bool to_be_solved;\n int width;\n int height;\n int depth;\n int single_depth;\n unsigned short* pixels;\n\n static const unsigned int max_num_exposures = 4;\n unsigned short* separate_buffers[max_num_exposures];\n\n bool focus_known;\n int focus;\n bool aperture_known;\n int aperture;\n bool gain_known;\n double gain;\n\n Shared::Solving::Filters filters;\n\n bool has_netisc_framenum;\n int netisc_framenum;\n};\n\n// writes: camera\n// reads: solver\nextern Shared::CircularBuffer <Raw> raw_from_camera;\n\n// writes: camera\n// reads: net_image_client1\nextern Shared::CircularBuffer <Raw> raw_for_image_client1;\n\n// writes: camera\n// reads: net_image_client2\nextern Shared::CircularBuffer <Raw> raw_for_image_client2;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.583882212638855, "alphanum_fraction": 0.7438977360725403, "avg_line_length": 43.465518951416016, "blob_id": "5fa2cb08cac46c945ef0f9c829fdfaaaede19654", "content_id": "ee212a7f3ccee3e52676d9a99bf702f89dea5a77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2581, "license_type": "no_license", "max_line_length": 177, "num_lines": 58, "path": "/xsc_initialization_cmds_fc1.sh", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "# LAT and LON of the high bay at Penn\nblastcmd @192.168.1.3 pos_set 39.9526 284.8110\n\n# xsc_is_new_window_period which valid_period_cs\nblastcmd @192.168.1.3 xsc_is_new_window_period 0 1500\nblastcmd @192.168.1.3 xsc_is_new_window_period 1 1500\n\n# xsc_exposure_timing which exposure_cs grace_period_s (!!) share_delay_cs\n#blastcmd @192.168.1.3 xsc_exposure_timing 0 12 60 200\n#blastcmd @192.168.1.3 xsc_exposure_timing 1 12 60 200\nblastcmd @192.168.1.3 xsc_exposure_timing 0 12 8 200\nblastcmd @192.168.1.3 xsc_exposure_timing 1 12 8 200\n\n# xsc_solver_general which enabled timeout_s\nblastcmd @192.168.1.3 xsc_solver_general 0 1 7\nblastcmd @192.168.1.3 xsc_solver_general 1 1 7\n\n##### Triggering ######\n\n# xsc_trigger_threshold which enabled max_streaking_px # trigger only when conditions are met\nblastcmd @192.168.1.3 xsc_trigger_threshold 0 1 10\nblastcmd @192.168.1.3 xsc_trigger_threshold 1 1 10\n\n# xsc_scan_force_trigger which[doesnt apply] enabled # Force triggering at turnaround\nblastcmd @192.168.1.3 xsc_scan_force_trigger 0 0\n\n######### Solving and Filters ##########\n# xsc_filter_hor_location which enabled radius_degrees\n# blastcmd @192.168.1.3 xsc_filter_hor_location 0 1 20\n# blastcmd @192.168.1.3 xsc_filter_hor_location 1 1 20\nblastcmd @192.168.1.3 xsc_filter_hor_location 0 0 20\nblastcmd @192.168.1.3 xsc_filter_hor_location 1 0 20\n\n# xsc_filter_eq which enabled radius_degrees\nblastcmd @192.168.1.3 xsc_filter_eq_location 0 0 10\nblastcmd @192.168.1.3 xsc_filter_eq_location 1 0 10\n\n# xsc_filter_hor_roll which enabled min_deg max_deg\nblastcmd @192.168.1.3 xsc_filter_hor_roll 0 1 43 45\nblastcmd @192.168.1.3 xsc_filter_hor_roll 1 1 75 80\n\n# xsc_filter_el which enabled min_deg max_deg\nblastcmd @192.168.1.3 xsc_filter_el 0 1 5 60\nblastcmd @192.168.1.3 xsc_filter_el 1 1 5 60\n\n# xsc_blob_finding which snr_thresh max_num_blobs robust_mode_enabled fitting_method\n# blastcmd @192.168.1.3 xsc_blob_finding 0 10 15 1 0\n# blastcmd @192.168.1.3 xsc_blob_finding 1 10 15 1 0\nblastcmd @192.168.1.3 xsc_blob_finding 0 1 15 1 0\nblastcmd @192.168.1.3 xsc_blob_finding 1 1 15 1 0\n\n# xsc_pattern_matching which enabled display_star_name match_tol_px iplatescale_min_arcsec iplatescale_max_arcsec platescale_always_fixed platescale_fixed # platescale ~6.4\"/pix\nblastcmd @192.168.1.3 xsc_pattern_matching 0 1 0 5 6.5 6.8 0 0\nblastcmd @192.168.1.3 xsc_pattern_matching 1 1 0 5 6.5 6.8 0 0\n\n# xsc_filter_matching which error_threshold_arcsec fit_error_thresh_px num_matched \nblastcmd @192.168.1.3 xsc_filter_matching 0 6 10 6\nblastcmd @192.168.1.3 xsc_filter_matching 1 6 10 6\n\n\n" }, { "alpha_fraction": 0.6627634763717651, "alphanum_fraction": 0.6733021140098572, "avg_line_length": 17.54347801208496, "blob_id": "53d1bc69fa2698070f801ebdf24c289fd429683b", "content_id": "85adf4179c9132d24b4c0cff438731299558fcc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 855, "license_type": "no_license", "max_line_length": 73, "num_lines": 46, "path": "/stars/code/displaying/textures.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__TEXTURES_H\n#define DISPLAYING__TEXTURES_H\n\n#include \"texture.h\"\n#include \"glfont2/glfont2.h\"\n\nnamespace Displaying\n{\n class Textures;\n}\n\nnamespace Parameters\n{\n class Manager;\n}\n\nclass Displaying::Textures\n{\n public:\n enum texture_name {\n basic_drawing=0,\n font_texture,\n drawing_3d,\n };\n static const int num_textures = 3;\n\n Textures(Parameters::Manager& params);\n ~Textures();\n void init();\n GLuint get(texture_name name);\n glfont::GLFont font;\n\n private:\n bool display_enabled;\n std::string stars_dir;\n Displaying::Texture textures[num_textures];\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.6912037134170532, "alphanum_fraction": 0.6949074268341064, "avg_line_length": 25.987499237060547, "blob_id": "27cbeda29758bbb5492ac5fd52e707c910f7b90e", "content_id": "8d18c1a9cc27ba9aaaf84ca7bd0f9892d094129d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2161, "license_type": "no_license", "max_line_length": 79, "num_lines": 80, "path": "/stars/code/displaying/block.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__BLOCK_H\n#define DISPLAYING__BLOCK_H\n\n#include <string>\n#include \"dynamic_value.h\"\n#include \"utilities.h\"\n#include \"textures.h\"\n#include \"color.h\"\n#include \"../tools/timing.h\"\n\nnamespace Displaying\n{\n class Block;\n}\n\nclass Displaying::Block\n{\n public:\n Block();\n virtual ~Block();\n virtual void init(std::string title, Textures& textures_);\n void set_title(std::string title);\n void draw_text(std::string text, Position& pos, bool hold_temporary=false);\n void draw_value(DynamicValue& value, Position pos);\n void begin_draw(Position& position, double flip_scaling=1.0);\n void end_draw();\n void draw_border();\n void draw_title();\n void set_color(Color color, bool just_once=false);\n void set_text_scaling(double scaling, bool just_once=false);\n void set_rjust(double width, bool just_once=false);\n void scale_color(double scaling);\n void get_text_size(std::string text, double& width, double& height);\n\n void apply_flip_scaling(Position& position, double flip_scaling);\n void change_size(Size new_size, bool slow=false);\n void change_size(double width, double height, bool slow=false);\n void update_size(bool slow=false);\n bool size_update_finished();\n Size size();\n double width();\n double height();\n virtual void draw(Position& position, double flip_scaling=1.0);\n\n std::string title;\n double padding;\n double text_height;\n Textures* textures;\n\n private:\n Size current_size;\n Size requested_size;\n Size previous_size;\n Tools::Timer sizing_timer;\n bool sizing_finished;\n\n Color color_permanent;\n Color color_temporary;\n bool color_use_temporary;\n\n double text_scaling_permanent;\n double text_scaling_temporary;\n bool text_scaling_use_temporary;\n\n bool rjust_permanent;\n double rjust_width_permanent;\n bool rjust_temporary;\n double rjust_width_temporary;\n bool rjust_use_temporary;\n\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.6767998337745667, "alphanum_fraction": 0.6876398921012878, "avg_line_length": 49.7378044128418, "blob_id": "4fb9652be6cbfe03942ff1585e9f95907a489993", "content_id": "6fc239ca2d683461e07a0b2e6fec9a3f2f6efbdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8488, "license_type": "no_license", "max_line_length": 104, "num_lines": 164, "path": "/stars/code/networking/loading.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\r\n * © 2013 Columbia University. All Rights Reserved.\r\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\r\n * Software package, originally created for EBEX by Daniel Chapman.\r\n */\r\n\r\n#include \"connection.h\"\r\n#include \"logger.h\"\r\n#include \"../shared/update.h\"\r\n#include \"../shared/camera/results.h\"\r\n#include \"../shared/housekeeping/housekeeper.h\"\r\n#include \"../shared/lens/results.h\"\r\n#include \"../shared/image/blobs.h\"\r\n#include \"../shared/image/stats.h\"\r\n#include \"../shared/image/status.h\"\r\n#include \"../shared/image/solution_summary.h\"\r\n\r\n#define shared_camera_results (*(Shared::Camera::results_for_network.r))\r\n#define shared_camera_requests (*(Shared::Camera::requests_for_main.w))\r\n#define shared_housekeeper (*(Shared::Housekeeping::housekeeper_for_network.r))\r\n#define shared_lens_results (*(Shared::Lens::fcp_results_main_to_network.r))\r\n#define shared_image_blobs (*(Shared::Image::blobs_main_for_net.r))\r\n#define shared_image_stats (*(Shared::Image::stats_main_for_net.r))\r\n#define shared_image_status (*(Shared::Image::status_camera_for_network.r))\r\n#define shared_image_solution (*(Shared::Image::solution_summary_main_for_net.r))\r\n\r\nusing namespace Networking;\r\n\r\nvoid Connection::load_server_data_housekeeping()\r\n{\r\n for (unsigned int i=0; i<shared_housekeeper.measurements.size(); i++) {\r\n if (shared_housekeeper.measurements[i].valid) {\r\n if (shared_housekeeper.measurements[i].name.compare(\"lens\") == 0) {\r\n server_data.channels.hk_temp_lens = shared_housekeeper.measurements[i].value;\r\n } else if (shared_housekeeper.measurements[i].name.compare(\"comp\") == 0) {\r\n server_data.channels.hk_temp_comp = shared_housekeeper.measurements[i].value;\r\n } else if (shared_housekeeper.measurements[i].name.compare(\"plate\") == 0) {\r\n server_data.channels.hk_temp_plate = shared_housekeeper.measurements[i].value;\r\n } else if (shared_housekeeper.measurements[i].name.compare(\"flange\") == 0) {\r\n server_data.channels.hk_temp_flange = shared_housekeeper.measurements[i].value;\r\n } else if (shared_housekeeper.measurements[i].name.compare(\"press\") == 0) {\r\n server_data.channels.hk_pressure = shared_housekeeper.measurements[i].value;\r\n } else if (shared_housekeeper.measurements[i].name.compare(\"disk\") == 0) {\r\n server_data.channels.hk_disk = shared_housekeeper.measurements[i].value;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Connection::load_server_data_camera_and_lens()\r\n{\r\n server_data.channels.cam_gain_valid = 0;\r\n if (shared_camera_results.is_gain_valid(shared_camera_requests)) {\r\n server_data.channels.cam_gain_valid = 1;\r\n }\r\n server_data.channels.cam_gain_db = shared_camera_results.get_gain.value;\r\n server_data.channels.lens_focus = shared_lens_results.focus_value;\r\n server_data.channels.lens_aperture = shared_lens_results.aperture_value;\r\n}\r\n\r\nint gettimeofday(struct timeval * tp, struct timezone * tzp)\r\n{\r\n\t// Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's\r\n\t// This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC)\r\n\t// until 00:00:00 January 1, 1970 \r\n\tstatic const uint64_t EPOCH = ((uint64_t)116444736000000000ULL);\r\n\r\n\tSYSTEMTIME system_time;\r\n\tFILETIME file_time;\r\n\tuint64_t time;\r\n\r\n\tGetSystemTime(&system_time);\r\n\tSystemTimeToFileTime(&system_time, &file_time);\r\n\ttime = ((uint64_t)file_time.dwLowDateTime);\r\n\ttime += ((uint64_t)file_time.dwHighDateTime) << 32;\r\n\r\n\ttp->tv_sec = (long)((time - EPOCH) / 10000000L);\r\n\ttp->tv_usec = (long)(system_time.wMilliseconds * 1000);\r\n\treturn 0;\r\n}\r\n\r\nvoid Connection::load_server_data_image()\r\n{\r\n server_data.channels.image_ctr_stars = shared_image_status.counter_stars;\r\n server_data.channels.image_ctr_fcp = shared_image_status.counter_fcp;\r\n server_data.channels.image_num_exposures = shared_image_status.num_exposures;\r\n\r\n server_data.channels.image_stats_mean = UINT16_MAX;\r\n server_data.channels.image_stats_noise = UINT16_MAX;\r\n server_data.channels.image_stats_gaindb = -1.0;\r\n server_data.channels.image_stats_num_px_sat = -1;\r\n server_data.channels.image_stats_frac_px_sat = -1.0;\r\n server_data.channels.image_afocus_metric_valid = 0;\r\n server_data.channels.image_afocus_metric = 0.0;\r\n if (shared_image_stats.counter_stars == shared_image_status.counter_stars) {\r\n if (shared_image_stats.mean_known) {\r\n server_data.channels.image_stats_mean = shared_image_stats.mean;\r\n server_data.channels.image_stats_num_px_sat = shared_image_stats.num_pixels_saturated;\r\n server_data.channels.image_stats_frac_px_sat = shared_image_stats.fraction_pixels_saturated;\r\n }\r\n if (shared_image_stats.noise_known) {\r\n server_data.channels.image_stats_noise = shared_image_stats.noise;\r\n }\r\n if (shared_image_stats.gain_known) {\r\n server_data.channels.image_stats_gaindb = shared_image_stats.gaindb;\r\n }\r\n server_data.channels.image_afocus_metric_valid = shared_image_stats.autofocus_metric_valid;\r\n server_data.channels.image_afocus_metric = shared_image_stats.autofocus_metric;\r\n }\r\n\r\n server_data.channels.image_eq_valid = false;\r\n server_data.channels.image_hor_valid = false;\r\n if (shared_image_solution.counter_stars == shared_image_status.counter_stars) {\r\n server_data.channels.image_eq_valid = shared_image_solution.equatorial.valid;\r\n server_data.channels.image_eq_ra = shared_image_solution.equatorial.ra;\r\n server_data.channels.image_eq_dec = shared_image_solution.equatorial.dec;\r\n server_data.channels.image_eq_roll = shared_image_solution.equatorial.roll;\r\n server_data.channels.image_eq_sigma_ra = shared_image_solution.equatorial.sigma_ra;\r\n server_data.channels.image_eq_sigma_dec = shared_image_solution.equatorial.sigma_dec;\r\n server_data.channels.image_eq_sigma_roll = shared_image_solution.equatorial.sigma_roll;\r\n server_data.channels.image_eq_sigma_pointing = shared_image_solution.equatorial.sigma_pointing;\r\n server_data.channels.image_eq_iplate = shared_image_solution.equatorial.iplatescale;\r\n\r\n server_data.channels.image_hor_valid = shared_image_solution.horizontal.valid;\r\n server_data.channels.image_hor_az = shared_image_solution.horizontal.az;\r\n server_data.channels.image_hor_el = shared_image_solution.horizontal.el;\r\n server_data.channels.image_hor_roll = shared_image_solution.horizontal.roll;\r\n server_data.channels.image_hor_sigma_az = shared_image_solution.horizontal.sigma_az;\r\n server_data.channels.image_hor_sigma_el = shared_image_solution.horizontal.sigma_el;\r\n server_data.channels.image_hor_sigma_roll = shared_image_solution.horizontal.sigma_roll;\r\n server_data.channels.image_hor_sigma_pointing = shared_image_solution.horizontal.sigma_pointing;\r\n server_data.channels.image_hor_iplate = shared_image_solution.horizontal.iplatescale;\r\n\r\n server_data.channels.image_num_blobs_found = shared_image_solution.num_blobs_total;\r\n server_data.channels.image_num_blobs_matched = shared_image_solution.num_blobs_matched;\r\n\r\n }\r\n struct timeval tv = { 0 };\r\n gettimeofday(&tv, NULL);\r\n server_data.channels.timestamp_s = tv.tv_sec;\r\n server_data.channels.timestamp_us = tv.tv_usec;\r\n\r\n server_data.blobs.counter_stars = shared_image_blobs.counter_stars;\r\n server_data.blobs.num_blobs = 0;\r\n for (unsigned int i=0; i < XSC_BLOBS_ARRAY_SIZE && i < shared_image_blobs.blobs.size(); i++) {\r\n server_data.blobs.blobs[i].x = shared_image_blobs.blobs[i].x;\r\n server_data.blobs.blobs[i].y = shared_image_blobs.blobs[i].y;\r\n server_data.blobs.blobs[i].flux = shared_image_blobs.blobs[i].flux;\r\n server_data.blobs.blobs[i].peak_to_flux = shared_image_blobs.blobs[i].peak_to_flux;\r\n server_data.blobs.num_blobs++;\r\n }\r\n}\r\n\r\nvoid Connection::load_server_data()\r\n{\r\n Shared::update(Shared::ThreadNames::net_server);\r\n xsc_clear_server_data(&server_data);\r\n\r\n server_data.channels.ctr_stars = shared_camera_results.counter_stars;\r\n server_data.channels.stars_run_time = (unsigned int) logger.age->time();\r\n load_server_data_housekeeping();\r\n load_server_data_camera_and_lens();\r\n load_server_data_image();\r\n}\r\n\r\n" }, { "alpha_fraction": 0.652222216129303, "alphanum_fraction": 0.6566666960716248, "avg_line_length": 17.367347717285156, "blob_id": "5e13dc338b44f27a6b753905e93d20368d6dd649", "content_id": "af4355e57bd2f085b8825bb34bc134dc425c9b5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 901, "license_type": "no_license", "max_line_length": 76, "num_lines": 49, "path": "/stars/code/solving/finding/pedestal_fitter.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__FINDING__PEDESTAL_FITTER_H\n#define SOLVING__FINDING__PEDESTAL_FITTER_H\n\n#include <vector>\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n}\n\nnamespace Solving\n{\n class Blob;\n namespace Finding\n {\n class PedestalFitter;\n }\n}\n\nclass Solving::Finding::PedestalFitter\n{\n public:\n PedestalFitter();\n ~PedestalFitter();\n void fit_pedestal(Shared::Image::Raw& image, Blob& blob);\n void fit_pedestals(Shared::Image::Raw& image, std::vector<Blob>& blobs);\n\n private:\n int halfwidth;\n int padding;\n int max_num_pixels;\n double* pixels;\n int* us;\n int* vs;\n double* workspace;\n double* covar;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6100702285766602, "alphanum_fraction": 0.6346604228019714, "avg_line_length": 22.69444465637207, "blob_id": "7fc6818ef4ab174347d7f500da07f1680bbf1e2c", "content_id": "35f8d0ebdbaa378887d0f74091bc1af9dff6d8ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 855, "license_type": "no_license", "max_line_length": 97, "num_lines": 36, "path": "/stars/code/solving/star.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"star.h\"\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include <boost/format.hpp>\n#include \"../tools/angles.h\"\n#include \"../logging/logger.h\"\n\nusing namespace Solving;\n\nStar::Star(int id_, double ra_, double dec_, double mag_): id(id_), ra(ra_), dec(dec_), mag(mag_)\n{\n fitted_x = 0.0;\n fitted_y = 0.0;\n}\n\nStar::Star()\n{\n Star(-1, -1.0, -1.0, -1.0);\n}\n\nbool Star::sort_by_mag(Star first, Star second)\n{\n return first.mag < second.mag;\n}\n\nvoid Star::print(Logging::Logger& logger, string prefix)\n{\n logger.log(format(prefix + \"id %d ra (deg) %0.4f dec (deg) %0.4f mag %0.4e\")\n % id % to_degrees(ra) % to_degrees(dec) % mag);\n}\n\n" }, { "alpha_fraction": 0.689393937587738, "alphanum_fraction": 0.6988636255264282, "avg_line_length": 17.821428298950195, "blob_id": "59fa12b3423e6d18468488b94337c17c158b0d9a", "content_id": "cbcd91e016fdfa186db1fe8ce6b0e6716aa3716e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 529, "license_type": "no_license", "max_line_length": 85, "num_lines": 28, "path": "/stars/code/imaging/fake_sky.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef IMAGING__FAKE_SKY_H\n#define IMAGING__FAKE_SKY_H\n\n#include \"../tools/stocc/stocc.h\"\n\nnamespace Imaging\n{\n class FakeSky;\n}\n\nclass Imaging::FakeSky\n{\n public:\n FakeSky();\n void match_brightness(unsigned short pixels[], int width, int height, int depth);\n\n private:\n StochasticLib2 sto;\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.29736271500587463, "alphanum_fraction": 0.31171756982803345, "avg_line_length": 29.961240768432617, "blob_id": "ed47b8d3eb35e305cfabb39bc54a2c83446816b6", "content_id": "fd1a8ee0091e01ddb377fa33b02ba8d3ba6a0e24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11982, "license_type": "no_license", "max_line_length": 100, "num_lines": 387, "path": "/starcam/svd.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <stdlib.h>\n#include <math.h>\n#include \"svd.h\"\n\ndouble rms ( double a, double b );\nvoid svd ( int m, int n, int mp, int np, double *a, double *w, double *v, double *work, int *jstat )\n/*\n** - - - - - - -\n** s l a S v d\n** - - - - - - -\n**\n** Singular value decomposition.\n**\n** (double precision)\n**\n** This routine expresses a given matrix a as the product of\n** three matrices u, w, v:\n**\n** a = u x w x vt\n**\n** where:\n**\n** a is any m (rows) x n (columns) matrix, where m >= n\n** u is an m x n column-orthogonal matrix\n** w is an n x n diagonal matrix with w(i,i) >= 0\n** vt is the transpose of an n x n orthogonal matrix\n**\n** Note that m and n, above, are the logical dimensions of the\n** matrices and vectors concerned, which can be located in\n** arrays of larger physical dimensions, given by mp and np.\n**\n** Given:\n** m,n int numbers of rows and columns in matrix a\n** mp,np int physical dimensions of the array containing a\n** a double[mp][np] array containing m x n matrix a\n**\n** Returned:\n** *a double[mp][np] array containing m x n column-orthogonal matrix u\n** *w double[n] n x n diagonal matrix w (diagonal elements only)\n** *v double[np][np] array containing n x n orthogonal matrix v\n** *work double[n] workspace\n** *jstat int 0 = OK\n** -1 = the a array is the wrong shape\n** >0 = 1 + index of w for which convergence failed.\n**\n** (n.b. v contains matrix v, not the transpose of matrix v)\n**\n** References:\n** The algorithm is an adaptation of the routine SVD in the EISPACK\n** library (Garbow et al 1977, Eispack guide extension, Springer\n** Verlag), which is a Fortran 66 implementation of the Algol\n** routine SVD of Wilkinson & Reinsch 1971 (Handbook for Automatic\n** Computation, vol 2, Ed Bauer et al, Springer Verlag). For the\n** non-specialist, probably the clearest general account of the use\n** of SVD in least squares problems is given in Numerical Recipes\n** (Press et al 1986, Cambridge University Press).\n**\n** From slamac.h: TRUE, FALSE\n**\n** Example call (note handling of \"adjustable dimension\" 2D arrays):\n**\n** double a[MP][NP], w[NP], v[NP][NP], work[NP];\n** int m, n, j;\n** :\n** slaSvd ( m, n, MP, NP, (double *) a, w, (double *) v, work, &j );\n**\n** Last revision: 24 June 1997\n**\n** Copyright P.T.Wallace. All rights reserved.\n*/\n\n/* Maximum number of iterations in QR phase */\n#define ITMAX 30\n{\n int i, k, l, j, k1, its, l1, i1, cancel;\n double g, scale, an, s, x, f, h, cn, c, y, z;\n double *ai, *aj, *ak;\n double *vi, *vj, *vk;\n\n/* Check that the matrix is the right size and shape */\n if ( m < n || m > mp || n > np ) {\n *jstat = -1;\n } else {\n *jstat = 0;\n\n /* Householder reduction to bidiagonal form */\n g = 0.0;\n scale = 0.0;\n an = 0.0;\n for ( i = 0, ai = a; i < n; i++, ai += np ) {\n l = i + 1;\n work[i] = scale * g;\n g = 0.0;\n s = 0.0;\n scale = 0.0;\n if ( i < m ) {\n for ( k = i, ak = ai; k < m; k++, ak += np ) {\n scale += fabs ( ak[i] );\n }\n if ( scale != 0.0 ) {\n for ( k = i, ak = ai; k < m; k++, ak += np ) {\n x = ak[i] / scale;\n ak[i] = x;\n s += x * x;\n }\n f = ai[i];\n g = - dsign ( sqrt ( s ), f );\n h = f * g - s;\n ai[i] = f - g;\n if ( i != n - 1 ) {\n for ( j = l; j < n; j++ ) {\n s = 0.0;\n for ( k = i, ak = ai; k < m; k++, ak += np ) {\n s += ak[i] * ak[j];\n }\n f = s / h;\n for ( k = i, ak = ai; k < m; k++, ak += np ) {\n ak[j] += f * ak[i];\n }\n }\n }\n for ( k = i, ak = ai; k < m; k++, ak += np ) {\n ak[i] *= scale;\n }\n }\n }\n w[i] = scale * g;\n g = 0.0;\n s = 0.0;\n scale = 0.0;\n if ( i < m && i != n - 1 ) {\n for ( k = l; k < n; k++ ) {\n scale += fabs ( ai[k] );\n }\n if ( scale != 0.0 ) {\n for ( k = l; k < n; k++ ) {\n x = ai[k] / scale;\n ai[k] = x;\n s += x * x;\n }\n f = ai[l];\n g = - dsign ( sqrt ( s ), f );\n h = f * g - s;\n ai[l] = f - g;\n for ( k = l; k < n; k++ ) {\n work[k] = ai[k] / h;\n }\n if ( i != m-1 ) {\n for ( j = l, aj = a + l*np; j < m; j++, aj += np ) {\n s = 0.0;\n for ( k = l; k < n; k++ ) {\n s += aj[k] * ai[k];\n }\n for ( k = l; k < n; k++ ) {\n aj[k] += s * work[k];\n }\n }\n }\n for ( k = l; k < n; k++ ) {\n ai[k] *= scale;\n }\n }\n }\n\n /* Overestimate of largest column norm for convergence test */\n cn = fabs ( w[i] ) + fabs ( work[i] );\n an = gmax ( an, cn );\n }\n\n /* Accumulation of right-hand transformations */\n for ( i = n - 1, ai = a + ( n - 1 ) * np, vi = v + ( n - 1 ) * np;\n i >= 0;\n i--, ai -= np, vi -= np ) {\n if ( i != n - 1 ) {\n if ( g != 0.0 ) {\n for ( j = l, vj = v + l * np; j < n; j++, vj += np ) {\n vj[i] = ( ai[j] / ai[l] ) / g;\n }\n for ( j = l; j < n; j++ ) {\n s = 0.0;\n for ( k = l, vk = v + l*np; k < n; k++, vk += np ) {\n s += ai[k] * vk[j];\n }\n for ( k = l, vk = v + l*np; k < n; k++, vk += np ) {\n vk[j] += s * vk[i];\n }\n }\n }\n for ( j = l, vj = v + l*np; j < n; j++, vj += np ) {\n vi[j] = 0.0;\n vj[i] = 0.0;\n }\n }\n vi[i] = 1.0;\n g = work[i];\n l = i;\n }\n\n /* Accumulation of left-hand transformations */\n for ( i = n - 1, ai = a + i*np; i >= 0; i--, ai -= np ) {\n l = i + 1;\n g = w[i];\n if ( i != n - 1 ) {\n for ( j = l; j < n; j++ ) {\n ai[j] = 0.0;\n }\n }\n if ( g != 0.0 ) {\n if ( i != n - 1 ) {\n for ( j = l; j < n; j++ ) {\n s = 0.0;\n for ( k = l, ak = a + l * np; k < m; k++, ak += np ) {\n s += ak[i] * ak[j];\n }\n f = ( s / ai[i] ) / g;\n for ( k = i, ak = a + i * np; k < m; k++, ak += np ) {\n ak[j] += f * ak[i];\n }\n }\n }\n for ( j = i, aj = ai; j < m; j++, aj += np ) {\n aj[i] /= g;\n }\n } else {\n for ( j = i, aj = ai; j < m; j++, aj += np ) {\n aj[i] = 0.0;\n }\n }\n ai[i] += 1.0;\n }\n\n /* Diagonalization of the bidiagonal form */\n for ( k = n - 1; k >= 0; k-- ) {\n k1 = k - 1;\n\n /* Iterate until converged */\n for ( its = 1; its <= ITMAX; its++ ) {\n\n /* Test for splitting into submatrices */\n cancel = TRUE;\n for ( l = k; l >= 0; l-- ) {\n l1 = l - 1;\n if ( an + fabs ( work[l] ) == an ) {\n cancel = FALSE;\n break;\n }\n /* (Following never attempted for l=0 because work[0] is zero) */\n if ( an + fabs ( w[l1] ) == an ) {\n break;\n }\n }\n\n /* Cancellation of work[l] if l>0 */\n if ( cancel ) {\n c = 0.0;\n s = 1.0;\n for ( i = l; i <= k; i++ ) {\n f = s * work[i];\n if ( an + fabs ( f ) == an ) {\n break;\n }\n g = w[i];\n h = rms ( f, g );\n w[i] = h;\n c = g / h;\n s = - f / h;\n for ( j = 0, aj = a; j < m; j++, aj += np ) {\n y = aj[l1];\n z = aj[i];\n aj[l1] = y * c + z * s;\n aj[i] = - y * s + z * c;\n }\n }\n }\n\n /* Converged? */\n z = w[k];\n if ( l == k ) {\n\n /* Yes: ensure singular values non-negative */\n if ( z < 0.0 ) {\n w[k] = -z;\n for ( j = 0, vj = v; j < n; j++, vj += np ) {\n vj[k] = -vj[k];\n }\n }\n\n /* Stop iterating */\n break;\n\n } else {\n\n /* Not converged yet: set status if iteration limit reached */\n if ( its >= ITMAX ) {\n *jstat = k + 1;\n }\n\n /* Shift from bottom 2 x 2 minor */\n x = w[l];\n y = w[k1];\n g = work[k1];\n h = work[k];\n f = ( ( y - z ) * ( y + z )\n + ( g - h ) * ( g + h ) ) / ( 2.0 * h * y );\n g = ( fabs ( f ) <= 1e15 ) ? rms ( f, 1.0 ) : fabs ( f );\n f = ( ( x - z ) * ( x + z )\n + h * ( y / ( f + dsign ( g, f ) ) - h ) ) / x;\n\n /* Next QR transformation */\n c = 1.0;\n s = 1.0;\n for ( i1 = l; i1 <= k1; i1++ ) {\n i = i1 + 1;\n g = work[i];\n y = w[i];\n h = s * g;\n g = c * g;\n z = rms ( f, h );\n work[i1] = z;\n if ( z != 0.0 ) {\n c = f / z;\n s = h / z;\n } else {\n c = 1.0;\n s = 0.0;\n }\n f = x * c + g * s;\n g = - x * s + g * c;\n h = y * s;\n y = y * c;\n for ( j = 0, vj = v; j < n; j++, vj += np ) {\n x = vj[i1];\n z = vj[i];\n vj[i1] = x * c + z * s;\n vj[i] = - x * s + z * c;\n }\n z = rms ( f, h );\n w[i1] = z;\n if ( z != 0.0 ) {\n c = f / z;\n s = h / z;\n }\n f = c * g + s * y;\n x = - s * g + c * y;\n for ( j = 0, aj = a; j < m; j++, aj += np ) {\n y = aj[i1];\n z = aj[i];\n aj[i1] = y * c + z * s;\n aj[i] = - y * s + z * c;\n }\n }\n work[l] = 0.0;\n work[k] = f;\n w[k] = x;\n }\n }\n }\n }\n//printf(\"%lf %lf %lf\\n\",a[0],a[1],a[2]);\n//printf(\"%lf %lf %lf\\n\",a[3],a[4],a[5]);\n//printf(\"%lf %lf %lf\\n\",a[6],a[7],a[8]);\n}\n\ndouble rms ( double a, double b )\n\n/* sqrt(a*a+b*b) with protection against under/overflow */\n\n{\n double wa, wb, w;\n\n wa = fabs ( a );\n wb = fabs ( b );\n\n if ( wa > wb ) {\n w = wa;\n wa = wb;\n wb = w;\n }\n\n if ( wb == 0.0 ) {\n return 0.0;\n } else {\n w = wa / wb;\n return wb * sqrt ( 1.0 + w * w );\n }\n}\n" }, { "alpha_fraction": 0.6759884357452393, "alphanum_fraction": 0.6827386617660522, "avg_line_length": 19.739999771118164, "blob_id": "b19982977e84dbdd6e347667f399a412e254f958", "content_id": "a02e26b57b345255a005617e0f77aa2088340c4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1038, "license_type": "no_license", "max_line_length": 73, "num_lines": 50, "path": "/stars/code/shared/solving/mask.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__SOLVING__MASK_H\n#define SHARED__SOLVING__MASK_H\n\n#include \"../circular_buffer.h\"\n#include <boost/cstdint.hpp>\n\nnamespace Shared\n{\n namespace Solving\n {\n\nclass Mask\n{\n public:\n Mask();\n void init(Parameters::Manager& params);\n Mask& operator=(const Mask& rhs);\n bool cell_masked(unsigned int corner_x, unsigned int corner_y);\n bool block_masked(unsigned int i, unsigned int j);\n\n bool enabled;\n int counter;\n static const int num_fields = 3;\n uint32_t fields[num_fields];\n\n int block_size;\n int num_blocks_x;\n int num_blocks_y;\n int bits_per_word;\n};\n\n// writes: network\n// reads: solver\nextern Shared::CircularBufferPass <Mask> mask_network_for_solver;\n\n// writes: solver\n// reads: main\nextern Shared::CircularBuffer <Mask> mask_solver_for_main;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.7019230723381042, "alphanum_fraction": 0.7067307829856873, "avg_line_length": 22.77142906188965, "blob_id": "4ce9499b9743c453177d7d5ac94db7c9b088ad8f", "content_id": "4724b9c08b57b08402e7eff3623abb571f4cb1d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 833, "license_type": "no_license", "max_line_length": 123, "num_lines": 35, "path": "/stars/code/displaying/base_set.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__BASE_SET_H\n#define DISPLAYING__BASE_SET_H\n\n#include <math.h>\n#include <vector>\n#include \"../tools/timing.h\"\n#include \"../solving/base_set.h\"\n\nnamespace Displaying\n{\n class BaseSet;\n class Blob;\n}\n\nclass Displaying::BaseSet\n{\n public:\n BaseSet(Solving::BaseSet base_set_);\n void draw_lines(std::vector<Blob>& display_blobs, double progress, bool done, double global_brightness, int num_blobs);\n void draw(std::vector<Blob>& display_blobs, double progress, bool done, double global_brightness);\n\n private:\n Solving::BaseSet base_set;\n Tools::Timer timer;\n bool aged;\n};\n\n#endif\n" }, { "alpha_fraction": 0.5420116186141968, "alphanum_fraction": 0.5548644065856934, "avg_line_length": 37.960784912109375, "blob_id": "79ffce44529edc456e195dbd2ef5a392187f84a0", "content_id": "adb31bf09ec2039891622f390bd9cb78ac961e26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 21863, "license_type": "no_license", "max_line_length": 117, "num_lines": 561, "path": "/mole/mole.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* ---------------------------------------------------------------------\n * ------------------------------- MOLE --------------------------------\n * ---------------------------------------------------------------------\n * This program is distributed under the GNU General Public License (GPL)\n * Version 2 or higher.\n *\n * ------------------------- Description -------------------------------\n * Mole is a client program that requests frame data from a bittlm \n * server on a given network. Upon receipt, the framefile packets are \n * converted to the DIR file format on the local machine. Additionally,\n * image data (full frame images, thumbnails, science images) with the \n * framefile are parsed and assembled for viewing either via an external\n * interface (i.e. .jpg and .ppm files) or via the BIS format (viewable\n * in KST). Mole also stores a raw version of the framefile packets to \n * the local disk with a corresponding format file. \n * \n * The converted DIR file is available via /data/etc/mole.lnk and the \n * directory of cached DIR files, format files, framefiles is located at\n * /data/rawdir/.\n * \n * For convenience, symbolic links to the latest full frame images (saved\n * as .jpg) are generated in /data/etc every time a new image is received.\n *\n * ---------------------------- Author ---------------------------------\n * L. Javier Romualdez\n * Institute for Aerospace Studies (UTIAS)\n * University of Toronto\n *\n * Created: June 24, 2014\n *\n * Copyright 2017 Javier Romualdez\n *\n * -------------------------- Revisions --------------------------------\n *\n * 2019 - mole is now project agnostic and makes use of liblinklist to \n * connect, extract, and, write data. This constitutes version 2.0.\n *\n * 26/08/17 - made mole independent of local telemlist.bit and linklists;\n * the telemlist and linklist for a specified link is requested from the\n * bittlm server and parsed locally so that mole is always up-to-date\n *\n */\n\n#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n#include <errno.h>\n#include <netdb.h>\n#include <signal.h>\n#include <string.h>\n#include <time.h>\n#include <unistd.h>\n#include <inttypes.h>\n#include <getopt.h>\n#include <termios.h>\n\n#include <sys/socket.h>\n#include <sys/syslog.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/stat.h>\n#include <dirent.h>\n\n#include <netinet/in.h>\n#include <arpa/inet.h>\n\n#include <pthread.h> // threads\n#include <openssl/md5.h>\n\n#include <linklist.h>\n#include <linklist_compress.h>\n#include <linklist_writer.h>\n#include <linklist_connect.h>\n\n#define MOLE_VERSION \"2.0\" \n\nstatic linklist_tcpconn_t tcpconn = {\"localhost\"};\nchar mole_dir[LINKLIST_MAX_FILENAME_SIZE] = \"/data/mole\";\nchar data_etc[LINKLIST_MAX_FILENAME_SIZE] = \"/data/etc\";\nchar data_rawdir[LINKLIST_MAX_FILENAME_SIZE] = \"/data/rawdir\";\nchar symdir_name[LINKLIST_MAX_FILENAME_SIZE] = \"/data/etc/mole.lnk\";\nchar symraw_name[LINKLIST_MAX_FILENAME_SIZE] = \"/data/rawdir/LIVE\";\nchar mole_cfg[LINKLIST_MAX_FILENAME_SIZE] = \"/data/mole/mole.cfg\";\n\nvoid USAGE(void) {\n \n printf(\"\\n\\nMole is a generic linklist client/server that converts raw \"\n \"binary data to dirfiles.\\n\\n\"\n \"Version \" MOLE_VERSION \": compiled on \" __DATE__ \".\\n\\n\"\n \"Usage: mole [OPTION]...\\n\\n\"\n \" @host Connect to a specific host.\\n\"\n \" -ad --archive-dir dir Save raw binary files to specified directory.\\n\"\n \" Only valid if backing up binary data locally.\\n\"\n \" Default is /data/rawdir.\\n\"\n \" -b --backup Backup binary data in the archive directory.\\n\"\n \" -nb --no-backup Do not backup data in the archive directory (default).\\n\"\n \" -bs --block-size fpf Specify the number of frames per file flush.\\n\"\n \" Default is 1 frame per flush for real time.\\n\"\n \" -c --client Run a client (default).\\n\"\n \" -nc --no-client Don't run a client.\\n\"\n \" -d --dry-run Do a dry run of mole setup (i.e. get stats but don't transfer data\\n\"\n \" -F --filename regex Select a file by standard regex entry\\n\"\n \" If exactly one matching entry is found, that file will be loaded.\\n\"\n \" Otherwise, the file selection dialog box will be prompted.\\n\"\n \" -E --end X Last frame to read. Ignores rewind if specified.\\n\"\n \" Mole will exit once the last frame is read.\\n\"\n \" Must specify a start frame (-S) in this mode.\\n\"\n \" -k --check Evaluate checksum values when processing data (default).\\n\" \n \" -nk --no-check Ignore checksum values when processing data.\\n\" \n \" -L --loopback Have mole extract its own binary files.\\n\"\n \" Binary files at archive-dir will be extracted to mole-dir\\n\"\n \" -m --map-frames Give a report on the frames that have been converted on disk.\\n\"\n \" This is useful for determining what data is stored to a dirfile.\\n\"\n \" -M --map-and-fill Give a frame report and fill in data gaps.\\n\"\n \" After gaps are filled, data is read from end as normal.\\n\"\n \" This option ignores -S (start), -E (end), and -W (rewind).\\n\"\n \" -md --mole-dir dir Set the directory in which dirfiles will be stored.\\n\"\n \" The default is /data/mole.\\n\"\n \" -N --live-name str The name of the live data symlink (default /data/rawdir/LIVE).\\n\"\n \" Relative paths are w.r.t. /data/rawdir.\\n\"\n \" -O --offset Offset frame where the data will start being written (default 0).\\n\"\n \" -p --client-port p Client port to receive data (default 40204).\\n\"\n \" -P --server-port p Server port on which to serve up data (default 40204).\\n\"\n \" --port p Sets the client and server port (default 40204).\\n\"\n \" -r --rate Expected data rate (Hz) for receiving data (default 20).\\n\"\n \" -s --server Run a server for other mole clients to connect to.\\n\"\n \" -ns --no-server Don't run a server (default).\\n\"\n \" -S --start X Starting frame to read. Ignores rewind if specified.\\n\"\n \" -w --rewind X Start acquiring data X frames from the latest index (default 20).\\n\"\n \" Ignores how much data had been read already.\\n\"\n \" -W --smart-rewind X Start acquiring data X frames from the latest index (default 20).\\n\"\n \" Will start from the latest data acquired within the rewind value.\\n\"\n \" -v --verbose Verbose mode.\\n\"\n \" --version Print this message\\n\"\n \"\\n\");\n\n exit(0);\n}\n\nstruct CfgItems {\n\tchar name[256];\n\tchar value[256];\n};\ntypedef struct {\n unsigned int n;\n struct CfgItems * items;\n} Configuration;\n\n\nvoid load_mole_cfg(char * filename) {\n FILE * fp = fpreopenb(filename);\n char *line = NULL;\n size_t len = 0;\n unsigned int read = 0;\n\n while ((read = getline(&line, &len, fp)) != -1) {\n line[--read] = '\\0';\n\n }\n\n fclose(fp);\n}\n\nvoid save_mole_cfg(char * filename) {\n\n FILE * fp = fpreopenb(filename);\n\n fclose(fp);\n}\n\nvoid print_display(char * text, unsigned int recv_framenum) {\n static char spin[] = \"/-\\\\|\";\n static unsigned int s = 0;\n static unsigned int prev_framenum = 0;\n static unsigned int idle_count = 0;\n\n char arrow[13] = \"------------\";\n\n if (recv_framenum == prev_framenum) {\n idle_count++;\n } else {\n idle_count = 0;\n }\n prev_framenum = recv_framenum;\n\n if (idle_count < 5) {\n s = (s+1)%4;\n }\n\n arrow[s%12] = '>';\n arrow[(s+4)%12] = '>';\n arrow[(s+8)%12] = '>';\n arrow[10] = '\\0';\n printf(\"%c Frame %d %s %s\", spin[s], recv_framenum, arrow, text);\n printf(\"\\r\");\n fflush(stdout); \n}\n\nint main(int argc, char *argv[]) {\n // mode selection\n int server_mode = 0;\n int client_mode = 1;\n int map_frames = 0;\n int fill_in_gaps = 0;\n unsigned int gap_count = 0;\n int dry_run = 0;\n unsigned int rewind = 20;\n int force_rewind = 1;\n uint64_t start_frame = UINT64_MAX;\n uint64_t end_frame = UINT64_MAX;\n unsigned int tcp_flags = TCPCONN_FILE_RAW | TCPCONN_RESOLVE_NAME;\n unsigned int ll_rawfile_flags = 0;\n unsigned int ll_dirfile_flags = 0;\n int bin_backup = 0;\n char filename_selection[LINKLIST_MAX_FILENAME_SIZE] = {0};\n char custom_calspecs[LINKLIST_MAX_FILENAME_SIZE] = {0};\n unsigned int nodata_timeout = 50000; // default rate is 20 Hz = 1.0e6/50000\n\n // configure the TCP connection\n tcpconn.flag |= TCPCONN_LOOP;\n\n // initialization variables\n uint32_t req_serial = 0;\n unsigned int req_framenum = 0;\n int64_t req_init_framenum = 0;\n\n // received data variables\n uint8_t * recv_buffer = NULL;\n uint8_t recv_header[TCP_PACKET_HEADER_SIZE] = {0};\n unsigned int buffer_size = 0;\n int64_t recv_framenum = 0;\n uint64_t offset_framenum = 0;\n uint16_t recv_flags = 0;\n int resync = 1;\n unsigned int num_frames_per_flush = 1; // 1 ensures real time frame push to disk\n unsigned int frame_i = 0;\n\n // superframe and linklist \n superframe_t * superframe = NULL;\n linklist_t * linklist = NULL;\n linklist_dirfile_t * ll_dirfile = NULL;\n linklist_rawfile_t * ll_rawfile = NULL;\n\n int i;\n for (i = 1; i < argc; i++) {\n if (argv[i][0] == '@') { // custom target\n strcpy(tcpconn.ip, argv[i]+1);\n } else if ((strcmp(argv[i], \"--server\") == 0) ||\n (strcmp(argv[i], \"-s\") == 0)) { // server mode\n server_mode = 1;\n } else if ((strcmp(argv[i], \"--no-server\") == 0) ||\n (strcmp(argv[i], \"-ns\") == 0)) { // no server mode\n server_mode = 0;\n } else if ((strcmp(argv[i], \"--client\") == 0) ||\n (strcmp(argv[i], \"-c\") == 0)) { // client mode\n client_mode = 1;\n } else if ((strcmp(argv[i], \"--no-client\") == 0) ||\n (strcmp(argv[i], \"-nc\") == 0)) { // no client mode\n client_mode = 0;\n } else if ((strcmp(argv[i], \"--rewind\") == 0) ||\n (strcmp(argv[i], \"-w\") == 0)) { // rewind value \n rewind = atoi(argv[++i]);\n force_rewind = 1;\n } else if ((strcmp(argv[i], \"--smart-rewind\") == 0) ||\n (strcmp(argv[i], \"-W\") == 0)) { // rewind value \n rewind = atoi(argv[++i]);\n force_rewind = 0;\n } else if ((strcmp(argv[i], \"--start\") == 0) ||\n (strcmp(argv[i], \"-S\") == 0)) { // start frame \n start_frame = atoi(argv[++i]);\n } else if ((strcmp(argv[i], \"--end\") == 0) ||\n (strcmp(argv[i], \"-E\") == 0)) { // end frame \n end_frame = atoi(argv[++i]);\n } else if ((strcmp(argv[i], \"--verbose\") == 0) ||\n (strcmp(argv[i], \"-v\") == 0)) { // verbose mode\n ll_dirfile_flags |= LL_VERBOSE;\n } else if ((strcmp(argv[i], \"--backup\") == 0) ||\n (strcmp(argv[i], \"-b\") == 0)) { // write binary backup files\n bin_backup = 1;\n } else if ((strcmp(argv[i], \"--no-backup\") == 0) ||\n (strcmp(argv[i], \"-nb\") == 0)) { // don't write binary backup files\n bin_backup = 0;\n } else if ((strcmp(argv[i], \"--archive-dir\") == 0) ||\n (strcmp(argv[i], \"-ad\") == 0)) { // set the archive directory\n strcpy(archive_dir, argv[++i]);\n } else if ((strcmp(argv[i], \"--mole-dir\") == 0) ||\n (strcmp(argv[i], \"-md\") == 0)) { // set the mole directory dirfiles\n strcpy(mole_dir, argv[++i]);\n } else if ((strcmp(argv[i], \"--check\") == 0) ||\n (strcmp(argv[i], \"-k\") == 0)) { // checksum \n ll_dirfile_flags &= ~LL_IGNORE_CHECKSUM;\n } else if ((strcmp(argv[i], \"--no-check\") == 0) ||\n (strcmp(argv[i], \"-nk\") == 0)) { // no checksum \n ll_dirfile_flags |= LL_IGNORE_CHECKSUM;\n } else if ((strcmp(argv[i], \"--block-size\") == 0) ||\n (strcmp(argv[i], \"-bs\") == 0)) { // flush files after number of frames received\n num_frames_per_flush = atoi(argv[++i]);\n } else if ((strcmp(argv[i], \"--rate\") == 0) ||\n (strcmp(argv[i], \"-r\") == 0)) { // expected data rate\n nodata_timeout = 1.0e6/atof(argv[++i]);\n } else if ((strcmp(argv[i], \"--client-port\") == 0) ||\n (strcmp(argv[i], \"-p\") == 0)) { // client port\n set_linklist_client_port(atoi(argv[++i]));\n } else if ((strcmp(argv[i], \"--server-port\") == 0) ||\n (strcmp(argv[i], \"-P\") == 0)) { // server port\n set_linklist_server_port(atoi(argv[++i]));\n } else if ((strcmp(argv[i], \"--dry-run\") == 0) ||\n (strcmp(argv[i], \"-d\") == 0)) { // dry run\n dry_run = 1;\n } else if ((strcmp(argv[i], \"--map-frames\") == 0) ||\n (strcmp(argv[i], \"-m\") == 0)) { // map frames \n map_frames = 1;\n } else if ((strcmp(argv[i], \"--map-and-fill\") == 0) ||\n (strcmp(argv[i], \"-M\") == 0)) { // map frames and fill in gaps\n map_frames = 1;\n fill_in_gaps = 1;\n } else if (strcmp(argv[i], \"--port\") == 0) { // client and server port\n int port = atoi(argv[++i]);\n set_linklist_client_port(port);\n set_linklist_server_port(port);\n } else if ((strcmp(argv[i], \"--offset\") == 0) ||\n (strcmp(argv[i], \"-O\") == 0)) { // frame number offset\n offset_framenum = atoi(argv[++i]);\n printf(\"Data written at frame offset %\" PRIu64\"\\n\", offset_framenum);\n } else if ((strcmp(argv[i], \"--calspecs\") == 0) ||\n (strcmp(argv[i], \"-cs\") == 0)) { // custom calspecs file\n FILE * test_exists = fopen(argv[i+1], \"r\");\n if (test_exists) {\n strcpy(custom_calspecs, argv[++i]);\n fclose(test_exists);\n } else {\n printf(\"Calspecs file \\\"%s\\\" does not exist!\\n\", argv[++i]);\n }\n } else if ((strcmp(argv[i], \"--filename\") == 0) ||\n (strcmp(argv[i], \"-F\") == 0)) { // select file by name\n strcpy(filename_selection, argv[++i]);\n } else if ((strcmp(argv[i], \"--live-name\") == 0) ||\n (strcmp(argv[i], \"-N\") == 0)) { // name the live output file\n char * arg = argv[++i];\n if (arg[0] == '/') {\n strcpy(symraw_name, arg);\n sprintf(symdir_name, \"%s.lnk\", arg);\n } else {\n sprintf(symraw_name, \"%s/%s\", data_rawdir, arg);\n sprintf(symdir_name, \"%s/%s.lnk\", mole_dir, arg);\n }\n } else if ((strcmp(argv[i], \"--loopback\") == 0) ||\n (strcmp(argv[i], \"-L\") == 0)) { // loopback mode\n bin_backup = 0;\n strcpy(tcpconn.ip, \"localhost\");\n server_mode = 1;\n } else if (strcmp(argv[i], \"--help\") == 0) { // view usage\n USAGE();\n } else {\n printf(\"Unrecognized option \\\"%s\\\"\\n\", argv[i]);\n USAGE();\n }\n }\n\n if (archive_dir[strlen(archive_dir)-1] == '/') {\n archive_dir[strlen(archive_dir)-1] = '\\0';\n }\n if (mole_dir[strlen(mole_dir)-1] == '/') {\n mole_dir[strlen(mole_dir)-1] = '\\0';\n }\n if (bin_backup) {\n ll_rawfile_flags &= ~LL_RAWFILE_DUMMY;\n } else {\n ll_rawfile_flags |= LL_RAWFILE_DUMMY;\n }\n\n // Argument sanitization\n //\n if ((start_frame == UINT64_MAX) && (end_frame != UINT64_MAX)) {\n linklist_info(\"Must specify end frame (-E) when using start frame (-S)\\n\");\n exit(1);\n } else if (start_frame > end_frame) {\n linklist_info(\"Start frame %\"PRIu64\" is larger than end frame %\"PRIu64\".\\n\", start_frame, end_frame);\n exit(1);\n }\n\n pthread_t server_thread;\n if (server_mode) {\n // start the server to accept clients\n pthread_create(&server_thread, NULL, (void *) &linklist_server, NULL); \n }\n\n if (client_mode) {\n char linklistname[LINKLIST_MAX_FILENAME_SIZE] = {0};\n char filename[LINKLIST_MAX_FILENAME_SIZE] = {0};\n user_file_select(&tcpconn, filename_selection);\n\n while (1) {\n // display\n print_display(linklistname, recv_framenum);\n\n // the file on the server has switched, so resync \n if (resync) {\n // sync with the server and get the initial framenum\n req_serial = sync_with_server(&tcpconn, filename_selection, linklistname, tcp_flags, &superframe, &linklist);\n if (!req_serial) {\n printf(\"Failed to sync with server. Retrying...\\n\");\n resync = 1;\n continue;\n }\n req_init_framenum = initialize_client_connection(&tcpconn, req_serial);\n if (req_init_framenum < 0) {\n printf(\"Failed to initilize client connection. Retrying...\\n\");\n resync = 1;\n continue;\n }\n printf(\"Client initialized with %\" PRIi64 \" frames\\n\", req_init_framenum);\n\n // override calspecs file with custom calspecs\n if (custom_calspecs[0]) {\n strcpy(linklist->superframe->calspecs, custom_calspecs);\n printf(\"Using custom calpsecs file at \\\"%s\\\"\\n\", custom_calspecs);\n }\n\n // open linklist dirfile\n sprintf(filename, \"%s/%s\", mole_dir, linklistname);\n if (ll_dirfile) close_and_free_linklist_dirfile(ll_dirfile);\n ll_dirfile = open_linklist_dirfile_opt(filename, linklist, ll_dirfile_flags);\n if (map_frames) {\n seek_linklist_dirfile(ll_dirfile, req_init_framenum);\n map_frames_linklist_dirfile(ll_dirfile);\n }\n if (!dry_run) {\n unlink(symdir_name);\n symlink(filename, symdir_name); \n }\n\n // open the linklist rawfile\n sprintf(filename, \"%s/%s\", archive_dir, linklistname);\n if (ll_rawfile) close_and_free_linklist_rawfile(ll_rawfile);\n ll_rawfile = open_linklist_rawfile_opt(filename, linklist, ll_rawfile_flags);\n if (bin_backup) {\n create_rawfile_symlinks(ll_rawfile, symraw_name);\n }\n\n // set the first framenum request\n if (fill_in_gaps) { // filling in gaps trumps all other modes\n linklist_info(\"Filling in data gaps for dirfile %s...\\n\", ll_dirfile->filename);\n gap_count = 0;\n if (ll_dirfile->n_missing_blks) {\n req_framenum = ll_dirfile->missing_blks_start[gap_count];\n }\n } else if (start_frame != UINT64_MAX) { // user specified start\n req_framenum = start_frame;\n linklist_info(\"Reading from frame %\" PRIu64, start_frame);\n if (end_frame != UINT64_MAX) { // user specified end\n if (end_frame > req_init_framenum) end_frame = req_init_framenum;\n linklist_info(\" to %\" PRIu64\".\\n\", end_frame);\n } else {\n linklist_info(\".\\n\");\n }\n } else { // rewind mode\n req_framenum = (req_init_framenum > rewind) ? req_init_framenum-rewind : 0;\n if (!force_rewind) {\n req_framenum = MAX(req_framenum, tell_linklist_rawfile(ll_rawfile)); \n }\n linklist_info(\"Starting read from frame %\" PRIu64 \"\\n\", req_framenum); \n }\n\n if (dry_run) {\n linklist_info(\"\\nDry run complete.\\n\\n\");\n exit(0);\n }\n\n resync = 0;\n continue; \n }\n\n // gap filling mode: loop through all gaps in the dirfile \n if (fill_in_gaps) {\n if (req_framenum >= ll_dirfile->missing_blks_end[gap_count]) {\n linklist_info(\"Filled in gap [%d,%d]\\n\", ll_dirfile->missing_blks_start[gap_count],\n ll_dirfile->missing_blks_end[gap_count]);\n gap_count++;\n\n // handle gap filling termination condition\n if (gap_count < ll_dirfile->n_missing_blks) { // still have more blocks to fill\n req_framenum = ll_dirfile->missing_blks_start[gap_count];\n } else { // all missing data blocks are filled\n req_framenum = req_init_framenum;\n fill_in_gaps = 0;\n }\n }\n }\n\n // check size of the buffer and enlarge if necessary\n if (buffer_size < ll_rawfile->framesize) {\n buffer_size = ll_rawfile->framesize;\n recv_buffer = realloc(recv_buffer, buffer_size);\n }\n \n // send data request\n recv_flags = 0; \n recv_framenum = request_data(&tcpconn, req_framenum, &recv_flags);\n if ((recv_flags & TCPCONN_FILE_RESET) || (recv_framenum < 0)) { \n linklist_err(\"Data request failed\\n\");\n resync = 1;\n continue;\n }\n\n // there is no data on the server\n if (recv_flags & TCPCONN_NO_DATA) {\n usleep(nodata_timeout);\n continue;\n } \n\n // get the data from the server\n if (retrieve_data(&tcpconn, recv_buffer, ll_rawfile->framesize) < 0) {\n linklist_err(\"Data retrieve failed\\n\");\n resync = 1;\n continue;\n }\n\n /* all flags are cleared at this point */\n\n // write the dirfile\n if (ll_dirfile) {\n if (!(frame_i % num_frames_per_flush)) {\n seek_linklist_dirfile(ll_dirfile, recv_framenum + offset_framenum);\n }\n write_linklist_dirfile_opt(ll_dirfile, recv_buffer, ll_dirfile_flags);\n if (!(frame_i % num_frames_per_flush)) flush_linklist_dirfile(ll_dirfile);\n }\n\n // write the rawfile\n if (bin_backup && ll_rawfile) {\n seek_linklist_rawfile(ll_rawfile, recv_framenum + offset_framenum);\n write_linklist_rawfile_opt(ll_rawfile, recv_buffer, 0);\n if (!(frame_i % num_frames_per_flush)) flush_linklist_rawfile(ll_rawfile);\n }\n\n/* \n int i;\n for (i = 0; i < recv_size; i++) {\n if (i % 32 == 0) printf(\"\\n%.4d: \", i/32);\n printf(\"0x%.2x \", recv_buffer[i]);\n }\n printf(\"\\n\");\n*/\n if (recv_framenum >= end_frame) {\n linklist_info(\"\\n\\nFinished reading up to frame %\" PRIi64\".\\n\", recv_framenum);\n exit(0);\n }\n\n memset(recv_buffer, 0, buffer_size);\n memset(recv_header, 0, TCP_PACKET_HEADER_SIZE);\n start_frame = req_framenum;\n req_framenum++;\n frame_i++;\n }\n }\n\n if (server_mode) pthread_join(server_thread, NULL);\n}\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6831881403923035, "alphanum_fraction": 0.6901870965957642, "avg_line_length": 20.024024963378906, "blob_id": "3036fda0fbf22a239b71c7d3b3fc4af10d56c391", "content_id": "d0839f7c9eae3db39c29bfc0cc04706bc81e1bf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7002, "license_type": "no_license", "max_line_length": 73, "num_lines": 333, "path": "/stars/code/networking/xsc_protocol/xsc_protocol.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef XSC_PROTOCOL_H\n#define XSC_PROTOCOL_H\n\n#include <stdint.h>\n#ifdef _MSC_VER\n #ifndef __cplusplus\n typedef int bool;\n #define true 1\n #define false 0\n #endif\n#else\n #include <stdbool.h>\n#endif\n\n#define XSC_BLOBS_ARRAY_SIZE 20\n\n#pragma pack(push, 4)\n\n// Server Structs //\n\ntypedef struct XSCImageBlob\n{\n double x;\n double y;\n double flux;\n double peak_to_flux;\n} XSCImageBlob;\n\ntypedef struct XSCImageBlobs\n{\n int counter_stars;\n int num_blobs;\n XSCImageBlob blobs[XSC_BLOBS_ARRAY_SIZE];\n} XSCImageBlobs;\n\n\ntypedef struct\n{\n int32_t image_ctr_stars;\n int32_t image_ctr_fcp;\n int32_t ctr_stars;\n\n uint32_t stars_run_time;\n\n float hk_temp_lens;\n float hk_temp_comp;\n float hk_temp_plate;\n float hk_temp_flange;\n float hk_pressure;\n uint32_t hk_disk;\n\n uint8_t cam_gain_valid;\n float cam_gain_db;\n\n uint16_t lens_focus;\n uint16_t lens_aperture;\n\n uint16_t image_num_exposures;\n uint16_t image_stats_mean;\n uint16_t image_stats_noise;\n double image_stats_gaindb;\n int32_t image_stats_num_px_sat;\n double image_stats_frac_px_sat;\n double image_afocus_metric;\n\n uint8_t image_afocus_metric_valid;\n uint8_t image_eq_valid;\n uint8_t image_hor_valid;\n\n double image_eq_ra;\n double image_eq_dec;\n double image_eq_roll;\n double image_eq_sigma_ra;\n double image_eq_sigma_dec;\n double image_eq_sigma_roll;\n double image_eq_sigma_pointing;\n double image_eq_iplate;\n\n double image_hor_az;\n double image_hor_el;\n double image_hor_roll;\n double image_hor_sigma_az;\n double image_hor_sigma_el;\n double image_hor_sigma_roll;\n double image_hor_sigma_pointing;\n double image_hor_iplate;\n uint16_t image_num_blobs_found;\n uint16_t image_num_blobs_matched;\n\n uint32_t timestamp_s;\n\tuint32_t timestamp_us;\n} xsc_channels_t;\n\ntypedef struct XSCServerData\n{\n xsc_channels_t channels;\n XSCImageBlobs blobs;\n unsigned int xsc_protocol_version;\n}\nXSCServerData;\n\n\n// XSC enum types //\n\ntypedef enum\n{\n xC_solver_fitting_method_none=0,\n xC_solver_fitting_method_gaussian=1,\n xC_solver_fitting_method_double_gaussian=2,\n}\nxsc_solver_fitting_method_t;\n\ntypedef enum\n{\n xC_autofocus_display_mode_auto,\n xC_autofocus_display_mode_on,\n xC_autofocus_display_mode_off,\n}\nxsc_autofocus_display_mode_t;\n\n\n// Client Structs //\n\nenum\n{\n xC_quit,\n xC_shutdown,\n xC_network_reset,\n xC_main_settings,\n xC_display_zoom,\n xC_image_client,\n xC_multi_triggering,\n xC_flush_birger,\n xC_init_focus,\n xC_get_focus,\n xC_set_focus,\n xC_stop_focus,\n xC_set_focus_incremental,\n xC_define_focus,\n xC_define_aperture,\n xC_run_autofocus,\n xC_set_autofocus_range,\n xC_abort_autofocus,\n xC_autofocus_display_mode,\n xC_init_aperture,\n xC_get_aperture,\n xC_set_aperture,\n xC_stop_aperture,\n xC_get_gain,\n xC_set_gain,\n xC_brightness,\n xC_solver_general,\n xC_solver_abort,\n xC_solver_mask,\n xC_solver_blob_finder,\n xC_solver_blob_cells,\n xC_solver_pattern_matcher,\n xC_solver_filter_hor_location,\n xC_solver_filter_hor_roll,\n xC_solver_filter_hor_el,\n xC_solver_filter_eq_location,\n xC_solver_filter_matching,\n\n xC_num_command_admins\n};\n\ntypedef struct\n{\n unsigned int is_new_countdown;\n int counter;\n}\nxsc_command_admin_t;\n\ntypedef struct XSCFilters\n{\n bool hor_location_limit_enabled;\n double hor_location_limit_radius;\n double hor_location_limit_az;\n double hor_location_limit_el;\n\n bool hor_roll_limit_enabled;\n double hor_roll_limit_min;\n double hor_roll_limit_max;\n\n bool hor_el_limit_enabled;\n double hor_el_limit_min;\n double hor_el_limit_max;\n\n bool eq_location_limit_enabled;\n double eq_location_limit_radius;\n double eq_location_limit_ra;\n double eq_location_limit_dec;\n\n double matching_pointing_error_threshold;\n double matching_fit_error_threshold_px;\n unsigned int matching_num_matched;\n\n} XSCFilters;\n\ntypedef struct XSCSolverMask\n{\n bool enabled;\n unsigned int field0;\n unsigned int field1;\n unsigned int field2;\n} XSCSolverMask;\n\n\ntypedef struct XSCSolver\n{\n bool enabled;\n double timeout;\n XSCSolverMask mask;\n\n double snr_threshold;\n int max_num_blobs;\n bool robust_mode_enabled;\n xsc_solver_fitting_method_t fitting_method;\n unsigned int cell_size;\n unsigned int max_num_blobs_per_cell;\n\n bool pattern_matcher_enabled;\n bool display_star_names;\n double match_tolerance_px;\n double iplatescale_min;\n double iplatescale_max;\n bool platescale_always_fixed;\n double iplatescale_fixed;\n\n XSCFilters filters;\n}\nXSCSolver;\n\ntypedef struct XSCBrightness\n{\n int counter;\n bool enabled;\n double level_kepsa;\n double gain_db;\n double actual_exposure;\n double simulated_exposure;\n} XSCBrightness;\n\ntypedef struct XSCShutdown\n{\n int counter;\n bool shutdown_now;\n bool include_restart;\n} XSCShutdown;\n\ntypedef struct XSCNetworkReset\n{\n bool reset_now;\n bool reset_on_lull_enabled;\n double reset_on_lull_delay;\n}\nXSCNetworkReset;\n\ntypedef struct XSCMainSettings\n{\n int counter;\n double display_frequency;\n bool display_fullscreen;\n bool display_image_only;\n bool display_solving_filters;\n double display_image_brightness;\n int display_zoom_x;\n int display_zoom_y;\n double display_zoom_magnitude;\n}\nXSCMainSettings;\n\ntypedef struct XSCHorizontal\n{\n bool valid;\n double lat;\n double lst;\n} XSCHorizontal;\n\ntypedef struct XSCClientData\n{\n bool in_charge;\n int counter_fcp;\n\n int quit_counter;\n XSCShutdown shutdown;\n XSCNetworkReset network_reset;\n XSCMainSettings main_settings;\n bool image_client_enabled;\n\n double multi_triggering_readout_delay;\n\n int set_focus_value;\n int set_focus_incremental_value;\n int define_focus_value;\n int autofocus_search_min;\n int autofocus_search_max;\n int autofocus_search_step;\n bool abort_autofocus_still_use_solution;\n xsc_autofocus_display_mode_t autofocus_display_mode;\n int set_aperture_value;\n double set_gain_value;\n int define_aperture_value;\n\n XSCBrightness brightness;\n XSCSolver solver;\n XSCHorizontal horizontal;\n\n xsc_command_admin_t command_admins[xC_num_command_admins];\n\n unsigned int xsc_protocol_version;\n\n\tunsigned int heater_state;\n}\nXSCClientData;\n\nvoid xsc_clear_server_data(XSCServerData* server_data);\nvoid xsc_clear_client_data(XSCClientData* client_data);\nvoid xsc_decrement_is_new_countdowns(XSCClientData* client_data);\nvoid xsc_zero_command_admins(xsc_command_admin_t* admins);\nvoid xsc_init_server_data(XSCServerData* server_data);\n\n#pragma pack(pop)\n\n\n#endif\n" }, { "alpha_fraction": 0.6388888955116272, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 23, "blob_id": "8b50925852aab59146414e69b16c2c0619700a9a", "content_id": "b8a68cbb4303858ae5705bf534c5377d693ac050", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 144, "license_type": "no_license", "max_line_length": 66, "num_lines": 6, "path": "/stop_blast_fcs.sh", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\nSTOP_CMD=\"sudo pkill blast_inf_loop; sudo kill -INT \\$(pidof mcp)\"\n\nssh -t fc1user@fc1 \"$STOP_CMD\"\nssh -t fc1user@fc2 \"$STOP_CMD\"\n" }, { "alpha_fraction": 0.7104496955871582, "alphanum_fraction": 0.7188612222671509, "avg_line_length": 30.86598014831543, "blob_id": "91819234a9c9efaecaa67bdbdd4bfb452e00aef9", "content_id": "b02cdd458223a7267fe75d877ddef2f88a8812e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3091, "license_type": "no_license", "max_line_length": 79, "num_lines": 97, "path": "/owl/PAbstractDataItem.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"PObject.h\"\n#include \"PStyle.h\"\n#include <QWidget>\n#include <QHBoxLayout>\n#include <QLabel>\n#include <getdata/dirfile.h>\n\n#ifndef PABSTRACTDATAITEM_H\n#define PABSTRACTDATAITEM_H\n\nclass PMdiArea;\nclass PBox;\n\nclass PAbstractDataItem : public QWidget, public PObject\n{\n Q_OBJECT\nprotected:\n QHBoxLayout* _layout;\n QLabel* _caption;\n PStyle* _captionStyle;\n PStyle* _defaultDataStyle;\n PStyle* _lastCapStyle;\n\n QLabel* _data;\n QString _source;\n QPoint _dragStartPos;\n int _serverDirty;\n bool _neverGood;\n bool _sourceBad;\n\npublic:\n friend class PBox;\n friend class PMainWindow;\n friend QDataStream& operator<<(QDataStream&a,PAbstractDataItem&b);\n friend QDataStream& operator>>(QDataStream&a,PAbstractDataItem&b);\n friend QVariant save(PAbstractDataItem&);\n friend void load(QVariant v,PAbstractDataItem&);\n\n PAbstractDataItem(PBox* parent, QString caption);\n PAbstractDataItem(PBox* parent, PAbstractDataItem* other);\n virtual void gdUpdate(GetData::Dirfile*,int){}\n virtual double gdReadRawData(GetData::Dirfile* df,int nf, bool &ok);\n QString caption() const;\n const PStyle* captionStyle() const { return _captionStyle; }\n const PStyle* defaultDataStyle() const { return _defaultDataStyle; }\n QString data() const;\n QString source() const;\n void mousePressEvent(QMouseEvent *);\n void mouseMoveEvent(QMouseEvent*);\n void mouseDoubleClickEvent(QMouseEvent*);\n virtual QString format() { return \"???\"; }\n virtual PStyle* getPrevDataStyle() { return _defaultDataStyle; }\n void resetSource() {_neverGood = true; _sourceBad = false;}\n int delaysThisCycle();\n void incrementDelays();\n static void newCycle();\n\npublic slots:\n void setCaption(QString x, bool force=0);\n void pstyleLogic();\n void setSource(QString x, bool force=0);\n virtual void setFormat(QString,bool force=0){Q_UNUSED(force)}\n virtual void activate();\n\nsignals:\n void activated();\n void textChanged(QString);\n void sourceChanged(QString);\n void formatChanged(QString);\n void styleChanged(); \n};\n\nQDataStream& operator<<(QDataStream&a,PAbstractDataItem&b);\nQDataStream& operator>>(QDataStream&a,PAbstractDataItem&b);\n\n#endif // PABSTRACTDATAITEM_H\n" }, { "alpha_fraction": 0.6796537041664124, "alphanum_fraction": 0.6883116960525513, "avg_line_length": 20, "blob_id": "e1edde7a94250b47792e4828ab12b040761e432d", "content_id": "68f456badab77751d9606bb131d8373928a24aff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 463, "license_type": "no_license", "max_line_length": 73, "num_lines": 22, "path": "/stars/code/imaging/logger_camera.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef IMAGING__LOGGER_CAMERA_H\n#define IMAGING__LOGGER_CAMERA_H\n\n#include \"../logging/logger.h\"\n\nnamespace Imaging\n{\n namespace Cameraing\n {\n // To be used only by the camera thread\n extern Logging::Logger logger;\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.7144959568977356, "alphanum_fraction": 0.7380426526069641, "avg_line_length": 31.35714340209961, "blob_id": "7fd93c16dd9aa513821acaee7cece11c41296273", "content_id": "14b0cf3e1b72d6174cab557fb64985853e75af09", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1359, "license_type": "no_license", "max_line_length": 77, "num_lines": 42, "path": "/defricher/defricher_writer.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * defricher_writer.h: \n *\n * This software is copyright (C) 2013-2014 Seth Hillbrand\n *\n * This file is part of defricher, created for the BLASTPol Project.\n *\n * defricher 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 2 of the License, or\n * (at your option) any later version.\n *\n * defricher 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 defricher; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Apr 6, 2015 by Seth Hillbrand\n */\n\n#ifndef DEFRICHER_WRITER_H_\n#define DEFRICHER_WRITER_H_\n\n#include <stdint.h>\n#include <glib.h>\n\nextern channel_t *channels;\nextern channel_t *new_channels;\nextern derived_tng_t *derived_channels;\n\npthread_t defricher_writer_init(void);\nvoid defricher_queue_packet(uint16_t m_rate);\nvoid defricher_request_new_dirfile(void);\nvoid defricher_request_updated_derived(void);\nbool ready_to_read(uint16_t m_rate);\n\n#endif /* DEFRICHER_WRITER_H_ */\n" }, { "alpha_fraction": 0.6717557311058044, "alphanum_fraction": 0.694656491279602, "avg_line_length": 15.25, "blob_id": "c4464ca6e3ab05a1d65bfc793235e59564b63c4a", "content_id": "c021c55e893914e94d3f5573f5f0fef4b1697487", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 131, "license_type": "no_license", "max_line_length": 40, "num_lines": 8, "path": "/cathy/Makefile", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "cathy: cathy.c\n\tgcc -Wall -g -o cathy cathy.c -lgetdata\n\ninstall: cathy\n\tinstall -m 755 cathy /usr/local/bin\n\nclean:\n\trm -f cathy\n\n" }, { "alpha_fraction": 0.5891838073730469, "alphanum_fraction": 0.6045926213264465, "avg_line_length": 31.183643341064453, "blob_id": "8989db0c691be183c1ef08c986dbc7a75ff3ef3c", "content_id": "22692077602c23bf04e6cd92d4b67838626825ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 43287, "license_type": "no_license", "max_line_length": 136, "num_lines": 1345, "path": "/liblinklist/linklist.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * linklist.c: \n *\n * This software is copyright \n * (C) 2015-2018 University of Toronto, Toronto, ON\n *\n * This file is part of the SuperBIT project, modified and adapted for BLAST-TNG.\n *\n * linklist 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 2 of the License, or\n * (at your option) any later version.\n *\n * linklist 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Jan 25, 2018 by Javier Romualdez\n */\n/**\n * Description:\n *\n * This file contains functions for parsing and initializing linklist\n * files, which are used for the entry selection and compression of\n * BLAST frames over telemetry downlinks.\n */\n\n#include <math.h>\n#include <arpa/inet.h> // socket stuff\n#include <netinet/in.h> // socket stuff\n#include <stdio.h> // socket stuff\n#include <sys/types.h> // socket types\n#include <sys/socket.h> // socket stuff\n#include <sys/stat.h>\n#include <dirent.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <signal.h>\n#include <stdlib.h>\n#include <string.h>\n#include <pthread.h> // threads\n#include <openssl/md5.h>\n#include <float.h>\n#include <ctype.h>\n\n#include \"linklist.h\"\n#include \"linklist_compress.h\"\n\n#define COMM '#'\n#define SPEC ':'\n#define MULT '|'\n#define DESC '\"'\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n// user override-able functions for printfs\nint (*linklist_info)(const char *, ...) = printf;\nint (*linklist_err)(const char *, ...) = printf;\nint (*linklist_warn)(const char *, ...) = printf;\nint (*linklist_fatal)(const char *, ...) = printf;\n\nint num_compression_routines = 0; // number of compression routines available\nsuperframe_entry_t block_entry; // a dummy entry for blocks\nsuperframe_entry_t stream_entry; // a dummy entry for streams\nunsigned int ll_rawfile_default_fpf = 900; // number of frames per file before incrementing linklist rawfiles\nchar archive_dir[LINKLIST_MAX_FILENAME_SIZE] = \"/data/rawdir\";\n\nstatic char * def_ll_extensions[] = {\".ll\", LINKLIST_FORMAT_EXT, \"\"}; \n\nconst char * SF_TYPES_STR[] = {\n \"UINT8\", \"UINT16\", \"UINT32\", \"UINT64\", \n \"INT8\", \"INT16\", \"INT32\", \"INT64\", \n \"FLOAT32\", \"FLOAT64\", \"BLOCK\", \"STREAM\"\n};\nconst char * get_sf_type_string(uint8_t m_type)\n{\n return SF_TYPES_STR[m_type];\n}\n\nuint8_t get_sf_type_int(char * str) {\n int i = 0;\n \n for (i = 0; SF_TYPES_STR[i][0]; i++) {\n if (strncmp(str, SF_TYPES_STR[i], strlen(SF_TYPES_STR[i])) == 0) break;\n }\n return i;\n}\n\nint hashkey = 5381;\n\n//Implements the djb2 hashing algorithm for char*s \nunsigned int hash(const char* input){\n int returnVal = hashkey;\n int c;\n\n while ((c = *input++))\n returnVal = ((returnVal << 5) + returnVal) + c;\n\n return returnVal;\n}\n\ndouble def_datatodouble(uint8_t * data, uint8_t type)\n{\n switch (type) {\n case SF_FLOAT64 : return (*((double *) data));\n case SF_FLOAT32 : return (*((float *) data));\n case SF_INT16 : return (int16_t) (*((int16_t *) data));\n case SF_UINT16 : return (*((uint16_t *) data));\n case SF_INT32 : return (int32_t) (*((int32_t *) data));\n case SF_UINT32 : return (*((uint32_t *) data));\n case SF_INT8 : return *((int8_t *) data);\n case SF_UINT8 : return *((uint8_t *) data);\n default : return 0;\n }\n return 0;\n}\nint def_doubletodata(uint8_t * data, double dub, uint8_t type)\n{\n if (type == SF_FLOAT64)\n {\n *(double *) data = dub;\n return 8;\n } else if (type == SF_FLOAT32) {\n *(float *) data = dub;\n return 4;\n } else if (type == SF_INT16) {\n int16_t s = dub;\n *(int16_t*) data = s;\n return 2;\n } else if (type == SF_UINT16) {\n uint16_t u = dub;\n *(uint16_t*) data = u;\n return 2;\n } else if (type == SF_INT32) {\n int32_t i = dub;\n *(int32_t*) data = i;\n return 4;\n } else if (type == SF_UINT32) {\n uint32_t i = dub;\n *(uint32_t*) data = i;\n return 4;\n } else if (type == SF_INT8) {\n *(int8_t*) data = dub;\n return 1;\n } else if (type == SF_UINT8) {\n *(uint8_t*) data = dub;\n return 1;\n }\n return 0;\n}\n\ndouble def_datatodouble_be(uint8_t * data, uint8_t type)\n{\n switch (type) {\n case SF_FLOAT64 : return bedtoh(*((double *) data));\n case SF_FLOAT32 : return beftoh(*((float *) data));\n case SF_INT16 : return (int16_t) be16toh(*((int16_t *) data));\n case SF_UINT16 : return be16toh(*((uint16_t *) data));\n case SF_INT32 : return (int32_t) be32toh(*((int32_t *) data));\n case SF_UINT32 : return be32toh(*((uint32_t *) data));\n case SF_INT8 : return *((int8_t *) data);\n case SF_UINT8 : return *((uint8_t *) data);\n default : return 0;\n }\n return 0;\n}\nint def_doubletodata_be(uint8_t * data, double dub, uint8_t type)\n{\n if (type == SF_FLOAT64) {\n htobed(dub, *(uint64_t*) data);\n return 8;\n } else if (type == SF_FLOAT32) {\n htobef(dub, *(uint32_t*) data)\n return 4;\n } else if (type == SF_INT16) {\n int16_t s = dub;\n *(int16_t*) data = htobe16(s);\n return 2;\n } else if (type == SF_UINT16) {\n uint16_t u = dub;\n *(uint16_t*) data = htobe16(u);\n return 2;\n } else if (type == SF_INT32) {\n int32_t i = dub;\n *(int32_t*) data = htobe32(i);\n return 4;\n } else if (type == SF_UINT32) {\n uint32_t i = dub;\n *(uint32_t*) data = htobe32(i);\n return 4;\n } else if (type == SF_INT8) {\n *(int8_t*) data = dub;\n return 1;\n } else if (type == SF_UINT8) {\n *(uint8_t*) data = dub;\n return 1;\n }\n return 0;\n}\n\nvoid linklist_assign_datatodouble(superframe_t * superframe, double (*func)(uint8_t *, uint8_t)) {\n if (func) {\n superframe->datatodouble = func;\n } else {\n superframe->datatodouble = &def_datatodouble;\n }\n}\nvoid linklist_assign_doubletodata(superframe_t * superframe, int (*func)(uint8_t *, double, uint8_t)) {\n if (func) {\n superframe->doubletodata = func;\n } else {\n superframe->doubletodata = &def_doubletodata;\n }\n}\n\nsuperframe_t * linklist_build_superframe(superframe_entry_t* m_superframe_list, \n double (*datatodouble)(uint8_t *, uint8_t), \n int (*doubletodata)(uint8_t *, double, uint8_t),\n unsigned int flags) {\n\n superframe_t * superframe = (superframe_t *) calloc(1, sizeof(superframe_t)); \n\n superframe->entries = m_superframe_list;\n linklist_assign_datatodouble(superframe, datatodouble);\n linklist_assign_doubletodata(superframe, doubletodata);\n superframe->size = 0;\n superframe->n_entries = 0;\n superframe->flags = flags;\n\n int i = 0;\n for (i = 0; superframe->entries[i].field[0]; i++) {\n superframe->size += get_superframe_entry_size(&superframe->entries[i])*superframe->entries[i].spf;\n superframe->entries[i].superframe = superframe; // reference superframe\n superframe->n_entries++;\n }\n\n superframe->hash_table_size = superframe->n_entries*1000;\n superframe->hash_table = (superframe_entry_t **) calloc(superframe->hash_table_size, sizeof(superframe_entry_t *));\n \n for (i = 0; i < (int) superframe->n_entries; i++) {\n unsigned int hashloc = hash(superframe->entries[i].field)%superframe->hash_table_size;\n if (superframe->hash_table[hashloc]) {\n memset(superframe->hash_table, 0, sizeof(superframe_entry_t *)*superframe->hash_table_size);\n hashkey = (hashkey*137)&0xffff;\n linklist_err(\"Hash with entry \\\"%s\\\". Trying key %d\\n\", superframe->entries[i].field, hashkey);\n i = -1;\n } else {\n superframe->hash_table[hashloc] = &superframe->entries[i];\n }\n }\n\n superframe->serial = generate_superframe_serial(superframe);\n superframe->allframe_size = write_allframe(NULL, superframe, NULL);\n\n return superframe;\n}\n\nsuperframe_entry_t * superframe_find_by_name(superframe_t * sf, const char * name) {\n if (!name) return NULL;\n\n return sf->hash_table[hash(name)%sf->hash_table_size];\n}\n\nvoid realloc_list(linklist_t * ll, int * x)\n{\n *x += 100;\n ll->items = (linkentry_t *) realloc(ll->items,(*x)*(sizeof(linkentry_t)));\n}\n\nvoid parse_line(char *line, char ** sinks, unsigned int nargs)\n{\n int i, j;\n unsigned int n;\n int read = strlen(line);\n \n for (n=0;n<nargs;n++) sinks[n] = NULL;\n \n char * buffer = (char *) calloc(2*read,1);\n int quoteon = 0; \n\n n = 0;\n j = 0;\n sinks[n++] = &line[j];\n \n for (i=0;i<read;i++)\n {\n while (((line[i] == ' ') || (line[i] == '\\t')) && (n<nargs) && !quoteon)\n {\n i++;\n // concatenate args separated by MULT symbol\n if ((line[i] != ' ') && (line[i] != '\\t') && \n (line[i] != MULT) && (buffer[j-1] != MULT) &&\n (line[i] != '=') && (buffer[j-1] != '='))\n {\n buffer[j++] = '\\0';\n sinks[n++] = &line[j];\n }\n }\n if (line[i] != DESC) buffer[j++] = line[i];\n else quoteon = 1-quoteon; \n }\n for (i=n;((unsigned int)i)<nargs;i++) sinks[i] = &line[j];\n buffer[j++] = '\\0';\n memcpy(line,buffer,j+1);\n free(buffer);\n \n}\n\nstatic int one (const struct dirent * unused)\n{\n (void) unused;\n return 1;\n}\n\nint load_all_linklists(superframe_t * superframe, char * linklistdir, linklist_t ** ll_array, unsigned int flags) {\n return load_all_linklists_opt(superframe, linklistdir, ll_array, flags, NULL);\n}\nint load_all_linklists_opt(superframe_t * superframe, char * linklistdir, linklist_t ** ll_array, unsigned int flags, char ** exts) {\n if (!exts) exts = def_ll_extensions;\n\n struct dirent **dir;\n int n = scandir(linklistdir,&dir,one,alphasort);\n int i, j;\n int num = 0;\n\n if (n<0) { \n linklist_fatal(\"Cannot open the linklists directory %s\", linklistdir);\n } else if (n>=MAX_NUM_LINKLIST_FILES) { \n linklist_fatal(\"Max linklists in %s\\n\",linklistdir);\n }\n \n // check to see if there are already linklists allocated\n i = 0;\n while (ll_array[i]) {\n delete_linklist(ll_array[i]);\n ll_array[i] = 0;\n i++;\n }\n\n char full_path_name[LINKLIST_MAX_FILENAME_SIZE] = {0};\n\n // load linklist names\n for (i = 0; i < n; i++) {\n int len = strlen(dir[i]->d_name);\n for (j=0; exts[j][0]; j++) {\n int extlen = strlen(exts[j]);\n if ((len >= extlen) && strcmp(&dir[i]->d_name[len-extlen], exts[j]) == 0) {\n snprintf(full_path_name, LINKLIST_MAX_FILENAME_SIZE, \"%s%s\",linklistdir, dir[i]->d_name);\n \n if ((ll_array[num] = parse_linklist_format_opt(superframe, full_path_name, flags)) == NULL) {\n linklist_fatal(\"Unable to load linklist at %s\", full_path_name);\n }\n num++;\n break;\n }\n }\n }\n ll_array[num] = generate_superframe_linklist_opt(superframe, flags); // last linklist contains all the telemetry items\n ll_array[num+1] = NULL; // null terminate the list\n\n linklist_info(\"Total of %d linklists loaded from \\\"%s\\\"\\n\", num, linklistdir);\n\n return 1;\n}\n\nint linklist_find_id_by_name(char * name, linklist_t ** ll_array) {\n linklist_t * ll = ll_array[0];\n int i = 0;\n\n while (ll) {\n if (strcmp(ll->name, name) == 0) return i;\n ll = ll_array[++i];\n }\n // linklist_err(\"Linklist \\\"%s\\\" not found.\\n\", name);\n\n return -1;\n}\n\nlinklist_t * linklist_find_by_name(char * name, linklist_t ** ll_array) {\n int i = linklist_find_id_by_name(name, ll_array);\n if (i >= 0) return ll_array[i];\n return NULL;\n}\n\nint set_checksum_field(linkentry_t * le, unsigned int byteloc)\n{\n int blk_size = 2; // checksums are 16 bit\n\n le->tlm = NULL; // no tlm\n le->comp_type = 255; // arbitrary\n le->start = byteloc;\n le->num = 1; // only one \n le->blk_size = blk_size;\n\n return blk_size;\n}\n\nint superframe_entry_get_index(superframe_entry_t * sfi, superframe_entry_t * sf) {\n long unsigned int item = (long unsigned int) sfi;\n long unsigned int base = (long unsigned int) sf;\n if (item < base) return -1;\n return (item-base)/sizeof(superframe_entry_t);\n}\n\nvoid update_linklist_hash(MD5_CTX *mdContext, linkentry_t * le)\n{\n MD5_Update(mdContext, &le->start, sizeof(le->start));\n MD5_Update(mdContext, &le->comp_type, sizeof(le->comp_type));\n MD5_Update(mdContext, &le->blk_size, sizeof(le->blk_size));\n MD5_Update(mdContext, &le->num, sizeof(le->num));\n}\n\nvoid update_superframe_entry_hash(MD5_CTX *mdContext, superframe_entry_t * chan)\n{\n MD5_Update(mdContext, chan->field, SF_FIELD_LEN);\n MD5_Update(mdContext, &chan->type, sizeof(chan->type));\n MD5_Update(mdContext, &chan->spf, sizeof(chan->spf));\n MD5_Update(mdContext, &chan->start, sizeof(chan->start));\n MD5_Update(mdContext, &chan->skip, sizeof(chan->skip));\n}\n\nint parse_block(linklist_t * ll, char * name)\n{\n if (ll->num_blocks >= MAX_DATA_BLOCKS) {\n linklist_err(\"parse_block: cannot add \\\"%s\\\"; maximum data blocks (%d)\\n\", \n name, MAX_DATA_BLOCKS);\n return -1;\n }\n\n strcpy(ll->blocks[ll->num_blocks].name, name);\n ll->blocks[ll->num_blocks].id = 0; // use id as block send count\n ll->blocks[ll->num_blocks].buffer = (uint8_t *) calloc(1, DEF_BLOCK_ALLOC);\n ll->blocks[ll->num_blocks].alloc_size = DEF_BLOCK_ALLOC;\n ll->blocks[ll->num_blocks].le = &(ll->items[ll->n_entries]);\n ll->blocks[ll->num_blocks].i = 1; // inits\n ll->blocks[ll->num_blocks].n = 1; // inits\n ll->blocks[ll->num_blocks].num = 0; // inits\n\n ll->blocks[ll->num_blocks].filename[0] = 0; // inits\n ll->blocks[ll->num_blocks].fp = NULL; // inits\n\n return ll->num_blocks++;\n}\n\nint parse_stream(linklist_t * ll, char * name)\n{\n if (ll->num_streams >= MAX_DATA_STREAMS) {\n linklist_err(\"parse_stream: cannot add \\\"%s\\\"; maximum data streams (%d)\\n\", \n name, MAX_DATA_STREAMS);\n return -1;\n }\n\n int ind = ll->num_streams;\n strcpy(ll->streams[ind].name, name);\n ll->streams[ind].le = &(ll->items[ll->n_entries]);\n\n int i;\n for (i=0; i<2; i++) {\n ll->streams[ind].buffers[i].data_size = 0;\n ll->streams[ind].buffers[i].loc = 0;\n ll->streams[ind].buffers[i].buffer = (uint8_t *) calloc(1, DEF_STREAM_ALLOC);\n ll->streams[ind].buffers[i].alloc_size = DEF_STREAM_ALLOC;\n }\n\n ll->streams[ind].curr = 0;\n ll->streams[ind].next = 0;\n\n return ll->num_streams++;\n}\n\nblock_t * linklist_find_block_by_pointer(linklist_t * ll, linkentry_t * le)\n{\n int i;\n for (i = 0; i < (int) ll->num_blocks; i++) {\n if (ll->blocks[i].le == le) return &ll->blocks[i];\n }\n return NULL;\n}\nstream_t * linklist_find_stream_by_pointer(linklist_t * ll, linkentry_t * le)\n{\n int i;\n for (i = 0; i < (int) ll->num_streams; i++) {\n if (ll->streams[i].le == le) return &ll->streams[i];\n }\n return NULL;\n}\n\nuint32_t get_superframe_entry_size(superframe_entry_t * chan) {\n if (!chan) return 0;\n size_t retsize = 0;\n\n switch (chan->type) {\n case SF_INT8:\n case SF_UINT8:\n case SF_NUM:\n case SF_INF:\n retsize = 1;\n break;\n case SF_INT16:\n case SF_UINT16:\n retsize = 2;\n break;\n case SF_INT32:\n case SF_UINT32:\n case SF_FLOAT32:\n retsize = 4;\n break;\n case SF_INT64:\n case SF_UINT64:\n case SF_FLOAT64:\n retsize = 8;\n break;\n default:\n linklist_fatal(\"Invalid channel size for %s!\\n\", chan->field);\n }\n return retsize;\n}\n\nint linklist_get_comp_index(char * name) {\n int i;\n for (i=0; i<NUM_COMPRESS_TYPES; i++) {\n if (strcmp(name, compRoutine[i].name) == 0) break;\n }\n if (i != NUM_COMPRESS_TYPES) {\n return i;\n } else {\n linklist_err(\"Could not find compression type \\\"%s\\\"\\n\", name);\n return NO_COMP;\n }\n}\n\nint linklist_get_default_compression(superframe_entry_t * tlm, int flags) {\n // with the LL_AUTO_FLOAT_COMP flag, floats are automatically compressed to fixed point\n // 32 bit float => 16 bit fixed point\n // 64 bit float => 32 bit fixed point\n if ((flags & LL_AUTO_FLOAT_COMP) && tlm &&\n ((tlm->max != 0) || (tlm->min != 0))) {\n if (tlm->type == SF_FLOAT32) {\n return (enum dataCompressTypes) FIXED_PT_16BIT; \n } else if (tlm->type == SF_FLOAT64) {\n return (enum dataCompressTypes) FIXED_PT_32BIT;\n }\n }\n // the default without special flags is no compression\n return NO_COMP;\n}\n\nchar * strip_path(char * fname) {\n int i;\n for (i = strlen(fname)-1; i > 0; i--) {\n if (fname[i] == '/') { // got the filename\n i++;\n break;\n }\n }\n return (fname+i);\n}\n/**\n * parse_linklist_format_opt\n * \n * Returns a pointer to a linklist parsed from file.\n * -> fname: path to linklist to be parsed\n */\n\nlinklist_t * parse_linklist_format(superframe_t * superframe, char *fname) {\n return parse_linklist_format_opt(superframe, fname, 0);\n}\n\nlinklist_t * parse_linklist_format_opt(superframe_t * superframe, char *fname, int flags)\n{\n // count the number of compression routines available\n if (num_compression_routines == 0) {\n int c = 0;\n while (strlen(compRoutine[c].name)) c++;\n num_compression_routines = c;\n }\n if (superframe == NULL) {\n linklist_err(\"parse_linklist_format: superframe is null\\n\");\n return NULL;\n }\n\n FILE * cf = fopen(fname,\"r\"); \n if (cf == NULL) {\n linklist_err(\"parse_linklist_format: cannot find %s\\n\",fname);\n return NULL; \n }\n\n int i, st;\n int read;\n char *line = NULL;\n size_t len = 0;\n\n uint8_t comp_type;\n uint32_t blk_size, num;\n uint32_t byteloc = 0;\n unsigned int chksm_count = 0;\n\n char *temps[20];\n int def_n_entries = 150;\n int optflag = 1;\n\n // allocate new linklist with entries and assign superframe\n linklist_t * ll = (linklist_t *) calloc(1,sizeof(linklist_t));\n ll->items = (linkentry_t *) calloc(def_n_entries,sizeof(linkentry_t));\n ll->superframe = superframe;\n\n // allocate extended types\n ll->blocks = (struct block_container *) calloc(MAX_DATA_BLOCKS, sizeof(struct block_container));\n ll->num_blocks = 0;\n ll->streams = (struct stream_container *) calloc(MAX_DATA_STREAMS, sizeof(struct stream_container));\n ll->num_streams = 0;\n\n // MD5 hash\n MD5_CTX mdContext;\n uint8_t md5hash[MD5_DIGEST_LENGTH] = {0};\n MD5_Init(&mdContext); // initialize hash\n\n // initial field for first checksum\n blk_size = set_checksum_field(&(ll->items[ll->n_entries]),byteloc);\n update_linklist_hash(&mdContext,&ll->items[ll->n_entries]);\n byteloc += blk_size;\n ll->n_entries++;\n\n while ((read = getline(&line, &len, cf)) != -1) {\n // remove carriage return, trailing whitespace, etc\n line[read-1] = 0;\n read--;\n for (i = (read-1); i >= 0; i--) {\n if ((line[i] != ' ') && (line[i] != '\\t')) break;\n else line[i] = 0;\n }\n read = i+1;\n \n if ((int) ll->n_entries >= (def_n_entries-1)) {\n realloc_list(ll,&def_n_entries);\n }\n\n // remove whitespace\n st = 0;\n while ((line[st] == '\\t') || (line[st] == ' ')) st++;\n if ((line[st] != COMM) && (line[st] != '\\n') && ((read-st) > 0)) { // skip comments and blank lines\n // check for options at the beginning of file\n if (optflag) {\n // check for auto checksum field\n if (strncmp(line+st, STR(LL_NO_AUTO_CHECKSUM), strlen(STR(LL_NO_AUTO_CHECKSUM))) == 0) {\n flags |= LL_NO_AUTO_CHECKSUM; \n continue;\n }\n }\n optflag = 0;\n\n // add min checksum if necessary\n if ((chksm_count >= MIN_CHKSM_SPACING) && !(flags & LL_NO_AUTO_CHECKSUM)) {\n blk_size = set_checksum_field(&(ll->items[ll->n_entries]),byteloc);\n update_linklist_hash(&mdContext,&ll->items[ll->n_entries]);\n byteloc += blk_size;\n ll->n_entries++;\n chksm_count = 0;\n } \n\n parse_line(line+st,temps,6);\n memset(&ll->items[ll->n_entries],0,sizeof(linkentry_t));\n\n if (strcmp(temps[0], LL_PARSE_CHECKSUM) == 0) { // special checksum field indicator\n blk_size = set_checksum_field(&(ll->items[ll->n_entries]),byteloc);\n chksm_count = 0;\n } else { // not a checksum field\n superframe_entry_t * chan = NULL;\n if (strcmp(temps[1], \"B\") == 0) { // blocks extended extended item\n chan = &block_entry; // dummy entry associated with block\n parse_block(ll, temps[0]);\n comp_type = NO_COMP;\n } else if (strcmp(temps[1], \"S\") == 0) { // streams extended item \n chan = &stream_entry; // dummy entry associated with stream\n parse_stream(ll, temps[0]);\n comp_type = NO_COMP;\n } else { // just a normal field\n // find the entry in the superframe\n if (!(chan = superframe_find_by_name(superframe, temps[0]))) {\n linklist_err(\"**** parse_linklist_format (%s): unable to find telemetry entry %s ****\\n\",\n fname, temps[0]);\n continue;\n }\n\n // compression can be:\n // - NONE: no compression\n // - ##: compression indexed by number in compRoutines\n // - name: compression indicated by name in compRoutines\n if ((strcmp(temps[1], \"NONE\") == 0) || (strlen(temps[1]) == 0)) {\n comp_type = linklist_get_default_compression(chan, flags);\n } else if (strspn(temps[1], \"0123456789\") == strlen(temps[1])) { // normal field, number\n comp_type = atoi(temps[1]); // get compression type\n } else { // normal field, string\n comp_type = linklist_get_comp_index(temps[1]);\n }\n // check that comp_type is within range\n if ((comp_type >= num_compression_routines) && (comp_type != NO_COMP)) {\n linklist_err(\"Invalid comp. type %d for \\\"%s\\\". Defaulting to uncompressed.\\n\",\n comp_type, chan->field);\n comp_type = NO_COMP;\n }\n }\n\n // we know the superframe entry associated with the linklist entry, so update the hash\n update_superframe_entry_hash(&mdContext, chan);\n ll->items[ll->n_entries].tlm = chan;\n\n // get compressed samples per frame\n if ((strcmp(temps[2], \"NONE\") == 0) || (strlen(temps[2]) == 0)) {\n num = chan->spf; // no compression means same number as superframe entry\n } else {\n num = atoi(temps[2]); // get compressed samples per frame \n }\n\n // fill the link entry structure\n ll->items[ll->n_entries].comp_type = comp_type;\n ll->items[ll->n_entries].start = byteloc;\n ll->items[ll->n_entries].num = num;\n ll->items[ll->n_entries].linklist = ll;\n\n // determine size of entry in the frame\n blk_size = 0;\n if (comp_type != NO_COMP) { // normal compressed field\n blk_size = (*compRoutine[comp_type].compressFunc)(NULL, &ll->items[ll->n_entries], NULL);\n } else { // no compression, so identical field to telemlist, but with decimation\n blk_size = num*get_superframe_entry_size(ll->items[ll->n_entries].tlm);\n }\n\n // assign blk_size bytes to entry in the frame\n if (blk_size > 0) {\n ll->items[ll->n_entries].blk_size = blk_size;\n } else {\n linklist_err(\"parse_linklist_format: zero compressed size for %s in %s\\n\",\n ll->items[ll->n_entries].tlm->field,fname);\n }\n }\n\n // update the serial\n update_linklist_hash(&mdContext,&ll->items[ll->n_entries]);\n byteloc += blk_size;\n chksm_count += blk_size;\n ll->n_entries++;\n }\n }\n fclose(cf);\n\n // check memory allocation\n if ((int) ll->n_entries >= (def_n_entries-1)) {\n realloc_list(ll,&def_n_entries);\n }\n\n // add one last field for final checksum\n blk_size = set_checksum_field(&(ll->items[ll->n_entries]),byteloc);\n update_linklist_hash(&mdContext,&ll->items[ll->n_entries]);\n byteloc += blk_size;\n ll->n_entries++;\n\n // fix linkentry pointers for blocks and streams\n int b_ind = 0;\n int s_ind = 0;\n for (i=0; i<(int) ll->n_entries; i++) {\n if (ll->items[i].tlm == &block_entry) {\n ll->blocks[b_ind].le = &ll->items[i];\n b_ind++;\n } else if (ll->items[i].tlm == &stream_entry) {\n ll->streams[s_ind].le = &ll->items[i];\n s_ind++;\n } \n }\n if (b_ind != (int) ll->num_blocks) {\n linklist_err(\"Found inconsistent number of blocks (%d != %d)\\n\", b_ind, ll->num_blocks);\n }\n if (s_ind != (int) ll->num_streams) {\n linklist_err(\"Found inconsistent number of streams (%d != %d)\\n\", s_ind, ll->num_streams);\n }\n\n int file_blk_size = read_linklist_formatfile_comment(fname, LINKLIST_FILE_SIZE_IND, \"%d\");\n if ((file_blk_size > 0) && (file_blk_size != (int) byteloc)) {\n if (file_blk_size == (int) (byteloc+superframe->allframe_size)) {\n flags |= LL_INCLUDE_ALLFRAME;\n } else {\n linklist_err(\"File blksize %d inconsistent with parsed blksize %d\\n\", file_blk_size, byteloc);\n }\n }\n\n ll->blk_size = byteloc;\n ll->flags = flags;\n\n // add the linklist name\n memset(ll->name, 0, LINKLIST_SHORT_FILENAME_SIZE); // clear name completely\n strcpy(ll->name, strip_path(fname)); // copy the name\n\n // update the hash\n MD5_Update(&mdContext, &byteloc, sizeof(byteloc));\n MD5_Update(&mdContext, &ll->n_entries, sizeof(ll->n_entries));\n //MD5_Update(&mdContext, ll->name, strlen(ll->name));\n\n // generate serial\n MD5_Final(md5hash,&mdContext);\n memcpy(ll->serial,md5hash,MD5_DIGEST_LENGTH);\n\n // set defaults for the internal (de)compression routines\n ll->internal_buffer = NULL;\n ll->internal_id = 0;\n\n return ll;\n}\n\n// this should be the inverse of parse_linklist_format\nvoid write_linklist_format(linklist_t * ll, char * fname)\n{\n write_linklist_format_opt(ll, fname, ll->flags);\n}\n\n// this should be the inverse of parse_linklist_format\n// flags are in addition to the ll->flags generated by parse_linklist_format\nvoid write_linklist_format_opt(linklist_t * ll, char * fname, int flags)\n{\n int i;\n FILE * formatfile = fopen(fname, \"w\");\n\n if (formatfile == NULL) {\n linklist_err(\"Unable to generate linklist file \\\"%s\\\"\", fname);\n return;\n }\n flags |= ll->flags; // add the flags from linklist\n\n fprintf(formatfile, \"#\\n\");\n fprintf(formatfile, \"# Linklist \\\"%s\\\" Format File\\n\", fname);\n fprintf(formatfile, \"# Auto-generated by linklist\\n\");\n fprintf(formatfile, \"#\");\n fprintf(formatfile, \"\\n\");\n fprintf(formatfile, LINKLIST_FILE_SERIAL_IND \"%.08x\\n\", *((uint32_t *) ll->serial)); // format specifier\n if (flags & LL_INCLUDE_ALLFRAME) {\n fprintf(formatfile, LINKLIST_FILE_SIZE_IND \"%d\\n\", ll->blk_size+ll->superframe->allframe_size); \n } else {\n fprintf(formatfile, LINKLIST_FILE_SIZE_IND \"%d\\n\", ll->blk_size); // blk_size = bulk size\n }\n fprintf(formatfile, LINKLIST_FRAMES_PER_FILE_IND \"%d\\n\", ll_rawfile_default_fpf); // number of frames per file\n fprintf(formatfile, \"#\\n\");\n \n fprintf(formatfile, \"%s\\n\\n\", STR(LL_NO_AUTO_CHECKSUM));\n\n for (i = 0; i < (int) ll->n_entries; i++) { \n if (ll->items[i].tlm == &block_entry) { // a block\n block_t * theblock = linklist_find_block_by_pointer(ll, &ll->items[i]);\n if (theblock) {\n fprintf(formatfile, \"%s \", theblock->name); // block name\n fprintf(formatfile, \"B \"); // block indicator\n fprintf(formatfile, \"%u\\n\", ll->items[i].num); // block size \n } else {\n linklist_err(\"Could not find block in linklist\\n\");\n }\n } else if (ll->items[i].tlm == &stream_entry) { // a stream\n stream_t * thestream = linklist_find_stream_by_pointer(ll, &ll->items[i]);\n if (thestream) {\n fprintf(formatfile, \"%s \", thestream->name); // stream name\n fprintf(formatfile, \"S \"); // stream indicator\n fprintf(formatfile, \"%u\\n\", ll->items[i].num); // stream size \n } else {\n linklist_err(\"Could not find stream in linklist\\n\");\n }\n } else if (ll->items[i].tlm) { // not a checksum field\n fprintf(formatfile, \"%s \", ll->items[i].tlm->field); // field name\n if (ll->items[i].comp_type == NO_COMP) {\n fprintf(formatfile, \"%s \", \"NONE\"); // compression type\n } else {\n fprintf(formatfile, \"%s \", compRoutine[ll->items[i].comp_type].name); // compression type\n }\n fprintf(formatfile, \"%u\\n\", ll->items[i].num); // samples per frame (spf)\n } else if ((i != 0) && (i != (int) (ll->n_entries-1))){ // don't include first or last checksum\n fprintf(formatfile, \"%s\\n\", LL_PARSE_CHECKSUM); // checksum indicator\n }\n\n }\n fflush(formatfile);\n fclose(formatfile);\n\n}\n\nvoid delete_superframe(superframe_t * sf) {\n free(sf->entries);\n free(sf->hash_table);\n free(sf);\n}\n\nvoid delete_linklist(linklist_t * ll)\n{\n int i;\n for (i = 0; i < (int) ll->num_blocks; i++) {\n free(ll->blocks[i].buffer);\n }\n for (i = 0; i < (int) ll->num_streams; i++) {\n free(ll->streams[i].buffers[0].buffer);\n free(ll->streams[i].buffers[1].buffer);\n }\n free(ll->blocks);\n free(ll->streams);\n free(ll->items);\n free(ll);\n}\n\nlinklist_t ** ll_list = NULL;\nint8_t linktable[65536] = {0};\n\nint linklist_generate_lookup(linklist_t ** lll) {\n uint16_t hash;\n int i = 0;\n\n memset(linktable, -1, 65536*sizeof(int8_t));\n if (!lll) {\n linklist_err(\"Linklist array is null\\n\");\n return 0;\n }\n ll_list = lll;\n linklist_t * ll = ll_list[0];\n\n while (ll) {\n hash = *((uint16_t *) ll->serial);\n if (linktable[hash] != -1)\n {\n linklist_err(\"Hash colliision for linklist %d and %d\\n\", i, linktable[hash]);\n return -1;\n }\n linktable[hash] = i;\n ll = ll_list[++i];\n }\n return 1;\n}\n\n// returns the a pointer to the linklist with the given serial number \nlinklist_t * linklist_lookup_by_serial(uint16_t serial) {\n if (!ll_list) {\n linklist_err(\"linklist lookup is unallocated\\n\");\n return NULL;\n }\n int ind = linktable[serial];\n if (ind < 0) return NULL;\n return ll_list[ind];\n}\n\n/*\n * linklist_duplicate\n *\n * This function duplicates a linklist exactly, copying all entries and blocks.\n * References to the superframe are copied as well as the serial and flags.\n*/\nlinklist_t * linklist_duplicate(linklist_t * ll) {\n if (!ll) {\n linklist_err(\"Cannot duplicate NULL linklist\\n\");\n return NULL;\n }\n int i, j;\n linklist_t * ll_copy = (linklist_t *) calloc(1, sizeof(linklist_t)); \n \n // copy the structure directly\n memcpy(ll_copy, ll, sizeof(linklist_t));\n\n // copy the entries\n ll_copy->items = (linkentry_t *) calloc(ll->n_entries, sizeof(linkentry_t));\n memcpy(ll_copy->items, ll->items, ll->n_entries*sizeof(linkentry_t));\n\n // copy the blocks\n ll_copy->blocks = (struct block_container *) calloc(MAX_DATA_BLOCKS, sizeof(struct block_container));\n memcpy(ll_copy->blocks, ll->blocks, MAX_DATA_BLOCKS*sizeof(struct block_container));\n\n // copy the streams\n ll_copy->streams = (struct stream_container *) calloc(MAX_DATA_STREAMS, sizeof(struct stream_container));\n memcpy(ll_copy->streams, ll->streams, MAX_DATA_STREAMS*sizeof(struct stream_container));\n\n // change the reference to the copied linklist for each linkentry\n int b_ind = 0;\n int s_ind = 0;\n for (i=0; i<(int) ll_copy->n_entries; i++) {\n ll_copy->items[i].linklist = ll_copy;\n // allocate block memory and update reference to linkentry to the copied linklist\n if (ll_copy->items[i].tlm == &block_entry) {\n ll_copy->blocks[b_ind].buffer = (uint8_t *) calloc(1, ll_copy->blocks[b_ind].alloc_size);\n ll_copy->blocks[b_ind].fp = NULL; // only one block can own the file descriptor if non-NULL\n ll_copy->blocks[b_ind].le = &ll_copy->items[i];\n b_ind++;\n } else if (ll_copy->items[i].tlm == &stream_entry) {\n for (j=0; j<2; j++) {\n\t\t\t\tll_copy->streams[s_ind].buffers[j].buffer = \n (uint8_t *) calloc(1, ll_copy->streams[s_ind].buffers[j].alloc_size);\n ll_copy->streams[s_ind].buffers[j].data_size = 0;\n ll_copy->streams[s_ind].buffers[j].loc = 0;\n }\n ll_copy->streams[s_ind].curr = 0;\n ll_copy->streams[s_ind].next = 0;\n\t\t\tll_copy->streams[s_ind].fp = NULL; // only one block can own the file descriptor if non-NULL\n ll_copy->streams[s_ind].le = &ll_copy->items[i];\n s_ind++;\n }\n }\n\n // check consistency with the number of blocks found\n if (b_ind != (int) ll_copy->num_blocks) {\n linklist_err(\"linklist_duplicate: num_blocks mismatch (found %d, expected %d)\\n\", \n i, ll_copy->num_blocks);\n }\n\n return ll_copy;\n}\n\n\nlinklist_t * generate_superframe_linklist(superframe_t * superframe) {\n return generate_superframe_linklist_opt(superframe, 0);\n}\n\nlinklist_t * generate_superframe_linklist_opt(superframe_t * superframe, int flags)\n{\n if (superframe== NULL) {\n linklist_err(\"Supeframe is NULL\\n\");\n return NULL;\n }\n superframe_entry_t * ll_superframe_list = superframe->entries;\n\n int i;\n unsigned int byteloc = 0;\n unsigned int blk_size = 0;\n unsigned int chksm_count = 0;\n unsigned int comp_type = 0;\n\n unsigned int extra_chksm = !(flags & LL_NO_AUTO_CHECKSUM) ? superframe->size/MIN_CHKSM_SPACING : 0;\n extra_chksm += 5;\n\n // MD5 hash\n MD5_CTX mdContext;\n uint8_t md5hash[MD5_DIGEST_LENGTH] = {0};\n MD5_Init(&mdContext); // initialize hash\n\n linklist_t * ll = (linklist_t *) calloc(1, sizeof(linklist_t));\n ll->items = (linkentry_t *) calloc(superframe->n_entries+extra_chksm, sizeof(linkentry_t));\n ll->flags = flags;\n ll->superframe = superframe;\n ll->blocks = (struct block_container *) calloc(MAX_DATA_BLOCKS,sizeof(struct block_container));\n ll->streams = (struct stream_container *) calloc(MAX_DATA_STREAMS,sizeof(struct stream_container));\n ll->n_entries = 0;\n\n // add initial checksum\n blk_size = set_checksum_field(&(ll->items[ll->n_entries]), byteloc);\n update_linklist_hash(&mdContext, &ll->items[ll->n_entries]);\n byteloc += blk_size;\n ll->n_entries++;\n\n // add all telemetry entries\n for (i = 0; i < (int) superframe->n_entries; i++) {\n if ((chksm_count >= MIN_CHKSM_SPACING) && !(flags & LL_NO_AUTO_CHECKSUM)) {\n blk_size = set_checksum_field(&(ll->items[ll->n_entries]), byteloc);\n update_linklist_hash(&mdContext, &ll->items[ll->n_entries]);\n byteloc += blk_size;\n ll->n_entries++;\n chksm_count = 0;\n }\n\n comp_type = linklist_get_default_compression(&ll_superframe_list[i], flags);\n\n ll->items[ll->n_entries].start = byteloc;\n ll->items[ll->n_entries].num = ll_superframe_list[i].spf;\n ll->items[ll->n_entries].comp_type = comp_type;\n\n superframe_entry_t * chan = NULL;\n if (ll_superframe_list[i].type == SF_NUM) {\n chan = &block_entry;\n parse_block(ll, ll_superframe_list[i].field);\n } else if (ll_superframe_list[i].type == SF_INF) {\n chan = &stream_entry;\n parse_stream(ll, ll_superframe_list[i].field);\n } else {\n chan = &ll_superframe_list[i];\n }\n ll->items[ll->n_entries].tlm = chan;\n ll->items[ll->n_entries].linklist = ll;\n\n if (comp_type != NO_COMP) { // normal compressed field\n blk_size = (*compRoutine[comp_type].compressFunc)(NULL, &ll->items[ll->n_entries], NULL);\n } else { // no compression, so identical field supeframe entry \n blk_size = get_superframe_entry_size(&ll_superframe_list[i])*ll_superframe_list[i].spf; \n }\n ll->items[ll->n_entries].blk_size = blk_size;\n\n update_superframe_entry_hash(&mdContext, chan);\n update_linklist_hash(&mdContext, &ll->items[ll->n_entries]);\n byteloc += blk_size;\n ll->n_entries++;\n chksm_count += blk_size;\n }\n\n // final checksum\n blk_size = set_checksum_field(&(ll->items[ll->n_entries]), byteloc);\n update_linklist_hash(&mdContext, &ll->items[ll->n_entries]);\n byteloc += blk_size;\n ll->n_entries++;\n\n ll->blk_size = byteloc;\n strcpy(ll->name, ALL_TELEMETRY_NAME);\n\n MD5_Update(&mdContext, &byteloc, sizeof(byteloc));\n MD5_Update(&mdContext, &ll->n_entries, sizeof(ll->n_entries));\n //MD5_Update(&mdContext, ll->name, (strlen(ll->name)/4)*4);\n\n // generate serial\n MD5_Final(md5hash, &mdContext);\n memcpy(ll->serial, md5hash, MD5_DIGEST_LENGTH);\n \n return ll;\n}\n\nuint64_t generate_superframe_serial(superframe_t * superframe) \n{\n superframe_entry_t * sf = superframe->entries;\n\n // MD5 hash variables\n MD5_CTX mdContext;\n uint8_t md5hash[MD5_DIGEST_LENGTH];\n MD5_Init(&mdContext); // initialize MD5 hash\n\n int i = 0;\n for (i = 0; sf[i].field[0]; i++) {\n MD5_Update(&mdContext, sf[i].field, strlen(sf[i].field));\n MD5_Update(&mdContext, &sf[i].type, sizeof(sf[i].type));\n MD5_Update(&mdContext, &sf[i].spf, sizeof(sf[i].spf));\n MD5_Update(&mdContext, &sf[i].start, sizeof(sf[i].start));\n MD5_Update(&mdContext, &sf[i].skip, sizeof(sf[i].skip));\n //if (strlen(sf[i].quantity)) MD5_Update(&mdContext, sf[i].quantity, strlen(sf[i].quantity));\n //if (strlen(sf[i].units)) MD5_Update(&mdContext, sf[i].units, strlen(sf[i].units));\n }\n\n // generate MD5 hash of command_list\n MD5_Final(md5hash,&mdContext);\n\n return *(uint64_t *) md5hash;\n}\n\n// get the number of frames per file (fpf) from the linklist formatfile\nint read_linklist_formatfile_comment(char * fin, char * comment, const char * format) {\n FILE * f;\n\n if ((f = fopen(fin, \"r\")) == NULL) {\n return -2;\n }\n\n char * line = NULL;\n size_t len = 0; \n int read = 0;\n int retval = -1;\n\n while ((read = getline(&line, &len, f)) != -1) {\n if (strncmp(line, comment, strlen(comment)) == 0) {\n fclose(f);\n sscanf(line+strlen(comment), format, &retval);\n return retval;\n }\n }\n fclose(f);\n\n return retval;\n}\n\nsuperframe_t * parse_superframe_format(char * fname) {\n // big endian is the default if the superframe format does not specify\n return parse_superframe_format_opt(fname, SF_USE_BIG_ENDIAN);\n}\n\nsuperframe_t * parse_superframe_format_opt(char * fname, int flags) {\n FILE * cf = fopen(fname, \"r\"); // open command file\n if (cf == NULL) {\n linklist_err(\"Cannot find %s\\n\",fname);\n return NULL;\n }\n\n char *line = NULL;\n size_t len = 0;\n int st, read;\n int i, j, r;\n char temp[100];\n char *temps[20];\n uint8_t * frame = NULL;\n int start, skip;\n int count = 1;\n uint64_t serial = 0;\n\n // flags\n uint8_t begin_f = 0, size_f = 0, serial_f = 0;\n\n int def_n_entries = 150;\n unsigned int blksize = 0;\n unsigned int n_entries = 0;\n\n superframe_entry_t * sf = (superframe_entry_t *) calloc(def_n_entries, sizeof(superframe_entry_t));\n\n while ((read = getline(&line, &len, cf)) != -1) {\n // remove the newline\n line[read-1] = '\\0';\n read--;\n\n // remove end whitespace\n for (r=(read-1);r>=0;r--) {\n if ((line[r] != ' ') && (line[r] != '\\t')) break;\n else line[r] = '\\0';\n }\n read = r+1;\n\n // remove beginning whitespace\n st = 0;\n while ((line[st] == '\\t') || (line[st] == ' ')) st++;\n\n if ((line[st] != COMM) && (line[st] != '\\n') && ((read-st) > 0)) { // skip comments and blank lines\n strcpy(temp, line+st);\n\n if (!begin_f) { // ignore everything up to the BEGIN marker\n if (strncmp(temp,\"BEGIN\",5) == 0) begin_f = 1; // found beginning\n } else if (!serial_f) { // next is the serial number\n sscanf(temp, \"%\" PRIx64, &serial);\n serial_f = 1;\n } else if (!size_f) { // next is the frame size\n blksize = atoi(temp);\n size_f = 1;\n frame = (uint8_t *) calloc(blksize, sizeof(uint8_t));\n } else { // everything else is a telemetry entry\n parse_line(temp, temps, 8); \n\n if (strncmp(temps[0],\"END\",3) == 0) {\n break;\n } else if (strncmp(temps[0], SUPERFRAME_ENDIAN_IND, strlen(SUPERFRAME_ENDIAN_IND)) == 0) {\n if (strncmp(temps[1], SUPERFRAME_ENDIAN_LITTLE, strlen(SUPERFRAME_ENDIAN_LITTLE)) == 0) {\n flags &= ~SF_USE_BIG_ENDIAN;\n } else if (strncmp(temps[1], SUPERFRAME_ENDIAN_BIG, strlen(SUPERFRAME_ENDIAN_BIG)) == 0) {\n flags |= SF_USE_BIG_ENDIAN;\n }\n continue;\n }\n if ((int) n_entries >= (def_n_entries-1)) {\n def_n_entries += 5;\n sf = (superframe_entry_t *) realloc(sf, def_n_entries*sizeof(superframe_entry_t));\n }\n\n memset(sf[n_entries].field, 0, SF_FIELD_LEN);\n strcpy(sf[n_entries].field, temps[0]); // name\n sf[n_entries].type = get_sf_type_int(temps[1]); // type int\n sf[n_entries].spf = atoi(temps[2]); // samples per frame\n\n unsigned int type_str_len = strlen(get_sf_type_string(sf[n_entries].type));\n if (strlen(temps[1]) > type_str_len) { // trailing characters are assumed to be min and max of format (min,max) \n sscanf(temps[1]+type_str_len, \"(%lf,%lf)%*s\", &sf[n_entries].min, &sf[n_entries].max);\n //linklist_info(\"%s min=%f max=%f\\n\", sf[n_entries].field, sf[n_entries].min, sf[n_entries].max);\n }\n\n // determine start byte and skip\n start = atoi(temps[3]);\n skip = atoi(temps[4]);\n sf[n_entries].start = start; // start byte\n sf[n_entries].skip = skip; // skip\n memset(sf[n_entries].quantity, 0, SF_UNITS_LEN);\n memset(sf[n_entries].units, 0, SF_UNITS_LEN);\n if (strlen(temps[5])) strcpy(sf[n_entries].quantity, temps[5]);\n if (strlen(temps[6])) strcpy(sf[n_entries].units, temps[6]);\n sf[n_entries].var = NULL;\n\n // populate byte map\n for (i = 0; i < (int) sf[n_entries].spf; i++) {\n for (j = 0; j < (int) get_superframe_entry_size(&sf[n_entries]); j++) {\n if (frame[skip*i+start+j] == 1) {\n linklist_warn(\"Warning (line %d): byte %d overlap\\n\", count, skip*i+start+j);\n }\n frame[skip*i+start+j] = 1;\n }\n }\n n_entries++;\n }\n }\n count++;\n }\n fclose(cf);\n\n sf[n_entries].field[0] = '\\0';\n\n superframe_t * superframe = NULL;\n if (flags & SF_USE_BIG_ENDIAN) {\n superframe = linklist_build_superframe(sf, &def_datatodouble_be, &def_doubletodata_be, flags);\n } else {\n superframe = linklist_build_superframe(sf, NULL, NULL, flags);\n }\n\n if (superframe->serial != serial) {\n linklist_err(\"Parsed serial 0x%\" PRIx64 \" does not match file serial 0x%\" PRIx64 \"\\n\", superframe->serial, serial);\n }\n if (superframe->size != blksize) {\n linklist_err(\"Parsed size %d does not match file size %d\\n\", superframe->size, blksize);\n }\n\n superframe->flags = flags;\n if (frame) free(frame);\n\n return superframe;\n}\n\nvoid write_superframe_format(superframe_t * superframe, const char * fname) {\n if (!superframe || !superframe->entries) return;\n superframe_entry_t * sf = superframe->entries;\n\n FILE * fp = fopen(fname, \"w\");\n if (!fp) {\n linklist_err(\"Unable to write format at \\\"%s\\\"\\n\", fname);\n }\n int i = 0;\n \n fprintf(fp, \"BEGIN\\n\");\n fprintf(fp, \"%\" PRIx64 \"\\n\", superframe->serial); \n fprintf(fp, \"%d\\n\", superframe->size); \n if (!(superframe->flags & SF_USE_BIG_ENDIAN)) {\n fprintf(fp, \"%s %s\\n\", SUPERFRAME_ENDIAN_IND, SUPERFRAME_ENDIAN_LITTLE); \n }\n\n char type_string[128] = \"\";\n\n for (i = 0; sf[i].field[0]; i++) {\n if ((sf[i].max != 0) || (sf[i].min != 0)) sprintf(type_string, \"%s(%lf,%lf)\", get_sf_type_string(sf[i].type), sf[i].min, sf[i].max);\n else sprintf(type_string, \"%s\", get_sf_type_string(sf[i].type));\n fprintf(fp, \"%s %s %u %u %u\", sf[i].field, type_string, sf[i].spf, sf[i].start, sf[i].skip);\n if (strlen(sf[i].quantity)) fprintf(fp, \" \\\"%s\\\" \\\"%s\\\"\", sf[i].quantity, sf[i].units);\n fprintf(fp, \"\\n\");\n }\n\n fprintf(fp, \"END\\n\");\n\n fflush(fp);\n fclose(fp);\n}\n\n#ifdef __cplusplus\n}\n\n#endif\n" }, { "alpha_fraction": 0.7075985074043274, "alphanum_fraction": 0.7075985074043274, "avg_line_length": 34.604652404785156, "blob_id": "d0f9c1a546c0d17da024ec9d624e176be9d5d04d", "content_id": "60a639269c7b6cc797ff1a88fc46d96405999332", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 4593, "license_type": "no_license", "max_line_length": 60, "num_lines": 129, "path": "/common/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "set(MCP_COMMON_SRCS\n ${MCP_COMMON_SRCS}\n ${CMAKE_CURRENT_SOURCE_DIR}/bitserver.c\n ${CMAKE_CURRENT_SOURCE_DIR}/blast.c\n ${CMAKE_CURRENT_SOURCE_DIR}/channels_tng.c\n ${CMAKE_CURRENT_SOURCE_DIR}/crc.c\n ${CMAKE_CURRENT_SOURCE_DIR}/CRC_func.c\n ${CMAKE_CURRENT_SOURCE_DIR}/fir.c\n ${CMAKE_CURRENT_SOURCE_DIR}/lut.c\n ${CMAKE_CURRENT_SOURCE_DIR}/mputs.c\n ${CMAKE_CURRENT_SOURCE_DIR}/pq.c\n ${CMAKE_CURRENT_SOURCE_DIR}/PMurHash.c\n ${CMAKE_CURRENT_SOURCE_DIR}/sip.c\n ${CMAKE_CURRENT_SOURCE_DIR}/slowdl.c\n ${CMAKE_CURRENT_SOURCE_DIR}/xsc_fifo.c\n ${CMAKE_CURRENT_SOURCE_DIR}/FIFO.c\n ${CMAKE_CURRENT_SOURCE_DIR}/log.c\n PARENT_SCOPE\n)\nset(MCP_COMMON_HEADERS\n ${MCP_COMMON_HEADERS}\n ${CMAKE_CURRENT_SOURCE_DIR}/include/bitserver.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/blast.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/blast_packet_format.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/blast_time.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/channels_tng.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/derived.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/crc.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/CRC_func.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/fir.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/lut.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/mputs.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/pq.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/PMurHash.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/portable_endian.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/sip.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/slowdl.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/xsc_fifo.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/FIFO.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/log.h\n PARENT_SCOPE\n)\n\nset(GROUNDHOG_COMMON_SRCS\n ${GROUNDHOG_COMMON_SRCS}\n ${CMAKE_CURRENT_SOURCE_DIR}/blast.c\n ${CMAKE_CURRENT_SOURCE_DIR}/bitserver.c\n ${CMAKE_CURRENT_SOURCE_DIR}/channels_tng.c\n ${CMAKE_CURRENT_SOURCE_DIR}/crc.c\n ${CMAKE_CURRENT_SOURCE_DIR}/CRC_func.c\n ${CMAKE_CURRENT_SOURCE_DIR}/FIFO.c\n ${CMAKE_CURRENT_SOURCE_DIR}/mputs.c\n ${CMAKE_CURRENT_SOURCE_DIR}/PMurHash.c\n PARENT_SCOPE\n)\nset(GROUNDHOG_COMMON_HEADERS\n ${GROUNDHOG_COMMON_HEADERS}\n ${CMAKE_CURRENT_SOURCE_DIR}/include/blast.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/blast_time.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/bitserver.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/channels_tng.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/crc.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/CRC_func.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/derived.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/FIFO.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/mputs.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/PMurHash.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/portable_endian.h\n PARENT_SCOPE\n)\n\nset(DECOM_COMMON_SRCS\n ${DECOM_COMMON_SRCS}\n ${CMAKE_CURRENT_SOURCE_DIR}/blast.c\n ${CMAKE_CURRENT_SOURCE_DIR}/channels_tng.c\n ${CMAKE_CURRENT_SOURCE_DIR}/crc.c\n ${CMAKE_CURRENT_SOURCE_DIR}/mputs.c\n ${CMAKE_CURRENT_SOURCE_DIR}/PMurHash.c\n PARENT_SCOPE\n)\nset(DECOM_COMMON_HEADERS\n ${DECOM_COMMON_HEADERS}\n ${CMAKE_CURRENT_SOURCE_DIR}/include/blast.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/blast_time.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/channels_tng.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/crc.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/derived.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/mputs.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/PMurHash.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/portable_endian.h\n PARENT_SCOPE\n)\n\nset(DEFRICHER_COMMON_SRCS\n ${DEFRICHER_COMMON_SRCS}\n ${CMAKE_CURRENT_SOURCE_DIR}/blast.c\n ${CMAKE_CURRENT_SOURCE_DIR}/channels_tng.c\n ${CMAKE_CURRENT_SOURCE_DIR}/crc.c\n ${CMAKE_CURRENT_SOURCE_DIR}/CRC_func.c\n ${CMAKE_CURRENT_SOURCE_DIR}/FIFO.c\n ${CMAKE_CURRENT_SOURCE_DIR}/mputs.c\n ${CMAKE_CURRENT_SOURCE_DIR}/PMurHash.c\n PARENT_SCOPE\n)\nset(DEFRICHER_COMMON_HEADERS\n ${DEFRICHER_COMMON_HEADERS}\n ${CMAKE_CURRENT_SOURCE_DIR}/include/blast.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/blast_time.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/channels_tng.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/crc.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/CRC_func.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/derived.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/FIFO.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/mputs.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/PMurHash.h\n ${CMAKE_CURRENT_SOURCE_DIR}/include/portable_endian.h\n PARENT_SCOPE\n)\n\nset(CMD_SRCS\n ${CMD_SRCS}\n ${CMAKE_CURRENT_SOURCE_DIR}/command_common.c\n PARENT_SCOPE\n)\nset(CMD_HEADERS\n ${CMD_HEADERS}\n ${CMAKE_CURRENT_SOURCE_DIR}/include/command_common.h\n PARENT_SCOPE\n)\n" }, { "alpha_fraction": 0.5820028781890869, "alphanum_fraction": 0.6182873845100403, "avg_line_length": 19.235294342041016, "blob_id": "bf69abf89784b30412f814b5da335d2bde1d00a5", "content_id": "1fd0466cea857fe0fd498174a8117e5c6ea34598", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 690, "license_type": "no_license", "max_line_length": 73, "num_lines": 34, "path": "/stars/code/displaying/quit_box.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"quit_box.h\"\n#include \"glhelper.h\"\n\nusing namespace Displaying;\n\nQuitBox::QuitBox()\n{\n change_size(51, 29);\n}\n\nvoid QuitBox::draw(Position &position)\n{\n begin_draw(position);\n draw_border();\n\n glPushMatrix();\n GL::Color4f(0.0, 0.0, 0.0, 1.0);\n glBegin(GL_POLYGON);\n glVertex2d(1, 0);\n glVertex2d(width(), 0);\n glVertex2d(width(), height());\n glVertex2d(1, height());\n glEnd();\n glPopMatrix();\n\n draw_title();\n end_draw();\n}\n\n" }, { "alpha_fraction": 0.4937428832054138, "alphanum_fraction": 0.5079635977745056, "avg_line_length": 30.11504364013672, "blob_id": "1405506f119d52eb1d9cc09180cd94e8340390f8", "content_id": "182436537a81dc2b679c5919f873060fbf1d2714", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3516, "license_type": "no_license", "max_line_length": 105, "num_lines": 113, "path": "/owl/PNumberDataItem.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"PNumberDataItem.h\"\n#include <stdio.h>\n#include <QDebug>\n#include <unistd.h>\n\n\nvoid PNumberDataItem::gdUpdate(GetData::Dirfile* dirFile,int lastNFrames)\n{\n double indata;\n bool ok;\n\n indata = gdReadRawData(dirFile, lastNFrames, ok);\n\n if (ok) {\n PStyle* style=_extrema?_extrema->formatForValue(indata,_defaultDataStyle):_defaultDataStyle;\n\n if(prevStyle!=style|| //the reason this works is because PStyleChooser works via reference to ptr\n style->_dirty) {\n applyStyle(this,style);\n prevStyle=style;\n }\n\n if(_format.isEmpty()) {\n if(_data->text() != QString::number(indata)) {\n _data->setText(QString::number(indata));\n _serverDirty=-1;\n } else {\n --_serverDirty;\n }\n } else {\n const char* asciiFormat=_format.toStdString().c_str();\n\n bool is_int = 0;\n bool is_binary = 0;\n for (int i=0; asciiFormat[i]!='\\0'; i++) {\n char c = asciiFormat[i];\n switch (c) {\n case 'x':\n case 'X':\n case 'o':\n case 'd':\n is_int = 1;\n break;\n case 'b':\n is_binary = 1;\n break;\n default:\n break;\n }\n }\n char display[512];\n if (is_int) {\n sprintf(display, asciiFormat, (int)indata);\n } else if (is_binary) {\n int idata = (int)indata;\n long int num_bits = strtol((asciiFormat)+1, NULL, 0);\n if (num_bits < 1 || num_bits > 32) {\n num_bits = 8;\n }\n for (int z = 0; z < num_bits; z++) {\n display[z] = (idata & (1 << ((num_bits - 1) - z))) ? '1' : '0';\n }\n display[num_bits]='\\0';\n } else {\n sprintf(display, asciiFormat, indata);\n }\n if (strlen(display)==1) {\n display[1] = ' ';\n display[2] = '\\0';\n }\n if(_data->text()!=display) {\n _data->setText(display);\n _serverDirty=-1;\n } else {\n --_serverDirty;\n }\n }\n }\n}\n\nQString PNumberDataItem::format() const {\n return _format;\n}\n\nvoid PNumberDataItem::setFormat(QString format,bool force) {\n if(!isCurrentObject()&&!force) return;\n if(_format==format) {\n return;\n }\n _format=format;\n emit formatChanged(format);\n}\n" }, { "alpha_fraction": 0.5887038111686707, "alphanum_fraction": 0.6100651621818542, "avg_line_length": 23.44247817993164, "blob_id": "b29bb1dbe2604456c509119f279767794e7ad67f", "content_id": "34d59d4d16df1c28e9443249c0c39366c5b2831d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2762, "license_type": "no_license", "max_line_length": 85, "num_lines": 113, "path": "/starcam/scviewer.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* viewer.cpp: simple app for displaying star camera images\n * Updating requires the pointed-to file to a a symlink to an image\n * Polls the file and updates image as file changes.\n * Mostly used to view current images from star camera\n */\n\n#include <fstream>\n#include <iostream>\n#include <qapplication.h>\n#include <unistd.h>\n#include <pthread.h>\n#include <sys/stat.h>\n#include \"blobimage.h\"\n#include \"csbigimgdefs.h\"\n#include \"imageviewer.h\"\n\n#define DEFAULT_FILE \"/data/etc/current_bad.sbig\"\n\nchar* filename;\nBlobImage* img[2]; //images. Using only 1 caused segfaults...\nint imgindex = 0;\n\nvoid failure()\n{\n delete img[0];\n delete img[1];\n exit(1);\n}\n\nvoid* updateImage(void* arg)\n{\n ImageViewer* iv = (ImageViewer*)arg;\n struct stat stats;\n time_t time, oldtime;\n int retries = 0;\n int nextindex;\n\n if (stat(filename, &stats)) {\n cerr << \"Problem getting file stats...\" << endl;\n failure();\n }\n oldtime = stats.st_mtime;\n\n while (1) {\n if (stat(filename, &stats)) {\n cerr << \"Problem getting file stats...\" << endl;\n failure();\n }\n time = stats.st_mtime;\n if (time > oldtime) { //the image file has been modified\n //usleep(5000); //give starcam a chance to save the file\n nextindex = (imgindex == 0) ? 1 : 0;\n oldtime = time;\n cout << \"Image updated, refreshing it\" << endl;\n while (img[nextindex]->OpenImage(filename) != SBFE_NO_ERROR) {\n retries++;\n if (retries > 1) cout << \"...failed, retrying\" << endl;\n if (retries >= 5) {\n cerr << \"Oops, something's broken\" << endl;\n failure();\n }\n usleep(100);\n }\n retries = 0;\n iv->load(img[nextindex], TRUE);\n imgindex = nextindex;\n }\n usleep(10000); //wait 10ms before trying again\n }\n\n return NULL;\n}\n\nint main(int argc, char* argv[])\n{\n //open the image\n filename = DEFAULT_FILE;\n if (argc == 2)\n filename = argv[1];\n else if (argc > 2) {\n cerr << \"You're not using me right\" << endl;\n return 1;\n }\n img[0] = new BlobImage();\n img[1] = new BlobImage();\n if (img[0]->OpenImage(filename) != SBFE_NO_ERROR) {\n cerr << \"Error opening image: \" << filename << endl;\n return 1;\n }\n else cout << \"Opened image: \" << filename << endl;\n\n //set up the viewer\n QApplication a(argc, argv);\n ImageViewer iv(640, 480, img[0]->GetWidth(), img[0]->GetHeight(), 10, 0, \"viewer\");\n iv.setGeometry(0,0,640,480);\n a.setMainWidget(&iv);\n iv.show();\n iv.load(img[0], TRUE);\n\n //start a thread to update the image\n pthread_t update_id;\n pthread_create(&update_id, NULL, &updateImage, (void*)&iv);\n\n //start the viewer\n cout << \"Starting the viewer\" << endl;\n a.exec();\n\n pthread_cancel(update_id);\n\n delete img[0];\n delete img[1];\n return 0;\n}\n" }, { "alpha_fraction": 0.6788617968559265, "alphanum_fraction": 0.6817653775215149, "avg_line_length": 18.78160858154297, "blob_id": "5fb6a47f1a9e0495dc8fd4b0a225ea2a789eb2fe", "content_id": "51bbb059e01915c0138eb3fb341b57f99081ea82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1723, "license_type": "no_license", "max_line_length": 73, "num_lines": 87, "path": "/stars/code/displaying/manager.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__MANAGER_H\n#define DISPLAYING__MANAGER_H\n\n#if defined(_MSC_VER)\n #include <windows.h>\n#endif\n#ifdef _MSC_VER\n\t#undef uint8_t\n #include \"SDL.h\"\n #undef main\n#else\n #include \"SDL.h\"\t\t//was SDL/SDL.h\n#endif\n#include \"GL/gl.h\"\n#include \"GL/glu.h\"\n#include \"utilities.h\"\n#include \"housekeeping.h\"\n#include \"textures.h\"\n#include \"texture.h\"\n#include \"visual.h\"\n#include \"autofocus.h\"\n#include \"solving_filters.h\"\n#include \"name.h\"\n#include \"camera.h\"\n#include \"image.h\"\n#include \"lens.h\"\n#include \"quit_box.h\"\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Displaying\n{\n class DisplayManager;\n}\n\nclass Displaying::DisplayManager\n{\n public:\n DisplayManager(Parameters::Manager& params);\n ~DisplayManager();\n void set_video_mode();\n void reshape();\n void init();\n void process_events();\n void print_available_chars();\n void update_zoom(double delta_t);\n void draw();\n void wait_for_quit();\n\n private:\n bool using_camera;\n bool enabled;\n bool fullscreen;\n int shared_fullscreen_counter;\n SDL_Surface* screen;\n Size full_screen_size, normal_screen_size, current_screen_size;\n Size resolution;\n\n Textures textures;\n\n Housekeeping housekeeping;\n Visual visual;\n Autofocus autofocus;\n SolvingFilters solving_filters;\n Camera camera_block;\n Image image;\n Lens lens;\n QuitBox quit_box;\n Name name;\n\n double current_zoom_x;\n double current_zoom_y;\n double current_zoom_magnitude;\n\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.6273784637451172, "alphanum_fraction": 0.6548625826835632, "avg_line_length": 27.238805770874023, "blob_id": "5590386ae17db5d35d2cb653fa629c05b42ae87d", "content_id": "9f1d2b4e950b4a7f9b12405ca3fe739f3d2a8bdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1893, "license_type": "no_license", "max_line_length": 93, "num_lines": 67, "path": "/stars/code/displaying/network.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#define NOMINMAX\n#include \"network.h\"\n#include \"../shared/network/packets.h\"\n#include \"../shared/network/client.h\"\n#include \"../shared/camera/results.h\"\n\nusing namespace Displaying;\nusing std::string;\n\n#define shared_packets_from_fc1 (*(Shared::Network::packets_from_fc1.r))\n#define shared_client (*(Shared::Network::client_for_main.r))\n#define shared_camera_results (*(Shared::Camera::results_for_main.r))\n\nNetwork::Network()\n{\n string name;\n name = \"ctr_f\";\n counter_fcp.init(name);\n name = \"ctr_s\";\n counter_stars.init(name);\n\n //change_size(140, 2*padding+3*text_height);\n change_size(140, 2*padding+1*text_height);\n\n}\n\nvoid Network::draw_packets()\n{\n Position pos = {padding+72, height() - padding};\n double scale = 0.0;\n double dim_rate = 2.0;\n\n scale = std::max(1.0 - shared_packets_from_fc1.time_since_sent.time()*dim_rate, 0.0);\n Color color_sent(1.0*scale, 0.7*scale, 0.7*scale, 1.0);\n scale = std::max(1.0 - shared_packets_from_fc1.time_since_received.time()*dim_rate, 0.0);\n Color color_received(0.7*scale, 1.0*scale, 0.7*scale, 1.0);\n\n set_color(color_sent, true);\n draw_text(\"s\", pos);\n pos.x += 11;\n set_color(color_received, true);\n draw_text(\"r\", pos);\n}\n\nvoid Network::draw(Position &position)\n{\n update_size();\n\n counter_fcp.set_value(shared_client.counter_fcp, 0);\n counter_stars.set_value(shared_camera_results.counter_stars, 0);\n\n begin_draw(position);\n draw_border();\n draw_title();\n draw_packets();\n //Position pos = {padding+padding, height() - padding - text_height};\n //draw_value(counter_fcp, pos);\n //pos.y -= text_height;\n //draw_value(counter_stars, pos);\n end_draw();\n}\n" }, { "alpha_fraction": 0.7254641652107239, "alphanum_fraction": 0.7307692170143127, "avg_line_length": 18.842105865478516, "blob_id": "d7a4ccfc9faf21ebecdd226c9f71c5c248651b65", "content_id": "ce9f6da0e79427137088ac43d2f394619ceeb253", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 755, "license_type": "no_license", "max_line_length": 73, "num_lines": 38, "path": "/stars/code/shared/housekeeping/housekeeper.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__HOUSEKEEPING__HOUSEKEEPER_H\n#define SHARED__HOUSEKEEPING__HOUSEKEEPER_H\n\n#include <vector>\n#include \"../circular_buffer.h\"\n#include \"measurement.h\"\n\nnamespace Shared\n{\n namespace Housekeeping\n {\n\nclass Housekeeper\n{\n public:\n std::vector<Measurement> measurements;\n\tint heater_state;\n};\n\n// writes: main\n// reads: camera\nextern Shared::CircularBufferPass <Housekeeper> housekeeper_for_camera;\n\n// writes: camera\n// reads: network\nextern Shared::CircularBuffer <Housekeeper> housekeeper_for_network;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.6761245727539062, "alphanum_fraction": 0.7190311551094055, "avg_line_length": 26.788461685180664, "blob_id": "fb067b3f6a5e6889a3c804f5c0ba523bca69520e", "content_id": "a16dc921dd99bef6e7c5c7647c34ad80230b83c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1445, "license_type": "no_license", "max_line_length": 81, "num_lines": 52, "path": "/common/include/CRC_func.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * CRC.h: \n *\n * This software is copyright \n * (C) 2015-2018 University of Toronto, Toronto, ON\n *\n * This file is part of the SuperBIT project, modified and adapted for BLAST-TNG.\n *\n * linklist 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 2 of the License, or\n * (at your option) any later version.\n *\n * linklist 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Jan 25, 2018 by Javier Romualdez\n */\n\n\n#ifndef INCLUDE_CRC_FUNC_H\n#define INCLUDE_CRC_FUNC_H\n\n#define CRC_POLY 0x1021\t\t// polynomial basis for CRC generation\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\n// define some global variables\nextern uint16_t *crctable;\n\n// define some function prototypes\n\nuint16_t *mk_crctable(uint16_t, uint16_t (*crcfn)(uint16_t, uint16_t, uint16_t));\nuint16_t crchware(uint16_t, uint16_t, uint16_t);\nvoid crccheck(uint16_t, uint16_t *, uint16_t *);\n\n#ifdef __cplusplus\n}\n\n#endif\n\n#endif /* INCLUDE_CRC_FUNC_H */\n" }, { "alpha_fraction": 0.6172889471054077, "alphanum_fraction": 0.6310876607894897, "avg_line_length": 24.391752243041992, "blob_id": "fa507d009ed40469f75028fb1d3762e7f3daf17b", "content_id": "52c318c87e524fe421c49440129c4f94f14e30f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2465, "license_type": "no_license", "max_line_length": 97, "num_lines": 97, "path": "/stars/code/solving/solution.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__SOLUTION_H\n#define SOLVING__SOLUTION_H\n\n#include <vector>\n#include \"blob.h\"\n#include \"star.h\"\n#include \"attitude.h\"\n\nnamespace Logging\n{\n class Logger;\n}\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n}\n\nnamespace Solving\n{\n\nclass Solution;\n\n}\n\nclass Solving::Solution\n{\n public:\n Solution();\n void print(Logging::Logger& logger, bool print_matches=false, bool print_base_matches=false);\n void print_simple_code(Shared::Image::Raw& image);\n static bool sort_by_num_matches(Solution first, Solution second);\n\n\n // --- Pattern Matching Stage 1 ---\n // load from catalog\n std::vector<double> base_distances;\n std::vector<Star> base_stars;\n std::vector<Blob> base_blobs;\n\n // --- Pattern Matching Stage 2 ---\n // get the base equatorial solution\n SolutionAttitude equatorial;\n\n // --- Pattern Matching Stage 3 ---\n // get the base horizontal solution if there are any horizontal filters enabled\n SolutionAttitude horizontal;\n\n // --- Pattern Matching Stage 4 ---\n // filter on:\n // 1) equatorial solution\n // 2) horizontal solution\n\n // --- Pattern Matching Stage 5 ---\n // fill stars in field of view\n std::vector<Star> stars_in_fov;\n\n // --- Pattern Matching Stage 6 ---\n // perform matches\n std::vector<Star> matched_stars;\n std::vector<Blob> matched_blobs;\n int num_blobs_total;\n\n // --- Pattern Matching Stage 5 ---\n // get the final equatorial solution\n // (previous definitions of ra, dec, equatorial_roll, platescale, error)\n\n // --- Pattern Matching Stage 6 ---\n // get the final horizontal solution if there are any horizontal filters enabled\n // (previous definitions of az, el, horizontal_roll)\n\n // --- Pattern Matching Stage 7 ---\n // filter on (when applicable):\n // 1) equatorial solution\n // 2) horizontal solution\n // 3) platescale\n // 4) error\n // 5) matched_blobs.size()\n // 5) matched_blobs.size() / num_blobs_total\n\n // --- Pattern Matching Stage 8 ---\n // find exposure time (assuming gain 0.04096 ADU/e and aperture 0 for f1.8 200mm))\n double measured_exposure;\n\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.5748528838157654, "alphanum_fraction": 0.5951732397079468, "avg_line_length": 32.617218017578125, "blob_id": "ffe147c51f58cc33d41f7e26cb33b6135efa7848", "content_id": "a25f8562962b64d208a0381db8c1f377dd46ea94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 18357, "license_type": "no_license", "max_line_length": 136, "num_lines": 546, "path": "/stars/code/cataloging/abstract_catalog_manager.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"abstract_catalog_manager.h\"\n#include <cstdio>\n#include <string>\n#include <cstdlib>\n#include <stdlib.h>\n#include <boost/lexical_cast.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/filesystem.hpp>\t\t\t\t\t\n#include \"../tools/slalib.h\"\n#include \"../tools/angles.h\"\n#include \"../tools/ccd_projection.h\"\n#include \"../shared/solving/settings.h\"\n#include \"../parameters/manager.h\"\n#include \"../shared/general/quit.h\"\n#include \"../shared/image/raw.h\"\n#include \"../logging/logger.h\"\n\nusing namespace Cataloging;\nusing std::vector;\nusing std::string;\nusing std::ifstream;\nusing std::ios;\nusing std::numeric_limits;\nusing std::system;\nusing Solving::Star;\nusing Solving::Blob;\nusing Solving::Solution;\n#define shared_settings (*(Shared::Solving::settings.r)) // this assumes called from solver thread\n\ntypedef float catfloat;\n\nstruct RawTriplet\n{\n float dist1;\n float dist2;\n float dist3;\n int s1_id;\n float s1_ra;\n float s1_dec;\n int s2_id;\n float s2_ra;\n float s2_dec;\n int s3_id;\n float s3_ra;\n float s3_dec;\n};\n\nstruct RawPair\n{\n float dist;\n int s1_id;\n float s1_ra;\n float s1_dec;\n int s2_id;\n float s2_ra;\n float s2_dec;\n};\n\nstruct RawStar\n{\n int id;\n float ra;\n float dec;\n float mag;\n};\n\nRegion::Region()\n{\n}\n\nAbstractCatalogManager::AbstractCatalogManager(Parameters::Manager& params, bool enabled,\n string catalog_path_, Logging::Logger& logger_)\n{ \n\timage_width = params.general.image_width;\n\timage_height = params.general.image_height;\n mag_limit = numeric_limits<double>::infinity();\n catalog_path = fs::path(catalog_path_);\n logger = &logger_;\n}\n\nAbstractCatalogManager::~AbstractCatalogManager() {}\n\nvoid AbstractCatalogManager::init()\n{\n\tTools::Timer timer;\n\tstring line;\n\tint max_line_reads = 200000;\n\tint counter = 0;\n\n if (shared_settings.enabled) { \n\n\t\ttimer.start();\n logger->log(format(\"loading catalog %s\")%catalog_path);\n regions.reserve(422); // 422 is for combo_9p0_8p0 and combo_top3_top10\n if (exists(catalog_path)) {\n load_regions();\n }\n else {\n logger->log(format(\"catalog %s does not exist\")%catalog_path);\n }\n logger->log(format(\"loading catalog took %.3f s\")%timer.time());\n\n\t\ttimer.reset();\n\t\ttimer.start();\n\t\t\n\t\tif (star_names.size() == 0) {\n\t\t\tfs::path filename = catalog_path / \"lists\" / \"stars.txt\";\n\t\t\tifstream infile(filename.string().c_str());\n\t\t\tstd::stringstream ss(std::stringstream::in | std::stringstream::out);\n\t\t\tif (infile.is_open()) {\n\t\t\t\tdouble in0;\n\t\t\t\tstd::string in1;\n\t\t\t\twhile (infile.good() && counter < max_line_reads) {\n\t\t\t\t\tgetline(infile, line);\n\t\t\t\t\tss.clear();\n\t\t\t\t\tss.str(\"\");\n\t\t\t\t\tss << line;\n\t\t\t\t\tss >> in0 >> in1;\n\t\t\t\t\tif (!ss.fail()) {\n\t\t\t\t\t\tstar_names.push_back(std::make_pair(in0, in1));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tinfile.close();\n\t\t\t}\n\t\t\tlogger->log(format(\"cat: loading star name took %f s\") % timer.time());\n\t\t}\n }\n}\n\nRegion AbstractCatalogManager::load_region(fs::path filename)\n{\n catfloat temp = 0.0;\n Region region;\n region.stars.reserve(1451); // 1451 is the most in any region in combo_top3_top10\n ifstream infile(filename.string().c_str(), ios::in | ios::binary);\t\t//file_string\n if (infile.is_open()) {\n infile.read(reinterpret_cast <char *> (&temp), sizeof(catfloat));\n region.ra = double(temp);\n infile.read(reinterpret_cast <char *> (&temp), sizeof(catfloat));\n region.dec = double(temp);\n\n RawStar raw_star;\n while (infile.read((char *) &raw_star, sizeof(raw_star))) {\n if (raw_star.mag <= mag_limit) {\n Star star;\n star.id = raw_star.id;\n star.ra = double(raw_star.ra);\n star.dec = double(raw_star.dec);\n star.mag = double(raw_star.mag);\n region.stars.push_back(star);\n }\n }\n\n\n infile.close();\n }\n return region;\n}\n\nvoid AbstractCatalogManager::load_regions()\n{\n fs::path dir = catalog_path / \"regions\";\n if (exists(dir)) {\n fs::directory_iterator end;\n for (fs::directory_iterator iter(dir); iter!= end && !Shared::General::quit; ++iter) {\n if (!fs::is_directory(*iter)) {\n Region region = load_region(iter->path());\n regions.push_back(region);\n }\n }\n }\n\n}\n\nbool AbstractCatalogManager::in_range(double value, double min, double max)\n{\n return ((value >= min) && (value <= max));\n}\n\nvector<Solution> AbstractCatalogManager::load_triplets_from_file(vector<Blob>& base_blobs,\n int leg0, int leg1,\n double leg0min, double leg0max, double leg1min,\n double leg1max, double leg2min, double leg2max, Shared::Solving::Filters& filters)\n{\n fs::path filename = catalog_path / \"triplets\";\n filename /= boost::lexical_cast<string> (leg0);\n filename /= boost::lexical_cast<string> (leg1);\n\n vector<Solution> solutions;\n double epoch = get_epoch();\n\n RawTriplet triplet;\n\n ifstream infile(filename.string().c_str(), ios::in | ios::binary);\t\n if (infile.is_open()) {\n while (infile.read((char*) &triplet, sizeof(triplet))) {\n\n if (!in_range(triplet.dist1, leg0min, leg0max) ||\n !in_range(triplet.dist2, leg1min, leg1max) ||\n !in_range(triplet.dist3, leg2min, leg2max)) {\n continue;\n }\n\n precess_if_desired(epoch, triplet.s1_ra, triplet.s1_dec);\n precess_if_desired(epoch, triplet.s2_ra, triplet.s2_dec);\n precess_if_desired(epoch, triplet.s3_ra, triplet.s3_dec);\n\n if (!filters.check_field_star(triplet.s1_ra, triplet.s1_dec, shared_settings.iplatescale_max)) {\n continue;\n }\n if (!filters.check_field_star(triplet.s2_ra, triplet.s2_dec, shared_settings.iplatescale_max)) {\n continue;\n }\n if (!filters.check_field_star(triplet.s3_ra, triplet.s3_dec, shared_settings.iplatescale_max)) {\n continue;\n }\n\n\n Solution solution;\n solution.base_distances.push_back(triplet.dist1);\n solution.base_distances.push_back(triplet.dist2);\n solution.base_distances.push_back(triplet.dist2);\n Star star;\n star.id = triplet.s1_id; star.ra = triplet.s1_ra; star.dec = triplet.s1_dec; star.mag = -1234;\n solution.base_stars.push_back(star);\n star.id = triplet.s2_id; star.ra = triplet.s2_ra; star.dec = triplet.s2_dec; star.mag = -1234;\n solution.base_stars.push_back(star);\n star.id = triplet.s3_id; star.ra = triplet.s3_ra; star.dec = triplet.s3_dec; star.mag = -1234;\n solution.base_stars.push_back(star);\n solution.base_blobs = base_blobs;\n solutions.push_back(solution);\n\n }\n\n infile.close();\n }\n else {\n }\n\n return solutions;\n}\n\nvoid merge_solutions(vector<Solution>& solutions, vector<Solution>& new_solutions)\n{\n solutions.insert(solutions.end(), new_solutions.begin(), new_solutions.end());\n}\n\nvector<Solution> AbstractCatalogManager::load_solutions_from_triplet(vector<Blob>& blobs, Shared::Solving::Filters& filters)\n{\n Tools::Timer timer;\n timer.start();\n\n // this is a funny thing; already skipped the beginning of load solutions\n // assume blobs has size 3 and that's the triangle we're supposed to load\n\n double radians_to_filename_units = 180./M_PI*3600./60.; // filenames correspond to arcsec*60\n double double_correction = 0.00000001;\n\n double legs_min[3];\n double legs_max[3];\n double leg_tolerance = 40.0 / 3600.0 * M_PI/180.;\n\n double leg0min, leg0max, leg1min, leg1max, leg2min, leg2max;\n int leg0int, leg1int, leg0min_int, leg0max_int, leg1min_int, leg1max_int;\n\n int i, j, k, m, n;\n\n vector<Solution> solutions, temp_solutions;\n vector<Blob> base_blobs;\n\n for (i=0; i<3; i++) {\n j = (i+1)%3;\n legs_min[i] = tanplane_distance(blobs[i].x, blobs[i].y, blobs[j].x, blobs[j].y, shared_settings.iplatescale_min);\n legs_max[i] = tanplane_distance(blobs[i].x, blobs[i].y, blobs[j].x, blobs[j].y, shared_settings.iplatescale_max);\n }\n\n for (m=0; m<3; m++) {\n for (n=0; n<2; n++) {\n\n i = m;\n j = (m+(n+1))%3;\n k = (m+(1-n+1))%3;\n\n base_blobs.clear();\n base_blobs.push_back(blobs[i]);\n base_blobs.push_back(blobs[j]);\n base_blobs.push_back(blobs[k]);\n if (n==0) {\n leg0min = legs_min[i] - leg_tolerance;\n leg0max = legs_max[i] + leg_tolerance;\n leg1min = legs_min[j] - leg_tolerance;\n leg1max = legs_max[j] + leg_tolerance;\n leg2min = legs_min[k] - leg_tolerance;\n leg2max = legs_max[k] + leg_tolerance;\n }\n else {\n leg0min = legs_min[j] - leg_tolerance;\n leg0max = legs_max[j] + leg_tolerance;\n leg1min = legs_min[k] - leg_tolerance;\n leg1max = legs_max[k] + leg_tolerance;\n leg2min = legs_min[i] - leg_tolerance;\n leg2max = legs_max[i] + leg_tolerance;\n }\n if (leg1min <= leg0max && leg2min <= leg1max) {\n\n leg0min_int = std::max(0, int(floor(leg0min*radians_to_filename_units+double_correction)));\n leg0max_int = int(floor(leg0max*radians_to_filename_units+double_correction));\n leg1min_int = std::max(0, int(floor(leg1min*radians_to_filename_units+double_correction)));\n leg1max_int = int(floor(leg1max*radians_to_filename_units+double_correction));\n\n for (leg0int = leg0min_int; leg0int <= leg0max_int; leg0int++) {\n for (leg1int = leg1min_int; leg1int <= leg1max_int; leg1int++) {\n temp_solutions = load_triplets_from_file(base_blobs,\n leg0int, leg1int, leg0min, leg0max, leg1min, leg1max, leg2min, leg2max, filters);\n for (unsigned int snum = 0; snum < temp_solutions.size(); snum++) {\n if (true) {\n solutions.push_back(temp_solutions[snum]);\n }\n }\n }\n }\n\n }\n }\n }\n\n logger->log(format(\"cat: loading %d triplets took %f s\")%solutions.size()%timer.time());\n\n return solutions;\n}\n\nvector<Solution> AbstractCatalogManager::load_pairs_from_file(vector<Blob>& base_blobs,\n int leg, double leg_min, double leg_max, Shared::Solving::Filters& filters)\n{\n fs::path filename = catalog_path / \"pairs\";\n filename /= boost::lexical_cast<string> (leg);\n\n vector<Solution> solutions;\n\n double epoch = get_epoch();\n\n ifstream infile(filename.string().c_str(), ios::in | ios::binary);\t\n if (infile.is_open()) {\n\n RawPair pair;\n while (infile.read((char *) &pair, sizeof(pair))) {\n if (!in_range(pair.dist, leg_min, leg_max)) {\n continue;\n }\n\n precess_if_desired(epoch, pair.s1_ra, pair.s1_dec);\n precess_if_desired(epoch, pair.s2_ra, pair.s2_dec);\n\n if (!filters.check_field_star(pair.s1_ra, pair.s1_dec, shared_settings.iplatescale_max)) {\n continue;\n }\n if (!filters.check_field_star(pair.s2_ra, pair.s2_dec, shared_settings.iplatescale_max)) {\n continue;\n }\n\n Solution solution1;\n solution1.base_distances.push_back(pair.dist);\n Star star1;\n star1.id = pair.s1_id; star1.ra = pair.s1_ra; star1.dec = pair.s1_dec; star1.mag = -1234;\n solution1.base_stars.push_back(star1);\n star1.id = pair.s2_id; star1.ra = pair.s2_ra; star1.dec = pair.s2_dec; star1.mag = -1234;\n solution1.base_stars.push_back(star1);\n solution1.base_blobs = base_blobs;\n solutions.push_back(solution1);\n\n Solution solution2;\n solution2.base_distances.push_back(pair.dist);\n Star star2;\n star2.id = pair.s2_id; star2.ra = pair.s2_ra; star2.dec = pair.s2_dec; star2.mag = -1234;\n solution2.base_stars.push_back(star2);\n star2.id = pair.s1_id; star2.ra = pair.s1_ra; star2.dec = pair.s1_dec; star2.mag = -1234;\n solution2.base_stars.push_back(star2);\n solution2.base_blobs = base_blobs;\n solutions.push_back(solution2);\n }\n\n infile.close();\n }\n else {\n }\n\n return solutions;\n}\n\nvector<Solution> AbstractCatalogManager::load_solutions_from_pair(vector<Blob>& blobs, Shared::Solving::Filters& filters)\n{\n Tools::Timer timer;\n timer.start();\n\n vector<Solution> solutions, temp_solutions;\n\n double radians_to_filename_units = 180./M_PI*3600./60.; // filenames correspond to arcsec*60\n double double_correction = 0.00000001;\n double leg_tolerance = 40.0 / 3600.0 * M_PI/180.;\n\n double leg_min = tanplane_distance(blobs[0].x, blobs[0].y, blobs[1].x, blobs[1].y, shared_settings.iplatescale_min) - leg_tolerance;\n double leg_max = tanplane_distance(blobs[0].x, blobs[0].y, blobs[1].x, blobs[1].y, shared_settings.iplatescale_max) + leg_tolerance;\n\n vector<Blob> base_blobs;\n for (unsigned int i=0; i<2; i++) {\n unsigned int j = 1-i;\n base_blobs.clear();\n base_blobs.push_back(blobs[i]);\n base_blobs.push_back(blobs[j]);\n\n int leg_min_int = std::max(0, int(floor(leg_min*radians_to_filename_units+double_correction)));\n int leg_max_int = int(floor(leg_max*radians_to_filename_units+double_correction));\n for (int leg_int = leg_min_int; leg_int <= leg_max_int; leg_int++) {\n temp_solutions = load_pairs_from_file(base_blobs, leg_int, leg_min, leg_max, filters);\n for (unsigned int snum = 0; snum < temp_solutions.size(); snum++) {\n if (true) {\n solutions.push_back(temp_solutions[snum]);\n }\n }\n }\n }\n logger->log(format(\"cat: loading %d pairs took %f s\")%solutions.size()%timer.time());\n return solutions;\n}\n\n\nvector<Star> AbstractCatalogManager::get_stars_near(double ra, double dec)\n{\n unsigned int i, best_i;\n double distance, best_distance;\n best_distance = numeric_limits<double>::infinity();\n best_i = 0;\n for (i=0; i<regions.size(); i++) {\n distance = great_circle(ra, dec, regions[i].ra, regions[i].dec);\n if (distance < best_distance) {\n best_distance = distance;\n best_i = i;\n }\n }\n return regions[best_i].stars;\n}\n\nbool cm_is_inbounds_centered(double& u, double& v, double& width, double& height)\n{\n // this should be put in tools, as should angdist func\n if ((u > width/2.0) || (u < -width/2.0)) {\n return false;\n }\n if ((v > height/2.0) || (v < -height/2.0)) {\n return false;\n }\n return true;\n}\n\ndouble AbstractCatalogManager::get_epoch()\n{\n double epoch = 2000.0;\n if (shared_settings.precession_epoch_source == Shared::Solving::Settings::precession_system_time) {\n boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();\n int year = now.date().year();\n int month = now.date().month();\n int day = now.date().day();\n double mjd;\n int flag;\n Slalib::slaCaldj(year, month, day, &mjd, &flag);\n epoch = Slalib::slaEpj(mjd);\n } else if (shared_settings.precession_epoch_source == Shared::Solving::Settings::precession_manual) {\n epoch = shared_settings.precession_manual_epoch;\n }\n return epoch;\n}\n\nvoid AbstractCatalogManager::precess_if_desired(double epoch, float& ra, float& dec)\n{\n double ra_d = (double) ra;\n double dec_d = (double) dec;\n precess_if_desired(epoch, ra_d, dec_d);\n ra = (float) ra_d;\n dec = (float) dec_d;\n}\n\nvoid AbstractCatalogManager::precess_if_desired(double epoch, double& ra, double& dec)\n{\n if (shared_settings.precession_epoch_source == Shared::Solving::Settings::precession_system_time ||\n shared_settings.precession_epoch_source == Shared::Solving::Settings::precession_manual)\n {\n Slalib::slaPreces((char*) \"FK5\", 2000, epoch, &ra, &dec);\n }\n}\n\nvoid AbstractCatalogManager::fill_stars_in_fov(Solution& solution, Shared::Image::Raw& image,\n Shared::Solving::Refraction& refraction_settings)\n{\n\n vector<Star> nearby_stars;\n double u = 0.0;\n double v = 0.0;\n double cos_roll = cos(solution.equatorial.roll);\n double sin_roll = sin(solution.equatorial.roll);\n double distance = 0.0;\n double width = image_width;\n double height = image_height;\n\n nearby_stars = get_stars_near(solution.equatorial.ra, solution.equatorial.dec);\n\n double epoch = get_epoch();\n for (unsigned int i=0; i<nearby_stars.size(); i++) {\n precess_if_desired(epoch, nearby_stars[i].ra, nearby_stars[i].dec);\n }\n\n double star_ra = 0.0;\n double star_dec = 0.0;\n for (unsigned int i=0; i<nearby_stars.size(); i++) {\n distance = great_circle(solution.equatorial.ra, solution.equatorial.dec, nearby_stars[i].ra, nearby_stars[i].dec);\n if (distance < from_degrees(3.2)) {\n Tools::get_refraction_corrected_equatorial(nearby_stars[i].ra, nearby_stars[i].dec,\n shared_settings.refraction, image.filters, star_ra, star_dec);\n Tools::ccd_projection(star_ra, star_dec, solution.equatorial.ra, solution.equatorial.dec,\n 1.0/solution.equatorial.iplatescale, cos_roll, sin_roll, u, v, true);\n\n if (cm_is_inbounds_centered(u, v, width, height)) {\n solution.stars_in_fov.push_back(nearby_stars[i]);\n }\n }\n }\n}\n\nvoid AbstractCatalogManager::get_star_name(int id, string& name, double& mag)\n{\n\n\tif ((int)star_names.size() >= id) {\n\t\tname = star_names[id].second;\n\t\tmag = star_names[id].first;\n\t}\n}\n\nbool AbstractCatalogManager::abort()\n{\n return false;\n}\n\n" }, { "alpha_fraction": 0.7150368094444275, "alphanum_fraction": 0.7150368094444275, "avg_line_length": 35.61538314819336, "blob_id": "a676bf202c336b85c918658a5b51f80772ef09e1", "content_id": "507271446bc2c0e42fa7089bd0df946f09eb1a21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 951, "license_type": "no_license", "max_line_length": 52, "num_lines": 26, "path": "/external_libs/soem/soem/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "set(SOEM_SRCS\n ${SOEM_SRCS}\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatbase.c\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatcoe.c\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatconfig.c\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatdc.c\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatfoe.c\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatmain.c\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatprint.c\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatsoe.c\n PARENT_SCOPE\n)\nset(OSHW_HEADERS\n ${OSHW_HEADERS}\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatbase.h\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatcoe.h\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatconfig.h\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatconfiglist.h\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatdc.h\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatfoe.h\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatmain.h\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatprint.h\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercatsoe.h\n ${CMAKE_CURRENT_SOURCE_DIR}/ethercattype.h\n PARENT_SCOPE\n)" }, { "alpha_fraction": 0.4923161268234253, "alphanum_fraction": 0.5115258097648621, "avg_line_length": 25.201438903808594, "blob_id": "752095c56a9969f6e559951d0ab9bf39f6b8051b", "content_id": "095791b2915a7788afa014f89290ae9b0a7b10d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3644, "license_type": "no_license", "max_line_length": 83, "num_lines": 139, "path": "/common/lut.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* mcp: the BLAST master control program\n *\n * This software is copyright (C) 2003-2005 University of Toronto\n *\n * This file is part of mcp.\n *\n * mcp 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#include \"blast.h\"\n#include \"lut.h\"\n\n#define MAXITER 10\n#define MAX_LINE_LENGTH 1024\n#define TOLERANCE (10.0/3600.*M_PI/180.)\n\n/***************************************************************************/\n/* GetLine: read non-comment line from file */\n/* The line is placed in *line. */\n/* Returns 1 if succesful, 0 if unsuccesful */\n/***************************************************************************/\nint GetLine(FILE *fp, char *line)\n{\n char buffer[MAX_LINE_LENGTH];\n char *ret_val;\n int first_char;\n\n do {\n ret_val = fgets(buffer, MAX_LINE_LENGTH, fp);\n if (ret_val != NULL) {\n first_char = 0;\n while ((buffer[first_char] == ' ') || (buffer[first_char] == '\\t'))\n\tfirst_char++;\n strncpy(line, &buffer[first_char], MAX_LINE_LENGTH - first_char);\n }\n } while ((ret_val != NULL) && ((line[0] == '#') || (strlen(line) < 2)));\n\n if (ret_val != NULL)\n return 1; /* a line was read */\n else\n return 0; /* there were no valid lines */\n}\n\nvoid LutInit(struct LutType *L)\n{\n int i;\n\n FILE *fp;\n char line[1024];\n\n fp = fopen(L->filename, \"r\");\n if (fp == NULL) {\n blast_err(\"LUT: error reading LUT file %s: no calibration\\n\", L->filename);\n L->n = 1;\n return;\n }\n\n /* first read the file to see how big it is */\n i = 0;\n while (GetLine(fp, line))\n i++;\n\n if (i < 2) {\n blast_err(\"LUT: error reading LUT file %s: no calibration\\n\", L->filename);\n L->n = 1;\n return;\n }\n\n // blast_info(\"LUT: Reading lut `%s' with %i lines\\n\", L->filename, i);\n L->n = i;\n L->x = (double *) balloc(fatal, i * sizeof(double));\n L->y = (double *) balloc(fatal, i * sizeof(double));\n\n /* now read in the data */\n rewind(fp);\n for (i = 0; i < L->n; i++) {\n GetLine(fp, line);\n sscanf(line, \"%lg %lg\", &(L->x[i]), &(L->y[i]));\n }\n L->last_n = L->n / 2;\n\n /* Is the LUT index ascending or descending? */\n if (L->x[1] <= L->x[(L->n) - 1]) {\n L->dir = 1;\n } else {\n L->dir = -1;\n }\n}\n\ndouble LutCal(struct LutType *L, double x)\n{\n int i, n;\n double y;\n\n n = L->n;\n\n if (n == 1) {\n return(x); // no LUT, not cal\n }\n /* find index */\n i = L->last_n;\n\n if (L->dir >= 0) {\n while ((i < n - 2) && (x > L->x[i]))\t// i can't be over n-2 since i+1 is used\n i++;\n while ((i > 0) && (x < L->x[i]))\n i--;\n } else {\n while ((i < n - 2) && (x < L->x[i]))\n i++;\n while ((i > 0) && (x > L->x[i]))\n i--;\n }\n\n L->last_n = i;\n\n y = L->y[i] + (L->y[i + 1] - L->y[i]) / (L->x[i + 1] - L->x[i]) *\n (x - L->x[i]);\n\n return(y);\n}\n\n\n" }, { "alpha_fraction": 0.6650227904319763, "alphanum_fraction": 0.7245826721191406, "avg_line_length": 37.20289993286133, "blob_id": "cd5595a226eb88e39c26b645a31124e2686a0b6a", "content_id": "09a6c950d4f0ae285ba6a6b43b1bae2ff9dd391c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2636, "license_type": "no_license", "max_line_length": 71, "num_lines": 69, "path": "/common/include/quenya.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* quenya.h: Quenya Protocol definitions\n *\n * This software is copyright (C) 2004 University of Toronto\n * \n * This 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 2 of the License, or\n * (at your option) any later version.\n * \n * This 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 this file; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#ifndef QUENYA_H\n#define QUENYA_H\n\n/* Responses */\n#define QUENYA_RESPONSE_LISTENING 123\n#define QUENYA_RESPONSE_SENDING_SPEC 152\n#define QUENYA_RESPONSE_SENDING_DATA 153\n#define QUENYA_RESPONSE_OK 200\n#define QUENYA_RESPONSE_DATA_STAGED 211\n#define QUENYA_RESPONSE_FRAME_SIZE 212\n#define QUENYA_RESPONSE_STAGED_NEXT 213\n#define QUENYA_RESPONSE_SERVICE_READY 220\n#define QUENYA_RESPONSE_GOODBYE 221\n#define QUENYA_RESPONSE_PORT_OPENED 223\n#define QUENYA_RESPONSE_ACCESS_GRANTED 230\n#define QUENYA_RESPONSE_TRANS_COMPLETE 250\n#define QUENYA_RESPONSE_BLOCK_CRC 316\n#define QUENYA_RESPONSE_OPEN_ERROR 423\n#define QUENYA_RESPONSE_NO_CUR_DATA 451\n#define QUENYA_RESPONSE_SYNTAX_ERROR 500\n#define QUENYA_RESPONSE_PARAM_ERROR 501\n#define QUENYA_RESPONSE_CMD_NOT_IMPL 502\n#define QUENYA_RESPONSE_PORT_INACTIVE 503\n#define QUENYA_RESPONSE_PORT_NOT_OPEN 523\n#define QUENYA_RESPONSE_PORT_ACTIVE 524\n#define QUENYA_RESPONSE_NOT_IDENTIFIED 530\n#define QUENYA_RESPONSE_NO_ACCESS 531\n#define QUENYA_RESPONSE_NO_DATA_STAGED 551\n#define QUENYA_RESPONSE_TIMEOUT 621\n#define QUENYA_RESPONSE_PORT_CLOSE_ERR 623\n\n/* Commands */\n#define QUENYA_COMMAND_DATA 1000\n#define QUENYA_COMMAND_SPEC 1001\n#define QUENYA_COMMAND_SYNC 1002\n#define QUENYA_COMMAND_RTBK 1003\n#define QUENYA_COMMAND_IDEN 1004\n#define QUENYA_COMMAND_OPEN 1005\n#define QUENYA_COMMAND_ASYN 1006\n#define QUENYA_COMMAND_NOOP 1007\n#define QUENYA_COMMAND_ABOR 1008\n#define QUENYA_COMMAND_CLOS 1009\n#define QUENYA_COMMAND_QUIT 1010\n#define QUENYA_COMMAND_CONT 1011\n#define QUENYA_COMMAND_QNOW 1012\n#define QUENYA_COMMAND_RDVS 1013\n#define QUENYA_COMMAND_SIZE 1014\n\n#endif\n" }, { "alpha_fraction": 0.6621392369270325, "alphanum_fraction": 0.6675155758857727, "avg_line_length": 22.87162208557129, "blob_id": "f97d2834c3f99d820d6e9d34a9442da8005e2d28", "content_id": "6afebf603aa41f5cb3102d23d51895895be491e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3534, "license_type": "no_license", "max_line_length": 74, "num_lines": 148, "path": "/starcam/camcommserver.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <unistd.h>\n#include <sys/socket.h>\n#include <sys/types.h>\n#include <arpa/inet.h>\n#include \"camcommserver.h\"\n\n#define CCSERV_DEBUG 0\n\nCamCommServer::CamCommServer(short int port /* = DEFAULT_CAM_PORT */)\n{\n serverFD = -1;\n first = last = NULL;\n count = 0;\n listenPort = port;\n}\n\nCamCommServer::~CamCommServer()\n{\n while (last != NULL) remove(last);\n closeConnection();\n}\n\n\n\n//let connection run its read loop in a thread\n//this takes a bit of a hack to allow calling the C++ member\nstruct servconn {\n CamCommServer* server;\n CamCommServer::camConnection* connection;\n};\nstatic void* runConnectionWrap(void* arg)\n{\n servconn* sc = (servconn*)arg;\n sc->server->runConnection(sc->connection);\n return NULL;\n}\nvoid CamCommServer::runConnection(camConnection* conn)\n{\n add(conn);\n cout << \"New connection recieved from: \" << conn->comm->target << endl;\n conn->comm->readLoop(conn->interpreter);\n\n cout << \"Connection terminated from: \" << conn->comm->target << endl;\n remove(conn);\n}\n\n//perpetually listen for new conenctions\n//should be created in its own thread\nint CamCommServer::startServer(string (*interpretFunction)(string))\n{\n sockaddr_in servaddr;\n servaddr.sin_family = AF_INET;\n servaddr.sin_port = htons(listenPort);\n servaddr.sin_addr.s_addr = htonl(INADDR_ANY);\n\n serverFD = socket(PF_INET, SOCK_STREAM, 0);\n if (serverFD < 0) {\n return -1;\n }\n //enable address reuse (to restart without having to wait forever)\n int optval = 1;\n setsockopt(serverFD, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));\n if (bind(serverFD, (sockaddr*)&servaddr, sizeof(servaddr)) < 0) {\n closeConnection();\n return -2;\n }\n if (listen(serverFD, 2) < 0) {\n closeConnection();\n return -3;\n }\n\n while (1) {\n sockaddr_in cliaddr;\n socklen_t clilen = sizeof(cliaddr);\n int clifd = accept(serverFD, (sockaddr*)&cliaddr, &clilen);\n if (clifd < 0) {\n#if CCSERV_DEBUG\n cerr << \"[CCServer Debug]: failed to accept connection.\" << endl;\n#endif\n continue;\n }\n //otherwise, got a good fd and have a new connection\n camConnection* conn = new camConnection();\n conn->comm = new CamCommunicator();\n conn->interpreter = interpretFunction;\n conn->comm->serverFD = -2;\n conn->comm->commFD = clifd;\n conn->comm->target = inet_ntoa(cliaddr.sin_addr);\n //hack to allow calling member in pthread\n servconn sc;\n sc.server = this;\n sc.connection = conn;\n pthread_create(&conn->thread, NULL, runConnectionWrap, (void*)&sc);\n }\n\n return 0;\n}\n\n\n\n//send a message over all connected sockets\nint CamCommServer::sendAll(string msg)\n{\n camConnection* conn = first;\n while (conn != NULL) {\n conn->comm->sendCommand(msg);\n conn = conn->next;\n }\n return 0;\n}\n\n\n\nvoid CamCommServer::closeConnection()\n{\n if (serverFD >= 0) {\n close(serverFD);\n serverFD = -1;\n }\n}\n\n\n\n//add new connection to end of the list\nvoid CamCommServer::add(camConnection* addee)\n{\n addee->prev = last;\n addee->next = NULL;\n if (last != NULL) last->next = addee;\n else first = addee; //last == NULL means first == NULL too\n last = addee;\n count++;\n}\n\n//remove connection from anywhere in the list\nvoid CamCommServer::remove(camConnection* removee)\n{\n if (removee->next == NULL)\n last = removee->prev;\n else removee->next->prev = removee->prev;\n if (removee->prev == NULL)\n first = removee->next;\n else removee->prev->next = removee->next;\n delete removee->comm; //delete the CamCommunicator first\n delete removee;\n count--;\n}\n\n" }, { "alpha_fraction": 0.6947988271713257, "alphanum_fraction": 0.7036309838294983, "avg_line_length": 21.64444351196289, "blob_id": "2a80541256ca959f0703ee8281ac25ff172cfc7c", "content_id": "4d12d6d3e52dda7484843c4fdd845d3a3eee0ec2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1019, "license_type": "no_license", "max_line_length": 129, "num_lines": 45, "path": "/starcam/imageviewer.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#ifndef IMAGEVIEWER_H\n#define IMAGEVIEWER_H\n\n#include <qwidget.h>\n\n/**\n\t@author Steve Benton <[email protected]>\n\tQt widget for displaying BlobImage objects\n*/\n\nclass BlobImage;\nclass QTimer;\n\nclass ImageViewer : public QWidget\n{\n\tQ_OBJECT\npublic:\n ImageViewer(int width, int height, int img_width, int img_height, int msec = 10, QWidget *parent = 0, const char * name = 0);\n void load(BlobImage *img, bool autoBR = FALSE);\n static unsigned char conv16to8(unsigned short val16, unsigned short back, \n\t\t unsigned short range);\n int getRefreshTime() { return refreshTime; }\n void setRefreshTime(int msec);\n void manualRepaint() { needsRepaint = true; }\n\n ~ImageViewer();\n\t\npublic slots:\n\tvoid refresh();\n\t\nprotected:\n\tvoid paintEvent(QPaintEvent*);\n\t\nprivate:\n\tQImage *qimg; //copy of BlobImage in QImage format\n\tQTimer *refreshTimer;\n\tint refreshTime; //time (ms) between image refreshes\n\t\n\tBlobImage *bimg; //pointer to current blob image\n\tbool autoBR;\n\tbool needsRepaint;\n\tbool loading;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6611909866333008, "alphanum_fraction": 0.6681724786758423, "avg_line_length": 26.514123916625977, "blob_id": "28bebf80dcde45493ad02d15820d12fb150b2e4d", "content_id": "5027bdc433632c5c32bd1326f824310bc2c45af8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4870, "license_type": "no_license", "max_line_length": 80, "num_lines": 177, "path": "/common/include/pq.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * pq.h\n *\n * @date Jan 31, 2011\n * @author seth\n *\n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2010 Columbia University\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * Based on fdqueue.c from the Apache httpd project. Original code is\n * licensed under Apache License version 2.0. A copy of this is\n * available at http://www.apache.org/licenses/LICENSE-2.0\n *\n */\n\n#ifndef INCLUDE_PQ_H_\n#define INCLUDE_PQ_H_\n\n#include <stdint.h>\n#include <unistd.h>\n\n/** priority data type */\ntypedef uint64_t pq_pri_t;\n\n/** callback functions to get/set/compare the priority of an element */\ntypedef pq_pri_t (*pq_get_pri_f)(void *a);\ntypedef void (*pq_set_pri_f)(void *a, pq_pri_t pri);\ntypedef int (*pq_cmp_pri_f)(pq_pri_t next, pq_pri_t curr);\n\n\n/** callback functions to get/set the position of an element */\ntypedef size_t (*pq_get_pos_f)(void *a);\ntypedef void (*pq_set_pos_f)(void *a, size_t pos);\n\n\n/** debug callback function to print a entry */\ntypedef void (*pq_print_entry_f)(FILE *out, void *a);\n\n\n/** the priority queue handle */\ntypedef struct pq_t\n{\n size_t size; /**< number of elements in this queue */\n size_t avail; /**< slots available in this queue */\n size_t step; /**< growth stepping setting */\n pq_cmp_pri_f cmppri; /**< callback to compare nodes */\n pq_get_pri_f getpri; /**< callback to get priority of a node */\n pq_set_pri_f setpri; /**< callback to set priority of a node */\n pq_get_pos_f getpos; /**< callback to get position of a node */\n pq_set_pos_f setpos; /**< callback to set position of a node */\n void **d; /**< The actual queue in binary heap form */\n} pq_t;\n\n\n/**\n * initialize the queue\n *\n * @param n the initial estimate of the number of queue items for which memory\n * should be preallocated\n * @param cmppri The callback function to run to compare two elements\n * This callback should return 0 for 'lower' and non-zero\n * for 'higher', or vice versa if reverse priority is desired\n * @param setpri the callback function to run to assign a score to an element\n * @param getpri the callback function to run to set a score to an element\n * @param getpos the callback function to get the current element's position\n * @param setpos the callback function to set the current element's position\n *\n * @return the handle or NULL for insufficent memory\n */\npq_t *\npq_init(size_t n, pq_cmp_pri_f cmppri, pq_get_pri_f getpri, pq_set_pri_f setpri,\n pq_get_pos_f getpos, pq_set_pos_f setpos);\n\n\n/**\n * free all memory used by the queue\n * @param q the queue\n */\nvoid pq_free(pq_t *q);\n\n\n/**\n * return the size of the queue.\n * @param q the queue\n */\nsize_t pq_size(pq_t *q);\n\n\n/**\n * insert an item into the queue.\n * @param q the queue\n * @param d the item\n * @return 0 on success\n */\nint pq_insert(pq_t *q, void *d);\n\n\n/**\n * move an existing entry to a different priority\n * @param q the queue\n * @param new_pri the new priority\n * @param d the entry\n */\nvoid pq_change_priority(pq_t *q, pq_pri_t new_pri, void *d);\n\n\n/**\n * pop the highest-ranking item from the queue.\n * @param q the queue\n * @return NULL on error, otherwise the entry\n */\nvoid *pq_pop(pq_t *q);\n\n\n/**\n * remove an item from the queue.\n * @param q the queue\n * @param d the entry\n * @return 0 on success\n */\nint pq_remove(pq_t *q, void *d);\n\n\n/**\n * access highest-ranking item without removing it.\n * @param q the queue\n * @return NULL on error, otherwise the entry\n */\nvoid *pq_peek(pq_t *q);\n\n\n/**\n * print the queue\n * @internal\n * DEBUG function only\n * @param q the queue\n * @param out the output handle\n * @param the callback function to print the entry\n */\nvoid pq_print(pq_t *q, FILE *out, pq_print_entry_f print);\n\n\n/**\n * dump the queue and it's internal structure\n * @internal\n * debug function only\n * @param q the queue\n * @param out the output handle\n * @param the callback function to print the entry\n */\nvoid pq_dump(pq_t *q, FILE *out, pq_print_entry_f print);\n\n\n/**\n * checks that the pq is in the right order, etc\n * @internal\n * debug function only\n * @param q the queue\n */\nint pq_is_valid(pq_t *q);\n\n#endif /* INCLUDE_PQ_H_ */\n" }, { "alpha_fraction": 0.6270081400871277, "alphanum_fraction": 0.6352735757827759, "avg_line_length": 30.350364685058594, "blob_id": "ef7226c23d4bbe6cba6e8ced80913c7d51e470a5", "content_id": "98e45bbd4ea0100fac7a0565fedb85bcfdd28719", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8590, "license_type": "no_license", "max_line_length": 120, "num_lines": 274, "path": "/blast_comms/comms_serial.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/**\n * @file comms_serial.c\n *\n * @date 2011-02-07\n * @author Seth Hillbrand\n *\n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2011-2015 Seth Hillbrand\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n#include <stdbool.h>\n#include <termios.h>\n#include <fcntl.h>\n#include <sys/ioctl.h>\n#include <linux/serial.h>\n\n#include <blast.h>\n#include <comms_common.h>\n#include <comms_serial.h>\n#include <comms_netsock.h>\n\n/**\n * The allocate function for a serial line is the same as for a network socket. The exception is that we set #is_socket\n * to false to ensure we use \"write\" instead of \"send\" and \"read\" instead of \"recv\"\n * @param m_data Pointer to custom data. This will be passed as part of the socket to any handler functions\n * @return New socket pointer on success, NULL on failure\n */\ncomms_serial_t *comms_serial_new(void *m_data)\n{\n\tcomms_serial_t *serial;\n\n\tserial = (comms_serial_t *)malloc(sizeof(comms_serial_t));\n\tif (!serial) return NULL;\n\tmemset(serial, 0, sizeof(comms_serial_t));\n\n\tserial->sock = comms_sock_new();\n\tif (!serial->sock) {\n\t\tlog_leave(\"Could not register serial socket\");\n\t\treturn NULL;\n\t}\n\n\tserial->sock->is_socket = false;\n\tserial->sock->priv_data = m_data;\n\n\t/**\n\t * Sets the terminal to RAW mode (no echo, no special processing, character at a time IO\n\t */\n\n\tserial->term.c_cflag = CS8 | B1200 | CLOCAL | CREAD;\n\n\tlog_leave();\n\treturn serial;\n}\n\n/**\n * Takes a double-pointer to a serial fd and ensures that it is in a pristine state, ready for a new connection.\n * @param m_sock Double pointer to a serial fd\n */\nvoid comms_serial_reset(comms_serial_t **m_serial)\n{\n log_enter();\n if (!(*m_serial)) {\n *m_serial = comms_serial_new(NULL);\n } else {\n if (!pthread_mutex_lock(&(*m_serial)->mutex)) {\n comms_sock_reset(&(*m_serial)->sock);\n (*m_serial)->sock->is_socket = false;\n pthread_mutex_unlock(&(*m_serial)->mutex);\n }\n } log_leave();\n}\n\nvoid comms_serial_close(comms_serial_t *m_serial)\n{\n if (m_serial && m_serial->sock) {\n if (!pthread_mutex_lock(&m_serial->mutex)) {\n comms_sock_close(m_serial->sock);\n pthread_mutex_unlock(&m_serial->mutex);\n }\n }\n}\n\nvoid comms_serial_free(void *m_serial)\n{\n /// This will close and free the socket and its buffers\n if (m_serial) {\n comms_serial_close(m_serial);\n free(m_serial);\n }\n}\n\nbool comms_serial_setspeed(comms_serial_t *m_serial, speed_t m_speed)\n{\n if (cfsetospeed(&m_serial->term, m_speed) || cfsetispeed(&m_serial->term, m_speed)) {\n blast_err(\"Could not set speed to %d\", (int) m_speed);\n return false;\n }\n\n if (m_serial->sock->fd != INVALID_SOCK) {\n tcsetattr(m_serial->sock->fd, TCSANOW, &m_serial->term);\n }\n return true;\n}\n\nint comms_serial_set_baud_base(comms_serial_t *m_serial, int m_base)\n{\n struct serial_struct ss;\n if (ioctl(m_serial->sock->fd, TIOCGSERIAL, &ss) != 0) {\n blast_strerror(\"TIOCGSERIAL failed\");\n return -1;\n }\n\n ss.baud_base = m_base;\n\n if (ioctl(m_serial->sock->fd, TIOCSSERIAL, &ss)) {\n blast_strerror(\"Count not set base to %d\", m_base);\n return -1;\n }\n return 0;\n}\n\nint comms_serial_set_baud_divisor(comms_serial_t *m_serial, int m_speed)\n{\n // default baud was not found, so try to set a custom divisor\n struct serial_struct ss;\n if (ioctl(m_serial->sock->fd, TIOCGSERIAL, &ss) != 0) {\n blast_strerror(\"TIOCGSERIAL failed\");\n return -1;\n }\n\n ss.flags = (ss.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST;\n ss.custom_divisor = (ss.baud_base + (m_speed / 2)) / m_speed;\n\n if (m_speed > 115200) ss.custom_divisor |= (1 << 15); // Set the High-speed bit\n /**\n * It is debatable whether this next line is required. Generally, we need frob config\n * bits to get 921600 (despite the SMSC manual's directions). But it doesn't seem to hurt so we\n * keep it here for completeness.\n */\n if (m_speed > 460800) ss.custom_divisor |= (1 << 14); // Set the Enhanced Freq low bit\n\n if (ioctl(m_serial->sock->fd, TIOCSSERIAL, &ss)) {\n blast_strerror(\"Count not set divisor to %d\", m_speed);\n return -1;\n }\n return 0;\n}\n/**\n * Buffer data for asynchronous writing to the serial device\n * @param m_serial Pointer to the serial structure\n * @param m_buf Pointer to the data stream from which to write\n * @param m_len Length in bytes to write\n * @return NETSOCK_OK on success, NETSOCK_ERR on failure\n */\nint comms_serial_write(comms_serial_t *m_serial, const void *m_buf, size_t m_len)\n{\n int retval;\n\n if (m_serial && m_serial->sock) {\n if (!pthread_mutex_lock(&m_serial->mutex)) {\n retval = comms_sock_write(m_serial->sock, m_buf, m_len);\n pthread_mutex_unlock(&m_serial->mutex);\n if (retval != NETSOCK_ERR) return NETSOCK_OK;\n } else {\n blast_err(\"Could not lock mutex!\");\n return NETSOCK_ERR;\n }\n } else {\n blast_err(\"Attempted to write to NULL Socket for serial port\");\n }\n return NETSOCK_ERR;\n}\n\n/**\n * Open a serial port device for bi-directional, asynchronous communication\n * @param m_serial Pointer to the serial structure\n * @param m_terminal Name of the tty serial device\n * @return NETSOCK_OK on success, NETSOCK_ERR on failure\n */\nint comms_serial_connect(comms_serial_t *m_serial, const char *m_terminal)\n{\n log_enter();\n\n if (!m_terminal) {\n blast_err(\"Passed NULL pointer to terminal name\");\n log_leave(\"NULL\");\n return NETSOCK_ERR;\n }\n\n if (m_serial->sock->fd != INVALID_SOCK) comms_serial_close(m_serial);\n\n if ((m_serial->sock->fd = open(m_terminal, O_NOCTTY | O_RDWR)) == INVALID_SOCK) {\n blast_strerror(\"Could not open terminal '%s'\", m_terminal);\n log_leave(\"Open Error\");\n return NETSOCK_ERR;\n }\n\n if (!m_serial->sock->host) {\n blast_info(\"Successfully opened %s for serial communication\", m_terminal);\n m_serial->sock->host = bstrdup(err, m_terminal);\n } else if (strcmp(m_serial->sock->host, m_terminal)) {\n blast_info(\"Successfully opened %s for serial communication\", m_terminal);\n bfree(err, m_serial->sock->host);\n m_serial->sock->host = bstrdup(err, m_terminal);\n }\n\n m_serial->sock->state = NETSOCK_STATE_CONNECTING;\n\n tcsetattr(m_serial->sock->fd, TCSANOW, &m_serial->term);\n\n comms_net_async_set_events(comms_sock_get_poll_handle(m_serial->sock), POLLOUT);\n\n m_serial->sock->can_write = true;\n\n log_leave();\n return NETSOCK_OK;\n}\n\n/**\n * Connects the #comms_serial_t structure to a known FIFO file.\n * @param m_serial Pointer to the serial structure\n * @param m_fifo Name of the FIFO to open\n * @param m_flags flags that will be passed to open(2) (e.g. O_RDONLY, O_WRONLY). O_NONBLOCK is assumed.\n * @return NETSOCK_OK on success, NETSOCK_ERR on failure\n */\nint comms_fifo_connect(comms_serial_t *m_serial, const char *m_fifo, int m_flags)\n{\n log_enter();\n\n if (!m_fifo) {\n blast_err(\"Passed NULL pointer to FIFO name\");\n log_leave(\"NULL\");\n return NETSOCK_ERR;\n }\n if (!m_serial) {\n blast_err(\"Passed NULL pointer to serial device\");\n log_leave(\"NULL\");\n return NETSOCK_ERR;\n }\n\n if (m_serial->sock->fd != INVALID_SOCK) comms_serial_close(m_serial);\n\n if ((m_serial->sock->fd = open(m_fifo, m_flags | O_NONBLOCK)) == INVALID_SOCK) {\n blast_err(\"Could not open FIFO '%s'\", m_fifo);\n blast_strerror(\"\\t\");\n log_leave(\"Open Error\");\n return NETSOCK_ERR;\n }\n\n m_serial->sock->host = bstrdup(err, m_fifo);\n m_serial->sock->state = NETSOCK_STATE_CONNECTING;\n\n comms_net_async_set_events(comms_sock_get_poll_handle(m_serial->sock), POLLOUT);\n\n blast_info(\"Successfully opened %s for FIFO communication\", m_fifo);\n\n log_leave();\n return NETSOCK_OK;\n}\n" }, { "alpha_fraction": 0.6951581239700317, "alphanum_fraction": 0.7066230177879333, "avg_line_length": 29.061538696289062, "blob_id": "2ff40bd10b5969a53243630e64bd98326253744b", "content_id": "dbdba2fd57c8b5d528379ea437af0e9086c611ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9769, "license_type": "no_license", "max_line_length": 142, "num_lines": 325, "path": "/balloon_cam/cameraCommunicator.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//cameraCommunicator.cpp\n//a class that contains a linked list of network connection classes, and uses them to communicate over the network\n\n#include \"stdafx.h\"\n#include \"cameraCommunicator.h\"\n\nCameraCommunicator::CameraCommunicator(Locator* locator){//constructor\n\tinit(locator);\n}\n\nCameraCommunicator::~CameraCommunicator(){//destructor\n\tfor(unsigned int i =0; i< list->size(); i++){//ensures that no threads are still running\n\t\tif((*list)[i]->isLooping()){\n\t\t\t(*list)[i]->endLoop();\n\t\t}\n\t\tdelete (*list)[i];//deletes the struct\n\t\t(*list)[i] = NULL;\n\t}\n\n\tclosesocket(socketFileDescriptor);//closes the sockets\n\tlist->clear();\n\tdelete list;\n\tdelete servInfo->ai_addr;\n\tdelete servInfo;\n\tWSACleanup();//mandatory system cleanup call\n}\n\nvoid CameraCommunicator::init(Locator* locator){\n\n\tlist = new std::vector<NetworkConnection*>;\n\tnumConnections = 0;\n\tthis->locator = locator;\n\tWSADATA wsaData;\n\tint status;\n\n\tstatus = WSAStartup(MAKEWORD(2,2), &wsaData);//mandatory system startup call\n\n\tif(status != 0){\n\t\tprintf(\"Wsa startup failed, error code %d\\n\", WSAGetLastError);\n\t\treturn;\n\t}\n\n\taddrinfo hints;\n\taddrinfo* serverInfo = new addrinfo;\n\tmemset(&hints, 0, sizeof(hints));\n\thints.ai_family = AF_INET;\n\thints.ai_socktype = SOCK_STREAM;\n\thints.ai_flags = AI_PASSIVE;\n\n\tstatus = getaddrinfo(NULL, DEFAULT_PORT, &hints, &serverInfo);//gets address info for a local socket\n\n\tif(status != 0){\n\t\tprintf(\"getaddrinfo fails for port %d, error code %d\\n\", DEFAULT_PORT, WSAGetLastError());\n\t\treturn;\n\t}\n\tservInfo = new addrinfo();//copies the data into the member variables\n\tmemcpy(servInfo, serverInfo, sizeof(addrinfo));\n\n\tSOCKET socketHandle = socket(serverInfo->ai_family, serverInfo->ai_socktype, serverInfo->ai_protocol);//makes a local socket\n\tif(socketHandle == INVALID_SOCKET){\n\t\tprintf(\"Invalid socket returned. Error code %d\\n\", WSAGetLastError());\n\t}\n\n\tservInfo->ai_addr = new sockaddr();\n\tmemcpy(servInfo->ai_addr, serverInfo->ai_addr, sizeof(sockaddr));\n\n\tfreeaddrinfo(serverInfo);//frees the now useless addrinfo struct\n\n\tsocketFileDescriptor = socketHandle;\n\n\t//sets the socket in reuse mode, this prevents crashes from requiring a restart to free the socket\n\t//then sets a timeout value for send(), otherwise it can hang perpetually\n\tbool value = true;\n\tDWORD timeLim = 30000;\n\n\tsetsockopt(socketFileDescriptor, SOL_SOCKET, SO_REUSEADDR, (char *)&value, sizeof(bool));\n\tsetsockopt(socketFileDescriptor, SOL_SOCKET, SO_SNDTIMEO, (char*) &timeLim, sizeof(DWORD));\n\n\tstatus = bind(socketHandle, servInfo->ai_addr, sizeof(sockaddr));//binds the socket to the local port specified above\n\n\tif(status != 0){\n\t\tprintf(\"Bind fails, error code %d\\n\", WSAGetLastError());\n\t\treturn;\n\t}\n\n\tstatus = listen(socketHandle, 15);//sets the socket to listening mode\n printf(\"Listening...\\n\");\n\tif(status != 0){\n\t\tprintf(\"Listen has failed, error code %d\\n\", WSAGetLastError());\n\t}\n}\n\nint CameraCommunicator::addConnection(std::string hostname){//adds a new connection to the list of connections\n\t\n\tstruct sockaddr address;\n\tint size = sizeof(address);\n\tprintf(\"Accepting...\\n\");\n\tSOCKET status = accept(socketFileDescriptor, &address, &size);//accepts the connection\n\tprintf(\"Accepted.\\n\");\n\tif(status == INVALID_SOCKET){\n\t\tprintf(\"Accept fails. Error code %d\\n\", WSAGetLastError());\n\t\treturn -1;\n\t}\n\n\tconnection = new NetworkConnection(status, address, locator);//makes a new netowrk connection instance\n\n\tconnection->loop();//sets the loop running\n\t//sets information about the connection in the classes\n\tconnection->setHostId(hostname);\n\n\t(*list).push_back(connection);\n\tconnection = NULL;\n\tnumConnections ++;\n\treturn 0;\n}\n\nvoid CameraCommunicator::removeConnection(std::string hostname){//removes a connection from the list of connections\n\n\tNetworkConnection* current; \n\tbool found = false;\n\n\tfor(unsigned int i = 0; i<list->size(); i++){//iterates through the list\n\t\tif((*list)[i]->getHostId() == hostname){//if this is the connection we want\n\t\t\tfound = true;\n\t\t\tcurrent = (*list)[i];\n\t\t}\n\t\tif(found && (i != list->size() -1)){//if we are past the connection\n\t\t\t(*list)[i] = (*list)[i+1];//moves everthing up one\n\t\t}\n\t}\n\n\tif(found){\n\t\tcurrent->endLoop();//ends the connections loop\n\t\tdelete current;\n\t\tif(numConnections == 1){\n\t\t\tlist->clear();\n\t\t}else{\n\t\t\tlist->pop_back();//removes the duplicate entry from the end of the list\n\t\t}\n\t\tnumConnections --;\n\t}else{\n\t\tprintf(\"connection not found\\n\");\n\t}\n}\n\nCameraCommunicator::NetworkConnection::NetworkConnection(SOCKET fileDescriptor, sockaddr addressInfo, Locator* locator){//constructor\n\tthis->locator = locator;\n\tservInfo = new sockaddr();\n\tsocketFileDescriptor = fileDescriptor;\n\tlooping = false;\n\tmemcpy(servInfo, &addressInfo, sizeof(addressInfo));\n\tpleaseStop = false; \n}\n\nCameraCommunicator::NetworkConnection::~NetworkConnection(){//destructor\n\tif(this->isLooping()){\n\t\tendLoop();\n\t}\n\twhile(this->isLooping()){\n\t\tSleep(100);\n\t}\n\tdelete servInfo;\n}\n\nint CameraCommunicator::NetworkConnection::loop(){\n\n\t//makes a new thread to handle the loop, the thread runs the communicate routine\n\tDWORD threadId;\n\t\n\tHANDLE threadHandle = CreateThread(NULL, 0,(LPTHREAD_START_ROUTINE) &CameraCommunicator::NetworkConnection::communicate, this, 0, &threadId);\n\n\tif(threadHandle == NULL){\n\t\tprintf(\"Create thread has failed. Error code %d\\n\", GetLastError());\n\t\treturn -1;\n\t}\n\t//sets varibles pertaining to the thread\n\tlooping = true;\n\n\tthis->threadId = threadId;\n\n\tthis->threadHandle = threadHandle;\n\n\treturn 0;\n\n}\n\nvoid CameraCommunicator::NetworkConnection::endLoop(){//tells the thread to end the loop\n\tif(!isLooping()){\n\t\tprintf(\"Useless call to endLoop(), connection is not looping.\\n\");\n\t\treturn;\n\t}\n\n\tpleaseStop = true;\n}\n//fake wrapper function for the thread. Basically, createThread() blows.\n DWORD WINAPI CameraCommunicator::NetworkConnection::communicate(void* instance){\n\t((CameraCommunicator::NetworkConnection*)instance)->communicate();\n\treturn 0;\n}\n\nvoid CameraCommunicator::NetworkConnection::communicate(){\n\n\ttimeval time;\n\ttimeval localTime;\n\tFILETIME systemTime;\n\tint status;\n\tbool resend = false;\n\ttimeval oldTime;\n\tblob data;\n\tDeleteFile((LPCTSTR)\"laglog.txt\");\n\tLARGE_INTEGER bigTimeInt;\n\n\twhile(!pleaseStop){//as long as endLoop() hasn't been called\n\t\t//Sleep(1);//only for testing, otherwise it is too fast\n\t\tif(!resend){//if there was no resend request\n\t\t\ttime = getData();//recieves the data\n\t\t\tGetSystemTimeAsFileTime(&systemTime);\n\t\t\tbigTimeInt.HighPart = systemTime.dwHighDateTime;\n\t\t\tbigTimeInt.LowPart = systemTime.dwLowDateTime;\n\t\t\tbigTimeInt.QuadPart -= _int64(116444736000000000);\n\t\t\tlocalTime.tv_sec = (long)(bigTimeInt.QuadPart/10000000);\n\t\t\tlocalTime.tv_usec = (bigTimeInt.QuadPart%10000000)/10;\n\t\t\tlog(time, localTime);\n\t\t}\n\n\t\tif(time.tv_sec == -1){//if there was an unknown error, drop this timevalue and give up\n\t\t\tprintf(\"Get data has failed.\\n\");\n\t\t\toldTime = time;\n\t\t\tcontinue;\n\t\t}\n\t\tif(time.tv_sec == -2){//if there was a resend request\n\t\t\tprintf(\"Server has requested the last data again\\n\");\n\t\t\tresend = true;\n\t\t}\n\t\tif(time.tv_sec == 0){//if the connection was closed from the other end\n\t\t\tprintf(\"Server has closed the connection\\n\");\n\t\t\treturn;\n\t\t}\n\t\tif(!resend){//if there was no resend request\n\t\t\tif(time.tv_sec != -3){\n\t\t\t\tdata = locator->locate();\n\t\t\t}\n\t\t\tstatus = sendData(time, data);//send the new data\n\t\t\toldTime = time;\n\t\t}else{//otherwise, resend the old data\n\t\t\tstatus = sendData(oldTime, data);\n\t\t\tresend = false;\n\t\t}\n\n\t\tif(status < 0){\n\t\t\tprintf(\"Send data fails\\n\");\n\t\t\tcontinue;\n\t\t}\n\t}\n\tlooping = false;\n\treturn;\n}\n\ntimeval CameraCommunicator::NetworkConnection::getData(){\n\ttimeval fakeTime;\n\t//recieves the data in a buffer\n\tchar buffer[100];\n\tint status = recv(socketFileDescriptor, buffer, 100, 0);\n\t\n\tif(status < 1){//if there was an error\n\t\tfakeTime.tv_sec = status;\n\t\treturn fakeTime;\n\t}else{\n\t\tbuffer[status] = '\\0';\n\t\t//NOTE: RAND IS HERE FOR TEST PURPOSES ONLY. REMOVE BEFORE USE\n\t\tif((strchr(buffer, '\\n') == NULL)/*||(rand() % 10 < 2)*/){//if the data does not resemble the data that was sent\n\t\t\tprintf(\"%d bytes recieved in getData(). Retrying\\n\", status);\n\t\t\tblob fakeblob;\n\t\t\tfakeblob.size = 0;\n\t\t\tfakeTime.tv_sec = -2;\n\t\t\tstatus = sendData(fakeTime, fakeblob);//sends a retry request\n\t\t\treturn getData();//recurses until the data looks right\n\t\t}else{//otherwise returns the data as a timeval\t\n\t\t\tprintf(\"data recieved: %s\\n\", buffer);\n\t\t\ttimeval returnValue;\n\t\t\tsscanf_s((char*)buffer, \"%ld s; %ld us;\\n\", &returnValue.tv_sec, &returnValue.tv_usec);\n\t\t\treturn returnValue;\n\t\t}\n\t}\n}\n\nint CameraCommunicator::NetworkConnection::sendData(timeval time, blob data){\n\t//creates an output string\n\tchar* outData = (char *)malloc(1000);\n\n\tif(time.tv_sec == -2){\n\t\toutData = \"resend\\n\\0\";\n\t}else if(time.tv_sec == -3){\n\t\toutData = \"ping\\n\\0\";\n\t}else{\n\t\tsprintf_s(outData, 1000, \"X=%d;Y=%d;s=%ld;us=%ld\\n\", data.centroid.x, data.centroid.y, time.tv_sec, time.tv_usec);\n\t}\n\tint dataSize = (int) strlen(outData);\n\tprintf(\"sending data: %s\\n\", outData);\n\t//sends the data to the server\n\tint bytesSent = send(socketFileDescriptor, outData, dataSize, 0);\n\n\tif(bytesSent < 0){//if there was an error\n\t\tprintf(\"Send has failed. Error code %d\\n\", WSAGetLastError());\n\t\treturn -1;\n\t}else{\n\t\tif(bytesSent != dataSize){//notifies that there was an error on this end. Does not resend, as this would screw up resend protocol\n\t\t\tprintf(\"Not all bytes sent. Expect a retry request\\n\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nvoid CameraCommunicator::NetworkConnection::log(timeval networkTime, timeval localTime){\n\n\tFILE* file;\n\tfopen_s(&file, \"laglog.txt\", \"a\");\n\tint secondsDiff = localTime.tv_sec - networkTime.tv_sec;\n\tint usecDiff = localTime.tv_usec - networkTime.tv_usec;\n\tif(file != NULL){\n\t\tfprintf(file, \"%d\\n\",(1000000* secondsDiff) + usecDiff);\n\t\tfclose(file);\n\t}\n}" }, { "alpha_fraction": 0.6805707812309265, "alphanum_fraction": 0.686059296131134, "avg_line_length": 27.40625, "blob_id": "c16b1fd4253100c1e84d6d70172a58368569b320", "content_id": "07c8756a1aae3e1e5f8ad2a6cc168ff38682a3bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 912, "license_type": "no_license", "max_line_length": 102, "num_lines": 32, "path": "/stars/code/networking/server.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"server.h\"\n#include <boost/bind.hpp>\n\nusing namespace Networking;\nusing boost::asio::ip::tcp;\n\nServer::Server(boost::asio::io_service& io_service, int port):\n acceptor(io_service, tcp::endpoint(tcp::v4(), port))\n{\n start_accept();\n}\n\nvoid Server::start_accept()\n{\n Connection::pointer new_connection = Connection::create(acceptor.get_io_service());\n acceptor.async_accept(new_connection->socket(),\n boost::bind(&Server::handle_accept, this, new_connection, boost::asio::placeholders::error));\n}\n\nvoid Server::handle_accept(Connection::pointer new_connection, const boost::system::error_code& error)\n{\n if (!error) {\n new_connection->start();\n start_accept();\n }\n}\n\n\n" }, { "alpha_fraction": 0.7217898964881897, "alphanum_fraction": 0.7295719981193542, "avg_line_length": 24.649999618530273, "blob_id": "69a8b0fc944ab2b105486447558c3027342852ee", "content_id": "45eeeec2f6022ffdd694db2000ff5bc8f5873f9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 515, "license_type": "no_license", "max_line_length": 75, "num_lines": 20, "path": "/stars/code/shared/network/image_client_settings.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"image_client_settings.h\"\n#include \"../../parameters/manager.h\"\n\nusing namespace Shared::Network;\n\nImageClientSettings::ImageClientSettings()\n{\n enabled = true;\n}\n\nvoid ImageClientSettings::init(Parameters::Manager& params)\n{\n enabled = params.general.try_get(\"imaging.image_client.enabled\", true);\n}\n\n" }, { "alpha_fraction": 0.6789536476135254, "alphanum_fraction": 0.6848989129066467, "avg_line_length": 21.105262756347656, "blob_id": "bdb4cebb45ff4773562f913b8349ade7619a4a54", "content_id": "6d51b66fce3323344ca0979550dffc75b9e03a15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 841, "license_type": "no_license", "max_line_length": 56, "num_lines": 38, "path": "/groundhog/blast/groundhog.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include \"groundhog_funcs.h\"\n\n/* ------ BEGIN CUSTOM GROUNDHOG DEFINITIONS ------ */\n\n// groundhog customization\n#define GROUNDHOG_MAX_FRAMES_RESET 900\n\n// BLAST general\n#include \"blast.h\"\n#include \"blast_time.h\"\n#define ROACH_CHANNEL_REF_NAME \"kidA_roachN\"\n#define ROACH_CHANNEL_REF_INDEX_NAME \"kidA_roachN_index\"\n\n// BLAST telemetry\n#include \"channels_tng.h\"\n#include \"derived.h\"\n#include \"FIFO.h\"\n#ifndef MAX\n#define MAX(a, b) ((a) > (b) ? (a):(b))\n#endif\nenum DownLinkTypes {PILOT, BI0, HIGHRATE, \n NUM_DOWNLINKS};\n\n// BLAST pilot\n#include \"bitserver.h\"\n#include \"pilot.h\"\nvoid udp_receive(void *arg);\n\n// BLAST biphase\n#include \"bbc_pci.h\"\n#include \"decom_pci.h\"\n#include \"bi0.h\"\nvoid biphase_receive(void *arg);\n\n// BLAST highrate\n#include \"highrate.h\"\n#include \"comms_serial.h\"\nvoid highrate_receive(void *arg);\n\n" }, { "alpha_fraction": 0.5424836874008179, "alphanum_fraction": 0.5520541667938232, "avg_line_length": 32.4609375, "blob_id": "7979dc1ecfa9041cf011b8e378fcd45e7be2a4b6", "content_id": "4c8e03555271817969ecb22755d1838feaa57a0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4284, "license_type": "no_license", "max_line_length": 103, "num_lines": 128, "path": "/stars/utilities/channel_generator/generator.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <string.h>\n#include \"xsc_protocol.h\"\n\ntypedef enum\n{\n ctr_fcp,\n tr_m_azvel,\n tr_r_azvel,\n tr_m_totvel,\n tr_m_azacc,\n point_az,\n point_el,\n point_sigma,\n point_az_trim,\n point_el_trim,\n num_fcp_channels\n}\nFCPChannelNames;\n\nvoid fill_slots(XSCChannelInfo* infos, unsigned int num_channels)\n{\n unsigned int current_relative_loop = 0;\n unsigned int current_slot = 0;\n unsigned int size = 0;\n for (unsigned int i=0; i<num_channels; i++) {\n size = 1;\n if (infos[i].form == xN_wide_slow || infos[i].form == xN_wide_fast) {\n size = 2;\n }\n if (current_slot + size - 1 < 64) {\n // put it in this loop\n infos[i].relative_loop_num = current_relative_loop;\n infos[i].slot_num = current_slot;\n current_slot += size;\n } else {\n // put it in the next loop\n current_relative_loop++;\n current_slot = 0;\n infos[i].relative_loop_num = current_relative_loop;\n infos[i].slot_num = current_slot;\n current_slot += size;\n }\n }\n if (current_relative_loop >= 2) {\n printf(\"WARNING: using more than 2 loops per star camera\");\n }\n}\n\nvoid init_fcp_channels(XSCChannelInfo* ci)\n{\n double identity[2] = {1.0, 0.0};\n xsc_init_channel_info(&ci[ctr_fcp], \"ctr_fcp\", xN_wide_fast, identity);\n xsc_init_channel_info(&ci[tr_m_azvel], \"tr_m_azvel\", xN_narrow_slow, identity);\n xsc_init_channel_info(&ci[tr_r_azvel], \"tr_r_azvel\", xN_narrow_slow, identity);\n xsc_init_channel_info(&ci[tr_m_totvel], \"tr_m_totvel\", xN_narrow_slow, identity);\n xsc_init_channel_info(&ci[tr_m_azacc], \"tr_m_azacc\", xN_narrow_slow, identity);\n xsc_init_channel_info(&ci[point_az], \"point_az\", xN_narrow_slow, identity);\n xsc_init_channel_info(&ci[point_el], \"point_el\", xN_narrow_slow, identity);\n xsc_init_channel_info(&ci[point_sigma], \"point_sigma\", xN_narrow_slow, identity);\n xsc_init_channel_info(&ci[point_az_trim], \"point_az_trim\", xN_narrow_slow, identity);\n xsc_init_channel_info(&ci[point_el_trim], \"point_el_trim\", xN_narrow_slow, identity);\n}\n\nvoid init_infos(XSCChannelInfo* infos)\n{\n XSCChannelInfo ci_from_fcp[num_fcp_channels];\n init_fcp_channels(ci_from_fcp);\n\n XSCServerData sd;\n XSCChannelInfos ci_struct_from_stars;\n xsc_clear_server_data(&sd);\n xsc_init_server_data_and_infos(&sd, &ci_struct_from_stars);\n\n for (unsigned int i=0; i<num_fcp_channels; i++) {\n infos[i] = ci_from_fcp[i];\n }\n for (unsigned int i=0; i<xN_num_channels; i++) {\n infos[i + num_fcp_channels] = ci_struct_from_stars.infos[i];\n }\n}\n\nint main()\n{\n unsigned int num_channels = xN_num_channels + num_fcp_channels;\n XSCChannelInfo infos[num_channels];\n\n init_infos(infos);\n fill_slots(infos, num_channels);\n\n unsigned int starting_loops[2] = {6, 10};\n for (unsigned int form=0; form<4; form++) {\n if (form == xN_narrow_slow) {\n printf(\"Narrow Slow channels:\\n\");\n } else if (form == xN_narrow_fast) {\n printf(\"Narrow Fast channels:\\n\");\n } else if (form == xN_wide_slow) {\n printf(\"Wide Slow channels:\\n\");\n } else if (form == xN_wide_fast) {\n printf(\"Wide Fast channels:\\n\");\n }\n\n char name_string[31+2+1] = \"\"; // max name length + two quotes + null terminator\n char loop_string[7] = \"\";\n for (unsigned int which=0; which<2; which++) {\n for (unsigned int i=0; i<num_channels; i++) {\n if (form == infos[i].form) {\n sprintf(name_string, \"\\\"x%i_%s\\\"\", which, infos[i].tx_name);\n\n // one special case\n if ((which == 1) && (strcmp(infos[i].tx_name, \"ctr_fcp\") == 0)) {\n sprintf(name_string, \"\\\"x0_lt_age_cs\\\"\");\n }\n\n sprintf(loop_string, \"LOOP%i\", starting_loops[which] + infos[i].relative_loop_num);\n printf(\" {%-33s, 'w', %6s, %2i,},\\n\",\n name_string,\n loop_string,\n infos[i].slot_num\n );\n }\n }\n }\n\n }\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.5927889943122864, "alphanum_fraction": 0.6224814653396606, "avg_line_length": 25.94285774230957, "blob_id": "1bca2a6f843981914b797b6120288d95bcfb312a", "content_id": "638e9910f8b871f4a9603969b4f4c0d036e9dab0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1886, "license_type": "no_license", "max_line_length": 96, "num_lines": 70, "path": "/interloquendi/BlastDataSynch.sh", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#for mcp systems\n#curfile=\"datafile.cur\"\n#for decomd systems\ncurfile=\"decom.cur\"\n\npid_file=\"/tmp/bds.pid\"\n\ncurfile_ptr=\"/data/etc/$curfile\"\naddr=\"[email protected]\"\n\necho \"Start a persistent connection to $addr\"\necho \" ssh $addr\"\necho \" remember to have the following lines in your .ssh/config file:\"\necho \" \tHost *\"\necho \" \t\tControlMaster auto\" \necho \"\t\tControlPath /tmp/%r@%h:%p\"\n\n\nread -p \"Press [Enter] to contine...\"\n\n#if test -e $pid_file\n#then\n# kill -KILL `cat $pid_file ` > /dev/null 2>&1\n# echo \"process killed\"\n#fi\n\n#echo \"Opening connection to \" $addr\n#eval \"ssh $addr sleep 525600 &\" \n#echo $! > $pid_file\n#echo \"Connection estabilished\"\n#sleep 2\n\nlastfile=\"aaa\"\n\necho $curfile\nwhile true; do\n\tif [ \"$lastfile\" != \"`cat $curfile_ptr | sed 's/000//'`\" ]; then\n\t\tlastfile=`cat $curfile_ptr | sed 's/000//'`\n\t\tnum=0\n\t\tfname=`cat $curfile_ptr | sed 's/000//' | awk -v num=$num '{printf(\"%s%03X\", $0, num)}'`\n\t\twhile test -e $fname\n\t\tdo\n\t\t\tlet num=$num+1\n\t\t\tfname=`cat $curfile_ptr | sed 's/000//' | awk -v num=$num '{printf(\"%s%03X\", $0, num)}'`\n\t\t\techo Skipping File $curfile $fname\n\t\tdone\n\t\tlet num=$num-1\t\n\t\tfname=`cat $curfile_ptr | sed 's/000//' | awk -v num=$num '{printf(\"%s%03X\", $0, num)}'`\n\t\tssh $addr \"echo $fname > /data/etc/$curfile\"\n\t\trsync -v --progress --append `cat $curfile_ptr | sed 's/000/.spec/'` $addr:/data/rawdir\n\t\t\t\n\tfi\n\t\n\tfname=`cat $curfile_ptr | sed 's/000//' | awk -v num=$num '{printf(\"%s%03X\", $0, num)}'`\n\tfname_next=`cat $curfile_ptr | sed 's/000//' | awk -v num=$num '{printf(\"%s%03X\", $0, num+1)}'`\n\trsync -vz --progress --append $fname $addr:/data/rawdir\n\tif test -e \"$fname_next\"; then\n\t\trsync -vz --progress --append $fname $addr:/data/rawdir\n\t\trsync -vz --progress --append $fname_next $addr:/data/rawdir\n\t\tlet num=$num+1\n\t\tfname=$fname_next\n\tfi\n\tsleep 1\ndone\n\n\n#kill -KILL `cat $pid_file ` > /dev/null 2>&1\n\n#rm -f $pid_file\n" }, { "alpha_fraction": 0.6151170134544373, "alphanum_fraction": 0.6290322542190552, "avg_line_length": 28.009174346923828, "blob_id": "305930578a817f193bb064a37629fe29c802e98d", "content_id": "45cc8702a8f9b6c218fbca56e6ccfbac89cdc28c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3162, "license_type": "no_license", "max_line_length": 101, "num_lines": 109, "path": "/owl/PBitMultiDataItem.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"PBitMultiDataItem.h\"\n#include \"PStyle.h\"\n\n#include <unistd.h>\n\nvoid PBitMultiDataItem::gdUpdate(GetData::Dirfile* dirFile,int lastNFrames)\n{\n double indata;\n bool ok;\n\n indata = gdReadRawData(dirFile, lastNFrames, ok);\n\n if (ok) {\n PStyle* style=_extrema?_extrema->formatForValue(indata,_defaultDataStyle):_defaultDataStyle;\n\n if(prevStyle!=style|| //the reason this works is because PStyleChooser works via reference to ptr\n style->_dirty) {\n applyStyle(this,style);\n prevStyle=style;\n }\n\n if(_nBits < 1) {\n if(_data->text() != QString::number(indata)) {\n _data->setText(QString::number(indata));\n _serverDirty=-1;\n } else {\n --_serverDirty;\n }\n } else {\n char display[32];\n int num_bits = _nBits;\n int high_len = _highWord.length();\n int low_len = _lowWord.length();\n unsigned idata = (unsigned)indata;\n if (num_bits > 32)\n num_bits = 32;\n\n for (int z = 0; z < num_bits; z++)\n if (idata & (1 << ((num_bits - 1) - z)))\n display[z] = (z >= high_len) ? '1' : (char)_highWord.at(z).toLatin1();\n else\n display[z] = (z >= low_len) ? '0' : (char)_lowWord.at(z).toLatin1();\n display[num_bits]='\\0';\n\n if (strlen(display)==1) {\n display[1] = ' ';\n display[2] = '\\0';\n }\n if(_data->text() != display) {\n _data->setText(display);\n _serverDirty=-1;\n } else {\n --_serverDirty;\n }\n }\n }\n}\n\nQString PBitMultiDataItem::highWord() const { return _highWord; }\nQString PBitMultiDataItem::lowWord() const { return _lowWord; }\nint PBitMultiDataItem::nBits() const { return _nBits; }\n\nvoid PBitMultiDataItem::setHighWord(QString highWord,bool force) {\n if(!isCurrentObject()&&!force) return;\n if(_highWord==highWord) {\n return;\n }\n _highWord=highWord;\n emit highWordChanged(highWord);\n}\n\nvoid PBitMultiDataItem::setLowWord(QString lowWord,bool force) {\n if(!isCurrentObject()&&!force) return;\n if(_lowWord==lowWord) {\n return;\n }\n _lowWord=lowWord;\n emit lowWordChanged(lowWord);\n}\n\nvoid PBitMultiDataItem::setNBits(int nBits,bool force) {\n if(!isCurrentObject()&&!force) return;\n if(_nBits==nBits) {\n return;\n }\n _nBits=nBits;\n emit nBitsChanged(nBits);\n}\n" }, { "alpha_fraction": 0.6160714030265808, "alphanum_fraction": 0.6517857313156128, "avg_line_length": 15, "blob_id": "f45f6d576ef12b04dc0505c1cba68c67527d3cd3", "content_id": "3b78f077443c1499af53f592b0f97a498a63cc7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 112, "license_type": "no_license", "max_line_length": 36, "num_lines": 7, "path": "/rove/Makefile", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "CC=gcc -O2 -W -Wall\n\nrove: rove.o\n\t$(CC) -o rove rove.o -lm\n\ninstall: rove\n\tinstall -m 755 rove /usr/local/sbin\n" }, { "alpha_fraction": 0.6172161102294922, "alphanum_fraction": 0.622710645198822, "avg_line_length": 22.212766647338867, "blob_id": "e858f710a1964e92c290da6a732642d0a4f0dc73", "content_id": "c7320dfc9f65d077b16a6a1880b5d43ed9cdd974", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1093, "license_type": "no_license", "max_line_length": 100, "num_lines": 47, "path": "/stars/code/displaying/dynamic_value.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"dynamic_value.h\"\n#include <boost/format.hpp>\n#include <iomanip>\n\nusing namespace Displaying;\nusing std::string;\n\nDynamicValue::DynamicValue(): color()\n{\n value = \"\";\n known = false;\n}\n\nvoid DynamicValue::init(string name_)\n{\n name = name_;\n}\n\nvoid DynamicValue::set_value(double value_, int precision)\n{\n try {\n value = (boost::format(\"%f\")%boost::io::group(std::setprecision(precision), value_) ).str();\n known = true;\n } catch (int) { }\n}\n\nvoid DynamicValue::set_value(double value_, string units, int precision)\n{\n try {\n value = (boost::format(\"%f\")%boost::io::group(std::setprecision(precision), value_) ).str();\n value += units;\n known = true;\n } catch (int) { }\n //value = str( boost::format(\"%|1.1f|\") % value_ ) + \" \" + units;\n}\n\nvoid DynamicValue::set_value(string value_)\n{\n value = value_;\n known = true;\n}\n\n" }, { "alpha_fraction": 0.5812686681747437, "alphanum_fraction": 0.630691409111023, "avg_line_length": 46.58641815185547, "blob_id": "a8faa98c0615643c3bb86c497b3906ac7817ff99", "content_id": "4c62bfc70ce4bb14bc9841fa42c2a7cae25ec864", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7709, "license_type": "no_license", "max_line_length": 79, "num_lines": 162, "path": "/common/include/bbc_pci.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* bbc_pci.h: contains definitions for the PCI BLAST Bus Controller module\n *\n * This software is copyright (C) 2004 University of Toronto\n * \n * This file is part of the BLAST flight code licensed under the GNU \n * General Public License.\n * \n * You should have received a copy of the GNU General Public License\n * along with this software; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <linux/ioctl.h>\n\n#define BBCPCI_IOC_MAGIC 0xbb\n\n/* Define the ioctl commands - use the return value (int) to return the info\n rather than using the arguments. This is more convenient I think. */\n\n/* reset the controller: clear memory and reset counter to zero */\n#define BBCPCI_IOC_RESET _IO(BBCPCI_IOC_MAGIC, 0)\n#define BBCPCI_IOC_SYNC _IO(BBCPCI_IOC_MAGIC, 1)\n#define BBCPCI_IOC_VERSION _IO(BBCPCI_IOC_MAGIC, 2)\n#define BBCPCI_IOC_COUNTER _IO(BBCPCI_IOC_MAGIC, 3)\n#define BBCPCI_IOC_WRITEBUF _IO(BBCPCI_IOC_MAGIC, 4)\n#define BBCPCI_IOC_COMREG _IO(BBCPCI_IOC_MAGIC, 5)\n#define BBCPCI_IOC_READBUF_WP _IO(BBCPCI_IOC_MAGIC, 6)\n#define BBCPCI_IOC_READBUF_RP _IO(BBCPCI_IOC_MAGIC, 7)\n#define BBCPCI_IOC_BBC_FIONREAD _IO(BBCPCI_IOC_MAGIC, 8)\n#define BBCPCI_IOC_BI0_FIONREAD _IO(BBCPCI_IOC_MAGIC, 9)\n#define BBCPCI_IOC_ON_IRQ _IO(BBCPCI_IOC_MAGIC, 10)\n#define BBCPCI_IOC_OFF_IRQ\t_IO(BBCPCI_IOC_MAGIC, 11)\n#define BBCPCI_IOC_IRQT_READ\t_IO(BBCPCI_IOC_MAGIC, 12)\n#define BBCPCI_IOC_IRQ_RATE\t_IO(BBCPCI_IOC_MAGIC, 13) /* deprecated */\n#define BBCPCI_IOC_RESET_SERIAL _IO(BBCPCI_IOC_MAGIC, 14)\n#define BBCPCI_IOC_GET_SERIAL\t_IO(BBCPCI_IOC_MAGIC, 15)\n#define BBCPCI_IOC_SERIAL_RDY\t_IO(BBCPCI_IOC_MAGIC, 16)\n#define BBCPCI_IOC_EXT_SER_ON _IO(BBCPCI_IOC_MAGIC, 17)\n#define BBCPCI_IOC_EXT_SER_OFF _IO(BBCPCI_IOC_MAGIC, 18)\n#define BBCPCI_IOC_FRAME_RATE\t_IO(BBCPCI_IOC_MAGIC, 19) /* deprecated */\n#define BBCPCI_IOC_FRAME_COUNT\t_IO(BBCPCI_IOC_MAGIC, 20)\n/* on newer firmware, these are preferred to the deprecated versions above */\n#define BBCPCI_IOC_IRQ_RATE_INT _IO(BBCPCI_IOC_MAGIC, 21)\n#define BBCPCI_IOC_IRQ_RATE_EXT _IO(BBCPCI_IOC_MAGIC, 22)\n#define BBCPCI_IOC_FRAME_RATE_INT _IO(BBCPCI_IOC_MAGIC, 23)\n#define BBCPCI_IOC_FRAME_RATE_EXT _IO(BBCPCI_IOC_MAGIC, 24)\n\n#define BBCPCI_SIZE_UINT sizeof(unsigned int)\n#define BBCPCI_ADD_WRITE_BUF_P (0x01 * BBCPCI_SIZE_UINT)\n#define BBCPCI_ADD_IR_WRITE_BUF 0x40\n#define BBCPCI_ADD_IR_WRITE_PRE 0x36\n#define BBCPCI_IR_WRITE_BUF_SIZE 0x100\n#define BBCPCI_ADD_COMREG (0x03 * BBCPCI_SIZE_UINT)\n#define BBCPCI_ADD_IRQREG (0x0a * BBCPCI_SIZE_UINT)\n#define BBCPCI_ADD_IRQ_RATE\t (0x0b * BBCPCI_SIZE_UINT)\n#define BBCPCI_ADD_FRAME_RATE (0x0e * BBCPCI_SIZE_UINT)\n#define BBCPCI_ADD_VERSION (0x00 * BBCPCI_SIZE_UINT)\n#define BBCPCI_ADD_COUNTER (0x02 * BBCPCI_SIZE_UINT)\n#define BBCPCI_ADD_SERIAL\t (0x0c * BBCPCI_SIZE_UINT)\n#define BBCPCI_ADD_SERIAL_RDY\t (0x0d * BBCPCI_SIZE_UINT)\n#define BBCPCI_ADD_FRAME_COUNT\t (0x0f * BBCPCI_SIZE_UINT)\n#define BBCPCI_ADD_READ_BUF 0x840\n#define BBCPCI_ADD_READ_BUF_END 0x2ff0\n#define BBCPCI_ADD_READ_BUF_WP (0x04 * BBCPCI_SIZE_UINT)\n#define BBCPCI_ADD_READ_BUF_RP (0x05 * BBCPCI_SIZE_UINT)\n#define BBCPCI_ADD_BI0_WP (0x06 * BBCPCI_SIZE_UINT)\n#define BBCPCI_ADD_BI0_RP (0x07 * BBCPCI_SIZE_UINT)\n#define BBCPCI_IR_BI0_BUF 0x3000\n#define BBCPCI_IR_BI0_BUF_END 0x3ff8\n\n#define BBCPCI_MAX_FRAME_SIZE 0x10000\n\n#define BBCPCI_SD_WFRAME 0x00\n#define BBCPCI_WFRAME_ADD(x) (BBCPCI_SD_WFRAME + x)\n\n//compatibility hack for code that's looking for two buses\n#define BBCPCI_WFRAME1_ADD(x)\t BBCPCI_WFRAME_ADD(x)\n#define BBCPCI_SD_WFRAME2 (BBCPCI_SD_WFRAME + BBCPCI_MAX_FRAME_SIZE)\n//NB on new firmware, this is start of NIOS read buffer. Writing on startup is\n//okay (beginning entries skipped anyway). Writing again can corrupt data!!!\n#define BBCPCI_WFRAME2_ADD(x) (BBCPCI_SD_WFRAME2 + x)\n\n/* Command register bitfield. */\n#define BBCPCI_COMREG_RESET 0x00000001 // Fully reset all pointers etc.\n#define BBCPCI_COMREG_SYNC 0x00000002 // Clear rx buffers; start frame.\n#define BBCPCI_COMREG_ON_IRQ 0x00000004 // Turn on IRQ generation.\n#define BBCPCI_COMREG_OFF_IRQ 0x00000008 // Turn off IRQ generation.\n#define BBCPCI_COMREG_EXT_SER_ON 0x00000010 // Set serial generation external.\n#define BBCPCI_COMREG_EXT_SER_OFF 0x00000020 // Set serial generation internal.\n\n/* Message register bitfield. */\n#define BBCPCI_MSGREG_IRQ 0x00000001 /* An IRQ was generated. */\n\n/* The BBus bitfield looks like:\n * 1 1 1\n * F 8 0 8 0\n * fwsnnnnnnrccccccdddddddddddddddd\n *\n * where:\n * d = data (16 bits starting at bit 0)\n * c = channel (0-63) (6 bits starting at bit 16)\n * r = read flag (1 bit at bit 22)\n * n = node (0-63) (6 bits starting at bit 23)\n * s = ADC sync bit (1 bit at bit 29)\n * w = write flag (1 bit at bit 30)\n * f = frame sync (1 bit at bit 31)\n */\n\n#define BBC_NODE(x) ((unsigned int) (x) << 23)\n#define BBC_CH(x) ((unsigned int) (x) << 16)\n#define BBC_ADC_SYNC (0x20000000)\n#define BBC_READ (0x00400000)\n#define BBC_WRITE (0x40000000)\n#define BBC_FSYNC (0x80000000)\n#define BBC_ENDWORD (0x00000000)\n#define BBC_BI0_SYNC (0x0000eb90)\n#define BBC_BI0_ENDWORD (0xffff0000)\n\n#define BBC_ADDRESS(x) (((unsigned int)(x) & 0xffff0000) >> 16)\n#define BBC_DATA(x) ( (unsigned int)(x) & 0x0000ffff)\n\n#define BBC_NEXT_CHANNEL(x) ((x) + 0x10000)\n#define BI0_MAGIC(x) (((x) >> 16) & 0x1fff)\n#define BI0_TABLE_SIZE 0x2000\n\n#define GET_CH(x) (((x) >> 16) & 0x3f)\n#define GET_NODE(x) (((x) >> 23) & 0x3f)\n#define GET_STORE(x) (((x) & BBC_WRITE) != 0)\n#define GET_READ(x) (((x) & BBC_READ) != 0)\n#define GET_SYNC(x) (((x) & BBC_ADC_SYNC) != 0)\n\n/* timings */\n#define BBC_MASTER_CLK 32000000 /* set by the oscilator */\n#define BBC_MCLKS_PER_BBC_CLK 8\n#define BBC_CLK (BBC_MASTER_CLK / BBC_MCLKS_PER_BBC_CLK)\n\n#define BBC_ADC_MULTIPLIER 384 /* set by the ADC hardware */\n#define BBC_ADC_RATE (BBC_CLK / BBC_ADC_MULTIPLIER)\n#define BBC_ADCS_PER_SAMPLE 104 /* this sets the frame size */\n#define BBC_FRAME_RATE /* = (BBC_ADC_RATE / BBC_ADS_PER_SAMPLE) */ \\\n (BBC_CLK / (BBC_ADC_MULTIPLIER \\\n * BBC_ADCS_PER_SAMPLE))\n\n#define BBC_WORD_SIZE (32 * 2) /* x2 because of tx/rx pair */\n#define BBC_WORD_RATE (BBC_CLK / BBC_WORD_SIZE)\n#define BBC_MAX_FRAME_SIZE /* = (BBC_WORD_RATE / BBC_FRAME_RATE) */ \\\n ((BBC_ADC_MULTIPLIER * BBC_ADCS_PER_SAMPLE) \\\n / BBC_WORD_SIZE)\n#define BBC_EFFICIENCY 520 / 624\n#define BBC_FRAME_SIZE /* = (BBC_MAX_FRAME_SIZE * BBC_EFFICIENCY) */ \\\n ((BBC_ADC_MULTIPLIER * BBC_ADCS_PER_SAMPLE \\\n * BBC_EFFICIENCY) / BBC_WORD_SIZE)\n\n#define BI0_MCLKS_PER_BI0_CLK 32\n#define BI0_CLK (BBC_MASTER_CLK / BI0_MCLKS_PER_BI0_CLK)\n#define BI0_WORD_SIZE 16\n#define BI0_WORD_RATE (BI0_CLK / BI0_WORD_SIZE)\n#define BI0_FRAME_SIZE /* = (BBC_WORD_RATE / BI0_FRAME_RATE) */ \\\n ((BBC_MCLKS_PER_BBC_CLK * BBC_ADC_MULTIPLIER \\\n * BBC_ADCS_PER_SAMPLE) \\\n / (BI0_MCLKS_PER_BI0_CLK * BI0_WORD_SIZE))\n" }, { "alpha_fraction": 0.579734206199646, "alphanum_fraction": 0.5897009968757629, "avg_line_length": 26.363636016845703, "blob_id": "97044bf3f253c26f6324491cbc63d1c7b06936b7", "content_id": "c46f7d67935281a5942b34e0230f91e4299c28ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 602, "license_type": "no_license", "max_line_length": 101, "num_lines": 22, "path": "/starcam/svd.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <stdlib.h>\n\n/* max(A,B) - larger (most +ve) of two numbers (generic) */\n#define gmax(A,B) ((A)>(B)?(A):(B))\n\n/* min(A,B) - smaller (least +ve) of two numbers (generic) */\n#define gmin(A,B) ((A)<(B)?(A):(B))\n\n/* dsign(A,B) - magnitude of A with sign of B (double) */\n#define dsign(A,B) ((B)<0.0?-(A):(A))\n\n/* logicals */\n#if !defined(FALSE) || ((FALSE)!=0)\n#define FALSE 0\n#endif\n#if !defined(TRUE) || ((TRUE)!=1)\n#define TRUE 1\n#endif\n\ndouble rms ( double a, double b );\nvoid svd ( int m, int n, int mp, int np, double *a, double *w, double *v, double *work, int *jstat );\n" }, { "alpha_fraction": 0.6216495037078857, "alphanum_fraction": 0.6268041133880615, "avg_line_length": 24.5, "blob_id": "a6195401c6111cddaded52ea63d8bb763d651a1c", "content_id": "047b71dc3fdd91ede62c0701dcd696304b2157c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 971, "license_type": "no_license", "max_line_length": 73, "num_lines": 38, "path": "/stars/code/solving/refitting/refitter.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"refitter.h\"\n#include \"../solution.h\"\n#include \"../../shared/image/raw.h\"\n\n#include \"../../tools/quick_cout.h\"\n\nusing namespace Solving;\nusing namespace Solving::Refitting;\n\nvoid Refitter::fit(Solution& solution, Shared::Image::Raw& image)\n{\n\n // scratch\n /*\n for (unsigned int i=0; i<solution.matched_blobs.size(); i++) {\n cout << \"matched_blobs[\" << i << \"] has \";\n cout << solution.matched_blobs[i].x << \" \";\n cout << solution.matched_blobs[i].y << \" \";\n cout << solution.matched_blobs[i].sigma_x << endl;\n }\n */\n\n\n // sort matched blobs\n\n // get blob shapes from brightest N\n //shape_fitter.fit_gaussian(image, solution.matched_blobs);\n\n // fit blobs with set shape\n\n // fit solution with set blobs\n}\n\n" }, { "alpha_fraction": 0.7035688161849976, "alphanum_fraction": 0.7210487723350525, "avg_line_length": 30.930233001708984, "blob_id": "6c7d826a8a4c0bb271f5cf23c76a046ec398f4f3", "content_id": "0a95adac9c7c2db76164151942154b347a550b31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1373, "license_type": "no_license", "max_line_length": 79, "num_lines": 43, "path": "/owl/PBoxTitle.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"PBoxTitle.h\"\n#include \"PBox.h\"\n#include \"PMainWindow.h\"\n\nPBoxTitle::PBoxTitle(QWidget *parent) :\n QLabel(parent)\n{\n setAlignment(Qt::AlignHCenter | Qt::AlignTop );\n setMouseTracking(1);\n}\n\nvoid PBoxTitle::mouseMoveEvent(QMouseEvent *ev) {\n if (PMainWindow::me->mouseInactive()) return;\n\n dynamic_cast<PBox*>(parentWidget())->mouseMoveEvent(ev);\n}\n\nvoid PBoxTitle::mousePressEvent(QMouseEvent *ev) {\n if (PMainWindow::me->mouseInactive()) return;\n\n dynamic_cast<PBox*>(parentWidget())->mousePressEvent(ev);\n}\n" }, { "alpha_fraction": 0.7234637141227722, "alphanum_fraction": 0.7402234673500061, "avg_line_length": 34.70000076293945, "blob_id": "155cf122a417cb1ec88f67049d8274a42b79702a", "content_id": "8cac3da0b06e01e792bf8a48f22b7d86a0e29eaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 359, "license_type": "no_license", "max_line_length": 73, "num_lines": 10, "path": "/stars/code/preprocessor_reference.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n// This file is a reference for preprocessor_custom.h\n\n#define PREPROCESSOR_USING_CAMERA 0 // no camera\n//#define PREPROCESSOR_USING_CAMERA 1 // camera windows\n\n" }, { "alpha_fraction": 0.6060606241226196, "alphanum_fraction": 0.643236517906189, "avg_line_length": 30.067960739135742, "blob_id": "d25155abb4cee6ddbdeea51f9309385cabbc4852", "content_id": "99ed8826d97f21bc71565f3b48b6d309aae96777", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3201, "license_type": "no_license", "max_line_length": 106, "num_lines": 103, "path": "/liblinklist/linklist_connect.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* -----------------------------------------------------------------------\n * -------------------------- TCP Communications -------------------------\n * -----------------------------------------------------------------------\n * This program is distributed under the GNU General Public License (GPL).\n *\n * The following was developed in the QNX Momentics IDE and compiled on\n * using QNX RTOS version 6.5.\n *\n * ------------------------- Description -------------------------------\n * This is TCP network setup and configuration for communications with\n * ground station links. Contained are the functions used to transfer\n * frame files over the network along with the format files and\n * linklists required to parse the received data. The main programs that\n * use this code are mole and bittlm.\n *\n * ---------------------------- Author ---------------------------------\n * L. Javier Romualdez (B.Eng Aerospace)\n * Institute for Aerospace Studies (UTIAS)\n * University of Toronto\n *\n * Created: August 29, 2017\n *\n * Copyright 2017 Javier Romualdez\n *\n * -------------------------- Revisions --------------------------------\n *\n *\n */\n#ifndef TCPCONN_H_\n#define TCPCONN_H_\n\n#define SERVER_LL_REQ 0xEE000001\n#define SERVER_LL_LIST_REQ 0xEE000002\n#define SERVER_ARCHIVE_REQ 0xEE000003\n#define SERVER_SERIAL_REQ 0xEE000004\n#define SERVER_SET_LL_NAME_REQ 0xEE000005\n#define SERVER_ARCHIVE_LIST_REQ 0xEE000006\n#define SERVER_LL_NAME_REQ 0xEE000007\n\n#define TCPCONN_LOOP 0x01\n#define TCPCONN_FILE_RAW 0x02\n#define TCPCONN_NOLOOP 0x04\n#define TCPCONN_CLIENT_INIT 0x08\n#define TCPCONN_RESOLVE_NAME 0x10\n#define TCPCONN_FILE_RESET 0x20\n#define TCPCONN_NO_DATA 0x40\n\n#define TCP_PACKET_HEADER_SIZE 12\n#define CLIENT_TELEM_PORT 40204\n\n#ifndef MSG_MORE\n#define MSG_MORE 0\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nstruct TCPCONN\n{\n char ip[128];\n int fd;\n\tint flag;\n\tuint16_t theday, themonth, theyear;\n\tuint32_t serial;\n};\n \ntypedef struct TCPCONN linklist_tcpconn_t;\n\n#ifndef MAX\n#define MAX(a,b) ((a) > (b) ? (a) : (b))\n#endif\n\nvoid readTCPHeader(uint8_t *, uint32_t **, uint32_t **, uint16_t **, uint16_t **);\n\nint connect_tcp(struct TCPCONN * );\nint close_connection(struct TCPCONN *);\nint64_t initialize_client_connection(struct TCPCONN * , uint32_t );\nvoid set_linklist_server_port(unsigned int );\nvoid set_linklist_client_port(unsigned int );\n\nint request_server_list(struct TCPCONN * , char [][LINKLIST_SHORT_FILENAME_SIZE]);\nint request_server_archive_list(struct TCPCONN * , char [][LINKLIST_SHORT_FILENAME_SIZE]);\n\nint retrieve_data(struct TCPCONN * , uint8_t *, unsigned int);\nint request_data(struct TCPCONN *, unsigned int, uint16_t *);\n\nvoid set_server_linklist_name(struct TCPCONN * , char *);\nvoid request_server_linklist_name(struct TCPCONN * , char *, unsigned int, unsigned int);\nuint32_t request_server_file(struct TCPCONN * , char * , unsigned int );\nint send_client_file(struct TCPCONN * , char * , uint32_t );\n\nvoid send_client_error(struct TCPCONN *);\nvoid linklist_server(void *);\n\nvoid user_file_select(linklist_tcpconn_t *, char *);\nuint32_t sync_with_server(struct TCPCONN *, char *, char *, unsigned int, superframe_t **, linklist_t **);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* TCPCONN_H_ */\n\n" }, { "alpha_fraction": 0.6926069855690002, "alphanum_fraction": 0.6964980363845825, "avg_line_length": 19.979591369628906, "blob_id": "5de26ea2556cb668bc578e7e9f5b65d60a78e779", "content_id": "22f0e8dc7387bf77ad42a3076859eb37e418a707", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1029, "license_type": "no_license", "max_line_length": 73, "num_lines": 49, "path": "/stars/code/shared/autofocus/requests.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__AUTOFOCUS__REQUESTS_H\n#define SHARED__AUTOFOCUS__REQUESTS_H\n\n#include \"../circular_buffer.h\"\n#include \"../request.h\"\nextern \"C\" {\n#include \"../../networking/xsc_protocol/xsc_protocol.h\"\n}\n\nnamespace Shared\n{\n namespace Autofocus\n {\n\nclass Requests\n{\n public:\n Requests();\n void init(Parameters::Manager& params);\n Requests& operator=(const Requests& rhs);\n\n int run_counter;\n int focus_search_min;\n int focus_search_max;\n int focus_search_step;\n int abort_counter;\n bool abort_still_use_solution;\n xsc_autofocus_display_mode_t display_mode;\n};\n\n// writes: network\n// reads: main\nextern Shared::CircularBufferPass <Requests> requests_network_to_main;\n\n// writes: main\n// reads: lens\nextern Shared::CircularBuffer <Requests> requests_main_to_lens;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.6200000047683716, "alphanum_fraction": 0.6313043236732483, "avg_line_length": 31.167831420898438, "blob_id": "8a56daaf127ce1f2f84f6a017956efad0e1f8800", "content_id": "20a30d510312455f2dcd15b0b6911c7fcc2d3882", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4600, "license_type": "no_license", "max_line_length": 106, "num_lines": 143, "path": "/groundhog/bit/pilot.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <math.h>\n#include <stdbool.h>\n#include <arpa/inet.h> // socket stuff\n#include <netinet/in.h> // socket stuff\n#include <stdio.h> // socket stuff\n#include <sys/types.h> // socket types\n#include <sys/socket.h> // socket stuff\n#include <sys/stat.h>\n#include <dirent.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <signal.h>\n#include <stdlib.h>\n#include <string.h>\n#include <pthread.h> // threads\n#include <openssl/md5.h>\n#include <float.h>\n#include <time.h>\n#include <ctype.h>\n#include <sys/time.h>\n\n#include \"groundhog.h\"\n\nextern struct TlmReport ll_report[MAX_NUM_LINKLIST_FILES+1];\nstruct LinklistState ll_state[MAX_NUM_LINKLIST_FILES+1] = {{0}};\n\nvoid udp_receive(void *arg) {\n\n struct UDPSetup * udpsetup = (struct UDPSetup *) arg;\n\n struct BITRecver udprecver = {0};\n uint8_t * recvbuffer = NULL;\n uint16_t serial = 0, prev_serial = 0;\n linklist_t * ll = NULL;\n int32_t blk_size = 0;\n uint32_t recv_size = 0;\n uint64_t transmit_size = 0;\n int64_t framenum = 0;\n uint64_t recv_framenum = 0;\n\n uint8_t *local_allframe = calloc(1, superframe->allframe_size);\n\n // raw linklist data and fileblocks\n struct LinklistState * state = NULL;\n struct TlmReport * report = NULL;\n uint8_t * compbuffer = calloc(1, udpsetup->maxsize);\n\n // initialize UDP connection via bitserver/BITRecver\n initBITRecver(&udprecver, udpsetup->addr, udpsetup->port, 10, udpsetup->maxsize, udpsetup->packetsize);\n\n int bad_serial_count = 0;\n\n while (true) {\n do {\n // get the linklist serial for the data received\n recvbuffer = getBITRecverAddr(&udprecver, &recv_size);\n serial = *(uint16_t *) recvbuffer;\n if (!(ll = linklist_lookup_by_serial(serial))) {\n removeBITRecverAddr(&udprecver);\n if (verbose) groundhog_info(\"[%s] Receiving bad serial packets (0x%x)\\n\", udpsetup->name, serial);\n bad_serial_count++;\n } else {\n bad_serial_count = 0;\n break;\n }\n } while (true);\n\n // set the linklist serial\n setBITRecverSerial(&udprecver, serial);\n\n // receive the data from payload via bitserver\n blk_size = recvFromBITRecver(&udprecver, compbuffer, udpsetup->maxsize, 0);\n if (blk_size < 0) {\n\t\t\tgroundhog_info(\"Malformed packet received on Pilot\\n\");\n\t\t\tcontinue;\n }\n\n // process the auxiliary data into transmit size and frame number\n get_aux_packet_data(udprecver.frame_num, &transmit_size, &recv_framenum); \n\n // get the linklist state struct \n int flags = 0;\n\t\tint i;\n if (serial != prev_serial) {\n\t\t\tfor (i=0; i<MAX_NUM_LINKLIST_FILES; i++) {\n\t\t\t\tif (!ll_state[i].serial || (serial == ll_state[i].serial)) break;\n\t\t\t}\n\t\t\tll_state[i].serial = serial;\n\t\t\tstate = &ll_state[i];\n }\n\n // if this serial has not be recv'd yet, a new state will be allocated\n if (!state->ll_rawfile) {\n // set the flags to open a new rawfile\n flags |= GROUNDHOG_OPEN_NEW_RAWFILE;\n\n // reuse the rawfile if it had been accessed before\n if (ll->internal_id) flags |= GROUNDHOG_REUSE_VALID_RAWFILE;\n ll->internal_id = 42;\n\n\t\t\t// build the symlink name based on linklist name\n\t\t\tfor (i = 0; i < strlen(ll->name); i++) {\n\t\t\t\tif (ll->name[i] == '.') break;\n\t\t\t\tstate->symname[i] = toupper(ll->name[i]);\n\t\t\t}\n\t\t\tstate->symname[i] = '\\0'; // terminate\n }\n\n unsigned int bytes_unpacked = 0;\n while (bytes_unpacked < transmit_size) {\n // Received <= the data expected for the linklist, so received a single linklist packet or a\n // bandwidth-limited linklist.\n unsigned int comp_size = MIN(ll->blk_size, transmit_size-bytes_unpacked);\n framenum = groundhog_process_and_write(ll, comp_size, compbuffer+bytes_unpacked, \n local_allframe, state->symname, udpsetup->name, \n &state->ll_rawfile, flags); \n // only open a new rawfile once\n flags &= ~GROUNDHOG_OPEN_NEW_RAWFILE;\n\n // check to see how many bytes were unpacked\n // (negative framenum indicates allframe\n bytes_unpacked += (framenum > 0) ? ll->blk_size : ll->superframe->allframe_size;\n }\n\n // get the telemetry report\n if (serial != prev_serial) {\n\t\t\tfor (i=0; i<MAX_NUM_LINKLIST_FILES; i++) {\n\t\t\t\tif (!ll_report[i].ll || (serial == *(uint16_t *) ll_report[i].ll->serial)) break;\n\t\t\t}\n report = &ll_report[i];\n\t\t report->ll = ll;\n report->type = 0; // pilot report type\n }\n\n // fill out the telemetry report\n report->framenum = abs(framenum); \n report->allframe = (framenum < 0);\n\n prev_serial = serial;\n memset(compbuffer, 0, udpsetup->maxsize);\n \n }\n}\n" }, { "alpha_fraction": 0.7063291072845459, "alphanum_fraction": 0.7135021090507507, "avg_line_length": 32.38028335571289, "blob_id": "23d4c1350224ddd539e8316e25bbe1784757d1a5", "content_id": "f5be0bb6c01940bd27b0d091b20e463dc26748d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 2370, "license_type": "no_license", "max_line_length": 86, "num_lines": 71, "path": "/groundhog/blast/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "# Find glib \npkg_check_modules(PC_GLIB glib-2.0)\nset(GLIB_DEFINITIONS ${PC_GLIB_CFLAGS_OTHER})\n\nfind_path(GLIB_INCLUDE_DIR NAMES glib.h\n\t\t\t\t\tHINTS ${PC_GLIB_INCLUDEDIR} ${PC_GLIB_INCLUDE_DIRS}\n\t\t\t\t\tPATH_SUFFIXES glib-2.0 REQUIRED)\nfind_path(GLIBCONFIG_INCLUDE_DIR NAMES glibconfig.h\n\t\t\t\t\tHINTS ${PC_GLIB_INCLUDEDIR} ${PC_GLIB_INCLUDE_DIRS}\n\t\t\t\t\tPATH_SUFFIXES glib-2.0 REQUIRED)\nfind_library(GLIB_LIBRARY NAMES glib-2.0 libglib-2.0\n\t\t\t\t\t\tHINTS ${PC_GLIB_LIBDIR} ${PC_GLIB_LIBRARY_DIRS} REQUIRED)\nIF(NOT GLIB_INCLUDE_DIR)\n\t\tMESSAGE(FATAL_ERROR \"Did not find glib.h. Is libglib2.0-dev installed?\")\nENDIF()\nIF(NOT GLIB_LIBRARY) \n\t\tMESSAGE(FATAL_ERROR \"Did not find libglib-2.0. Is libglib2.0-0 installed?\")\nENDIF()\ninclude_directories(${GLIB_INCLUDE_DIR} ${GLIBCONFIG_INCLUDE_DIR})\n\n\nset(COMMON_DIR \"${PROJECT_SOURCE_DIR}/../common\")\nset(COMMUNICATIONS_DIR \"${PROJECT_SOURCE_DIR}/../mcp/communications\")\nset(CONFIG_DIR \"${PROJECT_SOURCE_DIR}/../blast_config\")\nset(COMMS_DIR \"${PROJECT_SOURCE_DIR}/../blast_comms\")\n\ninclude_directories (\n \"${COMMON_DIR}/include\"\n \"${COMMS_DIR}/include\"\n \"${CONFIG_DIR}/include\"\n \"${COMMUNICATIONS_DIR}/include\"\n)\n\n# add common objects \nadd_subdirectory(${COMMON_DIR} \"${PROJECT_BINARY_DIR}/blast_common\")\nadd_subdirectory(${CONFIG_DIR} \"${PROJECT_BINARY_DIR}/blast_config\")\n# add asynchronous communication objects\nadd_subdirectory(${COMMS_DIR} \"${PROJECT_BINARY_DIR}/blast_comms\")\n\nadd_library (blast_common OBJECT ${GROUNDHOG_COMMON_SRCS} ${GROUNDHOG_COMMON_HEADERS})\ndefine_file_basename_for_sources(blast_common)\n\nadd_library (blast_comms OBJECT ${COMMS_SRCS} ${COMMS_HEADERS})\ndefine_file_basename_for_sources(blast_comms)\n\ndefine_file_basename_for_sources(groundhog)\n\nadd_executable (groundhog \n $<TARGET_OBJECTS:liblinklist>\n ${PROJECT_SOURCE_DIR}/groundhog_funcs.c\n ${PROJECT_SOURCE_DIR}/groundhog_funcs.h\n\n $<TARGET_OBJECTS:blast_common>\n $<TARGET_OBJECTS:blast_comms>\n ${PROJECT_SOURCE_DIR}/blast/main.c\n ${PROJECT_SOURCE_DIR}/blast/decom_pci.h\n ${PROJECT_SOURCE_DIR}/blast/groundhog.h\n ${PROJECT_SOURCE_DIR}/blast/biphase.c\n ${PROJECT_SOURCE_DIR}/blast/highrate.c\n\n ${PROJECT_SOURCE_DIR}/blast/pilot.c\n ) \n\ntarget_link_libraries(groundhog\n ${GLIB_LIBRARY} \n ${GD_LIBRARY}\n ${CMAKE_THREAD_LIBS_INIT} \n ssl crypto\n )\n\ninstall(TARGETS groundhog DESTINATION bin)\n" }, { "alpha_fraction": 0.6145584583282471, "alphanum_fraction": 0.620525062084198, "avg_line_length": 20.461538314819336, "blob_id": "01e3fc0ccf8a444fbab32016473e28b523497726", "content_id": "129c2e8c0b11e35fbbd242e16a169dc19e7ffa2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 839, "license_type": "no_license", "max_line_length": 73, "num_lines": 39, "path": "/stars/code/shared/camera/results.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"results.h\"\n\nusing namespace Shared::Camera;\n\nResults::Results()\n{\n counter_stars = 0;\n connected = false;\n}\n\nResults& Results::operator=(const Results &rhs)\n{\n if (this != &rhs) {\n counter_stars = rhs.counter_stars;\n connected = rhs.connected;\n set_gain = rhs.set_gain;\n get_gain = rhs.get_gain;\n }\n return *this;\n}\n\nbool Results::is_gain_valid(Requests& requests)\n{\n if (!get_gain.found) {\n return false;\n }\n if (set_gain.counter == requests.set_gain.counter &&\n get_gain.counter == requests.get_gain.counter)\n {\n return true;\n }\n return false;\n}\n\n" }, { "alpha_fraction": 0.7003722190856934, "alphanum_fraction": 0.7084367275238037, "avg_line_length": 19.40506362915039, "blob_id": "9e6ed69ffd4fd03bcc75ea534b813e48747292ca", "content_id": "e58f4d715bb6ebbe30c264a381d913fa2bfdd6ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1613, "license_type": "no_license", "max_line_length": 82, "num_lines": 79, "path": "/stars/code/imaging/camera_windows.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"../preprocessor.h\"\n#if PREPROCESSOR_USING_CAMERA\n\n#pragma once\n#ifndef IMAGING__CAMERA_WINDOWS_H\n#define IMAGING__CAMERA_WINDOWS_H\n\n#ifdef _WIN32\n #include <windows.h>\n#endif\n#include <boost/thread/thread.hpp>\n#include \"abstract_camera.h\"\n#include <QCamAPI.h>\n#include <QCamImgfnc.h>\n// QCamAPI.h is idiotic and defines types with a macro. This breaks lots of stuff\n#undef uint32_t\n#undef uint16_t\n#undef uint8_t\n#include <cstdint>\n\n#include \"../dmm.h\"\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Imaging\n{\n class CameraWindows;\n}\n\nclass Imaging::CameraWindows: public Imaging::AbstractCamera\n{\n public:\n CameraWindows(Parameters::Manager& params, dmm *card);\n\n bool init_camera();\n void clean_up_camera();\n void read_image_if_available();\n\n void get_trigger_mode();\n void set_trigger_mode();\n\n\tvoid init_gain();\n\tvoid get_gain();\n void process_requests();\n\n void thread_function();\n void wait_for_quit();\n\n private:\n QCam_Err camerror;\n\tQCam_CamListItem camlist[2]; // List of connected cameras\t\n\tQCam_Handle camhandle;\n\tQCam_SettingsEx settings;\n\tunsigned char *frameBuf1;\n QCam_Frame frame;\n\tunsigned long FrameSize;\t\n\tunsigned short FrameNumber;\n\tbool isCapturing;\n\n double gain_min;\n double gain_max;\n\tdmm *io_card;\n\n // thread belongs to derived class to prevent pure virtual function call\n boost::thread thread;\n};\n\n#endif\n\n#endif\n" }, { "alpha_fraction": 0.7208480834960938, "alphanum_fraction": 0.7279151678085327, "avg_line_length": 25.904762268066406, "blob_id": "e18ae12cdc366e131025076060ea2fa8c2a0fc42", "content_id": "9e730bf8394df1b585795aa23641b599dfc1cc33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 567, "license_type": "no_license", "max_line_length": 101, "num_lines": 21, "path": "/stars/code/solving/matching/catalog_manager.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"catalog_manager.h\"\n#include \"../update.h\"\n#include \"../logger.h\"\n\nusing namespace Solving::Matching;\n\nCatalogManager::CatalogManager(Parameters::Manager& params, bool enabled, std::string catalog_path_):\n Cataloging::AbstractCatalogManager(params, enabled, catalog_path_, Solving::logger)\n{\n}\n\nbool CatalogManager::abort()\n{\n return Solving::done();\n}\n\n" }, { "alpha_fraction": 0.6634646058082581, "alphanum_fraction": 0.6733909845352173, "avg_line_length": 26.637168884277344, "blob_id": "b0ef210bdc1ea3305187bfe3637cac1ad93364d2", "content_id": "63f707d18fbaacd59838b32f7e56e30af094cd7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3123, "license_type": "no_license", "max_line_length": 130, "num_lines": 113, "path": "/starcam/testfifo.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//test program to communicate with the \"flight computer\" end of the FIFOs\n\n//these are reversed because the files are named from starcam perspective\nconst char* readFifoName = \"/usr/local/starcam/writefifo\";\nconst char* writeFifoName = \"/usr/local/starcam/readfifo\";\n\n#define USE_COMMAND_GUI 0\n\n#if USE_COMMAND_GUI\n#include <qapplication.h>\n#include \"commandgui.h\"\n\nint main(int argc, char *argv[])\n{\n\tQApplication a(argc, argv);\n\tCommandGUI gui(0, \"gui\", readFifoName, writeFifoName);\n\ta.setMainWidget(&gui);\n\tgui.setGeometry(100, 100, 600, 400);\n\tgui.show();\n\treturn a.exec();\n}\n\n#endif\n\n#if USE_COMMAND_GUI == 0\n#include <iostream>\n#include <string>\n//#include <unistd.h>\n//#include <fcntl.h>\n#include <pthread.h>\n#include \"fifocommunicator.h\"\n#include \"camconfig.h\"\n\n\n//function prototypes\nvoid* readLoop(void* arg);\nstring displayReturn(string rtn);\n\nint main(int argc, char *argv[])\n{\n\tchar buf[256];\n\t//open fifos in opposite manner to main starcam program\n\tcout << \"Opening \" << readFifoName << \" to read and \" << writeFifoName << \" to write\\nwill block until other side opens\" << endl;\n\tFIFOCommunicator comm;\n\tif (comm.openOppositeFifos(readFifoName, writeFifoName) < 0) \n\t\tcout << \"An error occured while opening the fifos.\" << endl;\n\t\t\n\t//start thread that constantly waits to read a return value\n\tpthread_t thread;\n\tpthread_create(&thread, NULL, &readLoop, (void*)&comm);\n\t\n\t//in this thread, constantly read command strings from keyboard and send to camera\n\twhile (1) {\n\t\tcout << \"Enter a string to send to the star camera (Ctrl-C quits): \";\n\t\tcin.getline(buf, 256);\n\t\tcout << \"Sending command: \" << buf << endl;\n\t\tif (comm.sendCommand(buf) < 0) break;\n\t}\n\tcout << \"Loop has quit unexpectedly...sending of command must have failed.\" << endl;\n\t\t\t\n\t//wait for read thread to end (eg. never)\n\tpthread_join(thread, NULL);\n\t\n\treturn 0;\n}\n\n/*\n\n readLoop:\n \n simply a wrapper function for calling the FIFOCommunicator::readLoop member in a pthread\n \n*/\nvoid* readLoop(void* arg)\n{\n\tFIFOCommunicator* comm = (FIFOCommunicator*)arg;\n\tcomm->readLoop(&displayReturn);\n\treturn NULL;\n}\n\n/*\n\n displayReturn:\n \n interprets and displays the return string obtained from starcam\n \n*/\nstring displayReturn(string rtn_str)\n{\n\tif (rtn_str.substr(0,5) == \"<str>\") { //return is a string\n\t\trtn_str = rtn_str.substr(5, rtn_str.length() - 11);\n\t\tcout << \"Command returned string:\\n \" << rtn_str << endl;\n\t} else { //otherwise it is a return struct\n\t\tStarcamReturn rtn;\n\t\tFIFOCommunicator::interpretReturn(rtn_str, &rtn);\n\t\tcout << \"\\n\\nObtained a picture return signal from camera #\" << rtn.cameraID << endl\n\t\t \t<< \"... mapmean =\" << rtn.mapmean << endl\n\t\t \t<< \"... sigma=\" << rtn.sigma << endl\n\t\t \t<< \"... exposuretime=\" << rtn.exposuretime << endl\n\t\t \t<< \"... imagestarttime=\" << rtn.imagestarttime.tv_sec << \"s \" \n\t\t\t<< rtn.imagestarttime.tv_usec << \"us\" << endl\n\t\t\t \t<< \"... ccdtemperature=\" << rtn.ccdtemperature << endl\n\t\t \t<< \"... numblobs=\" << rtn.numblobs << endl;\n\t}\n\t\n\t//reprompt\n\tcout << \"\\nEnter a string to send to the star camera (Ctrl-C quits): \";\n\n\t\n\treturn \"\";\n}\n\n#endif //if USE_COMMAND_GUI == 0\n" }, { "alpha_fraction": 0.5680851340293884, "alphanum_fraction": 0.5946808457374573, "avg_line_length": 32.53571319580078, "blob_id": "4ced5ce910628b5ce00f9605aa58395aae8cb0bf", "content_id": "390a289c23262292d0cde4e262e2b775f3fba2d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 941, "license_type": "no_license", "max_line_length": 94, "num_lines": 28, "path": "/stars/code/tools/blob_shape.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"math.h\"\n\ndouble blob_shape(double r, double A, double rfocus_unscaled, double sigma, double inner_flat)\n{\n double value = 0.0;\n\n if (rfocus_unscaled < 0) {\n double rfocus = rfocus_unscaled;\n double normalization = 1.0; // needs to be calculated\n if (r < rfocus) {\n value = exp(-pow(r-rfocus, 2.0)/pow(sigma, 2.0));\n value = value*(1.0 - inner_flat) + inner_flat;\n value = A*normalization*value;\n } else {\n value = A*normalization*(exp(-pow(r-rfocus, 2.0)/pow(sigma, 2.0)));\n }\n } else {\n double normalization = 1.0; // needs to be calculated\n value = A*normalization*(exp(-pow(r, 2.0)/pow(sigma, 2.0)));\n }\n return value;\n}\n\n" }, { "alpha_fraction": 0.6927083134651184, "alphanum_fraction": 0.7005208134651184, "avg_line_length": 17.731706619262695, "blob_id": "e2e1b1fe5973db81a0afa7c8579c87d318b2084d", "content_id": "499076e836d76733ceb136033294cc8ce093d5be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 769, "license_type": "no_license", "max_line_length": 73, "num_lines": 41, "path": "/stars/code/shared/network/packets.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__NETWORK__PACKETS_H\n#define SHARED__NETWORK__PACKETS_H\n\n#include \"../circular_buffer.h\"\n#include \"../../tools/timing.h\"\n\nnamespace Shared\n{\nnamespace Network\n{\n\nclass Packets\n{\n public:\n Packets();\n Packets& operator=(const Packets& rhs);\n\n bool in_charge;\n Tools::Timer time_since_sent;\n Tools::Timer time_since_received;\n};\n\n// writes: network\n// reads: main\nextern Shared::CircularBuffer <Packets> packets_from_fc1;\n\n// writes: network\n// reads: main\nextern Shared::CircularBuffer <Packets> packets_from_fc2;\n\n}\n}\n\n#endif\n" }, { "alpha_fraction": 0.5402851104736328, "alphanum_fraction": 0.5678648948669434, "avg_line_length": 31.590909957885742, "blob_id": "aaf7aed7f425bfb668fb5758f11a8c5621b390b8", "content_id": "a7b8f8779cd7d0bd52a1786d141011a4289e3e74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6455, "license_type": "no_license", "max_line_length": 129, "num_lines": 198, "path": "/stars/code/solving/finding/fitter.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"fitter.h\"\n#include <levmar.h>\n#include \"../../shared/solving/settings.h\"\n#include \"../../shared/image/raw.h\"\n\nusing namespace Solving;\nusing namespace Solving::Finding;\nusing std::min;\nusing std::max;\n\n#define shared_settings (*(Shared::Solving::settings.r))\n\nnamespace levmar_c_functions\n{\n\nstruct gaussian_additional_data\n{\n int* us;\n int* vs;\n};\n\nvoid gaussian(double* params, double* pixels, int num_params, int num_pixels, void* data)\n{\n gaussian_additional_data* additional_data = (gaussian_additional_data*) data;\n int* us = additional_data->us;\n int* vs = additional_data->vs;\n double mu_u = params[1];\n double mu_v = params[2];\n double sigma_sq = pow(params[3], 2.0);\n double base = params[3];\n for (int i=0; i<num_pixels; i++) {\n pixels[i] = params[0] * exp(-(pow(us[i]-mu_u, 2.0) + pow(vs[i]-mu_v, 2.0)) / (2.0*sigma_sq)) + base;\n }\n}\n\nvoid double_gaussian(double* params, double* pixels, int num_params, int num_pixels, void* data)\n{\n gaussian_additional_data* additional_data = (gaussian_additional_data*) data;\n int* us = additional_data->us;\n int* vs = additional_data->vs;\n double mu1_x = params[1];\n double mu1_y = params[2];\n double sigma1_sq = pow(params[3], 2.0);\n double mu2_x = params[5];\n double mu2_y = params[6];\n double sigma2_sq = pow(params[7], 2.0);\n double base = params[8];\n for (int i=0; i<num_pixels; i++) {\n pixels[i] = params[0] * exp(-(pow(us[i]-mu1_x, 2.0) + pow(vs[i]-mu1_y, 2.0)) / (2.0*sigma1_sq));\n pixels[i] += params[4] * exp(-(pow(us[i]-mu2_x, 2.0) + pow(vs[i]-mu2_y, 2.0)) / (2.0*sigma2_sq));\n pixels[i] += base;\n }\n}\n\n}\n\nFitter::Fitter()\n{\n max_num_pixels = 50*50;\n pixels = new double[max_num_pixels];\n us = new int[max_num_pixels];\n vs = new int[max_num_pixels];\n\n int max_num_params = 9;\n workspace = (double *) malloc((LM_DIF_WORKSZ(max_num_params, max_num_pixels)+max_num_params* max_num_params)*sizeof(double));\n covar = workspace + LM_DIF_WORKSZ(max_num_params, max_num_pixels);\n}\n\nFitter::~Fitter()\n{\n delete [] pixels;\n delete [] us;\n delete [] vs;\n free(workspace);\n}\n\nvoid Fitter::fit_gaussian(Shared::Image::Raw& image, Blob& blob)\n{\n int halfwidth = 10;\n int i = 0;\n for (int u = blob.u-halfwidth; u <= blob.u+halfwidth; u++) {\n for (int v = blob.v-halfwidth; v <= blob.v+halfwidth; v++) {\n if (i < max_num_pixels && image.is_inbounds(u, v)) {\n pixels[i] = double(image.get_pixel(u, v));\n us[i] = u;\n vs[i] = v;\n i++;\n }\n }\n }\n int num_pixels = i;\n levmar_c_functions::gaussian_additional_data additional_data;\n additional_data.us = us;\n additional_data.vs = vs;\n\n int num_params = 5;\n double* params = new double[num_params];\n params[0] = blob.flux; // A / sqrt(2*pi*sigma*sigma)\n params[1] = double(blob.u); // mu_u\n params[2] = double(blob.v); // mu_v\n params[3] = 3.0; // sigma\n params[4] = 0; // base\n\n dlevmar_dif(levmar_c_functions::gaussian, params, pixels, num_params, num_pixels,\n 100, NULL, NULL, workspace, covar, (void*) &additional_data);\n\n blob.x = params[1] - (double(image.width)-1.0)/2.0;\n blob.y = params[2] - (double(image.height)-1.0)/2.0;\n blob.sigma_x = params[3];\n blob.fit_error_x = sqrt(covar[1*num_params+1]);\n blob.fit_error_y = sqrt(covar[2*num_params+2]);\n\n delete [] params;\n}\n\nvoid Fitter::fit_double_gaussian(Shared::Image::Raw& image, Blob& blob)\n{\n int halfwidth = 10;\n int i = 0;\n for (int u = blob.u-halfwidth; u <= blob.u+halfwidth; u++) {\n for (int v = blob.v-halfwidth; v <= blob.v+halfwidth; v++) {\n if (i < max_num_pixels && image.is_inbounds(u, v)) {\n pixels[i] = double(image.get_pixel(u, v));\n us[i] = u;\n vs[i] = v;\n i++;\n }\n }\n }\n int num_pixels = i;\n levmar_c_functions::gaussian_additional_data additional_data;\n additional_data.us = us;\n additional_data.vs = vs;\n\n int num_params = 9;\n double* params = new double[num_params];\n params[0] = blob.flux; // A1 / sqrt(2*pi*sigma1*sigma1)\n params[1] = double(blob.u); // mu1_x\n params[2] = double(blob.v); // mu1_y\n params[3] = 3.0; // sigma1\n params[4] = blob.flux/5.0; // A2 / sqrt(2*pi*sigma2*sigma2)\n params[5] = double(blob.u+5); // mu2_x\n params[6] = double(blob.v+0); // mu2_y\n params[7] = 3.0; // sigma2\n params[8] = 0; // base\n\n dlevmar_dif(levmar_c_functions::double_gaussian, params, pixels, num_params, num_pixels,\n 30, NULL, NULL, workspace, covar, (void*) &additional_data);\n\n if (params[0] >= params[4]) {\n blob.x = params[1] - (double(image.width)-1.0)/2.0;\n blob.y = params[2] - (double(image.height)-1.0)/2.0;\n blob.sigma_x = params[3];\n } else {\n blob.x = params[5] - (double(image.width)-1.0)/2.0;\n blob.y = params[6] - (double(image.height)-1.0)/2.0;\n blob.sigma_x = params[7];\n }\n\n delete [] params;\n}\n\nBlob Fitter::fit(Shared::Image::Raw& image, Blob& blob)\n{\n using namespace Shared::Solving;\n double original_x = double(blob.u) - (double(image.width)-1.0)/2.0;\n double original_y = double(blob.v) - (double(image.height)-1.0)/2.0;\n switch (shared_settings.fitting_method) {\n\n case xC_solver_fitting_method_gaussian:\n fit_gaussian(image, blob);\n break;\n\n case xC_solver_fitting_method_double_gaussian:\n fit_double_gaussian(image, blob);\n break;\n\n case xC_solver_fitting_method_none:\n default:\n blob.x = double(blob.u) - (double(image.width)-1.0)/2.0;\n blob.y = double(blob.v) - (double(image.height)-1.0)/2.0;\n break;\n\n }\n double distance_moved_squared = pow(original_x - blob.x, 2.0) + pow(original_y - blob.y, 2.0);\n if (distance_moved_squared < 20*20 && image.is_xy_inbounds(blob.x, blob.y)) {\n blob.fit_was_good = true;\n } else {\n blob.fit_was_good = false;\n }\n return blob;\n}\n\n" }, { "alpha_fraction": 0.5553612112998962, "alphanum_fraction": 0.5633115768432617, "avg_line_length": 27.58333396911621, "blob_id": "ff261f5d6f6f55bd3ab852c065278c61f3906cba", "content_id": "9310cfe017970d29d19b6f70c82eebc444caa330", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 18867, "license_type": "no_license", "max_line_length": 117, "num_lines": 660, "path": "/owl/PDotOwl.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"POwlAnimation.h\"\n#include \"PAbstractDataItem.h\"\n#include \"PExtremaDataItem.h\"\n#include \"PDirfileDataItem.h\"\n#include \"PBox.h\"\n#include \"PExtrema.h\"\n#include \"PMainWindow.h\"\n#include \"PMap.h\"\n#include \"PMdiArea.h\"\n#include \"PMdiArea.h\"\n#include \"PBitMultiDataItem.h\"\n#include \"PMultiDataItem.h\"\n#include \"PNumberDataItem.h\"\n#include \"PTimeDataItem.h\"\n#include \"PObject.h\"\n#include <QTimer>\n#include <QDebug>\n#include <QMessageBox>\n\n#define OLDEST_SUPPORTED_OWL_REVISION 20140928\n#define LATEST_OWL_REVISION 20140928\nint revId=-1;\nint _lastId=0; //in order to not break anything\n\nQVariant save(PObject& b)\n{\n QMap<QString,QVariant> ret;\n ret.insert(\"_id\",QString::number(b._id));\n return ret;\n}\n\nvoid load(QVariant s,PObject& b)\n{\n b._id=s.toMap()[\"_id\"].toInt();\n PObject::_u[b._id]=&b;\n}\n\nQVariant save(PExtrema &b)\n{\n QMap<QString,QVariant> ret;\n ret.insert(\"_name\",b._name);\n ret.insert(\"_xhigh\",b._xhigh);\n ret.insert(\"_high\",b._high);\n ret.insert(\"_low\",b._low);\n ret.insert(\"_xlow\",b._xlow);\n\n if(b._sxhigh!=PStyle::noStyle) {\n ret.insert(\"_sxhigh\",b._sxhigh->idText());\n } else {\n ret.insert(\"_sxhigh\",\"NO STYLE\");\n }\n\n if(b._shigh!=PStyle::noStyle) {\n ret.insert(\"_shigh\",b._shigh->idText());\n } else {\n ret.insert(\"_shigh\",\"NO STYLE\");\n }\n\n if(b._slow!=PStyle::noStyle) {\n ret.insert(\"_slow\",b._slow->idText());\n } else {\n ret.insert(\"_slow\",\"NO STYLE\");\n }\n\n if(b._sxlow!=PStyle::noStyle) {\n ret.insert(\"_sxlow\",b._sxlow->idText());\n } else {\n ret.insert(\"_sxlow\",\"NO STYLE\");\n }\n\n ret.insert(\"PObject\",save(*(PObject*)(&b)));\n return ret;\n}\n\nvoid load(QVariant r,PExtrema&b)\n{\n QVariantMap v=r.toMap();\n b._name=v[\"_name\"].toString();\n b._xhigh=v[\"_xhigh\"].toFloat();\n b._high=v[\"_high\"].toFloat();\n b._low=v[\"_low\"].toFloat();\n b._xlow=v[\"_xlow\"].toFloat();\n\n if(v[\"_sxhigh\"].toString()==\"NO STYLE\") {\n b._sxhigh=PStyle::noStyle;\n } else {\n QString idText=v[\"_sxhigh\"].toString();\n bool ok=0;\n for(int i=0;i<PStyle::_u.size();i++) {\n if(PStyle::_u[i]->idText()==idText) {\n ok=1;\n b._sxhigh=PStyle::_u[i];\n break;\n }\n }\n Q_ASSERT(ok);\n }\n\n if(v[\"_shigh\"].toString()==\"NO STYLE\") {\n b._shigh=PStyle::noStyle;\n } else {\n QString idText=v[\"_shigh\"].toString();\n bool ok=0;\n for(int i=0;i<PStyle::_u.size();i++) {\n if(PStyle::_u[i]->idText()==idText) {\n ok=1;\n b._shigh=PStyle::_u[i];\n break;\n }\n }\n Q_ASSERT(ok);\n }\n\n if(v[\"_slow\"].toString()==\"NO STYLE\") {\n b._slow=PStyle::noStyle;\n } else {\n QString idText=v[\"_slow\"].toString();\n bool ok=0;\n for(int i=0;i<PStyle::_u.size();i++) {\n if(PStyle::_u[i]->idText()==idText) {\n ok=1;\n b._slow=PStyle::_u[i];\n break;\n }\n }\n Q_ASSERT(ok);\n }\n\n if(v[\"_sxlow\"].toString()==\"NO STYLE\") {\n b._sxlow=PStyle::noStyle;\n } else {\n QString idText=v[\"_sxlow\"].toString();\n bool ok=0;\n for(int i=0;i<PStyle::_u.size();i++) {\n if(PStyle::_u[i]->idText()==idText) {\n ok=1;\n b._sxlow=PStyle::_u[i];\n break;\n }\n }\n Q_ASSERT(ok);\n }\n\n load(v[\"PObject\"],*(PObject*)(&b));\n}\n\nQVariant save(PStyle& b)\n{\n QMap<QString,QVariant> ret;\n ret.insert(\"_bg\",b._bg);\n ret.insert(\"_bold\",b._bold);\n ret.insert(\"_fg\",b._fg);\n ret.insert(\"_italic\",b._italic);\n ret.insert(\"_linked\",b._linked);\n ret.insert(\"_name\",b._name);\n ret.insert(\"PObject\",save(*(PObject*)(&b)));\n\n return ret;\n}\n\nvoid load(QVariant v,PStyle& b)\n{\n QVariantMap r=v.toMap();\n\n b._bg=r[\"_bg\"].value<QColor>();\n b._bold=r[\"_bold\"].toBool();\n b._fg=r[\"_fg\"].value<QColor>();\n b._italic=r[\"_italic\"].toBool();\n b._linked=r[\"_linked\"].toBool();\n b._name=r[\"_name\"].toString();\n\n load(r[\"PObject\"],*(PObject*)(&b));\n\n if(b._linked) {\n PStyle::_u.push_back(&b);\n }\n}\n\nQVariant save(PMap& b)\n{\n QMap<QString, QVariant> ret;\n QMap<QString, QVariant> bmap;\n\n for(int i=0;i<b._map.size();i++) {\n bmap.insertMulti(QString::number(b._map.keys()[i]), b._map.values()[i]);\n }\n\n ret.insert(\"_map\",bmap);\n ret.insert(\"PObject\",save(*(PObject*)(&b)));\n return ret;\n}\n\nvoid load(QVariant v,PMap&b)\n{\n QVariantMap m=v.toMap();\n\n load(m[\"PObject\"],*(PObject*)(&b));\n\n for(int i=0;i<m[\"_map\"].toMap().count();i++) {\n b._map.insertMulti(m[\"_map\"].toMap().keys()[i].toInt(),\n m[\"_map\"].toMap().values()[i].toString());\n }\n}\n\nQVariant save(PAbstractDataItem&b)\n{\n QMap<QString,QVariant> ret;\n PBitMultiDataItem* pbdi=dynamic_cast<PBitMultiDataItem*>(&b);\n if(pbdi) {\n ret.insert(\"type\",\"PBDI\");\n ret.insert(\"_highWord\",pbdi->_highWord);\n ret.insert(\"_lowWord\",pbdi->_lowWord);\n ret.insert(\"_nBits\",pbdi->_nBits);\n }\n\n PMultiDataItem* pmdi=dynamic_cast<PMultiDataItem*>(&b);\n if(pmdi) {\n ret.insert(\"type\",\"PMDI\");\n ret.insert(\"PMDI\",save(*pmdi->_map));\n }\n\n PNumberDataItem* pndi=dynamic_cast<PNumberDataItem*>(&b);\n if(pndi) {\n ret.insert(\"type\",\"PNDI\");\n ret.insert(\"_format\",pndi->_format);\n }\n\n PTimeDataItem* ptdi=dynamic_cast<PTimeDataItem*>(&b);\n if(ptdi) {\n ret.insert(\"type\",\"PTDI\");\n ret.insert(\"_format\",ptdi->_format);\n }\n\n PExtremaDataItem *pedi=dynamic_cast<PExtremaDataItem*>(&b);\n if (pedi) {\n ret.insert(\"_extrema\",(bool)pedi->_extrema);\n if(pedi->_extrema) ret.insert(\"_extremaID\",pedi->_extrema->idText());\n }\n\n PDirfileDataItem* pddi=dynamic_cast<PDirfileDataItem*>(&b);\n if(pddi) {\n ret.insert(\"type\",\"PDDI\");\n }\n\n if(!pbdi&&!pmdi&&!pndi&&!ptdi&&!pddi) {\n ret.insert(\"type\",\"INVALID!\");\n qDebug()<<\"Warning: Saving PAbstractDataItem of unknown type...\";\n }\n\n ret[\"PObject\"]=save(*(PObject*)(&b));\n ret.insert(\"_caption\",b._caption->text());\n ret.insert(\"_source\",b._source);\n\n\n if(b._captionStyle!=PStyle::noStyle) {\n ret.insert(\"_captionStyle\",b._captionStyle->idText());\n } else {\n ret.insert(\"_captionStyle\",\"noStyle\");\n }\n\n if(b._defaultDataStyle!=PStyle::noStyle) {\n ret.insert(\"_defaultStyle\",b._defaultDataStyle->idText());\n } else {\n ret.insert(\"_defaultStyle\",\"noStyle\");\n }\n\n return ret;\n}\n\nvoid load(QVariant v,PAbstractDataItem&b)\n{\n QVariantMap m=v.toMap();\n\n load(m[\"PObject\"],*(PObject*)(&b));\n\n b._caption->setText(m[\"_caption\"].toString());\n b._source=m[\"_source\"].toString();\n\n if(m[\"_captionStyle\"].toString()==\"noStyle\") {\n b._captionStyle=PStyle::noStyle;\n } else {\n QString idText=m[\"_captionStyle\"].toString();\n bool ok=0;\n for(int i=0;i<PStyle::_u.size();i++) {\n if(PStyle::_u[i]->idText()==idText) {\n ok=1;\n b._captionStyle=PStyle::_u[i];\n break;\n }\n }\n Q_ASSERT(ok);\n }\n\n if(m[\"_defaultStyle\"].toString()==\"noStyle\") {\n b._defaultDataStyle=PStyle::noStyle;\n } else {\n QString idText=m[\"_defaultStyle\"].toString();\n bool ok=0;\n for(int i=0;i<PStyle::_u.size();i++) {\n if(PStyle::_u[i]->idText()==idText) {\n ok=1;\n b._defaultDataStyle=PStyle::_u[i];\n break;\n }\n }\n Q_ASSERT(ok);\n }\n}\n\nvoid load(QVariant v, PExtremaDataItem &b)\n{\n QVariantMap m=v.toMap();\n if(m[\"_extrema\"].toBool())\n {\n QString exIdText;\n exIdText=m[\"_extremaID\"].toString();\n bool ok=0;\n for(int i=0;i<PExtrema::_u.size();i++) {\n if(PExtrema::_u[i]->idText()==exIdText) {\n b._extrema=PExtrema::_u[i];\n ok=1;\n break;\n }\n }\n Q_ASSERT(ok);\n }\n}\n\nvoid load(QVariant v,PBitMultiDataItem &b)\n{\n QVariantMap m=v.toMap();\n b._highWord=m[\"_highWord\"].toString();\n b._lowWord=m[\"_lowWord\"].toString();\n b._nBits=m[\"_nBits\"].toInt();\n}\n\nvoid load(QVariant v,PMultiDataItem &b)\n{\n load(v.toMap()[\"PMDI\"],*b._map);\n}\n\nvoid load(QVariant r, PTimeDataItem &b)\n{\n b._format=r.toMap()[\"_format\"].toString();\n}\n\nvoid load(QVariant v,PNumberDataItem&b)\n{\n QVariantMap m=v.toMap();\n b._format=m[\"_format\"].toString();\n}\n\nQVariant save(POwlAnimation&b)\n{\n QVariantMap map;\n\n double scale = b.fontMetrics().height()/18.0;\n map.insert(\"geometryX\",int(b.geometry().x()));\n map.insert(\"geometryY\",int(b.geometry().y()));\n map.insert(\"geometryWidth\",int(b.geometry().width()));\n map.insert(\"geometryHeight\",int(b.geometry().height())); //our wonderful json serialzer doesn't like QRects :(\n\n // new geometry: in font-height cells\n scale = b.fontMetrics().height();\n map.insert(\"cellX\",int(b.geometry().x()/scale+0.49));\n map.insert(\"cellY\",int(b.geometry().y()/scale+0.49));\n map.insert(\"cellWidth\",int(b.geometry().width()/scale+0.49));\n map.insert(\"cellHeight\",int(b.geometry().height()/scale+0.49));\n\n map.insert(\"PObject\",save(*(PObject*)(&b)));\n return map;\n}\nvoid load(QVariant v,POwlAnimation&b) {\n QVariantMap m = v.toMap();\n\n double scale;\n double w, h, x, y;\n\n w = m[\"cellWidth\"].toDouble();\n\n if (w>0) {\n scale = b.fontMetrics().height();\n w *= scale;\n h = m[\"cellHeight\"].toDouble() * scale;\n x = m[\"cellX\"].toDouble() * scale;\n y = m[\"cellY\"].toDouble() * scale;\n } else {\n scale = b.fontMetrics().height()/18.0;\n w = m[\"geometryWidth\"].toDouble() * scale;\n h = m[\"geometryHeight\"].toDouble() * scale;\n x = m[\"geometryX\"].toDouble() * scale;\n y = m[\"geometryY\"].toDouble() * scale;\n }\n\n b.setGeometry(QRect(x, y, w, h));\n\n load(m[\"PObject\"],*(PObject*)(&b));\n}\n\nQVariant save(PBox&b)\n{\n QVariantMap map;\n QVariantList dataItems;\n for(int i=0;i<b._dataItems.size();i++) {\n dataItems.push_back(save(*b._dataItems[i]));\n }\n\n double scale = b.fontMetrics().height()/18.0;\n\n map.insert(\"PObject\",save(*(PObject*)(&b)));\n map.insert(\"geometryX\",int(b.geometry().x()));\n map.insert(\"geometryY\",int(b.geometry().y()));\n map.insert(\"geometryWidth\",int(b.geometry().width()));\n map.insert(\"geometryHeight\",int(b.geometry().height())); //our wonderful json parser doesn't like parsing qrects\n\n // new geometry: in font-height cells\n scale = b.fontMetrics().height();\n map.insert(\"cellX\",int(b.geometry().x()/scale+0.49));\n map.insert(\"cellY\",int(b.geometry().y()/scale+0.49));\n map.insert(\"cellWidth\",int(b.geometry().width()/scale+0.49));\n map.insert(\"cellHeight\",int(b.geometry().height()/scale+0.49));\n\n map.insert(\"_boxTitle\",b._boxTitle);\n if(b._pstyle!=PStyle::noStyle) {\n map.insert(\"_style\",b._pstyle->idText());\n } else {\n map.insert(\"_style\",\"noStyle\");\n }\n map.insert(\"dataItems\", dataItems);\n return map;\n}\n\nvoid load(QVariant v,PBox&b)\n{\n QVariantMap m=v.toMap();\n\n double scale;\n double w, h, x, y;\n\n w = m[\"cellWidth\"].toDouble();\n\n if (w>0) {\n scale = b.fontMetrics().height();\n w *= scale;\n h = m[\"cellHeight\"].toDouble() * scale;\n x = m[\"cellX\"].toDouble() * scale;\n y = m[\"cellY\"].toDouble() * scale;\n } else {\n scale = b.fontMetrics().height()/18.0;\n w = m[\"geometryWidth\"].toDouble() * scale;\n h = m[\"geometryHeight\"].toDouble() * scale;\n x = m[\"geometryX\"].toDouble() * scale;\n y = m[\"geometryY\"].toDouble() * scale;\n }\n\n b.setGeometry(QRect(x, y, w, h));\n\n\n load(m[\"PObject\"],*(PObject*)(&b));\n\n b.setBoxTitle(m[\"_boxTitle\"].toString());\n\n QString idText=m[\"_style\"].toString();\n bool ok=0;\n for(int i=0;i<PStyle::_u.size();i++) {\n if(PStyle::_u[i]->idText()==idText) {\n ok=1;\n b._pstyle=PStyle::_u[i];\n break;\n }\n }\n if (!ok) {\n qDebug() << \"warning: box without style\";\n }\n\n QVariantList dataItems = m.value(\"dataItems\").toList();\n for(int i = 0; i < dataItems.length(); ++i) {\n PAbstractDataItem* padi=0;\n\n if(dataItems[i].toMap()[\"type\"]==\"PMDI\") {\n load(dataItems[i],*qobject_cast<PMultiDataItem*>(padi=new PMultiDataItem(&b,\"Loaded Item\")));\n } else if(dataItems[i].toMap()[\"type\"]==\"PBDI\") {\n load(dataItems[i],*qobject_cast<PBitMultiDataItem*>(padi=new PBitMultiDataItem(&b,\"Loaded Item\")));\n } else if(dataItems[i].toMap()[\"type\"]==\"PNDI\") {\n load(dataItems[i],*qobject_cast<PNumberDataItem*>(padi=new PNumberDataItem(&b,\"Loaded Item\")));\n } else if(dataItems[i].toMap()[\"type\"]==\"PTDI\") {\n load(dataItems[i],*qobject_cast<PTimeDataItem*>(padi=new PTimeDataItem(&b,\"Loaded Item\")));\n } else if(dataItems[i].toMap()[\"type\"]==\"PDDI\") {\n load(dataItems[i],*qobject_cast<PDirfileDataItem*>(padi=new PDirfileDataItem(&b,\"Loaded Item\")));\n } else {\n qFatal(\"Unsupported data type in .owl file. Aborting.\\n\");\n }\n PExtremaDataItem *pedi=dynamic_cast<PExtremaDataItem*>(padi);\n if (pedi)\n load(dataItems[i], *pedi);\n load(dataItems[i], *padi);\n b.addProperty(padi);\n }\n}\n\nQVariant save(PMainWindow&b)\n{\n QVariantMap root;\n QMap<int,bool> allExtremas;\n QVariantList styles;\n QVariantList uniqueExtremas;\n QVariantList owls;\n QVariantList boxes;\n\n for (int i=0;i<PStyle::_u.size();i++) {\n styles.push_back(save(*PStyle::_u[i]));\n }\n\n // There can be duplicate extremas, so filter them, and save\n // all the unique ones to uniqueExtremas\n for(int i=0;i<PExtrema::_u.size();i++) {\n if(!allExtremas.value(PExtrema::_u[i]->id(),0)) {\n allExtremas.insert(PExtrema::_u[i]->id(),1);\n uniqueExtremas.push_back(save(*PExtrema::_u[i]));\n }\n }\n\n for(int i=0;i<b._owlList.size();i++) {\n owls.push_back(save(*b._owlList[i]));\n }\n\n for(int i=0;i<b._pboxList.size();i++) {\n boxes.push_back(save(*b._pboxList[i]));\n }\n\n root.insert(\"OWL FILE rev.\",QString::number(LATEST_OWL_REVISION));\n root.insert(\"PObject\",save(*(PObject*)(&b))); // Add the root ID\n root.insert(\"linkSelected\", b._link);\n root.insert(\"linkNames\", b.linkNames());\n root.insert(\"windowWidth\", b.size().width());\n root.insert(\"windowHeight\", b.size().height());\n root.insert(\"windowCellWidth\", int(double(b.size().width())/double(b.fontMetrics().height())+0.49));\n root.insert(\"windowCellHeight\", b.size().height()/b.fontMetrics().height());\n root.insert(\"styles\", styles);\n root.insert(\"owls\", owls);\n root.insert(\"boxes\", boxes);\n root.insert(\"extremas\", uniqueExtremas);\n#if QT_VERSION >= 0x050300\n root.insert(\"webPort\", QString(b.webPort()));\n#else\n root.insert(\"webPort\", \"0\");\n#endif\n return root;\n}\n\nvoid load(QVariant v,PMainWindow&b)\n{\n PObject::isLoading=1;\n QVariantMap m=v.toMap();\n int rev = m[\"OWL FILE rev.\"].toInt();\n\n if(rev < OLDEST_SUPPORTED_OWL_REVISION) {\n QMessageBox::critical(0,\"Unsupported OWL File\",\"The OWL file you are \"\n \"trying to load is too old. Please open the transitional version of \"\n \"Owl 4 and save it in the new format.\",\n QMessageBox::Ok);\n qFatal(\"Unknown file version.\");\n } else if(rev > LATEST_OWL_REVISION) {\n QMessageBox::critical(0,\"Unsupported OWL File\",\"The OWL file you are \"\n \"trying to load is too new. Update your version of Owl.\",\n QMessageBox::Ok);\n qFatal(\"Unknown file version.\");\n }\n\n QVariantList styles = m.value(\"styles\").toList();\n QVariantList extremas = m.value(\"extremas\").toList();\n QVariantList owls = m.value(\"owls\").toList();\n QVariantList boxes = m.value(\"boxes\").toList();\n QVariant super = m.value(\"PObject\");\n QVariant link = m.value(\"linkSelected\");\n QStringList linkNames = m.value(\"linkNames\").toStringList();\n QVariant webPort = m.value(\"webPort\");\n\n int wW, wH;\n wW = m.value(\"windowCellWidth\").toInt() * b.fontMetrics().height();\n\n if (wW == 0) {\n wW = m.value(\"windowWidth\").toInt();\n wH = m.value(\"windowHeight\").toInt();\n } else {\n wH = m.value(\"windowCellHeight\").toInt() * b.fontMetrics().height();\n }\n\n b.setLink(link.toInt(), linkNames);\n\n b.resize(wW, wH);\n\n b._mdiArea->setFont(b.font());\n b._mdiArea->set_H(b._mdiArea->fontMetrics().height());\n for(int i = 0; i < styles.length(); ++i) {\n PStyle* nee=new PStyle(\"Loaded PStyle\");\n load(styles[i],*nee);\n }\n\n for(int i = 0; i < extremas.length(); ++i) {\n PExtrema* pee=new PExtrema;\n load(extremas[i],*pee);\n }\n\n load(super,*(PObject*)(&b));\n\n for(int i = 0; i < owls.length(); ++i) {\n POwlAnimation*oa=new POwlAnimation(b.fontMetrics().height());\n oa->setFont(b.font());\n\n load(owls[i],*oa);\n b._mdiArea->createOwl(0,0,oa);\n }\n\n for(int i = 0; i < boxes.length(); ++i) {\n PBox*pbox=new PBox(\"Loaded Box\", b.font());\n pbox->setFont(b.font());\n b._currentObject=pbox;\n load(boxes[i],*pbox);\n b._mdiArea->createPBox(0,0,pbox);\n QObject::connect(pbox,SIGNAL(activated()),&b,SLOT(uiLogic()));\n }\n\n for(int i=0;i<b._pboxList.count();i++) {\n for(int j=0;j<b._pboxList[i]->_dataItems.size();j++) {\n b.newLabelLogic(b._pboxList[i]->_dataItems[j]);\n }\n }\n\n for(int i=0;i<PExtrema::_u.size();i++) {\n b.recognizeExtrema(PExtrema::_u[i]);\n }\n\n#if QT_VERSION >= 0x050300\n b.setWebPort(webPort.isValid() ? webPort.toInt() : -1);\n#endif\n\n PObject::isLoading=0;\n}\n\n\n" }, { "alpha_fraction": 0.6756548285484314, "alphanum_fraction": 0.6904853582382202, "avg_line_length": 40.19841384887695, "blob_id": "99c97b92dc564e16f46f232b931bda26ab83f432", "content_id": "f6c8e21f155b69b59d4b375c95f4cef2ed7d25e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5193, "license_type": "no_license", "max_line_length": 115, "num_lines": 126, "path": "/stars/code/shared/solving/settings.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"settings.h\"\n#include <boost/algorithm/string.hpp>\n#include <boost/filesystem/operations.hpp>\n#include \"../../parameters/manager.h\"\n#include \"../../tools/angles.h\"\n\nusing namespace Shared::Solving;\n\nSettings::Settings()\n{\n enabled = true;\n abort_counter = 0;\n timeout = 30.0;\n\n snr_threshold = 1.0;\n max_num_blobs = 10;\n robust_mode_enabled = false;\n fitting_method = xC_solver_fitting_method_none;\n cell_size = 128;\n max_num_blobs_per_cell = 2;\n\n pattern_matcher_enabled = true;\n display_names = false;\n match_tolerance_px = 6.0;\n iplatescale_min = from_arcsec(9.45);\n iplatescale_max = from_arcsec(9.56);\n platescale_always_fixed = false;\n iplatescale_fixed = from_arcsec(9.5);\n\n debug_timing = false;\n catalog = \"catalogs/combo_9p0_8p0\";\n precession_epoch_source = precession_none;\n precession_manual_epoch = 2000.0;\n}\n\nvoid Settings::init(Parameters::Manager& params)\n{\n using std::string;\n\n enabled = params.general.try_get(\"solver.general.enabled\", true);\n timeout = params.general.try_get(\"solver.general.timeout\", 30.0);\n\n snr_threshold = params.general.try_get(\"solver.blob_finder.snr_threshold\", 1.0);\n max_num_blobs = params.general.try_get(\"solver.blob_finder.max_num_blobs\", 10);\n robust_mode_enabled = params.general.try_get(\"solver.blob_finder.robust_mode_enabled\", false);\n string fitting_str;\n fitting_str = params.general.try_get(\"solver.blob_finder.fitting_method\", string(\"none\"));\n boost::to_lower(fitting_str);\n fitting_method = xC_solver_fitting_method_none;\n if (fitting_str == \"gaussian\") {\n fitting_method = xC_solver_fitting_method_gaussian;\n }\n if (fitting_str == \"double_gaussian\") {\n fitting_method = xC_solver_fitting_method_double_gaussian;\n }\n cell_size = params.general.try_get(\"solver.blob_finder.cell_size\", (unsigned int) 128);\n max_num_blobs_per_cell = params.general.try_get(\"solver.blob_finder.max_num_blobs_per_cell\", (unsigned int) 2);\n\n pattern_matcher_enabled = params.general.try_get(\"solver.pattern_matcher.enabled\", true);\n display_names = params.general.try_get(\"solver.pattern_matcher.display_names\", false);\n match_tolerance_px = params.general.try_get(\"solver.pattern_matcher.match_tolerance_px\", 6.0);\n iplatescale_min = params.general.try_get(\"solver.pattern_matcher.iplatescale_min\", 9.45);\n iplatescale_min = from_arcsec(iplatescale_min);\n iplatescale_max = params.general.try_get(\"solver.pattern_matcher.iplatescale_max\", 9.45);\n iplatescale_max = from_arcsec(iplatescale_max);\n platescale_always_fixed = params.general.try_get(\"solver.pattern_matcher.platescale_always_fixed\", false);\n iplatescale_fixed = params.general.try_get(\"solver.pattern_matcher.iplatescale_fixed\", 9.45);\n iplatescale_fixed = from_arcsec(iplatescale_fixed);\n\n debug_timing = params.general.try_get(\"solver.general.debug_timing\", true);\n catalog = params.general.try_get(\"solver.pattern_matcher.catalog\", string(\"catalogs/combo_9p0_8p0\"));\n catalog = boost::filesystem::system_complete(params.stars_dir + catalog).string();\n\n string precession_from;\n precession_from = params.general.try_get(\"solver.pattern_matcher.precession_from\", string(\"none\"));\n boost::to_lower(precession_from);\n if (precession_from == \"system_time\") {\n precession_epoch_source = precession_system_time;\n } else if (precession_from == \"manual\") {\n precession_epoch_source = precession_manual;\n }\n precession_manual_epoch = params.general.try_get(\"solver.pattern_matcher.precession_manual_epoch\", 2000.0);\n\n refraction.enabled = params.general.try_get(\"solver.refraction.enabled\", false);\n refraction.pressure_mbar = params.general.try_get(\"solver.refraction.pressure_mbar\", 1013.25);\n refraction.temperature = params.general.try_get(\"solver.refraction.temperature\", 296.15);\n\n\n}\n\nSettings& Settings::operator=(const Settings &rhs)\n{\n if (this != &rhs) {\n enabled = rhs.enabled;\n abort_counter = rhs.abort_counter;\n timeout = rhs.timeout;\n\n snr_threshold = rhs.snr_threshold;\n max_num_blobs = rhs.max_num_blobs;\n robust_mode_enabled = rhs.robust_mode_enabled;\n fitting_method = rhs.fitting_method;\n cell_size = rhs.cell_size;\n max_num_blobs_per_cell = rhs.max_num_blobs_per_cell;\n\n pattern_matcher_enabled = rhs.pattern_matcher_enabled;\n display_names = rhs.display_names;\n match_tolerance_px = rhs.match_tolerance_px;\n iplatescale_min = rhs.iplatescale_min;\n iplatescale_max = rhs.iplatescale_max;\n platescale_always_fixed = rhs.platescale_always_fixed;\n iplatescale_fixed = rhs.iplatescale_fixed;\n\n debug_timing = rhs.debug_timing;\n catalog = rhs.catalog;\n precession_epoch_source = rhs.precession_epoch_source;\n precession_manual_epoch = rhs.precession_manual_epoch;\n refraction = rhs.refraction;\n }\n return *this;\n}\n\n" }, { "alpha_fraction": 0.7115384340286255, "alphanum_fraction": 0.7115384340286255, "avg_line_length": 19.799999237060547, "blob_id": "e9e5dcb976f6246bac8959d5b2136caec479b5c2", "content_id": "73613bf0c656d730eec540f87792c22ff866c992", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 104, "license_type": "no_license", "max_line_length": 41, "num_lines": 5, "path": "/external_libs/synclink/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "set(SYNCLINK_HEADERS\n ${SYNCLINK_HEADERS}\n ${CMAKE_CURRENT_SOURCE_DIR}/synclink.h\n PARENT_SCOPE\n)\n" }, { "alpha_fraction": 0.603190541267395, "alphanum_fraction": 0.6233266592025757, "avg_line_length": 27.322275161743164, "blob_id": "61a4e227428dfdafb82a0b93961ae960537281b3", "content_id": "ff59de54e80a253a01db06683ed9536f51fab8c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 17928, "license_type": "no_license", "max_line_length": 80, "num_lines": 633, "path": "/interloquendi/quendi.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* quendi.c: an implementation of the Quenya Protocol\n *\n * This software is copyright (C) 2004 University of Toronto\n * \n * quendi 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 2 of the License, or\n * (at your option) any later version.\n * \n * quendi 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 quendi; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <stdlib.h>\n\n#include <stdio.h>\n#include <string.h>\n#include <syslog.h>\n#include <unistd.h>\n#include <sys/select.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <fcntl.h>\n#include <tcpd.h>\n\n#include <sys/socket.h>\n\n#include <netinet/in.h>\n\n#include <arpa/inet.h>\n\n#include \"crc.h\"\n#include \"blast.h\"\n#include \"quendi.h\"\n#include \"quendiclient.h\"\n#include \"frameread.h\"\n\n/* upped from 50 to 200 to handle high latencies of rsyncing frame files */\n#define INPUT_BUF_SIZE 200 /* Frames are big (~1 kb) and we take a big\n * performance hit if we read more than 64k at a\n * time, so we keep this small */\n\n/* internals */\nstatic const char quendi_version[] = \"1.1\";\nstatic const struct quendi_server_data_t *quendi_server_data = NULL;\nstatic const struct quendi_data_port_t *quendi_data_port = NULL;\nstatic unsigned short* quendi_input_buffer[INPUT_BUF_SIZE];\nstatic unsigned quendi_frame_size;\n\n/* functions */\nint quendi_access_ok(int level) {\n if (quendi_server_data->access_level == 0) {\n quendi_respond(QUENYA_RESPONSE_NOT_IDENTIFIED, NULL);\n return 0;\n } else if (quendi_server_data->access_level < level) {\n quendi_respond(QUENYA_RESPONSE_NO_ACCESS, NULL);\n return 0;\n }\n\n return 1;\n}\n\nvoid quendi_add_data_port(const struct quendi_data_port_t* data_port)\n{\n quendi_data_port = data_port;\n}\n\nint quendi_cmdnum(char* buffer)\n{\n int i;\n\n /* command name to lower case */\n for (i = 0; i < 4; ++i)\n buffer[i] |= 0x20;\n\n switch(htonl(*(int*)buffer)) {\n case 0x61626f72: return QUENYA_COMMAND_ABOR;\n case 0x6173796e: return QUENYA_COMMAND_ASYN;\n case 0x636c6f73: return QUENYA_COMMAND_CLOS;\n case 0x636f6e74: return QUENYA_COMMAND_CONT;\n case 0x64617461: return QUENYA_COMMAND_DATA; \n case 0x6964656e: return QUENYA_COMMAND_IDEN;\n case 0x6e6f6f70: return QUENYA_COMMAND_NOOP;\n case 0x6f70656e: return QUENYA_COMMAND_OPEN;\n case 0x716e6f77: return QUENYA_COMMAND_QNOW;\n case 0x71756974: return QUENYA_COMMAND_QUIT;\n case 0x72647673: return QUENYA_COMMAND_RDVS;\n case 0x7274626b: return QUENYA_COMMAND_RTBK;\n case 0x73697a65: return QUENYA_COMMAND_SIZE;\n case 0x73706563: return QUENYA_COMMAND_SPEC;\n case 0x73796e63: return QUENYA_COMMAND_SYNC;\n }\n\n printf(\"cmd = %04x\\n\", htonl(*(int*)buffer));\n return -1;\n}\n\nint quendi_get_cmd(char* buffer)\n{\n int overrun;\n int eolfound;\n int n, i;\n fd_set sock_set;\n struct timeval timeout;\n int did_timeout;\n\n timeout.tv_sec = 60;\n timeout.tv_usec = 0;\n\n FD_ZERO(&sock_set);\n FD_SET(quendi_server_data->csock, &sock_set);\n if (quendi_data_port->sock >= 0)\n FD_SET(quendi_data_port->sock, &sock_set);\n\n i = quendi_server_data->csock;\n if (i < quendi_data_port->sock)\n i = quendi_data_port->sock;\n\n n = select(i + 1, &sock_set, NULL, NULL, &timeout);\n\n did_timeout = 1;\n if (quendi_data_port->sock > 0 &&\n FD_ISSET(quendi_data_port->sock, &sock_set)) {\n did_timeout = 0;\n n = read(quendi_data_port->sock, buffer, QUENDI_COMMAND_LENGTH);\n\n if (n == 0) {\n bprintf(warning, \"data port close\\n\");\n return -4;\n }\n }\n\n if (FD_ISSET(quendi_server_data->csock, &sock_set)) {\n did_timeout = 0;\n for (overrun = eolfound = 0; !eolfound; ) {\n n = read(quendi_server_data->csock, buffer, QUENDI_COMMAND_LENGTH);\n\n if (n == 0)\n return -2;\n\n eolfound = 0;\n /* check for buffer overrun */\n for (i = 0; i < QUENDI_COMMAND_LENGTH; ++i)\n if (buffer[i] == '\\n') {\n buffer[i] = '\\0';\n eolfound = 1;\n break;\n }\n\n if (!eolfound)\n overrun = 1;\n }\n\n if (overrun)\n quendi_respond(QUENYA_RESPONSE_SYNTAX_ERROR, \"Command Line too Long\");\n else if (i <= 4 || buffer[i - 1] != '\\r')\n quendi_respond(QUENYA_RESPONSE_SYNTAX_ERROR, NULL);\n else if (buffer[4] != ' ' && buffer[4] != '\\r') {\n printf(\"'%c' == %i\\n\", buffer[4], buffer[4]);\n quendi_respond(QUENYA_RESPONSE_SYNTAX_ERROR, NULL);\n } else {\n buffer[i - 1] = '\\0';\n printf(\"Got: %s\\n\", buffer);\n return 0;\n }\n }\n\n if (did_timeout)\n return -3;\n else \n return -1;\n}\n\nint quendi_get_next_param(char *buffer, int *nparams,\n char params[][QUENDI_COMMAND_LENGTH])\n{\n char* ptr = buffer;\n if (*ptr == '\\0')\n return 1;\n\n if (*++ptr == '\\0')\n return 1;\n\n strncpy(params[(*nparams)++], ptr, QUENDI_COMMAND_LENGTH);\n\n while (*ptr != '\\0' && *ptr != ' ')\n ++ptr;\n\n *ptr = '\\0';\n\n printf(\"Param %i: %s\\n\", *nparams - 1, params[*nparams - 1]);\n\n return 0;\n}\n\nint quendi_dp_open(void)\n{\n struct sockaddr_in addr;\n socklen_t addrlen;\n int dsock;\n\n addrlen = sizeof(addr);\n getsockname(quendi_server_data->csock, (struct sockaddr*)&addr, &addrlen);\n if ((dsock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)\n berror(warning, \"socket\");\n\n addr.sin_port = htons(0);\n if (bind(dsock, (struct sockaddr*)&addr, (socklen_t)sizeof(addr)) == -1)\n berror(warning, \"bind\");\n\n return dsock;\n}\n\nint quendi_dp_connect(void)\n{\n int dsock;\n int i;\n char buffer[QUENDI_RESPONSE_LENGTH];\n struct sockaddr_in addr;\n socklen_t addrlen;\n struct request_info req;\n fd_set sock_set;\n struct timeval timeout;\n\n dsock = quendi_dp_open();\n if (dsock < 1) {\n quendi_respond(QUENYA_RESPONSE_OPEN_ERROR, NULL);\n return -1;\n }\n\n addrlen = sizeof(addr);\n getsockname(dsock, (struct sockaddr*)&addr, &addrlen);\n snprintf(buffer, QUENDI_RESPONSE_LENGTH - 1,\n \"%i@%s:%i Listening on Port\", 1, inet_ntoa(addr.sin_addr),\n ntohs(addr.sin_port));\n quendi_respond(QUENYA_RESPONSE_LISTENING, buffer);\n\n if (listen(dsock, 1)) {\n syslog(LOG_WARNING, \"dp listen: %m\");\n return 0;\n }\n\n FD_ZERO(&sock_set);\n FD_SET(dsock, &sock_set);\n\n timeout.tv_sec = 60;\n timeout.tv_usec = 0;\n\n i = select(dsock + 1, &sock_set, NULL, NULL, &timeout);\n if (i == -1)\n syslog(LOG_WARNING, \"dp select: %m\");\n else if (FD_ISSET(dsock, &sock_set)) {\n i = accept(dsock, (struct sockaddr*)&addr, &addrlen);\n if (i == -1)\n syslog(LOG_WARNING, \"dp accept: %m\");\n } else {\n close(dsock);\n return -2; /* timeout */\n }\n\n if (i == -1) {\n close(dsock);\n return -1; /* select or accept error */\n }\n\n /* tcp wrapper check */\n request_init(&req, RQ_DAEMON, quendi_server_data->server_name, RQ_FILE,\n quendi_server_data->csock, 0);\n fromhost(&req);\n\n if (!hosts_access(&req)) {\n close(dsock);\n return -3; /* host access error */\n }\n\n close(dsock);\n return i;\n}\n\nint quendi_rp_connect(const char* host)\n{\n int rsock;\n struct sockaddr_in addr;\n\n rsock = MakeSock();\n\n if (ResolveHost(host, &addr, 0) != NULL)\n return -2;\n\n if (connect(rsock, (struct sockaddr*)&addr, sizeof(addr)) != 0)\n return -1;\n\n return rsock;\n}\n\nchar* quendi_make_response(char* buffer, int response_num, const char* message)\n{\n int size;\n\n if (message)\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH, \"%i %s\\r\\n\", response_num,\n message);\n else\n switch (response_num) {\n case QUENYA_RESPONSE_LISTENING: /* 123 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Listening on Data Port for Connection\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_SENDING_DATA: /* 152 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Sending Data\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_SENDING_SPEC: /* 153 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Sending Spec File\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_OK: /* 200 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH, \"%i OK\\r\\n\",\n response_num);\n break;\n case QUENYA_RESPONSE_DATA_STAGED: /* 211 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Data Staged\\r\\n\", response_num);\n break; \n case QUENYA_RESPONSE_SERVICE_READY: /* 220 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i %s %s %s/%s Service Ready\\r\\n\", response_num,\n quendi_server_data->server_host, quendi_server_data->server_name,\n quendi_server_data->server_version, quendi_version);\n break;\n case QUENYA_RESPONSE_GOODBYE: /* 221 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i %s Closing Connection\\r\\n\", response_num,\n quendi_server_data->server_host);\n break;\n case QUENYA_RESPONSE_PORT_OPENED: /* 223 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Data Port Opened\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_ACCESS_GRANTED: /* 230 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Access Granted\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_FRAME_SIZE: /* 242 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i %u Frame Bytes\\r\\n\", response_num, quendi_frame_size);\n break;\n case QUENYA_RESPONSE_TRANS_COMPLETE: /* 250 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Data Transfer Complete\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_BLOCK_CRC: /* 316 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i 0x0000 Chunk CRC\\r\\n\", response_num);\n break; \n case QUENYA_RESPONSE_OPEN_ERROR: /* 423 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Error Opening Data Port\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_NO_CUR_DATA: /* 451 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i No Current Data Writer\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_SYNTAX_ERROR: /* 500 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH, \"%i Syntax Error\\r\\n\",\n response_num);\n break;\n case QUENYA_RESPONSE_PARAM_ERROR: /* 501 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Parameter Error\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_CMD_NOT_IMPL: /* 502 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Command Not Implemented\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_PORT_INACTIVE: /* 503 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Invalid Command: Data Port Not Active\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_PORT_NOT_OPEN: /* 523 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Data Port Not Open\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_PORT_ACTIVE: /* 524 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Data Port Already Active. Send ABOR First.\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_NOT_IDENTIFIED: /* 530 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Client Not Identified\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_NO_ACCESS: /* 531 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Insufficient Privilege\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_NO_DATA_STAGED: /* 551 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i No Data Staged\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_TIMEOUT: /* 621 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Timeout Waiting for Command\\r\\n\", response_num);\n break;\n case QUENYA_RESPONSE_PORT_CLOSE_ERR: /* 623 */\n size = snprintf(buffer, QUENDI_RESPONSE_LENGTH,\n \"%i Data Port Closed\\r\\n\", response_num);\n break;\n default:\n return NULL;\n } \n\n if (size <= 0 || size > QUENDI_RESPONSE_LENGTH)\n return NULL;\n\n return buffer;\n}\n\nint quendi_parse(char *buffer, int *nparams,\n char params[][QUENDI_COMMAND_LENGTH])\n{\n int cmd = quendi_cmdnum(buffer);\n\n *nparams = 0;\n\n switch(cmd) {\n case QUENYA_COMMAND_IDEN:\n case QUENYA_COMMAND_RDVS:\n if (quendi_get_next_param(buffer + 4, nparams, params))\n return -2;\n break;\n }\n\n return cmd;\n}\n\nunsigned long quendi_reader_init(unsigned frame_size, unsigned long pos,\n char* chunk, const char* name, int sufflen)\n{\n int i;\n\n strcpy(chunk, name);\n\n quendi_input_buffer[0] = (unsigned short*)balloc(fatal,\n frame_size * INPUT_BUF_SIZE);\n\n for (i = 1; i < INPUT_BUF_SIZE; ++i)\n quendi_input_buffer[i] = (void*)quendi_input_buffer[0] + i * frame_size;\n\n return SetStartChunk(pos, chunk, sufflen) * frame_size;\n}\n\nint quendi_respond(int response_num, const char *message)\n{\n char buffer[QUENDI_RESPONSE_LENGTH + 1];\n\n if (quendi_make_response(buffer, response_num, message) == NULL)\n return -1;\n\n send(quendi_server_data->csock, buffer, strlen(buffer), MSG_DONTWAIT);\n printf(\"Replied: %s\", buffer);\n\n return 0;\n}\n\nint quendi_read_data(int new_chunk, int* fd, const char* chunk,\n unsigned long seek_to, int *chunk_total, unsigned frame_size,\n unsigned long *frames_read, unsigned *remainder)\n{\n int n, block_size;\n struct stat chunk_stat;\n\n if (new_chunk) {\n printf(\"New chunk ok\\n\");\n if ((*fd = open(chunk, O_RDONLY)) < 0)\n berror(fatal, \"cannot open `%s'\", chunk);\n\n printf(\"New chunk fopen ok\\n\");\n if (seek_to > 0) {\n lseek(*fd, seek_to, SEEK_SET);\n seek_to = 0;\n printf(\"New chunk fseek ok\\n\");\n }\n\n if (stat(chunk, &chunk_stat))\n berror(fatal, \"cannot stat `%s'\", chunk);\n\n *chunk_total = chunk_stat.st_size / frame_size;\n printf(\"New chunk stat ok (%i)\\n\", *chunk_total);\n\n }\n\n if ((n = read(*fd, (void*)quendi_input_buffer[0] + *remainder, frame_size *\n INPUT_BUF_SIZE - *remainder)) < 1) {\n if (n == 0)\n return 0;\n else {\n berror(err, \"error reading `%s'\", chunk);\n\n close(*fd);\n if ((*fd = open(chunk, O_RDONLY)) < 0)\n berror(fatal, \"cannot open `%s'\", chunk);\n\n lseek(*fd, *frames_read * frame_size, SEEK_SET);\n n = 0;\n }\n }\n\n block_size = (*remainder + n) / frame_size;\n *remainder = (*remainder + n) % frame_size;\n *frames_read += block_size;\n\n return block_size;\n}\n\nvoid quendi_send_data(int dsock, unsigned frame_size, int block_size)\n{\n int i;\n char buffer[100];\n unsigned short crc;\n\n if (block_size > 0) {\n snprintf(buffer, 100, \"%i Frame Block Transfer Starting\", block_size);\n quendi_respond(QUENYA_RESPONSE_SENDING_DATA, buffer);\n\n for (i = 0; i < block_size; ++i) {\n if (write(dsock, quendi_input_buffer[i], frame_size) < 0)\n\tberror(err, \"failed to write to socket\");\n }\n\n crc = CalculateCRC(CRC_SEED, quendi_input_buffer[0],\n frame_size * block_size);\n\n sprintf(buffer, \"0x%04X Block CRC\", crc);\n quendi_respond(QUENYA_RESPONSE_BLOCK_CRC, buffer);\n }\n\n return;\n}\n\nint quendi_advance_data(int persist, char* chunk, int sufflen, int *chunk_total,\n const char* curfile_name, char* curfile_val, int block_size,\n unsigned remainder)\n{\n if (block_size > 0 && remainder > 0)\n memcpy(quendi_input_buffer[0], quendi_input_buffer[block_size + 1],\n remainder);\n\n return StreamToNextChunk(persist, chunk, sufflen, chunk_total, curfile_name,\n curfile_val);\n}\n\nvoid quendi_reader_shutdown(int fd, int flag)\n{\n bfree(fatal, quendi_input_buffer[0]);\n\n close(fd);\n\n if (flag)\n quendi_respond(QUENYA_RESPONSE_TRANS_COMPLETE, NULL);\n}\n\nvoid quendi_send_spec(int dsock, const char* name)\n{\n char spec_file[200];\n char buffer[100];\n unsigned length;\n void *spec;\n struct stat stat_buf;\n int fd;\n\n GetSpecFile(spec_file, name, NULL);\n\n if (stat(spec_file, &stat_buf))\n berror(fatal, \"cannot stat spec file `%s'\", spec_file);\n\n length = stat_buf.st_size;\n\n if ((fd = open(spec_file, O_RDONLY)) < 0)\n berror(fatal, \"cannot open spec file `%s'\", spec_file);\n\n snprintf(buffer, 100, \"%i Sending Spec File\", length);\n quendi_respond(QUENYA_RESPONSE_SENDING_SPEC, buffer);\n\n spec = balloc(fatal, length);\n\n if (read(fd, spec, length) < 0)\n berror(err, \"failed to read from spec file\");\n if (write(dsock, spec, length) < 0)\n berror(err, \"failed to write to spec file\");\n\n close(fd);\n bfree(fatal, spec);\n\n quendi_respond(QUENYA_RESPONSE_TRANS_COMPLETE, NULL);\n}\n\nvoid quendi_server_init(const struct quendi_server_data_t* server_data)\n{\n quendi_server_data = server_data;\n quendi_respond(QUENYA_RESPONSE_SERVICE_READY, NULL);\n}\n\nvoid quendi_server_shutdown(void)\n{\n}\n\nint quendi_stage_data(const char* file, unsigned long pos, int sufflen,\n int streamed_here, unsigned frame_size)\n{\n char buffer[NAME_MAX + 60];\n char source[NAME_MAX];\n\n quendi_frame_size = frame_size;\n\n PathSplit_r(file, NULL, buffer);\n StaticSourcePart(source, buffer, NULL, sufflen);\n if (streamed_here) {\n snprintf(buffer, NAME_MAX + 60, \"%lu:%s Data Continues: New Data Staged\",\n pos, source);\n quendi_respond(QUENYA_RESPONSE_STAGED_NEXT, buffer);\n } else {\n snprintf(buffer, NAME_MAX + 60, \"%lu:%s Data Staged\", pos, source);\n quendi_respond(QUENYA_RESPONSE_DATA_STAGED, buffer);\n }\n return 1;\n}\n" }, { "alpha_fraction": 0.6993622183799744, "alphanum_fraction": 0.701561450958252, "avg_line_length": 34.5234375, "blob_id": "5277236d3428311d09082b440271ab072ad7091a", "content_id": "f77187814ced666379ef35702fa9a5b7d9b1348a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 4547, "license_type": "no_license", "max_line_length": 141, "num_lines": 128, "path": "/groundhog/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "# Helper function to add preprocesor definition of FILE_BASENAME\n# to pass the filename without directory path for debugging use.\n#\n# Example:\n#\n# define_file_basename_for_sources(my_target)\n#\n# Will add -DFILE_BASENAME=\"filename\" for each source file depended on\n# by my_target, where filename is the name of the file.\n#\nfunction(define_file_basename_for_sources targetname)\n get_target_property(source_files \"${targetname}\" SOURCES)\n foreach(sourcefile ${source_files})\n # Get source file's current list of compile definitions.\n get_property(defs SOURCE \"${sourcefile}\"\n PROPERTY COMPILE_DEFINITIONS)\n # Add the FILE_BASENAME=filename compile definition to the list.\n get_filename_component(basename \"${sourcefile}\" NAME)\n list(APPEND defs \"__FILENAME__=\\\"${basename}\\\"\")\n # Set the updated compile definitions on the source file.\n set_property(\n SOURCE \"${sourcefile}\"\n PROPERTY COMPILE_DEFINITIONS ${defs})\n endforeach()\nendfunction()\n\nproject (groundhog)\n\ncmake_minimum_required (VERSION 2.8.8)\n\noption(USE_CLANG \"build groundhog using clang\" OFF)\n\nif (USE_CLANG)\n SET (CMAKE_C_COMPILER \"/usr/bin/clang\")\n SET (CMAKE_CXX_COMPILER \"/usr/bin/clang++\")\nendif(USE_CLANG)\n\nSET (CMAKE_C_FLAGS \"-Wall -std=gnu99\")\nSET (CMAKE_C_FLAGS_DEBUG \"-g\")\nSET (CMAKE_C_FLAGS_MINSIZEREL \"-Os -DNDEBUG\")\nSET (CMAKE_C_FLAGS_RELEASE \"-O3 -DNDEBUG\")\nSET (CMAKE_C_FLAGS_RELWITHDEBINFO \"-O2 -g\")\n\nSET (CMAKE_CXX_FLAGS \"-Wall\")\nSET (CMAKE_CXX_FLAGS_DEBUG \"-g\")\nSET (CMAKE_CXX_FLAGS_MINSIZEREL \"-Os -DNDEBUG\")\nSET (CMAKE_CXX_FLAGS_RELEASE \"-O3 -DNDEBUG\")\nSET (CMAKE_CXX_FLAGS_RELWITHDEBINFO \"-O2 -g\") \n\n# Set global definitions\nadd_definitions(-D_GNU_SOURCE)\n\n# Find external libs\nfind_package(PkgConfig)\n\n# Find Threading lib\nfind_package (Threads)\n\n# Find ExternalProject module\ninclude (ExternalProject)\n\nfind_path(BLAST_CONFIG NAMES tx_struct_tng.c\n HINTS ${PROJECT_SOURCE_DIR}/../blast_config REQUIRED)\nIF(BLAST_CONFIG)\n\t\tmessage(\"Have blast_config\")\n set(MAKE_BLAST True)\n add_definitions(-DMAKE_BLAST)\n include(${PROJECT_SOURCE_DIR}/blast/CMakeLists.txt)\nENDIF()\n\nfind_path(BIT_CONFIG NAMES telemlist.bit\n HINTS ${PROJECT_SOURCE_DIR}/../bit_config REQUIRED)\nIF(BIT_CONFIG)\n\t\tmessage(\"Have bit_config\")\n set(MAKE_BIT True)\n add_definitions(-DMAKE_BIT)\n include(${PROJECT_SOURCE_DIR}/bit/CMakeLists.txt)\n include(${PROJECT_SOURCE_DIR}/../common/CMakeLists.txt)\nENDIF()\n\n\n# Find getdata \npkg_check_modules(PC_GD QUIET getdata)\n\nfind_path(GD_INCLUDE_DIR NAMES getdata.h\n HINTS ${PC_GD_INCLUDEDIR} ${PC_GD_INCLUDE_DIRS} REQUIRED)\nfind_library(GD_LIBRARY NAMES getdata\n HINTS ${PC_GD_LIBDIR} ${PC_GD_LIBRARY_DIRS} REQUIRED)\nIF(NOT GD_INCLUDE_DIR)\n MESSAGE(FATAL_ERROR \"Did not find getdata.h. Is libgetdata-dev installed?\")\nENDIF()\nIF(NOT GD_LIBRARY) \n MESSAGE(FATAL_ERROR \"Did not find libgetdata. Is libgetdata4 installed?\")\nENDIF()\ninclude_directories(${GD_INCLUDE_DIR})\n\nset(LIBLINKLIST_DIR \"${PROJECT_SOURCE_DIR}/../liblinklist\")\n\n# add machine directory for OSX builds (needs endian.h)\ninclude_directories (\"/usr/include/machine\")\n# add the binary tree to the search path for include files so that we will find decomd_config.h\ninclude_directories (\n \"${LIBLINKLIST_DIR}\"\n \"${PROJECT_BINARY_DIR}/include\"\n \"${PROJECT_SOURCE_DIR}\"\n )\n\n# add common linklist objects\nadd_subdirectory(${LIBLINKLIST_DIR} \"${PROJECT_BINARY_DIR}/liblinklist\")\nadd_library (liblinklist OBJECT ${LL_SOURCES} ${LL_HEADERS})\ndefine_file_basename_for_sources(liblinklist)\nset(COMMON_OBJECTS\n $<TARGET_OBJECTS:liblinklist>\n ${PROJECT_SOURCE_DIR}/groundhog_funcs.c\n ${PROJECT_SOURCE_DIR}/groundhog_funcs.h\n )\n\n\nIF(NOT MAKE_BLAST AND NOT MAKE_BIT)\n\t\tmessage(\"No _config directories found. No executable compiled.\")\nENDIF()\n\ninstall(DIRECTORY DESTINATION \"/data/rawdir\"\n DIRECTORY_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_WRITE GROUP_EXECUTE WORLD_READ WORLD_WRITE WORLD_EXECUTE)\ninstall(DIRECTORY DESTINATION \"/data/groundhog\"\n DIRECTORY_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_WRITE GROUP_EXECUTE WORLD_READ WORLD_WRITE WORLD_EXECUTE)\ninstall(DIRECTORY DESTINATION \"/data/etc\"\n DIRECTORY_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_WRITE GROUP_EXECUTE WORLD_READ WORLD_WRITE WORLD_EXECUTE)\n" }, { "alpha_fraction": 0.6036258935928345, "alphanum_fraction": 0.6530696153640747, "avg_line_length": 23.01980209350586, "blob_id": "e5582d49845eac78020119690b2d86a347e6b6a1", "content_id": "8ad6f815fd837d970488c121caf382e97598f702", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2428, "license_type": "no_license", "max_line_length": 123, "num_lines": 101, "path": "/stars/code/tools/angles.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"angles.h\"\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include \"slalib.h\"\n\ndouble from_hours(double angle)\n{\n return angle*M_PI/12.;\n}\n\ndouble to_hours(double angle)\n{\n return angle*12./M_PI;\n}\n\ndouble from_degrees(double angle)\n{\n return angle*M_PI/180.;\n}\n\ndouble to_degrees(double angle)\n{\n return angle*180./M_PI;\n}\n\ndouble from_arcmin(double angle)\n{\n return (angle/60.)*M_PI/180.;\n}\n\ndouble to_arcmin(double angle)\n{\n return angle*(180./M_PI)*60.;\n}\n\ndouble from_arcsec(double angle)\n{\n return (angle/3600.)*M_PI/180.;\n}\n\ndouble to_arcsec(double angle)\n{\n return angle*(180./M_PI)*3600.;\n}\n\ndouble great_circle(double ra0, double dec0, double ra1, double dec1)\n{\n double delta_ra = ra1 - ra0;\n double y = sqrt(pow(cos(dec1)*sin(delta_ra), 2.0) + pow(cos(dec0)*sin(dec1) - sin(dec0)*cos(dec1)*cos(delta_ra), 2.0));\n double x = sin(dec0)*sin(dec1) + cos(dec0)*cos(dec1)*cos(delta_ra);\n return atan2(y, x);\n}\n\nbool angles_within_basic(double ra0, double dec0, double ra1, double dec1, double distance)\n{\n double true_distance = great_circle(ra0, dec0, ra1, dec1);\n if (true_distance >= distance) {\n return false;\n }\n return true;\n}\n\nbool angles_within(double ra0, double dec0, double ra1, double dec1, double distance)\n{\n if (fabs(dec0 - dec1) >= distance) {\n return false;\n }\n return angles_within_basic(ra0, dec0, ra1, dec1, distance);\n}\n\ndouble tanplane_distance(double x0, double y0, double x1, double y1, double iplatescale)\n{\n double ra0 = 0.0;\n double dec0 = 0.0;\n double ra1 = 0.0;\n double dec1 = 0.0;\n double distance = 0.0;\n Slalib::slaDtp2s(x0*iplatescale, y0*iplatescale, 0.0, 0.0, &ra0, &dec0);\n Slalib::slaDtp2s(x1*iplatescale, y1*iplatescale, 0.0, 0.0, &ra1, &dec1);\n distance = great_circle(ra0, dec0, ra1, dec1);\n return distance;\n}\n\nvoid equatorial_to_horizontal(double ra, double dec, double lat, double lst, double &az, double &el)\n{\n double ha = lst - ra;\n Slalib::slaDe2h(ha, dec, lat, &az, &el);\n}\n\nvoid horizontal_to_equatorial(double az, double el, double lat, double lst, double& ra, double& dec)\n{\n double ha = 0.0;\n Slalib::slaDh2e(az, el, lat, &ha, &dec);\n ra = lst - ha;\n}\n\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.7080000042915344, "avg_line_length": 19, "blob_id": "ccb626713544ab609f551980bd36d8cd9e1f8195", "content_id": "6aab0a3a8c09bae11ffb021de87e9fe7c91b6f23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 501, "license_type": "no_license", "max_line_length": 75, "num_lines": 25, "path": "/stars/code/tools/psf.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#ifndef TOOLS__PSF_H\n#define TOOLS__PSF_H\n\n#include <vector>\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nnamespace Tools\n{\n namespace PSF\n {\n\nvoid get_kernel_separated_gauss(double *gauss, int halfwidth, double size);\ndouble gaussian(double A, double sigma, double x, double y);\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.6642441749572754, "alphanum_fraction": 0.6774709224700928, "avg_line_length": 27.192623138427734, "blob_id": "a1b7b5b72ff09f624b72c4473558a14328df198b", "content_id": "004abf397f5f68599360dc44e7e3798e0f24078e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6880, "license_type": "no_license", "max_line_length": 97, "num_lines": 244, "path": "/test_programs/synclink/send-raw.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * send raw serial data\n *\n * This sample demonstrates raw serial communications using a\n * SyncLink serial card. The companion sample receive-raw.c receives\n * raw serial data. Use both programs to send data between two serial cards\n * connected with a NULL modem (cross over cable) or other serial link.\n *\n * The sample is simple to clearly show basic programming concepts.\n * Use this code to start development of more complex applications.\n *\n * Overview:\n *\n * 1. open serial device (syscall open)\n * 2. configure serial device (syscall ioctl)\n * 3. send data to serial device (syscall write)\n *\n * For more information about SyncLink specific programming refer to\n * the Programming.txt file included with the SyncLink software package.\n *\n * Microgate and SyncLink are registered trademarks\n * of Microgate corporation.\n *\n * This code is released under the GNU General Public License (GPL)\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <stdio.h>\n#include <memory.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <sys/ioctl.h>\n#include <linux/types.h>\n#include <termios.h>\n#include <errno.h>\n#include <sys/time.h>\n\n#include \"synclink.h\"\n\n#ifndef N_HDLC\n#define N_HDLC 13\n#endif\n\n/*\n * set base clock frequency in cycles per second\n *\n * Data clocks are generated by dividing a fixed base clock by a 16-bit integer.\n * GT family base clock default is 14745600 (14.7456MHz)\n *\n * Other base clocks (up to 33MHz) can be installed\n * at the factory by special order. Non default values require driver\n * configuration with the actual value so correct divisors are used for\n * a specified data rate.\n */\nint set_base_clock(int fd, unsigned int freq)\n{\n\tMGSL_PARAMS params;\n\tint rc;\n\n\t/* fields other than mode and clock_speed are ignored */\n\tparams.mode = MGSL_MODE_BASE_CLOCK;\n\tparams.clock_speed = freq;\n\trc = ioctl(fd, MGSL_IOCSPARAMS, &params);\n\tif (rc < 0) {\n\t\tprintf(\"set base clock frequency error=%d %s\\n\",\n\t\t errno, strerror(errno));\n\t}\n\treturn rc;\n}\n\nint main(int argc, char* argv[])\n{\n\tint fd;\n\tint rc;\n\tint sigs, idle;\n\tint ldisc = N_HDLC;\n\tMGSL_PARAMS params;\n\tint size = 1024;\n\tunsigned char buf[1024];\n\tchar *devname;\n\tstruct timeval begin, end;\n\n\tif (argc > 1)\n\t\tdevname = argv[1];\n\telse\n\t\tdevname = \"/dev/ttyUSB0\";\n\n\tprintf(\"send raw serial data on %s\\n\", devname);\n\n\t/* open serial device with O_NONBLOCK to ignore DCD input */\n\tfd = open(devname, O_RDWR | O_NONBLOCK, 0);\n\tif (fd < 0) {\n\t\tprintf(\"open error=%d %s\\n\", errno, strerror(errno));\n\t\treturn fd;\n\t}\n\tclose(fd);\n\tfd = open(devname, O_RDWR | O_NONBLOCK, 0);\n\tif (fd < 0) {\n\t\tprintf(\"open error=%d %s\\n\", errno, strerror(errno));\n\t\treturn fd;\n\t}\n\n\t/*\n\t * set N_HDLC line discipline (used for synchronous modes)\n\t *\n\t * A line discipline is a software layer between a tty device driver\n\t * and user application that performs intermediate processing,\n\t * formatting, and buffering of data.\n\t */\n\t/*\n\trc = ioctl(fd, TIOCSETD, &ldisc);\n\tif(rc < 0) {\n\t\tprintf(\"set line discipline error=%d %s\\n\",\n\t\t errno, strerror(errno));\n\t\treturn rc;\n\t}\n\t*/\n\n\t/* required only if custom base clock (not 14745600) installed */\n//\tif (set_base_clock(fd, 32000000) < 0)\n//\t\treturn rc;\n\n\t/* get current device parameters */\n\trc = ioctl(fd, MGSL_IOCGPARAMS, &params);\n\tif (rc < 0) {\n\t\tprintf(\"ioctl(MGSL_IOCGPARAMS) error=%d %s\\n\",\n\t\t errno, strerror(errno));\n\t\treturn rc;\n\t}\n\n\t/*\n\t * modify device parameters\n\t *\n\t * raw synchronous mode, loopback disabled, NRZ encoding\n\t * data clocks sourced from clock input pins\n\t * output 9600bps clock on auxclk output pin\n\t * disable hardware CRC generation/checking\n\t */\n\n\tparams.mode = MGSL_MODE_RAW;\n\tparams.loopback = 0;\n\tparams.flags = HDLC_FLAG_RXC_BRG + HDLC_FLAG_TXC_BRG;\n\t// params.encoding = HDLC_ENCODING_NRZ;\n\tparams.encoding = HDLC_ENCODING_BIPHASE_LEVEL;\n\tparams.clock_speed = 100000;\n\tparams.crc_type = HDLC_CRC_NONE;\n\n\t/* set current device parameters */\n\trc = ioctl(fd, MGSL_IOCSPARAMS, &params);\n\tif (rc < 0) {\n\t\tprintf(\"ioctl(MGSL_IOCSPARAMS) error=%d %s\\n\",\n\t\t errno, strerror(errno));\n\t\treturn rc;\n\t}\n\n\t// /* set transmit idle pattern (sent when no send data available) */\n\t// idle = HDLC_TXIDLE_ONES;\n\t// rc = ioctl(fd, MGSL_IOCSTXIDLE, idle);\n\t// if (rc < 0) {\n\t//\tprintf(\"ioctl(MGSL_IOCSTXIDLE) error=%d %s\\n\",\n\t//\t errno, strerror(errno));\n\t//\treturn rc;\n\t//}\n\n\t/* initialize send buffer to all zeros */\n\tmemset(buf, 0, size);\n\n\t/* set device to blocking mode for reads and writes */\n\tfcntl(fd, F_SETFL, fcntl(fd,F_GETFL) & ~O_NONBLOCK);\n\n\tprintf(\"Turn on RTS and DTR serial outputs\\n\");\n\tsigs = TIOCM_RTS + TIOCM_DTR;\n\trc = ioctl(fd, TIOCMBIS, &sigs);\n\tif(rc < 0) {\n\t\tprintf(\"assert DTR/RTS error=%d %s\\n\", errno, strerror(errno));\n\t\treturn rc;\n\t}\n\n\twhile (1) {\n\n\t\t/*\n\t\t * idle pattern is all 1s and data is all 0s to allow easy\n\t\t * inspection of data received on remote card. Because raw serial mode\n\t\t * has no synchronization, received data may appear bit shifted.\n\t\t */\n\t\tgettimeofday(&begin, NULL);\n\t\tprintf(\"Sending %d bytes\\n\", size);\n\t\trc = write(fd, buf, size);\n\t\tif (rc < 0) {\n\t\t\tprintf(\"write error=%d %s\\n\", errno, strerror(errno));\n\t\t\treturn rc;\n\t\t}\n\n\t\tprintf(\"wait for all data sent...\\n\");\n\t\t/* chose method to wait for all data sent: blocked or polling */\n\t#if 1\n\t\t/* block until all data sent */\n\t\trc = tcdrain(fd);\n\t\tgettimeofday(&end, NULL);\n\t#else\n\t\t/* poll until all data sent */\n\t\tdo {\n\t\t\trc = ioctl(fd, TIOCOUTQ, &size);\n\t\t\tif (rc < 0) {\n\t\t\t\tprintf(\"ioctl(TIOCOUTQ) error=%d %s\\n\",\n\t\t\t\t errno, strerror(errno));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} while (size);\n\t#endif\n\t\tprintf(\"all data sent\\n\");\n\t\tprintf(\"It took %f second to write %d bytes\\n\", (end.tv_usec - begin.tv_usec)/1000000.0, size);\n\n\t\t/*\n\t\t * Delay to allow sending of idle pattern and\n\t\t * keep auxclk clock output active for 2 seconds to give remote receiver\n\t\t * extra clock cycles for internal processing of received data.\n\t\t * If an external device supplies data clocks, this is not needed.\n\t\t */\n\t\tsleep(2);\n\n\t\tprintf(\"Turn off RTS and DTR\\n\");\n\t\tsigs = TIOCM_RTS + TIOCM_DTR;\n\t\trc = ioctl(fd, TIOCMBIC, &sigs);\n\t\tif (rc < 0) {\n\t\t\tprintf(\"negate DTR/RTS error=%d %s\\n\", errno, strerror(errno));\n\t\t\treturn rc;\n\t\t}\n\t}\n\n\tclose(fd);\n\n\treturn 0;\n}\n\n" }, { "alpha_fraction": 0.6913580298423767, "alphanum_fraction": 0.6975308656692505, "avg_line_length": 17.514286041259766, "blob_id": "8649ba58572dd7787879fd342fbcf41e7a3ea96a", "content_id": "7ab5d36c69635839a6d8383eb4beeeccf901b4c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 649, "license_type": "no_license", "max_line_length": 73, "num_lines": 35, "path": "/stars/code/shared/autofocus/latest_image.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__AUTOFOCUS__LATEST_IMAGE_H\n#define SHARED__AUTOFOCUS__LATEST_IMAGE_H\n\n#include \"../circular_buffer.h\"\n#include \"../../tools/timing.h\"\n\nnamespace Shared\n{\n namespace Autofocus\n {\n\nclass LatestImage\n{\n public:\n LatestImage();\n LatestImage& operator=(const LatestImage& rhs);\n\n int counter_stars;\n};\n\n// writes: camera\n// reads: lens\nextern Shared::CircularBuffer <LatestImage> latest_image;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.578012228012085, "alphanum_fraction": 0.5946696400642395, "avg_line_length": 20.698795318603516, "blob_id": "787b917e45658b08563e283785331dd540b53d77", "content_id": "487eabbaa88c875938adb92fea27e98dde53233d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1802, "license_type": "no_license", "max_line_length": 73, "num_lines": 83, "path": "/stars/code/tools/stats.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef TOOLS__STATS_H\n#define TOOLS__STATS_H\n\n#include <cmath>\n#include <vector>\n\ntemplate <typename T>\ndouble get_mean(std::vector<T>& values)\n{\n if (values.size() < 1) {\n return 0.0;\n }\n double total = 0;\n for (unsigned int i=0; i<values.size(); i++) {\n total += values[i];\n }\n return total/double(values.size());\n}\n\ntemplate <typename T>\ndouble get_mean(T values[], int num_values)\n{\n if (num_values < 1) {\n return 0.0;\n }\n double total = 0;\n for (int i=0; i<num_values; i++) {\n total += values[i];\n }\n return total/double(num_values);\n}\n\ntemplate <typename T>\ndouble get_sample_stdev(std::vector<T>& values, double& mean)\n{\n if (values.size() < 2) {\n return 1.0;\n }\n double s = 0;\n for (unsigned int i=0; i<values.size(); i++) {\n s += pow(double(values[i])-mean, 2);\n }\n s = s / (double(values.size()) - 1.0);\n return sqrt(s);\n}\n\ntemplate <typename T>\ndouble get_sample_stdev(T values[], int num_values, double& mean)\n{\n if (num_values < 2) {\n return 1.0;\n }\n double s = 0;\n for (int i=0; i<num_values; i++) {\n s += pow(double(values[i])-mean, 2);\n }\n s = s / (double(num_values) - 1.0);\n return sqrt(s);\n}\n\ntemplate <typename T>\ndouble get_sample_stdev(std::vector<T>& values)\n{\n double mean = get_mean(values);\n return get_sample_stdev(values, mean);\n}\n\ntemplate <typename T>\ndouble get_sample_stdev(T values[], int num_values)\n{\n double mean = get_mean(values, num_values);\n return get_sample_stdev(values, num_values, mean);\n}\n\n\n#endif\n" }, { "alpha_fraction": 0.596265435218811, "alphanum_fraction": 0.6197324991226196, "avg_line_length": 41.6129035949707, "blob_id": "4034e80f7876974f145c69e03b847cb6cfb4febc", "content_id": "9bc3489c3e8c5a637fabfc211b29a63aae86d19d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3963, "license_type": "no_license", "max_line_length": 118, "num_lines": 93, "path": "/common/include/blast_packet_format.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * blast_packet_format.h: \n *\n * This software is copyright (C) 2013-2015 Seth Hillbrand\n *\n * This file is part of blast_comms, created for the BLASTPol Project.\n *\n * blast_comms 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 2 of the License, or\n * (at your option) any later version.\n *\n * blast_comms 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 blast_comms; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Apr 7, 2015 by Seth Hillbrand\n */\n\n#ifndef INCLUDE_BLAST_PACKET_FORMAT_H\n#define INCLUDE_BLAST_PACKET_FORMAT_H\n\n#include <lookup.h>\n\n#define _BLAST_PORT_DEFS(x, _) \\\n _(x, DATA) \\\n _(x, COMMAND) \\\n _(x, FILE) \\\n\n\nstatic const uint8_t sip_start_byte = 0x10;\nstatic const uint8_t sip_end_byte = 0x03;\n\ntypedef struct blast_master_packet\n{\n uint8_t magic; /**< magic = 0xEB for all packets */\n\n uint32_t version:2; /**< version Currently at 1 */\n uint32_t qos:1; /**< qos Quality of service flag. 1 = Response required */\n uint32_t has_ack:1; /**< has_ack The packet has an appended acknowledgment signature */\n uint32_t multi_packet:1; /**< multi_packet 0 = single packet in the payload; 1 = multiple packets*/\n uint32_t type:3; /**< type The type of data in this payload */\n uint16_t length; /**< length Number of bytes in the payload */\n} __attribute__((packed)) blast_master_packet_t; /** 4 bytes */\n\n\ntypedef struct blast_seg_pkt_hdr\n{\n blast_master_packet_t header;\n uint8_t seg_id; /**< seg_id sequential id to group the segments */\n uint8_t seg_num; /**< seg_num ordering number of multi-segment data */\n} __attribute__((packed)) blast_seg_pkt_hdr_t;\n\ntypedef struct\n{\n uint8_t start_byte;\n uint8_t link_route; /**< link_route los, tdrss or iridium */\n uint8_t link_address; /**!< link_address either comm1 or comm2 */\n uint8_t length;\n} __attribute__((packed)) sip_rts_packet_t;\n\ntypedef struct blast_data_pkt_header\n{\n uint32_t hash; /**< hash Hash of the data contained in the packet */\n}__attribute__((packed)) blast_data_pkt_header_t;\n\ntypedef struct blast_cmd_pkt_header\n{\n uint32_t cmd; /**< cmd Hash of the command name */\n uint16_t cmd_num; /**< cmd_num A sequential number allowing distinct acknowledgment */\n}__attribute__((packed)) blast_cmd_pkt_header_t;\n\ntypedef struct blast_file_pkt_header\n{\n char filename[1]; /**< filename Pointer to the name of the file found in the packet */\n}__attribute__((packed)) blast_file_pkt_header_t;\n\n#define BLAST_MASTER_PACKET_FULL_LENGTH(_ptr) (sizeof(blast_master_packet_t) + (_ptr)->length + 4)\n#define BLAST_MASTER_PACKET_PAYLOAD(_ptr) ((uint8_t*)(((blast_master_packet_t*)(_ptr))+1))\n#define BLAST_MASTER_PACKET_CRC(_ptr) (*(uint32_t*)(&BLAST_MASTER_PACKET_PAYLOAD(_ptr)[(_ptr)->length]))\n#define BLAST_MASTER_PACKET_ACK(_ptr) (*(uint32_t*)(&BLAST_MASTER_PACKET_PAYLOAD(_ptr)[(_ptr)->length + 4]))\n#define BLAST_SEGMENT_PACKET_COUNT(_ptr) \\\n (((_ptr)->header.length + 4 - (255 - sizeof(blast_seg_pkt_hdr_t) -1)) / (255 - sizeof(blast_seg_pkt_hdr_t)))\n#define BLAST_SEGMENT_PACKET_PAYLOAD(_ptr) ((uint8_t*)(((blast_seg_pkt_hdr_t*)(_ptr))+1))\n\n\n#endif /* INCLUDE_BLAST_PACKET_FORMAT_H_ */\n" }, { "alpha_fraction": 0.5965664982795715, "alphanum_fraction": 0.5965664982795715, "avg_line_length": 24.77777862548828, "blob_id": "b004d6a2246b5bd1c4e0537a8b5fcb8d555e4a39", "content_id": "d21d51b92dd4e78d552a9bd2d588dc07a5b7a0b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 233, "license_type": "no_license", "max_line_length": 59, "num_lines": 9, "path": "/stars/utilities/ebex_images/ezip_decompress_many.py", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\nimport os\n\nfor filename in os.listdir(\".\"):\n if filename.endswith(\".ez\"):\n outfilename = filename.strip(\".ez\")\n command = \"ezip -d %s %s\" % (filename, outfilename)\n os.system(command)\n\n" }, { "alpha_fraction": 0.4750938415527344, "alphanum_fraction": 0.7876309752464294, "avg_line_length": 72.25648498535156, "blob_id": "b3416253e301c73e8e346e0408cd8dcdab099983", "content_id": "1a6e6c683c905e3f796c3861e0e8b051ef10fcbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 79117, "license_type": "no_license", "max_line_length": 76, "num_lines": 1080, "path": "/common/include/crc32table.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * crc32table.h: \n *\n * This software is copyright \n * (C) 2013-2014 California State University, Sacramento\n *\n * This file is part of mcp, created for the BLASTPol Project.\n *\n * mcp 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Feb 18, 2015 by seth\n */\n\n#ifndef CRC32TABLE_H_\n#define CRC32TABLE_H_\n#include <stdint.h>\n\n#include \"blast_compiler.h\"\n\n\n/* this file is generated - do not edit */\n\nstatic uint32_t __attribute__((__aligned__(8))) crc32table_le[8][256] = {{\ntole(0x00000000L), tole(0x77073096L), tole(0xee0e612cL), tole(0x990951baL),\ntole(0x076dc419L), tole(0x706af48fL), tole(0xe963a535L), tole(0x9e6495a3L),\ntole(0x0edb8832L), tole(0x79dcb8a4L), tole(0xe0d5e91eL), tole(0x97d2d988L),\ntole(0x09b64c2bL), tole(0x7eb17cbdL), tole(0xe7b82d07L), tole(0x90bf1d91L),\ntole(0x1db71064L), tole(0x6ab020f2L), tole(0xf3b97148L), tole(0x84be41deL),\ntole(0x1adad47dL), tole(0x6ddde4ebL), tole(0xf4d4b551L), tole(0x83d385c7L),\ntole(0x136c9856L), tole(0x646ba8c0L), tole(0xfd62f97aL), tole(0x8a65c9ecL),\ntole(0x14015c4fL), tole(0x63066cd9L), tole(0xfa0f3d63L), tole(0x8d080df5L),\ntole(0x3b6e20c8L), tole(0x4c69105eL), tole(0xd56041e4L), tole(0xa2677172L),\ntole(0x3c03e4d1L), tole(0x4b04d447L), tole(0xd20d85fdL), tole(0xa50ab56bL),\ntole(0x35b5a8faL), tole(0x42b2986cL), tole(0xdbbbc9d6L), tole(0xacbcf940L),\ntole(0x32d86ce3L), tole(0x45df5c75L), tole(0xdcd60dcfL), tole(0xabd13d59L),\ntole(0x26d930acL), tole(0x51de003aL), tole(0xc8d75180L), tole(0xbfd06116L),\ntole(0x21b4f4b5L), tole(0x56b3c423L), tole(0xcfba9599L), tole(0xb8bda50fL),\ntole(0x2802b89eL), tole(0x5f058808L), tole(0xc60cd9b2L), tole(0xb10be924L),\ntole(0x2f6f7c87L), tole(0x58684c11L), tole(0xc1611dabL), tole(0xb6662d3dL),\ntole(0x76dc4190L), tole(0x01db7106L), tole(0x98d220bcL), tole(0xefd5102aL),\ntole(0x71b18589L), tole(0x06b6b51fL), tole(0x9fbfe4a5L), tole(0xe8b8d433L),\ntole(0x7807c9a2L), tole(0x0f00f934L), tole(0x9609a88eL), tole(0xe10e9818L),\ntole(0x7f6a0dbbL), tole(0x086d3d2dL), tole(0x91646c97L), tole(0xe6635c01L),\ntole(0x6b6b51f4L), tole(0x1c6c6162L), tole(0x856530d8L), tole(0xf262004eL),\ntole(0x6c0695edL), tole(0x1b01a57bL), tole(0x8208f4c1L), tole(0xf50fc457L),\ntole(0x65b0d9c6L), tole(0x12b7e950L), tole(0x8bbeb8eaL), tole(0xfcb9887cL),\ntole(0x62dd1ddfL), tole(0x15da2d49L), tole(0x8cd37cf3L), tole(0xfbd44c65L),\ntole(0x4db26158L), tole(0x3ab551ceL), tole(0xa3bc0074L), tole(0xd4bb30e2L),\ntole(0x4adfa541L), tole(0x3dd895d7L), tole(0xa4d1c46dL), tole(0xd3d6f4fbL),\ntole(0x4369e96aL), tole(0x346ed9fcL), tole(0xad678846L), tole(0xda60b8d0L),\ntole(0x44042d73L), tole(0x33031de5L), tole(0xaa0a4c5fL), tole(0xdd0d7cc9L),\ntole(0x5005713cL), tole(0x270241aaL), tole(0xbe0b1010L), tole(0xc90c2086L),\ntole(0x5768b525L), tole(0x206f85b3L), tole(0xb966d409L), tole(0xce61e49fL),\ntole(0x5edef90eL), tole(0x29d9c998L), tole(0xb0d09822L), tole(0xc7d7a8b4L),\ntole(0x59b33d17L), tole(0x2eb40d81L), tole(0xb7bd5c3bL), tole(0xc0ba6cadL),\ntole(0xedb88320L), tole(0x9abfb3b6L), tole(0x03b6e20cL), tole(0x74b1d29aL),\ntole(0xead54739L), tole(0x9dd277afL), tole(0x04db2615L), tole(0x73dc1683L),\ntole(0xe3630b12L), tole(0x94643b84L), tole(0x0d6d6a3eL), tole(0x7a6a5aa8L),\ntole(0xe40ecf0bL), tole(0x9309ff9dL), tole(0x0a00ae27L), tole(0x7d079eb1L),\ntole(0xf00f9344L), tole(0x8708a3d2L), tole(0x1e01f268L), tole(0x6906c2feL),\ntole(0xf762575dL), tole(0x806567cbL), tole(0x196c3671L), tole(0x6e6b06e7L),\ntole(0xfed41b76L), tole(0x89d32be0L), tole(0x10da7a5aL), tole(0x67dd4accL),\ntole(0xf9b9df6fL), tole(0x8ebeeff9L), tole(0x17b7be43L), tole(0x60b08ed5L),\ntole(0xd6d6a3e8L), tole(0xa1d1937eL), tole(0x38d8c2c4L), tole(0x4fdff252L),\ntole(0xd1bb67f1L), tole(0xa6bc5767L), tole(0x3fb506ddL), tole(0x48b2364bL),\ntole(0xd80d2bdaL), tole(0xaf0a1b4cL), tole(0x36034af6L), tole(0x41047a60L),\ntole(0xdf60efc3L), tole(0xa867df55L), tole(0x316e8eefL), tole(0x4669be79L),\ntole(0xcb61b38cL), tole(0xbc66831aL), tole(0x256fd2a0L), tole(0x5268e236L),\ntole(0xcc0c7795L), tole(0xbb0b4703L), tole(0x220216b9L), tole(0x5505262fL),\ntole(0xc5ba3bbeL), tole(0xb2bd0b28L), tole(0x2bb45a92L), tole(0x5cb36a04L),\ntole(0xc2d7ffa7L), tole(0xb5d0cf31L), tole(0x2cd99e8bL), tole(0x5bdeae1dL),\ntole(0x9b64c2b0L), tole(0xec63f226L), tole(0x756aa39cL), tole(0x026d930aL),\ntole(0x9c0906a9L), tole(0xeb0e363fL), tole(0x72076785L), tole(0x05005713L),\ntole(0x95bf4a82L), tole(0xe2b87a14L), tole(0x7bb12baeL), tole(0x0cb61b38L),\ntole(0x92d28e9bL), tole(0xe5d5be0dL), tole(0x7cdcefb7L), tole(0x0bdbdf21L),\ntole(0x86d3d2d4L), tole(0xf1d4e242L), tole(0x68ddb3f8L), tole(0x1fda836eL),\ntole(0x81be16cdL), tole(0xf6b9265bL), tole(0x6fb077e1L), tole(0x18b74777L),\ntole(0x88085ae6L), tole(0xff0f6a70L), tole(0x66063bcaL), tole(0x11010b5cL),\ntole(0x8f659effL), tole(0xf862ae69L), tole(0x616bffd3L), tole(0x166ccf45L),\ntole(0xa00ae278L), tole(0xd70dd2eeL), tole(0x4e048354L), tole(0x3903b3c2L),\ntole(0xa7672661L), tole(0xd06016f7L), tole(0x4969474dL), tole(0x3e6e77dbL),\ntole(0xaed16a4aL), tole(0xd9d65adcL), tole(0x40df0b66L), tole(0x37d83bf0L),\ntole(0xa9bcae53L), tole(0xdebb9ec5L), tole(0x47b2cf7fL), tole(0x30b5ffe9L),\ntole(0xbdbdf21cL), tole(0xcabac28aL), tole(0x53b39330L), tole(0x24b4a3a6L),\ntole(0xbad03605L), tole(0xcdd70693L), tole(0x54de5729L), tole(0x23d967bfL),\ntole(0xb3667a2eL), tole(0xc4614ab8L), tole(0x5d681b02L), tole(0x2a6f2b94L),\ntole(0xb40bbe37L), tole(0xc30c8ea1L), tole(0x5a05df1bL), tole(0x2d02ef8dL)},\n{\ntole(0x00000000L), tole(0x191b3141L), tole(0x32366282L), tole(0x2b2d53c3L),\ntole(0x646cc504L), tole(0x7d77f445L), tole(0x565aa786L), tole(0x4f4196c7L),\ntole(0xc8d98a08L), tole(0xd1c2bb49L), tole(0xfaefe88aL), tole(0xe3f4d9cbL),\ntole(0xacb54f0cL), tole(0xb5ae7e4dL), tole(0x9e832d8eL), tole(0x87981ccfL),\ntole(0x4ac21251L), tole(0x53d92310L), tole(0x78f470d3L), tole(0x61ef4192L),\ntole(0x2eaed755L), tole(0x37b5e614L), tole(0x1c98b5d7L), tole(0x05838496L),\ntole(0x821b9859L), tole(0x9b00a918L), tole(0xb02dfadbL), tole(0xa936cb9aL),\ntole(0xe6775d5dL), tole(0xff6c6c1cL), tole(0xd4413fdfL), tole(0xcd5a0e9eL),\ntole(0x958424a2L), tole(0x8c9f15e3L), tole(0xa7b24620L), tole(0xbea97761L),\ntole(0xf1e8e1a6L), tole(0xe8f3d0e7L), tole(0xc3de8324L), tole(0xdac5b265L),\ntole(0x5d5daeaaL), tole(0x44469febL), tole(0x6f6bcc28L), tole(0x7670fd69L),\ntole(0x39316baeL), tole(0x202a5aefL), tole(0x0b07092cL), tole(0x121c386dL),\ntole(0xdf4636f3L), tole(0xc65d07b2L), tole(0xed705471L), tole(0xf46b6530L),\ntole(0xbb2af3f7L), tole(0xa231c2b6L), tole(0x891c9175L), tole(0x9007a034L),\ntole(0x179fbcfbL), tole(0x0e848dbaL), tole(0x25a9de79L), tole(0x3cb2ef38L),\ntole(0x73f379ffL), tole(0x6ae848beL), tole(0x41c51b7dL), tole(0x58de2a3cL),\ntole(0xf0794f05L), tole(0xe9627e44L), tole(0xc24f2d87L), tole(0xdb541cc6L),\ntole(0x94158a01L), tole(0x8d0ebb40L), tole(0xa623e883L), tole(0xbf38d9c2L),\ntole(0x38a0c50dL), tole(0x21bbf44cL), tole(0x0a96a78fL), tole(0x138d96ceL),\ntole(0x5ccc0009L), tole(0x45d73148L), tole(0x6efa628bL), tole(0x77e153caL),\ntole(0xbabb5d54L), tole(0xa3a06c15L), tole(0x888d3fd6L), tole(0x91960e97L),\ntole(0xded79850L), tole(0xc7cca911L), tole(0xece1fad2L), tole(0xf5facb93L),\ntole(0x7262d75cL), tole(0x6b79e61dL), tole(0x4054b5deL), tole(0x594f849fL),\ntole(0x160e1258L), tole(0x0f152319L), tole(0x243870daL), tole(0x3d23419bL),\ntole(0x65fd6ba7L), tole(0x7ce65ae6L), tole(0x57cb0925L), tole(0x4ed03864L),\ntole(0x0191aea3L), tole(0x188a9fe2L), tole(0x33a7cc21L), tole(0x2abcfd60L),\ntole(0xad24e1afL), tole(0xb43fd0eeL), tole(0x9f12832dL), tole(0x8609b26cL),\ntole(0xc94824abL), tole(0xd05315eaL), tole(0xfb7e4629L), tole(0xe2657768L),\ntole(0x2f3f79f6L), tole(0x362448b7L), tole(0x1d091b74L), tole(0x04122a35L),\ntole(0x4b53bcf2L), tole(0x52488db3L), tole(0x7965de70L), tole(0x607eef31L),\ntole(0xe7e6f3feL), tole(0xfefdc2bfL), tole(0xd5d0917cL), tole(0xcccba03dL),\ntole(0x838a36faL), tole(0x9a9107bbL), tole(0xb1bc5478L), tole(0xa8a76539L),\ntole(0x3b83984bL), tole(0x2298a90aL), tole(0x09b5fac9L), tole(0x10aecb88L),\ntole(0x5fef5d4fL), tole(0x46f46c0eL), tole(0x6dd93fcdL), tole(0x74c20e8cL),\ntole(0xf35a1243L), tole(0xea412302L), tole(0xc16c70c1L), tole(0xd8774180L),\ntole(0x9736d747L), tole(0x8e2de606L), tole(0xa500b5c5L), tole(0xbc1b8484L),\ntole(0x71418a1aL), tole(0x685abb5bL), tole(0x4377e898L), tole(0x5a6cd9d9L),\ntole(0x152d4f1eL), tole(0x0c367e5fL), tole(0x271b2d9cL), tole(0x3e001cddL),\ntole(0xb9980012L), tole(0xa0833153L), tole(0x8bae6290L), tole(0x92b553d1L),\ntole(0xddf4c516L), tole(0xc4eff457L), tole(0xefc2a794L), tole(0xf6d996d5L),\ntole(0xae07bce9L), tole(0xb71c8da8L), tole(0x9c31de6bL), tole(0x852aef2aL),\ntole(0xca6b79edL), tole(0xd37048acL), tole(0xf85d1b6fL), tole(0xe1462a2eL),\ntole(0x66de36e1L), tole(0x7fc507a0L), tole(0x54e85463L), tole(0x4df36522L),\ntole(0x02b2f3e5L), tole(0x1ba9c2a4L), tole(0x30849167L), tole(0x299fa026L),\ntole(0xe4c5aeb8L), tole(0xfdde9ff9L), tole(0xd6f3cc3aL), tole(0xcfe8fd7bL),\ntole(0x80a96bbcL), tole(0x99b25afdL), tole(0xb29f093eL), tole(0xab84387fL),\ntole(0x2c1c24b0L), tole(0x350715f1L), tole(0x1e2a4632L), tole(0x07317773L),\ntole(0x4870e1b4L), tole(0x516bd0f5L), tole(0x7a468336L), tole(0x635db277L),\ntole(0xcbfad74eL), tole(0xd2e1e60fL), tole(0xf9ccb5ccL), tole(0xe0d7848dL),\ntole(0xaf96124aL), tole(0xb68d230bL), tole(0x9da070c8L), tole(0x84bb4189L),\ntole(0x03235d46L), tole(0x1a386c07L), tole(0x31153fc4L), tole(0x280e0e85L),\ntole(0x674f9842L), tole(0x7e54a903L), tole(0x5579fac0L), tole(0x4c62cb81L),\ntole(0x8138c51fL), tole(0x9823f45eL), tole(0xb30ea79dL), tole(0xaa1596dcL),\ntole(0xe554001bL), tole(0xfc4f315aL), tole(0xd7626299L), tole(0xce7953d8L),\ntole(0x49e14f17L), tole(0x50fa7e56L), tole(0x7bd72d95L), tole(0x62cc1cd4L),\ntole(0x2d8d8a13L), tole(0x3496bb52L), tole(0x1fbbe891L), tole(0x06a0d9d0L),\ntole(0x5e7ef3ecL), tole(0x4765c2adL), tole(0x6c48916eL), tole(0x7553a02fL),\ntole(0x3a1236e8L), tole(0x230907a9L), tole(0x0824546aL), tole(0x113f652bL),\ntole(0x96a779e4L), tole(0x8fbc48a5L), tole(0xa4911b66L), tole(0xbd8a2a27L),\ntole(0xf2cbbce0L), tole(0xebd08da1L), tole(0xc0fdde62L), tole(0xd9e6ef23L),\ntole(0x14bce1bdL), tole(0x0da7d0fcL), tole(0x268a833fL), tole(0x3f91b27eL),\ntole(0x70d024b9L), tole(0x69cb15f8L), tole(0x42e6463bL), tole(0x5bfd777aL),\ntole(0xdc656bb5L), tole(0xc57e5af4L), tole(0xee530937L), tole(0xf7483876L),\ntole(0xb809aeb1L), tole(0xa1129ff0L), tole(0x8a3fcc33L), tole(0x9324fd72L)},\n{\ntole(0x00000000L), tole(0x01c26a37L), tole(0x0384d46eL), tole(0x0246be59L),\ntole(0x0709a8dcL), tole(0x06cbc2ebL), tole(0x048d7cb2L), tole(0x054f1685L),\ntole(0x0e1351b8L), tole(0x0fd13b8fL), tole(0x0d9785d6L), tole(0x0c55efe1L),\ntole(0x091af964L), tole(0x08d89353L), tole(0x0a9e2d0aL), tole(0x0b5c473dL),\ntole(0x1c26a370L), tole(0x1de4c947L), tole(0x1fa2771eL), tole(0x1e601d29L),\ntole(0x1b2f0bacL), tole(0x1aed619bL), tole(0x18abdfc2L), tole(0x1969b5f5L),\ntole(0x1235f2c8L), tole(0x13f798ffL), tole(0x11b126a6L), tole(0x10734c91L),\ntole(0x153c5a14L), tole(0x14fe3023L), tole(0x16b88e7aL), tole(0x177ae44dL),\ntole(0x384d46e0L), tole(0x398f2cd7L), tole(0x3bc9928eL), tole(0x3a0bf8b9L),\ntole(0x3f44ee3cL), tole(0x3e86840bL), tole(0x3cc03a52L), tole(0x3d025065L),\ntole(0x365e1758L), tole(0x379c7d6fL), tole(0x35dac336L), tole(0x3418a901L),\ntole(0x3157bf84L), tole(0x3095d5b3L), tole(0x32d36beaL), tole(0x331101ddL),\ntole(0x246be590L), tole(0x25a98fa7L), tole(0x27ef31feL), tole(0x262d5bc9L),\ntole(0x23624d4cL), tole(0x22a0277bL), tole(0x20e69922L), tole(0x2124f315L),\ntole(0x2a78b428L), tole(0x2bbade1fL), tole(0x29fc6046L), tole(0x283e0a71L),\ntole(0x2d711cf4L), tole(0x2cb376c3L), tole(0x2ef5c89aL), tole(0x2f37a2adL),\ntole(0x709a8dc0L), tole(0x7158e7f7L), tole(0x731e59aeL), tole(0x72dc3399L),\ntole(0x7793251cL), tole(0x76514f2bL), tole(0x7417f172L), tole(0x75d59b45L),\ntole(0x7e89dc78L), tole(0x7f4bb64fL), tole(0x7d0d0816L), tole(0x7ccf6221L),\ntole(0x798074a4L), tole(0x78421e93L), tole(0x7a04a0caL), tole(0x7bc6cafdL),\ntole(0x6cbc2eb0L), tole(0x6d7e4487L), tole(0x6f38fadeL), tole(0x6efa90e9L),\ntole(0x6bb5866cL), tole(0x6a77ec5bL), tole(0x68315202L), tole(0x69f33835L),\ntole(0x62af7f08L), tole(0x636d153fL), tole(0x612bab66L), tole(0x60e9c151L),\ntole(0x65a6d7d4L), tole(0x6464bde3L), tole(0x662203baL), tole(0x67e0698dL),\ntole(0x48d7cb20L), tole(0x4915a117L), tole(0x4b531f4eL), tole(0x4a917579L),\ntole(0x4fde63fcL), tole(0x4e1c09cbL), tole(0x4c5ab792L), tole(0x4d98dda5L),\ntole(0x46c49a98L), tole(0x4706f0afL), tole(0x45404ef6L), tole(0x448224c1L),\ntole(0x41cd3244L), tole(0x400f5873L), tole(0x4249e62aL), tole(0x438b8c1dL),\ntole(0x54f16850L), tole(0x55330267L), tole(0x5775bc3eL), tole(0x56b7d609L),\ntole(0x53f8c08cL), tole(0x523aaabbL), tole(0x507c14e2L), tole(0x51be7ed5L),\ntole(0x5ae239e8L), tole(0x5b2053dfL), tole(0x5966ed86L), tole(0x58a487b1L),\ntole(0x5deb9134L), tole(0x5c29fb03L), tole(0x5e6f455aL), tole(0x5fad2f6dL),\ntole(0xe1351b80L), tole(0xe0f771b7L), tole(0xe2b1cfeeL), tole(0xe373a5d9L),\ntole(0xe63cb35cL), tole(0xe7fed96bL), tole(0xe5b86732L), tole(0xe47a0d05L),\ntole(0xef264a38L), tole(0xeee4200fL), tole(0xeca29e56L), tole(0xed60f461L),\ntole(0xe82fe2e4L), tole(0xe9ed88d3L), tole(0xebab368aL), tole(0xea695cbdL),\ntole(0xfd13b8f0L), tole(0xfcd1d2c7L), tole(0xfe976c9eL), tole(0xff5506a9L),\ntole(0xfa1a102cL), tole(0xfbd87a1bL), tole(0xf99ec442L), tole(0xf85cae75L),\ntole(0xf300e948L), tole(0xf2c2837fL), tole(0xf0843d26L), tole(0xf1465711L),\ntole(0xf4094194L), tole(0xf5cb2ba3L), tole(0xf78d95faL), tole(0xf64fffcdL),\ntole(0xd9785d60L), tole(0xd8ba3757L), tole(0xdafc890eL), tole(0xdb3ee339L),\ntole(0xde71f5bcL), tole(0xdfb39f8bL), tole(0xddf521d2L), tole(0xdc374be5L),\ntole(0xd76b0cd8L), tole(0xd6a966efL), tole(0xd4efd8b6L), tole(0xd52db281L),\ntole(0xd062a404L), tole(0xd1a0ce33L), tole(0xd3e6706aL), tole(0xd2241a5dL),\ntole(0xc55efe10L), tole(0xc49c9427L), tole(0xc6da2a7eL), tole(0xc7184049L),\ntole(0xc25756ccL), tole(0xc3953cfbL), tole(0xc1d382a2L), tole(0xc011e895L),\ntole(0xcb4dafa8L), tole(0xca8fc59fL), tole(0xc8c97bc6L), tole(0xc90b11f1L),\ntole(0xcc440774L), tole(0xcd866d43L), tole(0xcfc0d31aL), tole(0xce02b92dL),\ntole(0x91af9640L), tole(0x906dfc77L), tole(0x922b422eL), tole(0x93e92819L),\ntole(0x96a63e9cL), tole(0x976454abL), tole(0x9522eaf2L), tole(0x94e080c5L),\ntole(0x9fbcc7f8L), tole(0x9e7eadcfL), tole(0x9c381396L), tole(0x9dfa79a1L),\ntole(0x98b56f24L), tole(0x99770513L), tole(0x9b31bb4aL), tole(0x9af3d17dL),\ntole(0x8d893530L), tole(0x8c4b5f07L), tole(0x8e0de15eL), tole(0x8fcf8b69L),\ntole(0x8a809decL), tole(0x8b42f7dbL), tole(0x89044982L), tole(0x88c623b5L),\ntole(0x839a6488L), tole(0x82580ebfL), tole(0x801eb0e6L), tole(0x81dcdad1L),\ntole(0x8493cc54L), tole(0x8551a663L), tole(0x8717183aL), tole(0x86d5720dL),\ntole(0xa9e2d0a0L), tole(0xa820ba97L), tole(0xaa6604ceL), tole(0xaba46ef9L),\ntole(0xaeeb787cL), tole(0xaf29124bL), tole(0xad6fac12L), tole(0xacadc625L),\ntole(0xa7f18118L), tole(0xa633eb2fL), tole(0xa4755576L), tole(0xa5b73f41L),\ntole(0xa0f829c4L), tole(0xa13a43f3L), tole(0xa37cfdaaL), tole(0xa2be979dL),\ntole(0xb5c473d0L), tole(0xb40619e7L), tole(0xb640a7beL), tole(0xb782cd89L),\ntole(0xb2cddb0cL), tole(0xb30fb13bL), tole(0xb1490f62L), tole(0xb08b6555L),\ntole(0xbbd72268L), tole(0xba15485fL), tole(0xb853f606L), tole(0xb9919c31L),\ntole(0xbcde8ab4L), tole(0xbd1ce083L), tole(0xbf5a5edaL), tole(0xbe9834edL)},\n{\ntole(0x00000000L), tole(0xb8bc6765L), tole(0xaa09c88bL), tole(0x12b5afeeL),\ntole(0x8f629757L), tole(0x37def032L), tole(0x256b5fdcL), tole(0x9dd738b9L),\ntole(0xc5b428efL), tole(0x7d084f8aL), tole(0x6fbde064L), tole(0xd7018701L),\ntole(0x4ad6bfb8L), tole(0xf26ad8ddL), tole(0xe0df7733L), tole(0x58631056L),\ntole(0x5019579fL), tole(0xe8a530faL), tole(0xfa109f14L), tole(0x42acf871L),\ntole(0xdf7bc0c8L), tole(0x67c7a7adL), tole(0x75720843L), tole(0xcdce6f26L),\ntole(0x95ad7f70L), tole(0x2d111815L), tole(0x3fa4b7fbL), tole(0x8718d09eL),\ntole(0x1acfe827L), tole(0xa2738f42L), tole(0xb0c620acL), tole(0x087a47c9L),\ntole(0xa032af3eL), tole(0x188ec85bL), tole(0x0a3b67b5L), tole(0xb28700d0L),\ntole(0x2f503869L), tole(0x97ec5f0cL), tole(0x8559f0e2L), tole(0x3de59787L),\ntole(0x658687d1L), tole(0xdd3ae0b4L), tole(0xcf8f4f5aL), tole(0x7733283fL),\ntole(0xeae41086L), tole(0x525877e3L), tole(0x40edd80dL), tole(0xf851bf68L),\ntole(0xf02bf8a1L), tole(0x48979fc4L), tole(0x5a22302aL), tole(0xe29e574fL),\ntole(0x7f496ff6L), tole(0xc7f50893L), tole(0xd540a77dL), tole(0x6dfcc018L),\ntole(0x359fd04eL), tole(0x8d23b72bL), tole(0x9f9618c5L), tole(0x272a7fa0L),\ntole(0xbafd4719L), tole(0x0241207cL), tole(0x10f48f92L), tole(0xa848e8f7L),\ntole(0x9b14583dL), tole(0x23a83f58L), tole(0x311d90b6L), tole(0x89a1f7d3L),\ntole(0x1476cf6aL), tole(0xaccaa80fL), tole(0xbe7f07e1L), tole(0x06c36084L),\ntole(0x5ea070d2L), tole(0xe61c17b7L), tole(0xf4a9b859L), tole(0x4c15df3cL),\ntole(0xd1c2e785L), tole(0x697e80e0L), tole(0x7bcb2f0eL), tole(0xc377486bL),\ntole(0xcb0d0fa2L), tole(0x73b168c7L), tole(0x6104c729L), tole(0xd9b8a04cL),\ntole(0x446f98f5L), tole(0xfcd3ff90L), tole(0xee66507eL), tole(0x56da371bL),\ntole(0x0eb9274dL), tole(0xb6054028L), tole(0xa4b0efc6L), tole(0x1c0c88a3L),\ntole(0x81dbb01aL), tole(0x3967d77fL), tole(0x2bd27891L), tole(0x936e1ff4L),\ntole(0x3b26f703L), tole(0x839a9066L), tole(0x912f3f88L), tole(0x299358edL),\ntole(0xb4446054L), tole(0x0cf80731L), tole(0x1e4da8dfL), tole(0xa6f1cfbaL),\ntole(0xfe92dfecL), tole(0x462eb889L), tole(0x549b1767L), tole(0xec277002L),\ntole(0x71f048bbL), tole(0xc94c2fdeL), tole(0xdbf98030L), tole(0x6345e755L),\ntole(0x6b3fa09cL), tole(0xd383c7f9L), tole(0xc1366817L), tole(0x798a0f72L),\ntole(0xe45d37cbL), tole(0x5ce150aeL), tole(0x4e54ff40L), tole(0xf6e89825L),\ntole(0xae8b8873L), tole(0x1637ef16L), tole(0x048240f8L), tole(0xbc3e279dL),\ntole(0x21e91f24L), tole(0x99557841L), tole(0x8be0d7afL), tole(0x335cb0caL),\ntole(0xed59b63bL), tole(0x55e5d15eL), tole(0x47507eb0L), tole(0xffec19d5L),\ntole(0x623b216cL), tole(0xda874609L), tole(0xc832e9e7L), tole(0x708e8e82L),\ntole(0x28ed9ed4L), tole(0x9051f9b1L), tole(0x82e4565fL), tole(0x3a58313aL),\ntole(0xa78f0983L), tole(0x1f336ee6L), tole(0x0d86c108L), tole(0xb53aa66dL),\ntole(0xbd40e1a4L), tole(0x05fc86c1L), tole(0x1749292fL), tole(0xaff54e4aL),\ntole(0x322276f3L), tole(0x8a9e1196L), tole(0x982bbe78L), tole(0x2097d91dL),\ntole(0x78f4c94bL), tole(0xc048ae2eL), tole(0xd2fd01c0L), tole(0x6a4166a5L),\ntole(0xf7965e1cL), tole(0x4f2a3979L), tole(0x5d9f9697L), tole(0xe523f1f2L),\ntole(0x4d6b1905L), tole(0xf5d77e60L), tole(0xe762d18eL), tole(0x5fdeb6ebL),\ntole(0xc2098e52L), tole(0x7ab5e937L), tole(0x680046d9L), tole(0xd0bc21bcL),\ntole(0x88df31eaL), tole(0x3063568fL), tole(0x22d6f961L), tole(0x9a6a9e04L),\ntole(0x07bda6bdL), tole(0xbf01c1d8L), tole(0xadb46e36L), tole(0x15080953L),\ntole(0x1d724e9aL), tole(0xa5ce29ffL), tole(0xb77b8611L), tole(0x0fc7e174L),\ntole(0x9210d9cdL), tole(0x2aacbea8L), tole(0x38191146L), tole(0x80a57623L),\ntole(0xd8c66675L), tole(0x607a0110L), tole(0x72cfaefeL), tole(0xca73c99bL),\ntole(0x57a4f122L), tole(0xef189647L), tole(0xfdad39a9L), tole(0x45115eccL),\ntole(0x764dee06L), tole(0xcef18963L), tole(0xdc44268dL), tole(0x64f841e8L),\ntole(0xf92f7951L), tole(0x41931e34L), tole(0x5326b1daL), tole(0xeb9ad6bfL),\ntole(0xb3f9c6e9L), tole(0x0b45a18cL), tole(0x19f00e62L), tole(0xa14c6907L),\ntole(0x3c9b51beL), tole(0x842736dbL), tole(0x96929935L), tole(0x2e2efe50L),\ntole(0x2654b999L), tole(0x9ee8defcL), tole(0x8c5d7112L), tole(0x34e11677L),\ntole(0xa9362eceL), tole(0x118a49abL), tole(0x033fe645L), tole(0xbb838120L),\ntole(0xe3e09176L), tole(0x5b5cf613L), tole(0x49e959fdL), tole(0xf1553e98L),\ntole(0x6c820621L), tole(0xd43e6144L), tole(0xc68bceaaL), tole(0x7e37a9cfL),\ntole(0xd67f4138L), tole(0x6ec3265dL), tole(0x7c7689b3L), tole(0xc4caeed6L),\ntole(0x591dd66fL), tole(0xe1a1b10aL), tole(0xf3141ee4L), tole(0x4ba87981L),\ntole(0x13cb69d7L), tole(0xab770eb2L), tole(0xb9c2a15cL), tole(0x017ec639L),\ntole(0x9ca9fe80L), tole(0x241599e5L), tole(0x36a0360bL), tole(0x8e1c516eL),\ntole(0x866616a7L), tole(0x3eda71c2L), tole(0x2c6fde2cL), tole(0x94d3b949L),\ntole(0x090481f0L), tole(0xb1b8e695L), tole(0xa30d497bL), tole(0x1bb12e1eL),\ntole(0x43d23e48L), tole(0xfb6e592dL), tole(0xe9dbf6c3L), tole(0x516791a6L),\ntole(0xccb0a91fL), tole(0x740cce7aL), tole(0x66b96194L), tole(0xde0506f1L)},\n{\ntole(0x00000000L), tole(0x3d6029b0L), tole(0x7ac05360L), tole(0x47a07ad0L),\ntole(0xf580a6c0L), tole(0xc8e08f70L), tole(0x8f40f5a0L), tole(0xb220dc10L),\ntole(0x30704bc1L), tole(0x0d106271L), tole(0x4ab018a1L), tole(0x77d03111L),\ntole(0xc5f0ed01L), tole(0xf890c4b1L), tole(0xbf30be61L), tole(0x825097d1L),\ntole(0x60e09782L), tole(0x5d80be32L), tole(0x1a20c4e2L), tole(0x2740ed52L),\ntole(0x95603142L), tole(0xa80018f2L), tole(0xefa06222L), tole(0xd2c04b92L),\ntole(0x5090dc43L), tole(0x6df0f5f3L), tole(0x2a508f23L), tole(0x1730a693L),\ntole(0xa5107a83L), tole(0x98705333L), tole(0xdfd029e3L), tole(0xe2b00053L),\ntole(0xc1c12f04L), tole(0xfca106b4L), tole(0xbb017c64L), tole(0x866155d4L),\ntole(0x344189c4L), tole(0x0921a074L), tole(0x4e81daa4L), tole(0x73e1f314L),\ntole(0xf1b164c5L), tole(0xccd14d75L), tole(0x8b7137a5L), tole(0xb6111e15L),\ntole(0x0431c205L), tole(0x3951ebb5L), tole(0x7ef19165L), tole(0x4391b8d5L),\ntole(0xa121b886L), tole(0x9c419136L), tole(0xdbe1ebe6L), tole(0xe681c256L),\ntole(0x54a11e46L), tole(0x69c137f6L), tole(0x2e614d26L), tole(0x13016496L),\ntole(0x9151f347L), tole(0xac31daf7L), tole(0xeb91a027L), tole(0xd6f18997L),\ntole(0x64d15587L), tole(0x59b17c37L), tole(0x1e1106e7L), tole(0x23712f57L),\ntole(0x58f35849L), tole(0x659371f9L), tole(0x22330b29L), tole(0x1f532299L),\ntole(0xad73fe89L), tole(0x9013d739L), tole(0xd7b3ade9L), tole(0xead38459L),\ntole(0x68831388L), tole(0x55e33a38L), tole(0x124340e8L), tole(0x2f236958L),\ntole(0x9d03b548L), tole(0xa0639cf8L), tole(0xe7c3e628L), tole(0xdaa3cf98L),\ntole(0x3813cfcbL), tole(0x0573e67bL), tole(0x42d39cabL), tole(0x7fb3b51bL),\ntole(0xcd93690bL), tole(0xf0f340bbL), tole(0xb7533a6bL), tole(0x8a3313dbL),\ntole(0x0863840aL), tole(0x3503adbaL), tole(0x72a3d76aL), tole(0x4fc3fedaL),\ntole(0xfde322caL), tole(0xc0830b7aL), tole(0x872371aaL), tole(0xba43581aL),\ntole(0x9932774dL), tole(0xa4525efdL), tole(0xe3f2242dL), tole(0xde920d9dL),\ntole(0x6cb2d18dL), tole(0x51d2f83dL), tole(0x167282edL), tole(0x2b12ab5dL),\ntole(0xa9423c8cL), tole(0x9422153cL), tole(0xd3826fecL), tole(0xeee2465cL),\ntole(0x5cc29a4cL), tole(0x61a2b3fcL), tole(0x2602c92cL), tole(0x1b62e09cL),\ntole(0xf9d2e0cfL), tole(0xc4b2c97fL), tole(0x8312b3afL), tole(0xbe729a1fL),\ntole(0x0c52460fL), tole(0x31326fbfL), tole(0x7692156fL), tole(0x4bf23cdfL),\ntole(0xc9a2ab0eL), tole(0xf4c282beL), tole(0xb362f86eL), tole(0x8e02d1deL),\ntole(0x3c220dceL), tole(0x0142247eL), tole(0x46e25eaeL), tole(0x7b82771eL),\ntole(0xb1e6b092L), tole(0x8c869922L), tole(0xcb26e3f2L), tole(0xf646ca42L),\ntole(0x44661652L), tole(0x79063fe2L), tole(0x3ea64532L), tole(0x03c66c82L),\ntole(0x8196fb53L), tole(0xbcf6d2e3L), tole(0xfb56a833L), tole(0xc6368183L),\ntole(0x74165d93L), tole(0x49767423L), tole(0x0ed60ef3L), tole(0x33b62743L),\ntole(0xd1062710L), tole(0xec660ea0L), tole(0xabc67470L), tole(0x96a65dc0L),\ntole(0x248681d0L), tole(0x19e6a860L), tole(0x5e46d2b0L), tole(0x6326fb00L),\ntole(0xe1766cd1L), tole(0xdc164561L), tole(0x9bb63fb1L), tole(0xa6d61601L),\ntole(0x14f6ca11L), tole(0x2996e3a1L), tole(0x6e369971L), tole(0x5356b0c1L),\ntole(0x70279f96L), tole(0x4d47b626L), tole(0x0ae7ccf6L), tole(0x3787e546L),\ntole(0x85a73956L), tole(0xb8c710e6L), tole(0xff676a36L), tole(0xc2074386L),\ntole(0x4057d457L), tole(0x7d37fde7L), tole(0x3a978737L), tole(0x07f7ae87L),\ntole(0xb5d77297L), tole(0x88b75b27L), tole(0xcf1721f7L), tole(0xf2770847L),\ntole(0x10c70814L), tole(0x2da721a4L), tole(0x6a075b74L), tole(0x576772c4L),\ntole(0xe547aed4L), tole(0xd8278764L), tole(0x9f87fdb4L), tole(0xa2e7d404L),\ntole(0x20b743d5L), tole(0x1dd76a65L), tole(0x5a7710b5L), tole(0x67173905L),\ntole(0xd537e515L), tole(0xe857cca5L), tole(0xaff7b675L), tole(0x92979fc5L),\ntole(0xe915e8dbL), tole(0xd475c16bL), tole(0x93d5bbbbL), tole(0xaeb5920bL),\ntole(0x1c954e1bL), tole(0x21f567abL), tole(0x66551d7bL), tole(0x5b3534cbL),\ntole(0xd965a31aL), tole(0xe4058aaaL), tole(0xa3a5f07aL), tole(0x9ec5d9caL),\ntole(0x2ce505daL), tole(0x11852c6aL), tole(0x562556baL), tole(0x6b457f0aL),\ntole(0x89f57f59L), tole(0xb49556e9L), tole(0xf3352c39L), tole(0xce550589L),\ntole(0x7c75d999L), tole(0x4115f029L), tole(0x06b58af9L), tole(0x3bd5a349L),\ntole(0xb9853498L), tole(0x84e51d28L), tole(0xc34567f8L), tole(0xfe254e48L),\ntole(0x4c059258L), tole(0x7165bbe8L), tole(0x36c5c138L), tole(0x0ba5e888L),\ntole(0x28d4c7dfL), tole(0x15b4ee6fL), tole(0x521494bfL), tole(0x6f74bd0fL),\ntole(0xdd54611fL), tole(0xe03448afL), tole(0xa794327fL), tole(0x9af41bcfL),\ntole(0x18a48c1eL), tole(0x25c4a5aeL), tole(0x6264df7eL), tole(0x5f04f6ceL),\ntole(0xed242adeL), tole(0xd044036eL), tole(0x97e479beL), tole(0xaa84500eL),\ntole(0x4834505dL), tole(0x755479edL), tole(0x32f4033dL), tole(0x0f942a8dL),\ntole(0xbdb4f69dL), tole(0x80d4df2dL), tole(0xc774a5fdL), tole(0xfa148c4dL),\ntole(0x78441b9cL), tole(0x4524322cL), tole(0x028448fcL), tole(0x3fe4614cL),\ntole(0x8dc4bd5cL), tole(0xb0a494ecL), tole(0xf704ee3cL), tole(0xca64c78cL)},\n{\ntole(0x00000000L), tole(0xcb5cd3a5L), tole(0x4dc8a10bL), tole(0x869472aeL),\ntole(0x9b914216L), tole(0x50cd91b3L), tole(0xd659e31dL), tole(0x1d0530b8L),\ntole(0xec53826dL), tole(0x270f51c8L), tole(0xa19b2366L), tole(0x6ac7f0c3L),\ntole(0x77c2c07bL), tole(0xbc9e13deL), tole(0x3a0a6170L), tole(0xf156b2d5L),\ntole(0x03d6029bL), tole(0xc88ad13eL), tole(0x4e1ea390L), tole(0x85427035L),\ntole(0x9847408dL), tole(0x531b9328L), tole(0xd58fe186L), tole(0x1ed33223L),\ntole(0xef8580f6L), tole(0x24d95353L), tole(0xa24d21fdL), tole(0x6911f258L),\ntole(0x7414c2e0L), tole(0xbf481145L), tole(0x39dc63ebL), tole(0xf280b04eL),\ntole(0x07ac0536L), tole(0xccf0d693L), tole(0x4a64a43dL), tole(0x81387798L),\ntole(0x9c3d4720L), tole(0x57619485L), tole(0xd1f5e62bL), tole(0x1aa9358eL),\ntole(0xebff875bL), tole(0x20a354feL), tole(0xa6372650L), tole(0x6d6bf5f5L),\ntole(0x706ec54dL), tole(0xbb3216e8L), tole(0x3da66446L), tole(0xf6fab7e3L),\ntole(0x047a07adL), tole(0xcf26d408L), tole(0x49b2a6a6L), tole(0x82ee7503L),\ntole(0x9feb45bbL), tole(0x54b7961eL), tole(0xd223e4b0L), tole(0x197f3715L),\ntole(0xe82985c0L), tole(0x23755665L), tole(0xa5e124cbL), tole(0x6ebdf76eL),\ntole(0x73b8c7d6L), tole(0xb8e41473L), tole(0x3e7066ddL), tole(0xf52cb578L),\ntole(0x0f580a6cL), tole(0xc404d9c9L), tole(0x4290ab67L), tole(0x89cc78c2L),\ntole(0x94c9487aL), tole(0x5f959bdfL), tole(0xd901e971L), tole(0x125d3ad4L),\ntole(0xe30b8801L), tole(0x28575ba4L), tole(0xaec3290aL), tole(0x659ffaafL),\ntole(0x789aca17L), tole(0xb3c619b2L), tole(0x35526b1cL), tole(0xfe0eb8b9L),\ntole(0x0c8e08f7L), tole(0xc7d2db52L), tole(0x4146a9fcL), tole(0x8a1a7a59L),\ntole(0x971f4ae1L), tole(0x5c439944L), tole(0xdad7ebeaL), tole(0x118b384fL),\ntole(0xe0dd8a9aL), tole(0x2b81593fL), tole(0xad152b91L), tole(0x6649f834L),\ntole(0x7b4cc88cL), tole(0xb0101b29L), tole(0x36846987L), tole(0xfdd8ba22L),\ntole(0x08f40f5aL), tole(0xc3a8dcffL), tole(0x453cae51L), tole(0x8e607df4L),\ntole(0x93654d4cL), tole(0x58399ee9L), tole(0xdeadec47L), tole(0x15f13fe2L),\ntole(0xe4a78d37L), tole(0x2ffb5e92L), tole(0xa96f2c3cL), tole(0x6233ff99L),\ntole(0x7f36cf21L), tole(0xb46a1c84L), tole(0x32fe6e2aL), tole(0xf9a2bd8fL),\ntole(0x0b220dc1L), tole(0xc07ede64L), tole(0x46eaaccaL), tole(0x8db67f6fL),\ntole(0x90b34fd7L), tole(0x5bef9c72L), tole(0xdd7beedcL), tole(0x16273d79L),\ntole(0xe7718facL), tole(0x2c2d5c09L), tole(0xaab92ea7L), tole(0x61e5fd02L),\ntole(0x7ce0cdbaL), tole(0xb7bc1e1fL), tole(0x31286cb1L), tole(0xfa74bf14L),\ntole(0x1eb014d8L), tole(0xd5ecc77dL), tole(0x5378b5d3L), tole(0x98246676L),\ntole(0x852156ceL), tole(0x4e7d856bL), tole(0xc8e9f7c5L), tole(0x03b52460L),\ntole(0xf2e396b5L), tole(0x39bf4510L), tole(0xbf2b37beL), tole(0x7477e41bL),\ntole(0x6972d4a3L), tole(0xa22e0706L), tole(0x24ba75a8L), tole(0xefe6a60dL),\ntole(0x1d661643L), tole(0xd63ac5e6L), tole(0x50aeb748L), tole(0x9bf264edL),\ntole(0x86f75455L), tole(0x4dab87f0L), tole(0xcb3ff55eL), tole(0x006326fbL),\ntole(0xf135942eL), tole(0x3a69478bL), tole(0xbcfd3525L), tole(0x77a1e680L),\ntole(0x6aa4d638L), tole(0xa1f8059dL), tole(0x276c7733L), tole(0xec30a496L),\ntole(0x191c11eeL), tole(0xd240c24bL), tole(0x54d4b0e5L), tole(0x9f886340L),\ntole(0x828d53f8L), tole(0x49d1805dL), tole(0xcf45f2f3L), tole(0x04192156L),\ntole(0xf54f9383L), tole(0x3e134026L), tole(0xb8873288L), tole(0x73dbe12dL),\ntole(0x6eded195L), tole(0xa5820230L), tole(0x2316709eL), tole(0xe84aa33bL),\ntole(0x1aca1375L), tole(0xd196c0d0L), tole(0x5702b27eL), tole(0x9c5e61dbL),\ntole(0x815b5163L), tole(0x4a0782c6L), tole(0xcc93f068L), tole(0x07cf23cdL),\ntole(0xf6999118L), tole(0x3dc542bdL), tole(0xbb513013L), tole(0x700de3b6L),\ntole(0x6d08d30eL), tole(0xa65400abL), tole(0x20c07205L), tole(0xeb9ca1a0L),\ntole(0x11e81eb4L), tole(0xdab4cd11L), tole(0x5c20bfbfL), tole(0x977c6c1aL),\ntole(0x8a795ca2L), tole(0x41258f07L), tole(0xc7b1fda9L), tole(0x0ced2e0cL),\ntole(0xfdbb9cd9L), tole(0x36e74f7cL), tole(0xb0733dd2L), tole(0x7b2fee77L),\ntole(0x662adecfL), tole(0xad760d6aL), tole(0x2be27fc4L), tole(0xe0beac61L),\ntole(0x123e1c2fL), tole(0xd962cf8aL), tole(0x5ff6bd24L), tole(0x94aa6e81L),\ntole(0x89af5e39L), tole(0x42f38d9cL), tole(0xc467ff32L), tole(0x0f3b2c97L),\ntole(0xfe6d9e42L), tole(0x35314de7L), tole(0xb3a53f49L), tole(0x78f9ececL),\ntole(0x65fcdc54L), tole(0xaea00ff1L), tole(0x28347d5fL), tole(0xe368aefaL),\ntole(0x16441b82L), tole(0xdd18c827L), tole(0x5b8cba89L), tole(0x90d0692cL),\ntole(0x8dd55994L), tole(0x46898a31L), tole(0xc01df89fL), tole(0x0b412b3aL),\ntole(0xfa1799efL), tole(0x314b4a4aL), tole(0xb7df38e4L), tole(0x7c83eb41L),\ntole(0x6186dbf9L), tole(0xaada085cL), tole(0x2c4e7af2L), tole(0xe712a957L),\ntole(0x15921919L), tole(0xdececabcL), tole(0x585ab812L), tole(0x93066bb7L),\ntole(0x8e035b0fL), tole(0x455f88aaL), tole(0xc3cbfa04L), tole(0x089729a1L),\ntole(0xf9c19b74L), tole(0x329d48d1L), tole(0xb4093a7fL), tole(0x7f55e9daL),\ntole(0x6250d962L), tole(0xa90c0ac7L), tole(0x2f987869L), tole(0xe4c4abccL)},\n{\ntole(0x00000000L), tole(0xa6770bb4L), tole(0x979f1129L), tole(0x31e81a9dL),\ntole(0xf44f2413L), tole(0x52382fa7L), tole(0x63d0353aL), tole(0xc5a73e8eL),\ntole(0x33ef4e67L), tole(0x959845d3L), tole(0xa4705f4eL), tole(0x020754faL),\ntole(0xc7a06a74L), tole(0x61d761c0L), tole(0x503f7b5dL), tole(0xf64870e9L),\ntole(0x67de9cceL), tole(0xc1a9977aL), tole(0xf0418de7L), tole(0x56368653L),\ntole(0x9391b8ddL), tole(0x35e6b369L), tole(0x040ea9f4L), tole(0xa279a240L),\ntole(0x5431d2a9L), tole(0xf246d91dL), tole(0xc3aec380L), tole(0x65d9c834L),\ntole(0xa07ef6baL), tole(0x0609fd0eL), tole(0x37e1e793L), tole(0x9196ec27L),\ntole(0xcfbd399cL), tole(0x69ca3228L), tole(0x582228b5L), tole(0xfe552301L),\ntole(0x3bf21d8fL), tole(0x9d85163bL), tole(0xac6d0ca6L), tole(0x0a1a0712L),\ntole(0xfc5277fbL), tole(0x5a257c4fL), tole(0x6bcd66d2L), tole(0xcdba6d66L),\ntole(0x081d53e8L), tole(0xae6a585cL), tole(0x9f8242c1L), tole(0x39f54975L),\ntole(0xa863a552L), tole(0x0e14aee6L), tole(0x3ffcb47bL), tole(0x998bbfcfL),\ntole(0x5c2c8141L), tole(0xfa5b8af5L), tole(0xcbb39068L), tole(0x6dc49bdcL),\ntole(0x9b8ceb35L), tole(0x3dfbe081L), tole(0x0c13fa1cL), tole(0xaa64f1a8L),\ntole(0x6fc3cf26L), tole(0xc9b4c492L), tole(0xf85cde0fL), tole(0x5e2bd5bbL),\ntole(0x440b7579L), tole(0xe27c7ecdL), tole(0xd3946450L), tole(0x75e36fe4L),\ntole(0xb044516aL), tole(0x16335adeL), tole(0x27db4043L), tole(0x81ac4bf7L),\ntole(0x77e43b1eL), tole(0xd19330aaL), tole(0xe07b2a37L), tole(0x460c2183L),\ntole(0x83ab1f0dL), tole(0x25dc14b9L), tole(0x14340e24L), tole(0xb2430590L),\ntole(0x23d5e9b7L), tole(0x85a2e203L), tole(0xb44af89eL), tole(0x123df32aL),\ntole(0xd79acda4L), tole(0x71edc610L), tole(0x4005dc8dL), tole(0xe672d739L),\ntole(0x103aa7d0L), tole(0xb64dac64L), tole(0x87a5b6f9L), tole(0x21d2bd4dL),\ntole(0xe47583c3L), tole(0x42028877L), tole(0x73ea92eaL), tole(0xd59d995eL),\ntole(0x8bb64ce5L), tole(0x2dc14751L), tole(0x1c295dccL), tole(0xba5e5678L),\ntole(0x7ff968f6L), tole(0xd98e6342L), tole(0xe86679dfL), tole(0x4e11726bL),\ntole(0xb8590282L), tole(0x1e2e0936L), tole(0x2fc613abL), tole(0x89b1181fL),\ntole(0x4c162691L), tole(0xea612d25L), tole(0xdb8937b8L), tole(0x7dfe3c0cL),\ntole(0xec68d02bL), tole(0x4a1fdb9fL), tole(0x7bf7c102L), tole(0xdd80cab6L),\ntole(0x1827f438L), tole(0xbe50ff8cL), tole(0x8fb8e511L), tole(0x29cfeea5L),\ntole(0xdf879e4cL), tole(0x79f095f8L), tole(0x48188f65L), tole(0xee6f84d1L),\ntole(0x2bc8ba5fL), tole(0x8dbfb1ebL), tole(0xbc57ab76L), tole(0x1a20a0c2L),\ntole(0x8816eaf2L), tole(0x2e61e146L), tole(0x1f89fbdbL), tole(0xb9fef06fL),\ntole(0x7c59cee1L), tole(0xda2ec555L), tole(0xebc6dfc8L), tole(0x4db1d47cL),\ntole(0xbbf9a495L), tole(0x1d8eaf21L), tole(0x2c66b5bcL), tole(0x8a11be08L),\ntole(0x4fb68086L), tole(0xe9c18b32L), tole(0xd82991afL), tole(0x7e5e9a1bL),\ntole(0xefc8763cL), tole(0x49bf7d88L), tole(0x78576715L), tole(0xde206ca1L),\ntole(0x1b87522fL), tole(0xbdf0599bL), tole(0x8c184306L), tole(0x2a6f48b2L),\ntole(0xdc27385bL), tole(0x7a5033efL), tole(0x4bb82972L), tole(0xedcf22c6L),\ntole(0x28681c48L), tole(0x8e1f17fcL), tole(0xbff70d61L), tole(0x198006d5L),\ntole(0x47abd36eL), tole(0xe1dcd8daL), tole(0xd034c247L), tole(0x7643c9f3L),\ntole(0xb3e4f77dL), tole(0x1593fcc9L), tole(0x247be654L), tole(0x820cede0L),\ntole(0x74449d09L), tole(0xd23396bdL), tole(0xe3db8c20L), tole(0x45ac8794L),\ntole(0x800bb91aL), tole(0x267cb2aeL), tole(0x1794a833L), tole(0xb1e3a387L),\ntole(0x20754fa0L), tole(0x86024414L), tole(0xb7ea5e89L), tole(0x119d553dL),\ntole(0xd43a6bb3L), tole(0x724d6007L), tole(0x43a57a9aL), tole(0xe5d2712eL),\ntole(0x139a01c7L), tole(0xb5ed0a73L), tole(0x840510eeL), tole(0x22721b5aL),\ntole(0xe7d525d4L), tole(0x41a22e60L), tole(0x704a34fdL), tole(0xd63d3f49L),\ntole(0xcc1d9f8bL), tole(0x6a6a943fL), tole(0x5b828ea2L), tole(0xfdf58516L),\ntole(0x3852bb98L), tole(0x9e25b02cL), tole(0xafcdaab1L), tole(0x09baa105L),\ntole(0xfff2d1ecL), tole(0x5985da58L), tole(0x686dc0c5L), tole(0xce1acb71L),\ntole(0x0bbdf5ffL), tole(0xadcafe4bL), tole(0x9c22e4d6L), tole(0x3a55ef62L),\ntole(0xabc30345L), tole(0x0db408f1L), tole(0x3c5c126cL), tole(0x9a2b19d8L),\ntole(0x5f8c2756L), tole(0xf9fb2ce2L), tole(0xc813367fL), tole(0x6e643dcbL),\ntole(0x982c4d22L), tole(0x3e5b4696L), tole(0x0fb35c0bL), tole(0xa9c457bfL),\ntole(0x6c636931L), tole(0xca146285L), tole(0xfbfc7818L), tole(0x5d8b73acL),\ntole(0x03a0a617L), tole(0xa5d7ada3L), tole(0x943fb73eL), tole(0x3248bc8aL),\ntole(0xf7ef8204L), tole(0x519889b0L), tole(0x6070932dL), tole(0xc6079899L),\ntole(0x304fe870L), tole(0x9638e3c4L), tole(0xa7d0f959L), tole(0x01a7f2edL),\ntole(0xc400cc63L), tole(0x6277c7d7L), tole(0x539fdd4aL), tole(0xf5e8d6feL),\ntole(0x647e3ad9L), tole(0xc209316dL), tole(0xf3e12bf0L), tole(0x55962044L),\ntole(0x90311ecaL), tole(0x3646157eL), tole(0x07ae0fe3L), tole(0xa1d90457L),\ntole(0x579174beL), tole(0xf1e67f0aL), tole(0xc00e6597L), tole(0x66796e23L),\ntole(0xa3de50adL), tole(0x05a95b19L), tole(0x34414184L), tole(0x92364a30L)},\n{\ntole(0x00000000L), tole(0xccaa009eL), tole(0x4225077dL), tole(0x8e8f07e3L),\ntole(0x844a0efaL), tole(0x48e00e64L), tole(0xc66f0987L), tole(0x0ac50919L),\ntole(0xd3e51bb5L), tole(0x1f4f1b2bL), tole(0x91c01cc8L), tole(0x5d6a1c56L),\ntole(0x57af154fL), tole(0x9b0515d1L), tole(0x158a1232L), tole(0xd92012acL),\ntole(0x7cbb312bL), tole(0xb01131b5L), tole(0x3e9e3656L), tole(0xf23436c8L),\ntole(0xf8f13fd1L), tole(0x345b3f4fL), tole(0xbad438acL), tole(0x767e3832L),\ntole(0xaf5e2a9eL), tole(0x63f42a00L), tole(0xed7b2de3L), tole(0x21d12d7dL),\ntole(0x2b142464L), tole(0xe7be24faL), tole(0x69312319L), tole(0xa59b2387L),\ntole(0xf9766256L), tole(0x35dc62c8L), tole(0xbb53652bL), tole(0x77f965b5L),\ntole(0x7d3c6cacL), tole(0xb1966c32L), tole(0x3f196bd1L), tole(0xf3b36b4fL),\ntole(0x2a9379e3L), tole(0xe639797dL), tole(0x68b67e9eL), tole(0xa41c7e00L),\ntole(0xaed97719L), tole(0x62737787L), tole(0xecfc7064L), tole(0x205670faL),\ntole(0x85cd537dL), tole(0x496753e3L), tole(0xc7e85400L), tole(0x0b42549eL),\ntole(0x01875d87L), tole(0xcd2d5d19L), tole(0x43a25afaL), tole(0x8f085a64L),\ntole(0x562848c8L), tole(0x9a824856L), tole(0x140d4fb5L), tole(0xd8a74f2bL),\ntole(0xd2624632L), tole(0x1ec846acL), tole(0x9047414fL), tole(0x5ced41d1L),\ntole(0x299dc2edL), tole(0xe537c273L), tole(0x6bb8c590L), tole(0xa712c50eL),\ntole(0xadd7cc17L), tole(0x617dcc89L), tole(0xeff2cb6aL), tole(0x2358cbf4L),\ntole(0xfa78d958L), tole(0x36d2d9c6L), tole(0xb85dde25L), tole(0x74f7debbL),\ntole(0x7e32d7a2L), tole(0xb298d73cL), tole(0x3c17d0dfL), tole(0xf0bdd041L),\ntole(0x5526f3c6L), tole(0x998cf358L), tole(0x1703f4bbL), tole(0xdba9f425L),\ntole(0xd16cfd3cL), tole(0x1dc6fda2L), tole(0x9349fa41L), tole(0x5fe3fadfL),\ntole(0x86c3e873L), tole(0x4a69e8edL), tole(0xc4e6ef0eL), tole(0x084cef90L),\ntole(0x0289e689L), tole(0xce23e617L), tole(0x40ace1f4L), tole(0x8c06e16aL),\ntole(0xd0eba0bbL), tole(0x1c41a025L), tole(0x92cea7c6L), tole(0x5e64a758L),\ntole(0x54a1ae41L), tole(0x980baedfL), tole(0x1684a93cL), tole(0xda2ea9a2L),\ntole(0x030ebb0eL), tole(0xcfa4bb90L), tole(0x412bbc73L), tole(0x8d81bcedL),\ntole(0x8744b5f4L), tole(0x4beeb56aL), tole(0xc561b289L), tole(0x09cbb217L),\ntole(0xac509190L), tole(0x60fa910eL), tole(0xee7596edL), tole(0x22df9673L),\ntole(0x281a9f6aL), tole(0xe4b09ff4L), tole(0x6a3f9817L), tole(0xa6959889L),\ntole(0x7fb58a25L), tole(0xb31f8abbL), tole(0x3d908d58L), tole(0xf13a8dc6L),\ntole(0xfbff84dfL), tole(0x37558441L), tole(0xb9da83a2L), tole(0x7570833cL),\ntole(0x533b85daL), tole(0x9f918544L), tole(0x111e82a7L), tole(0xddb48239L),\ntole(0xd7718b20L), tole(0x1bdb8bbeL), tole(0x95548c5dL), tole(0x59fe8cc3L),\ntole(0x80de9e6fL), tole(0x4c749ef1L), tole(0xc2fb9912L), tole(0x0e51998cL),\ntole(0x04949095L), tole(0xc83e900bL), tole(0x46b197e8L), tole(0x8a1b9776L),\ntole(0x2f80b4f1L), tole(0xe32ab46fL), tole(0x6da5b38cL), tole(0xa10fb312L),\ntole(0xabcaba0bL), tole(0x6760ba95L), tole(0xe9efbd76L), tole(0x2545bde8L),\ntole(0xfc65af44L), tole(0x30cfafdaL), tole(0xbe40a839L), tole(0x72eaa8a7L),\ntole(0x782fa1beL), tole(0xb485a120L), tole(0x3a0aa6c3L), tole(0xf6a0a65dL),\ntole(0xaa4de78cL), tole(0x66e7e712L), tole(0xe868e0f1L), tole(0x24c2e06fL),\ntole(0x2e07e976L), tole(0xe2ade9e8L), tole(0x6c22ee0bL), tole(0xa088ee95L),\ntole(0x79a8fc39L), tole(0xb502fca7L), tole(0x3b8dfb44L), tole(0xf727fbdaL),\ntole(0xfde2f2c3L), tole(0x3148f25dL), tole(0xbfc7f5beL), tole(0x736df520L),\ntole(0xd6f6d6a7L), tole(0x1a5cd639L), tole(0x94d3d1daL), tole(0x5879d144L),\ntole(0x52bcd85dL), tole(0x9e16d8c3L), tole(0x1099df20L), tole(0xdc33dfbeL),\ntole(0x0513cd12L), tole(0xc9b9cd8cL), tole(0x4736ca6fL), tole(0x8b9ccaf1L),\ntole(0x8159c3e8L), tole(0x4df3c376L), tole(0xc37cc495L), tole(0x0fd6c40bL),\ntole(0x7aa64737L), tole(0xb60c47a9L), tole(0x3883404aL), tole(0xf42940d4L),\ntole(0xfeec49cdL), tole(0x32464953L), tole(0xbcc94eb0L), tole(0x70634e2eL),\ntole(0xa9435c82L), tole(0x65e95c1cL), tole(0xeb665bffL), tole(0x27cc5b61L),\ntole(0x2d095278L), tole(0xe1a352e6L), tole(0x6f2c5505L), tole(0xa386559bL),\ntole(0x061d761cL), tole(0xcab77682L), tole(0x44387161L), tole(0x889271ffL),\ntole(0x825778e6L), tole(0x4efd7878L), tole(0xc0727f9bL), tole(0x0cd87f05L),\ntole(0xd5f86da9L), tole(0x19526d37L), tole(0x97dd6ad4L), tole(0x5b776a4aL),\ntole(0x51b26353L), tole(0x9d1863cdL), tole(0x1397642eL), tole(0xdf3d64b0L),\ntole(0x83d02561L), tole(0x4f7a25ffL), tole(0xc1f5221cL), tole(0x0d5f2282L),\ntole(0x079a2b9bL), tole(0xcb302b05L), tole(0x45bf2ce6L), tole(0x89152c78L),\ntole(0x50353ed4L), tole(0x9c9f3e4aL), tole(0x121039a9L), tole(0xdeba3937L),\ntole(0xd47f302eL), tole(0x18d530b0L), tole(0x965a3753L), tole(0x5af037cdL),\ntole(0xff6b144aL), tole(0x33c114d4L), tole(0xbd4e1337L), tole(0x71e413a9L),\ntole(0x7b211ab0L), tole(0xb78b1a2eL), tole(0x39041dcdL), tole(0xf5ae1d53L),\ntole(0x2c8e0fffL), tole(0xe0240f61L), tole(0x6eab0882L), tole(0xa201081cL),\ntole(0xa8c40105L), tole(0x646e019bL), tole(0xeae10678L), tole(0x264b06e6L)},\n};\n\nstatic uint32_t __attribute__((__aligned__(8))) crc32table_be[8][256] = {{\ntobe(0x00000000L), tobe(0x04c11db7L), tobe(0x09823b6eL), tobe(0x0d4326d9L),\ntobe(0x130476dcL), tobe(0x17c56b6bL), tobe(0x1a864db2L), tobe(0x1e475005L),\ntobe(0x2608edb8L), tobe(0x22c9f00fL), tobe(0x2f8ad6d6L), tobe(0x2b4bcb61L),\ntobe(0x350c9b64L), tobe(0x31cd86d3L), tobe(0x3c8ea00aL), tobe(0x384fbdbdL),\ntobe(0x4c11db70L), tobe(0x48d0c6c7L), tobe(0x4593e01eL), tobe(0x4152fda9L),\ntobe(0x5f15adacL), tobe(0x5bd4b01bL), tobe(0x569796c2L), tobe(0x52568b75L),\ntobe(0x6a1936c8L), tobe(0x6ed82b7fL), tobe(0x639b0da6L), tobe(0x675a1011L),\ntobe(0x791d4014L), tobe(0x7ddc5da3L), tobe(0x709f7b7aL), tobe(0x745e66cdL),\ntobe(0x9823b6e0L), tobe(0x9ce2ab57L), tobe(0x91a18d8eL), tobe(0x95609039L),\ntobe(0x8b27c03cL), tobe(0x8fe6dd8bL), tobe(0x82a5fb52L), tobe(0x8664e6e5L),\ntobe(0xbe2b5b58L), tobe(0xbaea46efL), tobe(0xb7a96036L), tobe(0xb3687d81L),\ntobe(0xad2f2d84L), tobe(0xa9ee3033L), tobe(0xa4ad16eaL), tobe(0xa06c0b5dL),\ntobe(0xd4326d90L), tobe(0xd0f37027L), tobe(0xddb056feL), tobe(0xd9714b49L),\ntobe(0xc7361b4cL), tobe(0xc3f706fbL), tobe(0xceb42022L), tobe(0xca753d95L),\ntobe(0xf23a8028L), tobe(0xf6fb9d9fL), tobe(0xfbb8bb46L), tobe(0xff79a6f1L),\ntobe(0xe13ef6f4L), tobe(0xe5ffeb43L), tobe(0xe8bccd9aL), tobe(0xec7dd02dL),\ntobe(0x34867077L), tobe(0x30476dc0L), tobe(0x3d044b19L), tobe(0x39c556aeL),\ntobe(0x278206abL), tobe(0x23431b1cL), tobe(0x2e003dc5L), tobe(0x2ac12072L),\ntobe(0x128e9dcfL), tobe(0x164f8078L), tobe(0x1b0ca6a1L), tobe(0x1fcdbb16L),\ntobe(0x018aeb13L), tobe(0x054bf6a4L), tobe(0x0808d07dL), tobe(0x0cc9cdcaL),\ntobe(0x7897ab07L), tobe(0x7c56b6b0L), tobe(0x71159069L), tobe(0x75d48ddeL),\ntobe(0x6b93dddbL), tobe(0x6f52c06cL), tobe(0x6211e6b5L), tobe(0x66d0fb02L),\ntobe(0x5e9f46bfL), tobe(0x5a5e5b08L), tobe(0x571d7dd1L), tobe(0x53dc6066L),\ntobe(0x4d9b3063L), tobe(0x495a2dd4L), tobe(0x44190b0dL), tobe(0x40d816baL),\ntobe(0xaca5c697L), tobe(0xa864db20L), tobe(0xa527fdf9L), tobe(0xa1e6e04eL),\ntobe(0xbfa1b04bL), tobe(0xbb60adfcL), tobe(0xb6238b25L), tobe(0xb2e29692L),\ntobe(0x8aad2b2fL), tobe(0x8e6c3698L), tobe(0x832f1041L), tobe(0x87ee0df6L),\ntobe(0x99a95df3L), tobe(0x9d684044L), tobe(0x902b669dL), tobe(0x94ea7b2aL),\ntobe(0xe0b41de7L), tobe(0xe4750050L), tobe(0xe9362689L), tobe(0xedf73b3eL),\ntobe(0xf3b06b3bL), tobe(0xf771768cL), tobe(0xfa325055L), tobe(0xfef34de2L),\ntobe(0xc6bcf05fL), tobe(0xc27dede8L), tobe(0xcf3ecb31L), tobe(0xcbffd686L),\ntobe(0xd5b88683L), tobe(0xd1799b34L), tobe(0xdc3abdedL), tobe(0xd8fba05aL),\ntobe(0x690ce0eeL), tobe(0x6dcdfd59L), tobe(0x608edb80L), tobe(0x644fc637L),\ntobe(0x7a089632L), tobe(0x7ec98b85L), tobe(0x738aad5cL), tobe(0x774bb0ebL),\ntobe(0x4f040d56L), tobe(0x4bc510e1L), tobe(0x46863638L), tobe(0x42472b8fL),\ntobe(0x5c007b8aL), tobe(0x58c1663dL), tobe(0x558240e4L), tobe(0x51435d53L),\ntobe(0x251d3b9eL), tobe(0x21dc2629L), tobe(0x2c9f00f0L), tobe(0x285e1d47L),\ntobe(0x36194d42L), tobe(0x32d850f5L), tobe(0x3f9b762cL), tobe(0x3b5a6b9bL),\ntobe(0x0315d626L), tobe(0x07d4cb91L), tobe(0x0a97ed48L), tobe(0x0e56f0ffL),\ntobe(0x1011a0faL), tobe(0x14d0bd4dL), tobe(0x19939b94L), tobe(0x1d528623L),\ntobe(0xf12f560eL), tobe(0xf5ee4bb9L), tobe(0xf8ad6d60L), tobe(0xfc6c70d7L),\ntobe(0xe22b20d2L), tobe(0xe6ea3d65L), tobe(0xeba91bbcL), tobe(0xef68060bL),\ntobe(0xd727bbb6L), tobe(0xd3e6a601L), tobe(0xdea580d8L), tobe(0xda649d6fL),\ntobe(0xc423cd6aL), tobe(0xc0e2d0ddL), tobe(0xcda1f604L), tobe(0xc960ebb3L),\ntobe(0xbd3e8d7eL), tobe(0xb9ff90c9L), tobe(0xb4bcb610L), tobe(0xb07daba7L),\ntobe(0xae3afba2L), tobe(0xaafbe615L), tobe(0xa7b8c0ccL), tobe(0xa379dd7bL),\ntobe(0x9b3660c6L), tobe(0x9ff77d71L), tobe(0x92b45ba8L), tobe(0x9675461fL),\ntobe(0x8832161aL), tobe(0x8cf30badL), tobe(0x81b02d74L), tobe(0x857130c3L),\ntobe(0x5d8a9099L), tobe(0x594b8d2eL), tobe(0x5408abf7L), tobe(0x50c9b640L),\ntobe(0x4e8ee645L), tobe(0x4a4ffbf2L), tobe(0x470cdd2bL), tobe(0x43cdc09cL),\ntobe(0x7b827d21L), tobe(0x7f436096L), tobe(0x7200464fL), tobe(0x76c15bf8L),\ntobe(0x68860bfdL), tobe(0x6c47164aL), tobe(0x61043093L), tobe(0x65c52d24L),\ntobe(0x119b4be9L), tobe(0x155a565eL), tobe(0x18197087L), tobe(0x1cd86d30L),\ntobe(0x029f3d35L), tobe(0x065e2082L), tobe(0x0b1d065bL), tobe(0x0fdc1becL),\ntobe(0x3793a651L), tobe(0x3352bbe6L), tobe(0x3e119d3fL), tobe(0x3ad08088L),\ntobe(0x2497d08dL), tobe(0x2056cd3aL), tobe(0x2d15ebe3L), tobe(0x29d4f654L),\ntobe(0xc5a92679L), tobe(0xc1683bceL), tobe(0xcc2b1d17L), tobe(0xc8ea00a0L),\ntobe(0xd6ad50a5L), tobe(0xd26c4d12L), tobe(0xdf2f6bcbL), tobe(0xdbee767cL),\ntobe(0xe3a1cbc1L), tobe(0xe760d676L), tobe(0xea23f0afL), tobe(0xeee2ed18L),\ntobe(0xf0a5bd1dL), tobe(0xf464a0aaL), tobe(0xf9278673L), tobe(0xfde69bc4L),\ntobe(0x89b8fd09L), tobe(0x8d79e0beL), tobe(0x803ac667L), tobe(0x84fbdbd0L),\ntobe(0x9abc8bd5L), tobe(0x9e7d9662L), tobe(0x933eb0bbL), tobe(0x97ffad0cL),\ntobe(0xafb010b1L), tobe(0xab710d06L), tobe(0xa6322bdfL), tobe(0xa2f33668L),\ntobe(0xbcb4666dL), tobe(0xb8757bdaL), tobe(0xb5365d03L), tobe(0xb1f740b4L)},\n{\ntobe(0x00000000L), tobe(0xd219c1dcL), tobe(0xa0f29e0fL), tobe(0x72eb5fd3L),\ntobe(0x452421a9L), tobe(0x973de075L), tobe(0xe5d6bfa6L), tobe(0x37cf7e7aL),\ntobe(0x8a484352L), tobe(0x5851828eL), tobe(0x2abadd5dL), tobe(0xf8a31c81L),\ntobe(0xcf6c62fbL), tobe(0x1d75a327L), tobe(0x6f9efcf4L), tobe(0xbd873d28L),\ntobe(0x10519b13L), tobe(0xc2485acfL), tobe(0xb0a3051cL), tobe(0x62bac4c0L),\ntobe(0x5575babaL), tobe(0x876c7b66L), tobe(0xf58724b5L), tobe(0x279ee569L),\ntobe(0x9a19d841L), tobe(0x4800199dL), tobe(0x3aeb464eL), tobe(0xe8f28792L),\ntobe(0xdf3df9e8L), tobe(0x0d243834L), tobe(0x7fcf67e7L), tobe(0xadd6a63bL),\ntobe(0x20a33626L), tobe(0xf2baf7faL), tobe(0x8051a829L), tobe(0x524869f5L),\ntobe(0x6587178fL), tobe(0xb79ed653L), tobe(0xc5758980L), tobe(0x176c485cL),\ntobe(0xaaeb7574L), tobe(0x78f2b4a8L), tobe(0x0a19eb7bL), tobe(0xd8002aa7L),\ntobe(0xefcf54ddL), tobe(0x3dd69501L), tobe(0x4f3dcad2L), tobe(0x9d240b0eL),\ntobe(0x30f2ad35L), tobe(0xe2eb6ce9L), tobe(0x9000333aL), tobe(0x4219f2e6L),\ntobe(0x75d68c9cL), tobe(0xa7cf4d40L), tobe(0xd5241293L), tobe(0x073dd34fL),\ntobe(0xbabaee67L), tobe(0x68a32fbbL), tobe(0x1a487068L), tobe(0xc851b1b4L),\ntobe(0xff9ecfceL), tobe(0x2d870e12L), tobe(0x5f6c51c1L), tobe(0x8d75901dL),\ntobe(0x41466c4cL), tobe(0x935fad90L), tobe(0xe1b4f243L), tobe(0x33ad339fL),\ntobe(0x04624de5L), tobe(0xd67b8c39L), tobe(0xa490d3eaL), tobe(0x76891236L),\ntobe(0xcb0e2f1eL), tobe(0x1917eec2L), tobe(0x6bfcb111L), tobe(0xb9e570cdL),\ntobe(0x8e2a0eb7L), tobe(0x5c33cf6bL), tobe(0x2ed890b8L), tobe(0xfcc15164L),\ntobe(0x5117f75fL), tobe(0x830e3683L), tobe(0xf1e56950L), tobe(0x23fca88cL),\ntobe(0x1433d6f6L), tobe(0xc62a172aL), tobe(0xb4c148f9L), tobe(0x66d88925L),\ntobe(0xdb5fb40dL), tobe(0x094675d1L), tobe(0x7bad2a02L), tobe(0xa9b4ebdeL),\ntobe(0x9e7b95a4L), tobe(0x4c625478L), tobe(0x3e890babL), tobe(0xec90ca77L),\ntobe(0x61e55a6aL), tobe(0xb3fc9bb6L), tobe(0xc117c465L), tobe(0x130e05b9L),\ntobe(0x24c17bc3L), tobe(0xf6d8ba1fL), tobe(0x8433e5ccL), tobe(0x562a2410L),\ntobe(0xebad1938L), tobe(0x39b4d8e4L), tobe(0x4b5f8737L), tobe(0x994646ebL),\ntobe(0xae893891L), tobe(0x7c90f94dL), tobe(0x0e7ba69eL), tobe(0xdc626742L),\ntobe(0x71b4c179L), tobe(0xa3ad00a5L), tobe(0xd1465f76L), tobe(0x035f9eaaL),\ntobe(0x3490e0d0L), tobe(0xe689210cL), tobe(0x94627edfL), tobe(0x467bbf03L),\ntobe(0xfbfc822bL), tobe(0x29e543f7L), tobe(0x5b0e1c24L), tobe(0x8917ddf8L),\ntobe(0xbed8a382L), tobe(0x6cc1625eL), tobe(0x1e2a3d8dL), tobe(0xcc33fc51L),\ntobe(0x828cd898L), tobe(0x50951944L), tobe(0x227e4697L), tobe(0xf067874bL),\ntobe(0xc7a8f931L), tobe(0x15b138edL), tobe(0x675a673eL), tobe(0xb543a6e2L),\ntobe(0x08c49bcaL), tobe(0xdadd5a16L), tobe(0xa83605c5L), tobe(0x7a2fc419L),\ntobe(0x4de0ba63L), tobe(0x9ff97bbfL), tobe(0xed12246cL), tobe(0x3f0be5b0L),\ntobe(0x92dd438bL), tobe(0x40c48257L), tobe(0x322fdd84L), tobe(0xe0361c58L),\ntobe(0xd7f96222L), tobe(0x05e0a3feL), tobe(0x770bfc2dL), tobe(0xa5123df1L),\ntobe(0x189500d9L), tobe(0xca8cc105L), tobe(0xb8679ed6L), tobe(0x6a7e5f0aL),\ntobe(0x5db12170L), tobe(0x8fa8e0acL), tobe(0xfd43bf7fL), tobe(0x2f5a7ea3L),\ntobe(0xa22feebeL), tobe(0x70362f62L), tobe(0x02dd70b1L), tobe(0xd0c4b16dL),\ntobe(0xe70bcf17L), tobe(0x35120ecbL), tobe(0x47f95118L), tobe(0x95e090c4L),\ntobe(0x2867adecL), tobe(0xfa7e6c30L), tobe(0x889533e3L), tobe(0x5a8cf23fL),\ntobe(0x6d438c45L), tobe(0xbf5a4d99L), tobe(0xcdb1124aL), tobe(0x1fa8d396L),\ntobe(0xb27e75adL), tobe(0x6067b471L), tobe(0x128ceba2L), tobe(0xc0952a7eL),\ntobe(0xf75a5404L), tobe(0x254395d8L), tobe(0x57a8ca0bL), tobe(0x85b10bd7L),\ntobe(0x383636ffL), tobe(0xea2ff723L), tobe(0x98c4a8f0L), tobe(0x4add692cL),\ntobe(0x7d121756L), tobe(0xaf0bd68aL), tobe(0xdde08959L), tobe(0x0ff94885L),\ntobe(0xc3cab4d4L), tobe(0x11d37508L), tobe(0x63382adbL), tobe(0xb121eb07L),\ntobe(0x86ee957dL), tobe(0x54f754a1L), tobe(0x261c0b72L), tobe(0xf405caaeL),\ntobe(0x4982f786L), tobe(0x9b9b365aL), tobe(0xe9706989L), tobe(0x3b69a855L),\ntobe(0x0ca6d62fL), tobe(0xdebf17f3L), tobe(0xac544820L), tobe(0x7e4d89fcL),\ntobe(0xd39b2fc7L), tobe(0x0182ee1bL), tobe(0x7369b1c8L), tobe(0xa1707014L),\ntobe(0x96bf0e6eL), tobe(0x44a6cfb2L), tobe(0x364d9061L), tobe(0xe45451bdL),\ntobe(0x59d36c95L), tobe(0x8bcaad49L), tobe(0xf921f29aL), tobe(0x2b383346L),\ntobe(0x1cf74d3cL), tobe(0xceee8ce0L), tobe(0xbc05d333L), tobe(0x6e1c12efL),\ntobe(0xe36982f2L), tobe(0x3170432eL), tobe(0x439b1cfdL), tobe(0x9182dd21L),\ntobe(0xa64da35bL), tobe(0x74546287L), tobe(0x06bf3d54L), tobe(0xd4a6fc88L),\ntobe(0x6921c1a0L), tobe(0xbb38007cL), tobe(0xc9d35fafL), tobe(0x1bca9e73L),\ntobe(0x2c05e009L), tobe(0xfe1c21d5L), tobe(0x8cf77e06L), tobe(0x5eeebfdaL),\ntobe(0xf33819e1L), tobe(0x2121d83dL), tobe(0x53ca87eeL), tobe(0x81d34632L),\ntobe(0xb61c3848L), tobe(0x6405f994L), tobe(0x16eea647L), tobe(0xc4f7679bL),\ntobe(0x79705ab3L), tobe(0xab699b6fL), tobe(0xd982c4bcL), tobe(0x0b9b0560L),\ntobe(0x3c547b1aL), tobe(0xee4dbac6L), tobe(0x9ca6e515L), tobe(0x4ebf24c9L)},\n{\ntobe(0x00000000L), tobe(0x01d8ac87L), tobe(0x03b1590eL), tobe(0x0269f589L),\ntobe(0x0762b21cL), tobe(0x06ba1e9bL), tobe(0x04d3eb12L), tobe(0x050b4795L),\ntobe(0x0ec56438L), tobe(0x0f1dc8bfL), tobe(0x0d743d36L), tobe(0x0cac91b1L),\ntobe(0x09a7d624L), tobe(0x087f7aa3L), tobe(0x0a168f2aL), tobe(0x0bce23adL),\ntobe(0x1d8ac870L), tobe(0x1c5264f7L), tobe(0x1e3b917eL), tobe(0x1fe33df9L),\ntobe(0x1ae87a6cL), tobe(0x1b30d6ebL), tobe(0x19592362L), tobe(0x18818fe5L),\ntobe(0x134fac48L), tobe(0x129700cfL), tobe(0x10fef546L), tobe(0x112659c1L),\ntobe(0x142d1e54L), tobe(0x15f5b2d3L), tobe(0x179c475aL), tobe(0x1644ebddL),\ntobe(0x3b1590e0L), tobe(0x3acd3c67L), tobe(0x38a4c9eeL), tobe(0x397c6569L),\ntobe(0x3c7722fcL), tobe(0x3daf8e7bL), tobe(0x3fc67bf2L), tobe(0x3e1ed775L),\ntobe(0x35d0f4d8L), tobe(0x3408585fL), tobe(0x3661add6L), tobe(0x37b90151L),\ntobe(0x32b246c4L), tobe(0x336aea43L), tobe(0x31031fcaL), tobe(0x30dbb34dL),\ntobe(0x269f5890L), tobe(0x2747f417L), tobe(0x252e019eL), tobe(0x24f6ad19L),\ntobe(0x21fdea8cL), tobe(0x2025460bL), tobe(0x224cb382L), tobe(0x23941f05L),\ntobe(0x285a3ca8L), tobe(0x2982902fL), tobe(0x2beb65a6L), tobe(0x2a33c921L),\ntobe(0x2f388eb4L), tobe(0x2ee02233L), tobe(0x2c89d7baL), tobe(0x2d517b3dL),\ntobe(0x762b21c0L), tobe(0x77f38d47L), tobe(0x759a78ceL), tobe(0x7442d449L),\ntobe(0x714993dcL), tobe(0x70913f5bL), tobe(0x72f8cad2L), tobe(0x73206655L),\ntobe(0x78ee45f8L), tobe(0x7936e97fL), tobe(0x7b5f1cf6L), tobe(0x7a87b071L),\ntobe(0x7f8cf7e4L), tobe(0x7e545b63L), tobe(0x7c3daeeaL), tobe(0x7de5026dL),\ntobe(0x6ba1e9b0L), tobe(0x6a794537L), tobe(0x6810b0beL), tobe(0x69c81c39L),\ntobe(0x6cc35bacL), tobe(0x6d1bf72bL), tobe(0x6f7202a2L), tobe(0x6eaaae25L),\ntobe(0x65648d88L), tobe(0x64bc210fL), tobe(0x66d5d486L), tobe(0x670d7801L),\ntobe(0x62063f94L), tobe(0x63de9313L), tobe(0x61b7669aL), tobe(0x606fca1dL),\ntobe(0x4d3eb120L), tobe(0x4ce61da7L), tobe(0x4e8fe82eL), tobe(0x4f5744a9L),\ntobe(0x4a5c033cL), tobe(0x4b84afbbL), tobe(0x49ed5a32L), tobe(0x4835f6b5L),\ntobe(0x43fbd518L), tobe(0x4223799fL), tobe(0x404a8c16L), tobe(0x41922091L),\ntobe(0x44996704L), tobe(0x4541cb83L), tobe(0x47283e0aL), tobe(0x46f0928dL),\ntobe(0x50b47950L), tobe(0x516cd5d7L), tobe(0x5305205eL), tobe(0x52dd8cd9L),\ntobe(0x57d6cb4cL), tobe(0x560e67cbL), tobe(0x54679242L), tobe(0x55bf3ec5L),\ntobe(0x5e711d68L), tobe(0x5fa9b1efL), tobe(0x5dc04466L), tobe(0x5c18e8e1L),\ntobe(0x5913af74L), tobe(0x58cb03f3L), tobe(0x5aa2f67aL), tobe(0x5b7a5afdL),\ntobe(0xec564380L), tobe(0xed8eef07L), tobe(0xefe71a8eL), tobe(0xee3fb609L),\ntobe(0xeb34f19cL), tobe(0xeaec5d1bL), tobe(0xe885a892L), tobe(0xe95d0415L),\ntobe(0xe29327b8L), tobe(0xe34b8b3fL), tobe(0xe1227eb6L), tobe(0xe0fad231L),\ntobe(0xe5f195a4L), tobe(0xe4293923L), tobe(0xe640ccaaL), tobe(0xe798602dL),\ntobe(0xf1dc8bf0L), tobe(0xf0042777L), tobe(0xf26dd2feL), tobe(0xf3b57e79L),\ntobe(0xf6be39ecL), tobe(0xf766956bL), tobe(0xf50f60e2L), tobe(0xf4d7cc65L),\ntobe(0xff19efc8L), tobe(0xfec1434fL), tobe(0xfca8b6c6L), tobe(0xfd701a41L),\ntobe(0xf87b5dd4L), tobe(0xf9a3f153L), tobe(0xfbca04daL), tobe(0xfa12a85dL),\ntobe(0xd743d360L), tobe(0xd69b7fe7L), tobe(0xd4f28a6eL), tobe(0xd52a26e9L),\ntobe(0xd021617cL), tobe(0xd1f9cdfbL), tobe(0xd3903872L), tobe(0xd24894f5L),\ntobe(0xd986b758L), tobe(0xd85e1bdfL), tobe(0xda37ee56L), tobe(0xdbef42d1L),\ntobe(0xdee40544L), tobe(0xdf3ca9c3L), tobe(0xdd555c4aL), tobe(0xdc8df0cdL),\ntobe(0xcac91b10L), tobe(0xcb11b797L), tobe(0xc978421eL), tobe(0xc8a0ee99L),\ntobe(0xcdaba90cL), tobe(0xcc73058bL), tobe(0xce1af002L), tobe(0xcfc25c85L),\ntobe(0xc40c7f28L), tobe(0xc5d4d3afL), tobe(0xc7bd2626L), tobe(0xc6658aa1L),\ntobe(0xc36ecd34L), tobe(0xc2b661b3L), tobe(0xc0df943aL), tobe(0xc10738bdL),\ntobe(0x9a7d6240L), tobe(0x9ba5cec7L), tobe(0x99cc3b4eL), tobe(0x981497c9L),\ntobe(0x9d1fd05cL), tobe(0x9cc77cdbL), tobe(0x9eae8952L), tobe(0x9f7625d5L),\ntobe(0x94b80678L), tobe(0x9560aaffL), tobe(0x97095f76L), tobe(0x96d1f3f1L),\ntobe(0x93dab464L), tobe(0x920218e3L), tobe(0x906bed6aL), tobe(0x91b341edL),\ntobe(0x87f7aa30L), tobe(0x862f06b7L), tobe(0x8446f33eL), tobe(0x859e5fb9L),\ntobe(0x8095182cL), tobe(0x814db4abL), tobe(0x83244122L), tobe(0x82fceda5L),\ntobe(0x8932ce08L), tobe(0x88ea628fL), tobe(0x8a839706L), tobe(0x8b5b3b81L),\ntobe(0x8e507c14L), tobe(0x8f88d093L), tobe(0x8de1251aL), tobe(0x8c39899dL),\ntobe(0xa168f2a0L), tobe(0xa0b05e27L), tobe(0xa2d9abaeL), tobe(0xa3010729L),\ntobe(0xa60a40bcL), tobe(0xa7d2ec3bL), tobe(0xa5bb19b2L), tobe(0xa463b535L),\ntobe(0xafad9698L), tobe(0xae753a1fL), tobe(0xac1ccf96L), tobe(0xadc46311L),\ntobe(0xa8cf2484L), tobe(0xa9178803L), tobe(0xab7e7d8aL), tobe(0xaaa6d10dL),\ntobe(0xbce23ad0L), tobe(0xbd3a9657L), tobe(0xbf5363deL), tobe(0xbe8bcf59L),\ntobe(0xbb8088ccL), tobe(0xba58244bL), tobe(0xb831d1c2L), tobe(0xb9e97d45L),\ntobe(0xb2275ee8L), tobe(0xb3fff26fL), tobe(0xb19607e6L), tobe(0xb04eab61L),\ntobe(0xb545ecf4L), tobe(0xb49d4073L), tobe(0xb6f4b5faL), tobe(0xb72c197dL)},\n{\ntobe(0x00000000L), tobe(0xdc6d9ab7L), tobe(0xbc1a28d9L), tobe(0x6077b26eL),\ntobe(0x7cf54c05L), tobe(0xa098d6b2L), tobe(0xc0ef64dcL), tobe(0x1c82fe6bL),\ntobe(0xf9ea980aL), tobe(0x258702bdL), tobe(0x45f0b0d3L), tobe(0x999d2a64L),\ntobe(0x851fd40fL), tobe(0x59724eb8L), tobe(0x3905fcd6L), tobe(0xe5686661L),\ntobe(0xf7142da3L), tobe(0x2b79b714L), tobe(0x4b0e057aL), tobe(0x97639fcdL),\ntobe(0x8be161a6L), tobe(0x578cfb11L), tobe(0x37fb497fL), tobe(0xeb96d3c8L),\ntobe(0x0efeb5a9L), tobe(0xd2932f1eL), tobe(0xb2e49d70L), tobe(0x6e8907c7L),\ntobe(0x720bf9acL), tobe(0xae66631bL), tobe(0xce11d175L), tobe(0x127c4bc2L),\ntobe(0xeae946f1L), tobe(0x3684dc46L), tobe(0x56f36e28L), tobe(0x8a9ef49fL),\ntobe(0x961c0af4L), tobe(0x4a719043L), tobe(0x2a06222dL), tobe(0xf66bb89aL),\ntobe(0x1303defbL), tobe(0xcf6e444cL), tobe(0xaf19f622L), tobe(0x73746c95L),\ntobe(0x6ff692feL), tobe(0xb39b0849L), tobe(0xd3ecba27L), tobe(0x0f812090L),\ntobe(0x1dfd6b52L), tobe(0xc190f1e5L), tobe(0xa1e7438bL), tobe(0x7d8ad93cL),\ntobe(0x61082757L), tobe(0xbd65bde0L), tobe(0xdd120f8eL), tobe(0x017f9539L),\ntobe(0xe417f358L), tobe(0x387a69efL), tobe(0x580ddb81L), tobe(0x84604136L),\ntobe(0x98e2bf5dL), tobe(0x448f25eaL), tobe(0x24f89784L), tobe(0xf8950d33L),\ntobe(0xd1139055L), tobe(0x0d7e0ae2L), tobe(0x6d09b88cL), tobe(0xb164223bL),\ntobe(0xade6dc50L), tobe(0x718b46e7L), tobe(0x11fcf489L), tobe(0xcd916e3eL),\ntobe(0x28f9085fL), tobe(0xf49492e8L), tobe(0x94e32086L), tobe(0x488eba31L),\ntobe(0x540c445aL), tobe(0x8861deedL), tobe(0xe8166c83L), tobe(0x347bf634L),\ntobe(0x2607bdf6L), tobe(0xfa6a2741L), tobe(0x9a1d952fL), tobe(0x46700f98L),\ntobe(0x5af2f1f3L), tobe(0x869f6b44L), tobe(0xe6e8d92aL), tobe(0x3a85439dL),\ntobe(0xdfed25fcL), tobe(0x0380bf4bL), tobe(0x63f70d25L), tobe(0xbf9a9792L),\ntobe(0xa31869f9L), tobe(0x7f75f34eL), tobe(0x1f024120L), tobe(0xc36fdb97L),\ntobe(0x3bfad6a4L), tobe(0xe7974c13L), tobe(0x87e0fe7dL), tobe(0x5b8d64caL),\ntobe(0x470f9aa1L), tobe(0x9b620016L), tobe(0xfb15b278L), tobe(0x277828cfL),\ntobe(0xc2104eaeL), tobe(0x1e7dd419L), tobe(0x7e0a6677L), tobe(0xa267fcc0L),\ntobe(0xbee502abL), tobe(0x6288981cL), tobe(0x02ff2a72L), tobe(0xde92b0c5L),\ntobe(0xcceefb07L), tobe(0x108361b0L), tobe(0x70f4d3deL), tobe(0xac994969L),\ntobe(0xb01bb702L), tobe(0x6c762db5L), tobe(0x0c019fdbL), tobe(0xd06c056cL),\ntobe(0x3504630dL), tobe(0xe969f9baL), tobe(0x891e4bd4L), tobe(0x5573d163L),\ntobe(0x49f12f08L), tobe(0x959cb5bfL), tobe(0xf5eb07d1L), tobe(0x29869d66L),\ntobe(0xa6e63d1dL), tobe(0x7a8ba7aaL), tobe(0x1afc15c4L), tobe(0xc6918f73L),\ntobe(0xda137118L), tobe(0x067eebafL), tobe(0x660959c1L), tobe(0xba64c376L),\ntobe(0x5f0ca517L), tobe(0x83613fa0L), tobe(0xe3168dceL), tobe(0x3f7b1779L),\ntobe(0x23f9e912L), tobe(0xff9473a5L), tobe(0x9fe3c1cbL), tobe(0x438e5b7cL),\ntobe(0x51f210beL), tobe(0x8d9f8a09L), tobe(0xede83867L), tobe(0x3185a2d0L),\ntobe(0x2d075cbbL), tobe(0xf16ac60cL), tobe(0x911d7462L), tobe(0x4d70eed5L),\ntobe(0xa81888b4L), tobe(0x74751203L), tobe(0x1402a06dL), tobe(0xc86f3adaL),\ntobe(0xd4edc4b1L), tobe(0x08805e06L), tobe(0x68f7ec68L), tobe(0xb49a76dfL),\ntobe(0x4c0f7becL), tobe(0x9062e15bL), tobe(0xf0155335L), tobe(0x2c78c982L),\ntobe(0x30fa37e9L), tobe(0xec97ad5eL), tobe(0x8ce01f30L), tobe(0x508d8587L),\ntobe(0xb5e5e3e6L), tobe(0x69887951L), tobe(0x09ffcb3fL), tobe(0xd5925188L),\ntobe(0xc910afe3L), tobe(0x157d3554L), tobe(0x750a873aL), tobe(0xa9671d8dL),\ntobe(0xbb1b564fL), tobe(0x6776ccf8L), tobe(0x07017e96L), tobe(0xdb6ce421L),\ntobe(0xc7ee1a4aL), tobe(0x1b8380fdL), tobe(0x7bf43293L), tobe(0xa799a824L),\ntobe(0x42f1ce45L), tobe(0x9e9c54f2L), tobe(0xfeebe69cL), tobe(0x22867c2bL),\ntobe(0x3e048240L), tobe(0xe26918f7L), tobe(0x821eaa99L), tobe(0x5e73302eL),\ntobe(0x77f5ad48L), tobe(0xab9837ffL), tobe(0xcbef8591L), tobe(0x17821f26L),\ntobe(0x0b00e14dL), tobe(0xd76d7bfaL), tobe(0xb71ac994L), tobe(0x6b775323L),\ntobe(0x8e1f3542L), tobe(0x5272aff5L), tobe(0x32051d9bL), tobe(0xee68872cL),\ntobe(0xf2ea7947L), tobe(0x2e87e3f0L), tobe(0x4ef0519eL), tobe(0x929dcb29L),\ntobe(0x80e180ebL), tobe(0x5c8c1a5cL), tobe(0x3cfba832L), tobe(0xe0963285L),\ntobe(0xfc14cceeL), tobe(0x20795659L), tobe(0x400ee437L), tobe(0x9c637e80L),\ntobe(0x790b18e1L), tobe(0xa5668256L), tobe(0xc5113038L), tobe(0x197caa8fL),\ntobe(0x05fe54e4L), tobe(0xd993ce53L), tobe(0xb9e47c3dL), tobe(0x6589e68aL),\ntobe(0x9d1cebb9L), tobe(0x4171710eL), tobe(0x2106c360L), tobe(0xfd6b59d7L),\ntobe(0xe1e9a7bcL), tobe(0x3d843d0bL), tobe(0x5df38f65L), tobe(0x819e15d2L),\ntobe(0x64f673b3L), tobe(0xb89be904L), tobe(0xd8ec5b6aL), tobe(0x0481c1ddL),\ntobe(0x18033fb6L), tobe(0xc46ea501L), tobe(0xa419176fL), tobe(0x78748dd8L),\ntobe(0x6a08c61aL), tobe(0xb6655cadL), tobe(0xd612eec3L), tobe(0x0a7f7474L),\ntobe(0x16fd8a1fL), tobe(0xca9010a8L), tobe(0xaae7a2c6L), tobe(0x768a3871L),\ntobe(0x93e25e10L), tobe(0x4f8fc4a7L), tobe(0x2ff876c9L), tobe(0xf395ec7eL),\ntobe(0xef171215L), tobe(0x337a88a2L), tobe(0x530d3accL), tobe(0x8f60a07bL)},\n{\ntobe(0x00000000L), tobe(0x490d678dL), tobe(0x921acf1aL), tobe(0xdb17a897L),\ntobe(0x20f48383L), tobe(0x69f9e40eL), tobe(0xb2ee4c99L), tobe(0xfbe32b14L),\ntobe(0x41e90706L), tobe(0x08e4608bL), tobe(0xd3f3c81cL), tobe(0x9afeaf91L),\ntobe(0x611d8485L), tobe(0x2810e308L), tobe(0xf3074b9fL), tobe(0xba0a2c12L),\ntobe(0x83d20e0cL), tobe(0xcadf6981L), tobe(0x11c8c116L), tobe(0x58c5a69bL),\ntobe(0xa3268d8fL), tobe(0xea2bea02L), tobe(0x313c4295L), tobe(0x78312518L),\ntobe(0xc23b090aL), tobe(0x8b366e87L), tobe(0x5021c610L), tobe(0x192ca19dL),\ntobe(0xe2cf8a89L), tobe(0xabc2ed04L), tobe(0x70d54593L), tobe(0x39d8221eL),\ntobe(0x036501afL), tobe(0x4a686622L), tobe(0x917fceb5L), tobe(0xd872a938L),\ntobe(0x2391822cL), tobe(0x6a9ce5a1L), tobe(0xb18b4d36L), tobe(0xf8862abbL),\ntobe(0x428c06a9L), tobe(0x0b816124L), tobe(0xd096c9b3L), tobe(0x999bae3eL),\ntobe(0x6278852aL), tobe(0x2b75e2a7L), tobe(0xf0624a30L), tobe(0xb96f2dbdL),\ntobe(0x80b70fa3L), tobe(0xc9ba682eL), tobe(0x12adc0b9L), tobe(0x5ba0a734L),\ntobe(0xa0438c20L), tobe(0xe94eebadL), tobe(0x3259433aL), tobe(0x7b5424b7L),\ntobe(0xc15e08a5L), tobe(0x88536f28L), tobe(0x5344c7bfL), tobe(0x1a49a032L),\ntobe(0xe1aa8b26L), tobe(0xa8a7ecabL), tobe(0x73b0443cL), tobe(0x3abd23b1L),\ntobe(0x06ca035eL), tobe(0x4fc764d3L), tobe(0x94d0cc44L), tobe(0xddddabc9L),\ntobe(0x263e80ddL), tobe(0x6f33e750L), tobe(0xb4244fc7L), tobe(0xfd29284aL),\ntobe(0x47230458L), tobe(0x0e2e63d5L), tobe(0xd539cb42L), tobe(0x9c34accfL),\ntobe(0x67d787dbL), tobe(0x2edae056L), tobe(0xf5cd48c1L), tobe(0xbcc02f4cL),\ntobe(0x85180d52L), tobe(0xcc156adfL), tobe(0x1702c248L), tobe(0x5e0fa5c5L),\ntobe(0xa5ec8ed1L), tobe(0xece1e95cL), tobe(0x37f641cbL), tobe(0x7efb2646L),\ntobe(0xc4f10a54L), tobe(0x8dfc6dd9L), tobe(0x56ebc54eL), tobe(0x1fe6a2c3L),\ntobe(0xe40589d7L), tobe(0xad08ee5aL), tobe(0x761f46cdL), tobe(0x3f122140L),\ntobe(0x05af02f1L), tobe(0x4ca2657cL), tobe(0x97b5cdebL), tobe(0xdeb8aa66L),\ntobe(0x255b8172L), tobe(0x6c56e6ffL), tobe(0xb7414e68L), tobe(0xfe4c29e5L),\ntobe(0x444605f7L), tobe(0x0d4b627aL), tobe(0xd65ccaedL), tobe(0x9f51ad60L),\ntobe(0x64b28674L), tobe(0x2dbfe1f9L), tobe(0xf6a8496eL), tobe(0xbfa52ee3L),\ntobe(0x867d0cfdL), tobe(0xcf706b70L), tobe(0x1467c3e7L), tobe(0x5d6aa46aL),\ntobe(0xa6898f7eL), tobe(0xef84e8f3L), tobe(0x34934064L), tobe(0x7d9e27e9L),\ntobe(0xc7940bfbL), tobe(0x8e996c76L), tobe(0x558ec4e1L), tobe(0x1c83a36cL),\ntobe(0xe7608878L), tobe(0xae6deff5L), tobe(0x757a4762L), tobe(0x3c7720efL),\ntobe(0x0d9406bcL), tobe(0x44996131L), tobe(0x9f8ec9a6L), tobe(0xd683ae2bL),\ntobe(0x2d60853fL), tobe(0x646de2b2L), tobe(0xbf7a4a25L), tobe(0xf6772da8L),\ntobe(0x4c7d01baL), tobe(0x05706637L), tobe(0xde67cea0L), tobe(0x976aa92dL),\ntobe(0x6c898239L), tobe(0x2584e5b4L), tobe(0xfe934d23L), tobe(0xb79e2aaeL),\ntobe(0x8e4608b0L), tobe(0xc74b6f3dL), tobe(0x1c5cc7aaL), tobe(0x5551a027L),\ntobe(0xaeb28b33L), tobe(0xe7bfecbeL), tobe(0x3ca84429L), tobe(0x75a523a4L),\ntobe(0xcfaf0fb6L), tobe(0x86a2683bL), tobe(0x5db5c0acL), tobe(0x14b8a721L),\ntobe(0xef5b8c35L), tobe(0xa656ebb8L), tobe(0x7d41432fL), tobe(0x344c24a2L),\ntobe(0x0ef10713L), tobe(0x47fc609eL), tobe(0x9cebc809L), tobe(0xd5e6af84L),\ntobe(0x2e058490L), tobe(0x6708e31dL), tobe(0xbc1f4b8aL), tobe(0xf5122c07L),\ntobe(0x4f180015L), tobe(0x06156798L), tobe(0xdd02cf0fL), tobe(0x940fa882L),\ntobe(0x6fec8396L), tobe(0x26e1e41bL), tobe(0xfdf64c8cL), tobe(0xb4fb2b01L),\ntobe(0x8d23091fL), tobe(0xc42e6e92L), tobe(0x1f39c605L), tobe(0x5634a188L),\ntobe(0xadd78a9cL), tobe(0xe4daed11L), tobe(0x3fcd4586L), tobe(0x76c0220bL),\ntobe(0xccca0e19L), tobe(0x85c76994L), tobe(0x5ed0c103L), tobe(0x17dda68eL),\ntobe(0xec3e8d9aL), tobe(0xa533ea17L), tobe(0x7e244280L), tobe(0x3729250dL),\ntobe(0x0b5e05e2L), tobe(0x4253626fL), tobe(0x9944caf8L), tobe(0xd049ad75L),\ntobe(0x2baa8661L), tobe(0x62a7e1ecL), tobe(0xb9b0497bL), tobe(0xf0bd2ef6L),\ntobe(0x4ab702e4L), tobe(0x03ba6569L), tobe(0xd8adcdfeL), tobe(0x91a0aa73L),\ntobe(0x6a438167L), tobe(0x234ee6eaL), tobe(0xf8594e7dL), tobe(0xb15429f0L),\ntobe(0x888c0beeL), tobe(0xc1816c63L), tobe(0x1a96c4f4L), tobe(0x539ba379L),\ntobe(0xa878886dL), tobe(0xe175efe0L), tobe(0x3a624777L), tobe(0x736f20faL),\ntobe(0xc9650ce8L), tobe(0x80686b65L), tobe(0x5b7fc3f2L), tobe(0x1272a47fL),\ntobe(0xe9918f6bL), tobe(0xa09ce8e6L), tobe(0x7b8b4071L), tobe(0x328627fcL),\ntobe(0x083b044dL), tobe(0x413663c0L), tobe(0x9a21cb57L), tobe(0xd32cacdaL),\ntobe(0x28cf87ceL), tobe(0x61c2e043L), tobe(0xbad548d4L), tobe(0xf3d82f59L),\ntobe(0x49d2034bL), tobe(0x00df64c6L), tobe(0xdbc8cc51L), tobe(0x92c5abdcL),\ntobe(0x692680c8L), tobe(0x202be745L), tobe(0xfb3c4fd2L), tobe(0xb231285fL),\ntobe(0x8be90a41L), tobe(0xc2e46dccL), tobe(0x19f3c55bL), tobe(0x50fea2d6L),\ntobe(0xab1d89c2L), tobe(0xe210ee4fL), tobe(0x390746d8L), tobe(0x700a2155L),\ntobe(0xca000d47L), tobe(0x830d6acaL), tobe(0x581ac25dL), tobe(0x1117a5d0L),\ntobe(0xeaf48ec4L), tobe(0xa3f9e949L), tobe(0x78ee41deL), tobe(0x31e32653L)},\n{\ntobe(0x00000000L), tobe(0x1b280d78L), tobe(0x36501af0L), tobe(0x2d781788L),\ntobe(0x6ca035e0L), tobe(0x77883898L), tobe(0x5af02f10L), tobe(0x41d82268L),\ntobe(0xd9406bc0L), tobe(0xc26866b8L), tobe(0xef107130L), tobe(0xf4387c48L),\ntobe(0xb5e05e20L), tobe(0xaec85358L), tobe(0x83b044d0L), tobe(0x989849a8L),\ntobe(0xb641ca37L), tobe(0xad69c74fL), tobe(0x8011d0c7L), tobe(0x9b39ddbfL),\ntobe(0xdae1ffd7L), tobe(0xc1c9f2afL), tobe(0xecb1e527L), tobe(0xf799e85fL),\ntobe(0x6f01a1f7L), tobe(0x7429ac8fL), tobe(0x5951bb07L), tobe(0x4279b67fL),\ntobe(0x03a19417L), tobe(0x1889996fL), tobe(0x35f18ee7L), tobe(0x2ed9839fL),\ntobe(0x684289d9L), tobe(0x736a84a1L), tobe(0x5e129329L), tobe(0x453a9e51L),\ntobe(0x04e2bc39L), tobe(0x1fcab141L), tobe(0x32b2a6c9L), tobe(0x299aabb1L),\ntobe(0xb102e219L), tobe(0xaa2aef61L), tobe(0x8752f8e9L), tobe(0x9c7af591L),\ntobe(0xdda2d7f9L), tobe(0xc68ada81L), tobe(0xebf2cd09L), tobe(0xf0dac071L),\ntobe(0xde0343eeL), tobe(0xc52b4e96L), tobe(0xe853591eL), tobe(0xf37b5466L),\ntobe(0xb2a3760eL), tobe(0xa98b7b76L), tobe(0x84f36cfeL), tobe(0x9fdb6186L),\ntobe(0x0743282eL), tobe(0x1c6b2556L), tobe(0x311332deL), tobe(0x2a3b3fa6L),\ntobe(0x6be31dceL), tobe(0x70cb10b6L), tobe(0x5db3073eL), tobe(0x469b0a46L),\ntobe(0xd08513b2L), tobe(0xcbad1ecaL), tobe(0xe6d50942L), tobe(0xfdfd043aL),\ntobe(0xbc252652L), tobe(0xa70d2b2aL), tobe(0x8a753ca2L), tobe(0x915d31daL),\ntobe(0x09c57872L), tobe(0x12ed750aL), tobe(0x3f956282L), tobe(0x24bd6ffaL),\ntobe(0x65654d92L), tobe(0x7e4d40eaL), tobe(0x53355762L), tobe(0x481d5a1aL),\ntobe(0x66c4d985L), tobe(0x7decd4fdL), tobe(0x5094c375L), tobe(0x4bbcce0dL),\ntobe(0x0a64ec65L), tobe(0x114ce11dL), tobe(0x3c34f695L), tobe(0x271cfbedL),\ntobe(0xbf84b245L), tobe(0xa4acbf3dL), tobe(0x89d4a8b5L), tobe(0x92fca5cdL),\ntobe(0xd32487a5L), tobe(0xc80c8addL), tobe(0xe5749d55L), tobe(0xfe5c902dL),\ntobe(0xb8c79a6bL), tobe(0xa3ef9713L), tobe(0x8e97809bL), tobe(0x95bf8de3L),\ntobe(0xd467af8bL), tobe(0xcf4fa2f3L), tobe(0xe237b57bL), tobe(0xf91fb803L),\ntobe(0x6187f1abL), tobe(0x7aaffcd3L), tobe(0x57d7eb5bL), tobe(0x4cffe623L),\ntobe(0x0d27c44bL), tobe(0x160fc933L), tobe(0x3b77debbL), tobe(0x205fd3c3L),\ntobe(0x0e86505cL), tobe(0x15ae5d24L), tobe(0x38d64aacL), tobe(0x23fe47d4L),\ntobe(0x622665bcL), tobe(0x790e68c4L), tobe(0x54767f4cL), tobe(0x4f5e7234L),\ntobe(0xd7c63b9cL), tobe(0xccee36e4L), tobe(0xe196216cL), tobe(0xfabe2c14L),\ntobe(0xbb660e7cL), tobe(0xa04e0304L), tobe(0x8d36148cL), tobe(0x961e19f4L),\ntobe(0xa5cb3ad3L), tobe(0xbee337abL), tobe(0x939b2023L), tobe(0x88b32d5bL),\ntobe(0xc96b0f33L), tobe(0xd243024bL), tobe(0xff3b15c3L), tobe(0xe41318bbL),\ntobe(0x7c8b5113L), tobe(0x67a35c6bL), tobe(0x4adb4be3L), tobe(0x51f3469bL),\ntobe(0x102b64f3L), tobe(0x0b03698bL), tobe(0x267b7e03L), tobe(0x3d53737bL),\ntobe(0x138af0e4L), tobe(0x08a2fd9cL), tobe(0x25daea14L), tobe(0x3ef2e76cL),\ntobe(0x7f2ac504L), tobe(0x6402c87cL), tobe(0x497adff4L), tobe(0x5252d28cL),\ntobe(0xcaca9b24L), tobe(0xd1e2965cL), tobe(0xfc9a81d4L), tobe(0xe7b28cacL),\ntobe(0xa66aaec4L), tobe(0xbd42a3bcL), tobe(0x903ab434L), tobe(0x8b12b94cL),\ntobe(0xcd89b30aL), tobe(0xd6a1be72L), tobe(0xfbd9a9faL), tobe(0xe0f1a482L),\ntobe(0xa12986eaL), tobe(0xba018b92L), tobe(0x97799c1aL), tobe(0x8c519162L),\ntobe(0x14c9d8caL), tobe(0x0fe1d5b2L), tobe(0x2299c23aL), tobe(0x39b1cf42L),\ntobe(0x7869ed2aL), tobe(0x6341e052L), tobe(0x4e39f7daL), tobe(0x5511faa2L),\ntobe(0x7bc8793dL), tobe(0x60e07445L), tobe(0x4d9863cdL), tobe(0x56b06eb5L),\ntobe(0x17684cddL), tobe(0x0c4041a5L), tobe(0x2138562dL), tobe(0x3a105b55L),\ntobe(0xa28812fdL), tobe(0xb9a01f85L), tobe(0x94d8080dL), tobe(0x8ff00575L),\ntobe(0xce28271dL), tobe(0xd5002a65L), tobe(0xf8783dedL), tobe(0xe3503095L),\ntobe(0x754e2961L), tobe(0x6e662419L), tobe(0x431e3391L), tobe(0x58363ee9L),\ntobe(0x19ee1c81L), tobe(0x02c611f9L), tobe(0x2fbe0671L), tobe(0x34960b09L),\ntobe(0xac0e42a1L), tobe(0xb7264fd9L), tobe(0x9a5e5851L), tobe(0x81765529L),\ntobe(0xc0ae7741L), tobe(0xdb867a39L), tobe(0xf6fe6db1L), tobe(0xedd660c9L),\ntobe(0xc30fe356L), tobe(0xd827ee2eL), tobe(0xf55ff9a6L), tobe(0xee77f4deL),\ntobe(0xafafd6b6L), tobe(0xb487dbceL), tobe(0x99ffcc46L), tobe(0x82d7c13eL),\ntobe(0x1a4f8896L), tobe(0x016785eeL), tobe(0x2c1f9266L), tobe(0x37379f1eL),\ntobe(0x76efbd76L), tobe(0x6dc7b00eL), tobe(0x40bfa786L), tobe(0x5b97aafeL),\ntobe(0x1d0ca0b8L), tobe(0x0624adc0L), tobe(0x2b5cba48L), tobe(0x3074b730L),\ntobe(0x71ac9558L), tobe(0x6a849820L), tobe(0x47fc8fa8L), tobe(0x5cd482d0L),\ntobe(0xc44ccb78L), tobe(0xdf64c600L), tobe(0xf21cd188L), tobe(0xe934dcf0L),\ntobe(0xa8ecfe98L), tobe(0xb3c4f3e0L), tobe(0x9ebce468L), tobe(0x8594e910L),\ntobe(0xab4d6a8fL), tobe(0xb06567f7L), tobe(0x9d1d707fL), tobe(0x86357d07L),\ntobe(0xc7ed5f6fL), tobe(0xdcc55217L), tobe(0xf1bd459fL), tobe(0xea9548e7L),\ntobe(0x720d014fL), tobe(0x69250c37L), tobe(0x445d1bbfL), tobe(0x5f7516c7L),\ntobe(0x1ead34afL), tobe(0x058539d7L), tobe(0x28fd2e5fL), tobe(0x33d52327L)},\n{\ntobe(0x00000000L), tobe(0x4f576811L), tobe(0x9eaed022L), tobe(0xd1f9b833L),\ntobe(0x399cbdf3L), tobe(0x76cbd5e2L), tobe(0xa7326dd1L), tobe(0xe86505c0L),\ntobe(0x73397be6L), tobe(0x3c6e13f7L), tobe(0xed97abc4L), tobe(0xa2c0c3d5L),\ntobe(0x4aa5c615L), tobe(0x05f2ae04L), tobe(0xd40b1637L), tobe(0x9b5c7e26L),\ntobe(0xe672f7ccL), tobe(0xa9259fddL), tobe(0x78dc27eeL), tobe(0x378b4fffL),\ntobe(0xdfee4a3fL), tobe(0x90b9222eL), tobe(0x41409a1dL), tobe(0x0e17f20cL),\ntobe(0x954b8c2aL), tobe(0xda1ce43bL), tobe(0x0be55c08L), tobe(0x44b23419L),\ntobe(0xacd731d9L), tobe(0xe38059c8L), tobe(0x3279e1fbL), tobe(0x7d2e89eaL),\ntobe(0xc824f22fL), tobe(0x87739a3eL), tobe(0x568a220dL), tobe(0x19dd4a1cL),\ntobe(0xf1b84fdcL), tobe(0xbeef27cdL), tobe(0x6f169ffeL), tobe(0x2041f7efL),\ntobe(0xbb1d89c9L), tobe(0xf44ae1d8L), tobe(0x25b359ebL), tobe(0x6ae431faL),\ntobe(0x8281343aL), tobe(0xcdd65c2bL), tobe(0x1c2fe418L), tobe(0x53788c09L),\ntobe(0x2e5605e3L), tobe(0x61016df2L), tobe(0xb0f8d5c1L), tobe(0xffafbdd0L),\ntobe(0x17cab810L), tobe(0x589dd001L), tobe(0x89646832L), tobe(0xc6330023L),\ntobe(0x5d6f7e05L), tobe(0x12381614L), tobe(0xc3c1ae27L), tobe(0x8c96c636L),\ntobe(0x64f3c3f6L), tobe(0x2ba4abe7L), tobe(0xfa5d13d4L), tobe(0xb50a7bc5L),\ntobe(0x9488f9e9L), tobe(0xdbdf91f8L), tobe(0x0a2629cbL), tobe(0x457141daL),\ntobe(0xad14441aL), tobe(0xe2432c0bL), tobe(0x33ba9438L), tobe(0x7cedfc29L),\ntobe(0xe7b1820fL), tobe(0xa8e6ea1eL), tobe(0x791f522dL), tobe(0x36483a3cL),\ntobe(0xde2d3ffcL), tobe(0x917a57edL), tobe(0x4083efdeL), tobe(0x0fd487cfL),\ntobe(0x72fa0e25L), tobe(0x3dad6634L), tobe(0xec54de07L), tobe(0xa303b616L),\ntobe(0x4b66b3d6L), tobe(0x0431dbc7L), tobe(0xd5c863f4L), tobe(0x9a9f0be5L),\ntobe(0x01c375c3L), tobe(0x4e941dd2L), tobe(0x9f6da5e1L), tobe(0xd03acdf0L),\ntobe(0x385fc830L), tobe(0x7708a021L), tobe(0xa6f11812L), tobe(0xe9a67003L),\ntobe(0x5cac0bc6L), tobe(0x13fb63d7L), tobe(0xc202dbe4L), tobe(0x8d55b3f5L),\ntobe(0x6530b635L), tobe(0x2a67de24L), tobe(0xfb9e6617L), tobe(0xb4c90e06L),\ntobe(0x2f957020L), tobe(0x60c21831L), tobe(0xb13ba002L), tobe(0xfe6cc813L),\ntobe(0x1609cdd3L), tobe(0x595ea5c2L), tobe(0x88a71df1L), tobe(0xc7f075e0L),\ntobe(0xbadefc0aL), tobe(0xf589941bL), tobe(0x24702c28L), tobe(0x6b274439L),\ntobe(0x834241f9L), tobe(0xcc1529e8L), tobe(0x1dec91dbL), tobe(0x52bbf9caL),\ntobe(0xc9e787ecL), tobe(0x86b0effdL), tobe(0x574957ceL), tobe(0x181e3fdfL),\ntobe(0xf07b3a1fL), tobe(0xbf2c520eL), tobe(0x6ed5ea3dL), tobe(0x2182822cL),\ntobe(0x2dd0ee65L), tobe(0x62878674L), tobe(0xb37e3e47L), tobe(0xfc295656L),\ntobe(0x144c5396L), tobe(0x5b1b3b87L), tobe(0x8ae283b4L), tobe(0xc5b5eba5L),\ntobe(0x5ee99583L), tobe(0x11befd92L), tobe(0xc04745a1L), tobe(0x8f102db0L),\ntobe(0x67752870L), tobe(0x28224061L), tobe(0xf9dbf852L), tobe(0xb68c9043L),\ntobe(0xcba219a9L), tobe(0x84f571b8L), tobe(0x550cc98bL), tobe(0x1a5ba19aL),\ntobe(0xf23ea45aL), tobe(0xbd69cc4bL), tobe(0x6c907478L), tobe(0x23c71c69L),\ntobe(0xb89b624fL), tobe(0xf7cc0a5eL), tobe(0x2635b26dL), tobe(0x6962da7cL),\ntobe(0x8107dfbcL), tobe(0xce50b7adL), tobe(0x1fa90f9eL), tobe(0x50fe678fL),\ntobe(0xe5f41c4aL), tobe(0xaaa3745bL), tobe(0x7b5acc68L), tobe(0x340da479L),\ntobe(0xdc68a1b9L), tobe(0x933fc9a8L), tobe(0x42c6719bL), tobe(0x0d91198aL),\ntobe(0x96cd67acL), tobe(0xd99a0fbdL), tobe(0x0863b78eL), tobe(0x4734df9fL),\ntobe(0xaf51da5fL), tobe(0xe006b24eL), tobe(0x31ff0a7dL), tobe(0x7ea8626cL),\ntobe(0x0386eb86L), tobe(0x4cd18397L), tobe(0x9d283ba4L), tobe(0xd27f53b5L),\ntobe(0x3a1a5675L), tobe(0x754d3e64L), tobe(0xa4b48657L), tobe(0xebe3ee46L),\ntobe(0x70bf9060L), tobe(0x3fe8f871L), tobe(0xee114042L), tobe(0xa1462853L),\ntobe(0x49232d93L), tobe(0x06744582L), tobe(0xd78dfdb1L), tobe(0x98da95a0L),\ntobe(0xb958178cL), tobe(0xf60f7f9dL), tobe(0x27f6c7aeL), tobe(0x68a1afbfL),\ntobe(0x80c4aa7fL), tobe(0xcf93c26eL), tobe(0x1e6a7a5dL), tobe(0x513d124cL),\ntobe(0xca616c6aL), tobe(0x8536047bL), tobe(0x54cfbc48L), tobe(0x1b98d459L),\ntobe(0xf3fdd199L), tobe(0xbcaab988L), tobe(0x6d5301bbL), tobe(0x220469aaL),\ntobe(0x5f2ae040L), tobe(0x107d8851L), tobe(0xc1843062L), tobe(0x8ed35873L),\ntobe(0x66b65db3L), tobe(0x29e135a2L), tobe(0xf8188d91L), tobe(0xb74fe580L),\ntobe(0x2c139ba6L), tobe(0x6344f3b7L), tobe(0xb2bd4b84L), tobe(0xfdea2395L),\ntobe(0x158f2655L), tobe(0x5ad84e44L), tobe(0x8b21f677L), tobe(0xc4769e66L),\ntobe(0x717ce5a3L), tobe(0x3e2b8db2L), tobe(0xefd23581L), tobe(0xa0855d90L),\ntobe(0x48e05850L), tobe(0x07b73041L), tobe(0xd64e8872L), tobe(0x9919e063L),\ntobe(0x02459e45L), tobe(0x4d12f654L), tobe(0x9ceb4e67L), tobe(0xd3bc2676L),\ntobe(0x3bd923b6L), tobe(0x748e4ba7L), tobe(0xa577f394L), tobe(0xea209b85L),\ntobe(0x970e126fL), tobe(0xd8597a7eL), tobe(0x09a0c24dL), tobe(0x46f7aa5cL),\ntobe(0xae92af9cL), tobe(0xe1c5c78dL), tobe(0x303c7fbeL), tobe(0x7f6b17afL),\ntobe(0xe4376989L), tobe(0xab600198L), tobe(0x7a99b9abL), tobe(0x35ced1baL),\ntobe(0xddabd47aL), tobe(0x92fcbc6bL), tobe(0x43050458L), tobe(0x0c526c49L)},\n{\ntobe(0x00000000L), tobe(0x5ba1dccaL), tobe(0xb743b994L), tobe(0xece2655eL),\ntobe(0x6a466e9fL), tobe(0x31e7b255L), tobe(0xdd05d70bL), tobe(0x86a40bc1L),\ntobe(0xd48cdd3eL), tobe(0x8f2d01f4L), tobe(0x63cf64aaL), tobe(0x386eb860L),\ntobe(0xbecab3a1L), tobe(0xe56b6f6bL), tobe(0x09890a35L), tobe(0x5228d6ffL),\ntobe(0xadd8a7cbL), tobe(0xf6797b01L), tobe(0x1a9b1e5fL), tobe(0x413ac295L),\ntobe(0xc79ec954L), tobe(0x9c3f159eL), tobe(0x70dd70c0L), tobe(0x2b7cac0aL),\ntobe(0x79547af5L), tobe(0x22f5a63fL), tobe(0xce17c361L), tobe(0x95b61fabL),\ntobe(0x1312146aL), tobe(0x48b3c8a0L), tobe(0xa451adfeL), tobe(0xfff07134L),\ntobe(0x5f705221L), tobe(0x04d18eebL), tobe(0xe833ebb5L), tobe(0xb392377fL),\ntobe(0x35363cbeL), tobe(0x6e97e074L), tobe(0x8275852aL), tobe(0xd9d459e0L),\ntobe(0x8bfc8f1fL), tobe(0xd05d53d5L), tobe(0x3cbf368bL), tobe(0x671eea41L),\ntobe(0xe1bae180L), tobe(0xba1b3d4aL), tobe(0x56f95814L), tobe(0x0d5884deL),\ntobe(0xf2a8f5eaL), tobe(0xa9092920L), tobe(0x45eb4c7eL), tobe(0x1e4a90b4L),\ntobe(0x98ee9b75L), tobe(0xc34f47bfL), tobe(0x2fad22e1L), tobe(0x740cfe2bL),\ntobe(0x262428d4L), tobe(0x7d85f41eL), tobe(0x91679140L), tobe(0xcac64d8aL),\ntobe(0x4c62464bL), tobe(0x17c39a81L), tobe(0xfb21ffdfL), tobe(0xa0802315L),\ntobe(0xbee0a442L), tobe(0xe5417888L), tobe(0x09a31dd6L), tobe(0x5202c11cL),\ntobe(0xd4a6caddL), tobe(0x8f071617L), tobe(0x63e57349L), tobe(0x3844af83L),\ntobe(0x6a6c797cL), tobe(0x31cda5b6L), tobe(0xdd2fc0e8L), tobe(0x868e1c22L),\ntobe(0x002a17e3L), tobe(0x5b8bcb29L), tobe(0xb769ae77L), tobe(0xecc872bdL),\ntobe(0x13380389L), tobe(0x4899df43L), tobe(0xa47bba1dL), tobe(0xffda66d7L),\ntobe(0x797e6d16L), tobe(0x22dfb1dcL), tobe(0xce3dd482L), tobe(0x959c0848L),\ntobe(0xc7b4deb7L), tobe(0x9c15027dL), tobe(0x70f76723L), tobe(0x2b56bbe9L),\ntobe(0xadf2b028L), tobe(0xf6536ce2L), tobe(0x1ab109bcL), tobe(0x4110d576L),\ntobe(0xe190f663L), tobe(0xba312aa9L), tobe(0x56d34ff7L), tobe(0x0d72933dL),\ntobe(0x8bd698fcL), tobe(0xd0774436L), tobe(0x3c952168L), tobe(0x6734fda2L),\ntobe(0x351c2b5dL), tobe(0x6ebdf797L), tobe(0x825f92c9L), tobe(0xd9fe4e03L),\ntobe(0x5f5a45c2L), tobe(0x04fb9908L), tobe(0xe819fc56L), tobe(0xb3b8209cL),\ntobe(0x4c4851a8L), tobe(0x17e98d62L), tobe(0xfb0be83cL), tobe(0xa0aa34f6L),\ntobe(0x260e3f37L), tobe(0x7dafe3fdL), tobe(0x914d86a3L), tobe(0xcaec5a69L),\ntobe(0x98c48c96L), tobe(0xc365505cL), tobe(0x2f873502L), tobe(0x7426e9c8L),\ntobe(0xf282e209L), tobe(0xa9233ec3L), tobe(0x45c15b9dL), tobe(0x1e608757L),\ntobe(0x79005533L), tobe(0x22a189f9L), tobe(0xce43eca7L), tobe(0x95e2306dL),\ntobe(0x13463bacL), tobe(0x48e7e766L), tobe(0xa4058238L), tobe(0xffa45ef2L),\ntobe(0xad8c880dL), tobe(0xf62d54c7L), tobe(0x1acf3199L), tobe(0x416eed53L),\ntobe(0xc7cae692L), tobe(0x9c6b3a58L), tobe(0x70895f06L), tobe(0x2b2883ccL),\ntobe(0xd4d8f2f8L), tobe(0x8f792e32L), tobe(0x639b4b6cL), tobe(0x383a97a6L),\ntobe(0xbe9e9c67L), tobe(0xe53f40adL), tobe(0x09dd25f3L), tobe(0x527cf939L),\ntobe(0x00542fc6L), tobe(0x5bf5f30cL), tobe(0xb7179652L), tobe(0xecb64a98L),\ntobe(0x6a124159L), tobe(0x31b39d93L), tobe(0xdd51f8cdL), tobe(0x86f02407L),\ntobe(0x26700712L), tobe(0x7dd1dbd8L), tobe(0x9133be86L), tobe(0xca92624cL),\ntobe(0x4c36698dL), tobe(0x1797b547L), tobe(0xfb75d019L), tobe(0xa0d40cd3L),\ntobe(0xf2fcda2cL), tobe(0xa95d06e6L), tobe(0x45bf63b8L), tobe(0x1e1ebf72L),\ntobe(0x98bab4b3L), tobe(0xc31b6879L), tobe(0x2ff90d27L), tobe(0x7458d1edL),\ntobe(0x8ba8a0d9L), tobe(0xd0097c13L), tobe(0x3ceb194dL), tobe(0x674ac587L),\ntobe(0xe1eece46L), tobe(0xba4f128cL), tobe(0x56ad77d2L), tobe(0x0d0cab18L),\ntobe(0x5f247de7L), tobe(0x0485a12dL), tobe(0xe867c473L), tobe(0xb3c618b9L),\ntobe(0x35621378L), tobe(0x6ec3cfb2L), tobe(0x8221aaecL), tobe(0xd9807626L),\ntobe(0xc7e0f171L), tobe(0x9c412dbbL), tobe(0x70a348e5L), tobe(0x2b02942fL),\ntobe(0xada69feeL), tobe(0xf6074324L), tobe(0x1ae5267aL), tobe(0x4144fab0L),\ntobe(0x136c2c4fL), tobe(0x48cdf085L), tobe(0xa42f95dbL), tobe(0xff8e4911L),\ntobe(0x792a42d0L), tobe(0x228b9e1aL), tobe(0xce69fb44L), tobe(0x95c8278eL),\ntobe(0x6a3856baL), tobe(0x31998a70L), tobe(0xdd7bef2eL), tobe(0x86da33e4L),\ntobe(0x007e3825L), tobe(0x5bdfe4efL), tobe(0xb73d81b1L), tobe(0xec9c5d7bL),\ntobe(0xbeb48b84L), tobe(0xe515574eL), tobe(0x09f73210L), tobe(0x5256eedaL),\ntobe(0xd4f2e51bL), tobe(0x8f5339d1L), tobe(0x63b15c8fL), tobe(0x38108045L),\ntobe(0x9890a350L), tobe(0xc3317f9aL), tobe(0x2fd31ac4L), tobe(0x7472c60eL),\ntobe(0xf2d6cdcfL), tobe(0xa9771105L), tobe(0x4595745bL), tobe(0x1e34a891L),\ntobe(0x4c1c7e6eL), tobe(0x17bda2a4L), tobe(0xfb5fc7faL), tobe(0xa0fe1b30L),\ntobe(0x265a10f1L), tobe(0x7dfbcc3bL), tobe(0x9119a965L), tobe(0xcab875afL),\ntobe(0x3548049bL), tobe(0x6ee9d851L), tobe(0x820bbd0fL), tobe(0xd9aa61c5L),\ntobe(0x5f0e6a04L), tobe(0x04afb6ceL), tobe(0xe84dd390L), tobe(0xb3ec0f5aL),\ntobe(0xe1c4d9a5L), tobe(0xba65056fL), tobe(0x56876031L), tobe(0x0d26bcfbL),\ntobe(0x8b82b73aL), tobe(0xd0236bf0L), tobe(0x3cc10eaeL), tobe(0x6760d264L)},\n};\n\n#endif /* CRC32TABLE_H_ */\n" }, { "alpha_fraction": 0.5446815490722656, "alphanum_fraction": 0.5521144270896912, "avg_line_length": 28.897306442260742, "blob_id": "638caeaf03fa1ca20765a094a83c862ca18506a6", "content_id": "7753dffa5fcb896f92dd76f647a215a6e4b15645", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 17759, "license_type": "no_license", "max_line_length": 80, "num_lines": 594, "path": "/interloquendi/interloquendi.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* interloquendi: copies a mcp frame file to a TCP port\n *\n * This software is copyright (C) 2004 University of Toronto\n *\n * This file is part of interloquendi.\n *\n * interloquendi 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 2 of the License, or\n * (at your option) any later version.\n *\n * interloquendi 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 interloquendi; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <stdlib.h>\n\n#include <errno.h>\n#include <netdb.h>\n#include <signal.h>\n#include <string.h>\n#include <tcpd.h>\n#include <unistd.h>\n\n#include <sys/syslog.h>\n\n#include <arpa/inet.h>\n\n#include \"blast.h\"\n#include \"frameread.h\"\n#include \"quendi.h\"\n#include \"quendiclient.h\"\n\n#define VERSION \"1.2.0\"\n#define SERVER_PORT 44144\n#define RENDEZ_PORT 14141\n#define PID_FILE \"/var/run/interloquendi.pid\"\n#define CONFIG_FILE \"/etc/interloquendi.conf\"\n\n#define DEBUG\n\n/* in rendezvous.c */\nint InitRendezvous(const char*, int, const char*);\n\nstruct {\n union {\n char* as_string;\n int as_int;\n } value;\n char type;\n const char name[48];\n} options[] = {\n {{NULL}, 's', \"CurFile\"},\n {{NULL}, 's', \"Directory\"},\n {{NULL}, 's', \"LocalNet\"},\n {{NULL}, 'i', \"MaxConnect\"},\n {{NULL}, 's', \"PidFile\"},\n {{NULL}, 's', \"RendezvousAs\"},\n {{NULL}, 'i', \"RendezvousAt\"},\n {{NULL}, 's', \"RendezvousWith\"},\n {{NULL}, 'i', \"SuffixLength\"},\n {{NULL}, '\\0', \"\"}\n};\n\n#define CFG_CUR_FILE 0\n#define CFG_DIRECTORY 1\n#define CFG_LOCAL_NET 2\n#define CFG_MAX_CONNECT 3\n#define CFG_PID_FILE 4\n#define CFG_RENDEZ_AS 5\n#define CFG_RENDEZ_AT 6\n#define CFG_RENDEZ_WITH 7\n#define CFG_SUFFIX_LENGTH 8\n\n/* for libwrap */\nint allow_severity = LOG_INFO;\nint deny_severity = LOG_WARNING;\n\nchar* GetCurFile(char *buffer, int buflen)\n{\n FILE* stream = NULL;\n char* ptr;\n\n if ((stream = fopen(options[CFG_CUR_FILE].value.as_string, \"rt\")) == NULL)\n berror(err, \"can't open curfile %s\",options[CFG_CUR_FILE].value.as_string);\n else if (fgets(buffer, buflen, stream) == NULL) {\n berror(err, \"read error on curfile\");\n fclose(stream);\n } else {\n if ((ptr = strchr(buffer, '\\n')) != NULL)\n *ptr = '\\0';\n fclose(stream);\n return buffer;\n }\n\n return NULL;\n}\n\nvoid Connection(int csock)\n{\n struct sockaddr_in addr;\n socklen_t addrlen = sizeof(addr);\n struct hostent* thishost;\n struct request_info req;\n struct quendi_server_data_t QuendiData;\n\n char buffer[QUENDI_COMMAND_LENGTH];\n int np;\n int n;\n char params[1][QUENDI_COMMAND_LENGTH];\n struct quendi_data_port_t data;\n\n data.sock = -1;\n data.port_active = 0;\n data.sending_data = 0;\n\n /* tcp wrapper check */\n request_init(&req, RQ_DAEMON, \"interloquendi\", RQ_FILE, csock, 0);\n fromhost(&req);\n\n if (!hosts_access(&req)) {\n refuse(&req);\n exit(1); /* can't get here */\n }\n\n getsockname(csock, (struct sockaddr*)&addr, &addrlen);\n thishost = gethostbyaddr((const char*)&addr.sin_addr, sizeof(addr.sin_addr),\n AF_INET);\n if (thishost == NULL && h_errno) {\n bprintf(warning, \"gethostbyaddr: %s\", hstrerror(h_errno));\n thishost = NULL;\n }\n\n QuendiData.server_version = VERSION;\n QuendiData.server_name = \"interloquendi\";\n QuendiData.server_host = thishost ? thishost->h_name\n : inet_ntoa(addr.sin_addr);\n QuendiData.csock = csock;\n QuendiData.access_level = 1;\n QuendiData.directory = (char*)options[CFG_DIRECTORY].value.as_string;\n\n quendi_server_init(&QuendiData);\n quendi_add_data_port(&data);\n\n /* Service Loop */\n for (;;) {\n if ((n = quendi_get_cmd(buffer)) == 0) {\n n = quendi_parse(buffer, &np, params);\n switch(n) {\n case -2:\n quendi_respond(QUENYA_RESPONSE_PARAM_ERROR, \"Parameter Missing\");\n break;\n case -1:\n quendi_respond(QUENYA_RESPONSE_SYNTAX_ERROR, \"Unrecognised Command\");\n break;\n case QUENYA_COMMAND_ABOR:\n if (!data.sending_data)\n quendi_respond(QUENYA_RESPONSE_PORT_INACTIVE, NULL);\n else {\n quendi_reader_shutdown(data.fd, 1);\n data.sending_data = 0;\n }\n break;\n case QUENYA_COMMAND_CLOS:\n if (data.sock < 0)\n quendi_respond(QUENYA_RESPONSE_PORT_NOT_OPEN, NULL);\n else if (data.sending_data)\n quendi_respond(QUENYA_RESPONSE_PORT_ACTIVE, NULL);\n else {\n shutdown(data.sock, SHUT_RDWR);\n close(data.sock);\n data.sock = -1;\n quendi_respond(QUENYA_RESPONSE_OK, NULL);\n }\n break;\n case QUENYA_COMMAND_DATA:\n if (data.sock < 0) {\n quendi_respond(QUENYA_RESPONSE_PORT_NOT_OPEN, NULL);\n break;\n } else if (!data.staged) {\n quendi_respond(QUENYA_RESPONSE_NO_DATA_STAGED, NULL);\n break;\n } else if (data.sending_data) {\n quendi_respond(QUENYA_RESPONSE_PORT_ACTIVE, NULL);\n break;\n }\n\n data.seek_to = quendi_reader_init(data.frame_size, data.pos,\n data.chunk, data.name, options[CFG_SUFFIX_LENGTH].value.as_int);\n\n /* The first read from the file always involves a new chunk */\n data.new_chunk = 1;\n data.chunk_total = 0;\n data.frames_read = 0;\n data.sending_data = 1;\n data.remainder = 0;\n\n /* Fallthrough */\n case QUENYA_COMMAND_CONT:\n if (n == QUENYA_COMMAND_CONT && !data.sending_data) {\n quendi_respond(QUENYA_RESPONSE_PORT_INACTIVE, NULL);\n break;\n }\n\n data.port_active = 1;\n do {\n if (n != QUENYA_COMMAND_DATA) {\n n = quendi_advance_data(data.persist, data.chunk,\n options[CFG_SUFFIX_LENGTH].value.as_int, &data.chunk_total,\n options[CFG_CUR_FILE].value.as_string, data.name,\n data.block_length, data.remainder);\n\n switch (n) {\n case FR_DONE:\n quendi_reader_shutdown(data.fd, 1);\n data.sending_data = 0;\n data.staged = 0;\n data.port_active = 0;\n break;\n case FR_MORE_IN_FILE:\n data.new_chunk = 0;\n break;\n case FR_NEW_CHUNK:\n close(data.fd);\n data.new_chunk = 1;\n break;\n case FR_CURFILE_CHANGED:\n quendi_reader_shutdown(data.fd, 0);\n data.sending_data = 0;\n data.port_active = 0;\n if (GetCurFile(data.name, QUENDI_COMMAND_LENGTH) == NULL)\n quendi_respond(QUENYA_RESPONSE_TRANS_COMPLETE, NULL);\n else {\n data.frame_size = ReconstructChannelLists(data.name, NULL);\n data.staged = quendi_stage_data(data.name, 0,\n options[CFG_SUFFIX_LENGTH].value.as_int, 1,\n data.frame_size);\n }\n break;\n default:\n printf(\"huh? (%i)\\n\", n);\n exit(1);\n }\n } else\n n = FR_NEW_CHUNK;\n\n if (n == FR_NEW_CHUNK || n == FR_MORE_IN_FILE) {\n /* read a block */\n data.block_length = quendi_read_data(data.new_chunk,\n &data.fd, data.chunk, data.seek_to, &data.chunk_total,\n data.frame_size, &data.frames_read, &data.remainder);\n\n data.seek_to = 0;\n data.new_chunk = 0;\n// printf(\"block size = %i\\n\", data.block_length);\n } else\n break;\n } while (data.block_length <= 0);\n\n if (n == FR_NEW_CHUNK || n == FR_MORE_IN_FILE)\n /* send the block */\n quendi_send_data(data.sock, data.frame_size, data.block_length);\n break;\n case QUENYA_COMMAND_IDEN:\n QuendiData.access_level = 1;\n quendi_respond(QUENYA_RESPONSE_ACCESS_GRANTED, NULL);\n break;\n case QUENYA_COMMAND_ASYN:\n case QUENYA_COMMAND_NOOP:\n quendi_respond(QUENYA_RESPONSE_OK, NULL);\n break;\n case QUENYA_COMMAND_OPEN:\n if (quendi_access_ok(1)) {\n if (data.sock < 0) {\n data.sock = quendi_dp_connect();\n if (data.sock == -2)\n quendi_respond(QUENYA_RESPONSE_OPEN_ERROR,\n \"Timeout Opening Data Port\");\n else if (data.sock == -3)\n quendi_respond(QUENYA_RESPONSE_OPEN_ERROR,\n \"Access from Unauthorised Client on Data Port\");\n else if (data.sock < 0)\n quendi_respond(QUENYA_RESPONSE_OPEN_ERROR, NULL);\n else {\n quendi_respond(QUENYA_RESPONSE_PORT_OPENED, NULL);\n }\n } else\n quendi_respond(QUENYA_RESPONSE_OPEN_ERROR, \"Too Many Open Ports\");\n }\n break;\n case QUENYA_COMMAND_QNOW:\n if (quendi_access_ok(1)) {\n if (data.sending_data)\n quendi_respond(QUENYA_RESPONSE_PORT_ACTIVE, NULL);\n else if (GetCurFile(data.name, QUENDI_COMMAND_LENGTH) == NULL)\n quendi_respond(QUENYA_RESPONSE_NO_CUR_DATA, NULL);\n else {\n data.persist = 1;\n data.frame_size = ReconstructChannelLists(data.name, NULL);\n data.pos = GetFrameFileSize(data.name,\n options[CFG_SUFFIX_LENGTH].value.as_int) / data.frame_size;\n data.staged = quendi_stage_data(data.name, data.pos,\n options[CFG_SUFFIX_LENGTH].value.as_int, 0, data.frame_size);\n }\n }\n break;\n case QUENYA_COMMAND_QUIT:\n quendi_respond(QUENYA_RESPONSE_GOODBYE, NULL);\n close(csock);\n exit(0);\n case QUENYA_COMMAND_RDVS:\n if (quendi_access_ok(1)) {\n QuendiData.rendezvous_name = bstrdup(fatal, params[0]);\n if (data.sock < 0) {\n data.sock = quendi_rp_connect(QuendiData.rendezvous_name);\n if (data.sock == -2)\n quendi_respond(QUENYA_RESPONSE_OPEN_ERROR,\n \"Unable to Resolve Rendezvous Host\");\n else if (data.sock < 0)\n quendi_respond(QUENYA_RESPONSE_OPEN_ERROR,\n \"Error Opening Rendezvous Port\");\n else\n quendi_respond(QUENYA_RESPONSE_PORT_OPENED,\n \"Connected to Rendezvous Port\");\n } else\n quendi_respond(QUENYA_RESPONSE_OPEN_ERROR, \"Too Many Open Ports\");\n }\n break;\n case QUENYA_COMMAND_RTBK:\n if (!data.sending_data)\n quendi_respond(QUENYA_RESPONSE_PORT_INACTIVE, NULL);\n else {\n data.port_active = 1;\n quendi_send_data(data.sock, data.frame_size, data.block_length);\n }\n break;\n case QUENYA_COMMAND_SIZE:\n if (!data.staged)\n quendi_respond(QUENYA_RESPONSE_NO_DATA_STAGED, NULL);\n else\n quendi_respond(QUENYA_RESPONSE_FRAME_SIZE, NULL);\n break;\n case QUENYA_COMMAND_SPEC:\n if (data.sock < 0)\n quendi_respond(QUENYA_RESPONSE_PORT_NOT_OPEN, NULL);\n else if (!data.staged)\n quendi_respond(QUENYA_RESPONSE_NO_DATA_STAGED, NULL);\n else if (data.sending_data)\n quendi_respond(QUENYA_RESPONSE_PORT_ACTIVE, NULL);\n else {\n data.port_active = 1;\n quendi_send_spec(data.sock, data.name);\n data.port_active = 0;\n }\n break;\n case QUENYA_COMMAND_SYNC:\n default:\n quendi_respond(QUENYA_RESPONSE_CMD_NOT_IMPL, NULL);\n break;\n }\n } else if (n == -2) {\n bprintf(warning, \"connection dropped\\n\");\n shutdown(csock, SHUT_RDWR);\n close(csock);\n if (data.sock >= 0) {\n bprintf(warning, \"shutdown data port\\n\");\n shutdown(data.sock, SHUT_RDWR);\n close(data.sock);\n }\n quendi_server_shutdown();\n return;\n } else if (n == -3) {\n if (!data.port_active) {\n quendi_respond(QUENYA_RESPONSE_TIMEOUT, NULL);\n shutdown(csock, SHUT_RDWR);\n close(csock);\n quendi_server_shutdown();\n return;\n }\n } else if (n == -4) {\n quendi_respond(QUENYA_RESPONSE_PORT_CLOSE_ERR,\n \"Unexpected Close on Data Port\");\n shutdown(data.sock, SHUT_RDWR);\n close(data.sock);\n data.sock = -1;\n }\n }\n}\n\nint MakeListener(int port)\n{\n int sock;\n struct sockaddr_in addr;\n\n sock = MakeSock();\n\n addr.sin_family = AF_INET;\n addr.sin_port = htons(port);\n addr.sin_addr.s_addr = INADDR_ANY;\n\n if (bind(sock, (struct sockaddr*)&addr, (socklen_t)sizeof(addr)) == -1)\n berror(fatal, \"bind\");\n\n if (listen(sock, 10) == -1)\n berror(fatal, \"listen\");\n\n bprintf(info, \"listening on port %i.\", port);\n\n return sock;\n}\n\nvoid CleanUp(void)\n{\n unlink(options[CFG_PID_FILE].value.as_string);\n closelog();\n}\n\nvoid ReadConfig(FILE* stream)\n{\n char buffer[1024];\n char *option, *value;\n int i, found;\n\n while (fgets(buffer, sizeof(buffer), stream)) {\n /* remove comments */\n if ((option = strchr(buffer, '#')) != NULL)\n *option = '\\0';\n\n /* strip newline */\n if ((option = strchr(buffer, '\\n')) != NULL)\n *option = '\\0';\n\n /* strip leading whitespace */\n option = buffer + strspn(buffer, \" \\t\");\n if ((value = strchr(option, ' ')) != NULL) {\n *(value++) = '\\0';\n value += strspn(value, \" \\t\");\n }\n\n found = 0;\n for (i = 0; options[i].type != '\\0'; ++i)\n if (strcasecmp(option, options[i].name) == 0) {\n found = 1;\n switch (options[i].type) {\n case 's':\n options[i].value.as_string = bstrdup(fatal, value);\n break;\n case 'i':\n options[i].value.as_int = atoi(value);\n break;\n default:\n printf(\"Unknown option type\\n\");\n exit(1);\n }\n break;\n }\n\n if (!found)\n bprintf(warning, \"Unknown option `%s'\", option);\n }\n}\n\nvoid LoadDefaultConfig(void)\n{\n int i;\n\n for (i = 0; options[i].type; ++i)\n if (options[i].value.as_string == NULL)\n switch (i) {\n case CFG_CUR_FILE:\n options[i].value.as_string\n = bstrdup(fatal, \"/mnt/decom/etc/decom.cur\");\n break;\n case CFG_DIRECTORY:\n options[i].value.as_string = bstrdup(fatal, \"/mnt/decom/rawdir\");\n break;\n case CFG_LOCAL_NET:\n case CFG_RENDEZ_AS:\n case CFG_RENDEZ_WITH:\n options[i].value.as_string = \"\";\n break;\n case CFG_MAX_CONNECT:\n options[i].value.as_int = 0;\n break;\n case CFG_PID_FILE:\n options[i].value.as_string = bstrdup(fatal, PID_FILE);\n break;\n case CFG_RENDEZ_AT:\n options[i].value.as_int = RENDEZ_PORT;\n break;\n case CFG_SUFFIX_LENGTH:\n options[i].value.as_int = 3;\n break;\n default:\n bprintf(warning, \"No default value for option `%s'\",\n options[i].name);\n }\n}\n\nint main(void)\n{\n int pid;\n FILE* stream;\n int sock, csock;\n socklen_t addrlen;\n struct sockaddr_in addr;\n\n /* set up our outputs */\n#ifdef DEBUG\n buos_use_stdio();\n#else\n openlog(\"interloquendi\", LOG_PID, LOG_DAEMON);\n buos_use_syslog();\n#endif\n\n /* read config file */\n if ((stream = fopen(CONFIG_FILE, \"rt\")) != NULL) {\n ReadConfig(stream);\n fclose(stream);\n } else\n berror(warning, \"unable to open config file `%s'\", CONFIG_FILE);\n\n /* fill uninitialised options with default values */\n LoadDefaultConfig();\n\n#ifndef DEBUG\n /* Fork to background */\n if ((pid = fork()) != 0) {\n if (pid == -1)\n berror(fatal, \"unable to fork to background\");\n\n if ((stream = fopen(options[CFG_PID_FILE].value.as_string, \"w\")) == NULL)\n berror(err, \"unable to write PID to disk\");\n else {\n fprintf(stream, \"%i\\n\", pid);\n fflush(stream);\n fclose(stream);\n }\n closelog();\n printf(\"PID = %i\\n\", pid);\n exit(0);\n }\n atexit(CleanUp);\n\n /* Daemonise */\n chdir(\"/\");\n freopen(\"/dev/null\", \"r\", stdin);\n freopen(\"/dev/null\", \"w\", stdout);\n freopen(\"/dev/null\", \"w\", stderr);\n setsid();\n#endif\n\n /* Autoreap children */\n signal(SIGCHLD, SIG_IGN);\n\n /* Set up Rendezvous, if necessary */\n if (InitRendezvous(options[CFG_RENDEZ_WITH].value.as_string,\n options[CFG_RENDEZ_AT].value.as_int,\n options[CFG_RENDEZ_AS].value.as_string))\n bputs(fatal, \"Unable to rendezvous with upstream host.\");\n\n /* initialise listener socket */\n sock = MakeListener(SERVER_PORT);\n\n /* accept loop */\n for (;;) {\n addrlen = sizeof(addr);\n csock = accept(sock, (struct sockaddr*)&addr, &addrlen);\n\n if (csock == -1 && errno == EINTR)\n continue;\n else if (csock == -1)\n berror(err, \"accept\");\n else {\n /* fork child */\n if ((pid = fork()) == 0) {\n close(sock);\n Connection(csock);\n exit(0);\n }\n\n bprintf(info, \"spawned %i to handle connect from %s\", pid,\n inet_ntoa(addr.sin_addr));\n close(csock);\n }\n }\n}\n" }, { "alpha_fraction": 0.5713765621185303, "alphanum_fraction": 0.7399854063987732, "avg_line_length": 43.98360824584961, "blob_id": "470710887ad5847b037ca66996587bccb6d48875", "content_id": "14b1e9a09561cde891ca9de42c8c3804eec668eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2746, "license_type": "no_license", "max_line_length": 177, "num_lines": 61, "path": "/xsc_initialization_cmds_fc2.sh", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "# LAT and LON of the high bay at Penn\nblastcmd @192.168.1.4 pos_set 39.9526 284.8110\nblastcmd @192.168.1.4 pos_set 31.7793 -95.7167\n\n# xsc_is_new_window_period which valid_period_cs\nblastcmd @192.168.1.4 xsc_is_new_window_period 0 1500\nblastcmd @192.168.1.4 xsc_is_new_window_period 1 1500\n\n# xsc_exposure_timing which exposure_cs grace_period_s (!!) share_delay_cs\n#blastcmd @192.168.1.4 xsc_exposure_timing 0 12 60 200\n#blastcmd @192.168.1.4 xsc_exposure_timing 1 12 60 200\nblastcmd @192.168.1.4 xsc_exposure_timing 0 12 8 200\nblastcmd @192.168.1.4 xsc_exposure_timing 1 12 8 200\n\n# xsc_solver_general which enabled timeout_s\nblastcmd @192.168.1.4 xsc_solver_general 0 1 7\nblastcmd @192.168.1.4 xsc_solver_general 1 1 7\n\n##### Triggering ######\n\n# xsc_trigger_threshold which enabled max_streaking_px # trigger only when conditions are met\nblastcmd @192.168.1.4 xsc_trigger_threshold 0 1 10\nblastcmd @192.168.1.4 xsc_trigger_threshold 1 1 10\n\n# xsc_scan_force_trigger which[doesnt apply] enabled # Force triggering at turnaround\nblastcmd @192.168.1.4 xsc_scan_force_trigger 0 0\n\n######### Solving and Filters ##########\n# xsc_filter_hor_location which enabled radius_degrees\n# blastcmd @192.168.1.4 xsc_filter_hor_location 0 1 20\n# blastcmd @192.168.1.4 xsc_filter_hor_location 1 1 20\nblastcmd @192.168.1.4 xsc_filter_hor_location 0 0 20\nblastcmd @192.168.1.4 xsc_filter_hor_location 1 0 20\n\n# xsc_filter_eq which enabled radius_degrees\nblastcmd @192.168.1.4 xsc_filter_eq_location 0 0 10\nblastcmd @192.168.1.4 xsc_filter_eq_location 1 0 10\n\n# xsc_filter_hor_roll which enabled min_deg max_deg\n# blastcmd @192.168.1.4 xsc_filter_hor_roll 0 1 -90 90\n# blastcmd @192.168.1.4 xsc_filter_hor_roll 1 1 -90 90\n# blastcmd @192.168.1.4 xsc_filter_hor_roll 0 1 -90 90\n# blastcmd @192.168.1.4 xsc_filter_hor_roll 1 1 -90 90\n\n# xsc_filter_el which enabled min_deg max_deg\nblastcmd @192.168.1.4 xsc_filter_el 0 1 5 60\nblastcmd @192.168.1.4 xsc_filter_el 1 1 5 60\n\n# xsc_blob_finding which snr_thresh max_num_blobs robust_mode_enabled fitting_method\n# blastcmd @192.168.1.4 xsc_blob_finding 0 10 15 1 0\n# blastcmd @192.168.1.4 xsc_blob_finding 1 10 15 1 0\nblastcmd @192.168.1.4 xsc_blob_finding 0 10 15 0 0\nblastcmd @192.168.1.4 xsc_blob_finding 1 10 15 0 0\n\n# xsc_pattern_matching which enabled display_star_name match_tol_px iplatescale_min_arcsec iplatescale_max_arcsec platescale_always_fixed platescale_fixed # platescale ~6.4\"/pix\nblastcmd @192.168.1.4 xsc_pattern_matching 0 1 0 5 6.5 7.0 0 0\nblastcmd @192.168.1.4 xsc_pattern_matching 1 1 0 5 6.5 7.0 0 0\n\n# xsc_filter_matching which error_threshold_arcsec fit_error_thresh_px num_matched \nblastcmd @192.168.1.4 xsc_filter_matching 0 6 10 6\nblastcmd @192.168.1.4 xsc_filter_matching 1 6 10 6\n\n\n" }, { "alpha_fraction": 0.7093023061752319, "alphanum_fraction": 0.7241601943969727, "avg_line_length": 26.64285659790039, "blob_id": "52369b852c1b66e75e6b67e8b84f73b55aaee950", "content_id": "31e50347fb956bac27c8bf492ca952418ae4fb32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1548, "license_type": "no_license", "max_line_length": 120, "num_lines": 56, "path": "/owl/PServer.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include <QSystemSemaphore>\n#include <QSharedMemory>\n#include <QString>\n#include <QObject>\n#include <QTimer>\n\n#ifndef PSERVER_H\n#define PSERVER_H\n\nclass PServer : public QObject\n{\n Q_OBJECT\n QSystemSemaphore _sema;\n QSharedMemory _smemHtml;\n QSharedMemory _smemCSS;\n QSharedMemory _smemLayout;\n QSharedMemory _smemData;\n\npublic:\n friend class QTimer;\n\n QString key;\n\n /*WARNING: this is __NOT__ platform independant. See the Qt documentation for the constructor for QSystemSemaphore*/\n PServer(QString ckey);\n\n ~PServer();\n\n void clockOn(const QString& html,const QString&css,const QString&layout,const QString&data);\n\npublic slots:\n void clockOff();\n};\n\n#endif // PSERVER_H\n" }, { "alpha_fraction": 0.676627516746521, "alphanum_fraction": 0.693703293800354, "avg_line_length": 26.970149993896484, "blob_id": "6b67c8d599ea9b41476b155f67f706384da909f2", "content_id": "de8e33d018977dee72085943b1c5283237fd6dc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1874, "license_type": "no_license", "max_line_length": 79, "num_lines": 67, "path": "/owl/PMdiArea.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"PObject.h\"\n#include \"POwlAnimation.h\"\n#include \"PBox.h\"\n\n#include <QMdiArea>\n#include <QDragEnterEvent>\n#include <QMdiSubWindow>\n#include <QDebug>\n\n#ifndef PMDIAREA_H\n#define PMDIAREA_H\n\n/* Despite the name, this has nothing to do with QMdiArea.\n * It was a QMdiArea before, but QMdiArea was not efficient\n * enough.\n */\nclass PMdiArea : public QWidget, public PObject\n{\n Q_OBJECT\npublic:\n explicit PMdiArea(QWidget *parent = 0) : QWidget(parent)\n {\n setAcceptDrops(1);\n QPalette pal=palette();\n pal.setColor(backgroundRole(),\"white\");\n setPalette(pal);\n setAutoFillBackground(1);\n _H = fontMetrics().height();\n }\n void set_H(int h_in) {_H = h_in;}\n\nprotected:\n void dragEnterEvent(QDragEnterEvent *ev);\n void dropEvent(QDropEvent *ev);\n int _H;\n\npublic slots:\n void createPBox(int x=0,int y=0,PBox*c_pbox=0);\n void createOwl(int x=0,int y=0,POwlAnimation*c_owl=0);\n\nsignals:\n void newBox(PBox*);\n void newOwl(POwlAnimation*);\n};\n\n#endif // PMDIAREA_H\n" }, { "alpha_fraction": 0.679114818572998, "alphanum_fraction": 0.679114818572998, "avg_line_length": 22.322580337524414, "blob_id": "ea2ac51c21423f3950464c8b33ef77160ef8e12b", "content_id": "686d3a9188ae9a1346f5bcc92f91c169563d0105", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 723, "license_type": "no_license", "max_line_length": 53, "num_lines": 31, "path": "/blast_config/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "set(CMD_SRCS\n ${CMD_SRCS}\n ${CMAKE_CURRENT_SOURCE_DIR}/command_list.c\n PARENT_SCOPE\n)\nset(CMD_HEADERS\n ${CMD_HEADERS}\n ${CMAKE_CURRENT_SOURCE_DIR}/include/command_list.h\n PARENT_SCOPE\n)\n\nset(MCP_COMMON_SRCS\n ${MCP_COMMON_SRCS}\n ${CMAKE_CURRENT_SOURCE_DIR}/tx_struct_tng.c\n ${CMAKE_CURRENT_SOURCE_DIR}/derived.c\n ${CMAKE_CURRENT_SOURCE_DIR}/slowdl_struct.c\n PARENT_SCOPE\n)\n\nset(GROUNDHOG_COMMON_SRCS\n ${GROUNDHOG_COMMON_SRCS}\n ${CMAKE_CURRENT_SOURCE_DIR}/tx_struct_tng.c\n ${CMAKE_CURRENT_SOURCE_DIR}/derived.c\n PARENT_SCOPE\n)\nset(DECOM_COMMON_SRCS\n ${DECOM_COMMON_SRCS}\n ${CMAKE_CURRENT_SOURCE_DIR}/tx_struct_tng.c\n ${CMAKE_CURRENT_SOURCE_DIR}/derived.c\n PARENT_SCOPE\n)\n" }, { "alpha_fraction": 0.6778621673583984, "alphanum_fraction": 0.6892321705818176, "avg_line_length": 22.189071655273438, "blob_id": "7b4791e8fea4384e65b4431effbd5faaf862af1b", "content_id": "d2b6bcc715e84a97e47d61e4da4d0110153ef683", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 26737, "license_type": "no_license", "max_line_length": 112, "num_lines": 1153, "path": "/starcam/csbigcam.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n \n\tcsbigcam.cpp - Contains the code for the sbigcam class\n\n\t1. This software (c)2004-2005 Santa Barbara Instrument Group.\n\t2. This free software is provided as an example of how\n\tto communicate with SBIG cameras. It is provided AS-IS\n\twithout any guarantees by SBIG of suitability for a\n\tparticular purpose and without any guarantee to be\n\tbug-free. If you use it you agree to these terms and\n\tagree to do so at your own risk.\n\t3. Any distribution of this source code to include these\n\tterms.\n\n\tRevision History\n\tDate \t\tModification\n\t=========================================================\n\t1/9/05\t\tFixed a bug in the ActivateRelay() method\n\t\t\t\t where only the XPlus relay would ever\n\t\t\t\t fire\n\t\t\t\tRenamed the development ST-F by it's\n\t\t\t\t production name ST-402\n\n\t1/17/05\t\tAdded the Get/SetSubFrame() methods for\n\t\t\t\t specifying a partila frame readout in\n\t\t\t\t the GrabImage() method\n\t\t\t\tAdded the GetFullFrame() method that returns\n\t\t\t\t the size of the active CCD in the current\n\t\t\t\t readout mode.\n\n\t1/18/05\t\tAdded the IsRelayActive() method.\n\t\t\t\t \n\t \n*/\n#include \"sbigudrv.h\"\n#include \"csbigcam.h\"\n#include \"csbigimg.h\"\n//FIXME string.h - strchr\n//#include <string>\n#include <string.h>\n#include <math.h>\n#include <stdio.h>\n\nusing namespace std;\n\n//defined in camconfig.h\n//#ifndef INVALID_HANDLE_VALUE\n//#define INVALID_HANDLE_VALUE -1\n//#endif\n\n/*\n \n Temperature Conversion Constants\n Defined in the SBIG Universal Driver Documentation\n \n*/\n#define T0 25.0\n#define R0 3.0\n#define DT_CCD 25.0\n#define DT_AMB 45.0\n#define RR_CCD 2.57\n#define RR_AMB 7.791\n#define RB_CCD 10.0\n#define RB_AMB 3.0\n#define MAX_AD 4096\n\n/*\n \n hex2double:\n\t \n Convert the passed hex value to double.\n The hex value is assumed to be in the\n format: XXXXXX.XX\n\t \n*/\nstatic double hex2double(unsigned long ul)\n{\n\tdouble res, mult;\n\tint i;\n\t\n\tres = 0.0;\n\tmult = 1.0;\n\tfor (i=0; i<8; i++)\n\t{\n\t\tres += mult * (double)(ul & 0x0F);\n\t\tul >>= 4;\n\t\tmult *= 10.0;\n\t}\n\treturn res / 100.0;\n\t\n}\n\n/*\n \n Init:\n\t \n Initialize the base variables.\n \n*/\nvoid CSBIGCam::Init(SBIGCamConfigParams params/*=defaultCameraParams.SBIGParams*/)\n{\n\tm_eLastError = params.lastError;\n\tm_eLastCommand = params.lastCommand;\n\tm_nDrvHandle = params.drvHandle;\n\tm_eCameraType = params.cameraType;\n\tm_eActiveCCD = params.activeCCD;\n\tm_dExposureTime = params.exposureTime;\n\tm_uReadoutMode = params.readoutMode;\n\tm_eABGState = params.ABGState;\n\tm_nSubFrameLeft = params.subframeLeft;\n\tm_nSubFrameTop = params.subframeTop;\n\tm_nSubFrameWidth = params.subframeWidth;\n\tm_nSubFrameHeight = params.subframeHeight;\n}\n/* original method replaced\nvoid CSBIGCam::Init()\n{\n\tm_eLastError = CE_NO_ERROR;\n\tm_eLastCommand = CC_NULL;\n\tm_nDrvHandle = INVALID_HANDLE_VALUE;\n\tm_eCameraType = NO_CAMERA;\n\tm_eActiveCCD = CCD_IMAGING;\n\tm_dExposureTime = 1.0;\n\tm_uReadoutMode = 0;\n\tm_eABGState = ABG_CLK_MED7;\n\tm_nSubFrameLeft = m_nSubFrameTop = m_nSubFrameWidth = m_nSubFrameWidth = 0;\n}\n*/\n\n/*\n \n CSBIGCam:\n\t \n Stamdard constructor. Initialize appropriate member variables.\n \n*/\nCSBIGCam::CSBIGCam()\n{\n\tInit();\n}\n\n/*\n \n CSBIGCam:\n\t \n Alternate constructor. Init the vars, Open the driver and then\n try to open the passed device.\n \n If you want to use the Ethernet connection this is the best\n constructor. If you're using the LPT or USB connections\n the alternate constructor below may make more sense.\n \n*/\nCSBIGCam::CSBIGCam(OpenDeviceParams odp)\n{\n\tInit();\n\tif ( OpenDriver() == CE_NO_ERROR )\n\t\tm_eLastError = OpenDevice(odp);\n}\n\n/*\n \n CSBIGCam:\n\t \n Alternate constructor. Init the vars, Open the driver and then\n try to open the passed device.\n \n This won't work the Ethernet port because no IP address\n is specified. Use the constructor above where you can\n pass the OpenDeviceParams struct.\n \n*/\nCSBIGCam::CSBIGCam(SBIG_DEVICE_TYPE dev)\n{\n\tOpenDeviceParams odp;\n\todp.ipAddress = 0;\n\todp.lptBaseAddress = 0;\n\n\t\n\tInit();\n\tif ( dev == DEV_ETH )\n\t\tm_eLastError = CE_BAD_PARAMETER;\n\telse {\n\t\todp.deviceType = dev;\n\t\tif ( OpenDriver() == CE_NO_ERROR )\n\t\t\tm_eLastError = OpenDevice(odp);\n\t}\n}\n\n\n/*\n \n ~CSBIGCam:\n \n Standard destructor. Close the device then the driver.\n \n*/\nCSBIGCam::~CSBIGCam()\n{\n\tCloseDevice();\n\tCloseDriver();\n}\n\n/*\n \n GetError:\n\t \n Return the error generated in the previous driver call.\n \n*/\nPAR_ERROR CSBIGCam::GetError()\n{\n\treturn m_eLastError;\n}\n\n/*\n \n GetCommand:\n\t \n Return the command last passed to the driver.\n \n*/\nPAR_COMMAND CSBIGCam::GetCommand()\n{\n\treturn m_eLastCommand;\n}\n\n/*\n\n GetSubFrame:\n SetSubFrame:\n\n Set or return the coordinates of the subframe for\n readout. Setting the Height or Width to zero uses\n the whole frame.\n\n*/\nvoid CSBIGCam::SetSubFrame(int nLeft, int nTop, int nWidth, int nHeight)\n{\n\tm_nSubFrameLeft = nLeft;\n\tm_nSubFrameTop = nTop;\n\tm_nSubFrameWidth = nWidth;\n\tm_nSubFrameHeight = nHeight;\n}\n\nvoid CSBIGCam::GetSubFrame(int &nLeft, int &nTop, int &nWidth, int &nHeight)\n{\n\tnLeft = m_nSubFrameLeft;\n\tnTop = m_nSubFrameTop;\n\tnWidth = m_nSubFrameWidth;\n\tnHeight = m_nSubFrameHeight;\n}\n\n/*\n\n GetFullFrame:\n\n Return the size of the full frame image based upon the active\n CCD and current readout mode.\n\n*/\nPAR_ERROR CSBIGCam::GetFullFrame(int &nWidth, int &nHeight)\n{\n\tGetCCDInfoResults0 gcir;\n\tGetCCDInfoParams gcip;\n\tunsigned short vertNBinning;\n\tunsigned short rm;\n\n\t// Get the image dimensions\n\tvertNBinning = m_uReadoutMode >> 8;\n\tif ( vertNBinning == 0 )\n\t\tvertNBinning = 1;\n\trm = m_uReadoutMode & 0xFF;\n\tgcip.request = (m_eActiveCCD == CCD_IMAGING ? CCD_INFO_IMAGING : CCD_INFO_TRACKING);\n\tif ( SBIGUnivDrvCommand(CC_GET_CCD_INFO, &gcip, &gcir) != CE_NO_ERROR )\n\t\treturn m_eLastError;\n\tif ( rm >= gcir.readoutModes )\n\t\treturn CE_BAD_PARAMETER;\n\tnWidth = gcir.readoutInfo[rm].width;\n\tnHeight = gcir.readoutInfo[rm].height / vertNBinning;\n\treturn CE_NO_ERROR;\n}\n\n/*\n \n GetCameraTypeString:\n\t \n Return a string describing the model camera\n that has been linked to.\n \n*/\n//typedef enum { ST7_CAMERA=4, ST8_CAMERA, ST5C_CAMERA, TCE_CONTROLLER,\n// ST237_CAMERA, STK_CAMERA, ST9_CAMERA, STV_CAMERA, ST10_CAMERA,\n// ST1K_CAMERA, ST2K_CAMERA, STL_CAMERA, ST402_CAMERA, NEXT_CAMERA, NO_CAMERA=0xFFFF } CAMERA_TYPE;\nstatic const char *CAM_NAMES[] = {\n\t\"Type 0\", \"Type 1\", \"Type 2\", \"Type 3\",\n\t\"ST-7\", \"ST-8\", \"ST-5C\", \"TCE\",\n\t\"ST-237\", \"ST-K\", \"ST-9\", \"STV\", \"ST-10\",\n\t\"ST-1K\", \"ST-2K\", \"ST-L\", \"ST-402\" };\nstring CSBIGCam::GetCameraTypeString(void)\n{\n\tstring s;\n\tGetCCDInfoParams gcip;\n\tGetCCDInfoResults0 gcir;\n\tchar *p1, *p2;\n\t\n\tif ( m_eCameraType < (CAMERA_TYPE)(sizeof(CAM_NAMES)/sizeof(const char *)) ) {\n\t\t// default name\n\t\ts = CAM_NAMES[m_eCameraType];\n\t\t\n\t\t// see if ST-237A and if so indicate it in the name\n\t\tif ( m_eCameraType == ST237_CAMERA ) {\n\t\t\tgcip.request = CCD_INFO_IMAGING;\n\t\t\tif ( SBIGUnivDrvCommand(CC_GET_CCD_INFO, &gcip, &gcir) == CE_NO_ERROR )\n\t\t\t\tif ( gcir.readoutInfo[0].gain >= 0x100 )\n\t\t\t\t\ts += \"A\";\n\t\t}\n\t\t\n\t\t// include the ST-L sub-models\n\t\tif ( m_eCameraType == STL_CAMERA ) {\n\t\t\tgcip.request = CCD_INFO_IMAGING;\n\t\t\tif ( SBIGUnivDrvCommand(CC_GET_CCD_INFO, &gcip, &gcir) == CE_NO_ERROR ) {\n\t\t\t\t// driver reports name as \"SBIG ST-L-XXX...\"\n\t\t\t\tp1 = gcir.name + 5;\n\t\t\t\tif ( (p2 = strchr(p1,' ')) != NULL ) {\n\t\t\t\t\t*p2 = 0;\n\t\t\t\t\ts = p1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse if ( m_eCameraType == NO_CAMERA )\n\t\ts = \"No Camera\";\n\telse\n\t\ts = \"Unknown\";\n\treturn s;\n}\n\n/*\n \n SBIGUnivDrvCommand:\n\t \n Bottleneck function for all calls to the driver that logs\n the command and error. First it activates our handle and\n then it calls the driver. Activating the handle first\n allows having multiple instances of this class dealing\n with multiple cameras on different communications port.\n \n Also allows direct access to the SBIG Universal Driver after\n the driver has been opened.\n \n*/\nPAR_ERROR CSBIGCam::SBIGUnivDrvCommand(short command, void *Params, void *Results)\n{\n\tSetDriverHandleParams sdhp;\n\t\n\t// make sure we have a valid handle to the driver\n\tm_eLastCommand = (PAR_COMMAND)command;\n\tif ( m_nDrvHandle == INVALID_HANDLE_VALUE )\n\t\tm_eLastError = CE_DRIVER_NOT_OPEN;\n\telse\n\t{\n\t\t// handle is valid so install it in the driver\n\t\tsdhp.handle = m_nDrvHandle;\n\t\tif ( (m_eLastError = (PAR_ERROR)::SBIGUnivDrvCommand(CC_SET_DRIVER_HANDLE, &sdhp, NULL)) == CE_NO_ERROR )\n\t\t\t// call the desired command\n\t\t\tm_eLastError = (PAR_ERROR)::SBIGUnivDrvCommand(command, Params, Results);\n\t}\n\treturn m_eLastError;\n}\n\n/*\n \n OpenDriver:\n\t \n Open the driver. Must be made before any other calls and\n should be called only once per instance of the camera class.\n Based on the results of the open call to the driver this can\n open a new handle to the driver.\n \n The alternate constructors do this for you when you specify\n the communications port to use.\n \n*/\nPAR_ERROR CSBIGCam::OpenDriver()\n{\n\tshort res;\n\tGetDriverHandleResults gdhr;\n\tSetDriverHandleParams sdhp;\n\t\n\t// call the driver directly so doesn't install our handle\n\tres = ::SBIGUnivDrvCommand(m_eLastCommand = CC_OPEN_DRIVER, NULL, NULL);\n\tif ( res == CE_DRIVER_NOT_CLOSED )\n\t{\n\t\t/*\n the driver is open already which we interpret\n as having been opened by another instance of\n the class so get the driver to allocate a new\n handle and then record it\n */\n\t\tsdhp.handle = INVALID_HANDLE_VALUE;\n\t\tres = ::SBIGUnivDrvCommand(CC_SET_DRIVER_HANDLE, &sdhp, NULL);\n\t\tif ( res == CE_NO_ERROR ) {\n\t\t\tres = ::SBIGUnivDrvCommand(CC_OPEN_DRIVER, NULL, NULL);\n\t\t\tif ( res == CE_NO_ERROR ) {\n\t\t\t\tres = ::SBIGUnivDrvCommand(CC_GET_DRIVER_HANDLE, NULL, &gdhr);\n\t\t\t\tif ( res == CE_NO_ERROR )\n\t\t\t\t\tm_nDrvHandle = gdhr.handle;\n\t\t\t}\n\t\t}\n\t}\n\telse if ( res == CE_NO_ERROR )\n\t{\n\t\t/*\n the driver was not open so record the driver handle\n so we can support multiple instances of this class\n talking to multiple cameras\n */\n\t\tres = ::SBIGUnivDrvCommand(CC_GET_DRIVER_HANDLE, NULL, &gdhr);\n\t\tif ( res == CE_NO_ERROR )\n\t\t\tm_nDrvHandle = gdhr.handle;\n\t}\n\treturn m_eLastError = (PAR_ERROR)res;\n}\n\n/*\n \n CloseDriver:\n\t \n Should be called for every call to OpenDriver.\n Standard destructor does this for you as well.\n Closing the Drriver multiple times won't hurt\n but will return an error.\n \n The destructor will do this for you if you\n don't do it explicitly.\n \n*/\nPAR_ERROR CSBIGCam::CloseDriver()\n{\n\tPAR_ERROR res;\n\t\n\tres = SBIGUnivDrvCommand(CC_CLOSE_DRIVER, NULL, NULL);\n\tif ( res == CE_NO_ERROR )\n\t\tm_nDrvHandle = INVALID_HANDLE_VALUE;\n\treturn res;\n}\n\n/*\n \n OpenDevice:\n\t \n Call once to open a particular port (USB, LPT,\n Ethernet, etc). Must be balanced with a call\n to CloseDevice.\n \n Note that the alternate constructors will make\n this call for you so you don't have to do it\n explicitly.\n \n*/\nPAR_ERROR CSBIGCam::OpenDevice(OpenDeviceParams odp)\n{\n\treturn SBIGUnivDrvCommand(CC_OPEN_DEVICE, &odp, NULL);\n}\n\n/*\n \n CloseDevice:\n\t \n Closes which ever device was opened by OpenDriver.\n \n The destructor does this for you so you don't have\n to call it explicitly.\n \n*/\nPAR_ERROR CSBIGCam::CloseDevice()\n{\n\treturn SBIGUnivDrvCommand(CC_CLOSE_DEVICE, NULL, NULL);\n}\n\n/*\n \n GetErrorString:\n\t \n Return a string object describing the passed error code.\n \n*/\nstring CSBIGCam::GetErrorString(PAR_ERROR err)\n{\n\tGetErrorStringParams gesp;\n\tGetErrorStringResults gesr;\n\tstring s;\n\t\n\tgesp.errorNo = err;\n\tSBIGUnivDrvCommand(CC_GET_ERROR_STRING, &gesp, &gesr);\n\ts = gesr.errorString;\n\treturn s;\n}\n\n/*\n \n GetDriverInfo:\n\t \n Get the requested driver info for the passed request.\n This call only works with the DRIVER_STANDARD and\n DRIVER_EXTENDED requests as you pass it a result\n reference that only works with those 2 requests.\n For other requests simply call the\n SBIGUnivDrvCommand class function.\n \n*/\nPAR_ERROR CSBIGCam::GetDriverInfo(DRIVER_REQUEST request, GetDriverInfoResults0 &gdir)\n{\n\tGetDriverInfoParams gdip;\n\t\n\tgdip.request = request;\n\tm_eLastCommand = CC_GET_DRIVER_INFO;\n\tif ( request > DRIVER_EXTENDED )\n\t\treturn m_eLastError = CE_BAD_PARAMETER;\n\telse\n\t\treturn SBIGUnivDrvCommand(CC_GET_DRIVER_INFO, &gdip, &gdir);\n}\n/*\n\nSetDriverControl:\n\nModify the behavior of the driver by changing the\nsettings of one of the driver control parameters.\nDriver options can be enabled or disabled with this\ncommand.\n\n*/\nPAR_ERROR CSBIGCam::SetDriverControl(DRIVER_CONTROL_PARAM ctrlpram, unsigned long ctrlval)\n{\n\tSetDriverControlParams sdcp;\n\n\tsdcp.controlParameter = ctrlpram;\n\tsdcp.controlValue = ctrlval;\n\tif ( CheckLink() )\n\t\treturn SBIGUnivDrvCommand(CC_SET_DRIVER_CONTROL, &sdcp, NULL);\n\telse\n\t\treturn m_eLastError;\n}\n\n/*\n \n GrabImage:\n\t \n Grab an image into the passed image of the passed type.\n This does the whole processing for you: Starts\n and Ends the Exposure then Readsout the data.\n \n*/\nPAR_ERROR CSBIGCam::GrabImage(CSBIGImg *pImg, SBIG_DARK_FRAME dark)\n{\n\tint left, top, width, height;\n\tGetCCDInfoResults0 gcir;\n\tGetCCDInfoParams gcip;\n\tdouble ccdTemp;\n\tunsigned short vertNBinning, hBin, vBin;\n\tunsigned short rm;\n\tstring s;\n\tunsigned short es;\n\tMY_LOGICAL expComp;\n\tPAR_ERROR err;\n\tStartReadoutParams srp;\n\tint i;\n\tReadoutLineParams rlp;\n\ttime_t curTime;\n\tstruct tm *pLT;\n\tchar cs[80];\n\t// Get the image dimensions\n\tvertNBinning = m_uReadoutMode >> 8;\n\tif ( vertNBinning == 0 )\n\t\tvertNBinning = 1;\n\trm = m_uReadoutMode & 0xFF;\n\thBin = vBin = 1;\n\tif ( rm < 3 )\n\t\thBin = vBin = (rm + 1);\n\telse if ( rm < 6 ) {\n\t\thBin = (rm - 5);\n\t\tvBin = vertNBinning;\n\t} else if ( rm < 9 )\n\t\thBin = vBin = (rm - 8);\n\telse if ( rm == 9 )\n\t\thBin = vBin = 9;\n\tgcip.request = (m_eActiveCCD == CCD_IMAGING ? CCD_INFO_IMAGING : CCD_INFO_TRACKING);\n\tif ( SBIGUnivDrvCommand(CC_GET_CCD_INFO, &gcip, &gcir) != CE_NO_ERROR )\n\t\treturn m_eLastError;\n\tif ( rm >= gcir.readoutModes )\n\t\treturn CE_BAD_PARAMETER;\n\tif ( m_nSubFrameWidth == 0 || m_nSubFrameHeight == 0 ) {\n\t\tleft = top = 0;\n\t\twidth = gcir.readoutInfo[rm].width;\n\t\theight = gcir.readoutInfo[rm].height / vertNBinning;\n\t} else {\n\t\tleft = m_nSubFrameLeft;\n\t\ttop = m_nSubFrameTop;\n\t\twidth = m_nSubFrameWidth;\n\t\theight = m_nSubFrameHeight;\n\t}\n\n\t// try to allocate the image buffer\n\tif ( !pImg->AllocateImageBuffer(height, width) )\n\t\treturn CE_MEMORY_ERROR;\n\tpImg->SetImageModified(TRUE);\n\n\t// initialize some image header params\n\tif ( GetCCDTemperature(ccdTemp) != CE_NO_ERROR )\n\t\treturn m_eLastError;\n\tpImg->SetCCDTemperature(ccdTemp);\n\tpImg->SetEachExposure(m_dExposureTime);\n\tpImg->SetEGain(hex2double(gcir.readoutInfo[rm].gain));\n\tpImg->SetPixelHeight(hex2double(gcir.readoutInfo[rm].pixelHeight) * vertNBinning / 1000.0);\n\tpImg->SetPixelWidth(hex2double(gcir.readoutInfo[rm].pixelWidth) / 1000.0);\n\tes = ES_DCS_ENABLED | ES_DCR_DISABLED | ES_AUTOBIAS_ENABLED;\n\tif ( m_eCameraType == ST5C_CAMERA )\n\t\tes |= (ES_ABG_CLOCKED | ES_ABG_RATE_MED);\n\telse if ( m_eCameraType == ST237_CAMERA )\n\t\tes |= (ES_ABG_CLOCKED | ES_ABG_RATE_FIXED);\n\telse if ( m_eActiveCCD == CCD_TRACKING )\n\t\tes |= (ES_ABG_CLOCKED | ES_ABG_RATE_MED);\n\telse\n\t\tes |= ES_ABG_LOW;\n\tpImg->SetExposureState(es);\n\tpImg->SetExposureTime(m_dExposureTime);\n\tpImg->SetNumberExposures(1);\n\tpImg->SetReadoutMode(m_uReadoutMode);\n\ts = GetCameraTypeString();\n\tif ( m_eCameraType == ST5C_CAMERA || ( m_eCameraType == ST237_CAMERA && s.find(\"ST-237A\", 0) == string::npos) )\n\t\tpImg->SetSaturationLevel(4095);\n\telse\n\t\tpImg->SetSaturationLevel(65535);\n\ts = gcir.name;\n\tpImg->SetCameraModel(s);\n\tpImg->SetBinning(hBin, vBin);\n\tpImg->SetSubFrame(left, top);\n\n\t// end any exposure in case one in progress\n\tEndExposure();\n\tif ( m_eLastError != CE_NO_ERROR && m_eLastError != CE_NO_EXPOSURE_IN_PROGRESS )\n\t\treturn m_eLastError;\n\t// start the exposure\n\tif ( StartExposure(dark == SBDF_LIGHT_ONLY ? SC_OPEN_SHUTTER : SC_CLOSE_SHUTTER) != CE_NO_ERROR )\n\t\treturn m_eLastError;\n\t\n\tcurTime = time(NULL);\n\tpImg->SetImageStartTime(curTime);\n\n\t// wait for exposure to complete\n\tdo {\n\t} while ((err = IsExposureComplete(expComp)) == CE_NO_ERROR && !expComp );\n\tEndExposure();\n\tif ( err != CE_NO_ERROR )\n\t\treturn err;\n\tif ( m_eLastError != CE_NO_ERROR )\n\t\treturn m_eLastError;\n\n\t// readout the CCD\n\tsrp.ccd = m_eActiveCCD;\n\tsrp.left = left;\n\tsrp.top = top;\n\tsrp.height = height;\n\tsrp.width = width;\n\tsrp.readoutMode = m_uReadoutMode;\n\tif ( (err = StartReadout(srp)) == CE_NO_ERROR ) {\n\t\trlp.ccd = m_eActiveCCD;\n\t\trlp.pixelStart = left;\n\t\trlp.pixelLength = width;\n\t\trlp.readoutMode = m_uReadoutMode;\n\t\tfor (i=0; i<height && err==CE_NO_ERROR; i++ )\n\t\t\terr = ReadoutLine(rlp, FALSE, pImg->GetImagePointer() + (long)i * width);\n\t}\n\tEndReadout();\n\tif ( err != CE_NO_ERROR )\n\t\treturn err;\n\tif ( m_eLastError != CE_NO_ERROR )\n\t\treturn err;\n\n\t// we're done unless we wanted a dark also image\n\tif ( dark == SBDF_DARK_ALSO ) {\n\t\t// start the light exposure\n\t\tif ( StartExposure(SC_OPEN_SHUTTER) != CE_NO_ERROR )\n\t\t\treturn m_eLastError;\n\t\tcurTime = time(NULL);\n\t\tpImg->SetImageStartTime(curTime);\n\n\t\t// wait for exposure to complete\n\t\tdo {\n\t\t} while ((err = IsExposureComplete(expComp)) == CE_NO_ERROR && !expComp );\n\t\tEndExposure();\n\t\tif ( err != CE_NO_ERROR )\n\t\t\treturn err;\n\t\tif ( m_eLastError != CE_NO_ERROR )\n\t\t\treturn m_eLastError;\n\n\t\t// readout the CCD\n\t\tsrp.ccd = m_eActiveCCD;\n\t\tsrp.left = left;\n\t\tsrp.top = top;\n\t\tsrp.height = height;\n\t\tsrp.width = width;\n\t\tsrp.readoutMode = m_uReadoutMode;\n\t\tif ( (err = StartReadout(srp)) == CE_NO_ERROR ) {\n\t\t\trlp.ccd = m_eActiveCCD;\n\t\t\trlp.pixelStart = left;\n\t\t\trlp.pixelLength = width;\n\t\t\trlp.readoutMode = m_uReadoutMode;\n\t\t\tfor (i=0; i<height && err==CE_NO_ERROR; i++ )\n\t\t\t\terr = ReadoutLine(rlp, TRUE, pImg->GetImagePointer() + (long)i * width);\n\t\t}\n\t\tEndReadout();\n\t\tif ( err != CE_NO_ERROR )\n\t\t\treturn err;\n\t\tif ( m_eLastError != CE_NO_ERROR )\n\t\t\treturn err;\n\n\t\t// record dark subtraction in history\n\t\tif ( m_eCameraType == ST5C_CAMERA || m_eCameraType == ST237_CAMERA )\n\t\t\tpImg->SetHistory(\"f\");\n\t\telse\n\t\t\tpImg->SetHistory(\"R\");\n\t}\n\n\t// set the note to the local time\n\tif ( pImg->GetImageNote().length() == 0 ) {\n\t\tpLT = localtime(&curTime);\n\t\tsprintf(cs, \"Local time:%d/%d/%4d at %d:%02d:%02d\",\n\t\t\tpLT->tm_mon+1, pLT->tm_mday, pLT->tm_year+1900,\n\t\t\tpLT->tm_hour, pLT->tm_min, pLT->tm_sec);\n\t\tpImg->SetImageNote(cs);\n\t}\n\n\treturn CE_NO_ERROR;\t\n}\n\n\n/*\n \n\tStartExposure:\n\t\t\n\tStart an exposure in the camera. Should be matched\n\twith an EndExposure call.\n\t\n*/\nPAR_ERROR CSBIGCam::StartExposure(SHUTTER_COMMAND shutterState)\n{\n\tStartExposureParams sep;\n\tsep.ccd = m_eActiveCCD;\n\tsep.exposureTime = (unsigned long)(m_dExposureTime * 100.0 + 0.5);\n\t//adding START_SKIP_VDD should speed up the process, but may result in a glow on the side of the image\n//\tsep.ccd = m_eActiveCCD + START_SKIP_VDD;\n//\tsep.exposureTime = (unsigned long)(m_dExposureTime * 100.0 + 0.5 + EXP_SEND_TRIGGER_OUT);\n\tif ( sep.exposureTime < 1 )\n\t\tsep.exposureTime = 1;\n\tsep.abgState = m_eABGState;\n\tsep.openShutter = shutterState;\n\tif ( CheckLink() ) \n\t\treturn SBIGUnivDrvCommand(CC_START_EXPOSURE, &sep, NULL);\n\telse \n\t\treturn m_eLastError;\n}\n\n/*\n \n\tEndExposure:\n\t\t\n\tEnd or abort an exposure in the camera. Should be\n\tmatched to a StartExposure but no damage is done\n\tby calling it by itself if you don't know if an\n\texposure was started for example.\n\t\n*/\nPAR_ERROR CSBIGCam::EndExposure(void)\n{\n\tEndExposureParams eep;\n\t\n\teep.ccd = m_eActiveCCD;\n\tif ( CheckLink() )\n\t\treturn SBIGUnivDrvCommand(CC_END_EXPOSURE, &eep, NULL);\n\telse\n\t\treturn m_eLastError;\n}\n\n/*\n \n\tIsExposueComplete:\n\t\t\n\tQuery the camera to see if the exposure in progress is complete.\n\tThis returns TRUE if the CCD is idle (an exposure was never\n\tstarted) or if the CCD exposure is complete.\n\t\n*/\nPAR_ERROR CSBIGCam::IsExposureComplete(MY_LOGICAL &complete)\n{\n\tQueryCommandStatusParams qcsp;\n\tQueryCommandStatusResults qcsr;\n\t\n\tcomplete = FALSE;\n\tif ( CheckLink() ) {\n\t\tqcsp.command = CC_START_EXPOSURE;\n\t\tif ( SBIGUnivDrvCommand(CC_QUERY_COMMAND_STATUS, &qcsp, &qcsr) == CE_NO_ERROR ) {\n\t\t\tif ( m_eActiveCCD == CCD_IMAGING )\n\t\t\t\tcomplete = (qcsr.status & 0x03) != 0x02;\n\t\t\telse\n\t\t\t\tcomplete = (qcsr.status & 0x0C) != 0x08;\n\t\t}\n\t}\n\treturn m_eLastError;\n}\n\n/*\n \n\tStartReadout:\n\t\t\n\tStart the readout process. This should be called\n\tafter EndExposure and should be matched with an\n\tEndExposure call.\n\t\n*/\nPAR_ERROR CSBIGCam::StartReadout(StartReadoutParams srp)\n{\n\tif ( CheckLink() )\n\t\treturn SBIGUnivDrvCommand(CC_START_READOUT, &srp, NULL);\n\telse\n\t\treturn m_eLastError;\n}\n\n/*\n \n\tEndReadout:\n\t\t\n\tEnd a readout started with StartReadout.\n\tDon't forget to make this call to prepare the\n\tCCD for idling.\n\t\n*/\nPAR_ERROR CSBIGCam::EndReadout(void)\n{\n\tEndReadoutParams erp;\n\t\n\terp.ccd = m_eActiveCCD;\n\tif ( CheckLink() )\n\t\treturn SBIGUnivDrvCommand(CC_END_READOUT, &erp, NULL);\n\telse\n\t\treturn m_eLastError;\n}\n\n/*\n \n\tReadoutLine:\n\t\t\n\tReadout a line of data from the camera, optionally\n\tperforming a dark subtraction, placing the data\n\tat dest.\n\t\n*/\nPAR_ERROR CSBIGCam::ReadoutLine(ReadoutLineParams rlp, MY_LOGICAL darkSubtract,\n\t\t\t\t\t\t\t\tunsigned short *dest)\n{\n\tif ( CheckLink() ) {\n\t\tif ( darkSubtract )\n\t\t\treturn SBIGUnivDrvCommand(CC_READ_SUBTRACT_LINE, &rlp, dest);\n\t\telse\n\t\t\treturn SBIGUnivDrvCommand(CC_READOUT_LINE, &rlp, dest);\n\t}\n\telse\n\t\treturn m_eLastError;\n\t\n}\n\n/*\n \n\tDumpLines:\n\t\t\n\tDiscard data from one or more lines in the camera.\n\t\n*/\nPAR_ERROR CSBIGCam::DumpLines(unsigned short noLines)\n{\n\tDumpLinesParams dlp;\n\t\n\tdlp.ccd = m_eActiveCCD;\n\tdlp.lineLength = noLines;\n\tdlp.readoutMode = m_uReadoutMode;\n\tif ( CheckLink() )\n\t\treturn SBIGUnivDrvCommand(CC_DUMP_LINES, &dlp, NULL);\n\telse\n\t\treturn m_eLastError;\n}\n\n/*\n \n\tSetTemperatureRegulation:\n\t\t\n\tEnable or disable the temperatre controll at\n\tthe passed setpoint which is the absolute\n\t(not delta) temperature in degrees C.\n\t\n*/\nPAR_ERROR CSBIGCam::SetTemperatureRegulation(MY_LOGICAL enable, double setpoint)\n{\n\tSetTemperatureRegulationParams strp;\n\t\n\tif ( CheckLink() ) {\n\t\tstrp.regulation = enable ? REGULATION_ON : REGULATION_OFF;\n\t\tstrp.ccdSetpoint = DegreesCToAD(setpoint, TRUE);\n\t\treturn SBIGUnivDrvCommand(CC_SET_TEMPERATURE_REGULATION, &strp, NULL);\n\t}\n\telse\n\t\treturn m_eLastError;\n}\n\n/*\n \n\tQueryTemperatureStatus:\n\t\t\n\tGet whether the cooling is enabled, the CCD temp\n\tand setpoint in degrees C and the percent power\n\tapplied to the TE cooler.\n\t\n*/\nPAR_ERROR CSBIGCam::QueryTemperatureStatus(MY_LOGICAL &enabled, double &ccdTemp,\n\t\t\t\t\t\t\t\t\t\t double &setpointTemp, double &percentTE)\n{\n\tQueryTemperatureStatusResults qtsr;\n\t\n\tif ( CheckLink() ) {\n\t\tif ( SBIGUnivDrvCommand(CC_QUERY_TEMPERATURE_STATUS, NULL, &qtsr) == CE_NO_ERROR )\n\t\t{\n\t\t\tenabled = qtsr.enabled;\n\t\t\tccdTemp = ADToDegreesC(qtsr.ccdThermistor, TRUE);\n\t\t\tsetpointTemp = ADToDegreesC(qtsr.ccdSetpoint, TRUE);\n\t\t\tpercentTE = qtsr.power/255.0;\n\t\t}\n\t}\n\treturn m_eLastError;\n}\n\n/*\n \n\tGetCCDTemperature:\n\t\t\n\tRead and return the current CCD temperature.\n\t\n*/\nPAR_ERROR CSBIGCam::GetCCDTemperature(double &ccdTemp)\n{\n\tdouble setpointTemp, percentTE;\n\tMY_LOGICAL teEnabled;\n\t\n\treturn QueryTemperatureStatus(teEnabled, ccdTemp, setpointTemp, percentTE);\n}\n\n\n/*\n \n\tActivateRelay:\n\t\t\n\tActivate one of the four relays for the passed\n\tperiod of time. Cancel a relay by passing\n\tzero for the time.\n\t\n*/\nPAR_ERROR CSBIGCam::ActivateRelay(CAMERA_RELAY relay, double time)\n{\n\tActivateRelayParams arp;\n\tunsigned short ut;\n\t\n\tif ( CheckLink() ) {\n\t\tarp.tXMinus = arp.tXPlus = arp.tYMinus = arp.tYPlus = 0;\n\t\tif ( time >= 655.35 )\n\t\t\tut = 65535;\n\t\telse\n\t\t\tut = (unsigned short)(time/0.01);\n\t\tswitch ( relay ){\n\t\tcase RELAY_XPLUS: arp.tXPlus = ut; break;\n\t\tcase RELAY_XMINUS: arp.tXMinus = ut; break;\n\t\tcase RELAY_YPLUS: arp.tYPlus = ut; break;\n\t\tcase RELAY_YMINUS: arp.tYMinus = ut; break;\n\t\t}\n\t\treturn SBIGUnivDrvCommand(CC_ACTIVATE_RELAY, &arp, NULL);\n\t}\n\telse\n\t\treturn m_eLastError;\n}\n\n/*\n\n\tIsRelayActive:\n\n\tReturns tru in the passed parameter if the passed\n\trelay is active.\n\n*/\nPAR_ERROR CSBIGCam::IsRelayActive(CAMERA_RELAY relay, MY_LOGICAL &active)\n{\n\tQueryCommandStatusParams qcsp;\n\tQueryCommandStatusResults qcsr;\n\n\tif ( CheckLink() ) {\n\t\tqcsp.command = CC_ACTIVATE_RELAY;\n\t\tif ( SBIGUnivDrvCommand(CC_QUERY_COMMAND_STATUS, &qcsp, &qcsr) == CE_NO_ERROR ) {\n\t\t\tactive = FALSE;\n\t\t\tswitch ( relay ){\n\t\t\tcase RELAY_XPLUS: active = ((qcsr.status & 8) != 0); break;\n\t\t\tcase RELAY_XMINUS: active = ((qcsr.status & 4) != 0); break;\n\t\t\tcase RELAY_YPLUS: active = ((qcsr.status & 2) != 0); break;\n\t\t\tcase RELAY_YMINUS: active = ((qcsr.status & 1) != 0); break;\n\t\t\t}\n\t\t}\n\t}\n\treturn m_eLastError;\n}\n\n/*\n \n\tAOTipTilt:\n\t\t\n\tSend a tip/tilt command to the AO-7.\n\t\n*/\nPAR_ERROR CSBIGCam::AOTipTilt(AOTipTiltParams attp)\n{\n\tif ( CheckLink() )\n\t\treturn SBIGUnivDrvCommand(CC_AO_TIP_TILT, &attp, NULL);\n\telse\n\t\treturn m_eLastError;\n}\n\n/*\n \n\tCFWCommand:\n\t\t\n\tSend a command to the Color Filter Wheel.\n\t\n*/\nPAR_ERROR CSBIGCam::CFWCommand(CFWParams cfwp, CFWResults &cfwr)\n{\n\tif ( CheckLink() )\n\t\treturn SBIGUnivDrvCommand(CC_CFW, &cfwp, &cfwr);\n\telse\n\t\treturn m_eLastError;\n}\n\n/*\n \n\tEstablishLink:\n\t\t\n\tOnce the driver and device are open call this to\n\testablish a communications link with the camera.\n\tMay be called multiple times without problem.\n\t\n\tIf there's no error and you want to find out what\n\tmodel of camera was found use the GetCameraType()\n\tfunction.\n\t\n*/\nPAR_ERROR CSBIGCam::EstablishLink(void)\n{\n\tPAR_ERROR res;\n\tEstablishLinkResults elr;\n\tEstablishLinkParams elp;\n\t\n\tres = SBIGUnivDrvCommand(CC_ESTABLISH_LINK, &elp, &elr);\n\tif ( res == CE_NO_ERROR )\n\t\tm_eCameraType = (CAMERA_TYPE)elr.cameraType;\n\treturn res;\n}\n\n/*\n \n\tGetErrorString:\n\t\t\n\tReturns a ANSI C++ standard string object describing\n\tthe error code returned from the lass call to the driver.\n\t\n*/\nstring CSBIGCam::GetErrorString()\n{\n\treturn GetErrorString(m_eLastError);\n}\n\n/*\n \n\tCheckLink:\n\t\t\n\tIf a link has been established to a camera return TRUE.\n\tOtherwise try to establish a link and if successful\n\treturn TRUE. If fails return FALSE.\n\t\n*/\nMY_LOGICAL CSBIGCam::CheckLink(void)\n{\n\tif ( m_eCameraType != NO_CAMERA || EstablishLink() == CE_NO_ERROR )\n\t\treturn TRUE;\n\telse\n\t\treturn FALSE;\n}\n\n/*\n \n\tDegreesCToAD:\n\t\t\n\tConvert temperatures in degrees C to\n\tcamera AD setpoints.\n\t\n*/\nunsigned short CSBIGCam::DegreesCToAD(double degC, MY_LOGICAL ccd /* = TRUE */)\n{\n\tdouble r;\n\tunsigned short setpoint;\n\t\n\tif ( degC < -50.0 )\n\t\tdegC = -50.0;\n\telse if ( degC > 35.0 )\n\t\tdegC = 35.0;\n\tif ( ccd ) {\n\t\tr = R0 * exp(log(RR_CCD)*(T0 - degC)/DT_CCD);\n\t\tsetpoint = (unsigned short)(MAX_AD/((RB_CCD/r) + 1.0) + 0.5);\n\t} else {\n\t\tr = R0 * exp(log(RR_AMB)*(T0 - degC)/DT_AMB);\n\t\tsetpoint = (unsigned short)(MAX_AD/((RB_AMB/r) + 1.0) + 0.5);\n\t}\n\treturn setpoint;\n}\n\n/*\n \n\tADToDegreesC:\n\t\t\n\tConvert camera AD temperatures to\n\tdegrees C\n\t\n*/\ndouble CSBIGCam::ADToDegreesC(unsigned short ad, MY_LOGICAL ccd /* = TRUE */)\n{\n\tdouble r, degC;\n\t\n\tif ( ad < 1 )\n\t\tad = 1;\n\telse if ( ad >= MAX_AD - 1 )\n\t\tad = MAX_AD - 1;\n\tif ( ccd ) {\n\t\tr = RB_CCD/(((double)MAX_AD/ad) - 1.0);\n\t\tdegC = T0 - DT_CCD*(log(r/R0)/log(RR_CCD));\n\t} else {\n\t\tr = RB_AMB/(((double)MAX_AD/ad) - 1.0);\n\t\tdegC = T0 - DT_AMB*(log(r/R0)/log(RR_AMB));\n\t}\n\treturn degC;\n}\n" }, { "alpha_fraction": 0.6473029255867004, "alphanum_fraction": 0.6763485670089722, "avg_line_length": 33.42856979370117, "blob_id": "1ee18bc8bf4b632856b1e98942208718af00d70a", "content_id": "28671e6d706659d6ffd26e8cc7005b1704afa19a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 482, "license_type": "no_license", "max_line_length": 118, "num_lines": 14, "path": "/install_and_restart_mcp.sh", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\nTMP_DIR=\"/tmp\"\nINSTALL_DIR=\"/usr/local/bin\"\n\nINF_LOOP_CHECK=\"cd; sudo pkill blast_inf_loop; sudo nohup ./start_blast_inf_loop > /dev/null 2> /dev/null < /dev/null\"\nKILL_MCP=\"sudo kill -INT \\$(pidof mcp) > /dev/null 2>&1\"\nINSTALL_MCP=\"install -m 755 -p $TMP_DIR/mcp $INSTALL_DIR/\" \n\nscp mcp fc1user@fc1:$TMP_DIR/ \nscp mcp fc1user@fc2:$TMP_DIR/\n\nssh -t fc1user@fc1 \"$INF_LOOP_CHECK; $INSTALL_MCP; $KILL_MCP\"\nssh -t fc1user@fc2 \"$INF_LOOP_CHECK; $INSTALL_MCP; $KILL_MCP\"\n" }, { "alpha_fraction": 0.623680591583252, "alphanum_fraction": 0.639284074306488, "avg_line_length": 28.849315643310547, "blob_id": "c4cf6b490f1fb93b5d9ac1f56b9655602e55e6b8", "content_id": "42bc4812c05f3b241082c9d2075ff7890b7d2bb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2179, "license_type": "no_license", "max_line_length": 105, "num_lines": 73, "path": "/owl/PTimeDataItem.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"PTimeDataItem.h\"\n#include <ctime>\n#include <unistd.h>\n\n\nvoid PTimeDataItem::gdUpdate(GetData::Dirfile* dirFile,int lastNFrames)\n{\n double indata;\n bool ok;\n\n indata = gdReadRawData(dirFile, lastNFrames, ok);\n\n //sanity check:\n if ((indata < 0.0) || (indata > INT_MAX)) {\n // this is not a time. Don't use it!\n indata = 0.0;\n }\n if (ok) {\n PStyle* style = _extrema\n ? _extrema->formatForValue(time(NULL) - indata,_defaultDataStyle)\n : _defaultDataStyle;\n\n if(prevStyle!=style|| //the reason this works is because PStyleChooser works via reference to ptr\n style->_dirty) {\n applyStyle(this,style);\n prevStyle=style;\n }\n char tmp[255];\n time_t timetmp = (time_t)indata;\n struct tm* currTime;\n\n currTime = gmtime(&timetmp);\n strftime(tmp, 255, _format.toStdString().c_str(), currTime);\n if(_data->text()!=tr(tmp)) {\n _data->setText(tr(tmp));\n _serverDirty=-1;\n } else --_serverDirty;\n }\n}\n\nQString PTimeDataItem::format() const {\n return _format;\n}\n\nvoid PTimeDataItem::setFormat(QString format,bool force) {\n if(!isCurrentObject()&&!force) return;\n if(_format==format) {\n return;\n }\n _format=format;\n emit formatChanged(format);\n}\n" }, { "alpha_fraction": 0.5606625080108643, "alphanum_fraction": 0.5797101259231567, "avg_line_length": 31.19333267211914, "blob_id": "a0ffc4147b602c0733fe2284b00372b26dbc2474", "content_id": "f9c35192ccf2f8eb3fe31fece65009b6588d4b02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4830, "license_type": "no_license", "max_line_length": 95, "num_lines": 150, "path": "/singalong/singalong.py", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#!/usr/bin/env /usr/bin/python\n\nimport time\nimport sys\nimport mpd\nimport re\nimport random\nimport pygetdata as gd\nimport numpy as np\n\n#setup for the mpd connection\nmpdHost = \"galadriel.blast\"\nmpdPort = 6606\nmpdPass = \"250micron\"\n\n#setup for the dirfile\ndirfilePath = \"/data/etc/fox.lnk\"\n\n\n#region to song mapping\nsongNameLookup = {\n \"VYCma\":\t ('title', \"YMCA\", \\\n\t\t 'artist', \"Village People, The\"),\n \"CG12\":\t ('title', \"Don't Stop Believin'\", \\\n\t\t 'artist', \"Journey\"),\n \"Spearhead\": ('title', 'Theme from \"Shaft\"', \\\n\t\t 'artist', \"Hayes, Isaac\"),\n \"Mickey\":\t ('title', \"Hey Mickey\", \\\n\t\t 'artist', \"Basil, Toni\"),\n \"Lupus1a\":\t ('title', \"Hungry Like the Wolf\", \\\n\t\t 'artist', \"Duran Duran\"),\n \"Lupus1b\":\t ('title', \"Walking on Sunshine\", \\\n\t\t 'artist', \"Katrina & the Waves\"),\n \"NatsRegion\": ('title', \"The Good, the Bad, and the Ugly\", \\\n\t\t 'artist', \"Morricone, Ennio\"),\n \"IRAS15100\": ('title', \"Home\", \\\n\t\t 'artist', \"Edward Sharpe & The Magnetic Zeros\"),\n \"Nanten\":\t ('title', \"Turning Japanese\", \\\n\t\t 'artist', \"Vapors, The\"),\n \"M83\":\t ('title', \"Eye of the Tiger\", \\\n\t\t 'artist', \"Survivor\"),\n \"Axehead\":\t ('artist', \"U2\"),\n \"CarinaTan\": ('title', \"O... Saya\", \\\n\t\t 'artist', \"A.R. Rahman & M.I.A.\"),\n \"G333\":\t ('title', \"Not Ready to Make Nice\", \\\n\t\t 'artist', \"Dixie Chicks\"),\n \"G331\":\t ('title', \"The Cave\", \\\n\t\t 'artist', \"Albarn, Damon / Nyman, Michael\"),\n \"G3219\":\t ('title', \"To The Dogs Or Whoever\", \\\n\t\t 'artist', \"Josh Ritter\"),\n \"G3199\":\t ('album', \"Thriller\", \\\n\t\t 'artist', \"Jackson, Michael\"),\n \"G3047\":\t ('title', \"Oxford Comma\", \\\n\t\t 'artist', \"Vampire Weekend\"),\n \"G3237\":\t ('title', \"Blame Canada\", \\\n\t\t 'album', \"South Park - Bigger, Longer, & Uncut\"),\n \"G3265\":\t ('title', \"Hallelujah\", \\\n\t\t 'artist', \"Cohen, Leonard\", \\\n\t\t 'album', \"Various Positions\"),\n \"G3290\":\t ('title', \"Throne Room and Finale\", \\\n\t 'artist', \"Williams, John and the Skywalker Symphony Orchestra\"),\n \"G3168\":\t ('title', \"Awesome God\", \\\n\t\t 'artist', \"Praise Band\"),\n \"CenA\":\t ('title', 'Danger Zone (Theme from \"Top Gun\")', \\\n\t\t 'artist', \"Loggins, Kenny\"),\n \"NGC4945\":\t ('title', \"White Winter Hymnal\", \\\n\t\t 'artist', \"Fleet Foxes\", \\\n\t\t 'album', \"Fleet Foxes\")\n }\n\n#find songs in the database, make more useful lookup\nsongLookup = dict()\nclient = mpd.MPDClient();\nclient.connect(mpdHost, mpdPort)\nclient.password(mpdPass)\n\nfor region in songNameLookup.iterkeys():\n songs = client.find(*songNameLookup[region])\n songLookup[region] = songs\n print region, len(songs), \"song matches\"\n\nclient.close()\nclient.disconnect()\n\n#function to pick random song from list for targets\ndef playSong(key):\n client.connect(mpdHost, mpdPort)\n client.password(mpdPass)\n songs = songLookup[key]\n song = songs[random.randint(0, len(songs)-1)]\n pl = client.playlist()\n cur = client.currentsong()\n if(pl and cur):\n idx = client.playlist().index(cur['file'])\n client.addid(song['file'], idx+1)\n client.play(idx+1) #length one higher now, with added song\n else:\n client.add(song['file'])\n client.play(len(pl))\n client.close()\n client.disconnect()\n\n#parse schedule file passed as command line argument\nschedparser = re.compile(r\"\\w+\\s+(?P<day>[0-9.]+)\\s+(?P<hour>[0-9.]+)[^#]*#\\s*(?P<name>\\S*).*\")\nschedule = [];\nwith open(sys.argv[1]) as f:\n for line in f:\n match = schedparser.match(line)\n if (match):\n lst = (float(match.group(\"day\"))*24*3600 \\\n\t + float(match.group(\"hour\"))*3600)\n schedule.append( (lst, match.group(\"name\")) )\n\nprint \"\\nSchedule parsed with\", len(schedule), \"command lines\"\nprint\nprint \"************************************************************\"\nprint \"* Starting main loop, waiting for new scans *\"\nprint \"************************************************************\"\nprint\n\n#main loop. read LST_SCHED and if it crosses a schedule threshold, play the song\ntry:\n while True:\n df = gd.dirfile(dirfilePath, gd.RDONLY)\n lst = df.getdata(\"LST_SCHED\", gd.FLOAT, \\\n\tfirst_frame=df.nframes-1, num_frames=1)[0]\n df.close()\n newsong = False\n try:\n while lst > schedule[1][0]:\n\tschedule.pop(0)\n\tprint \"Passed threshold\", schedule[0][0], \"<\", lst, \\\n\t \"for region\", schedule[0][1]\n\tnewsong = True\n if newsong:\n\t#can't do direct songLookup access because names may have modifier chars\n\tfor region in songLookup.iterkeys():\n\t if schedule[0][1].find(region) >= 0:\n\t print \"New song!\", schedule[0][1], \"matches\", region\n\t playSong(region)\n\t break\n\telse:\n\t print \"Could not find song match for\", schedule[0][1]\n time.sleep(1)\n except IndexError:\n print \"Schedule out of commands! Do something! Forget about music!\"\n sys.exit(1)\n\nexcept KeyboardInterrupt:\n print \"bye\"\n\n" }, { "alpha_fraction": 0.588688313961029, "alphanum_fraction": 0.6018179655075073, "avg_line_length": 30.68400001525879, "blob_id": "d52a2d0a6b0c17a1d5c1782075cf0dc90e083643", "content_id": "a6d10352063c1384f27b79f4bab603adeee33bc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7921, "license_type": "no_license", "max_line_length": 162, "num_lines": 250, "path": "/owl/PAbstractDataItem.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"PAbstractDataItem.h\"\n#include \"PMainWindow.h\"\n#include <QMouseEvent>\n#include <QApplication>\n#include <QDebug>\n#include <QDrag>\n#include <QMimeData>\n#include <QProcess>\n#include <QTemporaryFile>\n\n//#include <QPlastiqueStyle>\n\n#ifdef __APPLE__\n#include <python2.6/Python.h>\n#else\n#include <python2.7/Python.h> //you may need to change this\n#endif\n\nstatic int _delaysThisCycle = 0;\n\nPAbstractDataItem::PAbstractDataItem(PBox* parent, QString caption) : QWidget(parent), _layout(new QHBoxLayout()),\n _caption(new QLabel(caption)), _captionStyle(PStyle::noStyle), _defaultDataStyle(PStyle::noStyle),\n _lastCapStyle(0), _data(new QLabel(tr(\"Loading\"))), _serverDirty(-1), _neverGood(true), _sourceBad(false)\n{\n connect(PStyleNotifier::me,SIGNAL(change()),this,SLOT(pstyleLogic()));\n setLayout(_layout);\n _layout->setMargin(0);\n _layout->setSpacing(0);\n _layout->addWidget(_caption);\n _layout->addWidget(_data);\n parent->_dirty=1;\n// QPlastiqueStyle* ps=new QPlastiqueStyle;\n// _caption->setStyle(ps);\n// _data->setStyle(ps);\n}\n\nPAbstractDataItem::PAbstractDataItem(PBox* parent, PAbstractDataItem* other) : QWidget(parent), _layout(new QHBoxLayout()),\n _caption(new QLabel(other->caption())), _captionStyle(other->_captionStyle), _defaultDataStyle(other->_defaultDataStyle),\n _lastCapStyle(0), _data(new QLabel(tr(\"Loading\"))), _source(other->_source), _serverDirty(-1)\n{\n connect(PStyleNotifier::me,SIGNAL(change()),this,SLOT(pstyleLogic()));\n setLayout(_layout);\n _layout->setMargin(0);\n _layout->setSpacing(0);\n _layout->addWidget(_caption);\n _layout->addWidget(_data);\n parent->_dirty=1;\n// QPlastiqueStyle* ps=new QPlastiqueStyle;\n// _caption->setStyle(ps);\n// _data->setStyle(ps);\n}\n\nint PAbstractDataItem::delaysThisCycle() {\n return _delaysThisCycle;\n}\n\nvoid PAbstractDataItem::newCycle() {\n _delaysThisCycle = 0;\n}\n\nvoid PAbstractDataItem::incrementDelays() {\n _delaysThisCycle++;\n}\n\nQString PAbstractDataItem::caption() const\n{\n return _caption->text();\n}\n\nQString PAbstractDataItem::data() const\n{\n return _data->text();\n}\n\nQString PAbstractDataItem::source() const\n{\n return _source;\n}\n\nvoid PAbstractDataItem::mousePressEvent(QMouseEvent *event)\n{\n if (PMainWindow::me->mouseInactive()) return;\n\n emit activated();\n\n if(event) {\n if (event->button() == Qt::LeftButton) {\n _dragStartPos = event->pos();\n }\n }\n}\n\nvoid PAbstractDataItem::mouseDoubleClickEvent(QMouseEvent*)\n{\n QTemporaryFile tmpfile;\n if (tmpfile.open()) { //QIODevice::WriteOnly | QIODevice::Text)) {\n tmpfile.write(QString(\n \"import pykst as kst\\n\"\n \"client = kst.Client(\\\"\"+QString(getenv(\"USER\"))+\"-owl\\\")\\n\"\n \"x=client.new_data_vector(\\\"\"+QString(PMainWindow::me->_dirfileFilename)+\"\\\",field = \\\"INDEX\\\", start=-1, num_frames=1000)\\n\"\n \"y=client.new_data_vector(\\\"\"+QString(PMainWindow::me->_dirfileFilename)+\"\\\",field = \\\"\"+QString(source())+\"\\\", start=-1, num_frames=1000)\\n\"\n \"c=client.new_curve(x,y)\\n\"\n \"p=client.new_plot()\\n\"\n \"p.add(c)\\n\"\n ).toLatin1());\n QString filename = tmpfile.fileName();\n tmpfile.close();\n QProcess::execute (\"python2.7 \" + filename);\n } else {\n printf(\"could not write to file!\");\n }\n\n /* // This died. Don't know why.\n PyRun_SimpleString(QString(\n \"import pykst as kst\\n\"\n \"client = kst.Client(\\\"\"+QString(getenv(\"USER\"))+\"-owl\\\")\\n\"\n \"x=client.new_data_vector(\\\"\"+QString(PMainWindow::me->_dirfileFilename)+\"\\\",field = \\\"INDEX\\\", start=-1, num_frames=1000)\\n\"\n \"y=client.new_data_vector(\\\"\"+QString(PMainWindow::me->_dirfileFilename)+\"\\\",field = \\\"\"+QString(source())+\"\\\", start=-1, num_frames=1000)\\n\"\n \"c=client.new_curve(x,y)\\n\"\n \"p=client.new_plot()\\n\"\n \"p.add(c)\\n\"\n ).toLatin1());\n */\n\n}\n\nvoid PAbstractDataItem::mouseMoveEvent(QMouseEvent *event)\n{\n if (PMainWindow::me->mouseInactive()) return;\n\n if (!(event->buttons() & Qt::LeftButton))\n return;\n if ((event->pos() - _dragStartPos).manhattanLength() < QApplication::startDragDistance())\n return;\n\n QDrag *drag = new QDrag(this);\n QMimeData *mimeData = new QMimeData;\n\n mimeData->setData(\"text/plain\", (PMainWindow::me->_dirfileFilename+\"#\"+_source).toLatin1());\n mimeData->setData(\"application/x-owlid\", QByteArray::number(id()));\n drag->setMimeData(mimeData);\n\n drag->exec(Qt::CopyAction | Qt::MoveAction);\n}\n\nvoid PAbstractDataItem::setCaption(QString x, bool force) {\n if(!isCurrentObject()&&!force) {\n return;\n }\n\n if(_caption->text()==x) {\n return;\n }\n _caption->setText(x);\n emit textChanged(x);\n dynamic_cast<PBox*>(parent())->_dirty=1;\n}\n\nvoid PAbstractDataItem::pstyleLogic() {\n if(_captionStyle!=_lastCapStyle|| //the reason this works is because PStyleChooser works via reference to ptr\n _captionStyle->_dirty) {\n applyStyle(_caption,_captionStyle);\n _lastCapStyle=_captionStyle;\n }\n}\n\nvoid PAbstractDataItem::setSource(QString x,bool force) {\n if(!isCurrentObject()&&!force) return;\n if(x==_source) {\n return;\n }\n _source=x;\n _sourceBad = false;\n _neverGood = true;\n emit sourceChanged(x);\n}\n\nvoid PAbstractDataItem::activate()\n{\n emit activated();\n}\n\ndouble PAbstractDataItem::gdReadRawData(GetData::Dirfile* dirFile,int lastNFrames, bool &ok)\n{\n double indata;\n\n ok = false;\n\n // Read in from disk\n int i=0;\n if (_sourceBad) { // we have determined that this field does not exist in the dirfile, so quit trying.\n return 0.0;\n }\n while (dirFile->GetData(_source.toStdString().c_str(),\n lastNFrames-1, 0, 0, 1, // 1 sample from frame nf-1\n GetData::Float64, (void*)(&indata))==0) {\n\n if (dirFile->Error()== GD_E_BAD_CODE) {\n _sourceBad = true;\n _data->setText(\"bad src\");\n return 0.0;\n }\n if (delaysThisCycle()<=5) {\n if (++i>=5) { // keep trying for 10 x 10000 uS = 0.05s\n if (_neverGood) {\n if(_data->text()!=\"bad src\") {\n _data->setText(\"bad src\");\n _serverDirty=-1;\n //_sourceBad = true;\n //qDebug() << \"field\" << _source << \"giving up after 50 tries\";\n } else {\n --_serverDirty;\n }\n }\n //qDebug() << \"field\" << _source << \"giving up after 5 tries\";\n return 0.0;\n }\n //qDebug() << \"field\" << _source << \"couldn't be read. Sleeping before trying again.\" << i;\n incrementDelays();\n usleep(10000);\n } else {\n return 0.0;\n }\n }\n _neverGood = false;\n\n ok = true;\n return (indata);\n}\n" }, { "alpha_fraction": 0.5431606769561768, "alphanum_fraction": 0.5803452730178833, "avg_line_length": 28.880952835083008, "blob_id": "2241f0895e22e91b48442cfeca068f40c2e3b3f0", "content_id": "62b75aa01b1d94ab66e6df8426e5a13b112ec853", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3765, "license_type": "no_license", "max_line_length": 119, "num_lines": 126, "path": "/test_programs/mpsse/test_biphase.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <signal.h>\n#include <sys/time.h>\n\n#include \"mpsse.h\"\n#include \"blast.h\"\n#include \"crc.h\"\n\n#define IFACE_A 0;\n#define IFACE_B 1;\n#define IFACE_C 2;\n#define IFACE_D 3;\n\nvoid send_biphase_writes();\nvoid send_bitbang_value();\n\nstruct mpsse_ctx *ctx; \n\n\nint main(int argc, char *argv[]) {\n\n\tconst uint16_t vid = 1027;\n\tconst uint16_t pid = 24593;\n\tconst char *serial = NULL;\n\tconst char *description = NULL;\n\tint channel = IFACE_A;\n int counter = 0;\n int frequency = 0;\n uint16_t frame_counter = 0;\n\n\n // The first open is a hack to make sure the chip is properly closed and reset\n\tctx = mpsse_open(&vid, &pid, description, serial, channel);\n usleep(1000);\n mpsse_reset_purge_close(ctx);\n usleep(1000);\n \n // This is now the real open \n\tctx = mpsse_open(&vid, &pid, description, serial, channel);\n usleep(1000);\n\n // Writing an array of data (0xFFFFFFFF...) through the bipase write functions\n\n uint16_t *data_to_write = NULL;\n uint16_t *inverse_data_to_write = NULL;\n size_t bytes_to_write = 1248; \n if (argc == 2) {\n frequency = atoi(argv[1]);\n } else {\n frequency = 1000000;\n }\n struct timeval begin, end;\n\n printf(\"The clock is set at %d bps\\n\", frequency);\n\n\n uint8_t data = 0x00;\n uint8_t dir = 0xFF; // direction output for all bits\n // uint8_t dir = 0xBF; // 0b10111111 pin 6 = input/read\n uint16_t crc_calculated;\n\n mpsse_set_data_bits_low_byte(ctx, data, dir);\n mpsse_set_data_bits_high_byte(ctx, data, dir);\n mpsse_flush(ctx);\n usleep(1000);\n mpsse_set_frequency(ctx, frequency);\n mpsse_flush(ctx);\n usleep(1000);\n // mpsse_purge(ctx);\n // usleep(1000);\n\n data_to_write = malloc(bytes_to_write); \n if (data_to_write) {\n *data_to_write = 0xEB90;\n for (int i = 1; i < ((int) bytes_to_write/2); i++) {\n *(data_to_write+i) = 0xFFFF;\n // *(data_to_write+i) = i;\n }\n } else {\n mpsse_close(ctx); \n return 0;\n }\n inverse_data_to_write = malloc(bytes_to_write); \n if (inverse_data_to_write) {\n *inverse_data_to_write = 0x146F;\n // *inverse_data_to_write = 0xEB90;\n for (int i = 1; i < ((int) bytes_to_write/2); i++) {\n *(inverse_data_to_write+i) = 0xFFFF;\n // *(inverse_data_to_write+i) = i;\n }\n } else {\n mpsse_close(ctx); \n return 0;\n }\n\n int last_word = ((int) bytes_to_write/2) - 1;\n\n for (int j=0; j>-1; j++) {\n gettimeofday(&begin, NULL);\n data_to_write[2] = frame_counter;\n if (j%2 == 0) {\n crc_calculated = crc16(CRC16_SEED, data_to_write, bytes_to_write-2);\n *(data_to_write+last_word) = crc_calculated; // I know 0xAB40 is the CRC if no counter in the frame\n mpsse_biphase_write_data(ctx, data_to_write, bytes_to_write);\n } else {\n inverse_data_to_write[2] = frame_counter;\n crc_calculated = crc16(CRC16_SEED, data_to_write, bytes_to_write-2);\n *(inverse_data_to_write+last_word) = crc_calculated; // I know 0xAB40 is the CRC if no counter in the frame\n mpsse_biphase_write_data(ctx, inverse_data_to_write, bytes_to_write);\n }\n mpsse_flush(ctx);\n gettimeofday(&end, NULL);\n if ((counter % 10) == 0) {\n blast_info(\"The CRC calculated is %04x\", crc_calculated);\n blast_dbg(\"It took %f second to write %zd bytes\", (end.tv_usec - begin.tv_usec)/1000000.0, bytes_to_write);\n }\n counter += 1;\n frame_counter++;\n // signal(SIGHUP, close_mpsse);\n // signal(SIGINT, close_mpsse);\n // signal(SIGTERM, close_mpsse);\n } \n}\n" }, { "alpha_fraction": 0.5452868342399597, "alphanum_fraction": 0.5784172415733337, "avg_line_length": 34.94827651977539, "blob_id": "2b2f79f6224c2556cf6fc0bff0ff4cb58559719d", "content_id": "7ea868249346c0cfc0db567b8d36497543600ed5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 27105, "license_type": "no_license", "max_line_length": 171, "num_lines": 754, "path": "/news/fox.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <termios.h>\n#include <time.h>\n#include <math.h>\n#include <string.h>\n#include <ctype.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <netdb.h>\n#include <sys/ioctl.h>\n#include <time.h>\n#include <string.h>\n#include <errno.h>\n\n#include \"compressstruct.h\"\n#include \"compressconst.h\"\n#include \"channels.h\"\n#include \"derived.h\"\n#include \"news.h\"\n\n#ifdef __SPIDER__\n#include \"tes.h\"\n#endif\n\n#define RAWDIR \"/data/rawdir\"\n\n#define FOX_LNKFILE \"/data/etc/fox.lnk\"\n#define RNC_PORT 41114\n#define FOX_EXT 'h'\n#define MSNBC_LNKFILE \"/data/etc/msnbc.lnk\"\n#define DNC_PORT 14441\n#define MSNBC_EXT 't'\n#define RUSH_LNKFILE \"/data/etc/rush.lnk\"\n#define TEA_PORT 14141\n#define RUSH_EXT 's'\n\n#define MAX_STREAM_FIELDS 400\n#define MAX_SAMPLES_PER_FRAME 100\n\nchar channelset_oth;\n\nchar LNKFILE[4096];\nint PORT;\nchar EXT;\n\nchar *GetArrayFieldName(int i_field);\n\nextern struct ChannelStruct WideSlowChannels[];\nextern struct ChannelStruct SlowChannels[];\nextern struct ChannelStruct WideFastChannels[];\nextern struct ChannelStruct FastChannels[];\nextern struct ChannelStruct DecomChannels[];\n\nextern char *frameList[];\nextern struct fieldStreamStruct streamList[N_OTH_SETS][MAX_OTH_STREAM_FIELDS];\n\nextern union DerivedUnion DerivedChannels[];\n\nint n_framefields = 0;\nstruct ChannelStruct **framefields;\nint *framefieldUnique;\n\nunsigned short n_streamfields = 0;\nunsigned short n_streamfieldlist = 0;\nint n_array_in_sframe;\n\nstruct ChannelStruct **streamfields;\nunsigned *stream_gains;\nlong long *stream_offsets;\n\nint n_sync = 0;\nint n_bytemon = 0;\nint is_lost = 1;\n\nint tty_fd;\nchar hostname[255];\n\n#ifdef NUM_ARRAY_STAT\nuint8_t array_statistics[NUM_ARRAY_STAT];\n#endif\n\n//*********************************************************\n// usage\n//*********************************************************\nvoid Usage(char *name) {\n fprintf(stderr,\"%s <hostname>\\n\"\n \"File Output eXtractor: \\n\"\n \"Connects to an rnc server and downloads and\\n\"\n \"produce defiles from an over the horizon link.\\n\", name);\n exit(0);\n}\n\n\n//*********************************************************\n// See if a field already exists - case sensitive\n//*********************************************************\nint FieldExists(char *field) {\n int i_field;\n\n for (i_field = 0; i_field<n_framefields; i_field++) {\n if (strcmp(field, framefields[i_field]->field)==0) {\n return(1);\n }\n }\n for (i_field = 0; i_field<n_streamfields; i_field++) {\n if (strcmp(field, streamfields[i_field]->field)==0) {\n return(1);\n }\n }\n return(0);\n}\n\n//*********************************************************\n// verify that a field is not listed in the stream field list\n//*********************************************************\nint FrameFieldIsUnique(char *field) {\n int i_field;\n for (i_field = 0; i_field<n_streamfields; i_field++) {\n if (strcmp(field, streamfields[i_field]->field)==0) {\n return(0);\n }\n }\n return(1); \n}\n\n//*********************************************************\n// Check to see if a raw field is in one of the lists\n// ignore case...\n//*********************************************************\nint FieldSupported(char *field) {\n int i_field;\n char lowerfield[512];\n\n convertToLower(field, lowerfield);\n\n for (i_field = 0; i_field<n_framefields; i_field++) {\n if (strcmp(lowerfield, framefields[i_field]->field)==0) {\n return(1);\n }\n }\n for (i_field = 0; i_field<n_streamfields; i_field++) {\n if (strcmp(lowerfield, streamfields[i_field]->field)==0) {\n return(1);\n }\n }\n return(0);\n}\n\n\n//*********************************************************\n// Make the format file\n//*********************************************************\nvoid MakeFormatFile(char *filedirname) {\n char formatfilename[1024];\n FILE *formatfile;\n int i_field;\n int i_derived;\n char fieldU[1024];\n\n /* Make format File */\n sprintf(formatfilename, \"%s/format\", filedirname);\n\n formatfile = fopen(formatfilename, \"w\");\n if (formatfile == NULL) {\n fprintf(stderr,\"Could not open format file %s\", formatfilename);\n exit(0);\n }\n for (i_field = 0; i_field < n_framefields; i_field++) {\n // if the frame field already appears in the stream list\n // then we won't add it to the format file, and we will\n // set the file pointer to point to /dev/null in\n // OpenDirfilePointers.\n framefieldUnique[i_field] = FrameFieldIsUnique(frameList[i_field]);\n \n if (framefieldUnique[i_field]) {\n convertToUpper( framefields[i_field]->field, fieldU);\n fprintf(formatfile, \"%-16s RAW %c 1\\n\", framefields[i_field]->field, framefields[i_field]->type);\n fprintf(formatfile, \"%-16s LINCOM 1 %16s %.12e %.12e 1\\n\", fieldU, framefields[i_field]->field,\n framefields[i_field]->m_c2e, framefields[i_field]->b_e2e);\n if (framefields[i_field]->quantity[0]!='\\0') {\n fprintf(formatfile, \"%s/quantity STRING %s\\n\",fieldU, framefields[i_field]->quantity);\n }\n if (framefields[i_field]->units[0]!='\\0') {\n fprintf(formatfile, \"%s/units STRING %s\\n\",fieldU, framefields[i_field]->units);\n }\n }\n }\n#ifdef __SPIDER__\n for (i_field = 0; i_field < NUM_ARRAY_STAT; i_field++) {\n fprintf(formatfile, \"%16s RAW c 1\\n\", GetArrayFieldName(i_field));\n }\n#endif\n\n for (i_field = 0; i_field < n_streamfields; i_field++) {\n convertToUpper( streamfields[i_field]->field, fieldU);\n fprintf(formatfile, \"%-16s RAW %c %d\\n\", streamfields[i_field]->field, streamfields[i_field]->type,\n streamList[channelset_oth][i_field].samples_per_frame);\n fprintf(formatfile, \"%-16s LINCOM 1 %16s %.12e %.12e 1\\n\", fieldU, streamfields[i_field]->field,\n streamfields[i_field]->m_c2e, streamfields[i_field]->b_e2e);\n if (streamfields[i_field]->quantity[0]!='\\0') {\n fprintf(formatfile, \"%s/quantity STRING %s\\n\",fieldU, streamfields[i_field]->quantity);\n }\n if (streamfields[i_field]->units[0]!='\\0') {\n fprintf(formatfile, \"%s/units STRING %s\\n\",fieldU, streamfields[i_field]->units);\n }\n }\n\n fprintf(formatfile, \"/REFERENCE %s\\n\", streamfields[n_streamfields-1]->field);\n // the Time field\n //fprintf(formatfile, \"Time RAW d 1\\n/REFERENCE Time\\n\");\n\n // Derived channels\n for (i_derived = 0; DerivedChannels[i_derived].comment.type != DERIVED_EOC_MARKER; ++i_derived) {\n switch (DerivedChannels[i_derived].comment.type) {\n case 'b': /* bitfield */\n if (FieldSupported(DerivedChannels[i_derived].bitfield.source)) {\n int j;\n // write bitfield\n fprintf(formatfile, \"\\n# %s BITFIELD:\\n\", DerivedChannels[i_derived].bitfield.source);\n for (j = 0; j < 16; ++j) {\n if (DerivedChannels[i_derived].bitfield.field[j][0]!='\\0') {\n fprintf(formatfile, \"%-16s BIT %-16s %i\\n\", DerivedChannels[i_derived].bitfield.field[j],\n DerivedChannels[i_derived].bitfield.source, j);\n }\n }\n }\n break;\n case '2': /* lincom2 */\n if (FieldExists(DerivedChannels[i_derived].lincom2.field)) {\n continue;\n }\n\n if (FieldSupported(DerivedChannels[i_derived].lincom2.source)) {\n if (FieldSupported(DerivedChannels[i_derived].lincom2.source2)) {\n // write lincom2\n fprintf(formatfile, \n \"%-16s LINCOM 2 %-16s %.12e %.12e %-16s %.12e %.12e\\n\",\n DerivedChannels[i_derived].lincom2.field, DerivedChannels[i_derived].lincom2.source,\n DerivedChannels[i_derived].lincom2.m_c2e, DerivedChannels[i_derived].lincom2.b_e2e,\n DerivedChannels[i_derived].lincom2.source2,\n DerivedChannels[i_derived].lincom2.m2_c2e,\n DerivedChannels[i_derived].lincom2.b2_e2e);\n }\n }\n break;\n case 'w': /* bitword */\n if (FieldSupported(DerivedChannels[i_derived].bitword.source)) {\n // write bitword\n fprintf(formatfile, \"%-16s BIT %-16s %i %i\\n\",\n DerivedChannels[i_derived].bitword.field, DerivedChannels[i_derived].bitword.source,\n DerivedChannels[i_derived].bitword.offset,\n DerivedChannels[i_derived].bitword.length);\n }\n break;\n case 't': /* linterp */\n if (FieldSupported(DerivedChannels[i_derived].linterp.source)) {\n // write linterp\n fprintf(formatfile, \"%-16s LINTERP %-16s %s\\n\",\n DerivedChannels[i_derived].linterp.field, DerivedChannels[i_derived].linterp.source,\n DerivedChannels[i_derived].linterp.lut);\n }\n break;\n case 'p': /* phase */\n if (FieldSupported(DerivedChannels[i_derived].phase.source)) {\n // write phase\n fprintf(formatfile, \"%-16s PHASE %-16s %i\\n\",\n DerivedChannels[i_derived].phase.field, DerivedChannels[i_derived].phase.source,\n DerivedChannels[i_derived].phase.shift);\n }\n break;\n case 'c': /* lincom */\n if (FieldExists(DerivedChannels[i_derived].lincom.field)) {\n continue;\n }\n\n if (FieldSupported(DerivedChannels[i_derived].lincom.source)) {\n // write lincom\n fprintf(formatfile, \"%-16s LINCOM 1 %-16s %.12e %.12e\\n\",\n DerivedChannels[i_derived].lincom.field, DerivedChannels[i_derived].lincom.source,\n DerivedChannels[i_derived].lincom.m_c2e, DerivedChannels[i_derived].lincom.b_e2e);\n }\n break;\n case '#': /* comment -- do nothing */\n break;\n case 'u': /* Units metadata */\n if (FieldSupported(DerivedChannels[i_derived].units.source)) {\n // write units\n fprintf(formatfile, \"%s/units STRING %s\\n%s/quantity STRING %s\\n\",\n DerivedChannels[i_derived].units.source, DerivedChannels[i_derived].units.units,\n DerivedChannels[i_derived].units.source, DerivedChannels[i_derived].units.quantity);\n }\n break;\n default: // unrecognized -- do nothing\n break;\n }\n }\n\n /* Hack for a few important derived of derived fields: BLAST10 and probably BLAST12 */\n/*\n fprintf(formatfile, \"DR_INFO_IO_RW LINCOM 2 DR_INFO_OPEN_RW 1.000000000000e+00 0.000000000000e+00 DR_INFO_INIT_1_RW 2.000000000000e+00 0.000000000000e+00\\n\");\n fprintf(formatfile, \"DR_INFO_IO_EL LINCOM 2 DR_INFO_OPEN_EL 1.000000000000e+00 0.000000000000e+00 DR_INFO_INIT_1_EL 2.000000000000e+00 0.000000000000e+00\\n\");\n fprintf(formatfile, \"DR_INFO_IO_PIV LINCOM 2 DR_INFO_OPEN_PIV 1.000000000000e+00 0.000000000000e+00 DR_INFO_INIT_1_PIV 2.000000000000e+00 0.000000000000e+00\\n\");\n fprintf(formatfile, \"DR_INFO_RIO_EL LINCOM 2 DR_INFO_RESET_EL 4.000000000000e+00 0.000000000000e+00 DR_INFO_IO_EL 1.000000000000e+00 0.000000000000e+00\\n\");\n fprintf(formatfile, \"DR_INFO_RIO_PIV LINCOM 2 DR_INFO_RESET_PIV 4.000000000000e+00 0.000000000000e+00 DR_INFO_IO_PIV 1.000000000000e+00 0.000000000000e+00\\n\");\n fprintf(formatfile, \"DR_INFO_RIO_RW LINCOM 2 DR_INFO_RESET_RW 4.000000000000e+00 0.000000000000e+00 DR_INFO_IO_RW 1.000000000000e+00 0.000000000000e+00\\n\");\n fprintf(formatfile, \"POT_STATE LINCOM 2 POT_IS_CLOSED 2.000000000000e+00 0.000000000000e+00 POT_IS_OPEN 1.000000000000e+00 0.000000000000e+00\\n\");\n fprintf(formatfile, \"LHE_STATE LINCOM 2 LHE_IS_CLOSED 2.000000000000e+00 0.000000000000e+00 LHE_IS_OPEN 1.000000000000e+00 0.000000000000e+00\\n\");\n fprintf(formatfile, \"LN_STATE LINCOM 2 LN_IS_CLOSED 2.000000000000e+00 0.000000000000e+00 LN_IS_OPEN 1.000000000000e+00 0.000000000000e+00\\n\");\n*/\n\n fclose(formatfile);\n\n}\n\n//*********************************************************\n// Make the list of frame channels\n//*********************************************************\nvoid MakeFrameList() {\n int i_field;\n\n // Initialize the channel lists\n // Count the frame channels\n for (n_framefields = 0; frameList[n_framefields][0] !='\\0'; n_framefields++);\n \n framefieldUnique = (int *) malloc(n_framefields * sizeof(int));\n\n // find and set the frame fields\n framefields = (struct ChannelStruct **)malloc(n_framefields * sizeof (struct ChannelStruct *));\n\n for (i_field = 0; i_field<n_framefields; i_field++) {\n \n framefields[i_field] = GetChannelStruct(frameList[i_field]);\n \n if (!framefields[i_field]) {\n fprintf(stderr,\"Error: could not find field in tx_struct! |%s|\\n\", frameList[i_field]);\n exit(0);\n }\n }\n\n}\n\n//*********************************************************\n// Make the list of stream channels\n//*********************************************************\nvoid MakeStreamList() {\n int i_streamfield;\n char *name;\n\n // Initialize the channel lists */\n // Count the frame channels\n for (n_streamfieldlist = 0; streamList[channelset_oth][n_streamfieldlist].name[0] !='\\0'; n_streamfieldlist++);\n \n // find and set the frame fields\n streamfields = (struct ChannelStruct **)malloc(n_streamfieldlist * sizeof (struct ChannelStruct *));\n stream_gains = (unsigned *)malloc(n_streamfieldlist*sizeof(unsigned));\n stream_offsets = (long long *)malloc(n_streamfieldlist*sizeof(long long));\n\n for (i_streamfield = 0; i_streamfield<n_streamfieldlist; i_streamfield++) {\n stream_gains[i_streamfield] = 1;\n stream_offsets[i_streamfield] = 0;\n\n name = streamList[channelset_oth][i_streamfield].name;\n\n streamfields[i_streamfield] = GetChannelStruct(name);\n \n if (!streamfields[i_streamfield]) {\n fprintf(stderr,\"Error: could not find field in tx_struct! |%s|\\n\", streamList[channelset_oth][i_streamfield].name);\n exit(0);\n }\n }\n}\n\n//*********************************************************\n// open the file pointers for the dirfile\n//*********************************************************\nvoid OpenDirfilePointers(int **fieldfp, int **streamfp, int **arraystatfp, char *filedirname) {\n int i_field;\n char filename[1024];\n \n *fieldfp = (int *) malloc((n_framefields+1) * sizeof(int));\n for (i_field = 0; i_field < n_framefields; i_field++) {\n if (framefieldUnique[i_field]) {\n sprintf(filename, \"%s/%s\", filedirname, framefields[i_field]->field);\n if( ((*fieldfp)[i_field] = open(filename, O_WRONLY | O_CREAT, 00644)) < 0 ) {\n fprintf(stderr,\"rnc: Could not create %s\\n\", filename);\n exit(0);\n }\n } else {\n (*fieldfp)[i_field] = open(\"/dev/null\", O_WRONLY);\n }\n }\n \n *streamfp = (int *) malloc(n_streamfields * sizeof(int));\n for (i_field = 0; i_field < n_streamfields; i_field++) {\n sprintf(filename, \"%s/%s\", filedirname, streamfields[i_field]->field);\n if( ((*streamfp)[i_field] = open(filename, O_WRONLY | O_CREAT, 00644)) < 0 ) {\n fprintf(stderr,\"fox: Could not create %s\\n\", filename);\n exit(0);\n }\n }\n \n#ifdef __SPIDER__\n *arraystatfp = (int *)malloc(n_array_in_sframe*sizeof(int));\n for (i_field = 0; i_field < n_array_in_sframe; i_field++) {\n sprintf(filename, \"%s/%s\", filedirname, GetArrayFieldName(i_field));\n if( ((*arraystatfp)[i_field] = open(filename, O_WRONLY | O_CREAT, 00644)) < 0 ) {\n fprintf(stderr,\"fox: Could not create %s\\n\", filename);\n exit(0);\n }\n }\n#endif\n}\n\n//*********************************************************\n// main\n//*********************************************************\nint main(int argc, char *argv[]) {\n int index = 0;\n int i_framefield;\n int i_streamfield;\n int i_arrayfield;\n char filedirname[1024];\n int fieldsize = 0;\n int *fieldfp;\n int *streamfp;\n int *arraystatfp;\n char fielddata[2000][8];\n int n_wrote;\n int i_samp;\n int i_frame;\n \n int i_array, j_array;\n \n \n unsigned short us_in;\n short s_in;\n unsigned char uc_in;\n signed char c_in;\n int i_in;\n unsigned u_in;\n long long ll_in[MAX_STREAM_FIELDS][MAX_SAMPLES_PER_FRAME];\n int first_time = 1;\n char name[128];\n\n int len;\n int i0;\n \n struct fifoStruct fs;\n\n /* find if we are fox, rush, or msnbc from the file name */\n /* first strip out the directory */\n len = strlen(argv[0]);\n for (i0=len-1; i0>0 && (argv[0][i0-1] != '/'); i0--);\n for (i_in = i0; i_in<len; i_in++) {\n name[i_in-i0] = argv[0][i_in];\n }\n name[i_in-i0] = '\\0';\n \n if (strncmp(name, \"fox\", 3)==0) {\n strcpy(LNKFILE, FOX_LNKFILE);\n PORT = RNC_PORT;\n EXT = FOX_EXT;\n } else if (strncmp(name, \"msn\", 3)==0) {\n strcpy(LNKFILE, MSNBC_LNKFILE);\n PORT = DNC_PORT;\n EXT = MSNBC_EXT;\n } else if (strncmp(name, \"rus\", 3)==0) {\n strcpy(LNKFILE, RUSH_LNKFILE);\n PORT = TEA_PORT;\n EXT = RUSH_EXT;\n } else {\n fprintf(stderr, \"unknown program: %s\\n\", name);\n exit(0);\n }\n\n fs.i_in = fs.i_out = 0;\n \n if (argc!=2) Usage(name);\n if (argv[1][0]=='-') Usage(name);\n\n sprintf(filedirname, \"%s/%lu.%c\", RAWDIR, time(NULL),EXT);\n if (mkdir(filedirname, 0777)<0) {\n fprintf(stderr, \"could not create dirfile %s\\n\", filedirname);\n exit(0);\n }\n\n unlink(LNKFILE);\n if (symlink(filedirname, LNKFILE)<0) {\n fprintf(stderr, \"could not create link from `%s' to `%s'\",\n filedirname, LNKFILE);\n exit(0);\n }\n\n strncpy(hostname, argv[1], 250);\n \n tty_fd = party_connect(hostname, PORT);\n\n MakeFrameList();\n \n //** read and parse the data */\n while (1) { // for each superframe\n index = 0; // start of superframe\n\n // Look for sync word\n while (index == 0) {\n n_bytemon+=BlockingRead(sizeof(unsigned), &fs, tty_fd, hostname, PORT);\n\n peek(&fs, (char *)&u_in, sizeof(unsigned));\n if (u_in==SYNCWORD) {\n printf(\"\\rRead %d bytes for frame %d \", n_bytemon, n_sync);\n advance(&fs, sizeof(unsigned));\n index = 1;\n is_lost = 0;\n n_bytemon = 0;\n n_sync++;\n fflush(stdout);\n } else {\n is_lost = 1;\n advance(&fs, 1);\n printf(\"\\rlost for %3d bytes (frame %d) \", n_bytemon, n_sync);\n fflush(stdout);\n }\n }\n \n // read frameset char\n n_bytemon+=BlockingRead(sizeof(char), &fs, tty_fd, hostname, PORT);\n pop(&fs, &channelset_oth, 1);\n printf(\"channelset %d \\n\", (int)channelset_oth);\n // Read once per frame fields\n for (i_framefield = 0; i_framefield < n_framefields; i_framefield++) {\n switch (framefields[i_framefield]->type) {\n case 'u':\n case 's':\n fieldsize = 2;\n break;\n case 'U':\n case 'S':\n fieldsize = 4;\n break;\n default:\n break;\n }\n n_bytemon+=BlockingRead(fieldsize, &fs, tty_fd, hostname, PORT);\n\n pop(&fs, fielddata[i_framefield], fieldsize);\n index++;\n }\n#ifdef __SPIDER__\n // Read Array Statistics\n // Array Stats per Superframe\n n_bytemon+=BlockingRead(2, &fs, tty_fd, hostname, PORT);\n pop(&fs, (char *)(&us_in), 2);\n n_array_in_sframe = us_in;\n if (n_array_in_sframe > NUM_ARRAY_STAT) {\n fprintf(stderr, \"error: Unreasonably large number of array stats (%d). Something is wrong.\\n\", \n n_array_in_sframe);\n continue;\n }\n \n // starting index\n n_bytemon+=BlockingRead(2, &fs, tty_fd, hostname, PORT);\n pop(&fs, (char *)(&us_in), 2);\n i_array = us_in;\n if (i_array > NUM_ARRAY_STAT) {\n fprintf(stderr, \"error: invalid array stats index. Something is wrong.\\n\");\n continue;\n }\n // read them...\n for (j_array = 0; j_array<n_array_in_sframe; j_array++) {\n pop(&fs, (char *)(&uc_in), 1);\n array_statistics[i_array] = uc_in;\n i_array++;\n if (i_array>= NUM_ARRAY_STAT) i_array=0;\n }\n \n#endif\n \n n_bytemon+=BlockingRead(2, &fs, tty_fd, hostname, PORT);\n pop(&fs, (char *)(&us_in), 2);\n\n \n if (first_time) {\n MakeStreamList();\n // reset first_time later\n }\n\n if (n_streamfields == 0) {\n n_streamfields = us_in;\n if (n_streamfields>n_streamfieldlist) {\n fprintf(stderr, \"error file asks for more streamfields than are listed (%u > %u)\\n\", n_streamfields, n_streamfieldlist); \n n_streamfields = 0;\n } else {\n printf(\"\\nstream contains %u out of %u stream fields\\n\", n_streamfields, n_streamfieldlist);\n }\n }\n // check for bad n_streamfields \n if ((n_streamfields != us_in) || (n_streamfields==0)) {\n printf(\"\\nChange in number of stream fields (%d vs %u), or bad data...\\n\"\n \"\\nIf this persists, you might want to restart\\n\", n_streamfields, us_in);\n continue;\n }\n \n if (first_time) {\n MakeStreamList();\n MakeFormatFile(filedirname);\n OpenDirfilePointers(&fieldfp, &streamfp, &arraystatfp, filedirname);\n first_time = 0;\n }\n \n // Read stream gains and offsets\n for (i_streamfield = 0; i_streamfield < n_streamfields; i_streamfield++) {\n n_bytemon+=BlockingRead(sizeof(unsigned short), &fs, tty_fd, hostname, PORT);\n pop(&fs, (char *)&us_in, sizeof(unsigned short));\n stream_gains[i_streamfield] = us_in;\n if (stream_gains[i_streamfield] == 0) {\n printf(\"\\nzero gain for field %s. Setting to 1\\n\", streamfields[i_streamfield]->field);\n stream_gains[i_streamfield]=1;\n }\n switch (streamfields[i_streamfield]->type) {\n case 'u':\n n_bytemon+=BlockingRead(sizeof(short), &fs, tty_fd, hostname, PORT);\n pop(&fs, (char *)&us_in, sizeof(short));\n stream_offsets[i_streamfield] = us_in;\n break;\n case 's': // 16 bit offsets\n n_bytemon+=BlockingRead(sizeof(short), &fs, tty_fd, hostname, PORT);\n pop(&fs, (char *)&s_in, sizeof(short));\n stream_offsets[i_streamfield] = s_in;\n break;\n case 'U':\n n_bytemon+=BlockingRead(sizeof(int), &fs, tty_fd, hostname, PORT);\n pop(&fs, (char *)&u_in, sizeof(int));\n stream_offsets[i_streamfield] = u_in;\n break;\n case 'S': // 32 bit offsets\n n_bytemon+=BlockingRead(sizeof(int), &fs, tty_fd, hostname, PORT);\n pop(&fs, (char *)&i_in, sizeof(int));\n stream_offsets[i_streamfield] = i_in;\n break;\n }\n }\n\n // Handle the 1 Hz frame stuff.\n for (i_frame = 0; i_frame < STREAMFRAME_PER_SUPERFRAME; i_frame++) {\n // Read the >= 1 Hz streamed data.\n for (i_streamfield = 0; i_streamfield < n_streamfields; i_streamfield++) {\n n_bytemon+=BlockingRead(streamList[channelset_oth][i_streamfield].samples_per_frame*streamList[channelset_oth][i_streamfield].bits/8, &fs, tty_fd, hostname, PORT);\n for (i_samp = 0; i_samp<streamList[channelset_oth][i_streamfield].samples_per_frame; i_samp++) {\n // read streamfield;\n if (streamList[channelset_oth][i_streamfield].bits == 4) {\n // FIXME: deal with 4 bit fields. There should always be a pair of them\n } else if (streamList[channelset_oth][i_streamfield].bits == 8) {\n pop(&fs, (char *)&c_in, 1);\n ll_in[i_streamfield][i_samp] = (int)c_in * stream_gains[i_streamfield]+stream_offsets[i_streamfield];\n if (streamList[channelset_oth][i_streamfield].doDifferentiate) { // undiferentiate...\n ll_in[i_streamfield][i_samp] = stream_offsets[i_streamfield];\n stream_offsets[i_streamfield]+=(int)c_in * stream_gains[i_streamfield];\n }\n } else if (streamList[channelset_oth][i_streamfield].bits == 16) {\n pop(&fs, (char *)&s_in, 2);\n ll_in[i_streamfield][i_samp] = (int)s_in * stream_gains[i_streamfield]+stream_offsets[i_streamfield];\n if (streamList[channelset_oth][i_streamfield].doDifferentiate) { // undiferentiate...\n ll_in[i_streamfield][i_samp] = stream_offsets[i_streamfield];\n stream_offsets[i_streamfield]+=(int)s_in * stream_gains[i_streamfield];\n }\n } else {\n fprintf(stderr,\"Unsupported stream resolution... (a definite bug!)\\n\");\n }\n }\n }\n // read frame sync byte\n n_bytemon+=BlockingRead(sizeof(char), &fs, tty_fd, hostname, PORT);\n pop(&fs, (char *)(&uc_in), sizeof(char));\n if (uc_in != 0xa5) {\n printf(\"bad sync byte: must be lost %x\\n\", (int)uc_in);\n i_frame = STREAMFRAME_PER_SUPERFRAME;\n break;\n } else {\n // write the slow data at 1 hz, even though it is only updated slower than that\n // this is so we can get near-realtime updated data.\n for (i_framefield=0; i_framefield<n_framefields; i_framefield++) {\n switch (framefields[i_framefield]->type) {\n case 'u':\n case 's':\n fieldsize = 2;\n break;\n case 'U':\n case 'S':\n fieldsize = 4;\n break;\n default:\n break;\n }\n \n n_wrote = write(fieldfp[i_framefield], fielddata[i_framefield], fieldsize);\n if (n_wrote != fieldsize) {\n fprintf(stderr, \"\\nWriting field data unsuccesful. Out of disk space?\\n\");\n }\n }\n#ifdef __SPIDER__\n for (i_arrayfield = 0; i_arrayfield < n_array_in_sframe; i_arrayfield++) {\n n_wrote = write(arraystatfp[i_arrayfield], array_statistics+i_arrayfield, 1);\n if (n_wrote != 1) {\n fprintf(stderr, \"\\nWriting field data unsuccesful. %s %d %d\\n\", strerror(errno), arraystatfp[i_arrayfield],\n i_arrayfield);\n }\n }\n\n#endif\n for (i_streamfield = 0; i_streamfield < n_streamfields; i_streamfield++) {\n for (i_samp = 0; i_samp<streamList[channelset_oth][i_streamfield].samples_per_frame; i_samp++) {\n switch (streamfields[i_streamfield]->type) {\n case 'u':\n us_in = ll_in[i_streamfield][i_samp];\n n_wrote = write(streamfp[i_streamfield], (char *)(&us_in), 2);\n if (n_wrote != 2) {\n fprintf(stderr, \"Writing field data unsuccesful. Out of disk space?\\n\");\n }\n break;\n case 's': \n s_in = ll_in[i_streamfield][i_samp];\n n_wrote = write(streamfp[i_streamfield], (char *)(&s_in), 2);\n if (n_wrote != 2) {\n fprintf(stderr, \"Writing field data unsuccesful. Out of disk space?\\n\");\n }\n break;\n case 'U':\n u_in = ll_in[i_streamfield][i_samp];\n n_wrote = write(streamfp[i_streamfield], (char *)(&u_in), 4);\n if (n_wrote != 4) {\n fprintf(stderr, \"Writing field data unsuccesful. Out of disk space?\\n\");\n }\n break;\n case 'S':\n i_in = ll_in[i_streamfield][i_samp];\n n_wrote = write(streamfp[i_streamfield], (char *)(&i_in), 4);\n if (n_wrote != 4) {\n fprintf(stderr, \"Writing field data unsuccesful. Out of disk space?\\n\");\n }\n break;\n }\n } // next samp\n } // next streamfield\n } // endif\n } // next frame\n } // end while 1\n\n return (0); // can't ever get here\n}\n" }, { "alpha_fraction": 0.5328947305679321, "alphanum_fraction": 0.5427631735801697, "avg_line_length": 18.580644607543945, "blob_id": "ba5d0c32c19ea29ab869dfd5b1c950a268aed3ce", "content_id": "174e394e0949c8aa5492b894870682c898f5bb96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 609, "license_type": "no_license", "max_line_length": 73, "num_lines": 31, "path": "/stars/code/shared/thread_names.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__THREAD_NAMES_H\n#define SHARED__THREAD_NAMES_H\n\nnamespace Shared\n{\n namespace ThreadNames\n {\n enum Name\n {\n nobody,\n main,\n solver,\n camera,\n lens,\n net_server,\n net_client,\n net_reset,\n net_image_client1,\n net_image_client2\n };\n }\n}\n\n#endif\n\n" }, { "alpha_fraction": 0.6062964797019958, "alphanum_fraction": 0.616195023059845, "avg_line_length": 32.674964904785156, "blob_id": "5ca2ddf73b4d5630b66cc1b197cf5a4ca9e3c7a6", "content_id": "a47d33189a6a1f264989d4ba550600c563e7e599", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 48694, "license_type": "no_license", "max_line_length": 174, "num_lines": 1446, "path": "/owl/PMainWindow.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include <stdlib.h>\n#include \"PMainWindow.h\"\n#include \"PMdiArea.h\"\n#include \"PTimeDataItem.h\"\n#include \"PDirfileDataItem.h\"\n#include \"PStyle.h\"\n#include \"POwlAnimation.h\"\n\n#include \"ui_PMainWindow.h\"\n\n#include <QTextEdit>\n#include <QColorDialog>\n#include <QTextStream>\n#include <QTimer>\n#include <QCompleter>\n#include <QFile>\n#include <QInputDialog>\n#include <QMessageBox>\n#include <QColorDialog>\n#include <QFileDialog>\n#include <QDebug>\n#include <QDialogButtonBox>\n#include <QFileSystemModel>\n#include <QDateTime>\n#include <QMenu>\n#include <QWidgetAction>\n\n#ifdef __APPLE__\n#include <python2.6/Python.h>\n#else\n#include <python2.7/Python.h> //you may need to change this\n#endif\n\n\n#if QT_VERSION >= 0x050000\n#include <QJsonDocument>\n#include <QJsonObject>\n#else\n#include <qjson/parser.h>\n#include <qjson/serializer.h>\n#endif\n\nPMainWindow* PMainWindow::me=0;\n\nstatic QString _filename;\n\nPMainWindow::PMainWindow(int font_size, QString file, QWidget *parent) :\n QMainWindow(parent),\n PObject(0),\n _currentObject(0),\n _dirfile(0),\n _scrollArea(new QScrollArea()),\n styleVersion(0),\n layoutVersion(0),\n#if QT_VERSION >= 0x050300\n _server(0),\n#endif\n _deleteScheduled(0),\n _lastNFrames(-1),\n ui(new Ui::PMainWindow)\n{\n _link = 0; /* LOS */\n _settings = new QSettings(\"UToronto\", \"owl\");\n setWindowIcon(QIcon(\":icons/Owl0.png\"));\n\n PStyle::noStyle = PStyle::noStyle?PStyle::noStyle:new PStyle(\"No style\");\n me=this;\n\n QFont my_font = font();\n my_font.setPointSize(font_size);\n setFont(my_font);\n\n ui->setupUi(this);\n\n int listHeight = ui->listWidgetInsertReal->fontMetrics().height() *\n ui->listWidgetInsertReal->count() * 1.05 + 2*ui->listWidgetInsertReal->frameWidth();\n\n ui->listWidgetInsertReal->setMaximumHeight(listHeight);\n ui->comboBox->addItem(\"Owl \"+idText());\n _mdiArea=new PMdiArea;\n _scrollArea->setParent(centralWidget());\n _scrollArea->setAutoFillBackground(1);\n QPalette p=_scrollArea->palette();\n p.setColor(_scrollArea->backgroundRole(),\"white\");\n _scrollArea->setPalette(p);\n _scrollArea->setWidget(_mdiArea);\n _mdiArea->adjustSize();\n centralWidget()->layout()->addWidget(_scrollArea);\n connect(_mdiArea,SIGNAL(newBox(PBox*)),this,SLOT(uiLogic()));\n connect(ui->comboBox,SIGNAL(activated(int)),this,SLOT(uiLogic()));\n connect(ui->actionSave,SIGNAL(triggered()),this,SLOT(owlSave()));\n connect(ui->actionSaveAs,SIGNAL(triggered()),this,SLOT(owlSaveAs()));\n connect(ui->actionLoad,SIGNAL(triggered()),this,SLOT(owlLoad()));\n connect(ui->actionReset, SIGNAL(triggered()), this, SLOT(resetLink()));\n connect(PStyleNotifier::me,SIGNAL(change()),this,SLOT(currowLogic()));\n connect(ui->actionHelp,SIGNAL(triggered()),this,SLOT(readmeHelp()));\n connect(_mdiArea,SIGNAL(newOwl(POwlAnimation*)),this,SLOT(addOwl()));\n#if QT_VERSION >= 0x050300\n connect(ui->checkBoxServer, SIGNAL(toggled(bool)), this, SLOT(setWebEnabled(bool)));\n connect(ui->spinBoxServerPort, SIGNAL(valueChanged(int)), this, SLOT(setWebPort(int)));\n#else\n ui->actionServer_Options->setVisible(false);\n#endif\n QFileSystemModel* fsm=new QFileSystemModel();\n fsm->setRootPath(QDir::currentPath());\n ui->lineEditHighGain->setCompleter(new QCompleter(fsm));\n ui->lineEditTDRSSOmni->setCompleter(new QCompleter(fsm));\n ui->lineEditLOS->setCompleter(new QCompleter(fsm));\n ui->lineEditIridium->setCompleter(new QCompleter(fsm));\n ui->lineEditLoRate->setCompleter(new QCompleter(fsm));\n\n curfileLogic();\n\n _currowStyle=PStyle::noStyle;\n\n uiLogic();\n\n _ut=new QTimer(this);\n _ut->setInterval(500);\n connect(_ut,SIGNAL(timeout()),this,SLOT(gdUpdate()));\n _ut->start();\n\n _reset_timer=new QTimer(this);\n _reset_timer->setInterval(30000); /* twice a minute is good...? */\n connect(_reset_timer,SIGNAL(timeout()),this,SLOT(resetLink()));\n _reset_timer->start();\n\n activate();\n\n //_mdiArea->setMinimumSize(1000,900);\n setMinimumSize(1,1);\n\n //setWindowTitle(_WINDOW_TITLE_);\n\n if (file == \"__lastfile\") {\n file = _settings->value(\"filename\").toString();\n }\n\n restoreState(_settings->value(\"windowState\").toByteArray());\n\n //if (_settings->value(\"hideWeb\", false).toBool()) {\n ui->actionServer_Options->setChecked(false);\n ui->dockWebServer->hide();\n //}\n //if (_settings->value(\"hideConfig\", false).toBool()) {\n ui->actionConfigure->setChecked(false);\n ui->dockConfigure->hide();\n //}\n //if (_settings->value(\"hideLink\", false).toBool()) {\n ui->actionLink->setChecked(false);\n ui->dockLink->hide();\n //}\n if(file.size()) {\n owlLoad(file);\n _filename = file;\n }\n\n setStatusBar(0);\n\n if(!_deleteScheduled&&!PObject::isLoading) show();\n}\n\n#define reconnect(a,b,c,d) \\\n disconnect(a,b,c,d); \\\n connect(a,b,c,d)\n\nPMainWindow::~PMainWindow()\n{\n while(_pboxList.size()) {\n delete _pboxList.takeFirst();\n }\n while(_owlList.size()) {\n delete _owlList.takeFirst();\n }\n}\n\nvoid PMainWindow::keyPressEvent ( QKeyEvent * e ) {\n if (e->key()== Qt::Key_T) {\n ui->toolBar->setVisible(!ui->toolBar->isVisible());\n }\n QMainWindow::keyPressEvent(e);\n}\n\nvoid PMainWindow::contextMenuEvent(QContextMenuEvent *event) {\n\n QMenu menu;\n\n#if 0\n QWidgetAction *title = new QWidgetAction(&menu);\n title->setEnabled(false);\n\n QLabel *label = new QLabel(\"Test Title\");\n label->setAlignment(Qt::AlignCenter);\n label->setStyleSheet(\"QLabel {\"\n \"border-bottom: 2px solid lightGray;\"\n \"font: bold large;\"\n \"padding: 3px;\"\n \"margin: 1px;\"\n \"}\");\n title->setDefaultWidget(label);\n menu.addAction(title);\n#endif\n\n QAction *show_toolbar_action = new QAction(tr(\"Show Toolbar (T)\"),this);\n show_toolbar_action->setCheckable(true);\n show_toolbar_action->setChecked(!ui->toolBar->isHidden());\n connect(show_toolbar_action, SIGNAL(toggled(bool)), this, SLOT(showToolbar(bool)));\n\n menu.addAction(show_toolbar_action);\n\n menu.exec(event->globalPos());\n //QMainWindow::contextMenuEvent(event);\n}\n\nvoid PMainWindow::showToolbar(bool show) {\n if (show) {\n ui->toolBar->show();\n } else {\n ui->toolBar->hide();\n }\n}\n\nvoid PMainWindow::closeEvent(QCloseEvent* e)\n{\n Q_UNUSED(e);\n\n/*\n _settings->setValue(\"hideWeb\",!ui->dockWebServer->isVisible());\n _settings->setValue(\"hideConfig\",!ui->dockConfigure->isVisible());\n _settings->setValue(\"hideLink\",!ui->dockLink->isVisible());\n*/\n _settings->setValue(\"windowState\", saveState());\n //e->setAccepted(QMessageBox::question(this,\"Really Quit?\",\"If you quit, you will lose all unsaved data. Quit anyway?\",QMessageBox::Yes,QMessageBox::No)==QMessageBox::Yes);\n}\n\nvoid PMainWindow::readmeHelp()\n{\n QFile readme(\":/client/README.txt\");\n readme.open(QFile::ReadOnly);\n\n QDialog x;\n QTextEdit te(&x);\n te.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);\n te.setWordWrapMode(QTextOption::NoWrap);\n te.setFontFamily(\"monospace\");\n te.setText(readme.readAll());\n te.setReadOnly(1);\n QVBoxLayout hb(&x);\n hb.addWidget(&te);\n QDialogButtonBox bb(QDialogButtonBox::Close);\n connect(&bb,SIGNAL(accepted()),&x,SLOT(close()));\n connect(&bb,SIGNAL(rejected()),&x,SLOT(close()));\n hb.addWidget(&bb);\n x.setWindowTitle(\"README\");\n x.show();\n x.adjustSize();\n x.setGeometry(x.x(),x.y(),680,480);\n\n x.exec();\n}\n\nvoid PMainWindow::hideEverything()\n{\n setUpdatesEnabled(0);\n ui->pstyleCaption->hide();\n disconnect(ui->pstyleCaption,0,0,0);\n ui->pstyleData->hide();\n disconnect(ui->pstyleData,0,0,0);\n ui->labelCaption->hide();\n ui->lineEditCaption->hide();\n disconnect(ui->lineEditCaption,0,0,0);\n //ui->labelColour->hide();\n ui->labelSource->hide();\n ui->lineEditSource->hide();\n disconnect(ui->lineEditSource,0,0,0);\n ui->labelType->hide();\n ui->comboBoxType->hide();\n disconnect(ui->comboBoxType,0,0,0);\n ui->labelFormat_multi->hide();\n ui->tableWidgetFormat->hide();\n disconnect(ui->tableWidgetFormat,0,0,0);\n //ui->label_colour2->hide();\n ui->pushButtonAddFormat->hide();\n disconnect(ui->pushButtonAddFormat,0,0,0);\n ui->pushButtonDelFormat->hide();\n disconnect(ui->pushButtonDelFormat,0,0,0);\n ui->labelFormat_num->hide();\n ui->lineEditFormat->hide();\n disconnect(ui->lineEditFormat,0,0,0);\n ui->labelNBits->hide();\n ui->spinBoxNBits->hide();\n disconnect(ui->spinBoxNBits,0,0,0);\n ui->labelHighWord->hide();\n ui->lineEditHighWord->hide();\n disconnect(ui->lineEditHighWord,0,0,0);\n ui->labelLowWord->hide();\n ui->lineEditLowWord->hide();\n disconnect(ui->lineEditLowWord,0,0,0);\n ui->labelExtrema->hide();\n ui->comboBoxExtrema->hide();\n disconnect(ui->comboBoxExtrema,0,0,0);\n ui->labelName->hide();\n ui->lineEditExtremaName->hide();\n disconnect(ui->lineEditExtremaName,0,0,0);\n ui->labelXHigh->hide();\n ui->doubleSpinBoxXHigh->hide();\n disconnect(ui->doubleSpinBoxXHigh,0,0,0);\n ui->labelHigh->hide();\n ui->doubleSpinBoxHigh->hide();\n disconnect(ui->doubleSpinBoxHigh,0,0,0);\n ui->labelLow->hide();\n ui->doubleSpinBoxLow->hide();\n disconnect(ui->doubleSpinBoxLow,0,0,0);\n ui->labelXLow->hide();\n ui->doubleSpinBoxXLow->hide();\n disconnect(ui->doubleSpinBoxXLow,0,0,0);\n\n ui->labelCurRow->hide();\n disconnect(ui->labelCurRow,0,0,0);\n ui->pushButtonRemove->hide();\n disconnect(ui->pushButtonRemove,0,0,0);\n\n ui->pstyleXHigh->hide();\n disconnect(ui->pstyleXHigh,0,0,0);\n ui->pstyleHigh->hide();\n disconnect(ui->pstyleHigh,0,0,0);\n ui->pstyleLow->hide();\n disconnect(ui->pstyleLow,0,0,0);\n ui->pstyleXLow->hide();\n disconnect(ui->pstyleXLow,0,0,0);\n ui->pstyleSelected->hide();\n disconnect(ui->pstyleSelected,0,0,0);\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::addPBox()\n{\n setUpdatesEnabled(0);\n ui->comboBox->addItem(_pboxList.back()->boxTitle()+\" \"+_pboxList.back()->idText());\n connect(_pboxList.back(),SIGNAL(activated()),this,SLOT(uiLogic()));\n connect(_pboxList.back(),SIGNAL(newChild(PAbstractDataItem*)),\n this,SLOT(newLabelLogic(PAbstractDataItem*)));\n _currentObject=_pboxList.back();\n ui->comboBox->setCurrentIndex(ui->comboBox->count()-1);\n\n ui->pstyleCaption->setWidgetStyleRef(_pboxList.back()->_pstyle);\n ui->pushButtonRemove->show();\n connect(ui->pushButtonRemove,SIGNAL(clicked()),_pboxList.back(),SLOT(deleteLater()));\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::setCurrentObject(POwlAnimation*obj)\n{\n ui->pushButtonRemove->show();\n reconnect(ui->pushButtonRemove,SIGNAL(clicked()),this,SLOT(removeCurrentDataItem()));\n for(int i=0;i<ui->comboBox->count();i++) {\n if(ui->comboBox->itemText(i).contains(obj->idText())) {\n ui->comboBox->setCurrentIndex(i);\n break;\n }\n }\n _currentObject=obj;\n}\n\nvoid PMainWindow::setCurrentObject(PBox*obj)\n{\n setUpdatesEnabled(0);\n QString x=obj->idText();\n _currentObject=obj;\n bool ok=0;\n for(int i=0;i<ui->comboBox->count();i++) {\n if(ui->comboBox->itemText(i).contains(x)) {\n ok=1;\n ui->comboBox->setCurrentIndex(i);\n }\n }\n Q_ASSERT(ok);\n ui->pstyleCaption->setWidgetStyleRef(obj->_pstyle);\n ui->pushButtonRemove->show();\n connect(ui->pushButtonRemove,SIGNAL(clicked()),obj,SLOT(deleteLater()));\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::setCurrentObject(PAbstractDataItem*obj)\n{\n setUpdatesEnabled(0);\n QString x=obj->idText();\n _currentObject=obj;\n for(int i=0;i<ui->comboBox->count();i++) {\n if(ui->comboBox->itemText(i).contains(x)) {\n ui->comboBox->setCurrentIndex(i);\n }\n }\n\n ui->labelCaption->show();\n ui->lineEditCaption->show();\n reconnect(ui->lineEditCaption,SIGNAL(textChanged(QString)),obj,SLOT(setCaption(QString)));\n reconnect(obj,SIGNAL(textChanged(QString)),this,SLOT(uiLogic()));\n\n //ui->labelColour->show();\n\n ui->labelSource->show();\n ui->lineEditSource->show();\n reconnect(ui->lineEditSource,SIGNAL(textChanged(QString)),obj,SLOT(setSource(QString)));\n reconnect(obj,SIGNAL(sourceChanged(QString)),this,SLOT(uiLogic()));\n\n //ui->label_colour2->show();\n ui->pstyleCaption->show();\n ui->pstyleCaption->setWidgetStyleRef(obj->_captionStyle);\n\n ui->pushButtonRemove->show();\n reconnect(ui->pushButtonRemove,SIGNAL(clicked()),this,SLOT(removeCurrentDataItem()));\n\n ui->pstyleData->show();\n ui->pstyleData->setWidgetStyleRef(obj->_defaultDataStyle);\n\n if(dynamic_cast<PExtremaDataItem*>(obj))\n setCurrentObject(dynamic_cast<PExtremaDataItem*>(obj));\n\n if(dynamic_cast<PNumberDataItem*>(obj)) setCurrentObject(dynamic_cast<PNumberDataItem*>(obj));\n else if(dynamic_cast<PMultiDataItem*>(obj)) setCurrentObject(dynamic_cast<PMultiDataItem*>(obj));\n else if(dynamic_cast<PBitMultiDataItem*>(obj)) setCurrentObject(dynamic_cast<PBitMultiDataItem*>(obj));\n else if(dynamic_cast<PTimeDataItem*>(obj)) setCurrentObject(dynamic_cast<PTimeDataItem*>(obj));\n else if(dynamic_cast<PDirfileDataItem*>(obj)) {\n ui->labelSource->hide();\n ui->lineEditSource->hide();\n }\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::setCurrentObject(PNumberDataItem*obj)\n{\n setUpdatesEnabled(0);\n ui->labelFormat_num->show();\n ui->lineEditFormat->show();\n ui->lineEditFormat->setText(obj->format());\n ui->lineEditFormat->setPlaceholderText(\"printf format str (\\\"man printf\\\")\");\n reconnect(ui->lineEditFormat,SIGNAL(textChanged(QString)),obj,SLOT(setFormat(QString)));\n reconnect(obj,SIGNAL(formatChanged(QString)),this,SLOT(uiLogic()));\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::setCurrentObject(PExtremaDataItem *obj)\n{\n setUpdatesEnabled(0);\n ui->labelExtrema->show();\n ui->comboBoxExtrema->show();\n reconnect(ui->comboBoxExtrema,SIGNAL(currentIndexChanged(QString)),this,SLOT(extremaLogic(QString)));\n\n ui->labelName->show();\n ui->lineEditExtremaName->show();\n reconnect(ui->lineEditExtremaName,SIGNAL(textChanged(QString)),this,SLOT(extremaLogic(QString)));\n ui->lineEditExtremaName->setEnabled(obj->_extrema);\n if(obj->_extrema) {\n reconnect(obj->_extrema,SIGNAL(nameChanged(QString)), this,SLOT(extremaLogic(QString)));\n }\n\n if(obj->_extrema) {\n PExtrema* extrema=obj->_extrema;\n ui->comboBoxExtrema->setCurrentIndex(0);\n for(int i=0;i<ui->comboBoxExtrema->count();i++) {\n if(ui->comboBoxExtrema->itemText(i).contains(extrema->idText())) {\n ui->comboBoxExtrema->setCurrentIndex(i);\n break;\n }\n }\n } else {\n ui->comboBoxExtrema->setCurrentIndex(0);\n }\n\n ui->labelXHigh->show();\n ui->doubleSpinBoxXHigh->show();\n ui->doubleSpinBoxXHigh->setEnabled(obj->_extrema);\n ui->doubleSpinBoxXHigh->setValue(obj->_extrema?obj->_extrema->_xhigh:0.0f);\n reconnect(ui->doubleSpinBoxXHigh,SIGNAL(valueChanged(double)),this,SLOT(extremaXHighLogic(double)));\n\n ui->labelHigh->show();\n ui->doubleSpinBoxHigh->show();\n ui->doubleSpinBoxHigh->setEnabled(obj->_extrema);\n ui->doubleSpinBoxHigh->setValue(obj->_extrema?obj->_extrema->_high:0.0f);\n reconnect(ui->doubleSpinBoxHigh,SIGNAL(valueChanged(double)),this,SLOT(extremaHighLogic(double)));\n\n ui->labelLow->show();\n ui->doubleSpinBoxLow->show();\n ui->doubleSpinBoxLow->setEnabled(obj->_extrema);\n ui->doubleSpinBoxLow->setValue(obj->_extrema?obj->_extrema->_low:0.0f);\n reconnect(ui->doubleSpinBoxLow,SIGNAL(valueChanged(double)),this,SLOT(extremaLowLogic(double)));\n\n ui->labelXLow->show();\n ui->doubleSpinBoxXLow->show();\n ui->doubleSpinBoxXLow->setEnabled(obj->_extrema);\n ui->doubleSpinBoxXLow->setValue(obj->_extrema?obj->_extrema->_xlow:0.0f);\n reconnect(ui->doubleSpinBoxXLow,SIGNAL(valueChanged(double)),this,SLOT(extremaXLowLogic(double)));\n\n ui->pstyleXHigh->show();\n ui->pstyleXHigh->setEnabled(obj->_extrema);\n ui->pstyleHigh->show();\n ui->pstyleHigh->setEnabled(obj->_extrema);\n ui->pstyleLow->show();\n ui->pstyleLow->setEnabled(obj->_extrema);\n ui->pstyleXLow->show();\n ui->pstyleXLow->setEnabled(obj->_extrema);\n if(obj->_extrema) {\n ui->pstyleXHigh->setWidgetStyleRef(obj->_extrema->_sxhigh);\n ui->pstyleHigh->setWidgetStyleRef(obj->_extrema->_shigh);\n ui->pstyleLow->setWidgetStyleRef(obj->_extrema->_slow);\n ui->pstyleXLow->setWidgetStyleRef(obj->_extrema->_sxlow);\n }\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::setCurrentObject(PMultiDataItem*obj)\n{\n setUpdatesEnabled(0);\n disconnect(ui->tableWidgetFormat,0,0,0);\n\n ui->tableWidgetFormat->clear();\n while(ui->tableWidgetFormat->rowCount()) {\n ui->tableWidgetFormat->removeRow(0);\n }\n for(int i=0;i<obj->_map->_map.size();i++) {\n ui->tableWidgetFormat->insertRow(0);\n }\n QStringList a,b;\n for(int i=0;i<obj->_map->_map.size();i++) {\n a.push_back(QString::number(obj->_map->_map.keys()[i]));\n b.push_back(obj->_map->_map.values()[i]);\n }\n\n for(int i=0;i<a.size();i++) {\n QTableWidgetItem* twi=new QTableWidgetItem(a[i]);\n ui->tableWidgetFormat->setItem(i,0,twi);\n QTableWidgetItem* twii=new QTableWidgetItem(b[i]);\n ui->tableWidgetFormat->setItem(i,1,twii);\n }\n\n ui->pstyleSelected->show();\n ui->pstyleSelected->setDisabled(1);\n\n ui->labelCurRow->show();\n\n ui->labelFormat_multi->show();\n ui->tableWidgetFormat->show();\n reconnect(ui->tableWidgetFormat,SIGNAL(itemChanged(QTableWidgetItem*)),this,SLOT(multiLogic()));\n reconnect(ui->tableWidgetFormat,SIGNAL(currentCellChanged(int,int,int,int)),this,SLOT(multiLogic()));\n ui->pushButtonAddFormat->show();\n reconnect(ui->pushButtonAddFormat,SIGNAL(clicked()),this,SLOT(multiLogic()));\n ui->pushButtonDelFormat->show();\n reconnect(ui->pushButtonDelFormat,SIGNAL(clicked()),this,SLOT(multiLogic()));\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::setCurrentObject(PBitMultiDataItem*obj)\n{\n setUpdatesEnabled(0);\n ui->labelNBits->show();\n ui->spinBoxNBits->show();\n ui->spinBoxNBits->setValue(obj->nBits());\n reconnect(ui->spinBoxNBits,SIGNAL(valueChanged(int)),obj,SLOT(setNBits(int)));\n reconnect(obj,SIGNAL(nBitsChanged(int)),this,SLOT(uiLogic()));\n\n ui->labelHighWord->show();\n ui->lineEditHighWord->show();\n ui->lineEditHighWord->setText(obj->highWord());\n ui->lineEditHighWord->setPlaceholderText(\"11111111\");\n reconnect(ui->lineEditHighWord,SIGNAL(textChanged(QString)),obj,SLOT(setHighWord(QString)));\n reconnect(obj,SIGNAL(highWordChanged(QString)),this,SLOT(uiLogic()));\n\n ui->labelLowWord->show();\n ui->lineEditLowWord->show();\n ui->lineEditLowWord->setText(obj->lowWord());\n ui->lineEditLowWord->setPlaceholderText(\"00000000\");\n reconnect(ui->lineEditLowWord,SIGNAL(textChanged(QString)),obj,SLOT(setLowWord(QString)));\n reconnect(obj,SIGNAL(lowWordChanged(QString)),this,SLOT(uiLogic()));\n\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::setCurrentObject(PTimeDataItem*obj)\n{\n setUpdatesEnabled(0);\n ui->labelFormat_num->show();\n ui->lineEditFormat->show();\n ui->lineEditFormat->setText(obj->format());\n ui->lineEditFormat->setPlaceholderText(\"strftime str (\\\"man strftime\\\")\");\n reconnect(ui->lineEditFormat,SIGNAL(textChanged(QString)),obj,SLOT(setFormat(QString)));\n reconnect(obj,SIGNAL(formatChanged(QString)),this,SLOT(uiLogic()));\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::addOwl()\n{\n setUpdatesEnabled(0);\n ui->comboBox->addItem(\"Owl Animation \"+_owlList.back()->idText());\n connect(_owlList.back(),SIGNAL(activated()),this,SLOT(uiLogic()));\n _currentObject=_owlList.back();\n ui->comboBox->setCurrentIndex(ui->comboBox->count()-1);\n\n ui->pushButtonRemove->show();\n hideEverything();\n setCurrentObject(dynamic_cast<POwlAnimation*>(_owlList.back()));\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::uiLogic()\n{\n setUpdatesEnabled(0);\n bool newWidget=sender()!=_currentObject||!sender()||dynamic_cast<POwlAnimation*>(sender());\n\n if(newWidget) {\n hideEverything();\n\n if(sender()==_mdiArea) addPBox();\n else if(dynamic_cast<PBox*>(sender())) setCurrentObject(dynamic_cast<PBox*>(_currentObject=sender()));\n else if(dynamic_cast<PAbstractDataItem*>(sender())) setCurrentObject(dynamic_cast<PAbstractDataItem*>(_currentObject=sender()));\n else if(dynamic_cast<POwlAnimation*>(sender())) setCurrentObject(dynamic_cast<POwlAnimation*>(_currentObject=sender()));\n else if(sender()==ui->comboBox) {\n QString x=ui->comboBox->currentText();\n x.remove(0,x.indexOf('(')+2);\n x.remove(x.indexOf(')'),999999999);\n Q_ASSERT(PObject::_u[x.toInt()]);\n PObject::_u[x.toInt()]->activate(); // ==> uiLogic();\n setUpdatesEnabled(1);\n return;\n }\n }\n\n _dirty=1;\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::setFileLineEditValidity(QLineEdit* fle)\n{\n QPalette pal=fle->palette();\n pal.setColor(fle->foregroundRole(),QFile::exists(fle->text())?\"black\":\"red\");\n fle->setPalette(pal);\n}\n\n/* Set the current link based on an .owl file value */\nvoid PMainWindow::setLink(int link, QStringList linkNames)\n{\n /* LOS is the default link */\n if (link < 0 || link > 4)\n link = 0;\n\n if (linkNames.size()>4) {\n ui->lineEditLOS->setText(linkNames[0]);\n ui->lineEditIridium->setText(linkNames[1]);\n ui->lineEditTDRSSOmni->setText(linkNames[2]);\n ui->lineEditHighGain->setText(linkNames[3]);\n ui->lineEditLoRate->setText(linkNames[4]);\n }\n ui->radioButtonLoRate->setChecked(link == 4);\n ui->radioButtonHighGain->setChecked(link == 3);\n ui->radioButtonTDRSSOmni->setChecked(link == 2);\n ui->radioButtonIridium->setChecked(link == 1);\n ui->radioButtonLOS->setChecked(link == 0);\n\n /* do the link logic */\n curfileLogic(true);\n}\n\nvoid PMainWindow::curfileLogic(bool force)\n{\n setUpdatesEnabled(0);\n setFileLineEditValidity(ui->lineEditLoRate);\n setFileLineEditValidity(ui->lineEditHighGain);\n setFileLineEditValidity(ui->lineEditTDRSSOmni);\n setFileLineEditValidity(ui->lineEditIridium);\n setFileLineEditValidity(ui->lineEditLOS);\n QString filename;\n if (ui->radioButtonLoRate->isChecked()) {\n filename = ui->lineEditLoRate->text();\n _link = 4;\n } else if (ui->radioButtonHighGain->isChecked()) {\n filename = ui->lineEditHighGain->text();\n _link = 3;\n } else if (ui->radioButtonTDRSSOmni->isChecked()) {\n filename = ui->lineEditTDRSSOmni->text();\n _link = 2;\n } else if (ui->radioButtonIridium->isChecked()) {\n filename = ui->lineEditIridium->text();\n _link = 1;\n } else {\n filename = ui->lineEditLOS->text();\n _link = 0;\n }\n\n if(QFile::exists(filename) && ((filename != _dirfileFilename) || (force))) {\n delete _dirfile;\n _dirfileFilename=filename;\n _dirfile = new GetData::Dirfile(_dirfileFilename.toLatin1(), GD_RDONLY);\n\n int flc=_dirfile->NFields();\n const char** flv=_dirfile->FieldList();\n QStringList fields;\n for(int i=0;i<flc;i++) {\n fields<<flv[i];\n }\n delete ui->lineEditSource->completer();\n QCompleter* completer=new QCompleter(fields);\n completer->setCaseSensitivity(Qt::CaseInsensitive);\n ui->lineEditSource->setCompleter(completer);\n for(int i=0;i<_pboxList.size();i++) {\n for(int j=0;j<_pboxList[i]->_dataItems.size();j++) {\n _pboxList[i]->_dataItems[j]->resetSource();\n }\n }\n }\n setUpdatesEnabled(1);\n\n setWindowTitle(\"Owl - \" + filename);\n}\n\nbool PMainWindow::mouseInactive() {\n return !(ui->actionConfigure->isChecked());\n}\n\nQStringList PMainWindow::linkNames() {\n QStringList names;\n\n names.append(ui->lineEditLOS->text());\n names.append(ui->lineEditIridium->text());\n names.append(ui->lineEditTDRSSOmni->text());\n names.append(ui->lineEditHighGain->text());\n names.append(ui->lineEditLoRate->text());\n\n return names;\n}\n\nvoid PMainWindow::newLabelLogic(PAbstractDataItem *padi)\n{\n setUpdatesEnabled(0);\n ui->comboBox->addItem(padi->caption()+\" \"+padi->idText());\n connect(padi,SIGNAL(activated()),this,SLOT(uiLogic()));\n padi->mousePressEvent(0); //make it current\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::extremaLogic(QString)\n{\n PExtremaDataItem* pedi=dynamic_cast<PExtremaDataItem*>(_currentObject);\n if (!pedi)\n return;\n\n setUpdatesEnabled(0);\n QLineEdit* le=dynamic_cast<QLineEdit*>(sender());\n QComboBox* cb=dynamic_cast<QComboBox*>(sender());\n PExtrema* ex=dynamic_cast<PExtrema*>(sender());\n if (le && pedi->_extrema) { //change current extrema name\n Q_ASSERT(pedi->_extrema);\n pedi->_extrema->setName(le->text());\n } else if(cb) { //change current extrema\n if (pedi->_extrema) {\n disconnect(pedi->_extrema, SIGNAL(nameChanged(QString)), this,\n SLOT(extremaLogic(QString)));\n }\n PExtrema* extrema=0;\n for(int i=0;i<PExtrema::_u.count();i++) {\n if(cb->currentText().contains(PExtrema::_u[i]->idText())) {\n extrema=PExtrema::_u[i];\n }\n }\n\n ui->pstyleXHigh->setEnabled(extrema);\n ui->pstyleHigh->setEnabled(extrema);\n ui->pstyleLow->setEnabled(extrema);\n ui->pstyleXLow->setEnabled(extrema);\n\n if(extrema) {\n pedi->_extrema = extrema;\n ui->lineEditExtremaName->setText(extrema->name());\n ui->lineEditExtremaName->setEnabled(1);\n ui->doubleSpinBoxXHigh->setEnabled(1);\n ui->doubleSpinBoxXHigh->setValue(pedi->_extrema->_xhigh);\n ui->doubleSpinBoxHigh->setEnabled(1);\n ui->doubleSpinBoxHigh->setValue(pedi->_extrema->_high);\n ui->doubleSpinBoxLow->setEnabled(1);\n ui->doubleSpinBoxLow->setValue(pedi->_extrema->_low);\n ui->doubleSpinBoxXLow->setEnabled(1);\n ui->doubleSpinBoxXLow->setValue(pedi->_extrema->_xlow);\n disconnect(pedi->_extrema, SIGNAL(nameChanged(QString)), this,\n SLOT(extremaLogic(QString)));\n connect(pedi->_extrema, SIGNAL(nameChanged(QString)), this,\n SLOT(extremaLogic(QString)));\n\n ui->pstyleXHigh->setWidgetStyleRef(pedi->_extrema->_sxhigh);\n ui->pstyleHigh->setWidgetStyleRef(pedi->_extrema->_shigh);\n ui->pstyleLow->setWidgetStyleRef(pedi->_extrema->_slow);\n ui->pstyleXLow->setWidgetStyleRef(pedi->_extrema->_sxlow);\n\n } else if (!extrema) {\n if(cb->currentText()==tr(\"No Extrema\")) {\n pedi->_extrema = 0;\n ui->lineEditExtremaName->setText(\"\");\n ui->lineEditExtremaName->setDisabled(1);\n ui->doubleSpinBoxXHigh->setDisabled(1);\n ui->doubleSpinBoxHigh->setDisabled(1);\n ui->doubleSpinBoxLow->setDisabled(1);\n ui->doubleSpinBoxXLow->setDisabled(1);\n } else if(cb->currentText()==tr(\"New Extrema\")) {\n QString x;\n while(1) {\n bool ok;\n x=QInputDialog::getText(this,\"New Extrema\",\"Extrema name:\",QLineEdit::Normal,\"\",&ok);\n if(!ok) {\n setUpdatesEnabled(1);\n return;\n }\n if(!x.isEmpty()&&!x.contains(\"(\")&&!x.contains(\")\")) break;\n QMessageBox::information(this,\"Bad name\",\"Your extrema is poorly named. Try again.\");\n }\n PExtrema* ext=new PExtrema;\n ext->setName(x);\n ui->comboBoxExtrema->addItem(x+\" \"+ext->idText());\n ui->comboBoxExtrema->setCurrentIndex(ui->comboBoxExtrema->count()-1);\n repaint();\n } else {\n qDebug()<<\"Warning: unknown extrema:\"<<cb->currentText();\n }\n }\n } else if(ex) { //change current extrema name\n ui->lineEditExtremaName->setText(ex->name());\n ui->comboBoxExtrema->setItemText(ui->comboBoxExtrema->currentIndex(),ex->name()+\" \"+ex->idText());\n }\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::extremaXHighLogic(double x)\n{\n PExtremaDataItem* pedi=dynamic_cast<PExtremaDataItem*>(_currentObject);\n Q_ASSERT(pedi && pedi->_extrema);\n pedi->_extrema->_xhigh=x;\n}\n\nvoid PMainWindow::extremaHighLogic(double x)\n{\n PExtremaDataItem* pedi=dynamic_cast<PExtremaDataItem*>(_currentObject);\n Q_ASSERT(pedi && pedi->_extrema);\n pedi->_extrema->_high=x;\n}\n\nvoid PMainWindow::extremaLowLogic(double x)\n{\n PExtremaDataItem* pedi=dynamic_cast<PExtremaDataItem*>(_currentObject);\n Q_ASSERT(pedi&&pedi->_extrema);\n pedi->_extrema->_low=x;\n}\n\nvoid PMainWindow::extremaXLowLogic(double x)\n{\n PExtremaDataItem* pedi=dynamic_cast<PExtremaDataItem*>(_currentObject);\n Q_ASSERT(pedi && pedi->_extrema);\n pedi->_extrema->_xlow=x;\n}\n\nvoid PMainWindow::multiLogic()\n{\n setUpdatesEnabled(0);\n PMultiDataItem* pmdi=dynamic_cast<PMultiDataItem*>(_currentObject);\n Q_ASSERT(pmdi);\n bool update=0;\n if(sender()==ui->pushButtonAddFormat) {\n ui->tableWidgetFormat->insertRow(ui->tableWidgetFormat->rowCount());\n } else if(sender()==ui->pushButtonDelFormat) {\n ui->tableWidgetFormat->removeRow(1);\n update=1;\n } else if(sender()==ui->tableWidgetFormat) {\n update=1;\n }\n\n if(update) {\n pmdi->_map->reset();\n for(int i=0;i<ui->tableWidgetFormat->rowCount();i++) {\n if(ui->tableWidgetFormat->item(i,0))\n {\n int a=ui->tableWidgetFormat->item(i,0)->data(Qt::EditRole).toInt();\n QString b;\n if(ui->tableWidgetFormat->columnCount()>=2&&\n ui->tableWidgetFormat->item(i,1) &&\n !ui->tableWidgetFormat->item(i,1)->data(Qt::EditRole).isNull()) {\n b=ui->tableWidgetFormat->item(i,1)->data(Qt::EditRole).toString();\n } else {\n continue;\n }\n pmdi->_map->set(a,b);\n }\n }\n\n if(ui->tableWidgetFormat->currentRow()!=-1&&ui->tableWidgetFormat->item(ui->tableWidgetFormat->currentRow(),0)) {\n _currowStyle=pmdi->_map->style(ui->tableWidgetFormat->item(\n ui->tableWidgetFormat->currentRow(),0)->text().toInt(),PStyle::noStyle);\n ui->pstyleSelected->setWidgetStyleRef(_currowStyle);\n ui->pstyleSelected->setEnabled(1);\n } else {\n ui->pstyleSelected->setEnabled(0);\n }\n }\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::bitmultiLogic()\n{\n setUpdatesEnabled(0);\n PMultiDataItem* pmdi=dynamic_cast<PMultiDataItem*>(_currentObject);\n Q_ASSERT(pmdi);\n bool update=0;\n if(sender()==ui->pushButtonAddFormat) {\n ui->tableWidgetFormat->insertRow(ui->tableWidgetFormat->rowCount());\n } else if(sender()==ui->pushButtonDelFormat) {\n ui->tableWidgetFormat->removeRow(1);\n update=1;\n } else if(sender()==ui->tableWidgetFormat) {\n update=1;\n }\n\n if(update) {\n pmdi->_map->reset();\n for(int i=0;i<ui->tableWidgetFormat->rowCount();i++) {\n if(ui->tableWidgetFormat->item(i,0))\n {\n int a=ui->tableWidgetFormat->item(i,0)->data(Qt::EditRole).toInt();\n QString b;\n if(ui->tableWidgetFormat->columnCount()>=2&&\n ui->tableWidgetFormat->item(i,1) &&\n !ui->tableWidgetFormat->item(i,1)->data(Qt::EditRole).isNull()) {\n b=ui->tableWidgetFormat->item(i,1)->data(Qt::EditRole).toString();\n } else {\n continue;\n }\n pmdi->_map->set(a,b);\n }\n }\n\n if(ui->tableWidgetFormat->currentRow()!=-1&&ui->tableWidgetFormat->item(ui->tableWidgetFormat->currentRow(),0)) {\n _currowStyle=pmdi->_map->style(ui->tableWidgetFormat->item(\n ui->tableWidgetFormat->currentRow(),0)->text().toInt(),PStyle::noStyle);\n ui->pstyleSelected->setWidgetStyleRef(_currowStyle);\n ui->pstyleSelected->setEnabled(1);\n } else {\n ui->pstyleSelected->setEnabled(0);\n }\n }\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::currowLogic()\n{\n if(!ui->tableWidgetFormat->isVisible()) return;\n setUpdatesEnabled(0);\n if(ui->tableWidgetFormat->selectedItems().size()==1&&\n ui->tableWidgetFormat->item(ui->tableWidgetFormat->selectedItems()[0]->row(),1))\n {\n QString t=ui->tableWidgetFormat->item(ui->tableWidgetFormat->selectedItems()[0]->row(),1)->text();\n if(t.contains(\"[style=\")) {\n if(t.indexOf(\"]\",t.indexOf(\"[style=\"))) {\n t.remove(t.indexOf(\"[style=\"),t.indexOf(\"]\"));\n } else {\n t.remove(t.indexOf(\"[style=\"),999999999);\n }\n }\n t.push_back(\"[style=\"+_currowStyle->name()+\" \"+_currowStyle->idText()+\"]\");\n ui->tableWidgetFormat->item(ui->tableWidgetFormat->selectedItems()[0]->row(),1)->setText(t);\n }\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::gdUpdate()\n{\n if (!_dirfile) {\n return;\n }\n\n static int last_nFrames = 0;\n int nFrames = _dirfile->NFrames();\n\n if (nFrames != last_nFrames) {\n last_nFrames = nFrames;\n /* reset the resetLink timer */\n _reset_timer->start();\n }\n PAbstractDataItem::newCycle(); // reset delay timeout so\n // item updates don't take too long\n for(int i=0;i<_pboxList.size();i++) {\n _pboxList[i]->gdUpdate(_dirfile,nFrames);\n }\n\n\n if (_lastNFrames != nFrames) {\n _lastNFrames = nFrames;\n _lastUpdate = time(NULL);\n }\n\n int dT = time(NULL) - _lastUpdate;\n for(int i=0;i<_owlList.size();i++) {\n _owlList[i]->gdUpdate(_dirfile,nFrames, dT);\n }\n if(_dirty) {\n bool ok=0;\n for(int i=0;i<_pboxList.size();i++) {\n for(int j=0;j<ui->comboBox->count();j++) {\n if(ui->comboBox->itemText(j).contains(_pboxList[i]->idText())) {\n ui->comboBox->setItemText(j,_pboxList[i]->boxTitle()+\" \"+_pboxList[i]->idText());\n }\n }\n\n if(ui->comboBox->currentText().contains(_pboxList[i]->idText())) {\n Q_ASSERT(!ok);\n ok=1;\n ui->lineEditCaption->setText(_pboxList[i]->boxTitle());\n ui->labelCaption->show();\n ui->lineEditCaption->show();\n //ui->labelColour->show();\n ui->pstyleCaption->show();\n reconnect(ui->lineEditCaption,SIGNAL(textChanged(QString)),_pboxList[i],SLOT(setBoxTitle(QString)));\n reconnect(_pboxList[i],SIGNAL(textChanged(QString)),this,SLOT(uiLogic()));\n }\n\n for(int j=0;j<_pboxList[i]->_dataItems.size();j++) {\n PAbstractDataItem* padi=_pboxList[i]->_dataItems[j];\n\n if(ui->comboBox->currentText().contains(padi->idText())) {\n Q_ASSERT(!ok); // the reason for this is that we should not have the same PADI in two places.\n ok=1;\n int l=ui->lineEditCaption->cursorPosition();\n ui->lineEditCaption->setText(padi->caption());\n ui->lineEditCaption->setCursorPosition(l);\n int v=ui->lineEditSource->cursorPosition();\n ui->lineEditSource->setText(padi->source());\n ui->lineEditSource->setCursorPosition(v);\n }\n }\n }\n _dirty=0;\n }\n PStyleNotifier::me->notifyChange();\n serverUpdate();\n}\n\nvoid PMainWindow::removeCurrentDataItem()\n{\n PAbstractDataItem* padi=dynamic_cast<PAbstractDataItem*>(_currentObject);\n POwlAnimation* owl=dynamic_cast<POwlAnimation*>(_currentObject);\n if(!padi&&!owl) return;\n else if(owl) {\n for(int i=0;i<_owlList.size();i++) {\n if(_owlList[i]==owl) {\n obviate(owl);\n ui->comboBox->setCurrentIndex(0);\n owl->deleteLater();\n hideEverything();\n activate();\n }\n }\n return;\n }\n for(int i=0;i<_pboxList.size();i++) {\n _pboxList[i]->_dataItems.removeOne(padi);\n }\n obviate(padi);\n ui->comboBox->setCurrentIndex(0);\n _currentObject->deleteLater();\n hideEverything();\n ui->comboBox->setCurrentIndex(0);\n activate();\n}\n\nvoid PMainWindow::obviate(POwlAnimation *byeBye)\n{\n for(int i=0;i<ui->comboBox->count();i++) {\n if(ui->comboBox->itemText(i).contains(byeBye->idText())) {\n ui->comboBox->removeItem(i);\n break;\n }\n }\n activate();\n}\n\nvoid PMainWindow::obviate(PBox *byeBye)\n{\n ui->comboBox->setCurrentIndex(0);\n ui->pstyleCaption->setNoWidgetStyleRef();\n ui->pstyleData->setNoWidgetStyleRef();\n _pboxList.removeOne(byeBye);\n for(int i=0;i<ui->comboBox->count();i++) {\n if(ui->comboBox->itemText(i).contains(byeBye->idText())) {\n ui->comboBox->removeItem(i);\n break;\n }\n }\n for(int j=0;j<byeBye->_dataItems.size();j++) {\n obviate(byeBye->_dataItems[j]);\n }\n hideEverything();\n ui->comboBox->setCurrentIndex(0);\n activate();\n}\n\nvoid PMainWindow::obviate(PAbstractDataItem *byeBye)\n{\n ui->comboBox->setCurrentIndex(0);\n ui->pstyleCaption->setNoWidgetStyleRef();\n ui->pstyleData->setNoWidgetStyleRef();\n ui->pstyleHigh->setNoWidgetStyleRef();\n ui->pstyleLow->setNoWidgetStyleRef();\n ui->pstyleSelected->setNoWidgetStyleRef();\n ui->pstyleXHigh->setNoWidgetStyleRef();\n ui->pstyleXLow->setNoWidgetStyleRef();\n\n for(int i=0;i<ui->comboBox->count();i++) {\n if(ui->comboBox->itemText(i).contains(byeBye->idText())) {\n ui->comboBox->removeItem(i);\n break;\n }\n }\n activate();\n}\n\nvoid PMainWindow::recognizeExtrema(PExtrema *e)\n{\n ui->comboBoxExtrema->addItem(e->name()+\" \"+e->idText());\n}\n\nQVariant PMainWindow::state()\n{\n QVariantMap state;\n state.insert(\"statics\", save(*this));\n state.insert(\"data\", _data());\n return state;\n}\n\nQVariant PMainWindow::_data()\n{\n QVariantMap data;\n for (int i = 0; i < _pboxList.size(); ++i) {\n for (int j = 0; j < _pboxList[i]->_dataItems.size(); ++j) {\n PAbstractDataItem* padi = _pboxList[i]->_dataItems[j];\n QVariantList list;\n list.push_back(padi->data());\n list.push_back(padi->getPrevDataStyle()->id());\n data.insert(\"(P\" + QString::number(padi->id()) + \")\", list);\n }\n }\n return data;\n}\n\nQVariant PMainWindow::stateChanges()\n{\n // This does not currently send changes to layout and such.\n QVariantMap state;\n\n QVariantMap data;\n for (int i = 0; i < _pboxList.size(); ++i) {\n for (int j = 0; j < _pboxList[i]->_dataItems.size(); ++j) {\n PAbstractDataItem* padi = _pboxList[i]->_dataItems[j];\n if (padi->_serverDirty) {\n QVariantList list;\n list.push_back(padi->data());\n list.push_back(padi->getPrevDataStyle()->id());\n data.insert(\"(P\" + QString::number(padi->id()) + \")\", list);\n //data.insert(\"(P\" + QString::number(padi->id()) + \")\", padi->data());\n padi->_serverDirty = false;\n }\n }\n }\n\n state.insert(\"data\", data);\n return state;\n}\n\nvoid PMainWindow::serverUpdate()\n{\n#if QT_VERSION >= 0x050300\n if (_server) {\n _server->update();\n }\n#endif\n}\n\n#if QT_VERSION >= 0x050300\nint PMainWindow::webPort()\n{\n if (ui->checkBoxServer->isChecked()) {\n return ui->spinBoxServerPort->value();\n } else {\n return -1;\n }\n}\n\nvoid PMainWindow::setWebEnabled(const bool &enabled) {\n this->setWebPort(enabled ? ui->spinBoxServerPort->value() : -1);\n}\n\nvoid PMainWindow::setWebPort(const int &port)\n{\n static bool noRecurse = false;\n if (noRecurse) {\n return;\n }\n noRecurse = true;\n\n delete _server;\n _server = 0;\n if (port == -1) {\n ui->checkBoxServer->setChecked(false);\n ui->spinBoxServerPort->setValue(8001);\n } else {\n ui->checkBoxServer->setChecked(true);\n ui->spinBoxServerPort->setValue(port);\n _server = new PWebServer(this, port);\n }\n\n noRecurse = false;\n}\n#endif\n\nvoid PMainWindow::activate()\n{\n reconnect(ui->pushButtonResetLink, SIGNAL(clicked()), this, SLOT(resetLink()));\n reconnect(ui->lineEditLOS,SIGNAL(textChanged(QString)),this,SLOT(curfileLogic()));\n reconnect(ui->lineEditLoRate,SIGNAL(textChanged(QString)),this,SLOT(curfileLogic()));\n reconnect(ui->lineEditHighGain,SIGNAL(textChanged(QString)),this,SLOT(curfileLogic()));\n reconnect(ui->lineEditIridium,SIGNAL(textChanged(QString)),this,SLOT(curfileLogic()));\n reconnect(ui->lineEditTDRSSOmni,SIGNAL(textChanged(QString)),this,SLOT(curfileLogic()));\n reconnect(ui->radioButtonLOS,SIGNAL(clicked()),this,SLOT(curfileLogic()));\n reconnect(ui->radioButtonLoRate,SIGNAL(clicked()),this,SLOT(curfileLogic()));\n reconnect(ui->radioButtonHighGain,SIGNAL(clicked()),this,SLOT(curfileLogic()));\n reconnect(ui->radioButtonIridium,SIGNAL(clicked()),this,SLOT(curfileLogic()));\n reconnect(ui->radioButtonTDRSSOmni,SIGNAL(clicked()),this,SLOT(curfileLogic()));\n}\n\nQByteArray formatStream(QByteArray &rawS) {\n QByteArray formatedS;\n int n_spaces = 0;\n\n formatedS.reserve(rawS.size()*1.5);\n\n rawS.replace(\"{ \",\"{\\n\").replace('}',\"\\n}\").replace(\", \\\"\", \",\\n\\\"\");\n\n for (int i=0; i<rawS.size(); i++) {\n formatedS.append(rawS.at(i));\n if ((i+1<rawS.size()) && (rawS.at(i+1)=='}')) {\n n_spaces--;\n }\n if (rawS.at(i)=='\\n') {\n for (int j=0; j<n_spaces*2; j++) {\n formatedS.append(' ');\n }\n } else if (rawS.at(i)=='{') {\n n_spaces++;\n }\n }\n\n return formatedS;\n}\n\nQVariant save(PMainWindow&b);\nvoid PMainWindow::owlSave()\n{\n QString filename = _filename; //settings->value(\"filename\").toString();\n QFileInfo qfi(filename);\n if (qfi.exists()) {\n QFile file(filename);\n file.open(QFile::WriteOnly | QFile::Text);\n\n#if QT_VERSION >= 0x050000\n QJsonDocument document = QJsonDocument::fromVariant(save(*this));\n file.write(document.toJson(QJsonDocument::Indented));\n#else\n QJson::Serializer s;\n QByteArray rawS(s.serialize(save(*this)));\n file.write(formatStream(rawS));\n //file.write(rawS);\n#endif\n\n _settings->setValue(\"filename\", file.fileName());\n\n file.close();\n } else {\n owlSaveAs();\n }\n}\n\n\nvoid PMainWindow::owlSaveAs()\n{\n QString filename = _filename; //settings->value(\"filename\").toString();\n QFileInfo qfi(filename);\n\n QFile file(QFileDialog::getSaveFileName(this,\"Save the current owl project\",qfi.dir().dirName(),\"Owl projects(*.owl)\"));\n file.open(QFile::WriteOnly | QFile::Text);\n\n#if QT_VERSION >= 0x050000\n QJsonDocument document = QJsonDocument::fromVariant(save(*this));\n file.write(document.toJson(QJsonDocument::Indented));\n#else\n QJson::Serializer s;\n QByteArray rawS(s.serialize(save(*this)));\n file.write(formatStream(rawS));\n //file.write(rawS);\n#endif\n\n _settings->setValue(\"filename\", file.fileName());\n\n _filename = file.fileName();\n\n file.close();\n}\n\n\nvoid load(QVariant v,PMainWindow&b);\nvoid PMainWindow::owlLoad(QString filename)\n{\n if(filename.isEmpty()) {\n filename = QFileDialog::getOpenFileName(0,\"Load an Owl project\",\"\",\"Owl projects(*.owl)\");\n }\n\n QFileInfo f(filename);\n\n if (!f.exists()) {\n return;\n }\n\n filename=f.absoluteFilePath();\n\n if(filename.isEmpty()) {\n return;\n }\n setUpdatesEnabled(0);\n\n ///////////////////////////////////////////\n _deleteScheduled=1;\n deleteLater();\n PExtrema::_u.clear();\n PStyle::_u.clear();\n PObject::_u.clear();\n PStyleNotifier::me->disable();\n ///////////////////////////////////////////\n\n if(filename.endsWith(\"owl\")) {\n QFile file(filename);\n file.open(QFile::ReadOnly);\n QByteArray qba = file.readAll();\n\n#if QT_VERSION >= 0x050000\n QJsonParseError error;\n\n QJsonDocument d = QJsonDocument::fromJson(qba, &error);\n QVariant root = d.toVariant();\n\n if (error.error != QJsonParseError::NoError) {\n QMessageBox::critical(0, \"Parse Error\", \"Could not parse JSON: \" + error.errorString());\n return;\n }\n#else\n QJson::Parser p; // QT4\n bool ok;\n QVariant root=p.parse(qba,&ok); // QT4\n\n if (!(ok&&root.isValid())) {\n QMessageBox::critical(0, \"Parse Error\", \"Could not parse JSON: \");\n return;\n }\n#endif\n\n PObject::isLoading=1;\n PMainWindow* newWindow=new PMainWindow(font().pointSize(), 0);\n newWindow->setUpdatesEnabled(0);\n newWindow->_ut->stop();\n newWindow->_reset_timer->stop();\n load(root,*newWindow);\n\n newWindow->_mdiArea->adjustSize();\n newWindow->_mdiArea->setMinimumSize(newWindow->width()-70, newWindow->height()-70);\n\n //newWindow->setWindowTitle(_WINDOW_TITLE_);\n newWindow->show();\n newWindow->_ut->start();\n newWindow->_reset_timer->start();\n newWindow->setUpdatesEnabled(1);\n file.close();\n } else {\n QMessageBox::warning(0,\"Could not load file\",filename+\" does not seem to be either a .owl file!\");\n\n PMainWindow* newMain=new PMainWindow(font().pointSize(), 0);\n qApp->setActiveWindow(newMain);\n newMain->show();\n PStyleNotifier::me->enable();\n PStyleNotifier::me->notifyChange();\n return;\n }\n\n _settings->setValue(\"filename\", filename);\n _filename = filename;\n PStyleNotifier::me->enable();\n PStyleNotifier::me->notifyChange();\n setUpdatesEnabled(1);\n}\n\nvoid PMainWindow::setMDIMinSize(int w, int h) {\n _mdiArea->setMinimumSize(QSize(w, h));\n}\n\nvoid PMainWindow::showInKst() {\n PAbstractDataItem* padi=dynamic_cast<PAbstractDataItem*>(currentObject());\n if(!padi) return;\n /*\n qDebug() << QString(\"import pykst as kst\\n\"\n \"client = kst.Client(\\\"\"+QString(getenv(\"USER\"))+\"-owl\\\")\\n\"\n \"x=client.new_data_vector(\\\"\"+QString(_dirfileFilename)+\"\\\",field = \\\"INDEX\\\", start=-1, num_frames=1000)\\n\"\n \"y=client.new_data_vector(\\\"\"+QString(_dirfileFilename)+\"\\\",field = \\\"\"+QString(padi->source())+\"\\\", start=-1, num_frames=1000)\\n\"\n \"c=client.new_curve(x,y)\\n\"\n \"p=client.new_plot((0.5, 0.5), (1.0, 1.0))\\n\"\n \"p.add(c)\\n\"\n );\n */\n PyRun_SimpleString(QString(\"import pykst as kst\\n\"\n \"client = kst.Client(\\\"\"+QString(getenv(\"USER\"))+\"-owl\\\")\\n\"\n \"x=client.new_data_vector(\\\"\"+QString(_dirfileFilename)+\"\\\",field = \\\"INDEX\\\", start=-1, num_frames=1000)\\n\"\n \"y=client.new_data_vector(\\\"\"+QString(_dirfileFilename)+\"\\\",field = \\\"\"+QString(padi->source())+\"\\\", start=-1, num_frames=1000)\\n\"\n \"c=client.new_curve(x,y)\\n\"\n \"p=client.new_plot((0.5, 0.5), (1.0, 1.0))\\n\"\n \"p.add(c)\\n\"\n ).toLatin1());\n}\n" }, { "alpha_fraction": 0.6991701126098633, "alphanum_fraction": 0.7033194899559021, "avg_line_length": 24.36842155456543, "blob_id": "4e1a4802a87cee69703ef447cb5da5fafc45433b", "content_id": "485b4aadfb2cc42be5ac5b65f58b9729994b1c5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 482, "license_type": "no_license", "max_line_length": 69, "num_lines": 19, "path": "/blastd/rc.local", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n# rc.local\n#\n# This script is executed at the end of each multiuser runlevel.\n# Make sure that the script will \"exit 0\" on success or any other\n# value on error.\n#\n# In order to enable or disable this script just change the execution\n# bits.\n#\n\n/usr/local/sbin/tdrsslogger >& /data/etc/tdrsslogger.log &\n/usr/local/sbin/rnc >& /data/etc/rnc.log &\n/usr/local/sbin/dnc >& /data/etc/dnc.log &\n/usr/local/sbin/tea >& /data/etc/tea.log &\n/usr/local/bin/blastcmd -d\n\nexit 0\n" }, { "alpha_fraction": 0.7166666388511658, "alphanum_fraction": 0.7277777791023254, "avg_line_length": 21.5, "blob_id": "4e60b687a836119e67741d5ec5701344470e2ad4", "content_id": "1c31e809185cd3dd70a3dfbc56a43842c2f43f2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 361, "license_type": "no_license", "max_line_length": 73, "num_lines": 16, "path": "/stars/code/tools/refraction.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef TOOLS__REFRACTION_H\n#define TOOLS__REFRACTION_H\n\nnamespace Tools\n{\n double refraction_angle(double el, double P_mbar, double T);\n}\n\n#endif\n" }, { "alpha_fraction": 0.7523809671401978, "alphanum_fraction": 0.761904776096344, "avg_line_length": 33.66666793823242, "blob_id": "89b8322b3c026c5b62d714d32038837095776fb9", "content_id": "aeb49525b2b9f21be9b03482584b0507717c8a01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 105, "license_type": "no_license", "max_line_length": 53, "num_lines": 3, "path": "/stars/code/preprocessor.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "// This file is a reference for preprocessor_custom.h\n\n#define PREPROCESSOR_USING_CAMERA 1 // no camera\n\n" }, { "alpha_fraction": 0.5643052458763123, "alphanum_fraction": 0.5743387341499329, "avg_line_length": 28.35714340209961, "blob_id": "ee4fff2cf96037d67568befb463d2bf03497a77c", "content_id": "ec2a1ca705da111484e8802fafa4fd2795637421", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3290, "license_type": "no_license", "max_line_length": 128, "num_lines": 112, "path": "/stars/code/solving/finding/pedestal_fitter.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"pedestal_fitter.h\"\n#include <levmar.h>\n#include \"../blob.h\"\n#include \"../../shared/image/raw.h\"\n#include \"../../tools/timing.h\"\n\n#include \"../../tools/quick_cout.h\"\n\nusing namespace Solving;\nusing namespace Solving::Finding;\n\nnamespace levmar_c_functions\n{\n\nstruct pedestal_additional_data\n{\n int* us;\n int* vs;\n};\n\nvoid pedestal_error_function(double* params, double* pixels, int num_params, int num_pixels, void* data)\n{\n pedestal_additional_data* additional_data = (pedestal_additional_data*) data;\n int* us = additional_data->us;\n int* vs = additional_data->vs;\n for (int i=0; i<num_pixels; i++) {\n pixels[i] = params[0]*us[i] + params[1]*vs[i] + params[2];\n }\n}\n\n}\n\nPedestalFitter::PedestalFitter()\n{\n padding = 5;\n halfwidth = 30;\n max_num_pixels = (padding*2+halfwidth*2+1)*(padding*2+halfwidth*2+1);\n pixels = new double[max_num_pixels];\n us = new int[max_num_pixels];\n vs = new int[max_num_pixels];\n\n int max_num_params = 3;\n workspace = (double *) malloc((LM_DIF_WORKSZ(max_num_params, max_num_pixels)+max_num_params*max_num_params)*sizeof(double));\n covar = workspace + LM_DIF_WORKSZ(max_num_params, max_num_pixels);\n}\n\nPedestalFitter::~PedestalFitter()\n{\n delete [] pixels;\n delete [] us;\n delete [] vs;\n free(workspace);\n}\n\nvoid PedestalFitter::fit_pedestal(Shared::Image::Raw& image, Blob& blob)\n{\n int minu = blob.u - halfwidth - padding;\n int maxu = blob.u + halfwidth + padding;\n int minv = blob.v - halfwidth - padding;\n int maxv = blob.v + halfwidth + padding;\n int i = 0;\n double mean = 0.0;\n for (int u = minu; u <= maxu; u++ ) {\n for (int v = minv; v <= maxv; v++) {\n if (i < max_num_pixels && image.is_inbounds(u, v)) {\n if (u >= blob.u-halfwidth && u <= blob.u+halfwidth &&\n v >= blob.v-halfwidth && v <= blob.v+halfwidth)\n {\n // inside\n } else{\n // outside\n us[i] = u;\n us[i] = v;\n pixels[i] = double(image.get_pixel(u, v));\n mean += pixels[i];\n i++;\n }\n }\n }\n }\n int num_pixels = i;\n levmar_c_functions::pedestal_additional_data additional_data;\n additional_data.us = us;\n additional_data.vs = vs;\n\n int num_params = 3; // [a, b, c] in: z = a*u + b*v + c\n double* params = new double[num_params];\n params[0] = 0.0;\n params[1] = 0.0;\n params[2] = mean/double(num_pixels);\n\n dlevmar_dif(levmar_c_functions::pedestal_error_function, params, pixels, num_params, num_pixels,\n 100, NULL, NULL, workspace, covar, (void*) &additional_data);\n\n delete [] params;\n}\n\nvoid PedestalFitter::fit_pedestals(Shared::Image::Raw& image, std::vector<Blob>& blobs)\n{\n Tools::Timer timer;\n timer.start();\n for (unsigned int i=0; i<blobs.size(); i++) {\n //fit_pedestal(image, blobs[i]);\n }\n //cout << \"fitting \" << blobs.size() << \" pedestals took \" << timer.time() << endl;\n}\n\n" }, { "alpha_fraction": 0.6364710330963135, "alphanum_fraction": 0.6451358795166016, "avg_line_length": 31.55128288269043, "blob_id": "4671b1ddf64e88e8fffd6dc27e2b726013d82ed8", "content_id": "c29ff30d98dd41923c30ad7a369d46e242ded5e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2539, "license_type": "no_license", "max_line_length": 89, "num_lines": 78, "path": "/starcam/findbadpixel.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* findbadpixel.cpp\n *\n * utility program to analyze bad pixel dark exposures of different integration times\n * and construct a bad pixel text file, for use by starcam.cpp\n *\n */\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <fstream>\n\n#include \"blobimage.h\"\n#include \"camstruct.h\"\n\nusing namespace std;\n\nconst unsigned int box_size = 15;\nconst unsigned int n_boxes = 3;\nconst double expose_min = 0.1;\nconst char* avgfilename = \"/tmp/average.sbig\";\nconst double snr_threshold = 7.0;\n\nint main(int argc, char* argv[])\n{\n BlobImage bimg(CAM_HEIGHT, CAM_WIDTH);\n unsigned int* sum = new unsigned int[(int)CAM_HEIGHT*(int)CAM_WIDTH];\n unsigned short* bimg_p;\n\n if (argc < 2) {\n cerr << \"Must specify a list of image files to process\" << endl;\n return 1;\n }\n\n for (int i=0; i<CAM_WIDTH*CAM_HEIGHT; i++) sum[i] = 0;\n\n for (int i=1; i<argc; i++) {\n cout << \"Opening Image File \" << argv[i];\n bimg.OpenImage(argv[i]);\n cout << \" with integration time \" << bimg.GetExposureTime() << \"s\" << endl;\n bimg.setBadpixFilename(\"/tmp/IdontExist\"); //clear badpix file name\n bimg.FixBadpix(\"/tmp/badpix.txt\");\t //don't test already detected blobs\n bimg.highPassFilter(box_size, n_boxes);\n bimg_p = bimg.GetImagePointer();\n double normalization = bimg.GetExposureTime()/expose_min;\n for (int i=0; i<CAM_WIDTH*CAM_HEIGHT; i++)\n sum[i] += (unsigned int)round((double)bimg_p[i]/normalization);\n }\n\n BlobImage avgimg(CAM_HEIGHT, CAM_WIDTH);\n unsigned short* avgimg_p = avgimg.GetImagePointer();\n for (int i=0; i<CAM_WIDTH*CAM_HEIGHT; i++)\n avgimg_p[i] = (unsigned short)round((double)sum[i]/(double)(argc-1));\n double avgmean = avgimg.getFrameBlob()->get_mapmean();\n double avgsigma = avgimg.getFrameBlob()->calc_stddev();\n cout << \"Mean: \" << avgmean << \" Sigma: \" << avgsigma << endl;\n int badcount = 0;\n ofstream fout(\"/tmp/badpix.txt\");\n BlobImage avgimg_copy(CAM_HEIGHT, CAM_WIDTH);\n avgimg_copy.copyImageFrom(avgimg.GetImagePointer());\n for (int x=0; x<(int)CAM_WIDTH; x++) {\n for (int y=0; y<(int)CAM_HEIGHT; y++) {\n if ((int)avgimg_p[x+y*(int)CAM_WIDTH] - avgmean > snr_threshold*avgsigma) {\n\tcout << \"Bad pixel at \" << x <<\",\" << y << endl;\n\tfout << x << \" \" << y << endl;\n avgimg_copy.drawBox(x, y, 40, 0);\n\tbadcount++;\n }\n }\n }\n cout << \"Found \" << badcount << \" bad pixels with SNR above \" << snr_threshold << endl;\n\n cout << \"Saving averaged image to \" << avgfilename << endl;\n avgimg_copy.SaveImage(avgfilename);\n\n\n delete [] sum;\n return 0;\n}\n" }, { "alpha_fraction": 0.6245704293251038, "alphanum_fraction": 0.6466208696365356, "avg_line_length": 26.714284896850586, "blob_id": "9691ffbdc45db4a8480483c30d65b30108013e3a", "content_id": "c743fab7dec4eb03b1e5222f77158f2f6b5ee80b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3492, "license_type": "no_license", "max_line_length": 81, "num_lines": 126, "path": "/common/include/bitserver.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* ---------------------------------------------------------------------\n * ----------------------------- BITSERVER -----------------------------\n * ---------------------------------------------------------------------\n * Copyright 2014 Javier Romualdez\n *\n * This program is distributed under the GNU General Public License (GPL)\n * Version 2 or higher.\n *\n * ------------------------- Description -------------------------------\n * The functions here enable UDP communication between various network\n * machines.\n *\n * ---------------------------- Author ---------------------------------\n * L. Javier Romualdez (B.Eng Aerospace)\n * Institute for Aerospace Studies (UTIAS)\n * University of Toronto\n *\n * Created: May 1, 2014\n *\n *\n * -------------------------- Revisions --------------------------------\n *\n */\n#ifndef INCLUDE_BITSERVER_H\n#define INCLUDE_BITSERVER_H\n\n#define UDPMAXBUFLEN 65536 // maximum UDP buffer size [bytes]\n#define PACKET_HEADER_SIZE 12 // header size for packets [bytes]\n#define DEFAULT_SERIAL 0xabadfeed // default serial for packets\n#define NO_HEADER 0x02 // flag to send message without a header\n#define DONT_REMOVE 0x04 // bit receiver without removing from bit receiver\n#define RECV_TIMEOUT 0x08 // recvFromBITRecver times out\n\n#define RECV_TIMEOUT_NUM 10 // number of tenths of seconds until recvFrom timeout\n\n/* OSX doesn't support MSG_NOSIGNAL (it never signals) */\n#ifdef __APPLE__\n\n#define COMMON_DIGEST_FOR_OPENSSL\n#include <CommonCrypto/CommonDigest.h>\n#define SHA1 CC_SHA1\n\n#include <sys/socket.h>\n#include \"FIFO.h\"\n\n#ifndef MSG_NOSIGNAL\n#define MSG_NOSIGNAL 0\n#endif\n#endif\n\n#ifndef MIN\n#define MIN(a, b) ((a) < (b) ? (a) : (b))\n#endif\n#ifndef MAX\n#define MAX(a, b) ((a) > (b) ? (a) : (b))\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nstruct BITSender\n{\n int sck;\n struct sockaddr_in my_addr;\n struct sockaddr_in send_addr;\n socklen_t slen;\n uint32_t serial;\n uint32_t frame_num;\n\n pthread_t send_thread;\n unsigned int packet_maxsize;\n struct Fifo * send_fifo;\n};\n\nstruct BITRecver\n{\n int sck;\n struct sockaddr_in my_addr;\n struct sockaddr_in recv_addr;\n socklen_t slen;\n uint32_t serial;\n uint32_t frame_num;\n\n pthread_t recv_thread;\n unsigned int packet_maxsize;\n struct Fifo * recv_fifo;\n};\n\nextern int verbosity;\n\n// some function prototypes\nint initBITSender(struct BITSender *, const char *,\n unsigned int, unsigned int,\n unsigned int, unsigned int);\nint initBITRecver(struct BITRecver *, const char *,\n unsigned int, unsigned int,\n unsigned int, unsigned int);\n\nint closeBITSender(struct BITSender *);\nint closeBITRecver(struct BITRecver *);\n\nint sendToBITSender(struct BITSender *, uint8_t *, unsigned int, uint8_t);\nint recvFromBITRecver(struct BITRecver *, uint8_t *, unsigned int, uint8_t);\nint peekBITRecver(struct BITRecver *);\n\nuint16_t writeHeader(uint8_t *, uint32_t, uint32_t, uint16_t, uint16_t);\nuint16_t readHeader(uint8_t *, uint32_t**, uint32_t**, uint16_t**, uint16_t**);\n\nint setBITSenderAddr(struct BITSender *, uint8_t *);\nuint8_t *getBITSenderAddr(struct BITSender *);\nuint8_t *getBITRecverAddr(struct BITRecver *, unsigned int *);\n\nint setBITSenderSerial(struct BITSender *, uint32_t);\nint setBITRecverSerial(struct BITRecver *, uint32_t);\nint setBITSenderFramenum(struct BITSender *, uint32_t);\nint setBITRecverFramenum(struct BITRecver *, uint32_t);\n\nint appendBITSenderAddr(struct BITSender *, unsigned int);\nint removeBITRecverAddr(struct BITRecver *);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* INCLUE_BITSERVER_H */\n" }, { "alpha_fraction": 0.6950517892837524, "alphanum_fraction": 0.6998191475868225, "avg_line_length": 33.174156188964844, "blob_id": "8d9654e761fb65120e75a25b2e1d9d5d67081a67", "content_id": "89166fcb30c5e34228c3539b76a85537539009a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 6083, "license_type": "no_license", "max_line_length": 92, "num_lines": 178, "path": "/defricher/CMakeLists.txt", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "# Helper function to add preprocesor definition of FILE_BASENAME\n# to pass the filename without directory path for debugging use.\n#\n# Example:\n#\n# define_file_basename_for_sources(my_target)\n#\n# Will add -DFILE_BASENAME=\"filename\" for each source file depended on\n# by my_target, where filename is the name of the file.\n#\nfunction(define_file_basename_for_sources targetname)\n get_target_property(source_files \"${targetname}\" SOURCES)\n foreach(sourcefile ${source_files})\n # Get source file's current list of compile definitions.\n get_property(defs SOURCE \"${sourcefile}\"\n PROPERTY COMPILE_DEFINITIONS)\n # Add the FILE_BASENAME=filename compile definition to the list.\n get_filename_component(basename \"${sourcefile}\" NAME)\n list(APPEND defs \"__FILENAME__=\\\"${basename}\\\"\")\n # Set the updated compile definitions on the source file.\n set_property(\n SOURCE \"${sourcefile}\"\n PROPERTY COMPILE_DEFINITIONS ${defs})\n endforeach()\nendfunction()\n\nproject (defricher)\n\ncmake_minimum_required (VERSION 2.8.8)\n\noption(USE_CLANG \"build defricher using clang\" OFF)\n\nif (USE_CLANG)\n SET (CMAKE_C_COMPILER \"/usr/bin/clang\")\n SET (CMAKE_CXX_COMPILER \"/usr/bin/clang++\")\nendif(USE_CLANG)\n\nSET (CMAKE_C_FLAGS \"-Wall -std=gnu99\")\nSET (CMAKE_C_FLAGS_DEBUG \"-g\")\nSET (CMAKE_C_FLAGS_MINSIZEREL \"-Os -DNDEBUG\")\nSET (CMAKE_C_FLAGS_RELEASE \"-O3 -DNDEBUG\")\nSET (CMAKE_C_FLAGS_RELWITHDEBINFO \"-O2 -g\")\n\nSET (CMAKE_CXX_FLAGS \"-Wall\")\nSET (CMAKE_CXX_FLAGS_DEBUG \"-g\")\nSET (CMAKE_CXX_FLAGS_MINSIZEREL \"-Os -DNDEBUG\")\nSET (CMAKE_CXX_FLAGS_RELEASE \"-O3 -DNDEBUG\")\nSET (CMAKE_CXX_FLAGS_RELWITHDEBINFO \"-O2 -g\") \n\n# Set global definitions\nadd_definitions(-D_GNU_SOURCE)\n\n# Find external libs\nfind_package(PkgConfig)\n\n# Find Threading lib\nfind_package (Threads)\n\n# Find ExternalProject module\ninclude (ExternalProject)\n\n# Find glib \npkg_check_modules(PC_GLIB glib-2.0)\nset(GLIB_DEFINITIONS ${PC_GLIB_CFLAGS_OTHER})\n\nfind_path(GLIB_INCLUDE_DIR NAMES glib.h\n HINTS ${PC_GLIB_INCLUDEDIR} ${PC_GLIB_INCLUDE_DIRS}\n PATH_SUFFIXES glib-2.0 REQUIRED)\nfind_path(GLIBCONFIG_INCLUDE_DIR NAMES glibconfig.h\n HINTS ${PC_GLIB_INCLUDEDIR} ${PC_GLIB_INCLUDE_DIRS}\n PATH_SUFFIXES glib-2.0 REQUIRED)\nfind_library(GLIB_LIBRARY NAMES glib-2.0 libglib-2.0\n HINTS ${PC_GLIB_LIBDIR} ${PC_GLIB_LIBRARY_DIRS} REQUIRED)\nIF(NOT GLIB_INCLUDE_DIR)\n MESSAGE(FATAL_ERROR \"Did not find glib.h. Is libglib2.0-dev installed?\")\nENDIF()\nIF(NOT GLIB_LIBRARY) \n MESSAGE(FATAL_ERROR \"Did not find libglib-2.0. Is libglib2.0-0 installed?\")\nENDIF()\ninclude_directories(${GLIB_INCLUDE_DIR} ${GLIBCONFIG_INCLUDE_DIR})\n\n# Find mosquitto \npkg_check_modules(PC_MOSQ QUIET mosquitto)\nset(MOSQ_DEFINITIONS ${PC_MOSQ_CFLAGS_OTHER})\n\nfind_path(MOSQ_INCLUDE_DIR NAMES mosquitto.h\n HINTS ${PC_MOSQ_INCLUDEDIR} ${PC_MOSQ_INCLUDE_DIRS}\n PATH_SUFFIXES mosquitto REQUIRED)\nfind_library(MOSQ_LIBRARY NAMES mosquitto libmosquitto\n HINTS ${PC_MOSQ_LIBDIR} ${PC_MOSQ_LIBRARY_DIRS} REQUIRED)\nIF(NOT MOSQ_INCLUDE_DIR)\n MESSAGE(FATAL_ERROR \"Did not find mosquitto.h. Is libmosquitto-dev installed?\")\nENDIF()\nIF(NOT MOSQ_LIBRARY) \n MESSAGE(FATAL_ERROR \"Did not find libmosquitto. Is libmosquitto1 installed?\")\nENDIF()\ninclude_directories(${MOSQ_INCLUDE_DIR})\n\n# Find getdata \npkg_check_modules(PC_GD QUIET getdata)\n\nfind_path(GD_INCLUDE_DIR NAMES getdata.h\n HINTS ${PC_GD_INCLUDEDIR} ${PC_GD_INCLUDE_DIRS} REQUIRED)\nfind_library(GD_LIBRARY NAMES getdata\n HINTS ${PC_GD_LIBDIR} ${PC_GD_LIBRARY_DIRS} REQUIRED)\nIF(NOT GD_INCLUDE_DIR)\n MESSAGE(FATAL_ERROR \"Did not find getdata.h. Is libgetdata-dev installed?\")\nENDIF()\nIF(NOT GD_LIBRARY) \n MESSAGE(FATAL_ERROR \"Did not find libgetdata. Is libgetdata4 installed?\")\nENDIF()\ninclude_directories(${GD_INCLUDE_DIR})\n\n# add linklist library\nset(LINKLIST_LIBRARY ${CMAKE_CURRENT_BINARY_DIR}/linklist/liblinklist.a)\nExternalProject_Add(linklist\n PREFIX ${CMAKE_CURRENT_BINARY_DIR}/linklist\n BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/linklist\n URL ${PROJECT_SOURCE_DIR}/../external_libs/linklist\n INSTALL_COMMAND \"\"\n BUILD_ALWAYS 1)\n\ninclude_directories(${PROJECT_SOURCE_DIR}/../external_libs/linklist)\n\n# configure a header file to pass some of the CMake settings to the source code\nconfigure_file (\n \"${PROJECT_SOURCE_DIR}/defricher_config.h.in\"\n \"${PROJECT_BINARY_DIR}/include/defricher_config.h\"\n )\n\n# add machine directory for OSX builds (needs endian.h)\ninclude_directories (\"/usr/include/machine\")\n\n# add the binary tree to the search path for include files so that we will find mcp_config.h\ninclude_directories (\"${PROJECT_BINARY_DIR}/include\")\n\nset(COMMON_DIR \"${PROJECT_SOURCE_DIR}/../common\")\nset(CONFIG_DIR \"${PROJECT_SOURCE_DIR}/../blast_config\")\n\ninclude_directories (\n \"${PROJECT_SOURCE_DIR}/include\"\n \"${COMMON_DIR}/include\"\n \"${CONFIG_DIR}/include\"\n )\n\n# add common objects\nadd_subdirectory(${COMMON_DIR} \"${PROJECT_BINARY_DIR}/blast_common\")\nadd_subdirectory(${CONFIG_DIR} \"${PROJECT_BINARY_DIR}/blast_config\")\n\nadd_library (blast_common OBJECT ${DEFRICHER_COMMON_SRCS} ${DEFRICHER_COMMON_HEADERS})\ndefine_file_basename_for_sources(blast_common)\n\nadd_executable (defricher \n $<TARGET_OBJECTS:blast_common>\n ${PROJECT_SOURCE_DIR}/defricher.c\n ${PROJECT_SOURCE_DIR}/defricher.h\n ${PROJECT_SOURCE_DIR}/defricher_utils.c\n ${PROJECT_SOURCE_DIR}/defricher_utils.h\n ${PROJECT_SOURCE_DIR}/defricher_netreader.c\n ${PROJECT_SOURCE_DIR}/defricher_netreader.h\n ${PROJECT_SOURCE_DIR}/defricher_writer.c\n ${PROJECT_SOURCE_DIR}/defricher_writer.h\n ) \n\nadd_dependencies(defricher linklist)\n\ndefine_file_basename_for_sources(defricher)\n\ntarget_link_libraries(defricher \n ${GLIB_LIBRARY} \n ${GD_LIBRARY}\n ${MOSQ_LIBRARY} \n ${LINKLIST_LIBRARY} \n ${CMAKE_THREAD_LIBS_INIT} \n ssl crypto\n m)\n\ninstall(TARGETS defricher DESTINATION bin)\n" }, { "alpha_fraction": 0.7302989363670349, "alphanum_fraction": 0.7459239363670349, "avg_line_length": 33.23255920410156, "blob_id": "a95d632dbbbe5adbe731357628d3b9a710ebb89a", "content_id": "e286a54890fb203e723e5bdfea01d7b43b36f060", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1472, "license_type": "no_license", "max_line_length": 84, "num_lines": 43, "path": "/owl/PDirfileDataItem.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"PObject.h\"\n#include <QWidget>\n#include <QHBoxLayout>\n#include <QLabel>\n#include \"getdata/dirfile.h\"\n#include \"PAbstractDataItem.h\"\n\n#ifndef PDIRFILEDATAITEM_H\n#define PDIRFILEDATAITEM_H\n\nclass PDirfileDataItem : public PAbstractDataItem\n{\n Q_OBJECT\npublic:\n friend QDataStream& operator<<(QDataStream&a,PAbstractDataItem&b);\n friend class PMainWindow;\n PDirfileDataItem(PBox*p,QString caption) : PAbstractDataItem(p,caption) {}\n PDirfileDataItem(PBox*p,PDirfileDataItem* other) : PAbstractDataItem(p,other) {}\n virtual void gdUpdate(GetData::Dirfile* dirFile,int lastNFrames);\n};\n\n#endif // PDIRFILEDATAITEM_H\n" }, { "alpha_fraction": 0.561971127986908, "alphanum_fraction": 0.5719974637031555, "avg_line_length": 33.63793182373047, "blob_id": "3219a89fc9776e32149a8b18013bf03b01f7f730", "content_id": "a2a09988e8364bd35198f8b95549bc44235edd7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14063, "license_type": "no_license", "max_line_length": 137, "num_lines": 406, "path": "/owl/PBox.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include \"PBox.h\"\n#include \"PMainWindow.h\"\n#include \"PTimeDataItem.h\"\n#include \"PDirfileDataItem.h\"\n#include \"PBoxTitle.h\"\n#include <QInputDialog>\n#include <QDesktopServices>\n#include <QMimeData>\n\nPBox::PBox(QString boxTitle, const QFont &F, QWidget*p) : QFrame(p), _pstyle(PStyle::noStyle), _lastPStyle(0),_layout(new QVBoxLayout()),\n _boxTitle(boxTitle), _geoMode(-1), _dirty(1)\n{\n bool ok=0;\n for(int i=0;i<PStyle::_u.size();i++) {\n Q_ASSERT(PStyle::_u[i]);\n if(PStyle::_u[i]->name()==\"defbox\") {\n ok=1;\n _pstyle=PStyle::_u[i];\n break;\n }\n }\n\n setFont(F);\n _H = fontMetrics().height();\n\n _pstyle=ok?_pstyle:new PStyle(\"defbox\",1,0,\"white\",\"blue\",1);\n\n setFrameStyle(QFrame::NoFrame | QFrame::Plain);\n\n setLineWidth(1);\n int margin = fontMetrics().height()/3;\n setContentsMargins(0,0,0,0);\n setMidLineWidth(1);\n //setFrameShadow(QFrame::Plain);\n _pbt=new PBoxTitle;\n _pbt->setText(\"[change me]\");\n _pbt->setFont(F);\n addTitle(_pbt);\n connect(PStyleNotifier::me,SIGNAL(change()),this,SLOT(styleLogic()));\n setWindowTitle(boxTitle);\n setLayout(_layout);\n _layout->setSpacing(0);\n setMinimumSize(_H*2,_H*3);\n setAcceptDrops(1);\n _layout->setContentsMargins(margin,0,margin,0);\n _layout->addSpacerItem(new QSpacerItem(0,0,QSizePolicy::Minimum,QSizePolicy::MinimumExpanding));\n\n // QRect geo=geometry();\n // geo.setX(((int)geo.x()/_H)*_H);\n // geo.setY(((int)geo.y()/_H)*_H);\n // geo.setWidth(((int)geo.width()/_H)*_H+0);\n // geo.setHeight(((int)geo.height()/_H)*_H+0);\n // if(geo!=geometry()) {\n // setGeometry(geo);\n // }\n setAutoFillBackground(1);\n setMouseTracking(1);\n}\n\nPBox::~PBox()\n{\n PMainWindow::me->obviate(this);\n}\n\nvoid PBox::checkActivationState() {\n if(!children().contains(PMainWindow::me->currentObject())) {\n emit activated();\n }\n}\n\nvoid PBox::styleLogic() {\n if(_pstyle!=_lastPStyle|| //the reason this works is because PStyleChooser works via reference to ptr\n _pstyle->_dirty) {\n applyStyle(this,_pstyle);\n _lastPStyle=_pstyle;\n }\n setAutoFillBackground(1);\n}\n\nvoid PBox::setBoxTitle(const QString& boxTitle, bool force)\n{\n if (boxTitle.isEmpty()) {\n _pbt->setFixedHeight(0);\n }\n\n if (!isCurrentObject() && !force) return;\n\n if(_boxTitle==boxTitle) return;\n\n _boxTitle=boxTitle;\n _pbt->setText(boxTitle);\n\n emit textChanged(boxTitle);\n}\n\nvoid PBox::gdUpdate(GetData::Dirfile* dirFile,int lastNFrames)\n{\n for(int i=0;i<_dataItems.size();i++) {\n _dataItems[i]->gdUpdate(dirFile,lastNFrames);\n }\n if(_dirty) {\n int maxCapWidth = 0;\n int maxCapHeight = 0;\n for(int i=0;i<_dataItems.size();i++) {\n _dataItems[i]->gdUpdate(dirFile, lastNFrames);\n QSize size = _dataItems[i]->_caption->fontMetrics().size(0, _dataItems[i]->_caption->text());\n\n maxCapWidth=qMax(maxCapWidth, size.width());\n maxCapHeight = qMax(maxCapHeight, _dataItems[i]->_caption->fontMetrics().height());\n }\n for(int i=0;i<_dataItems.size();i++) {\n if(_dataItems[i]->_caption->width()!=maxCapWidth) {\n _dataItems[i]->_caption->setFixedWidth(maxCapWidth);\n }\n _dataItems[i]->_caption->setFixedHeight(maxCapHeight);\n _dataItems[i]->_data->setFixedHeight(maxCapHeight);\n }\n _dirty=0;\n }\n}\n\nvoid PBox::dragEnterEvent(QDragEnterEvent *ev)\n{\n if(ev->mimeData()->hasFormat(\"application/x-qabstractitemmodeldatalist\"))\n {\n QByteArray encoded = ev->mimeData()->data(\"application/x-qabstractitemmodeldatalist\");\n QDataStream stream(&encoded, QIODevice::ReadOnly);\n\n int row, col;\n QMap<int, QVariant> roleDataMap;\n stream >> row >> col >> roleDataMap;\n if(row&&row<6&&!col) { //HACKHACKHACKHACK!!!\n ev->acceptProposedAction();\n }\n }\n else if(ev->mimeData()->hasFormat(\"application/x-owlid\")) {\n ev->acceptProposedAction();\n }\n}\n\nint PBox::getWhereToInsert(QPoint p) {\n int pos=-1;\n for(int i=0;i<_dataItems.size();i++) {\n if(!i&&_dataItems[i]->y()>p.y()) {\n pos=0;\n break;\n }\n if(_dataItems[i]->geometry().contains(p)) {\n if(p.y()>_dataItems[i]->geometry().center().y()) {\n pos=i+1;\n } else {\n pos=i;\n }\n break;\n }\n }\n return pos;\n}\n\nvoid PBox::dropEvent(QDropEvent *ev)\n{\n if(ev->mimeData()->hasFormat(\"application/x-qabstractitemmodeldatalist\"))\n {\n QByteArray encoded = ev->mimeData()->data(\"application/x-qabstractitemmodeldatalist\");\n QDataStream stream(&encoded, QIODevice::ReadOnly);\n\n int row, col;\n QMap<int, QVariant> roleDataMap;\n stream >> row >> col >> roleDataMap;\n int pos=getWhereToInsert(ev->pos());\n if(pos!=-1) ++pos;\n if(row&&row<6&&!col) { //HACKHACKHACKHACK!!!\n switch(row) {\n case 1:\n addProperty(\"Number\",pos);\n break;\n case 2:\n addProperty(\"Multi\",pos);\n break;\n case 3:\n addProperty(\"Time/Date\",pos);\n break;\n case 4:\n addProperty(\"Dirfile\",pos);\n break;\n case 5:\n addProperty(\"BitMulti\",pos);\n break;\n default:\n addProperty(\"Item\",pos);\n break;\n }\n }\n }\n else if(ev->mimeData()->hasFormat(\"application/x-owlid\")) {\n int oid=ev->mimeData()->data(\"application/x-owlid\").toInt();\n for(int i=0;i<PObject::_u.size();i++) {\n if(!PObject::_u.values()[i]) continue;\n if(PObject::_u.values()[i]->id()==oid&&dynamic_cast<PAbstractDataItem*>(PObject::_u.values()[i])) {\n QString answer;\n if(ev->keyboardModifiers()&Qt::ControlModifier) {\n answer=\"copy\";\n } else if(ev->keyboardModifiers()&Qt::ShiftModifier) {\n answer=\"move\";\n } else {\n QStringList a;\n a.push_back(\"move (shift+drag)\");\n a.push_back(\"copy (ctrl+drag)\");\n bool ok;\n answer=QInputDialog::getItem(this,\"Move or Copy?\",\"Choose an action:\",a,0,false,&ok);\n if(!ok) return;\n }\n int pos=getWhereToInsert(ev->pos());\n if(pos!=-1) ++pos;\n if(answer.startsWith(\"copy\")) {\n if(dynamic_cast<PNumberDataItem*>(PObject::_u.values()[i])) {\n addProperty(new PNumberDataItem(this,dynamic_cast<PNumberDataItem*>(PObject::_u.values()[i])),pos);\n } else if(dynamic_cast<PMultiDataItem*>(PObject::_u.values()[i])) {\n addProperty(new PMultiDataItem(this,dynamic_cast<PMultiDataItem*>(PObject::_u.values()[i])),pos);\n } else if(dynamic_cast<PBitMultiDataItem*>(PObject::_u.values()[i])) {\n addProperty(new PBitMultiDataItem(this,dynamic_cast<PBitMultiDataItem*>(PObject::_u.values()[i])),pos);\n } else if(dynamic_cast<PTimeDataItem*>(PObject::_u.values()[i])) {\n addProperty(new PTimeDataItem(this,dynamic_cast<PTimeDataItem*>(PObject::_u.values()[i])),pos);\n } else if(dynamic_cast<PDirfileDataItem*>(PObject::_u.values()[i])) {\n addProperty(new PDirfileDataItem(this,dynamic_cast<PDirfileDataItem*>(PObject::_u.values()[i])),pos);\n } else {\n qDebug()<<\"Cannot copy data item of unknown type!\";\n }\n } else if(answer.startsWith(\"move\")) {\n dynamic_cast<PAbstractDataItem*>(PObject::_u.values()[i])->_caption->setFixedWidth(1);\n PBox*x=dynamic_cast<PBox*>(dynamic_cast<PAbstractDataItem*>(PObject::_u.values()[i])->parentWidget()); //assert?\n x->_layout->removeWidget(dynamic_cast<PAbstractDataItem*>(PObject::_u.values()[i]));\n x->_dataItems.removeOne(dynamic_cast<PAbstractDataItem*>(PObject::_u.values()[i]));\n addProperty(dynamic_cast<PAbstractDataItem*>(PObject::_u.values()[i]),pos);\n _dirty=1;\n }\n return;\n }\n }\n }\n}\n\nvoid PBox::addProperty(QString property,int pos)\n{\n if(property==\"Number\") {\n addProperty(new PNumberDataItem(this, property),pos);\n } else if(property==\"BitMulti\") {\n addProperty(new PBitMultiDataItem(this, property),pos);\n } else if(property==\"Multi\") {\n addProperty(new PMultiDataItem(this, property),pos);\n } else if(property==\"Time/Date\") {\n addProperty(new PTimeDataItem(this, property),pos);\n } else if(property==\"Dirfile\") {\n addProperty(new PDirfileDataItem(this, property),pos);\n } else {\n qWarning()<<\"Adding pure abstract data item\";\n addProperty(new PAbstractDataItem(this, property),pos);\n }\n}\n\nvoid PBox::addProperty(PAbstractDataItem* padi,int pos)\n{\n if (pos==-1) {\n _dataItems.push_back(padi);\n } else { /* if != -1, then pos has biased by one by the caller */\n _dataItems.insert(pos - 1,padi);\n }\n\n _layout->insertWidget((pos==-1)?_dataItems.size():pos, padi); //not -1 because of title\n padi->setFixedHeight(padi->fontMetrics().height());\n padi->show();\n emit newChild(padi);\n}\n\nvoid PBox::addTitle(PBoxTitle* pbt)\n{\n if (pbt->text().isEmpty()) {\n printf(\"Empty Title!\\n\");\n }\n\n _layout->insertWidget(0,pbt);\n pbt->setFixedHeight(pbt->fontMetrics().height());\n pbt->show();\n}\n\nvoid PBox::mousePressEvent(QMouseEvent *e)\n{\n if (PMainWindow::me->mouseInactive()) return;\n\n _geoMode=-1;\n emit activated();\n QWidget::mousePressEvent(e);\n}\n\nvoid PBox::mouseReleaseEvent(QMouseEvent *)\n{\n if (PMainWindow::me->mouseInactive()) return;\n\n _geoMode=-1;\n}\n\nvoid PBox::mouseMoveEvent(QMouseEvent *ev)\n{\n if (PMainWindow::me->mouseInactive()) {\n setCursor(QCursor(Qt::ArrowCursor));\n return;\n }\n\n QPoint p1=parentWidget()->mapFromGlobal(ev->globalPos()); //setGeometry refers to parent's (x,y)\n QRect geo=geometry();\n bool resize=(ev->buttons()&Qt::LeftButton);\n if(!resize) {\n _geoMode=-1;\n }\n if(_geoMode==-1) {\n int mdis=99999999;\n int mcase=-1;\n\n int dis2TL=(p1-geometry().topLeft()).manhattanLength();\n if(dis2TL<mdis&&(resize||dis2TL<_H)) { mdis=dis2TL; mcase=0; }\n\n int dis2TR=(p1-geometry().topRight()).manhattanLength();\n if(dis2TR<mdis&&(resize||dis2TR<_H)) { mdis=dis2TR; mcase=1; }\n\n int dis2BL=(p1-geometry().bottomLeft()).manhattanLength();\n if(dis2BL<mdis&&(resize||dis2BL<_H)) { mdis=dis2BL; mcase=2; }\n\n int dis2BR=(p1-geometry().bottomRight()).manhattanLength();\n if(dis2BR<mdis&&(resize||dis2BR<_H)) { mdis=dis2BR; mcase=3; }\n\n int dis2TC=(p1-QPoint((geometry().left()+geometry().right())/2,geometry().top())).manhattanLength();\n if(dis2TC<mdis&&(resize||dis2TC<_H)) { mdis=dis2TC; mcase=4; }\n\n Q_ASSERT(!resize||(mcase!=-1));\n _geoMode=mcase;\n }\n switch(_geoMode) {\n case 0: //TL\n setCursor(QCursor(Qt::SizeFDiagCursor));\n geo.setX(parentWidget()->mapFromGlobal(ev->globalPos()).x()/_H*_H);\n geo.setY(parentWidget()->mapFromGlobal(ev->globalPos()).y()/_H*_H);\n break;\n case 1: //TR\n setCursor(QCursor(Qt::SizeBDiagCursor));\n geo.setRight(parentWidget()->mapFromGlobal(ev->globalPos()).x()/_H*_H+0);\n geo.setY(parentWidget()->mapFromGlobal(ev->globalPos()).y()/_H*_H);\n break;\n case 2: //BL\n setCursor(QCursor(Qt::SizeBDiagCursor));\n geo.setX(parentWidget()->mapFromGlobal(ev->globalPos()).x()/_H*_H);\n geo.setBottom(parentWidget()->mapFromGlobal(ev->globalPos()).y()/_H*_H+0);\n break;\n case 3: //BR\n setCursor(QCursor(Qt::SizeFDiagCursor));\n geo.setRight(parentWidget()->mapFromGlobal(ev->globalPos()).x()/_H*_H+0);\n geo.setBottom(parentWidget()->mapFromGlobal(ev->globalPos()).y()/_H*_H+0);\n break;\n case 4: //TC\n if(ev->buttons()&Qt::LeftButton) {\n setCursor(QCursor(Qt::ClosedHandCursor));\n } else {\n setCursor(QCursor(Qt::OpenHandCursor));\n }\n {\n QPoint origCenter=QPoint((geometry().left()+geometry().right())/2,geometry().top());\n int moveX=(origCenter.x()-p1.x())/_H*_H;\n int origWidth=geometry().width();\n int moveY=(origCenter.y()-p1.y())/_H*_H;\n int origHeight=geometry().height();\n geo.setX((geo.x()-moveX)/_H*_H);\n geo.setY((geo.y()-moveY)/_H*_H);\n geo.setWidth(origWidth/_H*_H);\n geo.setHeight(origHeight/_H*_H);\n }\n break;\n\n default:\n setCursor(QCursor(Qt::ArrowCursor));\n\n }\n\n if(ev->buttons()&Qt::LeftButton) {\n setGeometry(geo);\n }\n}\n" }, { "alpha_fraction": 0.6380297541618347, "alphanum_fraction": 0.6426116824150085, "avg_line_length": 17.5744686126709, "blob_id": "7bd72e1ef62254287171ee2418842b7b621b7a8e", "content_id": "770a75154722f4c304cb896a506acb3786a10af4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 874, "license_type": "no_license", "max_line_length": 77, "num_lines": 47, "path": "/stars/code/solving/finding/fitter.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__FINDING__FITTER_H\n#define SOLVING__FINDING__FITTER_H\n\n#include \"../blob.h\"\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n}\n\nnamespace Solving\n{\n namespace Finding\n {\n class Fitter;\n }\n}\n\nclass Solving::Finding::Fitter\n{\n public:\n Fitter();\n ~Fitter();\n void fit_gaussian(Shared::Image::Raw& image, Solving::Blob& blob);\n void fit_double_gaussian(Shared::Image::Raw& image, Solving::Blob& blob);\n Blob fit(Shared::Image::Raw& image, Solving::Blob& blob);\n\n private:\n int max_num_pixels;\n double* pixels;\n int* us;\n int* vs;\n double* workspace;\n double* covar;\n};\n\n#endif\n" }, { "alpha_fraction": 0.618852436542511, "alphanum_fraction": 0.6290983557701111, "avg_line_length": 20.173913955688477, "blob_id": "0aa22544d85ab1c018bc78fb5a99c0f8ce9b46c2", "content_id": "b8d6280fa79ad1a9598934a0f36bb4ff5ddd5e06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 489, "license_type": "no_license", "max_line_length": 73, "num_lines": 23, "path": "/stars/code/shared/lens/requests.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"requests.h\"\n\nusing namespace Shared::Lens;\n\nRequests::Requests()\n{\n}\n\nRequests& Requests::operator=(const Requests &rhs)\n{\n if (this != &rhs) {\n for (unsigned int i=0; i<num_requests; i++) {\n commands[i] = rhs.commands[i];\n }\n }\n return *this;\n}\n\n" }, { "alpha_fraction": 0.7231404781341553, "alphanum_fraction": 0.7231404781341553, "avg_line_length": 20, "blob_id": "3185227a7d6f8f545f6783a0727bd6aa1f8f7ecc", "content_id": "3f71741f00a6baae0d76aa51dbcd59ac6d13bed2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 484, "license_type": "no_license", "max_line_length": 77, "num_lines": 23, "path": "/stars/code/dmm.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"dscud.h\"\n\nclass dmm\n{\npublic:\n\tdmm();\n\t~dmm();\n\tvoid dmm::dmm_initialize();\n\tvoid dmm::dmm_scan(double *);\n\tvoid dmm::cycle_camera(void);\n\tvoid dmm::heat_camera(bool enable);\n\nprivate:\n\tbool initialized;\n\n\tDSCB dscb; // handle used to refer to the DMM board\n\tDSCCB dsccb; // structure containing board settings\n\tDSCADSETTINGS dscadsettings; // structure containing A/D conversion settings\n\tDSCADSCAN dscadscan; // structure containing A/D scan settings\n\n};\n\n" }, { "alpha_fraction": 0.5929721593856812, "alphanum_fraction": 0.6061493158340454, "avg_line_length": 29.647436141967773, "blob_id": "fdc82a22fedcf00b0b39fb034133791e43a94cbc", "content_id": "c20ffd90bb9d5443966ac113bbf61d710e21b491", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4781, "license_type": "no_license", "max_line_length": 103, "num_lines": 156, "path": "/common/xsc_fifo.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/**\n * @file xsc_fifo.c\n *\n * @date Feb 14, 2011\n * @author seth\n *\n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2010 Columbia University\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <sched.h>\n#include <stdbool.h>\n\n#include <blast.h>\n#include <atomic.h>\n#include <xsc_fifo.h>\n\ntypedef struct __attribute__((packed)) fifo_element\n{\n xsc_fifo_node_t *node;\n intptr_t count;\n} fifo_element_t __attribute__((aligned(ALIGN_SIZE)));\n/**\n * Pushes a new chunk of data on the FIFO queue\n * @param m_fifo Pointer to the queue\n * @param m_data Pointer to the data to add\n */\nbool xsc_fifo_push(xsc_fifo_t *m_fifo, void *m_data)\n{\n xsc_fifo_node_t *new_node = malloc(sizeof(xsc_fifo_node_t));\n fifo_element_t push_struct[2];\n\n if (!m_fifo || !m_data) return false;\n\n new_node->next = END_FIFO(m_fifo);\n new_node->data = m_data;\n while (1) {\n push_struct[0].node = m_fifo->tail;\n push_struct[0].count = m_fifo->push_count;\n push_struct[1].node = m_fifo->tail->next;\n push_struct[1].count = m_fifo->push_count + 1;\n\n if (CAS_BOOL(&push_struct[0].node->next, END_FIFO(m_fifo), new_node)) break;\n\n /**\n * If we didn't succeed, then tail did not have the FIFO tail, in which\n * case we need to swing tail around and try again\n */\n sched_yield();\n CAS2(&m_fifo->tail, push_struct[0], push_struct[1]);\n }\n\n /**\n * We've successfully queued the node. Now try and point our fifo tail to the newly inserted\n * node. If we fail, then another node has been inserted behind us and we allow it to be set as\n * the tail.\n */\n push_struct[1].node = new_node;\n CAS2(&m_fifo->tail, push_struct[0], push_struct[1]);\n return true;\n}\n\n/**\n * Removes the oldest chunk of data from the FIFO queue\n * @param m_fifo Pointer to the FIFO queue\n * @return Pointer to the data chunk or NULL on failure\n */\nvoid *xsc_fifo_pop(xsc_fifo_t *m_fifo)\n{\n void *retval = NULL;\n fifo_element_t pop_struct[2];\n\n if (!m_fifo) return NULL;\n\n while (1) {\n pop_struct[0].node = m_fifo->head;\n pop_struct[0].count = m_fifo->pop_count;\n pop_struct[1].node = m_fifo->head->next;\n pop_struct[1].count = m_fifo->pop_count + 1;\n if (pop_struct[0].node == m_fifo->tail) {\n if (pop_struct[1].node == END_FIFO(m_fifo)) return NULL; /** If our queue is empty, exit */\n\n pop_struct[0].count = m_fifo->push_count;\n pop_struct[1].count = m_fifo->push_count + 1;\n CAS2(&m_fifo->tail, pop_struct[0], pop_struct[1]);\n } else if (pop_struct[1].node != END_FIFO(m_fifo)) {\n /**\n * Extract the data from our new dummy node\n */\n retval = pop_struct[1].node->data;\n if (CAS2_BOOL(&m_fifo->head, pop_struct[0], pop_struct[1])) break;\n }\n sched_yield();\n }\n\n /**\n * Free the dummy node\n */\n free(pop_struct[0].node);\n return retval;\n}\n\n/**\n * Creates a new FIFO structure and initializes the dummy node\n * @return Pointer to the FIFO structure\n */\nxsc_fifo_t *xsc_fifo_new()\n{\n xsc_fifo_t *new_fifo = NULL;\n xsc_fifo_node_t *new_node = NULL;\n\n if ((new_node = calloc(1, sizeof(xsc_fifo_node_t)))\n && (new_fifo = calloc(1, sizeof(xsc_fifo_t)))) {\n new_fifo->head = new_fifo->tail = (xsc_fifo_node_t*) new_node;\n } else {\n if (new_node) free(new_node);\n }\n return new_fifo;\n}\n\n/**\n * Frees the FIFO data structure. This will free internally allocated nodes as well, using either\n * a user-defined free() equivalent or the system free()\n * @param m_fifo Pointer to the FIFO data structure\n * @param m_free Pointer to the free()-equivalent function\n */\nvoid xsc_fifo_free(xsc_fifo_t *m_fifo, void (*m_free)(void*))\n{\n void *m_data = NULL;\n\n if (m_fifo) {\n while ((m_data = xsc_fifo_pop(m_fifo))) {\n if (m_free) m_free(m_data);\n }\n if (m_fifo->head) {\n if (m_free) free(m_fifo->head);\n }\n free(m_fifo);\n }\n}\n" }, { "alpha_fraction": 0.7147514224052429, "alphanum_fraction": 0.7180114388465881, "avg_line_length": 24.040817260742188, "blob_id": "b27c104fe9b88713df089fb84b6fe464d1f615a2", "content_id": "df3c41182071d0c4b172f1e77e91b3109f1f4aa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1228, "license_type": "no_license", "max_line_length": 110, "num_lines": 49, "path": "/stars/code/shared/general/main_settings.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__MAIN_SETTINGS_H\n#define SHARED__MAIN_SETTINGS_H\n\n#include \"../circular_buffer.h\"\n\nnamespace Shared\n{\n namespace General\n {\n\nclass MainSettings\n{\n public:\n MainSettings();\n void init(Parameters::Manager& params);\n\n double display_period;\n bool display_fullscreen;\n int display_fullscreen_counter;\n bool display_image_only;\n bool display_solving_filters;\n double display_image_brightness;\n int display_zoom_x;\n int display_zoom_y;\n double display_zoom_magnitude;\n};\n\n// writes: network\n// reads: main\nextern Shared::CircularBufferPass <MainSettings> main_settings_net_for_main;\n\n// writes: main\n// reads: solver\n// note: sharing the main settings with the solver thread comes from a poor design too close to flight\n// that muddles main settings with display settings, as the parameter display_image_brightness is used\n// by the solver's statistician\nextern Shared::CircularBuffer <MainSettings> main_settings_main_for_solver;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.6018306612968445, "alphanum_fraction": 0.7455377578735352, "avg_line_length": 43.53061294555664, "blob_id": "13888d5c6deec741a2be011d949dbb4b7312ad8a", "content_id": "4734066723a3dee97acdd43b46d20ace5eab7b73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2185, "license_type": "no_license", "max_line_length": 177, "num_lines": 49, "path": "/xsc_initialization_cmds.sh", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "\n# xsc_is_new_window_period which valid_period_cs\n#blastcmd @192.168.1.3 xsc_is_new_window_period 0 1500\n#blastcmd @192.168.1.3 xsc_is_new_window_period 1 1500\n\n# xsc_exposure_timing which exposure_cs grace_period_s (!!) share_delay_cs\nblastcmd @192.168.1.3 xsc_exposure_timing 0 12 60 200\nblastcmd @192.168.1.3 xsc_exposure_timing 1 12 60 200\n\n# xsc_solver_general which enabled timeout\n#blastcmd @192.168.1.3 xsc_solver_general 0 1 19\n#blastcmd @192.168.1.3 xsc_solver_general 1 1 19\n\n##### Triggering ######\n\n# xsc_trigger_threshold which enabled max_streaking_px # trigger only when conditions are met\nblastcmd @192.168.1.3 xsc_trigger_threshold 0 0 10\nblastcmd @192.168.1.3 xsc_trigger_threshold 1 0 10\n\n# xsc_scan_force_trigger which[doesnt apply] enabled # Force triggering at turnaround\nblastcmd @192.168.1.3 xsc_scan_force_trigger 0 1\n\n######### Solving and Filters ##########\n# xsc_filter_hor_location which enabled radius_degrees\nblastcmd @192.168.1.3 xsc_filter_hor_location 0 1 30\nblastcmd @192.168.1.3 xsc_filter_hor_location 1 1 30\n\n# xsc_filter_eq which enabled radius_degrees\nblastcmd @192.168.1.3 xsc_filter_eq_location 0 0 10\nblastcmd @192.168.1.3 xsc_filter_eq_location 1 0 10\n\n# xsc_filter_hor_roll which enabled min_deg max_deg\nblastcmd @192.168.1.3 xsc_filter_hor_roll 0 1 -5 5\nblastcmd @192.168.1.3 xsc_filter_hor_roll 1 1 -129 -135\n\n# xsc_filter_el which enabled min_deg max_deg\nblastcmd @192.168.1.3 xsc_filter_el 0 1 15 90\nblastcmd @192.168.1.3 xsc_filter_el 1 1 15 90\n\n# xsc_blob_finding which snr_thresh max_num_blobs robust_mode_enabled fitting_method\n#blastcmd @192.168.1.3 xsc_blob_finding 0 10 10 0 0\n#blastcmd @192.168.1.3 xsc_blob_finding 1 10 10 0 0\n\n# xsc_pattern_matching which enabled display_star_name match_tol_px iplatescale_min_arcsec iplatescale_max_arcsec platescale_always_fixed platescale_fixed # platescale ~6.4\"/pix\nblastcmd @192.168.1.3 xsc_pattern_matching 0 1 0 5 6.5 6.7 0 0\nblastcmd @192.168.1.3 xsc_pattern_matching 1 1 0 5 6.5 6.7 0 0\n\n# xsc_filter_matching which error_threshold_arcsec fit_error_thresh_px num_matched \nblastcmd @192.168.1.3 xsc_filter_matching 0 6 10 8\nblastcmd @192.168.1.3 xsc_filter_matching 1 6 10 8\n\n\n" }, { "alpha_fraction": 0.6882216930389404, "alphanum_fraction": 0.7043879628181458, "avg_line_length": 24.979999542236328, "blob_id": "8d5245805daa637b5ab2908a6726f22957076873", "content_id": "a46ca28f45f045a7f7bcf56d978703b562232c09", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1299, "license_type": "no_license", "max_line_length": 71, "num_lines": 50, "path": "/common/include/fir.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* mcp: the BLAST master control program\n *\n * This software is copyright (C) 2005 University of Toronto\n *\n * This file is part of mcp.\n *\n * mcp 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n\n#ifndef INCLUDE_FIR_H\n#define INCLUDE_FIR_H\n\n#define NSTAGE 8\ntypedef enum {\n wind_oldblast = 0,\n wind_blackman,\n wind_gauss,\n wind_lanczos,\n wind_hamming,\n wind_hann,\n wind_rect\n} e_windows;\n\ntypedef struct FirStruct {\n int i_w[NSTAGE];\n int ns;\n double *w;\n double sum[NSTAGE];\n double out;\n} fir_t;\n\nvoid init_fir(fir_t *fs, int N, int window, double alpha);\nvoid deinit_fir(fir_t *fs);\ndouble fir_filter(double x, fir_t *fs);\n\n#endif\n" }, { "alpha_fraction": 0.6728476881980896, "alphanum_fraction": 0.678145706653595, "avg_line_length": 18.346153259277344, "blob_id": "3ad5c0ecb5216ff1b7d341c857b21b22d9333fde", "content_id": "286d1e22c658bfb4f60be7c885bb90d901f460d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1511, "license_type": "no_license", "max_line_length": 84, "num_lines": 78, "path": "/stars/code/shared/autofocus/datapoints.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__AUTOFOCUS__DATAPOINTS_H\n#define SHARED__AUTOFOCUS__DATAPOINTS_H\n\n#include <vector>\n#include \"../circular_buffer.h\"\n#include \"../../tools/timing.h\"\n\nnamespace Logging\n{\n class Logger;\n}\n\nnamespace Shared\n{\n namespace Autofocus\n {\n\nenum datapoints_t\n{\n metric_brightest_blob_flux,\n metric_star_flux,\n metric_sobel\n};\n\nstruct CurvePoint\n{\n double focus;\n double value;\n CurvePoint(double focus_=0.0, double value_=0.0): focus(focus_), value(value_){}\n};\n\nclass Curve\n{\n public:\n Curve();\n bool get_peak(double& focus, double& value);\n void log(Logging::Logger& logger);\n Curve& operator=(const Curve& rhs);\n static bool sort_by_type(Curve first, Curve second)\n {\n return first.type > second.type;\n }\n\n datapoints_t type;\n int star_id;\n std::vector<CurvePoint> points;\n Tools::Timer age_since_last_datapoint_added;\n};\n\nclass Datapoints\n{\n public:\n Datapoints();\n Datapoints& operator=(const Datapoints& rhs);\n\n std::vector<Curve> curves;\n int last_fully_solved_counter_stars;\n};\n\n// writes: solver\n// reads: lens\nextern Shared::CircularBufferPass <Datapoints> datapoints_solver_to_lens;\n\n// writes: lens\n// reads: main\nextern Shared::CircularBuffer <Datapoints> datapoints_lens_to_main;\n\n }\n}\n\n#endif\n\n" }, { "alpha_fraction": 0.6413570046424866, "alphanum_fraction": 0.6526656150817871, "avg_line_length": 22.769229888916016, "blob_id": "2301c93d43d822fc64de32d2885fd630dfee6e9f", "content_id": "db2c508be1af7db73961f9d693f8b462596d2fc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 620, "license_type": "no_license", "max_line_length": 73, "num_lines": 26, "path": "/stars/code/shared/camera/requests.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"requests.h\"\n\nusing namespace Shared::Camera;\n\nRequests::Requests()\n{\n max_num_triggers = 4;\n multi_triggering_delay = 1.0;\n}\n\nRequests& Requests::operator=(const Requests &rhs)\n{\n if (this != &rhs) {\n set_gain = rhs.set_gain;\n get_gain = rhs.get_gain;\n max_num_triggers = rhs.max_num_triggers;\n multi_triggering_delay = rhs.multi_triggering_delay;\n }\n return *this;\n}\n\n" }, { "alpha_fraction": 0.5937255024909973, "alphanum_fraction": 0.6054902076721191, "avg_line_length": 30.850000381469727, "blob_id": "fce1fb38b0fb517bb8a99ac5491bdfeab63f19c4", "content_id": "ab3cba10a15b23ecd5920c3e4ba557e00cc795d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1276, "license_type": "no_license", "max_line_length": 98, "num_lines": 40, "path": "/stars/code/parameters/housekeeping.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"housekeeping.h\"\n#include <fstream>\n#include <string>\n#include <boost/format.hpp>\n#include \"../logger_main.h\"\n\nusing namespace Parameters;\nusing Main::logger;\n\nHousekeeping::Housekeeping()\n{\n using namespace boost::program_options;\n using std::string;\n for (unsigned int num=0; num<16; num++) {\n options.add_options()\n ((boost::format(\"channel%01d.name\") %num).str().c_str(), value<string>(), \"\")\n ((boost::format(\"channel%01d.type\") %num).str().c_str(), value<string>(), \"\")\n ((boost::format(\"channel%01d.resistor_value\")%num).str().c_str(), value<float>(), \"\")\n ((boost::format(\"channel%01d.voltage\") %num).str().c_str(), value<float>(), \"\")\n ;\n }\n}\n\nvoid Housekeeping::load(std::string filename)\n{\n std::ifstream file(filename.c_str());\n try {\n store(parse_config_file(file, options), map);\n } catch(std::exception& e) {\n logger.log(format(\"Caught exception in Parameters::Housekeeping: %s\") % e.what());\n }\n notify(map);\n file.close();\n}\n\n" }, { "alpha_fraction": 0.6653845906257629, "alphanum_fraction": 0.6705127954483032, "avg_line_length": 16.311111450195312, "blob_id": "cf94857b158e3c7356a665b7a665e13364e493eb", "content_id": "45e756263aaaa1d15e18e1c11cff0e1e15e3fd1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 781, "license_type": "no_license", "max_line_length": 102, "num_lines": 45, "path": "/stars/code/solving/finding/smoother.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__FINDING__SMOOTHER_H\n#define SOLVING__FINDING__SMOOTHER_H\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n}\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Solving\n{\n namespace Finding\n {\n class Smoother;\n }\n}\n\nclass Solving::Finding::Smoother\n{\n public:\n Smoother(Parameters::Manager& params);\n ~Smoother();\n void make_smooth(Shared::Image::Raw& image, double *pixels_smoothed, int halfwidth, double sigma);\n\n private:\n int image_width;\n int image_height;\n double* scratch;\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.559152364730835, "alphanum_fraction": 0.5684165954589844, "avg_line_length": 34.433963775634766, "blob_id": "66efb4c26dcdf462e25dcd4e2b8f0a9cf5573154", "content_id": "8d0c9214dc7485cdd8f55036a9656c64d64ee947", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9392, "license_type": "no_license", "max_line_length": 135, "num_lines": 265, "path": "/stars/code/displaying/image.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"image.h\"\n#include <string>\n#include <boost/format.hpp>\n#include \"../tools/angles.h\"\n#include \"../shared/image/blobs.h\"\n#include \"../shared/image/status.h\"\n#include \"../shared/image/stats.h\"\n#include \"../shared/image/solution_summary.h\"\n\nusing namespace Displaying;\n\n#define shared_blobs (*(Shared::Image::blobs_solver_for_main.r))\n#define shared_status (*(Shared::Image::status_solver_for_main.r))\n#define shared_stats (*(Shared::Image::stats_solver_for_main.r))\n#define shared_solution (*(Shared::Image::solution_summary_for_main.r))\n\nImage::Image()\n{\n change_size(630, 140);\n\n Color stored_color = Color(0.0, 1.0, 0.0, 1.0);\n Color measured_color = Color(0.5, 0.5, 1.0, 1.0);\n Color solution_color = Color(1.0, 1.0, 0.5, 1.0);\n\n age.init(\"age\");\n counter_stars.init(\"ctr_s\");\n counter_fcp.init(\"ctr_f\");\n lat.init(\"lat\");\n lst.init(\"lst\");\n mean.init(\"mean\");\n noise.init(\"noise\");\n gain.init(\"gain\");\n num_pixels_saturated.init(\"num_sat\");\n stage.init(\"\");\n ra.init(\"ra\");\n dec.init(\"dec\");\n az.init(\"az\");\n el.init(\"el\");\n hroll.init(\"hroll\");\n matched.init(\"match\");\n measured_exposure.init(\"mexp\");\n pointing_error.init(\"pt error\");\n fit_error.init(\"fit error\");\n platescale.init(\"plate\");\n\n age.color = stored_color;\n counter_stars.color = stored_color;\n counter_fcp.color = stored_color;\n lat.color = stored_color;\n lst.color = stored_color;\n mean.color = measured_color;\n noise.color = measured_color;\n gain.color = measured_color;\n num_pixels_saturated.color = measured_color;\n stage.color = solution_color;\n ra.color = solution_color;\n dec.color = solution_color;\n az.color = solution_color;\n el.color = solution_color;\n hroll.color = solution_color;\n matched.color = solution_color;\n measured_exposure.color = solution_color;\n pointing_error.color = solution_color;\n fit_error.color = solution_color;\n platescale.color = solution_color;\n}\n\nvoid Image::update()\n{\n using std::string;\n\n set_title(\"Emptiness\");\n age.known = false;\n counter_stars.known = false;\n counter_fcp.known = false;\n lat.known = false;\n lst.known = false;\n stage.known = false;\n if (shared_status.age.started()) {\n if (shared_status.num_exposures > 1) {\n set_title((boost::format(\"%s (%i)\") % shared_status.filename % shared_status.num_exposures).str());\n } else {\n set_title((boost::format(\"%s\") % shared_status.filename).str());\n }\n age.set_value(shared_status.age.time(), \" s\", 0);\n age.known = true;\n if (shared_status.from_camera) {\n counter_stars.set_value(shared_status.counter_stars, \"\", 0);\n } else {\n counter_stars.set_value(shared_status.counter_stars, \" [nc]\", 0);\n }\n counter_stars.known = true;\n counter_fcp.set_value(shared_status.counter_fcp, \"\", 0);\n counter_fcp.known = true;\n if (shared_status.horizontal_known) {\n lat.set_value(to_degrees(shared_status.lat), \"*\", 2);\n lat.known = true;\n lst.set_value(to_hours(shared_status.lst), \" hrs\", 2);\n lst.known = true;\n }\n switch (shared_status.stage) {\n using namespace Shared::Image;\n case Status::empty:\n stage.set_value(\"\"); break;\n case Status::doing_statistics:\n stage.set_value(\"getting stats...\"); break;\n case Status::blob_finding:\n stage.set_value(\"blob finding...\"); break;\n case Status::pattern_matching:\n stage.set_value(\"pattern matching...\"); break;\n case Status::refitting:\n stage.set_value(\"refitting...\"); break;\n case Status::getting_names:\n stage.set_value(\"getting names...\"); break;\n case Status::done:\n {\n string reason_string = \"\";\n switch(shared_status.reason_for_being_done) {\n case Status::no_reason:\n reason_string = \"no reason specified\"; break;\n case Status::solved:\n reason_string = \"solved\"; break;\n case Status::not_solving:\n reason_string = \"not solving\"; break;\n case Status::saturated:\n reason_string = \"too saturated\"; break;\n case Status::tried_all_patterns:\n reason_string = \"tried_all_patterns\"; break;\n case Status::timed_out:\n reason_string = \"timed out\"; break;\n case Status::aborted:\n reason_string = \"aborted\"; break;\n default:\n break;\n }\n string solving_time_string = \"\";\n if (shared_solution.counter_stars == shared_status.counter_stars) {\n if (shared_solution.equatorial.valid) {\n solving_time_string = (boost::format(\" (%.1f s)\") % shared_solution.solving_time).str();\n }\n }\n stage.set_value((boost::format(\"done, %s%s\") % reason_string % solving_time_string).str());\n break;\n }\n default:\n stage.set_value(\"\");\n stage.known = false;\n }\n }\n\n mean.known = false;\n noise.known = false;\n gain.known = false;\n num_pixels_saturated.known = false;\n if (shared_stats.counter_stars == shared_status.counter_stars) {\n if (shared_stats.mean_known) {\n mean.set_value(shared_stats.mean, \"\", 1);\n if (shared_stats.fraction_pixels_saturated > 0.001) {\n num_pixels_saturated.set_value(shared_stats.fraction_pixels_saturated*100.0, \"%\", 1);\n } else {\n num_pixels_saturated.set_value(shared_stats.num_pixels_saturated, \"\", 0);\n }\n }\n if (shared_stats.noise_known) {\n noise.set_value(shared_stats.noise, \"\", 1);\n }\n if (shared_stats.gain_known) {\n gain.set_value(shared_stats.gaindb, \" dB\", 1);\n }\n }\n\n ra.known = false;\n dec.known = false;\n az.known = false;\n el.known = false;\n hroll.known = false;\n matched.known = false;\n measured_exposure.known = false;\n pointing_error.known = false;\n fit_error.known = false;\n platescale.known = false;\n if (shared_solution.counter_stars == shared_status.counter_stars) {\n if (shared_solution.equatorial.valid) {\n ra.set_value(to_degrees(shared_solution.equatorial.ra), \"*\", 2);\n dec.set_value(to_degrees(shared_solution.equatorial.dec), \"*\", 2);\n matched.set_value((boost::format(\"%s of %s\") % shared_solution.num_blobs_matched % shared_solution.num_blobs_total).str());\n measured_exposure.set_value(shared_solution.measured_exposure*1000.0, \" ms\", 0);\n pointing_error.set_value(to_arcsec(shared_solution.equatorial.sigma_pointing), \"\\\"\", 2);\n fit_error.set_value(shared_solution.equatorial.fit_error, \" px\", 2);\n platescale.set_value(to_arcsec(shared_solution.equatorial.iplatescale), \"\\\"\", 3);\n }\n if (shared_solution.horizontal.valid) {\n az.set_value(to_degrees(shared_solution.horizontal.az), \"*\", 2);\n el.set_value(to_degrees(shared_solution.horizontal.el), \"*\", 2);\n hroll.set_value(to_degrees(shared_solution.horizontal.roll), \"*\", 2);\n }\n }\n}\n\nvoid Image::draw(Position& position)\n{\n update();\n\n glBindTexture(GL_TEXTURE_2D, textures->get(Textures::basic_drawing)); // Bind 0\n begin_draw(position);\n draw_border();\n draw_title();\n\n Position pos = {padding + padding, height() - padding - text_height - 4};\n draw_value(age, pos);\n pos.y -= text_height;\n draw_value(counter_stars, pos);\n pos.y -= text_height;\n draw_value(counter_fcp, pos);\n pos.y -= text_height;\n draw_value(lat, pos);\n pos.y -= text_height;\n draw_value(lst, pos);\n\n pos.x += 160;\n pos.y = height() - padding - text_height - 4;\n draw_value(mean, pos);\n pos.y -= text_height;\n draw_value(noise, pos);\n pos.y -= text_height;\n draw_value(num_pixels_saturated, pos);\n pos.y -= text_height;\n draw_value(gain, pos);\n\n pos.y = height() - padding;\n pos.x += 160;\n draw_value(stage, pos);\n pos.y -= 4;\n pos.y -= text_height;\n draw_value(ra, pos);\n pos.y -= text_height;\n draw_value(dec, pos);\n pos.y -= text_height;\n draw_value(az, pos);\n pos.y -= text_height;\n draw_value(el, pos);\n pos.y -= text_height;\n draw_value(hroll, pos);\n\n pos.y = height() - padding - text_height - 4;\n pos.x += 160;\n draw_value(matched, pos);\n pos.y -= text_height;\n draw_value(pointing_error, pos);\n pos.y -= text_height;\n draw_value(fit_error, pos);\n pos.y -= text_height;\n draw_value(platescale, pos);\n pos.y -= text_height;\n draw_value(measured_exposure, pos);\n\n end_draw();\n glBindTexture(GL_TEXTURE_2D, 0); // unBind 0\n}\n\n" }, { "alpha_fraction": 0.7322834730148315, "alphanum_fraction": 0.7334948778152466, "avg_line_length": 31.372549057006836, "blob_id": "8c0734b7e94a409a635794b70e9482b208494bde", "content_id": "345fc566221febd8a9fa321b7728d0e27d3ddfbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1651, "license_type": "no_license", "max_line_length": 100, "num_lines": 51, "path": "/starcam/fifocommunicator.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//class for reading, interpreting, and executing commands received via a FIFO\n\n#ifndef FIFOCOMMUNICATOR_H\n#define FIFOCOMMUNICATOR_H\n\n#include <string>\n#include <sys/time.h>\n#include \"camconfig.h\"\n#include \"mycam.h\"\n#include \"blobimage.h\"\n\n/**\n\t@author Steve Benton <[email protected]>\n\tthis class is no longer being used. instead use CamCommunicator with a localhost socket\n*/\nclass FIFOCommunicator{\npublic:\n FIFOCommunicator();\n\tFIFOCommunicator(string fifoInName, string fifoOutName);\n\t~FIFOCommunicator();\n\tvoid Init();\n\t\n\tint openFifos(string fifoInName, string fifoOutName);\n\tint closeFifos();\n\t\n\t//main program of communicator: infinite loop that reads commands and executes on global objects\n\tvoid readLoop(string (*interpretFunction)(string));\n\tstring looplessRead();\n\t\n\t//send a return value to the flight computer\n\tint sendReturn(const StarcamReturn* returnStruct);\n\tint sendReturnString(string returnStr);\n\t\n\t//functions for use on \"flight computer\"\n\tstatic StarcamReturn* interpretReturn(string returnString, StarcamReturn* rtn);\n\tint openOppositeFifos(string fifoInName, string fifoOutName);\n\tint sendCommand(string cmd);\n\tint sendCommand(const char* cmd); //in case flight uses C only\n\n\t//accessors\n\tint getErrorFlag() { return m_nErrorFlag; }\n\t\nprivate:\n\tstring m_sFifoInName; //filename of input (from flight) fifo\n\tstring m_sFifoOutName; //filename of output (to flight) fifo\n\tint m_nFifoInFD; //file descriptor for input fifo\n\tint m_nFifoOutFD; //file descriptor for output fifo\n\tint m_nErrorFlag; //will be -1 in case of error, 0 otherwise. check after constructor\n};\n\n#endif\n" }, { "alpha_fraction": 0.6914350390434265, "alphanum_fraction": 0.6937038898468018, "avg_line_length": 26.123077392578125, "blob_id": "9f5d8389c292e55f60cf7d92c1ad607ef35655b9", "content_id": "29674a106fc14f3ef61fdc8635484a48bcb6cc0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1764, "license_type": "no_license", "max_line_length": 118, "num_lines": 65, "path": "/stars/code/solving/matching/solution_fitter.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__MATCHING__SOLUTION_FITTER_H\n#define SOLVING__MATCHING__SOLUTION_FITTER_H\n\n#include <vector>\n#include \"../solution.h\"\n#include \"../star.h\"\n#include \"../blob.h\"\n#include \"../../shared/image/raw.h\"\n\nnamespace levmar_solution_fitter\n{\n\nstruct additional_data\n{\n double* star_data;\n double* weights;\n bool using_weights;\n bool flipped_coordinate_system;\n bool platescale_fixed;\n};\n\n}\n\nnamespace Solving\n{\n namespace PatternMatching\n {\n class SolutionFitter;\n }\n}\n\nclass Solving::PatternMatching::SolutionFitter\n{\n public:\n SolutionFitter();\n ~SolutionFitter();\n double get_error(int num_params, double dec);\n double get_fit_error(double* blob_measurements, double* blob_fit_positions, int num_measurements, int num_params);\n void init_params(double blobs[], double stars[], bool platescale_fixed, bool horizontal);\n void fit_helper(std::vector<Blob>& blobs, std::vector<Star>& stars,\n Solution& solution, Shared::Image::Raw& image, bool platescale_fixed, bool do_horizontal);\n void fill_star_ccd_positions(std::vector<Star>& stars, Solution& solution,\n Shared::Image::Raw& image);\n void fit(std::vector<Blob>& blobs, std::vector<Star>& stars, Solution& solution,\n Shared::Image::Raw& image, bool final_pass=false);\n\n private:\n unsigned int max_num_blobs;\n double* workspace;\n double* covar;\n levmar_solution_fitter::additional_data adata;\n double* blob_measurements;\n double* blob_fit_positions;\n double* params;\n double* info;\n};\n\n#endif\n" }, { "alpha_fraction": 0.7477954030036926, "alphanum_fraction": 0.7513227462768555, "avg_line_length": 23.65217399597168, "blob_id": "cf2f714ad4fe7657ba4541d6e294832d1527cbe5", "content_id": "24a42f38281e31b4e2cafe13f1c8431a4733ab25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1135, "license_type": "no_license", "max_line_length": 73, "num_lines": 46, "path": "/stars/code/displaying/solving_filters.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__SOLVING_FILTERS_H\n#define DISPLAYING__SOLVING_FILTERS_H\n\n#include \"block.h\"\n\nnamespace Displaying\n{\n class SolvingFilters;\n}\n\nclass Displaying::SolvingFilters: public Block\n{\n public:\n SolvingFilters();\n void update();\n void draw(Position& position);\n\n private:\n DynamicValue horizontal_location_enabled;\n DynamicValue horizontal_location_radius;\n DynamicValue horizontal_location_az;\n DynamicValue horizontal_location_el;\n\n DynamicValue horizontal_roll_limit_enabled;\n DynamicValue horizontal_roll_limit_min;\n DynamicValue horizontal_roll_limit_max;\n\n DynamicValue horizontal_el_limit_enabled;\n DynamicValue horizontal_el_limit_min;\n DynamicValue horizontal_el_limit_max;\n\n DynamicValue equatorial_location_enabled;\n DynamicValue equatorial_location_radius;\n DynamicValue equatorial_location_ra;\n DynamicValue equatorial_location_dec;\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.7462349534034729, "alphanum_fraction": 0.7507529854774475, "avg_line_length": 34.89189147949219, "blob_id": "3eda0cb81c57754461b333c7044412f23b426216", "content_id": "3896ddb25de28c960be8fe0b0279fae04f692e15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1328, "license_type": "no_license", "max_line_length": 94, "num_lines": 37, "path": "/starcam/clensadapterdefs.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#ifndef CLENSADAPTERDEFS_H\n#define CLENSADAPTERDEFS_H\n\n#define RM_VERBOSE_MODE 1\n#define RM_NONVERBOSE_MODE 0\n\ntypedef enum { \n\t//interface and hardware commands\n\tLC_NULL, \n\tLC_IDENTIFY_LENS, LC_HARDWARE_VERSION, LC_SET_BAUD_RATE, LC_BAUD_STORE, LC_SET_RESPONSE_MODE,\n\tLC_XMODEM, LC_SERIAL_NUMBER, LC_VERSION_NUM, LC_VERSION_STR, LC_LIBRARY_VERSION,\n\t\n\t//focus commands\n\tLC_MOVE_FOCUS_INFINITY, LC_MOVE_FOCUS_ZERO, LC_MOVE_FOCUS_ABS, LC_MOVE_FOCUS_INC, \n\tLC_GET_FOCUS_POSITION, LC_GET_FOCUS_DISTANCE, LC_SET_FOCUS_COUNTER, LC_DEFINE_ZOOM,\n\t\n\t//aperture commands\n\tLC_INITIALIZE, LC_DEFINE_APERTURE_AXIS, LC_MOVE_APERTURE_OPEN, LC_MOVE_APERTURE_CLOSED,\n\tLC_MOVE_APERTURE_ABS, LC_MOVE_APERTURE_INC, LC_GET_APERTURE_POSITION, \n\t\n\t//unknown and not-implemented commands\n\tLC_IMAGE_STABILIZATION, LC_DEFINE_FOCUS_AXIS\n\n} LENS_COMMAND; //lens adapter commands\n\ntypedef enum {\n\t//errors affiliated with the interface\n\tLE_PARSE_ERROR=1, LE_MANUAL_FOCUS, LE_NO_LENS, LE_DISTANCE_NOT_AVAIL, \n\tLE_NOT_INITIALIZED, LE_INVALID_BAUD, LE_NO_SHUTTER, LE_INSUFFICIENT_POWER, \n\tLE_INVALID_LIBRARY,LE_COMMUNICATION_ERROR,\n\t\n\t//errors used by this class\n\tLE_NO_ERROR = 0, LE_BAD_PARAM = 11, LE_CONNECTION_ERROR, LE_TIMEOUT, LE_AUTOFOCUS_ERROR\n\t\n} LENS_ERROR; //possible error values returned by the lens adapter\n\n#endif //CLENSADAPTERDEFS_H\n" }, { "alpha_fraction": 0.5251242518424988, "alphanum_fraction": 0.5494202375411987, "avg_line_length": 20.559524536132812, "blob_id": "67bf1bf5e3f2f99f02bc246dc408f2095beef0c0", "content_id": "e24e1b91dd4e9e058a4ed616891323f6608138d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1811, "license_type": "no_license", "max_line_length": 63, "num_lines": 84, "path": "/blastd/tdrsssim.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <termios.h>\n#include <time.h>\n#include <syslog.h>\n#include <sys/ioctl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n\n#define OUTPUT_TTY \"/dev/ttyS5\"\n#define DAEMON \"tdrsssim\"\nunsigned short simbuf[1024];\n\n//-------------------------------------------------------------\n//\n// OpenSerial: open serial port\n//\n//-------------------------------------------------------------\n\nint OpenSerial(char* device) {\n int fd;\n struct termios term;\n\n if ((fd = open(device, O_RDWR)) < 0) {\n printf(\"Unable to open serial port.\\n\");\n exit(1);\n }\n if (tcgetattr(fd, &term)) {\n printf(\"Unable to get serial device attributes.\");\n return -1;\n }\n\n term.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);\n term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);\n term.c_iflag |= INPCK;\n term.c_cc[VMIN] = 0;\n term.c_cc[VTIME] = 0;\n\n term.c_cflag &= ~(CSTOPB | CSIZE);\n term.c_oflag &= ~(OPOST);\n term.c_cflag |= CS8;\n\n if (cfsetospeed(&term, B19200)) { // Baud\n printf(\"Error setting serial output speed.\");\n return -1;\n }\n if (cfsetispeed(&term, B19200)) { // Baud\n printf(\"Error setting serial output speed.\");\n return -1;\n }\n if(tcsetattr(fd, TCSANOW, &term)) {\n printf(\"Unable to set serial attributes.\");\n return -1;\n }\n\n printf(\"%s: %s : %d open\\n\", DAEMON, device, fd);\n return fd;\n}\n\n\nint main(void)\n{\n int idx;\n int fd;\n int written;\n\n if ( (fd = OpenSerial(OUTPUT_TTY)) < 0 ) return 0; \n \n simbuf[0] = 0xeb90;\n for(idx = 2; idx < 1024; idx++) {\n simbuf[idx] = idx-2;\n }\n\n for(idx = 0;;) {\n simbuf[1] = idx++;\n written = write(fd, simbuf, 1024*sizeof(short)); \n printf(\"writing data %d - written %d\\n\", idx, written);\n sleep(3);\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5462897419929504, "alphanum_fraction": 0.565371036529541, "avg_line_length": 24.118343353271484, "blob_id": "d7b63c3b88e48ffde3e29cd60fb5cdf7cb804236", "content_id": "dd09ca64d111963166e50c2fbc465b798f383368", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4245, "license_type": "no_license", "max_line_length": 151, "num_lines": 169, "path": "/rove/rove.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <termios.h>\n#include <time.h>\n#include <syslog.h>\n#include <sys/ioctl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n\n#include <math.h>\n#include <string.h>\n#include <ctype.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <netdb.h>\n\n#define LINKFILE \"/data/etc/highgain.lnk\"\n#define RAWDIR \"/data/rawdir\"\n\n#define RNC_PORT 41114\n#define TIMEOUT 30\n\n\n#define BUFSIZE 8194\n\nvoid Usage() {\n fprintf(stderr, \"rove: collect data from a remote rnc server, and make it availible for a local rnc server.\\n\"\n \" usage: rove <remoteserver1> [<remoteserver1> [...]]\\n\");\n exit(0);\n}\n\n//*********************************************************\n// connect to the political party server\n//*********************************************************\nint party_connect(const char *hostname, int port) {\n int s;\n struct sockaddr_in sn;\n struct hostent *hostinfo;\n struct servent *sp;\n struct servent sp_real;\n int on =1 ;\n\n sp = &sp_real;\n sp->s_port = htons(port);\n\n sn.sin_family = AF_INET;\n sn.sin_port = sp->s_port;\n\n if(!inet_aton(hostname, &sn.sin_addr)) {\n hostinfo = gethostbyname(hostname);\n if (hostinfo == NULL) {\n herror(hostname);\n exit(1);\n }\n sn.sin_addr = *(struct in_addr *) hostinfo->h_addr;\n }\n\n /* Create the socket. */\n if ( (s = socket (AF_INET, SOCK_STREAM, 0)) < 0 ) {\n perror(\"socket\");\n exit(1);\n }\n /* set socket options */\n (void) setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));\n\n if (connect(s, (struct sockaddr *)&sn, sizeof (sn)) < 0) {\n perror(\"socket\");\n }\n\n return s;\n}\n\n\nint main(int argc, char *argv[]) {\n char remote_server[2][256];\n int port[2];\n int n_servers;\n char out_filename[256];\n char inbuf[BUFSIZE];\n \n int tty_fd;\n int out_fd;\n int numin, numread, totalread = 0;\n time_t t, last_t = 0;\n int blockread = 0;\n int i_server = 0;\n int i_ch;\n\n time_t t_r, t_lr;\n \n t_lr = time(NULL);\n\n n_servers = argc-1;\n \n if (argc<2) Usage();\n n_servers = argc-1;\n \n for (i_server=0; i_server<n_servers; i_server++) {\n if (argv[i_server+1][0]=='-') Usage();\n for (i_ch = 0; (argv[i_server+1][i_ch] != '\\0') && (argv[i_server+1][i_ch] != ':'); i_ch++) {\n remote_server[i_server][i_ch] = argv[i_server+1][i_ch];\n }\n remote_server[i_server][i_ch] = '\\0';\n if (argv[i_server+1][i_ch] == ':') {\n port[i_server] = atoi(argv[i_server+1]+i_ch+1);\n } else {\n port[i_server] = RNC_PORT;\n }\n //strncpy(remote_server[i_server], argv[i_server+1], 254);\n }\n\n for (i_server=0; i_server<n_servers; i_server++) {\n printf(\"Using host: %s port: %d\\n\", remote_server[i_server], port[i_server]);\n }\n\n i_server = 0;\n \n sprintf(out_filename, \"%s/%lu.highgain\", RAWDIR, time(NULL));\n if( (out_fd = open(out_filename, O_WRONLY | O_CREAT, 00644)) < 0 ) {\n syslog(LOG_ERR | LOG_DAEMON, \"Error opening data file\\n\");\n fprintf(stderr, \"Error opening data file %s\\n\", out_filename);\n exit(0);\n }\n \n unlink(LINKFILE);\n if (symlink(out_filename, LINKFILE)<0) {\n fprintf(stderr, \"rove: could not create link from `%s' to `%s'\",\n out_filename, LINKFILE);\n exit(0);\n }\n\n tty_fd = party_connect(remote_server[i_server], port[i_server]);\n \n while (1) {\n ioctl(tty_fd, FIONREAD, &numin);\n if (numin>BUFSIZE-2) numin = BUFSIZE-2;\n \n if (numin>64) {\n numread = read(tty_fd, inbuf, numin);\n write(out_fd, inbuf, numread);\n totalread += numread;\n blockread += numread;\n t_lr = time(NULL);\n } else {\n t_r = time(NULL);\n if ((t_r -t_lr) > TIMEOUT) {\n printf(\"No data for %us. Resetting connection.\\n\", t_r-t_lr);\n t_lr = t_r;\n shutdown(tty_fd, SHUT_RDWR);\n i_server++;\n if (i_server>=n_servers) i_server = 0;\n tty_fd = party_connect(remote_server[i_server], port[i_server]);\n } \n usleep(30000);\n }\n t = time(NULL);\n \n if (t-last_t > 10) {\n printf(\"Host %s:%d %7d bytes at %.0f bps at %s\", remote_server[i_server],port[i_server], totalread, (double)blockread*8.0/(t-last_t), ctime(&t));\n last_t = t;\n blockread = 0;\n }\n }\n \n exit(0);\n}\n" }, { "alpha_fraction": 0.5626134276390076, "alphanum_fraction": 0.5767291784286499, "avg_line_length": 27.5, "blob_id": "0b0dc583013b46471e20bc7c7219aa8316414105", "content_id": "374c2b18f945ca3788f3b551a22552c0ed6e123b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4959, "license_type": "no_license", "max_line_length": 116, "num_lines": 174, "path": "/groundhog/bit/main.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <math.h>\n#include <arpa/inet.h> // socket stuff\n#include <netinet/in.h> // socket stuff\n#include <sys/types.h> // socket types\n#include <sys/socket.h> // socket stuff\n#include <sys/stat.h>\n#include <dirent.h>\n#include <unistd.h>\n#include <signal.h>\n#include <string.h>\n#include <pthread.h> // threads\n#include <float.h>\n#include <ctype.h>\n\n#include \"groundhog.h\"\n#include \"linklist_connect.h\"\n\nstruct TlmReport ll_report[MAX_NUM_LINKLIST_FILES+1] = {{0}};\n\nchar * cmdfile = \"/data/etc/bit_config/cmdlist.bit\";\nchar * telemfile = \"/data/etc/bit_config/telemlist.bit\";\nchar * calspecfile = \"/data/etc/bit_config/calspecs.bit\";\nchar * linklistdir = \"/data/etc/bit_config/linklists/\";\n\nvoid groundhog_write_calspecs(char * fname) {\n FILE * fin = fopen(calspecfile, \"r\");\n if (!fin) return;\n\n FILE * fout = fopen(fname, \"w\");\n if (!fout) {\n groundhog_warn(\"Unable to open calspecs file %s\\n\", fname);\n fclose(fin);\n return;\n }\n\n char *line = NULL;\n size_t len = 0;\n int began = 0;\n\n while (getline(&line, &len, fin) != -1) {\n if (!strncmp(line, \"END\", 3)) {\n break;\n }\n if (began) {\n fprintf(fout, \"%s\", line); \n } else if (!strncmp(line, \"BEGIN\", 5)) {\n began = 1;\n }\n }\n fclose(fin);\n fclose(fout);\n}\n\nint main(int argc, char * argv[]) {\n // set the directory in which to save raw linklist files received from the payload\n sprintf(archive_dir, \"/data/groundhog\");\n\n // initialize the main telemetry superframe\n\n // load command list from text file\n if (parse_cmdlist(cmdfile) < 0) {\n groundhog_fatal(\"Command parser error\\n\");\n }\n // load telemetry list from text file\n if (parse_telemlist(telemfile, \"superframe.txt\") < 0) {\n groundhog_fatal(\"Telemetry parser error\\n\");\n }\n \n // initialize the linklists derived from the superframe\n linklist_t ** ll_list = calloc(MAX_NUM_LINKLIST_FILES, sizeof(linklist_t *));\n char *exts[] = {\".bit\",\".ll\",\"\"};\n\tif (load_all_linklists_opt(superframe, linklistdir, ll_list, LL_AUTO_FLOAT_COMP | LL_INCLUDE_ALLFRAME, exts) < 0) {\n groundhog_fatal(\"Unable to load linklists\\n\");\n }\n linklist_generate_lookup(ll_list); \n \n int pilot_on = 1;\n int bi0_on = 1;\n int highrate_on = 1;\n int daemon = 0;\n verbose = 0;\n\n for (int i = 1; i < argc; i++) {\n if (strcmp(argv[i], \"-no_pilot\") == 0) pilot_on = 0;\n else if (strcmp(argv[i], \"-no_bi0\") == 0) bi0_on = 0;\n else if (strcmp(argv[i], \"-no_highrate\") == 0) highrate_on = 0;\n else if (strcmp(argv[i], \"-pilot_only\") == 0) bi0_on = highrate_on = 0;\n else if (strcmp(argv[i], \"-bi0_only\") == 0) highrate_on = pilot_on = 0;\n else if (strcmp(argv[i], \"-highrate_only\") == 0) pilot_on = bi0_on = 0;\n else if (strcmp(argv[i], \"-d\") == 0) daemon = 1;\n else if (strcmp(argv[i], \"-quiet\") == 0) verbose = 0;\n else if (strcmp(argv[i], \"-verbose\") == 0) verbose = 1;\n else {\n groundhog_warn(\"Unrecognized option \\\"%s\\\"\", argv[i]);\n exit(1);\n }\n }\n\n if (daemon) {\n daemonize();\n }\n\n pthread_t server_thread;\n pthread_t pilot_receive_worker;\n pthread_t biphase_receive_worker;\n\n struct UDPSetup pilot_setup = {\"Pilot\", \n GND_IP, \n GND_TELEM_PORT, \n superframe->size, \n PILOT_PKT_SIZE,\n 0};\n\n // start the server thread for mole clients\n pthread_create(&server_thread, NULL, (void *) &linklist_server, NULL);\n\n if (pilot_on) {\n pthread_create(&pilot_receive_worker, NULL, (void *) &udp_receive, (void *) &pilot_setup);\n }\n\n if (bi0_on) {\n // pthread_create(&biphase_receive_worker, NULL, (void *) &biphase_receive, NULL);\n }\n\n char fn_str[1024] = \"\";\n int len = 0, prev_len = 0;\n int update_freq = 20;\n int stale_ticks = 60;\n char * report_types[] = {\n BLU, // pilot\n GRN, // bi0\n YLW, // highrate\n RED // sbd\n };\n\n // print out the reports\n while (true) {\n int i;\n fn_str[0] = '\\0';\n for (i=0; ll_report[i].ll; i++) {\n if (ll_report[i].prev_framenum != ll_report[i].framenum) {\n ll_report[i].stale = 0;\n } else {\n ll_report[i].stale++;\n }\n ll_report[i].prev_framenum = ll_report[i].framenum;\n\n if (ll_report[i].stale > stale_ticks) continue;\n\n\t\t\tsprintf(fn_str, \"%s %s %s %s [%\" PRIu64 \"];\" NOR, \n fn_str, \n report_types[ll_report[i].type],\n\t\t\t\t\t\t\tll_report[i].ll->name, \n\t\t\t\t\t\t\t(ll_report[i].allframe) ? \"AF\" : \" \",\n\t\t\t\t\t\t\tll_report[i].framenum\n\t\t\t);\n }\n // print enough characters to overwrite the previous line\n len = strlen(fn_str);\n for (int i = len; i < prev_len; i++) fn_str[i] = ' ';\n fn_str[(len > prev_len) ? len : prev_len] = '\\0'; // terminate\n prev_len = len;\n\n fprintf(stdout, \"%s\\r\", fn_str);\n fflush(stdout); \n\n usleep(1000000/update_freq);\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.711904764175415, "alphanum_fraction": 0.7198412418365479, "avg_line_length": 27.636363983154297, "blob_id": "ada641b2f4c727738ab024180741531fa2d68699", "content_id": "ec48d51a58fdd2f5291ce96b700348a1cd655799", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1260, "license_type": "no_license", "max_line_length": 78, "num_lines": 44, "path": "/common/include/mcp_sched.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* mcp: the Spider master control program\n *\n * This software is copyright (C) 2002-2013 D. V. Wiebe and others\n *\n * This file is part of pcm.\n *\n * mcp 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp 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 mcp; if not, write to the Free Software Foundation, Inc.,\n */\n#include \"netcmd.h\"\n\n#ifndef MCP_SCHED_H\n#define MCP_SCHED_H\n\n/* This structure is now also used by the MCE command passthrough. Be careful\n * when modifying it.\n */\nstruct ScheduleEvent {\n int t;\n int is_multi;\n int command;\n int done; /* MCEserv only; not used by scheduler */\n double rvalues[MAX_N_PARAMS];\n int ivalues[MAX_N_PARAMS];\n char svalues[MAX_N_PARAMS][CMD_STRING_LEN];\n};\n\nstruct ScheduleType {\n int n_sched;\n time_t t0;\n struct ScheduleEvent* event;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6900212168693542, "alphanum_fraction": 0.6928520798683167, "avg_line_length": 21.428571701049805, "blob_id": "221764711d22dfbcd2e8655e8256850e512238c4", "content_id": "9df2acb3cc93b3dc7ca6596f879a4952e30e7f99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1414, "license_type": "no_license", "max_line_length": 88, "num_lines": 63, "path": "/stars/code/networking/image_client.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef NETWORKING__IMAGE_CLIENT_H\n#define NETWORKING__IMAGE_CLIENT_H\n\n#include <string>\n#include <boost/asio.hpp>\n#include \"ebex_images.h\"\n\nnamespace Shared\n{\n namespace Image\n {\n class Raw;\n }\n namespace Network\n {\n class ImageClientSettings;\n }\n}\n\nnamespace Logging\n{\n class Logger;\n}\n\nnamespace NetworkingImageClient\n{\n class ImageClient;\n}\n\nclass NetworkingImageClient::ImageClient\n{\n public:\n ImageClient(boost::asio::io_service& io_service, int which_fc);\n ~ImageClient();\n\n private:\n void write_image(boost::asio::io_service& io_service);\n void write_exposure();\n void handle_write(const boost::system::error_code& error, size_t bytes_transferred);\n void handle_read(const boost::system::error_code& error, size_t bytes_transferred);\n\n boost::asio::ip::tcp::socket socket;\n boost::asio::deadline_timer read_timer;\n ebex_images_header_t* header;\n ebex_images_result_t read_buffer;\n\n std::string server_ip;\n Shared::Image::Raw* shared_image;\n Shared::Network::ImageClientSettings* shared_settings;\n Logging::Logger* logger;\n int counter_stars;\n size_t data_size;\n unsigned int current_exposure;\n};\n\n#endif\n" }, { "alpha_fraction": 0.7037718296051025, "alphanum_fraction": 0.7295308113098145, "avg_line_length": 32.96875, "blob_id": "1e0885168577bd158f08385a85be08d1c8335a75", "content_id": "5254fb6fb892ab367b43571c60b5900bbc9c7de7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1087, "license_type": "no_license", "max_line_length": 77, "num_lines": 32, "path": "/defricher/defricher_netreader.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * defricher_netreader.h: \n *\n * This software is copyright (C) 2013-2014 Seth Hillbrand\n *\n * This file is part of defricher, created for the BLASTPol Project.\n *\n * defricher 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 2 of the License, or\n * (at your option) any later version.\n *\n * defricher 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 defricher; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Apr 6, 2015 by Seth Hillbrand\n */\n\n#ifndef DEFRICHER_NETREADER_H_\n#define DEFRICHER_NETREADER_H_\n\npthread_t netreader_init(const char *m_host, void *m_telemetry);\n\n\n#endif /* DEFRICHER_NETREADER_H_ */\n" }, { "alpha_fraction": 0.5306432247161865, "alphanum_fraction": 0.5596951842308044, "avg_line_length": 27.77983283996582, "blob_id": "00f554f6446828d52ad137bac83755b9ad13fb06", "content_id": "20c373f2ef804fe152ef5c3b3b9aa95623fb011a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 34249, "license_type": "no_license", "max_line_length": 186, "num_lines": 1190, "path": "/starcam/pyramid.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* pyramid.cc: PYRAMID is\n * an implementation of \n * D. Mortari, et al., \"the PYRAMID star identification Techinque\"\n *\n * This file is copyright (C) 2006 E. Pascale \n *\n * PYRAMID 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 2 of the License, or\n * (at your option) any later version.\n *\n * PYRAMID 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 The Deacon; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include <iostream>\n#include <fstream>\n#include <list>\n#include <math.h>\n#include <time.h>\n#include <stdlib.h> \n#include <string.h>\n#include \"pyramid.h\"\n#include \"svd.h\"\n#include \"stdint.h\"\n\nusing namespace std;\n\n//flag to activate display of debugging information\n#define PYRAMID_DEBUG 0\n\n//comparison function for sorting pointers to gsc_t (first by dec, then by ra)\n// static int decl_sort(const void *x, const void *y)\n// {\n// gsc_t *gsc_0 = (gsc_t *)x;\n// gsc_t *gsc_1 = (gsc_t *)y;\n// \n// int retval;\n// \n// if(gsc_0->dec < gsc_1->dec) {\n// retval = -1;\n// } else if(gsc_0->dec > gsc_1->dec) {\n// retval = 1;\n// } else if(gsc_0->ra <= gsc_1->ra) {\n// retval = -1;\n// } else retval = 1;\n// \n// return retval;\n// }\n\n//comparison function for sorting pointers to rec_t by distance (d)\nstatic int dist_sort(const void *x, const void *y)\n{\n rec_t *r0 = (rec_t *)x;\n rec_t *r1 = (rec_t *)y;\n\n if(r0->d <= r1->d) return -1;\n return 1;\n}\n\n//comparison function for sorting pointers of type rec_t by I (catalog index of first member of pair?)\nstatic int rec_I_sort(const void *x, const void *y)\n{\n rec_t *r0 = (rec_t *)x;\n rec_t *r1 = (rec_t *)y;\n\n if(r0->I < r1->I) return -1;\n if(r0->I == r1->I) return 0;\n return 1;\n}\n\n//comparison function for sorting pointers of type rec_t by J (catalog index of second member of pair?)\nstatic int rec_J_sort(const void *x, const void *y)\n{\n rec_t *r0 = (rec_t *)x;\n rec_t *r1 = (rec_t *)y;\n\n if(r0->J < r1->J) return -1;\n if(r0->J == r1->J) return 0;\n return 1;\n}\n\n//comparison function between pointer to unsigned int (x) and to I member of pointer to rect_t (y)\nstatic int I_match(const void *x, const void *y)\n{\n const uint32_t *I0 = (uint32_t *)x;\n const rec_t *r1 = (rec_t *)y;\n return (*I0 > r1->I) - (*I0 < r1->I);\n}\n//comparison function between pointer to unsigned int (x) and to J member of pointer to rect_t (y)\nstatic int J_match(const void *x, const void *y)\n{\n const uint32_t *I0 = (uint32_t *)x;\n const rec_t *r1 = (rec_t *)y;\n return (*I0 > r1->J) - (*I0 < r1->J);\n}\n\n/* Perform a binary search for KEY in BASE which has NMEMB elements\n of SIZE bytes each. The comparisons are done by (*COMPAR)(). */\nvoid *\npbsearch (const void *key, const void *base, size_t nmemb, size_t size,\n int (*compar) (const void *, const void *))\n{\n size_t l, u, idx;\n const void *p;\n int comparison;\n\n l = 0;\n u = nmemb;\n while (l < u)\n {\n idx = (l + u) / 2;\n p = (void *) (((const char *) base) + (idx * size));\n comparison = (*compar) (key, p);\n if (comparison < 0)\n u = idx;\n else if (comparison > 0)\n l = idx + 1;\n else {\n do {\n if(idx == 0) return (void *)p;\n p = (void *) (((const char *) base) + (--idx * size));\n } while((*compar) (key, p) == 0);\n p = (void *) (((const char *) base) + (++idx * size));\n return (void *) p;\n }\n }\n\n return NULL;\n}\n\n//default constructor: must call Init before using the object\nPyramid::Pyramid()\n{\n\tngsc = nrec = nsolution = 0;\n\tgsc = NULL;\n\trec = NULL;\n\tsolution = NULL;\n\tcatalog = katalog = (char *)\"\";\n}\n/* alternate constructor: calls Init\n must specify fov (longest of length or width in radians of sky)\n catalogname (star catalog filename)\n katalogname (catalogue of star pairs & distances (?))\n*/\nPyramid::Pyramid(double fov, const char *catalogname, const char *katalogname)\n{\n\tgsc = NULL;\n\trec = NULL;\n\tsolution = NULL;\n\tInit(fov, catalogname, katalogname);\n}\n\nvoid Pyramid::Init(double fov, const char *catalogname, const char *katalogname)\n{\n uint32_t k;\n this->fov = fov;\n this->c_fov = cos(this->fov);\n\n this->catalog = (char *)catalogname;\n this->katalog = (char *)katalogname;\n\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: opening file: \" << this->catalog << endl;\n#endif\n ifstream file(this->catalog, ios::in|ios::binary);\n \n if(!file.is_open()) {\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: unable to open file catalog \" << this->catalog << endl;\n#endif\n exit(0);\n }\n\n file.read ((char *)&ngsc, sizeof(ngsc));\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: reading star catalogue data, ngsc = \" << ngsc << endl;\n#endif\n if (gsc) delete[] gsc; gsc = new gsc_t[ngsc]; \n\n for(k = 0; k < ngsc; k++) {\n file.read((char *)&gsc[k].ra, sizeof(gsc[k].ra));\n file.read((char *)&gsc[k].dec, sizeof(gsc[k].dec));\n file.read((char *)&gsc[k].mag, sizeof(gsc[k].mag));\n }\n file.close(); \n \n // load kvector catalog\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: opening file: \" << this->katalog << endl;\n#endif\n file.open(this->katalog, ios::in|ios::binary);\n \n if(!file.is_open()) {\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: unable to open file catalog \" << this->katalog << endl;\n#endif\n exit(0);\n }\n \n file.read ((char *)&this->m, sizeof(double));\n file.read ((char *)&this->q, sizeof(double));\n file.read ((char *)&this->nrec, sizeof(uint32_t));\n\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: reading k-vector catalog, nrec = \" << this->nrec << endl;\n#endif\n \n if (rec) delete[] rec; rec = new rec_t[this->nrec];\n \n for(k = 0; k < this->nrec; k++) {\n file.read((char *)&rec[k].I, sizeof(rec[k].I));\n file.read((char *)&rec[k].J, sizeof(rec[k].J));\n file.read((char *)&rec[k].K, sizeof(rec[k].K));\n file.read((char *)&rec[k].d, sizeof(rec[k].d));\n }\n\n file.close();\n\n if (solution) delete[] solution; solution = NULL;\n nsolution = 0;\n return;\n}\n\n//destructor: unallocates arrays\nPyramid::~Pyramid()\n{\n ngsc = 0;\n if (gsc) delete[] gsc;\n\n nrec = 0;\n if(rec) delete[] rec;\n\n nsolution = 0;\n if(solution) delete[] solution;\n}\n\n//finds the distance between two points with (RA, dec) in radians of (a0, d0) and (a1, d1)\n//this distance is the cosine of the great-circle distance separating the points\ndouble Pyramid::dist(double& a0, double& a1, double& d0, double& d1)\n{\n double temp;\n\n temp = cos(a0-a1);\n temp *= cos(d0)*cos(d1);\n temp += sin(d0)*sin(d1);\n \n return temp;\n}\n\n\n//finds (cosine of) distance between two tangent plane points\n// Note: I cannot use tangent plane coordinates to calculate the inter-star\n// distances; dicrepancies are order of 20\" on 3.4 deg fov\ndouble Pyramid::cdist(double& x0, double& x1, double& y0, double& y1){\n double temp;\n double denom;\n\n denom = x0*x0 + y0*y0 + 1.0;\n denom *= x1*x1 + y1*y1 + 1.0;\n\n temp = (x0*x1 + y0*y1 + 1.0);\n temp /= sqrt(denom);\n\n return temp;\n}\n\n//a small number that is used to avoid division by zero errors (smaller denominators are assigned +/- this)\n#define SMALLNUMBER 1.0E-9\n//next two functions convert between spherical coordinates (ra, dec) and tangent plane coordinates (x, y)\n//(raz, decz) is the location of the tangent point in spherical coordinates\n//s2tp returns a status code depending on what denominator rounding might have been necessary\nint Pyramid::s2tp(double ra, double dec, double raz, double decz, double& x, double& y)\n{\n double sdecz, sdec, cdecz, cdec, radif, sradif, cradif, denom;\n int retval;\n \n // Trig functions \n sdecz = sin(decz);\n sdec = sin(dec);\n cdecz = cos(decz);\n cdec = cos(dec);\n radif = ra - raz;\n sradif = sin(radif);\n cradif = cos(radif);\n \n // Reciprocal of star vector length to tangent plane \n denom = sdec * sdecz + cdec * cdecz * cradif;\n\n // Handle vectors too far from axis \n if (denom > SMALLNUMBER) {\n retval = 0;\n } else if (denom >= 0.0) {\n retval = 1;\n denom = SMALLNUMBER;\n } else if (denom > -SMALLNUMBER) {\n retval = 2;\n denom = -SMALLNUMBER;\n } else {\n retval = 3;\n }\n \n // Compute tangent plane coordinates (even in dubious cases) \n x = cdec * sradif / denom;\n y = (sdec * cdecz - cdec * sdecz * cradif) / denom;\n\n return retval;\n}\n\nvoid Pyramid::tp2s(double& ra, double& dec, double raz, double decz, double x, double y)\n{\n double sdecz, cdecz, denom, radif;\n\n sdecz = sin(decz);\n cdecz = cos(decz);\n\n denom = cdecz - y * sdecz;\n radif = atan2(x, denom);\n\n ra = radif + raz;\n dec = atan2(sdecz + y*cdecz, sqrt (x*x + denom*denom));\n}\n#undef SMALLNUMBER\n\n\n//maximum number of records allowed in the star pair & distance catalogue\n#define MAXREC 8000000UL\n//builds catalogue of star pairs within distance (on sphere) r0 of point (ra0, dec0) and closer together than fov\n//all positions and distances are in radians\n//returns -1 on error, 0 otherwise\n//(? this description is a guess, the function originally apperaed to create the inverse of the above set)\nint Pyramid::BuildCatalog(double ra0, double dec0, double r0)\n{\n uint32_t i, i0, i1; \n uint32_t j; \n double dec_min, dec_max;\n double d;\n double c_r0;\n\n c_r0 = cos(r0);\n \n rec_t *rec_ = new rec_t [MAXREC]; \n nrec = 0;\n \n //find suitable declination range to search in\n dec_max = dec0 + 0.5*r0;\n dec_min = dec0 - 0.5*r0;\n if(dec_max > M_PI_2) {\n dec_max = M_PI_2;\n dec_min = dec_max - r0;\n } else if(dec_min < -M_PI_2) {\n dec_min = -M_PI_2;\n dec_max = dec_min + r0;\n }\n\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid degub]: cataloguing for dec between \" << dec_min*180.0/M_PI << \" and \" << dec_max*180./M_PI << endl;\n#endif\n\n //find catalogue indexes corresponding to this declination range (requires catalogue sorted by dec)\n i0 = 0;\n while(gsc[i0].dec < dec_min) \n if(++i0 == ngsc) break;\n \n i1 = i0;\n while(gsc[i1].dec <= dec_max) \n if(++i1 == ngsc) break;\n\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: building distances catalog\" << endl;\n#endif\n for(i = i0; i < i1-1; i++) {\n //if the star is further than r0 from (ra0, dec0) then ignore is\n d = dist(gsc[i].ra, ra0, gsc[i].dec, dec0);\n if(d > c_r0) continue; //I (steve) have switched this inequality\n\n //otherwise, look at all higher index stars (suitable lower index ones would already have matched this one)\n for(j = i+1; j < i1; j++) {\n\n //if the higher index star is within fov of the original, add it to the distances catalogue\n d = dist(gsc[i].ra, gsc[j].ra, gsc[i].dec, gsc[j].dec);\n if(d < c_fov) { //I (steve) have switched this inequality\n if(i < j) { //shouldn't this always be true inside this for loop?\n rec_[nrec].I = i;\n rec_[nrec].J = j;\n } else {\n rec_[nrec].I = j;\n rec_[nrec].J = i;\n }\n rec_[nrec].d = d;\n if(++nrec == MAXREC) {\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: too many star pairs\" << endl;\n#endif\n delete[] rec_;\n return -1;\n }\n } else {\n //once the declinations are separated by more than fov, no point in searching further\n if(cos(gsc[i].dec - gsc[j].dec) > c_fov) //I (steve) have switched this inequality\n break;\n }\n }\n }\n\n //copy the created catalogue to the class member variable and sort it by increasing distance\n if(rec != NULL) delete[] rec;\n rec = new rec_t [nrec];\n memcpy(rec, rec_, nrec*sizeof(rec_t));\n delete[] rec_;\n \n qsort((void *)rec, nrec, sizeof(*rec), dist_sort);\n \n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: distance catalog has \" << nrec << \" elemenst\" << endl;\n#endif\n\n // Now build K vector\n //TODO I don't know what this is for...it seems like some relation between actual trend and a linear approximation\n this->m = (rec[nrec-1].d - rec[0].d + 2*CSI) / (double)(nrec - 1);\n this->q = rec[0].d - this->m - CSI;\n\n rec[0].K = 0;\n for(i = 1, j=0; i < nrec-1; i++) {\n while( ((rec[j].d > (m*(i+1) + q)) || (rec[j+1].d <= (m*(i+1) + q))) && j < nrec ) j++;\n rec[i].K = j;\n }\n rec[nrec-1].K = nrec-1;\n\n return 0;\n}\n#undef MAXREC\n\n\n//maximum number of stars to find in GetTestStars function\n//finds the catalogue index (id) and coordinates (xx and yy) in the tagnet plane centered at ra0, dec0\n//of up to n stars within half fov from tangent point (id, xx, and yy must be at least n elements long)\n//when less than n stars are found, randomly chooses which ones to save, returns the number of stars returned\n#define MAXSTARS 10000\nint Pyramid::GetTestStars(double ra0, double dec0,\n double *xx, double *yy, \n uint32_t *id,\n uint32_t n)\n{\n double c_fov_2;\n int star[MAXSTARS];\n\n uint32_t nstar;\n uint32_t star_idx;\n uint32_t k;\n \n c_fov_2 = cos(0.5*fov); //I (steve) changed acos(c_fov) to simply fov\n for(k = 0, nstar = 0; k < ngsc; k++) {\n if(dist(ra0, gsc[k].ra, dec0, gsc[k].dec) < c_fov_2) { //I (steve) switched this inequality\n star[nstar] = k;\n if(++nstar == MAXSTARS) break;\n }\n }\n \n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: Found \" << nstar << \"/\" << n << \" stars\\n\"; \n#endif\n if(nstar < n) n = nstar;\n\n srand((uint32_t)time(NULL));\n for(k = 0; k < n; k++) {\n do {\n star_idx = (int) ( (nstar-1)*((double)rand()/(double)RAND_MAX));\n } while(star[star_idx] == -1 && star_idx < nstar);\n \n s2tp(gsc[star[star_idx]].ra,gsc[star[star_idx]].dec,\n ra0, dec0, xx[k], yy[k]);\n\n id[k] = star[star_idx];\n \n star[star_idx] = -1;\n }\n\n\n return n;\n}\n#undef MAXSTARS\n\n\n//finds the star catalgue indexes (id0 and id1) surrounding the distance val with an error determined by ftol\n//returns -1 on error, or 0 on success\nint Pyramid::GetIdx(double val, double ftol, \n uint32_t& id0, uint32_t& id1)\n{\n double error;\n double val_m, val_M;\n\n error = ftol*(sqrt(1 - val*val) + 0.5*val*ftol); \n\n val_m = val - error; \n val_M = val + error; \n\n if (val_m < rec[0].d) {\n#if PYRAMID_DEBUG\n\t cerr << \"[Pyramid debug]: GetIdx has val_m too low\" << endl;\n#endif\n\t val_m = rec[0].d;\n\t val_M = val_m + 2*error;\n }\n if (val_M > rec[nrec-1].d) {\n#if PYRAMID_DEBUG\n\t cerr << \"[Pyramid debug]: GetIdx has val_M too high\" << endl;\n#endif\n\t val_M = rec[nrec-1].d;\n\t val_m = val_M - 2*error;\n }\n// if( val_m < rec[0].d || val_M > rec[nrec-1].d) {\n// #if PYRAMID_DEBUG\n// cerr << \"[Pyramid debug]: warning, index out of range\" << endl;\n// #endif\n// return -1;\n// }\n\n id0 = (uint32_t)floor((val_m - this->q) / this->m) - 1;\n id1 = (uint32_t) ceil((val_M - this->q) / this->m) - 1;\n\n\n if(id0 >= this->nrec || id1 >= this->nrec) return -1;\n \n id0 = rec[id0].K+1;\n id1 = rec[id1].K;\n\n return 0;\n}\n\n//when called with n>=3, creates arrays containing indexes for all sets of 3 points (out of a total of n) and returns 0\n//on subsequent calls (n<3), it will return (in ii, jj, and kk) one such combination and step to the next (returns 1)\n//when all combinations have been exhausted, returns 0 again\nint Pyramid::GetTriangle(uint32_t& ii, uint32_t& jj, \n uint32_t& kk, uint32_t n/*=0*/) \n{\n static uint32_t *Ti = NULL;\n static uint32_t *Tj = NULL;\n static uint32_t *Tk = NULL;\n static uint32_t ntriangles = 0;\n static uint32_t Tidx = 0;\n\n if(n >= 3) {\n uint32_t dj, dk, i;\n ntriangles = (n*(n-1)*(n-2)) / 6; //n \"choose\" 3\n Tidx = 0;\n if(Ti != NULL) delete[] Ti; Ti = new uint32_t [ntriangles];\n if(Tj != NULL) delete[] Tj; Tj = new uint32_t [ntriangles];\n if(Tk != NULL) delete[] Tk; Tk = new uint32_t [ntriangles];\n\n for(dj = 1; dj <= (n-2); dj++) {\n for(dk = 1; dk <= (n - dj -1); dk++) {\n for(i = 1; i <= (n - dj - dk); i++) {\n Ti[Tidx] = i - 1;\n Tj[Tidx] = i + dj - 1;\n Tk[Tidx] = Tj[Tidx] + dk;\n Tidx++;\n }\n }\n }\n Tidx = 0;\n\n return 0;\n }\n\n if(Tidx < ntriangles) {\n ii = Ti[Tidx];\n jj = Tj[Tidx];\n kk = Tk[Tidx];\n Tidx++;\n return 1;\n }\n\n return 0;\n}\n\n\nint Pyramid::CheckSpecularTriangle(double* x, double* y, solution_t* S)\n{\n double b0[3], b1[3], b2[3];\n double s0[3], s1[3], s2[3];\n double b_vol, s_vol;\n double tcos;\n\n b0[0] = x[S->B[0]]; b0[1] = y[S->B[0]]; b0[2] = 1.0;\n b1[0] = x[S->B[1]]; b1[1] = y[S->B[1]]; b1[2] = 1.0;\n b2[0] = x[S->B[2]]; b2[1] = y[S->B[2]]; b2[2] = 1.0;\n\n tcos = cos(gsc[S->I[0]].dec);\n s0[0] = cos(gsc[S->I[0]].ra)*tcos; s0[1] = sin(gsc[S->I[0]].ra)*tcos; s0[2] = sin(gsc[S->I[0]].dec); \n tcos = cos(gsc[S->I[1]].dec);\n s1[0] = cos(gsc[S->I[1]].ra)*tcos; s1[1] = sin(gsc[S->I[1]].ra)*tcos; s1[2] = sin(gsc[S->I[1]].dec); \n tcos = cos(gsc[S->I[2]].dec);\n s2[0] = cos(gsc[S->I[2]].ra)*tcos; s2[1] = sin(gsc[S->I[2]].ra)*tcos; s2[2] = sin(gsc[S->I[2]].dec); \n \n b_vol = b0[0]*(b1[1]*b2[2] - b1[2]*b2[1]);\n b_vol += b0[1]*(b1[2]*b2[0] - b1[0]*b2[2]);\n b_vol += b0[2]*(b1[0]*b2[1] - b1[1]*b2[0]);\n\n s_vol = s0[0]*(s1[1]*s2[2] - s1[2]*s2[1]);\n s_vol += s0[1]*(s1[2]*s2[0] - s1[0]*s2[2]);\n s_vol += s0[2]*(s1[0]*s2[1] - s1[1]*s2[0]);\n\n return ((b_vol*s_vol > 0.0) ? 1 : 0);\n}\n\n\n//finds all pairs of stars that might match (within ftol) those in the x and y arrays (of length n)\n//stores the solutions in the array sol with length nsol and returns 0 if there are solutions (-1 if there aren't)\nint Pyramid::StarPair(double* x, double* y, uint32_t n, double ftol,\n solution_t* sol, uint32_t& nsol)\n \n{\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: in StarPair function\" << endl;\n#endif\n uint32_t i,j,k;\n uint32_t idx_m, idx_M;\n double d;\n solution_t* S;\n \n nsol = 0;\n for(i = 0; i < n-1; i++) {\n for(j = i+1; j < n; j++) {\n d = cdist(x[i],x[j],y[i],y[j]);\n if(GetIdx(d, ftol, idx_m, idx_M)) continue;\n \n for(k = idx_m; k <= idx_M; k++) {\n S = &sol[nsol];\n S->n = 0;\n S->flag = 1;\n S->I[S->n] = rec[k].I;\n S->B[S->n++] = i;\n S->I[S->n] = rec[k].J;\n S->B[S->n++] = j;\n if(++nsol == MAXSOLUTION) return 0;\n }\n }\n }\n\n return ( (nsol) ? 0 : -1 );\n}\n\n//checks the catalogue for star pairs with separations d1, d2, and d3 (within ftol) that share stars in a triangle\n//if so, those stars (with blob indexes i, j, and k) are added to the solution array sol and nsol is incremented for each\n//returns 0 if a solution is found or if nsol >= MAXSOLUTION, otherwise -1\nint Pyramid::StarTriangle(uint32_t i, uint32_t j, uint32_t k,\n double d1, double d2, double d3, double ftol,\n solution_t* sol, uint32_t& nsol)\n{\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: in StarTriangle function, indexes: (\" << i << \",\"\n << j << \",\" << k << \") and distances: (\" << d1 << \",\" << d2 << \",\" << d3 << \")\" << endl;\n#endif\n uint32_t l, p;\n uint32_t idx1_m, idx1_M, idx2_m, idx2_M, idx3_m, idx3_M;\n \n list<solution_t> pivot;\n list<solution_t>::iterator i_piv;\n solution_t P;\n\n int retval = -1;\n\n if( nsol >= MAXSOLUTION ) return 0;\n\n if(GetIdx(d1, ftol, idx1_m, idx1_M)) return retval; \n if(GetIdx(d2, ftol, idx2_m, idx2_M)) return retval; \n if(GetIdx(d3, ftol, idx3_m, idx3_M)) return retval; \n \n uint32_t nrec2 = idx2_M - idx2_m + 1;\n rec_t *rec2 = new rec_t [nrec2];\n\n memcpy(rec2, &rec[idx2_m], nrec2*sizeof(rec_t));\n qsort(rec2, nrec2, sizeof(rec_t), rec_I_sort);\n\n \n rec_t *R;\n\n //search list of pairs separated by d2 (rec2) for an I that matches a star in a pair separated by d1\n //for all matches found, push the possible solution struct onto pivot\n for(l = idx1_m; l <= idx1_M; l++) { \n // I in I\n if( (R = (rec_t *)pbsearch(&rec[l].I, rec2, nrec2, sizeof(rec_t), I_match)) != NULL) {\n\t do { //TODO valgrind reports: invalid read of size 4 (0 bytes after block of rec2)\n P.n = 3;\n P.flag = 0;\n P.I[0] = rec[l].I;\n P.B[0] = i;\n P.I[1] = rec[l].J;\n P.B[1] = j;\n P.I[2] = R->J;\n P.B[2] = k;\n \n pivot.push_back(P);\n \n R++;\n } while(rec[l].I == R->I); \n } \n\n // J in I\n if( (R = (rec_t *)pbsearch(&rec[l].J, rec2, nrec2, sizeof(rec_t), I_match)) != NULL) {\n\t do { //TODO valgrind reports: invalid read of size 4 (0 bytes after block of rec2)\n P.n = 3;\n P.flag = 0;\n P.I[0] = rec[l].J;\n P.B[0] = i;\n P.I[1] = rec[l].I;\n P.B[1] = j;\n P.I[2] = R->J;\n P.B[2] = k;\n \n pivot.push_back(P);\n \n R++;\n } while(rec[l].J == R->I); \n }\n } // loop on l\n\n //search list of pairs separated by d2 (rec2) for a J that matches a star in a pair separated by d1\n //for all matches found, push the possible solution struct onto pivot\n qsort(rec2, nrec2, sizeof(rec_t), rec_J_sort);\n for(l = idx1_m; l <= idx1_M; l++) { \n // I in J\n if( (R = (rec_t *)pbsearch(&rec[l].I, rec2, nrec2, sizeof(rec_t), J_match)) != NULL) {\n\t do { //TODO valgrind reports: invalid read of size 4 (4 bytes after block of rec2)\n P.n = 3;\n P.flag = 0;\n P.I[0] = rec[l].I;\n P.B[0] = i;\n P.I[1] = rec[l].J;\n P.B[1] = j;\n P.I[2] = R->I;\n P.B[2] = k;\n \n pivot.push_back(P);\n \n R++;\n } while(rec[l].I == R->J); \n } \n // J in J\n if( (R = (rec_t *)pbsearch(&rec[l].J, rec2, nrec2, sizeof(rec_t), J_match)) != NULL) {\n\t do { //TODO valgrind reports: invalid read of size 4 (4 bytes after block of rec2)\n P.n = 3;\n P.flag = 0;\n P.I[0] = rec[l].J;\n P.B[0] = i;\n P.I[1] = rec[l].I;\n P.B[1] = j;\n P.I[2] = R->I;\n P.B[2] = k;\n \n pivot.push_back(P);\n \n R++;\n } while(rec[l].J == R->J); \n }\n \n } // loop on l\n\n delete[] rec2;\n\n //for every solution in the pivot list, check if the two unmatched endpoints are in a pair separated by d3\n //if so, then a solution is found and it is added to the array for return\n for(i_piv = pivot.begin(); i_piv != pivot.end(); i_piv++) {\n for(p = idx3_m; p <= idx3_M; p++) {\n if( (i_piv->I[2] == rec[p].I && i_piv->I[1] == rec[p].J) || \n (i_piv->I[2] == rec[p].J && i_piv->I[1] == rec[p].I) ) {\n // Found triangle\n sol[nsol] = *i_piv;\n retval = 0; \n if(++nsol == MAXSOLUTION) return retval;\n break;\n }\n }\n\n }\n\n return retval;\n}\n\n\n//checks a star of blob index r, that is d1, d2, and d3 away from the 1st, 2nd, and 3rd stars in the triangle in S (within ftol)\n//if a matching 4th star is found then it is added to the solution and 0 is returned, otherwise -1 is returned\nint Pyramid::StarPyramid(uint32_t r, \n double d1, double d2, double d3, double ftol,\n solution_t* S)\n{\n uint32_t l,m,p;\n uint32_t p1, p2, p3;\n uint32_t idx1_m, idx1_M, idx2_m, idx2_M, idx3_m, idx3_M;\n int retval = -1;\n \n if(S->n == MAXSOLUTION) return retval;\n\n if(GetIdx(d1, ftol, idx1_m, idx1_M)) return retval;\n if(GetIdx(d2, ftol, idx2_m, idx2_M)) return retval;\n if(GetIdx(d3, ftol, idx3_m, idx3_M)) return retval;\n\n for(l = idx1_m; l <= idx1_M; l++) {\n if(rec[l].I == S->I[0]) {\n p1 = rec[l].J;\n } else if(rec[l].J == S->I[0]) {\n p1 = rec[l].I;\n } else {\n continue;\n }\n for(m = idx2_m; m <= idx2_M; m++) {\n if(rec[m].I == S->I[1]) {\n p2 = rec[m].J;\n } else if(rec[m].J == S->I[1]) {\n p2 = rec[m].I;\n } else {\n continue;\n }\n for(p = idx3_m; p <= idx3_M; p++) {\n if(rec[p].I == S->I[2]) {\n p3 = rec[p].J;\n } else if(rec[p].J == S->I[2]) {\n p3 = rec[p].I;\n } else {\n continue;\n }\n \n // Candidate triad\n if(p1 == p2 && p1 == p3) {\n S->I[S->n] = p1;\n S->B[S->n++] = r;\n return 0; // Match achieved: quit here.\n }\n }\n }\n }\n \n return retval;\n}\n\n\n//seraches tangent plane coordinates (x and y with length n) of stars for pattern matches within tolerance ftol\nint Pyramid::Match(double* x, double* y, double ftol, uint32_t n)\n\n{\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: in Match function\" << endl;\n#endif\n uint32_t i, j, k, r;\n double d1, d2, d3;\n\n solution_t sol_[MAXSOLUTION];\n solution_t *S;\n uint32_t nsol_ = 0;\n uint32_t nsol = 0;\n uint32_t sol_idx, sol_start;\n int pyramid;\n\n int retval = -1;\n\n if(n > MAXBLOBS) n = MAXBLOBS;\n switch (n) {\n case 0: retval = 0; nsol = 0; break;\n case 1: retval = 0; nsol = 0; break;\n case 2: \n StarPair(x, y, n, ftol, sol_, nsol_);\n nsol = nsol_;\n retval = (nsol) ? 2 : 0;\n break;\n case 3: \n i = 0; j = 1; k = 2;\n d1 = cdist(x[i], x[j], y[i], y[j]);\n d2 = cdist(x[i], x[k], y[i], y[k]);\n d3 = cdist(x[j], x[k], y[j], y[k]);\n \n if(StarTriangle(i,j,k,d1,d2,d3, ftol, sol_, nsol_) ) {\n \n for(sol_idx = 0; sol_idx < nsol_; sol_idx++) {\n S = &sol_[sol_idx];\n if(CheckSpecularTriangle(x, y, S)) {\n S->flag = 1;\n nsol++;\n }\n }\n }\n \n if(nsol == 0) { // no valid solutions found\n StarPair(x, y, n, ftol, sol_, nsol_);\n nsol = nsol_;\n retval = (nsol) ? 2 : 0;\n } else {\n retval = 3;\n }\n\n break;\n \n default: // More than three candidate stars\n GetTriangle(i,j,k,n); //creates a list of possible triangles\n M0: \n\tif(GetTriangle(i,j,k) == 0) { //steps through list of triangles (assigns i,j,k)\n#if PYRAMID_DEBUG\n\t\tcerr << \"[Pyramid debug]: Checked all triangles\\n\";\n#endif\n // There are no more triangles to be scanned\n // check if there were some matched triangles and use those\n for(sol_idx = 0; sol_idx < nsol_; sol_idx++) {\n S = &sol_[sol_idx];\n if(CheckSpecularTriangle(x, y, S)) {\n S->flag = 1;\n nsol++;\n } \n }\n if(nsol == 0) { // no valid solutions found\n StarPair(x, y, n, ftol, sol_, nsol_);\n nsol = nsol_;\n retval = (nsol) ? 2 : 0;\n } else {\n retval = 3;\n }\n break;\n }\n\t//else, this is a possible triangle so try to match to it\n\n d1 = cdist(x[i], x[j], y[i], y[j]);\n d2 = cdist(x[i], x[k], y[i], y[k]);\n d3 = cdist(x[j], x[k], y[j], y[k]);\n\n sol_start = nsol_;\n\tif(StarTriangle(i,j,k,d1,d2,d3, ftol, sol_, nsol_) ) {\n#if PYRAMID_DEBUG\n\t\tcerr << \"[Pyramid debug]: Failed to match triangle\\n\";\n#endif\n\t\tgoto M0; //pattern matching failed, try next triangle\n\t}\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: Found \" << nsol_ << \" triangles\" << endl;\n#endif\n // Now I have some candidate triangles, look for the pyramid\n for(sol_idx = sol_start, pyramid = 0; sol_idx < nsol_ && !pyramid; sol_idx++) {\n S = &sol_[sol_idx];\n for(r = 0; r < n; r++) {\n if( r == i || r == j || r == k) continue;\n \n d1 = cdist(x[i], x[r], y[i], y[r]);\n d2 = cdist(x[j], x[r], y[j], y[r]);\n d3 = cdist(x[k], x[r], y[k], y[r]);\n \n if(StarPyramid(r, d1, d2, d3, ftol, S) == 0) {\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: Matched a pyramid!!\\n\";\n#endif\n pyramid = 1;\n S->flag = 1;\n }\n\n } // loop on piramid r star\n } // loop on sol_ \n\n\tif(!pyramid) {\n#if PYRAMID_DEBUG\n\t\tcerr << \"[Pyramid debug]: Failed to match pyramid\\n\";\n#endif\n\t\tgoto M0; // No matching pyramid found, start over\n\t}\n nsol++;\n retval = S->n;\n break;\n }\n \n if(solution != NULL) delete[] solution;\n solution = new solution_t [nsol];\n\n for(sol_idx = 0, k = 0; sol_idx < nsol_; sol_idx++) {\n if(sol_[sol_idx].flag) {\n memcpy(&solution[k], &sol_[sol_idx], sizeof(solution_t));\n \n // memset(solution[k].C, 0, n*sizeof(gsc_t*)); //I (steve) changed this to size of a pointer\n for(i = 0; i < solution[k].n; i++) {\n solution[k].C[i] = &gsc[solution[k].I[i]];\n }\n if(++k == nsol) break;\n }\n }\n\n nsolution = k;\n\n return retval;\n}\n\nvoid Pyramid::SwapColumns(double *matrix, int n_rows,int n_columns,int column1, int column2 )\n{\n double tmp = 0.;\n if((column1 < n_columns)&&(column2 < n_columns)) {\n \tfor(int j = 0; j < n_rows; j++) {\n\t\ttmp = matrix[j*n_columns+column1];\n\t\tmatrix[j*n_columns+column1] = matrix[j*n_columns+column2];\n\t\tmatrix[j*n_columns+column2] = tmp;\n\t\ttmp = 0.;\n \t}\n }\n else cerr << \"Unable to swap columns\" << endl;\n}\n\nvoid Pyramid::Transpose(double *matrix, int n_rows,int n_columns)\n{\n double tmp = 0.;\n for(int i = 0; i < n_rows; i++) {\n \tfor(int j = i; j < n_columns; j++) {\n\t\ttmp = matrix[i*n_columns+j];\n\t\tmatrix[i*n_columns+j] = matrix[j*n_columns+i];\n\t\tmatrix[j*n_columns+i] = tmp;\n\t\ttmp = 0.;\n \t}\n }\n}\n\n//in row-major order, the linear offset from the beginning of the array to any given element A[row][column] can then be computed as: offset = row*NUMCOLS + column\ndouble* Pyramid::Product(double *matrix1, double *matrix2, int n_rows1,int n_common, int n_columns2)\n{\n double *product = new double [n_rows1*n_columns2];\n double tmp = 0.0;\n for(int i = 0; i < n_rows1; i++) {\n \tfor(int j = 0; j < n_columns2; j++) {\n\t\tfor(int k = 0; k < n_common; k++) {\n\t\t\ttmp += matrix1[i*n_common+k]*matrix2[k*n_columns2+j];\n\t\t}\n\tproduct[i*n_columns2+j] = tmp;\n\ttmp = 0.;\n \t}\n }\nreturn product;\n}\n\ndouble Pyramid::Determinant3x3(double *matrix)\n{\ndouble det;\ndet = matrix[0]*matrix[4]*matrix[8]-matrix[0]*matrix[5]*matrix[7]+matrix[1]*matrix[5]*matrix[6]-matrix[1]*matrix[3]*matrix[8]+matrix[2]*matrix[3]*matrix[7]-matrix[2]*matrix[4]*matrix[6];\nreturn det;\n}\n\n// In this rutine I assume the boresight to be in the x direction, the vertical in the y direction.\nvoid Pyramid::GetCenter(double* x, double* y, int nblobs, double &ra0, double &dec0, double &r0)\n{\n\n int idx,i,k,j;\n double ra_tp, dec_tp;\n\n double *B = new double [3*3];\n double *V = new double [3*3];\n memset(B, 0, 9*sizeof(double));\n memset(V, 0, 9*sizeof(double));\n double W[3] = {0,0,0};\n double work[3] = {0,0,0};\n double b[3] = {0,0,0};\n double r[3] = {0,0,0};\n double det_B, det_V;\n double *prod;\n double *A;\n\n double *this_x = new double [solution->n];\n double *this_y = new double [solution->n];\n\n for(idx = 0; idx < solution->n; idx++) {\n\tthis_x[idx] = x[(solution->B[idx])];\n\tthis_y[idx] = y[(solution->B[idx])];\n }\n\n for(idx = 0; idx < solution->n; idx++) {\n\n double xt = -this_x[idx];\n double yt = this_y[idx];\n\n tp2s(ra_tp, dec_tp, 0.0, 0.0, xt, yt);\n\n b[0] = cos(ra_tp)*cos(dec_tp);\n b[1] = sin(dec_tp);\n b[2] = -sin(ra_tp)*cos(dec_tp);\n\n r[0] = cos((solution->C)[idx]->ra)*cos((solution->C)[idx]->dec);\n r[1] = sin((solution->C)[idx]->dec);\n r[2] = -sin((solution->C)[idx]->ra)*cos((solution->C)[idx]->dec);\n\n for(i = 0; i < 3; i++) {\n\tfor(k = 0; k < 3; k++) {\n\t\tB[i*3+k] += b[i] * r[k];\n\t}\n }\n }\n\n delete[] this_x;\n delete[] this_y;\n\n svd ( 3, 3, 3, 3, (double *) B, W, (double *) V, work, &j );\n\n // Sort\n if(W[0] < W[1]) {\n SwapColumns((double *) B, 3, 3, 0, 1);\n SwapColumns((double *) V, 3, 3, 0, 1);\n }\n if(W[1] < W[2]) {\n SwapColumns((double *) B, 3, 3, 1, 2);\n SwapColumns((double *) V, 3, 3, 1, 2);\n }\n if(W[0] < W[1]) {\n SwapColumns((double *) B, 3, 3, 0, 1);\n SwapColumns((double *) V, 3, 3, 0, 1);\n }\n\n det_B = Determinant3x3((double *) B);\n\n det_V = Determinant3x3((double *) V);\n double D[3][3] = {{1.0,0,0},{0,1.0,0},{0,0,1.0/(det_B*det_V)}};\n\n Transpose((double *) B, 3, 3);\n prod = Product((double *) V, (double *) D, 3,3,3);\n A = Product((double *) prod, (double *) B, 3,3,3);\n\n delete[] B;\n delete[] V;\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: A[6]= \" << A[6] << \" A[0]= \" << A[0] << endl;\n#endif\n/////HERE:\n ra0 = -atan2(A[6], A[0]);\n dec0 = asin(A[3]);\n r0 = atan2(A[5], A[4]);\n}\n\n//main function to perform pattern matching\n//finds stars that match those with tangent plane coordinates x and y (there are nblobs of them) within tolerance ftol\n//the number of solutions (nsol) and an array of them (sol) are returned (these don't need to be allocated before calling)\n//ra0, dec0, and r0 currently do nothing, so this method is more or less a wrapper for the Match function\n//returns 2, 3, or 4 for a pair, triangle, or pyramid match, 0 for no match and -1 for error\nint Pyramid::GetSolution(double ftol, double* x, double* y, int nblobs, solution_t** sol, int* nsol,double* ra0, double* dec0, double* r0)\n{ \n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: in GetSolution function\" << endl;\n#endif\n int retval = 0;\n\n#ifdef __TIMING__\n struct timeval t0, t1;\n gettimeofday(&t0, NULL);\n#endif\n\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: starting pattern matching.\\n\";\n#endif\n retval = Match(x, y, ftol, nblobs);\n#if PYRAMID_DEBUG\n cerr << \"[Pyramid debug]: pattern matching completed with return value: \" << retval << \"\\n\";\n#endif\n \n#ifdef __TIMING__\n gettimeofday(&t1, NULL);\n cerr << \"[Pyramid debug]: It took \" << ((t1.tv_sec + t1.tv_usec*1.0E-6) -(t0.tv_sec + t0.tv_usec*1.0E-6)) *1.0E3 << endl; \n#endif\n\n// if(retval > 3) lis = 0;\n\n// if(retval < 2) return retval;\n\n// if(retval == 2 && r0 > 0.0) {\n// solution_t sol_[MAXSOLUTION];\n// int nsol_;\n// int k;\n// double c_r0 = cos(r0);\n// for(k = 0, nsol_ = 0; k < nsolution; k++) {\n// if(dist(gsc[solution[k].I[0]].ra, ra0, gsc[solution[k].I[0]].dec, dec0) > c_r0) {\n// memcpy(sol_ + nsol_, &solution[k], sizeof(solution_t));\n// nsol_++;\n// }\n// }\n// delete solution;\n// solution = new solution_t [nsol_];\n// memcpy(solution, sol_, nsol_*sizeof(solution_t));\n// nsolution = nsol_;\n// }\n\n this->GetCenter(x, y, nblobs, *ra0, *dec0, *r0);\n\n\n *sol = this->solution;\n *nsol = this->nsolution;\n\n return retval;\n}\n\n" }, { "alpha_fraction": 0.7145161032676697, "alphanum_fraction": 0.7209677696228027, "avg_line_length": 25.913043975830078, "blob_id": "2a1dd53f2a6a416ec859ac8f89bfde6a4e65d1b8", "content_id": "952e257a5286e7ce85ffe15483fa62c9c9bdb46e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 621, "license_type": "no_license", "max_line_length": 89, "num_lines": 23, "path": "/stars/code/parameters/manager.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"manager.h\"\n#include <boost/filesystem/operations.hpp>\n\nusing namespace Parameters;\n\nManager::Manager(std::string stars_absolute_dir):\n stars_dir(stars_absolute_dir),\n general(stars_absolute_dir)\n{\n}\n\nvoid Manager::load(int argc, char* argv[])\n{\n using namespace boost::filesystem;\n general.load(argc, argv);\n housekeeping.load(system_complete(stars_dir + \"settings/housekeeping.txt\").string());\n}\n\n" }, { "alpha_fraction": 0.6499051451683044, "alphanum_fraction": 0.6859582662582397, "avg_line_length": 29.941177368164062, "blob_id": "d61fa3033eac24db327b274357ece3e399bf9dec", "content_id": "654a2ee1aa97da2641672c6ee0a9f819bc01684c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1054, "license_type": "no_license", "max_line_length": 71, "num_lines": 34, "path": "/stars/code/displaying/glfont2/fonts/editing/convert_png_to_glf.py", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\nimport pylab\nimport Image\n\nclass Header:\n pass\n\ndef parse_header(header_str):\n header = Header()\n header.tex_width = pylab.fromstring(header_str[4:8], \"int32\")[0]\n header.tex_height = pylab.fromstring(header_str[8:12], \"int32\")[0]\n header.start_char = pylab.fromstring(header_str[12:16], \"int32\")[0]\n header.end_char = pylab.fromstring(header_str[16:20], \"int32\")[0]\n return header\n\ndef create_glf(original_filename, image):\n infile = open(original_filename, \"r\")\n contents = infile.read()\n infile.close()\n header = parse_header(contents[0:24]) \n num_chars = header.end_char - header.start_char + 1\n return contents[0: 24+num_chars*24] + image.tostring()\n\ndef save_file(outdata, outfilename):\n outfile = open(outfilename, \"wb\")\n outfile.write(outdata)\n outfile.close()\n\noriginal_filename = \"arial24.glf\"\ninfilename = \"arial24_with_degrees.png\"\nimage = Image.open(infilename)\noutdata = create_glf(original_filename, image)\nsave_file(outdata, infilename.replace(\".png\", \".glf\"))\n\n\n" }, { "alpha_fraction": 0.6104453802108765, "alphanum_fraction": 0.6206194758415222, "avg_line_length": 28.098684310913086, "blob_id": "d47c8ec41b5a4e128fe0e47cfcbafdb3a0f7ea13", "content_id": "70f902b3607bf52f21cc508b683df3aa7f9b8294", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4423, "license_type": "no_license", "max_line_length": 95, "num_lines": 152, "path": "/defricher/defricher_utils.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * defricher_utils.c: \n *\n * This software is copyright (C) 2013-2014 Seth Hillbrand\n *\n * This file is part of defricher, created for the BLASTPol Project.\n *\n * defricher 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 2 of the License, or\n * (at your option) any later version.\n *\n * defricher 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 defricher; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Apr 6, 2015 by Seth Hillbrand\n */\n\n\n#include <stdint.h>\n#include <inttypes.h>\n#include <stdbool.h>\n#include <limits.h>\n\n#if defined(__APPLE__)\n#include <sys/syslimits.h>\n#endif\n\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <string.h>\n#include <unistd.h>\n#include <stdio.h>\n\n#include <blast.h>\n#include \"defricher_utils.h\"\n\n/**\n * Ensure that the referenced directory and all of its parent directories have been made\n * @param m_directory\n * @return\n */\nstatic int defricher_mkdir_recursive (char *m_directory)\n{\n char current_path[PATH_MAX];\n char *path_chunk = NULL;\n char *strtok_ref = NULL;\n int ret = 0;\n struct stat dir_stat;\n\n /** Ensure that we have a NULL delimiter in our temp string */\n current_path[0]=0;\n\n /**\n * Takes a chunk of the directory path at a time\n */\n path_chunk = strtok_r(m_directory, \"/\", &strtok_ref);\n if (m_directory[0] == '/')\n {\n strcat(current_path, \"/\");\n }\n while (path_chunk != NULL)\n {\n if (strlen(current_path) + strlen(path_chunk) + 2 > PATH_MAX)\n {\n defricher_err(\"Path too long\");\n return -1;\n }\n strcat(current_path, path_chunk);\n strcat(current_path, \"/\");\n if (stat(current_path, &dir_stat) != 0)\n {\n ret = mkdir(current_path, ACCESSPERMS);\n if (ret < 0)\n {\n defricher_strerr(\"Could not make %s\", current_path);\n return ret;\n }\n }\n path_chunk = strtok_r(NULL, \"/\", &strtok_ref);\n }\n return 0;\n}\n/**\n * Takes a fully justified path to a file and\n * recursively makes the directory structure to hold the file\n *\n * @details Begins by extracting the first token delimited by a\n * slash. Since the slash is not included in the token, it appends a\n * slash to the directory name. Then, if we get another token, we know\n * that we have at least 1 directory to make. The directory is created\n * and we loop. The last token is the filename, which we don't want as\n * a directory. We check for disk and permission errors but allow for\n * existence errors (we don't care if the directory is already created)\n *\n * @param [in] m_file Justified file or directory name. If partially justified,\n * the primary disk's mount point is prepended\n * @param [in] m_file_appended true if #m_filename is suffixed with a filename\n * false if #m_filename is a bare directory name\n * @return -1 on error, 0 on success\n */\nint defricher_mkdir_file(const char *m_filename, bool m_file_appended)\n{\n\n char directory_name[PATH_MAX];\n size_t len = 0;\n\n if (m_filename == NULL)\n {\n defricher_err(\"Passed NULL pointer\");\n return -1;\n }\n\n if (m_file_appended)\n {\n len = (size_t)(strrchr(m_filename, '/') - m_filename);\n }\n else\n {\n len = strlen(m_filename);\n }\n\n /** len is used for the maximum number of characters inclusive of the \\0 char, so increment\n * by one from strlen's return\n */\n if (++len > PATH_MAX) len = PATH_MAX;\n\n if (*m_filename == '/')\n {\n snprintf(directory_name, len, \"%s\", m_filename);\n }\n else\n {\n char cwd[PATH_MAX];\n getcwd(cwd, PATH_MAX);\n len += strlen(cwd) + 1; /* The additional character here is for the '/' */\n if (len > PATH_MAX) len = PATH_MAX;\n\n snprintf(directory_name,len+1,\"%s/%s\",cwd,m_filename);\n }\n\n\n return defricher_mkdir_recursive(directory_name);\n\n}\n" }, { "alpha_fraction": 0.6761141419410706, "alphanum_fraction": 0.6977240443229675, "avg_line_length": 31.119197845458984, "blob_id": "79584419d870a680b4361357067e735b65cdfb5b", "content_id": "8675893da3aa4c470ac5264d987a4aa2837efa5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 30449, "license_type": "no_license", "max_line_length": 88, "num_lines": 948, "path": "/stars/code/imaging/QCamApi2.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n|==============================================================================\n| Copyright (C) 2002 Quantitative Imaging Corporation. All Rights Reserved.\n| Reproduction or disclosure of this file or its contents without the prior\n| written consent of Quantitative Imaging Corporation is prohibited.\n|==============================================================================\n|\n| File:\t\t\tQCamApi.h\n|\n| Project/lib:\tQCam Driver\n|\n| Target:\t\tMac OS 9, Mac OS X, Win32\n|\n| Description:\t\n|\n| Notes:\t\tThis interface is not reentrant. See \"QCam API.pdf\" for\n|\t\t\t\tdetails.\n|\n|==============================================================================\n| dd/mon/yy Author\t\tNotes\n|------------------------------------------------------------------------------\n| 30/Aug/00 DavidL\t\tOriginal.\n| 31/Jan/01 DavidL\t\tVersion 1.00.\n| 01/Feb/02 DavidL\t\tDriver release 1.50. We will try to keep this up to\n|\t\t\t\t\t\tdate from now on.\n| 14/Feb/02 DavidL\t\tAdd qprmSyncb, qinfFirmwareBuild, qinfUniqueId, and\n|\t\t\t\t\t\tQCam_GetSerialString().\n| 02/Apr/02 DavidL\t\tChange constant qcCcdICX252AK to qcCcdICX252AQ. Sorry\n|\t\t\t\t\t\tif you were using that! Just change the constants in\n|\t\t\t\t\t\tyour code to qcCcdICX252AQ and you're done.\n| 13/May/02 DavidL\t\tAdd qinfIsModelB, QCam_IsParamSupported(). Add error\n|\t\t\t\t\t\tchecking for bad uPub ROI, fix corrupt bayerPattern\n|\t\t\t\t\t\tfield in QCam_Frame after QueueSettings(). When a\n|\t\t\t\t\t\tcamera is unplugged you now get error qerrUnplugged.\n| 13/Jun/02 DavidL\t\tAdd qcCallbackExposeDone.\n| 18/Sep/02 JonS\t\tAdded QCam_Param64 enum. type with types \n|\t\t\t\t\t\tqprm64Exposure, qprm64ExposureRed, and \n|\t\t\t\t\t\tqprm64ExposureBlue.\n|\t\t\t\t\t\tAdded new QCam_GetParam64(), QCam_SetParam64(), \n|\t\t\t\t\t\tQCam_GetParam64Max(), QCam_GetParam64Min() and\n|\t\t\t\t\t\tQCam_IsParam64Supported() functions.\n|\t\t\t\t\t\tAdded new QCam_qcCameraType: qcCameraRetIT.\n|\t\t\t\t\t\tAlso added new enum. type QCam_IntensifierModel with types\n|\t\t\t\t\t\tqcITVSStdGenIIIA and qcITVSEBGenIIIA.\n|\t\t\t\t\t\tAdded new QCam_Info types qinfIntensifierModel,\n|\t\t\t\t\t\tqinfExposureRes, and qinfTriggerDelayRes.\n|\t\t\t\t\t\tAdded new QCam_Param types qprmIntensifierGain and\n|\t\t\t\t\t\tqprmTriggerDelay.\n| 28/Feb/03 BradR\t\tAdded Sparse Tabling support (32 and 64 bit) along with\n|\t\t\t\t\t\tQCam_IsRangeParam and QCam_IsSparseParam (32 and 64 bit).\n| 25/Jul/03 ChrisS\t\tAdded mode support. Currently this is only used with\n|\t\t\t\t\t\tMicroPublisher cameras.\n| 05/Sep/03 ChrisS Added sparse table and range table support for signed 32\n|\t\t\t\t\t\tbit integer parameters.\n|\t\t\t\t\t\tAdded Normalized Gain support. This includes parameters\n|\t\t\t\t\t\tqprmNormalizedGain, qprmS32NormalizedGaindB, and info\n|\t\t\t\t\t\tkeys qinfNormGainSigFigs and qinfNormGaindBRes.\n|\t\t\t\t\t\tAdded Absolute Offset support. This includes parameter\n|\t\t\t\t\t\tqprmS32AbsoluteOffset.\n| 03/Oct/03 ChrisS\t\tAdded Normalized Intensifier Gain support. This includes\n|\t\t\t\t\t\tqprmNormIntensGaindB and qprm64NormIntensGain. Info\n|\t\t\t\t\t\titems added for ITGain are qinfNormITGainSigFigs and\n|\t\t\t\t\t\tqinfNormITGaindBRes.\n|\t\t\t\t\t\tIncreased the size of the QCam_Settings structure to 64.\n| 09/Dec/03 ChrisS\t\tAdded QCam_LibVersion to replace QCam_Version.\n|\t\t\t\t\t\tQCam_LibVersion returns an additional build revision.\n|==============================================================================\n*/\n\n#ifndef QCAMAPI_H_INCLUDE\n#define QCAMAPI_H_INCLUDE\n\n#ifndef QCAMAPI\n\t#ifdef _WIN32\n\t\t#define QCAMAPI __stdcall\n\t\t#define UNSIGNED64 unsigned __int64\n\t#else\n\t\t#define QCAMAPI\n\t\t#define UNSIGNED64 unsigned long long\n\t#endif\n#endif // QCAMAPI\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n//===== INCLUDE FILES =========================================================\n\n//===== #DEFINES ==============================================================\n\n//===== TYPE DEFINITIONS ======================================================\n\ntypedef enum\n{\n\t// Model-A cameras (old camera hardware):\n\tqcCameraUnknown\t\t\t= 0,\n\tqcCameraMi2\t\t\t\t= 1,\t\t// MicroImager II and Retiga 1300\n\tqcCameraPmi\t\t\t\t= 2,\n\tqcCameraRet1350\t\t\t= 3,\t\t// Retiga EX\n\tqcCameraQICam\t\t\t= 4,\n\n\t// Model-B cameras (new camera hardware):\n\tqcCameraRet1300B\t\t= 5,\n\tqcCameraRet1350B\t\t= 6,\n\tqcCameraQICamB\t\t\t= 7,\n\tqcCameraMicroPub\t\t= 8,\t\t// First versions of MicroPub were model A,\n\t\t\t\t\t\t\t\t\t\t// but both A and B return the same type.\n\tqcCameraRetIT\t\t \t= 9,\t\t// Intensified Retiga\n\tqcCameraQICamIR\t\t\t= 10,\n\n\t// These names are for engineering and OEM use:\n\tqcCameraX\t\t\t\t= 1000,\n\tqcCameraOem1\t\t\t= 1001,\n\tqcCameraOem2\t\t\t= 1002\n\n}\nQCam_qcCameraType;\n\ntypedef enum\n{\n\tqcCcdMonochrome\t\t= 0,\n\tqcCcdColorBayer\t\t= 1,\n\tqctype_last\t\t\t= 2\n}\nQCam_qcCcdType;\n\ntypedef enum\n{\n\tqcCcdKAF1400\t\t= 0,\n\tqcCcdKAF1600\t\t= 1,\n\tqcCcdKAF1600L\t\t= 2,\n\tqcCcdKAF4200\t\t= 3,\n\tqcCcdICX085AL\t\t= 4,\n\tqcCcdICX085AK\t\t= 5,\n\tqcCcdICX285AL\t\t= 6,\n\tqcCcdICX285AK\t\t= 7,\n\tqcCcdICX205AL\t\t= 8,\n\tqcCcdICX205AK\t\t= 9,\n\tqcCcdICX252AQ\t\t= 10,\n\tqcCcdS70311006\t\t= 11,\n\tqcCcdICX282AQ\t\t= 12,\n\tqcCcdICX407AL\t\t= 13,\n\tqcCcdS70310908\t\t= 14,\n\tqcCcdVQE3618L\t\t= 15,\n\tqcCcdX\t\t\t\t= 255\t\t// Don't use this value\n}\nQCam_qcCcd;\n\ntypedef enum\n{\n\tqcItVsStdGenIIIA\t= 0,\n\tqcItVsEbGenIIIA\t\t= 1\n}\nQCam_qcIntensifierModel;\n\ntypedef enum\n{\n\tqcBayerRGGB\t\t\t= 0,\n\tqcBayerGRBG\t\t\t= 1,\n\tqcBayerGBRG\t\t\t= 2,\n\tqcBayerBGGR\t\t\t= 3\n}\nQCam_qcBayerPattern;\n\ntypedef enum\n{\n\tqcTriggerNone\t\t= 0,\t\t// Depreciated\n\n\t// Freerun mode: expose images as fast as possible\n\tqcTriggerFreerun\t= 0,\n\n\t// Hardware trigger modes (software trigger also works):\n\tqcTriggerEdgeHi\t\t= 1,\t\t// Edge triggers exposure start\n\tqcTriggerEdgeLow\t= 2,\n\tqcTriggerPulseHi\t= 3,\t\t// Integrate over pulse\n\tqcTriggerPulseLow\t= 4,\n\n\t// Software trigger (software only, no hardware):\n\tqcTriggerSoftware\t= 5,\n\n\tqcTrigger_last\t\t= 6\n}\nQCam_qcTriggerType;\n\ntypedef enum\n{\n\tqcWheelRed\t\t\t= 0,\n\tqcWheelGreen\t\t= 1,\n\tqcWheelBlack\t\t= 2,\n\tqcWheelBlue\t\t\t= 3,\n\tqcWheel_last\t\t= 4\n}\nQCam_qcWheelColor;\n\ntypedef enum\n{\n\tqcReadout20M\t\t= 0,\n\tqcReadout10M\t\t= 1,\n\tqcReadout5M\t\t\t= 2,\n\tqcReadout2M5\t\t= 3,\n\tqcReadout_last\t\t= 4\n}\nQCam_qcReadoutSpeed;\n\ntypedef enum\n{\n\tqcShutterAuto\t\t= 0,\n\tqcShutterClose\t\t= 1,\n\tqcShutterOpen\t\t= 2,\n\tqcShutter_last\t\t= 3\n}\nQCam_qcShutterControl;\n\ntypedef enum\n{\n\tqcSyncbTrigmask\t\t= 0,\n\tqcSyncbExpose\t\t= 1,\n\tqcSyncbOem1\t\t\t= 0,\n\tqcSyncbOem2\t\t\t= 1\n}\nQCam_qcSyncb;\n\ntypedef enum\n{\n\tqcCallbackDone\t\t\t= 1,\t// Callback when QueueFrame (or QueueSettings) is done\n\tqcCallbackExposeDone\t= 2\t\t// Callback when exposure done (readout starts);\n\t\t\t\t\t\t\t\t\t// model-B and all MicroPublishers only;\n\t\t\t\t\t\t\t\t\t// callback is not guaranteed to occur\n}\nQCam_qcCallbackFlags;\n\ntypedef enum\n{\n\tqmdStandard\t\t\t\t= 0,\t// Default camera mode, legacy mode of operation\n\tqmdRealTimeViewing\t\t= 1,\t// Real Time Viewing mode, MicroPublisher model only\n\tqmd_last\t\t\t\t= 2,\n\t_qmd_force32\t\t\t= 0xFFFFFFFF\n}\nQCam_Mode;\n\ntypedef enum\n{\n\tqerrSuccess\t\t\t\t= 0,\n\tqerrNotSupported\t\t= 1,\t// Function is not supported for this device\n\tqerrInvalidValue\t\t= 2,\t// Invalid parameter value\n\tqerrBadSettings\t\t\t= 3,\t// Bad QCam_Settings struct\n\tqerrNoUserDriver\t\t= 4,\n\tqerrNoFirewireDriver\t= 5,\t// No firewire device driver installed\n\tqerrDriverConnection\t= 6,\n\tqerrDriverAlreadyLoaded\t= 7,\t// Too many calls to QCam_LoadDriver()\n\tqerrDriverNotLoaded\t\t= 8,\t// Did not call QCam_LoadDriver()\n\tqerrInvalidHandle\t\t= 9,\t// Invalid QCam_Handle\n\tqerrUnknownCamera\t\t= 10,\t// Camera type is unknown to this version of QCam\n\tqerrInvalidCameraId\t\t= 11,\t// Invalid camera id used in QCam_OpenCamera\n\tqerrNoMoreConnections\t= 12,\t// Obsolete...\n\tqerrHardwareFault\t\t= 13,\n\tqerrFirewireFault\t\t= 14,\n\tqerrCameraFault\t\t\t= 15,\n\tqerrDriverFault\t\t\t= 16,\n\tqerrInvalidFrameIndex\t= 17,\n\tqerrBufferTooSmall\t\t= 18,\t// Frame buffer (pBuffer) is too small for image\n\tqerrOutOfMemory\t\t\t= 19,\n\tqerrOutOfSharedMemory\t= 20,\n\tqerrBusy\t\t\t\t= 21,\n\tqerrQueueFull\t\t\t= 22,\t// Cannot queue more items, queue is full\n\tqerrCancelled\t\t\t= 23,\n\tqerrNotStreaming\t\t= 24,\t// Streaming must be on before calling this command\n\tqerrLostSync\t\t\t= 25,\t// This frame is trash, frame sync was lost\n\tqerrBlackFill\t\t\t= 26,\t// This frame is damanged, some data is missing\n\tqerrFirewireOverflow\t= 27,\t// Firewire overflow - restart streaming\n\tqerrUnplugged\t\t\t= 28,\t// Camera has been unplugged or turned off\n\tqerrAccessDenied\t\t= 29,\t// The camera is already open\n\tqerrStreamFault\t\t\t= 30,\t// Stream Allocation Failed. Is there enough Bandwidth\n\t_qerr_force32\t\t\t= 0xFFFFFFFF\n}\nQCam_Err;\n\n//\n// For 16-bit data: the data is in words, least-significant-bit aligned.\n//\n// When reading RGB formats, read the name as bytes... For example, Xrgb32\n// means that byte[ 0 ] is not used, byte[ 1 ] is red, byte[ 2 ] is green,\n// byte[ 3 ] is blue. On a mac, this would mean that the least significant\n// byte of a 32-bit word is RED.\n//\n// For Mi2/Retiga:\n//\t\t- color CCD requires bayerX (or rawX) format in 1x1\n//\t\t- color CCD requires monoX (or rawX) format in binning other than 1x1\n//\t\t- if you choose color formats on monochrome CCD you will get a 3-shot\n//\t\t\trgb filter image; color CCD cameras do not have rgb filter capability\n//\ntypedef enum\n{\n\tqfmtRaw8\t\t\t\t= 0,\t// Raw CCD output\n\tqfmtRaw16\t\t\t\t= 1,\t// Raw CCD output\n\tqfmtMono8\t\t\t\t= 2,\t// Data is bytes\n\tqfmtMono16\t\t\t\t= 3,\t// Data is shorts, LSB aligned\n\tqfmtBayer8\t\t\t\t= 4,\t// Bayer mosaic; data is bytes\n\tqfmtBayer16\t\t\t\t= 5,\t// Bayer mosaic; data is shorts, LSB aligned\n\tqfmtRgbPlane8\t\t\t= 6,\t// Separate color planes\n\tqfmtRgbPlane16\t\t\t= 7,\t// Separate color planes\n\tqfmtBgr24\t\t\t\t= 8,\t// Common Windows format\n\tqfmtXrgb32\t\t\t\t= 9,\t// Format of Mac pixelmap\n\tqfmtRgb48\t\t\t\t= 10,\n\tqfmtBgrx32\t\t\t\t= 11,\t// Common Windows format\n\tqfmt_last\t\t\t\t= 12\n}\nQCam_ImageFormat;\n\n//\n// Deprecated parameters:\n// Gain\t\t- Cameras produced after Mar 1, 2004 will no longer support the\n//\t\t\t parameter \"qprmGain\". The normalized gain parameter\n//\t\t\t \"qprmNormalizedGain\" must be used in its place.\n//\t\t\t Consult API documentation for more details.\n// Offset - Cameras produced after Mar 1, 2004 will no longer support the\n//\t\t\t parameter \"qprmOffset\". The absolute offset parameter\n//\t\t\t \"qprmS32AbsoluteOffset\" must be used in its place.\n//\t\t\t Consult API documentation for more details.\n\ntypedef enum\n{\n\tqprmGain\t\t\t\t= 0,\t// Camera gain (gain on CCD output)\n\tqprmOffset\t\t\t\t= 1,\t// Camera offset (offset in CCD ADC)\n\tqprmExposure\t\t\t= 2,\t// Exposure in microseconds\n\tqprmBinning\t\t\t\t= 3,\t// Binning, for cameras with square binning\n\tqprmHorizontalBinning\t= 4,\t// Binning, if camera has separate horiz value\n\tqprmVerticalBinning\t\t= 5,\t// Binning, if camera has separate vert value\n\tqprmReadoutSpeed\t\t= 6,\t// See readout speed constants\n\tqprmTriggerType\t\t\t= 7,\t// See trigger constants\n\tqprmColorWheel\t\t\t= 8,\t// Manual control of wheel color\n\tqprmCoolerActive\t\t= 9,\t// 1 turns on cooler, 0 turns off\n\tqprmExposureRed\t\t\t= 10,\t// For LCD filter mode: exposure (ms) of red shot\n\tqprmExposureBlue\t\t= 11,\t// For LCD filter mode: exposure (ms) of green shot\n\tqprmImageFormat\t\t\t= 12,\t// See QCam_ImageFormat\n\tqprmRoiX\t\t\t\t= 13,\t// Upper left X of ROI\n\tqprmRoiY\t\t\t\t= 14,\t// Upper left Y of ROI\n\tqprmRoiWidth\t\t\t= 15,\t// Width of ROI, in pixels\n\tqprmRoiHeight\t\t\t= 16,\t// Height of ROI, in pixels\n\tqprmReserved1\t\t\t= 17,\n\tqprmShutterState\t\t= 18,\t// Shutter position\n\tqprmReserved2\t\t\t= 19,\n\tqprmSyncb\t\t\t\t= 20,\t// SyncB output on some model-B cameras\n\tqprmReserved3\t\t\t= 21,\n\tqprmIntensifierGain\t\t= 22,\t// Gain value for the intensifier (Intensified cameras only)\n\tqprmTriggerDelay\t\t= 23,\t// Trigger delay in nanoseconds.\n\tqprmCameraMode\t\t\t= 24,\t// Camera mode\n\tqprmNormalizedGain\t\t= 25,\t// Normalized camera gain (micro units)\n\tqprmNormIntensGaindB\t= 26,\t// Normalized intensifier gain dB (micro units)\n \tqprm_last\t\t\t\t= 27,\n\t_qprm_force32\t\t\t= 0xFFFFFFFF\n}\nQCam_Param;\n\ntypedef enum\n{\n\tqprmS32NormalizedGaindB = 0,\t// Normalized camera gain in dB (micro units)\n\tqprmS32AbsoluteOffset\t= 1,\t// Absolute camera offset (offset in CCD ADC)\n\tqprmS32_last\t\t\t= 2,\n\t_qprmS32_force32\t\t= 0xFFFFFFFF\n}\nQCam_ParamS32;\n\ntypedef enum\n{\n\tqprm64Exposure\t\t= 0,\t\t// Exposure in nanoseconds\n\tqprm64ExposureRed\t= 1,\t\t// For LCD filter mode: exposure (ns) of red shot\n\tqprm64ExposureBlue\t= 2,\t\t// For LCD filter mode: exposure (ns) of green shot\n\tqprm64NormIntensGain= 3,\t\t// Normalized intensifier gain (micro units)\n \tqprm64_last\t\t\t= 4,\n\t_qprm64_force32\t\t= 0xFFFFFFFF\n}\nQCam_Param64;\n\ntypedef enum\n{\n\tqinfCameraType\t\t\t= 0,\n\tqinfSerialNumber\t\t= 1,\t// Only for model-A (not MicroPublishers);\n\t\t\t\t\t\t\t\t\t// otherwise returns 0\n\tqinfHardwareVersion\t\t= 2,\n\tqinfFirmwareVersion\t\t= 3,\n\tqinfCcd\t\t\t\t\t= 4,\n\tqinfBitDepth\t\t\t= 5,\t// Maximum number of bits\n\tqinfCooled\t\t\t\t= 6,\t// 1 if camera has cooler\n\tqinfReserved1\t\t\t= 7,\t// Factory test values\n\tqinfImageWidth\t\t\t= 8,\t// Width of ROI, in pixels\n\tqinfImageHeight\t\t\t= 9,\t// Height of ROI, in pixels\n\tqinfImageSize\t\t\t= 10,\t// Size of image, in bytes\n\tqinfCcdType\t\t\t\t= 11,\t// Monochrome, bayer, etc.\n\tqinfCcdWidth\t\t\t= 12,\t// Maximum width\n\tqinfCcdHeight\t\t\t= 13,\t// Maximum height\n\tqinfFirmwareBuild\t\t= 14,\n\tqinfUniqueId\t\t\t= 15,\t// Same as uniqueId in QCam_CamListItem\n\tqinfIsModelB\t\t\t= 16,\t// 1 for model-B functionality, 0 otherwise\n\tqinfIntensifierModel\t= 17,\t// Intensifier tube model, see QCam_qcIntensifierModel\n\tqinfExposureRes\t\t\t= 18,\t// Exposure Time resolution (in nanoseconds)\n\tqinfTriggerDelayRes\t\t= 19, \t// Trigger Delay Resolution (in nanoseconds)\n\tqinfStreamVersion\t\t= 20,\t// Streaming Version\n\tqinfNormGainSigFigs\t\t= 21,\t// Normalized Gain Significant Figures resolution\n\tqinfNormGaindBRes\t\t= 22,\t// Normalized Gain dB resolution (micro units)\n\tqinfNormITGainSigFigs\t= 23,\t// Normalized Intensifier Gain Significant Figures\n\tqinfNormITGaindBRes\t\t= 24,\t// Normalized Intensifier Gain dB resolution (micro units)\n\tqinf_last\t\t\t\t= 25,\n\t_qinf_force32\t\t\t= 0xFFFFFFFF\n}\nQCam_Info;\n\ntypedef void* QCam_Handle;\n\n\ntypedef struct\n{\n\tunsigned long size;\t\t// You must set this to sizeof( QCam_Settings )\n\tunsigned long _private_data[ 64 ];\n}\nQCam_Settings;\n\n\ntypedef struct\n{\n\tunsigned long\t\tcameraId;\n\tunsigned long\t\tcameraType;\n\tunsigned long\t\tuniqueId;\n\tunsigned long\t\tisOpen;\t\t\t\t// 1 if already open\n\n\tunsigned long\t\t_reserved[ 10 ];\n}\nQCam_CamListItem;\n\n\n//\n// For calls to QCam_GrabFrame() etc...\n//\n// These fields must be filled before the Api call:\n//\t\tpBuffer\n//\t\tbufferSize\n//\n// These fields are set (by QCam) during the Api call:\n//\t\tformat\n//\t\twidth\n//\t\theight\n//\t\tsize\n//\t\tbits\n//\t\tframeNumber\n//\t\tbayerPattern\n//\t\terrorCode\n//\t\ttimeStamp\n//\ntypedef struct\n{\n\tvoid*\t\t\t\tpBuffer;\t\t\t// Image buffer, 4-byte aligned\n\tunsigned long\t\tbufferSize;\t\t\t// Length of buffer, in bytes\n\n\tunsigned long\t\tformat;\t\t\t\t// Format of image\n\tunsigned long\t\twidth;\t\t\t\t// Image width, in pixels\n\tunsigned long\t\theight;\t\t\t\t// Image height, in pixels\n\tunsigned long\t\tsize;\t\t\t\t// Size of image data, in bytes\n\tunsigned short\t\tbits;\t\t\t\t// Bit depth\n\tunsigned short\t\tframeNumber;\t\t// Rolling frame number\n\tunsigned long\t\tbayerPattern;\t\t// For bayer CCDs: mosaic pattern\n\tunsigned long\t\terrorCode;\t\t\t// QCam_Err-type code for this frame\n\tunsigned long\t\ttimeStamp;\t\t\t// Exposure time stamp\n\n\tunsigned long\t\t_reserved[ 8 ];\n}\nQCam_Frame;\n\n\ntypedef void ( QCAMAPI *QCam_AsyncCallback )\n(\n\tvoid*\t\t\t\tuserPtr,\t\t\t// User defined\n\tunsigned long\t\tuserData,\t\t\t// User defined\n\tQCam_Err\t\t\terrcode,\t\t\t// Error code\n\tunsigned long\t\tflags\t\t\t\t// Combination of QCam_qcCallbackFlags\n);\n\n\n//===== FUNCTION PROTOTYPES ===================================================\n\n//-----\tLoading and releasing the QCam driver -----\n\n// Load the QCam driver. Call before using any QCam Api functions.\nextern QCam_Err QCAMAPI QCam_LoadDriver\n(\n\tvoid\n);\n\n// Release the QCam driver.\nextern void QCAMAPI QCam_ReleaseDriver\n(\n\tvoid\n);\n\n// Get the version of this module (the QCam Driver).\nextern QCam_Err QCAMAPI QCam_LibVersion\n(\n\tunsigned short*\t\tverMajor,\n\tunsigned short*\t\tverMinor,\n\tunsigned short*\t\tverBuild\n);\n\n//----- Listing, opening, and closing cameras -----\n\n// List the connected cameras.\nextern QCam_Err QCAMAPI QCam_ListCameras\n(\n\tQCam_CamListItem*\tpList,\t\t\t\t// IN: ptr to array of items\n\tunsigned long*\t\tpNumberInList\t\t// IN: length of list (array)\n\t\t\t\t\t\t\t\t\t\t\t// OUT: number of cameras; may be\n\t\t\t\t\t\t\t\t\t\t\t// greater than array length!\n);\n\n// Open a camera.\nextern QCam_Err QCAMAPI QCam_OpenCamera\n(\n\tunsigned long\t\tcameraId,\t\t\t// IN: Id of camera to open\n\tQCam_Handle*\t\tpHandle\t\t\t\t// OUT: handle to camera \n);\n\n// Close a camera.\nextern QCam_Err QCAMAPI QCam_CloseCamera\n(\n\tQCam_Handle\t\t\thandle\t\t\t\t// IN: handle to camera\n);\n\n//----- Retrieving information from the camera -----\n\n// Only for model-B and all MicroPublisher cameras.\nextern QCam_Err QCAMAPI QCam_GetSerialString\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to camera\n\tchar*\t\t\t\tstring,\t\t\t\t// IN: destination of string copy\n\tunsigned long\t\tsize\t\t\t\t// IN: size of string buffer\n);\n\nextern QCam_Err QCAMAPI QCam_GetInfo\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to camera\n\tQCam_Info\t\t\tinfoKey,\t\t\t// IN: information key\n\tunsigned long*\t\tpValue\t\t\t\t// OUT: information value\n);\n\n//----- Sending and receiving camera settings -----\n//\n// The camera settings (which determines the camera mode) is sent to the\n// camera all at once. The QCam_Settings structure represents all the camera\n// parameters. For example, you might read the settings structure from the\n// camera, change the exposure parameter and the binning parameters, then\n// write the settings structure back to the camera.\n//\n// The QCam_Settings struct is an opaque structure. Access the structure\n// with QCam_GetParam() and QCam_SetParam(). The QCam_Settings struct can\n// be saved or restored from a file, and is forward and backward compatible\n// as the QCam driver evolves.\n//\n// A new QCam_Settings struct must be initialized by a call to\n// QCam_ReadDefaultSettings() or QCam_ReadSettingsFromCam().\n//\n// A QCam_Settings struct is associated with the camera by which it was\n// initialized. If you have a QCam_Settings struct for one camera (say\n// camera A) and want to use it for a different camera (say camera B), or\n// if your QCam_Settings struct was loaded from a file, call the following\n// function:\n//\n//\t\tQCam_TranslateSettings()\t- fix the settings (from camera A) so\n//\t\t\t\t\t\t\t\t\t they work on camera B; this involves\n//\t\t\t\t\t\t\t\t\t changing bad or unsupported paramters\n//\t\t\t\t\t\t\t\t\t to camera B's default values\n//\n// After this call, the QCam_Settings struct is associated with the new\n// camera.\n//\n\n// Get the camera's default settings.\nextern QCam_Err QCAMAPI QCam_ReadDefaultSettings\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to camera\n\tQCam_Settings*\t\tpSettings\t\t\t// IN: opaque settings struct\n);\n\n// Read camera settings.\nextern QCam_Err QCAMAPI QCam_ReadSettingsFromCam\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to camera\n\tQCam_Settings*\t\tpSettings\t\t\t// IN: opaque settings struct\n);\n\n// Set the camera. Your settings struct reflects any tweaking required\n// (specifically, roi parameters).\nextern QCam_Err QCAMAPI QCam_SendSettingsToCam\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to camera\n\tQCam_Settings*\t\tpSettings\t\t\t// IN: opaque settings struct\n);\n\n// Changes your settings struct just as with QCam_SendSettingsToCam(), but\n// does not actually set the camera.\nextern QCam_Err QCAMAPI QCam_PreflightSettings\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to camera\n\tQCam_Settings*\t\tpSettings\t\t\t// IN: opaque settings struct\n);\n\n// Translate a settings struct so another camera can use it. Parameters which\n// are out of range or unsupported on the new camera are set to their default\n// values. After this call, you can set and get parameters from the\n// translated QCam_Settings struct.\nextern QCam_Err QCAMAPI QCam_TranslateSettings\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to a camera\n\tQCam_Settings*\t\tpSettings\t\t\t// IN: opaque settings struct\n\t\t\t\t\t\t\t\t\t\t\t// initialized by another camera\n);\n\n\n//-----\tModifying parameters in the camera settings struct -----\n//\n// These functions allow access to individual parameters in the QCam_Settings\n// structure.\n//\n// Before using these functions, the QCam_Settings struct must have been\n// initialized by one of the following:\n//\n//\t\tQCam_ReadDefaultSettings()\n//\t\tQCam_ReadSettingsFromCam()\n//\t\tQCam_TranslateSettings()\n//\n// All of the above functions require a camera handle, ie. the camera\n// must first be opened.\n//\n// Parameters can be one of three different types\n// 1. Unsigned 32 bit (QCam_Param)\n// 2. Signed 32 bit (QCam_ParamS32)\n// 3. Unsigned 64 bit (QCam_Param64)\n//\n// Range tables and sparse tables support all the above types.\n\n\n// Get parameter from settings struct.\nextern QCam_Err QCAMAPI QCam_GetParam\n(\n\tQCam_Settings const* pSettings,\t\t\t// IN: opaque settings struct\n\tQCam_Param\t\t\tparamKey,\t\t\t// IN: parameter key\n\tunsigned long*\t\tpValue\t\t\t\t// OUT: parameter value\n);\n\nextern QCam_Err QCAMAPI QCam_GetParamS32\n(\n\tQCam_Settings const* pSettings,\t\t\t// IN: opaque settings struct\n\tQCam_ParamS32\t\tparamKey,\t\t\t// IN: parameter key\n\tsigned long*\t\tpValue\t\t\t\t// OUT: parameter value\n);\n\nextern QCam_Err QCAMAPI QCam_GetParam64\n(\n\tQCam_Settings const* pSettings,\t\t\t// IN: opaque settings struct\n\tQCam_Param64 \t\tparamKey,\t\t\t// IN: parameter key\n\tUNSIGNED64*\t\t\tpValue\t\t\t\t// OUT: parameter value\n);\n\n\n// Set a parameter in a settings struct.\nextern QCam_Err QCAMAPI QCam_SetParam\n(\n\tQCam_Settings*\t\tpSettings,\t\t\t// IN: opaque settings struct\n\tQCam_Param\t\t\tparamKey,\t\t\t// IN: parameter key\n\tunsigned long\t\tvalue\t\t\t\t// IN: parameter key\n);\n\nextern QCam_Err QCAMAPI QCam_SetParamS32\n(\n\tQCam_Settings*\t\tpSettings,\t\t\t// IN: opaque settings struct\n\tQCam_ParamS32\t\tparamKey,\t\t\t// IN: parameter key\n\tsigned long\t\t\tvalue\t\t\t\t// IN: parameter key\n);\n\nextern QCam_Err QCAMAPI QCam_SetParam64\n(\n\tQCam_Settings*\t\tpSettings,\t\t\t// IN: opaque settings struct\n\tQCam_Param64\t\tparamKey,\t\t\t// IN: parameter key\n\tUNSIGNED64\t\t\tvalue\t\t\t\t// IN: parameter key\n);\n\n// Get the parameter minimum.\nextern QCam_Err QCAMAPI QCam_GetParamMin\n(\n\tQCam_Settings const*\tpSettings,\t\t// IN: opaque settings struct\n\tQCam_Param\t\t\t\tparamKey,\t\t// IN: parameter key\n\tunsigned long*\t\t\tpValue\t\t\t// OUT: parameter minimum\n);\n\nextern QCam_Err QCAMAPI QCam_GetParamS32Min\n(\n\tQCam_Settings const*\tpSettings,\t\t// IN: opaque settings struct\n\tQCam_ParamS32\t\t\tparamKey,\t\t// IN: parameter key\n\tsigned long*\t\t\tpValue\t\t\t// OUT: parameter minimum\n);\n\nextern QCam_Err QCAMAPI QCam_GetParam64Min\n(\n\tQCam_Settings const*\tpSettings,\t\t// IN: opaque settings struct\n\tQCam_Param64\t\t\tparamKey,\t\t// IN: parameter key\n\tUNSIGNED64*\t\t\t\tpValue\t\t\t// OUT: parameter minimum\n);\n\n// Get the parameter maximum.\nextern QCam_Err QCAMAPI QCam_GetParamMax\n(\n\tQCam_Settings const*\tpSettings,\t\t// IN: opaque settings struct\n\tQCam_Param\t\t\t\tparamKey,\t\t// IN: parameter key\n\tunsigned long*\t\t\tpValue\t\t\t// OUT: parameter maximum\n);\n\nextern QCam_Err QCAMAPI QCam_GetParamS32Max\n(\n\tQCam_Settings const*\tpSettings,\t\t// IN: opaque settings struct\n\tQCam_ParamS32\t\t\tparamKey,\t\t// IN: parameter key\n\tsigned long*\t\t\tpValue\t\t\t// OUT: parameter maximum\n);\n\nextern QCam_Err QCAMAPI QCam_GetParam64Max\n(\n\tQCam_Settings const*\tpSettings,\t\t// IN: opaque settings struct\n\tQCam_Param64\t\t\tparamKey,\t\t// IN: parameter key\n\tUNSIGNED64*\t\t\t\tpValue\t\t\t// OUT: parameter maximum\n);\n\n// Get the parameter sparse table\nextern QCam_Err QCAMAPI QCam_GetParamSparseTable\n(\n\tQCam_Settings const*\tpSettings,\t\t// IN: opaque settings struct\n\tQCam_Param\t\t\t\tparamKey,\t\t// IN: parameter key\n\tunsigned long*\t\t\tpSparseTable,\t// OUT: parameter sparse table\n\tint*\t\t\t\t\tuSize\t\t\t// IN: size / OUT: number of entries\n);\n\nextern QCam_Err QCAMAPI QCam_GetParamSparseTableS32\n(\n\tQCam_Settings const*\tpSettings,\t\t// IN: opaque settings struct\n\tQCam_ParamS32\t\t\tparamKey,\t\t// IN: parameter key\n\tsigned long*\t\t\tpSparseTable,\t// OUT: parameter sparse table\n\tint*\t\t\t\t\tuSize\t\t\t// IN: size / OUT: number of entries\n);\n\nextern QCam_Err QCAMAPI QCam_GetParamSparseTable64\n(\n\tQCam_Settings const*\tpSettings,\t\t// IN: opaque settings struct\n\tQCam_Param64\t\t\tparamKey,\t\t// IN: parameter key\n\tUNSIGNED64*\t\t\t\tpSparseTable,\t// OUT: parameter sparse table\n\tint*\t\t\t\t\tuSize\t\t\t// IN: size / OUT: number of entries\n);\n\n// Returns qerrSuccess if SparseTabling supported, qerrNotSupported otherwise\nextern QCam_Err QCAMAPI QCam_IsSparseTable\n(\n\tQCam_Settings const*\tpSettings,\t\t// IN: opaque settings struct\n\tQCam_Param\t\t\t\tparamKey\t\t// IN: parameter key\n);\n\nextern QCam_Err QCAMAPI QCam_IsSparseTableS32\n(\n\tQCam_Settings const*\tpSettings,\t\t// IN: opaque settings struct\n\tQCam_ParamS32\t\t\tparamKey\t\t// IN: parameter key\n);\n\nextern QCam_Err QCAMAPI QCam_IsSparseTable64\n(\n\tQCam_Settings const*\tpSettings,\t\t// IN: opaque settings struct\n\tQCam_Param64\t\t\tparamKey\t\t// IN: parameter key\n);\n\n// Returns qerrSuccess if RangeTabling supported, qerrNotSupported otherwise\nextern QCam_Err QCAMAPI QCam_IsRangeTable\n(\n\tQCam_Settings const*\tpSettings,\t\t// IN: opaque settings struct\n\tQCam_Param\t\t\t\tparamKey\t\t// IN: parameter key\n);\n\nextern QCam_Err QCAMAPI QCam_IsRangeTableS32\n(\n\tQCam_Settings const*\tpSettings,\t\t// IN: opaque settings struct\n\tQCam_ParamS32\t\t\tparamKey\t\t// IN: parameter key\n);\n\nextern QCam_Err QCAMAPI QCam_IsRangeTable64\n(\n\tQCam_Settings const*\tpSettings,\t\t// IN: opaque settings struct\n\tQCam_Param64\t\t\tparamKey\t\t// IN: parameter key\n);\n\n\n// Is a parameter supported on this camera? Returns qerrSuccess if supported,\n// qerrNotSupported if not available.\nextern QCam_Err QCAMAPI QCam_IsParamSupported\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to a camera\n\tQCam_Param\t\t\tparamKey\t\t\t// IN: parameter key\n);\n\nextern QCam_Err QCAMAPI QCam_IsParamS32Supported\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to a camera\n\tQCam_ParamS32\t\tparamKey\t\t\t// IN: parameter key\n);\n\nextern QCam_Err QCAMAPI QCam_IsParam64Supported\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to a camera\n\tQCam_Param64\t\tparamKey\t\t\t// IN: parameter key\n);\n\n\n//-----\tFrame grabbing misc -----\n\n// Start/stop firewire streaming. The camera's firewire port must be streaming\n// continuously to transmit an image. If you call a Grab() function without\n// firewire streaming on, the QCam driver will start streaming, capture the\n// image, then stop streaming. For higher frame rates, such as preview mode,\n// it is an advantage to turn on firewire streaming manually. (The disadvantage\n// of firewire streaming when you are not capturing images: the OS must process\n// empty firewire packets.)\nextern QCam_Err QCAMAPI QCam_SetStreaming\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to a camera\n\tunsigned long\t\tenable\t\t\t\t// IN: non-0 to enable, 0 to disable\n);\n\n// Trigger an exposure to start (software trigger). The trigger mode must be\n// set to a hardware or software-only mode. Firewire streaming must be started\n// (see QCam_SetStreaming).\n//\n// You can guarantee that the frame resulting from QCam_Trigger was exposed\n// after this function call was entered.\n//\n// WARNING: Software triggering is unreliable in model-A cameras! See SDK\n// documentation. If you need QCam_Trigger(), you should consider restricting\n// your support to model-B cameras. (Model-A MicroPublishers also do not have\n// reliable software triggering.)\nextern QCam_Err QCAMAPI QCam_Trigger\n(\n\tQCam_Handle\t\t\thandle\t\t\t\t// IN: handle to a camera\n);\n\n// Stop all pending frame-grabs, and clear the queue. You will not receive\n// any more QueueFrame() and QueueSettings() callbacks after this function\n// has returned.\nextern QCam_Err QCAMAPI QCam_Abort\n(\n\tQCam_Handle\t\t\thandle\t\t\t\t// IN: handle to camera\n);\n\n\n//----- Frame grabbing synchronous -----\n\nextern QCam_Err QCAMAPI QCam_GrabFrame\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to a camera\n\tQCam_Frame*\t\t\tpFrame\t\t\t\t// IN: frame\n);\n\n\n//-----\tFrame grabbing, camera settings - asynchronous -----\n\n// Queue a frame buffer. Returns immediately. Callback occurs when the frame\n// has been captured. The frame struct and associated buffer must persist until\n// the frame has been grabbed.\nextern QCam_Err QCAMAPI QCam_QueueFrame\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to camera\n\tQCam_Frame*\t\t\tpFrame,\t\t\t\t// IN: frame\n\tQCam_AsyncCallback\tcallback,\t\t\t// IN: completion callback; can be NULL\n\tunsigned long\t\tcbFlags,\t\t\t// IN: qcCallbackFlags\n\tvoid*\t\t\t\tuserPtr,\t\t\t// IN: user specified value for callback\n\tunsigned long\t\tuserData\t\t\t// IN: user specified value for callback\n);\n\n// Queue a change in camera settings. Returns immediately. Callback occurs\n// when the settings are changed. Your settings structure must persist until\n// the settings have been changed.\nextern QCam_Err QCAMAPI QCam_QueueSettings\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to camera\n\tQCam_Settings*\t\tpSettings,\t\t\t// IN: settings struct\n\tQCam_AsyncCallback\tcallback,\t\t\t// IN: completion callback; can be NULL\n\tunsigned long\t\tcbFlags,\t\t\t// IN: qcCallbackFlags\n\tvoid*\t\t\t\tuserPtr,\t\t\t// IN: user specified value for callback\n\tunsigned long\t\tuserData\t\t\t// IN: user specified value for callback\n);\n\n\n//----- Deprecated functions -----\n//\n// Please use the alternative API call \"QCam_LibVersion\" \"QCam_LibVersion\"\n// is identical to \"QCam_Version\" but it also returns the library build \n// version.\n// Get the version of this module (the QCam Driver).\nextern QCam_Err QCAMAPI QCam_Version\n(\n\tunsigned short*\t\tverMajor,\n\tunsigned short*\t\tverMinor\n);\n\n// These functions were written when only synchronous frame-grabbing was\n// available. Since postprocessing was required in some formats, the full\n// frame rate could be achieved only by post-processing on a second thread.\n// If you are tempted to use these functions in a new project, please\n// reconsider your design.\n//\n\n// Setup the frame buffers, used to store image data.\nextern QCam_Err QCAMAPI QCam_SetFrameBuffers\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to a camera\n\tQCam_Frame*\t\t\tpFrames,\t\t\t// IN: list of frames. Null Ok.\n\tunsigned long\t\tnumber\t\t\t\t// IN: number of frames in list\n);\n\n// Grab one frame. Returns when one frame has been received and processed.\nextern QCam_Err QCAMAPI QCam_GrabFrameNow\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to camera\n\tunsigned long\t\tframeIndex\t\t\t// IN: index of frame to use\n);\n\n// Grab a raw frame. Returns when the raw frame has been grabbed. You must\n// call QCam_ProcessRaw() on this frame if your call to QCam_GrabRawNow()\n// succeeds.\nextern QCam_Err QCAMAPI QCam_GrabRawNow\n(\n\tQCam_Handle\t\t\thandle,\t\t\t\t// IN: handle to camera\n\tunsigned long\t\tframeIndex\t\t\t// IN: index of frame to use\n);\n\n// Process the raw data in a frame. You must call this function after\n// QCam_GrabRawNow() otherwise your data may not be formatted properly.\nextern QCam_Err QCAMAPI QCam_ProcessRaw\n(\n\tQCam_Handle\t\t\thandle,\n\tunsigned long\t\tframeIndex\n);\n\n\n\n#ifdef __cplusplus\n} // end extern \"C\"\n#endif\n\n#endif // QCAMAPI_H_INCLUDE\n" }, { "alpha_fraction": 0.5610510110855103, "alphanum_fraction": 0.5692206025123596, "avg_line_length": 27.6645565032959, "blob_id": "0f707bfd0947e00134d6ab0d69de26f42c538594", "content_id": "5a5341f5db3ffcf38a4130ecd3c56a137987d790", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4529, "license_type": "no_license", "max_line_length": 95, "num_lines": 158, "path": "/owl/PStyleChooser.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include \"PStyleChooser.h\"\n#include \"ui_PStyleChooser.h\"\n#include <QInputDialog>\n#include <QColorDialog>\n\nvoid PStyleNotifier::notifyChange()\n{\n if(on) {\n emit change();\n for(int i=0;i<PStyle::_u.size();i++) {\n PStyle::_u[i]->_dirty=0;\n }\n }\n}\n\nPStyleNotifier* PStyleNotifier::me=new PStyleNotifier;\nPStyle* PStyle::noStyle = 0;\nQList<PStyle*> PStyle::_u;\n\nPStyleChooser::PStyleChooser(QWidget *parent) :\n QWidget(parent), current(0),\n ui(new Ui::PStyleChooser)\n{\n ui->setupUi(this);\n connect(ui->comboBoxStyle,SIGNAL(currentIndexChanged(QString)),this,SLOT(select(QString)));\n ui->comboBoxStyle->view()->setMinimumWidth(width()*0.8);\n connect(ui->toolButtonB,SIGNAL(toggled(bool)),this,SLOT(boldLogic(bool)));\n connect(ui->toolButtonI,SIGNAL(toggled(bool)),this,SLOT(italicLogic(bool)));\n connect(ui->toolButtonBG,SIGNAL(clicked()),this,SLOT(bgLogic()));\n connect(ui->toolButtonFG,SIGNAL(clicked()),this,SLOT(fgLogic()));\n connect(PStyleNotifier::me,SIGNAL(change()),this,SLOT(refresh()));\n}\n\nPStyleChooser::~PStyleChooser()\n{\n delete ui;\n}\n\nvoid PStyleChooser::setWidgetStyleRef(PStyle *&style)\n{\n current=&style;\n}\n\nvoid PStyleChooser::select(QString s)\n{\n Q_ASSERT(current&&(*current));\n\n if(s==\"No Style\") {\n ui->toolButtonB->setEnabled(0);\n ui->toolButtonI->setEnabled(0);\n ui->toolButtonBG->setEnabled(0);\n ui->toolButtonFG->setEnabled(0);\n if(*current!=PStyle::noStyle) {\n (*current) = PStyle::noStyle;\n }\n } else if(s==\"New Style\") {\n bool ok;\n QString n=QInputDialog::getText(this,\"New Style\",\"Name\",QLineEdit::Normal,\"\",&ok);\n\n if(!ok) {\n return;\n }\n\n (*current) = new PStyle(n,0,0,\"white\",\"black\",1);\n ui->toolButtonB->setEnabled(1);\n ui->toolButtonI->setEnabled(1);\n ui->toolButtonBG->setEnabled(1);\n ui->toolButtonFG->setEnabled(1);\n PStyleNotifier::me->notifyChange();\n ui->comboBoxStyle->setCurrentIndex(ui->comboBoxStyle->count()-1);\n } else {\n for(int i=0;i<PStyle::_u.size();i++) {\n if(s.contains(PStyle::_u[i]->idText())) {\n if(*current!=PStyle::_u[i]) {\n (*current) = PStyle::_u[i];\n ui->toolButtonB->setEnabled(1);\n ui->toolButtonI->setEnabled(1);\n ui->toolButtonBG->setEnabled(1);\n ui->toolButtonFG->setEnabled(1);\n }\n }\n }\n }\n\n if((*current)->isBold()!=ui->toolButtonB->isChecked()) {\n ui->toolButtonB->setChecked((*current)->isBold());\n }\n\n if((*current)->isItalic()!=ui->toolButtonI->isChecked()) {\n ui->toolButtonI->setChecked((*current)->isItalic());\n }\n}\n\nvoid PStyleChooser::boldLogic(bool b)\n{\n Q_ASSERT(current&&(*current));\n (*current)->setBold(b);\n}\n\nvoid PStyleChooser::italicLogic(bool b)\n{\n Q_ASSERT(current&&(*current));\n (*current)->setItalic(b);\n}\n\nvoid PStyleChooser::fgLogic()\n{\n Q_ASSERT(current&&(*current));\n QColor c=QColorDialog::getColor((*current)->fgColour());\n if(c.isValid()) {\n (*current)->setFg(c);\n }\n}\n\nvoid PStyleChooser::bgLogic()\n{\n Q_ASSERT(current&&(*current));\n QColor c=QColorDialog::getColor((*current)->bgColour());\n if(c.isValid()) {\n (*current)->setBg(c);\n }\n}\n\nvoid PStyleChooser::refresh()\n{\n if(!current||!(*current))\n {\n return;\n }\n for(int i=0;i<PStyle::_u.size();i++) {\n bool ok=0;\n for(int j=0;j<ui->comboBoxStyle->count();j++) {\n if(ui->comboBoxStyle->itemText(j).contains(PStyle::_u[i]->idText())) {\n ok=1;\n break;\n }\n }\n if(!ok) {\n ui->comboBoxStyle->addItem(PStyle::_u[i]->name()+\" \"+PStyle::_u[i]->idText());\n }\n }\n if((*current)==PStyle::noStyle) {\n ui->comboBoxStyle->setCurrentIndex(0);\n ui->toolButtonB->setEnabled(0);\n ui->toolButtonI->setEnabled(0);\n ui->toolButtonBG->setEnabled(0);\n ui->toolButtonFG->setEnabled(0);\n } else for(int i=2;i<ui->comboBoxStyle->count();i++) {\n if(ui->comboBoxStyle->itemText(i).contains((*current)->idText())) {\n ui->comboBoxStyle->setCurrentIndex(i);\n ui->toolButtonB->setEnabled(1);\n ui->toolButtonI->setEnabled(1);\n ui->toolButtonBG->setEnabled(1);\n ui->toolButtonFG->setEnabled(1);\n break;\n }\n }\n}\n" }, { "alpha_fraction": 0.6008896231651306, "alphanum_fraction": 0.6069551110267639, "avg_line_length": 32.863014221191406, "blob_id": "ef500af9cb0c29ad24407fa12a5aede0619289a0", "content_id": "54eaa96e00821f42a0e94339c36f5d32046e06e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2473, "license_type": "no_license", "max_line_length": 97, "num_lines": 73, "path": "/stars/utilities/ebex_images/diff_raw_with_fits.py", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\nimport os\nimport sys\nimport pyfits\nimport pylab\n\ndef load_raw_data(filename):\n infile = open(filename, \"r\")\n data = pylab.fromstring(infile.read(), \"uint16\")\n infile.close()\n return data\n\ndef load_fits_data(filename):\n infile = pyfits.open(filename)\n data = infile[0].data.flatten()\n infile.close()\n return data\n\ndef diff_image(raw_filename, fits_filename, verbose=False):\n filestem_raw = os.path.splitext(os.path.split(raw_filename)[-1])[0]\n filestem_fits = os.path.splitext(os.path.split(fits_filename)[-1])[0]\n if filestem_fits != filestem_raw:\n print \"warning: files %s and %s don't have the same stem\" % (filestem_raw, filestem_fits)\n if verbose:\n print \"comparison:\"\n raw_data = load_raw_data(raw_filename)\n if verbose:\n print \"%64s --\" % raw_filename,\n print raw_data\n fits_data = load_fits_data(fits_filename)\n if verbose:\n print \"%64s --\" % fits_filename,\n print fits_data\n differ = False\n if len(raw_data) != len(fits_data):\n differ = True\n elif (raw_data-fits_data).any():\n differ = True\n if differ:\n print \"file %s contents differ\" % filestem_raw\n else:\n print \"file %s contents are identical\" % filestem_raw\n\ndef diff_dir(raw_dirname, fits_dirname):\n for raw_filename in os.listdir(raw_dirname):\n match_found = False\n for fits_filename in os.listdir(fits_dirname):\n full_raw_filename = os.path.join(raw_dirname, raw_filename)\n full_fits_filename = os.path.join(fits_dirname, fits_filename)\n raw_stem = os.path.splitext(raw_filename)[0]\n fits_stem = os.path.splitext(fits_filename)[0]\n if raw_stem == fits_stem:\n match_found = True\n diff_image(full_raw_filename, full_fits_filename, verbose=False)\n if not match_found:\n print \"could not find match for raw image\", raw_filename\n \n\ndef main():\n try:\n raw_filename = sys.argv[1]\n fits_filename = sys.argv[2]\n except IndexError:\n print \"Usage: ./diff_raw_with_fits.py raw_filename fits_filename\"\n return\n if os.path.isdir(raw_filename) and os.path.isdir(fits_filename):\n diff_dir(raw_filename, fits_filename)\n else:\n diff_image(raw_filename, fits_filename, verbose=True)\n\nif __name__ == \"__main__\":\n sys.exit(main())\n\n" }, { "alpha_fraction": 0.6838709712028503, "alphanum_fraction": 0.6838709712028503, "avg_line_length": 24.66666603088379, "blob_id": "95fbe118089eb90ce88136c4902c119ac0f0ace5", "content_id": "1bffa790be0119bb4fc055d80c05cc150e2dee4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 155, "license_type": "no_license", "max_line_length": 58, "num_lines": 6, "path": "/install_scripts.sh", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\nINSTALL_DIR=\"/usr/local/bin/\"\n\nsudo ln -s $(pwd)/install_and_restart_mcp.sh $INSTALL_DIR \nsudo ln -s $(pwd)/restart_blastgs.sh $INSTALL_DIR \n" }, { "alpha_fraction": 0.4819960594177246, "alphanum_fraction": 0.5553327798843384, "avg_line_length": 81.03135681152344, "blob_id": "9f92b3c87f35daadcfea3ad3c43f4ac7e8d07604", "content_id": "9dc04d5db3d3b413ccf1b4e088e019aa617164e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 149134, "license_type": "no_license", "max_line_length": 116, "num_lines": 1818, "path": "/blast_config/tx_struct_tng.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n * tx_struct_tng.c: \n *\n * This software is copyright \n * (C) 2013-2014 California State University, Sacramento\n * (C) 2014-2016 University of Pennsylvania\n *\n * This file is part of mcp, created for the BLASTPol Project.\n *\n * mcp 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 2 of the License, or\n * (at your option) any later version.\n *\n * mcp 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 mcp; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * History:\n * Created on: Aug 5, 2014 by seth\n */\n\n#include <limits.h>\n\n#include \"channels_tng.h\"\n#include \"calibrate.h\"\n#include \"conversions.h\"\n/* Analog channel calibrations */\n/* 16-bit channels with analog preamps. To Volts */\n#define CAL16(m, b) ((m)*M_16PRE), ((b) + B_16PRE*(m)*M_16PRE)\n/* bare thermistor. To Volts. Use LUT for temperature conversion */\n#define CAL16T(m, b) ((m)*M_16T), ((b) + B_16T*(m)*M_16T)\n/* AD590 conversion. To Celsius */\n#define CAL_AD590(m, b) ((m)*M_16_AD590), ((b)+B_16_AD590*(m)*M_16_AD590-273.15)\n\n#define U_NONE \"\", \"\"\n#define U_T_C \"Temperature\", \"^oC\"\n#define U_T_K \"Temperature\", \"K\"\n#define U_P_PSI \"Pressure\", \"PSI\"\n#define U_V_DPS \"Rate\", \"^o/s\"\n#define U_V_MPS \"Speed\", \"m/s\"\n#define U_V_KPH \"Speed\", \"km/hr\"\n#define U_ALT_M \"Altitude\", \"m\"\n#define U_P_DEG \"Position\", \"^o\"\n#define U_LA_DEG \"Latitude\", \"^o\"\n#define U_LO_DEG \"Longitude\", \"^o\"\n#define U_D_DEG \"Direction\", \"^o\"\n#define U_V_V \"Voltage\", \"V\"\n#define U_I_A \"Current\", \"A\"\n#define U_T_MS \"Time\", \"ms\"\n#define U_T_S \"Time\", \"s\"\n#define U_T_MIN \"Time\", \"min\"\n#define U_R_O \"Resistance\", \"Ohms\"\n#define U_RATE \"Rate\", \"bps\"\n#define U_GB \"\", \"GB\"\n#define U_TRIM_DEG \"Trim\", \"^o\"\n#define U_TRIM_MM \"Trim\", \"mm\"\n\n// #define NO_KIDS_TEST\n\n#define SCALE(_type) _type ## _M, _type ## _B\n// TODO(seth): Unify the _M, _B scale factor offset terms in a single location\n\nchannel_t channel_list[] =\n{\n { \"test_values\", SCALE(CRYO_D), TYPE_UINT16, RATE_200HZ, U_V_V, 0 },\n { \"heater_status_write\", 1, 0, TYPE_UINT16, RATE_1HZ, U_NONE, 0},\n { \"heater_status_read\", 1, 0, TYPE_UINT16, RATE_1HZ, U_NONE, 0},\n { \"cycle_state\", 1, 0, TYPE_UINT8, RATE_1HZ, U_NONE, 0},\n { \"pulse_timer\", 1, 0, TYPE_UINT16, RATE_1HZ, U_NONE, 0},\n { \"time_to_pulse\", 1, 0, TYPE_UINT16, RATE_1HZ, U_NONE, 0},\n { \"cycle_allowed\", 1, 0, TYPE_UINT16, RATE_1HZ, U_NONE, 0},\n { \"wd_allowed\", 1, 0, TYPE_UINT16, RATE_1HZ, U_NONE, 0},\n { \"load_curve\", 1, 0, TYPE_FLOAT, RATE_1HZ, U_NONE, 0},\n { \"hawkeye\", 1, 0, TYPE_UINT8, RATE_200HZ, U_NONE, 0},\n { \"stage_chopper\", SCALE(CRYO_D), TYPE_UINT16, RATE_200HZ, U_V_V, 0 },\n { \"microscroll_a\", 1, 0, TYPE_UINT8, RATE_1HZ, U_NONE, 0},\n { \"microscroll_b\", 1, 0, TYPE_UINT8, RATE_1HZ, U_NONE, 0},\n\n { \"read_dio\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"tr_fpa_1k\", SCALE(CRYO_R), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"tr_250_fpa\", SCALE(CRYO_R), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"tr_1k_plate\", SCALE(CRYO_R), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"tr_300mk_strap\", SCALE(CRYO_R), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"tr_350_fpa\", SCALE(CRYO_R), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"tr_he4_pot\", SCALE(CRYO_R), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"tr_he3_fridge\", SCALE(CRYO_R), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"tr_500_fpa\", SCALE(CRYO_R), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"rox_bias\", SCALE(CRYO_R), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"bias_alsa_state_rox\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n // highbay gauges\n { \"n2_flow_v\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"he_blow_v\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"he_pot_hi_flow_v\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"he_pot_lo_flow_v\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"he_purge_flow_v\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"alarm_gauge\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"of_status\", 1, 0, TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"if_status\", 1, 0, TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"labjack_conn_status\", 1, 0, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n\n { \"td_charcoal_hs\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"td_vcs2_filt\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"td_250fpa\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"td_hwp\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"td_vcs1_hx\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"td_1k_fridge\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"td_4k_plate\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"td_vcs1_filt\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"td_m3\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"td_charcoal\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"td_ob_filter\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"td_vcs2_plate\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"td_m4\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"td_4k_filt\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"td_vcs2_hx\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"td_vcs1_plate\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n // random cryo labjack AINs\n { \"level_sensor_read\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"cal_lamp_read\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"heater_300mk_read\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n // below are the thermistor channels as well as the current loop channels\n { \"thermistor_1\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_2\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_3\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_4\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_5\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_6\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_7\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_8\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_9\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_10\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_11\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_12\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_13\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_14\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_15\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_16\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_17\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_18\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_19\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_20\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_21\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_22\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_23\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_24\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_25\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_26\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_27\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_28\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_29\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_30\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_31\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_32\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_33\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_34\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_35\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_36\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_37\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_38\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_39\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_40\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_41\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_42\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_43\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_44\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_45\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_46\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_47\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_48\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_49\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_50\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_51\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_52\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_53\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_54\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_55\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_56\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_57\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_58\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_59\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_60\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_61\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_62\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_63\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"thermistor_64\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"thermistor_65\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"thermistor_66\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"thermistor_67\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"thermistor_68\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"thermistor_69\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"thermistor_70\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"thermistor_71\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"thermistor_72\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"thermistor_73\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"thermistor_74\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"micro_thermistor_1\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"micro_thermistor_2\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"micro_thermistor_3\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"micro_thermistor_4\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"micro_thermistor_5\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"micro_thermistor_6\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"micro_thermistor_7\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"micro_thermistor_8\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"current_eth_switch\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"current_fc1\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"current_xsc0\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"current_fc2\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"current_xsc1\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"current_ele_mot\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"current_pivot\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"current_rw_mot\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"current_hd_pv\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"current_gyros\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"current_data_transmit\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n // { \"current_if1\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n // { \"current_if2\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n // { \"current_if3\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n // { \"current_if4\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n // { \"current_if5\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n // { \"current_if6\", SCALE(CURLOOP_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n\n // ADD CLINOMETER CHANNELS\n { \"clin_of_x\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_NONE, 0},\n { \"clin_of_y\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_NONE, 0},\n { \"clin_if_x\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_NONE, 0},\n { \"clin_if_y\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_NONE, 0},\n { \"clin_of_t\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_NONE, 0},\n { \"clin_if_t\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_NONE, 0},\n\n // below are the status channels\n { \"status_charcoal_heater\", 1, 0, TYPE_UINT8, RATE_1HZ, U_NONE, 0},\n { \"status_250_LNA\", 1, 0, TYPE_UINT8, RATE_1HZ, U_NONE, 0},\n { \"status_1K_heater\", 1, 0, TYPE_UINT8, RATE_1HZ, U_NONE, 0},\n { \"status_charcoal_hs\", 1, 0, TYPE_UINT8, RATE_1HZ, U_NONE, 0},\n { \"status_500_LNA\", 1, 0, TYPE_UINT8, RATE_1HZ, U_NONE, 0},\n { \"status_350_LNA\", 1, 0, TYPE_UINT8, RATE_1HZ, U_NONE, 0},\n { \"status_300mk_heater\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"status_cal_lamp\", SCALE(CRYO_D), TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n\n {\"x0_point_az_raw\", SCALE(CONVERT_ANGLE_DEG), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x0_point_az\", SCALE(CONVERT_WIDE_ANGLE_DEG), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n {\"x0_point_el_raw\", SCALE(CONVERT_ANGLE_DEG), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x0_point_el\", SCALE(CONVERT_WIDE_ANGLE_DEG), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n {\"x0_point_var\", SCALE(CONVERT_WIDE_ANGLE_DEG), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n {\"x0_point_sigma\", SCALE(CONVERT_WIDE_ANGLE_DEG), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n {\"x0_point_az_trim\", SCALE(CONVERT_ANGLE), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x0_point_el_trim\", SCALE(CONVERT_ANGLE), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x0_cd_robust_mode\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n\n {\"x1_point_az_raw\", CONVERT_ANGLE_DEG_M, CONVERT_ANGLE_DEG_B, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x1_point_az\", CONVERT_WIDE_ANGLE_DEG_M, CONVERT_ANGLE_DEG_B, TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n {\"x1_point_el_raw\", CONVERT_ANGLE_DEG_M, CONVERT_ANGLE_DEG_B, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x1_point_el\", CONVERT_WIDE_ANGLE_DEG_M, CONVERT_ANGLE_DEG_B, TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n {\"x1_point_var\", CONVERT_WIDE_ANGLE_DEG_M, CONVERT_ANGLE_DEG_B, TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n {\"x1_point_sigma\", CONVERT_WIDE_ANGLE_DEG_M, CONVERT_ANGLE_DEG_B, TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n {\"x1_point_az_trim\", CONVERT_ANGLE_M, CONVERT_ANGLE_B, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x1_point_el_trim\", CONVERT_ANGLE_M, CONVERT_ANGLE_B, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x1_cd_robust_mode\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n\n {\"x1_heater\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n {\"x0_heater\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n\n {\"x0_ctr_mcp\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_200HZ, U_NONE, 0 },\n {\"x0_last_trig_age_cs\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_200HZ, U_NONE, 0 },\n {\"x0_last_trig_ctr_mcp\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_200HZ, U_NONE, 0 },\n {\"x0_predicted_streaking_px\", CONVERT_VEL_M, CONVERT_VEL_B, TYPE_UINT16, RATE_200HZ, U_NONE, 0 },\n {\"x0_last_trig_ctr_stars\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_200HZ, U_NONE, 0 },\n {\"x0_image_blobn_x\", CONVERT_BLOB_POS_M, CONVERT_BLOB_POS_B, TYPE_UINT16, RATE_200HZ, U_NONE, 0 },\n {\"x0_image_blobn_y\", CONVERT_BLOB_POS_M, CONVERT_BLOB_POS_B, TYPE_UINT16, RATE_200HZ, U_NONE, 0 },\n {\"x0_image_blobn_flux\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_200HZ, U_NONE, 0 },\n {\"x0_image_blobn_peak_to_flux\", SCALE(CONVERT_0_TO_10), TYPE_UINT16, RATE_200HZ, U_NONE, 0 },\n {\"x1_last_trig_ctr_stars\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_200HZ, U_NONE, 0 },\n {\"x1_image_blobn_x\", CONVERT_BLOB_POS_M, CONVERT_BLOB_POS_B, TYPE_UINT16, RATE_200HZ, U_NONE, 0 },\n {\"x1_image_blobn_y\", CONVERT_BLOB_POS_M, CONVERT_BLOB_POS_B, TYPE_UINT16, RATE_200HZ, U_NONE, 0 },\n {\"x1_image_blobn_flux\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_200HZ, U_NONE, 0 },\n {\"x1_image_blobn_peak_to_flux\", SCALE(CONVERT_0_TO_10), TYPE_UINT16, RATE_200HZ, U_NONE, 0 },\n {\"x1_predicted_streaking_px\", CONVERT_VEL_M, CONVERT_VEL_B, TYPE_UINT16, RATE_200HZ, U_NONE, 0 },\n\n\n {\"x0_last_trig_lat\", LI2DEG, 0.0, TYPE_UINT32, RATE_200HZ, U_NONE, 0 },\n {\"x0_last_trig_lst\", LI2SEC*SEC2HR, 0.0, TYPE_UINT32, RATE_200HZ, U_NONE, 0 },\n\n {\"x0_image_num_blobs_found\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_num_blobs_matched\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n\n {\"x0_ctr_stars\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_200HZ, U_NONE, 0 },\n {\"x0_image_ctr_stars\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_200HZ, U_NONE, 0 },\n {\"x0_image_ctr_mcp\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_200HZ, U_NONE, 0 },\n\n {\"x0_hk_temp_lens\", CONVERT_TEMP_M, CONVERT_TEMP_B, TYPE_UINT16, RATE_1HZ, U_T_C, 0 },\n {\"x0_hk_temp_comp\", CONVERT_TEMP_M, CONVERT_TEMP_B, TYPE_UINT16, RATE_1HZ, U_T_C, 0 },\n {\"x0_hk_temp_plate\", CONVERT_TEMP_M, CONVERT_TEMP_B, TYPE_UINT16, RATE_1HZ, U_T_C, 0 },\n {\"x0_hk_temp_flange\", CONVERT_TEMP_M, CONVERT_TEMP_B, TYPE_UINT16, RATE_1HZ, U_T_C, 0 },\n {\"x0_hk_pressure\", CONVERT_PRES_M, CONVERT_PRES_B, TYPE_UINT16, RATE_1HZ, U_P_PSI, 0 },\n {\"x0_hk_disk\", CONVERT_GB_M, CONVERT_GB_B, TYPE_UINT16, RATE_1HZ, U_GB, 0 },\n\n {\"x0_image_eq_valid\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_cam_gain_valid\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_hor_valid\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_afocus_metric_valid\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n\n {\"x0_stars_run_time\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_T_S, 0 },\n {\"x0_cam_gain_db\", CONVERT_GAIN_M, CONVERT_GAIN_B, TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_lens_focus\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_lens_aperture\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n\n {\"x0_image_num_exposures\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_stats_mean\", CONVERT_STATS_DEPTH_M, CONVERT_STATS_DEPTH_B, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_stats_noise\", CONVERT_STATS_4000_M, CONVERT_STATS_4000_B, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_stats_gaindb\", CONVERT_STATS_4000_M, CONVERT_STATS_4000_B, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_stats_num_px_sat\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_stats_frac_px_sat\", 2.0/(NARROW_MAX-1.0), -1.0, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_afocus_metric\", CONVERT_STATS_DEPTH_M, CONVERT_STATS_DEPTH_B, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n\n {\"x0_image_eq_iplate\", 9.7e-5/NARROW_MAX, 0.0, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_hor_iplate\", 9.7e-5/NARROW_MAX, 0.0, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n\n {\"x0_image_eq_ra\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_eq_dec\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_eq_roll\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_eq_sigma_ra\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_eq_sigma_dec\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_eq_sigma_roll\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_eq_sigma_pointing\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_hor_az\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_hor_el\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_hor_roll\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_hor_sigma_az\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_hor_sigma_el\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_hor_sigma_roll\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x0_image_hor_sigma_pointing\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n\n {\"x1_image_num_blobs_found\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_num_blobs_matched\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n\n {\"x1_ctr_stars\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_200HZ, U_NONE, 0 },\n {\"x1_image_ctr_stars\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_200HZ, U_NONE, 0 },\n {\"x1_image_ctr_mcp\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_200HZ, U_NONE, 0 },\n\n {\"x1_hk_temp_lens\", CONVERT_TEMP_M, CONVERT_TEMP_B, TYPE_UINT16, RATE_1HZ, U_T_C, 0 },\n {\"x1_hk_temp_comp\", CONVERT_TEMP_M, CONVERT_TEMP_B, TYPE_UINT16, RATE_1HZ, U_T_C, 0 },\n {\"x1_hk_temp_plate\", CONVERT_TEMP_M, CONVERT_TEMP_B, TYPE_UINT16, RATE_1HZ, U_T_C, 0 },\n {\"x1_hk_temp_flange\", CONVERT_TEMP_M, CONVERT_TEMP_B, TYPE_UINT16, RATE_1HZ, U_T_C, 0 },\n {\"x1_hk_pressure\", CONVERT_PRES_M, CONVERT_PRES_B, TYPE_UINT16, RATE_1HZ, U_P_PSI, 0 },\n {\"x1_hk_disk\", CONVERT_GB_M, CONVERT_GB_B, TYPE_UINT16, RATE_1HZ, U_GB, 0 },\n\n {\"x1_image_eq_valid\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_cam_gain_valid\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_hor_valid\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_afocus_metric_valid\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n\n {\"x1_stars_run_time\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_T_S, 0 },\n {\"x1_cam_gain_db\", CONVERT_GAIN_M, CONVERT_GAIN_B, TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_lens_focus\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_lens_aperture\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n\n {\"x1_image_num_exposures\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_stats_mean\", CONVERT_STATS_DEPTH_M, CONVERT_STATS_DEPTH_B, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_stats_noise\", CONVERT_STATS_4000_M, CONVERT_STATS_4000_B, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_stats_gaindb\", CONVERT_STATS_4000_M, CONVERT_STATS_4000_B, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_stats_num_px_sat\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_stats_frac_px_sat\", 2.0/(NARROW_MAX-1.0), -1.0, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_afocus_metric\", CONVERT_STATS_DEPTH_M, CONVERT_STATS_DEPTH_B, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n\n {\"x1_image_eq_iplate\", 9.7e-5/NARROW_MAX, 0.0, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_hor_iplate\", 9.7e-5/NARROW_MAX, 0.0, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n\n {\"x1_image_eq_ra\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_eq_dec\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_eq_roll\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_eq_sigma_ra\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_eq_sigma_dec\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_eq_sigma_roll\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_eq_sigma_pointing\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_hor_az\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_hor_el\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_hor_roll\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_hor_sigma_az\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_hor_sigma_el\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_hor_sigma_roll\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n {\"x1_image_hor_sigma_pointing\", SCALE(CONVERT_WIDE_ANGLE), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n\n\n { \"subframe_counter_1hz\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_100HZ, U_NONE, 0 },\n { \"subframe_counter_5hz\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_100HZ, U_NONE, 0 },\n { \"time\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_100HZ, U_NONE, 0 },\n { \"time_usec\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_100HZ, U_NONE, 0 },\n { \"time_sip\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_100HZ, U_NONE, 0 },\n { \"lst\", LI2H, 0.0, TYPE_UINT32, RATE_100HZ, U_NONE, 0 },\n { \"parts_sched\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_100HZ, U_NONE, 0 },\n\n { \"lat\", LI2DEG*2.0, 0.0, TYPE_INT32, RATE_100HZ, U_NONE, 0 },\n { \"lon\", LI2DEG*2.0, 0.0, TYPE_INT32, RATE_100HZ, U_NONE, 0 },\n\n { \"ra\", LI2H, 0.0, TYPE_UINT32, RATE_100HZ, U_NONE, 0 },\n { \"dec\", LI2DEG, 0.0, TYPE_INT32, RATE_100HZ, U_NONE, 0 },\n { \"start_cycle\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_100HZ, U_NONE, 0 },\n\n { \"lst_sched\", LI2DEG, 0.0, TYPE_UINT32, RATE_100HZ, U_NONE, 0 },\n\n { \"start_set_cycle\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_100HZ, U_NONE, 0 },\n\n { \"ampl_500_bias\", 0.5, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ampl_350_bias\", 0.5, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ampl_250_bias\", 0.5, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ampl_rox_bias\", 0.5, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ampl_x_bias\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"dig21_das\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"dig65_das\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ramp_ena_bias\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ramp_ampl_bias\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"t_padcdc_rec\", CAL_AD590(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_T_C, 0 },\n { \"t_pauram_rec\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_T_C, 0 },\n { \"t_hkdcdc_rec\", CAL_AD590(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_T_C, 0 },\n { \"vt_stbd_das\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"vt_stbd_rec\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"vt_port_das\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"vt_port_rec\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n\n { \"vt_mot_pump_val\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"vt_1_prime\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"vt_if_top_back\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"vt_hwpr_mot\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"vt_if_top_frnt\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"vt_hwpr_feed\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"vt_if_bot_frnt\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"vt_strut_bot\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"vt_strut_side\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"vt_2_prime\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"vt_if_bot_back\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"vt_dac_box\", CAL16T(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"t_mot_act\", CAL_AD590(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_T_C, 0 },\n { \"t_push_plate\", CAL_AD590(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_T_C, 0 },\n { \"t_1_second\", CAL_AD590(1.0, 0), TYPE_UINT16, RATE_5HZ, U_T_C, 0 },\n { \"t_2_second\", CAL_AD590(1.0, 0), TYPE_UINT16, RATE_5HZ, U_T_C, 0 },\n\n { \"he4_lev\", CAL16(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"i_charcoal\", CAL16(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"i_cal_lamp\", CAL16(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"i_hs_char\", CAL16(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"i_hs_pot\", CAL16(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"i_300mk\", CAL16(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n { \"i_jfet\", CAL16(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_V_V, 0 },\n\n { \"pin_in_lock\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"period_cal\", .20, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"status_eth\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"el_null\", I2DEG, 0.0, TYPE_UINT16, RATE_100HZ, U_D_DEG, 0 },\n { \"az_null\", I2DEG, 0.0, TYPE_UINT16, RATE_100HZ, U_D_DEG, 0 },\n { \"az_sun\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_D_DEG, 0 },\n { \"lvdt_low_act\", 1.0, -5000.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"status_mcc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"cryostate\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"upslot_sched\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"t_chip_flc\", 0.01, 0.0, TYPE_UINT16, RATE_5HZ, U_T_C, 0 },\n { \"veto_sensor\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ok_motor_enc\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"ok_mag1\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"ok_dgps\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"ok_mag2\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"ok_elclin\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"i_level_on_bal\", CUR15_M, CUR15_B, TYPE_UINT16, RATE_5HZ, U_I_A, 0 },\n { \"i_level_off_bal\", CUR15_M, CUR15_B, TYPE_UINT16, RATE_5HZ, U_I_A, 0 },\n { \"i_el_req_avg_bal\", CUR15_M, CUR15_B, TYPE_UINT16, RATE_5HZ, U_I_A, 0 },\n { \"status_bal\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n\n {\"enc_potvalve\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0},\n {\"pos_potvalve\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_5HZ, U_NONE, 0},\n {\"state_potvalve\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0},\n {\"vel_potvalve\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0},\n {\"i_open_potvalve\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0},\n {\"i_close_potvalve\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0},\n {\"i_hold_potvalve\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0},\n {\"thresh_clos_potvalve\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0},\n {\"threshlclos_potvalve\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0},\n {\"thresh_open_potvalve\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0},\n {\"tight_move_potvalve\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0},\n {\"enable_potvalve\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0},\n\n {\"lims_vent_A_valve\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0},\n {\"pos_vent_A_valve\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_5HZ, U_NONE, 0},\n {\"lims_vent_B_valve\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0},\n {\"pos_vent_B_valve\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_5HZ, U_NONE, 0},\n {\"vel_valves\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0},\n {\"i_move_valves\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0},\n {\"i_hold_valves\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0},\n {\"acc_valves\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0},\n\n {\"goal_1_aalborg\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0},\n {\"goal_2_aalborg\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0},\n {\"goal_3_aalborg\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0},\n {\"timer_1_aalborg\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0},\n {\"timer_2_aalborg\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0},\n {\"timer_3_aalborg\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0},\n {\"speed_1_aalborg\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0},\n {\"speed_2_aalborg\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0},\n {\"speed_3_aalborg\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0},\n {\"ain_1_aalborg\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0},\n {\"ain_2_aalborg\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0},\n {\"ain_3_aalborg\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0},\n\n\n { \"vel_bal\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"acc_bal\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"i_move_bal\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"i_hold_bal\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"pos_bal\", \t SCALE(CONVERT_UNITY), TYPE_INT32, RATE_5HZ, U_NONE, 0 },\n { \"lim_bal\",\t SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n\n { \"alt_sip\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"lat_sip\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_LA_DEG, 0 },\n { \"lon_sip\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_LO_DEG, 0 },\n\n { \"mode_p\", 1, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"x_p\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"y_p\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"vel_az_p\", I2VEL, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"del_p\", I2VEL, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"w_p\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n\n { \"offset_ifel_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_V_DPS, 0 },\n { \"offset_ifroll_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_V_DPS, 0 },\n { \"offset_ifyaw_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_V_DPS, 0 },\n\n { \"lvdt_high_act\", 1.0, -5000.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"pulse_cal\", 10.0, 0., TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"sigma_clin\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"mks_hi_sip\", 0.003256, -0.226858, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"mks_med_sip\", 0.032614, -0.072580, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"pref_tp_sf\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"bi0_fifo_size\", 1. / 624, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"plover\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"jfet_set_on\", 1 / 100., 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"jfet_set_off\", 1 / 100., 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"state_cycle\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"g_p_heat_gy\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"g_i_heat_gy\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"g_d_heat_gy\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"t_set_gy\", (100.0 / 32768.0), 0.0, TYPE_UINT16, RATE_5HZ, U_T_C, 0 },\n { \"h_age_gy\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"h_hist_gy\", (100.0 / 32768.0), 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"ra_1_p\", I2H, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"dec_1_p\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"ra_2_p\", I2H, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"dec_2_p\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"ra_3_p\", I2H, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"dec_3_p\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"ra_4_p\", I2H, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"dec_4_p\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"trim_clin\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"trim_motor_enc\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"trim_el_null\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"trim_null\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"trim_mag1\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"trim_mag2\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n\n { \"gain_bal\", 1 / 1000., 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"el_clin\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"h_p\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"el_lut_clin\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"mks_lo_sip\", 0.327045, -5.944902, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"alt\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"mode_az_mc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"mode_el_mc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"dest_az_mc\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"dest_el_mc\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"vel_az_mc\", 1. / 6000, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"vel_el_mc\", 1. / 6000, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"dir_az_mc\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"dir_el_mc\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"slew_veto\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"sveto_len\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"pot_lock\", -100.0 / 16068.0, 1636800.0 / 16068.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"dith_el\", 0.5 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_D_DEG, 0 },\n { \"state_lock\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"goal_lock\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"seized_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"n_dith_p\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"x_vel_stage\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"x_stp_stage\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"x_str_stage\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"y_lim_stage\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"i_dith_el\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"y_stp_stage\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"y_str_stage\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"x_lim_stage\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"y_vel_stage\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"he4_lev_old\", CAL16(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"offset_ifelxsc0_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"offset_ifelxsc1_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"offset_ifrollxsc0_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"offset_ifrollxsc1_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"offset_ifyawxsc0_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"offset_ifyawxsc1_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"new_offset_ifelmotorenc_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"offset_ifelmotorenc_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_1HZ, U_NONE, 0 },\n { \"offset_ifelclin_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_1HZ, U_NONE, 0 },\n { \"int_ifelmotorenc\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"new_offset_ifyawmag1_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"new_offset_ifrollmag1_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"int_ifyawmag1\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"int_ifrollmag1\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"d_az_mag1\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"new_offset_ifyawmag2_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"new_offset_ifrollmag2_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"int_ifyawmag2\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"int_ifrollmag2\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"d_az_mag2\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"new_offset_ifelxsc0_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"new_offset_ifyawxsc0_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"new_offset_ifrollxsc0_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"d_az_xsc0\", 100.0 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"int_ifrollxsc0\", 100.0 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"int_ifyawxsc0\", 100.0 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"int_ifelxsc0\", 100.0 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"prev_soln_az_xsc0\", 360.0 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"prev_soln_el_xsc0\", 360.0 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"new_offset_ifelxsc1_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"new_offset_ifyawxsc1_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"new_offset_ifrollxsc1_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"d_az_xsc1\", 100.0 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"int_ifyawxsc1\", 100.0 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"int_ifrollxsc1\", 100.0 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"int_ifelxsc1\", 100.0 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"prev_soln_az_xsc1\", 360.0 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"prev_soln_el_xsc1\", 360.0 / 32768.0, 0.0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n\n { \"pos_lock\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"pos_0_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"pos_1_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"pos_2_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"enc_0_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"enc_1_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"enc_2_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"goal_sf\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"focus_sf\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n\n { \"offset_ifrollmag1_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_V_DPS, 0 },\n { \"offset_ifyawmag1_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_V_DPS, 0 },\n { \"offset_ifrolldgps_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_1HZ, U_V_DPS, 0 },\n { \"offset_ifyawdgps_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_1HZ, U_V_DPS, 0 },\n { \"offset_ifrollmag2_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_V_DPS, 0 },\n { \"offset_ifyawmag2_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_V_DPS, 0 },\n { \"offset_ifrollpss_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_V_DPS, 0 },\n { \"offset_ifyawpss_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_V_DPS, 0 },\n { \"next_i_hwpr_p\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"next_i_dith_p\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n\n { \"pref_ts_sf\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"spread_sf\", 1 / 500., 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"acc_lock\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"i_move_act\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"i_hold_act\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"vel_act\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"acc_act\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"i_move_lock\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"i_hold_lock\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"vel_lock\", 100., 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"g_prime_sf\", 0.01, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"g_second_sf\", 0.01, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"step_sf\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"wait_sf\", 1 / 30., 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"mode_sf\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"correction_sf\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"age_sf\", 1 / 30., 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"offset_sf\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"t_prime_sf\", CAL_AD590(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_T_C, 0 },\n { \"t_second_sf\", CAL_AD590(1.0, 0.0), TYPE_UINT16, RATE_5HZ, U_T_C, 0 },\n { \"flags_act\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"lvdt_spread_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"el_sun\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"hwpr_cal\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"mode_cal\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"overshoot_hwpr\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"drive_err_cts_rw\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"drive_err_cts_el\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"drive_err_cts_piv\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"vel_hwpr\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"acc_hwpr\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"i_move_hwpr\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"i_hold_hwpr\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"pos_hwpr\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_5HZ, U_NONE, 0 },\n { \"enc_hwpr\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"step_start_bias\", 0.5, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"step_end_bias\", 0.5, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"step_n_bias\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"step_time_bias\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"step_pul_len_bias\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"step_array_bias\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"step_start_phase\", 0.5, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"step_end_phase\", 0.5, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"step_nsteps_phase\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"step_time_phase\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"step_ena_bias\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"step_ena_phase\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n\n\n { \"v_batt_cc1\", 1 / 180.0, -32400.0 / 180.0, TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"v_arr_cc1\", 1 / 180.0, -32400.0 / 180.0, TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"i_batt_cc1\", 1 / 400.0, -32000.0 / 400.0, TYPE_UINT16, RATE_1HZ, U_I_A, 0 },\n { \"i_arr_cc1\", 1 / 400.0, -32000.0 / 400.0, TYPE_UINT16, RATE_1HZ, U_I_A, 0 },\n { \"t_hs_cc1\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_1HZ, U_T_C, 0 },\n { \"fault_cc1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"alarm_cc1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"v_targ_cc1\", 1 / 180.0, -32400.0 / 180.0, TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"state_cc1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n\n\n { \"lvdt_0_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"lvdt_1_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"lvdt_2_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n\n { \"gy_az_vel\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_DPS, 0 },\n { \"gy_el_vel\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_DPS, 0 },\n { \"gy_total_vel\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_DPS, 0 },\n { \"gy_total_accel\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_DPS, 0 },\n\n { \"offset_0_act\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"offset_1_act\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"offset_2_act\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"goal_0_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"goal_1_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"goal_2_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n // PSS Channels\n { \"ok_pss\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"sigma_pss\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"cal_imin_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"az_raw_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_P_DEG, 0 },\n { \"el_raw_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_P_DEG, 0 },\n { \"az_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_P_DEG, 0 },\n { \"trim_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"trim_dgps\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"cal_el_pss1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_el_pss2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_el_pss3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_el_pss4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_el_pss5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_el_pss6\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_roll_pss1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_roll_pss2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_roll_pss3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_roll_pss4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_roll_pss5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_roll_pss6\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_az_pss_array\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_az_pss1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_az_pss2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_az_pss3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_az_pss4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_az_pss5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_az_pss6\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_DEG, 0 },\n { \"cal_d_pss1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_MM, 0 },\n { \"cal_d_pss2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_MM, 0 },\n { \"cal_d_pss3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_MM, 0 },\n { \"cal_d_pss4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_MM, 0 },\n { \"cal_d_pss5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_MM, 0 },\n { \"cal_d_pss6\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_TRIM_MM, 0 },\n { \"noise_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"snr_pss1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"snr_pss2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"snr_pss3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"snr_pss4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"snr_pss5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"snr_pss6\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"az_raw_pss1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_P_DEG, 0 },\n { \"az_raw_pss2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_P_DEG, 0 },\n { \"az_raw_pss3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_P_DEG, 0 },\n { \"az_raw_pss4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_P_DEG, 0 },\n { \"az_raw_pss5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_P_DEG, 0 },\n { \"az_raw_pss6\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_P_DEG, 0 },\n { \"el_raw_pss1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_P_DEG, 0 },\n { \"el_raw_pss2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_P_DEG, 0 },\n { \"el_raw_pss3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_P_DEG, 0 },\n { \"el_raw_pss4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_P_DEG, 0 },\n { \"el_raw_pss5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_P_DEG, 0 },\n { \"el_raw_pss6\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_P_DEG, 0 },\n // v1-4 for each PSS are the voltages from the PSD, v5 is the voltage from the thermistor\n { \"v1_1_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v2_1_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v3_1_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v4_1_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v5_1_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v1_2_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v2_2_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v3_2_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v4_2_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v5_2_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v1_3_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v2_3_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v3_3_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v4_3_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v5_3_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v1_4_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v2_4_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v3_4_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v4_4_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v5_4_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v1_5_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v2_5_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v3_5_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v4_5_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v5_5_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v1_6_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v2_6_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v3_6_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v4_6_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v5_6_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n /* { \"v1_7_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v2_7_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v3_7_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v4_7_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v5_7_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v1_8_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v2_8_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v3_8_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v4_8_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 },\n { \"v5_8_pss\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_V, 0 }, */\n\n { \"accel_az\", 2.0 / 65536, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"led_cc1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"force_sbsc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"exp_int_sbsc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_T_MS, 0 },\n { \"exp_time_sbsc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_T_MS, 0 },\n { \"foc_res_sbsc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"move_tol_sbsc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"maxblob_sbsc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"grid_sbsc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"thresh_sbsc\", 1.0 / 1000.0, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"mdist_sbsc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"mapmean_sbsc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"mapsigma_sbsc\", 1.0 / 10.0, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ccd_t_sbsc\", 1.0 / 100.0, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"nblobs_sbsc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"blob00_x_sbsc\", CAM_WIDTH / SHRT_MAX, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"blob00_y_sbsc\", CAM_WIDTH / SHRT_MAX, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"blob00_f_sbsc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"blob00_s_sbsc\", 1.0 / 100.0, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"blob01_x_sbsc\", CAM_WIDTH / SHRT_MAX, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"blob01_y_sbsc\", CAM_WIDTH / SHRT_MAX, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"blob01_f_sbsc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"blob01_s_sbsc\", 1.0 / 100.0, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"blob02_x_sbsc\", CAM_WIDTH / SHRT_MAX, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"blob02_y_sbsc\", CAM_WIDTH / SHRT_MAX, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"blob02_f_sbsc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"blob02_s_sbsc\", 1.0 / 100.0, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"g_pt_az\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"g_pt_el\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"pos0_hwpr\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"pos1_hwpr\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n // { \"i_pos_rq_hwpr\", SCALE(CONVERT_UNITY), TYPE_INT8, RATE_5HZ, U_NONE, 0 },\n { \"i_pos_rq_hwpr\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"rate_highrate\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_RATE, 0 },\n { \"rate_biphase\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_RATE, 0 },\n { \"mpsse_clock_speed\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_RATE, 0 },\n { \"rate_pilot\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_RATE, 0 },\n { \"nkids_tlm_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_RATE, 0 },\n { \"skids_tlm_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_RATE, 0 },\n { \"nkids_tlm_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_RATE, 0 },\n { \"skids_tlm_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_RATE, 0 },\n { \"nkids_tlm_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_RATE, 0 },\n { \"skids_tlm_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_RATE, 0 },\n { \"nkids_tlm_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_RATE, 0 },\n { \"skids_tlm_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_RATE, 0 },\n { \"nkids_tlm_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_RATE, 0 },\n { \"skids_tlm_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_RATE, 0 },\n { \"roach_tlm_mode\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_RATE, 0 },\n { \"read_wait_hwpr\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"i_pos_hwpr\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n // { \"i_pos_hwpr\", SCALE(CONVERT_UNITY), TYPE_INT8, RATE_5HZ, U_NONE, 0 },\n { \"stop_cnt_hwpr\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"rel_move_hwpr\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_5HZ, U_NONE, 0 },\n { \"stat_control_hwpr\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n // { \"margin_hwpr\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"margin_hwpr\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"pot_targ_hwpr\", 1.0 / 65535.0, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"mode_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"enc_targ_hwpr\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"enc_real_hwpr\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"enc_real_targ_hwpr\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"enc_err_hwpr\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"enc_real_err_hwpr\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"backoff_hwpr\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"dr_0_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"dr_1_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"dr_2_act\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"tol_act\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"status_actbus\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"pot_err_hwpr\", 1.0 / 32767.0, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"blob_idx_sbsc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"el_raw_enc\", I2DEG, 0.0, TYPE_UINT16, RATE_100HZ, U_P_DEG, 0 },\n { \"el_motor_enc\", I2DEG, 0.0, TYPE_UINT16, RATE_100HZ, U_P_DEG, 0 },\n { \"sigma_motor_enc\", I2DEG, 0.0, TYPE_UINT16, RATE_100HZ, U_NONE, 0 },\n { \"chatter\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_100HZ, U_NONE, 0 },\n\n { \"focpos_sbsc\", 1.0 / 10.0, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"delay_sbsc\", 1.0 / 1000.0, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"daz_p\", I2VEL, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"steps_shutter\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"steps_slow_shutter\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"pos_shutter\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_5HZ, U_NONE, 0 },\n { \"lims_shutter\",\t SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"i_hold_shutter\",\t SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"i_move_shutter\",\t SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"vel_shutter\",\t SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"acc_shutter\",\t SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"ra_sbsc\", 1.0 / 1000.0, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"dec_sbsc\", 1.0 / 1000.0, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n\n { \"i_tot\", 1.0e-3, 0.0, TYPE_UINT16, RATE_5HZ, U_I_A, 0 },\n { \"t_set_sbsc\", (100.0 / 32768.0), 0.0, TYPE_UINT16, RATE_5HZ, U_T_C, 0 },\n\n { \"pot_hwpr\", 1.0 / 65535.0, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n /// Shared Variables\n { \"t_cpu0_flc_s\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_1HZ, U_T_C, 0 },\n { \"t_cpu0_flc_n\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_1HZ, U_T_C, 0 },\n\n { \"t_cpu1_flc_s\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_1HZ, U_T_C, 0 },\n { \"t_cpu1_flc_n\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_1HZ, U_T_C, 0 },\n\n { \"v_12v_flc_s\", 0.01, 0.0, TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"v_12v_flc_n\", 0.01, 0.0, TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n\n { \"v_5v_flc_s\", 0.01, 0.0, TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"v_5v_flc_n\", 0.01, 0.0, TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n\n { \"v_batt_flc_s\", 0.01, 0.0, TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"v_batt_flc_n\", 0.01, 0.0, TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n\n { \"i_flc_s\", 0.01, 0.0, TYPE_UINT16, RATE_1HZ, U_I_A, 0 },\n { \"i_flc_n\", 0.01, 0.0, TYPE_UINT16, RATE_1HZ, U_I_A, 0 },\n\n { \"last_cmd_s\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"last_cmd_n\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"count_cmd_s\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"count_cmd_n\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"df_flc_s\", 1.0 / 250.0, 0.0, TYPE_UINT16, RATE_5HZ, U_GB, 0 },\n { \"df_flc_n\", 1.0 / 250.0, 0.0, TYPE_UINT16, RATE_5HZ, U_GB, 0 },\n\n { \"time_flc_s\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"time_flc_n\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n\n { \"hdd_disk_space_s\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"hdd_disk_space_n\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n\n { \"hdd_disk_index_s\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"hdd_disk_index_n\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n\n { \"timeout_s\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"timeout_n\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"t_start_cycle\", 4.0 / 65536.0, 0.0, TYPE_UINT16, RATE_5HZ, U_T_K, 0 },\n { \"t_pot_max_cycle\", 10.0 / 65536.0, 0.0, TYPE_UINT16, RATE_5HZ, U_T_K, 0 },\n { \"t_char_max_cycle\", 70.0 / 65536.0, 0.0, TYPE_UINT16, RATE_5HZ, U_T_K, 0 },\n { \"t_char_set_cycle\", 70.0 / 65536.0, 0.0, TYPE_UINT16, RATE_5HZ, U_T_K, 0 },\n { \"time_char_cycle\", 120.0 / 65536.0, 0.0, TYPE_UINT16, RATE_5HZ, U_T_MIN, 0 },\n { \"time_set_cycle\", 120.0 / 65536.0, 0.0, TYPE_UINT16, RATE_5HZ, U_T_MIN, 0 },\n { \"thresh_cmd_atrim\", 10.0 / 65536.0, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"time_cmd_atrim\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"rate_cmd_atrim\", 30.0 / 65536.0, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"rate_atrim\", 30.0 / 65536.0, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"thresh_atrim\", 10.0 / 65536.0, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"fresh_trim\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"new_az\", 720.0 / 65536.0, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"new_el\", 720.0 / 65536.0, 0.0, TYPE_INT16, RATE_5HZ, U_NONE, 0 },\n { \"weight_az\", 360.0 / 65536.0, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"weight_el\", 360.0 / 65536.0, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"v_batt_cc2\", 1 / 180.0, -32400.0 / 180.0, TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"v_arr_cc2\", 1 / 180.0, -32400.0 / 180.0, TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"i_batt_cc2\", 1 / 400.0, -32000.0 / 400.0, TYPE_UINT16, RATE_1HZ, U_I_A, 0 },\n { \"i_arr_cc2\", 1 / 400.0, -32000.0 / 400.0, TYPE_UINT16, RATE_1HZ, U_I_A, 0 },\n { \"t_hs_cc2\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_1HZ, U_T_C, 0 },\n { \"fault_cc2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"alarm_cc2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"v_targ_cc2\", 1 / 180.0, -32400.0 / 180.0, TYPE_UINT16, RATE_1HZ, U_V_V, 0 },\n { \"state_cc2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"led_cc2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n\n #ifndef BOLOTEST\n\n { \"latch0\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"latch1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"switch_gy\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"switch_misc\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"bus_reset_act\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"v_pump_bal\", 3.91 / 13107.0, -9.775, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"dac2_ampl\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"mask_gy\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_200HZ, U_NONE, 0 },\n { \"bits_vtx\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"bits_bal\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"pch_pyr_clin\", 0.001343, -45.426, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"roll_pyr_clin\", 0.001413, -45.398, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"xel_if_clin\", 0.00546739, -25. * 6.144, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"el_raw_if_clin\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"x_stage\", 2.0, 0.0, TYPE_INT32, RATE_5HZ, U_NONE, 0 },\n { \"y_stage\", 2.0, 0.0, TYPE_INT32, RATE_5HZ, U_NONE, 0 },\n\n { \"ifpm_hall\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"lvdt_65_act\", LVDT65_ADC_TO_ENC, LVDT65_ZERO, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"lvdt_63_act\", LVDT63_ADC_TO_ENC, LVDT63_ZERO, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"lvdt_64_act\", LVDT64_ADC_TO_ENC, LVDT64_ZERO, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n #endif\n\n { \"ifyaw_1_gy\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_V_DPS, 0 },\n { \"ifroll_1_gy\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_V_DPS, 0 },\n { \"ifyaw_2_gy\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_V_DPS, 0 },\n { \"ifel_1_gy\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_V_DPS, 0 },\n { \"ifel_2_gy\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_V_DPS, 0 },\n { \"ifroll_2_gy\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_V_DPS, 0 },\n\n { \"good_pktcnt_yaw_1_gy\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_200HZ, U_NONE, 0 },\n { \"good_pktcnt_roll_1_gy\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_200HZ, U_NONE, 0 },\n { \"good_pktcnt_el_1_gy\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_200HZ, U_NONE, 0 },\n\n { \"good_pktcnt_yaw_2_gy\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_200HZ, U_NONE, 0 },\n { \"good_pktcnt_roll_2_gy\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_200HZ, U_NONE, 0 },\n { \"good_pktcnt_el_2_gy\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_200HZ, U_NONE, 0 },\n\n { \"az\", LI2DEG, 0.0, TYPE_UINT32, RATE_200HZ, U_P_DEG, 0 },\n { \"el\", LI2DEG, 0.0, TYPE_UINT32, RATE_200HZ, U_P_DEG, 0 },\n\n { \"ifel_gy\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_100HZ, U_V_DPS, 0 },\n { \"ifroll_gy\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_100HZ, U_V_DPS, 0 },\n { \"ifyaw_gy\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_100HZ, U_V_DPS, 0 },\n\n { \"vel_req_el\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_V_DPS, 0 },\n { \"vel_req_az\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_V_DPS, 0 },\n\n { \"trigger_xsc\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_100HZ, U_NONE, 0 },\n\n { \"dig43_das\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_100HZ, U_NONE, 0 },\n { \"chopper\", CAL16(1.0, 0.0), TYPE_UINT16, RATE_100HZ, U_V_V, 0 },\n\n { \"x_mag1_n\", M_16MAG, 0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"y_mag1_n\", M_16MAG, 0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"z_mag1_n\", M_16MAG, 0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"status_mag1_n\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"err_count_mag1_n\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"timeout_count_mag1_n\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"reset_count_mag1_n\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"x_mag2_s\", M_16MAG, 0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"y_mag2_s\", M_16MAG, 0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"z_mag2_s\", M_16MAG, 0, TYPE_INT16, RATE_100HZ, U_NONE, 0 },\n { \"status_mag2_s\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"err_count_mag2_s\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"timeout_count_mag2_s\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"reset_count_mag2_s\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"lat_dgps\", I2DEG, 0, TYPE_INT16, RATE_1HZ, U_NONE, 0 },\n { \"lon_dgps\", I2DEG, 0, TYPE_INT16, RATE_1HZ, U_NONE, 0 },\n { \"alt_dgps\", I2DEG, 0, TYPE_INT16, RATE_1HZ, U_NONE, 0 },\n { \"num_sat_dgps\", SCALE(CONVERT_UNITY), TYPE_INT8, RATE_1HZ, U_NONE, 0 },\n { \"quality_dgps\", SCALE(CONVERT_UNITY), TYPE_INT8, RATE_1HZ, U_NONE, 0 },\n { \"az_raw_dgps\", I2DEG, 0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"az_dgps\", I2DEG, 0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"sigma_dgps\", I2DEG, 0, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n\n { \"ifel_earth_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_V_DPS, 0 },\n { \"ifroll_earth_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_V_DPS, 0 },\n { \"ifyaw_earth_gy\", 0.1 / 32768.0, 0.0, TYPE_INT16, RATE_5HZ, U_V_DPS, 0 },\n\n { \"az_mag1\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_D_DEG, 0 },\n { \"az_raw_mag1\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_D_DEG, 0 },\n { \"pitch_mag1\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_D_DEG, 0 },\n\n { \"sigma_mag1\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"declination_mag1\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_D_DEG, 0 },\n { \"dip_mag1\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_D_DEG, 0 },\n\n { \"cal_xmax_mag1\", M_32UNI*20.0, 0.0, TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"cal_xmin_mag1\", M_32UNI*20.0, 0.0, TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"cal_ymax_mag1\", M_32UNI*20.0, 0.0, TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"cal_ymin_mag1\", M_32UNI*20.0, 0.0, TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"cal_align_mag1\", M_16UNI*180.0, 0.0, TYPE_INT16, RATE_1HZ, U_NONE, 0 },\n\n { \"az_mag2\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_D_DEG, 0 },\n { \"az_raw_mag2\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_D_DEG, 0 },\n { \"pitch_mag2\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_D_DEG, 0 },\n\n { \"sigma_mag2\", I2DEG, 0.0, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"declination_mag2\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_D_DEG, 0 },\n { \"dip_mag2\", I2DEG, 0.0, TYPE_INT16, RATE_5HZ, U_D_DEG, 0 },\n\n { \"cal_xmax_mag2\", M_32UNI*20.0, 0.0, TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"cal_xmin_mag2\", M_32UNI*20.0, 0.0, TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"cal_ymax_mag2\", M_32UNI*20.0, 0.0, TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"cal_ymin_mag2\", M_32UNI*20.0, 0.0, TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"cal_align_mag2\", M_16UNI*180.0, 0.0, TYPE_INT16, RATE_1HZ, U_NONE, 0 },\n\n /** Motor Channels */\n { \"mc_rw_vel\", RW_ENCODER_SCALING * 0.1, 0.0, TYPE_INT32, RATE_100HZ, U_V_DPS, 0 },\n { \"mc_rw_pos\", RW_ENCODER_SCALING, 0.0, TYPE_INT32, RATE_100HZ, U_D_DEG, 0 },\n { \"mc_el_vel\", EL_MOTOR_ENCODER_SCALING * 0.1, 0.0, TYPE_INT32, RATE_100HZ, U_V_DPS, 0 },\n { \"mc_el_pos\", EL_LOAD_ENCODER_SCALING, 0.0, TYPE_INT32, RATE_100HZ, U_D_DEG, 0 },\n { \"mc_el_motor_pos\", EL_MOTOR_ENCODER_SCALING, 0.0, TYPE_INT32, RATE_100HZ, U_D_DEG, 0 },\n { \"mc_piv_vel\", PIV_RESOLVER_SCALING * 0.1, 0.0, TYPE_INT32, RATE_100HZ, U_V_DPS, 0 },\n { \"mc_piv_pos\", PIV_RESOLVER_SCALING, 0.0, TYPE_INT32, RATE_100HZ, U_D_DEG, 0 },\n { \"mc_phase_rw\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_D_DEG, 0 },\n { \"mc_phase_el\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_D_DEG, 0 },\n { \"mc_phase_piv\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_D_DEG, 0 },\n { \"mc_phase_mode_rw\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"mc_phase_mode_el\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"mc_phase_mode_piv\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n {\"control_word_read_el\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n {\"control_word_read_rw\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_100HZ, U_NONE, 0 },\n {\"control_word_read_piv\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n {\"control_word_write_el\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n {\"control_word_write_rw\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_100HZ, U_NONE, 0 },\n {\"control_word_write_piv\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n {\"latched_fault_el\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n {\"latched_fault_rw\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_100HZ, U_NONE, 0 },\n {\"latched_fault_piv\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n {\"network_status_el\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n {\"network_status_rw\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_100HZ, U_NONE, 0 },\n {\"network_status_piv\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n {\"network_problem_el\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n {\"network_problem_rw\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_100HZ, U_NONE, 0 },\n {\"network_problem_piv\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n {\"mc_cmd_status\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n\n // TODO(seth): Ensure that scale factors for all currents/commands are in Amps\n { \"mc_piv_i_cmd\", 1.0/100.0, 0.0, TYPE_INT16, RATE_200HZ, U_NONE, 0 },\n { \"mc_rw_i_cmd\", 1.0/100.0, 0.0, TYPE_INT16, RATE_200HZ, U_NONE, 0 },\n { \"mc_el_i_cmd\", 1.0/100.0, 0.0, TYPE_INT16, RATE_200HZ, U_NONE, 0 },\n\n { \"mc_piv_i_read\", 1.0/100.0, 0.0, TYPE_INT16, RATE_200HZ, U_NONE, 0 },\n { \"mc_rw_i_read\", 1.0/100.0, 0.0, TYPE_INT16, RATE_200HZ, U_NONE, 0 },\n { \"mc_el_i_read\", 1.0/100.0, 0.0, TYPE_INT16, RATE_200HZ, U_NONE, 0 },\n\n /** EtherCat Status Info */\n { \"n_found_ec\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"slave_count_ec\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"status_ec\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"status_ec_hwpr\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"status_ec_rw\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"status_ec_piv\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"status_ec_el\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n\n /** Velocity control loop commanded P/I terms */\n { \"g_p_el\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"g_i_el\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"g_d_el\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"g_db_el\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"g_p_az\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"g_i_az\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"g_d_az\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"g_pe_piv\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"g_pv_piv\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"g_iv_piv\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"g_ie_piv\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_NONE, 0 },\n { \"set_rw\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_5HZ, U_V_DPS, 0 },\n\n { \"fault_gy\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_200HZ, U_NONE, 0 },\n { \"vel_el_p\", I2VEL, 0.0, TYPE_UINT16, RATE_200HZ, U_NONE, 0 },\n { \"frict_off_piv\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"frict_term_piv\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"frict_term_uf_piv\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"frict_off_el\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"frict_term_el\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"frict_term_uf_el\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n\n /** Motor Controller State and Status Registers */\n { \"status_rw\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_100HZ, U_NONE, 0 },\n { \"state_rw\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_100HZ, U_NONE, 0 },\n { \"status_el\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"state_el\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"status_piv\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"state_piv\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n /** Motor Controller Temperatures */\n { \"t_mc_rw\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_T_C, 0 },\n { \"t_mc_el\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_T_C, 0 },\n { \"t_mc_piv\", SCALE(CONVERT_UNITY), TYPE_INT16, RATE_5HZ, U_T_C, 0 },\n\n /** Calculated P/I and Error (diff btw commanded/actual velocity) terms from control loop */\n { \"p_term_el\", 0.01, 0.0, TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"i_term_el\", 0.01, 0.0, TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"d_term_el\", 0.01, 0.0, TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"error_el\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"el_integral_step\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"p_term_az\", 0.01, 0.0, TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"i_term_az\", 0.01, 0.0, TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"d_term_az\", 0.01, 0.0, TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"error_az\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"p_rw_term_piv\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"i_rw_term_piv\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"p_err_term_piv\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n { \"i_err_term_piv\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_200HZ, U_NONE, 0 },\n\n\n { \"dio_heaters\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_100HZ, U_NONE, 0 },\n\n /* housekeeping cryo channels */\n /** Cyro Labjack Analog Inputs */\n { \"ain00_cryo_labjack\", M_16LJAIN, B_16LJAIN, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ain01_cryo_labjack\", M_16LJAIN, B_16LJAIN, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ain02_cryo_labjack\", M_16LJAIN, B_16LJAIN, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ain03_cryo_labjack\", M_16LJAIN, B_16LJAIN, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ain04_cryo_labjack\", M_16LJAIN, B_16LJAIN, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ain05_cryo_labjack\", M_16LJAIN, B_16LJAIN, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ain06_cryo_labjack\", M_16LJAIN, B_16LJAIN, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ain07_cryo_labjack\", M_16LJAIN, B_16LJAIN, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ain08_cryo_labjack\", M_16LJAIN, B_16LJAIN, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ain09_cryo_labjack\", M_16LJAIN, B_16LJAIN, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ain10_cryo_labjack\", M_16LJAIN, B_16LJAIN, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ain11_cryo_labjack\", M_16LJAIN, B_16LJAIN, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ain12_cryo_labjack\", M_16LJAIN, B_16LJAIN, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ain13_cryo_labjack\", M_16LJAIN, B_16LJAIN, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n { \"ain14_cryo_labjack\", M_16LJAIN, B_16LJAIN, TYPE_UINT16, RATE_5HZ, U_NONE, 0 },\n\n { \"mcp_1hz_framecount\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"mcp_1hz_framecount_dl\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"mcp_5hz_framecount\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_5HZ, U_NONE, 0 },\n { \"mcp_100hz_framecount\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_100HZ, U_NONE, 0 },\n { \"mcp_200hz_framecount\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_200HZ, U_NONE, 0 },\n { \"mcp_244hz_framecount\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_244HZ, U_NONE, 0 },\n { \"mcp_488hz_framecount\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_488HZ, U_NONE, 0 },\n\n// Begin ROACH channels\n { \"ctime_packet_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"ctime_packet_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"ctime_packet_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"ctime_packet_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"ctime_packet_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"pps_count_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"pps_count_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"pps_count_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"pps_count_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"pps_count_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"clock_count_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"clock_count_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"clock_count_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"clock_count_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"clock_count_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"packet_count_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"packet_count_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"packet_count_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"packet_count_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"packet_count_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n // roach diagnostic channels\n { \"is_chopping_lo_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"is_chopping_lo_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"is_chopping_lo_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"is_chopping_lo_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"is_chopping_lo_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"packet_count_mcp_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"packet_count_mcp_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"packet_count_mcp_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"packet_count_mcp_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"packet_count_mcp_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"packet_count_valid_mcp_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"packet_count_valid_mcp_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"packet_count_valid_mcp_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"packet_count_valid_mcp_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"packet_count_valid_mcp_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"packet_count_invalid_mcp_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"packet_count_invalid_mcp_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"packet_count_invalid_mcp_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"packet_count_invalid_mcp_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"packet_count_invalid_mcp_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"pi_error_count_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"pi_error_count_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"pi_error_count_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"pi_error_count_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"pi_error_count_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"state_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"state_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"state_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"state_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"state_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"roach_trig_turn_retune\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"roach_auto_check_cycle\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"roach_fridge_cycle_warning\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"roach_enable_cal_pulse\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"df_retune_thresh_roach1\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"df_retune_thresh_roach2\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"df_retune_thresh_roach3\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"df_retune_thresh_roach4\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"df_retune_thresh_roach5\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"df_diff_retune_thresh_roach1\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"df_diff_retune_thresh_roach2\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"df_diff_retune_thresh_roach3\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"df_diff_retune_thresh_roach4\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"df_diff_retune_thresh_roach5\", SCALE(CONVERT_UNITY), TYPE_INT32, RATE_1HZ, U_NONE, 0 },\n { \"avg_df_diff_roach1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"avg_df_diff_roach2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"avg_df_diff_roach3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"avg_df_diff_roach4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"avg_df_diff_roach5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n /*\n { \"is_averaging_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"is_averaging_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"is_averaging_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"is_averaging_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"is_averaging_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n */\n { \"roach_lamp_now\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_5HZ, U_NONE, 0 },\n { \"fk_smooth_scale_roach1\", M_32RFREQ, B_32RFREQ, TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"fk_smooth_scale_roach2\", M_32RFREQ, B_32RFREQ, TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"fk_smooth_scale_roach3\", M_32RFREQ, B_32RFREQ, TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"fk_smooth_scale_roach4\", M_32RFREQ, B_32RFREQ, TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"fk_smooth_scale_roach5\", M_32RFREQ, B_32RFREQ, TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"fk_peak_thresh_roach1\", M_16R_DB, B_16R_DB, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"fk_peak_thresh_roach2\", M_16R_DB, B_16R_DB, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"fk_peak_thresh_roach3\", M_16R_DB, B_16R_DB, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"fk_peak_thresh_roach4\", M_16R_DB, B_16R_DB, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"fk_peak_thresh_roach5\", M_16R_DB, B_16R_DB, TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"fk_space_thresh_roach1\", M_32RFREQ, B_32RFREQ, TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"fk_space_thresh_roach2\", M_32RFREQ, B_32RFREQ, TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"fk_space_thresh_roach3\", M_32RFREQ, B_32RFREQ, TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"fk_space_thresh_roach4\", M_32RFREQ, B_32RFREQ, TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"fk_space_thresh_roach5\", M_32RFREQ, B_32RFREQ, TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"set_atten_in_roach1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"set_atten_in_roach2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"set_atten_in_roach3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"set_atten_in_roach4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"set_atten_in_roach5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"set_atten_out_roach1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"set_atten_out_roach2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"set_atten_out_roach3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"set_atten_out_roach4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"set_atten_out_roach5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"read_atten_in_roach1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"read_atten_in_roach2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"read_atten_in_roach3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"read_atten_in_roach4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"read_atten_in_roach5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"read_atten_out_roach1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"read_atten_out_roach2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"read_atten_out_roach3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"read_atten_out_roach4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"read_atten_out_roach5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"adcI_rms_roach1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"adcI_rms_roach2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"adcI_rms_roach3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"adcI_rms_roach4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"adcI_rms_roach5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"adcQ_rms_roach1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"adcQ_rms_roach2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"adcQ_rms_roach3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"adcQ_rms_roach4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"adcQ_rms_roach5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"pow_per_tone_roach1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"pow_per_tone_roach2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"pow_per_tone_roach3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"pow_per_tone_roach4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"pow_per_tone_roach5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"prev_nkids_found_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"prev_nkids_found_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"prev_nkids_found_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"prev_nkids_found_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"prev_nkids_found_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nkids_found_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nkids_found_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nkids_found_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nkids_found_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nkids_found_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nkids_good_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nkids_good_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nkids_good_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nkids_good_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nkids_good_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nkids_bad_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nkids_bad_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nkids_bad_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nkids_bad_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nkids_bad_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"status_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"status_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"status_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"status_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"status_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_5HZ, U_NONE, 0 },\n { \"current_ntones_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"current_ntones_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"current_ntones_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"current_ntones_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"current_ntones_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"pi_temp_roach1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"pi_temp_roach2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"pi_temp_roach3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"pi_temp_roach4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"pi_temp_roach5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"lo_freq_req_roach1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"lo_freq_req_roach2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"lo_freq_req_roach3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"lo_freq_req_roach4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"lo_freq_req_roach5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"lo_freq_read_roach1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"lo_freq_read_roach2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"lo_freq_read_roach3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"lo_freq_read_roach4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"lo_freq_read_roach5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"lo_center_freq_roach1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"lo_center_freq_roach2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"lo_center_freq_roach3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"lo_center_freq_roach4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"lo_center_freq_roach5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"fpga_clock_freq_roach1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"fpga_clock_freq_roach2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"fpga_clock_freq_roach3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"fpga_clock_freq_roach4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"fpga_clock_freq_roach5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"nflag_thresh_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nflag_thresh_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nflag_thresh_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nflag_thresh_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"nflag_thresh_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"median_df_roach1\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"median_df_roach2\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"median_df_roach3\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"median_df_roach4\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"median_df_roach5\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_1HZ, U_NONE, 0 },\n { \"targ_sweep_span_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"targ_sweep_span_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"targ_sweep_span_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"targ_sweep_span_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"targ_sweep_span_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"trnd_sweep_span_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"trnd_sweep_span_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"trnd_sweep_span_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"trnd_sweep_span_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"trnd_sweep_span_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_1HZ, U_NONE, 0 },\n { \"scan_retune_trigger_roach\", SCALE(CONVERT_UNITY), TYPE_UINT8, RATE_1HZ, U_NONE, 0 },\n { \"kidA_roachN\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_488HZ, U_NONE, 0 },\n { \"kidB_roachN\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_488HZ, U_NONE, 0 },\n { \"kidC_roachN\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_488HZ, U_NONE, 0 },\n { \"kidD_roachN\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_488HZ, U_NONE, 0 },\n { \"kidE_roachN\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_488HZ, U_NONE, 0 },\n { \"kidF_roachN\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_488HZ, U_NONE, 0 },\n { \"kidG_roachN\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_488HZ, U_NONE, 0 },\n { \"kidH_roachN\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_488HZ, U_NONE, 0 },\n { \"kidI_roachN\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_488HZ, U_NONE, 0 },\n { \"kidJ_roachN\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_488HZ, U_NONE, 0 },\n { \"kidK_roachN\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_488HZ, U_NONE, 0 },\n { \"kidL_roachN\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_488HZ, U_NONE, 0 },\n { \"kidM_roachN\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_488HZ, U_NONE, 0 },\n { \"kidN_roachN\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_488HZ, U_NONE, 0 },\n { \"kidO_roachN\", SCALE(CONVERT_UNITY), TYPE_FLOAT, RATE_488HZ, U_NONE, 0 },\n { \"kidA_roachN_index\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"kidB_roachN_index\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"kidC_roachN_index\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"kidD_roachN_index\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"kidE_roachN_index\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"kidF_roachN_index\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"kidG_roachN_index\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"kidH_roachN_index\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"kidI_roachN_index\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"kidJ_roachN_index\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"kidK_roachN_index\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"kidL_roachN_index\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"kidM_roachN_index\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"kidN_roachN_index\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"kidO_roachN_index\", SCALE(CONVERT_UNITY), TYPE_UINT32, RATE_488HZ, U_NONE, 0 },\n { \"flags_kids0000_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0016_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0032_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0048_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0064_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0080_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0096_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0112_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0128_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0144_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0160_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0176_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0192_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0208_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0224_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0240_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0256_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0272_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0288_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0304_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0320_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0336_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0352_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0368_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0384_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0400_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0416_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0432_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0448_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0464_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0480_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0496_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0512_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0528_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0544_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0560_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0576_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0592_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0608_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0624_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0640_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0656_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0672_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0688_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0704_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0720_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0736_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0752_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0768_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0784_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0800_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0816_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0832_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0848_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0864_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0880_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0896_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0912_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0928_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0944_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0960_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0976_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0992_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids1008_roach1\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0000_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0016_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0032_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0048_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0064_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0080_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0096_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0112_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0128_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0144_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0160_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0176_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0192_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0208_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0224_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0240_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0256_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0272_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0288_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0304_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0320_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0336_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0352_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0368_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0384_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0400_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0416_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0432_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0448_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0464_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0480_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0496_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0512_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0528_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0544_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0560_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0576_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0592_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0608_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0624_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0640_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0656_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0672_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0688_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0704_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0720_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0736_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0752_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0768_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0784_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0800_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0816_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0832_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0848_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0864_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0880_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0896_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0912_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0928_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0944_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0960_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0976_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0992_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids1008_roach2\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0000_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0016_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0032_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0048_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0064_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0080_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0096_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0112_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0128_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0144_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0160_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0176_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0192_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0208_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0224_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0240_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0256_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0272_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0288_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0304_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0320_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0336_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0352_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0368_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0384_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0400_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0416_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0432_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0448_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0464_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0480_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0496_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0512_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0528_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0544_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0560_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0576_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0592_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0608_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0624_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0640_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0656_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0672_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0688_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0704_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0720_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0736_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0752_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0768_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0784_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0800_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0816_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0832_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0848_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0864_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0880_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0896_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0912_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0928_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0944_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0960_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0976_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0992_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids1008_roach3\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0000_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0016_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0032_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0048_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0064_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0080_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0096_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0112_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0128_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0144_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0160_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0176_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0192_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0208_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0224_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0240_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0256_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0272_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0288_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0304_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0320_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0336_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0352_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0368_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0384_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0400_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0416_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0432_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0448_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0464_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0480_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0496_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0512_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0528_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0544_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0560_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0576_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0592_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0608_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0624_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0640_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0656_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0672_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0688_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0704_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0720_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0736_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0752_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0768_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0784_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0800_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0816_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0832_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0848_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0864_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0880_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0896_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0912_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0928_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0944_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0960_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0976_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0992_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids1008_roach4\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0000_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0016_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0032_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0048_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0064_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0080_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0096_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0112_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0128_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0144_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0160_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0176_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0192_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0208_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0224_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0240_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0256_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0272_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0288_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0304_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0320_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0336_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0352_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0368_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0384_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0400_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0416_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0432_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0448_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0464_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0480_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0496_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0512_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0528_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0544_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0560_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0576_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0592_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0608_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0624_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0640_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0656_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0672_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0688_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0704_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0720_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0736_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0752_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0768_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0784_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0800_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0816_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0832_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0848_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0864_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0880_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0896_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0912_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0928_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0944_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0960_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0976_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids0992_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n { \"flags_kids1008_roach5\", SCALE(CONVERT_UNITY), TYPE_UINT16, RATE_1HZ, U_NONE, 0 },\n\n /* ----------------------- */\n /* NULL TERMINATE THE LIST */\n /* ----------------------- */\n { {0} }\n };\n\n" }, { "alpha_fraction": 0.6898148059844971, "alphanum_fraction": 0.6990740895271301, "avg_line_length": 20.600000381469727, "blob_id": "82c895af14f6c1bc15f26a27d01ae4d84a79e459", "content_id": "154a5f6319cc450c01259f0cf4bca7432e7c04c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 865, "license_type": "no_license", "max_line_length": 73, "num_lines": 40, "path": "/stars/code/networking/network_manager.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef NETWORKING__NETWORK_MANAGER_H\n#define NETWORKING__NETWORK_MANAGER_H\n\n#include <boost/thread/thread.hpp>\n#include \"../tools/timing.h\"\n\nnamespace Networking\n{\n class NetworkManager;\n}\n\nclass Networking::NetworkManager\n{\n public:\n NetworkManager();\n void run_server();\n void run_image_client_fc1();\n void run_image_client_fc2();\n void reset_network_adapter();\n void watch_for_reset();\n void wait_for_quit();\n\n private:\n\n Tools::Timer time_since_last_reset;\n\n boost::thread server_thread;\n boost::thread image_client_fc1_thread;\n boost::thread image_client_fc2_thread;\n boost::thread reset_thread;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6858638525009155, "alphanum_fraction": 0.6928446888923645, "avg_line_length": 15.852941513061523, "blob_id": "07c8ab128bd9a9442d09867f16cda8e2c89e7d5d", "content_id": "c4248f57d82ffbb7f541c79f33904c30a9126ef7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 574, "license_type": "no_license", "max_line_length": 73, "num_lines": 34, "path": "/stars/code/shared/general/shutdown.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__GENERAL__SHUTDOWN_H\n#define SHARED__GENERAL__SHUTDOWN_H\n\n#include \"../circular_buffer.h\"\n\nnamespace Shared\n{\n namespace General\n {\n\nclass Shutdown\n{\n public:\n Shutdown();\n\n bool shutdown_now;\n bool include_restart;\n};\n\n// writes: network\n// reads: main\nextern Shared::CircularBuffer <Shutdown> shutdown_for_main;\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.6761062145233154, "alphanum_fraction": 0.6942477822303772, "avg_line_length": 25.904762268066406, "blob_id": "8d97b2e543ed3bdd971b7076f949430a3ba8e644", "content_id": "09b6f3e5e3d805b5913f43f9d3a4f9e339df0a9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2260, "license_type": "no_license", "max_line_length": 87, "num_lines": 84, "path": "/blast_comms/include/comms_common.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/**\n * @file comms_common.h\n *\n * @date Jan 17, 2011\n * @author Seth Hillbrand\n * \n * @brief This file is part of FCP, created for the EBEX project\n *\n * This software is copyright (C) 2010-2015 Seth Hillbrand\n *\n * FCP 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 2 of the License, or\n * (at your option) any later version.\n *\n * FCP 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 FCP; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n\n#ifndef INCLUDE_COMMS_COMMON_H\n#define INCLUDE_COMMS_COMMON_H\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <blast.h>\n\n#define DEFAULT_MTU 1432\n\ntypedef int socket_t;\n#define INVALID_SOCK ((socket_t) -1)\n\n/**\n * Socket status signals\n */\n#define NETSOCK_NOT_WRITABLE 1\n#define NETSOCK_WRITABLE 2\n\n/**\n * Socket Return codes\n */\n#define NETSOCK_OK 0\n#define NETSOCK_ERR -1\n#define NETSOCK_CONNECT_TIMEOUT -2\n#define NETSOCK_AGAIN -3\n#define NETSOCK_DATA_ERR -4\n\ntypedef enum\n{\n NETSOCK_STATE_NONE,\n NETSOCK_STATE_CONNECTING,\n NETSOCK_STATE_CONNECTED,\n NETSOCK_STATE_EOS,\n NETSOCK_STATE_CLOSED,\n NETSOCK_STATE_ERROR,\n NETSOCK_STATE_END,\n} e_comms_socket_state;\n\ntypedef void (*netsock_int_callback_t)(int m_code, void *m_priv);\ntypedef int (*netsock_data_callback_t)(const void *m_data, size_t m_len, void *m_priv);\ntypedef void (*netsock_intint_callback_t)(int m_code, int m_errcode, void *m_priv);\n\ntypedef struct netsock_callbacks\n{\n void *priv;\n netsock_data_callback_t data;\n netsock_int_callback_t control;\n netsock_int_callback_t error;\n netsock_data_callback_t finished;\n netsock_intint_callback_t connected;\n} netsock_callbacks_t;\n\n/// Clear definitions unless needed for call tracing\n#define log_enter(...)\n#define log_leave(...)\n\n#endif /* COMMS_COMMON_H_ */\n" }, { "alpha_fraction": 0.6346812844276428, "alphanum_fraction": 0.6439341902732849, "avg_line_length": 16.064327239990234, "blob_id": "924294214c9db93de8f1eab4645ec66405528802", "content_id": "525bad17ca0e32ee45f2c43c6e0cab17588783ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2918, "license_type": "no_license", "max_line_length": 71, "num_lines": 171, "path": "/interloquendi/quendi.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* quendi.h: an implementation of the Quenya Protocol\n *\n * This software is copyright (C) 2004 University of Toronto\n * \n * quendi 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 2 of the License, or\n * (at your option) any later version.\n * \n * quendi 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 quendi; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#ifndef QUENDI_H\n#define QUENDI_H\n\n#include <linux/limits.h>\n\n/* Protocol definitions */\n#include \"quenya.h\"\n\n/* Server Constants */\n#define QUENDI_COMMAND_LENGTH 1024\n#define QUENDI_RESPONSE_LENGTH 1024\n\nstruct quendi_server_data_t {\n const char* server_version;\n const char* server_name;\n const char* server_host;\n const char* rendezvous_name;\n int access_level;\n char* directory;\n int csock;\n};\n\nstruct quendi_data_port_t {\n int sock;\n int staged;\n int persist;\n int port_active;\n unsigned frame_size;\n unsigned long pos;\n unsigned long seek_to;\n char name[PATH_MAX];\n char chunk[PATH_MAX];\n int new_chunk;\n int sending_data;\n int fd;\n int chunk_total;\n unsigned long frames_read;\n int block_length;\n unsigned remainder;\n};\n\nint quendi_access_ok(\n int\n );\n\nvoid quendi_add_data_port(\n const struct quendi_data_port_t*\n );\n\nint quendi_advance_data(\n int,\n char*,\n int,\n int*,\n const char*,\n char*,\n int,\n unsigned\n );\n\nint quendi_cmdnum(\n char*\n );\n\nint quendi_dp_connect(\n void\n );\n\nint quendi_get_cmd(\n char*\n );\n\nint quendi_get_next_param(\n char*,\n int*,\n char[][QUENDI_COMMAND_LENGTH]\n );\n\nchar* quendi_make_response(\n char*,\n int,\n const char*\n );\n\nint quendi_parse(\n char*,\n int*,\n char[][QUENDI_COMMAND_LENGTH]\n );\n\nunsigned long quendi_reader_init(\n unsigned,\n unsigned long,\n char*,\n const char*,\n int\n );\n\nvoid quendi_reader_shutdown(\n int,\n int\n );\n\nint quendi_read_data(\n int,\n int*,\n const char*,\n unsigned long,\n int*,\n unsigned,\n unsigned long*,\n unsigned*\n );\n\nint quendi_respond(\n int,\n const char*\n );\n\nint quendi_rp_connect(\n const char*\n );\n\nvoid quendi_send_data(\n int,\n unsigned,\n int\n );\n\nvoid quendi_send_spec(\n int,\n const char*\n );\n\nvoid quendi_server_init(\n const struct quendi_server_data_t*\n );\n\nvoid quendi_server_shutdown(\n void\n );\n\nint quendi_stage_data(\n const char*,\n unsigned long,\n int,\n int,\n unsigned\n );\n\n#endif\n" }, { "alpha_fraction": 0.5754716992378235, "alphanum_fraction": 0.6041509509086609, "avg_line_length": 32.125, "blob_id": "50e422fe0dc50a8fbf1cb738e897e9e5537f2717", "content_id": "04c4be865fc5cd3fa5df55796d77674e621daea1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2650, "license_type": "no_license", "max_line_length": 79, "num_lines": 80, "path": "/owl/PExtrema.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#ifndef PEXTREMA_H\n#define PEXTREMA_H\n\n#include \"PObject.h\"\n#include \"PStyle.h\"\n#include <QObject>\n#include <QColor>\n\nclass PExtrema : public QObject, public PObject\n{\n Q_OBJECT\n QString _name;\npublic:\n friend QDataStream& operator<<(QDataStream&,PExtrema&b);\n friend QDataStream& operator>>(QDataStream&,PExtrema&b);\n friend QVariant save(PExtrema&);\n friend void load(QVariant v,PExtrema&);\n static QList<PExtrema*> _u;\n float _xhigh,_high,_low,_xlow;\n PStyle* _sxhigh,*_shigh,*_slow,*_sxlow;\n const QString& name() const { return _name; }\n\n PExtrema() : _xhigh(2.0f),_high(1.0f),_low(-1.0f),_xlow(-2.0f)\n {\n _u.push_back(this);\n bool xmaxok=0,maxok=0,minok=0,xminok=0;\n for(int i=0;i<PStyle::_u.size();i++) {\n Q_ASSERT(PStyle::_u[i]);\n if(PStyle::_u[i]->name()==\"xhigh\") {\n _sxhigh=PStyle::_u[i];\n xmaxok=1;\n } else if(PStyle::_u[i]->name()==\"high\") {\n _shigh=PStyle::_u[i];\n maxok=1;\n } else if(PStyle::_u[i]->name()==\"low\") {\n _slow=PStyle::_u[i];\n minok=1;\n } else if(PStyle::_u[i]->name()==\"xlow\") {\n _sxlow=PStyle::_u[i];\n xminok=1;\n }\n }\n _sxhigh=xmaxok?_sxhigh:new PStyle(\"xhigh\",1,0,\"#ffaaaa\",\"#000055\",1);\n _shigh=maxok?_shigh:new PStyle(\"high\",1,0,\"white\",\"#ff0000\",1);\n _slow=minok?_slow:new PStyle(\"low\",1,0,\"white\",\"#00bb00\",1);\n _sxlow=xminok?_sxlow:new PStyle(\"xlow\",1,0,\"#00ff00\",\"#000033\",1);\n }\n\n ~PExtrema() { _u.removeOne(this); }\n PStyle* formatForValue(float val,PStyle* defaultValue);\n\npublic slots:\n void setName(QString name);\n\nsignals:\n void nameChanged(QString name);\n};\n\n#endif // PEXTREMA_H\n" }, { "alpha_fraction": 0.6501650214195251, "alphanum_fraction": 0.6508983969688416, "avg_line_length": 41.27906799316406, "blob_id": "360526a3fb9b23bf6b5fc86eeade76d91e0cd6f1", "content_id": "ed9dd7358373d2bdd121958eed220d35489c9ad8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5454, "license_type": "no_license", "max_line_length": 87, "num_lines": 129, "path": "/starcam/frameblob.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* \n frameblob.h\n\n class which takes a bitmapped frame and locates blobs (where\n blobs are stored as a linked list)\n\n Depends on bloblist class, some definitions in mapglobals.\n\n This class has been altered slightly from previous (BLAST) version\n*/\n\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"bloblist.h\"\n#include \"camconfig.h\"\n\n#ifndef FRAMEBLOB_H\n#define FRAMEBLOB_H\n\n#define D 15 // Size of the box used by findCentre\n#define R 2 // Radius of the parabolic smoothing kernel for findCentre\n\nclass frameblob {\n public:\n // --- Constructors / Destructor ---\n frameblob( void ); // Constructors\n frameblob( MAPTYPE *map_in, unsigned int xpix_in, unsigned int ypix_in,\n unsigned int bits_in, double platescale_in );\n/* void commonconstructor(MAPTYPE *map_in, unsigned int xpix_in, \n unsigned int ypix_in,\n unsigned int bits_in, double platescale_in ); \n*/\n void commonconstructor(FrameBlobConfigParams params = defaultImageParams.blobParams);\n ~frameblob(); // Destructor\n \n void set_map( MAPTYPE *in_map );\n void set_map( MAPTYPE *in_map, int height, int width );\n MAPTYPE *get_map(void) { return map; };\n \n // --- Add blob, delete blob, return blob list ---\n void addblob( int flux, double x, double y ); // Add a blob to the list\n void deleteblob( bloblist *killblob ); // Remove blob from the list\n void clearblobs(); // Clear the whole blob list \n bloblist *getblobs(); // return pointer to 1st blob in list\n void sortblobs(); // sort blobs by descending order of flux\n void set_maxblobs(unsigned int in_maxblobs); // set maximum number of blobs\n \n // --- Bad pixel map ---\n int load_badpix(const char *fname); // Load bad pixel map from file\n void fix_badpix(MAPTYPE val); // set bad pixels to val\n \n // --- Set search parameters ---\n void set_satval( MAPTYPE in_satval ); // set numeric value of sat pixels\n void set_grid( unsigned int in_grid ); // coarse grid pixsize\n void set_threshold( double in_threshold ); // n sigma source threshold\n void set_disttol( int in_disttol ); // adjacent source dist tolerance\n \n // --- Get search parameters ---\n MAPTYPE get_satval(void) { return satval; };\n unsigned int get_maxblobs(void) { return maxblobs; }\n unsigned int get_grid(void) { return grid; };\n double get_threshold(void) { return threshold; };\n int get_disttol(void);\n \n // --- Source find / map statistics ---\n void calc_mapstat(); // calc map mean + count # saturated pixels each col.\n double get_mapmean(); // return the map mean - calls mapstat\n double get_sigma(); // return estimates standard deviation of the image\n double get_stddev() { return stddev; }\n void calc_searchgrid();// find cells in search grid with sources\n void fix_multiple(); // check for multiple sources w/i disttol and fix\n \n void set_gain( double in_gain );\n void set_readout_offset( double in_readout_offset );\n void set_readout_noise( double in_readout_noise );\n \n double get_gain(void) { return gain; };\n double get_readout_offset(void) { return readout_offset; };\n double get_readout_noise(void) { return readout_noise; };\n int get_numblobs(void) { return numblobs; };\n \n double calc_stddev(void);\n \n private:\n // better centroid\n void findCentre(double *x, double *y, double *z, double M[D][D]); \n double convolve(double x, double y, double *noise, double M[D][D]); \n \n MAPTYPE *map; // Pointer to the map buffer\n unsigned int bits; // number of bits per pixel\n unsigned int xpix; // # pixels wide\n unsigned int ypix; // # pixels high\n unsigned int npix; // # pixels in total map\n \n double *searchgrid; // coarse grid cells - store S/N brightest pixel\n double *meangrid; // array of mean values for each grid cell\n unsigned int xgrid; // dimensions of the search grid array\n unsigned int ygrid; // \"\n unsigned int ngrid; // \"\n \n double platescale; // number of degrees/pixel in the image\n double gain; // gain applied to N_photons going to measured val\n double readout_offset; // constant offset in the frame \n double readout_noise; // constant RMS noise added to frame due to readout\n \n bloblist *firstblob; // blob linked list pointers (sources)\n bloblist *lastblob;\n bloblist *thisblob; // multi-purpose blob pointer for list traversal\n unsigned int numblobs;\n unsigned int maxblobs; // won't exceed this number of blobs if non-zero\n \n unsigned int *badpixels; // array of indices of bad pixels in CCD frames\n unsigned int numbadpix; // # of bad pixels\n \n double mapmean; // the mean value of the total map\n double sigma; // estimated standard deviation of the map\n double stddev; // measured standard deviation of the map\n MAPTYPE satval; // numerical value of a saturated pixel\n int *satcol; // # saturated pixels in each column of the map\n double convweight; // weight of the convolution filter\n\n unsigned int grid; // # pixels/side in coarse grid\n double threshold; // N sigma threshold for detection \n int disttol; // distance tolerance adjacent sources in pixels\n};\n\n#endif //FRAMEBLOB_H\n" }, { "alpha_fraction": 0.691577672958374, "alphanum_fraction": 0.6963226795196533, "avg_line_length": 18.604650497436523, "blob_id": "9c2093b92e5b0a3b0cb213db6337ef12ce8472c6", "content_id": "e7d66989f5b3ee2581bd35610354be7a77ce52fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 844, "license_type": "no_license", "max_line_length": 73, "num_lines": 43, "path": "/stars/code/shared/camera/requests.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__CAMERA__REQUESTS_H\n#define SHARED__CAMERA__REQUESTS_H\n\n#include \"../circular_buffer.h\"\n#include \"../request.h\"\n\nnamespace Shared\n{\n namespace Camera\n {\n\nclass Requests\n{\n public:\n Requests();\n Requests& operator=(const Requests& rhs);\n\n ::Shared::Request<double> set_gain;\n ::Shared::Request<double> get_gain;\n unsigned int max_num_triggers;\n double multi_triggering_delay;\n};\n\n// writes: network\n// reads: main\nextern Shared::CircularBufferPass <Requests> requests_for_main;\n\n// writes: main\n// reads: camera\nextern Shared::CircularBuffer <Requests> requests_for_camera;\n\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.6351931095123291, "alphanum_fraction": 0.6382587552070618, "avg_line_length": 17.325841903686523, "blob_id": "16aca0f2aaeed3ff99b07cfc2c818cea05d03a03", "content_id": "0e7949777a3b0c578143108e2ae523cf589d7377", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1632, "license_type": "no_license", "max_line_length": 73, "num_lines": 89, "path": "/stars/code/shared/image/status.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__IMAGE__STATUS_H\n#define SHARED__IMAGE__STATUS_H\n\n#include <string>\n#include \"../circular_buffer.h\"\n#include \"../../tools/timing.h\"\n\nnamespace Logging\n{\n class Logger;\n}\n\nnamespace Shared\n{\n namespace Image\n {\n\nclass Raw;\n\nclass Status\n{\n public:\n\n enum Stages {\n empty=0,\n doing_statistics,\n blob_finding,\n pattern_matching,\n refitting,\n getting_names,\n done\n };\n\n enum ReasonsForBeingDone {\n no_reason,\n solved,\n not_solving,\n saturated,\n tried_all_patterns,\n timed_out,\n aborted\n };\n\n Status();\n void init(Parameters::Manager& params);\n Status& operator=(const Status& rhs);\n Status& operator=(const Raw& rhs);\n\n int counter_stars;\n bool from_camera;\n int abort_counter;\n int num_exposures;\n int counter_fcp;\n bool horizontal_known;\n double lat;\n double lst;\n std::string filename;\n Stages stage;\n ReasonsForBeingDone reason_for_being_done;\n Tools::Timer age;\n int width;\n int height;\n int depth;\n};\n\n// writes: solver\n// reads: main\nextern Shared::CircularBufferPass <Status> status_solver_for_main;\n\n// writes: main\n// reads: camera\nextern Shared::CircularBufferPass <Status> status_main_for_camera;\n\n// writes: camera\n// reads: network\nextern Shared::CircularBuffer <Status> status_camera_for_network;\n\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.5483871102333069, "alphanum_fraction": 0.5806451439857483, "avg_line_length": 14.5, "blob_id": "2f782e376413109cd553c1d3f41c3d1707f316f4", "content_id": "f727526cbe8adecf2a17c4809434a76ec8b815c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 155, "license_type": "no_license", "max_line_length": 57, "num_lines": 10, "path": "/check_formatfile.sh", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nif [ -z \"$1\" ]\nthen\n FILENAME=\"/data/etc/mole.lnk/format\"\nelse\n FILENAME=\"$1\"\nfi\n\nawk 'x[$1]++ == 1 { print $1 \" is duplicated\"}' $FILENAME\n" }, { "alpha_fraction": 0.6646180748939514, "alphanum_fraction": 0.6681299209594727, "avg_line_length": 17.370967864990234, "blob_id": "e8779ab59c5e1aabb5cce3fb4f20d3001520bf16", "content_id": "1110121a0e99455546ef79c40257f1ff193b80a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1140, "license_type": "no_license", "max_line_length": 100, "num_lines": 62, "path": "/stars/code/logging/logger.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef LOGGING__LOGGER_H\n#define LOGGING__LOGGER_H\n\n#include <string>\n#include <boost/format.hpp>\n\nusing std::string;\nusing boost::format;\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Tools\n{\n class Timer;\n}\n\nnamespace boost\n{\n namespace posix_time\n {\n class ptime;\n }\n}\n\nnamespace Logging\n{\n class Logger;\n}\n\nclass Logging::Logger\n{\n public:\n Logger(string log_name_);\n Logger(string log_name_, bool writing_to_stdout_);\n void construct(string log_name_, bool writing_to_stdout_);\n ~Logger();\n void log(string info);\n void log(boost::format& info);\n void init(Parameters::Manager& params, boost::posix_time::ptime& birthtime, Tools::Timer& age_);\n void flush();\n void update();\n Tools::Timer* age;\n\n private:\n std::ofstream* my_stream;\n string name;\n bool writing_to_stdout;\n Tools::Timer* timer_since_last_flush;\n double flush_period;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6985377073287964, "alphanum_fraction": 0.7088863849639893, "avg_line_length": 25.61676597595215, "blob_id": "775eed38367a49f135068ebde70c72d44026647a", "content_id": "d8887900f07565b3a8514fd8d0f4de828f456597", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4445, "license_type": "no_license", "max_line_length": 79, "num_lines": 167, "path": "/owl/PMainWindow.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* Owl: BLAST status GUI\n *\n * This file is part of Owl.\n *\n * Owl (originally \"palantir\") is copyright (C) 2002-2012 University of Toronto\n *\n * Owl 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 2 of the License, or\n * (at your option) any later version.\n *\n * Owl 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 Owl; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include <QMainWindow>\n#include <QDataStream>\n#include <QScrollArea>\n#include <QSystemSemaphore>\n#include <QSettings>\n#include <QMimeData>\n#include <time.h>\n#include \"PAbstractDataItem.h\"\n#include \"PObject.h\"\n#include \"PBox.h\"\n#include \"POwlAnimation.h\"\n\n#if QT_VERSION >= 0x050300\n#include \"PWebServer.h\"\n#endif\n\n#ifndef PMAINWINDOW_H\n#define PMAINWINDOW_H\n#define _WINDOW_TITLE_ \"Owl 5.x\"\n\nstruct PTimeDataItem;\n\nclass QLineEdit;\n\nnamespace Ui {\nclass PMainWindow;\n}\n\nclass PMainWindow : public QMainWindow, public PObject\n{\n Q_OBJECT\nprotected:\n QTimer* _ut;\n QTimer* _reset_timer;\n QObject* _currentObject;\n GetData::Dirfile* _dirfile;\n QString _dirfileFilename;\n PMdiArea* _mdiArea;\n QScrollArea* _scrollArea;\n QString oldStyle;\n QString oldLayout;\n int styleVersion;\n int layoutVersion;\n PStyle* _currowStyle;\n QList<PBox*> _pboxList;\n QList<POwlAnimation*> _owlList;\n bool _dirty;\n int _link;\n void keyPressEvent ( QKeyEvent * e );\n void contextMenuEvent(QContextMenuEvent * event);\n#if QT_VERSION >= 0x050300\n PWebServer* _server;\n#endif\n\n bool _deleteScheduled;\n QSettings *_settings;\n int _lastNFrames;\n time_t _lastUpdate;\n\npublic:\n friend QDataStream& operator<<(QDataStream&a,PMainWindow&b);\n friend QDataStream& operator>>(QDataStream&a,PMainWindow&b);\n friend QVariant save(PMainWindow&);\n friend void load(QVariant v,PMainWindow&b);\n friend class POwlAnimation;\n friend class PBox;\n friend class PAbstractDataItem;\n friend class PMdiArea;\n static PMainWindow* me;\n explicit PMainWindow(int font_size, QString file=\"\", QWidget *parent = 0);\n QObject* currentObject() const { return _currentObject; }\n virtual ~PMainWindow();\n void closeEvent(QCloseEvent *);\n bool mouseInactive();\n QStringList linkNames();\n\npublic slots:\n void readmeHelp();\n\n void hideEverything();\n void addPBox();\n void setCurrentObject(PBox*);\n void setCurrentObject(PAbstractDataItem*);\n void setCurrentObject(PExtremaDataItem*);\n void setCurrentObject(PNumberDataItem*);\n void setCurrentObject(PMultiDataItem*);\n void setCurrentObject(PBitMultiDataItem*);\n void setCurrentObject(PTimeDataItem*);\n void setCurrentObject(POwlAnimation*);\n\n void uiLogic();\n void curfileLogic(bool force = false);\n void setFileLineEditValidity(QLineEdit* fle);\n void newLabelLogic(PAbstractDataItem* padi);\n void resetLink() {curfileLogic(true);}\n void setLink(int link, QStringList linkNames);\n\n void extremaLogic(QString);\n void extremaXHighLogic(double);\n void extremaHighLogic(double);\n void extremaLowLogic(double);\n void extremaXLowLogic(double);\n\n void showInKst();\n\n void bitmultiLogic();\n void multiLogic();\n void currowLogic();\n\n void gdUpdate();\n void serverUpdate();\n\n void removeCurrentDataItem();\n void obviate(PBox* byeBye);\n void obviate(PAbstractDataItem* byeBye);\n void obviate(POwlAnimation* byeBye);\n void recognizeExtrema(PExtrema*);\n\n#if QT_VERSION >= 0x050300\n int webPort();\n void setWebPort(const int& port);\n void setWebEnabled(const bool& enabled);\n#endif\n\n QVariant state();\n QVariant stateChanges();\n\n void activate();\n\n void owlSave();\n void owlSaveAs();\n void owlLoad(QString file=\"\");\n void addOwl();\n\n void setMDIMinSize(int w, int h);\n\n void showToolbar(bool show);\nprivate:\n QVariant _data();\n Ui::PMainWindow *ui;\n};\n\nQDataStream& operator<<(QDataStream&a,PMainWindow&b);\nQDataStream& operator>>(QDataStream&a,PMainWindow&b);\n\n#endif//PMAINWINDOW_H\n" }, { "alpha_fraction": 0.5697838068008423, "alphanum_fraction": 0.5833439826965332, "avg_line_length": 28.383459091186523, "blob_id": "494db56618a80267b29bd1567bbf5ba60c1736df", "content_id": "d2846a6f3b4a7c4f1e842b3c0035b6a6f2b69c0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7818, "license_type": "no_license", "max_line_length": 120, "num_lines": 266, "path": "/stars/code/displaying/manager.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"manager.h\"\n#include \"../parameters/manager.h\"\n#include \"../shared/general/main_settings.h\"\n#include \"../shared/general/quit.h\"\n#include \"../logger_main.h\"\n#include \"../preprocessor.h\"\t\t\n#include \"../tools/quick_cout.h\"\n\n\nusing namespace Displaying;\nusing Main::logger;\nusing std::max;\nusing std::min;\n\n#define shared_main_settings (*(Shared::General::main_settings_net_for_main.r))\n\nDisplayManager::DisplayManager(Parameters::Manager& params):\n textures(params), visual(params)\n{\n if (PREPROCESSOR_USING_CAMERA > 0) {\n using_camera = true;\n } else {\n using_camera = false;\n }\n screen = NULL;\n enabled = params.general.try_get(\"main.display_enabled\", true);\n fullscreen = shared_main_settings.display_fullscreen;\n shared_fullscreen_counter = shared_main_settings.display_fullscreen_counter;\n\n normal_screen_size.w = 800;\n normal_screen_size.h = 600;\n\n full_screen_size.w = 1024;\n full_screen_size.h = 768;\n\n if (fullscreen) {\n current_screen_size = full_screen_size;\n } else {\n current_screen_size = normal_screen_size;\n }\n\n resolution.w = 640;\n resolution.h = 480;\n\n current_zoom_x = 320;\n current_zoom_y = 240;\n current_zoom_magnitude = 1.0;\n\n if ( SDL_Init(SDL_INIT_EVERYTHING) != 0 ) {\n logger.log(format(\"Unable to initialize SDL: %s\") % SDL_GetError());\n }\n SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1) ;\n //SDL_SetWindowTitle(\"STARS\", \"STARS\");\n\tSDL_WM_SetCaption(\"STARS\", \"STARS\");\n\n set_video_mode();\n textures.init();\n init();\n name.set_title(params.general.try_get(\"main.which_sensor\", std::string(\"(sensor name)\")));\n}\n\nDisplayManager::~DisplayManager()\n{\n}\n\nvoid DisplayManager::init()\n{\n if (!enabled) return;\n glEnable(GL_TEXTURE_2D);\n glLineWidth(2.0);\n\n housekeeping.init(\"Housekeeping\", textures);\n camera_block.init(\"Camera\", textures);\n lens.init(\"Lens\", textures);\n image.init(\"Working Block\", textures);\n visual.init(\"Visual\", textures);\n autofocus.init(\"Autofocus\", textures);\n solving_filters.init(\"Solving Filters\", textures);\n quit_box.init(\"QUIT\", textures);\n name.init(\"(sensor name)\", textures);\n\n autofocus.change_size(image.width(), image.height());\n solving_filters.change_size(image.width(), image.height());\n}\n\nvoid DisplayManager::set_video_mode()\n{\n Uint32 flags = SDL_OPENGL | SDL_RESIZABLE;\n if (fullscreen) {\n flags |= SDL_FULLSCREEN;\n current_screen_size = full_screen_size;\n } else {\n current_screen_size = normal_screen_size;\n }\n SDL_FreeSurface(screen);\n if (enabled) screen = SDL_SetVideoMode(int(current_screen_size.w), int(current_screen_size.h), 32, flags);\n if (!screen) {\n logger.log(\"after call to SDL_SetVideoMode, screen is NULL\");\n logger.log(format(\" error is: %s\") % SDL_GetError());\n }\n reshape();\n}\n//Changed to work with SDL2\nvoid DisplayManager::reshape()\n{\n if (!enabled) return;\n glViewport(0, 0, int(current_screen_size.w), int(current_screen_size.h));\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluOrtho2D(0.0, resolution.w, 0.0, resolution.h);\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n}\n\n\nvoid DisplayManager::process_events()\n{\n if (!enabled) return;\n static SDL_Event event;\n while ( SDL_PollEvent(&event) ) {\n switch ( event.type ) {\n case SDL_VIDEORESIZE:\n normal_screen_size.w = (double)event.resize.w;\n normal_screen_size.h = (double)event.resize.h;\n set_video_mode();\n break;\n case SDL_KEYDOWN:\n switch ( event.key.keysym.sym ) {\n case SDLK_ESCAPE:\n Shared::General::quit = true;\n break;\n case SDLK_q:\n Shared::General::quit = true;\n break;\n case SDLK_f:\n break;\n case SDLK_n:\n break;\n default:\n break;\n }\n break;\n case SDL_QUIT:\n Shared::General::quit = true;\n break;\n default:\n break;\n }\n }\n}\n\nvoid DisplayManager::print_available_chars()\n{\n logger.log(\"display reporting available characters:\");\n for (int i=textures.font.GetStartChar(); i<=textures.font.GetEndChar(); i++) {\n logger.log(format(\"%d %c\") % i % char(i));\n }\n}\n\nvoid DisplayManager::update_zoom(double delta_t)\n{\n if (delta_t > 0.2) {\n delta_t = 0.2;\n }\n current_zoom_x += 5.0*((double) shared_main_settings.display_zoom_x-current_zoom_x)*delta_t;\n current_zoom_y += 5.0*((double) shared_main_settings.display_zoom_y-current_zoom_y)*delta_t;\n current_zoom_magnitude += 5.0*((double) shared_main_settings.display_zoom_magnitude-current_zoom_magnitude)*delta_t;\n\n}\n\nvoid DisplayManager::draw()\n{\n if (!enabled) return;\n\n if (shared_fullscreen_counter != shared_main_settings.display_fullscreen_counter) {\n shared_fullscreen_counter = shared_main_settings.display_fullscreen_counter;\n }\n\n housekeeping.update();\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n glEnable(GL_BLEND);\n\tglEnable(GL_LINE_SMOOTH);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glPushMatrix();\n glTranslated(resolution.w/2.0, resolution.h/2.0, 0.0);\n glScaled(current_zoom_magnitude, current_zoom_magnitude, 1.0);\n glTranslated(-current_zoom_x, -current_zoom_y, 0.0);\n\n if (shared_main_settings.display_image_only) {\n double padding = 2.0;\n\n Size max_size;\n max_size.w = resolution.w - 2.0*padding;\n max_size.h = resolution.h - 2.0*padding;\n visual.update_size(max_size);\n\n Position pos;\n pos.x = padding;\n pos.y = resolution.h - visual.height() - 1.0*padding;\n visual.update();\n visual.draw(pos);\n }\n else {\n\n double padding = 5.0;\n Size max_size;\n max_size.w = resolution.w - name.width() - 3*padding;\n max_size.h = resolution.h - image.height() - 3*padding;\n visual.update_size(max_size);\n\n glColor4f(1.0, 1.0, 1.0, 1.0);\n\n Position pos;\n pos.x = padding;\n pos.y = resolution.h - visual.height() - image.height() - 2*padding;\n\n if (autofocus.display_enabled()) {\n autofocus.draw(pos);\n } else {\n if (shared_main_settings.display_solving_filters) {\n solving_filters.draw(pos);\n } else {\n image.draw(pos);\n }\n }\n glColor4f(1.0, 1.0, 1.0, 1.0);\n\n pos.x = visual.width() + 2.0*padding;\n pos.y = resolution.h - name.height() - padding;\n name.draw(pos);\n pos.y -= (housekeeping.height() + padding);\n housekeeping.draw(pos);\n if (using_camera) {\n pos.y -= (camera_block.height() + padding);\n camera_block.draw(pos);\n }\n pos.y -= (lens.height() + padding);\n lens.draw(pos);\n pos.x = padding;\n pos.y = resolution.h - visual.height() - padding;\n\n visual.update();\n visual.draw(pos);\n\n if (Shared::General::quit) {\n pos.x += visual.width()/2 - quit_box.width()/2;\n pos.y += visual.height()/2 - quit_box.height()/2;\n quit_box.draw(pos);\n }\n }\n\n glPopMatrix();\n SDL_GL_SwapBuffers();\n}\n\nvoid DisplayManager::wait_for_quit(){\n if (!enabled) return;\n SDL_Quit();\n}\n\n" }, { "alpha_fraction": 0.5899665355682373, "alphanum_fraction": 0.6093645691871643, "avg_line_length": 31.478260040283203, "blob_id": "beeecc87c86c45232d44133e7ac30a2838216f19", "content_id": "78df40feae37f1183b11e84626a2abf3a732a000", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1496, "license_type": "no_license", "max_line_length": 101, "num_lines": 46, "path": "/stars/code/imaging/fake_sky.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"fake_sky.h\"\n#include <time.h>\n#include \"../shared/simulations/brightness.h\"\n#include \"../tools/stats.h\"\n#include \"../tools/quick_cout.h\"\n\nusing namespace Imaging;\n\n#define shared_brightness (*(Shared::Simulations::brightness.r))\n\nFakeSky::FakeSky(): sto((int) time(0))\n{\n}\n\nvoid FakeSky::match_brightness(unsigned short pixels[], int width, int height, int depth)\n{\n double final_level_e = shared_brightness.level_kepsa*1000.0*shared_brightness.simulated_exposure;\n double scaling = shared_brightness.simulated_exposure / shared_brightness.actual_exposure;\n double gain = 0.04096 * pow(10.0, shared_brightness.gain_db/20.0);\n double existing_level_e = get_mean(pixels, width*height) * scaling / gain;\n double missing_level_e = final_level_e - existing_level_e;\n if (missing_level_e < 0) {\n missing_level_e = 0;\n }\n\n for (int j=0; j<height; j++) {\n for (int i=0; i<width; i++) {\n int k = j*width + i;\n double pixel = pixels[k];\n pixel *= scaling;\n pixel += sto.Poisson(missing_level_e)*gain;\n pixels[k] = int(pixel);\n if (pixels[k] < 0) {\n pixels[k] = 0;\n } else if (pixels[k] >= depth) {\n pixels[k] = depth-1;\n }\n }\n }\n}\n\n" }, { "alpha_fraction": 0.6785714030265808, "alphanum_fraction": 0.6857143044471741, "avg_line_length": 17.032258987426758, "blob_id": "4d940291863f639f613538ce8f8e86166cc6fe64", "content_id": "8fbad6b0439f7d9c0bf224a4f549858b2f14d15a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 561, "license_type": "no_license", "max_line_length": 73, "num_lines": 31, "path": "/stars/code/displaying/name.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef DISPLAYING__NAME_H\n#define DISPLAYING__NAME_H\n\n#include \"block.h\"\n#include \"../tools/timing.h\"\n\nnamespace Displaying\n{\n class Name;\n}\n\nclass Displaying::Name: public Block\n{\n public:\n Name();\n void draw_packets();\n void draw_network_resetting();\n void draw(Position& position);\n\n private:\n Tools::Timer timer;\n};\n\n#endif\n\n" }, { "alpha_fraction": 0.6907073259353638, "alphanum_fraction": 0.694868266582489, "avg_line_length": 12.884614944458008, "blob_id": "8ddb59660084018f7fa39d4380f7b62d82e5bf50", "content_id": "9fda36063d070f0edb3114e48819c9f1b92cec2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 721, "license_type": "no_license", "max_line_length": 88, "num_lines": 52, "path": "/balloon_cam/camera.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "//camera.h\n//a class to interface with the camera\n\n#pragma once\n\n\nclass Camera{\n\n\tpublic:\n\n\t\tCamera();\n\n\t\tbool closeCamera(); //shut down the camera, frees the memory\n\n\t\tvoid* capture(); //takes a picture when triggered, returns the address of the picture \n\n\t\tint getXSize();\n\n\t\tint getYSize();\n\n\t\tint getPixelSize();\n\n\t\tdouble getExposureTime();\n\n\t\tvoid saveActiveData();\n\n\t\tbool open(){return isOpen;};\n\n\tprivate:\n\t\t\n\t\tbool initCamera(); //starts up the camera, initializes the memory\n\n\t\tHIDS cameraHandle;\n\n\t\tbool isOpen;\n\n\t\tvoid* activeMemoryLocation;\n\n\t\tchar* memoryPointer;\n\n\t\tSENSORINFO sensorInfo;\n\n\t\tBOARDINFO boardInfo;\n\n\t\tint colourDepth;\n\t\t\n\t\tint memoryID;\n\n\t\tdouble exposureTime;\n\n\t\tchar* ringBuffer[101];\n};" }, { "alpha_fraction": 0.6725663542747498, "alphanum_fraction": 0.6792035102844238, "avg_line_length": 18.65217399597168, "blob_id": "45264bb745e91d9cc3b1e8ce00935654a3bb1c24", "content_id": "abcb97158573e9b67cb9409dbae0fdd618743d05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 452, "license_type": "no_license", "max_line_length": 54, "num_lines": 23, "path": "/groundhog/bit/groundhog.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#include \"groundhog_funcs.h\"\n\n/* ------ BEGIN CUSTOM GROUNDHOG DEFINITIONS ------ */\n\n// groundhog customization\n#define GROUNDHOG_MAX_FRAMES_RESET 900\n\n// BIT telemetry\n#include \"netcmd.h\"\n#include \"cmdparser.h\"\n#include \"telemparser.h\"\n#ifndef MAX\n#define MAX(a, b) ((a) > (b) ? (a):(b))\n#endif\n\n// BIT pilot\n#include \"bitserver.h\"\n#include \"address.h\"\n#include \"comms.h\"\nvoid udp_receive(void *arg);\n\n// BIT biphase\nvoid biphase_receive(void *arg);\n" }, { "alpha_fraction": 0.6506469249725342, "alphanum_fraction": 0.6839186549186707, "avg_line_length": 29, "blob_id": "8362d099907669396d8bba78fa03b2fef2d8af34", "content_id": "9e4185c97d786b4646b9903f6a7cda62e6de568e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 541, "license_type": "no_license", "max_line_length": 78, "num_lines": 18, "path": "/blast_config/slowdl_struct.c", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/* slowdl_struct.c: contains the slow channel lists\n *\n * This software is copyright (C) 2013 University of Toronto\n *\n * This file is part of mcp/pcm licensed under the GNU General Public License.\n *\n * You should have received a copy of the GNU General Public License\n * along with this software; if not, write to the Free Software Foundation,\n * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n#include \"slowdl.h\"\n\nstruct SlowDlStruct slowDLList[] = {\n {\"plover\", 'u', SDL_RAW},\n {\"time\", 'U', SDL_RAW},\n {\"\"}\n};\n\n" }, { "alpha_fraction": 0.6695095896720886, "alphanum_fraction": 0.6982942223548889, "avg_line_length": 30.233333587646484, "blob_id": "fba4f70fa29281a3a4a60e1656f729adb39965bc", "content_id": "4f421d825833d2025771fb5cda5ec680dd49cb0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 939, "license_type": "no_license", "max_line_length": 92, "num_lines": 30, "path": "/stars/code/shared/general/main_settings.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"main_settings.h\"\n#include \"../../parameters/manager.h\"\n\nusing namespace Shared::General;\n\nMainSettings::MainSettings()\n{\n display_period = 1.0 / 20.0;\n display_fullscreen = true;\n display_fullscreen_counter = 0;\n display_image_only = false;\n display_solving_filters = false;\n display_image_brightness = 1.0;\n display_zoom_x = 320;\n display_zoom_y = 240;\n display_zoom_magnitude = 1.0;\n}\n\nvoid MainSettings::init(Parameters::Manager& params)\n{\n display_period = 1.0 / params.general.try_get(\"main.display_frequency\", 20.0);\n display_fullscreen = params.general.try_get(\"main.display_fullscreen\", true);\n display_image_brightness = params.general.try_get(\"main.display_image_brightness\", 1.0);\n}\n\n" }, { "alpha_fraction": 0.6906474828720093, "alphanum_fraction": 0.6978417038917542, "avg_line_length": 20.045454025268555, "blob_id": "9f627dfdee350f63ea893ed0e29aedf5c0dc7a78", "content_id": "2cde850e49464f42be41096688012b2c48e80bb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1391, "license_type": "no_license", "max_line_length": 81, "num_lines": 66, "path": "/stars/code/shared/lens/requests.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SHARED__LENS__REQUESTS_H\n#define SHARED__LENS__REQUESTS_H\n\n#include \"../circular_buffer.h\"\n#include \"../request.h\"\n#include \"../../imaging/commands.h\"\n\nnamespace Shared\n{\n namespace Lens\n {\n\nclass Requests\n{\n public:\n Requests();\n Requests& operator=(const Requests& rhs);\n\n static const unsigned int num_requests = Imaging::LensCommands::num_commands;\n ::Shared::Request<int> commands[num_requests];\n};\n\n\n// path: 0\n// writes: network\n// reads: main\nextern Shared::CircularBufferPass <Requests> fcp_requests_network_to_main;\n\n// path: 0\n// writes: main\n// reads: camera\nextern Shared::CircularBufferPass <Requests> fcp_requests_main_to_camera;\n\n// path: 0\n// writes: camera\n// reads: lens\nextern Shared::CircularBuffer <Requests> fcp_requests_camera_to_lens;\n\n\n// path: 1\n// writes: lens\n// reads: main\nextern Shared::CircularBufferPass <Requests> stars_requests_lens_to_main;\n\n// path: 1\n// writes: main\n// reads: camera\nextern Shared::CircularBufferPass <Requests> stars_requests_main_to_camera;\n\n// path: 1\n// writes: camera\n// reads: lens\nextern Shared::CircularBuffer <Requests> stars_requests_camera_to_lens;\n\n\n }\n}\n\n#endif\n\n" }, { "alpha_fraction": 0.6279876828193665, "alphanum_fraction": 0.6401310563087463, "avg_line_length": 33.125, "blob_id": "f29915f465d4d4356152f54303ca5dc6dd38eeb4", "content_id": "a15aa738793d65074f263d7a965113dd0a071507", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5189, "license_type": "no_license", "max_line_length": 127, "num_lines": 152, "path": "/stars/code/networking/network_manager.cpp", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#include \"network_manager.h\"\n#include <cstdlib>\n#include <boost/bind.hpp>\n#include <limits>\n#include \"server.h\"\n#include \"image_client.h\"\n#include \"logger.h\"\n#include \"../shared/general/network_reset.h\"\n#include \"../shared/network/packets.h\"\n#include \"../shared/network/image_client_settings.h\"\n#include \"../shared/general/quit.h\"\n#include \"../shared/update.h\"\n#include \"../tools/timing.h\"\n#include \"../tools/quick_cout.h\"\n\n#define shared_reset_request (*(Shared::General::network_reset_for_net_reset.r))\n#define shared_reset_status (*(Shared::General::network_reset_status_for_main.w))\n#define shared_packets_from_fc1 (*(Shared::Network::packets_from_fc1.r))\n#define shared_packets_from_fc2 (*(Shared::Network::packets_from_fc2.r))\n\nusing namespace Networking;\n\nNetworkManager::NetworkManager():\n #pragma warning(push)\n #pragma warning(disable: 4355)\n server_thread(boost::bind(&NetworkManager::run_server, this)),\n image_client_fc1_thread(boost::bind(&NetworkManager::run_image_client_fc1, this)),\n image_client_fc2_thread(boost::bind(&NetworkManager::run_image_client_fc2, this)),\n reset_thread(boost::bind(&NetworkManager::watch_for_reset, this))\n #pragma warning(pop)\n{\n}\n\nvoid NetworkManager::run_server()\n{\n try {\n boost::asio::io_service io_service;\n Server server(io_service, 2017);\n io_service.run();\n } catch (std::exception&) { }\n}\n\nvoid NetworkManager::run_image_client_fc1()\n{\n if (Shared::Network::image_client_settings1.r->enabled) {\n try {\n boost::asio::io_service io_service;\n NetworkingImageClient::ImageClient image_client(io_service, 1);\n } catch (std::exception&) { }\n }\n}\n\nvoid NetworkManager::run_image_client_fc2()\n{\n if (Shared::Network::image_client_settings2.r->enabled) {\n try {\n boost::asio::io_service io_service;\n NetworkingImageClient::ImageClient image_client(io_service, 2);\n } catch (std::exception&) { }\n }\n}\n\nvoid NetworkManager::reset_network_adapter()\n{\n shared_reset_status.resetting = true;\n Shared::General::network_reset_status_for_main.share();\n\n logger.log(\"(when the code is implemented) resetting the network adapter\");\n string command = (format(\"devcon disable %s\")%shared_reset_request.device_name).str();\n logger.log(format(\"calling system command: %s\")%command);\n if(system(command.c_str()) != 0) {\n logger.log(\"warning: system call may have failed\");\n }\n\n for (int i=0; i<5; i++) {\n Shared::update(Shared::ThreadNames::net_reset);\n usleep(1000000);\n }\n\n command = (format(\"devcon enable %s\")%shared_reset_request.device_name).str();\n logger.log(format(\"calling system command: %s\")%command);\n if(system(command.c_str()) != 0) {\n logger.log(\"warning: system call may have failed\");\n }\n\n shared_reset_status.resetting = false;\n Shared::General::network_reset_status_for_main.share();\n\n time_since_last_reset.start();\n}\n\nvoid NetworkManager::watch_for_reset()\n{\n int last_reset_now_counter = shared_reset_request.reset_now_counter;\n bool received_any_packets_so_far = false;\n time_since_last_reset.start();\n\n while (!Shared::General::quit) {\n bool activate_reset = false;\n\n if (last_reset_now_counter != shared_reset_request.reset_now_counter) {\n last_reset_now_counter = shared_reset_request.reset_now_counter;\n activate_reset = true;\n }\n if (shared_reset_request.reset_on_lull_enabled) {\n if (time_since_last_reset.time() > shared_reset_request.reset_on_lull_delay\n && shared_packets_from_fc1.time_since_received.time() > shared_reset_request.reset_on_lull_delay\n && shared_packets_from_fc2.time_since_received.time() > shared_reset_request.reset_on_lull_delay)\n {\n activate_reset = true;\n }\n }\n if (activate_reset) {\n reset_network_adapter();\n }\n\n\n if ( shared_packets_from_fc1.time_since_received.time() < std::numeric_limits<double>::infinity()\n || shared_packets_from_fc2.time_since_received.time() < std::numeric_limits<double>::infinity())\n {\n received_any_packets_so_far = true;\n }\n\n if (shared_reset_request.reset_on_lull_enabled) {\n if (received_any_packets_so_far\n && shared_packets_from_fc1.time_since_received.time() > (shared_reset_request.reset_on_lull_delay + 10.0*60.0)\n && shared_packets_from_fc2.time_since_received.time() > (shared_reset_request.reset_on_lull_delay + 10.0*60.0))\n {\n Shared::General::quit = true;\n }\n }\n\n\n Shared::update(Shared::ThreadNames::net_reset);\n logger.update();\n usleep(100000);\n }\n}\n\nvoid NetworkManager::wait_for_quit()\n{\n //server_thread.join();\n image_client_fc1_thread.join();\n image_client_fc2_thread.join();\n reset_thread.join();\n}\n\n" }, { "alpha_fraction": 0.6502164602279663, "alphanum_fraction": 0.656277060508728, "avg_line_length": 40.21428680419922, "blob_id": "7c2abb9f044c8a7d66cf7dcd1445a8f60ab323ce", "content_id": "aecb8fdbe76acd4e528c7ae1d014c55bb5a3c0df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1155, "license_type": "no_license", "max_line_length": 92, "num_lines": 28, "path": "/stars/utilities/solution_fit/plot_last_solution_fit.py", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\nimport stars_log_parser\nimport pylab as pl\n\ndef plot_solution_fit(solution):\n exaggeration = 100.0\n star_xs = pl.array(map(lambda match: match.star.fitted_x, solution.matches))\n star_ys = pl.array(map(lambda match: match.star.fitted_y, solution.matches))\n blob_xs = pl.array(map(lambda match: match.blob.x, solution.matches))\n blob_ys = pl.array(map(lambda match: match.blob.y, solution.matches))\n error_xs = (blob_xs - star_xs)*exaggeration\n error_ys = (blob_ys - star_ys)*exaggeration\n pl.plot(star_xs, star_ys, 'ro', label=\"star_positions\")\n for i in range(len(star_xs)):\n label = None\n if i == 0:\n label = \"error toward blob position\\n(exaggerated %.1f)\"%exaggeration\n pl.plot([star_xs[i], star_xs[i]+error_xs[i]], [star_ys[i], star_ys[i]+error_ys[i]],\\\n 'b-', label=label)\n pl.legend()\n pl.xlabel(\"pixel x-coordinate\")\n pl.ylabel(\"pixel y-coordinate\")\n\nlast_logname = stars_log_parser.get_last_logname(\"../../output_dir/logs\", \"solving\")\nlast_solution = stars_log_parser.get_solutions(last_logname)[-1]\nplot_solution_fit(last_solution)\npl.show()\n\n" }, { "alpha_fraction": 0.7210756540298462, "alphanum_fraction": 0.7217010855674744, "avg_line_length": 32.3125, "blob_id": "5c268eba886c338ac266c52b8e504208618327e1", "content_id": "f4e028f40c97e835eb3c51ce638e1dfab8f39c0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1599, "license_type": "no_license", "max_line_length": 89, "num_lines": 48, "path": "/starcam/clensadapter.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "#ifndef CLENSADAPTER_H\n#define CLENSADAPTER_H\n\n#include <string>\n#include \"camconfig.h\"\n#include \"clensadapterdefs.h\"\n\nusing namespace std;\n\n/**\n\t@author Steve Benton <[email protected]>\n*/\n\nclass CLensAdapter{\nprivate:\n\tLENS_COMMAND m_eLastCommand; //most recently executed command\n\tLENS_ERROR m_eLastError; //most recent error to occur\n\tint m_nPortFD; //file descriptor for serial port connection\n\tstring m_sSerialDeviceName; //name of file in /dev/ folder corresponding to port\n\tint m_nFocalRange; //number of motor counts along entire focal range\n\tunsigned int m_nFocusTol; //precision (in counts) for a precise move\n\t\npublic:\n CLensAdapter();\n\tCLensAdapter(string deviceName);\n ~CLensAdapter();\n\t\n\tvoid Init(LensAdapterConfigParams params=defaultCameraParams.lensParams);\n\tLENS_ERROR openConnection(string deviceName);\n\tLENS_ERROR closeConnection();\n\t\n\tLENS_COMMAND getLastCommand() { return m_eLastCommand; }\n\tLENS_ERROR getLastError() { return m_eLastError; }\n\tstring getDeviceName() { return m_sSerialDeviceName; }\n\tstatic string getErrorString(LENS_ERROR err);\n\tLENS_ERROR findFocalRange();\n\tint getFocalRange() {return m_nFocalRange; }\n\tvoid setFocusTol(unsigned int tol) { m_nFocusTol = tol; }\n\tunsigned int getFocusTol() { return m_nFocusTol; }\n\t\n\tLENS_ERROR runCommand(LENS_COMMAND cmd, string &return_value);\n\tLENS_ERROR runCommand(LENS_COMMAND cmd, int val, string &return_value);\n\tLENS_ERROR runCommand(string cmd, string &return_value);\n\t\n\tLENS_ERROR preciseMove(int counts, int &remaining, int force = 0);\n};\n\n#endif\n" }, { "alpha_fraction": 0.715133547782898, "alphanum_fraction": 0.721068263053894, "avg_line_length": 18.823530197143555, "blob_id": "271243c88d1ef9930f65cb09a1b30f07707d4564", "content_id": "90230273f8d42ff0b306111480851b97461038fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 675, "license_type": "no_license", "max_line_length": 89, "num_lines": 34, "path": "/stars/code/solving/matching/catalog_manager.h", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "/*\n * © 2013 Columbia University. All Rights Reserved.\n * This file is part of STARS, the Star Tracking Attitude Reconstruction\n * Software package, originally created for EBEX by Daniel Chapman.\n */\n\n#pragma once\n#ifndef SOLVING__MATCHING__CATALOG_MANAGER_H\n#define SOLVING__MATCHING__CATALOG_MANAGER_H\n\n#include <string>\n#include \"../../cataloging/abstract_catalog_manager.h\"\n\nnamespace Parameters\n{\n class Manager;\n}\n\nnamespace Solving\n{\n namespace Matching\n {\n\nclass CatalogManager: public Cataloging::AbstractCatalogManager\n{\n public:\n CatalogManager(Parameters::Manager& params, bool enabled, std::string catalog_path_);\n bool abort();\n};\n\n }\n}\n\n#endif\n" }, { "alpha_fraction": 0.7838709950447083, "alphanum_fraction": 0.7838709950447083, "avg_line_length": 40.33333206176758, "blob_id": "b2f81e78d7ed63c3ea83a7f2416446a1a750cd29", "content_id": "88cbb147c601f8102d831948b64164ea701604cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 620, "license_type": "no_license", "max_line_length": 73, "num_lines": 15, "path": "/sedpy/replacetables.sql", "repo_name": "BlastTNG/flight", "src_encoding": "UTF-8", "text": "DELETE FROM cable;\nDELETE FROM component;\nDELETE FROM congender;\nDELETE FROM connector;\nDELETE FROM jack;\nDELETE FROM line;\nDELETE FROM pin;\n\nLOAD DATA LOCAL INFILE '/data/sedweb/out/cable' INTO TABLE cable;\nLOAD DATA LOCAL INFILE '/data/sedweb/out/component' INTO TABLE component;\nLOAD DATA LOCAL INFILE '/data/sedweb/out/congender' INTO TABLE congender;\nLOAD DATA LOCAL INFILE '/data/sedweb/out/connector' INTO TABLE connector;\nLOAD DATA LOCAL INFILE '/data/sedweb/out/jack' INTO TABLE jack;\nLOAD DATA LOCAL INFILE '/data/sedweb/out/line' INTO TABLE line;\nLOAD DATA LOCAL INFILE '/data/sedweb/out/pin' INTO TABLE pin;\n" } ]
502
youonf/location_intelligence
https://github.com/youonf/location_intelligence
e63b6a518460d8624793f63cebbe43143745ae87
d454912de149cac0eec6020d6beed410e1d76914
eb66edf5acf9d3d8001618fb792998b06ed57f08
refs/heads/master
2021-06-10T20:36:46.488691
2021-06-06T12:10:44
2021-06-06T12:10:44
173,902,047
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5738738775253296, "alphanum_fraction": 0.6108108162879944, "avg_line_length": 20.6862735748291, "blob_id": "7e0bba5d0adbed014479733fd4fe60d6813edb83", "content_id": "432ac727c13d76ef013126778c897741d2be069c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1110, "license_type": "permissive", "max_line_length": 134, "num_lines": 51, "path": "/restaurant/openrice_scraper.py", "repo_name": "youonf/location_intelligence", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport pandas as pd\nfrom tqdm import tqdm\nimport json\n\n\n# In[3]:\n\n\nwith open('data.json', 'w') as f:\n json.dump({}, f)\n\n\n# In[ ]:\n\n\ndata={}\nfor j in tqdm(range(0,1843)):\n url = \"https://www.openrice.com/en/hongkong/restaurants?sortBy=BookmarkedDesc&page=\"\n page = j+1\n headers = requests.utils.default_headers()\n headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'\n response = requests.get(url+\"?page=\"+str(j), headers=headers)\n response = response.text\n soup = BeautifulSoup(response, \"html.parser\")\n \n content = soup.find(class_='sr1-listing-content-cells pois-restaurant-list js-poi-list-content-cell-container')\n \n data[j] = content.prettify()\n \n if j % 10 == 0:\n with open('data.json') as f:\n file = json.load(f)\n\n file.update(data)\n\n with open('data.json', 'w') as f:\n json.dump(file, f)\n \n data = {}\n\n\n# In[ ]:\n\n\n\n\n" }, { "alpha_fraction": 0.6281041502952576, "alphanum_fraction": 0.634161114692688, "avg_line_length": 29.5, "blob_id": "217cae51bf12c835fb602ff9401a68179d0275cd", "content_id": "a85352314cf01f8afc7ad9c2138518e487e3fc22", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1651, "license_type": "permissive", "max_line_length": 151, "num_lines": 54, "path": "/restaurant/openrice_retrieve_json.py", "repo_name": "youonf/location_intelligence", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport pandas as pd\nfrom tqdm import tqdm\nimport json\n\n\n# In[3]:\n\n\nwith open('data.json') as f:\n data = json.load(f)\n\n\n# In[2]:\n\n\ndf = pd.DataFrame(columns =['name','review','bookmark','smile','sad','address','district','cuisine','dish'])\n\n\n# In[236]:\n\n\nfor k in tqdm(range(len(data))):\n soup = BeautifulSoup(data[str(k)], \"html.parser\")\n for i in range(len(soup.find_all(class_='title-name'))):\n rest = {}\n rest['name'] = soup.find_all(class_='title-name')[i].text.strip()\n review = soup.find_all(class_=\"counters-container\")[i].text.strip()\n rest['review'] = int(*re.findall('\\d+', review))\n rest['bookmark'] = soup.find_all(class_=\"text bookmarkedUserCount js-bookmark-count\")[i]['data-count']\n rest['smile'] = soup.find_all(class_=\"emoticon-container smile-face pois-restaurant-list-cell-content-right-info-rating-happy\")[i].text.strip()\n rest['sad'] = soup.find_all(class_=\"emoticon-container sad-face pois-restaurant-list-cell-content-right-info-rating-sad\")[i].text.strip()\n rest['address'] = soup.find_all(class_='icon-info-wrapper')[i].find('span').find(text=True).strip()\n rest['district'] = soup.find_all(class_='icon-info-wrapper')[i].find('a').text\n rest['cuisine'] = soup.find_all(class_=\"icon-info icon-info-food-name\")[i].find_all('a')[0].text\n rest['dish'] = soup.find_all(class_=\"icon-info icon-info-food-name\")[i].find_all('a')[1].text\n df = df.append(rest, ignore_index=True)\n\n\n# In[ ]:\n\n\ndf.to_csv('restaurant.csv')\n\n\n# In[ ]:\n\n\n\n\n" }, { "alpha_fraction": 0.6013478636741638, "alphanum_fraction": 0.6210471987724304, "avg_line_length": 18.67346954345703, "blob_id": "310d16461e536e5883992c3302e4ef8016ef2a70", "content_id": "8f6509032efcce25d37af954c51a1ca1bad5b093", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1929, "license_type": "permissive", "max_line_length": 127, "num_lines": 98, "path": "/restaurant/openrice_parse_ogcio.py", "repo_name": "youonf/location_intelligence", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nimport pandas as pd\nimport json\nfrom random import randint\nfrom time import sleep\nimport requests\nfrom tqdm import tqdm\nimport numpy as np\n\n\n# ### Clan the district, cuisine, dish columns\n\n# In[3]:\n\n\ndf = pd.read_csv('restaurant_clean.csv', index_col=0)\n\n\n# In[ ]:\n\n\nwith open('all_restaurant.json', 'w') as f:\n json.dump({}, f)\n\n\n# In[15]:\n\n\nre_dict={}\n\n\n# In[18]:\n\n\ndef ogcioparser_dict(address):\n data = {\"q\":address, \"n\":1} #n means only send 1 \n headers ={\"Accept\": \"application/json\"}\n api_url = \"https://www.als.ogcio.gov.hk/lookup\"\n res = requests.post(api_url, data=data, headers=headers, timeout=(5, 14))\n add = json.loads(res.text)\n add_dict = {}\n add_dict['Latitude'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Latitude'] \n add_dict['Longitude'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Longitude']\n add_dict['Easting'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Easting']\n add_dict['Northing'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Northing']\n return add_dict\n\n# In[28]:\n\n\naddresses = df['address']\n\n\n# In[31]:\n\n\nsleep_counter = 0\n\n\n# In[32]:\n\n\nall_dict = {}\nworking_dict = {}\nfor i, a in enumerate(tqdm(addresses)):\n parse = ogcioparser_dict(a)\n all_dict[i] = parse\n working_dict[i] = parse\n sleep_counter +=1\n if sleep_counter % 500 == 0:\n sleep(randint(5,10))\n\n with open('all_restaurant.json') as f:\n file = json.load(f)\n\n file.update(working_dict)\n\n with open('all_restaurant.json', 'w') as f:\n json.dump(file, f)\n \n working_dict = {}\n\n\n# In[26]:\n\n\ndf_parse = pd.DataFrame.from_dict(all_dict, orient='index')\n\n\n# In[ ]:\n\n\ndf_parse.to_csv('parse.csv')\n\n" }, { "alpha_fraction": 0.8013244867324829, "alphanum_fraction": 0.8211920261383057, "avg_line_length": 24.16666603088379, "blob_id": "0d5431ea28b556d8b348317d3f071a2823c8aaad", "content_id": "31cc06ea3f73ed516b317b71a244d7cfbabb7601", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 151, "license_type": "permissive", "max_line_length": 37, "num_lines": 6, "path": "/README.md", "repo_name": "youonf/location_intelligence", "src_encoding": "UTF-8", "text": "# location_intelligence\nExploration of location intelligence\n\n1. Scrape of restaurants detail\n2. Scrape HK location and census data\n3. Build dashboard\n" }, { "alpha_fraction": 0.6346153616905212, "alphanum_fraction": 0.6578249335289001, "avg_line_length": 20.55714225769043, "blob_id": "a00db8aaf54492aa1cbbc7e1a7a3f0d5a973cd3b", "content_id": "6be8d0b9501322918ecca2345fa8131ef6ebe993", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1508, "license_type": "permissive", "max_line_length": 125, "num_lines": 70, "path": "/restaurant/openrice_allrestaurant.py", "repo_name": "youonf/location_intelligence", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport json\nfrom random import randint\nfrom time import sleep\nimport requests\nfrom tqdm import tqdm\nimport numpy as np\n\n\n# ### Clan the district, cuisine, dish columns\n\n\ndf = pd.read_csv('restaurant_clean.csv', index_col=0)\n\n\n# In[18]:\n\n\ndef ogcioparser_dict(address):\n data = {\"q\":address, \"n\":1} #n means only send 1 \n headers ={\"Accept\": \"application/json\"}\n api_url = \"https://www.als.ogcio.gov.hk/lookup\"\n res = requests.post(api_url, data=data, headers=headers, timeout=(5, 14))\n add = json.loads(res.text)\n add_dict = {}\n add_dict['Northing'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Northing']\n add_dict['Easting'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Easting']\n add_dict['Longitude'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Longitude']\n add_dict['Latitude'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Latitude']\n return add_dict\n\n\n# In[28]:\n\n\naddresses = df['address']\n\n\n# In[29]:\n\n\nall_dict = {}\n\n\n# In[31]:\n\n\nsleep_counter = 0\n\n\n# In[32]:\n\nfor i, a in enumerate(tqdm(addresses)):\n all_dict[i] = ogcioparser_dict(a)\n sleep_counter +=1\n if sleep_counter % 500 == 0:\n sleep(randint(5,10))\n\n\n# In[ ]:\n\ndf_parse = pd.DataFrame.from_dict(all_dict, orient='index')\n\ndf_parse.to_csv('parse.csv')" } ]
5
L200170034/prak_ASD_A
https://github.com/L200170034/prak_ASD_A
8c4c54d9a1ff41bb45632a860142c61dae749d17
878b03b89e11dcf7f4f45142bfec9d346c327fe0
5d63486a9964591582644af81527768635f42e6b
refs/heads/master
2020-04-26T17:15:13.057230
2019-07-01T13:52:52
2019-07-01T13:52:52
173,707,138
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4543277323246002, "alphanum_fraction": 0.5056448578834534, "avg_line_length": 26.656862258911133, "blob_id": "ac71e676c860de0a2a494a6060215ed0e31104a0", "content_id": "97db854120e006fad34f7059e3404b02b523281c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2923, "license_type": "no_license", "max_line_length": 98, "num_lines": 102, "path": "/modul_5.py", "repo_name": "L200170034/prak_ASD_A", "src_encoding": "UTF-8", "text": "class Mahasiswa(object):\r\n def __init__(self, nama, nim, kota, uangsaku):\r\n self.nama = nama\r\n self.nim = nim\r\n self.kota = kota\r\n self.uangsaku = uangsaku\r\n \r\n#----------------------NO.1--------------------#\r\ndef bubleshort(val):\r\n for passnum in range(len(val)-1,0,-1):\r\n for i in range (passnum):\r\n if val[i]>val[i+1]:\r\n temp = val[1]\r\n val[i] = val [i+1]\r\n val [i+1] = temp\r\n\r\n#----------------------NO.2--------------------#\r\nA = [1,2,3,4,5]\r\nB = [6,7,9,10]\r\nC = []\r\n\r\n\r\ndef insertionSort(A):\r\n n = len(A)\r\n for i in range(1, n):\r\n nilai = A[i]\r\n pos = i\r\n while pos > 0 and nilai < A[pos - 1]:\r\n A[pos] = A[pos - 1]\r\n pos = pos - 1\r\n A[pos] = nilai\r\n\r\nC.extend(A)\r\nC.extend(B)\r\nprint (C)\r\n\r\n#-----------------------NO.3-------------------#\r\nfrom time import time as detak\r\nfrom random import shuffle as kocok\r\ndef swap(A,p,q):\r\n tmp = A[p]\r\n A[q]= A[q]\r\n A[q]= tmp\r\n \r\ndef bubbleSort(A):\r\n n = len(A)\r\n for i in range(n-1):\r\n for j in range (n-i-1):\r\n if A[j] > A[j+1]:\r\n swap(A,j,j+1)\r\n \r\ndef cariPosisiYangTerkecil(A, dariSini, sampaiSini):\r\n posisiYangTerkecil=dariSini\r\n for i in range(dariSini+1, sampaiSini):\r\n if A[i]<A[posisiYangTerkecil]:\r\n posisiYangTerkecil = i\r\n return posisiYangTerkecil \r\n\r\ndef selectionSort(A):\r\n n = len(A)\r\n for i in range(n-1):\r\n indexKecil = cariPosisiYangTerkecil(A, i, n)\r\n if indexKecil != i:\r\n swap(A, i, indexKecil)\r\n \r\ndef insertionSort(A):\r\n n = len(A)\r\n for i in range(1, n):\r\n nilai = A[i]\r\n pos = i\r\n while pos > 0 and nilai < A[pos - 1]:\r\n A[pos] = A[pos - 1]\r\n pos = pos - 1\r\n A[pos] = nilai\r\n\r\nk = []\r\nfor i in range(1, 6001):\r\n k.append(i)\r\nkocok(k)\r\nu_bub = k[:]\r\nu_sel = k[:]\r\nu_ins = k[:]\r\n\r\naw=detak();bubbleSort(u_bub);ak=detak();print('bubble: %g detik' %(ak-aw));\r\naw=detak();selectionSort(u_sel);ak=detak();print('selection: %g detik' %(ak-aw));\r\naw=detak();insertionSort(u_ins);ak=detak();print('insertion:%g detik' %(ak-aw));\r\n\r\nm0 = Mahasiswa('Ika', 10, 'Sukoharjo', 240000)\r\nm1 = Mahasiswa('Ahmad', 2, 'Surakarta', 250000)\r\nm2 = Mahasiswa('Chandra', 18, 'Surakarta', 235000)\r\nm3 = Mahasiswa('Eka', 4, 'Boyolali', 240000)\r\nm4 = Mahasiswa('Fandi', 31, 'Salatiga', 250000)\r\nm5 = Mahasiswa('Deni', 13, 'Klaten', 245000)\r\nm6 = Mahasiswa('Galuh', 5, 'Wonogiri', 245000)\r\nm7 = Mahasiswa('Janto', 23, 'Klaten', 245000)\r\nm8 = Mahasiswa('Hasan', 64, 'Karanganyar', 270000)\r\nm9 = Mahasiswa('Khalid', 29, 'Purwodadi', 265000)\r\nm10 = Mahasiswa('Budi', 51, 'Klaten', 210000)\r\n\r\nDaftar = [m0.nim, m1.nim, m2.nim, m3.nim, m4.nim, m5.nim, m6.nim, m7.nim, m8.nim, m9.nim, m10.nim]\r\nbubleshort(Daftar)\r\nprint(Daftar)\r\n" }, { "alpha_fraction": 0.40516677498817444, "alphanum_fraction": 0.42620450258255005, "avg_line_length": 29.307167053222656, "blob_id": "bcacd1c501a693aa9142061663de3a0c1befbd1e", "content_id": "aa5c881a86802477f83134bfdd0319b714adec61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9174, "license_type": "no_license", "max_line_length": 126, "num_lines": 293, "path": "/Modul_3.py", "repo_name": "L200170034/prak_ASD_A", "src_encoding": "UTF-8", "text": "-----------------------No.1------------------------\r\na = [[ 1 , 2 ], [ 3 , 4 ]]\r\nb = [[ 5 , 6 ], [ 7 , 8 ]]\r\nc = [[ 12 , 3 , \" x \" , \" y \" ], [ 12 , 33 , 4 ]]\r\nd = [[ 3 , 4 ], [ 2 , 4 ], [ 1 , 5 ]]\r\ne = [[ 5 , 6 , 7 ], [ 7 , 8 , 9 ]]\r\nf = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]]\r\n\r\ndef cekKonsis ( n ):\r\n x = len (n [ 0 ])\r\n z = 0\r\n untuk saya dalam kisaran ( len (n)):\r\n if ( len (n [i]) == x):\r\n z + = 1\r\n if (z == len (n)):\r\n print ( \" matriks konsisten \" )\r\n lain :\r\n print ( \" matrik tidak konsisten \" )\r\n\r\ncekKonsis (a)\r\ncekKonsis (b)\r\ncekKonsis (c)\r\n\r\ndef cekInt ( n ):\r\n x = 0\r\n y = 0\r\n untuk saya dalam n:\r\n untuk j in i:\r\n y + = 1\r\n if ( str (j) .isdigit () == Salah ):\r\n print ( \" tidak semua isi matriks adalah angka \" )\r\n istirahat\r\n lain :\r\n x + = 1\r\n jika (x == y):\r\n print ( \" semua isi matriks adalah angka \" )\r\n \r\ncekInt (a)\r\ncekInt (b)\r\ncekInt (c)\r\n\r\ndef ordo ( n ):\r\n x, y = 0 , 0\r\n untuk saya dalam kisaran ( len (n)):\r\n x + = 1\r\n y = len (n [i])\r\n print ( \"memiliki ordo \" + str (x) + \" x \" + str (y))\r\n\r\nordo (a)\r\nordo (b)\r\nordo (d)\r\nordo (e)\r\n\r\ndef jumlah ( n , m ):\r\n x, y = 0 , 0\r\n untuk saya dalam kisaran ( len (n)):\r\n x + = 1\r\n y = len (n [i])\r\n xy = [[ 0 untuk j dalam rentang (x)] untuk i dalam kisaran (y)]\r\n \r\n z = 0\r\n if ( len (n) == len (m)):\r\n untuk saya dalam kisaran ( len (n)):\r\n if ( len (n [i]) == len (m [i])):\r\n z + = 1\r\n if (z == len (n) dan z == len (m)):\r\n print ( \" ukuran sama \" )\r\n untuk saya dalam kisaran ( len (n)):\r\n untuk j dalam kisaran ( len (n [i]))):\r\n xy [i] [j] = n [i] [j] + m [i] [j]\r\n cetak (xy)\r\n lain :\r\n print ( \" ukuran beda \" )\r\n\r\njumlah (a, b)\r\njumlah (a, d)\r\n \r\n \r\ndef kali ( n , m ):\r\n aa = 0\r\n x, y = 0 , 0\r\n untuk saya dalam kisaran ( len (n)):\r\n x + = 1\r\n y = len (n [i])\r\n v, w = 0 , 0\r\n untuk saya dalam kisaran ( len (m)):\r\n v + = 1\r\n w = len (m [i])\r\n \r\n jika (y == v):\r\n print ( \" bisa dikalikan \" )\r\n vwxy = [[ 0 untuk j dalam rentang (w)] untuk i dalam kisaran (x)]\r\n untuk saya dalam kisaran ( len (n)):\r\n untuk j dalam kisaran ( len (m [ 0 ])):\r\n untuk k dalam kisaran ( len (m)):\r\n # print (n [i] [k], m [k] [j])\r\n vwxy [i] [j] + = n [i] [k] * m [k] [j]\r\n cetak (vwxy)\r\n \r\n lain :\r\n print ( \" tidak memenuhi persyaratan \" )\r\n\r\nzz = [[ 1 , 2 , 3 ], [ 1 , 2 , 3 ]]\r\nzx = [[ 1 ], [ 2 ], [ 3 ]]\r\nkali (zz, zx)\r\nkali (a, b)\r\nkali (a, e)\r\nkali (a, zx)\r\n\r\n\r\ndef determHitung ( A , total = 0 ):\r\n x = len (A [ 0 ])\r\n z = 0\r\n untuk saya dalam kisaran ( len (A)):\r\n if ( len (A [i]) == x):\r\n z + = 1\r\n if (z == len (A)):\r\n if (x == len (A)):\r\n indeks = daftar ( rentang ( len (A)))\r\n jika len (A) == 2 dan len (A [ 0 ]) == 2 :\r\n val = A [ 0 ] [ 0 ] * A [ 1 ] [ 1 ] - A [ 1 ] [ 0 ] * A [ 0 ] [ 1 ]\r\n mengembalikan val\r\n untuk fc dalam indeks:\r\n As = A\r\n As = As [ 1 :]\r\n tinggi = len (As)\r\n untuk saya dalam kisaran (tinggi):\r\n As [i] = As [i] [ 0 : fc] + As [i] [fc + 1 :]\r\n tanda = ( - 1 ) ** (fc % 2 )\r\n sub_det = determHitung (As)\r\n total + = tanda * A [ 0 ] [fc] * sub_det\r\n lain :\r\n return \" tidak bisa dihitung determinan, bukan matrix bujursangkar \"\r\n lain :\r\n return \" tidak bisa dihitung determinan, bukan matrix bujursangkar \"\r\n mengembalikan total\r\n\r\n\r\nz = [[ 3 , 1 ], [ 2 , 5 ]]\r\nx = [[ 1 , 2 , 1 ], [ 3 , 3 , 1 ], [ 2 , 1 , 2 ]]\r\nv = [[ 1 , - 2 , 0 , 0 ], [ 3 , 2 , - 3 , 1 ], [ 4 , 0 , 5 , 1 ], [ 2 , 3 , - 1 , 4 ]]\r\nr = [[ 10 , 23 , 45 , 12 , 13 ], [ 1 , 2 , 3 , 4 , 5 ], [ 1 , 2 , 3 , 4 , 6 ], [ 4 , 2 , 3 , 4 , 8 ] , [ 1 , 4 , 5 , 6 , 10 ]]\r\nprint (determHitung (z))\r\nprint (determHitung (x))\r\nprint (determHitung (v))\r\nprint (determHitung (r))\r\nprint (determHitung (d))\r\nprint (determHitung (e))\r\n-----------------------No.2------------------------\r\ndef buatNol ( n , m = Tidak Ada ):\r\n jika (m == Tidak Ada ):\r\n m = n\r\n print ( \" membuat matriks 0 dengan ordo \" + str (n) + \" x \" + str (m))\r\n cetak ([[ 0 untuk j dalam kisaran (m)] untuk i dalam kisaran (n)])\r\n\r\nbuatNol ( 2 , 4 )\r\nbuatNol ( 3 )\r\n\r\ndef buatIden ( n ):\r\n print ( \" membuat matriks identitas dengan ordo \" + str (n) + \" x \" + str (n))\r\n cetak ([[ 1 jika j == saya yang lain 0 untuk j dalam rentang (n)] untuk saya dalam kisaran (n)])\r\n\r\nbuatIden ( 4 )\r\nbuatIden ( 2 )\r\n-----------------------No.3------------------------\r\nkelas Node :\r\n def __init__ ( mandiri , data ):\r\n self .data = data\r\n self .next = Tidak ada\r\nkelas LinkedList :\r\n def __init__ ( mandiri ):\r\n self .head = Tidak ada\r\n def pushAw ( self , new_data ):\r\n new_node = Node (new_data)\r\n new_node.next = self .head\r\n self .head = new_node\r\n def pushAk ( mandiri , data ):\r\n if ( self .head == Tidak Ada ):\r\n self .head = Node (data)\r\n lain :\r\n saat ini = self .head\r\n while (current.next ! = Tidak Ada ):\r\n current = current.next\r\n current.next = Node (data)\r\n kembali diri. kepala\r\n sisipan def ( diri , data , pos ):\r\n simpul = Node (data)\r\n jika tidak diri .head:\r\n self .head = node\r\n elif pos == 0 :\r\n node.next = self .head\r\n self .head = node\r\n lain :\r\n prev = Tidak Ada\r\n saat ini = self .head\r\n current_pos = 0\r\n while (current_pos < pos) dan current.next:\r\n prev = saat ini\r\n current = current.next\r\n current_pos + = 1\r\n prev.next = simpul\r\n node.next = saat ini\r\n kembali diri. kepala\r\n def deleteNode ( mandiri , posisi ):\r\n if self .head == Tidak Ada :\r\n kembali \r\n temp = self .head\r\n jika posisi == 0 :\r\n self .head = temp.next\r\n temp = Tidak ada\r\n kembali \r\n untuk saya dalam jangkauan (posisi - 1 ):\r\n temp = temp.next\r\n jika temp tidak ada :\r\n istirahat\r\n jika temp tidak ada :\r\n kembali \r\n jika temp.next adalah None :\r\n kembali \r\n next = temp.next.next\r\n temp.next = Tidak Ada\r\n temp.next = berikutnya \r\n pencarian def ( mandiri , x ):\r\n saat ini = self .head\r\n saat ini ! = Tidak Ada :\r\n jika current.data == x:\r\n kembali \" Benar \"\r\n current = current.next\r\n kembali \" Salah \"\r\n tampilan def ( mandiri ):\r\n saat ini = self .head\r\n sementara saat ini tidak ada :\r\n print (current.data, end = ' ' )\r\n current = current.next \r\n \r\nllist = LinkedList ()\r\nllist.pushAw ( 21 )\r\nllist.pushAw ( 22 )\r\nllist.pushAw ( 12 )\r\nllist.pushAw ( 14 )\r\nllist.pushAw ( 2 )\r\nllist.pushAw ( 19 )\r\nllist.pushAk ( 9 )\r\nllist.deleteNode ( 0 )\r\nllist.insert ( 1 , 6 )\r\nprint (llist.search ( 21 ))\r\nprint (llist.search ( 29 ))\r\nllist.display ()\r\n-----------------------No.4------------------------\r\nkelas Node :\r\n def __init__ ( mandiri , data ):\r\n self .data = data\r\n self .prev = Tidak ada\r\nkelas DoublyLinkedList :\r\n def __init__ ( mandiri ):\r\n self .head = Tidak ada\r\n def awal ( self , new_data ):\r\n print ( \" tambah pada awal \" , new_data)\r\n new_node = Node (new_data)\r\n new_node.next = self .head\r\n jika diri .head adalah tidak ada :\r\n self .head.prev = new_node\r\n self .head = new_node\r\n def akhir ( self , new_data ):\r\n print ( \" tambah pada akhir \" , new_data)\r\n new_node = Node (new_data)\r\n new_node.next = Tidak Ada\r\n jika self .head tidak ada :\r\n new_node.prev = Tidak Ada\r\n self .head = new_node\r\n kembali \r\n last = self .head\r\n sementara (last.next adalah tidak ada ):\r\n last = last.next\r\n last.next = new_node\r\n new_node.prev = terakhir\r\n kembali\r\n def printList ( self , node ):\r\n print ( \" \\ n Dari Depan: \" )\r\n sementara (node adalah tidak ada ):\r\n print ( \" % d \" % (node.data))\r\n last = node\r\n node = node.next\r\n print ( \" \\ n Dari Belakang: \" )\r\n sementara (terakhir adalah tidak ada ):\r\n cetak ( \" % d \" % (last.data))\r\n last = last.prev\r\nllist = DoublyLinkedList ()\r\nllist.awal ( 7 ) \r\nllist.awal ( 1 )\r\nllist.akhir ( 6 )\r\nllist.akhir ( 4 )\r\nllist.printList (llist.head) \r\n" }, { "alpha_fraction": 0.4709923565387726, "alphanum_fraction": 0.5433841943740845, "avg_line_length": 29.190475463867188, "blob_id": "7d34a2a465b71f1065ef34d16dea71ff1dcf3835", "content_id": "2776ab943e4e301ec64be34f53d3351c47c7ee46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7860, "license_type": "no_license", "max_line_length": 135, "num_lines": 252, "path": "/Modul_4.py", "repo_name": "L200170034/prak_ASD_A", "src_encoding": "UTF-8", "text": "class Mahasiswa(object):\r\n def __init__(self, nama, nim, kota, uangsaku):\r\n self.nama = nama\r\n self.nim = nim\r\n self.kota = kota\r\n self.uangsaku = uangsaku\r\n\r\nm0 = Mahasiswa('Ika', 10, 'Sukoharjo', 240000)\r\nm1 = Mahasiswa('Ahmad', 2, 'Surakarta', 250000)\r\nm2 = Mahasiswa('Chandra', 18, 'Surakarta', 235000)\r\nm3 = Mahasiswa('Eka', 4, 'Boyolali', 240000)\r\nm4 = Mahasiswa('Fandi', 31, 'Salatiga', 250000)\r\nm5 = Mahasiswa('Deni', 13, 'Klaten', 245000)\r\nm6 = Mahasiswa('Galuh', 5, 'Wonogiri', 245000)\r\nm7 = Mahasiswa('Janto', 23, 'Klaten', 245000)\r\nm8 = Mahasiswa('Hasan', 64, 'Karanganyar', 270000)\r\nm9 = Mahasiswa('Khalid', 29, 'Purwodadi', 265000)\r\nm10 = Mahasiswa('Budi', 51, 'Klaten', 210000)\r\n\r\nDaftar = [m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10]\r\n\r\n-----------------NO.1-----------------------\r\ndef CariIndexKota(kumpulan, k):\r\n ko = []\r\n for i in kumpulan :\r\n if i.kota == k :\r\n ko.append(kumpulan.index(i))\r\n return ko\r\n-----------------NO.2-----------------------\r\ndef UangSakuTerkecil(kumpulan) :\r\n terkecil = kumpulan[0].uangsaku\r\n for i in kumpulan :\r\n if i.uangsaku < terkecil :\r\n terkecil = i.uangsaku\r\n return terkecil\r\n-----------------NO.3-----------------------\r\ndef DaftarSakuTerkecil(kumpulan) :\r\n kecil = []\r\n terkecil = kumpulan[0].uangsaku\r\n for i in kumpulan :\r\n if i.uangsaku < terkecil :\r\n terkecil = i.uangsaku\r\n kecil.append(kumpulan.index(i))\r\n return kecil\r\n-----------------NO.4-----------------------\r\ndef DaftarSakuKecil(kumpulan):\r\n kecil = []\r\n for i in kumpulan :\r\n if i.uangsaku < 250000 :\r\n kecil.append(kumpulan.index(i))\r\n\r\n\r\n\r\nclass Node :\r\n def __init__(self, data):\r\n self.data = data\r\n self.next = None\r\n\r\nclass LinkedList :\r\n def __init__(self): \r\n self.head = None\r\n \r\n def pushAw(self, new_data): \r\n new_node = Node(new_data) \r\n new_node.next = self.head \r\n self.head = new_node\r\n \r\n def pushAk(self, data):\r\n if (self.head == None):\r\n self.head = Node(data)\r\n else:\r\n current = self.head\r\n while (current.next != None):\r\n current = current.next\r\n current.next = Node(data)\r\n return self.head\r\n \r\n def insert(self,data,pos):\r\n node = Node(data)\r\n if not self.head:\r\n self.head = node\r\n elif pos==0:\r\n node.next = self.head\r\n self.head = node\r\n else:\r\n prev = None\r\n current = self.head\r\n current_pos = 0\r\n while(current_pos < pos) and current.next:\r\n prev = current\r\n current = current.next\r\n current_pos +=1\r\n prev.next = node\r\n node.next = current\r\n return self.head\r\n\r\n def search(self, x): \r\n current = self.head \r\n while current != None: \r\n if current.data == x: \r\n return \"True\"\r\n current = current.next\r\n return \"False\"\r\n\r\n-----------------NO.5-----------------------\r\n def display(self):\r\n current = self.head\r\n while current is not None:\r\n print(current.data, end = ' ')\r\n current = current.next\r\n\r\nclass Mahasiswa(object):\r\n def __init__(self, nama, nim, kota, uangsaku):\r\n self.nama = nama\r\n self.nim = nim\r\n self.kota = kota\r\n self.uangsaku = uangsaku\r\n\r\nm0 = Mahasiswa('Ika', 10, 'Sukoharjo', 240000)\r\nm1 = Mahasiswa('Ahmad', 2, 'Surakarta', 250000)\r\nm2 = Mahasiswa('Chandra', 18, 'Surakarta', 235000)\r\nm3 = Mahasiswa('Eka', 4, 'Boyolali', 240000)\r\nm4 = Mahasiswa('Fandi', 31, 'Salatiga', 250000)\r\nm5 = Mahasiswa('Deni', 13, 'Klaten', 245000)\r\nm6 = Mahasiswa('Galuh', 5, 'Wonogiri', 245000)\r\nm7 = Mahasiswa('Janto', 23, 'Klaten', 245000)\r\nm8 = Mahasiswa('Hasan', 64, 'Karanganyar', 270000)\r\nm9 = Mahasiswa('Khalid', 29, 'Purwodadi', 265000)\r\nm10 = Mahasiswa('Budi', 51, 'Klaten', 210000)\r\n\r\nDaftar = [m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10]\r\ndef CariIndexKota(kumpulan, k):\r\n ko = []\r\n for i in kumpulan :\r\n if i.kota == k :\r\n ko.append(kumpulan.index(i))\r\n return ko\r\n\r\ndef UangSakuTerkecil(kumpulan) :\r\n terkecil = kumpulan[0].uangsaku\r\n for i in kumpulan :\r\n if i.uangsaku < terkecil :\r\n terkecil = i.uangsaku\r\n return terkecil\r\n\r\ndef DaftarSakuTerkecil(kumpulan) :\r\n kecil = []\r\n terkecil = kumpulan[0].uangsaku\r\n for i in kumpulan :\r\n if i.uangsaku < terkecil :\r\n terkecil = i.uangsaku\r\n kecil.append(kumpulan.index(i))\r\n return kecil\r\n\r\ndef DaftarSakuKecil(kumpulan):\r\n kecil = []\r\n for i in kumpulan :\r\n if i.uangsaku < 250000 :\r\n kecil.append(kumpulan.index(i))\r\n return kecil\r\n\r\n-----------------NO.6-----------------------\r\ndef binary_search(kumpulan, target):\r\n jml = []\r\n kiri = 0\r\n kanan = len(kumpulan) - 1\r\n\r\n while kiri <= kanan :\r\n mid = (kiri + kanan) // 2\r\n if kumpulan[mid] == target :\r\n jml.append(kumpulan.index(target))\r\n return jml\r\n elif target < kumpulan[mid]:\r\n kanan = mid - 1\r\n else :\r\n kiri = mid + 1\r\n return False\r\n\r\nd = [1, 2, 3, 3, 4, 5, 5, 5, 5, 133, 134, 157, 157, 189, 200, 230, 235,345]\r\n\r\n-----------------NO.7-----------------------\r\nclass Mahasiswa(object):\r\n def __init__(self, nama, nim, kota, uangsaku):\r\n self.nama = nama\r\n self.nim = nim\r\n self.kota = kota\r\n self.uangsaku = uangsaku\r\n\r\nm0 = Mahasiswa('Ika', 10, 'Sukoharjo', 240000)\r\nm1 = Mahasiswa('Ahmad', 2, 'Surakarta', 250000)\r\nm2 = Mahasiswa('Chandra', 18, 'Surakarta', 235000)\r\nm3 = Mahasiswa('Eka', 4, 'Boyolali', 240000)\r\nm4 = Mahasiswa('Fandi', 31, 'Salatiga', 250000)\r\nm5 = Mahasiswa('Deni', 13, 'Klaten', 245000)\r\nm6 = Mahasiswa('Galuh', 5, 'Wonogiri', 245000)\r\nm7 = Mahasiswa('Janto', 23, 'Klaten', 245000)\r\nm8 = Mahasiswa('Hasan', 64, 'Karanganyar', 270000)\r\nm9 = Mahasiswa('Khalid', 29, 'Purwodadi', 265000)\r\nm10 = Mahasiswa('Budi', 51, 'Klaten', 210000)\r\n\r\nDaftar = [m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10]\r\n\r\n\r\ndef CariIndexKota(kumpulan, k):\r\n ko = []\r\n for i in kumpulan :\r\n if i.kota == k :\r\n ko.append(kumpulan.index(i))\r\n return ko\r\n\r\ndef UangSakuTerkecil(kumpulan) :\r\n terkecil = kumpulan[0].uangsaku\r\n for i in kumpulan :\r\n if i.uangsaku < terkecil :\r\n terkecil = i.uangsaku\r\n return terkecil\r\n\r\ndef DaftarSakuTerkecil(kumpulan) :\r\n return kecil\r\n\r\n-----------------NO.8-----------------------\r\n\r\ndef binery_search(kumpulan, target) :\r\n kiri = 0\r\n kanan = len(kumpulan) - 1\r\n\r\n while kiri <= kanan :\r\n tengah = (kiri + kanan) // 2\r\n\r\n if kumpulan[tengah] == target :\r\n return tengah\r\n\r\n elif kumpulan[tengah] < target :\r\n kiri = tengah + 1\r\n\r\n else :\r\n kanan = tengah - 1\r\n\r\n return -1\r\n\r\nd = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]\r\n\r\n\"\"\"\r\nUntuk mencari berapa tabakan yang digunakan Binary Search, menggunakan Logaritma basis 2 (Log2(n))\r\nmisal :\r\n - apabila terdapat element array berjumlah 100 maka akan memilki maksimal 7 kali tebakan.\r\n perhitungannya log2(100) = 6.643856189774725 kita tambahkan 1 menjadi 7.643856189774725 sehingga kita bulatkan ke bawah menjadi 7\r\n selain itu 7 didapatkan dari log2(128) = 7, dimana 100 paling mendekati dengan 128.\r\n - apabila itu terdapat 1000 element maka perhitungan akan sama.\r\n log2(1000) = 9.965784284662087 kita tambahkan 1 menjadi 10.965784284662087 dibulatkan ke bawah menjadi 10.\r\n bisa didapat dari log2(1024) = 10, dimana 1000 paling mendekati 1024.\r\n\"\"\"\r\n" } ]
3
plunked/mimic
https://github.com/plunked/mimic
48fe3050f7f69abb1d6f3cf8d5190cbab6a21a64
62d8d5ac485838d02454fb3f6685949b34ef2db8
e29b88665338e3965f0949a411ca2646eb496ccf
refs/heads/master
2017-03-22T14:18:43.103032
2015-10-17T06:03:30
2015-10-17T06:03:30
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.39617207646369934, "alphanum_fraction": 0.5558943152427673, "avg_line_length": 29.12244987487793, "blob_id": "524afdff05043589619bf41897f057240537d501", "content_id": "e1a02bc1b4917237b462802b4325a510cdd0b8ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5904, "license_type": "no_license", "max_line_length": 109, "num_lines": 196, "path": "/mimic", "repo_name": "plunked/mimic", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# coding=utf-8\n\n\ndef get_homographs():\n \"\"\"\n Use http://dev.networkerror.org/utf8/?start=0&end=255&cols=10&show_uni_hex=on\n with the stupid table width forced to auto.\n This dataset is for ASCII characters mapped to UTF-8 homographs (some approximate).\n \"\"\"\n return (\n u'!\\uFF01\\u01C3\\u119D\\u2D51\\uFE57',\n u'\"\\uFF02\\u030E',\n u'#\\uFF03\\uFE5F',\n u'$\\uFF04\\uFE69',\n u'%\\uFF05\\u066A\\u2052\\uFE6A',\n u'&\\uFF06\\uFE60',\n u\"'\\uFF07\\u02B9\\u030D\",\n u'(\\uFF08\\u27EE\\uFE59',\n u')\\uFF09\\u27EF\\uFE5A',\n u'*\\uFF0A\\u22C6\\uFE61',\n u'+\\uFF0B\\u16ED\\uFE62',\n u',\\uFF0C\\u0317\\u0326\\u02CF\\u16E7\\u201A',\n u'-\\uFF0D\\u0335\\u02D7\\u1680\\u174D\\u1806\\u1C7C\\u2212\\u23AF\\u23BC\\u2574\\u2CBB\\u2CBB\\u30FC\\u3127\\uFE63',\n u'.\\uFF0E\\u0323\\u2024',\n u'/\\uFF0F\\u0338\\u1735\\u2044\\u2215\\u29F8\\u2CC6\\u3033',\n u'0\\uFF10\\u1C50',\n u'1\\uFF11',\n u'2\\uFF12\\u14BF',\n u'3\\uFF13\\u01B7\\u1883\\u2CC4\\u2CCC\\u2CCD',\n u'4\\uFF14\\u13CE',\n u'5\\uFF15',\n u'6\\uFF16\\u13EE',\n u'7\\uFF17',\n u'8\\uFF18',\n u'9\\uFF19\\u13ED',\n u':\\uFF1A\\u02D0\\u02F8\\u0589\\u05C3\\u1361\\u16EC\\u17C8\\u1804\\u1C7A\\u205A\\u2236\\u2806\\uFE30\\uFE55',\n u';\\uFF1B\\u037E\\uFE54',\n u'<\\uFF1C\\u02C2\\u2039\\u227A\\u276E\\u2D66\\u3031\\u3111\\uFE64',\n u'=\\uFF1D\\u2550\\u268C\\u30A0\\uFE66',\n u'>\\uFF1E\\u02C3\\u203A\\u227B\\u276F\\uFE65',\n u'?\\uFF1F\\uFE56',\n u'@\\uFF20\\uFE6B',\n u'A\\uFF21\\u0391\\u0410\\u13AA',\n u'B\\uFF22\\u0392\\u0412\\u13F4\\u15F7\\u2C82',\n u'C\\uFF23\\u03F9\\u0421\\u13DF\\u216D\\u2CA4',\n u'D\\uFF24\\u13A0\\u15EA\\u216E',\n u'E\\uFF25\\u0395\\u0415\\u13AC',\n u'F\\uFF26\\u15B4',\n u'G\\uFF27\\u050C\\u13C0',\n u'H\\uFF28\\u0397\\u041D\\u12D8\\u13BB\\u157C\\u2C8E',\n u'I\\uFF29\\u0399\\u0406',\n u'J\\uFF2A\\u0408\\u13AB\\u148D',\n u'K\\uFF2B\\u039A\\u039A\\u13E6\\u16D5\\u212A\\u2C94',\n u'L\\uFF2C\\u13DE\\u14AA\\u216C\\u2CD0\\u31C4',\n u'M\\uFF2D\\u039C\\u03FA\\u041C\\u13B7\\u216F',\n u'N\\uFF2E\\u039D\\u2C9A',\n u'O\\uFF2F\\u039F\\u041E\\u1C5B\\u2C9E',\n u'P\\uFF30\\u03A1\\u0420\\u13E2\\u2CA2',\n u'Q\\uFF31\\u051A\\u10B3\\u2D55',\n u'R\\uFF32\\u13A1\\u13D2\\u1587',\n u'S\\uFF33\\u0405\\u10BD\\u13DA',\n u'T\\uFF34\\u03A4\\u0422\\u13A2',\n u'U\\uFF35',\n u'V\\uFF36\\u13D9',\n u'W\\uFF37\\u13B3\\u13D4',\n u'X\\uFF38\\u03A7\\u0425\\u2CAC',\n u'Y\\uFF39\\u03A5\\u2CA8',\n u'Z\\uFF3A\\u0396\\u13C3',\n u'[\\uFF3B',\n u'\\\\\\uFF3C\\u2216\\u29F5\\u29F9\\u3035\\uFE68',\n u']\\uFF3D',\n u'^\\uFF3E\\u0302\\u02C4\\u02C6\\u1DBA\\u2303',\n u'_\\uFF3F\\u02CD\\u0331\\u0320\\u268A\\uFE58',\n u'`\\uFF40\\u0300\\u02CB\\u2035',\n u'a\\uFF41\\u0251\\u0430',\n u'b\\uFF42',\n u'c\\uFF43\\u03F2\\u0441\\u217D',\n u'd\\uFF44\\u0501\\u217E',\n u'e\\uFF45\\u0435\\u1971\\u19C9',\n u'f\\uFF46',\n u'g\\uFF47\\u0261',\n u'h\\uFF48\\u04BB',\n u'i\\uFF49\\u0456\\u2170',\n u'j\\uFF4A\\u03F3\\u0458',\n u'k\\uFF4B',\n u'l\\uFF4C',\n u'm\\uFF4D\\u217F',\n u'n\\uFF4E\\u1952',\n u'o\\uFF4F\\u03BF\\u043E\\u0CE6\\u0D20\\u0D66\\u199E\\u19D0\\u2C9F',\n u'p\\uFF50\\u0440\\u2CA3',\n u'q\\uFF51',\n u'r\\uFF52',\n u's\\uFF53\\u0455',\n u't\\uFF54',\n u'u\\uFF55\\u1959\\u222A',\n u'v\\uFF56\\u1D20\\u2174\\u2228\\u22C1',\n u'w\\uFF57\\u1D21',\n u'x\\uFF58\\u0445\\u2179\\u2CAD',\n u'y\\uFF59\\u0443\\u1EFF',\n u'z\\uFF5A\\u1901\\u1D22',\n u'{\\uFF5B\\uFE5B',\n u'|\\uFF5C\\u01C0\\u0846\\u1175\\u16C1\\u20D2\\u239C\\u239F\\u23A2'\n + u'\\u23A5\\u23AA\\u23AE\\u2F01\\u3021\\u4E28\\uFE31\\uFE33\\uFFE8',\n u'}\\uFF5D\\uFE5C',\n u'~\\uFF5E\\u02DC\\u2053\\u223C\\u301C'\n )\n\n\ndef homographs_for_char(char):\n index = ord(char) - ord('!')\n return get_homographs()[index]\n\n\ndef has_homographs(char):\n return ord('!') <= ord(char) <= ord('~')\n\n\ndef listing():\n for homs in get_homographs():\n for c in homs:\n print c,\n print\n\n\ndef explain(char):\n if not has_homographs(char):\n print 'Must be ASCII'\n return\n\n try:\n import unicodedata\n except ImportError:\n print 'Install docutils.'\n return\n\n for hg in homographs_for_char(char):\n print ' %(hg)c\\tu%(point)04X %(cat)s/%(name)s' % {\n 'hg': hg,\n 'point': ord(hg),\n 'name': unicodedata.name(hg, '<unnamed>'),\n 'cat': unicodedata.category(hg)\n }\n\n\ndef pipe(hardness):\n from codecs import getwriter\n from random import random, randrange\n from sys import stdin, stdout\n\n out = getwriter(stdout.encoding or 'utf-8')(stdout)\n\n # for line in stdin works for piped input but not keyboard input\n\n while True:\n try:\n line = raw_input()\n except EOFError:\n return\n for c in line:\n if random() < hardness/100 and has_homographs(c):\n hms = homographs_for_char(c)\n index = randrange(len(hms))\n c = hms[index]\n out.write(c)\n print\n\n\ndef parse():\n from optparse import OptionParser\n\n parser = OptionParser()\n parser.add_option('-m', '--me-harder', dest='chance', type='float', default=1,\n help='replacement percent')\n parser.add_option('-e', '--explain', dest='char',\n help=\"show a char's homographs\")\n parser.add_option('-l', '--list', action='store_true',\n help='show all homographs')\n return parser.parse_args()\n\n\ndef main():\n try:\n (options, args) = parse()\n if options.list:\n listing()\n elif options.char:\n explain(unicode(options.char[0], 'utf-8'))\n else:\n pipe(options.chance)\n except KeyboardInterrupt:\n pass\n\n\nif __name__ == '__main__':\n main()\n" } ]
1
trineary/TradeTestingEngine
https://github.com/trineary/TradeTestingEngine
ed483a45270c5f0e7905538215202f911f3e53d2
fd124bc9265962b4214d293906fbaabbcc5ec540
2fb8bb27ff7ed5b0825ba47a73d18fa6d0f2b24e
refs/heads/master
2021-01-12T08:34:26.267683
2016-12-16T05:08:32
2016-12-16T05:08:32
76,616,080
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.753997266292572, "alphanum_fraction": 0.7677021622657776, "avg_line_length": 57.37333297729492, "blob_id": "c0f7c25652c121d1018c4244e831426828fde28c", "content_id": "a57d3f21d20213d84166ac83f52f39c19b2a2856", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4378, "license_type": "no_license", "max_line_length": 545, "num_lines": 75, "path": "/README.md", "repo_name": "trineary/TradeTestingEngine", "src_encoding": "UTF-8", "text": "# TradeTestingEngine\n\n**Background**\n\nThe Trade Testing Engine is a Python package for helping ascertain whether trading strategies have predictive capabilities or not. These statistical approaches were originally developed and written about in a number of different journals [1], [2], [3].\n\nThis project attempts to implement a variation of White's test, a Monte Carlo test, and a new test. The purpose of these tests is to establish a null hypothesis that it's not possible to predict where the market is going to go. The goal is to reject the null hypothesis and show that there is a high probability that a trading strategy does indeed have some predictive ability. Generally with hypothesis testing, a p-value of 0.05 or less is considered significant. The output of the TTE test is a p-value that the user is able to interpret.\n\nThis code consists of several different blocks: the interface, trade tracking, and the bootstrap algorithms.\n\n*Interface*\n\nThe interface provides a handful of easy calls that the user interacts with in conjuction with their trading algorithm. These calls will be discussed in more detail later with an example.\n\n*Trade Tracking*\n\nThe trade tracking component tracks all trades made by the user and generates a handful of statistics at the end. It helps track information that is used by the bootstrap algorithms.\n\n*Bootstrap Algorithms*\n\nAs previously mentioned, the bootstrap algorithms implement some statistical tools to help determine if a trading strategy has predictive capability. For those that are interested, the White and Monte Carlo tests are described in detail here [4].\n\n\n\n**Example**\n\nThis example is modified from the TTEPaperEx2 file in this repository. I'll post the code and then describe what's happening.\n\n\n equity = \"DIA\"\n startDate = '2016-01-04'\n endDate = '2016-03-20'\n\n tte = TTE()\n df = tte.get_hist_data(equity, startDate, endDate)\n\n *Trade 1*\n tte.open_trade(0, tte.SHORT)\n tte.close_trade(5)\n\n * Trade 2*\n tte.open_trade(8, tte.SHORT)\n tte.close_trade(12)\n\n * Trade 3*\n tte.open_trade(15, tte.LONG)\n tte.close_trade(20)\n\n tte.select_bootstrap(tte.BOOTSTRAP_TTE)\n pval = tte.get_pvalue(iterations=5000)\n tte.print_trade_history()\n tte.print_trade_stats()\n tte.plot_all(title) \n\n*Example Explanation*\n\nThis example starts out by defining an equity, start date, and end date. After the tte object is created, those three values are used to grab a historical set of open, high, low, close data from yahoo finance. The get_hist_data call returns the specified data in a dataframe. That information is also stored internally for use by the algorithms.\n\nAs the user steps sequentially through the time series in the dataframe, the user's algorithm will specify when to make entries and exits. When a new position is to be entered, the user calls open_trade with two parameters. The first parameter is the index to the current line in the dataframe in which the entry is made. The second parameter is the direction of the trade. When the trade is done, the user again supplies the index for the dataframe entry that their algorithm decides to claose the trade on.\n\nOnce the user has finished opening and closing trades, they specify which bootstrap to use by calling select_bootstrap. The user may then get the pvalue for the trades made by calling get_pvalue.\n\nOf interest as well are some of the printing and plotting functions. The print_trade_history call generates a list of all the trades made during the back test. The print_trade_stats call lists some basic stats of the trades made, number of winning nad losing trades, etc. Finally the plot_all call brings up a plot showing the distribution for the bootstrap, the time series that the user specified, and a graph showing where the long and short trades were made.\n\nThis project is a work in progress, so any constructive criticism is welcome.\n\n**Pseudo Bibliography**\n\n[1] Halbert White, A Reality Check for Data Snooping, Econometrica, 2000\n\n[2] William Brock and Josef Lakonishok and Blake Lebaron, Simple Technical Trading Rules and the Stochastic Properties of Stock Returns, The Journal of Finance, 1992\n\n[3] Ryan Sullivan and Allan Timmermann and Halbert White, Data-Snooping, Technical Trading Rule Performance, and the Bootstrap, The Journal of Finance, 1999\n\n[4] David Aronson, Evidence-Based Technical Analysis, Wiley & Sons, 2007\n" }, { "alpha_fraction": 0.530684769153595, "alphanum_fraction": 0.5394057035446167, "avg_line_length": 30.252525329589844, "blob_id": "74f54449a77690ec88bf1d7c01a3817e6d0f2cd3", "content_id": "1289db75a536b4a4a5ca411041c76eb48c0d86ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3096, "license_type": "no_license", "max_line_length": 118, "num_lines": 99, "path": "/TTEBootstrapTests/WhiteBootstrap.py", "repo_name": "trineary/TradeTestingEngine", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------------------------------------------------\n#\n# Patrick Neary\n# Date: 11/12/2016\n#\n# Fin 5350 / Dr. Tyler J. Brough\n# Trade Testing Engine:\n#\n# kWhiteRealityCheck.py\n#\n# This file is an implementation of White's Reality Check for evaluating the significance of a trading rule's\n# predictive power.\n#\n# --------------------------------------------------------------------------------------------------------------------\n\n\n# Import standard packages\nimport random\nfrom matplotlib import pyplot as plt\nfrom BootstrapABC import BootstrapABC\n\n# Import my classes\nfrom BootstrapCalcTools import GetDailyReturns, GetMeanDailyReturn, GetPVal\n\n# Global values for selecting different options\n\n\n# --------------------------------------------------------------------------------------------------------------------\n\nclass WhiteBootstrap(BootstrapABC):\n\n def __init__(self):\n self._sample_means = []\n self._df = None\n self._detrended_data = None\n self._col_name = None\n self._num_iterations = None\n pass\n\n\n def init_test(self, df, col_name, num_iterations=5000):\n \"\"\"\n init_test initializes the White Reality Check Bootstrap test\n\n :param df: dataframe containing data to bootstrap\n :param col_name: name of colume in data frame containing data\n :param num_iterations: number of iterations to build bootstrap sampling distribution\n :return: none\n \"\"\"\n self._df = df\n self._detrended_data = None\n self._col_name = col_name\n self._num_iterations = num_iterations\n\n datalen = len(self._df.index)\n\n # Detrend the data\n meanDailyReturn, dailyreturns = GetMeanDailyReturn(self._df, self._col_name)\n dailyreturns = dailyreturns.apply(lambda x: x-meanDailyReturn)\n\n # Iterate over the daily returns and build a distribution of returns\n meanList = []\n for meanCount in xrange(0, self._num_iterations):\n sampleSum = 0\n for randomReturn in xrange(0, datalen):\n index = random.randint(0, datalen-1)\n sampleSum += dailyreturns.iat[index, 0]\n #sampleMean = sampleSum #/ datalen\n #meanList.append(sampleMean)\n meanList.append(sampleSum)\n\n #histogram, edges = np.histogram(meanList, bins=10)\n\n self._sample_means = meanList\n\n pass\n\n def plot_histogram(self, bins=20):\n if len(self._sample_means) > 0:\n plt.hist(self._sample_means, bins=bins)\n plt.grid(True)\n plt.show()\n return\n\n def get_histogram_data(self):\n return self._sample_means\n\n def has_predictive_power(self, rule_percent_return):\n\n return GetPVal(self._sample_means, rule_percent_return)\n\n\n# --------------------------------------------------------------------------------------------------------------------\n# Test functions\n\n\nif __name__ == \"__main__\":\n # Functions to run if this file is executed\n print \"Run default function for \", __file__\n\n\n" }, { "alpha_fraction": 0.5495668649673462, "alphanum_fraction": 0.57844078540802, "avg_line_length": 20.61458396911621, "blob_id": "98a578dc42a4a972d948c55c6567bd4cab141643", "content_id": "24793317f6ddc1482997a87ce8e1d8d521e53d54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2078, "license_type": "no_license", "max_line_length": 118, "num_lines": 96, "path": "/TTEPaperEx2.py", "repo_name": "trineary/TradeTestingEngine", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------------------------------------------------\n#\n# Patrick Neary\n# Date: 12/14/2016\n#\n# Fin 5350 / Dr. Tyler J. Brough\n# Trade Testing Engine:\n#\n# TTEPaperEx2.py\n#\n# This file illustrates an example of trading rules that are engaged in a varied environment that is profitable\n# and rejects the null hypothesis.\n#\n# --------------------------------------------------------------------------------------------------------------------\n\n\n# Import standard packages\n\n# Import my classes\nfrom pytte.tte import TTE\n\n\ndef PrintResults(tte, title=None):\n\n pval = tte.get_pvalue(iterations=5000)\n print \"pval:\", pval, \"\\n\"\n tte.print_trade_history()\n tte.print_trade_stats()\n tte.plot_all(title)\n\n pass\n\ndef TestWhiteRealityCheck(tte):\n print \"White Bootstrap\"\n tte.select_bootstrap(tte.BOOTSTRAP_WHITE)\n PrintResults(tte, \"White Bootstrap\")\n\n pass\n\n\ndef TestMonteCarloBootstrap(tte):\n print \"Monte Carlo Bootstrap\"\n tte.select_bootstrap(tte.BOOTSTRAP_MONTE_CARLO)\n PrintResults(tte, \"Monte Carlo Bootstrap\")\n\n pass\n\n\ndef TestTTEBootstrap(tte):\n print \"TTE Bootstrap\"\n tte.select_bootstrap(tte.BOOTSTRAP_TTE)\n PrintResults(tte, \"TTE Bootstrap\")\n\n pass\n\n\nif __name__ == \"__main__\":\n # Functions to run if this file is executed\n print \"Run default function for \", __file__\n\n equity = \"DIA\"\n startDate = '2016-01-04'\n endDate = '2016-03-20'\n\n tte = TTE()\n df = tte.get_hist_data(equity, startDate, endDate)\n print len(df)\n\n # Trade 1\n tte.open_trade(0, tte.SHORT)\n tte.close_trade(5)\n\n # Trade 2\n tte.open_trade(8, tte.SHORT)\n tte.close_trade(12)\n\n # Trade 3\n #tte.open_trade(15, tte.LONG)\n #tte.close_trade(20)\n\n # Trade 4\n tte.open_trade(29, tte.LONG)\n tte.close_trade(34)\n\n # Trade 5\n #\n tte.open_trade(39, tte.LONG)\n tte.close_trade(46)\n\n # Trade 6\n tte.open_trade(47, tte.LONG)\n tte.close_trade(50)\n\n #TestWhiteRealityCheck(tte)\n #TestMonteCarloBootstrap(tte)\n TestTTEBootstrap(tte)\n\n\n\n" }, { "alpha_fraction": 0.5770297050476074, "alphanum_fraction": 0.5849505066871643, "avg_line_length": 26.150537490844727, "blob_id": "0ad2b578b31e323d9b68af36bf0dcb12dd51b68e", "content_id": "4f1e6ed5672b1def7dc7e2271df0634aeb9174f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2525, "license_type": "no_license", "max_line_length": 118, "num_lines": 93, "path": "/TTEBootstrapTests/BootstrapCalcTools.py", "repo_name": "trineary/TradeTestingEngine", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------------------------------------------------\n#\n# Patrick Neary\n# Date: 11/12/2016\n#\n# Fin 5350 / Dr. Tyler J. Brough\n# Trade Testing Engine:\n#\n# BootstrapCalcTools.py\n#\n# This file contains tools common to the bootstrap processes.\n#\n# --------------------------------------------------------------------------------------------------------------------\n\n\n# Import standard packages\nimport pandas\nimport math\n\n\n\n# --------------------------------------------------------------------------------------------------------------------\n\n\ndef GetDailyReturns(df, colName):\n \"\"\"\n Generate a dataframe containing the mean daily returns from the specified data frame and column name. The daily\n returns are calculated using log(day/prev day).\n\n :param df:\n :param colName:\n :return:\n \"\"\"\n\n prev = None\n returns = []\n for index, rowVal in df[colName].iteritems():\n\n if(prev == None):\n dreturn = 0.0\n else:\n dreturn = math.log10(float(rowVal)/prev)\n #print index, rowVal, dreturn\n prev = float(rowVal)\n returns.append(dreturn)\n\n return pandas.DataFrame(data=returns)\n\n\ndef GetMeanDailyReturn(df, colName):\n \"\"\"\n Given the dataframe and column, calculate the daily return for the sequence and then determine the mean daily\n return.\n\n :param df:\n :param colName:\n :return: return the mean along with the dataframe containing the data\n \"\"\"\n\n dailyReturns = GetDailyReturns(df, colName)\n meanDailyReturn = dailyReturns[0].mean()\n\n return meanDailyReturn, dailyReturns\n\n\ndef GetDetrendedReturns(df, col_name):\n\n # Get the daily returns and the mean daily return\n meanDailyReturn, dailyreturns = GetMeanDailyReturn(df, col_name)\n # Detrend the daily returns by subtracting off the mean daily return\n detrended_returns = dailyreturns.apply(lambda x: x-meanDailyReturn)\n\n return detrended_returns\n\n\ndef GetPVal(sample_dist, rule_percent_return):\n '''\n\n :param sample_dist: sample distribution, this is assumed to be a distribution around zero\n :param rule_percent_return: percent return of the trading rule\n :return: return the pvalue associated with the trading rule\n '''\n\n lessThanCnt = 0\n for meanReturn in sample_dist:\n if meanReturn < rule_percent_return:\n lessThanCnt += 1\n\n percentage = lessThanCnt/float(len(sample_dist))\n #print percentage, lessThanCnt\n pval = 1-percentage\n\n return pval\n" }, { "alpha_fraction": 0.5231910943984985, "alphanum_fraction": 0.5343227982521057, "avg_line_length": 23.454545974731445, "blob_id": "084de993d0d21a9a5d444749b1c1a874b9df6f90", "content_id": "cdb86d8f804b01a234b91c2efb37afd5d2162fc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1078, "license_type": "no_license", "max_line_length": 118, "num_lines": 44, "path": "/TTEBootstrapTests/BootstrapABC.py", "repo_name": "trineary/TradeTestingEngine", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------------------------------------------------\n#\n# Patrick Neary\n# Date: 11/12/2016\n#\n# Fin 5350 / Dr. Tyler J. Brough\n# Trade Testing Engine:\n#\n# BootstrapABC.py\n#\n# Abstract base class for all tests developed to evaluate rules.\n#\n# --------------------------------------------------------------------------------------------------------------------\n\n\n# Import standard packages\nfrom abc import ABCMeta, abstractmethod\n\n\nclass BootstrapABC():\n \"\"\"\n Base test class for bootstrap tests.\n\n InitTest will initialize the bootstrap test with data that it needs and parameters needed to build the\n sampling distribution.\n\n HasPredictivePower will take a percent gain from a rule and determine what the predictive power is\n\n SaveOutput will generate output for the test.. maybe\n \"\"\"\n\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def init_test(self):\n pass\n\n @abstractmethod\n def has_predictive_power(self):\n pass\n\n #@abstractmethod\n #def SaveOutput(self):\n #s pass\n\n\n" }, { "alpha_fraction": 0.5586029291152954, "alphanum_fraction": 0.574566125869751, "avg_line_length": 35.74803161621094, "blob_id": "ff9dfb5a1eb999baafe050ece7f516b56f7b2dcc", "content_id": "2b71efe2aa7cd5f1ca25b387e98437c9a5e519de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9334, "license_type": "no_license", "max_line_length": 121, "num_lines": 254, "path": "/TradeTracking/TradeHistory.py", "repo_name": "trineary/TradeTestingEngine", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------------------------------------------------\n# Patrick Neary\n# Fin5350\n# Project\n# 10/6/2016\n#\n# TradeHistory.py\n#\n# This file\n# --------------------------------------------------------------------------------------------------------------------\n\nimport math\nimport datetime\nimport numpy as np\nfrom TradeDetails import TradeDetails\n\n\nclass TradeTracking:\n\n def __init__(self, trackHistory=True, trackDailyPositions=False):\n self.totalPL = 0.0\n self.totalPercentReturn = 0.0\n self.tradeHistory = []\n self.currTrade = TradeDetails()\n self.trackHistory = trackHistory\n self.totalWins = 0\n self.totalLosses = 0\n self.longWins = 0\n self.shortWins = 0\n self.longLosses = 0\n self.shortLosses = 0\n self.tickData = None\n self.trackDailyPositions = trackDailyPositions\n self.ID = None\n self.isTradeOpen = False\n self.currTradeDirection = 0\n self.currPrice = 0.0\n self.CASH = 0\n self.LONG = 1\n self.SHORT = -1\n self.firsttimestamp = None\n self.lasttimestamp = None\n self.openPrice = 0.0\n self.cnt = 0\n return\n\n def __str__(self):\n tradehistorystr = \"\"\n for trade in self.tradeHistory:\n tradehistorystr += trade.__str__() + \"\\n\"\n return tradehistorystr\n\n def InitTickData(self, tickData):\n # tickData - data frame containing time stamped tick information. A column will be added to this data to\n # track every time period's position. 0 - No trade, 1 - Long position, -1 - Short position.\n\n self.tickData = tickData\n\n # Add column to track position for every time period and make sure entries are 0 for 'no trade'\n self.tickData['Position'] = np.zeros((len(tickData), 1))\n pass\n\n def UpdateTradePositions(self):\n # Find and update the positions between the open and close dates in the dataframe. This function is based\n # off of values in self.currTrade. This shouldn't be called until after openTimeStamp, closeTimeStamp, and\n # tradeDirection have been set.. or after CloseTrade has been called.\n\n # Only run through this if we're tracking daily positions\n if self.trackDailyPositions == False:\n return\n # Iterate through the array looking for relevant time stamps.\n\n index = 0\n for idx in self.tickData.iterrows():\n #print idx\n currtimestamp = datetime.datetime.strptime(self.tickData.ix[index]['Date'], \"%Y-%m-%d\")\n if currtimestamp >= self.currTrade.openTimeStamp and currtimestamp <= self.currTrade.closeTimeStamp:\n self.tickData.set_value(index, 'Position', self.currTrade.tradeDirection)\n index += 1\n\n pass\n\n def OpenTrade(self, equity, openprice, spread, direction, timestamp, id=None):\n if self.firsttimestamp == None:\n self.firsttimestamp = timestamp\n self.currTrade = TradeDetails()\n self.currTrade.OpenTrade(equity, openprice, spread, direction, timestamp, id)\n self.ID = id\n self.isTradeOpen = True\n self.currTradeDirection = direction\n self.openPrice = openprice\n #print \"OpenTrade\", equity, openprice, spread, direction, timestamp, id\n return\n\n def UpdateStats(self, closeprice):\n tradePL = self.currTrade.GetCurrentPL(closeprice)\n if tradePL > 0:\n if self.currTradeDirection == self.LONG:\n self.longWins += 1\n else:\n self.shortWins += 1\n self.totalWins += 1\n else:\n if self.currTradeDirection == self.LONG:\n self.longLosses += 1\n else:\n self.shortLosses += 1\n self.totalLosses += 1\n pass\n\n def CloseTrade(self, closeprice, timestamp, direction):\n self.lasttimestamp = timestamp\n # Close the trade\n self.currTrade.CloseTrade(closeprice, timestamp)\n tradePL = self.currTrade.GetCurrentPL(closeprice)\n self.totalPercentReturn += self.currTrade.GetTradePercentPL()\n\n if tradePL > 0 or self.cnt == 0:\n # add trade to the history if enabled\n if self.trackHistory == True:\n # Drop half of the losing trades\n self.tradeHistory.append(self.currTrade)\n # Add trade results to total PL\n self.totalPL += tradePL\n self.currTrade.SetTotalPL(self.totalPL)\n # Update stats\n self.UpdateStats(closeprice)\n # Update trade positions for this trade if it's being tracked\n self.UpdateTradePositions()\n if tradePL < 0:\n if self.cnt < 3:\n self.cnt += 1\n if self.cnt >= 3:\n self.cnt = 0\n self.ID = None\n self.isTradeOpen = False\n self.currTradeDirection = direction\n return\n\n def GetTradeCurrPL(self, currPrice):\n return self.currTrade.GetCurrentPL(currPrice)\n\n def UpdateCurrPrice(self, currPrice):\n self.currPrice = currPrice\n pass\n\n def GetTimeStepPL(self, nextPrice):\n # This gets the difference between the updated price and the next price. Order of subtraction is based on\n # the direction of the trade.\n if self.currTradeDirection == self.LONG:\n return nextPrice - self.currPrice\n elif self.currTradeDirection == self.SHORT:\n return self.currPrice - nextPrice\n else:\n return 0.0\n\n def GetTradeCurrDuration(self):\n return self.currTrade.GetTradeDuration()\n\n def GetTotalPL(self):\n # This returns the cumulative PL prior to current trade (if any)\n return self.totalPL\n\n def GetPercentReturn(self):\n # This calculates the percent return using ln(r1) - ln(r2) where r1 and r2 are opening/closing prices\n return self.totalPercentReturn\n\n def GetTradeStatsStr(self):\n\n tradestatsstr = \"\"\n totalTrades = max((self.totalWins + self.totalLosses), 1)\n\n tradestatsstr += \"Trading Stats:\\n\"\n tradestatsstr += \"Total trades:\\t %d\\n\" % totalTrades\n tradestatsstr += \"Total Wins:\\t\\t %d, \\t%0.2f%%\\n\" %(self.totalWins, (float(self.totalWins)/totalTrades)*100)\n tradestatsstr += \"Total Losses:\\t %d, \\t%0.2f%%\\n\" %(self.totalLosses, (float(self.totalLosses)/totalTrades)*100)\n longTrades = max((self.longWins + self.longLosses), 1)\n shortTrades = max((self.shortWins + self.shortLosses), 1)\n tradestatsstr += \"Long wins:\\t\\t %d, \\t%0.2f%%\\n\" %(self.longWins, (float(self.longWins)/longTrades)*100)\n tradestatsstr += \"Long losses:\\t %d, \\t%0.2f%%\\n\" %(self.longLosses, (float(self.longLosses)/longTrades)*100)\n tradestatsstr += \"Short wins:\\t\\t %d, \\t%0.2f%%\\n\" %(self.shortWins, (float(self.shortWins)/shortTrades)*100)\n tradestatsstr += \"Short losses:\\t %d, \\t%0.2f%%\\n\" %(self.shortLosses, (float(self.shortLosses)/shortTrades)*100)\n tradestatsstr += \"Total P/L:\\t\\t %0.2f\\n\" % self.totalPL\n tradestatsstr += \"Percent P\\L:\\t %0.2f\\n\" % self.totalPercentReturn\n tradestatsstr += \"First timestamp: %s\\n\" % self.firsttimestamp\n tradestatsstr += \"Last timestamp:\\t %s\\n\" % self.lasttimestamp\n\n return tradestatsstr\n\n def PrintHistory(self):\n tradehistorystr = \"\"\n for trade in self.tradeHistory:\n tradehistorystr += trade.__str__()\n print trade\n\n return tradehistorystr\n\n def GetHistory(self):\n # Return list of TradeDetails\n return self.tradeHistory\n\n def getCurrID(self):\n # If application is interested in the ID for the current trade then it will be available (if set).\n return self.ID\n\n def GetIsTradeOpen(self):\n return self.isTradeOpen\n\n def GetCurrTradeDirection(self):\n return self.currTradeDirection\n\n\n\n# --------------------------------------------------------------------------------------------------------------------\n#\n# --------------------------------------------------------------------------------------------------------------------\ndef ExecuteTestTrades():\n CASH = 0\n LONG = 1\n SHORT = 2\n\n openTS = datetime.datetime(2016, 04, 18)\n closeTS = datetime.datetime(2016, 04, 19)\n openPrice = 78.8\n closePrice = 78.2\n spread = 0.032\n\n tt = TradeTracking()\n tt.OpenTrade(\"AUDJPY\", openPrice, spread, LONG, openTS)\n tt.CloseTrade(closePrice, closeTS)\n print tt\n\n openTS = datetime.datetime(2016, 04, 20)\n closeTS = datetime.datetime(2016, 04, 22)\n openPrice = 79.0\n closePrice = 79.8\n spread = 0.032\n\n tt.OpenTrade(\"AUDJPY\", openPrice, spread, LONG, openTS)\n tt.CloseTrade(closePrice, closeTS)\n print \"\"\n print tt\n\n return\n\n# --------------------------------------------------------------------------------------------------------------------\n# Default function when the file is run\n# --------------------------------------------------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n # Functions to run if this file is executed\n print \"Run default function for \", __file__\n\n ExecuteTestTrades()\n" }, { "alpha_fraction": 0.5501378178596497, "alphanum_fraction": 0.5617977380752563, "avg_line_length": 30.446666717529297, "blob_id": "f88c12740e770e94e0f9368005c75ef13ff52b33", "content_id": "ae9d2fb40b4c29f6b148aa909b301cf6285aefbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4717, "license_type": "no_license", "max_line_length": 118, "num_lines": 150, "path": "/TTEBootstrapTests/MonteCarloBootstrap.py", "repo_name": "trineary/TradeTestingEngine", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------------------------------------------------\n#\n# Patrick Neary\n# Date: 11/12/2016\n#\n# Fin 5350 / Dr. Tyler J. Brough\n# Trade Testing Engine:\n#\n# kWhiteRealityCheck.py\n#\n# This file is an implementation of White's Reality Check for evaluating the significance of a trading rule's\n# predictive power.\n#\n# --------------------------------------------------------------------------------------------------------------------\n\n\n# Import standard packages\nimport random\nfrom matplotlib import pyplot as plt\nfrom BootstrapABC import BootstrapABC\n\n# Import my classes\nfrom BootstrapCalcTools import GetDailyReturns, GetMeanDailyReturn, GetDetrendedReturns, GetPVal\n\n# Global values for selecting different options\n\n\n# --------------------------------------------------------------------------------------------------------------------\nclass MonteCarloBootstrap(BootstrapABC):\n\n def __init__(self):\n self._sample_means = []\n self._rules = []\n pass\n\n def init_test(self, df, col_name, num_iterations=5000):\n \"\"\"\n init_test initializes the White Reality Check Bootstrap test\n\n :param df: dataframe containing data to bootstrap\n :param col_name: name of colume in data frame containing data\n :param daily_rules: list of rules applied to the time series in the data frame. rules take on (+1, -1) values\n :param num_iterations: number of iterations to build bootstrap sampling distribution\n :return: none\n \"\"\"\n self._df = df\n self._detrended_data = None\n self._col_name = col_name\n self._num_iterations = num_iterations\n\n datalen = len(self._df.index)\n #gain = float(self._df.at[datalen-1, col_name]) - float(self._df.at[0, col_name])\n #dailyGain = gain/datalen\n\n pass\n\n\n def plot_histogram(self, bins=20):\n if len(self._sample_means) > 0:\n plt.hist(self._sample_means, bins=bins)\n plt.grid(True)\n plt.show()\n return\n\n def get_histogram_data(self):\n return self._sample_means\n\n def run_monte_carlo_round(self, detrended_data):\n # Run through one iteration of pairing daily rules with detrended returns. Calculate the average return\n # and return that value.\n\n # check length of detrended data and daily rules. They should be the same length.\n if len(detrended_data) != len(self._rules):\n print \"Monte Carlo error! Detrended data and daily rules not the same length.\"\n return -1\n\n # Get a copy of the detrended data\n detrended_copy = detrended_data[0].tolist()\n\n # Cycle through the data now\n total_val = 0\n tradeDirection = 1\n for index in xrange(0, len(detrended_copy)):\n index = random.randint(0, len(detrended_copy)-1)\n if tradeDirection == 1:\n tradeDirection = -1\n else:\n tradeDirection = 1\n total_val += tradeDirection * detrended_copy.pop(index)\n\n #print \"total_val: \", total_val\n\n return total_val\n\n def has_predictive_power(self, rule_percent_return):\n\n # Get daily rules from the dataframe\n rules = self._df['Position'].tolist()\n #print \"rules\", rules\n\n # Set daily rules\n self._rules = rules\n\n # Get one-day market price changes\n\n # Detrend the data\n detrended_returns = GetDetrendedReturns(self._df, self._col_name)\n\n # Run through iterations and collect distribution\n self._sample_means = []\n for i in range(0, self._num_iterations, 1):\n avg_val = self.run_monte_carlo_round(detrended_returns)\n self._sample_means.append(avg_val)\n\n # Calculate and return the p-value for the sample mean distribution calculated above\n return GetPVal(self._sample_means, rule_percent_return)\n\n# --------------------------------------------------------------------------------------------------------------------\n# Test functions\n\ndef test_monte_carlo_round():\n rules = [1, 1, -1, -1, -1]\n data = [2, 3, 4, 3, 2]\n\n mc = MonteCarloBootstrap()\n mc._rules = rules\n\n mean = mc.run_monte_carlo_round(data)\n print \"mean result: \", mean\n\n pass\n\ndef test_monte_carlo_prediction():\n rules = [1, 1, -1, -1, -1]\n data = [2, 3, 4, 3, 2]\n\n mc = MonteCarloBootstrap()\n mc._rules = rules\n\n mean = mc.run_monte_carlo_round(data)\n print \"mean result: \", mean\n\n pass\n\nif __name__ == \"__main__\":\n # Functions to run if this file is executed\n print \"Run default function for \", __file__\n\n #test_monte_carlo_round()\n test_monte_carlo_prediction()\n" }, { "alpha_fraction": 0.563343346118927, "alphanum_fraction": 0.5929535031318665, "avg_line_length": 22.289474487304688, "blob_id": "4ef9c62150ad424b3ca563f503d1ec36781a1432", "content_id": "4689fa0a0859ea26731c37a8e856a850e1e0db71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2668, "license_type": "no_license", "max_line_length": 118, "num_lines": 114, "path": "/TTEExampleCode.py", "repo_name": "trineary/TradeTestingEngine", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------------------------------------------------\n#\n# Patrick Neary\n# Date: 9/22/2016\n#\n# Fin 5350 / Dr. Tyler J. Brough\n# Trade Testing Engine:\n#\n# TestFile.py\n#\n# This file shows how to use the TTE package\n#\n# --------------------------------------------------------------------------------------------------------------------\n\n\n# Import standard packages\n\n# Import my classes\nfrom pytte.tte import TTE\n\n\ndef TestWhiteRealityCheck(tte, df):\n\n #tte.open_trade(4, tte.LONG)\n #tte.close_trade(11)\n\n tte.open_trade(10, tte.SHORT)\n tte.close_trade(13)\n\n tte.select_bootstrap(tte.BOOTSTRAP_WHITE)\n pval = tte.get_pvalue(iterations=5000)\n print \"pval:\", pval\n tte.plot_pdf()\n print tte.get_trade_stats()\n tte.plot_trades_equity()\n\n pass\n\n\ndef TestMonteCarloBootstrap(tte, df):\n\n #tte.open_trade(4, tte.LONG)\n #tte.close_trade(11)\n\n tte.open_trade(10, tte.SHORT)\n tte.close_trade(13)\n\n tte.select_bootstrap(tte.BOOTSTRAP_MONTE_CARLO)\n pval = tte.get_pvalue(iterations=5000)\n print \"pval:\", pval\n tte.plot_pdf()\n print tte.get_trade_stats()\n tte.plot_trades_equity()\n\n pass\n\n\ndef TestTTEBootstrap(tte, df):\n\n #tte.open_trade(4, tte.LONG)\n #tte.close_trade(11)\n\n tte.open_trade(10, tte.SHORT)\n tte.close_trade(13)\n\n tte.select_bootstrap(tte.BOOTSTRAP_TTE)\n pval = tte.get_pvalue(iterations=5000)\n print \"pval:\", pval, \"\\n\"\n tte.plot_pdf()\n tte.plot_trades_equity()\n tte.print_trade_history()\n tte.print_trade_stats()\n\n pass\n\ndef CompareBootstrapOutputs(tte, df):\n #tte.open_trade(4, tte.LONG)\n #tte.close_trade(11)\n\n tte.open_trade(10, tte.SHORT)\n tte.close_trade(13)\n\n # Get and display TTE Bootstrap pvalue\n #tte.select_bootstrap(tte.BOOTSTRAP_TTE)\n #pval = tte.get_pvalue(iterations=5000)\n #print \"TTE pval:\", pval\n\n # Get and display TTE Bootstrap pvalue\n #tte.select_bootstrap(tte.BOOTSTRAP_MONTE_CARLO)\n #pval = tte.get_pvalue(iterations=5000)\n #print \"Monte Carlo pval:\", pval\n\n # Get and display TTE Bootstrap pvalue\n tte.select_bootstrap(tte.BOOTSTRAP_WHITE)\n pval = tte.get_pvalue(iterations=5000)\n print \"White pval:\", pval\n\n pass\n\nif __name__ == \"__main__\":\n # Functions to run if this file is executed\n print \"Run default function for \", __file__\n\n equity = \"SPY\"\n startDate = '2016-08-20'\n endDate = '2016-09-16'\n\n tte = TTE()\n df = tte.get_hist_data(equity, startDate, endDate)\n\n #TestWhiteRealityCheck(tte, df)\n #TestMonteCarloBootstrap(tte, df)\n #TestTTEBootstrap(tte, df)\n CompareBootstrapOutputs(tte, df)\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5195508599281311, "alphanum_fraction": 0.5321837067604065, "avg_line_length": 32.246665954589844, "blob_id": "7967bedd4763321484b8b8dda095307302e0306d", "content_id": "6597cae0adcfcd55ec3e848813837fa88a6628a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4987, "license_type": "no_license", "max_line_length": 118, "num_lines": 150, "path": "/TradeTracking/TradeDetails.py", "repo_name": "trineary/TradeTestingEngine", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------------------------------------------------\n# Patrick Neary\n# CS 6110\n# Project\n# 10/6/2016\n#\n# TradeDetails.py\n#\n# This file\n# --------------------------------------------------------------------------------------------------------------------\n\nimport datetime\nimport math\n\nclass TradeDetails:\n\n CASH = 0\n LONG = 1\n SHORT = -1\n\n def __init__(self):\n self.openPrice = 0.0\n self.closePrice = 0.0\n self.spread = 0.0\n self.tradeDirection = self.CASH\n self.equityName = \"\"\n self.openTimeStamp = None\n self.closeTimeStamp = None\n self.duration = None\n self.currPL = 0.0\n self.stopLoss = None\n self.profitTarget = None\n self.totalPL = 0.0\n self.ID = None\n return\n\n def __str__(self):\n mystr = \"%s, %s, %s, %s, %s, %s, %s, %s, %s\" % (self.equityName, self.openTimeStamp, self.closeTimeStamp,\n self.duration, self.openPrice, self.closePrice, self.currPL, self.totalPL, self.ID)\n return mystr\n\n def OpenTrade(self, equity, openprice, spread, direction, timestamp, id=None):\n # timestamp - needs to be a string in format of \"year-month-day\" or in datetime format.\n if isinstance(timestamp, str) == True:\n timestamp = datetime.datetime.strptime(timestamp, \"%Y-%m-%d\")\n\n # Check to make sure timestamp is a date/time format\n if isinstance(timestamp, datetime.datetime) == False:\n print \"Timestamp needs to be in datetime format\"\n return\n\n self.openPrice = openprice\n self.equityName = equity\n self.spread = spread\n self.tradeDirection = direction\n self.openTimeStamp = timestamp\n self.ID = id # ID of entity making the trade\n return\n\n def CloseTrade(self, closeprice, timestamp):\n # timestamp - needs to be a string in format of \"year-month-day\" or in datetime format.\n if isinstance(timestamp, str) == True:\n timestamp = datetime.datetime.strptime(timestamp, \"%Y-%m-%d\")\n\n # Check to make sure timestamp is a date/time format\n if isinstance(timestamp, datetime.datetime) == False:\n print \"Timestamp needs to be in datetime format\"\n return\n\n # Close the trade\n self.closePrice = closeprice\n self.closeTimeStamp = timestamp\n #self.tradeDirection = self.CASH\n\n self.GetCurrentPL(closeprice)\n self.GetTradeDuration()\n #self.ID = None\n return\n\n def GetCurrentPL(self, currprice):\n # Calculate the change in price from open to now. This includes the cost of the spread.\n\n if self.tradeDirection is self.CASH:\n self.currPL = 0.0\n elif self.tradeDirection is self.SHORT:\n self.currPL = float(self.openPrice) - float(currprice) - float(self.spread)\n else:\n self.currPL = float(currprice) - float(self.openPrice) - float(self.spread)\n\n #print \"GetCurrentPL: \", self.currPL, self.tradeDirection, self.spread\n\n return self.currPL\n\n def GetTradePercentPL(self):\n\n if self.tradeDirection is self.CASH:\n totalPercentReturn = 0.0\n elif self.tradeDirection is self.SHORT:\n totalPercentReturn = math.log10(float(self.openPrice)) - math.log10(float(self.closePrice))\n else:\n totalPercentReturn = math.log10(float(self.closePrice)) - math.log10(float(self.openPrice))\n\n return totalPercentReturn\n\n def GetTradeDuration(self):\n duration = self.closeTimeStamp - self.openTimeStamp\n self.duration = duration\n return self.duration\n\n def RedefineDirection(self, cash, long, short):\n self.CASH = cash\n self.LONG = long\n self.SHORT = short\n return\n\n def SetTotalPL(self, totalPL):\n self.totalPL = totalPL\n return\n\n def GetCurrentTradeID(self):\n return self.ID\n\n# --------------------------------------------------------------------------------------------------------------------\n#\n# --------------------------------------------------------------------------------------------------------------------\n\ndef TestTradeDetails():\n\n openTS = datetime.datetime(2016, 04, 18)\n closeTS = datetime.datetime(2016, 04, 19)\n openPrice = 78.8\n closePrice = 78.2\n spread = 0.032\n\n td = TradeDetails()\n td.OpenTrade(\"AUDJPY\", openPrice, spread, 1, openTS)\n td.CloseTrade(closePrice, closeTS)\n print td\n\n return\n\n# --------------------------------------------------------------------------------------------------------------------\n# Default function when the file is run\n# --------------------------------------------------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n # Functions to run if this file is executed\n print \"Run default function for \", __file__\n\n TestTradeDetails()\n" }, { "alpha_fraction": 0.5740002393722534, "alphanum_fraction": 0.585849404335022, "avg_line_length": 31.742536544799805, "blob_id": "5d01710b922d01086cb4194560679d760cc2f236", "content_id": "7fa6c7e830abb8d6bbcb552762b34fccf9439984", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8777, "license_type": "no_license", "max_line_length": 119, "num_lines": 268, "path": "/TTE.py", "repo_name": "trineary/TradeTestingEngine", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------------------------------------------------\n#\n# Patrick Neary\n# Date: 9/21/2016\n#\n# Fin 5350 / Dr. Tyler J. Brough\n# Trade Testing Engine:\n#\n# tte.py\n#\n# This file handles the interface to most of the code in this project.\n#\n# --------------------------------------------------------------------------------------------------------------------\n\n# Import standard packages\nimport math\nimport pandas as pd\nimport datetime as dt\nfrom matplotlib import pyplot\nimport yahoo_finance as yfinance\n\n\n# Import my classes\nfrom TradeTracking.TradeHistory import TradeTracking\nfrom pytte.TTEBootstrapTests import WhiteBootstrap, MonteCarloBootstrap, TTEBootstrap\n\n\nclass TTE:\n # Bootstrap options that are available with this package\n BOOTSTRAP_TTE = 0\n BOOTSTRAP_MONTE_CARLO = 1\n BOOTSTRAP_WHITE = 2\n # Trading direction options\\\n CASH = 0\n LONG = 1\n SHORT = -1\n\n def __init__(self):\n\n # Trade tracking\n self._tt = TradeTracking(trackDailyPositions=True)\n self._trade_history = None\n # Bootstrap initializations\n self._bs_tte = None\n self._bs_mc = None\n self._bs_wh = None\n self._bs = None # this is the currently selected bootstrap\n # Dataframe for trade data\n self._df = None\n self._column = None\n self._ticker = None\n\n return\n\n def get_hist_data(self, ticker, startdate, stopdate, column=\"Adj_Close\"):\n # get historical data\n # Inputs\n # 1. ticker - ticker sympol of desired equite. Ex. 'SPY'\n # 2. startdate - start date to start collecting data from. Ex. startdate = '2016-08-20'\n # 3. stopdate - stop date to stop collecting data from. Ex. endDate = '2016-09-16'\n # 4. column - this is the column in the dataframe to use to get price information from. Default is 'Adj_Close'\n # Returns\n # 1. dataframe containing data for the specified inputs\n #\n # Get a dataframe with data between the two dates for the specified ticker. This will automatically load\n # the historical data into the local _df variable.\n # Get the historical data and load into the dataframe variable. Return the historical data to the calling\n # function for the user to cycle through it to generate trade signals.\n\n #self._df = GetHistoricalStockData(ticker, startdate, stopdate)\n\n # Get the data from yahoo finance, reorder the data, and then put the data into a dataframe for easy use.\n yahoo = yfinance.Share(ticker)\n data = yahoo.get_historical(start_date=startdate, end_date=stopdate)\n\n # data comes in reversed order. Put it in ascending order.\n data = data[::-1]\n\n # Put the data into a dataframe\n df = pd.DataFrame(data=data)\n\n # Load historical data and initialize other values\n self.load_hist_data(ticker, df, column)\n\n return df\n\n def load_hist_data(self, ticker, hist_data, column=\"Adj_Close\"):\n # Load the specified data set. This is only used if the user loads historical data from a different source\n # (forex data for example).\n # Inputs\n # 1. hist_data - historical data in the format of a dataframe\n # 2. column - this is the column in the dataframe to use to get price information from. Default is 'Adj_Close'\n\n self._ticker = ticker\n self._df = hist_data\n self._tt.InitTickData(self._df)\n self._column = column\n self._trade_history = [0]*len(self._df[self._column]) # Make trade history the same length as the data\n\n pass\n\n def reset(self):\n '''\n reset - dataframe is left alone, but all other internal tracking is reset so system can run a new test\n :return:\n '''\n print \"TODO: reset still needs to be implemented\"\n pass\n\n\n def open_trade(self, index, direction):\n '''\n\n :param index: index into the dataframe.\n :param direction: direction of the trade (CASH, LONG, or SHORT)\n :return: None\n '''\n\n # Make sure index is in a valid range\n if index < 0 or index > len(self._df[self._column]):\n print \"open_trade error! index is out of bounds (%d)\\n\" %index\n return False\n\n openprice = self._df.ix[index][self._column]\n spread = 0.0\n timestamp = self._df.ix[index]['Date']\n self._tt.OpenTrade(self._ticker, openprice=openprice, spread=spread, direction=direction, timestamp=timestamp)\n\n return True\n\n def close_trade(self, index):\n\n # Make sure index is in a valid range\n if index < 0 or index > len(self._df[self._column]):\n print \"close_trade error! index is out of bounds (%d)\\n\" %index\n return False\n\n closeprice = self._df.ix[index][self._column]\n timestamp = self._df.ix[index]['Date']\n self._tt.CloseTrade(closeprice=closeprice, timestamp=timestamp, direction=self.CASH)\n\n return True\n\n def select_bootstrap(self, selection):\n '''\n set_bootstrap\n\n Set the bootstrap to be used for all subsequent queries. This can be updated at any time to get information\n relevant to the specified bootstrap.\n\n :return:\n '''\n\n if selection == self.BOOTSTRAP_TTE:\n self._bs = TTEBootstrap.TTEBootstrap()\n elif selection == self.BOOTSTRAP_MONTE_CARLO:\n self._bs = MonteCarloBootstrap.MonteCarloBootstrap()\n elif selection == self.BOOTSTRAP_WHITE:\n self._bs = WhiteBootstrap.WhiteBootstrap()\n else:\n print \"select_bootstrap error! selection was invaled (%d)\\n\" %(selection)\n print \"Valid selections are the following: \\n\"\n print \" BOOTSTRAP_TTE, BOOTSTRAP_MONTE_CARLO, BOOTSTRAP_WHITE\\n\\n\"\n return False\n\n return True\n\n def get_pvalue(self, iterations=5000):\n\n # Calculate the total return based on what has been tracked in the trade tracker\n rule_percent_return = self._tt.GetPercentReturn()\n\n # Initialize the test\n self._bs.init_test(self._df, self._column, num_iterations=iterations)\n # Determine what the p-value is for this bootstrap method\n pvalue = self._bs.has_predictive_power(rule_percent_return)\n\n return pvalue\n\n def get_trade_stats(self):\n\n return self._tt.GetTradeStatsStr()\n\n def print_trade_stats(self):\n\n print \"\\n\", self._tt.GetTradeStatsStr()\n pass\n\n def print_trade_history(self):\n self._tt.PrintHistory()\n pass\n\n def plot_pdf(self):\n '''\n plot_pdf\n\n # Display a plot showing the probability density function of returns calculated.\n :return:\n '''\n self._bs.plot_histogram()\n pass\n\n def plot_trades_equity(self):\n '''\n plot_trades_equity\n\n Generate a plot that shows the trades and the equity curve for the given dataframe\n\n :return:\n '''\n\n #print len(self.pairtimestmps), len(self.pairhistory), len(self.visualRewardHistory)\n\n pyplot.figure(1)\n #pyplot.subplot(211)\n\n pyplot.plot(self._df[self._column])\n #pyplot.subplot(212)\n #pyplot.plot(self.visualRewardHistory)\n #pyplot.subplot(313)\n #pyplot.plot(self.visualTradeHistory)\n #x1,x2,y1,y2 = pyplot.axis()\n #pyplot.axis((x1,x2,(y1-0.25), (y2+0.25)))\n\n pyplot.xticks( rotation= 45 )\n\n pyplot.show()\n pass\n\n def plot_all(self, title=None):\n\n #pyplot.xlabel('Smarts')\n #pyplot.ylabel('Probability')\n\n pyplot.figure(1)\n\n pyplot.subplot(311)\n pyplot.title(title)\n sample_means = self._bs.get_histogram_data()\n pyplot.hist(sample_means, bins=20)\n pyplot.grid(True)\n\n pyplot.subplot(312)\n pyplot.plot(self._df[self._column])\n\n pyplot.subplot(313)\n dates = self._df['Date'].tolist()\n x = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in dates]\n pyplot.plot(self._df['Position'])\n #pyplot.plot(x, self._df['Position'])\n #pyplot.gcf().autofmt_xdate()\n pyplot.xticks( rotation= 45 )\n x1,x2,y1,y2 = pyplot.axis()\n pyplot.axis((x1,x2,(y1-0.25), (y2+0.25)))\n\n pyplot.show()\n pass\n\n# --------------------------------------------------------------------------------------------------------------------\n# Test functions\n\n\n# --------------------------------------------------------------------------------------------------------------------\n# Default function when the file is run\n\nif __name__ == \"__main__\":\n # Functions to run if this file is executed\n print \"Run default function for \", __file__\n\n\n" }, { "alpha_fraction": 0.546419084072113, "alphanum_fraction": 0.5769230723381042, "avg_line_length": 22.0510196685791, "blob_id": "00d87be2d23d3b16ff435afbac215d2433804adb", "content_id": "4e3d09641e166e351e289864c3f78116744b8df4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2262, "license_type": "no_license", "max_line_length": 118, "num_lines": 98, "path": "/TTEPaperEx1.py", "repo_name": "trineary/TradeTestingEngine", "src_encoding": "UTF-8", "text": "# --------------------------------------------------------------------------------------------------------------------\n#\n# Patrick Neary\n# Date: 12/14/2016\n#\n# Fin 5350 / Dr. Tyler J. Brough\n# Trade Testing Engine:\n#\n# TTEPaperEx1.py\n#\n# This file shows illustrates an example of trading rules that are active during a trend that, while provfitable,\n# fails to reject the null hypothesis.\n#\n# --------------------------------------------------------------------------------------------------------------------\n\n\n# Import standard packages\n\n# Import my classes\nfrom pytte.tte import TTE\n\n\ndef TestWhiteRealityCheck(tte, df):\n print \"White Bootstrap\"\n tte.select_bootstrap(tte.BOOTSTRAP_WHITE)\n pval = tte.get_pvalue(iterations=5000)\n print \"pval:\", pval\n tte.plot_pdf()\n print tte.get_trade_stats()\n tte.plot_trades_equity()\n\n pass\n\n\ndef TestMonteCarloBootstrap(tte, df):\n print \"Monte Carlo Bootstrap\"\n tte.select_bootstrap(tte.BOOTSTRAP_MONTE_CARLO)\n pval = tte.get_pvalue(iterations=5000)\n print \"pval:\", pval\n tte.plot_pdf()\n print tte.get_trade_stats()\n #tte.plot_trades_equity()\n tte.print_trade_history()\n\n pass\n\n\ndef TestTTEBootstrap(tte, df):\n print \"TTE Bootstrap\"\n tte.select_bootstrap(tte.BOOTSTRAP_TTE)\n pval = tte.get_pvalue(iterations=5000)\n print \"pval:\", pval, \"\\n\"\n tte.plot_pdf()\n tte.plot_trades_equity()\n tte.print_trade_history()\n tte.print_trade_stats()\n\n pass\n\n\nif __name__ == \"__main__\":\n # Functions to run if this file is executed\n print \"Run default function for \", __file__\n\n equity = \"DIA\"\n startDate = '2016-02-12'\n endDate = '2016-04-20'\n\n tte = TTE()\n df = tte.get_hist_data(equity, startDate, endDate)\n\n # Trade 1\n tte.open_trade(0, tte.LONG)\n tte.close_trade(5)\n\n # Trade 2\n tte.open_trade(10, tte.LONG)\n tte.close_trade(15)\n\n # Trade 3\n tte.open_trade(10, tte.LONG)\n tte.close_trade(20)\n\n # Trade 4\n #tte.open_trade(20, tte.LONG)\n #tte.close_trade(25)\n\n # Trade 5\n #tte.open_trade(30, tte.LONG)\n #tte.close_trade(35)\n\n # Trade 6\n #tte.open_trade(40, tte.LONG)\n #tte.close_trade(45)\n\n #TestWhiteRealityCheck(tte, df)\n #TestMonteCarloBootstrap(tte, df)\n TestTTEBootstrap(tte, df)\n\n\n\n" }, { "alpha_fraction": 0.7200000286102295, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 21, "blob_id": "c79b523143628d7090319be8fab18ac80a294840", "content_id": "92c87d7f2283232fded4fc06ad368a736feba4df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25, "license_type": "no_license", "max_line_length": 21, "num_lines": 1, "path": "/__init__.py", "repo_name": "trineary/TradeTestingEngine", "src_encoding": "UTF-8", "text": "\n\nfrom pytte import tte\n\n" } ]
12
PuppyCode0723/IMDB-crawler
https://github.com/PuppyCode0723/IMDB-crawler
18a7f8e2252a188a052b0523e0b219eae1c139e0
0498d30c92b50d0800099fc2abf8e98a976057f2
93fa4f958ae2b0de3171509aa1e4adb2af66b4f8
refs/heads/master
2021-07-18T05:06:18.508695
2021-03-26T08:47:28
2021-03-26T08:47:28
123,303,104
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.41761553287506104, "alphanum_fraction": 0.4313462972640991, "avg_line_length": 40.45138931274414, "blob_id": "0cfcf9161649cd58deab4834263a2a177ec39701", "content_id": "beabf84b08f4b82934120dfcc72bd2e9d61f7f53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6538, "license_type": "no_license", "max_line_length": 164, "num_lines": 144, "path": "/IMDB crawler.py", "repo_name": "PuppyCode0723/IMDB-crawler", "src_encoding": "UTF-8", "text": "#IMDB crawler\nimport requests\nimport nltk\nfrom nltk import RegexpParser\nfrom nltk.corpus import treebank\nfrom nltk.corpus import sentiwordnet as swn\nfrom lxml import html\nfrom bs4 import BeautifulSoup\nfrom time import sleep \nimport sqlite3\n#遇到亂碼可以用join函數存取\ncon = sqlite3.connect('imdb.sqlite')\nsql = 'insert into movie_comments_rating(film_name,author,score) values(?,?,?)'\ncur = con.cursor()\n\n\n\n_URL = requests.get('http://www.imdb.com/chart/top?sort=us,desc&mode=simple&page=1')\ntree = html.fromstring(_URL.text)\nlinkURL = tree.xpath(\"//tbody[@class='lister-list']//tr//td[@class='titleColumn']/a/@href\")\nheadtitle = tree.xpath(\"//tbody[@class='lister-list']//tr//td[@class='titleColumn']/a/text()\") #250部電影\nyearForEachMovie = tree.xpath(\"//div[@class = 'lister'] // tbody[@class = 'lister-list']//tr//td[@class = 'titleColumn']//span//text()\")\n#儲存超連結網址,內容為要進入每個排名電影的超連結\nURL_List = []\n\n\n\n#用來拼接到每個網頁網址的list\nURL_To_EachMovie = []\n#儲存每個評論\nEach_Comments = []\n#儲存每個評論給的分數\nEach_Rate = []\n#儲存每個圖片的網址\n_Score = []\n\n#存進資料庫\nlistscore = []\nheadtitle_list = []\ncomment_author_list = []\n#存進資料庫\n\n\n# 抓...前20個排名高的電影(最近)\ncnt = 1\nfor i in linkURL:\n page = 1 #記錄換頁 IMDB裡評論的下一頁是前一頁*10\n URL_List.append(i)\n #print(URL_List)\n temp = URL_List.pop()\n \n #做拼接而且進入該網頁,因為進入每個評論的attributes都是同一個 \"reviews?ref_=tt_ov_rt\" 所以直接用\n URL_Link_To_Comments_array = temp.split('/?') #結果 /title/tt2119532 \n URL_Link_To_Comments = URL_Link_To_Comments_array.pop(0)\n #進入評論的網頁\n Link_To_Comments = requests.get('http://www.imdb.com' + URL_Link_To_Comments + \"/reviews?ref_=tt_ov_rt\") \n tree2 = html.fromstring(Link_To_Comments.text)\n #print(tree2.text)\n linkURL2 = tree2.xpath(\"//div[@id = 'tn15content']//p/text()\")\n #linkURL2 = tree2.xpath('//*[@id=\"tn15content\"]//p/text()')\n #join\n # str.join(iterable)\t回傳將 str 連結 iterable 各元素的字串\n status = True #判斷有沒有到最後一頁\n while(status == True): \n tree3 = html.fromstring(Link_To_Comments.text)\n author = tree3.xpath(\"//div[@id = 'tn15content'] // div // a[2] // text()\") #print 10筆作者資料 \n for j in range(0,len(author)):\n comment_author_list.append(author.pop(0)) #儲存作者名字 資料庫~~~~~~~~~~~~~~\n #print(comment_author_list) \n \n \n #---------------------------------評分處理------------------------------------------- \n soup = BeautifulSoup(Link_To_Comments.text) \n for j in soup.findAll('div' , id = 'tn15content'): \n for k in j.findAll('div'): \n # --------------------------每段評論的標題---------------------------------\n if(len(k.select('h2')) == 1): \n _head = k.select('h2')\n _Stringhead = (str)(_head[0])\n _Stringhead = _Stringhead.replace('<h2>','')\n _Stringhead = _Stringhead.replace('</h2>','')\n #print(_Stringhead) #印出標題 \n \n # -----------------------------------------------------------------------\n \n s = k.select('img')\n if(len(s)): #判斷是否為空陣列 ==> 裡面為有\n if(len(s) == 2):#代表該作者有給評分\n ppp = s[1]['alt'].split(\"/\") \n aaaa = ppp[0] #fsadfsdfsdfasdfsdfasdfsd\n listscore.append(aaaa) \n #print(aaaa) \n else: #代表該作者沒有給評分 讓list為null\n listscore.append(\"NULL\")\n #print(\"----------------------------NULL---------------------------------\") \n #print(listscore) #資料庫~~~~~~~~~~~~~~~~~~~~~~~~~~\n \n \n # ---------------------------------查詢有無下頁(評論)------------------------------------------\n for k in j.findAll('tr'): \n for q in k.findAll('td' , nowrap = '1'): \n isNext = k.select('img')\n if(len(isNext) == 2): #中間頁數判斷\n if(isNext[1]['alt'] == '[Next]'): #有下一頁就做下一頁 \n Link_To_Comments = requests.get('http://www.imdb.com'+URL_Link_To_Comments+'/reviews?start='+(str)(page*10)) \n #print(\"OKOK\")\n #print(page)\n break\n #http://www.imdb.com/title/tt2119532/reviews?start=10 第2頁 \n else:\n #print(\"Wrong1\")\n status = False \n elif(len(isNext) == 1): #判斷最後一頁跟第一頁\n if(isNext[0]['alt'] == '[Prev]'):\n #print(\"Wrong2\")\n status = False \n elif(isNext[0]['alt'] == '[Next]'): #第一頁 有下一頁\n #print(\"OKOK\")\n #print(page)\n Link_To_Comments = requests.get('http://www.imdb.com'+URL_Link_To_Comments+'/reviews?start='+(str)(page*10)) \n break\n page += 1\n \n #--------------------------------------------------------------------------------------- \n \n # 換電影評論\n cnt+=1 \n if(cnt <= 100):\n print(comment_author_list) \n print(listscore)\n ggg = headtitle.pop(0) \n print(ggg)\n print(\"=================================\")\n for length in range(0,len(comment_author_list)): \n ccc = comment_author_list.pop(0)\n ddd = listscore.pop(0)\n #print(ccc)\n #print(ddd)\n ret = [ggg,ccc,ddd]\n cur.execute(sql,ret) \n else:\n break\ncon.commit()\ncon.close() " }, { "alpha_fraction": 0.76106196641922, "alphanum_fraction": 0.769911527633667, "avg_line_length": 21.600000381469727, "blob_id": "fc2a3f1a9c77bf2a7ac6d517864402945cc85780", "content_id": "f91ffabc015dc6d04cb75b9ffc8310f2704e6b8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 167, "license_type": "no_license", "max_line_length": 57, "num_lines": 5, "path": "/README.md", "repo_name": "PuppyCode0723/IMDB-crawler", "src_encoding": "UTF-8", "text": "# IMDB crawler\n## 簡介:\n> 使用 request、lxm、beautifulsoup、sqlite3套件進行IMDB網站的抓取並存入資料庫\n## 運行方式\n> python IMDB crawler.py\n" } ]
2
xiaohan2012/random_steiner_tree
https://github.com/xiaohan2012/random_steiner_tree
0533ee04543fae14b210cf36e692a0b62f2bea08
dc976f2b11b197cf19b90ce8321444979dc1141c
7962bd77edfa98e56d06693b2777c673f743bc20
refs/heads/master
2021-07-24T05:54:05.861068
2018-06-04T08:30:08
2018-06-04T08:30:08
114,779,249
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7245762944221497, "alphanum_fraction": 0.7330508232116699, "avg_line_length": 15.857142448425293, "blob_id": "6409ce31b1971849cc5ea1496ef5e164500d66bd", "content_id": "4980245827e6a89207710ce1393947efb521c56e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 236, "license_type": "no_license", "max_line_length": 71, "num_lines": 14, "path": "/README.md", "repo_name": "xiaohan2012/random_steiner_tree", "src_encoding": "UTF-8", "text": "# random_steiner_tree\nRandom Steiner tree generation using Boost Graph with Python interface.\n\n# dependency\n\n- g++\n- boost\n- python3-dev\n\nIn Ubuntu, run `sudo apt-get install g++ libboost-all-dev python3-dev`\n\n# todo\n\n- put it in conda\n" }, { "alpha_fraction": 0.5442253351211548, "alphanum_fraction": 0.5825352072715759, "avg_line_length": 23.3150691986084, "blob_id": "bdb77cdb04e56a09ff22b4d2a6fd20ff3b67753c", "content_id": "5405b8717a5b4ee58a512b25b484430df1c60439", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1775, "license_type": "no_license", "max_line_length": 85, "num_lines": 73, "path": "/test_loop_erased_weighted.py", "repo_name": "xiaohan2012/random_steiner_tree", "src_encoding": "UTF-8", "text": "import pytest\nimport numpy as np\nfrom graph_tool import Graph\nfrom random_steiner_tree import random_steiner_tree\nfrom random_steiner_tree.util import from_gt\nfrom collections import Counter\n\nEPSILON = 1e-10\n\n\ndef graph():\n \"\"\" \n 0 (root)\n / \\\n 1 2\n \\ /\n 3 (X)\n \"\"\"\n g = Graph()\n g.add_vertex(4)\n g.add_edge(0, 1)\n g.add_edge(0, 2)\n g.add_edge(1, 3)\n g.add_edge(2, 3)\n return g\n\n\ncase1 = {\n (0, 1): 1,\n (0, 2): EPSILON,\n (1, 3): 1,\n (2, 3): EPSILON\n}\n\ncase2 = {\n (0, 1): 1,\n (0, 2): 2,\n (1, 3): 1,\n (2, 3): 1\n}\n\n\ndef build_gi_by_weights(edge2weight):\n g = graph()\n weights = g.new_edge_property('float')\n for (u, v), w in edge2weight.items():\n weights[g.edge(u, v)] = w\n \n return from_gt(g, weights=weights)\n \n\[email protected](\"edge2weight,expected_fraction\", [(case1, 0), (case2, 4/3)])\[email protected](\"sampling_method\", [\"loop_erased\"])\ndef test_distribution(edge2weight, expected_fraction, sampling_method):\n gi = build_gi_by_weights(edge2weight)\n root = 0\n X = [3]\n n = 100000\n steiner_node_freq = Counter()\n for i in range(n):\n edges = random_steiner_tree(gi, X, root, method=sampling_method, seed=None)\n steiner_nodes = {u for e in edges for u in e} - {root} - set(X)\n for u in steiner_nodes:\n steiner_node_freq[u] += 1\n\n np.testing.assert_almost_equal(steiner_node_freq[2] / steiner_node_freq[1],\n expected_fraction, decimal=2)\n\n # if the following assertion fails, you can buy a lottery\n # assert steiner_node_freq[2] == 0\n # assert steiner_node_freq[1] == n\n\n # np.testing.assert_almost_equal(steiner_node_freq[2] / steiner_node_freq[1], 0)\n" }, { "alpha_fraction": 0.5971978902816772, "alphanum_fraction": 0.6199649572372437, "avg_line_length": 30.72222137451172, "blob_id": "6eaf6dc4a4fe0da5d0f909e71bfc978827c033ac", "content_id": "611c0ee999fe33a0f590e1fca3e912a3874bbef0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 571, "license_type": "no_license", "max_line_length": 85, "num_lines": 18, "path": "/random_steiner_tree/__init__.py", "repo_name": "xiaohan2012/random_steiner_tree", "src_encoding": "UTF-8", "text": "import random\nfrom .interface import loop_erased, cut_based\n\n\ndef random_steiner_tree(gi, X, root, method=\"loop_erased\", seed=None, verbose=False):\n assert method in {\"loop_erased\", \"closure\", \"cut\"}\n # C++ is strict with type...\n X = list(map(int, X))\n\n root = int(root)\n if seed is None:\n seed = random.randint(0, 2147483647) # int32\n if method == \"loop_erased\":\n return loop_erased(gi, X, root, seed, verbose)\n elif method == \"cut\":\n return cut_based(gi, X, root, seed, verbose)\n else:\n raise NotImplemented('yet')\n" }, { "alpha_fraction": 0.7954545617103577, "alphanum_fraction": 0.7954545617103577, "avg_line_length": 17.85714340209961, "blob_id": "c9b8be1ad4e7f058e02a8d197e8377a7914caaf7", "content_id": "afb99604765405213df7162d6f6198defdaaeed8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 132, "license_type": "no_license", "max_line_length": 71, "num_lines": 7, "path": "/random_steiner_tree/README.md", "repo_name": "xiaohan2012/random_steiner_tree", "src_encoding": "UTF-8", "text": "# random_steiner_tree\nRandom Steiner tree generation using Boost Graph with Python interface.\n\n\n# todo\n\n- test solution feasibility\n" }, { "alpha_fraction": 0.5886843204498291, "alphanum_fraction": 0.60125732421875, "avg_line_length": 27.18987274169922, "blob_id": "2801f1244687eed18e3cd3736bc2afd6aa67aae4", "content_id": "9c76d1c65508cad0059286952e8ad5d17ac5bb17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2227, "license_type": "no_license", "max_line_length": 83, "num_lines": 79, "path": "/distribution.py", "repo_name": "xiaohan2012/random_steiner_tree", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\nimport networkx as nx\nimport numpy as np\nimport random\nimport pandas as pd\nfrom scipy.spatial.distance import cosine\nfrom tqdm import tqdm\nfrom collections import Counter\nfrom random_steiner_tree import random_steiner_tree\nfrom random_steiner_tree.util import from_nx\nfrom joblib import Parallel, delayed\n\n# random.seed(1)\n# np.random.seed(1)\n# nx.florentine_families_graph().number_of_nodes()\n# nx.davis_southern_women_graph().number_of_nodes()\n\n\n# g = nx.karate_club_graph()\ng = nx.florentine_families_graph()\ng = nx.convert_node_labels_to_integers(g)\n\n# add some random edges\nn_rand_edges = 5\nfor i in range(n_rand_edges):\n while True:\n u, v = map(int, np.random.permutation(g.nodes())[:2])\n if not g.has_edge(u, v):\n g.add_edge(u, v)\n break\n # u, v = random.choice(g.nodes()), random.choice(g.nodes())\n\nprint(g.number_of_nodes(), g.number_of_edges())\nfor u, v in g.edges_iter():\n g[u][v]['weight'] = 1\n\n\ndef one_run(g, k, N):\n gi = from_nx(g)\n X = np.random.permutation(g.number_of_nodes())[:k]\n root = random.choice(g.nodes())\n # tree_sizes = [len(random_steiner_tree(gi, X, root))\n # for i in tqdm(range(N))]\n\n def sort_edges(edges):\n return tuple(sorted(edges))\n\n tree_freq = Counter()\n # for i in tqdm(range(N)):\n for i in range(N):\n edges = sort_edges(random_steiner_tree(gi, X, root))\n tree_freq[edges] += 1\n\n def tree_proba(edges):\n prod = np.product([g.degree(u) for u, v in edges])\n return 1 / prod\n\n probas = np.array([tree_proba(t)\n for t in tree_freq.keys()])\n # for t in tqdm(tree_freq.keys(),\n # total=len(tree_freq.keys()))])\n probas /= probas.sum()\n actual_probas = np.array(list(tree_freq.values())) / N\n\n # print('using {} samples on {} terminals, the cosine similarity is {}'.format(\n # N, k, 1-cosine(probas, actual_probas)))\n\n return 1-cosine(probas, actual_probas)\n\nk = 5\nN = 10000000\n# N = 10000\nn_rounds = 800\nsims = Parallel(n_jobs=-1)(delayed(one_run)(g, k, N)\n for i in range(n_rounds))\n\n\nprint(pd.Series(sims).describe())\n" }, { "alpha_fraction": 0.6316537261009216, "alphanum_fraction": 0.633979320526123, "avg_line_length": 31.79660987854004, "blob_id": "17202fe17e01ed9486bf6ecf9b5a1eec61304ba9", "content_id": "3509aba2b1c8e6320bf2691e63b9f3899b022ed6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7740, "license_type": "no_license", "max_line_length": 122, "num_lines": 236, "path": "/random_steiner_tree/interface.cpp", "repo_name": "xiaohan2012/random_steiner_tree", "src_encoding": "UTF-8", "text": "#include <boost/foreach.hpp>\n\n#include <boost/python.hpp>\n#include <boost/python/list.hpp>\n#include <boost/python/extract.hpp>\n\n#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <random>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/random_number_generator.hpp>\n\n#include \"loop_erased.cpp\"\n#include \"cut.cpp\"\n\n\n// Define a directed graph type that associates a weight with each\n// edge. We store the weights using internal properties as described\n// in BGL.\ntypedef boost::property<boost::edge_weight_t, double> EdgeProperty;\ntypedef boost::adjacency_list<boost::listS,\n boost::vecS,\n boost::directedS,\n boost::no_property,\n EdgeProperty> Graph;\ntypedef boost::graph_traits<Graph>::vertex_descriptor Vertex;\ntypedef boost::graph_traits<Graph>::edge_descriptor Edge;\n\nGraph build_graph(int N, boost::python::list edge_with_weights){\n long l = len(edge_with_weights);\n Graph g(N);\n for(int i=0; i<l; i++){\n boost::python::list edge = (boost::python::list)edge_with_weights[i];\n int source = boost::python::extract<int>(edge[0]);\n int target = boost::python::extract<int>(edge[1]);\n double weight = boost::python::extract<double>(edge[2]);\n\n add_edge(source, target, weight, g);\n }\n return g;\n}\n\nint num_vertices(Graph &g){\n return boost::num_vertices(g);\n}\n\nvoid isolate_vertex(Graph &g, int v){\n /*\n strange lessons:\n - if using remove_edge(edge, g), it might throw segmentation fault\n - using remove_edge(u, v, g) then works\n */\n // std::cout << \"NEW, CPP: remove node \" << v << std::endl;\n \n Graph::out_edge_iterator eit, eend;\n std::tie(eit, eend) = boost::out_edges((Vertex) v, g);\n std::vector<int> nbrs; // collect the edges\n std::for_each(eit, eend,\n \t\t[&g, &nbrs](Edge e)\n \t\t{\n \t\t // boost::remove_edge(e, g);\n \t\t nbrs.push_back((int)boost::target(e, g));\n \t\t});\n // std::cout << \"CPP: num. edges to remove \" << nbrs.size() << std::endl;\n for(auto n: nbrs) {\n boost::remove_edge(v, n, g);\n boost::remove_edge(n, v, g);\n }\n}\n\nvoid isolate_vertex_old(Graph &g, int v){\n std::cout << \"CPP: remove node \" << v << std::endl;\n \n Graph::out_edge_iterator eit, eend;\n std::tie(eit, eend) = boost::out_edges((Vertex) v, g);\n std::vector<Edge> edges_to_remove; // collect the edges\n std::for_each(eit, eend,\n \t\t[&g, &edges_to_remove](Edge e)\n \t\t{\n \t\t // boost::remove_edge(e, g);\n \t\t edges_to_remove.push_back(e);\n \t\t});\n std::cout << \"CPP: num. edges to remove \" << edges_to_remove.size() << std::endl;\n for(auto e: edges_to_remove)\n boost::remove_edge(e, g);\n}\n\n\nboost::python::list reachable_vertices(Graph &g, int pivot){\n // given pivot node, traverse from it using BFS and collect nodes that are traversed\n unsigned int N = num_vertices(g);\n std::vector<Vertex> predecessors (N, boost::graph_traits<Graph>::null_vertex());\n\n // predecessors.fill(-1);\n boost::breadth_first_search(g, pivot,\n boost::visitor(\n\t\t boost::make_bfs_visitor(\n\t\t\t\t\t boost::record_predecessors(boost::make_iterator_property_map(predecessors.begin(), get(boost::vertex_index, g)),\n\t\t\t\t\t\t\t\t\tboost::on_tree_edge{})\n\t\t\t\t\t )));\n boost::python::list nodes;\n for(unsigned int i=0; i<N; i++){\n if(pivot == (int)i || predecessors[i] != boost::graph_traits<Graph>::null_vertex()) // visited\n nodes.append((int) i);\n }\n return nodes;\n}\n\nstd::string graph_to_string(Graph &g){\n boost::property_map<Graph, boost::edge_weight_t>::type weights =\n get(boost::edge_weight_t(), g);\n \n // Print the graph (or rather the edges of the graph).\n std::stringstream ss;\n BOOST_FOREACH (Edge e, edges(g))\n {\n ss << \"(\" << boost::source(e, g) << \", \"\n\t << boost::target(e, g) << \")\\t\"\n\t << get(weights, e) << \"\\n\";\n }\n \n return ss.str();;\n}\n\nboost::python::list _edges(Graph &g){\n boost::python::list tuples;\n BOOST_FOREACH (Edge e, edges(g))\n {\n tuples.append(boost::python::make_tuple((int)boost::source(e, g),\n\t\t\t\t\t (int)boost::target(e, g)));\n }\n return tuples;\n}\n\nboost::python::list _vertices(Graph & g){\n boost::python::list nodes;\n std::pair<Graph::vertex_iterator,\n\t Graph::vertex_iterator> vs = vertices(g);\n for(Graph::vertex_iterator it=vs.first; it<vs.second; it++)\n nodes.append((int)*it);\n return nodes;\n}\n\nboost::python::list loop_erased(Graph & g, boost::python::list terminals, int root, int seed, bool verbose){\n long length = len(terminals);\n std::vector<Vertex> X(length);\n for(long i=0; i<length; i++){\n int node_id = boost::python::extract<int>(terminals[i]);\n X[i] = (Vertex)node_id;\n } \n \n std::vector<Vertex> predmap (num_vertices(g), boost::graph_traits<Graph>::null_vertex());\n std::vector<boost::default_color_type> colormap(num_vertices(g));\n boost::property_map<Graph, boost::edge_weight_t>::type weightmap = get(boost::edge_weight_t(), g);\n\n std::mt19937 prng { seed }; // as simple as this, fanculo!!!\n\n loop_erased_random_steiner_tree(g,\n\t\t\t\t X,\n\t\t\t\t prng,\n\t\t\t\t (Vertex) root,\n\t\t\t\t boost::make_iterator_property_map(predmap.begin(), get(boost::vertex_index, g)),\n\t\t\t\t weightmap,\n\t\t\t\t boost::make_iterator_property_map(colormap.begin(), get(boost::vertex_index, g)),\n\t\t\t\t verbose);\n \n boost::python::list l;\n typedef boost::graph_traits<Graph>::vertex_iterator vertex_iter;\n std::pair<vertex_iter, vertex_iter> vp;\n for (vp = boost::vertices(g); vp.first != vp.second; ++vp.first){\n Vertex target= (*vp.first);\n // store visited edges\n if(predmap[target] != boost::graph_traits<Graph>::null_vertex())\n l.append(boost::python::make_tuple((int)predmap[target], target));\n }\n return l; \n}\n\n\nboost::python::list cut_based(Graph & g, boost::python::list terminals, int root, int seed, bool verbose){\n long length = len(terminals);\n std::vector<Vertex> X(length);\n for(long i=0; i<length; i++){\n int node_id = boost::python::extract<int>(terminals[i]);\n X[i] = (Vertex)node_id;\n } \n \n std::vector<Vertex> predmap (num_vertices(g), boost::graph_traits<Graph>::null_vertex());\n std::vector<boost::default_color_type> colormap(num_vertices(g));\n boost::property_map<Graph, boost::edge_weight_t>::type weightmap = get(boost::edge_weight_t(), g);\n\n std::mt19937 prng { seed }; // as simple as this, fanculo!!!\n\n cut_based_random_steiner_tree(g,\n\t\t\t\tX,\n\t\t\t\tprng,\n\t\t\t\t(Vertex) root,\n\t\t\t\tboost::make_iterator_property_map(predmap.begin(), get(boost::vertex_index, g)),\n\t\t\t\tweightmap,\n\t\t\t\tboost::make_iterator_property_map(colormap.begin(), get(boost::vertex_index, g)),\n\t\t\t\tverbose);\n \n boost::python::list l;\n typedef boost::graph_traits<Graph>::vertex_iterator vertex_iter;\n std::pair<vertex_iter, vertex_iter> vp;\n for (vp = boost::vertices(g); vp.first != vp.second; ++vp.first){\n Vertex target= (*vp.first);\n // store visited edges\n if(predmap[target] != boost::graph_traits<Graph>::null_vertex())\n l.append(boost::python::make_tuple((int)predmap[target], target));\n }\n return l; \n}\n\n\nBOOST_PYTHON_MODULE(interface) {\n using namespace boost::python;\n\n class_<Graph>(\"Graph\");\n def(\"build_graph\", build_graph);\n def(\"graph_to_string\", graph_to_string);\n def(\"num_vertices\", num_vertices);\n def(\"isolate_vertex\", isolate_vertex);\n def(\"reachable_vertices\", reachable_vertices);\n def(\"vertices\", _vertices);\n def(\"edges\", _edges);\n def(\"loop_erased\", loop_erased);\n def(\"cut_based\", cut_based); \n};\n" }, { "alpha_fraction": 0.6598626971244812, "alphanum_fraction": 0.6617183089256287, "avg_line_length": 36.6853141784668, "blob_id": "7cbe1acf02e0cd22a24fb90e683226aac8e12bdb", "content_id": "2efe3edbd4c63d23e2225839019f7c7c2c8dc38e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5389, "license_type": "no_license", "max_line_length": 122, "num_lines": 143, "path": "/random_steiner_tree/cut.cpp", "repo_name": "xiaohan2012/random_steiner_tree", "src_encoding": "UTF-8", "text": "// \"sampling&cut\" algorithm for random steiner tree sampling\n// adapted from http://www.boost.org/doc/libs/1_65_1/boost/graph/random_spanning_tree.hpp\n\n// Authors: Han Xiao\n\n\n#ifndef BOOST_GRAPH_CUT_RANDOM_STEINER_TREE_HPP\n#define BOOST_GRAPH_CUT_RANDOM_STEINER_TREE_HPP\n\n#include <iostream>\n#include <vector>\n\n#include <boost/assert.hpp>\n#include <boost/graph/loop_erased_random_walk.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/config.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/named_function_params.hpp>\n\n#include <boost/graph/random_spanning_tree.hpp>\n\n#include \"loop_erased.cpp\"\n\nnamespace boost {\n\n namespace detail {\n // Use Wilson's algorithm (based on loop-free random walks) to generate a\n // random spanning tree. The distribution of edges used is controlled by\n // the next_edge() function, so this version allows either weighted or\n // unweighted selection of trees.\n // Algorithm is from http://en.wikipedia.org/wiki/Uniform_spanning_tree\n \n template <typename Graph, typename PredMap, typename ColorMap, typename NextEdge>\n void cut_based_random_steiner_tree_internal(const Graph& g,\n\t\t\t\t\t\tstd::vector<typename graph_traits<Graph>::vertex_descriptor> X, \n\t\t\t\t\t\ttypename graph_traits<Graph>::vertex_descriptor s, \n\t\t\t\t\t\tPredMap pred,\n\t\t\t\t\t\tColorMap color,\n\t\t\t\t\t\tNextEdge next_edge,\n\t\t\t\t\t\tbool verbose){\n typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n // 1. retrieve reachable node set starting from s\n\n std::vector<Vertex> reachable;\n unsigned int N = num_vertices(g);\n std::vector<Vertex> predecessors (N, boost::graph_traits<Graph>::null_vertex());\n\n boost::breadth_first_search(g, s,\n\t\t\t\t boost::visitor(\n\t\t\t\t\t\t boost::make_bfs_visitor(\n\t\t\t\t\t\t\t\t\t boost::record_predecessors(boost::make_iterator_property_map(predecessors.begin(), get(boost::vertex_index, g)),\n\t\t\t\t\t\t\t\t\t\t\t\t boost::on_tree_edge{})\n\t\t\t\t\t\t\t\t\t )));\n for(unsigned int i=0; i<N; i++){\n\tif((int)s == (int)i || predecessors[i] != boost::graph_traits<Graph>::null_vertex()) // visited\n\t reachable.push_back((Vertex) i);\n }\n\n // 2. get the spanning tree on the reachable set\n loop_erased_random_steiner_tree_internal(g, reachable, s, pred, color, next_edge, verbose);\n\n // random_spanning_tree_internal(g, s, pred, color, next_edge);\n // std::cout << \"spanning tree built\" << std::endl;\n\n // 3. cut the tree \n // traverse from terminals to the root and mark visited nodes\n std::vector<bool> visited(num_vertices(g), false);\n visited[s] = true;\n\n for(auto x: X){\n\t// std::cout << \"x=\" << x << std::endl;\n\tvisited[x] = true;\n\twhile(get(pred, x) != graph_traits<Graph>::null_vertex() // not root\n\t && !visited[get(pred, x)]){\n\t visited[get(pred, x)] = true;\n\t x = get(pred, x);\n\t}\n }\n\n // std::cout << \"traversing done\" << std::endl;\n // remove unvisited nodes\n for(unsigned int v=0; v<num_vertices(g); v++){\n // BGL_FORALL_VERTICES_T(v, g, Graph) {\n\tif(!visited[v])\n\t put(pred, v, graph_traits<Graph>::null_vertex());\n }\n // std::cout << \"masking done\" << std::endl;\n }\n }\n\n template <typename Graph, typename Gen, typename PredMap, typename ColorMap>\n void cut_based_random_steiner_tree(const Graph& g,\n\t\t\t\t std::vector<typename graph_traits<Graph>::vertex_descriptor> X,\n\t\t\t\t Gen& gen,\n\t\t\t\t typename graph_traits<Graph>::vertex_descriptor root,\n\t\t\t\t PredMap pred,\n\t\t\t\t static_property_map<double>,\n\t\t\t\t ColorMap color,\n\t\t\t\t bool verbose) {\n unweighted_random_out_edge_gen<Graph, Gen> random_oe(gen);\n detail::cut_based_random_steiner_tree_internal(g, X, root, pred, color, random_oe, verbose);\n }\n\n // Compute a weight-distributed spanning tree on a graph.\n template <typename Graph, typename Gen, typename PredMap, typename WeightMap, typename ColorMap>\n void cut_based_random_steiner_tree(const Graph& g,\n\t\t\t\t std::vector<typename graph_traits<Graph>::vertex_descriptor> X,\n\t\t\t\t Gen& gen,\n\t\t\t\t typename graph_traits<Graph>::vertex_descriptor root,\n\t\t\t\t PredMap pred,\n\t\t\t\t WeightMap weight,\n\t\t\t\t ColorMap color,\n\t\t\t\t bool verbose) {\n weighted_random_out_edge_gen<Graph, WeightMap, Gen> random_oe(weight, gen);\n detail::cut_based_random_steiner_tree_internal(g, X, root, pred, color, random_oe, verbose);\n }\n\n template <typename Graph, typename Gen, typename P, typename T, typename R>\n void cut_based_random_steiner_tree(const Graph& g,\n\t\t\t\t std::vector<typename graph_traits<Graph>::vertex_descriptor> X,\n\t\t\t\t Gen& gen, const bgl_named_params<P, T, R>& params,\n\t\t\t\t bool verbose) {\n using namespace boost::graph::keywords;\n typedef bgl_named_params<P, T, R> params_type;\n BOOST_GRAPH_DECLARE_CONVERTED_PARAMETERS(params_type, params)\n cut_based_random_steiner_tree(g,\n\t\t\t\t X, \n\t\t\t\t gen,\n\t\t\t\t arg_pack[_root_vertex | *vertices(g).first],\n\t\t\t\t arg_pack[_predecessor_map],\n\t\t\t\t arg_pack[_weight_map | static_property_map<double>(1.)],\n\t\t\t\t boost::detail::make_color_map_from_arg_pack(g, arg_pack),\n\t\t\t\t verbose);\n }\n}\n\n#include <boost/graph/iteration_macros_undef.hpp>\n\n#endif // BOOST_GRAPH_RANDOM_STEINER_TREE_HPP\n" }, { "alpha_fraction": 0.644629716873169, "alphanum_fraction": 0.6458209156990051, "avg_line_length": 37.74615478515625, "blob_id": "39d9fbe09d79e8bc2ccdfda1aa7c6c0f036fe818", "content_id": "5af28e0ff7f8be6f0d594a95d56d791637d18d23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5037, "license_type": "no_license", "max_line_length": 115, "num_lines": 130, "path": "/random_steiner_tree/loop_erased.cpp", "repo_name": "xiaohan2012/random_steiner_tree", "src_encoding": "UTF-8", "text": "// adapted from http://www.boost.org/doc/libs/1_65_1/boost/graph/random_spanning_tree.hpp\n\n// Authors: Han Xiao\n\n\n#ifndef BOOST_GRAPH_LOOP_ERASED_RANDOM_STEINER_TREE_HPP\n#define BOOST_GRAPH_LOOP_ERASED_RANDOM_STEINER_TREE_HPP\n\n#include <vector>\n#include <time.h> \n#include <boost/assert.hpp>\n#include <boost/graph/loop_erased_random_walk.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/config.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/named_function_params.hpp>\n\nnamespace boost {\n\n namespace detail {\n // Use Wilson's algorithm (based on loop-free random walks) to generate a\n // random spanning tree. The distribution of edges used is controlled by\n // the next_edge() function, so this version allows either weighted or\n // unweighted selection of trees.\n // Algorithm is from http://en.wikipedia.org/wiki/Uniform_spanning_tree\n template <typename Graph, typename PredMap, typename ColorMap, typename NextEdge>\n void loop_erased_random_steiner_tree_internal(const Graph& g,\n\t\t\t\t\t\t std::vector<typename graph_traits<Graph>::vertex_descriptor> X, \n\t\t\t\t\t\t typename graph_traits<Graph>::vertex_descriptor s, \n\t\t\t\t\t\t PredMap pred,\n\t\t\t\t\t\t ColorMap color,\n\t\t\t\t\t\t NextEdge next_edge,\n\t\t\t\t\t\t bool verbose) {\n typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n\n BOOST_ASSERT (num_vertices(g) >= 1); // g must also be undirected (or symmetric) and connected\n\n typedef color_traits<typename property_traits<ColorMap>::value_type> color_gen;\n BGL_FORALL_VERTICES_T(v, g, Graph) put(color, v, color_gen::white());\n\n std::vector<vertex_descriptor> path;\n\n put(color, s, color_gen::black());\n put(pred, s, graph_traits<Graph>::null_vertex());\n\n clock_t t;\n\t\n if(verbose){\n\tstd::cout << \"root is \" << (int)s << std::endl;\n }\n for(auto v: X) {\n\tif (verbose)\n\t t = clock();\n\n if (get(color, v) != color_gen::white()) continue;\n loop_erased_random_walk(g, v, next_edge, color, path);\n for (typename std::vector<vertex_descriptor>::const_reverse_iterator i = path.rbegin();\n boost::next(i) !=\n (typename std::vector<vertex_descriptor>::const_reverse_iterator)path.rend();\n ++i) {\n typename std::vector<vertex_descriptor>::const_reverse_iterator j = i;\n ++j;\n BOOST_ASSERT (get(color, *j) == color_gen::gray());\n put(color, *j, color_gen::black());\n put(pred, *j, *i);\n }\n\tif (verbose){\n\t t = clock() - t;\n\t std::cout << \"CPP: connecting node {\" << v << \"} took {\" << (float) t / CLOCKS_PER_SEC << \"} secs\" << std::endl;\n\t}\n }\n if (verbose) {\n\tstd::cout << std::endl;\n }\n }\n }\n\n template <typename Graph, typename Gen, typename PredMap, typename ColorMap>\n void loop_erased_random_steiner_tree(const Graph& g,\n\t\t\t\t std::vector<typename graph_traits<Graph>::vertex_descriptor> X,\n\t\t\t\t Gen& gen,\n\t\t\t\t typename graph_traits<Graph>::vertex_descriptor root,\n\t\t\t\t PredMap pred,\n\t\t\t\t static_property_map<double>,\n\t\t\t\t ColorMap color,\n\t\t\t\t bool verbose) {\n unweighted_random_out_edge_gen<Graph, Gen> random_oe(gen);\n detail::loop_erased_random_steiner_tree_internal(g, X, root, pred, color, random_oe, verbose);\n }\n\n // Compute a weight-distributed spanning tree on a graph.\n template <typename Graph, typename Gen, typename PredMap, typename WeightMap, typename ColorMap>\n void loop_erased_random_steiner_tree(const Graph& g,\n\t\t\t\t std::vector<typename graph_traits<Graph>::vertex_descriptor> X,\n\t\t\t\t Gen& gen,\n\t\t\t\t typename graph_traits<Graph>::vertex_descriptor root,\n\t\t\t\t PredMap pred,\n\t\t\t\t WeightMap weight,\n\t\t\t\t ColorMap color,\n\t\t\t\t bool verbose) {\n weighted_random_out_edge_gen<Graph, WeightMap, Gen> random_oe(weight, gen);\n detail::loop_erased_random_steiner_tree_internal(g, X, root, pred, color, random_oe, verbose);\n }\n\n template <typename Graph, typename Gen, typename P, typename T, typename R>\n void loop_erased_random_steiner_tree(const Graph& g,\n\t\t\t\t std::vector<typename graph_traits<Graph>::vertex_descriptor> X,\n\t\t\t\t Gen& gen, const bgl_named_params<P, T, R>& params,\n\t\t\t\t bool verbose) {\n using namespace boost::graph::keywords;\n typedef bgl_named_params<P, T, R> params_type;\n BOOST_GRAPH_DECLARE_CONVERTED_PARAMETERS(params_type, params)\n loop_erased_random_steiner_tree(g,\n\t\t\t\t X, \n\t\t\t\t gen,\n\t\t\t\t arg_pack[_root_vertex | *vertices(g).first],\n\t\t\t\t arg_pack[_predecessor_map],\n\t\t\t\t arg_pack[_weight_map | static_property_map<double>(1.)],\n\t\t\t\t boost::detail::make_color_map_from_arg_pack(g, arg_pack),\n\t\t\t\t verbose);\n }\n}\n\n#include <boost/graph/iteration_macros_undef.hpp>\n\n#endif // BOOST_GRAPH_RANDOM_STEINER_TREE_HPP\n" }, { "alpha_fraction": 0.6200440526008606, "alphanum_fraction": 0.6387665271759033, "avg_line_length": 30.310344696044922, "blob_id": "fb821df1b15af010c36434c7227e2a791da90b21", "content_id": "7d671c9a42c57de6a4ce97d783ee08c9dcc36dec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 908, "license_type": "no_license", "max_line_length": 62, "num_lines": 29, "path": "/setup.py", "repo_name": "xiaohan2012/random_steiner_tree", "src_encoding": "UTF-8", "text": "# from distutils.core import setup, Extension\nimport os\nfrom setuptools import setup, Extension\n\nos.environ[\"CC\"] = \"g++\"\nos.environ[\"CXX\"] = \"g++\"\n\ncore_module = Extension(\n 'random_steiner_tree/interface',\n include_dirs=['/usr/include/python3.5/'],\n libraries=['boost_python-py35', 'boost_graph'],\n library_dirs=['/usr/lib/x86_64-linux-gnu/'],\n extra_compile_args=['-std=c++11', '-O2', '-Wall'],\n extra_link_args=['-Wl,--export-dynamic'],\n sources=['random_steiner_tree/interface.cpp']\n)\n\nsetup(name='rand_steiner_tree',\n version='0.1',\n description='Random Steiner tree sampling algorithm',\n url='http://github.com/xiaohan2012/random_steiner_tree',\n author='Han Xiao',\n author_email='[email protected]',\n license='MIT',\n packages=['random_steiner_tree'],\n ext_modules=[core_module],\n setup_requires=['pytest-runner'],\n tests_require=['pytest']\n)\n" }, { "alpha_fraction": 0.5473260879516602, "alphanum_fraction": 0.5669664144515991, "avg_line_length": 28.144826889038086, "blob_id": "3cea3bb2121d175a52afbcde30f41c500c370c81", "content_id": "1de9f414bb5c4fb4a9cd5ced34c068ef3913bbcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4226, "license_type": "no_license", "max_line_length": 86, "num_lines": 145, "path": "/test.py", "repo_name": "xiaohan2012/random_steiner_tree", "src_encoding": "UTF-8", "text": "import pytest\nimport random\nimport numpy as np\nimport networkx as nx\nfrom graph_tool import Graph\nfrom random_steiner_tree import random_steiner_tree\nfrom random_steiner_tree.util import (from_nx, from_gt,\n num_vertices,\n isolate_vertex,\n vertices,\n edges,\n reachable_vertices)\n\n\ndef check_feasiblity(tree, root, X):\n X = set(X) | {int(root)}\n # number of components\n ncc = nx.number_connected_components(tree)\n assert ncc == 1, 'number_connected_components: {} != 1'.format(ncc)\n\n nodes = set(tree.nodes())\n assert X.issubset(nodes), 'tree does not contain all X'\n \n # leaves are terminals\n # no extra edges\n for n in tree.nodes_iter():\n if tree.degree(n) == 1:\n assert n in X, 'one leaf does not belong to terminal'\n\n\ndef input_data_nx():\n g = nx.karate_club_graph().to_directed()\n \n for u, v in g.edges_iter():\n g[u][v]['weight'] = 1\n return g, from_nx(g, 'weight'), g.number_of_nodes()\n\n\ndef input_data_gt():\n g_nx = nx.karate_club_graph()\n g = Graph(directed=True)\n g.add_vertex(g_nx.number_of_nodes())\n for u, v in g_nx.edges():\n g.add_edge(u, v)\n g.add_edge(v, u) # the other direction\n\n return g, from_gt(g, None), g.num_vertices()\n\n\[email protected](\"data_type\", [\"gt\", \"nx\"])\[email protected](\"method\", [\"loop_erased\", \"cut\"])\ndef test_feasiblility(data_type, method):\n if data_type == 'nx':\n data = input_data_nx()\n elif data_type == 'gt':\n data = input_data_gt()\n g, gi, N = data\n for i in range(10):\n # try different number of terminals1\n for k in range(2, N+1):\n X = np.random.permutation(N)[:10]\n\n if data_type == 'nx':\n nodes = g.nodes()\n elif data_type == 'gt':\n nodes = list(map(int, g.vertices()))\n\n root = random.choice(nodes)\n tree_edges = random_steiner_tree(gi, X, root, method=method, verbose=True)\n t = nx.Graph()\n t.add_edges_from(tree_edges)\n check_feasiblity(t, root, X)\n\n\[email protected]\ndef line_g():\n g = Graph(directed=True)\n g.add_edge(0, 1)\n g.add_edge(1, 0)\n g.add_edge(1, 2)\n g.add_edge(2, 1)\n return g\n\n\ndef test_edges(line_g):\n gi = from_gt(line_g, None)\n assert set(edges(gi)) == {(0, 1), (1, 0), (1, 2), (2, 1)}\n\n\ndef test_isolate_vertex(line_g):\n gi = from_gt(line_g, None)\n isolate_vertex(gi, 0)\n assert set(edges(gi)) == {(2, 1), (1, 2)}\n\n isolate_vertex(gi, 1)\n assert set(edges(gi)) == set()\n\n \ndef test_isolate_vertex_num_vertices():\n _, gi, _ = input_data_gt()\n prev_N = num_vertices(gi)\n isolate_vertex(gi, 0)\n nodes_with_edges = {u for e in edges(gi) for u in e}\n assert 0 not in nodes_with_edges\n\n assert prev_N == num_vertices(gi)\n isolate_vertex(gi, 1)\n assert prev_N == num_vertices(gi)\n\n\[email protected]\ndef disconnected_line_graph():\n \"\"\"0 -- 1 -- 2 3 -- 4\n \"\"\"\n g = nx.Graph()\n g.add_nodes_from([0, 1, 2, 3, 4])\n g.add_edges_from([(0, 1), (1, 2), (3, 4)])\n g = g.to_directed()\n return from_nx(g)\n\n\ndef test_remove_vertex_node_index(disconnected_line_graph):\n gi = disconnected_line_graph\n isolate_vertex(gi, 0)\n assert set(vertices(gi)) == {0, 1, 2, 3, 4}\n\n assert reachable_vertices(gi, 0) == [0]\n assert reachable_vertices(gi, 1) == [1, 2]\n assert reachable_vertices(gi, 3) == [3, 4]\n\n \[email protected](\"expected, pivot\", [({0, 1, 2}, 1), ({3, 4}, 3)])\ndef test_reachable_vertices(disconnected_line_graph, expected, pivot):\n gi = disconnected_line_graph\n nodes = reachable_vertices(gi, pivot)\n print('num_vertices', num_vertices(gi))\n # 0, 1, 2 remains\n assert set(nodes) == expected\n\n\[email protected](\"method\", ['cut', 'loop_erased'])\ndef test_steiner_tree_with_disconnected_component(disconnected_line_graph, method):\n gi = disconnected_line_graph\n edges = random_steiner_tree(gi, X=[0, 2], root=1, method=method)\n assert set(edges) == {(1, 0), (1, 2)}\n" } ]
10
Echelon133/PROJECT_EULER
https://github.com/Echelon133/PROJECT_EULER
e1cac3e94765849be018d7f52d4c6542f135db95
4d6156f591b73321a772d5e77c45715d3909008b
17b34efed508dfc82091017d0f1f1c057e7b8d3b
refs/heads/master
2016-07-27T07:44:48.486687
2015-11-15T14:40:35
2015-11-15T14:40:35
42,861,227
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5651558041572571, "alphanum_fraction": 0.5963172912597656, "avg_line_length": 28.41666603088379, "blob_id": "1c49a8a8d2d60c05817b04fcaecda2815f428d50", "content_id": "581d1632a2e6fa7e2f81f08d3b61a32b069ea77d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 706, "license_type": "no_license", "max_line_length": 75, "num_lines": 24, "path": "/longest_collatz_#14.py", "repo_name": "Echelon133/PROJECT_EULER", "src_encoding": "UTF-8", "text": "from itertools import islice, count\ndef collatz(number):\n '''returns collatz conjecture with starting point equal to first_num'''\n li = []\n li.append(number) # appending the starting number to the sequence\n while number != 1:\n if number % 2 ==0:\n number = number //2\n li.append(number)\n else:\n number = (number*3) + 1\n li.append(number)\n return len(li)\n\n# debug print(collatz(13))\n\nlongest = [0,0] #[len of list,number passed to collatz() func]\nnum = 0\nfor num in islice(count(2),1000000):\n if collatz(num) >= longest[0]:\n longest[0] = collatz(num)\n longest[1] = num\n print(longest)\nprint(\"Result =\",longest)\n" }, { "alpha_fraction": 0.5336787700653076, "alphanum_fraction": 0.575129508972168, "avg_line_length": 16.545454025268555, "blob_id": "571683348f54d67a94a1228d9c6da18da0359bb4", "content_id": "e0563e5238261562ed2c67d6ed999ce10d5f44b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 193, "license_type": "no_license", "max_line_length": 51, "num_lines": 11, "path": "/factorial_sum_#20.py", "repo_name": "Echelon133/PROJECT_EULER", "src_encoding": "UTF-8", "text": "def factorial(num):\n res = num\n while num != 1:\n res*=num-1\n num-=1\n return res\n\n#print(factorial(10))\n\nresult = sum([int(x) for x in str(factorial(100))])\nprint(result)\n" }, { "alpha_fraction": 0.5480769276618958, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 12, "blob_id": "61ebbb327a21de5709aca1380ecfaf4d1d09bcb5", "content_id": "af337c02bd7b6ae4e8888b00a70a37eedeb33737", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 104, "license_type": "no_license", "max_line_length": 24, "num_lines": 8, "path": "/power_digit_#16.py", "repo_name": "Echelon133/PROJECT_EULER", "src_encoding": "UTF-8", "text": "num = 2**1000\n\nsplit = str(num).split()\n\nresult = 0\nfor x in split[0]:\n result+=int(x)\nprint(result)\n" }, { "alpha_fraction": 0.6366197466850281, "alphanum_fraction": 0.7042253613471985, "avg_line_length": 28.58333396911621, "blob_id": "5bcddf0212674ba07833e09c5a76bfa4715456a5", "content_id": "ac7f63ad43aaa79e8e9aa2301d7c9985c4707240", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 355, "license_type": "no_license", "max_line_length": 80, "num_lines": 12, "path": "/sum_of_primes_#10.py", "repo_name": "Echelon133/PROJECT_EULER", "src_encoding": "UTF-8", "text": "from itertools import count, islice\nfrom math import sqrt\n\ndef is_prime(num):\n if num < 2: return False\n return all(num%x for x in islice(count(2),int(sqrt(num)-1)))\n\ndef sum_of_primes(threshold):\n generator = (num for num in islice(count(2),(threshold-1)) if is_prime(num))\n return sum(generator)\n\nprint(sum_of_primes(2000000)) #142913828922\n" }, { "alpha_fraction": 0.57421875, "alphanum_fraction": 0.623046875, "avg_line_length": 25.947368621826172, "blob_id": "cddfc4715050d2929f23e06400304b95e1a02cc9", "content_id": "ea16d44b1d1422b11bc35cdbc7ed115d418e8257", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 512, "license_type": "no_license", "max_line_length": 64, "num_lines": 19, "path": "/10001st_prime_#7.py", "repo_name": "Echelon133/PROJECT_EULER", "src_encoding": "UTF-8", "text": "from itertools import count, islice\nfrom math import sqrt\n\ndef is_prime(num):\n if num < 2: return False\n return all(num%x for x in islice(count(2),int(sqrt(num)-1)))\n\ndef gen_primes():\n counter = 0 #incremented with every prime number\n number = 0 #incremented with each while loop run\n while counter != 10001:\n if is_prime(number):\n counter+=1\n number+=1\n else:\n number+=1\n return number - 1, counter \n\nprint(gen_primes()) #returns (104743,10001)\n" }, { "alpha_fraction": 0.6129496693611145, "alphanum_fraction": 0.6561151146888733, "avg_line_length": 29.217391967773438, "blob_id": "707fa6c94acbdb039d1616a53a88247a4ae0de56", "content_id": "1d53f7aaee9d20560b7adb192bfe650086a8865b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 695, "license_type": "no_license", "max_line_length": 64, "num_lines": 23, "path": "/largest_prime_factor_#3.py", "repo_name": "Echelon133/PROJECT_EULER", "src_encoding": "UTF-8", "text": "from math import sqrt\nfrom itertools import count, islice\n\ndef is_prime(num):\n if num < 2: return False\n return all(num%x for x in islice(count(2),int(sqrt(num)-1)))\n\ndef gen_primes(max_range):\n '''generate prime numbers up to specified max_range'''\n for x in islice(count(2),int(sqrt(max_range)-1)):\n if is_prime(x):\n yield x\n\ndef largest_prime_factor(number):\n '''calculate the largest prime factor of passed number)'''\n largest_pf = 0\n for x in gen_primes(number):\n if number % x == 0:\n largest_pf = x\n return largest_pf\n\n#print(largest_prime_factor(13195)) #should return 29\nprint(largest_prime_factor(600851475143)) #returns 6857\n" }, { "alpha_fraction": 0.6253968477249146, "alphanum_fraction": 0.6539682745933533, "avg_line_length": 24.200000762939453, "blob_id": "03c3e7867617f0cfe401288320ccaf6813501611", "content_id": "758346eeb0d11f724a63e1fc14dc5ddd036e3b24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 630, "license_type": "no_license", "max_line_length": 65, "num_lines": 25, "path": "/largest_palindrome_#4.py", "repo_name": "Echelon133/PROJECT_EULER", "src_encoding": "UTF-8", "text": "def reverse(num):\n\tstr_num = str(num)\n\treversed_num = str_num[::-1]\n\treturn int(reversed_num)\n\npalindromes = [] #contains all possible palindromes\n\ndef list_palindromes():\n\t'''appends all possible combinations of xyz * abc palindromes'''\n for x in range(100,1000):\n for y in range(100,x):\n\t if y*x == reverse(y*x):\n\t palindromes.append(y*x)\n\ndef deter_largest():\n\t'''determines the largest palindrome in a list'''\n largest = 0\n for x in palindromes:\n if x > largest:\n largest = x\n print(largest)\n\n\nlist_palindromes() #calling necessary functions\ndeter_largest() #should print 906609\n" }, { "alpha_fraction": 0.5333333611488342, "alphanum_fraction": 0.5719298124313354, "avg_line_length": 19.35714340209961, "blob_id": "83413c06d4d775eacd0fdd35fac2b5b39032efcd", "content_id": "2046bb25a5eaa38b252d79c1d327e6e9a8fed072", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 285, "license_type": "no_license", "max_line_length": 51, "num_lines": 14, "path": "/even_fibonacci_#2.py", "repo_name": "Echelon133/PROJECT_EULER", "src_encoding": "UTF-8", "text": "def fibonacci(max_range):\n fib_list = []\n a = 0\n b = 1\n while a < max_range:\n fib_list.append(a)\n a,b = b, a+b\n return fib_list\n\n\nfibonacci_seq = (fibonacci(4000000))\neven_num = [x for x in fibonacci_seq if x % 2 == 0]\nanswer = sum(even_num)\nprint(answer)\n" }, { "alpha_fraction": 0.5825892686843872, "alphanum_fraction": 0.6339285969734192, "avg_line_length": 31, "blob_id": "3597597bec9d7819c607a7f37a3420a53047fc19", "content_id": "9dac02ab48d4f7ac0a829a3f83fa7dabeaa92bfc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 448, "license_type": "no_license", "max_line_length": 57, "num_lines": 14, "path": "/counting_sundays_#19.py", "repo_name": "Echelon133/PROJECT_EULER", "src_encoding": "UTF-8", "text": "from datetime import timedelta, date\n\ndef daterange(start_date, end_date):\n for n in range(int ((end_date - start_date).days)):\n yield start_date + timedelta(n)\n\nstart_date = date(1901, 1, 1)\nend_date = date(2000, 12, 31)\ndates = [0,[]]\nfor single_date in daterange(start_date, end_date):\n if single_date.strftime(\"%A/%d\") == 'Sunday/01':\n dates[1].append(single_date.strftime(\"%d/%m/%Y\"))\n dates[0]+=1\nprint(dates) #171\n" } ]
9
formigarafa/uroslibpy
https://github.com/formigarafa/uroslibpy
a7ca20e8f7cc0e3178463f4386517dd6c1e95123
c84f99690a6feb186ca621871c1bc29763f08240
31fe9191eb744e6b1c58a58668d561140be67b52
refs/heads/master
2023-01-20T15:26:43.138185
2020-11-27T08:34:29
2020-11-27T08:34:29
316,437,083
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.47404903173446655, "alphanum_fraction": 0.47607776522636414, "avg_line_length": 32.4180793762207, "blob_id": "b9b664589e25c3a016648692139f573ac37c1b0b", "content_id": "29f37988f762653082f32f702dbf42ddf3b8e5fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5915, "license_type": "no_license", "max_line_length": 79, "num_lines": 177, "path": "/core.py", "repo_name": "formigarafa/uroslibpy", "src_encoding": "UTF-8", "text": "# Copyright AF386 Group LLC 2019\n\nimport json\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\n###############################################################################\nclass Message:\n ###########################################################################\n def __init__(self, values=None):\n self._values = values\n\n ###########################################################################\n @property\n def str_message(self):\n \"\"\"\n If values of message is a dict, then convert it into a JSON string\n \"\"\"\n if isinstance(self._values, dict):\n return json.dumps(self._values)\n else:\n return self._values\n\n @property\n def values(self):\n return self._values\n\n###############################################################################\n\n\nclass Topic:\n \"\"\"Publish and/or subscribe to a topic in ROS.\n\n Args:\n ros (:class:`.Ros`): Instance of the ROS connection.\n name (:obj:`str`): Topic name, e.g. ``/cmd_vel``.\n message_type (:obj:`str`): Message type, e.g. ``std_msgs/String``.\n compression (:obj:`str`): Type of compression to use, e.g. `png`.\n Defaults to `None`.\n throttle_rate (:obj:`int`): Rate (in ms between messages) at which to\n throttle the topics.\n queue_size (:obj:`int`): Queue size created at bridge side for\n re-publishing webtopics.\n latch (:obj:`bool`): True to latch the topic when publishing,\n False otherwise.\n queue_length (:obj:`int`): Queue length at bridge side used when\n subscribing.\n \"\"\"\n SUPPORTED_COMPRESSION_TYPES = ('png', 'none')\n\n ###########################################################################\n def __init__(self, ros, name, message_type,\n compression=None, latch=False, throttle_rate=0,\n queue_size=100, queue_length=0):\n self._ros = ros\n self._name = name\n self._message_type = message_type\n self._compression = compression\n if self._compression is None:\n self._compression = 'none'\n self._latch = latch\n self._throttle_rate = throttle_rate\n self._queue_size = queue_size\n self._queue_length = queue_length\n\n self._subscribe_id = None\n self._advertise_id = None\n\n ###########################################################################\n @property\n def is_advertised(self):\n \"\"\"Indicate if the topic is currently advertised or not.\n\n Returns:\n bool: True if advertised as publisher of this topic,\n False otherwise.\n \"\"\"\n return self._advertise_id is not None\n\n ###########################################################################\n @property\n def is_subscribed(self):\n \"\"\"Indicate if the topic is currently subscribed or not.\n\n Returns:\n bool: True if subscribed to this topic, False otherwise.\n \"\"\"\n return self._subscribe_id is not None\n\n ###########################################################################\n def subscribe(self, callback):\n \"\"\"Register a subscription to the topic.\n\n Every time a message is published for the given topic,\n the callback will be called with the message object.\n\n Args:\n callback: Function to be called when messages of this topic are\n published.\n \"\"\"\n # Avoid duplicate subscription\n if self._subscribe_id:\n return\n\n self._subscribe_id = 'subscribe:%s:%d' % (\n self._name, self._ros.id_counter)\n\n sub_msg = Message({\n 'op': 'subscribe',\n 'id': self._subscribe_id,\n 'type': self._message_type,\n 'topic': self._name,\n 'compression': self._compression,\n 'throttle_rate': self._throttle_rate,\n 'queue_length': self._queue_length\n })\n\n self._ros.on(self._name, callback)\n self._ros.send_on_ready(sub_msg)\n\n ###########################################################################\n def publish(self, message):\n \"\"\"Publish a message to the topic.\n\n Args:\n message (:class:`.Message`): ROS Bridge Message to publish.\n \"\"\"\n if self.is_advertised is False:\n self.advertise()\n\n publish_id = 'publish:%s:%d' % (self._name, self._ros.id_counter)\n\n pub_msg = Message({\n \"op\": \"publish\",\n \"id\": publish_id,\n \"topic\": self._name,\n \"msg\": message.values,\n \"latch\": self._latch\n })\n\n try:\n rval = self._ros.send_on_ready(pub_msg)\n if rval is not None:\n logger.error(\"Error publishing {}\".format(pub_msg.str_message))\n except Exception as ex:\n # Need to better handle this\n logger.error(\"Send request failed {}\".format(str(ex)))\n raise ex\n pass\n\n ###########################################################################\n def advertise(self):\n if self.is_advertised:\n logger.error(\"We already advertised {}\".format(self._name))\n\n self._advertise_id = 'advertise:%s:%d' % (\n self._name, self._ros.id_counter)\n\n adv_msg = Message({\n \"op\": \"advertise\",\n \"id\": self._advertise_id,\n \"type\": self._message_type,\n \"topic\": self._name,\n \"latch\": self._latch,\n \"queue_size\": self._queue_size\n })\n\n logger.info(\"Advertising: {}\".format(adv_msg.str_message))\n rval = self._ros.send_on_ready(adv_msg)\n logger.info(\"Done advertising\")\n\n if rval is not None:\n logger.info(\"Error advertising: {}\".format(adv_msg.str_message))\n self._advertise_id = None\n" } ]
1
EStepzz/LogData
https://github.com/EStepzz/LogData
859e0a30dae7feb009e63aa9f8017bdfc6303f57
59cc68e0b8c0995de4703f60e3d62799e828c01d
d5543e5cda26b9d8f2367f5547342d85f6c4a4b8
refs/heads/master
2021-01-02T09:04:22.791356
2017-08-13T08:44:40
2017-08-13T08:44:40
99,135,110
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5840517282485962, "alphanum_fraction": 0.6120689511299133, "avg_line_length": 17.600000381469727, "blob_id": "1d74a2ac80eb6274d1c9ec8efb18ad89ea4ae9fd", "content_id": "27d1c97da68325bf63a4a410df14c4cb036a1dfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 512, "license_type": "no_license", "max_line_length": 60, "num_lines": 25, "path": "/tools/GenPic.py", "repo_name": "EStepzz/LogData", "src_encoding": "UTF-8", "text": "#coding = utf-8\n#author:QINWANG\n'''\n使用pyecharts 创建不同的图形图像\n目前有:xxxx等图像\n'''\nfrom pyecharts import Line\nfrom tools.ConnectDB import DbSomething\n\na = DbSomething('localhost','dns_query', 'postgres', 111111)\nv1,v2 = a.search()\nprint (v1,v2)\n\nclass GenPic:\n '''生成折线图'''\n def lineChart(self):\n line= Line(\"QPS图\")\n line.add('', v1, v2)\n line.show_config()\n line.render()\n\n\nif __name__=='__main__':\n pic = GenPic()\n pic.lineChart()" }, { "alpha_fraction": 0.4902998208999634, "alphanum_fraction": 0.49970605969429016, "avg_line_length": 25.184616088867188, "blob_id": "5b51b0a421e30b65c05da81c70a62a28185e58a8", "content_id": "18106babee540f22a792c35bb2dc56dac99c387a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1789, "license_type": "no_license", "max_line_length": 77, "num_lines": 65, "path": "/tools/ConnectDB.py", "repo_name": "EStepzz/LogData", "src_encoding": "UTF-8", "text": "#coding=utf-8\nimport psycopg2\nimport datetime\nimport time\n\nclass DbSomething():\n def __init__(self,ip,database,username, password,port=5432):\n self.ip = ip\n self.database = database\n self.username = username\n self.password = password\n self.port = port\n '''如果把connection写到__init__中,每次初始化类就好?可以一试'''\n def connection(self):\n conn = psycopg2.connect(host=self.ip,\n database=self.database,\n user=self.username,\n password=self.password,\n port=self.port)\n cur = conn.cursor()\n return cur, conn\n\n '''创建表操作'''\n def creatTable(self, sql):\n cur, conn = self.connection()\n cur.execute(sql)\n print (\"table is created\")\n conn.commit()\n cur.close()\n conn.close()\n\n '''插入数据\n #table,which table insert to\n #data,what to insert\n '''\n def Insert(self,sql):\n pass\n\n '''\n #通过输入查询条件返回查询结果\n #table\n #conditions\n '''\n def search(self):\n v1 =[]\n v2=[]\n '''sql = select ctime ,count(*)\n from qps\n group by ctime order by ctime\n '''\n sql = 'select ctime ,count(*) from qps group by ctime order by ctime'\n cur, conn = self.connection()\n cur.execute(sql)\n data = cur.fetchall()\n #data list type\n\n for i in data:\n date = datetime.datetime.strftime(i[0], '%Y-%m-%d %H:%M:%S')\n print (type(date),type(i[1]))\n v1.append(date)\n\n v2.append(i[1])\n cur.close()\n conn.close()\n return v1,v2" } ]
2
Bthelisma/repTravelbuddy
https://github.com/Bthelisma/repTravelbuddy
9272b2b7e5da7d4bcd713adc7490b5d2606a99a8
02146befae59df60356a1b9dd7ec9099decf4eac
c6a9d6f37491dca69d9a97048bf7323def6587d7
refs/heads/master
2021-09-02T03:59:04.966727
2017-12-30T05:41:22
2017-12-30T05:41:22
115,776,337
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5672997236251831, "alphanum_fraction": 0.5986787676811218, "avg_line_length": 39.36666488647461, "blob_id": "9213de384a1bdc3667cd3e8d259e6e07ec2e48bc", "content_id": "18e67afd6a1a223a7ffa90f46003218a49c94b7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1211, "license_type": "no_license", "max_line_length": 138, "num_lines": 30, "path": "/apps/travel_app/migrations/0003_trip.py", "repo_name": "Bthelisma/repTravelbuddy", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11 on 2017-12-27 10:38\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('travel_app', '0002_auto_20171227_0048'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Trip',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('destination', models.CharField(max_length=255)),\n ('description', models.CharField(max_length=255)),\n ('travelfrom', models.DateTimeField(auto_now_add=True)),\n ('travelto', models.DateTimeField(auto_now_add=True)),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('updated_at', models.DateTimeField(auto_now=True)),\n ('my_trip', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='planner', to='travel_app.User')),\n ('travellers', models.ManyToManyField(related_name='joiner', to='travel_app.User')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5215311050415039, "alphanum_fraction": 0.5693780183792114, "avg_line_length": 19.899999618530273, "blob_id": "998fe4b68931dfbe41fc05ca78a33ed4b22c87bd", "content_id": "beafa4fd9f6493a8dd1dae553709a777f4212be1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 418, "license_type": "no_license", "max_line_length": 46, "num_lines": 20, "path": "/apps/travel_app/migrations/0004_auto_20171227_0320.py", "repo_name": "Bthelisma/repTravelbuddy", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11 on 2017-12-27 11:20\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('travel_app', '0003_trip'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='trip',\n old_name='my_trip',\n new_name='created_by',\n ),\n ]\n" }, { "alpha_fraction": 0.44999998807907104, "alphanum_fraction": 0.4541666805744171, "avg_line_length": 21.399999618530273, "blob_id": "83b05a4317af9129486a3c783957964a6ee733bf", "content_id": "134941a5585cb422fbeb41fad43dc9ec2c29e417", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1680, "license_type": "no_license", "max_line_length": 74, "num_lines": 75, "path": "/apps/travel_app/templates/travel_app/dashboard.html", "repo_name": "Bthelisma/repTravelbuddy", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <title>Travel Dashboard</title>\n <style>\n table {\n font-family: arial, sans-serif;\n border-collapse: collapse;\n width: 60%;\n }\n\n td, th {\n border: 1px solid #dddddd;\n text-align: left;\n padding: 8px;\n }\n\n tr:nth-child(even) {\n background-color: #dddddd;\n }\n </style>\n </head>\n <body>\n <a href=\"/logout\">| logout</a>\n <h1>Hello, {{ user.name}}!</h1>\n <p>Your Trip Schedules</p>\n\n <table >\n <tr>\n <th >Destination</th>\n <th >Travel Start Date</th>\n <th >Travel End Date</th>\n <th >Plan</th>\n </tr>\n\n\n {% for trip in my_trips %}\n <tr>\n <td><a href =\"travels/{{trip.id}}\">{{trip.destination}}</a></td>\n <td>{{trip.start_date}}</td>\n <td>{{trip.end_date}}</td>\n <td>{{trip.description}}</td>\n </tr>\n {%endfor%}\n\n </table><br><br>\n\n <p>Other Users' Travel Plans</p>\n <table >\n <tr>\n <th >Name</th>\n <th >Destination</th>\n <th >Travel Start Date</th>\n <th >Travel End Date</th>\n <th >Do you want to join</th>\n\n </tr>\n\n {% for trip in other_plans %}\n <tr>\n <td>{{trip.created_by.name}}</td>\n <td><a href =\"travels/{{trip.id}}\">{{trip.destination}}</a></td>\n <td>{{trip.start_date}}</td>\n <td>{{trip.end_date}}</td>\n <td><a href =\"travels/{{trip.id}}/join\">Join</a></td>\n </tr>\n {%endfor%}\n </table >\n\n <a href=\"/addplan\">Add Travel Plan</a>\n\n\n </body>\n</html>\n" }, { "alpha_fraction": 0.5776699185371399, "alphanum_fraction": 0.5838017463684082, "avg_line_length": 30.063491821289062, "blob_id": "5629c5dff86c213e8361d4b4527a2764e75cc56b", "content_id": "9cff7a9baaf39a7ad283704c0893296f2e22dc5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3914, "license_type": "no_license", "max_line_length": 80, "num_lines": 126, "path": "/apps/travel_app/models.py", "repo_name": "Bthelisma/repTravelbuddy", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport re\nimport bcrypt\nimport datetime\nfrom django.db import models\n\n\nclass UserManager(models.Manager):\n def register_validate(self, postData):\n errors = []\n\n name = postData['name']\n username = postData['username']\n password = postData['password']\n cpassword = postData['cpassword']\n\n if not name or not username or not password or not cpassword:\n errors.append( \"All fields are required\")\n\n # check name\n if len(name) < 3 :\n errors.append( \"name fields should be at least 3 characters\")\n\n # check username\n if len(username) < 1:\n errors.append( \"Username cannot be blank\")\n\n\n # check password\n if len(password ) < 8:\n errors.append ( \"password must be at least 8 characters\")\n elif password != cpassword:\n errors.append ( \"password must be match\")\n\n if not errors:\n if User.objects.filter(username=username):\n errors.append(\"username is not unique\")\n else:\n hashed = bcrypt.hashpw((password.encode()), bcrypt.gensalt(5))\n\n return self.create(\n name=name,\n username=username,\n password=hashed\n )\n\n return errors\n\n def login_validate(self, postData):\n errors = []\n password = postData['password']\n username = postData['username']\n # check DB for username\n try:\n # check user's password\n user = self.get(username=username)\n if bcrypt.checkpw(password.encode(), user.password.encode()):\n return user\n\n except:\n pass\n\n errors.append('Invalid login info')\n return errors\n\nclass TripManager(models.Manager):\n def trip_validate(self, postData, id):\n errors=[]\n destination=postData['destination']\n description=postData['description']\n start_date=postData['start_date']\n end_date=postData['end_date']\n \n\n\n if start_date < datetime.datetime.now().strftime('%m-%d-%Y'):\n errors.append('Start Date must be after today')\n\n elif start_date > end_date:\n errors.append('End Date must be after Start Date')\n\n if not destination or not destination or not start_date or not end_date:\n errors.append( \"All fields are required\")\n\n if len(destination)<1:\n errors.append('please enter a destination')\n if len(description)<1:\n errors.append('please enter a description')\n\n if not errors:\n user = User.objects.get(id=id)\n trip = self.create(\n destination = destination,\n description = description,\n start_date = start_date,\n end_date= end_date,\n created_by = user\n )\n trip.travellers.add(user)\n return trip\n\n return errors\n\n\nclass User(models.Model):\n name = models.CharField(max_length=255)\n username = models.CharField(max_length=255)\n password = models.CharField(max_length=255)\n created_at = models.DateTimeField(auto_now_add = True)\n updated_at = models.DateTimeField(auto_now = True)\n objects = UserManager()\n\n\n\n\nclass Trip(models.Model):\n destination = models.CharField(max_length=255)\n description = models.CharField(max_length=255)\n start_date = models.DateTimeField()\n end_date = models.DateTimeField()\n created_by = models.ForeignKey(User, related_name=\"planner\")\n travellers = models.ManyToManyField(User, related_name=\"joiner\")\n created_at = models.DateTimeField(auto_now_add = True)\n updated_at = models.DateTimeField(auto_now = True)\n objects=TripManager()\n" }, { "alpha_fraction": 0.5719984173774719, "alphanum_fraction": 0.5723972916603088, "avg_line_length": 26.85555648803711, "blob_id": "2e4a88e3d3afd2afbfba32bd1184056cd7cf7eef", "content_id": "ab09ef4d17d393e1992170c94796b535f37f9fe7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2507, "license_type": "no_license", "max_line_length": 87, "num_lines": 90, "path": "/apps/travel_app/views.py", "repo_name": "Bthelisma/repTravelbuddy", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render, redirect\nfrom .models import User\nfrom .models import Trip\nfrom django.contrib import messages\n\n#==================================================#\n# RENDER METHODS #\n#==================================================#\n\ndef index(request):\n context = {\n 'users': User.objects.all()\n }\n return render(request, \"travel_app/index.html\", context)\n\ndef addplan(request):\n return render(request, \"travel_app/new.html\")\n\n\ndef dashboard(request):\n try:\n context = {\n 'user': User.objects.get(id=request.session['user_id']),\n 'my_trips':Trip.objects.filter(travellers=request.session['user_id']),\n 'other_plans': Trip.objects.exclude(travellers=request.session['user_id']),\n }\n return render (request, \"travel_app/dashboard.html\", context)\n\n except KeyError:\n return redirect('/')\n\ndef show(request, id):\n\n context={\n\n 'trip':Trip.objects.get(id=id),\n 'jointrips': Trip.objects.exclude(travellers =request.session['user_id'])\n\n }\n return render (request, \"travel_app/show.html\", context)\n\n\n\n#==================================================#\n# PROCESS METHODS #\n#==================================================#\n\ndef register(request):\n result = User.objects.register_validate(request.POST)\n if type(result) == list:\n for error in result:\n messages.error(request, error)\n return redirect('/')\n\n request.session['user_id'] = result.id\n\n return redirect('/dashboard')\n\n\ndef login(request):\n result = User.objects.login_validate(request.POST)\n if type(result) == list:\n for error in result:\n messages.error(request, error)\n return redirect (\"/\")\n\n request.session['user_id'] = result.id\n\n return redirect(\"/dashboard\")\n\ndef logout(request):\n request.session.clear()\n return redirect('/')\n\ndef create(request):\n result = Trip.objects.trip_validate(request.POST, request.session['user_id'])\n if type(result) == list:\n for error in result:\n messages.error(request, error)\n return redirect (\"/addplan\")\n return redirect('/dashboard')\n\ndef join(request, id):\n other_plans = Trip.objects.get(id=id)\n user=User.objects.get(id=request.session['user_id'])\n user.joiner.add(other_plans)\n return redirect('/dashboard')\n" }, { "alpha_fraction": 0.511035680770874, "alphanum_fraction": 0.5653650164604187, "avg_line_length": 22.559999465942383, "blob_id": "a197de1f1146bc6332b8993d16d0229aefff20cd", "content_id": "f695bd478d7d8d794a24d3427f81f5c3693bc075", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 589, "license_type": "no_license", "max_line_length": 50, "num_lines": 25, "path": "/apps/travel_app/migrations/0005_auto_20171227_1455.py", "repo_name": "Bthelisma/repTravelbuddy", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11 on 2017-12-27 22:55\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('travel_app', '0004_auto_20171227_0320'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='trip',\n name='travelfrom',\n field=models.DateTimeField(),\n ),\n migrations.AlterField(\n model_name='trip',\n name='travelto',\n field=models.DateTimeField(),\n ),\n ]\n" } ]
6
devikadayanand16/todo
https://github.com/devikadayanand16/todo
790d9f54787f38297c71dcc3aa7c9613f231fd6e
550cf71194bdb1c0e0515457d87482624c300335
2c6dce356132aa1746f08bc481bf076b1f2a2b6e
refs/heads/main
2023-01-24T07:52:51.184991
2020-11-20T08:31:50
2020-11-20T08:31:50
314,286,419
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7198443412780762, "alphanum_fraction": 0.7276264429092407, "avg_line_length": 42, "blob_id": "9229ac5703b7c95be7d840f7e585168f8aa7f6e9", "content_id": "9b8a990ee0066257c8bfd0d2af50106f49678fba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 257, "license_type": "no_license", "max_line_length": 134, "num_lines": 6, "path": "/todolist/forms.py", "repo_name": "devikadayanand16/todo", "src_encoding": "UTF-8", "text": "from django import forms\n\nclass TodoListForm(forms.Form):\n\ttext = forms.CharField(max_length=50,\n\t\twidget=forms.TextInput(\n\t\t\tattrs={'class':'form-control','placeholder':'Enter todo e.g. Grocery Shopping', 'aria-label':'Todo', 'aria-describeby':'add-btn'}))" }, { "alpha_fraction": 0.7637362480163574, "alphanum_fraction": 0.7747252583503723, "avg_line_length": 25.14285659790039, "blob_id": "9560e8d2aabc8483e0cd73c8f442baacae78593b", "content_id": "f1b0ae8cb7ffdcb3583246801e1efb48bb6c1bb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 182, "license_type": "no_license", "max_line_length": 45, "num_lines": 7, "path": "/todolist/models.py", "repo_name": "devikadayanand16/todo", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass Todolist(models.Model):\n\ttext=models.CharField(max_length=50)\n\tcompleted=models.BooleanField(default=False)\n\tdef __str__(self):\n\t\treturn self.text" }, { "alpha_fraction": 0.7516930103302002, "alphanum_fraction": 0.7516930103302002, "avg_line_length": 25.84848403930664, "blob_id": "274f02f188aaafa4fa66e23744e1a31cc92ad37a", "content_id": "f20ededb0d44ecb88c87e4a45a2a5b2b8212032a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 886, "license_type": "no_license", "max_line_length": 56, "num_lines": 33, "path": "/todolist/views.py", "repo_name": "devikadayanand16/todo", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect\nfrom .models import Todolist\nfrom .forms import TodoListForm\nfrom django.views.decorators.http import require_POST\n\ndef index(request):\n\ttodo_items=Todolist.objects.order_by('id')\n\tform = TodoListForm()\n\tcontext = {'todo_items' : todo_items, 'form' : form }\n\treturn render(request, 'todolist/index.html', context)\n\n@require_POST\ndef addTodoItem(request):\n\tform=TodoListForm(request.POST)\n\t\n\tif form.is_valid():\n\t\tnew_todo = Todolist(text=request.POST['text'])\n\t\tnew_todo.save()\n\treturn redirect('index')\n\ndef completedTodo(request, todo_id):\n\ttodo= Todolist.objects.get(pk=todo_id)\n\ttodo.completed=True\n\ttodo.save()\n\treturn redirect('index')\n\ndef deleteCompleted(request):\n\tTodolist.objects.filter(completed__exact=True).delete()\n\treturn redirect('index')\n\ndef deleteAll(request):\n\tTodolist.objects.all().delete()\n\treturn redirect('index')\t" } ]
3
morjp/py-uc_serial-protocol
https://github.com/morjp/py-uc_serial-protocol
84a5ca508979194648a8bb5d84eb2313c4481593
1caa5bcf04236eaa9548be7a973609bb947cf1e0
ce33a41f0b52928c6e7aa4eddea471813940518c
refs/heads/master
2020-09-24T18:06:07.108253
2019-12-04T12:59:52
2019-12-04T12:59:52
225,813,589
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8163265585899353, "alphanum_fraction": 0.8265306353569031, "avg_line_length": 48, "blob_id": "b7e35af3f4d67553137d77a54f39a938b0d55efb", "content_id": "69325597662dd1c24ef2e6ca1eddd3e177acfd52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 98, "license_type": "permissive", "max_line_length": 73, "num_lines": 2, "path": "/README.md", "repo_name": "morjp/py-uc_serial-protocol", "src_encoding": "UTF-8", "text": "# py-uc_serial-protocol\nPython to ATmega microcontroller serial protocol sending 4-Byte packages.\n" }, { "alpha_fraction": 0.6366653442382812, "alphanum_fraction": 0.6575556397438049, "avg_line_length": 36.394161224365234, "blob_id": "1419513fe5fea4455e8d64c763ae8ad67596341a", "content_id": "a337348c45c6cdb6a42dbed3f5b5b8ff9d573daf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5123, "license_type": "permissive", "max_line_length": 209, "num_lines": 137, "path": "/py-uc_Serial_Protocol_0.1_Client/py-uc_Serial_Protocol_0.1_Client.ino", "repo_name": "morjp/py-uc_serial-protocol", "src_encoding": "UTF-8", "text": "/*\nATmega 328P Serial Protocol Client \nVersion 0.1\nCompatible with host version 0.1\nCreated 02/12/2019 by Moritz Prenzlow <[email protected]>\n\nThis client receives a serial packet from the host using the function receivePacket().\nPacket structure: START BYTE (DEC 42), COMMAND BYTE, VALUE BYTE, END BYTE (DEC 255).\n\nIt checks for validity of the packet and if command and value are known.\nThe packet is always stored in inData[], but a flag is set if the packet is valid and the data can be used.\n\nA sample function that blinks a LED on pin 13 can be called with the command 0, values 5 to 20 (amount of blinks).\nA sample function that lights a LED on pin 12 can be called with the command 1, values 1 to 254 (seconds)\n*/\n\nint inData[4]; // data buffer\nint index = 0; // data buffer index\n// packet flags\nbool isReceiving = false; // true if currently receiving packet\nbool isBusy = false; // true if packet has been received and is being processed\nbool isOk = false; // true if packet is valid\n\n// arrays for packet validation\nconst int numberOfCommands = 2;\nint validCommandRange[2] = {0,1}; // range of valid commands (all commands in validCommandRange[0] <= x <= validCommandRange[1] will be accepted\nint validValueRanges[numberOfCommands][2] = { {5,20},\n {1, 10} }; // valid value range for each command (row 0 contains value range for the command in validCommandRange[0], row 1 for command in validCommandRange[1]...)\n\nvoid setup() {\n Serial.begin(9600);\n\n pinMode(LED_BUILTIN, OUTPUT); // for sample functions\n}\n\nvoid loop() {\n receivePacket();\n\n if (!isReceiving && isBusy && isOk) { // packet stored in inData is fully received and valid, so command stored in it can now be executed\n\n /////// execution of sample functions ///////\n \n // example: when the command byte is 0, blinkLED() is executed with the value byte as a parameter\n if (inData[1] == 0) {\n blinkLED(inData[2]);\n } \n\n if (inData[1] == 1) {\n lightLED(inData[2]);\n }\n\n ///////////////////////////////////////////\n\n serialFlush(); // flush serial buffer to discard everything that has been send during execution of command\n isBusy = false; // packet is discarded and next incoming one is processed\n }\n \n}\n\n// receives packet sent by host from serial buffer, checks for validity and if command and value are known, then sends ACK/NACK response\nvoid receivePacket() {\n // reads packet from serial buffer, stores it in inData\n if (Serial.available() > 0) {\n\n int inByte = Serial.read(); // read the first available (\"oldest\") byte from the serial buffer\n\n if (!isBusy && !isReceiving && inByte == 42) { // look for start byte (DEC 42), but only when currently not receiving and not busy\n //TODO: clear data buffer I don´t think we need to do that\n // reset flags\n isReceiving = true;\n isOk = false;\n index = 0; // reset data buffer index\n } \n else if (!isBusy && isReceiving && inByte == 255) { // look for end byte (DEC 255), but only when currently receiving\n index += 1;\n inData[index] = inByte; // put end byte in data array\n isReceiving = false;\n isBusy = true; // packet has been received and is now stored in inData\n }\n else if (!isBusy && isReceiving) { // if inByte is neither start or end byte, it has to be one of the data bytes\n index += 1;\n if (index == 3) { // true, if no end byte has been received as fourth byte and loop continues to receive\n inData[index] = inByte; //store non-end byte\n // reset flags, packet will be discarded in following validation-if-loop\n isReceiving = false;\n isBusy = true;\n }\n }\n\n if (isReceiving) { // saves current inByte in data buffer\n inData[index] = inByte;\n }\n\n }\n\n // validates packet in inData and sends response\n if (isBusy && !isReceiving) {\n if (inData[0] == 42 && inData[3] == 255 && // packet contains start and end byte in the right place\n inData[1] >= validCommandRange[0] && inData[1] <= validCommandRange[1] && // packet contains valid command byte (is in validCommandRange)\n inData[2] >= validValueRanges[inData[1]][0] && inData[2] <= validValueRanges[inData[1]][1]) // packet contains valid value byte for the corresponding command\n { \n Serial.print(\"ACK\"); // sends acknowledged response\n isOk = true; // packet is valid and command can now be executed\n } \n else { \n Serial.print(\"NACK\"); // sends not acknowledged response\n isOk = false; // packet is invalid\n isBusy = false; // packet is discarded and next incoming one is processed\n } \n }\n}\n\n// flushes serial input buffer\nvoid serialFlush() {\n while(Serial.available() > 0) {\n char t = Serial.read();\n }\n}\n\n/////// Sample Functions: ///////\n\n// blinks builtin LED\nvoid blinkLED(int times) {\n for (int i = 0; i < times; i++) {\n digitalWrite(LED_BUILTIN, HIGH);\n delay(300);\n digitalWrite(LED_BUILTIN, LOW);\n delay(300);\n }\n}\n\n// lights builtin LED\nvoid lightLED(int time) {\n digitalWrite(LED_BUILTIN, HIGH);\n delay(time * 1000);\n digitalWrite(LED_BUILTIN, LOW);\n}" }, { "alpha_fraction": 0.6656991839408875, "alphanum_fraction": 0.6968337893486023, "avg_line_length": 36.900001525878906, "blob_id": "4ae72989e0c646831c6194433989e8d12068e2a5", "content_id": "1517f7076a212ba5f8e8ebed930db3c4a8313e56", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3790, "license_type": "permissive", "max_line_length": 164, "num_lines": 100, "path": "/py-uc_Serial_Protocol_0.1_Host/py-uc_Serial_Protocol_0.1_Host.py", "repo_name": "morjp/py-uc_serial-protocol", "src_encoding": "UTF-8", "text": "#ATmega 328P Serial Protocol Host\n#Version 0.1\n#Compatible with client version 0.1\n#Created 02/12/2019 by Moritz Prenzlow <[email protected]>\n#\n#This host application can send packets over the serial bus to be received from the ATmega 328P and waits for a response.\n#Packet structure: START BYTE (DEC 42), COMMAND BYTE, VALUE BYTE, END BYTE (DEC 255).\n#\n#sendPacket(int command, int value) \n# Arguments: int value, int command; in range 0<=x<=254 \n# Returns: string response\n\n\nimport serial, time, struct\nimport warnings\nimport serial.tools.list_ports\n\n#searches for arduino in connected serial devices, opens serial connection if arduino is found\narduino_ports = [\n p.device\n for p in serial.tools.list_ports.comports()\n if 'Arduino' in p.description\n]\nif not arduino_ports:\n raise IOError(\"No Arduino found\")\nif len(arduino_ports) > 1:\n warnings.warn('Multiple Arduinos found - using the first')\n\nser = serial.Serial(arduino_ports[0], 9600, timeout=2)\ntime.sleep(3)\n\n\n#sends 4-byte packet over serial bus\ndef sendPacket(command, value):\n #check if arguments are going to fit in one byte, returns False if not; does not check for validity of command\n if command in range(0,255) and value in range(0,255): #both cannot contain 255 (end byte)\n #write packet to serial bus in bytes format\n ser.write((struct.pack('>B', 42))) #write start byte (DEC 42)\n ser.write((struct.pack('>B', command)))\n ser.write((struct.pack('>B', value)))\n ser.write((struct.pack('>B', 255))) #write end byte (DEC 255)\n\n #waits for response and returns it; possible responses are: \n #\n #ACK (acknowledged: command is known and will be executed)\n #\n #NACK (not acknowledged: packet is invalid or command is not known\n #\n #IF NO RESPONSE IS RECEIVED AFTER 20 SECONDS, BECAUSE THE CLIENT IS CURRENTLY EXECUTING OTHER CODE,\n #BSY (busy: client is busy) IS RETURNED, THE FUCTION WILL BLOCK CODE FOR THOSE 20 SECONDS\n #THE CLIENT WILL THEN NOT EXECUTE THE COMMAND\n #THUS THE CIENT CANNOT PERFORM ACTIONS BLOCKING CODE LONGER HAN 20 SECONDS (or whatever the timeout parameter is set to) WITHOUT PROPER HANDLING BY THE HOST\n response = ser.readline().decode('utf-8') #wait for response, decode from byte to ASCII\n if response == \"\": #no response, return BSY\n return \"BSY\"\n else: #response received, return response\n return response\n ser.reset_input_buffer() #clean the input buffer\n #ser.reset_output_buffer()\n else:\n return False\n\n\n######## Examples ########\n\n#A sample function that blinks a LED on pin 13 can be called with the command 0, values 5 to 20 (amount of blinks).\n#A sample function that lights a LED on pin 12 can be called with the command 1, values 1 to 254 (seconds)\n\n#blinks LED 10 times, returns ACK\nprint(\"Command: 0 Value: 10\")\nreturns = sendPacket(0, 10)\nprint(returns)\ntime.sleep(5)\n\n#returns NACK, because minimum value for command 0 is 5\nprint(\"Command: 0 Value: 4\")#\nreturns = sendPacket(0, 4)\nprint(returns)\ntime.sleep(5)\n\n#lights LED 10 seconds\nprint(\"Command: 1 Value: 10\")\nreturns = sendPacket(1, 10)\nprint(returns)\ntime.sleep(0.2) #not enough sleep to let client complete action\n\n#not enough time, no response in timeout=2 seconds => returns BSY and packet is discarded on client side\nprint(\"Command: 0 Value: 7\")#\nreturns = sendPacket(0, 7)\nprint(returns)\ntime.sleep(5)\n\n#returns False, because arguments are bigger than 1 byte\nprint(\"Command: 1 Value: 256\")\nreturns = sendPacket(1, 256)\nprint(returns) \n\n#TODO: -Change timeout to real value\n# -Set wait time after opening serial port to appropriate value to leave room for homing\n# so no BSY is returned already on the first packet " } ]
3
amoazeni75/multiclass-Classification-ML
https://github.com/amoazeni75/multiclass-Classification-ML
8ab39f613f20a3db403a7f0f2183bce6e711136b
d534ff9a25f524b6815fa69fe84bdcab39e17406
f2df2eee059bb58ca1c9f20acec63d11e4d3ee10
refs/heads/master
2022-03-13T20:10:07.267826
2019-09-20T06:46:09
2019-09-20T06:46:09
207,543,808
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.744534432888031, "alphanum_fraction": 0.755465567111969, "avg_line_length": 36.42424392700195, "blob_id": "2cbd5b09a1ec932f538c092a71a24c254990c23d", "content_id": "eb9429c08a584b52f56cd023fc41160b8086fea8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2470, "license_type": "no_license", "max_line_length": 104, "num_lines": 66, "path": "/source.py", "repo_name": "amoazeni75/multiclass-Classification-ML", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n@author: S.Alireza Moazeni(S.A.M.P.8)\n@tutorial source: Deep Learning With Python, Develop Deep Learning Models On Theano And TensorFlow Using\nKeras, Jason Brownlee\n\"\"\"\n\nimport numpy\nimport pandas\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom keras.utils import np_utils\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.pipeline import Pipeline\n\n# fix random seed for reproducibility\nseed = 7\nnumpy.random.seed(seed)\n\n# load dataset\ndataframe = pandas.read_csv(\"iris.csv\", header=None)\ndataset = dataframe.values\nX = dataset[:,0:4].astype(float)\nY = dataset[:,4]\n\n\"\"\"\nWhen modeling multiclass classification problems using neural networks, it is good practice to \nreshape the output attribute from a vector that contains values for each class value to be a \nmatrix with a boolean for each class value and whether or not a given instance has that class \nvalue or not. This is called one hot encoding or creating dummy variables from a categorical variabl\n\"\"\"\n# encode class values as integers\nencoder = LabelEncoder()\nencoder.fit(Y)\nencoded_Y = encoder.transform(Y)\n\n# convert integers to dummy variables (i.e. one hot encoded)\ndummy_y = np_utils.to_categorical(encoded_Y)\n\n\n# define baseline model\n\"\"\"\nFully connected network with one hidden layer which contains 4 neurons.\nThe hidden layer uses a rectifier activation function which is a good practice. Because we used \na one-hot encoding for our iris dataset, the output layer must create 3 output values, one for \neach class. The output value with the largest value will be taken as the class predicted by the model. \n\"\"\"\ndef baseline_model():\n # create model\n model = Sequential()\n model.add(Dense(4, kernel_initializer= 'normal' , activation= 'relu' ,input_dim=4))\n model.add(Dense(3, kernel_initializer= 'normal' , activation= 'sigmoid' ))\n # Compile model\n model.compile(loss= 'categorical_crossentropy' , optimizer= 'adam' , metrics=[ 'accuracy' ])\n return model\n\nestimator = KerasClassifier(build_fn=baseline_model, nb_epoch=200, batch_size=15, verbose=0)\n\n# Define the model evaluation procedure\nkfold = KFold(n_splits=10, shuffle=True, random_state=seed)\n\nresults = cross_val_score(estimator, X, dummy_y, cv=kfold)\nprint(\"Accuracy: %.2f%% (%.2f%%)\" % (results.mean()*100, results.std()*100))\n" }, { "alpha_fraction": 0.7332372069358826, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 29.15217399597168, "blob_id": "573d97b8be63e0ae44907023f9cea3f284b1dcae", "content_id": "b55072fa99410d0186d037ea7e7902a206608986", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1387, "license_type": "no_license", "max_line_length": 106, "num_lines": 46, "path": "/README.md", "repo_name": "amoazeni75/multiclass-Classification-ML", "src_encoding": "UTF-8", "text": "<h1>Multiclass Classification Of Flower Species</h1>\n<p>\n In this project tutorial we will discover how we can use Keras to develop and evaluate neural\n network models for multiclass classification problems. Primary purpose of this project are:\n</p>\n<ul>\n <li>\nHow to load data from CSV and make it available to Keras.\n </li>\n <li>\nHow to prepare multiclass classification data for modeling with neural networks.\n </li>\n <li>\nHow to evaluate Keras neural network models with scikit-learn.\n </li> \n</ul>\n\n<h3>Iris Flowers Classification Dataset</h3>\n<p>\n In this project we will use the standard machine learning problem called the iris flowers dataset.\nThis dataset is well studied and is a good problem for practicing on neural networks because\nall of the 4 input variables are numeric and have the same scale in centimeters. Each instance\ndescribes the properties of an observed flower measurements and the output variable is specific\niris species. The attributes for this dataset can be summarized as follows:\n </p>\n \n <ol>\n <li>\n Sepal length in centimeters.\n </li>\n <li>\n Sepal width in centimeters.\n </li>\n <li>\n Petal length in centimeters.\n </li>\n <li>\n Petal length in centimeters.\n </li>\n <li>\n Class.\n </li>\n </ol>\n\n<p>tutorial source: Deep Learning With Python, Develop Deep Learning Models On Theano And TensorFlow Using\nKeras, Jason Brownlee</p>\n" } ]
2
pomma89/Relazione-Dessert
https://github.com/pomma89/Relazione-Dessert
4365c58f0a3d497c393f7c437466e31bd3224537
793c9051e670ae74013cf874cf8012ba4a692f78
90be8eb6b66e7074f11aa06f5fe0273c9786a9c7
refs/heads/master
2016-08-06T12:49:47.134602
2013-10-20T13:35:49
2013-10-20T13:35:49
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5634218454360962, "alphanum_fraction": 0.5634218454360962, "avg_line_length": 26.15999984741211, "blob_id": "7959aeb2e69c1b267e21d35e216c7b53a8e0caab", "content_id": "7fd7ebd9b30432336c734851376a6b99705bec5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 684, "license_type": "no_license", "max_line_length": 54, "num_lines": 25, "path": "/Listati/CSharp_Deposit_Interface.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "ISO-8859-1", "text": "interface IBank {\n /// <summary>\n /// La cifra depositata nella banca.\n /// </summary>\n double Amount { get; }\n\n /// <summary>\n /// Vero se la banca è aperta, falso altrimenti.\n /// </summary> \n bool IsOpen { get; }\n\n /// <summary>\n /// Deposita la quantità data nella banca.\n /// </summary>\n /// <param name=\"amount\">\n /// Una quantità positiva di denaro.\n /// </param>\n /// <exception cref=\"ArgumentOutOfRangeException\">\n /// La quantità è zero o negativa.\n /// </exception>\n /// <exception cref=\"InvalidOperationException\">\n /// La banca è chiusa.\n /// </exception>\n void Deposit(double amount);\n}" }, { "alpha_fraction": 0.6122047305107117, "alphanum_fraction": 0.6279527544975281, "avg_line_length": 22.136363983154297, "blob_id": "b50aaf8229302bb4451604b657aea8c66cdcd2fd", "content_id": "f13f835b0fbbe9aa8f96fca63363846fa0cf3cfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 508, "license_type": "no_license", "max_line_length": 58, "num_lines": 22, "path": "/Listati/Python_Machine_Load.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from random import *\nfrom simpy import *\n\nrand = Random(21)\nloadTime = 5 # Minuti\nworkTime = 25 # Minuti\nsimTime = 100 # Minuti\n\ndef worker(env):\n print(\"%g: Carico la macchina...\" % env.now)\n yield env.timeout(loadTime)\n env.exit(rand.choice([\"A\", \"B\", \"C\"]))\n \ndef machine(env):\n while True:\n cmd = yield env.start(worker(env))\n print(\"%g: Eseguo il compito %s\" % (env.now, cmd))\n yield env.timeout(workTime)\n\nenv = Environment()\nenv.start(machine(env))\nenv.run(simTime)" }, { "alpha_fraction": 0.5700365304946899, "alphanum_fraction": 0.5773447155952454, "avg_line_length": 27.34482765197754, "blob_id": "e097cbde0ae60bfe6e9ac28f7a1134f0c19c815c", "content_id": "21bd93ae17159df6ab61a6f22a1e438ea0017ebf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 821, "license_type": "no_license", "max_line_length": 61, "num_lines": 29, "path": "/Listati/Python_Cond_Tester.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from simpy import *\nfrom simpy.util import *\n\ndef aProcess(env):\n yield env.timeout(7)\n env.exit(\"VAL_P\")\n\ndef conditionTester(env):\n aProc = env.start(aProcess(env), \"P\")\n res = yield all_of([env.timeout(5, \"VAL_T\", \"T\"), aProc])\n print(\"ALL: %s\" % res)\n \n aProc = env.start(aProcess(env), \"P\")\n res = yield any_of([env.timeout(5, \"VAL_T\", \"T\"), aProc])\n print(\"ANY: %s\" % res)\n \n def customEval(events, values):\n return len(events) == len(values) \\\n and values[events[0]] == \"VAL_T\" \\\n and values[events[1]] == \"VAL_P\"\n \n aProc = env.start(aProcess(env), \"P\")\n aTime = env.timeout(5, \"VAL_T\", \"T\")\n res = yield Condition(env, customEval, [aTime, aProc]) \n print(\"CUSTOM: %s\" % res)\n\nenv = Environment()\nenv.start(conditionTester(env))\nenv.run()" }, { "alpha_fraction": 0.6868686676025391, "alphanum_fraction": 0.6902356743812561, "avg_line_length": 36.25, "blob_id": "f9360b5b2113e0be3d16f2ac72fd42097546ea98", "content_id": "72a3ade236045b5120d441c86b7824a588b767b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 299, "license_type": "no_license", "max_line_length": 50, "num_lines": 8, "path": "/Listati/Python_Generator_Exp.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "IBM852", "text": "def storeUser(env):\n store = Store(env, capacity=1)\n # Lo store Ŕ vuoto, per cui la chiamata\n # sottostante sarÓ bloccante. Tuttavia,\n # supponendo che qualcuno metta degli oggetti\n # nello store, su item proprio ritroveremo uno\n # di quegli oggetti.\n item = yield store.get()" }, { "alpha_fraction": 0.5676975846290588, "alphanum_fraction": 0.5786941647529602, "avg_line_length": 31.35555648803711, "blob_id": "ecab911d6de7f0e4f4374255d3d01462b9914c1c", "content_id": "611fef182fedf7dccab5999bcd751460dbdcc615", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1455, "license_type": "no_license", "max_line_length": 65, "num_lines": 45, "path": "/Listati/CSharp_TrainInterrupt.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "using IEvents = System.Collections.Generic.IEnumerable<IEvent>;\n\nstatic class TrainInterrupt {\n static readonly double AvgTravelTime;\n static readonly double BreakTime;\n\n static TrainInterrupt() {\n Sim.CurrentTimeUnit = TimeUnit.Minute;\n AvgTravelTime = 20.Minutes();\n BreakTime = 50.Minutes();\n }\n\n static IEvents Train(IEnvironment env) {\n object cause;\n string fmt;\n while (true) {\n var time = env.Random.Exponential(1.0/AvgTravelTime);\n fmt = \"Treno in viaggio per {0:.00} minuti\";\n Console.WriteLine(fmt, time);\n yield return env.Timeout(time);\n if (env.ActiveProcess.Interrupted(out cause)) \n break;\n fmt = \"Arrivo in stazione, attesa passeggeri\";\n Console.WriteLine(fmt);\n yield return env.Timeout(2.Minutes());\n if (env.ActiveProcess.Interrupted(out cause))\n break;\n }\n fmt = \"Al minuto {0:.00}: {1}\";\n Console.WriteLine(fmt, env.Now, cause);\n }\n\n static IEvents EmergencyBrake(IEnvironment env, \n IProcess train) {\n yield return env.Timeout(BreakTime);\n train.Interrupt(\"FRENO EMERGENZA\");\n }\n\n public static void Run() {\n var env = Sim.NewEnvironment(21);\n var train = env.Start(Train(env));\n env.Start(EmergencyBrake(env, train));\n env.Run();\n }\n}" }, { "alpha_fraction": 0.6009732484817505, "alphanum_fraction": 0.6034063100814819, "avg_line_length": 33.33333206176758, "blob_id": "a95f5706552175be288a3450442aca4530635fe8", "content_id": "5ec4895879e65bb674ca89158552815514287e6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 411, "license_type": "no_license", "max_line_length": 47, "num_lines": 12, "path": "/Listati/Python_Bank_Example_Pt2.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "def client(env, queue, bank, amount, get):\n global totServedClients, totWaitT, totServT\n with queue.request() as req:\n start = env.now\n yield req\n totWaitT += env.now - start\n start = env.now\n yield env.timeout(exp(avgServiceT))\n if get: yield bank.get(amount)\n else: yield bank.put(amount)\n totServT += env.now - start\n totServedClients += 1" }, { "alpha_fraction": 0.6568265557289124, "alphanum_fraction": 0.6863468885421753, "avg_line_length": 23.727272033691406, "blob_id": "84bc226e2e7de6b027dbd09dd451b1555132b05b", "content_id": "c241e85aa127128344345b85f899243c7e191574", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 271, "license_type": "no_license", "max_line_length": 42, "num_lines": 11, "path": "/Listati/Python_SimPy_StartDelayed.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from simpy import *\nfrom simpy.util import *\n\ndef myProcess(env):\n # Codice del processo...\n \nenv = Environment()\np1 = start_delayed(env, myProcess(env), 7)\np2 = start_delayed(env, myProcess(env), 3)\np3 = env.start(myProcess(env))\n# Ordine di esecuzione: p3, p2, p1" }, { "alpha_fraction": 0.6408601999282837, "alphanum_fraction": 0.6408601999282837, "avg_line_length": 22.299999237060547, "blob_id": "76a53a541cacbbcbba0623ede24c9f063e63dc80", "content_id": "7f6cec4259f4673a3d4cd4496d155a163bff9ac2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 465, "license_type": "no_license", "max_line_length": 60, "num_lines": 20, "path": "/Listati/Python_SimPy_Layer.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "import clr\nclr.AddReferenceToFile(\"Armando.exe\")\n\nimport sys\nimport Armando\n\nclass Interrupt(Exception):\n def __init__(self):\n self.cause = None\n\nclass Environment(object): \n def __new__(cls):\n object.__new__(cls)\n moveHandler = Armando.CustomMoveHandler(Interrupt())\n return moveHandler.Env\n\nclass Store(object): \n def __new__(cls, env, capacity = sys.maxint):\n object.__new__(cls)\n return env.new_store(capacity)" }, { "alpha_fraction": 0.6293333172798157, "alphanum_fraction": 0.6566666960716248, "avg_line_length": 30.27083396911621, "blob_id": "946be21a9970e8d059f7f505f7a23b3189470917", "content_id": "e277a1ac3e5d22004fb40d8159e7a5c04d7cc98c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1500, "license_type": "no_license", "max_line_length": 58, "num_lines": 48, "path": "/Listati/Python_Bank_Example.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "rand = Random(21)\nexp = lambda x: rand.expovariate(1.0/x)\n\navgIncomingT, avgServiceT = 3.0, 10.0 # Minuti\nqueueCount = 3 # Numero sportelli\nbankCap, bankLvl = 20000, 2000 # Euro\n\ntotClients, totServedClients = 0, 0\ntotWaitT, totServT = 0.0, 0.0\n\ndef client(env, queue, bank, amount, get):\n global totServedClients, totWaitT, totServT\n with queue.request() as req:\n start = env.now\n yield req\n totWaitT += env.now - start\n start = env.now\n yield env.timeout(exp(avgServiceT))\n if get: yield bank.get(amount)\n else: yield bank.put(amount)\n totServT += env.now - start\n totServedClients += 1\n \ndef spawner(env, queues, bank):\n global totClients\n while True:\n yield env.timeout(exp(avgIncomingT))\n queue = min(queues, key=lambda q:len(q.queue))\n amount = rand.uniform(50, 500)\n get = rand.random() < 0.4\n env.start(client(env, queue, bank, amount, get))\n totClients += 1\n\nenv = Environment()\nqueues = [Resource(env, 1) for i in range(queueCount)]\nbank = Container(env, bankCap, bankLvl)\n\nenv.start(spawner(env, queues, bank))\nenv.run(until=5*60)\n\nlvl = bank.level\nprint(\"Finanze totali al tempo %.2f: %d\" % (env.now, lvl))\nprint(\"Clienti entrati: %d\" % totClients)\nprint(\"Clienti serviti: %d\" % totServedClients)\navgWait = totWaitT/totServedClients\nprint(\"Tempo medio di attesa: %.2f\" % avgWait)\navgServ = totServT/totServedClients\nprint(\"Tempo medio di servizio: %.2f\" % avgServ)" }, { "alpha_fraction": 0.6859344840049744, "alphanum_fraction": 0.7167630195617676, "avg_line_length": 36.14285659790039, "blob_id": "187e5fcccc35cd11465ea49bb2758f74deb52836", "content_id": "a2347f11605719bb1ce2bb9789e3354f4d5cb2e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 519, "license_type": "no_license", "max_line_length": 55, "num_lines": 14, "path": "/Listati/CSharp_Random_NoTRandom.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "// Generiamo tre numeri casuali aventi una\n// distribuzione esponenziale, con 5 come media.\nvar exponential = new ExponentialDistribution(1.0/5.0);\nConsole.WriteLine(\"Exponential:\");\nfor (var i = 0; i < 3; ++i)\n Console.WriteLine(exponential.NextDouble());\n\n// Generiamo tre numeri casuali aventi una\n// distribuzione normale, con 7 come media\n// e 0.5 come varianza.\nvar normal = new NormalDistribution(7.0, 0.5);\nConsole.WriteLine(\"Normal:\");\nfor (var i = 0; i < 3; ++i)\n Console.WriteLine(normal.NextDouble());" }, { "alpha_fraction": 0.596783459186554, "alphanum_fraction": 0.6260769963264465, "avg_line_length": 59.068965911865234, "blob_id": "565975687d675a5eadd4e5f65b05b8d3539eeac8", "content_id": "4d5af583910d94ca8272602b1cfca9585e552633", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1741, "license_type": "no_license", "max_line_length": 108, "num_lines": 29, "path": "/Benchmark/galois-plot-gen.sh", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "TITLE_GENERAL=\"Completion time for a P2P simulation\"\nXLABEL=\"Number of active machines\"\nYLABEL=\"Minutes\"\n\nOUTPUT_FILE=\"galois-plot1.png\"\necho -e \"set terminal png enhanced giant size 640, 480\\n set out '\"$OUTPUT_FILE\"'\\n\n\t\tset title \\\"\"$TITLE_GENERAL\"\\\"\\n\n\t\tset key left top\\n\n\t\tset xlabel \\\"\"$XLABEL\"\\\"\\n\n\t\tset ylabel \\\"\"$YLABEL\"\\\"\\n\n\t\tplot \\\"\"galois-plot-data1.txt\"\\\" using 1:2 title \\\"\"Dessert \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"galois-plot-data1.txt\"\\\" using 1:3 title \\\"\"Dessert \\(Windows\\)\"\\\" with lines, \\\n\t\t \\\"\"galois-plot-data1.txt\"\\\" using 1:4 title \\\"\"Armando \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"galois-plot-data1.txt\"\\\" using 1:5 title \\\"\"Armando \\(Windows\\)\"\\\" with lines, \\\n\t\t \\\"\"galois-plot-data1.txt\"\\\" using 1:6 title \\\"\"SimPy \\(Ubuntu, with threads\\)\"\\\" with lines, \\\n\t\t \\\"\"galois-plot-data1.txt\"\\\" using 1:7 title \\\"\"SimPy \\(Windows, with threads\\)\"\\\" with lines, \\\n\t\t \\\"\"galois-plot-data1.txt\"\\\" using 1:8 title \\\"\"SimPy \\(Ubuntu, no threads\\)\"\\\" with lines, \\\n\t\t \\\"\"galois-plot-data1.txt\"\\\" using 1:9 title \\\"\"SimPy \\(Windows, no threads\\)\"\\\" with lines\" | gnuplot\n\t\t \nOUTPUT_FILE=\"galois-plot2.png\"\necho -e \"set terminal png enhanced giant size 640, 480\\n set out '\"$OUTPUT_FILE\"'\\n\n\t\tset title \\\"\"$TITLE_GENERAL\"\\\"\\n\n\t\tset key left top\\n\n\t\tset xlabel \\\"\"$XLABEL\"\\\"\\n\n\t\tset ylabel \\\"\"$YLABEL\"\\\"\\n\n\t\tplot \\\"\"galois-plot-data2.txt\"\\\" using 1:2 title \\\"\"Dessert \\(with checks\\)\"\\\" with lines, \\\n\t\t \\\"\"galois-plot-data2.txt\"\\\" using 1:3 title \\\"\"Dessert \\(without checks\\)\"\\\" with lines, \\\n\t\t \\\"\"galois-plot-data2.txt\"\\\" using 1:4 title \\\"\"Armando \\(with checks\\)\"\\\" with lines, \\\n\t\t \\\"\"galois-plot-data2.txt\"\\\" using 1:5 title \\\"\"Armando \\(without checks\\)\"\\\" with lines\" | gnuplot" }, { "alpha_fraction": 0.5681415796279907, "alphanum_fraction": 0.5858407020568848, "avg_line_length": 22.58333396911621, "blob_id": "05f9a2c3c1c5b9092f628c83b34a2ba74646890c", "content_id": "6b08105c2ca8f9d24bd117bb2764e166fea9bda4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 565, "license_type": "no_license", "max_line_length": 59, "num_lines": 24, "path": "/Listati/Python_Target_Shooting.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from random import *\nfrom simpy import *\n\nrand = Random(21)\nhitProb = 0.7\nsimTime = 100 # Secondi\n\ndef newTarget(env):\n delay = rand.uniform(1, 20)\n target = rand.choice([\"Alieno\", \"Pollo\", \"Unicorno\"])\n return env.timeout(delay, target)\n\ndef shooter(env):\n while True:\n tgt = yield newTarget(env)\n hit = rand.random();\n if hit < hitProb:\n print(\"%g: %s colpito, si!\" % (env.now, tgt))\n else:\n print(\"%g: %s mancato, no...\" % (env.now, tgt))\n\nenv = Environment()\nenv.start(shooter(env))\nenv.run(simTime)" }, { "alpha_fraction": 0.5970149040222168, "alphanum_fraction": 0.608208954334259, "avg_line_length": 23.454545974731445, "blob_id": "ba848c5eaf20298f63b1fd11d6a009818ef04dbe", "content_id": "f033f4ad7c94bf9d4ce547c71dafee0bac6ca947", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 268, "license_type": "no_license", "max_line_length": 56, "num_lines": 11, "path": "/Listati/CSharp_DelayedStart.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "IEnumerable<IEvent> Process(IEnvironment env, char id) {\n Console.WriteLine(\"{0}: {1}\", id, env.Now);\n yield break;\n}\n\nvoid Run() {\n var env = Sim.NewEnvironment();\n env.StartDelayed(Process(env, 'A'), 7);\n env.Start(Process(env, 'B'));\n env.Run();\n}" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6225806474685669, "avg_line_length": 30.03333282470703, "blob_id": "2314990eb8599fa0e6e23deeabba8042934f61b5", "content_id": "629881344071232432477f35021e92e45246ddd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 930, "license_type": "no_license", "max_line_length": 60, "num_lines": 30, "path": "/Listati/Python_Public_Toilet.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from random import *\nfrom simpy import *\n\nrand = Random(21)\navgPersonArrival, avgTimeInToilet = 1.0, 5.0 # Minuti\nsimTime = 10 # Minuti\nexponential = rand.expovariate\n\ndef person(env, gender, toilet):\n with toilet.request() as req:\n yield req\n print(\"%.2f: %s --> Bagno\" % (env.now, gender))\n yield env.timeout(exponential(1.0/avgTimeInToilet))\n print(\"%.2f: %s <-- Bagno\" % (env.now, gender)) \n\ndef personGenerator(env):\n womenTt, menTt = Resource(env, 1), Resource(env, 1)\n id = 0\n while True:\n isWoman = rand.random() < 0.5\n gender = (\"Donna\" if isWoman else \"Uomo\") + str(id)\n toilet = womenTt if isWoman else menTt\n id += 1\n print(\"%.2f: %s in coda\" % (env.now, gender))\n env.start(person(env, gender, toilet))\n yield env.timeout(exponential(1.0/avgPersonArrival))\n\nenv = Environment()\nenv.start(personGenerator(env))\nenv.run(simTime)" }, { "alpha_fraction": 0.5659655928611755, "alphanum_fraction": 0.5783938765525818, "avg_line_length": 26.552631378173828, "blob_id": "5d9af16420e60739b2abd1755e8190455ce09066", "content_id": "1b7227376b213085f001a00991746a8422904651", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1046, "license_type": "no_license", "max_line_length": 60, "num_lines": 38, "path": "/Listati/CSharp_FibonacciProducerConsumer.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "IEnumerable<IEvent> FibonacciFunc(IEnvironment env, int n) {\n if (n <= 0) yield return env.Exit(0);\n else if (n == 1) yield return env.Exit(1);\n else {\n var call = env.Call<int>(FibonacciFunc(env, n - 1));\n yield return call;\n var n1 = call.Value;\n call = env.Call<int>(FibonacciFunc(env, n - 2));\n yield return call;\n var n2 = call.Value;\n yield return env.Exit(n1 + n2);\n }\n}\n\nIEnumerable<IEvent> Producer(IEnvironment env, \n IStore<int> store, int n)\n{\n var call = env.Call<int>(FibonacciFunc(env, n));\n yield return call;\n store.Put(call.Value);\n}\n\nIEnumerable<IEvent> Consumer(IStore<int> store) {\n var getEv = store.Get();\n yield return getEv;\n Console.WriteLine(getEv.Value);\n}\n\nvoid Run() {\n const int count = 10;\n var env = Sim.NewEnvironment();\n var store = env.NewStore<int>();\n for (var i = 0; i < count; ++i) {\n env.Start(Producer(env, store, i));\n env.Start(Consumer(store));\n }\n env.Run();\n}" }, { "alpha_fraction": 0.695652186870575, "alphanum_fraction": 0.695652186870575, "avg_line_length": 37.41666793823242, "blob_id": "667c71573199732bca4ad0a16b00369ba608496d", "content_id": "55a4244f981d30fe91c211a2e9cdf76c4fbb5f30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 461, "license_type": "no_license", "max_line_length": 54, "num_lines": 12, "path": "/Listati/CSharp_Default_MoveHandler.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "ISO-8859-1", "text": "SimEvent DefaultMoveHandler(SimProcess process, \n SimEvent oldTarget)\n{\n if (!process.Steps.MoveNext()) return EndEvent;\n // Dobbiamo controllare che l'evento restituito\n // sia stato generato da questa libreria,\n // poiché dobbiamo essere in grado di\n // convertirlo al tipo SimEvent.\n var newTarget = process.Steps.Current as SimEvent;\n Raise<ArgumentNullException>.IfIsNull(newTarget);\n return newTarget;\n}" }, { "alpha_fraction": 0.5557047128677368, "alphanum_fraction": 0.563758373260498, "avg_line_length": 22.3125, "blob_id": "8c623f0da5fd5f68f039f9503faf58c40bbde4ab", "content_id": "aef3143c78fe6ad0ed76cfab4426b9ab6fd0e82b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 745, "license_type": "no_license", "max_line_length": 56, "num_lines": 32, "path": "/Listati/CSharp_Hippie_IHeap.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "interface IHeap<V, P>\n : ICollection<IHeapHandle<V, P>>\n{\n IComparer<P> Comparer { get; } \n IEqualityComparer<V> EqualityComparer { get; } \n int MaxCapacity { get; } \n IHeapHandle<V, P> Min { get; } \n P this[V val] { get; set; }\n\n void Add(V val, P pr);\n \n bool Contains(V val);\n \n bool Contains(V val, P pr);\n \n void Merge<V2, P2>(IHeap<V2, P2> other) \n where V2 : V where P2 : P;\n \n P PriorityOf(V val);\n \n IHeapHandle<V, P> Remove(V val);\n \n IHeapHandle<V, P> RemoveMin();\n \n P Update(V val, V newVal, P newPr);\n \n P UpdatePriorityOf(V val, P newPr);\n \n void UpdateValue(V val, V newVal);\n \n IEnumerable<IReadOnlyTree<V, P>> ToReadOnlyForest();\n}" }, { "alpha_fraction": 0.5554545521736145, "alphanum_fraction": 0.5654545426368713, "avg_line_length": 29.58333396911621, "blob_id": "bb3182b63993ee72b8a86c1f3bda72558ed4ea49", "content_id": "24c60c824386827566e14df8e423244cab9789ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1100, "license_type": "no_license", "max_line_length": 60, "num_lines": 36, "path": "/Listati/CSharp_MachineLoad.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "static class MachineLoad {\n static readonly string[] Tasks = {\"A\", \"B\", \"C\"};\n static readonly double LoadTime;\n static readonly double WorkTime;\n static readonly double SimTime;\n\n static MachineLoad() {\n Sim.CurrentTimeUnit = TimeUnit.Minute;\n LoadTime = 5.Minutes();\n WorkTime = 25.Minutes();\n SimTime = 100.Minutes();\n }\n\n static IEnumerable<IEvent> Worker(IEnvironment env) {\n Console.WriteLine(\"{0}: Carico la macchina...\", \n env.Now);\n yield return env.Timeout(LoadTime);\n env.Exit(env.Random.Choice(Tasks));\n }\n\n static IEnumerable<IEvent> Machine(IEnvironment env) {\n while (true) {\n var worker = env.Start(Worker(env));\n yield return worker;\n Console.WriteLine(\"{0}: Eseguo il comando {1}\", \n env.Now, worker.Value);\n yield return env.Timeout(WorkTime);\n }\n }\n\n public static void Run() {\n var env = Sim.NewEnvironment(21);\n env.Start(Machine(env));\n env.Run(SimTime);\n }\n}" }, { "alpha_fraction": 0.5464654564857483, "alphanum_fraction": 0.5583796501159668, "avg_line_length": 34, "blob_id": "7b3d5ae685b5047eae0325280d0509a6096a02f7", "content_id": "ce071933bbfe9dbe74524d05b4794557a7ed540c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1259, "license_type": "no_license", "max_line_length": 61, "num_lines": 36, "path": "/Listati/CSharp_ConditionTester.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "static class ConditionTester {\n static IEnumerable<IEvent> AProcess(IEnvironment env) {\n yield return env.Timeout(7);\n env.Exit(\"VAL_P\");\n }\n\n static IEnumerable<IEvent> CondTester(IEnvironment env) {\n var t1 = env.NamedTimeout(5, \"VAL_T\", \"T\");\n var aProc = env.Start(AProcess(env), name: \"P\");\n var cond = env.AllOf(t1, aProc);\n yield return cond;\n Console.WriteLine(\"ALL: {0}\", cond.Value);\n \n var t2 = env.NamedTimeout(5, \"VAL_T\", \"T\");\n aProc = env.Start(AProcess(env), name: \"P\");\n cond = env.AnyOf(t2, aProc);\n yield return cond;\n Console.WriteLine(\"ANY: {0}\", cond.Value);\n\n aProc = env.Start(AProcess(env), name: \"P\");\n var aTime = env.NamedTimeout(5, \"VAL_T\", \"T\");\n ConditionEval<ITimeout<string>, IProcess> pred =\n c => c.Ev1.Succeeded && c.Ev2.Succeeded && \n c.Ev1.Value.Equals(\"VAL_T\") && \n c.Ev2.Value.Equals(\"VAL_P\");\n cond = env.Condition(aTime, aProc, pred);\n yield return cond;\n Console.WriteLine(\"CUSTOM: {0}\", cond.Value);\n }\n\n public static void Run() {\n var env = Sim.NewEnvironment();\n env.Start(CondTester(env));\n env.Run();\n }\n}" }, { "alpha_fraction": 0.632523775100708, "alphanum_fraction": 0.6420274376869202, "avg_line_length": 26.08571434020996, "blob_id": "63b01abe5d2b75d45c8844e1dd27780fc7990ed3", "content_id": "cd7459031340c89b8d1ce1c9e7f8e392ade48668", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 947, "license_type": "no_license", "max_line_length": 59, "num_lines": 35, "path": "/Listati/Python_Water_Drinkers.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from simpy import *\n\nboxCapacity = 1 # Litri\nglassCapacity = 0.25 # Litri\nfillBox = None\n\ndef filler(env, box):\n global fillBox\n while True:\n yield box.put(boxCapacity - box.level)\n fillBox = env.event()\n id = yield fillBox\n print(\"%d: %d chiama tecnico\" % (env.now, id))\n\ndef drinker(env, id, box):\n # Occorre controllare che l'evento fillBox non sia gia'\n # stato attivato, perche' attivarlo nuovamente\n # risulterebbe in una eccezione da parte di SimPy.\n if box.level < glassCapacity and not fillBox.triggered:\n fillBox.succeed(id) \n yield box.get(glassCapacity)\n print(\"%d: %d ha bevuto!\" % (env.now, id))\n\ndef spawner(env, box):\n id = 0\n while True:\n yield env.timeout(5)\n env.start(drinker(env, id, box))\n id += 1\n\nenv = Environment()\nbox = Container(env, capacity=boxCapacity)\nenv.start(filler(env, box))\nenv.start(spawner(env, box))\nenv.run(until=31)" }, { "alpha_fraction": 0.6991341710090637, "alphanum_fraction": 0.7294372320175171, "avg_line_length": 32.07143020629883, "blob_id": "272c77480cfc427cdefca0155d21d0e9bb75d63c", "content_id": "6784d81597e1178e0bec7f61abd99377e34a5780", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 462, "license_type": "no_license", "max_line_length": 59, "num_lines": 14, "path": "/Listati/CSharp_Random_FluentTRandom.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "var rand = new TRandom();\n\n// Generiamo tre numeri casuali aventi una\n// distribuzione esponenziale, con 5 come media.\nConsole.WriteLine(\"Exponential:\");\nforeach (var e in rand.ExponentialSamples(1.0/5.0).Take(3))\n Console.WriteLine(e);\n\n// Generiamo tre numeri casuali aventi una\n// distribuzione normale, con 7 come media\n// e 0.5 come varianza.\nConsole.WriteLine(\"Normal:\");\nforeach (var n in rand.NormalSamples(7.0, 0.5).Take(3))\n Console.WriteLine(n);" }, { "alpha_fraction": 0.5701415538787842, "alphanum_fraction": 0.5727155804634094, "avg_line_length": 30.079999923706055, "blob_id": "6eed9413e0ec4306675f35ba06fed9fd23f5045e", "content_id": "b8a3895ec6530537f397bbff924c546868e620c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 780, "license_type": "no_license", "max_line_length": 61, "num_lines": 25, "path": "/Listati/CSharp_Deposit_ContractClass.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "ISO-8859-1", "text": "// Per rendere lo script più sintetico...\nusing IOP = System.InvalidOperationException;\nusing AOR = System.ArgumentOutOfRangeException;\n\n[ContractClassFor(typeof(IBank))]\nabstract class BankContract {\n double Amount { \n get {\n Contract.Ensures(Contract.Result<double>() >= 0);\n return default(double);\n }\n }\n \n // Non si definisce un particolare contratto\n abstract bool IsOpen { get; }\n \n void Deposit(double amount) {\n Contract.Requires<IOP>(IsOpen, \n \"La banca è chiusa\");\n Contract.Requires<AOR>(amount > 0, \n \"Quantità non positiva\");\n Contract.Ensures(Amount == \n Contract.OldValue(Amount) + amount);\n }\n}\n" }, { "alpha_fraction": 0.489533007144928, "alphanum_fraction": 0.49597424268722534, "avg_line_length": 23.8799991607666, "blob_id": "d57fd708f67f964a89388151ab0fc626382b9240", "content_id": "1f7467c4410bd30f9720c2e85ab14c0b4ca4376e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 621, "license_type": "no_license", "max_line_length": 44, "num_lines": 25, "path": "/Listati/Python_Generator_SimCore.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from heapq import *\n\nclass Process:\n def __init__(self, gen, time):\n self.gen = gen\n self.time = time\n \n def __cmp__(self, other):\n return self.time.__cmp__(other.time)\n \nclass Environment:\n def __init__(self):\n self._agenda = []\n self._now = 0.0\n \n def start(self, gen):\n p = Process(gen, self._now)\n heappush(self._agenda, p)\n \n def simulate(self):\n while len(self._agenda) > 0:\n p = self._agenda[0]\n p.gen.next()\n # Modifica dello heap a seconda\n # dello stato di p dopo il next." }, { "alpha_fraction": 0.502136766910553, "alphanum_fraction": 0.5149572491645813, "avg_line_length": 25.77142906188965, "blob_id": "9ccca1af19310a03e6c85ec167f522dbc77a2820", "content_id": "8cfec1992e6addff1afafb2d2f1bdc2b63827c63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 936, "license_type": "no_license", "max_line_length": 60, "num_lines": 35, "path": "/Listati/CSharp_EventTrigger.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "static class EventTrigger {\n static IEnumerable<IEvent> DoSucceed(IEnvironment env, \n IEvent<object> ev)\n {\n yield return env.Timeout(5);\n ev.Succeed(\"SI :)\");\n }\n\n static IEnumerable<IEvent> DoFail(IEnvironment env, \n IEvent<object> ev)\n {\n yield return env.Timeout(5);\n ev.Fail(\"NO :(\");\n }\n\n static IEnumerable<IEvent> Proc(IEnvironment env) {\n var ev1 = env.Event();\n env.Start(DoSucceed(env, ev1));\n yield return ev1;\n if (ev1.Succeeded)\n Console.WriteLine(ev1.Value);\n\n var ev2 = env.Event();\n env.Start(DoFail(env, ev2));\n yield return ev2;\n if (ev2.Failed)\n Console.WriteLine(ev2.Value);\n }\n\n public static void Run() {\n var env = Sim.NewEnvironment();\n env.Start(Proc(env));\n env.Run();\n }\n}" }, { "alpha_fraction": 0.6571428775787354, "alphanum_fraction": 0.6571428775787354, "avg_line_length": 37, "blob_id": "30be58dbfd84875116161b1f9d91558df98cf901", "content_id": "7c0be98021624585ad5f8ca8cbcd0293120ab53e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 455, "license_type": "no_license", "max_line_length": 60, "num_lines": 12, "path": "/Listati/CSharp_GeneratorTransform.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "Type TW = typeof(IEnumerableOfTWrapper<IEvent>);\nFieldInfo Generator = TW.GetField(\"enumerable\",\n BindingFlags.Instance |\n BindingFlags.NonPublic);\n\nIEnumerable GenTransformer(IEnumerable<IEvent> generator)\n{\n if (generator is IEnumerableOfTWrapper<IEvent>)\n return Generator.GetValue(generator) as IEnumerable;\n // Caso speciale per il processo Until.\n return generator;\n}" }, { "alpha_fraction": 0.4060606062412262, "alphanum_fraction": 0.41818180680274963, "avg_line_length": 17.44444465637207, "blob_id": "15d977df69ce4005f378be51c88174cc1b6c33f4", "content_id": "e3a1bfb6ccf61632a7fab600b7bdcdb6f0e19e04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 165, "license_type": "no_license", "max_line_length": 30, "num_lines": 9, "path": "/Listati/CSharp_Yield.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "IEnumerable<int> Fibonacci() {\n int a = 1, b = 0;\n while (true) {\n yield return a;\n b = a + b;\n yield return b;\n a = a + b;\n }\n}" }, { "alpha_fraction": 0.6247379183769226, "alphanum_fraction": 0.6268343925476074, "avg_line_length": 28.875, "blob_id": "a761f42a7134e4b412be7145f49d9a37f022781e", "content_id": "a3a669a8e2c4621ba1847a1edf42f7f4e8acbcb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 480, "license_type": "no_license", "max_line_length": 51, "num_lines": 16, "path": "/Listati/CSharp_Deposit_Standard.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "ISO-8859-1", "text": "// Per rendere lo script più sintetico...\nusing IOP = System.InvalidOperationException;\nusing AOR = System.ArgumentOutOfRangeException;\n\nclass MyBank : IBank {\n public double Amount { get; private set; }\n public bool IsOpen { get; private set; }\n \n public void Deposit(double amount) {\n if (!IsOpen)\n throw new IOP(\"La banca è chiusa\");\n if (amount <= 0)\n throw new AOR(\"Quantità non positiva\");\n Amount += amount;\n }\n}" }, { "alpha_fraction": 0.6185897588729858, "alphanum_fraction": 0.6314102411270142, "avg_line_length": 24, "blob_id": "00590882c770413ecb400e52254b8b4cbc505db6", "content_id": "c2842e39301eadcda681f129688a2d212cfdf132", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 624, "license_type": "no_license", "max_line_length": 54, "num_lines": 25, "path": "/Listati/Python_Producer_Consumer.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from random import *\nfrom simpy import *\n\nrand = Random(21)\ndef randInt(): return rand.randint(1, 20)\n\ndef producer(env, store):\n while True:\n yield env.timeout(randInt())\n item = randInt()\n yield store.put(item)\n print(\"%d: Prodotto un %d\" % (env.now, item))\n\ndef consumer(env, store):\n while True:\n yield env.timeout(randInt())\n item = yield store.get()\n print(\"%d: Consumato un %d\" % (env.now, item))\n\nenv = Environment()\nstore = Store(env, capacity=2)\nenv.start(producer(env, store))\nenv.start(producer(env, store))\nenv.start(consumer(env, store))\nenv.run(until=60)" }, { "alpha_fraction": 0.6583333611488342, "alphanum_fraction": 0.6645833253860474, "avg_line_length": 33.35714340209961, "blob_id": "12b1d9a6d1bc80b93f390036f6fe64bffffcd3ec", "content_id": "51c4a065a6011ce622d49c4cd9377466522b447b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 486, "license_type": "no_license", "max_line_length": 54, "num_lines": 14, "path": "/Listati/Python_UntypedStore.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "ISO-8859-1", "text": "def consumer(env, stringStore):\n while True:\n msg = yield stringStore.get()\n print(\"First char of message: %c\" % msg[0])\n # La prima iterazione è OK, stamperà \"P\".\n # Tuttavia, si avrà un crash per la seconda,\n # poiché un intero non è indicizzabile.\n\nenv = Environment()\nstringStore = Store(env)\nstringStore.put(\"PINO\") # Una stringa è OK\nstringStore.put(21) # Ops, abbiamo inserito un intero!\nenv.start(consumer(env, stringStore))\nenv.run()" }, { "alpha_fraction": 0.6029216647148132, "alphanum_fraction": 0.6029216647148132, "avg_line_length": 33.272727966308594, "blob_id": "7f4efb27c788bab11de3dee0c8ce439d6c2dd63e", "content_id": "f702aaf415e4a5b7f29e5ccfa6686b906e264e70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 753, "license_type": "no_license", "max_line_length": 60, "num_lines": 22, "path": "/Listati/CSharp_Custom_MoveHandler.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "SimEvent MoveHandler(SimProcess process, SimEvent oldTarget)\n{\n var gen = process.Generator as PythonGenerator;\n if (gen != null) {\n dynamic next;\n object cause;\n if (Env.ActiveProcess.Interrupted(out cause)) {\n _interrupt.cause = cause;\n next = gen.@throw(_interrupt);\n } else if (oldTarget == null)\n next = gen.send(null);\n else if (oldTarget.Failed)\n next = gen.@throw(oldTarget.Value);\n else\n next = gen.send(oldTarget.Value);\n return (next as SimEvent) ?? Env.EndEvent;\n }\n // Caso speciale per il processo Until.\n var hasNext = process.Steps.MoveNext();\n Debug.Assert(hasNext);\n return process.Steps.Current as SimEvent;\n}" }, { "alpha_fraction": 0.6556122303009033, "alphanum_fraction": 0.6556122303009033, "avg_line_length": 22.117647171020508, "blob_id": "30b477d9e967556611534d03e5cbabbdd1b953ec", "content_id": "2a5384d8f1733c63491255d64c626fd47fedaa55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 392, "license_type": "no_license", "max_line_length": 52, "num_lines": 17, "path": "/Listati/CSharp_EventFailure.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "IEnumerable<IEvent> EventFailer(IEvent<string> ev) {\n ev.Fail(\"SOMETHING BAD HAPPENED\");\n yield break;\n}\n\nIEnumerable<IEvent> Process(IEnvironment env) {\n var ev = env.Event<string>();\n env.Start(EventFailer(ev));\n yield return ev;\n if (ev.Failed) Console.WriteLine(ev.Value);\n}\n\nvoid Run() {\n var env = Sim.NewEnvironment();\n env.Start(Process(env));\n env.Run();\n}" }, { "alpha_fraction": 0.5795180797576904, "alphanum_fraction": 0.5963855385780334, "avg_line_length": 28.678571701049805, "blob_id": "37c13ad69cf47491a1df77cf2188c07066c370e6", "content_id": "2379f72037062cfa8c99b168d864c72bd5b920d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 830, "license_type": "no_license", "max_line_length": 59, "num_lines": 28, "path": "/Listati/CSharp_DataRecording.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "IEnumerable<IEvent> Person(IEnvironment env, \n IResource queue, ITally rec)\n{\n using (var req = queue.Request()) {\n var startTime = env.Now;\n yield return req;\n rec.Observe(env.Now - startTime);\n var workTime = env.Random.Next(3, 10);\n yield return env.Timeout(workTime);\n }\n}\n\nIEnumerable<IEvent> Spawner(IEnvironment env, ITally rec) {\n var queue = env.NewResource(2);\n while (true) {\n env.Start(Person(env, queue, rec));\n yield return env.Timeout(env.Random.Next(2, 5));\n }\n}\n\nvoid Run() {\n var env = Sim.NewEnvironment(seed: 42);\n var rec = env.NewTally();\n env.Start(Spawner(env, rec));\n env.Run(2*60);\n Console.WriteLine(\"Totale clienti: {0}\", rec.Total());\n Console.WriteLine(\"Attesa media: {0:.0}\", rec.Mean());\n}" }, { "alpha_fraction": 0.5159051418304443, "alphanum_fraction": 0.5344129800796509, "avg_line_length": 33.599998474121094, "blob_id": "eb8a6385b3d0d1f0dad1c31f9d3bd442bee602ac", "content_id": "da725d49d6f644c42601c515af369de3c5b6eeba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1729, "license_type": "no_license", "max_line_length": 65, "num_lines": 50, "path": "/Listati/CSharp_PublicToilet.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "using IEvents = System.Collections.Generic.IEnumerable<IEvent>;\n\nstatic class PublicToilet {\n static readonly double AvgPersonArrival;\n static readonly double AvgTimeInToilet;\n static readonly double SimTime;\n\n static PublicToilet() {\n Sim.CurrentTimeUnit = TimeUnit.Minute;\n AvgPersonArrival = 1.Minutes();\n AvgTimeInToilet = 5.Minutes();\n SimTime = 10.Minutes();\n }\n\n static IEvents Person(IEnvironment env, \n string gender, \n IResource toilet) {\n using (var req = toilet.Request()) {\n yield return req;\n Console.WriteLine(\"{0:0.00}: {1} --> Bagno\", \n env.Now, gender);\n var t = env.Random.Exponential(1.0/AvgTimeInToilet);\n yield return env.Timeout(t);\n Console.WriteLine(\"{0:0.00}: {1} <-- Bagno\", \n env.Now, gender);\n }\n }\n\n static IEvents PersonGenerator(IEnvironment env) {\n var womenToilet = env.NewResource(1);\n var menToilet = env.NewResource(1);\n var count = 0;\n while (true) {\n var rnd = env.Random.NextDouble();\n var gn = ((rnd<0.5) ? \"Donna\" : \"Uomo\") + count++;\n var tt = (rnd<0.5) ? womenToilet : menToilet;\n Console.WriteLine(\"{0:0.00}: {1} in coda\", \n env.Now, gn);\n env.Start(Person(env, gn, tt));\n var t = env.Random.Exponential(1.0/AvgPersonArrival);\n yield return env.Timeout(t);\n }\n }\n\n public static void Run() {\n var env = Sim.NewEnvironment(21);\n env.Start(PersonGenerator(env));\n env.Run(SimTime);\n }\n}" }, { "alpha_fraction": 0.6824877262115479, "alphanum_fraction": 0.6890343427658081, "avg_line_length": 31.210525512695312, "blob_id": "e3a636607ec58bfea9cbe2c1d122d0c806cb7002", "content_id": "f0d00253629b8f47cd7d58c817d85ca6cf991766", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 611, "license_type": "no_license", "max_line_length": 52, "num_lines": 19, "path": "/Listati/Python_Hospital.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from simpy import *\n\n# Priorita' decrescenti, piu' una priorita' e' bassa\n# prima il processo sara' posizionato nella coda.\nRED, YELLOW, GREEN = 0, 1, 2\n\ndef person(env, name, code, hospital):\n with hospital.request(code) as req:\n yield req\n print(\"%s viene curato...\" % name) \n\nenv = Environment()\nhospital = PriorityResource(env, capacity=2)\nenv.start(person(env, \"Pino\", YELLOW, hospital))\nenv.start(person(env, \"Gino\", GREEN, hospital))\nenv.start(person(env, \"Nino\", GREEN, hospital))\nenv.start(person(env, \"Dino\", YELLOW, hospital))\nenv.start(person(env, \"Tino\", RED, hospital))\nenv.run()" }, { "alpha_fraction": 0.591230571269989, "alphanum_fraction": 0.605374813079834, "avg_line_length": 25.22222137451172, "blob_id": "641258209109a47f730e4e61a23024b042e78d95", "content_id": "bca7ce93b39818061643378596cfe9838509ef08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 707, "license_type": "no_license", "max_line_length": 58, "num_lines": 27, "path": "/Listati/Python_Train_Interrupt.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from random import *\nfrom simpy import *\n\nrand = Random(21)\navgTravelTime = 20.0 # Minuti\nbreakTime = 50 # Minuti\n\ndef train(env):\n while True:\n try:\n time = rand.expovariate(1.0/avgTravelTime)\n print(\"Treno in viaggio per %g minuti\" % time)\n yield env.timeout(time)\n print(\"Arrivo in stazione, attesa passeggeri\")\n yield env.timeout(2)\n except Interrupt, i:\n print(\"Al minuto %g: %s\" % (env.now, i.cause))\n break\n \ndef emergencyBrake(env, tr):\n yield env.timeout(breakTime)\n tr.interrupt(\"FRENO EMERGENZA\")\n\nenv = Environment()\ntr = env.start(train(env))\nenv.start(emergencyBrake(env, tr))\nenv.run()" }, { "alpha_fraction": 0.6639566421508789, "alphanum_fraction": 0.6653116345405579, "avg_line_length": 29.79166603088379, "blob_id": "6a7978849f64053adf4d7022ea1b355127106e3c", "content_id": "f54eeff1f4c0d70999346aa6867999762a9ce903", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 739, "license_type": "no_license", "max_line_length": 62, "num_lines": 24, "path": "/Listati/CSharp_InterruptHandling.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "ISO-8859-1", "text": "IEnumerable<IEvent> Interrupter(IProcess victim) {\n victim.Interrupt(\"NOW\");\n yield break;\n}\n\nIEnumerable<IEvent> Process(IEnvironment env) { \n yield return env.Start(Interrupter(env.ActiveProcess));\n object cause;\n if (env.ActiveProcess.Interrupted(out cause))\n Console.WriteLine(\"Interrupted at: \" + cause); \n \n // Le seguenti istruzioni sono commentate, poiché\n // darebbero origine a un'eccezione. Infatti,\n // il secondo segnale di interrupt non sarebbe catturato.\n //\n // yield return env.Start(Interrupter(env.ActiveProcess));\n // yield return env.Timeout(5);\n}\n\nvoid Run() {\n var env = Sim.NewEnvironment();\n env.Start(Process(env), \"INTERRUPTED\");\n env.Run();\n}" }, { "alpha_fraction": 0.7235954999923706, "alphanum_fraction": 0.7370786666870117, "avg_line_length": 33.30769348144531, "blob_id": "10c695c3fb182b2bb5d9132c65f077bb4d23700c", "content_id": "5b32746743c1fc3b1d4463aa19cf4f43eac6f6d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 445, "license_type": "no_license", "max_line_length": 58, "num_lines": 13, "path": "/Listati/Python_Bank_Example_Pt4.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "# Avvio della simulazione\nenv.start(spawner(env, queues, bank))\nenv.run(until=5*60)\n\n# Raccolta dati statistici\nlvl = bank.level\nprint(\"Finanze totali al tempo %.2f: %d\" % (env.now, lvl))\nprint(\"Clienti entrati: %d\" % totClients)\nprint(\"Clienti serviti: %d\" % totServedClients)\navgWait = totWaitT/totServedClients\nprint(\"Tempo medio di attesa: %.2f\" % avgWait)\navgServ = totServT/totServedClients\nprint(\"Tempo medio di servizio: %.2f\" % avgServ)" }, { "alpha_fraction": 0.6147651076316833, "alphanum_fraction": 0.6308724880218506, "avg_line_length": 27.69230842590332, "blob_id": "c12751b0ae61ad4e17409d7e5f7d28d165325dde", "content_id": "e6775e01c1093d1880de541dc3e3f7f564ca2b74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 745, "license_type": "no_license", "max_line_length": 62, "num_lines": 26, "path": "/Listati/Python_Producer_Consumer_Filter.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from random import *\nfrom simpy import *\n\nrand = Random(63)\ndef randInt(): return rand.randint(1, 20)\n\ndef producer(env, store):\n while True:\n yield env.timeout(randInt())\n item = randInt()\n yield store.put(item)\n print(\"%d: Prodotto un %d\" % (env.now, item))\n\ndef consumer(env, store, name, filter):\n while True:\n yield env.timeout(randInt())\n i = yield store.get(filter)\n print(\"%d: %s, consumato un %d\" % (env.now, name, i))\n\nenv = Environment()\nstore = FilterStore(env, capacity=2)\nenv.start(producer(env, store))\nenv.start(producer(env, store))\nenv.start(consumer(env, store, \"PARI\", lambda i: i%2 == 0))\nenv.start(consumer(env, store, \"DISPARI\", lambda i: i%2 == 1))\nenv.run(until=40)" }, { "alpha_fraction": 0.6202929019927979, "alphanum_fraction": 0.6307531595230103, "avg_line_length": 33.17856979370117, "blob_id": "ed8c6d3eb2d44325d1b419c1b5d9f7900b103459", "content_id": "b5ac92554c5a8ac05dc4d5219b9b3a4f9a299c23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 956, "license_type": "no_license", "max_line_length": 57, "num_lines": 28, "path": "/Listati/Python_Hospital_Preemption.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from simpy import *\n\n# Priorita' decrescenti, piu' una priorita' e' bassa\n# prima il processo sara' posizionato nella coda.\nRED, YELLOW, GREEN = 0, 1, 2\n\ndef person(env, name, code, hospital, delay):\n yield env.timeout(delay)\n env.active_process.name = name\n preempt = code == RED\n with hospital.request(code, preempt) as req: \n yield req\n print(\"%s viene curato...\" % name)\n try: \n yield env.timeout(7)\n print(\"Cure finite per %s\" % name)\n except Interrupt, i:\n byName = i.cause.by.name\n print(\"%s scavalcato da %s\" % (name, byName))\n\nenv = Environment()\nhospital = PreemptiveResource(env, capacity=2)\nenv.start(person(env, \"Pino\", YELLOW, hospital, 0))\nenv.start(person(env, \"Gino\", GREEN, hospital, 0))\nenv.start(person(env, \"Nino\", GREEN, hospital, 1))\nenv.start(person(env, \"Dino\", YELLOW, hospital, 1))\nenv.start(person(env, \"Tino\", RED, hospital, 2))\nenv.run()" }, { "alpha_fraction": 0.6567164063453674, "alphanum_fraction": 0.6616915464401245, "avg_line_length": 32.66666793823242, "blob_id": "8c6da2346f985a588897f78d6f5d4eddc9d32bbc", "content_id": "678add2229b70b090acdcdbe0ff42f77151780a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 201, "license_type": "no_license", "max_line_length": 58, "num_lines": 6, "path": "/Listati/CSharp_Random_Choice.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "var names = new[] {\"Pino\", \"Gino\", \"Dino\"};\nvar rand = new TRandom();\n\n// Estraiamo un nome a caso da \"names\"\n// e lo stampiamo sulla console.\nConsole.WriteLine(\"Nome scelto: {0}\", rand.Choice(names));" }, { "alpha_fraction": 0.5090090036392212, "alphanum_fraction": 0.5292792916297913, "avg_line_length": 25.176469802856445, "blob_id": "a62a18c5c9bf6d7df84943fe1337286ce240d16d", "content_id": "cd7223a36a419f06d500a68b38c5a7565bd49a63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 444, "license_type": "no_license", "max_line_length": 48, "num_lines": 17, "path": "/Listati/Python_Example_SimPy2.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from SimPy.Simulation import *\n\nclass Car(Process):\n def run():\n while True:\n print('Start parking at %d' % now())\n parking_duration = 5.0\n yield hold, self, parking_duration\n \n print('Start driving at %d' % now())\n trip_duration = 2.0\n yield hold, self, parking_duration\n \ninitialize()\nc = Car()\nactivate(c, c.run(), at=0.0)\nsimulate(until=15.0)" }, { "alpha_fraction": 0.529321014881134, "alphanum_fraction": 0.5416666865348816, "avg_line_length": 33.157894134521484, "blob_id": "686badbfdc164bc844630562a9eb5b3d0e4607ba", "content_id": "2236d3b6d0b5fe47cf99f57679c15c517ff3fcce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 648, "license_type": "no_license", "max_line_length": 61, "num_lines": 19, "path": "/Listati/CSharp_ResourcePolicy.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "IEnumerable<IEvent> Getter(IStore<int> store, char id) {\n var getEv = store.Get();\n yield return getEv;\n Console.WriteLine(\"{0}: {1}\", id, getEv.Value);\n}\n\nvoid Run() {\n var env = Sim.NewEnvironment(seed: 21);\n const int capacity = 10;\n // Gli oggetti vengono conservati in ordine \"casuale\".\n var store = env.NewStore<int>(capacity, WaitPolicy.FIFO, \n WaitPolicy.FIFO, \n WaitPolicy.Random);\n for (var i = 0; i < capacity; ++i)\n store.Put(i);\n for (var i = 0; i < capacity; ++i)\n env.Start(Getter(store, (char) ('A' + i)));\n env.Run();\n}" }, { "alpha_fraction": 0.6453900933265686, "alphanum_fraction": 0.6851063966751099, "avg_line_length": 34.29999923706055, "blob_id": "a0f31353776648355eb688bfdfb3d781d96faa56", "content_id": "8d48e44becf6df719fa5f6ada9686fecd3f1f841", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 705, "license_type": "no_license", "max_line_length": 68, "num_lines": 20, "path": "/Listati/CSharp_ConditionOperators.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "IEnumerable<IEvent> Process(IEnvironment env) {\n var c1 = env.Timeout(3).And(env.Timeout(5)).And(env.Timeout(7));\n yield return c1;\n Console.WriteLine(env.Now);\n Console.WriteLine(c1.Value.ContainsKey(c1.Ev1));\n Console.WriteLine(c1.Value.ContainsKey(c1.Ev2));\n Console.WriteLine(c1.Value.ContainsKey(c1.Ev3));\n var c2 = env.Timeout(7).Or(env.Timeout(5).Or(env.Timeout(3)));\n yield return c2;\n Console.WriteLine(env.Now);\n Console.WriteLine(c2.Value.ContainsKey(c2.Ev1));\n Console.WriteLine(c2.Value.ContainsKey(c2.Ev2));\n Console.WriteLine(c2.Value.ContainsKey(c2.Ev3));\n}\n\nvoid Run() {\n var env = Sim.NewEnvironment();\n env.Start(Process(env));\n env.Run();\n}" }, { "alpha_fraction": 0.7129186391830444, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 28.928571701049805, "blob_id": "2059a454171b2be8837117068f7c829d640df376", "content_id": "b751308346b5f4b750316836709adc846be043bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 418, "license_type": "no_license", "max_line_length": 47, "num_lines": 14, "path": "/Listati/Python_SimPy_Start.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from simpy import *\n\n# Risulta utile, se non necessario,\n# passare un'istanza dell'ambiente ai processi.\ndef myProcess(env):\n # Codice del processo, composto da una\n # serie di yield alternate ad altro codice.\n \nenv = Environment()\np1 = env.start(myProcess(env))\np2 = env.start(myProcess(env))\np3 = env.start(myProcess(env))\n# p1, p2 e p3 saranno eseguiti esattamente\n# nell'ordine con cui sono stati avviati." }, { "alpha_fraction": 0.5463623404502869, "alphanum_fraction": 0.554921567440033, "avg_line_length": 24.071428298950195, "blob_id": "52d089a45d764d51b0f985477a303341ea8f96c0", "content_id": "523844bbdde52400db5302ac633d078cdaa0fd20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 701, "license_type": "no_license", "max_line_length": 56, "num_lines": 28, "path": "/Listati/CSharp_Hippie_IRawHeap.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "interface IHeapHandle<out V, out P> {\n V Value { get; }\n P Priority { get; }\n}\n\ninterface IRawHeap<V, P> \n : ICollection<IHeapHandle<V, P>>\n{\n IComparer<P> Comparer { get; }\n int MaxCapacity { get; } \n IHeapHandle<V, P> Min { get; }\n P this[IHeapHandle<V, P> handle] { set; }\n \n IHeapHandle<V, P> Add(V val, P pr);\n \n void Merge<V2, P2>(IRawHeap<V2, P2> other) \n where V2 : V where P2 : P;\n \n IHeapHandle<V, P> RemoveMin();\n \n P UpdatePriorityOf(IHeapHandle<V, P> handle, \n P newPr);\n \n V UpdateValue(IHeapHandle<V, P> handle, \n V newVal);\n \n IEnumerable<IReadOnlyTree<V, P>> ToReadOnlyForest();\n}" }, { "alpha_fraction": 0.6231883764266968, "alphanum_fraction": 0.6231883764266968, "avg_line_length": 16.25, "blob_id": "448c386513a7b6f2607d4348ebbbdcacb070c376", "content_id": "d77522e8de6e4ab7f03237325e52ce4447d40da3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 69, "license_type": "no_license", "max_line_length": 31, "num_lines": 4, "path": "/README.md", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "Relazione-Dessert\n=================\n\nRelazione sul progetto Dessert.\n" }, { "alpha_fraction": 0.6676056385040283, "alphanum_fraction": 0.6676056385040283, "avg_line_length": 31.363636016845703, "blob_id": "52eb4b956156de161f2ad5d544c3146a325a6be3", "content_id": "82d40eeef1e10a319514d54f3bed5697487f8f16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 355, "license_type": "no_license", "max_line_length": 52, "num_lines": 11, "path": "/Listati/Python_ProducerConsumerBenchmark.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "def prodConsBenchmark_Consumer(env, store, counter):\n while True:\n yield env.timeout(counter.randomDelay())\n yield store.get()\n counter.increment()\n\ndef prodConsBenchmark_Producer(env, store, counter):\n while True:\n yield env.timeout(counter.randomDelay())\n yield store.put(randomInt())\n counter.increment()" }, { "alpha_fraction": 0.6265432238578796, "alphanum_fraction": 0.6373456716537476, "avg_line_length": 26.04166603088379, "blob_id": "399c426d5b6a00b01fe550ce30a573423fee76ff", "content_id": "7bfe83b71a0a9ef1abf99c75e82bb72c08c3edb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 648, "license_type": "no_license", "max_line_length": 58, "num_lines": 24, "path": "/Listati/Python_Pasta_Cooking.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from random import *\nfrom simpy import *\n\nrand = Random(21)\navgCookTime = 10 # Minuti\nstdCookTime = 1 # Minuti\nsimTime = 50 # Minuti\n\ndef pastaCook(env):\n normal = rand.normalvariate\n while True:\n cookTime = normal(avgCookTime, stdCookTime)\n print(\"Pasta in cottura per %g minuti\" % cookTime)\n yield env.timeout(cookTime)\n if cookTime < avgCookTime - stdCookTime:\n print(\"Pasta poco cotta!\")\n elif cookTime > avgCookTime + stdCookTime:\n print(\"Pasta troppo cotta...\")\n else:\n print(\"Pasta ben cotta!!!\")\n\nenv = Environment()\nenv.start(pastaCook(env))\nenv.run(simTime)" }, { "alpha_fraction": 0.45201238989830017, "alphanum_fraction": 0.45201238989830017, "avg_line_length": 16.052631378173828, "blob_id": "f854d3c8adc9aba6e55dd59733f52f6aabce7d1a", "content_id": "ae47f26562552f253a5ae4050c777593a67b3425", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 323, "license_type": "no_license", "max_line_length": 37, "num_lines": 19, "path": "/Listati/CSharp_Deposit_Interface_Contracts.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "[ContractClass(typeof(BankContract))]\ninterface IBank {\n /// <summary>\n /// ...\n /// </summary>\n [Pure]\n double Amount { get; }\n\n /// <summary>\n /// ...\n /// </summary> \n [Pure]\n bool IsOpen { get; }\n\n /// <summary>\n /// ...\n /// </summary>\n void Deposit(double amount);\n}" }, { "alpha_fraction": 0.652466356754303, "alphanum_fraction": 0.6883407831192017, "avg_line_length": 30.928571701049805, "blob_id": "2b29764beeff06d69a5e73da1a9d35b42deabe33", "content_id": "0722ae80e5eadc0ed8d782b0900c33edb000d28e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 446, "license_type": "no_license", "max_line_length": 49, "num_lines": 14, "path": "/Listati/CSharp_Random_TRandom.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "var rand = new TRandom();\n\n// Generiamo tre numeri casuali aventi una\n// distribuzione esponenziale, con 5 come media.\nConsole.WriteLine(\"Exponential:\");\nfor (var i = 0; i < 3; ++i)\n Console.WriteLine(rand.Exponential(1.0/5.0));\n\n// Generiamo tre numeri casuali aventi una\n// distribuzione normale, con 7 come media\n// e 0.5 come varianza.\nConsole.WriteLine(\"Normal:\");\nfor (var i = 0; i < 3; ++i)\n Console.WriteLine(rand.Normal(7.0, 0.5));" }, { "alpha_fraction": 0.6081504821777344, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 55.733333587646484, "blob_id": "e21f395199def4eb0c961d20fe62bbd6d38299fd", "content_id": "f9fe4872c44ed9ffda504ddfcf73971b6b8113d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2552, "license_type": "no_license", "max_line_length": 100, "num_lines": 45, "path": "/Benchmark/prodcons-plot-gen.sh", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "TITLE_GENERAL=\"Results of producer-consumer benchmark\"\nXLABEL=\"Number of processes\"\nYLABEL=\"Store events per second\"\n\nOUTPUT_FILE=\"prodcons-plot1.png\"\necho -e \"set terminal png enhanced giant size 640, 480\\n set out '\"$OUTPUT_FILE\"'\\n\n\t\tset title \\\"\"$TITLE_GENERAL\"\\\"\\n\n\t\tset xlabel \\\"\"$XLABEL\"\\\"\\n\n\t\tset ylabel \\\"\"$YLABEL\"\\\"\\n\n\t\tplot \\\"\"prodcons-plot-data1.txt\"\\\" using 1:2 title \\\"\"Dessert \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"prodcons-plot-data1.txt\"\\\" using 1:3 title \\\"\"Dessert \\(Windows\\)\"\\\" with lines, \\\n\t\t \\\"\"prodcons-plot-data1.txt\"\\\" using 1:4 title \\\"\"Armando \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"prodcons-plot-data1.txt\"\\\" using 1:5 title \\\"\"Armando \\(Windows\\)\"\\\" with lines, \\\n\t\t \\\"\"prodcons-plot-data1.txt\"\\\" using 1:6 title \\\"\"SimPy \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"prodcons-plot-data1.txt\"\\\" using 1:7 title \\\"\"SimPy \\(Windows\\)\"\\\" with lines\" | gnuplot\n\t\t \nTITLE_GENERAL=\"RAM usage of producer-consumer benchmark\"\nYLABEL=\"Megabytes\"\n\nOUTPUT_FILE=\"prodcons-plot2.png\"\necho -e \"set terminal png enhanced giant size 640, 480\\n set out '\"$OUTPUT_FILE\"'\\n\n\t\tset title \\\"\"$TITLE_GENERAL\"\\\"\\n\n\t\tset xlabel \\\"\"$XLABEL\"\\\"\\n\n\t\tset ylabel \\\"\"$YLABEL\"\\\"\\n\n\t\tset key left top\\n\n\t\tplot \\\"\"prodcons-plot-data2.txt\"\\\" using 1:2 title \\\"\"Dessert \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"prodcons-plot-data2.txt\"\\\" using 1:3 title \\\"\"Dessert \\(Windows\\)\"\\\" with lines, \\\n\t\t \\\"\"prodcons-plot-data2.txt\"\\\" using 1:4 title \\\"\"SimPy \\(Ubuntu\\)\"\\\" with lines\" | gnuplot\n\t\t \nTITLE_GENERAL=\"Heap efficiency in producer-consumer benchmark\"\nYLABEL=\"Store events per second\"\n\nOUTPUT_FILE=\"prodcons-plot3.png\"\necho -e \"set terminal png enhanced giant size 640, 480\\n set out '\"$OUTPUT_FILE\"'\\n\n\t\tset title \\\"\"$TITLE_GENERAL\"\\\"\\n\n\t\tset xlabel \\\"\"$XLABEL\"\\\"\\n\n\t\tset ylabel \\\"\"$YLABEL\"\\\"\\n\n\t\tplot \\\"\"prodcons-plot-data3.txt\"\\\" using 1:2 title \\\"\"Binary \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"prodcons-plot-data3.txt\"\\\" using 1:3 title \\\"\"Binary \\(Windows\\)\"\\\" with lines, \\\n\t\t \\\"\"prodcons-plot-data3.txt\"\\\" using 1:4 title \\\"\"Binomial \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"prodcons-plot-data3.txt\"\\\" using 1:5 title \\\"\"Binomial \\(Windows\\)\"\\\" with lines, \\\n\t\t \\\"\"prodcons-plot-data3.txt\"\\\" using 1:6 title \\\"\"Fibonacci \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"prodcons-plot-data3.txt\"\\\" using 1:7 title \\\"\"Fibonacci \\(Windows\\)\"\\\" with lines, \\\n\t\t \\\"\"prodcons-plot-data3.txt\"\\\" using 1:8 title \\\"\"Pairing \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"prodcons-plot-data3.txt\"\\\" using 1:9 title \\\"\"Pairing \\(Windows\\)\"\\\" with lines\" | gnuplot" }, { "alpha_fraction": 0.6818181872367859, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 32.25, "blob_id": "b43b6faa1b0281affa6aa4e7b062878e2e6fbd03", "content_id": "02673fdfa0c7742d7bd6bc051f1e043e81cc265f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 132, "license_type": "no_license", "max_line_length": 48, "num_lines": 4, "path": "/Listati/Python_TimeoutBenchmark.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "def timeoutBenchmark_PEM(env, counter):\n while True:\n yield env.timeout(counter.randomDelay())\n counter.increment()" }, { "alpha_fraction": 0.5838150382041931, "alphanum_fraction": 0.6213873028755188, "avg_line_length": 25.653846740722656, "blob_id": "3428f0cb59619f37f456ab5c52db7d823376579f", "content_id": "c77953ea4380b536d5e0823a2018b997e4b661d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 692, "license_type": "no_license", "max_line_length": 48, "num_lines": 26, "path": "/Listati/CSharp_ConditionUsage.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "IEnumerable<IEvent> Process(IEnvironment env) {\n var t1 = env.Timeout(3);\n var t2 = env.Timeout(7);\n var c1 = env.AllOf(t1, t2);\n yield return c1;\n Console.WriteLine(env.Now);\n Console.WriteLine(c1.Value.ContainsKey(t1));\n Console.WriteLine(c1.Value.ContainsKey(t2));\n \n t1 = env.Timeout(3);\n t2 = env.Timeout(7);\n var c2 = env.Condition(\n t1, t2, \n c => c.Ev1.Succeeded || c.Ev2.Succeeded\n );\n yield return c2;\n Console.WriteLine(env.Now);\n Console.WriteLine(c2.Value.ContainsKey(t1));\n Console.WriteLine(c2.Value.ContainsKey(t2));\n}\n\nvoid Run() {\n var env = Sim.NewEnvironment();\n env.Start(Process(env));\n env.Run();\n}" }, { "alpha_fraction": 0.7104676961898804, "alphanum_fraction": 0.7126948833465576, "avg_line_length": 29, "blob_id": "57dc79e48650df174e88a72bd0777b5a8e6f9061", "content_id": "6be95f21708cac42c4208e36c9def3fd83da85c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 450, "license_type": "no_license", "max_line_length": 56, "num_lines": 15, "path": "/Listati/CSharp_EventOrientedSim.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "ISO-8859-13", "text": "// Rappresentazione sintetica di un evento.\n// Il metodo Apply esegue l'attivitą\n// dell'evento, come l'aggiunta in coda\n// di un nuovo cliente della banca.\nclass Event {\n public double Time;\n public void Apply() { /* ... */ }\n}\n\n// Insieme ordinato dove vengono memorizzati gli eventi.\nvar eventSet = SortedSet<Event>();\nAddSomeEvents(eventSet);\n// Ciclo principale del simulatore.\nwhile (eventSet.Count > 0)\n eventSet.RemoveMin().Apply();" }, { "alpha_fraction": 0.5426008701324463, "alphanum_fraction": 0.5852017998695374, "avg_line_length": 26.875, "blob_id": "4cba431d5a3fc8b2c6011f779642cd3ac803fec9", "content_id": "90713a4eef5f28da1e97de9aafaae3116bc0b30b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 446, "license_type": "no_license", "max_line_length": 55, "num_lines": 16, "path": "/Listati/CSharp_Hippie_HeapSort.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "IList<T> HeapSort<T>(IEnumerable<T> elems) \n where T : IComparable<T>\n{\n var heap = HeapFactory.NewBinaryHeap<T>();\n foreach (var elem in elems)\n heap.Add(elem);\n var list = new List<T>(heap.Count);\n while (heap.Count != 0)\n list.Add(heap.RemoveMin());\n return list;\n}\n\nvar ints = HeapSort(new[] {9, 8, 7, 6, 5, 4, 3, 2, 1});\n// Output atteso: 1 2 3 4 5 6 7 8 9\nforeach (var i in ints)\n Console.Write(i + \" \"); " }, { "alpha_fraction": 0.5935335159301758, "alphanum_fraction": 0.6120092272758484, "avg_line_length": 18.727272033691406, "blob_id": "51daf56052028870cc5eceda689b4428b9356eac", "content_id": "6c60d9761547abd71b0f44ad44836d95200655b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 433, "license_type": "no_license", "max_line_length": 36, "num_lines": 22, "path": "/Listati/Python_Event_Trigger.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from simpy import *\n\ndef doSucceed(env, ev):\n yield env.timeout(5)\n ev.succeed(\"SI :)\")\n \ndef doFail(env, ev):\n yield env.timeout(5)\n ev.fail(Exception())\n \ndef proc(env):\n ev1 = env.event()\n env.start(doSucceed(env, ev1))\n print(yield ev1) \n ev2 = env.event()\n env.start(doFail(env, ev2))\n try: yield ev2\n except Exception: print(\"NO :(\")\n\nenv = Environment()\nenv.start(proc(env))\nenv.simulate()" }, { "alpha_fraction": 0.6293436288833618, "alphanum_fraction": 0.6293436288833618, "avg_line_length": 23.714284896850586, "blob_id": "a3f38e4202990f33877216b2af662f9153d0b563", "content_id": "9a54d50f699346b009f116f8a13d1f1133af243f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 519, "license_type": "no_license", "max_line_length": 61, "num_lines": 21, "path": "/Listati/CSharp_EventOrientedSim_Client.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "ISO-8859-1", "text": "class OnCustomerEntered : Event {\n public void Apply() {\n // La chiamata ad Enqueue, a tempo debito, aggiungerà\n // un'istanza di OnCustomerOutOfQueue all'event set.\n FindShortestQueue().Enqueue(TheCustomer);\n }\n}\n\nclass OnCustomerOutOfQueue : Event {\n public void Apply() {\n State = BeingServed;\n EventSet.Add(new OnCustomerDone(), GetServiceTime());\n }\n}\n\nclass OnCustomerDone : Event {\n public void Apply() {\n State = Served;\n RegisterStats();\n }\n}" }, { "alpha_fraction": 0.6004015803337097, "alphanum_fraction": 0.6293172836303711, "avg_line_length": 54.35555648803711, "blob_id": "313c91ba1aa6b9433442156232efa48d5f0fd036", "content_id": "93c5791e74f75d9043b9671632a60b42c24fdfb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2490, "license_type": "no_license", "max_line_length": 99, "num_lines": 45, "path": "/Benchmark/timeout-plot-gen.sh", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "TITLE_GENERAL=\"Results of timeout benchmark\"\nXLABEL=\"Number of processes\"\nYLABEL=\"Events per second\"\n\nOUTPUT_FILE=\"timeout-plot1.png\"\necho -e \"set terminal png enhanced giant size 640, 480\\n set out '\"$OUTPUT_FILE\"'\\n\n\t\tset title \\\"\"$TITLE_GENERAL\"\\\"\\n\n\t\tset xlabel \\\"\"$XLABEL\"\\\"\\n\n\t\tset ylabel \\\"\"$YLABEL\"\\\"\\n\n\t\tplot \\\"\"timeout-plot-data1.txt\"\\\" using 1:2 title \\\"\"Dessert \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"timeout-plot-data1.txt\"\\\" using 1:3 title \\\"\"Dessert \\(Windows\\)\"\\\" with lines, \\\n\t\t \\\"\"timeout-plot-data1.txt\"\\\" using 1:4 title \\\"\"Armando \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"timeout-plot-data1.txt\"\\\" using 1:5 title \\\"\"Armando \\(Windows\\)\"\\\" with lines, \\\n\t\t \\\"\"timeout-plot-data1.txt\"\\\" using 1:6 title \\\"\"SimPy \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"timeout-plot-data1.txt\"\\\" using 1:7 title \\\"\"SimPy \\(Windows\\)\"\\\" with lines\" | gnuplot\n\t\t \nTITLE_GENERAL=\"RAM usage of timeout benchmark\"\nYLABEL=\"Megabytes\"\n\nOUTPUT_FILE=\"timeout-plot2.png\"\necho -e \"set terminal png enhanced giant size 640, 480\\n set out '\"$OUTPUT_FILE\"'\\n\n\t\tset title \\\"\"$TITLE_GENERAL\"\\\"\\n\n\t\tset xlabel \\\"\"$XLABEL\"\\\"\\n\n\t\tset ylabel \\\"\"$YLABEL\"\\\"\\n\n\t\tset key left top\\n\n\t\tplot \\\"\"timeout-plot-data2.txt\"\\\" using 1:2 title \\\"\"Dessert \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"timeout-plot-data2.txt\"\\\" using 1:3 title \\\"\"Dessert \\(Windows\\)\"\\\" with lines, \\\n\t\t \\\"\"timeout-plot-data2.txt\"\\\" using 1:4 title \\\"\"SimPy \\(Ubuntu\\)\"\\\" with lines\" | gnuplot\n\t\t \nTITLE_GENERAL=\"Heap efficiency in timeout benchmark\"\nYLABEL=\"Events per second\"\n\nOUTPUT_FILE=\"timeout-plot3.png\"\necho -e \"set terminal png enhanced giant size 640, 480\\n set out '\"$OUTPUT_FILE\"'\\n\n\t\tset title \\\"\"$TITLE_GENERAL\"\\\"\\n\n\t\tset xlabel \\\"\"$XLABEL\"\\\"\\n\n\t\tset ylabel \\\"\"$YLABEL\"\\\"\\n\n\t\tplot \\\"\"timeout-plot-data3.txt\"\\\" using 1:2 title \\\"\"Binary \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"timeout-plot-data3.txt\"\\\" using 1:3 title \\\"\"Binary \\(Windows\\)\"\\\" with lines, \\\n\t\t \\\"\"timeout-plot-data3.txt\"\\\" using 1:4 title \\\"\"Binomial \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"timeout-plot-data3.txt\"\\\" using 1:5 title \\\"\"Binomial \\(Windows\\)\"\\\" with lines, \\\n\t\t \\\"\"timeout-plot-data3.txt\"\\\" using 1:6 title \\\"\"Fibonacci \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"timeout-plot-data3.txt\"\\\" using 1:7 title \\\"\"Fibonacci \\(Windows\\)\"\\\" with lines, \\\n\t\t \\\"\"timeout-plot-data3.txt\"\\\" using 1:8 title \\\"\"Pairing \\(Ubuntu\\)\"\\\" with lines, \\\n\t\t \\\"\"timeout-plot-data3.txt\"\\\" using 1:9 title \\\"\"Pairing \\(Windows\\)\"\\\" with lines\" | gnuplot" }, { "alpha_fraction": 0.6584821343421936, "alphanum_fraction": 0.6607142686843872, "avg_line_length": 31, "blob_id": "2f15a51dca79071c669c48dcf60bb96dea58f481", "content_id": "a87a0fdfb58bcc62a15497f5ed4c533ec88f7263", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 451, "license_type": "no_license", "max_line_length": 60, "num_lines": 14, "path": "/Listati/CSharp_Deposit_Thrower.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "ISO-8859-1", "text": "// Per rendere lo script più sintetico...\nusing IOP = System.InvalidOperationException;\nusing AOR = System.ArgumentOutOfRangeException;\n\nclass MyBank : IBank {\n public double Amount { get; private set; }\n public bool IsOpen { get; private set; }\n \n public void Deposit(double amount) {\n Raise<IOP>.IfNot(IsOpen, \"La banca è chiusa\");\n Raise<AOR>.If(amount <= 0, \"Quantità non positiva\");\n Amount += amount;\n }\n}\n" }, { "alpha_fraction": 0.5322916507720947, "alphanum_fraction": 0.546875, "avg_line_length": 29.03125, "blob_id": "0bbd87dbacce9f2aa9028c1189b6eefb94f2f5f9", "content_id": "cee554b469ce76c3f1a4b81496d33eafcad4025e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 960, "license_type": "no_license", "max_line_length": 62, "num_lines": 32, "path": "/Listati/CSharp_TargetShooting.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "static class TargetShooting {\n const double HitProb = 0.7;\n const double SimTime = 100;\n\n static string[] Targets = {\"Alieno\", \"Pollo\", \"Unicorno\"};\n\n static ITimeout<string> NewTarget(IEnvironment env) {\n var delay = env.Random.DiscreteUniform(1, 20);\n var target = env.Random.Choice(Targets);\n return env.Timeout(delay, target);\n }\n\n static IEnumerable<IEvent> Shooter(IEnvironment env) {\n while (true) {\n var timeout = NewTarget(env);\n yield return timeout;\n var hit = env.Random.NextDouble();\n string fmt;\n if (hit < HitProb)\n fmt = \"{0}: {1} colpito, si!\";\n else\n fmt = \"{0}: {1} mancato, no...\";\n Console.WriteLine(fmt, env.Now, timeout.Value);\n }\n }\n\n public static void Run() {\n var env = Sim.NewEnvironment(21);\n env.Start(Shooter(env));\n env.Run(SimTime);\n }\n}" }, { "alpha_fraction": 0.5585664510726929, "alphanum_fraction": 0.565559446811676, "avg_line_length": 32.67647171020508, "blob_id": "fbb37530ebdf8512e04406513878a7c7fdb525ee", "content_id": "663127f5690d8f7aaaa39a84c81d3f87e58e0215", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1144, "license_type": "no_license", "max_line_length": 60, "num_lines": 34, "path": "/Listati/CSharp_PastaCooking.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "static class PastaCooking {\n static readonly double AvgCookTime;\n static readonly double StdCookTime;\n static readonly double SimTime;\n\n static PastaCooking() {\n Sim.CurrentTimeUnit = TimeUnit.Minute;\n AvgCookTime = 10.Minutes();\n StdCookTime = 1.Minutes();\n SimTime = 50.Minutes();\n }\n\n static IEnumerable<IEvent> PastaCook(IEnvironment env) {\n while (true) {\n var cookTime = env.Random.Normal(AvgCookTime, \n StdCookTime);\n var fmt = \"Pasta in cottura per {0} minuti\";\n Console.WriteLine(fmt, cookTime);\n yield return env.Timeout(cookTime);\n if (cookTime < AvgCookTime - StdCookTime)\n Console.WriteLine(\"Pasta poco cotta!\");\n else if (cookTime > AvgCookTime + StdCookTime)\n Console.WriteLine(\"Pasta troppo cotta...\");\n else\n Console.WriteLine(\"Pasta ben cotta!!!\");\n }\n }\n\n public static void Run() {\n var env = Sim.NewEnvironment(21);\n env.Start(PastaCook(env));\n env.Run(SimTime);\n }\n}" }, { "alpha_fraction": 0.597122311592102, "alphanum_fraction": 0.597122311592102, "avg_line_length": 26.899999618530273, "blob_id": "ff0664006577e9dda27d7272db4fda8962f139c2", "content_id": "b56ba730e0422979e1752aadafae241d217d6721", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 280, "license_type": "no_license", "max_line_length": 56, "num_lines": 10, "path": "/Listati/CSharp_ProcessOrientedSim_Client.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "ISO-8859-1", "text": "class Customer : Process {\n public void Run() {\n // Chiamata bloccante finché non è il suo turno.\n FindShortestQueue().Enqueue(TheCustomer);\n State = BeingServed;\n Timeout(GetServiceTime());\n State = Served;\n RegisterStats();\n }\n}" }, { "alpha_fraction": 0.6696832776069641, "alphanum_fraction": 0.7285068035125732, "avg_line_length": 25.058822631835938, "blob_id": "839f514df1d16a45c19db3afd3d8c22a4852b735", "content_id": "867d90932f31e75738ef29f3b9512fc77972eaf6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 442, "license_type": "no_license", "max_line_length": 54, "num_lines": 17, "path": "/Listati/Python_Bank_Example_Pt1.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from random import *\nfrom simpy import *\n\nrand = Random(21)\nexp = lambda x: rand.expovariate(1.0/x)\n\navgIncomingT, avgServiceT = 3.0, 10.0 # Minuti\nqueueCount = 3 # Numero sportelli\nbankCap, bankLvl = 20000, 2000 # Euro\n\n# Usate per raccogliere dati statistici\ntotClients, totServedClients = 0, 0\ntotWaitT, totServT = 0.0, 0.0\n\nenv = Environment()\nqueues = [Resource(env, 1) for i in range(queueCount)]\nbank = Container(env, bankCap, bankLvl)" }, { "alpha_fraction": 0.5253036618232727, "alphanum_fraction": 0.5283401012420654, "avg_line_length": 28.08823585510254, "blob_id": "617d6ce4bf100e3bbe7b9b7540b0d32cb24b3c56", "content_id": "ef4d2afd6ce3322bfac2dc3954d96c213f8040ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 988, "license_type": "no_license", "max_line_length": 53, "num_lines": 34, "path": "/Listati/CSharp_Hippie_Dijkstra.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "struct Edge {\n public int Length;\n public int Target;\n}\n\nint[] Traverse(IRawHeap<int, int> heap, \n IList<IEnumerable<Edge>> edges,\n int start, int nodeCount)\n{\n var distances = new int[nodeCount];\n var visited = new bool[nodeCount];\n var nodes = new IHeapHandle<int, int>[nodeCount];\n for (var i = 0; i < nodeCount; ++i) {\n nodes[i] = heap.Add(i, int.MaxValue);\n distances[i] = int.MaxValue; \n }\n heap[nodes[start]] = 0;\n\n while (heap.Count != 0) {\n var u = heap.RemoveMin();\n if (u.Priority == int.MaxValue) break;\n var uId = u.Value;\n distances[uId] = u.Priority;\n visited[uId] = true;\n foreach (var e in edges[uId]) {\n if (visited[e.Target]) continue;\n var tmpDist = u.Priority + e.Length;\n var v = nodes[e.Target];\n if (tmpDist < v.Priority)\n heap[v] = tmpDist;\n }\n }\n return distances;\n}" }, { "alpha_fraction": 0.5817409753799438, "alphanum_fraction": 0.6008492708206177, "avg_line_length": 20.454545974731445, "blob_id": "c608baf4521dcd65fcd6fad8aa6f0824ea24102b", "content_id": "dd90466401dccb207f0cafb22b2bfd912ef42f36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 471, "license_type": "no_license", "max_line_length": 61, "num_lines": 22, "path": "/Listati/Python_Event_Callbacks.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "from simpy import *\n \ndef doFail(env, ev):\n yield env.timeout(5)\n ev.fail(Exception(\"NO\"))\n \ndef myCallback(ev):\n print(\"Successo: '%s'; Valore: '%s'\" % (ev.ok, ev.value))\n \ndef proc(env):\n ev1 = env.timeout(7, \"SI\")\n ev1.callbacks = [myCallback]\n yield ev1 \n ev2 = env.event()\n ev2.callbacks = [myCallback]\n env.start(doFail(env, ev2))\n try: yield ev2\n except Exception: pass\n\nenv = Environment()\nenv.start(proc(env))\nenv.run()" }, { "alpha_fraction": 0.5758513808250427, "alphanum_fraction": 0.6006191968917847, "avg_line_length": 35, "blob_id": "93214b1a0527ce7ef92e321dcc2951b84b7e513e", "content_id": "8ca03483f918aee4c075232f5f6b2bcab836aa93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 323, "license_type": "no_license", "max_line_length": 56, "num_lines": 9, "path": "/Listati/Python_Bank_Example_Pt3.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "def spawner(env, queues, bank):\n global totClients\n while True:\n yield env.timeout(exp(avgIncomingT))\n queue = min(queues, key=lambda q:len(q.queue))\n amount = rand.uniform(50, 500)\n get = rand.random() < 0.4\n env.start(client(env, queue, bank, amount, get))\n totClients += 1" }, { "alpha_fraction": 0.6030927896499634, "alphanum_fraction": 0.6030927896499634, "avg_line_length": 23.375, "blob_id": "77926fbb6b9dfa8fb433e1401e1cb89ccc2ec8ba", "content_id": "8a70157917b6816ea00b2b1f49a52973b692110b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 194, "license_type": "no_license", "max_line_length": 46, "num_lines": 8, "path": "/Listati/CSharp_Deposit_WithContracts.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "class MyBank : IBank {\n public double Amount { get; private set; }\n public bool IsOpen { get; private set; }\n \n public void Deposit(double amount) {\n Amount += amount;\n }\n}" }, { "alpha_fraction": 0.6927223801612854, "alphanum_fraction": 0.7304581999778748, "avg_line_length": 25.5, "blob_id": "34fe05d3e3b717135ab8f5d7a484b53b34fd487a", "content_id": "2ee968ed63e57efdaab1328c7772bb29c0598fa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 371, "license_type": "no_license", "max_line_length": 47, "num_lines": 14, "path": "/Listati/Python_Random.py", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "import random\n\n# Generiamo tre numeri casuali aventi una\n# distribuzione esponenziale, con 5 come media.\nprint(\"Exponential:\")\nfor i in range(3):\n print(random.expovariate(1.0/5.0))\n\n# Generiamo tre numeri casuali aventi una\n# distribuzione normale, con 7 come media\n# e 0.5 come varianza.\nprint(\"Normal:\")\nfor i in range(3):\n print(random.normalvariate(7.0, 0.5))\n" }, { "alpha_fraction": 0.6014319658279419, "alphanum_fraction": 0.6085919141769409, "avg_line_length": 25.25, "blob_id": "d4aa3a9ec4d2666c80d5727d832083dbd3dd13fb", "content_id": "275c371c506750f1f186a473b7ae4b1397fc7835", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 419, "license_type": "no_license", "max_line_length": 47, "num_lines": 16, "path": "/Listati/CSharp_NamedEvents.cs", "repo_name": "pomma89/Relazione-Dessert", "src_encoding": "UTF-8", "text": "IEnumerable<IEvent> Process(IEnvironment env) {\n var a = env.NamedTimeout(3, \"A\");\n var b = env.NamedTimeout(5, \"B\");\n var c = env.NamedTimeout(7, \"C\");\n var cond = a.And(b.Or(c));\n yield return cond;\n Console.WriteLine(env.Now);\n foreach (var e in cond.Value.Keys)\n Console.WriteLine(e.Name);\n}\n\nvoid Run() {\n var env = Sim.NewEnvironment();\n env.Start(Process(env));\n env.Run();\n}" } ]
69
tuvm/php-iot
https://github.com/tuvm/php-iot
a6a944eafcf2a89f9bb0339e1b56b227148b72cb
7f612b5e80c1495ac2448e3f99f0a53742c9c37a
baacc33ae7ee1a950e7726c8698d5e836d0e28eb
refs/heads/master
2020-09-04T14:53:06.077169
2019-11-05T14:08:22
2019-11-05T14:08:22
219,760,812
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.2736823260784149, "alphanum_fraction": 0.2809829115867615, "avg_line_length": 56.306121826171875, "blob_id": "2d2bf57ad053a7528c0fec8ecc92e80fbe1a7060", "content_id": "9d5b6eda5aea8253df613ac1dce2edba865701d0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 11232, "license_type": "permissive", "max_line_length": 181, "num_lines": 196, "path": "/make_general.php", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "<?php\n\n include \"connect.php\";\n $min_value = 0;\n $min_time = \"0\";\n $max_value = 0;\n $max_time = \"0\";\n $avg_value=0;\n if(isset($_POST[\"request\"])){\n\n $obj = json_decode($_COOKIE[\"select\"],true);\n if(sizeof($obj) != 0){\n for( $i = 0; $i < sizeof($obj) ; $i++){\n\n $cur_id = \"0\";\n $min_value = 0;\n $min_time = \"0\";\n $max_value = 0;\n $max_time = \"0\";\n $before = 0;\n $avg_value=0;\n $id_area = $obj[$i];\n $res_id = $conn->query(\"select * FROM location WHERE parentid = $id_area \");//Xem id nay co phai la node la khong.\n if ($res_id->num_rows == 0){\n $ind = 0;\n $res_type = $conn->query(\"SELECT * FROM sensor\"); //truy van cac kieu du lieu da co.\n if ($res_type->num_rows > 0){\n while($row = $res_type->fetch_assoc()){\n $id_sensor = $row[\"id\"];\n $cur_id = $row[\"code\"];\n $sensor = $row[\"type\"];\n $min_range = explode(\",\",$row[\"arange\"])[0];\n $range_1 = explode(\",\",$row[\"arange\"])[1];\n $range_2 = explode(\",\",$row[\"arange\"])[2];\n $max_range = explode(\",\",$row[\"arange\"])[3];\n $status = NULL;\n $icon = $row['icon'];\n $don_vi = $row[\"ext\"];\n $color = $row[\"des\"];\n $time =\"time\";\n \n $res_cur_id = $conn->query(\"SELECT id FROM router WHERE areaid = $id_area AND sensorid = $id_sensor\");\n if ($res_cur_id->num_rows > 0){\n\n while($row = $res_cur_id->fetch_assoc()){\n $cur_id = $row[\"id\"];\n $data[$cur_id]['mx_r']=$max_range;\n \n $Avg = $conn->query(\"SELECT AVG(value) AS av FROM sensordata WHERE sensor = $cur_id\");\n if ($Avg->num_rows > 0){\n while($row = $Avg->fetch_assoc()){\n $data[$cur_id]['av']=$row[\"av\"];\n }\n }\n\n $Mx = $conn->query(\"SELECT * FROM sensordata WHERE value = (SELECT MAX(value) FROM sensordata WHERE sensor = $cur_id) AND sensor = $cur_id\");\n if ($Mx->num_rows > 0){\n while($row = $Mx->fetch_assoc()){\n $data[$cur_id]['mx']=$row[\"value\"];\n $data[$cur_id]['mx_t']=(string)$row[\"time\"];\n }\n }\n $Mn = $conn->query(\"SELECT * FROM sensordata WHERE value = (SELECT MIN(value) FROM sensordata WHERE sensor = $cur_id) AND sensor = $cur_id\");\n if ($Mn->num_rows > 0){\n while($row = $Mn->fetch_assoc()){\n $data[$cur_id]['mn']=$row[\"value\"];\n $data[$cur_id]['mn_t']=(string)$row[\"time\"];\n }\n }\n\n $cur_value = $conn->query(\"SELECT * FROM sensordata WHERE id = ( SELECT MAX(id) FROM sensordata WHERE sensor = $cur_id )\");\n if ($cur_value->num_rows > 0){\n while($row = $cur_value->fetch_assoc()){\n if($row['value']>=$min_range&&$row['value'] < $range_1){\n $status = \"LOW\";\n $colorstt = \"#DD0000\";\n }\n if($row['value']>=$range_1&&$row['value'] < $range_2){\n $status = \"MEDIUM\";\n $colorstt = \"#00CC00\";\n }\n if($row['value']>=$range_2&&$row['value'] <= $max_range){\n $status = \"HIGHT\";\n $colorstt = \"#DD0000\";\n }\n $data[$cur_id]['stt']=$status;\n $data[$cur_id]['stt_cl']=$colorstt;\n $data[$cur_id]['cr_vl']=$row[\"value\"];\n $old_value = $row[\"value\"];\n }\n }\n \n }\n }\n }\n \n }\n }\n }\n echo json_encode($data);\n mysqli_close($conn);\n }else{\n $res_all = $conn->query(\"SELECT * FROM location\"); //truy van cac kieu du lieu da co.\n if ($res_all->num_rows > 0){\n while($row = $res_all->fetch_assoc()){\n $id_area = $row[\"id\"];\n $cur_id = \"0\";\n $min_value = 0;\n $min_time = \"0\";\n $max_value = 0;\n $max_time = \"0\";\n $before = 0;\n $avg_value=0;\n $res_id = $conn->query(\"select * FROM location WHERE parentid = $id_area \");//Xem id nay co phai la node la khong.\n if ($res_id->num_rows == 0){\n $ind = 0;\n $res_type = $conn->query(\"SELECT * FROM sensor\"); //truy van cac kieu du lieu da co.\n if ($res_type->num_rows > 0){\n while($row = $res_type->fetch_assoc()){\n $id_sensor = $row[\"id\"];\n $cur_id = $row[\"code\"];\n $sensor = $row[\"type\"];\n $min_range = explode(\",\",$row[\"arange\"])[0];\n $range_1 = explode(\",\",$row[\"arange\"])[1];\n $range_2 = explode(\",\",$row[\"arange\"])[2];\n $max_range = explode(\",\",$row[\"arange\"])[3];\n $status = NULL;\n $icon = $row['icon'];\n $don_vi = $row[\"ext\"];\n $color = $row[\"des\"];\n $time =\"time\";\n \n $res_cur_id = $conn->query(\"SELECT id FROM router WHERE areaid = $id_area AND sensorid = $id_sensor\");\n if ($res_cur_id->num_rows > 0){\n\n while($row = $res_cur_id->fetch_assoc()){\n $cur_id = $row[\"id\"];\n $data[$cur_id]['mx_r']=$max_range;\n \n $Avg = $conn->query(\"SELECT AVG(value) AS av FROM sensordata WHERE sensor = $cur_id\");\n if ($Avg->num_rows > 0){\n while($row = $Avg->fetch_assoc()){\n $data[$cur_id]['av']=$row[\"av\"];\n }\n }\n\n $Mx = $conn->query(\"SELECT * FROM sensordata WHERE value = (SELECT MAX(value) FROM sensordata WHERE sensor = $cur_id) AND sensor = $cur_id\");\n if ($Mx->num_rows > 0){\n while($row = $Mx->fetch_assoc()){\n $data[$cur_id]['mx']=$row[\"value\"];\n $data[$cur_id]['mx_t']=(string)$row[\"time\"];\n }\n }\n $Mn = $conn->query(\"SELECT * FROM sensordata WHERE value = (SELECT MIN(value) FROM sensordata WHERE sensor = $cur_id) AND sensor = $cur_id\");\n if ($Mn->num_rows > 0){\n while($row = $Mn->fetch_assoc()){\n $data[$cur_id]['mn']=$row[\"value\"];\n $data[$cur_id]['mn_t']=(string)$row[\"time\"];\n }\n }\n\n $cur_value = $conn->query(\"SELECT * FROM sensordata WHERE id = ( SELECT MAX(id) FROM sensordata WHERE sensor = $cur_id )\");\n if ($cur_value->num_rows > 0){\n while($row = $cur_value->fetch_assoc()){\n if($row['value']>=$min_range&&$row['value'] < $range_1){\n $status = \"LOW\";\n $colorstt = \"#DD0000\";\n }\n if($row['value']>=$range_1&&$row['value'] < $range_2){\n $status = \"MEDIUM\";\n $colorstt = \"#00CC00\";\n }\n if($row['value']>=$range_2&&$row['value'] <= $max_range){\n $status = \"HIGHT\";\n $colorstt = \"#DD0000\";\n }\n $data[$cur_id]['stt']=$status;\n $data[$cur_id]['stt_cl']=$colorstt;\n $data[$cur_id]['cr_vl']=$row[\"value\"];\n $old_value = $row[\"value\"];\n }\n }\n \n }\n }\n }\n }\n }\n }\n echo json_encode($data);\n mysqli_close($conn);\n }\n \n }\n }\n?>\n" }, { "alpha_fraction": 0.44763728976249695, "alphanum_fraction": 0.5442741513252258, "avg_line_length": 18.570833206176758, "blob_id": "514dac1b4429aa2a7754748b4480478a681d706b", "content_id": "aab53d058cbc2aaa21b74ece1eddcab4e5d20eab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4698, "license_type": "permissive", "max_line_length": 111, "num_lines": 240, "path": "/signin.php", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html>\n <head>\n <title> Sigin </title>\n <meta charset=\"UTF-8\">\n <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\"></script>\n <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.0/css/all.css\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js\"></script>\n <link rel=\"stylesheet\" href=\"//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/themes/default/style.min.css\" />\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/jstree.min.js\"></script>\n <style>\n#chartdiv {\n width: 900px;\n height: 500px;\n}\n\n</style>\n\n<!-- Resources -->\n<script src=\"https://www.amcharts.com/lib/4/core.js\"></script>\n<script src=\"https://www.amcharts.com/lib/4/charts.js\"></script>\n<script src=\"https://www.amcharts.com/lib/4/themes/animated.js\"></script>\n\n<!-- Chart code -->\n<script>\nam4core.ready(function() {\n\n// Themes begin\nam4core.useTheme(am4themes_animated);\n// Themes end\n\n// Create chart instance\nvar chart = am4core.create(\"chartdiv\", am4charts.XYChart);\n\n// Add data\nchart.data = [{\n \"year\": \"1950\",\n \"value\": -0.307\n}, {\n \"year\": \"1951\",\n \"value\": -0.168\n}, {\n \"year\": \"1952\",\n \"value\": -0.073\n}, {\n \"year\": \"1953\",\n \"value\": -0.027\n}, {\n \"year\": \"1954\",\n \"value\": -0.251\n}, {\n \"year\": \"1955\",\n \"value\": -0.281\n}, {\n \"year\": \"1956\",\n \"value\": -0.348\n}, {\n \"year\": \"1957\",\n \"value\": -0.074\n}, {\n \"year\": \"1958\",\n \"value\": -0.011\n}, {\n \"year\": \"1959\",\n \"value\": -0.074\n}, {\n \"year\": \"1960\",\n \"value\": -0.124\n}, {\n \"year\": \"1961\",\n \"value\": -0.024\n}, {\n \"year\": \"1962\",\n \"value\": -0.022\n}, {\n \"year\": \"1963\",\n \"value\": 0\n}, {\n \"year\": \"1964\",\n \"value\": -0.296\n}, {\n \"year\": \"1965\",\n \"value\": -0.217\n}, {\n \"year\": \"1966\",\n \"value\": -0.147\n}, {\n \"year\": \"1967\"\n}, {\n \"year\": \"1971\",\n \"value\": -0.19\n}, {\n \"year\": \"1972\",\n \"value\": -0.056\n}, {\n \"year\": \"1973\",\n \"value\": 0.077\n}, {\n \"year\": \"1974\",\n \"value\": -0.213\n}, {\n \"year\": \"1975\",\n \"value\": -0.17\n}, {\n \"year\": \"1976\",\n \"value\": -0.254\n}, {\n \"year\": \"1977\",\n \"value\": 0.019\n}, {\n \"year\": \"1978\",\n \"value\": -0.063\n}, {\n \"year\": \"1979\",\n \"value\": 0.05\n}, {\n \"year\": \"1980\",\n \"value\": 0.077\n}, {\n \"year\": \"1981\",\n \"value\": 0.12\n}, {\n \"year\": \"1982\",\n \"value\": 0.011\n}, {\n \"year\": \"1983\",\n \"value\": 0.177\n}, {\n \"year\": \"1984\"\n}, {\n \"year\": \"1989\",\n \"value\": 0.104\n}, {\n \"year\": \"1990\",\n \"value\": 0.255\n}, {\n \"year\": \"1991\",\n \"value\": 0.21\n}, {\n \"year\": \"1992\",\n \"value\": 0.065\n}, {\n \"year\": \"1993\",\n \"value\": 0.11\n}, {\n \"year\": \"1994\",\n \"value\": 0.172\n}, {\n \"year\": \"1995\",\n \"value\": 0.269\n}, {\n \"year\": \"1996\",\n \"value\": 0.141\n}, {\n \"year\": \"1997\",\n \"value\": 0.353\n}, {\n \"year\": \"1998\",\n \"value\": 0.548\n}, {\n \"year\": \"1999\",\n \"value\": 0.298\n}, {\n \"year\": \"2000\",\n \"value\": 0.267\n}, {\n \"year\": \"2001\",\n \"value\": 0.411\n}, {\n \"year\": \"2002\",\n \"value\": 0.462\n}, {\n \"year\": \"2003\",\n \"value\": 0.47\n}, {\n \"year\": \"2004\",\n \"value\": 0.445\n}, {\n \"year\": \"2005\",\n \"value\": 0.47\n}];\n\n// Create axes\nvar dateAxis = chart.xAxes.push(new am4charts.DateAxis());\ndateAxis.renderer.minGridDistance = 50;\ndateAxis.renderer.grid.template.location = 0.5;\ndateAxis.baseInterval = {\n count: 1,\n timeUnit: \"year\"\n}\n\nvar valueAxis = chart.yAxes.push(new am4charts.ValueAxis());\n\n// Create series\nvar series = chart.series.push(new am4charts.LineSeries());\nseries.dataFields.valueY = \"value\";\nseries.dataFields.dateX = \"year\";\nseries.strokeWidth = 3;\nseries.stroke = \"red\";\nseries.fill = \"red\";\nseries.connect = false;\n//series.tensionX = 0.8;\nseries.fillOpacity = 0.2;\n\nvar bullet = series.bullets.push(new am4charts.CircleBullet());\nbullet.stroke = am4core.color(\"#fff\");\nbullet.strokeWidth = 3;\n\nvar range = valueAxis.createSeriesRange(series);\nrange.value = -0.2;\nrange.endValue = -0.1;\nrange.contents.stroke = \"green\";\nrange.contents.fill = range.contents.stroke;\nrange.contents.fillOpacity = 0.2;\n\nchart.scrollbarX = new am4core.Scrollbar();\n\nchart.events.on(\"inited\", function(ev) {\n dateAxis.zoomToDates(new Date(1970, 0), new Date(1995, 0));\n});\n\n}); // end am4core.ready()\n</script>\n </head>\n <body style=\"position:relative; margin: 0px;\">\n <?php\n include \"connect.php\";\n include \"taskbar.php\";\n include \"sidebar.php\";\n ?>\n <div id=\"page-content\" style=\"float:left;height:1000px;color: #18699F;margin: 70px 0px 0px 200px;\">\n <div id=\"chartdiv\"></div>\n </div>\n </body>\n</html>\n\n\n\n<!-- HTML -->\n\n" }, { "alpha_fraction": 0.656105637550354, "alphanum_fraction": 0.6864686608314514, "avg_line_length": 26.053571701049805, "blob_id": "5e2605cce2eee410dbc056400728d690df4b7551", "content_id": "b363c0761addac3197858d4b273eaa36a1e3aa62", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1515, "license_type": "permissive", "max_line_length": 159, "num_lines": 56, "path": "/python/pub.py", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "import paho.mqtt.client as mqtt\nimport random\nimport json\nfrom datetime import datetime\nfrom time import sleep\n\nBroker = \"soldier.cloudmqtt.com\"\nPort = 11600\nWait = 50\nTopic = \"datafake\"\n\ndef on_connect(client, userdata, flags, rc):\n\tif rc!=0:\n\t\tpass\n\t\tprint('Unable connect to Broker...')\n\telse:\n\t\tprint('Connected with Broker' + str(Broker))\n\ndef on_publish(client, userdata, mid):\n\tpass\n\ndef disconnect(client, userdata, rc):\n\tif rc != 0:\n\t\tpass\n\nmqttc = mqtt.Client()\nmqttc.username_pw_set(username = \"guapvdfg\", password = \"k5WzGtSNWMQY\")\nmqttc.on_connect = on_connect\nmqttc.disconnect = disconnect\nmqttc.on_publish = on_publish\nmqttc.connect(Broker, Port, Wait)\n\ndef pub2topic(topic, message):\n\tmqttc.publish(topic, message)\n\tprint('Published: ' + str(message) + '' +'on MQTT topic ' + str(topic))\n\tprint('')\n\ndef pub_data_fake(namesensor):\n\tmac = int(random.uniform(0,5))\n\tmacadd = ['AAAA','BBBB', 'CCCC', 'DDDD', 'EEEE']\n\t#Sprint(ssarea[1])\n\tcode = int(random.uniform(0,5))\n\ttypecode = ['temp', 'hum', 'dust', 'light','rain']\n\tfor i in range(0,5):\n\t\tvalue = [int(random.uniform(20, 50)),int(random.uniform(40, 95)),int(random.uniform(500, 1000)),int(random.uniform(500, 1023)),int(random.uniform(50, 200))];\n\t\tsensor_data = {};\n\t\tsensor_data['mac'] = macadd[i];\n\t\tsensor_data['code'] = typecode;\n\t\tsensor_data['value'] = value;\n\t\tsensor_json_data = json.dumps(sensor_data)\n\t\tprint('Publishing data fake from %s:' %namesensor)\n\t\tpub2topic(Topic, sensor_json_data)\n\nwhile True:\n\tpub_data_fake('Fake')\n\tsleep(5)\n" }, { "alpha_fraction": 0.5013399720191956, "alphanum_fraction": 0.507127046585083, "avg_line_length": 49.189083099365234, "blob_id": "791add25baac4e65cb5826c6dcdb4a4b07c9ff2b", "content_id": "5671db4cf0398b5957b024e1dbc8a7351da3507d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 25747, "license_type": "permissive", "max_line_length": 277, "num_lines": 513, "path": "/manage.php", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html>\n <head>\n <title> Manage </title>\n <meta charset=\"UTF-8\">\n <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\"></script>\n <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.0/css/all.css\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js\"></script>\n <link rel=\"stylesheet\" href=\"//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/themes/default/style.min.css\" />\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/jstree.min.js\"></script>\n <script>\n function createCookie(name, value, days) {\n var expires;\n if (days) {\n var date = new Date();\n date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));\n expires = \"; expires=\" + date.toGMTString();\n }\n else {\n expires = \"\";\n }\n document.cookie = name+ \"=\" + value + expires + \"; path=/\";\n //console.log(document.cookie);\n }\n createCookie(\"select_manage\",'', \"10\");\n $(function () {\n $(\"#tree\").jstree({\n \"checkbox\": {\n \"keep_selected_style\": false,\n \"three_state\":false,\n \"real_checkboxes\":false\n },\n \"plugins\": [\"types\", \"checkbox\"],\n \"core\": {\n \"multiple\": false\n },\n \"types\": {\n \"default\": {\n \"icon\": \"fas fa-map-marker-alt\"\n }\n }\n });\n $(\"#tree\").bind(\"changed.jstree\",\n function (e, data) {\n var output = {};\n for(i=0 ;i<data.selected.length ;i++){\n output[i] = data.selected[i];\n }\n var kq = JSON.stringify(output);\n console.log(output);\n console.log(kq);\n createCookie(\"select_manage\", kq , \"10\");\n });\n });\n </script>\n </head>\n <body style=\"position:relative; margin: 0px;\">\n <?php\n include \"connect.php\";\n include \"taskbar.php\";\n ?>\n <script >\n openTab(5);\n </script>\n <div id=\"sidebar\" style=\"position:fixed;width: 200px;height:100%; background-color: #1E282C; padding: 0px; margin: 70px 0px; color: #ECF0F5; float:left;\">\n <div id=\"menu_text\" style=\"height: 60px; text-align: center; vertical-align: middle; line-height: 60px; border-bottom: 1px solid #ECF0F5\">\n <p style=\"font-size: 30px;margin: 0;px border-bottom: 1px solid #ECF0F5; border-top: 1px solid #ECF0F5\"><strong> MENU </strong></p>\n </div>\n </div>\n <div id=\"page-content\" style=\"float:left;height:100%;color: #18699F;margin: 70px 0px 0px 200px;\">\n <div id=\"general-page\" class=\"page\">\n <h1>MANAGE</h1>\n <div id=\"tree\" style=\"width: auto; background-color: #ECF0F5 ;color: blue; padding: 0px; margin: 10px 10px 10px 10px\">\n <?php\n function trytry($id_parent,$conn){\n $res_id_t = $conn->query(\"SELECT * FROM location WHERE parentid = $id_parent \");\n if ($res_id_t->num_rows > 0){\n echo \"<ul>\";\n while($row = $res_id_t->fetch_assoc()){\n $save_id = $row[\"id\"];\n $save_area = $row[\"area\"];\n $icon = $row[\"ext\"];\n echo \"<li id=\\\"$save_id\\\" data-jstree = '{\\\"icon\\\": \\\"\" .$icon .\"\\\"}' >$save_area\";\n // $res_device = $conn->query(\"SELECT * FROM device WHERE areaid = $save_id \");\n // if ($res_device->num_rows > 0){\n // echo \"<ul>\";\n // while($row = $res_device->fetch_assoc()){\n // $id_device = $row['id'];\n // $name_device = $row['name'];\n // $icon_d = $row['des'];\n // echo \"<li id=\\\"$id_device\\\" data-jstree = '{\\\"icon\\\": \\\"\" .$icon_d .\"\\\"}' >$name_device - Topic: $id_device </li>\";\n // }\n // echo \"</ul>\";\n // }\n trytry($save_id,$conn);\n echo \"</li>\";\n }\n echo \"</ul>\";\n }\n }\n $res_id = $conn->query(\"SELECT * FROM location where parentid IS NULL \");\n if ($res_id->num_rows > 0){ \n echo \"<ul>\";\n while($row = $res_id->fetch_assoc()){\n $save_id = $row[\"id\"];\n $save_area = $row[\"area\"];\n $icon = $row[\"ext\"];\n echo \"<li id=\\\"$save_id\\\" data-jstree = '{\\\"icon\\\": \\\"\" .$icon .\"\\\"}' >$save_area\";\n // $res_device = $conn->query(\"SELECT * FROM device WHERE areaid = $save_id \");\n // if ($res_device->num_rows > 0){\n // echo \"<ul>\";\n // while($row = $res_device->fetch_assoc()){\n // $id_device = $row['id'];\n // $name_device = $row['name'];\n // $icon_d = $row['des'];\n // echo \"<li id=\\\"$id_device\\\" data-jstree = '{\\\"icon\\\": \\\"\" .$icon_d .\"\\\"}' >$name_device - Topic: $id_device </li>\";\n // }\n // echo \"</ul>\";\n // }\n trytry($save_id,$conn);\n echo\"</li>\";\n }\n echo \"</ul>\";\n }\n ?>\n </div>\n </div>\n <div>\n <button onclick=\"document.getElementById('addlocation').style.display='block'\" style=\"width:auto;\"><span class=\"far fa-plus-square\"></span>&nbsp; Add Location</button>\n <button onclick=\"document.getElementById('addsensor').style.display='block'\" style=\"width:auto;\"><span class=\"far fa-plus-square\"></span>&nbsp; Add gateway</button>\n <button onclick=\"document.getElementById('adddevice').style.display='block'\" style=\"width:auto;\"><span class=\"far fa-plus-square\"></span>&nbsp; Add Device</button>\n <button onclick=\"document.getElementById('rename').style.display='block'\" style=\"width:auto;\"><span class=\"fas fa-edit\"></span>&nbsp; Rename</button>\n <button onclick=\"document.getElementById('relocation').style.display='block'\" style=\"width:auto;\"><span class=\"fas fa-people-carry\"></span>&nbsp; Relocation</button>\n <button onclick=\"document.getElementById('delete').style.display='block'\" style=\"width:auto;\"><span class=\"fas fa-trash-alt\"></span>&nbsp; Delete</button>\n \n </div>\n </div>\n\n <body>\n <div id=\"relocation\" class=\"modal\" >\n <script>\n createCookie(\"select_manage_t\",'', \"10\");\n $(function () {\n $(\"#tree_t\").jstree({\n \"checkbox\": {\n \"keep_selected_style\": false,\n \"three_state\":false,\n \"real_checkboxes\":false\n },\n \"plugins\": [\"types\", \"checkbox\"],\n \"core\": {\n \"multiple\": false\n },\n \"types\": {\n \"default\": {\n \"icon\": \"fas fa-map-marker-alt\"\n }\n }\n });\n $(\"#tree_t\").bind(\"changed.jstree\",\n function (e, data) {\n var output = {};\n for(i=0 ;i<data.selected.length ;i++){\n output[i] = data.selected[i];\n }\n var kq = JSON.stringify(output);\n console.log(output);\n console.log(kq);\n createCookie(\"select_manage_t\", kq , \"10\");\n });\n });\n\n </script>\n <span onclick=\"document.getElementById('relocation').style.display='none'\" class=\"close\" title=\"Close Modal\">&times;</span>\n <form class=\"modal-content\" action=\"manage.php\" method = \"post\" role = \"form\">\n <div class=\"container\">\n <center>\n <h1>Relocation</h1>\n <p>Please select the location you want move to.</p>\n </center>\n <div id=\"tree_t\" style=\"width: auto; background-color: #ECF0F5 ;color: blue; padding: 0px; margin: 10px 10px 10px 10px\">\n <?php\n function trytry_t($id_parent,$conn){\n $res_id_t = $conn->query(\"SELECT * FROM location WHERE parentid = $id_parent \");\n if ($res_id_t->num_rows > 0){\n echo \"<ul>\";\n while($row = $res_id_t->fetch_assoc()){\n $save_id = $row[\"id\"];\n $save_area = $row[\"area\"];\n $icon = $row[\"ext\"];\n $res_id = $conn->query(\"SELECT * FROM location WHERE id = $save_id AND ext = 'fas fa-building' \");\n if ($res_id->num_rows > 0){\n echo \"<li id=\\\"$save_id\\\" data-jstree = '{\\\"icon\\\": \\\"\" .$icon .\"\\\"}' >$save_area\";\n trytry_t($save_id,$conn);\n echo \"</li>\";\n }\n }\n echo \"</ul>\";\n }\n }\n $res_id = $conn->query(\"SELECT * FROM location where parentid IS NULL AND ext = 'fas fa-building'\");\n if ($res_id->num_rows > 0){ \n echo \"<ul>\";\n while($row = $res_id->fetch_assoc()){\n $save_id = $row[\"id\"];\n $save_area = $row[\"area\"];\n $icon = $row[\"ext\"];\n echo \"<li id=\\\"$save_id\\\" data-jstree = '{\\\"icon\\\": \\\"\" .$icon .\"\\\"}' >$save_area\";\n trytry_t($save_id,$conn);\n echo\"</li>\";\n }\n echo \"</ul>\";\n }\n ?>\n </div>\n <hr>\n <div class=\"clearfix\">\n <button type=\"button\" onclick=\"document.getElementById('relocation').style.display='none'\" class=\"cancelbtn\" style=\"float:left;\">Cancel</button>\n <button type=\"submit\" class=\"makebtn\" name=\"do_relocation\">Update</button>\n </div>\n </div>\n </form>\n </div>\n </body>\n <?php\n if(isset($_POST[\"do_relocation\"])){\n $old = json_decode($_COOKIE['select_manage'],true);\n $new = json_decode($_COOKIE['select_manage_t'],true);\n\n if($old==NULL OR $new==NULL){\n echo \"<script type=\\\"text/javascript\\\">alert(\\\"You must select enough location !\\\");</script>\";\n }\n else{\n $location_old = $old[0];\n $location_new = $new[0];\n\n $res_name = $conn->query(\"SELECT * FROM location WHERE area = ( SELECT area FROM location WHERE id = $location_old ) AND parentid <> ( SELECT parentid FROM location WHERE id = $location_old ) AND parentid = $location_new\");//Xem ten nay da ton tai trong thu muc chua.\n if ($res_name->num_rows == 0){\n $conn->query(\"UPDATE location SET parentid = $location_new WHERE id = $location_old \");//Di chuyen old vao new.\n echo \"<script type=\\\"text/javascript\\\">alert(\\\"Change location successfully !\\\");</script>\";\n echo '<script type=\"text/javascript\">window.location.href =\"manage.php\";</script>';\n }\n else echo \"<script type=\\\"text/javascript\\\">alert(\\\"Location name already exists ! Please rename before relocation !\\\");</script>\";\n }\n }\n ?>\n\n <body>\n <div id=\"delete\" class=\"modal\">\n <span onclick=\"document.getElementById('delete').style.display='none'\" class=\"close\" title=\"Close Modal\">&times;</span>\n <form class=\"modal-content\" action=\"manage.php\" method = \"post\" role = \"form\">\n <div class=\"container\">\n <center>\n <h1>Delete</h1>\n <p>Are you sure you want to delete this location?.</p>\n </center>\n \n <div class=\"clearfix\">\n <button type=\"button\" onclick=\"document.getElementById('delete').style.display='none'\" class=\"cancelbtn\">Cancel</button>\n <button type=\"submit\" class=\"makebtn\" name=\"do_delete\">YES</button>\n </div>\n </div>\n </form>\n </div>\n </body>\n <?php\n if(isset($_POST[\"do_delete\"])){\n $obj = json_decode($_COOKIE['select_manage'],true);\n function del($id_parent,$conn){\n $res_id_son = $conn->query(\"SELECT id FROM location WHERE parentid = $id_parent \");\n $conn->query(\"DELETE FROM location WHERE id = $id_parent \");//Xoa trong bang location.\n $conn->query(\"DELETE FROM device WHERE areaid = $id_parent \");\n $res_id_router = $conn->query(\"SELECT id FROM router WHERE areaid = $id_parent \");\n if ($res_id_router->num_rows > 0){\n while($row = $res_id_router->fetch_assoc()){\n $id_sensor = $row[\"id\"];\n $conn->query(\"DELETE FROM router WHERE id = $id_sensor \");//Xoa trong bang router.\n $conn->query(\"DELETE FROM sensordata WHERE sensor = $id_sensor \");//Xoa trong bang sensordata.\n $conn->query(\"DELETE FROM device WHERE areaid = $id_sensor \");\n }\n }\n if ($res_id_son->num_rows > 0){\n while($row = $res_id_son->fetch_assoc()){\n $save_id = $row[\"id\"];\n del($save_id,$conn);\n }\n }\n }\n if($obj==NULL){\n echo \"<script type=\\\"text/javascript\\\">alert(\\\"You must select a location :((\\\");</script>\";\n }\n else{\n $id_area = $obj[0];\n del($id_area,$conn);\n echo \"<script type=\\\"text/javascript\\\">alert(\\\"Delete complete !\\\");</script>\";\n echo '<script type=\"text/javascript\">window.location.href =\"manage.php\";</script>';\n }\n }\n ?>\n\n <body>\n <div id=\"rename\" class=\"modal\" >\n <span onclick=\"document.getElementById('rename').style.display='none'\" class=\"close\" title=\"Close Modal\">&times;</span>\n <form class=\"modal-content\" action=\"manage.php\" method = \"post\" role = \"form\">\n <div class=\"container\">\n <center>\n <h1>Rename</h1>\n <p>Please fill in this form to rename.</p>\n </center>\n <hr>\n <label for=\"rename\"><b>New name</b></label>\n <input type=\"text\" placeholder=\"Enter New Name\" name=\"newname\" required>\n <div class=\"clearfix\">\n <button type=\"button\" onclick=\"document.getElementById('rename').style.display='none'\" class=\"cancelbtn\" style=\"float:left;\">Cancel</button>\n <button type=\"submit\" class=\"makebtn\" name=\"do_rename\">Update</button>\n </div>\n </div>\n </form>\n </div>\n </body>\n <?php\n if(isset($_POST[\"do_rename\"])){\n $obj = json_decode($_COOKIE['select_manage'],true);\n if($obj==NULL){\n echo \"<script type=\\\"text/javascript\\\">alert(\\\"You must select a location :((\\\");</script>\";\n }\n else{\n $id_area = $obj[0];\n $newname = (string)$_POST[\"newname\"];\n // echo \"<script type=\\\"text/javascript\\\">alert(\\\"\".$kt .\" \" .$id_area .\" \" .$newname .\"\\\");</script>\";\n $res_id_parent = $conn->query(\"SELECT parentid FROM location WHERE id = $id_area \");//Lay parent cua node.\n if ($res_id_parent->num_rows > 0){\n while($row = $res_id_parent->fetch_assoc()){\n $id_parent = $row[\"parentid\"];\n // echo \"<script type=\\\"text/javascript\\\">alert(\\\"\".$id_parent.\"\\\");</script>\";\n $res_name = $conn->query(\"SELECT * FROM location WHERE area = '$newname' AND id <> $id_area AND parentid = $id_parent\");//Xem ten nay da ton tai trong thu muc chua.\n if ($res_name->num_rows == 0){\n $conn->query(\"UPDATE location SET area = '$newname' WHERE id = $id_area \");//Doi ten cho area.\n echo \"<script type=\\\"text/javascript\\\">alert(\\\"Done :)\\\");</script>\";\n echo '<script type=\"text/javascript\">window.location.href =\"manage.php\";</script>';\n }\n else echo \"<script type=\\\"text/javascript\\\">alert(\\\"Location name already exists ! Please try again !\\\");</script>\";\n }\n }\n }\n }\n ?>\n\n <body>\n <div id=\"adddevice\" class=\"modal\">\n <span onclick=\"document.getElementById('adddevice').style.display='none'\" class=\"close\" title=\"Close Modal\">&times;</span>\n <form class=\"modal-content\" action=\"manage.php\" method = \"post\" role = \"form\">\n <div class=\"container\">\n <center>\n <h1>Add device</h1>\n <p>Please fill in this form to add device.</p>\n </center>\n <hr>\n <label for=\"namedevice\"><b>Device's name </b></label>\n <input type=\"text\" placeholder=\"Enter device's name\" name=\"device_name\" required>\n\n <label for=\"codedevice\"><b>Control code </b></label>\n <input type=\"text\" placeholder=\"Enter device's code\" name=\"device_code\" required>\n <div class=\"clearfix\">\n <button type=\"button\" onclick=\"document.getElementById('adddevice').style.display='none'\" class=\"cancelbtn\">Cancel</button>\n <button type=\"submit\" class=\"makebtn\" name=\"do_adddevice\" >ADD</button>\n </div>\n </div>\n </form>\n </div>\n </body>\n <?php\n if(isset($_POST[\"do_adddevice\"])){\n $obj = json_decode($_COOKIE['select_manage'],true);\n $name_device = (string)$_POST[\"device_name\"];\n $code_device = (string)$_POST[\"device_code\"];\n \n if($obj==NULL){\n echo \"<script type=\\\"text/javascript\\\">alert('You need choose a location !');</script>\";\n }\n else{\n $id_area = $obj[0];\n $res_leaf = $conn->query(\"SELECT * FROM location WHERE ext = 'fas fa-building' AND id = $id_area \");//Chi duoc phep chon location ko duoc chon device.\n if ($res_leaf->num_rows == 0){\n $res_name = $conn->query(\"SELECT * FROM device WHERE name = '$name_device' AND areaid = $id_area \");//Xem ten nay da ton tai trong thu muc chua.\n if ($res_name->num_rows == 0){\n $conn->query(\"INSERT INTO device (areaid,name,code) VALUES (\\\"\" .$id_area .\"\\\",\\\"\" .$name_device .\"\\\",\\\"\" .$code_device .\"\\\")\");\n echo \"<script type=\\\"text/javascript\\\">alert('Create new device successfully !');</script>\";\n echo '<script type=\"text/javascript\">window.location.href =\"manage.php\";</script>';\n }\n else echo \"<script type=\\\"text/javascript\\\">alert('Device name already exists ! Please try again !');</script>\";\n }\n else echo \"<script type=\\\"text/javascript\\\">alert(\\\"You can't add into a location ! Please choose a esp device!\\\");</script>\";\n }\n }\n ?>\n\n <body>\n <div id=\"addsensor\" class=\"modal\">\n <span onclick=\"document.getElementById('addsensor').style.display='none'\" class=\"close\" title=\"Close Modal\">&times;</span>\n <form class=\"modal-content\" action=\"manage.php\" method = \"post\" role = \"form\">\n <div class=\"container\">\n <center>\n <h1>Add sensor</h1>\n <p>Please fill in this form to add sensor.</p>\n </center>\n <hr>\n <label for=\"macadd\"><b>MAC Address</b></label>\n <input type=\"text\" placeholder=\"Enter MAC Address\" name=\"macadd\" required>\n <label for=\"sensor\"><b>Sensor's location </b></label>\n <input type=\"text\" placeholder=\"Enter Sensor's location\" name=\"sensor\" required>\n <div class=\"clearfix\">\n <button type=\"button\" onclick=\"document.getElementById('addsensor').style.display='none'\" class=\"cancelbtn\">Cancel</button>\n <button type=\"submit\" class=\"makebtn\" name=\"do_addsensor\" >ADD</button>\n </div>\n </div>\n </form>\n </div>\n </body>\n <?php\n if(isset($_POST[\"do_addsensor\"])){\n $obj = json_decode($_COOKIE['select_manage'],true);\n $macadd = (string)$_POST[\"macadd\"];\n $loc_sensor = (string)$_POST[\"sensor\"];\n \n $res_mac = $conn->query(\"SELECT * FROM location WHERE mac = '$macadd'\");//Xem dia chi mac nay da ton tai chua.\n if ($res_mac->num_rows == 0){\n if($obj==NULL){\n $res_name = $conn->query(\"SELECT * FROM location WHERE area = '$loc_sensor' AND parentid IS NULL\");//Xem ten nay da ton tai trong thu muc chua.\n if ($res_name->num_rows == 0){\n $conn->query(\"INSERT INTO location (mac, area, ext) VALUES (\\\"\" .$macadd .\"\\\",\\\"\" .$loc_sensor .\"\\\",'fas fa-map-marker-alt')\");\n echo \"<script type=\\\"text/javascript\\\">alert('Create new sensor successfully !');</script>\";\n echo '<script type=\"text/javascript\">window.location.href =\"manage.php\";</script>';\n }\n else echo \"<script type=\\\"text/javascript\\\">alert('Sensor name already exists ! Please try again !');</script>\";\n }\n else{\n $id_area = $obj[0];\n $res_leaf = $conn->query(\"SELECT * FROM location WHERE ext = 'fas fa-building' AND id = $id_area \");//Chi duoc phep chon location ko duoc chon sensor.\n if ($res_leaf->num_rows > 0){\n $res_name = $conn->query(\"SELECT * FROM location WHERE area = '$loc_sensor' AND parentid = $id_area \");//Xem ten nay da ton tai trong thu muc chua.\n if ($res_name->num_rows == 0){\n $conn->query(\"INSERT INTO location (mac, area, parentid, ext) VALUES (\\\"\" .$macadd .\"\\\",\\\"\" .$loc_sensor .\"\\\",\\\"\" .$id_area .\"\\\",'fas fa-map-marker-alt')\");\n echo \"<script type=\\\"text/javascript\\\">alert('Create new sensor successfully !');</script>\";\n echo '<script type=\"text/javascript\">window.location.href =\"manage.php\";</script>';\n }\n else echo \"<script type=\\\"text/javascript\\\">alert('Sensor name already exists ! Please try again !');</script>\";\n }\n else echo \"<script type=\\\"text/javascript\\\">alert(\\\"You can't add into a sensor ! Please choose a location !\\\");</script>\";\n }\n }\n else echo \"<script type=\\\"text/javascript\\\">alert('MAC address already exists ! Please try again !');</script>\";\n }\n ?>\n\n\n <body>\n <div id=\"addlocation\" class=\"modal\">\n <span onclick=\"document.getElementById('addlocation').style.display='none'\" class=\"close\" title=\"Close Modal\">&times;</span>\n <form class=\"modal-content\" action=\"manage.php\" method = \"post\" role = \"form\">\n <div class=\"container\">\n <center>\n <h1>Add location</h1>\n <p>Please fill in this form to add location.</p>\n </center>\n <hr>\n <label for=\"location\"><b>Location's name </b></label>\n <input type=\"text\" placeholder=\"Location's name\" name=\"location\" required>\n <label for=\"describe\"><b>Describe </b></label>\n <input type=\"text\" placeholder=\"Enter Describe\" name=\"describe\" required>\n <div class=\"clearfix\">\n <button type=\"button\" onclick=\"document.getElementById('addlocation').style.display='none'\" class=\"cancelbtn\">Cancel</button>\n <button type=\"submit\" class=\"makebtn\" name=\"do_addlocation\" >ADD</button>\n </div>\n </div>\n </form>\n </div>\n </body>\n <?php\n if(isset($_POST[\"do_addlocation\"])){\n $obj = json_decode($_COOKIE['select_manage'],true);\n if($obj==NULL){\n $loc_name = (string)$_POST[\"location\"];\n $loc_des = (string)$_POST[\"describe\"];\n $res_name = $conn->query(\"SELECT * FROM location WHERE area = '$loc_name' AND parentid IS NULL\");//Xem ten nay da ton tai trong thu muc chua.\n if ($res_name->num_rows == 0){\n $conn->query(\"INSERT INTO location (area, des, ext) VALUES (\\\"\" .$loc_name .\"\\\",\\\"\" .$loc_des .\"\\\",'fas fa-building')\");\n echo \"<script type=\\\"text/javascript\\\">alert('Create new location successfully !');</script>\";\n echo '<script type=\"text/javascript\">window.location.href =\"manage.php\";</script>';\n }\n else echo \"<script type=\\\"text/javascript\\\">alert('Location name already exists ! Please try again !');</script>\";\n }\n else{\n $id_area = $obj[0];\n $res_leaf = $conn->query(\"SELECT id FROM location WHERE ext = 'fas fa-building' AND id = $id_area \");//Chi duoc phep chon location ko duoc chon sensor.\n if ($res_leaf->num_rows > 0){\n $loc_name = (string)$_POST[\"location\"];\n $loc_des = (string)$_POST[\"describe\"];\n $res_name = $conn->query(\"SELECT * FROM location WHERE area = '$loc_name' AND parentid = $id_area \");//Xem ten nay da ton tai trong thu muc chua.\n if ($res_name->num_rows == 0){\n $conn->query(\"INSERT INTO location (area, des, parentid, ext) VALUES (\\\"\" .$loc_name .\"\\\",\\\"\" .$loc_des .\"\\\",\\\"\" .$id_area .\"\\\",'fas fa-building')\");\n echo \"<script type=\\\"text/javascript\\\">alert('Create new location successfully !');</script>\";\n echo '<script type=\"text/javascript\">window.location.href =\"manage.php\";</script>';\n }\n else echo \"<script type=\\\"text/javascript\\\">alert('Location name already exists ! Please try again !');</script>\";\n }\n else echo \"<script type=\\\"text/javascript\\\">alert(\\\"You can't add into a sensor ! Please choose a location !\\\");</script>\";\n }\n }\n ?>\n </body>\n</html>\n" }, { "alpha_fraction": 0.39024990797042847, "alphanum_fraction": 0.40900957584381104, "avg_line_length": 50.119873046875, "blob_id": "afc8a0e838136b18cec2563a749a01cdbc7cdeef", "content_id": "51aa44ee8dd92bc433258cdf7142f4d7ab400638", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 16211, "license_type": "permissive", "max_line_length": 167, "num_lines": 317, "path": "/real_time.php", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html>\n <head>\n <title> Monitor </title>\n <meta charset=\"UTF-8\">\n <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.0/css/all.css\">\n <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\"></script>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"/main/bootstrap.css\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"/main/style.css\">\n \n <script src=\"//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js\"></script>\n <link rel=\"stylesheet\" href=\"//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/themes/default/style.min.css\" />\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/jstree.min.js\"></script>\n <script>\n function drawDonut(c,posX,posY,value,oldValue,minValue,maxValue,rgb){\n var range = maxValue - minValue,\n ratio = 100/range,\n fps = 1000 / 200,\n procent = 0,\n oneProcent = 360 / range,\n oneColor = 150 / range,\n result = oneProcent * (value - minValue);\n c.font = \"22px Lato\";\n var deegres = oldValue * oneProcent;\n var acrInterval = setInterval (function() {\n if (deegres > result){\n factor = -1; \n }else{\n factor = 1;\n }\n deegres += factor;\n c.clearRect( 0, 0, posX*2, posY*2 );\n procent = deegres / oneProcent + minValue;\n if(procent > maxValue){\n procent = maxValue;\n }else if(procent < minValue){\n procent = minValue;\n }\n index = 1;\n c.beginPath();\n c.arc( posX, posY, 40, (Math.PI/180) * 270, (Math.PI/180) * (270 + 360) );\n c.strokeStyle = '#b1b1b1';\n c.lineWidth = '18';\n c.stroke();\n c.beginPath();\n c.strokeStyle = rgb;\n c.lineWidth = '18';\n c.arc( posX, posY, 40, (Math.PI/180) * 270, (Math.PI/180) * (270 + deegres) );\n c.stroke();\n c.fillStyle = rgb;\n c.textAlign = \"center\";\n c.textBaseline = \"middle\";\n c.fillText(procent.toFixed(index),posX,posY);\n if( deegres * factor >= result * factor ) clearInterval(acrInterval);\n }, fps);\n }\n </script>\n <script>\n function printData(){\n var old = new Array();\n \n setInterval(function () { \n $.ajax({\n dataType: 'text', // Type text\n url : 'make_general.php', // Request to solve.php\n data : {'request':'113'}, // Send $_POST[\"request\"]\n type : 'POST', // Method = POST\n\n success : function(result){\n var data = JSON.parse(result);\n for(var i in data){\n if(!old[i]) old[i]=0;\n console.log(old);\n console.log(data[i]['cr_vl']);\n tmp = document.getElementById('donut-'+i);\n drawDonut(tmp.getContext(\"2d\"),60,90,data[i]['cr_vl'] ,old[i],0,data[i]['mx_r'],data[i]['stt_cl']);\n old[i]=data[i]['cr_vl'];\n document.getElementById('max'+i).innerHTML = data[i]['mx'];\n document.getElementById('min'+i).innerHTML = data[i]['mn'];\n document.getElementById('avg'+i).innerHTML = data[i]['av'];\n document.getElementById('time-max'+i).innerHTML = data[i]['mx_t'];\n document.getElementById('time-min'+i).innerHTML = data[i]['mn_t'];\n document.getElementById('status'+i).innerHTML = data[i]['stt'];\n document.getElementById('range'+i).innerHTML = data[i]['mn'] +'-'+data[i]['mx'];\n var stt = document.getElementById('status'+i);\n stt.style.color = data[i]['stt_cl'];\n }\n }\n });\n }, 4000);\n }\n printData();\n </script>\n </head>\n <body style=\"position:relative; margin: 0px;\">\n <?php\n include \"connect.php\";\n include \"taskbar.php\";\n include \"sidebar.php\";\n ?>\n <script>\n openTab(2);\n </script>\n <div id=\"page-content\" style=\"float:left; width: 89% ; height:auto;color: #18699F;margin: 70px 0px 0px 200px;\">\n <div id=\"general-page\" class=\"page\">\n <div id=\"general-title\" class=\"page-title\"> \n <div> Detail </div> \n </div>\n \n <?php\n function find_parent($id_parent,$conn){\n $res_parent = $conn->query(\"SELECT * FROM location WHERE id = $id_parent \");\n if ($res_parent->num_rows > 0){\n while($row = $res_parent->fetch_assoc()){\n $save_id = $row[\"parentid\"];\n $save_area = $row[\"area\"];\n return $save_area .\" / \" .find_parent($save_id,$conn);\n }\n }\n }\n $obj = json_decode($_COOKIE[\"select\"],true);\n if(sizeof($obj) != 0){\n for( $i = 0; $i < sizeof($obj) ; $i++){\n $id_area = $obj[$i];\n $area = NULL;\n $des_area = NULL;\n $res_id = $conn->query(\"SELECT * FROM location WHERE parentid = $id_area \");//Xem id nay co phai la node la khong.\n if ($res_id->num_rows == 0){\n $res_area = $conn->query(\"SELECT * FROM location WHERE id = $id_area \");\n if ($res_area->num_rows > 0){\n while($row = $res_area->fetch_assoc()){\n $des_area = $row[\"des\"];\n $area = find_parent($id_area,$conn);\n }\n }\n echo \"<div style=\\\"margin:10px 10px 10px 10px;border: 3px solid black; width:100% ;background-color: #FFFFFF ; float:left\\\">\n <div class=\\\"sub-title\\\">\n <span style=\\\"float:left ;margin-left: 15px; color:#FFF8DC;\\\">Location : $area </span>\n <!--<div style=\\\"float:left ; margin-left: 50px; font-size: 20px ;color:#FFF8DC;\\\">Mô tả :$des_area</div>-->\n </div>\";\n\n $res_type = $conn->query(\"SELECT * FROM sensor\"); //truy van cac kieu du lieu da co.\n if ($res_type->num_rows > 0){\n while($row = $res_type->fetch_assoc()){\n $id_sensor = $row[\"id\"];\n $sensor = $row[\"type\"];\n $icon = $row['icon'];\n $unit = $row[\"ext\"];\n $color = $row[\"des\"];\n $res_cur_id = $conn->query(\"SELECT id FROM router WHERE areaid = $id_area and sensorid = $id_sensor\");\n if ($res_cur_id->num_rows > 0){\n while($row = $res_cur_id->fetch_assoc()){\n $cur_id = $row[\"id\"];\n echo \"\n <div style=\\\"margin:10px 10px 10px 10px;border: 1px solid gray; width: 395px ; height : 200px ;float:left ;background-color: #ECF0F5;\\\">\n <div class=\\\"sub-title\\\">\n <span style=\\\"margin-left: 15px; font-size: 20px; color:\".$color.\";\\\"><span class='$icon'></span> $sensor</span>\n </div>\n <div style=\\\"height:120px;width:120px;float:left\\\">\n <canvas id=\\\"donut-$cur_id\\\"width=\\\"250\\\" height=\\\"250\\\">\n </canvas>\n </div>\n <div style=\\\"float:left;\\\">\n <table title=\\\"$cur_id Table\\\" style=\\\" margin:20px 0px 10px 0px ; border-collapse: collapse;\\\">\n <tr>\n <td style=\\\"border: none;font-size: 15px;\\\"> Avg </td>\n <td style=\\\"border: none;font-size: 15px;\\\" id=\\\"avg$cur_id\\\"> </td>\n \n </tr>\n <tr>\n <td style=\\\"border: none;font-size: 15px;\\\"> Max </td>\n <td style=\\\"border: none;font-size: 15px;\\\" id=\\\"max$cur_id\\\"> NaNa </td>\n <td style=\\\"border: none;font-size: 15px;\\\" id=\\\"time-max$cur_id\\\"> NaNa </td>\n </tr>\n <tr>\n <td style=\\\"border: none;font-size: 15px;\\\"> Min </td>\n <td style=\\\"border: none;font-size: 15px;\\\" id=\\\"min$cur_id\\\"> NaNa </td>\n <td style=\\\"border: none;font-size: 15px;\\\" id=\\\"time-min$cur_id\\\"> NaNa </td>\n </tr>\n <tr>\n <td style=\\\"border: none;font-size: 15px;\\\"> Rang </td>\n <td solspan=\\\"2\\\" style=\\\"border: none;font-size: 15px;\\\" id=\\\"range$cur_id\\\";></td>\n <td style=\\\"border: none;font-size: 15px;\\\">($unit)</td>\n </tr>\n <tr>\n <td style=\\\"border: none;font-size: 15px;\\\"> Status </td>\n <td style=\\\"border: none;font-size: 15px;\\\"></td>\n <b><td solspan=\\\"2\\\" style=\\\"border: none;font-size: 15px;\\\" id=\\\"status$cur_id\\\";> NaNa </td></b>\n </tr>\n </table>\n </div>\n </div>\n \" ; \n }\n }\n }\n }\n echo \"</div>\";\n }\n }\n }\n else{\n $res_all = $conn->query(\"SELECT * FROM location\"); //truy van cac kieu du lieu da co.\n if ($res_all->num_rows > 0){\n while($row = $res_all->fetch_assoc()){\n $id_area = $row[\"id\"];\n $area = NULL;\n $des_area = NULL;\n $res_id = $conn->query(\"SELECT * FROM location WHERE parentid = $id_area \");//Xem id nay co phai la node la khong.\n if ($res_id->num_rows == 0){\n $ind = 0;\n\n $res_area = $conn->query(\"SELECT * FROM location WHERE id = $id_area \");\n if ($res_area->num_rows > 0){\n while($row = $res_area->fetch_assoc()){\n $des_area = $row[\"des\"];\n $area = find_parent($id_area,$conn);\n }\n }\n\n echo \"<div style=\\\"margin:10px 10px 10px 10px;border: 3px solid black; width:99% ;background-color: #FFFFFF ; float:left\\\">\n <div class=\\\"sub-title\\\">\n <span style=\\\"float:left ;margin-left: 15px; color:#FFF8DC;\\\">Location : $area </span>\n <!--<div style=\\\"float:left ; margin-left: 50px; font-size: 20px ;color:#FFF8DC;\\\">Mô tả :$des_area</div>-->\n </div>\";\n\n $res_type = $conn->query(\"SELECT * FROM sensor\"); //truy van cac kieu du lieu da co.\n if ($res_type->num_rows > 0){\n while($row = $res_type->fetch_assoc()){\n $id_sensor = $row[\"id\"];\n $sensor = $row[\"type\"];\n $icon = $row['icon'];\n $unit = $row[\"ext\"];\n $color = $row[\"des\"];\n $res_cur_id = $conn->query(\"SELECT id FROM router WHERE areaid = $id_area and sensorid = $id_sensor\");\n if ($res_cur_id->num_rows > 0){\n $ind = $ind + 2;\n while($row = $res_cur_id->fetch_assoc()){\n $cur_id = $row[\"id\"];\n\n $Avg = $conn->query(\"SELECT AVG(value) AS av FROM sensordata WHERE sensor = $cur_id\");\n if ($Avg->num_rows > 0){\n while($row = $Avg->fetch_assoc()){\n $avg_value=$row[\"av\"];\n }\n }\n \n $Mx = $conn->query(\"SELECT * FROM sensordata WHERE value = (SELECT MAX(value) FROM sensordata WHERE sensor = $cur_id) AND sensor = $cur_id\");\n if ($Mx->num_rows > 0){\n while($row = $Mx->fetch_assoc()){\n $max_value=$row[\"value\"];\n $max_time=(string)$row[\"time\"];\n }\n }\n $Mn = $conn->query(\"SELECT * FROM sensordata WHERE value = (SELECT MIN(value) FROM sensordata WHERE sensor = $cur_id) AND sensor = $cur_id\");\n if ($Mn->num_rows > 0){\n while($row = $Mn->fetch_assoc()){\n $min_value=$row[\"value\"];\n $min_time=(string)$row[\"time\"];\n }\n }\n \n $cur_value = $conn->query(\"SELECT * FROM sensordata WHERE id = ( SELECT MAX(id) FROM sensordata WHERE sensor = $cur_id )\");\n echo \"\n <div style=\\\"margin:10px 10px 10px 10px;border: 1px solid gray; width: 395px ; height : 200px ;float:left ;background-color: #ECF0F5;\\\">\n <div class=\\\"sub-title\\\">\n <span style=\\\"margin-left: 15px; font-size: 20px; color:\".$color.\";\\\"><span class='$icon'></span> $sensor</span>\n </div>\n <div style=\\\"height:120px;width:120px;float:left\\\">\n <canvas id=\\\"donut-$cur_id\\\"width=\\\"250\\\" height=\\\"250\\\">\n </canvas>\n </div>\n <div style=\\\"float:left;\\\">\n <table title=\\\"$cur_id Table\\\" style=\\\" margin:20px 0px 10px 0px ; border-collapse: collapse;\\\">\n <tr>\n <td style=\\\"border: none;font-size: 15px;\\\"> Avg </td>\n <td style=\\\"border: none;font-size: 15px;\\\" id=\\\"avg$cur_id\\\"> </td>\n \n </tr>\n <tr>\n <td style=\\\"border: none;font-size: 15px;\\\"> Max </td>\n <td style=\\\"border: none;font-size: 15px;\\\" id=\\\"max$cur_id\\\"> NaNa </td>\n <td style=\\\"border: none;font-size: 15px;\\\" id=\\\"time-max$cur_id\\\"> $max_time </td>\n </tr>\n <tr>\n <td style=\\\"border: none;font-size: 15px;\\\"> Min </td>\n <td style=\\\"border: none;font-size: 15px;\\\" id=\\\"min$cur_id\\\"> NaNa </td>\n <td style=\\\"border: none;font-size: 15px;\\\" id=\\\"time-min$cur_id\\\"> $min_time </td>\n </tr>\n <tr>\n <td style=\\\"border: none;font-size: 15px;\\\"> Range </td>\n <td style=\\\"border: none;font-size: 15px;\\\"></td>\n <td solspan=\\\"2\\\" style=\\\"border: none;font-size: 15px;\\\"> $min_value - $max_value ($don_vi)</td>\n </tr>\n <tr>\n <td style=\\\"border: none;font-size: 15px;\\\"> Status </td>\n <td style=\\\"border: none;font-size: 15px;\\\"></td>\n <td solspan=\\\"2\\\" style=\\\"border: none;font-size: 15px;color:$colorstt;\\\"> $status </td>\n </tr>\n </table>\n </div>\n </div>\n \" ;\n }\n }\n }\n }\n echo \"</div>\";\n }\n }\n }\n }\n ?>\n </div>\n </div> \n </body>\n</html>\n" }, { "alpha_fraction": 0.6089184880256653, "alphanum_fraction": 0.6191696524620056, "avg_line_length": 32.06779479980469, "blob_id": "c3b9cd5ae5e14b2066a6d2c24459e306b7855a5e", "content_id": "a53f0d2ecf17bd8f2cc00ff80f184bbd3c5c1585", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1951, "license_type": "permissive", "max_line_length": 126, "num_lines": 59, "path": "/python/savedata.py", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "import MySQLdb\nimport json\nfrom datetime import datetime\n\ndef Sensor(jsondata):\n\tdata = json.loads(jsondata)\n\tmac_t = (data['mac'])\n\tcode_t = (data['code'])\n\tvalue_t = (data['value'])\n\t# time_t = datetime.now()\n\tfor i in range(0,len(code_t)):\n\n\t\tcode_i = code_t[i]\n\t\tvalue_i = value_t[i]\n\t\tconn = MySQLdb.connect(\"localhost\",\"root\",\"\",\"doan\")\n\t\tcur = conn.cursor()\n\n\t\tsql_mac = \"\"\"SELECT mac FROM location WHERE mac = \\\"%s\\\"\"\"\" %mac_t\n\t\tcur.execute(sql_mac)\n\t\tresults_mac = cur.fetchall()\n\t\tif not results_mac:\n\t\t\tsql_location = \"\"\"INSERT INTO location(mac,area,ext) VALUES(\\\"%s\\\",\\\"%s\\\",\\\"%s\\\")\"\"\" %(mac_t,mac_t,'fas fa-map-marker-alt')\n\t\t\tcur.execute(sql_location)\n\t\t\tconn.commit()\n\n\t\tsql_sensor = \"\"\"SELECT code FROM sensor WHERE code = \\\"%s\\\"\"\"\" %code_i\n\t\tcur.execute(sql_sensor)\n\t\tresults_sensor = cur.fetchall()\n\t\tif not results_sensor:\n\t\t\tsql_location = \"\"\"INSERT INTO sensor (code) VALUES(\\\"%s\\\")\"\"\" %code_i\n\t\t\tcur.execute(sql_location)\n\t\t\tconn.commit()\n\n\t\tsql1 = \"\"\"SELECT id FROM sensor WHERE code = \\\"%s\\\"\"\"\" %code_i\n\t\tcur.execute(sql1)\n\t\tcode_id = cur.fetchall()\n\n\t\tsql2 = \"\"\"SELECT id FROM location WHERE mac = \\\"%s\\\"\"\"\" %mac_t\n\t\tcur.execute(sql2)\n\t\tmac_id = cur.fetchall()\n\n\t\tsql_sensor_id = \"\"\"SELECT id FROM router WHERE sensorid = \\\"%s\\\" AND areaid = \\\"%s\\\"\"\"\" %(code_id[0][0], mac_id[0][0])\n\t\tcur.execute(sql_sensor_id)\n\t\tresults_sensor_id = cur.fetchall()\n\t\tif not results_sensor_id:\n\t\t\tsql_location = \"\"\"INSERT INTO router (areaid, sensorid, active) VALUES(\\\"%s\\\",\\\"%s\\\", 1)\"\"\" %(mac_id[0][0], code_id[0][0])\n\t\t\tcur.execute(sql_location)\n\t\t\tconn.commit()\n\n\t\tsensor_id = \"\"\"SELECT id FROM router WHERE sensorid = \\\"%s\\\" AND areaid = \\\"%s\\\"\"\"\" %(code_id[0][0], mac_id[0][0])\n\t\tcur.execute(sensor_id)\n\t\tres_sensor_id = cur.fetchall()\n\n\t\tsql_data = \"\"\"insert INTO sensordata (sensor, value,time) VALUES(\\\"%s\\\", \\\"%s\\\",now())\"\"\" %(res_sensor_id[0][0],value_i)\n\t\tcur.execute(sql_data)\n\t\tconn.commit()\n\n\tprint('Data saved.')\n\tconn.close\n" }, { "alpha_fraction": 0.5689722299575806, "alphanum_fraction": 0.5795232653617859, "avg_line_length": 45.54545593261719, "blob_id": "922e063d4aeb96f859443ef3e58729920971cb1b", "content_id": "fa06d4afbec2e3056124fc11060d6f87ebb0ac25", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2559, "license_type": "permissive", "max_line_length": 116, "num_lines": 55, "path": "/make_control.php", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "<?php\n require \"phpMQTT-master/phpMQTT.php\";\n include \"connect.php\";\n\n if (isset($_POST['change'])) {\n $status = $_POST['change'];\n $id_device = $_POST['id'];\n $mqtt = new phpMQTT(\"soldier.cloudmqtt.com\", 11600, \"PHP MQTT Publisher\");\n if ($mqtt->connect(true, NULL, \"guapvdfg\",\"k5WzGtSNWMQY\")) {\n if($status == 1)\n $conn->query(\"UPDATE device SET status = 'checked' WHERE id = $id_device \");\n else\n $conn->query(\"UPDATE device SET status = NULL WHERE id = $id_device \");\n $mqtt->publish($id_device,1-$status, 0);\n $mqtt->close();\n echo '<script type=\"text/javascript\">window.location.href =\"control.php\";</script>';\n }\n }\n if (isset($_POST['all_on'])) {\n // $obj_area = json_decode($_COOKIE[\"select\"],true);\n $id_area = $_POST[\"all_on\"];\n $res_device = $conn->query(\"SELECT * FROM device WHERE areaid = $id_area\");//Tat ca cac thiet bi co trong phong.\n if ($res_device->num_rows > 0){\n while($row = $res_device->fetch_assoc()){\n $id_device = $row[\"id\"];\n echo \"<script>console.log(\".$id_device.\");</script>\";\n $mqtt = new phpMQTT(\"soldier.cloudmqtt.com\", 11600, \"PHP MQTT Publisher\");\n if ($mqtt->connect(true, NULL, \"guapvdfg\",\"k5WzGtSNWMQY\")) {\n $conn->query(\"UPDATE device SET status = 'checked' WHERE id = $id_device \");\n $mqtt->publish($id_device,0, 0);\n $mqtt->close();\n echo '<script type=\"text/javascript\">window.location.href =\"control.php\";</script>';\n }\n }\n }else echo '<script type=\"text/javascript\">window.location.href =\"control.php\";</script>';\n }\n if (isset($_POST['all_off'])) {\n // $obj_area = json_decode($_COOKIE[\"select\"],true);\n $id_area = $_POST[\"all_off\"];\n $res_device = $conn->query(\"SELECT * FROM device WHERE areaid = $id_area\");//Tat ca cac thiet bi co trong phong.\n if ($res_device->num_rows > 0){\n while($row = $res_device->fetch_assoc()){\n $id_device = $row[\"id\"];\n echo \"<script>console.log(\".$id_device.\");</script>\";\n $mqtt = new phpMQTT(\"soldier.cloudmqtt.com\", 11600, \"PHP MQTT Publisher\");\n if ($mqtt->connect(true, NULL, \"guapvdfg\",\"k5WzGtSNWMQY\")) {\n $conn->query(\"UPDATE device SET status = NULL WHERE id = $id_device \");\n $mqtt->publish($id_device,1, 0);\n $mqtt->close();\n echo '<script type=\"text/javascript\">window.location.href =\"control.php\";</script>';\n }\n }\n }else echo '<script type=\"text/javascript\">window.location.href =\"control.php\";</script>';\n }\n?>" }, { "alpha_fraction": 0.45477545261383057, "alphanum_fraction": 0.4765971004962921, "avg_line_length": 33.74725341796875, "blob_id": "4ee254b5527fc15d106b7def1b84d6afd37e1bc7", "content_id": "09f48ad18c3e75afe165ec0f5c00cc26b7774741", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3162, "license_type": "permissive", "max_line_length": 160, "num_lines": 91, "path": "/index.php", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html>\n <head>\n <title> Monitor </title>\n <meta charset=\"UTF-8\">\n <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\"></script>\n <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.0/css/all.css\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js\"></script>\n <link rel=\"stylesheet\" href=\"//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/themes/default/style.min.css\" />\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/jstree.min.js\"></script>\n <script>\n function createCookie(name, value, days) {\n var expires;\n if (days) {\n var date = new Date();\n date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));\n expires = \"; expires=\" + date.toGMTString();\n }\n else {\n expires = \"\";\n }\n document.cookie = name+ \"=\" + value + expires + \"; path=/\";\n //console.log(document.cookie);\n }\n createCookie(\"select_manage\",'', \"10\");\n $(function () {\n $(\"#tree\").jstree({\n \"checkbox\": {\n \"keep_selected_style\": false,\n \"three_state\":false,\n \"real_checkboxes\":false\n },\n \"plugins\": [\"types\", \"checkbox\"],\n \"core\": {\n \"multiple\": false\n },\n \"types\": {\n \"default\": {\n \"icon\": \"fas fa-map-marker-alt\"\n }\n }\n });\n $(\"#tree\").bind(\"changed.jstree\",\n function (e, data) {\n var output = {};\n for(i=0 ;i<data.selected.length ;i++){\n output[i] = data.selected[i];\n }\n var kq = JSON.stringify(output);\n console.log(output);\n console.log(kq);\n createCookie(\"select_manage\", kq , \"10\");\n });\n });\n </script>\n </head>\n <div id=\"container\">\n <body style=\"position:relative; margin: 0px;\">\n <?php\n include \"connect.php\";\n include \"taskbar.php\";\n ?>\n <script >\n openTab(5);\n </script>\n <div id=\"sidebar\" style=\"position:fixed;width: 200px;height:100%; background-color: #1E282C; padding: 0px; margin: 70px 0px; color: #ECF0F5; float:left;\">\n </div>\n <div id=\"page-content\" style=\"float:left;height:100%;color: #18699F;margin: 70px 0px 0px 200px;\">\n <div id=\"general-page\" class=\"page\">\n </div>\n <div>\n <script type=\"text/javascript\">\n function printData(){\n setInterval(function(){\n var test = [<?php $Mn=$conn->query(\"SELECT * FROM sensordata WHERE id = (SELECT MAX(id) FROM sensordata)\");\n if ($Mn->num_rows > 0){\n while($row = $Mn->fetch_assoc()){\n echo $row['id'];\n }\n }\n ?>];\n console.log(test);\n },1000);\n }\n printData();\n </script>\n </div>\n </body>\n </div>\n</html>\n" }, { "alpha_fraction": 0.4224051833152771, "alphanum_fraction": 0.43945443630218506, "avg_line_length": 44.03370666503906, "blob_id": "38a01e154a4ec35baa88aa3466a74694df9bc1f8", "content_id": "fafa468b4cd1b6e24be00db511e1062f799e6f3b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 12024, "license_type": "permissive", "max_line_length": 170, "num_lines": 267, "path": "/chart.php", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html>\n <head>\n <title> History </title>\n <meta charset=\"UTF-8\">\n <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\"></script>\n <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.0/css/all.css\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js\"></script>\n <link rel=\"stylesheet\" href=\"//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/themes/default/style.min.css\" />\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/jstree.min.js\"></script>\n <script type=\"text/javascript\" src=\"https://canvasjs.com/assets/script/canvasjs.min.js\"></script>\n <script src=\"https://www.amcharts.com/lib/4/core.js\"></script>\n <script src=\"https://www.amcharts.com/lib/4/charts.js\"></script>\n <script src=\"https://www.amcharts.com/lib/4/themes/animated.js\"></script>\n \n </head>\n\n <body style=\"position:relative; margin: 0px;\">\n <?php\n include \"connect.php\";\n include \"taskbar.php\";\n ?>\n <script>\n openTab(4);\n </script>\n <script>\n function createCookie(name, value, days) {\n var expires;\n if (days) {\n var date = new Date();\n date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));\n expires = \"; expires=\" + date.toGMTString();\n }\n else {\n expires = \"\";\n }\n document.cookie = name+ \"=\" + value + expires + \"; path=/\";\n //console.log(document.cookie);\n }\n $(function () {\n $(\"#tree\").jstree({\n \"checkbox\": {\n \"keep_selected_style\": false,\n \"three_state\":false,\n \"real_checkboxes\":false\n },\n \"plugins\": [\"types\", \"checkbox\"],\n \"core\": {\n \"multiple\": false\n },\n \"types\": {\n \"default\": {\n \"icon\": \"fas fa-map-marker-alt\"\n }\n }\n });\n\n $(\"#tree\").bind(\"changed.jstree\",\n function (e, data) {\n var output = {};\n for(i=0 ;i<data.selected.length ;i++){\n output[i] = data.selected[i];\n }\n var kq = JSON.stringify(output);\n //console.log(output);\n console.log(kq);\n createCookie(\"select_chart\", kq , \"10\");\n });\n });\n </script>\n\n <div id=\"sidebar\" style=\"position:fixed;width: 200px;height:100%; background-color: #1E282C; padding: 0px; margin: 70px 0px; color: #ECF0F5; float:left;z-index: 10;\">\n <div id=\"menu_text\" style=\"height: 60px; text-align: center; vertical-align: middle; line-height: 60px; border-bottom: 1px solid #ECF0F5\">\n <p style=\"font-size: 30px;margin: 0;px border-bottom: 1px solid #ECF0F5; border-top: 1px solid #ECF0F5\"><strong> MENU </strong></p>\n </div>\n <div id=\"tree\" style=\"width: auto; background-color: #ECF0F5 ;color: black; padding: 0px; margin: 5px 0px 5px 5px\">\n <?php\n function trytry($id_parent,$conn){\n $res_id_t = $conn->query(\"SELECT * FROM location WHERE parentid = $id_parent \");\n if ($res_id_t->num_rows > 0){\n echo \"<ul>\";\n while($row = $res_id_t->fetch_assoc()){\n $save_id = $row[\"id\"];\n $save_area = $row[\"area\"];\n $icon = $row[\"ext\"];\n echo \"<li id=\\\"$save_id\\\" data-jstree = '{\\\"icon\\\": \\\"\" .$icon .\"\\\"}'>$save_area\";\n trytry($save_id,$conn);\n echo \"</li>\";\n }\n echo \"</ul>\";\n }\n }\n $res_id = $conn->query(\"SELECT * FROM location where parentid IS NULL \");\n if ($res_id->num_rows > 0){ \n echo \"<ul>\";\n while($row = $res_id->fetch_assoc()){\n $save_id = $row[\"id\"];\n $save_area = $row[\"area\"];\n $icon = $row[\"ext\"];\n echo \"<li id=\\\"$save_id\\\" data-jstree = '{\\\"icon\\\": \\\"\" .$icon .\"\\\"}'>$save_area\";\n trytry($save_id,$conn);\n echo\"</li>\";\n }\n echo \"</ul>\";\n }\n ?>\n \n </div>\n <form action=\"#\" method=\"post\" style = \"margin: 20px auto auto 20px\">\n From:<input type=\"date\" name=\"date_bg\" style = \"margin-top: 20px; border: 1px solid black; background-color: #ECF0F5;font-family: Roboto;\">\n To&nbsp;&nbsp;&nbsp;&nbsp;:<input type=\"date\" name=\"date_end\" style = \"margin-top: 20px; border: 1px solid black; background-color: #ECF0F5;font-family: Roboto;\">\n <input type=\"submit\" class=\"square_btn\" style = \" margin-top: 20px \" name=\"make\" value=\"Select\">\n </form>\n </div> \n\n <div id=\"page-content\" style=\"float:left; height: auto;width: 100%;color: #18699F;margin: 70px 0px 0px 200px;\">\n <div id=\"general-page\" class=\"page\" style=\"height: auto; width: 85%\">\n <?php\n function find_parent($id_parent,$conn){\n $res_parent = $conn->query(\"SELECT * FROM location WHERE id = $id_parent \");\n if ($res_parent->num_rows > 0){\n while($row = $res_parent->fetch_assoc()){\n $save_id = $row[\"parentid\"];\n $save_area = $row[\"area\"];\n return $save_area .\" / \" .find_parent($save_id,$conn);\n }\n }\n }\n if(isset($_POST['make'])){\n $obj = json_decode($_COOKIE[\"select_chart\"],true);\n\n $date_bg = $_POST['date_bg'];\n $date_end = $_POST['date_end'];\n $time_bg = \"\\\"$date_bg 23:59:59\\\"\";\n $time_end = \"\\\"$date_end 23:59:59\\\"\";\n if($date_bg==NULL || $date_end==NULL){\n $date = date(\"Y-m-d\");\n $time_bg = \"\\\"$date 00:00:00\\\"\";\n $time_end = \"\\\"$date 23:59:59\\\"\";\n }\n $time =\"time\";\n for( $i = 0; $i < sizeof($obj) ; $i++){\n $type = \"0\";\n $id_area = $obj[$i];\n \n $res_id = $conn->query(\"SELECT * FROM location WHERE parentid = $id_area \");//Xem id nay co phai la node la khong.\n if ($res_id->num_rows == 0){\n $area = find_parent($id_area,$conn);\n echo \"<center><h1 style= \\\"color: $color;\\\">Location: $area <br> From: $time_bg - : $time_end</h1></center>\";\n $res_type = $conn->query(\"SELECT * FROM sensor\"); //truy van cac kieu du lieu da co.\n if ($res_type->num_rows > 0){\n while($row = $res_type->fetch_assoc()){\n $phpvalue = array();\n $phptimeline = array();\n $len;\n $id_sensor = $row[\"id\"];\n $type = $row[\"code\"];\n $sensor = $row[\"type\"];\n $color = $row[\"des\"];\n $range_1 = explode(\",\",$row[\"arange\"])[1];\n $range_2 = explode(\",\",$row[\"arange\"])[2];\n\n $res_2id = $conn->query(\"SELECT id FROM router WHERE areaid = $id_area and sensorid = $id_sensor\");\n if ($res_2id->num_rows > 0){\n while($row = $res_2id->fetch_assoc()){\n $cur_id = $row[\"id\"];\n $res_his = NULL;\n $res_his = $conn->query(\"SELECT * FROM sensordata WHERE sensor = $cur_id AND $time >= $time_bg AND $time <= $time_end \");\n if ($res_his->num_rows > 0){\n $len = $res_his->num_rows;\n while($row = $res_his->fetch_assoc()){\n $phpvalue[] = $row[\"value\"];\n $phptimeline[] =$row[\"time\"];\n }\n }\n }\n \n $value = json_encode($phpvalue);\n $time_line = json_encode($phptimeline);\n echo \"\n <script>\n am4core.ready(function() {\n // Themes begin\n am4core.useTheme(am4themes_animated);\n // Themes end\n // Create chart instance\n var chart = am4core.create(\\\"chartdiv$type\\\", am4charts.XYChart);\n // Add data\n chart.data = generateChartData$type();\n // Create axes\n var dateAxis = chart.xAxes.push(new am4charts.DateAxis());\n dateAxis.renderer.minGridDistance = 50;\n dateAxis.baseInterval = {\n \\\"timeUnit\\\": \\\"second\\\",\n \\\"count\\\": 1\n };\n dateAxis.tooltipDateFormat = \\\"HH:mm:ss, d MMMM\\\";\n\n var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());\n // Create series\n var series = chart.series.push(new am4charts.LineSeries());\n series.dataFields.valueY = \\\"visits\\\";\n series.dataFields.dateX = \\\"time\\\";\n series.strokeWidth = 3;\n series.stroke = \\\"red\\\";\n series.fill = \\\"red\\\";\n series.fillOpacity = 0.2;\n //series.connect = false;\n //series.tensionX = 0.8;\n //series.minBulletDistance = 10;\n //series.tooltipText = \\\"{valueY}\\\";\n //series.tooltip.pointerOrientation = \\\"vertical\\\";\n //series.tooltip.background.cornerRadius = 20;\n //series.tooltip.background.fillOpacity = 0.5;\n //series.tooltip.label.padding(12,12,12,12)\n\n var range = valueAxis.createSeriesRange(series);\n range.value = $range_1;\n range.endValue = $range_2;\n range.contents.stroke = \\\"green\\\";\n range.contents.fill = range.contents.stroke;\n range.contents.fillOpacity = 0.2;\n\n // Add scrollbar\n chart.scrollbarX = new am4core.Scrollbar();\n //chart.scrollbarX.series.push(series);\n // Add cursor\n chart.background.fill = '#ffffff'\n chart.background.opacity = 1\n chart.cursor = new am4charts.XYCursor();\n chart.cursor.xAxis = dateAxis;\n chart.cursor.snapToSeries = series;\n function generateChartData$type() {\n \n var chartData$type = [];\n \n var data$type = \" .$value .\";\n var timeline = \" .$time_line .\";\n\n for (var i = 0; i < \" .$len .\"; i++) {\n\n chartData$type.push({\n time: new Date(timeline[i]),\n visits: data\".$type.\"[i]\n });\n }\n return chartData$type;\n }\n }); // end am4core.ready()\n </script>\n <div style=\\\"height: auto; width: 100%; margin: 50px 50px 50px 20px;\\\">\n <center><h1 style= \\\"color: $color;\\\">$sensor</h1></center>\n <div id=\\\"chartdiv$type\\\" style=\\\"height: 350px;\\\"></div>\n </div>\n \";\n }\n }\n }\n }else echo \"<script>alert(\\\"Please select specifically location! :(\\\");</script>\";\n }\n }\n ?>\n </div>\n </div>\n </body>\n</html>\n" }, { "alpha_fraction": 0.3706975281238556, "alphanum_fraction": 0.3782363831996918, "avg_line_length": 48.554718017578125, "blob_id": "d1d4f44ff45532e25100e2f700105326aa160634", "content_id": "4d7d61dd21a64e278911356971a71466e21d5105", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 13132, "license_type": "permissive", "max_line_length": 155, "num_lines": 265, "path": "/control.php", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html>\n <head>\n <title> Control </title>\n <link rel=\"Shortcut Icon\" href=\"image/WSN.ico\">\n <meta http-equiv=\"content-type\" content=\"tex/html\">\n <meta charset=\"UTF-8\">\n <meta rel=\"stylesheet\" href=\"font/Roboto.woff2\">\n <meta rel=\"stylesheet\" href=\"font/Lato.woff2\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <script src=\"https://canvasjs.com/assets/script/canvasjs.min.js\"> </script>\n <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\"></script>\n <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.0/css/all.css\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js\"></script>\n <link rel=\"stylesheet\" href=\"//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/themes/default/style.min.css\" />\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/jstree.min.js\"></script>\n <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.0/css/all.css\">\n </head>\n <body style=\"position:relative; margin: 0px;\">\n <!-Taskbar-->\n <?php\n require \"phpMQTT-master/phpMQTT.php\";\n include \"connect.php\";\n include \"taskbar.php\";\n include \"sidebar.php\";\n ?> \n <script>\n openTab(3);\n </script>\n \n <!-Page-content-->\n <div id=\"page-content\" style=\"float:left;color: #18699F;margin: 70px 0px 0px 200px;\">\n <!-Graph-page--> \n <div id=\"general-page\" class=\"page\" style=\"float:left ; width: 100%;\" >\n <div id=\"general-title\" class=\"page-title\"> \n <div> Control </div> \n <input id=\"testbutton\" type=\"checkbox\" checked>\n </div>\n <?php\n function find_parent($id_parent,$conn){\n $res_parent = $conn->query(\"SELECT * FROM location WHERE id = $id_parent \");\n if ($res_parent->num_rows > 0){\n while($row = $res_parent->fetch_assoc()){\n $save_id = $row[\"parentid\"];\n $save_area = $row[\"area\"];\n return $save_area .\" / \" .find_parent($save_id,$conn);\n }\n }\n }\n $obj = json_decode($_COOKIE[\"select\"],true);\n if(isset($_POST['make']) && sizeof($obj) != 0){\n for( $i = 0; $i < sizeof($obj) ; $i++){\n $id_area = $obj[$i];\n $area = NULL;\n $des_area = NULL;\n $res_id = $conn->query(\"SELECT * FROM location WHERE parentid = $id_area \");//Xem id nay co phai la node la khong.\n if ($res_id->num_rows == 0){\n $ind = 0;\n $res_area = $conn->query(\"SELECT * FROM location WHERE id = $id_area \");\n if ($res_area->num_rows > 0){\n while($row = $res_area->fetch_assoc()){\n $des_area = $row[\"des\"];\n $area = find_parent($id_area,$conn);\n }\n }\n echo '<div style=\"margin:10px 10px 10px 50px;border: 3px solid black; width:750px ;background-color: #FFFFFF ; float:left\">\n <div id=\"lighttext\" class=\"sub-title\"><span style=\"margin-left: 30px; margin-right: 20px; color:#0eed0e;\"> '.$area .' </span></div>';\n \n $res_device = $conn->query(\"SELECT * FROM device WHERE areaid = $id_area\");//Tat ca cac thiet bi co trong phong.\n if ($res_device->num_rows > 0){\n while($row = $res_device->fetch_assoc()){\n $device_id = $row[\"id\"];\n $device_name = $row[\"name\"];\n $device_code = $row[\"code\"];\n $device_status = $row[\"status\"];\n echo \"\n <label class='form-switch'>\n <br><input id='device\".$device_id.\"' type='checkbox' value='$device_id' $device_status> $device_name\n <i></i>\n </label>\n <script>\n $('#device\".$device_id.\"').click(function(){\n var stt = $(this).prop('checked');\n if(stt) stt = 1;\n else stt = 0;\n $.post('make_control.php',{ change : stt, id : $device_id })\n .done(function(data) {\n // alert('Data Loaded: ' + data);\n });\n\n }); \n </script>\n \";\n }\n echo '\n <center style=\"margin:10px\">\n <label\">\n <input type=\"submit\" id=\"allon'.$id_area.'\" name=\"all_on'.$id_area.'\" class=\"square_btn\" value=\"All On\"> \n <i></i>\n </label>\n <script>\n $(\"#allon'.$id_area.'\").click(function(){\n $.post(\"make_control.php\",{ all_on : '.$id_area .' })\n .done(function(data) {\n // alert(data);\n });\n });\n </script>\n <label\">\n <input type=\"submit\" id=\"alloff'.$id_area.'\" name=\"all_off'.$id_area.'\" class=\"square_btn\" value=\"All Off\"> \n <i></i>\n </label>\n <script>\n $(\"#alloff'.$id_area.'\").click(function(){\n $.post(\"make_control.php\",{ all_off : '.$id_area.' })\n .done(function(data) {\n // alert(data);\n });\n });\n </script>\n </center>\n <div id=\"checkboxlist\" style=\"\" >';\n echo ' <script>\n $(\"#allon'.$id_area.'\").click(function() {';\n $res_device = $conn->query(\"SELECT * FROM device WHERE areaid = $id_area\");//Tat ca cac thiet bi co trong phong.\n if ($res_device->num_rows > 0){\n while($row = $res_device->fetch_assoc()){\n $device_id = $row[\"id\"];\n echo \"$('#device\".$device_id.\"').prop(\\\"checked\\\", true);\";\n }\n }\n echo \"});\n </script>\";\n echo \" <script>\n $('#alloff\".$id_area.\"').click(function() {\";\n $res_device = $conn->query(\"SELECT * FROM device WHERE areaid = $id_area\");//Tat ca cac thiet bi co trong phong.\n if ($res_device->num_rows > 0){\n while($row = $res_device->fetch_assoc()){\n $device_id = $row[\"id\"];\n echo \"$('#device\".$device_id.\"').prop(\\\"checked\\\", false);\";\n }\n }\n echo \"});\n </script>\n </div>\";\n \n }else echo '<center style=\"color:red;\"><b>No device </b></center>';\n echo\"</div>\"; \n }\n }\n }\n else{\n $res_all = $conn->query(\"SELECT * FROM location\"); //truy van cac kieu du lieu da co.\n if ($res_all->num_rows > 0){\n while($row = $res_all->fetch_assoc()){\n $id_area = $row['id'];\n $area = NULL;\n $des_area = NULL;\n $res_id = $conn->query(\"SELECT * FROM location WHERE parentid = $id_area \");//Xem id nay co phai la node la khong.\n if ($res_id->num_rows == 0){\n $ind = 0;\n\n $res_area = $conn->query(\"SELECT * FROM location WHERE id = $id_area \");\n if ($res_area->num_rows > 0){\n while($row = $res_area->fetch_assoc()){\n $des_area = $row[\"des\"];\n $area = find_parent($id_area,$conn);\n }\n }\n\n echo'\n <div style=\"margin:10px 10px 10px 50px;border: 3px solid black; width:750px ;background-color: #FFFFFF ; float:left\">\n <div id=\"lighttext\" class=\"sub-title\"><span style=\"margin-left: 30px; margin-right: 20px; color:#0eed0e;\"> '.$area .' </span></div>';\n \n $res_device = $conn->query(\"SELECT * FROM device WHERE areaid = $id_area\");//Tat ca cac thiet bi co trong phong.\n if ($res_device->num_rows > 0){\n while($row = $res_device->fetch_assoc()){\n\n $device_id = $row[\"id\"];\n $device_name = $row[\"name\"];\n $device_code = $row[\"code\"];\n $device_status = $row[\"status\"];\n echo \"\n <label class='form-switch'>\n <br><input id='device\".$device_id.\"' type='checkbox' value='$device_id' $device_status> $device_name\n <i></i>\n </label>\n <script>\n $('#device\".$device_id.\"').click(function(){\n var stt = $(this).prop('checked');\n if(stt) stt = 1;\n else stt = 0;\n $.post('make_control.php',{ change : stt, id : $device_id })\n .done(function(data) {\n // alert('Data Loaded: ' + data);\n });\n\n }); \n </script>\n \";\n }\n echo '\n <center style=\"margin:10px\">\n <label\">\n <input type=\"submit\" id=\"allon'.$id_area.'\" name=\"all_on'.$id_area.'\" class=\"square_btn\" value=\"All On\"> \n <i></i>\n </label>\n <script>\n $(\"#allon'.$id_area.'\").click(function(){\n $.post(\"make_control.php\",{ all_on : '.$id_area .' })\n .done(function(data) {\n // alert(data);\n });\n });\n </script>\n <label\">\n <input type=\"submit\" id=\"alloff'.$id_area.'\" name=\"all_off'.$id_area.'\" class=\"square_btn\" value=\"All Off\"> \n <i></i>\n </label>\n <script>\n $(\"#alloff'.$id_area.'\").click(function(){\n $.post(\"make_control.php\",{ all_off : '.$id_area.' })\n .done(function(data) {\n // alert(data);\n });\n });\n </script>\n </center>\n <div id=\"checkboxlist\" style=\"\" >';\n echo ' <script>\n $(\"#allon'.$id_area.'\").click(function() {';\n $res_device = $conn->query(\"SELECT * FROM device WHERE areaid = $id_area\");//Tat ca cac thiet bi co trong phong.\n if ($res_device->num_rows > 0){\n while($row = $res_device->fetch_assoc()){\n $device_id = $row[\"id\"];\n echo \"$('#device\".$device_id.\"').prop(\\\"checked\\\", true);\";\n }\n }\n echo \"});\n </script>\";\n echo \" <script>\n $('#alloff\".$id_area.\"').click(function() {\";\n $res_device = $conn->query(\"SELECT * FROM device WHERE areaid = $id_area\");//Tat ca cac thiet bi co trong phong.\n if ($res_device->num_rows > 0){\n while($row = $res_device->fetch_assoc()){\n $device_id = $row[\"id\"];\n echo \"$('#device\".$device_id.\"').prop(\\\"checked\\\", false);\";\n }\n }\n echo \"});\n </script>\n </div>\";\n \n }else echo '<center style=\"color:red;\"><b>No device </b></center>';\n echo\"</div>\"; \n }\n }\n }\n }\n ?>\n </div>\n </div>\n </body>\n</html>\n" }, { "alpha_fraction": 0.546042799949646, "alphanum_fraction": 0.6047784686088562, "avg_line_length": 30.390625, "blob_id": "b6822cfdc7135c74610962daf3ba8012cb4b6e25", "content_id": "a6d1806e3cc809f084262c1a140114529010952e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2009, "license_type": "permissive", "max_line_length": 73, "num_lines": 64, "path": "/python/create.py", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "import MySQLdb\nfrom datetime import datetime\n \nmyconn = MySQLdb.connect(\"localhost\",\"root\",\"\",\"doan\")\n\ncur = myconn.cursor() \n\ns1 = \"DROP TABLE IF EXISTS location\"\ncur.execute(s1)\ns2 = \"DROP TABLE IF EXISTS router\"\ncur.execute(s2)\ns3 = \"DROP TABLE IF EXISTS sensor\"\ncur.execute(s3)\ns4 = \"DROP TABLE IF EXISTS sensordata\"\ncur.execute(s4)\ns5 = \"DROP TABLE IF EXISTS device\"\ncur.execute(s5)\ns6 = \"DROP TABLE IF EXISTS user\"\ncur.execute(s6)\nsql1 = \"\"\"create table location(id int(11) auto_increment primary key,\\\n\t\t\t\t\t\t\t\t\t\tarea char(255) not null,\\\n\t\t\t\t\t\t\t\t\t\tparentid int(255) null,\\\n\t\t\t\t\t\t\t\t\t\tmac char(255) not null,\\\n\t\t\t\t\t\t\t\t\t\tdes char(255) null,\\\n\t\t\t\t\t\t\t\t\t\text char(255) null)\"\"\"\ncur.execute(sql1)\nsql2 = \"\"\"create table router(id int(11) auto_increment primary key,\\\n\t\t\t\t\t\t\t\t\t\tareaid int(255) null,\\\n\t\t\t\t\t\t\t\t\t\tsensorid int(255) null,\\\n\t\t\t\t\t\t\t\t\t\tactive int(11) null)\"\"\"\ncur.execute(sql2)\nsql3 = \"\"\"create table sensor(id int(11) auto_increment primary key,\\\n\t\t\t\t\t\t\t\t\t\ttype char(255) null,\\\n\t\t\t\t\t\t\t\t\t\tcode char(255) not null,\\\n\t\t\t\t\t\t\t\t\t\tarange char(255) null,\\\n\t\t\t\t\t\t\t\t\t\tdes char(255) null,\\\n\t\t\t\t\t\t\t\t\t\ticon char(255) null,\\\n\t\t\t\t\t\t\t\t\t\text char(255) null)\"\"\"\ncur.execute(sql3)\nsql4 = \"\"\"create table sensordata(id int(11) auto_increment primary key,\\\n\t\t\t\t\t\t\t\t\t\tsensor int(255) null,\\\n\t\t\t\t\t\t\t\t\t\tvalue int(255) null,\\\n\t\t\t\t\t\t\t\t\t\ttime datetime null)\"\"\"\ncur.execute(sql4)\nsql5 = \"\"\"create table device(id int(11) auto_increment primary key,\\\n\t\t\t\t\t\t\t\t\t\tareaid int(11) not null,\\\n\t\t\t\t\t\t\t\t\t\tname char(255) null,\\\n\t\t\t\t\t\t\t\t\t\tcode char(255) null,\\\n\t\t\t\t\t\t\t\t\t\tstatus char(255) null,\\\n\t\t\t\t\t\t\t\t\t\tdes char(255) null,\\\n\t\t\t\t\t\t\t\t\t\text char(255) null)\"\"\"\ncur.execute(sql5)\nsql6 = \"\"\"create table user(id int(11) auto_increment primary key,\\\n\t\t\t\t\t\t\t\t\t\tname char(255) not null,\\\n\t\t\t\t\t\t\t\t\t\tgmail char(255) not null,\\\n\t\t\t\t\t\t\t\t\t\tpassword char(255) null,\\\n\t\t\t\t\t\t\t\t\t\taddress char(255) null,\\\n\t\t\t\t\t\t\t\t\t\tdes char(255) null,\\\n\t\t\t\t\t\t\t\t\t\text char(255) null,\\\n\t\t\t\t\t\t\t\t\t\ttime datetime null)\"\"\"\ncur.execute(sql6)\nprint('success')\n \nmyconn.close()\n" }, { "alpha_fraction": 0.6884584426879883, "alphanum_fraction": 0.6973365545272827, "avg_line_length": 21.962963104248047, "blob_id": "b0df0e5ce2351c8952e11091a7fcf029914d91e0", "content_id": "f0148aa6c0039129bf3fcfac06b05bb3de984676", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1239, "license_type": "permissive", "max_line_length": 72, "num_lines": 54, "path": "/python/pub_manual.py", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "import paho.mqtt.client as mqtt\nimport random\nimport json\nfrom datetime import datetime\nfrom time import sleep\n\nBroker = \"localhost\"\nPort = 1883\nWait = 45\nTopic = \"iot\"\n\ndef on_connect(client, userdata, flags, rc):\n\tif rc!=0:\n\t\tpass\n\t\tprint('Unable connect to Broker...')\n\telse:\n\t\tprint('Connected with Broker' + str(Broker))\n\ndef on_publish(client, userdata, mid):\n\tpass\n\ndef disconnect(client, userdata, rc):\n\tif rc != 0:\n\t\tpass\n\nmqttc = mqtt.Client()\nmqttc.username_pw_set(username = \"xukiijqw\", password = \"McQhmmD2eEJ2\")\nmqttc.on_connect = on_connect\nmqttc.disconnect = disconnect\nmqttc.on_publish = on_publish\nmqttc.connect(Broker, Port, Wait)\n\ndef pub2topic(topic, message):\n\tmqttc.publish(topic, message)\n\tprint('Published: ' + str(message) + '' +'on MQTT topic ' + str(topic))\n\tprint('')\n\ndef pub_data_fake(namesensor):\n\tprint('Nhap dia chi:')\n\tssarea = input()\n\tprint('Nhap ten du lieu:')\n\tssdata = input()\n\tprint('Nhap gia tri:')\n\tvalue = input()\n\tsensor_data = {}\n\tsensor_data['area'] = ssarea;\n\tsensor_data['type'] = ssdata;\n\tsensor_data['value'] = int(value);\n\tsensor_json_data = json.dumps(sensor_data)\n\tprint('Publishing data fake from %s:' %namesensor)\n\tpub2topic(Topic, sensor_json_data)\n\nwhile True:\n\tpub_data_fake('esp1')" }, { "alpha_fraction": 0.5965517163276672, "alphanum_fraction": 0.5965517163276672, "avg_line_length": 23.08333396911621, "blob_id": "d3fc6bbb8038c59f60b1972041cfe033bdfd97da", "content_id": "555487029d309bef3ab71eead84c7c762c97dca4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 298, "license_type": "permissive", "max_line_length": 64, "num_lines": 12, "path": "/connect.php", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "<?php\n\t$servername = \"localhost\";\n\t$username = \"root\";\n\t$password = \"\";\n\t$dbname = \"doan\";\n\t// tao connect\n\t$conn = new mysqli($servername, $username, $password, $dbname);\n\t// kiem tra connect\n\tif ($conn->connect_error) {\n\t die(\"Kết nối thất bại :( <br>\" . $conn->connect_error);\n\t}\n?>\n\n" }, { "alpha_fraction": 0.587639331817627, "alphanum_fraction": 0.6220871210098267, "avg_line_length": 34.25, "blob_id": "fab533ec052dbde31c98f01098953e512a48563e", "content_id": "bd6641e456c474d10903f76996eac9c8900db258", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 987, "license_type": "permissive", "max_line_length": 111, "num_lines": 28, "path": "/privacy.php", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html>\n <head>\n <title> Monitor </title>\n <meta charset=\"UTF-8\">\n <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\"></script>\n <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.0/css/all.css\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js\"></script>\n <link rel=\"stylesheet\" href=\"//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/themes/default/style.min.css\" />\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.8/jstree.min.js\"></script>\n \n </head>\n <body style=\"position:relative; margin: 0px;\">\n <?php\n include \"connect.php\";\n include \"taskbar.php\";\n include \"sidebar.php\";\n ?>\n <script>\n openTab(1);\n </script>\n <div id=\"page-content\" style=\"float:left;height:1000px;color: #18699F;margin: 70px 0px 0px 200px;\">\n <b> Just for test ! :)\n </b>\n </div>\n </body>\n</html>\n" }, { "alpha_fraction": 0.46756383776664734, "alphanum_fraction": 0.4875776469707489, "avg_line_length": 31.211111068725586, "blob_id": "1bf81093051277dbe1ef78d8b7f038348ae4553a", "content_id": "04a458ea99b81982f5d0ce74465cdcc539a26e82", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2898, "license_type": "permissive", "max_line_length": 166, "num_lines": 90, "path": "/sidebar.php", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "<script>\nfunction createCookie(name, value, days) {\n var expires;\n if (days) {\n var date = new Date();\n date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));\n expires = \"; expires=\" + date.toGMTString();\n }\n else {\n expires = \"\";\n }\n document.cookie = name+ \"=\" + value + expires + \"; path=/\";\n //console.log(document.cookie);\n}\n// createCookie(\"select\",'', \"10\");\n$(function () {\n $(\"#tree\").jstree({\n \"checkbox\": {\n \"keep_selected_style\": false\n },\n \"plugins\": [ \"types\", \"checkbox\"],\n \"types\": {\n \"default\": {\n \"icon\": \"fas fa-map-marker-alt\"\n }\n }\n });\n $(\"#tree\").bind(\"changed.jstree\",\n function (e, data) {\n var output = {};\n for(i=0 ;i<data.selected.length ;i++){\n output[i] = data.selected[i];\n }\n var kq = JSON.stringify(output);\n //console.log(output);\n console.log(kq);\n createCookie(\"select\", kq , \"/\");\n });\n});\n</script>\n\n<div id=\"sidebar\" style=\"position:fixed;width: 200px;height:100%; background-color: #1E282C; padding: 0px; margin: 70px 0px; color: #ECF0F5; float:left;z-index: 10;\">\n <div id=\"menu_text\" style=\"height: 60px; text-align: center; vertical-align: middle; line-height: 60px; border-bottom: 1px solid #ECF0F5\">\n <p style=\"font-size: 20px;margin: 0;px border-bottom: 1px solid #ECF0F5; border-top: 1px solid #ECF0F5\"><strong> Location </strong></p>\n </div>\n <div id=\"tree\" style=\"width: auto; background-color: #ECF0F5 ;color: black; padding: 0px; margin: 5px 0px 5px 5px\">\n <?php\n function trytry($id_parent,$conn){\n $res_id_t = $conn->query(\"SELECT * FROM location WHERE parentid = $id_parent \");\n if ($res_id_t->num_rows > 0){\n echo \"\n <ul>\";\n while($row = $res_id_t->fetch_assoc()){\n $save_id = $row[\"id\"];\n $save_area = $row[\"area\"];\n $icon = $row[\"ext\"];\n echo \"\n <li id=\\\"$save_id\\\" data-jstree = '{\\\"icon\\\": \\\"\" .$icon .\"\\\"}' >$save_area\";\n trytry($save_id,$conn);\n echo \"\n </li>\";\n }\n echo \"\n </ul>\";\n }\n }\n $res_id = $conn->query(\"SELECT * FROM location where parentid IS NULL \");\n if ($res_id->num_rows > 0){ \n echo \"\n <ul>\";\n while($row = $res_id->fetch_assoc()){\n $save_id = $row[\"id\"];\n $save_area = $row[\"area\"];\n $icon = $row[\"ext\"];\n echo \"\n <li id=\\\"$save_id\\\" data-jstree = '{\\\"icon\\\": \\\"\" .$icon .\"\\\"}' >$save_area\";\n trytry($save_id,$conn);\n echo\"\n </li>\";\n }\n echo \"\n </ul>\";\n }\n ?>\n </div>\n <form action=\"#\" method=\"post\">\n <input type=\"submit\" style = \" margin-left: 20px \" name=\"make\" value=\"Check\"></form>\n </form>\n \n</div>" }, { "alpha_fraction": 0.713936448097229, "alphanum_fraction": 0.7298288345336914, "avg_line_length": 21.72222137451172, "blob_id": "5f0059df41d85670a230582f784b85695df84414", "content_id": "b8206e54871fe36e7e5d79fdc47407038c574cad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 818, "license_type": "permissive", "max_line_length": 70, "num_lines": 36, "path": "/python/sub.py", "repo_name": "tuvm/php-iot", "src_encoding": "UTF-8", "text": "import paho.mqtt.client as mqtt\nfrom savedata import *\nimport MySQLdb\nimport random\nimport json\nfrom datetime import datetime\nfrom time import sleep\n\nBroker = \"soldier.cloudmqtt.com\"\nPort = 11600\nWait = 400\nTopic = \"datasensor\"\nTopic2 = \"datafake\"\n\ndef on_connect(client, userdata, flags, rc):\n\tif rc!=0:\n\t\tpass\n\t\tprint('Unable connect to Broker...')\n\telse:\n\t\tprint('Connected with Broker' + str(Broker))\n\tclient.subscribe(Topic,0)\n\tclient.subscribe(Topic2,0)\n\ndef on_message(client, userdata, msg):\n\t# print('Receiving data...')\n\t# print('Topic: ' + msg.topic)\n\tprint(msg.payload)\n\tSensor(msg.payload)\n\nclient = mqtt.Client()\nclient.username_pw_set(username = \"guapvdfg\", password = \"k5WzGtSNWMQY\")\nclient.on_connect = on_connect\nclient.on_message = on_message\nclient.connect(Broker, Port, Wait)\n\nclient.loop_forever()\n" } ]
16
FUZIK/secret_punto
https://github.com/FUZIK/secret_punto
b05f850cdad92cd50444d614fd2fb91be2a69073
4b48cc30346d539c552403d3dbf8471f0310f800
ba649c0ef0475de366ebc965a34549d98c1e8680
refs/heads/master
2023-02-26T08:52:32.152559
2020-05-24T19:57:19
2020-05-24T19:57:19
264,653,364
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6195651888847351, "alphanum_fraction": 0.6195651888847351, "avg_line_length": 22, "blob_id": "83725d9a2cce9ff5e4099d055aaaa916088ec88e", "content_id": "35e7d8a58cc64da546d2b8be35867f7e19d3d3e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 92, "license_type": "no_license", "max_line_length": 40, "num_lines": 4, "path": "/main.py", "repo_name": "FUZIK/secret_punto", "src_encoding": "UTF-8", "text": "import tg_manager_bot.bot as manager_bot\n\nif __name__ == '__main__':\n manager_bot.main()\n" }, { "alpha_fraction": 0.6639999747276306, "alphanum_fraction": 0.7519999742507935, "avg_line_length": 30.375, "blob_id": "5326812f15578d388531ebde134ba04ed23f3699", "content_id": "385cf520cfd96405d424cba4bcd9165a5c09d18e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 250, "license_type": "no_license", "max_line_length": 68, "num_lines": 8, "path": "/config.py", "repo_name": "FUZIK/secret_punto", "src_encoding": "UTF-8", "text": "DATABASE_HOST = \"ec2-54-247-169-129.eu-west-1.compute.amazonaws.com\"\nDATABASE_PORT = 5432\nDATABASE_NAME = \"dbm6aqb8gc2vd3\"\nDATABASE_USER = \"lwejloxflohbkt\"\nDATABASE_PASSWORD = \"963dca4e85ea295a09653fad768c530c2035732fd07800146d04b9ebc28186ca\"\n\n# PuntoManagerBot\nMANAGER_TG_BOT_TOKEN = \"1161956935:AAEelrfE2ksdxAjdanj-Uq1kIkjnFqAX1us\"" }, { "alpha_fraction": 0.6551046967506409, "alphanum_fraction": 0.6551046967506409, "avg_line_length": 25.34482765197754, "blob_id": "9b6b3c809836e27ea60037b88b9b517729712426", "content_id": "a683e2b715558f5e708dd541bee372ae61ce69d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1528, "license_type": "no_license", "max_line_length": 113, "num_lines": 58, "path": "/core/database_adapter.py", "repo_name": "FUZIK/secret_punto", "src_encoding": "UTF-8", "text": "import config\nfrom peewee import PostgresqlDatabase, Model, AutoField, IntegerField, TextField, ForeignKeyField, TimestampField\nfrom playhouse.postgres_ext import ArrayField, BlobField\n\n_connection = PostgresqlDatabase(config.DATABASE_NAME,\n host=config.DATABASE_HOST,\n port=config.DATABASE_PORT,\n user=config.DATABASE_USER,\n password=config.DATABASE_PASSWORD)\n\n\nclass _BaseModel(Model):\n id = AutoField()\n\n class Meta:\n database = _connection\n\n\nclass _NamedModel(_BaseModel):\n name = TextField()\n\n\nclass Category(_NamedModel):\n pass\n\n\nclass Brand(_NamedModel):\n pass\n\n\nclass UserRole(_NamedModel):\n pass\n\n\nclass MediaResource(_BaseModel):\n content = BlobField()\n telegram_upload_id = TextField()\n\n\nclass User(_BaseModel):\n user_role = ForeignKeyField(UserRole, column_name=\"user_role_id\")\n telegram_user_id = TextField()\n telegram_username = TextField()\n first_name = TextField()\n\n\nclass Item(_BaseModel):\n title = TextField()\n description = TextField()\n category = ForeignKeyField(Category, column_name=\"category_id\")\n brand = ForeignKeyField(Brand, column_name=\"brand_id\")\n price = IntegerField()\n in_stock = IntegerField()\n media_resources = ArrayField(IntegerField, column_name='media_resource_ids')\n # edited_by = IntegerField()\n # created_at = TimestampField()\n # updated_at = TimestampField()\n # flags_ids is unused\n" } ]
3
Tadaboody/good_smell
https://github.com/Tadaboody/good_smell
f9ab43dd4cb9f26ea6ddfc431503df944f55f67a
7330d3903f9c6f3b1cb79c6c782df4ca96ed70c2
cf980d7dc3c44003532b526f255f0e0e78e482cc
refs/heads/master
2021-11-23T20:40:23.523008
2021-11-18T10:18:51
2021-11-18T10:18:51
159,647,478
26
4
BSD-3-Clause
2018-11-29T10:19:45
2021-03-27T08:56:06
2021-03-27T09:06:34
Python
[ { "alpha_fraction": 0.778777003288269, "alphanum_fraction": 0.7877697944641113, "avg_line_length": 36.06666564941406, "blob_id": "3e432ebca9e8667e1e05a2b3d136e3af591f7534", "content_id": "a191132c36d5ee4292a4c402ba573c0fa1357994", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 556, "license_type": "permissive", "max_line_length": 68, "num_lines": 15, "path": "/good_smell/__init__.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "# flake8:noqa\ntry:\n from importlib import metadata\nexcept ImportError:\n # Running on pre-3.8 Python; use importlib-metadata package\n import importlib_metadata as metadata\n__version__ = metadata.version(\"good-smell\")\n\nfrom .smell_warning import SmellWarning\nfrom .lint_smell import LintSmell\nfrom .ast_smell import AstSmell, LoggingTransformer\nfrom .smells import implemented_smells\nfrom .main import fix_smell, print_fixed_smell, main, smell_warnings\nfrom . import smells # Allow importing good_smell.smells\nfrom .flake8_ext import LintingFlake8\n" }, { "alpha_fraction": 0.6017868518829346, "alphanum_fraction": 0.6037013530731201, "avg_line_length": 33.065216064453125, "blob_id": "eececff66858c7cdd465af1d0bb4dd92cea1eb8f", "content_id": "b8dce54ce7ef374c818aba467d4a56fdd719c574", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3134, "license_type": "permissive", "max_line_length": 101, "num_lines": 92, "path": "/good_smell/smells/range_len_fix.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "import ast\n\nfrom good_smell import AstSmell, LoggingTransformer\nfrom typing import Union, Container\n\n\nclass RangeLenSmell(AstSmell):\n @property\n def transformer_class(self):\n return EnumerateFixer\n\n @property\n def symbol(self):\n return \"range-len\"\n\n @property\n def warning_message(self) -> str:\n return \"Instead of using a c-style for loop, try using enumerate!\"\n\n\nclass AssignDeleter(ast.NodeTransformer):\n def __init__(self, seq: ast.Name, target: ast.Name):\n self.id = target\n self.seq = seq\n self.elem_target = None or ast.Name(id=\"elm\", ctx=ast.Store())\n self.uses_seq = False\n\n def visit_Assign(self, node: ast.Assign):\n \"\"\"Deletes a node if it assigning using the for target\"\"\"\n if self.accesses_seq(node.value):\n self.elem_target = node.targets[0]\n return None\n return self.generic_visit(node)\n\n @staticmethod\n def __get_slice_id(node: ast.Subscript) -> Container[str]:\n \"\"\"Get slice identifier.\n\n Needed because in python3.9 ast.Subscript.slice became a ast.Name, instead of a ast.Index.\"\"\"\n slice = node.slice\n if isinstance(slice, ast.Name):\n return [slice.id]\n if isinstance(slice, ast.Index):\n return [slice.value.id]\n if isinstance(slice, ast.Slice):\n return [slice.upper, slice.lower]\n\n def accesses_seq(self, node) -> bool:\n \"\"\"Checks if the node acceses the sequence[target]\"\"\"\n if (\n isinstance(node, ast.Subscript)\n and self.id.id in self.__get_slice_id(node)\n and node.value.id == self.seq.id\n ):\n self.uses_seq = True\n return True\n\n def visit_Subscript(self, node: ast.Subscript):\n if self.accesses_seq(node):\n return self.elem_target\n return self.generic_visit(node)\n\n\nclass EnumerateFixer(LoggingTransformer):\n def visit_For(self, node: ast.For) -> Union[bool, ast.For]:\n enumerate_node = ast.Name(id=\"enumerate\", ctx=ast.Load())\n node_iterable = node.iter.args[0].args[0]\n original_target = node.target\n deleter = AssignDeleter(target=original_target, seq=node_iterable)\n new_body = deleter.visit(node).body or [ast.Pass()]\n elm_target = (\n deleter.elem_target\n if deleter.uses_seq\n else ast.Name(id=\"_\", ctx=ast.Store())\n )\n # for (original_target,elm_target) in enumerate(node_iterable):\n new_node = ast.For(\n target=ast.Tuple(elts=[original_target, elm_target], ctx=ast.Store()),\n iter=ast.Call(func=enumerate_node, args=[node_iterable], keywords=[]),\n body=new_body,\n orelse=node.orelse,\n )\n new_node = ast.fix_missing_locations(ast.copy_location(new_node, node))\n new_node = self.generic_visit(new_node)\n return new_node\n\n @staticmethod\n def is_smelly(node: ast.For):\n try:\n return node.iter.func.id == \"range\" and node.iter.args[0].func.id == \"len\"\n except AttributeError:\n return False\n" }, { "alpha_fraction": 0.5789473652839661, "alphanum_fraction": 0.5835240483283997, "avg_line_length": 22, "blob_id": "7ff05538c4cc6c72101a7b3ef0d583dc9516e5af", "content_id": "f6250ba68a7e2ea96281dade329179cbd2f5334f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 437, "license_type": "permissive", "max_line_length": 83, "num_lines": 19, "path": "/docs/generate_smell_doc.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "from tests.test_collection import collect_tests, test_case_files\n\n\ndef generate_smell_docs():\n for example_test in [list(collect_tests(file))[0] for file in test_case_files]:\n desc, symbols, before, after = example_test\n symbol = list(symbols)[0]\n print(\n f\"\"\"### {desc} ({symbol})\n```py\n{before}```\nWill be fixed to\n```py\n{after}```\"\"\"\n )\n\n\nif __name__ == \"__main__\":\n generate_smell_docs()\n" }, { "alpha_fraction": 0.623644232749939, "alphanum_fraction": 0.623644232749939, "avg_line_length": 28.74193572998047, "blob_id": "cadb08d51eab5aacd30f51553f783cb3fb39fbed", "content_id": "dae3b94d65cf5dfbe4850b1759de3629f07026ec", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1844, "license_type": "permissive", "max_line_length": 85, "num_lines": 62, "path": "/good_smell/ast_smell.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "import abc\nimport ast\nfrom typing import List, Optional, Type, TypeVar\n\nimport astor\nfrom good_smell import LintSmell, SmellWarning\n\n\nclass LoggingTransformer(ast.NodeTransformer, abc.ABC):\n \"\"\"A subclass of transformer that logs the nodes it transforms\"\"\"\n\n def __init__(self, transform):\n self.transformed_nodes = list()\n self.transofrm = transform\n\n @abc.abstractmethod\n def is_smelly(self, node: ast.AST) -> bool:\n \"\"\"Checks if the given `node` should be transformed\"\"\"\n\n def visit(self, node: ast.AST):\n if not self.is_smelly(node):\n return self.generic_visit(node)\n self.transformed_nodes.append(node)\n if self.transofrm:\n return super().visit(node)\n return self.generic_visit(node)\n\n\nT = TypeVar(\"T\")\n\n\ndef unwrap(x: Optional[T]) -> T:\n if x is None:\n raise ValueError(\"Unrwapped None\")\n return x\n\n\nclass AstSmell(LintSmell):\n def check_for_smell(self) -> List[SmellWarning]:\n \"\"\"Return a list of all occuring smells of this smell class\"\"\"\n transformer = self.transformer_class(self.transform)\n transformer.visit(unwrap(self.tree))\n node: ast.stmt\n return [\n SmellWarning(\n msg=self.warning_message,\n row=node.lineno,\n col=node.col_offset,\n path=unwrap(self.path),\n symbol=self.symbol,\n )\n for node in transformer.transformed_nodes\n ]\n\n def fix_smell(self) -> str:\n \"\"\"Return a fixed version of the code without the code smell\"\"\"\n return astor.to_source(self.transformer_class(True).visit(unwrap(self.tree)))\n\n @property\n @abc.abstractmethod\n def transformer_class(self) -> Type[LoggingTransformer]:\n \"\"\"The class for the transformer used to create\"\"\"\n" }, { "alpha_fraction": 0.7594654560089111, "alphanum_fraction": 0.7611358761787415, "avg_line_length": 39.818180084228516, "blob_id": "6ac29f52ad3c07552ca74d11eb1ff6fffebc36c1", "content_id": "5ad90ced37d09397f144885bb6fd5772fdcb2ed7", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1796, "license_type": "permissive", "max_line_length": 160, "num_lines": 44, "path": "/CONTRIBUTING.md", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "# Contributing\n:tada:Thank you so much for taking the time to contribute:tada:\n## Wait!\nBefore trying to help please tell us what's wrong.\nPlease check if there is an [open issue](https://github.com/Tadaboody/good_smell/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc) with your problem.\nIf there isn't one, [create one](https://github.com/Tadaboody/good_smell/issues/new/choose)\n\nIf you want to contribute code you will need to:\n\n## Create an enviroment\nThis project uses [Poetry](https://python-poetry.org/docs) for package managment\n\nClone the repository and run inside it:\n```sh\ncurl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python # Install poetry on your machine\npoetry install # Create a new enviroment and install the development requirements\npoetry shell # Activate \nrun pre-commit install # Install pre-commit hooks\n```\n## Write the solution\nNew smells are implented in a new file in `good_smell/smells`, by creating a class that inherits `good_smell/lint_smell.py`.\nAfter implementing the methods add the class to the list `implemented_smells` in `good_smell/smells/__init__.py`\n\nIf you're new to parsing and transforming ASTs, [green tree snakes](https://greentreesnakes.readthedocs.io/en/latest/index.html) is a great guide to the basics.\n## Write the tests\nInside the relevant file in the `tests/examples` dir (Or a new), the tests are formatted like this\n```py\n#:<Test description>\n#<Comma-seperated list of warning symbols emmited> or \"None\"\n<Python code emitting the smells>\n# ==>\n<Python code after fixing the smell>\n# END\n```\nSee [the example file](tests/examples/example.py) for an example\n## Run the tests\nActivate your virtual enviroment and run\n```sh\npytest\n```\nTo run a specific test run \n```sh\npytest -k <Test description>\n```\n" }, { "alpha_fraction": 0.6571428775787354, "alphanum_fraction": 0.6590476036071777, "avg_line_length": 24, "blob_id": "a21e498c001875e585cac52f9b194f6dfc9a376c", "content_id": "5ec5cb04e1f585642039c4cf86f450118da728c9", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 525, "license_type": "permissive", "max_line_length": 61, "num_lines": 21, "path": "/good_smell/smell_warning.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "from typing import NamedTuple\n\nFLAKE8_FORMAT = \"{path}:{row}:{col} {symbol} {msg}\"\nPYLINT_FORMAT = \"{path}:{line}:{column}: {msg} ({symbol})\"\n\n\ndef to_dict(namedtuple: NamedTuple) -> dict:\n return dict(zip(namedtuple._fields, list(namedtuple)))\n\n\nclass SmellWarning(NamedTuple):\n \"\"\"Class to represent a warning message about a smell\"\"\"\n\n row: int\n col: int\n path: str\n msg: str\n symbol: str\n\n def warning_string(self, formatter: str = PYLINT_FORMAT):\n return formatter.format(**to_dict(self))\n" }, { "alpha_fraction": 0.830258309841156, "alphanum_fraction": 0.830258309841156, "avg_line_length": 37.71428680419922, "blob_id": "c5fe493f5e033686de230033411055576c63901f", "content_id": "801b0a18718b7535df0e3600316d3b549f26db82", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 271, "license_type": "permissive", "max_line_length": 87, "num_lines": 7, "path": "/good_smell/smells/__init__.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "from .filter import FilterIterator\nfrom .join_literal import JoinLiteral\nfrom .nested_for import NestedFor\nfrom .range_len_fix import RangeLenSmell\nfrom .yield_from import YieldFrom\n\nimplemented_smells = (RangeLenSmell, NestedFor, FilterIterator, YieldFrom, JoinLiteral)\n" }, { "alpha_fraction": 0.5515151619911194, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 9.375, "blob_id": "8da19f6f32a00d81e37e46b8d4d33c9427079b9a", "content_id": "480cf96520f3d4260fae02e02a8691b39f2fcfee", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 165, "license_type": "permissive", "max_line_length": 28, "num_lines": 16, "path": "/tests/examples/example.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "#: example\n# example-symbol,another-one\nbefore = 0\nbefore = 1\n# ==>\nafter = 0\nafter = 1\n# END\n#: example\n# None\nbefore = 0\nbefore = 1\n# ==>\nafter = 0\nafter = 1\n# END" }, { "alpha_fraction": 0.6228747963905334, "alphanum_fraction": 0.6280267834663391, "avg_line_length": 20.10869598388672, "blob_id": "0ad857114e2512bce82ea6de34f8c41512ec326a", "content_id": "6dd54d6a81461e2cb1729e49be320da877ba286d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1941, "license_type": "permissive", "max_line_length": 62, "num_lines": 92, "path": "/tests/examples/range_len.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "#: Range len instead of enumerate\n# range-len\nfor i in range(len(sequence)):\n a = sequence[i]\n print(a)\n# ==>\nfor i, a in enumerate(sequence):\n print(a)\n# END\n#: Replace an empty body with pass\n# range-len\nfor i in range(len(sequence)):\n a = sequence[i]\n# ==>\nfor i, a in enumerate(sequence):\n pass\n# END\n#: replaces access\n# range-len\nfor i in range(len(sequence)):\n other_thing(sequence[i], i)\n# ==>\nfor i, elm in enumerate(sequence):\n other_thing(elm, i)\n# END\n#: Multiple replaces\n# range-len\nfor i in range(len(sequence)):\n x = sequence[i]\n do_thing(x, i)\n other_thing(sequence[i], i)\n# ==>\nfor i, x in enumerate(sequence):\n do_thing(x, i)\n other_thing(x, i)\n\n# END\n#: Nested for\n# range-len\nfor i in range(len(sequence)):\n x = sequence[i]\n for j in range(len(sequence)):\n do_thing(x, j)\n other_thing(sequence[i], i)\n# ==>\nfor i, x in enumerate(sequence):\n for j, _ in enumerate(sequence):\n do_thing(x, j)\n other_thing(x, i)\n# END\n#: Replace unused var with _\n# range-len\nfor i in range(len(sequence)):\n do_thing(i)\n# ==>\nfor i, _ in enumerate(sequence):\n do_thing(i)\n# END\n#: Don't remove an assign to something else\n# range-len\nfor i in range(len(sequence)):\n a = 0\n print(sequence[j])\n# ==>\nfor i, _ in enumerate(sequence):\n a = 0\n print(sequence[j])\n# END\n#: Behave correctly when used in the upper part of a slice\n# range-len\nfor i in range(len(sequence)):\n print(sequence[1:i])\n# ==>\nfor i, _ in enumerate(sequence):\n print(sequence[1:i])\n# END\n#: Don't replace access when used in the upper part of a slice\n# range-len\nfor i in range(len(sequence)):\n print(sequence[i:1])\n# ==>\nfor i, _ in enumerate(sequence):\n print(sequence[i:1])\n# END\n#: Don't replace access used in the upper part of a slice\n# range-len\nfor i in range(len(sequence)):\n print(sequence[2:1])\n# ==>\nfor i, _ in enumerate(sequence):\n print(sequence[2:1])\n# END" }, { "alpha_fraction": 0.6137640476226807, "alphanum_fraction": 0.6151685118675232, "avg_line_length": 25.370370864868164, "blob_id": "03a22325637b358929b379b8a2942522160bbca2", "content_id": "03877125ed8dc4a89f87e1ce63125eacb023a8c4", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1424, "license_type": "permissive", "max_line_length": 79, "num_lines": 54, "path": "/good_smell/main.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "from pathlib import Path\nfrom typing import Iterable, Type\n\nfrom fire import Fire\n\nfrom good_smell import LintSmell, SmellWarning, implemented_smells\n\n\ndef print_smell_warnings(path: str):\n \"\"\"Prints any warning messages about smells\"\"\"\n print(\n \"\\n\".join(\n warning.warning_string()\n for warning in smell_warnings(Path(path).read_text(), path)\n )\n )\n\n\ndef smell_warnings(source: str, path: str = \"\") -> Iterable[SmellWarning]:\n for smell in implemented_smells:\n yield from smell.from_source(\n source_code=source, path=str(path), transform=False\n ).check_for_smell()\n\n\ndef print_fixed_smell(path: str, starting_line: int = 0, end_line: int = None):\n \"\"\"Prints a fixed version of `source`\"\"\"\n pathlib_path = Path(path)\n source = pathlib_path.read_text()\n print(fix_smell(source, starting_line, end_line))\n\n\ndef fix_smell(\n source: str, starting_line: int = 0, end_line: int = None, path: str = None\n) -> str:\n \"\"\"Returns a fixed version of `source`\"\"\"\n smell: Type[LintSmell]\n for smell in implemented_smells:\n source = smell.from_source(\n source_code=source,\n start_line=starting_line,\n end_line=end_line,\n path=path,\n transform=True,\n ).fix_smell()\n return source\n\n\ndef main():\n Fire({\"fix\": print_fixed_smell})\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6458733081817627, "alphanum_fraction": 0.6487523913383484, "avg_line_length": 27.16216278076172, "blob_id": "07b67b3c46ff3d72febf146638ec72ac9813aeb3", "content_id": "3fcb772a88503ff54f762cb43aec1a02ead5c02a", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1042, "license_type": "permissive", "max_line_length": 80, "num_lines": 37, "path": "/good_smell/smells/yield_from.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "from good_smell import AstSmell, LoggingTransformer\nimport ast\n\n\nclass YieldFrom(AstSmell):\n \"\"\"Checks for yields inside for loops\"\"\"\n\n @property\n def transformer_class(self):\n return YieldFromTransformer\n\n @property\n def warning_message(self):\n return \"Consider using yield from instead of yield inside of a for loop\"\n\n @property\n def symbol(self):\n return \"yield-from\"\n\n\nclass YieldFromTransformer(LoggingTransformer):\n \"\"\"NodeTransformer that goes visits all the yields in fors and replaces them\n with yield from\"\"\"\n\n def visit_For(self, node: ast.For):\n yield_from = ast.Expr(value=ast.YieldFrom(node.iter))\n return ast.fix_missing_locations(yield_from)\n\n @staticmethod\n def is_smelly(node: ast.AST):\n \"\"\"Check if the node is a yield inside a for\"\"\"\n return (\n isinstance(node, ast.For)\n and len(node.body) == 1\n and isinstance(node.body[0], ast.Expr)\n and isinstance(node.body[0].value, ast.Yield)\n )\n" }, { "alpha_fraction": 0.7134416699409485, "alphanum_fraction": 0.7223042845726013, "avg_line_length": 32.024391174316406, "blob_id": "567da2281a1955a72bc7d2e4b60c4a97fe56e5a4", "content_id": "3ba48f2ad7a92fd8f76faba754aa4b221305b24d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1354, "license_type": "permissive", "max_line_length": 179, "num_lines": 41, "path": "/README.md", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "# Good Smell - it makes your code smell good! \nA linting/refactoring library for python best practices and lesser-known tricks \n---\n![Build](https://github.com/tadaboody/good_smell/workflows/Python%20package/badge.svg)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black)\n[![PyPi version](https://pypip.in/v/good_smell/badge.png)](https://pypi.org/project/good-smell/)\n\n---\n\nThis Tool tries to find bits of code that are possible to make more pythonic, more beautiful by using the language features and standard library functions you might not know about\n\nFor example\nDirectly nested for loops (nested-for)\n```py\nfor i in seq_a:\n for j in seq_b:\n print(i, j)\n```\nwill be flattened to a nested comprehension\n```py\nfor i, j in ((i,j) for i in seq_a for j in seq_b):\n print(i, j)\n```\nFor a full list - check the list of [implemented smells](docs/smell_list.md)\n## Installing:\n```sh\npip install good_smell \n```\n## Usage\n\nTo issue warnings, good_smell installs itself as a [flake8](http://flake8.pycqa.org/en/latest/) plugin with error codes starting with SML.\n\nTo automatically fix the code use ``good_smell fix``:\n\n```sh\ngood_smell fix PATH >PATH\ngood_smell fix PATH [--starting-line STARTING_LINE] [--end-line END_LINE]\n```\n\n## Developing\nSee [contributing guide](CONTRIBUTING.md)\n" }, { "alpha_fraction": 0.6723891496658325, "alphanum_fraction": 0.6866952776908875, "avg_line_length": 20.84375, "blob_id": "55161bc5c29c7b97bfceca4b52a1e221e73fd5c9", "content_id": "253a73bc781bd8065b4309b8ae394deb985c32d5", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": true, "language": "Markdown", "length_bytes": 699, "license_type": "permissive", "max_line_length": 63, "num_lines": 32, "path": "/.github/ISSUE_TEMPLATE/bug_report.md", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: bug, new\nassignees: ''\n\n---\n\n#### Describe the bug\nA clear and concise description of what the bug is.\n\n#### To Reproduce\nSteps to reproduce the behavior:\n1. With file `...`\n2. Run `...`\n3. ???\n4. Get error\n#### Expected behavior\nA clear and concise description of what you expected to happen.\n\n#### Screenshots\nIf applicable, add screenshots to help explain your problem.\n\n#### Desktop (please complete the following information):**\n - OS: [e.g. Linux]\n - Python version: [e.g. 3.6.5]\n - Version [e.g. good_smell=0.3.1]\n - Output of `pip freeze`\n\n#### Additional context\nAdd any other context about the problem here.\n" }, { "alpha_fraction": 0.5504240989685059, "alphanum_fraction": 0.5692742466926575, "avg_line_length": 15.841269493103027, "blob_id": "e03650942cfa9a75c757a104bd9f7c2f09ec2ee3", "content_id": "3334b1715b32b6ad2f7efe5455cadbde5600ba54", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1061, "license_type": "permissive", "max_line_length": 71, "num_lines": 63, "path": "/docs/smell_list.md", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "### Warn when using join on a list of known literals. (join-literal)\n```py\na = \"foo\"\nb = \"bar\"\n\",\".join([a, b])\n```\nWill be fixed to\n```py\na = \"foo\"\nb = \"bar\"\n\"{},{}\".format(a, b)\n```\n### Use \"yield from\" instead of yield inside of a for loop (yield-from)\n```py\nseq = range(10)\nfor x in seq:\n yield x\n```\nWill be fixed to\n```py\nseq = range(10)\nyield from seq\n```\n### Range len instead of enumerate (range-len)\n```py\nfor i in range(len(sequence)):\n a = sequence[i]\n print(a)\n```\nWill be fixed to\n```py\nfor i, a in enumerate(sequence):\n print(a)\n```\n### Move if to iterator (filter-iterator)\n```py\nfor i in range(10):\n if i == 2:\n print(1)\n print(2)\n```\nWill be fixed to\n```py\nfor i in (x for x in range(10) if x == 2):\n print(1)\n print(2)\n```\n### Flatten for-loops using nested comprehensions (nested-for)\n```py\nseq_a = [0]\nseq_b = range(10)\nfor i in seq_a:\n for j in seq_b:\n print(i, j)\n```\nWill be fixed to\n```py\nseq_a = [0]\nseq_b = range(10)\nfor i, j in ((i,j) for i in seq_a for j in seq_b):\n print(i, j)\n\n```\n" }, { "alpha_fraction": 0.5358919501304626, "alphanum_fraction": 0.561478316783905, "avg_line_length": 20.31818199157715, "blob_id": "9d2faf8cceeec7ea73a13dba8510a69a1676297a", "content_id": "0886442a5b18cd4012e7dba893b1c6a196da9e60", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1407, "license_type": "permissive", "max_line_length": 79, "num_lines": 66, "path": "/tests/examples/nested_for.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "#: Flatten for-loops using nested comprehensions\n# nested-for\nfor i in seq_a:\n for j in seq_b:\n print(i, j)\n# ==>\nfor i, j in ((i, j) for i in seq_a for j in seq_b):\n print(i, j)\n\n# END\n#: Don't work if there's code between the loops (no way to know if it's unsafe)\n# None\nfor i in seq_a:\n print(i)\n for j in seq_b:\n print(i, j)\n# ==>\nfor i in seq_a:\n print(i)\n for j in seq_b:\n print(i, j)\n# END\n#: Don't work if there's code after the nested for\n# None\nfor i in seq_a:\n for j in seq_b:\n print(i, j)\n print(i)\n# ==>\nfor i in seq_a:\n for j in seq_b:\n print(i, j)\n print(i)\n# END\n#: Don't flatten a nested for with dependencies (#26)\n# None\nfor num in range(1, 5):\n for digits in range(1, 10 ** num):\n pass\n# ==>\nfor num in range(1, 5):\n for digits in range(1, 10 ** num):\n pass\n# END\n#: Check no errors with unpacking (#61)\n# None\nfor i, num in enumerate(range(1, 5)):\n for digits in range(1, 10 ** num):\n pass\n# ==>\nfor i, num in enumerate(range(1, 5)):\n for digits in range(1, 10 ** num):\n pass\n# END\n#: Check no errors with unpacking (#61), but also flatten\n# nested-for\nfor i, j in enumerate(range(1, 5)):\n for digits in range(1, 10 ** num):\n pass\n# ==>\nfor (i, j), digits in (\n ((i, j), digits)\n for i, j in enumerate(range(1, 5))\n for digits in range(1, 10 ** num)\n):\n pass\n" }, { "alpha_fraction": 0.6266666650772095, "alphanum_fraction": 0.653333306312561, "avg_line_length": 17.75, "blob_id": "30c0acbd240d5715f05f86ce07c513342c70db58", "content_id": "d287eb6d0e8594619faa4bc4264163146898c56a", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 150, "license_type": "permissive", "max_line_length": 57, "num_lines": 8, "path": "/tests/examples/yield_from.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "#: Use \"yield from\" instead of yield inside of a for loop\n# yield-from\nseq = range(10)\nfor x in seq:\n yield x\n# ==>\nseq = range(10)\nyield from seq\n" }, { "alpha_fraction": 0.6369723677635193, "alphanum_fraction": 0.6384279727935791, "avg_line_length": 31.10280418395996, "blob_id": "9d14b38b6a974143296c4f79f963292d67ea03ae", "content_id": "b7ddcec339664a9ecaae53bf8bd6f616d691e848", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3435, "license_type": "permissive", "max_line_length": 87, "num_lines": 107, "path": "/tests/test_collection.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "import ast\nimport itertools\nfrom os import PathLike\nfrom pathlib import Path\nfrom typing import Iterator, NamedTuple, Set\n\nimport astor\nimport black\nimport pytest\n\nfrom good_smell import fix_smell, smell_warnings\n\nFILE_DIR = Path(__file__).parent\nEXAMPLES_DIR = FILE_DIR / \"examples\"\n\n\ndef normalize_formatting(code: str) -> str:\n \"\"\"Returns a string of the code with normalized formatting for easier compares\"\"\"\n code = astor.to_source(ast.parse(code))\n try:\n return black.format_file_contents(code, fast=True, mode=black.Mode())\n except black.NothingChanged:\n return code\n\n\nclass CollectedTest(NamedTuple):\n desc: str\n error_symbols: Set[str]\n before: int\n after: str\n\n\ndef is_title(line: str) -> bool:\n return line.startswith(TITLE_PREFIX)\n\n\nTITLE_PREFIX = \"#:\"\nBEFORE_AFTER_SPLITTER = \"==>\"\nEND_SYMBOL = \"END\"\nSPECIAL_SYMBOLS = (TITLE_PREFIX, BEFORE_AFTER_SPLITTER, END_SYMBOL)\n\n\ndef collect_tests(path: PathLike) -> Iterator[CollectedTest]:\n \"\"\"Collects all test cases listed in `path`\"\"\"\n with open(path) as fp:\n lines = fp.readlines()\n lines_iter = iter(lines) # Create iterator for continued iteration\n for line_num, line in enumerate(line for line in lines_iter if is_title(line)):\n desc = line.strip(\"#:\").strip()\n symbols_line = next(lines_iter).strip(\"#\").strip()\n symbols = {symbol for symbol in symbols_line.split(\",\") if symbol != \"None\"}\n before = \"\".join(\n itertools.takewhile(lambda l: BEFORE_AFTER_SPLITTER not in l, lines_iter)\n )\n after = \"\".join(itertools.takewhile(lambda l: END_SYMBOL not in l, lines_iter))\n\n collected_test = CollectedTest(\n desc=desc, error_symbols=symbols, before=before, after=after\n )\n if any(\n symbol in field\n for field, symbol in itertools.product(collected_test, SPECIAL_SYMBOLS)\n ):\n raise Exception(\n f\"\"\"Wrongly formatted example in {path}:{line_num}\n {collected_test}\"\"\"\n )\n yield collected_test\n\n\ndef test_collect_tests():\n example_path = EXAMPLES_DIR / \"example.py\"\n collected_tests = list(collect_tests(example_path))\n assert len(collected_tests) == 2\n case_with_symbol, case_with_no_symbol = collected_tests\n assert case_with_symbol.desc == \"example\"\n assert case_with_symbol.error_symbols == {\"example-symbol\", \"another-one\"}\n assert case_with_symbol.before == \"\"\"before = 0\\nbefore = 1\\n\"\"\"\n assert case_with_symbol.after == \"\"\"after = 0\\nafter = 1\\n\"\"\"\n\n assert case_with_no_symbol.error_symbols == set()\n\n\ntest_case_files = [f for f in EXAMPLES_DIR.iterdir() if \"example\" not in f.name]\n\n\ndef params_from_file():\n for file in test_case_files:\n yield from (\n pytest.param(\n case.before,\n case.after,\n case.error_symbols,\n id=f\"{file.with_suffix('').name}:{case.desc}\",\n )\n for case in collect_tests(file)\n )\n\n\[email protected]([\"before\", \"_\", \"symbols\"], params_from_file())\ndef test_smell_warning(before, _, symbols):\n assert set(symbols) == {smell.symbol for smell in smell_warnings(before)}\n\n\[email protected]([\"before\", \"after\", \"_\"], list(params_from_file()))\ndef test_smell_fixing(before, after, _):\n assert normalize_formatting(fix_smell(before)) == normalize_formatting(after)\n" }, { "alpha_fraction": 0.6178082227706909, "alphanum_fraction": 0.6184931397438049, "avg_line_length": 27.627450942993164, "blob_id": "c5a178c8cc972aabfe6b1d9e0d30864948a0c364", "content_id": "65b3adc9ce1b0710de1feb926e388f8bbbe97586", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1460, "license_type": "permissive", "max_line_length": 84, "num_lines": 51, "path": "/good_smell/lint_smell.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "import abc\nimport ast\nimport os\nfrom typing import List, Optional\nfrom good_smell import SmellWarning\n\n\nclass LintSmell(abc.ABC):\n \"\"\"Abstract Base class to represent the sniffing instructions for the linter\"\"\"\n\n def __init__(\n self,\n transform: bool,\n path: Optional[str] = None,\n tree: Optional[ast.AST] = None,\n ):\n self.tree = tree\n self.path = path\n self.transform = transform\n\n @classmethod\n def from_source(\n cls,\n source_code: str,\n transform: bool = True,\n start_line: Optional[int] = 0,\n end_line: Optional[int] = None,\n path: Optional[str] = None,\n ) -> \"LintSmell\":\n start_line = start_line\n end_line = end_line or len(source_code.splitlines())\n source_code = os.linesep.join(source_code.splitlines()[start_line:end_line])\n return cls(transform=transform, path=path, tree=ast.parse(source_code))\n\n @abc.abstractmethod\n def check_for_smell(self) -> List[SmellWarning]:\n \"\"\"Return a list of all occuring smells of this smell class\"\"\"\n\n @abc.abstractmethod\n def fix_smell(self) -> str:\n \"\"\"Return a fixed version of the code without the code smell\"\"\"\n\n @property\n @abc.abstractmethod\n def symbol(self) -> str:\n \"\"\"The symbolic name for the smell\"\"\"\n\n @property\n @abc.abstractmethod\n def warning_message(self) -> str:\n \"\"\"The symbolic name for the smell\"\"\"\n" }, { "alpha_fraction": 0.635159969329834, "alphanum_fraction": 0.6369988918304443, "avg_line_length": 31.369047164916992, "blob_id": "0de640014398855d8def3495ce633e024bc24965", "content_id": "fe48fddd4b3fefcdfb46639d5815d98b5b4e0b4f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2719, "license_type": "permissive", "max_line_length": 88, "num_lines": 84, "path": "/good_smell/smells/nested_for.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "import ast\nimport typing\n\nfrom good_smell import AstSmell, LoggingTransformer\n\n\nclass NameInNode(LoggingTransformer):\n def __init__(self, name: ast.Name):\n self.name = name\n super().__init__(transform=False)\n\n def is_smelly(self, node: ast.AST) -> bool:\n return isinstance(node, ast.Name) and node.id == self.name.id\n\n\ndef name_in_node(node: ast.AST, name: ast.Name) -> bool:\n \"\"\"Checks if the node `name` is in `node`\"\"\"\n checker = NameInNode(name)\n checker.visit(node)\n return bool(checker.transformed_nodes)\n\n\nclass NestedFor(AstSmell):\n \"\"\"Checks for adjacent nested fors and replaces them with itertools.product\"\"\"\n\n @property\n def transformer_class(self):\n return NestedForTransformer\n\n @property\n def warning_message(self):\n return \"Consider using a nested comprehension instead of a nested for\"\n\n @property\n def symbol(self):\n return \"nested-for\"\n\n\nclass NestedForTransformer(LoggingTransformer):\n \"\"\"NodeTransformer that goes visits all the nested `for`s and replaces them\n with itertools.product\"\"\"\n\n def visit_For(self, node: ast.For) -> ast.For:\n inner_for: ast.For = node.body[0]\n new_target = ast.Tuple(elts=[node.target, inner_for.target])\n\n def create_comprehension(for_node: ast.For) -> ast.comprehension:\n return ast.comprehension(target=for_node.target, iter=for_node.iter, ifs=[])\n\n gen_exp = ast.GeneratorExp(\n elt=new_target,\n generators=[create_comprehension(node), create_comprehension(inner_for)],\n )\n new_for = ast.For(\n target=new_target, iter=gen_exp, body=inner_for.body, orelse=node.orelse\n )\n new_for = ast.fix_missing_locations(new_for)\n return new_for\n\n @staticmethod\n def is_smelly(node: ast.AST):\n \"\"\"Check if the node is only a nested for\"\"\"\n return (\n isinstance(node, ast.For)\n and isinstance(node.body[0], ast.For)\n and len(node.body) == 1\n # Check there's no dependancy between nodes\n and not any(\n name_in_node(node.body[0].iter, target)\n for target in for_target_names(node)\n )\n )\n\n\ndef ast_node(expr: str) -> ast.AST:\n \"\"\"Helper function to parse a string denoting an expression into an AST node\"\"\"\n # ast.parse returns \"Module(body=[Node])\"\n return ast.parse(expr).body[0]\n\n\ndef for_target_names(node: ast.For) -> typing.List[ast.Name]:\n \"\"\"Returns the names that are the targets of the for loop.\"\"\"\n target = typing.cast(typing.Union[ast.Tuple, ast.Name], node.target)\n return target.elts if isinstance(target, ast.Tuple) else [target]\n" }, { "alpha_fraction": 0.6003544330596924, "alphanum_fraction": 0.6052281856536865, "avg_line_length": 31.242856979370117, "blob_id": "5d7986945fae202c05dc6271b85d4c706b79acb9", "content_id": "a2ae542a113bd17bb715f43e44c32da07a16a1cc", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2257, "license_type": "permissive", "max_line_length": 104, "num_lines": 70, "path": "/good_smell/smells/join_literal.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "import ast\n\nfrom good_smell import AstSmell, LoggingTransformer\n\ntry:\n # ast.Str is deprecated in py3.8 and will be removed\n StrConst = (ast.Constant, ast.Str)\nexcept AttributeError:\n StrConst = (ast.Constant,)\n\n\nclass JoinLiteral(AstSmell):\n \"\"\"Checks if joining a literal of a sequence.\"\"\"\n\n @property\n def transformer_class(self):\n return Transformer\n\n @property\n def warning_message(self):\n return (\n \"Consider using str.format instead of joining a constant amount of strings.\"\n )\n\n @property\n def symbol(self):\n return \"join-literal\"\n\n\nclass Transformer(LoggingTransformer):\n \"\"\"Checks for usages of str.join with a constant amount of arguments.\"\"\"\n\n @staticmethod\n def normalize_constant(node) -> ast.Constant:\n \"\"\"Compatibility wrapper for py3.8+, ast, ast.Str and ast.Num are replaced by ast.Constant.\n\n We don't type annotate `node` so it doesn't break on py3.10+ when these classes will be removed.\n \"\"\"\n for attr in [\"value\", \"s\", \"n\"]:\n try:\n return ast.Constant(value=getattr(node, attr))\n except AttributeError:\n pass\n raise ValueError(\"Not a constat.\")\n\n def visit_Call(self, node: ast.Call) -> ast.Call:\n format_arguments = node.args[0].elts\n format_delimiter = self.normalize_constant(node.func.value).value\n format_string = format_delimiter.join([\"{}\"] * len(format_arguments))\n new_call = ast.Call(\n func=ast.Attribute(\n value=ast.Constant(value=format_string), attr=\"format\", ctx=ast.Load()\n ),\n args=format_arguments,\n keywords=[],\n )\n return ast.fix_missing_locations(new_call)\n\n @staticmethod\n def is_smelly(node: ast.AST):\n \"\"\"Check if the node is only a nested for\"\"\"\n return (\n isinstance(node, ast.Call)\n and isinstance(node.func, ast.Attribute)\n and isinstance(node.func.value, StrConst)\n and node.func.attr == \"join\"\n and len(node.args) == 1\n and isinstance(node.args[0], ast.List)\n and not any(isinstance(el, ast.Starred) for el in node.args[0].elts)\n )\n" }, { "alpha_fraction": 0.5569800734519958, "alphanum_fraction": 0.5826210975646973, "avg_line_length": 18.52777862548828, "blob_id": "9693b5cbb26f052c8bebdb00b2bedb1cbcaf099e", "content_id": "fcca21c53361113711a5be8a7f5b54ac6d5214bd", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 702, "license_type": "permissive", "max_line_length": 57, "num_lines": 36, "path": "/tests/examples/join_literal.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "#: Warn when using join on a list of known literals.\n# join-literal\na = \"foo\"\nb = \"bar\"\n\",\".join([a, b])\n# ==>\na = \"foo\"\nb = \"bar\"\n\"{},{}\".format(a, b)\n# END\n#: Don't warn when joining an iterable\n# None\niterable = [\"a\",\"b\"]\n\",\".join(iterable)\n# ==>\niterable = [\"a\",\"b\"]\n\",\".join(iterable)\n# END\n#: Don't warn when joining a generator expression\n# None\n\",\".join(str(i) for i in range(100))\n# ==>\n\",\".join(str(i) for i in range(100))\n# END\n#: Don't warn when joining a list comprehension\n# None\n\",\".join([str(i) for i in range(100)])\n# ==>\n\",\".join([str(i) for i in range(100)])\n# END\n#: Don't warn when the list literal includes an unpacking\n# None\n\",\".join([1,2,3,*a])\n# ==>\n\",\".join([1,2,3,*a])\n# END" }, { "alpha_fraction": 0.5859938263893127, "alphanum_fraction": 0.610710620880127, "avg_line_length": 27.558822631835938, "blob_id": "2c02c9fdb90b701899860f8f75e09d05fc6b4e10", "content_id": "5d0a3d84a24db067a19fad2e16440b842540908e", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 971, "license_type": "permissive", "max_line_length": 83, "num_lines": 34, "path": "/tests/test_no_transform.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "import itertools\nimport ast\nfrom good_smell.smells import NestedFor\n\n\ndef compare_ast(node1, node2):\n \"\"\"Compare two ast, adapted from https://stackoverflow.com/a/30581854 to py3\"\"\"\n if type(node1) is not type(node2):\n return False\n if isinstance(node1, ast.AST):\n for k, v in vars(node1).items():\n if k in (\"lineno\", \"col_offset\", \"ctx\"):\n continue\n if not compare_ast(v, getattr(node2, k)):\n return False\n return True\n elif isinstance(node1, list):\n return all(itertools.starmap(compare_ast, zip(node1, node2)))\n else:\n return node1 == node2\n\n\ndef test_no_transform():\n source = \"\"\"\nseq_a = [0]\nseq_b = range(10)\nfor i in seq_a:\n for j in seq_b:\n print(i, j)\"\"\"\n original_tree = ast.parse(source)\n tree = ast.parse(source)\n assert NestedFor(transform=False, path=\"test\", tree=tree).check_for_smell()\n\n assert compare_ast(original_tree, tree)\n" }, { "alpha_fraction": 0.6520146727561951, "alphanum_fraction": 0.6764346957206726, "avg_line_length": 20.552631378173828, "blob_id": "0a16d33b1d0b6d42a08d08a08293c94c6b006863", "content_id": "d6c74dd4204430f3acc0aa650d2634a6cee86717", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 819, "license_type": "permissive", "max_line_length": 73, "num_lines": 38, "path": "/pyproject.toml", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "[tool.poetry]\nname = \"good_smell\"\nversion = \"0.18\"\ndescription = \"A linter/refactoring tool to make your code smell better!\"\nauthors = [\"Tomer Keren <[email protected]>\"]\nlicense = \"BSD-3-Clause\"\nreadme = \"README.md\"\nrepository = \"https://github.com/Tadaboody/good_smell\"\nclassifiers = [\n\"Development Status :: 3 - Alpha\",\n\"Framework :: Flake8\",\n\"Environment :: Console\",\n\"Operating System :: OS Independent\",\n]\n\n[tool.poetry.dependencies]\npython = \"^3.6\"\nfire = \"*\"\nastor = \"*\"\nflake8 = \"^3\"\n\n[tool.poetry.dev-dependencies]\npre-commit = \"*\"\npytest = \"*\"\nautopep8 = \"*\"\npylint = \"*\"\nblack = \"==20.8b1\"\n\n[tool.poetry.scripts]\ngood_smell = \"good_smell:main\"\n\n[tool.poetry.plugins]\n[tool.poetry.plugins.\"flake8.extension\"]\nSML = \"good_smell:LintingFlake8\"\n\n[build-system]\nrequires = [\"poetry>=0.12\"]\nbuild-backend = \"poetry.masonry.api\"\n" }, { "alpha_fraction": 0.6062546968460083, "alphanum_fraction": 0.6085154414176941, "avg_line_length": 30.223529815673828, "blob_id": "6ba9e6c5bcf956db7189962d719e2de6d61065d8", "content_id": "d271ceec387e3ff921de254c8f89dbfa292c51bb", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2654, "license_type": "permissive", "max_line_length": 110, "num_lines": 85, "path": "/good_smell/smells/filter.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "from typing import TypeVar\nimport ast\nfrom typing import cast\n\nfrom good_smell import AstSmell, LoggingTransformer\n\n\nclass NameReplacer(ast.NodeTransformer):\n def __init__(self, old: ast.Name, new: ast.AST):\n self.old = old\n self.new = new\n\n def visit_Name(self, node: ast.Name) -> ast.AST:\n if node.id == self.old.id:\n return self.new\n return node\n\n\nT = TypeVar(\"T\", bound=ast.AST)\n\n\ndef replace_name_with_node(node: T, old_val: ast.Name, new_val: ast.AST) -> T:\n \"\"\"Returns `node` with all occurences of `old_val` (a variable) replaced with `new_val` (an expression)\"\"\"\n return NameReplacer(old_val, new_val).visit(node)\n\n\nclass FilterTransformer(LoggingTransformer):\n \"\"\"Bumps the filter to the iterator\"\"\"\n\n def visit_For(self, node: ast.For) -> ast.For:\n if_node: ast.If = node.body[0]\n filter_condition: ast.Expr = if_node.test\n if not isinstance(node.iter, ast.GeneratorExp):\n # Create a generator expression if it doesn't exist\n GEN_ELT_NAME = \"x\"\n gen_exp: ast.GeneratorExp = cast(\n ast.GeneratorExp,\n ast_node(f\"({GEN_ELT_NAME} for {GEN_ELT_NAME} in seq)\").value,\n )\n gen_target = ast_node(GEN_ELT_NAME).value\n iter_comprehension = gen_exp.generators[0]\n iter_comprehension.iter = replace_name_with_node(\n node.iter, node.target, gen_target\n )\n else:\n gen_exp = node.iter\n iter_comprehension = gen_exp.generators[0]\n gen_target = gen_exp.elt\n\n iter_comprehension.ifs.append(\n replace_name_with_node(filter_condition, node.target, gen_target)\n )\n node.iter = gen_exp\n node.body = if_node.body\n return node\n\n def is_smelly(self, node: ast.AST):\n \"\"\"Check if the node is only a nested for\"\"\"\n return (\n isinstance(node, ast.For)\n and len(node.body) == 1\n and isinstance(node.body[0], ast.If)\n )\n\n\nclass FilterIterator(AstSmell):\n \"\"\"Checks for adjacent nested fors and replaces them with itertools.product\"\"\"\n\n @property\n def transformer_class(self):\n return FilterTransformer\n\n @property\n def warning_message(self):\n return \"Consider using itertools.product instead of a nested for\"\n\n @property\n def symbol(self) -> str:\n return \"filter-iterator\"\n\n\ndef ast_node(expr: str) -> ast.AST:\n \"\"\"Helper function to parse a string denoting an expression into an AST node\"\"\"\n # ast.parse returns \"Module(body=[Node])\"\n return ast.parse(expr).body[0]\n" }, { "alpha_fraction": 0.5464216470718384, "alphanum_fraction": 0.5502901077270508, "avg_line_length": 31.3125, "blob_id": "8220089f2203720ab5dd41f9a09cc378ccdbf264", "content_id": "2a49da43b125a2eb7535001e430047750fbd6f9e", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1034, "license_type": "permissive", "max_line_length": 90, "num_lines": 32, "path": "/good_smell/flake8_ext.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "import ast\nfrom typing import Generator, Tuple\n\nfrom good_smell import SmellWarning, implemented_smells, __version__\n\n\nclass LintingFlake8:\n \"\"\"Entry point good smell to be used as a flake8 linting plugin\"\"\"\n\n name = \"good-smell\"\n version = __version__\n\n def __init__(self, tree: ast.AST, filename: str):\n \"\"\"\"http://flake8.pycqa.org/en/latest/plugin-development/plugin-parameters.html\"\"\"\n self.tree = tree\n self.filename = filename\n\n def run(self) -> Generator[Tuple[int, int, str, str], None, None]:\n for num, smell in enumerate(implemented_smells):\n warnings = smell(\n transform=False, tree=self.tree, path=self.filename\n ).check_for_smell()\n warning: SmellWarning\n yield from (\n (\n warning.row,\n warning.col,\n f\"SML{str(num).zfill(3)} {warning.msg}\",\n \"GoodSmell\",\n )\n for warning in warnings\n )\n" }, { "alpha_fraction": 0.5787401795387268, "alphanum_fraction": 0.5787401795387268, "avg_line_length": 10.545454978942871, "blob_id": "8710d5e4e3e9ac9db1d0bdb5b97b2864f8f809ab", "content_id": "6cbd3aa86c85dbf0a36048b954cc1186eb066610", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": true, "language": "Markdown", "length_bytes": 254, "license_type": "permissive", "max_line_length": 44, "num_lines": 22, "path": "/.github/ISSUE_TEMPLATE/new-smell.md", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "---\nname: New Smell\nabout: Suggest a new smell to detect and fix\ntitle: ''\nlabels: smell, new\nassignees: ''\n\n---\n\n# New smell\n\n### Smelly code\n```py\nfor x in iterable:\n ...\n```\n### Fixed code\n```py\nfor x in iterable:\n ...\n```\n### Why is it smelly?\n" }, { "alpha_fraction": 0.49157893657684326, "alphanum_fraction": 0.5294736623764038, "avg_line_length": 16.592592239379883, "blob_id": "155b0beeee9559d4183c86ef43c2eee0a02a667c", "content_id": "c2fbbf7e162e527ea4c0d86e02e01d0c505acad1", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 950, "license_type": "permissive", "max_line_length": 56, "num_lines": 54, "path": "/tests/examples/filter.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "#: Move if to iterator\n# filter-iterator\nfor i in range(10):\n if i == 2:\n print(1)\n print(2)\n# ==>\nfor i in (x for x in range(10) if x == 2):\n print(1)\n print(2)\n# END\n#: Don't move if there's code before\n# None\nfor i in range(10):\n print(1)\n if pred(i):\n print(2)\n# ==>\nfor i in range(10):\n print(1)\n if pred(i):\n print(2)\n# END\n#: don't move if there's code after\n# None\nfor i in range(10):\n if pred(i):\n print(1)\n print(2)\n# ==>\nfor i in range(10):\n if pred(i):\n print(1)\n print(2)\n# END\n#: Merge into existing expr\n# filter-iterator\nfor i in (a * 2 for a in range(2)):\n if pred(i):\n pass\n# ==>\nfor i in (a * 2 for a in range(2) if pred(a * 2)):\n pass\n\n# END\n#: Merge into existing complex expr\n# filter-iterator\nfor i in (f(a) * 2 for a in range(2)):\n if pred(i):\n pass\n# ==>\nfor i in (f(a) * 2 for a in range(2) if pred(f(a) * 2)):\n pass\n# END\n" }, { "alpha_fraction": 0.552763819694519, "alphanum_fraction": 0.5577889680862427, "avg_line_length": 18.899999618530273, "blob_id": "6afb7342851bc67b0293ee37f67f88db56324bac", "content_id": "417fba6f813de45343725cccc1ed0759b0cdad40", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 398, "license_type": "permissive", "max_line_length": 55, "num_lines": 20, "path": "/tests/test_enumerate_fix.py", "repo_name": "Tadaboody/good_smell", "src_encoding": "UTF-8", "text": "from good_smell import fix_smell\nfrom re import match\nimport pytest\n\nvalid_sources = [\"\"\"\na = [0]\nfor i in range(len(a)):\n print(a[i])\n\"\"\",\n \"\"\"\nb = [1]\nfor i in range(len(a + b)):\n print(i)\n\"\"\"]\n\n\[email protected](\"source\", valid_sources)\ndef test_range_len_fix(source):\n assert not match(r'for \\w+ in range\\(len\\(.+\\)\\):',\n fix_smell(source))\n" } ]
28
1ambda/test-driven
https://github.com/1ambda/test-driven
f74992f3f61b0d6a7a3ec81bbfd23dea6edc58e6
872fba27f27949046c36911f7d2f1012e459d786
173f2c004c1c9b5c6c861fcd50206de9523eab05
refs/heads/master
2016-09-05T09:20:17.658823
2015-05-09T06:01:28
2015-05-09T06:01:28
34,334,946
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5216360688209534, "alphanum_fraction": 0.5251926779747009, "avg_line_length": 18.835294723510742, "blob_id": "414b7672ef7e8cc110535185c7bd382593f51dff", "content_id": "f0b326162c217bd6f7cceb8812a21ddf0579b189", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1687, "license_type": "no_license", "max_line_length": 94, "num_lines": 85, "path": "/xunit-python/XUnit.py", "repo_name": "1ambda/test-driven", "src_encoding": "UTF-8", "text": "\nclass TestSuite:\n def __init__(self):\n self.tests = []\n\n def add(self, case):\n methods = [m for m in dir(case) if callable(getattr(case, m)) if m.startswith('test')]\n\n for m in methods:\n self.tests.append(case(m))\n\n\n def run(self, result):\n for t in self.tests:\n t.run(result)\n\nclass TestCase:\n def __init__(self, name):\n self.name = name\n\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n def run(self, result):\n try:\n self.setUp()\n except Exception as e:\n pass\n\n try:\n result.testStarted()\n method = getattr(self, self.name)\n method()\n except Exception as e:\n result.testFailed()\n\n self.tearDown()\n return result\n\nclass SuccessCase(TestCase):\n def __init__(self, name):\n TestCase.__init__(self, name)\n self.log = \"\"\n\n def setUp(self):\n self.log += \"setUp \"\n\n def testMethod(self):\n self.log += \"testMethod \"\n\n def tearDown(self):\n self.log += \"tearDown\"\n\nclass FailureCase(TestCase):\n def __init__(self, name):\n TestCase.__init__(self, name)\n self.log = \"\"\n\n def setUp(self):\n a = 1 / 0\n\n def testMethod(self):\n self.log += \"testMethod \"\n\n def tearDown(self):\n self.log += \"tearDown\"\n\n\n\n\nclass TestResult:\n def __init__(self):\n self.runCount = 0\n self.failCount = 0\n\n def testStarted(self):\n self.runCount += 1\n\n def testFailed(self):\n self.failCount += 1\n\n def summary(self):\n return \"%d run, %d failed\" % (self.runCount, self.failCount)\n" }, { "alpha_fraction": 0.6106114983558655, "alphanum_fraction": 0.6196042895317078, "avg_line_length": 21.67346954345703, "blob_id": "ec87ec1e3760d154266f77de8e81c1962a92f929", "content_id": "cc273ee189285ea766a57bb2ec84be8c787e7f9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1112, "license_type": "no_license", "max_line_length": 59, "num_lines": 49, "path": "/xunit-python/XUnitSpec.py", "repo_name": "1ambda/test-driven", "src_encoding": "UTF-8", "text": "from XUnit import *\n\nclass TestCaseSpec(TestCase):\n\n def setUp(self):\n self.result = TestResult()\n\n def testTemplateMethod(self):\n self.test = SuccessCase(\"testMethod\")\n\n self.test.run(self.result)\n\n assert \"setUp testMethod tearDown\" == self.test.log\n assert \"1 run, 0 failed\" == self.result.summary()\n\n def testFailedCase(self):\n self.test = FailureCase(\"brokenMethod\")\n\n self.test.run(self.result)\n\n # failed to setup\n assert(\"tearDown\" == self.test.log)\n # failed to call the test method\n assert(\"1 run, 1 failed\" == self.result.summary())\n\n def testSuiteAdd(self):\n suite = TestSuite()\n suite.add(SampleSpec)\n suite.add(SuccessCase)\n suite.add(FailureCase)\n suite.run(self.result)\n\n assert(\"4 run, 1 failed\" == self.result.summary())\n\n\nclass SampleSpec(TestCase):\n def testSuccess(self):\n assert(1 == 1)\n\n def testFailure(self):\n assert(1 == 2)\n\n\nsuite = TestSuite()\nsuite.add(TestCaseSpec)\n\nresult = TestResult()\nsuite.run(result)\nprint result.summary()\n\n" }, { "alpha_fraction": 0.7222222089767456, "alphanum_fraction": 0.7339181303977966, "avg_line_length": 30, "blob_id": "704251db3ec16665ac66b1401b192a4d66240246", "content_id": "f62ca1a560a1f7b21151c331a9a45ee08ebb7904", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 342, "license_type": "no_license", "max_line_length": 268, "num_lines": 11, "path": "/README.md", "repo_name": "1ambda/test-driven", "src_encoding": "UTF-8", "text": "# Clean code that works\n\n[![Build Status](https://travis-ci.org/1ambda/test-driven.svg?branch=master)](https://travis-ci.org/1ambda/test-driven) [![Coverage Status](https://coveralls.io/repos/1ambda/test-driven/badge.svg?branch=master)](https://coveralls.io/r/1ambda/test-driven?branch=master)\n\n## Poly Currency\n \n- Java\n\n## XUnit\n\n- Python\n\n" }, { "alpha_fraction": 0.6382022500038147, "alphanum_fraction": 0.670412003993988, "avg_line_length": 22.017240524291992, "blob_id": "bfac2df2eb1ce8b0f55c0737aa767c4dff23f6a0", "content_id": "a820bde90c6f77fcbdca000847fa328a440e456e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 1335, "license_type": "no_license", "max_line_length": 92, "num_lines": 58, "path": "/poly-currency-java/build.gradle", "repo_name": "1ambda/test-driven", "src_encoding": "UTF-8", "text": "buildscript {\n repositories {\n mavenCentral()\n }\n\n dependencies {\n classpath 'net.saliman:gradle-cobertura-plugin:2.2.8'\n classpath 'org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.3.1'\n }\n} \n\napply plugin: 'java'\napply plugin: 'idea'\napply plugin: net.saliman.gradle.plugin.cobertura.CoberturaPlugin\napply plugin: 'com.github.kt3k.coveralls'\n\nconfigurations.all {\n resolutionStrategy {\n // Cobertura includes an ASM version that can't handle Java 8, ASM 5.0.3 handles Java8\n force 'org.ow2.asm:asm:5.0.3'\n forcedModules = [ 'org.ow2.asm:asm:5.0.3' ]\n }\n}\n\ncobertura.coverageFormats = ['html', 'xml'] // coveralls plugin depends on xml format report\n\nsourceCompatibility = 1.8\nversion = '1.0'\njar {\n manifest {\n attributes 'Implementation-Title': 'Gradle Quickstart',\n 'Implementation-Version': version\n }\n}\n\nrepositories {\n mavenCentral()\n}\n\ndependencies {\n compile 'org.hamcrest:hamcrest-core:1.3'\n compile group: 'commons-collections', name: 'commons-collections', version: '3.2'\n testCompile group: 'junit', name: 'junit', version: '4.+'\n testRuntime \"org.slf4j:slf4j-log4j12:1.7.5\"\n testRuntime \"log4j:log4j:1.2.7\"\n}\n\ntest {\n systemProperties 'property': 'value'\n}\n\nuploadArchives {\n repositories {\n flatDir {\n dirs 'repos'\n }\n }\n}\n" }, { "alpha_fraction": 0.6191585063934326, "alphanum_fraction": 0.6261433362960815, "avg_line_length": 20.9270076751709, "blob_id": "d00ec689a193d29a10555ae874be8a9d6e4840c3", "content_id": "2a1067a8347152d3d25fcf7e6e91e555f0b5dfcb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8131, "license_type": "no_license", "max_line_length": 216, "num_lines": 274, "path": "/xunit-python/README.md", "repo_name": "1ambda/test-driven", "src_encoding": "UTF-8", "text": "# XUnit Implementation using Python\n\n[Ref - Test Driven Development: By Example](http://www.amazon.com/Test-Driven-Development-Kent-Beck/dp/0321146530/ref=sr_1_1?s=books&ie=UTF8&qid=1430807061&sr=1-1&keywords=test+driven+development+by+example+in+Books)\n\n> 소프트웨어 공학 역사에서 이렇게 짧은 코드로, 이토록 많은 사람이, 이런 큰 은혜를 입은적이 없었다.\n\n\n## Day 4\n \n### TODO\n\n- ~~테스트 메서드 호출하기~~\n- ~~먼저 `setUp` 호출하기~~\n- ~~나중에 `tearDown` 호출하기~~\n- ~~테스트 메서드가 실패하더라도, `tearDown` 호출하기~~\n- ~~수집된 결과를 출력하기~~\n- ~~실패한 테스트 보고하기~~\n- **여러개의 테스트를 실행하기**\n- **Suite 에 테스트 케이스를 인자로 넣으면, 자동으로 테스트 생성하기**\n\n### SUMMARY\n\n- 중간에 `finally` 때문에 디버깅에 애를 먹었다.\n\n- `setUp` 을 테스트하기 위해, 실패하는 `setUp` 을 가진 클래스 `InvalidSetup` 을 만들었다. 이제 `testBorkenMethod` 를 `InvalidSetup` 을 이용해\n서 진행했고, 많은 중복을 제거할 수 있었다. 돌이켜 보니 `InvalidSetup` 이란 이름 대신에, `FailedCase` 란 이름이 더 나을 것 같다. \n`WasRun` 도 `SuccessCase` 로 변경했다. 이제 각각 성공과 실패의 책임을 담당하는 분리된 테스트 케이스를 가지게 되었다.\n\n```python\ndef testFailedCase(self):\n self.test = FailedCase(\"brokenMethod\")\n result = self.test.run()\n # failed to setup\n assert(\"tearDown\" == self.test.log)\n # failed to call the test method\n assert(\"1 run, 1 failed\" == result.summary())\n \nclass FailedCase(TestCase):\n def __init__(self, name):\n TestCase.__init__(self, name)\n self.log = \"\"\n\n def setUp(self):\n a = 1 / 0\n\n def testMethod(self):\n self.log += \"testMethod \"\n\n def tearDown(self):\n self.log += \"tearDown\"\n```\n\n- 테스트 하나와 테스트 집단 (`TestSuite`) 를 동일하게 다루기 위해 [컴포지트 패턴](https://www.wikiwand.com/en/Composite_pattern) 을 도입했다. \n 이 이름보다는 `Tree` 라는 이름이 더 직관적이다. 켄트백이 말하는 **적절한 메타포** 에 더 가까운것 같고.\n\n![](http://rpouiller.developpez.com/tutoriel/java/design-patterns-gang-of-four/images/designPatternStructuralComposite.png)\n\n```python\nsuite = TestSuite()\nsuite.add(TestCaseSpec(\"testTemplateMethod\"))\nsuite.add(TestCaseSpec(\"testFailedCase\"))\nsuite.add(TestCaseSpec(\"testTestSuite\"))\n\nresult = TestResult()\nsuite.run(result)\nprint result.summary()\n\n```\n\n```python\nclass TestSuite:\n def __init__(self):\n self.tests = []\n\n def add(self, test):\n self.tests.append(test)\n\n def run(self, result):\n for t in self.tests:\n t.run(result)\n\nclass TestCase:\n def __init__(self, name):\n self.name = name\n\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n def run(self, result):\n try:\n self.setUp()\n except Exception as e:\n pass\n\n try:\n result.testStarted()\n method = getattr(self, self.name)\n method()\n except Exception as e:\n result.testFailed()\n\n self.tearDown()\n return result\n```\n\n- 매번 `add` 로 `TestSuite` 에 추가하는 것이 귀찮아서 `add` 인자로 `TestCase` 를 넣으면, 자동으로 실행하게끔 만들었다.\n 당연히 테스트케이스 부터 작성했다.\n\n```python\n# test case\ndef testSuiteAdd(self):\n suite = TestSuite()\n suite.add(SampleSpec)\n suite.add(SuccessCase)\n suite.add(FailureCase)\n suite.run(self.result)\n\n assert(\"4 run, 1 failed\" == self.result.summary())\n\n# example TestCase subclass\nclass SampleSpec(TestCase):\n def testSuccess(self):\n assert(1 == 1)\n\n def testFailure(self):\n assert(1 == 2)\n \n# add Impl in `TestSuite`\ndef add(self, case):\n methods = [m for m in dir(case) if callable(getattr(case, m)) if m.startswith('test')]\n\n for m in methods:\n self.tests.append(case(m))\n```\n\n다 만들고 보니, 제거할 테스트가 생겨서 정리했다.\n\n\n\n\n## Day 3\n\n### TODO\n\n- ~~테스트 메서드 호출하기~~\n- ~~먼저 `setUp` 호출하기~~\n- ~~나중에 `tearDown` 호출하기~~\n- 테스트 메서드가 실패하더라도, `tearDown` 호출하기\n- 여러개의 테스트를 실행하기\n- **수집된 결과를 출력하기**\n- **실패한 테스트 보고하기**\n\n- 동적으로 메소드 찾아서 실행하기\n\n### SUMMARY\n\n- 테스트를 작성할 때, 나에게 가르침을 줄 것 같고, 만들 수 있다는 확신이 드는 것 부터 구현했다.\n\n\n## Day 2\n\n### TODO\n\n- ~~테스트 메서드 호출하기~~\n- **먼저 `setUp` 호출하기**\n- **나중에 `tearDown` 호출하기**\n- 테스트 메서드가 실패하더라도, `tearDown` 호출하기\n- 여러개의 테스트를 실행하기\n- 수집된 결과를 출력하기\n\n### SUMMARY\n\n- 무언가 배우기를 기대한다면, 한 번의 하나의 메소드만 수정하면서 테스트가 성공할 수 있도록 고민하자.\n- `setUp` 에서 사용했던 플래그 전략을 버렸다. 플래그가 많아지니까 귀찮아졌다. 그리고 플래그보다 \n더 테스트 순서에 대해 자세히 기록할 수 있는 로그 방식을 택했다. 메소드의 본질에 집중하려고 노력했\n다\n\n```python\nclass TestCaseSpec(TestCase):\n def testTemplateMethod(self):\n self.test = WasRun(\"testMethod\")\n self.test.run()\n assert self.test.log == \"setUp testMethod \"\n\nTestCaseSpec(\"testTemplateMethod\").run()\n```\n\n이렇게 변경하니까, 이제 `tearDown` 을 검사하는 일은 `setUp testMethod teatDown ` 과 로그를 비교하기만 하면 된다!\n\n\n## Day 1\n\n### TODO\n\n- **테스트 메서드 호출하기**\n- 먼저 `setUp` 호출하기\n- 나중에 `tearDown` 호출하기\n- 테스트 메서드가 실패하더라도, `tearDown` 호출하기\n- 여러개의 테스트를 실행하기\n- 수집된 결과를 출력하기\n\n### SUMMARY\n\n- **pluggable selector** 를 사용했다. 더 자세한 내용은 [여기](http://junit.sourceforge.net/doc/cookstour/cookstour.htm) 를 참조하자.\n\n\n### LESSON\n\n우선 테스트 케이스를 만들고, 테스트 메서드를 작성할 수 있도록 해야 한다. 그러려면 테스트 케이스 작성을 도와주는 프레임워크를 테스트하기 위한 테스트 케이스를 작성해야 한다. ~~응?~~\n\n작은 것 부터 수동으로 시작하자. 테스트가 실행되었는지 알려주는 `wasRun` 플래그를, `WasRun` 클래스에 담아서 테스트 메소드가 실행되었는지 알 수 있게끔 하자. 당연히 테스트부터 작성한다.\n\n```python\n# Xunit.\nfrom XUnit import WasRun\n\ntest = WasRun(\"testMethod\")\nprint test.wasRun # None\ntest.testMethod()\nprint test.wasRun # 1\n\n# XUnit.py\nclass WasRun:\n def __init__(self, name):\n self.wasRun = None\n self.name = name\n\n def testMethod(self):\n self.wasRun = 1\n\n def run(self):\n method = getattr(self, self.name)\n method()\n\n```\n\n`WasRun` 클래스는 두 개의 독립된 책임이 있다. 하나는 메소드를 실행하는 것이고, 하나는 `wasRun` 을 다루는 일이다. \n메소드를 실행하는 부분을 `TestCase` 로 옮기고 `WasRun` 클래스가 이를 상속받게 하자.\n\n```python\nclass TestCase:\n def __init__(self, name):\n self.name = name\n\n def run(self):\n method = getattr(self, self.name)\n method()\n\nclass WasRun(TestCase):\n def __init__(self, name):\n self.wasRun = None\n TestCase.__init__(self, name)\n\n def testMethod(self):\n self.wasRun = 1\n ```\n \n이 `TestCase` 를 이용해 테스트를 하는 `TestCaseSpec` 을 만들어 보자.\n\n```python\nclass TestCaseSpec(TestCase):\n def testRunning(self):\n test = WasRun(\"testMethod\")\n assert(not test.wasRun)\n test.run()\n assert(test.wasRun)\n\nTestCaseSpec(\"testRunning\").run()\n```\n\n좀 괴상하지만, 어쨌든 이제 `print` 가 필요없다.\n\n \n\n" }, { "alpha_fraction": 0.6234511137008667, "alphanum_fraction": 0.6347157955169678, "avg_line_length": 21.243736267089844, "blob_id": "9a5c5576c874d4559fbd97ccfa157f7f70b1691a", "content_id": "893c4472cb90768a8d76814c27d27b8b775aa13b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 13944, "license_type": "no_license", "max_line_length": 117, "num_lines": 439, "path": "/poly-currency-java/README.md", "repo_name": "1ambda/test-driven", "src_encoding": "UTF-8", "text": "# TDD Example: Poly Currency\n\n[Ref: Test Driven Development: By Example](http://www.amazon.com/Test-Driven-Development-By-Example/dp/0321146530)\n\n\n## Retrospection\n\n- JUnit 이 로그를 남기도록 해서, 테스트를 얼마나 실행하는가 보는것도 자신의 패턴을 파악하는데 도움이 된다.\n\n- 코드 매트릭스, 즉 모델 코드와 테스트 코드 사이의 클래스, 함수, 줄, 복잡도 등을 나타냄으로써 테스트의 경제성을 파악할 수 있다.\n\n- 테스트의 질을 판별하기 위해 *coverage* 나, *defect insertion* 등을 사용할 수 있다.\n\n**JProbe**, **Jester**\n\n- 커버리지를 높이기 위해 테스트를 더 많이 작성하는 대신, 코드의 로직을 단순하게 할 수 있다.\n \n## Day 7: Ending\n\n**TODO** \n- 다른 통화간 덧셈\n- `Money` 의 책임을 뺏어 `IExpression` 으로 옮기기 \n\n**LESSON**\n\n- 두 개의 서브클래스 `Money`, `Sum` 에서 동일한 함수 `plus` 를 발견했다. 추상클래스를 떠올려봤다.\n\n- TDD 의 경제성에 대해서 생각해 봤다.\n\n> TDD 로 구현할 땐 테스트의 라인 수와, 모델 코드의 라인 수가 거의 비슷한 상태로 끝난다. TDD가 경제적이려면 매일 만들어내는 코드가 두배가 되거나, \n동일한 기능을 구현하되 절반의 줄 수로 해내야한다. TDD 가 본래 자신의 방법에 디해서 어떻게 다른지 직접 측정해 보는것이 필요한데, 이때는 디버깅, 통합작업, \n다른사람에게 설명하는데 걸리는 시간 등을 반드시 포함해야 한다. \n\n- 테스트가 코드보다 길다는것을 발견했다. 이 문제를 해결하기 위해 [JUnit Fixture](https://github.com/junit-team/junit/wiki/Test-fixtures) 를 사용했다.\n\n결국, 테스트는 비용과 관련된 문제이며, 픽스쳐를 이용하는것도 이 비용을 절감해준다는것을 알게 되었다. 테스트는 경제적이어야 한다.\n\n\n```java\n// before\npublic IExpression plus(IExpression addend) {\n return new Sum(this, addend);\n}\n\n@Test\npublic void testSumPlus () {\n IExpression fiveBucks = Money.dollar(5);\n IExpression tenFrancs = Money.franc(10);\n\n Bank bank = new Bank();\n bank.addRate(\"CHF\", \"USD\", 2);\n\n IExpression sum = new Sum(fiveBucks, tenFrancs).plus(fiveBucks);\n Money result = bank.reduce(sum, \"USD\");\n\n assertEquals(Money.dollar(15), result);\n}\n```\n\n```java\n// after\nprivate IExpression fiveBucks;\nprivate IExpression tenFrancs;\nprivate Bank bank;\n\n@Before\npublic void setUpClass() {\n fiveBucks = Money.dollar(5);\n tenFrancs = Money.franc(10);\n bank = new Bank();\n bank.addRate(\"CHF\", \"USD\", 2);\n}\n\n@Test\npublic void testSumTimes () {\n IExpression sum = new Sum(fiveBucks, tenFrancs).times(2);\n Money result = bank.reduce(sum, \"USD\");\n assertEquals(Money.dollar(20), result);\n}\n\n@Test\npublic void testSumPlus () {\n IExpression sum = new Sum(fiveBucks, tenFrancs).plus(fiveBucks);\n Money result = bank.reduce(sum, \"USD\");\n\n assertEquals(Money.dollar(15), result);\n}\n```\n\n\n## Day 6\n\n**TODO**\n- **통화 변환: 2 CHF -> 1 USD**\n- 다른 통화간 변환\n- 다른 환율간 덧셈\n\n**Summary**\n\n- 테스트 없이 `private` 헬퍼 메소드를 만들었다.\n- 자바의 `equals` 검증을 위한 테스트를 만들어 봤다.\n\n**LESSON**\n\n- 환율을 변환하기 위해 테스트를 먼저 작성했다. 그리고 가짜로 구현하는 과정에서, `Money` 가 환율을 알게된다는 사실에 절망했다.\n모든 책임은 `Bank` 에 있어야 한다. `reduce` 는 `Expression` 이 수행해야 하며, 환율을 아는 `Bank` 를 파라미터로 넘겨줘야겠다.\n\n```java\n// test\n@Test\npublic void testReduceMoneyDifferentCurrency() {\n Bank bank = new Bank();\n bank.addRate(\"CHF\", \"USD\", 2);\n Money reduced = bank.reduce(Money.franc(2), \"USD\");\n assertEquals(Money.dollar(1), reduced);\n}\n\n// Money.java\npublic Money reduce(String to) {\n int rate = (this.currency.equals(\"CHF\") && to.equals(\"USD\"))\n ? 2 : 1;\n return new Money(amount / rate, to);\n}\n```\n\n- 코드를 리팩토링 하기 전에, 테스트가 기능에 따라 영향을 받을 것 같아서 테스트를 먼저 수정했다. 이제 빨간막대다.\n이 과정을 끝내면 다른 통화간 덧셈을 구현.. 아니 테스트를 작성할 수 있다는 느낌이 들었다.\n\n```java\n@Test\npublic void testReduceMoneyDifferentCurrency() {\n Bank bank = new Bank();\n bank.addRate(\"CHF\", \"USD\", 2);\n\n Money reduced = Money.franc(2).reduce(bank, \"USD\");\n assertEquals(Money.dollar(1), reduced);\n}\n\n@Test\npublic void testReduceMoney() {\n Money one = Money.dollar(1);\n Bank bank = new Bank();\n\n Money reduced = one.reduce(bank, \"USD\");\n assertEquals(Money.dollar(1), reduced);\n}\n\n@Test\npublic void testSimpleAddtion() {\n Money five = Money.dollar(5);\n IExpression sum = five.plus(five);\n\n Bank bank = new Bank();\n Money reduced = sum.reduce(bank, \"USD\");\n\n assertEquals(Money.dollar(10), reduced);\n}\n```\n\n```java\n// Money.java\npublic Money reduce(Bank bank, String to) {\n int rate = bank.rate(this.currency, to);\n return new Money(amount / rate, to);\n}\n\n\n// Bank.java\npublic int rate(String from, String to) {\n return (from.equals(\"CHF\") && to.equals(\"USD\"))\n ? 2 : 1;\n}\n```\n\n가짜로 구현했기 때문에, `2` 가 등장한다. 환율 테이블 표를 만들 수 있을까? 무엇을 이용하면 좋을지 생각해봤는데, 해시테이블은 어떨까?\n해시테이블에서 사용할 키로는 **두개의 통화** 를 써야한다. `Array` 가 동치성 검사를 제대로 해주는지 확인하기 위해 테스트를 작성했다.\n\n```java\n@Test\npublic void testArrayEquals () {\n assertArrayEquals(new Object[] {\"USD\"}, new Object[] {\"USD\"});\n}\n```\n\n책에서와는 달리 성공한다. `Pair` 객체를 구현하면서 무언가 또 배울 수 있을테니. 책을 쫓아가겠다. \n\n- `Pair` 객체를 키로 사용하기 위해 `equals` 와 `hashCode` 를 오버라이딩 했다. 죄악을 저질렀지만 동작은 할 것 같다.\n만약 내가 컨텍스트를 모른채로 리팩토링하고 있었다면 테스트 코드를 먼저 작성해야 했을 것이다.\n\n그리고, `hashCode` 에서 `0` 했기 때문에 테이블에서 선형검색처럼 빠르게 검색될 것이다.\n나중에 통화의 종류가 많아지면 문제가 되겠지만, 일단 그건 그 때 생각하자. \n\n```java\npublic class Pair {\n private String from;\n private String to;\n\n public Pair(String from, String to) {\n this.from = from;\n this.to = to;\n }\n\n @Override\n public boolean equals(Object object) {\n // TODO\n Pair that = (Pair) object;\n return (from.equals(that.from) && to.equals(that.to));\n }\n\n @Override\n public int hashCode() {\n // TODO\n return 0;\n }\n}\n```\n\n- `Bank` 클래스에 테이블을 추가했다. 그리고 중간에, 같은 통화로의 `rate` 에 대해 테스트 실패가 일어나는걸 발견했는데\n 꾹 참고 테스트부터 만들었다.\n\n```java\npublic class Bank {\n\n Hashtable<Pair, Integer> rates;\n\n public Bank() {\n rates = new Hashtable<Pair, Integer>(); ;\n }\n\n public void addRate(String from, String to, int rate) {\n rates.put(new Pair(from, to), rate);\n }\n\n public int rate(String from, String to) {\n if (from.equals(to)) return 1;\n return rates.get(new Pair(from, to));\n }\n}\n\n// test\n@Test\npublic void testIdentityRate () {\n assertEquals(1, new Bank().rate(\"USD\", \"USD\"));\n}\n```\n\n- 추가적으로, `HashTable` 을 `ConcurrentHashMap` 으로 변경헀다.\n\n## Day 5\n\n**TODO**\n\n- ~~5$ + 5$ = 10$~~\n- ~~가짜 구현 `Money.plus` 리팩토링~~\n- ~~가짜 구현 'Bank.reduce` 리팩토링~~\n- `Money.times` 지저분하다.\n\n**LESSON**\n\n- 두 구현체 `Money`, `Sum` 에서 `reudce` 가 가능한지 검토하고, 인터페이스 메소드로 추출했다. 이 과정에서 지저분한 캐스팅이 사라졌다.\n\n즉, 명시적인 클래스 검사 및 캐스팅을 제거하기 위해 **다형성** 을 사용했다. \n이 과정에서, 먼저 한곳에서 캐스팅을 이용해서 구현했다가 이후에 코드를 다른곳으로 옮겼다. \n캐스팅을 이용해도 리팩토링에서 제거할 수 있으므로, 흘러가는대로 하면 된다는 사실을 깨달았다.\n \n \n```java\n// after\npublic class Bank {\n public Money reduce(IExpression expr, String to) {\n return expr.reduce(to);\n }\n}\n```\n\n \n- 다시 한번, **리팩토링은 초록막대에서만 진행한다** 는 사실을 마음에 새겼다. \n- 연산의 외부 행위가 아닌 내부 구현에 대해 집중하는 테스트는, 좋지 않다는 것을 배웠다.\n- 외부에서 내부 필드(Variable)에 너무나 많이 접근한다면 메서드 본문을 해당 클래스로 옮기는것도 생각해 볼 만하다.\n\n\n```java\n// before\n\npublic class Bank {\n public Money reduce(IExpression expr, String currency) {\n Sum sum = (Sum) expr;\n\n Money augend = sum.augend;\n Money addend = sum.addend;\n\n if (!augend.currency().equals(addend.currency())\n && augend.currency().equals(currency))\n return null;\n\n return new Money(augend.amount() + addend.amount(), currency);\n }\n}\n\n\n\n// after\n\npublic class Bank {\n public Money reduce(IExpression expr, String currency) {\n if (expr instanceof Money) return (Money) expr;\n\n Sum sum = (Sum) expr;\n return sum.reduce(currency);\n }\n}\n\npublic class Sum implements IExpression {\n ...\n ...\n \n public Money reduce(String currency) {\n if (!augend.currency().equals(addend.currency())\n && augend.currency().equals(currency)) {\n return null;\n }\n\n int amount = augend.amount() + augend.amount();\n\n return new Money(amount, currency);\n }\n\n}\n```\n \n\n## Day 4\n\n**TODO**\n\n- 5$ + 5$ = 10$\n- 5$ + 5$ 는 `Money`\n- 가짜 구현 `Money.plus` 리팩토링\n- 가짜 구현 'Bank.reduce` 리팩토링\n\n**LESSON**\n\n- 다중 통화를 표현하고 싶지만 시스템의 다른 부분이 모르도록 하고 싶다. \n- 참조 통화 대신에, 다중 통화 *수식* 그 자체를 사용하고 싶다.\n- 이를 위해서 `Expression` 을 도입했다. \n\n- `reduce` 의 책임을 `Expression` 이 아니라 `Bank` 에게 전가했다.\n- 이는 핵심 객체인 `Expression` 이 시스템의 다른부분에 대해서 모르도록 하기 위해서다.\n\n```java\n@Test\npublic void testSimpleAddtion() {\n\tMoney five = Money.dollar(5);\n\tExpression sum = five.plus(five);\n\n\tBank bank = new Bank();\n\tMoney reduced = bank.reduce(sum, \"USD\");\n\n\tassertEquals(Money.dollar(10), reduced);\n}\n```\n\n## Day 3\n\n**TODO**\n\n- 더하기 (가짜로 먼저 구현)\n\n**LESSON**\n\n- 실험해본 걸 물리고, 또 다른 테스틀 작성했다. 때때로 다시 테스트가 성공하도록 되돌아 간뒤, 실패하는 테스트를 다시 작성하고 전진할 필요가 있다.\n- 기능이 복잡할때는, 간단한 버전부터 시작해보자. 예를 들어 완벽한 화폐 덧셈을 구현하기 전에 `5$ + 5$ = 10$` 을 만들어 볼 수 있다. \n\n## Day 2\n\n- ~~공용 equal~~\n- ~~공용 times~~\n- ~~Franc, Dollar 중복~~\n- ~~Franc, Dollar 비교~~\n\n- Currency 개념. flyweight factory 를 이용할수도 있으나 지금은 간단하게\n 더 많은 동기가 있기 전까지는, 더 많은 설계를 도입하지 말자.\n\n http://ko.wikipedia.org/wiki/%ED%94%8C%EB%9D%BC%EC%9D%B4%EC%9B%A8%EC%9D%B4%ED%8A%B8_%ED%8C%A8%ED%84%B4ç\n\n\n- Equal Null\n- Equal Object\n- hashCode()\n\n- getClass 비교보다는 Currency 개념\n\n\n1. 모든것에 대해 테스트코드를 작성하려고 노력할 필요는 없다. 예를 들어, 상속과 같은 **문법적** 기능에 대해 테스팅 하지 않아도 된다. (필요하면 당연히 해야한다.)\n\n문법적 기능보다는, 객체의 기능을 테스트하는데 노력을 쏟자. 다시 말해서 제품을 개선하는 방향으로의 테스트를 우선적으로 하자.\n\n2. 객체의 기능이 정상적으로 변경되었나, 테스트하면서 확인할 수 있다. 당연한 사실인데도 테스트를 **실행하는데** 익숙지 않으면 잘 하지 않게된다. printf 찍듯이, 자주 run 을 실행하자.\n\n3. 더 많은 동기가 있기 전까지는, **더 많은 설계를 도입하지 마라.**\n\n4. 하위 클래스에 대한 직접적인 참조가 적어지면, 하위 클래스의 중복을 제거할 수 있다.\n\n5. 빨간 막대에서는, 테스트를 더 작성하지 않는 것이 좋다.\n\n6. 빨간 막대에서, 기능을 변경하려고 하는데 해당 기능에 대한 테스트가 없다면\n다시 초록막대로 돌아가서, 테스트를 작성하는 보수적인 방법을 사용할 수 있다.\n\n## Day 1\n\n1. 가능한 아름다운 인터페이스를 테스트코드로 작성한다. 또는 설계상의 결함을, 테스트로 작성할 수 있다.\n2. 쉽고 간결한 방법이 있으면, 코드로 작성한다. 그럴수 없으면 적어놓고, 빠르게 초록막대를 보도록 죄악을 범한다.\n3. 중복을 제거한다.\n\n내가 해야할 유일한 일, 가장 중요한 일은 설계에 대한 결정과, 그에 대한 피드백 사이의 간격을 조절하는 것이다.\n\n### 두 테스트가 동시에 실패하면 망한다.\n\n곱셈 테스트는, 동치성 테스트에 의존한다. 이런 위험은 관리해야 한다.\n\n```java\n@Test\npublic void testMultiplication() {\n Dollar five = new Dollar(5);\n Dollar ten = five.times(2);\n assertEquals(new Dollar(5), five);\n assertEquals(new Dollar(10), ten);\n\n Dollar fifteen = five.times(3);\n assertEquals(new Dollar(15), fifteen);\n assertEquals(new Dollar(5), five);\n}\n\n@Test\npublic void testEquality() {\n assertTrue(new Dollar(5).equals(new Dollar(5)));\n assertFalse(new Dollar(6).equals(new Dollar(5)));\n}\n```\n" } ]
6
ionambrinoc/practicals
https://github.com/ionambrinoc/practicals
4355c34501377749263c902512493c34d9e3e036
7784d8be4152fd374412f7287a3f004b0dd74e07
a171d966286b6107898b524ffea1eb19e85639ae
refs/heads/master
2016-09-06T06:27:39.353347
2015-03-02T17:14:46
2015-03-02T17:14:46
30,879,866
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.461457222700119, "alphanum_fraction": 0.4751847982406616, "avg_line_length": 36.880001068115234, "blob_id": "965d86fefd2ef61fa100344f351f1ed29df275b1", "content_id": "832a61ee7668c0702a2ebbc243e9fada499fde2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 947, "license_type": "no_license", "max_line_length": 103, "num_lines": 25, "path": "/prac1.py", "repo_name": "ionambrinoc/practicals", "src_encoding": "UTF-8", "text": "##############################ADVANCED SECURITY PRACTICAL ASSIGNMENT 1#################################\n###########################CRYPTOGRAPHY FOR PRIVACY####HILARY TERM 2015################################\n\n#######################################################################################################\n\"\"\" PROTOCOL SPECIFICATION. \n\n[A knows a not b; B knows b not a; each has a random number r_a, r_b]\n\n1. A -> B : {m, m_a=m^a, n_a=m^a'}_B\t\t\n2. B -> A : {m_b=m^b, n_b =m^b'}_A\n[at this point, they both have M=m^(ab), N=m^(a'b') - 2xDiffie-Hellman up to here]\n3. A -> B: {N^r_a, M^r_a * N^s_a}_B\n4. B -> A: {N^r_b, M^r_b * N^s_b}_A\n[each checks that N^r_a * (M^r_a * N^s_a)^(-1) = N\n\n\nProtocol advantages: 2 parties only, minimal number of messages, minimal information leakage\nForward secrecy: if the encryption is broken, the only thing that can leak is the hash in (3).\n\n\n\n\t\t\t\t \t\t\t\t\t\t\t\t\"\"\"\n\nfrom Crypto import Random\nprint(\"boss\")\n" }, { "alpha_fraction": 0.6169650554656982, "alphanum_fraction": 0.6331083178520203, "avg_line_length": 40.54878234863281, "blob_id": "c40f92c13f9360ece3e9909d8d6ea6fd50945f2f", "content_id": "9061f7266b9763a1972f1219d654ff84290bd37f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10221, "license_type": "no_license", "max_line_length": 102, "num_lines": 246, "path": "/report.py", "repo_name": "ionambrinoc/practicals", "src_encoding": "UTF-8", "text": "##############################ADVANCED SECURITY PRACTICAL ASSIGNMENT 1###############################\n###########################CRYPTOGRAPHY FOR PRIVACY####HILARY TERM 2015##############################\n\n\"\"\"PROTOCOL IDEA AND SPECIFICATION-------------------------------------------------------------------\n0. Sam -> Alice, Bob: prime p, u coprime with p\t\t --server prepares (double) D-H\n1. Alice -> Bob : u^r_a, u^r'_a\t\t\t\t --fresh random numbers r_a,r'_a\n2. Bob -> Alice : u^r_b, u^r'_b --fresh random numbers r_b,r'_b\n\n [both now know x=u^(r_ar_b), y=u^(r'_ar'_b); Alice knows x_a = x^H(s_a), Bob knows x_b = x^H(s_b)]\n [H is a hash function; communication is done through HTTP server Sam; we abstract away from this ]\n3. Alice -> Bob : y^r''_a\t\t\t\t\t --fresh random number r''_a\n4. Bob -> Alice : y^(-r''_b)\t\t\t\t --fresh random number r''_b\n\n [both now know z=y^(r''_a-r''_b) which will later be used in the check]\n\n5. Alice -> Bob : x_a \t* u^(r'_a)\t\t\t --relying on DiscreteLog Problem\n6. Bob -> Alice : x_b^(-1)* u^(-r'_b)\t\t\t --for nondisclosure\n7. Bob -> Alice : r'_b\n8. Alice -> Bob\t : r'_a\t\t\t\t\t --cross-disclose it\n\n [both form t=x_a* u^(r'_a)*x_b^(-1)* u^(-r'_b); then they check if t^(r'_ar'_b)==z <==>s_a==s_b ]\n [Alice additionally checks if Bob is lying: if u^(r'_b(10)) != u^(r'_b)(2), then he is! ]\n\nProtocol strengths: Alice can detect whether Bob has been dishonest; Bob commits to x_b at message 6,\n\t\t so he cannot lie when he sends it there and keep another true x_b for which he\n\t\t finds out the answer; what he can do is send Alice a fake random number at step 7;\n\t\t at which point Alice does the above check and finds out if he is being dishonest.\n\n\t\t Further, the information leaked is minimal: the only time the secret is sent over\n\t\t the network is at messages 5 and 6, at which point it is heavily hashed, so very\n\t\t little (if any) information about it is leaked.\n\n\t\t We can also implement this on top of SSL/TLS to ensure privacy and confidentiality\n\t\t of the messages, to provide security against a Dolev-Yao attacker. Note also the\n\t\t forward secrecy: due to hashing and the Discrete Log problem, an attacker can find\n\t\t out, at most, if the two values were equal, and not the values themselves.\n\n\t\t Finally, note that there are only 8 messages exchanged, an arguably small number.\n\nProof of work: t^(r'_ar'_b)=(x_ax_b^(-1))u^(r'_ar'_b(r''_ar''_b)) = 1 * z since s_a=s_b => x_a=x_b\"\"\"\n\n# I have run into implementation problems in the Python code, specifically in the transmission\n# of messages over TCP/IP, with failures occurring nondeterministically throughout the code.\n\n# Extra assumption: we assume that we are working over authenticated secure channels (eg TLS), \n# in order to simplify implementation (this is why we are not sending encrypted information).\n\n###SAMPLE CODE FOR SERVER PROCESS - \"ALICE\"#####(as server to simplify implementation)###############\n\nimport socket \t\t\t\t# note that Alice is one of the participants, the one who\nimport sys\t\t\t\t# does not invert numbers modulo p; she acts as a server\nfrom thread import *\t\t# for simplicity of implementation only, and this is not\n\t\t\t\t# necessary for the purposes of the (abstract) protocol.\n\nfrom Crypto.Util import number # generate random large prime (p in specification)\nprime = number.getPrime(512)\t # (first ingredient for Diffie-Hellman); all\np = prime\nu = number.getRandomInteger(128) # generate u coprime with p; Diffie-Hellman base\nimport fractions\t\t\t\t # (second ingredient for Diffie-Hellman)\nwhile fractions.gcd(u,prime)!=1:\n\tu = number.getRandomInteger(128)\n\nfrom Crypto.Util import number \t\t# generate fresh random numbers for \nrA = number.getRandomInteger(128)\t# use in protocol; Bob also does this step\nrAp = number.getRandomInteger(128)\nrApp= number.getRandomInteger(128)\nfrom Crypto.Hash import MD5\nh = MD5.new()\nsecret = 12345678\t\t\t\t#manually define secret; same to be done for Bob\nh.update(str(secret))\t\t\t\t#then hash secret using MD5\nHs = h.digest()\nprint \"Hash of secret: \", h.hexdigest()\nurA = (u^rA) %p \t\t\t#exponentiate for Diffie-Hellman\nurAp = (u^rAp)%p\nprint \"Generated \", hex(urA), hex(urAp)\n#cryptographic component generation now done.\n#from now on act as a socket server and just pass messages on\n\nHOST = '' \t\t\t# listen on all connections\nPORT = 4321\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nprint 'Socket created'\n\ntry:\t\t\t\t\t#Bind socket to local host and port\n s.bind((HOST, PORT))\nexcept socket.error , msg:\n print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]\n sys.exit()\nprint 'Socket bind complete'\n\ns.listen(10)\t\t\t\t#Start listening on socket\nprint 'Socket now listening'\n\n#Function for handling connections, to be used to create thread for Bob;\n#very simplified to make not a general socket server, but one that strictly\n#carries out required protocol with Bob.\ndef clientthread(conn):\n\tconn.sendall(str(prime))\t# message 0: pass Bob ingredients for Diffie-Hellman\n\tconn.sendall(str(u))\t\t# as strings (sendall does not take longs)\n\tprint 'sent ' + hex(p) + ' and '+ hex(u) +' as message 0'\n \n\n\tconn.sendall(str(urA))\t\t# message 1: two Diffie-Hellman messages.\n\tconn.sendall(str(urAp))\n\tprint 'sent '+ hex(urA) + ' and ' + hex(urAp) + ' as message 1'\n\n\turB = long(conn.recv(4096))\t# message 2: Bob's corresponding D-H messages.\n\turBp= long(conn.recv(4096)) # reconverted into (useful) longs.\n\tprint 'got '+ hex(urB) + ' and ' + hex(urBp) + ' as message 2'\n\n\tx = (urB ^ rA ) % p \t# x=u^(r_ar_b) mod p\n\ty = (urBp ^ rAp) % p \t# y = u^(r'_ar'_b) mod p\n\txa \t = (x^Hs) % p\t# x_a=x^H(s_a), known by Alice only\n\tyrppa = (y^rApp)\t % p # y^r''_a for fresh r''_a generated above \n\tprint 'computed' + str(x) +' and '+str(y)+' and '+str(xa)+' and '+str(yrppa) \n\tconn.sendall(str(yrppa)) # message 3\n\tprint 'sent '+str(yrppa)+' as message 3'\n\tyrppb = long(conn.recv(4096))# message 4, from Bob: y^(-r''_b)\n\tprint 'got '+str(yrppb)+' as message 4'\n\n\tz = yrppb^rApp\t\t\t % p # known by both, to be used later in the check.\n\taliceCheck = xa*(u^(rAp)) % p\n\tprint 'computed' + str(z) +' and '+str(aliceCheck)\n\n\tconn.sendall(str(aliceCheck)) # message 5, relying on hash and discrete \n\t\t\t\t\t# to ensure secret is not leaked; this is the\n\t\t\t\t\t# only place where a function of the secret is\n\t\t\t\t\t# actually transferred between Alice and Bob.\n\tprint 'sent '+str(aliceCheck)+' as message 5'\n\tbobCheck = long(conn.recv(4096)) # message 6, Bob's analogous to 5.\n\tprint 'got '+str(bobCheck)+' as message 6'\n\n\tt = aliceCheck * bobCheck % p\n\trBp = long(conn.recv(4096))\t\t# reverse message order; Bob discloses one of the \n\tif (u^rBp) % p != urBp:\n\t\tprint \"BOB IS LYING, DROPPING CONNECTION\"\n\t\ts.close()\t\t\t\t#and drop connection; otherwise...\n\tconn.sendall(str(rAp))\t\t\t# message 8; do the same as Bob\n\n\tif (t^(rAp * rBp)) % p == z:\n\t\tprint \"The secrets match!\"\n\telse: print \"The secrets don't match.\"\n\n \tconn.close()\t\t\t\t#come out of loop\nwhile 1:\t\t\t\t\t\t#now talk to Bob\n conn, addr = s.accept()\t\t#wait to accept connection; blocking call\n print 'Connection accepted'\n print 'Connected with ' + addr[0] + ':' + str(addr[1]) + 'as Bob'\n start_new_thread(clientthread ,(conn,))\ns.close()\n\n###SAMPLE CODE FOR ONE PROCESS - \"BOB\" (INVERTING)###(as client to simplify implementation)##########\n\nimport socket #for sockets\nimport sys #for exit\n \nfrom Crypto.Util import number # generate fresh random numbers for \nrB = number.getRandomInteger(128) # use in protocol; \nrBp = number.getRandomInteger(128)\nrBpp= number.getRandomInteger(128)\n\nfrom Crypto.Hash import MD5\nh = MD5.new()\nsecret = 12345678 #manually define secret; same to be done for Bob\nh.update(str(secret)) #then hash secret using MD5\nHs = h.digest()\nprint \"Hash of secret: \", h.hexdigest()\n\ntry:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nexcept socket.error:\n print 'Failed to create socket'\n sys.exit()\nprint 'Socket Created'\nhost = ''; #run everything on localhost\nport = 4321;\n \ntry:\n remote_ip = socket.gethostbyname( host ) \nexcept socket.gaierror:\n print 'Hostname could not be resolved. Exiting'\n sys.exit()\n \ns.connect((remote_ip , port))\t\t\t\t#Connect to remote server\nprint 'Socket Connected to ' + host + ' on ip ' + remote_ip\n \np = long(s.recv(4096))\t#receive Diffie-Hellman ingredients from server\nu = long(s.recv(4096))\t#message 0 in protocol spec.\nprint \"Received DH ingredients \" + hex(p) + ' and ' + hex(u)\n\nurB = u^rB%p #exponentiate for Diffie-Hellman\nurBp = u^rBp%p\nprint \"Generated \", hex(urB), hex(urBp)\n\nurA = long(s.recv(4096)) #receive message 1\nprint \"Received \"+hex(urA)\nurAp = long(s.recv(4096))\nprint \"Received \" + hex(urA) + \" and \" + urAp + \" as message 1\"\n\ntry : #send message 2\n s.sendall(str(urB))\nexcept socket.error:\n print 'Send failed'\n sys.exit()\ntry : \n s.sendall(str(urBp))\nexcept socket.error:\n print 'Send failed'\n sys.exit()\n\nx = (urA ^ rB ) % p # x=u^(r_ar_b) mod p\ny = (urAp ^ rBp) % p # y = u^(r'_ar'_b) mod p\nxb = (x^Hs) % p # x_b=H^H(s_b) known only by Bob\nyrppb = (y^rBpp) % p # y^r''_b for fresh r''_b generated above\n\nyrppa = long(s.recv(4096)) # receive message 3\ntry : #send message 4\n s.sendall(str(yrppb))\nexcept socket.error:\n print 'Send failed'\n sys.exit()\n\nz = yrppa^rBpp #known by both, to be used later in the check\nbobCheck = xb ^ (u^(rBp))\n\naliceCheck = long(s.recv(4096)) # message 5\ntry : #send message 6\n s.sendall(str(bobCheck))\nexcept socket.error:\n print 'Send failed'\n sys.exit()\n\nt = aliceCheck * bobCheck % p\ntry : #send message 7; disclose random\n s.sendall(str(rBp))\nexcept socket.error:\n print 'Send failed'\n sys.exit()\n\nrAp = long(s.recv(4096)) #message 8\n\nif (t^(rAp * rBp)) % p == z:\n print \"The secrets match!\"\nelse: print \"The secrets don't match.\"\ns.close() #done\nprint urA, urAp, urB, urBp\n" }, { "alpha_fraction": 0.6435845494270325, "alphanum_fraction": 0.6594251990318298, "avg_line_length": 39.172725677490234, "blob_id": "f2307c0f28f33b5b4e9ccecc43fc8d0669892510", "content_id": "4afcae0285aa3fbdc9c1a678a20f2bffca725cf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4419, "license_type": "no_license", "max_line_length": 92, "num_lines": 110, "path": "/alice_server.py", "repo_name": "ionambrinoc/practicals", "src_encoding": "UTF-8", "text": "###SAMPLE CODE FOR SERVER PROCESS - \"ALICE\"#################################################\n\nimport socket \t\t\t\t# note that Alice is one of the participants, the one who\nimport sys\t\t\t\t\t# does not invert numbers modulo p; she acts as a server\nfrom thread import *\t\t# for simplicity of implementation only, and this is not\n\t\t\t\t\t\t\t# necessary for the purposes of the (abstract) protocol.\n\nfrom Crypto.Util import number # generate random large prime (p in specification)\nprime = number.getPrime(512)\t # (first ingredient for Diffie-Hellman); all\np = prime\n\nu = number.getRandomInteger(128) # generate u coprime with p; Diffie-Hellman base\nimport fractions\t\t\t\t # (second ingredient for Diffie-Hellman)\nwhile fractions.gcd(u,prime)!=1:\n\tu = number.getRandomInteger(128)\n\nfrom Crypto.Util import number \t\t# generate fresh random numbers for \nrA = number.getRandomInteger(128)\t# use in protocol; Bob also does this step\nrAp = number.getRandomInteger(128)\nrApp= number.getRandomInteger(128)\n\nfrom Crypto.Hash import MD5\nh = MD5.new()\nsecret = 12345678\t\t\t\t\t#manually define secret; same to be done for Bob\nh.update(str(secret))\t\t\t\t#then hash secret using MD5\nHs = h.digest()\nprint \"Hash of secret: \", h.hexdigest()\n\nurA = (u^rA) %p \t\t\t#exponentiate for Diffie-Hellman\nurAp = (u^rAp)%p\nprint \"Generated \", hex(urA), hex(urAp)\n\n#cryptographic component generation now done.\n#from now on act as a socket server and just pass messages on\n\nHOST = '' \t\t\t# listen on all connections\nPORT = 4321\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nprint 'Socket created'\n\ntry:\t\t\t\t\t#Bind socket to local host and port\n s.bind((HOST, PORT))\nexcept socket.error , msg:\n print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]\n sys.exit()\nprint 'Socket bind complete'\n\ns.listen(10)\t\t\t\t#Start listening on socket\nprint 'Socket now listening'\n\n#Function for handling connections, to be used to create thread for Bob;\n#very simplified to make not a general socket server, but one that strictly\n#carries out required protocol with Bob.\ndef clientthread(conn):\n\tconn.sendall(str(prime))\t# message 0: pass Bob ingredients for Diffie-Hellman\n\tconn.sendall(str(u))\t\t# as strings (sendall does not take longs)\n\tprint 'sent ' + hex(p) + ' and '+ hex(u) +' as message 0'\n \n\n\tconn.sendall(str(urA))\t\t# message 1: two Diffie-Hellman messages.\n\tconn.sendall(str(urAp))\n\tprint 'sent '+ hex(urA) + ' and ' + hex(urAp) + ' as message 1'\n\n\turB = long(conn.recv(4096))\t# message 2: Bob's corresponding D-H messages.\n\turBp= long(conn.recv(4096)) # reconverted into (useful) longs.\n\tprint 'got '+ hex(urB) + ' and ' + hex(urBp) + ' as message 2'\n\n\tx = (urB ^ rA ) % p \t# x=u^(r_ar_b) mod p\n\ty = (urBp ^ rAp) % p \t# y = u^(r'_ar'_b) mod p\n\txa \t = (x^Hs) % p\t# x_a=x^H(s_a), known by Alice only\n\tyrppa = (y^rApp)\t % p # y^r''_a for fresh r''_a generated above \n\tprint 'computed' + str(x) +' and '+str(y)+' and '+str(xa)+' and '+str(yrppa) \n\n\tconn.sendall(str(yrppa)) # message 3\n\tprint 'sent '+str(yrppa)+' as message 3'\n\tyrppb = long(conn.recv(4096))# message 4, from Bob: y^(-r''_b)\n\tprint 'got '+str(yrppb)+' as message 4'\n\n\tz = yrppb^rApp\t\t\t % p # known by both, to be used later in the check.\n\taliceCheck = xa*(u^(rAp)) % p\n\tprint 'computed' + str(z) +' and '+str(aliceCheck)\n\n\tconn.sendall(str(aliceCheck)) # message 5, relying on hash and discrete \n\t\t\t\t\t\t\t\t\t# to ensure secret is not leaked; this is the\n\t\t\t\t\t\t\t\t\t# only place where a function of the secret is\n\t\t\t\t\t\t\t\t\t# actually transferred between Alice and Bob.\n\tprint 'sent '+str(aliceCheck)+' as message 5'\n\tbobCheck = long(conn.recv(4096)) # message 6, Bob's analogous to 5.\n\tprint 'got '+str(bobCheck)+' as message 6'\n\n\tt = aliceCheck * bobCheck % p\n\n\trBp = long(conn.recv(4096))\t\t# reverse message order; Bob discloses one of the \n\tif (u^rBp) % p != urBp:\n\t\tprint \"BOB IS LYING, DROPPING CONNECTION\"\n\t\ts.close()\t\t\t\t\t#and drop connection; otherwise...\n\tconn.sendall(str(rAp))\t\t\t# message 8; do the same as Bob\n\n\tif (t^(rAp * rBp)) % p == z:\n\t\tprint \"The secrets match!\"\n\telse: print \"The secrets don't match.\"\n\n \tconn.close()\t\t\t\t#come out of loop\n \nwhile 1:\t\t\t\t\t\t#now talk to Bob\n conn, addr = s.accept()\t\t#wait to accept connection; blocking call\n print 'Connection accepted'\n print 'Connected with ' + addr[0] + ':' + str(addr[1]) + 'as Bob'\n start_new_thread(clientthread ,(conn,))\ns.close()\n" }, { "alpha_fraction": 0.6567436456680298, "alphanum_fraction": 0.6840826272964478, "avg_line_length": 23.92424201965332, "blob_id": "fe2b40a93bb5de7f664a2b5ae20663fa99da138e", "content_id": "5af1027f648f18021de236bbd270f54c627558d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1646, "license_type": "no_license", "max_line_length": 98, "num_lines": 66, "path": "/alice.py", "repo_name": "ionambrinoc/practicals", "src_encoding": "UTF-8", "text": "###SAMPLE CODE FOR ONE PROCESS - \"ALICE\" (NON-INVERTING)##########################################\n\nimport socket #for sockets\nimport sys #for exit\n \n# generate fresh random numbers for use in protocol:\nfrom Crypto.Util import number\nrA = number.getRandomInteger(128)\nrAp = number.getRandomInteger(128)\nrApp= number.getRandomInteger(128)\n\nfrom Crypto.Hash import MD5\nh = MD5.new()\nsecret = 12345678\t\t#manually define secret\nh.update(str(secret))\t\t#hash secret using MD5\nHs = h.digest()\nprint Hs\n\n#PKBob = \n#SK = \n\ntry:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nexcept socket.error:\n print 'Failed to create socket'\n sys.exit()\nprint 'Socket Created'\nhost = '127.0.0.1'; #run everything on localhost\nport = 4322;\n \ntry:\n remote_ip = socket.gethostbyname( host ) \nexcept socket.gaierror:\n #could not resolve\n print 'Hostname could not be resolved. Exiting'\n sys.exit()\n \ns.connect((remote_ip , port))\t\t\t\t#Connect to remote server\nprint 'Socket Connected to ' + host + ' on ip ' + remote_ip\n \n#Now receive data\np = long(s.recv(512))\t#receive Diffie-Hellman ingredients from server\nu = long(s.recv(128))\t#message 0 in protocol spec.\nprint(\"Received DH ingredients\")\n\n#Send identification to server\nmessage = \"ALICE\" \ntry :\n #Set the whole string\n s.sendall(message)\nexcept socket.error:\n #Send failed\n print 'Send failed'\n sys.exit()\nprint 'Identification sent successfully'\n\nurA = u^rA%p\nurAp = u^rAp%p\nprint \"Generated \", urA, urAp\n\ns.sendall(str(urA))\t\t#send message 1\ns.sendall(str(urAp))\t\nurB = long(s.recv(128)) \t#receive message 2\nurBp = long(s.recv(128))\n\nprint urA, urAp, urB, urBp\n\n" }, { "alpha_fraction": 0.6370558142662048, "alphanum_fraction": 0.6568527817726135, "avg_line_length": 28.84848403930664, "blob_id": "0c3226f8faaf109bc8a8e41127d2570ecd07295e", "content_id": "5c578e01bc3272c126dd72a7173f427dfa22666a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1970, "license_type": "no_license", "max_line_length": 102, "num_lines": 66, "path": "/sam.py", "repo_name": "ionambrinoc/practicals", "src_encoding": "UTF-8", "text": "###SAMPLE CODE FOR SERVER PROCESS - \"SAM\"#############################################################\n\nimport socket\nimport sys\nfrom thread import *\n\n#generate random large prime (p in specification)\nfrom Crypto.Util import number\nprime = number.getPrime(512)\n\n#generate u coprime with p; Diffie-Hellman base\nu = number.getRandomInteger(128)\nimport fractions\nwhile fractions.gcd(u,prime)!=1:\n\tu = number.getRandomInteger(128)\nprint 'Crypto done.'\n\n#from now on act as a socket server and just pass messages on\n \nHOST = '' \t\t\t# listen on all connections\nPORT = 4321\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nprint 'Socket created'\n\ntry:\t\t\t\t\t#Bind socket to local host and port\n s.bind((HOST, PORT))\nexcept socket.error , msg:\n print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]\n sys.exit()\nprint 'Socket bind complete'\n\ns.listen(10)\t\t\t\t#Start listening on socket\nprint 'Socket now listening'\n\n#Function for handling connections. This will be used to create threads\ndef clientthread(conn):\n while True:\t\t\t\t#infinite loop so that function does \n \t\t\t\t#not terminate and thread does not end.\n\tconn.sendall(str(prime))\t#start by passing Diffie-Hellman ingredients\n\tconn.sendall(str(u))\t\t#as strings (message 0 in protocol spec)\n #Receiving from client\n\tname = conn.recv(128)\t\t#client identification\n\tif name==\"ALICE\":\n\t\turA = conn.recv(128)\t#message 1\n\t\turAp= conn.recv(128)\n\t\tconn.sendall(urB)\n\t\tconn.sendall(urBp)\n\t\t\t\t\n\tif name==\"BOB\":\n\t\turB = conn.recv(128)\t#message 2\n\t\turBp= conn.recv(128)\n\t\tconn.sendall(urA)\n\t\tconn.sendall(urAp)\n\t\t\n # reply = 'OK...' + data\n # if not data:\n # break \n # conn.sendall(reply) \n conn.close()\t\t\t#come out of loop\n \nwhile 1:\t\t\t\t#now keep talking to clients\n conn, addr = s.accept()\t\t#wait to accept connection; blocking call\n print 'Connected with ' + addr[0] + ':' + str(addr[1])\n start_new_thread(clientthread ,(conn,))\n\ns.close()\n" }, { "alpha_fraction": 0.5807814002037048, "alphanum_fraction": 0.6026046872138977, "avg_line_length": 28.905263900756836, "blob_id": "6678b54ea94f8d555f707eba6a06832faab86df2", "content_id": "3eedaddd9094ecaaba4397c478f36df612286c53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2841, "license_type": "no_license", "max_line_length": 92, "num_lines": 95, "path": "/bob.py", "repo_name": "ionambrinoc/practicals", "src_encoding": "UTF-8", "text": "###SAMPLE CODE FOR ONE PROCESS - \"BOB\" (INVERTING)##########################################\n\nimport socket #for sockets\nimport sys #for exit\n \nfrom Crypto.Util import number # generate fresh random numbers for \nrB = number.getRandomInteger(128) # use in protocol; \nrBp = number.getRandomInteger(128)\nrBpp= number.getRandomInteger(128)\n\nfrom Crypto.Hash import MD5\nh = MD5.new()\nsecret = 12345678 #manually define secret; same to be done for Bob\nh.update(str(secret)) #then hash secret using MD5\nHs = h.digest()\nprint \"Hash of secret: \", h.hexdigest()\n\ntry:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nexcept socket.error:\n print 'Failed to create socket'\n sys.exit()\nprint 'Socket Created'\nhost = ''; #run everything on localhost\nport = 4321;\n \ntry:\n remote_ip = socket.gethostbyname( host ) \nexcept socket.gaierror:\n print 'Hostname could not be resolved. Exiting'\n sys.exit()\n \ns.connect((remote_ip , port))\t\t\t\t#Connect to remote server\nprint 'Socket Connected to ' + host + ' on ip ' + remote_ip\n \np = long(s.recv(4096))\t#receive Diffie-Hellman ingredients from server\nu = long(s.recv(4096))\t#message 0 in protocol spec.\nprint \"Received DH ingredients \" + hex(p) + ' and ' + hex(u)\n\nurB = u^rB%p #exponentiate for Diffie-Hellman\nurBp = u^rBp%p\nprint \"Generated \", hex(urB), hex(urBp)\n\nurA = long(s.recv(4096)) #receive message 1\nprint \"Received \"+hex(urA)\nurAp = long(s.recv(4096))\nprint \"Received \" + hex(urA) + \" and \" + urAp + \" as message 1\"\n\ntry : #send message 2\n s.sendall(str(urB))\nexcept socket.error:\n print 'Send failed'\n sys.exit()\ntry : \n s.sendall(str(urBp))\nexcept socket.error:\n print 'Send failed'\n sys.exit()\n\nx = (urA ^ rB ) % p # x=u^(r_ar_b) mod p\ny = (urAp ^ rBp) % p # y = u^(r'_ar'_b) mod p\nxb = (x^Hs) % p # x_b=H^H(s_b) known only by Bob\nyrppb = (y^rBpp) % p # y^r''_b for fresh r''_b generated above\n\nyrppa = long(s.recv(4096)) # receive message 3\ntry : #send message 4\n s.sendall(str(yrppb))\nexcept socket.error:\n print 'Send failed'\n sys.exit()\n\nz = yrppa^rBpp #known by both, to be used later in the check\nbobCheck = xb ^ (u^(rBp))\n\naliceCheck = long(s.recv(4096)) # message 5\ntry : #send message 6\n s.sendall(str(bobCheck))\nexcept socket.error:\n print 'Send failed'\n sys.exit()\n\nt = aliceCheck * bobCheck % p\ntry : #send message 7; disclose random\n s.sendall(str(rBp))\nexcept socket.error:\n print 'Send failed'\n sys.exit()\n\nrAp = long(s.recv(4096)) #message 8\n\nif (t^(rAp * rBp)) % p == z:\n print \"The secrets match!\"\nelse: print \"The secrets don't match.\"\ns.close() #done\nprint urA, urAp, urB, urBp\n" } ]
6
belong112/collatest
https://github.com/belong112/collatest
dd413120da791125f05b99cb19c8ffb81dc2ecd6
b2c7a8f4bd5f6c34cbd62b53e1567cee34c84f1b
056408b8ba3495aec118e21a186c28a01acdbd42
refs/heads/master
2020-04-09T18:38:25.737393
2018-12-27T16:11:32
2018-12-27T16:11:32
160,518,680
0
1
null
2018-12-05T12:59:18
2018-12-11T07:36:55
2018-12-11T07:37:32
JavaScript
[ { "alpha_fraction": 0.6464480757713318, "alphanum_fraction": 0.6464480757713318, "avg_line_length": 35.619998931884766, "blob_id": "bce07fc028b89604d6365dad049883008888f1f9", "content_id": "4a288f6ba57d4edf97c7bf4ffba8d17ca87f179c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1830, "license_type": "no_license", "max_line_length": 92, "num_lines": 50, "path": "/accounts/views.py", "repo_name": "belong112/collatest", "src_encoding": "UTF-8", "text": "from django.shortcuts import render,redirect\nfrom django.http import HttpResponse\nfrom django.contrib.auth.forms import UserCreationForm,AuthenticationForm\nfrom django.contrib.auth import login,logout\nfrom django.contrib.auth.models import User\nfrom attendanceSheet.models import attendanceSheet,date_course\n# Create your views here.\n\ndef signup(request):\n if request.method=='POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n username=request.POST['username']\n form.save()\n #create new attendance record for new user\n courseLst=date_course.objects.all()\n user=User.objects.get(username=username)\n for course in courseLst:\n attendanceSheet.objects.create(user=user,course=course)\n \n #return HttpResponse(user)\n return redirect('/collaAdmin/teacherpage ') #remeber the slash at the very front\n else:\n form=UserCreationForm()\n return render(request,'accounts/signup.html',locals())\n\ndef login_views(request,timecode):\n if request.method=='POST':\n form=AuthenticationForm(data=request.POST)\n if form.is_valid():\n #login the user\n user=form.get_user()\n login(request,user)\n if request.user.is_authenticated:\n if request.user.is_superuser:\n return redirect('/collaAdmin/teacherpage')\n else:\n return redirect('/collaAdmin/studentpage')\n else:\n return HttpResponse(\"/\")\n else:\n form=AuthenticationForm\n return render(request,'accounts/login.html',locals())\n\ndef logout_views(request):\n logout(request)\n return redirect('/')\n\ndef googleLog(request):\n return render(request,'accounts/googleLog.html')" }, { "alpha_fraction": 0.3499338924884796, "alphanum_fraction": 0.35522255301475525, "avg_line_length": 33.83076858520508, "blob_id": "5087dc61085538dc5343068a9de68ea8511ca0e0", "content_id": "ac7b3d42bf1fa1d1054585346e82cd88881c6ab1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2397, "license_type": "no_license", "max_line_length": 79, "num_lines": 65, "path": "/attendanceSheet/templates/leaveApprove.html", "repo_name": "belong112/collatest", "src_encoding": "UTF-8", "text": "\n {% extends 'baseLayout.html' %}\n\n {% block someFcn %}\n <h1>待審核請假申請</h1>\n <table align = \"center\" width = \"100%\" border=\"1px\">\n <tr>\n <th>申請序號</th>\n <th>申請人</th>\n <th>申請日期</th>\n <th>課堂名稱</th>\n <th>上課日期</th>\n <th>請假事由</th>\n <th>審核</th>\n </tr>\n\n {% for aplc in aplcLst %}\n <tr>\n <td>{{aplc.id}}</td>\n <td>{{aplc.user.username}}</td>\n <td>{{aplc.applicateDate}}</td>\n <td>{{aplc.course.course_name}}</td>\n <td>{{aplc.course.date}}</td>\n <td>{{aplc.description}}</td> \n <td>\n <form action='' method='post'>\n {% csrf_token %}\n <input type=hidden name='targetID' value='{{aplc.id}}'>\n <input type=submit name='result' value='approve'>\n <input type=submit name='result' value='deny'>\n </form>\n </td>\n </tr>\n {% endfor %}\n </table>\n <br>\n <h1>已審核請假申請</h1>\n <table align = \"center\" width = \"100%\" style=\"border-width: 1px;\">\n <tr>\n <th>申請序號</th>\n <th>申請人</th>\n <th>申請日期</th>\n <th>課堂名稱</th>\n <th>上課日期</th>\n <th>請假事由</th>\n <th>審核</th>\n </tr>\n {% for aplc in aplcLST_approved %}\n <tr>\n <td>{{aplc.id}}</td>\n <td>{{aplc.user.username}}</td>\n <td>{{aplc.applicateDate}}</td>\n <td>{{aplc.course.course_name}}</td>\n <td>{{aplc.course.date}}</td>\n <td>{{aplc.description}}</td> \n <td>\n <form action='' method='post'>\n {% csrf_token %}\n <input type=hidden name='targetID' value='{{aplc.id}}'>\n <input type=submit name='regret' value='regret'>\n </form>\n </td>\n </tr>\n {% endfor %}\n </table>\n {% endblock %}\n" }, { "alpha_fraction": 0.5841430425643921, "alphanum_fraction": 0.5934706330299377, "avg_line_length": 42.61016845703125, "blob_id": "96348cc349f7899bd467b73d274c7f0a2574212c", "content_id": "9ddcacbfece71803bf0bfb63173f060c35e0de3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2573, "license_type": "no_license", "max_line_length": 184, "num_lines": 59, "path": "/attendanceSheet/migrations/0001_initial.py", "repo_name": "belong112/collatest", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-12-07 02:07\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 ('auth', '0009_alter_user_last_name_max_length'),\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='attendanceSheet',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('presence', models.BooleanField(default=False)),\n ('absence', models.BooleanField(default=True)),\n ('late', models.BooleanField(default=False)),\n ('personal_leave', models.BooleanField(default=False)),\n ],\n ),\n migrations.CreateModel(\n name='date_course',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('date', models.CharField(default='', max_length=11)),\n ('course_name', models.CharField(default='course0', max_length=50)),\n ('memo', models.TextField(default='')),\n ('is_rollcallNow', models.BooleanField(default=False)),\n ],\n ),\n migrations.CreateModel(\n name='userProfile',\n fields=[\n ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='userprofile', serialize=False, to=settings.AUTH_USER_MODEL)),\n ('isIntern', models.BooleanField(default=False)),\n ('isJunior', models.BooleanField(default=False)),\n ('isSenior', models.BooleanField(default=False)),\n ('isFamily', models.BooleanField(default=True)),\n ('isMentor', models.BooleanField(default=False)),\n ],\n ),\n migrations.AddField(\n model_name='attendancesheet',\n name='course',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='atdSummary', to='attendanceSheet.date_course'),\n ),\n migrations.AddField(\n model_name='attendancesheet',\n name='user',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='attendanceSheet', to=settings.AUTH_USER_MODEL),\n ),\n ]\n" }, { "alpha_fraction": 0.7883211970329285, "alphanum_fraction": 0.7883211970329285, "avg_line_length": 36.09090805053711, "blob_id": "5b4c8e3c679ad8b1aca22b8975217215c4363576", "content_id": "b0fd35d29b2497657a2a3bda318fb83d0f6bb2fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 419, "license_type": "no_license", "max_line_length": 63, "num_lines": 11, "path": "/collaAttendance/views.py", "repo_name": "belong112/collatest", "src_encoding": "UTF-8", "text": "from django.shortcuts import render,redirect # 加入 redirect 套件\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib import auth,contenttypes\nfrom attendanceSheet.models import date_course\n\ndef homepage(request):\n\t\treturn render (request, \"homepage.html\")\n\t\ndef rollcall(request):\n\tcourseLst = date_course.objects.order_by('date')\n\treturn render (request, \"rollcall.html\",locals())\n\n\n\n" }, { "alpha_fraction": 0.658815860748291, "alphanum_fraction": 0.6612882018089294, "avg_line_length": 39.661376953125, "blob_id": "d4d265eb70105d8c5504c21a4c5d6233a59c9caa", "content_id": "34a56513ee1c51fdb32c26770910eaf10f6b8901", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7719, "license_type": "no_license", "max_line_length": 142, "num_lines": 189, "path": "/attendanceSheet/views.py", "repo_name": "belong112/collatest", "src_encoding": "UTF-8", "text": "from django.shortcuts import render,redirect\nfrom . models import userProfile,attendanceSheet,date_course,leaveApplication\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponse\nfrom datetime import datetime\nfrom datetime import date\nimport pytz\n\n# Create your views here.\n\ndef userProfiles_views(request):\n allUsers=userProfile.objects.all()\n\n if (request.method==\"hold on a second\"):\n #do something searched\n finalPresent=allUsers[0]\n else:\n finalPresent=allUsers\n\n context = {'finalPresent':finalPresent}\n return render(request,'userProfiles_tepl.html',context=context)\n\ndef userAttendance_views(request):\n userLst=User.objects.all()\n if request.method=='POST':\n if request.POST['targetUser']!='':\n userLst=User.objects.filter(username__contains=request.POST['targetUser'])\n\n courseLst=date_course.objects.order_by('date')\n atdDict=dict()\n\n for users in userLst:\n atdDict[users.username]=[]\n for course in courseLst:\n atdDict[users.username].append(users.attendanceSheet.order_by('-id').get(course=course).status())\n \n return render(request,'userAtd_tepl.html',locals())\n\ndef sign(request,time):\n time_copy = time\n c = time_copy%10\n time_copy /= 10\n s = time_copy%100\n m = time_copy/100\n m2 = datetime.now().strftime(\"%M\")\n s2 = datetime.now().strftime(\"%S\")\n delta_s = (int(m2)-m)*60 + int(s2)-s\n\n if delta_s > 30:\n return HttpResponse('u are yoo late hahaha')\n else:\n if request.user.is_authenticated:\n username=request.user.username\n currentUser=User.objects.get(username=username)\n today=datetime.now().strftime('%Y/%m/%d')\n currenCourse=date_course.objects.get(course_name = \"course \"+str(c))\n\n attendanceSheet.objects.filter(user=currentUser,course=currenCourse).update(presence=True,absence=False)\n return HttpResponse('succesfully signUp')\n \n return redirect('/accounts/login/'+str(time))\n \n\ndef teacherpage(request):\n return render(request,'teacherpage.html')\n\ndef addCourse(request):\n if request.method==\"POST\":\n courseDate=request.POST['course_date']\n courseName=request.POST['course_name']\n courseDescription=request.POST['course_description']\n date_course.objects.create(date=courseDate,course_name=courseName,memo=courseDescription,is_rollcallNow=False)\n\n #幫固有的使用者創建新課堂的出席紀錄\n userLst=User.objects.all()\n newCourse=date_course.objects.get(course_name=courseName)\n for user in userLst:\n attendanceSheet.objects.create(user=user,course=newCourse)\n return redirect('/collaAdmin/userAttendance')\n else:\n return render(request,'addCourse.html',locals())\n\ndef manageCourse(request):\n if request.user.is_superuser:\n courseLst=date_course.objects.order_by('date')\n return render(request,'manageCourse.html',locals())\n return redirect('/')\n\ndef modifyCourse(request):\n if request.method=='GET':\n targetName=request.GET['targetName']\n targetDate=date_course.objects.get(course_name=targetName).date\n targetMemo=date_course.objects.get(course_name=targetName).memo\n return render(request,'modifyCourse.html',locals())\n \n elif request.method=='POST':\n originName=request.POST['targetCourse']\n newName=request.POST['course_name']\n newDate=request.POST['course_date']\n newMemo=request.POST['course_description']\n targetCourse=date_course.objects.filter(course_name=originName)\n if newMemo=='':\n newMemo=date_course.objects.get(course_name=originName).memo\n test=newName+newDate+newMemo+originName\n\n targetCourse.update(date=newDate)\n targetCourse.update(memo=newMemo)\n targetCourse.update(course_name=newName)\n return redirect('/collaAdmin/manageCourse')\n\ndef studentpage(request):\n return render(request,'studentpage.html',locals())\n\ndef leaveApplication_view(request):\n if request.method=='POST':\n if 'application' in request.POST:\n \n targetName=request.POST['targetCourse']\n targetCourse=date_course.objects.get(course_name=targetName)\n description = request.POST['description']\n \n tz=pytz.timezone('Asia/Taipei')\n applicateDate = datetime.now(tz).strftime('%Y/%m/%d')\n\n leaveApplication.objects.create(user=request.user,\n course=targetCourse,\n description=description,\n applicateDate=applicateDate)\n return redirect('/collaAdmin/personalAtd')\n\n\n courseNameLst=[]\n for course in date_course.objects.order_by('date'):\n courseNameLst.append(course.course_name)\n return render(request,'leaveApplication.html',locals())\n\ndef personalAtd(request):\n querySet=date_course.objects.order_by('date')\n tableRow=[]\n temp=[]\n if request.method=='POST':\n if request.POST['targetCourse']!='':\n querySet=date_course.objects.filter(course_name__contains=request.POST['targetCourse'])\n\n for course in querySet:\n temp.append(course.course_name)\n temp.append(course.date)\n temp.append(course.memo)\n temp.append(attendanceSheet.objects.get(user=request.user,course=course).status())\n tableRow.append(temp)\n temp=[]\n \n leaveAplc_query=leaveApplication.objects.filter(user=request.user)\n leaveAplc=[]\n for aplc in leaveAplc_query:\n temp.append(aplc.applicateDate)\n temp.append(aplc.course.course_name)\n temp.append(aplc.course.date)\n temp.append(aplc.description)\n temp.append(aplc.status())\n leaveAplc.append(temp)\n temp=[]\n\n\n return render(request, 'personalAtd.html',locals())\n\ndef leaveApprove(request):\n if request.user.is_superuser:\n lvAplc=[]\n temp=[]\n aplcLst = leaveApplication.objects.order_by('applicateDate').filter(under_review=True) \n aplcLST_approved = leaveApplication.objects.order_by('applicateDate').filter(under_review=False)\n if request.method==\"POST\":\n if 'result' in request.POST:\n leaveApplication.objects.filter(id=int(request.POST['targetID'])).update(under_review=False)\n targetCourse=leaveApplication.objects.get(id=int(request.POST['targetID'])).course\n targetUser=leaveApplication.objects.get(id=int(request.POST['targetID'])).user\n if request.POST['result']=='approve':\n leaveApplication.objects.filter(id=int(request.POST['targetID'])).update(is_approved=True,is_denied=False)\n attendanceSheet.objects.filter(user=targetUser, course=targetCourse).update(absence=False, personal_leave=True)\n else:\n leaveApplication.objects.filter(id=int(request.POST['targetID'])).update(is_denied=True,is_approved=False)\n elif 'regret' in request.POST:\n targetCourse=leaveApplication.objects.get(id=int(request.POST['targetID'])).course\n targetUser=leaveApplication.objects.get(id=int(request.POST['targetID'])).user\n leaveApplication.objects.filter(id=int(request.POST['targetID'])).update(under_review=True, is_approved=False,is_denied=False)\n attendanceSheet.objects.filter(user=targetUser, course=targetCourse).update(absence=True, personal_leave=False)\n return render(request, 'leaveApprove.html',locals())\n return redirect('/')\n" }, { "alpha_fraction": 0.7904762029647827, "alphanum_fraction": 0.7904762029647827, "avg_line_length": 20, "blob_id": "61dbfc690f43017bd9b313fb2001723b69573020", "content_id": "3d77c62d218a06bb14a9e06e5358128d303f2d8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 105, "license_type": "no_license", "max_line_length": 39, "num_lines": 5, "path": "/attendanceSheet/apps.py", "repo_name": "belong112/collatest", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass AttendancesheetConfig(AppConfig):\n name = 'attendanceSheet'\n" }, { "alpha_fraction": 0.6431870460510254, "alphanum_fraction": 0.6431870460510254, "avg_line_length": 38.40909194946289, "blob_id": "6ac5c2beda2545fcb22bb365d0da8dc7c9871734", "content_id": "e0aa322815d0f1f3c817e9eeb791ae72718bf6cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 866, "license_type": "no_license", "max_line_length": 79, "num_lines": 22, "path": "/attendanceSheet/urls.py", "repo_name": "belong112/collatest", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom . import views\nfrom django.urls import path\n\napp_name = 'collaAdmin'\n#name the app\n\nurlpatterns=[\n url(r'^userProfile/$',views.userProfiles_views,name='uerProfile'),\n url(r'^userAttendance/$',views.userAttendance_views,name='userAtd'),\n # url(r'^sign',views.sign,name='sign'),\n path('sign/<int:time>',views.sign,name = 'sign'),\n url(r'^teacherpage',views.teacherpage,name='teacherpage'),\n url(r'^addCourse',views.addCourse,name='addCourse'),\n url(r'^manageCourse',views.manageCourse),\n url(r'^modifyCourse',views.modifyCourse),\n url(r'^leaveApprove',views.leaveApprove),\n #--------------------------------------------------------------------------\n url(r'^studentpage$',views.studentpage),\n url(r'^leaveApplication$',views.leaveApplication_view),\n url(r'^personalAtd',views.personalAtd),\n]" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7647058963775635, "avg_line_length": 10.166666984558105, "blob_id": "9dbc9ee173f0b17147faca0762c9de4331df1ad2", "content_id": "e4a6df0bf394fe93c7c01007f79bdbc9ae62254c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 84, "license_type": "no_license", "max_line_length": 33, "num_lines": 6, "path": "/README.md", "repo_name": "belong112/collatest", "src_encoding": "UTF-8", "text": "# collatest\nhttps://colla-atd2.herokuapp.com/\n\naddCoutse\n\n新增增加課程頁面\n\n" }, { "alpha_fraction": 0.6314460635185242, "alphanum_fraction": 0.6339704394340515, "avg_line_length": 27.597938537597656, "blob_id": "d0a393ca9920b578e63f621fbc786e10fd2529cc", "content_id": "4e457ef108b491bd046bf38c8f1779478880efea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2787, "license_type": "no_license", "max_line_length": 67, "num_lines": 97, "path": "/attendanceSheet/models.py", "repo_name": "belong112/collatest", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.conf import settings\n\n# Create your models here.\nclass date_course(models.Model):\n date = models.CharField(max_length=11,default='')\n # date of the course\n course_name = models.CharField(max_length=50,default='course0')\n # name of the course\n memo = models.TextField(default='')\n is_rollcallNow=models.BooleanField(default=False)\n\n def __str__(self):\n course_str = self.course_name + ':' + self.memo\n return course_str\n\nclass userProfile(models.Model):\n user = models.OneToOneField(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name='userprofile',\n primary_key=True\n )\n\n isIntern = models.BooleanField(default=False)\n isJunior = models.BooleanField(default=False)\n isSenior = models.BooleanField(default=False)\n isFamily = models.BooleanField(default=True)\n isMentor = models.BooleanField(default=False)\n\nclass attendanceSheet(models.Model):\n user=models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name='attendanceSheet',\n null=True,\n blank=True\n )\n \n course = models.ForeignKey(\n date_course,\n on_delete=models.CASCADE,\n related_name='atdSummary',\n null=True,\n blank=True\n )\n\n presence = models.BooleanField(default=False)\n absence = models.BooleanField(default=True)\n late = models.BooleanField(default=False)\n personal_leave = models.BooleanField(default=False)\n\n def status(self):\n if self.presence:\n return 'presence'\n elif self.absence:\n return 'absence'\n elif self.late: \n return 'late'\n elif self.personal_leave:\n return 'personal leave'\n else:\n return 'fuck you'\n\nclass leaveApplication(models.Model):\n user=models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name='leaveApplications',\n null=True,\n blank=True,\n )\n\n course = models.ForeignKey(\n date_course,\n on_delete=models.CASCADE,\n related_name='atdSummary_leave',\n null=True,\n blank=True\n )\n\n description = models.TextField(default='')\n applicateDate = models.CharField(max_length=11,default='')\n under_review = models.BooleanField(default=True)\n is_approved = models.BooleanField(default=False)\n is_denied = models.BooleanField(default=False)\n\n def status(self):\n if self.under_review:\n return '審核中'\n elif self.is_approved:\n return '通過'\n elif self.is_denied:\n return '拒絕'\n else:\n return 'fuck you'" }, { "alpha_fraction": 0.6840795874595642, "alphanum_fraction": 0.6840795874595642, "avg_line_length": 27.785715103149414, "blob_id": "205033089c97ed235c4af4a9956530721719da13", "content_id": "721e0a14a14d3813c238591a4e106d5611cbb7ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 402, "license_type": "no_license", "max_line_length": 70, "num_lines": 14, "path": "/accounts/urls.py", "repo_name": "belong112/collatest", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom django.urls import path\nfrom . import views\n\napp_name = 'accounts'\n#name the app\n\nurlpatterns=[\n url(r'^signup/$',views.signup,name='signup'),\n #url(r'^login/$',views.login_views,name='login_student'),\n path('login/<int:timecode>',views.login_views,name='login_views'),\n url(r'^logout/$',views.logout_views),\n url(r'^googleLog/$',views.googleLog),\n]" } ]
10
xergio/redtorrent
https://github.com/xergio/redtorrent
49a92bd78ad8f07d1ddb39ad2b525e06800100ac
5d7b78b3882be69cdbdac2013b7144e3402967ba
1c6064b65414fa2f8cc38a025888be13fc68fb71
refs/heads/master
2021-01-13T02:16:51.751560
2012-04-10T20:32:35
2012-04-10T20:32:35
3,948,138
4
0
null
null
null
null
null
[ { "alpha_fraction": 0.5904718041419983, "alphanum_fraction": 0.6779661178588867, "avg_line_length": 24.822484970092773, "blob_id": "eab68843e77ec2c9de5f4d2b87457d260c1bd766", "content_id": "41f63a6391ecf4a5909c0d59f6bab9d252b6792f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4366, "license_type": "no_license", "max_line_length": 328, "num_lines": 169, "path": "/tracker/views.py", "repo_name": "xergio/redtorrent", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport django\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponse\nfrom tracker.models import AnnounceForm, ScrapeForm, Store\n\nimport sys\nimport socket\nimport bencode\nimport struct\nimport time\nimport redis\n\n\"\"\"\n\nhttp://bittorrent.org/beps/bep_0003.html\nhttp://wiki.theory.org/BitTorrentSpecification#Tracker_HTTP.2FHTTPS_Protocol\n\n/announce?\ninfo_hash=gK%91d%e0%ec%fc%c0G%c1%0a%9bD8%85%a9%99%88%27%da&\npeer_id=-TR2330-fnovv1t92c12&\nport=51413&\nuploaded=0&\ndownloaded=0&\nleft=0&\nnumwant=80&\nkey=6083d376&\ncompact=1&\nsupportcrypto=1&\nevent=started\n\n/scrape?\ninfo_hash=gK%91d%e0%ec%fc%c0G%c1%0a%9bD8%85%a9%99%88%27%da\n\n\nstart complete torrent\n[07/Apr/2012 08:55:26] \"GET /announce?info_hash=7%cc%08%1fG%60%a6%ab%05%1d%b8%d6%fa%d6%cd%2b%a1gl%98&peer_id=-TR2500-46xugddkkm12&port=51413&uploaded=0&downloaded=0&left=0&numwant=80&key=5085515f&compact=1&supportcrypto=1&event=started HTTP/1.1\" 200 25\n\nping complete torrent \n[07/Apr/2012 08:56:27] \"GET /announce?info_hash=7%cc%08%1fG%60%a6%ab%05%1d%b8%d6%fa%d6%cd%2b%a1gl%98&peer_id=-TR2500-46xugddkkm12&port=51413&uploaded=0&downloaded=0&left=0&numwant=80&key=5085515f&compact=1&supportcrypto=1 HTTP/1.1\" 200 25\n\n\nstart nuevo cliente\n[07/Apr/2012 08:56:01] \"GET /announce?info_hash=7%cc%08%1fG%60%a6%ab%05%1d%b8%d6%fa%d6%cd%2b%a1gl%98&peer_id=M7-2-2--%c9d%e2%b2T%85%f8%93%ce%d9%ac%1d&port=15644&uploaded=0&downloaded=0&left=733261824&corrupt=0&key=6C7ED1C1&event=started&numwant=200&compact=1&no_peer_id=1&ipv6=fe80%3a%3a21c%3ab3ff%3afec5%3aa4a1 HTTP/1.1\" 200 25\n\nping nuevo cliente\n[07/Apr/2012 08:57:02] \"GET /announce?info_hash=7%cc%08%1fG%60%a6%ab%05%1d%b8%d6%fa%d6%cd%2b%a1gl%98&peer_id=M7-2-2--%c9d%e2%b2T%85%f8%93%ce%d9%ac%1d&port=15644&uploaded=0&downloaded=0&left=733261824&corrupt=0&key=6C7ED1C1&numwant=200&compact=1&no_peer_id=1&ipv6=fe80%3a%3a21c%3ab3ff%3afec5%3aa4a1 HTTP/1.1\" 200 25\n\n\"\"\"\n\ndef announce(request):\n\tqs = request.GET.copy()\n\tqs.update({'ip': request.GET.get('ip') or request.META.get('REMOTE_ADDR')})\n\tann = AnnounceForm(qs.dict())\n\n\tif not ann.is_valid():\n\t\traise Exception(ann.errors)\n\n\tqs = ann.cleaned_data\n\tr = Store(host='localhost')\n\tr.set_info(qs['info_hash'], qs['peer_id'])\n\n\n\t# save ALL the params!\n\tr.save_peer(qs)\n\n\n\t# save ALL the states!\n\tif qs['event'] == 'completed':\n\t\tr.add_seeder()\n\t\tr.del_leecher()\n\n\telif qs['event'] == 'stopped':\n\t\tr.del_seeder()\n\t\tr.del_leecher()\n\t\tr.delete_peer()\n\n\telse:\n\t\tif qs['left'] == 0:\n\t\t\tr.add_seeder()\n\t\t\tr.del_leecher()\n\t\telse:\n\t\t\tr.add_seeder()\n\t\t\tr.add_leecher()\n\t\n\n\t# get ALL the peers!\n\tnmembers = r.len_seeders()\n\tif nmembers < qs['numwant']:\n\t\tpeer_ids = r.all_seeders()\n\telif nmembers > 0:\n\t\tpeer_ids = r.get_seeders(qs['numwant'])\n\telse:\n\t\tpeer_ids = set()\n\n\n\t# clean ALL the peers!\n\tpeers_data = []\n\tnow = time.time()\n\tfor peer_id in peer_ids:\n\t\tdata = r.get_peer(peer_id)\n\t\tif not data or int(data['seen']) < now-(60*2):\n\t\t\tr.del_peer(peer_id)\n\t\telse:\n\t\t\tpeers_data.append(data)\n\n\n\t# send ALL the peers\n\tif qs['compact']:\n\t\tpeers_l = \"\"\n\t\tfor peer in peers_data:\n\t\t\tpeers_l += struct.pack('>4sH', socket.inet_aton(peer['ip']), int(peer['port']))\n\n\telif qs['no_peer_id']:\n\t\tpeers_l = []\n\t\tfor peer in peers_data:\n\t\t\tpeers_l.append({'ip': peer['ip'], 'port': int(peer['port'])})\n\n\telse:\n\t\tpeers_l = []\n\t\tfor peer in peers_data:\n\t\t\tpeers_l.append({'peer id': peer['peer_id'], 'ip': peer['ip'], 'port': peer['port']})\n\n\n\ttry:\n\t\treturn HttpResponse(\n\t\t\tbencode.bencode({\n\t\t\t\t'interval': 60,\n\t\t\t\t'peers': peers_l\n\t\t\t}),\n\t\t\tcontent_type = 'text/plain'\n\t\t)\n\n\texcept:\n\t\treturn response_fail(sys.exc_info()[1])\n\n\ndef scrape(request):\n\t\"\"\"qs = request.GET.copy()\n\tscp = ScrapeForm(qs.dict())\n\n\tif not scp.is_valid():\n\t\traise Exception(scp.errors)\n\n\tqs = scp.cleaned_data\n\tr = redis.Redis(host='localhost')\n\tseeders_key = 'redtracker:seeders:'+ qs['info_hash']\n\tleechers_key = 'redtracker:leechers:'+ qs['info_hash']\n\n\treturn HttpResponse(\n\t\tbencode.bencode({\n\t\t\t'files': {\n\t\t\t\tqs['info_hash']: {\n\t\t\t\t\t'complete': r.sdiffstore('tmp', seeders_key, leechers_key), \n\t\t\t\t\t'incomplete': r.scard(leechers_key), \n\t\t\t\t\t'downloaded': 0 #TODO\n\t\t\t\t}\n\t\t\t}\n\t\t}),\n\t\tcontent_type = 'text/plain'\n\t)\"\"\"\n\treturn render_to_response('tracker/scrape.html', {})\n\n\ndef response_fail(reason):\n\treturn HttpResponse(\n\t\tbencode.bencode({'failure reason': reason or 'unknown'}), \n\t\tcontent_type = 'text/plain'\n\t)\n\n\n" }, { "alpha_fraction": 0.6994242072105408, "alphanum_fraction": 0.7105566263198853, "avg_line_length": 29.162790298461914, "blob_id": "2ad12ae22880ccdf4175ae0e88729aa68bd1d573", "content_id": "f4ba7e13eb669875869716ea53347aa41fb33532", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2605, "license_type": "no_license", "max_line_length": 73, "num_lines": 86, "path": "/tracker/models.py", "repo_name": "xergio/redtorrent", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django import forms\nimport redis\nimport time\n\n\nclass AnnounceForm(forms.Form):\n\tinfo_hash = forms.CharField(max_length=100)\n\tpeer_id = forms.CharField(max_length=100)\n\tport = forms.IntegerField()\n\tuploaded = forms.IntegerField()\n\tdownloaded = forms.IntegerField()\n\tleft = forms.IntegerField()\n\tcompact = forms.BooleanField(required=False, initial=False)\n\tno_peer_id = forms.BooleanField(required=False, initial=False)\n\tevent = forms.CharField(max_length=9, required=False)\n\tip = forms.CharField(max_length=100, required=False)\n\tnumwant = forms.IntegerField(required=False, initial=50)\n\tkey = forms.CharField(max_length=20, required=False)\n\ttrackerid = forms.CharField(max_length=20, required=False)\n\tsupportcrypto = forms.BooleanField(required=False, initial=False)\n\trequirecrypto = forms.BooleanField(required=False, initial=False)\n\n\tdef clean_event(self):\n\t\tevent = self.cleaned_data['event'].strip()\n\t\tif event not in ['started', 'completed', 'stopped'] and len(event) > 0:\n\t\t\traise forms.ValidationError(\"event '%s' is invalid.\" % event)\n\t\treturn event\n\n\nclass ScrapeForm(forms.Form):\n\tinfo_hash = forms.CharField(max_length=100)\n\n\nclass Store(redis.Redis):\n\t\n\tdef set_info(self, info_hash, peer_id):\n\t\tself.info_hash = info_hash\n\t\tself.peer_id = peer_id\n\t\tself.peer_key = \"redtorrent:peer:%s\" % self.peer_id\n\t\tself.seeders_key = \"redtracker:seeders:%s\" % self.info_hash\n\t\tself.leechers_key = \"redtracker:leechers:%s\" % self.info_hash\n\t\n\tdef save_peer(self, data):\n\t\tdata.update({'seen': int(time.time())})\n\t\treturn self.hmset(self.peer_key, data)\n\t\t\n\tdef delete_peer(self):\n\t\treturn self.delete(self.peer_key)\n\t\t\n\tdef get_peer(self, peer_id):\n\t\treturn self.hgetall(u\"redtorrent:peer:%s\" % peer_id)\n\t\t\n\tdef del_peer(self, peer_id):\n\t\tself.srem(self.seeders_key, peer_id)\n\t\tself.srem(self.leechers_key, peer_id)\n\t\treturn self.delete(u\"redtorrent:peer:%s\" % peer_id)\n\t\t\n\tdef add_seeder(self):\n\t\treturn self.sadd(self.seeders_key, self.peer_id)\n\t\t\n\tdef del_seeder(self):\n\t\treturn self.srem(self.seeders_key, self.peer_id)\n\t\t\n\tdef add_leecher(self):\n\t\treturn self.sadd(self.leechers_key, self.peer_id)\n\t\t\n\tdef del_leecher(self):\n\t\treturn self.srem(self.leechers_key, self.peer_id)\n\t\t\n\tdef len_seeders(self):\n\t\treturn self.scard(self.seeders_key)\n\t\t\n\tdef len_leechers(self):\n\t\treturn self.scard(self.leechers_key)\n\t\t\n\tdef all_seeders(self):\n\t\treturn self.smembers(self.seeders_key)\n\t\t\n\tdef get_seeders(self, num=50):\n\t\tpeer_ids = set()\n\t\ti = 0\n\t\twhile len(peer_ids) < num and i < 1000:\n\t\t\tpeer_ids.add(self.srandmember(self.seeders_key))\n\t\t\ti += 1\n\t\treturn peer_ids\n\t\t\n\t\t\n\t\t\n\t\t" }, { "alpha_fraction": 0.6640926599502563, "alphanum_fraction": 0.6640926599502563, "avg_line_length": 36, "blob_id": "2ee9069d6022175d422583ebc1fe32e17fe97657", "content_id": "fb7ed7da75f8a383c62a85577ffc7931b73fc901", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 259, "license_type": "no_license", "max_line_length": 65, "num_lines": 7, "path": "/redtorrent/urls.py", "repo_name": "xergio/redtorrent", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, url\n\nurlpatterns = patterns('',\n url(r'^$', 'tracker.views.announce', name='announce'),\n url(r'^announce', 'tracker.views.announce', name='announce'),\n url(r'^scrape$', 'tracker.views.scrape', name='scrape'),\n)\n" } ]
3
zaccharieramzi/tf-didn
https://github.com/zaccharieramzi/tf-didn
cd34e30a5b1b25bb59a775d0739d0c75bb7513d1
5da6cc5c5ad8421337e09c8b5aa85452a5db27e2
e1a075ab59aa090f978b9ebbd24d51b751c94260
refs/heads/master
2022-11-01T10:46:58.433233
2020-06-12T12:55:10
2020-06-12T12:55:10
271,322,840
2
1
null
null
null
null
null
[ { "alpha_fraction": 0.7745415568351746, "alphanum_fraction": 0.7799353003501892, "avg_line_length": 45.349998474121094, "blob_id": "776691de2b2b2d45c96533fd172c0e791edf450c", "content_id": "aff10e5bb8bbcbbb2a70275cda5bcccaf8aa8a73", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 927, "license_type": "permissive", "max_line_length": 127, "num_lines": 20, "path": "/README.md", "repo_name": "zaccharieramzi/tf-didn", "src_encoding": "UTF-8", "text": "# TensorFlow implementation of the Deep iterative down-up CNN\n\n[![Build Status](https://travis-ci.com/zaccharieramzi/tf-didn.svg?branch=master)](https://travis-ci.com/zaccharieramzi/tf-didn)\n\nThe Deep iterative down-up CNN (DIDN) is a network introduced by Songhyun Yu et\nal. in \"Deep Iterative Down-Up CNN for Image Denoising\" CVPR 2019.\nIf you use this network, please cite their work appropriately.\n\nThe official implementation is available [here](https://github.com/SonghyunYu/DIDN)\nin Pytorch.\n\nThe goal of this implementation in TensorFlow is to be easy to read and to adapt:\n- all the code is in one file\n- defaults are those from the paper\n- there is no other imports than from TensorFlow\n\nSome implementation details were taken from the code and not the paper itself:\n- no bias is used in the convolutions\n- the number of down-up blocks is set to 6\n- the activation of the last convolutional layer of the network is linear\n" }, { "alpha_fraction": 0.5359042286872864, "alphanum_fraction": 0.5625, "avg_line_length": 22.5, "blob_id": "915fd563aecface21e8ce48a28147a0c52adc1c0", "content_id": "da206943e6ecbca751c9336503a47c17dff1a62c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 752, "license_type": "permissive", "max_line_length": 59, "num_lines": 32, "path": "/didn_test.py", "repo_name": "zaccharieramzi/tf-didn", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\n\nfrom didn import DIDN\n\ndef test_didn():\n n_filters = 8\n model = DIDN(\n n_filters=n_filters,\n n_dubs=2,\n n_convs_recon=3,\n n_scales=3,\n )\n model(tf.zeros((1, 64, 64, 1)))\n\ndef test_didn_change():\n n_filters = 8\n model = DIDN(\n n_filters=n_filters,\n n_dubs=2,\n n_convs_recon=3,\n n_scales=3,\n )\n x = tf.random.normal((1, 64, 64, 1))\n y = x\n model(x)\n before = [v.numpy() for v in model.trainable_variables]\n model.compile(optimizer='sgd', loss='mse')\n model.train_on_batch(x, y)\n after = [v.numpy() for v in model.trainable_variables]\n for b, a in zip(before, after):\n assert np.any(np.not_equal(b, a))\n" } ]
2
Redon913/SpaceGame
https://github.com/Redon913/SpaceGame
03c5b81ba66c3b2e56416b64280927cd8d96e63e
c21481c5f7add95850734e530c13c0a9ee78a649
56f2cbc6b80ae97f9ecb3445bfc3320d72569c3c
refs/heads/master
2022-11-19T06:15:08.071094
2020-07-25T08:15:31
2020-07-25T08:15:31
271,751,316
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.46960967779159546, "alphanum_fraction": 0.5115241408348083, "avg_line_length": 31.80487823486328, "blob_id": "184e5152d1f3f5009d8c4daebd0ff9f0a5a972e7", "content_id": "762bad3c87e452840d2a5ef3027aa6a07d0094c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10760, "license_type": "no_license", "max_line_length": 126, "num_lines": 328, "path": "/space_adventure.py", "repo_name": "Redon913/SpaceGame", "src_encoding": "UTF-8", "text": "import pygame\n\npygame.init()\n\nroot_width = 640\nroot_height = 780\nroot = pygame.display.set_mode((root_width, root_height))\npygame.display.set_caption('SPACE ADVENTURE')\n\nclock = pygame.time.Clock()\nbg_g = pygame.transform.scale(pygame.image.load('space/space_bg1.jpg'), (640, 780))\nbg_m = pygame.transform.scale(pygame.image.load('space/space_bg2.jpg'), (640, 780))\nbg_music = pygame.mixer.music.load('space/space_bg.mp3')\nmenu_b = pygame.transform.scale(pygame.image.load('space/menu_b.png'), (150, 70))\npygame.mixer.music.play(-1)\n\ne_sound = pygame.mixer.Sound('space/explosion3.wav')\ns_sound = pygame.mixer.Sound('space/explosion1.wav')\nalert = pygame.mixer.Sound('space/1beeper.wav')\nshipFire = pygame.mixer.Sound('space/missile2.wav')\n\n\nclass Ship:\n jet1 = pygame.transform.scale(pygame.image.load('space/ship1.png'), (70, 70))\n jet2 = pygame.transform.scale(pygame.image.load('space/ship2.png'), (70, 70))\n explosion = pygame.transform.scale(pygame.image.load('space/explosion1.png'), (100, 100))\n\n def __init__(self, x, y, width, height, jet):\n self.x = x\n self.y = y\n self.width = width\n self.jet = jet\n self.height = height\n self.vel = 8\n self.hitBox = (self.x, self.y, self.width, self.height)\n self.health = 7\n self.visible = True\n\n def draw(self, win):\n if self.visible:\n self.hitBox = (self.x, self.y, self.width, self.height)\n # pygame.draw.rect(win, (255, 0, 0), self.hitBox, 1)\n if self.jet == 1:\n win.blit(self.jet1, (self.x, self.y))\n else:\n win.blit(self.jet2, (self.x, self.y))\n pygame.draw.rect(win, (255, 0, 0), (self.x, self.y + self.height, self.width, 5))\n pygame.draw.rect(win, (0, 255, 0), (self.x, self.y + self.height, 70 - (10 * (7 - self.health)), 5))\n else:\n s_sound.play()\n win.blit(self.explosion, (self.x, self.y))\n\n def hit(self):\n if self.health == 2:\n alert.play()\n else:\n alert.stop()\n if self.health > 1:\n self.health -= 1\n else:\n self.visible = False\n\n def reset(self):\n self.x = 320\n self.y = 700\n self.health = 7\n self.visible = True\n\nclass Weapon:\n fire = pygame.transform.scale(pygame.image.load('space/missile1.png'), (10, 70))\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.vel = 10 # 684.999999999999943156\n\n def draw(self, win):\n win.blit(self.fire, (self.x, self.y))\n\n\nclass Enemy:\n e_ship = pygame.transform.scale(pygame.image.load('space/enemyShip1.png'), (300, 300))\n explosion = pygame.transform.scale(pygame.image.load('space/explosion1.png'), (300, 300))\n\n def __init__(self, x, y, end):\n self.x = x\n self.y = y\n self.path = (self.x, end)\n self.vel = 7\n self.hitBox = (self.x + 25, self.y, 265, 300)\n self.health = 10\n self.visible = True\n\n def draw(self, win):\n if self.visible:\n self.move()\n self.hitBox = (self.x + 25, self.y + 10, 252, 270)\n # pygame.draw.rect(win, (255, 0, 0), self.hitBox, 1)\n pygame.draw.rect(root, (255, 0, 0), (self.x, self.y + 5, 300, 5))\n pygame.draw.rect(root, (0, 255, 0), (self.x, self.y + 5, 300 - (30 * (10 - self.health)), 5))\n win.blit(self.e_ship, (self.x, self.y))\n else:\n e_sound.play()\n win.blit(self.explosion, (self.x, self.y))\n\n def move(self):\n if self.vel > 0:\n if self.x + self.vel + 300 < self.path[1]:\n self.x += self.vel\n else:\n self.vel *= -1\n else:\n if self.x + self.vel > self.path[0]:\n self.x += self.vel\n else:\n self.vel *= -1\n\n def hit(self):\n if self.health > 0.5:\n self.health -= 0.5\n else:\n self.visible = False\n\n def reset(self):\n self.x = 0\n self.y = 5\n self.health = 10\n self.visible = True\n\n\n\nclass EWeapon:\n\n def __init__(self, x, y, width, height):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.vel = 20\n self.e_missile = pygame.transform.scale(pygame.image.load('space/e_missile1.png'), (self.width, self.height))\n\n def draw(self, win):\n win.blit(self.e_missile, (self.x, self.y))\n\n\ndef reset_values():\n globals()['score'] = 0\n global missiles\n global e_missiles\n global e_missilesR\n Falcon.reset()\n Thanos.reset()\n missiles.clear()\n e_missiles.clear()\n e_missilesR.clear()\n\n\ndef re_draw_everything():\n root.blit(bg_g, (0, 0))\n Falcon.draw(root)\n if Thanos.visible:\n if Falcon.visible:\n text = font.render('SCORE:' + str(score), 1, (255, 255, 255))\n root.blit(text, (250, 390))\n else:\n text = font1.render('GALAXY IS DESTROYED...', 1, (255, 255, 255))\n root.blit(text, (120, 390))\n text = font1.render('GAME OVER.', 1, (255, 255, 255))\n root.blit(text, (220, 420))\n text = font1.render('PRESS C TO RESTART..', 1, (255, 255, 255))\n root.blit(text, (120, 520))\n else:\n text = font1.render('YOU SAVED THE GALAXY.', 1, (255, 255, 255))\n root.blit(text, (120, 390))\n text = font1.render('WELL PLAYED...', 1, (255, 255, 255))\n root.blit(text, (220, 420))\n\n for missile in missiles:\n missile.draw(root)\n for e_missile in e_missiles:\n e_missile.draw(root)\n for e_missile in e_missilesR:\n e_missile.draw(root)\n Thanos.draw(root)\n pygame.display.update()\n\n\ndef re_draw_menu_window():\n root.blit(bg_m, (0, 0))\n text = font1.render('PRESS S TO START.', 1, (255, 255, 255))\n root.blit(text, (160, 190))\n text = font1.render('PRESS Q TO QUIT.', 1, (255, 255, 255))\n root.blit(text, (160, 240))\n pygame.display.update()\n\n\nif __name__ == \"__main__\":\n Falcon = Ship(320, 700, 70, 70, 1)\n # Armada = Ship(320, 700, 70, 70, 2)\n Thanos = Enemy(0, 5, root_width + 10)\n\n\n missiles = []\n e_missiles = []\n e_missilesR = []\n\n score = 0\n font = pygame.font.SysFont('ink free', 50)\n font1 = pygame.font.SysFont('ink free', 30, True)\n shootDelay = 0\n e_missile_delay = 0\n e_missile_delayR = 0\n\n run = True\n runMain = False\n\n while run:\n clock.tick(35)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n keys = pygame.key.get_pressed()\n if keys[pygame.K_s]:\n runMain = True\n if keys[pygame.K_q]:\n run = False\n if keys[pygame.K_m]:\n runMain = False\n reset_values()\n\n if runMain:\n # FALCON MISSILE DEPLOY\n\n if shootDelay > 0:\n shootDelay += 1\n if shootDelay > 10:\n shootDelay = 0\n\n for missile in missiles:\n if missile.y > Thanos.hitBox[1] and missile.y < Thanos.hitBox[1] + Thanos.hitBox[3]:\n if missile.x + 10 > Thanos.hitBox[0] and missile.x < Thanos.hitBox[0] + Thanos.hitBox[2]:\n missiles.pop(missiles.index(missile))\n score += 10\n Thanos.hit()\n\n for missile in missiles:\n if missile.y > 0:\n missile.y -= missile.vel\n else:\n missiles.pop(missiles.index(missile))\n\n # ENEMY MISSILE DEPLOY\n\n if e_missile_delay > 0:\n e_missile_delay += 1\n if e_missile_delay > 20:\n e_missile_delay = 0\n\n if Thanos.visible:\n if Falcon.visible:\n if e_missile_delay == 0:\n e_missiles.append(EWeapon(round(Thanos.x + 45), round(Thanos.y + 300//2), 10, 50))\n e_missile_delay = 1\n\n for e_missile in e_missiles:\n if e_missile.y < root_height:\n e_missile.y += e_missile.vel\n else:\n e_missiles.pop(e_missiles.index(e_missile))\n\n for e_missile in e_missiles:\n if e_missile.y < Falcon.hitBox[1] + Falcon.hitBox[3] and e_missile.y + e_missile.height > Falcon.hitBox[1]:\n if e_missile.x + e_missile.width > Falcon.hitBox[0] and e_missile.x < Falcon.hitBox[0] + Falcon.hitBox[2]:\n e_missiles.pop(e_missiles.index(e_missile))\n score -= 10\n Falcon.hit()\n\n if e_missile_delayR > 0:\n e_missile_delayR += 1\n if e_missile_delayR > 15:\n e_missile_delayR = 0\n\n if Thanos.visible:\n if Falcon.visible:\n if e_missile_delayR == 0:\n e_missilesR.append(EWeapon(round(Thanos.x + 245), round(Thanos.y + 300 // 2), 10, 50))\n e_missile_delayR = 1\n\n for e_missile in e_missilesR:\n if e_missile.y < root_height:\n e_missile.y += e_missile.vel\n else:\n e_missilesR.pop(e_missilesR.index(e_missile))\n\n for e_missile in e_missilesR:\n if e_missile.y < Falcon.hitBox[1] + Falcon.hitBox[3] and e_missile.y + e_missile.height > Falcon.hitBox[1]:\n if e_missile.x + e_missile.width > Falcon.hitBox[0] and e_missile.x < Falcon.hitBox[0] + Falcon.hitBox[2]:\n e_missilesR.pop(e_missilesR.index(e_missile))\n score -= 10\n Falcon.hit()\n\n # KEY IN USE\n\n if not Falcon.visible:\n if keys[pygame.K_c]:\n Falcon.visible = True\n reset_values()\n\n if Thanos.visible:\n if Falcon.visible:\n if keys[pygame.K_SPACE] and shootDelay == 0:\n shipFire.play()\n if len(missiles) < 10:\n missiles.append(Weapon(round(Falcon.x - 5 + Falcon.width/2), Falcon.y))\n shootDelay = 1\n if keys[pygame.K_RIGHT] and Falcon.x < root_width - Falcon.width:\n Falcon.x += Falcon.vel\n if keys[pygame.K_LEFT] and Falcon.x > 0:\n Falcon.x -= Falcon.vel\n\n # DRAW FUNCTION\n re_draw_everything()\n else:\n\n re_draw_menu_window()\n pygame.quit()\n" }, { "alpha_fraction": 0.671600341796875, "alphanum_fraction": 0.6975023150444031, "avg_line_length": 36.27586364746094, "blob_id": "4f3537295e7fe3f8414d425f5f8b7d0ecf610c23", "content_id": "397728b27f3125533b42b8b6b16236e9f2fa071a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1081, "license_type": "no_license", "max_line_length": 253, "num_lines": 29, "path": "/README.md", "repo_name": "Redon913/SpaceGame", "src_encoding": "UTF-8", "text": "# SpaceGame\n\nThis is a simple Space-Game that I created using Pygame Module in python in about 24hr (18/March/2019 - 19/March/2019) just for self-lerning purpose.\n\n# Disclaimer\n\nI made this game a year ago (today: 25/July/2020). So I don't have a reference or knowledge about who create all the Graphic images in the game. I had just downloaded those from Internet. So if you made any of them and want them removed just Contact Me.\n\n# Screenshots of Game\n\n## This game has two screens\n\n1. **For the Main Menu to start or quit the game** \n ![Main Menu Screen](./.gitImg/Main_screen.png)\n\n2. **For the Actual game that you can play**\n 1. Screen for main game \n ![Game Screen](./.gitImg/Game_screen.png) \n 2. Screen for when game is won \n ![Game Screen Win](./.gitImg/Game_screen_win.png) \n 3. Screen for when game is lost \n ![Game Screen Lose](./.gitImg/Game_screen_end.png) \n\n# Game Variants\n\n1. This the First Game variant \n ![Game Screen](./.gitImg/Game_screen.png)\n1. This the Second Game variant \n ![Game Screen](./.gitImg/Game_screen_2.png)\n" } ]
2
scatteredwriter/MyPython
https://github.com/scatteredwriter/MyPython
a69f681122994ace66d665caee18ac66725b4381
e1620c7b0081b85fa98e618c84bc1084fda48fc9
58cff52dda4ac7ffdf4fa4e042606059ebe06cf4
refs/heads/master
2021-07-06T00:12:44.468292
2019-03-22T06:16:02
2019-03-22T06:16:02
107,134,970
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5846508741378784, "alphanum_fraction": 0.5963438749313354, "avg_line_length": 29.461139678955078, "blob_id": "3580f0ad4454cb34ff7df3af708400d6161787d8", "content_id": "1d87c5f8d28c81424d452006f1afd9d688602056", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6318, "license_type": "no_license", "max_line_length": 107, "num_lines": 193, "path": "/study.py", "repo_name": "scatteredwriter/MyPython", "src_encoding": "UTF-8", "text": "# coding=utf-8\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\nfrom selenium.webdriver.remote.webelement import WebElement\r\nimport time\r\nimport re\r\n\r\n\r\ndef Login():\r\n loginbut.click()\r\n uname = driver.find_element_by_name('uname')\r\n password = driver.find_element_by_name('password')\r\n numcode = driver.find_element_by_name('numcode')\r\n but = driver.find_element_by_class_name('zl_btn_right')\r\n # username = input('请输入账号: ')\r\n # password_p = input(\"请输入密码: \")\r\n yanzheng = input(\"请输入验证码: \")\r\n uname.clear()\r\n password.clear()\r\n numcode.clear()\r\n uname.send_keys('2015212856')\r\n password.send_keys('Scattered1')\r\n numcode.send_keys(yanzheng)\r\n but.click()\r\n print('登录完成')\r\n\r\n\r\ndef GetChapterIds():\r\n driver.get('http://mooc1.chaoxing.com/course/96522356.html')\r\n cellbgbluebgblue1wh = driver.find_element_by_css_selector(\r\n 'div.cell.bgblue.bgblue1.wh')\r\n p20s = cellbgbluebgblue1wh.find_elements_by_css_selector(\r\n 'div.p20.btdwh.btdwh1.fix')\r\n for p20 in p20s:\r\n mt10 = p20.find_element_by_class_name('mt10')\r\n mb15s = mt10.find_elements_by_css_selector(\r\n 'li.mb15.course_section.fix')\r\n for mb15 in mb15s:\r\n link = mb15.find_element_by_css_selector('a.wh.wh1')\r\n href = link.get_attribute('href')\r\n pattern = re.compile('knowledgeId=\\d+')\r\n match = pattern.search(href)\r\n if match:\r\n chapterids.append(match.group().replace('knowledgeId=', ''))\r\n print('所有章节数据已经获取完毕')\r\n driver.back()\r\n\r\n\r\ndef ChioceCourse():\r\n '选择课程'\r\n driver.switch_to_frame('frame_content')\r\n a = driver.find_element_by_partial_link_text('创新创业')\r\n url = a.get_attribute('href')\r\n driver.switch_to_default_content()\r\n return url\r\n\r\n\r\ndef ClickCourse():\r\n '点击任务点'\r\n global coursename\r\n timeline = driver.find_element_by_class_name('timeline')\r\n units = timeline.find_elements_by_class_name('units')\r\n for unit in units:\r\n leveltwos = unit.find_elements_by_class_name('leveltwo')\r\n for leveltwo in leveltwos:\r\n clearfix = leveltwo.find_element_by_class_name('clearfix')\r\n icon = clearfix.find_element_by_class_name('icon')\r\n\r\n # 判断该课程是否学习完成\r\n try:\r\n orange = icon.find_element_by_class_name('orange')\r\n if not orange:\r\n continue\r\n except Exception as identifier:\r\n continue\r\n\r\n articlename = clearfix.find_element_by_class_name('articlename')\r\n but = articlename.find_element_by_tag_name('a')\r\n but.click()\r\n break\r\n break\r\n while True:\r\n PlayVideo()\r\n print('所有课程已经学习完成')\r\n\r\n\r\ndef EnteriFrame():\r\n '进入iFrame'\r\n driver.switch_to_default_content()\r\n driver.switch_to_frame('iframe')\r\n ans_attach_ct = driver.find_element_by_class_name('ans-attach-ct')\r\n _iframe = ans_attach_ct.find_element_by_tag_name('iframe')\r\n driver.switch_to_frame(_iframe)\r\n\r\n\r\ndef JundgeFinished():\r\n '判断是否播放完成'\r\n driver.switch_to_default_content()\r\n driver.switch_to_frame('iframe')\r\n try:\r\n finished = driver.find_element_by_css_selector(\r\n 'div.ans-attach-ct.ans-job-finished')\r\n if finished:\r\n driver.switch_to_default_content()\r\n return True\r\n else:\r\n EnteriFrame()\r\n return False\r\n except Exception as identifier:\r\n EnteriFrame()\r\n return False\r\n\r\n\r\ndef StudyNext():\r\n '播放下一节'\r\n global url\r\n onetoone = driver.find_element_by_class_name('onetoone')\r\n ncells = onetoone.find_elements_by_class_name('ncells')\r\n i = 0\r\n for ncell in ncells:\r\n try:\r\n a = ncell.find_element_by_css_selector(\r\n 'a[title={}]'.format(coursename))\r\n currents = a.find_element_by_class_name('currents')\r\n if currents:\r\n i += 1\r\n break\r\n except Exception as identifier:\r\n pass\r\n i += 1\r\n continue\r\n url = driver.current_url\r\n pattern = re.compile('enc=.+')\r\n match = pattern.search(url)\r\n if match:\r\n enc = match.group().replace('enc=', '')\r\n driver.get(studypage.format(chapterids[i], courseId, clazzid, enc))\r\n\r\n\r\ndef PlayVideo():\r\n '播放视频'\r\n global coursename\r\n driver.switch_to_default_content()\r\n main = driver.find_element_by_class_name('main')\r\n coursename = main.find_element_by_tag_name('h1').text\r\n EnteriFrame()\r\n reader = driver.find_element_by_id('reader')\r\n flash = None\r\n while not flash:\r\n try:\r\n flash = reader.find_element_by_css_selector(\r\n \"object[type='application/x-shockwave-flash']\")\r\n except Exception as identifier:\r\n pass\r\n print('正在学习:', coursename)\r\n size = flash.size\r\n try:\r\n chains.move_to_element_with_offset(\r\n flash, 10, size['height'] - 10).click(flash).perform()\r\n except Exception as identifier:\r\n pass\r\n while not JundgeFinished():\r\n try:\r\n # chains.move_to_element_with_offset(\r\n # flash, 10, size['height'] - 10).click(flash).perform()\r\n # time.sleep(1)\r\n chains.release(flash).perform()\r\n except Exception as identifier:\r\n pass\r\n chains.reset_actions()\r\n print(coursename, \"学习视频观看完毕,现在学习下一节\")\r\n StudyNext()\r\n\r\n\r\ndriver = webdriver.Chrome()\r\nchains = ActionChains(driver)\r\ncoursename = None\r\ncourseId = 96522356\r\nclazzid = 1406028\r\nstudypage = 'https://mooc1-1.chaoxing.com/mycourse/studentstudy?chapterId={}&courseId={}&clazzid={}&enc={}'\r\n\r\ndriver.get('http://cqupt.benke.chaoxing.com/')\r\nloginbut = driver.find_element_by_class_name('zt_l_loading')\r\nprint('进行账号登录...')\r\nLogin()\r\nprint('\\n获取课程章节数据...')\r\nchapterids = []\r\nGetChapterIds()\r\nurl = ChioceCourse()\r\ndriver.get(url)\r\nprint('\\n开始学习...')\r\nClickCourse()\r\n" }, { "alpha_fraction": 0.5466204285621643, "alphanum_fraction": 0.5795493721961975, "avg_line_length": 30.415729522705078, "blob_id": "6063e6a7babee3deeadad7144b1d2252f213a761", "content_id": "217f5229239361d17f065328e14fc5bba1c533d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2921, "license_type": "no_license", "max_line_length": 188, "num_lines": 89, "path": "/alarm.py", "repo_name": "scatteredwriter/MyPython", "src_encoding": "UTF-8", "text": "# coding=utf-8\r\n\r\nimport requests\r\nimport json\r\nimport re\r\nimport os\r\nimport time\r\nimport datetime\r\nimport urllib.request\r\n\r\n\r\nstu_num = '2015212856'\r\nheaders = {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',\r\n 'Referer': 'http://www.weather.com.cn/weather/101040100.shtml'}\r\n\r\n\r\ndef getWeather():\r\n url = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101040100'\r\n result = requests.get(url, headers=headers)\r\n try:\r\n encoding = ''\r\n if result.encoding == 'ISO-8859-1':\r\n encodings = requests.utils.get_encodings_from_content(result.text)\r\n if encodings:\r\n encoding = encodings[0]\r\n else:\r\n encoding = result.apparent_encoding\r\n encode_content = result.content.decode(\r\n encoding, 'replace').encode('utf-8', 'replace')\r\n result = encode_content.decode('utf-8')\r\n except:\r\n result = result.text\r\n result = json.loads(result)\r\n result = result['data']\r\n return '播报闹钟。%s今日%s。' % (result['city'], result['forecast'][1]['low'] + ',' + result['forecast'][1]['high'])\r\n\r\n\r\ndef getCourses():\r\n url = 'https://wx.idsbllp.cn/api/kebiao'\r\n data = {'stu_num': stu_num}\r\n result = ''\r\n for i in range(3):\r\n try:\r\n result = requests.post(url, data=data)\r\n break\r\n except:\r\n pass\r\n result = result.text\r\n result = json.loads(result)\r\n data = result['data']\r\n week = datetime.datetime.now().weekday()\r\n if(week == 6):\r\n week = 0\r\n else:\r\n week = week + 1\r\n courseMode = ''\r\n if(result['nowWeek'] % 2):\r\n courseMode = 'single'\r\n else:\r\n courseMode = 'double'\r\n courses = []\r\n for item in data:\r\n if(item['weekBegin'] <= result['nowWeek'] and item['weekEnd'] >= result['nowWeek'] and item['hash_day'] == week and(item['weekModel'] == 'all' or item['weekModel'] == courseMode)):\r\n courses.append(item)\r\n result = ''\r\n for item in courses:\r\n result += '第%s有%s,教室在%s。' % (item['lesson'],\r\n item['course'], item['classroom'])\r\n if(result):\r\n result = '今天' + result\r\n return result\r\n\r\n\r\ndef getVoice(text):\r\n text = urllib.parse.quote(text)\r\n tokenurl = 'https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=Pp1PNrUVnECO7LH7Ki4uQxnx&client_secret=0b1ab78a06e3b571c8e76143849b85d5'\r\n result = requests.get(tokenurl, headers=headers)\r\n result = json.loads(result.text)\r\n url = 'http://tsn.baidu.com//text2audio?tex=%s&tok=%s&lan=zh&ctp=1&cuid=7808972&pit=5&vol=15&per=4' % (\r\n text, result['access_token'])\r\n os.system('mpg123 -q \"%s\"' % url)\r\n\r\n\r\nweather = getWeather()\r\nprint(weather)\r\ncourses = getCourses()\r\nprint(courses)\r\ngetVoice(weather + courses)\r\n" }, { "alpha_fraction": 0.4499618113040924, "alphanum_fraction": 0.49656227231025696, "avg_line_length": 24.44444465637207, "blob_id": "8d935dd8f774fef71048fdc4280c1b34179d4c10", "content_id": "70ec083defa7568c22d3a692fbc54bde519069ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3030, "license_type": "no_license", "max_line_length": 123, "num_lines": 99, "path": "/recommend.py", "repo_name": "scatteredwriter/MyPython", "src_encoding": "UTF-8", "text": "# coding=utf-8\r\nimport math\r\n\r\ncourses = {\r\n 1: '电工学',\r\n 2: '高等数学(上)',\r\n 3: '大学英语3',\r\n 4: 'C语言程序设计'\r\n}\r\ndata = {\r\n '曽钦威': {\r\n courses[1]: 81,\r\n courses[2]: 77,\r\n courses[3]: 80,\r\n courses[4]: 95\r\n },\r\n '张晓阳': {\r\n courses[1]: 75,\r\n courses[2]: 60,\r\n courses[3]: 65,\r\n courses[4]: 75\r\n },\r\n '周杰': {\r\n courses[1]: 77,\r\n courses[2]: 90,\r\n courses[3]: 89,\r\n courses[4]: 82\r\n },\r\n '庄智': {\r\n courses[1]: 87,\r\n courses[2]: 61,\r\n courses[3]: 50,\r\n courses[4]: 90\r\n }\r\n}\r\n\r\n\r\ndef sim_distance(datas, person1, person2):\r\n '通过计算欧氏距离得出两者的相似度'\r\n si = {}\r\n for item in datas[person1]:\r\n if item in datas[person2]:\r\n si[item] = 1\r\n if len(si) == 0:\r\n return 0\r\n\r\n # 计算两者的欧氏距离\r\n sum_of_squares = sum([pow(datas[person1][item] - datas[person2][item], 2)\r\n for item in datas[person1] if item in datas[person2]])\r\n\r\n # 返回值越接近1则代表两者的相似度越大\r\n return 1 / (1 + math.sqrt(sum_of_squares))\r\n\r\n\r\ndef sim_pearson(datas, person1, person2):\r\n '通过皮尔逊相关系数得出两者的相关程度'\r\n si = {}\r\n for item in datas[person1]:\r\n if item in datas[person2]:\r\n si[item] = 1\r\n if len(si) == 0:\r\n return 1\r\n # 计算person1所有item评分之和\r\n sum1 = sum([datas[person1][item] for item in si])\r\n sum2 = sum([datas[person2][item] for item in si])\r\n sum_of_1x2 = sum([datas[person1][item] * datas[person2][item]\r\n for item in si])\r\n sum_of_square1 = sum([pow(datas[person1][item], 2) for item in si])\r\n sum_of_square2 = sum([pow(datas[person2][item], 2) for item in si])\r\n n = len(si)\r\n try:\r\n result = (sum_of_1x2 - (sum1 * sum2) / n) / math.sqrt((sum_of_square1 -\r\n (pow(sum1, 2) / n)) * (sum_of_square2 - (pow(sum2, 2) / n)))\r\n except Exception as identifier:\r\n return 0\r\n return result\r\n\r\n\r\ndef get_result(person1, person2, fun):\r\n '计算相关度'\r\n result = fun(data, person1, person2)\r\n if fun == sim_distance:\r\n print('你们的相似度有%f哦' % result)\r\n elif fun == sim_pearson:\r\n if result > 0.0:\r\n print('你们两个人的学习情况非常相似哦!')\r\n elif result == 0.0:\r\n print('你们两个人的学习情况看起来没有什么关系')\r\n elif result < 0.0:\r\n print('你们真的是一点关系都没有...')\r\n\r\n\r\nc = input('请选择使用哪种方式计算相关关系:\\n1.欧氏距离\\n2.皮尔逊相关度\\n')\r\np1 = input('请输入第一位学生的名字:')\r\np2 = input('请输入第二位学生的名字:')\r\nif c == '1':\r\n get_result(p1, p2, sim_distance)\r\nelif c == '2':\r\n get_result(p1, p2, sim_pearson)\r\n" }, { "alpha_fraction": 0.46777820587158203, "alphanum_fraction": 0.49106788635253906, "avg_line_length": 40.751380920410156, "blob_id": "bafeae92b4a1b0e9638e94bd06acad4f38ea2ece", "content_id": "16585f86c54e68db56d26a1e9e7daa2d63d5c478", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7787, "license_type": "no_license", "max_line_length": 256, "num_lines": 181, "path": "/downloadmusic.py", "repo_name": "scatteredwriter/MyPython", "src_encoding": "UTF-8", "text": "import requests\nimport json\nimport os\nimport platform\n\n\nclass Color:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\nheaders = {\n 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'\n}\n\ndef getMusicList(keyword, p):\n get_url = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?new_json=1&aggr=1&cr=1&catZhida=1&p=%d&n=20&w=%s&format=jsonp&inCharset=utf8&outCharset=utf-8'\n get_url = get_url % (p, keyword)\n result = requests.get(get_url).text\n result = json.loads(result[9:-1])\n musicList = result['data']['song']['list']\n musics = []\n for item in musicList:\n albumName = item['album']['title']\n singerName = ''\n for singer in item['singer']:\n singerName += '/' + singer['title']\n singerName = singerName[1:]\n songName = item['title']\n songMid = item['mid']\n mediaMid = item['file']['media_mid']\n albumMid = item['album']['mid']\n musics.append({\n 'singerName': singerName,\n 'albumName': albumName,\n 'songName': songName,\n 'songMid': songMid,\n 'mediaMid': mediaMid,\n 'albumMid': albumMid\n })\n return musics\n\n\ndef getVkey(songMid, mediaMid=None):\n if mediaMid is None:\n mediaMid = songMid\n get_url = 'https://c.y.qq.com/base/fcgi-bin/fcg_music_express_mobile3.fcg?g_tk=5381&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq&needNewCode=0&cid=205361747&uin=0&songmid=%s&filename=M500%s.mp3&guid=9391879250'\n get_url = get_url % (songMid, mediaMid)\n result = requests.get(get_url).text\n result = json.loads(result)\n return result['data']['items'][0]['vkey']\n\n\ndef getMusic(music, fileType=None):\n typeList = [\n 'M500',\n 'M800',\n ]\n if fileType is None:\n fileType = typeList[0]\n elif int(fileType) <= len(typeList):\n fileType = typeList[int(fileType)]\n else:\n fileType = typeList[1]\n music_url = 'http://dl.stream.qqmusic.qq.com/%s%s.mp3?vkey=%s&guid=9391879250&fromtag=27'\n albumImg_url = 'https://y.gtimg.cn/music/photo_new/T002R500x500M000%s.jpg?max_age=2592000'\n songMid = music['songMid']\n albumMid = music['albumMid']\n mediaMid = music['mediaMid']\n vkey = getVkey(songMid, mediaMid)\n if len(vkey) == 0:\n vkey = getVkey('003OUlho2HcRHC')\n music_url = music_url % (fileType, mediaMid, vkey)\n albumImg_url = albumImg_url % albumMid\n return (music_url, albumImg_url)\n\n\ndef downloadFile(music, musicInfo):\n music_url = musicInfo[0]\n musicImg_url = musicInfo[1]\n musicFile_base_url = ''\n musicImgFile_base_url = ''\n if platform.system() == 'Windows':\n musicFile_base_url = os.path.expanduser('~/Music')\n musicImgFile_base_url = os.path.expanduser('~/Pictures')\n else:\n musicFile_base_url = os.path.expanduser('~/Music')\n musicImgFile_base_url = os.path.expanduser('~/Pictures')\n\n musicFile_url = os.path.join(musicFile_base_url, (\n '%s - %s.mp3' % (music['singerName'], music['songName'])))\n musicImgFile_url = os.path.join(musicImgFile_base_url, (\n '%s - %s.jpg' % (music['singerName'], music['albumName'])))\n\n _file = requests.get(music_url, headers=headers)\n if _file.status_code is not 200:\n return False\n with open(musicFile_url, 'wb') as code:\n code.write(_file.content)\n _file = requests.get(musicImg_url)\n with open(musicImgFile_url, 'wb') as code:\n code.write(_file.content)\n return True\n\n\ndef mainFun():\n while(True):\n musics = []\n begin = 0\n p = 0\n keyword = input(\n '请输入要查询的关键字:(%sq或Q%s取消):' % (Color.WARNING, Color.ENDC))\n if keyword == 'q' or keyword == 'Q':\n exit()\n while(True):\n p += 1\n newMusics = getMusicList(keyword, p)\n if len(newMusics) == 0:\n print('%s已到最后一页!%s' % (Color.FAIL, Color.ENDC))\n else:\n musics.extend(newMusics)\n for i in range(begin, len(musics)):\n realI = i\n print(\n '[%s].%s:%s\\t%s:%s\\t%s:%s' % (Color.OKGREEN + str(realI) + Color.ENDC,\n Color.OKGREEN +\n '歌曲' + Color.ENDC,\n Color.BOLD +\n musics[realI]['songName'] +\n Color.ENDC,\n Color.OKGREEN +\n '歌手' + Color.ENDC,\n Color.BOLD +\n musics[realI]['singerName'] +\n Color.ENDC,\n Color.OKGREEN +\n '专辑' + Color.ENDC,\n Color.BOLD +\n musics[realI]['albumName'] +\n Color.ENDC\n ))\n selected = input('请输入要下载的歌曲%s序号%s(支持多选,用%s空格%s分割序号,%s回车%s查看下一页,输入%sq或Q%s重新搜索):' % (\n Color.WARNING, Color.ENDC, Color.WARNING, Color.ENDC, Color.WARNING, Color.ENDC, Color.WARNING, Color.ENDC))\n if selected == 'q' or selected == 'Q':\n break\n elif len(selected) == 0:\n begin = len(musics)\n continue\n selecteds = selected.split(' ')\n for selectIndex in selecteds:\n music = musics[int(selectIndex)]\n music_info = getMusic(music, 0)\n print('歌曲:%s - %s\\n歌曲链接:%s\\n专辑图片:%s' % (Color.OKBLUE + music['singerName'], music['songName'] +\n Color.ENDC, Color.OKBLUE + music_info[0] + Color.ENDC, Color.OKBLUE + music_info[1] + Color.ENDC))\n command = input(\n '输入任意键下载(%sq或Q%s取消):' % (Color.WARNING, Color.ENDC))\n if command == 'q' or command == 'Q':\n continue\n print('开始下载 %s - %s ...' % (Color.OKGREEN + music[\n 'singerName'], music['songName'] + '.mp3' + Color.ENDC))\n isSucc = downloadFile(music, music_info)\n if not isSucc:\n print('%s下载失败,正在重试...%s' % (Color.FAIL, Color.ENDC))\n music_info = getMusic(music, 1)\n print('歌曲:%s - %s\\n歌曲链接:%s\\n专辑图片:%s' % (Color.OKBLUE + music['singerName'], music['songName'] +\n Color.ENDC, Color.OKBLUE + music_info[0] + Color.ENDC, Color.OKBLUE + music_info[1] + Color.ENDC))\n isSucc = downloadFile(music, music_info)\n if not isSucc:\n print('%s下载失败!%s' % (Color.FAIL, Color.ENDC))\n break\n print('%s下载完成!%s' % (Color.OKGREEN, Color.ENDC))\n break\n\n\nif __name__ == '__main__':\n mainFun()\n" }, { "alpha_fraction": 0.549929678440094, "alphanum_fraction": 0.5963431596755981, "avg_line_length": 20.935483932495117, "blob_id": "e5fdd4a2cc3c5aa40b2e0caa99bde4533a7c2204", "content_id": "cd33405d3016442fbffc7e95ee6708906cd273ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 711, "license_type": "no_license", "max_line_length": 136, "num_lines": 31, "path": "/playmusic.py", "repo_name": "scatteredwriter/MyPython", "src_encoding": "UTF-8", "text": "# coding=utf-8\r\n\r\nimport requests\r\nimport os\r\n\r\n\r\nheaders = {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'}\r\n\r\n\r\ndef getmusic():\r\n url = 'http://rodvm.cloudapp.net/playmusic/playmusic.php'\r\n result = requests.post(url, headers=headers)\r\n result = result.text\r\n return result\r\n\r\n\r\ndef playover():\r\n url = 'http://rodvm.cloudapp.net/playmusic/playmusic.php?type=over'\r\n requests.get(url, headers=headers)\r\n\r\n\r\nwhile True:\r\n try:\r\n music = getmusic()\r\n print(music)\r\n if(music):\r\n os.system('mpg123 -q \"%s\"' % music)\r\n playover()\r\n except:\r\n pass\r\n" }, { "alpha_fraction": 0.6237623691558838, "alphanum_fraction": 0.6534653306007385, "avg_line_length": 14.833333015441895, "blob_id": "028489b6a38b171b3d9bab17760ef568c7a19d00", "content_id": "c4094db097a216816d30ec9c5dea896967e71274", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 101, "license_type": "no_license", "max_line_length": 65, "num_lines": 6, "path": "/ConnectInternet/connect.py", "repo_name": "scatteredwriter/MyPython", "src_encoding": "UTF-8", "text": "#coding = utf-8\r\n\r\nimport os\r\n\r\n\r\nos.system(r'cd C:\\Program Files (x86)\\NetKeeper & NetKeeper.exe')\r\n" }, { "alpha_fraction": 0.580152690410614, "alphanum_fraction": 0.6259542107582092, "avg_line_length": 24.871795654296875, "blob_id": "44db29e50e9c95cf972f888860ab844c9ed903ab", "content_id": "c021749ab3a5cc973376bffa3862f030860a3adb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1048, "license_type": "no_license", "max_line_length": 136, "num_lines": 39, "path": "/broadcast.py", "repo_name": "scatteredwriter/MyPython", "src_encoding": "UTF-8", "text": "# coding=utf-8\r\n\r\nimport requests\r\nimport json\r\nimport re\r\nimport os\r\nimport time\r\nimport urllib.request\r\n\r\n\r\nheaders = {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'}\r\n\r\n\r\ndef gettext():\r\n url = 'http://rodvm.cloudapp.net/broadcast/text.php'\r\n result = requests.get(url, headers=headers)\r\n result = result.text\r\n return result\r\n\r\n\r\ndef getVoice(text):\r\n text = urllib.parse.quote(text)\r\n tokenurl = 'https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=Pp1PNrUVnECO7LH7Ki4uQxnx&client_secret=0b1ab78a06e3b571c8e76143849b85d5'\r\n result = requests.get(tokenurl, headers=headers)\r\n result = json.loads(result.text)\r\n url = 'http://tsn.baidu.com//text2audio?tex=%s&tok=%s&lan=zh&ctp=1&cuid=7808972&pit=5&vol=15&per=4' % (\r\n text, result['access_token'])\r\n os.system('mpg123 -q \"%s\"' % url)\r\n\r\n\r\nwhile True:\r\n try:\r\n text = gettext()\r\n print(text)\r\n if(text):\r\n getVoice(text)\r\n except:\r\n pass\r\n" }, { "alpha_fraction": 0.5871559381484985, "alphanum_fraction": 0.5986238718032837, "avg_line_length": 31.538461685180664, "blob_id": "a227b3e0ffc06837ecb5e66a079484e1b0df98ed", "content_id": "86377dfef424525f618cfd607f32f6d904149d61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1426, "license_type": "no_license", "max_line_length": 248, "num_lines": 39, "path": "/studentphoto.py", "repo_name": "scatteredwriter/MyPython", "src_encoding": "UTF-8", "text": "import requests\r\nimport json\r\n\r\n\r\ndef SearchStudent(searchkey):\r\n url = 'http://jwzx.cqu.pt/data/json_StudentSearch.php?searchKey=%s'\r\n url = url % searchkey\r\n response = requests.get(url)\r\n response = json.loads(response.text)\r\n for i in range(len(response['returnData'])):\r\n print('第%i位:姓名:%s\\t年级:%s\\t性别:%s\\t学号:%s\\t班级:%s\\t专业:%s\\t学院:%s' % (\r\n i, response['returnData'][i]['xm'], response['returnData'][i]['nj'], response['returnData'][i]['xb'], response['returnData'][i]['xh'], response['returnData'][i]['bj'], response['returnData'][i]['zym'], response['returnData'][i]['yxm']))\r\n try:\r\n choose = input('请选择一项进行查询:')\r\n if int(choose) > len(response['returnData']) or int(choose) < 0:\r\n print('输入错误!')\r\n exit\r\n\r\n return response['returnData'][int(choose)]['xh']\r\n except:\r\n print('输入错误!')\r\n exit\r\n\r\n\r\ndef GetStudentPhoto(studentId):\r\n url = 'http://jwzx.cqu.pt/showstuPic.php?xh=%s'\r\n print('学生照片:' + url % studentId)\r\n\r\n\r\ndef GetCETPhoto(studentId):\r\n url = 'http://172.22.80.212.cqu.pt/PHOTO0906CET/%s.JPG'\r\n print('CET照片:' + url % studentId)\r\n\r\n\r\nwhile True:\r\n searchkey = input('请输入关键字:')\r\n studentId = SearchStudent(searchkey)\r\n GetStudentPhoto(studentId)\r\n GetCETPhoto(studentId)\r\n" }, { "alpha_fraction": 0.45603182911872864, "alphanum_fraction": 0.5360141396522522, "avg_line_length": 27.012821197509766, "blob_id": "dc9091ef9ad6c09005002e71ad7150d9ea13f00a", "content_id": "37b29b6aff987ccd7894f12b865fb8464e8d189c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2295, "license_type": "no_license", "max_line_length": 152, "num_lines": 78, "path": "/shuapiao.py", "repo_name": "scatteredwriter/MyPython", "src_encoding": "UTF-8", "text": "# coding=utf-8\r\n\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nimport re\r\n\r\naddLists = []\r\ndan = u''\r\ndan2 = u''\r\nindex = -1\r\nheaders = {\r\n 'User-Agent': 'Mozilla/5.0 (Linux; Android 6.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19',\r\n 'Referer': 'http://x3zl.17-g.com/a2/i1/67491503471904/index.asp?id=45774&uid=67491503471904'}\r\n\r\n\r\ndef getAddress():\r\n url = 'http://www.xicidaili.com/nt/'\r\n html = requests.get(url, headers=headers)\r\n html = html.text\r\n address = re.findall(r'(\\d+\\.\\d+\\.\\d+\\.\\d+)</td>\\s*<td>(\\d+)</td>', html)\r\n for tr in address:\r\n addLists.append({'http': tr[0] + ':' + tr[1]})\r\n\r\n\r\ndef getDan():\r\n while True:\r\n try:\r\n url = 'http://x3zl.17-g.com/a2/zhulic.asp?id=45774&uid=67491503471904'\r\n html = requests.get(url, headers=headers)\r\n html = html.text\r\n dans = re.findall(\r\n r'/a2/plugin.asp\\?id=45774&uid=67491503471904&dan=(\\d+)&dan2=(\\d+)\\'', html)\r\n dan = dans[0][0]\r\n dan2 = dans[0][1]\r\n print dan, dan2\r\n return(dan, dan2)\r\n except:\r\n print u'获取dan失败!'\r\n\r\n\r\ndef shuaPiao((dan, dan2), ip):\r\n try:\r\n url = 'http://x3zl.17-g.com/a2/plugin.asp?id=45774&uid=67491503471904&dan={0}&dan2={1}'\r\n url = url.replace('{0}', dan).replace('{1}', dan2)\r\n result = requests.get(url, headers=headers,\r\n proxies=ip, timeout=20)\r\n print result.text\r\n except:\r\n pass\r\n\r\n\r\ndef getIPtxt():\r\n txt = open(u'下载.txt')\r\n for line in txt:\r\n addLists.append({'https': line.replace('\\n', '')})\r\n\r\n\r\ndef getRanking():\r\n try:\r\n url = 'http://x3zl.17-g.com/a2/zhulix.asp?id=45774&uid=67491503471904'\r\n result = requests.get(url, headers=headers)\r\n result = result.text\r\n zhuli = re.findall(\r\n u\">(\\d+) \", result)\r\n ranking = re.findall(\r\n u\">(\\d+)</div>\", result)\r\n print u'助力:' + zhuli[0] + u' 排名:' + ranking[0] + u' 热度:' + ranking[1] + '\\n'\r\n except:\r\n pass\r\n\r\n\r\n# getAddress()\r\ngetIPtxt()\r\nprint addLists\r\ngetRanking()\r\nfor ip in addLists:\r\n shuaPiao(getDan(), ip)\r\ngetRanking()\r\n" }, { "alpha_fraction": 0.6909090876579285, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 20, "blob_id": "1608eb5ecbc6904fa357a3e1300597f1a457544b", "content_id": "d48aea965e69846d1e73301cc387934b2e8313c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 110, "license_type": "no_license", "max_line_length": 69, "num_lines": 5, "path": "/test.py", "repo_name": "scatteredwriter/MyPython", "src_encoding": "UTF-8", "text": "# coding=utf-8\r\nimport subprocess\r\n\r\n\r\nsubprocess.Popen(r'C:\\Program Files (x86)\\NetKeeper\\NetKeeper.exe',0)\r\n" }, { "alpha_fraction": 0.5269784331321716, "alphanum_fraction": 0.5845323801040649, "avg_line_length": 21.16666603088379, "blob_id": "952308515eaeb9c59faa44a0b33b78f771088e6e", "content_id": "87fba37f93166c4cb5882a39c0f8b913659cbf64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 556, "license_type": "no_license", "max_line_length": 136, "num_lines": 24, "path": "/changemusic.py", "repo_name": "scatteredwriter/MyPython", "src_encoding": "UTF-8", "text": "# coding=utf-8\r\n\r\nimport requests\r\nimport os\r\n\r\n\r\nheaders = {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'}\r\n\r\n\r\ndef changemusic():\r\n url = 'http://rodvm.cloudapp.net/playmusic/changemusic.php'\r\n result = requests.post(url, headers=headers)\r\n result = result.text\r\n if(result):\r\n os.system(\r\n 'kill $(ps aux | grep -m 2 %s | awk \\'{print $2}\\')' % result)\r\n\r\n\r\nwhile True:\r\n try:\r\n changemusic()\r\n except:\r\n pass\r\n" }, { "alpha_fraction": 0.609929084777832, "alphanum_fraction": 0.6418439745903015, "avg_line_length": 41.38461685180664, "blob_id": "51bf665a86c224d5c9a900c97d091485adab5ff9", "content_id": "3528bd0d058c5d4c4cc4427fa4d0d3b70a084881", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 564, "license_type": "no_license", "max_line_length": 70, "num_lines": 13, "path": "/ConnectInternet/dialer.py", "repo_name": "scatteredwriter/MyPython", "src_encoding": "UTF-8", "text": "import requests\r\nimport json\r\nusername = \"1H<:EI 5617308362964@cqupt\"\r\nusername = \"%0d\" + username\r\nlogin_json = {\"method\": \"do\", \"login\": {\"password\": \"ubc8e6wuLTefbwK\"}}\r\nresponse = requests.post('http://192.168.1.1', json=login_json).text\r\nresponse = json.loads(response)\r\nprint(response['stok'])\r\ndail_url = 'http://192.168.1.1/stok=%s/ds' % response['stok']\r\ndail_json = {\"protocol\": {\"wan\": {\"wan_type\": \"pppoe\"}, \"pppoe\": {\r\n \"username\": username, \"password\": \"230279\"}}, \"method\": \"set\"}\r\nresponse = requests.post(dail_url, json=dail_json).text\r\nprint(response)\r\n" } ]
12
tonyt1272/Build_a_Blog
https://github.com/tonyt1272/Build_a_Blog
11a138f30b91297d113b105356a551cfd26fb7c7
b3b96d93a3bc772e596d1af71b2b668ac9168f8d
12835b9c7284c405a7bb86de275fefd2d5788352
refs/heads/master
2020-04-12T23:49:41.704226
2018-12-24T19:58:57
2018-12-24T19:58:57
162,831,270
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6705706715583801, "alphanum_fraction": 0.6734412908554077, "avg_line_length": 34.84362030029297, "blob_id": "b5c7ca8c8a63a603076debbcb9a326c530208f53", "content_id": "d3bbb453e120487097859fe2b99963126fb8a08c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8709, "license_type": "no_license", "max_line_length": 121, "num_lines": 243, "path": "/main.py", "repo_name": "tonyt1272/Build_a_Blog", "src_encoding": "UTF-8", "text": "from flask import Flask, request, redirect, render_template, session, flash #Imports for Flask server\nfrom datetime import datetime\nimport re\n\nfrom flask_sqlalchemy import SQLAlchemy #Importing necessary sqlalchemy tools for using\n\t\t\t\t\t\t\t\t\t\t#the SQL database, the SQLAlchemy class is imported\n\t\t\t\t\t\t\t\t\t\t#from the flask_sqlalchemy module.\napp = Flask(__name__)\napp.config['DEBUG'] = True\n\n##Configures the application to connect to the database\n## \t\t\t\t\t\t\t\t\ttypedb\tdrive\t\tusername:password\tserver\tport\tdbname\t\t\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://build-a-blog:MyNewPass@localhost:8889/build-a-blog'\napp.config['SQLALCHEMY_ECHO'] = True\ndb = SQLAlchemy(app)\t#The constructor function recievs the app object and creates a \n\t\t\t\t\t\t#database object\napp.secret_key= 'test123'\n\nclass Blog(db.Model): # Creating persistent class that represents blog posts within the application\n\t\t\t\t\t\t# This class inherits db.Model class which was created above. The .Model part\n\t\t\t\t\t\t# is a method generated by the SQLAlchemy() constructor\n\n\tid = db.Column(db.Integer, primary_key=True)\t#set to auto create primary keys for the data entry\n\ttitle = db.Column(db.String(120))\t\t\t\t#creating a column holds a string 120 max length\n\tbody = db.Column(db.String(5000))\t\t\t\t#create the blog text attribute\n\towner_id = db.Column(db.Integer, db.ForeignKey('user.id')) #links to a primary key 'user.id'\n\t\t\t\t\t\t\t\t\t\t\t\t\t#Creating owner id column that is integer type\n\t\t\t\t\t\t\t\t\t\t\t\t\t#and its value will be the the 'user.id'\n\t\t\t\t\t\t\t\t\t\t\t\t\t#associated with the owner passed to Task\t\t\t\t\n\tpub_date = db.Column(db.DateTime)\n\thidden = db.Column(db.Boolean)\n\n\tdef __init__(self,title,body,owner):\t\t\t#constructor that creates an instance\n\t\tself.title = title \t\t\t\t\t\t#set the input title to the title value of the object\t\t\t\t\n\t\tself.body = body\t\t\t\t\t\t\t#set the body of the object to the entered string\n\t\tself.owner = owner\t\t\t\t\t\t\t#owner is a user object for the blog post\n\t\tpub_date = datetime.utcnow()\n\t\tself.pub_date = pub_date\n\t\tself.hidden = False\n\nclass User(db.Model):\n\n\tid = db.Column(db.Integer, primary_key=True)\n\temail = db.Column(db.String(120), unique=True) #unique=True, Not possible to add two\n\t\t\t\t\t\t\t\t\t\t\t\t\t#different recotds with the same email\n\tpassword = db.Column(db.String(120))\n\tblogs = db.relationship('Blog', backref='owner')#This is NOT a column, it is a relationship\n\t\t\t\t\t\t\t\t\t\t\t\t\t#that populates tasks list with task objects from the Task \n\t\t\t\t\t\t\t\t\t\t\t\t\t#table such that the owner property is equal to this\n\t\t\t\t\t\t\t\t\t\t\t\t\t#specific user object. \n\tdef __init__(self, email, password):\n\t\tself.email = email\n\t\tself.password = password\n##-----------------------------------------------------------------------------------------\n\n## user email validation\ndef is_email(string):#Regular expression for email validation\n\tpattern = re.compile(r'^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$')\n\tvalid_email = pattern.findall(string)\n\tif valid_email:\n\t\treturn True\n\telse:\n\t\treturn False\n##-------------\n\n##login wall\[email protected]_request\t#special decorator tells flask to run this function before any request\ndef require_login():\n\tallowed_routes = ['login', 'register']\n\tprint(session)\n\tif request.endpoint not in allowed_routes and 'email' not in session:\n\t\treturn redirect('/login')\n##-------------\n\n##Main page\[email protected](\"/\")\ndef index():\n\tencoded_error = request.args.get(\"error\")\n\tuser = User.query.filter_by(email=session['email']).first()\n\tuser_posts = Blog.query.filter_by(owner=user, hidden=False).order_by(Blog.pub_date.desc()).all()\n\thidden_user_posts = Blog.query.filter_by(owner=user, hidden=True).order_by(Blog.pub_date.desc()).all()\n\treturn render_template('/index.html',title=\"Build a Blog\",user_posts=user_posts,\n\t\thidden_user_posts=hidden_user_posts)\n##----------\n\n##Register new users\[email protected](\"/register\", methods=['GET', 'POST'])\ndef register():\n\tif request.method == 'POST':\n\t\temail = request.form['email']\n\t\tpassword = request.form['password']\n\t\tverify = request.form['vpassword']\n\n\t\tif not is_email(email):\n\t\t\tflash('{} is not a valid email address'.format(email),'error')\n\t\t\treturn redirect('/register')\n\n\t\tif password != verify:\n\t\t\tflash('password and verification do not match.','error')\n\t\t\treturn render_template('register.html',form_email=email,title=\"Build a Blog Registration\")\n \n\t\texisting_user = User.query.filter_by(email=email).first()\n\t\tif existing_user:\n\t\t\tflash('user with email {} already exists.'.format(email),'error')\n\t\t\treturn redirect('/register')\n \n\t\tuser = User(email=email, password=password)\n\t\tdb.session.add(user)\n\t\tdb.session.commit()\n\t\tsession['email'] = user.email\n\t\treturn redirect(\"/\")\n\telse:\n\t\treturn render_template('register.html', title=\"Build a Blog Registration\")\n##-------------------\n\n##Enter blog post\[email protected]('/entry', methods = ['POST', 'GET'])\ndef entry():\n\tuser = User.query.filter_by(email=session['email']).first() #match current userr in db\n\ttitle_error=None\n\tbody_error=None\n\tentry_error=False\n\tif request.method == 'POST':\n\t\tnew_title = request.form['new_title']\n\t\tnew_entry = request.form['new_entry']\n\n\t\tif not new_title:\n\t\t\tentry_error = True\n\t\t\ttitle_error=\"Please enter a title for your post\"\n\t\t\t\n\t\tif not new_entry:\n\t\t\tentry_error = True\n\t\t\tbody_error=\"Please enter your blog post in the 'New entry' form above\"\n\t\t\t\n\t\tif entry_error == True:\n\t\t\treturn render_template('blog_entry.html',title=\"Add a Blog Entry\",\n\t\t\t\ttitle_error=title_error, body_error=body_error, blog_title=new_title, body=new_entry)\n\n\t\tblog = Blog(new_title, new_entry, user)\n\t\tpost_body = blog.body \n\t\tpost_title = blog.title\n\t\tdb.session.add(blog)\n\t\tdb.session.commit()\n\t\tpost_id = blog.id #the id gets assigned after the commit\n\t\treturn render_template(\"display_entry.html\",title=post_title, post_body=post_body, post_id=post_id, post_hidden=False) \n\t\t\n\n\telse:\n\t\treturn render_template('blog_entry.html',title=\"Add a Blog Entry\")\n##--------------\n\n##Display entry\[email protected]('/display_entry', methods = ['GET'])\ndef display_entry():\n\tpub_date = request.args.get('date_time')\n\tuser = User.query.filter_by(email=session['email']).first()\n\towner_id = user.id\n\tpost = Blog.query.filter_by(owner_id=owner_id, pub_date=pub_date).first()\n\ttitle = post.title\n\tpost_body = post.body\n\tpost_id = post.id\n\tpost_hidden = post.hidden\n\treturn render_template(\"display_entry.html\",title=title, post_body=post_body, post_id=post_id, post_hidden=post_hidden) \n##--------------\n\n##Existing user login\[email protected]('/login', methods = ['POST','GET'])\ndef login():\n\t## Delete current session before allowing another login\n\tif 'email' in session:\n\t\tdel session['email']\n\t##-----------------\n\tif request.method == 'POST':\n\t\temail = request.form['email']\n\t\tpassword = request.form['password']\n\t\tuser = User.query.filter_by(email=email).first() #.first() returns the first user object\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t#If no email match, returns python None\t\t\t\n\t\tif user and user.password == password:\t\t#If user exists and user.password = password entered\n\t\t\tsession['email'] = email #session object is a dictionary, here it is used to hold the\n\t\t\t\t\t\t\t\t\t #the user's email address\n\t\t\treturn redirect('/')\n\t\telse:\n\t\t\tflash('User password incorrect or user does not exist', 'error')\n\n\treturn render_template('login.html', title=\"Build a Blog Log in\")\n##-----------\n\n##Hide post\[email protected]('/hide', methods= ['POST'])\ndef hide():\n\tpost_id = request.form['post_id']\n\thide_post = Blog.query.get(post_id)\n\thide_post.hidden = True\n\tdb.session.add(hide_post)\n\tdb.session.commit()\n\treturn redirect('/')\n##-----------\n\n##unHide post\[email protected]('/unhide', methods= ['POST'])\ndef unhide():\n\tpost_id = request.form['post_id']\n\tunhide_post = Blog.query.get(post_id)\n\tunhide_post.hidden = False\n\tdb.session.add(unhide_post)\n\tdb.session.commit()\n\treturn redirect('/')\n##-----------\n\n##Delete post\[email protected]('/delete', methods= ['POST'])\ndef delete():\n\tif 'be_sure' not in request.form: #verifying users intent to delete\n\t\tflash('Are you sure? If you are, click delete again.','error')\n\t\tflash(\"If you have changed your mind just go back to the Main Blog Page.\",'error')\n\t\tbe_sure = True\n\t\tpost_id = request.form['post_id']\n\t\tpost = Blog.query.get(post_id)\n\t\ttitle = post.title\n\t\tpost_body = post.body\n\t\tpost_id = post.id\n\t\tpost_hidden = post.hidden\n\t\treturn render_template(\"display_entry.html\",title=title, \n\t\t\tpost_body=post_body, post_id=post_id, post_hidden=post_hidden, be_sure = be_sure)\n\n\tpost_id = request.form['post_id']\n\tdelete_post = Blog.query.get(post_id)\n\tdb.session.delete(delete_post)\n\tdb.session.commit()\n\treturn redirect('/')\n##------------\n\n##log out\[email protected]('/logout')\ndef logout():\n\tif 'email' in session:\n\t\tdel session['email']\n\n\treturn redirect('/')\n##---------\n\nif __name__ == '__main__':\n\tapp.run()" } ]
1
jewkesy/legendary-happiness
https://github.com/jewkesy/legendary-happiness
54adcc13e73274612918f66d2b90f7de5ea6e8ef
bd70b86077e2e22f7b362af91c8f72cf13900182
b876bef2314bb20267adb2e3aa43b053c081e4f3
refs/heads/master
2021-01-10T09:06:27.931953
2016-02-04T12:15:09
2016-02-04T12:15:09
50,835,035
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6423051953315735, "alphanum_fraction": 0.645524799823761, "avg_line_length": 26.24561309814453, "blob_id": "8144cbd841ecc104c6884ac9c65606d90a046a25", "content_id": "43c2d7495c06a27851a752d419b1ac23603e5a73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3106, "license_type": "no_license", "max_line_length": 99, "num_lines": 114, "path": "/lib/ruby/metabolizer.rb", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "# This file is called metabolizer.rb. It contains the class Metabolizer.\n\nrequire 'Pool'\ninclude Plasma\n\n# Metabolizer metabolizes proteins from a pool based on matching descrips. The\n# descrips may include :anything to allow the metabolizer to match any value for\n# that descrip.\n# \n# ==== Usage\n#\n# hose = Pool.participate('poolname')\n# m = Metabolizer.new(hose)\n# m.appendMetabolizer(['descrip1', 'descrip2', :anything]) do |p|\n# # process protein p here\n# end\n# m.metabolize(0.1)\nclass Metabolizer\n attr_accessor :gang\n attr_accessor :quit\n # Creates a new Metabolizer.\n # ==== Arguments \n # * +hoses+ - One or more pool name strings. A hose will be created for each\n # pool name.\n # \n # ==== Returns \n # * A new Metabolizer.\n def initialize(*hoses)\n @gang = HoseGang.new\n hoses.each { |hose| @gang.add_tributary hose }\n @metabolizers = []\n @quit = false\n end\n\n # Stops the metabolize loop.\n def stop\n @quit = true\n end\n\n # Gets a hose with the name matching a pool name.\n # ==== Arguments \n # * +name+ - Name of the pool\n # \n # ==== Returns \n # A Hose.\n def getHose(name)\n @gang.tributaries.detect { |x| x.pool_name == name }\n end\n\n # Adds a metabolizer.\n # ==== Arguments \n # * +descrips+ - Descrips to match for the metabolizer\n # * +block+ - Code block of the metabolizer\n # \n # ==== Returns \n # * A Hose.\n def appendMetabolizer(descrips, &block)\n @metabolizers << [ descrips, block ]\n end\n\n # Matches two descrip values.\n # ==== Arguments \n # * +expected+ - Expected descrip value. The value of :anything will match any value positively.\n # * +descrips+ - Descrip value to match\n # \n # ==== Returns \n # true or false\n def descrips_match(expected, descrips)\n begin\n expected.zip(descrips).collect {\n |x, y| (x == :anything || x == y) }.inject(true) {\n |x, y| x && y }\n rescue TypeError => te\n puts \"TypeError: #{te}\"\n end\n end\n\n # Helper method for metabolizer. This method would not be directly used. \n def metabolize1(protein)\n d = protein.descrips.emit\n @metabolizers.each do |descrips, block|\n block.call protein if descrips_match(descrips, d)\n break if @quit\n end\n end\n\n # This method begins metabolizing proteins. This method does not return until\n # stop is called.\n # ==== Arguments \n # * +timeout+ - Wait value that the metabolize loop uses to sleep. Defaults to 1.0 second.\n # * +startup_block+ - Optional code block to execute at the start of this method.\n def metabolize(timeout = 1.0, &startup_block)\n startup_block.call(self) if startup_block\n until @quit do\n protein = @gang.next timeout\n metabolize1(protein) if protein\n end\n end\nend\n\n# Use this method to trap the SIGINT, or System Exit signal.\n# ==== Arguments \n# * +metabolizer+ - Metabolizer to stop\n# * +block+ - Optional code block to execute at the start of this method.\n# ==== Usage\n# trap_sigint(z) do\n# puts \"Ending daemon\"\n# end\ndef trap_sigint(metabolizer, &block)\n trap 'SIGINT', proc {\n block.call if block\n metabolizer.stop\n }\nend\n" }, { "alpha_fraction": 0.6749622821807861, "alphanum_fraction": 0.6794871687889099, "avg_line_length": 21.86206817626953, "blob_id": "690dbddcbddf0a2fb06b121669a2190c3d6d6b11", "content_id": "5e18ecdb82670b511bba5094f058fdeeef8bffcb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1326, "license_type": "no_license", "max_line_length": 136, "num_lines": 58, "path": "/lib/ruby/Protein.rb", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "require 'Slaw'\nrequire 'base64'\n\n\nmodule Plasma\n\n# A protein is the message envelope in Plasma. A protein is composed of:\n# descrips:: An Array of message subject which can be used in filtering.\n# ingests:: A Hash that is the message payload. The hash can be arbitrarily complex.\n# rude_data:: Completely unstructured binary data. This can be absolutely anything.\nclass Protein < Slaw\n attr_accessor :hose\n attr_accessor :index\n attr_accessor :timestamp\n\n def initialize(descrips, ingests, rude=\"\", _construct_type=:protein)\n super([descrips,ingests,rude], _construct_type)\n end\n\n # Returns the list of descrips\n def descrips\n _c_slaw_protein_descrips\n end\n\n # returns the Hash of ingests\n def ingests\n _c_slaw_protein_ingests\n end\n\n # returns the rude data\n def rude_data\n _c_slaw_protein_rude_data\n end\n\n # identity: returns this object\n def emit\n self\n end\n\n # Creates and returns a protein from a JSON object. The keys in the JSON object should be descrips, ingests, and optionally rude_data.\n def self.json_create(o)\n des = o['descrips']\n ing = o['ingests']\n rude = \"\"\n if des.nil?\n des = []\n end\n if ing.nil?\n ing = {}\n end\n if o.has_key?(\"rude_data\")\n rude = Base64.decode64(o[\"rude_data\"])\n end\n Protein.new(des, ing, rude)\n end\nend\n\nend\n" }, { "alpha_fraction": 0.5947349071502686, "alphanum_fraction": 0.5993949770927429, "avg_line_length": 26.798864364624023, "blob_id": "4c41fdc7115d0e492fa06d944f7c9db69ffd574e", "content_id": "70f214fc8c4f8fb3d6f7026128374fef73c5299f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 24472, "license_type": "no_license", "max_line_length": 123, "num_lines": 880, "path": "/lib/ruby/Slaw.rb", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# ¡¡¡¡¡¡¡¡¡ IF YOU WANT TO USE JSON, YOU NEED THE JSON GEM INSTALLED !!!!!!!!!\nrequire 'rubyPlasma'\nrequire 'base64'\n\n#---\n# notes -- fix:\n#\n# errors need to be clearer for things like too few arguments to a\n# v234 constructor (or implicit constructor from inside a list). not\n# sure how to do this without slowing things down.\n#\n# we probably need v2? v3? and v4? introspectors\n#\n# there are not vXNNXXX_array kernel module constructors\n#\n#+++\n\nmodule Plasma\n\nclass SlawTypeNoMethodError < NoMethodError; end\nclass SlawConsNeedsTwoArgumentsError < StandardError; end\nclass SlawTypeTagError < StandardError; end\nclass UserError < StandardError; end\n\n# The following two exceptions are never raised anymore (bug 1871),\n# but we're still going to define them, in case there is existing\n# code that uses them in a rescue clause.\nclass ProteinDescripsAreNotListError < StandardError; end\nclass ProteinIngestsAreNotMapError < StandardError; end\n\n# In c/c++ plasma, Slaw is a wrapper for all g-speak supported data types. It is necessary because of c's strong typing.\n# In a duck-typed language like Ruby where all classes descend from Object, the concept of Slaw is not necessary. However,\n# as these are bindings for c plasma, we do need to deal with Slaw here and there. For the most part, when using the #Pool,\n# #Hose, & #Protein APIs, you can safely ignore Slaw.\nclass Slaw\n\n include Enumerable\n\n protected\n attr_reader :_c_slaw, :_container\n\n public\n attr_reader :type_tag\n\n def initialize (value_, type=nil)\n @ruby_value = value_\n\n _c_initialize\n\n if type == :_derive_type_tag_from_c_slaw\n # our c-level constructor code is obligated to set the type tag\n # after we return from new()\n elsif value_.is_a? Slaw\n @_c_slaw = value_._c_slaw\n @type_tag = value_.type_tag\n # Yo, this is important! If you don't copy this, then the underlying\n # C slaw can be freed when the original Slaw is garbage collected.\n # Resulting in at least incorrect results, and sometimes segfaults.\n # See _new_slaw_from_c_slaw() in rubyPlasma.c.\n # This is tested by test_container in slaw-tests.rb.\n @_container = value_._container\n else\n if type\n if !(type.is_a?(Symbol) ||\n (value_.is_a?(Array) && type.is_a?(Array) &&\n type.all? {|x| x.is_a?(Symbol)}))\n raise SlawTypeTagError,\n \"type tag must be a :symbol or an [:array, :of, :symbols]\"\n else\n @type_tag = type\n end\n else\n @type_tag = _ruby_auto_type_tag\n end\n _freeze\n end\n # and throw away our passed-in value to ensure consistency between\n # values pulled out of slawx generated from ruby and slawx\n # generated from c-slawx\n @ruby_value = nil\n end\n\n protected\n\n ENCODING_UTF8 = begin\n Encoding.find(\"UTF-8\")\n rescue NameError\n # No Encoding class in Ruby 1.8\n nil\n end\n\n public\n\n def Slaw._ensure_utf8(str)\n # C plasma assumes all strings are utf8. On ruby 1.8, there's not\n # much we can do about this, because 1.8 doesn't keep track of the\n # encoding of a string. But in 1.9, we can find out the encoding\n # and transcode to UTF-8 if necessary.\n if (str.respond_to?(:encoding) and\n !(ENCODING_UTF8 == str.encoding or str.ascii_only?))\n return str.encode(ENCODING_UTF8)\n else\n return str\n end\n end\n\n # Constructs a slaw from YAML and returns it.\n def Slaw.from_yaml (yaml)\n _c_slaw_from_string _ensure_utf8(yaml)\n end\n\n # Merges all passed in map objects into one, and returns the result.\n def Slaw.merge_maps(*maps)\n if ! maps.all? {|x| x.map?}\n raise ArgumentError, \"can only merge slaw maps\"\n end\n _c_merge_maps(*maps)\n end\n\n # Takes arguments in pairs, which should be a slaw list and a range\n # of elements for that list, and creates a new list from them\n # e. g. Slaw.recombobulate_lists([list1, 0..1], [list2, 0..9], [list1, 2..3])\n def Slaw.recombobulate_lists(*args)\n a = Array.new\n args.each do |list, range|\n if not list.list?\n raise ArgumentError, \"first argument of each pair must be slaw list\"\n end\n if not range.respond_to?(:each)\n raise ArgumentError, \"second argument of each pair must be a range\"\n end\n range.each {|n| a.push(list.nth_slaw(n))}\n end\n return Slaw.new(a)\n end\n\n # Concatenates all passed in list objects, and returns the result.\n def Slaw.concatenate_lists(*lists)\n if ! lists.all? {|x| x.list?}\n raise ArgumentError, \"can only concatenate slaw lists\"\n end\n pairs = lists.map {|x| [x, 0...x.count]}\n Slaw.recombobulate_lists(*pairs)\n end\n\n # Returns the PORO (Plain Old Ruby Object) version of this Slaw.\n def emit\n @ruby_value ||= _unpack(self)\n end\n\n # Returns the binary data contained within this slaw. If the object is a Protein, returns the #rude_data.\n def emit_binary\n case @type_tag\n when :unt8_array then return _c_slaw_value_as_string\n when :int8_array then return _c_slaw_value_as_string\n when :protein then return _c_slaw_protein_rude_data\n end\n raise SlawTypeNoMethodError,\n \"emit_binary can only be called on int8 or unt8 arrays, or a protein\"\n end\n\n # Alias for #count\n def size\n count\n end\n\n # Returns the size of the Slaw.\n #\n # * Returns 1 if an atomic type\n # * Returns 2 if a cons\n # * Returns number of elements if a List\n # * Returns number of elements + number of keys if a Map.\n def count\n if nil? or atomic?\n return 1\n elsif list? || map?\n return _c_slaw_list_count if @_c_slaw\n elsif array?\n return _c_slaw_numeric_array_count if @_c_slaw\n elsif cons?\n return 2\n end\n end\n\n # Iterate over all elements. Accepts a block.\n def each\n if list? || map? || array? || vect?\n return emit.each { |e| yield e }\n end\n raise SlawTypeNoMethodError,\n \"each can only be called on a list or map slaw\"\n end\n\n # Returns the keys when this Slaw is a map.\n def keys\n if map?\n return emit.keys\n end\n raise SlawTypeNoMethodError,\n \"keys can only be called on a map slaw\"\n end\n\n # Return the values with this Slaw is a map.\n def values\n if map?\n return emit.values\n end\n raise SlawTypeNoMethodError,\n \"values can only be called on a map slaw\"\n end\n\n # Returns the first element of a cons pair.\n def car\n if cons?\n return _c_slaw_cons_car\n end\n raise SlawTypeNoMethodError,\n \"car can only be called on a cons slaw\"\n end\n\n # Returns the second element of a cons pair.\n def cdr\n if cons?\n return _c_slaw_cons_cdr\n end\n raise SlawTypeNoMethodError,\n \"cdr can only be called on a cons slaw\"\n end\n\n\n # Returns the nth element of a list or map as an \"emitted\" result.\n #\n # If you want a Slaw, you should call #nth_slaw (for lists)\n # of find_slaw (for maps).\n def [](n)\n if list? || map?\n return emit[n]\n elsif array? || vect?\n # fix: this should probably be in c\n return emit[n]\n end\n return nil\n end\n\n # Returns the nth element of a list or map. See also #[].\n def nth_slaw(n)\n if list? || map?\n if (n < 0)\n n = count + n\n end\n return _c_slaw_list_nth(n)\n end\n raise SlawTypeNoMethodError,\n \"nth_slaw can only be called on a list or map slaw\"\n end\n\n\n def each_slaw\n count.times {|n| yield nth_slaw(n)}\n end\n\n\n # Returns (as a Slaw) the value associated with a key in a\n # slaw map. Returns nil (the Ruby nil, not a nil Slaw) if not found.\n def find_slaw(findme)\n if not map?\n raise SlawTypeNoMethodError, \"find_slaw can only be called on a map slaw\"\n end\n each_slaw do |s|\n key = s.car\n if (key == findme)\n return s.cdr\n end\n end\n nil\n end\n\n # Returns true if this is a nil Slaw.\n def nil?\n _c_slaw_is_nil\n end\n\n # Returns true if an atomic type.\n def atomic?\n (!array? && !vect? && !composite?)\n end\n\n # Returns true if an array type.\n def array?\n _c_slaw_is_array\n end\n\n # Returns true if a composite type (list, map, protein, or cons).\n def composite?\n list? || map? || protein? || cons?\n end\n\n # Returns true if a cons type.\n def cons?\n _c_slaw_is_cons\n end\n\n # Returns true if a list type.\n def list?\n _c_slaw_is_list\n end\n\n # Returns true if a map type.\n def map?\n _c_slaw_is_map\n end\n\n # Returns true if a protein.\n def protein?\n @type_tag == :protein\n end\n\n # Returns true if a boolean.\n def boolean?\n _c_slaw_is_boolean\n end\n\n # Returns true if a vector.\n def vect?\n _c_slaw_is_vect\n end\n\n # Returns true if a string.\n def string?\n @type_tag == :string\n end\n\n # Returns true if a numeric type.\n def numeric?\n _c_slaw_is_numeric\n end\n\n # Test whether the value of two Slaw are equal.\n def ==(other)\n if (other.is_a? Slaw)\n return _c_slaw_equals(other)\n end\n e = emit\n if (e.equal?(self))\n # For proteins and conses, emit just returns the slaw unchanged.\n # If we call == on that, we will just go into a horrible infinite\n # loop. So, don't so that.\n return false\n else\n return e == other\n end\n end\n\n # Test whether the two Slaw have the same value and are of the same type.\n def eql?(other)\n if (other.is_a? Slaw)\n return _c_slaw_equals(other)\n end\n return false\n end\n\n # Returns the underlying hash of this Slaw when it is a Map.\n def hash\n @_hash ||= _c_slaw_hash\n end\n\n # Comparison operator\n def <=>(other)\n return _c_slaw_spaceship(other)\n end\n\n # Returns a new list created by appending the list other to this list Slaw.\n def +(other)\n if not list?\n raise SlawTypeNoMethodError, \"+ can only be called on a list slaw\"\n end\n if not other.list?\n raise ArgumentError, \"+ can only be called on a list slaw\"\n end\n a = Array.new\n self.count.times {|n| a.push(self.nth_slaw(n))}\n other.count.times {|n| a.push(other.nth_slaw(n))}\n return Slaw.new(a)\n end\n\n # Returns a new map created by merging the map other with this map Slaw.\n def merge(other)\n if not map?\n raise SlawTypeNoMethodError, \"merge can only be called on a map slaw\"\n end\n if not other.map?\n raise ArgumentError, \"merge can only be called on a map slaw\"\n end\n Slaw.merge_maps(self, other)\n end\n\n # Returns a new map based on this Slaw map, with {key => value} added to the map.\n def map_put(key, value)\n if not map?\n raise SlawTypeNoMethodError, \"map_put can only be called on a map slaw\"\n end\n Slaw.merge_maps(self, Slaw.new({key => value}))\n end\n\n # Returns a new map based on this Slaw map, less the k-v pair keyed by key.\n def map_remove(key)\n if not map?\n raise SlawTypeNoMethodError, \"map_remove can only be called on a map slaw\"\n end\n a = Array.new\n count.times do |n|\n s = nth_slaw(n)\n car = s.car\n if (car != key)\n cdr = s.cdr\n a.push(car)\n a.push(cdr)\n end\n end\n Slaw.new(a, :map)\n end\n\n # Returns a list based on this Slaw list, with elem added to the end of the list.\n def append(elem)\n if not list?\n raise SlawTypeNoMethodError, \"append can only be called on a list slaw\"\n end\n return self + Slaw.new([elem])\n end\n\n # Returns a list based on this Slaw list, with elem added to the front of the list.\n def prepend(elem)\n if not list?\n raise SlawTypeNoMethodError, \"prepend can only be called on a list slaw\"\n end\n return Slaw.new([elem]) + self\n end\n\n # Returns a list based on this Slaw list, with list inserted in this list at position index.\n def insert_list(index, list)\n if not list?\n raise SlawTypeNoMethodError, \"insert_list can only be called on a list slaw\"\n end\n if not list.list?\n raise ArgumentError, \"insert_list can only be called on a list slaw\"\n end\n Slaw.recombobulate_lists([self, 0...index],\n [list, 0...list.count],\n [self, index...self.count])\n end\n\n # Returns a new list based on this Slaw list, with the variable length parameter list inserted at position index.\n def insert(index, *elems)\n if not list?\n raise SlawTypeNoMethodError, \"insert can only be called on a list slaw\"\n end\n insert_list(index, Slaw.new([*elems]))\n end\n\n # Returns a new list based on this list, with elements removed at index_or_range\n def list_remove(index_or_range)\n if not list?\n raise SlawTypeNoMethodError, \"list_remove can only be called on a list slaw\"\n end\n if index_or_range.respond_to?(:integer?) and index_or_range.integer?\n index_or_range = index_or_range..index_or_range\n end\n if !index_or_range.is_a?(Range)\n raise ArgumentError, \"argument must be an integer or a range\"\n end\n b = index_or_range.begin\n e = index_or_range.end\n if not index_or_range.exclude_end?\n # now e is always excluded\n e = e + 1\n end\n Slaw.recombobulate_lists([self, 0...b],\n [self, e...self.count])\n end\n\n # Returns the underlying Array when this Slaw is a List or Array.\n def to_ary\n if list? || array?\n return emit\n end\n raise SlawTypeNoMethodError,\n \"to_ary can only be called on a list or array slaw\"\n end\n\n # Returns the underlying Hash when this Slaw is a Map or Hash.\n def to_hash\n if map?\n return emit\n end\n raise SlawTypeNoMethodError,\n \"to_hash can only be called on a hash slaw\"\n end\n\n # Returns the underlying string when this Slaw is a string.\n def to_s\n if string?\n return emit\n end\n _c_slaw_to_string.emit\n end\n\n # Returns the underlying string when this Slaw is a string.\n # Raises #SlawTypeNoMethodError if not a string.\n def to_str\n if string?\n return emit\n end\n raise SlawTypeNoMethodError,\n \"to_str can only be called on a string slaw\"\n end\n\n # Returns the integer value of this Slaw. Safe to call on strings.\n def to_i\n if string? || (atomic? && numeric?)\n return emit.to_i\n end\n raise SlawTypeNoMethodError,\n \"to_i can only be called on a string or atomic, numeric slaw\"\n end\n\n # Returns the integer value of this Slaw. May not be called on strings.\n def to_int\n if (atomic? && numeric?)\n return emit.to_int\n end\n raise SlawTypeNoMethodError,\n \"to_int can only be called on an atomic, numeric slaw\"\n end\n\n # Returns the floating point value of this Slaw. Safe to call on strings.\n def to_f\n if string? || (atomic? && numeric?)\n return emit.to_f\n end\n raise SlawTypeNoMethodError,\n \"to_f can only be called on a string or atomic, numeric slaw\"\n end\n\n\n def respond_to? (method)\n case method\n when :emit_binary then return (@type_tag == :unt8_array ||\n @type_tag == :int8_array ||\n @type_tag == :protein)\n when :each then return (list? || map? || array? || vect?)\n when :keys then return (map?)\n when :values then return (map?)\n when :car then return (cons?)\n when :cdr then return (cons?)\n when :[] then return (list? || map? || array? || vect?)\n when :nth_slaw then return (list? || map?)\n when :each_slaw then return (list? || map?)\n when :find_slaw then return (map?)\n when :+ then return (list?)\n when :merge then return (map?)\n when :map_put then return (map?)\n when :map_remove then return (map?)\n when :append then return (list?)\n when :prepend then return (list?)\n when :insert_list then return (list?)\n when :insert then return (list?)\n when :list_remove then return (list?)\n when :to_a then return (list? || map? || array? || vect?)\n when :to_ary then return (list? || array?)\n when :to_hash then return (map?)\n when :to_str then return (string?)\n when :to_i then return (string? || (atomic? && numeric?))\n when :to_int then return (atomic? && numeric?)\n when :to_f then return (string? || (atomic? && numeric?))\n end\n super\n end\n\n\n protected\n\n # given a slaw, recurse, pulling the slawx apart into constituent\n # ruby values and returning the whole assemblage.\n def _unpack (s)\n if (s.atomic? || s.vect? || s.array?)\n return s._c_slaw_value\n elsif s.protein? || s.cons?\n return s\n elsif (s.list?)\n return s._c_slaw_value.map { |entry| _unpack(entry) }\n elsif (s.map?)\n unpacked = Hash.new\n s._c_slaw_value.each_pair do |key, value|\n unpacked[_unpack(key)] = _unpack(value)\n end\n return unpacked\n end\n\n end\n\n\n\n def _freeze\n if @_c_slaw\n # we're immutable, you know. we can only freeze once\n return\n elsif type_tag == :protein\n _freeze_protein\n return\n else\n case @ruby_value\n when Array\n if type_tag.to_s =~ /^(.+)_array/\n _freeze_numeric_array\n return\n elsif type_tag.to_s =~ /^v([234])(.+)/\n _freeze_v234\n return\n elsif type_tag == :map\n sorted_keys = Array.new\n map_pairs = Hash.new\n (0..@ruby_value.size-1).each do |index|\n if (index%2) == 0\n sorted_keys.push @ruby_value[index]\n map_pairs[@ruby_value[index]] = @ruby_value[index+1]\n end\n end\n @ruby_value = map_pairs\n _freeze_map( sorted_keys )\n elsif type_tag == :cons\n _freeze_cons\n else\n _freeze_list\n return\n end\n\n when Hash\n _freeze_map\n return\n else\n ruval = @ruby_value\n if (type_tag == :string)\n if (not ruval.is_a?(String))\n ruval = ruval.to_s\n end\n ruval = Slaw._ensure_utf8(ruval)\n end\n @_c_slaw = _c_freeze_atomic( ruval, type_tag )\n return\n end\n end\n end\n\n def _freeze_numeric_array\n @_c_slaw = _c_freeze_array( @ruby_value, type_tag );\n end\n\n def _freeze_v234\n @_c_slaw = _c_freeze_vect( @ruby_value, type_tag );\n end\n\n def _freeze_list\n tags = IteratorFinalValueRepeater.new(@type_tag)\n @_c_slaw = _c_freeze_list( @ruby_value.map do |rv|\n if Slaw === rv\n # okay, just embed the slaw\n rv\n else\n Slaw.new(rv, tags.next)\n end\n end )\n @type_tag = :list\n end\n\n def _freeze_protein\n # if (! ((@ruby_value[0].is_a? Array) ||\n # ((@ruby_value[0].is_a? Slaw) && (@ruby_value[0].list?))))\n # raise ProteinDescripsAreNotListError\n # end\n ing_tag = :map\n if (! ((@ruby_value[1].is_a? Hash) || (@ruby_value[1].is_a? Array)) and\n ! (((@ruby_value[1].is_a? Slaw) && (@ruby_value[1].map?))))\n # raise ProteinIngestsAreNotMapError\n ing_tag = nil\n end\n if (not @ruby_value[2].is_a?(String))\n raise ArgumentError, \"rude data should be a string\"\n end\n descrips = Slaw.new @ruby_value[0]\n ingests = Slaw.new @ruby_value[1], ing_tag\n @_c_slaw = _c_freeze_protein(descrips, ingests, @ruby_value[2])\n end\n\n def _freeze_map (sorted_keys=nil)\n sorted_keys ||= @ruby_value.keys\n sk = Array.new\n sv = Hash.new\n sorted_keys.each do |k|\n key = (Slaw === k) ? k : Slaw.new(k)\n v = @ruby_value[k]\n val = (Slaw === v) ? v : Slaw.new(v)\n sk.push key\n sv[key] = val\n end\n @_c_slaw = _c_freeze_map(sv, sk)\n @type_tag = :map\n end\n\n def _freeze_cons\n raise SlawConsNeedsTwoArgumentsError if @ruby_value.size != 2\n car_cdr = @ruby_value.map { |r| (r.is_a? Slaw) ? r : Slaw.new(r) }\n @_c_slaw = _c_freeze_cons( *car_cdr )\n @type_tag = :cons\n end\n\n def _ruby_auto_type_tag\n case @ruby_value\n when Float then return :float64\n when Fixnum, Bignum then return :int64\n when String, Symbol then return :string\n when TrueClass, FalseClass then return :boolean\n when NilClass then return :nil\n when Hash then return :map\n when Array then return :list\n end\n raise ArgumentError, \"don't know how to treat #{@ruby_value.class} as slaw\"\n end\n\n public\n\n # Returns a JSON-serialized version of this Slaw\n def to_json(*a)\n begin\n JSON\n rescue NameError\n # Instead of doing \"require 'json'\" at the top of the file, like\n # would normally be done, we only require it if this particular\n # method is called, since only this one method needs the JSON gem,\n # and most users will never call this method. The only reason this\n # is an issue is because in certain rare but unknown circumstances,\n # it appears to be possible for \"require 'json'\" to take up to\n # 30 seconds. We don't want all Plasma users to have to pay this\n # price for functionality only needed by a minority of users.\n # (See bug 3183 comment 4.)\n begin\n require 'rubygems'\n require 'json'\n rescue LoadError\n raise UserError, \"You must install the JSON gem if you want to use \" +\n \"JSON. If you have ruby 1.8.6 or later, do \\\"gem install json\\\". \" +\n \"If you have ruby 1.8.5, do \\\"gem install json_pure\\\". If you are \" +\n \"on Mac OS X 10.5, your gem command is broken; see http://gwcoffey.\" +\n \"posterous.com/cant-update-really-old-rubygems-101-on-mac-os\"\n end\n end\n _j.to_json(*a)\n end\n\n protected\n\n def _j\n typ = @type_tag.to_s\n case typ\n when \"\"\n j = nil\n when \"cons\"\n j = _j_cons\n when \"list\"\n j = _j_list\n when \"map\"\n j = _j_map\n when \"protein\"\n j = _j_protein\n when /^v\\d([ui]n|floa)t\\d+$/\n j = _j_vector\n else\n j = emit\n end\n j\n end\n\n def _j_cons\n {\n JSON.create_id => \"Plasma::SlawCons\",\n 'car' => car._j,\n 'cdr' => cdr._j,\n }\n end\n\n def _j_list\n a = Array.new\n count.times do |n|\n a.push(nth_slaw(n)._j)\n end\n a\n end\n\n def _j_map\n h = Hash.new\n count.times do |n|\n x = nth_slaw(n)\n h[x.car._j] = x.cdr._j\n end\n h\n end\n\n def _j_protein\n h = {\n JSON.create_id => \"Plasma::Protein\",\n 'descrips' => descrips._j,\n 'ingests' => ingests._j,\n }\n rude = rude_data\n if not rude.empty?\n h[\"rude_data\"] = Base64.encode64(rude)\n end\n h\n end\n\n def _j_vector\n {\n JSON.create_id => \"Plasma::SlawVector\",\n 'v' => emit,\n }\n end\n\n # protect all the underscored C methods, too\n protected :_c_freeze_array, :_c_freeze_atomic, :_c_freeze_cons\n protected :_c_freeze_list, :_c_freeze_map, :_c_freeze_protein\n protected :_c_freeze_vect, :_c_initialize, :_c_slaw_cons_car\n protected :_c_slaw_cons_cdr, :_c_slaw_equals, :_c_slaw_hash\n protected :_c_slaw_is_array, :_c_slaw_is_boolean, :_c_slaw_is_cons\n protected :_c_slaw_is_list, :_c_slaw_is_map, :_c_slaw_is_nil\n protected :_c_slaw_is_numeric, :_c_slaw_is_vect, :_c_slaw_list_count\n protected :_c_slaw_list_nth, :_c_slaw_numeric_array_count\n protected :_c_slaw_protein_descrips, :_c_slaw_protein_ingests\n protected :_c_slaw_protein_rude_data, :_c_slaw_spaceship, :_c_slaw_to_string\n protected :_c_slaw_value, :_c_slaw_value_as_string, :_c_spew_stderr\n protected :_c_type_tag\n\n class IteratorFinalValueRepeater\n attr :arr\n def initialize(array_or_value)\n if Array === array_or_value then @arr = Array.new(array_or_value).push(nil)\n else @arr = [array_or_value]\n end\n end\n def next\n nxt = if @arr.length > 1 then @arr.shift\n else @arr[0]\n end\n if nxt == :list\n nxt = nil\n end\n nxt\n end\n end # IteratorFinalValueRepeater\nend # Slaw\n\nclass SlawCons < Slaw\n def self.json_create(o)\n Slaw.new([o['car'],o['cdr']], :cons)\n end\nend\n\nclass SlawVector < Slaw\n def self.json_create(o)\n v = o['v']\n if v.all? { |x| x.is_a?(Integer) }\n tag = \"int64\"\n else\n tag = \"float64\"\n end\n tag = \"v\" + v.length.to_s + tag\n Slaw.new(v, tag.to_sym)\n end\nend\n\nend # Plasma\n" }, { "alpha_fraction": 0.5313432812690735, "alphanum_fraction": 0.5313432812690735, "avg_line_length": 19.9375, "blob_id": "49dbf009873dcf19e0a456c0767a5e73773385e0", "content_id": "ccb7507dad6ad51b903d883f9687429edaa14c18", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 335, "license_type": "permissive", "max_line_length": 144, "num_lines": 16, "path": "/web/modules/niteworks/webpanel/public/javascripts/alltweets.js", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "$( document ).ready(function() {\n\n\t$.getJSON('/mongo/getalltweets', function(data) {\n\t\t\n\t\tvar tweetsHtml;\n\n\t\t$.each(data, function() {\n\n\t\t\ttweetsHtml += \"<tr><td>\" + this.id + \"</td><td>\" + this.created_at + \"</td><td>\" + this['user[name]'] + \"</td><td>\" + this.text + \"</td><tr>\"\n\n\t\t});\n\n\t\t$('#allTweets').html(tweetsHtml)\n\n \t});\n});\n" }, { "alpha_fraction": 0.7214673757553101, "alphanum_fraction": 0.7214673757553101, "avg_line_length": 23.5, "blob_id": "dcfa901f87e137bb954cd0f883afcd35a7118b0c", "content_id": "37edffd6cb654cccdd1fd141256a8446de33f2a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 736, "license_type": "no_license", "max_line_length": 65, "num_lines": 30, "path": "/Makefile", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "#Most demos have use python code in a virtualenv, created by make\nVENVDO=$(PWD)/scripts/venvdo\n\n#Other things that change per demo\nWEB_TIME=web/modules/runner/static/runner/js/demo_time.json\n\nall: loan-fluoro \n\ndeps: $(PWD)/venv/bin/activate\n\n$(WEB_TIME): lib/python/mutualVision/demo_time.json\n\tcp $^ $@\n\n$(PWD)/venv/bin/activate: requirements.txt\n\ttest -d $(PWD)/venv/bin || virtualenv $(PWD)/venv\n\t$(VENVDO) pip install --upgrade pip\n\t$(VENVDO) pip install -r $^\n\n\nloan-fluoro: deps\n\t$(VENVDO) python -m mutualVision.generate_loan_fluoroscope\n\nneat:\n\tgit checkout $(PWD)/etc/mutualVision/loan.protein\n\tgit checkout $(PWD)/etc/mutualVision/inculcators.protein\n\trm -f $(WEB_TIME)\n\trm -f $(TOPO_FILES)\n\nclean: neat\n\trm -fr $(PWD)/venv\n\n" }, { "alpha_fraction": 0.6451612710952759, "alphanum_fraction": 0.6451612710952759, "avg_line_length": 30.100000381469727, "blob_id": "1c8965f2e8819ecf016335bca0df392d918755a4", "content_id": "43adc088fe637349ed6eb910039e32d4b67f96c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 310, "license_type": "no_license", "max_line_length": 60, "num_lines": 10, "path": "/web/modules/showrunner/server.py", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "from flask import Blueprint, render_template\nfrom emcs_admin_utils import jsplasma\n\nrunner = Blueprint('runner', __name__,\n static_folder = 'static',\n template_folder = 'templates')\n\[email protected]('/')\ndef base():\n return render_template('runner.html', jsplasma=jsplasma)" }, { "alpha_fraction": 0.6320000290870667, "alphanum_fraction": 0.6399999856948853, "avg_line_length": 24, "blob_id": "125f6f1d49a6af3f0a0d596c890e3ace1d102ced", "content_id": "0fbf4a77ffa4521877c6b16269df48955ad9681f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 125, "license_type": "no_license", "max_line_length": 71, "num_lines": 5, "path": "/scripts/niteworks/mvClick.sh", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nroot=$(cd `dirname $0`/../..; echo $PWD)\n\nexec \"${root}/scripts/rubydo\" ruby ${root}/scripts/niteworks/mvClick.rb\n" }, { "alpha_fraction": 0.5527690649032593, "alphanum_fraction": 0.6259143352508545, "avg_line_length": 21.785715103149414, "blob_id": "1035eb538922b1036f7cc402eaf9b00ca8572d08", "content_id": "2e0279c5b5e99eed2953901d716c2d6493ad8ecd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1914, "license_type": "no_license", "max_line_length": 89, "num_lines": 84, "path": "/scripts/niteworks/zoomTo.rb", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "require 'optparse'\nrequire 'metabolizer'\n\ninclude Plasma\n\nclass Hearty < Metabolizer\n attr_accessor :verbose\n def initialize(*hoses)\n puts \"starting Hearty daemon\" if @verbose\n super(*hoses)\n @verbose = false\n @outpool = 'edge-to-sluice'\n @descrips = ['sluice', 'prot-spec v1.0', 'psa', 'heartbeat']\n @sequence = 1\n appendMetabolizer(@descrips) { |p| receive p }\n end\n\n def receive(p)\n puts \"Got heartbeat protein from sluice\" if @verbose\n\n ing = p.ingests\n if ing['location'].nil?\n puts \"ERROR: did not find location in ingest\"\n return\n end\n\n # zoomTo(51.279121, -0.769756, 22000) #Farnborough\n # zoomTo(54.711976144614532, -2.792778845872681, 20.5, 10) #UK\n# zoomTo(48.9267902, 2.3308999, 20, 10) # Paris Attacks\n #\n zoomTo(20.201122363199918, 23.704901015773963, 1.9486890091833518)\n\n\n puts \"Zoom To applied, I'm outta here\"\n exit 1\n end\n\n def zoomTo(lat, lon, zoomLevel, speed = 5.0)\n puts \"Zooming to #{lat}, #{lon}, #{zoomLevel}\"\n\n outdescrips = ['sluice', 'prot-spec v1.0', 'request', 'zoom']\n\n ingests = {\n 'lat' => lat,\n 'lon' => lon,\n 'level' => zoomLevel,\n 'interp-time' => speed\n }\n p = Protein.new(outdescrips, ingests)\n PokeProtein(p)\n end\n\n def PokeProtein(protein)\n hose = Pool.participate 'edge-to-sluice'\n hose.deposit(protein)\n hose.withdraw()\n end\nend\n\npool = 'sluice-to-heart'\n\nverbose = true\nrespire = 0.1\n\noptparse = OptionParser.new do |opt|\n opt.on('--pool=MANDATORY', '-p', String, \"Input Pool (#{pool})\") { |x| pool = x }\n opt.on('--respire=MANDATORY', '-r', Float, \"Respire (#{respire})\") { |x| respire = x }\nend\noptparse.parse!\n\nif verbose\n puts \"pool: #{pool}\"\n puts \"respire: #{respire}\"\nend\n\nh = Hearty.new pool\nh.verbose = verbose\n\ntrap 'SIGINT', proc {\n puts \"Ending Hearty daemon\" if h.verbose\n h.quit = true\n}\n\nh.metabolize respire\n" }, { "alpha_fraction": 0.5551663637161255, "alphanum_fraction": 0.5757443308830261, "avg_line_length": 19.576576232910156, "blob_id": "536f24525c1a310fadb9010833df7e09ae74dd20", "content_id": "1f67a097a61feda9ee7dfa7ee9c83cde7dbc68b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2284, "license_type": "no_license", "max_line_length": 97, "num_lines": 111, "path": "/scripts/niteworks/showIntro.rb", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "require 'optparse'\nrequire 'metabolizer'\n\ninclude Plasma\n\nclass Hearty < Metabolizer\n attr_accessor :verbose\n def initialize(*hoses)\n puts \"starting Hearty daemon\" if @verbose\n super(*hoses)\n @verbose = false\n @outpool = 'edge-to-sluice'\n @descrips = ['sluice', 'prot-spec v1.0', 'psa', 'heartbeat']\n @sequence = 1\n appendMetabolizer(@descrips) { |p| receive p }\n end\n\n def receive(p)\n puts \"Got heartbeat protein from sluice\" if @verbose\n\n ing = p.ingests\n if ing['location'].nil?\n puts \"ERROR: did not find location in ingest\"\n return\n end\n\n url = 'http://localhost:7787/sluice/mutualvision/intro'\n\n openWebPage(url, 'intro', [0, 0], 'left', [1.0, 1.0]);\n\n puts \"Introduction applied #{url} , I'm outta here\"\n exit 1\n end\n\n def openWebPage(url, name, position, feld, size)\n puts \"Loadig url: #{url}, name: #{name}, position: #{position}, feld: #{feld}, size: #{size}\"\n\n outdescrips = ['sluice', 'prot-spec v1.0', 'request', 'web']\n\n\n\tingests = {\n 'windshield' => [\n {\n 'feld' => feld,\n 'loc' => position,\n 'url' => url,\n 'name' => name,\n 'size' => size\n }\n ]\n }\n\n\n p = Protein.new(outdescrips, ingests)\n PokeProtein(p)\n\n\n# %YAML 1.1\n# %TAG ! tag:oblong.com,2009:slaw/\n# --- !protein\n# descrips:\n# - sluice\n# - prot-spec v1.0\n# - request\n# - web\n# ingests:\n# windshield:\n# - name: devPageCent\n# feld: center\n# loc:\n# - 0\n# - 0\n# size:\n# - 1.0\n# - 1.0\n# url: http://192.168.25.188:7787/sluice/mutualvision/vernon\n\n end\n\n def PokeProtein(protein)\n hose = Pool.participate 'edge-to-sluice'\n hose.deposit(protein)\n hose.withdraw()\n end\nend\n\npool = 'sluice-to-heart'\n\nverbose = true\nrespire = 1.0\n\noptparse = OptionParser.new do |opt|\n opt.on('--pool=MANDATORY', '-p', String, \"Input Pool (#{pool})\") { |x| pool = x }\n opt.on('--respire=MANDATORY', '-r', Float, \"Respire (#{respire})\") { |x| respire = x }\nend\noptparse.parse!\n\nif verbose\n puts \"pool: #{pool}\"\n puts \"respire: #{respire}\"\nend\n\nh = Hearty.new pool\nh.verbose = verbose\n\ntrap 'SIGINT', proc {\n puts \"Ending Hearty daemon\" if h.verbose\n h.quit = true\n}\n\nh.metabolize respire\n" }, { "alpha_fraction": 0.49242115020751953, "alphanum_fraction": 0.5493650436401367, "avg_line_length": 17.338346481323242, "blob_id": "af81756317071ef437e3f3d7b35ba4ed58dfc29f", "content_id": "1e6e31c6e8d3777237e2c6cd25cb6b405ed0c5e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2441, "license_type": "no_license", "max_line_length": 67, "num_lines": 133, "path": "/lib/ruby/slaw-not-tests.rb", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "require 'Pool'\n\n# #s = Plasma::Slaw.new(23.0, :int64)\n# s = Plasma::Slaw.new(23.0)\n# s._c_spew_stderr\n# s = Plasma::Slaw.new(23)\n# s._c_spew_stderr\n# s = Plasma::Slaw.new(\"23\")\n# s._c_spew_stderr\n# s = Plasma::Slaw.new(true)\n# s._c_spew_stderr\n# s = Plasma::Slaw.new(nil)\n# s._c_spew_stderr\n\ns = slaw(nil)\ns._c_spew_stderr\n\ns = Plasma::Slaw.new(23.0)\ns._c_spew_stderr\n\n# t = Plasma::Slaw.new(23.0)\n\n# p s==t\n# p s.eql?(t)\n\n# p s==23.0\n# p s==23\n\n# p s.eql?(23.0)\n# p s.eql?(23)\n# exit\n\ns = Plasma::Slaw.new( [1, 2, 3], :v3float32 );\ns._c_spew_stderr\n\ns = Plasma::Slaw.new( [1, 2, 3, 4], :v4unt64 );\ns._c_spew_stderr\n\ns = Plasma::Slaw.new( [1, 2], :v2unt8 );\ns._c_spew_stderr\n\ns = Plasma::Slaw.new( [1, 2, 3, 4], [:float32, :int8, :float64] )\ns._c_spew_stderr\n\ns = Plasma::Slaw.new( [1, 2, 3], :float32_array );\ns._c_spew_stderr\n\ns = Plasma::Slaw.new( [1, 2, 3, 4, 5, 6, 7], :unt16_array );\ns._c_spew_stderr\n\ns = Plasma::Slaw.new( [[1, 2, 3],[4, 5, 6]], :v3float32 );\ns._c_spew_stderr\n\ns = Plasma::Slaw.new( [[1, 2, 3],[4, 5, 6]], :v3float32_array );\ns._c_spew_stderr\n\ns = Plasma::Slaw.new( [[1, 2, 3, 4],[4, 5, 6, 7]], :v4int8_array );\ns._c_spew_stderr\n\n# fix:\ns = v4int8(1,2,3,4);\ns._c_spew_stderr\n\n# s = Plasma::Slaw.new(400, :string)\n# s._c_spew_stderr\n\nt = Plasma::Slaw.new(23.0)\ns = Plasma::Slaw.new([1, 2, t], :int8);\ns._c_spew_stderr\n\nu = Plasma::Slaw.new(\"two-point-two\")\ns = Plasma::Slaw.new( { \"one\" => 1.0,\n \"two\" => 2.0,\n u => 2.2 } )\ns._c_spew_stderr\n\np u.map?\np s.map?\n\nprint \"----------\\n\"\nt = Plasma::Slaw.new([1, 2, 3, 4])\n\nu = Plasma::Slaw.new(\"two-point-two\")\nt = Plasma::Slaw.new( { \"one\" => 1.0,\n \"two\" => 2.0,\n u => 2.2 } )\n\np t[\"two-point-two\"]\n\ns = slaw(4)\nt = slaw(s)\n\np = protein([\"one\", \"two\", \"three\"],\n { \"one\" => 1.0,\n \"two\" => 2.0,\n u => 2.2 })\np._c_spew_stderr\n\nprint \"connecting to pool 'rt'\\n\"\nph = Plasma::Pool.new \"rt\"\nprint \"depositing\\n\"\nph.deposit p\n\nprint \"nexting\\n\"\nprot = ph.next\np prot\np prot.protein?\np prot.descrips[0]\np prot.descrips[1]\np prot.descrips[2]\np prot.ingests[\"two-point-two\"]\np prot.timestamp\np prot.index\n\nprint \"rewind\\n\"\nph.rewind\nprot = ph.next\np prot.index\n\nprint \"seek by\\n\"\nph.seekby(1)\nprot = ph.next\np prot.index\n\nprint \"seek to\\n\"\nph.seekto(0)\nprot = ph.next\np prot.index\n\nprint \"to last\\n\"\nph.tolast\nprot = ph.next\np prot.index\n\n\n" }, { "alpha_fraction": 0.7458116412162781, "alphanum_fraction": 0.7458116412162781, "avg_line_length": 31.074073791503906, "blob_id": "59c28230e69121743f966f36c1638ba7d97f1936", "content_id": "ff5c379a613ce7ab0803e736c0ea9a6f2806ac6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1731, "license_type": "no_license", "max_line_length": 100, "num_lines": 54, "path": "/web/modules/niteworks/routes.py", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "from flask import render_template\nimport os.path\nfrom emcs_admin_utils import jsplasma\nfrom emcs_admin_utils.flask_components import Component\n\n#use flask because will do a lot of work for us\nBASEPATH = os.path.abspath(os.path.dirname(__file__))\nSTATIC_PATH = os.path.join(BASEPATH, 'public')\nTEMPLATES_PATH = os.path.join(BASEPATH, 'templates')\napp = Component('mutualvision', __name__, static_folder=STATIC_PATH, template_folder=TEMPLATES_PATH)\n\[email protected]('/mutualvision')\ndef streetcams_base():\n return render_template('main.html', jsplasma=jsplasma)\n\[email protected]('/mutualvision/arrears')\ndef arrears_base():\n return render_template('arrears.html', jsplasma=jsplasma)\n\[email protected]('/mutualvision/customers')\ndef customers_base():\n return render_template('customers.html', jsplasma=jsplasma)\n\[email protected]('/mutualvision/buildsoc')\ndef buildsoc_base():\n return render_template('buildsoc.html', jsplasma=jsplasma)\n\[email protected]('/mutualvision/dashboard')\ndef dashboard_base():\n return render_template('dashboard.html', jsplasma=jsplasma)\n\[email protected]('/mutualvision/legend')\ndef legend_base():\n return render_template('other.html', jsplasma=jsplasma)\n\[email protected]('/mutualvision/loans')\ndef loans_base():\n return render_template('loans.html', jsplasma=jsplasma)\n\[email protected]('/mutualvision/ratings')\ndef ratings_base():\n return render_template('ratings.html', jsplasma=jsplasma)\n\[email protected]('/mutualvision/ltv')\ndef ltv_base():\n return render_template('ltv.html', jsplasma=jsplasma)\n\[email protected]('/mutualvision/vernon')\ndef vernon_base():\n return render_template('vernon.html', jsplasma=jsplasma)\n\[email protected]('/mutualvision/intro')\ndef intro_base():\n return render_template('intro.html', jsplasma=jsplasma)" }, { "alpha_fraction": 0.7031630277633667, "alphanum_fraction": 0.7226277589797974, "avg_line_length": 29.850000381469727, "blob_id": "31c2fc5a2c426edff130d1f3d1117ec1c9d73fc1", "content_id": "90cfede98004bf96080acccacdd4ae8234c90e8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1233, "license_type": "no_license", "max_line_length": 192, "num_lines": 40, "path": "/README.md", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "# NiteWorks Conduce Demonstrator\n\n### MongoDB 3.0\nMongoDB 3.0 can use the *Wired Tiger* storage engine for faster data retrieval. If you normally start MongoDB on demand, you can take advantage of the performance gains using the following: -\n```\n$ mongod --storageEngine wiredTiger --dbpath /data/tiger/\n```\n\nCheck your indexes\n```\n> db.tweets.createIndex({ \"twitter.coordinates.coordinates\":1 }, { sparse: true })\n```\n\n\n## Launch Sluice\n```\nrm -rf .sluice/var/logs/*; /opt/mct/sluice/bin/sluice-run -w -D ~/Documents/conduce/treatments/niteworks/\n```\n\n## LaunchPad\nUes a web-based applicaiton to run through the demonstrator. Navigate to the [LaunchPad] which is hosted as part of the Treatment\n\n - http://localhost:7787/launchpad/\n\n## Administration Panel\nSluice has a web-based control/administration panel. Navigate to [sluice] which is hosted by the treatment loaded\n\n - http://localhost:7787/sluice\n\n[LaunchPad]:http://localhost:7787/launchpad/\n[sluice]:http://localhost:7787/sluice\n\n## Web Panel Indexes\nAt the following index to the db to improve the performance\n\n```\n> db.tweets.createIndex( { twitter: 1 } ) -????\n> db.tweets.createIndex( { 'twitter.id': 1 } )\n> db.tweets.createIndex( { 'twitter.user.id': 1 } )\n```" }, { "alpha_fraction": 0.6610169410705566, "alphanum_fraction": 0.6610169410705566, "avg_line_length": 7.800000190734863, "blob_id": "4c3ae94df073c3cb55b68e7d96d5b3ba03e597f5", "content_id": "2f7b12b76db29156ad7bb1503e01fd61558786ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 177, "license_type": "no_license", "max_line_length": 24, "num_lines": 20, "path": "/lib/ruby/SlawInputFile.rb", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "\nrequire 'Protein'\nrequire 'Slaw'\n\n\nmodule Plasma\n\nclass SlawInputFile\n\n\n def initialize (fname)\n _c_input_open fname\n end\n\n def read ()\n _c_input_read\n end\n\nend\n\nend\n" }, { "alpha_fraction": 0.6369456052780151, "alphanum_fraction": 0.638317346572876, "avg_line_length": 21.79166603088379, "blob_id": "d6c690a7cc7400890e00f9a2aff1fefeb9070858", "content_id": "c974712781e7dbb02ca3c72c057ca4fc8400429b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2187, "license_type": "no_license", "max_line_length": 79, "num_lines": 96, "path": "/scripts/jsonImport/app.js", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "var jsonfile = require('jsonfile')\nvar util = require('util')\nvar fs = require('fs');\n\nfunction readFiles(dirname, onFileContent, onError) {\n fs.readdir(dirname, function(err, filenames) {\n if (err) {\n \tconsole.log(err)\n onError(err);\n return;\n }\n\n\n filenames.forEach(function(filename) {\n \tvar fullPath = '/Users/Daryl/Desktop/niteworksTweets/' + filename\n \t// console.log(fullPath)\n \tvar processedPath = '/Users/Daryl/Desktop/processed/' + filename\n\n\n\n\t\tfs.exists(processedPath, function(exists) {\n\t\t if (exists) {\n\t\t \t//console.log('already done', processedPath)\n\t\t return;\n\t\t }\n\t\t});\n\n\n\n\t\tvar obj = jsonfile.readFileSync(fullPath);\n\n\t\tvar newJson = obj.interactions\nconsole.log('about to write', processedPath)\n\n\t\t jsonfile.writeFile(processedPath, newJson, {spaces: 2}, function (err) {\n\t\t\t if (err) console.error(err)\n\t\t\t})\n\t\t // console.log(newJson)\n\t\t// })\n\n\n // jsonfile.readFile(fullPath, function(err, obj) {\n // \t\tif (err) {\n // \t\t\tconsole.log(err)\n // \t\t}\n\t\t// // console.dir(obj)\n\t\t// var newJson = obj.interactions\n\n\n\t\t// jsonfile.writeFile(processedPath, newJson, {spaces: 2}, function (err) {\n\t\t// \t if (err) console.error(err)\n\t\t// \t})\n\t\t// // console.log(newJson)\n\t\t// })\n });\n });\n}\n\n\n\n\nfunction readFilesSync(path) {\n\tvar filesArr = fs.readdirSync(path)\n\tconsole.log(filesArr.length)\n\tfilesArr.forEach(function(filename) {\n\t\t// console.log(filename)\n\t\tvar fullPath = '/Users/Daryl/Desktop/niteworksTweets/' + filename\n \t// console.log(fullPath)\n \tvar processedPath = '/Users/Daryl/Desktop/processed/' + filename\n\n\n\n\t\tfs.exists(processedPath, function(exists) {\n\t\t if (exists) {\n\t\t \tconsole.log('already done', processedPath)\n\t\t return;\n\t\t }\n\t\t});\n\n\n\n\t\tvar obj = jsonfile.readFileSync(fullPath);\n\n\t\tvar newJson = obj.interactions\n\t\tconsole.log('about to write', processedPath)\n\n\t\tjsonfile.writeFileSync(processedPath, newJson)\n\n\t\t // jsonfile.writeFile(processedPath, newJson, {spaces: 2}, function (err) {\n\t\t\t// if (err) console.error(err)\n\t\t\t// })\n\t});\n}\n\nreadFilesSync('/Users/Daryl/Desktop/niteworksTweets')\n// readFiles('/Users/Daryl/Desktop/toprocess')" }, { "alpha_fraction": 0.49883177876472473, "alphanum_fraction": 0.5186915993690491, "avg_line_length": 23.69230842590332, "blob_id": "d6a486b5ff553a3c84f3b1f39f41ff4e1c20b3b5", "content_id": "ca823916b11e18479ea19fa24021ea9f8fe25987", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2568, "license_type": "no_license", "max_line_length": 93, "num_lines": 104, "path": "/scripts/niteworks/mvClick.rb", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "require 'optparse'\nrequire 'metabolizer'\n\ninclude Plasma\n\nclass Clicky < Metabolizer\n attr_accessor :verbose\n attr_accessor :outpool\n\n @@webURl = \"http://localhost:7787/sluice/niteworks/\"\n\n def initialize(*hoses)\n puts \"starting Clicky daemon\" if @verbose\n super(*hoses)\n @verbose = false\n @outpool = ''\n @descrips = ['sluice', 'prot-spec v1.0', 'psa', 'poked-it']\n @outdescrips = ['sluice', 'prot-spec v1.0', 'request', 'web' ]\n appendMetabolizer(@descrips) { |p| receive p }\n end\n\n def receive(p)\n ing = p.ingests\n puts \"Got click protein from sluice\" if @verbose\n\n if ing['id'].nil?\n puts \"Id is empty, node was not clicked\" if @verbose\n return\n end\n# puts ing\n if ing['kind'] == 'tweet_blue' || ing['kind'] == 'tweet_green'\n\n if (ing['attrs']['media'].length > 0)\n ingests = {'windshield' => [{\n 'name' => 'dashboard',\n 'feld' => 'left',\n 'loc' => [0,0],\n 'size' => [1.0, 1.0],\n 'url' => 'http://localhost:3000/?id=' + ing['attrs']['tweetId']\n }, {\n 'name' => 'photos',\n 'feld' => 'right',\n 'loc' => [-0.25,-0.25],\n 'size' => [0.25, 0.25],\n 'url' => ing['attrs']['media']\n }]}\n\n\n\n else \n ingests = {'windshield' => [{\n 'name' => 'dashboard',\n 'feld' => 'left',\n 'loc' => [0,0],\n 'size' => [1.0, 1.0],\n 'url' => 'http://localhost:3000/?id=' + ing['attrs']['tweetId']\n }, {\n 'name' => 'photos',\n 'feld' => 'right',\n 'loc' => [-2,-2],\n 'size' => [0.25, 0.25],\n 'url' => ''\n }]}\n\n end\n \n\n hose = Pool.participate @outpool\n hose.deposit(Protein.new(@outdescrips, ingests))\n hose.withdraw()\n puts (\"Web panel request sent\") if @verbose\n end \n end\nend\n\npool = 'sluice-to-edge'\noutpool = 'edge-to-sluice'\n\nverbose = true\nrespire = 0.1\n\noptparse = OptionParser.new do |opt|\n opt.on('--pool=MANDATORY', '-p', String, \"Input Pool (#{pool})\") { |x| pool = x }\n opt.on('--outpool=MANDATORY', '-o', String, \"Output Pool (#{outpool})\") { |x| outpool = x }\n opt.on('--respire=MANDATORY', '-r', Float, \"Respire (#{respire})\") { |x| respire = x }\nend\noptparse.parse!\n\nif verbose\n puts \"pool: #{pool}\"\n puts \"outpool: #{outpool}\"\n puts \"respire: #{respire}\"\nend\n\nw = Clicky.new pool\nw.outpool = outpool\nw.verbose = verbose\n\ntrap 'SIGINT', proc {\n puts \"Ending Clicky daemon\" if w.verbose\n w.quit = true\n}\n\nw.metabolize respire\n" }, { "alpha_fraction": 0.5975610017776489, "alphanum_fraction": 0.6036585569381714, "avg_line_length": 17.22222137451172, "blob_id": "1eccb009ec75b277a97c1e00be7adcd1eb51b1c4", "content_id": "7ef3ae46cc895cf9e755741b52c0e2af59a691e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 164, "license_type": "no_license", "max_line_length": 68, "num_lines": 9, "path": "/scripts/venvdo", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nroot=$(cd `dirname $0`/.. && echo $PWD)\n\n. \"${root}/venv/bin/activate\"\n\nexport PYTHONPATH=\"${PYTHONPATH}:${root}/lib/python:${root}/scripts\"\n\nexec \"$@\"\n" }, { "alpha_fraction": 0.5401083827018738, "alphanum_fraction": 0.5547425746917725, "avg_line_length": 31.359649658203125, "blob_id": "33acd9c99c2f7dacfaa4674edb387557041b9c8a", "content_id": "b3b65b8ab5fbaa8a5274f5a5d6a70737f1461b23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3690, "license_type": "no_license", "max_line_length": 88, "num_lines": 114, "path": "/web/modules/showrunner/static/runner/js/timeline.js", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "\nfunction Timeline(slider){\n const TO_SLUICE = 'tcp://localhost/edge-to-sluice';\n const FROM_SLUICE = 'tcp://localhost/sluice-to-heart';\n\n const TIME_CHANGE = ['sluice', 'prot-spec v1.0', 'request', 'set-time'];\n\n function fmt_date(x) {\n if (undefined != x) {\n var d = new Date(x * 1000);\n // console.log(d.toString());\n // console.log(d);\n // console.log(x);\n return d.toString();\n } else {\n console.log('Whatever');\n return 'Unknown';\n }\n }\n\n var minimum_time = 0.0, maximum_time = 0.0, cur_time = 0.0;\n var rate = 1.0;\n\n function time_change(ing) {\n Plasma\n .Hose(TO_SLUICE)\n .Deposit ({ descrips : TIME_CHANGE,\n ingests : ing });\n }\n\n function sliderchange(evt) {\n time_change({ pause: false, time: parseInt(slider.attr('value')), rate: rate });\n }\n\n //timeslider event listeners\n slider.change(function(evt){sliderchange(evt)});\n document.getElementById('range-set').addEventListener(\"input\",\n function(evt){\n sliderchange(evt)\n }\n );\n\n Plasma\n .Hose (FROM_SLUICE)\n .Match (['sluice', 'prot-spec v1.0', 'psa', 'heartbeat'])\n .Await (function (p) {\n $('#time-rate').text(rate = p.ingests.time.rate);\n $('#time-current').text(fmt_date(cur_time = p.ingests.time.current));\n slider.attr('value', cur_time);\n if (undefined != p.ingests.time.min) {\n // minimum_time = p.ingests.time.min;\n $('#time-minimum').text(fmt_date(slider.attr('min')));\n }\n if (undefined != p.ingests.time.max) {\n // maximum_time = p.ingests.time.max\n $('#time-maximum').text(fmt_date(slider.attr('max')));\n }\n });\n\n var masterTime = {};\n\n $.ajax({\n url: \"static/runner/js/demo_time.json\",\n async: false,\n dataType: 'json',\n success: function (data) {\n for (var key in data) {\n masterTime[key] = data[key];\n }\n console.log(\"setting master time to \", masterTime);\n }\n });\n\n function timeStart() { return masterTime.start_time + 1200; }\n function monthlyEnd() { return masterTime.monthly_end - 1200; }\n function dailyStart() { return masterTime.daily_start + 1200; }\n function dailyEnd() { return masterTime.daily_end - 1200; }\n function hourlyStart() { return masterTime.hourly_start + 1200; }\n function hourlyEnd() { return masterTime.hourly_end - 1200; }\n\n this.setLiveTime = function(){\n //TODO: Figure out how to disable the slider\n //tried slider.slider( \"option\", \"disabled\", true );\n //and slider.slider(\"disable\"); and a few others\n //with no luck\n time_change({'live': true, 'rate': 1});\n }\n\n this.setTimeRangeMonthly = function(){\n slider.attr('min', timeStart());\n slider.attr('max', monthlyEnd());\n slider.attr('value', timeStart());\n slider.change();\n };\n this.setTimeRangeDaily = function(){\n var min_time = dailyStart();\n var max_time = dailyEnd();\n // var max_time = min_time + 86400;\n slider.attr('min', min_time);\n slider.attr('max', max_time);\n slider.attr('value', min_time + (max_time - min_time) / 2.0);\n slider.change();\n };\n this.setTimeRangeHourly = function(){\n var min_time = hourlyStart();\n var max_time = hourlyEnd();\n // var max_time = min_time + 3600;\n slider.attr('min', min_time);\n slider.attr('max', max_time);\n slider.attr('value', min_time + (max_time - min_time) / 2.0);\n slider.change();\n };\n\n return this;\n};\n" }, { "alpha_fraction": 0.707602322101593, "alphanum_fraction": 0.707602322101593, "avg_line_length": 17.88888931274414, "blob_id": "4c3dc250c806e44bacd57cfe50065edeb99cde87", "content_id": "af615eae452112fd72466ea9be9cc8b5a74ba912", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 171, "license_type": "no_license", "max_line_length": 72, "num_lines": 9, "path": "/scripts/jsonImport/import.sh", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nIMPORT_PATH=/Users/Daryl/Desktop/processed/*.json\n\nfor i in $IMPORT_PATH; do\n\n mongoimport --db niteworks --collection tweets --file $i --jsonArray\n\ndone\n\n" }, { "alpha_fraction": 0.6294277906417847, "alphanum_fraction": 0.6294277906417847, "avg_line_length": 13.038461685180664, "blob_id": "c875d7b9354d83f69029174a15deccbb8e066521", "content_id": "55bf4cc6214948301eefe2ccc76d99f9ec9c4c2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 367, "license_type": "no_license", "max_line_length": 51, "num_lines": 26, "path": "/lib/ruby/SlawOutputFile.rb", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "\n\nrequire 'Protein'\nrequire 'Slaw'\n\n\nmodule Plasma\n\nclass SlawOutputFile\n\n\n def initialize (fname, mode = :text)\n if (mode == :text)\n _c_output_open_text fname\n elsif (mode == :binary)\n _c_output_open_binary fname\n else\n raise \"unrecognized slaw output mode #{mode}\"\n end\n end\n\n def write (slaw)\n _c_output_write slaw\n end\n\nend\n\nend\n" }, { "alpha_fraction": 0.7512437701225281, "alphanum_fraction": 0.7512437701225281, "avg_line_length": 32.5, "blob_id": "9c9b14b8e57aa4b450189891b84c47c0d8865759", "content_id": "bccdbe84495deb44a223b6f7c48eb4f9412b3d1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 201, "license_type": "no_license", "max_line_length": 95, "num_lines": 6, "path": "/share/niteworks/elixir/tweets/data/importJSON", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nIMPORT_PATH=/Users/jb/code/legendary-happiness/share/niteworks/elixir/tweets/data/output/*.json\nfor i in $IMPORT_PATH; do\n mongoimport --db niteworks --collection tweets --file $i\ndone\n" }, { "alpha_fraction": 0.6666977405548096, "alphanum_fraction": 0.6689359545707703, "avg_line_length": 26.77979278564453, "blob_id": "8ad6afdbe825b20f654f4443687f751d217def82", "content_id": "6d1854bf96c3a397b7a6e86e2772f85b7b4f6798", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 10723, "license_type": "no_license", "max_line_length": 117, "num_lines": 386, "path": "/lib/ruby/Pool.rb", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "require 'weakref'\n\nrequire 'Protein'\nrequire 'Slaw'\n\n# Plasma is a combination of:\n# * A schema-free, binary envelope for message data called a Protein\n# * A persistance layer for Proteins implemented as a ring buffer called a Pool\n# * A network transport protocol to pass proteins to/from remote pools\nmodule Plasma\n\n NO_WAIT = 0.0\n WAIT_FOREVER = -1.0\n\n POOL_DEFAULT_SIZE = 1048576\n\nclass PoolOperationError < StandardError ; end\n\n#--\n# XXX: Can someone document the rationale for all these to_string calls?\n# Shouldn't our arguments be strings already?\n# YYY: It's been suggested that someone might pass pool names as symbols?\n#++\n#\n# A pool is a ring buffer of Proteins.\n#\nclass Pool\n # Creates a pool with name pname.\n #\n # pname can be:\n # * a local pool, such as 'mypool'\n # * a remote networked pool, such as 'tcp://otherhost.com/mypool'\n # * a local pool accessed via the networking stack, such as 'tcp://localhost/mypool'\n def Pool.create (pname, options=nil)\n options_slaw = Slaw.new( { \"size\" => POOL_DEFAULT_SIZE }, :map )\n if (not options.nil?)\n options_slaw = Slaw.merge_maps( options_slaw, Slaw.new( options, :map ) )\n end\n _c_create pname.to_str, options_slaw\n end\n\n # Deletes the pool with name pname.\n #\n # pname can be:\n # * a local pool, such as 'mypool'\n # * a remote networked pool, such as 'tcp://otherhost.com/mypool'\n # * a local pool accessed via the networking stack, such as 'tcp://localhost/mypool'\n def Pool.dispose (pname)\n _c_dispose pname.to_str\n end\n\n #--\n # For backwards compatibility; could we deprecate in favor of list_pools?\n #++\n # This method is deprecated. Call #Pool.list_pools with no arguments instead.\n def Pool.list_locals\n _c_list_pools nil\n end\n\n # Returns a lists of pools contained on the given server. If server is null, lists local pools.\n #\n # The server must be a fully qualified uri and contain a trailing slash, e.g. 'tcp://otherhost.com/'\n def Pool.list_pools(server=nil)\n _c_list_pools(server)\n end\n\n # Participates in a pool with name pname.\n #\n # Returns a Hose object.\n #\n # pname can be:\n # * a local pool, such as 'mypool'\n # * a remote networked pool, such as 'tcp://otherhost.com/mypool'\n # * a local pool accessed via the networking stack, such as 'tcp://localhost/mypool'\n #\n # Ex. h = Pool.participate(\"tcp://otherhost.com/mypool\")\n def Pool.participate (pname)\n Hose.new( pname.to_str )\n end\n\n # Renames a pool.\n #\n # Only pools which are not in use can be renamed.\n #\n # * Throws #PoolInUseError if any hoses are open to the pool.\n # * Throws #PoolExistsError if the destination exists\n # * Throws #PoolNotFoundError if the source does not.\n def Pool.rename(oldname, newname)\n _c_rename(oldname.to_str, newname.to_str)\n end\n\n # Returns true if pool is in use, false if it is not, or raises\n # an exception if it can't determine. (e. g. doesn't exist)\n # Beware of TOCTOU: http://cwe.mitre.org/data/definitions/367.html\n def Pool.is_in_use?(name)\n _c_is_in_use(name.to_str)\n end\n\nend\n\n# A hose is a connection to a pool, local or remote. A hose allows for read, write, and seek operations on a pool.\nclass Hose\n attr_accessor :pool_name\n\n def initialize (pname)\n @pool_name = pname\n _c_initialize # fix: initializes @_pool_hose to nil, but\n # if that's all we do here, we should just\n # do it in ruby, to be clearer\n end\n\n # Returns the pool name\n def name\n _c_get_name\n end\n\n # Sets the pool name to nm\n def name= (nm)\n _c_set_name(Slaw._ensure_utf8(nm))\n end\n\n # Retrieves the next protein from the pool, after the current index.\n def next (timeout=NO_WAIT)\n _c_await_next(timeout)\n end\n\n # implemented in c\n #\n # deposit (protein)\n # rewind\n # runout\n # tolast\n # seekby (offset)\n # seekto (index)\n # nth (index)\n # oldest_index\n # newest_index\n # withdraw\n #\n # note that next() is not implemented directly in c because we don't\n # know how to do default argument values in a super-simple way. we\n # could certainly do something using ruby varargs\n\n # Sets the \"oldest\" index of a pool, essentially erasing any proteins\n # prior to that index. Returns OB_OK if at least one protein was erased.\n # Returns OB_NOTHING_TO_DO if idx_in is older than the current\n # oldest index. Returns POOL_NO_SUCH_PROTEIN if idx_in is newer than\n # the newest index.\n def oldest_index= (idx)\n _c_advance_oldest(idx)\n end\n\n def add_trib__dispatch (gang)\n gang.add_standard_c_hose_tributary self\n end\n\n def is_empty?\n begin\n newest_index\n rescue PoolNoProteinError\n true\n else\n false\n end\n end\n\n # Allows some of the options that were specified in pool_create\n # to be changed after the pool is created. options can be\n # either a protein or a slaw map, as in pool_create.\n #\n # The possible keys for the options map/protein are documented in\n # share/doc/g-speak/option-map-keys.html in the install tree,\n # or doc-non-dox/option-map-keys.html in the source tree.\n def change_options (options)\n options_slaw = Slaw.new( options, :map )\n _c_change_options(options_slaw)\n end\n\n # Returns a hash with information about a pool.\n #\n # Should always include an ingest \"type\", which is a string naming the\n # pool type, and \"terminal\", which is a boolean which is true if this is\n # a terminal pool type like \"mmap\", or false if this is a transport pool\n # type like \"tcp\".\n #\n # For mmap pools, should include an ingest \"size\", which is an integer\n # giving the size of the pool in bytes.\n # For tcp pools, should include an ingest \"host\", which is a string\n # naming the host the pool is on, and \"port\" which is an integer\n # giving the port.\n #\n # For other pool types, ingests with other relevant info can be included.\n # If \"hops\" is 0, means return information about this pool hose.\n # If \"hops\" is 1, means return information about the pool beyond this\n # hose (assuming this hose is a nonterminal type like TCP). And higher\n # values of \"hops\" mean go further down the line, if multiple nonterminal\n # types are chained together. If \"hops\" is -1, means return information\n # about the terminal pool, no matter how far it is.\n def info (hops=-1)\n # c function returns a protein, but really a map is nicer\n _c_get_info(hops).ingests\n end\n\n # True if the pool is resizable, false otherwise.\n def resizable?\n mmv = info[\"mmap-pool-version\"]\n (! mmv.nil?) && (mmv > 0)\n end\n\n # Returns the size of the pool in bytes.\n def size\n info[\"size\"]\n end\n\n # Sets the size of the pool to x.\n def size= (x)\n change_options({\"size\" => x})\n end\n\n # Returns the bytes used.\n def size_used\n info[\"size-used\"]\n end\n\n # Deprecated. Use toc_capacity instead.\n def index_capacity\n info[\"index-capacity\"]\n end\n\n # Returns the capacity (in # of proteins) of the pool's table of contents\n def toc_capacity\n info[\"toc-capacity\"]\n end\n\n def stop_when_full\n info[\"stop-when-full\"]\n end\n\n def stop_when_full= (x)\n change_options({\"stop-when-full\" => x})\n end\n\n # Boolean whether this pool is frozen.\n def frozen\n info[\"frozen\"]\n end\n\n # Set whether the pool is frozen or not.\n def frozen= (x)\n change_options({\"frozen\" => x})\n end\n\n # Boolean whether this pool with be auto-disposed after withdrawal.\n def auto_dispose\n info[\"auto-dispose\"]\n end\n\n # Set whether this pool should be auto-disposed after withdrawal.\n def auto_dispose= (x)\n change_options({\"auto-dispose\" => x})\n end\n\n def sync\n info[\"sync\"]\n end\n\n def sync= (x)\n change_options({\"sync\" => x})\n end\nend\n\n\nclass HoseNotAddableToGangError < StandardError ; end\n\n# A HoseGang is a collection of #Hose objects that are treated as a single entity for the purposes of reading.\nclass HoseGang\n attr_accessor :tributaries\n attr_accessor :_awaiter\n\n def initialize (*args)\n @tributaries = Array.new\n args.each do |hose_or_string|\n add_tributary hose_or_string\n end\n end\n\n # Returns the next #Protein from whichever #Pool in the gang has an available protein first.\n def next (timeout=NO_WAIT)\n return @_awaiter ? @_awaiter.next(timeout) : nil\n end\n\n # Tests whether the provided object can be added to a gang. To be addable, it must behave like or truly be a #Hose.\n def is_addable? (hose_duck)\n hose_duck.respond_to?(:next) && hose_duck.respond_to?(:add_trib__dispatch)\n end\n\n # Ads a #Hose to the gang\n def add_tributary (hose_or_string)\n if is_addable? hose_or_string\n hose_or_string.add_trib__dispatch self\n @tributaries.push hose_or_string\n return self\n else\n h = Hose.new hose_or_string\n if is_addable? h\n h.add_trib__dispatch self\n @tributaries.push h\n return self\n end\n end\n raise HoseNotAddableToGangError,\n \"hose doesn't support :next and :add_trib__dispatch\"\n end\n\n # Removes a #Hose from the gang\n def remove_tributary (hose_or_hosename)\n return false if ! @_awaiter\n\n # support being passed either a hose object or a string which we\n # assume to be a hose name. in either case, we'll remove all\n # tributaries that correspond\n if hose_or_hosename.respond_to? :to_str\n name_to_find = hose_or_hosename.to_str\n hs = tributaries.select { |t| t.name == name_to_find }\n else\n hs = tributaries.select { |t| t == hose_or_hosename }\n end\n\n hs.each do |h|\n @_awaiter.remove_hose h\n tributaries.delete h\n end\n return hs.size > 0\n end\n\n # Adds a #Hose to the gang\n def add_standard_c_hose_tributary (hose)\n @_awaiter ||= GangBasicAwaiter.new self\n @_awaiter.add_hose hose\n end\n\n # Withdraw all Hose objects from all pools\n def withdraw\n hs = @tributaries.select { |t| t.respond_to?(:withdraw) }\n if _awaiter\n hs.each { |h| _awaiter.remove_hose(h) }\n end\n hs.each { |h| h.withdraw }\n @tributaries = Array.new\n end\nend\n\n\nclass GangBasicAwaiter\n attr_accessor :_hose_gang\n\n def initialize (containing_gang)\n @containing_gang_ref = WeakRef.new containing_gang\n @_hose_gang ||= _c_initialize_gang\n end\n\n # Wait for and return the next protein. The timeout argument specifies how long to wait\n # for a protein:\n # * timeout == POOL_WAIT_FOREVER (-1): Wait forever\n # * timeout == POOL_NO_WAIT (0) : Don't wait at all\n # * timeout > 0 : Return after this many seconds.\n #\n # Returns POOL_AWAIT_TIMEDOUT if no protein arrived before the\n # timeout expired.\n def next (timeout)\n _c_await_next timeout\n end\n\n def add_hose (hose)\n _c_add_hose hose\n end\n\n def remove_hose (hose)\n _c_remove_hose hose\n end\n\n\nend\n\n\nend\n" }, { "alpha_fraction": 0.6341463327407837, "alphanum_fraction": 0.6585366129875183, "avg_line_length": 31.799999237060547, "blob_id": "4617d009b593d0572eb886d0c7f53b09e26ce5c6", "content_id": "e2f796d19c91c7fd467468d58242728b8851a0f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 164, "license_type": "no_license", "max_line_length": 110, "num_lines": 5, "path": "/scripts/niteworks/mvDataLoad.sh", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nroot=$(cd `dirname $0`/../..; echo $PWD)\n\nexec \"${root}/scripts/rubydo\" ruby ${root}/scripts/niteworks/mvDataLoad.rb -v -s localhost -m localhost -c 100\n" }, { "alpha_fraction": 0.5382771492004395, "alphanum_fraction": 0.5447190999984741, "avg_line_length": 27.89610481262207, "blob_id": "7d20740258fd0fbfa122544c484dc3d023380e17", "content_id": "55b3891a5004e897459a7a144f3694f25d5a7ceb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6675, "license_type": "no_license", "max_line_length": 123, "num_lines": 231, "path": "/scripts/niteworks/generate_loan_fluoroscope.py", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "import os\nfrom plasma import yamlio, protein\nfrom plasma.obtypes import obmap, oblist\n\nTREATMENT_ROOT = os.path.join(os.path.dirname(__file__), '..', '..')\nCOIN_BASE_DIR = \"mutualVision/images/coins\"\nCOINS_ROOT = os.path.join(TREATMENT_ROOT, 'share', COIN_BASE_DIR)\nCOIN_DIRS = os.listdir(COINS_ROOT)\n\n\ndef ingest_default_shaders(protein):\n defaultShaders = {\n 'path': {\n 'fragment':'ribbons.frag',\n 'vertex':'ribbons.vert'\n },\n 'point': {\n 'fragment':'network.frag',\n 'vertex':'network.vert'\n }\n }\n\n protein.update_ingests(default_shaders=defaultShaders) \n return\n\n\ndef ingest_hover(protein):\n defaultHover = {\n 'max-found':256,\n 'min_zoom':1.0,\n 'glyph': 'sluice/sharkmouth.png'\n }\n protein.update_ingests(hover=defaultHover)\n return\n\n\ndef ingest_boilerplate(protein, name):\n #protein.update_ingests(**{'display-text':'{ ' + name + ' }'})\n protein.update_ingests(**{'display-text':name})\n protein.update_ingests(name=name.replace(' ', '-').lower())\n\n #Make this customizable\n protein.update_ingests(icon='mutualVision/images/loanicon.png')\n\n #Make this customizable\n protein.update_ingests(type='network')\n\n\n ingest_default_shaders(protein)\n ingest_hover(protein)\n return\n\n\ndef ingest_kinds(protein, kinds):\n protein.update_ingests(kinds=kinds)\n return\n\n\ndef ingest_pigments(protein, pigments):\n protein.update_ingests(pigments=pigments)\n return\n\n\ndef build_enable_menu():\n enableMenu = {\n 'name':'enable-menu',\n 'selection-type':'exclusive',\n 'contents': [{\n 'name': True,\n 'display-text': 'Enable',\n 'selected': True\n },\n {\n 'name': False,\n 'display-text': 'Disable',\n 'selected': False\n }]\n }\n\n return enableMenu\n\n\ndef build_opacity():\n opacity = {\n 'name': 'opacity',\n 'selection-type': 'exclusive',\n 'contents': [{\n 'name': '0.25',\n 'display-text': '25%',\n 'selected': 0,\n },\n {\n 'name': '0.50',\n 'display-text': '50%',\n 'selected': 0,\n },\n {\n 'name': '0.75',\n 'display-text': '75%',\n 'selected': 0,\n },\n {\n 'name': '1.00',\n 'display-text': '100%',\n 'selected': 1,\n }]\n }\n return opacity\n\n\ndef build_enabled_kinds(protein, kinds):\n enabledKinds = {\n 'name': 'enabled-kinds',\n 'display-text': 'Filter Options',\n 'selection-type': 'inclusive',\n 'contents': []\n }\n for kind in kinds:\n enabledKind = {'name':kind, 'display-text':kind, 'selected':True}\n enabledKinds['contents'].append(enabledKind)\n\n return enabledKinds\n\n\ndef ingest_attributes(protein, kinds):\n attributes = []\n #Make this customizable\n attributes.append(build_enable_menu())\n #Make this customizable\n attributes.append(build_opacity())\n\n attributes.append(build_enabled_kinds(protein, kinds))\n\n protein.update_ingests(attributes=attributes)\n return\n\n\ndef gen_ingests(fluoroProtein, name, kinds, pigments):\n ingest_boilerplate(fluoroProtein, name)\n ingest_kinds(fluoroProtein, kinds)\n ingest_pigments(fluoroProtein, pigments)\n ingest_attributes(fluoroProtein, kinds)\n return\n\n\ndef get_kinds(resources):\n return resources.keys()\n\n\ndef get_pigments(resources):\n SIZE_VALUE = 1.0\n SIZE_TYPE = 'SoftFloat'\n TYPE = 'point'\n COLOR_WHITE = [ 1.0, 1.0, 1.0, 1.0 ] #RGBA\n\n pigments = []\n for name, resource in resources.iteritems():\n for icon in resource:\n iconName, fileExt = os.path.splitext(os.path.basename(icon))\n pigment = {\n 'name':iconName, \n 'icon':COIN_BASE_DIR + '/' + name + '/' + icon,\n 'type':TYPE,\n 'size': {\n 'type':SIZE_TYPE,\n 'value':SIZE_VALUE\n },\n 'color': {\n 'type': 'SoftColor',\n 'value': oblist(COLOR_WHITE) \n }\n }\n pigments.append(pigment)\n return pigments\n\n\ndef gen_fluoroscope(fluoroName, resources):\n fluoroProtein = protein.Protein()\n fluoroProtein.set_descrips('sluice','prot-spec v1.0','request','new-fluoro-template')\n\n gen_ingests(fluoroProtein, fluoroName, get_kinds(resources), get_pigments(resources))\n return fluoroProtein\n \n\ndef update_inculcators(protein, pigments, resources):\n inculcators = protein.ingests()['inculcators']\n\n for kind, resource in resources.iteritems():\n for icon in resource:\n iconName, fileExt = os.path.splitext(os.path.basename(icon))\n inculcatorName = iconName + '_inc'\n if(not any(d['name'] == inculcatorName for d in inculcators)):\n inculcator = {\n 'name': inculcatorName, \n 'kinds': [ kind ],\n 'pigment': iconName,\n 'jstest' : \"parseInt(observation(n, 'Coins', t)) == \" + iconName.split('-')[-1]\n }\n inculcators.append(inculcator)\n protein.update_ingests(inculcators=inculcators)\n return\n\n\ndef main():\n coinFiles = {}\n fluoroFilename = os.path.join(os.path.dirname(__file__), '..', '..', 'etc', 'mutualVision', 'loan.protein')\n inculcatorsFilename = os.path.join(os.path.dirname(__file__), '..', '..', 'etc', 'mutualVision', 'inculcators.protein')\n\n for theDir in COIN_DIRS:\n\tcoinFiles[theDir] = os.listdir(COINS_ROOT + '/' + theDir)\n\n fluoroName = 'Loans'\n fluoroProtein = gen_fluoroscope(fluoroName, coinFiles)\n \n #fluoroFilename = fluoroName.replace(' ', '-').lower() + '-fluoro.protein'\n proteinFile = file(fluoroFilename, 'w')\n proteinFile.write(yamlio.dump_yaml_protein(fluoroProtein))\n\n\n inculcatorsProtein = yamlio.parse_yaml_protein(file(inculcatorsFilename, 'r'))\n\n update_inculcators(inculcatorsProtein, fluoroProtein, coinFiles)\n\n inculcatorFile = file(inculcatorsFilename, 'w')\n inculcatorFile.write(yamlio.dump_yaml_protein(inculcatorsProtein))\n\n return\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4297945201396942, "alphanum_fraction": 0.4297945201396942, "avg_line_length": 21.384614944458008, "blob_id": "0799ca0badfaab347ebd81e3afb8820bd2379dca", "content_id": "60c4afdbed092a9709e1c5b8254d8b94b470a7d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 584, "license_type": "no_license", "max_line_length": 57, "num_lines": 26, "path": "/web/modules/niteworks/public/javascript/dashboard.js", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "\n$(document).ready(function(){\n\n $('#stats').slideDown('slow', function(){\n \t$('#activity').show('slow', function(){\n\n\n\t \t $('#messages').show('slow', function(){\n\n\t \t \t$('.tiles').show(function(){\n\t \t \t\t$('.tile').each(function(){\n\n\t\t\t\t\t $(this).slideDown('slow');\n\t\t\t\t\t});\n\t \t \t});\n\n\t \t \t$('#growth').slideDown('slow', function(){\n\t \t \t\t$('#brassband').slideDown('slowest', function(){\n\t \t \t\t\t$('#daryl').slideDown('slow', function(){\n\t \t \t\t\t\t$('#council').fadeIn('slowest');\n\t \t \t\t\t});\n\t \t \t\t});\n\t \t \t});\n\t \t });\n \t });\n });\n});\n\n" }, { "alpha_fraction": 0.5336898565292358, "alphanum_fraction": 0.5529412031173706, "avg_line_length": 18.893617630004883, "blob_id": "53ae0469c2ba629c25d5b503a1a5ddae3f961361", "content_id": "4c56fe07210bde04ae54a5075881d773190dbd2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 935, "license_type": "no_license", "max_line_length": 50, "num_lines": 47, "path": "/web/modules/niteworks/public/javascript/streetcams.js", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "$(document).ready(function () {\n\n var MOVIE_POOL = 'tcp://localhost/movie';\n var VID_SPEED = 1.0;\n\n function setVidSpeed() {\n Plasma\n .Hose(MOVIE_POOL)\n\t.Deposit({ descrips: ['movie', 'set-play-speed'],\n ingests: { 'rate': VID_SPEED } });\n }\n\n // Handles the play button\n $(\"#rewind\").click(function(e) {\n e.preventDefault();\n if (VID_SPEED >= 0.0)\n\tVID_SPEED = -1.0;\n else\n\tVID_SPEED = VID_SPEED-1.0;\n setVidSpeed();\n });\n\n // Handles the play button\n $(\"#play\").click(function(e) {\n e.preventDefault();\n VID_SPEED = 1.0;\n setVidSpeed();\n });\n\n // Handles the play button\n $(\"#pause\").click(function(e) {\n e.preventDefault();\n VID_SPEED = 0.0;\n setVidSpeed();\n });\n\n // Handles the play button\n $(\"#ff\").click(function(e) {\n e.preventDefault();\n if (VID_SPEED <= 0.0)\n VID_SPEED = 1.0;\n else\n VID_SPEED = VID_SPEED+1.0;\n setVidSpeed();\n });\n\n});\n" }, { "alpha_fraction": 0.5457317233085632, "alphanum_fraction": 0.5807400941848755, "avg_line_length": 25.87005615234375, "blob_id": "f3377eda5fc32b280d1dcecdf5a805a21b0b8eef", "content_id": "97a0a8ff673baae9d71f3e36378edbf3531c4d15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 9512, "license_type": "no_license", "max_line_length": 238, "num_lines": 354, "path": "/scripts/niteworks/mvDataLoad.rb", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "require 'rubygems'\nrequire 'metabolizer'\nrequire 'thread'\nrequire 'mongo'\nrequire 'optparse'\nrequire 'date'\n\ninclude Plasma\ninclude Mongo\n\n@@verbose = false\n@@sluiceHost = 'localhost'\n@@mongoDB = 'localhost'\n@@chunks = 100\n\n# Parse options using OptionParser\noptparse = OptionParser.new do |opt|\n opt.on('--verbose', '-v') { @@verbose = true }\n opt.on('-s', '--sluice SLUICEHOST', 'Sluice host') do |x|\n @@sluiceHost = x\n end\n opt.on('-m', '--mongodb MONGOHOST', 'MongoDB host') do |x|\n @@mongoDB = x\n end\n opt.on('-c', '--chunks CHUNKS', 'Chunk size') do |x|\n @@chunks = x\n end\nend\noptparse.parse!\n\nif @@verbose\n puts \"sluiceHost: \" + @@sluiceHost.to_s\n puts \"mongoDB: \" + @@mongoDB.to_s\n puts \"chunks: \" + @@chunks.to_s\nend\n\nclass Hearty < Metabolizer\n attr_accessor :verbose\n\n @outdescrips = ['sluice', 'prot-spec v1.0', 'topology', 'add' ]\n @hose\n @db\n\n def initialize(*hoses)\n puts \"starting MV Data Load daemon\" if @verbose\n super(*hoses)\n @descrips = ['sluice', 'prot-spec v1.0', 'psa', 'heartbeat']\n @count = 0\n appendMetabolizer(@descrips) { |p| receive p }\n end\n\n def receive(p)\n puts \"Got heartbeat protein from sluice\" if @@verbose\n\n LoadData()\n\n puts \"Data has all loaded, I'm outta here\"\n exit 1\n end\n\n def LoadPOIs()\n puts 'loading POIs'\n uniqueItems = Set.new\n arrItems = []\n kind = 'poi'\n\n uniqueId = kind + '_poi_1'\n uniqueItems.add(uniqueId)\n ing = BuildIngest(uniqueId, 48.9244627, 2.3579705, kind, { 'Text' => 'Stade De France', 'timestamp' => 1447449600000 }); # 9:20\n arrItems.push(ing) \n\n uniqueId = kind + '_poi_2'\n uniqueItems.add(uniqueId)\n ing = BuildIngest(uniqueId, 48.8716804,2.3659606, kind, { 'Text' => 'Le Petit Cambodge', 'timestamp' => 1447449900000 }); # 9:25\n arrItems.push(ing) \n\n uniqueId = kind + '_poi_3'\n uniqueItems.add(uniqueId)\n ing = BuildIngest(uniqueId, 48.868166,2.3715372, kind, { 'Text' => 'Rue de la Fountaine au Roi', 'timestamp' => 1447450320000 }); # 9:32\n arrItems.push(ing) \n\n uniqueId = kind + '_poi_4'\n uniqueItems.add(uniqueId)\n ing = BuildIngest(uniqueId, 48.8791313,2.3476176, kind, { 'Text' => 'Le Belle Equipe', 'timestamp' => 1447450560000 }); # 9:36\n arrItems.push(ing) \n\n uniqueId = kind + '_poi_5'\n uniqueItems.add(uniqueId)\n ing = BuildIngest(uniqueId, 48.8713992,2.2599972, kind, { 'Text' => 'Boulevard Voltaire', 'timestamp' => 1447450800000 }); # 9:40\n arrItems.push(ing) \n\n uniqueId = kind + '_poi_6'\n uniqueItems.add(uniqueId)\n ing = BuildIngest(uniqueId, 48.8630134,2.368421, kind, { 'Text' => 'Bataclan', 'timestamp' => 1447450800000 }); # 9:40\n arrItems.push(ing) \n \n PokeProtein(Protein.new(['sluice', 'prot-spec v1.0', 'topology', 'add' ], { 'topology' => arrItems }))\n puts 'POIs loaded: ' + uniqueItems.size.to_s \n end\n\n def LoadTweetsGreen()\n\n\n # {\"twitter.coordinates.coordinates\": {\"$exists\": false }, \"twitter.place.bounding_box.coordinates\": { \"$exists\": true} }\n uniqueItems = Set.new\n arrItems = []\n progress = 0\n \n filter = { 'twitter.coordinates.coordinates' => { '$exists' => false }, 'twitter.place.bounding_box.coordinates' => { '$exists' => true } }\n\n projection = ['twitter.coordinates', 'twitter.id_str', 'twitter.text', 'twitter.user.id_str', 'twitter.user.name', 'twitter.user.screen_name', 'twitter.retweet_count', 'twitter.timestamp_ms', 'twitter.place', 'twitter.entities.media']\n\n @db.collection(\"tweets\").find(filter , :fields => projection).each do |row|\n\n tweet = row['twitter']\n\n kind = 'tweet_green'\n\n uniqueId = kind + tweet['id_str']\n if (uniqueItems.include?(uniqueId))\n next\n end\n uniqueItems.add(uniqueId)\n \n if (tweet['entities']['media'].nil?)\n imgUrl = ''\n else\n if (tweet['entities']['media'][0]['type'] == 'photo') \n imgUrl = tweet['entities']['media'][0]['media_url']\n else\n imgUrl =''\n end\n end\n\n attrs = {\n 'tweetId' => tweet['id_str'],\n 'Text' => tweet['text'].to_s,\n 'user' => tweet['user']['screen_name'].to_s,\n 'ReTweetCount' => tweet['retweet_count'].to_s,\n 'hashtagScore' => BuildHashTagWeights(tweet['text'].downcase),\n 'media' => imgUrl,\n 'timestamp' => tweet['timestamp_ms'].to_i\n }\n\n lon = tweet['place']['bounding_box']['coordinates'][0][0][1]\n lat = tweet['place']['bounding_box']['coordinates'][0][0][0]\n\n ing = BuildIngest(kind + '_' + tweet['id_str'], lon, lat, kind, attrs);\n\n arrItems.push(ing) \n progress += 1\n\n if (progress >= @@chunks.to_i)\n PokeProtein(Protein.new(['sluice', 'prot-spec v1.0', 'topology', 'add' ], { 'topology' => arrItems }))\n progress = 0\n arrItems = []\n end\n end\n PokeProtein(Protein.new(['sluice', 'prot-spec v1.0', 'topology', 'add' ], { 'topology' => arrItems }))\n puts 'Blue Tweets loaded: ' + uniqueItems.size.to_s \n\n\n end\n\n def LoadTweetsBlue()\n uniqueItems = Set.new\n arrItems = []\n progress = 0\n # filter = { } # {\"twitter.coordinates.coordinates\": {\"$exists\":true } } { 'LAT' => { '$exists' => true } }\n filter = { 'twitter.coordinates.coordinates' => { '$exists' => true } }\n\n projection = ['twitter.coordinates', 'twitter.id_str', 'twitter.text', 'twitter.user.id_str', 'twitter.user.name', 'twitter.user.screen_name', 'twitter.retweet_count', 'twitter.timestamp_ms', 'twitter.entities.media']\n\n @db.collection(\"tweets\").find(filter , :fields => projection).each do |row|\n\n\n tweet = row['twitter']\n\n if (tweet['coordinates'].nil?) \n next\n end \n\n kind = 'tweet_blue'\n\n uniqueId = kind + tweet['id_str']\n if (uniqueItems.include?(uniqueId))\n next\n end\n uniqueItems.add(uniqueId)\n\n if (tweet['entities']['media'].nil?)\n imgUrl = ''\n else\n if (tweet['entities']['media'][0]['type'] == 'photo') \n imgUrl = tweet['entities']['media'][0]['media_url']\n else\n imgUrl =''\n end\n end\n \n attrs = {\n 'tweetId' => tweet['id_str'],\n 'Text' => tweet['text'].to_s,\n 'user' => tweet['user']['screen_name'].to_s,\n 'ReTweetCount' => tweet['retweet_count'].to_s,\n 'media' => imgUrl,\n 'hashtagScore' => BuildHashTagWeights(tweet['text'].downcase),\n 'timestamp' => tweet['timestamp_ms'].to_i\n }\n ing = BuildIngest(kind + '_' + tweet['id_str'], tweet['coordinates']['coordinates'][1], tweet['coordinates']['coordinates'][0], kind, attrs);\n\n arrItems.push(ing) \n progress += 1\n\n if (progress >= @@chunks.to_i)\n PokeProtein(Protein.new(['sluice', 'prot-spec v1.0', 'topology', 'add' ], { 'topology' => arrItems }))\n progress = 0\n arrItems = []\n end\n end\n PokeProtein(Protein.new(['sluice', 'prot-spec v1.0', 'topology', 'add' ], { 'topology' => arrItems }))\n puts 'Blue Tweets loaded: ' + uniqueItems.size.to_s \n end\n\n\n def LoadData()\n puts \"Start time: \" + Time.now.inspect\n @hose = Plasma::Pool.participate 'tcp://' + @@sluiceHost + '/topo-to-sluice'\n \tmongo_client = MongoClient.new(@@mongoDB, 27017, :pool_size => 5)\n \t@db = mongo_client.db(\"niteworks\")\n\n # t1 = Thread.new{ LoadBranches() }\n # t2 = Thread.new{ LoadBuildingSocs() }\n # t3 = Thread.new{ LoadIntroducers() }\n # t4 = Thread.new{ LoadCustomers() }\n # t5 = Thread.new{ LoadLoans() }\n t4 = Thread.new{LoadPOIs()}\n t5 = Thread.new{LoadTweetsGreen()}\n t6 = Thread.new{LoadTweetsBlue()}\n t6.join\n t5.join\n t4.join\n # t1.join\n # t2.join\n # t3.join\n # t4.join\n # t5.join\n\n @hose.withdraw()\n puts \"End time: \" + Time.now.inspect\n end\n\n def BuildAddr(line1 = '', line2 = '', line3 = '', line4 = '')\n\n\n return line1\n end\n\n def BuildKind(prefix, gender, age)\n\n g = 'm'\n\n if (gender.downcase == 'female')\n g = 'f'\n end\n\n case age\n when 0..15\n a = 0\n when 16..24\n a = 16\n when 25..54\n a = 25\n when 55..200\n a = 55\n else\n a = age\n end\n\n retVal = prefix + '_' + g + '_' + a.to_s;\n return retVal;\n end\n\n\n def BuildHashTagWeights(text)\n return '0.0'\n #parisattacks\n #prayforparis\n #paris\n #isis\n #trump2016\n\n retVal = 0\n\n if text.include? \"#parisattacks\"\n retVal += 5\n end\n if text.include? \"#prayforparis\"\n retVal += 4\n end\n if text.include? \"#paris\"\n retVal += 3\n end\n if text.include? \"#isis\"\n retVal += 2\n end\n if text.include? \"#trump2016\"\n retVal += 1\n end\n\n return retVal.round(1).to_s\n\n end \n\n def BuildIngest(itemId, latitiude, longitude, kind, attributesContent)\n# puts attributesContent['time']\n\n# timestamp: 2008-04-03 18:26:07\n# 'time' => Time.at(tweet['timestamp_ms'].to_i / 1000).to_datetime\n\n theTime = Time.at(attributesContent['timestamp'].to_i / 1000).to_datetime.to_s\ntheTime.sub! 'T', ' '\n# puts theTime\n\n ingest = {\n 'attrs' => attributesContent,\n 'id' => itemId,\n 'loc' => [latitiude.to_f, longitude.to_f, 0.0],\n 'kind' => kind,\n 'timestamp' => theTime \n }\n\n return ingest\n end\n\n def PokeProtein(protein)\n @hose.deposit(protein)\n end\nend\n\npool = 'sluice-to-heart'\n\nrespire = 0.1\n\nh = Hearty.new pool\n\nsleep(5)\n\ntrap 'SIGINT', proc {\n puts \"Ending MV Hearty daemon\"\n h.quit = true\n}\n\nh.metabolize respire\n" }, { "alpha_fraction": 0.5870967507362366, "alphanum_fraction": 0.5887096524238586, "avg_line_length": 16.22222137451172, "blob_id": "48eb6e7ce8e48fe6ea1655d8097156d365267de8", "content_id": "55799c585a94014d6072dc98c0e8da697dc37cfa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 620, "license_type": "permissive", "max_line_length": 55, "num_lines": 36, "path": "/web/modules/niteworks/webpanel/public/javascripts/tags.js", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "var words = [];\n\nvar keywordswords = [];\n\n$( document ).ready(function() {\n\n\t$.getJSON('/mongo/gettagcounts', function(data) {\n\t\t//populateUserTable();\n\t\tconsole.log(data);\n\t\t$.each(data, function() {\n\t\t\tvar tag = {\n\t\t\t\ttext: this.word, \n\t\t\t\tweight: this.count\n\t\t\t}\n\n\t\t\twords.push(tag);\n\t\t});\n\n\t\t$('#keywords').jQCloud(words);\n \t});\n\n \t$.getJSON('/mongo/getkeywordcounts', function(data) {\n\t\t//populateUserTable();\n\t\tconsole.log(data);\n\t\t$.each(data, function() {\n\t\t\tvar tag = {\n\t\t\t\ttext: this.keyword, \n\t\t\t\tweight: this.count\n\t\t\t}\n\n\t\t\tkeywordswords.push(tag);\n\t\t});\n\n\t\t$('#keywords2').jQCloud(keywordswords);\n \t});\n});\n" }, { "alpha_fraction": 0.6361290216445923, "alphanum_fraction": 0.6929032206535339, "avg_line_length": 37.75, "blob_id": "4a18d8e0e2308465adc8ab28c3002c29cd9069cb", "content_id": "26b84b2a3df1ce1a16252ff43d7b37e8254d6144", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 775, "license_type": "no_license", "max_line_length": 77, "num_lines": 20, "path": "/scripts/rubydo", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nroot=$(cd `dirname $0`/.. && echo $PWD)\n\nexport RUBYLIB=\"${RUBYLIB}:/Library/Ruby/Gems/2.0.0/gems/rmagick-2.13.2/lib\"\n\nexport RUBYLIB=\"${RUBYLIB}:/Library/Ruby/Gems/2.0.0/gems/mongo-1.12.0/lib/\"\nexport RUBYLIB=\"${RUBYLIB}:/Library/Ruby/Gems/2.0.0/gems/bson-1.12.0/lib/\"\nexport RUBYLIB=\"${RUBYLIB}:/Library/Ruby/Gems/2.0.0/gems/bson_ext-1.12.0/lib\"\n\nexport RUBYLIB=\"${RUBYLIB}:/var/lib/gems/1.8/gems/mongo-1.12.0/lib/\"\nexport RUBYLIB=\"${RUBYLIB}:/var/lib/gems/1.8/gems/bson-1.12.0/lib/\"\n\nexport RUBYLIB=\"${RUBYLIB}:${root}/lib/ruby\"\nexport RUBYLIB=\"${RUBYLIB}:/opt/mct/sluice/lib/ruby\"\nexport RUBYLIB=\"${RUBYLIB}:/opt/mct/sluice/deps/lib/ruby\"\nexport RUBYLIB=\"${RUBYLIB}:/opt/mct/sluice/bin\"\nexport RUBYLIB=\"${RUBYLIB}:/opt/oblong/g-speak3.14/lib/ruby\"\n\nexec \"$@\"\n" }, { "alpha_fraction": 0.4911602735519409, "alphanum_fraction": 0.4950246214866638, "avg_line_length": 33.38870620727539, "blob_id": "123df3fc2b36bc8229f704329b7a2cd93a62fcd0", "content_id": "ccadb268819866196c52683e8849da62f126b0f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 10351, "license_type": "no_license", "max_line_length": 115, "num_lines": 301, "path": "/web/modules/showrunner/static/runner/js/runner.js", "repo_name": "jewkesy/legendary-happiness", "src_encoding": "UTF-8", "text": "$(document).ready(function() {\n\n // var timeline = new Timeline($('#range-set'));\n // // initialize time range\n // timeline.setTimeRangeMonthly();\n\n function EdgeToSluice() { return Plasma.Hose('edge-to-sluice'); }\n function SluiceToEdge() { return Plasma.Hose('sluice-to-edge'); }\n\n const slc_s = 'sluice';\n const prs_s = 'prot-spec v1.0';\n const req_s = 'request';\n const rmf_s = 'remove-all-fluoro'\n const zom_s = 'zoom';\n const flist_s = 'fluoroscopes';\n\n var desiredFluorder = ['Map','Demographics','Heatmap','Weather'];\n\n\n // Keep us up to date on the center of things.\n var center_lat = undefined, center_lon = undefined;\n var main_zoom = 0.0;\n var fluoro_list = [];\n SluiceToEdge()\n .Match([slc_s, prs_s, 'psa', 'atlas-view'])\n .Await(function(p) {\n var ing = p.ingests;\n center_lat = ing.lat_center;\n center_lon = ing.lon_center;\n main_zoom = ing.level;\n });\n SluiceToEdge()\n .Match([slc_s, prs_s, 'psa', 'fluoroscopes'])\n .Await(function(p) {\n var ing = p.ingests;\n //change the global\n fluoro_list = ing.fluoroscopes;\n });\n //Request a fluoroscope list to get one\n EdgeToSluice()\n .Deposit({ descrips: [slc_s, prs_s, req_s, flist_s],\n ingests: {}}\n );\n\n Array.prototype.move = function (from, to) {\n this.splice(to, 0, this.splice(from, 1)[0]);\n };\n // Keep track of the current fluoroscope Z-order.\n// SluiceToEdge()\n// .Match([slc_s, prs_s, 'psa', 'fluoroscopes'])\n// .Await( function(p){\n// var fluoroscopes = p.ingests.fluoroscopes;\n// var curFluorder = [];\n// for(var f=0; f<fluoroscopes.length; ++f){\n// curFluorder.push(fluoroscopes[f]['name']);\n// }\n// // console.log(\"old\");\n// // console.log(curFluorder);\n// for(var i=0; i<desiredFluorder.length; ++i){\n// // for(var j=0; j<curFluorder.length; ++j){\n// // if(curFluorder.indexOf(desiredFluorder[i]) != null){\n// if(curFluorder.indexOf(desiredFluorder[i]) >\n// curFluorder.indexOf(desiredFluorder[i+1])){\n//\n// curFluorder.move(curFluorder.indexOf(desiredFluorder[i+1]),\n// curFluorder.indexOf(desiredFluorder[i]));\n// // console.log(\"new\");\n// // console.log(curFluorder);\n// reorder_and_send_sluice(curFluorder, fluoroscopes);\n// }\n// // }\n// }\n// return;\n// });\n function PlasmaDeposit(hose, msg) {\n Plasma.Hose(hose).Deposit(msg);\n }\n\n function EdgeToSluiceDeposit(msg) {\n EdgeToSluice().Deposit(msg);\n }\n\n function bookmark(lat, lon, level, interp) {\n if(interp == null){\n interp = 5.0;\n }\n EdgeToSluice()\n .Deposit({ descrips: [slc_s, prs_s, req_s, zom_s],\n ingests: {\n \"lat\": lat,\n \"lon\": lon,\n \"level\": level,\n \"interp-time\": interp\n }});\n };\n\n function add_sticky(stickytext){\n //send the sticky to sluice\n Plasma\n .Hose ('tcp://localhost/stickie-notes')\n .Deposit({\n descrips: ['sluice', 'prot2.0', 'stickie', 'create'],\n ingests: {\n 'text': stickytext\n }\n });\n };\n\n function update_fluoros_attrs(name, args) {\n //WARNING: Only updates, does not add\n for (var i=0; i < fluoro_list.length; i++) {\n if (fluoro_list[i].name == name) {\n //Update this fluoroscope\n var fluoro = fluoro_list[i];\n for (var j=0; j < fluoro.attributes.length; j++){\n if (args.hasOwnProperty(fluoro.attributes[j].name)) {\n var attr_name = fluoro.attributes[j].name;\n fluoro.attributes[j] = args[attr_name];\n fluoro.attributes[j].name = attr_name;\n }\n }\n EdgeToSluice()\n .Deposit({ descrips: [slc_s, prs_s, req_s, 'configure-fluoro'],\n ingests: fluoro});\n }\n }\n }\n\n function add_fluoro_args(name, ing) {\n ing['name'] = name;\n EdgeToSluice()\n .Deposit({ descrips: [slc_s, prs_s, req_s, 'new-fluoro-instance'],\n ingests: ing });\n }\n\n function fluoroAlreadyLoaded(name) {\n // console.log(fluoro_list)\n for (var i=0; i < fluoro_list.length; i++) {\n // console.log(fluoro_list[i])\n if (fluoro_list[i].name == name) {\n reorder_and_send_sluice([name]);\n return true;\n }\n }\n return false;\n }\n\n function add_fluoroscope(name) {\n if ($(\"#uniqueFluoros\").attr('checked') && fluoroAlreadyLoaded(name)) return;\n\n EdgeToSluice()\n .Deposit({ descrips: [slc_s, prs_s, req_s, 'new-fluoro-instance'],\n ingests: {\"name\":name}});\n }\n\n function add_fluoroscopeWithBounds(name, tr, bl) {\n if ($(\"#uniqueFluoros\").attr('checked') && fluoroAlreadyLoaded(name)) return;\n\n EdgeToSluice()\n .Deposit({ descrips: [slc_s, prs_s, req_s, 'new-fluoro-instance'],\n ingests: {\"name\":name, \"tr\":tr, \"bl\":bl}});\n }\n\n function remove_fluoroscope(name) {\n for (var i=0; i < fluoro_list.length; i++) {\n if (fluoro_list[i].name == name) {\n var fluoro = fluoro_list[i];\n console.log(fluoro)\n remove_fluoroById(fluoro.SlawedQID)\n }\n }\n }\n\n function remove_fluoroById(slawId) {\n EdgeToSluice()\n .Deposit({ descrips: [slc_s, prs_s, req_s, 'remove-fluoro-instance'],\n ingests: {\"SlawedQID\": slawId}});\n }\n\n function clear_fluoroscopes() {\n EdgeToSluice()\n .Deposit({ descrips: [slc_s, prs_s, req_s, rmf_s],\n ingests: {}});\n }\n\n function reorder_and_send_sluice(fluorder){\n fluoroscopes = fluoro_list;\n var len = fluorder.length;\n var sortedFluoros = [];\n for(var i=0; i<len; ++i){\n for(var j=0; j<fluoroscopes.length; ++j){\n if(fluorder[i] == fluoroscopes[j]['name']){\n sortedFluoros.push(fluoroscopes[j]);\n }\n }\n }\n EdgeToSluice()\n .Deposit({ descrips:[slc_s, prs_s, req_s, 'reorder-z-axis'],\n ingests:{\"scopes\":sortedFluoros}});\n }\n\n function getFluoros() {\n return fluoro_list;\n }\n\n //Share all the useful functions\n //TODO: Find a better way to do this\n var runner = {\n reorder_and_send_sluice: reorder_and_send_sluice,\n getFluoros: getFluoros,\n fluoroAlreadyLoaded: fluoroAlreadyLoaded,\n remove_fluoroscope: remove_fluoroscope,\n update_fluoros_attrs: update_fluoros_attrs,\n clear_fluoroscopes: clear_fluoroscopes,\n add_fluoroscope: add_fluoroscope,\n add_fluoroscopeWithBounds: add_fluoroscopeWithBounds,\n add_fluoro_args: add_fluoro_args,\n bookmark: bookmark,\n // timeline: timeline,\n slc_s: slc_s,\n prs_s: prs_s,\n req_s: req_s,\n rmf_s: rmf_s,\n zom_s: zom_s,\n main_zoom: main_zoom,\n flist_s: flist_s,\n PlasmaDeposit: PlasmaDeposit,\n EdgeToSluiceDeposit: EdgeToSluiceDeposit\n }\n\n //////////////\n // Setup script buttons & functions\n //////////////\n var runner_config = load_runner_config(runner);\n var num_acts = 6;\n var num_scenes = 12;\n\n function _set_scene_button(button_config, target_name) {\n $(elem_id).click(function (evt) {\n evt.preventDefault();\n // console.log(target_name)\n button_config[1]();\n });\n }\n\n // Setup \"main\" buttons\n //TODO: Add playall button & method\n var valid_keys = ['fzin', 'fzout'];\n for (var act_i = 0; act_i <= num_acts; act_i++) {\n valid_keys.push('act'+act_i);\n }\n\n for (var i = 0; i < valid_keys.length; i++) {\n var key_name = valid_keys[i];\n var elem_id = '#' + key_name;\n var button_name = ''\n\n if (runner_config.hasOwnProperty(key_name)) {\n // runner_config has a function for key_name, bind it to an event\n var button_config = runner_config[key_name]\n button_name = button_config[0]\n _set_scene_button(button_config, key_name)\n }\n //Add button class\n $(elem_id).addClass('button');\n if (key_name.indexOf('act') > -1) {\n //set the act name\n $(elem_id).html('<div>'+button_name+'</div>')\n }\n }\n\n // Setup scene buttons\n for (var act_i = 0; act_i <= num_acts; act_i++) {\n for (var scene_i = 1; scene_i <= num_scenes; scene_i++) {\n //add a scene button\n var key_name = 'a' + act_i + 'scene' + scene_i\n var elem_id = '#' + key_name;\n\n if (runner_config.hasOwnProperty(key_name)) {\n // runner_config has a function for key_name, bind it to an event\n var button_config = runner_config[key_name]\n _set_scene_button(button_config, key_name)\n //Add button class\n $(elem_id).addClass('button');\n //Add number & text\n $(elem_id).html('<div class=\"num\">'+scene_i+'</div><div class=\"label\">'+button_config[0]+'</div>');\n } else {\n //Scene button, but nothing to run, add the ebutton class\n $(elem_id).addClass('ebutton');\n }\n }\n }\n\n $(\"input[type=checkbox]\").switchButton({\n checked: true,\n labels_placement: \"right\",\n width: 100,\n height: 40,\n button_width: 70\n });\n});\n" } ]
29
remschira/titanic
https://github.com/remschira/titanic
2f46c3137f8a303718344b7ca615a0099c44b039
3e1cce57f5781d6d76963c5986b457ea85f354cb
6a868a3b456ab7dd34483600ac24d6875123335d
refs/heads/master
2020-03-20T10:37:40.346598
2018-06-14T16:15:06
2018-06-14T16:15:06
137,377,095
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7738515734672546, "alphanum_fraction": 0.7738515734672546, "avg_line_length": 30.33333396911621, "blob_id": "ee1289297b14467ec0163d963f47a3ab1f7f408c", "content_id": "947010d1db092dcb3fa7599ec0b9f53b9601bfb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 283, "license_type": "no_license", "max_line_length": 85, "num_lines": 9, "path": "/README.md", "repo_name": "remschira/titanic", "src_encoding": "UTF-8", "text": "# titanic\nKaggle's \"Titanic: Machine Learning from Disaster\" competition\n\ndownload data from https://www.kaggle.com/c/titanic/data\n\nin directory where code is placed, make a \"data\" directory and an \"output\" directory.\n\n\ncopy the data downloaded from Kaggle in the ./data directory.\n\n" }, { "alpha_fraction": 0.5532065629959106, "alphanum_fraction": 0.5732474327087402, "avg_line_length": 39.88424301147461, "blob_id": "a425bfc74a8e2852297972d77bf33f4353e09bf9", "content_id": "b69214b5ab588f4e78b2e3178220c46edeb29421", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12724, "license_type": "no_license", "max_line_length": 112, "num_lines": 311, "path": "/titanic.py", "repo_name": "remschira/titanic", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\nfrom sklearn.model_selection import train_test_split,cross_val_score\nfrom sklearn.linear_model.logistic import LogisticRegression\nfrom sklearn.metrics import confusion_matrix, accuracy_score\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier,GradientBoostingClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.svm import LinearSVC,SVC\nfrom nameparser import HumanName\nfrom sklearn import preprocessing\n\nif __name__ == '__main__':\n\n rng = np.random.RandomState(42)\n\n\n path = './data/'\n fileName = 'train.csv'\n data = pd.read_csv(path+fileName) \n features = [i for i in data]\n\n\n y = ['Survived']\n #drop some of the columns from features. Such as 'Survived' which is the dependent variable.\n features = data.drop(['Survived','PassengerId','Ticket','Cabin'],axis=1)\n\n\n #Make a new df that will contain the each person's title.\n features_titles = pd.DataFrame(index=features.index,columns=['Title'])\n \n\n #This loop is where the titles are determined\n j = 0\n for i in features['Name']:\n name = HumanName(i)\n features_titles.loc[features.index[j]] = [name.title]\n j = j+1 \n\n #Concatenate features and features_titles\n features = pd.concat([features,features_titles],axis=1)\n\n\n\n\n\n #Split data\n X_train,X_test,y_train,y_test = train_test_split(\n features,data[y],test_size=0.33,random_state=rng)\n\n\n #produce boolean df's that contain title information\n title = X_train['Title']\n master = (title == 'Master.')\n mr = (title == 'Mr.') \n dr = (title == 'Dr.') \n miss = ( (title == 'Miss.') | (title == 'Ms.') |\n (title == 'Mlle.') )\n mrs = ( (title == 'Mrs.') | (title == 'Lady.') |\n (title == 'Mme.') | (title == 'the Countess. of') )\n\n #Separate the 'Miss.' title into the young (who have siblings and/or parents) and\n #into old (who don't have siblings or parents)\n young = (X_train['SibSp'] != 0) | (X_train['Parch'] !=0)\n miss_young = miss & young\n miss_old = miss & ~young\n\n\n #Find the median age for each Title category.\n age_master = X_train.loc[master,'Age'].median()\n age_mr = X_train.loc[mr,'Age'].median()\n age_dr = X_train.loc[dr,'Age'].median() \n age_miss_young = X_train.loc[miss_young,'Age'].median()\n age_miss_old = X_train.loc[miss_old,'Age'].median() \n age_mrs = X_train.loc[mrs,'Age'].median() \n\n\n #Fill in NaN ages with the median age for the correct Title category\n X_train.loc[master,'Age'] = X_train.loc[master,'Age'].fillna(age_master)\n X_train.loc[mr,'Age'] = X_train.loc[mr,'Age'].fillna(age_mr)\n X_train.loc[dr,'Age'] = X_train.loc[dr,'Age'].fillna(age_dr) \n X_train.loc[miss_old,'Age'] = X_train.loc[miss_old,'Age'].fillna(age_miss_old)\n X_train.loc[miss_young,'Age'] = X_train.loc[miss_young,'Age'].fillna(age_miss_young) \n X_train.loc[mrs,'Age'] = X_train.loc[mrs,'Age'].fillna(age_mrs) \n \n\n #If have NaN for 'Embarked', replace NaN with the mode of the 'Embarked' column\n X_train['Embarked'].fillna(X_train['Embarked'].mode()[0],inplace=True) #fill nan values with mode \n\n\n \n\n #Repeat above steps for the X_test data\n title = X_test['Title']\n master = (title == 'Master.')\n mr = (title == 'Mr.')\n\n dr = (title == 'Dr.') \n\n miss = ( (title == 'Miss.') | (title == 'Ms.') |\n (title == 'Mlle.') )\n mrs = ( (title == 'Mrs.') | (title == 'Lady.') |\n (title == 'Mme.') | (title == 'the Countess. of') )\n\n young = (X_test['SibSp'] != 0) | (X_test['Parch'] !=0)\n miss_young = miss & young\n miss_old = miss & ~young\n \n\n age_master = X_test.loc[master,'Age'].median()\n age_mr = X_test.loc[mr,'Age'].median()\n age_dr = X_test.loc[dr,'Age'].median()\n age_miss_young = X_test.loc[miss_young,'Age'].median()\n age_miss_old = X_test.loc[miss_old,'Age'].median() \n age_mrs = X_test.loc[mrs,'Age'].median() \n\n\n\n X_test.loc[master,'Age'] = X_test.loc[master,'Age'].fillna(age_master)\n X_test.loc[mr,'Age'] = X_test.loc[mr,'Age'].fillna(age_mr)\n X_test.loc[dr,'Age'] = X_test.loc[dr,'Age'].fillna(age_dr) \n X_test.loc[miss_old,'Age'] = X_test.loc[miss_old,'Age'].fillna(age_miss_old)\n X_test.loc[miss_young,'Age'] = X_test.loc[miss_young,'Age'].fillna(age_miss_young) \n X_test.loc[mrs,'Age'] = X_test.loc[mrs,'Age'].fillna(age_mrs) \n \n\n X_test['Embarked'].fillna(X_test['Embarked'].mode()[0],inplace=True) #fill nan values with mode \n\n\n\n #transform categorical to numeric values\n #Use the train encoding for the test data\n le=LabelEncoder()\n if X_train['Sex'].dtype=='object':\n le.fit(X_train['Sex'].values)\n X_train['Sex'] = le.transform(X_train['Sex'])\n X_test['Sex'] = le.transform(X_test['Sex'])\n\n\n if X_train['Embarked'].dtype=='object':\n le.fit(X_train['Embarked'].values)\n X_train['Embarked'] = le.transform(X_train['Embarked'])\n X_test['Embarked'] = le.transform(X_test['Embarked'])\n\n\n\n #remove some columns\n X_train = X_train.drop(['Name','Title'],axis=1)\n X_test = X_test.drop(['Name','Title'],axis=1) \n\n #scale data\n scaler = preprocessing.StandardScaler()\n scaler.fit(X_train)\n X_train_scaled = scaler.transform(X_train) #this converts pandas dataframe to numpy\n X_test_scaled = scaler.transform(X_test)\n\n X_train = pd.DataFrame(X_train, index=X_train.index, columns=X_train.columns)\n X_test = pd.DataFrame(X_test, index=X_test.index, columns=X_test.columns) \n \n \n c,r = y_train.shape \n y_train_reshape = y_train.values.reshape(c,) \n\n\n clf_gbm = GradientBoostingClassifier(n_estimators=350,max_depth=2,learning_rate=0.01,\n min_samples_split=5,min_samples_leaf=1) \n clf_gbm.fit(X_train,y_train_reshape)\n pred_gbm = clf_gbm.predict(X_test)\n\n\n importances = clf_gbm.feature_importances_\n g = sns.barplot(x=list(X_train), y=importances)\n\n for item in g.get_xticklabels():\n item.set_rotation(90)\n plt.show()\n print(accuracy_score(y_test,pred_gbm))\n\n\n\n\n \n\n file = open('./output/classifier_performance_new.dat','w')\n\n\n file.write( '\\n::::::gradient boosting::::::\\n')\n lam = [1,2,3,5,6,10,15,20,30,50,100]\n lam = [1,2,3,4,5]\n #random forest\n #n_estimators = 300 best, acc=.669,trace=353\n #default max_depth is best\n\n #gradient boosting\n #n_estimators = 300 best, acc=.652,trace=344\n #default max_depth is best\n for l in lam:\n clf_gbm = GradientBoostingClassifier(n_estimators=350,max_depth=l,learning_rate=0.1,\n min_samples_split=5,min_samples_leaf=1) \n clf_gbm.fit(X_train,y_train_reshape)\n pred_gbm = clf_gbm.predict(X_test)\n file.write( '\\n \\n::: with max_depth = %d :::::: \\n\\n' %l ) \n file.write('\\naccuracy = %f \\n' % accuracy_score(y_test,pred_gbm))\n file.write('confusion m. trace = %d \\n' % np.trace(confusion_matrix(y_test,pred_gbm) ) )\n file.write('cross val score = %f \\n' %\n np.average(cross_val_score(clf_gbm,X_train,y_train_reshape,cv=5, scoring='accuracy'))) \n\n\n \n file.write( '::::::logistic regression::::::\\n') \n lam = [0.001,0.01,0.1,1.,10.,100.,1000.]\n for l in lam:\n clf_logit = LogisticRegression(penalty='l2',C=l,solver='newton-cg')\n clf_logit.fit(X_train,y_train_reshape)\n pred_logit = clf_logit.predict(X_test)\n file.write( '\\n \\n::: with C = %f :::::: \\n\\n' %l ) \n file.write('\\naccuracy = %f \\n' % accuracy_score(y_test,pred_logit))\n mat = confusion_matrix(y_test,pred_logit) \n file.write('confusion m. trace = %d \\n' % np.trace(mat ) )\n file.write('cross val score = %f \\n' %\n np.average(cross_val_score(clf_logit,X_train,y_train_reshape,cv=5, scoring='accuracy')))\n\n\n \n file.write( '\\n::::::Decision Tree::::::\\n') \n lam = [2,5,8,10,15,30,50,70,100,150]\n for l in lam:\n clf_tree = DecisionTreeClassifier(max_depth=l)\n clf_tree.fit(X_train,y_train_reshape)\n pred_tree = clf_tree.predict(X_test)\n file.write( '\\n \\n::: with max_depth = %d :::::: \\n\\n' %l )\n file.write('\\naccuracy = %f \\n' % accuracy_score(y_test,pred_tree))\n file.write('confusion m. trace = %d \\n' % np.trace(confusion_matrix(y_test,pred_tree) ) )\n file.write('cross val score = %f \\n' %\n np.average(cross_val_score(clf_tree,X_train,y_train_reshape,cv=5, scoring='accuracy')))\n\n\n file.write( '\\n::::::random forest::::::\\n')\n lam = [2,5,8,10,15,30,50,70,100,150]\n #n_estimators = 300 best, acc=.669,trace=353\n #default max_depth is best\n for l in lam:\n clf_rf = RandomForestClassifier(n_estimators=300,max_depth=l) \n clf_rf.fit(X_train,y_train_reshape)\n pred_rf = clf_rf.predict(X_test)\n file.write( '\\n \\n::: with max_depth = %d :::::: \\n\\n' %l ) \n file.write('\\naccuracy = %f \\n' % accuracy_score(y_test,pred_rf))\n file.write('confusion m. trace = %d \\n' % np.trace(confusion_matrix(y_test,pred_rf) ) )\n file.write('cross val score = %f \\n' %\n np.average(cross_val_score(clf_rf,X_train,y_train_reshape,cv=5, scoring='accuracy'))) \n\n file.write( '\\n::::::Adaboost::::::\\n')\n lam = [1,2,4,10,50,100] \n for l in lam:\n clf_ada = AdaBoostClassifier(n_estimators=l)\n clf_ada.fit(X_train,y_train_reshape)\n pred_ada = clf_ada.predict(X_test)\n\n \n file.write( '\\n \\n::: with n_estimators = %d :::::: \\n\\n' %l )\n file.write('\\naccuracy = %f \\n' % accuracy_score(y_test,pred_ada))\n file.write('confusion m. trace = %d \\n' % np.trace(confusion_matrix(y_test,pred_ada) ) )\n file.write('cross val score = %f \\n' %\n np.average(cross_val_score(clf_ada,X_train,y_train_reshape,cv=5, scoring='accuracy'))) \n \n\n file.write( '\\n::::::gradient boosting::::::\\n')\n lam = [1,2,3,5,6,10,15,20,30,50,100]\n #random forest\n #n_estimators = 300 best, acc=.669,trace=353\n #default max_depth is best\n\n #gradient boosting\n #n_estimators = 300 best, acc=.652,trace=344\n #default max_depth is best\n for l in lam:\n clf_gbm = GradientBoostingClassifier(n_estimators=300,max_depth=l) \n clf_gbm.fit(X_train,y_train_reshape)\n pred_gbm = clf_gbm.predict(X_test)\n file.write( '\\n \\n::: with max_depth = %d :::::: \\n\\n' %l ) \n file.write('\\naccuracy = %f \\n' % accuracy_score(y_test,pred_gbm))\n file.write('confusion m. trace = %d \\n' % np.trace(confusion_matrix(y_test,pred_gbm) ) )\n file.write('cross val score = %f \\n' %\n np.average(cross_val_score(clf_gbm,X_train,y_train_reshape,cv=5, scoring='accuracy'))) \n\n\n file.write( '\\n::::::Linear SVM::::::\\n')\n lam = [0.001,0.01,0.02,0.04,0.06,0.08,0.10,1.0,5.0] \n for l in lam:\n clf_lsvm = LinearSVC(C=l)\n clf_lsvm.fit(X_train,y_train_reshape)\n pred_lsvm = clf_lsvm.predict(X_test)\n file.write( '\\n \\n::: with C = %f :::::: \\n\\n' %l )\n file.write('\\naccuracy = %f \\n' % accuracy_score(y_test,pred_lsvm))\n file.write('confusion m. trace = %d \\n' % np.trace(confusion_matrix(y_test,pred_lsvm) ) )\n file.write('cross val score = %f \\n' %\n np.average(cross_val_score(clf_lsvm,X_train,y_train_reshape,cv=5, scoring='accuracy'))) \n\n file.write( '\\n::::::SVM rbf::::::\\n')\n lam = [0.001,0.01,0.02,0.04,0.06,0.08,0.10,1.0,5.0] \n for l in lam:\n clf_kernel_svm = SVC(kernel='rbf',C=l)\n clf_kernel_svm.fit(X_train,y_train_reshape)\n pred_kernel_svm = clf_kernel_svm.predict(X_test) \n file.write( '\\n \\n::: with C = %f :::::: \\n\\n' %l )\n file.write('\\naccuracy = %f \\n' % accuracy_score(y_test,pred_kernel_svm))\n file.write('confusion m. trace = %d \\n' % np.trace(confusion_matrix(y_test,pred_kernel_svm) ) )\n file.write('cross val score = %f \\n' %\n np.average(cross_val_score(clf_kernel_svm,X_train,y_train_reshape,cv=5, scoring='accuracy')))\n \n" } ]
2
ChanJeunlam/eddy_wave
https://github.com/ChanJeunlam/eddy_wave
ba42783dc02913cda714360210e9e7f8bcb006d5
52bde5d39413b327047e339100087714ea7accc1
16df991697a8dc7d3a26a38593feb1ee0bfcaf6f
refs/heads/master
2022-04-11T10:42:34.833348
2020-03-24T13:11:21
2020-03-24T13:11:21
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.738170325756073, "alphanum_fraction": 0.7602523565292358, "avg_line_length": 27.81818199157715, "blob_id": "c10e40111f9214a1081691c9a97ed05b89a11cd0", "content_id": "cd03ceac542e29f049a001f27c79bd32e0299da1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 317, "license_type": "no_license", "max_line_length": 75, "num_lines": 11, "path": "/runs/res_3000m/wind/data.rbcs", "repo_name": "ChanJeunlam/eddy_wave", "src_encoding": "UTF-8", "text": "#!sh RBCS package parameters:\n&RBCS_PARM01\n tauRelaxT=600.,\n relaxMaskFile='/Users/takachanbo/MITgcm/eddy_airsea/input/tmask.box',\n useRBCtemp=.TRUE.,\n relaxTFile='/Users/takachanbo/MITgcm/eddy_airsea/input/trelax.box',\n &\n\n# RBCS for pTracers (read this namelist only when ptracers pkg is compiled)\n &RBCS_PARM02\n &\n" }, { "alpha_fraction": 0.6881287693977356, "alphanum_fraction": 0.7062374353408813, "avg_line_length": 23.850000381469727, "blob_id": "bda6c0a48aed66feb3ba80076e6d0ed5f1ffaab3", "content_id": "5313e14353d49585ca825caecb2796e805d71133", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 497, "license_type": "no_license", "max_line_length": 89, "num_lines": 20, "path": "/make_script.zsh", "repo_name": "ChanJeunlam/eddy_wave", "src_encoding": "UTF-8", "text": "#!/bin/zsh\n#\n# emulate sh\nemulate -R sh\n# run the following to activate a node\n# $sinfo | less\n# and choose a node with either 'idle' or 'mixed' classification under the column \"STATE\"\n# $srun --pty -t 0-03:00 -A ocp -w node<node number> /bin/bash\n\n\nROOT='/Users/takachanbo/MITgcm/'\nGENMAKE=$ROOT'tools/genmake2'\nMOD=$ROOT'eddy_airsea/code'\nOPTFILE=${ROOT}'eddy_airsea/code/linux_amd64_gfortran+mpi_generic'\n\ncd build\n${GENMAKE} -rootdir=${ROOT} -mods=${MOD} -of=${OPTFILE}\n\nmake depend\nmake -j 2\n" }, { "alpha_fraction": 0.4894736707210541, "alphanum_fraction": 0.5768421292304993, "avg_line_length": 22.170732498168945, "blob_id": "256d723ea1561d520b6b4313d0c7a2bb2008d689", "content_id": "ebccc45b70bf1da43ff349560244c76473dbd72d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 950, "license_type": "no_license", "max_line_length": 133, "num_lines": 41, "path": "/analysis/ode_wave.py", "repo_name": "ChanJeunlam/eddy_wave", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate as integrate\n\nplt.ion()\n\nf0 = 1e-4\nu0 = 0.5\nR0 = 40e3 # radius\nvmax = 0.5 # m/s\n\n\n\ndef v1(rr):\n v = -vmax*rr/R0*np.exp(-0.5*(rr/R0)**2)\n# v = -vmax*np.tanh(rr/R0)/(np.cosh(rr/R0))**2/(np.tanh(1.0)/(np.cosh(1.0))**2)\n return v\ndef dv1(rr):\n v = -vmax/R0*np.exp(-0.5*(rr/R0)**2)*(1-(rr/R0)**2)\n# v = -vmax*2/R0*np.tanh(rr/R0)/((np.cosh(rr/R0))**2)*(1/(np.cosh(rr/R0))**2 - (np.tanh(rr/R0))**2)/(np.tanh(1.0)/(np.cosh(1.0))**2)\n return v\n\n\ndef f(r, t):\n omega = np.sqrt((dv1(r)+v1(r)/r + f0)*(2*v1(r)/r + f0))\n return u0*np.sin(omega*t)\n\nsi_r = 30\nsi_t = 100000\nr0 = np.linspace(1,5*R0,si_r)\nt = np.linspace(0, si_t/f0/1000, si_t)\nra = np.zeros((si_t,si_r))\nfor ni in range(0,si_r):\n ra[:,ni] = integrate.odeint(f, r0[ni], t).squeeze()\n\nplt.figure()\nplt.plot(t*f0/(2*np.pi),ra/R0,'k',linewidth=1)\nplt.xlabel('t*f/2pi')\nplt.ylabel('r/R0')\n" }, { "alpha_fraction": 0.7922705411911011, "alphanum_fraction": 0.7922705411911011, "avg_line_length": 40.400001525878906, "blob_id": "ad698f66d69ba432a3f38c483a0b0ea9af036d14", "content_id": "b7f94eb0b6697617f3564dd505759354bcce4d42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 207, "license_type": "no_license", "max_line_length": 99, "num_lines": 5, "path": "/README.md", "repo_name": "ChanJeunlam/eddy_wave", "src_encoding": "UTF-8", "text": "# Eddy-inertial wave interaction induced by surface wind forcing\n\n![Baroclinic eddy](input/surf_eddy.png)\n\nConfiguration files for running the simulation in [MITgcm](https://github.com/bderembl/MITgcm.git).\n" }, { "alpha_fraction": 0.3820224702358246, "alphanum_fraction": 0.516853928565979, "avg_line_length": 12.692307472229004, "blob_id": "7657a8a5e99261812746d3722c9a53742c0fd26b", "content_id": "4b56c6aa53ecc303bb1769869795b32381a03e14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 178, "license_type": "no_license", "max_line_length": 40, "num_lines": 13, "path": "/runs/res_3000m/wind/remove001s.zsh", "repo_name": "ChanJeunlam/eddy_wave", "src_encoding": "UTF-8", "text": "#!/bin/zsh\n#\n#\nfor f in *.001.001.data\ndo\n# print \"$f\"\n mv -- \"$f\" \"${f%.001.001.data}.data\"\ndone\n\nfor f in *.001.001.meta\ndo\n mv -- \"$f\" \"${f%.001.001.meta}.meta\"\ndone\n" } ]
5
florije1988/manman
https://github.com/florije1988/manman
48275f587591feeaf4185a5576fd982b6d53f5d4
b5b4447f153c2d21ca5f57713fa58b38c132f9c9
48872c163fd003a93f6060de39b1bb458a80e49b
refs/heads/master
2016-08-11T05:24:32.083862
2016-02-17T02:21:59
2016-02-17T02:21:59
43,860,512
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5142857432365417, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 27, "blob_id": "7f686b7bcdde2141538f4269ce1ae318692afc39", "content_id": "5d642fa8d380b83663ce280aa70e5b872f1f731f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 140, "license_type": "no_license", "max_line_length": 50, "num_lines": 5, "path": "/global/simple_loop2.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\nprint('I will display the od number 1 through 9.')\nfor num in [1, 3, 5, 7, 9]:\n print(num)\n" }, { "alpha_fraction": 0.636904776096344, "alphanum_fraction": 0.6696428656578064, "avg_line_length": 32.599998474121094, "blob_id": "1808f8bf6a7096f1f753b6ef41f044e4190b72b5", "content_id": "0041b09934099935ff36ba658bd126e7be3a8abf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 336, "license_type": "no_license", "max_line_length": 59, "num_lines": 10, "path": "/global/time_converter.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\ntotal_seconds = float(input('Enter a number of seconds: '))\nhours = total_seconds // 3600\nminutes = (total_seconds // 60) % 60\nseconds = total_seconds % 60\nprint('Here is the time in hours,minutes, and seconds:')\nprint('Hours:', hours)\nprint('minutes:', minutes)\nprint('seconds:', seconds)\n" }, { "alpha_fraction": 0.5262866616249084, "alphanum_fraction": 0.5766463875770569, "avg_line_length": 25.970149993896484, "blob_id": "428e04ae4339f713d174006d940f5bded5b162a6", "content_id": "603929608f06af77c01cda3d2ca913235d2c3a62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2163, "license_type": "no_license", "max_line_length": 67, "num_lines": 67, "path": "/other/aes_demo.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom Crypto.Cipher import AES\nfrom Crypto import Random\nfrom binascii import b2a_hex, a2b_hex\n\n__author__ = 'florije'\n\n\nclass prpcrypt():\n def __init__(self, key):\n self.key = key\n self.mode = AES.MODE_CBC\n\n # 加密函数,如果text不足16位就用空格补足为16位,\n # 如果大于16当时不是16的倍数,那就补足为16的倍数。\n def encrypt(self, text):\n cryptor = AES.new(self.key, self.mode, b'0000000000000000')\n # 这里密钥key 长度必须为16(AES-128),\n # 24(AES-192),或者32 (AES-256)Bytes 长度\n # 目前AES-128 足够目前使用\n length = 16\n count = len(text)\n if count < length:\n add = (length - count)\n # \\0 backspace\n text = text + ('\\0' * add)\n elif count > length:\n add = (length - (count % length))\n text = text + ('\\0' * add)\n self.ciphertext = cryptor.encrypt(text)\n # 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题\n # 所以这里统一把加密后的字符串转化为16进制字符串\n return b2a_hex(self.ciphertext)\n\n # 解密后,去掉补足的空格用strip() 去掉\n def decrypt(self, text):\n cryptor = AES.new(self.key, self.mode, b'0000000000000000')\n plain_text = cryptor.decrypt(a2b_hex(text))\n return plain_text.rstrip('\\0')\n\n\nif __name__ == '__main__':\n # pc = prpcrypt('keyskeyskeyskeys')\n # import sys\n #\n # e = pc.encrypt(sys.argv[1])\n # d = pc.decrypt(e)\n # print \"加密:\", e\n # print \"解密:\", d\n\n key = '0123456789abcdef'\n mode = AES.MODE_CBC\n iv = Random.new().read(AES.block_size)\n encryptor = AES.new(key, mode, iv)\n text = 'j' * 64\n ciphertext = encryptor.encrypt(text)\n print ciphertext\n\n \"\"\"\n 上例中的key是16位, 还可以是24 或 32 位长度, 其对应为 AES-128, AES-196 和 AES-256.\n 解密则可以用以下代码进行:\n \"\"\"\n\n decryptor = AES.new(key, mode, iv)\n plain = decryptor.decrypt(ciphertext)\n print plain\n" }, { "alpha_fraction": 0.4347181022167206, "alphanum_fraction": 0.44510385394096375, "avg_line_length": 19.42424201965332, "blob_id": "22e6a66e246f0b0417817be840aaf2f240ffa04a", "content_id": "647d431b0446bc566ced30d56d59b24315aa0c0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 760, "license_type": "no_license", "max_line_length": 65, "num_lines": 33, "path": "/21days/5_5.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n'''\n\n'''\n\ndata = [1, 2, 3, 4]\n\n# for i in data:\n# for j in data:\n# print('{a}{b}'.format(a=i, b=j), end=' ')\n# 上下两种表达一样,都是生成两位数。\n# for i in data:\n# for j in data:\n# print('%s%s' % (i, j), end=' ')\n\n\n# 下面生成任意组合三位数。\n# for i in data:\n# for j in data:\n# for k in data:\n# print('{a}{b}{c}'.format(a=i, b=j, c=k), end=' ')\n\n# 下面生成无重复数字的三位数。\ncount = 0\nfor i in data:\n for j in data:\n for k in data:\n if i != j and j != k and i != k:\n count += 1\n print('{a}{b}{c}'.format(a=i, b=j, c=k), end=' ')\nprint('\\n{count}'.format(count=count))\n" }, { "alpha_fraction": 0.34306567907333374, "alphanum_fraction": 0.4136252999305725, "avg_line_length": 21.77777862548828, "blob_id": "c1714427480219d2fa7e8f762b445300e3fec16d", "content_id": "675708d810ad039dc7b90e319d40318845bf1ab0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 495, "license_type": "no_license", "max_line_length": 40, "num_lines": 18, "path": "/learn/004.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n\"\"\"\n输出所有的水仙花数,把谓水仙花数是指一个数3位数,其各各位数字立方和等于其本身,\n例如: 153 = 1*1*1 + 3*3*3 + 5*5*5\n\"\"\"\ndef get_flower():\n for i in range(1, 10):\n for j in range(10):\n for k in range(10):\n s = 100*i + 10*j + k\n h = i**3 + j**3 + k**3\n if s == h:\n print(s)\n\nif __name__ == '__main__':\n get_flower()\n\n" }, { "alpha_fraction": 0.6111111044883728, "alphanum_fraction": 0.6166666746139526, "avg_line_length": 16.700000762939453, "blob_id": "66134975e58c05cee5796489080d95f5c66695bd", "content_id": "7966074b2dc7a4e7871b8419fcf0828b95c87c2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 180, "license_type": "no_license", "max_line_length": 45, "num_lines": 10, "path": "/byte/chapter_9_1.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8-*-\n__author__ = 'manman'\n\nimport sys\n\nprint('The command line arguments are:')\nfor i in sys.argv:\n print i\n\nprint '\\n\\nThe PRTHONPATH is', sys.path, '\\n'\n\n\n\n" }, { "alpha_fraction": 0.5818696618080139, "alphanum_fraction": 0.6594901084899902, "avg_line_length": 36.553192138671875, "blob_id": "b200cc638bdea52aef57d668f81d19036ed3f18d", "content_id": "dc2ba23b7b63bb85f996c6e154b06aa2d558e727", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1765, "license_type": "no_license", "max_line_length": 122, "num_lines": 47, "path": "/other/python_java/java_sign.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport jpype\n\n__author__ = 'florije'\n\nlib_base_path = r'E:\\fuboqing\\files\\company\\po_upnp\\libs'\njar_list = ['commons-codec-1.10.jar', 'log4j-1.2.17.jar', 'chinapaysecure.jar', 'bcprov-jdk15on-154.jar']\nclass_path = ';'.join(['%s\\%s' % (lib_base_path, jar) for jar in jar_list])\n\njpype.startJVM(jpype.getDefaultJVMPath(), \"-ea\", \"-Djava.class.path=%s\" % class_path)\n\nsecssUtil = jpype.JClass('com.chinapay.secss.PythonDelegate')()\nprop = jpype.JClass('java.util.Properties')()\n# jpype.java.lang.System.out.println(\"hello world\")\n\nconfigs_dict = {'sign.file.password': 'abcd1234', 'sign.cert.type': 'PKCS12', 'sign.invalid.fields': 'Signature,CertId',\n 'verify.file': 'E:\\\\fuboqing\\\\files\\\\company\\\\po_upnp\\\\pfx\\\\000001509184450.cer',\n 'sign.file': 'E:\\\\fuboqing\\\\files\\\\company\\\\po_upnp\\\\pfx\\\\000001509184450.pfx', 'log4j.name': 'cpLog',\n 'signature.field': 'Signature'}\n\nfor key, value in configs_dict.iteritems():\n prop.setProperty(key, value)\n\ntry:\n secssUtil.PyInit(prop)\n if secssUtil.getErrCode() != '00':\n print(secssUtil.getErrMsg())\nexcept jpype.JavaException as e:\n raise e\n\ndata = {'Version': '20140728', 'OrderAmt': str(1L), 'TranDate': '20160114', 'BusiType': '0001',\n 'MerBgUrl': 'http://182.48.115.36:8443/upnp/payNotify', 'MerPageUrl': 'http://182.48.115.35:20060/pay-success',\n 'MerOrderNo': '2016844500000009', 'TranTime': '170733', 'CurryNo': 'CNY', 'MerId': '000001509184450'}\ndata_map = jpype.JClass(\"java.util.HashMap\")()\nfor key, value in data.iteritems():\n data_map.put(key, value)\n\ntry:\n secssUtil.PySign(data_map)\nexcept jpype.JavaException as e:\n print(e.message())\n\nres = secssUtil.getSign()\nprint res\n\njpype.shutdownJVM()\n" }, { "alpha_fraction": 0.5222222208976746, "alphanum_fraction": 0.5444444417953491, "avg_line_length": 21.5, "blob_id": "161194eea9865b9618e783cd4263c74a52194fe4", "content_id": "bd450573a7d21f62f34cdf5c2280bde08a1fc264", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 90, "license_type": "no_license", "max_line_length": 24, "num_lines": 4, "path": "/global/simple_loop4.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\nfor x in range(5):\n print('Hello world')\n" }, { "alpha_fraction": 0.5563380122184753, "alphanum_fraction": 0.6173709034919739, "avg_line_length": 25.5625, "blob_id": "734ab32d64b8d15dfad949150b518db7cbe16f24", "content_id": "53028528e6289b2c1658563f37246143214a3228", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 426, "license_type": "no_license", "max_line_length": 109, "num_lines": 16, "path": "/other/requests_demo.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport requests\n\n\n__author__ = 'florije'\n\nres = requests.get('http://www.weather.com.cn/data/list3/city.xml', params={'level': 1}, headers={\n 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6',\n 'Content-Type': 'text/xml',\n 'Host': 'www.weather.com.cn',\n})\nif res.status_code == 200:\n print res.content.decode('utf-8')\nelse:\n pass\n\n" }, { "alpha_fraction": 0.4897260367870331, "alphanum_fraction": 0.4931506812572479, "avg_line_length": 15.222222328186035, "blob_id": "70621ef31dfad2e747c8718a0d68bfd7f550543e", "content_id": "094edcd866b195b9ce87d1f8eddde6988dc3f07b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 292, "license_type": "no_license", "max_line_length": 40, "num_lines": 18, "path": "/other/chap1key6.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n\nclass Meta(type):\n def __call__(*args):\n print(\"meta call\", *args)\n return None\n\n\nclass C(metaclass=Meta):\n def __init__(*args):\n print(\"C init not called\", args)\n\n\nif __name__ == '__main__':\n c = C()\n print(c)\n" }, { "alpha_fraction": 0.5436070561408997, "alphanum_fraction": 0.5537227988243103, "avg_line_length": 29.90985870361328, "blob_id": "8b5a7087a8ef01fc91cad98b12fc383c516450c2", "content_id": "1c17b1cc8829b06e2a2ca230749b79b4155c96c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11139, "license_type": "no_license", "max_line_length": 119, "num_lines": 355, "path": "/other/weather_data.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport time\nimport random\nimport requests\nfrom flask import Flask, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_script import Manager, Shell, Server\nfrom flask_migrate import Migrate, MigrateCommand\n\n__author__ = 'florije'\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///weather.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\ndb = SQLAlchemy(app)\n\nmanager = Manager(app)\nmanager.add_command(\"runserver\", Server())\n\nmigrate = Migrate(app, db)\n\n\ndef make_shell_context():\n # return dict(app=app, db=db, TaskModel=TodoModel)\n return dict(app=app)\n\n\nmanager.add_command(\"shell\", Shell(make_context=make_shell_context))\nmanager.add_command('db', MigrateCommand)\n\nMUNICIPALITIES = [u'北京', u'上海', u'天津', u'重庆']\n\n\ndef request_data(url):\n \"\"\"\n 获取url地址的数据\n :param url:\n :return:\n \"\"\"\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6',\n 'Content-Type': 'text/xml',\n 'Host': 'www.weather.com.cn',\n }\n res = requests.get(url, headers=headers)\n\n if res.status_code == 200:\n return res.content.decode('utf-8')\n else:\n raise Exception(res.status_code, res.reason)\n\n\nclass BaseModel(db.Model):\n \"\"\"\n Model基类\n \"\"\"\n __abstract__ = True\n\n id = db.Column(db.Integer, primary_key=True)\n create_time = db.Column(db.DateTime(), default=db.func.datetime('now', 'localtime')) # db.func.now()\n update_time = db.Column(db.DateTime(), default=db.func.datetime('now', 'localtime'),\n onupdate=db.func.datetime('now', 'localtime'))\n\n\nclass ModelMixin(object):\n \"\"\"\n Model拓展类\n \"\"\"\n def __repr__(self):\n return unicode(self.__dict__)\n\n\nclass ProvinceModel(BaseModel, ModelMixin):\n \"\"\"\n Province Model\n \"\"\"\n __tablename__ = 'province'\n\n uid = db.Column(db.String(6), unique=False, nullable=False)\n province = db.Column(db.String(20), unique=False, nullable=False)\n\n def __init__(self, uid, province):\n self.uid = uid\n self.province = province\n\n # def __repr__(self):\n # return '<Weather %r>' % self.province\n\n\nclass CityModel(BaseModel, ModelMixin):\n \"\"\"\n City Model\n \"\"\"\n __tablename__ = 'city'\n\n uid = db.Column(db.String(6), unique=False, nullable=False)\n province_uid = db.Column(db.String(6), unique=False, nullable=False)\n city = db.Column(db.String(20), unique=False, nullable=False)\n\n def __init__(self, uid, province_uid, city):\n self.uid = uid\n self.province_uid = province_uid\n self.city = city\n\n # def __repr__(self):\n # return '<City %r>' % self.city\n\n\nclass DistrictModel(BaseModel, ModelMixin):\n \"\"\"\n District Model\n \"\"\"\n __tablename__ = 'district'\n\n uid = db.Column(db.String(6), unique=False, nullable=False)\n code = db.Column(db.String(20), unique=False, nullable=True)\n province_uid = db.Column(db.String(6), unique=False, nullable=False)\n city_uid = db.Column(db.String(6), unique=False, nullable=False)\n district = db.Column(db.String(20), unique=False, nullable=False)\n\n def __init__(self, uid, province_uid, city_uid, district):\n self.uid = uid\n self.province_uid = province_uid\n self.city_uid = city_uid\n self.district = district\n\n # def __repr__(self):\n # return '<District %r>' % self.district\n\n\ndef sleep(start, end):\n \"\"\"\n 睡眠时间\n :param start: 开始数字\n :param end: 停止数字\n :return:\n \"\"\"\n time.sleep(random.randint(start, end))\n\n\[email protected]\ndef create_db():\n \"\"\"\n 创建数据库,暂未使用migrate\n :return:\n \"\"\"\n db.create_all()\n print \"db ok.\"\n\n\[email protected]\ndef get_province():\n \"\"\"\n 获取省份\n :return:\n \"\"\"\n success = False\n try:\n res = request_data('http://www.weather.com.cn/data/list3/city.xml?level=1')\n province_list = []\n for item in res.split(','):\n split_item = item.split('|')\n if split_item:\n province = ProvinceModel(uid=split_item[0], province=split_item[1])\n province_list.append(province)\n if province_list:\n db.session.add_all(province_list)\n db.session.commit()\n success = True\n except Exception as e:\n print e.args, e.message\n time.sleep(random.randint(2, 5))\n while not success:\n try:\n res = request_data('http://www.weather.com.cn/data/list3/city.xml?level=1')\n province_list = []\n for item in res.split(','):\n split_item = item.split('|')\n if split_item:\n province = ProvinceModel(uid=split_item[0], province=split_item[1])\n province_list.append(province)\n if province_list:\n db.session.add_all(province_list)\n db.session.commit()\n success = True\n except Exception as e:\n print e.args, e.message\n time.sleep(random.randint(2, 5))\n\n print 'get province data ok.'\n\n\[email protected]\ndef get_city():\n \"\"\"\n 获取城市\n :return:\n \"\"\"\n province_list = ProvinceModel.query.all()\n to_deal_provinces = []\n for province in province_list:\n sleep(1, 4)\n print \"in origin province %s\" % province.province\n try:\n res = request_data('http://www.weather.com.cn/data/list3/city{code}.xml?level=2'.format(code=province.uid))\n city_list = []\n for item in res.split(','):\n split_item = item.split('|')\n city = CityModel(uid=split_item[0], city=split_item[1], province_uid=province.uid)\n city_list.append(city)\n if city_list:\n db.session.add_all(city_list)\n db.session.commit()\n except Exception as e:\n print e.args, e.message\n to_deal_provinces.append(province)\n sleep(3, 7)\n while to_deal_provinces:\n for province in to_deal_provinces[:]:\n print \"in to deal province %s\" % province.province\n sleep(1, 4)\n try:\n res = request_data(\n 'http://www.weather.com.cn/data/list3/city{code}.xml?level=2'.format(code=province.uid))\n city_list = []\n for item in res.split(','):\n split_item = item.split('|')\n city = CityModel(uid=split_item[0], city=split_item[1], province_uid=province.uid)\n city_list.append(city)\n if city_list:\n db.session.add_all(city_list)\n db.session.commit()\n to_deal_provinces.remove(province)\n except Exception as e:\n print e.args, e.message\n sleep(3, 7)\n\n print 'get city data ok.'\n\n\[email protected]\ndef get_district():\n \"\"\"\n 获取城区\n :return:\n \"\"\"\n city_list = CityModel.query.all()\n to_deal_cities = []\n for city in city_list:\n sleep(1, 4)\n print \"in origin city %s\" % city.city\n try:\n res = request_data('http://www.weather.com.cn/data/list3/city{code}.xml?level=3'.format(code=city.uid))\n district_list = []\n for item in res.split(','):\n split_item = item.split('|')\n district = DistrictModel(uid=split_item[0], district=split_item[1], province_uid=city.province_uid,\n city_uid=city.uid)\n district_list.append(district)\n if district_list:\n db.session.add_all(district_list)\n db.session.commit()\n except Exception as e:\n print e.args, e.message\n to_deal_cities.append(city)\n sleep(3, 7)\n while to_deal_cities:\n for city in to_deal_cities[:]:\n print \"in to deal city %s\" % city.city\n sleep(1, 4)\n try:\n res = request_data('http://www.weather.com.cn/data/list3/city{code}.xml?level=3'.format(code=city.uid))\n\n district_list = []\n for item in res.split(','):\n split_item = item.split('|')\n district = DistrictModel(uid=split_item[0], district=split_item[1], province_uid=city.province_uid,\n city_uid=city.uid)\n district_list.append(district)\n if district_list:\n db.session.add_all(district_list)\n db.session.commit()\n to_deal_cities.remove(city)\n except Exception as e:\n print e.args, e.message\n sleep(3, 7)\n print 'get district data ok.'\n\n\[email protected]\ndef get_weather_code():\n \"\"\"\n 获取天气编码\n :return:\n \"\"\"\n district_list = DistrictModel.query.all()\n to_deal_districts = []\n for district in district_list:\n municipality_codes = [city.uid for city in CityModel.query.filter(CityModel.city.in_(MUNICIPALITIES)).all()]\n if district.city_uid in municipality_codes:\n sleep(1, 4)\n print \"in origin municipality district %s\" % district.district\n try:\n res = request_data(\n 'http://www.weather.com.cn/data/list3/city{code}.xml?level=4'.format(code=district.uid))\n district.code = res.split('|')[1] # if res.split('|') and len(res.split('|')) >= 2 else res\n db.session.commit()\n except Exception as e:\n to_deal_districts.append(district)\n print e.args, e.message\n sleep(3, 7)\n else:\n # 直辖市的比较复杂直接获取,其他省市直接拼接.\n print \"in origin common district %s\" % district.district\n district.code = '101{code}'.format(code=district.uid)\n db.session.commit()\n while to_deal_districts:\n for district in to_deal_districts[:]:\n print \"in to deal district %s\" % district.district\n sleep(1, 4)\n try:\n res = request_data(\n 'http://www.weather.com.cn/data/list3/city{code}.xml?level=4'.format(code=district.uid))\n district.code = res.split('|')[1] # if res.split('|') and len(res.split('|')) >= 2 else res\n to_deal_districts.remove(district)\n db.session.commit()\n except Exception as e:\n print e.args, e.message\n sleep(3, 7)\n\n\[email protected]\ndef get_weather():\n \"\"\"\n 获取天气\n :return:\n \"\"\"\n code = request.args.get('code', '')\n res = request_data('http://weather.com.cn/adat/cityinfo/{code}.html'.format(code=code))\n return res\n\n\[email protected](\"/\")\ndef hello():\n \"\"\"\n index\n :return:\n \"\"\"\n return \"Hello, World!\"\n\n\nif __name__ == '__main__':\n # app.run(debug=True, host='127.0.0.1', port=8020)\n manager.run()\n" }, { "alpha_fraction": 0.565625011920929, "alphanum_fraction": 0.581250011920929, "avg_line_length": 25.66666603088379, "blob_id": "acd99faa60be0607d3a829b750e8c36cc341c6f4", "content_id": "86d963d01651ae4bd53a1d37c8281a0e9cf74f35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 320, "license_type": "no_license", "max_line_length": 93, "num_lines": 12, "path": "/other/lxml_demo.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom lxml import etree\n\n__author__ = 'florije'\n\ntree = etree.parse('citylist.xml')\nroot = tree.getroot()\nfor subroot in root:\n for field in subroot:\n print 'number:', field.get('d1'), 'name_cn:', field.get('d2'), 'name_en:', field.get(\n 'd3'), 'prov_name:', field.get('d4')\n" }, { "alpha_fraction": 0.4972067177295685, "alphanum_fraction": 0.5474860072135925, "avg_line_length": 24.571428298950195, "blob_id": "2dd43921da9d1c59b44f9ace87edeebca90334a5", "content_id": "3d14d94ec8b0aba1eda93d7779251343c7139cd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 179, "license_type": "no_license", "max_line_length": 35, "num_lines": 7, "path": "/global/dollar_display.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\nmonthly_pay = 5000.0\nannual_pay = monthly_pay * 12\nprint('Your annual pay is $', \\\n format(annual_pay, ',.2f'), \\\n sep='')\n" }, { "alpha_fraction": 0.4797297418117523, "alphanum_fraction": 0.5219594836235046, "avg_line_length": 14.15384578704834, "blob_id": "3ec3f8ce7c3dc72534ed8bce64b61ab0b2904f63", "content_id": "862f312707bfc68f7da8bf66be7294c01c8cd76c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 852, "license_type": "no_license", "max_line_length": 28, "num_lines": 39, "path": "/21days/4_3.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n'''\n总科目状态:1,未通过,2,补考,3,通过\n1.输入两门成绩\n2.第一门成绩大于60分即通过,不及格则未通过\n3.第一门成绩及格而第二门成绩不及格,则显示‘补考’。\n'''\n'''\nx = int(input('输入第一门课程成绩:'))\ny = int(input('输入第二门课程成绩:'))\n\nstatus = 0 # 总科目状态,0定义为未知。\n\nif x >= 60:\n if y < 60:\n status = 2\n else:\n status = 3\nelse:\n status = 1\n\nif status == 1:\n print('未通过')\nelif status == 2:\n print('补考')\nelif status == 3:\n print('通过')\n'''\n\nx = int(input('输入第一门课程成绩:'))\ny = int(input('输入第二门课程成绩:'))\nif x >= 60:\n if y >= 60:\n print('通过')\n else:\n print('补考')\nelse:\n print('未通过')\n\n" }, { "alpha_fraction": 0.42574256658554077, "alphanum_fraction": 0.6204620599746704, "avg_line_length": 19.200000762939453, "blob_id": "246366523ca95d7c48faf8280d4cb9ee47fe1fe2", "content_id": "9ab1e48b805a54dd06049a8c04b9daa9370bf72a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 303, "license_type": "no_license", "max_line_length": 27, "num_lines": 15, "path": "/global/columns.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\nnum1 = 127.899\nnum2 = 3465.148\nnum3 = 3.776\nnum4 = 264.821\nnum5 = 88.081\nnum6 = 799.999\n\nprint(format(num1, '7.2f'))\nprint(format(num2, '7.2f'))\nprint(format(num3, '7.2f'))\nprint(format(num4, '7.2f'))\nprint(format(num5, '7.2f'))\nprint(format(num6, '7.2f'))\n" }, { "alpha_fraction": 0.562841534614563, "alphanum_fraction": 0.6120218634605408, "avg_line_length": 25.14285659790039, "blob_id": "6f75a8a32634684c2f08ab87a42cf61082204608", "content_id": "685c416d8cb3d5488b7ed18085c698325135c403", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 193, "license_type": "no_license", "max_line_length": 37, "num_lines": 7, "path": "/global/formatting.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\namount_due = 5000.0\nmonthly_payment = amount_due / 12\n # \\可加可不加\nprint('The monthly payment is ' +\\\n format(monthly_payment, '.2f'))\n" }, { "alpha_fraction": 0.6458333134651184, "alphanum_fraction": 0.7121211886405945, "avg_line_length": 26.789474487304688, "blob_id": "5ab0c5a1091bab1f7bba18947f8780504720502c", "content_id": "5485e74010345eb326af56ab6eb258a36c696b94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 528, "license_type": "no_license", "max_line_length": 64, "num_lines": 19, "path": "/other/aes_js_py/aes.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\nfrom crypto_py import Cryptor\nimport binascii\n\niv, encrypted = Cryptor.encrypt('fuboqing', Cryptor.KEY)\n\nprint \"iv : %s\" % iv\n# => iv 6aa60df8ff95955ec605d5689036ee88\nprint \"encrypted : %s\" % binascii.b2a_base64(encrypted).rstrip()\n# => encrypted r19YcF8gc8bgk5NNui6I3w==\n\n# encrypted_str = \"U2FsdGVkX18Qr0xuqggzVgHwDkxBHLLJiPLppAFoAjQsybTv9jj96gSK4CIQyZb3Ead1k3yMSRx0UOH11hyzbvksA2au/JSoo9rd79Dd/a/bpxMXPh4ot3gd6kSgWaPMbr6LxsD0lhUdKF+qR9u+e3hvmSrGRBKuhCNUJUm+419pdt4DMyRw4eJ0TFEhPDzj9GHYJCDXvI58ORA3uOIHJU5ITMfzse2zYCC9is46OlAuli+FKuQ9g966xNjhQb4rakllujU547VdXTOeZAIVtcZXY7XTBtJDGt72+JPNEMQeaC9pkfgyfbp6fcoYwlvOKT6iJspJE2nVclKA+yPnvDCaDVjJxf2lACVOeJGBx20Bd3YvbkYCTvFftmfTrz4rmBvOQw1/68+kFTT4cRsN3DQrLM29wsHL8sRynSzxNMnck4BQ6Ds0InW8z639Luh/+9kodyScbx69gXdtlFqrRZ2CZhei/eMKJDgZbG1BZMBOz5H9VQ45j8kZW5Wzog19FZWSg5ZD8KOt9i0PHCJHo8rM6geHj/UZ2Zv6S+PV/Y7mQa7ik4jBsotqifxGLA1uG8HKp+3XeJPllngsX/LHkMlT9FXDwvO8QPHWutO36O01QGzx70VbgWqgrlZLsMmgL6i7K+JGHXYgYV1b4Ex3iN7WlD4ma6KCeM8u9xDNA6BVjNhXa8v5waJsg4apMHQAD0AdZPkyCo2ju53pSM8hF1ZW/1cwUjVkK6NP0+2c4cDoMH0ZTx50CAEJtESZkT/UG3/AQrWOgGolJhqvO0sU4dIxb7OcHgpWMfMy1v9RYGoD9gYdY3yz2mSLlYUgtu7rmbcPpzSYdoWqYFR6lOf2ru66kD1luqZwsKtymkmJBjRWz3bjYw3Nf/BO4MIugz/9pny+DV/08yAa9R7zi29ZypgEpj99PRoDW1AOMU3LhxbAHmP9Alw7/knaClt2wovbvpNLGDlUqO5da43fFoy9P063JfPkKFh2RjN1EUOXYEOf+wskwcPyRSCMGbCK6CoFAT4MgpY90XoO1Auez19X0aK89BgZlfEiVYiWnPkEnQU4T3L7wraJomJzTchhJUD6oJm+KQJDYf4YXqVLJSw0XVn4v8RLJYd+/N+m1gVQX2kQDT5ua9t8bUEIPza0qv7DFfHT80lOm0/012xeRFaHK5RyXfzyfmRQy/1qmeVv09sszvPvj/0OGF7F9+8XFlEYeq4A16qL8InMADeXmv18f+YNsdjDzGdvGNuv6JOISogxNLtpr49rWDwgC6eJMFQ+4Lnq4rkP7xfaNv4PU5A3/iRsmoLoUfxlYeTM/ujEsrAwkKs9ujmxiyT9dOs6afHrIkfLDfVnXLevqn1EB8ujXO48PY6lr9rVd+l4zwiV6TlgLh1LRVISvdcPnVVcWjuaxXX1CiHOfVRbQPbhUm4rv/CziszC6rCCN4EDIVQI8+EXYPlfHuiRQK6mrTllLENfSJpbhzyKBy7suHz9kL2eaWb+vuZkWipElgYbm6ulOBWD6V1Ttp2oa4HfVGtHfyROgS5fyWo+8LNiDKAYMuNa7d7xVZo20dJexygNxCHSZaLEN6XfpICdKWitMrrN5yOf1SboxRFwBFpklkw7AbUtRC5c2zrAM/yVob5S9E1ZnnY2hbsfeq8mpVfrERH4/8JVtMRKrSB5ra9vr6n/uEUn9fEAkswVMpoH9kyk5/Eqc3LJpj2h7B06vGj6v7VD66Tc5USVKznsIN2P1TeJHxdgNKSrqFKezktL5Sk/05r9MGbEJ/AhD2z5+Hlw1ptDn3jkEw7dIKeq+4e8zZ+9jU4WpeJp8jT/4HrK7ltwNwHWciV/G8gvFe7k2GWe7NUtFDpYm07jOZlNFuTXgMzIi1V2ghcGyu31BFAxrWVOcd6wYMgmYvg+9uyaswxN/Y7MpmZzG9jYfUVEjSO4wptHw/Dh4tBvEcZ9qdVQyFdXkM1SbuQTyxDHCHWEEtk+lP1Mr7FoZgyaxSznX1bkplTSyWX9mC0MajU8IeCq1KUEnOoQe5S+JnzyD3deeWWhEV/vE1IgknbwFJx2HVoC0cb32H7HkP8/G34hEb08w4Nxrwq55cDyvX+cYXwSa4oVCi8diopLWpIRofQloJN7NzmlCwR2Kqt7h6fj0CgVfVO5fW3aTYC0ZXWDfAhn13SmkXBlwtYycLehl+V16Rp8Nt5v/hje+HoFOu0btq31kGH/qq6b0qEp+9h8OxTLQZc1kk6HA0sw1dXG4KXFz5njvA1113rRxZaunl63AjkDqZsH0BLBTKa/kNQngQoXfWwfpWFv2zM9xsnCuf4+YrLSNsFjAWtuXb+uHYbamHAcecmlqePyx96YMN+fvS7FLk2K99IgKM9YPVsmxTx4tFvvCXQaGU6HIDFelfW/k/DK13E1gMoUNRUoEyxHnOLYqQdCRRqJ9+jSSoh1rjuhdup5tuPZx3tXgtAvBw14hAxN+ytOmc9caa7sfASZmGHn8M2NfopVciIP/LlzOD8I259qch9suwfuUgqa2SpzZ3m0RabWiLwvdEZ1fPf95L0b8qpwxGkWQcNtP+oZcrCJcoHT4PeQDAE46L0dXG1p4V4uEmZ6JysSyyVFihn0NVCK7zLGyaVmAVQOqrByC30LjqTZ7qHbAgmLzOFa/3hsl/6QYgrP4JLeC1qpA/eenjbWcZNubMdfal9p0RiBLP6FAzyq8rDLuDs0hbKdbEitTWggI0gQ0eemFI8YeO+lL7DjAy+Yc12Y4iPGcCp3OyvJQwh7nEyE1/ExoUZ1E8ocTEZaExgEM9qd1+xYe6HdniuQNC6XjGwC8I5jxu+yKBbxvBs+bD3UKcnS5tRmkaM68NvrNkYnbj00tWRbuDqWMd9mFS4Bo7YEvkbjdRe83BzVBQKBvxHMSAUnOtXVZsKUXXha7kjuRXFrYXzmhAatW9eh+JDo4GwD8fod5Un6EkUUiwna7FCmFUxuABR+Tmt+ioRbSZYptt76CFiOObtSvZdyN82YmNVUNggC/Vc8s6/GOUzl4bjM46qFHH9qPp3IpmgITthoOWJ9dO1ZIqcJ1/03t8HDPh9UXDi5LhOXPrObl3TPMZIZXdW5fHQzrIZ+NPJ0i0AjL7EbPNYiXwm6wN+sMM1DNwKjxtvxcsdOuyjXWuZ66CsYxBy1TUjBmyeuOJV2EZg+iNtIdkoLhv7Zrvx5biMcNruOix8RsYUERC/j1rrYTphoB4q+s6i9fjjWwJ/1IQo5McskitRBRpjzRHM3mFm9BW1StrMKxoK3RiJffU5OqyMK0ldJxKbmS0AtntSFMtdPDkF9YHJnMHfa5rPdnm6hN6nHXGcd4ytpixyXSt5Fb2d0MhwRwfIn51vuEruwoM395xQvvgcCNCARjk8mPsTyu0E6EtWDVKhPmDE5t4a/G7hl6LAKRXec7qglKsF1UmdZZDsHdbg4WaO+LNWF1VlVt4qVTkB1vBX1wVJKWMGdY9Mk4Rg3TWYVpzPm2yqtxcnev7haGnOQ5GF1gFZlqSDnb8Ka7y3OHsGh+XxFpAgPMw68ZfrvFHzEXhn8OV7sH+up5c0/3iHNbFnnAsRDVcFciYnLfm9Y6A6MeUjxYyi35mWFiHkHDpxBiXt+UV9oocJS+/wm9v8OP28bXfza6TGlu4VBnIQfsznZhIh5j50Zr8W4+3cwEM7jlmEDaAmJNwkjqwtWGawP7ZV4uMzhTXNnlzxnH10YNa+YMozqYU7keEd5WT66SEsOokRi6mzihl0iaHfCEpviG0yll5Z//pGMEVOw4+axlRbnCF3JgUxRAzQzoaUdLC6pQ+8GpwT01zmMP0U8RymBu+nPaUhiAsTER3/3LyypjS3H6chnLxmc3hAyPhN5g2LYxJP7Yryzji+UysZfRRBoJ2fOgL2K7tScuVhXRPXfpI2mcQDTNxkw5++vLKw9wtBRGhYcczP4d49v2aF3o2o9KJnOexaO7iDOExB2CTqAq1jlni0WThHOczcBh5y1cuMdKXEbT5NQZI3breL9QFmf01lGtXG5W3NtPkl3q2tOwEheFKHYx2pdebIO6qdlSqsVKBWIQCF4KKJ2BHHU+jeOATvZd/ijykDXNcFDg1oIDIkuX4VS5/vS7PJvxb2zAih9IiKbont/4nSpz7lYA4bvX6REb456AIS/vQZqiODQb1eJouKZVPwWm+FeDGbz9LOt/AJ7fuwawwJaa63cBLRjrHtEmOF1zYtWdzGLAmDyVKH3wWac/uap6G4jdCfjLOnGnfVeItjF/eRn8HKAru2V3Eh2vX1Jqc9d6gCwC250znVvKToo7y3iGtFCAypEsFw/sgq29tHdBH/BrmPX3vX4e0eoieLEwXSOahhpmfO/7WL4RZZgroFofILsQ49VFF0QEwlRXLC6g1zI+P6pWU3wbmlgO69zAdezIAriYhpiRk4YwOLs5PIC1GcBFZ0aOLo8we3SnmjpprkoqQ4xXOguFeCgYzhcbAgo6ASfF38Nw7CnGdzjnBDFOQSZ9sD/JpOcFUDnN1Q8s7C5aAGiJaD6udH0Pzsh3rH9iT67H9CbZMG+6g28j9jjOzMw4CukUjzb6lfepW31DXHwCiTIYhtF9V8P/ptz+vLL/9LpS4asP0n+v/VxZD6sbUO8C2MXgW7FYvSbi6PEg5ZsC+24cAapd+u8IK/ypTXcg0PuxRXHApEZWSWvN5spbxg94SgY4QqWyBCxUXAEYXDFHa7jkD24C9IxPW1tgZFBkLpTTEZ0QZY5k8Ijmu/XMWcwdpCi4yXQfkCBIZ454zKMjiV8rEqMw5nQ1Gd6fUhjJ7VGangdcNweeHP5AATQCwAaRKORcXr3DOqvRh0lpe63fQj1Grl/7RjfbUId8m+nJJGbLi1dv+umGNzAtWsSuaVmh2vWfmPw8sIeDhfrwXT5EpKhlyWYQKKsRhVS1SQCJSwxeDdtIHxj1mKWDgEV0JA5K5f7R+pLC0/00/tiOheswlWwR1FUoLeAvoS8Io2tDYVd7jdsVd5bHRicVdigjcM2el0hZj43x9/75B7FmLO7CdLjFNjKivTVCNjj4Do72m/2Unu7unNBBSt3XMpCzezBUTJuPMAiFaaBG+o3UOR+Qh0+Wfx7dSYCbfr4XsAhsaTdEGm2ByWN6rs81EquA/OR6Wr5Jzrag34p1NYYrXIF4HRuBs0j+KuaxtFWWs8HGPSYznWtJ7sMhxuUC5S139/E5SVy7x1qhYFI4z1r/k6kelMLxs4H/7kGt2WoXJgbabmSgPVXUnVeRoqumeVc3f4KF4IUe63vCmMjDrPKCvDPFJ8vN7d70z244d4hFT3LURL2B1z6fIaLGuwj+7H8XMG25B0H8M0zMCiK5Ux0qxmzkBeFvl+0/mE6UWskM4VXUnDpSOtDUn5/1ZPTrClACYFsfF/mC7kRkLmNS0t7P4gMoPgI5YHljhn1Yqq+95alafONSoEFgw/vMlZRf/iyAlRwx16tcv6ehMPbz6xSCzvZRV7LD+S5d1NjKOuTmTUc3hs+iJb/xlwrkMOr+ucVDMM61wkh/HCPPFvGRhdmS4+Q8ioAisgOSMAbMQDCv/bHMsAtTqbRHIp71M/KFLceBSozrLg6VtURzxXs2R76NkkefJBd2sRpk+cu2dxLit5Os9slHL3AtM2spTWHSEPTZl5382JIhtbBLB3nyjYerRKSiOwGbrYzVlnSnGFClG0XGmZWakI46CPVsk9IeCLM/pmKmWZ/P7j+FhzmXv/blgepOZgHVM9ncSCnbuCeiOWfdYnZNkCFihYyUjIBz3179oCLSBgBg+K9RofneiTjxLJfLmRLjBjit29JGNAH6ECe+gkkf1wdZGn7rnkXfTW8OFvy4SaEFd/7KJhtZK/vKwrWMDC33VUKNwpCIsRw0BIL+kH/xh5gCgM1XQfCSj6jJHNjm1w09uTKT67mWlwIC0pX6VtHy9cDJeI3ulUOl8AI+WtKZycE7bRA7OR80rVIHyOtL9Mgmw==\"\n\nencrypted_str = binascii.b2a_base64(encrypted).rstrip()\ndecrypted = Cryptor.decrypt(encrypted_str, Cryptor.KEY, iv)\nprint \"decrypted : %s\" % decrypted\n# => decrypted : fisproject\n" }, { "alpha_fraction": 0.4702380895614624, "alphanum_fraction": 0.4836309552192688, "avg_line_length": 15.800000190734863, "blob_id": "962f87aa9e8ab1667b11b7ca346800609c106976", "content_id": "3cc971e9c84e0a19215e0bc8a130588961ab171a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 872, "license_type": "no_license", "max_line_length": 43, "num_lines": 40, "path": "/learn/006.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n\"\"\"\n用户输入两个数字,程序计算出这两个数字的最小公倍数。\n百度关键字:辗转相除法\n\"\"\"\n\"\"\"\n1.定义函数,引出俩数x,y\n2.大数除以小数得一余数不为零时,小数继续除以该余数,直至余数为零停止\n3.最小公倍数 = (x*y)/余数\n\"\"\"\nfrom fractions import gcd\n\n\ndef arb(x, y):\n while y != 0:\n x, y = y, x % y\n return x\n\n\nif __name__ == '__main__':\n x = int(input('Please input x value:'))\n y = int(input('Please input y value:'))\n print(x * y / arb(x, y))\n\n'''\ndef arb(x, y):\n print(x, y)\n for i in range(x * y, x + 1, -1):\n if i % x == 0 and i % y == 0:\n c = i\n print(c)\n\n\nif __name__ == '__main__':\n x = int(input(\"请输入数字:\"))\n y = int(input(\"请输入数字:\"))\n arb(x, y)\n'''\n" }, { "alpha_fraction": 0.6036585569381714, "alphanum_fraction": 0.625, "avg_line_length": 28.909090042114258, "blob_id": "0a776c4060045574b3a9bb5daf5a2957d1c4149a", "content_id": "f105bc0de2eaa7e5d707a59ace2bc741018adeb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 328, "license_type": "no_license", "max_line_length": 40, "num_lines": 11, "path": "/21days/3_2.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\naint = int(input('please input a int:'))\nbint = int(input('please input a int:'))\ncint = int(input('please input a int:'))\ndint = int(input('please input a int:'))\nfint = int(input('please input a int:'))\nalst = [aint, bint, cint, dint, fint]\n\nprint(alst[1:4:2])\nprint(alst[3:0:-2])" }, { "alpha_fraction": 0.5360360145568848, "alphanum_fraction": 0.7117117047309875, "avg_line_length": 16.076923370361328, "blob_id": "060c073c09aa515880cadab8f7f96664d93f413e", "content_id": "8653cef3c3a8fb3d463bdf18d6281c70dc0205c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 222, "license_type": "no_license", "max_line_length": 21, "num_lines": 13, "path": "/requirements.txt", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "Flask==0.10.1\nFlask-Migrate==1.7.0\nFlask-SQLAlchemy==2.1\nFlask-Script==2.0.5\nJinja2==2.8\nMako==1.0.3\nMarkupSafe==0.23\nSQLAlchemy==1.0.9\nWerkzeug==0.11.1\nalembic==0.8.3\nitsdangerous==0.24\npython-editor==0.4\nrequests==2.8.1\n" }, { "alpha_fraction": 0.6025640964508057, "alphanum_fraction": 0.6111111044883728, "avg_line_length": 24.88888931274414, "blob_id": "aab229527bd5dfd5a67bb1aefd1b7c8367c6811f", "content_id": "177277b12a2363a22f97fae10a91d3b8d0f10691", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 40, "num_lines": 9, "path": "/21days/3_1.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n'''输入3个整数,列表,求最小值'''\naint = int(input('please input a int:'))\nbint = int(input('please input a int:'))\ncint = int(input('please input a int:'))\nalst = [aint, bint,cint]\nprint(min(alst))\n\n" }, { "alpha_fraction": 0.5288461446762085, "alphanum_fraction": 0.5384615659713745, "avg_line_length": 25, "blob_id": "d8138b5ebeddc94cce47261e71a572feb5990e55", "content_id": "8ca526c7a6ee86d2a20dad64b29356c7b4e3fcf5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 104, "license_type": "no_license", "max_line_length": 41, "num_lines": 4, "path": "/global/simple_loop3.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\nfor name in ['Winken', 'Blinken', 'Nod']:\n print(name)\n" }, { "alpha_fraction": 0.532608687877655, "alphanum_fraction": 0.54347825050354, "avg_line_length": 8.199999809265137, "blob_id": "89095829d11b5cd0a1cdec71cd2f09e124eb7999", "content_id": "4e049ba4b0111aa6f02511bfbe39dcebe0fbb761", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 92, "license_type": "no_license", "max_line_length": 22, "num_lines": 10, "path": "/byte/chapter_12_1.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8-*-\n__author__ = 'manman'\n\n\nclass Person:\n pass\n\n\np = Person\nprint(p)\n" }, { "alpha_fraction": 0.6901408433914185, "alphanum_fraction": 0.7206572890281677, "avg_line_length": 31.769229888916016, "blob_id": "67d080db3c5f022773392a5f13bc02518118f25d", "content_id": "9eacb0d1bf792b5afcf0b2768766d60f17d26293", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 426, "license_type": "no_license", "max_line_length": 80, "num_lines": 13, "path": "/other/aes_js_py/new/002.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\nfrom Crypto.Cipher import AES\n# Encryption\nencryption_suite = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')\ncipher_text = encryption_suite.encrypt(\"The answer is no\")\nprint cipher_text['ciphertext']\n\n# Decryption\ndecryption_suite = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')\nplain_text = decryption_suite.decrypt(cipher_text)\nprint plain_text\n" }, { "alpha_fraction": 0.6161879897117615, "alphanum_fraction": 0.650130569934845, "avg_line_length": 33.818180084228516, "blob_id": "94a0db0d6b590a2e2e5497fcdc56714461e978ca", "content_id": "dfb7e107910a5aa6d97bcbad71db434a32a83338", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 383, "license_type": "no_license", "max_line_length": 49, "num_lines": 11, "path": "/global/test_average.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\nhigh_score = 95\ntest1 = int(input('Enter the score for test 1:'))\ntest2 = int(input('Enter the score for test 2:'))\ntest3 = int(input('Enter the score for test 3:'))\naverage = (test1 + test2 + test3) / 3\nprint('The average score is', average)\nif average >= high_score:\n print('Congratulations!')\n print('That is a great average!')\n" }, { "alpha_fraction": 0.49000000953674316, "alphanum_fraction": 0.5049999952316284, "avg_line_length": 17.18181800842285, "blob_id": "af41f792705baea24126c4539ddf8a94fd42a656", "content_id": "1ec16433f52691c166c629f450f4d2a5763632c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "no_license", "max_line_length": 28, "num_lines": 11, "path": "/21days/4_2.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\nfor i in range(3):\n for j in range(i, 3):\n print('+', end='')\n print()\n\nprint('women')\nprint('doushi', end='')\nprint('haohaizi.', end='\\n')\n" }, { "alpha_fraction": 0.6333333253860474, "alphanum_fraction": 0.6399999856948853, "avg_line_length": 20.285715103149414, "blob_id": "8d41a00887eee2ab778b33628503888d45d8dbe8", "content_id": "14ce18611ec394c4fe13f4787935966f411ec646", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 150, "license_type": "no_license", "max_line_length": 28, "num_lines": 7, "path": "/global/string_variable.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\nfirst_name = 'Kathryn'\nlast_name = 'Marino'\nprint(first_name, last_name)\nprint(first_name, last_name)\n\n" }, { "alpha_fraction": 0.5842450857162476, "alphanum_fraction": 0.6433260440826416, "avg_line_length": 29.46666717529297, "blob_id": "f7676d524a47081b748c7bc90f18ae72901fbf4d", "content_id": "8e6b799371f6e43b85f685d21492996176e358f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 457, "license_type": "no_license", "max_line_length": 53, "num_lines": 15, "path": "/other/aes_js_py/urls.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\nimport urllib, json\nimport urllib.parse, urllib.request\n\nquery_args = {'pass': 'b6ce159334e155d8',\n 'word': 'U2FsdGVkX1/7IVjirkhwvDYzNDPDDyiDWbXHmETFG3+RlJtHwYBtXUL+tr3Gbu17/xak/TACBGRpGfsbEQdnnuwAGmVtf36QRsMHUWNv5hbyQ/+Ymf/J5REE94DfRqQUvOjeh6lbGz4VoblsXK54AqSg260j69ScB1c+YC0xYc14q1b02p7wyfxNsmydsqKPLlNfVDjLGsQL0PihKJeu8n4NXRCD/VDRImuEvTDTayCsiKB3TjH2ONDVJI17YbbX7Yxds3CD1rcBwn9iJ4v+5Vee4p/KoTwak4kZjiNgOQz02KI5QF2o9RtpqaWesU8d3o+agD8+6gjZv5GhocWkcWVWCea/xqvEA/26zXswNvkhPOoZrlThWps2xf+KLHJoI4+btDcKpy/9I5Xskcq6yN/5vfwKcymIlICnECNr4jI3pf/VXBB+mt6BQCD6/pvWrfuhEG4req1mziOZRX3NfOsB134xNZze4c/Fmp7o2EHEYwdWCCU3kgWSEXnX9Mv7kL2rO3YNMlqJnQx87XCM7Sk2OTXjrJFZ3PHyrNMcen1g4Xf0KE5nXWtnSD7lQONZK6nlLahlKfyWPI7RyYNDqCUo/djhxygkqNMQL0S8Y4pbkf4nfS8pxcFPMiij7lYPHsW/qHzis1S0PHyK0Wef9eoXlYzBz8TO2Hk23AqwCTqGjfGVNoZe0oMFyH2QXSI6Ibm8DtngkUmrRL8UcDi7/4fND3PTcbdHQIDNVoDohRDCCbiSfRfh6eJvZfCEG7x7trSmDcFuoL4x5a9NFKgmIF4DqM/4xXFrBlj5oLyMu/PyOGdvc7vz/nzUdc3276/VPJDhwvSKycywFikNpgfYVOlZ9kgOH/9DwrLQllhKryLjV8mgnJ/5/f2vAp+ukZQr41wAO5EUkEgrVRiZPg8/pc2jhBKWj/a2aJYX+WwgeMcuSZ5Y7cYFvGh7ruH/0xqDMc4wS06bkgvaIFUchwJND73uPM/BqsgVEjVVMcRbv74ocqgiqAriJQRZG3hI8s2VXjOS9JVzRjqRDkjPC0dP9XVVCGfmlNCYcrsFMnbtosww3KLmDLmYZ5F9QqfuCT2Wr6EdMN2T2Nam98sGr08MTqd2kFXphUNr4eK8C+8B4S2pbJsABYEIox5ARnXozY3Q5GrATUa0c7zpNij1jPHm9X019itxVMPhaeN6fc3Y9d0lTJZ5BvF4YbB7gaLsnW63MTQmgRpSGPyCYBK5UcSJl9vALFW+ypQyKlts4v+qpUwXyegC9DMuSoljjZMMFh8QRoi7kH+eRt/iIZBc4RKx04opB/SkTfIS8hu7/O9EmxW6drPbWpNAAOKRPpk2/FWdFIixIw7S/FWGGQY2r9yQSbNRFEq7u6O5gXSulD7s/j8E22yddOBoGLfDSc7afSV4BKX6V8qNFmCVkjdcryDh4ZWLMfbAJrA2Kjs6atFHvbOqgBwMSZn33ing+wqw5H4Hxacu/uoyRLo9RYyY/uiC5BqV2jle43udjCofUBCoNsVopKXdr6t7vkwQcJaqAqIPwqbC0/Xi2xHPRZYifzBRPfMaQ0LABSQOOHx7VprZ4Di9pTQgA6CgOJXW9dVQTmDrUGdd13Evee6Y5o3K/XWNPMiOu7T94EMR/2d4O2hCvABvmX1tKG+9AohsGIM4saxr9fwu34agZjmLXiSQiFwPVKZfLsy3+3Ji8JRJIyKr2bEMMz5sikZoWf/OqoWyV80Cw+LvURUZEYqaYeg6aAv0hRXHwDrODM2KMBXUsgm0gYoo+C1j3so5d6/6wrjugYngptG53L2xcd4iqAZ7sG9xFpCXbQQgtTqHekwThVZLAV58ElBBiUS6tcXym6DPGgCcx29Jw9r10OBFlbMbbNXFGCSGBDBG2GDbRnWXX6TWbOketDF2qQ53IPQtwSUfR2U3OE4RxtHjs8VArtezsn5uVZVxKThXdEH0lQ2+bEYPZRAevIyPj1Swwa123/dqqyBOUPK6KUfrnbfeMD1+mSJ/4uwuAfwQOj5Ds8kNaPpCPGz7KCtmgncoIUj21KLO4F5UfFQoZ3C6QFi5K40UTwOT3KfZyaeFLeSB1Sr9PZXsSm3OWBH0D+3AdFplDrsUR/tIK0BlZS6yuQe0VsWrXAdLq0oj3Fa1Bz9FcNGfoyOCxlrLl1Gh++Cl3FqDHSy/r7MYy7xvA5rh2whci6c/WC78nrpMWgNDhw5OyrXxcleXhLbRtKs96cGM4R+9o8yR1Q6Z+eWuHKFiOa549hQ7LCh+M3c5JKrqvTre4v+F6OAiYOgzbWIy3s2cwKh4asatKcOKnmgbeEgQDpb2SJmK7i3S3G10oSizEhhuqewujCrzLmIATNpktJ4xkoH9YG8K8GOgdkvw66wLm/KYgoUow8OHu7WcDc0wmE+2/WYegcRT/6lpbQ72jdUqo8OXpmqYP3cR5HSLv5sRCmdWO0IkylLX3mWsZklvQXOUDhodk0U+549EoWub27uYVrhzOjRST5vMs8y7/4XsDZlazC3+JrZAq0jkERk7AerJ2VtTp3U1de3nuuxDb4f/JLNTkuXsWvE6AdBded8SR7QKvub0bY555ssWgMZV/3m6ewBDPn90bBl03DMXiapCycPrlwQLr19F2e0/WcEfYoSDFn4Yj2IBBSD91F3aPJKIPqk9d/jfjmRvq5XME04Rs6i4lcIGUhGlh6xuV4rqdZrESdWgq/1WRikp+g7zv9g4lbrxNoYDMk2QaCsKWgHn+cMcg13pwUgLxChmBRow4Lx77P3AIZfhw+OxDKE0x3/ifhkvSUNC280XOKngrtVTCVxo5cHw64SvE4qPr4n0hO7pqqmsABA57KUC3VzBWKTIDmWyLlVUjSuT3nUrpN3ROWVnTDmVeCXuTy0X+Q1l15xYCxZ4goXUxbIMGkktw2zZqrsAXuWHblq8fcEbkOJRDhrqLZUULDF2q/ivsm4HaknXEgdrqlbLjYDMDUkhDGqff3N15wChSgyUqY7bfQfADqZKHS7RvfRGn9Bp3JmzwqsE8JKMNGKjkDdNCnM45gy2snbR1KCPArPWiGZtKuKKJJihDtggeGU5ajoxQHtZHnMKXBOYFGCON9n2YkYdYmT5HO/fd1GIky/NUK1xbiJZAvqXBMRVNVXAYVOXP8bycH8wZpd2+qwlq8lbPF3FrFv8/V/SeF2maQW56ZhB8uHJcp4ojY09gqimorFWQ20vAzAyl4B4Whuz6ID3OOvv19Ofdq4WbByTZbTQiRU3yN0qXR4SP5LaAXz2QuStYOCJX+UsQcxAgykd+4ojdX/Lnz5+dJjWovyD85gDpClQZiBJ61wqFtrsQYhThyFYKyf4MgPuj8gPgBQ4B7BAHCBQ69zxCggLSMwa9Z+QEz7rej14hO/HmsdbXGyKvlFU4K9YSEgS/TYhqpaQKA4YECyQqZeMmgUy7OMf4mlboTcIsi4yyZjwHM6aYMf1ECZlrMMyiy3ZtV9NIdlY03YzzdJXNp5aJp3zvk/x6K2HFGmm311O6AGLHAR9hvqU3izkwoAPgupe+ohiOTNDBXn1pOvKVeIkyy3llTMdBXaOYXsbcsWCyOs2+Xx1RhmemuHslomcU7Rd+1S6YbpA7v5dcO6chNcFrGYJ3oCwwNoXFfN3M3VTgCZSvUarzSkSqq3szSe3gPb2FsNFnhvz9wpnwt/0kX7m+8Y+OiWKTQv6T0R11obSwpHT0tmv9s7IGNhQEFM90NAs/5gOmnHP9Ur3ZhQBI9JejR7yTyfjKWoJnP5uL/qvOTlHhuU0p9LQfjyLX30r/62/oZAHj8CWKi0g8uy2t/GfvUrgqH8q23DZHG8Yjn7CP6s1KnBmmMGQv5fJU9JAjq1kuRHMTE+cbv1AeoQzfTEIX6j3cQ9Qd1kx8b8y6w7zdKV23t+SHyoevnt38eY9BlAGKZ1KmTfvWQBQZ2eQdgE7zsdcH3D0H81CjUc9aE/pxwpKxseHyrzpCBWdPmZcT/wHhuhly1HiLult30ag+bX7cqLyTvMbg10WKDn+6iKHb5KeLG0n3ngqtuvqZnpf7eFjftSIJ4plaxO1VyU8Qdt5Bqb88Z8vA9duOCPPe8YRtIBgifsxwqblESimmvWx68b6iGuANFLZueMVabAMW1ydoqmToZ+ODPs34zYBVkIcARnaEYGOoc4LP5dAjKmHGzlchsRgR49owzcF1JYq0ZayOqbx1v1HmB+lckF7mfLKWFjJnDNiQh/eFN9aAkt25Vgj1P1XWGpGqKuLtaM9XKa/O3CiXQhwG3vjTWCn0hw4HXUZ9vs3ilaewmuSS1/C8MqeBu83Z37/hEiDMrwaDz/y1ApurAAz5LFBZM7xbPWojtd+tvCPYwCUm7vXPurDgUMUI2x+Kb0qdJ5zNQBJgn53NGNp0aE4lJzlA+ds7xnYUAQoG1p75mO/OQNbkhunQLmW+HkPWIwFwbEIfsT2yFAFUlTfzLy+Qq/MJLgYx5hskiljMhvfWdQV2Cxmf+VGgZoPnf0InQPyKemGkDwyToq7NjGI9ZGnw7S6TUokmIKwnc9EdGyjTv10AXTdqK0mwd6nIfWVaVvbUexQIzINyJ4171ZOlkHqQ4vw3nERtb3fnw13l3vGbfW2gLZHxfuiJizmVd8AbsBNdGPbame3u86j0Bq7NDIblsIAyOQS0MVyEZ2yqPhaoIreX2xGDDWFDPW/HLCQnvb6Y5QvL628QN1JCNKHbSoxSBITB+cP0fOghMsknCBlCd6pcI1YPt2aWBMyYdjN5UxrJ608rLUR276qLj1c4EM0WHya6HJJ230rD76U/m/lBRZT2hPF9ldciBGl2fHTSCfbFrNxMV8SdjYyKRx2KNYhLQ9xoS9Ik/HAR2q8450DRMyX3SDE+8JFN8EifuMKScqwEaHIp3Upg91gDTIS6fE2nzKackLSMrySQ0HY22JhxA7jsHPVsHDC7k8oY5nRBU23wTEkurO6GZ1jlaXkWgqcJWi28wBu3TVMdpEmpkKz1BGb13Fyb6bM0qGIqAamPEHNHy8TeTye4s4of5ZTsQgTGT7mPla5ELT4z+Oipx2lqJDosGPjtzm1I094YYFY3bXjxkgvRsdJi3IoFlWy1NYo/bzeWUTy8kxYAR2bDETKbX+FamqxLwoLAi7HHQM4IlVxnoiHPVV9kLGCSc5r6EQqh6CeDm3GlgfkIO5WknaijkPOIfaGLYgCX1yYnKAT2vzSHpyr+7J9uSrsJE1ZQf1q0mYv8ZhW1yZTQIJwQPCdyuh/hnBngq6GRvjJb3YfQlQs3eYMzDASDvyS5k8/TXhJp9UvuWYq9rWEmWO7bz7Ouimi/mdRbI2IuBHWRA2u1IOjAR59P/t8RcYeGCyb8hGQFP0brBi7Ey2AFlgFmhW9M9IOkKxtXSaHyB0oQWP2SRt1WmyMGy2Q+ufwxQ6c5YOQ376aYTl6IVXhEY8p9Q4TazxTnI0P0/BrlEt4xvjyYJcVcxvl8KuBrehyjC88QR7grv06X9A57jhe7fNWJxO79Pf6uUFql/60728z3fp/LKvOjIBfEdRXzwD5t+WzGm791SaKNLKLHiV9bXm4Jw+O1k1OJcDDyo/BejNJai4n9xy4SpwRp3VxgQvMg4VPD3ORmRNBXispn9oFJCOzw9vIX9OiPYByeKM0owFDZAuwdhFWf2OIF3p7otuEdVrYGrT6O5MdCwqUG30lh63te8vHeHXtcaFTVgEwniBgmdAY5TxYixSuOO1zRYA2Nw/HfFgyhC4AS/7g+m3PQgXxdGK0Vr7KIiOkxBrbs2WyJhjdh64XpGDAXu69cwTMFgSA4ca2x9xwug9ysJMB/4QlOgLBEdjGlma5NnXuLA+Km2Tins3XHdXYQW3OA4vMGHfucWYLwBLIIk1/zzxVrTwCTu4G9Be3W51GGGl2ptZOfWTw7gzcEgfzHgZ3sQUAVCwphxSi7H0bg80Xpbq0vRiMIrSb0S8kznSzRSVt9AZU1EeU3DRJypimXTUNdV4uIMFHHs6OKkX+PxOKFGIK967LICxn97xd9CO0J3517+den+3XzGTiML7WOJA0PMZr5ql2PzvP1fMofZ2Ss2oNQeNxROw6vAx+5wXR3v/3CWKsFIr84JN6HKgD3CdNrGHyUek7kFqjBAI1icxY2n3pjbxp8hrBhyecIFNkXWH9o5geoIjfDq0DeAB/Bjq7GyTmXv5d1mzDfhCo1mjV2KWiEzP4YqPXEdhYUWypRnD3uHeVXagZxCAxkk2l+Z127ww8fIZD7N4UDFhHgkCBxyxreXIJd+4hKUxYmZ8ZT18ZqYoTJrB4Q0/bajNtBnFFpQApsVbuoVn7GuJbFOV4V3UNfVBiaOow/5Uq55aLLagTm5YndQVa8irP1fiP4pqKaMZdsQkqVZFy0ilRCBvijxEcxOdBTGdFGy1wGBK9pUTq87TolawATODLpDpyjyITQnbLkJ6z2oU/MlKrmLqjPl75KOUN/jldj5o3R4xstbi64/90CCKTKc6WPjgUt68PCKpnUPtjjArDF5y26KagNrZ529PBdwpTfxdL7k/bd8KBPHUCNng4P6aOItMMOhN8PFyzI+7GEwZ9y5l7rK/38n+Sab19WHtoGX8Hi1utFhPOy4gYAgikJEbyWoiFHgT9hteYUHWIZ3RkfvG7jX8nrd/nymy9Bb1hboxEfM8/qnh1mnMt6atttUkNzJ3qLMXYMgLrGGvzgfoNUmx1/Mg+DewH1zvjQufjE2UHLQpLcPuAk/rFfVXngqTGxka7UtQFpLk+7xEMWYF/5T0O6bpXEHFM8UkY7uxay8x7p/aJrh1BqPCaKnjW96Q/bQ=='}\nencoded_args = urllib.parse.urlencode(query_args)\nprint('Encoded:', encoded_args)\n\nurl = 'http://45.56.64.124:3000/aes/?' + encoded_args\nres = urllib.request.urlopen(url).read()\nfor item in json.loads(res.decode('utf-8', )):\n print(item['album'], item['artist'], item['mp3'])\n" }, { "alpha_fraction": 0.6214689016342163, "alphanum_fraction": 0.6271186470985413, "avg_line_length": 28.16666603088379, "blob_id": "c26b22a12b23bc56514b715a1d89d3a6b012d944", "content_id": "bf53fec86b7bcb02e75007ffe9382c493242a9ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 177, "license_type": "no_license", "max_line_length": 45, "num_lines": 6, "path": "/global/string_input.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\nfirst_name = input('Enter your first name: ')\nlast_name = input('Enter your last name: ')\nprint('Hello', first_name, last_name)\n\n\n" }, { "alpha_fraction": 0.4725130796432495, "alphanum_fraction": 0.5157067775726318, "avg_line_length": 24.46666717529297, "blob_id": "efcd414db2f831650f076d171c0ca14b8f7e0f58", "content_id": "f42fb0876b425812f5ad26ee10af91c336ffc015", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 826, "license_type": "no_license", "max_line_length": 90, "num_lines": 30, "path": "/other/problem01.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\n\"\"\"\n去除重复关键字,\n'[a:1,b:2,c:3]','[a:7,c:2,m:7,r:4]','[a:3,b:2,c:7,o:5]'\n\"\"\"\n\nmyseq = \"\"\"[a:1,b:2,c:3]\n[a:3,b:3,c:8]\n[a:7,c:2,m:7,r:4]\n[a:2,c:4,m:6,r:4]\n[a:3,b:2,c:7,o:5]\"\"\"\n\nres_keys, res_strs = [], []\n\nfor item in myseq.split('\\n'):\n # 获取key\n item_keys = [raw_item.split(':')[0] for raw_item in item[1: len(item) - 1].split(',')]\n # 判断是否有key的列表,然后决定是否放进去。\n for key_list in res_keys: # 已存['a', 'b', 'c']\n list_r = [a for a in item_keys if a in key_list]\n long_len = len(item_keys) if len(item_keys) >= len(key_list) else len(key_list)\n if len(list_r) >= long_len:\n break\n else:\n res_keys.append(item_keys)\n res_strs.append(item)\n\nprint(', '.join(res_strs))\n" }, { "alpha_fraction": 0.553398072719574, "alphanum_fraction": 0.5889967679977417, "avg_line_length": 10.884614944458008, "blob_id": "6a9732fa293f3669338e3e0c818db92fa18891af", "content_id": "a32ab935be212cd24424b52b9bed0a21a4156b53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 309, "license_type": "no_license", "max_line_length": 26, "num_lines": 26, "path": "/byte/func_default.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8-*-\n__author__ = 'manman'\n\n\ndef say(message, times=1):\n print(message * times)\n\n\nsay('Hello')\nsay('World', 5)\n\n\ndef say(message, times=2):\n print(message * times)\n\n\nsay('Hello', 2)\nsay('World', 4)\n\n\ndef say(message, times=1):\n print(message * times)\n\n\nsay('Hate')\nsay('You', 1314)\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5048543810844421, "avg_line_length": 11.058823585510254, "blob_id": "578094dc6b4c4a02b5e542d510f76749bb44d52e", "content_id": "6b183cab9653705e104a313a051080218cad449f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 206, "license_type": "no_license", "max_line_length": 28, "num_lines": 17, "path": "/global/display_quote.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\nprint('''one\ntwo\nthree''')\n\nprint('''one two three''')\n\nprint('''one, two, three''')\n\nprint('''one,\ntwo,\nthree''')\n\nprint(\"one\\n\"\n \"two\\n\"\n \"three\")\n\n" }, { "alpha_fraction": 0.5263158082962036, "alphanum_fraction": 0.5457822680473328, "avg_line_length": 18.26388931274414, "blob_id": "cb94c3cb2bf222fd8c63959b648aba14cc6114b6", "content_id": "e159d1de06186269ee096350d6c10122a4032bb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1499, "license_type": "no_license", "max_line_length": 72, "num_lines": 72, "path": "/learn/010.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\nimport json\nimport urllib.request\n\n\"\"\"\n读取1.json文件内容,然后解析出来把mp3下载地址找到,然后下载mp3文件。\n\n\"\"\"\n\n# import os\n#\n# for r, ds, fs in os.walk(\"/home/test\"):\n# for f in fs:\n# fn = os.path.join(r, f)\n# if f == \"A\":\n# print(os.path.abspath(fn))\n#\n#\n# def file_hdl(name='1.json'):\n# f = open(name)\n# for line in f:\n# print(line)\n\n\ndef read_content(filename):\n \"\"\"\n 从filename读取数据\n :param filename:\n :return:\n \"\"\"\n result = ''\n f = open(filename)\n for line in f:\n result += line\n f.close()\n return result\n\n\ndef find_mp3_link(content):\n \"\"\"\n 从content里面找到mp3链接\n :param content:\n :return:\n \"\"\"\n json_data = json.loads(content)\n print(json_data)\n res = []\n for item in json_data:\n res.append(item['mp3'])\n return res # http://luoo-mp3.kssws.ks-cdn.com/low/luoo/radio1/1.mp3\n\n\ndef store_mp3(mp3_links):\n \"\"\"\n 根据mp3链接下载mp3文件,然后存储到本地\n :param mp3_link:\n :return:\n \"\"\"\n for link in mp3_links:\n res = urllib.request.urlopen(link).read()\n f = open(link.split('/')[-1], 'wb')\n f.write(res)\n f.close()\n print('{mp3} download success.'.format(mp3=link.split('/')[-1]))\n\n\nif __name__ == '__main__':\n content = read_content('1.json')\n mp3_links = find_mp3_link(content)\n store_mp3(mp3_links)\n" }, { "alpha_fraction": 0.5677965879440308, "alphanum_fraction": 0.5932203531265259, "avg_line_length": 11.88888931274414, "blob_id": "3fa658fd90d8baeef7bb2108dd964ec8e54f0c11", "content_id": "63349c5bee852fbdc6d92bb0b7e0c0dce1105f9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 212, "license_type": "no_license", "max_line_length": 32, "num_lines": 9, "path": "/start/2_1/2_1.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\n\"\"\"\n2.1 设计程序流程\n设计程序-写代码-更正语法错误-测试程序-更正逻辑错误-继续循环\n\n流程图的概念,稍后搜索学习。\n\"\"\"\n\n\n" }, { "alpha_fraction": 0.6026490330696106, "alphanum_fraction": 0.6622516512870789, "avg_line_length": 29.200000762939453, "blob_id": "825c8bc9ae62174fe5942e5474c3d4f1ccd124d3", "content_id": "b21f072e1ae9d83ee04b9c9fa7ff5ad46baf1048", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 151, "license_type": "no_license", "max_line_length": 48, "num_lines": 5, "path": "/global/no_formatting.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\namount_due = 5000.0\nmonthly_payment = amount_due / 12.0\nprint('The monthly payment is', monthly_payment)\n" }, { "alpha_fraction": 0.6339869499206543, "alphanum_fraction": 0.6405228972434998, "avg_line_length": 15.777777671813965, "blob_id": "567a525e9df6dac45371f3db41dd1f2ecb4b1688", "content_id": "0b4118aa24de49b5b2ac5bbd356058e0273a4456", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 153, "license_type": "no_license", "max_line_length": 38, "num_lines": 9, "path": "/byte/mymodule_demo.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8-*-\n__author__ = 'manman'\n\n# Filename: mymodule_demo.py\n\nimport mymodule\n\nmymodule.say_hi()\nprint('Version', mymodule.__version__)\n\n\n" }, { "alpha_fraction": 0.6245614290237427, "alphanum_fraction": 0.6561403274536133, "avg_line_length": 39.71428680419922, "blob_id": "665aa277c47d3a05c5bc3b3a68c18e5cd6816250", "content_id": "14e73f9e8c4138d2b4f8a45295de38c2d30c8e79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 285, "license_type": "no_license", "max_line_length": 53, "num_lines": 7, "path": "/global/test_score_average.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\ntest1 = float(input('Enter the first test score: '))\ntest2 = float(input('Enter the second test score: '))\ntest3 = float(input('Enter the third test score: '))\naverage = (test1 + test2 + test3) / 3.0\nprint('The average score is', average)\n" }, { "alpha_fraction": 0.45362135767936707, "alphanum_fraction": 0.5209656953811646, "avg_line_length": 18.649999618530273, "blob_id": "ee402d394bef2a350e6ac811169e161c8d1265cf", "content_id": "8b38e2dbf1db91b600770da489f5c5ee866a5dfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 787, "license_type": "no_license", "max_line_length": 53, "num_lines": 40, "path": "/byte/func_key.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8-*-\n__author__ = 'manman'\n\n\ndef func(a, b=5, c=10):\n print 'a is', a, 'b is', b, 'c is', c\n\n\nfunc(3, 7)\nfunc(25, c=24)\nfunc(c=50, a=100)\n\nfunc(a=3)\n\n\ndef show_info(name, age=20, *args, **kwargs):\n \"\"\"\n show student's info\n :param name: student's name\n :param age: student's age\n :param score: student's score\n :return: nothing\n \"\"\"\n print name,\n print age,\n print args,\n print kwargs\n\nif __name__ == '__main__':\n show_info('zhuzai')\n print '-' * 40\n show_info('zhuzai', 10)\n print '-' * 40\n show_info('zhuzai', age=11)\n print '-' * 40\n show_info('zhuzai', 12, 13, 14)\n print '-' * 40\n show_info('zhuzai', 15, *(16, 17), score=100)\n print '-' * 40\n show_info('zhuzai', 18, *(19, ), **{'score': 20})\n\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.561188817024231, "avg_line_length": 21.8799991607666, "blob_id": "f7b6cd9e93623b16fef59d1228739d8c412abfe2", "content_id": "890184aa1ff8a44d91cf6879fa93954f63592d76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 572, "license_type": "no_license", "max_line_length": 68, "num_lines": 25, "path": "/other/yields/yielding.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\n\ndef pydanny_selected_numbers():\n # If you multiple 9 by any other number you can easily play with\n # numbers to get back to 9.\n # Ex: 2 * 9 = 18. 1 + 8 = 9\n # Ex: 15 * 9 = 135. 1 + 3 + 5 = 9\n # See https://en.wikipedia.org/wiki/Digital_root\n yield 9\n\n # A pretty prime.\n yield 31\n\n # What's 6 * 7?\n yield 42\n\n # The string representation of my first date with Audrey Roy\n yield \"2010/02/20\"\n\n\nif __name__ == '__main__':\n for item in pydanny_selected_numbers():\n print item\n" }, { "alpha_fraction": 0.5547945499420166, "alphanum_fraction": 0.6301369667053223, "avg_line_length": 19.85714340209961, "blob_id": "61f7650671d915d886c25eea53f0a2a9d9f75f03", "content_id": "e72d785304231f862eb24830ee52b4a6a85ddd09", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 160, "license_type": "no_license", "max_line_length": 30, "num_lines": 7, "path": "/start/2_2/output.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\n# Program 2-1 练习单引号使用\nprint('Kate Austen')\nprint('123 Full Circle Drive')\nprint('Asheville, NC 28899')\n" }, { "alpha_fraction": 0.6790123581886292, "alphanum_fraction": 0.6954732537269592, "avg_line_length": 39.5, "blob_id": "4e5848d71e8cf651addc87d66c434fc074661c16", "content_id": "78546dda36197ffa4639a03b332d7744180e5282", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 486, "license_type": "no_license", "max_line_length": 73, "num_lines": 12, "path": "/global/temperature.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\nmax_temp = 102.5\ntemperature = float(input(\"Enter the substance's Celsius temperature: \"))\nwhile temperature > max_temp:\n print('The temperature is too high.')\n print('Turn the thermostat down and wait')\n print('5 minutes.Then take the temperature')\n print('again and enter it.')\n temperature = float(input('Enter the new Celsius temperature:'))\nprint('The temperature is acceptable.')\nprint('Check it again in 15 minutes.')\n" }, { "alpha_fraction": 0.45055556297302246, "alphanum_fraction": 0.504444420337677, "avg_line_length": 28.032258987426758, "blob_id": "73a26f5473e873c3df1d8fcd615095210ff12dbe", "content_id": "10f4fbd77bff1d1d6599ad62997e2820119c3461", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2404, "license_type": "no_license", "max_line_length": 103, "num_lines": 62, "path": "/other/alabo.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\n\"\"\"\nhttp://www.cnblogs.com/xiongqiangcs/p/3416072.html\n\"\"\"\n\nunitArab = (2, 3, 4, 5, 9)\nunitStr = u'十百千万亿'\nunitStr = u'拾佰仟万亿'\n# 单位字典unitDic,例如(2,'十')表示给定的字符是两位数,那么返回的结果里面定会包含'十'.3,4,5,9以此类推.\nunitDic = dict(zip(unitArab, unitStr))\n\nnumArab = u'0123456789'\nnumStr = u'零一二三四五六七八九'\nnumStr = u'零壹贰叁肆伍陆柒捌玖'\n# 数值字典numDic,和阿拉伯数字是简单的一一对应关系\nnumDic = dict(zip(numArab, numStr))\n\n\ndef chn_number(s):\n def wrapper(v):\n \"\"\"\n 针对多位连续0的简写规则设计的函数\n 例如\"壹佰零零\"会变为\"壹佰\",\"壹仟零零壹\"会变为\"壹仟零壹\"\n \"\"\"\n if u'零零' in v:\n return wrapper(v.replace(u'零零', u'零'))\n return v[:-1] if v[-1] == u'零' else v\n\n def recur(s, bit):\n \"\"\"\n 此函数接收2个参数:\n 1.纯数字字符串\n 2.此字符串的长度,相当于位数\n \"\"\"\n # 如果是一位数,则直接按numDic返回对应汉字\n if bit == 1:\n return numDic[s]\n # 否则,且第一个字符是0,那么省略\"单位\"字符,返回\"零\"和剩余字符的递归字符串\n if s[0] == u'0':\n return wrapper(u'%s%s' % (u'零', recur(s[1:], bit - 1)))\n # 否则,如果是2,3,4,5,9位数,那么返回最高位数的字符串\"数值\"+\"单位\"+\"剩余字符的递归字符串\"\n if bit < 6 or bit == 9:\n return wrapper(u'%s%s%s' % (numDic[s[0]], unitDic[bit], recur(s[1:], bit - 1)))\n # 否则,如果是6,7,8位数,那么用\"万\"将字符串从万位数划分为2个部分.\n # 例如123456就变成:12+\"万\"+3456,再对两个部分进行递归.\n if bit < 9:\n return u'%s%s%s' % (recur(s[:-4], bit - 4), u\"万\", recur(s[-4:], 4))\n # 否则(即10位数及以上),用\"亿\"仿照上面的做法进行划分.\n if bit > 9:\n return u'%s%s%s' % (recur(s[:-8], bit - 8), u\"亿\", recur(s[-8:], 8))\n\n return recur(s, len(s))\n\n\nif __name__ == '__main__':\n for i in range(18):\n v1 = '9' + '0' * (i + 1)\n v2 = '9' + '0' * i + '9'\n v3 = '1' * (i + 2)\n print ('%s->%s\\n%s->%s\\n%s->%s' % (v1, chn_number(v1), v2, chn_number(v2), v3, chn_number(v3)))\n" }, { "alpha_fraction": 0.5866666436195374, "alphanum_fraction": 0.6079999804496765, "avg_line_length": 30.25, "blob_id": "849f04cde40ebf98a88c101b203446e2e0984081", "content_id": "55990acd03d1c211c159f78f595ba08ff1ab3eb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 375, "license_type": "no_license", "max_line_length": 54, "num_lines": 12, "path": "/global/loan_qualifier2.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\nmin_salary = 30000.0\nmin_years = 2\n\nsalary = float(input('Enter your annual salary:'))\nyears_on_job = int(input('Enter the number of ' +\n 'years employed:'))\nif salary >= min_salary and years_on_job >= min_years:\n print('You qualify for the loan.')\nelse:\n print('You do not qualify for this loan.')\n" }, { "alpha_fraction": 0.5249999761581421, "alphanum_fraction": 0.5550000071525574, "avg_line_length": 15.666666984558105, "blob_id": "f8eede38d76709752d258b9f06cf180626c1c706", "content_id": "792d087c442978b313d06c487c02e8541098b2c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "no_license", "max_line_length": 33, "num_lines": 12, "path": "/byte/for..in.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8-*-\n__author__ = 'manman'\n\nfor i in range(1, 5, 2):\n print(i)\nelse:\n print('The for loop is over')\n\nfor i in range(1, 5):\n print(i)\nelse:\n print('The for loop is over')\n" }, { "alpha_fraction": 0.5446622967720032, "alphanum_fraction": 0.5882353186607361, "avg_line_length": 20.85714340209961, "blob_id": "13e01e6ff4e9f1eea6b209c1d881b40847438ad2", "content_id": "c11cee352665bf2d1a0efde24af2bd627f2ea64a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 601, "license_type": "no_license", "max_line_length": 64, "num_lines": 21, "path": "/learn/001.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n\"\"\"\n编写程序,判断给定的某个年份是否是闰年。\n闰年的判断规则如下:\n(1)若某个年份能被4整除但不能被100整除,则是闰年。\n(2)若某个年份能被400整除,则也是闰年。\n\"\"\"\n\n\ndef leap_year(year):\n if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:\n print('{year} year is leap year!'.format(year=year))\n else:\n print('{year} year is not leap year!'.format(year=year))\n\n\nif __name__ == '__main__':\n year = int(input(\"Please input some years: \"))\n leap_year(year)\n" }, { "alpha_fraction": 0.5324675440788269, "alphanum_fraction": 0.6969696879386902, "avg_line_length": 32, "blob_id": "dd251eb2a7f69481949c916d50dbd48dd470ccf1", "content_id": "89524aa87784d93f802f5d8407537876cd055880", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 255, "license_type": "no_license", "max_line_length": 155, "num_lines": 7, "path": "/learn/012.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\n\"\"\"\n<script type=\"text/javascript\">var fish=1734+473;var frog=435+2716^fish;var seal=168+8742^frog;var chick=7275+2941^seal;var snake=3820+4023^chick;</script>\n以上script脚本提取变量为字典。\n\"\"\"\n" }, { "alpha_fraction": 0.48051947355270386, "alphanum_fraction": 0.5051947832107544, "avg_line_length": 21.647058486938477, "blob_id": "2c4194df4cffe724328f7c79747831836b15d28a", "content_id": "8e97849ac233533344e4ebe60edb8fad29a2ca0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 770, "license_type": "no_license", "max_line_length": 95, "num_lines": 34, "path": "/other/proxy.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport urllib\nfrom lxml import etree\n\n__author__ = 'florije'\n\n\ndef get_html(url):\n page = urllib.urlopen(url)\n html = page.read()\n return html\n\n\ndef get_key(html):\n page = etree.HTML(html.lower().decode('gb2312'))\n trs = page.xpath(u\"//td[@valign='top']/font[@size='2']//table[contains(@width,'100%')]/tr\")\n i = 1\n size = len(trs)\n while (i < size):\n ip = trs[i].xpath(\"./td[2]/text()\")[0]\n port = trs[i].xpath(\"./td[3]/text()\")[0]\n i = i + 1\n print ip + \" \" + port\n\n\nif __name__ == '__main__':\n i = 1\n total_page = 12\n while i < total_page:\n addr = \"http://www.proxy.com.ru/list_\" + str(i) + \".html\"\n html = get_html(addr)\n key = get_key(html)\n i += 1\n" }, { "alpha_fraction": 0.6184971332550049, "alphanum_fraction": 0.6705202460289001, "avg_line_length": 23.714284896850586, "blob_id": "c24750d6d0036d6b92d6e5512ef4b8e77d507bb3", "content_id": "9b79180f2bfde87be7214d450a7c9f473b59b5fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 173, "license_type": "no_license", "max_line_length": 51, "num_lines": 7, "path": "/global/comment1.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n# this program displays a person's name and address\nprint('Kate')\nprint('123 Full circle Drive')\nprint('Asheville, NC 28899')\n" }, { "alpha_fraction": 0.6022099256515503, "alphanum_fraction": 0.6408839821815491, "avg_line_length": 29.16666603088379, "blob_id": "e17dcc733700c1e0926acdb0bc526001963a49a9", "content_id": "67ea3a2115a027c747a435147ed68f8c50a74fb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 362, "license_type": "no_license", "max_line_length": 52, "num_lines": 12, "path": "/global/speed_converter.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\nstart_speed = 60 # Starting speed\nend_speed = 131 # Ending speed\nincrement = 10 # Speed increment\nconversion_factor = 0.6214 # Conversation factor\nprint('KPH\\tMPH')\nprint('--------')\n\nfor kph in range(start_speed, end_speed, increment):\n mph = kph * conversion_factor\n print(kph, '\\t', format(mph, '.1f'))\n" }, { "alpha_fraction": 0.5034482479095459, "alphanum_fraction": 0.5310344696044922, "avg_line_length": 15.11111068725586, "blob_id": "8acfc9935b6aff8552ecdf1cdc2236a5583ebc0b", "content_id": "6746662e349b274e4c9800bbc3af5dfdfc0e77a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 145, "license_type": "no_license", "max_line_length": 24, "num_lines": 9, "path": "/other/for.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\na = [1, 2, 3]\nb = [item for item in a]\ntmp = []\nfor item in a:\n tmp.append(item)\nprint b, tmp\n" }, { "alpha_fraction": 0.6222222447395325, "alphanum_fraction": 0.6792592406272888, "avg_line_length": 18.852941513061523, "blob_id": "0471f9a5e03e41e6e9b24557dca0fb9eafc20a78", "content_id": "e768608bc203f0a0e840be2370c2b9614911d63e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1603, "license_type": "no_license", "max_line_length": 205, "num_lines": 68, "path": "/other/crys.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\nfrom Crypto.Hash import SHA512\n\nimport cgi, base64\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Signature import PKCS1_v1_5\nfrom Crypto.Hash import SHA\n\nh = SHA512.new()\n\nh.update(b'Hello')\nprint h.hexdigest()\n\n\n\"\"\"\n先生成rsa的公私钥:\n打开控制台,输入 openssl\n再输入 genrsa -out private.pem 1024 来生成私钥\n接着输入 rsa -in private.pem -pubout -out public.pem 来生成公钥\n\"\"\"\n\n# 私钥文件\npriKey = \"\"\"-----BEGIN RSA PRIVATE KEY-----\nMIICXgIBAAKBgQD4c1uYjQfxsxD/RWLWYPKUN1QPWIp1Vu/K3Do6DFh2tyhnN8PD\niMzNoIKh5f6QtRU45uHzQtw+WSVCks6hJvAWUAmPZEk7T0Wfl9yny4vJkkbgA5/E\nUIVvHDkyLC5qcDly0n/wC/SF+NC4QGi+N8MTThseMcf06eBpEq2mpXpawwIDAQAB\nAoGBALzvjOJPrZDiabSWYXlBtHd+M9CPtotRF32fSDBInyV4V6NWxup1p7lfrLfN\nnW8SJhdljMJfP/mx9SHRXo0yfTQa/0X/bBF73Q6Bg0kNGA8SSSvrYTeh9SPTqrae\na6R2Y8WEvtcnTa4NE1fNE00kYjSGpC8Iit5dkYTZ5dBY0CjBAkEA//8D0HMnSO1E\niEL0AyZQyAWnkWOTVHBhKz4qGaJBo2tyUt8WcLyxUD2Wi31ni3EdGk1UO+QhRIPC\n6bOkn9TA0QJBAPh0UFkyLG846uTvv5haUG9QfExnLgpeUHotc4u1k6RbiZfHapzt\n8DKByS3+nDGuWD8KCHrgzT5SSpuH1FAgJ1MCQQC8M4plVFNcXPsWRkrIigG3m9ie\nnZsx59C4DuK6p7wj3ZlV7aa8ySx+dljYQiC+tjEUJie4RDZk/Y1tbOGpk6sRAkEA\npc8yJCTI5L0uffTGf82eKnujSHX/kunYeYFFwHJAgwqX69QpAWwFxh85fNmTsdAx\nkniGqkLGlpXitqNSfNrIgwJAJ6crblQCX9M+8QzgeYP3g+/DD6k8t5BPlNcA1IPs\nA2w8mlNwTNuDzKqP17yyBBVivDu0sYYczSiOlvg0xhkLig==\n-----END RSA PRIVATE KEY-----\"\"\"\n\n# 公钥文件\npubKey = \"\"\"-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD4c1uYjQfxsxD/RWLWYPKUN1QP\nWIp1Vu/K3Do6DFh2tyhnN8PDiMzNoIKh5f6QtRU45uHzQtw+WSVCks6hJvAWUAmP\nZEk7T0Wfl9yny4vJkkbgA5/EUIVvHDkyLC5qcDly0n/wC/SF+NC4QGi+N8MTThse\nMcf06eBpEq2mpXpawwIDAQAB\n-----END PUBLIC KEY-----\"\"\"\n\n'''*RSA签名\n* data待签名数据\n* 签名用商户私钥,必须是没有经过pkcs8转换的私钥\n* 最后的签名,需要用base64编码\n* return Sign签名\n'''\n\n\ndef sign(data):\n key = RSA.importKey(priKey)\n h = SHA.new(data)\n signer = PKCS1_v1_5.new(key)\n signature = signer.sign(h)\n return base64.b64encode(signature)\n\n\n'''*RSA验签\n* data待签名数据\n* signature需要验签的签名\n* 验签用支付宝公钥\n* return 验签是否通过 bool值\n'''\n\n\ndef verify(data, signature):\n key = RSA.importKey(pubKey)\n\n h = SHA.new(data)\n verifier = PKCS1_v1_5.new(key)\n if verifier.verify(h, base64.b64decode(signature)):\n return True\n return False\n\n\nraw_data = 'partner=\"2088701924089318\"&seller=\"[email protected]\"&out_trade_no=\"123000\"&subject=\"123456\"&body=\"2010新款NIKE 耐克902第三代板鞋 耐克男女鞋 386201 白红\"&total_fee=\"0.01\"¬ify_url=\"http://notify.java.jpxx.org/index.jsp\"'\nsign_data = sign(raw_data)\nprint \"sign_data: \", sign_data\nprint verify(raw_data, sign_data)\n" }, { "alpha_fraction": 0.4747474789619446, "alphanum_fraction": 0.5288600325584412, "avg_line_length": 21.721311569213867, "blob_id": "766ef6968442e12ba3bf3e4598c4179b3384288a", "content_id": "f298a8bd88058b0bcf986cdd628273d0ab3ef26f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1648, "license_type": "no_license", "max_line_length": 104, "num_lines": 61, "path": "/learn/008.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n\"\"\"\n1.判断用户输入的年月日,然后判断这一天是当年的第几天。\n2.随机生成20个10以内的数字,放入数组中,然后去掉重复的数字。然后打印数组。\n\"\"\"\n\n\n# 根据出生年先判断是平年还是闰年,得出2月份天数,各月份天数相加即可。\n\n\n\n\n# year = int(input(\"请输入年份: \"))\n# march = int(input(\"请输入月份: \"))\n# days = int(input(\"请输入日子: \"))\n# def feb_days():\n# for i in range():\n# if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:\n# xadct.valus({'feb': 28})\n# days = days + xadct.valus()\n# return(days)\n# else:\n# return(days + 1)\n\n\ndef is_leap(year):\n \"\"\"\n 判断是否是瑞年\n :param year:\n :return:\n \"\"\"\n if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:\n return True\n else:\n return False\n\n\ndef print_days_of_year(year, month, day):\n \"\"\"\n 打印当前天是这一年的第几天\n :param year:\n :param month:\n :param day:\n :return:\n \"\"\"\n month_days = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}\n if is_leap(year):\n month_days[2] = 29\n full_month_day_count = 0\n for i in range(1, month):\n full_month_day_count += month_days[i]\n total_days = full_month_day_count + day\n print(total_days)\n\nif __name__ == '__main__':\n year = int(input('Please input year:'))\n month = int(input('Please input month:'))\n day = int(input('Please input day:'))\n print_days_of_year(year, month, day)\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5394088625907898, "avg_line_length": 15.916666984558105, "blob_id": "a2e91837cc8ac6c48bcb760cb7d26bfbd91cd945", "content_id": "0747a1c2c3c0c1d90739c97284ba98380d342ad8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 406, "license_type": "no_license", "max_line_length": 52, "num_lines": 24, "path": "/byte/VarArgs.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8-*-\n__author__ = 'manman'\n\n\ndef total(initial=5, *numbers, **keywords):\n count = initial\n for number in numbers:\n count += number\n for key in keywords:\n count += keywords[key]\n return count\n\n\nprint(total(10, 1, 2, 3, vegetables=50, fruits=100))\n\n\ndef add(a, b, c):\n if a == 1:\n return a + b + c\n else:\n return a * b * c\n\n\nprint add(2, 2, 4)\n" }, { "alpha_fraction": 0.5328947305679321, "alphanum_fraction": 0.5368421077728271, "avg_line_length": 24.33333396911621, "blob_id": "cb0f6fdd6b0cb93cc81db6656054c6f72aec9d41", "content_id": "bca94172ce263c349d8a744389e8a240b8cc57f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 768, "license_type": "no_license", "max_line_length": 72, "num_lines": 30, "path": "/21days/5_4.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\nuser_infos = [{'name': 'john', 'password': '2354kdd', 'usertype': 1},\n {'name': 'kate', 'password': '3574kdd', 'usertype': 2}]\n\n\ndef login(name, password):\n \"\"\"\n 用户登录\n :param name:\n :param password:\n :return:\n \"\"\"\n for user in user_infos:\n if user['name'] == name and user['password'] == password:\n return user['usertype']\n else:\n return None\n\n\nif __name__ == '__main__':\n name = input(\"Please input your name: \")\n password = input(\"Please input your password: \")\n\n res = login(name, password)\n if not res:\n print(\"You have not registered in the system\")\n else:\n print(\"Welcome, your user type is %d\" % res)\n" }, { "alpha_fraction": 0.5372617244720459, "alphanum_fraction": 0.5528596043586731, "avg_line_length": 31.05555534362793, "blob_id": "2698dbcb7b28bfb740bbee7835d790eb9f92e16e", "content_id": "fb074ae509360ac9f23248976a352f1218035943", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 577, "license_type": "no_license", "max_line_length": 50, "num_lines": 18, "path": "/global/loan_qualifier.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\nmin_salary = 30000.0\nmin_years = 2\nsalary = float(input('Enter your annual salary:'))\nyears_on_job = int(input('Enter the number of' +\n 'years employed:'))\nif salary >= min_salary:\n if years_on_job >= min_years:\n print('You quality for the loan.')\n else:\n print('You must have been employed', \\\n 'for at least', min_years, \\\n 'years to qualify.')\nelse:\n print('You must earn at least $', \\\n format(min_salary, ',.2f'), \\\n ' per year to qualify.', sep='')\n" }, { "alpha_fraction": 0.30841121077537537, "alphanum_fraction": 0.41588786244392395, "avg_line_length": 11.529411315917969, "blob_id": "6e2f2468dd4f5dffa7392d34d3860f943a8924e2", "content_id": "96d8ec7f0793b4157caa1443172a086d1ba6ecb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 226, "license_type": "no_license", "max_line_length": 34, "num_lines": 17, "path": "/learn/005.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n\"\"\"\n求 2/1+3/2+5/3+8/5+13/8.....前20项之和?\n\"\"\"\n\na = 1.0\nb = 2.0\nsum = 0\nc = 0\nfor i in range(0, 20):\n sum = sum + b/a\n c = a + b\n a = b\n b = c\n print(sum)\n\n" }, { "alpha_fraction": 0.44170403480529785, "alphanum_fraction": 0.45515695214271545, "avg_line_length": 16.115385055541992, "blob_id": "1495464f0e87c5f1f0bd5102c645b642f21f252a", "content_id": "8777583dafde3ab90d13cc4f9e65a7abf28d30d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 454, "license_type": "no_license", "max_line_length": 34, "num_lines": 26, "path": "/21days/2_1.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\nfirst_name = 'ww'\nlast_name = 'rr'\nprint('I am a teacher', \\\n first_name, \\\n last_name)\n\nprint('a', 'b', 'c', end=';')\nprint('a', 'b', 'c', sep='**')\n\nprint(1, 2, 3, 4, sep='')\nprint('****\\n*\\n****\\n* *\\n****')\nprint('****')\nprint('*')\nprint('* *')\nprint('* *')\n\n\nprint('你好'.encode())\n# print('你好'.decode())\ntest_dict = {'a': 3}\nabc = test_dict.get('b')\nprint('~~~~~~~~')\nprint(abc)\n\n" }, { "alpha_fraction": 0.5248227119445801, "alphanum_fraction": 0.588652491569519, "avg_line_length": 13.100000381469727, "blob_id": "a14abd751bc6762c8a6214c5847816c0798d51e7", "content_id": "e3c61206a7bee7ee0ef82d4e03d174a22794c9d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 155, "license_type": "no_license", "max_line_length": 30, "num_lines": 10, "path": "/start/2_2/double_quotes.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\n\"\"\"\n练习双引号使用\n\"\"\"\n\nprint(\"Kate Austen\")\nprint(\"123 Full Circle Drive\")\nprint(\"Asheville, NC 28899\")\n" }, { "alpha_fraction": 0.6725440621376038, "alphanum_fraction": 0.6801007390022278, "avg_line_length": 18.850000381469727, "blob_id": "122ff76c15fcc46cecc8a4a097d9a01c33d529bf", "content_id": "c36c5ca0be016b8acb2bcfedb42252882791e39c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 397, "license_type": "no_license", "max_line_length": 49, "num_lines": 20, "path": "/byte/chapter_10_5.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8-*-\n__author__ = 'manman'\n\nprint 'Simple Assignment'\nshoplist = ['apple', 'mango', 'carrot', 'banana']\n\nmylist = shoplist\n\ndel shoplist[0]\n\nprint 'shoplist is', shoplist, id(shoplist)\nprint 'mylist is', mylist, id(mylist)\n\nprint 'Copy by making a full slice'\nmylist = shoplist[:]\n\ndel mylist[0]\n\nprint 'shoplist is', shoplist, id(shoplist)\nprint 'mylist is', mylist, id(mylist)\n" }, { "alpha_fraction": 0.5506607890129089, "alphanum_fraction": 0.592510998249054, "avg_line_length": 25.705883026123047, "blob_id": "1ecf934b846a34ca56472786d8f15e6c45be4c87", "content_id": "683904123baa7d94050770d28c7cd9980e67f590", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 454, "license_type": "no_license", "max_line_length": 58, "num_lines": 17, "path": "/byte/format.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8-*-\n__author__ = 'manman'\n\n# !/usr/bin/python\n# Filename: str_format.py\nage = 25\nname = 'Swaroop'\nprint (' {0} is {1} years old'.format(name, age))\nprint('Why is {0} playing with that python?'.format(name))\n\nprint('{:3}'.format('hello'))\nprint('{:<11}'.format('hello'))\nprint('{:>11}'.format('hello'))\nprint('{:>15}'.format('huaibizai'))\nprint('{:^11}'.format('hello'))\nprint('{:^11}'.format('bizi'))\nprint ('{:_>11}'.format('hello'))\n" }, { "alpha_fraction": 0.5332852005958557, "alphanum_fraction": 0.5866858959197998, "avg_line_length": 36.707481384277344, "blob_id": "1b51460136dde7897fb1dec4f86752a0ce66321a", "content_id": "795cb3ae6c730b1a567155719a872a7ad134a81e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5547, "license_type": "no_license", "max_line_length": 163, "num_lines": 147, "path": "/other/jiandan/proxy.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\nimport re\nimport json\nimport time\nimport random\nimport requests\nimport datetime\nimport requesocks\nfrom bs4 import BeautifulSoup\n\n\ndef test_url_available(url):\n proxies = {\n 'http': 'http://{url}'.format(url=url),\n # 'http': 'http://222.88.142.51:8000',\n }\n try:\n res = requests.get('http://www.luoo.net/', proxies=proxies)\n except Exception as e:\n return False\n return res.status_code == 200\n\navailable_url = 'http://pachong.org/test/single/id/{id}'\n\nproxies = {\n \"http\": \"socks5://127.0.0.1:1080\",\n \"https\": \"socks5://127.0.0.1:1080\"\n}\nuser_agent = \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36\"\nheaders = {\n \"User-Agent\": user_agent,\n \"Host\": \"pachong.org\",\n \"Referer\": \"http://pachong.org/\"\n}\n\n\ndef get_var_list(page_content):\n # res = 'var chick=958+2894;var bee=6981+6600^chick;var cock=8243+890^bee;var calf=8872+4397^cock;var fish=3571+2760^calf;'\n # var dog=7544+4134;var worm=3554+5240^dog;var goat=1408+5265^worm;var cat=1981+8542^goat;var fish=7827+5906^cat;\n # print page_content\n pattern = re.compile(r'var \\w+=\\S+;var \\w+=\\S+;var \\w+=\\S+;var \\w+=\\S+;var \\w+=\\S+;')\n match = pattern.search(page_content)\n if match:\n print match.group()\n content = match.group()[:-1]\n var_list = content.split(';') # ['var chick=958+2894']\n\n map_dict = {}\n\n # one\n raw_one = var_list[0] # 'var chick=958+2894'\n left_raw_one, right_raw_one = raw_one.split('=')[0], raw_one.split('=')[1]\n ont_var = left_raw_one.split(' ')[1]\n one_value = sum([int(value) for value in right_raw_one.split('+')])\n print ont_var, one_value\n map_dict[ont_var] = one_value\n\n # two\n raw_two = var_list[1] # 'var bee=6981+6600^chick'\n left_raw_two, right_raw_two = raw_two.split('=')[0], raw_two.split('=')[1]\n two_var = left_raw_two.split(' ')[1]\n two_value = int(right_raw_two.split('+')[0]) + int(right_raw_two.split('+')[1].split('^')[0]) ^ map_dict.get(right_raw_two.split('+')[1].split('^')[1])\n print two_var, two_value\n map_dict[two_var] = two_value\n\n # three\n raw_three = var_list[2] # 'var cock=8243+890^bee'\n left_raw_three, right_raw_three = raw_three.split('=')[0], raw_three.split('=')[1]\n three_var = left_raw_three.split(' ')[1]\n three_value = int(right_raw_three.split('+')[0]) + int(right_raw_three.split('+')[1].split('^')[0]) ^ map_dict.get(right_raw_three.split('+')[1].split('^')[1])\n print three_var, three_value\n map_dict[three_var] = three_value\n\n # four\n raw_four = var_list[3] # var calf=8872+4397^cock;\n left_raw_four, right_raw_four = raw_four.split('=')[0], raw_four.split('=')[1]\n four_var = left_raw_four.split(' ')[1]\n four_value = int(right_raw_four.split('+')[0]) + int(right_raw_four.split('+')[1].split('^')[0]) ^ map_dict.get(right_raw_four.split('^')[1])\n print four_var, four_value\n map_dict[four_var] = four_value\n\n # five\n raw_five = var_list[4] # 'var fish=3571+2760^calf'\n left_raw_five, right_raw_five = raw_five.split('=')[0], raw_five.split('=')[1]\n five_var = left_raw_five.split(' ')[1]\n five_value = int(right_raw_five.split('+')[0]) + int(right_raw_five.split('+')[1].split('^')[0]) ^ map_dict.get(right_raw_five.split('^')[1])\n print five_var, five_value\n map_dict[five_var] = five_value\n\n return map_dict\n\n\ndef get_urls():\n\n session = requesocks.Session(headers=headers, proxies=proxies)\n page_content = session.get('http://pachong.org/').content\n # print(page_content.content)\n\n soup = BeautifulSoup(page_content)\n # print soup.find(\"table\", {\"class\": \"tb\"})\n # var chick=958+2894;var bee=6981+6600^chick;var cock=8243+890^bee;var calf=8872+4397^cock;var fish=3571+2760^calf;\n\n map_dict = get_var_list(page_content)\n\n table = soup.find('table', attrs={'class': 'tb'})\n table_body = table.find('tbody')\n rows = table_body.find_all('tr')\n data = []\n for row in rows:\n cols = row.find_all('td')\n\n # url_res = session.get(available_url.format(id=cols[6].find('a').get('name'))).content\n # json_url_res = json.loads(url_res)\n json_url_res = {'ret': 0, 'data': {'all': 0}}\n if json_url_res.get('ret') == 0:\n raw_port = cols[2].text.strip() # document.write((11476^fish)+298);\n port = raw_port[raw_port.index('(') + 1: raw_port.index(';') - 1] # (11476^fish)+298\n\n port = (int(port.split('^')[0][1:]) ^ map_dict.get(port[port.index('^') + 1: port.index(')')])) + int(port.split('+')[1])\n\n tmp = {'id': cols[0].text.strip(), 'ip': cols[1].text.strip(), 'port': port,\n 'url_id': cols[6].find('a').get('name'), 'con_time': json_url_res.get('data').get('all'), 'region': cols[3].text.strip()}\n data.append(tmp)\n print(tmp)\n # time.sleep(random.randint(3, 7))\n\n # cols = [ele.text.strip() for ele in row.find_all('td')]\n # data.append([ele for ele in cols if ele])\n\n return data\n\n\ndef save_data(json_data):\n with open('data_{date}.json'.format(date=datetime.datetime.now().strftime('%Y%m%d%H%M%S')), mode='w') as f:\n f.write(json_data)\n\n\nif __name__ == '__main__':\n res = get_urls()\n data = []\n for item in res:\n if u'调试' not in item.get('region'):\n if test_url_available('{ip}:{port}'.format(ip=item.get('ip'), port=item.get('port'))):\n data.append(item)\n save_data(json.dumps(data))\n" }, { "alpha_fraction": 0.6814814805984497, "alphanum_fraction": 0.7074074149131775, "avg_line_length": 21.5, "blob_id": "3475dc851db419be48323092d91ffa1056471a8e", "content_id": "dec90e351a9c4e67474f9e16c6753e5002be691c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 270, "license_type": "no_license", "max_line_length": 49, "num_lines": 12, "path": "/global/variable_demo2.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n# Create two variables: top_speed and distance.\ntop_speed = 160\ndistance = 300\n\n# Display the values referenced by the variables.\nprint('The top speed is')\nprint(top_speed)\nprint('The distance traveled is')\nprint(distance)\n" }, { "alpha_fraction": 0.47442325949668884, "alphanum_fraction": 0.5005015134811401, "avg_line_length": 27.285715103149414, "blob_id": "6856fa9b549a68dfdaf1691f2f94976414e1c2bc", "content_id": "6cc9349f82d3854ba6812315752a56f9a2c34e61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1057, "license_type": "no_license", "max_line_length": 90, "num_lines": 35, "path": "/21days/4_5.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\nmyseq = \"\"\"[a:1, b:2, c:3]\n[a:3, b:3, c:8]\n[a:7, c:2, m:7, r:4]\n[a:2, c:4, m:6, r:4]\n[a:3, b:2, c:7, o:5]\"\"\"\n\nres_keys = []\nres_strs = []\n\n# res = [item[1: len(item) - 1].split(',') for item in myseq.split('\\n')]\n# print res\n\nfor item in myseq.split('\\n'):\n # item_list = item[1: len(item) - 1].split(',')\n # print item_list\n # 获取key\n item_keys = [raw_item.split(':')[0] for raw_item in item[1: len(item) - 1].split(',')]\n # print item_keys\n # 判断是否有key的列表,然后决定是否放进去。\n for key_list in res_keys: # 已存['a', 'b', 'c']\n # ['a', 'b', 'c'] 比较 ['a', 'b', 'c']是否相等。\n # if key_list == item_keys:\n # break\n list_r = [a for a in item_keys if a in key_list]\n long_len = len(item_keys) if len(item_keys) >= len(key_list) else len(key_list)\n if len(list_r) >= long_len:\n break\n else:\n res_keys.append(item_keys)\n res_strs.append(item)\n\nprint(', '.join(res_strs))\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.3677419424057007, "alphanum_fraction": 0.448387086391449, "avg_line_length": 17.117647171020508, "blob_id": "c376b3d7b30677cf4933ec42e9001f243bcff027", "content_id": "d6535b49d685deecbd012f31efbe865427c09b05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 332, "license_type": "no_license", "max_line_length": 40, "num_lines": 17, "path": "/21days/3_3.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n#.adct = {'a': 1, 'b': 2, 'c': 3}\n#.print(adct)\n\n# adct = {'a': 1, 'b': 2}\n# adct.update({'c': 3})\n# print(adct)\n\n\n# d1,d2,d3是三种不同的表达形式,\nd1 = dict((['a', 1], ['b', 2],['c', 3]))\nd2 = dict(a=1, b=2,c=3)\nd3 = {'a': 1, 'b': 2, 'c': 3}\nprint(d1)\nprint(d2)\nprint(d3)\n\n\n" }, { "alpha_fraction": 0.4548577070236206, "alphanum_fraction": 0.4818449318408966, "avg_line_length": 28.08571434020996, "blob_id": "fef5e71937a702cbdeade6375f1c62d66fd94db7", "content_id": "97968817ebe2aba90d466f7fb241245091e1301f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2146, "license_type": "no_license", "max_line_length": 107, "num_lines": 70, "path": "/global/0.0shuzizhuanhuan.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n\"\"\"\n壹、贰、叁、肆、伍、陆、柒、捌、玖、拾、佰、仟、万\n11111\n壹万壹仟壹佰壹拾壹\n\"\"\"\n\n\nmap_value_dict = {'0': '零', '1': '壹', '2': '贰', '3': '叁', '4': '肆', '5': '伍', '6': '陆', '7': '柒', '8': '捌',\n '9': '玖'}\nmap_unit_dict = {2: '拾', 3: '佰', 4: '仟', 5: '万'}\n\nresult = []\n\n\ndef convert_num_str(num):\n str_value = str(num)\n print(str_value)\n if len(str_value) > 5:\n raise Exception('Too long value!!!')\n if 5 >= len(str_value) > 4:\n pop_value = str_value[0:1]\n if int(pop_value) == 0:\n pass\n else:\n result.append(map_value_dict[pop_value])\n result.append(map_unit_dict[len(str_value)])\n str_value = str_value[1:]\n if 4 >= len(str_value) > 3:\n pop_value = str_value[0:1]\n if int(pop_value) == 0:\n result.append('零')\n else:\n result.append(map_value_dict[pop_value])\n result.append(map_unit_dict[len(str_value)])\n str_value = str_value[1:]\n if 3 >= len(str_value) > 2:\n pop_value = str_value[0:1]\n if int(pop_value) == 0:\n if not result[-1] == '零':\n result.append('零')\n else:\n result.append(map_value_dict[pop_value])\n result.append(map_unit_dict[len(str_value)])\n str_value = str_value[1:]\n if 2 >= len(str_value) > 1:\n pop_value = str_value[0:1]\n if int(pop_value) == 0:\n if not result[-1] == '零':\n result.append('零')\n else:\n result.append(map_value_dict[pop_value])\n result.append(map_unit_dict[len(str_value)])\n str_value = str_value[1:]\n if 1 >= len(str_value):\n pop_value = str_value[0:1]\n if int(pop_value) == 0:\n # result.append('零')\n pass\n else:\n result.append(map_value_dict[pop_value])\n # result.append(map_unit_dict[len(str_value)])\n\n\nif __name__ == '__main__':\n value = 9099\n convert_num_str(value)\n print(''.join(result))\n\n\n" }, { "alpha_fraction": 0.6072289347648621, "alphanum_fraction": 0.6192771196365356, "avg_line_length": 19.75, "blob_id": "30f8d6ca231067891567f74c17cc952023132794", "content_id": "166a49be1b7a3da7de0fbb17a85943cff1a38ce5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 415, "license_type": "no_license", "max_line_length": 91, "num_lines": 20, "path": "/other/functions.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\nfunction_class = (lambda x: x).__class__\nprint(function_class)\n\n\ndef foo():\n print(\"hello world.\")\n\n\ndef myprint(*args, **kwargs):\n print(\"this is my print.\")\n print(*args, **kwargs)\n\nnewfunc1 = function_class(foo.__code__, {'print': myprint})\nnewfunc1()\n\nnewfunc2 = function_class(compile(\"print('asdf')\", \"filename\", \"single\"), {'print': print})\nnewfunc2()\n" }, { "alpha_fraction": 0.6651785969734192, "alphanum_fraction": 0.6785714030265808, "avg_line_length": 31, "blob_id": "f3ca1497fa4a0f4cf37c76ee21132a5198ec3b28", "content_id": "7f6f3fe8f5739a60ced4a49ee4b53b8d47420fb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 224, "license_type": "no_license", "max_line_length": 66, "num_lines": 7, "path": "/global/sale_price.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\noriginal_price = float(input(\"Enter the item's original price: \"))\ndiscount = original_price * 0.2\nsale_price = original_price - discount\nprint('The sale price is', sale_price)\n" }, { "alpha_fraction": 0.534246563911438, "alphanum_fraction": 0.5388127565383911, "avg_line_length": 14.642857551574707, "blob_id": "9221c865c666f01df8082c4515ef61b05ab87244", "content_id": "8e737310ee8d3debf17be00557d3ef58b07597da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "no_license", "max_line_length": 44, "num_lines": 14, "path": "/byte/chapter_12_3.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8-*-\n__author__ = 'manman'\n\n\nclass Person:\n def __init__(self, name):\n self.name = name\n\n def say_hi(self):\n print 'Hello, my name is', self.name\n\n\np = Person('Swaroop')\np.say_hi()\n" }, { "alpha_fraction": 0.5889570713043213, "alphanum_fraction": 0.6380367875099182, "avg_line_length": 17, "blob_id": "2195084e22324c9a2d568247b74074924c686cb1", "content_id": "91c1e77ebe3faa11c2ba202d95d9ad670af02d27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 163, "license_type": "no_license", "max_line_length": 42, "num_lines": 9, "path": "/global/variable_demo3.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\nroom =1002\nprint('I am staying in room number')\nprint(room)\n\nroom = 503\nprint('I am staying in room number', room)\n\n" }, { "alpha_fraction": 0.6417657136917114, "alphanum_fraction": 0.6434634923934937, "avg_line_length": 29.947368621826172, "blob_id": "ba0926e642434eacf726959964d6d5fed44f6b20", "content_id": "852bda0dceaa836925a2c4b9fa04afc6bc29348f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 589, "license_type": "no_license", "max_line_length": 67, "num_lines": 19, "path": "/21days/3_4.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\naint = int(input('please input a int:'))\nbint = int(input('please input a int:'))\ncint = int(input('please input a int:'))\ndint = int(input('please input a int:'))\nfint = int(input('please input a int:'))\ngint = int(input('please input a int:'))\nhint = int(input('please input a int:'))\nlint = int(input('please input a int:'))\nmint = int(input('please input a int:'))\nnint = int(input('please input a int:'))\n\nalst = [aint, bint, cint, dint, fint, gint, hint, lint, mint, nint]\n\nprint(sum(alst))\nprint(len(alst))\nprint(sum(alst)/len(alst))\n\n" }, { "alpha_fraction": 0.671515166759491, "alphanum_fraction": 0.71757572889328, "avg_line_length": 22.600000381469727, "blob_id": "877e8e928e551697a8acf9e8c55238c9525898cb", "content_id": "49e67338411e303f748d33c0b06a13c38f0832c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 887, "license_type": "no_license", "max_line_length": 51, "num_lines": 35, "path": "/other/aes_js_py/encrypt.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\nimport base64\n\nfrom Crypto.Cipher import AES\nfrom pkcs7 import PKCS7Encoder\n\n# 使用256位的AES,Python会根据传入的Key长度自动选择,长度为16时使用128位的AES\nkey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'\nmode = AES.MODE_CBC\niv = '1234567812345678' # AES的CBC模式使用IV\n\nencoder = PKCS7Encoder()\ntext = \"This is for test.\"\n\ndef encrypt(data):\n encryptor = AES.new(key, AES.MODE_CBC, iv)\n padded_text = encoder.encode(data)\n encrypted_data = encryptor.encrypt(padded_text)\n\n return base64.b64encode(encrypted_data)\n\ndef decrypt(data):\n cipher = base64.b64decode(data)\n decryptor = AES.new(key, AES.MODE_CBC, iv)\n plain = decryptor.decrypt(cipher)\n\n return encoder.decode(plain)\n\nencrypted_text = encrypt(text)\nclean_text = decrypt(encrypted_text)\n\nprint \"encrypted_text:\", encrypted_text\nprint \"clean_text: \", clean_text" }, { "alpha_fraction": 0.6178707480430603, "alphanum_fraction": 0.6349809765815735, "avg_line_length": 15.967741966247559, "blob_id": "7678447dd6663c72ad93a3f21e516762966f20ad", "content_id": "4d6bfc5bf22d29c41a16c0eff66bef6ad7934fbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 566, "license_type": "no_license", "max_line_length": 48, "num_lines": 31, "path": "/21days/4_4.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n'''\n1.输入20个数\n2.收入一个列表\n3.按正负数分入两个列表\n'''\n\nsource_list = []\npositive_list = []\nnegative_list = []\n\nfor i in range(20):\n num = int(input('Please input the number:'))\n print(num)\n source_list.append(num)\n\nprint('source list data is:')\nprint(source_list)\n\nfor item in source_list:\n if item >= 0:\n positive_list.append(item)\n else:\n negative_list.append(item)\n\nprint('positive data is:')\nprint(positive_list)\nprint('negative data is:')\nprint(negative_list)\n" }, { "alpha_fraction": 0.5776579976081848, "alphanum_fraction": 0.5982361435890198, "avg_line_length": 30.399999618530273, "blob_id": "abb2c99c75c1456f2250b2dec22b9fb5d6128f07", "content_id": "de78d5c60aeb34bb31733d2ed51f8a7e9a26fd69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2041, "license_type": "no_license", "max_line_length": 120, "num_lines": 65, "path": "/other/signvto.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\nimport time\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef sign_daily(username, password):\n username = username # username\n password = password # password\n singin_url = 'https://v2ex.com/signin'\n home_page = 'https://www.v2ex.com'\n daily_url = 'https://www.v2ex.com/mission/daily'\n\n user_agent = \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36\"\n\n headers = {\n \"User-Agent\": user_agent,\n \"Host\": \"www.v2ex.com\",\n \"Referer\": \"https://www.v2ex.com/signin\",\n \"Origin\": \"https://www.v2ex.com\"\n }\n\n v2ex_session = requests.Session()\n\n def make_soup(url, tag, name):\n page = v2ex_session.get(url, headers=headers, verify=True).text\n soup = BeautifulSoup(page)\n soup_result = soup.find(attrs={tag: name})\n return soup_result\n\n once_vaule = make_soup(singin_url, 'name', 'once')['value']\n print(once_vaule) # will show you the once\n\n post_info = {\n 'u': username,\n 'p': password,\n 'once': once_vaule,\n 'next': '/'\n }\n\n resp = v2ex_session.post(singin_url, data=post_info, headers=headers, verify=True)\n\n short_url = make_soup(daily_url, 'class', 'super normal button')['onclick']\n\n first_quote = short_url.find(\"'\")\n last_quote = short_url.find(\"'\", first_quote + 1)\n final_url = home_page + short_url[first_quote + 1:last_quote]\n\n page = v2ex_session.get(final_url, headers=headers, verify=True).content\n\n suceessful = make_soup(daily_url, 'class', 'fa fa-ok-sign')\n if suceessful:\n print (\"Sucessful.\")\n else:\n print (\"Something wrong.\")\n\n\nif __name__ == '__main__':\n user_list = [{'username': 'florije', 'password': 'fuboqing'}, {'username': 'vob636', 'password': 'fuboqing1988'},\n {'username': '[email protected]', 'password': '19931221'}]\n for user in user_list:\n sign_daily(user.get('username'), user.get('password'))\n time.sleep(60)\n" }, { "alpha_fraction": 0.5040000081062317, "alphanum_fraction": 0.5920000076293945, "avg_line_length": 16.85714340209961, "blob_id": "34c914e88271fc2f3f1152978d37c56f941dab5b", "content_id": "238fe9b7958fa0758a84fd6798608e098a3c9704", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 125, "license_type": "no_license", "max_line_length": 25, "num_lines": 7, "path": "/global/simple_math.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\nsalary = 2500.0\nbonus = 1200.0\npay = salary + bonus\nprint('Your pay is', pay)\n" }, { "alpha_fraction": 0.5078125, "alphanum_fraction": 0.53125, "avg_line_length": 13, "blob_id": "c0d803b47770f51f6b41a154c8f0182bc188ae58", "content_id": "54254ed8bb0c88b10c4d2c807398ddb2f07754fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 128, "license_type": "no_license", "max_line_length": 42, "num_lines": 9, "path": "/byte/mymodule.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8-*-\n__author__ = 'manman'\n\n\ndef say_hi():\n print('Hi,this is mymodule speaking.')\n\n\n__version__ = '0.1'\n\n\n" }, { "alpha_fraction": 0.6308724880218506, "alphanum_fraction": 0.6375839114189148, "avg_line_length": 16.52941131591797, "blob_id": "4b30e8922ff1a5f729b54aa27f7ac2eddc7c400d", "content_id": "5c91331aa7e0e03f71c828dd7b0ffec583608bca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 298, "license_type": "no_license", "max_line_length": 38, "num_lines": 17, "path": "/byte/chapter_13_1.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\n\ndef reverse(text):\n return text[::-1]\n\n\ndef is_palindrome(text):\n return text == reverse(text)\n\n\nsomething = raw_input(\"Enter input: \")\nif is_palindrome(something):\n print \"Yes,it is a palindrome\"\nelse:\n print\"No,it is not a palindrome\"\n" }, { "alpha_fraction": 0.6228813529014587, "alphanum_fraction": 0.6313559412956238, "avg_line_length": 38.33333206176758, "blob_id": "9724e0fbd6dc6eff14043879aefe0372eb793bd0", "content_id": "1f2f1f74e2b0e7781ac0baa66ed0ee323a663fc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 236, "license_type": "no_license", "max_line_length": 56, "num_lines": 6, "path": "/global/gross_pay.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\nhours = int(input('Enter the hours worked this week: '))\npay_rate = float(input('Enter the hourly pay rate: '))\ngross_pay = hours * pay_rate\nprint('Gross pay: $', format(gross_pay, ',.2f'))\n" }, { "alpha_fraction": 0.6283783912658691, "alphanum_fraction": 0.6554054021835327, "avg_line_length": 20.14285659790039, "blob_id": "02d91cc7d07ea9d5b4ede27a172f2a795fcca28a", "content_id": "7a954476fdf5e90f9788a85b32698d7af6d2a6dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 148, "license_type": "no_license", "max_line_length": 39, "num_lines": 7, "path": "/global/variable_demo.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n# This program demonstrates a variable.\nroom = 503\nprint('I am staying in room number.')\nprint(room)\n" }, { "alpha_fraction": 0.4046364724636078, "alphanum_fraction": 0.4193888306617737, "avg_line_length": 14.557376861572266, "blob_id": "d0e8bbdfea51bc78b2008a690311b0d19a80098a", "content_id": "8e85cb1f595e0dbf9c1e04787aa566ba60cf3064", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1051, "license_type": "no_license", "max_line_length": 60, "num_lines": 61, "path": "/learn/007.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n\"\"\"\n根据用户输入打印正三角,比如用户输入3打印如下:\n\n*\n\n *\n* *\n\n *\n * *\n* * *\n\n打印菱形\n\n\n\"\"\"\n\n\n# 1. 三角形\n# def show_triangle(num):\n# \"\"\"\n# print triangle\n# :param num:\n# :return:\n# \"\"\"\n# for i in range(num):\n# # print('i%s' % i)\n# print(' ' * (num - i - 1), end='')\n# for j in range(i + 1):\n# print('*', end=' ')\n# print()\n#\n# if __name__ == '__main__':\n# num = int(input('Please input the number:'))\n# show_triangle(num)\n\n\n# 2. 菱形\ndef show_diamond(num):\n \"\"\"\n print diamond\n :param num:\n :return:\n \"\"\"\n # 菱形的上半部分\n for i in range(num):\n print(' ' * (num - i) + '*' * (2 * i + 1))\n # 菱形的正中\n print('*' * (2 * num + 1))\n # 菱形的下半部分\n for i in range(num):\n print(' ' * (i + 1) + '*' * (2 * (num - i - 1) + 1))\n\n\n\nif __name__ == '__main__':\n num = int(input('Please input the number:'))\n show_diamond(num)\n" }, { "alpha_fraction": 0.5339366793632507, "alphanum_fraction": 0.5475113391876221, "avg_line_length": 16, "blob_id": "3507f9e1dd851651f95cb50b90363498d2a94ef3", "content_id": "ec19acd60786c2c1dec95007e09546529e6e9b74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 540, "license_type": "no_license", "max_line_length": 43, "num_lines": 26, "path": "/21days/5_2.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n\"\"\"\n1,定义函数get_blank_count\n2,该函数获取字符串空格\n3,测试该方法\n\"\"\"\n\n\ndef get_blank_count(strs):\n \"\"\"\n 获取字符串中空格数目\n :param strs: 传入原始字符串\n :return: 返回字符串中空格数目\n \"\"\"\n count = 0\n for item in strs:\n if item == ' ':\n count += 1\n return count\n\nif __name__ == '__main__':\n test_str = \"women doushi haohaizi.\"\n blank_count = get_blank_count(test_str)\n print(blank_count)\n" }, { "alpha_fraction": 0.48222222924232483, "alphanum_fraction": 0.5355555415153503, "avg_line_length": 15.071428298950195, "blob_id": "31a73aca23fa9f43f544a9dde806de1f46b05b9b", "content_id": "c405b527b6de82ca2388dedd445acbe4bdab71ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 514, "license_type": "no_license", "max_line_length": 55, "num_lines": 28, "path": "/21days/5_1.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n'''\n1,写一个function\n2,这个函数是排序列表使用\n3,写调用function\n'''\n\n# alist = [8, 4, 7, 12, 10, 9, 16]\n# alist.sort() # 默认按升序排列\n# print(alist)\n# alist.sort(reverse=True) # 按降序排列\n# print(alist)\n#\n# alist = [(3, 'ab'), (13, 'd'), (2, 'ss'), (101, 'c')]\n# alist.sort()\n# print(alist)\n\n\ndef sort_list(data):\n data.sort()\n\n\nif __name__ == '__main__':\n raw_list = [1, 3, 2]\n sort_list(raw_list)\n print(raw_list)\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5571428537368774, "avg_line_length": 26.399999618530273, "blob_id": "851697d0f88232e1e7df69ea592f5c0591d5b10d", "content_id": "c7b9a758d333880947815c67e4b5084b72df422d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 140, "license_type": "no_license", "max_line_length": 47, "num_lines": 5, "path": "/global/simple_loop1.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\nprint('I will display the number 1 through 5.')\nfor num in [1, 2, 3, 4, 5]:\n print(num)\n\n\n\n" }, { "alpha_fraction": 0.4710424840450287, "alphanum_fraction": 0.48262548446655273, "avg_line_length": 13.38888931274414, "blob_id": "146c573ba908f2324a37d80e0ea25a67c33596d5", "content_id": "e3f4070e0ebc1f6b0931c4ee65b2240d8fa87216", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 259, "license_type": "no_license", "max_line_length": 48, "num_lines": 18, "path": "/byte/func_nonlocal.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8-*-\n__author__ = 'manman'\n\n\ndef func_outer():\n x = 2\n print('x is', x)\n\n def func_inner():\n nonlocal x # zhe li bu dui ya. bu dong.\n\n x = 5\n\n func_inner()\n print('Changed local x to', x)\n\n\nfunc_outer()\n" }, { "alpha_fraction": 0.6933867931365967, "alphanum_fraction": 0.7835671305656433, "avg_line_length": 34.71428680419922, "blob_id": "4c16dac96e2223c391f119660f330f2533d87405", "content_id": "e9515be4f718f51407b775546176bfdaf815c057", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 637, "license_type": "no_license", "max_line_length": 75, "num_lines": 14, "path": "/other/other_readme.md", "repo_name": "florije1988/manman", "src_encoding": "GB18030", "text": "http://www.weather.com.cn/adat/sk/101190408.html\n\n\nhttp://mobile.weather.com.cn/js/citylist.xml\nhttp://www.weather.com.cn/data/list3/city.xml?level=1\nhttp://www.weather.com.cn/data/list3/city.xml\n\n\n获取省级代码:http://www.weather.com.cn/data/list3/city.xml?level=1\n获取城市代码(比如安徽是22):http://www.weather.com.cn/data/list3/city22.xml?level=2\n获取区域代码(比如安庆是2206):http://www.weather.com.cn/data/list3/city2206.xml?level=3\n获取到安徽省安庆市望江县的代码是220607\n然后去加上中国代码请求URL:http://m.weather.com.cn/data/101220607.html\n就可以获取当地天气。" }, { "alpha_fraction": 0.46739131212234497, "alphanum_fraction": 0.5, "avg_line_length": 9.222222328186035, "blob_id": "ed1f79ec371e08eb4b41ab71a569cfcea3a32382", "content_id": "26e77be354ca54e60fed0fcad4500fb7891d14dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 108, "license_type": "no_license", "max_line_length": 23, "num_lines": 9, "path": "/start/2_2/2_2.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\n\"\"\"\n2.2 输入,执行,输出\n\n\"\"\"\n\nprint('Hello world')\n" }, { "alpha_fraction": 0.4660493731498718, "alphanum_fraction": 0.485339492559433, "avg_line_length": 26.553192138671875, "blob_id": "bdcd1bdec8731a88847b402e1512c38250d8aef5", "content_id": "21a173556a24eb653ea9693b808512d60a5ca8f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1598, "license_type": "no_license", "max_line_length": 100, "num_lines": 47, "path": "/21days/5_3.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n\"\"\"\n1,给定字符串,带分行,然后split(分裂)为list\n2,分析list每个元素,判断是否有href关键字,保存有关键字的数据\n3,提取剩余元素里面的href=开头的部分\n\"\"\"\n\n\ndef get_hrefs(str_data):\n \"\"\"\n 获取str_data里面所有超链接\n :param str_data:\n :return:\n \"\"\"\n # split str_data to list\n str_list = str_data.split('\\n') # 分析原始数据看到有回车换行\n href_list = []\n for line in str_list:\n if 'href=' in line:\n line = line.strip() # 看到有的行有空格,就去掉\n line = line[4: -5] # href带其他标签,规则去掉\n line = line[0: line.find('>') + 1] # 看规则去掉字符串尾部的汉字\n href_list.append(line)\n #\n return href_list # [href sre[0:href str.find('>') + 1] for href str in[line.strip()[4: -5]for]\n\nif __name__ == '__main__':\n str_data = \"\"\"\n <h3>联系我们</h3>\n <p>联系人:王经理</p>\n <p>电话:021-87017800</p>\n <div>\n <ul>\n <li><a class=\"nav-first\" href=\"/\"首 页</li>\n <li><a href=\"/lista.php\">吸粮机</a></li>\n <li><a href=\"/listb.php\">灌包机</a></li>\n <li><a href=\"/listc.php\">汽油吸粮机</a></li>\n <li><a href=\"/order/setorder.php\">我要订购</a></li>\n <li><a href=\"/about.php\">关于我们</a></li>\n </ul>\n </div>\n \"\"\"\n res = get_hrefs(str_data)\n for item in res:\n print(item)\n\n" }, { "alpha_fraction": 0.5533333420753479, "alphanum_fraction": 0.5600000023841858, "avg_line_length": 23.83333396911621, "blob_id": "9c6de9c721c3df9e379c57cae97e5a155159e5bb", "content_id": "f8d1a382437759f999580e85b51da64d61515fbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 150, "license_type": "no_license", "max_line_length": 37, "num_lines": 6, "path": "/hard/ex10.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8-*-\n__author__ = 'manman'\n\ntabby_cat = \"\\tI'm tabbed in.\"\npersian_cat = \"I'm split non a line.\"\nbackslash_cat = \"I'm \\\\ a \\\\cat.\"\n\n" }, { "alpha_fraction": 0.5697211027145386, "alphanum_fraction": 0.5707171559333801, "avg_line_length": 17.943395614624023, "blob_id": "ea3e54c18c48932964f206271b3a69508ad8c297", "content_id": "17088f29c836622678f6cf93bfee86ec39596b4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1084, "license_type": "no_license", "max_line_length": 95, "num_lines": 53, "path": "/learn/011.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n\"\"\"\n遍历文件夹jsons,获取所有文件内容,并保存文件title到一个list里面并打印。\n\"\"\"\n\nimport os\nimport json\n\nbase_path = '{base_path}\\\\jsons'.format(base_path=os.getcwd())\n\n\ndef get_content(filename):\n \"\"\"\n 从filename读取数据\n :param filename:\n :return:\n \"\"\"\n result = ''\n with open(filename) as f:\n for line in f:\n result += line\n return result\n\n\ndef get_json_data():\n \"\"\"\n 获取json数据的title的list\n :param content:\n :return: res_list\n \"\"\"\n res_list = []\n for item in os.listdir(base_path): # '.\\\\jsons'\n res = get_content('{base_path}\\\\{filename}'.format(base_path=base_path, filename=item))\n json_res = json.loads(res)\n res_list.extend(data.get('title') for data in json_res)\n return res_list\n\n\ndef print_data(res_list):\n \"\"\"\n\n :param res_list:\n :return:\n \"\"\"\n for title in res_list:\n print(title)\n\n\nif __name__ == '__main__':\n res_list = get_json_data()\n print_data(res_list)\n" }, { "alpha_fraction": 0.6708464026451111, "alphanum_fraction": 0.7304075360298157, "avg_line_length": 31, "blob_id": "e41102d91c006f010ffe8130a5258e8cdccc2202", "content_id": "ec54f76ac21386e05199ebac313e3d06e61c0ebe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 319, "license_type": "no_license", "max_line_length": 81, "num_lines": 10, "path": "/other/aes_js_py/aes.js", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "/**\n * Created by florije on 11/3/2015.\n */\n'use strict';\nvar CryptoJS = require(\"crypto-js\");\nvar key = \"b6ce159334e155d8\";\nvar encrypted = CryptoJS.AES.encrypt(\"florije\", key);\nconsole.log(encrypted.toString());\nvar decrypted = CryptoJS.AES.decrypt(encrypted, key).toString(CryptoJS.enc.Utf8);\nconsole.log(decrypted);" }, { "alpha_fraction": 0.5587668418884277, "alphanum_fraction": 0.610468864440918, "avg_line_length": 30.775510787963867, "blob_id": "90c09f17cabb0f1c1bc9a87c2752a851315e9be8", "content_id": "fdffa8f21a69ade87e41d201315033a8549b0f62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3114, "license_type": "no_license", "max_line_length": 88, "num_lines": 98, "path": "/other/cryptojs_aes.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'florije'\n\nimport binascii\nimport StringIO\nfrom Crypto.Cipher import AES\n\nKEY = 'ce975de9294067470d1684442555767fcb007c5a3b89927714e449c3f66cb2a4'\nIV = '9AAECFCF7E82ABB8118D8E567D42EE86'\nPLAIN_TEXT = \"ciao\"\n\n\nclass PKCS7Padder(object):\n '''\n RFC 2315: PKCS#7 page 21\n Some content-encryption algorithms assume the\n input length is a multiple of k octets, where k > 1, and\n let the application define a method for handling inputs\n whose lengths are not a multiple of k octets. For such\n algorithms, the method shall be to pad the input at the\n trailing end with k - (l mod k) octets all having value k -\n (l mod k), where l is the length of the input. In other\n words, the input is padded at the trailing end with one of\n the following strings:\n 01 -- if l mod k = k-1\n 02 02 -- if l mod k = k-2\n .\n .\n .\n k k ... k k -- if l mod k = 0\n The padding can be removed unambiguously since all input is\n padded and no padding string is a suffix of another. This\n padding method is well-defined if and only if k < 256;\n methods for larger k are an open issue for further study.\n '''\n\n def __init__(self, k=16):\n self.k = k\n\n ## @param text: The padded text for which the padding is to be removed.\n # @exception ValueError Raised when the input padding is missing or corrupt.\n def decode(self, text):\n '''\n Remove the PKCS#7 padding from a text string\n '''\n nl = len(text)\n val = int(binascii.hexlify(text[-1]), 16)\n if val > self.k:\n raise ValueError('Input is not padded or padding is corrupt')\n\n l = nl - val\n return text[:l]\n\n ## @param text: The text to encode.\n def encode(self, text):\n '''\n Pad an input string according to PKCS#7\n '''\n l = len(text)\n output = StringIO.StringIO()\n val = self.k - (l % self.k)\n for _ in xrange(val):\n output.write('%02x' % val)\n return text + binascii.unhexlify(output.getvalue())\n\n\ndef encrypt(my_key=KEY, my_iv=IV, my_plain_text=PLAIN_TEXT):\n \"\"\"\n Expected result if called without parameters:\n PLAIN 'ciao'\n KEY 'ce975de9294067470d1684442555767fcb007c5a3b89927714e449c3f66cb2a4'\n IV '9aaecfcf7e82abb8118d8e567d42ee86'\n ENCRYPTED '62e6f521d533b26701f78864c541173d'\n \"\"\"\n\n key = binascii.unhexlify(my_key)\n iv = binascii.unhexlify(my_iv)\n\n padder = PKCS7Padder()\n padded_text = padder.encode(my_plain_text)\n\n encryptor = AES.new(key, AES.MODE_CFB, iv, segment_size=128) # Initialize encryptor\n result = encryptor.encrypt(padded_text)\n\n return {\n \"plain\": my_plain_text,\n \"key\": binascii.hexlify(key),\n \"iv\": binascii.hexlify(iv),\n \"ciphertext\": result\n }\n\n\nif __name__ == '__main__':\n result = encrypt()\n print \"PLAIN %r\" % result['plain']\n print \"KEY %r\" % result['key']\n print \"IV %r\" % result['iv']\n print \"ENCRYPTED %r\" % binascii.hexlify(result['ciphertext'])\n" }, { "alpha_fraction": 0.6098901033401489, "alphanum_fraction": 0.6181318759918213, "avg_line_length": 29.33333396911621, "blob_id": "f5ffc279357a671d7c252b0129a3eb0badbb8ad8", "content_id": "338273bc650771738d212fbb75763148cbe6aeb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 364, "license_type": "no_license", "max_line_length": 49, "num_lines": 12, "path": "/global/user_squares1.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\nprint('This program displays a list of number')\nprint('and their squares.')\nstart = int(input('Enter the starting number: '))\nend = int(input('How high should I go?'))\nprint()\nprint('Number\\tSquare')\nprint('--------------')\nfor number in range(start, end + 1):\n square = number ** 2\n print(number, '\\t', square)\n" }, { "alpha_fraction": 0.560693621635437, "alphanum_fraction": 0.6069363951683044, "avg_line_length": 23.428571701049805, "blob_id": "7fcf9ba12dadb23290aa37bd31b07f7ab58f7a28", "content_id": "4dd6daaa8bdb51112edcfc7c5359eadadf676800", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 173, "license_type": "no_license", "max_line_length": 50, "num_lines": 7, "path": "/global/variable_demo4.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\ndollars = 2.75\nprint('I have', dollars, 'in my account.')\ndollars =99.95\nprint('But now I have', dollars, 'in my account!')\n\n\n" }, { "alpha_fraction": 0.40136054158210754, "alphanum_fraction": 0.4523809552192688, "avg_line_length": 11.782608985900879, "blob_id": "eea7089d8bc621917a06af8973d6fa6bb6f73d64", "content_id": "ab68d0e0eb57b7ba9461ba93761dd872875331eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 332, "license_type": "no_license", "max_line_length": 29, "num_lines": 23, "path": "/learn/002.py", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = 'manman'\n\n\"\"\"\n编写程序求 1+3+5+7+……+99 的和值。\n\"\"\"\n'''\n1.定义一组数列\n2.求和\n'''\n\n\ndef get_res():\n source = range(1, 100, 2)\n sum = 0\n for i in source:\n print(i)\n sum += i\n return sum\n\nif __name__ == '__main__':\n res = get_res()\n print(res)\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 27, "blob_id": "670694f89e4d3dedbfac231e4acc5665755317b9", "content_id": "1e703749ff54436d79d4540bb0f69a862b92e110", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 28, "license_type": "no_license", "max_line_length": 27, "num_lines": 1, "path": "/readme.md", "repo_name": "florije1988/manman", "src_encoding": "UTF-8", "text": "# This is the hard way code " } ]
94
dronperminov/Word2VecCodeNames
https://github.com/dronperminov/Word2VecCodeNames
7be03ee8d5f79734f3346eac1746aa7bfb3e15eb
7dedc7b5fc50b7ea899994ced010a4273af6dd25
39cb45f6ae05c19f294d6eaa6424247a255ddef9
refs/heads/master
2023-08-26T08:28:26.752693
2021-10-15T21:32:01
2021-10-16T17:27:54
416,824,483
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.40227049589157104, "alphanum_fraction": 0.40227049589157104, "avg_line_length": 12.332237243652344, "blob_id": "659742ef8dba7c64ffb879c2a70b0e2be242fc7c", "content_id": "cfcc214760796214e2d7186b4eab43463207771f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5672, "license_type": "no_license", "max_line_length": 18, "num_lines": 304, "path": "/js/words.js", "repo_name": "dronperminov/Word2VecCodeNames", "src_encoding": "UTF-8", "text": "const WORDS = [\n \"АГЕНТ\",\n \"АКТ\",\n \"АКЦИЯ\",\n \"АЛЬБОМ\",\n \"АМФИБИЯ\",\n \"АППАРАТ\",\n \"БАБОЧКА\",\n \"БАЗА\",\n \"БАНК\",\n \"БАНЯ\",\n \"БАР\",\n \"БАРЬЕР\",\n \"БАССЕЙН\",\n \"БАТАРЕЯ\",\n \"БАШНЯ\",\n \"БЕЛОК\",\n \"БЕРЁЗА\",\n \"БИЛЕТ\",\n \"БИРЖА\",\n \"БЛОК\",\n \"БОБ\",\n \"БОЕВИК\",\n \"БОЛЬНИЦА\",\n \"БОМБА\",\n \"БОРТ\",\n \"БОТИНОК\",\n \"БОЧКА\",\n \"БРАК\",\n \"БУМАГА\",\n \"БУТЫЛКА\",\n \"БЫК\",\n \"БЫЧОК\",\n \"БЮСТ\",\n \"ВАЛ\",\n \"ВЕДЬМА\",\n \"ВЕНЕЦ\",\n \"ВЕРТОЛЁТ\",\n \"ВЕРФЬ\",\n \"ВЕТЕР\",\n \"ВИЛКА\",\n \"ВИРУС\",\n \"ВИСКИ\",\n \"ВОДА\",\n \"ВОЖДЬ\",\n \"ВОЛНА\",\n \"ВОР\",\n \"ВОРОТ\",\n \"ГАЗ\",\n \"ГАЗЕЛЬ\",\n \"ГАЛОП\",\n \"ГВОЗДЬ\",\n \"ГИГАНТ\",\n \"ГОЛОВА\",\n \"ГОЛЬФ\",\n \"ГРАНАТ\",\n \"ГРЕБЕНЬ\",\n \"ГРИФ\",\n \"ГРУША\",\n \"ГУБА\",\n \"ГУСЕНИЦА\",\n \"ДАМА\",\n \"ДАЧА\",\n \"ДВОР\",\n \"ДВОРНИК\",\n \"ДИСК\",\n \"ДОЛГ\",\n \"ДРАКОН\",\n \"ДРОБЬ\",\n \"ДЫРА\",\n \"ЕДИНОРОГ\",\n \"ЖИЛА\",\n \"ЗАБОР\",\n \"ЗАВОД\",\n \"ЗАЛИВ\",\n \"ЗАМОК\",\n \"ЗАЯЦ\",\n \"ЗВЕЗДА\",\n \"ЗЕБРА\",\n \"ЗЕМЛЯ\",\n \"ЗМЕЙ\",\n \"ЗОЛОТО\",\n \"ЗОНА\",\n \"ИГЛА\",\n \"ИКРА\",\n \"ИНСТИТУТ\",\n \"КАБАЧОК\",\n \"КАБИНЕТ\",\n \"КАДР\",\n \"КАЗИНО\",\n \"КАМЕНЬ\",\n \"КАМЕРА\",\n \"КАНАЛ\",\n \"КАРАУЛ\",\n \"КАРЛИК\",\n \"КАРТА\",\n \"КАТОК\",\n \"КАША\",\n \"КЕНГУРУ\",\n \"КЕНТАВР\",\n \"КЕТЧУП\",\n \"КИВИ\",\n \"КИСТЬ\",\n \"КИТ\",\n \"КЛАСС\",\n \"КЛЕТКА\",\n \"КЛЮЧ\",\n \"КОЛ\",\n \"КОЛОДА\",\n \"КОЛОННА\",\n \"КОЛЬЦО\",\n \"КОРЕНЬ\",\n \"КОРОЛЕВА\",\n \"КОРОЛЬ\",\n \"КОРОНА\",\n \"КОСА\",\n \"КОСЯК\",\n \"КОШКА\",\n \"КРАН\",\n \"КРЕПОСТЬ\",\n \"КРОЛИК\",\n \"КРОНА\",\n \"КРОШКА\",\n \"КРУГ\",\n \"КРЫЛО\",\n \"КУЛАК\",\n \"КУРС\",\n \"ЛАДЬЯ\",\n \"ЛАЗЕР\",\n \"ЛАМА\",\n \"ЛАСКА\",\n \"ЛЕВ\",\n \"ЛЕГЕНДА\",\n \"ЛЁД\",\n \"ЛЕС\",\n \"ЛИМУЗИН\",\n \"ЛИНИЯ\",\n \"ЛИПА\",\n \"ЛИРА\",\n \"ЛИЦО\",\n \"ЛОЖЕ\",\n \"ЛОПАТКА\",\n \"ЛОТ\",\n \"ЛОШАДЬ\",\n \"ЛУК\",\n \"МАНДАРИН\",\n \"МАРКА\",\n \"МАРШ\",\n \"МАСЛО\",\n \"МАТ\",\n \"МЕДВЕДЬ\",\n \"МИКРОСКОП\",\n \"МИНА\",\n \"МИР\",\n \"МОЛНИЯ\",\n \"МОЛЬ\",\n \"МОРКОВЬ\",\n \"МОТИВ\",\n \"МУШКА\",\n \"НАЛЁТ\",\n \"НАРЯД\",\n \"НЕБОСКРЁБ\",\n \"НОМЕР\",\n \"НОРКА\",\n \"НОТА\",\n \"НЯНЯ\",\n \"ОБЛОМ\",\n \"ОБРАЗОВАНИЕ\",\n \"ОБРЕЗ\",\n \"ОВСЯНКА\",\n \"ОЛИМП\",\n \"ОПЕРА\",\n \"ОРГАН\",\n \"ОРДЕН\",\n \"ОРЁЛ\",\n \"ОСЬМИНОГ\",\n \"ОЧКИ\",\n \"ПАДЕНИЕ\",\n \"ПАНАМА\",\n \"ПАРА\",\n \"ПАРАШЮТ\",\n \"ПАРК\",\n \"ПАРТИЯ\",\n \"ПАТРОН\",\n \"ПАУК\",\n \"ПЕРЕВОД\",\n \"ПЕРО\",\n \"ПЕЧАТЬ\",\n \"ПИЛОТ\",\n \"ПИРАТ\",\n \"ПИСТОЛЕТ\",\n \"ПЛАТА\",\n \"ПЛАТЬЕ\",\n \"ПЛОМБА\",\n \"ПЛОЩАДЬ\",\n \"ПОВАР\",\n \"ПОГОН\",\n \"ПОДКОВА\",\n \"ПОДЪЁМ\",\n \"ПОЛ\",\n \"ПОЛЕ\",\n \"ПОМПА\",\n \"ПОРТ\",\n \"ПОСОЛ\",\n \"ПОСТ\",\n \"ПОТОК\",\n \"ПОЧКА\",\n \"ПРАВО\",\n \"ПРЕДЛОЖЕНИЕ\",\n \"ПРИЗРАК\",\n \"ПРИНЦЕССА\",\n \"ПРИШЕЛЕЦ\",\n \"ПРОБКА\",\n \"ПРОВОДНИК\",\n \"ПРОКАТ\",\n \"ПРОСПЕКТ\",\n \"ПУТЬ\",\n \"ПУШКИН\",\n \"ПЯТАЧОК\",\n \"РАЗВОД\",\n \"РАЗВОРОТ\",\n \"РАЗРЯД\",\n \"РАСТВОР\",\n \"РИФ\",\n \"РОБОТ\",\n \"РОГ\",\n \"РОД\",\n \"РОК\",\n \"РУБАШКА\",\n \"РУБКА\",\n \"РУЛЕТКА\",\n \"РУЧКА\",\n \"РЫБА\",\n \"РЫСЬ\",\n \"РЫЦАРЬ\",\n \"САЛЮТ\",\n \"САНТЕХНИК\",\n \"САЧОК\",\n \"СВЕЧА\",\n \"СВИДЕТЕЛЬ\",\n \"СЕКРЕТ\",\n \"СЕТЬ\",\n \"СКАТ\",\n \"СНАРЯД\",\n \"СНЕГ\",\n \"СНЕГОВИК\",\n \"СОБАКА\",\n \"СОЛДАТ\",\n \"СОЛЬ\",\n \"СПЛАВ\",\n \"СПУТНИК\",\n \"ССЫЛКА\",\n \"СТАВКА\",\n \"СТАДИОН\",\n \"СТАНОК\",\n \"СТВОЛ\",\n \"СТЕКЛО\",\n \"СТЕНА\",\n \"СТОЛ\",\n \"СТОПКА\",\n \"СТРЕЛА\",\n \"СТРОЧКА\",\n \"СТРУНА\",\n \"СТУЛ\",\n \"СЪЕЗД\",\n \"ТАЗ\",\n \"ТАКСА\",\n \"ТАКТ\",\n \"ТАНЕЦ\",\n \"ТАРЕЛКА\",\n \"ТЕЛЕГА\",\n \"ТЕЛЕСКОП\",\n \"ТИТАН\",\n \"ТОК\",\n \"ТРЕУГОЛЬНИК\",\n \"ТРУБА\",\n \"ТУР\",\n \"УДАРНИК\",\n \"УЗЕЛ\",\n \"УТКА\",\n \"УЧЁНЫЙ\",\n \"УЧИТЕЛЬ\",\n \"ФАКЕЛ\",\n \"ФАЛАНГА\",\n \"ФИНКА\",\n \"ФЛЕЙТА\",\n \"ХЛОПОК\",\n \"ЦИЛИНДР\",\n \"ЧЕСТЬ\",\n \"ШАЙБА\",\n \"ШАЙКА\",\n \"ШАР\",\n \"ШАХ\",\n \"ШАШКА\",\n \"ШИШКА\",\n \"ШОКОЛАД\",\n \"ШПАГАТ\",\n \"ШПИОН\",\n \"ШУБА\",\n \"ЭЛЬФ\",\n \"ЯБЛОКО\",\n \"ЯЗЫК\",\n \"ЯЧМЕНЬ\"\n]" }, { "alpha_fraction": 0.5196687579154968, "alphanum_fraction": 0.5248447060585022, "avg_line_length": 22, "blob_id": "0cfe481e3f7d4e88ab167953ec9ea808e592d812", "content_id": "23513e8ad352960a5430f34b4a32430f5075a366", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 970, "license_type": "no_license", "max_line_length": 71, "num_lines": 42, "path": "/scripts/convert.py", "repo_name": "dronperminov/Word2VecCodeNames", "src_encoding": "UTF-8", "text": "import json\nimport os\nfrom math import sqrt\nimport re\n\n\ndef norm(vec):\n dot = 0\n\n for v in vec:\n dot += v*v\n\n return sqrt(dot)\n\n\ndef main():\n filename = 'embedding.txt'\n embedding = dict()\n\n with open(filename, encoding='utf-8') as f:\n args = f.readline().strip('\\n').split(' ')\n embedding['size'] = int(args[1])\n embedding['embedding'] = dict()\n\n for line in f:\n word, *vector = line.strip().split(' ')\n\n if not re.fullmatch(r'[а-яА-Я\\-]+', word) or len(word) < 3:\n continue\n\n assert(len(vector) == embedding['size'])\n vector = [float(v) for v in vector]\n length = norm(vector)\n vector = [v / length for v in vector]\n embedding['embedding'][word] = vector\n\n with open(filename + '.js', 'w', encoding='utf-8') as f:\n f.write('const EMBEDDING = ' + json.dumps(embedding))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5790838599205017, "alphanum_fraction": 0.622299075126648, "avg_line_length": 26.547618865966797, "blob_id": "0127c1458c12a07d23ebb980958b16ae3405553e", "content_id": "f780a0f70fa1b66ad2f248440f5a6bd617c76356", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1637, "license_type": "no_license", "max_line_length": 266, "num_lines": 42, "path": "/README.md", "repo_name": "dronperminov/Word2VecCodeNames", "src_encoding": "UTF-8", "text": "# Word2VecCodeNames\nКодовые имена с использованием word2vec\n\n## Что умеет игра\n* редактировать карту с игровым полем\n* генерировать игровое поле\n* генерировать слова\n* закрывать отгаданные карточки\n* предсказывать слово (пока что очень тупым способом)\n\n## Внешний вид игры\n<img src='https://github.com/dronperminov/Word2VecCodeNames/blob/master/examples/example.png' />\n\n## Что нужно для работы предсказания слова\nДля того, чтобы работал функционал предсказания слова необходимо добавить файл с эмбеддингом для слов в папку с javascript кодом (js) с названием embedding.js. Файл должен иметь следующий формат (все вектора должны быть нормализованы, то есть иметь единичную длину):\n```\n{\n size: vector_size,\n embedding: {\n word_1: vector_1,\n word_2: vector_2,\n ...\n word_n: vector_n,\n }\n}\n```\n\n### Пример файла с эмбеддингом\n```\n{\n size: 5,\n embedding: {\n \"печать\": [1, 0, 0, 0, 0],\n \"блок\": [0, 1, 0, 0, 0],\n \"амфибия\": [0, 0, 1, 0, 0],\n \"шар\": [0, 0, 0, 1, 0],\n \"рок\": [0, 0, 0, 0, 1],\n \"кот\": [0, 0, 0.8, 0, 0.6],\n \"лопата\": [0.3, 0.3, 0.8, 0.3, 0.3]\n }\n}\n```\n" }, { "alpha_fraction": 0.5316931009292603, "alphanum_fraction": 0.547122597694397, "avg_line_length": 23.46938705444336, "blob_id": "b660c7d6ab6818239906ac3fa68efa39406e7d33", "content_id": "48dbf782aeb5cb3361acb8d150a72d2234f2314f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2398, "license_type": "no_license", "max_line_length": 167, "num_lines": 98, "path": "/js/word2vec.js", "repo_name": "dronperminov/Word2VecCodeNames", "src_encoding": "UTF-8", "text": "function Word2vec(embedding, size) {\n this.embedding = embedding\n this.size = size\n}\n\nWord2vec.prototype.Dot = function(a, b) {\n let dot = 0\n\n for (let i = 0; i < this.size; i++)\n dot += a[i] * b[i]\n\n return dot\n}\n\nWord2vec.prototype.Similarity = function(a, b) {\n return this.Dot(a, b)\n}\n\nWord2vec.prototype.Combination = function(words, weights) {\n let v = new Array(this.size).fill(0)\n\n for (let i = 0; i < words.length; i++) {\n let vector = this.embedding[words[i]]\n\n if (vector == undefined) {\n console.log('word \"' + words[i] + '\" was skipped')\n continue\n }\n\n for (let j = 0; j < this.size; j++)\n v[j] += vector[j] * weights[i]\n }\n\n let len = Math.sqrt(this.Dot(v, v))\n\n if (len > 0) {\n for (let i = 0; i < this.size; i++) {\n v[i] /= len\n }\n }\n\n return v\n}\n\nWord2vec.prototype.GetTopWords = function(v, count = 10) {\n let words = this.PartialSort(Object.keys(this.embedding), count, (a, b) => { return this.Similarity(v, this.embedding[b]) - this.Similarity(v, this.embedding[a])})\n let result = []\n\n for (let i = 0; i < count; i++) {\n let similarity = this.Similarity(v, this.embedding[words[i]])\n result.push({ word: words[i], similarity: Math.round(similarity * 1000) / 1000 })\n }\n\n return result\n}\n\nWord2vec.prototype.GetTopWordsCombination = function(words, weights, count = 10) {\n return this.GetTopWords(this.Combination(words, weights), count)\n}\n\nWord2vec.prototype.Bisect = function(items, x, comparator, lo, hi) {\n if (typeof(lo) == 'undefined')\n lo = 0\n\n if (typeof(hi) == 'undefined')\n hi = items.length\n\n while (lo < hi) {\n let mid = Math.floor((lo + hi) / 2)\n\n if (comparator(x, items[mid]) < 0) {\n hi = mid\n }\n else {\n lo = mid + 1\n }\n }\n\n return lo;\n}\n\nWord2vec.prototype.PartialSort = function(items, k, comparator) {\n let smallest = []\n\n for (let i = 0, len = items.length; i < len; ++i) {\n let item = items[i]\n\n if (smallest.length < k || comparator(item, smallest[smallest.length - 1]) < 0) {\n smallest.splice(this.Bisect(smallest, item, comparator), 0, item)\n\n if (smallest.length > k) {\n smallest.splice(k, 1)\n }\n }\n }\n\n return smallest\n}\n" }, { "alpha_fraction": 0.6071857213973999, "alphanum_fraction": 0.621961236000061, "avg_line_length": 35.65972137451172, "blob_id": "10d181548a895c78281760c667b1bd9adbeae6a5", "content_id": "1e90761a63a02cb5be0bb1435a552e7dfd99c29c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 15837, "license_type": "no_license", "max_line_length": 175, "num_lines": 432, "path": "/js/CodeNamesGame.js", "repo_name": "dronperminov/Word2VecCodeNames", "src_encoding": "UTF-8", "text": "const RED_CELL_COLOR = '#fb3a18'\nconst BLUE_CELL_COLOR = '#3690c7'\nconst EMPTY_CELL_COLOR = '#cba976'\nconst GAME_OVER_CELL_COLOR = '#4c403a'\n\nconst CELL_COUNT = 5\n\nconst EMPTY_STATUS = 'empty'\nconst RED_STATUS = 'red'\nconst BLUE_STATUS = 'blue'\nconst GAME_OVER_STATUS = 'over'\n\nconst BLUE_COLOR = 0\nconst RED_COLOR = 1\n\nconst STATUSES = [EMPTY_STATUS, RED_STATUS, BLUE_STATUS, GAME_OVER_STATUS]\n\nfunction CodeNamesGame(field, wordsBox, predictionsBox) {\n this.field = field\n this.wordsBox = wordsBox\n this.predictionsBox = predictionsBox\n this.predictionsBox.style.display = 'none'\n\n this.padding = 12\n this.border = 15\n this.radius = 20\n this.fieldSize = field.clientWidth\n this.fieldColors = ['#47c6ff', '#fd5337']\n this.fieldBorderColors = ['#416fad', '#9d3b3a']\n this.colorIndex = BLUE_COLOR\n\n this.cardUrls = {}\n this.cardUrls[RED_STATUS] = ['cards/red1.jpg', 'cards/red2.jpg', 'cards/red_blue.jpg']\n this.cardUrls[BLUE_STATUS] = ['cards/blue1.jpg', 'cards/blue2.jpg', 'cards/blue_red.jpg']\n this.cardUrls[EMPTY_STATUS] = ['cards/empty1.jpg', 'cards/empty2.jpg']\n this.cardUrls[GAME_OVER_STATUS] = ['cards/game_over.jpg']\n\n this.InitField()\n this.InitWords()\n}\n\nCodeNamesGame.prototype.MakePath = function(stroke, fill, strokeWidth, d) {\n let path = document.createElementNS('http://www.w3.org/2000/svg', 'path')\n path.setAttribute('stroke', stroke)\n path.setAttribute('fill', fill)\n path.setAttribute('stroke-width', strokeWidth)\n path.setAttribute('d', d)\n\n return path\n}\n\nCodeNamesGame.prototype.MakeCell = function(x, y, cellSize, status) {\n let radius = cellSize / 5\n let colors = []\n\n colors[EMPTY_STATUS] = EMPTY_CELL_COLOR\n colors[RED_STATUS] = RED_CELL_COLOR\n colors[BLUE_STATUS] = BLUE_CELL_COLOR\n colors[GAME_OVER_STATUS] = GAME_OVER_CELL_COLOR\n\n let g = document.createElementNS('http://www.w3.org/2000/svg', 'g')\n g.appendChild(this.MakePath('#000', colors[status], '1', `\n M ${x + radius} ${y}\n l ${cellSize - 2 * radius} 0\n q ${radius} 0 ${radius} ${radius}\n l 0 ${cellSize - 2 * radius}\n q 0 ${radius} ${-radius} ${radius}\n l ${-cellSize + 2 * radius} 0\n q ${-radius} 0 ${-radius} ${-radius}\n l 0 ${-cellSize + 2 * radius}\n q 0 ${-radius} ${radius} ${-radius}\n `))\n\n\n if (status == RED_STATUS) {\n let size = cellSize / 4\n g.appendChild(this.MakePath('#ff8474', '#ee4723', '2', `\n M ${x + cellSize / 2} ${y + cellSize / 2 - size}\n l ${size} ${size} l ${-size} ${size}\n l ${-size} ${-size}\n l ${size} ${-size}\n `))\n }\n else if (status == BLUE_STATUS) {\n let size = cellSize / 5\n g.appendChild(this.MakePath('#79c5f7', '#238dcb', '2', `\n M ${x + cellSize / 2} ${y + cellSize / 2}\n m ${-size} 0\n a ${size} ${size} 0 1 0 ${2 * size} 0\n a ${size} ${size} 0 1 0 ${-2 * size} 0\n `))\n }\n else if (status == GAME_OVER_STATUS) {\n let size = cellSize / 2.5 + 2\n g.appendChild(this.MakePath('#7f746f', '#000', '5', `\n M ${x + cellSize / 2 - size / 2} ${y + cellSize / 2 - size / 2} l ${size} ${size}\n M ${x + cellSize / 2 - size / 2} ${y + cellSize / 2 + size / 2} l ${size} ${-size}\n `))\n\n size -= 2\n g.appendChild(this.MakePath('#000', '#000', '3', `\n M ${x + cellSize / 2 - size / 2} ${y + cellSize / 2 - size / 2} l ${size} ${size}\n M ${x + cellSize / 2 - size / 2} ${y + cellSize / 2 + size / 2} l ${size} ${-size}\n `))\n }\n\n return g\n}\n\nCodeNamesGame.prototype.SetColor = function(colorIndex) {\n this.colorIndex = colorIndex\n this.colorsPath.setAttribute('fill', this.fieldColors[this.colorIndex])\n this.colorsPath.setAttribute('stroke', this.fieldBorderColors[this.colorIndex])\n}\n\nCodeNamesGame.prototype.SetCellStatus = function(cellIndex, status, needHide = false) {\n let cell = this.cells[cellIndex]\n this.field.removeChild(cell.cell)\n cell.status = status\n cell.cell = this.MakeCell(cell.x, cell.y, cell.cellSize, cell.status)\n this.field.appendChild(cell.cell)\n cell.cell.addEventListener('mousedown', (e) => this.UpdateCell(e, cellIndex))\n\n let img = document.getElementById('card-img-' + cellIndex)\n img.src = this.Choice(this.cardUrls[status])\n\n if (needHide) {\n img.style.display = 'none'\n }\n}\n\nCodeNamesGame.prototype.UpdateCell = function(e, cellIndex) {\n let index = STATUSES.indexOf(this.cells[cellIndex].status)\n let delta = e.button == 0 ? 1 : STATUSES.length - 1\n\n this.SetCellStatus(cellIndex, STATUSES[(index + delta) % STATUSES.length])\n}\n\nCodeNamesGame.prototype.InitCells = function(cellPadding, cellSize, cellOffset) {\n this.cells = []\n\n for (let i = 0; i < CELL_COUNT; i++) {\n for (let j = 0; j < CELL_COUNT; j++) {\n let x = cellPadding + j * (cellSize + cellOffset)\n let y = cellPadding + i * (cellSize + cellOffset)\n let statuses = [EMPTY_STATUS, RED_STATUS, BLUE_STATUS, GAME_OVER_STATUS]\n let cell = this.MakeCell(x, y, cellSize, EMPTY_STATUS)\n\n this.cells.push({ cell: cell, x: x, y: y, cellSize: cellSize, status: EMPTY_STATUS })\n this.field.appendChild(cell)\n\n cell.addEventListener('mousedown', (e) => this.UpdateCell(e, i * CELL_COUNT + j))\n }\n }\n}\n\nCodeNamesGame.prototype.GenerateField = function() {\n let redCount = Math.floor((CELL_COUNT*CELL_COUNT - 1) / 3)\n let blueCount = redCount + 1\n let emptyCount = CELL_COUNT*CELL_COUNT - redCount - blueCount - 1\n\n if (this.colorIndex == RED_COLOR) {\n redCount++\n blueCount--\n }\n\n let statuses = []\n\n for (let i = 0; i < redCount; i++)\n statuses.push(RED_STATUS)\n\n for (let i = 0; i < blueCount; i++)\n statuses.push(BLUE_STATUS)\n\n for (let i = 0; i < emptyCount; i++)\n statuses.push(EMPTY_STATUS)\n\n statuses.push(GAME_OVER_STATUS)\n statuses.sort((a, b) => Math.random() < 0.5 ? -1 : 1)\n\n for (let i = 0; i < CELL_COUNT * CELL_COUNT; i++) {\n this.SetCellStatus(i, statuses.pop())\n }\n\n this.FindWords()\n}\n\nCodeNamesGame.prototype.ChangeColor = function() {\n this.SetColor(this.colorIndex == RED_COLOR ? BLUE_COLOR : RED_COLOR)\n}\n\nCodeNamesGame.prototype.ResetField = function() {\n for (let i = 0; i < CELL_COUNT * CELL_COUNT; i++) {\n this.SetCellStatus(i, EMPTY_STATUS, true)\n }\n}\n\nCodeNamesGame.prototype.InitField = function() {\n let part = this.fieldSize / 5\n let colorWidth = this.fieldSize / 8\n let colorHeight = colorWidth / 4\n let colorIndex = 0\n\n let innerPadding = this.padding + this.border + 12\n\n let cellPadding = innerPadding + 10\n let cellOffset = 3\n let cellSize = (this.fieldSize - 2 * cellPadding - (CELL_COUNT - 1) * cellOffset) / CELL_COUNT\n\n this.field.appendChild(this.MakePath('#5f351e', '#845337', '2', `\n M ${this.padding + part} ${this.padding + this.border}\n L ${this.fieldSize - this.padding - part} ${this.padding + this.border}\n L ${this.fieldSize - this.padding - part + this.border} ${this.padding}\n L ${this.fieldSize - this.padding - this.radius} ${this.padding}\n Q ${this.fieldSize - this.padding} ${this.padding} ${this.fieldSize - this.padding} ${this.padding + this.radius}\n\n L ${this.fieldSize - this.padding} ${this.padding + part - this.border}\n L ${this.fieldSize - this.padding - this.border} ${this.padding + part}\n L ${this.fieldSize - this.padding - this.border} ${this.fieldSize - this.padding - part - this.border}\n L ${this.fieldSize - this.padding} ${this.fieldSize - this.padding - part}\n L ${this.fieldSize - this.padding} ${this.fieldSize - this.padding - this.radius}\n Q ${this.fieldSize - this.padding} ${this.fieldSize - this.padding} ${this.fieldSize - this.padding - this.radius} ${this.fieldSize - this.padding}\n\n L ${this.fieldSize - this.padding - part + this.border} ${this.fieldSize - this.padding}\n L ${this.fieldSize - this.padding - part} ${this.fieldSize - this.padding - this.border}\n L ${this.padding + part + this.border} ${this.fieldSize - this.padding - this.border}\n L ${this.padding + part} ${this.fieldSize - this.padding}\n L ${this.padding + this.radius} ${this.fieldSize - this.padding}\n Q ${this.padding} ${this.fieldSize - this.padding} ${this.padding} ${this.fieldSize - this.padding - this.radius}\n\n L ${this.padding} ${this.fieldSize - this.padding - part + this.border}\n L ${this.padding + this.border} ${this.fieldSize - this.padding - part}\n L ${this.padding + this.border} ${this.padding + part + this.border}\n L ${this.padding} ${this.padding + part}\n L ${this.padding} ${this.padding + this.radius}\n Q ${this.padding} ${this.padding} ${this.padding + this.radius} ${this.padding}\n\n L ${this.padding + part - this.border} ${this.padding}\n L ${this.padding + part} ${this.padding + this.border}\n `))\n\n this.colorsPath = this.MakePath(this.fieldBorderColors[this.colorIndex], this.fieldColors[this.colorIndex], '2', `\n M ${this.fieldSize / 2 - colorWidth / 2} ${this.padding + this.border - 2} l ${colorWidth} 0 l 0 ${-colorHeight} l ${-colorWidth} 0 l 0 ${colorHeight}\n M ${this.fieldSize / 2 - colorWidth / 2} ${this.fieldSize - this.padding - this.border + 2} l ${colorWidth} 0 l 0 ${colorHeight} l ${-colorWidth} 0 l 0 ${-colorHeight}\n M ${this.padding + this.border - 2} ${this.fieldSize / 2 - colorWidth / 2} l 0 ${colorWidth} l ${-colorHeight} 0 l 0 ${-colorWidth} l ${colorHeight} 0\n M ${this.fieldSize - this.padding - this.border + 2} ${this.fieldSize / 2 - colorWidth / 2} l 0 ${colorWidth} l ${colorHeight} 0 l 0 ${-colorWidth} l ${-colorHeight} 0\n `)\n\n this.field.appendChild(this.colorsPath)\n\n this.field.appendChild(this.MakePath('#5f351e', '#000', '4', `\n M ${innerPadding + this.radius} ${innerPadding}\n L ${this.fieldSize - innerPadding - this.radius} ${innerPadding}\n Q ${this.fieldSize - innerPadding} ${innerPadding} ${this.fieldSize - innerPadding} ${innerPadding + this.radius}\n L ${this.fieldSize - innerPadding} ${this.fieldSize - innerPadding - this.radius}\n Q ${this.fieldSize - innerPadding} ${this.fieldSize - innerPadding} ${this.fieldSize - innerPadding - this.radius} ${this.fieldSize - innerPadding}\n L ${innerPadding + this.radius} ${this.fieldSize - innerPadding}\n Q ${innerPadding} ${this.fieldSize - innerPadding} ${innerPadding} ${this.fieldSize - innerPadding - this.radius}\n L ${innerPadding} ${innerPadding + this.radius}\n Q ${innerPadding} ${innerPadding} ${innerPadding + this.radius} ${innerPadding}\n `))\n\n this.InitCells(cellPadding, cellSize, cellOffset)\n}\n\nCodeNamesGame.prototype.MakeDiv = function(className = '', innerHTML = '') {\n let div = document.createElement('div')\n div.className = className\n div.innerHTML = innerHTML\n return div\n}\n\nCodeNamesGame.prototype.Choice = function(collection) {\n return collection[Math.floor(Math.random() * collection.length)]\n}\n\nCodeNamesGame.prototype.ClickByCard = function(e, div, img) {\n if (e.target.tagName == 'INPUT')\n return\n\n img.style.display = img.style.display == 'none' ? '' : 'none'\n this.FindWords()\n}\n\nCodeNamesGame.prototype.MakeWordDiv = function(word, index) {\n let div = document.createElement('div')\n div.className = 'word-block'\n div.id = 'word-' + index\n\n let inner = this.MakeDiv('word-inner-block')\n let circle = this.MakeDiv('circle-block')\n circle.appendChild(this.MakeDiv('circle'))\n\n let rotated = this.MakeDiv('rotated', word)\n\n let input = document.createElement('input')\n input.type = 'text'\n input.value = word\n input.className = 'word-input'\n input.id = 'word-input-' + index\n input.addEventListener('input', () => rotated.innerHTML = input.value)\n input.addEventListener('change', () => rotated.innerHTML = input.value)\n\n let bottom = this.MakeDiv('bottom')\n\n bottom.appendChild(rotated)\n bottom.appendChild(document.createElement('hr'))\n bottom.appendChild(input)\n inner.appendChild(circle)\n inner.appendChild(bottom)\n div.appendChild(inner)\n\n let img = document.createElement('img')\n img.src = this.Choice(this.cardUrls[this.cells[index].status])\n img.className = 'card-img'\n img.id = 'card-img-' + index\n img.style.display = 'none'\n div.appendChild(img)\n\n div.addEventListener('mousedown', (e) => this.ClickByCard(e, div, img))\n return div\n}\n\nCodeNamesGame.prototype.GetRandomWords = function(n) {\n let words = new Set()\n\n for (let i = 0; i < n; i++) {\n let word = this.Choice(WORDS)\n\n while (words.has(word))\n word = this.Choice(WORDS)\n\n words.add(word)\n }\n\n return Array.from(words)\n}\n\nCodeNamesGame.prototype.InitWords = function() {\n let table = document.createElement('div')\n table.className = 'table'\n let words = this.GetRandomWords(CELL_COUNT * CELL_COUNT)\n\n for (let i = 0; i < CELL_COUNT; i++) {\n let tr = document.createElement('div')\n\n for (let j = 0; j < CELL_COUNT; j++) {\n let word = words[i * CELL_COUNT + j]\n let div = this.MakeWordDiv(word, i * CELL_COUNT + j)\n\n let td = document.createElement('div')\n td.className = 'cell'\n td.style.width = (100 / CELL_COUNT) + '%'\n\n td.appendChild(div)\n tr.appendChild(td)\n }\n\n table.appendChild(tr)\n }\n\n this.wordsBox.innerHTML = ''\n this.wordsBox.appendChild(table)\n this.FindWords()\n}\n\nCodeNamesGame.prototype.HideCardImages = function() {\n for (let i = 0; i < CELL_COUNT * CELL_COUNT; i++) {\n let img = document.getElementById('card-img-' + i)\n img.style.display = 'none'\n }\n\n this.FindWords()\n}\n\nCodeNamesGame.prototype.GetNonOpenedWords = function(status) {\n let words = []\n\n for (let i = 0; i < CELL_COUNT * CELL_COUNT; i++) {\n if (this.cells[i].status != status)\n continue\n\n if (document.getElementById('card-img-' + i).style.display != 'none')\n continue\n\n let word = document.getElementById('word-input-' + i).value\n words.push(word.toLowerCase())\n }\n\n return words\n}\n\nCodeNamesGame.prototype.InitEmbedding = function() {\n this.predictionsBox.style.display = ''\n this.word2vec = new Word2vec(EMBEDDING['embedding'], EMBEDDING['size'])\n this.FindWords()\n}\n\nCodeNamesGame.prototype.FindWords = function() {\n if (this.predictionsBox.style.display != '')\n return\n\n let status = document.getElementById('color-box').value\n let wordsCount = +document.getElementById('word-count-box').value\n\n let positive = this.GetNonOpenedWords(status)\n let negative = this.GetNonOpenedWords(status == RED_STATUS ? BLUE_STATUS : RED_STATUS)\n let empty = this.GetNonOpenedWords(EMPTY_STATUS)\n let killer = this.GetNonOpenedWords(GAME_OVER_STATUS)\n let words = positive.concat(negative).concat(empty).concat(killer)\n let weights = []\n\n for (let i = 0; i < positive.length; i++)\n weights.push(1 / positive.length)\n\n for (let i = 0; i < negative.length; i++)\n weights.push(-2 / negative.length)\n\n for (let i = 0; i < empty.length; i++)\n weights.push(-1 / empty.length)\n\n weights.push(-3)\n\n let top = this.word2vec.GetTopWordsCombination(words, weights, wordsCount)\n\n let topWordsBox = document.getElementById('top-words-box')\n topWordsBox.innerHTML = ''\n\n for (let node of top) {\n topWordsBox.innerHTML += node.word + ' (' + node.similarity + ')<br>'\n }\n}\n" } ]
5
justincohler/opioid-epidemic-study
https://github.com/justincohler/opioid-epidemic-study
93d84e13df199392e85bee59946686a2c7cf014a
4d351f5d950c8f967bd583d63e093120c63528d3
06cfde53b2b13447549041f5733319f8e5b85955
refs/heads/master
2020-04-16T21:16:56.581719
2019-03-21T23:39:30
2019-03-21T23:39:30
165,919,488
0
1
MIT
2019-01-15T20:34:22
2019-03-06T20:49:52
2019-03-10T00:23:46
HTML
[ { "alpha_fraction": 0.5450061559677124, "alphanum_fraction": 0.5474722385406494, "avg_line_length": 22.171428680419922, "blob_id": "886183b7aa541d44225f859718dc742cbeceefbf", "content_id": "9afb3b102c43f6c8d50e8424fcf867f75035c330", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1622, "license_type": "permissive", "max_line_length": 69, "num_lines": 70, "path": "/choropleth/typeahead.js", "repo_name": "justincohler/opioid-epidemic-study", "src_encoding": "UTF-8", "text": "/**\n * Source/Credit: https://twitter.github.io/typeahead.js/examples/\n * @param {List[String]} strs\n */\n\nvar substringMatcher = function(strs) {\n return function findMatches(q, cb) {\n q = q.toLowerCase();\n var matches, substringRegex;\n\n // an array that will be populated with substring matches\n matches = [];\n\n // regex used to determine if a string contains the substring `q`\n substrRegex = new RegExp(q, \"i\");\n\n // iterate through the pool of strings and for any string that\n // contains the substring `q`, add it to the `matches` array\n $.each(strs, function(i, str) {\n if (substrRegex.test(str.toLowerCase())) {\n matches.push(str);\n }\n });\n\n cb(matches);\n };\n};\n\nload_counties = new Promise(resolve => {\n resolve(d3.tsv(\"county_fips.tsv\"));\n});\n\nload_counties\n .then(data =>\n data\n .filter(d => d.State === \"WV\")\n .reduce((acc, d) => {\n acc[d.Name.toLowerCase()] = d.FIPS;\n return acc;\n })\n )\n .then(counties => {\n console.log(counties);\n $(\".typeahead\").typeahead(\n {\n hint: true,\n highlight: true,\n minLength: 1\n },\n {\n name: \"counties\",\n source: substringMatcher(Object.keys(counties))\n }\n );\n\n $(\".typeahead\").on(\"keydown\", function search(e) {\n // If \"Enter\" key pressed\n if (e.keyCode == 13) {\n county = $(this)\n .val()\n .toLowerCase();\n fips = counties[county];\n console.log(fips);\n if (fips) {\n selected_counties.add(fips);\n highlight_counties();\n }\n }\n });\n });\n" }, { "alpha_fraction": 0.5287865400314331, "alphanum_fraction": 0.5590788125991821, "avg_line_length": 23.977876663208008, "blob_id": "70d9a57292727a3b4620dea9f404a38f46cd5b3c", "content_id": "a7ba7b08a9841df49aabef1ccb4df458277ecdc7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5645, "license_type": "permissive", "max_line_length": 93, "num_lines": 226, "path": "/choropleth/choropleth.js", "repo_name": "justincohler/opioid-epidemic-study", "src_encoding": "UTF-8", "text": "/* \nSource/Credit: https://bl.ocks.org/adamjanes/6cf85a4fd79e122695ebde7d41fe327f \n\nThe above source served as the start for this SVG element in the larger visualization.\n*/\nasync function make_choropleth([us, chr]) {\n d3.select(\"#wide\")\n .append(\"svg\")\n .attr(\"id\", \"choropleth\")\n .attr(\n \"height\",\n params.choropleth.height +\n params.choropleth.margin.top +\n params.choropleth.margin.bottom\n )\n .attr(\n \"width\",\n params.choropleth.width +\n params.choropleth.margin.left +\n params.choropleth.margin.right\n );\n\n var projection = d3\n .geoMercator()\n .scale(8500)\n .center([-79.5, 39.5]);\n\n // Create a path generator.\n var path = d3.geoPath().projection(projection);\n\n const x = d3\n .scaleLinear()\n .domain([1, 10])\n .rangeRound([600, 860]);\n\n let choropleth = d3.select(\"#choropleth\");\n\n // County shapes\n choropleth\n .append(\"g\")\n .attr(\"class\", \"counties\")\n .selectAll(\"path\")\n .data(\n topojson.feature(us, us.objects.cb_2015_west_virginia_county_20m).features\n )\n .enter()\n .append(\"path\")\n .attr(\"d\", path)\n .attr(\"id\", d => {\n return \"poly-\" + d.properties.GEOID;\n });\n\n let cities = [\n {\n name: \"Charleston\",\n lat: -81.63,\n lon: 38.35,\n shift_x: -30,\n shift_y: -10\n },\n {\n name: \"Huntington\",\n lat: -82.45,\n lon: 38.42,\n shift_x: -10,\n shift_y: 25\n },\n {\n name: \"Parkersburg\",\n lat: -81.56,\n lon: 39.27,\n shift_x: 0,\n shift_y: 25\n },\n {\n name: \"Morgantown\",\n lat: -79.96,\n lon: 39.63,\n shift_x: -70,\n shift_y: 25\n },\n {\n name: \"Wyoming County\",\n lat: -81.56,\n lon: 37.63,\n shift_x: 0,\n shift_y: -10\n }\n ];\n\n cities.forEach(city => {\n if (city.name === \"Wyoming County\") {\n choropleth\n .append(\"rect\")\n .attr(\"x\", projection([city.lat, city.lon])[0])\n .attr(\"y\", projection([city.lat, city.lon])[1])\n .attr(\"width\", 8)\n .attr(\"height\", 8)\n .style(\"fill\", \"#f9dc5c\");\n } else {\n choropleth\n .append(\"circle\")\n .attr(\"cx\", projection([city.lat, city.lon])[0])\n .attr(\"cy\", projection([city.lat, city.lon])[1])\n .attr(\"r\", 4)\n .style(\"fill\", \"#f9dc5c\");\n }\n choropleth\n .append(\"text\")\n .attr(\"x\", city.shift_x + projection([city.lat, city.lon])[0])\n .attr(\"y\", city.shift_y + projection([city.lat, city.lon])[1])\n .classed(\"city-label\", true)\n .html(city.name);\n });\n\n return chr;\n}\n\nasync function update_choropleth(chr) {\n let choropleth = d3.select(\"#choropleth\");\n\n // Tooltips\n tip = d3\n .tip()\n .attr(\"class\", \"d3-tip\")\n .offset([-10, 0])\n .direction(\"n\")\n .html(function(d) {\n county = chr[d.properties.GEOID].county;\n state = chr[d.properties.GEOID].state;\n\n text = county + \", \" + state + \"<br/>OD Mortality Rate: \";\n text +=\n chr[d.properties.GEOID].od_mortality_rate == \"\"\n ? \"N/A\"\n : chr[d.properties.GEOID].od_mortality_rate;\n return text;\n });\n choropleth.call(tip);\n // County shapes\n choropleth\n .selectAll(\"path\")\n .on(\"mouseover\", function(d, i) {\n tip.show(d, this);\n\n d3.select(this).style(\"cursor\", \"pointer\");\n\n od_mortality_rate = chr[d.properties.GEOID].od_mortality_rate;\n\n pctile = ntile(MAX_STAT, od_mortality_rate, NTILES);\n\n d3.select(\"#bar-\" + pctile).attr(\"fill\", YELLOW);\n\n d3.select(\"#line-\" + d.properties.GEOID).classed(\"hoverLine\", true);\n })\n .on(\"mouseout\", d => {\n tip.hide(d, this);\n\n od_mortality_rate = chr[d.properties.GEOID].od_mortality_rate;\n pctile = ntile(MAX_STAT, od_mortality_rate, NTILES);\n\n d3.select(\"#line-\" + d.properties.GEOID).classed(\"hoverLine\", false);\n\n d3.select(\"#bar-\" + pctile)\n .transition()\n .duration(200)\n .attr(\"fill\", function(d) {\n return bucketColorScale(pctile);\n });\n })\n .on(\"click\", function(d) {\n od_mortality_rate = chr[d.properties.GEOID].od_mortality_rate;\n pctile = ntile(MAX_STAT, od_mortality_rate, NTILES);\n\n if (!selected_counties.has(d.properties.GEOID)) {\n /* CLICK ON */\n selected_counties.add(d.properties.GEOID);\n } else {\n /* CLICK OFF */\n selected_counties.delete(d.properties.GEOID);\n }\n\n highlight_counties();\n highlight_bars(chr);\n highlight_lines(chr);\n })\n .transition()\n .duration(1000)\n .attr(\"fill\", d => {\n fips = d.properties.GEOID;\n value =\n chr[fips] && chr[fips].od_mortality_rate != \"\"\n ? chr[fips].od_mortality_rate\n : 0;\n return colorScale(value);\n });\n\n // SOURCE\n choropleth\n .append(\"text\")\n .attr(\"class\", \"source\")\n .attr(\"x\", params.choropleth.width / 2 - 50)\n .attr(\"y\", params.choropleth.height - 50)\n .text(\"Source: CountyHealthRankings.org\");\n\n // Summary\n summary_x = params.choropleth.width / 2 - 10;\n summary_y = params.choropleth.height / 2 + 140;\n\n // West Virginia's Drug Overdose Mortality Rates per 100k skyrocketed between 2014 and 2018\n\n // Top-Four Cities Explanation\n choropleth\n .append(\"text\")\n .attr(\"class\", \"robotic\")\n .attr(\"x\", 20 + params.choropleth.margin.left)\n .attr(\"y\", 150 + params.choropleth.margin.top)\n .text(`Most Populous WV`);\n\n choropleth\n .append(\"text\")\n .attr(\"class\", \"robotic\")\n .attr(\"x\", 20 + params.choropleth.margin.left)\n .attr(\"y\", 175 + params.choropleth.margin.top)\n .text(`Cities Marked Below`);\n}\n" }, { "alpha_fraction": 0.5181818008422852, "alphanum_fraction": 0.5554545521736145, "avg_line_length": 21.4489803314209, "blob_id": "015069ce44e4d77bfcc9634997386d15749a9354", "content_id": "b38db4edd876e760fbb748627f68ee3d2a1db1ea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1100, "license_type": "permissive", "max_line_length": 54, "num_lines": 49, "path": "/choropleth/instructions.js", "repo_name": "justincohler/opioid-epidemic-study", "src_encoding": "UTF-8", "text": "window.addEventListener(\"load\", function() {\n new Promise(function(resolve) {\n setTimeout(() => resolve(), 500);\n }).then(show_year_info());\n});\n\nshow_year_info = () => {\n d3.select(\"#dropdownMenuButton\")\n .append(\"a\")\n .classed(\"instruction\", true)\n .append(\"span\")\n .attr(\"top\", \"55\")\n .attr(\"left\", \"-40\")\n .text(\"Jump to a given year\");\n\n setTimeout(() => {\n d3.selectAll(\".instruction\").remove();\n show_prediction_info();\n }, 3000);\n};\n\nshow_prediction_info = () => {\n d3.select(\"#animate\")\n .append(\"a\")\n .classed(\"instruction\", true)\n .append(\"span\")\n .attr(\"top\", \"55\")\n .attr(\"left\", \"-40\")\n .text(\"Click to animate 2014-2018 data\");\n\n setTimeout(() => {\n d3.selectAll(\".instruction\").remove();\n show_reset_info();\n }, 3000);\n};\n\nshow_reset_info = () => {\n d3.select(\"#reset\")\n .append(\"a\")\n .classed(\"instruction\", true)\n .append(\"span\")\n .attr(\"top\", \"55\")\n .attr(\"left\", \"-40\")\n .text(\"Click to de-select all selected counties\");\n\n setTimeout(() => {\n d3.selectAll(\".instruction\").remove();\n }, 3000);\n};\n" }, { "alpha_fraction": 0.6283618807792664, "alphanum_fraction": 0.6316218376159668, "avg_line_length": 22.596153259277344, "blob_id": "17dd1428bc349c8f94bd5bc990d7fad5a4253b0b", "content_id": "d49d6cbb287495729a13c1c2345fa9247896349c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1227, "license_type": "permissive", "max_line_length": 78, "num_lines": 52, "path": "/choropleth/toolbar.js", "repo_name": "justincohler/opioid-epidemic-study", "src_encoding": "UTF-8", "text": "/* \n Source/Credit: https://www.w3schools.com/html/html5_draganddrop.asp\n\n The above source offers a starting point for drag and drop of features\n into the visualization toolbar. \n\n TODO - This still requires implementation.\n\n*/\n\nregressors = [];\n\nfunction drag(event) {\n // console.log(event.target.id);\n let text = regressors.length == 0 ? event.target.id : \",\" + event.target.id;\n regressors.push(event.target.id);\n event.dataTransfer.setData(\"text\", text);\n event.dataTransfer.effectAllowed = \"copyMove\";\n event.dataTransfer.dropEffect = \"copy\";\n}\n\nregress_bkp = () => {\n d3.select(\"#calculator\").on(\"input\", () => {\n console.log(this.value);\n });\n\n regressor = \"FAKE\";\n switch (regressor) {\n case \"Unemployed\":\n console.log(\"Unemployed\");\n break;\n case \"Food_Insecure\":\n console.log(\"Food Insecure\");\n break;\n case \"Preventable_Hosp\":\n console.log(\"Preventable_Hosp\");\n break;\n case \"Graduation_Rate\":\n console.log(\"Graduation_Rate\");\n break;\n case \"Household_Income\":\n console.log(\"Household_Income\");\n break;\n case \"Limited_Access\":\n console.log(\"Limited_Access\");\n break;\n default:\n break;\n }\n\n return;\n};\n" }, { "alpha_fraction": 0.5342782139778137, "alphanum_fraction": 0.5576952695846558, "avg_line_length": 40.34394836425781, "blob_id": "3376f0ea66eb3bca2d3cd850287ee6466cdc66a5", "content_id": "5e20dd5f5034888389a48ea5b277ec40c569f783", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 6491, "license_type": "permissive", "max_line_length": 244, "num_lines": 157, "path": "/choropleth/index.html", "repo_name": "justincohler/opioid-epidemic-study", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html>\n <head>\n <link\n rel=\"stylesheet\"\n href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"\n integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\"\n crossorigin=\"anonymous\"\n />\n <link href=\"https://fonts.googleapis.com/css?family=Lato|Noto+Sans|Open+Sans\" rel=\"stylesheet\">\n <link rel=\"stylesheet\" href=\"./style.css\" />\n <meta charset=\"utf-8\" />\n </head>\n\n <body>\n <div class=\"container\">\n <div class=\"row title\">\n <h1>The Center of the US Opioid Epidemic: West Virginia</span></h1>\n </div>\n <div class=\"row menubar\">\n <div class=\"col-8\">\n <input class=\"typeahead\" id=\"calculator\" type=\"text\" placeholder=\"SEARCH for a county...\" />\n </div>\n <div class=\"col\">\n <div class=\"dropdown\">\n <button\n class=\"btn btn-primary dropdown-toggle\"\n type=\"button\"\n id=\"dropdownMenuButton\"\n data-toggle=\"dropdown\"\n aria-haspopup=\"true\"\n aria-expanded=\"false\"\n >\n Year\n </button>\n <div class=\"dropdown-menu\" aria-labelledby=\"dropdownMenuButton\">\n <a class=\"dropdown-item\" href=\"#2018\" onclick=\"reanimate(2018)\"\n >2018</a\n >\n <a class=\"dropdown-item\" href=\"#2017\" onclick=\"reanimate(2017)\"\n >2017</a\n >\n <a class=\"dropdown-item\" href=\"#2016\" onclick=\"reanimate(2016)\"\n >2016</a\n >\n <a class=\"dropdown-item\" href=\"#2015\" onclick=\"reanimate(2015)\"\n >2015</a\n >\n <a class=\"dropdown-item\" href=\"#2014\" onclick=\"reanimate(2014)\"\n >2014</a\n >\n </div>\n <button\n class=\"btn btn-secondary\"\n type=\"button\"\n id=\"animate\"\n onclick=\"auto_animate()\"\n >\n Animate\n </button>\n \n <button\n class=\"btn btn-primary\"\n type=\"button\"\n id=\"reset\"\n onclick=\"clear_selected()\"\n >\n Reset\n </button>\n </div>\n </div>\n </div>\n <div class=\"overmap\">\n <p>West Virginia, and specifically Wyoming County, has had among the highest drug OD mortality rates of any in the country. Click on individual counties or search for one in the search bar to explore county data in detail over time.</p>\n </div>\n <div class=\"row underneath\">\n <div class=\"row\" id=\"parent\">\n <div id=\"wide\"></div>\n <divid=\"narrow\">\n <div class=\"row\" id=\"upper\"></div>\n <div class=\"row\" id=\"lower\"></div>\n </div>\n </div>\n </div>\n <div id=\"footer\">\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col\">\n <h1>ABOUT</h1>\n <p>This project was created using the \n <a target=\"_blank\" href=\"http://www.countyhealthrankings.org/explore-health-rankings/rankings-data-documentation/national-data-documentation-2010-2017\">County Health Rankings</a> \n yearly datasets. While 2010-2018 were available for use, only 2014-2018 contained drug overdose mortality data, \n which originates from the <a target=\"_blank\" href=\"https://wonder.cdc.gov/\">CDC's WONDER</a> dataset. Therefore this project only displays 2014-2018 changes, inclusively.\n </p>\n <p>Accompanying this project is a static visualization portfolio that further visualizes the epidemic \n across the country and in West Virgina, which can be found <a target=\"_blank\" href=\"https://justincohler.github.io/opioid-epidemic-study\">here</a>.\n </p>\n <p>\n All source code can be found on <a target=\"_blank\" href=\"https://github.com/justincohler/opioid-epidemic-study/tree/master/choropleth\">GitHub</a>. \n Please give it a star if you find it useful!\n </p>\n </div>\n <div class=\"col\">\n <h1>ACKNOWLEDGEMENTS</h1> \n <p>This project would not have been possible without the help from <a href=\"https://github.com/alexcengler\">Alex Engler</a> and <a target=\"_blank\" href=\"https://github.com/mcnuttandrew\">Andrew McNutt</a>\n , whose feedback is reflected throughout this page. I would also like to thank the authors of the following D3 blocks and code samples for their guidance:\n <ul>\n <li><a target=\"_blank\" href=\"https://bl.ocks.org/adamjanes/6cf85a4fd79e122695ebde7d41fe327f\">Adam Janes</a></li>\n <li><a target=\"_blank\" href=\"https://codepen.io/zakariachowdhury/pen/JEmjwq\">Zakaria Chowdhury</a></li>\n <li><a target=\"_blank\" href=\"https://twitter.github.io/typeahead.js/examples/\">Typeahead.js Examples</a></li>\n </ul>\n </p> \n </div>\n </div>\n </div>\n </div>\n </div>\n\n <!-- d3 Libraries -->\n <script src=\"https://d3js.org/d3.v5.min.js\"></script>\n <script src=\"https://d3js.org/d3-scale-chromatic.v1.min.js\"></script>\n <script src=\"https://d3js.org/topojson.v2.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.9.1/d3-tip.min.js\"></script>\n <script src=\"https://d3js.org/d3-interpolate.v1.min.js\"></script>\n <script src=\"https://d3js.org/d3-geo-projection.v2.min.js\"></script>\n\n <!-- JQuery -->\n <script\n src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"\n integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\"\n crossorigin=\"anonymous\"\n ></script>\n <script\n src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"\n integrity=\"sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1\"\n crossorigin=\"anonymous\"\n ></script>\n <script\n src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"\n integrity=\"sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM\"\n crossorigin=\"anonymous\"\n ></script>\n\n <!-- Typeahead -->\n <script src=\"https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js\"></script>\n\n \n <!-- Visualization Scripts -->\n <script src=\"histogram.js\"></script>\n <script src=\"line.js\"></script>\n <script src=\"choropleth.js\"></script>\n <script src=\"toolbar.js\"></script>\n <script src=\"typeahead.js\"></script>\n <script src=\"globals.js\"></script>\n <script src=\"instructions.js\"></script>\n </body>\n</html>\n" }, { "alpha_fraction": 0.4990154802799225, "alphanum_fraction": 0.5151898860931396, "avg_line_length": 29.51931381225586, "blob_id": "adc8668e5a52d81e2eaac9f4a6c92765fe40336b", "content_id": "a1be77c388467426dca4558b02d82ac2889afa59", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7110, "license_type": "permissive", "max_line_length": 92, "num_lines": 233, "path": "/reverse_scatter/script.js", "repo_name": "justincohler/opioid-epidemic-study", "src_encoding": "UTF-8", "text": "/**\n * The format of this initial d3 v4 ScatterPlot utilized the following\n * repository for reference. Style structure in style.css also utilized\n * reference styles in:\n * \n * https://github.com/alexcengler/tanf-exploration\n */\nd3.queue()\n .defer(d3.json, 'data/rx_data.json')\n .awaitAll(function (error, results) {\n if (error) { throw error; }\n\n scatter = new ScatterPlot(results[0]);\n scatter.update(results[0]);\n });\n\nconst margin = {\n left: 75,\n right: 50,\n top: 125,\n bottom: 75,\n yaxis: 150,\n xaxis: 40,\n legendBox: 9\n};\n\nconst radius = 6;\nconst width = 800 - margin.left - margin.right;\nconst height = 550 - margin.top - margin.bottom;\nconst colors = {\n \"KADIAN\": \"#F9DC5c\", // YELLOW\n \"FENTANYL\": \"#55BCC9\", // BLUE\n \"OXYCODONE\": \"#0F7173\", // AQUA\n \"OXYCONTIN\": \"#FC4445\" // RED\n};\n\nfunction ScatterPlot(data) {\n\n var chart = this;\n\n chart.svg = d3.select(\"#chart1\")\n .append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n .append(\"g\")\n\n // Title\n chart.svg\n .append(\"text\")\n .attr(\"class\", \"title\")\n .attr(\"transform\", `translate(50, 50)`)\n .html(\"Oxycodone Appears to Most Closely Correlate Prescriptions to Reimbursements\")\n\n // Legend Line #1\n chart.svg\n .append(\"rect\")\n .attr(\"class\", \"legendBox\")\n .attr('x', margin.left)\n .attr('y', margin.top + margin.xaxis)\n .attr('fill', colors[\"OXYCODONE\"]);\n\n chart.svg\n .append(\"text\")\n .attr(\"class\", \"legendText\")\n .attr(\"x\", margin.left + 2 * margin.legendBox)\n .attr(\"y\", margin.top + margin.xaxis + margin.legendBox)\n .html(\"OXYCODONE\")\n\n // Legend Line #2\n chart.svg\n .append(\"rect\")\n .attr(\"class\", \"legendBox\")\n .attr('x', margin.left)\n .attr('y', margin.top + 1.5 * margin.xaxis)\n .attr('fill', colors[\"OXYCONTIN\"]);\n\n chart.svg\n .append(\"text\")\n .attr(\"class\", \"legendText\")\n .attr(\"x\", margin.left + 2 * margin.legendBox)\n .attr(\"y\", margin.top + 1.5 * margin.xaxis + margin.legendBox)\n .html(\"OXYCONTIN\")\n\n // Legend Line #3\n chart.svg\n .append(\"rect\")\n .attr(\"class\", \"legendBox\")\n .attr('x', margin.left)\n .attr('y', margin.top + 2 * margin.xaxis)\n .attr('fill', colors[\"FENTANYL\"]);\n\n chart.svg\n .append(\"text\")\n .attr(\"class\", \"legendText\")\n .attr(\"x\", margin.left + 2 * margin.legendBox)\n .attr(\"y\", margin.top + 2 * margin.xaxis + margin.legendBox)\n .html(\"FENTANYL\")\n\n // Legend Line #4\n chart.svg\n .append(\"rect\")\n .attr(\"class\", \"legendBox\")\n .attr('x', margin.left)\n .attr('y', margin.top + 2.5 * margin.xaxis)\n .attr('fill', colors[\"KADIAN\"]);\n\n chart.svg\n .append(\"text\")\n .attr(\"class\", \"legendText\")\n .attr(\"x\", margin.left + 2 * margin.legendBox)\n .attr(\"y\", margin.top + 2.5 * margin.xaxis + margin.legendBox)\n .html(\"KADIAN\");\n\n // SOURCE\n chart.svg\n .append(\"text\")\n .attr(\"class\", \"source\")\n .attr(\"x\", width - 3 * margin.left)\n .attr(\"y\", margin.top + height)\n .html(\"Source: Data.Medicaid.gov\");\n\n chart.xScale = d3.scaleLinear()\n .domain([0, 10000000])\n .range([width, margin.left])\n .nice();\n\n chart.yScale = d3.scaleLinear()\n .domain([0, 600])\n .range([0, height]);\n\n chart.xAxis = d3.axisTop(chart.xScale).ticks(5, \"s\");\n chart.yAxis = d3.axisRight(chart.yScale).ticks(5, \"s\");\n\n};\n\nScatterPlot.prototype.update = function (data) {\n\n let chart = this;\n chart.full = data.slice();\n chart.svg.selectAll(\".circ\").remove();\n\n chart.svg.append(\"g\")\n .attr(\"transform\", `translate(0, ${margin.top})`)\n .attr(\"class\", \"axis\")\n .call(chart.xAxis);\n\n chart.svg.append(\"g\")\n .attr(\"transform\", `translate(${width}, ${margin.top})`)\n .attr(\"class\", \"axis\")\n .call(chart.yAxis);\n\n chart.svg\n .append(\"text\")\n .attr(\"class\", \"yAxisLabel\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"x\", -((height) / 2 + margin.yaxis))\n .attr(\"y\", width + margin.right)\n .style(\"text-anchor\", \"middle\")\n .html(\"Total Amount Reimbursed ($ Millions)\");\n\n chart.svg\n .append(\"text\")\n .attr(\"class\", \"xAxisLabel\")\n .attr(\"x\", width / 2)\n .attr(\"y\", 0 + margin.top - margin.xaxis)\n .style(\"text-anchor\", \"middle\")\n .html(\"Number of Prescriptions\");\n\n chart.svg.selectAll(\".circ\")\n .data(chart.full, (d) => d[\"Group.1\"]).enter()\n .append(\"circle\")\n .attr(\"transform\", () => `translate(0, ${margin.top})`)\n .attr(\"class\", \"circ\")\n .attr(\"r\", 0)\n .attr(\"cx\", (d) => chart.xScale(d[\"Number of Prescriptions\"]))\n .attr(\"cy\", (d) => chart.yScale(d[\"Total Amount Reimbursed\"]))\n .attr(\"xValue\", (d) => d[\"Number of Prescriptions\"])\n .attr(\"yValue\", (d) => d[\"Total Amount Reimbursed\"])\n .style(\"fill\", (d) => colors[d[\"Drug Name\"]])\n .style(\"stroke\", (d) => colors[d[\"Drug Name\"]])\n .on(\"mouseover\", function (d, i) {\n\n let x = this.cx.baseVal.value - margin.left - 10;\n let y = this.cy.baseVal.value + margin.top - 15;\n let xValue = this.getAttribute(\"xValue\")\n let yValue = this.getAttribute(\"yValue\")\n let id = `i${Math.trunc(xValue)}-${Math.trunc(yValue)}`;\n\n // Bump up circle size\n d3.select(this)\n .transition()\n .duration(100)\n .attr(\"r\", radius * 2);\n\n // Hover Tooltips\n chart.svg\n .append(\"text\")\n .attr(\"x\", x)\n .attr(\"y\", y - 8)\n .attr(\"id\", `${id}-Prescriptions`)\n .attr(\"class\", \"hoverLabel\")\n .html(`# Prescriptions: ${Number(xValue).toLocaleString()}`);\n\n chart.svg\n .append(\"text\")\n .attr(\"x\", x)\n .attr(\"y\", y)\n .attr(\"id\", `${id}-Reimbursements`)\n .attr(\"class\", \"hoverLabel\")\n .html(`$ Reimbursed: ${Math.trunc(Number(yValue)).toLocaleString()}M`);\n })\n .on(\"mouseout\", function (d, i) {\n let xValue = this.getAttribute(\"xValue\")\n let yValue = this.getAttribute(\"yValue\")\n let id = `i${Math.trunc(xValue)}-${Math.trunc(yValue)}`;\n\n\n d3.select(this)\n .transition()\n .duration(500)\n .attr(\"r\", radius);\n\n console.log(`Deleting ${id}`);\n chart.svg.selectAll(`#${id}-Prescriptions`)\n .remove();\n chart.svg.selectAll(`#${id}-Reimbursements`)\n .remove();\n })\n .transition()\n .delay(function (d, i) { return (i * 50) })\n .duration(500)\n .attr(\"r\", radius);\n};" }, { "alpha_fraction": 0.519810140132904, "alphanum_fraction": 0.5378857254981995, "avg_line_length": 24.47441864013672, "blob_id": "65094a7c59b0df8451080c7853b3407c37cdb962", "content_id": "bcdf51fe78fef54831f66df342743e3ade0b8248", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5477, "license_type": "permissive", "max_line_length": 81, "num_lines": 215, "path": "/choropleth/line.js", "repo_name": "justincohler/opioid-epidemic-study", "src_encoding": "UTF-8", "text": "/* \nSource/Credit: https://codepen.io/zakariachowdhury/pen/JEmjwq\n\nThe above source was invaluable in getting a starting point for how to create the\nmany elements involved in the below line graph (the lines themselves, the \ndata points as circles, the informative text revealed on hover, etc.)\n\n*/\nasync function make_line() {\n /* Scale */\n var xScale = d3\n .scaleLinear()\n .domain([2014, 2018])\n .range([0, params.line.width - params.line.margin.left]);\n\n var yScale = d3\n .scaleLinear()\n .domain([0, MAX_STAT])\n .range([params.line.height - params.line.margin.top, 0]);\n\n /* Add SVG */\n var svg = d3\n .select(\"#lower\")\n .append(\"svg\")\n .attr(\"id\", \"linePlot\")\n .attr(\"width\", params.line.width + params.line.margin.left)\n .attr(\"height\", params.line.height + params.line.margin.top)\n .append(\"g\")\n .attr(\n \"transform\",\n `translate(${params.line.margin.left}, ${params.line.margin.top})`\n );\n\n let lines = svg.append(\"g\").attr(\"class\", \"lines\");\n\n /* Add Axis into SVG */\n var xAxis = d3\n .axisBottom(xScale)\n .ticks(5)\n .tickFormat(d3.format(\"d\"));\n\n svg\n .append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\n \"transform\",\n `translate(0, ${params.line.height - params.line.margin.top})`\n )\n .call(xAxis);\n}\n\nasync function update_line(chr) {\n let line_data = {};\n\n let lines = d3.selectAll(\".lines\");\n\n let svg = d3.select(\"#linePlot\");\n\n /* Scale */\n var xScale = d3\n .scaleLinear()\n .domain([2014, 2018])\n .range([0, params.line.width - params.line.margin.left]);\n\n var yScale = d3\n .scaleLinear()\n .domain([0, MAX_STAT])\n .range([params.line.height - params.line.margin.top, 0]);\n\n /* Add line into SVG */\n var line = d3\n .line()\n .x(d => xScale(d.year))\n .y(d => yScale(d.od_mortality_rate));\n\n Object.values(chr).map(d => {\n if (d.county in line_data) {\n line_data[d.county].push({\n year: d.year,\n county: d.county,\n od_mortality_rate: d.od_mortality_rate,\n fips: d.FIPS\n });\n } else {\n line_data[d.county] = [\n {\n year: d.year,\n county: d.county,\n od_mortality_rate: d.od_mortality_rate,\n fips: d.FIPS\n }\n ];\n }\n });\n\n final_data = [];\n Object.keys(line_data).map(key => {\n obj = {\n name: key,\n values: line_data[key]\n };\n final_data.push(obj);\n });\n\n final_data = final_data.filter(d => d.name != \"undefined\");\n\n lines\n .selectAll(\".line-group\")\n .data(final_data)\n .enter()\n .append(\"g\")\n .attr(\"class\", \"line-group\")\n .on(\"mouseover\", function(d, i) {\n svg\n .append(\"text\")\n .attr(\"class\", \"title-text\")\n .style(\"fill\", colorScale(d.values.slice(-1)[0].od_mortality_rate))\n .text(d.name)\n .attr(\"text-anchor\", \"middle\")\n .attr(\"x\", params.line.width / 2)\n .attr(\"y\", 25);\n })\n .on(\"mouseout\", function(d) {\n svg.select(\".title-text\").remove();\n })\n .append(\"path\")\n .attr(\"class\", \"line\")\n .attr(\"id\", d => (\"line-\" + d.values.slice(-1)[0].fips).toLowerCase())\n .on(\"mouseover\", function(d) {\n d3.selectAll(\".line\").style(\"opacity\", 0.3);\n d3.selectAll(\".circle\").style(\"opacity\", 0.3);\n d3.select(this)\n .style(\"opacity\", 0.9)\n .style(\"stroke-width\", \"5px\")\n .style(\"cursor\", \"pointer\");\n })\n .on(\"mouseout\", function(d) {\n d3.selectAll(\".circle\").style(\"opacity\", 0.9);\n d3.select(this)\n .transition()\n .duration(500)\n .style(\"opacity\", 0.3)\n .style(\"stroke-width\", \"1\")\n .style(\"cursor\", \"none\");\n })\n .transition()\n .duration(2000)\n .attr(\"d\", d => line(d.values))\n .style(\"stroke\", (d, i) =>\n colorScale(d.values.slice(-1)[0].od_mortality_rate)\n )\n .style(\"opacity\", 0.3);\n\n /* Add circles in the line */\n lines.selectAll(\"circle-group\").remove();\n lines.selectAll(\"circle\").remove();\n\n lines\n .selectAll(\"circle-group\")\n\n .data(final_data)\n .enter()\n .append(\"g\")\n .style(\"fill\", d => colorScale(d.values.slice(-1)[0].od_mortality_rate))\n .style(\"fill-opacity\", 0.6)\n .style(\"stroke-opacity\", 1.0)\n .style(\"stroke\", d => colorScale(d.values.slice(-1)[0].od_mortality_rate))\n .selectAll(\"circle\")\n .data(d => d.values)\n .enter()\n .append(\"g\")\n .attr(\"class\", \"circle\")\n .on(\"mouseover\", function(d) {\n d3.select(this)\n .style(\"cursor\", \"pointer\")\n .append(\"text\")\n .attr(\"class\", \"text\")\n .text(`${d.od_mortality_rate}`)\n .attr(\"x\", d => xScale(d.year) + 5)\n .attr(\"y\", d => yScale(d.od_mortality_rate) - 10);\n })\n .on(\"mouseout\", function(d) {\n d3.select(this)\n .style(\"cursor\", \"none\")\n .transition()\n .duration(500)\n .selectAll(\".text\")\n .remove();\n })\n .append(\"circle\")\n .attr(\"cx\", d => xScale(d.year))\n .attr(\"cy\", d => yScale(d.od_mortality_rate))\n .attr(\"r\", 5)\n .style(\"fill\", d => {\n try {\n return d.year == YEAR\n ? YELLOW\n : colorScale(d.values.slice(-1)[0].od_mortality_rate);\n } catch {\n return d;\n }\n })\n .on(\"mouseover\", function(d) {\n d3.select(this)\n .transition()\n .duration(250)\n .attr(\"r\", 10);\n })\n .on(\"mouseout\", function(d) {\n d3.select(this)\n .transition()\n .duration(250)\n .attr(\"r\", 5);\n });\n}\n" }, { "alpha_fraction": 0.5469460487365723, "alphanum_fraction": 0.5758054852485657, "avg_line_length": 20.900432586669922, "blob_id": "2e24d4ebfe4f3be9d217d1565b58e51101d85c5a", "content_id": "fd878df14eaca5ae618d6ec114b6211eb6f0797b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5059, "license_type": "permissive", "max_line_length": 79, "num_lines": 231, "path": "/choropleth/globals.js", "repo_name": "justincohler/opioid-epidemic-study", "src_encoding": "UTF-8", "text": "const RED = \"#FC4445\";\nconst BLUE = \"#5E2BFF\";\nconst YELLOW = \"#F9DC5c\";\nconst AQUA = \"#0F7173\";\nconst LIGHT_GREEN = \"#56E39F\";\nconst ORANGE = \"#F18F01\";\nconst BRIGHT_GREEN = \"#4CB944\";\nconst WHITE = \"#CAFAFE\";\nconst SKY = \"#55BCC9\";\nconst MIDNIGHT = \"#0B132B\";\nconst NTILES = 20;\nconst MAX_STAT = 93; // Maximum value of OD Mortality Rate\n\n/**\n * SVG Size Parameters\n */\nconst params = {\n choropleth: {\n height: 740,\n width: 900,\n margin: { top: 20, right: 0, bottom: 20, left: 20 }\n },\n histogram: {\n height: 300,\n width: 400,\n margin: { top: 20, right: 20, bottom: 30, left: 20 }\n },\n line: {\n height: 300,\n width: 400,\n margin: { top: 20, right: 20, bottom: 20, left: 20 }\n }\n};\nconst colorScale = d3\n .scaleLinear()\n .domain([0, 82])\n .range([AQUA, RED]);\nconst bucketColorScale = d3\n .scaleLinear()\n .domain([0, NTILES])\n .range([AQUA, RED]);\n\nvar YEAR = 2014;\n\nlet selected_counties = new Set();\nlet promises = [\n d3.json(\"wv_county_topo.json\"),\n d3.csv(\"./od_2014_2018_wv.csv\", function(d) {\n return {\n FIPS: d.FIPS,\n year: +d.Year,\n od_mortality_rate: +d[\"Drug Overdose Mortality Rate\"],\n county: d.County,\n state: d.State\n };\n })\n];\n\nfilter_year = ([geojson, chr, year]) => {\n console.log(\"YEAR:\", year);\n fips_wise = chr\n .filter(d => d.year === year)\n .reduce(function(obj, d) {\n obj[d.FIPS] = {\n state: d.state,\n county: d.county,\n od_mortality_rate: d.od_mortality_rate\n };\n return obj;\n });\n return [geojson, fips_wise];\n};\n/**\n * Return the maimum value of the given data object's value argument.\n *\n * @param {} data\n * @param {} arg\n */\narg_max = (data, arg) => {\n const max = d3.max(Object.values(data), d => {\n return d[arg];\n });\n\n return max;\n};\n/**\n * Return the NTILE for a given data point.\n *\n * @param {} max\n * @param {} val\n * @param {} buckets=100\n */\nntile = (max, val, buckets = 100) => Math.trunc((val / max) * buckets);\n\n/**\n * Read GeoJSON and CHR data, then populate all SVG plots.\n *\n * The below line plot utilizes all years' data.\n * The below histogram and choropleth use a given year's data.\n *\n * @param {} year=2018\n */\nrender = (year = 2014) => {\n Promise.all(promises)\n .then(([geojson, chr]) => {\n make_histogram();\n make_choropleth([geojson, chr]);\n make_line();\n return [geojson, chr];\n })\n .then(([geojson, chr]) => {\n update_line(chr);\n return filter_year([geojson, chr, year]);\n })\n .then(([geojson, chr]) => {\n update_choropleth(chr);\n update_histogram(chr);\n });\n};\n/**\n * Update the line plot, choropleth, and histogram\n * for the given year.\n *\n * @param {} year\n */\nreanimate = year => {\n YEAR = +year;\n Promise.all(promises)\n .then(([geojson, chr]) => {\n update_line(chr);\n highlight_lines(chr);\n return filter_year([geojson, chr, year]);\n })\n .then(([geojson, chr]) => {\n animate_histogram(chr);\n update_choropleth(chr);\n highlight_counties();\n highlight_bars(chr);\n });\n};\n\n/**\n * Sweep through years from 2014 to 2018 across charts.\n */\nanimate_years = () => {\n if (!AUTOPLAY) {\n return;\n }\n reanimate(YEAR);\n setTimeout(() => {\n YEAR = YEAR === 2018 ? 2014 : YEAR + 1;\n animate_years();\n }, 1500);\n};\n\nAUTOPLAY = false;\n\nauto_animate = () => {\n if (!AUTOPLAY) {\n AUTOPLAY = true;\n d3.select(\"#animate\").text(\"Stop\");\n animate_years();\n } else {\n AUTOPLAY = !AUTOPLAY;\n d3.select(\"#animate\").text(\"Animate\");\n }\n};\n\nrender();\n\n/**\n * Remove all selected_counties and reanimate\n */\nclear_selected = () => {\n selected_counties.clear();\n reanimate(YEAR);\n};\n\n/**\n * Highlight all selected counties on choropleth.\n */\nhighlight_counties = () => {\n d3.selectAll(\".counties path\").classed(\"inactiveCounty\", d => {\n if (selected_counties.size === 0) {\n return false;\n } else {\n return !selected_counties.has(d.properties.GEOID);\n }\n });\n};\n\n/**\n * Given the selected county set, higlight the associated bars for\n * each time interval.\n */\nhighlight_bars = chr => {\n d3.selectAll(\".bar\").classed(\"inactiveCounty\", d => {\n selected_buckets = new Set();\n selected_counties.forEach(selected_county => {\n pctile = ntile(MAX_STAT, chr[selected_county].od_mortality_rate, NTILES);\n selected_buckets.add(pctile);\n });\n if (selected_buckets.size === 0) {\n return false;\n } else {\n return !selected_buckets.has(d.bucket);\n }\n });\n};\n\n/**\n * Given the selected county set, highlight the associated lines for\n * each time interval\n */\nhighlight_lines = chr => {\n d3.selectAll(\".line\")\n .classed(\"activeLine\", d => {\n if (selected_counties.size === 0) {\n return false;\n } else {\n return selected_counties.has(d.values.slice(-1)[0].fips);\n }\n })\n .classed(\"inactiveLine\", d => {\n if (selected_counties.size === 0) {\n return false;\n } else {\n return !selected_counties.has(d.values.slice(-1)[0].fips);\n }\n });\n};\n" }, { "alpha_fraction": 0.612738847732544, "alphanum_fraction": 0.6165605187416077, "avg_line_length": 30.440000534057617, "blob_id": "8a1f4e05e2b1ee538d5c9eddf9f26c350cca60ef", "content_id": "11ba5b3d6850473fb9489314dc933fc4c47b6889", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 785, "license_type": "permissive", "max_line_length": 72, "num_lines": 25, "path": "/choropleth/scripts/convert_fips.py", "repo_name": "justincohler/opioid-epidemic-study", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport json\n\ndef write_county_json():\n tsv = pd.read_csv(\"../data/county_fips.tsv\", sep='\\t')\n tsv = tsv[[\"FIPS\", \"Name\"]]\n print(tsv.head())\n county_json = json.loads(tsv.to_json())\n print(county_json)\n\n with open('county_fips.json', 'w') as outfile: \n json.dump(county_json, outfile)\n\ndef write_od_distribution_json():\n csv = pd.read_csv(\"../data/county_health_rankings.csv\")\n csv = csv[[\"FIPS\", \"Drug Overdose Mortality Rate\"]]\n max_od = csv[\"Drug Overdose Mortality Rate\"].max()\n print(max_od)\n\n csv[\"pctile\"] = (csv[\"Drug Overdose Mortality Rate\"] / max_od * 100)\n csv[\"pctile\"] = pd.to_numeric(csv[\"pctile\"], downcast=\"unsigned\") \n print(csv.tail())\n\nif __name__ == \"__main__\":\n write_od_distribution_json()" }, { "alpha_fraction": 0.5068492889404297, "alphanum_fraction": 0.5068492889404297, "avg_line_length": 72, "blob_id": "9da3270ee883f17856bd7dbf3c83d68c238a239e", "content_id": "5a6ab891b69fa677c97b2406889bcfd682bcc11a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 292, "license_type": "permissive", "max_line_length": 123, "num_lines": 4, "path": "/resources/resources.md", "repo_name": "justincohler/opioid-epidemic-study", "src_encoding": "UTF-8", "text": "|Description | Site |\n|------------|----------------------------------------|\n|Bump Chart | https://www.r-bloggers.com/bump-chart/ |\n|Recession Bars | https://www.r-bloggers.com/use-geom_rect-to-add-recession-bars-to-your-time-series-plots-rstats-ggplot/ |\n" } ]
10
jeffcheung2015/gallery_django_reactjs
https://github.com/jeffcheung2015/gallery_django_reactjs
4660945426e1c8b6fa6b94e8ee6db1d33d97c47a
b7bf2587de55bef8f7aa581929d78caaa937317e
9ba77a24f9a180d96ecc8cecfad114e2facc06cd
refs/heads/master
2022-03-20T07:14:19.062215
2019-08-27T10:16:14
2019-08-27T10:16:14
204,675,737
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6998977661132812, "alphanum_fraction": 0.7060326933860779, "avg_line_length": 38.119998931884766, "blob_id": "e68f80f193a4ed1b364ac7d0128c2d88229bd101", "content_id": "81002a98020102c66ec5385907ffc7902880153b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1956, "license_type": "no_license", "max_line_length": 93, "num_lines": 50, "path": "/backend/backend/urls.py", "repo_name": "jeffcheung2015/gallery_django_reactjs", "src_encoding": "UTF-8", "text": "\"\"\"backend URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/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\n\n# from customers import views\nfrom django.conf.urls import url\nfrom gallery import views\nfrom rest_framework_simplejwt import views as jwt_views\nfrom django.conf import settings\nfrom django.contrib.staticfiles.urls import static\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n\n path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),\n path('api/token/verify/', jwt_views.TokenVerifyView.as_view(), name='token_verify'),\n\n url(r'^getuser$', views.get_user),\n url(r'^signup$', views.user_signup),\n url(r'^login$', views.user_login),\n url(r'^logout$', views.user_logout),\n\n path('getimage/', views.get_image),\n # path('getuserimage/<int:user_id>', views.get_imgs_owned_by_user),\n path('gettags/', views.get_tags),\n path('api/upsert', views.upsert_image),\n path('api/updateuser', views.update_user),\n path('api/updateavatar', views.update_avatar),\n\n\n] + staticfiles_urlpatterns() + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n# url(r'^api/customers/$', views.customers_list),\n# url(r'^api/customers/(?P<pk>[0-9]+)$', views.customers_detail),\n# url(r'^api/gallery/(?P<pageNo>[0-9]+)$', views.image_page),\n" }, { "alpha_fraction": 0.6628788113594055, "alphanum_fraction": 0.6628788113594055, "avg_line_length": 25.399999618530273, "blob_id": "f858035a8cb571da3973883d805b454ba9352ace", "content_id": "9c5d83c4adffceab71dfbbfdf4ac47e0e22d6729", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 528, "license_type": "no_license", "max_line_length": 75, "num_lines": 20, "path": "/backend/gallery/forms.py", "repo_name": "jeffcheung2015/gallery_django_reactjs", "src_encoding": "UTF-8", "text": "from django import forms\nfrom .models import Image, Profile\nfrom django.contrib.auth.models import User\nfrom django.db import models\n\nclass UpsertImageForm(forms.ModelForm):\n class Meta:\n model = Image\n fields = [\"image_name\", \"image_desc\", \"image_file\", \"user\", \"tags\"]\n\nclass UpdateUserForm(forms.ModelForm):\n class Meta:\n model = User\n fields = [\"email\", \"password\"]\n\n\nclass UpdateAvatarForm(forms.ModelForm):\n class Meta:\n model = Profile\n fields = [\"avatar\", \"last_edit\"]\n" } ]
2
LeeHanYeong/CI-Test
https://github.com/LeeHanYeong/CI-Test
690058fe1f149e7451f10f7f8f76db6928b9d1f7
0241a3f5328c7c896bd8abdb16281a44a0fdebe2
d77f38bfdf6994de7afb0e67d758b9fe12ef22c7
refs/heads/master
2020-03-06T16:43:38.202983
2018-03-27T12:39:10
2018-03-27T12:39:10
126,978,115
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.680672287940979, "alphanum_fraction": 0.6974790096282959, "avg_line_length": 18.83333396911621, "blob_id": "a5beef3455a3c3a88e55843af74b67b4bee60353", "content_id": "7d0499fd75c2cdebc68568f62456cb5928251311", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 119, "license_type": "no_license", "max_line_length": 32, "num_lines": 6, "path": "/app/ft/tests.py", "repo_name": "LeeHanYeong/CI-Test", "src_encoding": "UTF-8", "text": "from django.test import TestCase\n\n\nclass SampleTest(TestCase):\n def test_fail(self):\n self.assertEqual(2, 1)\n" } ]
1
ajhoward7/Machine_Learning
https://github.com/ajhoward7/Machine_Learning
489ca3fb78fdcea3ccbd8954f73aa067cfb546f9
a80dca71683c1271fa5057525af5bb33c7243715
0172837a9d4d06f13003169c4db4fdfc2f87f38d
refs/heads/master
2021-08-14T08:45:09.526328
2017-11-15T05:23:25
2017-11-15T05:23:25
109,067,609
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8415841460227966, "alphanum_fraction": 0.8415841460227966, "avg_line_length": 66.33333587646484, "blob_id": "8d138e685258ebc09b7923918b79923cc9111d0c", "content_id": "21ac4749472d94fd498368d4782e07239510aa74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 202, "license_type": "no_license", "max_line_length": 181, "num_lines": 3, "path": "/README.md", "repo_name": "ajhoward7/Machine_Learning", "src_encoding": "UTF-8", "text": "# Machine Learning\n\nThis repository is aimed at providing a collection of theoretical notes and implementations of Machine Learning and Deep Learning algorithms, within the appropriate sub-directories.\n" }, { "alpha_fraction": 0.6782874464988708, "alphanum_fraction": 0.6939828991889954, "avg_line_length": 45.87482452392578, "blob_id": "66e93d51199a6dde143a5efff736497200568c05", "content_id": "403dd03656fc6fbdf95dca43f00a3875c8ccf776", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 33738, "license_type": "no_license", "max_line_length": 639, "num_lines": 719, "path": "/Regression_Project/1-CaseStudy-BusinessReport.Rmd", "repo_name": "ajhoward7/Machine_Learning", "src_encoding": "UTF-8", "text": "---\ntitle: \"Case Study Business Report\"\nauthor: \"Tim Lee, Taylor Pellerin, Jake Toffler, Ian Smeenk, Alex Howard\"\ndate: \"10/4/2017\"\noutput: \n pdf_document:\n toc: true\n toc_depth: 1\n---\n\n```{r setup, include=FALSE}\nrm(list=ls()) # removes all objects from the environment\ncat(\"\\014\") # clears the console\nlibrary(tidyverse)\nlibrary(magrittr)\nlibrary(dplyr)\nlibrary(glmnet)\nlibrary(caret)\nlibrary(knitr)\nlibrary(cvTools)\nlibrary(caTools)\nlibrary(ggplot2)\nlibrary(car)\nlibrary(MASS)\nlibrary(olsrr)\noptions(\"scipen\" = 10)\n# force default function masking \nselect <- dplyr::select\nknitr::opts_chunk$set(echo = FALSE, cache=FALSE, eval=TRUE, warning =FALSE, fig.height =4, tidy.opts = list(width.cutoff = 60), tidy=TRUE)\nsource('Part2-case_study_common_funcs.R')\n\n\n\nmultiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {\n library(grid)\n\n # Make a list from the ... arguments and plotlist\n plots <- c(list(...), plotlist)\n\n numPlots = length(plots)\n\n # If layout is NULL, then use 'cols' to determine layout\n if (is.null(layout)) {\n # Make the panel\n # ncol: Number of columns of plots\n # nrow: Number of rows needed, calculated from # of cols\n layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),\n ncol = cols, nrow = ceiling(numPlots/cols))\n }\n\n if (numPlots==1) {\n print(plots[[1]])\n\n } else {\n # Set up the page\n grid.newpage()\n pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))\n\n # Make each plot, in the correct location\n for (i in 1:numPlots) {\n # Get the i,j matrix positions of the regions that contain this subplot\n matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))\n\n print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,\n layout.pos.col = matchidx$col))\n }\n }\n}\n\n```\n\n---\n\n```{r fig.show=\"hide\", include=FALSE}\ndf <- read.csv('~/Documents/MSAN/04-601-LinRegression/Project/housing.txt', stringsAsFactors = FALSE)\n\ndf_clean <-df %>% \n Years_to_Age %>% \n SwapToFactor %>% \n DealWithNulls %>% \n QualityToNumeric %>% \n ImputeValues %>% \n RoofMatlToDollars %>% \n RemoveCollinear %>% \n #ExcludeFeatures_90Plus %>% # this was to improve the score \n AreaToLogArea %>% \n AreaToLogAreaExcluded90 %>% \n Exclude_Outliers\n\n```\n\n# Introduction:\n\nWe have conducted in-depth regression analysis on a set of data from 1400+ house sales in Ames, Iowa with 80+ associated features. Our report into this data focuses on 3 key sections:\n\n- Part 1A: Dominant Features related to different housing prices\n- Part 1B: Top Recommendations for Morty, a new home seller\n- Part 2B: Construction of a robust predictive model to be used going forward\n\n# Task 1A: Explanatory Modeling\n\n###Macro Data Summary:\n\n|Field| Value|\n|----|----|\n|Min Year| 2006|\n|Max Year| 2010|\n|Min Sale Price| $34,900|\n|Median Sale Price| $163,000|\n|Max Sale Price| $625,000|\n|Number of Neighborhoods| 25|\n|Number of Rows (houses)| 1460|\n|Number of Rows (houses), excluding outliers| 1349|\n\n```{r}\ndf %>% \n select(Neighborhood, SalePrice) %>% \n ggplot( aes(x=Neighborhood, y=SalePrice)) + \n geom_jitter() +\n labs(x='NeighborHoods', y='SalePrice', title='Sale Price by Neighborhood') +\n theme(axis.text.x = element_text(angle=-45, hjust=0, size=9), axis.text.y = element_text(size=9)) + theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n\n```\n\n###Dataset Considerations:\n\n- **Simplicity**: While it is enlightening to know exactly how big a pool is in square feet, the scarcity of pools makes this distinguishing detail unnecessary. A number of variables were simplified due to scarcity, or reduce the complexity of the problem. \n\n- **Subjective to numeric**: how does one rate the condition of a basement? What is the definition of good? A large number of the features in the data covering “conditions” of walls, kitchens and exteriors were recorded in phrases such as “excellent” to “poor”. Many of these variables were codified with integer scores to simplify the model.\n\n- **Duplicate information**: Being overly detailed, there were many fields that recorded the same information, such as number of bedrooms upstairs, number of bedrooms downstairs, and then total bedrooms. There were similar fields recording square footage that were functionally added for sales sake, but these introduce collinearity problems for statistical analysis. Some of these fields were examined and dropped completely from the analysis.\n\n- **Missing or Null Values**: with manual data collection or with the house not having all the features that in the database structure, empty fields are inevitable. These issues were either translated into something like “no garage”, or were given the correct value based on the description in the data dictionary.\n\n- **Outliers**: every generation has its Lebron James, and this housing dataset is no different. It contained a few massive outliers that were identified using DFFITs methods and were dealt with accordingly in the respective explanatory and predictive sections.\n\n- **Normality Considerations**: for the method ordinary least squares regression to apply, a few statistical assumptions must be met. Y must be normally distributed, and the resulting residual (Y_predicted - Y_true) should be normal as well. This test was performed using Kolmogorov_Smirnov. It turns out that sale price distribution is skewed left (figure left). After running a Box-Cox analysis, it was determined to use the log of price as the baseline (right)\n\n```{r}\nh1<- df %>% select(SalePrice) %>% ggplot(aes(x=SalePrice)) + geom_histogram(bins=40) + labs(title='Histogram of Sale Price') +\n theme(axis.text.x = element_text(size=9), axis.text.y = element_text(size=9))+ theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n\nh2<- df %>% select(SalePrice) %>% ggplot(aes(x=log(SalePrice))) + geom_histogram(bins=40) + labs(title='Histogram of Log(Sale Price)')+\n theme(axis.text.x = element_text(size=9), axis.text.y = element_text(size=9))+ theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n\nmultiplot(h1,h2, cols=2)\n\n```\n*Figure: SalePrice .vs Log(SalePrice) comparison of counts*\n\n\\pagebreak\n\n## Fitting a Linear Model: Features Analysis \n\nThe previously described dataset was analyzed use R Studio, and a linear model (no regularization) was fit. The following is a summary of the optimal model.\n\nLinear Model Summary:\n|Metric | Score|\n|--|---|\n|R^2 |0.962|\n|MSE (log sale) | 0.0052|\n|MSE(saleprice) | 237,269,622|\n|RMSE(saleprice) | 15,403|\n\n### Important Features\nAfter data transformation and cleaning, a Ordinary Least Squares (OLS) model was fit onto the data. A statistical analysis of the fields show the following fields as the top significant features:\n\n|Sig. Rank|Field|Description|\n|---|------------------|-----------------------------------------------------------------------|\n|1|OverallCond|Rates the overall condition of the house|\n|2|OverallQual|Rates the overall material and finish of the house|\n|3|LotArea|Lot size in square feet|\n|4|GrLivArea|Above grade (ground) living area square feet|\n|5|Functional|Home functionality (Assume typical unless deductions are warranted)|\n|6|YearBuilt|Original construction date|\n|7|Condition1Norm|Condition1: Proximity to various conditions, specifically if near a major railway. Norm = Normal|\n|8|BsmtExposure|BsmtExposure: Refers to walkout or garden level walls|\n|9|MSZoningRL|Residential Low Density Zoning|\n|10|BsmtFullBath|How many Full baths in the basement|\n|11|MSZoningFV|Floating Village Residential|\n|12|MSZoningRM|Residential Medium Density Zoning|\n|13|MSZoningRH|Residential High Density Zong|\n|14|Condition1PosN|Near positive feature such as parks|\n|15|GarageCars|How many cars fit in the garage|\n|16|MasVnrTypeNone|Masonry veneer type|\n|17|Fireplaces|How many fireplaces the house has|\n|18|BsmtFinSF1|Type 1 finished square feet|\n|19|BsmtQual|BsmtQual: Evaluates the height of the basement|\n\nFor full details of parameter estimates, see the extended report.\n\n### Trends between Sale price and Important Features:\n\nSelect features from the above list of significant features were plotted versus sale price below:\n\n```{r fig.show=\"hide\", include=FALSE}\n# data for EDA plots\ndf <- read.csv('~/Documents/MSAN/04-601-LinRegression/Project/housing.txt', stringsAsFactors = FALSE)\n\ndf_clean <-df %>% \n Years_to_Age %>% \n SwapToFactor %>% \n DealWithNulls %>% \n QualityToNumeric %>% \n ImputeValues %>% \n RoofMatlToDollars %>% \n RemoveCollinear %>% \n #ExcludeFeatures_90Plus %>% # this was to improve the score \n AreaToLogArea %>% \n AreaToLogAreaExcluded90 %>% \n Exclude_Outliers\n```\n\n```{r}\np1 <- df_clean %>% \n select(SalePrice, OverallCond) %>%\n ggplot(aes(x=OverallCond, y=log(SalePrice))) + \n geom_jitter()+\n labs(title = 'Log Sale Price vs. Overall Condition')+\n theme(axis.text.x = element_text(size=9), axis.text.y = element_text(size=9))+ theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n\np2 <- df_clean %>% \n select(SalePrice, OverallQual) %>%\n ggplot(aes(x=OverallQual, y=log(SalePrice))) + \n geom_jitter() +\n labs(title = 'Log Sale Price vs. Overall Quality')+\n theme(axis.text.x = element_text(size=9), axis.text.y = element_text(size=9))+ theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n\nmultiplot(p1,p2, cols=2)\n\n```\n\nThe overall condition has a loose linear correlation with Sale price, with a large number of houses showing up in the “normal” condition. It is not clear whether this is due to default choices, or all houses are generally rated normally, and only exceptional achieve higher ratings. The overall quality, on the other had shows a strong linear relationship with the log Home Price.\n\n\n```{r}\np1 <- df_clean %>% \n select(SalePrice, LotArea) %>%\n ggplot(aes(x=log(LotArea), y=log(SalePrice))) + \n geom_jitter()+\n labs(title = 'Log Sale Price vs. LotArea')+\n theme(axis.text.x = element_text(size=9), axis.text.y = element_text(size=9))+ theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n\np2 <- df_clean %>% \n select(SalePrice, GrLivArea) %>%\n ggplot(aes(x=log(GrLivArea), y=log(SalePrice))) + \n geom_jitter() +\n labs(title = 'Log Sale Price vs. Overall Quality')+\n theme(axis.text.x = element_text(size=9), axis.text.y = element_text(size=9))+ theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n\nmultiplot(p1,p2, cols=2)\n\n```\n\nComparing both the lot area and the general living area. Positive correlations can be seen in the scatter plots. The lot area is a much weaker relationship to sale price. This is most likely due to lots not being directly proportional to house sizes. A small house can have no backyard or can be on a farm. The below plot shows the interactions between lot area, and living area. The size of the dots are the sale prices of the houses. \n\n\n```{r }\ndf_clean %>% \n select(SalePrice, LotArea, GrLivArea) %>%\n ggplot(aes(x=GrLivArea, y=LotArea,size=SalePrice) ) + \n geom_hline(yintercept = mean(df_clean$LotArea), color='red') +\n geom_vline(xintercept = mean(df_clean$GrLivArea), color='red') +\n geom_point()+\n labs(title = 'General Living Area vs. LotArea, Sale Price = Size')+\n theme(axis.text.x = element_text(size=9), axis.text.y = element_text(size=9))+ theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n```\n\n```{r}\np1 <- df_clean %>% \n select(SalePrice, MSZoning) %>%\n ggplot(aes(x=MSZoning, y=log(SalePrice))) + \n geom_violin()+\n labs(title = 'Log Sale Price vs. MSZoning')+\n theme(axis.text.x = element_text(size=9), axis.text.y = element_text(size=9))+ theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n\np2 <- df_clean %>% \n select(SalePrice, Condition1) %>%\n ggplot(aes(x=Condition1, y=log(SalePrice))) + \n geom_violin() +\n labs(title = 'Log Sale Price vs. Overall Quality')+\n theme(axis.text.x = element_text(size=9), axis.text.y = element_text(size=9))+ theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n\nmultiplot(p1,p2, cols=2)\n\n```\n\nTwo of the categorical features, MS Zoning and Condition1 ( position of house relative to other local landmarks are shown below). The fatter parts of the violin plots show that in zoning, the floating village has the higher home prices, and low residential coming in 2nd. It should also be shown that it has the higher range of prices, which makes sense considering the house to land ratio of a mansion and a farm are very similar; few buildings, lots of area. \nFor the condition feature, normal contains most of the data, but being close to an intersection “artery” is associated with decreased prices, and being PosA - near a park or beltway showed a high increase in price. And interestingly being close to North-South railway was very high priced compared to being near East West railroad, or directly adjacent to the North-South railroad. Perhaps this is due to being near commuter traffic, but not right next to the train.\n\n\n```{r}\n\np1 <- df_clean %>% \n select(SalePrice, Functional) %>%\n ggplot(aes(x=Functional, y=log(SalePrice))) + \n geom_jitter()+\n labs(title = 'Log Sale Price vs. Functional')+\n theme(axis.text.x = element_text(size=9), axis.text.y = element_text(size=9))+ theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n\np2 <- df_clean %>% \n select(SalePrice, YearBuilt) %>%\n ggplot(aes(x=YearBuilt, y=log(SalePrice))) + \n geom_jitter() +\n labs(title = 'Log Sale Price vs. Overall Quality')+\n theme(axis.text.x = element_text(size=9), axis.text.y = element_text(size=9))+ theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n\nmultiplot(p1,p2, cols=2)\n\n```\n\nLooking at the functional field, this can be interpreted almost like deductions. 1 means there are few deductions, and 0 means severe deductions. A rough approximation is 100% functional. The way to interpret this plot is as the house loses functionality, the sale price is on average much lower.\nFinally, looking at YearBuilt, this field was translated into age by subtracting the report date of 2010. The number on the x-axis represents how old the house is. And as intuition would lend, the younger the house, the more expensive the house. We clearly see the inverse relationship to log SalePrice.\n\n\n```{r include=FALSE}\nX_OLS_all <- df_clean %>% select(-SalePrice, -Id)\ny_OLS <- df_clean %>% select(SalePrice) %>% unlist %>% as.numeric\ny_OLS_log <- log(y_OLS)\nfit_model <- lm(y_OLS_log ~., X_OLS_all)\ny_hat_log <- predict(lm(y_OLS_log ~., X_OLS_all), X_OLS_all, se.fit = TRUE)[[1]]\n```\n\n```{r fig.width=7, fig.heigh=3}\n# plot the result of y_hat vs. y_orig\np1<- data.frame(y_hat=y_hat_log, y_OLS=y_OLS_log) %>% \n ggplot(aes(x=y_hat, y=y_OLS)) + \n geom_point()+ \n geom_point(aes(x=y_hat, y=y_hat), color='red')+\n labs(x= \"Y Predicted (Log Sale Price)\", y = \"Y True (Log Sale Price)\", title=\"OLS Linear Regression of Log Sales Price\")+\n theme(axis.text.x = element_text(size=9), axis.text.y = element_text(size=9))+ theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n\np2<- data.frame(y_hat=exp(y_hat_log), y_OLS=exp(y_OLS_log)) %>% \n ggplot(aes(x=y_hat, y=y_OLS)) + \n geom_point()+ \n geom_point(aes(x=y_hat, y=y_hat), color='red')+\n labs(x= \"Y Predicted (Sale Price)\", y = \"Y True (Sale Price)\", title=\"OLS Linear Regression of Sales Price\")+\n theme(axis.text.x = element_text(size=9), axis.text.y = element_text(size=9))+ theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n\nmultiplot(p1,p2, cols=2)\n```\nThe above plots are a comparison of y_predicted from our OLS model (x-axix) and y_true (y-axis). The left plot units is the log version and the right plot units is the regular SalePrice. We can qualitatively observe a very tight relationship on the predicted vs. the actual sale price.\n\n\n# Task 1B: Prospective Customer Report - Morty’s House\n```{r}\nx_new <- \n read.csv('Morty.txt', stringsAsFactors = F) %>% \n select(-X) # Make sure pathname here is right\n\nx_clean <- x_new %>% \n Years_to_Age %>% \n DealWithNulls %>% \n SwapToFactor %>% \n QualityToNumeric %>% \n RoofMatlToDollars %>% \n RemoveCollinear %>% \n AreaToLogArea %>% \n AreaToLogAreaExcluded90 %>% select(-Id,-SalePrice)\n\nlog_y <- predict(fit_model, x_clean, interval = 'predict', level = 0.95)\ny <- round(exp(log_y),0)\n```\n\nOur client, Morty, received an estimate from another firm stating that he could likely sell his house for $143,000. Ever the skeptics, we looked to make a rough guess at his sale price via our own explanatory model, and give him a few tips as to how he could increase the interpolated value of his home. \n\nOur model predicts an expected house sale price of \\$ `r y[1,1]`. However, using standard regression Confidence Intervals, we are able to report to Morty that the maximum price we can reasonably expect his house to sell for (at the 95% level) is **\\$ `r y[1,3]`**. Any value more extreme than this would be considered to be a statistically significant outlier.\n\n##Features we recommend upgrading:\n\nFrom our analysis, we identified 3 key areas that would most benefit from Morty's attention: \n1. **Fireplaces** - the addition of an electrical fireplace is one of the most significant factors in raising a house price. \n2. **Kitchen Quality** - Morty's kitchen quality is currently below market average. This, again, is one of the most significant factors in determining a house price and a refurbishment could generate significant profits. \n3. **Garage Finish** - Morty's garage finish is also currently below market average. Similarly, we identified this as an easy feature to change that may add great value to the property.\n\n```{r, echo = F}\nx_update <- x_clean\nx_update$KitchenQual <- mean(df_clean$KitchenQual)\nx_update$GarageFinish <- mean(df_clean$GarageFinish)\nx_update$Fireplaces <- 1\nlog_y_update <- predict(fit_model, x_update, interval = 'predict', level = 0.95)\ny_update <- round(exp(log_y_update),0)\n```\n\nUpgrading the kitchen and garage to the market average and adding a single fireplace adjusts our predictions as follows: \n- Expected house sale price climbs from **\\$ `r y[1,1]`** to **\\$ `r y_update[1,1]`** \n- The maximum value for which we could reasonably expect to sell Morty's house climbs from **\\$ `r y[1,3]`** to **\\$ `r y_update[1,3]`**.\n\n\nGiven that we're most concerned by the significance of our coefficients, let's rank by the SL and exclude any not significant at 95% level:\n```{r include=FALSE}\nsignificant_fields <- NULL\ncoeffs <- NULL\nSL <- NULL\nfor(i in 1:135){\n if(summary(fit_model)$coefficients[i,4] < 0.05){\n significant_fields <- c(significant_fields, row.names(summary(fit_model)$coefficients)[i])\n coeffs <- c(coeffs, summary(fit_model)$coefficients[i,1])\n SL <- c(SL, summary(fit_model)$coefficients[i,4])\n }\n}\n(sig_fields_df <- data.frame(field = significant_fields, beta = coeffs, SL = SL) %>% arrange(SL))\n```\n\n\nIn the below table, we summarise the key statistics regarding these 3 features in our model:\n\n```{r, echo = F}\nmodel_params <- sig_fields_df %>% filter(field == 'Fireplaces' | field == 'KitchenQual' | field == 'GarageFinish')\nMorty_values <- data.frame(Morty = as.numeric(c(x_clean['Fireplaces'], x_clean['KitchenQual'], x_clean['GarageFinish'])))\nMean_values <- data.frame(Mean = as.numeric(c(mean(df_clean$Fireplaces), mean(df_clean$KitchenQual), mean(df_clean$GarageFinish))))\nsummary_data <- cbind(model_params, Morty_values, Mean_values)\nsummary_data$exp_beta <- exp(summary_data$beta)\nkable(summary_data)\n```\n\nNote that the final column in this table, the exponent of the coefficient, represents the approximate factor that value would increase if we were to increment the corresponding feature value by 1 unit.\n\n### Some other considerations, which are mostly out of Morty’s control include:\n1. Pick up his house and move it somewhere else, as neighborhood is quite significant\n2. Forge the documentation to change the date that the garage was constructed\n3. Buy some property off of a neighbor to fix the irregular shape of his lot\n\n### Final Notes on Morty House:\nAs noted before, we perfectly predicted the sell price of Morty’s house using an explanatory model, which is a symptom of overfitting. This model was too flexible and as such perfectly tuned in on the data provided, which will in turn result in large variability in the predicted price when we feed the model an observation that it has not seen before. Generally, a model that is over specified for explanation will perform terribly on new data. We deal with this by building a more appropriately flexible, and as a result, more robust model which can better handle new input. This will be covered further in the following section, Task 2.\n\n\n### Cosine Similarity\nOnce all of the explanatory feature framework was setup, all of the houses in the dataset were converted into vectors. Categorical features were turned into dummy binary variables, so the entire vector was integer. With this vector in hand, housing similarity was calculated to find similar houses to morty. The 6 closest houses are listed below. \n\nWow! It turns out there’s an exact copy of Morty’s House in the dataset! Id#6. \n\n```{r fig.show=FALSE, include=FALSE}\nselect <- dplyr::select\n\ndf <- read.csv('~/Documents/MSAN/04-601-LinRegression/Project/housing.txt', stringsAsFactors = FALSE)\n\ndf_clean <-df %>% \n Years_to_Age %>% \n SwapToFactor %>% \n DealWithNulls %>% \n QualityToNumeric %>% \n ImputeValues %>% \n RoofMatlToDollars %>% \n RemoveCollinear %>% \n #ExcludeFeatures_90Plus %>% # this was to improve the score \n AreaToLogArea %>% \n AreaToLogAreaExcluded90 %>% \n Exclude_Outliers\n\n\nx_new <- \n read.csv('Morty.txt', stringsAsFactors = F) %>% \n select(-X) # Make sure pathname here is right\n\nx_clean <- x_new %>% \n Years_to_Age %>% \n DealWithNulls %>% \n SwapToFactor %>% \n QualityToNumeric %>% \n RoofMatlToDollars %>% \n RemoveCollinear %>% \n #ExcludeFeatures_90Plus %>% # this was to improve the score \n AreaToLogArea %>% \n AreaToLogAreaExcluded90 %>% select(-Id,-SalePrice)\n\n\nX_OLS_all <- df_clean %>% select(-SalePrice, -Id)\ny_OLS <- df_clean %>% select(SalePrice) %>% unlist %>% as.numeric\ny_OLS_log <- log(y_OLS)\nfit_model <- lm(y_OLS_log ~., X_OLS_all)\ny_hat_log <- predict(lm(y_OLS_log ~., X_OLS_all), X_OLS_all, se.fit = TRUE)[[1]]\n\n# Bind together\ny_OLS_hat <- predict(fit_model, X_OLS_all)\n\n# Convert to dummy variables + model matrix\nproxy_matrix <- model.matrix(SalePrice~.,df_clean %>% select(-Id))\n\n# Pull morty's vector out\ntarget_vec <- proxy_matrix[5,] \n\n# The remaining houses will be compared to\ncompar_vecs <-proxy_matrix\nrows <- nrow(compar_vecs)\n\n# Calculate all teh scores\nscores <- list()\nfor (i in 1:rows){\n #scores[[i]] <- cosine.similarity(target_vec, compar_vecs[i,], .do.norm=T)\n scores[[i]] <- target_vec %*% compar_vecs[i,] / norm(target_vec,type=\"2\") / norm(compar_vecs[i,],type=\"2\")\n}\n\nx_clean$Id <- 9999\nx_clean$SalePrice <- 143000\n\nclose_5 <- df_clean%>% \n mutate(OLS_price = exp(y_OLS_hat)) %>% \n mutate(proxy_score = unlist(scores)) %>% \n bind_rows(x_clean) %>% \n arrange(desc(proxy_score)) %>% head(6) \n```\n\n\\pagebreak\n\n## Show Similar Houses - Cosine Similarity\n\n\\small\n\n```{r cache=F}\nt(close_5) %>% kable\n```\n\n\\normalsize\n\n\\pagebreak\n\n# Task 2: Predictive Modeling\n\n\n```{r}\n\nclean <- function(df){\n housing <- df\n \n pct_na <- sapply(housing, function(x) round((sum(is.na(x)) / length(x))*100))\n housing <- housing[,pct_na < 80]\n \n max_pct <- sapply(housing, function(x) round(max((table(x)/length(x))*100)))\n housing <- housing[,max_pct<90]\n \n housing$GarageYrBlt <- sapply(housing$GarageYrBlt, function(x) (as.integer(x) %/% 10) *10)\n housing$GarageYrBlt <- paste0(as.character(housing$GarageYrBlt), 's')\n \n housing$GarageYrBlt[is.na(housing$GarageYrBlt)] <- \"None\"\n housing$GarageType[is.na(housing$GarageType)] <- \"None\"\n housing$GarageFinish[is.na(housing$GarageFinish)] <- \"None\"\n housing$MasVnrType[is.na(housing$MasVnrType)] <- 'None'\n housing$BsmtQual[is.na(housing$BsmtQual)] <- 'None'\n housing$BsmtExposure[is.na(housing$BsmtExposure)] <- \"None\"\n housing$BsmtFinType1[is.na(housing$BsmtFinType1)] <- 'None'\n housing$BsmtFinType2[is.na(housing$BsmtFinType2)] <- \"None\"\n housing$FireplaceQu[is.na(housing$FireplaceQu)] <- \"None\"\n \n housing$MasVnrArea[is.na(housing$MasVnrArea)] <- 0\n housing$LotFrontage[is.na(housing$LotFrontage)] <- 0\n \n housing$MSSubClass <- factor(housing$MSSubClass, levels = c(20,30, 40, 45, 50, \n 60, 70, 75, 80, 85, \n 90, 120, 150, 160, \n 180, 190), \n labels = c('1-STORY 1946 & NEWER ALL STYLES',\n '1-STORY 1945 & OLDER',\n '1-STORY W/FINISHED ATTIC ALL AGES',\n '1-1/2 STORY - UNFINISHED ALL AGES',\n '1-1/2 STORY FINISHED ALL AGES',\n '2-STORY 1946 & NEWER',\n '2-STORY 1945 & OLDER',\n '2-1/2 STORY ALL AGES',\n 'SPLIT OR MULTI-LEVEL',\n 'SPLIT FOYER','DUPLEX - ALL STYLES AND AGES',\n '1-STORY PUD (Planned Unit Development) - 1946 & NEWER',\n '1-1/2 STORY PUD - ALL AGES',\n '2-STORY PUD - 1946 & NEWER',\n 'PUD - MULTILEVEL - INCLSPLIT LEV/FOYER',\n '2 FAMILY CONVERSION - ALL STYLES AND AGES'))\n \n cleaner <-\n housing %>% \n select(-Id)\n \n return(cleaner)\n}\nhousing <- read.csv('housing.txt', stringsAsFactors = F)\n\nhousing <- clean(housing)\n\ntrain <- sample(1:nrow(housing), nrow(housing) *(4/5))\ntest <- (-train)\n\nx <- model.matrix(SalePrice ~ ., data = housing)\ny <- housing$SalePrice\ngrid.lambda <- 10^seq(10, -2, length.out = 100)\n\ny.train <- y[train]\ny.test <- y[test]\nx.train <- x[train,]\nx.test <- x[test,]\n```\n\nHere, we employed a handful of modeling techniques, iteratively testing out how well they performed as measured by the mean squared prediction error on a set of hold out data. Parameters for the models considered were generated via OLS, Ridge, LASSO, and Elastic Net algorithms. Besides sharing the same model type as explanatory modeling, extrapolation was markedly different in the following ways:\n\n**Normality Conditions:** When optimizing our model for explanation, we used a number of functions to clean and alter the data in order to reduce bias and meet several assumptions when performing regression. When optimizing our model for prediction, however, we relaxed these assumptions to focus our concerns on prediction performance. Since we were only focused on the closeness of our predictions, our main criterion for selecting our best regression model was minimizing MSPE. \n\n**Variable Selection:** To do this, we took raw data and tested out different subsets of our earlier data cleaning functions. Some of the steps taken in the variable selection for interpolation could not be omitted, such as cleaning up any null values, imputing values where necessary, and changing qualitative variables to numeric variables. For the other cleaning procedures, such as translating the year a house was built to age or removing collinear variables, we exhausted all combinations to create \"partially clean\" datasets.\n\n**Parameter Selection:** With the data cleaned, we then ran several iterations of OLS, Ridge, LASSO, and Elastic Net on these variables to find the parameter estimates whose model had the lowest MSPE. After much consideration, we finally settled on a model with parameter estimates generated by L1 norm penalized regression (Lasso). Despite the fact that the table below has Lasso listed as having the highest MSPE, when averaged out, Lasso actually had the lowest mean MSPE. It also proved to be useful for decisive variable selection. The model in all its glory is detailed below.\n\n\n## Ridge Modeling\n\nThe ridge regularized regression was used as a possible model. Due to the high number of features and often redundant data, there could be a high level of collinearity between different fields. As mentioned previously, total area in square feet is redundant if all the parts are found in the data. For example, the MSSubClass is really a mashup of the year, and the number of levels of the house. The ridge should automatically minimize the impact of these redundant features on the predictive model.\n\n```{r}\n# do a grid search of lambdas for optimal value\nmodel.ridge.train <- glmnet(x.train, y.train, alpha = 0, lambda = grid.lambda)\nset.seed(101)\ncv.ridge.out <- cv.glmnet(x.train, y.train, alpha = 0, type.measure = 'mse')\nbest.lambda.ridge <- cv.ridge.out$lambda.min\n\n# do predictions\nridge.pred <- predict(model.ridge.train, s = best.lambda.ridge, newx = x.test)\n\n# calculate error\nmspe.ridge <- mean((ridge.pred - y.test)^2)\nmodel.ridge.final <- glmnet(x, y, alpha = 0, lambda = best.lambda.ridge)\nridge.coefs <- coef(model.ridge.final)[-2,]\nr.squared.ridge <- max(model.ridge.final$dev.ratio)\n```\n\n## Lasso Modeling\n\nLasso modeling was also applied against the dataset. This was ideal because we suspect that over 80+ features, there are probably a large number of features that do not have an affect on sales price. Things such as paved roads, or electrical breakers will most likely have little effect. Instead of plotting each of these fields against the main response variable SalePrice, we will apply a Lasso Regularized model which will drop some of these unnecessary variables. \n\n```{r}\n# do a grid search of lambdas for optimal value\nmodel.lasso.train <- glmnet(x.train, y.train, alpha = 1, lambda = grid.lambda)\nset.seed(101)\ncv.lasso.out <- cv.glmnet(x.train, y.train, alpha = 1, type.measure = 'mse')\nbest.lambda.lasso <- cv.lasso.out$lambda.min\n\n# do predictions\nlasso.pred <- predict(model.lasso.train, s = best.lambda.lasso, newx = x.test)\n\n# calculate error\nmspe.lasso <- mean((lasso.pred - y.test)^2)\nmodel.lasso.final <- glmnet(x, y, alpha = 1, lambda = best.lambda.lasso)\nlasso.coefs <- coef(model.lasso.final)[-2,]\nr.squared.lasso <- max(model.lasso.final$dev.ratio)\n```\n\n## ElasticNet Modeling\n\nElasticNet was also used, which has both regularization terms from both Ridge and Lasso, with an alpha blend factor. The model that was tried here was with alpha = 0.5\n\n```{r}\n# do a grid search of lambdas for optimal value\nmodel.en.train <- glmnet(x.train, y.train, alpha = 0.5, lambda = grid.lambda)\nset.seed(101)\ncv.en.out <- cv.glmnet(x.train, y.train, alpha = 0.5, type.measure = 'mse')\nbest.lambda.en <- cv.en.out$lambda.min\n\n# do predictions\nen.pred <- predict(model.en.train, s = best.lambda.en, newx = x.test)\n\n# calculate error\nmspe.en <- mean((en.pred - y.test)^2)\nmodel.en.final <- glmnet(x, y, alpha = 0.5, lambda = best.lambda.en)\nen.coefs <- coef(model.en.final)[-2,]\nr.squared.en <- max(model.en.final$dev.ratio)\n```\n\n## OLS Modeling informed by lasso model \n\nOLS was re-run again, only pulling features that were selected after running the Lasso model. This was used as a baseline score to compare the other models against.\n\n```{r}\n# ols defined by lasso variables\nols.vars <- names(abs(lasso.coefs) > 0)\n\n# ols defined by lasso variables\nx.ols <- x[, abs(lasso.coefs) > 0]\n\n# ols test train split\nx.ols.train <- x.ols[train,]\nx.ols.test <- x.ols[test,]\n\n# run the model\nmodel.ols.train <- lm(y.train ~ x.ols.train)\nset.seed(101)\nols.pred <- predict(model.ols.train, newx = x.ols.test)\nmspe.ols <- mean((ols.pred - y.test)^2)\nr.squared.ols <- summary(model.ols.train)$r.squared\n\n```\n\n\n```{r}\nCoefficients <- data.frame(Ridge = ridge.coefs, Lasso = lasso.coefs, Elastic.Net = en.coefs)\n\nMSPE_frame <- data.frame(model=c('Ridge','Lasso','Elastic.net', 'OLS'), \n MSPEscores= c(mspe.ridge, mspe.lasso, mspe.en, mspe.ols),\n r.squared = c(r.squared.ridge, r.squared.lasso, r.squared.en, r.squared.ols),\n best.lambda = c(best.lambda.ridge, best.lambda.lasso, best.lambda.en, 0)\n ) %>% mutate(RMSPE = sqrt(MSPEscores))\nMSPE_frame %>% kable\n```\n\n\n\n\n```{r}\nlasso_plot <- data.frame(y_hat=lasso.pred, true_sale_price = y.test) \ncolnames(lasso_plot) <- c('lasso_predictions','true_sale_price')\nlasso_plot %>% ggplot(aes(x=lasso_predictions, y=true_sale_price)) + \n geom_point() +\n geom_point(aes(x=lasso_predictions, y=lasso_predictions), color='red') +\n labs(x= \"Y Predicted (Sale Price)\", y = \"Y True (Sale Price)\", title=\"Lasso Regression of Sales Price\")+\n theme(axis.text.x = element_text(size=9), axis.text.y = element_text(size=9))+ theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n```\n\n\\pagebreak\n\n## Appendix: Optimal Lasso Beta Values\n```{r}\nlasso.coefs.ordered <- lasso.coefs[order(abs(lasso.coefs), decreasing = T)]\nlasso.coefs.ordered <- lasso.coefs.ordered[lasso.coefs.ordered != 0]\nlasso.coefs.ordered %>% data.frame %>% kable \n```\n\n" }, { "alpha_fraction": 0.6483780741691589, "alphanum_fraction": 0.6637730598449707, "avg_line_length": 30.720857620239258, "blob_id": "644806da9f14801ead374ab3a9429d573bd69f5a", "content_id": "80cb5b44d1d30d2c0a5924b84a7d6eaa1c0317ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 50341, "license_type": "no_license", "max_line_length": 586, "num_lines": 1587, "path": "/Regression_Project/2-CaseStudy-Expanded-Analysis.Rmd", "repo_name": "ajhoward7/Machine_Learning", "src_encoding": "UTF-8", "text": "---\ntitle: 'Case Study: Iowa Housing Prices'\nauthor: \"Tim Lee, Taylor Pellerin, Jake Toffler, Ian Smeenk, Alex Howard\"\ndate: \"10/4/2017\"\noutput: \n pdf_document:\n toc: true\n toc_depth: 2\n---\n\n```{r setup, include=FALSE}\nrm(list=ls()) # removes all objects from the environment\ncat(\"\\014\") # clears the console\nlibrary(tidyverse)\nlibrary(magrittr)\nlibrary(dplyr)\nlibrary(glmnet)\nlibrary(caret)\nlibrary(knitr)\nlibrary(cvTools)\nlibrary(caTools)\nlibrary(ggplot2)\nlibrary(car)\nlibrary(MASS)\nlibrary(olsrr)\noptions(\"scipen\" = 10)\n# force default function masking \nselect <- dplyr::select\nknitr::opts_chunk$set(echo = TRUE, fig.show = \"hide\", cache=F, tidy.opts = list(width.cutoff = 60), tidy=TRUE)\n\n# ----------------------------------------------------------------------------\n# Hidden functions used later for plotting\n# ----------------------------------------------------------------------------\n\nmultiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {\n library(grid)\n\n # Make a list from the ... arguments and plotlist\n plots <- c(list(...), plotlist)\n\n numPlots = length(plots)\n\n # If layout is NULL, then use 'cols' to determine layout\n if (is.null(layout)) {\n # Make the panel\n # ncol: Number of columns of plots\n # nrow: Number of rows needed, calculated from # of cols\n layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),\n ncol = cols, nrow = ceiling(numPlots/cols))\n }\n\n if (numPlots==1) {\n print(plots[[1]])\n\n } else {\n # Set up the page\n grid.newpage()\n pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))\n\n # Make each plot, in the correct location\n for (i in 1:numPlots) {\n # Get the i,j matrix positions of the regions that contain this subplot\n matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))\n\n print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,\n layout.pos.col = matchidx$col))\n }\n }\n}\n\n# ----------------------------------------------------------------------------\n# Used for Boxcox, but defined later\n# ----------------------------------------------------------------------------\nDealWithNulls <- function(df){\n drop_fields = c('LotFrontage',\n 'Alley',\n 'PoolQC',\n 'Fence',\n 'MiscFeature',\n 'FireplaceQu')\n \n df_clean <- data.frame(df) %>% \n select(-LotFrontage,\n -Alley,\n -PoolQC, \n -Fence,\n -MiscFeature,\n -FireplaceQu, \n -Utilities) %>% \n data.frame\n return(df_clean)\n}\n```\n\n\\pagebreak\n\n\n# EDA Summary:\n\n### Changing the sales price response field to log(sales price) for normality reasons\n\nAfter checking for normality, the sales price fails the two sided K-S test, forcing us to reject the null hypothesis. Then transforming the sales price into log(sales price), we find we keep the null hypothesis and the response variable is normal. \n\n### Dropping Null Fields\n\nA number of the fields were predominantly null. The following features were over 20% null and were excluded from the data:\n\n- Lot Frontage\n- Alley\n- PoolQC\n- Fence\n- MiscFeature\n- FireplaceQu\n\n### Converting String Quality Descriptions into numerics\n\nMany of the fields had discrete ratings such as \"excellent\", \"good\" etc. All of these related fields were changed to a ~10 point scale listed below. \n\n|Numeric Assigned | Str Encoding | Data Dictionary Description|\n|----|----|---|\n|9|Ex|Excellent|\n|7|Gd|Good|\n|5|TA|Average/Typical|\n|3|Fa|Fair|\n|1|Po|Poor|\n|0|NA|No basement|\n\n### Transform dates into years old (continuous)\n\nMany of the year related fields such as the year built, or the year modified, or year of the garage were transformed into continous \"age\" in years. The reference date to make this calculation is 2010 which is the most recent data in the fields. For example \n\n#### 2010 (current) - 2007 year built = house is 3 years old\n\n\n### Imputing missing values\n\nDepending on the field that was missing values, either the NA was replaced with a \"None\" for fields such as garage type. Or the \"average\" value was imputed instead like \"Standard Breaker\". In other cases the NA was a proxy for 0. For all the qualitative fields, the NA's were considered a rating of 0 (mainly for the size of the basement)\n\n### Convert specific fields to factors\n\nThe primary field that was converted to factors was the MSSubClass. The other fields under consideration were number of bedrooms, kitchens, bathes. Should these be considered discrete fields? Technically there is no such thing as 2.35 bedrooms. The final model left these counting fields as continuous integers, but will be discussed more later.\n\n### Detecting Outliers\n\nDFFITs was used to identify influential outliers in the data. These 59 row observations were excluded from the future analysis.\n\n### Removing Collinear Fields\n\nThese fields have been removed from tweaking and research during OLS, Lasso, or Ridge analysis.\n- TotalBsmtSF: this can be calculated from BsmtSF1 and BsmtSF2 added together\n- BldgType: this is covered more detail in the MSSubClass: Identifies the type of dwelling involved in the sale.\tSo this is unnecessary\n- Combining Exterior Fields, Exterior1st,Exterior2nd, \n\n### Removing imbalanced fields - these are fields where a high % of the field is the same value\n\nA histogram analysis was performed on all fields. The following fields had >= 90% one value so were dropped as predictors for this study:\n\n- Condition2\n- Heating\n- RoofMatl\n- X3SsnPorch\n- LowQualFinSF\n- KitchenAbvGr\n- MiscVal\n- LandSlope\n- CentralAir\n- BsmtHalfBath\n- Functional\n- PavedDrive\n- Electrical\n- ScreenPorch\n- GarageQual\n- LandContour\n\n\\pagebreak\n\n# Detailed EDA Analysis, Walkthrough and Code\n\n## Load the Data\n```{r}\n# load the kaggle CSV\ndf <- read.csv('~/Documents/MSAN/04-601-LinRegression/Project/housing.txt', stringsAsFactors = FALSE)\n```\n\n# EDA: Examination of the Response Variable (Testing for Normality):\n\n## Boxcox Examination\n\n```{r fig.width=7, fig.height=4}\ny_resp <- df$SalePrice %>% unlist\nX<- df %>% select(-SalePrice) %>% DealWithNulls\nfit.model <- lm(y_resp ~ .,X)\n\nres <- boxcox(lm(y_resp ~ .,X), plotit=T, lambda=seq(0,1,by=.5))\n\n\n```\n\n## Optimal Transform - Y to the power of 0.13, close to 0, will continue to use log\n```{r}\ndata.frame(res) %>% arrange(desc(y)) %>% head(5) %>% kable\n\n\n# make a function to do the transformation for later\nbcTrans <- function(val){\n return((val^0.131)/0.131)\n}\n```\n\n\n## Plot the histogram of Sale Price (not transformed)\n\n```{r fig.width=7, fig.height=3}\ndf %>% \n select(SalePrice) %>% \n ggplot(aes(x=SalePrice)) + \n geom_histogram(bins=40) + \n labs(x='Sales Price of House', title='Histogram of Sales Price in Iowa')\n\n```\n\n## K-S test of Sale Price (untransformed)\n\nFrom the K-S test we see we must reject the null hypothesis that hte data is normal\n\n```{r}\nset.seed(1)\nsale_price <- df %>% \n select(SalePrice) %>% \n unlist\n\nn_y <- length(sale_price)\nsale_price_norm <- (sale_price-mean(sale_price))/sd(sale_price)\nstd_norm <- rnorm(n =n_y,mean = 0, sd = 1 )\n\nks.test(sale_price_norm,std_norm)\n\n```\n\n## K-S test of log(Sale Price)\n\nSince the distribution of the sale price is skewed, we will try and apply a log transformation and retest under the Kolmagorov-Test\n\n```{r}\nset.seed(1)\nlog_sale_price <- log(sale_price)\nlog_sale_price_norm <- (log_sale_price-mean(log_sale_price))/sd(log_sale_price)\nstd_norm <- rnorm(n =n_y,mean = 0, sd = 1 )\n\n\nks.test(log_sale_price_norm,std_norm)\n\n```\n\n## Plot the histogram of log(Sale Price)\n\n\n```{r fig.width=7, fig.height=3}\ndf %>% \n select(SalePrice) %>% \n log %>% \n ggplot(aes(x=SalePrice)) + \n geom_histogram(bins=40) + \n labs(x='Log Sales Price of House', title='Histogram of Log(Sales Price) in Iowa')\n```\n\n\\pagebreak\n\n# EDA: Cleaning up the data with a Pipeline\n\n## Function: Dropping nulls, based on histogram statistics\n\nThis will be accomplished by checking for number of nulls\n\n```{r}\nnull_columns <- colSums(is.na(df))\nsort(null_columns[null_columns >0]/n_y, decreasing=T) %>% head(10) %>% kable(caption = 'Field Null%', col.names = c('%Null'))\n```\n\n\n\n## Function: Dealing with Nulls\n\nAnything with more than 20% more nulls, the field is dropped. The fields dropped are as follows:\n\n- Lot Frontage\n- Alley\n- PoolQC\n- Fence\n- MiscFeature\n- FireplaceQu\n\n```{r}\n# Drop fields with around 280 nulls (20%)\nDealWithNulls <- function(df){\n drop_fields = c('LotFrontage',\n 'Alley',\n 'PoolQC',\n 'Fence',\n 'MiscFeature',\n 'FireplaceQu')\n \n df_clean <- data.frame(df) %>% \n select(-LotFrontage,\n -Alley,\n -PoolQC, \n -Fence,\n -MiscFeature,\n -FireplaceQu, \n -Utilities) %>% \n data.frame\n return(df_clean)\n}\n```\n\n## Function: transform dates into years old\n\nWill assume that the current year is 2010\n\n```{r}\n\nYears_to_Age <- function(df){\n df_clean <- data.frame(df)\n df_clean$GarageYrBlt <- as.integer(2010 - df$GarageYrBlt)\n df_clean$YrSold <- as.integer(2010 - df$YrSold)\n df_clean$YearBuilt <- as.integer(2010 - df$YearBuilt)\n df_clean$YearRemodAdd <- as.integer(2010- df$YearRemodAdd)\n return(df_clean)\n}\n```\n\n## Function: Fixing fields of MS Sub Class: Turning Numerics into Factors\n\n- There is a zoning field that has numeric values that we force into a categorical factor type.\n- All counting factors were switched to factors ( room counts, bath counts)\n- Month was changed to factor\n\n```{r}\nSwapToFactor <- function(df){\n \n # setup a copy (to prevent from looping with the same variable name)\n df_clean <- data.frame(df)\n \n # Convert numerics into factors\n df_clean$MSSubClass <- factor(df$MSSubClass, \n levels = c(20,30, 40, 45, 50, 60, 70, 75, 80, 85, 90, 120, 150, 160, 180, 190), \n labels = c('1LVL>1946','1LVL<1945','1LVL_W_ATTIC','1.5LVL_UNF',\n '1.5LVL_FIN','2LVL>1946','2LVL<1945','2.5LVL','SPLIT',\n 'SPLIT_FOYER','DUPLEX','1LVL_PUD>1946','1.5LVL_PUD','2LVL_PUD>1946',\n 'MULTI_PUD','2FAM_CONV'))\n return(df_clean)\n}\n\n\nRoomsToFactor <- function(df){\n # setup a copy (to prevent from looping with the same variable name)\n df_clean <- data.frame(df)\n \n df_clean$BsmtFullBath <- factor(df$BsmtFullBath)\n df_clean$BsmtHalfBath <- factor(df$BsmtHalfBath)\n df_clean$FullBath <- factor(df$FullBath)\n df_clean$HalfBath <- factor(df$HalfBath)\n df_clean$BedroomAbvGr <- factor(df$BedroomAbvGr)\n df_clean$KitchenAbvGr <- factor(df$KitchenAbvGr)\n df_clean$TotRmsAbvGrd <- factor(df$TotRmsAbvGrd)\n df_clean$Fireplaces <- factor(df$Fireplaces)\n df_clean$GarageCars <- factor(df$GarageCars)\n df_clean$MoSold <- factor(df$MoSold)\n \n return(df_clean)\n}\n```\n\n## Function: Change any of the Quality fields into numbers. Define a transformation function\n\nFor all the fields that have a word rating, we converted the answers into a numeric scale. This will both reduce the number of categorical fields and allow more interpretability in the model. The word to score translation is listed below:\n\n|Numeric Assigned | Str Encoding | Data Dictionary Description|\n|----|----|---|\n|9|Ex|Excellent|\n|7|Gd|Good|\n|5|TA|Average/Typical|\n|3|Fa|Fair|\n|1|Po|Poor|\n|0|NA|No basement|\n\nFor the few of these fields that have nulls, this is intentional, the data dictionary actually defines the NA's as no basement.\n\n```{r}\n\nQualityToNumeric <- function(df){\n \n # setup a copy (to prevent from looping with the same variable name)\n df_clean <- data.frame(df)\n \n # convert words into continuous scores\n df_clean$GarageYrBlt <- as.numeric(df_clean$GarageYrBlt)\n df_clean$ExterCond <- sapply(df$ExterCond, function(x) { switch(x, Ex=9, Gd=7, TA=5, Av=5, Fa=3, Po=1, \"NA\"=0)})\n df_clean$ExterQual <- sapply(df$ExterQual, function(x) { switch(x, Ex=9, Gd=7, TA=5, Av=5, Fa=3, Po=1, \"NA\"=0)})\n df_clean$BsmtQual <- sapply(df$BsmtQual, function(x) { switch(x, Ex=9, Gd=7, TA=5, Av=5, Fa=3, Po=1, \"NA\"=0)})\n df_clean$BsmtCond <- sapply(df$BsmtCond, function(x) { switch(x, Ex=9, Gd=7, TA=5, Av=5, Fa=3, Po=1, \"NA\"=0)})\n df_clean$BsmtExposure <- sapply(df$BsmtExposure, function(x) { switch(x, Gd=10, Av=7, Mn=4, No=1, \"NA\"=0)})\n df_clean$BsmtFinType1 <- sapply(df$BsmtFinType1, function(x) { switch(x, GLQ=10, ALQ=7, Rec=7, BLQ=4, LwQ=1, Unf=0, \"NA\"=0)})\n df_clean$BsmtFinType2 <- sapply(df$BsmtFinType2, function(x) { switch(x, GLQ=10, ALQ=7, Rec=7, BLQ=4, LwQ=1, Unf=0, \"NA\"=0)})\n df_clean$HeatingQC <-sapply(df$HeatingQC, function(x) { switch(x, Ex=9, Gd=7, TA=5, Av=5, Fa=3, Po=1, \"NA\"=0)})\n df_clean$KitchenQual <- sapply(df$KitchenQual, function(x) { switch(x, Ex=9, Gd=7, TA=5, Av=5, Fa=3, Po=1, \"NA\"=0)})\n df_clean$Functional <- sapply(df$Functional, function(x) { switch(x, Typ=1.0, Min1=.85, Min2=.7, Mod=.55, Maj1=.45, Maj2=.3, Sev=.15, Sal=0.0)})\n df_clean$GarageQual <- sapply(df$GarageQual, function(x) { switch(x, Ex=9, Gd=7, TA=5, Av=5, Fa=3, Po=1, \"NA\"=0)})\n df_clean$GarageCond <- sapply(df$GarageQual, function(x) { switch(x, Ex=9, Gd=7, TA=5, Av=5, Fa=3, Po=1, \"NA\"=0)})\n df_clean$GarageFinish <- sapply(df$GarageFinish, function(x) { switch(x, Fin=1, RFn=0.66, Unf=0.33,\"NA\"=0)})\n return(df_clean)\n}\n```\n\n## Function: Imputing some of the missing values\n\nFor the few fields that were left with NA's, the following strategy was used. Since most of the NA's showed up in Categorical all the NA's were replaced with new categories called \"None\". Based on the data dictionary the remainder were assigned default values.\n\n```{r}\n\nImputeValues <- function(df){\n \n # setup a copy (to prevent from looping with the same variable name)\n df_clean <- data.frame(df)\n \n df_clean[is.na(df_clean$GarageYrBlt),]$GarageYrBlt = 0\n \n # add levels for none\n levels(df_clean$GarageType) = c(levels(df$GarageType),\"None\")\n df_clean[is.na(df_clean$GarageType),]$GarageType <- \"None\" \n \n # addFill nones, 0 and default values\n df_clean[is.na(df_clean$MasVnrType),]$MasVnrType <- \"None\"\n df_clean[is.na(df_clean$MasVnrArea),]$MasVnrArea <- 0\n df_clean[is.na(df_clean$Electrical),]$Electrical <- 'SBrkr'\n return(df_clean)\n}\n```\n\n\n## Clean all datasets - check for nulls in the clean dataset\n\n```{r}\ndf_clean <- df %>% \n Years_to_Age %>% \n SwapToFactor %>% \n DealWithNulls %>% \n QualityToNumeric %>% \n ImputeValues\n \n# check for nulls\nsum(is.na(df_clean))\n```\n\n\n## Sample of the Cleaned up table\n\n\\small\n\n```{r}\nt(head(df_clean)) %>% kable\n```\n\n\\normalsize\n\n\\pagebreak\n\n#EDA: Optional EDA Cleanup Functions\n\n## Optional - Function: swap roof materials with price per tile\n\nBasically plug in the price as the indicator:\nhttp://www.hgtv.com/remodel/outdoors/top-6-roofing-materials\n\n\n```{r}\nRoofMatlToDollars <- function(df){\n # make a local copy\n df_clean <- data.frame(df)\n df_clean$RoofMatl <- sapply(df_clean$RoofMatl,function(x) switch(x, ClyTile=400 ,CompShg=250 ,Membran=10 ,Metal=500 ,Roll=100 ,\"Tar&Grv\"=100 ,WdShake=125 ,WdShngl=125))\n return(df_clean)\n}\n\n```\n\n\n## Optional - Function: exclude dominant features (see overview below for a table)\n\nThe following fields had 90% one value so were dropped as predictors for this study:\n\n- Condition2\n- Heating\n- RoofMatl\n- X3SsnPorch\n- LowQualFinSF\n- KitchenAbvGr\n- MiscVal\n- LandSlope\n- CentralAir\n- BsmtHalfBath\n- Functional\n- PavedDrive\n- Electrical\n- ScreenPorch\n- GarageQual\n- GarageCond\n- LandContour\n\n```{r}\nExcludeFeatures_90Plus <- function(df){\n return(df %>% select(-Condition2, -Heating, -RoofMatl, -X3SsnPorch, -LowQualFinSF, -KitchenAbvGr, -MiscVal, -LandSlope, -CentralAir, -BsmtHalfBath, -Functional, -PavedDrive, -Electrical, -ScreenPorch, -GarageQual, -LandContour))\n}\n```\n\n## Optional - Function: Remove Collinear Fields from OLS analysis\n\nThese fields have been removed from tweaking and research during OLS, Lasso, or Ridge analysis.\n- TotalBsmtSF: this can be calculated from BsmtSF1 and BsmtSF2 added together\n- BldgType: this is covered more detail in the MSSubClass: Identifies the type of dwelling involved in the sale.\tSo this is unnecessary\n- Combining Exterior Fields, Exterior1st,Exterior2nd makes a single fields and deals with a Field1-NA case\n\n```{r}\n\nRemoveCollinear <- function(df){\n df_clean <- data.frame(df)\n df_clean$ExtCom <- df_clean %>% mutate(ExtCom = paste0(Exterior1st,'-', Exterior2nd)) %>% select(ExtCom) %>% unlist\n df_clean <- df %>% select(-TotalBsmtSF, -Exterior1st, -Exterior2nd,-BldgType, -HouseStyle, -GarageCond, -SaleCondition)\n return(df_clean)\n}\n```\n\n## Optional - Function: Convert All areas to Log Areas\n\nBased on some of the studies below:\n```{r}\n\nAreaToLogArea <- function(df){\n df_clean <- data.frame(df)\n df_clean$GrLivArea <- log(df$GrLivArea+1)\n df_clean$LotArea <- log(df$LotArea+1)\n df_clean$GarageArea <- log(df$GarageArea+1)\n df_clean$BsmtFinSF1 <- log(df$BsmtFinSF1+1)\n df_clean$BsmtFinSF2 <- log(df$BsmtFinSF2+1)\n df_clean$MasVnrArea <- log(df$MasVnrArea+1)\n df_clean$X1stFlrSF <- log(df$X1stFlrSF+1)\n df_clean$X2ndFlrSF <- log(df$X2ndFlrSF+1)\n df_clean$BsmtUnfSF <- log(df$BsmtUnfSF+1)\n \n return(df_clean)\n}\n\nAreaToLogAreaExcluded90 <- function(df){\n df_clean <- data.frame(df)\n df_clean$X3SsnPorch <- log(df$X3SsnPorch+1)\n df_clean$LowQualFinSF <- log(df$LowQualFinSF+1)\n df_clean$ScreenPorch <- log(df$ScreenPorch+1)\n df_clean$MiscVal <- log(df$MiscVal+1)\n df_clean$PoolArea <- log(df$PoolArea+1)\n df_clean$WoodDeckSF <- log(df$WoodDeckSF+1)\n df_clean$OpenPorchSF <- log(df$OpenPorchSF+1)\n df_clean$EnclosedPorch <- log(df$EnclosedPorch+1)\n return(df_clean)\n}\n\n```\n\n\\pagebreak\n\n#EDA: Exploration of Linear relationships to LogResponse: Check other fields manually\n\n## Compare Total Rooms Above Ground\n\nWe see from the plots below, that the rooms above ground level don't change much in comparison to their log versions. The inherent data is naturally linear already and do not need to be transformed\n\n```{r fig.width=7, fig.height=3}\n\nreg <- df %>% \n mutate(log_Saleprice = log(SalePrice)) %>% \n ggplot(aes(x=TotRmsAbvGrd, y=log_Saleprice)) + \n geom_point() +\n labs(title='TotRmsAbvGrd')\n\n\nlog <- df %>% \n mutate(log_Saleprice = log(SalePrice)) %>% \n ggplot(aes(x=log(TotRmsAbvGrd), y=log_Saleprice)) + \n geom_point() +\n labs(title='Log TotRmsAbvGrd')\n\nmultiplot(reg,log, cols=2)\n```\n\n\n## Compare How old the house is (Yr Built in years)\n\nWe see from the plots below, similarly, the years old the house is is loosely already linear to log sale price and does not need to be transformed.\n\n```{r fig.width=7, fig.height=3}\n\nreg <- df %>% \n mutate(log_Saleprice = log(SalePrice)) %>% \n ggplot(aes(x=YearBuilt, y=log_Saleprice)) + \n geom_point() +\n labs(title='YearBuilt')\n\n\nlog <- df %>% \n mutate(log_Saleprice = log(SalePrice)) %>% \n ggplot(aes(x=log(YearBuilt), y=log_Saleprice)) + \n geom_point() +\n labs(title='Log YearBuilt')\n\nmultiplot(reg,log, cols=2)\n```\n\n## Compare Garage Area \n\nWe look at garage area to see if log Area will be more closely linearly related to log price, and we see the shape straighten and spread out\n\n```{r fig.width=7, fig.height=3}\n\nreg <- df %>% \n mutate(log_Saleprice = log(SalePrice)) %>% \n ggplot(aes(x=GarageArea, y=log_Saleprice)) + \n geom_point() +\n labs(title='GarageArea')\n\n\nlog <- df %>% \n mutate(log_Saleprice = log(SalePrice)) %>% \n ggplot(aes(x=log(GarageArea), y=log_Saleprice)) + \n geom_point() +\n labs(title='Log GarageArea')\n\nmultiplot(reg,log, cols=2)\n```\n\n## Compare first floor Square Footage\n\nAs verification we look at first floor area to see if log Area will be more closely linearly related to log price, and we see the shape straighten and spread out. As a result, we will convert all area metrics into log versions of them to have a better linear relationship with the log price.\n\n```{r fig.width=7, fig.height=3}\n\nreg <- df %>% \n mutate(log_Saleprice = log(SalePrice)) %>% \n ggplot(aes(x=X1stFlrSF, y=log_Saleprice)) + \n geom_point() +\n labs(title='X1stFlrSF')\n\n\nlog <- df %>% \n mutate(log_Saleprice = log(SalePrice)) %>% \n ggplot(aes(x=log(X1stFlrSF), y=log_Saleprice)) + \n geom_point() +\n labs(title='Log X1stFlrSF')\n\nmultiplot(reg,log, cols=2)\n```\n\n\n\n\\pagebreak\n\n#EDA: Outlier Analysis\n\n```{r}\n\n# setup the fit model\ny_log <- df_clean$SalePrice %>% log %>% unlist\nX <- df_clean %>% select (-SalePrice,-Id)\nfit <- lm(y_log ~., X)\n```\n\n\n\n## Influence Plot\n\nFrom running a quick influence plot, we see a good number of outlier points with high influence (large circles). From the plot, there's approximately 30+ points that are outside of the criteria (horizontal lines)\n\n```{r fig.width=7, fig.height=4}\n# Influence Plot\ninfluencePlot(fit,\tid.method=\"identify\", main=\"Influence Plot\", sub=\"Circle size is proportial to Cook's Distance\" )\n```\n\n## Function: Using DFFITS to Exclude Points\n\nWill use the rule $$ 2\\sqrt{\\frac{p}{n}} $$ < DFFITS. To exclude points\n\n```{r}\ndf_clean <-df %>% \n Years_to_Age %>% \n SwapToFactor %>% \n DealWithNulls %>% \n QualityToNumeric %>% \n ImputeValues %>% \n RoofMatlToDollars %>% \n RemoveCollinear %>% \n #ExcludeFeatures_90Plus %>% # this was to improve the score \n AreaToLogArea %>% \n AreaToLogAreaExcluded90\n\nExclude_Outliers <- function(df_clean){\n\n # pull out OLS variables (will use all of them at the moment)\n y_log <- df_clean$SalePrice %>% log %>% unlist\n X <- df_clean %>% select (-SalePrice,-Id)\n \n # fit the model\n fit <- lm(y_log ~., X)\n \n # Set a general cut off parametner\n # 2 sqrt(p/n)\n y_log <- df_clean$SalePrice %>% log %>% unlist\n X <- df_clean %>% select (-SalePrice,-Id)\n fit_dffits<- ols_dffits_plot(lm(y_log ~., X))\n \n # conservatively leave the NA's in\n points_to_exclude_by_id <- fit_dffits$outliers$Observation\n \n # find hte points to keep\n points_to_keep <- setdiff(1:nrow(df_clean), points_to_exclude_by_id)\n \n # dplyr to filter for those points to keep\n return(df_clean %>% filter(Id %in% points_to_keep))\n}\n\n# Sample\nz <- Exclude_Outliers(df_clean)\n\n```\n\n\\pagebreak\n\n#EDA: Export to Disk for others to use:\n\n```{r fig.show=\"hide\"}\ndf_clean <- df %>% \n Years_to_Age %>% \n SwapToFactor %>% \n DealWithNulls %>% \n QualityToNumeric %>% \n ImputeValues %>% \n RoofMatlToDollars %>% \n RemoveCollinear %>% \n Exclude_Outliers\n\ndf %>% \n Years_to_Age %>% \n SwapToFactor %>% \n DealWithNulls %>% \n QualityToNumeric %>% \n ImputeValues %>% \n RoofMatlToDollars %>%\n RemoveCollinear %>% \n ExcludeFeatures_90Plus %>% \n Exclude_Outliers %>% \n write.csv('~/Documents/MSAN/04-601-LinRegression/Project/clean_dataframe.csv')\n\n```\n\n\\pagebreak\n\n#EDA: Function: Value counts within each field\n\nThis table is a mini histogram per field, it lists the top values, how often they show up and what % of the total field they occupy. These are used for identifying fields over 90% dominated by a single value.\n\n```{r}\n\nget_df_stats <- function(df){\n # get statistics\n rows <- nrow(df)\n colno <- ncol(df)\n colnames <- names(df)\n all_headings <- list()\n all_outputs <- list()\n null_pct <- list()\n \n # loop through each column\n for (i in 1:colno){\n \n # store the headings\n all_headings[[i]] <- colnames[i]\n \n # make the histogram for one field\n histo <- df %>% \n select(paste(colnames[i])) %>% \n group_by_at(colnames[i]) %>% \n count %>% \n arrange(desc(n)) %>% \n head(3)\n \n output <- ''\n \n # then order it and concatente the info\n # on a single line wiht % and #\n for (j in 1:nrow(histo)){\n \n value <- histo[[j,colnames[i]]]\n value_count <- histo[[j,'n']]\n value_count_pct <- round(histo[j,'n']/rows,2)*100\n \n \n null_pct[[i]] <- df %>% \n select(paste(colnames[i])) %>% \n is.na %>% \n sum()*1.0 / rows %>% \n round(2)*100\n \n # assemble the string output\n output <- paste0(output,\n '(',value_count_pct,'%, --',value,'--,', value_count,'# )', \n sep=' ', \n collapse = ' ')\n }\n \n # add the completed string\n all_outputs[[i]] <- output\n }\n return(list(all_headings, all_outputs, null_pct))\n}\n\nclean_stats <- get_df_stats(df_clean)\n \n# create a data table summary\nsummary <- data.frame(headings = unlist(clean_stats[[1]]), \n top_hist_values=unlist(clean_stats[[2]]), \n null_pcts=unlist(clean_stats[[3]]))\n# format for print\nsummary %>% arrange(desc(top_hist_values)) %>% head(30) %>% kable\n```\n\n\n\n\\pagebreak\n\n\\pagebreak\n\n# OLS: Linear Model Building\n\n## Load clean data\n\nWill clean the dataframe with all the same functions outlined in the EDA section.\n\n```{r fig.show=\"hide\"}\ndf <- read.csv('~/Documents/MSAN/04-601-LinRegression/Project/housing.txt', stringsAsFactors = FALSE)\n\ndf_clean <-df %>% \n Years_to_Age %>% \n SwapToFactor %>% \n DealWithNulls %>% \n QualityToNumeric %>% \n ImputeValues %>% \n RoofMatlToDollars %>% \n RemoveCollinear %>% \n #ExcludeFeatures_90Plus %>% # this was to improve the score \n AreaToLogArea %>% \n AreaToLogAreaExcluded90 %>% \n Exclude_Outliers\n\n\n\n```\n\n## Define the X by including all fields\n\nDefine our X features by all the fields, except the response variable\n```{r}\nX_OLS_all <- df_clean %>% select(-SalePrice, -Id)\n```\n\n## As discussed in EDA, will set our target Response Y to Log(SalePrice)\n```{r fig.width=5, fig.height=3}\ny_OLS <- df_clean %>% select(SalePrice) %>% unlist %>% as.numeric\ny_OLS_log <- log(y_OLS)\n```\n\n#OLS: Fit the OLS Model - All Fields (After EDA processing)\n\n```{r}\n# fit model\nfit_model <- lm(y_OLS_log ~., X_OLS_all)\n\n# interpolate the values y_hat\ny_hat_log <- predict(lm(y_OLS_log ~., X_OLS_all), X_OLS_all, se.fit = TRUE)[[1]]\n```\n\n## R-squared and MSE\n\n```{r}\nprint(summary(fit_model)$r.squared)\n# calculate MSE\nLog_MSE <- mean((y_hat_log - y_OLS_log)^2)\nprint(Log_MSE)\n\nMSE <- mean((exp(y_hat_log) - exp(y_OLS_log))^2)\nprint(MSE)\nprint(sqrt(MSE))\n\n\n```\n\n## Plot Y_predicted by Y_hat\n```{r fig.width=7, fig.heigh=3}\n# plot the result of y_hat vs. y_orig\np1<- data.frame(y_hat=y_hat_log, y_OLS=y_OLS_log) %>% \n ggplot(aes(x=y_hat, y=y_OLS)) + \n geom_point()+ \n geom_point(aes(x=y_hat, y=y_hat), color='red')+\n labs(x= \"Y Predicted (Log Sale Price)\", y = \"Y True (Log Sale Price)\", title=\"OLS Linear Regression of Log Sales Price\")\n\np2<- data.frame(y_hat=exp(y_hat_log), y_OLS=exp(y_OLS_log)) %>% \n ggplot(aes(x=y_hat, y=y_OLS)) + \n geom_point()+ \n geom_point(aes(x=y_hat, y=y_hat), color='red')+\n labs(x= \"Y Predicted (Sale Price)\", y = \"Y True (Sale Price)\", title=\"OLS Linear Regression of Sales Price\")\n\nmultiplot(p1,p2, cols=2)\n```\n\n\\pagebreak\n\n#OLS: Normality of Errors\n\n## Plot: Residuals vs. Response\n\n```{r fig.width=7, fig.height=3}\nresiduals <- y_hat_log - y_OLS_log\n\np1<- data.frame(y_OLS_log, residuals) %>% \n ggplot(aes(x=y_OLS_log,y=residuals)) + geom_point() + labs(x='Log Sale Price', y='Residuals (y_hat - y_true)', title='Residuals Scatter Plot (of the Logs)')\n\np2<- data.frame(y_OLS=exp(y_hat_log), residuals=(exp(y_hat_log) - exp(y_OLS_log))) %>% \n ggplot(aes(x=y_OLS,y=residuals)) + geom_point() + labs(x='Sale Price', y='Residuals (y_hat - y_true)', title='Residuals Scatter Plot (Non-Transformed)')\n\nmultiplot(p1,p2, cols=2)\n```\n\n## Plot: Distribution of the Residuals (Normalized)\n\n```{r fig.width=7, fig.height=3}\nresiduals_norm <- (residuals-mean(residuals))/sd(residuals)\ndata.frame(residuals_norm=residuals_norm) %>% ggplot(aes(x=residuals_norm)) + geom_histogram(bins=40) + labs(x='residuals (Normed)', y='Count', title='Distribution of Residuals (y_hat - y_true)')\n```\n\n\n## K-S Test of the Residuals\n```{r}\nn_resid <- length(residuals_norm)\nstd_norm <- rnorm(n = n_resid,mean = 0, sd = 1 )\n\nprint(ks.test(residuals_norm,std_norm))\n```\n\n#OLS: Significant Factors\n\n## Signficant Features Pr (<0.05), then ordered by Beta Magnitude\n```{r}\nOLS_results_df <- data.frame(summary(fit_model)$coefficients)\ncolnames(OLS_results_df) <- c('Beta_est','StdErr','t_val','Pr')\nOLS_results_df$names <- labels(OLS_results_df)[[1]]\nOLS_results_df %>% \n filter(Pr<0.05) %>% \n arrange(desc(abs(Beta_est))) %>% \n mutate(ct=rownames(.)) %>% \n kable(digits=c(3,3,3,3))\n```\n\n\\pagebreak\n\n--- \n\n# Discussion of Dominant OLS Factors:\n\nThe following section will look at some of the dominant features found in the OLS analysis and will do plots vs. Sale Price to verify the strong signal\n\n## Strong Beta: Comparison of Price vs. Zoning\n\n- A\tAgriculture\n- C\tCommercial\n- FV\tFloating Village Residential\n- I\tIndustrial\n- RH\tResidential High Density\n- RL\tResidential Low Density\n- RP\tResidential Low Density Park \n- RM\tResidential Medium Density\n\n```{r fig.width=7, fig.height=4}\np1 <- df_clean %>% \n select(SalePrice, MSZoning) %>%\n ggplot(aes(x=MSZoning, y=SalePrice)) + \n geom_violin() +\n labs(title = 'Sale Price vs. MSZone')\n\np2 <- df_clean %>% \n select(SalePrice, MSZoning) %>%\n ggplot(aes(x=MSZoning, y=log(SalePrice))) + \n geom_violin() +\n labs(title = 'Log Sale Price vs. MSZone')\n\nmultiplot(p1,p2, cols=2)\n```\n\n## Strong Beta: Comparison of Price Garage Type\n\n- 2Types\tMore than one type of garage\n- Attchd\tAttached to home\n- Basment\tBasement Garage\n- BuiltIn\tBuilt-In (Garage part of house - typically has room above garage)\n- CarPort\tCar Port\n- Detchd\tDetached from home\n- NA\tNo Garage\n\n```{r fig.width=7, fig.height=4}\np1 <- df_clean %>% \n select(SalePrice, GarageType) %>%\n ggplot(aes(x=GarageType, y=SalePrice)) + \n geom_violin() +\n labs(title = 'Sale Price vs. MSZone')\n\np2 <- df_clean %>% \n select(SalePrice, GarageType) %>%\n ggplot(aes(x=GarageType, y=log(SalePrice))) + \n geom_violin() +\n labs(title = 'Log Sale Price vs. MSZone')\n\nmultiplot(p1,p2, cols=2)\n```\n\n## Strong Beta: Lot Configuration\n\n- Inside\tInside lot\n- Corner\tCorner lot\n- CulDSac\tCul-de-sac\n- FR2\tFrontage on 2 sides of property\n- FR3\tFrontage on 3 sides of property\n\n```{r fig.width=7, fig.height=4}\np1 <- df_clean %>% \n select(LotConfig, SalePrice) %>%\n ggplot(aes(x=LotConfig, y=SalePrice)) + \n geom_violin() +\n labs(title = 'Sale Price vs. LotConfig')\n\np2 <- df_clean %>% \n select(SalePrice,LotConfig ) %>%\n ggplot(aes(x=LotConfig, y=log(SalePrice))) + \n geom_violin() +\n labs(title = 'Log Sale Price vs. LotConfig')\n\nmultiplot(p1,p2, cols=2)\n```\n\n## Comparison of General Living Area vs. Price\n\n\n```{r fig.width=7, fig.height=4}\np1 <- df_clean %>% \n select(SalePrice, GrLivArea) %>%\n ggplot(aes(x=GrLivArea, y=SalePrice)) + \n geom_point() +\n labs(title = 'Sale Price vs. General Living Area')\n\np2 <- df_clean %>% \n select(SalePrice, GrLivArea) %>%\n ggplot(aes(x=log(GrLivArea), y=log(SalePrice))) + \n geom_point() +\n labs(title = 'Log Sale Price vs. General Living Area')\n\nmultiplot(p1,p2, cols=2)\n```\n\n\n## Comparison of Lot Area vs. Price\n\n```{r fig.width=7, fig.height=4}\np1 <- df_clean %>% \n select(SalePrice, LotArea) %>%\n ggplot(aes(x=LotArea, y=SalePrice)) + \n geom_point() +\n labs(title = 'Sale Price vs. General Living Area')\n\np2 <- df_clean %>% \n select(SalePrice, LotArea) %>%\n ggplot(aes(x=log(LotArea), y=log(SalePrice))) + \n geom_point() +\n labs(title = 'Log Sale Price vs. Lot Area')\n\nmultiplot(p1,p2, cols=2)\n```\n\n\n## Comparison of Overall Quality vs. Price\n\n```{r fig.width=7, fig.height=4}\np1 <- df_clean %>% \n select(SalePrice, OverallQual) %>%\n ggplot(aes(x=OverallQual, y=SalePrice)) + \n geom_jitter()+\n labs(title = 'Sale Price vs. Overall Quality')\n\np2 <- df_clean %>% \n select(SalePrice, OverallQual) %>%\n ggplot(aes(x=OverallQual, y=log(SalePrice))) + \n geom_jitter() +\n labs(title = 'Sale Price vs. Overall Quality')\n\nmultiplot(p1,p2, cols=2)\n```\n\n```{r }\ndf_clean %>% \n select(SalePrice, LotArea, GrLivArea) %>%\n ggplot(aes(x=GrLivArea, y=LotArea,size=SalePrice) ) + \n geom_hline(yintercept = mean(df_clean$LotArea), color='red') +\n geom_vline(xintercept = mean(df_clean$GrLivArea), color='red') +\n geom_point()+\n labs(title = 'General Living Area vs. LotArea, Sale Price = Size')\n```\n\n\n--- \n\n# OLS: Cosine Similiarity of Morty to Other Houses\n\n```{r fig.show=\"hide\", include=FALSE}\nx_new <- \n read.csv('Morty.txt', stringsAsFactors = F) %>% \n select(-X) # Make sure pathname here is right\n\nx_clean <- x_new %>% \n Years_to_Age %>% \n DealWithNulls %>% \n SwapToFactor %>% \n QualityToNumeric %>% \n RoofMatlToDollars %>% \n RemoveCollinear %>% \n #ExcludeFeatures_90Plus %>% # this was to improve the score \n AreaToLogArea %>% \n AreaToLogAreaExcluded90 %>% select(-Id,-SalePrice)\n```\n\n```{r}\n\n# Bind together\ny_OLS_hat <- predict(fit_model, X_OLS_all)\n\n# Convert to dummy variables + model matrix\nproxy_matrix <- model.matrix(SalePrice~.,df_clean %>% select(-Id))\n\n# Pull morty's vector out\ntarget_vec <- proxy_matrix[5,] \n\n# The remaining houses will be compared to\ncompar_vecs <-proxy_matrix\nrows <- nrow(compar_vecs)\n\n```\n\n## Loop through and compare against all other houses\n\n```{r}\n# Calculate all teh scores\nscores <- list()\nfor (i in 1:rows){\n #scores[[i]] <- cosine.similarity(target_vec, compar_vecs[i,], .do.norm=T)\n scores[[i]] <- target_vec %*% compar_vecs[i,] / norm(target_vec,type=\"2\") / norm(compar_vecs[i,],type=\"2\")\n}\n```\n\n\n## Rebuild the data frame with predicted prices + morty's house. Sort by cosine similarity\n\n```{r cache=F}\nx_clean$Id <- 9999\nx_clean$SalePrice <- 143000\n\nclose_5 <- df_clean%>% \n mutate(OLS_price = exp(y_OLS_hat)) %>% \n mutate(proxy_score = unlist(scores)) %>% \n bind_rows(x_clean) %>% \n arrange(desc(proxy_score)) %>% head(6) \n```\n\n## Show Similar Houses\n\n\\small\n\n```{r cache=F}\nt(close_5) %>% kable\n```\n\n```{r include=FALSE}\n# for exporting for business report\nto_out<- t(close_5) %>% data.frame\nto_out$rownames <- row.names(to_out)\nto_out %>% write.csv('similarhouses.csv')\n```\n\n\\normalsize\n\n\\pagebreak\n\n# OLS: Explanatory Modeling: Part II\n\nWe are given a new set of features, Morty's house. We now clean this in the same way to put into our model:\n```{r}\n# Make sure this pipeline is still up to date\nx_new <- \n read.csv('Morty.txt', stringsAsFactors = F) %>% \n select(-X) # Make sure pathname here is right\n\nx_clean <- x_new %>% \n Years_to_Age %>% \n DealWithNulls %>% \n SwapToFactor %>% \n QualityToNumeric %>% \n RoofMatlToDollars %>% \n RemoveCollinear %>% \n #ExcludeFeatures_90Plus %>% # this was to improve the score \n AreaToLogArea %>% \n AreaToLogAreaExcluded90 %>% select(-Id,-SalePrice)\n```\n\n## Confidence interval of Morty's House Price\nOur first task is to predict the value, so let's explore the 95% CI given by our model:\n```{r}\nfit_model <- lm(y_OLS_log~., df_clean %>% select(-Id,-SalePrice))\nlog_y <- predict(fit_model, x_clean, interval = 'predict', level = 0.95)\n(y <- exp(log_y))\n```\nWe find a fitted value of \\$ `r y[1,1]`, with a 95% CI of (\\$ `r y[1,2]`, \\$ `r y[1,3]`). As such, we conclude the maximise value we can reasonably expect the house to sell for is \\$ `r y[1,3]`.\n\nNote that this analysis relies solely on unbiased OLS estimators. Our predicted range is wide, but the needed for an unbiased estimator in order to construct a CI necessitates the use of OLS for our estimation.\n\n# Key Factors\n\n##Assessing key factors to change:\n\nFirst, let's just have a look at the coefficients we've got in our model:\n\n\\small\n\n```{r}\nsummary(fit_model)\n```\n\n\\normalsize\n\nNow let's make some ground rules for how we're going to search: \n- A lot of features will be excluded immediately because they're not under our control (e.g. district of the house) \n- Our OLS analysis deals with correlation, and so we have no information as to causation. As such, we will try to safeguard our suggestions with the highest of significance levels and cross check this with common sense. \n- For the reason above, we'll look for fields that will add maximum value for minimum expense, to avoid unnecessary costs for Morty.\n\nGiven that we're most concerned by the significance of our coefficients, let's rank by the SL and exclude any not significant at 95% level:\n```{r}\nsignificant_fields <- NULL\ncoeffs <- NULL\nSL <- NULL\nfor(i in 1:135){\n if(summary(fit_model)$coefficients[i,4] < 0.05){\n significant_fields <- c(significant_fields, row.names(summary(fit_model)$coefficients)[i])\n coeffs <- c(coeffs, summary(fit_model)$coefficients[i,1])\n SL <- c(SL, summary(fit_model)$coefficients[i,4])\n }\n}\n(sig_fields_df <- data.frame(field = significant_fields, beta = coeffs, SL = SL) %>% arrange(SL))\n```\n\nOur process now will be to start with the most significant variables - search to find ones which we may be able to change on short notice, and then see how Morty's property compares to average values:\n\nEvaluating categories we think we may be able to change:\n\n##1. Fireplaces\n\n```{r}\n(Morty_Fireplaces <- x_clean$Fireplaces)\n(avg_Fireplaces <- mean(df_clean$Fireplaces))\n```\n\nMorty has a below average number of fireplaces (0), so adding an electrical fireplace may give his house an added boost if appropriate.\n\n**Adding an electrical fireplace may boost the appeal of Morty's house.**\n\n##2. Half-Bathrooms:\n\n\n```{r}\n(Morty_HalfBath <- x_clean$HalfBath)\n(avg_HalfBath <- mean(df_clean$HalfBath))\n```\n\nMorty's already above average on this metric though, so likely isn't going to be helped by creating more half-bathrooms.\n\n##3. Garage Cars:\n```{r}\n(Morty_GarageCars <- x_clean$GarageCars)\n(avg_GarageCars <- mean(df_clean$GarageCars))\n```\n\nAbove average on this one too so unlikely to help by adding garage capacity.\n\n##4. Heating Quality and Condition:\n\n```{r}\n(Morty_HeatingQC <- x_clean$HeatingQC)\n(avg_HeatingQC <- mean(df_clean$HeatingQC))\n```\n\nLikewise, Morty already has excellent heating quality and condition.\n\n##5. Kitchen Quality:\n\n```{r}\n(Morty_Kitchen <- x_clean$KitchenQual)\n(avg_Kitchen <- mean(df_clean$KitchenQual))\n```\n\n**Kitchen Quality - could be improved on to bring up to average.**\n\n##6. Garage Finish:\n\n```{r}\n(Morty_GarageFinish <- x_clean$GarageFinish)\n(avg_GarageFinish <- mean(df_clean$GarageFinish))\n```\n\n**Morty has below average garage finish, and we would think this is an easy thing to improve on.**\n\n\\pagebreak\n\n---\n\n#OLS: Summary\n\nThese are the only variables we can spot that are significant at 95% level that can be easily adapted. As such, we only have a list of 3 which we think can reasonably be improved upon: \n1. Adding electrical fireplace \n2. Improving kitchen quality \n3. Improving garage finish.\n\nIf, we impute the mean values for these metrics (and add a single fireplace) and recalculate the prediction interval:\n```{r}\nx_update <- x_clean\nx_update$KitchenQual <- mean(df_clean$KitchenQual)\nx_update$GarageFinish <- mean(df_clean$GarageFinish)\nx_update$Fireplaces <- 1\nlog_y_update <- predict(fit_model, x_update, interval = 'predict', level = 0.95)\n(y <- exp(log_y_update))\n```\n\nFinally, we summarise all of the above information in one table:\n```{r}\nmodel_params <- sig_fields_df %>% filter(field == 'Fireplaces' | field == 'KitchenQual' | field == 'GarageFinish')\nMorty_values <- data.frame(Morty = as.numeric(c(x_clean['Fireplaces'], x_clean['KitchenQual'], x_clean['GarageFinish'])))\nMean_values <- data.frame(Mean = as.numeric(c(mean(df_clean$Fireplaces), mean(df_clean$KitchenQual), mean(df_clean$GarageFinish))))\nsummary_data <- cbind(model_params, Morty_values, Mean_values)\nsummary_data$exp_beta <- exp(summary_data$beta)\nkable(summary_data)\n```\n\n\nNote that the final column in this table, the exponent of the coefficient, represents the approximate factor that value would increase if we were to increment the corresponding feature value by 1 unit.\n\n\\pagebreak\n\n# Pred: Predictive Analysis\n\n\n```{r include=F}\n# rm(list=ls()) # removes all objects from the environment\n# cat(\"\\014\") # clears the console\n# library(tidyverse)\n# library(magrittr)\n# library(glmnet)\n# select <- dplyr::select\n# source('Part2-case_study_common_funcs.R')\n\n```\n\n## Predictive modeling - Data Prep\n\n\n\n```{r}\nclean <- function(df){\n housing <- df\n \n pct_na <- sapply(housing, function(x) round((sum(is.na(x)) / length(x))*100))\n housing <- housing[,pct_na < 80]\n \n max_pct <- sapply(housing, function(x) round(max((table(x)/length(x))*100)))\n housing <- housing[,max_pct<90]\n \n housing$GarageYrBlt <- sapply(housing$GarageYrBlt, function(x) (as.integer(x) %/% 10) *10)\n housing$GarageYrBlt <- paste0(as.character(housing$GarageYrBlt), 's')\n \n housing$GarageYrBlt[is.na(housing$GarageYrBlt)] <- \"None\"\n housing$GarageType[is.na(housing$GarageType)] <- \"None\"\n housing$GarageFinish[is.na(housing$GarageFinish)] <- \"None\"\n housing$MasVnrType[is.na(housing$MasVnrType)] <- 'None'\n housing$BsmtQual[is.na(housing$BsmtQual)] <- 'None'\n housing$BsmtExposure[is.na(housing$BsmtExposure)] <- \"None\"\n housing$BsmtFinType1[is.na(housing$BsmtFinType1)] <- 'None'\n housing$BsmtFinType2[is.na(housing$BsmtFinType2)] <- \"None\"\n housing$FireplaceQu[is.na(housing$FireplaceQu)] <- \"None\"\n \n housing$MasVnrArea[is.na(housing$MasVnrArea)] <- 0\n housing$LotFrontage[is.na(housing$LotFrontage)] <- 0\n \n housing$MSSubClass <- factor(housing$MSSubClass, levels = c(20,30, 40, 45, 50, \n 60, 70, 75, 80, 85, \n 90, 120, 150, 160, \n 180, 190), \n labels = c('1-STORY 1946 & NEWER ALL STYLES',\n '1-STORY 1945 & OLDER',\n '1-STORY W/FINISHED ATTIC ALL AGES',\n '1-1/2 STORY - UNFINISHED ALL AGES',\n '1-1/2 STORY FINISHED ALL AGES',\n '2-STORY 1946 & NEWER',\n '2-STORY 1945 & OLDER',\n '2-1/2 STORY ALL AGES',\n 'SPLIT OR MULTI-LEVEL',\n 'SPLIT FOYER','DUPLEX - ALL STYLES AND AGES',\n '1-STORY PUD (Planned Unit Development) - 1946 & NEWER',\n '1-1/2 STORY PUD - ALL AGES',\n '2-STORY PUD - 1946 & NEWER',\n 'PUD - MULTILEVEL - INCLSPLIT LEV/FOYER',\n '2 FAMILY CONVERSION - ALL STYLES AND AGES'))\n \n cleaner <-\n housing %>% \n select(-Id)\n \n return(cleaner)\n}\n```\n\n## Predictive modeling - Test Train Split for Model Fitting\n\n20% of the entire data was held out for MSPE purposes. This is accomplished with the sample function that will randomly pull id's used for filtering. \n\n```{r}\nhousing <- read.csv('housing.txt', stringsAsFactors = F)\n\nhousing <- clean(housing)\n\ntrain <- sample(1:nrow(housing), nrow(housing) *(4/5))\ntest <- (-train)\n\nx <- model.matrix(SalePrice ~ ., data = housing)\ny <- housing$SalePrice\ngrid.lambda <- 10^seq(10, -2, length.out = 100)\n\ny.train <- y[train]\ny.test <- y[test]\nx.train <- x[train,]\nx.test <- x[test,]\n```\n\n\n## Ridge Modeling\n\nThe ridge regularized regression was used as a possible model. Due to the high number of features and often redundant data, there could be a high level of collinearity between different fields. As mentioned previously, total area in square feet is redundant if all the parts are found in the data. For example, the MSSubClass is really a mashup of the year, and the number of levels of the house. The ridge should automatically minimize the impact of these redundant features on the predictive model.\n\n```{r}\n# do a grid search of lambdas for optimal value\nmodel.ridge.train <- glmnet(x.train, y.train, alpha = 0, lambda = grid.lambda)\nset.seed(101)\ncv.ridge.out <- cv.glmnet(x.train, y.train, alpha = 0, type.measure = 'mse')\nbest.lambda.ridge <- cv.ridge.out$lambda.min\n\n# do predictions\nridge.pred <- predict(model.ridge.train, s = best.lambda.ridge, newx = x.test)\n\n# calculate error\nmspe.ridge <- mean((ridge.pred - y.test)^2)\nmodel.ridge.final <- glmnet(x, y, alpha = 0, lambda = best.lambda.ridge)\nridge.coefs <- coef(model.ridge.final)[-2,]\nr.squared.ridge <- max(model.ridge.final$dev.ratio)\n```\n\n## Lasso Modeling\n\nLasso modeling was also applied against the dataset. This was ideal because we suspect that over 80+ features, there are probably a large number of features that do not have an affect on sales price. Things such as paved roads, or electrical breakers will most likely have little effect. Instead of plotting each of these fields against the main response variable SalePrice, we will apply a Lasso Regularized model which will drop some of these unnecessary variables. \n\n```{r}\n# do a grid search of lambdas for optimal value\nmodel.lasso.train <- glmnet(x.train, y.train, alpha = 1, lambda = grid.lambda)\nset.seed(101)\ncv.lasso.out <- cv.glmnet(x.train, y.train, alpha = 1, type.measure = 'mse')\nbest.lambda.lasso <- cv.lasso.out$lambda.min\n\n# do predictions\nlasso.pred <- predict(model.lasso.train, s = best.lambda.lasso, newx = x.test)\n\n# calculate error\nmspe.lasso <- mean((lasso.pred - y.test)^2)\nmodel.lasso.final <- glmnet(x, y, alpha = 1, lambda = best.lambda.lasso)\nlasso.coefs <- coef(model.lasso.final)[-2,]\nr.squared.lasso <- max(model.lasso.final$dev.ratio)\n```\n\n## ElasticNet Modeling\n\nElasticNet was also used, which has both regularization terms from both Ridge and Lasso, with an alpha blend factor. The model that was tried here was with alpha = 0.5\n\n```{r}\n# do a grid search of lambdas for optimal value\nmodel.en.train <- glmnet(x.train, y.train, alpha = 0.5, lambda = grid.lambda)\nset.seed(101)\ncv.en.out <- cv.glmnet(x.train, y.train, alpha = 0.5, type.measure = 'mse')\nbest.lambda.en <- cv.en.out$lambda.min\n\n# do predictions\nen.pred <- predict(model.en.train, s = best.lambda.en, newx = x.test)\n\n# calculate error\nmspe.en <- mean((en.pred - y.test)^2)\nmodel.en.final <- glmnet(x, y, alpha = 0.5, lambda = best.lambda.en)\nen.coefs <- coef(model.en.final)[-2,]\nr.squared.en <- max(model.en.final$dev.ratio)\n```\n\n## OLS Modeling informed by lasso model \n\nOLS was re-run again, only pulling features that were selected after running the Lasso model. This was used as a baseline score to compare the other models against.\n\n```{r}\n# ols defined by lasso variables\nols.vars <- names(abs(lasso.coefs) > 0)\n\n# ols defined by lasso variables\nx.ols <- x[, abs(lasso.coefs) > 0]\n\n# ols test train split\nx.ols.train <- x.ols[train,]\nx.ols.test <- x.ols[test,]\n\n# run the model\nmodel.ols.train <- lm(y.train ~ x.ols.train)\nset.seed(101)\nols.pred <- predict(model.ols.train, newx = x.ols.test)\nmspe.ols <- mean((ols.pred - y.test)^2)\nr.squared.ols <- summary(model.ols.train)$r.squared\n\n```\n\n\n```{r}\nCoefficients <- data.frame(Ridge = ridge.coefs, Lasso = lasso.coefs, Elastic.Net = en.coefs)\n\nMSPE_frame <- data.frame(model=c('Ridge','Lasso','Elastic.net', 'OLS'), \n MSPEscores= c(mspe.ridge, mspe.lasso, mspe.en, mspe.ols),\n r.squared = c(r.squared.ridge, r.squared.lasso, r.squared.en, r.squared.ols),\n best.lambda = c(best.lambda.ridge, best.lambda.lasso, best.lambda.en, 0)\n ) %>% mutate(RMSPE = sqrt(MSPEscores))\nMSPE_frame %>% kable\n```\n\n\n## Regularized Prediction Discussion:\n\nTask 2: Predictive Modeling\n\nHere, we employed a handful of modeling techniques, iteratively testing out how well they performed as measured by the mean squared prediction error on a set of hold out data. Parameters for the models considered were generated via OLS, Ridge, LASSO, and Elastic Net algorithms. Besides sharing the same model type as explanatory modeling, extrapolation was markedly different in the following ways:\n\nNormality Conditions: When optimizing our model for explanation, we used a number of functions to clean and alter the data in order to reduce bias and meet several assumptions when performing regression. When optimizing our model for prediction, however, we relaxed these assumptions to focus our concerns on prediction performance. Since we were only focused on the closeness of our predictions, our main criterion for selecting our best regression model was minimizing MSPE. \n\nVariable Selection: To do this, we took raw data and tested out different subsets of our earlier data cleaning functions. Some of the steps taken in the variable selection for interpolation could not be omitted, such as cleaning up any null values, imputing values where necessary, and changing qualitative variables to numeric variables. For the other cleaning procedures, such as translating the year a house was built to age or removing collinear variables, we exhausted all combinations to create \"partially clean\" datasets.\n\nParameter Selection: With the data cleaned, we then ran several iterations of OLS, Ridge, LASSO, and Elastic Net on these variables to find the parameter estimates whose model had the lowest MSPE. After much consideration, we finally settled on a model with parameter estimates generated by L1 norm penalized regression (Lasso). Despite the fact that the table below has Lasso listed as having the highest MSPE, when averaged out, Lasso actually had the lowest mean MSPE. It also proved to be useful for decisive variable selection. The model in all its glory is detailed in this report\n\n```{r}\nlasso_plot <- data.frame(y_hat=lasso.pred, true_sale_price = y.test) \ncolnames(lasso_plot) <- c('lasso_predictions','true_sale_price')\nlasso_plot %>% ggplot(aes(x=lasso_predictions, y=true_sale_price)) + \n geom_point() +\n geom_point(aes(x=lasso_predictions, y=lasso_predictions), color='red') +\n labs(x= \"Y Predicted (Sale Price)\", y = \"Y True (Sale Price)\", title=\"Lasso Regression of Sales Price\")+\n theme(axis.text.x = element_text(size=9), axis.text.y = element_text(size=9))+ theme(plot.title = element_text(size=11)) + theme(axis.text = element_text(size=11))\n```\n\n### Appendix: Optimal Lasso Beta Values\n```{r}\nlasso.coefs.ordered <- lasso.coefs[order(abs(lasso.coefs), decreasing = T)]\nlasso.coefs.ordered <- lasso.coefs.ordered[lasso.coefs.ordered != 0]\nlasso.coefs.ordered %>% data.frame %>% kable \n```\n" }, { "alpha_fraction": 0.8179775476455688, "alphanum_fraction": 0.8247190713882446, "avg_line_length": 62.57143020629883, "blob_id": "44e975a96db0fddcd574df4e90d7223306f05cfa", "content_id": "8b14da31942e8567132b5bc081465892629e8b6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 445, "license_type": "no_license", "max_line_length": 238, "num_lines": 7, "path": "/Regression_Project/README.md", "repo_name": "ajhoward7/Machine_Learning", "src_encoding": "UTF-8", "text": "# Linear Regression Case Study\n\nThis repository contains the code and outputs for a predictive modelling competition, using Linear Regression techniques. Original taken from [this](https://www.kaggle.com/c/house-prices-advanced-regression-techniques) Kaggle Competition.\n\nThe repository contains both the raw code and knitted documents split into 2 sections:\n1. Business Report with final results and models\n2. Exploratory Analysis and workbook\n" }, { "alpha_fraction": 0.6382513642311096, "alphanum_fraction": 0.6455373167991638, "avg_line_length": 41.55038833618164, "blob_id": "5d963acc3ac55eb18a3d2ac569f57183d4064f8a", "content_id": "b1b680372b9a93f900cbd147950cf85d8fadfd5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5490, "license_type": "no_license", "max_line_length": 116, "num_lines": 129, "path": "/ML/fastai/structured.py", "repo_name": "ajhoward7/Machine_Learning", "src_encoding": "UTF-8", "text": "from .imports import *\nfrom .torch_imports import *\nfrom .core import *\n\nimport IPython, graphviz\nfrom concurrent.futures import ProcessPoolExecutor\n\nimport sklearn_pandas, sklearn, warnings\nfrom sklearn_pandas import DataFrameMapper\nfrom sklearn.preprocessing import LabelEncoder, Imputer, StandardScaler\nfrom pandas.api.types import is_string_dtype, is_numeric_dtype\nfrom sklearn.ensemble import forest\nfrom sklearn.tree import export_graphviz\n\n\ndef set_plot_sizes(sml, med, big):\n plt.rc('font', size=sml) # controls default text sizes\n plt.rc('axes', titlesize=sml) # fontsize of the axes title\n plt.rc('axes', labelsize=med) # fontsize of the x and y labels\n plt.rc('xtick', labelsize=sml) # fontsize of the tick labels\n plt.rc('ytick', labelsize=sml) # fontsize of the tick labels\n plt.rc('legend', fontsize=sml) # legend fontsize\n plt.rc('figure', titlesize=big) # fontsize of the figure title\n\ndef parallel_trees(m, fn, n_jobs=8):\n return list(ProcessPoolExecutor(n_jobs).map(fn, m.estimators_))\n\ndef draw_tree(t, df, size=10, ratio=0.6, precision=0):\n s=export_graphviz(t, out_file=None, feature_names=df.columns, filled=True,\n special_characters=True, rotate=True, precision=precision)\n IPython.display.display(graphviz.Source(re.sub('Tree {',\n f'Tree {{ size={size}; ratio={ratio}', s)))\n\ndef combine_date(years, months=1, days=1, weeks=None, hours=None, minutes=None,\n seconds=None, milliseconds=None, microseconds=None, nanoseconds=None):\n years = np.asarray(years) - 1970\n months = np.asarray(months) - 1\n days = np.asarray(days) - 1\n types = ('<M8[Y]', '<m8[M]', '<m8[D]', '<m8[W]', '<m8[h]',\n '<m8[m]', '<m8[s]', '<m8[ms]', '<m8[us]', '<m8[ns]')\n vals = (years, months, days, weeks, hours, minutes, seconds,\n milliseconds, microseconds, nanoseconds)\n return sum(np.asarray(v, dtype=t) for t, v in zip(types, vals)\n if v is not None)\n\ndef get_nn_mappers(df, cat_vars, contin_vars):\n # Replace nulls with 0 for continuous, \"\" for categorical.\n for v in contin_vars: df[v] = df[v].fillna(df[v].max()+100,)\n for v in cat_vars: df[v].fillna('#NA#', inplace=True)\n\n # list of tuples, containing variable and instance of a transformer for that variable\n # for categoricals, use LabelEncoder to map to integers. For continuous, standardize\n cat_maps = [(o, LabelEncoder()) for o in cat_vars]\n contin_maps = [([o], StandardScaler()) for o in contin_vars]\n return DataFrameMapper(cat_maps).fit(df), DataFrameMapper(contin_maps).fit(df)\n\ndef get_sample(df,n):\n idxs = sorted(np.random.permutation(len(df)))\n return df.iloc[idxs[:n]].copy()\n\ndef add_datepart(df, fldname):\n fld = df[fldname]\n targ_pre = re.sub('[Dd]ate$', '', fldname)\n for n in ('Year', 'Month', 'Week', 'Day', 'Dayofweek', 'Dayofyear',\n 'Is_month_end', 'Is_month_start', 'Is_quarter_end', 'Is_quarter_start', 'Is_year_end', 'Is_year_start'):\n df[targ_pre+n] = getattr(fld.dt,n.lower())\n df[targ_pre+'Elapsed'] = fld.astype(np.int64) // 10**9\n df.drop(fldname, axis=1, inplace=True)\n\ndef is_date(x): return np.issubdtype(x.dtype, np.datetime64)\n\ndef train_cats(df):\n for n,c in df.items():\n if is_string_dtype(c): df[n] = c.astype('category').cat.as_ordered()\n\ndef apply_cats(df, trn):\n for n,c in df.items():\n if trn[n].dtype.name=='category':\n df[n] = pd.Categorical(c, categories=trn[n].cat.categories, ordered=True)\n\ndef fix_missing(df, col, name, na_dict):\n if is_numeric_dtype(col):\n if pd.isnull(col).sum() or (name in na_dict):\n df[name+'_na'] = pd.isnull(col)\n filler = na_dict[name] if name in na_dict else col.median()\n df[name] = col.fillna(filler)\n na_dict[name] = filler\n return na_dict\n\ndef numericalize(df, col, name, max_n_cat):\n if not is_numeric_dtype(col) and ( max_n_cat is None or col.nunique()>max_n_cat):\n df[name] = col.cat.codes+1\n\ndef scale_vars(df):\n warnings.filterwarnings('ignore', category=sklearn.exceptions.DataConversionWarning)\n map_f = [([n],StandardScaler()) for n in df.columns if is_numeric_dtype(df[n])]\n mapper = DataFrameMapper(map_f).fit(df)\n df[mapper.transformed_names_] = mapper.transform(df)\n return mapper\n\ndef proc_df(df, y_fld, skip_flds=None, do_scale=False, na_dict=None,\n preproc_fn=None, max_n_cat=None, subset=None):\n if not skip_flds: skip_flds=[]\n if subset: df = get_sample(df,subset)\n df = df.copy()\n if preproc_fn: preproc_fn(df)\n y = df[y_fld].values\n df.drop(skip_flds+[y_fld], axis=1, inplace=True)\n\n if na_dict is None: na_dict = {}\n for n,c in df.items(): na_dict = fix_missing(df, c, n, na_dict)\n if do_scale: mapper = scale_vars(df)\n for n,c in df.items(): numericalize(df, c, n, max_n_cat)\n res = [pd.get_dummies(df, dummy_na=True), y, na_dict]\n if do_scale: res = res + [mapper]\n return res\n\n\ndef rf_feat_importance(m, df):\n return pd.DataFrame({'cols':df.columns, 'imp':m.feature_importances_}\n ).sort_values('imp', ascending=False)\n\ndef set_rf_samples(n):\n forest._generate_sample_indices = (lambda rs, n_samples:\n forest.check_random_state(rs).randint(0, n_samples, n))\n\ndef reset_rf_samples():\n forest._generate_sample_indices = (lambda rs, n_samples:\n forest.check_random_state(rs).randint(0, n_samples, n_samples))\n\n" } ]
5
olof98johansson/SentimentAnalysisNLP
https://github.com/olof98johansson/SentimentAnalysisNLP
1b00a00cc4a15dba7bff3ada753d3d96ce4c2bfe
50622351eaddff5ec9ca5a607f8cae91e63bdcfb
4e7b593484408bde52f0912baa8b845ed591f776
refs/heads/main
2023-03-06T12:52:55.246599
2023-03-02T14:52:57
2023-03-02T14:52:57
321,100,537
3
1
null
null
null
null
null
[ { "alpha_fraction": 0.5060804486274719, "alphanum_fraction": 0.5346117615699768, "avg_line_length": 48.67441940307617, "blob_id": "8c40756bd1489d35a7e3e18c837323450d2aa51b", "content_id": "f391540f63fb22ecf3616fd4565d4945fba9bc92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2138, "license_type": "no_license", "max_line_length": 143, "num_lines": 43, "path": "/main.py", "repo_name": "olof98johansson/SentimentAnalysisNLP", "src_encoding": "UTF-8", "text": "import train\nimport preprocessing\n\n\ndef run():\n '''\n Training function to run the training process after specifying parameters\n '''\n\n preprocessing.config.paths = ['./training_data/depressive1.json',\n './training_data/depressive2.json',\n './training_data/depressive3.json',\n './training_data/depressive4.json',\n './training_data/depressive5.json',\n './training_data/depressive6.json',\n './training_data/non-depressive1.json',\n './training_data/non-depressive2.json',\n './training_data/non-depressive3.json',\n './training_data/non-depressive4.json',\n './training_data/non-depressive5.json',\n './training_data/non-depressive6.json']\n\n preprocessing.config.save_path = './training_data/all_training_data.csv'\n\n\n preprocessing.config.labels = ['depressive', 'depressive', 'depressive', 'depressive', 'depressive', 'depressive',\n 'not-depressive', 'not-depressive', 'not-depressive', 'not-depressive',\n 'not-depressive', 'not-depressive']\n\n preprocessing.config.keywords = ['depressed', 'lonely', 'sad', 'depression', 'tired', 'anxious',\n 'happy', 'joy', 'thankful', 'health', 'hopeful', 'glad']\n\n preprocessing.config.nr_of_tweets = [1000, 1000, 1000, 1000, 1000, 1000,\n 1000, 1000, 1000, 1000, 1000, 1000]\n\n history, early_stop_check = train.train_rnn(save_path='./weights/lstm_model_2.pth', collect=True) # Collect=False if already collected data\n\n train.show_progress(history=history, save_name='./plots/training_progress.png')\n\n train.animate_progress(history=history, save_path='./plots/training_animation_progress_REAL.gif',\n early_stop_check=early_stop_check)\n\nrun()\n\n\n" }, { "alpha_fraction": 0.5994142293930054, "alphanum_fraction": 0.6180015802383423, "avg_line_length": 36.901710510253906, "blob_id": "40c6e3ea3a1e8105d00b80421398b756212e2ff9", "content_id": "29257644644873088063b3e6331f5ad908b76528", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8877, "license_type": "no_license", "max_line_length": 106, "num_lines": 234, "path": "/train.py", "repo_name": "olof98johansson/SentimentAnalysisNLP", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport models\nimport preprocessing\nfrom collections import defaultdict\nimport time\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('darkgrid')\nfrom celluloid import Camera\n\n\ndef Logger(elapsed_time, epoch, epochs, tr_loss, tr_acc, val_loss, val_acc):\n '''\n Logger function to track training progress\n\n Input: elapsed_time - the current elapsed training time\n epoch - current epoch\n epochs - total number of epochs\n tr_loss/val_loss - current training/validation loss\n tr_acc/val_acc - current training/validation accuracy\n '''\n\n tim = 'sec'\n if elapsed_time > 60 and elapsed_time <= 3600:\n elapsed_time /= 60\n tim = 'min'\n elif elapsed_time > 3600:\n elapsed_time /= 3600\n tim = 'hrs'\n elapsed_time = format(elapsed_time, '.2f')\n print(f'Elapsed time: {elapsed_time} {tim} Epoch: {epoch}/{epochs} ',\n f'Train Loss: {tr_loss:.4f} Val Loss: {val_loss:.4f} ',\n f'Train Acc: {tr_acc:.2f}% Val Acc: {val_acc:.2f}%')\n\n\nclass EarlyStopping(object):\n '''\n Stops the training progress if the performance has not improved for\n a number of epochs to avoid overfitting\n '''\n def __init__(self, patience):\n super().__init__()\n self.best_loss = 1e5\n self.patience = patience\n self.nr_no_improved = 0\n\n def update(self, curr_loss):\n if curr_loss < self.best_loss:\n self.best_loss = curr_loss\n self.nr_no_improved = 0\n return False\n else:\n self.nr_no_improved+=1\n if self.nr_no_improved >= self.patience:\n print(f'Early stopping! Model did not improve for last {self.nr_no_improved} epochs')\n return True\n else:\n return False\n\n\nclass rnn_params:\n '''\n Configuration to store and tune RNN specific hyperparameters\n '''\n rnn_type = 'lstm'\n emb_dim = 64\n rnn_size = 64\n nr_layers = 1\n dropout = 0.5\n lr = 1e-3\n batch_size = 64\n n_epochs = 30\n decay = 1e-5\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n patience = 5\n\ndef train_rnn(save_path = None, collect=True):\n '''\n Training function for the rnn model that trains and validates the models performance\n\n Input: save_path - path and file name to where to save the trained weights (type: string)\n collect - specify if to collect data or not (type: boolean)\n\n Output: history - history of the models training progression (type: defaultdict of lists)\n early_stop_check - if early stopping has been executed or not (type: boolean)\n '''\n dataloaders, vocab_size, n_classes = preprocessing.preprocess(rnn_params.batch_size, collect=collect)\n train_loader, val_loader = dataloaders\n model = models.RNNModel(rnn_type=rnn_params.rnn_type, nr_layers=rnn_params.nr_layers,\n voc_size=vocab_size, emb_dim=rnn_params.emb_dim, rnn_size=rnn_params.rnn_size,\n dropout=rnn_params.dropout, n_classes=n_classes)\n\n loss_fn = nn.BCELoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=rnn_params.lr, weight_decay=rnn_params.decay)\n model.to(rnn_params.device)\n\n history = defaultdict(list)\n init_training_time = time.time()\n early_stopping = EarlyStopping(patience=rnn_params.patience)\n\n for epoch in range(1, rnn_params.n_epochs):\n model.train()\n h = model.init_hidden(rnn_params.batch_size, device=rnn_params.device)\n n_correct, n_instances, total_loss = 0,0,0\n for inputs, labels in train_loader:\n model.zero_grad()\n inputs = inputs.to(rnn_params.device)\n labels = labels.to(rnn_params.device)\n h = tuple([each.data for each in h])\n outputs, h = model(inputs, h)\n\n loss = loss_fn(outputs.squeeze(), labels.float())\n\n total_loss+=loss.item()\n n_instances+=labels.shape[0]\n predictions = torch.round(outputs.squeeze())\n n_correct += (torch.sum(predictions == labels.float())).item()\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n epoch_loss = total_loss / (len(train_loader))\n epoch_acc = n_correct / n_instances\n\n n_correct_val, n_instances_val, total_loss_val = 0, 0, 0\n model.eval()\n val_h = model.init_hidden(rnn_params.batch_size, device=rnn_params.device)\n for val_inp, val_lab in val_loader:\n val_inp = val_inp.to(rnn_params.device)\n val_lab = val_lab.to(rnn_params.device)\n\n val_h = tuple([each.data for each in val_h])\n\n val_out, val_h = model(val_inp, val_h)\n val_loss = loss_fn(val_out.squeeze(), val_lab.float())\n\n total_loss_val += val_loss.item()\n n_instances_val += val_lab.shape[0]\n val_preds = torch.round(val_out.squeeze())\n n_correct_val += (torch.sum(val_preds == val_lab.float())).item()\n\n epoch_val_loss = total_loss_val / len(val_loader)\n epoch_val_acc = n_correct_val / n_instances_val\n\n curr_time = time.time()\n Logger(curr_time-init_training_time, epoch, rnn_params.n_epochs, epoch_loss,\n epoch_acc, epoch_val_loss, epoch_val_acc)\n\n history['training loss'].append(epoch_loss)\n history['training acc'].append(epoch_acc)\n history['validation loss'].append(epoch_val_loss)\n history['validation acc'].append(epoch_val_acc)\n\n early_stop_check = early_stopping.update(epoch_val_loss)\n if early_stop_check:\n models.ModelUtils.save_model(save_path=save_path, model=model)\n return history, early_stop_check\n\n if save_path:\n root, ext = os.path.splitext(save_path)\n save_path = root + '.pth'\n models.ModelUtils.save_model(save_path=save_path, model=model)\n\n\n return history, early_stop_check\n\n\n\ndef show_progress(history, save_name = None):\n fig, axes = plt.subplots(1, 2, figsize=(21, 7))\n fig.suptitle('Training progression', fontsize=18)\n axes[0].plot(history['training loss'], linewidth=2, color='#99ccff', alpha=0.9, label='Training')\n axes[0].plot(history['validation loss'], linewidth=2, color='#cc99ff', alpha=0.9, label='Validation')\n axes[0].set_xlabel(xlabel='Epochs', fontsize=12)\n axes[0].set_ylabel(ylabel=r'$\\mathcal{L}(\\hat{y}, y)$', fontsize=12)\n axes[0].set_title(label='Losses', fontsize=14)\n\n axes[1].plot(history['training acc'], linewidth=2, color='#99ccff', alpha=0.9, label='Training')\n axes[1].plot(history['validation acc'], linewidth=2, color='#cc99ff', alpha=0.9, label='Validation')\n axes[1].set_xlabel(xlabel='Epochs', fontsize=12)\n axes[1].set_ylabel(ylabel=r'%', fontsize=12)\n axes[1].set_title(label='Accuracies', fontsize=14)\n\n axes[0].legend()\n axes[1].legend()\n if save_name:\n plt.savefig(save_name, bbox_inches='tight')\n plt.show()\n\ndef animate_progress(history, save_path, early_stop_check):\n root, ext = os.path.splitext(save_path)\n save_path = root + '.gif'\n\n fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n camera = Camera(fig)\n fig.suptitle('Training progression', fontsize=18)\n axes[0].set_xlabel(xlabel='Epochs', fontsize=12)\n axes[0].set_ylabel(ylabel=r'$\\mathcal{L}(\\hat{y}, y)$', fontsize=12)\n axes[0].set_title(label='Losses', fontsize=14)\n\n axes[1].set_xlabel(xlabel='Epochs', fontsize=12)\n axes[1].set_ylabel(ylabel=r'%', fontsize=12)\n axes[1].set_title(label='Accuracies', fontsize=14)\n\n epochs = np.arange(len(history['training loss']))\n\n for e in epochs:\n axes[0].plot(epochs[:e], history['training loss'][:e], linewidth=2, color='#99ccff')\n axes[0].plot(epochs[:e], history['validation loss'][:e], linewidth=2, color='#cc99ff')\n\n axes[1].plot(epochs[:e], history['training acc'][:e], linewidth=2, color='#99ccff')\n axes[1].plot(epochs[:e], history['validation acc'][:e], linewidth=2, color='#cc99ff')\n axes[0].legend(['Training', 'Validation'])\n axes[1].legend(['Training', 'Validation'])\n camera.snap()\n\n\n for i in range(10):\n axes[0].plot(epochs, history['training loss'], linewidth=2, color='#99ccff')\n axes[0].plot(epochs, history['validation loss'], linewidth=2, color='#cc99ff')\n\n axes[1].plot(epochs, history['training acc'], linewidth=2, color='#99ccff')\n axes[1].plot(epochs, history['validation acc'], linewidth=2, color='#cc99ff')\n\n axes[0].legend(['Training', 'Validation'])\n axes[1].legend(['Training', 'Validation'])\n\n camera.snap()\n\n animation = camera.animate()\n animation.save(save_path, writer='imagemagick')\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.632612943649292, "alphanum_fraction": 0.6447282433509827, "avg_line_length": 31.838708877563477, "blob_id": "093e0f6243a04d8c52b368426b53ec019b34b73b", "content_id": "68b4f291ae416b05cd74a6addd413f9dfec64f82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3054, "license_type": "no_license", "max_line_length": 109, "num_lines": 93, "path": "/twint_scraping.py", "repo_name": "olof98johansson/SentimentAnalysisNLP", "src_encoding": "UTF-8", "text": "# NOTE: TWINT NEEDS TO BE INSTALLEED BY THE FOLLOWING COMMAND:\n# pip install --user --upgrade git+https://github.com/twintproject/twint.git@origin/master#egg=twint\n# OTHERWISE IT WON'T WORK\n\n\nimport twint\nimport nest_asyncio\nnest_asyncio.apply()\nfrom dateutil import rrule\nfrom datetime import datetime, timedelta\n\ndef get_weeks(start_date, end_date):\n '''\n Finds collection of weeks chronologically from a starting date to a final date\n\n Input: start_date - date of which to start collecting with format [year, month, day] (type: list of ints)\n end_date - date of which to stop collecting with format [year, month, day] (type: list of ints)\n\n Output: weeks - list containing the lists of starting and ending date for each week with format\n \"%Y-%m-%d %h-%m-%s\" (type: list of lists of strings)\n '''\n start_year, start_month, start_day = start_date\n final_year, final_month, final_day = end_date\n start = datetime(start_year, start_month, start_day)\n end = datetime(final_year, final_month, final_day)\n dates = rrule.rrule(rrule.WEEKLY, dtstart=start, until=end)\n nr_weeks = 0\n for _ in dates:\n nr_weeks+=1\n weeks = []\n for idx, dt in enumerate(dates):\n if idx < nr_weeks-1:\n week = [dates[idx].date().strftime('%Y-%m-%d %H:%M:%S'),\n dates[idx+1].date().strftime('%Y-%m-%d %H:%M:%S')]\n weeks.append(week)\n\n return weeks\n\n\n\ndef collect_tweets(keywords = None, nr_tweets = None,\n output_file=None, coord=None, timespan=[None, None]):\n '''\n Collectiing tweets using twint based on different attributes and save to json file\n\n Input: keywords - keywords that the tweet should contain (type: string)\n nr_tweets - number of tweets to collect (type: int)\n output_file - path and name to where the file should be saved (type: string, extension: .json)\n near - location or city of which the tweets were tweeted (type: string)\n timespan - timespan of when the tweet was tweeted in format \"%Y-%m-%d %h-%m-%s\" (type: string)\n\n Output: Returns twint object\n '''\n # configuration\n config = twint.Config()\n # Search keyword\n config.Search = keywords\n # Language\n config.Lang = \"en\"\n # Number of tweets\n config.Limit = nr_tweets\n #Dates\n config.Since = timespan[0]\n config.Until = timespan[1]\n # Output file format (alternatives: json, csv, SQLite)\n config.Store_json = True\n # Name of output file with format extension (i.e NAME.json, NAME.csv etc)\n config.Output = output_file\n\n config.Geo = coord\n\n # running search\n twint.run.Search(config)\n return twint\n\n\n# EXAMPLE\ndef test():\n config = twint.Config()\n config.Search = None\n config.Near = \"london\"\n config.Lang = \"en\"\n config.Limit = 10\n config.Since = \"2016-10-29 00:00:00\"\n config.Until = \"2016-11-29 12:15:19\"\n config.Store_json = True\n config.Output = \"test2.json\"\n\n #running search\n twint.run.Search(config)\n\n\n#test()\n" }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 12.833333015441895, "blob_id": "dd46b156186a56d8330a24242e42405e6285e95a", "content_id": "702d14fe595fb1383b7244f044dc25cea64a18df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 168, "license_type": "no_license", "max_line_length": 69, "num_lines": 12, "path": "/requirements.txt", "repo_name": "olof98johansson/SentimentAnalysisNLP", "src_encoding": "UTF-8", "text": "re \ntorch\nnumpy\nmatplotlib\ncollections\nseaborn\nsklearn\ngit+https://github.com/twintproject/twint.git@origin/master#egg=twint\nnest_asyncio\ndateutil\ndatetime\ncelluloid\n\n\n" }, { "alpha_fraction": 0.5783964395523071, "alphanum_fraction": 0.5819599032402039, "avg_line_length": 36.70588302612305, "blob_id": "6f169c09871fdaaacfed06a13db39b28a14a8bf0", "content_id": "cd1a23aa6571c5e3e9e1670d729c0903ddbbf389", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4490, "license_type": "no_license", "max_line_length": 113, "num_lines": 119, "path": "/models.py", "repo_name": "olof98johansson/SentimentAnalysisNLP", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport preprocessing\nimport os\nimport numpy as np\n\n\nclass ModelUtils:\n '''\n A utility class to save and load model weights\n '''\n def save_model(save_path, model):\n root, ext = os.path.splitext(save_path)\n if not ext:\n save_path = root + '.pth'\n try:\n torch.save(model.state_dict(), save_path)\n print(f'Successfully saved to model to \"{save_path}\"!')\n except Exception as e:\n print(f'Unable to save model, check save path!')\n print(f'Exception:\\n{e}')\n return None\n\n def load_model(load_path, model):\n try:\n model.load_state_dict(torch.load(load_path))\n print(f'Successfully loaded the model from path \"{load_path}\"')\n\n except Exception as e:\n print(f'Unable to load the weights, check if different model or incorrect path!')\n print(f'Exception:\\n{e}')\n return None\n\nclass RNNModel(nn.Module):\n '''\n RNN classifier with different available RNN types (basic RNN, LSTM, GRU)\n '''\n\n def __init__(self, rnn_type, nr_layers, voc_size, emb_dim, rnn_size, dropout, n_classes):\n '''\n Initiates the RNN model\n\n Input: rnn_type - specifies the rnn model type between \"rnn\", \"lstm\" or \"gru\" (type: string)\n nr_layers - number of rnn layers (type: int)\n voc_size - size of vocabulary of the encoded input data (type: int)\n emb_dim - size of embedding layer (type: int)\n rnn_size - number of hidden layers in RNN model (type: int)\n dropout - probability of dropout layers (type: float in between [0, 1])\n n_classes - number of different classes/labels (type: int)\n '''\n super().__init__()\n self.rnn_size = rnn_size\n self.rnn_type = rnn_type\n self.nr_layers = nr_layers\n self.embedding = nn.Embedding(voc_size, emb_dim)\n\n if self.rnn_type == 'rnn':\n self.rnn = nn.RNN(input_size=emb_dim, hidden_size=rnn_size, dropout=dropout if nr_layers > 1 else 0,\n bidirectional=False, num_layers=nr_layers, batch_first=True)\n\n elif self.rnn_type == 'lstm':\n self.rnn = nn.LSTM(input_size=emb_dim, hidden_size=rnn_size, dropout=dropout if nr_layers > 1 else 0,\n bidirectional=False, num_layers=nr_layers, batch_first=True)\n\n elif self.rnn_type == 'gru':\n self.rnn = nn.GRU(input_size=emb_dim, hidden_size=rnn_size, dropout=dropout if nr_layers > 1 else 0,\n bidirectional=False, num_layers=nr_layers, batch_first=True)\n\n else:\n print('Invalid or no choice for RNN type, please choose one of \"rnn\", \"lstm\" or \"gru\"')\n\n\n self.dropout = nn.Dropout(dropout)\n self.linear = nn.Linear(in_features=rnn_size, out_features=n_classes)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, X, hidden):\n '''\n Forward propagation of the RNN model\n\n Input: X - batch of input data (type: torch tensor)\n hidden - batch of input to the hidden cells (type: torch tensor)\n\n Output: out - model prediction (type: torch tensor)\n hidden - output of the hidden cells (torch.tensor)\n '''\n self.batch_size = X.size(0)\n embedded = self.embedding(X)\n\n\n if self.rnn_type == 'rnn' or self.rnn_type == 'gru':\n rnn_out, hidden = self.rnn(embedded, hidden)\n\n elif self.rnn_type == 'lstm':\n rnn_out, hidden = self.rnn(embedded, hidden)\n\n else:\n print(f'Invalid rnn type! Rebuild the model with a correct rnn type!')\n return None\n\n rnn_out = rnn_out.contiguous().view(-1, self.rnn_size)\n drop = self.dropout(rnn_out)\n out = self.linear(drop)\n out = self.sigmoid(out)\n # reshape such that batch size is first and get labels of last batch\n out = out.view(self.batch_size, -1)\n out = out[:, -1]\n\n return out, hidden\n\n def init_hidden(self, batch_size, device):\n '''\n Initializes hidden state\n '''\n # initialized to zero, for hidden state and cell state of LSTM\n h0 = torch.zeros((self.nr_layers, batch_size, self.rnn_size)).to(device)\n c0 = torch.zeros((self.nr_layers, batch_size, self.rnn_size)).to(device)\n hidden = (h0, c0)\n return hidden\n\n\n\n" }, { "alpha_fraction": 0.6060692667961121, "alphanum_fraction": 0.6156598925590515, "avg_line_length": 34.41116714477539, "blob_id": "c520dc90be7facce58f34ad9343196b3f1683377", "content_id": "70399b7d9b8b0fa1468879637dc873f8ec3d88d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6986, "license_type": "no_license", "max_line_length": 125, "num_lines": 197, "path": "/preprocessing.py", "repo_name": "olof98johansson/SentimentAnalysisNLP", "src_encoding": "UTF-8", "text": "import data_cleaning\nimport twint_scraping\nimport os\nfrom collections import Counter\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom torch.utils.data import Dataset, DataLoader\nimport torch\n\n\n\n\nclass config:\n '''\n Configuration class to store and tune global variables\n '''\n\n PAD = '___PAD___'\n UNKNOWN = '___UNKNOWN___'\n\n paths = ['./training_data/depressive1.json',\n './training_data/depressive2.json',\n './training_data/depressive3.json',\n './training_data/depressive4.json',\n './training_data/depressive5.json',\n './training_data/depressive6.json',\n './training_data/non-depressive1.json',\n './training_data/non-depressive2.json',\n './training_data/non-depressive3.json',\n './training_data/non-depressive4.json',\n './training_data/non-depressive5.json',\n './training_data/non-depressive6.json']\n\n labels = ['depressive', 'depressive', 'depressive', 'depressive', 'depressive', 'depressive',\n 'not-depressive', 'not-depressive', 'not-depressive', 'not-depressive',\n 'not-depressive', 'not-depressive']\n\n save_path = './training_data/all_training_data.csv'\n keywords = ['depressed', 'lonely', 'sad', 'depression', 'tired', 'anxious',\n 'happy', 'joy', 'thankful', 'hope', 'hopeful', 'glad']\n nr_of_tweets = [5000, 5000, 5000, 5000, 5000, 5000,\n 5000, 5000, 5000, 5000, 5000, 5000]\n hashtags_to_remove = []\n encoder = None\n vocab = None\n vocab_size = 0\n n_classes = 0\n\n\n\n\ndef collect_dataset(paths, keywords, nr_of_tweets, hashtags_to_remove, collect=True):\n '''\n Collecting the dataset and cleans the data\n\n Input: paths - path to where to save the collected tweets (type: list of strings)\n keywords - keywords to be used for collecting tweets (type: list of strings)\n nr_of_tweets - number of tweets to be collected for each collecting process (type: list of ints)\n collect - specifying if to collect tweets or not (type: boolean)\n\n Output: dataset - cleaned dataset of the tweet texts and their labels (type: list if lists)\n '''\n roots, exts = [], []\n for path in paths:\n root, ext = os.path.splitext(path)\n roots.append(root)\n exts.append(ext)\n #roots, exts = [os.path.splitext(path) for path in paths]\n save_root, save_exts = os.path.splitext(config.save_path)\n json_paths = [root+'.json' for root in roots]\n csv_path = save_root+'.csv'\n if collect:\n for idx, json_path in enumerate(json_paths):\n twint_scraping.collect_tweets(keywords=keywords[idx], nr_tweets=nr_of_tweets[idx], output_file=json_path)\n\n dataset, keys = data_cleaning.datacleaning(paths=json_paths, labels=config.labels, hashtags_to_remove=hashtags_to_remove,\n save_path=csv_path)\n\n return dataset, keys\n\n\nclass DocumentDataset(Dataset):\n '''\n Basic class for creating dataset from the input and label data\n '''\n def __init__(self, X, Y):\n self.X = X\n self.Y = Y\n\n def __getitem__(self, idx):\n return self.X[idx], self.Y[idx]\n\n def __len__(self):\n return len(self.X)\n\n\nclass DocumentBatcher:\n '''\n Process the batches to desired output by transform into torch tensors and pads uneven input text data\n to the same length\n '''\n def __init__(self, voc):\n self.pad = voc.get_pad_idx()\n\n def __call__(self, XY):\n max_len = max(len(x) for x, _ in XY)\n Xpadded = torch.as_tensor([x + [self.pad] * (max_len - len(x)) for x, _ in XY])\n Y = torch.as_tensor([y for _, y in XY])\n\n return Xpadded, Y\n\nclass Vocab:\n '''\n Encoding the documents\n '''\n\n def __init__(self):\n # Splitting the tweets into words as tokenizer\n self.tokenizer = lambda s: s.split()\n\n def build_vocab(self, docs):\n '''\n Building the vocabulary from the documents, i.e creating the\n word-to-encoding and encoding-to-word dicts\n\n Input: docs - list of all the lines in the corpus\n '''\n\n freqs = Counter(w for doc in docs for w in self.tokenizer(doc))\n freqs = sorted(((f, w) for w, f in freqs.items()), reverse=True)\n\n\n self.enc_to_word = [config.PAD, config.UNKNOWN] + [w for _, w in freqs]\n\n self.word_to_enc = {w: i for i, w in enumerate(self.enc_to_word)}\n\n def encode(self, docs):\n '''\n Encoding the documents\n Input: docs - list of all the lines in the corpus\n '''\n unkn_index = self.word_to_enc[config.UNKNOWN]\n return [[self.word_to_enc.get(w, unkn_index) for w in self.tokenizer(doc)] for doc in docs]\n\n def get_unknown_idx(self):\n return self.word_to_enc[config.UNKNOWN]\n\n def get_pad_idx(self):\n return self.word_to_enc[config.PAD]\n\n def __len__(self):\n return len(self.enc_to_word)\n\n\ndef preprocess(batch_size=64, collect=True):\n '''\n Function for preprocessing the data which splits the data into train/val, builds the vocabulary, fits\n the label encoder and creates the dataloaders for the train and validation set\n\n Input: batch_size - batch size to be used in the data loaders (type: int)\n collect - specifying if to collect data or not (type: boolean)\n\n Output: dataloaders - the created data loaders for training and validation set (type: list of data loaders)\n vocab_size - size of the built vocabulary (type: int)\n n_classes - number of classes/ladels in the dataset\n '''\n data, keys = collect_dataset(paths=config.paths, keywords=config.keywords,\n nr_of_tweets=config.nr_of_tweets,\n hashtags_to_remove=config.hashtags_to_remove,\n collect=collect)\n X, Y = data\n x_train, x_val, y_train, y_val = train_test_split(X, Y, test_size=0.2, shuffle=True, random_state=1)\n\n vocab = Vocab()\n vocab.build_vocab(x_train)\n config.vocab = vocab\n\n encoder = LabelEncoder()\n encoder.fit(y_train)\n config.encoder = encoder\n\n vocab_size = len(vocab)\n n_classes = len(encoder.classes_)\n config.vocab_size = vocab_size\n config.n_classes = n_classes\n\n batcher = DocumentBatcher(vocab)\n train_dataset = DocumentDataset(vocab.encode(x_train),\n encoder.transform(y_train))\n train_loader = DataLoader(train_dataset, batch_size,\n shuffle=True, collate_fn=batcher, drop_last=True)\n val_dataset = DocumentDataset(vocab.encode(x_val), encoder.transform(y_val))\n val_loader = DataLoader(val_dataset, batch_size,\n shuffle=True, collate_fn=batcher, drop_last=True)\n dataloaders = [train_loader, val_loader]\n\n return dataloaders, vocab_size, n_classes\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6118034720420837, "alphanum_fraction": 0.6298794746398926, "avg_line_length": 46.35853576660156, "blob_id": "fba3908a505fba94f87f9feb52725b0bd494bb8b", "content_id": "b829e5d98dbb86f399ab72c6ab96fe216127210f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19418, "license_type": "no_license", "max_line_length": 170, "num_lines": 410, "path": "/predict.py", "repo_name": "olof98johansson/SentimentAnalysisNLP", "src_encoding": "UTF-8", "text": "import models\nimport train\nimport preprocessing\nimport data_cleaning\nimport os\nimport torch\nimport twint_scraping\nimport numpy as np\nfrom torch.utils.data import Dataset, DataLoader\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nsns.set_style('darkgrid')\nimport pandas_alive\n\n\n\nclass Config:\n '''\n Configuration class to store and tune global variables\n '''\n test_set_keywords = []\n test_set_nr_of_tweets = [5000]\n\n # Coordinates spread out in UK to cover as wide geographical range as possible\n test_set_locations = [\"54.251186,-4.463196,550km\"]\n\n len_locations = len(test_set_locations)\n time_to = twint_scraping.get_weeks([2019, 12, 24], [2020, 3, 17]) # UK lockdown and 3 months back\n time_from = twint_scraping.get_weeks([2020, 3, 24], [2020, 6, 24]) # UK lockdown and 3 months forward\n test_set_time_spans = []\n for tt in time_to:\n test_set_time_spans.append(tt)\n for tf in time_from:\n test_set_time_spans.append(tf)\n len_timespan = len(test_set_time_spans)\n\n test_set_json_paths = []\n for t_idx in range(len_timespan):\n time_spec_path = []\n for l_idx in range(len_locations):\n time_spec_path.append(f'./forecast_data/testdata_{l_idx}_{t_idx}.json')\n\n test_set_json_paths.append(time_spec_path)\n\n test_set_csv_paths = [f'./forecast_data/all_loc_{t_idx}.csv' for t_idx in range(len_timespan)]\n\n path_to_weights = './weights/lstm_model_2.pth'\n\n\nclass TestDataset(Dataset):\n '''\n Basic class for creating dataset from the test input data\n '''\n def __init__(self, X):\n self.X = X\n\n def __getitem__(self, idx):\n return self.X[idx]\n\n def __len__(self):\n return len(self.X)\n\n\n\ndef get_testdata(paths, save_path, timespans, collect_test_data = False):\n '''\n Builds vocabulary and encoder based on the training data and collects, clean and builds data loaders\n for the test data\n\n Input: paths - path to store the collected test data with json extension (type: list of strings)\n save_path - path to where to save the cleaned and final test dataset with csv\n extension (type: list of strings)\n timespans - timespans of when the collected test tweets where tweeted (type: list of lists of strings)\n collect_test_data - specifying if to collect test data or not (type: boolean)\n\n Output: test_loader - data loader for the collected test data (type: DataLoader)\n encoder - encoder trained on the training labels (type: LabelEncoder)\n vocab_size - size of the vocabulary built from the training data (type: int)\n n_classes: number of classes/labels from the training data (type: int)\n '''\n roots, exts = [], []\n for path in paths:\n root, ext = os.path.splitext(path)\n roots.append(root)\n exts.append(ext)\n save_root, save_exts = os.path.splitext(save_path)\n json_paths = [root + '.json' for root in roots]\n csv_path = save_root + '.csv'\n\n rnn_params = train.rnn_params()\n _, vocab_size, n_classes = preprocessing.preprocess(rnn_params.batch_size, collect=False)\n encoder = preprocessing.config.encoder\n vocab = preprocessing.config.vocab\n if collect_test_data:\n for idx, json_path in enumerate(json_paths):\n twint_scraping.collect_tweets(nr_tweets=Config.test_set_nr_of_tweets[idx],\n output_file=json_path,\n coord=Config.test_set_locations[idx],\n timespan=timespans)\n testdata, keys = data_cleaning.datacleaning(paths=json_paths, labels=[],\n hashtags_to_remove=[],\n save_path=csv_path, train=False)\n\n cleaned_csv_path = save_root + '_cleaned.csv'\n df = pd.DataFrame(data={\"test docs\": testdata})\n df.to_csv(cleaned_csv_path, sep=',', index=False)\n\n pad = vocab.get_pad_idx()\n max_len = max(len(x) for x in testdata)\n testdata = vocab.encode(testdata)\n testdata_padded = torch.as_tensor([x + [pad] * (max_len - len(x)) for x in testdata])\n test_dataset = TestDataset(testdata_padded)\n test_loader = DataLoader(test_dataset, batch_size=1)\n\n return test_loader, encoder, vocab_size, n_classes\n\n\ndef predict(testdata, path_to_weights, vocab_size, n_classes):\n '''\n Creates, loads and initiates the model and making predictions on the test data\n\n Input: testdata - data loader of the test data (type: DataLoader)\n path_to_weights - relative path and file name of the saved model weights with .pth extension (type:string)\n vocab_size - size of the vocabulary (type: int)\n n_classes - number of labels/classes that can be predicted (type: int)\n\n Output: preds_prob_list - list of all the probabilities of which the model predicted\n the corresponding label (type: list of floats)\n preds_status_list - list of all the reencoded labels that were predicted (type: list of strings)\n '''\n rnn_params = train.rnn_params\n model = models.RNNModel(rnn_type=rnn_params.rnn_type, nr_layers=rnn_params.nr_layers,\n voc_size=vocab_size, emb_dim=rnn_params.emb_dim, rnn_size=rnn_params.rnn_size,\n dropout=rnn_params.dropout, n_classes=n_classes)\n models.ModelUtils.load_model(path_to_weights, model)\n model.to(rnn_params.device)\n batch_size = 1\n h = model.init_hidden(batch_size, device=rnn_params.device)\n model.zero_grad()\n\n preds_prob_list, preds_status_list = [], []\n for x_test in testdata:\n x_test = x_test.to(train.rnn_params.device)\n h = tuple([each.data for each in h])\n out, h = model(x_test, h)\n pred = torch.round(out.squeeze()).item()\n pred_status = \"depressive\" if pred < 0.5 else \"non-depressive\"\n prob = (1-pred) if pred_status == \"depressive\" else pred\n preds_status_list.append(pred_status)\n preds_prob_list.append(prob)\n\n return preds_prob_list, preds_status_list\n\n\ndef run_predictions(collect_test_data=False):\n '''\n Collect, preprocess and predicts the test data\n\n Input: collect_test_data - weither or not to collect test data (type: boolean)\n\n Output: status_results - all the predicted labels (type: dictionary of lists of strings)\n preds_results - all the predicted values, i.e the certainties of\n the predictions (type: dictionary of lists of strings)\n '''\n status_results = {}\n preds_results = {}\n\n for idx, ind_paths in enumerate(Config.test_set_json_paths):\n try:\n testdata, encoder, vocab_size, n_classes = get_testdata(ind_paths,\n Config.test_set_csv_paths[idx],\n timespans=Config.test_set_time_spans[idx],\n collect_test_data=collect_test_data)\n preds_list, preds_status_list = predict(testdata, Config.path_to_weights,\n vocab_size, n_classes)\n status_results[f'timespan_{idx}'] = preds_status_list\n preds_results[f'timespan_{idx}'] = preds_list\n\n except Exception as e:\n print(f'Unable to get test data!')\n print(f'Exception:\\n{e}')\n return None\n\n return status_results, preds_results\n\n\n\ndef plot_predictions(status_results, preds_results, save_name='./predictions_forecast.png', color=None):\n '''\n Plot the predictions in time order, i.e a time-based forecast of the predictions\n\n Input: status_results - all the predicted labels (type: dictionary of lists of strings)\n preds_results - all the predicted values, i.e the certainties of\n the predictions (type: dictionary of lists of strings)\n save_name - path and filename to where to save the forecasting plot\n '''\n timespans = list(status_results.keys())\n nr_depressive = [(np.array(status_results[timespans[t_idx]]) == 'depressive').sum() for t_idx in range(len(timespans))]\n percentage_dep = [((np.array(status_results[timespans[t_idx]]) == 'depressive').sum())/len(status_results[timespans[t_idx]]) for t_idx in range(len(timespans))]\n text_perc_dep = [format(percentage_dep[i]*100, '.2f') for i in range(len(percentage_dep))]\n ave_probs = [np.mean(np.array(preds_results[timespans[t_idx]])) for t_idx in range(len(timespans))]\n text_ave_probs = [format(ave_probs[i]*100, '.2f') for i in range(len(ave_probs))]\n weeks = Config.test_set_time_spans\n indexes = [f'{w[0].split()[0]}\\n{w[1].split()[0]}' for w in weeks]\n if color:\n color_bar = color\n else:\n color_bar = \"#ff3399\"\n if not len(indexes) == len(percentage_dep):\n print('Time indexes does not equal number of values')\n indexes = timespans\n fig = plt.figure(figsize=(28, 12))\n plt.bar(indexes, percentage_dep, color=color_bar, width=0.55, alpha=0.35)\n plt.plot(indexes, percentage_dep, color=\"#cc99ff\", alpha=0.5)\n for i, p in enumerate(percentage_dep):\n plt.text(indexes[i], p + 0.02, f'{text_perc_dep[i]}%', verticalalignment='center', color='black',\n horizontalalignment='center', fontweight='bold', fontsize=8)\n # plt.text(timespans[i], p+0.005, f'Average target prob: {text_ave_probs[i]}%', verticalalignment='center',\n # horizontalalignment='center', color='black', fontweight='bold', fontsize=8)\n plt.xlabel('Time period', fontsize=16)\n plt.ylabel('Percentage %', fontsize=16)\n plt.ylim(-0.05, 0.5)\n plt.xticks(fontsize=7.4)\n plt.yticks(fontsize=11)\n plt.title(f'Percentage of depressive tweets weekly from {indexes[0].split()[0]} to {indexes[len(indexes)-1].split()[1]}', fontsize=20)\n\n if save_name:\n root, ext = os.path.splitext(save_name)\n save_name = root + '.png'\n plt.savefig(save_name, bbox_inches='tight')\n plt.show()\n\n\n\n\ndef plot_all_predictions(status_results1, status_results2, status_results3, weeks, save_name='./predictions_forecast.png', colors=None):\n\n timespans1 = list(status_results1.keys())\n timespans2 = list(status_results2.keys())\n timespans3 = list(status_results3.keys())\n percentage_dep1 = [((np.array(status_results1[timespans1[t_idx]]) == 'depressive').sum())/len(status_results1[timespans1[t_idx]]) for t_idx in range(len(timespans1))]\n percentage_dep2 = [((np.array(status_results2[timespans2[t_idx]]) == 'depressive').sum())/len(status_results2[timespans2[t_idx]]) for t_idx in range(len(timespans2))]\n percentage_dep3 = [((np.array(status_results3[timespans3[t_idx]]) == 'depressive').sum())/len(status_results3[timespans3[t_idx]]) for t_idx in range(len(timespans3))]\n\n weeks1, weeks2, weeks3 = weeks\n indexes1 = [f'{w[0].split()[0]}\\n{w[1].split()[0]}' for w in weeks1]\n indexes2 = [f'{w[0].split()[0]}\\n{w[1].split()[0]}' for w in weeks2]\n indexes3 = [f'{w[0].split()[0]}\\n{w[1].split()[0]}' for w in weeks3]\n\n x = np.arange(len(indexes1))\n lengths = [len(indexes1), len(indexes2), len(indexes3)]\n if not all(l == lengths[0] for l in lengths):\n shortest = np.min(lengths)\n percentage_dep1 = percentage_dep1[:shortest]\n percentage_dep2 = percentage_dep2[:shortest]\n percentage_dep3 = percentage_dep3[:shortest]\n x = np.arange(shortest)\n\n\n fig = plt.figure(figsize=(28, 12))\n plt.bar(x-0.2, percentage_dep1, color=colors[0], width=0.2, alpha=0.4,\n label=f'{indexes1[0].split()[0]} to {indexes1[len(indexes1)-1].split()[1]}')\n plt.bar(x, percentage_dep2, color=colors[1], width=0.2, alpha=0.4,\n label=f'{indexes2[0].split()[0]} to {indexes2[len(indexes2) - 1].split()[1]}')\n plt.bar(x+0.2, percentage_dep3, color=colors[2], width=0.2, alpha=0.4,\n label=f'{indexes3[0].split()[0]} to {indexes3[len(indexes3) - 1].split()[1]}')\n\n plt.xlabel('Time periods', fontsize=16)\n plt.ylabel('Percentage %', fontsize=16)\n plt.ylim(-0.05, 0.5)\n plt.yticks(fontsize=12)\n plt.tick_params(\n axis='x', # changes apply to the x-axis\n which='both', # both major and minor ticks are affected\n bottom=False, # ticks along the bottom edge are off\n top=False, # ticks along the top edge are off\n labelbottom=False)\n plt.legend(fontsize=21)\n plt.title(f'Comparison of the percentage of depressive tweets weekly from for different time periods', fontsize=20)\n\n if save_name:\n root, ext = os.path.splitext(save_name)\n save_name = root + '.png'\n plt.savefig(save_name, bbox_inches='tight')\n plt.show()\n\n\n\ndef forecast_bar_race(status_results, preds_results, save_name='./plots/forecast_bar_race.mp4'):\n\n timespans = list(status_results.keys())\n nr_depressive = [(np.array(status_results[timespans[t_idx]]) == 'depressive').sum() for t_idx in\n range(len(timespans))]\n nr_nondepressive = [(np.array(status_results[timespans[t_idx]]) == 'non-depressive').sum() for t_idx in\n range(len(timespans))]\n percentage_dep = [\n ((np.array(status_results[timespans[t_idx]]) == 'depressive').sum()) / len(status_results[timespans[t_idx]]) for\n t_idx in range(len(timespans))]\n text_perc_dep = [format(percentage_dep[i] * 100, '.2f') for i in range(len(percentage_dep))]\n ave_probs = [np.mean(np.array(preds_results[timespans[t_idx]])) for t_idx in range(len(timespans))]\n text_ave_probs = [format(ave_probs[i] * 100, '.2f') for i in range(len(ave_probs))]\n percentage_antidep = [1 - percentage_dep[i] for i in range(len(percentage_dep))]\n\n df_dict = {'depressive': percentage_dep,\n 'non-depressive': percentage_antidep}\n weeks = Config.test_set_time_spans\n indexes = [f'{w[0].split()[0]}' for w in weeks]\n predictions_df = pd.DataFrame(df_dict, index=pd.DatetimeIndex(indexes))\n predictions_df.index.rename('date', inplace=True)\n\n root, ext = os.path.splitext(save_name)\n save_name = root + '.gif'\n save_name_pie = root + '.gif'\n\n #predictions_df.plot_animated(filename=save_name, period_fmt=\"%Y-%m-%d\")\n predictions_df.plot_animated(filename=save_name_pie, period_fmt=\"%Y-%m-%d\", period_label={'x': 0, 'y': 0.05},\n title= f'Weekly ratio between non-depressive and depressive tweets in the UK',\n kind=\"pie\", rotatelabels=True)\n\n\n\ndef run():\n '''\n Predict function to run the prediction process after specifying parameters for all three time periods\n '''\n preprocessing.config.paths = ['./training_data/depressive1.json',\n './training_data/depressive2.json',\n './training_data/depressive3.json',\n './training_data/depressive4.json',\n './training_data/depressive5.json',\n './training_data/depressive6.json',\n './training_data/non-depressive1.json',\n './training_data/non-depressive2.json',\n './training_data/non-depressive3.json',\n './training_data/non-depressive4.json',\n './training_data/non-depressive5.json',\n './training_data/non-depressive6.json']\n\n preprocessing.config.labels = ['depressive', 'depressive', 'depressive', 'depressive', 'depressive', 'depressive',\n 'not-depressive', 'not-depressive', 'not-depressive', 'not-depressive',\n 'not-depressive', 'not-depressive']\n\n preprocessing.config.save_path = './training_data/all_training_data.csv'\n\n status_results, preds_results = run_predictions(collect_test_data=True) # collect_test_data=False if already collected\n plot_predictions(status_results, preds_results, save_name='./plots/forecast_orig.png')\n forecast_bar_race(status_results, preds_results, save_name='./plots/forecast_bar_race_orig.gif')\n week1 = Config.test_set_time_spans\n\n\n # comparing to same period year before\n Config.time_to = twint_scraping.get_weeks([2018, 12, 24], [2019, 3, 24])\n Config.time_from = twint_scraping.get_weeks([2019, 3, 24], [2019, 6, 24])\n test_set_time_spans = []\n for tt in Config.time_to:\n test_set_time_spans.append(tt)\n for tf in Config.time_from:\n test_set_time_spans.append(tf)\n len_timespan = len(test_set_time_spans)\n Config.test_set_time_spans = test_set_time_spans\n Config.len_timespan = len_timespan\n test_set_json_paths = []\n for t_idx in range(len_timespan):\n time_spec_path = []\n for l_idx in range(Config.len_locations):\n time_spec_path.append(f'./forecast_data/testdata_yearbefore_{l_idx}_{t_idx}.json')\n\n test_set_json_paths.append(time_spec_path)\n Config.test_set_json_paths = test_set_json_paths\n Config.test_set_csv_paths = [f'./forecast_data/all_loc_year_before_{t_idx}.csv' for t_idx in range(len_timespan)]\n week2 = Config.test_set_time_spans\n status_results_before, preds_results_before = run_predictions(collect_test_data=True) # collect_test_data=False if already collected\n plot_predictions(status_results_before, preds_results_before, save_name='./plots/forecast_year_before.png', color=\"#3366ff\")\n forecast_bar_race(status_results_before, preds_results_before, save_name='./plots/forecast_bar_race_last_year.gif')\n\n # Comparing to from 3 months after lockdown to recent\n Config.time_to = twint_scraping.get_weeks([2020, 6, 24], [2020, 9, 24])\n Config.time_from = twint_scraping.get_weeks([2020, 9, 24], [2020, 12, 17])\n\n test_set_time_spans = []\n for tt in Config.time_to:\n test_set_time_spans.append(tt)\n for tf in Config.time_from:\n test_set_time_spans.append(tf)\n len_timespan = len(test_set_time_spans)\n Config.test_set_time_spans = test_set_time_spans\n Config.len_timespan = len_timespan\n test_set_json_paths = []\n for t_idx in range(len_timespan):\n time_spec_path = []\n for l_idx in range(Config.len_locations):\n time_spec_path.append(f'./forecast_data/testdata_uptorecent_{l_idx}_{t_idx}.json')\n\n test_set_json_paths.append(time_spec_path)\n Config.test_set_json_paths = test_set_json_paths\n Config.test_set_csv_paths = [f'./forecast_data/all_loc_up_to_recent_{t_idx}.csv' for t_idx in range(len_timespan)]\n week3 = Config.test_set_time_spans\n status_results_uptonow, preds_results_uptonow = run_predictions(collect_test_data=True) # collect_test_data=False if already collected\n plot_predictions(status_results_uptonow, preds_results_uptonow, save_name='./plots/forecast_up_to_now.png', color=\"#00cc66\")\n forecast_bar_race(status_results_uptonow, preds_results_uptonow, save_name='./plots/forecast_bar_race_up_to_now.gif')\n\n ##### COMPARISON #####\n weeks = [week1, week2, week3]\n colors = [\"#ff3399\", \"#3366ff\", \"#00cc66\"]\n plot_all_predictions(status_results, status_results_before, status_results_uptonow, weeks,\n save_name='./plots/comparison.png', colors=colors)\n\n\nrun()\n\n" }, { "alpha_fraction": 0.596807062625885, "alphanum_fraction": 0.5986752510070801, "avg_line_length": 35.339508056640625, "blob_id": "fa9d4a45224d57074af776353017095f5c5180e4", "content_id": "37b39087fdbab99b62755cc13a6796576574d0b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5888, "license_type": "no_license", "max_line_length": 122, "num_lines": 162, "path": "/data_cleaning.py", "repo_name": "olof98johansson/SentimentAnalysisNLP", "src_encoding": "UTF-8", "text": "\nimport json\nimport csv\nimport re\n\ndef load_json(path):\n '''\n Loads collected data in json format, checks it and then converts to csv format\n\n Input: path - path and file name to the collected json data (type: string)\n\n Output: keys - list of features/keys of the dataframe (type: list of strings)\n df_list - list containing all the dataframes from the json data (type: list of dataframes)\n '''\n if not path.endswith('.json'):\n print('File path not JSON file...')\n return None\n\n with open(path, 'r', encoding='utf8') as handle:\n df_list = [json.loads(line) for line in handle]\n\n nr_keys = [len(df_list[i].keys()) for i in range(len(df_list))]\n if not all(k == nr_keys[0] for k in nr_keys):\n print('Some features missing, review the data!')\n return None\n\n else:\n keys = df_list[0].keys()\n return keys, df_list\n\n\ndef combine_and_label(paths, labels, train=True):\n '''\n Combining multiple collections of data files and adds corresponding label (i.e depressive or non-depressive).\n List of labels in correct order with respect to the paths order must be specified manually\n\n Input: paths - list containing all the paths to the json files (type: list of strings)\n labels - list containing all the labels to the corresponding json files (type: list of strings)\n\n Output: df_list - list of all the combined dataframes from the json data (type: list of dataframes)\n '''\n\n if not type(paths)==type(list()):\n print('\"paths\" argument is not of type list! Please pass list of the paths to the collected data to be combined!')\n return None\n if train:\n if not len(paths) == len(labels):\n print(f'Number of datafile paths of {len(paths)} is not the same as number of labels of {len(labels)}!')\n return None\n\n df_list = []\n for idx, path in enumerate(paths):\n try:\n curr_keys, curr_df_list = load_json(path)\n except Exception as e:\n print(f'Unable to load data from path \"{path}\", check path name and file!')\n print(f'Exception:\\n{e}')\n return None\n for df in curr_df_list:\n if train:\n df['label'] = labels[idx]\n df_list.append(df)\n\n return df_list\n\n\n\ndef datacleaning(paths, labels, hashtags_to_remove = [], save_path=None, train=True):\n '''\n Cleans the data based on unwanted hashtags, duplication of tweets occured due\n to sharing of keywords, removal of mentions, urls, non-english alphabetic tokens\n and empty tweets obtained after cleaning\n\n Input: paths - list containing all the paths to the json files (type: list of strings)\n labels - list containing all the labels to the corresponding json files (type: list of strings)\n hashtags_to_remove - list containing hashtags wished to be removed (type: list of strings)\n save_path - path and file name to were to save the cleaned dataset (type: string or None)\n train - specify if it is training mode or not, i.e if to use labels or not (type: boolean)\n\n Output: dataset_doc - list of all the text documents and corresponding labels if train (type: list of strings)\n keys - list of features/keys of the dataframe (type: list of strings)\n\n '''\n if len(labels) > 0:\n train = True\n\n df_list = combine_and_label(paths, labels, train=train)\n\n # Remove tweets with specific hashtags\n nr_removed_tweets = 0\n for idx, df in enumerate(df_list):\n hashtags = df.copy()['hashtags']\n if any([h in hashtags_to_remove for h in hashtags]):\n df_list.pop(idx)\n print(f'Tweet nr {idx} removed!')\n nr_removed_tweets += 1\n\n print(f'Removed total of {nr_removed_tweets} tweets')\n\n # Removes duplicate of tweets\n unique_ids = {}\n for idx, df in enumerate(df_list):\n tweet_id = df.copy()['id']\n if not tweet_id in unique_ids:\n unique_ids[str(tweet_id)] = 1\n else:\n print('Found douplicate of tweet id, removing the duplicate!')\n df_list.pop(idx)\n\n\n # Cleaning the tweet texts\n for idx, df in enumerate(df_list):\n tweet = df.copy()['tweet']\n # Removing URLs\n tweet = re.sub(r\"http\\S+\", \" \", tweet)\n tweet = re.sub(r\"\\S+\\.com\\S\", \" \", tweet)\n\n # Remove mentions\n tweet = re.sub(r'\\@\\w+', ' ', tweet)\n\n # Remove non-alphabetic tokens\n tweet = re.sub('[^A-Za-z]', ' ', tweet.lower())\n\n # Remove double spacings\n tweet = re.sub(' +', ' ', tweet)\n\n # Remove from dataset if tweet empty after cleaning\n if tweet == 0:\n df_list.pop(idx)\n else:\n df['tweet'] = tweet\n\n print('Successfully cleaned data!')\n\n\n # Saving list of tweet dicts to csv format\n\n if save_path:\n print(f'Saving data...')\n if not save_path.endswith('.csv'):\n print('Save path is missing .csv format extension!')\n save_path = save_path + '.csv'\n try:\n with open(save_path, 'w', encoding='utf8', newline='') as output_file:\n csv_file = csv.DictWriter(output_file,\n fieldnames=df_list[0].keys(),\n )\n\n csv_file.writeheader()\n csv_file.writerows(df_list)\n print(f'Data succesfully saved to \"{save_path}\"')\n\n except Exception as e:\n print(f'Unable to save data to \"{save_path}\", check the path and data!')\n print(f'Exception:\\n{e}')\n\n dataset_docs = [df['tweet'] for df in df_list]\n keys = df_list[0].keys()\n if train:\n dataset_labels = [df['label'] for df in df_list]\n return [dataset_docs, dataset_labels], keys\n else:\n return dataset_docs, keys\n" }, { "alpha_fraction": 0.7634927034378052, "alphanum_fraction": 0.777036726474762, "avg_line_length": 87.5999984741211, "blob_id": "8b40523fe4235b9b088f37e8b51f9f85bdd86539", "content_id": "4e05bcdb0cf3c16d01a0ba932a7f3d0bb67fc8b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9752, "license_type": "no_license", "max_line_length": 1436, "num_lines": 110, "path": "/README.md", "repo_name": "olof98johansson/SentimentAnalysisNLP", "src_encoding": "UTF-8", "text": "<h1 align=\"center\"> Description </h1>\nTo run the files, make sure all the dependencies are installed. Do this by running\n\n```\npip install -r requirements.txt\n```\n\nin the terminal. Then to run the training process for the LSTM model along with the data collection, data cleaning and preprocessing, type\n\n```\npython -m main.py\n```\n\nand then to collect the test data as well as perform the weekly based predictions with visualizations, type\n\n```\npython -m predict.py\n```\n\n#### Below is a short, partial discription about the project itself including methodology and results \n\n<hr>\n\n<h2 align=\"center\"> Sentiment Analysis to Classify Depression from Twitter Using Tweets Before andAfter COVID-19 Through Different NLP Approaches </h2>\n\n<b>[Camille Porter](https://github.com/finli), [Olof Johansson](https://github.com/olof98johansson), [Savya Sachi Gupta](https://github.com/foo-bar-omastar)</b>\n\nIndependent project in course <b>DAT450: Machine Learning for Natural Language Processing</b>\n\nChalmers Institute of Technology, Sweden\n\n\n<h3 align=\"center\"> Quick Overview </h3>\nWe aim to understand the affect of the COVID-19 pandemic on mental health, specifically depression, by performing sentiment analysis on ‘tweets’ shared on the social media service Twitter. We selected the United Kingdom and Ireland for our analysis as they had a government instituted lockdown across the country, which provides us with a definitive date as a reference point to gauge trends before and after. In order to understand how a lockdown affects depression, we sampled tweets from these locations and trained two different models to detect depression in tweets — a LSTM model, and theDistilBERT model, which is a condensed form of BERT. We scraped 5,000 tweets for each week that we measured during multiple time periods. The LSTM model performed better than DistilBERT yielding an accuracy of 0.94 as compared to 0.90 for DistilBERT. We found a 2-3% bump in the levelof depression two weeks after lockdown started, but no longterm changes.\n\n<br>\n\n\n\n\n# Methodology <a name=\"Methodology\"></a>\n## Data Collection <a name=\"Data Collection\"></a>\nIn order to maximize the locations included in our analysis, we used the longitude/latitude method. Using Google Earth, we determined that the Isle of Man is approximately at the center of the UK. Using the measurement tool on Google Earth, we found that a 550 kilometer circle around the Isle of Man covered all of UK and Ireland without touching France. In order to train the model we sourced tweets in two halves. One half of tweets related to depression, and another half of tweets that were non-depressive. This enables accurate labeling of data that helps train the model. The words we used to label depressive tweets were : depressed, lonely, sad, depression, tired, and anxious. The words that were labeled non-depressive were: happy, joy, thankful, health, hopeful, and glad. For each word specified above, we scraped 1,000 tweets, resulting in a training set size of 12,000 tweets. 80% of the tweets were selected for training and 20% for testing. Subsequently, for analyzing, we sourced 5,000 tweets per week for three different time periods; three months before and after the initial UK lockdown of 23 March, 2020, same period the year before and then a six months period starting from three months after the initial lockdown up to 17th of December, 2020. The code for the tweet collection process is found in the [twint_scraping.py](https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/twint_scraping.py) file.\n\n## Preprocessing <a name=\"Preprocessing\"></a>\nPrior to the training process, the collected tweets had to be cleaned, annotated, and combined as many raw collected tweets contain emojis, URLs, mentions and non-alphabetic\ntokens. Thus, a pre-processing step cleaned the tweets as above and also removed possible punctuation marks. Next, a vocabulary based on words from the training data was built which consisted of two dictionaries for encoding and decoding the input text data. Moreover, the encoding process also padded the input sequences to be the same length by adding a specific padding token. Additionally had the labels also be encoded as the training data were labeled with either depressive or not-depressive. These two categories were encoded into corresponding integers of 0 and 1. This code for these processes are found in the [data_cleaning.py](https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/data_cleaning.py) file and the [preprocessing.py](https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/preprocessing.py)\n\n## Models <a name=\"models\"></a>\nThe initial model used for the sentiment analysis was a standardized embedding, that converts input integer tokens into real-valued data, followed by a Long-Short-Term-Memory (LSTM) model with an added feed-forward layer with dropout as output layer. The initial states, h<sub>0</sub> and c<sub>0</sub>, of the LSTM network were zero initiated and the output of the feed-forward output layer was then fed into a sigmoid function, also used as the activation function in the LSTM network. As the problem is binary classification, the loss was thereafter computed by the binary cross entropy loss (BCE). Lastly, the decoding of the output from the predictions on the test data was done as\n\n<p align=\"center\">\n<a href=\"https://www.codecogs.com/eqnedit.php?latex=f_{decode}(\\hat{y})&space;=&space;\\begin{cases}&space;\\text{\\textit{depressive}},&space;\\quad&space;\\text{if&space;$\\hat{y}_i&space;<&space;0.5$}\\\\&space;\\text{\\textit{not-depressive}},&space;\\quad&space;\\text{if&space;$\\hat{y}_i&space;\\geq&space;0.5$}\\end{cases}\" target=\"_blank\"><img align=\"center\" src=\"https://latex.codecogs.com/gif.latex?f_{decode}(\\hat{y})&space;=&space;\\begin{cases}&space;\\text{\\textit{depressive}},&space;\\quad&space;\\text{if&space;$\\hat{y}_i&space;<&space;0.5$}\\\\&space;\\text{\\textit{not-depressive}},&space;\\quad&space;\\text{if&space;$\\hat{y}_i&space;\\geq&space;0.5$}\\end{cases}\" title=\"f_{decode}(\\hat{y}) = \\begin{cases} \\text{\\textit{depressive}}, \\quad \\text{if $\\hat{y}_i < 0.5$}\\\\ \\text{\\textit{not-depressive}}, \\quad \\text{if $\\hat{y}_i \\geq 0.5$}\\end{cases}\" /></a>\n</p>\n\nThe code for the LSTM model and the training function is found in [models.py](https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/models.py) file and [train.py](https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/train.py) file respectively.\n<br>\n\nIn addition to our LSTM model, we wanted to try a stateof-the-art transfer learning model. We decided to use DistilBERT, a smaller version of Bidirectional Encoder Representation from Transformers (BERT). BERT is a bidirectional LSTM with multi-head attention. The model implementation and training for the DistilBERT is found in the [Twitter_Classification_DistilBERT.ipynb](https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/Twitter_Classification_DistilBERT.ipynb) file.\n\n\n# Results <a name=\"Results\"></a>\n## Training <a name=\"Training\"></ha>\nThe code to run the training process of the LSTM model is found in [main.py](https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/main.py) file. The results of the training progress and accuracy metrics for the LSTM model are shown below. The highest validation accuracy for this model was 0.94.\n\n![First training session](https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/plots/training_animation_progress_REAL.gif?raw=true)\n<br>\n\nThe corresponding results for the DistilBERT model is further shown [here](https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/distilBERT_plots/8_epoch_train.pdf).\n\n\nSince our LSTM model has a greater validation accuracy, we will select that model performing our time period analysis in the next section.\n\n## Time period analysis <a name=\"forecast\"></a>\nThe results show the forecast of the percentage of depressive tweets, weekly collected, predicted by the LSTM model. From three months before UK initial lockdown to three months after, the following results were obtained. The code for making the predictions is found in the [predict.py](https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/predict.py) file.\n\n![First forecast](https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/plots/forecast_orig.png?raw=true)\n<br>\n\nThe results of the same time period for the previous year is further shown below.\n\n![Second forecast](https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/plots/forecast_year_before.png?raw=true)\n<br>\n\nThe final analysis from three months after the start of the initial UK lockdown up to the 17th of December, 2020, is shown below.\n![Third forecast](https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/plots/forecast_up_to_now.png?raw=true)\n\n<br>\n\nThe combined result, for comparison, is further shown below.\n\n![Comparison](https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/plots/comparison.png?raw=true)\n\nAn animation of the weekly results are also visualized below.\n\n\n<h2 align=\"center\"> Animated time series of the forecasts </h2>\n\n<table>\n <tr>\n <td>3 months before and after UK lockdownn</td>\n <td>Same period previous year</td>\n <td>3 months after lockdown to recent</td>\n </tr>\n <tr>\n <td><img src=\"https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/plots/forecast_bar_race_orig.gif\" width=300></td>\n <td><img src=\"https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/plots/forecast_bar_race_last_year.gif\" width=300></td>\n <td><img src=\"https://github.com/olof98johansson/SentimentAnalysisNLP/blob/main/plots/forecast_bar_race_up_to_now.gif\" width=300></td>\n </tr>\n </table>\n" } ]
9
Guilherme99/flask-react-session-authenticaton-tutorial
https://github.com/Guilherme99/flask-react-session-authenticaton-tutorial
47cd5f3d7c08e35934ee1877d4e88a12b12a316e
88c454af9932435d0bd9ad1c16718beb6fc0e1c1
aae33fb68a524722077d26403524af8ab28d20a7
refs/heads/master
2023-08-21T03:39:00.600501
2021-10-13T10:27:47
2021-10-13T10:27:47
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7640449404716492, "alphanum_fraction": 0.7977527976036072, "avg_line_length": 28.66666603088379, "blob_id": "4a757d4407a29e384aa00d863c089eb459b0fd44", "content_id": "c7666d22e7a02dda5ba22a4a6094e3b3ecb53add", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 89, "license_type": "permissive", "max_line_length": 50, "num_lines": 3, "path": "/README.md", "repo_name": "Guilherme99/flask-react-session-authenticaton-tutorial", "src_encoding": "UTF-8", "text": "# Flask React Session Authentication\n\nVideo: https://www.youtube.com/watch?v=sBw0O5YTT4Q\n" }, { "alpha_fraction": 0.6739659309387207, "alphanum_fraction": 0.698296844959259, "avg_line_length": 23.235294342041016, "blob_id": "e21bd1aa8bae16d6090d96b7da1d382e6ba0da7d", "content_id": "f717729d6712f5bbd8b1c9f44dde5e6c1bc8107e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 411, "license_type": "permissive", "max_line_length": 60, "num_lines": 17, "path": "/server/config.py", "repo_name": "Guilherme99/flask-react-session-authenticaton-tutorial", "src_encoding": "UTF-8", "text": "from dotenv import load_dotenv\nimport os\nimport redis\n\nload_dotenv()\n\nclass ApplicationConfig:\n SECRET_KEY = os.environ[\"SECRET_KEY\"]\n\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n SQLALCHEMY_ECHO = True\n SQLALCHEMY_DATABASE_URI = r\"sqlite:///./db.sqlite\"\n\n SESSION_TYPE = \"redis\"\n SESSION_PERMANENT = False\n SESSION_USE_SIGNER = True\n SESSION_REDIS = redis.from_url(\"redis://127.0.0.1:6379\")" }, { "alpha_fraction": 0.6314731240272522, "alphanum_fraction": 0.6390146017074585, "avg_line_length": 23.875, "blob_id": "c51cd34c4884030ee9c9f73316a066480c3b3487", "content_id": "1eb95b3cb6c806e4366c934fb4da19e8db9252cc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1989, "license_type": "permissive", "max_line_length": 71, "num_lines": 80, "path": "/server/app.py", "repo_name": "Guilherme99/flask-react-session-authenticaton-tutorial", "src_encoding": "UTF-8", "text": "from flask import Flask, request, jsonify, session\nfrom flask_bcrypt import Bcrypt\nfrom flask_cors import CORS, cross_origin\nfrom flask_session import Session\nfrom config import ApplicationConfig\nfrom models import db, User\n\napp = Flask(__name__)\napp.config.from_object(ApplicationConfig)\n\nbcrypt = Bcrypt(app)\nCORS(app, supports_credentials=True)\nserver_session = Session(app)\ndb.init_app(app)\n\nwith app.app_context():\n db.create_all()\n\[email protected](\"/@me\")\ndef get_current_user():\n user_id = session.get(\"user_id\")\n\n if not user_id:\n return jsonify({\"error\": \"Unauthorized\"}), 401\n \n user = User.query.filter_by(id=user_id).first()\n return jsonify({\n \"id\": user.id,\n \"email\": user.email\n }) \n\[email protected](\"/register\", methods=[\"POST\"])\ndef register_user():\n email = request.json[\"email\"]\n password = request.json[\"password\"]\n\n user_exists = User.query.filter_by(email=email).first() is not None\n\n if user_exists:\n return jsonify({\"error\": \"User already exists\"}), 409\n\n hashed_password = bcrypt.generate_password_hash(password)\n new_user = User(email=email, password=hashed_password)\n db.session.add(new_user)\n db.session.commit()\n \n session[\"user_id\"] = new_user.id\n\n return jsonify({\n \"id\": new_user.id,\n \"email\": new_user.email\n })\n\[email protected](\"/login\", methods=[\"POST\"])\ndef login_user():\n email = request.json[\"email\"]\n password = request.json[\"password\"]\n\n user = User.query.filter_by(email=email).first()\n\n if user is None:\n return jsonify({\"error\": \"Unauthorized\"}), 401\n\n if not bcrypt.check_password_hash(user.password, password):\n return jsonify({\"error\": \"Unauthorized\"}), 401\n \n session[\"user_id\"] = user.id\n\n return jsonify({\n \"id\": user.id,\n \"email\": user.email\n })\n\[email protected](\"/logout\", methods=[\"POST\"])\ndef logout_user():\n session.pop(\"user_id\")\n return \"200\"\n\nif __name__ == \"__main__\":\n app.run(debug=True)" }, { "alpha_fraction": 0.862500011920929, "alphanum_fraction": 0.862500011920929, "avg_line_length": 10.571428298950195, "blob_id": "edeffd3cb0c0091083231b1cc0963efb230d1a6a", "content_id": "ce7d2e150affe30f89e3dc857fd6b8e9df8492ce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 80, "license_type": "permissive", "max_line_length": 16, "num_lines": 7, "path": "/server/requirements.txt", "repo_name": "Guilherme99/flask-react-session-authenticaton-tutorial", "src_encoding": "UTF-8", "text": "flask\nflask-sqlalchemy\nflask-bcrypt\npython-dotenv\nflask-session\nredis\nflask-cors" }, { "alpha_fraction": 0.6722689270973206, "alphanum_fraction": 0.6918767690658569, "avg_line_length": 26.461538314819336, "blob_id": "f26a4ef371b0ebb0db6d2cf01a7ba976349c7efb", "content_id": "ebef36101066ba7bb6315af74852a29c3149057b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 357, "license_type": "permissive", "max_line_length": 82, "num_lines": 13, "path": "/server/models.py", "repo_name": "Guilherme99/flask-react-session-authenticaton-tutorial", "src_encoding": "UTF-8", "text": "from flask_sqlalchemy import SQLAlchemy\nfrom uuid import uuid4\n\ndb = SQLAlchemy()\n\ndef get_uuid():\n return uuid4().hex\n\nclass User(db.Model):\n __tablename__ = \"users\"\n id = db.Column(db.String(32), primary_key=True, unique=True, default=get_uuid)\n email = db.Column(db.String(345), unique=True)\n password = db.Column(db.Text, nullable=False)\n" } ]
5
EricHughesABC/T2EPGviewer
https://github.com/EricHughesABC/T2EPGviewer
b2a6dbdec06bcbdafa0f6d3e0ae60d01bf46b509
b6912f671af3ddfad75e5143e28494c5e407c957
6c9b4a3712c424ad27c20c7f58e0bf481afe8a2f
refs/heads/master
2020-06-26T12:13:28.613803
2019-07-31T13:55:55
2019-07-31T13:55:55
199,627,638
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5393113493919373, "alphanum_fraction": 0.5733750462532043, "avg_line_length": 30.72891616821289, "blob_id": "af248c742c4d6db16d79511d90135f02dbcee4b9", "content_id": "f8df89745d54b84314eae16ecc941f629b84a506", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5431, "license_type": "permissive", "max_line_length": 155, "num_lines": 166, "path": "/t2fit.py", "repo_name": "EricHughesABC/T2EPGviewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 3 11:30:41 2018\r\n\r\n@author: ERIC\r\n\"\"\"\r\nimport numpy as np\r\nimport lmfit\r\nfrom epg import cpmg_epg_b1 as cpmg_epg_b1_c\r\n\r\nfrom scipy import integrate\r\n\r\nmxyz90 = np.fromfile( 'epg/mxyz90.txt', sep=' ' )\r\nmxyz180 = np.fromfile('epg/mxyz180.txt', sep=' ')\r\n\r\nmxyz90 = mxyz90.reshape(5,512)\r\nmxyz180 = mxyz180.reshape(5,512)\r\n\r\noffset=130\r\nstep=10\r\nepg_slice_xxx =mxyz90[0][offset:-offset+step:step] # mm\r\nepg_p90 = mxyz90[-1][offset:-offset+step:step] # degrees\r\nepg_p180 = mxyz180[-1][offset:-offset+step:step] # degrees\r\nepg_dx=epg_slice_xxx[1]-epg_slice_xxx[0]\r\n\r\n\r\ndef fit_cpmg_epg_muscle_philips_hargreaves_c( params, xxx, dx, p90_array, p180_array, yyy_exp=None):\r\n\r\n parvals = params.valuesdict()\r\n\r\n T1fat = parvals[ 'T1fat' ] # fixed\r\n T1muscle = parvals[ 'T1muscle' ] # fixed\r\n echo = parvals[ 'echo' ] # fixed\r\n T2fat = parvals[ 'T2fat' ] # fixed/optimized\r\n T2muscle = parvals['T2muscle'] # optimized\r\n Afat = parvals[ 'Afat'] # optimized\r\n Amuscle = parvals['Amuscle'] # optimized\r\n B1scale = parvals['B1scale']\r\n\r\n Nechos = len(xxx)\r\n Ngauss = len(p90_array)\r\n\r\n signal = np.zeros([Ngauss,Nechos])\r\n fat_signal = np.zeros(Nechos)\r\n muscle_signal = np.zeros(Nechos)\r\n\r\n for i,(p90,p180) in enumerate(zip(p90_array,p180_array)):\r\n\r\n cpmg_epg_b1_c( fat_signal, p90, p180, T1fat, T2fat, echo, B1scale )\r\n cpmg_epg_b1_c( muscle_signal, p90, p180, T1muscle, T2muscle, echo, B1scale )\r\n\r\n signal[i] = Afat*fat_signal+Amuscle*muscle_signal\r\n\r\n int_signal = integrate.simps(signal, dx=dx,axis=0)\r\n if isinstance(yyy_exp, np.ndarray):\r\n return( int_signal-yyy_exp)\r\n else:\r\n return(int_signal)\r\n\r\n\r\n\r\ndef calculate_T2values_on_slice_muscleEPG(lmparams, yyy_exp):\r\n\r\n# params = lmfit.Parameters()\r\n# params.add('T2fat', value = 180.0, min=0, max=5000, vary=False)\r\n# params.add('T2muscle', value = 35, min=0, max=100, vary=True )\r\n# params.add('Afat', value = 0.01, min=0, max=10, vary=True )\r\n# params.add('Amuscle', value = 0.1, min=0, max=10, vary=True )\r\n# params.add('T1fat', value = 365.0, vary=False)\r\n# params.add('T1muscle', value = 1400, vary=False)\r\n# params.add('echo', value = 10.0, vary=False)\r\n\r\n params = lmparams['epgt2fitparams']\r\n echo_time = params['echo'].value\r\n num_echoes = yyy_exp.size\r\n\r\n parvals = params.valuesdict()\r\n\r\n print(\"parvals\")\r\n for k,v in parvals.items():\r\n print(k,v)\r\n\r\n print(\"EPG echo time =\", echo_time)\r\n xxx = np.linspace( echo_time, echo_time*num_echoes, num_echoes)\r\n dx = xxx[1]-xxx[0]\r\n\r\n\r\n yyy_exp_max =yyy_exp.max()\r\n if yyy_exp_max == 0:\r\n yyy_exp_max = 1.0\r\n yyy_exp_norm = yyy_exp/yyy_exp_max\r\n\r\n fitModel = lmfit.Minimizer(fit_cpmg_epg_muscle_philips_hargreaves_c, lmparams['epgt2fitparams'], fcn_args=( xxx, dx, epg_p90, epg_p180, yyy_exp_norm))\r\n results = fitModel.minimize()\r\n\r\n fit_plot = np.zeros(num_echoes)\r\n\r\n if results.success:\r\n fit_plot = results.residual + yyy_exp_norm\r\n\r\n return( fit_plot, yyy_exp_norm, results, xxx)\r\n\r\n\r\n\r\n\r\ndef calculate_T2values_on_slice_muscleAzz(lmparams, yyy_exp):\r\n\r\n params = lmparams['azzt2fitparams']\r\n echo_time = params['echo'].value\r\n num_echoes = yyy_exp.size\r\n\r\n model = lmfit.models.ExpressionModel('Afat * (c_l*exp(-x/t2_fl)+c_s*exp(-x/t2_fs)) + Amuscle * (exp(-x/T2muscle))')\r\n\r\n parvals = params.valuesdict()\r\n print(\"parvals\")\r\n for k,v in parvals.items():\r\n print(k,v)\r\n\r\n print(\"azzabou echo time\", echo_time)\r\n\r\n# saved_output = {'T2muscle_value': [],\r\n# 'T2muscle_stderr': [],\r\n# 'Amuscle_value': [],\r\n# 'Amuscle_stderr': [],\r\n# 'Afat_value': [],\r\n# 'Afat_stderr': [],\r\n# 'chisqr': [],\r\n# 'redchi':[],\r\n# 'AIC':[],\r\n# 'BIC':[],\r\n# 'slice':[],\r\n# 'pixel_index':[],\r\n# }\r\n\r\n xxx = np.linspace( echo_time, echo_time*num_echoes, num_echoes)\r\n\r\n\r\n yyy_exp_max = yyy_exp.max()\r\n fit_plot = np.zeros(num_echoes-2)\r\n if yyy_exp_max == 0.0:\r\n yyy_exp_max = 1.0\r\n yyy_exp_norm = yyy_exp/yyy_exp_max\r\n\r\n\r\n print(\"fitting data\")\r\n\r\n results = model.fit(yyy_exp_norm[2:] , x=xxx[2:], params=lmparams['azzt2fitparams'])\r\n #mi.plot()\r\n #saved_output['name'].append('t2_m')\r\n# saved_output['T2muscle_value'].append(results.params['T2muscle'].value)\r\n# saved_output['T2muscle_stderr'].append(results.params['T2muscle'].stderr)\r\n# saved_output['chisqr'].append(results.chisqr)\r\n# saved_output['redchi'].append(results.redchi)\r\n# saved_output['AIC'].append(results.aic)\r\n# saved_output['BIC'].append(results.bic)\r\n#\r\n#\r\n# saved_output['Amuscle_value'].append(results.params['Amuscle'].value)\r\n# saved_output['Amuscle_stderr'].append(results.params['Amuscle'].stderr)\r\n\r\n# saved_output['Afat_value'].append(results.params['Afat'].value)\r\n# saved_output['Afat_stderr'].append(results.params['Afat'].stderr)\r\n\r\n fit_plot = results.residual + yyy_exp_norm[2:]\r\n\r\n return( fit_plot, yyy_exp_norm, results, xxx)" }, { "alpha_fraction": 0.5434625148773193, "alphanum_fraction": 0.566312849521637, "avg_line_length": 31.364152908325195, "blob_id": "ce0a269281b9f3cb430a4d55a078469d0d683099", "content_id": "f8074cff6b04a7964245388154f812af766aa823", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23457, "license_type": "permissive", "max_line_length": 171, "num_lines": 703, "path": "/visionplot_widgets.py", "repo_name": "EricHughesABC/T2EPGviewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Feb 28 13:11:07 2018\r\n\r\n@author: neh69\r\n\"\"\"\r\nimport sys\r\nimport numpy as np\r\n#import matplotlib\r\nimport pandas as pd\r\n#import mplcursors\r\n\r\nfrom uncertainties import ufloat\r\nimport t2fit\r\nimport lmfit as lm\r\n\r\nfrom matplotlib import pyplot as plt\r\n#import seaborn as sns\r\n\r\nfrom matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5\r\nimport seaborn as sns\r\n\r\nif is_pyqt5():\r\n print(\"pyqt5\")\r\n from matplotlib.backends.backend_qt5agg import (\r\n FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\r\nelse:\r\n print(\"pyqt4\")\r\n from matplotlib.backends.backend_qt4agg import (\r\n FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\r\nfrom matplotlib.figure import Figure\r\n\r\n\r\nfrom ImageData import T2imageData\r\nimport epgT2paramsDialog\r\nimport azzT2paramsDialog\r\n\r\n\r\n\r\n#mxyz90 = np.fromfile( 'epg\\mxyz90.txt', sep=' ' )\r\n#mxyz180 = np.fromfile('epg\\mxyz180.txt', sep=' ')\r\n#\r\n#mxyz90 = mxyz90.reshape(5,512)\r\n#mxyz180 = mxyz180.reshape(5,512)\r\n#\r\n#offset=130\r\n#step=10\r\n#epg_slice_xxx =mxyz90[0][offset:-offset+step:step] # mm\r\n#epg_p90 = mxyz90[-1][offset:-offset+step:step] # degrees\r\n#epg_p180 = mxyz180[-1][offset:-offset+step:step] # degrees\r\n#epg_dx=epg_slice_xxx[1]-epg_slice_xxx[0]\r\n\r\n\r\n\r\nclass PlotWidget(QtWidgets.QWidget):\r\n\r\n def __init__(self, parent=None, showToolbar=True):\r\n\r\n super(PlotWidget,self).__init__(parent)\r\n\r\n fig =Figure(figsize=(3, 5))\r\n fig.set_tight_layout(True)\r\n self.plot_canvas = FigureCanvas(fig)\r\n self.ax = fig.add_subplot(111)\r\n\r\n\r\n\r\n self.layout = QtWidgets.QVBoxLayout(self)\r\n self.layout.addWidget(self.plot_canvas)\r\n\r\n if showToolbar:\r\n self.toolbar = NavigationToolbar(self.plot_canvas, self)\r\n self.layout.addWidget(self.toolbar)\r\n\r\n def return_ax(self):\r\n return(self.ax)\r\n\r\n\r\n\r\nclass HistogramPlotWidget(PlotWidget):\r\n\r\n def __init__(self, parent=None, showToolbar=False, mri_plot=None, data_df=None, image_size=256):\r\n\r\n self.data_df = data_df\r\n self.image_size = image_size\r\n\r\n super(HistogramPlotWidget,self).__init__(parent=parent, showToolbar=showToolbar)\r\n\r\n self.buttonUpdate = QtWidgets.QPushButton('Update')\r\n self.buttonUpdate.clicked.connect(self.update)\r\n self.layout.addWidget(self.buttonUpdate)\r\n\r\n\r\n def update(self):\r\n\r\n print((self.ax.get_xlim()))\r\n xmin,xmax = self.ax.get_xlim()\r\n\r\n\r\n\r\n def update_plot(self, slice_info,data_dframes, plot_param):\r\n\r\n self.ax.cla()\r\n self.plot_canvas.draw()\r\n\r\n print(\"Entered HistogramPlotWidget.update_image, plot_param =\", plot_param)\r\n\r\n data_df=None\r\n\r\n slice_displayed = slice_info[0]\r\n T2_slices = slice_info[1]\r\n dixon_slices = slice_info[2]\r\n\r\n print(\"data_dframes[0]\", type(data_dframes[0]), data_dframes[0].columns)\r\n print(\"data_dframes[1]\", type(data_dframes[1]), data_dframes[1].columns)\r\n\r\n\r\n if isinstance(data_dframes[0],pd.core.frame.DataFrame):\r\n if plot_param in data_dframes[0].columns:\r\n print(\"plot_param {} found in dataframe is T2\".format(plot_param))\r\n data_df = data_dframes[0]\r\n data_df=data_df[data_df[\"slice\"]==slice_displayed]\r\n elif isinstance(data_dframes[1],pd.core.frame.DataFrame):\r\n print(\"plot_param {} found in dataframe is Dixon\".format(plot_param))\r\n print(\"data_dframes[1].columns\",data_dframes[1].columns)\r\n if plot_param in data_dframes[1].columns:\r\n print(\"plot_param in data_dframes[1]:\", plot_param)\r\n data_df = data_dframes[1]\r\n if slice_displayed in T2_slices:\r\n slice_displayed = dixon_slices[T2_slices.index(slice_displayed)]\r\n data_df=data_df[data_df[\"slice\"]==slice_displayed]\r\n else:\r\n print( \"HIST\", plot_param, \" not found\")\r\n return False\r\n else:\r\n print(\"HIST\", isinstance(data_dframes[1],pd.core.frame.DataFrame))\r\n return False\r\n\r\n print(\"HIST data_df.shape[0]\",data_df.shape[0])\r\n if data_df.shape[0] == 0 or type(data_df) == type(None):\r\n print(\"HIST return because df shape[0] = 0 or type of data_df = type None\")\r\n return False\r\n\r\n# self.ax2.cla()\r\n if isinstance(data_df, pd.core.frame.DataFrame):\r\n print(\"Plotting HIST Plot\" )\r\n data_df = data_df.sort_values(by=['roi'])\r\n #plot_param = \"T2value\"\r\n for roi in data_df.roi.unique():\r\n print(roi)\r\n query_str = '(slice == {}) and (roi == \"{}\")'.format(slice_displayed, roi)\r\n sns.distplot(data_df.query(query_str)[plot_param], hist=False, label=roi, ax=self.ax)\r\n# self.ax.hist( data_df.query(query_str)[plot_param], bins=100, label=roi, alpha=0.7);\r\n self.ax.legend()\r\n\r\n if plot_param == \"T2m\":\r\n self.ax.set_xlabel(\"$T_2$ [ms]\")\r\n\r\n elif plot_param == \"Am100\":\r\n self.ax.set_xlabel(\"$A_m$ [%]\")\r\n\r\n elif plot_param == \"Af100\":\r\n self.ax.set_xlabel(\"$A_f$ [%]\")\r\n elif plot_param == \"B1\":\r\n self.ax.set_xlabel(\"$B_1$\")\r\n\r\n elif plot_param == \"fatPC\":\r\n self.ax.set_xlabel(\"ff [%]\")\r\n\r\n self.ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\r\n\r\n self.plot_canvas.draw()\r\n\r\n return True\r\n\r\n\r\n\r\n\r\nclass BarPlotWidget(PlotWidget):\r\n\r\n def __init__(self, parent=None, showToolbar=True, data_df=None, image_size=256):\r\n\r\n self.data_df = data_df\r\n self.image_size = image_size\r\n\r\n super(BarPlotWidget,self).__init__(parent=parent, showToolbar=showToolbar)\r\n\r\n# self.buttonUpdate = QtWidgets.QPushButton('Update')\r\n# self.buttonUpdate.clicked.connect(self.update)\r\n# self.layout.addWidget(self.buttonUpdate)\r\n\r\n\r\n def update(self):\r\n\r\n print((self.ax.get_xlim()))\r\n xmin,xmax = self.ax.get_xlim()\r\n\r\n\r\n\r\n def update_plot(self, slice_info,data_dframes, plot_param):\r\n\r\n self.ax.cla()\r\n self.plot_canvas.draw()\r\n\r\n print(\"Entered BarPlotWidget.update_image, plot_param =\", plot_param)\r\n #print(data_.columns)\r\n\r\n slice_displayed = slice_info[0]\r\n T2_slices = slice_info[1]\r\n dixon_slices = slice_info[2]\r\n\r\n data_df=None\r\n\r\n print(\"data_dframes[0]\", type(data_dframes[0]), data_dframes[0].columns)\r\n print(\"data_dframes[1]\", type(data_dframes[1]), data_dframes[1].columns)\r\n\r\n\r\n if isinstance(data_dframes[0],pd.core.frame.DataFrame):\r\n\r\n if plot_param in data_dframes[0].columns:\r\n\r\n print(\"plot_param {} found in dataframe is T2\".format(plot_param))\r\n data_df = data_dframes[0]\r\n data_df=data_df[data_df[\"slice\"]==slice_displayed]\r\n\r\n elif isinstance(data_dframes[1],pd.core.frame.DataFrame):\r\n\r\n print(\"plot_param {} found in dataframe is Dixon\".format(plot_param))\r\n print(\"data_dframes[1].columns\",data_dframes[1].columns)\r\n\r\n if plot_param in data_dframes[1].columns:\r\n\r\n print(\"plot_param in data_dframes[1]:\", plot_param)\r\n data_df = data_dframes[1]\r\n\r\n if slice_displayed in T2_slices:\r\n\r\n slice_displayed = dixon_slices[T2_slices.index(slice_displayed)]\r\n# else:\r\n# dixon_slice = slice_displayed\r\n# slice_displayed = dixon_slices[T2_slices.index(slice_displayed)]\r\n data_df=data_df[data_df[\"slice\"]==slice_displayed]\r\n else:\r\n print( plot_param, \" not found\")\r\n return(False)\r\n else:\r\n print(isinstance(data_dframes[1],pd.core.frame.DataFrame))\r\n return(False)\r\n\r\n print(\"HIST data_df.shape[0]\", data_df.shape[0])\r\n\r\n if data_df.shape[0] == 0 or type(data_df) == type(None):\r\n print(\"return because df shape[0] = 0 or type of data_df = type None\")\r\n return False\r\n\r\n data_df = data_df.sort_values(by=['roi'])\r\n\r\n if isinstance(data_df, pd.core.frame.DataFrame):\r\n print(\"Plotting BAR Plot\" )\r\n #plot_param = \"T2value\"\r\n# for roi in data_df.roi.unique():\r\n# print(roi)\r\n# query_str = '(slice == {}) and (roi == \"{}\")'.format(slice_displayed, roi)\r\n# self.ax.hist( data_df.query(query_str)[plot_param], bins=100, label=roi, alpha=0.4);\r\n# self.ax.legend()\r\n\r\n# numRois = data_df.roi.unique().shape[0]\r\n\r\n sns.catplot( kind='bar',\r\n x='slice',\r\n y=plot_param,\r\n data=data_df,\r\n hue='roi',\r\n ci=\"sd\",\r\n ax=self.return_ax()\r\n );\r\n\r\n self.ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\r\n if plot_param == \"T2m\":\r\n self.ax.set_ylabel(\"$T_2$ [ms]\")\r\n elif plot_param == \"Am100\":\r\n self.ax.set_ylabel(\"$A_m$ [%]\")\r\n elif plot_param == \"Af100\":\r\n self.ax.set_ylabel(\"$A_f$ [%]\")\r\n elif plot_param == \"B1\":\r\n self.ax.set_ylabel(\"$B_1$\")\r\n elif plot_param == \"fatPC\":\r\n self.ax.set_ylabel(\"ff [%]\")\r\n\r\n self.ax.set_xlabel(\"slices\")\r\n# plt.tight_layout()\r\n self.plot_canvas.draw()\r\n\r\n return True\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass T2PlotWidget(PlotWidget):\r\n\r\n def __init__( self, lmparams, parent=None, showToolbar=True):\r\n\r\n super(T2PlotWidget, self).__init__(parent, showToolbar=showToolbar)\r\n self.plot_T2_startup()\r\n\r\n self.lmparams = lmparams\r\n\r\n\r\n\r\n self.T2epgnorm_btns = radiobuttons_EPGWidget(self.lmparams, self)\r\n self.layout.addWidget(self.T2epgnorm_btns)\r\n\r\n\r\n\r\n\r\n\r\n def plot_T2_startup(self):\r\n ttt = np.linspace(0,170, 17)\r\n yyy = 80*np.exp(-ttt/35.0)+20*np.exp(-ttt/120.0)\r\n yyy1 = yyy+np.random.randn(len(yyy))\r\n\r\n self.ax.semilogy(ttt, yyy1, 'o')\r\n self.ax.semilogy(ttt, yyy, '-')\r\n self.ax.set_xlabel('Time [ms]')\r\n self.ax.set_ylabel('Signal')\r\n self.ax.set_ylim(1,110)\r\n\r\n\r\n\r\n def update_plot(self, xcoord, ycoord, t2data):\r\n\r\n print(\"update_T2PlotImag called\")\r\n #self.ttt = np.linspace(0,170, 17)\r\n\r\n self.ax.cla() # clear the plot area\r\n\r\n if self.T2epgnorm_btns.epg_rbtn.isChecked():\r\n print(\"Run EPG Fit\")\r\n print('echo value', self.lmparams['epgt2fitparams']['echo'])\r\n\r\n# params = lm.Parameters()\r\n# params.add('T2fat', value = 180.0, min=0, max=5000, vary=False)\r\n# params.add('T2muscle', value = 35, min=0, max=100, vary=True )\r\n# params.add('Afat', value = 0.01, min=0, max=10, vary=True )\r\n# params.add('Amuscle', value = 0.1, min=0, max=10, vary=True )\r\n# params.add('T1fat', value = 365.0, vary=False)\r\n# params.add('T1muscle', value = 1400, vary=False)\r\n# params.add('echo', value = 10.0, vary=False)\r\n\r\n\r\n\r\n #xxx = np.linspace(10,10*len(t2data), len(t2data))\r\n# self.params.pretty_print()\r\n\r\n #fit_values, fit_curve, fit_data, lmresults = t2fit.calculate_T2values_on_slice_muscleEPG(self.lmparams, t2data, len(t2data), xxx, epg_dx, epg_p90, epg_p180)\r\n fit_curve, fit_data, lmresults, xxx = t2fit.calculate_T2values_on_slice_muscleEPG(self.lmparams, t2data)\r\n\r\n else:\r\n print(\"Run Normal T2 Fit\")\r\n\r\n fit_curve, fit_data, lmresults, xxx = t2fit.calculate_T2values_on_slice_muscleAzz(self.lmparams,t2data)\r\n\r\n print(dir(lmresults))\r\n print(lmresults.success)\r\n\r\n if not lmresults.success:\r\n return\r\n #\r\n # Create uncertainty floats of varied params\r\n #\r\n ufs = {}\r\n for vname in lmresults.var_names:\r\n v = lmresults.params[vname].value\r\n e = lmresults.params[vname].stderr\r\n ufs[vname] = ufloat( v,e)\r\n\r\n if ('Amuscle' in ufs.keys()) and ('Afat' in ufs.keys()):\r\n ufs['Amuscle'] = 100.0*ufs['Amuscle']/(ufs['Amuscle']+ufs['Afat'])\r\n ufs['Afat'] = 100.0-ufs['Amuscle']\r\n\r\n t2m_str = \"\"\r\n t2f_str = \"\"\r\n Am_str = \"\"\r\n Af_str = \"\"\r\n B1_str = \"\"\r\n\r\n for name, value in ufs.items():\r\n\r\n print(name)\r\n\r\n if name == 'T2muscle':\r\n\r\n t2m_str = \"$T_{{2m}}$ = ${:5.2fL}$ ms\\n\".format(value)\r\n\r\n elif name == 'T2fat':\r\n\r\n t2f_str = \"$T_{{2f}}$ = ${:5.2fL}$ ms\\n\".format(value)\r\n\r\n elif name == 'Amuscle':\r\n\r\n Am_str = \"$A_m$ = ${:5.2fL}$\\n\".format(value)\r\n\r\n elif name == 'Afat':\r\n\r\n Af_str = \"$A_f$ = ${:5.2fL}$\\n\".format(value)\r\n\r\n elif name == 'B1scale':\r\n\r\n B1_str = \"$B_1$ scale = ${:5.2fL}$\\n\".format(value)\r\n\r\n\r\n results_legend = \"{}{}{}{}{}\".format(t2m_str, t2f_str, Am_str, Af_str, B1_str)\r\n\r\n if self.T2epgnorm_btns.epg_rbtn.isChecked():\r\n self.ax.semilogy(xxx, 100*fit_data, 'o')\r\n self.ax.semilogy(xxx, 100*fit_curve, '-', label=results_legend)\r\n else:\r\n\r\n self.ax.semilogy(xxx[2:], 100*fit_curve, '-', label=results_legend)\r\n self.ax.semilogy(xxx, 100*fit_data, 'o')\r\n\r\n self.ax.legend( fontsize=8)\r\n #self.ax.set_ylim(1,110)\r\n self.ax.set_xlabel('Time [ms]')\r\n self.ax.set_ylabel('Signal')\r\n self.ax.set_ylim(0.5,150)\r\n\r\n self.plot_canvas.draw()\r\n\r\n\r\n\r\nclass radiobuttons_EPGWidget(QtWidgets.QWidget):\r\n\r\n def __init__(self, lmparams, parent=None):\r\n\r\n self.lmparams = lmparams\r\n\r\n self.epgDialog = QtWidgets.QDialog()\r\n self.epgT2params_widget = epgT2paramsDialog.EpgT2paramsDialog(self.lmparams)\r\n self.epgT2params_widget.setupEpgT2paramsDialog(self.epgDialog)\r\n\r\n self.azzDialog = QtWidgets.QDialog()\r\n self.azzT2params_widget = azzT2paramsDialog.AzzT2paramsDialog(self.lmparams)\r\n self.azzT2params_widget.setupAzzT2paramsDialog(self.azzDialog)\r\n\r\n super(radiobuttons_EPGWidget, self).__init__(parent)\r\n hlayout = QtWidgets.QHBoxLayout(self)\r\n\r\n group_rbtns = QtWidgets.QButtonGroup()\r\n group_rbtns.exclusive()\r\n\r\n self.epg_rbtn = QtWidgets.QRadioButton(\"EPG T2\")\r\n self.norm_rbtn = QtWidgets.QRadioButton(\"normal T2\")\r\n self.norm_rbtn.setChecked(True);\r\n self.T2params_btn = QtWidgets.QPushButton(\"T2 Parameters\")\r\n\r\n self.epg_rbtn.fittingParam = \"epg\"\r\n self.norm_rbtn.fittingParam= 'norm'\r\n\r\n self.epg_rbtn.toggled.connect(lambda:self.btnstate(self.epg_rbtn))\r\n self.norm_rbtn.toggled.connect(lambda:self.btnstate(self.norm_rbtn))\r\n\r\n self.T2params_btn.clicked.connect(self.T2params_btn_clicked)\r\n\r\n group_rbtns.addButton(self.epg_rbtn)\r\n group_rbtns.addButton(self.norm_rbtn)\r\n\r\n\r\n hlayout.addWidget(self.norm_rbtn)\r\n hlayout.addWidget(self.epg_rbtn)\r\n hlayout.addStretch(1)\r\n hlayout.addWidget(self.T2params_btn)\r\n\r\n def T2params_btn_clicked(self):\r\n print(\"T2params_btn_clicked\")\r\n\r\n if self.epg_rbtn.isChecked():\r\n rt = self.epgDialog.show()\r\n\r\n else:\r\n rt = self.azzDialog.show()\r\n\r\n\r\n print(\"rt =\", rt)\r\n\r\n def btnstate(self,b):\r\n\r\n if b.isChecked():\r\n print(b.text())\r\n print(b.fittingParam)\r\n #self.mri_window.on_fittingParams_rbtn_toggled( str(b.fittingParam))\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass radiobuttons_fitWidget(QtWidgets.QWidget):\r\n\r\n def __init__(self, parent=None, mri_window=None):\r\n\r\n super(radiobuttons_fitWidget, self).__init__(parent)\r\n self.mri_window = mri_window\r\n\r\n vbox1_radiobuttons = QtWidgets.QVBoxLayout(self)\r\n\r\n group_fittingParams_rbtns = QtWidgets.QButtonGroup()\r\n group_fittingParams_rbtns.exclusive()\r\n\r\n self.T2_rbtn = QtWidgets.QRadioButton(\"T2\")\r\n self.Am_rbtn = QtWidgets.QRadioButton(\"Am\")\r\n self.Af_rbtn = QtWidgets.QRadioButton(\"Af\")\r\n self.B1_rbtn = QtWidgets.QRadioButton(\"B1\")\r\n self.Dixon_rbtn = QtWidgets.QRadioButton(\"Dixon Fat [%]\")\r\n\r\n self.T2_rbtn.setChecked(True)\r\n\r\n self.T2_rbtn.fittingParam = \"T2m\"\r\n self.Am_rbtn.fittingParam = \"Am100\"\r\n self.Af_rbtn.fittingParam = \"Af100\"\r\n self.B1_rbtn.fittingParam = \"B1\"\r\n self.Dixon_rbtn.fittingParam = \"fatPC\"\r\n\r\n self.T2_rbtn.toggled.connect(lambda:self.btnstate(self.T2_rbtn))\r\n self.Am_rbtn.toggled.connect(lambda:self.btnstate(self.Am_rbtn))\r\n self.Af_rbtn.toggled.connect(lambda:self.btnstate(self.Af_rbtn))\r\n self.B1_rbtn.toggled.connect(lambda:self.btnstate(self.B1_rbtn))\r\n self.Dixon_rbtn.toggled.connect(lambda:self.btnstate(self.Dixon_rbtn))\r\n\r\n group_fittingParams_rbtns.addButton(self.T2_rbtn)\r\n group_fittingParams_rbtns.addButton(self.Am_rbtn)\r\n group_fittingParams_rbtns.addButton(self.Af_rbtn)\r\n group_fittingParams_rbtns.addButton(self.B1_rbtn)\r\n group_fittingParams_rbtns.addButton(self.Dixon_rbtn)\r\n\r\n vbox1_radiobuttons.addWidget(self.T2_rbtn)\r\n vbox1_radiobuttons.addWidget(self.Am_rbtn)\r\n vbox1_radiobuttons.addWidget(self.Af_rbtn)\r\n vbox1_radiobuttons.addWidget(self.B1_rbtn)\r\n vbox1_radiobuttons.addWidget(self.Dixon_rbtn)\r\n\r\n vbox1_radiobuttons.addStretch(1)\r\n\r\n def btnstate(self,b):\r\n\r\n if b.isChecked():\r\n print(b.text())\r\n print(b.fittingParam)\r\n self.mri_window.on_fittingParams_rbtn_toggled( str(b.fittingParam))\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass ApplicationWindow(QtWidgets.QMainWindow):\r\n def __init__(self, params):\r\n\r\n self.params = params\r\n\r\n imageData = T2imageData()\r\n\r\n print(\"imageData.fittingParam:\",imageData.fittingParam)\r\n\r\n npts = 256*100\r\n\r\n iii = np.random.permutation(np.arange(255*255))[:npts]\r\n ddd = np.random.randn(npts)*100+500\r\n\r\n data_df = pd.DataFrame({'iii': iii, 'ddd':ddd})\r\n\r\n super(ApplicationWindow, self).__init__()\r\n leftwindow = QtWidgets.QWidget()\r\n rightwindow = QtWidgets.QWidget()\r\n\r\n splitHwidget = QtWidgets.QSplitter(QtCore.Qt.Horizontal)\r\n\r\n\r\n\r\n #hlayout = QtWidgets.QHBoxLayout(self._main)\r\n hlayout = QtWidgets.QHBoxLayout(leftwindow)\r\n vlayout = QtWidgets.QVBoxLayout(rightwindow)\r\n\r\n\r\n\r\n\r\n mriplot_window = MRIPlotWidget(imageData=imageData)\r\n rbtns_window = radiobuttons_fitWidget(mri_window=mriplot_window)\r\n t2plot_window = T2PlotWidget( self.params, showToolbar=False)\r\n h1_window = PlotWidget( showToolbar=False)\r\n h2_window = HistogramPlotWidget(showToolbar=True)\r\n #hlayout.addWidget(mriplot_window)\r\n\r\n mriplot_window.register_PlotWidgets(t2plot_window, h1_window, h2_window)\r\n\r\n #vbox1_radiobuttons = QtWidgets.QVBoxLayout()\r\n\r\n# hbox.addLayout(vbox1_radiobuttons)\r\n# hbox.addLayout(vbox1_image)\r\n# hbox.addLayout(vbox2_image)\r\n\r\n hlayout.addWidget(rbtns_window)\r\n hlayout.addWidget(mriplot_window)\r\n vlayout.addWidget(t2plot_window)\r\n vlayout.addWidget(h1_window)\r\n vlayout.addWidget(h2_window)\r\n\r\n def func3(x, y):\r\n return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2 + y**2))\r\n\r\n\r\n # make these smaller to increase the resolution\r\n dx, dy = 0.05, 0.05\r\n\r\n x = np.arange(-3.0, 3.0, dx)\r\n y = np.arange(-3.0, 3.0, dy)\r\n X, Y = np.meshgrid(x, y)\r\n\r\n # when layering multiple images, the images need to have the same\r\n # extent. This does not mean they need to have the same shape, but\r\n # they both need to render to the same coordinate system determined by\r\n # xmin, xmax, ymin, ymax. Note if you use different interpolations\r\n # for the images their apparent extent could be different due to\r\n # interpolation edge effects\r\n\r\n extent = np.min(x), np.max(x), np.min(y), np.max(y)\r\n\r\n\r\n Z1 = np.add.outer(range(8), range(8)) % 2 # chessboard\r\n mriplot_window.return_ax().imshow(Z1, cmap=plt.cm.gray,\r\n interpolation='nearest', extent=extent)\r\n\r\n Z2 = func3(X, Y)\r\n\r\n mriplot_window.return_ax().imshow(Z2, cmap=plt.cm.viridis, alpha=.9,\r\n interpolation='bilinear', extent=extent)\r\n\r\n splitHwidget.addWidget(leftwindow)\r\n splitHwidget.addWidget(rightwindow )\r\n\r\n\r\n print(data_df.head())\r\n plot_image = np.zeros(255*255)\r\n plot_image[data_df['iii']] = data_df['ddd']\r\n\r\n h1_window.return_ax().imshow( plot_image.reshape((255,255)))\r\n h1_window.return_ax().set_xlabel('x')\r\n h1_window.return_ax().set_ylabel('y')\r\n\r\n\r\n h2_window.return_ax().hist(ddd, bins=100)\r\n h2_window.return_ax().set_xlabel('x')\r\n h2_window.return_ax().set_ylabel('y')\r\n\r\n\r\n self.setCentralWidget(splitHwidget)\r\n\r\n\r\n\r\n def zoom(self):\r\n self.histtoolbar.zoom()\r\n\r\n def ax_changed(self,ax):\r\n old_xlim, old_ylim = self.lim_dict[ax]\r\n print(\"old xlim\", old_xlim, \"ylim\", old_ylim)\r\n print(\"new xlim\", ax.get_xlim(), \"ylim\", ax.get_ylim())\r\n return np.all(old_xlim == ax.get_xlim()) and np.all(old_ylim == ax.get_ylim())\r\n\r\n def onrelease(self,event):\r\n print(\"Active Toolbar button:\",self.histtoolbar._active )\r\n print(\"plot release\")\r\n print(event)\r\n self.static_canvas.flush_events()\r\n\r\n changed_axes = [ax for ax in self.static_canvas.figure.axes if self.ax_changed(ax)]\r\n not_changed_axes = [ax for ax in self.static_canvas.figure.axes if not self.ax_changed(ax)]\r\n print(\"changed_axes\",changed_axes)\r\n print(\"not_changed_axes\",not_changed_axes)\r\n\r\n for ax in changed_axes:\r\n print(\"Changed xlim\", ax.get_xlim(), \"ylim\", ax.get_ylim())\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n epgt2fitparams = lm.Parameters()\r\n\r\n epgt2fitparams.add('T2fat', value = 180.0, min=0, max=5000, vary=False)\r\n epgt2fitparams.add('T2muscle', value = 35, min=0, max=100, vary=True )\r\n epgt2fitparams.add('Afat', value = 0.2, min=0, max=10, vary=True )\r\n epgt2fitparams.add('Amuscle', value = 0.8, min=0, max=10, vary=True )\r\n epgt2fitparams.add('T1fat', value = 365.0, vary=False)\r\n epgt2fitparams.add('T1muscle', value = 1400, vary=False)\r\n epgt2fitparams.add('echo', value = 10.0, vary=False)\r\n qapp = QtWidgets.QApplication(sys.argv)\r\n\r\n app = ApplicationWindow(epgt2fitparams)\r\n app.show()\r\n qapp.exec_()\r\n\r\n" }, { "alpha_fraction": 0.6065247654914856, "alphanum_fraction": 0.6313727498054504, "avg_line_length": 47.4277458190918, "blob_id": "9ef39ab62fdf150d9772148805051c7ee0cba70e", "content_id": "ef6b5b4659d40253b84d8f24d5a6f68d8dc5f30b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17104, "license_type": "permissive", "max_line_length": 158, "num_lines": 346, "path": "/epgT2paramsDialog.py", "repo_name": "EricHughesABC/T2EPGviewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\r\n# Form implementation generated from reading ui file 'epg_fit_parameters_dialog.ui'\r\n#\r\n# Created by: PyQt5 UI code generator 5.6\r\n#\r\n# WARNING! All changes made in this file will be lost!\r\n\r\nimport lmfit as lm\r\n\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\n\r\nclass EpgT2paramsDialog(object):\r\n\r\n def __init__(self, lmparams):\r\n\r\n self.lmparams = lmparams\r\n\r\n self.params = self.lmparams['epgt2fitparams']\r\n\r\n\r\n\r\n def setupEpgT2paramsDialog(self, Dialog):\r\n self.Dialog = Dialog\r\n Dialog.setObjectName(\"Dialog\")\r\n Dialog.resize(386, 284)\r\n self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)\r\n self.buttonBox.setGeometry(QtCore.QRect(60, 250, 321, 23))\r\n self.buttonBox.setOrientation(QtCore.Qt.Horizontal)\r\n self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)\r\n self.buttonBox.setObjectName(\"buttonBox\")\r\n self.widget = QtWidgets.QWidget(Dialog)\r\n self.widget.setGeometry(QtCore.QRect(20, 10, 361, 231))\r\n\r\n self.widget.setObjectName(\"widget\")\r\n self.gridLayout = QtWidgets.QGridLayout(self.widget)\r\n self.gridLayout.setContentsMargins(0, 0, 0, 0)\r\n\r\n self.gridLayout.setObjectName(\"gridLayout\")\r\n self.fatT1value = QtWidgets.QLineEdit(self.widget)\r\n self.fatT1value.setValidator(QtGui.QDoubleValidator())\r\n self.fatT1value.setObjectName(\"fatT1value\")\r\n self.gridLayout.addWidget(self.fatT1value, 7, 1, 1, 1)\r\n\r\n self.muscleFractionMax = QtWidgets.QLineEdit(self.widget)\r\n self.muscleFractionMax.setValidator(QtGui.QDoubleValidator())\r\n self.muscleFractionMax.setObjectName(\"muscleFractionMax\")\r\n self.gridLayout.addWidget(self.muscleFractionMax, 3, 3, 1, 1)\r\n\r\n self.optimizeMuscleFraction = QtWidgets.QCheckBox(self.widget)\r\n self.optimizeMuscleFraction.setText(\"\")\r\n self.optimizeMuscleFraction.setChecked(True)\r\n self.optimizeMuscleFraction.setObjectName(\"optimizeMuscleFraction\")\r\n self.gridLayout.addWidget(self.optimizeMuscleFraction, 3, 4, 1, 1)\r\n\r\n self.fatFractionMin = QtWidgets.QLineEdit(self.widget)\r\n self.fatFractionMin.setValidator(QtGui.QDoubleValidator())\r\n self.fatFractionMin.setObjectName(\"fatFractionMin\")\r\n self.gridLayout.addWidget(self.fatFractionMin, 4, 2, 1, 1)\r\n\r\n self.fatFractionMax = QtWidgets.QLineEdit(self.widget)\r\n self.fatFractionMax.setValidator(QtGui.QDoubleValidator())\r\n self.fatFractionMax.setObjectName(\"fatFractionMax\")\r\n self.gridLayout.addWidget(self.fatFractionMax, 4, 3, 1, 1)\r\n\r\n self.b1scaleMax = QtWidgets.QLineEdit(self.widget)\r\n self.b1scaleMax.setValidator(QtGui.QDoubleValidator())\r\n self.b1scaleMax.setObjectName(\"b1scaleMax\")\r\n self.gridLayout.addWidget(self.b1scaleMax, 5, 3, 1, 1)\r\n\r\n self.muscleFractionMin = QtWidgets.QLineEdit(self.widget)\r\n self.muscleFractionMin.setValidator(QtGui.QDoubleValidator())\r\n self.muscleFractionMin.setObjectName(\"muscleFractionMin\")\r\n self.gridLayout.addWidget(self.muscleFractionMin, 3, 2, 1, 1)\r\n\r\n self.b1scaleValue = QtWidgets.QLineEdit(self.widget)\r\n self.b1scaleValue.setValidator(QtGui.QDoubleValidator())\r\n self.b1scaleValue.setObjectName(\"b1scaleValue\")\r\n self.gridLayout.addWidget(self.b1scaleValue, 5, 1, 1, 1)\r\n\r\n self.b1scaleMin = QtWidgets.QLineEdit(self.widget)\r\n self.b1scaleMin.setValidator(QtGui.QDoubleValidator())\r\n self.b1scaleMin.setObjectName(\"b1scaleMin\")\r\n self.gridLayout.addWidget(self.b1scaleMin, 5, 2, 1, 1)\r\n\r\n self.fatFractionLabel = QtWidgets.QLabel(self.widget)\r\n self.fatFractionLabel.setObjectName(\"fatFractionLabel\")\r\n self.gridLayout.addWidget(self.fatFractionLabel, 4, 0, 1, 1)\r\n\r\n self.fatFractionValue = QtWidgets.QLineEdit(self.widget)\r\n self.fatFractionValue.setValidator(QtGui.QDoubleValidator())\r\n self.fatFractionValue.setObjectName(\"fatFractionValue\")\r\n self.gridLayout.addWidget(self.fatFractionValue, 4, 1, 1, 1)\r\n\r\n self.muscleT1label = QtWidgets.QLabel(self.widget)\r\n self.muscleT1label.setObjectName(\"muscleT1label\")\r\n self.gridLayout.addWidget(self.muscleT1label, 6, 0, 1, 1)\r\n\r\n self.fatT2min = QtWidgets.QLineEdit(self.widget)\r\n self.fatT2min.setValidator(QtGui.QDoubleValidator())\r\n self.fatT2min.setObjectName(\"fatT2min\")\r\n self.gridLayout.addWidget(self.fatT2min, 2, 2, 1, 1)\r\n\r\n self.maxHeadingLabel = QtWidgets.QLabel(self.widget)\r\n self.maxHeadingLabel.setObjectName(\"maxHeadingLabel\")\r\n self.gridLayout.addWidget(self.maxHeadingLabel, 0, 3, 1, 1)\r\n\r\n self.minHeadingLabel = QtWidgets.QLabel(self.widget)\r\n self.minHeadingLabel.setObjectName(\"minHeadingLabel\")\r\n self.gridLayout.addWidget(self.minHeadingLabel, 0, 2, 1, 1)\r\n\r\n self.valueHeadingLabel = QtWidgets.QLabel(self.widget)\r\n self.valueHeadingLabel.setObjectName(\"valueHeadingLabel\")\r\n self.gridLayout.addWidget(self.valueHeadingLabel, 0, 1, 1, 1)\r\n\r\n self.fatT2value = QtWidgets.QLineEdit(self.widget)\r\n self.fatT2value.setValidator(QtGui.QDoubleValidator())\r\n self.fatT2value.setObjectName(\"fatT2value\")\r\n self.gridLayout.addWidget(self.fatT2value, 2, 1, 1, 1)\r\n\r\n self.optimizeFatT2 = QtWidgets.QCheckBox(self.widget)\r\n self.optimizeFatT2.setText(\"\")\r\n self.optimizeFatT2.setChecked(False)\r\n self.optimizeFatT2.setObjectName(\"optimizeFatT2\")\r\n self.gridLayout.addWidget(self.optimizeFatT2, 2, 4, 1, 1)\r\n\r\n self.muscleT2value = QtWidgets.QLineEdit(self.widget)\r\n self.muscleT2value.setInputMethodHints(QtCore.Qt.ImhDigitsOnly|QtCore.Qt.ImhFormattedNumbersOnly)\r\n self.muscleT2value.setProperty(\"muscleValue\", 0.0)\r\n self.muscleT2value.setProperty(\"number\", 35.0)\r\n self.muscleT2value.setObjectName(\"muscleT2value\")\r\n self.gridLayout.addWidget(self.muscleT2value, 1, 1, 1, 1)\r\n\r\n self.fatT2label = QtWidgets.QLabel(self.widget)\r\n self.fatT2label.setObjectName(\"fatT2label\")\r\n self.gridLayout.addWidget(self.fatT2label, 2, 0, 1, 1)\r\n\r\n self.fatT2max = QtWidgets.QLineEdit(self.widget)\r\n self.fatT2max.setValidator(QtGui.QDoubleValidator())\r\n self.fatT2max.setObjectName(\"fatT2max\")\r\n self.gridLayout.addWidget(self.fatT2max, 2, 3, 1, 1)\r\n\r\n self.muscleT2max = QtWidgets.QLineEdit(self.widget)\r\n self.muscleT2max.setValidator(QtGui.QDoubleValidator())\r\n self.muscleT2max.setObjectName(\"muscleT2max\")\r\n self.gridLayout.addWidget(self.muscleT2max, 1, 3, 1, 1)\r\n\r\n self.opimizedHeadingLabel = QtWidgets.QLabel(self.widget)\r\n self.opimizedHeadingLabel.setObjectName(\"opimizedHeadingLabel\")\r\n self.gridLayout.addWidget(self.opimizedHeadingLabel, 0, 4, 1, 1)\r\n\r\n self.muscleT2label = QtWidgets.QLabel(self.widget)\r\n self.muscleT2label.setObjectName(\"muscleT2label\")\r\n self.gridLayout.addWidget(self.muscleT2label, 1, 0, 1, 1)\r\n\r\n self.muscleT2min = QtWidgets.QLineEdit(self.widget)\r\n self.muscleT2min.setInputMethodHints(QtCore.Qt.ImhFormattedNumbersOnly)\r\n self.muscleT2min.setObjectName(\"muscleT2min\")\r\n self.gridLayout.addWidget(self.muscleT2min, 1, 2, 1, 1)\r\n\r\n self.optimizeMuscleT2 = QtWidgets.QCheckBox(self.widget)\r\n self.optimizeMuscleT2.setText(\"\")\r\n self.optimizeMuscleT2.setChecked(True)\r\n self.optimizeMuscleT2.setObjectName(\"optimizeMuscleT2\")\r\n self.gridLayout.addWidget(self.optimizeMuscleT2, 1, 4, 1, 1)\r\n\r\n self.optimizeB1scale = QtWidgets.QCheckBox(self.widget)\r\n self.optimizeB1scale.setText(\"\")\r\n self.optimizeB1scale.setChecked(True)\r\n self.optimizeB1scale.setObjectName(\"optimizeB1scale\")\r\n self.gridLayout.addWidget(self.optimizeB1scale, 5, 4, 1, 1)\r\n\r\n self.optimizeFatFraction = QtWidgets.QCheckBox(self.widget)\r\n self.optimizeFatFraction.setText(\"\")\r\n self.optimizeFatFraction.setChecked(True)\r\n self.optimizeFatFraction.setObjectName(\"optimizeFatFraction\")\r\n self.gridLayout.addWidget(self.optimizeFatFraction, 4, 4, 1, 1)\r\n\r\n self.b1scaleLabel = QtWidgets.QLabel(self.widget)\r\n self.b1scaleLabel.setObjectName(\"b1scaleLabel\")\r\n self.gridLayout.addWidget(self.b1scaleLabel, 5, 0, 1, 1)\r\n\r\n self.muscleT1value = QtWidgets.QLineEdit(self.widget)\r\n self.muscleT1value.setObjectName(\"muscleT1value\")\r\n self.gridLayout.addWidget(self.muscleT1value, 6, 1, 1, 1)\r\n\r\n self.T2echoValue = QtWidgets.QLineEdit(self.widget)\r\n self.T2echoValue.setValidator(QtGui.QDoubleValidator())\r\n self.T2echoValue.setObjectName(\"T2echoValue\")\r\n self.gridLayout.addWidget(self.T2echoValue, 8, 1, 1, 1)\r\n\r\n self.muscleFractionValue = QtWidgets.QLineEdit(self.widget)\r\n self.muscleFractionValue.setValidator(QtGui.QDoubleValidator())\r\n self.muscleFractionValue.setObjectName(\"muscleFractionValue\")\r\n self.gridLayout.addWidget(self.muscleFractionValue, 3, 1, 1, 1)\r\n\r\n self.muscleFractionLabel = QtWidgets.QLabel(self.widget)\r\n self.muscleFractionLabel.setObjectName(\"muscleFractionLabel\")\r\n self.gridLayout.addWidget(self.muscleFractionLabel, 3, 0, 1, 1)\r\n\r\n self.label = QtWidgets.QLabel(self.widget)\r\n self.label.setObjectName(\"label\")\r\n self.gridLayout.addWidget(self.label, 8, 0, 1, 1)\r\n\r\n self.fatT1label = QtWidgets.QLabel(self.widget)\r\n self.fatT1label.setObjectName(\"fatT1label\")\r\n self.gridLayout.addWidget(self.fatT1label, 7, 0, 1, 1)\r\n\r\n\r\n\r\n self.retranslateUi(Dialog)\r\n self.buttonBox.accepted.connect(self.dialog_ok_clicked)\r\n self.buttonBox.rejected.connect(Dialog.reject)\r\n QtCore.QMetaObject.connectSlotsByName(Dialog)\r\n\r\n def retranslateUi(self, Dialog):\r\n _translate = QtCore.QCoreApplication.translate\r\n Dialog.setWindowTitle(_translate(\"Dialog\", \"EPG\"))\r\n self.fatT1value.setText(_translate(\"Dialog\", \"1450\"))\r\n self.muscleFractionMax.setText(_translate(\"Dialog\", \"10\"))\r\n self.fatFractionMin.setText(_translate(\"Dialog\", \"0\"))\r\n self.fatFractionMax.setText(_translate(\"Dialog\", \"10\"))\r\n self.b1scaleMax.setText(_translate(\"Dialog\", \"2\"))\r\n self.muscleFractionMin.setText(_translate(\"Dialog\", \"0\"))\r\n self.b1scaleValue.setText(_translate(\"Dialog\", \"1\"))\r\n self.b1scaleMin.setText(_translate(\"Dialog\", \"0\"))\r\n self.fatFractionLabel.setText(_translate(\"Dialog\", \"Fat Fraction\"))\r\n self.fatFractionValue.setText(_translate(\"Dialog\", \".3\"))\r\n self.muscleT1label.setText(_translate(\"Dialog\", \"<html><head/><body><p>Muscle T<span style=\\\" vertical-align:sub;\\\">1</span> (ms)</p></body></html>\"))\r\n self.fatT2min.setText(_translate(\"Dialog\", \"0\"))\r\n self.maxHeadingLabel.setText(_translate(\"Dialog\", \"maximum\"))\r\n self.minHeadingLabel.setText(_translate(\"Dialog\", \"minimum\"))\r\n self.valueHeadingLabel.setText(_translate(\"Dialog\", \"value\"))\r\n self.fatT2value.setText(_translate(\"Dialog\", \"200\"))\r\n self.muscleT2value.setText(_translate(\"Dialog\", \"35\"))\r\n self.fatT2label.setText(_translate(\"Dialog\", \"<html><head/><body><p>Fat T<span style=\\\" vertical-align:sub;\\\">2</span> (ms)</p></body></html>\"))\r\n self.fatT2max.setText(_translate(\"Dialog\", \"2000\"))\r\n self.muscleT2max.setText(_translate(\"Dialog\", \"150\"))\r\n self.opimizedHeadingLabel.setText(_translate(\"Dialog\", \"optimized\"))\r\n self.muscleT2label.setText(_translate(\"Dialog\", \"<html><head/><body><p>Muscle T<span style=\\\" vertical-align:sub;\\\">2</span> (ms)</p></body></html>\"))\r\n self.muscleT2min.setText(_translate(\"Dialog\", \"0\"))\r\n self.b1scaleLabel.setText(_translate(\"Dialog\", \"B<sub>1</sub> scale\"))\r\n self.muscleT1value.setText(_translate(\"Dialog\", \"500\"))\r\n self.T2echoValue.setText(_translate(\"Dialog\", \"10\"))\r\n self.muscleFractionValue.setText(_translate(\"Dialog\", \"0.7\"))\r\n self.muscleFractionLabel.setText(_translate(\"Dialog\", \"Muscle Fraction\"))\r\n self.label.setText(_translate(\"Dialog\", \"<html><head/><body><p>T<span style=\\\" vertical-align:sub;\\\">2</span> Echo (ms)</p></body></html>\"))\r\n self.fatT1label.setText(_translate(\"Dialog\", \"<html><head/><body><p>Fat T<span style=\\\" vertical-align:sub;\\\">1</span> (ms)</p></body></html>\"))\r\n\r\n def dialog_ok_clicked(self):\r\n print(\"dialog_ok_clicked\")\r\n self.Dialog.setResult(1)\r\n worked =self.get_fitparameters()\r\n if worked:\r\n self.params.pretty_print()\r\n self.Dialog.accept()\r\n\r\n\r\n\r\n def get_fitparameters( self ):\r\n\r\n print(\"self.optimizeFatFraction.isChecked()\", self.optimizeFatFraction.isChecked() )\r\n\r\n #epgt2fitparams = lm.Parameters()\r\n worked = True\r\n try:\r\n\r\n self.params.add(name='T2muscle', value = float(self.muscleT2value.text()),\r\n min = float(self.muscleT2min.text()),\r\n max = float(self.muscleT2max.text()),\r\n vary = self.optimizeMuscleT2.isChecked())\r\n\r\n self.params.add(name='T2fat', value = float(self.fatT2value.text()),\r\n min = float(self.fatT2min.text()),\r\n max = float(self.fatT2max.text()),\r\n vary = self.optimizeFatT2.isChecked())\r\n\r\n self.params.add(name='Amuscle', value = float(self.muscleFractionValue.text()),\r\n min = float(self.muscleFractionMin.text()),\r\n max = float(self.muscleFractionMax.text()),\r\n vary = self.optimizeMuscleFraction.isChecked())\r\n\r\n self.params.add(name='Afat', value = float(self.fatFractionValue.text()),\r\n min = float(self.fatFractionMin.text()),\r\n max = float(self.fatFractionMax.text()),\r\n vary = self.optimizeFatFraction.isChecked())\r\n\r\n self.params.add(name='B1scale', value = float(self.b1scaleValue.text()),\r\n min = float(self.b1scaleMin.text()),\r\n max = float(self.b1scaleMax.text()),\r\n vary = self.optimizeB1scale.isChecked())\r\n\r\n self.params.add(name='T1muscle', value = float(self.muscleT1value.text()),\r\n vary = False)\r\n\r\n self.params.add(name='T1fat', value = float(self.fatT1value.text()),\r\n vary = False)\r\n\r\n self.params.add(name='echo', value = float(self.T2echoValue.text()),\r\n vary = False)\r\n\r\n buttonsChecked = [not self.optimizeFatFraction.isChecked(),\r\n not self.optimizeMuscleFraction.isChecked(),\r\n not self.optimizeMuscleT2.isChecked(),\r\n not self.optimizeFatT2.isChecked(),\r\n not self.optimizeB1scale.isChecked()]\r\n\r\n print(buttonsChecked)\r\n\r\n if all(buttonsChecked):\r\n worked=False\r\n\r\n self.lmparams['epgt2fitparams'] = self.params\r\n except:\r\n\r\n worked = False\r\n return worked\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import sys\r\n app = QtWidgets.QApplication(sys.argv)\r\n Dialog = QtWidgets.QDialog()\r\n Dialog.setModal(False)\r\n\r\n lmparams = {}\r\n epgt2fitparams = lm.Parameters()\r\n\r\n epgt2fitparams.add('T2fat', value = 180.0, min=0, max=5000, vary=False)\r\n epgt2fitparams.add('T2muscle', value = 35, min=0, max=100, vary=True )\r\n epgt2fitparams.add('Afat', value = 0.01, min=0, max=10, vary=True )\r\n epgt2fitparams.add('Amuscle', value = 0.1, min=0, max=10, vary=True )\r\n epgt2fitparams.add('T1fat', value = 365.0, vary=False)\r\n epgt2fitparams.add('T1muscle', value = 1400, vary=False)\r\n epgt2fitparams.add('echo', value = 10.0, vary=False)\r\n epgt2fitparams.add('B1scale', value = 1.0, min=0, max=2, vary=True)\r\n\r\n lmparams['epgt2fitparams']=epgt2fitparams\r\n\r\n ui = EpgT2paramsDialog(lmparams)\r\n ui.setupEpgT2paramsDialog(Dialog)\r\n rt=Dialog.open()\r\n print(\"Dialog.result() =\",Dialog.result())\r\n\r\n #print( \"get_fitparameters(ui).items()\", ui.get_fitparameters().items())\r\n sys.exit(app.exec_())\r\n\r\n" }, { "alpha_fraction": 0.5726163983345032, "alphanum_fraction": 0.5815779566764832, "avg_line_length": 33.709571838378906, "blob_id": "d8b9aad8840f2e97f24c143787191e2dd7c6ddae", "content_id": "f43d881cc97e6f7c758022e92e89a68a0db539d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10824, "license_type": "permissive", "max_line_length": 124, "num_lines": 303, "path": "/mriplotwidget.py", "repo_name": "EricHughesABC/T2EPGviewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 17 14:34:43 2019\r\n\r\n@author: neh69\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib\r\n\r\nfrom matplotlib import pyplot as plt\r\n#import seaborn as sns\r\n\r\nfrom matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5\r\n#import seaborn as sns\r\n\r\nif is_pyqt5():\r\n print(\"pyqt5\")\r\n from matplotlib.backends.backend_qt5agg import (\r\n FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\r\nelse:\r\n print(\"pyqt4\")\r\n from matplotlib.backends.backend_qt4agg import (\r\n FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\r\n#from matplotlib.figure import Figure\r\n\r\nimport mplcursors\r\n\r\n#from ImageData import T2imageData\r\nparameterNames ={'T2m': [ 'T$_{2m}$ [ms]','{}, T$_{{2m}}$ = {:.1f} [ms]' ],\r\n 'Am100': [ 'A$_{m}$ [%]', '{}, A$_{{m}}$ = {:.1f} [%]' ],\r\n 'Af100': [ 'A$_{f}$ [%]', '{}, A$_{{f}}$ = {:.1f} [%]'],\r\n 'B1': [ 'B$_{1}$ [-]', '{}, B$_{{1}}$ = {:.1f} [-]'],\r\n 'fatPC': [ 'fat [%]', '{}, fat = {:.1f} [%]']\r\n }\r\n\r\nclass MRIPlotWidget(QtWidgets.QWidget):\r\n\r\n#class PlotWidget(QtWidgets.QWidget):\r\n\r\n def __init__(self, parent=None, showToolbar=True, imageData=None):\r\n\r\n super().__init__(parent)\r\n self.fig, self.ax = plt.subplots()\r\n# fig =Figure(figsize=(3, 5))\r\n self.fig.set_tight_layout(True)\r\n self.plot_canvas = FigureCanvas(self.fig)\r\n# self.ax = self.fig.add_subplot(111)\r\n\r\n# mplcursors.cursor(fig,hover=True)\r\n\r\n self.layout = QtWidgets.QVBoxLayout(self)\r\n\r\n# def __init__( self, parent=None, showToolbar=True, imageData=None):\r\n\r\n\r\n self.axesList = []\r\n self.imageData = imageData\r\n\r\n\r\n\r\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\r\n\r\n\r\n self.toggleImage = QtWidgets.QRadioButton(\"Hide background Image\")\r\n self.toggleImage.toggled.connect(lambda: self.toggleImageChanged(self.toggleImage))\r\n\r\n self.toggleImage.isChecked()\r\n\r\n self.layout.addWidget(self.toggleImage)\r\n self.toggleImage.setSizePolicy(sizePolicy)\r\n\r\n self.sliceLabel = QtWidgets.QLabel(\"slices\")\r\n self.layout.addWidget(self.sliceLabel)\r\n self.sliceLabel.setSizePolicy(sizePolicy)\r\n\r\n self.slicesSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal)\r\n self.slicesSlider.setMinimum(0)\r\n self.slicesSlider.setMaximum(4)\r\n self.slicesSlider.setValue(0)\r\n self.slicesSlider.setTickPosition(QtWidgets.QSlider.TicksBelow)\r\n self.slicesSlider.setTickInterval(1)\r\n self.slicesSlider.valueChanged.connect(self.valuechangedSlider)\r\n\r\n\r\n self.slicesSlider.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed))\r\n self.layout.addWidget(self.slicesSlider)\r\n\r\n\r\n self.echoesLabel = QtWidgets.QLabel(\"echoes\")\r\n self.echoesLabel.setSizePolicy(sizePolicy)\r\n self.layout.addWidget(self.echoesLabel)\r\n\r\n self.echoesSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal)\r\n self.echoesSlider.setMinimum(0)\r\n self.echoesSlider.setMaximum(16)\r\n self.echoesSlider.setValue(0)\r\n self.echoesSlider.setTickPosition(QtWidgets.QSlider.TicksBelow)\r\n self.echoesSlider.setTickInterval(1)\r\n self.echoesSlider.valueChanged.connect(self.valuechangedSlider)\r\n\r\n self.echoesSlider.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed))\r\n self.layout.addWidget(self.echoesSlider)\r\n\r\n self.layout.addWidget(self.plot_canvas)\r\n\r\n if showToolbar:\r\n self.toolbar = NavigationToolbar(self.plot_canvas, self)\r\n self.layout.addWidget(self.toolbar)\r\n\r\n\r\n self.setSizePolicy(QtWidgets.QSizePolicy.Expanding,\r\n QtWidgets.QSizePolicy.Expanding)\r\n self.updateGeometry()\r\n\r\n self.plot_canvas.mpl_connect('button_press_event', self.onclick)\r\n# self.plot_canvas.mpl_connect(\"motion_notify_event\", self.onhover)\r\n\r\n self.ax.imshow(matplotlib.image.imread('vision.png')[:,:,0])\r\n# self.canvas.figure.axes\r\n# self.mpl_cursor = mplcursors.cursor(self.plot_canvas.figure.axes,hover=True)\r\n self.ax.grid(False)\r\n\r\n\r\n def valuechangedSlider(self):\r\n slice_ = self.slicesSlider.value()\r\n echo = self.echoesSlider.value()\r\n\r\n self.imageData.currentSlice = slice_\r\n self.imageData.currentEcho = echo\r\n print(\"slicesSlider Value =\", slice_, \"echoesSlider Value =\", echo )\r\n if isinstance(self.imageData.ImageDataT2, np.ndarray):\r\n print(\"updating image slice\")\r\n if self.toggleImage.isChecked():\r\n self.imageData.mriSliceIMG *= 0.0\r\n else:\r\n self.imageData.mriSiceIMG=self.imageData.ImageDataT2[:,:,slice_,echo].copy()\r\n\r\n self.imageData.overlayRoisOnImage(slice_+1, self.imageData.fittingParam)\r\n self.update_plot(self.imageData.mriSiceIMG, self.imageData.maskedROIs.reshape(self.imageData.mriSiceIMG.shape))\r\n\r\n self.histPlotWidget.update_plot([slice_+1,self.imageData.T2slices,self.imageData.dixonSlices],\r\n [self.imageData.t2_data_summary_df,self.imageData.dixon_data_summary_df],\r\n self.imageData.fittingParam)\r\n\r\n self.barPlotWidget.update_plot([slice_+1,self.imageData.T2slices,self.imageData.dixonSlices],\r\n [self.imageData.t2_data_summary_df,self.imageData.dixon_data_summary_df],\r\n self.imageData.fittingParam)\r\n else:\r\n print(\"No images to update\")\r\n\r\n\r\n\r\n def on_fittingParams_rbtn_toggled(self, fittingParam):\r\n\r\n# rb = self.fittingParams_rbtn.sender()\r\n print(fittingParam)\r\n self.imageData.fittingParam = fittingParam\r\n self.valuechangedSlider()\r\n\r\n\r\n def register_PlotWidgets(self, T2PlotWidget, histPlotWidget,\r\n barPlotWidget, radioButtonsWidget):\r\n\r\n self.T2PlotWidget = T2PlotWidget\r\n self.histPlotWidget = histPlotWidget\r\n self.barPlotWidget = barPlotWidget\r\n self.radioButtonsWidget = radioButtonsWidget\r\n\r\n\r\n# def onhover(self,event):\r\n#\r\n# if event.inaxes:\r\n#\r\n# xcoord = int(round(event.xdata))\r\n# ycoord = int(round(event.ydata))\r\n#\r\n# print('on hover, ', xcoord, ycoord)\r\n\r\n def onclick(self,event):\r\n\r\n xcoord = int(round(event.xdata))\r\n ycoord = int(round(event.ydata))\r\n\r\n print(\"MRI Plot window On Click\")\r\n\r\n print('ycoord =', ycoord)\r\n\r\n print(type(self.imageData.ImageDataT2))\r\n\r\n if type(self.imageData.ImageDataT2) != type(None):\r\n\r\n image_shape = self.imageData.ImageDataT2.shape\r\n\r\n print(image_shape[0],image_shape[0]-ycoord, ycoord)\r\n\r\n t2data = self.imageData.ImageDataT2[ycoord,xcoord,int(self.slicesSlider.value()),:]\r\n\r\n self.T2PlotWidget.update_plot( xcoord, ycoord, t2data)\r\n\r\n\r\n\r\n\r\n def update_plot(self, img, maskedROIs):\r\n\r\n self.ax.cla()\r\n self.ax.imshow(img,cmap=plt.cm.gray,\r\n interpolation='nearest')\r\n\r\n print(\"maskedROIs.shape\", maskedROIs.shape)\r\n print(\"img.shape\", img.shape)\r\n\r\n print(\"maskedROIs.max()\",maskedROIs.max())\r\n\r\n if maskedROIs.max() > 0:\r\n\r\n self.ax.imshow(maskedROIs.reshape(img.shape),\r\n cmap=plt.cm.jet, alpha=.5,\r\n interpolation='bilinear')\r\n\r\n mpl_cursor = mplcursors.cursor(self.plot_canvas.figure.axes,hover=True)\r\n\r\n @mpl_cursor.connect(\"add\")\r\n def _(sel):\r\n\r\n ann = sel.annotation\r\n ttt = ann.get_text()\r\n xc,yc, zl = [s.split('=') for s in ttt.splitlines()]\r\n\r\n x = round(float(xc[1]))\r\n y = round(float(yc[1]))\r\n\r\n print(\"x\",x, \"y\",y)\r\n\r\n nrows,ncols = img.shape\r\n cslice=self.imageData.currentSlice\r\n fitParam = self.imageData.fittingParam\r\n\r\n print(\"cslice\",cslice, \"nrows\", nrows, \"ncols\")\r\n print(\"fitParam\",fitParam)\r\n\r\n ### figure out which data set to use\r\n \r\n \r\n slice_df = None\r\n \r\n if fitParam in self.imageData.t2_data_summary_df.columns:\r\n print(fitParam, \"T2 dataFrame chosen\")\r\n data_df = self.imageData.t2_data_summary_df\r\n slice_df = data_df[data_df.slice==cslice+1]\r\n elif fitParam in self.imageData.dixon_data_summary_df.columns:\r\n print(fitParam, \"Dixon dataFrame chosen\")\r\n data_df = self.imageData.dixon_data_summary_df\r\n if cslice+1 in self.imageData.T2slices:\r\n dixonSliceIndex = self.imageData.dixonSlices[self.imageData.T2slices.index(cslice+1)]\r\n slice_df = data_df[data_df.slice==dixonSliceIndex]\r\n else:\r\n slice_df = data_df[data_df.slice==cslice]\r\n\r\n\r\n\r\n ### return current slice\r\n\r\n# slice_df = data_df[data_df.slice==cslice+1]\r\n \r\n roiList = []\r\n valueList=[]\r\n \r\n \r\n if not isinstance(slice_df, type(None)):\r\n print(\"type(slice_df)\",type(slice_df))\r\n \r\n print(\"slice_df.shape\",slice_df.shape)\r\n \r\n roiList = slice_df[slice_df['pixel_index']==y*ncols+x]['roi'].values\r\n valueList = slice_df[slice_df['pixel_index']==y*ncols+x][fitParam].values\r\n \r\n print(\"roiList\", roiList)\r\n print(\"valueList\",valueList)\r\n \r\n fitParamLabel = parameterNames[fitParam][1]\r\n \r\n if len(roiList)>0:\r\n roi=roiList[0]\r\n value=valueList[0]\r\n ann.set_text(fitParamLabel.format( roi, value))\r\n else:\r\n ann.set_text(\"x = {:d}\\ny = {:d}\".format( x, y ))\r\n\r\n self.ax.grid(False)\r\n\r\n self.plot_canvas.draw()\r\n\r\n\r\n def toggleImageChanged(self,b1):\r\n\r\n print(\"Entered toggleImageChanged\")\r\n if not isinstance(self.imageData.mriSliceIMG, type(None) ):\r\n if self.toggleImage.isChecked():\r\n print(\"Clear background image\")\r\n self.update_plot(np.zeros((self.imageData.mriSliceIMG.shape)),\r\n self.imageData.maskedROIs.reshape((self.imageData.mriSliceIMG.shape)))\r\n else:\r\n self.valuechangedSlider()\r\n\r\n\r\n" }, { "alpha_fraction": 0.6030253767967224, "alphanum_fraction": 0.6330062747001648, "avg_line_length": 32.59434127807617, "blob_id": "72a4df0fa6d358a6f63bcde63b9dc0e56c315287", "content_id": "b6db4db6202ab3eeadb277d121b17138be6cee57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7338, "license_type": "permissive", "max_line_length": 161, "num_lines": 212, "path": "/simple_pandas_plot.py", "repo_name": "EricHughesABC/T2EPGviewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 20 10:29:38 2017\r\n\r\n@author: neh69\r\n\"\"\"\r\nimport os\r\nimport sys\r\nimport numpy as np\r\nimport pandas as pd\r\nimport lmfit as lm\r\n\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\nfrom PyQt5 import QtCore, QtWidgets\r\n\r\n\r\nimport visionplot_widgets\r\nimport mriplotwidget\r\n\r\n\r\nfrom ImageData import T2imageData\r\n\r\n\r\n\r\ndef openStudyDir():\r\n dlg = QtWidgets.QFileDialog()\r\n returned_data = dlg.getExistingDirectory(None, \"Study Directory\", \"\")\r\n print(\"openStudyDir\\n\",returned_data, type(returned_data))\r\n\r\n# tree_window.setRootIndex(tree_window.model.index(returned_data))\r\n\r\n\r\n\r\ndef openNiftiAnalyzeFile():\r\n dlg = QtWidgets.QFileDialog()\r\n returned_data = dlg.getOpenFileName(None, \"MRI data nifti/analyze\", procDataDirPath, \"nii files (*.nii);;analyze files (*.img);;All files (*)\")\r\n print(returned_data)\r\n\r\n\r\ndef getH5file():\r\n dlg = QtWidgets.QFileDialog()\r\n returned_data = dlg.getOpenFileName(None, \"select results file\", procDataDirPath, \"CSV files (*.csv);;All files (*)\")\r\n pathandfilename = returned_data[0]\r\n\r\n #self.hd5_store = pd.HDFStore(pathandfilename)\r\n\r\n\r\n if len(pathandfilename) > 0:\r\n ### attempt to extract details from data\r\n print(pathandfilename)\r\n imageData.readin_alldata_from_results_filename( os.path.abspath(pathandfilename))\r\n\r\n if imageData.read_T2_img_hdr_files():\r\n\r\n print(\"just before read_T2_data()\")\r\n\r\n if imageData.read_T2_data():\r\n\r\n imageData.read_Dixon_data()\r\n\r\n print(\"just after read_T2_data()\")\r\n\r\n mainWindow.setWindowTitle(imageData.T2resultsFilenameAndPath)\r\n\r\n #### Update image displayed in window\r\n imageData.overlayRoisOnImage(0, imageData.fittingParam)\r\n# mri_window.update_plot(imageData.img1)\r\n mri_window.update_plot(imageData.mriSliceIMG, imageData.maskedROIs)\r\n print(\"type(imageData.ImageDataT2)\",type(imageData.ImageDataT2))\r\n\r\n hist_window.update_plot([1,imageData.T2slices,imageData.dixonSlices], [imageData.t2_data_summary_df, imageData.dixon_data_summary_df], \"T2m\")\r\n bar_window.update_plot([1,imageData.T2slices,imageData.dixonSlices], [imageData.t2_data_summary_df, imageData.dixon_data_summary_df], \"T2m\")\r\n\r\n #### set min max on sliders\r\n\r\n mri_window.slicesSlider.setMinimum(0)\r\n mri_window.slicesSlider.setMaximum(imageData.numSlicesT2-1)\r\n mri_window.slicesSlider.setValue(0)\r\n\r\n mri_window.echoesSlider.setMinimum(0)\r\n mri_window.echoesSlider.setMaximum(imageData.numEchoesT2-1)\r\n mri_window.slicesSlider.setValue(0)\r\n else:\r\n print(imageData.t2_image_hdr_pathfilename, \" not found\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef fileQuit(self):\r\n self.close()\r\n\r\ndef closeEvent(self, ce):\r\n self.fileQuit()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n\r\n lmparams = {}\r\n\r\n epgt2fitparams = lm.Parameters()\r\n azzt2fitparams = lm.Parameters()\r\n\r\n epgt2fitparams.add('T2fat', value = 180.0, min=0, max=5000, vary=False)\r\n epgt2fitparams.add('T2muscle', value = 35, min=0, max=100, vary=True )\r\n epgt2fitparams.add('Afat', value = 0.20, min=0, max=10, vary=True )\r\n epgt2fitparams.add('Amuscle', value = 0.80, min=0, max=10, vary=True )\r\n epgt2fitparams.add('T1fat', value = 365.0, vary=False)\r\n epgt2fitparams.add('T1muscle', value = 1400, vary=False)\r\n epgt2fitparams.add('echo', value = 10.0, vary=False)\r\n epgt2fitparams.add('B1scale', value = 1.0, min=0, max=2, vary=True )\r\n\r\n\r\n azzt2fitparams.add_many(('Afat', 60.0, True, 0, 250, None),\r\n ('Amuscle', 40.0, True, 0, 250, None),\r\n ('T2muscle', 40.0, True, 0, 100, None),\r\n ('c_l', 0.55, False, 0, 2000, None),\r\n ('c_s', 0.45, False, 0, 2000, None),\r\n ('t2_fl', 250.0, False, 0, 2000, None),\r\n ('t2_fs', 43.0, False, 0, 2000, None),\r\n ('echo', 10.0, False, 0, 2000, None))\r\n\r\n\r\n lmparams['epgt2fitparams'] = epgt2fitparams\r\n lmparams['azzt2fitparams'] = azzt2fitparams\r\n\r\n params=azzt2fitparams\r\n\r\n matplotlib.use('Qt5Agg')\r\n plt.style.context('seaborn-colorblind')\r\n sns.set(font_scale = 0.6)\r\n\r\n# sns.set_palette(\"pastel\")\r\n\r\n procDataDirPath = r\"/home/eric/Documents/projects/programming/2019/mri_progs/T2EPGviewer/studyData/testStudy/HC-001/sess-1/upperleg/T2/results/muscle/AzzEPG\"\r\n\r\n\r\n progname = os.path.basename(sys.argv[0])\r\n qApp = QtWidgets.QApplication(sys.argv)\r\n imageData = T2imageData()\r\n\r\n print(\"imageData.fittingParam:\",imageData.fittingParam)\r\n\r\n mainWindow = QtWidgets.QMainWindow()\r\n\r\n mainWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose)\r\n\r\n mainWindow.setWindowTitle(\"application main window\")\r\n\r\n file_menu = QtWidgets.QMenu('&File', mainWindow)\r\n\r\n# file_menu.addAction(\"&Open study Directory\", openStudyDir)\r\n file_menu.addAction('&Choose Study Results File', getH5file, QtCore.Qt.CTRL + QtCore.Qt.Key_H)\r\n# file_menu.addAction('&Open nifti/analyze image File', openNiftiAnalyzeFile )\r\n# file_menu.addAction('&Choose Rois', imageData.getRoiFiles, QtCore.Qt.CTRL + QtCore.Qt.Key_R)\r\n\r\n# file_menu.addAction('&Quit', fileQuit, QtCore.Qt.CTRL + QtCore.Qt.Key_Q)\r\n\r\n mainWindow.menuBar().addMenu(file_menu)\r\n\r\n main_widget = QtWidgets.QWidget(mainWindow)\r\n\r\n mainlayout = QtWidgets.QHBoxLayout(main_widget)\r\n # mainWindow.setCentralWidget(main_widget)\r\n\r\n# plot_window1 = mri_widget(main_widget)\r\n\r\n npts = 256*100\r\n\r\n iii = np.random.permutation(np.arange(255*255))[:npts]\r\n ddd = np.random.randn(npts)*100+500\r\n data_df = pd.DataFrame({'iii': iii, 'ddd':ddd})\r\n\r\n\r\n leftwindow = QtWidgets.QWidget()\r\n rightwindow = QtWidgets.QWidget()\r\n\r\n splitHwidget = QtWidgets.QSplitter(QtCore.Qt.Horizontal)\r\n\r\n hlayout = QtWidgets.QHBoxLayout(leftwindow)\r\n vlayout = QtWidgets.QVBoxLayout(rightwindow)\r\n\r\n mri_window = mriplotwidget.MRIPlotWidget( imageData=imageData)\r\n\r\n rbtns_window = visionplot_widgets.radiobuttons_fitWidget(mri_window=mri_window)\r\n t2plot_window = visionplot_widgets.T2PlotWidget( lmparams, showToolbar=False)\r\n bar_window = visionplot_widgets.BarPlotWidget( showToolbar=False, data_df=data_df, image_size=256)\r\n hist_window = visionplot_widgets.HistogramPlotWidget( mri_plot=mri_window, showToolbar=True,data_df=data_df, image_size=256)\r\n\r\n mainlayout.addWidget(splitHwidget)\r\n hlayout.addWidget(rbtns_window)\r\n hlayout.addWidget(mri_window)\r\n vlayout.addWidget(t2plot_window)\r\n vlayout.addWidget(bar_window)\r\n vlayout.addWidget(hist_window)\r\n\r\n splitHwidget.addWidget(leftwindow)\r\n splitHwidget.addWidget(rightwindow )\r\n\r\n mri_window.register_PlotWidgets(t2plot_window, bar_window, hist_window, rbtns_window)\r\n\r\n main_widget.setFocus()\r\n mainWindow.setCentralWidget(main_widget)\r\n\r\n mainWindow.show()\r\n sys.exit(qApp.exec_())\r\n\r\n\r\n" }, { "alpha_fraction": 0.55753093957901, "alphanum_fraction": 0.5704736113548279, "avg_line_length": 35.482666015625, "blob_id": "06bc687239ae760f3109c0cf7c32b3a11d3f5c40", "content_id": "8a0ccf44ce01ac33499e2b86cd221ac3fc3d7898", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14062, "license_type": "permissive", "max_line_length": 124, "num_lines": 375, "path": "/ImageData.py", "repo_name": "EricHughesABC/T2EPGviewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 6 14:55:05 2018\r\n\r\n@author: ERIC\r\n\"\"\"\r\nimport os\r\nimport numpy as np\r\nimport pandas as pd\r\nimport nibabel\r\n\r\nclass T2imageData():\r\n\r\n def __init__(self):\r\n\r\n self.currentSlice = None\r\n self.currentEcho = None\r\n\r\n self.T2imagesDirpath = None\r\n self.dixonImagesDirpath = None\r\n self.dixonResultsDirpath = None\r\n self.T2resultsDirpath = None\r\n\r\n self.root = None\r\n\r\n self.studyName = None\r\n self.subject = None\r\n self.session = None\r\n self.imagedRegion = None\r\n self.protocol = None\r\n self.results = None\r\n self.roiType = None\r\n self.fitModel = None\r\n\r\n self.imagedRegionType = self.roiType\r\n\r\n self.T2imageType = None\r\n self.T2MRIimageFilenameAndPath = \"\"\r\n\r\n self.dixonImageType = None\r\n self.dixonMRIimageFilenameAndPath = \"\"\r\n\r\n self.T2resultsFilenameAndPath = \"\"\r\n self.dixonResultsFilenameAndPath = \"\"\r\n\r\n self.fittingParam = \"T2m\"\r\n\r\n self.numRowsT2 = None\r\n self.numColsT2 = None\r\n self.numSlicesT2 = None\r\n self.numEchoesT2 = None\r\n\r\n self.dixonSlices = None\r\n self.T2slices = None\r\n\r\n self.ImageDataT2 = None\r\n self.mriSliceIMG = None\r\n \r\n self.t2_data_summary_df = None\r\n self.dixon_data_summary_df = None\r\n \r\n\r\n\r\n\r\n def readin_alldata_from_results_filename(self, fn):\r\n\r\n print(\"inside readin_alldata_from_results_filename\")\r\n\r\n self.set_dataDir_and_results_filenames(fn)\r\n self.set_T2imageData_filename_and_type()\r\n self.set_dixonImageData_filename_and_type()\r\n\r\n print(\"T2resultsDirpath :: \",self.T2resultsDirpath)\r\n print(\"dixonResultsDirpath :: \", self.dixonResultsDirpath)\r\n print(\"T2imagesDirpath :: \", self.T2imagesDirpath)\r\n print(\"dixonImagesDirpath :: \", self.dixonImagesDirpath)\r\n print(\"T2imageType :: \", self.T2imageType)\r\n print(\"T2MRIimageFilenameAndPath :: \", self.T2MRIimageFilenameAndPath)\r\n print(\"dixonImageType :: \", self.dixonImageType)\r\n print(\"dixonMRIimageFilenameAndPath ::\", self.dixonMRIimageFilenameAndPath)\r\n print(\"T2resultsFilenameAndPath :: \", self.T2resultsFilenameAndPath)\r\n print(\"dixonResultsFilenameAndPath :: \", self.dixonResultsFilenameAndPath)\r\n\r\n\r\n def set_T2imageData_filename_and_type(self):\r\n\r\n \"\"\"Searches for image data in directory\r\n can be nifti or analyze sets the type and filename\"\"\"\r\n\r\n print(\"inside set_T2imageData_filename_and_type\")\r\n\r\n print(\"self.T2imagesDirpath\", self.T2imagesDirpath)\r\n\r\n if self.T2imagesDirpath == None:\r\n self.T2imageType = None\r\n return False\r\n else:\r\n imgFilenameList = [ os.path.join(self.T2imagesDirpath,fn)\r\n for fn in os.listdir(self.T2imagesDirpath)\r\n if \"nii\" in fn or \"img\" in fn]\r\n\r\n if len(imgFilenameList) == 0:\r\n self.T2imageType = None\r\n self.T2MRIimageFilenameAndPath = None\r\n return False\r\n else:\r\n self.T2MRIimageFilenameAndPath = imgFilenameList[0]\r\n if \"nii\" in self.T2MRIimageFilenameAndPath:\r\n self.T2imageType = \"nifti\"\r\n else:\r\n self.T2imageType = \"analyze\"\r\n\r\n return True\r\n\r\n\r\n def set_dixonImageData_filename_and_type(self):\r\n\r\n \"\"\"Searches for image data in directory\r\n can be nifti or analyze sets the type and filename\r\n filename must have fatPC. in it\"\"\"\r\n\r\n print( \"inside set_dixonImageData_filename_and_type\")\r\n\r\n print(\"self.dixonImagesDirpath\",self.dixonImagesDirpath)\r\n\r\n if self.dixonImagesDirpath == None:\r\n self.dionImageType = None\r\n return False\r\n else:\r\n imgFilenameList = [ os.path.join(self.dixonImagesDirpath,fn)\r\n for fn in os.listdir(self.dixonImagesDirpath)\r\n if \"fatPC.\" in fn and (\"nii\" in fn or \"img\" in fn)]\r\n\r\n if len(imgFilenameList) == 0:\r\n self.dixonImageType = None\r\n self.dixonMRIimageFilenameAndPath = None\r\n return False\r\n else:\r\n self.dixonMRIimageFilenameAndPath = imgFilenameList[0]\r\n if \"nii\" in self.dixonMRIimageFilenameAndPath:\r\n self.dixonImageType = \"nifti\"\r\n else:\r\n self.dixonImageType = \"analyze\"\r\n\r\n return True\r\n\r\n\r\n def set_results_dir(self,protocol, resultsDir):\r\n\r\n resultsDirpath = None\r\n\r\n# resultsDirpath1 = resultsDir\r\n\r\n dirpath = os.path.join(self.root,self.studyName,self.subject,self.session,\r\n self.imagedRegion,protocol, self.results,self.roiType,self.fitModel)\r\n if os.path.exists(dirpath):\r\n resultsDirpath = dirpath\r\n else:\r\n dirpath = os.path.join(self.root,self.studyName,self.subject,self.session,\r\n self.imagedRegion,protocol, self.results,self.roiType)\r\n if os.path.exists(dirpath):\r\n fitModels = [f for f in os.listdir(dirpath)]\r\n if len(fitModels)> 0:\r\n resultsDirpath = os.path.join(dirpath, fitModels[0])\r\n\r\n return resultsDir, resultsDirpath\r\n\r\n\r\n\r\n def set_dataDir_and_results_filenames( self, fn):\r\n\r\n print(\"inside set_dataDir_and_results_filenames\")\r\n print(\"fn\", fn)\r\n\r\n resultsDir, resultsFilename = os.path.split(fn)\r\n print(\"resultsDir\", resultsDir)\r\n print(\"resultsFilename\", resultsFilename)\r\n resultsDirList = resultsDir.split(os.path.sep)\r\n \r\n print(\"resultsDirList\",resultsDirList, )\r\n\r\n sessionIndex = [ i for i,w in enumerate(resultsDirList) if \"sess\" in w]\r\n \r\n print(\"sessionIndex\",sessionIndex)\r\n\r\n if len(sessionIndex):\r\n si = sessionIndex[0]\r\n \r\n print(\"si\",si)\r\n\r\n print(\"resultsDirList\",resultsDirList)\r\n print(\"resultsDirList[0]\",resultsDirList[0])\r\n# print(\"resultsDirList[0][-1]\",resultsDirList[0][-1])\r\n \r\n if len(resultsDirList[0])>0:\r\n\r\n if \":\" == resultsDirList[0][-1]: # add path seperator if root ends in :\r\n resultsDirList[0] = resultsDirList[0]+os.path.sep\r\n\r\n print(\"resultsDirList[0]\", resultsDirList[0])\r\n\r\n\r\n self.root = os.path.sep.join(resultsDirList[:si-2])\r\n\r\n self.studyName = resultsDirList[si-2]\r\n self.subject = resultsDirList[si-1]\r\n self.session = resultsDirList[si]\r\n self.imagedRegion = resultsDirList[si+1]\r\n self.protocol = resultsDirList[si+2]\r\n self.results = resultsDirList[si+3]\r\n self.roiType = imagedRegionType = resultsDirList[si+4]\r\n self.fitModel = resultsDirList[si+5]\r\n\r\n print(\"self.root\",self.root)\r\n\r\n ### create directory paths to T2 and Dixon results and image path\r\n\r\n # T2_images_dirPath\r\n # dixon_images_dirPath\r\n # dixon_results_dirPath\r\n # T2_results_dirPath\r\n\r\n ## T2 image path\r\n\r\n dirpath = os.path.join(self.root,self.studyName,self.subject,\r\n self.session,self.imagedRegion,\"T2\")\r\n if os.path.exists(dirpath):\r\n self.T2imagesDirpath = dirpath\r\n\r\n ## dixon image path\r\n\r\n dirpath = os.path.join(self.root,self.studyName,self.subject,self.session,\r\n self.imagedRegion,\"dixon\")\r\n if os.path.exists(dirpath):\r\n self.dixonImagesDirpath = dirpath\r\n\r\n ## set T2 and dixon results path\r\n\r\n if self.protocol.lower() == \"t2\":\r\n self.T2resultsDirpath, self.dixonResultsDirpath, = self.set_results_dir(\"dixon\", resultsDir)\r\n\r\n elif self.protocol.lower() == \"dixon\":\r\n self.dixonResultsDirpath, self.T2resultsDirpath, = self.set_results_dir(\"T2\", resultsDir)\r\n\r\n print(\"self.dixonResultsDirpath\", self.dixonResultsDirpath)\r\n print(\"self.T2resultsDirpath\", self.T2resultsDirpath)\r\n ## set csv results path name for T2 and dixon\r\n\r\n if \"T2\".lower() in fn.lower():\r\n self.T2resultsFilenameAndPath = fn\r\n\r\n resultFilenameList = [ os.path.join(self.dixonResultsDirpath,fi)\r\n for fi in os.listdir(self.dixonResultsDirpath)\r\n if \"results.\" in fi.lower() and (\".csv\" in fi.lower() )]\r\n if resultFilenameList:\r\n self.dixonResultsFilenameAndPath = resultFilenameList[0]\r\n\r\n elif \"dixon\" in fn.lower():\r\n self.dixonResultsFilenameAndPath = fn\r\n\r\n resultFilenameList = [ os.path.join(self.T2resultsDirpath,fi)\r\n for fi in os.listdir(self.T2ResultsDirpath)\r\n if \"results.\" in fi.lower() and (\".csv\" in fi.lower() )]\r\n if resultFilenameList:\r\n self.T2resultsFilenameAndPath = resultFilenameList[0]\r\n\r\n\r\n\r\n\r\n\r\n def read_T2_data(self):\r\n print(\"read_T2_data function entered\")\r\n print(\"self.T2resultsFilenameAndPath\", self.T2resultsFilenameAndPath)\r\n if os.path.exists(self.T2resultsFilenameAndPath):\r\n print(self.T2resultsFilenameAndPath, \"exists\")\r\n self.t2_data_summary_df = pd.read_csv(self.T2resultsFilenameAndPath)\r\n self.T2slices = list(self.t2_data_summary_df[\"slice\"].unique())\r\n return(True)\r\n else:\r\n print(self.T2resultsFilenameAndPath, \"not Found\" )\r\n return(False)\r\n\r\n def read_Dixon_data(self):\r\n print(\"read_Dixon_data function entered\")\r\n print(\"self.dixonResultsFilenameAndPath\",self.dixonResultsFilenameAndPath)\r\n if os.path.exists(self.dixonResultsFilenameAndPath):\r\n print(self.dixonResultsFilenameAndPath, \"exists\")\r\n self.dixon_data_summary_df = pd.read_csv(self.dixonResultsFilenameAndPath)\r\n self.dixonSlices = list(self.dixon_data_summary_df[\"slice\"].unique())\r\n return(True)\r\n else:\r\n print(self.dixonResultsFilenameAndPath, \"not Found\" )\r\n self.dixon_data_summary_df = pd.DataFrame()\r\n return(False)\r\n\r\n\r\n\r\n def read_T2_img_hdr_files(self):\r\n if os.path.exists(self.T2MRIimageFilenameAndPath):\r\n print(self.T2MRIimageFilenameAndPath, \" found\")\r\n self.t2_imghdr = nibabel.load(self.T2MRIimageFilenameAndPath)\r\n\r\n image_data = self.t2_imghdr.get_data()\r\n\r\n image_data = np.flipud(image_data.swapaxes(1,0))\r\n\r\n\r\n self.update_imageDataT2(image_data)\r\n [self.numRowsT2, self.numColsT2, self.numSlicesT2, self.numEchoesT2] = self.ImageDataT2.shape\r\n\r\n# self.img1 = np.zeros((self.numRowsT2, self.numColsT2,3), dtype=np.double)\r\n self.mriSliceIMG = np.zeros((self.numRowsT2, self.numColsT2), dtype=np.double)\r\n\r\n# self.img1[:,:,0] = self.ImageDataT2[:,:,0,0]/(self.ImageDataT2[:,:,0,0].max()*2)\r\n# self.img1[:,:,0] = self.ImageDataT2[:,:,0,0]\r\n self.mriSliceIMG = self.ImageDataT2[:,:,0,0]*1.0\r\n\r\n self.currentEcho = 0\r\n self.currentSlice = 0\r\n\r\n# mainWindow.setWindowTitle(self.study_name)\r\n return(True)\r\n else:\r\n return(False)\r\n\r\n\r\n\r\n def update_imageDataT2(self, imageData):\r\n self.ImageDataT2 = imageData\r\n\r\n\r\n\r\n\r\n\r\n\r\n def overlayRoisOnImage(self, slice_pos, roi_data):\r\n\r\n print(\"Entering overlayRoisOnImage\", slice_pos)\r\n print(\"roi_data\",roi_data)\r\n\r\n if roi_data in self.t2_data_summary_df.columns:\r\n\r\n\r\n roi_image_layer = np.zeros(self.numRowsT2*self.numColsT2)\r\n\r\n t2_data_query_df = self.t2_data_summary_df.query('slice == {}'.format(str(slice_pos)))\r\n\r\n roi_image_layer[t2_data_query_df.pixel_index] = t2_data_query_df[roi_data]\r\n\r\n self.maskedROIs = np.ma.masked_where(roi_image_layer == 0, roi_image_layer)\r\n\r\n elif roi_data in self.dixon_data_summary_df.columns:\r\n\r\n# print(\"slice_pos\", slice_pos)\r\n# print(\"self.T2slices.index(slice_pos)\",self.T2slices.index(slice_pos))\r\n# print(\"self.dixonSlices[self.T2slices.index(slice_pos)]\",self.dixonSlices[self.T2slices.index(slice_pos)])\r\n\r\n if slice_pos in self.T2slices:\r\n dixon_slice = self.dixonSlices[self.T2slices.index(slice_pos)]\r\n else:\r\n dixon_slice = slice_pos\r\n\r\n roi_image_layer = np.zeros(self.numRowsT2*self.numColsT2)\r\n\r\n #df_t2 = self.t2_data_summary_df[roi_data, 'pixel_index','roi'].groupby('slice')\r\n dixon_data_query_df = self.dixon_data_summary_df.query('slice == {}'.format(str(dixon_slice)))\r\n\r\n# roi_image_layer[dixon_data_query_df.pixels] = dixon_data_query_df[roi_data]/dixon_data_query_df[roi_data].max()\r\n roi_image_layer[dixon_data_query_df.pixel_index] = dixon_data_query_df[roi_data]\r\n\r\n# self.img1[:,:,2] = roi_image_layer.reshape((self.numRowsT2,self.numColsT2))\r\n self.maskedROIs = np.ma.masked_where(roi_image_layer == 0, roi_image_layer)\r\n else:\r\n roi_image_layer = np.zeros(self.numRowsT2*self.numColsT2)\r\n self.maskedROIs = np.ma.masked_where(roi_image_layer == 0, roi_image_layer)\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.7549591660499573, "alphanum_fraction": 0.7642940282821655, "avg_line_length": 22.135135650634766, "blob_id": "882a0f322047c599aa74c068036a4a401cab6023", "content_id": "924596d3e279409fb3d19a3e991563536da99bba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 857, "license_type": "permissive", "max_line_length": 135, "num_lines": 37, "path": "/README.md", "repo_name": "EricHughesABC/T2EPGviewer", "src_encoding": "UTF-8", "text": "# T2EPGviewer\npyQT Dashboard display of MRI T2 EPG muscle data\n\n### Running the main program\n\n```\n python simple_pandas_plot.py\n```\n\n![alt text](screenshot.png \"Logo Title Text 1\")\n\nThis progam summarizes the fitting of muscle MRI T2 data. \n\nIt reads in data from a study directory structure that was created from the project https://github.com/EricHughesABC/T2EPGStudiesMuscle\n\nExample data is provided in the study data directory testStudy.\n\nBelow is a screenshot of the fileopen dialog showing the data file required to be read in.\n\n![open file directory](openDialog.png \"Read in data set\" )\n\n### Requirements\n\nThe program has been tested on python 3.7\n\nIn order for the EPG fitting to work the following module has to be installed\n\nhttps://github.com/EricHughesABC/epg\n\n- pyQT5\n- pandas\n- seaborn\n- matplotlib\n- mplcursors\n- lmfit\n- pydicom\n- nibabel\n\n" }, { "alpha_fraction": 0.6042791604995728, "alphanum_fraction": 0.6348541975021362, "avg_line_length": 47.052978515625, "blob_id": "a965255ab9ce13f938687c566f91406ded86fd2f", "content_id": "97253c83d636656904914df971c0d633279cd95d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14816, "license_type": "permissive", "max_line_length": 106, "num_lines": 302, "path": "/azzT2paramsDialog.py", "repo_name": "EricHughesABC/T2EPGviewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\r\n# Form implementation generated from reading ui file 'azz_fit_parameters_dialog.ui'\r\n#\r\n# Created by: PyQt5 UI code generator 5.6\r\n#\r\n# WARNING! All changes made in this file will be lost!\r\n\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\n\r\nclass AzzT2paramsDialog(object):\r\n\r\n\r\n def __init__(self, lmparams):\r\n\r\n self.lmparams = lmparams\r\n self.params = self.lmparams['azzt2fitparams']\r\n\r\n\r\n def setupAzzT2paramsDialog(self, Dialog):\r\n self.dialog = Dialog\r\n Dialog.setObjectName(\"Azzabou\")\r\n Dialog.resize(398, 335)\r\n self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)\r\n self.buttonBox.setGeometry(QtCore.QRect(230, 280, 156, 23))\r\n\r\n self.buttonBox.setOrientation(QtCore.Qt.Horizontal)\r\n self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)\r\n self.buttonBox.setObjectName(\"buttonBox\")\r\n self.layoutWidget = QtWidgets.QWidget(Dialog)\r\n self.layoutWidget.setGeometry(QtCore.QRect(20, 10, 361, 252))\r\n\r\n self.layoutWidget.setObjectName(\"layoutWidget\")\r\n self.gridLayout = QtWidgets.QGridLayout(self.layoutWidget)\r\n self.gridLayout.setContentsMargins(0, 0, 0, 0)\r\n\r\n self.gridLayout.setObjectName(\"gridLayout\")\r\n self.label_11 = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_11.setObjectName(\"label_11\")\r\n self.gridLayout.addWidget(self.label_11, 7, 0, 1, 1)\r\n\r\n self.label_12 = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_12.setObjectName(\"label_12\")\r\n self.gridLayout.addWidget(self.label_12, 8, 0, 1, 1)\r\n\r\n self.echoTimeValue = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.echoTimeValue.setValidator(QtGui.QDoubleValidator())\r\n self.echoTimeValue.setObjectName(\"echoTimeValue\")\r\n self.gridLayout.addWidget(self.echoTimeValue, 8, 1, 1, 1)\r\n\r\n self.longFatT2value = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.longFatT2value.setValidator(QtGui.QDoubleValidator())\r\n self.longFatT2value.setObjectName(\"longFatT2value\")\r\n self.gridLayout.addWidget(self.longFatT2value, 6, 1, 1, 1)\r\n\r\n self.shortFatT2value = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.shortFatT2value.setValidator(QtGui.QDoubleValidator())\r\n self.shortFatT2value.setObjectName(\"shortFatT2value\")\r\n self.gridLayout.addWidget(self.shortFatT2value, 7, 1, 1, 1)\r\n\r\n self.label_2 = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_2.setObjectName(\"label_2\")\r\n self.gridLayout.addWidget(self.label_2, 0, 2, 1, 1)\r\n\r\n self.label_3 = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_3.setObjectName(\"label_3\")\r\n self.gridLayout.addWidget(self.label_3, 0, 3, 1, 1)\r\n\r\n self.muscleT2minimum = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.muscleT2minimum.setValidator(QtGui.QDoubleValidator())\r\n self.muscleT2minimum.setObjectName(\"muscleT2minimum\")\r\n self.gridLayout.addWidget(self.muscleT2minimum, 1, 2, 1, 1)\r\n\r\n self.fatFractionMinimum = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.fatFractionMinimum.setValidator(QtGui.QDoubleValidator())\r\n self.fatFractionMinimum.setObjectName(\"fatFractionMinimum\")\r\n self.gridLayout.addWidget(self.fatFractionMinimum, 3, 2, 1, 1)\r\n\r\n self.fatFractionMaximum = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.fatFractionMaximum.setValidator(QtGui.QDoubleValidator())\r\n self.fatFractionMaximum.setObjectName(\"fatFractionMaximum\")\r\n self.gridLayout.addWidget(self.fatFractionMaximum, 3, 3, 1, 1)\r\n\r\n self.muscleFractionMinimum = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.muscleFractionMinimum.setValidator(QtGui.QDoubleValidator())\r\n self.muscleFractionMinimum.setObjectName(\"muscleFractionMinimum\")\r\n self.gridLayout.addWidget(self.muscleFractionMinimum, 2, 2, 1, 1)\r\n\r\n self.optimizeMuscleFraction = QtWidgets.QCheckBox(self.layoutWidget)\r\n self.optimizeMuscleFraction.setText(\"\")\r\n self.optimizeMuscleFraction.setChecked(True)\r\n self.optimizeMuscleFraction.setObjectName(\"optimizeMuscleFraction\")\r\n self.gridLayout.addWidget(self.optimizeMuscleFraction, 2, 4, 1, 1)\r\n\r\n self.muscleFractionMaximum = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.muscleFractionMaximum.setValidator(QtGui.QDoubleValidator())\r\n self.muscleFractionMaximum.setObjectName(\"muscleFractionMaximum\")\r\n self.gridLayout.addWidget(self.muscleFractionMaximum, 2, 3, 1, 1)\r\n\r\n self.optimizeFatFraction = QtWidgets.QCheckBox(self.layoutWidget)\r\n self.optimizeFatFraction.setText(\"\")\r\n self.optimizeFatFraction.setChecked(True)\r\n self.optimizeFatFraction.setObjectName(\"optimizeFatFraction\")\r\n self.gridLayout.addWidget(self.optimizeFatFraction, 3, 4, 1, 1)\r\n\r\n self.label_7 = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_7.setObjectName(\"label_7\")\r\n self.gridLayout.addWidget(self.label_7, 3, 0, 1, 1)\r\n\r\n self.label_8 = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_8.setObjectName(\"label_8\")\r\n self.gridLayout.addWidget(self.label_8, 4, 0, 1, 1)\r\n\r\n self.optimizeMuscleT2 = QtWidgets.QCheckBox(self.layoutWidget)\r\n self.optimizeMuscleT2.setText(\"\")\r\n self.optimizeMuscleT2.setChecked(True)\r\n self.optimizeMuscleT2.setObjectName(\"optimizeMuscleT2\")\r\n self.gridLayout.addWidget(self.optimizeMuscleT2, 1, 4, 1, 1)\r\n\r\n self.fatFractionLongT2value = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.fatFractionLongT2value.setValidator(QtGui.QDoubleValidator())\r\n self.fatFractionLongT2value.setObjectName(\"fatFractionLongT2value\")\r\n self.gridLayout.addWidget(self.fatFractionLongT2value, 4, 1, 1, 1)\r\n\r\n self.label_4 = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_4.setObjectName(\"label_4\")\r\n self.gridLayout.addWidget(self.label_4, 0, 4, 1, 1)\r\n\r\n self.muscleT2value = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.muscleT2value.setObjectName(\"muscleT2value\")\r\n self.gridLayout.addWidget(self.muscleT2value, 1, 1, 1, 1)\r\n\r\n self.fatFractionShortT2value = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.fatFractionShortT2value.setValidator(QtGui.QDoubleValidator())\r\n self.fatFractionShortT2value.setObjectName(\"fatFractionShortT2value\")\r\n self.gridLayout.addWidget(self.fatFractionShortT2value, 5, 1, 1, 1)\r\n\r\n self.label_5 = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_5.setObjectName(\"label_5\")\r\n self.gridLayout.addWidget(self.label_5, 1, 0, 1, 1)\r\n\r\n self.label_6 = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_6.setObjectName(\"label_6\")\r\n self.gridLayout.addWidget(self.label_6, 2, 0, 1, 1)\r\n\r\n self.label_9 = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_9.setObjectName(\"label_9\")\r\n self.gridLayout.addWidget(self.label_9, 5, 0, 1, 1)\r\n\r\n self.muscleT2maximum = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.muscleT2maximum.setValidator(QtGui.QDoubleValidator())\r\n self.muscleT2maximum.setObjectName(\"muscleT2maximum\")\r\n self.gridLayout.addWidget(self.muscleT2maximum, 1, 3, 1, 1)\r\n\r\n self.label_10 = QtWidgets.QLabel(self.layoutWidget)\r\n self.label_10.setObjectName(\"label_10\")\r\n self.gridLayout.addWidget(self.label_10, 6, 0, 1, 1)\r\n\r\n self.muscleFractionValue = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.muscleFractionValue.setValidator(QtGui.QDoubleValidator())\r\n self.muscleFractionValue.setObjectName(\"muscleFractionValue\")\r\n self.gridLayout.addWidget(self.muscleFractionValue, 2, 1, 1, 1)\r\n\r\n self.label = QtWidgets.QLabel(self.layoutWidget)\r\n self.label.setObjectName(\"label\")\r\n self.gridLayout.addWidget(self.label, 0, 1, 1, 1)\r\n\r\n self.fatFractionValue = QtWidgets.QLineEdit(self.layoutWidget)\r\n self.fatFractionValue.setValidator(QtGui.QDoubleValidator())\r\n self.fatFractionValue.setObjectName(\"fatFractionValue\")\r\n self.gridLayout.addWidget(self.fatFractionValue, 3, 1, 1, 1)\r\n\r\n self.retranslateUi(Dialog)\r\n self.buttonBox.accepted.connect(self.dialog_ok_clicked)\r\n self.buttonBox.rejected.connect(Dialog.reject)\r\n QtCore.QMetaObject.connectSlotsByName(Dialog)\r\n\r\n def retranslateUi(self, Dialog):\r\n _translate = QtCore.QCoreApplication.translate\r\n Dialog.setWindowTitle(_translate(\"Azzabou\", \"Azzabout T2 model\"))\r\n self.label_11.setText(_translate(\"Azzabou\", \"Short Fat T<sub>2</sub> (ms)\"))\r\n self.label_12.setText(_translate(\"Azzabou\", \"Echo Time (ms)\"))\r\n self.echoTimeValue.setText(_translate(\"Azzabou\", \"10.0\"))\r\n self.longFatT2value.setText(_translate(\"Azzabou\", \"250.0\"))\r\n self.shortFatT2value.setText(_translate(\"Azzabou\", \"43.0\"))\r\n self.label_2.setText(_translate(\"Azzabou\", \"minimum\"))\r\n self.label_3.setText(_translate(\"Azzabou\", \"maximum\"))\r\n self.muscleT2minimum.setText(_translate(\"Azzabou\", \"0.0\"))\r\n self.fatFractionMinimum.setText(_translate(\"Azzabou\", \"0.0\"))\r\n self.fatFractionMaximum.setText(_translate(\"Azzabou\", \"10.0\"))\r\n self.muscleFractionMinimum.setText(_translate(\"Azzabou\", \"0.0\"))\r\n self.muscleFractionMaximum.setText(_translate(\"Azzabou\", \"10.0\"))\r\n self.label_7.setText(_translate(\"Azzabou\", \"Fat Fraction\"))\r\n self.label_8.setText(_translate(\"Azzabou\", \"Fat Fraction (Long T<sub>2</sub>)\"))\r\n self.fatFractionLongT2value.setText(_translate(\"Azzabou\", \"0.6\"))\r\n self.label_4.setText(_translate(\"Azzabou\", \"optimized\"))\r\n self.muscleT2value.setText(_translate(\"Azzabou\", \"35.0\"))\r\n self.fatFractionShortT2value.setText(_translate(\"Azzabou\", \"0.4\"))\r\n self.label_5.setText(_translate(\"Azzabou\", \"Muscle T<sub>2</sub> (ms)\"))\r\n self.label_6.setText(_translate(\"Azzabou\", \"Muscle Fraction\"))\r\n self.label_9.setText(_translate(\"Azzabou\", \"Fat Fraction (Short T<sub>2</sub>)\"))\r\n self.muscleT2maximum.setText(_translate(\"Azzabou\", \"100.0\"))\r\n self.label_10.setText(_translate(\"Azzabou\", \"Long Fat T<sub>2</sub> (ms)\"))\r\n self.muscleFractionValue.setText(_translate(\"Azzabou\", \"0.8\"))\r\n self.label.setText(_translate(\"Azzabou\", \"value\"))\r\n self.fatFractionValue.setText(_translate(\"Azzabou\", \"0.2\"))\r\n\r\n\r\n\r\n def dialog_ok_clicked(self):\r\n print(\"dialog_ok_clicked\")\r\n self.dialog.setResult(1)\r\n worked =self.get_fitparameters()\r\n if worked:\r\n self.params.pretty_print()\r\n self.dialog.accept()\r\n\r\n\r\n def get_fitparameters( self ):\r\n\r\n print(\"self.optimizeFatFraction.isChecked()\", self.optimizeFatFraction.isChecked() )\r\n\r\n #epgt2fitparams = lm.Parameters()\r\n worked = True\r\n try:\r\n\r\n self.params.add(name='T2muscle', value = float(self.muscleT2value.text()),\r\n min = float(self.muscleT2minimum.text()),\r\n max = float(self.muscleT2maximum.text()),\r\n vary = self.optimizeMuscleT2.isChecked())\r\n\r\n self.params.add(name='Amuscle', value = float(self.muscleFractionValue.text()),\r\n min = float(self.muscleFractionMinimum.text()),\r\n max = float(self.muscleFractionMaximum.text()),\r\n vary = self.optimizeMuscleFraction.isChecked())\r\n\r\n self.params.add(name='Afat', value = float(self.fatFractionValue.text()),\r\n min = float(self.fatFractionMinimum.text()),\r\n max = float(self.fatFractionMaximum.text()),\r\n vary = self.optimizeFatFraction.isChecked())\r\n\r\n self.params.add(name='c_l', value=float(self.fatFractionLongT2value.text()), vary=False)\r\n self.params.add(name='c_s', value=float(self.fatFractionShortT2value.text()), vary=False)\r\n self.params.add(name='t2_fl', value=float(self.longFatT2value.text()), vary=False)\r\n self.params.add(name='t2_fs', value=float(self.shortFatT2value.text()), vary=False)\r\n self.params.add(name='echo', value=float(self.echoTimeValue.text()), vary=False)\r\n\r\n buttonsUnChecked = [not self.optimizeFatFraction.isChecked(),\r\n not self.optimizeMuscleFraction.isChecked(),\r\n not self.optimizeMuscleT2.isChecked()]\r\n\r\n print(buttonsUnChecked)\r\n\r\n if all(buttonsUnChecked):\r\n print(\"all buttuns unchecked\")\r\n worked=False\r\n\r\n self.lmparams['azzt2fitparams'] = self.params\r\n except:\r\n print(\"exception occurred\")\r\n worked = False\r\n return worked\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import sys\r\n import lmfit as lm\r\n\r\n lmparams = {}\r\n\r\n epgt2fitparams = lm.Parameters()\r\n azzt2fitparams = lm.Parameters()\r\n\r\n epgt2fitparams.add('T2fat', value = 180.0, min=0, max=5000, vary=False)\r\n epgt2fitparams.add('T2muscle', value = 35, min=0, max=100, vary=True )\r\n epgt2fitparams.add('Afat', value = 0.20, min=0, max=10, vary=True )\r\n epgt2fitparams.add('Amuscle', value = 0.80, min=0, max=10, vary=True )\r\n epgt2fitparams.add('T1fat', value = 365.0, vary=False)\r\n epgt2fitparams.add('T1muscle', value = 1400, vary=False)\r\n epgt2fitparams.add('echo', value = 10.0, vary=False)\r\n\r\n\r\n azzt2fitparams.add_many(('Afat', 60.0, True, 0, 250, None),\r\n ('Amuscle', 40.0, True, 0, 250, None),\r\n ('T2muscle', 40.0, True, 0, 100, None),\r\n ('c_l', 0.55, False, 0, 2000, None),\r\n ('c_s', 0.45, False, 0, 2000, None),\r\n ('t2_fl', 250.0, False, 0, 2000, None),\r\n ('t2_fs', 43.0, False, 0, 2000, None),\r\n ('echo', 10.0, False, 0, 2000, None))\r\n\r\n\r\n lmparams['epgt2fitparams'] = epgt2fitparams\r\n lmparams['azzt2fitparams'] = azzt2fitparams\r\n\r\n app = QtWidgets.QApplication(sys.argv)\r\n Azzabou = QtWidgets.QDialog()\r\n ui = AzzT2paramsDialog(lmparams)\r\n ui.setupAzzT2paramsDialog(Azzabou)\r\n Azzabou.show()\r\n sys.exit(app.exec_())\r\n\r\n" } ]
8
mgh35/lab-grpc
https://github.com/mgh35/lab-grpc
e221ac390650917fddf679d321924a39665125e8
d387e00c17b479e2cfc5cc77e62e626fe639bf2d
d5ca54fd4f0b97e9eb584d49d5a65f6d03d3d0de
refs/heads/master
2022-10-17T06:55:13.740081
2020-06-08T01:52:24
2020-06-08T01:52:24
270,138,926
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6728838086128235, "alphanum_fraction": 0.6915351748466492, "avg_line_length": 25.80769157409668, "blob_id": "2bf58bdcf77e44c87b6e890ffad4152be68e0fff", "content_id": "bbc7eb137244d2b017b4f5f3a70e291b8677e5a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 697, "license_type": "permissive", "max_line_length": 68, "num_lines": 26, "path": "/summer-grpc/server.py", "repo_name": "mgh35/lab-grpc", "src_encoding": "UTF-8", "text": "from concurrent import futures\nfrom generated import summer_pb2, summer_pb2_grpc\nimport grpc\nimport logging\n\n\nclass SummerServicer(summer_pb2_grpc.SummerServicer):\n\n def Sum(self, request: summer_pb2.ToSum, context):\n logging.info(\"SummerServicer.Sum(%s)\", request)\n s = sum(request.values)\n return summer_pb2.Summed(sum=s)\n\n\ndef serve():\n server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\n summer_pb2_grpc.add_SummerServicer_to_server(\n SummerServicer(), server)\n server.add_insecure_port('[::]:50051')\n server.start()\n server.wait_for_termination()\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n serve()\n" }, { "alpha_fraction": 0.598705530166626, "alphanum_fraction": 0.6375404596328735, "avg_line_length": 24.75, "blob_id": "bb0b3727b164c1de091a0ab5b28c84ac4ae84e97", "content_id": "09433bae1615b3a6e6ff94c835cb84ade3a4900f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 309, "license_type": "permissive", "max_line_length": 50, "num_lines": 12, "path": "/summer-grpc/test_server.py", "repo_name": "mgh35/lab-grpc", "src_encoding": "UTF-8", "text": "from generated.summer_pb2 import ToSum\nimport pytest\n\n\[email protected]([\"values\", \"expected\"], [\n ([], 0),\n ([1.0], 1.0),\n ([1.0, 1.0], 2.0),\n])\ndef test_some(grpc_stub, values, expected):\n response = grpc_stub.Sum(ToSum(values=values))\n assert response.sum == pytest.approx(expected)\n" }, { "alpha_fraction": 0.7219153046607971, "alphanum_fraction": 0.7311233878135681, "avg_line_length": 14.083333015441895, "blob_id": "59286e311c1a94ebcfdd25f013d88f081afd9910", "content_id": "4d5109d934a76f464fefea653ce9013cde1ccb1e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 543, "license_type": "permissive", "max_line_length": 68, "num_lines": 36, "path": "/README.md", "repo_name": "mgh35/lab-grpc", "src_encoding": "UTF-8", "text": "# Lab: GRPC \n\nThe purpose of this lab is to investigate setting up a gRPC service.\n\n## gRPC Summer\n\nThe example service just sums a list of given floats.\n\nTo start the service:\n\n```shell script\nmake run\n```\n\nAnd run an example query:\n\n```shell script\nmake run_client\n```\n\n\n## References\n\n### gRPC\n\nhttps://grpc.io/docs/languages/python/basics/\n\nhttps://github.com/grpc/grpc\n\nhttps://developers.google.com/protocol-buffers/docs/proto3\n\n### Service Types\n\nhttps://www.youtube.com/watch?v=ZDUA5pD50Ok\n\nhttps://www.youtube.com/watch?v=IvsANO0qZEg\n" }, { "alpha_fraction": 0.630270779132843, "alphanum_fraction": 0.6338215470314026, "avg_line_length": 34.203125, "blob_id": "be28d41bc98d3532a6631db1374984cd96031f0e", "content_id": "dc63588837c6e316e94029b4da7934f856f86c58", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2253, "license_type": "permissive", "max_line_length": 91, "num_lines": 64, "path": "/summer-grpc/generated/summer_pb2_grpc.py", "repo_name": "mgh35/lab-grpc", "src_encoding": "UTF-8", "text": "# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!\nimport grpc\n\nfrom generated import summer_pb2 as generated_dot_summer__pb2\n\n\nclass SummerStub(object):\n \"\"\"Missing associated documentation comment in .proto file\"\"\"\n\n def __init__(self, channel):\n \"\"\"Constructor.\n\n Args:\n channel: A grpc.Channel.\n \"\"\"\n self.Sum = channel.unary_unary(\n '/Summer/Sum',\n request_serializer=generated_dot_summer__pb2.ToSum.SerializeToString,\n response_deserializer=generated_dot_summer__pb2.Summed.FromString,\n )\n\n\nclass SummerServicer(object):\n \"\"\"Missing associated documentation comment in .proto file\"\"\"\n\n def Sum(self, request, context):\n \"\"\"Missing associated documentation comment in .proto file\"\"\"\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')\n\n\ndef add_SummerServicer_to_server(servicer, server):\n rpc_method_handlers = {\n 'Sum': grpc.unary_unary_rpc_method_handler(\n servicer.Sum,\n request_deserializer=generated_dot_summer__pb2.ToSum.FromString,\n response_serializer=generated_dot_summer__pb2.Summed.SerializeToString,\n ),\n }\n generic_handler = grpc.method_handlers_generic_handler(\n 'Summer', rpc_method_handlers)\n server.add_generic_rpc_handlers((generic_handler,))\n\n\n # This class is part of an EXPERIMENTAL API.\nclass Summer(object):\n \"\"\"Missing associated documentation comment in .proto file\"\"\"\n\n @staticmethod\n def Sum(request,\n target,\n options=(),\n channel_credentials=None,\n call_credentials=None,\n compression=None,\n wait_for_ready=None,\n timeout=None,\n metadata=None):\n return grpc.experimental.unary_unary(request, target, '/Summer/Sum',\n generated_dot_summer__pb2.ToSum.SerializeToString,\n generated_dot_summer__pb2.Summed.FromString,\n options, channel_credentials,\n call_credentials, compression, wait_for_ready, timeout, metadata)\n" }, { "alpha_fraction": 0.6648841500282288, "alphanum_fraction": 0.6702316999435425, "avg_line_length": 16.53125, "blob_id": "b741c7c8590445fe56bae15ae1f4e4bd753f1772", "content_id": "18456da21fa8e05400c374b638a761c1160e41c5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 561, "license_type": "permissive", "max_line_length": 103, "num_lines": 32, "path": "/summer-grpc/Makefile", "repo_name": "mgh35/lab-grpc", "src_encoding": "UTF-8", "text": ".venv :\n\t( \\\n\t\tpython -m venv .venv ; \\\n\t\tsource .venv/bin/activate ; \\\n\t\tpip install -r requirements.txt \\\n\t)\n\nsetup : .venv\n\ngenerated : .venv\n\t(\\\n\t\tsource .venv/bin/activate ; \\\n\t\tmkdir generated; \\\n\t\tpython -m grpc_tools.protoc -Iproto --python_out=. --grpc_python_out=. proto/generated/summer.proto \\\n\t)\n\ntest : generated\n\t.venv/bin/python -m pytest .\n\nrun : generated\n\t.venv/bin/python -m server\n\nrun_client : generated\n\t.venv/bin/python -m client 1 2 3\n\nclean_venv :\n\trm -rf .venv\n\nclean_generated :\n\trm -rf generated\n\nclean : clean_venv clean_generated\n" }, { "alpha_fraction": 0.8709677457809448, "alphanum_fraction": 0.8709677457809448, "avg_line_length": 9.666666984558105, "blob_id": "e1966cb1bb3a16959a82a4114af4a7ba10179f31", "content_id": "5cdf482b112cad02a70001098f3f3af2d17b417c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 31, "license_type": "permissive", "max_line_length": 12, "num_lines": 3, "path": "/summer-grpc/requirements.txt", "repo_name": "mgh35/lab-grpc", "src_encoding": "UTF-8", "text": "grpcio\ngrpcio-tools\npytest-grpc" }, { "alpha_fraction": 0.6341463327407837, "alphanum_fraction": 0.6585366129875183, "avg_line_length": 23.117647171020508, "blob_id": "46ac8182669953b0530c5cd09b296d6bc2c79a65", "content_id": "d6a107d01aa69c9ce9aa38fd64041ff4b151e1b6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 410, "license_type": "permissive", "max_line_length": 61, "num_lines": 17, "path": "/summer-grpc/client.py", "repo_name": "mgh35/lab-grpc", "src_encoding": "UTF-8", "text": "from generated import summer_pb2, summer_pb2_grpc\nimport grpc\nimport sys\nimport typing\n\n\ndef run(values: typing.List[int]):\n with grpc.insecure_channel('localhost:50051') as channel:\n stub = summer_pb2_grpc.SummerStub(channel)\n\n summed = stub.Sum(summer_pb2.ToSum(values=values))\n print(summed)\n\n\nif __name__ == \"__main__\":\n values = [float(_) for _ in sys.argv[1:]]\n run(values)\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7544642686843872, "avg_line_length": 22.578947067260742, "blob_id": "adf3e310cdbb621cbe347ff1131fba242c5af63a", "content_id": "0d42b82109ae4c59c3f2edfbb90876523e4b5b4a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 448, "license_type": "permissive", "max_line_length": 70, "num_lines": 19, "path": "/summer-grpc/conftest.py", "repo_name": "mgh35/lab-grpc", "src_encoding": "UTF-8", "text": "import pytest\n\n\[email protected](scope='module')\ndef grpc_add_to_server():\n from generated.summer_pb2_grpc import add_SummerServicer_to_server\n return add_SummerServicer_to_server\n\n\[email protected](scope='module')\ndef grpc_servicer():\n from server import SummerServicer\n return SummerServicer()\n\n\[email protected](scope='module')\ndef grpc_stub_cls(grpc_channel):\n from generated.summer_pb2_grpc import SummerStub\n return SummerStub\n" } ]
8
yukojima424/deliverable
https://github.com/yukojima424/deliverable
9cb4cdf21ecbc591a73697dbb339141c99d2d369
68b76cc89e89d7be590dd9d5fae63d14f11af93d
d5b9ca7c46e4b6bc0c7b3cc896b2f2abe500b737
refs/heads/master
2023-03-11T11:44:30.380711
2021-02-25T06:51:56
2021-02-25T06:51:56
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5194648504257202, "alphanum_fraction": 0.5291878581047058, "avg_line_length": 29.783061981201172, "blob_id": "946390337c36c0046c3c449cf0aba22533a72a97", "content_id": "ab6a21a892352f589ff5038ee1c5521d2defaa40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 30161, "license_type": "no_license", "max_line_length": 143, "num_lines": 862, "path": "/train_seq2seq_gru_attention.py", "repo_name": "yukojima424/deliverable", "src_encoding": "UTF-8", "text": "# AttentionおよびGRU搭載型Seq2Seqの構築\n# 概要\n# Seq2SeqにAttention層を加え、さらに通常のRNNやLSTMではなくGRUを搭載したものを構築\n\nimport sys\nsys.path.append('../kojimayu')\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport pickle\nimport os\nimport os.path\n\n# データをIDに、IDをデータにするものの枠を作る。\nid_to_char = {}\nchar_to_id = {}\n\n\ndef _update_vocab(txt):\n chars = list(txt)\n\n for i, char in enumerate(chars): # 新しいデータであれば更新する。\n if char not in char_to_id:\n tmp_id = len(char_to_id)\n char_to_id[char] = tmp_id\n id_to_char[tmp_id] = char\n\n\ndef load_data(file_name='date.txt', seed=1984):\n file_path = '../kojimayu/date/' + file_name # 自身のローカルで行うため、パスは自身のもので構築している。\n\n if not os.path.exists(file_path):\n print('No file: %s' % file_name)\n return None\n\n questions, answers = [], []\n\n for line in open(file_path, 'r'):\n idx = line.find('_')\n questions.append(line[:idx])\n answers.append(line[idx:-1])\n\n for i in range(len(questions)):\n q, a = questions[i], answers[i]\n _update_vocab(q)\n _update_vocab(a)\n\n # x(入力データ)とt(正解ラベル)の配列を作る。\n x = np.zeros((len(questions), len(questions[0])), dtype=np.int)\n t = np.zeros((len(questions), len(answers[0])), dtype=np.int)\n\n for i, sentence in enumerate(questions):\n x[i] = [char_to_id[c] for c in list(sentence)]\n for i, sentence in enumerate(answers):\n t[i] = [char_to_id[c] for c in list(sentence)]\n\n # 乱数によりデータをシャッフルする。\n indices = np.arange(len(x))\n if seed is not None:\n np.random.seed(seed)\n np.random.shuffle(indices)\n x = x[indices]\n t = t[indices]\n\n # 8:2の割合で訓練データとテストデータを分ける。\n split_at = len(x) - len(x) // 5\n (x_train, x_test) = x[:split_at], x[split_at:]\n (t_train, t_test) = t[:split_at], t[split_at:]\n\n return (x_train, t_train), (x_test, t_test)\n\n\ndef get_vocab():\n return char_to_id, id_to_char\n\n# Adam\nclass Adam:\n def __init__(self, lr=0.001, beta1=0.9, beta2=0.999):\n self.lr = lr\n self.beta1 = beta1\n self.beta2 = beta2\n self.iter = 0\n self.m = None\n self.v = None\n \n def update(self, params, grads):\n if self.m is None:\n self.m, self.v = [], []\n for param in params:\n self.m.append(np.zeros_like(param))\n self.v.append(np.zeros_like(param))\n \n self.iter += 1\n lr_t = self.lr * np.sqrt(1.0 - self.beta2**self.iter) / (1.0 - self.beta1**self.iter)\n\n for i in range(len(params)):\n self.m[i] += (1 - self.beta1) * (grads[i] - self.m[i])\n self.v[i] += (1 - self.beta2) * (grads[i]**2 - self.v[i])\n \n params[i] -= lr_t * self.m[i] / (np.sqrt(self.v[i]) + 1e-7)\n\n# Trainer\nclass Trainer:\n def __init__(self, model, optimizer):\n self.model = model\n self.optimizer = optimizer\n self.loss_list = []\n self.eval_interval = None\n self.current_epoch = 0\n\n def fit(self, x, t, max_epoch=10, batch_size=32, max_grad=None, eval_interval=20):\n data_size = len(x)\n max_iters = data_size // batch_size\n self.eval_interval = eval_interval\n model, optimizer = self.model, self.optimizer\n total_loss = 0\n loss_count = 0\n\n start_time = time.time()\n for epoch in range(max_epoch):\n # シャッフル\n idx = np.random.permutation(np.arange(data_size))\n x = x[idx]\n t = t[idx]\n\n for iters in range(max_iters):\n batch_x = x[iters * batch_size:(iters+1) * batch_size]\n batch_t = t[iters * batch_size:(iters+1) * batch_size]\n\n # 勾配を求め、パラメータを更新\n loss = model.forward(batch_x, batch_t)\n model.backward()\n params, grads = remove_duplicate(model.params, model.grads) # 共有された重みを1つに集約\n if max_grad is not None:\n clip_grads(grads, max_grad) # 勾配爆発への対策メソッド 勾配クリッピングという\n optimizer.update(params, grads)\n total_loss += loss\n loss_count += 1\n\n # 評価\n if (eval_interval is not None) and (iters % eval_interval) == 0:\n avg_loss = total_loss / loss_count\n elapsed_time = time.time() - start_time\n print('| epoch %d | iter %d / %d | time %d[s] | loss %.2f'\n % (self.current_epoch + 1, iters + 1, max_iters, elapsed_time, avg_loss))\n self.loss_list.append(float(avg_loss))\n total_loss, loss_count = 0, 0\n\n self.current_epoch += 1\n\n def plot(self, ylim=None):\n x = np.arange(len(self.loss_list))\n if ylim is not None:\n plt.ylim(*ylim)\n plt.plot(x, self.loss_list, label='train')\n plt.xlabel('iterations (x' + str(self.eval_interval) + ')')\n plt.ylabel('loss')\n plt.show()\n \ndef clip_grads(grads, max_norm):\n total_norm = 0\n for grad in grads:\n total_norm += np.sum(grad ** 2)\n total_norm = np.sqrt(total_norm)\n \n rate = max_norm / (total_norm + 1e-6) \n if rate < 1:\n for grad in grads:\n grad *= rate\n \ndef remove_duplicate(params, grads):\n params, grads = params[:], grads[:] # copy list ※中身は複製されない※\n \n while True:\n find_flg = False\n L = len(params)\n \n for i in range(0, L - 1):\n for j in range(i + 1, L):\n # 重みを共有する場合\n if params[i] is params[j]: # params が同じものを探している(同じである場合の処理は以下)\n grads[i] += grads[j] # 勾配の加算\n find_flg = True\n params.pop(j) # pop() は削除を意味する\n grads.pop(j) # pop() は削除を意味する\n \n # 転置行列として重みを共有する場合(weight tying)\n elif params[i].ndim == 2 and params[j].ndim == 2 and params[i].T.shape == params[j].shape and np.all(params[i].T == params[j]):\n # np.all() は()内の条件を満たすか確認している\n grads[i] += grads[j].T\n find_flg = True\n params.pop(j) # pop() は削除を意味する\n grads.pop(j) # pop() は削除を意味する\n \n if find_flg: break\n if find_flg: break\n if not find_flg: break\n \n return params, grads\n\n# couting program\ndef eval_seq2seq(model, question, correct, id_to_char, verbose=False, is_reverse=False):\n correct = correct.flatten()\n # 頭の区切り文字\n start_id = correct[0]\n correct = correct[1:]\n guess = model.generate(question, start_id, len(correct))\n\n # 文字列への変換\n question = ''.join([id_to_char[int(c)] for c in question.flatten()]) # 質問文\n correct = ''.join([id_to_char[int(c)] for c in correct]) # 実際の解答\n guess = ''.join([id_to_char[int(c)] for c in guess]) # 解答文(文章生成文)\n\n if verbose:\n if is_reverse:\n question = question[::-1] # question の並びを逆にする\n\n colors = {'ok': '\\033[92m', 'fail': '\\033[91m', 'close': '\\033[0m'} # 色の指定\n print('Q', question)\n print('T', correct)\n\n is_windows = os.name == 'nt'\n\n if correct == guess: # 実際の解答と生成した解答が合ってた場合\n mark = colors['ok'] + '☑' + colors['close']\n if is_windows:\n mark = '0'\n print(mark + ' ' + guess)\n else: # その他の場合(不正解の場合)\n mark = colors['fail'] + '☒' + colors['close']\n if is_windows:\n mark = 'X'\n print(mark + ' ' + guess)\n print('---')\n\n return 1 if guess == correct else 0 # 正解していたら1を返し、不正解なら0を返す\n\n# build layers\ndef softmax(x):\n if x.ndim == 2:\n x = x - x.max(axis=1, keepdims=True)\n # keepdims=True とは元の配列に対してブロードキャストを正しく適用させ演算する\n x = np.exp(x)\n x /= x.sum(axis=1, keepdims=True)\n elif x.ndim == 1:\n x = x - np.max(x)\n x = np.exp(x) / np.sum(np.exp(x))\n\n return x\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n\n\nclass TimeSoftmaxWithLoss:\n def __init__(self):\n self.params, self.grads = [], []\n self.cache = None\n self.ignore_label = -1\n\n def forward(self, xs, ts):\n N, T, V = xs.shape\n\n if ts.ndim == 3: # 教師ラベルが one_hot_vector の場合 正解のインデックスに変換\n ts = ts.argmax(axis=2)\n\n mask = (ts != self.ignore_label) # ts が-1でない時(self.ignore_label の数値でない時)\n\n # バッチ分と時系列分を乗算でまとめる\n xs = xs.reshape(N * T, V)\n ts = ts.reshape(N * T)\n mask = mask.reshape(N * T)\n\n ys = softmax(xs)\n ls = np.log(ys[np.arange(N * T), ts])\n ls *= mask # ignore_label に該当するものは損失を 0 にする (mask の対象外で計算されない)\n loss = -np.sum(ls) # 各時刻ごとの損失 ls を加算していく\n loss /= mask.sum() # 損失の平均値を出す\n\n self.cache = (ts, ys, mask, (N, T, V))\n return loss\n\n def backward(self, dout=1):\n ts, ys, mask, (N, T, V) = self.cache\n\n dx = ys\n dx[np.arange(N * T), ts] -= 1\n # 該当する dx のインデックスにある要素全てに対して -1 する\n dx *= dout\n dx /= mask.sum()\n dx *= mask[:, np.newaxis]\n # [:, np.newaxis] により次元を1つ追加\n # mask により ignore_label に該当するものは損失を 0 にする (mask の対象外で計算されない)\n\n dx = dx.reshape((N, T, V)) # 入力データ(N, T, D)と同様の形に整形\n\n return dx\n\n\nclass TimeAffine:\n def __init__(self, W, b):\n self.params = [W, b]\n self.grads = [np.zeros_like(W), np.zeros_like(b)]\n self.x = None\n\n def forward(self, x):\n N, T, D = x.shape\n W, b = self.params\n\n rx = x.reshape(N * T, -1) # x の配列を N*T 行 にする (-1 は元の形状から推測して作られるという指定,今回なら列の長さが対象)\n out = np.dot(rx, W) + b # 全てをまとめて計算し,出力層へ\n self.x = x\n return out.reshape(N, T, -1) # -1 は元の形状から推測して作られるという指定, 今回なら3次元目が対象\n\n def backward(self, dout):\n x = self.x\n N, T, D = x.shape\n W, b = self.params\n\n dout = dout.reshape(N * T, -1)\n rx = x.reshape(N * T, -1)\n\n db = np.sum(dout, axis=0) # 列方向に(axis=0) dout を加算\n dW = np.dot(rx.T, dout) # 転置(.T)して計算\n dx = np.dot(dout, W.T) # 転置(.T)して計算\n dx = dx.reshape(* x.shape) # x の形状に変換\n\n self.grads[0][...] = dW\n self.grads[1][...] = db\n\n return dx\n\n\nclass Embedding:\n def __init__(self, W):\n self.params = [W]\n self.grads = [np.zeros_like(W)] # W と同じ形状の配列で全ての要素0にする\n self.idx = None\n # idx は重み(単語の分散表現)を取り出すときに使う数値\n # idx には単語idを配列として格納していく\n\n def forward(self, idx):\n W, = self.params\n self.idx = idx\n out = W[idx]\n return out\n\n def backward(self, dout):\n dW, = self.grads\n dW[...] = 0 # dW の形状を維持したまま、要素を0にする\n\n np.add.at(dW, self.idx, dout)\n # np.add.at(A, idx, B) → B を A に加算し、加算を行う A の行を idx によって指定する\n # つまり指定した重み(単語の分散表現)に対してだけ加算を行う (重複した idx があっても加算により正しく処理)\n # optimizer を使用するなら dW[self.idx] = dout\n return None\n\n\n \n \nclass TimeEmbedding:\n def __init__(self, W):\n self.params = [W]\n self.grads = [np.zeros_like(W)]\n self.layers = None\n self.W = W\n\n def forward(self, xs):\n N, T = xs.shape\n V, D = self.W.shape\n\n out = np.empty((N, T, D), dtype='f')\n self.layers = []\n\n for t in range(T):\n layer = Embedding(self.W)\n out[:, t, :] = layer.forward(xs[:, t]) # 各時刻ごとの重みを取り出し,該当する out に入れる\n self.layers.append(layer)\n\n return out\n\n def backward(self, dout):\n N, T, D = dout.shape\n\n grad = 0\n for t in range(T):\n layer = self.layers[t]\n layer.backward(dout[:, t, :])\n grad += layer.grads[0] # grad を加算していく\n\n self.grads[0][...] = grad # 最終的な勾配 grad を上書き\n\n return None\n\n# Attention and GRU\nclass GRU:\n def __init__(self, Wx, Wh, b):\n self.params = [Wx, Wh, b]\n self.grads = [np.zeros_like(Wx), np.zeros_like(Wh), np.zeros_like(b)]\n self.cache = None\n\n def forward(self, x, h_prev):\n '''\n それぞれのデータの形状は以下の通り(計算上最後に求める形状に問題がない事が分かる)\n 各パラメータは3つ分を集約\n x = N * D , Wx = D * 3H\n h_prev = N * H , Wh = H * 3H , b = 1 * 3H\n '''\n Wx, Wh, b = self.params\n H = Wh.shape[0]\n # Wx, Wh のパラメータを3つに分ける(z, r, h)\n Wxz, Wxr, Wxh = Wx[:, :H], Wx[:, H:2 * H], Wx[:, 2 * H:]\n Whz, Whr, Whh = Wh[:, :H], Wh[:, H:2 * H], Wh[:, 2 * H:]\n bz, br, bh = b[:H], b[H:2 * H], b[2 * H:]\n\n # GRU 内部の要素である z, r, h_hat を公式で算出\n z = sigmoid(np.dot(x, Wxz) + np.dot(h_prev, Whz) + bz)\n r = sigmoid(np.dot(x, Wxr) + np.dot(h_prev, Whr) + br)\n h_hat = np.tanh(np.dot(x, Wxh) + np.dot(r * h_prev, Whh) + bh)\n\n # z, r, h_hat を使い h_next を公式で算出(GRU の最後の計算)\n h_next = (1 - z) * h_prev + z * h_hat\n\n self.cache = (x, h_prev, z, r, h_hat)\n\n return h_next\n\n def backward(self, dh_next):\n Wx, Wh, b = self.params\n H = Wh.shape[0]\n # forward と同様にパラメータを3つに分ける(z, r, h) <ただしバイアスはいらない>\n Wxz, Wxr, Wxh = Wx[:, :H], Wx[:, H:2 * H], Wx[:, 2 * H:]\n Whz, Whr, Whh = Wh[:, :H], Wh[:, H:2 * H], Wh[:, 2 * H:]\n x, h_prev, z, r, h_hat = self.cache\n\n # forward で行った計算の逆伝播\n dh_hat = dh_next * z\n dh_prev = dh_next * (1 - z) # ①\n\n # dh_hat の逆伝播 <np.tanh() の逆伝播>\n dt = dh_hat * (1 - h_hat ** 2)\n dbh = np.sum(dt, axis=0) # bh の勾配 : (H,) の形状に戻すために axis=0 方向に合計\n dWhh = np.dot((r * h_prev).T, dt) # Wh の勾配 : 転置を行い乗算\n dhr = np.dot(dt, Whh.T) # (r * h_prev) の勾配 : 転置を行い乗算\n dWxh = np.dot(x.T, dt) # Wxh の勾配 : 転置を行い乗算\n dx = np.dot(dt, Wxh.T) # x の勾配 : 転置を行い乗算\n dh_prev += r * dhr # ①で出した dh_prev に加算\n\n # z の backward\n dz = dh_next * h_hat - dh_next * h_prev # h_next の算出計算の逆伝播\n dt = dz * z * (1 - z) # sigmoid の逆伝播公式\n dbz = np.sum(dt, axis=0)\n dWhz = np.dot(h_prev.T, dt)\n dh_prev += np.dot(dt, Whz.T) # ①で出した dh_prev に加算\n dWxz = np.dot(x.T, dt)\n dx += np.dot(dt, Wxz.T) # dx をまとめるため加算\n\n # r の backward\n dr = dhr * h_prev\n dt = dr * r * (1 - r) # sigmoid の逆伝播\n dbr = np.sum(dt, axis=0)\n dWhr = np.dot(h_prev.T, dt)\n dh_prev += np.dot(dt, Whr.T)\n dWxr = np.dot(x.T, dt)\n dx += np.dot(dt, Wxr.T) # dx をまとめるため加算\n\n # 引数に与えた配列を横方向に連結 (縦方向に連結する時 np.vstack())\n self.dWx = np.hstack((dWxz, dWxr, dWxh))\n self.dWh = np.hstack((dWhz, dWhr, dWhh))\n self.db = np.hstack((dbz, dbr, dbh))\n\n # grads を上書き\n self.grads[0][...] = self.dWx\n self.grads[1][...] = self.dWh\n self.grads[2][...] = self.db\n\n return dx, dh_prev\n\nclass TimeGRU:\n def __init__(self, Wx, Wh, b, stateful=False):\n self.params = [Wx, Wh, b]\n self.grads = [np.zeros_like(Wx), np.zeros_like(Wh), np.zeros_like(b)]\n self.layers = None\n self.h, self.dh = None, None\n self.stateful = stateful\n\n def forward(self, xs):\n Wx, Wh, b = self.params\n N, T, D = xs.shape\n H = Wh.shape[0]\n self.layers = []\n hs = np.empty((N, T, H), dtype='f')\n\n if not self.stateful or self.h is None:\n self.h = np.zeros((N, H), dtype='f')\n\n for t in range(T): # T回繰り返す(時系列データ分)\n layer = GRU(* self.params)\n self.h = layer.forward(xs[:, t, :], self.h)\n hs[:, t, :] = self.h\n self.layers.append(layer)\n return hs\n\n def backward(self, dhs):\n Wx, Wh, b = self.params\n N, T, H = dhs.shape\n D = Wx.shape[0]\n\n dxs = np.empty((N, T, D), dtype='f')\n\n dh = 0\n grads = [0, 0, 0]\n for t in reversed(range(T)):\n layer = self.layers[t]\n dx, dh = layer.backward(dhs[:, t, :] + dh)\n dxs[:, t, :] = dx\n\n for i, grad in enumerate(layer.grads):\n grads[i] += grad\n\n for i, grad in enumerate(grads):\n self.grads[i][...] = grad\n\n self.dh = dh\n return dxs\n\n def set_state(self, h):\n self.h = h\n\n def reset_state(self):\n self.h = None\n \n \nclass Softmax:\n def __init__(self):\n self.params, self.grads = [], []\n self.out = None\n\n def forward(self, x):\n self.out = softmax(x)\n return self.out\n\n def backward(self, dout):\n dx = self.out * dout\n sumdx = np.sum(dx, axis=1, keepdims=True)\n dx -= self.out * sumdx\n return dx\n\nclass WeightSum:\n def __init__(self):\n self.params, self.grads = [], [] # このレイヤは学習するパラメータを持たないため [] とする\n self.cache = None\n\n def forward(self, hs, a):\n N, T, H = hs.shape\n\n # a は各単語の重要度を表す重み\n ar = a.reshape(N, T, 1).repeat(H, axis=2)# a の形状を hs と同じ(N, T, H)へ変換\n t = hs * ar # 乗算により各単語の重要度を表現したコンテキストベクトルが誕生\n c = np.sum(t, axis=1) # 時系列の形状(T)を消す (N, H)\n\n self.cache = (hs, ar)\n return c\n\n def backward(self, dc):\n hs, ar = self.cache\n N, T, H = hs.shape\n\n dt = dc.reshape(N, 1, H).repeat(T, axis=1) # dt の形状に直す(N, T, H) <sum の逆伝播>\n dhs = dt * ar\n dar = dt * hs\n da = np.sum(dar, axis=2) # da の形状に直す(N, T) <repeat の逆伝播>\n return dhs, da\n\nclass AttentionWeight:\n def __init__(self):\n self.params, self.grads = [], []\n self.softmax = Softmax()\n self.cache = None\n\n def forward(self, hs, h):\n N, T, H = hs.shape\n\n hr = h.reshape(N, 1, H).repeat(T, axis=1) # hs と同じ形状の (N, T, H) へ変換\n t = hs * hr # 乗算によりhs と h の対応関係を表現(h が hs にどれだけ似ているかを表現)\n s = np.sum(t, axis=2)\n a = self.softmax.forward(s) # softmax により確率分布で表現\n\n self.cache = (hs, hr)\n return a\n\n def backward(self, da):\n hs, hr = self.cache\n N, T, H = hs.shape\n\n ds = self.softmax.backward(da)\n dt = ds.reshape(N, T, 1).repeat(H, axis=2) # ds の形状に直す (N, T, H) <sum の逆伝播>\n dhr = dt * hs\n dhs = dt * hr\n dh = np.sum(dhr, axis=1) # dh の形状に直す (N, H) <repeat の逆伝播>\n\n return dhs, dh\n\nclass Attention:\n def __init__(self):\n self.params, self.grads = [], []\n self.attention_weight_layer = AttentionWeight()\n self.weight_sum_layer = WeightSum()\n self.attention_weight = None\n\n def forward(self, hs, h):\n a = self.attention_weight_layer.forward(hs, h)\n out = self.weight_sum_layer.forward(hs, a)\n self.attention_weight = a # 各単語への重みを保持\n return out\n\n def backward(self, dout):\n dhs0, da = self.weight_sum_layer.backward(dout)\n dhs1, dh = self.attention_weight_layer.backward(da)\n dhs = dhs0 + dhs1\n return dhs, dh\n\nclass TimeAttention:\n def __init__(self):\n self.params, self.grads = [], []\n self.layers = None\n self.attention_weights = None\n\n def forward(self, hs_enc, hs_dec):\n N, T, H = hs_dec.shape\n out = np.empty_like(hs_dec)\n self.layers = []\n self.attention_weights = []\n\n for t in range(T): # 時系列分繰り返す\n layer = Attention()\n out[:, t, :] = layer.forward(hs_enc, hs_dec[:, t, :]) # 各時系列に該当するデータを入れていく\n self.layers.append(layer)\n self.attention_weights.append(layer.attention_weight)\n # Attention で保持した各単語への重みをリスト追加していく → 各時系列ごとの単語への重みを保有する\n\n return out\n\n def backward(self, dout):\n N, T, H = dout.shape\n dhs_enc = 0\n dhs_dec = np.empty_like(dout)\n\n for t in range(T):\n layer = self.layers[t] # t番目(各時系列の順番)のレイヤを呼び出す\n dhs, dh = layer.backward(dout[:, t, :]) # 各時系列に該当する dout をいれる\n dhs_enc += dhs # 各時系列ごとの dhs をまとめる(encoder の hs の勾配として)\n dhs_dec[:, t, :] = dh # 各時系列ごとの dh をまとめる(decoder の h の勾配として)\n\n return dhs_enc, dhs_dec\n\n# Seq2Seq\nclass AttentionEncoderGRU:\n '''\n vocab_size 語彙数(文字の種類)\n wordvec_size 文字ベクトルの次元数\n hidden_size 隠れ状態ベクトルの次元数\n '''\n def __init__(self, vocab_size, wordvec_size, hidden_size):\n V, D ,H = vocab_size, wordvec_size, hidden_size\n rn = np.random.randn\n\n embed_W = (rn(V, D) / 100).astype('f')\n gru_Wx = (rn(D, 3 * H) / np.sqrt(D)).astype('f')\n gru_Wh = (rn(H, 3 * H) / np.sqrt(H)).astype('f')\n gru_b = np.zeros(3 * H).astype('f')\n\n self.embed = TimeEmbedding(embed_W)\n self.gru = TimeGRU(gru_Wx, gru_Wh, gru_b, stateful=False)\n # stateful=False の理由:今回は短い時系列データが複数存在し、隠れ状態ベクトルを維持しないため\n\n self.params = self.embed.params + self.gru.params\n self.grads = self.embed.grads + self.gru.grads\n self.hs = None\n \n def forward(self, xs):\n xs = self.embed.forward(xs)\n hs = self.gru.forward(xs)\n return hs # hs の時系列データとして全て Decoder に渡す\n \n def backward(self, dhs):\n dout = self.gru.backward(dhs) # dh は Decoder より渡された勾配\n dout = self.embed.backward(dout)\n return dout\n \nclass AttentionDecoderGRU:\n def __init__(self, vocab_size, wordvec_size, hidden_size):\n V, D, H = vocab_size, wordvec_size, hidden_size\n rn = np.random.randn\n\n embed_W = (rn(V, D) / 100).astype('f')\n gru_Wx = (rn(D, 3 * H) / np.sqrt(D)).astype('f')\n gru_Wh = (rn(H, 3 * H) / np.sqrt(H)).astype('f')\n gru_b = np.zeros(3 * H).astype('f')\n affine_W = (rn(2 * H, V) / np.sqrt(2 * H)).astype('f')\n affine_b = np.zeros(V).astype('f')\n\n self.embed = TimeEmbedding(embed_W)\n self.gru = TimeGRU(gru_Wx, gru_Wh, gru_b, stateful=True)\n self.attention = TimeAttention()\n self.affine = TimeAffine(affine_W, affine_b)\n layers = [self.embed, self.gru, self.attention, self.affine]\n\n self.params, self.grads = [], []\n for layer in layers:\n self.params += layer.params\n self.grads += layer.grads\n\n def forward(self, xs, enc_hs):\n h = enc_hs[:, -1] # 一番最後の enc_hs を取り出す\n self.gru.set_state(h)\n\n out = self.embed.forward(xs)\n dec_hs = self.gru.forward(out)\n c = self.attention.forward(enc_hs, dec_hs)\n out = np.concatenate((c, dec_hs), axis=2) # self.gru で算出した dec_hs と c を連結\n score = self.affine.forward(out)\n\n return score\n\n def backward(self, dscore):\n dout = self.affine.backward(dscore)\n N, T, H2 = dout.shape\n H = H2 // 2\n\n # ①self.gru からもらった hs, attention で算出した c に分ける\n dc, ddec_hs0 = dout[:, :, :H], dout[:, :, H:]\n # ②attention に入っていった encoder の hs と decoder(self.gruで算出された) の hs に分ける\n denc_hs, ddec_hs1 = self.attention.backward(dc)\n # ①②で出した self.gru から出てきた ds0,1 を合流させる\n ddec_hs = ddec_hs0 + ddec_hs1\n dout = self.gru.backward(ddec_hs)\n dh = self.gru.dh\n denc_hs[:, -1] += dh # self.gru.dh は encoder の最後の hs であり, これも encoder へ渡す \n self.embed.backward(dout)\n\n return denc_hs\n\n def generate(self, enc_hs, start_id, sample_size):\n sampled = []\n sample_id = start_id\n h = enc_hs[:, -1]\n self.gru.set_state(h) # enc_hs の最後の h をセットする\n\n for _ in range(sample_size):\n x = np.array([sample_id]).reshape((1, 1)) # 生成物(sample_id)を入力データとして使うためのコード\n out = self.embed.forward(x)\n dec_hs = self.gru.forward(out)\n c = self.attention.forward(enc_hs, dec_hs)\n out = np.concatenate((c, dec_hs), axis=2)\n score = self.affine.forward(out)\n\n sample_id = np.argmax(score.flatten()) # argmax 今回は確率的でなく決定して出力するため\n sampled.append(sample_id)\n\n return sampled # 生成した単語のidリスト\n\n# Attention Seq2Seq\nclass AttentionSeq2seqGRU:\n def __init__(self, vocab_size, wordvec_size, hidden_size):\n args = vocab_size, wordvec_size, hidden_size\n self.encoder = AttentionEncoderGRU(*args)\n self.decoder = AttentionDecoderGRU(*args)\n self.softmax = TimeSoftmaxWithLoss()\n\n self.params = self.encoder.params + self.decoder.params\n self.grads = self.encoder.grads + self.decoder.grads\n\n def forward(self, xs, ts):\n decoder_xs, decoder_ts = ts[:, :-1], ts[:, 1:]\n\n h = self.encoder.forward(xs)\n score = self.decoder.forward(decoder_xs, h)\n loss = self.softmax.forward(score, decoder_ts)\n return loss\n\n def backward(self, dout=1):\n dout = self.softmax.backward(dout)\n dh = self.decoder.backward(dout)\n dout = self.encoder.backward(dh) # Encoder に dh を渡す\n return dout\n\n def generate(self, xs, start_id, sample_size):\n h = self.encoder.forward(xs)\n sample = self.decoder.generate(h, start_id, sample_size)\n return sample\n\n def save_params(self, file_name=None):\n if file_name is None:\n file_name = self.__class__.__name__ + '.pkl'\n\n params = [p.astype(np.float16) for p in self.params]\n\n with open(file_name, 'wb') as f:\n pickle.dump(params, f)\n\n def load_params(self, file_name=None):\n if file_name is None:\n file_name = self.__class__.__name__ + '.pkl'\n\n if '/' in file_name:\n file_name = file_name.replace('/', os.sep)\n\n if not os.path.exists(file_name):\n raise IOError('No file: ' + file_name)\n\n with open(file_name, 'rb') as f:\n params = pickle.load(f)\n\n params = [p.astype('f') for p in params]\n\n for i, param in enumerate(self.params):\n param[...] = params[i]\n\n# Trainer fit\n# データの取り出し\n(x_train, t_train), (x_test, t_test) = load_data('date.txt')\nchar_to_id, id_to_char = get_vocab()\n\n# データを反転させる(学習精度の向上)\nx_train, x_test = x_train[:, ::-1], x_test[:, ::-1]\n\nvocab_size = len(char_to_id)\nwordvec_size = 16\nhidden_size = 256\nbatch_size = 64\nmax_epoch = 4\nmax_grad = 5.0\n\nmodel = AttentionSeq2seqGRU(vocab_size, wordvec_size, hidden_size)\noptimizer = Adam()\ntrainer = Trainer(model, optimizer)\n\nacc_list = []\nfor epoch in range(max_epoch):\n trainer.fit(x_train, t_train, max_epoch=1, batch_size=batch_size, max_grad=max_grad)\n\n correct_num = 0\n for i in range(len(x_test)):\n question, correct = x_test[[i]], t_test[[i]]\n verbose = i < 10\n correct_num += eval_seq2seq(model, question, correct, id_to_char, verbose, is_reverse=True)\n\n acc = float(correct_num) / len(x_test)\n acc_list.append(acc)\n print('val acc %.3f%%' % (acc * 100))\n\nmodel.save_params()\n\n# グラフの描画(学習内容の評価)\nx = np.arange(len(acc_list))\nplt.plot(x, acc_list, marker='o')\nplt.xlabel('epochs')\nplt.ylabel('accuracy')\nplt.ylim(-0.05, 1.05)\nplt.show()\n" } ]
1
cheenwe/mm
https://github.com/cheenwe/mm
ff68a63941e0d2121dd0e1cd798ad675875a76c1
87f3769c468badad225f371fd5ba227a1de7d145
9311f08ace59100681f1e3d1cfc3cc3a97397a23
refs/heads/master
2021-01-19T03:00:54.928720
2017-04-05T15:02:13
2017-04-05T15:02:13
87,301,736
7
2
null
null
null
null
null
[ { "alpha_fraction": 0.5086241364479065, "alphanum_fraction": 0.5196550488471985, "avg_line_length": 40.20661163330078, "blob_id": "0c2c4f54c3001b5d7980f597133baa8a339b2d80", "content_id": "7cbee2838cfaa6e428a64fe3abe07ebbafd98053", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5032, "license_type": "no_license", "max_line_length": 126, "num_lines": 121, "path": "/mm.py", "repo_name": "cheenwe/mm", "src_encoding": "UTF-8", "text": "# encoding=utf-8\n\nimport re\nimport os\nimport utils\nimport urllib2\nfrom sqlhelper import SqlHelper\nfrom bs4 import BeautifulSoup as bs\n\nclass Crawler(object):\n def __init__(self):\n super(Crawler, self).__init__()\n self.album_prefix = 'https://mm.taobao.com/self/album/open_album_list.htm?_charset=utf-8&user_id%20={0}&page={1}'\n self.image_prefix = 'https://mm.taobao.com/album/json/get_album_photo_list.htm?user_id={0}&album_id={1}&page={2}'\n self.image_pattern = re.compile('''img.*290x10000.jpg''', re.U)\n self.image_name_pattern = re.compile('''\"picId\":\"(.*?)\"''', re.U)\n self.model_pattern = re.compile('''<a class=\"lady-name\" href=\"(.*?)\".*>(.*?)</a>''', re.U)\n self.album_pattern = re.compile('''.*album_id=(.*?)&.*''', re.U)\n self.links = []\n self.ids= []\n self.names= []\n self.sql = SqlHelper()\n\n\n def readHtml(self, html):\n response = urllib2.urlopen(html)\n return response.read()\n\n def getLinkIdAndNames(self, htmlData):\n items = re.findall(self.model_pattern, htmlData)\n self.links = [link for link, name in items]\n self.names = [name.decode('gbk') for link, name in items]\n self.ids = [link[link.index('=')+1:] for link in self.links]\n\n def getAlbums(self):\n for i, model_id in enumerate(self.ids):\n\n utils.log('start downloading:%s' % self.names[i])\n # print 'start downloading', self.names[i]\n\n # 插入用户\n command = self.sql.insert_data_to_users()\n msg = (model_id, self.names[i], \"\",)\n\n try:\n self.sql.insert_data(command, msg, commit = True)\n except Exception, e:\n utils.log('insert users data errors')\n\n\n for page in xrange(1, 10):\n utils.log('current page:%s' % page)\n # print 'current page', page\n\n model_url = self.album_prefix.format(model_id, page)\n soup = bs(self.readHtml(model_url), 'html.parser')\n albums = soup.find_all('div', class_ = 'mm-photo-cell-middle')\n if not albums:\n break\n for album in albums:\n album_name = album.find('h4').a.string.strip().rstrip('.')\n album_link= album.find('h4').a['href']\n album_id = re.findall(self.album_pattern, album_link)[0]\n album_create_time = album.find('p', class_ = 'mm-photo-date').string.strip(u'创建时间: ').strip(u'´´½¨Ê±¼ä:')\n album_img_count = album.find('span', class_ = 'mm-pic-number').string.strip('()').strip(u'张').strip(u'ÕÅ')\n\n # print \">>>>>>>>>>>>>>>>>>>>>>\"\n # print album.find('p', class_ = 'mm-photo-date').string\n # print album_create_time\n # print \">>>>>>>>>>>>>>>>>>>>>>\"\n\n # 插入相册\n command = self.sql.insert_data_to_albums()\n msg = (album_id, model_id, album_name, album_create_time, \"\", 1, album_img_count)\n try:\n self.sql.insert_data(command, msg, commit = True)\n except Exception, e:\n utils.log('insert albums data errors')\n\n\n utils.log('start in album:%s, total size: %s' % (album_name, album_img_count))\n\n self.getImages(model_id, album_id, album_img_count)\n\n\n def getImages(self, model_id, album_id, image_count):\n # print 'start downloading album', album_id, image_count, '张'\n for page in xrange(1, (int(image_count)-1)/16+2):\n link = self.image_prefix.format(model_id, album_id, page)\n body = self.readHtml(link).decode('gbk')\n images = re.findall(self.image_pattern, body)\n # tried to use des as names, however, it duplicates times. So i chose pic ids.\n names = re.findall(self.image_name_pattern, body)\n for idx, image in enumerate(images):\n image = image.replace('290', '620')\n try:\n img_url = ('http://'+image).replace('jpg_620x10000.jpg','jpg')\n except Exception as e:\n img_url = ('http://'+image)\n\n # id , album_id , name , url , kind\n\n # 插入图片\n command = self.sql.insert_data_to_photos()\n msg = (None, album_id, \"\", img_url, 1)\n try:\n self.sql.insert_data(command, msg, commit = True)\n except Exception, e:\n utils.log('insert photos data errors')\n\n\n # print 'created photos success'\n\n\nif __name__ == '__main__':\n test_html = 'https://mm.taobao.com/json/request_top_list.htm?page={0}'\n for page in xrange(1, 100):\n c = Crawler()\n data = c.readHtml(test_html.format(page))\n c.getLinkIdAndNames(data)\n c.getAlbums()\n" }, { "alpha_fraction": 0.5506465435028076, "alphanum_fraction": 0.5544180870056152, "avg_line_length": 32.44144058227539, "blob_id": "b825b82ca923cca1789256f9c43bf55c4aa3ef9d", "content_id": "da4fe3121802ff04ffaa605cd0424b0c6e734b3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3718, "license_type": "no_license", "max_line_length": 154, "num_lines": 111, "path": "/sqlhelper.py", "repo_name": "cheenwe/mm", "src_encoding": "UTF-8", "text": "# coding=utf-8\n\nimport utils\nimport logging\nimport config\nimport pymysql\n\nclass SqlHelper(object):\n def __init__(self):\n self.conn = pymysql.connect(**config.database_config)\n self.cursor = self.conn.cursor()\n\n try:\n self.conn.select_db(config.database)\n except:\n self.create_database()\n\n self.conn.select_db(config.database)\n\n def create_database(self):\n try:\n command = 'CREATE DATABASE IF NOT EXISTS %s DEFAULT CHARACTER SET \\'utf8\\' ' % config.database\n utils.log('create_database command:%s' % command)\n self.cursor.execute(command)\n self.conn.commit()\n except Exception, e:\n utils.log('SqlHelper create_database exception:%s' % str(e), logging.WARNING)\n\n def create_table(self, command):\n try:\n utils.log('create_table command:%s' % command)\n x = self.cursor.execute(command)\n self.conn.commit()\n return x\n except Exception, e:\n utils.log('create_table exception:%s' % str(e), logging.WARNING)\n\n def insert_data(self, command, data, commit = False):\n try:\n # utils.log('insert_data command:%s, data:%s' % (command, data))\n x = self.cursor.execute(command, data)\n if commit:\n self.conn.commit()\n return x\n except Exception, e:\n utils.log('insert_data exception msg:%s' % str(e), logging.WARNING)\n\n def commit(self):\n self.conn.commit()\n\n def execute(self, command, commit = True):\n try:\n utils.log('execute command:%s' % command)\n data = self.cursor.execute(command)\n if commit:\n self.conn.commit()\n return data\n except Exception, e:\n utils.log('execute exception msg:%s' % str(e))\n return None\n\n def query(self, command, commit = False):\n try:\n utils.log('execute command:%s' % command)\n\n self.cursor.execute(command)\n data = self.cursor.fetchall()\n if commit:\n self.conn.commit()\n return data\n except Exception, e:\n utils.log('execute exception msg:%s' % str(e))\n return None\n\n def query_one(self, command, commit = False):\n try:\n utils.log('execute command:%s' % command)\n\n self.cursor.execute(command)\n data = self.cursor.fetchone()\n if commit:\n self.conn.commit()\n\n return data\n except Exception, e:\n utils.log('execute exception msg:%s' % str(e))\n return None\n\n def insert_data_to_users(self):\n command = (\"INSERT INTO users \"\n \"(id, name, remark)\"\n \"VALUES(%s, %s, %s)\")\n return command\n\n def insert_data_to_albums(self):\n command = (\"INSERT INTO albums \"\n \"(id, user_id, name, created_at, remark, kind, total)\"\n \"VALUES(%s, %s, %s, %s, %s, %s, %s)\")\n return command\n\n def insert_data_to_photos(self):\n command = (\"INSERT INTO photos \"\n \"(id, album_id, name, url, kind)\"\n \"VALUES(%s, %s, %s, %s, %s)\")\n return command\n\n#创建表\nsql = SqlHelper()\nsql.create_table(\"create table IF NOT EXISTS users(id bigint, name varchar(255), remark text )\")\nsql.create_table(\"create table IF NOT EXISTS albums(id bigint, user_id bigint, name varchar(255), created_at date, remark text, kind int, total float) \")\nsql.create_table(\"create table IF NOT EXISTS photos(id bigint, album_id bigint, name varchar(255), url varchar(255), kind int) \")\n" }, { "alpha_fraction": 0.5344296097755432, "alphanum_fraction": 0.5632065534591675, "avg_line_length": 12.36111068725586, "blob_id": "321452a0562448915fade1a2a9394fbd0fefa602", "content_id": "d3f6da9067bcc59deb22a4c6627132e4e4736f07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1305, "license_type": "no_license", "max_line_length": 116, "num_lines": 72, "path": "/README.md", "repo_name": "cheenwe/mm", "src_encoding": "UTF-8", "text": "# MM\n爬取[淘宝MM](http://mm.taobao.com)用户、相册及图片数据, 存储到MySQL数据库中。\n\n该项目仅用于学习Python爬虫,请勿用于第三方用途。\n\n## 运行环境\npython 2.7.12\n\n### 运行依赖包\n\n* BeautifulSoup\n* pymysql\n\n\n安装命令:\n\n```\n$ pip install BeautifulSoup pymysql\n```\n\n## 下载使用\n将项目克隆到本地\n\n```\n$ git clone https://github.com/cheenwe/mm.git\n```\n\n进入工程目录\n\n```\n$ cd mm\n```\n\n修改 mysql 数据库配置 [config.py](https://github.com/cheenwe/mm/blob/master/config.py) 中 database_config 的用户名和密码为数据库的用户名和密码\n\n```\n$ nano config.py\n---------------\n\ndatabase_config = {\n\t'host': 'localhost',\n\t'port': 3306,\n\t'user': 'root',\n\t'password': '123456',\n\t'charset': 'utf8',\n}\n```\n\n运行启动脚本 mm.py 即开始抓取数据并存储到数据库中\n\n```\n$ python mm.py\n```\n查看日志文件信息\n\n```\n$tailf log/run.log\n```\n\n## 参考\n* [IPProxyPool](https://github.com/qiyeboy/IPProxyPool)\n\n\n## 项目更新\n\n-----------------------------2017-04-05----------------------------<br>\n1.添加数据库支持,存储数据到MySQL中<br>\n2.更新创建表单SQL语句<br>\n<br>\n\n-----------------------------2017-03-27----------------------------<br>\n1.实现图片下载功能<br>\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.594059407711029, "alphanum_fraction": 0.5952970385551453, "avg_line_length": 21.44444465637207, "blob_id": "0538ba6058fd8406e9e21aaacfb133fac1d77787", "content_id": "54e55059bf02afeb28795cb7c1ac4f7d9fd73b98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 824, "license_type": "no_license", "max_line_length": 98, "num_lines": 36, "path": "/utils.py", "repo_name": "cheenwe/mm", "src_encoding": "UTF-8", "text": "# encoding=utf-8\n\nimport logging\nimport os\nimport config\nimport traceback\nimport datetime\n\n\n\n\n# 自定义的日志输出\ndef log(msg, level = logging.DEBUG):\n if not os.path.exists('log'):\n os.makedirs('log')\n\n logging.basicConfig(\n filename = 'log/run.log',\n format = '%(asctime)s: %(message)s',\n level = logging.DEBUG\n )\n logging.log(level, msg)\n print('%s [%s], msg:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), level, msg))\n\n if level == logging.WARNING or level == logging.ERROR:\n for line in traceback.format_stack():\n print(line.strip())\n\n for line in traceback.format_stack():\n logging.log(level, line.strip())\n\n\ndef make_dir(dir):\n log('make dir:%s' % dir)\n if not os.path.exists(dir):\n os.makedirs(dir)\n" }, { "alpha_fraction": 0.6301369667053223, "alphanum_fraction": 0.6410958766937256, "avg_line_length": 18.210525512695312, "blob_id": "7ebb0e6bccbd1661db66c0efe6f27fd93fe4af7d", "content_id": "224eb9214892dc2351762ac81ade1e340ea9ecd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 365, "license_type": "no_license", "max_line_length": 44, "num_lines": 19, "path": "/mm_test.py", "repo_name": "cheenwe/mm", "src_encoding": "UTF-8", "text": "# encoding=utf-8\nfrom sqlhelper import SqlHelper\n\nsql = SqlHelper()\n\ndef insert_data_to_users():\n\tcommand = (\"INSERT IGNORE INTO users \"\n\t\t\t\t\t\t\"(id, name, created_at, remark)\"\n\t\t\t\t\t\t\"VALUES(%s, %s, %s, %s)\")\n\treturn command\n\n\ncommand = insert_data_to_users()\n\nmsg = (None, \"112\", \"\", \"\",)\n\nsql.insert_data(command, msg, commit = True)\n\nprint 'created user success'\n" } ]
5
eduwht/Python
https://github.com/eduwht/Python
51d8962b10479c11439c70090371262b2fdcd947
994e0a878ecedb454f747cb1e5facc6833020e33
a23f3126ab2f395827bda4806da8fe3085a78d66
refs/heads/master
2020-03-23T20:33:56.196185
2018-07-23T18:00:36
2018-07-23T18:00:36
142,048,639
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.555182695388794, "alphanum_fraction": 0.5667412281036377, "avg_line_length": 27.24210548400879, "blob_id": "5abfc9398b24d0a5562f3383b043ddb632b92185", "content_id": "04f48258c4c320377bb0c46ac41142913d973f02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2688, "license_type": "no_license", "max_line_length": 129, "num_lines": 95, "path": "/bicing_data_gather.py", "repo_name": "eduwht/Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#import requests\nimport time\nimport urllib.request, urllib.parse, urllib.error\nimport json\nimport pymysql.cursors\nimport re\nfrom datetime import datetime as dt, timedelta as td\n\ndef escriu_a_mysql(v2):\n #fem connexió\n connection = pymysql.connect(host='localhost',\n user='root',\n password='',\n db='bicing',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n\n try:\n with connection.cursor() as cursor:\n timeStp=v2['timestamp']\n\n timeStp=re.sub(r'(T)(.*)(\\..*)',r' \\2',timeStp)\n \n timeStp=dt.strptime(timeStp, \"%Y-%m-%d %H:%M:%S\")+td(hours=1)\n continue\n \n slots=(v2[\"empty_slots\"]+v2[\"free_bikes\"])\n\n #Inserir dades a la BD\n sql = \"INSERT INTO bicing_tmp (uid, slots, empty_slots, bikes, status, timestamp) \\\n VALUES (%s, %s, %s, %s, %s, %s)\" \n #executem SQL amb valors del camp \"bicing\"\n cursor.execute(sql, (v2[\"extra\"][\"uid\"], slots, v2[\"empty_slots\"], v2[\"free_bikes\"], v2[\"extra\"][\"status\"], timeStp))\n\n connection.commit()\n\n except Exception as e:\n print (e)\n\n finally:\n connection.close()\n\n return True\n\n#def check(lstr,str_j):\n# if (lstr==str_j) or not internet_on():\n# time.sleep(60)\n\n#App\ndef internet_on():\n try:\n urllib.request.urlopen('http://216.58.211.238', timeout=1)\n return True\n except urllib.request.URLError as err: \n print(err)\n return False\n\n#BICING\nurl= \"http://api.citybik.es/v2/networks/bicing\"\n\nlast_str_json = \"\"\ncont=0\nwhile True:\n origen_web = urllib.request.urlopen(url)\n # obtenim el darrer json de la web\n str_json = origen_web.read().decode()\n\n # si l'anterior json llegit és igual a l'acabat de llegir, voldrà dir que ja és a la BDD\n # esperem un minut i reiniciem el loop\n #check(last_str_json,str_json)\n if last_str_json==str_json:\n time.sleep(150)\n continue\n\n cont+=1\n print (cont)\n #print(cont + str(dt.now()))\n\n # actualizem \"last_str_json\" per al proper loop\n last_str_json = str_json\n \n #iniciem desat a base de dades\n try:\n current_dataset = json.loads(str_json)\n current_dataset=current_dataset['network']['stations']\n except Exception as e:\n current_dataset = None\n print(e)\n\n #si la comprobació es correcte, passar a l'acció\n if current_dataset != None:\n for element in current_dataset:\n\n escriu_a_mysql(element)" }, { "alpha_fraction": 0.5616059303283691, "alphanum_fraction": 0.5643746852874756, "avg_line_length": 32.42856979370117, "blob_id": "5819e98dc493d402b23c50de6b2fc4adec021da7", "content_id": "ce7494c0dfd1fdc09984d9db186bbb0b631d9e08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2169, "license_type": "no_license", "max_line_length": 130, "num_lines": 63, "path": "/bikeservices_data_gather.py", "repo_name": "eduwht/Python", "src_encoding": "UTF-8", "text": "import urllib.request, urllib.parse, urllib.error\r\nimport json\r\nimport pymysql.cursors\r\n\r\ndef mysql_bicis(name,nameservice,nbikes,nstations,lat,lon):\r\n #fem connexió\r\n conn = pymysql.connect(host='localhost',\r\n user='root',\r\n password='',\r\n db='bicing',\r\n charset='utf8mb4',\r\n cursorclass=pymysql.cursors.DictCursor)\r\n try:\r\n with conn.cursor() as cursor:\r\n print(\"%s,%s,%d,%d,%f,%f\" % (name,nameservice,nbikes,nstations,lat,lon))\r\n sql = \"INSERT INTO cities (name, serviceName, totalBikes, totalStations, latitude, longitude)\"\\\r\n \" VALUES (%s,%s,%s,%s,%s,%s)\"\r\n cursor.execute(sql, (name,nameservice,nbikes,nstations,lat,lon))\r\n\r\n conn.commit()\r\n\r\n except Exception as e:\r\n print (e)\r\n\r\n finally:\r\n conn.close()\r\n\r\n return True\r\n\r\nllistaServeis=[\"bicing\",\"bicimad\",\"velib\",\"santander-cycles\",\"oslo-bysykkel\",\"bikemi\",\"villo\",\"dublinbikes\",\"wowcycle-reykjavik\",\\\r\n\"nextbike-malta\"]\r\n\r\n# recopilació dades diferents serveis de bici\r\nfor i in llistaServeis:\r\n url = \"http://api.citybik.es/v2/networks/\"+i\r\n\r\n origen_web = urllib.request.urlopen(url)\r\n js = origen_web.read().decode()\r\n wjdata = json.loads(js)\r\n\r\n city= wjdata['network']['location']['city']\r\n nameservice=wjdata['network']['id']\r\n\r\n try:\r\n latitude=float(wjdata['network']['location']['latitude'])\r\n longitude=float(wjdata['network']['location']['longitude'])\r\n except Exception as e:\r\n print (e)\r\n\r\n wjdata=wjdata['network']['stations']\r\n\r\n nBicis=0\r\n nStations=0\r\n for elm in wjdata:\r\n if (elm['empty_slots'] != None and elm['free_bikes'] != None):\r\n es=int(elm['empty_slots'])\r\n fb=int(elm['free_bikes'])\r\n nBicis+= int(es+fb)\r\n #nForaServei+= (elm['extra']['slots']-((elm['empty-slots'])+(elm['free_bikes'])))\r\n #nCirculant+= (elm['empty-slots'])\r\n nStations+= 1\r\n\r\n mysql_bicis(city,nameservice,nBicis,nStations,latitude,longitude)" } ]
2
ravisharma607/Faulty-Calculator
https://github.com/ravisharma607/Faulty-Calculator
8f74d7fb789eb8ee94bd07e1686c87f73e348caf
39e3f7bf0e06d3d748b749b1422a1f78eeafabb4
f8324d0b1fbb5da94137dd3d6a9180ca681979c6
refs/heads/master
2023-07-31T21:35:22.522808
2021-09-12T09:07:58
2021-09-12T09:07:58
405,594,956
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4596949815750122, "alphanum_fraction": 0.5185185074806213, "avg_line_length": 37.29166793823242, "blob_id": "0f902160ea2827d12bf2b36b129b7c0d2a34a4c6", "content_id": "b3fa280478b89a21051a6245e11008f4f5b08e87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 918, "license_type": "no_license", "max_line_length": 142, "num_lines": 24, "path": "/faultyCalcy.py", "repo_name": "ravisharma607/Faulty-Calculator", "src_encoding": "UTF-8", "text": "\"\"\" Q->) design a calculator which will correctly solve all the problem except the following one\n 45*3 = 123, 85+2 = 546, 33-23 = 582 | your program should take operator and two numbers as input from the user and then return the result \"\"\"\ntry:\n num1 = int(input(\"enter first number:\"))\n num2 = int(input(\"enter second number:\"))\n op = input(\"choose operatot => | +, -, *, /| :\")\n if (num1 == 45 and num2 == 3 or num1 == 85 and num2 == 2 or num1 == 33 and num2 == 23):\n if op == \"+\":\n print(546)\n elif op == \"-\":\n print(582)\n elif op == \"*\":\n print(123)\n else:\n if op == \"+\":\n print(num1 + num2)\n elif op == \"-\":\n print(num1 - num2)\n elif op == \"*\":\n print(num1 * num2)\n elif op == \"/\":\n print(num1 / num2)\nexcept Exception as e:\n print(\"Please Enter a Valid Integer Value\")" } ]
1
dabercro/Xbb
https://github.com/dabercro/Xbb
68df7abc4146c0cef87452e2182aef4d00bf65b3
9407b6adf79ecb7fa5c9c66ba9f29248683f9ff4
be4c7e89c046a32fa8e48c7d81bd21c3fd8c2dd4
refs/heads/master
2022-12-09T03:48:27.988073
2020-08-20T11:44:20
2020-08-20T11:44:20
265,004,434
0
0
null
2020-05-18T16:57:17
2018-05-08T20:58:59
2018-06-28T18:46:48
null
[ { "alpha_fraction": 0.6630383133888245, "alphanum_fraction": 0.8452437520027161, "avg_line_length": 56.876712799072266, "blob_id": "22f1f8c2da93ef2a01d68f2837e1e01e37ceebac", "content_id": "12ebc49c0fda02428df1d78832d2cafb7351a414", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 4226, "license_type": "no_license", "max_line_length": 88, "num_lines": 73, "path": "/python/Zll2017config/hadd.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "# V11\n[Hadd]\nZJetsToNuNu_HT-800To1200_13TeV-madgraph: 10667\nQCD_HT200to300_TuneCP5_13TeV-madgraph-pythia8: 28000\nWplusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8: 466\nTTTo2L2Nu_TuneCP5_PSweights_13TeV-powheg-pythia8: 1\nTTToSemiLeptonic_TuneCP5_PSweights_13TeV-powheg-pythia8: 35\nWminusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8: 471\nDYJetsToLL_M-4to50_HT-200to400_TuneCP5_13TeV-madgraphMLM-pythia8: 2\nWJetsToLNu_BGenFilter_Wpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 1343\nDYJetsToLL_M-4to50_HT-600toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 2\nggZH_HToBB_ZToLL_M125_13TeV_powheg_pythia8: 1\nDoubleMuon: 2\nWZTo1L1Nu2Q_13TeV_amcatnloFXFX_madspin_pythia8: 259\nWJetsToLNu_HT-1200To2500_TuneCP5_13TeV-madgraphMLM-pythia8: 289\nDYJetsToLL_M-4to50_HT-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYJetsToLL_M-50_HT-1200to2500_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZJetsToNuNu_HT-400To600_13TeV-madgraph: 34667\nZJetsToNuNu_BGenFilter_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 9999\nWBJetsToLNu_Wpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 768\nDYJetsToLL_M-50_HT-2500toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYBJetsToLL_M-50_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 5\nDYJetsToLL_M-4to50_HT-400to600_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYJetsToLL_M-50_TuneCP5_13TeV-madgraphMLM-pythia8: 2\nZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8: 69334\nZBJetsToNuNu_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 98667\nWJetsToLNu_HT-200To400_TuneCP5_13TeV-madgraphMLM-pythia8: 480\nZBJetsToNuNu_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 9999\nTTToHadronic_TuneCP5_PSweights_13TeV-powheg-pythia8: 426\nST_t-channel_antitop_4f_InclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8: 73\nWBJetsToLNu_Wpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 1434\nZJetsToNuNu_HT-2500ToInf_13TeV-madgraph: 9999\nWJetsToLNu_BGenFilter_Wpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 2250\nWZ_TuneCP5_13TeV-pythia8: 2\nQCD_HT2000toInf_TuneCP5_13TeV-madgraph-pythia8: 1600\nWW_TuneCP5_13TeV-pythia8: 15\nDYJetsToLL_M-50_HT-800to1200_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZZ_TuneCP5_13TeV-pythia8: 2\nQCD_HT500to700_TuneCP5_13TeV-madgraph-pythia8: 3479\nDYJetsToLL_M-50_HT-200to400_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nWJetsToLNu_HT-400To600_TuneCP5_13TeV-madgraphMLM-pythia8: 436\nDYJetsToLL_M-50_HT-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYBJetsToLL_M-50_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 1\nZJetsToNuNu_HT-100To200_13TeV-madgraph: 9999\nQCD_HT1000to1500_TuneCP5_13TeV-madgraph-pythia8: 10000\nZJetsToNuNu_HT-1200To2500_13TeV-madgraph: 9999\nQCD_HT300to500_TuneCP5_13TeV-madgraph-pythia8: 4149\nDYJetsToLL_BGenFilter_Zpt-100to200_M-50_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 2\nWJetsToLNu_HT-800To1200_TuneCP5_13TeV-madgraphMLM-pythia8: 437\nST_tW_antitop_5f_inclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8: 3\nQCD_HT700to1000_TuneCP5_13TeV-madgraph-pythia8: 7423\nZH_HToBB_ZToLL_M125_13TeV_powheg_pythia8: 1\nZJetsToNuNu_HT-200To400_13TeV-madgraph: 56000\nQCD_HT1500to2000_TuneCP5_13TeV-madgraph-pythia8: 1186\nZJetsToNuNu_BGenFilter_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 9999\nDYJetsToLL_M-50_HT-600to800_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYJetsToLL_M-50_HT-400to600_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nST_tW_top_5f_inclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8: 4\nWWTo1L1Nu2Q_13TeV_amcatnloFXFX_madspin_pythia8: 4\nST_s-channel_4f_leptonDecays_TuneCP5_PSweights_13TeV-amcatnlo-pythia8: 101\nWJetsToLNu_HT-2500ToInf_TuneCP5_13TeV-madgraphMLM-pythia8: 304\nDYJetsToLL_BGenFilter_Zpt-200toInf_M-50_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 4\nWJetsToLNu_HT-600To800_TuneCP5_13TeV-madgraphMLM-pythia8: 344\nZJetsToNuNu_HT-600To800_13TeV-madgraph: 24000\nWJetsToLNu_HT-100To200_TuneCP5_13TeV-madgraphMLM-pythia8: 1064\nDoubleEG: 3\nQCD_HT100to200_TuneCP5_13TeV-madgraph-pythia8: 64000\nggZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8: 24000\nZZTo4L_13TeV_powheg_pythia8: 1\nST_t-channel_top_4f_InclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8: 234\nWJetsToLNu_TuneCP5_13TeV-madgraphMLM-pythia8: 12062\nZZTo2L2Q_13TeV_amcatnloFXFX_madspin_pythia8: 1\nDYJetsToLL_M-50_TuneCP5_13TeV-amcatnloFXFX-pythia8: 1\n\n" }, { "alpha_fraction": 0.696753740310669, "alphanum_fraction": 0.7133808135986328, "avg_line_length": 28.372093200683594, "blob_id": "e4a24a2b5aa2b6d119d4ceef9fde4fb476038c81", "content_id": "d17781845ec5ad5d67b22d3bf1a9176bdc77733f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1263, "license_type": "no_license", "max_line_length": 195, "num_lines": 43, "path": "/python/runMIT.sh", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\ntag=$1\nsample=$2\nfilelist=$3\npart=$4\n\nexport SCRAM_ARCH=slc6_amd64_gcc630\nexport CMSSW_VER=CMSSW_10_1_0\n\nsource /cvmfs/cms.cern.ch/cmsset_default.sh\n\nscramv1 project CMSSW $CMSSW_VER\n\ncd $CMSSW_VER\n\ntar -xf ../xbb_condor.tgz\n\ncd src\neval `scram runtime -sh`\n\ncd Xbb/python\n\n./runAll.sh run_${sample}_part$part $tag run 1 noid --inputDir=PREPin --sampleIdentifier=$sample --addCollections=Prep.VHbb --fileList=$filelist --outputDir=PREPout --noretry\n\n./runAll.sh sysnew_${sample}_part$part $tag sysnew 1 noid --inputDir=SYSin --sampleIdentifier=$sample --addCollections=Sys.all --fileList=$filelist --outputDir=SYSout --noretry\n\nif [ \"$(expr substr $tag 1 3)\" = \"Zll\" ]\nthen\n\n ./runAll.sh run_${sample}_part$part $tag run 1 noid --inputDir=KINFITin --sampleIdentifier=$sample --addCollections=KinematicFit.fitter --fileList=$filelist --outputDir=KINFITout --noretry\n\nfi\n\nif [ \"$(./submitMIT.py -T $tag -c 'Directories:CONDORin')\" = \"$(./submitMIT.py -T $tag -c 'Directories:MVAout')\" ]\nthen\n\n ./runAll.sh run_${sample}_part$part $tag run 1 noid --inputDir=MVAin --sampleIdentifier=$sample --addCollections=Eval.VH --fileList=$filelist --outputDir=MVAout --noretry\n\nfi\n\npwd\nfind $(./submitMIT.py -T $tag -c 'Directories:CONDORin') -type f\n" }, { "alpha_fraction": 0.7170731425285339, "alphanum_fraction": 0.7707316875457764, "avg_line_length": 38.315067291259766, "blob_id": "c3887b4023bf7ecde86bd3e9b8800596ee6356c6", "content_id": "ee2c63441e6dc654fc667565887adbb0f105fed6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 2870, "license_type": "no_license", "max_line_length": 393, "num_lines": 73, "path": "/python/Zll2018config/paths.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "[Configuration]\n#!! List of the config you want to use\n#!! The list only support spaces between configs\nList = paths.ini ../VHbb2018commonconfig/general.ini general.ini ../Zll2018config/cuts.ini training_WP.ini ../VHbb2018commonconfig/systematics.ini datacards.ini plots.ini lhe_weights.ini ../VHbb2018commonconfig/samples_mc.ini ../VHbb2018commonconfig/stxs.ini data.ini ../VHbb2018commonconfig/vhbbPlotDef.ini vhbbPlotDef.ini fit.ini volatile.ini ../VHbb2018commonconfig/EventCounts2018V12.ini \n\nchannel = Zll\n\n# general config\n#whereToLaunch = PSI\nwhereToLaunch = auto\nuser = %(USER)s\ncmsswbase = %(CMSSW_BASE)s\n\n# Xrootd config, first redirector is the primary one if multiple ones are given\nxrootdRedirectors = eoscms.cern.ch\nxrootdRedirectorGlobal = root://eoscms.cern.ch/\npnfsStoragePath = .\n\n[Directories]\nDname = logs_Zll2018\nWdir = <!Configuration|cmsswbase!>/src/\nvhbbpath = <!Directories|Wdir!>/Xbb\ntagDir = <!Directories|vhbbpath!>/python/<!Directories|Dname!>/\nscratch = scratch\nsamplepath = <!Directories|plottingSamples!>\n\n# original samples\n#samplefiles = <!Configuration|cmsswbase!>/src/Xbb/samples/VHbbPostNano2018_V4_2/merged_Zll2018/\n#samplefiles_split = <!Configuration|cmsswbase!>/src/Xbb/samples/VHbbPostNano2018_V4_2/\n\n#VHbbPostNano2018_V6_V1_Zll/merged_Zll2018/\n#VHbbPostNano2018_V4_2/merged_Zll2018/\nsamplefiles = <!Configuration|cmsswbase!>/src/Xbb/samples/VHbbPostNano2018_V12\nsamplefiles_split = <!Configuration|cmsswbase!>/src/Xbb/samples/VHbbPostNano2018_V6_V1_Zll\n#VHbbPostNano2018_V4_2/\n\n;!! from which samples to plot and where to save the plots\n;plottingSamples: <!Directories|SYSoutV12v1!> \n;plottingSamples: <!Directories|KINFITMERGEout!> \n;plottingSamples: <!Directories|MVAout!> \n;plottingSamples: <!Directories|MVAout!> \n;plottingSamples: <!Directories|SYSout!> \nplottingSamples: <!Directories|CONDORout!>\n\n;#!! cached files\ntmpSamples = /data/t3home000/dabercro/Xbb/Zll2018_tmp\n\n#!! from which samples to make the DCs and where to save the DCs\ndcSamples: <!Directories|CONDORout!> \n\nPREPin: root://eoscms.cern.ch/\nPREPout: prep\n\nHADDin: <!Directories|PREPout!>\nHADDout: prep\n\nSYSin: <!Directories|PREPout!>\nSYSout: sys\n\nKINFITin: <!Directories|SYSout!>\nKINFITout: kinfit\n\nKINFITMERGEin: <!Directories|KINFITin!>\nKINFITMERGEbase: root://t3dcachedb03.psi.ch:1094//pnfs/psi.ch/cms/trivcat/store/user/<!Configuration|user!>/VHbb/Zll/VHbbPostNano2018/kinfit/23mar20\n\nKINFITMERGEout: root://t3dcachedb03.psi.ch:1094//pnfs/psi.ch/cms/trivcat/store/user/<!Configuration|user!>/VHbb/Zll/VHbbPostNano2018/kinfit/23mar20/\nKINFITMERGEoutv1: root://t3dcachedb03.psi.ch:1094//pnfs/psi.ch/cms/trivcat/store/user/<!Configuration|user!>/VHbb/Zll/VHbbPostNano2018/kinfit/23mar20v2/\n\nMVAin: <!Directories|KINFITout!>\nMVAout: mva\n\nCONDORin = kinfit\nCONDORout = /mnt/hadoop/scratch/dabercro/Xbb/Zll2018\n" }, { "alpha_fraction": 0.5370185375213623, "alphanum_fraction": 0.6805902719497681, "avg_line_length": 21.44382095336914, "blob_id": "bd4e0998bd74772f798f6346c19b4b27d22314c9", "content_id": "2af08c770ea65b7eb63e40fb513e4e6b96ce8f9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 3998, "license_type": "no_license", "max_line_length": 284, "num_lines": 178, "path": "/python/Zvv2017config/vhbbPlotDef.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "[General]\nBDTbins = 15\n\n# Plot Definitions\n\n# use wider range in 0-lepton\n[plotDef:MET]\nrelPath = MET_Pt\nxAxis = MET p_{T} [GeV] (corrected & smeared)\nnBins = 45\nmin = 0\nmax = 450\n\n[plotDef:CRDNN]\nxAxis = CRDNN \nrelPath = <!Zhf_medhigh_Znn|branchName!>.Nominal \nnBins = 8\nmin = 0\nmax = 8\n\n[plotDef:CRDNN_high]\nxAxis = CRDNN (high)\nrelPath = <!Zhf_high_Znn|branchName!>.Nominal \nnBins = 6\nmin = 0\nmax = 6\n\n[plotDef:CRDNN_high_mjj]\nxAxis = CRDNN (high)\nrelPath = <!Zhf_high_Znn|branchName!>.Nominal+(H_mass>90)*4+(H_mass<=90&&<!Zhf_high_Znn|branchName!>.Nominal>=4.0)*4 \nnBins = 10\nmin = 0\nmax = 10\n\n[plotDef:VV_CRDNN_high]\nxAxis = VZ CRDNN (high)\nrelPath = <!VV_Zhf_high_Znn|branchName!>.Nominal \nnBins = 5\nmin = 0\nmax = 5\n\n\n[plotDef:CRDNN_med_0j]\nxAxis = CRDNN (med, 0j)\nrelPath = <!Zhf_med_Znn|branchName!>.Nominal \nnBins = 5\nmin = 0\nmax = 5\n\n[plotDef:CRDNN_med_ge1j]\nxAxis = CRDNN (med, >=1 j)\nrelPath = <!Zhf_med_Znn|branchName!>.Nominal \nnBins = 5\nmin = 0\nmax = 5\n\n[plotDef:CRDNN_med]\nxAxis = CRDNN (med)\nrelPath = <!Zhf_med_Znn|branchName!>.Nominal \nnBins = 6\nmin = 0\nmax = 6\n\n[plotDef:CRDNN_med_mjj]\nxAxis = CRDNN (med)\nrelPath = <!Zhf_med_Znn|branchName!>.Nominal+(H_mass>90)*4+(H_mass<=90&&<!Zhf_med_Znn|branchName!>.Nominal>=4.0)*4 \nnBins = 10\nmin = 0\nmax = 10\n\n\n[plotDef:CRDNN_med_fine]\nxAxis = CRDNN (med)\nrelPath = <!Zhf_med_Znn|branchName!>.Nominal \nnBins = 5\nmin = 0\nmax = 5\n#binList = <!Zhf_med_Znn|bins!>\nbinList = [0.0, 0.35662203775888796, 0.4051809301159696, 1.0, 1.3495357892757025, 1.3978901888266408, 2.0, 2.3125765463736134, 2.3780697227013587, 3.0, 3.424002261440659, 3.569156441127205, 4.0, 4.333468404010809, 4.407281374295103, 5.0, 5.398235786631016, 5.535963939930132, 6.00001]\nplotEqualSize = True\n\n\n[plotDef:VV_CRDNN_med]\nxAxis = VZ CRDNN (med)\nrelPath = <!VV_Zhf_med_Znn|branchName!>.Nominal \nnBins = 5\nmin = 0\nmax = 5\n\n\n\n[plotDef:CRDNNfine]\nxAxis = CRDNN\nrelPath = <!Zhf_medhigh_Znn|branchName!>.Nominal \nnBins = 80\nmin = 0\nmax = 8\nlog = True\n\n[plotDef:multiDNN]\nxAxis = multi\nrelPath = <!Multi_medhigh_Znn|branchName!>.Nominal\nnBins = 65\nmin = 0.0\nmax = 11.0\nlog = True\nbinList = <!Multi_medhigh_Znn|bins!> \nplotEqualSize = True\nvisualizeBlindCutThreshold = 9.5\n\n[plotDef:multiDNN_Background]\nxAxis = multi\nrelPath = <!Multi_medhigh_Znn|branchName!>.Nominal\nmin = 0.0\nmax = 10.0\nlog = True\nbinList = <!Multi|binsCR!> \nplotEqualSize = True\nvisualizeBlindCutThreshold = 9.5\n\n[plotDef:multiDNN_SIG]\nxAxis = multiDNN signal\nrelPath = <!dc:Multi_medhigh_Znn_SIG|var!>\nmin = 10.0\nmax = 11.0\nlog = True\nbinList = <!dc:Multi_medhigh_Znn_SIG|rebin_list!>\nplotEqualSize = True\n\n\n[plotDef:DNN]\nrelPath = <!SR_medhigh_Znn|branchName!>.Nominal\nxAxis = DNN (final binning) \nnBins = 15\nmin = 0.0\nmax = 1.0\nlog = True\nbinList = <!SR_medhigh_Znn|bins!> \nplotEqualSize = True\nvisualizeBlindCutThreshold = 0.6\n\n[plotDef:VV_DNN]\n#VV_SR_medhigh_Znn\nrelPath = <!VV_SR_medhigh_Znn|branchName!>.Nominal\nxAxis = VZ DNN (final binning) \nnBins = 15\nmin = 0.0\nmax = 1.0\nlog = True\nbinList = <!VV_SR_medhigh_Znn|bins!> \nplotEqualSize = True\nvisualizeBlindCutThreshold = 0.6\n\n\n[plotDef:VVDNN]\nrelPath = <!VV_SR_medhigh_Znn|branchName!>.Nominal\nxAxis = VZ DNN (final binning)\nnBins = 15\nmin = 0.0\nmax = 1.0\nlog = True\nbinList = <!dc:Limit_VV_Signal|rebin_list!>\nplotEqualSize = True\nvisualizeBlindCutThreshold = 0.6\n\n[plotDef:BDT_Zvv_BOOSTFinal_wdB]\nrelPath = BDT_Zvv_BOOSTFinal_wdB.Nominal\nxAxis = BDT_Zvv_BOOSTFinal_wdB\nnBins = 15000\nmin = -1\nmax = 1\nlog = True\nplotEqualSize = True\n# gauss signal:\n#rebinMethod = [0.169, 0.2454, 0.3411, 0.4538, 0.5777, 0.7039, 0.8208, 0.916, 0.9783, 1., 0.9783, 0.916, 0.8208, 0.7039, 0.5777]\n# arctan\n#rebinMethod = [0.1092, 0.1358, 0.1778, 0.25, 0.3789, 0.5628, 0.7148, 0.8026, 0.8524, 0.8831, 0.9036, 0.9181, 0.9289, 0.9372, 0.9438]\nbinList = [-1.00000, -0.04800, -0.00480, 0.02973, 0.07307, 0.12907, 0.21987, 0.30813, 0.37093, 0.42600, 0.46773, 0.50573, 0.53427, 0.56347, 0.60147, 1.00001] \n\n\n" }, { "alpha_fraction": 0.6023220419883728, "alphanum_fraction": 0.6516149640083313, "avg_line_length": 34.15536880493164, "blob_id": "fb49f62faf17c2eb3fbc6bd320550c12d3d21bdc", "content_id": "20d47da7ef651ef19129a913876ff0bd3f92464f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 24892, "license_type": "no_license", "max_line_length": 414, "num_lines": 708, "path": "/python/Zvv2016config/datacards.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "[LimitGeneral]\n\nreplace_cut_base_vector = [\n 'V_pt>MET_pt_{syst}{UD}',\n 'V_phi>MET_phi_{syst}{UD}',\n ]\nreplace_cut_unclustEn = [\n 'MET_Pt>MET_pt_unclustEn{UD}',\n 'MET_Phi>MET_phi_unclustEn{UD}',\n 'V_pt>MET_pt_unclustEn{UD}',\n 'V_phi>MET_phi_unclustEn{UD}',\n 'MET_sig30puid>MET_sig30puid_{syst}_{UD}',\n ]\n;IMPORTANT: this has to be exacly the same as the variable in vhbbPlotDef for the pre/postfit macro to work\n;Ragne for mjj datacards\nMass = H_mass\nMassRange = 17,0,255\nMassRangeVV = 34,0, 255\n\n;!! --------------------------------------\n;!! Systematics\n;!! --------------------------------------\nremove_systematics = True\n\nsys_cr = [\n 'jer',\n 'jerReg',\n 'jesAbsoluteStat',\n 'jesAbsoluteScale',\n 'jesAbsoluteMPFBias',\n 'jesFragmentation',\n 'jesSinglePionECAL',\n 'jesSinglePionHCAL',\n 'jesFlavorQCD',\n 'jesRelativeJEREC1',\n 'jesRelativeJEREC2',\n 'jesRelativeJERHF',\n 'jesRelativePtBB',\n 'jesRelativePtEC1',\n 'jesRelativePtEC2',\n 'jesRelativePtHF',\n 'jesRelativeBal',\n 'jesRelativeFSR',\n 'jesRelativeStatFSR',\n 'jesRelativeStatEC',\n 'jesRelativeStatHF',\n 'jesPileUpDataMC',\n 'jesPileUpPtRef',\n 'jesPileUpPtBB',\n 'jesPileUpPtEC1',\n 'jesPileUpPtEC2',\n 'jesPileUpPtHF',\n 'jesPileUpMuZero',\n 'jesPileUpEnvelope',\n 'unclustEn',\n 'jmr',\n 'jms',\n ]\n\nsys_BDT = <!LimitGeneral|sys_cr!>\nsys_Mjj = <!LimitGeneral|sys_cr!>\n\nweightF_sys = [\n;top pt reweighting\n 'CMS_vhbb_topptreweighting_13TeV',\n; LO to NLO weight\n 'CMS_vhbb_vjetnlodetajjrw_13TeV',\n; Pileup\n 'CMS_vhbb_puWeight',\n; n add jets\n 'CMS_vhbb_ttbar_nAddJets',\n; Jet PU ID\n 'CMS_vhbb_jetPUID',\n; LHE scale\n 'CMS_LHE_weights_scale_muR_ZH',\n 'CMS_LHE_weights_scale_muR_WH',\n 'CMS_LHE_weights_scale_muR_ggZH',\n 'CMS_LHE_weights_scale_muR_TT',\n 'CMS_LHE_weights_scale_muR_Zj0b',\n 'CMS_LHE_weights_scale_muR_Zj1b',\n 'CMS_LHE_weights_scale_muR_Zj2b',\n 'CMS_LHE_weights_scale_muR_Wj0b',\n 'CMS_LHE_weights_scale_muR_Wj1b',\n 'CMS_LHE_weights_scale_muR_Wj2b',\n; 'CMS_LHE_weights_scale_muR_VVHF',\n; 'CMS_LHE_weights_scale_muR_VVLF',\n 'CMS_LHE_weights_scale_muF_ZH',\n 'CMS_LHE_weights_scale_muF_WH',\n 'CMS_LHE_weights_scale_muF_ggZH',\n 'CMS_LHE_weights_scale_muF_TT',\n 'CMS_LHE_weights_scale_muF_Zj0b',\n 'CMS_LHE_weights_scale_muF_Zj1b',\n 'CMS_LHE_weights_scale_muF_Zj2b',\n 'CMS_LHE_weights_scale_muF_Wj0b',\n 'CMS_LHE_weights_scale_muF_Wj1b',\n 'CMS_LHE_weights_scale_muF_Wj2b',\n; 'CMS_LHE_weights_scale_muF_VVHF',\n; 'CMS_LHE_weights_scale_muF_VVLF',\n; EWK signal correction\n 'CMS_vhbb_signal_ewk_13TeV',\n 'CMS_vhbb_VJets_ewk_13TeV',\n 'CMS_vhbb_Vjets_pdfwgt_0lep',\n 'CMS_vhbb_Vjets_pdfwgt_1lep',\n 'CMS_vhbb_Vjets_pdfwgt_2lep',\n; Prefire correction\n 'CMS_vhbb_PrefireWeight_13TeV',\n; MET SF\n; small -> use 0.5% global uncert. \n; btag\n 'CMS_bTagWeightDeepBJES_13TeV_pt0_eta0',\n 'CMS_bTagWeightDeepBJES_13TeV_pt0_eta1',\n 'CMS_bTagWeightDeepBJES_13TeV_pt0_eta2',\n 'CMS_bTagWeightDeepBJES_13TeV_pt1_eta0',\n 'CMS_bTagWeightDeepBJES_13TeV_pt1_eta1',\n 'CMS_bTagWeightDeepBJES_13TeV_pt1_eta2',\n 'CMS_bTagWeightDeepBJES_13TeV_pt2_eta0',\n 'CMS_bTagWeightDeepBJES_13TeV_pt2_eta1',\n 'CMS_bTagWeightDeepBJES_13TeV_pt2_eta2',\n 'CMS_bTagWeightDeepBJES_13TeV_pt3_eta0',\n 'CMS_bTagWeightDeepBJES_13TeV_pt3_eta1',\n 'CMS_bTagWeightDeepBJES_13TeV_pt3_eta2',\n 'CMS_bTagWeightDeepBJES_13TeV_pt4_eta0',\n 'CMS_bTagWeightDeepBJES_13TeV_pt4_eta1',\n 'CMS_bTagWeightDeepBJES_13TeV_pt4_eta2',\n 'CMS_bTagWeightDeepBLF_13TeV_pt0_eta0',\n 'CMS_bTagWeightDeepBLF_13TeV_pt0_eta1',\n 'CMS_bTagWeightDeepBLF_13TeV_pt0_eta2',\n 'CMS_bTagWeightDeepBLF_13TeV_pt1_eta0',\n 'CMS_bTagWeightDeepBLF_13TeV_pt1_eta1',\n 'CMS_bTagWeightDeepBLF_13TeV_pt1_eta2',\n 'CMS_bTagWeightDeepBLF_13TeV_pt2_eta0',\n 'CMS_bTagWeightDeepBLF_13TeV_pt2_eta1',\n 'CMS_bTagWeightDeepBLF_13TeV_pt2_eta2',\n 'CMS_bTagWeightDeepBLF_13TeV_pt3_eta0',\n 'CMS_bTagWeightDeepBLF_13TeV_pt3_eta1',\n 'CMS_bTagWeightDeepBLF_13TeV_pt3_eta2',\n 'CMS_bTagWeightDeepBLF_13TeV_pt4_eta0',\n 'CMS_bTagWeightDeepBLF_13TeV_pt4_eta1',\n 'CMS_bTagWeightDeepBLF_13TeV_pt4_eta2',\n 'CMS_bTagWeightDeepBHF_13TeV_pt0_eta0',\n 'CMS_bTagWeightDeepBHF_13TeV_pt0_eta1',\n 'CMS_bTagWeightDeepBHF_13TeV_pt0_eta2',\n 'CMS_bTagWeightDeepBHF_13TeV_pt1_eta0',\n 'CMS_bTagWeightDeepBHF_13TeV_pt1_eta1',\n 'CMS_bTagWeightDeepBHF_13TeV_pt1_eta2',\n 'CMS_bTagWeightDeepBHF_13TeV_pt2_eta0',\n 'CMS_bTagWeightDeepBHF_13TeV_pt2_eta1',\n 'CMS_bTagWeightDeepBHF_13TeV_pt2_eta2',\n 'CMS_bTagWeightDeepBHF_13TeV_pt3_eta0',\n 'CMS_bTagWeightDeepBHF_13TeV_pt3_eta1',\n 'CMS_bTagWeightDeepBHF_13TeV_pt3_eta2',\n 'CMS_bTagWeightDeepBHF_13TeV_pt4_eta0',\n 'CMS_bTagWeightDeepBHF_13TeV_pt4_eta1',\n 'CMS_bTagWeightDeepBHF_13TeV_pt4_eta2',\n 'CMS_bTagWeightDeepBLFStats1_13TeV_pt0_eta0',\n 'CMS_bTagWeightDeepBLFStats1_13TeV_pt0_eta1',\n 'CMS_bTagWeightDeepBLFStats1_13TeV_pt0_eta2',\n 'CMS_bTagWeightDeepBLFStats1_13TeV_pt1_eta0',\n 'CMS_bTagWeightDeepBLFStats1_13TeV_pt1_eta1',\n 'CMS_bTagWeightDeepBLFStats1_13TeV_pt1_eta2',\n 'CMS_bTagWeightDeepBLFStats1_13TeV_pt2_eta0',\n 'CMS_bTagWeightDeepBLFStats1_13TeV_pt2_eta1',\n 'CMS_bTagWeightDeepBLFStats1_13TeV_pt2_eta2',\n 'CMS_bTagWeightDeepBLFStats1_13TeV_pt3_eta0',\n 'CMS_bTagWeightDeepBLFStats1_13TeV_pt3_eta1',\n 'CMS_bTagWeightDeepBLFStats1_13TeV_pt3_eta2',\n 'CMS_bTagWeightDeepBLFStats1_13TeV_pt4_eta0',\n 'CMS_bTagWeightDeepBLFStats1_13TeV_pt4_eta1',\n 'CMS_bTagWeightDeepBLFStats1_13TeV_pt4_eta2',\n 'CMS_bTagWeightDeepBLFStats2_13TeV_pt0_eta0',\n 'CMS_bTagWeightDeepBLFStats2_13TeV_pt0_eta1',\n 'CMS_bTagWeightDeepBLFStats2_13TeV_pt0_eta2',\n 'CMS_bTagWeightDeepBLFStats2_13TeV_pt1_eta0',\n 'CMS_bTagWeightDeepBLFStats2_13TeV_pt1_eta1',\n 'CMS_bTagWeightDeepBLFStats2_13TeV_pt1_eta2',\n 'CMS_bTagWeightDeepBLFStats2_13TeV_pt2_eta0',\n 'CMS_bTagWeightDeepBLFStats2_13TeV_pt2_eta1',\n 'CMS_bTagWeightDeepBLFStats2_13TeV_pt2_eta2',\n 'CMS_bTagWeightDeepBLFStats2_13TeV_pt3_eta0',\n 'CMS_bTagWeightDeepBLFStats2_13TeV_pt3_eta1',\n 'CMS_bTagWeightDeepBLFStats2_13TeV_pt3_eta2',\n 'CMS_bTagWeightDeepBLFStats2_13TeV_pt4_eta0',\n 'CMS_bTagWeightDeepBLFStats2_13TeV_pt4_eta1',\n 'CMS_bTagWeightDeepBLFStats2_13TeV_pt4_eta2',\n 'CMS_bTagWeightDeepBHFStats1_13TeV_pt0_eta0',\n 'CMS_bTagWeightDeepBHFStats1_13TeV_pt0_eta1',\n 'CMS_bTagWeightDeepBHFStats1_13TeV_pt0_eta2',\n 'CMS_bTagWeightDeepBHFStats1_13TeV_pt1_eta0',\n 'CMS_bTagWeightDeepBHFStats1_13TeV_pt1_eta1',\n 'CMS_bTagWeightDeepBHFStats1_13TeV_pt1_eta2',\n 'CMS_bTagWeightDeepBHFStats1_13TeV_pt2_eta0',\n 'CMS_bTagWeightDeepBHFStats1_13TeV_pt2_eta1',\n 'CMS_bTagWeightDeepBHFStats1_13TeV_pt2_eta2',\n 'CMS_bTagWeightDeepBHFStats1_13TeV_pt3_eta0',\n 'CMS_bTagWeightDeepBHFStats1_13TeV_pt3_eta1',\n 'CMS_bTagWeightDeepBHFStats1_13TeV_pt3_eta2',\n 'CMS_bTagWeightDeepBHFStats1_13TeV_pt4_eta0',\n 'CMS_bTagWeightDeepBHFStats1_13TeV_pt4_eta1',\n 'CMS_bTagWeightDeepBHFStats1_13TeV_pt4_eta2',\n 'CMS_bTagWeightDeepBHFStats2_13TeV_pt0_eta0',\n 'CMS_bTagWeightDeepBHFStats2_13TeV_pt0_eta1',\n 'CMS_bTagWeightDeepBHFStats2_13TeV_pt0_eta2',\n 'CMS_bTagWeightDeepBHFStats2_13TeV_pt1_eta0',\n 'CMS_bTagWeightDeepBHFStats2_13TeV_pt1_eta1',\n 'CMS_bTagWeightDeepBHFStats2_13TeV_pt1_eta2',\n 'CMS_bTagWeightDeepBHFStats2_13TeV_pt2_eta0',\n 'CMS_bTagWeightDeepBHFStats2_13TeV_pt2_eta1',\n 'CMS_bTagWeightDeepBHFStats2_13TeV_pt2_eta2',\n 'CMS_bTagWeightDeepBHFStats2_13TeV_pt3_eta0',\n 'CMS_bTagWeightDeepBHFStats2_13TeV_pt3_eta1',\n 'CMS_bTagWeightDeepBHFStats2_13TeV_pt3_eta2',\n 'CMS_bTagWeightDeepBHFStats2_13TeV_pt4_eta0',\n 'CMS_bTagWeightDeepBHFStats2_13TeV_pt4_eta1',\n 'CMS_bTagWeightDeepBHFStats2_13TeV_pt4_eta2',\n 'CMS_bTagWeightDeepBcErr1_13TeV_pt0_eta0',\n 'CMS_bTagWeightDeepBcErr1_13TeV_pt0_eta1',\n 'CMS_bTagWeightDeepBcErr1_13TeV_pt0_eta2',\n 'CMS_bTagWeightDeepBcErr1_13TeV_pt1_eta0',\n 'CMS_bTagWeightDeepBcErr1_13TeV_pt1_eta1',\n 'CMS_bTagWeightDeepBcErr1_13TeV_pt1_eta2',\n 'CMS_bTagWeightDeepBcErr1_13TeV_pt2_eta0',\n 'CMS_bTagWeightDeepBcErr1_13TeV_pt2_eta1',\n 'CMS_bTagWeightDeepBcErr1_13TeV_pt2_eta2',\n 'CMS_bTagWeightDeepBcErr1_13TeV_pt3_eta0',\n 'CMS_bTagWeightDeepBcErr1_13TeV_pt3_eta1',\n 'CMS_bTagWeightDeepBcErr1_13TeV_pt3_eta2',\n 'CMS_bTagWeightDeepBcErr1_13TeV_pt4_eta0',\n 'CMS_bTagWeightDeepBcErr1_13TeV_pt4_eta1',\n 'CMS_bTagWeightDeepBcErr1_13TeV_pt4_eta2',\n 'CMS_bTagWeightDeepBcErr2_13TeV_pt0_eta0',\n 'CMS_bTagWeightDeepBcErr2_13TeV_pt0_eta1',\n 'CMS_bTagWeightDeepBcErr2_13TeV_pt0_eta2',\n 'CMS_bTagWeightDeepBcErr2_13TeV_pt1_eta0',\n 'CMS_bTagWeightDeepBcErr2_13TeV_pt1_eta1',\n 'CMS_bTagWeightDeepBcErr2_13TeV_pt1_eta2',\n 'CMS_bTagWeightDeepBcErr2_13TeV_pt2_eta0',\n 'CMS_bTagWeightDeepBcErr2_13TeV_pt2_eta1',\n 'CMS_bTagWeightDeepBcErr2_13TeV_pt2_eta2',\n 'CMS_bTagWeightDeepBcErr2_13TeV_pt3_eta0',\n 'CMS_bTagWeightDeepBcErr2_13TeV_pt3_eta1',\n 'CMS_bTagWeightDeepBcErr2_13TeV_pt3_eta2',\n 'CMS_bTagWeightDeepBcErr2_13TeV_pt4_eta0',\n 'CMS_bTagWeightDeepBcErr2_13TeV_pt4_eta1',\n 'CMS_bTagWeightDeepBcErr2_13TeV_pt4_eta2',\n ]\n\nrebin_active = True\n\n;!! --------------------------------------\n;#!! Samples\n;#!! --------------------------------------\n;#!! Datacard samples setup (1st Signal, afterwards BKG)\n\n;VH - before STXS\n; QCD will be removed from signal region by combine harvester!\n;setup: ['ZH', 'WH', 'ggZH', 'ZJets_0b', 'ZJets_1b', 'ZJets_2b', 'WJets_0b', 'WJets_1b', 'WJets_2b','VVHF', 'VVLF', 'TT', 'ST', 'QCD']\n;setupSignals: ['ZH', 'WH', 'ggZH']\n\n; STXS\nsetupSignals = ['ZH_lep_PTV_0_75_hbb','ZH_lep_PTV_75_150_hbb','ZH_lep_PTV_150_250_0J_hbb','ZH_lep_PTV_150_250_GE1J_hbb','ZH_lep_PTV_GT250_hbb','WH_lep_PTV_0_75_hbb','WH_lep_PTV_75_150_hbb','WH_lep_PTV_150_250_0J_hbb','WH_lep_PTV_150_250_GE1J_hbb','WH_lep_PTV_GT250_hbb','ggZH_lep_PTV_0_75_hbb','ggZH_lep_PTV_75_150_hbb','ggZH_lep_PTV_150_250_0J_hbb','ggZH_lep_PTV_150_250_GE1J_hbb','ggZH_lep_PTV_GT250_hbb']\nsetupBackgrounds = ['ZJets_0b', 'ZJets_1b', 'ZJets_2b', 'WJets_0b', 'WJets_1b', 'WJets_2b','VVHF', 'VVLF', 'TT', 'ST', 'QCD']\nsetup = <!.|setupSignals!> + <!.|setupBackgrounds!>\n\nsetup_VV = ['VVHF', 'VVLF', 'ZJets_0b', 'ZJets_1b', 'ZJets_2b', 'WJets_0b', 'WJets_1b', 'WJets_2b', 'TT', 'ST', 'ZH', 'ggZH', 'WH']\nsetupSignals_VV = ['VVHF']\nsetup_NoSTXS = ['ZH', 'WH', 'ggZH', 'ZJets_0b', 'ZJets_1b', 'ZJets_2b', 'WJets_0b', 'WJets_1b', 'WJets_2b','VVHF', 'VVLF', 'TT', 'ST', 'QCD']\nsetup_NoSTXS_NoQCD = ['ZH', 'WH', 'ggZH', 'ZJets_0b', 'ZJets_1b', 'ZJets_2b', 'WJets_0b', 'WJets_1b', 'WJets_2b','VVHF', 'VVLF', 'TT', 'ST']\n\n#Group = <!Plot_general|Group!>\nGroup = {} \n\n#!! --------------------------------------\n#!! Naming\n#!! --------------------------------------\n#!! naming of processes in the DC\nDict = <!VHbbCommon|Dict!> \nsystematicsnaming = <!VHbbCommon|systematicsnaming!>\n\n# only needed for datacards without CH\nremoveWeightSystematics = {'Zee': ['CMS_vhbb_eff_m_13TeV', 'CMS_vhbb_eff_m_trigger_Zll_13TeV', 'CMS_vhbb_eff_m_MVAID_Zll_13TeV', 'CMS_vhbb_eff_m_tracker_Zll_13TeV', 'CMS_vhbb_eff_m_ISO_Zll_13TeV'], 'Zuu': ['CMS_vhbb_eff_e_13TeV', 'CMS_vhbb_eff_e_trigger_Zll_13TeV', 'CMS_vhbb_eff_e_MVAID_Zll_13TeV', 'CMS_vhbb_eff_e_MVAID_Zll_eta0_13TeV', 'CMS_vhbb_eff_e_MVAID_Zll_eta1_13TeV', 'CMS_vhbb_eff_e_tracker_Zll_13TeV']}\n\n# obsolete, to be removed\nptRegionsDict = {'HighPt': ['Znn_13TeV_Signal','Znn_13TeV_Zlight','Znn_13TeV_Zbb','Znn_13TeV_TT']}\n\n# datacard CR+SR\nList = <!.|ListVHLegacy!>,<!.|List_BOOSToverlap!> \nListMulti = Multi_medhigh_Znn_BKG,Multi_medhigh_Znn_SIG\nListMjj = Zhf_medhigh_Znn,Zlf_medhigh_Znn,ttbar_medhigh_Znn,Znn_Mjj_0,Znn_Mjj_1,Znn_Mjj_2,Znn_Mjj_3\nListVV = VV_SR_medhigh_Znn,Zhf_medhigh_Znn,ttbar_medhigh_Znn,Zlf_medhigh_Znn\nListVH = SR_medhigh_Znn,Zhf_medhigh_Znn,Zlf_medhigh_Znn,ttbar_medhigh_Znn\nListVHLegacy = SR_med_Znn_0j,Zhf_med_Znn,Zlf_med_Znn,ttbar_med_Znn,SR_med_Znn_ge1j,SR_high_Znn,Zhf_high_Znn,Zlf_high_Znn,ttbar_high_Znn\nListVHLegacyNjetCR = SR_med_Znn_0j,Zhf_med_Znn_0j,Zlf_med_Znn_0j,ttbar_med_Znn_0j,SR_med_Znn_ge1j,Zhf_med_Znn_ge1j,Zlf_med_Znn_ge1j,ttbar_med_Znn_ge1j,SR_high_Znn,Zhf_high_Znn,Zlf_high_Znn,ttbar_high_Znn\nList_BOOSToverlap = SR_high_Znn_BOOST,Zlf_high_Znn_BOOST,Zhf_high_Znn_BOOST,ttbar_high_Znn_BOOST\n\n\n[Datacard]\n\nproduceTextFiles = False\n\n# STXS:\nSignals = <!STXS|Signals!> \nBackgrounds = <!Plot_general|allBKGwithQCD!> \nVV_Signals = <!Plot_general|VVSIG!> \nVV_Backgrounds = <!Plot_general|VVBKG!>\n\n#-------------------------------------------------\n# standard RESOLVED analysis\n#-------------------------------------------------\n\n[dc:Zlf_med_Znn]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = cr\n\n[dc:Zlf_med_Znn_0j]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = cr\n\n\n[dc:Zlf_med_Znn_ge1j]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = cr\n\n[dc:Zhf_med_Znn]\nrebin_method = list\nrebin_list = <!Zhf_medhigh_Znn|bins!> \nvar = <!Zhf_medhigh_Znn|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:Zhf_med_Znn_0j]\nrebin_method = list\nrebin_list = <!Zhf_medhigh_Znn|bins!> \nvar = <!Zhf_medhigh_Znn|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:Zhf_med_Znn_ge1j]\nrebin_method = list\nrebin_list = <!Zhf_medhigh_Znn|bins!> \nvar = <!Zhf_medhigh_Znn|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:ttbar_med_Znn]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ntype = cr\ndata = <!.|data_<!General|TTdataset!>!>\ndata_MET = <!Plot_general|DataMET!>\ndata_SingleLepton = <!Plot_general|DataSingleLepton!>\n\n[dc:ttbar_med_Znn_0j]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ntype = cr\ndata = <!.|data_<!General|TTdataset!>!>\ndata_MET = <!Plot_general|DataMET!>\ndata_SingleLepton = <!Plot_general|DataSingleLepton!>\n\n[dc:ttbar_med_Znn_ge1j]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ntype = cr\ndata = <!.|data_<!General|TTdataset!>!>\ndata_MET = <!Plot_general|DataMET!>\ndata_SingleLepton = <!Plot_general|DataSingleLepton!>\n\n[dc:SR_med_Znn]\nrebin_method = list\nrebin_list = <!SR_medhigh_Znn|bins!> \nvar = <!SR_medhigh_Znn|branchName!>.Nominal \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:SR_med_Znn_0j]\nrebin_method = list\nrebin_list = <!SR_medhigh_Znn|bins!> \nvar = <!SR_medhigh_Znn|branchName!>.Nominal \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:SR_med_Znn_ge1j]\nrebin_method = list\nrebin_list = <!SR_medhigh_Znn|bins!> \nvar = <!SR_medhigh_Znn|branchName!>.Nominal \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:Zlf_high_Znn]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = cr\n\n[dc:Zhf_high_Znn]\nrebin_method = list\nrebin_list = <!Zhf_medhigh_Znn|bins!> \nvar = <!Zhf_medhigh_Znn|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:ttbar_high_Znn]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ntype = cr\ndata = <!.|data_<!General|TTdataset!>!>\ndata_MET = <!Plot_general|DataMET!>\ndata_SingleLepton = <!Plot_general|DataSingleLepton!>\n\n[dc:SR_high_Znn]\nrebin_method = list\nrebin_list = <!SR_medhigh_Znn|bins!> \nvar = <!SR_medhigh_Znn|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:Zlf_medhigh_Znn]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = cr\n\n[dc:Zhf_medhigh_Znn]\nrebin_method = list\nrebin_list = <!Zhf_medhigh_Znn|bins!> \nvar = <!Zhf_medhigh_Znn|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:ttbar_medhigh_Znn]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ntype = cr\ndata = <!.|data_<!General|TTdataset!>!>\ndata_MET = <!Plot_general|DataMET!>\ndata_SingleLepton = <!Plot_general|DataSingleLepton!>\n\n[dc:SR_medhigh_Znn]\nrebin_method = list\nrebin_list = <!SR_medhigh_Znn|bins!> \nvar = <!SR_medhigh_Znn|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n# VZ analysis\n[dc:VV_SR_medhigh_Znn]\nrebin_method = list\nrebin_list = <!VV_SR_medhigh_Znn|bins!> \nvar = <!VV_SR_medhigh_Znn|branchName!>.Nominal\nsignal = <!Datacard|VV_Signals!>\nbackground = <!Datacard|VV_Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:VV_SR_med_Znn]\nrebin_method = list\nrebin_list = <!VV_SR_medhigh_Znn|bins!> \nvar = <!VV_SR_medhigh_Znn|branchName!>.Nominal \nsignal = <!Datacard|VV_Signals!>\nbackground = <!Datacard|VV_Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:VV_SR_med_Znn_0j]\nrebin_method = list\nrebin_list = <!VV_SR_medhigh_Znn|bins!> \nvar = <!VV_SR_medhigh_Znn|branchName!>.Nominal \nsignal = <!Datacard|VV_Signals!>\nbackground = <!Datacard|VV_Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:VV_SR_med_Znn_ge1j]\nrebin_method = list\nrebin_list = <!VV_SR_medhigh_Znn|bins!> \nvar = <!VV_SR_medhigh_Znn|branchName!>.Nominal \nsignal = <!Datacard|VV_Signals!>\nbackground = <!Datacard|VV_Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:VV_Zhf_med_Znn]\nrebin_method = list\nrebin_list = <!VV_Zhf_medhigh_Znn|bins!> \nvar = <!VV_Zhf_medhigh_Znn|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:VV_Zhf_med_Znn_0j]\nrebin_method = list\nrebin_list = <!VV_Zhf_medhigh_Znn|bins!> \nvar = <!VV_Zhf_medhigh_Znn|branchName!>.Nominal\nsignal = <!Datacard|VV_Signals!>\nbackground = <!Datacard|VV_Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:VV_Zhf_med_Znn_ge1j]\nrebin_method = list\nrebin_list = <!VV_Zhf_medhigh_Znn|bins!> \nvar = <!VV_Zhf_medhigh_Znn|branchName!>.Nominal\nsignal = <!Datacard|VV_Signals!>\nbackground = <!Datacard|VV_Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n\n# mjj analysis\n[dc:Znn_Mjj_0]\ncut = Mjj_0\nrange = 20,60.0,160.0\nvar = <!LimitGeneral|Mass!>\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:Znn_Mjj_1]\ncut = Mjj_1\nrange = 20,60.0,160.0\nvar = <!LimitGeneral|Mass!>\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:Znn_Mjj_2]\ncut = Mjj_2\nrange = 20,60.0,160.0\nvar = <!LimitGeneral|Mass!>\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n[dc:Znn_Mjj_3]\ncut = Mjj_3\nrange = 20,60.0,160.0\nvar = <!LimitGeneral|Mass!>\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n# multi-class datacards\n\n[Multi]\nList = Multi_medhigh_Znn_SIG,Multi_medhigh_Znn_BKG \nvar = <!Multi_medhigh_Znn|branchName!>.Nominal \nbinsCR = <!Multi_medhigh_Znn|bins!>[:-15]\nbinsSR = <!Multi_medhigh_Znn|bins!>[-16:]\n\n\n[dc:Multi_medhigh_Znn_BKG]\ncut = Multi_medhigh_Znn\nrebin_method = list\nrebin_list = <!Multi|binsCR!> \nvar = <!Multi|var!>\nrange = 50,0,10.0 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|Data!>\ntype = BDT\n\n[dc:Multi_medhigh_Znn_SIG]\ncut = Multi_medhigh_Znn\nrebin_method = list\nrebin_list = <!Multi|binsSR!> \n# test: tt / vjets split\n#rebin_list = [10,10.1461,10.2029,10.2585,10.3122,10.3738,10.6241,10.689,10.7485,10.798,10.8374,10.8687,10.8925,10.9121,10.9291,11.0001]\n#v = BDT_Jan31_Znn_multi_DNN\n#var = (<!.|v!>_argmax.Nominal==10)*(10.0+max(min(0.5+0.5*(2.0*((<!.|v!>_6.Nominal+<!.|v!>_7.Nominal+<!.|v!>_8.Nominal+<!.|v!>_9.Nominal)<(<!.|v!>_1.Nominal+<!.|v!>_2.Nominal+<!.|v!>_4.Nominal+<!.|v!>_5.Nominal))-1.0)*<!.|v!>_10.Nominal,0.9999),0.0))\nvar = <!Multi|var!>\nrange = 15,10.0,11.0 \nsignal = <!Datacard|Signals!> \nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|Data!>\ntype = BDT\n\n\n;======================\n;BDT output names and datacards\n;======================\nBDToutname_BOOST \t= BDT_Zvv_BOOSTFinal_wdB.Nominal \nBTagVar_BOOST\t\t= 1/(1+(FatJet_deepTagMD_TvsQCD[Hbb_fjidx]/FatJet_deepTagMD_HbbvsQCD[Hbb_fjidx])*(1-FatJet_deepTagMD_HbbvsQCD[Hbb_fjidx])/(1-FatJet_deepTagMD_TvsQCD[Hbb_fjidx]))\nBDTrange_BOOST \t\t= 15,-1,1 \nBTagVarRange1_BOOST\t= 10,0.8,1 \nBTagVarRange2_BOOST\t= 10,0,0.8 \n\n\n\n\n#----- Boosted analysis -----#\n\n[dc:SR_high_Znn_BOOST]\n#var = <!Datacard|BDToutname_BOOST!>\nvar = BDT_Zvv_BOOSTFinal_wdB.Nominal\nrange = 15,-1,1 \nsignal = <!Datacard|Signals!>\nbackground= <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = BDT\n\n\n[dc:Zlf_high_Znn_BOOST]\n#var = <!Datacard|BTagVar_BOOST!>\nvar = 1/(1+(FatJet_deepTagMD_TvsQCD[Hbb_fjidx]/FatJet_deepTagMD_HbbvsQCD[Hbb_fjidx])*(1-FatJet_deepTagMD_HbbvsQCD[Hbb_fjidx])/(1-FatJet_deepTagMD_TvsQCD[Hbb_fjidx]))\nrange = 10,0,0.8 \nsignal = <!Datacard|Signals!>\nbackground= <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = cr\n\n\n[dc:Zhf_high_Znn_BOOST]\n#var = <!Datacard|BTagVar_BOOST!>\nvar = 1/(1+(FatJet_deepTagMD_TvsQCD[Hbb_fjidx]/FatJet_deepTagMD_HbbvsQCD[Hbb_fjidx])*(1-FatJet_deepTagMD_HbbvsQCD[Hbb_fjidx])/(1-FatJet_deepTagMD_TvsQCD[Hbb_fjidx]))\nrange = 10,0.8,1 \nsignal = <!Datacard|Signals!>\nbackground= <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = cr\n\n\n\n[dc:ttbar_high_Znn_BOOST]\n#var = <!Datacard|BTagVar_BOOST!>\nvar = 1/(1+(FatJet_deepTagMD_TvsQCD[Hbb_fjidx]/FatJet_deepTagMD_HbbvsQCD[Hbb_fjidx])*(1-FatJet_deepTagMD_HbbvsQCD[Hbb_fjidx])/(1-FatJet_deepTagMD_TvsQCD[Hbb_fjidx]))\nrange = 10,0.8,1\nsignal = <!Datacard|Signals!>\nbackground= <!Datacard|Backgrounds!>\ndata = <!Plot_general|DataMET!>\ntype = cr\n\n# to speed up shape creation\n\n[ZJetsToNuNu_HT-200To400_13TeV-madgraph]\nmergeCachingSize=1\n[ZJetsToNuNu_HT-400To600_13TeV-madgraph]\nmergeCachingSize=1\n[ZJetsToNuNu_HT-600To800_13TeV-madgraph]\nmergeCachingSize=1\n[ZJetsToNuNu_HT-800To1200_13TeV-madgraph]\nmergeCachingSize=1\n[ZJetsToNuNu_HT-1200To2500_13TeV-madgraph]\nmergeCachingSize=1\n[ggZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8]\nmergeCachingSize=2\n[WJetsToLNu_HT-400To600_TuneCP5_13TeV-madgraphMLM-pythia8]\nmergeCachingSize=1\n[WJetsToLNu_HT-600To800_TuneCP5_13TeV-madgraphMLM-pythia8]\nmergeCachingSize=1\n[WJetsToLNu_HT-800To1200_TuneCP5_13TeV-madgraphMLM-pythia8]\nmergeCachingSize=1\n[WJetsToLNu_HT-1200To2500_TuneCP5_13TeV-madgraphMLM-pythia8]\nmergeCachingSize=1\n[TTToSemiLeptonic_TuneCP5_PSweights_13TeV-powheg-pythia8]\nmergeCachingSize=1\n[MET]\nmergeCachingSize=20\n\n\n" }, { "alpha_fraction": 0.5854604244232178, "alphanum_fraction": 0.6196982860565186, "avg_line_length": 28.8419246673584, "blob_id": "66a05b79f0bca4448c1af4383e6acfd6afa7391f", "content_id": "d3d85caf1a4597862a2eb3028653eb9c348db6ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 26053, "license_type": "no_license", "max_line_length": 411, "num_lines": 873, "path": "/python/Wlv2016config/datacards.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "[LimitGeneral]\n#!! --------------------------------------\n##!! Binning:\n##!! --------------------------------------\n\n\n;IMPORTANT: this has to be exacly the same as the variable in vhbbPlotDef for the pre/postfit macro to work\n;Ragne for mjj datacards\nMass = H_mass\nMassRange = 17,0,255\nMassRangeVV = 34,0, 255\n\n;CR\nbTagVar = <!General|Jet_btag!>[<!General|btagidx1!>] \nbTagVarRange = 20,-1,1\nBDTrange_BDT = 15,-1,1\nBDTrange_DNN = 15,0,1\nBDTrange = <!LimitGeneral|BDTrange_<!General|MVAtype!>!>\n\nMass = H_mass\n\n;!! --------------------------------------\n;!! Systematics\n;!! --------------------------------------\n\nremove_systematics = True\n\n;_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*\n;FOR CR\n;_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*\n\nsys_cr = [\n 'jer',\n 'jerReg',\n 'jesAbsoluteStat',\n 'jesAbsoluteScale',\n 'jesAbsoluteFlavMap',\n 'jesAbsoluteMPFBias',\n 'jesFragmentation',\n 'jesSinglePionECAL',\n 'jesSinglePionHCAL',\n 'jesFlavorQCD',\n 'jesRelativeJEREC1',\n 'jesRelativeJEREC2',\n 'jesRelativeJERHF',\n 'jesRelativePtBB',\n 'jesRelativePtEC1',\n 'jesRelativePtEC2',\n 'jesRelativePtHF',\n 'jesRelativeBal',\n 'jesRelativeFSR',\n 'jesRelativeStatFSR',\n 'jesRelativeStatEC',\n 'jesRelativeStatHF',\n 'jesPileUpDataMC',\n 'jesPileUpPtRef',\n 'jesPileUpPtBB',\n 'jesPileUpPtEC1',\n 'jesPileUpPtEC2',\n 'jesPileUpPtHF',\n 'jmr',\n 'jms'\n ]\n\nsys_BDT = <!LimitGeneral|sys_cr!>\nsys_Mjj = <!LimitGeneral|sys_cr!>\n\n\nweightF_sys = [\n 'PileUp',\n; pT(W) fit reweighting\n 'CMS_vhbb_topptreweighting_13TeV',\n 'FitCorrection',\n 'FitCorrectionHF',\n; Lepton efficiencies\n 'CMS_vhbb_eff_e_trigger_Wlv_13TeV',\n 'CMS_vhbb_eff_e_MVAID_Wlv_13TeV',\n 'CMS_vhbb_eff_m_trigger_Wlv_13TeV',\n 'CMS_vhbb_eff_m_MVAID_Wlv_13TeV',\n 'CMS_vhbb_eff_m_ISO_Wlv_13TeV',\n; LO to NLO shape reweighting\n 'CMS_vhbb_vjetnlodetajjrw_13TeV',\n; 2017 version\n 'CMS_vhbb_vjetnlovptrw_p0_13TeV',\n 'CMS_vhbb_vjetnlovptrw_p1_13TeV',\n; 'CMS_vhbb_vjetnlovptrw_naddjet0_p0_13TeV',\n; 'CMS_vhbb_vjetnlovptrw_naddjet0_p1_13TeV',\n; 'CMS_vhbb_vjetnlovptrw_naddjet1_p0_13TeV',\n; 'CMS_vhbb_vjetnlovptrw_naddjet1_p1_13TeV',\n; 'CMS_vhbb_vjetnlovptrw_naddjet2_p0_13TeV',\n; 'CMS_vhbb_vjetnlovptrw_naddjet2_p1_13TeV',\n; 'CMS_vhbb_vjetnlovptrw_naddjet3_p0_13TeV',\n; 'CMS_vhbb_vjetnlovptrw_naddjet3_p1_13TeV',\n; 'CMS_vhbb_vjetnlovptrw_naddjet4_p0_13TeV',\n; 'CMS_vhbb_vjetnlovptrw_naddjet4_p1_13TeV',\n; 'CMS_vhbb_vjetnlovptrw_naddjet5_p0_13TeV',\n; 'CMS_vhbb_vjetnlovptrw_naddjet5_p1_13TeV',\n; add jet activity\n 'CMS_vhbb_ttbar_nAddJets',\n; Jet PU ID\n 'CMS_vhbb_jetPUID',\n; Prefire correction\n 'CMS_vhbb_PrefireWeight_13TeV',\n; scales\n 'CMS_LHE_weights_scale_muR_ZH',\n 'CMS_LHE_weights_scale_muR_WH',\n 'CMS_LHE_weights_scale_muR_ggZH',\n 'CMS_LHE_weights_scale_muR_TT',\n 'CMS_LHE_weights_scale_muR_Zj0b',\n 'CMS_LHE_weights_scale_muR_Zj1b',\n 'CMS_LHE_weights_scale_muR_Zj2b',\n 'CMS_LHE_weights_scale_muR_Wj0b',\n 'CMS_LHE_weights_scale_muR_Wj1b',\n 'CMS_LHE_weights_scale_muR_Wj2b',\n# 'CMS_LHE_weights_scale_muR_VVHF',\n# 'CMS_LHE_weights_scale_muR_VVLF',\n 'CMS_LHE_weights_scale_muF_ZH',\n 'CMS_LHE_weights_scale_muF_WH',\n 'CMS_LHE_weights_scale_muF_ggZH',\n 'CMS_LHE_weights_scale_muF_TT',\n 'CMS_LHE_weights_scale_muF_Zj0b',\n 'CMS_LHE_weights_scale_muF_Zj1b',\n 'CMS_LHE_weights_scale_muF_Zj2b',\n 'CMS_LHE_weights_scale_muF_Wj0b',\n 'CMS_LHE_weights_scale_muF_Wj1b',\n 'CMS_LHE_weights_scale_muF_Wj2b',\n# 'CMS_LHE_weights_scale_muF_VVHF',\n# 'CMS_LHE_weights_scale_muF_VVLF',\n; EWK signal correction\n 'CMS_vhbb_signal_ewk_13TeV',\n 'CMS_vhbb_VJets_ewk_13TeV',\n 'CMS_vhbb_Vjets_pdfwgt_0lep',\n 'CMS_vhbb_Vjets_pdfwgt_1lep',\n 'CMS_vhbb_Vjets_pdfwgt_2lep',\n;\n 'btagWeight_jes_pt0_eta1',\n 'btagWeight_jes_pt0_eta2',\n 'btagWeight_jes_pt0_eta3',\n 'btagWeight_jes_pt1_eta1',\n 'btagWeight_jes_pt1_eta2',\n 'btagWeight_jes_pt1_eta3',\n 'btagWeight_jes_pt2_eta1',\n 'btagWeight_jes_pt2_eta2',\n 'btagWeight_jes_pt2_eta3',\n 'btagWeight_jes_pt3_eta1',\n 'btagWeight_jes_pt3_eta2',\n 'btagWeight_jes_pt3_eta3',\n 'btagWeight_jes_pt4_eta1',\n 'btagWeight_jes_pt4_eta2',\n 'btagWeight_jes_pt4_eta3',\n;\n 'btagWeight_lf_pt0_eta1',\n 'btagWeight_lf_pt0_eta2',\n 'btagWeight_lf_pt0_eta3',\n 'btagWeight_lf_pt1_eta1',\n 'btagWeight_lf_pt1_eta2',\n 'btagWeight_lf_pt1_eta3',\n 'btagWeight_lf_pt2_eta1',\n 'btagWeight_lf_pt2_eta2',\n 'btagWeight_lf_pt2_eta3',\n 'btagWeight_lf_pt3_eta1',\n 'btagWeight_lf_pt3_eta2',\n 'btagWeight_lf_pt3_eta3',\n 'btagWeight_lf_pt4_eta1',\n 'btagWeight_lf_pt4_eta2',\n 'btagWeight_lf_pt4_eta3',\n;\n 'btagWeight_hf_pt0_eta1',\n 'btagWeight_hf_pt0_eta2',\n 'btagWeight_hf_pt0_eta3',\n 'btagWeight_hf_pt1_eta1',\n 'btagWeight_hf_pt1_eta2',\n 'btagWeight_hf_pt1_eta3',\n 'btagWeight_hf_pt2_eta1',\n 'btagWeight_hf_pt2_eta2',\n 'btagWeight_hf_pt2_eta3',\n 'btagWeight_hf_pt3_eta1',\n 'btagWeight_hf_pt3_eta2',\n 'btagWeight_hf_pt3_eta3',\n 'btagWeight_hf_pt4_eta1',\n 'btagWeight_hf_pt4_eta2',\n 'btagWeight_hf_pt4_eta3',\n;\n 'btagWeight_lfstats1_pt0_eta1',\n 'btagWeight_lfstats1_pt0_eta2',\n 'btagWeight_lfstats1_pt0_eta3',\n 'btagWeight_lfstats1_pt1_eta1',\n 'btagWeight_lfstats1_pt1_eta2',\n 'btagWeight_lfstats1_pt1_eta3',\n 'btagWeight_lfstats1_pt2_eta1',\n 'btagWeight_lfstats1_pt2_eta2',\n 'btagWeight_lfstats1_pt2_eta3',\n 'btagWeight_lfstats1_pt3_eta1',\n 'btagWeight_lfstats1_pt3_eta2',\n 'btagWeight_lfstats1_pt3_eta3',\n 'btagWeight_lfstats1_pt4_eta1',\n 'btagWeight_lfstats1_pt4_eta2',\n 'btagWeight_lfstats1_pt4_eta3',\n;\n 'btagWeight_lfstats2_pt0_eta1',\n 'btagWeight_lfstats2_pt0_eta2',\n 'btagWeight_lfstats2_pt0_eta3',\n 'btagWeight_lfstats2_pt1_eta1',\n 'btagWeight_lfstats2_pt1_eta2',\n 'btagWeight_lfstats2_pt1_eta3',\n 'btagWeight_lfstats2_pt2_eta1',\n 'btagWeight_lfstats2_pt2_eta2',\n 'btagWeight_lfstats2_pt2_eta3',\n 'btagWeight_lfstats2_pt3_eta1',\n 'btagWeight_lfstats2_pt3_eta2',\n 'btagWeight_lfstats2_pt3_eta3',\n 'btagWeight_lfstats2_pt4_eta1',\n 'btagWeight_lfstats2_pt4_eta2',\n 'btagWeight_lfstats2_pt4_eta3',\n;\n 'btagWeight_hfstats1_pt0_eta1',\n 'btagWeight_hfstats1_pt0_eta2',\n 'btagWeight_hfstats1_pt0_eta3',\n 'btagWeight_hfstats1_pt1_eta1',\n 'btagWeight_hfstats1_pt1_eta2',\n 'btagWeight_hfstats1_pt1_eta3',\n 'btagWeight_hfstats1_pt2_eta1',\n 'btagWeight_hfstats1_pt2_eta2',\n 'btagWeight_hfstats1_pt2_eta3',\n 'btagWeight_hfstats1_pt3_eta1',\n 'btagWeight_hfstats1_pt3_eta2',\n 'btagWeight_hfstats1_pt3_eta3',\n 'btagWeight_hfstats1_pt4_eta1',\n 'btagWeight_hfstats1_pt4_eta2',\n 'btagWeight_hfstats1_pt4_eta3',\n;\n 'btagWeight_hfstats2_pt0_eta1',\n 'btagWeight_hfstats2_pt0_eta2',\n 'btagWeight_hfstats2_pt0_eta3',\n 'btagWeight_hfstats2_pt1_eta1',\n 'btagWeight_hfstats2_pt1_eta2',\n 'btagWeight_hfstats2_pt1_eta3',\n 'btagWeight_hfstats2_pt2_eta1',\n 'btagWeight_hfstats2_pt2_eta2',\n 'btagWeight_hfstats2_pt2_eta3',\n 'btagWeight_hfstats2_pt3_eta1',\n 'btagWeight_hfstats2_pt3_eta2',\n 'btagWeight_hfstats2_pt3_eta3',\n 'btagWeight_hfstats2_pt4_eta1',\n 'btagWeight_hfstats2_pt4_eta2',\n 'btagWeight_hfstats2_pt4_eta3',\n;\n 'btagWeight_cferr1_pt0_eta1',\n 'btagWeight_cferr1_pt0_eta2',\n 'btagWeight_cferr1_pt0_eta3',\n 'btagWeight_cferr1_pt1_eta1',\n 'btagWeight_cferr1_pt1_eta2',\n 'btagWeight_cferr1_pt1_eta3',\n 'btagWeight_cferr1_pt2_eta1',\n 'btagWeight_cferr1_pt2_eta2',\n 'btagWeight_cferr1_pt2_eta3',\n 'btagWeight_cferr1_pt3_eta1',\n 'btagWeight_cferr1_pt3_eta2',\n 'btagWeight_cferr1_pt3_eta3',\n 'btagWeight_cferr1_pt4_eta1',\n 'btagWeight_cferr1_pt4_eta2',\n 'btagWeight_cferr1_pt4_eta3',\n;\n 'btagWeight_cferr2_pt0_eta1',\n 'btagWeight_cferr2_pt0_eta2',\n 'btagWeight_cferr2_pt0_eta3',\n 'btagWeight_cferr2_pt1_eta1',\n 'btagWeight_cferr2_pt1_eta2',\n 'btagWeight_cferr2_pt1_eta3',\n 'btagWeight_cferr2_pt2_eta1',\n 'btagWeight_cferr2_pt2_eta2',\n 'btagWeight_cferr2_pt2_eta3',\n 'btagWeight_cferr2_pt3_eta1',\n 'btagWeight_cferr2_pt3_eta2',\n 'btagWeight_cferr2_pt3_eta3',\n 'btagWeight_cferr2_pt4_eta1',\n 'btagWeight_cferr2_pt4_eta2',\n 'btagWeight_cferr2_pt4_eta3',\n;\n 'bTagWeightDoubleB_mp_pt200to300',\n 'bTagWeightDoubleB_mp_pt300to400',\n 'bTagWeightDoubleB_mp_pt400to500',\n 'bTagWeightDoubleB_mp_pt500to600',\n 'bTagWeightDoubleB_mp_pt600toInf',\n 'bTagWeightDoubleB_hp_pt200to300',\n 'bTagWeightDoubleB_hp_pt300to400',\n 'bTagWeightDoubleB_hp_pt400to500',\n 'bTagWeightDoubleB_hp_pt500to600',\n 'bTagWeightDoubleB_hp_pt600toInf',\n ]\n\n;!! --------------------------------------\n;#!! Samples\n;#!! --------------------------------------\n;#!! Datacard samples setup (1st Signal, afterwards BKG)\n\n;;VH\n;setup: ['ZH', 'WH', 'ggZH', 'VVHF', 'VVLF', 'ZJets_0b', 'ZJets_1b', 'ZJets_2b', 'WJets_0b', 'WJets_1b', 'WJets_2b', 'TT', 'ST']\n;setupSignals: ['ZH', 'WH', 'ggZH']\n\n; STXS\nsetupSignals = ['ZH_lep_PTV_0_75_hbb','ZH_lep_PTV_75_150_hbb','ZH_lep_PTV_150_250_0J_hbb','ZH_lep_PTV_150_250_GE1J_hbb','ZH_lep_PTV_GT250_hbb','WH_lep_PTV_0_75_hbb','WH_lep_PTV_75_150_hbb','WH_lep_PTV_150_250_0J_hbb','WH_lep_PTV_150_250_GE1J_hbb','WH_lep_PTV_GT250_hbb','ggZH_lep_PTV_0_75_hbb','ggZH_lep_PTV_75_150_hbb','ggZH_lep_PTV_150_250_0J_hbb','ggZH_lep_PTV_150_250_GE1J_hbb','ggZH_lep_PTV_GT250_hbb']\nsetupBackgrounds = ['ZJets_0b', 'ZJets_1b', 'ZJets_2b', 'WJets_0b', 'WJets_1b', 'WJets_2b','VVHF', 'VVLF', 'TT', 'ST']\nsetup = <!.|setupSignals!> + <!.|setupBackgrounds!>\n\n\n#setup_VV: ['VVHF', 'VVLF', 'ZJets_0b', 'ZJets_1b', 'ZJets_2b', 'WJets_0b', 'WJets_1b', 'WJets_2b', 'ZH', 'WH', 'TT', 'ST']\nsetup_VV: ['VVHF', 'VVLF', 'ZJets_0b', 'ZJets_1b', 'ZJets_2b', 'WJets_0b', 'WJets_1b', 'WJets_2b', 'TT', 'ST', 'WH', 'ZH']\nsetupSignals_VV = ['VVHF']\n\nsetup_NoSTXS = ['ZH', 'WH', 'ggZH', 'VVHF', 'VVLF', 'ZJets_0b', 'ZJets_1b', 'ZJets_2b', 'WJets_0b', 'WJets_1b', 'WJets_2b', 'TT', 'ST']\n\n#Group: <!Plot_general|Group!>\nGroup: {}\n\n#!! --------------------------------------\n#!! Naming\n#!! --------------------------------------\n#!! naming of processes in the DC\n\nDict = <!VHbbCommon|Dict!>\nsystematicsnaming = <!VHbbCommon|systematicsnaming!>\n\n\nremoveWeightSystematics = {}\n\n#List = Limit_Wen_TT,Limit_Wun_TT,Limit_Wen_Wlight,Limit_Wun_Wlight,Limit_Wen_Signal,Limit_Wun_Signal,Limit_Wen_Wbb,Limit_Wun_Wbb\n\n#List = ttbar_med_Wen,ttbar_med_Wmn,Wlf_med_Wen,Wlf_med_Wmn,Whf_med_Wen,Whf_med_Wmn,SR_med_Wen,SR_med_Wmn,SR_high_Wen_BOOST,SR_high_Wmn_BOOST,Wlf_high_Wen_BOOST,Wlf_high_Wmn_BOOST,Whf_high_Wmn_BOOST,Whf_high_Wen_BOOST,ttbar_high_Wmn_BOOST,ttbar_high_Wen_BOOST\n\n\nList = SR_high_Wen,SR_high_Wmn,Wlf_high_Wen,Wlf_high_Wmn,Whf_high_Wen,Whf_high_Wmn,ttbar_high_Wen,ttbar_high_Wmn,SR_med_Wen,SR_med_Wmn,Wlf_med_Wen,Wlf_med_Wmn,Whf_med_Wen,Whf_med_Wmn,ttbar_med_Wen,ttbar_med_Wmn,SR_high_Wen_BOOST,SR_high_Wmn_BOOST,Wlf_high_Wen_BOOST,Wlf_high_Wmn_BOOST,Whf_high_Wmn_BOOST,Whf_high_Wen_BOOST,ttbar_high_Wmn_BOOST,ttbar_high_Wen_BOOST\n\n\n\n \n#List = ttbar_high_Wmn_BOOST\n\n\n\n#List = <!.|ListVHLegacy!>,<!.|List_BOOSToverlap!> \n\n#List_BOOSToverlap =\n\n\n# diboson list, use with: --set='LimitGeneral.List=<!LimitGeneral|ListVV!>'\nListVV = ttbar_medhigh_Wen,ttbar_medhigh_Wmn,Wlf_medhigh_Wen,Wlf_medhigh_Wmn,VV_Whf_medhigh_Wen,VV_Whf_medhigh_Wmn,VV_SR_medhigh_Wen,VV_SR_medhigh_Wmn\nListVH = ttbar_medhigh_Wen,ttbar_medhigh_Wmn,Wlf_medhigh_Wen,Wlf_medhigh_Wmn,Whf_medhigh_Wen,Whf_medhigh_Wmn,SR_medhigh_Wen,SR_medhigh_Wmn\nListVHLegacy = ttbar_med_Wen,ttbar_med_Wmn,Wlf_med_Wen,Wlf_med_Wmn,Whf_med_Wen,Whf_med_Wmn,SR_med_Wen,SR_med_Wmn,ttbar_high_Wen,ttbar_high_Wmn,Wlf_high_Wen,Wlf_high_Wmn,Whf_high_Wen,Whf_high_Wmn,SR_high_Wen,SR_high_Wmn\nListMjj = ttbar_medhigh_Wen,ttbar_medhigh_Wmn,Wlf_medhigh_Wen,Wlf_medhigh_Wmn,Whf_medhigh_Wen,Whf_medhigh_Wmn,Mjj_SR_medhigh_Wen_0,Mjj_SR_medhigh_Wen_1,Mjj_SR_medhigh_Wen_2,Mjj_SR_medhigh_Wen_3,Mjj_SR_medhigh_Wmn_0,Mjj_SR_medhigh_Wmn_1,Mjj_SR_medhigh_Wmn_2,Mjj_SR_medhigh_Wmn_3\nListMulti = <!Multi|List!>\n\n[Multi]\nList = Multi_medhigh_Wen_SIG,Multi_medhigh_Wen_BKG,Multi_medhigh_Wmn_SIG,Multi_medhigh_Wmn_BKG\n\n# V1: same DNN for e/mu\n#Wen = <!Multi_medhigh_Wln|branchName!>.Nominal\n#Wmn = <!Multi_medhigh_Wln|branchName!>.Nominal\n\n# V2: separate DNN (as in standard analysis)\nWen = <!Multi_medhigh_Wen|branchName!>.Nominal\nWmn = <!Multi_medhigh_Wmn|branchName!>.Nominal\n\n# V2\nbinsWmnCR = <!Multi_medhigh_Wmn|bins!>[:-15]\nbinsWmnSR = <!Multi_medhigh_Wmn|bins!>[-16:]\nbinsWenCR = <!Multi_medhigh_Wen|bins!>[:-15]\nbinsWenSR = <!Multi_medhigh_Wen|bins!>[-16:]\n\n;;!! --------------------------------------\n;;!! Datacards specific setup\n;;!! --------------------------------------\n\n;;List here the lnN sys in use\n[Datacard]\n\nproduceTextFiles = False\n\n#!! -------------------------\n#!! Limit definitions\n#!! -------------------------\n\n;======================\n;For SF fit (CR+SF)\n;======================\n#Signals = ['ZH_Znunu','ZH_Zll','WminusH','WplusH','ggZH_Zll','ggZH_Znunu']\n\n# STXS - For now QCD has to be excluded from the allBKG before producing datacards!\nSignals = <!STXS|Signals!> \nBackgrounds = <!Plot_general|allBKG!>\n\n# VV analysis\nVV_Signals = <!Plot_general|VVSIG!> \nVV_Backgrounds = <!Plot_general|VVBKG!>\n\n\n\n\n\n\n\n\n;======================\n;BDT output names and datacards\n;======================\nBDToutname_BOOST \t=\nBTagVar_BOOST\t\t= FatJet_deepTagMD_bbvsLight[Hbb_fjidx]\nBDTrange_BOOST \t\t= \nBDToutname_BOOST \t= BDT_Wlv_BOOSTFinal_wdB.Nominal \nBTagVarRange1_BOOST\t= \nBTagVarRange2_BOOST\t=\n\n\n\n;;;;;;;;;;;;;;\n;VH datacards\n;;;;;;;;;;;;;;\n\n\n#----- Boosted analysis -----#\n\n[dc:SR_high_Wmn_BOOST]\nvar = BDT_Wlv_BOOSTFinal_wdB.Nominal \nrange = 15,-1,1 \nsignal = <!Datacard|Signals!>\nbackground= <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!> \ntype = BDT \n\n[dc:SR_high_Wen_BOOST]\nvar = BDT_Wlv_BOOSTFinal_wdB.Nominal \nrange = 15,-1,1 \nsignal = <!Datacard|Signals!>\nbackground= <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = BDT \n\n[dc:Wlf_high_Wmn_BOOST]\nvar = FatJet_deepTagMD_bbvsLight[Hbb_fjidx]\nrange = 3,0,0.8 \nsignal = <!Datacard|Signals!>\nbackground= <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = cr \n\n[dc:Wlf_high_Wen_BOOST]\nvar = FatJet_deepTagMD_bbvsLight[Hbb_fjidx]\nrange = 3,0,0.8 \nsignal = <!Datacard|Signals!>\nbackground= <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = cr \n\n[dc:Whf_high_Wmn_BOOST]\nvar = FatJet_deepTagMD_bbvsLight[Hbb_fjidx]\nrange = 3,0.8,1\nsignal = <!Datacard|Signals!>\nbackground= <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = cr \n\n[dc:Whf_high_Wen_BOOST]\nvar = FatJet_deepTagMD_bbvsLight[Hbb_fjidx]\nrange = 3,0.8,1\nsignal = <!Datacard|Signals!>\nbackground= <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = cr \n\n[dc:ttbar_high_Wmn_BOOST]\nvar = FatJet_deepTagMD_bbvsLight[Hbb_fjidx]\nrange = 3,0.8,1\nsignal = <!Datacard|Signals!>\nbackground= <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = cr \n\n[dc:ttbar_high_Wen_BOOST]\nvar = FatJet_deepTagMD_bbvsLight[Hbb_fjidx]\nrange = 3,0.8,1\nsignal = <!Datacard|Signals!>\nbackground= <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = cr \n\n\n\n#----- tt -----#\n[dc:ttbar_med_Wen]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = cr\n\n[dc:ttbar_med_Wmn]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = cr\n\n#----- Whf --------#\n[dc:Whf_med_Wen]\nrebin_method = list\nrebin_list = <!Whf_med_Wln|bins!> \nvar = <!Whf_med_Wln|branchName!>.Nominal \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = BDT\n\n[dc:Whf_med_Wmn]\nrebin_method = list\nrebin_list = <!Whf_med_Wln|bins!> \nvar = <!Whf_med_Wln|branchName!>.Nominal \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = BDT\n\n#----- Wlf -----#\n[dc:Wlf_med_Wen]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = cr\n\n[dc:Wlf_med_Wmn]\nvar = 1 \nrange = 1,0,2\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = cr\n\n#----- Signal -----#\n[dc:SR_med_Wen]\nrebin_method = list\nrebin_list = <!SR_medhigh_Wln|bins!>\nvar = <!SR_medhigh_Wln|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = BDT\n\n[dc:SR_med_Wmn]\nrebin_method = list\nrebin_list = <!SR_medhigh_Wln|bins!> \nvar = <!SR_medhigh_Wln|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = BDT\n\n#----- tt -----#\n[dc:ttbar_high_Wen]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = cr\n\n[dc:ttbar_high_Wmn]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = cr\n\n#----- Whf --------#\n[dc:Whf_high_Wen]\nrebin_method = list\nrebin_list = <!Whf_high_Wln|bins!> \nvar = <!Whf_high_Wln|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = BDT\n\n[dc:Whf_high_Wmn]\nrebin_method = list\nrebin_list = <!Whf_high_Wln|bins!> \nvar = <!Whf_high_Wln|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = BDT\n\n#----- Wlf -----#\n[dc:Wlf_high_Wen]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = cr\n\n[dc:Wlf_high_Wmn]\nvar = 1 \nrange = 1,0,2\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = cr\n\n#----- Signal -----#\n[dc:SR_high_Wen]\nrebin_method = list\nrebin_list = <!SR_medhigh_Wln|bins!>\nvar = <!SR_medhigh_Wln|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = BDT\n\n[dc:SR_high_Wmn]\nrebin_method = list\nrebin_list = <!SR_medhigh_Wln|bins!> \nvar = <!SR_medhigh_Wln|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = BDT\n\n# medhigh\n\n#----- tt -----#\n[dc:ttbar_medhigh_Wen]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = cr\n\n[dc:ttbar_medhigh_Wmn]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = cr\n\n#----- Whf --------#\n[dc:Whf_medhigh_Wen]\nrebin_method = list\nrebin_list = <!Whf_medhigh_Wln|bins!> \nvar = <!Whf_medhigh_Wln|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = BDT\n\n[dc:Whf_medhigh_Wmn]\nrebin_method = list\nrebin_list = <!Whf_medhigh_Wln|bins!> \nvar = <!Whf_medhigh_Wln|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = BDT\n\n#----- VV Whf --------#\n[dc:VV_Whf_medhigh_Wen]\nrebin_method = list\nrebin_list = <!VV_Whf_medhigh_Wln|bins!> \nvar = <!VV_Whf_medhigh_Wln|branchName!>.Nominal\nsignal = <!Datacard|VV_Signals!>\nbackground = <!Datacard|VV_Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = BDT\n\n[dc:VV_Whf_medhigh_Wmn]\nrebin_method = list\nrebin_list = <!VV_Whf_medhigh_Wln|bins!> \nvar = <!VV_Whf_medhigh_Wln|branchName!>.Nominal\nsignal = <!Datacard|VV_Signals!>\nbackground = <!Datacard|VV_Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = BDT\n\n#----- Wlf -----#\n[dc:Wlf_medhigh_Wen]\nvar = 1 \nrange = 1,0,2 \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = cr\n\n[dc:Wlf_medhigh_Wmn]\nvar = 1 \nrange = 1,0,2\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = cr\n\n#----- Signal -----#\n[dc:SR_medhigh_Wen]\nrebin_method = list\nrebin_list = <!SR_medhigh_Wln|bins!> \nvar = <!SR_medhigh_Wln|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = BDT\n\n[dc:SR_medhigh_Wmn]\nrebin_method = list\nrebin_list = <!SR_medhigh_Wln|bins!> \nvar = <!SR_medhigh_Wln|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = BDT\n\n[dc:SR_medhigh_Wln]\nrebin_method = list\nrebin_list = <!SR_medhigh_Wln|bins!> \nvar = <!SR_medhigh_Wln|branchName!>.Nominal\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|Data!>\ntype = BDT\n\n\n# ---------- VV ----------\n[dc:VV_SR_medhigh_Wen]\nrebin_method = list\nrebin_list = <!VV_SR_medhigh_Wln|bins!> \nvar = <!VV_SR_medhigh_Wln|branchName!>.Nominal\nsignal = <!Datacard|VV_Signals!>\nbackground = <!Datacard|VV_Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = BDT\n\n[dc:VV_SR_medhigh_Wmn]\nrebin_method = list\nrebin_list = <!VV_SR_medhigh_Wln|bins!> \nvar = <!VV_SR_medhigh_Wln|branchName!>.Nominal\nsignal = <!Datacard|VV_Signals!>\nbackground = <!Datacard|VV_Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = BDT\n\n# Mjj\n[dc:Mjj_SR_medhigh_Wen_0]\nvar = <!LimitGeneral|Mass!> \nrange = 12,90.0,150.0\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = BDT\n\n[dc:Mjj_SR_medhigh_Wen_1]\nvar = <!LimitGeneral|Mass!> \nrange = 12,90.0,150.0\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = BDT\n\n[dc:Mjj_SR_medhigh_Wen_2]\nvar = <!LimitGeneral|Mass!> \nrange = 12,90.0,150.0\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = BDT\n\n[dc:Mjj_SR_medhigh_Wen_3]\nvar = <!LimitGeneral|Mass!> \nrange = 12,90.0,150.0\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = BDT\n\n[dc:Mjj_SR_medhigh_Wmn_0]\nvar = <!LimitGeneral|Mass!> \nrange = 12,90.0,150.0\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = BDT\n\n[dc:Mjj_SR_medhigh_Wmn_1]\nvar = <!LimitGeneral|Mass!> \nrange = 12,90.0,150.0\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = BDT\n\n[dc:Mjj_SR_medhigh_Wmn_2]\nvar = <!LimitGeneral|Mass!> \nrange = 12,90.0,150.0\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = BDT\n\n[dc:Mjj_SR_medhigh_Wmn_3]\nvar = <!LimitGeneral|Mass!> \nrange = 12,90.0,150.0\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = BDT\n\n\n# multi-class datacards\n\n[dc:Multi_medhigh_Wen_SIG]\ncut = Multi_medhigh_Wen\nrebin_method = list\nrebin_list = <!Multi|binsWenSR!> \nvar = <!Multi|Wen!> \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = BDT\n\n[dc:Multi_medhigh_Wmn_SIG]\ncut = Multi_medhigh_Wmn\nrebin_method = list\nrebin_list = <!Multi|binsWmnSR!> \nvar = <!Multi|Wmn!> \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = BDT\n\n[dc:Multi_medhigh_Wen_BKG]\ncut = Multi_medhigh_Wen\nrebin_method = list\nrebin_list = <!Multi|binsWenCR!> \nvar = <!Multi|Wen!> \nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|eData!>\ntype = BDT\n\n[dc:Multi_medhigh_Wmn_BKG]\ncut = Multi_medhigh_Wmn\nrebin_method = list\nrebin_list = <!Multi|binsWmnCR!> \nvar = <!Multi|Wmn!>\nsignal = <!Datacard|Signals!>\nbackground = <!Datacard|Backgrounds!>\ndata = <!Plot_general|muData!>\ntype = BDT\n\n[WJetsToLNu_HT-200To400_TuneCP5_13TeV-madgraphMLM-pythia8]\nmergeCachingSize=1\n[WJetsToLNu_HT-400To600_TuneCP5_13TeV-madgraphMLM-pythia8]\nmergeCachingSize=1\n[WJetsToLNu_HT-600To800_TuneCP5_13TeV-madgraphMLM-pythia8]\nmergeCachingSize=1\n[WJetsToLNu_HT-800To1200_TuneCP5_13TeV-madgraphMLM-pythia8]\nmergeCachingSize=1\n[WJetsToLNu_HT-1200To2500_TuneCP5_13TeV-madgraphMLM-pythia8]\nmergeCachingSize=1\n[WJetsToLNu_HT-2500ToInf_TuneCP5_13TeV-madgraphMLM-pythia8]\nmergeCachingSize=1\n\n" }, { "alpha_fraction": 0.6006808280944824, "alphanum_fraction": 0.6774024367332458, "avg_line_length": 20.94827651977539, "blob_id": "1774d575f738148443bc10918b678eed4596e8fb", "content_id": "b4f82f2b6287775ce7aee8aa70753dff32930b9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 3819, "license_type": "no_license", "max_line_length": 554, "num_lines": 174, "path": "/python/Zvv2017config/fit.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "[Fit]\nFitDiagnosticsDump = /work/berger_p2/VHbb/CMSSW_10_2_13/src/CombineHarvester/VHLegacy/output/cmb_V11_Mar4_STXS_fix_2017/cmb_CRonly/fitDiagnostics.Test.root \n\n# Zlf_med_Znn,Zhf_med_Znn,ttbar_med_Znn,Zlf_high_Znn,Zhf_high_Znn,ttbar_high_Znn\nregions = {\"SR_med_Znn_0j\":\"vhbb_Znn_5_13TeV2017\", \"Zlf_med_Znn\":\"vhbb_Znn_6_13TeV2017\", \"Zhf_med_Znn\":\"vhbb_Znn_7_13TeV2017\", \"ttbar_med_Znn\":\"vhbb_Znn_8_13TeV2017\", \"SR_med_Znn_ge1j\":\"vhbb_Znn_9_13TeV2017\", \"SR_high_Znn\":\"vhbb_Znn_13_13TeV2017\", \"Zlf_high_Znn\":\"vhbb_Znn_14_13TeV2017\", \"Zhf_high_Znn\":\"vhbb_Znn_15_13TeV2017\", \"ttbar_high_Znn\":\"vhbb_Znn_16_13TeV2017\", \"SR_high_Znn_BOOST\":\"vhbb_Znn_17_13TeV2017\", \"Zlf_high_Znn_BOOST\":\"vhbb_Znn_18_13TeV2017\", \"Zhf_high_Znn_BOOST\":\"vhbb_Znn_19_13TeV2017\", \"ttbar_high_Znn_BOOST\":\"vhbb_Znn_20_13TeV2017\"}\nregions_multi = {\"Multi_medhigh_Znn_SIG\": \"vhbb_Znn_1_13TeV2017\", \"Multi_medhigh_Znn_BKG\": \"vhbb_Znn_5_13TeV2017\"} \nregions_mjj = {\"Znn_Mjj_0\": \"vhbb_Znn_1_13TeV2017\", \"Znn_Mjj_1\": \"vhbb_Znn_2_13TeV2017\", \"Znn_Mjj_2\": \"vhbb_Znn_3_13TeV2017\", \"Znn_Mjj_3\": \"vhbb_Znn_4_13TeV2017\"}\n\nplotCaption = \"combined fit\"\nplotText = [\"post-fit\" if \"_fit_s\" in self.directory else \"pre-fit\",self.region, <!.|plotCaption!>]\nplotText_multi = [\"post-fit\" if \"_fit_s\" in self.directory else \"pre-fit\",self.region, <!.|plotCaption!>] \n\nblindBins = [10,11,12,13,14,15]\nsetup = ['ZJets_0b_udsg', 'ZJets_0b_c', 'ZJets_1b', 'ZJets_2b', 'WJets_0b_udsg', 'WJets_0b_c', 'WJets_1b', 'WJets_2b', 'VVHF', 'VVLF', 'TT', 'ST']\n\n[Fit:SR_med_Znn_0j]\nvar = postfitDNN\nblindBins = <!Fit|blindBins!> \nplotDataOverBackground = True\nratioRange = [0.3,3.9]\n\n[Fit:SR_med_Znn_ge1j]\nvar = postfitDNN\nblindBins = <!Fit|blindBins!> \nplotDataOverBackground = True\nratioRange = [0.3,3.9]\n\n[Fit:SR_high_Znn]\nvar = postfitDNN\nblindBins = <!Fit|blindBins!> \nplotDataOverBackground = True\nratioRange = [0.3,3.9]\n\n\n[Fit:Zlf_med_Znn]\nvar = postfitNormalization\nnBins = 1\n\n[Fit:Zlf_high_Znn]\nvar = postfitNormalization\nnBins = 1\n\n[Fit:Zlf_high_Znn_BOOST]\nvar = postfitDeepAK8low \nnBins = 3\n\n\n[Fit:ttbar_med_Znn]\nvar = postfitNormalization\nnBins = 1\n\n[Fit:ttbar_high_Znn]\nvar = postfitNormalization\nnBins = 1\n\n[Fit:ttbar_high_Znn_BOOST]\nvar = postfitDeepAK8high \nnBins = 3\n\n\n[Fit:Znn_Mjj_0]\nvar = postfitMjj\nnBins = 20\n\n[Fit:Znn_Mjj_1]\nvar = postfitMjj\nnBins = 20\n\n[Fit:Znn_Mjj_2]\nvar = postfitMjj\nnBins = 20\n\n[Fit:Znn_Mjj_3]\nvar = postfitMjj\nnBins = 20\n\n[Fit:ttbar_medhigh_Znn]\nvar = postfitNormalization\nnBins = 1\n\n[Fit:Zlf_medhigh_Znn]\nvar = postfitNormalization\nnBins = 1\n\n[Fit:Zhf_medhigh_Znn]\nvar = postfitCRDNN\nnBins = 6\n\n[Fit:Zhf_med_Znn]\nvar = postfitCRDNN\nnBins = 6\n\n[Fit:Zhf_high_Znn]\nvar = postfitCRDNN\nnBins = 6\n\n[Fit:Zhf_high_Znn_BOOST]\nvar = postfitDeepAK8high\nnBins = 3\n\n\n\n[Fit:Multi_medhigh_Znn_SIG]\nvar = postfitCRDNN_SIG\n#blindBins = [0,1,2,3,12,13,14,15] \nblindBins = [11,12,13,14,15] \n\n[Fit:Multi_medhigh_Znn_BKG]\nvar = postfitCRDNN_BKG\n\n[plotDef:postfitDNN]\nrelPath = 1\nxAxis = DNN bin\nnBins = 15\nmin = 0\nmax = 15\nlog = True\n\n[plotDef:postfitMjj]\nrelPath = 1\nxAxis = m_{jj} \nnBins = 20\nmin = 60\nmax = 160\nlog = False\n\n[plotDef:postfitNormalization]\nrelPath = 1\nxAxis = normalization\nnBins = 2\nmin = 0\nmax = 2\n\n[plotDef:postfitDeepCSV2]\nrelPath = 1\nxAxis = min DeepCSV bin\nnBins = 2\nmin = 0\nmax = 2\n\n[plotDef:postfitCRDNN]\nrelPath = None \nxAxis = CRDNN\nnBins = 5\nmin = 0\nmax = 5\n\n[plotDef:postfitCRDNN_SIG]\nrelPath = None\nxAxis = DNN bin\nnBins = 15\nmin = 0\nmax = 15\n\n[plotDef:postfitCRDNN_BKG]\nrelPath = None\nxAxis = Multi-class DNN bin\nnBins = 50\nmin = 0\nmax = 50\n\n[plotDef:postfitDeepAK8high]\nrelPath = 1\nxAxis = DeepAK8\nnBins = 3\nmin = 0.8\nmax = 1\n\n[plotDef:postfitDeepAK8low]\nrelPath = 1\nxAxis = DeepAK8\nnBins = 3\nmin = 0\nmax = 0.8\n" }, { "alpha_fraction": 0.6520503163337708, "alphanum_fraction": 0.6950873136520386, "avg_line_length": 35.761192321777344, "blob_id": "1432472f7d3cfcd4c6fb18d5985fbbdeb41984ad", "content_id": "9d4a8bd739d125439402f71fc03db89da0a083bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 2463, "license_type": "no_license", "max_line_length": 402, "num_lines": 67, "path": "/python/Wlv2018config/paths.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "[Configuration]\n#!! List of the config you want to use\n#!! The list only support spaces between configs\nList = paths.ini ../VHbb2018commonconfig/general.ini general.ini ../Wlv2018config/cuts.ini training_WP.ini datacards.ini ../VHbb2018commonconfig/systematics.ini plots.ini lhe_weights.ini ../VHbb2018commonconfig/samples_mc.ini ../VHbb2018commonconfig/stxs.ini hadd.ini data.ini fit.ini ../VHbb2018commonconfig/vhbbPlotDef.ini vhbbPlotDef.ini volatile.ini ../VHbb2018commonconfig/EventCounts2018V12.ini\n\n# general config\n#whereToLaunch = PSI\nwhereToLaunch = auto\nuser = %(USER)s\ncmsswbase = %(CMSSW_BASE)s\n\n# Xrootd config, first redirector is the primary one if multiple ones are given\nxrootdRedirectors = eoscms.cern.ch\nxrootdRedirectorGlobal = root://t3dcachedb.psi.ch:1094//pnfs/psi.ch/cms/trivcat/\npnfsStoragePath = .\n\n# datasets\ndatasets = <!Configuration|cmsswbase!>/src/Xbb/samples/VHbbPostNano2018_V5.txt\ndasQuery = dasgoclient -query=\"file dataset={dataset} instance=prod/phys03\"\n\n[Directories]\nDname = logs_Wlv2018\ntagDir = <!Directories|vhbbpath!>/python/<!Directories|Dname!>/\nscratch = scratch\nWdir = <!Configuration|cmsswbase!>/src/\nsamplepath = <!Directories|plottingSamples!>\ntmpSamples = /data/t3home000/dabercro/Xbb/Wlv2018_tmp\n\n#samplefiles = <!Configuration|cmsswbase!>/src/Xbb/samples/VHbbPostNano2017_V5/merged_Wlv2017/\nsamplefiles = <!Configuration|cmsswbase!>/src/Xbb/samples/VHbbPostNano2018_V12\n#VHbbPostNano2018_V4_2/merged_Wlv2018\nsamplefiles_split = <!Configuration|cmsswbase!>/src/Xbb/samples/VHbbPostNano2018_V6_V1_Wlv\n#VHbbPostNano2018_V4_2/\n\n;!! The directory with the code\nvhbbpath= <!Directories|Wdir!>/Xbb\n\n;#!! cached files\n\n;!! from which samples to plot and where to save the plots\n;plottingSamples = <!Directories|SYSout2!>\n;plottingSamples = <!Directories|SYSoutv1!> \nplottingSamples = <!Directories|CONDORout!> \n\n#!! from which samples to make the DCs and where to save the DCs\ndcSamples = <!Directories|CONDORout!>\n\n# --------------------------------------------------------------------------------\n# PATHS\n# --------------------------------------------------------------------------------\n\n# step 1) prep\nPREPin = root://eoscms.cern.ch/\nPREPout = prep\n\nHADDin = <!Directories|PREPout!> \nHADDout = prep\n#17jan20\n\nSYSin = prep\nSYSout = sys\n\nMVAin = sys\nMVAout = mva\n\nCONDORin = mva\nCONDORout = /mnt/hadoop/scratch/dabercro/Xbb/Wlv2018\n" }, { "alpha_fraction": 0.5979247689247131, "alphanum_fraction": 0.6044098734855652, "avg_line_length": 49.81318664550781, "blob_id": "f197c6ae0a152f6e4c8ec20c5e261d88a5f5cceb", "content_id": "e94976d34f264e8b48267ec193bff445afb4dc97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4626, "license_type": "no_license", "max_line_length": 577, "num_lines": 91, "path": "/python/myutils/METXY.py", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nfrom __future__ import print_function\nimport ROOT\nfrom BranchTools import Collection\nfrom BranchTools import AddCollectionsModule\nimport array\nimport os\nimport math\nimport numpy as np\n\n# MET X/Y correction \nclass METXY(AddCollectionsModule):\n\n def __init__(self, year):\n super(METXY, self).__init__()\n self.debug = 'XBBDEBUG' in os.environ\n self.year = int(year)\n self.quickloadWarningShown = False\n \n self.systematics = ['jer','jesAbsoluteStat','jesAbsoluteScale','jesAbsoluteFlavMap','jesAbsoluteMPFBias','jesFragmentation','jesSinglePionECAL','jesSinglePionHCAL','jesFlavorQCD','jesRelativeJEREC1','jesRelativeJEREC2','jesRelativeJERHF','jesRelativePtBB','jesRelativePtEC1','jesRelativePtEC2','jesRelativePtHF','jesRelativeBal','jesRelativeFSR','jesRelativeStatFSR','jesRelativeStatEC','jesRelativeStatHF','jesPileUpDataMC','jesPileUpPtRef','jesPileUpPtBB','jesPileUpPtEC1','jesPileUpPtEC2','jesPileUpPtHF','jesPileUpMuZero','jesPileUpEnvelope','jesTotal','unclustEn']\n\n def customInit(self, initVars):\n self.sampleTree = initVars['sampleTree']\n self.sample = initVars['sample']\n self.config = initVars['config']\n\n # load METXYCorr_Met_MetPhi from VHbb namespace\n VHbbNameSpace = self.config.get('VHbbNameSpace', 'library')\n ROOT.gSystem.Load(VHbbNameSpace)\n\n self.MET_Pt = array.array('f', [0.0])\n self.MET_Phi = array.array('f', [0.0])\n self.sampleTree.tree.SetBranchAddress(\"MET_Pt\", self.MET_Pt)\n self.sampleTree.tree.SetBranchAddress(\"MET_Phi\", self.MET_Phi)\n\n self.addBranch(\"MET_Pt_uncorrected\")\n self.addBranch(\"MET_Phi_uncorrected\")\n\n if self.sample.isMC():\n self.MET_Pt_syst = {}\n self.MET_Phi_syst = {}\n for syst in self.systematics:\n self.MET_Pt_syst[syst] = {}\n self.MET_Phi_syst[syst] = {}\n for Q in self._variations(syst):\n self.MET_Pt_syst[syst][Q] = array.array('f', [0.0])\n self.MET_Phi_syst[syst][Q] = array.array('f', [0.0])\n self.sampleTree.tree.SetBranchAddress(\"MET_pt_\"+syst+Q, self.MET_Pt_syst[syst][Q])\n self.sampleTree.tree.SetBranchAddress(\"MET_phi_\"+syst+Q, self.MET_Phi_syst[syst][Q])\n\n self.addBranch(\"MET_pt_uncorrected_\"+syst+Q)\n self.addBranch(\"MET_phi_uncorrected_\"+syst+Q)\n\n\n def processEvent(self, tree):\n if not self.hasBeenProcessed(tree):\n self.markProcessed(tree)\n\n # backup uncorrected branches\n self._b('MET_Pt_uncorrected')[0] = tree.MET_Pt\n self._b('MET_Phi_uncorrected')[0] = tree.MET_Phi\n\n MET_Pt_corrected, MET_Phi_corrected = ROOT.VHbb.METXYCorr_Met_MetPhi(tree.MET_Pt, tree.MET_Phi, tree.run, self.year, self.sample.isMC(), tree.PV_npvs)\n\n # overwrite MET_Pt, MET_Phi branches\n self.MET_Pt[0] = MET_Pt_corrected\n self.MET_Phi[0] = MET_Phi_corrected\n\n if self.sample.isMC():\n for syst in self.systematics:\n for Q in self._variations(syst):\n \n # backup uncorrected branches\n self._b(\"MET_pt_uncorrected_\"+syst+Q)[0] = self.MET_Pt_syst[syst][Q][0]\n self._b(\"MET_phi_uncorrected_\"+syst+Q)[0] = self.MET_Phi_syst[syst][Q][0]\n\n MET_Pt_corrected, MET_Phi_corrected = ROOT.VHbb.METXYCorr_Met_MetPhi(self.MET_Pt_syst[syst][Q][0], self.MET_Phi_syst[syst][Q][0], tree.run, self.year, self.sample.isMC(), tree.PV_npvs)\n\n # overwrite MET_Pt, MET_Phi branches\n self.MET_Pt_syst[syst][Q][0] = MET_Pt_corrected\n self.MET_Phi_syst[syst][Q][0] = MET_Phi_corrected\n \n # formulas by default reload the branch content when evaluating the first instance of the object!\n # SetQuickLoad(1) turns off this behavior\n for formulaName, treeFormula in self.sampleTree.formulas.items():\n if 'MET' in formulaName:\n if not self.quickloadWarningShown:\n self.quickloadWarningShown = True\n print(\"INFO: SetQuickLoad(1) called for formula:\", formulaName)\n print(\"INFO: -> EvalInstance(0) on formulas will not re-load branches but will take values from memory, which might have been modified by this module.\") \n treeFormula.SetQuickLoad(1)\n\n\n" }, { "alpha_fraction": 0.6983346939086914, "alphanum_fraction": 0.7608517408370972, "avg_line_length": 52.08695602416992, "blob_id": "6c32eec4498dccfc2738b4f6c0f2f353b82b1f6f", "content_id": "87aefda108e0aac9f8229683bc3f66250639dd7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 3663, "license_type": "no_license", "max_line_length": 333, "num_lines": 69, "path": "/python/Zll2017config/paths.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "[Configuration]\n#!! List of the config you want to use\n#!! The list only support spaces between configs\nList = paths.ini ../VHbb2017commonconfig/general.ini general.ini cuts.ini training.ini ../VHbb2017commonconfig/systematics.ini datacards.ini plots.ini lhe_weights.ini ../VHbb2017commonconfig/samples_mc.ini ../VHbb2017commonconfig/stxs.ini hadd.ini data.ini ../VHbb2017commonconfig/vhbbPlotDef.ini vhbbPlotDef.ini fit.ini volatile.ini\n\n# general config\n#whereToLaunch = PSI\nwhereToLaunch = auto\nuser = %(USER)s\ncmsswbase = %(CMSSW_BASE)s\n\n# Xrootd config, first redirector is the primary one if multiple ones are given\nxrootdRedirectors = root://t3dcachedb03.psi.ch:1094/ \nxrootdRedirectorGlobal = root://eoscms.cern.ch/\npnfsStoragePath = .\n\n[Directories]\nDname = logs_Zll2017 \nWdir = <!Configuration|cmsswbase!>/src/\nvhbbpath = <!Directories|Wdir!>/Xbb\ntagDir = <!Directories|vhbbpath!>/python/<!Directories|Dname!>/\nscratch = /scratch/<!Configuration|user!>/\nsamplepath = <!Directories|plottingSamples!>\n\n# original samples\nsamplefiles = <!Configuration|cmsswbase!>/src/Xbb/samples/VHbbPostNano2017_V11/merged_Zll2017/\nsamplefiles_split = <!Configuration|cmsswbase!>/src/Xbb/samples/VHbbPostNano2017_V11/\n\n;!! from which samples to plot and where to save the plots\n;plottingSamples: <!Directories|PREPout!> \n;plottingSamples: <!Directories|SYSout!> \nplottingSamples: <!Directories|MVAout!> \n;plottingSamples: <!Directories|KINFITout!> \n;plottingSamples: <!Directories|SYSin!> \n\n;#!! cached files\ntmpSamples = root://t3dcachedb03.psi.ch:1094//pnfs/psi.ch/cms/trivcat/store/user/<!Configuration|user!>/VHbb/Zll/VHbbPostNano2017_V11/tmp/v1/\n\n#!! from which samples to make the DCs and where to save the DCs\ndcSamples = <!Directories|MVAout!> \n\n# step 1) prep\nPREPin = root://eoscms.cern.ch/\nPREPout = root://t3dcachedb03.psi.ch:1094//pnfs/psi.ch/cms/trivcat/store/user/<!Configuration|user!>/VHbb/Zll/VHbbPostNano2017_V11/Jan2020/prep/\n\n# step 2) hadd\nHADDin = <!Directories|PREPout!>\nHADDout = root://t3dcachedb03.psi.ch:1094//pnfs/psi.ch/cms/trivcat/store/user/<!Configuration|user!>/VHbb/Zll/VHbbPostNano2017_V11/Jan2020/hadd/\n\n# step 3) add systematic variations and weights\nSYSin = <!Directories|HADDout!>\nSYSout = root://t3dcachedb03.psi.ch:1094//pnfs/psi.ch/cms/trivcat/store/user/<!Configuration|user!>/VHbb/Zll/VHbbPostNano2017_V11/Jan2020/sys/\n\nKINFITin = <!Directories|SYSout!>\nKINFITout = root://t3dcachedb03.psi.ch:1094//pnfs/psi.ch/cms/trivcat/store/user/<!Configuration|user!>/VHbb/Zll/VHbbPostNano2017_V11/Jan2020/kinfit_temp_<!KinematicFit|slice!>/\n\nKINFITMERGEin = <!Directories|KINFITin!> \nKINFITMERGEbase = root://t3dcachedb03.psi.ch:1094//pnfs/psi.ch/cms/trivcat/store/user/<!Configuration|user!>/VHbb/Zll/VHbbPostNano2017_V11/Jan2020/kinfit_temp\nKINFITMERGEout = root://t3dcachedb03.psi.ch:1094//pnfs/psi.ch/cms/trivcat/store/user/<!Configuration|user!>/VHbb/Zll/VHbbPostNano2017_V11/Jan2020/kinfit/\n\n#MVAin: <!Directories|KINFITMERGEout!>\nMVAin = <!Directories|KINFITMERGEout!>\nMVAout = root://t3dcachedb03.psi.ch:1094//pnfs/psi.ch/cms/trivcat/store/user/<!Configuration|user!>/VHbb/Zll/VHbbPostNano2017_V11/Jan2020/eval/\n\n# previous iteration\n#in: root://t3dcachedb03.psi.ch:1094//pnfs/psi.ch/cms/trivcat/store/user/<!Configuration|user!>/VHbb/Zll/VHbbPostNano2017_V11/final/eval/v27/\n#out: root://t3dcachedb03.psi.ch:1094//pnfs/psi.ch/cms/trivcat/store/user/<!Configuration|user!>/VHbb/Zll/VHbbPostNano2017_V11/final/eval/v28/\n\n#MVAout: root://t3dcachedb03.psi.ch:1094//pnfs/psi.ch/cms/trivcat/store/user/<!Configuration|user!>/VHbb/Zll/VHbbPostNano2017_V11/eleIDV2/eval/v11/\n" }, { "alpha_fraction": 0.40701916813850403, "alphanum_fraction": 0.7088502645492554, "avg_line_length": 73.43209838867188, "blob_id": "802e31b641eb2ad1e579513dc6650788bc6d1f1c", "content_id": "853d327480bbe903eee808d2631430efd4cd89c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 30146, "license_type": "no_license", "max_line_length": 929, "num_lines": 405, "path": "/python/Wlv2017config/training.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": ";!! -----------------------------\n;!! Config for the MVA training\n;!! -----------------------------\n[factory]\nfactoryname = MVA\nfactorysettings = V:!Silent:!Color:!DrawProgressBar:AnalysisType=Classification:Transformations=I\n\n[MVAGeneral]\n;!! ------------------\n;!! Factory settings\n;!! ------------------\nntupleVersion = V11-Dec9\ntype = BDT\n\n[MVALists]\n;List_for_submitscript = SR_medhigh_Wln,Whf_medhigh_Wln,VV_SR_medhigh_Wln,VV_Whf_medhigh_Wln\nList_for_submitscript = <!.|List!>\n\nList = <!.|List_VH!>,<!.|List_VV!>,<!.|List_Boosted!>\nList_VH = SR_medhigh_Wln,Whf_medhigh_Wln\nList_VV = VV_SR_medhigh_Wln,VV_Whf_medhigh_Wln\nList_Multi = Multi_medhigh_Wln\nList_Boosted = BDT_Wlv_BOOSTFinal_wdB\n\n[HFCR]\nnClasses = 5\nclasses = <!.|classes_<!.|nClasses!>!>\nclasses_5 = [['WLIGHT',[<!Samples|DY_0b!>,<!Samples|WJets_0b!>,<!Samples|ZJets_0b!>,<!Samples|VVLF!>,<!Samples|VVHF!>,<!Samples|ZHsignal!>,<!Samples|ggZHsignal!>,<!Samples|WHsignal!>,<!Samples|QCD!>]],['WB',[<!Samples|DY_1b!>,<!Samples|WJets_1b!>,<!Samples|ZJets_1b!>]],['WBB',[<!Samples|DY_2b!>,<!Samples|WJets_2b!>,<!Samples|ZJets_2b!>]],['ST',[<!Samples|ST!>]],['TT',[<!Samples|TT!>]]]\nclasses_6 = [['WLIGHT',[<!Samples|DY_0b!>,<!Samples|WJets_0b!>,<!Samples|ZJets_0b!>,<!Samples|VVLF!>,<!Samples|VVHF!>,<!Samples|ZHsignal!>,<!Samples|ggZHsignal!>,<!Samples|WHsignal!>]],['WB',[<!Samples|DY_1b!>,<!Samples|WJets_1b!>,<!Samples|ZJets_1b!>]],['WBB',[<!Samples|DY_2b!>,<!Samples|WJets_2b!>,<!Samples|ZJets_2b!>]],['ST',[<!Samples|ST!>]],['TT',[<!Samples|TT!>]],['QCD',[<!Samples|QCD!>]]]\nclasses_T = [['WLIGHT',[<!Samples|DY_0b!>,<!Samples|WJets_0b!>,<!Samples|ZJets_0b!>]],['WB',[<!Samples|DY_1b!>,<!Samples|WJets_1b!>,<!Samples|ZJets_1b!>]],['WBB',[<!Samples|DY_2b!>,<!Samples|WJets_2b!>,<!Samples|ZJets_2b!>]],['ST',[<!Samples|ST!>]],['TT',[<!Samples|TT!>]],['TRASH',[<!Samples|QCD!>,<!Samples|VVLF!>,<!Samples|VVHF!>,<!Samples|ZHsignal!>,<!Samples|ggZHsignal!>,<!Samples|WHsignal!>]]]\nWc = [['WLIGHT',[<!Samples|DY_0b!>,<!Samples|WJets_0b_udsg!>,<!Samples|ZJets_0b_udsg!>,<!Samples|VVLF!>,<!Samples|VVHF!>,<!Samples|ZHsignal!>,<!Samples|ggZHsignal!>,<!Samples|WHsignal!>]],['WC',[<!Samples|WJets_0b_c!>,<!Samples|ZJets_0b_c!>]],['WB',[<!Samples|DY_1b!>,<!Samples|WJets_1b!>,<!Samples|ZJets_1b!>]],['WBB',[<!Samples|DY_2b!>,<!Samples|WJets_2b!>,<!Samples|ZJets_2b!>]],['ST',[<!Samples|ST!>]],['TT',[<!Samples|TT!>]]]\n#\n#Wc = [['WLIGHT',[<!Samples|DY_0b!>,<!Samples|WJets_0b_udsg!>,<!Samples|ZJets_0b!>,<!Samples|VVLF!>,<!Samples|VVHF!>,<!Samples|ZHsignal!>,<!Samples|ggZHsignal!>,<!Samples|WHsignal!>]],['WC',[<!Samples|WJets_0b_c!>]],['WCC',[<!Samples|WJets_0b_2c!>]],['WB',[<!Samples|DY_1b!>,<!Samples|WJets_1b_udsg!>,<!Samples|ZJets_1b!>]],['WBC',[<!Samples|DY_1b!>,<!Samples|WJets_1b_c!>,<!Samples|ZJets_1b!>]],['WBB',[<!Samples|DY_2b!>,<!Samples|WJets_2b!>,<!Samples|ZJets_2b!>]],['ST',[<!Samples|ST!>]],['TT',[<!Samples|TT!>]]]\n\n[SR_medhigh_Wen]\nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ntreeVarSet = WlvBDTVarsWP\ntreeCut = SR_medhigh_Wen \nsignalIndex = 0\nbins = <!SR_medhigh_Wln|bins!> \n\n[SR_medhigh_Wmn]\nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ntreeVarSet = WlvBDTVarsWP\ntreeCut = SR_medhigh_Wmn\nsignalIndex = 0\nbins = <!SR_medhigh_Wln|bins!> \n\n[SR_medhigh_Wln]\nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ntreeVarSet = WlvBDTVarsWP\ntreeCut = SR_medhigh_Wln\nbranchName = DNN_200122_VHLegacyDNN2017V11_Wln_Jan2020OverlapToResolvedDeepCSVwp_SR_medhigh_Wln\ncheckpoint = DNN/200122_VHLegacyDNN2017V11_Wln_Jan2020OverlapToResolvedDeepCSVwp_SR_medhigh_Wln\nsignalIndex = 0\nbins = [0.0000, 0.0598, 0.1126, 0.1702, 0.2415, 0.3324, 0.4374, 0.5562, 0.6701, 0.7683, 0.8464, 0.9036, 0.9436, 0.9702, 0.9878, 1.0001]\n\n[SR_med_Wln]\nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ntreeVarSet = WlvBDTVarsWP\ntreeCut = SR_med_Wln\nbranchName = DNN_190704_DNN2017V11_Wmn_SR_maxBtagCutAtMedium_binnedWP\ncheckpoint = DNN/190704_DNN2017V11_Wmn_SR_maxBtagCutAtMedium_binnedWP/model.ckpt\nsignalIndex = 0\nbins = <!SR_medhigh_Wln|bins!> \n\n[SR_high_Wln]\nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ntreeVarSet = WlvBDTVarsWP\ntreeCut = SR_high_Wln\nbranchName = DNN_190704_DNN2017V11_Wmn_SR_maxBtagCutAtMedium_binnedWP\ncheckpoint = DNN/190704_DNN2017V11_Wmn_SR_maxBtagCutAtMedium_binnedWP/model.ckpt\nsignalIndex = 0\nbins = <!SR_medhigh_Wln|bins!> \n\n[VV_SR_medhigh_Wen]\nsignals = [<!Plot_general|VVSIG!>]\nbackgrounds = [<!Plot_general|VVBKG!>]\ntreeVarSet = WlvBDTVarsWP\ntreeCut = VV_SR_medhigh_Wen \nbins = <!VV_SR_medhigh_Wln|bins!>\nsignalIndex = 0\n\n[VV_SR_medhigh_Wmn]\nsignals = [<!Plot_general|VVSIG!>]\nbackgrounds = [<!Plot_general|VVBKG!>]\ntreeVarSet = WlvBDTVarsWP\ntreeCut = VV_SR_medhigh_Wmn \nbins = <!VV_SR_medhigh_Wln|bins!>\nsignalIndex = 0\n\n[VV_SR_medhigh_Wln]\nsignals = [<!Plot_general|VVSIG!>]\nbackgrounds = [<!Plot_general|VVBKG!>]\ntreeVarSet = WlvBDTVarsWP\ntreeCut = VV_SR_medhigh_Wln \nbranchName = DNN_200403_VHLegacyDNN2017V11_Wln_Feb2020flavBhadrons25DeepCSVwpOverlapToResolved_VV_SR_medhigh_Wln\ncheckpoint = DNN/200403_VHLegacyDNN2017V11_Wln_Feb2020flavBhadrons25DeepCSVwpOverlapToResolved_VV_SR_medhigh_Wln\nbins = [0.0000, 0.1099, 0.1703, 0.2355, 0.3144, 0.3940, 0.4594, 0.5459, 0.6419, 0.7332, 0.8096, 0.8701, 0.9142, 0.9438, 0.9655, 1.0001]\nsignalIndex = 0\n\n[VV_SR_med_Wln]\nsignals = [<!Plot_general|VVSIG!>]\nbackgrounds = [<!Plot_general|VVBKG!>]\ntreeVarSet = WlvBDTVarsWP\ntreeCut = VV_SR_med_Wln \nbranchName = DNN_200403_VHLegacyDNN2017V11_Wln_Feb2020flavBhadrons25DeepCSVwpOverlapToResolved_VV_SR_medhigh_Wln\ncheckpoint = DNN/200403_VHLegacyDNN2017V11_Wln_Feb2020flavBhadrons25DeepCSVwpOverlapToResolved_VV_SR_medhigh_Wln\nbins = [0.0000, 0.1014, 0.1701, 0.2491, 0.3402, 0.4248, 0.4910, 0.5707, 0.6584, 0.7450, 0.8172, 0.8739, 0.9139, 0.9407, 0.9621, 1.0001]\nsignalIndex = 0\n\n[VV_SR_high_Wln]\nsignals = [<!Plot_general|VVSIG!>]\nbackgrounds = [<!Plot_general|VVBKG!>]\ntreeVarSet = WlvBDTVarsWP\ntreeCut = VV_SR_high_Wln \nbranchName = DNN_200403_VHLegacyDNN2017V11_Wln_Feb2020flavBhadrons25DeepCSVwpOverlapToResolved_VV_SR_medhigh_Wln\ncheckpoint = DNN/200403_VHLegacyDNN2017V11_Wln_Feb2020flavBhadrons25DeepCSVwpOverlapToResolved_VV_SR_medhigh_Wln\nbins = [0.0000, 0.0908, 0.1360, 0.1856, 0.2400, 0.3015, 0.3716, 0.4292, 0.4870, 0.5504, 0.6245, 0.6901, 0.7575, 0.8335, 0.9017, 1.0001]\nsignalIndex = 0\n\n\n# TEST classifiers\n[Wlf_med_Wln]\nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ndata = <!Plot_general|Data!>\nincludeData = True\ntreeVarSet = WlvBDTVarsWP\ntreeCut = Wlf_med_Wln \nsignalIndex = 0\n\n[Wlf_medhigh_Wln]\nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ndata = <!Plot_general|Data!>\nincludeData = True\ntreeVarSet = WlvBDTVarsWP\ntreeCut = Wlf_medhigh_Wln \nsignalIndex = 0\n\n\n# BACKGROUND MULTI classifier\n\n[Whf_med_Wen]\nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ndata = <!Plot_general|eData!>\nincludeData = True\ntreeVarSet = WlvBDTVarsWP\ntreeCut = Whf_med_Wen \nclasses = <!Whf_medhigh_Wln|classes!> \nbins = [0, 1, 2, 3, 4, 5.0001]\n\n\n[Whf_med_Wmn]\nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ndata = <!Plot_general|muData!>\nincludeData = True\ntreeVarSet = WlvBDTVarsWP\ntreeCut = Whf_med_Wmn\nclasses = <!Whf_medhigh_Wln|classes!> \nbins = [0, 1, 2, 3, 4, 5.0001]\n\n[Whf_medhigh_Wln]\nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ndata = <!Plot_general|Data!>\nincludeData = True\ntreeVarSet = WlvBDTVarsWP\ntreeCut = Whf_medhigh_Wln\ncheckpoint = DNN/200228_VHLegacyDNN2017V11_Wln_Feb2020OverlapToResolvedDeepCSVwpNewFlav_Whf_medhigh_Wln\nbranchName = DNN_200228_VHLegacyDNN2017V11_Wln_Feb2020OverlapToResolvedDeepCSVwpNewFlav_Whf_medhigh_Wln\nclasses = <!HFCR|classes!>\nbins = [0, 1, 2, 3, 4, 5.0001]\nbins_2 = [0.0, 0.5031176550716648, 1.0, 1.367145249609191, 2.0, 2.407183428988726, 3.0, 3.388954386019735, 4.0, 4.464538687246538, 5.0001]\nbins_3 = [0.0, 0.4407655098803919, 0.5669487068768595, 1.0, 1.3319538927151906, 1.4098483680650813, 2.0, 2.3587354554922872, 2.471493774174012, 3.0, 3.3499914702023705, 3.4312395835449943, 4.0, 4.40524447633785, 4.532487406721602, 5.0001]\nbins_4 = [0.0, 0.40923300229039816, 0.5031176550716648, 0.5993863733801625, 1.0, 1.316338604482412, 1.367145249609191, 1.4380169942221086, 2.0, 2.3361541212795482, 2.407183428988726, 2.5198101398565482, 3.0, 3.3308848961748443, 3.388954386019735, 3.455931814516247, 4.0, 4.37512414220145, 4.464538687246538, 4.574671696730449, 5.0001]\nbins_5 = [0.0, 0.3891846184155254, 0.4656431566353023, 0.5413712371587293, 0.618629459705099, 1.0, 1.306912442986801, 1.3452350322600695, 1.3911822368125986, 1.4596793846360658, 2.0, 2.3217628911318533, 2.3774394531036176, 2.442565399820685, 2.5577033182753297, 3.0, 3.319831757398588, 3.3652309675341305, 3.4135417026706896, 3.472984634521638, 4.0, 4.356519510290809, 4.42866116709349, 4.503577930763595, 4.604418370810619, 5.0001]\nbins_10 = [0.0, 0.34267547301963347, 0.3891846184155254, 0.4281921584555048, 0.4656431566353023, 0.5031176550716648, 0.5413712371587293, 0.580148925958189, 0.618629459705099, 0.6624137303041265, 1.0, 1.2850409599473593, 1.306912442986801, 1.3256513976881736, 1.3452350322600695, 1.367145249609191, 1.3911822368125986, 1.4204306451401354, 1.4596793846360658, 1.5191592892441348, 2.0, 2.291371560427933, 2.3217628911318533, 2.349428248308212, 2.3774394531036176, 2.407183428988726, 2.442565399820685, 2.4883848230601266, 2.5577033182753297, 2.6773245784061377, 3.0, 3.294764432720147, 3.319831757398588, 3.3422470584742543, 3.3652309675341305, 3.388954386019735, 3.4135417026706896, 3.440536983500743, 3.472984634521638, 3.5228633538820384, 4.0, 4.318702804472567, 4.356519510290809, 4.393176338806117, 4.42866116709349, 4.464538687246538, 4.503577930763595, 4.54831747195128, 4.604418370810619, 4.680815588075326, 5.0001]\n\n[Whf_med_Wln]\nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ndata = <!Plot_general|Data!>\nincludeData = True\ntreeVarSet = <!Whf_medhigh_Wln|treeVarSet!> \ntreeCut = Whf_med_Wln\n#classes = <!Whf_medhigh_Wln|classes!> \nclasses = <!HFCR|Wc!>\n#bins = <!Whf_medhigh_Wln|bins!> \n#bins = [0.0, 0.30356704567400894, 0.3414082759701505, 0.36897353336325817, 0.40216173495021307, 1.0, 1.3122510053539556, 1.3517598744592387, 1.388836687727203, 1.4317713120331848, 2.0, 2.269986877616368, 2.2962464318336906, 2.32242668336968, 2.3549756270286526, 3.0, 3.3133287571117958, 3.369585222749688, 3.4416804301189567, 3.570886170413374, 4.0, 4.302623697220073, 4.345586240519726, 4.395935366994175, 4.463606428618999, 5.0, 5.337217980179913, 5.418429337765569, 5.503359678901619, 5.604769870526566, 6.0001] \n# Jan2020\n#bins_5 = [0.0, 0.39642986227895294, 0.4745739092692838, 0.5527473484235902, 0.6305160847681015, 1.0, 1.318875583024016, 1.3597697056776707, 1.4066067562125717, 1.4661431539771634, 2.0, 2.356057594221056, 2.422005692621216, 2.5032558515751484, 2.633570863655855, 3.0, 3.322169735669392, 3.3650754761856803, 3.4137562264255044, 3.47848950310525, 4.0, 4.360915514380608, 4.428606974892731, 4.49919392660717, 4.593842110409236, 5.0001]\n#branchName = DNN_200127_VHLegacyDNN2017V11_Wln_Jan2020OverlapToResolvedDeepCSVwp_Whf_med_Wln\n#checkpoint = DNN/200127_VHLegacyDNN2017V11_Wln_Jan2020OverlapToResolvedDeepCSVwp_Whf_med_Wln\n# Feb2020\n#branchName = DNN_200219_VHLegacyDNN2017V11_Wln_Feb2020flavBhadrons25DeepCSVwpOverlapToResolved_Whf_med_Wln\n#checkpoint = DNN/200219_VHLegacyDNN2017V11_Wln_Feb2020flavBhadrons25DeepCSVwpOverlapToResolved_Whf_med_Wln\n#bins_5 = [0.0, 0.3898592792205696, 0.465823349972078, 0.5407750916398725, 0.6147016246364536, 1.0, 1.3047704297711047, 1.3437705573532117, 1.3902082303908256, 1.4575808168711466, 2.0, 2.3200184657396257, 2.3751110362542454, 2.441867526686691, 2.5571375106166263, 3.0, 3.3198049312229836, 3.364178694238851, 3.4123684627423305, 3.4763297633078096, 4.0, 4.357442970763595, 4.427644392877418, 4.502268291317227, 4.603061051367618, 5.0001] \n# loose btag\n#branchName = DNN_200323_VHLegacyDNN2017V11_Wln_Feb2020OverlapToResolvedDeepCSVwpMinLoose_Whf_med_Wln\n#checkpoint = DNN/200323_VHLegacyDNN2017V11_Wln_Feb2020OverlapToResolvedDeepCSVwpMinLoose_Whf_med_Wln\n#bins_5 = [0.0, 0.39332811115826705, 0.46488966914128965, 0.5259286789593262, 0.590351133930236, 1.0, 1.304209594482059, 1.3376740369780464, 1.3742493327382364, 1.4215225957470388, 2.0, 2.345988354899711, 2.4055547390420795, 2.480707436051747, 2.611906598559006, 3.0, 3.3276209408869213, 3.371730177176673, 3.4216029442725047, 3.485790764120968, 4.0, 4.368904029921043, 4.445416715600195, 4.525662975502671, 4.624112567133586, 5.0001] \n# TEST W+c\nbranchName = DNN_200519_VHLegacyDNN2017V11_Wln_Apr2020v5TestSplitWplusC_Whf_med_Wln\ncheckpoint = DNN/200519_VHLegacyDNN2017V11_Wln_Apr2020v5TestSplitWplusC_Whf_med_Wln\n#bins = [0.0, 0.30356704567400894, 0.3414082759701505, 0.36897353336325817, 0.40216173495021307, 1.0, 1.3122510053539556, 1.3517598744592387, 1.388836687727203, 1.4317713120331848, 2.0, 2.269986877616368, 2.2962464318336906, 2.32242668336968, 2.3549756270286526, 3.0, 3.3133287571117958, 3.369585222749688, 3.4416804301189567, 3.570886170413374, 4.0, 4.302623697220073, 4.345586240519726, 4.395935366994175, 4.463606428618999, 5.0, 5.337217980179913, 5.418429337765569, 5.503359678901619, 5.604769870526566, 6.00001]\nbins = [0, 1, 2, 3, 4, 5, 6.0001]\n\n# TEST W6\n#branchName = DNN_200526_VHLegacyDNN2017V11_Wln_Apr2020v5TestSplitW6v2_Whf_med_Wln\n#checkpoint = DNN/200526_VHLegacyDNN2017V11_Wln_Apr2020v5TestSplitW6v2_Whf_med_Wln\n#bins = [0.0, 0.2527683518659244, 0.3007887256098394, 0.3526646616861824, 0.4340123456628638, 1.0, 1.2610901421636855, 1.293690667502696, 1.3245862111405537, 1.3621950363494668, 2.0, 2.252280797886007, 2.2907452172073124, 2.3247472601532486, 2.378415303079514, 3.0, 3.2150306824661623, 3.2436461303407356, 3.272608587342301, 3.3069883386863586, 4.0, 4.231627582762554, 4.265213188856133, 4.300396932945408, 4.352705689733821, 5.0, 5.233173679348866, 5.290228580126506, 5.367980687352731, 5.49410305179782, 6.0, 6.256845670173696, 6.299611596806379, 6.340427915956563, 6.386978893243416, 7.0, 7.282920455133172, 7.355191457552987, 7.432785309196443, 7.543759933638874, 8.00001]\n\n[Whf_high_Wln]\nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ndata = <!Plot_general|Data!>\nincludeData = True\ntreeVarSet = <!Whf_medhigh_Wln|treeVarSet!> \ntreeCut = Whf_high_Wln\n#classes = <!Whf_medhigh_Wln|classes!> \nclasses = <!HFCR|Wc!>\n#bins = <!Whf_medhigh_Wln|bins!> \n#bins = [0.0, 0.32271604584154595, 0.3608272699835217, 0.39674772490075544, 0.4393389661734349, 1.0, 1.3076777315562291, 1.3494402095945848, 1.3938054550577161, 1.4473895014249551, 2.0, 2.270620927799791, 2.2955836001654832, 2.3227054968414818, 2.3597095636451138, 3.0, 3.3136392743384246, 3.375763965212978, 3.4536894330060437, 3.5555801570988366, 4.0, 4.281205456143316, 4.314964104048392, 4.343805385887936, 4.386255120359146, 5.0, 5.326760523637086, 5.387902653851377, 5.454728391925087, 5.544216756616209, 6.00001]\n# Jan2020\n#bins_5 = [0.0, 0.37507024830767904, 0.45109503452308963, 0.5261132935490932, 0.6030292015582078, 1.0, 1.316664059059267, 1.3596634274198776, 1.408640567552635, 1.4707281447125566, 2.0, 2.357103972473934, 2.422244254348422, 2.5015838259977685, 2.6315258429495674, 3.0, 3.3221427931629908, 3.3627160707391033, 3.407036574707844, 3.457395175000694, 4.0, 4.362169914830597, 4.427176225432989, 4.489460636975875, 4.56817643964688, 5.0001] \n#branchName = DNN_200127_VHLegacyDNN2017V11_Wln_Jan2020OverlapToResolvedDeepCSVwp_Whf_high_Wln\n#checkpoint = DNN/200127_VHLegacyDNN2017V11_Wln_Jan2020OverlapToResolvedDeepCSVwp_Whf_high_Wln\n# Feb2020\n#branchName = DNN_200219_VHLegacyDNN2017V11_Wln_Feb2020flavBhadrons25DeepCSVwpOverlapToResolved_Whf_high_Wln\n#checkpoint = DNN/200219_VHLegacyDNN2017V11_Wln_Feb2020flavBhadrons25DeepCSVwpOverlapToResolved_Whf_high_Wln\n#bins_5 = [0.0, 0.36941476043992194, 0.43682796300765336, 0.5076066484712694, 0.5776203166351507, 1.0, 1.31306556913803, 1.3557043922670982, 1.4071319452024074, 1.4889059105411904, 2.0, 2.317130878054454, 2.366618738821678, 2.42330748560755, 2.5153457858279293, 3.0, 3.3186696105872198, 3.3663580205702313, 3.4117602375222877, 3.4618467877702312, 4.0, 4.358770825792842, 4.425613865482388, 4.487815378797675, 4.566535751062541, 5.0001]\n# loose btag\n#branchName = DNN_200323_VHLegacyDNN2017V11_Wln_Feb2020OverlapToResolvedDeepCSVwpMinLoose_Whf_high_Wln\n#checkpoint = DNN/200323_VHLegacyDNN2017V11_Wln_Feb2020OverlapToResolvedDeepCSVwpMinLoose_Whf_high_Wln\n#bins_5 = [0.0, 0.3730346161336382, 0.43896777497235234, 0.4984553994873903, 0.5639746355588138, 1.0, 1.3063910992510337, 1.343074261528207, 1.3787706249606697, 1.429477385642332, 2.0, 2.338826834497936, 2.4072402665320225, 2.4886361080668054, 2.602858476036959, 3.0, 3.320541355040187, 3.364122676111302, 3.4064544635199585, 3.456062655940625, 4.0, 4.368824326914432, 4.4333895282452, 4.500089716463676, 4.583008287270657, 5.0001] \n# TEST W+c\nbranchName = DNN_200519_VHLegacyDNN2017V11_Wln_Apr2020v5TestSplitWplusC_Whf_high_Wln\ncheckpoint = DNN/200519_VHLegacyDNN2017V11_Wln_Apr2020v5TestSplitWplusC_Whf_high_Wln\n#bins = [0.0, 0.32271604584154595, 0.3608272699835217, 0.39674772490075544, 0.4393389661734349, 1.0, 1.3076777315562291, 1.3494402095945848, 1.3938054550577161, 1.4473895014249551, 2.0, 2.270620927799791, 2.2955836001654832, 2.3227054968414818, 2.3597095636451138, 3.0, 3.3136392743384246, 3.375763965212978, 3.4536894330060437, 3.5555801570988366, 4.0, 4.281205456143316, 4.314964104048392, 4.343805385887936, 4.386255120359146, 5.0, 5.326760523637086, 5.387902653851377, 5.454728391925087, 5.544216756616209, 6.00001] \nbins = [0, 1, 2, 3, 4, 5, 6.0001]\n\n# TEST w6\n#branchName = DNN_200526_VHLegacyDNN2017V11_Wln_Apr2020v5TestSplitW6v2_Whf_high_Wln\n#checkpoint = DNN/200526_VHLegacyDNN2017V11_Wln_Apr2020v5TestSplitW6v2_Whf_high_Wln\n#bins = [0.0, 0.24904242677021826, 0.29772736358548113, 0.3528900397820092, 0.45110243488857166, 1.0, 1.241491585964388, 1.2739848713036022, 1.3028308242834945, 1.3424964152039545, 2.0, 2.237720521555664, 2.269516063218249, 2.299586733708817, 2.3469000898090555, 3.0, 3.211591283457043, 3.23685880520128, 3.266579643828297, 3.317184780324371, 4.0, 4.229929593260469, 4.257595277582664, 4.28669155515659, 4.3286625312201465, 5.0, 5.224340651705716, 5.272807190909573, 5.329784457708409, 5.427415293134217, 6.0, 6.234394588892467, 6.2675800887616235, 6.301335536923396, 6.338545110040462, 7.0, 7.273248634907263, 7.331910544077481, 7.391617499547851, 7.462656510397022, 8.00001]\n\n\n[VV_Whf_med_Wln]\nsignals = [<!Plot_general|VVSIG!>]\nbackgrounds = [<!Plot_general|VVBKG!>]\ndata = <!Plot_general|eData!>\nincludeData = True\ntreeVarSet = WlvBDTVarsWP\ntreeCut = VV_Whf_med_Wln \nclasses = <!VV_Whf_medhigh_Wln|classes!> \n# no btag min cut\n#branchName = DNN_200403_VHLegacyDNN2017V11_Wln_Feb2020flavBhadrons25DeepCSVwpOverlapToResolved_VV_Whf_med_Wln\n#checkpoint = DNN/200403_VHLegacyDNN2017V11_Wln_Feb2020flavBhadrons25DeepCSVwpOverlapToResolved_VV_Whf_med_Wln\n# batg min > loose\nbranchName = DNN_200422_VHLegacyDNN2017V11_Wln_Apr2020v3_DeepCSVwpMinLoose_VV_Whf_med_Wln\ncheckpoint = DNN/200422_VHLegacyDNN2017V11_Wln_Apr2020v3_DeepCSVwpMinLoose_VV_Whf_med_Wln\nbins = [0, 1, 2, 3, 4, 5.0001]\n\n[VV_Whf_high_Wln]\nsignals = [<!Plot_general|VVSIG!>]\nbackgrounds = [<!Plot_general|VVBKG!>]\ndata = <!Plot_general|muData!>\nincludeData = True\ntreeVarSet = WlvBDTVarsWP\ntreeCut = VV_Whf_high_Wln\nclasses = <!VV_Whf_medhigh_Wln|classes!> \n# no btag min cut\n#branchName = DNN_200403_VHLegacyDNN2017V11_Wln_Feb2020flavBhadrons25DeepCSVwpOverlapToResolved_VV_Whf_high_Wln\n#checkpoint = DNN/200403_VHLegacyDNN2017V11_Wln_Feb2020flavBhadrons25DeepCSVwpOverlapToResolved_VV_Whf_high_Wln\n# batg min > loose\nbranchName = DNN_200422_VHLegacyDNN2017V11_Wln_Apr2020v3_DeepCSVwpMinLoose_VV_Whf_high_Wln\ncheckpoint = DNN/200422_VHLegacyDNN2017V11_Wln_Apr2020v3_DeepCSVwpMinLoose_VV_Whf_high_Wln\nbins = [0, 1, 2, 3, 4, 5.0001]\n\n[VV_Whf_medhigh_Wln]\nsignals = [<!Plot_general|VVSIG!>]\nbackgrounds = [<!Plot_general|VVBKG!>]\ndata = <!Plot_general|Data!>\nincludeData = True\ntreeVarSet = WlvBDTVarsWP\ntreeCut = VV_Whf_medhigh_Wln\n#branchName = BDT_191106_VHLegacyDNN2017V11_Wln_VV_Whf_medhigh_Wln_noSA5\n#checkpoint = DNN/191106_VHLegacyDNN2017V11_Wln_VV_Whf_medhigh_Wln_noSA5/model.ckpt\ncheckpoint = DNN/191022_VHLegacyDNN2017V11_Wln_VV_Whf_medhigh_Wln\nbranchName = DNN_191022_VHLegacyDNN2017V11_Wln_VV_Whf_medhigh_Wln\nclasses = [['WLIGHT',[<!Samples|DY_0b!>,<!Samples|WJets_0b!>,<!Samples|ZJets_0b!>,<!Samples|VVLF!>,<!Samples|VVHF!>,<!Samples|ZHsignal!>,<!Samples|ggZHsignal!>,<!Samples|WHsignal!>]],['WB',[<!Samples|DY_1b!>,<!Samples|WJets_1b!>,<!Samples|ZJets_1b!>]],['WBB',[<!Samples|DY_2b!>,<!Samples|WJets_2b!>,<!Samples|ZJets_2b!>]],['ST',[<!Samples|ST!>]],['TT',[<!Samples|TT!>]]]\nbins = [0, 1, 2, 3, 4, 5.0001]\nbins_2 = [0.0, 0.40558735361457127, 1.0, 1.336627645603964, 2.0, 2.401251605158244, 3.0, 3.316897924970788, 4.0, 4.421120092389745, 5.0001]\n\n[Mjj_SR_medhigh_Wen]\nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ntreeVarSet = WlvBDTVars\ntreeCut = SR_medhigh_Wen \nbranchName = BDT_DNN2017V11_Wen_Mjj_v1\ncheckpoint = DNN/190826_DNN2017V11_Wen_Mjj_v1/model.ckpt\nsignalIndex = 0\n\n[Mjj_SR_medhigh_Wmn]\nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ntreeVarSet = WlvBDTVars\ntreeCut = SR_medhigh_Wmn\nbranchName = BDT_DNN2017V11_Wmn_Mjj_v1\ncheckpoint = DNN/190826_DNN2017V11_Wmn_Mjj_v1/model.ckpt\nsignalIndex = 0\n\n\n# MULTI classifier regions\n\n[Multi_medhigh_Wln]\nMVAtype = <!MVAGeneral|type!>\nMVAsettings = DNN \nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ndata = <!Plot_general|Data!>\ntreeVarSet = WlvBDTVars\ntreeCut = Multi_medhigh_Wln\nbranchName = BDT_DNN2017V11_Wln_Multi_v1\ncheckpoint = DNN/190726_DNN2017V11_Wln_Multi_v1/model.ckpt \nclasses = [['WLIGHT',[<!Samples|WJets_0b!>,<!Samples|ZJets_0b!>]],['WB',[<!Samples|WJets_1b!>,<!Samples|ZJets_1b!>]],['WBB',[<!Samples|WJets_2b!>,<!Samples|ZJets_2b!>]],['ST',[<!Samples|ST!>]],['TT',[<!Samples|TT!>]],['VVLF',[<!Samples|VVLF!>]],['VVHF',[<!Samples|VVHF!>]],['SIG_ALL',[<!Samples|ZHsignal!>,<!Samples|ggZHsignal!>,<!Samples|WHsignal!>]]]\nbins = [0.,0.319279,0.418765,0.503729,0.6012,1.,1.23342,1.27514,1.31764,1.37503,2.,2.2827,2.34378,2.4082,2.50068,3.,3.23922,3.2807,3.32004,3.37421,4.,4.34787,4.43096,4.5111,4.5964,5.,5.2521,5.32839,5.38707,5.44609,6.,6.23619,6.28173,6.33228,6.3983,7.,7.2208,7.2672,7.3211,7.3835,7.4656,7.5719,7.6971,7.7988,7.8609,7.9005,7.9254,7.9447,7.9602,7.9718,8.0001] \n\n[Multi_medhigh_Wen]\nMVAtype = <!MVAGeneral|type!>\nMVAsettings = DNN \nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ndata = <!Plot_general|eData!>\ntreeVarSet = WlvBDTVars\ntreeCut = Multi_medhigh_Wen\nbranchName = BDT_DNN2017V11_Wen_Multi_v2\ncheckpoint = DNN/190816_DNN2017V11_Wen_Multi_v2/model.ckpt\nclasses = [['WLIGHT',[<!Plot_general|WJets_0b!>,<!Plot_general|ZJets_0b!>]],['WB',[<!Plot_general|WJets_1b!>,<!Plot_general|ZJets_1b!>]],['WBB',[<!Plot_general|WJets_2b!>,<!Plot_general|ZJets_2b!>]],['ST',[<!Plot_general|ST!>]],['TT',[<!Plot_general|TT!>]],['VVLF',[<!Plot_general|VVLF!>]],['VVHF',[<!Plot_general|VVHF!>]],['SIG_ALL',[<!Plot_general|ZHsignal!>,<!Plot_general|ggZHsignal!>,<!Plot_general|WHsignal!>]]]\nbins = [0.,0.36099,0.447858,0.533651,0.648704,1.,1.26313,1.31244,1.36667,1.43999,2.,2.31879,2.39743,2.48598,2.61724,3.,3.29151,3.36728,3.44101,3.52786,4.,4.34992,4.46927,4.59096,4.71555,5.,5.32643,5.4046,5.46852,5.55771,6.,6.29494,6.37255,6.46491,6.59498,7.,7.24495,7.29473,7.36944,7.45179,7.54897,7.64058,7.72638,7.79678,7.84927,7.88358,7.90339,7.92078,7.93494,7.9503,8.0001]\n\n[Multi_medhigh_Wmn]\nMVAtype = <!MVAGeneral|type!>\nMVAsettings = DNN \nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ndata = <!Plot_general|muData!>\ntreeVarSet = WlvBDTVars\ntreeCut = Multi_medhigh_Wmn\nbranchName = BDT_DNN2017V11_Wmn_Multi_v2\ncheckpoint = DNN/190816_DNN2017V11_Wmn_Multi_v2/model.ckpt\nclasses = [['WLIGHT',[<!Plot_general|WJets_0b!>,<!Plot_general|ZJets_0b!>]],['WB',[<!Plot_general|WJets_1b!>,<!Plot_general|ZJets_1b!>]],['WBB',[<!Plot_general|WJets_2b!>,<!Plot_general|ZJets_2b!>]],['ST',[<!Plot_general|ST!>]],['TT',[<!Plot_general|TT!>]],['VVLF',[<!Plot_general|VVLF!>]],['VVHF',[<!Plot_general|VVHF!>]],['SIG_ALL',[<!Plot_general|ZHsignal!>,<!Plot_general|ggZHsignal!>,<!Plot_general|WHsignal!>]]]\nbins = [0.,0.361377,0.454427,0.54096,0.635657,1.,1.26538,1.31787,1.37387,1.44947,2.,2.32036,2.39655,2.48576,2.61804,3.,3.28677,3.36035,3.42978,3.50981,4.,4.35045,4.46739,4.581,4.69097,5.,5.32718,5.40972,5.48093,5.58241,6.,6.2991,6.37875,6.47045,6.59218,7.,7.24913,7.2988,7.37119,7.45513,7.55319,7.64659,7.73534,7.80996,7.85932,7.89164,7.91486,7.93109,7.94568,7.9604,8.0001]\n\n#(Jet_btagDeepB[hJidx[0]]>0.1522)+(Jet_btagDeepB[hJidx[0]]>0.4941)+(Jet_btagDeepB[hJidx[0]]>0.8001) (Jet_btagDeepB[hJidx[1]]>0.1522)+(Jet_btagDeepB[hJidx[1]]>0.4941)+(Jet_btagDeepB[hJidx[1]]>0.8001)\n\n[WlvBDTVarsWP]\nNominal = H_mass H_pt V_mt V_pt V_pt/H_pt abs(TVector2::Phi_mpi_pi(V_phi-H_phi)) (Jet_btagDeepB[hJidx[0]]>0.1522)+(Jet_btagDeepB[hJidx[0]]>0.4941)+(Jet_btagDeepB[hJidx[0]]>0.8001) (Jet_btagDeepB[hJidx[1]]>0.1522)+(Jet_btagDeepB[hJidx[1]]>0.4941)+(Jet_btagDeepB[hJidx[1]]>0.8001) max(hJets_0_pt_FSRrecovered,hJets_1_pt_FSRrecovered) min(hJets_0_pt_FSRrecovered,hJets_1_pt_FSRrecovered) hJets_FSRrecovered_dEta MET_Pt dPhiLepMet top_mass2_05 SA5 Sum$(Jet_Pt>30&&abs(Jet_eta)<2.5&&(Jet_puId>6||Jet_Pt>50.0)&&Jet_jetId>4&&Jet_lepFilter&&Iteration$!=hJidx[0]&&Iteration$!=hJidx[1])\n\n[WlvBDTVars]\nNominal = H_mass H_pt V_mt V_pt V_pt/H_pt abs(TVector2::Phi_mpi_pi(V_phi-H_phi)) Jet_btagDeepB[hJidx[0]] Jet_btagDeepB[hJidx[1]] max(hJets_0_pt_FSRrecovered,hJets_1_pt_FSRrecovered) min(hJets_0_pt_FSRrecovered,hJets_1_pt_FSRrecovered) hJets_FSRrecovered_dEta MET_Pt dPhiLepMet top_mass2_05 SA5 Sum$(Jet_Pt>30&&abs(Jet_eta)<2.5&&(Jet_puId>6||Jet_Pt>50.0)&&Jet_jetId>4&&Jet_lepFilter&&Iteration$!=hJidx[0]&&Iteration$!=hJidx[1])\n\n#BDT_Wlv_BOOSTFinal_wdB.treeVarSet=WlvBDTVarsOverlap\n[WlvBDTVarsOverlap]\nNominal = H_mass H_pt V_mt V_pt V_pt/H_pt abs(TVector2::Phi_mpi_pi(V_phi-H_phi)) (Jet_btagDeepB[hJidx[0]]>0.1522)+(Jet_btagDeepB[hJidx[0]]>0.4941)+(Jet_btagDeepB[hJidx[0]]>0.8001) (Jet_btagDeepB[hJidx[1]]>0.1522)+(Jet_btagDeepB[hJidx[1]]>0.4941)+(Jet_btagDeepB[hJidx[1]]>0.8001) max(hJets_0_pt_FSRrecovered,hJets_1_pt_FSRrecovered) min(hJets_0_pt_FSRrecovered,hJets_1_pt_FSRrecovered) hJets_FSRrecovered_dEta MET_Pt dPhiLepMet top_mass2_05 SA5 Sum$(Jet_Pt>30&&abs(Jet_eta)<2.5&&(Jet_puId>6||Jet_Pt>50.0)&&Jet_jetId>4&&Jet_lepFilter&&Iteration$!=hJidx[0]&&Iteration$!=hJidx[1]) FatJet_Msoftdrop[Hbb_fjidx] FatJet_Pt[Hbb_fjidx] FatJet_Pt[Hbb_fjidx]/V_pt (1/(1+(FatJet_deepTagMD_TvsQCD[Hbb_fjidx]/FatJet_deepTagMD_HbbvsQCD[Hbb_fjidx])*(1-FatJet_deepTagMD_HbbvsQCD[Hbb_fjidx])/(1-FatJet_deepTagMD_TvsQCD[Hbb_fjidx])))>0.97\n\n;!! ------------------\n;!! Boosted MVA \n;!! ------------------\n[WlvBDTBOOSTVarsFinal_wdB]\nNominal = FatJet_Msoftdrop[Hbb_fjidx] FatJet_Pt[Hbb_fjidx] MET_Pt V_mt SA5 FatJet_Pt[Hbb_fjidx]/V_pt (FatJet_deepTagMD_bbvsLight[Hbb_fjidx])>0.97 abs(TVector2::Phi_mpi_pi(V_phi-FatJet_phi[Hbb_fjidx])) (-99+(hJidx[0]>-1)*(99+H_mass)) (-99+Alt$((hJidx[0]>-1)*(99+H_pt),0)) (-99+Alt$((hJidx[0]>-1)*(99+V_pt/H_pt),0)) (-99+Alt$((hJidx[0]>-1)*(99+abs(TVector2::Phi_mpi_pi(V_phi-H_phi))),0)) (-99+Alt$((hJidx[0]>-1)*(99+max(hJets_0_pt_FSRrecovered,hJets_1_pt_FSRrecovered)),0)) (-99+Alt$((hJidx[0]>-1)*(99+min(hJets_0_pt_FSRrecovered,hJets_1_pt_FSRrecovered)),0)) (-99+Alt$((hJidx[0]>-1)*(99+hJets_FSRrecovered_dEta),0)) dPhiLepMet top_mass2_05 (-99+Alt$((hJidx[0]>-1)*(99+Sum$(Jet_Pt>30&&abs(Jet_eta)<2.5&&(Jet_puId>6||Jet_Pt>50.0)&&Jet_jetId>4&&Jet_lepFilter&&Iteration$!=hJidx[0]&&Iteration$!=hJidx[1])),0))\n\n\n\n;;;;;;;;;;;;;;\n;BDT Boost\n;;;;;;;;;;;;;;\n[BDT_Wlv_BOOSTFinal_wdB]\nxml = weights/MVA_BDT_Wlv_BOOSTFinal_wdB_200615_withResolvedFeatures.weights.xml\nMVAtype = <!MVAGeneral|type!>\nMVAsettings = NTrees=100:nCuts=20\nsignals = [<!Plot_general|allSIG!>]\nbackgrounds = [<!Plot_general|allBKG!>]\ntreeVarSet = WlvBDTBOOSTVarsFinal_wdB\ntreeCut = Signal_BOOSTv3\nsystematics = <!systematics|systematics_BOOST!>\nbins = [-1.00000, -0.41120, -0.32867, -0.26360, -0.18133, -0.09013, -0.00400, 0.08027, 0.15373, 0.22680, 0.28893, 0.35200, 0.40960, 0.46187, 0.52733, 1.00001] \n\n[BDT_VZ_Wlv_BOOSTFinal_wdB]\nMVAtype = <!MVAGeneral|type!>\nMVAsettings = NTrees=100:nCuts=20 \nsignals = [<!Plot_general|VVSIG!>]\nbackgrounds = [<!Plot_general|VVBKG!>]\ntreeVarSet = WlvBDTBOOSTVarsFinal_wdB\ntreeCut = VZ_Signal_BOOSTv3\nsystematics = <!systematics|systematics_BOOST!>\n\n" }, { "alpha_fraction": 0.6698911786079407, "alphanum_fraction": 0.8440145254135132, "avg_line_length": 56.41666793823242, "blob_id": "d78ea0a086f4ebed661a29fc7e44bb3cbe161b14", "content_id": "d6112b905c3b77e6a0f674ec7e7e092c150a359a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 4135, "license_type": "no_license", "max_line_length": 89, "num_lines": 72, "path": "/python/Wlv2017config/hadd.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "# V11\n[Hadd]\nZJetsToNuNu_HT-800To1200_13TeV-madgraph: 471\nQCD_HT200to300_TuneCP5_13TeV-madgraph-pythia8: 10182\nWplusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8: 2\nTTTo2L2Nu_TuneCP5_PSweights_13TeV-powheg-pythia8: 1\nTTToSemiLeptonic_TuneCP5_PSweights_13TeV-powheg-pythia8: 1\nWminusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8: 2\nDYJetsToLL_M-4to50_HT-200to400_TuneCP5_13TeV-madgraphMLM-pythia8: 21\nWJetsToLNu_BGenFilter_Wpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 2\nSingleElectron: 5\nDYJetsToLL_M-4to50_HT-600toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 6\nggZH_HToBB_ZToLL_M125_13TeV_powheg_pythia8: 3\nWZTo1L1Nu2Q_13TeV_amcatnloFXFX_madspin_pythia8: 1\nWJetsToLNu_HT-1200To2500_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYJetsToLL_M-4to50_HT-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 38\nDYJetsToLL_M-50_HT-1200to2500_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZJetsToNuNu_HT-400To600_13TeV-madgraph: 1010\nZJetsToNuNu_BGenFilter_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 64000\nWBJetsToLNu_Wpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 3\nDYJetsToLL_M-50_HT-2500toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 2\nDYBJetsToLL_M-50_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 10\nDYJetsToLL_M-4to50_HT-400to600_TuneCP5_13TeV-madgraphMLM-pythia8: 5\nDYJetsToLL_M-50_TuneCP5_13TeV-madgraphMLM-pythia8: 22\nZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8: 4953\nZBJetsToNuNu_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 12870\nWJetsToLNu_HT-200To400_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZBJetsToNuNu_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 9514\nTTToHadronic_TuneCP5_PSweights_13TeV-powheg-pythia8: 136\nST_t-channel_antitop_4f_InclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8: 1\nWBJetsToLNu_Wpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 2\nZJetsToNuNu_HT-2500ToInf_13TeV-madgraph: 16000\nWJetsToLNu_BGenFilter_Wpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 2\nWZ_TuneCP5_13TeV-pythia8: 5\nQCD_HT2000toInf_TuneCP5_13TeV-madgraph-pythia8: 191\nWW_TuneCP5_13TeV-pythia8: 4\nDYJetsToLL_M-50_HT-800to1200_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZZ_TuneCP5_13TeV-pythia8: 18\nQCD_HT500to700_TuneCP5_13TeV-madgraph-pythia8: 493\nDYJetsToLL_M-50_HT-200to400_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nWJetsToLNu_HT-400To600_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYJetsToLL_M-50_HT-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 4\nDYBJetsToLL_M-50_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 6\nZJetsToNuNu_HT-100To200_13TeV-madgraph: 16000\nQCD_HT1000to1500_TuneCP5_13TeV-madgraph-pythia8: 1067\nZJetsToNuNu_HT-1200To2500_13TeV-madgraph: 2182\nQCD_HT300to500_TuneCP5_13TeV-madgraph-pythia8: 1288\nDYJetsToLL_BGenFilter_Zpt-100to200_M-50_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 10\nWJetsToLNu_HT-800To1200_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nST_tW_antitop_5f_inclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8: 1\nQCD_HT700to1000_TuneCP5_13TeV-madgraph-pythia8: 967\nZH_HToBB_ZToLL_M125_13TeV_powheg_pythia8: 6\nZJetsToNuNu_HT-200To400_13TeV-madgraph: 3500\nQCD_HT1500to2000_TuneCP5_13TeV-madgraph-pythia8: 132\nZJetsToNuNu_BGenFilter_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 54000\nDYJetsToLL_M-50_HT-600to800_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYJetsToLL_M-50_HT-400to600_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nST_tW_top_5f_inclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8: 1\nWWTo1L1Nu2Q_13TeV_amcatnloFXFX_madspin_pythia8: 2\nST_s-channel_4f_leptonDecays_TuneCP5_PSweights_13TeV-amcatnlo-pythia8: 1\nWJetsToLNu_HT-2500ToInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYJetsToLL_BGenFilter_Zpt-200toInf_M-50_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 11\nWJetsToLNu_HT-600To800_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZJetsToNuNu_HT-600To800_13TeV-madgraph: 861\nWJetsToLNu_HT-100To200_TuneCP5_13TeV-madgraphMLM-pythia8: 4\nSingleMuon: 5\nQCD_HT100to200_TuneCP5_13TeV-madgraph-pythia8: 38400\nggZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8: 1600\nZZTo4L_13TeV_powheg_pythia8: 23\nST_t-channel_top_4f_InclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8: 2\nWJetsToLNu_TuneCP5_13TeV-madgraphMLM-pythia8: 27\nZZTo2L2Q_13TeV_amcatnloFXFX_madspin_pythia8: 2\n\n" }, { "alpha_fraction": 0.561876654624939, "alphanum_fraction": 0.7051181197166443, "avg_line_length": 39.210201263427734, "blob_id": "175ee926b4547addfbed194c063726d855f38e3d", "content_id": "d13132c4e1eb666353f844c1d006d82106f886e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 45720, "license_type": "no_license", "max_line_length": 356, "num_lines": 1137, "path": "/python/VHbb2016commonconfig/samples_mc.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "# common samples config for 2016 analysis\n\n[General]\nVVpythia_sampleGroup = ['VVLF', 'VVLF', 'VVHF']\nWJetsGroup = ['WJets_0b', 'WJets_1b', 'WJets_2b']\nZJetsGroup = ['ZJets_0b', 'ZJets_1b', 'ZJets_2b']\nZjets_sampleGroup_v3 = ['ZJets_0b', 'ZJets_1b', 'ZJets_2b']\nallDYweight = 1.0\n\nJetFlavor25 = [\n 'Sum$(GenJet_pt>25 && abs(GenJet_eta)<2.4 && GenJet_hadronFlavour==5)<1', # udscg jets\n 'Sum$(GenJet_pt>25 && abs(GenJet_eta)<2.4 && GenJet_hadronFlavour==5)==1', # single b-jet\n 'Sum$(GenJet_pt>25 && abs(GenJet_eta)<2.4 && GenJet_hadronFlavour==5)>=2', # double b-jets\n ]\n\nJetFlavor20 = [\n 'Sum$(GenJet_pt>20 && abs(GenJet_eta)<2.4 && GenJet_hadronFlavour==5)<1', # udscg jets\n 'Sum$(GenJet_pt>20 && abs(GenJet_eta)<2.4 && GenJet_hadronFlavour==5)==1', # single b-jet\n 'Sum$(GenJet_pt>20 && abs(GenJet_eta)<2.4 && GenJet_hadronFlavour==5)>=2', # double b-jets\n ]\n\nJetFlavor = <!General|JetFlavor25!>\n\nDibosonFlavorXbb = [\n '(Sum$(GenPart_genPartIdxMother>=0&&abs(GenPart_pdgId)==5&&(GenPart_pdgId[GenPart_genPartIdxMother]==23||abs(GenPart_pdgId[GenPart_genPartIdxMother])==24)&&GenPart_status[GenPart_genPartIdxMother]==62))<1',\n '(Sum$(GenPart_genPartIdxMother>=0&&abs(GenPart_pdgId)==5&&(GenPart_pdgId[GenPart_genPartIdxMother]==23||abs(GenPart_pdgId[GenPart_genPartIdxMother])==24)&&GenPart_status[GenPart_genPartIdxMother]==62))==1',\n '(Sum$(GenPart_genPartIdxMother>=0&&abs(GenPart_pdgId)==5&&(GenPart_pdgId[GenPart_genPartIdxMother]==23||abs(GenPart_pdgId[GenPart_genPartIdxMother])==24)&&GenPart_status[GenPart_genPartIdxMother]==62))>=2',\n ]\n\nDibosonFlavorAT = <!General|JetFlavor20!>\nDibosonFlavor = <!General|DibosonFlavorAT!>\n\n# test AT definition: --set='General.DibosonFlavor=<!General|DibosonFlavorAT!>'\n\npreselectionCut = 1\n\n[Stitching]\n\n# OFF: only use inclusive + HT binned samples\n# EXCL: use b-enriched exclusively in their phase-space (throw away overlap)\n\nMethodWJ = OFF\n#MethodWJ = EXCL\n\nMethodZJ = OFF\n#MethodZJ = EXCL\n\nMethodDY = OFF\n#MethodDY = EXCL\n\n# differential reweighting of b-enriched/filtered samples to inclusive+ht binned\n#ReweightLHEVpt = ON\n# normlization reweighting of b-enriched/filtered samples to inclusive+ht binned\nReweightLHEVpt = OFF\n\nWJincl_OFF = (LHE_HT<100)\nWJ100_OFF = (LHE_HT>=100&&LHE_HT<200) \nWJ200_OFF = (LHE_HT>=200&&LHE_HT<400)\nWJ400_OFF = (LHE_HT>=400&&LHE_HT<600)\nWJ600_OFF = (LHE_HT>=600&&LHE_HT<800)\nWJ800_OFF = (LHE_HT>=800&&LHE_HT<1200)\nWJ1200_OFF = (LHE_HT>=1200&&LHE_HT<2500)\nWJ2500_OFF = (LHE_HT>=2500)\nWJB100_OFF = 0.0\nWJB200_OFF = 0.0\nWJGBF100_OFF = 0.0\nWJGBF200_OFF = 0.0\n\nWJincl_EXCL = (((LHE_Nb==0&&nGenStatus2bHad==0)||LHE_Vpt<100)&&LHE_HT<100)\nWJ100_EXCL = ((LHE_Nb==0&&nGenStatus2bHad==0)||LHE_Vpt<100)\nWJ200_EXCL = ((LHE_Nb==0&&nGenStatus2bHad==0)||LHE_Vpt<100)\nWJ400_EXCL = ((LHE_Nb==0&&nGenStatus2bHad==0)||LHE_Vpt<100)\nWJ600_EXCL = ((LHE_Nb==0&&nGenStatus2bHad==0)||LHE_Vpt<100)\nWJ800_EXCL = ((LHE_Nb==0&&nGenStatus2bHad==0)||LHE_Vpt<100)\nWJ1200_EXCL = ((LHE_Nb==0&&nGenStatus2bHad==0)||LHE_Vpt<100)\nWJ2500_EXCL = ((LHE_Nb==0&&nGenStatus2bHad==0)||LHE_Vpt<100)\nWJB100_EXCL = (LHE_Nb>0&&LHE_Vpt>=100&&LHE_Vpt<200)\nWJB200_EXCL = (LHE_Nb>0&&LHE_Vpt>=200)\nWJGBF100_EXCL = (LHE_Nb==0&&nGenStatus2bHad>0&&LHE_Vpt>=100&&LHE_Vpt<200)\nWJGBF200_EXCL = (LHE_Nb==0&&nGenStatus2bHad>0&&LHE_Vpt>=200)\n\nWJincl = <!Stitching|WJincl_<!Stitching|MethodWJ!>!>\nWJ100 = <!Stitching|WJ100_<!Stitching|MethodWJ!>!>\nWJ200 = <!Stitching|WJ200_<!Stitching|MethodWJ!>!>\nWJ400 = <!Stitching|WJ400_<!Stitching|MethodWJ!>!>\nWJ600 = <!Stitching|WJ600_<!Stitching|MethodWJ!>!>\nWJ800 = <!Stitching|WJ800_<!Stitching|MethodWJ!>!>\nWJ1200 = <!Stitching|WJ1200_<!Stitching|MethodWJ!>!>\nWJ2500 = <!Stitching|WJ2500_<!Stitching|MethodWJ!>!>\nWJB100 = <!Stitching|WJB100_<!Stitching|MethodWJ!>!>\nWJB200 = <!Stitching|WJB200_<!Stitching|MethodWJ!>!>\nWJGBF100 = <!Stitching|WJGBF100_<!Stitching|MethodWJ!>!>\nWJGBF200 = <!Stitching|WJGBF200_<!Stitching|MethodWJ!>!>\n\n# don't use b-enriched samples\nDYincl_OFF = (LHE_HT<100)\nDY_HT100_OFF = (LHE_HT>=100&&LHE_HT<200)\nDY_HT200_OFF = (LHE_HT>=200&&LHE_HT<400)\nDY_HT400_OFF = (LHE_HT>=400&&LHE_HT<600)\nDY_HT600_OFF = (LHE_HT>=600&&LHE_HT<800)\nDY_HT800_OFF = (LHE_HT>=800&&LHE_HT<1200)\nDY_HT1200_OFF = (LHE_HT>=1200&&LHE_HT<2500)\nDY_HT2500_OFF = (LHE_HT>=2500)\nDY_B100_OFF = 0.0\nDY_B200_OFF = 0.0\nDY_F100_OFF = 0.0\nDY_F200_OFF = 0.0\n\n# don't use HT bins and b-enriched samples\nDYincl_NOHT = 1.0 \nDY_HT100_NOHT = 0.0 \nDY_HT200_NOHT = 0.0 \nDY_HT400_NOHT = 0.0 \nDY_HT600_NOHT = 0.0\nDY_HT800_NOHT = 0.0 \nDY_HT1200_NOHT = 0.0 \nDY_HT2500_NOHT = 0.0 \nDY_B100_NOHT = 0.0\nDY_B200_NOHT = 0.0\nDY_F100_NOHT = 0.0\nDY_F200_NOHT = 0.0\n\n# use b-enriched and GenFilter, exclusively\nDYincl_EXCL = (LHE_Vpt<100 || (nGenStatus2bHad==0 && LHE_Nb==0))*(<!Stitching|DYincl_OFF!>) \nDY_HT100_EXCL = (LHE_Vpt<100 || (nGenStatus2bHad==0 && LHE_Nb==0))*(<!Stitching|DY_HT100_OFF!>)\nDY_HT200_EXCL = (LHE_Vpt<100 || (nGenStatus2bHad==0 && LHE_Nb==0))*(<!Stitching|DY_HT200_OFF!>) \nDY_HT400_EXCL = (LHE_Vpt<100 || (nGenStatus2bHad==0 && LHE_Nb==0))*(<!Stitching|DY_HT400_OFF!>)\nDY_HT600_EXCL = (LHE_Vpt<100 || (nGenStatus2bHad==0 && LHE_Nb==0))*(<!Stitching|DY_HT600_OFF!>)\nDY_HT800_EXCL = (LHE_Vpt<100 || (nGenStatus2bHad==0 && LHE_Nb==0))*(<!Stitching|DY_HT800_OFF!>)\nDY_HT1200_EXCL = (LHE_Vpt<100 || (nGenStatus2bHad==0 && LHE_Nb==0))*(<!Stitching|DY_HT1200_OFF!>)\nDY_HT2500_EXCL = (LHE_Vpt<100 || (nGenStatus2bHad==0 && LHE_Nb==0))*(<!Stitching|DY_HT2500_OFF!>)\nDY_B100_EXCL = (LHE_Nb>0&&LHE_Vpt>=100)\nDY_B200_EXCL = (LHE_Nb>0&&LHE_Vpt>=200)\nDY_F100_EXCL = (LHE_Vpt>=100 && LHE_Nb==0 && nGenStatus2bHad > 0)\nDY_F200_EXCL = (LHE_Vpt>=200 && LHE_Nb==0 && nGenStatus2bHad > 0)\n\nDYincl = <!Stitching|DYincl_<!Stitching|MethodDY!>!>\nDY_HT100 = <!Stitching|DY_HT100_<!Stitching|MethodDY!>!>\nDY_HT200 = <!Stitching|DY_HT200_<!Stitching|MethodDY!>!>\nDY_HT400 = <!Stitching|DY_HT400_<!Stitching|MethodDY!>!>\nDY_HT600 = <!Stitching|DY_HT600_<!Stitching|MethodDY!>!>\nDY_HT800 = <!Stitching|DY_HT800_<!Stitching|MethodDY!>!>\nDY_HT1200 = <!Stitching|DY_HT1200_<!Stitching|MethodDY!>!>\nDY_HT2500 = <!Stitching|DY_HT2500_<!Stitching|MethodDY!>!>\nDY_B100 = <!Stitching|DY_B100_<!Stitching|MethodDY!>!>\nDY_B200 = <!Stitching|DY_B200_<!Stitching|MethodDY!>!>\nDY_F100 = <!Stitching|DY_F100_<!Stitching|MethodDY!>!>\nDY_F200 = <!Stitching|DY_F200_<!Stitching|MethodDY!>!>\n\n\nZJ100 = <!Stitching|ZJ100_<!Stitching|MethodZJ!>!>\nZJ200 = <!Stitching|ZJ200_<!Stitching|MethodZJ!>!> \nZJ400 = <!Stitching|ZJ400_<!Stitching|MethodZJ!>!>\nZJ600 = <!Stitching|ZJ600_<!Stitching|MethodZJ!>!>\nZJ800 = <!Stitching|ZJ800_<!Stitching|MethodZJ!>!>\nZJ1200 = <!Stitching|ZJ1200_<!Stitching|MethodZJ!>!>\nZJ2500 = <!Stitching|ZJ2500_<!Stitching|MethodZJ!>!>\nZJB100 = <!Stitching|ZJB100_<!Stitching|MethodZJ!>!>\nZJB200 = <!Stitching|ZJB200_<!Stitching|MethodZJ!>!>\nZJGBF100 = <!Stitching|ZJGBF100_<!Stitching|MethodZJ!>!>\nZJGBF200 = <!Stitching|ZJGBF200_<!Stitching|MethodZJ!>!>\n\nZJ100_OFF = 1.0 \nZJ200_OFF = 1.0\nZJ400_OFF = 1.0\nZJ600_OFF = 1.0\nZJ800_OFF = 1.0\nZJ1200_OFF = 1.0\nZJ2500_OFF = 1.0\nZJB100_OFF = 0.0\nZJB200_OFF = 0.0\nZJGBF100_OFF = 0.0\nZJGBF200_OFF = 0.0\n\nZJ100_EXCL = ((LHE_Nb==0&&nGenStatus2bHad==0)||LHE_Vpt<100)\nZJ200_EXCL = ((LHE_Nb==0&&nGenStatus2bHad==0)||LHE_Vpt<100)\nZJ400_EXCL = ((LHE_Nb==0&&nGenStatus2bHad==0)||LHE_Vpt<100)\nZJ600_EXCL = ((LHE_Nb==0&&nGenStatus2bHad==0)||LHE_Vpt<100)\nZJ800_EXCL = ((LHE_Nb==0&&nGenStatus2bHad==0)||LHE_Vpt<100)\nZJ1200_EXCL = ((LHE_Nb==0&&nGenStatus2bHad==0)||LHE_Vpt<100)\nZJ2500_EXCL = ((LHE_Nb==0&&nGenStatus2bHad==0)||LHE_Vpt<100)\nZJB100_EXCL = (LHE_Nb>0&&LHE_Vpt>=100&&LHE_Vpt<200)\nZJB200_EXCL = (LHE_Nb>0&&LHE_Vpt>=200)\nZJGBF100_EXCL = (LHE_Nb==0&&nGenStatus2bHad>0&&LHE_Vpt>=100&&LHE_Vpt<200)\nZJGBF200_EXCL = (LHE_Nb==0&&nGenStatus2bHad>0&&LHE_Vpt>=200)\n\n\n;----------------------------Background----------------------------\n\n#DIBOSON\n\n[ZZ_TuneCUETP8M1_13TeV-pythia8]\nsampleIndex = [3500,3501,3502]\nsampleName = ZZ_pythia\nsampleType = BKG\nsubsamples = True\nsubnames = ['ZZ_0b', 'ZZ_1b', 'ZZ_2b']\nsubcuts = <!General|DibosonFlavor!>\nsampleGroup = <!General|VVpythia_sampleGroup!>\nxSec = [14.6]*3\nSF = [1,1,1] \n\n[ZZTo2L2Q_13TeV_amcatnloFXFX_madspin_pythia8]\nsampleIndex = [34600,34601,34602]\nsampleName = ZZ_amc\nsampleType = BKG\nsubsamples = True\nsubnames = ['ZZTo2L2Qnlo_0b', 'ZZTo2L2Qnlo_1b', 'ZZTo2L2Qnlo_2b']\nsubcuts = <!General|DibosonFlavor!>\nsampleGroup = <!General|VVpythia_sampleGroup!>\n# NLO calculation\nxSec = [3.688]*3\n# SMP16-001: 14.6 * 0.1396 (BR) = 2.03816\n#xSec = [2.038]*3\nSF = [1,1,1]\n\n#[ZZTo4L_13TeV_powheg_pythia8]\n#sampleIndex = [34500,34501,34502]\n#sampleName = ZZ4l\n#sampleType = BKG\n#subsamples = True\n#subnames = ['ZZ4l_0b', 'ZZ4l_1b', 'ZZ4l_2b']\n#subcuts = <!General|DibosonFlavor!>\n#sampleGroup = <!General|VVpythia_sampleGroup!>\n#xSec = [1.256]*3\n#SF = [1,1,1]\n\n\n[WZ_TuneCUETP8M1_13TeV-pythia8]\nsampleIndex = [3000,3001,3002]\nsampleName = WZ_pythia\nsampleType = BKG\nsubsamples = False\nsubsamples = True\nsubcuts = <!General|DibosonFlavor!>\nsubnames = ['WZ_0b', 'WZ_1b', 'WZ_2b']\nsampleGroup = <!General|VVpythia_sampleGroup!>\nxSec = [48.1]*3\nSF = [1,1,1] \n\n\n[WZTo1L1Nu2Q_13TeV_amcatnloFXFX_madspin_pythia8]\nsampleIndex = [3200,3201,3202]\nsampleName = WZ_amc\nsampleType = BKG\nsubsamples = True\nsubnames = ['WZTo1L1Nu2Qnlo_0b', 'WZTo1L1Nu2Qnlo_1b', 'WZTo1L1Nu2Qnlo_2b']\nsubcuts =<!General|DibosonFlavor!>\nsampleGroup = <!General|VVpythia_sampleGroup!>\n#xS from SMP18-002\nxSec = [10.87]*3 \nSF = [1,1,1] \n\n\n\n[WW_TuneCUETP8M1_13TeV-pythia8]\nsampleIndex = [3300,3301,3302]\nsampleName = WW_pythia\nsampleType = BKG\nsubsamples = False\nsubsamples = True\nsubnames = ['WW_0b', 'WW_1b', 'WW_2b']\nsubcuts = <!General|DibosonFlavor!>\nsampleGroup = <!General|VVpythia_sampleGroup!>\nxSec = [115.3]*3\nSF = [1,1,1] \n\n\n[WWTo1L1Nu2Q_13TeV_amcatnloFXFX_madspin_pythia8]\nsampleIndex = [3400,3401,3402]\nsampleName = WW_amc\nsampleType = BKG\nsubsamples = True\nsubnames = ['WWTo1L1Nu2Qnlo_0b', 'WWTo1L1Nu2Qnlo_1b', 'WWTo1L1Nu2Qnlo_2b']\nsubcuts = <!General|DibosonFlavor!>\nsampleGroup = <!General|VVpythia_sampleGroup!>\nxSec = [50.85883]*3\nSF = [1,1,1] \n\n#-- W+Jets Samples --#\n\n[WJetsToLNu_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [4000,4001,4002]\nsampleName = WJetsHT0\nsampleType = BKG\nsubsamples = True\nsubnames = ['WJetsHT0_0b', 'WJetsHT0_1b', 'WJetsHT0_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|WJetsGroup!>\nxSec = [61526.7 * 1.21] * 3\nSF = <!General|SF_WJets!>\nspecialweight = <!Stitching|WJincl!>\n\n[WJetsToLNu_HT-100To200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [4100,4101,4102]\nsampleName = WJetsHT100\nsampleType = BKG\nsubsamples = True\nsubnames = ['WJetsHT100_0b', 'WJetsHT100_1b', 'WJetsHT100_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|WJetsGroup!>\nxSec = [1345 * 1.21] * 3\nSF = <!General|SF_WJets!>\nspecialweight = <!Stitching|WJ100!>\ndcChunkSize = 20\n\n[WJetsToLNu_HT-200To400_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [4200,4201,4202]\nsampleName = WJetsHT200\nsampleType = BKG\nsubsamples = True\nsubnames = ['WJetsHT200_0b', 'WJetsHT200_1b', 'WJetsHT200_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|WJetsGroup!>\nxSec = [359.7 * 1.21] * 3\nSF = <!General|SF_WJets!>\nspecialweight = <!Stitching|WJ200!>\ndcChunkSize = 20\n\n[WJetsToLNu_HT-400To600_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [4300,4301,4302]\nsampleName = WJetsHT400\nsampleType = BKG\nsubsamples = True\nsubnames = ['WJetsHT400_0b', 'WJetsHT400_1b', 'WJetsHT400_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|WJetsGroup!>\nxSec = [48.8 * 1.21] * 3\nSF = <!General|SF_WJets!>\nspecialweight = <!Stitching|WJ400!>\ndcChunkSize = 20\n\n[WJetsToLNu_HT-600To800_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [4400,4401,4402]\nsampleName = WJetsHT600\nsampleType = BKG\nsubsamples = True\nsubnames = ['WJetsHT600_0b', 'WJetsHT600_1b', 'WJetsHT600_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|WJetsGroup!>\nxSec = [12.07 * 1.21] * 3\nSF = <!General|SF_WJets!>\nspecialweight = <!Stitching|WJ600!>\ndcChunkSize = 20\n\n[WJetsToLNu_HT-800To1200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [4500,4501,4502]\nsampleName = WJetsHT800\nsampleType = BKG\nsubsamples = True\nsubnames = ['WJetsHT800_0b', 'WJetsHT800_1b', 'WJetsHT800_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|WJetsGroup!>\nxSec = [5.497 *1.21] * 3\nSF = <!General|SF_WJets!>\nspecialweight = <!Stitching|WJ800!>\ndcChunkSize = 20\n\n[WJetsToLNu_HT-1200To2500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [4600,4601,4602]\nsampleName = WJetsHT1200\nsampleType = BKG\nsubsamples = True\nsubnames = ['WJetsHT1200_0b', 'WJetsHT1200_1b', 'WJetsHT1200_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|WJetsGroup!>\nxSec = [1.329 * 1.21] * 3\nSF = <!General|SF_WJets!>\nspecialweight = <!Stitching|WJ1200!>\ndcChunkSize = 20\n\n[WJetsToLNu_HT-2500ToInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [4700,4701,4702]\nsampleName = WJetsHT2500\nsampleType = BKG\nsubsamples = True\nsubnames = ['WJetsHT2500_0b', 'WJetsHT2500_1b', 'WJetsHT2500_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|WJetsGroup!>\nxSec = [0.03209 * 1.21] * 3\nSF = <!General|SF_WJets!>\nspecialweight = <!Stitching|WJ2500!>\ndcChunkSize = 20\n\n# b-enriched W + jets\n\n#[WBJetsToLNu_Wpt-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\n#sampleIndex = [5000,5001,5002]\n#sampleName = WBJets100\n#sampleType = BKG\n#subsamples = True\n#subnames = ['WBJets100_0b', 'WBJets100_1b', 'WBJets100_2b']\n#subcuts = <!General|JetFlavor!>\n#sampleGroup = <!General|WJetsGroup!>\n#xSec = [6.004 * 1.21] * 3\n#SF = <!General|SF_WJets!>\n#specialweight_ON = (<!Stitching|WJB100!>)\n#specialweight_OFF = (<!Stitching|WJB100!>)\n#specialweight = <!.|specialweight_<!Stitching|ReweightLHEVpt!>!>\n\n#[WBJetsToLNu_Wpt-200toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\n#sampleIndex = [5100,5101,5102]\n#sampleName = WBJets200\n#sampleType = BKG\n#subsamples = True\n#subnames = ['WBJets200_0b', 'WBJets200_1b', 'WBJets200_2b']\n#subcuts = <!General|JetFlavor!>\n#sampleGroup = <!General|WJetsGroup!>\n#xSec = [0.8524 * 1.21] * 3 \n#SF = <!General|SF_WJets!>\n#specialweight_ON = (<!Stitching|WJB200!>)\n#specialweight_OFF = (<!Stitching|WJB200!>)\n#specialweight = <!.|specialweight_<!Stitching|ReweightLHEVpt!>!>\n\n#[WJetsToLNu_BGenFilter_Wpt-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\n#sampleIndex = [5300,5301,5302]\n#sampleName = WBGenFilter100\n#sampleType = BKG\n#subsamples = True\n#subnames = ['WBGenFilter100_0b', 'WBGenFilter100_1b', 'WBGenFilter100_2b']\n#subcuts = <!General|JetFlavor!>\n#sampleGroup = <!General|WJetsGroup!>\n#xSec = [26.1 * 1.21] * 3\n#SF = <!General|SF_WJets!>\n#specialweight_ON = (<!Stitching|WJGBF100!>)\n#specialweight_OFF = (<!Stitching|WJGBF100!>)\n#specialweight = <!.|specialweight_<!Stitching|ReweightLHEVpt!>!>\n\n#[WJetsToLNu_BGenFilter_Wpt-200toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\n#sampleIndex = [5400,5401,5402]\n#sampleName = WBGenFilter200\n#sampleType = BKG\n#subsamples = True\n#subnames = ['WBGenFilter200_0b', 'WBGenFilter200_1b', 'WBGenFilter200_2b']\n#subcuts = <!General|JetFlavor!>\n#sampleGroup = <!General|WJetsGroup!>\n#xSec = [3.545 * 1.21] * 3 \n#SF = <!General|SF_WJets!>\n#specialweight_ON = (<!Stitching|WJGBF200!>)\n#specialweight_OFF = (<!Stitching|WJGBF200!>)\n#specialweight = <!.|specialweight_<!Stitching|ReweightLHEVpt!>!>\n\n\n#TT\n\n[TT_TuneCUETP8M2T4_13TeV-powheg-pythia8]\nsampleIndex = 200\nsampleName = TT\nsampleType = BKG\nsubsamples = False\nsampleGroup = TT\nxSec = [831.76]\nSF = <!General|SF_TT!>\nspecialweight = 1.0\ndcChunkSize = 15\n\n#ST\n\n[ST_tW_antitop_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1]\nsampleIndex = 21 \nsampleName = ST_tW_antitop\nsampleType = BKG\nsubsamples = False\nsampleGroup = ST\nxSec = [35.85]\nSF = 1.0 \n\n[ST_tW_top_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1]\nsampleIndex = 20\nsampleName = ST_tW_top\nsampleType = BKG\nsubsamples = False\nsampleGroup = ST\nxSec = [35.85]\nSF = 1.0 \n\n[ST_s-channel_4f_InclusiveDecays_13TeV-amcatnlo-pythia8]\nsampleIndex = 16\nsampleName = ST_s-channel_4f\nsampleType = BKG\nsubsamples = False\nsampleGroup = ST\nxSec = [3.692]\nSF = 1.0 \n\n[ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1]\nsampleIndex = 18\nsampleName = ST_t-channel_top_4f\nsampleType = BKG\nsubsamples = False\nsampleGroup = ST\nxSec = [136.02]\nSF = 1.0 \n\n[ST_t-channel_antitop_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1]\nsampleIndex = 19\nsampleName = ST_t-channel_antitop_4f\nsampleType = BKG\nsubsamples = False\nsampleGroup = ST\nxSec = [80.95]\nSF = 1.0 \n\n#----- DY -----#\n\n#Jet binned M-4to50\n\n# sample broken!!!\n#[DYJetsToLL_M-4to50_HT-70to100_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\n#sampleName = DYJetsToLL_M-4to50_HT-70to100_TuneCUETP8M1_13TeV-madgraphMLM-pythia8 \n#sampleType = BKG\n#subsamples = True\n#subnames =['M4HT70to100_0b','M4HT70to100_1b','M4HT70to100_2b']\n#subcuts=<!General|JetFlavor!>\n#sampleGroup = <!General|Zjets_sampleGroup_v3!>\n#xSec = [145.5*1.23]*3\n#SF = <!General|SF_ZJets!>\n\n#[DYJetsToLL_M-4to50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\n#sampleIndex = [12500,12501,12502]\n#sampleName = DYJetsToLL_M-4to50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8 \n#sampleType = BKG\n#subsamples = True\n#subnames =['M4HT100to200_0b','M4HT100to200_1b','M4HT100to200_2b']\n#subcuts=<!General|JetFlavor!>\n#sampleGroup = <!General|Zjets_sampleGroup_v3!>\n#xSec = [204.0*1.23]*3\n#SF = <!General|SF_ZJets!>\n\n#[DYJetsToLL_M-4to50_HT-200to400_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\n#sampleIndex = [12600,12601,12602]\n#sampleName = DYJetsToLL_M-4to50_HT-200to400_TuneCUETP8M1_13TeV-madgraphMLM-pythia8 \n#sampleType = BKG\n#subsamples = True\n#subnames =['M4HT200to400_0b','M4HT200to400_1b','M4HT200to400_2b']\n#subcuts=<!General|JetFlavor!>\n#sampleGroup = <!General|Zjets_sampleGroup_v3!>\n#xSec = [54.39*1.23]*3\n#SF = <!General|SF_ZJets!>\n\n#[DYJetsToLL_M-4to50_HT-400to600_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\n#sampleIndex = [12700,12701,12702]\n#sampleName = DYJetsToLL_M-4to50_HT-400to600_TuneCUETP8M1_13TeV-madgraphMLM-pythia8 \n#sampleType = BKG\n#subsamples = True\n#subnames =['M4HT400to600_0b','M4HT400to600_1b','M4HT400to600_2b']\n#subcuts=<!General|JetFlavor!>\n#sampleGroup = <!General|Zjets_sampleGroup_v3!>\n#xSec = [5.697*1.23]*3\n#SF = <!General|SF_ZJets!>\n\n#[DYJetsToLL_M-4to50_HT-600toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\n#sampleIndex = [12800,12801,12802]\n#sampleName = DYJetsToLL_M-4to50_HT-600toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8\n#sampleType = BKG\n#subsamples = True\n#subnames = ['M4HT600toInf_0b','M4HT600toInf_1b','M4HT600toInf_2b']\n#subcuts= <!General|JetFlavor!>\n#sampleGroup = <!General|Zjets_sampleGroup_v3!>\n#xSec = [1.850*1.23]*3\n#SF = <!General|SF_ZJets!>\n\n\n[DYJetsToLL_M-50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [11100,11101,11102]\nsampleName = DYJetsToLL_M-50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8\nsampleType = BKG\nsubsamples = True\nsubnames =['HT100to200ZJets_0b','HT100to200ZJets_1b','HT100to200ZJets_2b']\nsubcuts=<!General|JetFlavor!>\nsampleGroup = <!General|Zjets_sampleGroup_v3!>\nxSec = [147.40*1.23]*3\nSF = <!General|SF_ZJets!>\ndcChunkSize = 3\nspecialweight = (<!General|allDYweight!>)*(<!Stitching|DY_HT100!>) \n\n[DYJetsToLL_M-50_HT-200to400_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [11200,11201,11202]\nsampleName = DYJetsToLL_M-50_HT-200to400_TuneCUETP8M1_13TeV-madgraphMLM-pythia8\nsampleType = BKG\nsubsamples = True\nsubnames =['HT200to400ZJets_0b','HT200to400ZJets_1b','HT200to400ZJets_2b']\nsubcuts=<!General|JetFlavor!>\nsampleGroup = <!General|Zjets_sampleGroup_v3!>\nxSec = [40.99*1.23]*3\nSF = <!General|SF_ZJets!>\nspecialweight = (<!General|allDYweight!>)*(<!Stitching|DY_HT200!>) \ndcChunkSize = 3\n\n[DYJetsToLL_M-50_HT-400to600_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [11300,11301,11302]\nsampleName = DYJetsToLL_M-50_HT-400to600_TuneCUETP8M1_13TeV-madgraphMLM-pythia8 \nsampleType = BKG\nsubsamples = True\nsubnames =['HT400to600ZJets_0b','HT400to600ZJets_1b','HT400to600ZJets_2b']\nsubcuts=<!General|JetFlavor!>\nsampleGroup = <!General|Zjets_sampleGroup_v3!>\nxSec = [5.678*1.23]*3\nSF = <!General|SF_ZJets!>\nspecialweight = (<!General|allDYweight!>)*(<!Stitching|DY_HT400!>) \ndcChunkSize = 3\n\n \n[DYJetsToLL_M-50_HT-600to800_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [11400,11401,11402]\nsampleName = DYJetsToLL_M-50_HT-600to800_TuneCUETP8M1_13TeV-madgraphMLM-pythia8 \nsampleType = BKG\nsubsamples = True\nsubnames =['HT600to800ZJets_0b','HT600to800ZJets_1b','HT600to800ZJets_2b']\nsubcuts=<!General|JetFlavor!>\nsampleGroup = <!General|Zjets_sampleGroup_v3!>\n;x-sec from https://twiki.cern.ch/twiki/bin/view/CMS/SummaryTable1G25ns#DY_Z\nxSec = [1.367*1.23]*3\nSF = <!General|SF_ZJets!>\nspecialweight = (<!General|allDYweight!>)*(<!Stitching|DY_HT600!>) \ndcChunkSize = 3\n\n[DYJetsToLL_M-50_HT-800to1200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [11500,11501,11502]\nsampleName = DYJetsToLL_M-50_HT-800to1200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8 \nsampleType = BKG\nsubsamples = True\nsubnames =['HT800to1200ZJets_0b','HT800to1200ZJets_1b','HT800to1200ZJets_2b']\nsubcuts=<!General|JetFlavor!>\nsampleGroup = <!General|Zjets_sampleGroup_v3!>\n;x-sec from https://twiki.cern.ch/twiki/bin/view/CMS/SummaryTable1G25ns#DY_Z\nxSec = [0.6304*1.23]*3\nSF = <!General|SF_ZJets!>\nspecialweight = (<!General|allDYweight!>)*(<!Stitching|DY_HT800!>) \n\n#[DYJetsToLL_M-50_HT-1200to2500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\n#sampleIndex = [11600,11601,11602]\n#sampleName = DYJetsToLL_M-50_HT-1200to2500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8 \n#sampleType = BKG\n#subsamples = True\n#subnames =['HT1200to2500ZJets_0b','HT1200to2500ZJets_1b','HT1200to2500ZJets_2b']\n#subcuts=<!General|JetFlavor!>\n#sampleGroup = <!General|Zjets_sampleGroup_v3!>\n#;x-sec from https://twiki.cern.ch/twiki/bin/view/CMS/SummaryTable1G25ns#DY_Z\n#xSec = [0.1514*1.23]*3\n#SF = <!General|SF_ZJets!>\n#specialweight = (<!General|allDYweight!>)*(<!Stitching|DY_HT1200!>) \n\n#[DYJetsToLL_M-50_HT-2500toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\n#sampleIndex = [11700,11701,11702]\n#sampleName = DYJetsToLL_M-50_HT-2500toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8 \n#sampleType = BKG\n#subsamples = True\n#subnames =['HT2500toinfZJets_0b','HT2500toinfZJets_1b','HT2500toinfZJets_2b']\n#subcuts=<!General|JetFlavor!>\n#sampleGroup = <!General|Zjets_sampleGroup_v3!>\n#;x-sec from https://twiki.cern.ch/twiki/bin/view/CMS/SummaryTable1G25ns#DY_Z\n#xSec = [0.003565*1.23]*3\n#SF = <!General|SF_ZJets!>\n#specialweight = (<!General|allDYweight!>)*(<!Stitching|DY_HT2500!>) \n\n[DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [11000,11001,11002]\nsampleName = DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8 \nsampleType = BKG\nsubsamples = True\nsubnames =['HT0to100ZJets_0b','HT0to100ZJets_1b','HT0to100ZJets_2b']\nsubcuts=<!General|JetFlavor!>\nsampleGroup = <!General|Zjets_sampleGroup_v3!>\n;x-sec from https://twiki.cern.ch/twiki/bin/view/CMS/SummaryTable1G25ns#DY_Z\nxSec = [5765.4*1.23]*3\nSF = <!General|SF_ZJets!>\nspecialweight = (<!General|allDYweight!>)*(<!Stitching|DYincl!>) \n\n\n#B enriched samples\n\n[DYBJetsToLL_M-50_Zpt-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [12100,12101,12102]\nsampleName = DYBJetsToLL_M-50_Zpt-100to200_TuneCUETP8M1_13TeV\nsampleType = BKG\nsubsamples = True\nsubnames =['DYBJets_100to200_0b','DYBJets_100to200_1b','DYBJets_100to200_2b']\nsubcuts=<!General|JetFlavor!>\nsampleGroup = <!General|Zjets_sampleGroup_v3!>\nxSec = [3.027 * 1.23] * 3\nSF = <!General|SF_ZJets!>\nspecialweight_ON = (<!General|allDYweight!>)*(<!Stitching|DY_B100!>)\nspecialweight_OFF = (<!General|allDYweight!>)*(<!Stitching|DY_B100!>)\nspecialweight = <!.|specialweight_<!Stitching|ReweightLHEVpt!>!>\n\n\n[DYBJetsToLL_M-50_Zpt-200toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [12200,12201,12202]\nsampleName = DYBJetsToLL_M-50_Zpt-200toInf_TuneCUETP8M1_13TeV\nsampleType = BKG\nsubsamples = True\nsubnames =['DYBJets_200toInf_0b','DYBJets_200toInf_1b','DYBJets_200toInf_2b']\nsubcuts=<!General|JetFlavor!>\nsampleGroup = <!General|Zjets_sampleGroup_v3!>\nxSec = [0.297 * 1.23] * 3\nSF = <!General|SF_ZJets!>\nspecialweight_ON = (<!General|allDYweight!>)*(<!Stitching|DY_B200!>)\nspecialweight_OFF = (<!General|allDYweight!>)*(<!Stitching|DY_B200!>)\nspecialweight = <!.|specialweight_<!Stitching|ReweightLHEVpt!>!>\n\n[DYJetsToLL_BGenFilter_Zpt-100to200_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [14100,14101,14102]\nsampleName = DYJetsToLL_BGenFilter_Zpt-100to200_M-50_TuneCUETP8M1_13TeV\nsampleType = BKG\nsubsamples = True\nsubnames =['DYJetsBGenFilter_100to200_0b','DYJetsBGenFilter_100to200_1b','DYJetsBGenFilter_100to200_2b']\nsubcuts=<!General|JetFlavor!>\nsampleGroup = <!General|Zjets_sampleGroup_v3!>\nxSec = [3.41 * 1.23] * 3\nSF = <!General|SF_ZJets!>\nspecialweight_ON = (<!General|allDYweight!>)*(<!Stitching|DY_F100!>)\nspecialweight_OFF = (<!General|allDYweight!>)*(<!Stitching|DY_F100!>)\nspecialweight = <!.|specialweight_<!Stitching|ReweightLHEVpt!>!>\n\n \n[DYJetsToLL_BGenFilter_Zpt-200toInf_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [14200,14201,14202]\nsampleName = DYJetsToLL_BGenFilter_Zpt-200toInf_M-50_TuneCUETP8M1_13TeV\nsampleType = BKG\nsubsamples = True\nsubnames =['DYJetsBGenFilter_200toInf_0b','DYJetsBGenFilter_200toInf_1b','DYJetsBGenFilter_200toInf_2b']\nsubcuts=<!General|JetFlavor!>\nsampleGroup = <!General|Zjets_sampleGroup_v3!>\nbStitchingKfactor_OFF = 1.00\nxSec = [0.5082 * 1.23] * 3\nSF = <!General|SF_ZJets!>\nspecialweight_ON = (<!General|allDYweight!>)*(<!Stitching|DY_F200!>)\nspecialweight_OFF = (<!General|allDYweight!>)*(<!Stitching|DY_F200!>)\nspecialweight = <!.|specialweight_<!Stitching|ReweightLHEVpt!>!>\n\n#[DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8]\n#sampleIndex = [20100,20101,20102]\n#sampleName = DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8\n#sampleType = BKG\n#subsamples = True\n#subnames = ['DYnloIncl_0b','DYnloIncl_1b','DYnloIncl_2b']\n#subcuts = <!General|JetFlavor!>\n#sampleGroup = <!General|Zjets_sampleGroup_v3!>\n#xSec = [6529.0]*3\n#SF = <!General|SF_ZJets!>\n#specialweight = <!General|allDYweight!>\n\n#-- QCD Samples --#\n\n[QCD_HT100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = 1 \nsampleName = QCDHT100\nsampleType = BKG\nsubsamples = False\nsampleGroup = QCD\nxSec = [23690000]\nSF = <!General|SF_QCD!>\n\n[QCD_HT200to300_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = 2\nsampleName = QCDHT200\nsampleType = BKG\nsubsamples = False\nsampleGroup = QCD\nxSec = [1556000]\nSF = <!General|SF_QCD!>\n\n[QCD_HT300to500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = 3\nsampleName = QCDHT300\nsampleType = BKG\nsubsamples = False\nsampleGroup = QCD\nxSec = [323600]\nSF = <!General|SF_QCD!>\n\n[QCD_HT500to700_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = 4\nsampleName = QCDHT500\nsampleType = BKG\nsubsamples = False\nsampleGroup = QCD\nxSec = [29930]\nSF = <!General|SF_QCD!>\n\n[QCD_HT700to1000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = 5\nsampleName = QCDHT700\nsampleType = BKG\nsubsamples = False\nsampleGroup = QCD\nxSec = [6351]\nSF = <!General|SF_QCD!>\n\n[QCD_HT1000to1500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = 6\nsampleName = QCDHT1000\nsampleType = BKG\nsubsamples = False\nsampleGroup = QCD\nxSec = [1094]\nSF = <!General|SF_QCD!>\n\n[QCD_HT1500to2000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = 7\nsampleName = QCDHT1500\nsampleType = BKG\nsubsamples = False\nsampleGroup = QCD\nxSec = [98.99]\nSF = <!General|SF_QCD!>\n\n[QCD_HT2000toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = 8\nsampleName = QCDHT2000\nsampleType = BKG\nsubsamples = False\nsampleGroup = QCD\nxSec = [20.23]\nSF = <!General|SF_QCD!>\n\n\n\n#-- Z+Jets Samples --#\n\n[ZJetsToNuNu_HT-100To200_13TeV-madgraph]\nsampleIndex = [15000,15001,15002]\nsampleName = ZJetsHT100\nsampleType = BKG\nsubsamples = True\nsubnames = ['ZJetsHT100_0b', 'ZJetsHT100_1b', 'ZJetsHT100_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|ZJetsGroup!>\nxSec = [280.59 * 1.23] * 3\nSF = <!General|SF_ZJets!>\nspecialweight = <!Stitching|ZJ100!>\n\n[ZJetsToNuNu_HT-200To400_13TeV-madgraph]\nsampleIndex = [15100,15101,15102]\nsampleName = ZJetsHT200\nsampleType = BKG\nsubsamples = True\nsubnames = ['ZJetsHT200_0b', 'ZJetsHT200_1b', 'ZJetsHT200_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|ZJetsGroup!>\nxSec = [77.79 * 1.23] * 3\nSF = <!General|SF_ZJets!>\nspecialweight = <!Stitching|ZJ200!>\n\n[ZJetsToNuNu_HT-400To600_13TeV-madgraph]\nsampleIndex = [15200,15201,15202]\nsampleName = ZJetsHT400\nsampleType = BKG\nsubsamples = True\nsubnames = ['ZJetsHT400_0b', 'ZJetsHT400_1b', 'ZJetsHT400_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|ZJetsGroup!>\nxSec = [10.755 * 1.23] * 3\nSF = <!General|SF_ZJets!>\nspecialweight = <!Stitching|ZJ400!>\n\n[ZJetsToNuNu_HT-600To800_13TeV-madgraph]\nsampleIndex = [15300,15301,15302]\nsampleName = ZJetsHT600\nsampleType = BKG\nsubsamples = True\nsubnames = ['ZJetsHT600_0b', 'ZJetsHT600_1b', 'ZJetsHT600_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|ZJetsGroup!>\nxSec = [2.5644 * 1.23] * 3\nSF = <!General|SF_ZJets!>\nspecialweight = <!Stitching|ZJ600!>\n\n[ZJetsToNuNu_HT-800To1200_13TeV-madgraph]\nsampleIndex = [15400,15401,15402]\nsampleName = ZJetsHT800\nsampleType = BKG\nsubsamples = True\nsubnames = ['ZJetsHT800_0b', 'ZJetsHT800_1b', 'ZJetsHT800_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|ZJetsGroup!>\nxSec = [1.1802 * 1.23] * 3\nSF = <!General|SF_ZJets!>\nspecialweight = <!Stitching|ZJ800!>\n\n[ZJetsToNuNu_HT-1200To2500_13TeV-madgraph]\nsampleIndex = [15500,15501,15502]\nsampleName = ZJetsHT1200\nsampleType = BKG\nsubsamples = True\nsubnames = ['ZJetsHT1200_0b', 'ZJetsHT1200_1b', 'ZJetsHT1200_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|ZJetsGroup!>\nxSec = [0.28629 * 1.23] * 3\nSF = <!General|SF_ZJets!>\nspecialweight = <!Stitching|ZJ1200!>\n\n[ZJetsToNuNu_HT-2500ToInf_13TeV-madgraph]\nsampleIndex = [15600,15601,15602]\nsampleName = ZJetsHT2500\nsampleType = BKG\nsubsamples = True\nsubnames = ['ZJetsHT2500_0b', 'ZJetsHT2500_1b', 'ZJetsHT2500_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|ZJetsGroup!>\nxSec = [0.006912 * 1.23] * 3\nSF = <!General|SF_ZJets!>\nspecialweight = <!Stitching|ZJ2500!>\n\n# b-enriched\n\n#[ZBJetsToNuNu_Zpt-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\n#sampleIndex = [16000,16001,16002]\n#sampleName = ZBJets100\n#sampleType = BKG\n#subsamples = True\n#subnames = ['ZBJets100_0b','ZBJets100_1b','ZBJets100_2b']\n#subcuts = <!General|JetFlavor!>\n#sampleGroup = <!General|ZJetsGroup!>\n#xSec = [5.93 * 1.23] * 3\n#SF = <!General|SF_ZJets!>\n#specialweight_ON = (<!Stitching|ZJB100!>)\n#specialweight_OFF = (<!Stitching|ZJB100!>)\n#specialweight = <!.|specialweight_<!Stitching|ReweightLHEVpt!>!>\n\n[ZBJetsToNuNu_Zpt-200toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [16100,16101,16102]\nsampleName = ZBJets200\nsampleType = BKG\nsubsamples = True\nsubnames = ['ZBJets200_0b','ZBJets200_1b','ZBJets200_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|ZJetsGroup!>\nxSec = [0.6068 * 1.23] * 3 \nSF = <!General|SF_ZJets!>\nspecialweight_ON = (<!Stitching|ZJB200!>)\nspecialweight_OFF = (<!Stitching|ZJB200!>)\nspecialweight = <!.|specialweight_<!Stitching|ReweightLHEVpt!>!>\n\n[ZJetsToNuNu_BGenFilter_Zpt-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [16200,16201,16202]\nsampleName = ZBGenFilter100\nsampleType = BKG\nsubsamples = True\nsubnames = ['ZBGenFilter100_0b','ZBGenFilter100_1b','ZBGenFilter100_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|ZJetsGroup!>\nxSec = [2.16 * 1.23] * 3 \nSF = <!General|SF_ZJets!>\nspecialweight_ON = (<!Stitching|ZJGBF100!>)\nspecialweight_OFF = (<!Stitching|ZJGBF100!>)\nspecialweight = <!.|specialweight_<!Stitching|ReweightLHEVpt!>!>\n\n[ZJetsToNuNu_BGenFilter_Zpt-200toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8]\nsampleIndex = [16300,16301,16302]\nsampleName = ZBGenFilter200\nsampleType = BKG\nsubsamples = True\nsubnames = ['ZBGenFilter200_0b','ZBGenFilter200_1b','ZBGenFilter200_2b']\nsubcuts = <!General|JetFlavor!>\nsampleGroup = <!General|ZJetsGroup!>\nxSec = [0.3155 * 1.23] * 3\nSF = <!General|SF_ZJets!>\nspecialweight_ON = (<!Stitching|ZJGBF200!>)\nspecialweight_OFF = (<!Stitching|ZJGBF200!>)\nspecialweight = <!.|specialweight_<!Stitching|ReweightLHEVpt!>!>\n\n\n\n# this is the list of samples which will be used to construct the lists of samples to plot/for shape making\n[Samples]\n\n#----- VH -----#\nZHsignal = 'ZllH_lep_PTV_0_75_hbb','ZllH_lep_PTV_75_150_hbb','ZllH_lep_PTV_150_250_0J_hbb','ZllH_lep_PTV_150_250_GE1J_hbb','ZllH_lep_PTV_GT250_hbb','ZnnH_lep_PTV_0_75_hbb','ZnnH_lep_PTV_75_150_hbb','ZnnH_lep_PTV_150_250_0J_hbb','ZnnH_lep_PTV_150_250_GE1J_hbb','ZnnH_lep_PTV_GT250_hbb'\nggZHsignal = 'ggZllH_lep_PTV_0_75_hbb','ggZllH_lep_PTV_75_150_hbb','ggZllH_lep_PTV_150_250_0J_hbb','ggZllH_lep_PTV_150_250_GE1J_hbb','ggZllH_lep_PTV_GT250_hbb','ggZnnH_lep_PTV_0_75_hbb','ggZnnH_lep_PTV_75_150_hbb','ggZnnH_lep_PTV_150_250_0J_hbb','ggZnnH_lep_PTV_150_250_GE1J_hbb','ggZnnH_lep_PTV_GT250_hbb'\nWHsignal = 'WminusH_lep_PTV_0_75_hbb','WminusH_lep_PTV_75_150_hbb','WminusH_lep_PTV_150_250_0J_hbb','WminusH_lep_PTV_150_250_GE1J_hbb','WminusH_lep_PTV_GT250_hbb','WplusH_lep_PTV_0_75_hbb','WplusH_lep_PTV_75_150_hbb','WplusH_lep_PTV_150_250_0J_hbb','WplusH_lep_PTV_150_250_GE1J_hbb','WplusH_lep_PTV_GT250_hbb'\nsignals = <!Samples|ZHsignal!>,<!Samples|ggZHsignal!>,<!Samples|WHsignal!>\n\n#----- W+jets -----#\nWJetsHT0 = 'WJetsHT0_0b', 'WJetsHT0_1b', 'WJetsHT0_2b'\nWJetsHT100 = 'WJetsHT100_0b', 'WJetsHT100_1b', 'WJetsHT100_2b'\nWJetsHT200 = 'WJetsHT200_0b', 'WJetsHT200_1b', 'WJetsHT200_2b'\nWJetsHT400 = 'WJetsHT400_0b', 'WJetsHT400_1b', 'WJetsHT400_2b'\nWJetsHT600 = 'WJetsHT600_0b', 'WJetsHT600_1b', 'WJetsHT600_2b'\nWJetsHT800 = 'WJetsHT800_0b', 'WJetsHT800_1b', 'WJetsHT800_2b'\nWJetsHT1200 = 'WJetsHT1200_0b', 'WJetsHT1200_1b', 'WJetsHT1200_2b'\nWJetsHT2500 = 'WJetsHT2500_0b', 'WJetsHT2500_1b', 'WJetsHT2500_2b'\n\n#WJetsB = 'WBJets100_0b', 'WBJets100_1b', 'WBJets100_2b','WBJets200_0b', 'WBJets200_1b', 'WBJets200_2b','WBGenFilter100_0b', 'WBGenFilter100_1b', 'WBGenFilter100_2b','WBGenFilter200_0b', 'WBGenFilter200_1b', 'WBGenFilter200_2b'\n#WJets = <!Samples|WJetsHT0!>,<!Samples|WJetsHT100!>,<!Samples|WJetsHT200!>,<!Samples|WJetsHT400!>,<!Samples|WJetsHT600!>,<!Samples|WJetsHT800!>,<!Samples|WJetsHT1200!>,<!Samples|WJetsB!>\nWJets = <!Samples|WJetsHT0!>,<!Samples|WJetsHT100!>,<!Samples|WJetsHT200!>,<!Samples|WJetsHT400!>,<!Samples|WJetsHT600!>,<!Samples|WJetsHT800!>,<!Samples|WJetsHT1200!>\n\n#WJets_0b = 'WJetsHT100_0b','WJetsHT200_0b','WJetsHT400_0b','WJetsHT600_0b','WJetsHT800_0b','WJetsHT1200_0b','WBJets100_0b','WBJets200_0b','WBGenFilter100_0b','WBGenFilter200_0b'\nWJets_0b = 'WJetsHT100_0b','WJetsHT200_0b','WJetsHT400_0b','WJetsHT600_0b','WJetsHT800_0b','WJetsHT1200_0b'\n#WJets_1b = 'WJetsHT100_1b','WJetsHT200_1b','WJetsHT400_1b','WJetsHT600_1b','WJetsHT800_1b','WJetsHT1200_1b','WBJets100_1b','WBJets200_1b','WBGenFilter100_1b','WBGenFilter200_1b'\nWJets_1b = 'WJetsHT100_1b','WJetsHT200_1b','WJetsHT400_1b','WJetsHT600_1b','WJetsHT800_1b','WJetsHT1200_1b'\n#WJets_2b = 'WJetsHT100_2b','WJetsHT200_2b','WJetsHT400_2b','WJetsHT600_2b','WJetsHT800_2b','WJetsHT1200_2b','WBJets100_2b','WBJets200_2b','WBGenFilter100_2b','WBGenFilter200_2b'\nWJets_2b = 'WJetsHT100_2b','WJetsHT200_2b','WJetsHT400_2b','WJetsHT600_2b','WJetsHT800_2b','WJetsHT1200_2b'\n\n\n#----- Z+jets -----#\nZJetsHT100 = 'ZJetsHT100_0b', 'ZJetsHT100_1b', 'ZJetsHT100_2b'\nZJetsHT200 = 'ZJetsHT200_0b', 'ZJetsHT200_1b', 'ZJetsHT200_2b'\nZJetsHT400 = 'ZJetsHT400_0b', 'ZJetsHT400_1b', 'ZJetsHT400_2b'\nZJetsHT600 = 'ZJetsHT600_0b', 'ZJetsHT600_1b', 'ZJetsHT600_2b'\nZJetsHT800 = 'ZJetsHT800_0b', 'ZJetsHT800_1b', 'ZJetsHT800_2b'\nZJetsHT1200 = 'ZJetsHT1200_0b', 'ZJetsHT1200_1b', 'ZJetsHT1200_2b'\nZJetsHT2500 = 'ZJetsHT2500_0b', 'ZJetsHT2500_1b', 'ZJetsHT2500_2b'\n\n#ZJB = 'ZBJets100_0b','ZBJets100_1b','ZBJets100_2b','ZBJets200_0b','ZBJets200_1b','ZBJets200_2b','ZBGenFilter100_0b','ZBGenFilter100_1b','ZBGenFilter100_2b','ZBGenFilter200_0b','ZBGenFilter200_1b','ZBGenFilter200_2b'\nZJB = 'ZBJets200_0b','ZBJets200_1b','ZBJets200_2b','ZBGenFilter100_0b','ZBGenFilter100_1b','ZBGenFilter100_2b','ZBGenFilter200_0b','ZBGenFilter200_1b','ZBGenFilter200_2b'\nZJets = <!Samples|ZJetsHT100!>, <!Samples|ZJetsHT200!>, <!Samples|ZJetsHT400!>, <!Samples|ZJetsHT600!>, <!Samples|ZJetsHT800!>, <!Samples|ZJetsHT1200!>, <!Samples|ZJetsHT2500!>, <!Samples|ZJB!>\n\n#ZJets_0b = 'ZJetsHT100_0b','ZJetsHT200_0b','ZJetsHT400_0b','ZJetsHT600_0b','ZJetsHT800_0b','ZJetsHT1200_0b','ZJetsHT2500_0b','ZBJets100_0b','ZBJets200_0b','ZBGenFilter100_0b','ZBGenFilter200_0b'\nZJets_0b = 'ZJetsHT100_0b','ZJetsHT200_0b','ZJetsHT400_0b','ZJetsHT600_0b','ZJetsHT800_0b','ZJetsHT1200_0b','ZJetsHT2500_0b','ZBJets200_0b','ZBGenFilter100_0b','ZBGenFilter200_0b'\n#ZJets_1b = 'ZJetsHT100_1b','ZJetsHT200_1b','ZJetsHT400_1b','ZJetsHT600_1b','ZJetsHT800_1b','ZJetsHT1200_1b','ZJetsHT2500_1b','ZBJets100_1b','ZBJets200_1b','ZBGenFilter100_1b','ZBGenFilter200_1b'\nZJets_1b = 'ZJetsHT100_1b','ZJetsHT200_1b','ZJetsHT400_1b','ZJetsHT600_1b','ZJetsHT800_1b','ZJetsHT1200_1b','ZJetsHT2500_1b','ZBJets200_1b','ZBGenFilter100_1b','ZBGenFilter200_1b'\n#ZJets_2b = 'ZJetsHT100_2b','ZJetsHT200_2b','ZJetsHT400_2b','ZJetsHT600_2b','ZJetsHT800_2b','ZJetsHT1200_2b','ZJetsHT2500_2b','ZBJets100_2b','ZBJets200_2b','ZBGenFilter100_2b','ZBGenFilter200_2b'\nZJets_2b = 'ZJetsHT100_2b','ZJetsHT200_2b','ZJetsHT400_2b','ZJetsHT600_2b','ZJetsHT800_2b','ZJetsHT1200_2b','ZJetsHT2500_2b','ZBJets200_2b','ZBGenFilter100_2b','ZBGenFilter200_2b'\n\n#----- DY -----#\n# DYm4 not available\n;DYm4HT70 = 'M4HT70to100_0b','M4HT70to100_1b','M4HT70to100_2b'\nDYm4HT100 = 'M4HT100to200_0b','M4HT100to200_1b','M4HT100to200_2b'\nDYm4HT200 = 'M4HT200to400_0b','M4HT200to400_1b','M4HT200to400_2b'\nDYm4HT400 = 'M4HT400to600_0b','M4HT400to600_1b','M4HT400to600_2b'\nDYm4HT600 = 'M4HT600toInf_0b','M4HT600toInf_1b','M4HT600toInf_2b'\n\nDYm4 = <!Samples|DYm4HT100!>,<!Samples|DYm4HT200!>,<!Samples|DYm4HT400!>,<!Samples|DYm4HT600!> \n\nDYHT0 = 'HT0to100ZJets_0b','HT0to100ZJets_1b','HT0to100ZJets_2b'\nDYHT100 = 'HT100to200ZJets_0b','HT100to200ZJets_1b','HT100to200ZJets_2b'\nDYHT200 = 'HT200to400ZJets_0b','HT200to400ZJets_1b','HT200to400ZJets_2b'\nDYHT400 = 'HT400to600ZJets_0b','HT400to600ZJets_1b','HT400to600ZJets_2b'\nDYHT600 = 'HT600to800ZJets_0b','HT600to800ZJets_1b','HT600to800ZJets_2b'\nDYHT800 = 'HT800to1200ZJets_0b','HT800to1200ZJets_1b','HT800to1200ZJets_2b'\n#DYHT1200= 'HT1200to2500ZJets_0b','HT1200to2500ZJets_1b','HT1200to2500ZJets_2b'\n#DYHT2500= 'HT2500toinfZJets_0b','HT2500toinfZJets_1b','HT2500toinfZJets_2b'\n\n#DYm50 = <!Samples|DYHT0!>,<!Samples|DYHT100!>,<!Samples|DYHT200!>,<!Samples|DYHT400!>,<!Samples|DYHT600!>,<!Samples|DYHT800!>,<!Samples|DYHT1200!>,<!Samples|DYHT2500!>\nDYm50 = <!Samples|DYHT0!>,<!Samples|DYHT100!>,<!Samples|DYHT200!>,<!Samples|DYHT400!>,<!Samples|DYHT600!>,<!Samples|DYHT800!>\n\nDYBJets = 'DYBJets_100to200_0b','DYBJets_100to200_1b','DYBJets_100to200_2b','DYBJets_200toInf_0b','DYBJets_200toInf_1b','DYBJets_200toInf_2b' \nDYJetsBGenFilter = 'DYJetsBGenFilter_100to200_0b','DYJetsBGenFilter_100to200_1b','DYJetsBGenFilter_100to200_2b','DYJetsBGenFilter_200toInf_0b','DYJetsBGenFilter_200toInf_1b','DYJetsBGenFilter_200toInf_2b' \n\n#DYlo = <!Samples|DYm4!>,<!Samples|DYm50!>,<!Samples|DYBJets!>,<!Samples|DYJetsBGenFilter!>\nDYlo = <!Samples|DYm50!>,<!Samples|DYBJets!>,<!Samples|DYJetsBGenFilter!>\nDY = <!Samples|DYlo!>\n\nDynloIncl = 'DYnloIncl_0b','DYnloIncl_1b','DYnloIncl_2b'\nDYnlom50 = <!Samples|DynloIncl!>\nDYnlo = <!Samples|DYnlom50!>\n\n#DY_0b = 'M4HT100to200_0b','M4HT200to400_0b','M4HT400to600_0b','M4HT600toInf_0b','HT0to100ZJets_0b','HT100to200ZJets_0b','HT200to400ZJets_0b','HT400to600ZJets_0b','HT600to800ZJets_0b','HT800to1200ZJets_0b','HT1200to2500ZJets_0b','HT2500toinfZJets_0b','DYBJets_100to200_0b','DYBJets_200toInf_0b','DYJetsBGenFilter_100to200_0b','DYJetsBGenFilter_200toInf_0b'\nDY_0b = 'HT0to100ZJets_0b','HT100to200ZJets_0b','HT200to400ZJets_0b','HT400to600ZJets_0b','HT600to800ZJets_0b','HT800to1200ZJets_0b','DYBJets_100to200_0b','DYBJets_200toInf_0b','DYJetsBGenFilter_100to200_0b','DYJetsBGenFilter_200toInf_0b'\n#DY_1b = 'M4HT100to200_1b','M4HT200to400_1b','M4HT400to600_1b','M4HT600toInf_1b','HT0to100ZJets_1b','HT100to200ZJets_1b','HT200to400ZJets_1b','HT400to600ZJets_1b','HT600to800ZJets_1b','HT800to1200ZJets_1b','HT1200to2500ZJets_1b','HT2500toinfZJets_1b','DYBJets_100to200_1b','DYBJets_200toInf_1b','DYJetsBGenFilter_100to200_1b','DYJetsBGenFilter_200toInf_1b'\nDY_1b = 'HT0to100ZJets_1b','HT100to200ZJets_1b','HT200to400ZJets_1b','HT400to600ZJets_1b','HT600to800ZJets_1b','HT800to1200ZJets_1b','DYBJets_100to200_1b','DYBJets_200toInf_1b','DYJetsBGenFilter_100to200_1b','DYJetsBGenFilter_200toInf_1b'\n#DY_2b = 'M4HT100to200_2b','M4HT200to400_2b','M4HT400to600_2b','M4HT600toInf_2b','HT0to100ZJets_2b','HT100to200ZJets_2b','HT200to400ZJets_2b','HT400to600ZJets_2b','HT600to800ZJets_2b','HT800to1200ZJets_2b','HT1200to2500ZJets_2b','HT2500toinfZJets_2b','DYBJets_100to200_2b','DYBJets_200toInf_2b','DYJetsBGenFilter_100to200_2b','DYJetsBGenFilter_200toInf_2b'\nDY_2b = 'HT0to100ZJets_2b','HT100to200ZJets_2b','HT200to400ZJets_2b','HT400to600ZJets_2b','HT600to800ZJets_2b','HT800to1200ZJets_2b','DYBJets_100to200_2b','DYBJets_200toInf_2b','DYJetsBGenFilter_100to200_2b','DYJetsBGenFilter_200toInf_2b'\n\nDYm50_0b = 'HT0to100ZJets_0b','HT100to200ZJets_0b','HT200to400ZJets_0b','HT400to600ZJets_0b','HT600to800ZJets_0b','HT800to1200ZJets_0b','HT1200to2500ZJets_0b','HT2500toinfZJets_0b','DYBJets_100to200_0b','DYBJets_200toInf_0b','DYJetsBGenFilter_100to200_0b','DYJetsBGenFilter_200toInf_0b'\nDYm50_1b = 'HT0to100ZJets_1b','HT100to200ZJets_1b','HT200to400ZJets_1b','HT400to600ZJets_1b','HT600to800ZJets_1b','HT800to1200ZJets_1b','HT1200to2500ZJets_1b','HT2500toinfZJets_1b','DYBJets_100to200_1b','DYBJets_200toInf_1b','DYJetsBGenFilter_100to200_1b','DYJetsBGenFilter_200toInf_1b'\nDYm50_2b = 'HT0to100ZJets_2b','HT100to200ZJets_2b','HT200to400ZJets_2b','HT400to600ZJets_2b','HT600to800ZJets_2b','HT800to1200ZJets_2b','HT1200to2500ZJets_2b','HT2500toinfZJets_2b','DYBJets_100to200_2b','DYBJets_200toInf_2b','DYJetsBGenFilter_100to200_2b','DYJetsBGenFilter_200toInf_2b'\n\nDYnlo_0b = 'DYnloIncl_0b'\nDYnlo_1b = 'DYnloIncl_1b'\nDYnlo_2b = 'DYnloIncl_2b'\n\n#----- top Samples -----#\nTT = 'TT'\nST = 'ST_tW_antitop','ST_tW_top','ST_s-channel_4f','ST_t-channel_top_4f','ST_t-channel_antitop_4f'\n\n#----- QCD Samples -----#\nQCD = 'QCDHT200', 'QCDHT300', 'QCDHT500', 'QCDHT700', 'QCDHT1000', 'QCDHT1500', 'QCDHT2000'\n\n#----- Diboson Samples -----#\nWWLF = 'WWTo1L1Nu2Qnlo_0b'\nWZLF = 'WZTo1L1Nu2Qnlo_0b'\nZZLF = 'ZZTo2L2Qnlo_0b'\n\nWWHF = 'WWTo1L1Nu2Qnlo_1b','WWTo1L1Nu2Qnlo_2b'\nWZHF = 'WZTo1L1Nu2Qnlo_1b','WZTo1L1Nu2Qnlo_2b'\nZZHF = 'ZZTo2L2Qnlo_1b','ZZTo2L2Qnlo_2b'\n\nVVLF = <!Samples|WWLF!>,<!Samples|WZLF!>,<!Samples|ZZLF!>\nVVHF = <!Samples|WWHF!>,<!Samples|WZHF!>,<!Samples|ZZHF!>\n\nVV = <!Samples|VVLF!>,<!Samples|VVHF!>\n\n#----- all -----#\nbackgrounds = <!Samples|TT!>,<!Samples|ST!>,<!Samples|VV!>,<!Samples|DY!>,<!Samples|WJets!>,<!Samples|ZJets!>\n\n[VHbbCommon]\n\nGroupZJetsHT = {\n 'ZJetsHT100_0b':'ZJets100',\n 'ZJetsHT100_1b':'ZJets100',\n 'ZJetsHT100_2b':'ZJets100',\n 'ZJetsHT200_0b':'ZJets200',\n 'ZJetsHT200_1b':'ZJets200',\n 'ZJetsHT200_2b':'ZJets200',\n 'ZJetsHT400_0b':'ZJets400',\n 'ZJetsHT400_1b':'ZJets400',\n 'ZJetsHT400_2b':'ZJets400',\n 'ZJetsHT600_0b':'ZJets600',\n 'ZJetsHT600_1b':'ZJets600',\n 'ZJetsHT600_2b':'ZJets600',\n 'ZJetsHT800_0b':'ZJets800',\n 'ZJetsHT800_1b':'ZJets800',\n 'ZJetsHT800_2b':'ZJets800',\n 'ZJetsHT1200_0b':'ZJets1200',\n 'ZJetsHT1200_1b':'ZJets1200',\n 'ZJetsHT1200_2b':'ZJets1200',\n 'ZJetsHT2500_0b':'ZJets2500',\n 'ZJetsHT2500_1b':'ZJets2500',\n 'ZJetsHT2500_2b':'ZJets2500',\n }\n\nGroupWJetsHT = {\n 'WJetsHT100_0b':'WJets100',\n 'WJetsHT100_1b':'WJets100',\n 'WJetsHT100_2b':'WJets100',\n 'WJetsHT200_0b':'WJets200',\n 'WJetsHT200_1b':'WJets200',\n 'WJetsHT200_2b':'WJets200',\n 'WJetsHT400_0b':'WJets400',\n 'WJetsHT400_1b':'WJets400',\n 'WJetsHT400_2b':'WJets400',\n 'WJetsHT600_0b':'WJets600',\n 'WJetsHT600_1b':'WJets600',\n 'WJetsHT600_2b':'WJets600',\n 'WJetsHT800_0b':'WJets800',\n 'WJetsHT800_1b':'WJets800',\n 'WJetsHT800_2b':'WJets800',\n 'WJetsHT1200_0b':'WJets1200',\n 'WJetsHT1200_1b':'WJets1200',\n 'WJetsHT1200_2b':'WJets1200',\n 'WJetsHT2500_0b':'WJets2500',\n 'WJetsHT2500_1b':'WJets2500',\n 'WJetsHT2500_2b':'WJets2500',\n }\n\n" }, { "alpha_fraction": 0.6670854091644287, "alphanum_fraction": 0.8340452313423157, "avg_line_length": 55.056339263916016, "blob_id": "125fdec6adfe6047f118c2ade7e96662c2f68b0c", "content_id": "48e0e8c9a0fba43e2ce0f07e879f28cb1bfded4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 7960, "license_type": "no_license", "max_line_length": 81, "num_lines": 142, "path": "/python/Wlv2018config/hadd.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "#V12\n[Hadd]\nDYBJetsToLL_M-50_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 57\nDYJetsToLL_M-50_HT-600to800_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 4\nWplusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8: 3\nWJetsToLNu_TuneCP5_13TeV-madgraphMLM-pythia8: 73\nWJetsToLNu_BGenFilter_Wpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 3\nWminusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8: 3\nST_s-channel_4f_leptonDecays_TuneCP5_13TeV-madgraph-pythia8: 8\nZJetsToNuNu_HT-800To1200_13TeV-madgraph: 1\nQCD_HT500to700_TuneCP5_13TeV-madgraphMLM-pythia8: 130\nggZH_HToBB_ZToLL_M125_13TeV_powheg_pythia8: 14\nQCD_HT300to500_TuneCP5_13TeV-madgraphMLM-pythia8: 4675\nWZTo1L1Nu2Q_13TeV_amcatnloFXFX_madspin_pythia8: 3\nWJetsToLNu_HT-1200To2500_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nWBJetsToLNu_Wpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYJetsToLL_M-4to50_HT-400to600_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 11\nDYJetsToLL_M-50_HT-2500toInf_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 2\nDYJetsToLL_M-4to50_HT-600toInf_TuneCP5_PSWeights_13TeV-madgraphMLM-pythia8: 7\nDYJetsToLL_M-50_HT-200to400_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 30\nST_tW_antitop_5f_inclusiveDecays_TuneCP5_13TeV-powheg-pythia8: 3\nDYJetsToLL_M-50_HT-400to600_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 7\nDYJetsToLL_M-4to50_HT-100to200_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 3827\nZZTo2Q2Nu_TuneCP5_13TeV_amcatnloFXFX_madspin_pythia8: 1\nTTToHadronic_TuneCP5_13TeV-powheg-pythia8: 53\nWJetsToLNu_HT-200To400_TuneCP5_13TeV-madgraphMLM-pythia8: 3\nZJetsToNuNu_BGenFilter_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nQCD_HT2000toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 2\nZJetsToNuNu_BGenFilter_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 2\nZJetsToNuNu_HT-2500ToInf_13TeV-madgraph: 1\nZJetsToNuNu_HT-200To400_13TeV-madgraph: 1\nZZTo2L2Q_13TeV_amcatnloFXFX_madspin_pythia8: 72\nDYJetsToLL_M-50_HT-1200to2500_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 3\nTTToSemiLeptonic_TuneCP5_13TeV-powheg-pythia8: 3\nQCD_HT1500to2000_TuneCP5_13TeV-madgraphMLM-pythia8: 2\nWJetsToLNu_HT-400To600_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYJetsToLL_M-50_HT-100to200_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 1156\nZJetsToNuNu_HT-1200To2500_13TeV-madgraph: 1\nSingleMuon: 9999\nWBJetsToLNu_Wpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 2\nDYJetsToLL_M-50_HT-800to1200_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 3\nDYJetsToLL_BGenFilter_Zpt-200toInf_M-50_TuneCP5_13TeV-madgraphMLM-pythia8: 4\nQCD_HT100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 9999\nZJetsToNuNu_HT-100To200_13TeV-madgraph: 11\nQCD_HT700to1000_TuneCP5_13TeV-madgraphMLM-pythia8: 21\nWJetsToLNu_HT-800To1200_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nEGamma: 9\nTTTo2L2Nu_TuneCP5_13TeV-powheg-pythia8: 7\nQCD_HT200to300_TuneCP5_13TeV-madgraphMLM-pythia8: 197334\nZH_HToBB_ZToLL_M125_13TeV_powheg_pythia8: 34\nDYJetsToLL_M-4to50_HT-200to400_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 48\nZBJetsToNuNu_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZJetsToNuNu_HT-400To600_13TeV-madgraph: 1\nST_tW_top_5f_inclusiveDecays_TuneCP5_13TeV-powheg-pythia8: 8\nDYJetsToLL_M-50_TuneCP5_13TeV-madgraphMLM-pythia8: 207\nWWTo1L1Nu2Q_13TeV_amcatnloFXFX_madspin_pythia8: 7\nWJetsToLNu_HT-2500ToInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8: 1\nWJetsToLNu_HT-600To800_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZJetsToNuNu_HT-600To800_13TeV-madgraph: 1\nST_t-channel_antitop_4f_InclusiveDecays_TuneCP5_13TeV-powheg-madspin-pythia8: 9\nWJetsToLNu_HT-100To200_TuneCP5_13TeV-madgraphMLM-pythia8: 44\nMET: 1\nWJetsToLNu_BGenFilter_Wpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZBJetsToNuNu_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nggZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8: 1\nDYBJetsToLL_M-50_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 3\nST_t-channel_top_4f_InclusiveDecays_TuneCP5_13TeV-powheg-madspin-pythia8: 6\nDYJetsToLL_BGenFilter_Zpt-100to200_M-50_TuneCP5_13TeV-madgraphMLM-pythia8: 55\nQCD_HT1000to1500_TuneCP5_13TeV-madgraphMLM-pythia8: 6\n\n# V11\n#[Hadd]\n#DYBJetsToLL_M-50_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 10\n#WplusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8: 2\n#DYJetsToLL_M-50_HT-600to800_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 1\n#WJetsToLNu_BGenFilter_Wpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 1\n#WminusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8: 2\n#ST_s-channel_4f_leptonDecays_TuneCP5_13TeV-madgraph-pythia8: 1\n#ZJetsToNuNu_HT-800To1200_13TeV-madgraph: 1\n#QCD_HT500to700_TuneCP5_13TeV-madgraphMLM-pythia8: 48\n#ggZH_HToBB_ZToLL_M125_13TeV_powheg_pythia8: 2\n#QCD_HT300to500_TuneCP5_13TeV-madgraphMLM-pythia8: 297\n#WJetsToLNu_HT-1200To2500_TuneCP5_13TeV-madgraphMLM-pythia8: 1\n#WBJetsToLNu_Wpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\n#DYJetsToLL_M-4to50_HT-400to600_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 121\n#DYJetsToLL_M-50_HT-2500toInf_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 1\n#DYJetsToLL_M-4to50_HT-600toInf_TuneCP5_PSWeights_13TeV-madgraphMLM-pythia8: 64\n#DYJetsToLL_M-50_HT-200to400_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 2\n#ST_tW_antitop_5f_inclusiveDecays_TuneCP5_13TeV-powheg-pythia8: 1\n#DYJetsToLL_M-50_HT-400to600_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 1\n#DYJetsToLL_M-4to50_HT-100to200_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 1499\n#ZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8: 2\n#TTToHadronic_TuneCP5_13TeV-powheg-pythia8: 69\n#WJetsToLNu_HT-200To400_TuneCP5_13TeV-madgraphMLM-pythia8: 2\n#ZJetsToNuNu_BGenFilter_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\n#QCD_HT2000toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\n#ZJetsToNuNu_BGenFilter_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 18\n#ZJetsToNuNu_HT-2500ToInf_13TeV-madgraph: 1\n#ZJetsToNuNu_HT-200To400_13TeV-madgraph: 1\n#WZ_TuneCP5_13TeV-pythia8: 37\n#ZZTo2L2Q_13TeV_amcatnloFXFX_madspin_pythia8: 8\n#DYJetsToLL_M-50_HT-1200to2500_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 1\n#WW_TuneCP5_13TeV-pythia8: 15\n#TTToSemiLeptonic_TuneCP5_13TeV-powheg-pythia8: 1\n#ZZ_TuneCP5_13TeV-pythia8: 6\n#QCD_HT1500to2000_TuneCP5_13TeV-madgraphMLM-pythia8: 1\n#WJetsToLNu_HT-400To600_TuneCP5_13TeV-madgraphMLM-pythia8: 1\n#DYJetsToLL_M-50_HT-100to200_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 5\n#ZJetsToNuNu_HT-1200To2500_13TeV-madgraph: 1\n#SingleMuon: 4\n#WBJetsToLNu_Wpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 1\n#DYJetsToLL_M-50_HT-800to1200_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 1\n#DYJetsToLL_BGenFilter_Zpt-200toInf_M-50_TuneCP5_13TeV-madgraphMLM-pythia8: 3\n#QCD_HT100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 72000\n#ZJetsToNuNu_HT-100To200_13TeV-madgraph: 2\n#QCD_HT700to1000_TuneCP5_13TeV-madgraphMLM-pythia8: 4\n#WJetsToLNu_HT-800To1200_TuneCP5_13TeV-madgraphMLM-pythia8: 1\n#EGamma: 5\n#TTTo2L2Nu_TuneCP5_13TeV-powheg-pythia8: 1\n#QCD_HT200to300_TuneCP5_13TeV-madgraphMLM-pythia8: 9143\n#ZH_HToBB_ZToLL_M125_13TeV_powheg_pythia8: 5\n#DYJetsToLL_M-4to50_HT-200to400_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 348\n#ZBJetsToNuNu_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\n#ZJetsToNuNu_HT-400To600_13TeV-madgraph: 1\n#ST_tW_top_5f_inclusiveDecays_TuneCP5_13TeV-powheg-pythia8: 13\n#DYJetsToLL_M-50_TuneCP5_13TeV-madgraphMLM-pythia8: 16\n#WWTo1L1Nu2Q_13TeV_amcatnloFXFX_madspin_pythia8: 1\n#WJetsToLNu_HT-2500ToInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\n#WJetsToLNu_TuneCP5_13TeV-madgraphMLM-pythia8: 8\n#WJetsToLNu_HT-600To800_TuneCP5_13TeV-madgraphMLM-pythia8: 1\n#ZJetsToNuNu_HT-600To800_13TeV-madgraph: 1\n#ST_t-channel_antitop_4f_InclusiveDecays_TuneCP5_13TeV-powheg-madspin-pythia8: 2\n#WJetsToLNu_HT-100To200_TuneCP5_13TeV-madgraphMLM-pythia8: 6\n#MET: 1\n#WJetsToLNu_BGenFilter_Wpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\n#ZBJetsToNuNu_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 2\n#ggZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8: 1\n#DYBJetsToLL_M-50_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 3\n#ST_t-channel_top_4f_InclusiveDecays_TuneCP5_13TeV-powheg-madspin-pythia8: 1\n#DYJetsToLL_BGenFilter_Zpt-100to200_M-50_TuneCP5_13TeV-madgraphMLM-pythia8: 7\n#QCD_HT1000to1500_TuneCP5_13TeV-madgraphMLM-pythia8: 1\n" }, { "alpha_fraction": 0.6739954352378845, "alphanum_fraction": 0.8430629372596741, "avg_line_length": 56.34782791137695, "blob_id": "42c063caba3ab6eab79fe27ed180eacbc008e568", "content_id": "6a0c44bf2622d79bffff1b3671d91fe9e7b4d1ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 3957, "license_type": "no_license", "max_line_length": 80, "num_lines": 69, "path": "/python/Zvv2018config/hadd.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "[Hadd]\nDYBJetsToLL_M-50_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 58\nDYJetsToLL_M-50_HT-600to800_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 4\nWplusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8: 3\nWJetsToLNu_TuneCP5_13TeV-madgraphMLM-pythia8: 62\nWJetsToLNu_BGenFilter_Wpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 3\nWminusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8: 3\nST_s-channel_4f_leptonDecays_TuneCP5_13TeV-madgraph-pythia8: 8\nZJetsToNuNu_HT-800To1200_13TeV-madgraph: 1\nQCD_HT500to700_TuneCP5_13TeV-madgraphMLM-pythia8: 137\nggZH_HToBB_ZToLL_M125_13TeV_powheg_pythia8: 14\nQCD_HT300to500_TuneCP5_13TeV-madgraphMLM-pythia8: 4983\nWZTo1L1Nu2Q_13TeV_amcatnloFXFX_madspin_pythia8: 3\nWJetsToLNu_HT-1200To2500_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nWBJetsToLNu_Wpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYJetsToLL_M-4to50_HT-400to600_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 11\nDYJetsToLL_M-50_HT-2500toInf_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 2\nDYJetsToLL_M-4to50_HT-600toInf_TuneCP5_PSWeights_13TeV-madgraphMLM-pythia8: 7\nDYJetsToLL_M-50_HT-200to400_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 27\nST_tW_antitop_5f_inclusiveDecays_TuneCP5_13TeV-powheg-pythia8: 3\nDYJetsToLL_M-50_HT-400to600_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 7\nDYJetsToLL_M-4to50_HT-100to200_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 3451\nZZTo2Q2Nu_TuneCP5_13TeV_amcatnloFXFX_madspin_pythia8: 1\nTTToHadronic_TuneCP5_13TeV-powheg-pythia8: 55\nWJetsToLNu_HT-200To400_TuneCP5_13TeV-madgraphMLM-pythia8: 2\nZJetsToNuNu_BGenFilter_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nQCD_HT2000toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 2\nZJetsToNuNu_BGenFilter_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 2\nZJetsToNuNu_HT-2500ToInf_13TeV-madgraph: 1\nZJetsToNuNu_HT-200To400_13TeV-madgraph: 1\nZZTo2L2Q_13TeV_amcatnloFXFX_madspin_pythia8: 71\nDYJetsToLL_M-50_HT-1200to2500_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 3\nTTToSemiLeptonic_TuneCP5_13TeV-powheg-pythia8: 3\nQCD_HT1500to2000_TuneCP5_13TeV-madgraphMLM-pythia8: 2\nWJetsToLNu_HT-400To600_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYJetsToLL_M-50_HT-100to200_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 1057\nZJetsToNuNu_HT-1200To2500_13TeV-madgraph: 1\nSingleMuon: 9999\nWBJetsToLNu_Wpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 2\nDYJetsToLL_M-50_HT-800to1200_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 3\nDYJetsToLL_BGenFilter_Zpt-200toInf_M-50_TuneCP5_13TeV-madgraphMLM-pythia8: 3\nQCD_HT100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 9999\nZJetsToNuNu_HT-100To200_13TeV-madgraph: 11\nQCD_HT700to1000_TuneCP5_13TeV-madgraphMLM-pythia8: 21\nWJetsToLNu_HT-800To1200_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nEGamma: 10\nTTTo2L2Nu_TuneCP5_13TeV-powheg-pythia8: 7\nQCD_HT200to300_TuneCP5_13TeV-madgraphMLM-pythia8: 197334\nZH_HToBB_ZToLL_M125_13TeV_powheg_pythia8: 34\nDYJetsToLL_M-4to50_HT-200to400_TuneCP5_PSweights_13TeV-madgraphMLM-pythia8: 44\nZBJetsToNuNu_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZJetsToNuNu_HT-400To600_13TeV-madgraph: 1\nST_tW_top_5f_inclusiveDecays_TuneCP5_13TeV-powheg-pythia8: 8\nDYJetsToLL_M-50_TuneCP5_13TeV-madgraphMLM-pythia8: 191\nWWTo1L1Nu2Q_13TeV_amcatnloFXFX_madspin_pythia8: 6\nWJetsToLNu_HT-2500ToInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8: 1\nWJetsToLNu_HT-600To800_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZJetsToNuNu_HT-600To800_13TeV-madgraph: 1\nST_t-channel_antitop_4f_InclusiveDecays_TuneCP5_13TeV-powheg-madspin-pythia8: 9\nWJetsToLNu_HT-100To200_TuneCP5_13TeV-madgraphMLM-pythia8: 43\nMET: 1\nWJetsToLNu_BGenFilter_Wpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZBJetsToNuNu_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nggZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8: 1\nDYBJetsToLL_M-50_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 3\nST_t-channel_top_4f_InclusiveDecays_TuneCP5_13TeV-powheg-madspin-pythia8: 6\nDYJetsToLL_BGenFilter_Zpt-100to200_M-50_TuneCP5_13TeV-madgraphMLM-pythia8: 55\nQCD_HT1000to1500_TuneCP5_13TeV-madgraphMLM-pythia8: 6\n" }, { "alpha_fraction": 0.6500672698020935, "alphanum_fraction": 0.6810228824615479, "avg_line_length": 33.29230880737305, "blob_id": "03edf55a63078acba1b77e7dfc3b4bdb01af1f80", "content_id": "ca2e9fc20f06bfa2681aaa7b0b67d24a5ac77216", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 2229, "license_type": "no_license", "max_line_length": 333, "num_lines": 65, "path": "/python/Wlv2016config/paths.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "[Configuration]\n#!! List of the config you want to use\n#!! The list only support spaces between configs\nList = paths.ini ../VHbb2016commonconfig/general.ini general.ini cuts.ini training.ini datacards.ini ../VHbb2016commonconfig/systematics.ini plots.ini lhe_weights.ini ../VHbb2016commonconfig/samples_mc.ini ../VHbb2016commonconfig/stxs.ini hadd.ini data.ini fit.ini ../VHbb2016commonconfig/vhbbPlotDef.ini vhbbPlotDef.ini volatile.ini\n\n# general config\n#whereToLaunch = PSI\nwhereToLaunch = auto\nuser = %(USER)s\ncmsswbase = %(CMSSW_BASE)s\n\n# Xrootd config, first redirector is the primary one if multiple ones are given\nxrootdRedirectors = eoscms.cern.ch\nxrootdRedirectorGlobal = root://t3dcachedb.psi.ch:1094//pnfs/psi.ch/cms/trivcat/\npnfsStoragePath = .\n\n# datasets\ndatasets = <!Configuration|cmsswbase!>/src/Xbb/samples/VHbbPostNano2016_V11.txt\ndasQuery = dasgoclient -query=\"file dataset={dataset} instance=prod/phys03\"\n\n[Directories]\nDname = logs_Wlv2016 \ntagDir = <!Directories|vhbbpath!>/python/<!Directories|Dname!>/\nscratch = scratch\nWdir = <!Configuration|cmsswbase!>/src/\nsamplepath = <!Directories|plottingSamples!>\n\nsamplefiles = <!Configuration|cmsswbase!>/src/Xbb/samples/VHbbPostNano2016_V11/\nsamplefiles_split = <!Configuration|cmsswbase!>/src/Xbb/samples/VHbbPostNano2016_V11/\n\n;!! The directory with the code\nvhbbpath= <!Directories|Wdir!>/Xbb\n\n;#!! cached files\ntmpSamples = /data/t3home000/dabercro/Xbb/Wlv2016_tmp\n\n;!! from which samples to plot and where to save the plots\n;plottingSamples = <!Directories|TOPout!>\nplottingSamples = <!Directories|CONDORout!>\n\n#!! from which samples to make the DCs and where to save the DCs\ndcSamples = <!Directories|MVAout!>\n\n# --------------------------------------------------------------------------------\n# PATHS\n# --------------------------------------------------------------------------------\n\ndcSamples = <!Directories|CONDORout!>\n\nPREPin = root://eoscms.cern.ch/\nPREPout = prep\n#prep_17jan20\n\nHADDin = <!Directories|PREPout!> \nHADDout = prep\n#17jan20\n\nSYSin = prep\nSYSout = sys\n\nMVAin = sys\nMVAout = mva\n\nCONDORin = sys\nCONDORout = /mnt/hadoop/scratch/dabercro/Xbb/Wlv2016\n" }, { "alpha_fraction": 0.55783611536026, "alphanum_fraction": 0.5842251777648926, "avg_line_length": 51.4538459777832, "blob_id": "b00746a34ffc003d7948e2a70de3ce69a91ee80e", "content_id": "fbc6a0c3c139757454ab103425c6694b4bb57b2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6821, "license_type": "no_license", "max_line_length": 177, "num_lines": 130, "path": "/python/myutils/JetSmearer.py", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nfrom __future__ import print_function\nimport ROOT\nfrom BranchTools import Collection\nfrom BranchTools import AddCollectionsModule\nimport array\nimport os\nimport math\nimport numpy as np\n\n# applies the smearing to MC jet resolution and modifies the Jet_PtReg* branches of the tree\nclass JetSmearer(AddCollectionsModule):\n\n def __init__(self, year, unsmearPreviousCorrection=True, backupPreviousCorrection=True):\n super(JetSmearer, self).__init__()\n self.debug = 'XBBDEBUG' in os.environ\n self.unsmearPreviousCorrection = unsmearPreviousCorrection\n self.backupPreviousCorrection = backupPreviousCorrection\n self.quickloadWarningShown = False\n\n self.year = year if type(year) == str else str(year)\n self.smear_params = {\n #'2016': [1.0, 0.0, 0.0, 0.0],\n '2017': [1.0029846959, 0.0212893588055, 0.030684, 0.052497],\n '2018': [0.98667384694, 0.0197153848807, 0.038481, 0.053924],\n }\n if self.year not in self.smear_params:\n print(\"ERROR: smearing for year\", self.year, \" not available!\")\n raise Exception(\"SmearingError\")\n\n self.scale, self.scale_err, self.smear, self.smear_err = self.smear_params[self.year]\n\n def customInit(self, initVars):\n self.sampleTree = initVars['sampleTree']\n self.isData = initVars['sample'].isData()\n self.sample = initVars['sample']\n\n if self.sample.isMC():\n # resolutions used in post-processor smearing\n self.unsmearResNom = 1.1\n self.unsmearResUp = 1.2\n self.unsmearResDown = 1.0\n\n self.maxNjet = 256\n self.PtReg = array.array('f', [0.0]*self.maxNjet)\n self.PtRegUp = array.array('f', [0.0]*self.maxNjet)\n self.PtRegDown = array.array('f', [0.0]*self.maxNjet)\n self.sampleTree.tree.SetBranchAddress(\"Jet_PtReg\", self.PtReg)\n self.sampleTree.tree.SetBranchAddress(\"Jet_PtRegUp\", self.PtRegUp)\n self.sampleTree.tree.SetBranchAddress(\"Jet_PtRegDown\", self.PtRegDown)\n\n if self.backupPreviousCorrection:\n self.addVectorBranch(\"Jet_PtRegOld\", default=0.0, branchType='f', length=self.maxNjet, leaflist=\"Jet_PtRegOld[nJet]/F\")\n self.addVectorBranch(\"Jet_PtRegOldUp\", default=0.0, branchType='f', length=self.maxNjet, leaflist=\"Jet_PtRegOldUp[nJet]/F\")\n self.addVectorBranch(\"Jet_PtRegOldDown\", default=0.0, branchType='f', length=self.maxNjet, leaflist=\"Jet_PtRegOldDown[nJet]/F\")\n\n def processEvent(self, tree):\n if not self.hasBeenProcessed(tree) and self.sample.isMC():\n self.markProcessed(tree)\n \n nJet = tree.nJet\n\n # backup the Jet_PtReg branches with the old smearing\n if self.backupPreviousCorrection:\n for i in range(nJet):\n self._b(\"Jet_PtRegOld\")[i] = self.PtReg[i]\n self._b(\"Jet_PtRegOldUp\")[i] = self.PtRegUp[i]\n self._b(\"Jet_PtRegOldDown\")[i] = self.PtRegDown[i]\n\n # original post-procesor smearing which is undone:\n # if isMC:\n # # until we have final post-regression smearing factors we assume a flat 10%\n # if sysVar==0: # nominal\n # resSmear = 1.1\n # elif sysVar==1: # up\n # resSmear = 1.2\n # elif sysVar==-1: # down\n # resSmear = 1.0\n # smearedPt = jet.pt*jet.bRegCorr \n # if jet.genJetIdx >=0 and jet.genJetIdx < len(self.genJetsWithNeutrinos) :\n # genJet=self.genJetsWithNeutrinos[jet.genJetIdx]\n # dPt = smearedPt - genJet.Pt()\n # smearedPt=genJet.Pt()+resSmear*dPt\n # return smearedPt\n\n # undo old smearing\n if self.unsmearPreviousCorrection:\n for i in range(nJet):\n genJetIdx = tree.Jet_genJetIdx[i]\n if genJetIdx > -1 and genJetIdx < len(tree.GenJetWithNeutrinos_pt):\n genJetPt = tree.GenJetWithNeutrinos_pt[genJetIdx]\n\n self.PtReg[i] = genJetPt + (self.PtReg[i] - genJetPt)/self.unsmearResNom\n self.PtRegUp[i] = genJetPt + (self.PtRegUp[i] - genJetPt)/self.unsmearResUp \n self.PtRegDown[i] = genJetPt + (self.PtRegDown[i] - genJetPt)/self.unsmearResDown\n\n # after undoing the smearing, check if up/down variations are the same\n assert (max(abs(self.PtReg[i]-self.PtRegUp[i]),abs(self.PtRegUp[i]-self.PtRegDown[i])) < 0.001 or self.PtReg[i] < 0)\n\n # apply new smearing\n for i in range(nJet):\n genJetIdx = tree.Jet_genJetIdx[i]\n if genJetIdx > -1 and genJetIdx < len(tree.GenJetWithNeutrinos_pt):\n gen_pt = tree.GenJetWithNeutrinos_pt[genJetIdx]\n\n # reference: https://github.com/dabercro/hbb/blob/b86589128a6839a12efaf041f579fe88c1d1be38/nanoslimmer/applysmearing/applysmearing.py\n regressed = self.PtReg[i]\n no_smear = regressed * self.scale\n gen_diff = regressed - gen_pt\n nominal = max(0.0, (gen_pt + gen_diff * (1.0 + self.smear)) * self.scale)\n band = math.sqrt(pow(nominal/self.scale * self.scale_err, 2) + pow(gen_diff * self.scale * self.smear_err, 2))\n\n down, up = (max(nominal - band, no_smear), nominal + band) if regressed > gen_pt else (min(nominal + band, no_smear), nominal - band) \n\n self.PtReg[i] = nominal\n self.PtRegUp[i] = up\n self.PtRegDown[i] = down\n\n\n # formulas by default reload the branch content when evaluating the first instance of the object!\n # SetQuickLoad(1) turns off this behavior\n for formulaName, treeFormula in self.sampleTree.formulas.items():\n if 'Jet_PtReg' in formulaName:\n if not self.quickloadWarningShown:\n self.quickloadWarningShown = True\n print(\"INFO: SetQuickLoad(1) called for formula:\", formulaName)\n print(\"INFO: -> EvalInstance(0) on formulas will not re-load branches but will take values from memory, which might have been modified by this module.\") \n treeFormula.SetQuickLoad(1)\n # print(\"\\x1b[31mERROR: this module can't be used together with others which use formulas based on branches changed inside this module!\\x1b[0m\")\n # raise Exception(\"NotImplemented\")\n\n\n" }, { "alpha_fraction": 0.6148220300674438, "alphanum_fraction": 0.6187225580215454, "avg_line_length": 32.08064651489258, "blob_id": "35f573cb1a8f2bf729a606d16eee97f8ffa407dd", "content_id": "43accc9bff494cdb7fab69d869f4d7c21233f50e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4102, "license_type": "no_license", "max_line_length": 157, "num_lines": 124, "path": "/python/submitMIT.py", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\nimport os\nimport sys\nimport glob\n\nfrom optparse import OptionParser\n\nfrom myutils.BetterConfigParser import BetterConfigParser\nfrom myutils.FileList import FileList\nfrom myutils.FileLocator import FileLocator\nfrom myutils.copytreePSI import filelist\nfrom myutils.sample_parser import ParseInfo\n\n\ndef get_config(opts):\n # From submit.py\n\n pathconfig = BetterConfigParser()\n pathconfig.read('%sconfig/paths.ini' % opts.tag)\n\n try:\n _configs = [x for x in pathconfig.get('Configuration', 'List').split(\" \") if len(x.strip()) > 0]\n if 'volatile.ini' in _configs:\n _configs.remove('volatile.ini')\n configs = ['%sconfig/' % (opts.tag) + c for c in _configs]\n\n except Exception as e:\n print(\"\\x1b[31mERROR:\" + str(e) + \"\\x1b[0m\")\n print(\"\\x1b[31mERROR: configuration file not found. Check config-tag specified with -T and presence of '[Configuration] List' in .ini files.\\x1b[0m\")\n raise Exception(\"ConfigNotFound\")\n\n # read config\n config = BetterConfigParser()\n config.read(configs)\n\n return config\n\n\ndef add_to_config(condor_config, template, sample, config, locator):\n\n if os.environ.get('XBBDEBUG'):\n print('Adding %s:' % sample)\n\n sampledir = os.path.join(config.get('Directories', 'CONDORout'), sample)\n if not os.path.exists(sampledir):\n os.makedirs(sampledir)\n\n for part, infile in enumerate(filelist(config.get('Directories', 'samplefiles'), sample)):\n\n job = {\n 'log': '%s_part%s' % (sample, part),\n 'part': part,\n 'sample': sample,\n 'filelist': FileList.compress(infile),\n 'outfile': locator.getFilenameAfterPrep(infile)\n }\n\n output_file = os.path.join(sampledir, job['outfile'])\n\n if os.path.exists(output_file) and os.stat(output_file).st_size:\n continue\n\n condor_config.write(template.format(**job))\n\n\nif __name__ == '__main__':\n\n parser = OptionParser()\n\n parser.add_option('-T', '--tag', dest='tag', default='default',\n help='Tag to run the analysis with, example \\'8TeV\\' uses 8TeVconfig to run the analysis')\n parser.add_option('-S','--samples',dest='samples',default='*', help='samples you want to run on')\n parser.add_option('-o', '--output', dest='output', default='condor', help='output prefix')\n\n parser.add_option('-c', '--config', dest='config', default=None, help='Display a config value instead of making a submit file')\n\n (opts, args) = parser.parse_args(sys.argv)\n\n config = get_config(opts)\n\n if opts.config:\n print(config.get(*opts.config.split(':')))\n exit(0)\n\n filelocator = FileLocator(config)\n parseinfo = ParseInfo(samples_path=config.get('Directories', 'PREPin'), config=config)\n\n with open('batch/condor/mit_header.sub', 'r') as header_file:\n header = header_file.read()\n\n logdir = os.path.join('/home/dabercro/public_html/xbb', config.get('Directories', 'Dname'))\n\n if not os.path.exists(logdir):\n os.makedirs(logdir)\n\n with open('batch/condor/mit_template.sub', 'r') as template_file:\n template = template_file.read().format(\n logdir=logdir,\n tag=opts.tag,\n outdir=config.get('Directories', 'CONDORin'),\n condorout=config.get('Directories', 'CONDORout'),\n log='{log}', part='{part}', sample='{sample}',\n filelist='{filelist}', outfile='{outfile}'\n )\n\n with open('%s_%s.cfg' % (opts.output, opts.tag), 'w') as condor_config:\n\n condor_config.write(header)\n\n for sample_file in glob.iglob('%s/%s.txt' % (config.get('Directories', 'samplefiles'), opts.samples)):\n\n if sample_file.endswith('.root.txt'):\n continue\n\n sample = os.path.basename(sample_file).split('.')[0]\n\n samples = parseinfo.find(sample)\n\n if os.environ.get('XBBDEBUG'):\n print(samples)\n\n if len(samples) == 1:\n add_to_config(condor_config, template, sample, config, filelocator)\n" }, { "alpha_fraction": 0.6818464398384094, "alphanum_fraction": 0.7563177943229675, "avg_line_length": 86.34496307373047, "blob_id": "fd34d0b35877307dab50c979e211a5782a590515", "content_id": "ace62f7506b52594dda397ed210a29f837dddc7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 90142, "license_type": "no_license", "max_line_length": 367, "num_lines": 1032, "path": "/python/VHbb2017commonconfig/systematics.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "[VHbbCommon]\n\n# ----------------------------------------------------------------\n# common modules\n# ----------------------------------------------------------------\n\nClean = Drop.Drop(dropBranches=['HLT_*','TrigObj_*','nTrigObj','SubJet_*','nSubJet','Photon_*','nPhoton','Tau_*','nTau','nGenVisTau','GenVisTau_*'],keepBranches=['HLT_Ele23_Ele12_CaloIdL_TrackIdL_Iso*','HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ_Mass*','HLT_PFMET120_PFMHT120_IDTight','HLT_PFMET120_PFMHT120_IDTight_PFHT60','HLT_Ele32_WPTight_Gsf_L1DoubleEG','HLT_IsoMu27'])\n\nJetSmearer = JetSmearer.JetSmearer(year='2017')\nMETXY = METXY.METXY(year='2017')\n\n# this can be used to print the branch contents before and after a module which modifies a branch\nDebugBefore = TestTree.TestTree(checkpoint='before', branch='Jet_PtReg', branchIndex=0, formula='Jet_PtReg[0]')\nDebugAfter = TestTree.TestTree(checkpoint='after', branch='Jet_PtReg', branchIndex=0, formula='Jet_PtReg[0]')\n\n# gen level\ngenBstatus = BranchTools.TreeFormulas({'nGenStatus2bHad': {'formula': 'Sum$((int(abs(GenPart_pdgId)/100)==5||int(abs(GenPart_pdgId)/1000)==5)&&GenPart_status==2)', 'type': 'i'}})\nisSignal = PerSampleWeight.PerSampleWeight(branchName='isSignal',affectedSampleNames=['WminusH','WplusH','ggZH_Zll','ZH_Zll','ZH_Znunu','ggZH_Znunu'],weightAffected=1.0,weightUnaffected=0.0)\nisGGZH = PerSampleWeight.PerSampleWeight(branchName='isGGZH',affectedSampleNames=['ggZH_HToBB_ZToNuNu','ggZH_Znunu'],weightAffected=1.0,weightUnaffected=0.0)\nisWH = PerSampleWeight.PerSampleWeight(branchName='isWH',affectedSampleNames=['WminusH','WplusH'],weightAffected=1.0,weightUnaffected=0.0)\nisZH = PerSampleWeight.PerSampleWeight(branchName='isWH',affectedSampleNames=['ZH_Zll','ggZH_Zll','ZH_Znunu','ggZH_Znunu'],weightAffected=1.0,weightUnaffected=0.0)\nisData = PerSampleWeight.PerSampleWeight(branchName='isData',affectedSampleNames=['SingleElectron','SingleMuon','DoubleMuon','DoubleEG','MET'],weightAffected=1.0,weightUnaffected=0.0)\n\n# sampleIndex and sampleGroup\nSampleGroup = SampleGroup.SampleGroup()\nSampleIndex = SampleGroup.SampleGroup(groupDict={})\nHeppyStyleGen = HeppyStyleGen.HeppyStyleGen()\nvLeptons = vLeptons.vLeptons()\nGenerator = ['VHbbCommon.HeppyStyleGen']\n\n# b-tag SF for DeepJet\nBTagSFDeepCSV = BTagWeightsFromCSV.BTagWeights(calibName='DeepCSV',calibFile='data/btag/DeepCSV_94XSF_V5_B_F.csv',method='iterativefit',jetBtagBranchName='Jet_btagDeepB',decorrelatePtEta=True)\nBTagSFDeepCSV_V2 = BTagWeightsFromCSV.BTagWeights(calibName='DeepCSV',calibFile='data/btag/DeepCSV_94XSF_V2_B_F.csv',branchName='bTagWeightDeepCSV_V2',method='iterativefit',jetBtagBranchName='Jet_btagDeepB',decorrelatePtEta=True)\nBtagSFDeepJet = BTagWeightsFromCSV.BTagWeights(calibName='DeepJet',calibFile='data/btag/DeepFlavour_94XSF_V2_B_F.csv',method='iterativefit',jetBtagBranchName='Jet_btagDeepFlavB',decorrelatePtEta=True) \n\n# double b-tag SF\nDoubleBtagSF = DoubleBTagWeightsFromCSV.DoubleBTagWeightsFromCSV(year=2017)\n\n# other sf\nTTweights = TTWeights.TTWeights(nano=True)\nEWKweights = EWKweights.EWKweights(nano=True)\n\n# linear pt correction\nFitCorr = addFitCorr.addFitCorr(nano=True)\nFitCorrV2 = addFitCorr.addFitCorr(branchName='FitCorrV2', nano=True, correctWjetsOnlyInOneLepton=True)\n\n# LO to NLO weight\nLOtoNLOweight = LOtoNLOweight.LOtoNLOweight(year=2017)\n\n# Higgs reco\nHiggsReco = HiggsCandidateSystematics.HiggsCandidateSystematics(addSystematics=True)\n\n# write stitching factors as branch\nDYspecialWeight = DYspecialWeight.DYspecialWeight()\n\n# Jet PU ID scale factors\nJetPUIDSF = JetPUIDSF.JetPUIDSF(year=2017,fName_sf=\"data/jetPUID/Oct2019/h2_eff_sf_2017_T.root\",hName_sf=\"h2_eff_sf2017_T\",fName_mcEff=\"data/jetPUID/Oct2019/h2_eff_mc_2017_T.root\",hName_mcEff=\"h2_eff_mc2017_T\")\nJetPUIDSF302p4 = JetPUIDSF.JetPUIDSF(year=2017,workingPoint='tight',ptCut=30.0,etaCut=2.4)\nJetPUIDSF302p5 = JetPUIDSF.JetPUIDSF(year=2017,workingPoint='tight',ptCut=30.0,etaCut=2.5)\nJetPUIDSFmedium = JetPUIDSF.JetPUIDSF(branchName='weightJetPUIDmedium',year=2017,workingPoint='medium')\n\nDropOldDNN = Drop.Drop(dropBranches=['BDT_DNN2017*'])\n\n# only for testing purpose\nBTagSFDeepCSV_noPU = BTagWeightsFromCSV.BTagWeights(branchName='bTagWeightDeepCSVnoPUid',calibName='DeepCSV',calibFile='data/btag/DeepCSV_94XSF_V4_B_F.csv',method='iterativefit',jetBtagBranchName='Jet_btagDeepB',decorrelatePtEta=True,puIdCut=-1)\nBTagSFDeepCSV_selected = BTagWeightsFromCSV.BTagWeights(branchName='bTagWeightDeepCSVselected',calibName='DeepCSV',calibFile='data/btag/DeepCSV_94XSF_V4_B_F.csv',method='iterativefit',jetBtagBranchName='Jet_btagDeepB',decorrelatePtEta=True,selected=True)\n\nVReco = VReco.VReco()\nVcut = Vcut.Vcut()\n\nisBoosted = isBoosted.isBoosted()\nisBoostedVZ = isBoosted.isBoosted(branchName='isBoosted_VZ',cutName='all_BOOST_VZ')\n\n# Pileup\n#data/pu/2017/pileup2017EF.root\npu2017B = PUweight.PUweight(fileNameData=\"data/pu/2017/pileup2017B.root\", fileNameMC=None, nano=True, puWeightName=\"puWeight_2017B\")\npu2017CD = PUweight.PUweight(fileNameData=\"data/pu/2017/pileup2017CD.root\", fileNameMC=None, nano=True, puWeightName=\"puWeight_2017CD\")\npu2017EF = PUweight.PUweight(fileNameData=\"data/pu/2017/pileup2017EF.root\", fileNameMC=None, nano=True, puWeightName=\"puWeight_2017EF\")\n\n\n# common systematics\nsystematicsnaming= {\n;stats\n 'stats':'CMS_vhbb_stats',\n; pT(W) correction\n 'FitCorrection': 'CMS_vhbb_ptwweights_wlf_13TeV',\n 'FitCorrectionHF': 'CMS_vhbb_ptwweights_whf_13TeV',\n; NLO reweighting\n 'CMS_vhbb_vjetnlodetajjrw_13TeV': 'CMS_vhbb_vjetnlodetajjrw_13TeV',\n;JER/JES sys\n 'PileUp':'CMS_vhbb_puWeight',\n 'sigEWK':'CMS_vhbb_signal_ewk_13TeV',\n 'CMS_LHE_weights_scale_muR_ZH':'CMS_LHE_weights_scale_muR_ZH',\n 'CMS_LHE_weights_scale_muR_ggZH':'CMS_LHE_weights_scale_muR_ggZH',\n 'CMS_LHE_weights_scale_muR_TT':'CMS_LHE_weights_scale_muR_TT',\n 'CMS_LHE_weights_scale_muR_Zj0b':'CMS_LHE_weights_scale_muR_Zj0b',\n 'CMS_LHE_weights_scale_muR_Zj1b':'CMS_LHE_weights_scale_muR_Zj1b',\n 'CMS_LHE_weights_scale_muR_Zj2b':'CMS_LHE_weights_scale_muR_Zj2b',\n 'CMS_LHE_weights_scale_muF_ZH':'CMS_LHE_weights_scale_muF_ZH',\n 'CMS_LHE_weights_scale_muF_ggZH':'CMS_LHE_weights_scale_muF_ggZH',\n 'CMS_LHE_weights_scale_muF_TT':'CMS_LHE_weights_scale_muF_TT',\n 'CMS_LHE_weights_scale_muF_Zj0b':'CMS_LHE_weights_scale_muF_Zj0b',\n 'CMS_LHE_weights_scale_muF_Zj1b':'CMS_LHE_weights_scale_muF_Zj1b',\n 'CMS_LHE_weights_scale_muF_Zj2b':'CMS_LHE_weights_scale_muF_Zj2b',\n; 1-lepton trigger/id\n 'CMS_vhbb_eff_m_trigger_Wlv_13TeV':'CMS_vhbb_eff_m_trigger_Wlv_13TeV',\n 'CMS_vhbb_eff_m_MVAID_Wlv_13TeV':'CMS_vhbb_eff_m_MVAID_Wlv_13TeV',\n 'CMS_vhbb_eff_m_ISO_Wlv_13TeV':'CMS_vhbb_eff_m_ISO_Wlv_13TeV',\n 'CMS_vhbb_eff_e_trigger_Wlv_13TeV':'CMS_vhbb_eff_e_trigger_Wlv_13TeV',\n 'CMS_vhbb_eff_e_MVAID_Wlv_13TeV':'CMS_vhbb_eff_e_MVAID_Wlv_13TeV',\n 'CMS_vhbb_eff_e_MVAID_Wlv_eta0_13TeV':'CMS_vhbb_eff_e_MVAID_Wlv_eta0_13TeV',\n 'CMS_vhbb_eff_e_MVAID_Wlv_eta1_13TeV':'CMS_vhbb_eff_e_MVAID_Wlv_eta1_13TeV',\n; 2-lepton trigger/id\n 'CMS_vhbb_eff_m_trigger_Zll_13TeV':'CMS_vhbb_eff_m_trigger_Zll_13TeV',\n 'CMS_vhbb_eff_m_MVAID_Zll_13TeV':'CMS_vhbb_eff_m_MVAID_Zll_13TeV',\n 'CMS_vhbb_eff_m_tracker_Zll_13TeV':'CMS_vhbb_eff_m_tracker_Zll_13TeV',\n 'CMS_vhbb_eff_m_ISO_Zll_13TeV':'CMS_vhbb_eff_m_ISO_Zll_13TeV',\n 'CMS_vhbb_eff_e_trigger_Zll_13TeV':'CMS_vhbb_eff_e_trigger_Zll_13TeV',\n 'CMS_vhbb_eff_e_MVAID_Zll_13TeV':'CMS_vhbb_eff_e_MVAID_Zll_13TeV',\n 'CMS_vhbb_eff_e_MVAID_Zll_eta0_13TeV':'CMS_vhbb_eff_e_MVAID_Zll_eta0_13TeV',\n 'CMS_vhbb_eff_e_MVAID_Zll_eta1_13TeV':'CMS_vhbb_eff_e_MVAID_Zll_eta1_13TeV',\n 'CMS_vhbb_eff_e_tracker_Zll_13TeV':'CMS_vhbb_eff_e_tracker_Zll_13TeV',\n 'weightF_sys':'UEPS',\n 'weightF_QCD':'CMS_vhbb_boost_QCD',\n 'model':'CMS_vhbb_Wj0bModel_ZnnHighPt_13TeV',\n; jet resoltion systematics \n \"jer\": \"CMS_res_j_13TeV\",\n; jet regression\n 'jerReg': 'CMS_res_j_reg_13TeV',\n; jet energy scale\n \"jesTotal\": \"CMS_jesAbsoluteStat\",\n \"jesAbsoluteStat\": \"CMS_scale_j_AbsoluteStat_13TeV\",\n \"jesAbsoluteScale\": \"CMS_scale_j_AbsoluteScale_13TeV\",\n \"jesAbsoluteFlavMap\": \"CMS_scale_j_AbsoluteFlavMap_13TeV\",\n \"jesAbsoluteMPFBias\": \"CMS_scale_j_AbsoluteMPFBias_13TeV\",\n \"jesFragmentation\": \"CMS_scale_j_Fragmentation_13TeV\",\n \"jesSinglePionECAL\": \"CMS_scale_j_SinglePionECAL_13TeV\",\n \"jesSinglePionHCAL\": \"CMS_scale_j_SinglePionHCAL_13TeV\",\n \"jesFlavorQCD\": \"CMS_scale_j_FlavorQCD_13TeV\",\n \"jesRelativeJEREC1\": \"CMS_scale_j_RelativeJEREC1_13TeV\",\n \"jesRelativeJEREC2\": \"CMS_scale_j_RelativeJEREC2_13TeV\",\n \"jesRelativeJERHF\": \"CMS_scale_j_RelativeJERHF_13TeV\",\n \"jesRelativePtBB\": \"CMS_scale_j_RelativePtBB_13TeV\",\n \"jesRelativePtEC1\": \"CMS_scale_j_RelativePtEC1_13TeV\",\n \"jesRelativePtEC2\": \"CMS_scale_j_RelativePtEC2_13TeV\",\n \"jesRelativePtHF\": \"CMS_scale_j_RelativePtHF_13TeV\",\n \"jesRelativeBal\": \"CMS_scale_j_RelativeBal_13TeV\",\n \"jesRelativeFSR\": \"CMS_scale_j_RelativeFSR_13TeV\",\n \"jesRelativeStatFSR\": \"CMS_scale_j_RelativeStatFSR_13TeV\",\n \"jesRelativeStatEC\": \"CMS_scale_j_RelativeStatEC_13TeV\",\n \"jesRelativeStatHF\": \"CMS_scale_j_RelativeStatHF_13TeV\",\n \"jesPileUpDataMC\": \"CMS_scale_j_PileUpDataMC_13TeV\",\n \"jesPileUpPtRef\": \"CMS_scale_j_PileUpPtRef_13TeV\",\n \"jesPileUpPtBB\": \"CMS_scale_j_PileUpPtBB_13TeV\",\n \"jesPileUpPtEC1\": \"CMS_scale_j_PileUpPtEC1_13TeV\",\n \"jesPileUpPtEC2\": \"CMS_scale_j_PileUpPtEC2_13TeV\",\n \"jesPileUpPtHF\": \"CMS_scale_j_PileUpPtHF_13TeV\",\n \"jesPileUpMuZero\": \"CMS_scale_j_PileUpMuZero_13TeV\",\n \"jesPileUpEnvelope\": \"CMS_scale_j_PileUpEnvelope_13TeV\",\n; unclustered energy\n \"unclustEn\": \"CMS_scale_met_unclustered_13TeV\",\n; DeepCSV\n \"CMS_bTagWeightDeepBJES_13TeV_pt0_eta0\": \"CMS_bTagWeightDeepBJES_13TeV_2017_pt0_eta0\",\n \"CMS_bTagWeightDeepBJES_13TeV_pt0_eta1\": \"CMS_bTagWeightDeepBJES_13TeV_2017_pt0_eta1\",\n \"CMS_bTagWeightDeepBJES_13TeV_pt0_eta2\": \"CMS_bTagWeightDeepBJES_13TeV_2017_pt0_eta2\",\n \"CMS_bTagWeightDeepBJES_13TeV_pt1_eta0\": \"CMS_bTagWeightDeepBJES_13TeV_2017_pt1_eta0\",\n \"CMS_bTagWeightDeepBJES_13TeV_pt1_eta1\": \"CMS_bTagWeightDeepBJES_13TeV_2017_pt1_eta1\",\n \"CMS_bTagWeightDeepBJES_13TeV_pt1_eta2\": \"CMS_bTagWeightDeepBJES_13TeV_2017_pt1_eta2\",\n \"CMS_bTagWeightDeepBJES_13TeV_pt2_eta0\": \"CMS_bTagWeightDeepBJES_13TeV_2017_pt2_eta0\",\n \"CMS_bTagWeightDeepBJES_13TeV_pt2_eta1\": \"CMS_bTagWeightDeepBJES_13TeV_2017_pt2_eta1\",\n \"CMS_bTagWeightDeepBJES_13TeV_pt2_eta2\": \"CMS_bTagWeightDeepBJES_13TeV_2017_pt2_eta2\",\n \"CMS_bTagWeightDeepBJES_13TeV_pt3_eta0\": \"CMS_bTagWeightDeepBJES_13TeV_2017_pt3_eta0\",\n \"CMS_bTagWeightDeepBJES_13TeV_pt3_eta1\": \"CMS_bTagWeightDeepBJES_13TeV_2017_pt3_eta1\",\n \"CMS_bTagWeightDeepBJES_13TeV_pt3_eta2\": \"CMS_bTagWeightDeepBJES_13TeV_2017_pt3_eta2\",\n \"CMS_bTagWeightDeepBJES_13TeV_pt4_eta0\": \"CMS_bTagWeightDeepBJES_13TeV_2017_pt4_eta0\",\n \"CMS_bTagWeightDeepBJES_13TeV_pt4_eta1\": \"CMS_bTagWeightDeepBJES_13TeV_2017_pt4_eta1\",\n \"CMS_bTagWeightDeepBJES_13TeV_pt4_eta2\": \"CMS_bTagWeightDeepBJES_13TeV_2017_pt4_eta2\",\n \"CMS_bTagWeightDeepBLF_13TeV_pt0_eta0\": \"CMS_bTagWeightDeepBLF_13TeV_2017_pt0_eta0\",\n \"CMS_bTagWeightDeepBLF_13TeV_pt0_eta1\": \"CMS_bTagWeightDeepBLF_13TeV_2017_pt0_eta1\",\n \"CMS_bTagWeightDeepBLF_13TeV_pt0_eta2\": \"CMS_bTagWeightDeepBLF_13TeV_2017_pt0_eta2\",\n \"CMS_bTagWeightDeepBLF_13TeV_pt1_eta0\": \"CMS_bTagWeightDeepBLF_13TeV_2017_pt1_eta0\",\n \"CMS_bTagWeightDeepBLF_13TeV_pt1_eta1\": \"CMS_bTagWeightDeepBLF_13TeV_2017_pt1_eta1\",\n \"CMS_bTagWeightDeepBLF_13TeV_pt1_eta2\": \"CMS_bTagWeightDeepBLF_13TeV_2017_pt1_eta2\",\n \"CMS_bTagWeightDeepBLF_13TeV_pt2_eta0\": \"CMS_bTagWeightDeepBLF_13TeV_2017_pt2_eta0\",\n \"CMS_bTagWeightDeepBLF_13TeV_pt2_eta1\": \"CMS_bTagWeightDeepBLF_13TeV_2017_pt2_eta1\",\n \"CMS_bTagWeightDeepBLF_13TeV_pt2_eta2\": \"CMS_bTagWeightDeepBLF_13TeV_2017_pt2_eta2\",\n \"CMS_bTagWeightDeepBLF_13TeV_pt3_eta0\": \"CMS_bTagWeightDeepBLF_13TeV_2017_pt3_eta0\",\n \"CMS_bTagWeightDeepBLF_13TeV_pt3_eta1\": \"CMS_bTagWeightDeepBLF_13TeV_2017_pt3_eta1\",\n \"CMS_bTagWeightDeepBLF_13TeV_pt3_eta2\": \"CMS_bTagWeightDeepBLF_13TeV_2017_pt3_eta2\",\n \"CMS_bTagWeightDeepBLF_13TeV_pt4_eta0\": \"CMS_bTagWeightDeepBLF_13TeV_2017_pt4_eta0\",\n \"CMS_bTagWeightDeepBLF_13TeV_pt4_eta1\": \"CMS_bTagWeightDeepBLF_13TeV_2017_pt4_eta1\",\n \"CMS_bTagWeightDeepBLF_13TeV_pt4_eta2\": \"CMS_bTagWeightDeepBLF_13TeV_2017_pt4_eta2\",\n \"CMS_bTagWeightDeepBHF_13TeV_pt0_eta0\": \"CMS_bTagWeightDeepBHF_13TeV_2017_pt0_eta0\",\n \"CMS_bTagWeightDeepBHF_13TeV_pt0_eta1\": \"CMS_bTagWeightDeepBHF_13TeV_2017_pt0_eta1\",\n \"CMS_bTagWeightDeepBHF_13TeV_pt0_eta2\": \"CMS_bTagWeightDeepBHF_13TeV_2017_pt0_eta2\",\n \"CMS_bTagWeightDeepBHF_13TeV_pt1_eta0\": \"CMS_bTagWeightDeepBHF_13TeV_2017_pt1_eta0\",\n \"CMS_bTagWeightDeepBHF_13TeV_pt1_eta1\": \"CMS_bTagWeightDeepBHF_13TeV_2017_pt1_eta1\",\n \"CMS_bTagWeightDeepBHF_13TeV_pt1_eta2\": \"CMS_bTagWeightDeepBHF_13TeV_2017_pt1_eta2\",\n \"CMS_bTagWeightDeepBHF_13TeV_pt2_eta0\": \"CMS_bTagWeightDeepBHF_13TeV_2017_pt2_eta0\",\n \"CMS_bTagWeightDeepBHF_13TeV_pt2_eta1\": \"CMS_bTagWeightDeepBHF_13TeV_2017_pt2_eta1\",\n \"CMS_bTagWeightDeepBHF_13TeV_pt2_eta2\": \"CMS_bTagWeightDeepBHF_13TeV_2017_pt2_eta2\",\n \"CMS_bTagWeightDeepBHF_13TeV_pt3_eta0\": \"CMS_bTagWeightDeepBHF_13TeV_2017_pt3_eta0\",\n \"CMS_bTagWeightDeepBHF_13TeV_pt3_eta1\": \"CMS_bTagWeightDeepBHF_13TeV_2017_pt3_eta1\",\n \"CMS_bTagWeightDeepBHF_13TeV_pt3_eta2\": \"CMS_bTagWeightDeepBHF_13TeV_2017_pt3_eta2\",\n \"CMS_bTagWeightDeepBHF_13TeV_pt4_eta0\": \"CMS_bTagWeightDeepBHF_13TeV_2017_pt4_eta0\",\n \"CMS_bTagWeightDeepBHF_13TeV_pt4_eta1\": \"CMS_bTagWeightDeepBHF_13TeV_2017_pt4_eta1\",\n \"CMS_bTagWeightDeepBHF_13TeV_pt4_eta2\": \"CMS_bTagWeightDeepBHF_13TeV_2017_pt4_eta2\",\n \"CMS_bTagWeightDeepBLFStats1_13TeV_pt0_eta0\": \"CMS_bTagWeightDeepBLFStats1_13TeV_2017_pt0_eta0\",\n \"CMS_bTagWeightDeepBLFStats1_13TeV_pt0_eta1\": \"CMS_bTagWeightDeepBLFStats1_13TeV_2017_pt0_eta1\",\n \"CMS_bTagWeightDeepBLFStats1_13TeV_pt0_eta2\": \"CMS_bTagWeightDeepBLFStats1_13TeV_2017_pt0_eta2\",\n \"CMS_bTagWeightDeepBLFStats1_13TeV_pt1_eta0\": \"CMS_bTagWeightDeepBLFStats1_13TeV_2017_pt1_eta0\",\n \"CMS_bTagWeightDeepBLFStats1_13TeV_pt1_eta1\": \"CMS_bTagWeightDeepBLFStats1_13TeV_2017_pt1_eta1\",\n \"CMS_bTagWeightDeepBLFStats1_13TeV_pt1_eta2\": \"CMS_bTagWeightDeepBLFStats1_13TeV_2017_pt1_eta2\",\n \"CMS_bTagWeightDeepBLFStats1_13TeV_pt2_eta0\": \"CMS_bTagWeightDeepBLFStats1_13TeV_2017_pt2_eta0\",\n \"CMS_bTagWeightDeepBLFStats1_13TeV_pt2_eta1\": \"CMS_bTagWeightDeepBLFStats1_13TeV_2017_pt2_eta1\",\n \"CMS_bTagWeightDeepBLFStats1_13TeV_pt2_eta2\": \"CMS_bTagWeightDeepBLFStats1_13TeV_2017_pt2_eta2\",\n \"CMS_bTagWeightDeepBLFStats1_13TeV_pt3_eta0\": \"CMS_bTagWeightDeepBLFStats1_13TeV_2017_pt3_eta0\",\n \"CMS_bTagWeightDeepBLFStats1_13TeV_pt3_eta1\": \"CMS_bTagWeightDeepBLFStats1_13TeV_2017_pt3_eta1\",\n \"CMS_bTagWeightDeepBLFStats1_13TeV_pt3_eta2\": \"CMS_bTagWeightDeepBLFStats1_13TeV_2017_pt3_eta2\",\n \"CMS_bTagWeightDeepBLFStats1_13TeV_pt4_eta0\": \"CMS_bTagWeightDeepBLFStats1_13TeV_2017_pt4_eta0\",\n \"CMS_bTagWeightDeepBLFStats1_13TeV_pt4_eta1\": \"CMS_bTagWeightDeepBLFStats1_13TeV_2017_pt4_eta1\",\n \"CMS_bTagWeightDeepBLFStats1_13TeV_pt4_eta2\": \"CMS_bTagWeightDeepBLFStats1_13TeV_2017_pt4_eta2\",\n \"CMS_bTagWeightDeepBLFStats2_13TeV_pt0_eta0\": \"CMS_bTagWeightDeepBLFStats2_13TeV_2017_pt0_eta0\",\n \"CMS_bTagWeightDeepBLFStats2_13TeV_pt0_eta1\": \"CMS_bTagWeightDeepBLFStats2_13TeV_2017_pt0_eta1\",\n \"CMS_bTagWeightDeepBLFStats2_13TeV_pt0_eta2\": \"CMS_bTagWeightDeepBLFStats2_13TeV_2017_pt0_eta2\",\n \"CMS_bTagWeightDeepBLFStats2_13TeV_pt1_eta0\": \"CMS_bTagWeightDeepBLFStats2_13TeV_2017_pt1_eta0\",\n \"CMS_bTagWeightDeepBLFStats2_13TeV_pt1_eta1\": \"CMS_bTagWeightDeepBLFStats2_13TeV_2017_pt1_eta1\",\n \"CMS_bTagWeightDeepBLFStats2_13TeV_pt1_eta2\": \"CMS_bTagWeightDeepBLFStats2_13TeV_2017_pt1_eta2\",\n \"CMS_bTagWeightDeepBLFStats2_13TeV_pt2_eta0\": \"CMS_bTagWeightDeepBLFStats2_13TeV_2017_pt2_eta0\",\n \"CMS_bTagWeightDeepBLFStats2_13TeV_pt2_eta1\": \"CMS_bTagWeightDeepBLFStats2_13TeV_2017_pt2_eta1\",\n \"CMS_bTagWeightDeepBLFStats2_13TeV_pt2_eta2\": \"CMS_bTagWeightDeepBLFStats2_13TeV_2017_pt2_eta2\",\n \"CMS_bTagWeightDeepBLFStats2_13TeV_pt3_eta0\": \"CMS_bTagWeightDeepBLFStats2_13TeV_2017_pt3_eta0\",\n \"CMS_bTagWeightDeepBLFStats2_13TeV_pt3_eta1\": \"CMS_bTagWeightDeepBLFStats2_13TeV_2017_pt3_eta1\",\n \"CMS_bTagWeightDeepBLFStats2_13TeV_pt3_eta2\": \"CMS_bTagWeightDeepBLFStats2_13TeV_2017_pt3_eta2\",\n \"CMS_bTagWeightDeepBLFStats2_13TeV_pt4_eta0\": \"CMS_bTagWeightDeepBLFStats2_13TeV_2017_pt4_eta0\",\n \"CMS_bTagWeightDeepBLFStats2_13TeV_pt4_eta1\": \"CMS_bTagWeightDeepBLFStats2_13TeV_2017_pt4_eta1\",\n \"CMS_bTagWeightDeepBLFStats2_13TeV_pt4_eta2\": \"CMS_bTagWeightDeepBLFStats2_13TeV_2017_pt4_eta2\",\n \"CMS_bTagWeightDeepBHFStats1_13TeV_pt0_eta0\": \"CMS_bTagWeightDeepBHFStats1_13TeV_2017_pt0_eta0\",\n \"CMS_bTagWeightDeepBHFStats1_13TeV_pt0_eta1\": \"CMS_bTagWeightDeepBHFStats1_13TeV_2017_pt0_eta1\",\n \"CMS_bTagWeightDeepBHFStats1_13TeV_pt0_eta2\": \"CMS_bTagWeightDeepBHFStats1_13TeV_2017_pt0_eta2\",\n \"CMS_bTagWeightDeepBHFStats1_13TeV_pt1_eta0\": \"CMS_bTagWeightDeepBHFStats1_13TeV_2017_pt1_eta0\",\n \"CMS_bTagWeightDeepBHFStats1_13TeV_pt1_eta1\": \"CMS_bTagWeightDeepBHFStats1_13TeV_2017_pt1_eta1\",\n \"CMS_bTagWeightDeepBHFStats1_13TeV_pt1_eta2\": \"CMS_bTagWeightDeepBHFStats1_13TeV_2017_pt1_eta2\",\n \"CMS_bTagWeightDeepBHFStats1_13TeV_pt2_eta0\": \"CMS_bTagWeightDeepBHFStats1_13TeV_2017_pt2_eta0\",\n \"CMS_bTagWeightDeepBHFStats1_13TeV_pt2_eta1\": \"CMS_bTagWeightDeepBHFStats1_13TeV_2017_pt2_eta1\",\n \"CMS_bTagWeightDeepBHFStats1_13TeV_pt2_eta2\": \"CMS_bTagWeightDeepBHFStats1_13TeV_2017_pt2_eta2\",\n \"CMS_bTagWeightDeepBHFStats1_13TeV_pt3_eta0\": \"CMS_bTagWeightDeepBHFStats1_13TeV_2017_pt3_eta0\",\n \"CMS_bTagWeightDeepBHFStats1_13TeV_pt3_eta1\": \"CMS_bTagWeightDeepBHFStats1_13TeV_2017_pt3_eta1\",\n \"CMS_bTagWeightDeepBHFStats1_13TeV_pt3_eta2\": \"CMS_bTagWeightDeepBHFStats1_13TeV_2017_pt3_eta2\",\n \"CMS_bTagWeightDeepBHFStats1_13TeV_pt4_eta0\": \"CMS_bTagWeightDeepBHFStats1_13TeV_2017_pt4_eta0\",\n \"CMS_bTagWeightDeepBHFStats1_13TeV_pt4_eta1\": \"CMS_bTagWeightDeepBHFStats1_13TeV_2017_pt4_eta1\",\n \"CMS_bTagWeightDeepBHFStats1_13TeV_pt4_eta2\": \"CMS_bTagWeightDeepBHFStats1_13TeV_2017_pt4_eta2\",\n \"CMS_bTagWeightDeepBHFStats2_13TeV_pt0_eta0\": \"CMS_bTagWeightDeepBHFStats2_13TeV_2017_pt0_eta0\",\n \"CMS_bTagWeightDeepBHFStats2_13TeV_pt0_eta1\": \"CMS_bTagWeightDeepBHFStats2_13TeV_2017_pt0_eta1\",\n \"CMS_bTagWeightDeepBHFStats2_13TeV_pt0_eta2\": \"CMS_bTagWeightDeepBHFStats2_13TeV_2017_pt0_eta2\",\n \"CMS_bTagWeightDeepBHFStats2_13TeV_pt1_eta0\": \"CMS_bTagWeightDeepBHFStats2_13TeV_2017_pt1_eta0\",\n \"CMS_bTagWeightDeepBHFStats2_13TeV_pt1_eta1\": \"CMS_bTagWeightDeepBHFStats2_13TeV_2017_pt1_eta1\",\n \"CMS_bTagWeightDeepBHFStats2_13TeV_pt1_eta2\": \"CMS_bTagWeightDeepBHFStats2_13TeV_2017_pt1_eta2\",\n \"CMS_bTagWeightDeepBHFStats2_13TeV_pt2_eta0\": \"CMS_bTagWeightDeepBHFStats2_13TeV_2017_pt2_eta0\",\n \"CMS_bTagWeightDeepBHFStats2_13TeV_pt2_eta1\": \"CMS_bTagWeightDeepBHFStats2_13TeV_2017_pt2_eta1\",\n \"CMS_bTagWeightDeepBHFStats2_13TeV_pt2_eta2\": \"CMS_bTagWeightDeepBHFStats2_13TeV_2017_pt2_eta2\",\n \"CMS_bTagWeightDeepBHFStats2_13TeV_pt3_eta0\": \"CMS_bTagWeightDeepBHFStats2_13TeV_2017_pt3_eta0\",\n \"CMS_bTagWeightDeepBHFStats2_13TeV_pt3_eta1\": \"CMS_bTagWeightDeepBHFStats2_13TeV_2017_pt3_eta1\",\n \"CMS_bTagWeightDeepBHFStats2_13TeV_pt3_eta2\": \"CMS_bTagWeightDeepBHFStats2_13TeV_2017_pt3_eta2\",\n \"CMS_bTagWeightDeepBHFStats2_13TeV_pt4_eta0\": \"CMS_bTagWeightDeepBHFStats2_13TeV_2017_pt4_eta0\",\n \"CMS_bTagWeightDeepBHFStats2_13TeV_pt4_eta1\": \"CMS_bTagWeightDeepBHFStats2_13TeV_2017_pt4_eta1\",\n \"CMS_bTagWeightDeepBHFStats2_13TeV_pt4_eta2\": \"CMS_bTagWeightDeepBHFStats2_13TeV_2017_pt4_eta2\",\n \"CMS_bTagWeightDeepBcErr1_13TeV_pt0_eta0\": \"CMS_bTagWeightDeepBcErr1_13TeV_2017_pt0_eta0\",\n \"CMS_bTagWeightDeepBcErr1_13TeV_pt0_eta1\": \"CMS_bTagWeightDeepBcErr1_13TeV_2017_pt0_eta1\",\n \"CMS_bTagWeightDeepBcErr1_13TeV_pt0_eta2\": \"CMS_bTagWeightDeepBcErr1_13TeV_2017_pt0_eta2\",\n \"CMS_bTagWeightDeepBcErr1_13TeV_pt1_eta0\": \"CMS_bTagWeightDeepBcErr1_13TeV_2017_pt1_eta0\",\n \"CMS_bTagWeightDeepBcErr1_13TeV_pt1_eta1\": \"CMS_bTagWeightDeepBcErr1_13TeV_2017_pt1_eta1\",\n \"CMS_bTagWeightDeepBcErr1_13TeV_pt1_eta2\": \"CMS_bTagWeightDeepBcErr1_13TeV_2017_pt1_eta2\",\n \"CMS_bTagWeightDeepBcErr1_13TeV_pt2_eta0\": \"CMS_bTagWeightDeepBcErr1_13TeV_2017_pt2_eta0\",\n \"CMS_bTagWeightDeepBcErr1_13TeV_pt2_eta1\": \"CMS_bTagWeightDeepBcErr1_13TeV_2017_pt2_eta1\",\n \"CMS_bTagWeightDeepBcErr1_13TeV_pt2_eta2\": \"CMS_bTagWeightDeepBcErr1_13TeV_2017_pt2_eta2\",\n \"CMS_bTagWeightDeepBcErr1_13TeV_pt3_eta0\": \"CMS_bTagWeightDeepBcErr1_13TeV_2017_pt3_eta0\",\n \"CMS_bTagWeightDeepBcErr1_13TeV_pt3_eta1\": \"CMS_bTagWeightDeepBcErr1_13TeV_2017_pt3_eta1\",\n \"CMS_bTagWeightDeepBcErr1_13TeV_pt3_eta2\": \"CMS_bTagWeightDeepBcErr1_13TeV_2017_pt3_eta2\",\n \"CMS_bTagWeightDeepBcErr1_13TeV_pt4_eta0\": \"CMS_bTagWeightDeepBcErr1_13TeV_2017_pt4_eta0\",\n \"CMS_bTagWeightDeepBcErr1_13TeV_pt4_eta1\": \"CMS_bTagWeightDeepBcErr1_13TeV_2017_pt4_eta1\",\n \"CMS_bTagWeightDeepBcErr1_13TeV_pt4_eta2\": \"CMS_bTagWeightDeepBcErr1_13TeV_2017_pt4_eta2\",\n \"CMS_bTagWeightDeepBcErr2_13TeV_pt0_eta0\": \"CMS_bTagWeightDeepBcErr2_13TeV_2017_pt0_eta0\",\n \"CMS_bTagWeightDeepBcErr2_13TeV_pt0_eta1\": \"CMS_bTagWeightDeepBcErr2_13TeV_2017_pt0_eta1\",\n \"CMS_bTagWeightDeepBcErr2_13TeV_pt0_eta2\": \"CMS_bTagWeightDeepBcErr2_13TeV_2017_pt0_eta2\",\n \"CMS_bTagWeightDeepBcErr2_13TeV_pt1_eta0\": \"CMS_bTagWeightDeepBcErr2_13TeV_2017_pt1_eta0\",\n \"CMS_bTagWeightDeepBcErr2_13TeV_pt1_eta1\": \"CMS_bTagWeightDeepBcErr2_13TeV_2017_pt1_eta1\",\n \"CMS_bTagWeightDeepBcErr2_13TeV_pt1_eta2\": \"CMS_bTagWeightDeepBcErr2_13TeV_2017_pt1_eta2\",\n \"CMS_bTagWeightDeepBcErr2_13TeV_pt2_eta0\": \"CMS_bTagWeightDeepBcErr2_13TeV_2017_pt2_eta0\",\n \"CMS_bTagWeightDeepBcErr2_13TeV_pt2_eta1\": \"CMS_bTagWeightDeepBcErr2_13TeV_2017_pt2_eta1\",\n \"CMS_bTagWeightDeepBcErr2_13TeV_pt2_eta2\": \"CMS_bTagWeightDeepBcErr2_13TeV_2017_pt2_eta2\",\n \"CMS_bTagWeightDeepBcErr2_13TeV_pt3_eta0\": \"CMS_bTagWeightDeepBcErr2_13TeV_2017_pt3_eta0\",\n \"CMS_bTagWeightDeepBcErr2_13TeV_pt3_eta1\": \"CMS_bTagWeightDeepBcErr2_13TeV_2017_pt3_eta1\",\n \"CMS_bTagWeightDeepBcErr2_13TeV_pt3_eta2\": \"CMS_bTagWeightDeepBcErr2_13TeV_2017_pt3_eta2\",\n \"CMS_bTagWeightDeepBcErr2_13TeV_pt4_eta0\": \"CMS_bTagWeightDeepBcErr2_13TeV_2017_pt4_eta0\",\n \"CMS_bTagWeightDeepBcErr2_13TeV_pt4_eta1\": \"CMS_bTagWeightDeepBcErr2_13TeV_2017_pt4_eta1\",\n \"CMS_bTagWeightDeepBcErr2_13TeV_pt4_eta2\": \"CMS_bTagWeightDeepBcErr2_13TeV_2017_pt4_eta2\",\n; DeepAK8\n \"bTagWeightDoubleB_mp_pt200to300\": \"CMS_bTagWeightDoubleB_mp_pt200to300_2017\",\n \"bTagWeightDoubleB_mp_pt300to400\": \"CMS_bTagWeightDoubleB_mp_pt300to400_2017\",\n \"bTagWeightDoubleB_mp_pt400to500\": \"CMS_bTagWeightDoubleB_mp_pt400to500_2017\",\n \"bTagWeightDoubleB_mp_pt500to600\": \"CMS_bTagWeightDoubleB_mp_pt500to600_2017\",\n \"bTagWeightDoubleB_mp_pt600toInf\": \"CMS_bTagWeightDoubleB_mp_pt600toInf_2017\",\n \"bTagWeightDoubleB_hp_pt200to300\": \"CMS_bTagWeightDoubleB_hp_pt200to300_2017\",\n \"bTagWeightDoubleB_hp_pt300to400\": \"CMS_bTagWeightDoubleB_hp_pt300to400_2017\",\n \"bTagWeightDoubleB_hp_pt400to500\": \"CMS_bTagWeightDoubleB_hp_pt400to500_2017\",\n \"bTagWeightDoubleB_hp_pt500to600\": \"CMS_bTagWeightDoubleB_hp_pt500to600_2017\",\n \"bTagWeightDoubleB_hp_pt600toInf\": \"CMS_bTagWeightDoubleB_hp_pt600toInf_2017\",\n; fat jet softdrop mass\n \"jmr\": \"CMS_scale_j_jmr_13TeV\", \n \"jms\": \"CMS_scale_j_jms_13TeV\", \n }\n\n\nGroup = {\n;Data\n 'DoubleEG': 'DATA',\n 'DoubleMuon': 'DATA',\n 'SingleMuon': 'DATA',\n 'SingleElectron': 'DATA',\n 'MET': 'DATA',\n;Signal\n 'ZH_Zll':'ZH',\n 'ggZH_Zll':'ggZH',\n 'ZH_Znunu':'ZH',\n 'ggZH_Znunu':'ggZH',\n;Drell-Yan\n 'Z1Jets_Zm10to50_0b':'ZJets_0b','Z1Jets_Zm10to50_1b':'ZJets_1b','Z1Jets_Zm10to50_2b':'ZJets_2b',\\\n 'Z2Jets_Zm10to50_0b':'ZJets_0b','Z2Jets_Zm10to50_1b':'ZJets_1b','Z2Jets_Zm10to50_2b':'ZJets_2b',\\\n 'Z3Jets_Zm10to50_0b':'ZJets_0b','Z3Jets_Zm10to50_1b':'ZJets_1b','Z3Jets_Zm10to50_2b':'ZJets_2b',\\\n 'M4HT70to100_0b':'ZJets_0b','M4HT70to100_1b':'ZJets_1b','M4HT70to100_2b':'ZJets_2b',\\\n 'M4HT100to200_0b':'ZJets_0b','M4HT100to200_1b':'ZJets_1b','M4HT100to200_2b':'ZJets_2b',\\\n 'M4HT200to400_0b':'ZJets_0b','M4HT200to400_1b':'ZJets_1b','M4HT200to400_2b':'ZJets_2b',\\\n 'M4HT400to600_0b':'ZJets_0b','M4HT400to600_1b':'ZJets_1b','M4HT400to600_2b':'ZJets_2b',\\\n 'M4HT600toInf_0b':'ZJets_0b','M4HT600toInf_1b':'ZJets_1b','M4HT600toInf_2b':'ZJets_2b',\\\n 'M50BB_0b':'ZJets_0b','M50BB_1b':'ZJets_1b','M50BB_2b':'ZJets_2b',\\\n;Zm50toInf\n 'HT0to100ZJets_0b': 'ZJets_0b','HT0to100ZJets_1b':'ZJets_1b', 'HT0to100ZJets_2b':'ZJets_2b',\\\n 'HT70to100ZJets_0b':'ZJets_0b','HT70to100ZJets_1b':'ZJets_1b','HT70to100ZJets_2b':'ZJets_2b',\\\n 'HT100to200ZJets_0b':'ZJets_0b','HT100to200ZJets_1b':'ZJets_1b','HT100to200ZJets_2b':'ZJets_2b',\\\n 'HT200to400ZJets_0b':'ZJets_0b','HT200to400ZJets_1b':'ZJets_1b','HT200to400ZJets_2b':'ZJets_2b',\\\n 'HT400to600ZJets_0b':'ZJets_0b','HT400to600ZJets_1b':'ZJets_1b','HT400to600ZJets_2b':'ZJets_2b',\\\n 'HT600to800ZJets_0b':'ZJets_0b','HT600to800ZJets_1b':'ZJets_1b','HT600to800ZJets_2b':'ZJets_2b',\\\n 'HT800to1200ZJets_0b':'ZJets_0b','HT800to1200ZJets_1b':'ZJets_1b','HT800to1200ZJets_2b':'ZJets_2b',\\\n 'HT1200to2500ZJets_0b':'ZJets_0b','HT1200to2500ZJets_1b':'ZJets_1b','HT1200to2500ZJets_2b':'ZJets_2b',\\\n 'HT2500toinfZJets_0b':'ZJets_0b','HT2500toinfZJets_1b':'ZJets_1b','HT2500toinfZJets_2b':'ZJets_2b',\\\n;DYB\n 'ZJetsB_Zpt100to200_0b':'ZJets_0b','ZJetsB_Zpt100to200_1b':'ZJets_1b','ZJetsB_Zpt100to200_2b':'ZJets_2b',\\\n 'ZJetsB_Zpt200toInf_0b':'ZJets_0b','ZJetsB_Zpt200toInf_1b':'ZJets_1b','ZJetsB_Zpt200toInf_2b':'ZJets_2b',\\\n;DY B filter\n 'ZJetsGenB_Zpt100to200_0b':'ZJets_0b', 'ZJetsGenB_Zpt100to200_1b':'ZJets_1b', 'ZJetsGenB_Zpt100to200_2b':'ZJets_2b',\\\n 'ZJetsGenB_Zpt200toInf_0b':'ZJets_0b', 'ZJetsGenB_Zpt200toInf_1b':'ZJets_1b', 'ZJetsGenB_Zpt200toInf_2b':'ZJets_2b',\\\n;DYnlo\n 'DYnlo1J50_0b':'ZJets_0b', 'DYnlo1J50_1b':'ZJets_1b', 'DYnlo1J50_2b':'ZJets_2b',\\\n 'DYnlo1J150_0b':'ZJets_0b', 'DYnlo1J150_1b':'ZJets_1b', 'DYnlo1J150_2b':'ZJets_2b',\\\n 'DYnlo1J250_0b':'ZJets_0b', 'DYnlo1J250_1b':'ZJets_1b', 'DYnlo1J250_2b':'ZJets_2b',\\\n 'DYnlo1J400_0b':'ZJets_0b', 'DYnlo1J400_1b':'ZJets_1b', 'DYnlo1J400_2b':'ZJets_2b',\\\n 'DYnlo2J50_0b':'ZJets_0b', 'DYnlo2J50_1b':'ZJets_1b', 'DYnlo2J50_2b':'ZJets_2b',\\\n 'DYnlo2J150_0b':'ZJets_0b', 'DYnlo2J150_1b':'ZJets_1b', 'DYnlo2J150_2b':'ZJets_2b',\\\n 'DYnlo2J250_0b':'ZJets_0b', 'DYnlo2J250_1b':'ZJets_1b', 'DYnlo2J250_2b':'ZJets_2b',\\\n 'DYnlo2J400_0b':'ZJets_0b', 'DYnlo2J400_1b':'ZJets_1b', 'DYnlo2J400_2b':'ZJets_2b',\\\n 'DYnloIncl_0b':'ZJets_0b', 'DYnloIncl_1b':'ZJets_1b', 'DYnloIncl_2b':'ZJets_2b',\\\n;Z+Jets to NuNu\n 'ZJetsHT100_0b': 'ZJets_0b', 'ZJetsHT100_1b': 'ZJets_1b', 'ZJetsHT100_2b': 'ZJets_2b',\n 'ZJetsHT200_0b': 'ZJets_0b', 'ZJetsHT200_1b': 'ZJets_1b', 'ZJetsHT200_2b': 'ZJets_2b',\n 'ZJetsHT400_0b': 'ZJets_0b', 'ZJetsHT400_1b': 'ZJets_1b', 'ZJetsHT400_2b': 'ZJets_2b',\n 'ZJetsHT600_0b': 'ZJets_0b', 'ZJetsHT600_1b': 'ZJets_1b', 'ZJetsHT600_2b': 'ZJets_2b',\n 'ZJetsHT800_0b': 'ZJets_0b', 'ZJetsHT800_1b': 'ZJets_1b', 'ZJetsHT800_2b': 'ZJets_2b',\n 'ZJetsHT1200_0b': 'ZJets_0b', 'ZJetsHT1200_1b': 'ZJets_1b', 'ZJetsHT1200_2b': 'ZJets_2b',\n 'ZJetsHT2500_0b': 'ZJets_0b', 'ZJetsHT2500_1b': 'ZJets_1b', 'ZJetsHT2500_2b': 'ZJets_2b',\n 'ZBJets100_0b': 'ZJets_0b','ZBJets100_1b': 'ZJets_1b','ZBJets100_2b': 'ZJets_2b',\n 'ZBJets200_0b': 'ZJets_0b','ZBJets200_1b': 'ZJets_1b','ZBJets200_2b': 'ZJets_2b',\n 'ZBGenFilter100_0b': 'ZJets_0b','ZBGenFilter100_1b': 'ZJets_1b','ZBGenFilter100_2b': 'ZJets_2b',\n 'ZBGenFilter200_0b': 'ZJets_0b','ZBGenFilter200_1b': 'ZJets_1b','ZBGenFilter200_2b': 'ZJets_2b',\n;single-top\n 'ST_s':'ST','ST_tW_antitop':'ST','ST_tW_top':'ST','ST_s-channel_4f':'ST','ST_t-channel_top_4f':'ST','ST_t-channel_antitop_4f':'ST',\\\n;ttbar\n 'TT_pow':'TT',\\\n 'TT_2l2n':'TT',\\\n 'TT_h':'TT',\\\n 'TT_Sl':'TT',\\\n;Diboson\n 'WZpythia_lf':'VVLF','WZpythia_hf':'VVHF',\\\n 'WWpythia_lf':'VVLF','WWpythia_hf':'VVHF',\\\n 'ZZpythia_lf':'VVLF','ZZpythia_hf':'VVHF',\\\n;Diboson nlo\n 'WZamc_lf':'VVLF', 'WZamc_hf':'VVHF',\\\n 'WWamc_lf':'VVLF', 'WWamc_hf':'VVHF',\\\n 'ZZamc_lf':'VVLF', 'ZZamc_hf':'VVHF',\\\n 'WW_0b':'VVLF', 'WW_1b':'VVLF', 'WW_2b':'VVHF',\\\n 'WZ_0b':'VVLF', 'WZ_1b':'VVLF', 'WZ_2b':'VVHF',\\\n 'ZZ_0b':'VVLF', 'ZZ_1b':'VVLF', 'ZZ_2b':'VVHF',\\\n 'WWnlo_0b':'VVLF', 'WWnlo_1b':'VVLF', 'WWnlo_2b':'VVHF',\\\n 'WZnlo_0b':'VVLF', 'WZnlo_1b':'VVLF', 'WZnlo_2b':'VVHF',\\\n 'ZZnlo_0b':'VVLF', 'ZZnlo_1b':'VVLF', 'ZZnlo_2b':'VVHF',\\\n 'ZZ4l_0b': 'VVLF', 'ZZ4l_1b': 'VVLF', 'ZZ4l_2b': 'VVHF',\\\n;Signal\n 'WminusH':'WH',\\\n 'WplusH':'WH',\\\n;W+Jets\n 'WJetsHT0_0b':'WJets_0b','WJetsHT0_1b':'WJets_1b','WJetsHT0_2b':'WJets_2b',\\\n 'WJetsHT100_0b':'WJets_0b','WJetsHT100_1b':'WJets_1b','WJetsHT100_2b':'WJets_2b',\\\n 'WJetsHT200_0b':'WJets_0b','WJetsHT200_1b':'WJets_1b','WJetsHT200_2b':'WJets_2b',\\\n 'WJetsHT400_0b':'WJets_0b','WJetsHT400_1b':'WJets_1b','WJetsHT400_2b':'WJets_2b',\\\n 'WJetsHT600_0b':'WJets_0b','WJetsHT600_1b':'WJets_1b','WJetsHT600_2b':'WJets_2b',\\\n 'WJetsHT800_0b':'WJets_0b','WJetsHT800_1b':'WJets_1b','WJetsHT800_2b':'WJets_2b',\\\n 'WJetsHT1200_0b':'WJets_0b','WJetsHT1200_1b':'WJets_1b','WJetsHT1200_2b':'WJets_2b',\\\n 'WJetsHT2500_0b':'WJets_0b','WJetsHT2500_1b':'WJets_1b','WJetsHT2500_2b':'WJets_2b',\\\n 'WBJets100_0b':'WJets_0b','WBJets100_1b':'WJets_1b','WBJets100_2b':'WJets_2b',\\\n 'WBJets200_0b':'WJets_0b','WBJets200_1b':'WJets_1b','WBJets200_2b':'WJets_2b',\\\n 'WBGenFilter100_0b':'WJets_0b','WBGenFilter100_1b':'WJets_1b','WBGenFilter100_2b':'WJets_2b',\\\n 'WBGenFilter200_0b':'WJets_0b','WBGenFilter200_1b':'WJets_1b','WBGenFilter200_2b':'WJets_2b',\\\n#----- QCD -----#\n 'QCDHT100': 'QCD','QCDHT200': 'QCD','QCDHT300': 'QCD','QCDHT500': 'QCD','QCDHT700': 'QCD','QCDHT1000': 'QCD','QCDHT1500': 'QCD','QCDHT2000': 'QCD',\\\n }\n\ncolorDict: {\n 'ZHbb':632,\\\n 'VJets':401,\\\n 'ZJets_0b':401,'ZJets_1b':41,'ZJets_2b':5,\\\n 'ZJets_0b_udsg':401,\\\n 'ZJets_0b_c':395,\\\n 'ZJets_0b_nlo':401,'Zb_nlo':41,'Zbb_nlo':5,\\\n 'ST':598,\\\n 'TT':596,\\\n 'TT_Sl':596,\\\n 'TT_2l2n':594,\\\n 'TT_h':590,\\\n 'Top':596,\\\n 'VVlight':920+2,'VV2b':920+1,\\\n 'VV':920+1,\\\n 'ggZHbb':632,'qqZHbb':632,\n 'ZH':632,\\\n 'ggZH':632-7,\\\n 'WH': 632+2,\\\n 'WJets_0b': 820-6,\\\n 'WJets_0b_udsg': 820-6,\\\n 'WJets_0b_c': 435,\\\n 'WJets_0b_2c': 429,\\\n 'WJets_1b': 820-5,\\\n 'WJets_1b_udsg': 820-5,\\\n 'WJets_1b_c': 840-7,\\\n 'WJets_2b': 820,\\\n 'QCD': 613,\\\n 'QCDEME': 616,\\\n 'QCDb': 910,\\\n 'QCDbcToE': 891,\\\n 'QCDPt': 891,\\\n 'VVLF': 920,\\\n 'VVHF': 920+1,\\\n 'ZJets100': 880,\\\n 'ZJets200': 870,\\\n 'ZJets400': 827,\\\n 'ZJets600': 806,\\\n 'ZJets800': 907,\\\n 'ZJets1200': 433,\\\n 'ZJets2500': 872,\\\n 'ZJetsB100': 846,\\\n 'ZJetsB200': 791,\\\n 'DYJets0': 0,\\\n 'DYJets100': 880,\\\n 'DYJets200': 870,\\\n 'DYJets400': 827,\\\n 'DYJets600': 806,\\\n 'DYJets800': 907,\\\n 'DYJets1200': 433,\\\n 'DYJets2500': 872,\\\n }\n\ntypLegendDict: {\n 'VJets':'V+jets',\\\n 'ZJets_0b':'Z+udscg','ZJets_1b':'Z + b','ZJets_2b':'Z + b#bar{b}',\\\n 'ZJets_0b_udsg':'Z+udsg','ZJets_0b_c':'Z+c',\\\n 'ZJets_0b_nlo': 'Z+udscg','Zb_nlo':'Z + b','Zbb_nlo':'Z + b#bar{b}',\\\n 'ST':'Single top',\\\n 'TT':'t#bar{t}',\\\n 'Top':'t#bar{t}+ST',\\\n 'VVlight':'VVLF','VV2b':'VVHF',\\\n 'VV':'VV',\\\n 'ggZHbb':'ggZHbb','qqZHbb':'qqZHbb',\n 'ZH': 'ZH(b#bar{b})',\n 'ZHbb':'ZH(b#bar{b})',\\\n 'ggZH': 'ggZH(b#bar{b})',\n 'WH': 'WH(b#bar{b})',\n 'WJets_0b': 'W+udscg',\n 'WJets_0b_udsg': 'W+udsg',\n 'WJets_0b_c': 'W+c',\n 'WJets_0b_2c': 'W+c#bar{c}',\n 'WJets_1b': 'W+b',\n 'WJets_1b_udsg': 'W+bl',\n 'WJets_1b_c': 'W+bc',\n 'WJets_2b': 'W+b#bar{b}',\n 'QCD': 'QCD',\n 'QCDPt': 'QCD (Pt-binned)',\n }\n\nDict = {\n 'ZH': 'ZH_hbb',\n 'WH': 'WH_hbb',\n 'ggZH': 'ggZH_hbb',\n 'ZJets_0b': 'Zj0b',\n 'ZJets_0b_udsg': 'Zj0b_udsg',\n 'ZJets_0b_c': 'Zj0b_c',\n 'ZJets_1b': 'Zj1b',\n 'ZJets_2b': 'Zj2b',\n 'WJets_0b_udsg': 'Wj0b_udsg',\n 'WJets_0b_c': 'Wj0b_c',\n 'WJets_0b_2c': 'Wj0b_2c',\n 'WJets_1b': 'Wj1b',\n 'WJets_1b_udsg': 'Wj1b_udsg',\n 'WJets_1b_c': 'Wj1b_c',\n 'WJets_2b': 'Wj2b',\n 'TT': 'TT',\n 'ST': 's_Top',\n 'QCD': 'QCD',\n 'VVHF': 'VVHF',\n 'VVLF': 'VVLF',\n 'Zb': 'Zj1b',\n 'Zbb': 'Zj2b',\n }\n\n[Tools]\nCheckDuplicateEvents = CheckDuplicateEvents.CheckDuplicateEvents()\n\n\n[Weights]\n\n#----- LHE scale ------#\nCMS_LHE_weights_scale_muR_ZH_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_WH_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_ggZH_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_TT_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_Zj0b_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_Zj0b_udsg_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_Zj0b_c_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_Zj1b_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_Zj2b_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_Wj0b_udsg_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_Wj0b_c_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_Wj0b_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_Wj0b_2c_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_Wj1b_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_Wj1b_udsg_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_Wj1b_c_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_Wj2b_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_QCD_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_VVHF_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_VVLF_UP: <!Weights|weightF!>*LHEScaleWeight[7]\nCMS_LHE_weights_scale_muR_ZH_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_WH_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_ggZH_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_TT_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_Zj0b_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_Zj0b_udsg_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_Zj0b_c_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_Zj1b_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_Zj2b_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_Wj0b_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_Wj0b_udsg_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_Wj0b_c_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_Wj0b_2c_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_Wj1b_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_Wj1b_udsg_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_Wj1b_c_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_Wj2b_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_QCD_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_VVHF_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\nCMS_LHE_weights_scale_muR_VVLF_DOWN: <!Weights|weightF!>*LHEScaleWeight[1]\n\nCMS_LHE_weights_scale_muF_ZH_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_WH_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_ggZH_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_TT_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_Zj0b_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_Zj0b_udsg_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_Zj0b_c_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_Zj1b_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_Zj2b_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_Wj0b_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_Wj0b_udsg_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_Wj0b_c_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_Wj0b_2c_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_Wj1b_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_Wj1b_udsg_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_Wj1b_c_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_Wj2b_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_QCD_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_VVHF_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_VVLF_UP: <!Weights|weightF!>*LHEScaleWeight[5]\nCMS_LHE_weights_scale_muF_ZH_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_WH_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_ggZH_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_TT_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_Zj0b_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_Zj0b_udsg_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_Zj0b_c_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_Zj1b_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_Zj2b_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_Wj0b_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_Wj0b_udsg_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_Wj0b_c_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_Wj0b_2c_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_Wj1b_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_Wj1b_udsg_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_Wj1b_c_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_Wj2b_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_QCD_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_VVHF_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\nCMS_LHE_weights_scale_muF_VVLF_DOWN: <!Weights|weightF!>*LHEScaleWeight[3]\n\n#----- PU -----#\nPileUp_Up: <!Weights|weight_noPU!>*puWeightUp\nPileUp_Down: <!Weights|weight_noPU!>*puWeightDown\nCMS_vhbb_puWeight_Up: <!Weights|weight_noPU!>*puWeightUp\nCMS_vhbb_puWeight_Down: <!Weights|weight_noPU!>*puWeightDown\n\n#----- EWK signal -----#\n# EWKw contains weight for both signal and background, splitting of both uncertainties is done in CH\nCMS_vhbb_signal_ewk_13TeV_DOWN: <!Weights|weight_noEWK!>*EWKw[1]\nCMS_vhbb_signal_ewk_13TeV_UP: <!Weights|weight_noEWK!>*EWKw[2]\n\n#----- EWK V+Jets -----#\nCMS_vhbb_VJets_ewk_13TeV_DOWN: <!Weights|weight_noEWK!>*EWKw[1]\nCMS_vhbb_VJets_ewk_13TeV_UP: <!Weights|weight_noEWK!>*EWKw[2]\n\n\n#----- pdfwgt -----#\nCMS_vhbb_Vjets_pdfwgt_0lep_UP: <!Weights|weightF!>*(1.0 + (sampleIndex>=15000&&sampleIndex<16500)*(0.001*Alt$(LHE_Vpt,0.0)))\nCMS_vhbb_Vjets_pdfwgt_0lep_DOWN: <!Weights|weightF!>*(1.0 + (sampleIndex>=15000&&sampleIndex<16500)*(-0.001*Alt$(LHE_Vpt,0.0)))\nCMS_vhbb_Vjets_pdfwgt_1lep_UP: <!Weights|weightF!>*(1.0 + (sampleIndex>=4000&&sampleIndex<5500)*(0.001*Alt$(LHE_Vpt,0.0)))\nCMS_vhbb_Vjets_pdfwgt_1lep_DOWN: <!Weights|weightF!>*(1.0 + (sampleIndex>=4000&&sampleIndex<5500)*(-0.001*Alt$(LHE_Vpt,0.0)))\nCMS_vhbb_Vjets_pdfwgt_2lep_UP: <!Weights|weightF!>*(1.0 + (sampleIndex>=11000&&sampleIndex<14300)*(0.001*Alt$(LHE_Vpt,0.0)))\nCMS_vhbb_Vjets_pdfwgt_2lep_DOWN: <!Weights|weightF!>*(1.0 + (sampleIndex>=11000&&sampleIndex<14300)*(-0.001*Alt$(LHE_Vpt,0.0)))\n\n\n#----- top pT -----#\n#CMS_vhbb_topptreweighting_13TeV_DOWN: <!Weights|weight_noFitCorr!>*FitCorr[1]\n#CMS_vhbb_topptreweighting_13TeV_UP: <!Weights|weight_noFitCorr!>*FitCorr[2]\n\n#----- Fit Correction -----#\n# fit correction for W+Jets, in same branch as TT correction\n#FitCorrection_DOWN: <!Weights|weight_noFitCorr!>*FitCorr[1]\n#FitCorrection_UP: <!Weights|weight_noFitCorr!>*FitCorr[2]\n#FitCorrectionHF_DOWN: <!Weights|weight_noFitCorr!>*FitCorr[1]\n#FitCorrectionHF_UP: <!Weights|weight_noFitCorr!>*FitCorr[2]\n\n#----- V+Jets LO to NLO -----#\n#CMS_vhbb_vjetnlodetajjrw_13TeV_UP: <!Weights|weight_noNLO!>*<!Weights|weightNLO!>*<!Weights|weightNLO!>\n#CMS_vhbb_vjetnlodetajjrw_13TeV_DOWN: <!Weights|weight_noNLO!>\n\nCMS_vhbb_vjetnlodetajjrw_13TeV_UP: <!Weights|weightF!>*weightLOtoNLO_2016\nCMS_vhbb_vjetnlodetajjrw_13TeV_DOWN: <!Weights|weightF!>/weightLOtoNLO_2016 \n\n# V2\n#CMS_vhbb_vjetnlovptrw_p0_13TeV_UP: <!Weights|weightF!>/weightLOtoNLO_LHEVptV2*weightLOtoNLO_LHEVptV2_p0_Up\n#CMS_vhbb_vjetnlovptrw_p0_13TeV_DOWN: <!Weights|weightF!>/weightLOtoNLO_LHEVptV2*weightLOtoNLO_LHEVptV2_p0_Down\n#CMS_vhbb_vjetnlovptrw_p1_13TeV_UP: <!Weights|weightF!>/weightLOtoNLO_LHEVptV2*weightLOtoNLO_LHEVptV2_p1_Up\n#CMS_vhbb_vjetnlovptrw_p1_13TeV_DOWN: <!Weights|weightF!>/weightLOtoNLO_LHEVptV2*weightLOtoNLO_LHEVptV2_p1_Down\n\n# V5\nCMS_vhbb_vjetnlovptrw_p0_13TeV_UP: <!Weights|weightF!>/weightLOtoNLO_LHEVptV5*weightLOtoNLO_LHEVptV5_p0_Up\nCMS_vhbb_vjetnlovptrw_p0_13TeV_DOWN: <!Weights|weightF!>/weightLOtoNLO_LHEVptV5*weightLOtoNLO_LHEVptV5_p0_Down\nCMS_vhbb_vjetnlovptrw_p1_13TeV_UP: <!Weights|weightF!>/weightLOtoNLO_LHEVptV5*weightLOtoNLO_LHEVptV5_p1_Up\nCMS_vhbb_vjetnlovptrw_p1_13TeV_DOWN: <!Weights|weightF!>/weightLOtoNLO_LHEVptV5*weightLOtoNLO_LHEVptV5_p1_Down\n\n# naddjet binned\nCMS_vhbb_vjetnlovptrw_naddjet0_p0_13TeV_UP: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet0_p0_Up\nCMS_vhbb_vjetnlovptrw_naddjet0_p0_13TeV_DOWN: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet0_p1_Down\nCMS_vhbb_vjetnlovptrw_naddjet0_p1_13TeV_UP: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet0_p0_Up\nCMS_vhbb_vjetnlovptrw_naddjet0_p1_13TeV_DOWN: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet0_p1_Down\nCMS_vhbb_vjetnlovptrw_naddjet1_p0_13TeV_UP: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet1_p0_Up\nCMS_vhbb_vjetnlovptrw_naddjet1_p0_13TeV_DOWN: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet1_p1_Down\nCMS_vhbb_vjetnlovptrw_naddjet1_p1_13TeV_UP: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet1_p0_Up\nCMS_vhbb_vjetnlovptrw_naddjet1_p1_13TeV_DOWN: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet1_p1_Down\nCMS_vhbb_vjetnlovptrw_naddjet2_p0_13TeV_UP: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet2_p0_Up\nCMS_vhbb_vjetnlovptrw_naddjet2_p0_13TeV_DOWN: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet2_p1_Down\nCMS_vhbb_vjetnlovptrw_naddjet2_p1_13TeV_UP: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet2_p0_Up\nCMS_vhbb_vjetnlovptrw_naddjet2_p1_13TeV_DOWN: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet2_p1_Down\nCMS_vhbb_vjetnlovptrw_naddjet3_p0_13TeV_UP: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet3_p0_Up\nCMS_vhbb_vjetnlovptrw_naddjet3_p0_13TeV_DOWN: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet3_p1_Down\nCMS_vhbb_vjetnlovptrw_naddjet3_p1_13TeV_UP: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet3_p0_Up\nCMS_vhbb_vjetnlovptrw_naddjet3_p1_13TeV_DOWN: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet3_p1_Down\nCMS_vhbb_vjetnlovptrw_naddjet4_p0_13TeV_UP: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet4_p0_Up\nCMS_vhbb_vjetnlovptrw_naddjet4_p0_13TeV_DOWN: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet4_p1_Down\nCMS_vhbb_vjetnlovptrw_naddjet4_p1_13TeV_UP: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet4_p0_Up\nCMS_vhbb_vjetnlovptrw_naddjet4_p1_13TeV_DOWN: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet4_p1_Down\nCMS_vhbb_vjetnlovptrw_naddjet5_p0_13TeV_UP: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet5_p0_Up\nCMS_vhbb_vjetnlovptrw_naddjet5_p0_13TeV_DOWN: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet5_p1_Down\nCMS_vhbb_vjetnlovptrw_naddjet5_p1_13TeV_UP: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet5_p0_Up\nCMS_vhbb_vjetnlovptrw_naddjet5_p1_13TeV_DOWN: <!Weights|weightF!>/<!Weights|weightNLO!>*weightLOtoNLO_LHEVptV3_njet5_p1_Down\n\n\n# only meant for plots, not used for shapes\nCMV_vhbb_vjetnlovptrw_full_13TeV_UP: <!Weights|weightF!>*weightLOtoNLO_LHEVptV2\nCMV_vhbb_vjetnlovptrw_full_13TeV_DOWN: <!Weights|weightF!>/weightLOtoNLO_LHEVptV2\n\nCMS_vhbb_vjetnlovptrw_full_UP: <!Weights|weightF!>\nCMS_vhbb_vjetnlovptrw_full_DOWN: <!Weights|weightF!>/weightLOtoNLO_LHEVptV2\n\nNLO_dEtaJJ_DY_13TeV_UP: <!Weights|weightF!>*(1.0+(sampleIndex>=11000&&sampleIndex<14300)*(-1.0+weightLOtoNLO_2016))\nNLO_dEtaJJ_DY_13TeV_DOWN: <!Weights|weightF!>/(1.0+(sampleIndex>=11000&&sampleIndex<14300)*(-1.0+weightLOtoNLO_2016))\n\nNLO_Vpt_DY_13TeV_UP: <!Weights|weightF!>*(1.0+(sampleIndex>=11000&&sampleIndex<14300)*(-1.0+weightLOtoNLO_LHEVptV2))\nNLO_Vpt_DY_13TeV_DOWN: <!Weights|weightF!>/(1.0+(sampleIndex>=11000&&sampleIndex<14300)*(-1.0+weightLOtoNLO_LHEVptV2))\n\n#CMS_vhbb_vjetnlodetajjrw_13TeV_UP: <!Weights|weightF!>*weightLOtoNLO_2016\n#CMS_vhbb_vjetnlodetajjrw_13TeV_DOWN: <!Weights|weightF!>/weightLOtoNLO_2016\n\nCMV_vhbb_vjetnlovptrw_full_13TeV_UP: <!Weights|weightF!>*weightLOtoNLO_LHEVptV2\nCMV_vhbb_vjetnlovptrw_full_13TeV_DOWN: <!Weights|weightF!>/weightLOtoNLO_LHEVptV2\n\n# only meant for plots, not used for shapes\nCMS_vhbb_vjetnlovptrw_full_UP: <!Weights|weightF!>\nCMS_vhbb_vjetnlovptrw_full_DOWN: <!Weights|weightF!>/weightLOtoNLO_LHEVptV2\n\n#----- btag new -----#\n# note the different naming conventions for the eta bin, TODO: \n# for SYST in JES LF HF LFStats1 LFStats2 HFStats1 HFStats2 cErr1 cErr2; do for PTBIN in 0 1 2 3 4; do for ETABIN in 0 1 2; do echo \"CMS_bTagWeightDeepB${SYST}_13TeV_pt${PTBIN}_eta${ETABIN}_UP = \"'<!Weights|weight_noBTag!>*<!Weights|bTagWeight!>_'${SYST}'_pt'${PTBIN}'_eta'$((ETABIN+1))'Up'; done; done; done > tmp.txt\nCMS_bTagWeightDeepBJES_13TeV_pt0_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt0_eta1Up))\nCMS_bTagWeightDeepBJES_13TeV_pt0_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt0_eta2Up))\nCMS_bTagWeightDeepBJES_13TeV_pt0_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt0_eta3Up))\nCMS_bTagWeightDeepBJES_13TeV_pt1_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt1_eta1Up))\nCMS_bTagWeightDeepBJES_13TeV_pt1_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt1_eta2Up))\nCMS_bTagWeightDeepBJES_13TeV_pt1_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt1_eta3Up))\nCMS_bTagWeightDeepBJES_13TeV_pt2_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt2_eta1Up))\nCMS_bTagWeightDeepBJES_13TeV_pt2_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt2_eta2Up))\nCMS_bTagWeightDeepBJES_13TeV_pt2_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt2_eta3Up))\nCMS_bTagWeightDeepBJES_13TeV_pt3_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt3_eta1Up))\nCMS_bTagWeightDeepBJES_13TeV_pt3_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt3_eta2Up))\nCMS_bTagWeightDeepBJES_13TeV_pt3_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt3_eta3Up))\nCMS_bTagWeightDeepBJES_13TeV_pt4_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt4_eta1Up))\nCMS_bTagWeightDeepBJES_13TeV_pt4_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt4_eta2Up))\nCMS_bTagWeightDeepBJES_13TeV_pt4_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt4_eta3Up))\nCMS_bTagWeightDeepBLF_13TeV_pt0_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt0_eta1Up))\nCMS_bTagWeightDeepBLF_13TeV_pt0_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt0_eta2Up))\nCMS_bTagWeightDeepBLF_13TeV_pt0_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt0_eta3Up))\nCMS_bTagWeightDeepBLF_13TeV_pt1_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt1_eta1Up))\nCMS_bTagWeightDeepBLF_13TeV_pt1_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt1_eta2Up))\nCMS_bTagWeightDeepBLF_13TeV_pt1_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt1_eta3Up))\nCMS_bTagWeightDeepBLF_13TeV_pt2_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt2_eta1Up))\nCMS_bTagWeightDeepBLF_13TeV_pt2_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt2_eta2Up))\nCMS_bTagWeightDeepBLF_13TeV_pt2_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt2_eta3Up))\nCMS_bTagWeightDeepBLF_13TeV_pt3_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt3_eta1Up))\nCMS_bTagWeightDeepBLF_13TeV_pt3_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt3_eta2Up))\nCMS_bTagWeightDeepBLF_13TeV_pt3_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt3_eta3Up))\nCMS_bTagWeightDeepBLF_13TeV_pt4_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt4_eta1Up))\nCMS_bTagWeightDeepBLF_13TeV_pt4_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt4_eta2Up))\nCMS_bTagWeightDeepBLF_13TeV_pt4_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt4_eta3Up))\nCMS_bTagWeightDeepBHF_13TeV_pt0_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt0_eta1Up))\nCMS_bTagWeightDeepBHF_13TeV_pt0_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt0_eta2Up))\nCMS_bTagWeightDeepBHF_13TeV_pt0_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt0_eta3Up))\nCMS_bTagWeightDeepBHF_13TeV_pt1_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt1_eta1Up))\nCMS_bTagWeightDeepBHF_13TeV_pt1_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt1_eta2Up))\nCMS_bTagWeightDeepBHF_13TeV_pt1_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt1_eta3Up))\nCMS_bTagWeightDeepBHF_13TeV_pt2_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt2_eta1Up))\nCMS_bTagWeightDeepBHF_13TeV_pt2_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt2_eta2Up))\nCMS_bTagWeightDeepBHF_13TeV_pt2_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt2_eta3Up))\nCMS_bTagWeightDeepBHF_13TeV_pt3_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt3_eta1Up))\nCMS_bTagWeightDeepBHF_13TeV_pt3_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt3_eta2Up))\nCMS_bTagWeightDeepBHF_13TeV_pt3_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt3_eta3Up))\nCMS_bTagWeightDeepBHF_13TeV_pt4_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt4_eta1Up))\nCMS_bTagWeightDeepBHF_13TeV_pt4_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt4_eta2Up))\nCMS_bTagWeightDeepBHF_13TeV_pt4_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt4_eta3Up))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt0_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt0_eta1Up))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt0_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt0_eta2Up))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt0_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt0_eta3Up))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt1_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt1_eta1Up))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt1_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt1_eta2Up))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt1_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt1_eta3Up))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt2_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt2_eta1Up))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt2_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt2_eta2Up))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt2_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt2_eta3Up))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt3_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt3_eta1Up))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt3_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt3_eta2Up))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt3_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt3_eta3Up))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt4_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt4_eta1Up))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt4_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt4_eta2Up))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt4_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt4_eta3Up))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt0_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt0_eta1Up))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt0_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt0_eta2Up))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt0_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt0_eta3Up))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt1_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt1_eta1Up))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt1_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt1_eta2Up))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt1_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt1_eta3Up))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt2_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt2_eta1Up))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt2_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt2_eta2Up))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt2_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt2_eta3Up))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt3_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt3_eta1Up))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt3_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt3_eta2Up))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt3_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt3_eta3Up))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt4_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt4_eta1Up))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt4_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt4_eta2Up))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt4_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt4_eta3Up))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt0_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt0_eta1Up))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt0_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt0_eta2Up))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt0_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt0_eta3Up))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt1_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt1_eta1Up))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt1_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt1_eta2Up))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt1_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt1_eta3Up))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt2_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt2_eta1Up))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt2_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt2_eta2Up))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt2_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt2_eta3Up))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt3_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt3_eta1Up))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt3_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt3_eta2Up))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt3_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt3_eta3Up))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt4_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt4_eta1Up))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt4_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt4_eta2Up))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt4_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt4_eta3Up))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt0_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt0_eta1Up))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt0_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt0_eta2Up))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt0_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt0_eta3Up))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt1_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt1_eta1Up))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt1_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt1_eta2Up))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt1_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt1_eta3Up))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt2_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt2_eta1Up))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt2_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt2_eta2Up))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt2_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt2_eta3Up))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt3_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt3_eta1Up))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt3_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt3_eta2Up))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt3_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt3_eta3Up))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt4_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt4_eta1Up))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt4_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt4_eta2Up))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt4_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt4_eta3Up))\nCMS_bTagWeightDeepBcErr1_13TeV_pt0_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt0_eta1Up))\nCMS_bTagWeightDeepBcErr1_13TeV_pt0_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt0_eta2Up))\nCMS_bTagWeightDeepBcErr1_13TeV_pt0_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt0_eta3Up))\nCMS_bTagWeightDeepBcErr1_13TeV_pt1_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt1_eta1Up))\nCMS_bTagWeightDeepBcErr1_13TeV_pt1_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt1_eta2Up))\nCMS_bTagWeightDeepBcErr1_13TeV_pt1_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt1_eta3Up))\nCMS_bTagWeightDeepBcErr1_13TeV_pt2_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt2_eta1Up))\nCMS_bTagWeightDeepBcErr1_13TeV_pt2_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt2_eta2Up))\nCMS_bTagWeightDeepBcErr1_13TeV_pt2_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt2_eta3Up))\nCMS_bTagWeightDeepBcErr1_13TeV_pt3_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt3_eta1Up))\nCMS_bTagWeightDeepBcErr1_13TeV_pt3_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt3_eta2Up))\nCMS_bTagWeightDeepBcErr1_13TeV_pt3_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt3_eta3Up))\nCMS_bTagWeightDeepBcErr1_13TeV_pt4_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt4_eta1Up))\nCMS_bTagWeightDeepBcErr1_13TeV_pt4_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt4_eta2Up))\nCMS_bTagWeightDeepBcErr1_13TeV_pt4_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt4_eta3Up))\nCMS_bTagWeightDeepBcErr2_13TeV_pt0_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt0_eta1Up))\nCMS_bTagWeightDeepBcErr2_13TeV_pt0_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt0_eta2Up))\nCMS_bTagWeightDeepBcErr2_13TeV_pt0_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt0_eta3Up))\nCMS_bTagWeightDeepBcErr2_13TeV_pt1_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt1_eta1Up))\nCMS_bTagWeightDeepBcErr2_13TeV_pt1_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt1_eta2Up))\nCMS_bTagWeightDeepBcErr2_13TeV_pt1_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt1_eta3Up))\nCMS_bTagWeightDeepBcErr2_13TeV_pt2_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt2_eta1Up))\nCMS_bTagWeightDeepBcErr2_13TeV_pt2_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt2_eta2Up))\nCMS_bTagWeightDeepBcErr2_13TeV_pt2_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt2_eta3Up))\nCMS_bTagWeightDeepBcErr2_13TeV_pt3_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt3_eta1Up))\nCMS_bTagWeightDeepBcErr2_13TeV_pt3_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt3_eta2Up))\nCMS_bTagWeightDeepBcErr2_13TeV_pt3_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt3_eta3Up))\nCMS_bTagWeightDeepBcErr2_13TeV_pt4_eta0_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt4_eta1Up))\nCMS_bTagWeightDeepBcErr2_13TeV_pt4_eta1_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt4_eta2Up))\nCMS_bTagWeightDeepBcErr2_13TeV_pt4_eta2_UP = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt4_eta3Up))\n\nCMS_bTagWeightDeepBJES_13TeV_pt0_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt0_eta1Down))\nCMS_bTagWeightDeepBJES_13TeV_pt0_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt0_eta2Down))\nCMS_bTagWeightDeepBJES_13TeV_pt0_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt0_eta3Down))\nCMS_bTagWeightDeepBJES_13TeV_pt1_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt1_eta1Down))\nCMS_bTagWeightDeepBJES_13TeV_pt1_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt1_eta2Down))\nCMS_bTagWeightDeepBJES_13TeV_pt1_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt1_eta3Down))\nCMS_bTagWeightDeepBJES_13TeV_pt2_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt2_eta1Down))\nCMS_bTagWeightDeepBJES_13TeV_pt2_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt2_eta2Down))\nCMS_bTagWeightDeepBJES_13TeV_pt2_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt2_eta3Down))\nCMS_bTagWeightDeepBJES_13TeV_pt3_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt3_eta1Down))\nCMS_bTagWeightDeepBJES_13TeV_pt3_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt3_eta2Down))\nCMS_bTagWeightDeepBJES_13TeV_pt3_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt3_eta3Down))\nCMS_bTagWeightDeepBJES_13TeV_pt4_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt4_eta1Down))\nCMS_bTagWeightDeepBJES_13TeV_pt4_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt4_eta2Down))\nCMS_bTagWeightDeepBJES_13TeV_pt4_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_JES_pt4_eta3Down))\nCMS_bTagWeightDeepBLF_13TeV_pt0_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt0_eta1Down))\nCMS_bTagWeightDeepBLF_13TeV_pt0_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt0_eta2Down))\nCMS_bTagWeightDeepBLF_13TeV_pt0_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt0_eta3Down))\nCMS_bTagWeightDeepBLF_13TeV_pt1_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt1_eta1Down))\nCMS_bTagWeightDeepBLF_13TeV_pt1_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt1_eta2Down))\nCMS_bTagWeightDeepBLF_13TeV_pt1_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt1_eta3Down))\nCMS_bTagWeightDeepBLF_13TeV_pt2_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt2_eta1Down))\nCMS_bTagWeightDeepBLF_13TeV_pt2_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt2_eta2Down))\nCMS_bTagWeightDeepBLF_13TeV_pt2_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt2_eta3Down))\nCMS_bTagWeightDeepBLF_13TeV_pt3_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt3_eta1Down))\nCMS_bTagWeightDeepBLF_13TeV_pt3_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt3_eta2Down))\nCMS_bTagWeightDeepBLF_13TeV_pt3_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt3_eta3Down))\nCMS_bTagWeightDeepBLF_13TeV_pt4_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt4_eta1Down))\nCMS_bTagWeightDeepBLF_13TeV_pt4_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt4_eta2Down))\nCMS_bTagWeightDeepBLF_13TeV_pt4_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LF_pt4_eta3Down))\nCMS_bTagWeightDeepBHF_13TeV_pt0_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt0_eta1Down))\nCMS_bTagWeightDeepBHF_13TeV_pt0_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt0_eta2Down))\nCMS_bTagWeightDeepBHF_13TeV_pt0_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt0_eta3Down))\nCMS_bTagWeightDeepBHF_13TeV_pt1_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt1_eta1Down))\nCMS_bTagWeightDeepBHF_13TeV_pt1_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt1_eta2Down))\nCMS_bTagWeightDeepBHF_13TeV_pt1_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt1_eta3Down))\nCMS_bTagWeightDeepBHF_13TeV_pt2_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt2_eta1Down))\nCMS_bTagWeightDeepBHF_13TeV_pt2_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt2_eta2Down))\nCMS_bTagWeightDeepBHF_13TeV_pt2_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt2_eta3Down))\nCMS_bTagWeightDeepBHF_13TeV_pt3_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt3_eta1Down))\nCMS_bTagWeightDeepBHF_13TeV_pt3_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt3_eta2Down))\nCMS_bTagWeightDeepBHF_13TeV_pt3_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt3_eta3Down))\nCMS_bTagWeightDeepBHF_13TeV_pt4_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt4_eta1Down))\nCMS_bTagWeightDeepBHF_13TeV_pt4_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt4_eta2Down))\nCMS_bTagWeightDeepBHF_13TeV_pt4_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HF_pt4_eta3Down))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt0_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt0_eta1Down))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt0_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt0_eta2Down))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt0_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt0_eta3Down))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt1_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt1_eta1Down))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt1_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt1_eta2Down))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt1_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt1_eta3Down))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt2_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt2_eta1Down))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt2_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt2_eta2Down))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt2_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt2_eta3Down))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt3_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt3_eta1Down))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt3_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt3_eta2Down))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt3_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt3_eta3Down))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt4_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt4_eta1Down))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt4_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt4_eta2Down))\nCMS_bTagWeightDeepBLFStats1_13TeV_pt4_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats1_pt4_eta3Down))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt0_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt0_eta1Down))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt0_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt0_eta2Down))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt0_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt0_eta3Down))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt1_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt1_eta1Down))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt1_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt1_eta2Down))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt1_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt1_eta3Down))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt2_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt2_eta1Down))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt2_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt2_eta2Down))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt2_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt2_eta3Down))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt3_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt3_eta1Down))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt3_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt3_eta2Down))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt3_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt3_eta3Down))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt4_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt4_eta1Down))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt4_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt4_eta2Down))\nCMS_bTagWeightDeepBLFStats2_13TeV_pt4_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_LFStats2_pt4_eta3Down))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt0_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt0_eta1Down))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt0_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt0_eta2Down))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt0_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt0_eta3Down))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt1_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt1_eta1Down))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt1_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt1_eta2Down))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt1_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt1_eta3Down))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt2_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt2_eta1Down))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt2_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt2_eta2Down))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt2_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt2_eta3Down))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt3_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt3_eta1Down))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt3_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt3_eta2Down))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt3_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt3_eta3Down))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt4_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt4_eta1Down))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt4_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt4_eta2Down))\nCMS_bTagWeightDeepBHFStats1_13TeV_pt4_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats1_pt4_eta3Down))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt0_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt0_eta1Down))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt0_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt0_eta2Down))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt0_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt0_eta3Down))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt1_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt1_eta1Down))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt1_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt1_eta2Down))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt1_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt1_eta3Down))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt2_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt2_eta1Down))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt2_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt2_eta2Down))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt2_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt2_eta3Down))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt3_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt3_eta1Down))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt3_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt3_eta2Down))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt3_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt3_eta3Down))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt4_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt4_eta1Down))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt4_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt4_eta2Down))\nCMS_bTagWeightDeepBHFStats2_13TeV_pt4_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_HFStats2_pt4_eta3Down))\nCMS_bTagWeightDeepBcErr1_13TeV_pt0_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt0_eta1Down))\nCMS_bTagWeightDeepBcErr1_13TeV_pt0_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt0_eta2Down))\nCMS_bTagWeightDeepBcErr1_13TeV_pt0_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt0_eta3Down))\nCMS_bTagWeightDeepBcErr1_13TeV_pt1_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt1_eta1Down))\nCMS_bTagWeightDeepBcErr1_13TeV_pt1_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt1_eta2Down))\nCMS_bTagWeightDeepBcErr1_13TeV_pt1_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt1_eta3Down))\nCMS_bTagWeightDeepBcErr1_13TeV_pt2_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt2_eta1Down))\nCMS_bTagWeightDeepBcErr1_13TeV_pt2_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt2_eta2Down))\nCMS_bTagWeightDeepBcErr1_13TeV_pt2_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt2_eta3Down))\nCMS_bTagWeightDeepBcErr1_13TeV_pt3_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt3_eta1Down))\nCMS_bTagWeightDeepBcErr1_13TeV_pt3_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt3_eta2Down))\nCMS_bTagWeightDeepBcErr1_13TeV_pt3_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt3_eta3Down))\nCMS_bTagWeightDeepBcErr1_13TeV_pt4_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt4_eta1Down))\nCMS_bTagWeightDeepBcErr1_13TeV_pt4_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt4_eta2Down))\nCMS_bTagWeightDeepBcErr1_13TeV_pt4_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr1_pt4_eta3Down))\nCMS_bTagWeightDeepBcErr2_13TeV_pt0_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt0_eta1Down))\nCMS_bTagWeightDeepBcErr2_13TeV_pt0_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt0_eta2Down))\nCMS_bTagWeightDeepBcErr2_13TeV_pt0_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt0_eta3Down))\nCMS_bTagWeightDeepBcErr2_13TeV_pt1_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt1_eta1Down))\nCMS_bTagWeightDeepBcErr2_13TeV_pt1_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt1_eta2Down))\nCMS_bTagWeightDeepBcErr2_13TeV_pt1_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt1_eta3Down))\nCMS_bTagWeightDeepBcErr2_13TeV_pt2_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt2_eta1Down))\nCMS_bTagWeightDeepBcErr2_13TeV_pt2_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt2_eta2Down))\nCMS_bTagWeightDeepBcErr2_13TeV_pt2_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt2_eta3Down))\nCMS_bTagWeightDeepBcErr2_13TeV_pt3_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt3_eta1Down))\nCMS_bTagWeightDeepBcErr2_13TeV_pt3_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt3_eta2Down))\nCMS_bTagWeightDeepBcErr2_13TeV_pt3_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt3_eta3Down))\nCMS_bTagWeightDeepBcErr2_13TeV_pt4_eta0_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt4_eta1Down))\nCMS_bTagWeightDeepBcErr2_13TeV_pt4_eta1_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt4_eta2Down))\nCMS_bTagWeightDeepBcErr2_13TeV_pt4_eta2_DOWN = <!Weights|weight_noBTag!>*(isBoosted+!isBoosted*(bTagWeightDeepCSV_cErr2_pt4_eta3Down))\n\n\n\n# DeepAK8 MD bb vs light\n# the old behavior can be reproduced with: --set='General.DeepAK8weightApplies=(isBoosted)'\nbTagWeightDoubleB_mp_pt200to300_Down: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_mp_pt200to300_Down))\nbTagWeightDoubleB_mp_pt300to400_Down: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_mp_pt300to400_Down))\nbTagWeightDoubleB_mp_pt400to500_Down: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_mp_pt400to500_Down))\nbTagWeightDoubleB_mp_pt500to600_Down: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_mp_pt500to600_Down))\nbTagWeightDoubleB_mp_pt600toInf_Down: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_mp_pt600toInf_Down))\nbTagWeightDoubleB_hp_pt200to300_Down: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_hp_pt200to300_Down))\nbTagWeightDoubleB_hp_pt300to400_Down: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_hp_pt300to400_Down))\nbTagWeightDoubleB_hp_pt400to500_Down: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_hp_pt400to500_Down))\nbTagWeightDoubleB_hp_pt500to600_Down: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_hp_pt500to600_Down))\nbTagWeightDoubleB_hp_pt600toInf_Down: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_hp_pt600toInf_Down))\n\nbTagWeightDoubleB_mp_pt200to300_Up: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_mp_pt200to300_Up))\nbTagWeightDoubleB_mp_pt300to400_Up: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_mp_pt300to400_Up))\nbTagWeightDoubleB_mp_pt400to500_Up: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_mp_pt400to500_Up))\nbTagWeightDoubleB_mp_pt500to600_Up: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_mp_pt500to600_Up))\nbTagWeightDoubleB_mp_pt600toInf_Up: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_mp_pt600toInf_Up))\nbTagWeightDoubleB_hp_pt200to300_Up: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_hp_pt200to300_Up))\nbTagWeightDoubleB_hp_pt300to400_Up: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_hp_pt300to400_Up))\nbTagWeightDoubleB_hp_pt400to500_Up: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_hp_pt400to500_Up))\nbTagWeightDoubleB_hp_pt500to600_Up: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_hp_pt500to600_Up))\nbTagWeightDoubleB_hp_pt600toInf_Up: (<!Weights|weightF!>)*(1.0+<!General|DeepAK8weightApplies!>*(-1.0+1.0/bTagWeightDoubleB*bTagWeightDoubleB_hp_pt600toInf_Up))\n\nCMS_vhbb_DeepCSV_TT_UP = <!Weights|weightF!>*(isBoosted+!isBoosted*(1.0+(<!General|resolvedBtag0!>><!General|btagWP_Tight!>&&<!General|resolvedBtag1!>><!General|btagWP_Tight!>)))\nCMS_vhbb_DeepCSV_TT_DOWN = <!Weights|weightF!>*(isBoosted+!isBoosted*(1.0-0.5*(<!General|resolvedBtag0!>><!General|btagWP_Tight!>&&<!General|resolvedBtag1!>><!General|btagWP_Tight!>)))\nCMS_vhbb_DeepCSV_TM_UP = <!Weights|weightF!>*(isBoosted+!isBoosted*(1.0+(<!General|resolvedBtag0!>><!General|btagWP_Tight!>&&<!General|resolvedBtag1!>><!General|btagWP_Medium!>&&<!General|resolvedBtag1!><<!General|btagWP_Tight!>)))\nCMS_vhbb_DeepCSV_TM_DOWN = <!Weights|weightF!>*(isBoosted+!isBoosted*(1.0-0.5*(<!General|resolvedBtag0!>><!General|btagWP_Tight!>&&<!General|resolvedBtag1!>><!General|btagWP_Medium!>&&<!General|resolvedBtag1!><<!General|btagWP_Tight!>)))\nCMS_vhbb_DeepCSV_TL_UP = <!Weights|weightF!>*(isBoosted+!isBoosted*(1.0+(<!General|resolvedBtag0!>><!General|btagWP_Tight!>&&<!General|resolvedBtag1!>><!General|btagWP_Loose!>&&<!General|resolvedBtag1!><<!General|btagWP_Medium!>)))\nCMS_vhbb_DeepCSV_TL_DOWN = <!Weights|weightF!>*(isBoosted+!isBoosted*(1.0-0.5*(<!General|resolvedBtag0!>><!General|btagWP_Tight!>&&<!General|resolvedBtag1!>><!General|btagWP_Loose!>&&<!General|resolvedBtag1!><<!General|btagWP_Medium!>)))\nCMS_vhbb_DeepCSV_MM_UP = <!Weights|weightF!>*(isBoosted+!isBoosted*(1.0+(<!General|resolvedBtag0!>><!General|btagWP_Medium!>&&<!General|resolvedBtag0!><<!General|btagWP_Tight!>&&<!General|resolvedBtag1!>><!General|btagWP_Medium!>&&<!General|resolvedBtag1!><<!General|btagWP_Tight!>)))\nCMS_vhbb_DeepCSV_MM_DOWN = <!Weights|weightF!>*(isBoosted+!isBoosted*(1.0-0.5*(<!General|resolvedBtag0!>><!General|btagWP_Medium!>&&<!General|resolvedBtag0!><<!General|btagWP_Tight!>&&<!General|resolvedBtag1!>><!General|btagWP_Medium!>&&<!General|resolvedBtag1!><<!General|btagWP_Tight!>)))\nCMS_vhbb_DeepCSV_ML_UP = <!Weights|weightF!>*(isBoosted+!isBoosted*(1.0+(<!General|resolvedBtag0!>><!General|btagWP_Medium!>&&<!General|resolvedBtag0!><<!General|btagWP_Tight!>&&<!General|resolvedBtag1!>><!General|btagWP_Loose!>&&<!General|resolvedBtag1!><<!General|btagWP_Medium!>)))\nCMS_vhbb_DeepCSV_ML_DOWN = <!Weights|weightF!>*(isBoosted+!isBoosted*(1.0-0.5*(<!General|resolvedBtag0!>><!General|btagWP_Medium!>&&<!General|resolvedBtag0!><<!General|btagWP_Tight!>&&<!General|resolvedBtag1!>><!General|btagWP_Loose!>&&<!General|resolvedBtag1!><<!General|btagWP_Medium!>)))\nCMS_vhbb_DeepCSV_LL_UP = <!Weights|weightF!>*(isBoosted+!isBoosted*(1.0+(<!General|resolvedBtag0!>><!General|btagWP_Loose!>&&<!General|resolvedBtag0!><<!General|btagWP_Medium!>&&<!General|resolvedBtag1!>><!General|btagWP_Loose!>&&<!General|resolvedBtag1!><<!General|btagWP_Medium!>)))\nCMS_vhbb_DeepCSV_LL_DOWN = <!Weights|weightF!>*(isBoosted+!isBoosted*(1.0-0.5*(<!General|resolvedBtag0!>><!General|btagWP_Loose!>&&<!General|resolvedBtag0!><<!General|btagWP_Medium!>&&<!General|resolvedBtag1!>><!General|btagWP_Loose!>&&<!General|resolvedBtag1!><<!General|btagWP_Medium!>)))\n\n\n[LimitGeneral]\nnormalizeShapes = ['CMS_vhbb_Vjets_pdfwgt_0lep_Up','CMS_vhbb_Vjets_pdfwgt_0lep_Down','CMS_vhbb_Vjets_pdfwgt_1lep_Up','CMS_vhbb_Vjets_pdfwgt_1lep_Down','CMS_vhbb_Vjets_pdfwgt_2lep_Up','CMS_vhbb_Vjets_pdfwgt_2lep_Down','CMS_vhbb_vjetnlodetajjrw_13TeV_UP','CMS_vhbb_vjetnlodetajjrw_13TeV_DOWN']\n\n\n" }, { "alpha_fraction": 0.6209616661071777, "alphanum_fraction": 0.6243426203727722, "avg_line_length": 40.546875, "blob_id": "7acecaf68ae1c61c905879364e9e8593cf56804a", "content_id": "adfa3cb110e4d31cc5e1797946bd2f97e09a03c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2662, "license_type": "no_license", "max_line_length": 139, "num_lines": 64, "path": "/python/myutils/isBoosted.py", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport ROOT\nimport numpy as np\nimport array\nimport os\nfrom BranchTools import Collection\nfrom BranchTools import AddCollectionsModule\nfrom XbbTools import XbbTools\n\nclass isBoosted(AddCollectionsModule):\n\n def __init__(self, branchName='isBoosted', cutName='all_BOOST'):\n super(isBoosted, self).__init__()\n self.branchName = branchName\n self.cutName = cutName\n self.version = 3\n self.variations = self._variations(\"isBoosted\") \n\n # returns cut string with variables replaced by their systematic variations\n def getSystVarCut(self, cut, syst, UD):\n replacementRulesList = XbbTools.getReplacementRulesList(self.config, syst)\n systVarCut = XbbTools.getSystematicsVariationTemplate(cut, replacementRulesList)\n systVarCut = systVarCut.replace('{syst}', syst).replace('{UD}', UD)\n return systVarCut\n\n def customInit(self, initVars):\n self.sample = initVars['sample']\n self.sampleTree = initVars['sampleTree']\n self.config = initVars['config']\n\n self.boostedCut = self.config.get('Cuts', self.cutName)\n self.systVarCuts = {}\n\n self.systematics = sorted(list(set(sum([eval(self.config.get('LimitGeneral', x)) for x in ['sys_cr', 'sys_BDT', 'sys_Mjj']], []))))\n\n # Nominal\n self.addIntegerBranch(self.branchName)\n self.sampleTree.addFormula(self.boostedCut)\n\n # systematic variations\n if self.sample.isMC():\n for syst in self.systematics:\n for UD in self.variations: \n systVarBranchName = self._v(self.branchName, syst, UD)\n self.addIntegerBranch(systVarBranchName)\n self.systVarCuts[systVarBranchName] = self.getSystVarCut(self.boostedCut, syst=syst, UD=UD)\n self.sampleTree.addFormula(self.systVarCuts[systVarBranchName])\n\n def processEvent(self, tree):\n # if current entry has not been processed yet\n if not self.hasBeenProcessed(tree):\n self.markProcessed(tree)\n\n # Nominal\n b = int(self.sampleTree.evaluate(self.boostedCut))\n self._b(self._v(self.branchName))[0] = 1 if b > 0 else 0 \n\n # systematic variations\n if self.sample.isMC():\n for syst in self.systematics:\n for UD in self.variations: \n systVarBranchName = self._v(self.branchName, syst, UD)\n b = int(self.sampleTree.evaluate(self.systVarCuts[systVarBranchName]))\n self._b(systVarBranchName)[0] = 1 if b > 0 else 0 \n\n\n" }, { "alpha_fraction": 0.678642213344574, "alphanum_fraction": 0.8414271473884583, "avg_line_length": 55.05555725097656, "blob_id": "5d2716eabcd8be907a6b17e948bb29b4abecf842", "content_id": "1b27c82f2111bc9756f50b1d95d85121aaa42620", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 4036, "license_type": "no_license", "max_line_length": 89, "num_lines": 72, "path": "/python/Zvv2017config/hadd.ini", "repo_name": "dabercro/Xbb", "src_encoding": "UTF-8", "text": "# V11\n[Hadd]\nZJetsToNuNu_HT-800To1200_13TeV-madgraph: 1\nQCD_HT200to300_TuneCP5_13TeV-madgraph-pythia8: 1932\nWplusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8: 2\nTTTo2L2Nu_TuneCP5_PSweights_13TeV-powheg-pythia8: 1\nTTToSemiLeptonic_TuneCP5_PSweights_13TeV-powheg-pythia8: 1\nWminusH_HToBB_WToLNu_M125_13TeV_powheg_pythia8: 2\nDYJetsToLL_M-4to50_HT-200to400_TuneCP5_13TeV-madgraphMLM-pythia8: 15\nWJetsToLNu_BGenFilter_Wpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 2\nSingleElectron: 5\nDYJetsToLL_M-4to50_HT-600toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 3\nggZH_HToBB_ZToLL_M125_13TeV_powheg_pythia8: 3\nWZTo1L1Nu2Q_13TeV_amcatnloFXFX_madspin_pythia8: 1\nWJetsToLNu_HT-1200To2500_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYJetsToLL_M-4to50_HT-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 35\nDYJetsToLL_M-50_HT-1200to2500_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZJetsToNuNu_HT-400To600_13TeV-madgraph: 1\nZJetsToNuNu_BGenFilter_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 4\nWBJetsToLNu_Wpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 2\nDYJetsToLL_M-50_HT-2500toInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYBJetsToLL_M-50_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 9\nDYJetsToLL_M-4to50_HT-400to600_TuneCP5_13TeV-madgraphMLM-pythia8: 3\nDYJetsToLL_M-50_TuneCP5_13TeV-madgraphMLM-pythia8: 20\nZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8: 2\nZBJetsToNuNu_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 3\nWJetsToLNu_HT-200To400_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZBJetsToNuNu_Zpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 2\nTTToHadronic_TuneCP5_PSweights_13TeV-powheg-pythia8: 7\nST_t-channel_antitop_4f_InclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8: 1\nWBJetsToLNu_Wpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 2\nZJetsToNuNu_HT-2500ToInf_13TeV-madgraph: 11\nWJetsToLNu_BGenFilter_Wpt-200toInf_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 1\nWZ_TuneCP5_13TeV-pythia8: 3\nQCD_HT2000toInf_TuneCP5_13TeV-madgraph-pythia8: 1\nWW_TuneCP5_13TeV-pythia8: 3\nDYJetsToLL_M-50_HT-800to1200_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZZ_TuneCP5_13TeV-pythia8: 4\nQCD_HT500to700_TuneCP5_13TeV-madgraph-pythia8: 14\nDYJetsToLL_M-50_HT-200to400_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nWJetsToLNu_HT-400To600_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYJetsToLL_M-50_HT-100to200_TuneCP5_13TeV-madgraphMLM-pythia8: 4\nDYBJetsToLL_M-50_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 5\nZJetsToNuNu_HT-100To200_13TeV-madgraph: 2\nQCD_HT1000to1500_TuneCP5_13TeV-madgraph-pythia8: 3\nZJetsToNuNu_HT-1200To2500_13TeV-madgraph: 1\nQCD_HT300to500_TuneCP5_13TeV-madgraph-pythia8: 133\nDYJetsToLL_BGenFilter_Zpt-100to200_M-50_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 10\nWJetsToLNu_HT-800To1200_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nST_tW_antitop_5f_inclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8: 1\nQCD_HT700to1000_TuneCP5_13TeV-madgraph-pythia8: 8\nZH_HToBB_ZToLL_M125_13TeV_powheg_pythia8: 6\nZJetsToNuNu_HT-200To400_13TeV-madgraph: 1\nQCD_HT1500to2000_TuneCP5_13TeV-madgraph-pythia8: 1\nZJetsToNuNu_BGenFilter_Zpt-100to200_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 9\nDYJetsToLL_M-50_HT-600to800_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYJetsToLL_M-50_HT-400to600_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nST_tW_top_5f_inclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8: 1\nWWTo1L1Nu2Q_13TeV_amcatnloFXFX_madspin_pythia8: 2\nST_s-channel_4f_leptonDecays_TuneCP5_PSweights_13TeV-amcatnlo-pythia8: 1\nWJetsToLNu_HT-2500ToInf_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nDYJetsToLL_BGenFilter_Zpt-200toInf_M-50_TuneCP5_13TeV-madgraphMLM-pythia8_newgridpack: 9\nWJetsToLNu_HT-600To800_TuneCP5_13TeV-madgraphMLM-pythia8: 1\nZJetsToNuNu_HT-600To800_13TeV-madgraph: 1\nWJetsToLNu_HT-100To200_TuneCP5_13TeV-madgraphMLM-pythia8: 3\nSingleMuon: 5\nQCD_HT100to200_TuneCP5_13TeV-madgraph-pythia8: 10667\nggZH_HToBB_ZToNuNu_M125_13TeV_powheg_pythia8: 1\nZZTo4L_13TeV_powheg_pythia8: 21\nST_t-channel_top_4f_InclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8: 2\nMET: 2\nWJetsToLNu_TuneCP5_13TeV-madgraphMLM-pythia8: 20\n" } ]
21
iJuanPablo/tools
https://github.com/iJuanPablo/tools
880d7e52495f79d2d3aeae7ae6d03f2357ffb681
176324daf8b4381a69130adad5796a87a79de335
22243ee17f48459e5b94c17b52a1788ea8c1bc87
refs/heads/master
2021-06-11T16:50:05.228384
2017-03-14T21:02:23
2017-03-14T21:02:23
84,996,618
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5927969813346863, "alphanum_fraction": 0.6047052145004272, "avg_line_length": 26.975608825683594, "blob_id": "e50d73f0f3c5848b4f188758f8e41b260550ba7d", "content_id": "d315fb89dab3915c4b2076de09494e5b98ef34a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3443, "license_type": "no_license", "max_line_length": 99, "num_lines": 123, "path": "/ip_reader.py", "repo_name": "iJuanPablo/tools", "src_encoding": "UTF-8", "text": "\"\"\"\nip_reader\n---------\nReads the Machine IP and emails if it has changed\n\nMac - Linux\n crontab\n\nWindows:\n\nCommand line as follows:\n\nschtasks /Create /SC HOURLY /TN PythonTask /TR \"PATH_TO_PYTHON_EXE PATH_TO_PYTHON_SCRIPT\"\n\nThat will create an hourly task called 'PythonTask'. You can replace HOURLY with DAILY, WEEKLY etc.\nPATH_TO_PYTHON_EXE will be something like: C:\\python25\\python.exe.\n\nOtherwise you can open the Task Scheduler and do it through the GUI. Hope this helps.\n\n\"\"\"\n\nimport collections\nimport base64\nimport json\n\nfrom httplib import HTTPSConnection\nfrom urllib import urlencode\nfrom urllib2 import urlopen\n\n\ndef encode_params(data):\n \"\"\"Encode parameters in a piece of data.\n\n Will successfully encode parameters when passed as a dict or a list of\n 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n if parameters are supplied as a dict.\n \"\"\"\n\n if isinstance(data, (str, bytes)):\n return data\n elif hasattr(data, 'read'):\n return data\n elif hasattr(data, '__iter__'):\n result = []\n for k, vs in to_key_val_list(data):\n if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):\n vs = [vs]\n for v in vs:\n if v is not None:\n result.append(\n (k.encode('utf-8') if isinstance(k, str) else k,\n v.encode('utf-8') if isinstance(v, str) else v))\n return urlencode(result, doseq=True)\n else:\n return data\n\n\ndef to_key_val_list(value):\n \"\"\"Take an object and test to see if it can be represented as a\n dictionary. If it can be, return a list of tuples, e.g.,\n\n ::\n\n >>> to_key_val_list([('key', 'val')])\n [('key', 'val')]\n >>> to_key_val_list({'key': 'val'})\n [('key', 'val')]\n >>> to_key_val_list('string')\n ValueError: cannot encode objects that are not 2-tuples.\n\n :rtype: list\n \"\"\"\n if value is None:\n return None\n\n if isinstance(value, (str, bytes, bool, int)):\n raise ValueError('cannot encode objects that are not 2-tuples')\n\n if isinstance(value, collections.Mapping):\n value = value.items()\n\n return list(value)\n\n\nfile_path = 'ip.txt'\nmy_ip = json.load(urlopen('https://api.ipify.org/?format=json'))['ip']\n\ntry:\n with open(file_path, 'r') as the_file:\n file_ip = the_file.read()\nexcept:\n file_ip = u''\n\nif my_ip != file_ip:\n\n http = 'http://'\n url = 'api.mailgun.net'\n request = '/v3/sandboxee586e52376a457d8b274c437718a56e.mailgun.org/messages'\n\n key = 'key-29caea072852af2816e0b02f6733b751'\n base64string = base64.encodestring('api:'+key).replace('\\n', '')\n\n headers = {'Authorization': 'Basic %s' % base64string,\n 'content-type': 'application/x-www-form-urlencoded'}\n payload = {\"from\": \"PostMaster <[email protected]>\",\n \"to\": \"Juan Pablo <[email protected]>\",\n \"subject\": \"La IP de la oficina ha cambiado!\",\n \"text\": \"La nueva IP es: \" + my_ip}\n\n body = encode_params(payload)\n\n http_connection = HTTPSConnection(url)\n http_connection.request(method=\"POST\", url=request, body=body, headers=headers)\n response = json.loads(http_connection.getresponse().read())\n print response\n\n if response['message'] == 'Queued. Thank you.':\n with open(file_path, 'w') as the_file:\n the_file.write(my_ip)\n print \"Escrito\"\n\nelse:\n print 'Same IP'\n\n\n" }, { "alpha_fraction": 0.7727272510528564, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 10, "blob_id": "3b05503d48e472ff5d50410ba8ff91a8e04fccbd", "content_id": "2fdf5b9c0ccacc0aac7e51bdde9f61446aa4d828", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 22, "license_type": "no_license", "max_line_length": 13, "num_lines": 2, "path": "/README.md", "repo_name": "iJuanPablo/tools", "src_encoding": "UTF-8", "text": "# tools\nSeveral Tools\n" } ]
2
DiegoArcelli/BlocksWorld
https://github.com/DiegoArcelli/BlocksWorld
1692a9a6cfc329ce4cc7a3570c4a5c55e670cfd6
60120a5ebd7d8837101d06189a816d5154fae9af
0f33eade5a23ea4552d841406f056a43e253373d
refs/heads/main
2023-06-17T22:27:26.108278
2021-07-16T12:55:35
2021-07-16T12:55:35
362,400,068
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7054924368858337, "alphanum_fraction": 0.7258522510528564, "avg_line_length": 28.33333396911621, "blob_id": "809d168af062b45e3a211a13bfdf7b1d995f05b0", "content_id": "27b86c254178fb8ff50c9324f6ed5ba421ad9034", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2112, "license_type": "no_license", "max_line_length": 109, "num_lines": 72, "path": "/cnn.py", "repo_name": "DiegoArcelli/BlocksWorld", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.datasets import mnist\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPool2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\nfrom keras import Sequential\n\n# file per allenare e salvare la rete neurale che effettua il riconoscimento delle cifre\n# il modello viene allenato sul dataset del MNIST\n\nBATCH_SIZE = 64\nEPOCHS = 10\n\n# si estraggono e si \n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n# si aggiunge la dimensione del canale e si normalizza il valore dei pixel tra 0 e 1\nx_train = np.expand_dims(x_train, -1)\nx_train = x_train / 255\nx_test = np.expand_dims(x_test, -1)\nx_test = x_test / 255\n\n# definizione del modello\nmodel = Sequential()\nmodel.add(Conv2D(filters=24, kernel_size=(3, 3), activation=\"relu\"))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.5))\nmodel.add(Conv2D(filters=36, kernel_size=(3, 3)))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.5))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation=\"relu\"))\nmodel.add(Dense(10, activation=\"softmax\"))\n\nmodel.predict(x_train[[0]])\n\nmodel.summary()\n\nmodel.compile(optimizer=\"adam\",\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\n# allenamento del modello\nhistory = model.fit(x_train, y_train, batch_size=BATCH_SIZE, epochs=EPOCHS, validation_data=(x_test, y_test))\n\n# calcolo della precisione e dell'errore nel validation set\ntest_loss, test_acc = model.evaluate(x_test, y_test)\n\nprint('Test loss', test_loss)\nprint('Test accuracy:', test_acc)\n\n# plot dei grafici relativi all'andamento di accuracy e loss\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Val'], loc='upper left')\nplt.show()\n\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Val'], loc='upper left')\nplt.show()\n\nmodel.save(\"./model/model.h5\")\n" }, { "alpha_fraction": 0.6041666865348816, "alphanum_fraction": 0.6191860437393188, "avg_line_length": 36.5363655090332, "blob_id": "16eaf36f4aa14e69410a5781927364af0173524d", "content_id": "43945f8915802105d23dc7e1cda2e8c5fa2c9f2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4128, "license_type": "no_license", "max_line_length": 139, "num_lines": 110, "path": "/launch.py", "repo_name": "DiegoArcelli/BlocksWorld", "src_encoding": "UTF-8", "text": "import tkinter as tk\nfrom tkinter.filedialog import askopenfilename\nfrom PIL import Image, ImageTk\nfrom load_state import prepare_image\nfrom utils import draw_state\nfrom blocks_world import BlocksWorld\nfrom search_algs import *\n\n# file che contiene l'implementazione dell'interfaccia grafica per utilizzare il programma\n\nclass Window(tk.Frame):\n\n\n def __init__(self, master=None):\n super().__init__(master)\n self.master = master\n self.pack()\n self.initial_state = None\n self.goal_state = None\n self.create_widgets()\n self.create_images(\"insert_image.png\", \"insert_image.png\")\n\n\n def create_widgets(self):\n initial_label = tk.Label(self, text = \"Seleziona stato iniziale:\")\n goal_label = tk.Label(self, text = \"Seleziona stato finale:\")\n initial_label.grid(row = 0, column = 0, padx = 10, pady = 10)\n goal_label.grid(row = 0, column = 2, padx = 10, pady = 10)\n\n initial_button = tk.Button(self, text=\"Seleziona file\", command=self.open_initial)\n goal_button = tk.Button(self, text=\"Seleziona file\", command=self.open_goal)\n initial_button.grid(row = 1, column = 0, padx = 10, pady = 10)\n goal_button.grid(row = 1, column = 2, padx = 10, pady = 10)\n\n alg_label = tk.Label(self, text = \"Seleziona algoritmo di ricerca:\")\n alg_label.grid(row = 0, column = 1, padx = 10, pady = 10)\n\n frame = tk.Frame(self)\n frame.grid(row = 1, column = 1, padx = 10, pady = 10)\n\n self.selected = tk.StringVar(self)\n self.selected.set(\"BFS\")\n select_alg_menu = tk.OptionMenu(frame, self.selected, \"BFS\", \"DFS\", \"IDS\", \"UCS\", \"A*\", \"RBFS\", command=self.read_algorithm).pack()\n\n start_button = tk.Button(frame, text=\"Start search\", command=self.start_search).pack()\n\n\n def create_images(self, initial, goal):\n self.initial_image_path = initial\n self.initial_image = ImageTk.PhotoImage(Image.open(\"./images/\" + initial).resize((300, 300)))\n initial_image_label = tk.Label(self, image=self.initial_image)\n initial_image_label.grid(row = 2, column = 0, padx = 10, pady = 10)\n\n self.goal_image_path = goal\n self.goal_image = ImageTk.PhotoImage(Image.open(\"./images/\" + goal).resize((300, 300)))\n goal_image_label = tk.Label(self, image=self.goal_image)\n goal_image_label.grid(row = 2, column = 2, padx = 10, pady = 10)\n\n\n def open_initial(self):\n self.initial_file = askopenfilename()\n if self.initial_file == ():\n return\n self.initial_state = prepare_image(self.initial_file, False)\n print(self.initial_state)\n draw_state(self.initial_state, \"initial\")\n self.create_images(\"/temp/initial.jpg\", self.goal_image_path)\n\n\n def read_algorithm(self, alg):\n return alg\n\n\n def open_goal(self):\n self.goal_file = askopenfilename()\n if self.goal_file == ():\n return\n self.goal_state = prepare_image(self.goal_file, False)\n print(self.goal_state)\n draw_state(self.goal_state, \"goal\")\n self.create_images(self.initial_image_path, \"/temp/goal.jpg\")\n\n\n def start_search(self):\n if self.goal_state is None and self.initial_state is None:\n return\n alg = self.selected.get()\n problem = BlocksWorld(self.initial_state, self.goal_state)\n print(\"Inizio ricerca:\")\n if alg == \"BFS\":\n problem.solution(graph_bfs(problem).solution())\n if alg == \"A*\":\n problem.solution(a_star(problem, lambda n: problem.misplaced_blocks(n)).solution())\n if alg == \"DFS\":\n problem.solution(graph_dfs(problem).solution())\n if alg == \"IDS\":\n problem.solution(ids(problem).solution())\n if alg == \"RBFS\":\n problem.solution(rbfs(problem, lambda n: problem.misplaced_blocks(n)).solution())\n if alg == \"UCS\":\n problem.solution(a_star(problem, lambda n: problem.depth(n)).solution())\n\n \n\n\nroot = tk.Tk()\nroot.title(\"Blocks World\")\nroot.resizable(0, 0) \napp = Window(master=root)\napp.mainloop()" }, { "alpha_fraction": 0.7767913937568665, "alphanum_fraction": 0.7793278098106384, "avg_line_length": 59.61538314819336, "blob_id": "9859faed36e2c57cc8e9255a0cda1bc0eb17c073", "content_id": "974a50ee1cf99c522294aaa62529967f0452ae86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1577, "license_type": "no_license", "max_line_length": 629, "num_lines": 26, "path": "/README.md", "repo_name": "DiegoArcelli/BlocksWorld", "src_encoding": "UTF-8", "text": "# Blocks World\nAn implementation of the famous domain of artificial intelligence blocks world.\n\n## Requirements\nThe program has been tested with python3.7, and the modules required are:\n- aima3\n- numpy\n- cv2\n- matplotlib\n- keras\n\nIn order to use the GUI these other two modules are needed:\n- tkinter \n- pillow\n\n## Description\nThis is just a summarized description of the program, to have a more detailed description you can read the [documentation file](./Relazione/relazione.pdf).\nThe program recives two input images that represent the initial and the final configuration of the blocks. The two images are processed using the functions in the file `load_state.py`, in order to extract a rappresentation of the states (as defined in the file `blocks_world.py` using the AIMA module) which can be used by the search algorithms defined in the file `search_algs.py` to output the actions needed to bring the blocks from the initial to the final configurations. In order to recognize the digits that identify the blocks, a convolutional neural networks has been trained on the MNIST dataset, in the file `cnn.py`.\n\n## Usage\nThere are two ways to use the program:\n - Using the GUI by executing the command `python launch.py`\n - Using che command line script by executing the command `python main.py`. You can use the option `-h` to visualize the helper.\n\nThere are some example images that you can use in the folder `images`.\nIf you want to train the neural network you can do it by launching the command `python cnn.py`, anyway there's a pretrained model in the folder `model`.\n\n" }, { "alpha_fraction": 0.5220975279808044, "alphanum_fraction": 0.5553011298179626, "avg_line_length": 33.393699645996094, "blob_id": "71c175d51cd64e32b06225f5f8cbd1bbfbb8a249", "content_id": "44c6aef3982103c5d23f2642490a7f9f8bdfed19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4367, "license_type": "no_license", "max_line_length": 80, "num_lines": 127, "path": "/utils.py", "repo_name": "DiegoArcelli/BlocksWorld", "src_encoding": "UTF-8", "text": "import heapq\nimport functools\nimport numpy as np\nimport cv2 as cv\nimport matplotlib.pyplot as plt\n\nclass PriorityQueue:\n \"\"\"A Queue in which the minimum (or maximum) element (as determined by f and\n order) is returned first.\n If order is 'min', the item with minimum f(x) is\n returned first; if order is 'max', then it is the item with maximum f(x).\n Also supports dict-like lookup.\"\"\"\n\n def __init__(self, order='min', f=lambda x: x):\n self.heap = []\n if order == 'min':\n self.f = f\n elif order == 'max': # now item with max f(x)\n self.f = lambda x: -f(x) # will be popped first\n else:\n raise ValueError(\"Order must be either 'min' or 'max'.\")\n\n def append(self, item):\n \"\"\"Insert item at its correct position.\"\"\"\n heapq.heappush(self.heap, (self.f(item), item))\n\n def extend(self, items):\n \"\"\"Insert each item in items at its correct position.\"\"\"\n for item in items:\n self.append(item)\n\n def pop(self):\n \"\"\"Pop and return the item (with min or max f(x) value)\n depending on the order.\"\"\"\n if self.heap:\n return heapq.heappop(self.heap)[1]\n else:\n raise Exception('Trying to pop from empty PriorityQueue.')\n\n def __len__(self):\n \"\"\"Return current capacity of PriorityQueue.\"\"\"\n return len(self.heap)\n\n def __contains__(self, key):\n \"\"\"Return True if the key is in PriorityQueue.\"\"\"\n return any([item == key for _, item in self.heap])\n\n def __getitem__(self, key):\n \"\"\"Returns the first value associated with key in PriorityQueue.\n Raises KeyError if key is not present.\"\"\"\n for value, item in self.heap:\n if item == key:\n return value\n raise KeyError(str(key) + \" is not in the priority queue\")\n\n def __delitem__(self, key):\n \"\"\"Delete the first occurrence of key.\"\"\"\n try:\n del self.heap[[item == key for _, item in self.heap].index(True)]\n except ValueError:\n raise KeyError(str(key) + \" is not in the priority queue\")\n heapq.heapify(self.heap)\n\n def get_item(self, key):\n \"\"\"Returns the first node associated with key in PriorityQueue.\n Raises KeyError if key is not present.\"\"\"\n for _, item in self.heap:\n if item == key:\n return item\n raise KeyError(str(key) + \" is not in the priority queue\")\n\n\ndef is_in(elt, seq):\n \"\"\"Similar to (elt in seq), but compares with 'is', not '=='.\"\"\"\n return any(x is elt for x in seq)\n\n\ndef memoize(fn, slot=None, maxsize=32):\n \"\"\"Memoize fn: make it remember the computed value for any argument list.\n If slot is specified, store result in that slot of first argument.\n If slot is false, use lru_cache for caching the values.\"\"\"\n if slot:\n def memoized_fn(obj, *args):\n if hasattr(obj, slot):\n return getattr(obj, slot)\n else:\n val = fn(obj, *args)\n setattr(obj, slot, val)\n return val\n else:\n @functools.lru_cache(maxsize=maxsize)\n def memoized_fn(*args):\n return fn(*args)\n\n return memoized_fn\n\n\ndef draw_state(state, file_path):\n blocks = [*state[0:-1]]\n w = state[-1]\n blocks.sort(key=lambda l: l[1], reverse=True)\n h = blocks[0][1]\n image = np.zeros(((h+1)*100, w*100), np.uint8)\n for block in blocks:\n n, i, j = block\n i = h - i\n digit = cv.imread(\"./images/digits/\" + str(n) + \".jpg\", 0)\n digit = cv.resize(digit, (100, 100))\n image[i*100:i*100 + 100, j*100:j*100 + 100] = ~digit\n size = (len(state) - 1)*100\n padded = np.zeros((size, w*100), np.uint8)\n padded[size - (h+1)*100 : size, :] = image\n h = len(state) - 1\n bg = np.zeros((h*100 + 40, w*100 + 40), np.uint8)\n bg[20: h*100 + 20, 20: w*100 + 20] = padded\n bg[0:10, :] = 255\n bg[h*100 + 30 : h*100 + 40, :] = 255\n bg[:, 0:10] = 255\n bg[h*100 + 30 : h*100 + 40, :] = 255\n bg[:,w*100 + 30 : w*100 + 40] = 255\n w, h = (w*100 + 40, h*100 + 40)\n l = max(w, h)\n adjust = np.zeros((l, l), np.uint8)\n d_w = (l - w) // 2\n d_h = (l - h) // 2\n adjust[d_h: d_h + h, d_w: d_w + w] = bg\n cv.imwrite(\"./images/temp/\" + str(file_path) + \".jpg\", ~adjust)" }, { "alpha_fraction": 0.568091094493866, "alphanum_fraction": 0.5737099051475525, "avg_line_length": 28.66666603088379, "blob_id": "fa6bbd202d10a69be94b70ed98cdf111cfd07fec", "content_id": "29432522ced4903362b9eb389064dcbc117b8a42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6763, "license_type": "no_license", "max_line_length": 81, "num_lines": 228, "path": "/search_algs.py", "repo_name": "DiegoArcelli/BlocksWorld", "src_encoding": "UTF-8", "text": "from aima3.search import *\nfrom utils import *\nfrom collections import deque\nfrom blocks_world import BlocksWorld\nimport sys\n\n# file che contiene le implementazioni degli algoritmi di ricerca\n\n\n\nnode_expanded = 0 # numero di nodi espansi durante la ricerca\nmax_node = 0 # massimo numero di nodi presenti nella frontiera durante la ricerca\nf_dim = 0 # dimensione della frontiera in un dato momento \ntotal_node = 0 \n\n\ndef init_param():\n global node_expanded, total_node, max_node, f_dim\n node_expanded = 0\n max_node = 0\n total_node = 0\n f_dim = 0\n\n\ndef print_param():\n print(f\"Nodi espansi: {node_expanded}\")\n print(f\"Max dimensione della frontiera: {max_node}\")\n print(f\"Dim media della frontiera: {int(total_node/node_expanded)}\")\n\n\n# def get_item(queue, key):\n# \"\"\"Returns the first node associated with key in PriorityQueue.\n# Raises KeyError if key is not present.\"\"\"\n# for _, item in queue.heap:\n# if item == key:\n# return item\n# raise KeyError(str(key) + \" is not in the priority queue\")\n\n\ndef show_solution(name_algo, node):\n try:\n print(name_algo + \":\", node.solution())\n except:\n if type(Node) == str:\n print(name_algo + \":\", node)\n else:\n print(name_algo + \":\", \"No solution found\")\n\n\n# Graph Breadth First Search\ndef graph_bfs(problem):\n global node_expanded, total_node, max_node, f_dim\n init_param()\n frontier = deque([Node(problem.initial)])\n f_dim += 1\n explored = set()\n while frontier:\n node_expanded += 1\n total_node += f_dim\n node = frontier.popleft()\n f_dim -= 1\n explored.add(node.state)\n if problem.goal_test(node.state):\n # print(node_expanded)\n print_param()\n return node\n for child_node in node.expand(problem):\n if child_node.state not in explored and child_node not in frontier:\n f_dim += 1\n max_node = f_dim if f_dim > max_node else max_node\n frontier.append(child_node)\n\n\n# Graph Depth First Search\ndef graph_dfs(problem):\n global node_expanded, total_node, max_node, f_dim\n init_param()\n frontier = deque([Node(problem.initial)])\n f_dim += 1\n explored = set()\n while frontier:\n total_node += f_dim\n node = frontier.pop()\n node_expanded += 1\n f_dim -= 1\n if problem.goal_test(node.state):\n print_param()\n return node\n explored.add(node.state)\n for child_node in node.expand(problem):\n if child_node.state not in explored and child_node not in frontier:\n f_dim += 1\n max_node = f_dim if f_dim > max_node else max_node\n frontier.append(child_node)\n\n\n# Uniform Cost Search\ndef ucs(problem, f):\n global node_expanded, total_node, max_node, f_dim\n init_param()\n if problem.goal_test(problem.initial):\n return Node(problem.initial)\n f = memoize(f, 'f')\n node_expanded += 1\n frontier = PriorityQueue('min', f)\n frontier.append(Node(problem.initial))\n f_dim += 1\n explored = set()\n while frontier:\n total_node += f_dim\n node_expanded += 1\n node = frontier.pop()\n f_dim -= 1\n # print(node, f(node))\n if problem.goal_test(node.state):\n print_param()\n return node\n explored.add(node.state)\n for child in node.expand(problem):\n if child.state not in explored and child not in frontier:\n f_dim += 1\n frontier.append(child)\n max_node = f_dim if f_dim > max_node else max_node\n elif child in frontier:\n next_node = frontier.get_item(child)\n if f(child) < f(next_node):\n del frontier[next_node]\n frontier.append(child)\n\n\n# Depth Limited Search\ndef dls(problem, limit):\n\n def recursive_dls(problem, node, limit):\n global node_expanded, total_node, max_node, f_dim\n node_expanded += 1\n total_node += f_dim\n if problem.goal_test(node.state):\n return node\n elif limit == 0:\n return 'cutoff'\n cutoff_occurred = False\n for child_node in node.expand(problem):\n f_dim+=1\n max_node = f_dim if f_dim > max_node else max_node\n result = recursive_dls(problem, child_node, limit-1)\n f_dim -= 1\n if result == 'cutoff':\n cutoff_occurred = True\n elif result is not None:\n return result\n return 'cutoff' if cutoff_occurred else None\n\n return recursive_dls(problem, Node(problem.initial), limit)\n\n\n# Iterative Deepening Search\ndef ids(problem):\n global node_expanded, total_node, max_node, f_dim\n init_param()\n prevexp = 0\n for depth in range(sys.maxsize):\n f_dim += 1\n result = dls(problem, depth)\n print(node_expanded - prevexp)\n prevexp = node_expanded\n f_dim = 0\n if result != 'cutoff':\n print_param()\n return result\n return None\n\n# A*\ndef a_star(problem: BlocksWorld, h=None):\n global node_expanded\n h = memoize(h or problem.h)\n return ucs(problem, lambda n: problem.depth(n) + h(n))\n\n\n# Recursive Best First Search\ndef rbfs(problem, h):\n global node_expanded, total_node, max_node, f_dim\n init_param()\n\n h = memoize(h or problem.h, 'h')\n g = memoize(lambda n: problem.depth(n), 'g')\n f = memoize(lambda n: g(n) + h(n), 'f')\n \n\n def rbfs_search(problem, node, f_limit=np.inf):\n global node_expanded, total_node, max_node, f_dim\n\n node_expanded += 1\n if problem.goal_test(node.state):\n print_param()\n return node, 0\n\n successors = [*node.expand(problem)]\n f_dim += len(successors)\n total_node += f_dim\n max_node = f_dim if f_dim > max_node else max_node\n\n if len(successors) == 0:\n return None, np.inf\n\n for child in successors:\n child.f = max(f(child), node.f)\n\n while True:\n successors.sort(key=lambda x: x.f)\n best = successors[0]\n\n if best.f > f_limit:\n f_dim -= len(successors)\n return None, best.f\n\n alt = successors[1].f if len(successors) > 1 else np.inf\n # importante, sovrascrivere best.f\n result, best.f = rbfs_search(problem, best, min(f_limit, alt))\n # return result\n if result is not None:\n f_dim -= len(successors)\n return result, best.f\n\n node = Node(problem.initial)\n f(node)\n f_dim += 1\n return rbfs_search(problem, node)[0]" }, { "alpha_fraction": 0.48008984327316284, "alphanum_fraction": 0.5023483633995056, "avg_line_length": 30.805194854736328, "blob_id": "053fb74906d462d43fb26d14736174554d21b1b0", "content_id": "e9487d03423f26404e16e4fec5cca7fd33654de2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4899, "license_type": "no_license", "max_line_length": 88, "num_lines": 154, "path": "/blocks_world.py", "repo_name": "DiegoArcelli/BlocksWorld", "src_encoding": "UTF-8", "text": "from aima3.search import *\nfrom utils import *\nimport numpy as np\nimport cv2 as cv\nimport matplotlib.pyplot as plt\n\n# file che contine l'implementazione del problema basata con AIMA\n\nclass BlocksWorld(Problem):\n\n def __init__(self, initial, goal):\n super().__init__(initial, goal)\n\n\n # restituisce il numero di blocchi\n def get_blocks_number(self):\n return len(self.initial)\n\n\n # restituisce la lista delle possibili azioni nello stato corrente\n def actions(self, state):\n blocks = [*state[0:-1]]\n size = state[-1]\n columns = {}\n tops = []\n for block in blocks:\n n, i, j = block\n if j not in columns:\n columns[j] = (n, i, j)\n else:\n if i > columns[j][1]:\n columns[j] = (n, i, j)\n for col in columns:\n tops.append(columns[col])\n actions = []\n for block in tops:\n n, i, j = block\n for col in range(size):\n if col != j:\n if col in columns:\n actions.append((n, columns[col][1]+1, col))\n else:\n actions.append((n, 0, col))\n return actions\n\n\n # \n def result(self, state, actions):\n blocks = [*state[0:-1]]\n size = state[-1]\n to_delete = ()\n for block in blocks:\n if block[0] == actions[0]:\n to_delete = block\n blocks.remove(to_delete)\n blocks.append((actions))\n blocks.append(size)\n return tuple(blocks)\n\n\n # verifica se lo stato passato è lo stato finale\n def goal_test(self, state):\n op_1 = [*state[0:-1]]\n op_2 = [*self.goal[0:-1]]\n op_1.sort(key=lambda l: l[0])\n op_2.sort(key=lambda l: l[0])\n return str(op_1) == str(op_2)\n\n\n # restituisce i blocchi che possono essere spostati nello stato che viene passato\n def get_movable(self, state):\n blocks = [*state[0:-1]]\n size = state[-1]\n columns = {}\n tops = []\n for block in blocks:\n n, i, j = block\n if j not in columns:\n columns[j] = (n, i, j)\n else:\n if i > columns[j][1]:\n columns[j] = (n, i, j)\n for col in columns:\n tops.append(columns[col])\n return tops\n\n\n # euristica che calcola il numero di blocchi in posizione errata\n def misplaced_blocks(self, node):\n blocks = [*node.state[0:-1]]\n target = [*self.goal[0:-1]]\n target.sort(key=lambda l: l[0])\n value = 0\n for block in blocks:\n n, i, j = block\n if target[n-1][1:3] != (i, j):\n value += 1\n # if block not in self.get_movable(node.state):\n # value += 1\n return value\n\n\n # ritorna la profondità di un nodo nell'albero di ricerca\n def depth(self, node):\n return node.depth\n \n\n # stampa la lista delle azioni che portano dallo stato iniziale allo stato finale\n def solution(self, actions, output=True):\n if len(actions) is None:\n return\n state = self.initial\n successor = None\n n = 1\n print(\"Lunghezza soluzione: \" + str(len(actions)))\n for action in actions:\n print(action)\n successor = self.result(state, action)\n if output:\n figue_1 = self.draw_state(state)\n figue_2 = self.draw_state(successor)\n _, axarr = plt.subplots(1, 2)\n axarr[0].imshow(figue_1, cmap=plt.cm.binary)\n axarr[0].set_xticks([])\n axarr[0].set_yticks([])\n axarr[0].set_xlabel(f\"\\nStato {n}\")\n axarr[1].imshow(figue_2, cmap=plt.cm.binary)\n axarr[1].set_xticks([])\n axarr[1].set_yticks([])\n axarr[1].set_xlabel(f\"\\nStato {n+1}\")\n figManager = plt.get_current_fig_manager()\n figManager.full_screen_toggle()\n plt.show()\n state = successor\n n += 1\n\n\n # metodo che fornisce una rappresentazione grafica dello stato che gli viene passato\n def draw_state(self, state):\n blocks = [*state[0:-1]]\n w = state[-1]\n blocks.sort(key=lambda l: l[1], reverse=True)\n h = blocks[0][1]\n image = np.zeros(((h+1)*100, w*100), np.uint8)\n for block in blocks:\n n, i, j = block\n i = h - i\n digit = cv.imread(\"./images/digits/\" + str(n) + \".jpg\", 0)\n digit = cv.resize(digit, (100, 100))\n image[i*100:i*100 + 100, j*100:j*100 + 100] = ~digit\n size = (len(state) - 1)*100\n adjust = np.zeros((size, w*100), np.uint8)\n adjust[size - (h+1)*100 : size, :] = image\n return adjust" }, { "alpha_fraction": 0.671046257019043, "alphanum_fraction": 0.6715328693389893, "avg_line_length": 37.79245376586914, "blob_id": "53b6e9362b35be58031c05cc351b05e93365c795", "content_id": "43ee1af39beee25485ae21db94661bca86000977", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2055, "license_type": "no_license", "max_line_length": 140, "num_lines": 53, "path": "/main.py", "repo_name": "DiegoArcelli/BlocksWorld", "src_encoding": "UTF-8", "text": "from PIL import Image, ImageTk\nfrom load_state import prepare_image\nfrom utils import draw_state\nfrom blocks_world import BlocksWorld\nfrom search_algs import *\nimport argparse\nfrom inspect import getfullargspec\n\n# file che definisce lo script da linea di comando per utilizzare il programma\n\n\nif __name__ == \"__main__\":\n\n search_algs = {\n \"astar\": a_star,\n \"ucs\": ucs,\n \"rbfs\": rbfs,\n \"bfs\": graph_bfs,\n \"dfs\": graph_dfs,\n \"ids\": ids\n }\n\n parser = argparse.ArgumentParser(description=\"Blocks World\")\n parser.add_argument(\"--initial\", \"-i\", type=str, default=None, required=True, help=\"The image representing the initial state\")\n parser.add_argument(\"--goal\", \"-g\", type=str, default=None, required=True, help=\"The image representing the goal state\")\n parser.add_argument(\"--algorithm\", \"-a\", type=str, default=None, required=True, help=\"The search algorithm used\")\n parser.add_argument(\"--debug\", \"-d\", default=False, required=False, action='store_true', help=\"Shows the steps of the image processing\")\n parser.add_argument(\"--output\", \"-o\", default=False, required=False, action='store_true', help=\"The solution is printed graphically\")\n args = vars(parser.parse_args())\n\n initial_state_path = args[\"initial\"]\n goal_state_path = args[\"goal\"]\n search_alg = args[\"algorithm\"]\n debug = args[\"debug\"]\n output = args[\"output\"]\n\n initial_state = prepare_image(initial_state_path, debug)\n goal_state = prepare_image(goal_state_path, debug)\n print(initial_state)\n print(goal_state)\n\n functions = {\n \"ucs\": lambda n: problem.depth(n),\n \"astar\": lambda n: problem.misplaced_blocks(n),\n \"rbfs\": lambda n: problem.misplaced_blocks(n)\n }\n\n problem = BlocksWorld(initial_state, goal_state)\n\n if len(getfullargspec(search_algs[search_alg]).args) == 2:\n problem.solution(search_algs[search_alg](problem, functions[search_alg]).solution(), output)\n else:\n problem.solution(search_algs[search_alg](problem).solution(), output)" }, { "alpha_fraction": 0.5352022051811218, "alphanum_fraction": 0.5618446469306946, "avg_line_length": 29.34415626525879, "blob_id": "d85518fe4d02177183d0d5724a831c8064522c61", "content_id": "4a322fda686fb9242d6be02d45b1ade974497a3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9346, "license_type": "no_license", "max_line_length": 101, "num_lines": 308, "path": "/load_state.py", "repo_name": "DiegoArcelli/BlocksWorld", "src_encoding": "UTF-8", "text": "import cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport glob\nfrom tensorflow import keras\nfrom math import ceil\n\ndeteced = [np.array([]) for x in range(6)] # lista che contiene le immagini delle cifre\npoisitions = [None for x in range(6)] # lista che contiene la posizione delle cifre nell'immagine\ndebug_mode = False\nmodel = keras.models.load_model(\"./model/model.h5\") # carica il modello allenato sul datase del MNIST\n\n# funzione che si occupa del riconoscimento della cifra presente nell'immagine\n# che gli viene passato come parametro\ndef predict(image):\n h, w = image.shape\n l = int(max(image.shape)*1.2)\n n_h = int((l - h)/2)\n n_w = int((l - w)/2)\n img = np.zeros((l, l), np.uint8)\n img[n_h : n_h + h, n_w : n_w + w] = image\n img = (img / 255).astype('float64')\n img = cv.resize(img, (28, 28), interpolation = cv.INTER_AREA)\n _in = np.array([img])\n _in = np.expand_dims(_in, -1)\n digit = np.argmax(model.predict(_in))\n if debug_mode:\n print(digit)\n show(img)\n return digit - 1 if digit > 0 else -1\n\n\n# stampa a schermo l'immagine che gli veiene passata come parametro\ndef show(img):\n figManager = plt.get_current_fig_manager()\n figManager.full_screen_toggle()\n plt.xticks([])\n plt.yticks([])\n plt.imshow(img)\n plt.show()\n\n\n# prime modifiche all'immagine che consistono nell'applicazione di blur\ndef preprocess(image):\n image = cv.medianBlur(image, 3)\n image = cv.GaussianBlur(image, (3, 3), 0)\n return 255 - image\n\n\ndef postprocess(image):\n image = cv.medianBlur(image, 5)\n image = cv.medianBlur(image, 5)\n kernel = np.ones((3, 3), np.uint8)\n image = cv.morphologyEx(image, cv.MORPH_OPEN, kernel)\n kernel = np.ones((3, 3), np.uint8)\n image = cv.erode(image, kernel, iterations=2)\n return image\n\n\ndef get_block_index(image_shape, yx, block_size):\n y = np.arange(max(0, yx[0]-block_size),\n min(image_shape[0], yx[0]+block_size))\n x = np.arange(max(0, yx[1]-block_size),\n min(image_shape[1], yx[1]+block_size))\n return np.meshgrid(y, x)\n\n\ndef adaptive_median_threshold(img_in):\n med = np.median(img_in)\n threshold = 40\n img_out = np.zeros_like(img_in)\n img_out[img_in - med < threshold] = 255\n return img_out\n\n\ndef block_image_process(image, block_size):\n out_image = np.zeros_like(image)\n for row in range(0, image.shape[0], block_size):\n for col in range(0, image.shape[1], block_size):\n idx = (row, col)\n block_idx = get_block_index(image.shape, idx, block_size)\n out_image[block_idx] = adaptive_median_threshold(image[block_idx])\n return out_image\n\n\ndef clean(image):\n contours, hierarchy = cv.findContours(\n image, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)\n for contour in contours:\n approx = cv.approxPolyDP(\n contour, 0.001 * cv.arcLength(contour, True), True)\n x, y, w, h = cv.boundingRect(approx)\n if search_noise(contour, approx, image.shape[::-1]):\n cv.drawContours(image, [approx], 0, 255, -1)\n return image\n\n\ndef search_noise(contour, approx, image_size):\n i_h, i_w = image_size\n x, y, w, h = cv.boundingRect(approx)\n image_area = i_w*i_h\n if cv.contourArea(contour) >= image_area/1000:\n return False\n if w >= i_w/50 or h >= i_h/50:\n return False\n return True\n\n\ndef find_digits(image, org_image, org):\n contours, hierarchy = cv.findContours(image, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)\n i = 0\n for contour in contours:\n approx = cv.approxPolyDP(contour, 0.001 * cv.arcLength(contour, True), True)\n x, y, w, h = cv.boundingRect(approx)\n if hierarchy[0][i][3] == -1:\n prev = predict(org_image[y:y+h, x:x+w])\n if prev != -1:\n deteced[prev] = org[y:y+h, x:x+w]\n poisitions[prev] = (x, y, x + w, y + h) \n i += 1\n\n\n# funzione che individua il box che contiene i blocchi ed individua le cifre\ndef find_box(image):\n o_h, o_w = image.shape[0:2]\n contours, hierarchy = cv.findContours(\n image, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)\n contours.sort(reverse=True, key=lambda c: cv.contourArea(c))\n contour = contours[1]\n approx = cv.approxPolyDP(\n contour, 0.001 * cv.arcLength(contour, True), True)\n x, y, w, h = cv.boundingRect(approx)\n box = (x, y, x + w, y + h)\n img = image[y:y+h, x:x+w]\n sub = img.copy()\n bg = ~np.zeros((h + 50, w + 50), np.uint8)\n bg[25: 25 + h, 25: 25 + w] = img\n img = bg\n i = 0\n i_h, i_w = img.shape[0:2]\n tot = np.zeros(shape=(i_h, i_w))\n if debug_mode:\n print(image)\n contours, hierarchy = cv.findContours(img, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)\n for contour in contours:\n approx = cv.approxPolyDP(\n contour, 0.001 * cv.arcLength(contour, True), True)\n if hierarchy[0][i][3] == 0:\n cv.drawContours(tot, [approx], 0, 255, -1)\n if hierarchy[0][i][3] == 1:\n cv.drawContours(tot, [approx], 0, 0, -1)\n i += 1\n tot = tot[25: 25 + h, 25: 25 + w]\n kernel = np.ones((5, 5), np.uint8)\n tot = cv.dilate(tot, kernel, iterations=3)\n tot = tot.astype('uint32')\n sub = sub.astype('uint32')\n res = sub + tot\n res = np.where(res == 0, 255, 0)\n result = np.zeros((o_h, o_w), np.uint8)\n result[y:y+h, x:x+w] = res\n if debug_mode:\n show(result)\n return (result, box)\n\n\ndef get_block_borders(dims, image):\n x_i, y_i, x_f, y_f = dims\n kernel = np.ones((5, 5), np.uint8)\n image = cv.erode(image, kernel, iterations=1)\n y_m = (y_f + y_i) // 2\n x_m = (x_f + x_i) // 2\n t = x_i - 1\n while image[y_m, t] != 255:\n t-=1\n x_i = t\n t = x_f + 1\n while image[y_m, t] != 255:\n t+=1\n x_f = t\n t = y_i - 1\n while image[t, x_m] != 255:\n t-=1\n y_i = t\n t = y_f + 1\n while image[t, x_m] != 255:\n t+=1\n y_f = t\n return (x_i, y_i, x_f, y_f)\n\n\ndef process_image_file(filename):\n global deteced, poisitions, explored, debug_mode\n block_size = 50\n deteced = [np.array([]) for x in range(6)]\n poisitions = [None for x in range(6)]\n explored = []\n image_in = cv.cvtColor(cv.imread(filename), cv.COLOR_BGR2GRAY)\n if debug_mode:\n show(image_in)\n image_in_pre = preprocess(image_in)\n image_out = block_image_process(image_in_pre, block_size)\n image_out = postprocess(image_out)\n image_out = clean(image_out)\n if debug_mode:\n show(image_out)\n digits, box = find_box(image_out)\n find_digits(digits, ~image_out, image_in)\n for i in range(6):\n if deteced[i].size > 0:\n image = deteced[i]\n x, y, w, h = get_block_borders(poisitions[i], ~image_out)\n poisitions[i] = (x, y, w, h)\n cv.rectangle(image_in, (x, y), (w, h), 255, 2)\n if debug_mode:\n show(image_in)\n return box\n\ndef check_intersection(values):\n v1_i, v1_f, v2_i, v2_f = values\n v2_m = (v2_i + v2_f) // 2\n if v1_i < v2_m and v1_f > v2_m:\n return True\n return False\n\n\ndef create_state(poisitions, box):\n cols = [[] for x in range(6)]\n mean_points = []\n for i in range(6):\n if poisitions[i] is not None:\n x1_i, y1_i, x1_f, y1_f = poisitions[i]\n mean_points.append(((x1_f + x1_i) // 2, ((y1_f + y1_i) // 2)))\n c = [i+1]\n for j in range(6):\n if poisitions[j] is not None and j != i:\n x2_i, y2_i, x2_f, y2_f = poisitions[j]\n if check_intersection((x1_i, x1_f, x2_i, x2_f)):\n c.append(j+1)\n c.sort()\n cols[i] = tuple([*c])\n else:\n cols[i] = ()\n\n temp_cols = list(set(tuple(cols)))\n if () in temp_cols:\n temp_cols.remove(())\n\n cols = []\n\n for t_col in temp_cols:\n col = list(t_col)\n col.sort(reverse=True, key=lambda e: mean_points[e-1][1])\n cols.append(tuple(col))\n\n cols.sort(key=lambda e: mean_points[e[0]-1][0])\n\n bottoms = [col[0] for col in cols]\n\n distances = []\n\n xb_i, _, xb_f, _ = box\n\n x_i, _, x_f, _ = poisitions[bottoms[0]-1]\n dist = abs(x_i - xb_i)\n dist = dist / (x_f - x_i)\n distances.append(dist)\n\n for i in range(len(bottoms)-1):\n x1_i, _, x1_f, _ = poisitions[bottoms[i]-1]\n x2_i, _, _, _ = poisitions[bottoms[i+1]-1]\n dist = abs(x2_i - x1_f)\n dist = dist / (x1_f - x1_i)\n distances.append(dist)\n\n x_i, _, x_f, _ = poisitions[bottoms[-1]-1]\n dist = abs(xb_f - x_f)\n dist = dist / (x_f - x_i)\n distances.append(dist)\n\n for i in range(len(distances)):\n dist = distances[i]\n if dist - int(dist) >= 0.5:\n distances[i] = int(dist) + 1\n else:\n distances[i] = int(dist)\n\n n = sum(distances) + len(cols)\n i = distances[0]\n state = []\n pos = 1\n for col in cols:\n j = 0\n for block in col:\n state.append((block, j, i))\n j += 1\n i += distances[pos] + 1\n pos += 1\n state.append(n)\n return tuple(state)\n\n\ndef prepare_image(file_path, debug):\n global debug_mode\n debug_mode = True if debug else False\n box = process_image_file(file_path)\n state = create_state(poisitions, box)\n return state\n" } ]
8